From 9e4703bd1f8504bf2971d8576107809be913dabc Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 13 Sep 2023 16:44:23 +0800 Subject: [PATCH 01/59] fix --- model/gmodel/fs_shopping_cart_gen.go | 2 +- server_api/shopping-cart.api | 48 ++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 server_api/shopping-cart.api diff --git a/model/gmodel/fs_shopping_cart_gen.go b/model/gmodel/fs_shopping_cart_gen.go index 47c69f94..e58ae44b 100644 --- a/model/gmodel/fs_shopping_cart_gen.go +++ b/model/gmodel/fs_shopping_cart_gen.go @@ -14,7 +14,7 @@ type FsShoppingCart struct { PriceId *int64 `gorm:"default:0;" json:"price_id"` // 价格id SizeId *int64 `gorm:"default:0;" json:"size_id"` // 尺寸id MaterialId *int64 `gorm:"default:0;" json:"material_id"` // 材质id - FittingIds *string `gorm:"default:'';" json:"fitting_ids"` // 配件id集合 + FittingId *int64 `gorm:"default:0;" json:"fitting_id"` // 配件id PurchaseQuantity *int64 `gorm:"default:0;" json:"purchase_quantity"` // 购买数量 UnitPrice *int64 `gorm:"default:0;" json:"unit_price"` // 当时加入购物车的单价,不作为支付计算,支付计算需要实时价格(厘)换算美元除以1000 TotalPrice *int64 `gorm:"default:0;" json:"total_price"` // 当时加入购物车单价x数量的总价,不作为支付计算,支付计算需要实时价格 diff --git a/server_api/shopping-cart.api b/server_api/shopping-cart.api new file mode 100644 index 00000000..ed7b9e1f --- /dev/null +++ b/server_api/shopping-cart.api @@ -0,0 +1,48 @@ +syntax = "v1" + +info ( + title: "shopping-cart"// TODO: add title + desc: "购物车服务"// TODO: add description + author: "" + email: "" +) + +import "basic.api" +service shopping-cart { + //加入购物车 + @handler AddToCartHandler + post /api/shopping-cart/add_to_cart(AddToCartReq) returns (response); + //删除购物车 + @handler DeleteCartHandler + post /api/shopping-cart/delete_cart(DeleteCartReq) returns (response); + //修改购物车购买数量 + @handler ModifyCartPurchaseQuantityHandler + post /api/shopping-cart/modify_cart_purchase_quantity(ModifyCartPurchaseQuantityReq) returns (response); + //获取购物车列表 + @handler GetCartsHandler + get /api/shopping-cart/get_carts(GetCartsReq) returns (response); +} +//加入购物车 +type AddToCartReq{ + ProductId int64 `json:"product_id"`//产品id + TemplateId int64 `json:"template_id"` //模板id + SizeId int64 `json:"size_id"` //尺寸id + FittingId int64 `json:"fitting_id"` //配件id + PurchaseQuantity int64 `json:"purchase_quantity"` //购买数量 + Logo string `json:"logo"` //logo地址 + CombineImage string `json:"combine_image"` //合图地址 + RenderImage string `json:"render_image"` //渲染结果图 +} +//删除购物车 +type DeleteCartReq{ + Id int64 `json:"id"`//购物车id +} +//修改购物车购买数量 +type ModifyCartPurchaseQuantityReq{ + Id int64 `json:"id"` //购物车id + Quantity int64 `json:"quantity"` //数量 +} +//获取购物车列表 +type GetCartsReq{ + Page int `form:"page"` //当前页 +} From 417228ce053f72fdfe19157107390688c46b4305 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 13 Sep 2023 17:20:39 +0800 Subject: [PATCH 02/59] fix --- server_api/shopping-cart.api | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/server_api/shopping-cart.api b/server_api/shopping-cart.api index ed7b9e1f..829ec1a6 100644 --- a/server_api/shopping-cart.api +++ b/server_api/shopping-cart.api @@ -46,3 +46,35 @@ type ModifyCartPurchaseQuantityReq{ type GetCartsReq{ Page int `form:"page"` //当前页 } +type GetCartsRsp { + Meta Meta `json:"meta"` //分页信息 + CartList []CartItem `json:"cart_list"` +} +type CartItem{ + ProductId int64 `json:"product_id"`//产品id + SizeInfo SizeInfo `json:"size_info"`//尺寸信息 + FittingInfo FittingInfo `json:"fitting_info"` //配件信息 + ItemPrice string `json:"item_price"` //单价 + TotalPrice string `json:"totalPrice"`//单价X数量=总价 + DiyInformation DiyInformation `json:"diy_information"` //diy信息 + StepNum []int64 `json:"step_num"` //阶梯数量 +} +type SizeInfo{ + SizeId int64 `json:"size_id"` //尺寸id + Capacity string `json:"capacity"`//尺寸名称 + Title SizeTitle `json:"title"` +} +type FittingInfo{ + FittingId int64 `json:"fitting_id"`//配件id + FittingName string `json:"fitting_name"` //配件名称 +} +type SizeTitle{ + Cm string `json:"cm"` + Inch string `json:"inch"` +} +type DiyInformation{ + Phone string `json:"phone"` + Address string `json:"address"` + Website string `json:"website"` + Qrcode string `json:"qrcode"` +} \ No newline at end of file From a8b85fad0287ec8f2c590c5d17a94e9e5f15aaa4 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 13 Sep 2023 17:27:16 +0800 Subject: [PATCH 03/59] fix --- server/product/etc/product.yaml | 2 +- server_api/shopping-cart.api | 67 +++++++++++++++++---------------- 2 files changed, 35 insertions(+), 34 deletions(-) diff --git a/server/product/etc/product.yaml b/server/product/etc/product.yaml index c43bfa02..938f3aca 100644 --- a/server/product/etc/product.yaml +++ b/server/product/etc/product.yaml @@ -1,5 +1,5 @@ Name: product -Host: localhost +Host: 0.0.0.0 Port: 9908 ReplicaId: 55 Timeout: 15000 #服务超时时间 diff --git a/server_api/shopping-cart.api b/server_api/shopping-cart.api index 829ec1a6..9731e835 100644 --- a/server_api/shopping-cart.api +++ b/server_api/shopping-cart.api @@ -22,59 +22,60 @@ service shopping-cart { @handler GetCartsHandler get /api/shopping-cart/get_carts(GetCartsReq) returns (response); } + //加入购物车 -type AddToCartReq{ - ProductId int64 `json:"product_id"`//产品id - TemplateId int64 `json:"template_id"` //模板id - SizeId int64 `json:"size_id"` //尺寸id - FittingId int64 `json:"fitting_id"` //配件id - PurchaseQuantity int64 `json:"purchase_quantity"` //购买数量 - Logo string `json:"logo"` //logo地址 - CombineImage string `json:"combine_image"` //合图地址 - RenderImage string `json:"render_image"` //渲染结果图 +type AddToCartReq { + ProductId int64 `json:"product_id"` //产品id + TemplateId int64 `json:"template_id"` //模板id + SizeId int64 `json:"size_id"` //尺寸id + FittingId int64 `json:"fitting_id"` //配件id + PurchaseQuantity int64 `json:"purchase_quantity"` //购买数量 + Logo string `json:"logo"` //logo地址 + CombineImage string `json:"combine_image"` //合图地址 + RenderImage string `json:"render_image"` //渲染结果图 } //删除购物车 -type DeleteCartReq{ - Id int64 `json:"id"`//购物车id +type DeleteCartReq { + Id int64 `json:"id"` //购物车id } //修改购物车购买数量 -type ModifyCartPurchaseQuantityReq{ - Id int64 `json:"id"` //购物车id +type ModifyCartPurchaseQuantityReq { + Id int64 `json:"id"` //购物车id Quantity int64 `json:"quantity"` //数量 } //获取购物车列表 -type GetCartsReq{ +type GetCartsReq { Page int `form:"page"` //当前页 } type GetCartsRsp { - Meta Meta `json:"meta"` //分页信息 - CartList []CartItem `json:"cart_list"` + Meta Meta `json:"meta"` //分页信息 + CartList []CartItem `json:"cart_list"` } -type CartItem{ - ProductId int64 `json:"product_id"`//产品id - SizeInfo SizeInfo `json:"size_info"`//尺寸信息 - FittingInfo FittingInfo `json:"fitting_info"` //配件信息 - ItemPrice string `json:"item_price"` //单价 - TotalPrice string `json:"totalPrice"`//单价X数量=总价 +type CartItem { + ProductId int64 `json:"product_id"` //产品id + SizeInfo SizeInfo `json:"size_info"` //尺寸信息 + FittingInfo FittingInfo `json:"fitting_info"` //配件信息 + ItemPrice string `json:"item_price"` //单价 + TotalPrice string `json:"totalPrice"` //单价X数量=总价 DiyInformation DiyInformation `json:"diy_information"` //diy信息 - StepNum []int64 `json:"step_num"` //阶梯数量 + StepNum []int64 `json:"step_num"` //阶梯数量 } -type SizeInfo{ - SizeId int64 `json:"size_id"` //尺寸id - Capacity string `json:"capacity"`//尺寸名称 +type SizeInfo { + SizeId int64 `json:"size_id"` //尺寸id + Capacity string `json:"capacity"` //尺寸名称 Title SizeTitle `json:"title"` } -type FittingInfo{ - FittingId int64 `json:"fitting_id"`//配件id +type FittingInfo { + FittingId int64 `json:"fitting_id"` //配件id FittingName string `json:"fitting_name"` //配件名称 } -type SizeTitle{ - Cm string `json:"cm"` +type SizeTitle { + Cm string `json:"cm"` Inch string `json:"inch"` } -type DiyInformation{ - Phone string `json:"phone"` +type DiyInformation { + Phone string `json:"phone"` Address string `json:"address"` Website string `json:"website"` - Qrcode string `json:"qrcode"` + Qrcode string `json:"qrcode"` } \ No newline at end of file From b8edd41e69e4b2b9b6aa525698e27bb447c8ef05 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 13 Sep 2023 17:33:58 +0800 Subject: [PATCH 04/59] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E8=B4=AD=E7=89=A9?= =?UTF-8?q?=E8=BD=A6=E6=9C=8D=E5=8A=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- server/shopping-cart/etc/shopping-cart.yaml | 12 ++ .../shopping-cart/internal/config/config.go | 13 ++ .../internal/handler/addtocarthandler.go | 35 +++++ .../internal/handler/deletecarthandler.go | 35 +++++ .../internal/handler/getcartshandler.go | 35 +++++ .../modifycartpurchasequantityhandler.go | 35 +++++ .../shopping-cart/internal/handler/routes.go | 37 +++++ .../internal/logic/addtocartlogic.go | 43 ++++++ .../internal/logic/deletecartlogic.go | 43 ++++++ .../internal/logic/getcartslogic.go | 43 ++++++ .../logic/modifycartpurchasequantitylogic.go | 43 ++++++ .../internal/svc/servicecontext.go | 26 ++++ server/shopping-cart/internal/types/types.go | 137 ++++++++++++++++++ server/shopping-cart/shopping-cart.go | 36 +++++ 14 files changed, 573 insertions(+) create mode 100644 server/shopping-cart/etc/shopping-cart.yaml create mode 100644 server/shopping-cart/internal/config/config.go create mode 100644 server/shopping-cart/internal/handler/addtocarthandler.go create mode 100644 server/shopping-cart/internal/handler/deletecarthandler.go create mode 100644 server/shopping-cart/internal/handler/getcartshandler.go create mode 100644 server/shopping-cart/internal/handler/modifycartpurchasequantityhandler.go create mode 100644 server/shopping-cart/internal/handler/routes.go create mode 100644 server/shopping-cart/internal/logic/addtocartlogic.go create mode 100644 server/shopping-cart/internal/logic/deletecartlogic.go create mode 100644 server/shopping-cart/internal/logic/getcartslogic.go create mode 100644 server/shopping-cart/internal/logic/modifycartpurchasequantitylogic.go create mode 100644 server/shopping-cart/internal/svc/servicecontext.go create mode 100644 server/shopping-cart/internal/types/types.go create mode 100644 server/shopping-cart/shopping-cart.go diff --git a/server/shopping-cart/etc/shopping-cart.yaml b/server/shopping-cart/etc/shopping-cart.yaml new file mode 100644 index 00000000..2b0db3dd --- /dev/null +++ b/server/shopping-cart/etc/shopping-cart.yaml @@ -0,0 +1,12 @@ +Name: shopping-cart +Host: 0.0.0.0 +Port: 9918 +Timeout: 15000 #服务超时时间(毫秒) +SourceMysql: fsreaderwriter:XErSYmLELKMnf3Dh@tcp(fusen.cdmigcvz3rle.us-east-2.rds.amazonaws.com:3306)/fusen +SourceRabbitMq: amqp://rabbit001:rabbit001129@110.41.19.98:5672 +Log: + Stat: false +Auth: + AccessSecret: fusen2023 + AccessExpire: 2592000 + RefreshAfter: 1592000 diff --git a/server/shopping-cart/internal/config/config.go b/server/shopping-cart/internal/config/config.go new file mode 100644 index 00000000..57f6dab8 --- /dev/null +++ b/server/shopping-cart/internal/config/config.go @@ -0,0 +1,13 @@ +package config + +import ( + "fusenapi/server/shopping-cart/internal/types" + "github.com/zeromicro/go-zero/rest" +) + +type Config struct { + rest.RestConf + SourceMysql string + Auth types.Auth + SourceRabbitMq string +} diff --git a/server/shopping-cart/internal/handler/addtocarthandler.go b/server/shopping-cart/internal/handler/addtocarthandler.go new file mode 100644 index 00000000..6fe5e246 --- /dev/null +++ b/server/shopping-cart/internal/handler/addtocarthandler.go @@ -0,0 +1,35 @@ +package handler + +import ( + "net/http" + "reflect" + + "fusenapi/utils/basic" + + "fusenapi/server/shopping-cart/internal/logic" + "fusenapi/server/shopping-cart/internal/svc" + "fusenapi/server/shopping-cart/internal/types" +) + +func AddToCartHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + + var req types.AddToCartReq + userinfo, err := basic.RequestParse(w, r, svcCtx, &req) + if err != nil { + return + } + + // 创建一个业务逻辑层实例 + l := logic.NewAddToCartLogic(r.Context(), svcCtx) + + rl := reflect.ValueOf(l) + basic.BeforeLogic(w, r, rl) + + resp := l.AddToCart(&req, userinfo) + + if !basic.AfterLogic(w, r, rl, resp) { + basic.NormalAfterLogic(w, r, resp) + } + } +} diff --git a/server/shopping-cart/internal/handler/deletecarthandler.go b/server/shopping-cart/internal/handler/deletecarthandler.go new file mode 100644 index 00000000..fa7c4fd0 --- /dev/null +++ b/server/shopping-cart/internal/handler/deletecarthandler.go @@ -0,0 +1,35 @@ +package handler + +import ( + "net/http" + "reflect" + + "fusenapi/utils/basic" + + "fusenapi/server/shopping-cart/internal/logic" + "fusenapi/server/shopping-cart/internal/svc" + "fusenapi/server/shopping-cart/internal/types" +) + +func DeleteCartHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + + var req types.DeleteCartReq + userinfo, err := basic.RequestParse(w, r, svcCtx, &req) + if err != nil { + return + } + + // 创建一个业务逻辑层实例 + l := logic.NewDeleteCartLogic(r.Context(), svcCtx) + + rl := reflect.ValueOf(l) + basic.BeforeLogic(w, r, rl) + + resp := l.DeleteCart(&req, userinfo) + + if !basic.AfterLogic(w, r, rl, resp) { + basic.NormalAfterLogic(w, r, resp) + } + } +} diff --git a/server/shopping-cart/internal/handler/getcartshandler.go b/server/shopping-cart/internal/handler/getcartshandler.go new file mode 100644 index 00000000..8d0a4a0a --- /dev/null +++ b/server/shopping-cart/internal/handler/getcartshandler.go @@ -0,0 +1,35 @@ +package handler + +import ( + "net/http" + "reflect" + + "fusenapi/utils/basic" + + "fusenapi/server/shopping-cart/internal/logic" + "fusenapi/server/shopping-cart/internal/svc" + "fusenapi/server/shopping-cart/internal/types" +) + +func GetCartsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + + var req types.GetCartsReq + userinfo, err := basic.RequestParse(w, r, svcCtx, &req) + if err != nil { + return + } + + // 创建一个业务逻辑层实例 + l := logic.NewGetCartsLogic(r.Context(), svcCtx) + + rl := reflect.ValueOf(l) + basic.BeforeLogic(w, r, rl) + + resp := l.GetCarts(&req, userinfo) + + if !basic.AfterLogic(w, r, rl, resp) { + basic.NormalAfterLogic(w, r, resp) + } + } +} diff --git a/server/shopping-cart/internal/handler/modifycartpurchasequantityhandler.go b/server/shopping-cart/internal/handler/modifycartpurchasequantityhandler.go new file mode 100644 index 00000000..b04427bf --- /dev/null +++ b/server/shopping-cart/internal/handler/modifycartpurchasequantityhandler.go @@ -0,0 +1,35 @@ +package handler + +import ( + "net/http" + "reflect" + + "fusenapi/utils/basic" + + "fusenapi/server/shopping-cart/internal/logic" + "fusenapi/server/shopping-cart/internal/svc" + "fusenapi/server/shopping-cart/internal/types" +) + +func ModifyCartPurchaseQuantityHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + + var req types.ModifyCartPurchaseQuantityReq + userinfo, err := basic.RequestParse(w, r, svcCtx, &req) + if err != nil { + return + } + + // 创建一个业务逻辑层实例 + l := logic.NewModifyCartPurchaseQuantityLogic(r.Context(), svcCtx) + + rl := reflect.ValueOf(l) + basic.BeforeLogic(w, r, rl) + + resp := l.ModifyCartPurchaseQuantity(&req, userinfo) + + if !basic.AfterLogic(w, r, rl, resp) { + basic.NormalAfterLogic(w, r, resp) + } + } +} diff --git a/server/shopping-cart/internal/handler/routes.go b/server/shopping-cart/internal/handler/routes.go new file mode 100644 index 00000000..08ade841 --- /dev/null +++ b/server/shopping-cart/internal/handler/routes.go @@ -0,0 +1,37 @@ +// Code generated by goctl. DO NOT EDIT. +package handler + +import ( + "net/http" + + "fusenapi/server/shopping-cart/internal/svc" + + "github.com/zeromicro/go-zero/rest" +) + +func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { + server.AddRoutes( + []rest.Route{ + { + Method: http.MethodPost, + Path: "/api/shopping-cart/add_to_cart", + Handler: AddToCartHandler(serverCtx), + }, + { + Method: http.MethodPost, + Path: "/api/shopping-cart/delete_cart", + Handler: DeleteCartHandler(serverCtx), + }, + { + Method: http.MethodPost, + Path: "/api/shopping-cart/modify_cart_purchase_quantity", + Handler: ModifyCartPurchaseQuantityHandler(serverCtx), + }, + { + Method: http.MethodGet, + Path: "/api/shopping-cart/get_carts", + Handler: GetCartsHandler(serverCtx), + }, + }, + ) +} diff --git a/server/shopping-cart/internal/logic/addtocartlogic.go b/server/shopping-cart/internal/logic/addtocartlogic.go new file mode 100644 index 00000000..e360240d --- /dev/null +++ b/server/shopping-cart/internal/logic/addtocartlogic.go @@ -0,0 +1,43 @@ +package logic + +import ( + "fusenapi/utils/auth" + "fusenapi/utils/basic" + + "context" + + "fusenapi/server/shopping-cart/internal/svc" + "fusenapi/server/shopping-cart/internal/types" + + "github.com/zeromicro/go-zero/core/logx" +) + +type AddToCartLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +func NewAddToCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddToCartLogic { + return &AddToCartLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +// 处理进入前逻辑w,r +// func (l *AddToCartLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) { +// } + +func (l *AddToCartLogic) AddToCart(req *types.AddToCartReq, userinfo *auth.UserInfo) (resp *basic.Response) { + // 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data) + // userinfo 传入值时, 一定不为null + + return resp.SetStatus(basic.CodeOK) +} + +// 处理逻辑后 w,r 如:重定向, resp 必须重新处理 +// func (l *AddToCartLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) { +// // httpx.OkJsonCtx(r.Context(), w, resp) +// } diff --git a/server/shopping-cart/internal/logic/deletecartlogic.go b/server/shopping-cart/internal/logic/deletecartlogic.go new file mode 100644 index 00000000..865a811f --- /dev/null +++ b/server/shopping-cart/internal/logic/deletecartlogic.go @@ -0,0 +1,43 @@ +package logic + +import ( + "fusenapi/utils/auth" + "fusenapi/utils/basic" + + "context" + + "fusenapi/server/shopping-cart/internal/svc" + "fusenapi/server/shopping-cart/internal/types" + + "github.com/zeromicro/go-zero/core/logx" +) + +type DeleteCartLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +func NewDeleteCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteCartLogic { + return &DeleteCartLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +// 处理进入前逻辑w,r +// func (l *DeleteCartLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) { +// } + +func (l *DeleteCartLogic) DeleteCart(req *types.DeleteCartReq, userinfo *auth.UserInfo) (resp *basic.Response) { + // 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data) + // userinfo 传入值时, 一定不为null + + return resp.SetStatus(basic.CodeOK) +} + +// 处理逻辑后 w,r 如:重定向, resp 必须重新处理 +// func (l *DeleteCartLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) { +// // httpx.OkJsonCtx(r.Context(), w, resp) +// } diff --git a/server/shopping-cart/internal/logic/getcartslogic.go b/server/shopping-cart/internal/logic/getcartslogic.go new file mode 100644 index 00000000..097f91b7 --- /dev/null +++ b/server/shopping-cart/internal/logic/getcartslogic.go @@ -0,0 +1,43 @@ +package logic + +import ( + "fusenapi/utils/auth" + "fusenapi/utils/basic" + + "context" + + "fusenapi/server/shopping-cart/internal/svc" + "fusenapi/server/shopping-cart/internal/types" + + "github.com/zeromicro/go-zero/core/logx" +) + +type GetCartsLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +func NewGetCartsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetCartsLogic { + return &GetCartsLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +// 处理进入前逻辑w,r +// func (l *GetCartsLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) { +// } + +func (l *GetCartsLogic) GetCarts(req *types.GetCartsReq, userinfo *auth.UserInfo) (resp *basic.Response) { + // 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data) + // userinfo 传入值时, 一定不为null + + return resp.SetStatus(basic.CodeOK) +} + +// 处理逻辑后 w,r 如:重定向, resp 必须重新处理 +// func (l *GetCartsLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) { +// // httpx.OkJsonCtx(r.Context(), w, resp) +// } diff --git a/server/shopping-cart/internal/logic/modifycartpurchasequantitylogic.go b/server/shopping-cart/internal/logic/modifycartpurchasequantitylogic.go new file mode 100644 index 00000000..9da2b886 --- /dev/null +++ b/server/shopping-cart/internal/logic/modifycartpurchasequantitylogic.go @@ -0,0 +1,43 @@ +package logic + +import ( + "fusenapi/utils/auth" + "fusenapi/utils/basic" + + "context" + + "fusenapi/server/shopping-cart/internal/svc" + "fusenapi/server/shopping-cart/internal/types" + + "github.com/zeromicro/go-zero/core/logx" +) + +type ModifyCartPurchaseQuantityLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +func NewModifyCartPurchaseQuantityLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ModifyCartPurchaseQuantityLogic { + return &ModifyCartPurchaseQuantityLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +// 处理进入前逻辑w,r +// func (l *ModifyCartPurchaseQuantityLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) { +// } + +func (l *ModifyCartPurchaseQuantityLogic) ModifyCartPurchaseQuantity(req *types.ModifyCartPurchaseQuantityReq, userinfo *auth.UserInfo) (resp *basic.Response) { + // 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data) + // userinfo 传入值时, 一定不为null + + return resp.SetStatus(basic.CodeOK) +} + +// 处理逻辑后 w,r 如:重定向, resp 必须重新处理 +// func (l *ModifyCartPurchaseQuantityLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) { +// // httpx.OkJsonCtx(r.Context(), w, resp) +// } diff --git a/server/shopping-cart/internal/svc/servicecontext.go b/server/shopping-cart/internal/svc/servicecontext.go new file mode 100644 index 00000000..2b0f1a9a --- /dev/null +++ b/server/shopping-cart/internal/svc/servicecontext.go @@ -0,0 +1,26 @@ +package svc + +import ( + "fusenapi/initalize" + "fusenapi/model/gmodel" + "fusenapi/server/shopping-cart/internal/config" + "gorm.io/gorm" +) + +type ServiceContext struct { + Config config.Config + MysqlConn *gorm.DB + AllModels *gmodel.AllModelsGen + RabbitMq *initalize.RabbitMqHandle +} + +func NewServiceContext(c config.Config) *ServiceContext { + conn := initalize.InitMysql(c.SourceMysql) + + return &ServiceContext{ + Config: c, + MysqlConn: conn, + AllModels: gmodel.NewAllModels(initalize.InitMysql(c.SourceMysql)), + RabbitMq: initalize.InitRabbitMq(c.SourceRabbitMq, nil), + } +} diff --git a/server/shopping-cart/internal/types/types.go b/server/shopping-cart/internal/types/types.go new file mode 100644 index 00000000..4dbebdbb --- /dev/null +++ b/server/shopping-cart/internal/types/types.go @@ -0,0 +1,137 @@ +// Code generated by goctl. DO NOT EDIT. +package types + +import ( + "fusenapi/utils/basic" +) + +type AddToCartReq struct { + ProductId int64 `json:"product_id"` //产品id + TemplateId int64 `json:"template_id"` //模板id + SizeId int64 `json:"size_id"` //尺寸id + FittingId int64 `json:"fitting_id"` //配件id + PurchaseQuantity int64 `json:"purchase_quantity"` //购买数量 + Logo string `json:"logo"` //logo地址 + CombineImage string `json:"combine_image"` //合图地址 + RenderImage string `json:"render_image"` //渲染结果图 +} + +type DeleteCartReq struct { + Id int64 `json:"id"` //购物车id +} + +type ModifyCartPurchaseQuantityReq struct { + Id int64 `json:"id"` //购物车id + Quantity int64 `json:"quantity"` //数量 +} + +type GetCartsReq struct { + Page int `form:"page"` //当前页 +} + +type GetCartsRsp struct { + Meta Meta `json:"meta"` //分页信息 + CartList []CartItem `json:"cart_list"` +} + +type CartItem struct { + ProductId int64 `json:"product_id"` //产品id + SizeInfo SizeInfo `json:"size_info"` //尺寸信息 + FittingInfo FittingInfo `json:"fitting_info"` //配件信息 + ItemPrice string `json:"item_price"` //单价 + TotalPrice string `json:"totalPrice"` //单价X数量=总价 + DiyInformation DiyInformation `json:"diy_information"` //diy信息 + StepNum []int64 `json:"step_num"` //阶梯数量 +} + +type SizeInfo struct { + SizeId int64 `json:"size_id"` //尺寸id + Capacity string `json:"capacity"` //尺寸名称 + Title SizeTitle `json:"title"` +} + +type FittingInfo struct { + FittingId int64 `json:"fitting_id"` //配件id + FittingName string `json:"fitting_name"` //配件名称 +} + +type SizeTitle struct { + Cm string `json:"cm"` + Inch string `json:"inch"` +} + +type DiyInformation struct { + Phone string `json:"phone"` + Address string `json:"address"` + Website string `json:"website"` + Qrcode string `json:"qrcode"` +} + +type Request struct { +} + +type Response struct { + Code int `json:"code"` + Message string `json:"msg"` + Data interface{} `json:"data"` +} + +type Auth struct { + AccessSecret string `json:"accessSecret"` + AccessExpire int64 `json:"accessExpire"` + RefreshAfter int64 `json:"refreshAfter"` +} + +type File struct { + Filename string `fsfile:"filename"` + Header map[string][]string `fsfile:"header"` + Size int64 `fsfile:"size"` + Data []byte `fsfile:"data"` +} + +type Meta struct { + TotalCount int64 `json:"totalCount"` + PageCount int64 `json:"pageCount"` + CurrentPage int `json:"currentPage"` + PerPage int `json:"perPage"` +} + +// 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 +} diff --git a/server/shopping-cart/shopping-cart.go b/server/shopping-cart/shopping-cart.go new file mode 100644 index 00000000..f7a8cb3f --- /dev/null +++ b/server/shopping-cart/shopping-cart.go @@ -0,0 +1,36 @@ +package main + +import ( + "flag" + "fmt" + "net/http" + "time" + + "fusenapi/utils/auth" + + "fusenapi/server/shopping-cart/internal/config" + "fusenapi/server/shopping-cart/internal/handler" + "fusenapi/server/shopping-cart/internal/svc" + + "github.com/zeromicro/go-zero/core/conf" + "github.com/zeromicro/go-zero/rest" +) + +var configFile = flag.String("f", "etc/shopping-cart.yaml", "the config file") + +func main() { + flag.Parse() + + var c config.Config + conf.MustLoad(*configFile, &c) + c.Timeout = int64(time.Second * 15) + server := rest.MustNewServer(c.RestConf, rest.WithCustomCors(auth.FsCors, func(w http.ResponseWriter) { + })) + 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() +} From f56946fce9254a7a7a9c2efe12aeba99095835f9 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 13 Sep 2023 18:37:50 +0800 Subject: [PATCH 05/59] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?=E8=B4=AD=E7=89=A9=E8=BD=A6=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- model/gmodel/fs_shopping_cart_gen.go | 1 + .../internal/logic/addtocartlogic.go | 79 ++++++++++++++++++- 2 files changed, 77 insertions(+), 3 deletions(-) diff --git a/model/gmodel/fs_shopping_cart_gen.go b/model/gmodel/fs_shopping_cart_gen.go index e58ae44b..0cdf795f 100644 --- a/model/gmodel/fs_shopping_cart_gen.go +++ b/model/gmodel/fs_shopping_cart_gen.go @@ -8,6 +8,7 @@ import ( // fs_shopping_cart 新版购物车表 type FsShoppingCart struct { Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // id + UserId *int64 `gorm:"default:0;" json:"user_id"` // 用户id ProductId *int64 `gorm:"default:0;" json:"product_id"` // 产品id TemplateId *int64 `gorm:"default:0;" json:"template_id"` // 模板id ModelId *int64 `gorm:"default:0;" json:"model_id"` // 模型id diff --git a/server/shopping-cart/internal/logic/addtocartlogic.go b/server/shopping-cart/internal/logic/addtocartlogic.go index e360240d..858ad0d6 100644 --- a/server/shopping-cart/internal/logic/addtocartlogic.go +++ b/server/shopping-cart/internal/logic/addtocartlogic.go @@ -1,8 +1,10 @@ package logic import ( + "errors" "fusenapi/utils/auth" "fusenapi/utils/basic" + "gorm.io/gorm" "context" @@ -31,12 +33,83 @@ func NewAddToCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddToCa // } func (l *AddToCartLogic) AddToCart(req *types.AddToCartReq, userinfo *auth.UserInfo) (resp *basic.Response) { - // 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data) - // userinfo 传入值时, 一定不为null - + if !userinfo.IsUser() { + return resp.SetStatusWithMessage(basic.CodeUnAuth, "please sign in before add to shopping cart") + } + //校验参数 + if err := l.AddToCartParamVerify(req); err != nil { + return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, err.Error()) + } + //获取产品信息 + productInfo, err := l.svcCtx.AllModels.FsProduct.FindOne(l.ctx, req.ProductId) + if err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "the product is not exists") + } + logx.Error("获取产品信息错误:", err) + return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get product info") + } + //获取模板信息 + templateInfo, err := l.svcCtx.AllModels.FsProductTemplateV2.FindOne(l.ctx, req.TemplateId) + if err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "the template is not exists") + } + logx.Error("获取模板信息错误:", err) + return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get template info") + } + if *templateInfo.IsDel == 1 { + return resp.SetStatusWithMessage(basic.CodeServiceErr, "the template is deleted") + } + if *templateInfo.Status != 1 { + return resp.SetStatusWithMessage(basic.CodeServiceErr, "the template`s status is unNormal") + } + //获取模型信息 + modelInfo, err := l.svcCtx.AllModels.FsProductModel3d.FindOne(l.ctx, *templateInfo.ModelId) + if err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "the template`s model is not exists") + } + logx.Error("获取模型信息错误:", err) + return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get template`s model info") + } + //模型里面的size_id是否跟传入的size_id匹配 + if req.SizeId != *modelInfo.SizeId { + return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "param size_id is not match model`s size_id") + } + //获取尺寸信息 + sizeInfo, err := l.svcCtx.AllModels.FsProductSize.FindOne(l.ctx, req.SizeId) + if err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "the size is not exists") + } + logx.Error("获取尺寸信息错误:", err) + return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "failed to get size info") + } + //状态 + if *sizeInfo.Status != 1 { + return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "size info status is not normal") + } return resp.SetStatus(basic.CodeOK) } +// 参数校验 +func (l *AddToCartLogic) AddToCartParamVerify(req *types.AddToCartReq) error { + if req.ProductId <= 0 { + return errors.New("invalid param:product_id") + } + if req.SizeId <= 0 { + return errors.New("invalid param:size_id") + } + if req.TemplateId <= 0 { + return errors.New("invalid param:template_id") + } + if req.PurchaseQuantity <= 0 { + return errors.New("invalid param:purchase_quantity") + } + return nil +} + // 处理逻辑后 w,r 如:重定向, resp 必须重新处理 // func (l *AddToCartLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) { // // httpx.OkJsonCtx(r.Context(), w, resp) From 13d5219e53728b35b2c80b2bb8c46386d4405a9f Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Thu, 14 Sep 2023 14:11:22 +0800 Subject: [PATCH 06/59] fix --- constants/min_purchase_box.go | 6 + model/gmodel/fs_shopping_cart_gen.go | 9 +- model/gmodel/fs_shopping_cart_logic.go | 48 +++++- .../internal/logic/addtocartlogic.go | 143 +++++++++++++----- server/shopping-cart/internal/types/types.go | 25 ++- server_api/shopping-cart.api | 24 ++- utils/shopping_cart/shopping_cart_snapshot.go | 33 ++++ 7 files changed, 228 insertions(+), 60 deletions(-) create mode 100644 constants/min_purchase_box.go create mode 100644 utils/shopping_cart/shopping_cart_snapshot.go diff --git a/constants/min_purchase_box.go b/constants/min_purchase_box.go new file mode 100644 index 00000000..9b26d20c --- /dev/null +++ b/constants/min_purchase_box.go @@ -0,0 +1,6 @@ +package constants + +type Purchase int64 + +// 最低购买箱数 +const MIN_PURCHASE_QUANTITY Purchase = 3 diff --git a/model/gmodel/fs_shopping_cart_gen.go b/model/gmodel/fs_shopping_cart_gen.go index 0cdf795f..2997ec11 100644 --- a/model/gmodel/fs_shopping_cart_gen.go +++ b/model/gmodel/fs_shopping_cart_gen.go @@ -12,22 +12,15 @@ type FsShoppingCart struct { ProductId *int64 `gorm:"default:0;" json:"product_id"` // 产品id TemplateId *int64 `gorm:"default:0;" json:"template_id"` // 模板id ModelId *int64 `gorm:"default:0;" json:"model_id"` // 模型id - PriceId *int64 `gorm:"default:0;" json:"price_id"` // 价格id SizeId *int64 `gorm:"default:0;" json:"size_id"` // 尺寸id - MaterialId *int64 `gorm:"default:0;" json:"material_id"` // 材质id FittingId *int64 `gorm:"default:0;" json:"fitting_id"` // 配件id PurchaseQuantity *int64 `gorm:"default:0;" json:"purchase_quantity"` // 购买数量 - UnitPrice *int64 `gorm:"default:0;" json:"unit_price"` // 当时加入购物车的单价,不作为支付计算,支付计算需要实时价格(厘)换算美元除以1000 - TotalPrice *int64 `gorm:"default:0;" json:"total_price"` // 当时加入购物车单价x数量的总价,不作为支付计算,支付计算需要实时价格 - Logo *string `gorm:"default:'';" json:"logo"` // - CombineImage *string `gorm:"default:'';" json:"combine_image"` // - RenderImage *string `gorm:"default:'';" json:"render_image"` // Snapshot *string `gorm:"default:'';" json:"snapshot"` // IsHighlyCustomized *int64 `gorm:"default:0;" json:"is_highly_customized"` // 是否高度定制 0非 1是(针对客人高度定制只能后台增加如购物车) Status *int64 `gorm:"default:0;" json:"status"` // 0未下单 1已下单 IsEffective *int64 `gorm:"default:1;" json:"is_effective"` // 是否有效 0非 1是(针对对购物车下单,此前数据表更失效) - IsDeleted *int64 `gorm:"default:0;" json:"is_deleted"` // 0正常 1删除 Ctime *time.Time `gorm:"default:'0000-00-00 00:00:00';" json:"ctime"` // + Utime *time.Time `gorm:"default:'0000-00-00 00:00:00';" json:"utime"` // } type FsShoppingCartModel struct { db *gorm.DB diff --git a/model/gmodel/fs_shopping_cart_logic.go b/model/gmodel/fs_shopping_cart_logic.go index e68225aa..684078ce 100644 --- a/model/gmodel/fs_shopping_cart_logic.go +++ b/model/gmodel/fs_shopping_cart_logic.go @@ -1,2 +1,48 @@ package gmodel -// TODO: 使用model的属性做你想做的 \ No newline at end of file + +import "context" + +// 获取用户购物车数量 +func (s *FsShoppingCartModel) CountUserCart(ctx context.Context, userId int64) (total int64, err error) { + err = s.db.WithContext(ctx).Where("user_id = ?", userId).Limit(1).Count(&total).Error + return total, err +} + +// 获取单个 +func (s *FsShoppingCartModel) FindOne(ctx context.Context, id int64, fields ...string) (resp *FsShoppingCart, err error) { + db := s.db.WithContext(ctx).Where("id = ?", id) + if len(fields) > 0 { + db = db.Select(fields[0]) + } + err = db.Take(&resp).Error + return resp, err +} + +// 获取多个 +func (s *FsShoppingCartModel) GetAllByIds(ctx context.Context, ids []int64, sort string, fields ...string) (resp []FsShoppingCart, err error) { + if len(ids) == 0 { + return + } + db := s.db.WithContext(ctx).Where("id in (?)", ids) + if len(fields) > 0 { + db = db.Select(fields[0]) + } + if sort != "" { + db = db.Order(sort) + } + err = db.Find(&resp).Error + return resp, err +} + +// 获取用户所有的购物车 +func (s *FsShoppingCartModel) GetUserAllCarts(ctx context.Context, userId int64, sort string, fields ...string) (resp []FsShoppingCart, err error) { + db := s.db.WithContext(ctx).Where("user_id = ?", userId) + if len(fields) > 0 { + db = db.Select(fields[0]) + } + if sort != "" { + db = db.Order(sort) + } + err = db.Find(&resp).Error + return resp, err +} diff --git a/server/shopping-cart/internal/logic/addtocartlogic.go b/server/shopping-cart/internal/logic/addtocartlogic.go index 858ad0d6..f6cca17b 100644 --- a/server/shopping-cart/internal/logic/addtocartlogic.go +++ b/server/shopping-cart/internal/logic/addtocartlogic.go @@ -1,12 +1,16 @@ package logic import ( + "context" "errors" + "fmt" + "fusenapi/constants" + "fusenapi/model/gmodel" "fusenapi/utils/auth" "fusenapi/utils/basic" + "fusenapi/utils/shopping_cart" "gorm.io/gorm" - - "context" + "math" "fusenapi/server/shopping-cart/internal/svc" "fusenapi/server/shopping-cart/internal/types" @@ -40,8 +44,17 @@ func (l *AddToCartLogic) AddToCart(req *types.AddToCartReq, userinfo *auth.UserI if err := l.AddToCartParamVerify(req); err != nil { return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, err.Error()) } - //获取产品信息 - productInfo, err := l.svcCtx.AllModels.FsProduct.FindOne(l.ctx, req.ProductId) + //查询该用户购物车数量 + cartCount, err := l.svcCtx.AllModels.FsShoppingCart.CountUserCart(l.ctx, userinfo.UserId) + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get the count of your shopping cart") + } + if cartCount >= 100 { + return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "sorry,the count of your carts can`t greater than 100") + } + //获取产品是否存在 + _, err = l.svcCtx.AllModels.FsProduct.FindOne(l.ctx, req.ProductId, "id") if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "the product is not exists") @@ -49,23 +62,66 @@ func (l *AddToCartLogic) AddToCart(req *types.AddToCartReq, userinfo *auth.UserI logx.Error("获取产品信息错误:", err) return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get product info") } - //获取模板信息 - templateInfo, err := l.svcCtx.AllModels.FsProductTemplateV2.FindOne(l.ctx, req.TemplateId) + var ( + templateJson string //模板表的记录中的json设计信息 + templateTag string //模板表的模板标签 + fittingJson string //配件的json设计信息 + ) + //有模板 + if req.TemplateId > 0 { + templateInfo, err := l.svcCtx.AllModels.FsProductTemplateV2.FindOne(l.ctx, req.TemplateId) + if err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "the template is not exists") + } + logx.Error("获取模板信息错误:", err) + return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get template info") + } + if *templateInfo.IsDel == 1 { + return resp.SetStatusWithMessage(basic.CodeServiceErr, "the template is deleted") + } + if *templateInfo.Status != 1 { + return resp.SetStatusWithMessage(basic.CodeServiceErr, "the template`s status is unNormal") + } + if templateInfo.TemplateInfo == nil || *templateInfo.TemplateInfo == "" { + return resp.SetStatusWithMessage(basic.CodeServiceErr, "the template`s design info is empty") + } + templateJson = *templateInfo.TemplateInfo + templateTag = *templateInfo.TemplateTag + } + //有配件 + if req.FittingId > 0 { + fittingInfo, err := l.svcCtx.AllModels.FsProductModel3d.FindOne(l.ctx, req.FittingId) + if err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "the fitting is not exists") + } + logx.Error("获取配件信息错误:", err) + return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get fitting info") + } + if *fittingInfo.Status != 1 { + return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "the fitting`s status is unNormal") + } + if fittingInfo.ModelInfo == nil || *fittingInfo.ModelInfo == "" { + return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "the fitting`s design info is empty") + } + fittingJson = *fittingInfo.ModelInfo + } + //获取尺寸信息 + sizeInfo, err := l.svcCtx.AllModels.FsProductSize.FindOne(l.ctx, req.SizeId) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { - return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "the template is not exists") + return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "the size is not exists") } - logx.Error("获取模板信息错误:", err) - return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get template info") + logx.Error("获取尺寸信息错误:", err) + return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get size info") } - if *templateInfo.IsDel == 1 { - return resp.SetStatusWithMessage(basic.CodeServiceErr, "the template is deleted") - } - if *templateInfo.Status != 1 { - return resp.SetStatusWithMessage(basic.CodeServiceErr, "the template`s status is unNormal") + //状态 + if *sizeInfo.Status != 1 { + return resp.SetStatusWithMessage(basic.CodeServiceErr, "size info status is not normal") } //获取模型信息 - modelInfo, err := l.svcCtx.AllModels.FsProductModel3d.FindOne(l.ctx, *templateInfo.ModelId) + modelInfo, err := l.svcCtx.AllModels.FsProductModel3d.GetOneBySizeIdTag(l.ctx, sizeInfo.Id, constants.TAG_MODEL) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "the template`s model is not exists") @@ -73,39 +129,56 @@ func (l *AddToCartLogic) AddToCart(req *types.AddToCartReq, userinfo *auth.UserI logx.Error("获取模型信息错误:", err) return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get template`s model info") } - //模型里面的size_id是否跟传入的size_id匹配 - if req.SizeId != *modelInfo.SizeId { - return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "param size_id is not match model`s size_id") + if *modelInfo.Status != 1 { + return resp.SetStatusWithMessage(basic.CodeServiceErr, "the model` status is unNormal") } - //获取尺寸信息 - sizeInfo, err := l.svcCtx.AllModels.FsProductSize.FindOne(l.ctx, req.SizeId) - if err != nil { - if errors.Is(err, gorm.ErrRecordNotFound) { - return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "the size is not exists") - } - logx.Error("获取尺寸信息错误:", err) - return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "failed to get size info") + //如果模型是配件则返回 + if *modelInfo.Tag != 1 { + return resp.SetStatusWithMessage(basic.CodeServiceErr, "the model your post is not a model but fitting") } - //状态 - if *sizeInfo.Status != 1 { - return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "size info status is not normal") + if modelInfo.ModelInfo == nil || *modelInfo.ModelInfo == "" { + return resp.SetStatusWithMessage(basic.CodeServiceErr, "the model`s design info is empty") } + //快照数据 + snapshot := shopping_cart.CartSnapshot{ + Logo: req.Logo, + CombineImage: req.CombineImage, + RenderImage: req.RenderImage, + TemplateInfo: shopping_cart.TemplateInfo{ + TemplateJson: templateJson, + TemplateTag: templateTag, + }, + ModelInfo: shopping_cart.ModelInfo{ + ModelJson: *modelInfo.ModelInfo, + }, + FittingInfo: shopping_cart.FittingInfo{ + FittingJson: fittingJson, + }, + SizeInfo: shopping_cart.SizeInfo{ + Title: *sizeInfo.Title, + }, + UserDiyInformation: shopping_cart.UserDiyInformation{ + Phone: req.DiyInfo.Phone, + Address: req.DiyInfo.Address, + Website: req.DiyInfo.Website, + Qrcode: req.DiyInfo.Qrcode, + Slogan: req.DiyInfo.Slogan, + }, + } + //根据 return resp.SetStatus(basic.CodeOK) } // 参数校验 func (l *AddToCartLogic) AddToCartParamVerify(req *types.AddToCartReq) error { if req.ProductId <= 0 { - return errors.New("invalid param:product_id") + return errors.New("product_id is required") } if req.SizeId <= 0 { - return errors.New("invalid param:size_id") - } - if req.TemplateId <= 0 { - return errors.New("invalid param:template_id") + return errors.New("product size is required") } if req.PurchaseQuantity <= 0 { - return errors.New("invalid param:purchase_quantity") + return errors.New("purchase quantity can not less than 0 or equal 0") } return nil } diff --git a/server/shopping-cart/internal/types/types.go b/server/shopping-cart/internal/types/types.go index 4dbebdbb..5d474939 100644 --- a/server/shopping-cart/internal/types/types.go +++ b/server/shopping-cart/internal/types/types.go @@ -6,14 +6,23 @@ import ( ) type AddToCartReq struct { - ProductId int64 `json:"product_id"` //产品id - TemplateId int64 `json:"template_id"` //模板id - SizeId int64 `json:"size_id"` //尺寸id - FittingId int64 `json:"fitting_id"` //配件id - PurchaseQuantity int64 `json:"purchase_quantity"` //购买数量 - Logo string `json:"logo"` //logo地址 - CombineImage string `json:"combine_image"` //合图地址 - RenderImage string `json:"render_image"` //渲染结果图 + ProductId int64 `json:"product_id"` //产品id + TemplateId int64 `json:"template_id,optional"` //模板id(不可定制的不传) + SizeId int64 `json:"size_id"` //尺寸id + FittingId int64 `json:"fitting_id,optional"` //配件id(没有可以不传) + PurchaseQuantity int64 `json:"purchase_quantity"` //购买数量 + Logo string `json:"logo,optional"` //logo地址(没有可以不传) + CombineImage string `json:"combine_image,optional"` //合图地址 (没有可以不传) + RenderImage string `json:"render_image,optional"` //渲染结果图 (没有可以不传) + DiyInfo DiyInfo `json:"diy_info,optional"` //用户diy数据(可选) +} + +type DiyInfo struct { + Phone string `json:"phone,optional"` //电话(可选) + Address string `json:"address,optional"` //地址 (可选) + Website string `json:"website,optional"` //网站 (可选) + Qrcode string `json:"qrcode,optional"` //二维码 (可选) + Slogan string `json:"slogan,optional"` //slogan (可选) } type DeleteCartReq struct { diff --git a/server_api/shopping-cart.api b/server_api/shopping-cart.api index 9731e835..5d50db8f 100644 --- a/server_api/shopping-cart.api +++ b/server_api/shopping-cart.api @@ -25,14 +25,22 @@ service shopping-cart { //加入购物车 type AddToCartReq { - ProductId int64 `json:"product_id"` //产品id - TemplateId int64 `json:"template_id"` //模板id - SizeId int64 `json:"size_id"` //尺寸id - FittingId int64 `json:"fitting_id"` //配件id - PurchaseQuantity int64 `json:"purchase_quantity"` //购买数量 - Logo string `json:"logo"` //logo地址 - CombineImage string `json:"combine_image"` //合图地址 - RenderImage string `json:"render_image"` //渲染结果图 + ProductId int64 `json:"product_id"` //产品id + TemplateId int64 `json:"template_id,optional"` //模板id(不可定制的不传) + SizeId int64 `json:"size_id"` //尺寸id + FittingId int64 `json:"fitting_id,optional"` //配件id(没有可以不传) + PurchaseQuantity int64 `json:"purchase_quantity"` //购买数量 + Logo string `json:"logo,optional"` //logo地址(没有可以不传) + CombineImage string `json:"combine_image,optional"` //合图地址 (没有可以不传) + RenderImage string `json:"render_image,optional"` //渲染结果图 (没有可以不传) + DiyInfo DiyInfo `json:"diy_info,optional"` //用户diy数据(可选) +} +type DiyInfo { + Phone string `json:"phone,optional"` //电话(可选) + Address string `json:"address,optional"` //地址 (可选) + Website string `json:"website,optional"` //网站 (可选) + Qrcode string `json:"qrcode,optional"` //二维码 (可选) + Slogan string `json:"slogan,optional"` //slogan (可选) } //删除购物车 type DeleteCartReq { diff --git a/utils/shopping_cart/shopping_cart_snapshot.go b/utils/shopping_cart/shopping_cart_snapshot.go new file mode 100644 index 00000000..66d23aa4 --- /dev/null +++ b/utils/shopping_cart/shopping_cart_snapshot.go @@ -0,0 +1,33 @@ +package shopping_cart + +// 购物车快照数据结构 +type CartSnapshot struct { + Logo string `json:"logo"` //logo地址 + CombineImage string `json:"combine_image"` //刀版图地址 + RenderImage string `json:"render_image"` //渲染结果图 + TemplateInfo TemplateInfo `json:"template_info"` //模板数据 + ModelInfo ModelInfo `json:"model_info"` //模型的数据 + FittingInfo FittingInfo `json:"fitting_info"` //配件信息 + SizeInfo SizeInfo `json:"size_info"` //尺寸基本信息 + UserDiyInformation UserDiyInformation `json:"user_diy_information"` //用户diy数据 +} +type ModelInfo struct { + ModelJson string `json:"model_json"` //模型json数据 +} +type FittingInfo struct { + FittingJson string `json:"fitting_json"` +} +type TemplateInfo struct { + TemplateJson string `json:"template_json"` //模板json数据 + TemplateTag string `json:"template_tag"` //模板标签 +} +type SizeInfo struct { + Title string `json:"title"` +} +type UserDiyInformation struct { + Phone string `json:"phone"` + Address string `json:"address"` + Website string `json:"website"` + Qrcode string `json:"qrcode"` + Slogan string `json:"slogan"` +} From b71141807b7bbbc172d5b23414eab6d54cb12b7f Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Thu, 14 Sep 2023 15:20:37 +0800 Subject: [PATCH 07/59] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?=E8=B4=AD=E7=89=A9=E8=BD=A6=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- model/gmodel/fs_shopping_cart_logic.go | 17 ++++++---- .../internal/logic/addtocartlogic.go | 31 ++++++++++++++----- utils/shopping_cart/shopping_cart_snapshot.go | 18 +++++------ 3 files changed, 44 insertions(+), 22 deletions(-) diff --git a/model/gmodel/fs_shopping_cart_logic.go b/model/gmodel/fs_shopping_cart_logic.go index 684078ce..c26ede81 100644 --- a/model/gmodel/fs_shopping_cart_logic.go +++ b/model/gmodel/fs_shopping_cart_logic.go @@ -2,12 +2,6 @@ package gmodel import "context" -// 获取用户购物车数量 -func (s *FsShoppingCartModel) CountUserCart(ctx context.Context, userId int64) (total int64, err error) { - err = s.db.WithContext(ctx).Where("user_id = ?", userId).Limit(1).Count(&total).Error - return total, err -} - // 获取单个 func (s *FsShoppingCartModel) FindOne(ctx context.Context, id int64, fields ...string) (resp *FsShoppingCart, err error) { db := s.db.WithContext(ctx).Where("id = ?", id) @@ -18,6 +12,17 @@ func (s *FsShoppingCartModel) FindOne(ctx context.Context, id int64, fields ...s return resp, err } +// 创建 +func (s *FsShoppingCartModel) Create(ctx context.Context, data *FsShoppingCart) error { + return s.db.WithContext(ctx).Create(&data).Error +} + +// 获取用户购物车数量 +func (s *FsShoppingCartModel) CountUserCart(ctx context.Context, userId int64) (total int64, err error) { + err = s.db.WithContext(ctx).Where("user_id = ?", userId).Limit(1).Count(&total).Error + return total, err +} + // 获取多个 func (s *FsShoppingCartModel) GetAllByIds(ctx context.Context, ids []int64, sort string, fields ...string) (resp []FsShoppingCart, err error) { if len(ids) == 0 { diff --git a/server/shopping-cart/internal/logic/addtocartlogic.go b/server/shopping-cart/internal/logic/addtocartlogic.go index f6cca17b..d939aaac 100644 --- a/server/shopping-cart/internal/logic/addtocartlogic.go +++ b/server/shopping-cart/internal/logic/addtocartlogic.go @@ -2,18 +2,17 @@ package logic import ( "context" + "encoding/json" "errors" - "fmt" "fusenapi/constants" "fusenapi/model/gmodel" + "fusenapi/server/shopping-cart/internal/svc" + "fusenapi/server/shopping-cart/internal/types" "fusenapi/utils/auth" "fusenapi/utils/basic" "fusenapi/utils/shopping_cart" "gorm.io/gorm" - "math" - - "fusenapi/server/shopping-cart/internal/svc" - "fusenapi/server/shopping-cart/internal/types" + "time" "github.com/zeromicro/go-zero/core/logx" ) @@ -165,8 +164,26 @@ func (l *AddToCartLogic) AddToCart(req *types.AddToCartReq, userinfo *auth.UserI Slogan: req.DiyInfo.Slogan, }, } - //根据 - return resp.SetStatus(basic.CodeOK) + snapshotJsonBytes, _ := json.Marshal(snapshot) + snapshotJsonStr := string(snapshotJsonBytes) + now := time.Now().UTC() + err = l.svcCtx.AllModels.FsShoppingCart.Create(l.ctx, &gmodel.FsShoppingCart{ + UserId: &userinfo.UserId, + ProductId: &req.ProductId, + TemplateId: &req.TemplateId, + ModelId: &modelInfo.Id, + SizeId: &req.SizeId, + FittingId: &req.FittingId, + PurchaseQuantity: &req.PurchaseQuantity, + Snapshot: &snapshotJsonStr, + Ctime: &now, + Utime: &now, + }) + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "system err:failed to add to cart ") + } + return resp.SetStatus(basic.CodeOK, "success") } // 参数校验 diff --git a/utils/shopping_cart/shopping_cart_snapshot.go b/utils/shopping_cart/shopping_cart_snapshot.go index 66d23aa4..30705c06 100644 --- a/utils/shopping_cart/shopping_cart_snapshot.go +++ b/utils/shopping_cart/shopping_cart_snapshot.go @@ -12,22 +12,22 @@ type CartSnapshot struct { UserDiyInformation UserDiyInformation `json:"user_diy_information"` //用户diy数据 } type ModelInfo struct { - ModelJson string `json:"model_json"` //模型json数据 + ModelJson string `json:"model_json"` //模型设计json数据 } type FittingInfo struct { - FittingJson string `json:"fitting_json"` + FittingJson string `json:"fitting_json"` //配件设计json数据 } type TemplateInfo struct { - TemplateJson string `json:"template_json"` //模板json数据 + TemplateJson string `json:"template_json"` //模板设计json数据 TemplateTag string `json:"template_tag"` //模板标签 } type SizeInfo struct { - Title string `json:"title"` + Title string `json:"title"` //尺寸信息 } type UserDiyInformation struct { - Phone string `json:"phone"` - Address string `json:"address"` - Website string `json:"website"` - Qrcode string `json:"qrcode"` - Slogan string `json:"slogan"` + Phone string `json:"phone"` //电话 + Address string `json:"address"` //地址 + Website string `json:"website"` //网站 + Qrcode string `json:"qrcode"` //二维码 + Slogan string `json:"slogan"` //slogan } From 0bb11f975d319a885b88d8493a53dd7fc7dc8b54 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Thu, 14 Sep 2023 15:46:37 +0800 Subject: [PATCH 08/59] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E6=9B=B4=E6=96=B0?= =?UTF-8?q?=E8=B4=AD=E7=89=A9=E8=BD=A6=E8=B4=AD=E4=B9=B0=E6=95=B0=E9=87=8F?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- model/gmodel/fs_shopping_cart_gen.go | 2 -- model/gmodel/fs_shopping_cart_logic.go | 15 ++++++++ model/gmodel/var_gen.go | 2 ++ .../internal/logic/addtocartlogic.go | 2 +- .../logic/modifycartpurchasequantitylogic.go | 34 ++++++++++++++++--- server/shopping-cart/internal/types/types.go | 4 +-- server_api/shopping-cart.api | 4 +-- 7 files changed, 52 insertions(+), 11 deletions(-) diff --git a/model/gmodel/fs_shopping_cart_gen.go b/model/gmodel/fs_shopping_cart_gen.go index 2997ec11..04996ad2 100644 --- a/model/gmodel/fs_shopping_cart_gen.go +++ b/model/gmodel/fs_shopping_cart_gen.go @@ -17,8 +17,6 @@ type FsShoppingCart struct { PurchaseQuantity *int64 `gorm:"default:0;" json:"purchase_quantity"` // 购买数量 Snapshot *string `gorm:"default:'';" json:"snapshot"` // IsHighlyCustomized *int64 `gorm:"default:0;" json:"is_highly_customized"` // 是否高度定制 0非 1是(针对客人高度定制只能后台增加如购物车) - Status *int64 `gorm:"default:0;" json:"status"` // 0未下单 1已下单 - IsEffective *int64 `gorm:"default:1;" json:"is_effective"` // 是否有效 0非 1是(针对对购物车下单,此前数据表更失效) Ctime *time.Time `gorm:"default:'0000-00-00 00:00:00';" json:"ctime"` // Utime *time.Time `gorm:"default:'0000-00-00 00:00:00';" json:"utime"` // } diff --git a/model/gmodel/fs_shopping_cart_logic.go b/model/gmodel/fs_shopping_cart_logic.go index c26ede81..d9c3894c 100644 --- a/model/gmodel/fs_shopping_cart_logic.go +++ b/model/gmodel/fs_shopping_cart_logic.go @@ -12,11 +12,26 @@ func (s *FsShoppingCartModel) FindOne(ctx context.Context, id int64, fields ...s return resp, err } +// 获取用户购物车指定item +func (s *FsShoppingCartModel) FineOneUserCart(ctx context.Context, id, userId int64, fields ...string) (resp *FsShoppingCart, err error) { + db := s.db.WithContext(ctx).Where("user_id = ? and id = ?", userId, id) + if len(fields) > 0 { + db = db.Select(fields[0]) + } + err = db.Take(&resp).Error + return resp, err +} + // 创建 func (s *FsShoppingCartModel) Create(ctx context.Context, data *FsShoppingCart) error { return s.db.WithContext(ctx).Create(&data).Error } +// 更新 +func (s *FsShoppingCartModel) Update(ctx context.Context, id, userId int64, data *FsShoppingCart) error { + return s.db.WithContext(ctx).Where("user_id = ? and id = ?", userId, id).Updates(&data).Error +} + // 获取用户购物车数量 func (s *FsShoppingCartModel) CountUserCart(ctx context.Context, userId int64) (total int64, err error) { err = s.db.WithContext(ctx).Where("user_id = ?", userId).Limit(1).Count(&total).Error diff --git a/model/gmodel/var_gen.go b/model/gmodel/var_gen.go index 1d92c033..b22d8ad4 100644 --- a/model/gmodel/var_gen.go +++ b/model/gmodel/var_gen.go @@ -60,6 +60,7 @@ type AllModelsGen struct { FsOrderDetail *FsOrderDetailModel // fs_order_detail 订单详细表 FsOrderDetailTemplate *FsOrderDetailTemplateModel // fs_order_detail_template 订单模板详细表 FsOrderRemark *FsOrderRemarkModel // fs_order_remark 订单备注表 + FsOrdersTrade *FsOrdersTradeModel // fs_orders_trade 订单交易记录表 FsPay *FsPayModel // fs_pay 支付记录 FsPayEvent *FsPayEventModel // fs_pay_event 支付回调事件日志 FsProduct *FsProductModel // fs_product 产品表 @@ -167,6 +168,7 @@ func NewAllModels(gdb *gorm.DB) *AllModelsGen { FsOrderDetail: NewFsOrderDetailModel(gdb), FsOrderDetailTemplate: NewFsOrderDetailTemplateModel(gdb), FsOrderRemark: NewFsOrderRemarkModel(gdb), + FsOrdersTrade: NewFsOrdersTradeModel(gdb), FsPay: NewFsPayModel(gdb), FsPayEvent: NewFsPayEventModel(gdb), FsProduct: NewFsProductModel(gdb), diff --git a/server/shopping-cart/internal/logic/addtocartlogic.go b/server/shopping-cart/internal/logic/addtocartlogic.go index d939aaac..f9ef46f3 100644 --- a/server/shopping-cart/internal/logic/addtocartlogic.go +++ b/server/shopping-cart/internal/logic/addtocartlogic.go @@ -37,7 +37,7 @@ func NewAddToCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddToCa func (l *AddToCartLogic) AddToCart(req *types.AddToCartReq, userinfo *auth.UserInfo) (resp *basic.Response) { if !userinfo.IsUser() { - return resp.SetStatusWithMessage(basic.CodeUnAuth, "please sign in before add to shopping cart") + return resp.SetStatusWithMessage(basic.CodeUnAuth, "please sign in") } //校验参数 if err := l.AddToCartParamVerify(req); err != nil { diff --git a/server/shopping-cart/internal/logic/modifycartpurchasequantitylogic.go b/server/shopping-cart/internal/logic/modifycartpurchasequantitylogic.go index 9da2b886..b78dd2e8 100644 --- a/server/shopping-cart/internal/logic/modifycartpurchasequantitylogic.go +++ b/server/shopping-cart/internal/logic/modifycartpurchasequantitylogic.go @@ -1,8 +1,11 @@ package logic import ( + "errors" + "fusenapi/model/gmodel" "fusenapi/utils/auth" "fusenapi/utils/basic" + "gorm.io/gorm" "context" @@ -31,10 +34,33 @@ func NewModifyCartPurchaseQuantityLogic(ctx context.Context, svcCtx *svc.Service // } func (l *ModifyCartPurchaseQuantityLogic) ModifyCartPurchaseQuantity(req *types.ModifyCartPurchaseQuantityReq, userinfo *auth.UserInfo) (resp *basic.Response) { - // 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data) - // userinfo 传入值时, 一定不为null - - return resp.SetStatus(basic.CodeOK) + if !userinfo.IsUser() { + return resp.SetStatusWithMessage(basic.CodeUnAuth, "please sign in") + } + if req.Id <= 0 { + return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "cart id is required") + } + if req.PurchaseQuantity <= 0 { + return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "purchase quantity can not less than 0 or equal to 0") + } + //查询购物车 + _, err := l.svcCtx.AllModels.FsShoppingCart.FineOneUserCart(l.ctx, req.Id, userinfo.UserId, "id") + if err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "the shopping cart is not exists") + } + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "system err:failed to get shopping cart info ") + } + //修改数量 + err = l.svcCtx.AllModels.FsShoppingCart.Update(l.ctx, req.Id, userinfo.UserId, &gmodel.FsShoppingCart{ + PurchaseQuantity: &req.PurchaseQuantity, + }) + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "system err:failed to modify cart purchase quantity") + } + return resp.SetStatus(basic.CodeOK, "success") } // 处理逻辑后 w,r 如:重定向, resp 必须重新处理 diff --git a/server/shopping-cart/internal/types/types.go b/server/shopping-cart/internal/types/types.go index 5d474939..aa61eb09 100644 --- a/server/shopping-cart/internal/types/types.go +++ b/server/shopping-cart/internal/types/types.go @@ -30,8 +30,8 @@ type DeleteCartReq struct { } type ModifyCartPurchaseQuantityReq struct { - Id int64 `json:"id"` //购物车id - Quantity int64 `json:"quantity"` //数量 + Id int64 `json:"id"` //购物车id + PurchaseQuantity int64 `json:"purchase_quantity"` //数量 } type GetCartsReq struct { diff --git a/server_api/shopping-cart.api b/server_api/shopping-cart.api index 5d50db8f..3824f27f 100644 --- a/server_api/shopping-cart.api +++ b/server_api/shopping-cart.api @@ -48,8 +48,8 @@ type DeleteCartReq { } //修改购物车购买数量 type ModifyCartPurchaseQuantityReq { - Id int64 `json:"id"` //购物车id - Quantity int64 `json:"quantity"` //数量 + Id int64 `json:"id"` //购物车id + PurchaseQuantity int64 `json:"purchase_quantity"` //数量 } //获取购物车列表 type GetCartsReq { From 9c178b2add662c1c9110ee2ca47d0853f1780e06 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Thu, 14 Sep 2023 18:33:29 +0800 Subject: [PATCH 09/59] fix --- model/gmodel/fs_shopping_cart_logic.go | 40 +++- .../internal/logic/addtocartlogic.go | 13 +- .../internal/logic/getcartslogic.go | 182 +++++++++++++++++- server/shopping-cart/internal/types/types.go | 10 +- server_api/basic.api | 8 +- server_api/shopping-cart.api | 2 +- utils/shopping_cart/shopping_cart_snapshot.go | 8 +- 7 files changed, 236 insertions(+), 27 deletions(-) diff --git a/model/gmodel/fs_shopping_cart_logic.go b/model/gmodel/fs_shopping_cart_logic.go index d9c3894c..1f508ac9 100644 --- a/model/gmodel/fs_shopping_cart_logic.go +++ b/model/gmodel/fs_shopping_cart_logic.go @@ -55,14 +55,34 @@ func (s *FsShoppingCartModel) GetAllByIds(ctx context.Context, ids []int64, sort } // 获取用户所有的购物车 -func (s *FsShoppingCartModel) GetUserAllCarts(ctx context.Context, userId int64, sort string, fields ...string) (resp []FsShoppingCart, err error) { - db := s.db.WithContext(ctx).Where("user_id = ?", userId) - if len(fields) > 0 { - db = db.Select(fields[0]) - } - if sort != "" { - db = db.Order(sort) - } - err = db.Find(&resp).Error - return resp, err +type GetAllCartsByParamReq struct { + Ids []int64 //id集合 + UserId int64 //用户id + Fields string //筛选的字段 + Sort string //排序 + Page int //当前页 + Limit int //每页数量 +} + +func (s *FsShoppingCartModel) GetAllCartsByParam(ctx context.Context, req GetAllCartsByParamReq) (resp []FsShoppingCart, total int64, err error) { + db := s.db.WithContext(ctx) + if req.UserId > 0 { + db = db.Where("user_id = ?", req.UserId) + } + if len(req.Ids) > 0 { + db = db.Where("id in (?)", req.Ids) + } + if req.Fields != "" { + db = db.Select(req.Fields) + } + if req.Sort != "" { + db = db.Order(req.Sort) + } + //查询数量 + if err = db.Limit(1).Count(&total).Error; err != nil { + return nil, 0, err + } + offset := (req.Page - 1) * req.Limit + err = db.Offset(offset).Limit(req.Limit).Find(&resp).Error + return resp, total, err } diff --git a/server/shopping-cart/internal/logic/addtocartlogic.go b/server/shopping-cart/internal/logic/addtocartlogic.go index f9ef46f3..6194aea9 100644 --- a/server/shopping-cart/internal/logic/addtocartlogic.go +++ b/server/shopping-cart/internal/logic/addtocartlogic.go @@ -53,7 +53,7 @@ func (l *AddToCartLogic) AddToCart(req *types.AddToCartReq, userinfo *auth.UserI return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "sorry,the count of your carts can`t greater than 100") } //获取产品是否存在 - _, err = l.svcCtx.AllModels.FsProduct.FindOne(l.ctx, req.ProductId, "id") + productInfo, err := l.svcCtx.AllModels.FsProduct.FindOne(l.ctx, req.ProductId) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "the product is not exists") @@ -138,6 +138,11 @@ func (l *AddToCartLogic) AddToCart(req *types.AddToCartReq, userinfo *auth.UserI if modelInfo.ModelInfo == nil || *modelInfo.ModelInfo == "" { return resp.SetStatusWithMessage(basic.CodeServiceErr, "the model`s design info is empty") } + var sizeTitleInfo shopping_cart.SizeInfo + if err = json.Unmarshal([]byte(*sizeInfo.Title), &sizeTitleInfo); err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeJsonErr, "failed to parse size info`s title ") + } //快照数据 snapshot := shopping_cart.CartSnapshot{ Logo: req.Logo, @@ -153,8 +158,10 @@ func (l *AddToCartLogic) AddToCart(req *types.AddToCartReq, userinfo *auth.UserI FittingInfo: shopping_cart.FittingInfo{ FittingJson: fittingJson, }, - SizeInfo: shopping_cart.SizeInfo{ - Title: *sizeInfo.Title, + SizeInfo: sizeTitleInfo, + ProductInfo: shopping_cart.ProductInfo{ + ProductName: *productInfo.Title, + ProductSn: *productInfo.Sn, }, UserDiyInformation: shopping_cart.UserDiyInformation{ Phone: req.DiyInfo.Phone, diff --git a/server/shopping-cart/internal/logic/getcartslogic.go b/server/shopping-cart/internal/logic/getcartslogic.go index 097f91b7..a289d151 100644 --- a/server/shopping-cart/internal/logic/getcartslogic.go +++ b/server/shopping-cart/internal/logic/getcartslogic.go @@ -1,8 +1,15 @@ package logic import ( + "encoding/json" + "fusenapi/constants" + "fusenapi/model/gmodel" "fusenapi/utils/auth" "fusenapi/utils/basic" + "fusenapi/utils/hash" + "fusenapi/utils/shopping_cart" + "math" + "strings" "context" @@ -31,12 +38,181 @@ func NewGetCartsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetCarts // } func (l *GetCartsLogic) GetCarts(req *types.GetCartsReq, userinfo *auth.UserInfo) (resp *basic.Response) { - // 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data) - // userinfo 传入值时, 一定不为null - + if req.CurrentPage <= 0 { + req.CurrentPage = constants.DEFAULT_PAGE + } + limit := 10 + //获取用户购物车列表 + carts, total, err := l.svcCtx.AllModels.FsShoppingCart.GetAllCartsByParam(l.ctx, gmodel.GetAllCartsByParamReq{ + UserId: userinfo.UserId, + Fields: "", + Sort: "id DESC", + Page: req.CurrentPage, + Limit: limit, + }) + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "system err:failed to get your shopping carts") + } + if len(carts) == 0 { + return resp.SetStatusWithMessage(basic.CodeOK, "success", types.GetCartsRsp{ + Meta: types.Meta{ + TotalCount: total, + PageCount: int64(math.Ceil(float64(total) / float64(limit))), + CurrentPage: req.CurrentPage, + PerPage: limit, + }, + CartList: nil, + }) + } + lenCarts := len(carts) + templateIds := make([]int64, 0, lenCarts) + modelIds := make([]int64, 0, lenCarts) //模型 + 配件 + sizeIds := make([]int64, 0, lenCarts) + for index := range carts { + templateIds = append(templateIds, *carts[index].TemplateId) + modelIds = append(modelIds, *carts[index].ModelId, *carts[index].FittingId) + sizeIds = append(sizeIds, *carts[index].SizeId) + } + //获取尺寸列表 + sizeList, err := l.svcCtx.AllModels.FsProductSize.GetAllByIds(l.ctx, sizeIds, "") + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get size list") + } + mapSize := make(map[int64]gmodel.FsProductSize) + for _, v := range sizeList { + mapSize[v.Id] = v + } + //获取模型和配件信息 + modelList, err := l.svcCtx.AllModels.FsProductModel3d.GetAllByIds(l.ctx, modelIds, "") + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get model list") + } + mapModel := make(map[int64]gmodel.FsProductModel3d) + for _, v := range modelList { + mapModel[v.Id] = v + } + //获取模板列表 + templateList, err := l.svcCtx.AllModels.FsProductTemplateV2.FindAllByIds(l.ctx, templateIds) + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get template list") + } + mapTemplate := make(map[int64]gmodel.FsProductTemplateV2) + for _, v := range templateList { + mapTemplate[v.Id] = v + } + //定义map收集变更信息 + mapCartChange := make(map[int64]string) + //校验购物车数据是否变更 + err = VerifyShoppingCartSnapshotDataChange(VerifyShoppingCartSnapshotDataChangeReq{ + Carts: carts, + MapSize: mapSize, + MapModel: mapModel, + MapTemplate: mapTemplate, + MapCartChange: mapCartChange, + }) + if err != nil { + logx.Error("VerifyShoppingCartSnapshotDataChange err:", err.Error()) + return resp.SetStatusWithMessage(basic.CodeServiceErr, "system err:failed to check shopping cart change data") + } + //for index return resp.SetStatus(basic.CodeOK) } +// 校验购物车快照数据跟目前是否一致 +type VerifyShoppingCartSnapshotDataChangeReq struct { + Carts []gmodel.FsShoppingCart + MapSize map[int64]gmodel.FsProductSize + MapModel map[int64]gmodel.FsProductModel3d //模型跟配件都在 + MapTemplate map[int64]gmodel.FsProductTemplateV2 + MapCartChange map[int64]string +} +type VerifyShoppingCartSnapshotDataChangeRsp struct { + CartId int64 //有改变的列表下标 + Descrption string //变更描述信息 +} + +func VerifyShoppingCartSnapshotDataChange(req VerifyShoppingCartSnapshotDataChangeReq) error { + for _, cartInfo := range req.Carts { + var snapShotParseInfo shopping_cart.CartSnapshot + if err := json.Unmarshal([]byte(*cartInfo.Snapshot), &snapShotParseInfo); err != nil { + return err + } + //快照中模板设计json数据哈希值 + snapshotTemplateJsonHash := hash.JsonHashKey(snapShotParseInfo.TemplateInfo.TemplateJson) + //快照中模型设计json数据哈希值 + snapshotModelJsonHash := hash.JsonHashKey(snapShotParseInfo.ModelInfo.ModelJson) + //快照中配件设计json数据哈希值 + snapshotFittingJsonHash := hash.JsonHashKey(snapShotParseInfo.FittingInfo.FittingJson) + descrptionBuilder := strings.Builder{} + //有模板验证模板相关 + if *cartInfo.TemplateId > 0 { + if curTemplateInfo, ok := req.MapTemplate[*cartInfo.TemplateId]; !ok { + descrptionBuilder.WriteString("
the template is lose
") + } else { + //当前模板设计json数据哈希值 + curTemplateJsonHash := hash.JsonHashKey(*curTemplateInfo.TemplateInfo) + //模板设计信息改变了 + if snapshotTemplateJsonHash != curTemplateJsonHash { + descrptionBuilder.WriteString("the template design info has changed
") + } + //模板标签改变了 + if snapShotParseInfo.TemplateInfo.TemplateTag != *curTemplateInfo.TemplateTag { + descrptionBuilder.WriteString("the template`s template tag has changed
") + } + } + } + //有模型验证模型相关 + if *cartInfo.ModelId > 0 { + if curModelInfo, ok := req.MapModel[*cartInfo.ModelId]; !ok { //不存在 + descrptionBuilder.WriteString("the model is lose
") + } else { + //当前模型设计json数据哈希值 + curModelJsonHash := hash.JsonHashKey(*curModelInfo.ModelInfo) + if snapshotModelJsonHash != curModelJsonHash { + descrptionBuilder.WriteString("the model design info has changed
") + } + } + } + //有配件验证配件相关 + if *cartInfo.FittingId > 0 { + if curFittingInfo, ok := req.MapModel[*cartInfo.FittingId]; !ok { //不存在 + descrptionBuilder.WriteString("the fitting is lose
") + } else { + //当前配件设计json数据哈希值 + curFittingJsonHash := hash.JsonHashKey(*curFittingInfo.ModelInfo) + if snapshotFittingJsonHash != curFittingJsonHash { + descrptionBuilder.WriteString("the fitting design info has changed
") + } + } + } + //验证尺寸相关 + if *cartInfo.SizeId > 0 { + curSize, ok := req.MapSize[*cartInfo.SizeId] + if !ok { + descrptionBuilder.WriteString("the size is lose
") + } else { + var curSizeTitle shopping_cart.SizeInfo + if err := json.Unmarshal([]byte(*curSize.Title), &curSizeTitle); err != nil { + return err + } + if snapShotParseInfo.SizeInfo.Inch != curSizeTitle.Inch || snapShotParseInfo.SizeInfo.Cm != curSizeTitle.Cm { + descrptionBuilder.WriteString("the size design info has changed
") + } + } + } + //收集错误 + descrption := descrptionBuilder.String() + if descrption != "" { + req.MapCartChange[cartInfo.Id] = descrption + } + } + return nil +} + // 处理逻辑后 w,r 如:重定向, resp 必须重新处理 // func (l *GetCartsLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) { // // httpx.OkJsonCtx(r.Context(), w, resp) diff --git a/server/shopping-cart/internal/types/types.go b/server/shopping-cart/internal/types/types.go index aa61eb09..fc3f605c 100644 --- a/server/shopping-cart/internal/types/types.go +++ b/server/shopping-cart/internal/types/types.go @@ -35,7 +35,7 @@ type ModifyCartPurchaseQuantityReq struct { } type GetCartsReq struct { - Page int `form:"page"` //当前页 + CurrentPage int `form:"current_page"` //当前页 } type GetCartsRsp struct { @@ -99,10 +99,10 @@ type File struct { } type Meta struct { - TotalCount int64 `json:"totalCount"` - PageCount int64 `json:"pageCount"` - CurrentPage int `json:"currentPage"` - PerPage int `json:"perPage"` + TotalCount int64 `json:"total_count"` + PageCount int64 `json:"page_count"` + CurrentPage int `json:"current_page"` + PerPage int `json:"per_page"` } // Set 设置Response的Code和Message值 diff --git a/server_api/basic.api b/server_api/basic.api index 7125abc4..be14515d 100644 --- a/server_api/basic.api +++ b/server_api/basic.api @@ -36,8 +36,8 @@ type File { // 统一分页 type Meta struct { - TotalCount int64 `json:"totalCount"` - PageCount int64 `json:"pageCount"` - CurrentPage int `json:"currentPage"` - PerPage int `json:"perPage"` + TotalCount int64 `json:"total_count"` + PageCount int64 `json:"page_count"` + CurrentPage int `json:"current_page"` + PerPage int `json:"per_page"` } \ No newline at end of file diff --git a/server_api/shopping-cart.api b/server_api/shopping-cart.api index 3824f27f..3f1f19c5 100644 --- a/server_api/shopping-cart.api +++ b/server_api/shopping-cart.api @@ -53,7 +53,7 @@ type ModifyCartPurchaseQuantityReq { } //获取购物车列表 type GetCartsReq { - Page int `form:"page"` //当前页 + CurrentPage int `form:"current_page"` //当前页 } type GetCartsRsp { Meta Meta `json:"meta"` //分页信息 diff --git a/utils/shopping_cart/shopping_cart_snapshot.go b/utils/shopping_cart/shopping_cart_snapshot.go index 30705c06..b0ab5797 100644 --- a/utils/shopping_cart/shopping_cart_snapshot.go +++ b/utils/shopping_cart/shopping_cart_snapshot.go @@ -9,8 +9,13 @@ type CartSnapshot struct { ModelInfo ModelInfo `json:"model_info"` //模型的数据 FittingInfo FittingInfo `json:"fitting_info"` //配件信息 SizeInfo SizeInfo `json:"size_info"` //尺寸基本信息 + ProductInfo ProductInfo `json:"product_info"` //产品基本信息(只记录不要使用) UserDiyInformation UserDiyInformation `json:"user_diy_information"` //用户diy数据 } +type ProductInfo struct { + ProductName string `json:"product_name"` + ProductSn string `json:"product_sn"` +} type ModelInfo struct { ModelJson string `json:"model_json"` //模型设计json数据 } @@ -22,7 +27,8 @@ type TemplateInfo struct { TemplateTag string `json:"template_tag"` //模板标签 } type SizeInfo struct { - Title string `json:"title"` //尺寸信息 + Inch string `json:"inch"` + Cm string `json:"cm"` } type UserDiyInformation struct { Phone string `json:"phone"` //电话 From 440dd1cefca6960ffd0beb0817642fa350843f57 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Thu, 14 Sep 2023 18:40:37 +0800 Subject: [PATCH 10/59] fix --- server/shopping-cart/internal/logic/getcartslogic.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/server/shopping-cart/internal/logic/getcartslogic.go b/server/shopping-cart/internal/logic/getcartslogic.go index a289d151..f28304c1 100644 --- a/server/shopping-cart/internal/logic/getcartslogic.go +++ b/server/shopping-cart/internal/logic/getcartslogic.go @@ -118,7 +118,10 @@ func (l *GetCartsLogic) GetCarts(req *types.GetCartsReq, userinfo *auth.UserInfo logx.Error("VerifyShoppingCartSnapshotDataChange err:", err.Error()) return resp.SetStatusWithMessage(basic.CodeServiceErr, "system err:failed to check shopping cart change data") } - //for index + /*list := make([]types.CartItem, 0, lenCarts) + for index := range carts { + + }*/ return resp.SetStatus(basic.CodeOK) } From 6606173050420d1ec0f97f2608571dfc20536f22 Mon Sep 17 00:00:00 2001 From: momo <1012651275@qq.com> Date: Thu, 14 Sep 2023 18:43:10 +0800 Subject: [PATCH 11/59] =?UTF-8?q?feat:=E6=96=B0=E5=A2=9Eapi?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../fs_cloud_deliver_every_tmp_old_gen.go | 23 + .../fs_cloud_deliver_every_tmp_old_logic.go | 2 + model/gmodel/fs_cloud_deliver_tmp_old_gen.go | 28 + .../gmodel/fs_cloud_deliver_tmp_old_logic.go | 2 + model/gmodel/fs_cloud_old_gen.go | 20 + model/gmodel/fs_cloud_old_logic.go | 2 + .../gmodel/fs_cloud_pick_up_detail_old_gen.go | 23 + .../fs_cloud_pick_up_detail_old_logic.go | 2 + model/gmodel/fs_cloud_pick_up_old_gen.go | 28 + model/gmodel/fs_cloud_pick_up_old_logic.go | 2 + .../gmodel/fs_cloud_receive_every_old_gen.go | 22 + .../fs_cloud_receive_every_old_logic.go | 2 + model/gmodel/fs_cloud_receive_old_gen.go | 26 + model/gmodel/fs_cloud_receive_old_logic.go | 2 + model/gmodel/fs_cloud_render_log_old_gen.go | 26 + model/gmodel/fs_cloud_render_log_old_logic.go | 2 + .../fs_cloud_user_apply_back_old_gen.go | 25 + .../fs_cloud_user_apply_back_old_logic.go | 2 + model/gmodel/fs_order_affiliate_old_gen.go | 27 + model/gmodel/fs_order_affiliate_old_logic.go | 2 + model/gmodel/fs_order_detail_old_gen.go | 41 ++ model/gmodel/fs_order_detail_old_logic.go | 2 + .../fs_order_detail_template_old_gen.go | 28 + .../fs_order_detail_template_old_logic.go | 2 + model/gmodel/fs_order_gen.go | 47 +- model/gmodel/fs_order_old_gen.go | 54 ++ model/gmodel/fs_order_old_logic.go | 2 + model/gmodel/fs_order_remark_old_gen.go | 22 + model/gmodel/fs_order_remark_old_logic.go | 2 + model/gmodel/fs_order_trade_event_gen.go | 25 + model/gmodel/fs_order_trade_event_logic.go | 2 + model/gmodel/fs_order_trade_gen.go | 36 ++ model/gmodel/fs_order_trade_logic.go | 2 + model/gmodel/fs_shopping_cart_gen.go | 2 - model/gmodel/var_gen.go | 62 +- .../internal/logic/usercontactservicelogic.go | 61 +- .../internal/logic/useroderdeletelogic.go | 184 +++--- .../internal/logic/userordercancellogic.go | 170 +++--- .../internal/logic/userorderdeletelogic.go | 58 +- .../internal/logic/userorderlistlogic.go | 474 +++++++-------- .../internal/logic/orderpaymentintentlogic.go | 250 ++++---- .../pay/internal/logic/stripewebhooklogic.go | 566 +++++++++--------- .../logic/getlastproductdesignlogic.go | 113 ++-- .../internal/logic/getpricebypidlogic.go | 3 +- .../internal/logic/getproductinfologic.go | 117 ++-- .../logic/getrendersettingbypidlogic.go | 50 +- server_api/basic.api | 183 +++++- server_api/orders.api | 217 +++++++ 48 files changed, 1929 insertions(+), 1114 deletions(-) create mode 100644 model/gmodel/fs_cloud_deliver_every_tmp_old_gen.go create mode 100644 model/gmodel/fs_cloud_deliver_every_tmp_old_logic.go create mode 100644 model/gmodel/fs_cloud_deliver_tmp_old_gen.go create mode 100644 model/gmodel/fs_cloud_deliver_tmp_old_logic.go create mode 100644 model/gmodel/fs_cloud_old_gen.go create mode 100644 model/gmodel/fs_cloud_old_logic.go create mode 100644 model/gmodel/fs_cloud_pick_up_detail_old_gen.go create mode 100644 model/gmodel/fs_cloud_pick_up_detail_old_logic.go create mode 100644 model/gmodel/fs_cloud_pick_up_old_gen.go create mode 100644 model/gmodel/fs_cloud_pick_up_old_logic.go create mode 100644 model/gmodel/fs_cloud_receive_every_old_gen.go create mode 100644 model/gmodel/fs_cloud_receive_every_old_logic.go create mode 100644 model/gmodel/fs_cloud_receive_old_gen.go create mode 100644 model/gmodel/fs_cloud_receive_old_logic.go create mode 100644 model/gmodel/fs_cloud_render_log_old_gen.go create mode 100644 model/gmodel/fs_cloud_render_log_old_logic.go create mode 100644 model/gmodel/fs_cloud_user_apply_back_old_gen.go create mode 100644 model/gmodel/fs_cloud_user_apply_back_old_logic.go create mode 100644 model/gmodel/fs_order_affiliate_old_gen.go create mode 100644 model/gmodel/fs_order_affiliate_old_logic.go create mode 100644 model/gmodel/fs_order_detail_old_gen.go create mode 100644 model/gmodel/fs_order_detail_old_logic.go create mode 100644 model/gmodel/fs_order_detail_template_old_gen.go create mode 100644 model/gmodel/fs_order_detail_template_old_logic.go create mode 100644 model/gmodel/fs_order_old_gen.go create mode 100644 model/gmodel/fs_order_old_logic.go create mode 100644 model/gmodel/fs_order_remark_old_gen.go create mode 100644 model/gmodel/fs_order_remark_old_logic.go create mode 100644 model/gmodel/fs_order_trade_event_gen.go create mode 100644 model/gmodel/fs_order_trade_event_logic.go create mode 100644 model/gmodel/fs_order_trade_gen.go create mode 100644 model/gmodel/fs_order_trade_logic.go create mode 100644 server_api/orders.api diff --git a/model/gmodel/fs_cloud_deliver_every_tmp_old_gen.go b/model/gmodel/fs_cloud_deliver_every_tmp_old_gen.go new file mode 100644 index 00000000..3fd8ba80 --- /dev/null +++ b/model/gmodel/fs_cloud_deliver_every_tmp_old_gen.go @@ -0,0 +1,23 @@ +package gmodel + +import ( + "gorm.io/gorm" +) + +// fs_cloud_deliver_every_tmp_old +type FsCloudDeliverEveryTmpOld struct { + Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // + AdminId *int64 `gorm:"default:0;" json:"admin_id"` // 管理员 + CloudId *int64 `gorm:"default:0;" json:"cloud_id"` // 云仓ID 暂且只有一个默认为 1 + OrderDetailTemplateSn *string `gorm:"default:'';" json:"order_detail_template_sn"` // + Num *int64 `gorm:"default:0;" json:"num"` // 发货数量 + Ctime *int64 `gorm:"default:0;" json:"ctime"` // 添加时间 +} +type FsCloudDeliverEveryTmpOldModel struct { + db *gorm.DB + name string +} + +func NewFsCloudDeliverEveryTmpOldModel(db *gorm.DB) *FsCloudDeliverEveryTmpOldModel { + return &FsCloudDeliverEveryTmpOldModel{db: db, name: "fs_cloud_deliver_every_tmp_old"} +} diff --git a/model/gmodel/fs_cloud_deliver_every_tmp_old_logic.go b/model/gmodel/fs_cloud_deliver_every_tmp_old_logic.go new file mode 100644 index 00000000..e68225aa --- /dev/null +++ b/model/gmodel/fs_cloud_deliver_every_tmp_old_logic.go @@ -0,0 +1,2 @@ +package gmodel +// TODO: 使用model的属性做你想做的 \ No newline at end of file diff --git a/model/gmodel/fs_cloud_deliver_tmp_old_gen.go b/model/gmodel/fs_cloud_deliver_tmp_old_gen.go new file mode 100644 index 00000000..a7711947 --- /dev/null +++ b/model/gmodel/fs_cloud_deliver_tmp_old_gen.go @@ -0,0 +1,28 @@ +package gmodel + +import ( + "gorm.io/gorm" +) + +// fs_cloud_deliver_tmp_old +type FsCloudDeliverTmpOld struct { + Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // id + CloudId *int64 `gorm:"default:0;" json:"cloud_id"` // 云仓id + UserId *int64 `gorm:"default:0;" json:"user_id"` // 用户id + AdminId *int64 `gorm:"default:0;" json:"admin_id"` // 操作员id + DeliveryType *int64 `gorm:"default:1;" json:"delivery_type"` // 发货公司 之后配置,默认1 + Fee *int64 `gorm:"default:0;" json:"fee"` // 价格 + AddressId *int64 `gorm:"default:0;" json:"address_id"` // 地址 + Ctime *int64 `gorm:"default:0;" json:"ctime"` // 创建时间 + IsDeliver *int64 `gorm:"default:0;" json:"is_deliver"` // 0未发货,1已发货 + IsEnd *int64 `gorm:"default:0;" json:"is_end"` // 0未完成,1已完成 + DeliverId *int64 `gorm:"default:0;" json:"deliver_id"` // 发货总表id +} +type FsCloudDeliverTmpOldModel struct { + db *gorm.DB + name string +} + +func NewFsCloudDeliverTmpOldModel(db *gorm.DB) *FsCloudDeliverTmpOldModel { + return &FsCloudDeliverTmpOldModel{db: db, name: "fs_cloud_deliver_tmp_old"} +} diff --git a/model/gmodel/fs_cloud_deliver_tmp_old_logic.go b/model/gmodel/fs_cloud_deliver_tmp_old_logic.go new file mode 100644 index 00000000..e68225aa --- /dev/null +++ b/model/gmodel/fs_cloud_deliver_tmp_old_logic.go @@ -0,0 +1,2 @@ +package gmodel +// TODO: 使用model的属性做你想做的 \ No newline at end of file diff --git a/model/gmodel/fs_cloud_old_gen.go b/model/gmodel/fs_cloud_old_gen.go new file mode 100644 index 00000000..8048d159 --- /dev/null +++ b/model/gmodel/fs_cloud_old_gen.go @@ -0,0 +1,20 @@ +package gmodel + +import ( + "gorm.io/gorm" +) + +// fs_cloud_old 云仓表 +type FsCloudOld struct { + Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // id + Address *string `gorm:"default:'';" json:"address"` // 云仓地址 + Title *string `gorm:"default:'';" json:"title"` // 云仓名称 +} +type FsCloudOldModel struct { + db *gorm.DB + name string +} + +func NewFsCloudOldModel(db *gorm.DB) *FsCloudOldModel { + return &FsCloudOldModel{db: db, name: "fs_cloud_old"} +} diff --git a/model/gmodel/fs_cloud_old_logic.go b/model/gmodel/fs_cloud_old_logic.go new file mode 100644 index 00000000..e68225aa --- /dev/null +++ b/model/gmodel/fs_cloud_old_logic.go @@ -0,0 +1,2 @@ +package gmodel +// TODO: 使用model的属性做你想做的 \ No newline at end of file diff --git a/model/gmodel/fs_cloud_pick_up_detail_old_gen.go b/model/gmodel/fs_cloud_pick_up_detail_old_gen.go new file mode 100644 index 00000000..c891ce19 --- /dev/null +++ b/model/gmodel/fs_cloud_pick_up_detail_old_gen.go @@ -0,0 +1,23 @@ +package gmodel + +import ( + "gorm.io/gorm" +) + +// fs_cloud_pick_up_detail_old 云仓提货单-详情 +type FsCloudPickUpDetailOld struct { + Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // Id + PickId *int64 `gorm:"index;default:0;" json:"pick_id"` // 提货单id + StockId *int64 `gorm:"default:0;" json:"stock_id"` // 用户云仓记录id + Num *int64 `gorm:"default:0;" json:"num"` // 提取数量 + Boxes *int64 `gorm:"default:0;" json:"boxes"` // 提取箱数 + Ctime *int64 `gorm:"default:0;" json:"ctime"` // 添加时间 +} +type FsCloudPickUpDetailOldModel struct { + db *gorm.DB + name string +} + +func NewFsCloudPickUpDetailOldModel(db *gorm.DB) *FsCloudPickUpDetailOldModel { + return &FsCloudPickUpDetailOldModel{db: db, name: "fs_cloud_pick_up_detail_old"} +} diff --git a/model/gmodel/fs_cloud_pick_up_detail_old_logic.go b/model/gmodel/fs_cloud_pick_up_detail_old_logic.go new file mode 100644 index 00000000..e68225aa --- /dev/null +++ b/model/gmodel/fs_cloud_pick_up_detail_old_logic.go @@ -0,0 +1,2 @@ +package gmodel +// TODO: 使用model的属性做你想做的 \ No newline at end of file diff --git a/model/gmodel/fs_cloud_pick_up_old_gen.go b/model/gmodel/fs_cloud_pick_up_old_gen.go new file mode 100644 index 00000000..68f2b758 --- /dev/null +++ b/model/gmodel/fs_cloud_pick_up_old_gen.go @@ -0,0 +1,28 @@ +package gmodel + +import ( + "gorm.io/gorm" +) + +// fs_cloud_pick_up_old 云仓提货单 +type FsCloudPickUpOld struct { + Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // Id + UserId *int64 `gorm:"index;default:0;" json:"user_id"` // 用户id + TrackNum *string `gorm:"default:'';" json:"track_num"` // 运输号 + AddressId *int64 `gorm:"default:0;" json:"address_id"` // 地址id + AddressInfo *string `gorm:"default:'';" json:"address_info"` // 地址信息 json + Status *int64 `gorm:"default:0;" json:"status"` // 运输状态 1 draw 2shipping 3ups 4arrival + Ctime *int64 `gorm:"default:0;" json:"ctime"` // 添加时间 + ShippingTime *int64 `gorm:"default:0;" json:"shipping_time"` // 发货时间 + UpsTime *int64 `gorm:"default:0;" json:"ups_time"` // 提货时间 + ArrivalTime *int64 `gorm:"default:0;" json:"arrival_time"` // 到达时间 + UpsSn *string `gorm:"default:'';" json:"ups_sn"` // 运输单号 +} +type FsCloudPickUpOldModel struct { + db *gorm.DB + name string +} + +func NewFsCloudPickUpOldModel(db *gorm.DB) *FsCloudPickUpOldModel { + return &FsCloudPickUpOldModel{db: db, name: "fs_cloud_pick_up_old"} +} diff --git a/model/gmodel/fs_cloud_pick_up_old_logic.go b/model/gmodel/fs_cloud_pick_up_old_logic.go new file mode 100644 index 00000000..e68225aa --- /dev/null +++ b/model/gmodel/fs_cloud_pick_up_old_logic.go @@ -0,0 +1,2 @@ +package gmodel +// TODO: 使用model的属性做你想做的 \ No newline at end of file diff --git a/model/gmodel/fs_cloud_receive_every_old_gen.go b/model/gmodel/fs_cloud_receive_every_old_gen.go new file mode 100644 index 00000000..436f9037 --- /dev/null +++ b/model/gmodel/fs_cloud_receive_every_old_gen.go @@ -0,0 +1,22 @@ +package gmodel + +import ( + "gorm.io/gorm" +) + +// fs_cloud_receive_every_old +type FsCloudReceiveEveryOld struct { + Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // + DeliveryId *int64 `gorm:"index;default:0;" json:"delivery_id"` // 云仓收货单id + OrderDetailTemplateSn *string `gorm:"index;default:'';" json:"order_detail_template_sn"` // + Num *int64 `gorm:"default:0;" json:"num"` // 收到的数量 + Ctime *int64 `gorm:"default:0;" json:"ctime"` // 添加时间 +} +type FsCloudReceiveEveryOldModel struct { + db *gorm.DB + name string +} + +func NewFsCloudReceiveEveryOldModel(db *gorm.DB) *FsCloudReceiveEveryOldModel { + return &FsCloudReceiveEveryOldModel{db: db, name: "fs_cloud_receive_every_old"} +} diff --git a/model/gmodel/fs_cloud_receive_every_old_logic.go b/model/gmodel/fs_cloud_receive_every_old_logic.go new file mode 100644 index 00000000..e68225aa --- /dev/null +++ b/model/gmodel/fs_cloud_receive_every_old_logic.go @@ -0,0 +1,2 @@ +package gmodel +// TODO: 使用model的属性做你想做的 \ No newline at end of file diff --git a/model/gmodel/fs_cloud_receive_old_gen.go b/model/gmodel/fs_cloud_receive_old_gen.go new file mode 100644 index 00000000..224d29f6 --- /dev/null +++ b/model/gmodel/fs_cloud_receive_old_gen.go @@ -0,0 +1,26 @@ +package gmodel + +import ( + "gorm.io/gorm" +) + +// fs_cloud_receive_old 云仓接收工厂总单 +type FsCloudReceiveOld struct { + Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // + CloudId *int64 `gorm:"index;default:0;" json:"cloud_id"` // 入库云仓id + AdminId *int64 `gorm:"index;default:0;" json:"admin_id"` // 操作员id + UserId *int64 `gorm:"index;default:0;" json:"user_id"` // 用户id + OrderId *int64 `gorm:"index;default:0;" json:"order_id"` // 入库云仓的订单 + Fee *int64 `gorm:"default:0;" json:"fee"` // 运费 + Delivery *string `gorm:"default:'';" json:"delivery"` // + Ctime *int64 `gorm:"default:0;" json:"ctime"` // 创建时间 + Status *int64 `gorm:"default:0;" json:"status"` // 0未收到 1收到 +} +type FsCloudReceiveOldModel struct { + db *gorm.DB + name string +} + +func NewFsCloudReceiveOldModel(db *gorm.DB) *FsCloudReceiveOldModel { + return &FsCloudReceiveOldModel{db: db, name: "fs_cloud_receive_old"} +} diff --git a/model/gmodel/fs_cloud_receive_old_logic.go b/model/gmodel/fs_cloud_receive_old_logic.go new file mode 100644 index 00000000..e68225aa --- /dev/null +++ b/model/gmodel/fs_cloud_receive_old_logic.go @@ -0,0 +1,2 @@ +package gmodel +// TODO: 使用model的属性做你想做的 \ No newline at end of file diff --git a/model/gmodel/fs_cloud_render_log_old_gen.go b/model/gmodel/fs_cloud_render_log_old_gen.go new file mode 100644 index 00000000..3abb9c33 --- /dev/null +++ b/model/gmodel/fs_cloud_render_log_old_gen.go @@ -0,0 +1,26 @@ +package gmodel + +import ( + "gorm.io/gorm" +) + +// fs_cloud_render_log_old 云渲染日志表 +type FsCloudRenderLogOld struct { + Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // ID + UserId *int64 `gorm:"default:0;" json:"user_id"` // 用户id + PostData *string `gorm:"default:'';" json:"post_data"` // + PostUrl *string `gorm:"default:'';" json:"post_url"` // + Title *string `gorm:"index;default:'';" json:"title"` // + Time *int64 `gorm:"default:0;" json:"time"` // 所用时间 + Result *string `gorm:"default:'';" json:"result"` // + Tag *string `gorm:"index;default:'';" json:"tag"` // 标识 + Ctime *int64 `gorm:"default:0;" json:"ctime"` // 添加时间 +} +type FsCloudRenderLogOldModel struct { + db *gorm.DB + name string +} + +func NewFsCloudRenderLogOldModel(db *gorm.DB) *FsCloudRenderLogOldModel { + return &FsCloudRenderLogOldModel{db: db, name: "fs_cloud_render_log_old"} +} diff --git a/model/gmodel/fs_cloud_render_log_old_logic.go b/model/gmodel/fs_cloud_render_log_old_logic.go new file mode 100644 index 00000000..e68225aa --- /dev/null +++ b/model/gmodel/fs_cloud_render_log_old_logic.go @@ -0,0 +1,2 @@ +package gmodel +// TODO: 使用model的属性做你想做的 \ No newline at end of file diff --git a/model/gmodel/fs_cloud_user_apply_back_old_gen.go b/model/gmodel/fs_cloud_user_apply_back_old_gen.go new file mode 100644 index 00000000..9c7f2dd7 --- /dev/null +++ b/model/gmodel/fs_cloud_user_apply_back_old_gen.go @@ -0,0 +1,25 @@ +package gmodel + +import ( + "gorm.io/gorm" +) + +// fs_cloud_user_apply_back_old 该表废弃 +type FsCloudUserApplyBackOld struct { + Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // + UserHash *string `gorm:"default:'';" json:"user_hash"` // + OrderDetailTemplateId *int64 `gorm:"default:0;" json:"order_detail_template_id"` // 详情modelID + Num *int64 `gorm:"default:0;" json:"num"` // 发货数量 + AddressTo *string `gorm:"default:'';" json:"address_to"` // 收获地址 + Ctime *int64 `gorm:"default:0;" json:"ctime"` // 添加时间 + StorageFee *int64 `gorm:"default:0;" json:"storage_fee"` // 存储费用 + Status *int64 `gorm:"default:0;" json:"status"` // 状态位 是否已发货 是否处理 是否删除 是否推送 +} +type FsCloudUserApplyBackOldModel struct { + db *gorm.DB + name string +} + +func NewFsCloudUserApplyBackOldModel(db *gorm.DB) *FsCloudUserApplyBackOldModel { + return &FsCloudUserApplyBackOldModel{db: db, name: "fs_cloud_user_apply_back_old"} +} diff --git a/model/gmodel/fs_cloud_user_apply_back_old_logic.go b/model/gmodel/fs_cloud_user_apply_back_old_logic.go new file mode 100644 index 00000000..e68225aa --- /dev/null +++ b/model/gmodel/fs_cloud_user_apply_back_old_logic.go @@ -0,0 +1,2 @@ +package gmodel +// TODO: 使用model的属性做你想做的 \ No newline at end of file diff --git a/model/gmodel/fs_order_affiliate_old_gen.go b/model/gmodel/fs_order_affiliate_old_gen.go new file mode 100644 index 00000000..4149fe3f --- /dev/null +++ b/model/gmodel/fs_order_affiliate_old_gen.go @@ -0,0 +1,27 @@ +package gmodel + +import ( + "gorm.io/gorm" +) + +// fs_order_affiliate_old 订单附属表-流程控制时间等 +type FsOrderAffiliateOld struct { + Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // id + OrderId *int64 `gorm:"unique_key;default:0;" json:"order_id"` // 订单id + SureTime *int64 `gorm:"default:0;" json:"sure_time"` // 确认时间 + ProductTime *int64 `gorm:"default:0;" json:"product_time"` // 生产时间 + ProductEndtime *int64 `gorm:"default:0;" json:"product_endtime"` // 生成完成时间 + DeliverTime *int64 `gorm:"default:0;" json:"deliver_time"` // 发货时间 + UpsDeliverTime *int64 `gorm:"default:0;" json:"ups_deliver_time"` // ups发货时间 + UpsTime *int64 `gorm:"default:0;" json:"ups_time"` // UPS提货时间 + ArrivalTime *int64 `gorm:"default:0;" json:"arrival_time"` // 到达云仓的时间 + RecevieTime *int64 `gorm:"default:0;" json:"recevie_time"` // 云仓收货时间 +} +type FsOrderAffiliateOldModel struct { + db *gorm.DB + name string +} + +func NewFsOrderAffiliateOldModel(db *gorm.DB) *FsOrderAffiliateOldModel { + return &FsOrderAffiliateOldModel{db: db, name: "fs_order_affiliate_old"} +} diff --git a/model/gmodel/fs_order_affiliate_old_logic.go b/model/gmodel/fs_order_affiliate_old_logic.go new file mode 100644 index 00000000..e68225aa --- /dev/null +++ b/model/gmodel/fs_order_affiliate_old_logic.go @@ -0,0 +1,2 @@ +package gmodel +// TODO: 使用model的属性做你想做的 \ No newline at end of file diff --git a/model/gmodel/fs_order_detail_old_gen.go b/model/gmodel/fs_order_detail_old_gen.go new file mode 100644 index 00000000..afc7c20f --- /dev/null +++ b/model/gmodel/fs_order_detail_old_gen.go @@ -0,0 +1,41 @@ +package gmodel + +import ( + "gorm.io/gorm" +) + +// fs_order_detail_old 订单详细表 +type FsOrderDetailOld struct { + Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // + Sn *string `gorm:"unique_key;default:'';" json:"sn"` // 唯一编码 + OrderId *int64 `gorm:"index;default:0;" json:"order_id"` // 订单ID + UserId *int64 `gorm:"default:0;" json:"user_id"` // 用户ID + FactoryId *int64 `gorm:"default:0;" json:"factory_id"` // 工厂ID + OrderDetailTemplateId *int64 `gorm:"default:0;" json:"order_detail_template_id"` // 详情templateID + ProductId *int64 `gorm:"default:0;" json:"product_id"` // 产品ID + BuyNum *int64 `gorm:"default:0;" json:"buy_num"` // 购买数量 + PushNum *int64 `gorm:"default:0;" json:"push_num"` // 已发数量 + Amount *int64 `gorm:"default:0;" json:"amount"` // 单价 + Cover *string `gorm:"default:'';" json:"cover"` // 截图 + Ctime *int64 `gorm:"default:0;" json:"ctime"` // 添加时间 + Status *int64 `gorm:"default:0;" json:"status"` // 状态位 是否推送到厂家 是否生产完成 是否发货完成 + OptionalId *int64 `gorm:"default:0;" json:"optional_id"` // 选项ID + OptionalTitle *string `gorm:"default:'';" json:"optional_title"` // 选项名称 + OptionPrice *int64 `gorm:"default:0;" json:"option_price"` // 配件价格 + IsTofactory *int64 `gorm:"default:0;" json:"is_tofactory"` // 是否推送到工厂 + IsProduct *int64 `gorm:"default:0;" json:"is_product"` // 是否生产中 + IsProductCompletion *int64 `gorm:"default:0;" json:"is_product_completion"` // 是否生产完成 + IsCloud *int64 `gorm:"default:0;" json:"is_cloud"` // 是否是云仓订单 + IsTocloud *int64 `gorm:"default:0;" json:"is_tocloud"` // 是否已发云仓(云仓单要发货到云仓,直接发到用户的不需要发到云仓) + IsDeliver *int64 `gorm:"default:0;" json:"is_deliver"` // 是否已发货 + IsEnd *int64 `gorm:"default:0;" json:"is_end"` // 是否完成订单(签收) + CartId *int64 `gorm:"index;default:0;" json:"cart_id"` // 购物车编号 +} +type FsOrderDetailOldModel struct { + db *gorm.DB + name string +} + +func NewFsOrderDetailOldModel(db *gorm.DB) *FsOrderDetailOldModel { + return &FsOrderDetailOldModel{db: db, name: "fs_order_detail_old"} +} diff --git a/model/gmodel/fs_order_detail_old_logic.go b/model/gmodel/fs_order_detail_old_logic.go new file mode 100644 index 00000000..e68225aa --- /dev/null +++ b/model/gmodel/fs_order_detail_old_logic.go @@ -0,0 +1,2 @@ +package gmodel +// TODO: 使用model的属性做你想做的 \ No newline at end of file diff --git a/model/gmodel/fs_order_detail_template_old_gen.go b/model/gmodel/fs_order_detail_template_old_gen.go new file mode 100644 index 00000000..36f74646 --- /dev/null +++ b/model/gmodel/fs_order_detail_template_old_gen.go @@ -0,0 +1,28 @@ +package gmodel + +import ( + "gorm.io/gorm" +) + +// fs_order_detail_template_old 订单模板详细表 +type FsOrderDetailTemplateOld struct { + Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // + Sn *string `gorm:"unique_key;default:'';" json:"sn"` // 唯一编码 + ProductId *int64 `gorm:"index;default:0;" json:"product_id"` // 产品ID + ModelId *int64 `gorm:"default:0;" json:"model_id"` // 模型ID + TemplateId *int64 `gorm:"index;default:0;" json:"template_id"` // 模板ID + MaterialId *int64 `gorm:"index;default:0;" json:"material_id"` // 材质id + SizeId *int64 `gorm:"index;default:0;" json:"size_id"` // 尺寸id + EachBoxNum *int64 `gorm:"default:0;" json:"each_box_num"` // 每一箱的个数 + EachBoxWeight *float64 `gorm:"default:0.00;" json:"each_box_weight"` // 每一箱的重量 单位KG + DesignId *int64 `gorm:"index;default:0;" json:"design_id"` // 设计ID + Ctime *int64 `gorm:"default:0;" json:"ctime"` // 添加时间 +} +type FsOrderDetailTemplateOldModel struct { + db *gorm.DB + name string +} + +func NewFsOrderDetailTemplateOldModel(db *gorm.DB) *FsOrderDetailTemplateOldModel { + return &FsOrderDetailTemplateOldModel{db: db, name: "fs_order_detail_template_old"} +} diff --git a/model/gmodel/fs_order_detail_template_old_logic.go b/model/gmodel/fs_order_detail_template_old_logic.go new file mode 100644 index 00000000..e68225aa --- /dev/null +++ b/model/gmodel/fs_order_detail_template_old_logic.go @@ -0,0 +1,2 @@ +package gmodel +// TODO: 使用model的属性做你想做的 \ No newline at end of file diff --git a/model/gmodel/fs_order_gen.go b/model/gmodel/fs_order_gen.go index ab34b331..66bdd701 100644 --- a/model/gmodel/fs_order_gen.go +++ b/model/gmodel/fs_order_gen.go @@ -5,44 +5,17 @@ import ( "time" ) -// fs_order +// fs_order 订单表 type FsOrder struct { - Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // - Sn *string `gorm:"unique_key;default:'';" json:"sn"` // 订单编号 FS211224OL2XDKNP - UserId *int64 `gorm:"index;default:0;" json:"user_id"` // 用户ID - SellerUserId *int64 `gorm:"default:0;" json:"seller_user_id"` // 销售员ID 0:自主下单 - TotalAmount *int64 `gorm:"default:0;" json:"total_amount"` // 总价 - PayedAmount *int64 `gorm:"default:0;" json:"payed_amount"` // 已支付金额 - PayMethod *int64 `gorm:"default:0;" json:"pay_method"` // 支付方式 1paypal 2strip - Ctime *int64 `gorm:"default:0;" json:"ctime"` // 添加时间 - Utime *int64 `gorm:"default:0;" json:"utime"` // 更新时间 - Ptime *int64 `gorm:"default:0;" json:"ptime"` // 最后一次 支付时间(可能多次支付) - AddressId *int64 `gorm:"index;default:0;" json:"address_id"` // 地址ID或者云仓ID - DeliveryMethod *int64 `gorm:"default:0;" json:"delivery_method"` // 配送方式 1:直接发货到收获地址 2:云仓 - CustomerMark *string `gorm:"default:'';" json:"customer_mark"` // 客户备注 - Mark *string `gorm:"default:'';" json:"mark"` // 后台订单备注 - AddressInfo *string `gorm:"default:'';" json:"address_info"` // 详细地址信息JSON - IsSup *int64 `gorm:"default:0;" json:"is_sup"` // 0不是补货 1是补货 - Status *int64 `gorm:"default:0;" json:"status"` // 状态位(0:未支付,1:部分支付,2:支付完成,3:部分生产,4:部分生产完成,5:全部生产,6:全部生产完成,7:部分发货,8:发货完成,9:完成订单,10:取消订单,11:退款中,12:退款完成,13:订单已删除,14:订单已关闭) - IsPartPay *int64 `gorm:"default:0;" json:"is_part_pay"` // 是否部分支付(0:否,1:是) - IsPayCompleted *int64 `gorm:"default:0;" json:"is_pay_completed"` // 是否支付完成(0:否,1:是) - IsPartProduct *int64 `gorm:"default:0;" json:"is_part_product"` // 是否部分生产(0:否,1:是) - IsPartProductCompleted *int64 `gorm:"default:0;" json:"is_part_product_completed"` // 是否部分生产完成(0:否,1:是) - IsAllProduct *int64 `gorm:"default:0;" json:"is_all_product"` // 是否全部生产(0:否,1:是) - IsAllProductCompleted *int64 `gorm:"default:0;" json:"is_all_product_completed"` // 是否全部生产完成(0:否,1:是) - IsPartDelivery *int64 `gorm:"default:0;" json:"is_part_delivery"` // 是否部分发货(0:否,1:是) - IsDeliveryCompleted *int64 `gorm:"default:0;" json:"is_delivery_completed"` // 是否发货完成(0:否,1:是) - IsComplated *int64 `gorm:"default:0;" json:"is_complated"` // 是否完成订单(0:否,1:是) - IsCancel *int64 `gorm:"default:0;" json:"is_cancel"` // 是否取消订单(0:否,1:是) - IsRefunding *int64 `gorm:"default:0;" json:"is_refunding"` // 是否退款中(0:否,1:是) - IsRefunded *int64 `gorm:"default:0;" json:"is_refunded"` // 是否退款完成(0:否,1:是) - IsDeleted *int64 `gorm:"default:0;" json:"is_deleted"` // 是否删除(0:否,1:是) - RefundReasonId *int64 `gorm:"default:0;" json:"refund_reason_id"` // 取消订单原因ID - RefundReason *string `gorm:"default:'';" json:"refund_reason"` // 取消订单原因 - TsTime *time.Time `gorm:"default:'0000-00-00 00:00:00';" json:"ts_time"` // - IsSure *int64 `gorm:"default:0;" json:"is_sure"` // 是否确认订单 1确认0未确认 - DeliverSn *string `gorm:"default:'';" json:"deliver_sn"` // 发货单号 - EmailTime *int64 `gorm:"default:0;" json:"email_time"` // 邮件发送时间 + Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // 订单ID + UserId *int64 `gorm:"index;default:0;" json:"user_id"` // 用户ID + DeliveryMethod *int64 `gorm:"index;default:0;" json:"delivery_method"` // 物流类型 + OrderNo *string `gorm:"index;default:'';" json:"order_no"` // + OrderSource *string `gorm:"default:'';" json:"order_source"` // + Status *int64 `gorm:"index;default:0;" json:"status"` // 订单状态 + Metadata *[]byte `gorm:"default:'';" json:"metadata"` // + Ctime *time.Time `gorm:"default:'0000-00-00 00:00:00';" json:"ctime"` // + Utime *time.Time `gorm:"default:'0000-00-00 00:00:00';" json:"utime"` // } type FsOrderModel struct { db *gorm.DB diff --git a/model/gmodel/fs_order_old_gen.go b/model/gmodel/fs_order_old_gen.go new file mode 100644 index 00000000..20e573ec --- /dev/null +++ b/model/gmodel/fs_order_old_gen.go @@ -0,0 +1,54 @@ +package gmodel + +import ( + "gorm.io/gorm" + "time" +) + +// fs_order_old +type FsOrderOld struct { + Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // + Sn *string `gorm:"unique_key;default:'';" json:"sn"` // 订单编号 FS211224OL2XDKNP + UserId *int64 `gorm:"index;default:0;" json:"user_id"` // 用户ID + SellerUserId *int64 `gorm:"default:0;" json:"seller_user_id"` // 销售员ID 0:自主下单 + TotalAmount *int64 `gorm:"default:0;" json:"total_amount"` // 总价 + PayedAmount *int64 `gorm:"default:0;" json:"payed_amount"` // 已支付金额 + PayMethod *int64 `gorm:"default:0;" json:"pay_method"` // 支付方式 1paypal 2strip + Ctime *int64 `gorm:"default:0;" json:"ctime"` // 添加时间 + Utime *int64 `gorm:"default:0;" json:"utime"` // 更新时间 + Ptime *int64 `gorm:"default:0;" json:"ptime"` // 最后一次 支付时间(可能多次支付) + AddressId *int64 `gorm:"index;default:0;" json:"address_id"` // 地址ID或者云仓ID + DeliveryMethod *int64 `gorm:"default:0;" json:"delivery_method"` // 配送方式 1:直接发货到收获地址 2:云仓 + CustomerMark *string `gorm:"default:'';" json:"customer_mark"` // 客户备注 + Mark *string `gorm:"default:'';" json:"mark"` // 后台订单备注 + AddressInfo *string `gorm:"default:'';" json:"address_info"` // 详细地址信息JSON + IsSup *int64 `gorm:"default:0;" json:"is_sup"` // 0不是补货 1是补货 + Status *int64 `gorm:"default:0;" json:"status"` // 状态位(0:未支付,1:部分支付,2:支付完成,3:部分生产,4:部分生产完成,5:全部生产,6:全部生产完成,7:部分发货,8:发货完成,9:完成订单,10:取消订单,11:退款中,12:退款完成,13:订单已删除,14:订单已关闭) + IsPartPay *int64 `gorm:"default:0;" json:"is_part_pay"` // 是否部分支付(0:否,1:是) + IsPayCompleted *int64 `gorm:"default:0;" json:"is_pay_completed"` // 是否支付完成(0:否,1:是) + IsPartProduct *int64 `gorm:"default:0;" json:"is_part_product"` // 是否部分生产(0:否,1:是) + IsPartProductCompleted *int64 `gorm:"default:0;" json:"is_part_product_completed"` // 是否部分生产完成(0:否,1:是) + IsAllProduct *int64 `gorm:"default:0;" json:"is_all_product"` // 是否全部生产(0:否,1:是) + IsAllProductCompleted *int64 `gorm:"default:0;" json:"is_all_product_completed"` // 是否全部生产完成(0:否,1:是) + IsPartDelivery *int64 `gorm:"default:0;" json:"is_part_delivery"` // 是否部分发货(0:否,1:是) + IsDeliveryCompleted *int64 `gorm:"default:0;" json:"is_delivery_completed"` // 是否发货完成(0:否,1:是) + IsComplated *int64 `gorm:"default:0;" json:"is_complated"` // 是否完成订单(0:否,1:是) + IsCancel *int64 `gorm:"default:0;" json:"is_cancel"` // 是否取消订单(0:否,1:是) + IsRefunding *int64 `gorm:"default:0;" json:"is_refunding"` // 是否退款中(0:否,1:是) + IsRefunded *int64 `gorm:"default:0;" json:"is_refunded"` // 是否退款完成(0:否,1:是) + IsDeleted *int64 `gorm:"default:0;" json:"is_deleted"` // 是否删除(0:否,1:是) + RefundReasonId *int64 `gorm:"default:0;" json:"refund_reason_id"` // 取消订单原因ID + RefundReason *string `gorm:"default:'';" json:"refund_reason"` // 取消订单原因 + TsTime *time.Time `gorm:"default:'0000-00-00 00:00:00';" json:"ts_time"` // + IsSure *int64 `gorm:"default:0;" json:"is_sure"` // 是否确认订单 1确认0未确认 + DeliverSn *string `gorm:"default:'';" json:"deliver_sn"` // 发货单号 + EmailTime *int64 `gorm:"default:0;" json:"email_time"` // 邮件发送时间 +} +type FsOrderOldModel struct { + db *gorm.DB + name string +} + +func NewFsOrderOldModel(db *gorm.DB) *FsOrderOldModel { + return &FsOrderOldModel{db: db, name: "fs_order_old"} +} diff --git a/model/gmodel/fs_order_old_logic.go b/model/gmodel/fs_order_old_logic.go new file mode 100644 index 00000000..e68225aa --- /dev/null +++ b/model/gmodel/fs_order_old_logic.go @@ -0,0 +1,2 @@ +package gmodel +// TODO: 使用model的属性做你想做的 \ No newline at end of file diff --git a/model/gmodel/fs_order_remark_old_gen.go b/model/gmodel/fs_order_remark_old_gen.go new file mode 100644 index 00000000..7c37fe76 --- /dev/null +++ b/model/gmodel/fs_order_remark_old_gen.go @@ -0,0 +1,22 @@ +package gmodel + +import ( + "gorm.io/gorm" +) + +// fs_order_remark_old 订单备注表 +type FsOrderRemarkOld struct { + Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // id + OrderId *int64 `gorm:"index;default:0;" json:"order_id"` // 订单id + Remark *string `gorm:"default:'';" json:"remark"` // 订单备注 + AdminId *int64 `gorm:"default:0;" json:"admin_id"` // 后台操作人员 + Ctime *int64 `gorm:"default:0;" json:"ctime"` // 添加时间 +} +type FsOrderRemarkOldModel struct { + db *gorm.DB + name string +} + +func NewFsOrderRemarkOldModel(db *gorm.DB) *FsOrderRemarkOldModel { + return &FsOrderRemarkOldModel{db: db, name: "fs_order_remark_old"} +} diff --git a/model/gmodel/fs_order_remark_old_logic.go b/model/gmodel/fs_order_remark_old_logic.go new file mode 100644 index 00000000..e68225aa --- /dev/null +++ b/model/gmodel/fs_order_remark_old_logic.go @@ -0,0 +1,2 @@ +package gmodel +// TODO: 使用model的属性做你想做的 \ No newline at end of file diff --git a/model/gmodel/fs_order_trade_event_gen.go b/model/gmodel/fs_order_trade_event_gen.go new file mode 100644 index 00000000..6fa748c8 --- /dev/null +++ b/model/gmodel/fs_order_trade_event_gen.go @@ -0,0 +1,25 @@ +package gmodel + +import ( + "gorm.io/gorm" + "time" +) + +// fs_order_trade_event 订单交易事件表 +type FsOrderTradeEvent struct { + Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // 订单交易ID + PayMethod *int64 `gorm:"default:0;" json:"pay_method"` // 支付方式:1=stripe,2=paypal + EventId *string `gorm:"default:'';" json:"event_id"` // + EventType *string `gorm:"default:'';" json:"event_type"` // + EventData *[]byte `gorm:"default:'';" json:"event_data"` // + Ctime *time.Time `gorm:"default:'0000-00-00 00:00:00';" json:"ctime"` // + Utime *time.Time `gorm:"default:'0000-00-00 00:00:00';" json:"utime"` // +} +type FsOrderTradeEventModel struct { + db *gorm.DB + name string +} + +func NewFsOrderTradeEventModel(db *gorm.DB) *FsOrderTradeEventModel { + return &FsOrderTradeEventModel{db: db, name: "fs_order_trade_event"} +} diff --git a/model/gmodel/fs_order_trade_event_logic.go b/model/gmodel/fs_order_trade_event_logic.go new file mode 100644 index 00000000..e68225aa --- /dev/null +++ b/model/gmodel/fs_order_trade_event_logic.go @@ -0,0 +1,2 @@ +package gmodel +// TODO: 使用model的属性做你想做的 \ No newline at end of file diff --git a/model/gmodel/fs_order_trade_gen.go b/model/gmodel/fs_order_trade_gen.go new file mode 100644 index 00000000..01414724 --- /dev/null +++ b/model/gmodel/fs_order_trade_gen.go @@ -0,0 +1,36 @@ +package gmodel + +import ( + "gorm.io/gorm" + "time" +) + +// fs_order_trade 订单交易表 +type FsOrderTrade struct { + Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // 订单交易ID + UserId *int64 `gorm:"index;default:0;" json:"user_id"` // 用户ID + OrderNo *string `gorm:"default:'';" json:"order_no"` // + OrderSource *string `gorm:"default:'';" json:"order_source"` // + TradeNo *string `gorm:"index;default:'';" json:"trade_no"` // + PayAmount *int64 `gorm:"default:0;" json:"pay_amount"` // 支付金额 (分) + PayStatus *int64 `gorm:"default:0;" json:"pay_status"` // 支付状态:1=未成功,2=已成功 + PaymentMethod *int64 `gorm:"default:0;" json:"payment_method"` // 支付方式:1=stripe,2=paypal + PayStage *int64 `gorm:"default:0;" json:"pay_stage"` // 支付阶段:1=首付,2=尾款 + RefundStatus *int64 `gorm:"default:0;" json:"refund_status"` // 退款状态:1=未退款,2=已退款 + CardNo *string `gorm:"default:'';" json:"card_no"` // + CardBrand *string `gorm:"default:'';" json:"card_brand"` // + Country *string `gorm:"default:'';" json:"country"` // + Currency *string `gorm:"default:'';" json:"currency"` // + Metadata *[]byte `gorm:"default:'';" json:"metadata"` // + Ctime *time.Time `gorm:"default:'0000-00-00 00:00:00';" json:"ctime"` // + Utime *time.Time `gorm:"default:'0000-00-00 00:00:00';" json:"utime"` // + PayTitle *string `gorm:"default:'';" json:"pay_title"` // +} +type FsOrderTradeModel struct { + db *gorm.DB + name string +} + +func NewFsOrderTradeModel(db *gorm.DB) *FsOrderTradeModel { + return &FsOrderTradeModel{db: db, name: "fs_order_trade"} +} diff --git a/model/gmodel/fs_order_trade_logic.go b/model/gmodel/fs_order_trade_logic.go new file mode 100644 index 00000000..e68225aa --- /dev/null +++ b/model/gmodel/fs_order_trade_logic.go @@ -0,0 +1,2 @@ +package gmodel +// TODO: 使用model的属性做你想做的 \ No newline at end of file diff --git a/model/gmodel/fs_shopping_cart_gen.go b/model/gmodel/fs_shopping_cart_gen.go index 2997ec11..04996ad2 100644 --- a/model/gmodel/fs_shopping_cart_gen.go +++ b/model/gmodel/fs_shopping_cart_gen.go @@ -17,8 +17,6 @@ type FsShoppingCart struct { PurchaseQuantity *int64 `gorm:"default:0;" json:"purchase_quantity"` // 购买数量 Snapshot *string `gorm:"default:'';" json:"snapshot"` // IsHighlyCustomized *int64 `gorm:"default:0;" json:"is_highly_customized"` // 是否高度定制 0非 1是(针对客人高度定制只能后台增加如购物车) - Status *int64 `gorm:"default:0;" json:"status"` // 0未下单 1已下单 - IsEffective *int64 `gorm:"default:1;" json:"is_effective"` // 是否有效 0非 1是(针对对购物车下单,此前数据表更失效) Ctime *time.Time `gorm:"default:'0000-00-00 00:00:00';" json:"ctime"` // Utime *time.Time `gorm:"default:'0000-00-00 00:00:00';" json:"utime"` // } diff --git a/model/gmodel/var_gen.go b/model/gmodel/var_gen.go index 1d92c033..88beb3b4 100644 --- a/model/gmodel/var_gen.go +++ b/model/gmodel/var_gen.go @@ -7,7 +7,6 @@ type AllModelsGen struct { CasbinRule *CasbinRuleModel // casbin_rule FsAddress *FsAddressModel // fs_address 用户地址表 FsAdminApi *FsAdminApiModel // fs_admin_api 后台--接口表 - FsAdminAuthRole *FsAdminAuthRoleModel // fs_admin_auth_role 后台--角色表 FsAdminDepartment *FsAdminDepartmentModel // fs_admin_department 后台--部门表 FsAdminMenu *FsAdminMenuModel // fs_admin_menu 后台--菜单表 FsAdminRole *FsAdminRoleModel // fs_admin_role 后台--角色表 @@ -23,15 +22,15 @@ type AllModelsGen struct { FsCardGroup *FsCardGroupModel // fs_card_group 卡号分组表 FsCart *FsCartModel // fs_cart 购物车 FsChangeCode *FsChangeCodeModel // fs_change_code 忘记密码code表 - FsCloud *FsCloudModel // fs_cloud 云仓表 - FsCloudDeliverEveryTmp *FsCloudDeliverEveryTmpModel // fs_cloud_deliver_every_tmp - FsCloudDeliverTmp *FsCloudDeliverTmpModel // fs_cloud_deliver_tmp - FsCloudPickUp *FsCloudPickUpModel // fs_cloud_pick_up 云仓提货单 - FsCloudPickUpDetail *FsCloudPickUpDetailModel // fs_cloud_pick_up_detail 云仓提货单-详情 - FsCloudReceive *FsCloudReceiveModel // fs_cloud_receive 云仓接收工厂总单 - FsCloudReceiveEvery *FsCloudReceiveEveryModel // fs_cloud_receive_every - FsCloudRenderLog *FsCloudRenderLogModel // fs_cloud_render_log 云渲染日志表 - FsCloudUserApplyBack *FsCloudUserApplyBackModel // fs_cloud_user_apply_back 该表废弃 + FsCloudDeliverEveryTmpOld *FsCloudDeliverEveryTmpOldModel // fs_cloud_deliver_every_tmp_old + FsCloudDeliverTmpOld *FsCloudDeliverTmpOldModel // fs_cloud_deliver_tmp_old + FsCloudOld *FsCloudOldModel // fs_cloud_old 云仓表 + FsCloudPickUpDetailOld *FsCloudPickUpDetailOldModel // fs_cloud_pick_up_detail_old 云仓提货单-详情 + FsCloudPickUpOld *FsCloudPickUpOldModel // fs_cloud_pick_up_old 云仓提货单 + FsCloudReceiveEveryOld *FsCloudReceiveEveryOldModel // fs_cloud_receive_every_old + FsCloudReceiveOld *FsCloudReceiveOldModel // fs_cloud_receive_old 云仓接收工厂总单 + FsCloudRenderLogOld *FsCloudRenderLogOldModel // fs_cloud_render_log_old 云渲染日志表 + FsCloudUserApplyBackOld *FsCloudUserApplyBackOldModel // fs_cloud_user_apply_back_old 该表废弃 FsContact *FsContactModel // fs_contact 该表暂未使用 FsContactService *FsContactServiceModel // fs_contact_service FsCoupon *FsCouponModel // fs_coupon 代金券(暂未使用) @@ -55,11 +54,14 @@ type AllModelsGen struct { FsMenu *FsMenuModel // fs_menu 后台菜单 FsMerchantCategory *FsMerchantCategoryModel // fs_merchant_category 商户类型表 FsMigration *FsMigrationModel // fs_migration 版本库 - FsOrder *FsOrderModel // fs_order - FsOrderAffiliate *FsOrderAffiliateModel // fs_order_affiliate 订单附属表-流程控制时间等 - FsOrderDetail *FsOrderDetailModel // fs_order_detail 订单详细表 - FsOrderDetailTemplate *FsOrderDetailTemplateModel // fs_order_detail_template 订单模板详细表 - FsOrderRemark *FsOrderRemarkModel // fs_order_remark 订单备注表 + FsOrder *FsOrderModel // fs_order 订单表 + FsOrderAffiliateOld *FsOrderAffiliateOldModel // fs_order_affiliate_old 订单附属表-流程控制时间等 + FsOrderDetailOld *FsOrderDetailOldModel // fs_order_detail_old 订单详细表 + FsOrderDetailTemplateOld *FsOrderDetailTemplateOldModel // fs_order_detail_template_old 订单模板详细表 + FsOrderOld *FsOrderOldModel // fs_order_old + FsOrderRemarkOld *FsOrderRemarkOldModel // fs_order_remark_old 订单备注表 + FsOrderTrade *FsOrderTradeModel // fs_order_trade 订单交易表 + FsOrderTradeEvent *FsOrderTradeEventModel // fs_order_trade_event 订单交易事件表 FsPay *FsPayModel // fs_pay 支付记录 FsPayEvent *FsPayEventModel // fs_pay_event 支付回调事件日志 FsProduct *FsProductModel // fs_product 产品表 @@ -114,7 +116,6 @@ func NewAllModels(gdb *gorm.DB) *AllModelsGen { CasbinRule: NewCasbinRuleModel(gdb), FsAddress: NewFsAddressModel(gdb), FsAdminApi: NewFsAdminApiModel(gdb), - FsAdminAuthRole: NewFsAdminAuthRoleModel(gdb), FsAdminDepartment: NewFsAdminDepartmentModel(gdb), FsAdminMenu: NewFsAdminMenuModel(gdb), FsAdminRole: NewFsAdminRoleModel(gdb), @@ -130,15 +131,15 @@ func NewAllModels(gdb *gorm.DB) *AllModelsGen { FsCardGroup: NewFsCardGroupModel(gdb), FsCart: NewFsCartModel(gdb), FsChangeCode: NewFsChangeCodeModel(gdb), - FsCloud: NewFsCloudModel(gdb), - FsCloudDeliverEveryTmp: NewFsCloudDeliverEveryTmpModel(gdb), - FsCloudDeliverTmp: NewFsCloudDeliverTmpModel(gdb), - FsCloudPickUp: NewFsCloudPickUpModel(gdb), - FsCloudPickUpDetail: NewFsCloudPickUpDetailModel(gdb), - FsCloudReceive: NewFsCloudReceiveModel(gdb), - FsCloudReceiveEvery: NewFsCloudReceiveEveryModel(gdb), - FsCloudRenderLog: NewFsCloudRenderLogModel(gdb), - FsCloudUserApplyBack: NewFsCloudUserApplyBackModel(gdb), + FsCloudDeliverEveryTmpOld: NewFsCloudDeliverEveryTmpOldModel(gdb), + FsCloudDeliverTmpOld: NewFsCloudDeliverTmpOldModel(gdb), + FsCloudOld: NewFsCloudOldModel(gdb), + FsCloudPickUpDetailOld: NewFsCloudPickUpDetailOldModel(gdb), + FsCloudPickUpOld: NewFsCloudPickUpOldModel(gdb), + FsCloudReceiveEveryOld: NewFsCloudReceiveEveryOldModel(gdb), + FsCloudReceiveOld: NewFsCloudReceiveOldModel(gdb), + FsCloudRenderLogOld: NewFsCloudRenderLogOldModel(gdb), + FsCloudUserApplyBackOld: NewFsCloudUserApplyBackOldModel(gdb), FsContact: NewFsContactModel(gdb), FsContactService: NewFsContactServiceModel(gdb), FsCoupon: NewFsCouponModel(gdb), @@ -163,10 +164,13 @@ func NewAllModels(gdb *gorm.DB) *AllModelsGen { FsMerchantCategory: NewFsMerchantCategoryModel(gdb), FsMigration: NewFsMigrationModel(gdb), FsOrder: NewFsOrderModel(gdb), - FsOrderAffiliate: NewFsOrderAffiliateModel(gdb), - FsOrderDetail: NewFsOrderDetailModel(gdb), - FsOrderDetailTemplate: NewFsOrderDetailTemplateModel(gdb), - FsOrderRemark: NewFsOrderRemarkModel(gdb), + FsOrderAffiliateOld: NewFsOrderAffiliateOldModel(gdb), + FsOrderDetailOld: NewFsOrderDetailOldModel(gdb), + FsOrderDetailTemplateOld: NewFsOrderDetailTemplateOldModel(gdb), + FsOrderOld: NewFsOrderOldModel(gdb), + FsOrderRemarkOld: NewFsOrderRemarkOldModel(gdb), + FsOrderTrade: NewFsOrderTradeModel(gdb), + FsOrderTradeEvent: NewFsOrderTradeEventModel(gdb), FsPay: NewFsPayModel(gdb), FsPayEvent: NewFsPayEventModel(gdb), FsProduct: NewFsProductModel(gdb), diff --git a/server/home-user-auth/internal/logic/usercontactservicelogic.go b/server/home-user-auth/internal/logic/usercontactservicelogic.go index 3b8509fb..b8278a86 100644 --- a/server/home-user-auth/internal/logic/usercontactservicelogic.go +++ b/server/home-user-auth/internal/logic/usercontactservicelogic.go @@ -1,10 +1,8 @@ package logic import ( - "fusenapi/model/gmodel" "fusenapi/utils/auth" "fusenapi/utils/basic" - "fusenapi/utils/collect" "context" @@ -12,7 +10,6 @@ import ( "fusenapi/server/home-user-auth/internal/types" "github.com/zeromicro/go-zero/core/logx" - "gorm.io/gorm" ) type UserContactServiceLogic struct { @@ -33,36 +30,36 @@ func (l *UserContactServiceLogic) UserContactService(req *types.RequestContactSe // 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data) // userinfo 传入值时, 一定不为null - if !userinfo.IsUser() { - return resp.SetStatus(basic.CodeUnAuth) - } + // if !userinfo.IsUser() { + // return resp.SetStatus(basic.CodeUnAuth) + // } - cs := gmodel.FsContactService{ - UserId: &userinfo.UserId, - } - collect.LoadJsonTag(&cs, &req) + // cs := gmodel.FsContactService{ + // UserId: &userinfo.UserId, + // } + // collect.LoadJsonTag(&cs, &req) - switch req.Type { - case "order": - _, err := l.svcCtx.AllModels.FsOrder.FindOneAndCreateServiceContact(l.ctx, userinfo.UserId, req.RelationID, &cs) - if err != nil { - if err == gorm.ErrRecordNotFound { - return resp.SetStatus(basic.CodeOrderNotFoundErr) - } - return resp.SetStatus(basic.CodeDbSqlErr) - } - case "cloud": - _, err := l.svcCtx.AllModels.FsCloudPickUp.GetCloudPickUpByIDAndUserID(l.ctx, userinfo.UserId, req.RelationID, &cs) - if err != nil { - if err == gorm.ErrRecordNotFound { - return resp.SetStatus(basic.CodeCloudOrderNotFoundErr) - } - return resp.SetStatus(basic.CodeDbSqlErr) - } - return - default: - return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "type is unknown") - } + // switch req.Type { + // case "order": + // _, err := l.svcCtx.AllModels.FsOrder.FindOneAndCreateServiceContact(l.ctx, userinfo.UserId, req.RelationID, &cs) + // if err != nil { + // if err == gorm.ErrRecordNotFound { + // return resp.SetStatus(basic.CodeOrderNotFoundErr) + // } + // return resp.SetStatus(basic.CodeDbSqlErr) + // } + // case "cloud": + // _, err := l.svcCtx.AllModels.FsCloudPickUp.GetCloudPickUpByIDAndUserID(l.ctx, userinfo.UserId, req.RelationID, &cs) + // if err != nil { + // if err == gorm.ErrRecordNotFound { + // return resp.SetStatus(basic.CodeCloudOrderNotFoundErr) + // } + // return resp.SetStatus(basic.CodeDbSqlErr) + // } + // return + // default: + // return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "type is unknown") + // } - return resp.SetStatus(basic.CodeOK, cs) + return resp.SetStatus(basic.CodeOK) } diff --git a/server/home-user-auth/internal/logic/useroderdeletelogic.go b/server/home-user-auth/internal/logic/useroderdeletelogic.go index 0b4eb5ce..63c2c679 100644 --- a/server/home-user-auth/internal/logic/useroderdeletelogic.go +++ b/server/home-user-auth/internal/logic/useroderdeletelogic.go @@ -1,23 +1,15 @@ package logic import ( - "errors" - "fusenapi/constants" - "fusenapi/model/gmodel" "fusenapi/utils/auth" "fusenapi/utils/basic" - "time" "context" "fusenapi/server/home-user-auth/internal/svc" "fusenapi/server/home-user-auth/internal/types" - "github.com/stripe/stripe-go/v74" - "github.com/stripe/stripe-go/v74/client" - "github.com/zeromicro/go-zero/core/logx" - "gorm.io/gorm" ) type UserOderDeleteLogic struct { @@ -38,109 +30,109 @@ func (l *UserOderDeleteLogic) UserOderDelete(req *types.RequestOrderId, userinfo // 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data) // userinfo 传入值时, 一定不为null - if !userinfo.IsUser() { - return resp.SetStatus(basic.CodeUnAuth) // 如果不是用户信息, 返回未授权错误 - } + // if !userinfo.IsUser() { + // return resp.SetStatus(basic.CodeUnAuth) // 如果不是用户信息, 返回未授权错误 + // } - //订单id - orderId := req.OrderId - if orderId < 1 { - return resp.SetStatus(basic.CodeRequestParamsErr) - } + // //订单id + // orderId := req.OrderId + // if orderId < 1 { + // return resp.SetStatus(basic.CodeRequestParamsErr) + // } - m := l.svcCtx.AllModels.FsOrder - order, err := m.FindOne(l.ctx, userinfo.UserId, orderId) - if err != nil { - if errors.Is(err, gorm.ErrRecordNotFound) { - return resp.SetStatus(basic.CodeOrderNotFoundErr) - } - logx.Error(err) - return resp.SetStatus(basic.CodeDbSqlErr) - } + // m := l.svcCtx.AllModels.FsOrder + // order, err := m.FindOne(l.ctx, userinfo.UserId, orderId) + // if err != nil { + // if errors.Is(err, gorm.ErrRecordNotFound) { + // return resp.SetStatus(basic.CodeOrderNotFoundErr) + // } + // logx.Error(err) + // return resp.SetStatus(basic.CodeDbSqlErr) + // } - if auth.CheckValueRange[constants.Order]( - constants.Order(*order.Status), - constants.STATUS_NEW_NOT_PAY, - constants.STATUS_NEW_PAY_COMPLETED, - constants.STATUS_NEW_PART_PAY, - ) { - return resp.SetStatus(basic.CodeOrderNotCancelledErr) - } + // if auth.CheckValueRange[constants.Order]( + // constants.Order(*order.Status), + // constants.STATUS_NEW_NOT_PAY, + // constants.STATUS_NEW_PAY_COMPLETED, + // constants.STATUS_NEW_PART_PAY, + // ) { + // return resp.SetStatus(basic.CodeOrderNotCancelledErr) + // } - if *order.IsPayCompleted == 1 && - time.Now().After(time.Unix(*order.Ctime, 0).Add(48*time.Hour)) { - return resp.SetStatus(basic.CodeOrderNotCancelledErr) - } + // if *order.IsPayCompleted == 1 && + // time.Now().After(time.Unix(*order.Ctime, 0).Add(48*time.Hour)) { + // return resp.SetStatus(basic.CodeOrderNotCancelledErr) + // } - uOrder := &gmodel.FsOrder{ - Id: orderId, - } + // uOrder := &gmodel.FsOrder{ + // Id: orderId, + // } - var ( - isCancel int64 = 1 - ustatus int64 = int64(constants.STATUS_NEW_CANCEL) - ) - // 修改取消状态和取消原因 - uOrder.Status = &ustatus - uOrder.IsCancel = &isCancel - uOrder.RefundReasonId = &req.RefundReasonId - uOrder.RefundReason = &req.RefundReason + // var ( + // isCancel int64 = 1 + // ustatus int64 = int64(constants.STATUS_NEW_CANCEL) + // ) + // // 修改取消状态和取消原因 + // uOrder.Status = &ustatus + // uOrder.IsCancel = &isCancel + // uOrder.RefundReasonId = &req.RefundReasonId + // uOrder.RefundReason = &req.RefundReason - err = m.Update(l.ctx, uOrder) - if err != nil { - logx.Error(err) - return resp.SetStatus(basic.CodeDbUpdateErr) - } + // err = m.Update(l.ctx, uOrder) + // if err != nil { + // logx.Error(err) + // return resp.SetStatus(basic.CodeDbUpdateErr) + // } - var ( - IsRefund int64 = 0 - CreatedAt = time.Now().UTC().Unix() - ) + // var ( + // IsRefund int64 = 0 + // CreatedAt = time.Now().UTC().Unix() + // ) - refund := &gmodel.FsRefundReason{ - IsRefund: &IsRefund, - RefundReasonId: &req.RefundReasonId, - RefundReason: &req.RefundReason, - OrderId: &order.Id, - CreatedAt: &CreatedAt, - } + // refund := &gmodel.FsRefundReason{ + // IsRefund: &IsRefund, + // RefundReasonId: &req.RefundReasonId, + // RefundReason: &req.RefundReason, + // OrderId: &order.Id, + // CreatedAt: &CreatedAt, + // } - mFsRefundReason := gmodel.NewFsRefundReasonModel(l.svcCtx.MysqlConn) - err = mFsRefundReason.Create(l.ctx, refund) - if err != nil { - logx.Error(err) - return resp.SetStatus(basic.CodeDbSqlErr) - } + // mFsRefundReason := gmodel.NewFsRefundReasonModel(l.svcCtx.MysqlConn) + // err = mFsRefundReason.Create(l.ctx, refund) + // if err != nil { + // logx.Error(err) + // return resp.SetStatus(basic.CodeDbSqlErr) + // } - // 退款 - // 调用第三方接口发起退款 + // // 退款 + // // 调用第三方接口发起退款 - config := &stripe.BackendConfig{ - MaxNetworkRetries: stripe.Int64(0), // Zero retries - } + // config := &stripe.BackendConfig{ + // MaxNetworkRetries: stripe.Int64(0), // Zero retries + // } - sc := &client.API{} - sc.Init(l.svcCtx.Config.Stripe.SK, &stripe.Backends{ - API: stripe.GetBackendWithConfig(stripe.APIBackend, config), - Uploads: stripe.GetBackendWithConfig(stripe.UploadsBackend, config), - }) - // ['order_number' => $order->sn, 'is_refund' => 0, 'pay_status' => 1] - payM := l.svcCtx.AllModels.FsPay + // sc := &client.API{} + // sc.Init(l.svcCtx.Config.Stripe.SK, &stripe.Backends{ + // API: stripe.GetBackendWithConfig(stripe.APIBackend, config), + // Uploads: stripe.GetBackendWithConfig(stripe.UploadsBackend, config), + // }) + // // ['order_number' => $order->sn, 'is_refund' => 0, 'pay_status' => 1] + // payM := l.svcCtx.AllModels.FsPay - // 查询支付信息 - pays, err := payM.GetOrderPayList(l.ctx, *order.Sn, 1, 0) - for _, pay := range pays { - sc.Refunds.New(&stripe.RefundParams{ - PaymentIntent: pay.TradeNo, - }) - } - if err != nil { - if errors.Is(err, gorm.ErrRecordNotFound) { - return resp.SetStatus(basic.CodeApiErr) - } - } + // // 查询支付信息 + // pays, err := payM.GetOrderPayList(l.ctx, *order.Sn, 1, 0) + // for _, pay := range pays { + // sc.Refunds.New(&stripe.RefundParams{ + // PaymentIntent: pay.TradeNo, + // }) + // } + // if err != nil { + // if errors.Is(err, gorm.ErrRecordNotFound) { + // return resp.SetStatus(basic.CodeApiErr) + // } + // } - return resp.SetStatus(basic.CodePayCancelOk, uOrder) + return resp.SetStatus(basic.CodePayCancelOk) // return ResponseError(500, "Cancellation failure") diff --git a/server/home-user-auth/internal/logic/userordercancellogic.go b/server/home-user-auth/internal/logic/userordercancellogic.go index 7e7832d6..d576cb19 100644 --- a/server/home-user-auth/internal/logic/userordercancellogic.go +++ b/server/home-user-auth/internal/logic/userordercancellogic.go @@ -1,13 +1,8 @@ package logic import ( - "errors" - "fusenapi/constants" - "fusenapi/model/gmodel" "fusenapi/utils/auth" "fusenapi/utils/basic" - "fusenapi/utils/handlers" - "time" "context" @@ -15,7 +10,6 @@ import ( "fusenapi/server/home-user-auth/internal/types" "github.com/zeromicro/go-zero/core/logx" - "gorm.io/gorm" ) type UserOrderCancelLogic struct { @@ -36,93 +30,93 @@ func (l *UserOrderCancelLogic) UserOrderCancel(req *types.UserOrderCancelReq, us // 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data) // userinfo 传入值时, 一定不为null - if userinfo == nil || userinfo.UserId == 0 { - return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found") - } + // if userinfo == nil || userinfo.UserId == 0 { + // return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found") + // } - //查询订单信息 - orderModel := gmodel.NewFsOrderModel(l.svcCtx.MysqlConn) - orderInfo, err := orderModel.FindOne(l.ctx, userinfo.UserId, req.ID) - if err != nil { - if errors.Is(err, gorm.ErrRecordNotFound) { - return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "the order is not exists") - } - logx.Error(err) - return resp.SetStatus(basic.CodeServiceErr, "failed to get order info") - } + // //查询订单信息 + // orderModel := gmodel.NewFsOrderModel(l.svcCtx.MysqlConn) + // orderInfo, err := orderModel.FindOne(l.ctx, userinfo.UserId, req.ID) + // if err != nil { + // if errors.Is(err, gorm.ErrRecordNotFound) { + // return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "the order is not exists") + // } + // logx.Error(err) + // return resp.SetStatus(basic.CodeServiceErr, "failed to get order info") + // } - // 判断订单状态 - var notCancelStatusMap = make(map[int64]struct{}, 3) - notCancelStatusMap[int64(constants.STATUS_NEW_NOT_PAY)] = struct{}{} - notCancelStatusMap[int64(constants.STATUS_NEW_PART_PAY)] = struct{}{} - notCancelStatusMap[int64(constants.STATUS_NEW_PAY_COMPLETED)] = struct{}{} - _, ok := notCancelStatusMap[int64(*orderInfo.Status)] - if !ok { - return resp.SetStatusWithMessage(basic.CodeOrderNotCancelledErr, "the order status not cancle") - } + // // 判断订单状态 + // var notCancelStatusMap = make(map[int64]struct{}, 3) + // notCancelStatusMap[int64(constants.STATUS_NEW_NOT_PAY)] = struct{}{} + // notCancelStatusMap[int64(constants.STATUS_NEW_PART_PAY)] = struct{}{} + // notCancelStatusMap[int64(constants.STATUS_NEW_PAY_COMPLETED)] = struct{}{} + // _, ok := notCancelStatusMap[int64(*orderInfo.Status)] + // if !ok { + // return resp.SetStatusWithMessage(basic.CodeOrderNotCancelledErr, "the order status not cancle") + // } - var cancelTime int64 = time.Now().UTC().Unix() - (*orderInfo.Ctime + int64(constants.CANCLE_ORDER_EXPIRE)) - // 第一次支付成功后48小时后不能进行取消操作 - if *orderInfo.IsPayCompleted == 1 && cancelTime > 0 { - return resp.SetStatusWithMessage(basic.CodeOrderNotCancelledErr, "The current order cannot be cancelled") - } + // var cancelTime int64 = time.Now().UTC().Unix() - (*orderInfo.Ctime + int64(constants.CANCLE_ORDER_EXPIRE)) + // // 第一次支付成功后48小时后不能进行取消操作 + // if *orderInfo.IsPayCompleted == 1 && cancelTime > 0 { + // return resp.SetStatusWithMessage(basic.CodeOrderNotCancelledErr, "The current order cannot be cancelled") + // } - // 修改订单--取消状态和取消原因 - *orderInfo.Status = int64(constants.STATUS_NEW_CANCEL) - *orderInfo.IsCancel = 1 - orderInfo.RefundReasonId = &req.RefundReasonId - orderInfo.RefundReason = &req.RefundReason + // // 修改订单--取消状态和取消原因 + // *orderInfo.Status = int64(constants.STATUS_NEW_CANCEL) + // *orderInfo.IsCancel = 1 + // orderInfo.RefundReasonId = &req.RefundReasonId + // orderInfo.RefundReason = &req.RefundReason - var nowTime = time.Now().UTC().Unix() - var payList []handlers.PayInfo - // 事务处理 - ctx := l.ctx - err = l.svcCtx.MysqlConn.Transaction(func(tx *gorm.DB) error { - // 修改订单信息 - orderModelTS := gmodel.NewFsOrderModel(tx) - err = orderModelTS.RBUpdate(ctx, orderInfo) - if err != nil { - return err - } - // 新增退款记录 - var isRefund int64 = 0 - refundReasonModelTS := gmodel.NewFsRefundReasonModel(tx) - refundReasonModelTS.RBCreateOrUpdate(ctx, &gmodel.FsRefundReason{ - IsRefund: &isRefund, - RefundReasonId: &req.RefundReasonId, - RefundReason: &req.RefundReason, - OrderId: &orderInfo.Id, - CreatedAt: &nowTime, - }) - // 退款申请 - // 退款申请--查询支付信息 - fsPayModelTS := gmodel.NewFsPayModel(tx) - rbFsPay := fsPayModelTS.RowSelectBuilder(nil).Where("order_number = ?", orderInfo.Sn).Where("pay_status =?", constants.PAYSTATUS_SUCCESS).Where("is_refund =?", 0) - payInfoList, err := fsPayModelTS.FindAll(ctx, rbFsPay, nil, "") - if err != nil { - return err - } - for _, payInfo := range payInfoList { - var key string - if *payInfo.PaymentMethod == int64(constants.PAYMETHOD_STRIPE) { - key = l.svcCtx.Config.PayConfig.Stripe.Key - } - payList = append(payList, handlers.PayInfo{ - TradeNo: *payInfo.TradeNo, - PaymentMethod: *payInfo.PaymentMethod, - Key: key, - }) - } - return nil - }) - // 退款申请--调取第三方接口发起退款 - handlers.PayRefundHandler(&handlers.PayRefundHandlerReq{ - PayInfoList: payList, - }) - if err != nil { - logx.Error(err) - return resp.SetStatusWithMessage(basic.CodeOrderCancelledNotOk, "the order cancle failed") - } + // var nowTime = time.Now().UTC().Unix() + // var payList []handlers.PayInfo + // // 事务处理 + // ctx := l.ctx + // err = l.svcCtx.MysqlConn.Transaction(func(tx *gorm.DB) error { + // // 修改订单信息 + // orderModelTS := gmodel.NewFsOrderModel(tx) + // err = orderModelTS.RBUpdate(ctx, orderInfo) + // if err != nil { + // return err + // } + // // 新增退款记录 + // var isRefund int64 = 0 + // refundReasonModelTS := gmodel.NewFsRefundReasonModel(tx) + // refundReasonModelTS.RBCreateOrUpdate(ctx, &gmodel.FsRefundReason{ + // IsRefund: &isRefund, + // RefundReasonId: &req.RefundReasonId, + // RefundReason: &req.RefundReason, + // OrderId: &orderInfo.Id, + // CreatedAt: &nowTime, + // }) + // // 退款申请 + // // 退款申请--查询支付信息 + // fsPayModelTS := gmodel.NewFsPayModel(tx) + // rbFsPay := fsPayModelTS.RowSelectBuilder(nil).Where("order_number = ?", orderInfo.Sn).Where("pay_status =?", constants.PAYSTATUS_SUCCESS).Where("is_refund =?", 0) + // payInfoList, err := fsPayModelTS.FindAll(ctx, rbFsPay, nil, "") + // if err != nil { + // return err + // } + // for _, payInfo := range payInfoList { + // var key string + // if *payInfo.PaymentMethod == int64(constants.PAYMETHOD_STRIPE) { + // key = l.svcCtx.Config.PayConfig.Stripe.Key + // } + // payList = append(payList, handlers.PayInfo{ + // TradeNo: *payInfo.TradeNo, + // PaymentMethod: *payInfo.PaymentMethod, + // Key: key, + // }) + // } + // return nil + // }) + // // 退款申请--调取第三方接口发起退款 + // handlers.PayRefundHandler(&handlers.PayRefundHandlerReq{ + // PayInfoList: payList, + // }) + // if err != nil { + // logx.Error(err) + // return resp.SetStatusWithMessage(basic.CodeOrderCancelledNotOk, "the order cancle failed") + // } return resp.SetStatus(basic.CodeOK) } diff --git a/server/home-user-auth/internal/logic/userorderdeletelogic.go b/server/home-user-auth/internal/logic/userorderdeletelogic.go index 0842b983..4baf0058 100644 --- a/server/home-user-auth/internal/logic/userorderdeletelogic.go +++ b/server/home-user-auth/internal/logic/userorderdeletelogic.go @@ -1,9 +1,6 @@ package logic import ( - "errors" - "fusenapi/constants" - "fusenapi/model/gmodel" "fusenapi/utils/auth" "fusenapi/utils/basic" @@ -13,7 +10,6 @@ import ( "fusenapi/server/home-user-auth/internal/types" "github.com/zeromicro/go-zero/core/logx" - "gorm.io/gorm" ) type UserOrderDeleteLogic struct { @@ -43,36 +39,36 @@ func (l *UserOrderDeleteLogic) UserOrderDelete(req *types.UserOrderDeleteReq, us // 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data) // userinfo 传入值时, 一定不为null - if userinfo == nil || userinfo.UserId == 0 { - return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found") - } + // if userinfo == nil || userinfo.UserId == 0 { + // return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found") + // } - orderModel := gmodel.NewFsOrderModel(l.svcCtx.MysqlConn) - orderInfo, err := orderModel.FindOne(l.ctx, userinfo.UserId, req.ID) + // orderModel := gmodel.NewFsOrderModel(l.svcCtx.MysqlConn) + // orderInfo, err := orderModel.FindOne(l.ctx, userinfo.UserId, req.ID) - if err != nil { - if errors.Is(err, gorm.ErrRecordNotFound) { - return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found") - } - logx.Error(err) - return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get order info") - } + // if err != nil { + // if errors.Is(err, gorm.ErrRecordNotFound) { + // return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found") + // } + // logx.Error(err) + // return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get order info") + // } - updateStatusMap := make(map[constants.Order]struct{}, 4) - updateStatusMap[constants.STATUS_NEW_COMPLETED] = struct{}{} - updateStatusMap[constants.STATUS_NEW_CANCEL] = struct{}{} - updateStatusMap[constants.STATUS_NEW_REFUNDED] = struct{}{} - updateStatusMap[constants.STATUS_NEW_CLOSE] = struct{}{} - if _, ok := updateStatusMap[constants.Order(*orderInfo.Status)]; !ok { - return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found") - } - *orderInfo.Status = int64(constants.STATUS_NEW_DELETE) - *orderInfo.IsDeleted = 1 - err = orderModel.Update(l.ctx, orderInfo) - if err != nil { - logx.Error(err) - return resp.SetStatusWithMessage(basic.CodeServiceErr, "fail to delete") - } + // updateStatusMap := make(map[constants.Order]struct{}, 4) + // updateStatusMap[constants.STATUS_NEW_COMPLETED] = struct{}{} + // updateStatusMap[constants.STATUS_NEW_CANCEL] = struct{}{} + // updateStatusMap[constants.STATUS_NEW_REFUNDED] = struct{}{} + // updateStatusMap[constants.STATUS_NEW_CLOSE] = struct{}{} + // if _, ok := updateStatusMap[constants.Order(*orderInfo.Status)]; !ok { + // return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found") + // } + // *orderInfo.Status = int64(constants.STATUS_NEW_DELETE) + // *orderInfo.IsDeleted = 1 + // err = orderModel.Update(l.ctx, orderInfo) + // if err != nil { + // logx.Error(err) + // return resp.SetStatusWithMessage(basic.CodeServiceErr, "fail to delete") + // } return resp.SetStatus(basic.CodeOK) } diff --git a/server/home-user-auth/internal/logic/userorderlistlogic.go b/server/home-user-auth/internal/logic/userorderlistlogic.go index 6122e26e..4741891d 100644 --- a/server/home-user-auth/internal/logic/userorderlistlogic.go +++ b/server/home-user-auth/internal/logic/userorderlistlogic.go @@ -1,20 +1,8 @@ package logic import ( - "errors" - "fmt" - "fusenapi/constants" - "fusenapi/model/gmodel" "fusenapi/utils/auth" "fusenapi/utils/basic" - "fusenapi/utils/configs" - "fusenapi/utils/image" - "strings" - - "fusenapi/utils/format" - "fusenapi/utils/order" - "math" - "time" "context" @@ -22,7 +10,6 @@ import ( "fusenapi/server/home-user-auth/internal/types" "github.com/zeromicro/go-zero/core/logx" - "gorm.io/gorm" ) type UserOrderListLogic struct { @@ -43,263 +30,264 @@ func (l *UserOrderListLogic) UserOrderList(req *types.UserOrderListReq, userinfo // 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data) // userinfo 传入值时, 一定不为null - size := req.Size + // size := req.Size - if size > 0 { - size = int64(image.GetCurrentSize(uint32(size))) - } + // if size > 0 { + // size = int64(image.GetCurrentSize(uint32(size))) + // } - orderDetailModel := gmodel.NewFsOrderDetailModel(l.svcCtx.MysqlConn) - orderDetailTemplateModel := gmodel.NewFsOrderDetailTemplateModel(l.svcCtx.MysqlConn) - fsProductDesignModel := gmodel.NewFsProductDesignModel(l.svcCtx.MysqlConn) - orderModel := gmodel.NewFsOrderModel(l.svcCtx.MysqlConn) - rowBuilder := orderModel.RowSelectBuilder(nil) - if userinfo == nil || userinfo.UserId == 0 { - return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found") - } + // orderDetailModel := gmodel.NewFsOrderDetailModel(l.svcCtx.MysqlConn) + // orderDetailTemplateModel := gmodel.NewFsOrderDetailTemplateModel(l.svcCtx.MysqlConn) + // fsProductDesignModel := gmodel.NewFsProductDesignModel(l.svcCtx.MysqlConn) + // orderModel := gmodel.NewFsOrderModel(l.svcCtx.MysqlConn) + // rowBuilder := orderModel.RowSelectBuilder(nil) + // if userinfo == nil || userinfo.UserId == 0 { + // return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found") + // } - // 查询条件 - var page = req.Page - var pageSize = req.PageSize - var listRes []*gmodel.FsOrderRel - rowBuilder = rowBuilder.Where("user_id =?", userinfo.UserId).Where("status <> ?", constants.STATUS_NEW_NOT_PAY).Where("status <>?", constants.STATUS_NEW_DELETE) + // // 查询条件 + // var page = req.Page + // var pageSize = req.PageSize + // var listRes []*gmodel.FsOrderRel + // rowBuilder = rowBuilder.Where("user_id =?", userinfo.UserId).Where("status <> ?", constants.STATUS_NEW_NOT_PAY).Where("status <>?", constants.STATUS_NEW_DELETE) - // 根据时间来查询不同范围的订单 - switch req.Time { - case 1: - rowBuilder = rowBuilder.Where("ctime >?", time.Now().UTC().AddDate(0, -1, 0).Unix()) - case 2: - rowBuilder = rowBuilder.Where("ctime >?", time.Now().UTC().AddDate(0, -3, 0).Unix()) - case 3: - rowBuilder = rowBuilder.Where("ctime >?", time.Now().UTC().AddDate(0, -6, 0).Unix()) - case 4: - rowBuilder = rowBuilder.Where("ctime >?", time.Now().UTC().AddDate(-1, 0, 0).Unix()) - default: - } + // // 根据时间来查询不同范围的订单 + // switch req.Time { + // case 1: + // rowBuilder = rowBuilder.Where("ctime >?", time.Now().UTC().AddDate(0, -1, 0).Unix()) + // case 2: + // rowBuilder = rowBuilder.Where("ctime >?", time.Now().UTC().AddDate(0, -3, 0).Unix()) + // case 3: + // rowBuilder = rowBuilder.Where("ctime >?", time.Now().UTC().AddDate(0, -6, 0).Unix()) + // case 4: + // rowBuilder = rowBuilder.Where("ctime >?", time.Now().UTC().AddDate(-1, 0, 0).Unix()) + // default: + // } - //按照订单状态查询不同的订单 - if req.Status != -1 { - switch req.Status { - case 1: - rowBuilder = rowBuilder.Where("status in ?", [3]constants.Order{constants.STATUS_NEW_PART_PAY, constants.STATUS_NEW_PAY_COMPLETED, constants.STATUS_NEW_SURE}) - case 2: - rowBuilder = rowBuilder.Where("status in ?", [2]constants.Order{constants.STATUS_NEW_PRODUTING, constants.STATUS_NEW_PRODUT_COMPLETED}) - case 3: - rowBuilder = rowBuilder.Where("status in ?", [2]constants.Order{constants.STATUS_NEW_DELIVER, constants.STATUS_NEW_UPS}) - case 4: - rowBuilder = rowBuilder.Where("status =?", constants.STATUS_NEW_ARRIVAL) - case 5: - rowBuilder = rowBuilder.Where("status =?", constants.STATUS_NEW_COMPLETED).Where("delivery_method =?", constants.DELIVERY_METHOD_ADDRESS) - case 7: - rowBuilder = rowBuilder.Where("status in ?", [3]constants.Order{constants.STATUS_NEW_CANCEL, constants.STATUS_NEW_REFUNDED, constants.STATUS_NEW_REFUNDING}) - case 8: - rowBuilder = rowBuilder.Where("status =?", constants.STATUS_NEW_COMPLETED).Where("delivery_method =?", constants.DELIVERY_METHOD_CLOUD) - } - } + // //按照订单状态查询不同的订单 + // if req.Status != -1 { + // switch req.Status { + // case 1: + // rowBuilder = rowBuilder.Where("status in ?", [3]constants.Order{constants.STATUS_NEW_PART_PAY, constants.STATUS_NEW_PAY_COMPLETED, constants.STATUS_NEW_SURE}) + // case 2: + // rowBuilder = rowBuilder.Where("status in ?", [2]constants.Order{constants.STATUS_NEW_PRODUTING, constants.STATUS_NEW_PRODUT_COMPLETED}) + // case 3: + // rowBuilder = rowBuilder.Where("status in ?", [2]constants.Order{constants.STATUS_NEW_DELIVER, constants.STATUS_NEW_UPS}) + // case 4: + // rowBuilder = rowBuilder.Where("status =?", constants.STATUS_NEW_ARRIVAL) + // case 5: + // rowBuilder = rowBuilder.Where("status =?", constants.STATUS_NEW_COMPLETED).Where("delivery_method =?", constants.DELIVERY_METHOD_ADDRESS) + // case 7: + // rowBuilder = rowBuilder.Where("status in ?", [3]constants.Order{constants.STATUS_NEW_CANCEL, constants.STATUS_NEW_REFUNDED, constants.STATUS_NEW_REFUNDING}) + // case 8: + // rowBuilder = rowBuilder.Where("status =?", constants.STATUS_NEW_COMPLETED).Where("delivery_method =?", constants.DELIVERY_METHOD_CLOUD) + // } + // } - // 查询总数 - total, err := orderModel.FindCount(l.ctx, rowBuilder, nil) - if err != nil { - if errors.Is(err, gorm.ErrRecordNotFound) { - return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found") - } - logx.Error(err) - return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get order info") - } + // // 查询总数 + // total, err := orderModel.FindCount(l.ctx, rowBuilder, nil) + // if err != nil { + // if errors.Is(err, gorm.ErrRecordNotFound) { + // return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found") + // } + // logx.Error(err) + // return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get order info") + // } - // 查询数据 - if total > 0 { - rowBuilder = rowBuilder.Preload("FsOrderAffiliateInfo").Preload("FsOrderDetails", func(dbPreload *gorm.DB) *gorm.DB { - return dbPreload.Table(orderDetailModel.TableName()).Preload("FsOrderDetailTemplateInfo", func(dbPreload *gorm.DB) *gorm.DB { - return dbPreload.Table(orderDetailTemplateModel.TableName()).Preload("FsProductDesignInfo", func(dbPreload *gorm.DB) *gorm.DB { - return dbPreload.Table(fsProductDesignModel.TableName()).Preload("OptionData").Preload("TemplateData") - }).Preload("FsProductSizeInfo") - }).Preload("FsProductInfo") - }) - listRes, err = orderModel.FindPageListByPage(l.ctx, rowBuilder, &page, &pageSize, nil, "") - } + // // 查询数据 + // if total > 0 { + // rowBuilder = rowBuilder.Preload("FsOrderAffiliateInfo").Preload("FsOrderDetails", func(dbPreload *gorm.DB) *gorm.DB { + // return dbPreload.Table(orderDetailModel.TableName()).Preload("FsOrderDetailTemplateInfo", func(dbPreload *gorm.DB) *gorm.DB { + // return dbPreload.Table(orderDetailTemplateModel.TableName()).Preload("FsProductDesignInfo", func(dbPreload *gorm.DB) *gorm.DB { + // return dbPreload.Table(fsProductDesignModel.TableName()).Preload("OptionData").Preload("TemplateData") + // }).Preload("FsProductSizeInfo") + // }).Preload("FsProductInfo") + // }) + // listRes, err = orderModel.FindPageListByPage(l.ctx, rowBuilder, &page, &pageSize, nil, "") + // } - if err != nil { - if errors.Is(err, gorm.ErrRecordNotFound) { - return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found") - } - logx.Error(err) - return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get order info") - } - listResLen := len(listRes) + // if err != nil { + // if errors.Is(err, gorm.ErrRecordNotFound) { + // return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found") + // } + // logx.Error(err) + // return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get order info") + // } + // listResLen := len(listRes) - var respList []types.Items - if listResLen > 0 { - // 获取订单时间配置 - orderTimeConfig, err := configs.GetOrderTimeConfig(l.ctx, l.svcCtx.MysqlConn) - if err != nil { - return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get config time info") - } + // var respList []types.Items + // if listResLen > 0 { + // // 获取订单时间配置 + // orderTimeConfig, err := configs.GetOrderTimeConfig(l.ctx, l.svcCtx.MysqlConn) + // if err != nil { + // return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get config time info") + // } - // 数据处理 - for _, item := range listRes { - var pbData types.Items - pbData.ID = item.Id - pbData.Sn = *item.Sn - pbData.UserID = *item.UserId - pbData.TotalAmount = *item.TotalAmount - pbData.Ctime = format.TimeIntToFormat(*item.Ctime) - pbData.Status = *item.Status - pbData.DeliveryMethod = *item.DeliveryMethod - pbData.TsTime = format.TimeToFormat(*item.TsTime) - pbData.IsPayCompleted = *item.IsPayCompleted - pbData.DeliverSn = *item.DeliverSn + // // 数据处理 + // for _, item := range listRes { + // var pbData types.Items + // pbData.ID = item.Id + // pbData.Sn = *item.Sn + // pbData.UserID = *item.UserId + // pbData.TotalAmount = *item.TotalAmount + // pbData.Ctime = format.TimeIntToFormat(*item.Ctime) + // pbData.Status = *item.Status + // pbData.DeliveryMethod = *item.DeliveryMethod + // pbData.TsTime = format.TimeToFormat(*item.TsTime) + // pbData.IsPayCompleted = *item.IsPayCompleted + // pbData.DeliverSn = *item.DeliverSn - var pcsBox int64 - var pcs int64 - var productList []types.Product + // var pcsBox int64 + // var pcs int64 + // var productList []types.Product - var surplusAt int64 + // var surplusAt int64 - //如果是部分支付状态,那么取消订单倒计时2天 - if *item.Status == int64(constants.STATUS_NEW_PART_PAY) { - surplusAt = (*item.Ctime + int64(constants.CANCLE_ORDER_EXPIRE)) - time.Now().UTC().Unix() - if surplusAt < 0 { - surplusAt = 0 - } - } + // //如果是部分支付状态,那么取消订单倒计时2天 + // if *item.Status == int64(constants.STATUS_NEW_PART_PAY) { + // surplusAt = (*item.Ctime + int64(constants.CANCLE_ORDER_EXPIRE)) - time.Now().UTC().Unix() + // if surplusAt < 0 { + // surplusAt = 0 + // } + // } - fsOrderAffiliateInfo := item.FsOrderAffiliateInfo + // fsOrderAffiliateInfo := item.FsOrderAffiliateInfo - var sureTime int64 - var productTime int64 - var ProductEndtime int64 - var deliverTime int64 - var upsDeliverTime int64 - var upsTime int64 - var arrivalTime int64 - var recevieTime int64 - if fsOrderAffiliateInfo.Id > 0 { - sureTime = *fsOrderAffiliateInfo.SureTime - productTime = *fsOrderAffiliateInfo.ProductTime - ProductEndtime = *fsOrderAffiliateInfo.ProductEndtime - deliverTime = *fsOrderAffiliateInfo.DeliverTime - upsDeliverTime = *fsOrderAffiliateInfo.UpsDeliverTime - upsTime = *fsOrderAffiliateInfo.UpsTime - arrivalTime = *fsOrderAffiliateInfo.ArrivalTime - recevieTime = *fsOrderAffiliateInfo.RecevieTime - } + // var sureTime int64 + // var productTime int64 + // var ProductEndtime int64 + // var deliverTime int64 + // var upsDeliverTime int64 + // var upsTime int64 + // var arrivalTime int64 + // var recevieTime int64 + // if fsOrderAffiliateInfo.Id > 0 { + // sureTime = *fsOrderAffiliateInfo.SureTime + // productTime = *fsOrderAffiliateInfo.ProductTime + // ProductEndtime = *fsOrderAffiliateInfo.ProductEndtime + // deliverTime = *fsOrderAffiliateInfo.DeliverTime + // upsDeliverTime = *fsOrderAffiliateInfo.UpsDeliverTime + // upsTime = *fsOrderAffiliateInfo.UpsTime + // arrivalTime = *fsOrderAffiliateInfo.ArrivalTime + // recevieTime = *fsOrderAffiliateInfo.RecevieTime + // } - var getOrderStatusAndLogisticsReq = order.GetOrderStatusAndLogisticsReq{ - OrderStatus: constants.Order(*item.Status), - DeliveryMethod: constants.DeliveryMethod(*item.DeliveryMethod), - IsPayCompleted: *item.IsAllProductCompleted, - OrderCtime: *item.Ctime, + // var getOrderStatusAndLogisticsReq = order.GetOrderStatusAndLogisticsReq{ + // OrderStatus: constants.Order(*item.Status), + // DeliveryMethod: constants.DeliveryMethod(*item.DeliveryMethod), + // IsPayCompleted: *item.IsAllProductCompleted, + // OrderCtime: *item.Ctime, - SureTime: sureTime, - ProductTime: productTime, - ProductEndtime: ProductEndtime, - DeliverTime: deliverTime, - UpsDeliverTime: upsDeliverTime, - UpsTime: upsTime, - ArrivalTime: arrivalTime, - RecevieTime: recevieTime, + // SureTime: sureTime, + // ProductTime: productTime, + // ProductEndtime: ProductEndtime, + // DeliverTime: deliverTime, + // UpsDeliverTime: upsDeliverTime, + // UpsTime: upsTime, + // ArrivalTime: arrivalTime, + // RecevieTime: recevieTime, - WebSetTimeInfo: orderTimeConfig, - } + // WebSetTimeInfo: orderTimeConfig, + // } - statusAndLogisticsRes := order.GetOrderStatusAndLogistics(getOrderStatusAndLogisticsReq) + // statusAndLogisticsRes := order.GetOrderStatusAndLogistics(getOrderStatusAndLogisticsReq) - // 流程控制 - var statusTime []types.StatusTime - for _, itemTimes := range statusAndLogisticsRes.Times { - statusTime = append(statusTime, types.StatusTime{ - Key: itemTimes.Key, - Time: itemTimes.Time, - }) - } - pbData.StatusTimes = statusTime - pbData.LogisticsStatus = int64(statusAndLogisticsRes.LogisticsStatus) - pbData.Status = int64(statusAndLogisticsRes.OrderStatus) + // // 流程控制 + // var statusTime []types.StatusTime + // for _, itemTimes := range statusAndLogisticsRes.Times { + // statusTime = append(statusTime, types.StatusTime{ + // Key: itemTimes.Key, + // Time: itemTimes.Time, + // }) + // } + // pbData.StatusTimes = statusTime + // pbData.LogisticsStatus = int64(statusAndLogisticsRes.LogisticsStatus) + // pbData.Status = int64(statusAndLogisticsRes.OrderStatus) - var isStopMax int64 - if len(item.FsOrderDetails) > 0 { - for _, fsOrderDetailItem := range item.FsOrderDetails { + // var isStopMax int64 + // if len(item.FsOrderDetails) > 0 { + // for _, fsOrderDetailItem := range item.FsOrderDetails { - fsOrderDetailBuyNum := *fsOrderDetailItem.FsOrderDetail.BuyNum - fsOrderDetailEachBoxNum := *fsOrderDetailItem.FsOrderDetailTemplateInfo.EachBoxNum - pcs = pcs + fsOrderDetailBuyNum - pcsBoxNum := fsOrderDetailBuyNum / fsOrderDetailEachBoxNum - var csBoxNumF int64 - if (fsOrderDetailBuyNum % fsOrderDetailEachBoxNum) > 0 { - csBoxNumF = 1 - } - pcsBox = pcsBox + pcsBoxNum + csBoxNumF + // fsOrderDetailBuyNum := *fsOrderDetailItem.FsOrderDetail.BuyNum + // fsOrderDetailEachBoxNum := *fsOrderDetailItem.FsOrderDetailTemplateInfo.EachBoxNum + // pcs = pcs + fsOrderDetailBuyNum + // pcsBoxNum := fsOrderDetailBuyNum / fsOrderDetailEachBoxNum + // var csBoxNumF int64 + // if (fsOrderDetailBuyNum % fsOrderDetailEachBoxNum) > 0 { + // csBoxNumF = 1 + // } + // pcsBox = pcsBox + pcsBoxNum + csBoxNumF - productCover := *fsOrderDetailItem.Cover - // 尺寸 - if size >= 200 { - coverArr := strings.Split(*fsOrderDetailItem.Cover, ".") - if len(coverArr) < 2 { - return resp.SetStatusWithMessage(basic.CodeServiceErr, "cover split slice item count is less than 2") - } - productCover = fmt.Sprintf("%s_%d.%s", coverArr[0], req.Size, coverArr[1]) - } + // productCover := *fsOrderDetailItem.Cover + // // 尺寸 + // if size >= 200 { + // coverArr := strings.Split(*fsOrderDetailItem.Cover, ".") + // if len(coverArr) < 2 { + // return resp.SetStatusWithMessage(basic.CodeServiceErr, "cover split slice item count is less than 2") + // } + // productCover = fmt.Sprintf("%s_%d.%s", coverArr[0], req.Size, coverArr[1]) + // } - // 判断stop - var isStop int64 - if fsOrderDetailItem.FsOrderDetailTemplateInfo.FsProductDesignInfo.OptionData.Id != 0 { - // 尺寸或者模板下架 - if fsOrderDetailItem.FsOrderDetailTemplateInfo.FsProductDesignInfo.Id != 0 { - isStop = 1 - } else { - isStop = 3 - } - } else { - if fsOrderDetailItem.FsOrderDetailTemplateInfo.FsProductDesignInfo.Id != 0 { - isStop = 1 - } - } + // // 判断stop + // var isStop int64 + // if fsOrderDetailItem.FsOrderDetailTemplateInfo.FsProductDesignInfo.OptionData.Id != 0 { + // // 尺寸或者模板下架 + // if fsOrderDetailItem.FsOrderDetailTemplateInfo.FsProductDesignInfo.Id != 0 { + // isStop = 1 + // } else { + // isStop = 3 + // } + // } else { + // if fsOrderDetailItem.FsOrderDetailTemplateInfo.FsProductDesignInfo.Id != 0 { + // isStop = 1 + // } + // } - // 判断产品是否下架 - if *fsOrderDetailItem.FsProductInfo.IsShelf == 0 || *fsOrderDetailItem.FsProductInfo.IsDel == 1 { - isStop = 2 - } - if isStop > isStopMax { - isStopMax = isStop - } + // // 判断产品是否下架 + // if *fsOrderDetailItem.FsProductInfo.IsShelf == 0 || *fsOrderDetailItem.FsProductInfo.IsDel == 1 { + // isStop = 2 + // } + // if isStop > isStopMax { + // isStopMax = isStop + // } - productList = append(productList, types.Product{ - Cover: productCover, - Fitting: *fsOrderDetailItem.OptionalTitle, - OptionPrice: *fsOrderDetailItem.OptionPrice, - OrderDetailTemplateId: *fsOrderDetailItem.OrderDetailTemplateId, - OrderId: *fsOrderDetailItem.OrderId, - Pcs: fsOrderDetailBuyNum, - PcsBox: pcsBox, - Price: *fsOrderDetailItem.FsOrderDetail.Amount, - ProductId: *fsOrderDetailItem.OptionPrice, - Title: *fsOrderDetailItem.FsProductInfo.Title, - Size: *fsOrderDetailItem.FsOrderDetailTemplateInfo.FsProductSizeInfo.Capacity, - IsStop: isStop, - }) - } - pbData.ProductList = productList - } + // productList = append(productList, types.Product{ + // Cover: productCover, + // Fitting: *fsOrderDetailItem.OptionalTitle, + // OptionPrice: *fsOrderDetailItem.OptionPrice, + // OrderDetailTemplateId: *fsOrderDetailItem.OrderDetailTemplateId, + // OrderId: *fsOrderDetailItem.OrderId, + // Pcs: fsOrderDetailBuyNum, + // PcsBox: pcsBox, + // Price: *fsOrderDetailItem.FsOrderDetail.Amount, + // ProductId: *fsOrderDetailItem.OptionPrice, + // Title: *fsOrderDetailItem.FsProductInfo.Title, + // Size: *fsOrderDetailItem.FsOrderDetailTemplateInfo.FsProductSizeInfo.Capacity, + // IsStop: isStop, + // }) + // } + // pbData.ProductList = productList + // } - pbData.IsStop = isStopMax - pbData.PcsBox = pcsBox - pbData.Pcs = pcs - pbData.SurplusAt = surplusAt - pbData.Deposit = *item.TotalAmount / 2 - pbData.Remaining = pbData.Deposit - respList = append(respList, pbData) - } + // pbData.IsStop = isStopMax + // pbData.PcsBox = pcsBox + // pbData.Pcs = pcs + // pbData.SurplusAt = surplusAt + // pbData.Deposit = *item.TotalAmount / 2 + // pbData.Remaining = pbData.Deposit + // respList = append(respList, pbData) + // } - } + // } - return resp.SetStatusWithMessage(basic.CodeOK, "success", types.UserOrderListRsp{ - Items: respList, - Meta: types.Meta{ - TotalCount: total, - PageCount: int64(math.Ceil(float64(total) / float64(pageSize))), - CurrentPage: int(page), - PerPage: int(pageSize), - }, - }) + // return resp.SetStatusWithMessage(basic.CodeOK, "success", types.UserOrderListRsp{ + // Items: respList, + // Meta: types.Meta{ + // TotalCount: total, + // PageCount: int64(math.Ceil(float64(total) / float64(pageSize))), + // CurrentPage: int(page), + // PerPage: int(pageSize), + // }, + // }) + return resp.SetStatusWithMessage(basic.CodeOK, "success") } diff --git a/server/pay/internal/logic/orderpaymentintentlogic.go b/server/pay/internal/logic/orderpaymentintentlogic.go index 35b4484d..23f5d8e8 100644 --- a/server/pay/internal/logic/orderpaymentintentlogic.go +++ b/server/pay/internal/logic/orderpaymentintentlogic.go @@ -1,13 +1,8 @@ package logic import ( - "errors" - "fusenapi/constants" - "fusenapi/model/gmodel" "fusenapi/utils/auth" "fusenapi/utils/basic" - "fusenapi/utils/pay" - "time" "context" @@ -15,7 +10,6 @@ import ( "fusenapi/server/pay/internal/types" "github.com/zeromicro/go-zero/core/logx" - "gorm.io/gorm" ) type OrderPaymentIntentLogic struct { @@ -45,143 +39,143 @@ func (l *OrderPaymentIntentLogic) OrderPaymentIntent(req *types.OrderPaymentInte // 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data) // userinfo 传入值时, 一定不为null - if userinfo == nil || userinfo.UserId == 0 { - return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found") - } + // if userinfo == nil || userinfo.UserId == 0 { + // return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found") + // } - // 查询订单数据 - orderModel := gmodel.NewFsOrderModel(l.svcCtx.MysqlConn) - orderInfo, err := orderModel.FindOneBySn(l.ctx, userinfo.UserId, req.Sn) + // // 查询订单数据 + // orderModel := gmodel.NewFsOrderModel(l.svcCtx.MysqlConn) + // orderInfo, err := orderModel.FindOneBySn(l.ctx, userinfo.UserId, req.Sn) - if err != nil { - if errors.Is(err, gorm.ErrRecordNotFound) { - return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found") - } - logx.Error(err) - return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get order info") - } + // if err != nil { + // if errors.Is(err, gorm.ErrRecordNotFound) { + // return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order not found") + // } + // logx.Error(err) + // return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get order info") + // } - // 校验订单状态 - if *orderInfo.IsCancel == 1 { - return resp.SetStatusWithMessage(basic.CodeServiceErr, "order cancelled") - } + // // 校验订单状态 + // if *orderInfo.IsCancel == 1 { + // return resp.SetStatusWithMessage(basic.CodeServiceErr, "order cancelled") + // } - // 校验地址信息 - addressModel := gmodel.NewFsAddressModel(l.svcCtx.MysqlConn) - _, err = addressModel.GetOne(l.ctx, req.AddressId, userinfo.UserId) + // // 校验地址信息 + // addressModel := gmodel.NewFsAddressModel(l.svcCtx.MysqlConn) + // _, err = addressModel.GetOne(l.ctx, req.AddressId, userinfo.UserId) - if err != nil { - if errors.Is(err, gorm.ErrRecordNotFound) { - return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "address not found") - } - logx.Error(err) - return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get address info") - } + // if err != nil { + // if errors.Is(err, gorm.ErrRecordNotFound) { + // return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "address not found") + // } + // logx.Error(err) + // return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get address info") + // } - // 校验订单支付信息 - if *orderInfo.IsPayCompleted == 1 { - return resp.SetStatusWithMessage(basic.CodeServiceErr, "order is pay completed") - } + // // 校验订单支付信息 + // if *orderInfo.IsPayCompleted == 1 { + // return resp.SetStatusWithMessage(basic.CodeServiceErr, "order is pay completed") + // } - // 判断订单状态以及该支付金额 - var nowAt int64 = time.Now().UTC().Unix() - var payAmount int64 - if *orderInfo.Status == int64(constants.STATUS_NEW_NOT_PAY) { - payAmount = *orderInfo.TotalAmount / 2 - *orderInfo.DeliveryMethod = req.DeliveryMethod - *orderInfo.AddressId = req.AddressId - *orderInfo.PayMethod = req.PayMethod - } else { - payAmount = *orderInfo.TotalAmount - *orderInfo.TotalAmount/2 - } + // // 判断订单状态以及该支付金额 + // var nowAt int64 = time.Now().UTC().Unix() + // var payAmount int64 + // if *orderInfo.Status == int64(constants.STATUS_NEW_NOT_PAY) { + // payAmount = *orderInfo.TotalAmount / 2 + // *orderInfo.DeliveryMethod = req.DeliveryMethod + // *orderInfo.AddressId = req.AddressId + // *orderInfo.PayMethod = req.PayMethod + // } else { + // payAmount = *orderInfo.TotalAmount - *orderInfo.TotalAmount/2 + // } - payConfig := &pay.Config{} - var generatePrepaymentReq = &pay.GeneratePrepaymentReq{ - OrderSn: req.Sn, - ProductName: "支付标题", - Amount: payAmount, - Currency: "eur", - Quantity: 1, - ProductDescription: "支付描述", - } + // payConfig := &pay.Config{} + // var generatePrepaymentReq = &pay.GeneratePrepaymentReq{ + // OrderSn: req.Sn, + // ProductName: "支付标题", + // Amount: payAmount, + // Currency: "eur", + // Quantity: 1, + // ProductDescription: "支付描述", + // } - var resData types.OrderPaymentIntentRes - // 事务处理 - ctx := l.ctx - err = l.svcCtx.MysqlConn.Transaction(func(connGorm *gorm.DB) error { - // 支付记录--处理 //支付记录改为一条订单多条,分首款尾款 - var payStatus int64 = 0 - var orderSource int64 = 1 - var payStage int64 - var fspay *gmodel.FsPay - newFsPayModel := gmodel.NewFsPayModel(connGorm) - if *orderInfo.Status == int64(constants.STATUS_NEW_NOT_PAY) { - fspay, err = newFsPayModel.RBGetListByOrderNumberStage(ctx, *orderInfo.Sn, 1) - if err != nil { - if !errors.Is(err, gorm.ErrRecordNotFound) { - return err - } - } - payStage = 1 - } else { - fspay, err = newFsPayModel.RBGetListByOrderNumberStage(ctx, *orderInfo.Sn, 2) - if err != nil { - if !errors.Is(err, gorm.ErrRecordNotFound) { - return err - } - } - payStage = 2 - } + // var resData types.OrderPaymentIntentRes + // // 事务处理 + // ctx := l.ctx + // err = l.svcCtx.MysqlConn.Transaction(func(connGorm *gorm.DB) error { + // // 支付记录--处理 //支付记录改为一条订单多条,分首款尾款 + // var payStatus int64 = 0 + // var orderSource int64 = 1 + // var payStage int64 + // var fspay *gmodel.FsPay + // newFsPayModel := gmodel.NewFsPayModel(connGorm) + // if *orderInfo.Status == int64(constants.STATUS_NEW_NOT_PAY) { + // fspay, err = newFsPayModel.RBGetListByOrderNumberStage(ctx, *orderInfo.Sn, 1) + // if err != nil { + // if !errors.Is(err, gorm.ErrRecordNotFound) { + // return err + // } + // } + // payStage = 1 + // } else { + // fspay, err = newFsPayModel.RBGetListByOrderNumberStage(ctx, *orderInfo.Sn, 2) + // if err != nil { + // if !errors.Is(err, gorm.ErrRecordNotFound) { + // return err + // } + // } + // payStage = 2 + // } - // 支付预付--生成 - if constants.PayMethod(req.PayMethod) == constants.PAYMETHOD_STRIPE { - payConfig.Stripe.Key = l.svcCtx.Config.PayConfig.Stripe.Key - generatePrepaymentReq.SuccessURL = l.svcCtx.Config.PayConfig.Stripe.SuccessURL - generatePrepaymentReq.CancelURL = l.svcCtx.Config.PayConfig.Stripe.CancelURL - } - payDriver := pay.NewPayDriver(req.PayMethod, payConfig) - prepaymentRes, err := payDriver.GeneratePrepayment(generatePrepaymentReq) - if err != nil { - return err - } + // // 支付预付--生成 + // if constants.PayMethod(req.PayMethod) == constants.PAYMETHOD_STRIPE { + // payConfig.Stripe.Key = l.svcCtx.Config.PayConfig.Stripe.Key + // generatePrepaymentReq.SuccessURL = l.svcCtx.Config.PayConfig.Stripe.SuccessURL + // generatePrepaymentReq.CancelURL = l.svcCtx.Config.PayConfig.Stripe.CancelURL + // } + // payDriver := pay.NewPayDriver(req.PayMethod, payConfig) + // prepaymentRes, err := payDriver.GeneratePrepayment(generatePrepaymentReq) + // if err != nil { + // return err + // } - // 订单信息--修改 - err = gmodel.NewFsOrderModel(connGorm).RBUpdate(ctx, orderInfo) - if err != nil { - return err - } + // // 订单信息--修改 + // err = gmodel.NewFsOrderModel(connGorm).RBUpdate(ctx, orderInfo) + // if err != nil { + // return err + // } - if fspay == nil { - fspay = &gmodel.FsPay{ - UserId: orderInfo.UserId, - OrderNumber: orderInfo.Sn, - CreatedAt: &nowAt, - } - } else { - fspay.UpdatedAt = &nowAt - } - fspay.PayAmount = &payAmount - fspay.PayStage = &payStage - //fspay.TradeNo = &prepaymentRes.TradeNo - fspay.PaymentMethod = &req.PayMethod - fspay.OrderSource = &orderSource - fspay.PayStatus = &payStatus + // if fspay == nil { + // fspay = &gmodel.FsPay{ + // UserId: orderInfo.UserId, + // OrderNumber: orderInfo.Sn, + // CreatedAt: &nowAt, + // } + // } else { + // fspay.UpdatedAt = &nowAt + // } + // fspay.PayAmount = &payAmount + // fspay.PayStage = &payStage + // //fspay.TradeNo = &prepaymentRes.TradeNo + // fspay.PaymentMethod = &req.PayMethod + // fspay.OrderSource = &orderSource + // fspay.PayStatus = &payStatus - _, err = newFsPayModel.RBCreateOrUpdate(ctx, fspay) - if err != nil { - return err - } + // _, err = newFsPayModel.RBCreateOrUpdate(ctx, fspay) + // if err != nil { + // return err + // } - resData.RedirectUrl = prepaymentRes.URL - resData.ClientSecret = prepaymentRes.ClientSecret + // resData.RedirectUrl = prepaymentRes.URL + // resData.ClientSecret = prepaymentRes.ClientSecret - return nil - }) + // return nil + // }) - if err != nil { - logx.Error(err) - return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to make payment") - } + // if err != nil { + // logx.Error(err) + // return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to make payment") + // } - return resp.SetStatusWithMessage(basic.CodeOK, "success", resData) + return resp.SetStatusWithMessage(basic.CodeOK, "success") } diff --git a/server/pay/internal/logic/stripewebhooklogic.go b/server/pay/internal/logic/stripewebhooklogic.go index e191b64b..05572894 100644 --- a/server/pay/internal/logic/stripewebhooklogic.go +++ b/server/pay/internal/logic/stripewebhooklogic.go @@ -1,13 +1,9 @@ package logic import ( - "encoding/json" - "errors" - "fusenapi/constants" "fusenapi/model/gmodel" "fusenapi/utils/auth" "fusenapi/utils/basic" - "time" "context" @@ -15,9 +11,7 @@ import ( "fusenapi/server/pay/internal/types" "github.com/stripe/stripe-go/v74" - "github.com/stripe/stripe-go/v74/webhook" "github.com/zeromicro/go-zero/core/logx" - "gorm.io/gorm" ) type StripeWebhookLogic struct { @@ -48,97 +42,97 @@ func (l *StripeWebhookLogic) StripeWebhook(req *types.StripeWebhookReq, userinfo // 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data) // userinfo 传入值时, 一定不为null - stripe.Key = l.svcCtx.Config.PayConfig.Stripe.Key - event := stripe.Event{} + // stripe.Key = l.svcCtx.Config.PayConfig.Stripe.Key + // event := stripe.Event{} - if err := json.Unmarshal(req.Payload, &event); err != nil { - logx.Error(err) - return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail") - } + // if err := json.Unmarshal(req.Payload, &event); err != nil { + // logx.Error(err) + // return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail") + // } - endpointSecret := l.svcCtx.Config.PayConfig.Stripe.EndpointSecret - signatureHeader := req.StripeSignature - event, err := webhook.ConstructEvent(req.Payload, signatureHeader, endpointSecret) - if err != nil { - logx.Error(err) - return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "Webhook signature verification failed") - } + // endpointSecret := l.svcCtx.Config.PayConfig.Stripe.EndpointSecret + // signatureHeader := req.StripeSignature + // event, err := webhook.ConstructEvent(req.Payload, signatureHeader, endpointSecret) + // if err != nil { + // logx.Error(err) + // return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "Webhook signature verification failed") + // } - // 新增支付回调事件日志 - var payMethod = int64(constants.PAYMETHOD_STRIPE) - var nowTime = time.Now().UTC().Unix() - var eventData = string(event.Data.Raw) - var fsPayEvent = &gmodel.FsPayEvent{ - PayMethod: &payMethod, - EventId: &event.ID, - EventType: &event.Type, - EventData: &eventData, - EventCreated: &event.Created, - Ip: &req.RemoteAddr, - CreatedAt: &nowTime, - } - l.HandlePayEventCreate(fsPayEvent) + // // 新增支付回调事件日志 + // var payMethod = int64(constants.PAYMETHOD_STRIPE) + // var nowTime = time.Now().UTC().Unix() + // var eventData = string(event.Data.Raw) + // var fsPayEvent = &gmodel.FsPayEvent{ + // PayMethod: &payMethod, + // EventId: &event.ID, + // EventType: &event.Type, + // EventData: &eventData, + // EventCreated: &event.Created, + // Ip: &req.RemoteAddr, + // CreatedAt: &nowTime, + // } + // l.HandlePayEventCreate(fsPayEvent) - // Unmarshal the event data into an appropriate struct depending on its Type - switch event.Type { - case "charge.succeeded": - // var charge stripe.Charge - // err := json.Unmarshal(event.Data.Raw, &charge) - // if err != nil { - // logx.Error(err) - // return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail event.Type charge.succeeded") - // } + // // Unmarshal the event data into an appropriate struct depending on its Type + // switch event.Type { + // case "charge.succeeded": + // // var charge stripe.Charge + // // err := json.Unmarshal(event.Data.Raw, &charge) + // // if err != nil { + // // logx.Error(err) + // // return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail event.Type charge.succeeded") + // // } - case "checkout.session.completed": - // checkout checkout.session.completed 处理逻辑 - // var session stripe.CheckoutSession - // err := json.Unmarshal(event.Data.Raw, &session) - // if err != nil { - // logx.Error(err) - // return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail event.Type payment_intent.succeeded") - // } - // fmt.Println("checkout.session.completed") - // err = l.handlePaymentSessionCompleted(session.ID, session.PaymentIntent.ID) - // if err != nil { - // return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "checkout.session.completed fail") - // } - case "payment_intent.succeeded": - var paymentIntent stripe.PaymentIntent - err := json.Unmarshal(event.Data.Raw, &paymentIntent) - if err != nil { - logx.Errorf("err:%+v,desc:%s", err, "pay notify Unmarshal fail event.Type payment_intent.succeeded") - return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail event.Type payment_intent.succeeded") - } - err = l.HandlePaymentIntentSucceeded(&paymentIntent) - if err != nil { - logx.Errorf("err:%+v,desc:%s", err, "pay notify handle payment_intent.succeeded") - return resp.SetStatusWithMessage(basic.CodePaybackNotOk, "pay notify handle payment_intent.succeeded") - } - case "payment_method.attached": - var paymentMethod stripe.PaymentMethod - err := json.Unmarshal(event.Data.Raw, &paymentMethod) - if err != nil { - logx.Error(err) - return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail event.Type payment_method.attached") - } - case "charge.refunded": - var chargeRefunded stripe.Charge - err := json.Unmarshal(event.Data.Raw, &chargeRefunded) - if err != nil { - logx.Errorf("err:%+v,desc:%s", err, "pay notify Unmarshal fail event.Type charge.refunded") - return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail event.Type charge.refunded") - } - err = l.HandleChargeRefunded(&chargeRefunded) - if err != nil { - logx.Errorf("err:%+v,desc:%s", err, "pay notify handle charge.refunded") - return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify handle charge.refunded") - } + // case "checkout.session.completed": + // // checkout checkout.session.completed 处理逻辑 + // // var session stripe.CheckoutSession + // // err := json.Unmarshal(event.Data.Raw, &session) + // // if err != nil { + // // logx.Error(err) + // // return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail event.Type payment_intent.succeeded") + // // } + // // fmt.Println("checkout.session.completed") + // // err = l.handlePaymentSessionCompleted(session.ID, session.PaymentIntent.ID) + // // if err != nil { + // // return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "checkout.session.completed fail") + // // } + // case "payment_intent.succeeded": + // var paymentIntent stripe.PaymentIntent + // err := json.Unmarshal(event.Data.Raw, &paymentIntent) + // if err != nil { + // logx.Errorf("err:%+v,desc:%s", err, "pay notify Unmarshal fail event.Type payment_intent.succeeded") + // return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail event.Type payment_intent.succeeded") + // } + // err = l.HandlePaymentIntentSucceeded(&paymentIntent) + // if err != nil { + // logx.Errorf("err:%+v,desc:%s", err, "pay notify handle payment_intent.succeeded") + // return resp.SetStatusWithMessage(basic.CodePaybackNotOk, "pay notify handle payment_intent.succeeded") + // } + // case "payment_method.attached": + // var paymentMethod stripe.PaymentMethod + // err := json.Unmarshal(event.Data.Raw, &paymentMethod) + // if err != nil { + // logx.Error(err) + // return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail event.Type payment_method.attached") + // } + // case "charge.refunded": + // var chargeRefunded stripe.Charge + // err := json.Unmarshal(event.Data.Raw, &chargeRefunded) + // if err != nil { + // logx.Errorf("err:%+v,desc:%s", err, "pay notify Unmarshal fail event.Type charge.refunded") + // return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail event.Type charge.refunded") + // } + // err = l.HandleChargeRefunded(&chargeRefunded) + // if err != nil { + // logx.Errorf("err:%+v,desc:%s", err, "pay notify handle charge.refunded") + // return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify handle charge.refunded") + // } - // ... handle other event types - default: - logx.Error("Unhandled event") - return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail event.Type Unhandled") - } + // // ... handle other event types + // default: + // logx.Error("Unhandled event") + // return resp.SetStatusWithMessage(basic.CodeAesCbcDecryptionErr, "pay notify Unmarshal fail event.Type Unhandled") + // } return resp.SetStatus(basic.CodeOK) } @@ -151,62 +145,62 @@ func (l *StripeWebhookLogic) HandlePayEventCreate(fsPayEvent *gmodel.FsPayEvent) // 退款成功 func (l *StripeWebhookLogic) HandleChargeRefunded(chargeRefunded *stripe.Charge) (err error) { - // 退款成功 - if chargeRefunded.Status == "succeeded" { - ctx := l.ctx - err = l.svcCtx.MysqlConn.Transaction(func(connGorm *gorm.DB) error { - // 查询支付记录 - payModelT := gmodel.NewFsPayModel(connGorm) - payModelTRSB := payModelT.BuilderTrans(nil) - payModelTRSB1 := payModelTRSB.Where("trade_no = ?", chargeRefunded.PaymentIntent.ID).Where("pay_status = ?", constants.PAYSTATUS_SUCCESS).Where("is_refund = ?", 0) - payInfo, err := payModelT.FindOneByQuery(ctx, payModelTRSB1, nil) - if err != nil { - return err - } - // 更新支付记录 - *payInfo.IsRefund = 1 - _, err = payModelT.RBCreateOrUpdate(ctx, payInfo) - if err != nil { - return err - } - // 获取是否还有未退款的数据 - payModelTRSB2 := payModelTRSB.Where("order_number = ?", payInfo.OrderNumber).Where("pay_status = ?", constants.PAYSTATUS_SUCCESS).Where("is_refund = ?", 0) - count, err := payModelT.FindCount(l.ctx, payModelTRSB2, nil) - if count == 0 { - // 退款完成更新订单状态 - orderModelT := gmodel.NewFsOrderModel(connGorm) - orderModelTRSB := orderModelT.BuilderTrans(nil).Where("sn =?", payInfo.OrderNumber) - orderInfoRel, err := orderModelT.FindOneByQuery(ctx, orderModelTRSB, nil) - if err != nil { - return err - } - var isRefunded int64 = 1 - var isRefunding int64 = 1 - var orderStatus int64 = int64(constants.STATUS_NEW_REFUNDED) - var orderInfo = &gmodel.FsOrder{} - orderInfo.Id = orderInfoRel.Id - orderInfo.IsRefunded = &isRefunded - orderInfo.IsRefunding = &isRefunding - orderInfo.Status = &orderStatus - orderModelT.Update(ctx, orderInfo) + // // 退款成功 + // if chargeRefunded.Status == "succeeded" { + // ctx := l.ctx + // err = l.svcCtx.MysqlConn.Transaction(func(connGorm *gorm.DB) error { + // // 查询支付记录 + // payModelT := gmodel.NewFsPayModel(connGorm) + // payModelTRSB := payModelT.BuilderTrans(nil) + // payModelTRSB1 := payModelTRSB.Where("trade_no = ?", chargeRefunded.PaymentIntent.ID).Where("pay_status = ?", constants.PAYSTATUS_SUCCESS).Where("is_refund = ?", 0) + // payInfo, err := payModelT.FindOneByQuery(ctx, payModelTRSB1, nil) + // if err != nil { + // return err + // } + // // 更新支付记录 + // *payInfo.IsRefund = 1 + // _, err = payModelT.RBCreateOrUpdate(ctx, payInfo) + // if err != nil { + // return err + // } + // // 获取是否还有未退款的数据 + // payModelTRSB2 := payModelTRSB.Where("order_number = ?", payInfo.OrderNumber).Where("pay_status = ?", constants.PAYSTATUS_SUCCESS).Where("is_refund = ?", 0) + // count, err := payModelT.FindCount(l.ctx, payModelTRSB2, nil) + // if count == 0 { + // // 退款完成更新订单状态 + // orderModelT := gmodel.NewFsOrderModel(connGorm) + // orderModelTRSB := orderModelT.BuilderTrans(nil).Where("sn =?", payInfo.OrderNumber) + // orderInfoRel, err := orderModelT.FindOneByQuery(ctx, orderModelTRSB, nil) + // if err != nil { + // return err + // } + // var isRefunded int64 = 1 + // var isRefunding int64 = 1 + // var orderStatus int64 = int64(constants.STATUS_NEW_REFUNDED) + // var orderInfo = &gmodel.FsOrder{} + // orderInfo.Id = orderInfoRel.Id + // orderInfo.IsRefunded = &isRefunded + // orderInfo.IsRefunding = &isRefunding + // orderInfo.Status = &orderStatus + // orderModelT.Update(ctx, orderInfo) - // 记录退款原因 - refundReasonModelT := gmodel.NewFsRefundReasonModel(connGorm) - refundReasonModelTRSB := refundReasonModelT.BuilderTrans(nil) - refundReasonModelTRSB1 := refundReasonModelTRSB.Where("order_id =?", orderInfoRel.Id) - refundReasonInfo, err := refundReasonModelT.FindOneByQuery(ctx, refundReasonModelTRSB1, nil) - if err != nil { - return err - } - *refundReasonInfo.IsRefund = 1 - _, err = refundReasonModelT.RBCreateOrUpdate(ctx, refundReasonInfo) - if err != nil { - return err - } - } - return err - }) - } + // // 记录退款原因 + // refundReasonModelT := gmodel.NewFsRefundReasonModel(connGorm) + // refundReasonModelTRSB := refundReasonModelT.BuilderTrans(nil) + // refundReasonModelTRSB1 := refundReasonModelTRSB.Where("order_id =?", orderInfoRel.Id) + // refundReasonInfo, err := refundReasonModelT.FindOneByQuery(ctx, refundReasonModelTRSB1, nil) + // if err != nil { + // return err + // } + // *refundReasonInfo.IsRefund = 1 + // _, err = refundReasonModelT.RBCreateOrUpdate(ctx, refundReasonInfo) + // if err != nil { + // return err + // } + // } + // return err + // }) + // } return err } @@ -234,160 +228,160 @@ func (l *StripeWebhookLogic) HandleChargeRefunded(chargeRefunded *stripe.Charge) // 付款成功 func (l *StripeWebhookLogic) HandlePaymentIntentSucceeded(paymentIntent *stripe.PaymentIntent) error { - orderSn, ok := paymentIntent.Metadata["order_sn"] - if !ok || orderSn == "" { - return errors.New("order_sn not found") - } + // orderSn, ok := paymentIntent.Metadata["order_sn"] + // if !ok || orderSn == "" { + // return errors.New("order_sn not found") + // } - // 查询支付记录 - payModel := gmodel.NewFsPayModel(l.svcCtx.MysqlConn) - rsbPay := payModel.RowSelectBuilder(nil) - rsbPay = rsbPay.Where("order_number = ?", orderSn).Where("pay_status = ?", constants.PAYSTATUS_UNSUCCESS) - payInfo, err := payModel.FindOneByQuery(l.ctx, rsbPay, nil) - if err != nil { - return err - } + // // 查询支付记录 + // payModel := gmodel.NewFsPayModel(l.svcCtx.MysqlConn) + // rsbPay := payModel.RowSelectBuilder(nil) + // rsbPay = rsbPay.Where("order_number = ?", orderSn).Where("pay_status = ?", constants.PAYSTATUS_UNSUCCESS) + // payInfo, err := payModel.FindOneByQuery(l.ctx, rsbPay, nil) + // if err != nil { + // return err + // } - //订单信息 - orderDetailTemplateModel := gmodel.NewFsOrderDetailTemplateModel(l.svcCtx.MysqlConn) - orderModel := gmodel.NewFsOrderModel(l.svcCtx.MysqlConn) - fsOrderDetailModel := gmodel.NewFsOrderDetailModel(l.svcCtx.MysqlConn) - fsProductDesignModel := gmodel.NewFsProductDesignModel(l.svcCtx.MysqlConn) + // //订单信息 + // orderDetailTemplateModel := gmodel.NewFsOrderDetailTemplateModel(l.svcCtx.MysqlConn) + // orderModel := gmodel.NewFsOrderModel(l.svcCtx.MysqlConn) + // fsOrderDetailModel := gmodel.NewFsOrderDetailModel(l.svcCtx.MysqlConn) + // fsProductDesignModel := gmodel.NewFsProductDesignModel(l.svcCtx.MysqlConn) - rsbOrder := orderModel.RowSelectBuilder(nil) - rsbOrder = rsbOrder.Where("sn =?", orderSn).Preload("FsOrderDetails") - rsbOrder = rsbOrder.Preload("FsOrderDetails", func(dbPreload *gorm.DB) *gorm.DB { - return dbPreload.Table(fsOrderDetailModel.TableName()).Preload("FsOrderDetailTemplateInfo", func(dbPreload *gorm.DB) *gorm.DB { - return dbPreload.Table(orderDetailTemplateModel.TableName()).Preload("FsProductDesignInfo", func(dbPreload *gorm.DB) *gorm.DB { - return dbPreload.Table(fsProductDesignModel.TableName()) - }) - }) - }) - fsOrderRelInfo, err := orderModel.FindOneByQuery(l.ctx, rsbOrder, nil) - if err != nil { - return err - } + // rsbOrder := orderModel.RowSelectBuilder(nil) + // rsbOrder = rsbOrder.Where("sn =?", orderSn).Preload("FsOrderDetails") + // rsbOrder = rsbOrder.Preload("FsOrderDetails", func(dbPreload *gorm.DB) *gorm.DB { + // return dbPreload.Table(fsOrderDetailModel.TableName()).Preload("FsOrderDetailTemplateInfo", func(dbPreload *gorm.DB) *gorm.DB { + // return dbPreload.Table(orderDetailTemplateModel.TableName()).Preload("FsProductDesignInfo", func(dbPreload *gorm.DB) *gorm.DB { + // return dbPreload.Table(fsProductDesignModel.TableName()) + // }) + // }) + // }) + // fsOrderRelInfo, err := orderModel.FindOneByQuery(l.ctx, rsbOrder, nil) + // if err != nil { + // return err + // } - var designIds []int64 - var cartIds []int64 - if len(fsOrderRelInfo.FsOrderDetails) > 0 { - for _, fsOrderDetail := range fsOrderRelInfo.FsOrderDetails { - if fsOrderDetail.FsOrderDetailTemplateInfo.FsProductDesignInfo.Id != 0 { - designIds = append(designIds, fsOrderDetail.FsOrderDetailTemplateInfo.FsProductDesignInfo.Id) - } - cartIds = append(cartIds, *fsOrderDetail.CartId) - } - } + // var designIds []int64 + // var cartIds []int64 + // if len(fsOrderRelInfo.FsOrderDetails) > 0 { + // for _, fsOrderDetail := range fsOrderRelInfo.FsOrderDetails { + // if fsOrderDetail.FsOrderDetailTemplateInfo.FsProductDesignInfo.Id != 0 { + // designIds = append(designIds, fsOrderDetail.FsOrderDetailTemplateInfo.FsProductDesignInfo.Id) + // } + // cartIds = append(cartIds, *fsOrderDetail.CartId) + // } + // } - var nowTime int64 = time.Now().UTC().Unix() + // var nowTime int64 = time.Now().UTC().Unix() - // 支付成功 - if paymentIntent.Status == "succeeded" { - var card string - var brand string - if paymentIntent.LatestCharge.PaymentMethodDetails != nil { - if paymentIntent.LatestCharge.PaymentMethodDetails.Card != nil { - if paymentIntent.LatestCharge.PaymentMethodDetails.Card.Last4 != "" { - card = paymentIntent.LatestCharge.PaymentMethodDetails.Card.Last4 - } - if paymentIntent.LatestCharge.PaymentMethodDetails.Card.Brand != "" { - brand = string(paymentIntent.LatestCharge.PaymentMethodDetails.Card.Brand) - } - } - } + // // 支付成功 + // if paymentIntent.Status == "succeeded" { + // var card string + // var brand string + // if paymentIntent.LatestCharge.PaymentMethodDetails != nil { + // if paymentIntent.LatestCharge.PaymentMethodDetails.Card != nil { + // if paymentIntent.LatestCharge.PaymentMethodDetails.Card.Last4 != "" { + // card = paymentIntent.LatestCharge.PaymentMethodDetails.Card.Last4 + // } + // if paymentIntent.LatestCharge.PaymentMethodDetails.Card.Brand != "" { + // brand = string(paymentIntent.LatestCharge.PaymentMethodDetails.Card.Brand) + // } + // } + // } - ctx := l.ctx - err = l.svcCtx.MysqlConn.Transaction(func(connGorm *gorm.DB) error { - // 更新支付信息 - payModelT := gmodel.NewFsPayModel(connGorm) - *payInfo.PayStatus = 1 - *payInfo.PayTime = nowTime - *payInfo.CardNo = card - *payInfo.Brand = brand - *payInfo.TradeNo = paymentIntent.ID - _, err = payModelT.RBCreateOrUpdate(ctx, payInfo) - if err != nil { - return err - } + // ctx := l.ctx + // err = l.svcCtx.MysqlConn.Transaction(func(connGorm *gorm.DB) error { + // // 更新支付信息 + // payModelT := gmodel.NewFsPayModel(connGorm) + // *payInfo.PayStatus = 1 + // *payInfo.PayTime = nowTime + // *payInfo.CardNo = card + // *payInfo.Brand = brand + // *payInfo.TradeNo = paymentIntent.ID + // _, err = payModelT.RBCreateOrUpdate(ctx, payInfo) + // if err != nil { + // return err + // } - // 更新设计数据 - productDesignModelT := gmodel.NewFsProductDesignModel(connGorm) - productDesignModelTRSB := productDesignModelT.BuilderTrans(ctx, nil) - var isPay int64 = 1 - err = productDesignModelT.RBUpdateByIds(productDesignModelTRSB, designIds, &gmodel.FsProductDesign{IsPay: &isPay}) - if err != nil { - return err - } + // // 更新设计数据 + // productDesignModelT := gmodel.NewFsProductDesignModel(connGorm) + // productDesignModelTRSB := productDesignModelT.BuilderTrans(ctx, nil) + // var isPay int64 = 1 + // err = productDesignModelT.RBUpdateByIds(productDesignModelTRSB, designIds, &gmodel.FsProductDesign{IsPay: &isPay}) + // if err != nil { + // return err + // } - var orderInfo = &gmodel.FsOrder{} - var orderStatus int64 - var orderIsPartPay int64 - var orderPayedAmount int64 - var orderIsPayCompleted int64 - // 支付记录是首款 - if *payInfo.PayStage == int64(constants.PAYSTAGE_DEPOSIT) { - orderStatus = int64(constants.STATUS_NEW_PART_PAY) - orderIsPartPay = 1 - orderInfo.IsPartPay = &orderIsPartPay - orderPayedAmount = paymentIntent.Amount + // var orderInfo = &gmodel.FsOrder{} + // var orderStatus int64 + // var orderIsPartPay int64 + // var orderPayedAmount int64 + // var orderIsPayCompleted int64 + // // 支付记录是首款 + // if *payInfo.PayStage == int64(constants.PAYSTAGE_DEPOSIT) { + // orderStatus = int64(constants.STATUS_NEW_PART_PAY) + // orderIsPartPay = 1 + // orderInfo.IsPartPay = &orderIsPartPay + // orderPayedAmount = paymentIntent.Amount - // 删除购物车 - cartModelT := gmodel.NewFsCartModel(connGorm) - cartModelTRSB := cartModelT.BuilderTrans(ctx, nil) - err = cartModelT.RBDeleteCartsByIds(cartModelTRSB, cartIds) - if err != nil { - return err - } - } + // // 删除购物车 + // cartModelT := gmodel.NewFsCartModel(connGorm) + // cartModelTRSB := cartModelT.BuilderTrans(ctx, nil) + // err = cartModelT.RBDeleteCartsByIds(cartModelTRSB, cartIds) + // if err != nil { + // return err + // } + // } - // 支付记录是尾款 - if *payInfo.PayStage == int64(constants.PAYSTAGE_REMAINING) { - if *fsOrderRelInfo.Status < int64(constants.STATUS_NEW_PAY_COMPLETED) { - orderStatus = int64(constants.STATUS_NEW_PAY_COMPLETED) - } - orderIsPayCompleted = 1 - orderInfo.IsPayCompleted = &orderIsPayCompleted - orderPayedAmount = *fsOrderRelInfo.PayedAmount + paymentIntent.Amount - } + // // 支付记录是尾款 + // if *payInfo.PayStage == int64(constants.PAYSTAGE_REMAINING) { + // if *fsOrderRelInfo.Status < int64(constants.STATUS_NEW_PAY_COMPLETED) { + // orderStatus = int64(constants.STATUS_NEW_PAY_COMPLETED) + // } + // orderIsPayCompleted = 1 + // orderInfo.IsPayCompleted = &orderIsPayCompleted + // orderPayedAmount = *fsOrderRelInfo.PayedAmount + paymentIntent.Amount + // } - // 更新订单信息 - orderInfo.Id = fsOrderRelInfo.Id - orderInfo.Status = &orderStatus - orderInfo.Ptime = &nowTime - orderInfo.PayedAmount = &orderPayedAmount - orderModelT := gmodel.NewFsOrderModel(connGorm) - err = orderModelT.RBUpdate(ctx, orderInfo) - if err != nil { - return err - } - return err - }) - if err != nil { - return err - } + // // 更新订单信息 + // orderInfo.Id = fsOrderRelInfo.Id + // orderInfo.Status = &orderStatus + // orderInfo.Ptime = &nowTime + // orderInfo.PayedAmount = &orderPayedAmount + // orderModelT := gmodel.NewFsOrderModel(connGorm) + // err = orderModelT.RBUpdate(ctx, orderInfo) + // if err != nil { + // return err + // } + // return err + // }) + // if err != nil { + // return err + // } - //千人千面的处理 - // $renderServer = (new RenderService()); - // $renderServer->thousandsFacesV2($order->id); - // //清除用户最新的设计 - // $cache = \Yii::$app->cache; - // $cache->delete(CacheConfigHelper::LAST_DESIGN . $order->user_id); - // //缓存最新订单编号 - // $cache->set(CacheConfigHelper::USER_ORDERNO . $order->user_id, $order->sn); + // //千人千面的处理 + // // $renderServer = (new RenderService()); + // // $renderServer->thousandsFacesV2($order->id); + // // //清除用户最新的设计 + // // $cache = \Yii::$app->cache; + // // $cache->delete(CacheConfigHelper::LAST_DESIGN . $order->user_id); + // // //缓存最新订单编号 + // // $cache->set(CacheConfigHelper::USER_ORDERNO . $order->user_id, $order->sn); - // //查询用户邮箱信息 - // $user = \api\models\User::find()->where(['id' => $order->user_id])->one(); - // $redisData = [ - // 'key' => 'receipt_download', - // 'param' => [ - // 'email' => $user->email, - // 'order_id' => $order->id, - // 'pay_id' => $pay->id, - // 'type' => 1,//付款成功为1 - // ] - // ]; - // Email::timely($redisData); - } + // // //查询用户邮箱信息 + // // $user = \api\models\User::find()->where(['id' => $order->user_id])->one(); + // // $redisData = [ + // // 'key' => 'receipt_download', + // // 'param' => [ + // // 'email' => $user->email, + // // 'order_id' => $order->id, + // // 'pay_id' => $pay->id, + // // 'type' => 1,//付款成功为1 + // // ] + // // ]; + // // Email::timely($redisData); + // } // 订单记录 return nil diff --git a/server/product/internal/logic/getlastproductdesignlogic.go b/server/product/internal/logic/getlastproductdesignlogic.go index b99f2a90..2a7fc19c 100644 --- a/server/product/internal/logic/getlastproductdesignlogic.go +++ b/server/product/internal/logic/getlastproductdesignlogic.go @@ -2,11 +2,10 @@ package logic import ( "context" - "encoding/json" "errors" - "fusenapi/constants" "fusenapi/utils/auth" "fusenapi/utils/basic" + "gorm.io/gorm" "fusenapi/server/product/internal/svc" @@ -47,64 +46,64 @@ func (l *GetLastProductDesignLogic) GetLastProductDesign(req *types.Request, use return resp.SetStatusWithMessage(basic.CodeOK, "success:IsOpenRender switch is closed") } //查询用户最近下单成功的数据 - orderInfo, err := l.svcCtx.AllModels.FsOrder.FindLastSuccessOneOrder(l.ctx, user.Id, int64(constants.STATUS_NEW_NOT_PAY)) - if err != nil { - if errors.Is(err, gorm.ErrRecordNotFound) { - return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "none of order is found") - } - logx.Error(err) - return resp.SetStatusAddMessage(basic.CodeDbSqlErr, "failed to get your last order") - } + // orderInfo, err := l.svcCtx.AllModels.FsOrder.FindLastSuccessOneOrder(l.ctx, user.Id, int64(constants.STATUS_NEW_NOT_PAY)) + // if err != nil { + // if errors.Is(err, gorm.ErrRecordNotFound) { + // return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "none of order is found") + // } + // logx.Error(err) + // return resp.SetStatusAddMessage(basic.CodeDbSqlErr, "failed to get your last order") + // } //获取该订单相关设计信息 - orderDetail, err := l.svcCtx.AllModels.FsOrderDetail.GetOneOrderDetailByOrderId(l.ctx, orderInfo.Id) - if err != nil { - if errors.Is(err, gorm.ErrRecordNotFound) { - return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order detail is not found") - } - logx.Error(err) - return resp.SetStatusAddMessage(basic.CodeDbSqlErr, "failed to get order detail") - } - //获取设计模板详情,便于获得design_id - orderDetailTemplate, err := l.svcCtx.AllModels.FsOrderDetailTemplate.FindOne(l.ctx, *orderDetail.OrderDetailTemplateId) - if err != nil { - if errors.Is(err, gorm.ErrRecordNotFound) { - return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order detail template is not found") - } - logx.Error(err) - return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get order detail template") - } + // orderDetail, err := l.svcCtx.AllModels.FsOrderDetail.GetOneOrderDetailByOrderId(l.ctx, orderInfo.Id) + // if err != nil { + // if errors.Is(err, gorm.ErrRecordNotFound) { + // return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order detail is not found") + // } + // logx.Error(err) + // return resp.SetStatusAddMessage(basic.CodeDbSqlErr, "failed to get order detail") + // } + // //获取设计模板详情,便于获得design_id + // orderDetailTemplate, err := l.svcCtx.AllModels.FsOrderDetailTemplate.FindOne(l.ctx, *orderDetail.OrderDetailTemplateId) + // if err != nil { + // if errors.Is(err, gorm.ErrRecordNotFound) { + // return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "order detail template is not found") + // } + // logx.Error(err) + // return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get order detail template") + // } //最后一次设计不存在,则不返回该设计相关数据 - if *orderDetailTemplate.DesignId <= 0 { - return resp.SetStatusWithMessage(basic.CodeOK, "success:last design id is not set") - } + // if *orderDetailTemplate.DesignId <= 0 { + // return resp.SetStatusWithMessage(basic.CodeOK, "success:last design id is not set") + // } //获取设计数据 - productDesign, err := l.svcCtx.AllModels.FsProductDesign.FindOne(l.ctx, *orderDetailTemplate.DesignId, user.Id) - if err != nil { - if errors.Is(err, gorm.ErrRecordNotFound) { - return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "product design is not found") - } - logx.Error(err) - return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get product design") - } - var info interface{} - if productDesign.Info != nil && *productDesign.Info != "" { - if err := json.Unmarshal([]byte(*productDesign.Info), &info); err != nil { - logx.Error(err) - return nil - } - } - var logoColor interface{} - if productDesign.LogoColor != nil && *productDesign.LogoColor != "" { - if err := json.Unmarshal([]byte(*productDesign.LogoColor), &logoColor); err != nil { - logx.Error(err) - return nil - } - } + // productDesign, err := l.svcCtx.AllModels.FsProductDesign.FindOne(l.ctx, *orderDetailTemplate.DesignId, user.Id) + // if err != nil { + // if errors.Is(err, gorm.ErrRecordNotFound) { + // return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "product design is not found") + // } + // logx.Error(err) + // return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get product design") + // } + // var info interface{} + // if productDesign.Info != nil && *productDesign.Info != "" { + // if err := json.Unmarshal([]byte(*productDesign.Info), &info); err != nil { + // logx.Error(err) + // return nil + // } + // } + // var logoColor interface{} + // if productDesign.LogoColor != nil && *productDesign.LogoColor != "" { + // if err := json.Unmarshal([]byte(*productDesign.LogoColor), &logoColor); err != nil { + // logx.Error(err) + // return nil + // } + // } return resp.SetStatusWithMessage(basic.CodeOK, "success", types.GetLastProductDesignRsp{ - Id: productDesign.Id, - OptionalId: *productDesign.OptionalId, - SizeId: *productDesign.SizeId, - LogoColor: logoColor, - Info: info, + Id: 1, + OptionalId: 1, + SizeId: 1, + LogoColor: 1, + Info: nil, }) } diff --git a/server/product/internal/logic/getpricebypidlogic.go b/server/product/internal/logic/getpricebypidlogic.go index 4848af9b..025a9c33 100644 --- a/server/product/internal/logic/getpricebypidlogic.go +++ b/server/product/internal/logic/getpricebypidlogic.go @@ -8,10 +8,11 @@ import ( "fusenapi/utils/basic" "fusenapi/utils/format" "fusenapi/utils/step_price" - "gorm.io/gorm" "sort" "strings" + "gorm.io/gorm" + "context" "fusenapi/server/product/internal/svc" diff --git a/server/product/internal/logic/getproductinfologic.go b/server/product/internal/logic/getproductinfologic.go index 1a768d3c..7db20475 100644 --- a/server/product/internal/logic/getproductinfologic.go +++ b/server/product/internal/logic/getproductinfologic.go @@ -14,10 +14,11 @@ import ( "fusenapi/utils/format" "fusenapi/utils/image" "fusenapi/utils/step_price" - "gorm.io/gorm" "strconv" "strings" + "gorm.io/gorm" + "fusenapi/server/product/internal/svc" "fusenapi/server/product/internal/types" @@ -460,66 +461,66 @@ func (l *GetProductInfoLogic) getRenderDesign(clientNo string) interface{} { // 获取用户最新设计 func (l *GetProductInfoLogic) getLastDesign(userInfo gmodel.FsUser) interface{} { //查询用户最近下单成功的数据 - orderInfo, err := l.svcCtx.AllModels.FsOrder.FindLastSuccessOneOrder(l.ctx, userInfo.Id, int64(constants.STATUS_NEW_NOT_PAY)) - if err != nil { - if errors.Is(err, gorm.ErrRecordNotFound) { - return nil - } - logx.Error(err) - return nil - } + // orderInfo, err := l.svcCtx.AllModels.FsOrder.FindLastSuccessOneOrder(l.ctx, userInfo.Id, int64(constants.STATUS_NEW_NOT_PAY)) + // if err != nil { + // if errors.Is(err, gorm.ErrRecordNotFound) { + // return nil + // } + // logx.Error(err) + // return nil + // } //获取该订单相关设计信息 - orderDetail, err := l.svcCtx.AllModels.FsOrderDetail.GetOneOrderDetailByOrderId(l.ctx, orderInfo.Id) - if err != nil { - if errors.Is(err, gorm.ErrRecordNotFound) { - return nil - } - logx.Error(err) - return nil - } - //获取设计模板详情,便于获得design_id - orderDetailTemplate, err := l.svcCtx.AllModels.FsOrderDetailTemplate.FindOne(l.ctx, *orderDetail.OrderDetailTemplateId) - if err != nil { - if errors.Is(err, gorm.ErrRecordNotFound) { - return nil - } - logx.Error(err) - return nil - } + // orderDetail, err := l.svcCtx.AllModels.FsOrderDetail.GetOneOrderDetailByOrderId(l.ctx, orderInfo.Id) + // if err != nil { + // if errors.Is(err, gorm.ErrRecordNotFound) { + // return nil + // } + // logx.Error(err) + // return nil + // } + // //获取设计模板详情,便于获得design_id + // orderDetailTemplate, err := l.svcCtx.AllModels.FsOrderDetailTemplate.FindOne(l.ctx, *orderDetail.OrderDetailTemplateId) + // if err != nil { + // if errors.Is(err, gorm.ErrRecordNotFound) { + // return nil + // } + // logx.Error(err) + // return nil + // } //若没打开了个性化渲染按钮或者最后一次设计不存在,则不返回该设计相关数据 - if *userInfo.IsOpenRender != 1 || *orderDetailTemplate.DesignId <= 0 { - return nil - } - //获取设计数据 - productDesign, err := l.svcCtx.AllModels.FsProductDesign.FindOne(l.ctx, *orderDetailTemplate.DesignId, userInfo.Id) - if err != nil { - if errors.Is(err, gorm.ErrRecordNotFound) { - return nil - } - logx.Error(err) - return nil - } - var info interface{} - if productDesign.Info != nil && *productDesign.Info != "" { - if err := json.Unmarshal([]byte(*productDesign.Info), &info); err != nil { - logx.Error(err) - return nil - } - } - var logoColor interface{} - if productDesign.LogoColor != nil && *productDesign.LogoColor != "" { - if err := json.Unmarshal([]byte(*productDesign.LogoColor), &logoColor); err != nil { - logx.Error(err) - return nil - } - } + // if *userInfo.IsOpenRender != 1 || *orderDetailTemplate.DesignId <= 0 { + // return nil + // } + // //获取设计数据 + // productDesign, err := l.svcCtx.AllModels.FsProductDesign.FindOne(l.ctx, *orderDetailTemplate.DesignId, userInfo.Id) + // if err != nil { + // if errors.Is(err, gorm.ErrRecordNotFound) { + // return nil + // } + // logx.Error(err) + // return nil + // } + // var info interface{} + // if productDesign.Info != nil && *productDesign.Info != "" { + // if err := json.Unmarshal([]byte(*productDesign.Info), &info); err != nil { + // logx.Error(err) + // return nil + // } + // } + // var logoColor interface{} + // if productDesign.LogoColor != nil && *productDesign.LogoColor != "" { + // if err := json.Unmarshal([]byte(*productDesign.LogoColor), &logoColor); err != nil { + // logx.Error(err) + // return nil + // } + // } return map[string]interface{}{ - "id": productDesign.Id, - "info": info, - "logo_color": logoColor, - "material_id": *productDesign.MaterialId, - "optional_id": *productDesign.OptionalId, - "size_id": *productDesign.SizeId, + "id": 1, + "info": 1, + "logo_color": 1, + "material_id": 1, + "optional_id": 1, + "size_id": 1, } } diff --git a/server/product/internal/logic/getrendersettingbypidlogic.go b/server/product/internal/logic/getrendersettingbypidlogic.go index 3529de22..94a2d546 100644 --- a/server/product/internal/logic/getrendersettingbypidlogic.go +++ b/server/product/internal/logic/getrendersettingbypidlogic.go @@ -2,14 +2,14 @@ package logic import ( "errors" - "fusenapi/constants" "fusenapi/model/gmodel" "fusenapi/utils/auth" "fusenapi/utils/basic" "fusenapi/utils/color_list" - "gorm.io/gorm" "strings" + "gorm.io/gorm" + "context" "fusenapi/server/product/internal/svc" @@ -126,28 +126,28 @@ func (l *GetRenderSettingByPidLogic) checkRenderDesign(clientNo string) (bool, e // 查询是否存在最新设计 func (l *GetRenderSettingByPidLogic) checkLastDesignExists(userId int64) (bool, error) { //查询用户最近下单成功的数据 - orderInfo, err := l.svcCtx.AllModels.FsOrder.FindLastSuccessOneOrder(l.ctx, userId, int64(constants.STATUS_NEW_NOT_PAY)) - if err != nil { - if errors.Is(err, gorm.ErrRecordNotFound) { - return false, nil - } - return false, err - } + // orderInfo, err := l.svcCtx.AllModels.FsOrder.FindLastSuccessOneOrder(l.ctx, userId, int64(constants.STATUS_NEW_NOT_PAY)) + // if err != nil { + // if errors.Is(err, gorm.ErrRecordNotFound) { + // return false, nil + // } + // return false, err + // } //获取该订单相关设计信息 - orderDetail, err := l.svcCtx.AllModels.FsOrderDetail.GetOneOrderDetailByOrderId(l.ctx, orderInfo.Id) - if err != nil { - if errors.Is(err, gorm.ErrRecordNotFound) { - return false, nil - } - return false, err - } - //获取设计模板详情,便于获得design_id - orderDetailTemplate, err := l.svcCtx.AllModels.FsOrderDetailTemplate.FindOne(l.ctx, *orderDetail.OrderDetailTemplateId) - if err != nil { - if errors.Is(err, gorm.ErrRecordNotFound) { - return false, nil - } - return false, err - } - return *orderDetailTemplate.DesignId > 0, nil + // orderDetail, err := l.svcCtx.AllModels.FsOrderDetail.GetOneOrderDetailByOrderId(l.ctx, orderInfo.Id) + // if err != nil { + // if errors.Is(err, gorm.ErrRecordNotFound) { + // return false, nil + // } + // return false, err + // } + // //获取设计模板详情,便于获得design_id + // orderDetailTemplate, err := l.svcCtx.AllModels.FsOrderDetailTemplate.FindOne(l.ctx, *orderDetail.OrderDetailTemplateId) + // if err != nil { + // if errors.Is(err, gorm.ErrRecordNotFound) { + // return false, nil + // } + // return false, err + // } + return false, nil } diff --git a/server_api/basic.api b/server_api/basic.api index 7125abc4..3adb78df 100644 --- a/server_api/basic.api +++ b/server_api/basic.api @@ -33,11 +33,192 @@ type File { Data []byte `fsfile:"data"` } - // 统一分页 type Meta struct { TotalCount int64 `json:"totalCount"` PageCount int64 `json:"pageCount"` CurrentPage int `json:"currentPage"` PerPage int `json:"perPage"` +} + +type ProductLogoResource struct { + ResourceID string `json:"resource_id"` + ResourceType string `json:"resource_type"` + ResourceURL string `json:"resource_url"` + Metadata map[string]int64erface{} `json:"metadata"` +} +type ProductSnapshot struct { +} +type TemplateInfo struct { + TemplateJSON string `json:"template_json"` + TemplateTag string `json:"template_tag"` +} +type ModelInfo struct { + ModelJSON string `json:"model_json"` +} +type FittingInfo struct { + FittingJSON string `json:"fitting_json"` +} +type SizeInfo struct { + Inch string `json:"inch"` + Cm string `json:"cm"` +} +type UserDiyInformation struct { + Phone string `json:"phone"` + Address string `json:"address"` + Website string `json:"website"` + Qrcode string `json:"qrcode"` + Slogan string `json:"slogan"` +} +type Snapshot struct { + Logo string `json:"logo"` + CombineImage string `json:"combine_image"` + RenderImage string `json:"render_image"` + TemplateInfo TemplateInfo `json:"template_info"` + ModelInfo ModelInfo `json:"model_info"` + FittingInfo FittingInfo `json:"fitting_info"` + SizeInfo SizeInfo `json:"size_info"` + UserDiyInformation UserDiyInformation `json:"user_diy_information"` +} +type ShoppingCartSnapshot struct { + ID int64 `json:"id"` + UserID int64 `json:"user_id"` + ProductID int64 `json:"product_id"` + TemplateID int64 `json:"template_id"` + ModelID int64 `json:"model_id"` + SizeID int64 `json:"size_id"` + FittingID int64 `json:"fitting_id"` + PurchaseQuantity int64 `json:"purchase_quantity"` + Snapshot Snapshot `json:"snapshot"` + IsHighlyCustomized int64 `json:"is_highly_customized"` + Ctime string `json:"ctime"` + Utime string `json:"utime"` +} +type OrderProduct struct { + ProductID string `json:"product_id"` + ProductName string `json:"product_name"` + ProductPrice string `json:"product_price"` + ProductLogo string `json:"product_logo"` + ProductLogoResource ProductLogoResource `json:"product_logo_resource"` + ProductSnapshot ProductSnapshot `json:"product_snapshot"` + Number int64 `json:"number"` + Amount string `json:"amount"` + Unit string `json:"unit"` + ExpectedDeliveryTime string `json:"expected_delivery_time"` + ShoppingCartSnapshot ShoppingCartSnapshot `json:"shopping_cart_snapshot"` +} +type Children struct { +} +type Status struct { + StatusCode int64 `json:"status_code"` + StatusTitle string `json:"status_title"` + ExpectedTime string `json:"expected_time"` + Ctime string `json:"ctime"` + Utime string `json:"utime"` + Metadata map[string]int64erface{} `json:"metadata"` + Children []Children `json:"children"` +} +type OrderStatus struct { + StatusCode int64 `json:"status_code"` + StatusTitle string `json:"status_title"` + ExpectedTime string `json:"expected_time"` + Ctime string `json:"ctime"` + Utime string `json:"utime"` + Metadata map[string]int64erface{} `json:"metadata"` + Children []Children `json:"children"` +} +type OrderInfo struct { + OrderNo string `json:"order_no"` + DeliveryMethod int64 `json:"delivery_method"` + Ctime string `json:"ctime"` + Utime string `json:"utime"` + Status OrderStatus `json:"status"` + StatusLink []OrderStatus `json:"status_link"` + Metadata map[string]int64erface{} `json:"metadata"` +} +type Subtotal struct { + Currency string `json:"currency"` + Current string `json:"current"` + Initiate string `json:"initiate"` + Change string `json:"change"` + ChangeRemark string `json:"change_remark"` + Metadata map[string]int64erface{} `json:"metadata"` +} +type ShippingFee struct { + Currency string `json:"currency"` + Current string `json:"current"` + Initiate string `json:"initiate"` + Change string `json:"change"` + ChangeRemark string `json:"change_remark"` + Metadata map[string]int64erface{} `json:"metadata"` +} +type Tax struct { + Currency string `json:"currency"` + Current string `json:"current"` + Initiate string `json:"initiate"` + Change string `json:"change"` + ChangeRemark string `json:"change_remark"` + Metadata map[string]int64erface{} `json:"metadata"` +} +type Discount struct { + Currency string `json:"currency"` + Current string `json:"current"` + Initiate string `json:"initiate"` + Change string `json:"change"` + ChangeRemark string `json:"change_remark"` + Metadata map[string]int64erface{} `json:"metadata"` +} +type Total struct { + Currency string `json:"currency"` + Current string `json:"current"` + Initiate string `json:"initiate"` + Change string `json:"change"` + ChangeRemark string `json:"change_remark"` + Metadata map[string]int64erface{} `json:"metadata"` +} +type PayStatus struct { + StatusCode int64 `json:"status_code"` + StatusTitle string `json:"status_title"` + Metadata map[string]int64erface{} `json:"metadata"` +} + +type PayAmount struct { + Currency string `json:"currency"` + Current string `json:"current"` + Initiate string `json:"initiate"` + Change string `json:"change"` + ChangeRemark string `json:"change_remark"` + Metadata map[string]int64erface{} `json:"metadata"` +} +type Deposit struct { + TradeNo string `json:"trade_no"` + Status Status `json:"status"` + StatusLink []PayStatus `json:"status_link"` + PayTime string `json:"pay_time"` + PayAmount PayAmount `json:"pay_amount"` + PayMethod string `json:"pay_method"` + Metadata map[string]int64erface{} `json:"metadata"` +} +type RemainingBalance struct { + TradeNo string `json:"trade_no"` + Status PayStatus `json:"status"` + StatusLink []PayStatus `json:"status_link"` + PayTime string `json:"pay_time"` + PayAmount PayAmount `json:"pay_amount"` + PayMethod string `json:"pay_method"` + Metadata map[string]int64erface{} `json:"metadata"` +} +type OrderAmount struct { + Subtotal Subtotal `json:"subtotal"` + ShippingFee ShippingFee `json:"shipping_fee"` + Tax Tax `json:"tax"` + Discount Discount `json:"discount"` + Total Total `json:"total"` + Deposit Deposit `json:"deposit"` + RemainingBalance RemainingBalance `json:"remaining_balance"` +} +type DeliveryAddres struct { + Address string `json:"address"` + Name string `json:"name"` + Mobile string `json:"mobile"` } \ No newline at end of file diff --git a/server_api/orders.api b/server_api/orders.api new file mode 100644 index 00000000..cc0b11b1 --- /dev/null +++ b/server_api/orders.api @@ -0,0 +1,217 @@ +syntax = "v1" + +info ( + title: "订单模块" + desc: "订单相关" + author: "" + email: "" +) + +import "basic.api" + +service orders { + + @handler CreateOrderHandler + post /api/orders/create(CreateOrderReq) returns (response); + + @handler CreatePrePaymentHandler + post /api/orders/create-prepayment(OrderRefundReq) returns (response); + + @handler OrderListHandler + post /api/orders/list(OrderListReq) returns (response); + +} + +type CreateOrderReq struct { + CartIds []int64 `json:"cart_ids"` + DeliveryMethod string `json:"delivery_method"` +} + +type OrderRefundReq struct { + OrderNo string `json:"order_no"` + DeliveryMethod int64 `json:"delivery_method"` + DeliveryAddres DeliveryAddres `json:"delivery_addres"` +} +type DeliveryAddres struct { + Address string `json:"address"` + Name string `json:"name"` + Mobile string `json:"mobile"` +} + +type OrderDetail struct { + OrderProduct []OrderProduct `json:"order_product"` + OrderInfo OrderInfo `json:"order_info"` + OrderAmount OrderAmount `json:"order_amount"` + DeliveryAddres DeliveryAddres `json:"delivery_addres"` +} + +type ProductLogoResource struct { + ResourceID string `json:"resource_id"` + ResourceType string `json:"resource_type"` + ResourceURL string `json:"resource_url"` + Metadata map[string]interface{} `json:"metadata"` +} + +type TemplateInfo struct { + TemplateJSON string `json:"template_json"` + TemplateTag string `json:"template_tag"` +} +type ModelInfo struct { + ModelJSON string `json:"model_json"` +} +type FittingInfo struct { + FittingJSON string `json:"fitting_json"` +} +type SizeInfo struct { + Inch string `json:"inch"` + Cm string `json:"cm"` +} +type UserDiyInformation struct { + Phone string `json:"phone"` + Address string `json:"address"` + Website string `json:"website"` + Qrcode string `json:"qrcode"` + Slogan string `json:"slogan"` +} +type Snapshot struct { + Logo string `json:"logo"` + CombineImage string `json:"combine_image"` + RenderImage string `json:"render_image"` + TemplateInfo TemplateInfo `json:"template_info"` + ModelInfo ModelInfo `json:"model_info"` + FittingInfo FittingInfo `json:"fitting_info"` + SizeInfo SizeInfo `json:"size_info"` + UserDiyInformation UserDiyInformation `json:"user_diy_information"` +} +type ShoppingCartSnapshot struct { + ID int64 `json:"id"` + UserID int64 `json:"user_id"` + ProductID int64 `json:"product_id"` + TemplateID int64 `json:"template_id"` + ModelID int64 `json:"model_id"` + SizeID int64 `json:"size_id"` + FittingID int64 `json:"fitting_id"` + PurchaseQuantity int64 `json:"purchase_quantity"` + Snapshot Snapshot `json:"snapshot"` + IsHighlyCustomized int64 `json:"is_highly_customized"` + Ctime string `json:"ctime"` + Utime string `json:"utime"` +} +type OrderProduct struct { + ProductID string `json:"product_id"` + ProductName string `json:"product_name"` + ProductPrice string `json:"product_price"` + ProductLogo string `json:"product_logo"` + ProductLogoResource ProductLogoResource `json:"product_logo_resource"` + ProductSnapshot map[string]interface{} `json:"product_snapshot"` + Number int64 `json:"number"` + Amount string `json:"amount"` + Unit string `json:"unit"` + ExpectedDeliveryTime string `json:"expected_delivery_time"` + ShoppingCartSnapshot ShoppingCartSnapshot `json:"shopping_cart_snapshot"` +} + +type OrderStatus struct { + StatusCode int64 `json:"status_code"` + StatusTitle string `json:"status_title"` + ExpectedTime string `json:"expected_time"` + Ctime string `json:"ctime"` + Utime string `json:"utime"` + Metadata map[string]interface{} `json:"metadata"` + Children []*OrderStatus `json:"children"` +} +type OrderInfo struct { + OrderNo string `json:"order_no"` + DeliveryMethod int64 `json:"delivery_method"` + Ctime string `json:"ctime"` + Utime string `json:"utime"` + Status OrderStatus `json:"status"` + StatusLink []OrderStatus `json:"status_link"` + Metadata map[string]interface{} `json:"metadata"` +} +type Subtotal struct { + Currency string `json:"currency"` + Current string `json:"current"` + Initiate string `json:"initiate"` + Change string `json:"change"` + ChangeRemark string `json:"change_remark"` + Metadata map[string]interface{} `json:"metadata"` +} +type ShippingFee struct { + Currency string `json:"currency"` + Current string `json:"current"` + Initiate string `json:"initiate"` + Change string `json:"change"` + ChangeRemark string `json:"change_remark"` + Metadata map[string]interface{} `json:"metadata"` +} +type Tax struct { + Currency string `json:"currency"` + Current string `json:"current"` + Initiate string `json:"initiate"` + Change string `json:"change"` + ChangeRemark string `json:"change_remark"` + Metadata map[string]interface{} `json:"metadata"` +} +type Discount struct { + Currency string `json:"currency"` + Current string `json:"current"` + Initiate string `json:"initiate"` + Change string `json:"change"` + ChangeRemark string `json:"change_remark"` + Metadata map[string]interface{} `json:"metadata"` +} +type Total struct { + Currency string `json:"currency"` + Current string `json:"current"` + Initiate string `json:"initiate"` + Change string `json:"change"` + ChangeRemark string `json:"change_remark"` + Metadata map[string]interface{} `json:"metadata"` +} +type PayStatus struct { + StatusCode int64 `json:"status_code"` + StatusTitle string `json:"status_title"` + Metadata map[string]interface{} `json:"metadata"` +} + +type PayAmount struct { + Currency string `json:"currency"` + Current string `json:"current"` + Initiate string `json:"initiate"` + Change string `json:"change"` + ChangeRemark string `json:"change_remark"` + Metadata map[string]interface{} `json:"metadata"` +} +type Deposit struct { + TradeNo string `json:"trade_no"` + Status Status `json:"status"` + StatusLink []PayStatus `json:"status_link"` + PayTime string `json:"pay_time"` + PayAmount PayAmount `json:"pay_amount"` + PayMethod string `json:"pay_method"` + Metadata map[string]interface{} `json:"metadata"` +} +type RemainingBalance struct { + TradeNo string `json:"trade_no"` + Status PayStatus `json:"status"` + StatusLink []PayStatus `json:"status_link"` + PayTime string `json:"pay_time"` + PayAmount PayAmount `json:"pay_amount"` + PayMethod string `json:"pay_method"` + Metadata map[string]interface{} `json:"metadata"` +} +type OrderAmount struct { + Subtotal Subtotal `json:"subtotal"` + ShippingFee ShippingFee `json:"shipping_fee"` + Tax Tax `json:"tax"` + Discount Discount `json:"discount"` + Total Total `json:"total"` + Deposit Deposit `json:"deposit"` + RemainingBalance RemainingBalance `json:"remaining_balance"` +} +type DeliveryAddres struct { + Address string `json:"address"` + Name string `json:"name"` + Mobile string `json:"mobile"` +} From 5df0a0f18437cb6d66caef916741f88e49706be5 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Fri, 15 Sep 2023 10:23:40 +0800 Subject: [PATCH 12/59] fix --- model/gmodel/fs_orders_trade_gen.go | 35 +++++++ model/gmodel/fs_orders_trade_logic.go | 2 + .../internal/logic/getcartslogic.go | 99 +------------------ server/shopping-cart/internal/types/types.go | 16 +-- server_api/shopping-cart.api | 16 +-- .../verify_shopping_cart_channged.go | 95 ++++++++++++++++++ 6 files changed, 152 insertions(+), 111 deletions(-) create mode 100644 model/gmodel/fs_orders_trade_gen.go create mode 100644 model/gmodel/fs_orders_trade_logic.go create mode 100644 utils/shopping_cart/verify_shopping_cart_channged.go diff --git a/model/gmodel/fs_orders_trade_gen.go b/model/gmodel/fs_orders_trade_gen.go new file mode 100644 index 00000000..4a5f4c17 --- /dev/null +++ b/model/gmodel/fs_orders_trade_gen.go @@ -0,0 +1,35 @@ +package gmodel + +import ( + "gorm.io/gorm" + "time" +) + +// fs_orders_trade 订单交易记录表 +type FsOrdersTrade struct { + Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // 订单交易ID + UserId *int64 `gorm:"index;default:0;" json:"user_id"` // 用户ID + OrderNo *string `gorm:"default:'';" json:"order_no"` // + OrderSource *string `gorm:"default:'';" json:"order_source"` // + TradeNo *string `gorm:"index;default:'';" json:"trade_no"` // + PayAmount *int64 `gorm:"default:0;" json:"pay_amount"` // 支付金额 (分) + PayStatus *int64 `gorm:"default:0;" json:"pay_status"` // 支付状态:1=未成功,2=已成功 + PaymentMethod *int64 `gorm:"default:0;" json:"payment_method"` // 支付方式:1=stripe,2=paypal + PayStage *int64 `gorm:"default:0;" json:"pay_stage"` // 支付阶段:1=首付,2=尾款 + RefundStatus *int64 `gorm:"default:0;" json:"refund_status"` // 退款状态:1=未退款,2=已退款 + CardNo *string `gorm:"default:'';" json:"card_no"` // + CardBrand *string `gorm:"default:'';" json:"card_brand"` // + Ctime *time.Time `gorm:"default:'0000-00-00 00:00:00';" json:"ctime"` // + Utime *time.Time `gorm:"default:'0000-00-00 00:00:00';" json:"utime"` // + Country *string `gorm:"default:'';" json:"country"` // + Currency *string `gorm:"default:'';" json:"currency"` // + Metadata *[]byte `gorm:"default:'';" json:"metadata"` // +} +type FsOrdersTradeModel struct { + db *gorm.DB + name string +} + +func NewFsOrdersTradeModel(db *gorm.DB) *FsOrdersTradeModel { + return &FsOrdersTradeModel{db: db, name: "fs_orders_trade"} +} diff --git a/model/gmodel/fs_orders_trade_logic.go b/model/gmodel/fs_orders_trade_logic.go new file mode 100644 index 00000000..e68225aa --- /dev/null +++ b/model/gmodel/fs_orders_trade_logic.go @@ -0,0 +1,2 @@ +package gmodel +// TODO: 使用model的属性做你想做的 \ No newline at end of file diff --git a/server/shopping-cart/internal/logic/getcartslogic.go b/server/shopping-cart/internal/logic/getcartslogic.go index f28304c1..015b88fb 100644 --- a/server/shopping-cart/internal/logic/getcartslogic.go +++ b/server/shopping-cart/internal/logic/getcartslogic.go @@ -1,17 +1,13 @@ package logic import ( - "encoding/json" + "context" "fusenapi/constants" "fusenapi/model/gmodel" "fusenapi/utils/auth" "fusenapi/utils/basic" - "fusenapi/utils/hash" "fusenapi/utils/shopping_cart" "math" - "strings" - - "context" "fusenapi/server/shopping-cart/internal/svc" "fusenapi/server/shopping-cart/internal/types" @@ -107,7 +103,7 @@ func (l *GetCartsLogic) GetCarts(req *types.GetCartsReq, userinfo *auth.UserInfo //定义map收集变更信息 mapCartChange := make(map[int64]string) //校验购物车数据是否变更 - err = VerifyShoppingCartSnapshotDataChange(VerifyShoppingCartSnapshotDataChangeReq{ + err = shopping_cart.VerifyShoppingCartSnapshotDataChange(shopping_cart.VerifyShoppingCartSnapshotDataChangeReq{ Carts: carts, MapSize: mapSize, MapModel: mapModel, @@ -125,97 +121,6 @@ func (l *GetCartsLogic) GetCarts(req *types.GetCartsReq, userinfo *auth.UserInfo return resp.SetStatus(basic.CodeOK) } -// 校验购物车快照数据跟目前是否一致 -type VerifyShoppingCartSnapshotDataChangeReq struct { - Carts []gmodel.FsShoppingCart - MapSize map[int64]gmodel.FsProductSize - MapModel map[int64]gmodel.FsProductModel3d //模型跟配件都在 - MapTemplate map[int64]gmodel.FsProductTemplateV2 - MapCartChange map[int64]string -} -type VerifyShoppingCartSnapshotDataChangeRsp struct { - CartId int64 //有改变的列表下标 - Descrption string //变更描述信息 -} - -func VerifyShoppingCartSnapshotDataChange(req VerifyShoppingCartSnapshotDataChangeReq) error { - for _, cartInfo := range req.Carts { - var snapShotParseInfo shopping_cart.CartSnapshot - if err := json.Unmarshal([]byte(*cartInfo.Snapshot), &snapShotParseInfo); err != nil { - return err - } - //快照中模板设计json数据哈希值 - snapshotTemplateJsonHash := hash.JsonHashKey(snapShotParseInfo.TemplateInfo.TemplateJson) - //快照中模型设计json数据哈希值 - snapshotModelJsonHash := hash.JsonHashKey(snapShotParseInfo.ModelInfo.ModelJson) - //快照中配件设计json数据哈希值 - snapshotFittingJsonHash := hash.JsonHashKey(snapShotParseInfo.FittingInfo.FittingJson) - descrptionBuilder := strings.Builder{} - //有模板验证模板相关 - if *cartInfo.TemplateId > 0 { - if curTemplateInfo, ok := req.MapTemplate[*cartInfo.TemplateId]; !ok { - descrptionBuilder.WriteString("the template is lose
") - } else { - //当前模板设计json数据哈希值 - curTemplateJsonHash := hash.JsonHashKey(*curTemplateInfo.TemplateInfo) - //模板设计信息改变了 - if snapshotTemplateJsonHash != curTemplateJsonHash { - descrptionBuilder.WriteString("the template design info has changed
") - } - //模板标签改变了 - if snapShotParseInfo.TemplateInfo.TemplateTag != *curTemplateInfo.TemplateTag { - descrptionBuilder.WriteString("the template`s template tag has changed
") - } - } - } - //有模型验证模型相关 - if *cartInfo.ModelId > 0 { - if curModelInfo, ok := req.MapModel[*cartInfo.ModelId]; !ok { //不存在 - descrptionBuilder.WriteString("the model is lose
") - } else { - //当前模型设计json数据哈希值 - curModelJsonHash := hash.JsonHashKey(*curModelInfo.ModelInfo) - if snapshotModelJsonHash != curModelJsonHash { - descrptionBuilder.WriteString("the model design info has changed
") - } - } - } - //有配件验证配件相关 - if *cartInfo.FittingId > 0 { - if curFittingInfo, ok := req.MapModel[*cartInfo.FittingId]; !ok { //不存在 - descrptionBuilder.WriteString("the fitting is lose
") - } else { - //当前配件设计json数据哈希值 - curFittingJsonHash := hash.JsonHashKey(*curFittingInfo.ModelInfo) - if snapshotFittingJsonHash != curFittingJsonHash { - descrptionBuilder.WriteString("the fitting design info has changed
") - } - } - } - //验证尺寸相关 - if *cartInfo.SizeId > 0 { - curSize, ok := req.MapSize[*cartInfo.SizeId] - if !ok { - descrptionBuilder.WriteString("the size is lose
") - } else { - var curSizeTitle shopping_cart.SizeInfo - if err := json.Unmarshal([]byte(*curSize.Title), &curSizeTitle); err != nil { - return err - } - if snapShotParseInfo.SizeInfo.Inch != curSizeTitle.Inch || snapShotParseInfo.SizeInfo.Cm != curSizeTitle.Cm { - descrptionBuilder.WriteString("the size design info has changed
") - } - } - } - //收集错误 - descrption := descrptionBuilder.String() - if descrption != "" { - req.MapCartChange[cartInfo.Id] = descrption - } - } - return nil -} - // 处理逻辑后 w,r 如:重定向, resp 必须重新处理 // func (l *GetCartsLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) { // // httpx.OkJsonCtx(r.Context(), w, resp) diff --git a/server/shopping-cart/internal/types/types.go b/server/shopping-cart/internal/types/types.go index fc3f605c..8fe8d2a2 100644 --- a/server/shopping-cart/internal/types/types.go +++ b/server/shopping-cart/internal/types/types.go @@ -44,13 +44,15 @@ type GetCartsRsp struct { } type CartItem struct { - ProductId int64 `json:"product_id"` //产品id - SizeInfo SizeInfo `json:"size_info"` //尺寸信息 - FittingInfo FittingInfo `json:"fitting_info"` //配件信息 - ItemPrice string `json:"item_price"` //单价 - TotalPrice string `json:"totalPrice"` //单价X数量=总价 - DiyInformation DiyInformation `json:"diy_information"` //diy信息 - StepNum []int64 `json:"step_num"` //阶梯数量 + ProductId int64 `json:"product_id"` //产品id + SizeInfo SizeInfo `json:"size_info"` //尺寸信息 + FittingInfo FittingInfo `json:"fitting_info"` //配件信息 + ItemPrice string `json:"item_price"` //单价 + TotalPrice string `json:"totalPrice"` //单价X数量=总价 + DiyInformation DiyInformation `json:"diy_information"` //diy信息 + StepNum []int64 `json:"step_num"` //阶梯数量 + IsInvalid bool `json:"is_invalid"` //是否无效 + InvalidDescription string `json:"invalid_description"` //无效原因 } type SizeInfo struct { diff --git a/server_api/shopping-cart.api b/server_api/shopping-cart.api index 3f1f19c5..7e96eebb 100644 --- a/server_api/shopping-cart.api +++ b/server_api/shopping-cart.api @@ -60,13 +60,15 @@ type GetCartsRsp { CartList []CartItem `json:"cart_list"` } type CartItem { - ProductId int64 `json:"product_id"` //产品id - SizeInfo SizeInfo `json:"size_info"` //尺寸信息 - FittingInfo FittingInfo `json:"fitting_info"` //配件信息 - ItemPrice string `json:"item_price"` //单价 - TotalPrice string `json:"totalPrice"` //单价X数量=总价 - DiyInformation DiyInformation `json:"diy_information"` //diy信息 - StepNum []int64 `json:"step_num"` //阶梯数量 + ProductId int64 `json:"product_id"` //产品id + SizeInfo SizeInfo `json:"size_info"` //尺寸信息 + FittingInfo FittingInfo `json:"fitting_info"` //配件信息 + ItemPrice string `json:"item_price"` //单价 + TotalPrice string `json:"totalPrice"` //单价X数量=总价 + DiyInformation DiyInformation `json:"diy_information"` //diy信息 + StepNum []int64 `json:"step_num"` //阶梯数量 + IsInvalid bool `json:"is_invalid"` //是否无效 + InvalidDescription string `json:"invalid_description"` //无效原因 } type SizeInfo { SizeId int64 `json:"size_id"` //尺寸id diff --git a/utils/shopping_cart/verify_shopping_cart_channged.go b/utils/shopping_cart/verify_shopping_cart_channged.go new file mode 100644 index 00000000..6863291b --- /dev/null +++ b/utils/shopping_cart/verify_shopping_cart_channged.go @@ -0,0 +1,95 @@ +package shopping_cart + +import ( + "encoding/json" + "fusenapi/model/gmodel" + "fusenapi/utils/hash" + "strings" +) + +// 校验购物车快照数据跟目前是否一致 +type VerifyShoppingCartSnapshotDataChangeReq struct { + Carts []gmodel.FsShoppingCart + MapSize map[int64]gmodel.FsProductSize + MapModel map[int64]gmodel.FsProductModel3d //模型跟配件都在 + MapTemplate map[int64]gmodel.FsProductTemplateV2 + MapCartChange map[int64]string +} + +func VerifyShoppingCartSnapshotDataChange(req VerifyShoppingCartSnapshotDataChangeReq) error { + for _, cartInfo := range req.Carts { + var snapShotParseInfo CartSnapshot + if err := json.Unmarshal([]byte(*cartInfo.Snapshot), &snapShotParseInfo); err != nil { + return err + } + //快照中模板设计json数据哈希值 + snapshotTemplateJsonHash := hash.JsonHashKey(snapShotParseInfo.TemplateInfo.TemplateJson) + //快照中模型设计json数据哈希值 + snapshotModelJsonHash := hash.JsonHashKey(snapShotParseInfo.ModelInfo.ModelJson) + //快照中配件设计json数据哈希值 + snapshotFittingJsonHash := hash.JsonHashKey(snapShotParseInfo.FittingInfo.FittingJson) + descrptionBuilder := strings.Builder{} + //有模板验证模板相关 + if *cartInfo.TemplateId > 0 { + if curTemplateInfo, ok := req.MapTemplate[*cartInfo.TemplateId]; !ok { + descrptionBuilder.WriteString("the template is lose
") + } else { + //当前模板设计json数据哈希值 + curTemplateJsonHash := hash.JsonHashKey(*curTemplateInfo.TemplateInfo) + //模板设计信息改变了 + if snapshotTemplateJsonHash != curTemplateJsonHash { + descrptionBuilder.WriteString("the template design info has changed
") + } + //模板标签改变了 + if snapShotParseInfo.TemplateInfo.TemplateTag != *curTemplateInfo.TemplateTag { + descrptionBuilder.WriteString("the template`s template tag has changed
") + } + } + } + //有模型验证模型相关 + if *cartInfo.ModelId > 0 { + if curModelInfo, ok := req.MapModel[*cartInfo.ModelId]; !ok { //不存在 + descrptionBuilder.WriteString("the model is lose
") + } else { + //当前模型设计json数据哈希值 + curModelJsonHash := hash.JsonHashKey(*curModelInfo.ModelInfo) + if snapshotModelJsonHash != curModelJsonHash { + descrptionBuilder.WriteString("the model design info has changed
") + } + } + } + //有配件验证配件相关 + if *cartInfo.FittingId > 0 { + if curFittingInfo, ok := req.MapModel[*cartInfo.FittingId]; !ok { //不存在 + descrptionBuilder.WriteString("the fitting is lose
") + } else { + //当前配件设计json数据哈希值 + curFittingJsonHash := hash.JsonHashKey(*curFittingInfo.ModelInfo) + if snapshotFittingJsonHash != curFittingJsonHash { + descrptionBuilder.WriteString("the fitting design info has changed
") + } + } + } + //验证尺寸相关 + if *cartInfo.SizeId > 0 { + curSize, ok := req.MapSize[*cartInfo.SizeId] + if !ok { + descrptionBuilder.WriteString("the size is lose
") + } else { + var curSizeTitle SizeInfo + if err := json.Unmarshal([]byte(*curSize.Title), &curSizeTitle); err != nil { + return err + } + if snapShotParseInfo.SizeInfo.Inch != curSizeTitle.Inch || snapShotParseInfo.SizeInfo.Cm != curSizeTitle.Cm { + descrptionBuilder.WriteString("the size design info has changed
") + } + } + } + //收集错误 + descrption := descrptionBuilder.String() + if descrption != "" { + req.MapCartChange[cartInfo.Id] = descrption + } + } + return nil +} From dd13dcbf0d5264c03adc5861a02c91f4a691abb4 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Fri, 15 Sep 2023 10:39:08 +0800 Subject: [PATCH 13/59] fix --- model/gmodel/fs_shopping_cart_logic.go | 5 +++++ .../canteen/internal/logic/getcanteendetaillogic.go | 2 +- .../internal/logic/savecanteentypeproductlogic.go | 2 +- .../internal/logic/getqrcodesetlistlogic.go | 2 +- .../internal/logic/getstandardlogolistlogic.go | 2 +- .../internal/logic/getmaplibrarylistlogic.go | 2 +- .../map-library/internal/logic/savemaplibrarylogic.go | 2 +- .../internal/logic/getlastproductdesignlogic.go | 2 +- .../product/internal/logic/getproductdesignlogic.go | 2 +- .../product/internal/logic/getsizebyproductlogic.go | 2 +- .../internal/logic/getsuccessrecommandlogic.go | 2 +- server/product/internal/logic/savedesignlogic.go | 2 +- .../shopping-cart/internal/logic/deletecartlogic.go | 11 ++++++++--- server/upload/internal/logic/uploadqrcodelogic.go | 2 +- 14 files changed, 25 insertions(+), 15 deletions(-) diff --git a/model/gmodel/fs_shopping_cart_logic.go b/model/gmodel/fs_shopping_cart_logic.go index 1f508ac9..bc5f4101 100644 --- a/model/gmodel/fs_shopping_cart_logic.go +++ b/model/gmodel/fs_shopping_cart_logic.go @@ -27,6 +27,11 @@ func (s *FsShoppingCartModel) Create(ctx context.Context, data *FsShoppingCart) return s.db.WithContext(ctx).Create(&data).Error } +// 删除 +func (s *FsShoppingCartModel) Delete(ctx context.Context, id, userId int64) error { + return s.db.WithContext(ctx).Where("user_id = ? and id = ?", userId, id).Delete(&FsShoppingCart{}).Error +} + // 更新 func (s *FsShoppingCartModel) Update(ctx context.Context, id, userId int64, data *FsShoppingCart) error { return s.db.WithContext(ctx).Where("user_id = ? and id = ?", userId, id).Updates(&data).Error diff --git a/server/canteen/internal/logic/getcanteendetaillogic.go b/server/canteen/internal/logic/getcanteendetaillogic.go index ea741565..95cd63aa 100644 --- a/server/canteen/internal/logic/getcanteendetaillogic.go +++ b/server/canteen/internal/logic/getcanteendetaillogic.go @@ -31,7 +31,7 @@ func NewGetCanteenDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) * // 获取餐厅详情 func (l *GetCanteenDetailLogic) GetCanteenDetail(req *types.GetCanteenDetailReq, userinfo *auth.UserInfo) (resp *basic.Response) { if userinfo.GetIdType() != auth.IDTYPE_User { - return resp.SetStatusWithMessage(basic.CodeServiceErr, "please login first") + return resp.SetStatusWithMessage(basic.CodeServiceErr, "please sign in first") } //获取餐厅类型数据 canteenTypeModel := gmodel.NewFsCanteenTypeModel(l.svcCtx.MysqlConn) diff --git a/server/canteen/internal/logic/savecanteentypeproductlogic.go b/server/canteen/internal/logic/savecanteentypeproductlogic.go index 2f1e9315..d66abf4d 100644 --- a/server/canteen/internal/logic/savecanteentypeproductlogic.go +++ b/server/canteen/internal/logic/savecanteentypeproductlogic.go @@ -32,7 +32,7 @@ func NewSaveCanteenTypeProductLogic(ctx context.Context, svcCtx *svc.ServiceCont // 保存餐厅类型的关联产品 func (l *SaveCanteenTypeProductLogic) SaveCanteenTypeProduct(req *types.SaveCanteenTypeProductReq, userinfo *auth.UserInfo) (resp *basic.Response) { if userinfo.GetIdType() != auth.IDTYPE_User { - return resp.SetStatusWithMessage(basic.CodeServiceErr, "please login first") + return resp.SetStatusWithMessage(basic.CodeServiceErr, "please sign in first") } if len(req.ProductList) == 0 { return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "product list can`t be empty") diff --git a/server/data-transfer/internal/logic/getqrcodesetlistlogic.go b/server/data-transfer/internal/logic/getqrcodesetlistlogic.go index 3b9215d4..e8395f9d 100644 --- a/server/data-transfer/internal/logic/getqrcodesetlistlogic.go +++ b/server/data-transfer/internal/logic/getqrcodesetlistlogic.go @@ -29,7 +29,7 @@ func NewGetQrCodeSetListLogic(ctx context.Context, svcCtx *svc.ServiceContext) * // 获取二维码配置列表 func (l *GetQrCodeSetListLogic) GetQrCodeSetList(req *types.Request, userinfo *auth.UserInfo) (resp *basic.Response) { if userinfo.GetIdType() != auth.IDTYPE_User { - return resp.SetStatusWithMessage(basic.CodeServiceErr, "please login first") + return resp.SetStatusWithMessage(basic.CodeServiceErr, "please sign in first") } qrCodeModel := gmodel.NewFsQrcodeSetModel(l.svcCtx.MysqlConn) qrCodeList, err := qrCodeModel.GetAll(l.ctx) diff --git a/server/data-transfer/internal/logic/getstandardlogolistlogic.go b/server/data-transfer/internal/logic/getstandardlogolistlogic.go index 4e946796..e4e9b814 100644 --- a/server/data-transfer/internal/logic/getstandardlogolistlogic.go +++ b/server/data-transfer/internal/logic/getstandardlogolistlogic.go @@ -29,7 +29,7 @@ func NewGetStandardLogoListLogic(ctx context.Context, svcCtx *svc2.ServiceContex // 获取标准logo列表 func (l *GetStandardLogoListLogic) GetStandardLogoList(req *types.Request, userinfo *auth.UserInfo) (resp *basic.Response) { if userinfo.GetIdType() != auth.IDTYPE_User { - return resp.SetStatusWithMessage(basic.CodeServiceErr, "please login first") + return resp.SetStatusWithMessage(basic.CodeServiceErr, "please sign in first") } standardLogoModel := gmodel.NewFsStandardLogoModel(l.svcCtx.MysqlConn) logoList, err := standardLogoModel.GetAll(l.ctx) diff --git a/server/map-library/internal/logic/getmaplibrarylistlogic.go b/server/map-library/internal/logic/getmaplibrarylistlogic.go index 1ecf5167..96f1d834 100644 --- a/server/map-library/internal/logic/getmaplibrarylistlogic.go +++ b/server/map-library/internal/logic/getmaplibrarylistlogic.go @@ -30,7 +30,7 @@ func NewGetMapLibraryListLogic(ctx context.Context, svcCtx *svc.ServiceContext) func (l *GetMapLibraryListLogic) GetMapLibraryList(req *types.Request, userinfo *auth.UserInfo) (resp *basic.Response) { if userinfo.GetIdType() != auth.IDTYPE_User { - return resp.SetStatusWithMessage(basic.CodeServiceErr, "please login first") + return resp.SetStatusWithMessage(basic.CodeServiceErr, "please sign in first") } mapLibraryModel := gmodel.NewFsMapLibraryModel(l.svcCtx.MysqlConn) mapLibraryList, err := mapLibraryModel.GetAllEnabledList(l.ctx) diff --git a/server/map-library/internal/logic/savemaplibrarylogic.go b/server/map-library/internal/logic/savemaplibrarylogic.go index 0b23c40b..d9373903 100644 --- a/server/map-library/internal/logic/savemaplibrarylogic.go +++ b/server/map-library/internal/logic/savemaplibrarylogic.go @@ -46,7 +46,7 @@ func (l *SaveMapLibraryLogic) BeforeLogic(w http.ResponseWriter, r *http.Request func (l *SaveMapLibraryLogic) SaveMapLibrary(req *types.Request, userinfo *auth.UserInfo) (resp *basic.Response) { if userinfo.GetIdType() != auth.IDTYPE_User { - return resp.SetStatusWithMessage(basic.CodeServiceErr, "please login first") + return resp.SetStatusWithMessage(basic.CodeServiceErr, "please sign in first") } if len(l.bodyData) == 0 { diff --git a/server/product/internal/logic/getlastproductdesignlogic.go b/server/product/internal/logic/getlastproductdesignlogic.go index b99f2a90..562aa314 100644 --- a/server/product/internal/logic/getlastproductdesignlogic.go +++ b/server/product/internal/logic/getlastproductdesignlogic.go @@ -31,7 +31,7 @@ func NewGetLastProductDesignLogic(ctx context.Context, svcCtx *svc.ServiceContex func (l *GetLastProductDesignLogic) GetLastProductDesign(req *types.Request, userinfo *auth.UserInfo) (resp *basic.Response) { if !userinfo.IsUser() { - return resp.SetStatusAddMessage(basic.CodeUnAuth, "please login") + return resp.SetStatusAddMessage(basic.CodeUnAuth, "please sign in") } //获取用户信息 user, err := l.svcCtx.AllModels.FsUser.FindUserById(l.ctx, userinfo.UserId) diff --git a/server/product/internal/logic/getproductdesignlogic.go b/server/product/internal/logic/getproductdesignlogic.go index 8882bec3..8a2e9fad 100644 --- a/server/product/internal/logic/getproductdesignlogic.go +++ b/server/product/internal/logic/getproductdesignlogic.go @@ -31,7 +31,7 @@ func NewGetProductDesignLogic(ctx context.Context, svcCtx *svc.ServiceContext) * func (l *GetProductDesignLogic) GetProductDesign(req *types.GetProductDesignReq, userinfo *auth.UserInfo) (resp *basic.Response) { if userinfo.GetIdType() != auth.IDTYPE_User { - return resp.SetStatusWithMessage(basic.CodeUnAuth, "please login first") + return resp.SetStatusWithMessage(basic.CodeUnAuth, "please sign in first") } if req.Sn == "" { return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "param sn is required") diff --git a/server/product/internal/logic/getsizebyproductlogic.go b/server/product/internal/logic/getsizebyproductlogic.go index dea0a181..5e88ef39 100644 --- a/server/product/internal/logic/getsizebyproductlogic.go +++ b/server/product/internal/logic/getsizebyproductlogic.go @@ -35,7 +35,7 @@ func NewGetSizeByProductLogic(ctx context.Context, svcCtx *svc.ServiceContext) * // 获取分类下的产品以及尺寸 func (l *GetSizeByProductLogic) GetSizeByProduct(req *types.Request, userinfo *auth.UserInfo) (resp *basic.Response) { if userinfo.GetIdType() != auth.IDTYPE_User { - return resp.SetStatusWithMessage(basic.CodeUnAuth, "please login first") + return resp.SetStatusWithMessage(basic.CodeUnAuth, "please sign in first") } //获取所有网站目录 tagsModel := gmodel.NewFsTagsModel(l.svcCtx.MysqlConn) diff --git a/server/product/internal/logic/getsuccessrecommandlogic.go b/server/product/internal/logic/getsuccessrecommandlogic.go index 601f7dab..67f6902c 100644 --- a/server/product/internal/logic/getsuccessrecommandlogic.go +++ b/server/product/internal/logic/getsuccessrecommandlogic.go @@ -30,7 +30,7 @@ func NewGetSuccessRecommandLogic(ctx context.Context, svcCtx *svc.ServiceContext // 获取推荐的产品列表 func (l *GetSuccessRecommandLogic) GetSuccessRecommand(req *types.GetSuccessRecommandReq, userInfo *auth.UserInfo) (resp *basic.Response) { if userInfo.GetIdType() != auth.IDTYPE_User { - return resp.SetStatusWithMessage(basic.CodeUnAuth, "please login first") + return resp.SetStatusWithMessage(basic.CodeUnAuth, "please sign in first") } //获取用户信息 userModel := gmodel.NewFsUserModel(l.svcCtx.MysqlConn) diff --git a/server/product/internal/logic/savedesignlogic.go b/server/product/internal/logic/savedesignlogic.go index 55fa1322..4894f508 100644 --- a/server/product/internal/logic/savedesignlogic.go +++ b/server/product/internal/logic/savedesignlogic.go @@ -47,7 +47,7 @@ func NewSaveDesignLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SaveDe func (l *SaveDesignLogic) SaveDesign(req *types.SaveDesignReq, userinfo *auth.UserInfo) (resp *basic.Response) { if userinfo.GetIdType() != auth.IDTYPE_User { - return resp.SetStatusWithMessage(basic.CodeUnAuth, "please login first") + return resp.SetStatusWithMessage(basic.CodeUnAuth, "please sign in first") } //查询是否是加密的(不太合理) encryptWebsetting, err := l.svcCtx.AllModels.FsWebSet.FindValueByKey(l.ctx, "is_encrypt") diff --git a/server/shopping-cart/internal/logic/deletecartlogic.go b/server/shopping-cart/internal/logic/deletecartlogic.go index 865a811f..4c1bc37b 100644 --- a/server/shopping-cart/internal/logic/deletecartlogic.go +++ b/server/shopping-cart/internal/logic/deletecartlogic.go @@ -31,9 +31,14 @@ func NewDeleteCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Delete // } func (l *DeleteCartLogic) DeleteCart(req *types.DeleteCartReq, userinfo *auth.UserInfo) (resp *basic.Response) { - // 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data) - // userinfo 传入值时, 一定不为null - + if !userinfo.IsUser() { + return resp.SetStatusWithMessage(basic.CodeUnAuth, "please sign in") + } + //删除购物车 + if err := l.svcCtx.AllModels.FsShoppingCart.Delete(l.ctx, userinfo.UserId, req.Id); err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to delete shopping cart") + } return resp.SetStatus(basic.CodeOK) } diff --git a/server/upload/internal/logic/uploadqrcodelogic.go b/server/upload/internal/logic/uploadqrcodelogic.go index f3242661..e8328640 100644 --- a/server/upload/internal/logic/uploadqrcodelogic.go +++ b/server/upload/internal/logic/uploadqrcodelogic.go @@ -32,7 +32,7 @@ func NewUploadQrcodeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Uplo func (l *UploadQrcodeLogic) UploadQrcode(req *types.UploadQrcodeReq, userinfo *auth.UserInfo) (resp *basic.Response) { if userinfo.GetIdType() != auth.IDTYPE_User { - return resp.SetStatusWithMessage(basic.CodeServiceErr, "please login first") + return resp.SetStatusWithMessage(basic.CodeServiceErr, "please sign in first") } if req.Url == "" { resp.SetStatus(basic.CodeApiErr, "param url is empty") From c1991351cf194d3f12e92bfd82130c420b84e61b Mon Sep 17 00:00:00 2001 From: eson <9673575+githubcontent@user.noreply.gitee.com> Date: Fri, 15 Sep 2023 11:20:49 +0800 Subject: [PATCH 14/59] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E8=A1=A8=E7=BB=93?= =?UTF-8?q?=E6=9E=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../fs_cloud_deliver_every_tmp_old_gen.go | 23 ++++++++ .../fs_cloud_deliver_every_tmp_old_logic.go | 2 + model/gmodel/fs_cloud_deliver_tmp_old_gen.go | 28 ++++++++++ .../gmodel/fs_cloud_deliver_tmp_old_logic.go | 2 + model/gmodel/fs_cloud_old_gen.go | 20 +++++++ model/gmodel/fs_cloud_old_logic.go | 2 + .../gmodel/fs_cloud_pick_up_detail_old_gen.go | 23 ++++++++ .../fs_cloud_pick_up_detail_old_logic.go | 2 + model/gmodel/fs_cloud_pick_up_old_gen.go | 28 ++++++++++ model/gmodel/fs_cloud_pick_up_old_logic.go | 2 + .../gmodel/fs_cloud_receive_every_old_gen.go | 22 ++++++++ .../fs_cloud_receive_every_old_logic.go | 2 + model/gmodel/fs_cloud_receive_old_gen.go | 26 +++++++++ model/gmodel/fs_cloud_receive_old_logic.go | 2 + model/gmodel/fs_cloud_render_log_old_gen.go | 26 +++++++++ model/gmodel/fs_cloud_render_log_old_logic.go | 2 + .../fs_cloud_user_apply_back_old_gen.go | 25 +++++++++ .../fs_cloud_user_apply_back_old_logic.go | 2 + model/gmodel/fs_order_affiliate_old_gen.go | 27 ++++++++++ model/gmodel/fs_order_affiliate_old_logic.go | 2 + model/gmodel/fs_order_detail_old_gen.go | 41 ++++++++++++++ model/gmodel/fs_order_detail_old_logic.go | 2 + .../fs_order_detail_template_old_gen.go | 28 ++++++++++ .../fs_order_detail_template_old_logic.go | 2 + model/gmodel/fs_order_gen.go | 47 ++++------------ model/gmodel/fs_order_old_gen.go | 54 +++++++++++++++++++ model/gmodel/fs_order_old_logic.go | 2 + model/gmodel/fs_order_remark_old_gen.go | 22 ++++++++ model/gmodel/fs_order_remark_old_logic.go | 2 + model/gmodel/fs_order_trade_event_gen.go | 25 +++++++++ model/gmodel/fs_order_trade_event_logic.go | 2 + model/gmodel/fs_order_trade_gen.go | 36 +++++++++++++ model/gmodel/fs_order_trade_logic.go | 2 + model/gmodel/fs_shopping_cart_gen.go | 2 - model/gmodel/var_gen.go | 40 +++++++++++--- 35 files changed, 529 insertions(+), 46 deletions(-) create mode 100644 model/gmodel/fs_cloud_deliver_every_tmp_old_gen.go create mode 100644 model/gmodel/fs_cloud_deliver_every_tmp_old_logic.go create mode 100644 model/gmodel/fs_cloud_deliver_tmp_old_gen.go create mode 100644 model/gmodel/fs_cloud_deliver_tmp_old_logic.go create mode 100644 model/gmodel/fs_cloud_old_gen.go create mode 100644 model/gmodel/fs_cloud_old_logic.go create mode 100644 model/gmodel/fs_cloud_pick_up_detail_old_gen.go create mode 100644 model/gmodel/fs_cloud_pick_up_detail_old_logic.go create mode 100644 model/gmodel/fs_cloud_pick_up_old_gen.go create mode 100644 model/gmodel/fs_cloud_pick_up_old_logic.go create mode 100644 model/gmodel/fs_cloud_receive_every_old_gen.go create mode 100644 model/gmodel/fs_cloud_receive_every_old_logic.go create mode 100644 model/gmodel/fs_cloud_receive_old_gen.go create mode 100644 model/gmodel/fs_cloud_receive_old_logic.go create mode 100644 model/gmodel/fs_cloud_render_log_old_gen.go create mode 100644 model/gmodel/fs_cloud_render_log_old_logic.go create mode 100644 model/gmodel/fs_cloud_user_apply_back_old_gen.go create mode 100644 model/gmodel/fs_cloud_user_apply_back_old_logic.go create mode 100644 model/gmodel/fs_order_affiliate_old_gen.go create mode 100644 model/gmodel/fs_order_affiliate_old_logic.go create mode 100644 model/gmodel/fs_order_detail_old_gen.go create mode 100644 model/gmodel/fs_order_detail_old_logic.go create mode 100644 model/gmodel/fs_order_detail_template_old_gen.go create mode 100644 model/gmodel/fs_order_detail_template_old_logic.go create mode 100644 model/gmodel/fs_order_old_gen.go create mode 100644 model/gmodel/fs_order_old_logic.go create mode 100644 model/gmodel/fs_order_remark_old_gen.go create mode 100644 model/gmodel/fs_order_remark_old_logic.go create mode 100644 model/gmodel/fs_order_trade_event_gen.go create mode 100644 model/gmodel/fs_order_trade_event_logic.go create mode 100644 model/gmodel/fs_order_trade_gen.go create mode 100644 model/gmodel/fs_order_trade_logic.go diff --git a/model/gmodel/fs_cloud_deliver_every_tmp_old_gen.go b/model/gmodel/fs_cloud_deliver_every_tmp_old_gen.go new file mode 100644 index 00000000..3fd8ba80 --- /dev/null +++ b/model/gmodel/fs_cloud_deliver_every_tmp_old_gen.go @@ -0,0 +1,23 @@ +package gmodel + +import ( + "gorm.io/gorm" +) + +// fs_cloud_deliver_every_tmp_old +type FsCloudDeliverEveryTmpOld struct { + Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // + AdminId *int64 `gorm:"default:0;" json:"admin_id"` // 管理员 + CloudId *int64 `gorm:"default:0;" json:"cloud_id"` // 云仓ID 暂且只有一个默认为 1 + OrderDetailTemplateSn *string `gorm:"default:'';" json:"order_detail_template_sn"` // + Num *int64 `gorm:"default:0;" json:"num"` // 发货数量 + Ctime *int64 `gorm:"default:0;" json:"ctime"` // 添加时间 +} +type FsCloudDeliverEveryTmpOldModel struct { + db *gorm.DB + name string +} + +func NewFsCloudDeliverEveryTmpOldModel(db *gorm.DB) *FsCloudDeliverEveryTmpOldModel { + return &FsCloudDeliverEveryTmpOldModel{db: db, name: "fs_cloud_deliver_every_tmp_old"} +} diff --git a/model/gmodel/fs_cloud_deliver_every_tmp_old_logic.go b/model/gmodel/fs_cloud_deliver_every_tmp_old_logic.go new file mode 100644 index 00000000..e68225aa --- /dev/null +++ b/model/gmodel/fs_cloud_deliver_every_tmp_old_logic.go @@ -0,0 +1,2 @@ +package gmodel +// TODO: 使用model的属性做你想做的 \ No newline at end of file diff --git a/model/gmodel/fs_cloud_deliver_tmp_old_gen.go b/model/gmodel/fs_cloud_deliver_tmp_old_gen.go new file mode 100644 index 00000000..a7711947 --- /dev/null +++ b/model/gmodel/fs_cloud_deliver_tmp_old_gen.go @@ -0,0 +1,28 @@ +package gmodel + +import ( + "gorm.io/gorm" +) + +// fs_cloud_deliver_tmp_old +type FsCloudDeliverTmpOld struct { + Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // id + CloudId *int64 `gorm:"default:0;" json:"cloud_id"` // 云仓id + UserId *int64 `gorm:"default:0;" json:"user_id"` // 用户id + AdminId *int64 `gorm:"default:0;" json:"admin_id"` // 操作员id + DeliveryType *int64 `gorm:"default:1;" json:"delivery_type"` // 发货公司 之后配置,默认1 + Fee *int64 `gorm:"default:0;" json:"fee"` // 价格 + AddressId *int64 `gorm:"default:0;" json:"address_id"` // 地址 + Ctime *int64 `gorm:"default:0;" json:"ctime"` // 创建时间 + IsDeliver *int64 `gorm:"default:0;" json:"is_deliver"` // 0未发货,1已发货 + IsEnd *int64 `gorm:"default:0;" json:"is_end"` // 0未完成,1已完成 + DeliverId *int64 `gorm:"default:0;" json:"deliver_id"` // 发货总表id +} +type FsCloudDeliverTmpOldModel struct { + db *gorm.DB + name string +} + +func NewFsCloudDeliverTmpOldModel(db *gorm.DB) *FsCloudDeliverTmpOldModel { + return &FsCloudDeliverTmpOldModel{db: db, name: "fs_cloud_deliver_tmp_old"} +} diff --git a/model/gmodel/fs_cloud_deliver_tmp_old_logic.go b/model/gmodel/fs_cloud_deliver_tmp_old_logic.go new file mode 100644 index 00000000..e68225aa --- /dev/null +++ b/model/gmodel/fs_cloud_deliver_tmp_old_logic.go @@ -0,0 +1,2 @@ +package gmodel +// TODO: 使用model的属性做你想做的 \ No newline at end of file diff --git a/model/gmodel/fs_cloud_old_gen.go b/model/gmodel/fs_cloud_old_gen.go new file mode 100644 index 00000000..8048d159 --- /dev/null +++ b/model/gmodel/fs_cloud_old_gen.go @@ -0,0 +1,20 @@ +package gmodel + +import ( + "gorm.io/gorm" +) + +// fs_cloud_old 云仓表 +type FsCloudOld struct { + Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // id + Address *string `gorm:"default:'';" json:"address"` // 云仓地址 + Title *string `gorm:"default:'';" json:"title"` // 云仓名称 +} +type FsCloudOldModel struct { + db *gorm.DB + name string +} + +func NewFsCloudOldModel(db *gorm.DB) *FsCloudOldModel { + return &FsCloudOldModel{db: db, name: "fs_cloud_old"} +} diff --git a/model/gmodel/fs_cloud_old_logic.go b/model/gmodel/fs_cloud_old_logic.go new file mode 100644 index 00000000..e68225aa --- /dev/null +++ b/model/gmodel/fs_cloud_old_logic.go @@ -0,0 +1,2 @@ +package gmodel +// TODO: 使用model的属性做你想做的 \ No newline at end of file diff --git a/model/gmodel/fs_cloud_pick_up_detail_old_gen.go b/model/gmodel/fs_cloud_pick_up_detail_old_gen.go new file mode 100644 index 00000000..c891ce19 --- /dev/null +++ b/model/gmodel/fs_cloud_pick_up_detail_old_gen.go @@ -0,0 +1,23 @@ +package gmodel + +import ( + "gorm.io/gorm" +) + +// fs_cloud_pick_up_detail_old 云仓提货单-详情 +type FsCloudPickUpDetailOld struct { + Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // Id + PickId *int64 `gorm:"index;default:0;" json:"pick_id"` // 提货单id + StockId *int64 `gorm:"default:0;" json:"stock_id"` // 用户云仓记录id + Num *int64 `gorm:"default:0;" json:"num"` // 提取数量 + Boxes *int64 `gorm:"default:0;" json:"boxes"` // 提取箱数 + Ctime *int64 `gorm:"default:0;" json:"ctime"` // 添加时间 +} +type FsCloudPickUpDetailOldModel struct { + db *gorm.DB + name string +} + +func NewFsCloudPickUpDetailOldModel(db *gorm.DB) *FsCloudPickUpDetailOldModel { + return &FsCloudPickUpDetailOldModel{db: db, name: "fs_cloud_pick_up_detail_old"} +} diff --git a/model/gmodel/fs_cloud_pick_up_detail_old_logic.go b/model/gmodel/fs_cloud_pick_up_detail_old_logic.go new file mode 100644 index 00000000..e68225aa --- /dev/null +++ b/model/gmodel/fs_cloud_pick_up_detail_old_logic.go @@ -0,0 +1,2 @@ +package gmodel +// TODO: 使用model的属性做你想做的 \ No newline at end of file diff --git a/model/gmodel/fs_cloud_pick_up_old_gen.go b/model/gmodel/fs_cloud_pick_up_old_gen.go new file mode 100644 index 00000000..68f2b758 --- /dev/null +++ b/model/gmodel/fs_cloud_pick_up_old_gen.go @@ -0,0 +1,28 @@ +package gmodel + +import ( + "gorm.io/gorm" +) + +// fs_cloud_pick_up_old 云仓提货单 +type FsCloudPickUpOld struct { + Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // Id + UserId *int64 `gorm:"index;default:0;" json:"user_id"` // 用户id + TrackNum *string `gorm:"default:'';" json:"track_num"` // 运输号 + AddressId *int64 `gorm:"default:0;" json:"address_id"` // 地址id + AddressInfo *string `gorm:"default:'';" json:"address_info"` // 地址信息 json + Status *int64 `gorm:"default:0;" json:"status"` // 运输状态 1 draw 2shipping 3ups 4arrival + Ctime *int64 `gorm:"default:0;" json:"ctime"` // 添加时间 + ShippingTime *int64 `gorm:"default:0;" json:"shipping_time"` // 发货时间 + UpsTime *int64 `gorm:"default:0;" json:"ups_time"` // 提货时间 + ArrivalTime *int64 `gorm:"default:0;" json:"arrival_time"` // 到达时间 + UpsSn *string `gorm:"default:'';" json:"ups_sn"` // 运输单号 +} +type FsCloudPickUpOldModel struct { + db *gorm.DB + name string +} + +func NewFsCloudPickUpOldModel(db *gorm.DB) *FsCloudPickUpOldModel { + return &FsCloudPickUpOldModel{db: db, name: "fs_cloud_pick_up_old"} +} diff --git a/model/gmodel/fs_cloud_pick_up_old_logic.go b/model/gmodel/fs_cloud_pick_up_old_logic.go new file mode 100644 index 00000000..e68225aa --- /dev/null +++ b/model/gmodel/fs_cloud_pick_up_old_logic.go @@ -0,0 +1,2 @@ +package gmodel +// TODO: 使用model的属性做你想做的 \ No newline at end of file diff --git a/model/gmodel/fs_cloud_receive_every_old_gen.go b/model/gmodel/fs_cloud_receive_every_old_gen.go new file mode 100644 index 00000000..436f9037 --- /dev/null +++ b/model/gmodel/fs_cloud_receive_every_old_gen.go @@ -0,0 +1,22 @@ +package gmodel + +import ( + "gorm.io/gorm" +) + +// fs_cloud_receive_every_old +type FsCloudReceiveEveryOld struct { + Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // + DeliveryId *int64 `gorm:"index;default:0;" json:"delivery_id"` // 云仓收货单id + OrderDetailTemplateSn *string `gorm:"index;default:'';" json:"order_detail_template_sn"` // + Num *int64 `gorm:"default:0;" json:"num"` // 收到的数量 + Ctime *int64 `gorm:"default:0;" json:"ctime"` // 添加时间 +} +type FsCloudReceiveEveryOldModel struct { + db *gorm.DB + name string +} + +func NewFsCloudReceiveEveryOldModel(db *gorm.DB) *FsCloudReceiveEveryOldModel { + return &FsCloudReceiveEveryOldModel{db: db, name: "fs_cloud_receive_every_old"} +} diff --git a/model/gmodel/fs_cloud_receive_every_old_logic.go b/model/gmodel/fs_cloud_receive_every_old_logic.go new file mode 100644 index 00000000..e68225aa --- /dev/null +++ b/model/gmodel/fs_cloud_receive_every_old_logic.go @@ -0,0 +1,2 @@ +package gmodel +// TODO: 使用model的属性做你想做的 \ No newline at end of file diff --git a/model/gmodel/fs_cloud_receive_old_gen.go b/model/gmodel/fs_cloud_receive_old_gen.go new file mode 100644 index 00000000..224d29f6 --- /dev/null +++ b/model/gmodel/fs_cloud_receive_old_gen.go @@ -0,0 +1,26 @@ +package gmodel + +import ( + "gorm.io/gorm" +) + +// fs_cloud_receive_old 云仓接收工厂总单 +type FsCloudReceiveOld struct { + Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // + CloudId *int64 `gorm:"index;default:0;" json:"cloud_id"` // 入库云仓id + AdminId *int64 `gorm:"index;default:0;" json:"admin_id"` // 操作员id + UserId *int64 `gorm:"index;default:0;" json:"user_id"` // 用户id + OrderId *int64 `gorm:"index;default:0;" json:"order_id"` // 入库云仓的订单 + Fee *int64 `gorm:"default:0;" json:"fee"` // 运费 + Delivery *string `gorm:"default:'';" json:"delivery"` // + Ctime *int64 `gorm:"default:0;" json:"ctime"` // 创建时间 + Status *int64 `gorm:"default:0;" json:"status"` // 0未收到 1收到 +} +type FsCloudReceiveOldModel struct { + db *gorm.DB + name string +} + +func NewFsCloudReceiveOldModel(db *gorm.DB) *FsCloudReceiveOldModel { + return &FsCloudReceiveOldModel{db: db, name: "fs_cloud_receive_old"} +} diff --git a/model/gmodel/fs_cloud_receive_old_logic.go b/model/gmodel/fs_cloud_receive_old_logic.go new file mode 100644 index 00000000..e68225aa --- /dev/null +++ b/model/gmodel/fs_cloud_receive_old_logic.go @@ -0,0 +1,2 @@ +package gmodel +// TODO: 使用model的属性做你想做的 \ No newline at end of file diff --git a/model/gmodel/fs_cloud_render_log_old_gen.go b/model/gmodel/fs_cloud_render_log_old_gen.go new file mode 100644 index 00000000..3abb9c33 --- /dev/null +++ b/model/gmodel/fs_cloud_render_log_old_gen.go @@ -0,0 +1,26 @@ +package gmodel + +import ( + "gorm.io/gorm" +) + +// fs_cloud_render_log_old 云渲染日志表 +type FsCloudRenderLogOld struct { + Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // ID + UserId *int64 `gorm:"default:0;" json:"user_id"` // 用户id + PostData *string `gorm:"default:'';" json:"post_data"` // + PostUrl *string `gorm:"default:'';" json:"post_url"` // + Title *string `gorm:"index;default:'';" json:"title"` // + Time *int64 `gorm:"default:0;" json:"time"` // 所用时间 + Result *string `gorm:"default:'';" json:"result"` // + Tag *string `gorm:"index;default:'';" json:"tag"` // 标识 + Ctime *int64 `gorm:"default:0;" json:"ctime"` // 添加时间 +} +type FsCloudRenderLogOldModel struct { + db *gorm.DB + name string +} + +func NewFsCloudRenderLogOldModel(db *gorm.DB) *FsCloudRenderLogOldModel { + return &FsCloudRenderLogOldModel{db: db, name: "fs_cloud_render_log_old"} +} diff --git a/model/gmodel/fs_cloud_render_log_old_logic.go b/model/gmodel/fs_cloud_render_log_old_logic.go new file mode 100644 index 00000000..e68225aa --- /dev/null +++ b/model/gmodel/fs_cloud_render_log_old_logic.go @@ -0,0 +1,2 @@ +package gmodel +// TODO: 使用model的属性做你想做的 \ No newline at end of file diff --git a/model/gmodel/fs_cloud_user_apply_back_old_gen.go b/model/gmodel/fs_cloud_user_apply_back_old_gen.go new file mode 100644 index 00000000..9c7f2dd7 --- /dev/null +++ b/model/gmodel/fs_cloud_user_apply_back_old_gen.go @@ -0,0 +1,25 @@ +package gmodel + +import ( + "gorm.io/gorm" +) + +// fs_cloud_user_apply_back_old 该表废弃 +type FsCloudUserApplyBackOld struct { + Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // + UserHash *string `gorm:"default:'';" json:"user_hash"` // + OrderDetailTemplateId *int64 `gorm:"default:0;" json:"order_detail_template_id"` // 详情modelID + Num *int64 `gorm:"default:0;" json:"num"` // 发货数量 + AddressTo *string `gorm:"default:'';" json:"address_to"` // 收获地址 + Ctime *int64 `gorm:"default:0;" json:"ctime"` // 添加时间 + StorageFee *int64 `gorm:"default:0;" json:"storage_fee"` // 存储费用 + Status *int64 `gorm:"default:0;" json:"status"` // 状态位 是否已发货 是否处理 是否删除 是否推送 +} +type FsCloudUserApplyBackOldModel struct { + db *gorm.DB + name string +} + +func NewFsCloudUserApplyBackOldModel(db *gorm.DB) *FsCloudUserApplyBackOldModel { + return &FsCloudUserApplyBackOldModel{db: db, name: "fs_cloud_user_apply_back_old"} +} diff --git a/model/gmodel/fs_cloud_user_apply_back_old_logic.go b/model/gmodel/fs_cloud_user_apply_back_old_logic.go new file mode 100644 index 00000000..e68225aa --- /dev/null +++ b/model/gmodel/fs_cloud_user_apply_back_old_logic.go @@ -0,0 +1,2 @@ +package gmodel +// TODO: 使用model的属性做你想做的 \ No newline at end of file diff --git a/model/gmodel/fs_order_affiliate_old_gen.go b/model/gmodel/fs_order_affiliate_old_gen.go new file mode 100644 index 00000000..4149fe3f --- /dev/null +++ b/model/gmodel/fs_order_affiliate_old_gen.go @@ -0,0 +1,27 @@ +package gmodel + +import ( + "gorm.io/gorm" +) + +// fs_order_affiliate_old 订单附属表-流程控制时间等 +type FsOrderAffiliateOld struct { + Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // id + OrderId *int64 `gorm:"unique_key;default:0;" json:"order_id"` // 订单id + SureTime *int64 `gorm:"default:0;" json:"sure_time"` // 确认时间 + ProductTime *int64 `gorm:"default:0;" json:"product_time"` // 生产时间 + ProductEndtime *int64 `gorm:"default:0;" json:"product_endtime"` // 生成完成时间 + DeliverTime *int64 `gorm:"default:0;" json:"deliver_time"` // 发货时间 + UpsDeliverTime *int64 `gorm:"default:0;" json:"ups_deliver_time"` // ups发货时间 + UpsTime *int64 `gorm:"default:0;" json:"ups_time"` // UPS提货时间 + ArrivalTime *int64 `gorm:"default:0;" json:"arrival_time"` // 到达云仓的时间 + RecevieTime *int64 `gorm:"default:0;" json:"recevie_time"` // 云仓收货时间 +} +type FsOrderAffiliateOldModel struct { + db *gorm.DB + name string +} + +func NewFsOrderAffiliateOldModel(db *gorm.DB) *FsOrderAffiliateOldModel { + return &FsOrderAffiliateOldModel{db: db, name: "fs_order_affiliate_old"} +} diff --git a/model/gmodel/fs_order_affiliate_old_logic.go b/model/gmodel/fs_order_affiliate_old_logic.go new file mode 100644 index 00000000..e68225aa --- /dev/null +++ b/model/gmodel/fs_order_affiliate_old_logic.go @@ -0,0 +1,2 @@ +package gmodel +// TODO: 使用model的属性做你想做的 \ No newline at end of file diff --git a/model/gmodel/fs_order_detail_old_gen.go b/model/gmodel/fs_order_detail_old_gen.go new file mode 100644 index 00000000..afc7c20f --- /dev/null +++ b/model/gmodel/fs_order_detail_old_gen.go @@ -0,0 +1,41 @@ +package gmodel + +import ( + "gorm.io/gorm" +) + +// fs_order_detail_old 订单详细表 +type FsOrderDetailOld struct { + Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // + Sn *string `gorm:"unique_key;default:'';" json:"sn"` // 唯一编码 + OrderId *int64 `gorm:"index;default:0;" json:"order_id"` // 订单ID + UserId *int64 `gorm:"default:0;" json:"user_id"` // 用户ID + FactoryId *int64 `gorm:"default:0;" json:"factory_id"` // 工厂ID + OrderDetailTemplateId *int64 `gorm:"default:0;" json:"order_detail_template_id"` // 详情templateID + ProductId *int64 `gorm:"default:0;" json:"product_id"` // 产品ID + BuyNum *int64 `gorm:"default:0;" json:"buy_num"` // 购买数量 + PushNum *int64 `gorm:"default:0;" json:"push_num"` // 已发数量 + Amount *int64 `gorm:"default:0;" json:"amount"` // 单价 + Cover *string `gorm:"default:'';" json:"cover"` // 截图 + Ctime *int64 `gorm:"default:0;" json:"ctime"` // 添加时间 + Status *int64 `gorm:"default:0;" json:"status"` // 状态位 是否推送到厂家 是否生产完成 是否发货完成 + OptionalId *int64 `gorm:"default:0;" json:"optional_id"` // 选项ID + OptionalTitle *string `gorm:"default:'';" json:"optional_title"` // 选项名称 + OptionPrice *int64 `gorm:"default:0;" json:"option_price"` // 配件价格 + IsTofactory *int64 `gorm:"default:0;" json:"is_tofactory"` // 是否推送到工厂 + IsProduct *int64 `gorm:"default:0;" json:"is_product"` // 是否生产中 + IsProductCompletion *int64 `gorm:"default:0;" json:"is_product_completion"` // 是否生产完成 + IsCloud *int64 `gorm:"default:0;" json:"is_cloud"` // 是否是云仓订单 + IsTocloud *int64 `gorm:"default:0;" json:"is_tocloud"` // 是否已发云仓(云仓单要发货到云仓,直接发到用户的不需要发到云仓) + IsDeliver *int64 `gorm:"default:0;" json:"is_deliver"` // 是否已发货 + IsEnd *int64 `gorm:"default:0;" json:"is_end"` // 是否完成订单(签收) + CartId *int64 `gorm:"index;default:0;" json:"cart_id"` // 购物车编号 +} +type FsOrderDetailOldModel struct { + db *gorm.DB + name string +} + +func NewFsOrderDetailOldModel(db *gorm.DB) *FsOrderDetailOldModel { + return &FsOrderDetailOldModel{db: db, name: "fs_order_detail_old"} +} diff --git a/model/gmodel/fs_order_detail_old_logic.go b/model/gmodel/fs_order_detail_old_logic.go new file mode 100644 index 00000000..e68225aa --- /dev/null +++ b/model/gmodel/fs_order_detail_old_logic.go @@ -0,0 +1,2 @@ +package gmodel +// TODO: 使用model的属性做你想做的 \ No newline at end of file diff --git a/model/gmodel/fs_order_detail_template_old_gen.go b/model/gmodel/fs_order_detail_template_old_gen.go new file mode 100644 index 00000000..36f74646 --- /dev/null +++ b/model/gmodel/fs_order_detail_template_old_gen.go @@ -0,0 +1,28 @@ +package gmodel + +import ( + "gorm.io/gorm" +) + +// fs_order_detail_template_old 订单模板详细表 +type FsOrderDetailTemplateOld struct { + Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // + Sn *string `gorm:"unique_key;default:'';" json:"sn"` // 唯一编码 + ProductId *int64 `gorm:"index;default:0;" json:"product_id"` // 产品ID + ModelId *int64 `gorm:"default:0;" json:"model_id"` // 模型ID + TemplateId *int64 `gorm:"index;default:0;" json:"template_id"` // 模板ID + MaterialId *int64 `gorm:"index;default:0;" json:"material_id"` // 材质id + SizeId *int64 `gorm:"index;default:0;" json:"size_id"` // 尺寸id + EachBoxNum *int64 `gorm:"default:0;" json:"each_box_num"` // 每一箱的个数 + EachBoxWeight *float64 `gorm:"default:0.00;" json:"each_box_weight"` // 每一箱的重量 单位KG + DesignId *int64 `gorm:"index;default:0;" json:"design_id"` // 设计ID + Ctime *int64 `gorm:"default:0;" json:"ctime"` // 添加时间 +} +type FsOrderDetailTemplateOldModel struct { + db *gorm.DB + name string +} + +func NewFsOrderDetailTemplateOldModel(db *gorm.DB) *FsOrderDetailTemplateOldModel { + return &FsOrderDetailTemplateOldModel{db: db, name: "fs_order_detail_template_old"} +} diff --git a/model/gmodel/fs_order_detail_template_old_logic.go b/model/gmodel/fs_order_detail_template_old_logic.go new file mode 100644 index 00000000..e68225aa --- /dev/null +++ b/model/gmodel/fs_order_detail_template_old_logic.go @@ -0,0 +1,2 @@ +package gmodel +// TODO: 使用model的属性做你想做的 \ No newline at end of file diff --git a/model/gmodel/fs_order_gen.go b/model/gmodel/fs_order_gen.go index ab34b331..66bdd701 100644 --- a/model/gmodel/fs_order_gen.go +++ b/model/gmodel/fs_order_gen.go @@ -5,44 +5,17 @@ import ( "time" ) -// fs_order +// fs_order 订单表 type FsOrder struct { - Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // - Sn *string `gorm:"unique_key;default:'';" json:"sn"` // 订单编号 FS211224OL2XDKNP - UserId *int64 `gorm:"index;default:0;" json:"user_id"` // 用户ID - SellerUserId *int64 `gorm:"default:0;" json:"seller_user_id"` // 销售员ID 0:自主下单 - TotalAmount *int64 `gorm:"default:0;" json:"total_amount"` // 总价 - PayedAmount *int64 `gorm:"default:0;" json:"payed_amount"` // 已支付金额 - PayMethod *int64 `gorm:"default:0;" json:"pay_method"` // 支付方式 1paypal 2strip - Ctime *int64 `gorm:"default:0;" json:"ctime"` // 添加时间 - Utime *int64 `gorm:"default:0;" json:"utime"` // 更新时间 - Ptime *int64 `gorm:"default:0;" json:"ptime"` // 最后一次 支付时间(可能多次支付) - AddressId *int64 `gorm:"index;default:0;" json:"address_id"` // 地址ID或者云仓ID - DeliveryMethod *int64 `gorm:"default:0;" json:"delivery_method"` // 配送方式 1:直接发货到收获地址 2:云仓 - CustomerMark *string `gorm:"default:'';" json:"customer_mark"` // 客户备注 - Mark *string `gorm:"default:'';" json:"mark"` // 后台订单备注 - AddressInfo *string `gorm:"default:'';" json:"address_info"` // 详细地址信息JSON - IsSup *int64 `gorm:"default:0;" json:"is_sup"` // 0不是补货 1是补货 - Status *int64 `gorm:"default:0;" json:"status"` // 状态位(0:未支付,1:部分支付,2:支付完成,3:部分生产,4:部分生产完成,5:全部生产,6:全部生产完成,7:部分发货,8:发货完成,9:完成订单,10:取消订单,11:退款中,12:退款完成,13:订单已删除,14:订单已关闭) - IsPartPay *int64 `gorm:"default:0;" json:"is_part_pay"` // 是否部分支付(0:否,1:是) - IsPayCompleted *int64 `gorm:"default:0;" json:"is_pay_completed"` // 是否支付完成(0:否,1:是) - IsPartProduct *int64 `gorm:"default:0;" json:"is_part_product"` // 是否部分生产(0:否,1:是) - IsPartProductCompleted *int64 `gorm:"default:0;" json:"is_part_product_completed"` // 是否部分生产完成(0:否,1:是) - IsAllProduct *int64 `gorm:"default:0;" json:"is_all_product"` // 是否全部生产(0:否,1:是) - IsAllProductCompleted *int64 `gorm:"default:0;" json:"is_all_product_completed"` // 是否全部生产完成(0:否,1:是) - IsPartDelivery *int64 `gorm:"default:0;" json:"is_part_delivery"` // 是否部分发货(0:否,1:是) - IsDeliveryCompleted *int64 `gorm:"default:0;" json:"is_delivery_completed"` // 是否发货完成(0:否,1:是) - IsComplated *int64 `gorm:"default:0;" json:"is_complated"` // 是否完成订单(0:否,1:是) - IsCancel *int64 `gorm:"default:0;" json:"is_cancel"` // 是否取消订单(0:否,1:是) - IsRefunding *int64 `gorm:"default:0;" json:"is_refunding"` // 是否退款中(0:否,1:是) - IsRefunded *int64 `gorm:"default:0;" json:"is_refunded"` // 是否退款完成(0:否,1:是) - IsDeleted *int64 `gorm:"default:0;" json:"is_deleted"` // 是否删除(0:否,1:是) - RefundReasonId *int64 `gorm:"default:0;" json:"refund_reason_id"` // 取消订单原因ID - RefundReason *string `gorm:"default:'';" json:"refund_reason"` // 取消订单原因 - TsTime *time.Time `gorm:"default:'0000-00-00 00:00:00';" json:"ts_time"` // - IsSure *int64 `gorm:"default:0;" json:"is_sure"` // 是否确认订单 1确认0未确认 - DeliverSn *string `gorm:"default:'';" json:"deliver_sn"` // 发货单号 - EmailTime *int64 `gorm:"default:0;" json:"email_time"` // 邮件发送时间 + Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // 订单ID + UserId *int64 `gorm:"index;default:0;" json:"user_id"` // 用户ID + DeliveryMethod *int64 `gorm:"index;default:0;" json:"delivery_method"` // 物流类型 + OrderNo *string `gorm:"index;default:'';" json:"order_no"` // + OrderSource *string `gorm:"default:'';" json:"order_source"` // + Status *int64 `gorm:"index;default:0;" json:"status"` // 订单状态 + Metadata *[]byte `gorm:"default:'';" json:"metadata"` // + Ctime *time.Time `gorm:"default:'0000-00-00 00:00:00';" json:"ctime"` // + Utime *time.Time `gorm:"default:'0000-00-00 00:00:00';" json:"utime"` // } type FsOrderModel struct { db *gorm.DB diff --git a/model/gmodel/fs_order_old_gen.go b/model/gmodel/fs_order_old_gen.go new file mode 100644 index 00000000..20e573ec --- /dev/null +++ b/model/gmodel/fs_order_old_gen.go @@ -0,0 +1,54 @@ +package gmodel + +import ( + "gorm.io/gorm" + "time" +) + +// fs_order_old +type FsOrderOld struct { + Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // + Sn *string `gorm:"unique_key;default:'';" json:"sn"` // 订单编号 FS211224OL2XDKNP + UserId *int64 `gorm:"index;default:0;" json:"user_id"` // 用户ID + SellerUserId *int64 `gorm:"default:0;" json:"seller_user_id"` // 销售员ID 0:自主下单 + TotalAmount *int64 `gorm:"default:0;" json:"total_amount"` // 总价 + PayedAmount *int64 `gorm:"default:0;" json:"payed_amount"` // 已支付金额 + PayMethod *int64 `gorm:"default:0;" json:"pay_method"` // 支付方式 1paypal 2strip + Ctime *int64 `gorm:"default:0;" json:"ctime"` // 添加时间 + Utime *int64 `gorm:"default:0;" json:"utime"` // 更新时间 + Ptime *int64 `gorm:"default:0;" json:"ptime"` // 最后一次 支付时间(可能多次支付) + AddressId *int64 `gorm:"index;default:0;" json:"address_id"` // 地址ID或者云仓ID + DeliveryMethod *int64 `gorm:"default:0;" json:"delivery_method"` // 配送方式 1:直接发货到收获地址 2:云仓 + CustomerMark *string `gorm:"default:'';" json:"customer_mark"` // 客户备注 + Mark *string `gorm:"default:'';" json:"mark"` // 后台订单备注 + AddressInfo *string `gorm:"default:'';" json:"address_info"` // 详细地址信息JSON + IsSup *int64 `gorm:"default:0;" json:"is_sup"` // 0不是补货 1是补货 + Status *int64 `gorm:"default:0;" json:"status"` // 状态位(0:未支付,1:部分支付,2:支付完成,3:部分生产,4:部分生产完成,5:全部生产,6:全部生产完成,7:部分发货,8:发货完成,9:完成订单,10:取消订单,11:退款中,12:退款完成,13:订单已删除,14:订单已关闭) + IsPartPay *int64 `gorm:"default:0;" json:"is_part_pay"` // 是否部分支付(0:否,1:是) + IsPayCompleted *int64 `gorm:"default:0;" json:"is_pay_completed"` // 是否支付完成(0:否,1:是) + IsPartProduct *int64 `gorm:"default:0;" json:"is_part_product"` // 是否部分生产(0:否,1:是) + IsPartProductCompleted *int64 `gorm:"default:0;" json:"is_part_product_completed"` // 是否部分生产完成(0:否,1:是) + IsAllProduct *int64 `gorm:"default:0;" json:"is_all_product"` // 是否全部生产(0:否,1:是) + IsAllProductCompleted *int64 `gorm:"default:0;" json:"is_all_product_completed"` // 是否全部生产完成(0:否,1:是) + IsPartDelivery *int64 `gorm:"default:0;" json:"is_part_delivery"` // 是否部分发货(0:否,1:是) + IsDeliveryCompleted *int64 `gorm:"default:0;" json:"is_delivery_completed"` // 是否发货完成(0:否,1:是) + IsComplated *int64 `gorm:"default:0;" json:"is_complated"` // 是否完成订单(0:否,1:是) + IsCancel *int64 `gorm:"default:0;" json:"is_cancel"` // 是否取消订单(0:否,1:是) + IsRefunding *int64 `gorm:"default:0;" json:"is_refunding"` // 是否退款中(0:否,1:是) + IsRefunded *int64 `gorm:"default:0;" json:"is_refunded"` // 是否退款完成(0:否,1:是) + IsDeleted *int64 `gorm:"default:0;" json:"is_deleted"` // 是否删除(0:否,1:是) + RefundReasonId *int64 `gorm:"default:0;" json:"refund_reason_id"` // 取消订单原因ID + RefundReason *string `gorm:"default:'';" json:"refund_reason"` // 取消订单原因 + TsTime *time.Time `gorm:"default:'0000-00-00 00:00:00';" json:"ts_time"` // + IsSure *int64 `gorm:"default:0;" json:"is_sure"` // 是否确认订单 1确认0未确认 + DeliverSn *string `gorm:"default:'';" json:"deliver_sn"` // 发货单号 + EmailTime *int64 `gorm:"default:0;" json:"email_time"` // 邮件发送时间 +} +type FsOrderOldModel struct { + db *gorm.DB + name string +} + +func NewFsOrderOldModel(db *gorm.DB) *FsOrderOldModel { + return &FsOrderOldModel{db: db, name: "fs_order_old"} +} diff --git a/model/gmodel/fs_order_old_logic.go b/model/gmodel/fs_order_old_logic.go new file mode 100644 index 00000000..e68225aa --- /dev/null +++ b/model/gmodel/fs_order_old_logic.go @@ -0,0 +1,2 @@ +package gmodel +// TODO: 使用model的属性做你想做的 \ No newline at end of file diff --git a/model/gmodel/fs_order_remark_old_gen.go b/model/gmodel/fs_order_remark_old_gen.go new file mode 100644 index 00000000..7c37fe76 --- /dev/null +++ b/model/gmodel/fs_order_remark_old_gen.go @@ -0,0 +1,22 @@ +package gmodel + +import ( + "gorm.io/gorm" +) + +// fs_order_remark_old 订单备注表 +type FsOrderRemarkOld struct { + Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // id + OrderId *int64 `gorm:"index;default:0;" json:"order_id"` // 订单id + Remark *string `gorm:"default:'';" json:"remark"` // 订单备注 + AdminId *int64 `gorm:"default:0;" json:"admin_id"` // 后台操作人员 + Ctime *int64 `gorm:"default:0;" json:"ctime"` // 添加时间 +} +type FsOrderRemarkOldModel struct { + db *gorm.DB + name string +} + +func NewFsOrderRemarkOldModel(db *gorm.DB) *FsOrderRemarkOldModel { + return &FsOrderRemarkOldModel{db: db, name: "fs_order_remark_old"} +} diff --git a/model/gmodel/fs_order_remark_old_logic.go b/model/gmodel/fs_order_remark_old_logic.go new file mode 100644 index 00000000..e68225aa --- /dev/null +++ b/model/gmodel/fs_order_remark_old_logic.go @@ -0,0 +1,2 @@ +package gmodel +// TODO: 使用model的属性做你想做的 \ No newline at end of file diff --git a/model/gmodel/fs_order_trade_event_gen.go b/model/gmodel/fs_order_trade_event_gen.go new file mode 100644 index 00000000..6fa748c8 --- /dev/null +++ b/model/gmodel/fs_order_trade_event_gen.go @@ -0,0 +1,25 @@ +package gmodel + +import ( + "gorm.io/gorm" + "time" +) + +// fs_order_trade_event 订单交易事件表 +type FsOrderTradeEvent struct { + Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // 订单交易ID + PayMethod *int64 `gorm:"default:0;" json:"pay_method"` // 支付方式:1=stripe,2=paypal + EventId *string `gorm:"default:'';" json:"event_id"` // + EventType *string `gorm:"default:'';" json:"event_type"` // + EventData *[]byte `gorm:"default:'';" json:"event_data"` // + Ctime *time.Time `gorm:"default:'0000-00-00 00:00:00';" json:"ctime"` // + Utime *time.Time `gorm:"default:'0000-00-00 00:00:00';" json:"utime"` // +} +type FsOrderTradeEventModel struct { + db *gorm.DB + name string +} + +func NewFsOrderTradeEventModel(db *gorm.DB) *FsOrderTradeEventModel { + return &FsOrderTradeEventModel{db: db, name: "fs_order_trade_event"} +} diff --git a/model/gmodel/fs_order_trade_event_logic.go b/model/gmodel/fs_order_trade_event_logic.go new file mode 100644 index 00000000..e68225aa --- /dev/null +++ b/model/gmodel/fs_order_trade_event_logic.go @@ -0,0 +1,2 @@ +package gmodel +// TODO: 使用model的属性做你想做的 \ No newline at end of file diff --git a/model/gmodel/fs_order_trade_gen.go b/model/gmodel/fs_order_trade_gen.go new file mode 100644 index 00000000..01414724 --- /dev/null +++ b/model/gmodel/fs_order_trade_gen.go @@ -0,0 +1,36 @@ +package gmodel + +import ( + "gorm.io/gorm" + "time" +) + +// fs_order_trade 订单交易表 +type FsOrderTrade struct { + Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // 订单交易ID + UserId *int64 `gorm:"index;default:0;" json:"user_id"` // 用户ID + OrderNo *string `gorm:"default:'';" json:"order_no"` // + OrderSource *string `gorm:"default:'';" json:"order_source"` // + TradeNo *string `gorm:"index;default:'';" json:"trade_no"` // + PayAmount *int64 `gorm:"default:0;" json:"pay_amount"` // 支付金额 (分) + PayStatus *int64 `gorm:"default:0;" json:"pay_status"` // 支付状态:1=未成功,2=已成功 + PaymentMethod *int64 `gorm:"default:0;" json:"payment_method"` // 支付方式:1=stripe,2=paypal + PayStage *int64 `gorm:"default:0;" json:"pay_stage"` // 支付阶段:1=首付,2=尾款 + RefundStatus *int64 `gorm:"default:0;" json:"refund_status"` // 退款状态:1=未退款,2=已退款 + CardNo *string `gorm:"default:'';" json:"card_no"` // + CardBrand *string `gorm:"default:'';" json:"card_brand"` // + Country *string `gorm:"default:'';" json:"country"` // + Currency *string `gorm:"default:'';" json:"currency"` // + Metadata *[]byte `gorm:"default:'';" json:"metadata"` // + Ctime *time.Time `gorm:"default:'0000-00-00 00:00:00';" json:"ctime"` // + Utime *time.Time `gorm:"default:'0000-00-00 00:00:00';" json:"utime"` // + PayTitle *string `gorm:"default:'';" json:"pay_title"` // +} +type FsOrderTradeModel struct { + db *gorm.DB + name string +} + +func NewFsOrderTradeModel(db *gorm.DB) *FsOrderTradeModel { + return &FsOrderTradeModel{db: db, name: "fs_order_trade"} +} diff --git a/model/gmodel/fs_order_trade_logic.go b/model/gmodel/fs_order_trade_logic.go new file mode 100644 index 00000000..e68225aa --- /dev/null +++ b/model/gmodel/fs_order_trade_logic.go @@ -0,0 +1,2 @@ +package gmodel +// TODO: 使用model的属性做你想做的 \ No newline at end of file diff --git a/model/gmodel/fs_shopping_cart_gen.go b/model/gmodel/fs_shopping_cart_gen.go index 2997ec11..04996ad2 100644 --- a/model/gmodel/fs_shopping_cart_gen.go +++ b/model/gmodel/fs_shopping_cart_gen.go @@ -17,8 +17,6 @@ type FsShoppingCart struct { PurchaseQuantity *int64 `gorm:"default:0;" json:"purchase_quantity"` // 购买数量 Snapshot *string `gorm:"default:'';" json:"snapshot"` // IsHighlyCustomized *int64 `gorm:"default:0;" json:"is_highly_customized"` // 是否高度定制 0非 1是(针对客人高度定制只能后台增加如购物车) - Status *int64 `gorm:"default:0;" json:"status"` // 0未下单 1已下单 - IsEffective *int64 `gorm:"default:1;" json:"is_effective"` // 是否有效 0非 1是(针对对购物车下单,此前数据表更失效) Ctime *time.Time `gorm:"default:'0000-00-00 00:00:00';" json:"ctime"` // Utime *time.Time `gorm:"default:'0000-00-00 00:00:00';" json:"utime"` // } diff --git a/model/gmodel/var_gen.go b/model/gmodel/var_gen.go index 1d92c033..2637c166 100644 --- a/model/gmodel/var_gen.go +++ b/model/gmodel/var_gen.go @@ -24,14 +24,20 @@ type AllModelsGen struct { FsCart *FsCartModel // fs_cart 购物车 FsChangeCode *FsChangeCodeModel // fs_change_code 忘记密码code表 FsCloud *FsCloudModel // fs_cloud 云仓表 - FsCloudDeliverEveryTmp *FsCloudDeliverEveryTmpModel // fs_cloud_deliver_every_tmp - FsCloudDeliverTmp *FsCloudDeliverTmpModel // fs_cloud_deliver_tmp + FsCloudDeliverEveryTmpOld *FsCloudDeliverEveryTmpOldModel // fs_cloud_deliver_every_tmp_old + FsCloudDeliverTmpOld *FsCloudDeliverTmpOldModel // fs_cloud_deliver_tmp_old + FsCloudOld *FsCloudOldModel // fs_cloud_old 云仓表 FsCloudPickUp *FsCloudPickUpModel // fs_cloud_pick_up 云仓提货单 FsCloudPickUpDetail *FsCloudPickUpDetailModel // fs_cloud_pick_up_detail 云仓提货单-详情 + FsCloudPickUpDetailOld *FsCloudPickUpDetailOldModel // fs_cloud_pick_up_detail_old 云仓提货单-详情 + FsCloudPickUpOld *FsCloudPickUpOldModel // fs_cloud_pick_up_old 云仓提货单 FsCloudReceive *FsCloudReceiveModel // fs_cloud_receive 云仓接收工厂总单 - FsCloudReceiveEvery *FsCloudReceiveEveryModel // fs_cloud_receive_every + FsCloudReceiveEveryOld *FsCloudReceiveEveryOldModel // fs_cloud_receive_every_old + FsCloudReceiveOld *FsCloudReceiveOldModel // fs_cloud_receive_old 云仓接收工厂总单 FsCloudRenderLog *FsCloudRenderLogModel // fs_cloud_render_log 云渲染日志表 + FsCloudRenderLogOld *FsCloudRenderLogOldModel // fs_cloud_render_log_old 云渲染日志表 FsCloudUserApplyBack *FsCloudUserApplyBackModel // fs_cloud_user_apply_back 该表废弃 + FsCloudUserApplyBackOld *FsCloudUserApplyBackOldModel // fs_cloud_user_apply_back_old 该表废弃 FsContact *FsContactModel // fs_contact 该表暂未使用 FsContactService *FsContactServiceModel // fs_contact_service FsCoupon *FsCouponModel // fs_coupon 代金券(暂未使用) @@ -55,11 +61,18 @@ type AllModelsGen struct { FsMenu *FsMenuModel // fs_menu 后台菜单 FsMerchantCategory *FsMerchantCategoryModel // fs_merchant_category 商户类型表 FsMigration *FsMigrationModel // fs_migration 版本库 - FsOrder *FsOrderModel // fs_order + FsOrder *FsOrderModel // fs_order 订单表 FsOrderAffiliate *FsOrderAffiliateModel // fs_order_affiliate 订单附属表-流程控制时间等 + FsOrderAffiliateOld *FsOrderAffiliateOldModel // fs_order_affiliate_old 订单附属表-流程控制时间等 FsOrderDetail *FsOrderDetailModel // fs_order_detail 订单详细表 + FsOrderDetailOld *FsOrderDetailOldModel // fs_order_detail_old 订单详细表 FsOrderDetailTemplate *FsOrderDetailTemplateModel // fs_order_detail_template 订单模板详细表 + FsOrderDetailTemplateOld *FsOrderDetailTemplateOldModel // fs_order_detail_template_old 订单模板详细表 + FsOrderOld *FsOrderOldModel // fs_order_old FsOrderRemark *FsOrderRemarkModel // fs_order_remark 订单备注表 + FsOrderRemarkOld *FsOrderRemarkOldModel // fs_order_remark_old 订单备注表 + FsOrderTrade *FsOrderTradeModel // fs_order_trade 订单交易表 + FsOrderTradeEvent *FsOrderTradeEventModel // fs_order_trade_event 订单交易事件表 FsPay *FsPayModel // fs_pay 支付记录 FsPayEvent *FsPayEventModel // fs_pay_event 支付回调事件日志 FsProduct *FsProductModel // fs_product 产品表 @@ -131,14 +144,20 @@ func NewAllModels(gdb *gorm.DB) *AllModelsGen { FsCart: NewFsCartModel(gdb), FsChangeCode: NewFsChangeCodeModel(gdb), FsCloud: NewFsCloudModel(gdb), - FsCloudDeliverEveryTmp: NewFsCloudDeliverEveryTmpModel(gdb), - FsCloudDeliverTmp: NewFsCloudDeliverTmpModel(gdb), + FsCloudDeliverEveryTmpOld: NewFsCloudDeliverEveryTmpOldModel(gdb), + FsCloudDeliverTmpOld: NewFsCloudDeliverTmpOldModel(gdb), + FsCloudOld: NewFsCloudOldModel(gdb), FsCloudPickUp: NewFsCloudPickUpModel(gdb), FsCloudPickUpDetail: NewFsCloudPickUpDetailModel(gdb), + FsCloudPickUpDetailOld: NewFsCloudPickUpDetailOldModel(gdb), + FsCloudPickUpOld: NewFsCloudPickUpOldModel(gdb), FsCloudReceive: NewFsCloudReceiveModel(gdb), - FsCloudReceiveEvery: NewFsCloudReceiveEveryModel(gdb), + FsCloudReceiveEveryOld: NewFsCloudReceiveEveryOldModel(gdb), + FsCloudReceiveOld: NewFsCloudReceiveOldModel(gdb), FsCloudRenderLog: NewFsCloudRenderLogModel(gdb), + FsCloudRenderLogOld: NewFsCloudRenderLogOldModel(gdb), FsCloudUserApplyBack: NewFsCloudUserApplyBackModel(gdb), + FsCloudUserApplyBackOld: NewFsCloudUserApplyBackOldModel(gdb), FsContact: NewFsContactModel(gdb), FsContactService: NewFsContactServiceModel(gdb), FsCoupon: NewFsCouponModel(gdb), @@ -164,9 +183,16 @@ func NewAllModels(gdb *gorm.DB) *AllModelsGen { FsMigration: NewFsMigrationModel(gdb), FsOrder: NewFsOrderModel(gdb), FsOrderAffiliate: NewFsOrderAffiliateModel(gdb), + FsOrderAffiliateOld: NewFsOrderAffiliateOldModel(gdb), FsOrderDetail: NewFsOrderDetailModel(gdb), + FsOrderDetailOld: NewFsOrderDetailOldModel(gdb), FsOrderDetailTemplate: NewFsOrderDetailTemplateModel(gdb), + FsOrderDetailTemplateOld: NewFsOrderDetailTemplateOldModel(gdb), + FsOrderOld: NewFsOrderOldModel(gdb), FsOrderRemark: NewFsOrderRemarkModel(gdb), + FsOrderRemarkOld: NewFsOrderRemarkOldModel(gdb), + FsOrderTrade: NewFsOrderTradeModel(gdb), + FsOrderTradeEvent: NewFsOrderTradeEventModel(gdb), FsPay: NewFsPayModel(gdb), FsPayEvent: NewFsPayEventModel(gdb), FsProduct: NewFsProductModel(gdb), From fd16d6ac67893bf7fcee1cb69b04bf36fece9901 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Fri, 15 Sep 2023 14:19:14 +0800 Subject: [PATCH 15/59] fix --- model/gmodel/fs_shopping_cart_logic.go | 12 +- .../internal/logic/addtocartlogic.go | 11 +- .../internal/logic/deletecartlogic.go | 1 + .../internal/logic/getcartslogic.go | 106 +++++++++++++++++- .../logic/modifycartpurchasequantitylogic.go | 1 + server/shopping-cart/internal/types/types.go | 8 +- server_api/shopping-cart.api | 7 +- utils/shopping_cart/shopping_cart_snapshot.go | 6 +- .../verify_shopping_cart_channged.go | 2 + 9 files changed, 136 insertions(+), 18 deletions(-) diff --git a/model/gmodel/fs_shopping_cart_logic.go b/model/gmodel/fs_shopping_cart_logic.go index bc5f4101..cc833471 100644 --- a/model/gmodel/fs_shopping_cart_logic.go +++ b/model/gmodel/fs_shopping_cart_logic.go @@ -24,22 +24,22 @@ func (s *FsShoppingCartModel) FineOneUserCart(ctx context.Context, id, userId in // 创建 func (s *FsShoppingCartModel) Create(ctx context.Context, data *FsShoppingCart) error { - return s.db.WithContext(ctx).Create(&data).Error + return s.db.WithContext(ctx).Model(&FsShoppingCart{}).Create(&data).Error } // 删除 func (s *FsShoppingCartModel) Delete(ctx context.Context, id, userId int64) error { - return s.db.WithContext(ctx).Where("user_id = ? and id = ?", userId, id).Delete(&FsShoppingCart{}).Error + return s.db.WithContext(ctx).Model(&FsShoppingCart{}).Where("user_id = ? and id = ?", userId, id).Delete(&FsShoppingCart{}).Error } // 更新 func (s *FsShoppingCartModel) Update(ctx context.Context, id, userId int64, data *FsShoppingCart) error { - return s.db.WithContext(ctx).Where("user_id = ? and id = ?", userId, id).Updates(&data).Error + return s.db.WithContext(ctx).Model(&FsShoppingCart{}).Where("user_id = ? and id = ?", userId, id).Updates(&data).Error } // 获取用户购物车数量 func (s *FsShoppingCartModel) CountUserCart(ctx context.Context, userId int64) (total int64, err error) { - err = s.db.WithContext(ctx).Where("user_id = ?", userId).Limit(1).Count(&total).Error + err = s.db.WithContext(ctx).Model(&FsShoppingCart{}).Where("user_id = ?", userId).Limit(1).Count(&total).Error return total, err } @@ -48,7 +48,7 @@ func (s *FsShoppingCartModel) GetAllByIds(ctx context.Context, ids []int64, sort if len(ids) == 0 { return } - db := s.db.WithContext(ctx).Where("id in (?)", ids) + db := s.db.WithContext(ctx).Model(&FsShoppingCart{}).Where("id in (?)", ids) if len(fields) > 0 { db = db.Select(fields[0]) } @@ -70,7 +70,7 @@ type GetAllCartsByParamReq struct { } func (s *FsShoppingCartModel) GetAllCartsByParam(ctx context.Context, req GetAllCartsByParamReq) (resp []FsShoppingCart, total int64, err error) { - db := s.db.WithContext(ctx) + db := s.db.WithContext(ctx).Model(&FsShoppingCart{}) if req.UserId > 0 { db = db.Where("user_id = ?", req.UserId) } diff --git a/server/shopping-cart/internal/logic/addtocartlogic.go b/server/shopping-cart/internal/logic/addtocartlogic.go index 6194aea9..a82d7d7a 100644 --- a/server/shopping-cart/internal/logic/addtocartlogic.go +++ b/server/shopping-cart/internal/logic/addtocartlogic.go @@ -36,6 +36,7 @@ func NewAddToCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddToCa // } func (l *AddToCartLogic) AddToCart(req *types.AddToCartReq, userinfo *auth.UserInfo) (resp *basic.Response) { + userinfo.UserId = 39 if !userinfo.IsUser() { return resp.SetStatusWithMessage(basic.CodeUnAuth, "please sign in") } @@ -65,6 +66,7 @@ func (l *AddToCartLogic) AddToCart(req *types.AddToCartReq, userinfo *auth.UserI templateJson string //模板表的记录中的json设计信息 templateTag string //模板表的模板标签 fittingJson string //配件的json设计信息 + fittingName string //配件名 ) //有模板 if req.TemplateId > 0 { @@ -105,6 +107,7 @@ func (l *AddToCartLogic) AddToCart(req *types.AddToCartReq, userinfo *auth.UserI return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "the fitting`s design info is empty") } fittingJson = *fittingInfo.ModelInfo + fittingName = *fittingInfo.Title } //获取尺寸信息 sizeInfo, err := l.svcCtx.AllModels.FsProductSize.FindOne(l.ctx, req.SizeId) @@ -138,11 +141,12 @@ func (l *AddToCartLogic) AddToCart(req *types.AddToCartReq, userinfo *auth.UserI if modelInfo.ModelInfo == nil || *modelInfo.ModelInfo == "" { return resp.SetStatusWithMessage(basic.CodeServiceErr, "the model`s design info is empty") } - var sizeTitleInfo shopping_cart.SizeInfo - if err = json.Unmarshal([]byte(*sizeInfo.Title), &sizeTitleInfo); err != nil { + var sizeKeyInfo shopping_cart.SizeInfo + if err = json.Unmarshal([]byte(*sizeInfo.Title), &sizeKeyInfo); err != nil { logx.Error(err) return resp.SetStatusWithMessage(basic.CodeJsonErr, "failed to parse size info`s title ") } + sizeKeyInfo.Capacity = *sizeInfo.Capacity //快照数据 snapshot := shopping_cart.CartSnapshot{ Logo: req.Logo, @@ -157,8 +161,9 @@ func (l *AddToCartLogic) AddToCart(req *types.AddToCartReq, userinfo *auth.UserI }, FittingInfo: shopping_cart.FittingInfo{ FittingJson: fittingJson, + FittingName: fittingName, }, - SizeInfo: sizeTitleInfo, + SizeInfo: sizeKeyInfo, ProductInfo: shopping_cart.ProductInfo{ ProductName: *productInfo.Title, ProductSn: *productInfo.Sn, diff --git a/server/shopping-cart/internal/logic/deletecartlogic.go b/server/shopping-cart/internal/logic/deletecartlogic.go index 4c1bc37b..d868d52e 100644 --- a/server/shopping-cart/internal/logic/deletecartlogic.go +++ b/server/shopping-cart/internal/logic/deletecartlogic.go @@ -31,6 +31,7 @@ func NewDeleteCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Delete // } func (l *DeleteCartLogic) DeleteCart(req *types.DeleteCartReq, userinfo *auth.UserInfo) (resp *basic.Response) { + userinfo.UserId = 39 if !userinfo.IsUser() { return resp.SetStatusWithMessage(basic.CodeUnAuth, "please sign in") } diff --git a/server/shopping-cart/internal/logic/getcartslogic.go b/server/shopping-cart/internal/logic/getcartslogic.go index 015b88fb..204836a9 100644 --- a/server/shopping-cart/internal/logic/getcartslogic.go +++ b/server/shopping-cart/internal/logic/getcartslogic.go @@ -2,12 +2,16 @@ package logic import ( "context" + "fmt" "fusenapi/constants" "fusenapi/model/gmodel" "fusenapi/utils/auth" "fusenapi/utils/basic" + "fusenapi/utils/format" "fusenapi/utils/shopping_cart" + "fusenapi/utils/step_price" "math" + "strings" "fusenapi/server/shopping-cart/internal/svc" "fusenapi/server/shopping-cart/internal/types" @@ -34,6 +38,7 @@ func NewGetCartsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetCarts // } func (l *GetCartsLogic) GetCarts(req *types.GetCartsReq, userinfo *auth.UserInfo) (resp *basic.Response) { + userinfo.UserId = 39 if req.CurrentPage <= 0 { req.CurrentPage = constants.DEFAULT_PAGE } @@ -102,6 +107,7 @@ func (l *GetCartsLogic) GetCarts(req *types.GetCartsReq, userinfo *auth.UserInfo } //定义map收集变更信息 mapCartChange := make(map[int64]string) + mapSnapshot := make(map[int64]shopping_cart.CartSnapshot) //校验购物车数据是否变更 err = shopping_cart.VerifyShoppingCartSnapshotDataChange(shopping_cart.VerifyShoppingCartSnapshotDataChangeReq{ Carts: carts, @@ -109,16 +115,106 @@ func (l *GetCartsLogic) GetCarts(req *types.GetCartsReq, userinfo *auth.UserInfo MapModel: mapModel, MapTemplate: mapTemplate, MapCartChange: mapCartChange, + MapSnapshot: mapSnapshot, }) if err != nil { logx.Error("VerifyShoppingCartSnapshotDataChange err:", err.Error()) return resp.SetStatusWithMessage(basic.CodeServiceErr, "system err:failed to check shopping cart change data") } - /*list := make([]types.CartItem, 0, lenCarts) - for index := range carts { - - }*/ - return resp.SetStatus(basic.CodeOK) + //根据sizeid获取价格列表 + priceList, err := l.svcCtx.AllModels.FsProductPrice.GetPriceListBySizeIds(l.ctx, sizeIds) + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get cart`s product price list") + } + mapSizePrice := make(map[int64]gmodel.FsProductPrice) + for _, v := range priceList { + mapSizePrice[*v.SizeId] = v + } + list := make([]types.CartItem, 0, lenCarts) + for _, cart := range carts { + snapShot := mapSnapshot[cart.Id] + sizePrice, ok := mapSizePrice[*cart.SizeId] + if !ok { + return resp.SetStatusWithMessage(basic.CodeServiceErr, fmt.Sprintf("the size`s price info is not exists:%d", *cart.SizeId)) + } + //阶梯数量切片 + stepNum, err := format.StrSlicToIntSlice(strings.Split(*sizePrice.StepNum, ",")) + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeServiceErr, fmt.Sprintf("failed to parse step number:%d", *cart.SizeId)) + } + lenStepNum := len(stepNum) + //阶梯价格切片 + stepPrice, err := format.StrSlicToIntSlice(strings.Split(*sizePrice.StepPrice, ",")) + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeServiceErr, fmt.Sprintf("failed to parse step price:%d", *cart.SizeId)) + } + lenStepPrice := len(stepPrice) + if lenStepPrice == 0 || lenStepNum == 0 { + return resp.SetStatusWithMessage(basic.CodeServiceErr, fmt.Sprintf("step price or step number is not set:%d ", *cart.SizeId)) + } + //购买箱数 + boxQuantity := int(math.Ceil(float64(*cart.PurchaseQuantity) / float64(*sizePrice.EachBoxNum))) + //获取阶梯数量 + stepQuantityList := make([]types.StepNumItem, 0, 10) + tmpMinBuyNum := *sizePrice.MinBuyNum + for tmpMinBuyNum < (int64(stepNum[lenStepNum-1]) + 5) { + //阶梯数 + tmpQuantity := tmpMinBuyNum * (*sizePrice.EachBoxNum) + stepQuantityList = append(stepQuantityList, types.StepNumItem{ + PurchaseQuantity: tmpQuantity, + IsSelected: *cart.PurchaseQuantity == tmpQuantity, + }) + tmpMinBuyNum++ + } + //根据数量获取阶梯价格中对应的价格 + itemPrice := step_price.GetStepPrice(boxQuantity, stepNum, stepPrice) + totalPrice := itemPrice * float64(*cart.PurchaseQuantity) + item := types.CartItem{ + ProductId: *cart.ProductId, + SizeInfo: types.SizeInfo{ + SizeId: *cart.SizeId, + Capacity: snapShot.SizeInfo.Capacity, + Title: types.SizeTitle{ + Cm: snapShot.SizeInfo.Cm, + Inch: snapShot.SizeInfo.Inch, + }, + }, + FittingInfo: types.FittingInfo{ + FittingId: *cart.FittingId, + FittingName: snapShot.FittingInfo.FittingName, + }, + ItemPrice: fmt.Sprintf("%.3f", itemPrice), + TotalPrice: fmt.Sprintf("%.3f", totalPrice), + DiyInformation: types.DiyInformation{ + Phone: snapShot.UserDiyInformation.Phone, + Address: snapShot.UserDiyInformation.Address, + Website: snapShot.UserDiyInformation.Website, + Qrcode: snapShot.UserDiyInformation.Qrcode, + Slogan: snapShot.UserDiyInformation.Slogan, + }, + StepNum: stepQuantityList, + IsInvalid: false, + InvalidDescription: "", + } + //是否有失效的 + if description, ok := mapCartChange[cart.Id]; ok { + item.IsInvalid = true + item.InvalidDescription = description + } + list = append(list, item) + } + return resp.SetStatusWithMessage(basic.CodeOK, "success", types.GetCartsRsp{ + Meta: types.Meta{ + TotalCount: total, + PageCount: int64(math.Ceil(float64(total) / float64(limit))), + CurrentPage: req.CurrentPage, + PerPage: limit, + }, + CartList: list, + }) } // 处理逻辑后 w,r 如:重定向, resp 必须重新处理 diff --git a/server/shopping-cart/internal/logic/modifycartpurchasequantitylogic.go b/server/shopping-cart/internal/logic/modifycartpurchasequantitylogic.go index b78dd2e8..916f85da 100644 --- a/server/shopping-cart/internal/logic/modifycartpurchasequantitylogic.go +++ b/server/shopping-cart/internal/logic/modifycartpurchasequantitylogic.go @@ -34,6 +34,7 @@ func NewModifyCartPurchaseQuantityLogic(ctx context.Context, svcCtx *svc.Service // } func (l *ModifyCartPurchaseQuantityLogic) ModifyCartPurchaseQuantity(req *types.ModifyCartPurchaseQuantityReq, userinfo *auth.UserInfo) (resp *basic.Response) { + userinfo.UserId = 39 if !userinfo.IsUser() { return resp.SetStatusWithMessage(basic.CodeUnAuth, "please sign in") } diff --git a/server/shopping-cart/internal/types/types.go b/server/shopping-cart/internal/types/types.go index 8fe8d2a2..7ee9b52d 100644 --- a/server/shopping-cart/internal/types/types.go +++ b/server/shopping-cart/internal/types/types.go @@ -50,11 +50,16 @@ type CartItem struct { ItemPrice string `json:"item_price"` //单价 TotalPrice string `json:"totalPrice"` //单价X数量=总价 DiyInformation DiyInformation `json:"diy_information"` //diy信息 - StepNum []int64 `json:"step_num"` //阶梯数量 + StepNum []StepNumItem `json:"step_num"` //阶梯数量 IsInvalid bool `json:"is_invalid"` //是否无效 InvalidDescription string `json:"invalid_description"` //无效原因 } +type StepNumItem struct { + PurchaseQuantity int64 `json:"purchase_quantity"` //数量 + IsSelected bool `json:"is_selected"` //是否选中 +} + type SizeInfo struct { SizeId int64 `json:"size_id"` //尺寸id Capacity string `json:"capacity"` //尺寸名称 @@ -76,6 +81,7 @@ type DiyInformation struct { Address string `json:"address"` Website string `json:"website"` Qrcode string `json:"qrcode"` + Slogan string `json:"slogan"` } type Request struct { diff --git a/server_api/shopping-cart.api b/server_api/shopping-cart.api index 7e96eebb..15bb5c98 100644 --- a/server_api/shopping-cart.api +++ b/server_api/shopping-cart.api @@ -66,10 +66,14 @@ type CartItem { ItemPrice string `json:"item_price"` //单价 TotalPrice string `json:"totalPrice"` //单价X数量=总价 DiyInformation DiyInformation `json:"diy_information"` //diy信息 - StepNum []int64 `json:"step_num"` //阶梯数量 + StepNum []StepNumItem `json:"step_num"` //阶梯数量 IsInvalid bool `json:"is_invalid"` //是否无效 InvalidDescription string `json:"invalid_description"` //无效原因 } +type StepNumItem { + PurchaseQuantity int64 `json:"purchase_quantity"` //数量 + IsSelected bool `json:"is_selected"` //是否选中 +} type SizeInfo { SizeId int64 `json:"size_id"` //尺寸id Capacity string `json:"capacity"` //尺寸名称 @@ -88,4 +92,5 @@ type DiyInformation { Address string `json:"address"` Website string `json:"website"` Qrcode string `json:"qrcode"` + Slogan string `json:"slogan"` } \ No newline at end of file diff --git a/utils/shopping_cart/shopping_cart_snapshot.go b/utils/shopping_cart/shopping_cart_snapshot.go index b0ab5797..07df7c9c 100644 --- a/utils/shopping_cart/shopping_cart_snapshot.go +++ b/utils/shopping_cart/shopping_cart_snapshot.go @@ -21,14 +21,16 @@ type ModelInfo struct { } type FittingInfo struct { FittingJson string `json:"fitting_json"` //配件设计json数据 + FittingName string `json:"fitting_name"` //配件名称 } type TemplateInfo struct { TemplateJson string `json:"template_json"` //模板设计json数据 TemplateTag string `json:"template_tag"` //模板标签 } type SizeInfo struct { - Inch string `json:"inch"` - Cm string `json:"cm"` + Inch string `json:"inch"` + Cm string `json:"cm"` + Capacity string `json:"capacity"` } type UserDiyInformation struct { Phone string `json:"phone"` //电话 diff --git a/utils/shopping_cart/verify_shopping_cart_channged.go b/utils/shopping_cart/verify_shopping_cart_channged.go index 6863291b..d237e5ec 100644 --- a/utils/shopping_cart/verify_shopping_cart_channged.go +++ b/utils/shopping_cart/verify_shopping_cart_channged.go @@ -14,6 +14,7 @@ type VerifyShoppingCartSnapshotDataChangeReq struct { MapModel map[int64]gmodel.FsProductModel3d //模型跟配件都在 MapTemplate map[int64]gmodel.FsProductTemplateV2 MapCartChange map[int64]string + MapSnapshot map[int64]CartSnapshot } func VerifyShoppingCartSnapshotDataChange(req VerifyShoppingCartSnapshotDataChangeReq) error { @@ -22,6 +23,7 @@ func VerifyShoppingCartSnapshotDataChange(req VerifyShoppingCartSnapshotDataChan if err := json.Unmarshal([]byte(*cartInfo.Snapshot), &snapShotParseInfo); err != nil { return err } + req.MapSnapshot[cartInfo.Id] = snapShotParseInfo //快照中模板设计json数据哈希值 snapshotTemplateJsonHash := hash.JsonHashKey(snapShotParseInfo.TemplateInfo.TemplateJson) //快照中模型设计json数据哈希值 From f72a0b9f7dd5491af503863ef43d8ee00c00c077 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Fri, 15 Sep 2023 14:20:08 +0800 Subject: [PATCH 16/59] fix --- server/shopping-cart/internal/logic/addtocartlogic.go | 1 - server/shopping-cart/internal/logic/deletecartlogic.go | 1 - server/shopping-cart/internal/logic/getcartslogic.go | 1 - .../internal/logic/modifycartpurchasequantitylogic.go | 1 - 4 files changed, 4 deletions(-) diff --git a/server/shopping-cart/internal/logic/addtocartlogic.go b/server/shopping-cart/internal/logic/addtocartlogic.go index a82d7d7a..e792eefe 100644 --- a/server/shopping-cart/internal/logic/addtocartlogic.go +++ b/server/shopping-cart/internal/logic/addtocartlogic.go @@ -36,7 +36,6 @@ func NewAddToCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddToCa // } func (l *AddToCartLogic) AddToCart(req *types.AddToCartReq, userinfo *auth.UserInfo) (resp *basic.Response) { - userinfo.UserId = 39 if !userinfo.IsUser() { return resp.SetStatusWithMessage(basic.CodeUnAuth, "please sign in") } diff --git a/server/shopping-cart/internal/logic/deletecartlogic.go b/server/shopping-cart/internal/logic/deletecartlogic.go index d868d52e..4c1bc37b 100644 --- a/server/shopping-cart/internal/logic/deletecartlogic.go +++ b/server/shopping-cart/internal/logic/deletecartlogic.go @@ -31,7 +31,6 @@ func NewDeleteCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Delete // } func (l *DeleteCartLogic) DeleteCart(req *types.DeleteCartReq, userinfo *auth.UserInfo) (resp *basic.Response) { - userinfo.UserId = 39 if !userinfo.IsUser() { return resp.SetStatusWithMessage(basic.CodeUnAuth, "please sign in") } diff --git a/server/shopping-cart/internal/logic/getcartslogic.go b/server/shopping-cart/internal/logic/getcartslogic.go index 204836a9..436831f9 100644 --- a/server/shopping-cart/internal/logic/getcartslogic.go +++ b/server/shopping-cart/internal/logic/getcartslogic.go @@ -38,7 +38,6 @@ func NewGetCartsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetCarts // } func (l *GetCartsLogic) GetCarts(req *types.GetCartsReq, userinfo *auth.UserInfo) (resp *basic.Response) { - userinfo.UserId = 39 if req.CurrentPage <= 0 { req.CurrentPage = constants.DEFAULT_PAGE } diff --git a/server/shopping-cart/internal/logic/modifycartpurchasequantitylogic.go b/server/shopping-cart/internal/logic/modifycartpurchasequantitylogic.go index 916f85da..b78dd2e8 100644 --- a/server/shopping-cart/internal/logic/modifycartpurchasequantitylogic.go +++ b/server/shopping-cart/internal/logic/modifycartpurchasequantitylogic.go @@ -34,7 +34,6 @@ func NewModifyCartPurchaseQuantityLogic(ctx context.Context, svcCtx *svc.Service // } func (l *ModifyCartPurchaseQuantityLogic) ModifyCartPurchaseQuantity(req *types.ModifyCartPurchaseQuantityReq, userinfo *auth.UserInfo) (resp *basic.Response) { - userinfo.UserId = 39 if !userinfo.IsUser() { return resp.SetStatusWithMessage(basic.CodeUnAuth, "please sign in") } From ee9246839281793d6071e92ac4cafc6cc621d517 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Fri, 15 Sep 2023 14:52:36 +0800 Subject: [PATCH 17/59] fix --- server/shopping-cart/internal/handler/routes.go | 6 +++--- .../shopping-cart/internal/logic/getcartslogic.go | 14 ++++++++++---- server_api/shopping-cart.api | 6 +++--- utils/format/price.go | 6 +++--- utils/step_price/price.go | 10 +++++----- 5 files changed, 24 insertions(+), 18 deletions(-) diff --git a/server/shopping-cart/internal/handler/routes.go b/server/shopping-cart/internal/handler/routes.go index 08ade841..9857154b 100644 --- a/server/shopping-cart/internal/handler/routes.go +++ b/server/shopping-cart/internal/handler/routes.go @@ -14,17 +14,17 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { []rest.Route{ { Method: http.MethodPost, - Path: "/api/shopping-cart/add_to_cart", + Path: "/api/shopping-cart/add", Handler: AddToCartHandler(serverCtx), }, { Method: http.MethodPost, - Path: "/api/shopping-cart/delete_cart", + Path: "/api/shopping-cart/delete", Handler: DeleteCartHandler(serverCtx), }, { Method: http.MethodPost, - Path: "/api/shopping-cart/modify_cart_purchase_quantity", + Path: "/api/shopping-cart/modify", Handler: ModifyCartPurchaseQuantityHandler(serverCtx), }, { diff --git a/server/shopping-cart/internal/logic/getcartslogic.go b/server/shopping-cart/internal/logic/getcartslogic.go index 436831f9..de21354b 100644 --- a/server/shopping-cart/internal/logic/getcartslogic.go +++ b/server/shopping-cart/internal/logic/getcartslogic.go @@ -169,8 +169,14 @@ func (l *GetCartsLogic) GetCarts(req *types.GetCartsReq, userinfo *auth.UserInfo tmpMinBuyNum++ } //根据数量获取阶梯价格中对应的价格 - itemPrice := step_price.GetStepPrice(boxQuantity, stepNum, stepPrice) - totalPrice := itemPrice * float64(*cart.PurchaseQuantity) + itemPrice := step_price.GetCentStepPrice(boxQuantity, stepNum, stepPrice) + //如果有配件,单价也要加入配件价格 + if *cart.FittingId > 0 { + if curFittingInfo, ok := mapModel[*cart.FittingId]; ok { + itemPrice += *curFittingInfo.Price + } + } + totalPrice := itemPrice * (*cart.PurchaseQuantity) item := types.CartItem{ ProductId: *cart.ProductId, SizeInfo: types.SizeInfo{ @@ -185,8 +191,8 @@ func (l *GetCartsLogic) GetCarts(req *types.GetCartsReq, userinfo *auth.UserInfo FittingId: *cart.FittingId, FittingName: snapShot.FittingInfo.FittingName, }, - ItemPrice: fmt.Sprintf("%.3f", itemPrice), - TotalPrice: fmt.Sprintf("%.3f", totalPrice), + ItemPrice: fmt.Sprintf("%.3f", format.CentitoDollar(itemPrice)), + TotalPrice: fmt.Sprintf("%.3f", format.CentitoDollar(totalPrice)), DiyInformation: types.DiyInformation{ Phone: snapShot.UserDiyInformation.Phone, Address: snapShot.UserDiyInformation.Address, diff --git a/server_api/shopping-cart.api b/server_api/shopping-cart.api index 15bb5c98..21ce857e 100644 --- a/server_api/shopping-cart.api +++ b/server_api/shopping-cart.api @@ -11,13 +11,13 @@ import "basic.api" service shopping-cart { //加入购物车 @handler AddToCartHandler - post /api/shopping-cart/add_to_cart(AddToCartReq) returns (response); + post /api/shopping-cart/add(AddToCartReq) returns (response); //删除购物车 @handler DeleteCartHandler - post /api/shopping-cart/delete_cart(DeleteCartReq) returns (response); + post /api/shopping-cart/delete(DeleteCartReq) returns (response); //修改购物车购买数量 @handler ModifyCartPurchaseQuantityHandler - post /api/shopping-cart/modify_cart_purchase_quantity(ModifyCartPurchaseQuantityReq) returns (response); + post /api/shopping-cart/modify(ModifyCartPurchaseQuantityReq) returns (response); //获取购物车列表 @handler GetCartsHandler get /api/shopping-cart/get_carts(GetCartsReq) returns (response); diff --git a/utils/format/price.go b/utils/format/price.go index 8c7ee70a..99063fde 100644 --- a/utils/format/price.go +++ b/utils/format/price.go @@ -5,9 +5,9 @@ import ( "strconv" ) -// 美分转美元 -func CentoDollar(price int64) float64 { - str := fmt.Sprintf("%.2f", float64(price)/float64(100)) +// 厘转美元 +func CentitoDollar(price int64) float64 { + str := fmt.Sprintf("%.3f", float64(price)/float64(1000)) dollar, _ := strconv.ParseFloat(str, 64) return dollar } diff --git a/utils/step_price/price.go b/utils/step_price/price.go index 0cfe5d09..f8eb2b9a 100644 --- a/utils/step_price/price.go +++ b/utils/step_price/price.go @@ -3,20 +3,20 @@ package step_price // 返回美元 func GetStepPrice(minBuyNum int, stepNum []int, stepPrice []int) float64 { if minBuyNum > stepNum[len(stepNum)-1] { - return float64(stepPrice[len(stepPrice)-1]) / float64(100) + return float64(stepPrice[len(stepPrice)-1]) / float64(1000) } for k, v := range stepNum { if minBuyNum <= v { if k <= (len(stepPrice) - 1) { - return float64(stepPrice[k]) / float64(100) + return float64(stepPrice[k]) / float64(1000) } - return float64(stepPrice[len(stepPrice)-1]) / float64(100) + return float64(stepPrice[len(stepPrice)-1]) / float64(1000) } } - return float64(stepPrice[len(stepPrice)-1]) / float64(100) + return float64(stepPrice[len(stepPrice)-1]) / float64(1000) } -// 返回美分 +// 返回厘 func GetCentStepPrice(minBuyNum int, stepNum []int, stepPrice []int) int64 { if minBuyNum > stepNum[len(stepNum)-1] { return int64(stepPrice[len(stepPrice)-1]) From 6987f2c2d19ee3c64304580ea34c535f74a8b21b Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Fri, 15 Sep 2023 15:27:39 +0800 Subject: [PATCH 18/59] fix --- model/gmodel/fs_product_price_logic.go | 5 +++++ server/shopping-cart/internal/logic/getcartslogic.go | 1 + server/shopping-cart/internal/types/types.go | 2 +- server_api/shopping-cart.api | 2 +- 4 files changed, 8 insertions(+), 2 deletions(-) diff --git a/model/gmodel/fs_product_price_logic.go b/model/gmodel/fs_product_price_logic.go index d78f8d5f..65e61a3f 100755 --- a/model/gmodel/fs_product_price_logic.go +++ b/model/gmodel/fs_product_price_logic.go @@ -71,6 +71,11 @@ func (p *FsProductPriceModel) GetPriceListByProductIds(ctx context.Context, prod } return } +func (p *FsProductPriceModel) FindOneBySizeId(ctx context.Context, sizeId int64) (resp *FsProductPrice, err error) { + err = p.db.WithContext(ctx).Model(&FsProductPrice{}). + Where("`size_id` = ? and `status` = ?", sizeId, 1).Take(&resp).Error + return resp, err +} // 产品价格 type ProductPrice struct { diff --git a/server/shopping-cart/internal/logic/getcartslogic.go b/server/shopping-cart/internal/logic/getcartslogic.go index de21354b..5d15c60a 100644 --- a/server/shopping-cart/internal/logic/getcartslogic.go +++ b/server/shopping-cart/internal/logic/getcartslogic.go @@ -38,6 +38,7 @@ func NewGetCartsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetCarts // } func (l *GetCartsLogic) GetCarts(req *types.GetCartsReq, userinfo *auth.UserInfo) (resp *basic.Response) { + userinfo.UserId = 39 if req.CurrentPage <= 0 { req.CurrentPage = constants.DEFAULT_PAGE } diff --git a/server/shopping-cart/internal/types/types.go b/server/shopping-cart/internal/types/types.go index 7ee9b52d..c692ba35 100644 --- a/server/shopping-cart/internal/types/types.go +++ b/server/shopping-cart/internal/types/types.go @@ -48,7 +48,7 @@ type CartItem struct { SizeInfo SizeInfo `json:"size_info"` //尺寸信息 FittingInfo FittingInfo `json:"fitting_info"` //配件信息 ItemPrice string `json:"item_price"` //单价 - TotalPrice string `json:"totalPrice"` //单价X数量=总价 + TotalPrice string `json:"total_price"` //单价X数量=总价 DiyInformation DiyInformation `json:"diy_information"` //diy信息 StepNum []StepNumItem `json:"step_num"` //阶梯数量 IsInvalid bool `json:"is_invalid"` //是否无效 diff --git a/server_api/shopping-cart.api b/server_api/shopping-cart.api index 21ce857e..495e46d1 100644 --- a/server_api/shopping-cart.api +++ b/server_api/shopping-cart.api @@ -64,7 +64,7 @@ type CartItem { SizeInfo SizeInfo `json:"size_info"` //尺寸信息 FittingInfo FittingInfo `json:"fitting_info"` //配件信息 ItemPrice string `json:"item_price"` //单价 - TotalPrice string `json:"totalPrice"` //单价X数量=总价 + TotalPrice string `json:"total_price"` //单价X数量=总价 DiyInformation DiyInformation `json:"diy_information"` //diy信息 StepNum []StepNumItem `json:"step_num"` //阶梯数量 IsInvalid bool `json:"is_invalid"` //是否无效 From 246e03d7927459c7b9075278c5f483029531e7fc Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Fri, 15 Sep 2023 15:28:11 +0800 Subject: [PATCH 19/59] fix --- server/shopping-cart/internal/logic/getcartslogic.go | 1 - 1 file changed, 1 deletion(-) diff --git a/server/shopping-cart/internal/logic/getcartslogic.go b/server/shopping-cart/internal/logic/getcartslogic.go index 5d15c60a..de21354b 100644 --- a/server/shopping-cart/internal/logic/getcartslogic.go +++ b/server/shopping-cart/internal/logic/getcartslogic.go @@ -38,7 +38,6 @@ func NewGetCartsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetCarts // } func (l *GetCartsLogic) GetCarts(req *types.GetCartsReq, userinfo *auth.UserInfo) (resp *basic.Response) { - userinfo.UserId = 39 if req.CurrentPage <= 0 { req.CurrentPage = constants.DEFAULT_PAGE } From 33055bbb4cdb07b869b27d7d38c463c37f026091 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Fri, 15 Sep 2023 15:28:42 +0800 Subject: [PATCH 20/59] fix --- server/shopping-cart/internal/logic/getcartslogic.go | 1 - 1 file changed, 1 deletion(-) diff --git a/server/shopping-cart/internal/logic/getcartslogic.go b/server/shopping-cart/internal/logic/getcartslogic.go index de21354b..8f66c64c 100644 --- a/server/shopping-cart/internal/logic/getcartslogic.go +++ b/server/shopping-cart/internal/logic/getcartslogic.go @@ -45,7 +45,6 @@ func (l *GetCartsLogic) GetCarts(req *types.GetCartsReq, userinfo *auth.UserInfo //获取用户购物车列表 carts, total, err := l.svcCtx.AllModels.FsShoppingCart.GetAllCartsByParam(l.ctx, gmodel.GetAllCartsByParamReq{ UserId: userinfo.UserId, - Fields: "", Sort: "id DESC", Page: req.CurrentPage, Limit: limit, From c94e59c907dce8374a52ca057784b8b521ff84ca Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Fri, 15 Sep 2023 15:54:12 +0800 Subject: [PATCH 21/59] fix --- .../internal/logic/getcartslogic.go | 125 +++++++++++------- 1 file changed, 77 insertions(+), 48 deletions(-) diff --git a/server/shopping-cart/internal/logic/getcartslogic.go b/server/shopping-cart/internal/logic/getcartslogic.go index 8f66c64c..dc9f4499 100644 --- a/server/shopping-cart/internal/logic/getcartslogic.go +++ b/server/shopping-cart/internal/logic/getcartslogic.go @@ -2,6 +2,7 @@ package logic import ( "context" + "errors" "fmt" "fusenapi/constants" "fusenapi/model/gmodel" @@ -38,6 +39,7 @@ func NewGetCartsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetCarts // } func (l *GetCartsLogic) GetCarts(req *types.GetCartsReq, userinfo *auth.UserInfo) (resp *basic.Response) { + userinfo.UserId = 39 if req.CurrentPage <= 0 { req.CurrentPage = constants.DEFAULT_PAGE } @@ -64,44 +66,22 @@ func (l *GetCartsLogic) GetCarts(req *types.GetCartsReq, userinfo *auth.UserInfo CartList: nil, }) } - lenCarts := len(carts) - templateIds := make([]int64, 0, lenCarts) - modelIds := make([]int64, 0, lenCarts) //模型 + 配件 - sizeIds := make([]int64, 0, lenCarts) - for index := range carts { - templateIds = append(templateIds, *carts[index].TemplateId) - modelIds = append(modelIds, *carts[index].ModelId, *carts[index].FittingId) - sizeIds = append(sizeIds, *carts[index].SizeId) - } - //获取尺寸列表 - sizeList, err := l.svcCtx.AllModels.FsProductSize.GetAllByIds(l.ctx, sizeIds, "") + var ( + mapSize = make(map[int64]gmodel.FsProductSize) + mapModel = make(map[int64]gmodel.FsProductModel3d) + mapTemplate = make(map[int64]gmodel.FsProductTemplateV2) + mapSizePrice = make(map[int64]gmodel.FsProductPrice) + ) + //获取相关信息 + err = l.GetRelationInfo(GetRelationInfoReq{ + Carts: carts, + MapSize: mapSize, + MapModel: mapModel, + MapTemplate: mapTemplate, + MapSizePrice: mapSizePrice, + }) if err != nil { - logx.Error(err) - return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get size list") - } - mapSize := make(map[int64]gmodel.FsProductSize) - for _, v := range sizeList { - mapSize[v.Id] = v - } - //获取模型和配件信息 - modelList, err := l.svcCtx.AllModels.FsProductModel3d.GetAllByIds(l.ctx, modelIds, "") - if err != nil { - logx.Error(err) - return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get model list") - } - mapModel := make(map[int64]gmodel.FsProductModel3d) - for _, v := range modelList { - mapModel[v.Id] = v - } - //获取模板列表 - templateList, err := l.svcCtx.AllModels.FsProductTemplateV2.FindAllByIds(l.ctx, templateIds) - if err != nil { - logx.Error(err) - return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get template list") - } - mapTemplate := make(map[int64]gmodel.FsProductTemplateV2) - for _, v := range templateList { - mapTemplate[v.Id] = v + return resp.SetStatusWithMessage(basic.CodeServiceErr, err.Error()) } //定义map收集变更信息 mapCartChange := make(map[int64]string) @@ -119,17 +99,8 @@ func (l *GetCartsLogic) GetCarts(req *types.GetCartsReq, userinfo *auth.UserInfo logx.Error("VerifyShoppingCartSnapshotDataChange err:", err.Error()) return resp.SetStatusWithMessage(basic.CodeServiceErr, "system err:failed to check shopping cart change data") } - //根据sizeid获取价格列表 - priceList, err := l.svcCtx.AllModels.FsProductPrice.GetPriceListBySizeIds(l.ctx, sizeIds) - if err != nil { - logx.Error(err) - return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get cart`s product price list") - } - mapSizePrice := make(map[int64]gmodel.FsProductPrice) - for _, v := range priceList { - mapSizePrice[*v.SizeId] = v - } - list := make([]types.CartItem, 0, lenCarts) + + list := make([]types.CartItem, 0, len(carts)) for _, cart := range carts { snapShot := mapSnapshot[cart.Id] sizePrice, ok := mapSizePrice[*cart.SizeId] @@ -221,6 +192,64 @@ func (l *GetCartsLogic) GetCarts(req *types.GetCartsReq, userinfo *auth.UserInfo }) } +// 获取相关信息 +type GetRelationInfoReq struct { + Carts []gmodel.FsShoppingCart + MapSize map[int64]gmodel.FsProductSize + MapModel map[int64]gmodel.FsProductModel3d + MapTemplate map[int64]gmodel.FsProductTemplateV2 + MapSizePrice map[int64]gmodel.FsProductPrice +} + +func (l *GetCartsLogic) GetRelationInfo(req GetRelationInfoReq) error { + lenCarts := len(req.Carts) + templateIds := make([]int64, 0, lenCarts) + modelIds := make([]int64, 0, lenCarts) //模型 + 配件 + sizeIds := make([]int64, 0, lenCarts) + for index := range req.Carts { + templateIds = append(templateIds, *req.Carts[index].TemplateId) + modelIds = append(modelIds, *req.Carts[index].ModelId, *req.Carts[index].FittingId) + sizeIds = append(sizeIds, *req.Carts[index].SizeId) + } + //获取尺寸列表 + sizeList, err := l.svcCtx.AllModels.FsProductSize.GetAllByIds(l.ctx, sizeIds, "") + if err != nil { + logx.Error(err) + return errors.New("failed to get size list") + } + for _, v := range sizeList { + req.MapSize[v.Id] = v + } + //获取模型和配件信息 + modelList, err := l.svcCtx.AllModels.FsProductModel3d.GetAllByIds(l.ctx, modelIds, "") + if err != nil { + logx.Error(err) + return errors.New("failed to get model list") + } + for _, v := range modelList { + req.MapModel[v.Id] = v + } + //获取模板列表 + templateList, err := l.svcCtx.AllModels.FsProductTemplateV2.FindAllByIds(l.ctx, templateIds) + if err != nil { + logx.Error(err) + return errors.New("failed to get template list") + } + for _, v := range templateList { + req.MapTemplate[v.Id] = v + } + //根据sizeid获取价格列表 + priceList, err := l.svcCtx.AllModels.FsProductPrice.GetPriceListBySizeIds(l.ctx, sizeIds) + if err != nil { + logx.Error(err) + return errors.New("failed to get cart`s product price list") + } + for _, v := range priceList { + req.MapSizePrice[*v.SizeId] = v + } + return nil +} + // 处理逻辑后 w,r 如:重定向, resp 必须重新处理 // func (l *GetCartsLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) { // // httpx.OkJsonCtx(r.Context(), w, resp) From 668db55e6be2a2f00c812f8894d21052cf30835d Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Fri, 15 Sep 2023 15:54:24 +0800 Subject: [PATCH 22/59] fix --- server/shopping-cart/internal/logic/getcartslogic.go | 1 - 1 file changed, 1 deletion(-) diff --git a/server/shopping-cart/internal/logic/getcartslogic.go b/server/shopping-cart/internal/logic/getcartslogic.go index dc9f4499..4b070b5d 100644 --- a/server/shopping-cart/internal/logic/getcartslogic.go +++ b/server/shopping-cart/internal/logic/getcartslogic.go @@ -39,7 +39,6 @@ func NewGetCartsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetCarts // } func (l *GetCartsLogic) GetCarts(req *types.GetCartsReq, userinfo *auth.UserInfo) (resp *basic.Response) { - userinfo.UserId = 39 if req.CurrentPage <= 0 { req.CurrentPage = constants.DEFAULT_PAGE } From da8f88b3e69f2dad42f0d9e445019ed0bc1acc49 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Fri, 15 Sep 2023 16:30:01 +0800 Subject: [PATCH 23/59] fix --- model/gmodel/fs_product_logic.go | 5 ++- model/gmodel/fs_product_price_logic.go | 6 ++-- .../internal/logic/getsizebyproductlogic.go | 12 +++---- .../internal/logic/getcartslogic.go | 33 +++++++++++++------ server/shopping-cart/internal/types/types.go | 8 ++--- server_api/shopping-cart.api | 7 ++-- .../verify_shopping_cart_channged.go | 7 +++- 7 files changed, 46 insertions(+), 32 deletions(-) diff --git a/model/gmodel/fs_product_logic.go b/model/gmodel/fs_product_logic.go index 8e7cca3c..dcd6d497 100755 --- a/model/gmodel/fs_product_logic.go +++ b/model/gmodel/fs_product_logic.go @@ -18,12 +18,15 @@ func (p *FsProductModel) FindOneBySn(ctx context.Context, sn string, fields ...s err = db.Take(&resp).Error return resp, err } -func (p *FsProductModel) GetProductListByIds(ctx context.Context, productIds []int64, sort string) (resp []FsProduct, err error) { +func (p *FsProductModel) GetProductListByIds(ctx context.Context, productIds []int64, sort string, fields ...string) (resp []FsProduct, err error) { if len(productIds) == 0 { return } db := p.db.Model(&FsProduct{}).WithContext(ctx). Where("`id` in (?) and `is_del` =? and `is_shelf` = ? and `status` =?", productIds, 0, 1, 1) + if len(fields) > 0 { + db = db.Select(fields[0]) + } switch sort { case "sort-asc": db = db.Order("`sort` ASC") diff --git a/model/gmodel/fs_product_price_logic.go b/model/gmodel/fs_product_price_logic.go index 65e61a3f..a4bee9cd 100755 --- a/model/gmodel/fs_product_price_logic.go +++ b/model/gmodel/fs_product_price_logic.go @@ -23,11 +23,11 @@ func (p *FsProductPriceModel) GetSimplePriceListByProductIds(ctx context.Context } return } -func (p *FsProductPriceModel) GetPriceListBySizeIds(ctx context.Context, sizeIds []int64) (resp []FsProductPrice, err error) { - if len(sizeIds) == 0 { +func (p *FsProductPriceModel) GetPriceListByProductIdsSizeIds(ctx context.Context, productIds, sizeIds []int64) (resp []FsProductPrice, err error) { + if len(sizeIds) == 0 || len(productIds) == 0 { return } - err = p.db.WithContext(ctx).Model(&FsProductPrice{}).Where("`size_id` in (?) and `status` = ? ", sizeIds, 1).Find(&resp).Error + err = p.db.WithContext(ctx).Model(&FsProductPrice{}).Where("`size_id` in (?) and `product_id` in (?) and `status` = ? ", sizeIds, productIds, 1).Find(&resp).Error if err != nil { return nil, err } diff --git a/server/product/internal/logic/getsizebyproductlogic.go b/server/product/internal/logic/getsizebyproductlogic.go index 5e88ef39..f8e56a96 100644 --- a/server/product/internal/logic/getsizebyproductlogic.go +++ b/server/product/internal/logic/getsizebyproductlogic.go @@ -74,14 +74,14 @@ func (l *GetSizeByProductLogic) GetSizeByProduct(req *types.Request, userinfo *a } //获取价格列表 productPriceModel := gmodel.NewFsProductPriceModel(l.svcCtx.MysqlConn) - productPriceList, err := productPriceModel.GetPriceListBySizeIds(l.ctx, sizeIds) + productPriceList, err := productPriceModel.GetPriceListByProductIdsSizeIds(l.ctx, productIds, sizeIds) if err != nil { logx.Error(err) return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get product proce list") } - mapProductPrice := make(map[int64]gmodel.FsProductPrice) + mapProductPrice := make(map[string]gmodel.FsProductPrice) for _, v := range productPriceList { - mapProductPrice[*v.SizeId] = v + mapProductPrice[fmt.Sprintf("%d_%d", *v.ProductId, *v.SizeId)] = v } //组装返回 list := make([]types.GetSizeByProductRsp, 0, len(tagsList)) @@ -103,7 +103,7 @@ func (l *GetSizeByProductLogic) GetSizeByProduct(req *types.Request, userinfo *a } // 第一层子层 -func (l *GetSizeByProductLogic) GetFirstChildrenList(tag gmodel.FsTags, productList []gmodel.FsProduct, productSizeList []gmodel.FsProductSize, mapProductPrice map[int64]gmodel.FsProductPrice) (childrenList []types.Children, err error) { +func (l *GetSizeByProductLogic) GetFirstChildrenList(tag gmodel.FsTags, productList []gmodel.FsProduct, productSizeList []gmodel.FsProductSize, mapProductPrice map[string]gmodel.FsProductPrice) (childrenList []types.Children, err error) { childrenList = make([]types.Children, 0, len(productList)) for _, product := range productList { if *product.Type != tag.Id { @@ -126,14 +126,14 @@ func (l *GetSizeByProductLogic) GetFirstChildrenList(tag gmodel.FsTags, productL } // 第2层子层 -func (l *GetSizeByProductLogic) GetSecondChildrenList(product gmodel.FsProduct, productSizeList []gmodel.FsProductSize, mapProductPrice map[int64]gmodel.FsProductPrice) (childrenObjList []types.ChildrenObj, err error) { +func (l *GetSizeByProductLogic) GetSecondChildrenList(product gmodel.FsProduct, productSizeList []gmodel.FsProductSize, mapProductPrice map[string]gmodel.FsProductPrice) (childrenObjList []types.ChildrenObj, err error) { childrenObjList = make([]types.ChildrenObj, 0, len(productSizeList)) for _, productSize := range productSizeList { if product.Id != *productSize.ProductId { continue } priceList := make([]types.PriceObj, 0, len(productSizeList)) - price, ok := mapProductPrice[productSize.Id] + price, ok := mapProductPrice[fmt.Sprintf("%d_%d", *productSize.ProductId, productSize.Id)] //无对应尺寸价格 if !ok { priceList = []types.PriceObj{ diff --git a/server/shopping-cart/internal/logic/getcartslogic.go b/server/shopping-cart/internal/logic/getcartslogic.go index 4b070b5d..0a52ba1e 100644 --- a/server/shopping-cart/internal/logic/getcartslogic.go +++ b/server/shopping-cart/internal/logic/getcartslogic.go @@ -69,7 +69,8 @@ func (l *GetCartsLogic) GetCarts(req *types.GetCartsReq, userinfo *auth.UserInfo mapSize = make(map[int64]gmodel.FsProductSize) mapModel = make(map[int64]gmodel.FsProductModel3d) mapTemplate = make(map[int64]gmodel.FsProductTemplateV2) - mapSizePrice = make(map[int64]gmodel.FsProductPrice) + mapSizePrice = make(map[string]gmodel.FsProductPrice) + mapProduct = make(map[int64]struct{}) ) //获取相关信息 err = l.GetRelationInfo(GetRelationInfoReq{ @@ -78,6 +79,7 @@ func (l *GetCartsLogic) GetCarts(req *types.GetCartsReq, userinfo *auth.UserInfo MapModel: mapModel, MapTemplate: mapTemplate, MapSizePrice: mapSizePrice, + MapProduct: mapProduct, }) if err != nil { return resp.SetStatusWithMessage(basic.CodeServiceErr, err.Error()) @@ -93,6 +95,7 @@ func (l *GetCartsLogic) GetCarts(req *types.GetCartsReq, userinfo *auth.UserInfo MapTemplate: mapTemplate, MapCartChange: mapCartChange, MapSnapshot: mapSnapshot, + MapProduct: mapProduct, }) if err != nil { logx.Error("VerifyShoppingCartSnapshotDataChange err:", err.Error()) @@ -102,7 +105,7 @@ func (l *GetCartsLogic) GetCarts(req *types.GetCartsReq, userinfo *auth.UserInfo list := make([]types.CartItem, 0, len(carts)) for _, cart := range carts { snapShot := mapSnapshot[cart.Id] - sizePrice, ok := mapSizePrice[*cart.SizeId] + sizePrice, ok := mapSizePrice[fmt.Sprintf("%d_%d", *cart.ProductId, *cart.SizeId)] if !ok { return resp.SetStatusWithMessage(basic.CodeServiceErr, fmt.Sprintf("the size`s price info is not exists:%d", *cart.SizeId)) } @@ -126,15 +129,12 @@ func (l *GetCartsLogic) GetCarts(req *types.GetCartsReq, userinfo *auth.UserInfo //购买箱数 boxQuantity := int(math.Ceil(float64(*cart.PurchaseQuantity) / float64(*sizePrice.EachBoxNum))) //获取阶梯数量 - stepQuantityList := make([]types.StepNumItem, 0, 10) + stepQuantityList := make([]int64, 0, 20) tmpMinBuyNum := *sizePrice.MinBuyNum for tmpMinBuyNum < (int64(stepNum[lenStepNum-1]) + 5) { //阶梯数 tmpQuantity := tmpMinBuyNum * (*sizePrice.EachBoxNum) - stepQuantityList = append(stepQuantityList, types.StepNumItem{ - PurchaseQuantity: tmpQuantity, - IsSelected: *cart.PurchaseQuantity == tmpQuantity, - }) + stepQuantityList = append(stepQuantityList, tmpQuantity) tmpMinBuyNum++ } //根据数量获取阶梯价格中对应的价格 @@ -169,6 +169,7 @@ func (l *GetCartsLogic) GetCarts(req *types.GetCartsReq, userinfo *auth.UserInfo Qrcode: snapShot.UserDiyInformation.Qrcode, Slogan: snapShot.UserDiyInformation.Slogan, }, + PurchaseQuantity: *cart.PurchaseQuantity, StepNum: stepQuantityList, IsInvalid: false, InvalidDescription: "", @@ -197,7 +198,8 @@ type GetRelationInfoReq struct { MapSize map[int64]gmodel.FsProductSize MapModel map[int64]gmodel.FsProductModel3d MapTemplate map[int64]gmodel.FsProductTemplateV2 - MapSizePrice map[int64]gmodel.FsProductPrice + MapSizePrice map[string]gmodel.FsProductPrice + MapProduct map[int64]struct{} } func (l *GetCartsLogic) GetRelationInfo(req GetRelationInfoReq) error { @@ -205,10 +207,21 @@ func (l *GetCartsLogic) GetRelationInfo(req GetRelationInfoReq) error { templateIds := make([]int64, 0, lenCarts) modelIds := make([]int64, 0, lenCarts) //模型 + 配件 sizeIds := make([]int64, 0, lenCarts) + productIds := make([]int64, 0, lenCarts) for index := range req.Carts { templateIds = append(templateIds, *req.Carts[index].TemplateId) modelIds = append(modelIds, *req.Carts[index].ModelId, *req.Carts[index].FittingId) sizeIds = append(sizeIds, *req.Carts[index].SizeId) + productIds = append(productIds, *req.Carts[index].ProductId) + } + //获取产品集合 + productList, err := l.svcCtx.AllModels.FsProduct.GetProductListByIds(l.ctx, productIds, "", "id") + if err != nil { + logx.Error(err) + return errors.New("failed to get product list") + } + for _, v := range productList { + req.MapProduct[v.Id] = struct{}{} } //获取尺寸列表 sizeList, err := l.svcCtx.AllModels.FsProductSize.GetAllByIds(l.ctx, sizeIds, "") @@ -238,13 +251,13 @@ func (l *GetCartsLogic) GetRelationInfo(req GetRelationInfoReq) error { req.MapTemplate[v.Id] = v } //根据sizeid获取价格列表 - priceList, err := l.svcCtx.AllModels.FsProductPrice.GetPriceListBySizeIds(l.ctx, sizeIds) + priceList, err := l.svcCtx.AllModels.FsProductPrice.GetPriceListByProductIdsSizeIds(l.ctx, productIds, sizeIds) if err != nil { logx.Error(err) return errors.New("failed to get cart`s product price list") } for _, v := range priceList { - req.MapSizePrice[*v.SizeId] = v + req.MapSizePrice[fmt.Sprintf("%d_%d", *v.ProductId, *v.SizeId)] = v } return nil } diff --git a/server/shopping-cart/internal/types/types.go b/server/shopping-cart/internal/types/types.go index c692ba35..db117d2a 100644 --- a/server/shopping-cart/internal/types/types.go +++ b/server/shopping-cart/internal/types/types.go @@ -50,16 +50,12 @@ type CartItem struct { ItemPrice string `json:"item_price"` //单价 TotalPrice string `json:"total_price"` //单价X数量=总价 DiyInformation DiyInformation `json:"diy_information"` //diy信息 - StepNum []StepNumItem `json:"step_num"` //阶梯数量 + StepNum []int64 `json:"step_num"` //阶梯数量 + PurchaseQuantity int64 `json:"purchase_quantity"` //当前购买数量 IsInvalid bool `json:"is_invalid"` //是否无效 InvalidDescription string `json:"invalid_description"` //无效原因 } -type StepNumItem struct { - PurchaseQuantity int64 `json:"purchase_quantity"` //数量 - IsSelected bool `json:"is_selected"` //是否选中 -} - type SizeInfo struct { SizeId int64 `json:"size_id"` //尺寸id Capacity string `json:"capacity"` //尺寸名称 diff --git a/server_api/shopping-cart.api b/server_api/shopping-cart.api index 495e46d1..27249f45 100644 --- a/server_api/shopping-cart.api +++ b/server_api/shopping-cart.api @@ -66,14 +66,11 @@ type CartItem { ItemPrice string `json:"item_price"` //单价 TotalPrice string `json:"total_price"` //单价X数量=总价 DiyInformation DiyInformation `json:"diy_information"` //diy信息 - StepNum []StepNumItem `json:"step_num"` //阶梯数量 + StepNum []int64 `json:"step_num"` //阶梯数量 + PurchaseQuantity int64 `json:"purchase_quantity"` //当前购买数量 IsInvalid bool `json:"is_invalid"` //是否无效 InvalidDescription string `json:"invalid_description"` //无效原因 } -type StepNumItem { - PurchaseQuantity int64 `json:"purchase_quantity"` //数量 - IsSelected bool `json:"is_selected"` //是否选中 -} type SizeInfo { SizeId int64 `json:"size_id"` //尺寸id Capacity string `json:"capacity"` //尺寸名称 diff --git a/utils/shopping_cart/verify_shopping_cart_channged.go b/utils/shopping_cart/verify_shopping_cart_channged.go index d237e5ec..10315ffe 100644 --- a/utils/shopping_cart/verify_shopping_cart_channged.go +++ b/utils/shopping_cart/verify_shopping_cart_channged.go @@ -15,10 +15,16 @@ type VerifyShoppingCartSnapshotDataChangeReq struct { MapTemplate map[int64]gmodel.FsProductTemplateV2 MapCartChange map[int64]string MapSnapshot map[int64]CartSnapshot + MapProduct map[int64]struct{} } func VerifyShoppingCartSnapshotDataChange(req VerifyShoppingCartSnapshotDataChangeReq) error { for _, cartInfo := range req.Carts { + descrptionBuilder := strings.Builder{} + //产品下架/删除 + if _, ok := req.MapProduct[*cartInfo.ProductId]; !ok { + descrptionBuilder.WriteString("the product is off shelf or deleted
") + } var snapShotParseInfo CartSnapshot if err := json.Unmarshal([]byte(*cartInfo.Snapshot), &snapShotParseInfo); err != nil { return err @@ -30,7 +36,6 @@ func VerifyShoppingCartSnapshotDataChange(req VerifyShoppingCartSnapshotDataChan snapshotModelJsonHash := hash.JsonHashKey(snapShotParseInfo.ModelInfo.ModelJson) //快照中配件设计json数据哈希值 snapshotFittingJsonHash := hash.JsonHashKey(snapShotParseInfo.FittingInfo.FittingJson) - descrptionBuilder := strings.Builder{} //有模板验证模板相关 if *cartInfo.TemplateId > 0 { if curTemplateInfo, ok := req.MapTemplate[*cartInfo.TemplateId]; !ok { From ca7cf4c81e2bc7a7881650914bbfae508f203682 Mon Sep 17 00:00:00 2001 From: momo <1012651275@qq.com> Date: Fri, 15 Sep 2023 17:58:45 +0800 Subject: [PATCH 24/59] =?UTF-8?q?fix:=E5=90=88=E5=B9=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- constants/orders.go | 85 +++++++ model/gmodel/fs_cloud_storage_gen.go | 25 +++ model/gmodel/fs_cloud_storage_logic.go | 2 + model/gmodel/fs_order_gen.go | 3 +- model/gmodel/fs_order_logic.go | 297 ++++++++++++------------- model/gmodel/fs_order_logic_1.go | 192 ++++++++++++++++ model/gmodel/fs_shopping_cart_logic.go | 11 +- model/gmodel/var_gen.go | 2 + server_api/order.api | 42 ++++ server_api/orders.api | 217 ------------------ service/repositories/order.go | 151 +++++++++++++ utils/basic/basic.go | 7 + utils/configs/order.go | 92 ++++---- utils/order/order.go | 24 ++ 14 files changed, 732 insertions(+), 418 deletions(-) create mode 100644 constants/orders.go create mode 100644 model/gmodel/fs_cloud_storage_gen.go create mode 100644 model/gmodel/fs_cloud_storage_logic.go mode change 100755 => 100644 model/gmodel/fs_order_logic.go create mode 100755 model/gmodel/fs_order_logic_1.go create mode 100644 server_api/order.api delete mode 100644 server_api/orders.api create mode 100644 service/repositories/order.go diff --git a/constants/orders.go b/constants/orders.go new file mode 100644 index 00000000..7fe2de34 --- /dev/null +++ b/constants/orders.go @@ -0,0 +1,85 @@ +package constants + +// 货币 +type Currency string + +const ( + Usd Currency = "usd" +) + +// 金额单位 +type AmountUnit string + +// 交易方式 +type PayMethods string + +const ( + Card PayMethods = "CARD" + Visa PayMethods = "VISA" +) + +// 支付状态 +type PayStatusCode int64 + +const ( + PayStatusUnpaid PayStatusCode = 10 //10,未支付 + PayStatusPaid PayStatusCode = 20 //20,已支付 + PayStatusRefunded PayStatusCode = 30 //30,已退款 +) + +// 订单状态 +type OrderStatusCode int64 + +const ( + ORDERSTATUSUNPAIDDEPOSIT OrderStatusCode = 0 // 0,未支付定金 + ORDERSTATUSDIRECTMAILORDERED OrderStatusCode = 10100 // 10100,直邮单--已下单 + ORDERSTATUSDIRECTMAILCANCEL OrderStatusCode = 10101 // 10101,直邮单--已取消 + ORDERSTATUSDIRECTMAILSTARTPRODUCTION OrderStatusCode = 10200 // 10200,直邮单--开始生产 + ORDERSTATUSDIRECTMAILCOMPLETEPRODUCTION OrderStatusCode = 10300 // 10300,直邮单--生产完成 + ORDERSTATUSDIRECTMAILSHIPPED OrderStatusCode = 10400 // 10400,直邮单--已发货 + ORDERSTATUSDIRECTMAILARRIVED OrderStatusCode = 10500 // 10500,直邮单--已到达 + ORDERSTATUSCLOUDSTOREORDERED OrderStatusCode = 20100 // 20100,云仓单--已下单 + ORDERSTATUSCLOUDSTORECANCEL OrderStatusCode = 20101 // 20101,云仓单--已取消 + ORDERSTATUSCLOUDSTORESTARTPRODUCTION OrderStatusCode = 20200 // 20200,云仓单--开始生产 + ORDERSTATUSCLOUDSTOREOMPLETEPRODUCTION OrderStatusCode = 20300 // 20300,云仓单--生产完成 + ORDERSTATUSCLOUDSTOREARRIVEDWAREHOUSE OrderStatusCode = 20400 // 20400,云仓单--直达仓库 +) + +// 订单状态名称 +var OrderStatusMessage map[OrderStatusCode]string + +// 支付状态名称 +var PayStatusMessage map[PayStatusCode]string + +// 订单状态--用户可见 +var OrderStatusUser []OrderStatusCode + +func init() { + // 订单状态名称 + PayStatusMessage = make(map[PayStatusCode]string) + PayStatusMessage[PayStatusUnpaid] = "Paid" + PayStatusMessage[PayStatusPaid] = "Unpaid" + PayStatusMessage[PayStatusRefunded] = "Refunded" + + // 订单状态名称 + OrderStatusMessage = make(map[OrderStatusCode]string) + OrderStatusMessage[ORDERSTATUSUNPAIDDEPOSIT] = "未支付定金" + + OrderStatusMessage[ORDERSTATUSDIRECTMAILORDERED] = "直邮单--已下单" + OrderStatusMessage[ORDERSTATUSDIRECTMAILSTARTPRODUCTION] = "直邮单--开始生产" + OrderStatusMessage[ORDERSTATUSDIRECTMAILCOMPLETEPRODUCTION] = "直邮单--生产完成" + OrderStatusMessage[ORDERSTATUSDIRECTMAILSHIPPED] = "直邮单--已发货" + OrderStatusMessage[ORDERSTATUSDIRECTMAILARRIVED] = "直邮单--已到达" + + OrderStatusMessage[ORDERSTATUSCLOUDSTOREORDERED] = "云仓单--已下单" + OrderStatusMessage[ORDERSTATUSCLOUDSTORESTARTPRODUCTION] = "云仓单--开始生产" + OrderStatusMessage[ORDERSTATUSCLOUDSTOREOMPLETEPRODUCTION] = "云仓单--生产完成" + OrderStatusMessage[ORDERSTATUSCLOUDSTOREARRIVEDWAREHOUSE] = "云仓单--直达仓库" + + // 订单状态--用户可见 + OrderStatusUser = []OrderStatusCode{ + ORDERSTATUSUNPAIDDEPOSIT, + ORDERSTATUSDIRECTMAILORDERED, ORDERSTATUSDIRECTMAILSTARTPRODUCTION, ORDERSTATUSDIRECTMAILCOMPLETEPRODUCTION, ORDERSTATUSDIRECTMAILSHIPPED, ORDERSTATUSDIRECTMAILARRIVED, + ORDERSTATUSCLOUDSTOREORDERED, ORDERSTATUSCLOUDSTORESTARTPRODUCTION, ORDERSTATUSCLOUDSTOREOMPLETEPRODUCTION, ORDERSTATUSCLOUDSTOREARRIVEDWAREHOUSE, + } +} diff --git a/model/gmodel/fs_cloud_storage_gen.go b/model/gmodel/fs_cloud_storage_gen.go new file mode 100644 index 00000000..ec90df8d --- /dev/null +++ b/model/gmodel/fs_cloud_storage_gen.go @@ -0,0 +1,25 @@ +package gmodel + +import ( + "gorm.io/gorm" +) + +// fs_cloud_storage 仓库的基本信息, 只做映射 +type FsCloudStorage struct { + CloudStorageId *string `gorm:"unique_key;default:'';" json:"cloud_storage_id"` // 仓库id, 需要固定的命名规则, 能表达国外国内,区域等,简单明了 + Name *string `gorm:"default:'';" json:"name"` // 仓库的名字, 中文使用拼音,国外使用英文 + Address *string `gorm:"default:'';" json:"address"` // 仓库地址 + Contact *[]byte `gorm:"default:'';" json:"contact"` // + Ownership *int64 `gorm:"default:0;" json:"ownership"` // 0为自有, 1为第三方, 后期可以自由定制 + Scope *[]byte `gorm:"default:'';" json:"scope"` // + Capacity *[]byte `gorm:"default:'';" json:"capacity"` // + Metadata *[]byte `gorm:"default:'';" json:"metadata"` // +} +type FsCloudStorageModel struct { + db *gorm.DB + name string +} + +func NewFsCloudStorageModel(db *gorm.DB) *FsCloudStorageModel { + return &FsCloudStorageModel{db: db, name: "fs_cloud_storage"} +} diff --git a/model/gmodel/fs_cloud_storage_logic.go b/model/gmodel/fs_cloud_storage_logic.go new file mode 100644 index 00000000..e68225aa --- /dev/null +++ b/model/gmodel/fs_cloud_storage_logic.go @@ -0,0 +1,2 @@ +package gmodel +// TODO: 使用model的属性做你想做的 \ No newline at end of file diff --git a/model/gmodel/fs_order_gen.go b/model/gmodel/fs_order_gen.go index 66bdd701..a8448ebf 100644 --- a/model/gmodel/fs_order_gen.go +++ b/model/gmodel/fs_order_gen.go @@ -10,12 +10,13 @@ type FsOrder struct { Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // 订单ID UserId *int64 `gorm:"index;default:0;" json:"user_id"` // 用户ID DeliveryMethod *int64 `gorm:"index;default:0;" json:"delivery_method"` // 物流类型 - OrderNo *string `gorm:"index;default:'';" json:"order_no"` // + OrderSn *string `gorm:"index;default:'';" json:"order_sn"` // OrderSource *string `gorm:"default:'';" json:"order_source"` // Status *int64 `gorm:"index;default:0;" json:"status"` // 订单状态 Metadata *[]byte `gorm:"default:'';" json:"metadata"` // Ctime *time.Time `gorm:"default:'0000-00-00 00:00:00';" json:"ctime"` // Utime *time.Time `gorm:"default:'0000-00-00 00:00:00';" json:"utime"` // + IsDel *int64 `gorm:"default:0;" json:"is_del"` // 是否删除:0=否,1=是 } type FsOrderModel struct { db *gorm.DB diff --git a/model/gmodel/fs_order_logic.go b/model/gmodel/fs_order_logic.go old mode 100755 new mode 100644 index 74f28208..78f82f1d --- a/model/gmodel/fs_order_logic.go +++ b/model/gmodel/fs_order_logic.go @@ -1,192 +1,189 @@ package gmodel import ( - "context" "fusenapi/constants" - "reflect" "time" - - "fusenapi/utils/handlers" - - "gorm.io/gorm" ) -func (o *FsOrderModel) FindOneBySn(ctx context.Context, userId int64, sn string) (resp *FsOrder, err error) { - err = o.db.WithContext(ctx).Model(&FsOrder{}).Where(" `user_id` = ? and `sn` = ? ", userId, sn).Take(&resp).Error - return resp, err +// TODO: 使用model的属性做你想做的 + +type NewFsOrder struct { + Id int64 `gorm:"primary_key;default:0;auto_increment;" json:"id"` // 订单ID + UserId *int64 `gorm:"index;default:0;" json:"user_id"` // 用户ID + DeliveryMethod *int64 `gorm:"index;default:0;" json:"delivery_method"` // 物流类型 + OrderSn *string `gorm:"index;default:'';" json:"order_sn"` // + OrderSource *string `gorm:"default:'';" json:"order_source"` // + Status *int64 `gorm:"index;default:0;" json:"status"` // 订单状态 + Metadata *OrderDetail `gorm:"metadata,type:json" json:"metadata"` // + Ctime *time.Time `gorm:"default:'0000-00-00 00:00:00';" json:"ctime"` // + Utime *time.Time `gorm:"default:'0000-00-00 00:00:00';" json:"utime"` // + IsDel *int64 `gorm:"default:0;" json:"is_del"` // 是否删除:0=否,1=是 } -func (o *FsOrderModel) FindOne(ctx context.Context, userId int64, OrderId int64) (order *FsOrder, err error) { - err = o.db.WithContext(ctx).Model(&FsOrder{}).Where("`user_id` = ? and `id` = ?", userId, OrderId).Take(&order).Error - if err != nil { - return nil, err - } - return +// 订单详情 +type OrderDetail struct { + DeliveryAddress *OrderAddress `json:"delivery_address"` // 收货地址 + OrderAmount OrderAmount `json:"order_amount"` // 订单金额 + OrderInfo OrderInfo `json:"order_info"` // 订单信息 + OrderProduct []OrderProduct `json:"order_product"` // 订单商品 } -func (o *FsOrderModel) Update(ctx context.Context, data *FsOrder) error { - return o.db.WithContext(ctx).Model(&FsOrder{}).Where("`id` = ?", data.Id).Updates(&data).Error +// 收货地址 +type OrderAddress struct { + Address string `json:"address"` // 详细地址 + Mobile string `json:"mobile"` // 手机 + Name string `json:"name"` // 姓名 } -func (o *FsOrderModel) RBUpdate(ctx context.Context, data *FsOrder) error { - return o.db.WithContext(ctx).Where("`id` = ?", data.Id).Updates(&data).Error +// 订单金额 +type OrderAmount struct { + Deposit PayInfo `json:"deposit"` // 定金 + RemainingBalance PayInfo `json:"remaining_balance"` // 尾款 + Discount AmountInfo `json:"discount"` // 折扣 + ShippingFee AmountInfo `json:"shipping_fee"` // 邮费 + Tax AmountInfo `json:"tax"` // 税费 + Subtotal AmountInfo `json:"subtotal"` // 商品总金额 + Total AmountInfo `json:"total"` // 订单总金额 } -func (o *FsOrderModel) Create(ctx context.Context, data *FsOrder) error { - return o.db.WithContext(ctx).Model(&FsOrder{}).Create(&data).Error +// 支付明细 +type PayInfo struct { + Metadata map[string]interface{} `json:"metadata"` // 额外参数 + PayAmount AmountInfo `json:"pay_amount"` // 金额明细 + PayMethod string `json:"pay_method"` // 交易方式 + PayTime string `json:"pay_time"` // 支付时间 + Status PayStatus `json:"status"` // 当前状态 + StatusLink []PayStatus `json:"status_link"` // 状态链路 + TradeNo string `json:"trade_no"` // 支付交易号 } -func (o *FsOrderModel) FindOneAndCreateServiceContact(ctx context.Context, userId int64, OrderId int64, cs *FsContactService) (order *FsOrder, err error) { - err = o.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { - err = tx.Model(&FsOrder{}).Select("id").Limit(1).Where("`user_id` = ? and `id` = ?", userId, OrderId).Take(&order).Error - if err != nil { - return err - } - ctime := time.Now().UTC().Unix() - cs.Ctime = &ctime - if constants.ConcactService(*cs.Type) == constants.TYPE_DEFAULT { - *cs.RelationId = 0 - } - - return tx.Model(&FsContactService{}).Create(cs).Error - }) - return order, err +// 金额明细 +type AmountInfo struct { + ExchangeRate string `json:"exchange_rate"` // 换算汇率 + Change constants.AmountUnit `json:"change,omitempty"` // 变动金额 + ChangeRemark string `json:"change_remark,omitempty"` // 变动备注状态编码 + Currency string `json:"currency"` // 货币 + Current constants.AmountUnit `json:"current"` // 当前金额 + Initiate constants.AmountUnit `json:"initiate"` // 初始金额 + Metadata map[string]interface{} `json:"metadata"` // 额外明细 } -// 获取用户最近下单成功的订单 -func (o *FsOrderModel) FindLastSuccessOneOrder(ctx context.Context, userId int64, statusGt int64) (order *FsOrder, err error) { - err = o.db.WithContext(ctx).Model(&FsOrder{}).Where("`user_id` = ? and `status` > ?", userId, statusGt).Order("id DESC").Take(&order).Error - return order, err +// 金额货币 +type AmountCurrency struct { + CurrentAmount constants.AmountUnit `json:"current_amount"` // 当前金额 + CurrentCurrency string `json:"current_currency"` // 当前货币 + ExchangeRate string `json:"exchange_rate"` // 换算汇率 + OriginalAmount constants.AmountUnit `json:"original_amount"` // 原始金额 + OriginalCurrency string `json:"original_currency"` // 原始货币 } -// 分页查询的订单 -func (o *FsOrderModel) FindPageListByPage(ctx context.Context, rowBuilder *gorm.DB, page *int64, pageSize *int64, filterMap map[string]string, orderBy string) ([]*FsOrderRel, error) { - var resp []*FsOrderRel - // 过滤 - if filterMap != nil { - rowBuilder = rowBuilder.Scopes(handlers.FilterData(filterMap)) - } - - // 排序 - if orderBy != "" { - var fieldsMap = make(map[string]struct{}) - s := reflect.TypeOf(&FsOrder{}).Elem() //通过反射获取type定义 - for i := 0; i < s.NumField(); i++ { - fieldsMap[s.Field(i).Tag.Get("json")] = struct{}{} - } - rowBuilder = rowBuilder.Scopes(handlers.OrderCheck(orderBy, fieldsMap)) - } - - // 分页 - rowBuilder = rowBuilder.Scopes(handlers.Paginate(page, pageSize)) - - // 结果 - result := rowBuilder.Debug().WithContext(ctx).Find(&resp) - if result.Error != nil { - return nil, result.Error - } else { - return resp, nil - } +// 支付状态 +type PayStatus struct { + Metadata map[string]interface{} `json:"metadata"` // 额外参数 + StatusCode int64 `json:"status_code"` // 状态编码 + StatusTitle string `json:"status_title"` // 状态名称 } -type FsOrderRel struct { - FsOrder - FsOrderDetails []FsOrderDetails `gorm:"foreignKey:order_id;references:id"` - FsOrderAffiliateInfo FsOrderAffiliate `gorm:"foreignKey:order_id;references:id"` +// 订单信息 +type OrderInfo struct { + Ctime string `json:"ctime"` // 创建日期 + DeliveryMethod int64 `json:"delivery_method"` // 物流类型 + Metadata map[string]interface{} `json:"metadata"` // 额外参数 + OrderSn string `json:"order_sn"` // 订单编号 + Status OrderStatus `json:"status"` // 当前状态 + StatusLink []OrderStatus `json:"status_link"` // 状态链路 + Utime string `json:"utime"` // 更新时间 } -type FsOrderDetails struct { - FsOrderDetail - FsOrderDetailTemplateInfo FsOrderDetailTemplateInfo `gorm:"foreignKey:id;references:order_detail_template_id"` - FsProductInfo FsProduct `gorm:"foreignKey:id;references:product_id"` +// 订单状态--用户 +type OrderStatus struct { + Children []*OrderStatus `json:"children"` // 子状态,管理人员的处理状态, 用户不可见 + Ctime string `json:"ctime"` // 创建时间 + ExpectedTime string `json:"expected_time"` // 预计时间 + Metadata map[string]interface{} `json:"metadata"` // 额外参数 + StatusCode constants.OrderStatusCode `json:"status_code"` // 状态编码 + StatusTitle string `json:"status_title"` // 状态名称 + Utime string `json:"utime"` // 更新时间 } -type FsOrderDetailTemplateInfo struct { - FsOrderDetailTemplate - FsProductDesignInfo FsProductDesignInfo `gorm:"foreignKey:id;references:design_id"` //获取设计数据 - FsProductSizeInfo FsProductSize `gorm:"foreignKey:id;references:size_id"` +// 订单商品 +type OrderProduct struct { + Amount AmountCurrency `json:"amount"` // 商品总价 + ExpectedDeliveryTime string `json:"expected_delivery_time"` // 预计到货时间 + Number int64 `json:"number"` // 商品数量 + ProductID string `json:"product_id"` // 商品ID + ProductLogo string `json:"product_logo"` // 商品logo + ProductLogoResource *Resource `json:"product_logo_resource"` // 商品封面--资源详情 + ProductName string `json:"product_name"` // 商品名称 + ProductPrice AmountCurrency `json:"product_price"` // 商品单价 + ProductSnapshot map[string]interface{} `json:"product_snapshot"` // 商品快照 + ShoppingCartSnapshot *ShoppingCartSnapshot `json:"shopping_cart_snapshot"` // 购物车快照 + Unit string `json:"unit"` // 商品单位 } -type FsProductDesignInfo struct { - FsProductDesign - OptionData FsProduct `gorm:"foreignKey:id;references:optional_id"` //获取配件信息 - TemplateData FsProductTemplateV2 `gorm:"foreignKey:id;references:template_id"` //获取模板信息 +// 资源详情 +type Resource struct { + Metadata map[string]interface{} `json:"metadata"` // 资源额外 + ResourceID string `json:"resource_id"` // 资源ID + ResourceType string `json:"resource_type"` // 资源类型 + ResourceURL string `json:"resource_url"` // 资源地址 } -func (m *FsOrderModel) RowSelectBuilder(selectData []string) *gorm.DB { - var rowBuilder = m.db.Table(m.name) - - if selectData != nil { - rowBuilder = rowBuilder.Select(selectData) - } else { - rowBuilder = rowBuilder.Select("*") - } - return rowBuilder +// 购物车 +type ShoppingCartSnapshot struct { + Ctime string `json:"ctime"` // 创建时间 + FittingID int64 `json:"fitting_id"` // 配件id + ID int64 `json:"id"` // 购物车ID + IsHighlyCustomized int64 `json:"is_highly_customized"` // 是否高度定制 0非 1是(针对客人高度定制只能后台增加如购物车) + ModelID int64 `json:"model_id"` // 模型id + ProductID int64 `json:"product_id"` // 产品id + PurchaseQuantity int64 `json:"purchase_quantity"` // 购买数量 + SizeID int64 `json:"size_id"` // 尺寸id + Snapshot Snapshot `json:"snapshot"` // 购物车快照数据 + TemplateID int64 `json:"template_id"` // 模板id + UserID int64 `json:"user_id"` // 用户id + Utime string `json:"utime"` // 更新时间 } -func (m *FsOrderModel) BuilderTrans(selectData []string) *gorm.DB { - var rowBuilder = m.db - - if selectData != nil { - rowBuilder = rowBuilder.Select(selectData) - } else { - rowBuilder = rowBuilder.Select("*") - } - return rowBuilder +// 购物车快照 +type Snapshot struct { + CombineImage string `json:"combine_image"` // 刀版图地址 + FittingInfo FittingInfo `json:"fitting_info"` + Logo string `json:"logo"` // logo地址 + ModelInfo ModelInfo `json:"model_info"` + RenderImage string `json:"render_image"` // 模板数据 + SizeInfo SizeInfo `json:"size_info"` + TemplateInfo TemplateInfo `json:"template_info"` + UserDiyInformation UserDiyInformation `json:"user_diy_information"` } -func (m *FsOrderModel) FindCount(ctx context.Context, countBuilder *gorm.DB, filterMap map[string]string) (int64, error) { - var count int64 - - // 过滤 - if filterMap != nil { - countBuilder = countBuilder.Scopes(handlers.FilterData(filterMap)) - } - - result := countBuilder.WithContext(ctx).Limit(1).Count(&count) - if result.Error != nil { - return 0, result.Error - } else { - return count, nil - } +// 配件信息 +type FittingInfo struct { + FittingJSON string `json:"fitting_json"` } -func (m *FsOrderModel) FindOneByQuery(ctx context.Context, rowBuilder *gorm.DB, filterMap map[string]string) (*FsOrderRel, error) { - var resp FsOrderRel - - if filterMap != nil { - rowBuilder = rowBuilder.Scopes(handlers.FilterData(filterMap)) - } - - result := rowBuilder.WithContext(ctx).Limit(1).Find(&resp) - if result.Error != nil { - return nil, result.Error - } else { - return &resp, nil - } +// 模型数据 +type ModelInfo struct { + ModelJSON string `json:"model_json"` } -// 事务 -func (m *FsOrderModel) Trans(ctx context.Context, fn func(ctx context.Context, connGorm *gorm.DB) error) error { - tx := m.db.Table(m.name).WithContext(ctx).Begin() - defer func() { - if r := recover(); r != nil { - tx.Rollback() - } - }() - - if err := tx.Error; err != nil { - return err - } - - if err := fn(ctx, tx); err != nil { - tx.Rollback() - return err - } - - return tx.Commit().Error +// 尺寸信息 +type SizeInfo struct { + CM string `json:"cm"` + Inch string `json:"inch"` } -func (m *FsOrderModel) TableName() string { - return m.name +// 模板数据 +type TemplateInfo struct { + TemplateJSON string `json:"template_json"` + TemplateTag string `json:"template_tag"` +} + +// DIY数据 +type UserDiyInformation struct { + Address string `json:"address"` // 地址 + Phone string `json:"phone"` // 电话 + Qrcode string `json:"qrcode"` // 二维码 + Slogan string `json:"slogan"` // slogan + Website string `json:"website"` // 网站 } diff --git a/model/gmodel/fs_order_logic_1.go b/model/gmodel/fs_order_logic_1.go new file mode 100755 index 00000000..74f28208 --- /dev/null +++ b/model/gmodel/fs_order_logic_1.go @@ -0,0 +1,192 @@ +package gmodel + +import ( + "context" + "fusenapi/constants" + "reflect" + "time" + + "fusenapi/utils/handlers" + + "gorm.io/gorm" +) + +func (o *FsOrderModel) FindOneBySn(ctx context.Context, userId int64, sn string) (resp *FsOrder, err error) { + err = o.db.WithContext(ctx).Model(&FsOrder{}).Where(" `user_id` = ? and `sn` = ? ", userId, sn).Take(&resp).Error + return resp, err +} + +func (o *FsOrderModel) FindOne(ctx context.Context, userId int64, OrderId int64) (order *FsOrder, err error) { + err = o.db.WithContext(ctx).Model(&FsOrder{}).Where("`user_id` = ? and `id` = ?", userId, OrderId).Take(&order).Error + if err != nil { + return nil, err + } + return +} + +func (o *FsOrderModel) Update(ctx context.Context, data *FsOrder) error { + return o.db.WithContext(ctx).Model(&FsOrder{}).Where("`id` = ?", data.Id).Updates(&data).Error +} + +func (o *FsOrderModel) RBUpdate(ctx context.Context, data *FsOrder) error { + return o.db.WithContext(ctx).Where("`id` = ?", data.Id).Updates(&data).Error +} + +func (o *FsOrderModel) Create(ctx context.Context, data *FsOrder) error { + return o.db.WithContext(ctx).Model(&FsOrder{}).Create(&data).Error +} + +func (o *FsOrderModel) FindOneAndCreateServiceContact(ctx context.Context, userId int64, OrderId int64, cs *FsContactService) (order *FsOrder, err error) { + err = o.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { + err = tx.Model(&FsOrder{}).Select("id").Limit(1).Where("`user_id` = ? and `id` = ?", userId, OrderId).Take(&order).Error + if err != nil { + return err + } + ctime := time.Now().UTC().Unix() + cs.Ctime = &ctime + if constants.ConcactService(*cs.Type) == constants.TYPE_DEFAULT { + *cs.RelationId = 0 + } + + return tx.Model(&FsContactService{}).Create(cs).Error + }) + return order, err +} + +// 获取用户最近下单成功的订单 +func (o *FsOrderModel) FindLastSuccessOneOrder(ctx context.Context, userId int64, statusGt int64) (order *FsOrder, err error) { + err = o.db.WithContext(ctx).Model(&FsOrder{}).Where("`user_id` = ? and `status` > ?", userId, statusGt).Order("id DESC").Take(&order).Error + return order, err +} + +// 分页查询的订单 +func (o *FsOrderModel) FindPageListByPage(ctx context.Context, rowBuilder *gorm.DB, page *int64, pageSize *int64, filterMap map[string]string, orderBy string) ([]*FsOrderRel, error) { + var resp []*FsOrderRel + // 过滤 + if filterMap != nil { + rowBuilder = rowBuilder.Scopes(handlers.FilterData(filterMap)) + } + + // 排序 + if orderBy != "" { + var fieldsMap = make(map[string]struct{}) + s := reflect.TypeOf(&FsOrder{}).Elem() //通过反射获取type定义 + for i := 0; i < s.NumField(); i++ { + fieldsMap[s.Field(i).Tag.Get("json")] = struct{}{} + } + rowBuilder = rowBuilder.Scopes(handlers.OrderCheck(orderBy, fieldsMap)) + } + + // 分页 + rowBuilder = rowBuilder.Scopes(handlers.Paginate(page, pageSize)) + + // 结果 + result := rowBuilder.Debug().WithContext(ctx).Find(&resp) + if result.Error != nil { + return nil, result.Error + } else { + return resp, nil + } +} + +type FsOrderRel struct { + FsOrder + FsOrderDetails []FsOrderDetails `gorm:"foreignKey:order_id;references:id"` + FsOrderAffiliateInfo FsOrderAffiliate `gorm:"foreignKey:order_id;references:id"` +} + +type FsOrderDetails struct { + FsOrderDetail + FsOrderDetailTemplateInfo FsOrderDetailTemplateInfo `gorm:"foreignKey:id;references:order_detail_template_id"` + FsProductInfo FsProduct `gorm:"foreignKey:id;references:product_id"` +} + +type FsOrderDetailTemplateInfo struct { + FsOrderDetailTemplate + FsProductDesignInfo FsProductDesignInfo `gorm:"foreignKey:id;references:design_id"` //获取设计数据 + FsProductSizeInfo FsProductSize `gorm:"foreignKey:id;references:size_id"` +} + +type FsProductDesignInfo struct { + FsProductDesign + OptionData FsProduct `gorm:"foreignKey:id;references:optional_id"` //获取配件信息 + TemplateData FsProductTemplateV2 `gorm:"foreignKey:id;references:template_id"` //获取模板信息 +} + +func (m *FsOrderModel) RowSelectBuilder(selectData []string) *gorm.DB { + var rowBuilder = m.db.Table(m.name) + + if selectData != nil { + rowBuilder = rowBuilder.Select(selectData) + } else { + rowBuilder = rowBuilder.Select("*") + } + return rowBuilder +} + +func (m *FsOrderModel) BuilderTrans(selectData []string) *gorm.DB { + var rowBuilder = m.db + + if selectData != nil { + rowBuilder = rowBuilder.Select(selectData) + } else { + rowBuilder = rowBuilder.Select("*") + } + return rowBuilder +} + +func (m *FsOrderModel) FindCount(ctx context.Context, countBuilder *gorm.DB, filterMap map[string]string) (int64, error) { + var count int64 + + // 过滤 + if filterMap != nil { + countBuilder = countBuilder.Scopes(handlers.FilterData(filterMap)) + } + + result := countBuilder.WithContext(ctx).Limit(1).Count(&count) + if result.Error != nil { + return 0, result.Error + } else { + return count, nil + } +} + +func (m *FsOrderModel) FindOneByQuery(ctx context.Context, rowBuilder *gorm.DB, filterMap map[string]string) (*FsOrderRel, error) { + var resp FsOrderRel + + if filterMap != nil { + rowBuilder = rowBuilder.Scopes(handlers.FilterData(filterMap)) + } + + result := rowBuilder.WithContext(ctx).Limit(1).Find(&resp) + if result.Error != nil { + return nil, result.Error + } else { + return &resp, nil + } +} + +// 事务 +func (m *FsOrderModel) Trans(ctx context.Context, fn func(ctx context.Context, connGorm *gorm.DB) error) error { + tx := m.db.Table(m.name).WithContext(ctx).Begin() + defer func() { + if r := recover(); r != nil { + tx.Rollback() + } + }() + + if err := tx.Error; err != nil { + return err + } + + if err := fn(ctx, tx); err != nil { + tx.Rollback() + return err + } + + return tx.Commit().Error +} + +func (m *FsOrderModel) TableName() string { + return m.name +} diff --git a/model/gmodel/fs_shopping_cart_logic.go b/model/gmodel/fs_shopping_cart_logic.go index 1f508ac9..f8356781 100644 --- a/model/gmodel/fs_shopping_cart_logic.go +++ b/model/gmodel/fs_shopping_cart_logic.go @@ -1,6 +1,15 @@ package gmodel -import "context" +import ( + "context" +) + +type RelaFsShoppingCart struct { + FsShoppingCart + ShoppingCartProduct *FsProduct `json:"shopping_cart_product" gorm:"foreignkey:product_id;references:id"` + ShoppingCartProductPriceList []*FsProductPrice `json:"shopping_cart_product_price_list" gorm:"foreignkey:product_id;references:product_id"` + ShoppingCartProductModel3dList []*FsProductModel3d `json:"shopping_cart_product_model3d_list" gorm:"foreignkey:product_id;references:product_id"` +} // 获取单个 func (s *FsShoppingCartModel) FindOne(ctx context.Context, id int64, fields ...string) (resp *FsShoppingCart, err error) { diff --git a/model/gmodel/var_gen.go b/model/gmodel/var_gen.go index 88beb3b4..df0d9ec3 100644 --- a/model/gmodel/var_gen.go +++ b/model/gmodel/var_gen.go @@ -30,6 +30,7 @@ type AllModelsGen struct { FsCloudReceiveEveryOld *FsCloudReceiveEveryOldModel // fs_cloud_receive_every_old FsCloudReceiveOld *FsCloudReceiveOldModel // fs_cloud_receive_old 云仓接收工厂总单 FsCloudRenderLogOld *FsCloudRenderLogOldModel // fs_cloud_render_log_old 云渲染日志表 + FsCloudStorage *FsCloudStorageModel // fs_cloud_storage 仓库的基本信息, 只做映射 FsCloudUserApplyBackOld *FsCloudUserApplyBackOldModel // fs_cloud_user_apply_back_old 该表废弃 FsContact *FsContactModel // fs_contact 该表暂未使用 FsContactService *FsContactServiceModel // fs_contact_service @@ -139,6 +140,7 @@ func NewAllModels(gdb *gorm.DB) *AllModelsGen { FsCloudReceiveEveryOld: NewFsCloudReceiveEveryOldModel(gdb), FsCloudReceiveOld: NewFsCloudReceiveOldModel(gdb), FsCloudRenderLogOld: NewFsCloudRenderLogOldModel(gdb), + FsCloudStorage: NewFsCloudStorageModel(gdb), FsCloudUserApplyBackOld: NewFsCloudUserApplyBackOldModel(gdb), FsContact: NewFsContactModel(gdb), FsContactService: NewFsContactServiceModel(gdb), diff --git a/server_api/order.api b/server_api/order.api new file mode 100644 index 00000000..3f755097 --- /dev/null +++ b/server_api/order.api @@ -0,0 +1,42 @@ +syntax = "v1" + +info ( + title: "订单模块" + desc: "订单相关" + author: "" + email: "" +) + +import "basic.api" + +service order { + + @handler CreateOrderHandler + post /api/order/create(CreateOrderReq) returns (response); + + @handler CreatePrePaymentHandler + post /api/order/create-prepayment(CreatePrePaymentReq) returns (response); + + @handler OrderListHandler + post /api/order/list(OrderListReq) returns (response); + +} + +type CreateOrderReq struct { + CartIds []int64 `json:"cart_ids"` + DeliveryMethod string `json:"delivery_method,options=[1,2]"` +} + +type CreatePrePaymentReq struct { + OrderSn string `json:"order_sn"` + DeliveryMethod int `json:"delivery_method"` + DeliveryAddres struct { + Address string `json:"address,optional"` + Name string `json:"name,optional"` + Mobile string `json:"mobile,optional"` + } `json:"delivery_addres,optional"` +} + +type OrderListReq struct { + +} \ No newline at end of file diff --git a/server_api/orders.api b/server_api/orders.api deleted file mode 100644 index cc0b11b1..00000000 --- a/server_api/orders.api +++ /dev/null @@ -1,217 +0,0 @@ -syntax = "v1" - -info ( - title: "订单模块" - desc: "订单相关" - author: "" - email: "" -) - -import "basic.api" - -service orders { - - @handler CreateOrderHandler - post /api/orders/create(CreateOrderReq) returns (response); - - @handler CreatePrePaymentHandler - post /api/orders/create-prepayment(OrderRefundReq) returns (response); - - @handler OrderListHandler - post /api/orders/list(OrderListReq) returns (response); - -} - -type CreateOrderReq struct { - CartIds []int64 `json:"cart_ids"` - DeliveryMethod string `json:"delivery_method"` -} - -type OrderRefundReq struct { - OrderNo string `json:"order_no"` - DeliveryMethod int64 `json:"delivery_method"` - DeliveryAddres DeliveryAddres `json:"delivery_addres"` -} -type DeliveryAddres struct { - Address string `json:"address"` - Name string `json:"name"` - Mobile string `json:"mobile"` -} - -type OrderDetail struct { - OrderProduct []OrderProduct `json:"order_product"` - OrderInfo OrderInfo `json:"order_info"` - OrderAmount OrderAmount `json:"order_amount"` - DeliveryAddres DeliveryAddres `json:"delivery_addres"` -} - -type ProductLogoResource struct { - ResourceID string `json:"resource_id"` - ResourceType string `json:"resource_type"` - ResourceURL string `json:"resource_url"` - Metadata map[string]interface{} `json:"metadata"` -} - -type TemplateInfo struct { - TemplateJSON string `json:"template_json"` - TemplateTag string `json:"template_tag"` -} -type ModelInfo struct { - ModelJSON string `json:"model_json"` -} -type FittingInfo struct { - FittingJSON string `json:"fitting_json"` -} -type SizeInfo struct { - Inch string `json:"inch"` - Cm string `json:"cm"` -} -type UserDiyInformation struct { - Phone string `json:"phone"` - Address string `json:"address"` - Website string `json:"website"` - Qrcode string `json:"qrcode"` - Slogan string `json:"slogan"` -} -type Snapshot struct { - Logo string `json:"logo"` - CombineImage string `json:"combine_image"` - RenderImage string `json:"render_image"` - TemplateInfo TemplateInfo `json:"template_info"` - ModelInfo ModelInfo `json:"model_info"` - FittingInfo FittingInfo `json:"fitting_info"` - SizeInfo SizeInfo `json:"size_info"` - UserDiyInformation UserDiyInformation `json:"user_diy_information"` -} -type ShoppingCartSnapshot struct { - ID int64 `json:"id"` - UserID int64 `json:"user_id"` - ProductID int64 `json:"product_id"` - TemplateID int64 `json:"template_id"` - ModelID int64 `json:"model_id"` - SizeID int64 `json:"size_id"` - FittingID int64 `json:"fitting_id"` - PurchaseQuantity int64 `json:"purchase_quantity"` - Snapshot Snapshot `json:"snapshot"` - IsHighlyCustomized int64 `json:"is_highly_customized"` - Ctime string `json:"ctime"` - Utime string `json:"utime"` -} -type OrderProduct struct { - ProductID string `json:"product_id"` - ProductName string `json:"product_name"` - ProductPrice string `json:"product_price"` - ProductLogo string `json:"product_logo"` - ProductLogoResource ProductLogoResource `json:"product_logo_resource"` - ProductSnapshot map[string]interface{} `json:"product_snapshot"` - Number int64 `json:"number"` - Amount string `json:"amount"` - Unit string `json:"unit"` - ExpectedDeliveryTime string `json:"expected_delivery_time"` - ShoppingCartSnapshot ShoppingCartSnapshot `json:"shopping_cart_snapshot"` -} - -type OrderStatus struct { - StatusCode int64 `json:"status_code"` - StatusTitle string `json:"status_title"` - ExpectedTime string `json:"expected_time"` - Ctime string `json:"ctime"` - Utime string `json:"utime"` - Metadata map[string]interface{} `json:"metadata"` - Children []*OrderStatus `json:"children"` -} -type OrderInfo struct { - OrderNo string `json:"order_no"` - DeliveryMethod int64 `json:"delivery_method"` - Ctime string `json:"ctime"` - Utime string `json:"utime"` - Status OrderStatus `json:"status"` - StatusLink []OrderStatus `json:"status_link"` - Metadata map[string]interface{} `json:"metadata"` -} -type Subtotal struct { - Currency string `json:"currency"` - Current string `json:"current"` - Initiate string `json:"initiate"` - Change string `json:"change"` - ChangeRemark string `json:"change_remark"` - Metadata map[string]interface{} `json:"metadata"` -} -type ShippingFee struct { - Currency string `json:"currency"` - Current string `json:"current"` - Initiate string `json:"initiate"` - Change string `json:"change"` - ChangeRemark string `json:"change_remark"` - Metadata map[string]interface{} `json:"metadata"` -} -type Tax struct { - Currency string `json:"currency"` - Current string `json:"current"` - Initiate string `json:"initiate"` - Change string `json:"change"` - ChangeRemark string `json:"change_remark"` - Metadata map[string]interface{} `json:"metadata"` -} -type Discount struct { - Currency string `json:"currency"` - Current string `json:"current"` - Initiate string `json:"initiate"` - Change string `json:"change"` - ChangeRemark string `json:"change_remark"` - Metadata map[string]interface{} `json:"metadata"` -} -type Total struct { - Currency string `json:"currency"` - Current string `json:"current"` - Initiate string `json:"initiate"` - Change string `json:"change"` - ChangeRemark string `json:"change_remark"` - Metadata map[string]interface{} `json:"metadata"` -} -type PayStatus struct { - StatusCode int64 `json:"status_code"` - StatusTitle string `json:"status_title"` - Metadata map[string]interface{} `json:"metadata"` -} - -type PayAmount struct { - Currency string `json:"currency"` - Current string `json:"current"` - Initiate string `json:"initiate"` - Change string `json:"change"` - ChangeRemark string `json:"change_remark"` - Metadata map[string]interface{} `json:"metadata"` -} -type Deposit struct { - TradeNo string `json:"trade_no"` - Status Status `json:"status"` - StatusLink []PayStatus `json:"status_link"` - PayTime string `json:"pay_time"` - PayAmount PayAmount `json:"pay_amount"` - PayMethod string `json:"pay_method"` - Metadata map[string]interface{} `json:"metadata"` -} -type RemainingBalance struct { - TradeNo string `json:"trade_no"` - Status PayStatus `json:"status"` - StatusLink []PayStatus `json:"status_link"` - PayTime string `json:"pay_time"` - PayAmount PayAmount `json:"pay_amount"` - PayMethod string `json:"pay_method"` - Metadata map[string]interface{} `json:"metadata"` -} -type OrderAmount struct { - Subtotal Subtotal `json:"subtotal"` - ShippingFee ShippingFee `json:"shipping_fee"` - Tax Tax `json:"tax"` - Discount Discount `json:"discount"` - Total Total `json:"total"` - Deposit Deposit `json:"deposit"` - RemainingBalance RemainingBalance `json:"remaining_balance"` -} -type DeliveryAddres struct { - Address string `json:"address"` - Name string `json:"name"` - Mobile string `json:"mobile"` -} diff --git a/service/repositories/order.go b/service/repositories/order.go new file mode 100644 index 00000000..1a34308e --- /dev/null +++ b/service/repositories/order.go @@ -0,0 +1,151 @@ +package repositories + +import ( + "context" + "encoding/json" + "errors" + "fusenapi/model/gmodel" + "fusenapi/utils/basic" + "fusenapi/utils/shopping_cart" + "math" + + "github.com/aws/aws-sdk-go/aws/session" + "gorm.io/gorm" +) + +func NewOrder(gormDB *gorm.DB, bLMServiceUrl *string, awsSession *session.Session) Order { + return &defaultOrder{ + MysqlConn: gormDB, + } +} + +type ( + defaultOrder struct { + MysqlConn *gorm.DB + } + Order interface { + // 下单 + // 预支付 + // 列表 + // 详情 + } + + /* 下单 */ + CreateReq struct { + CurrentCurrency string `json:"current_currency"` // 当前货币 + ExchangeRate string `json:"exchange_rate"` // 换算汇率 + OriginalCurrency string `json:"original_currency"` // 原始货币 + UserId int64 `json:"user_id"` + CartIds []int64 `json:"cart_ids"` + DeliveryMethod string `json:"delivery_method"` + } + CreateRes struct { + ErrorCode basic.StatusResponse + OrderSn string + } + /* 下单 */ +) + +// 下单 +func (d *defaultOrder) Create(ctx context.Context, in *CreateReq) (res *CreateRes, err error) { + var errorCode basic.StatusResponse + err = d.MysqlConn.WithContext(ctx).Transaction(func(tx *gorm.DB) error { + // 查询购物车 + var shoppingCartList []*gmodel.RelaFsShoppingCart + resShoppingCartFind := tx.Preload("ShoppingCartProduct").Preload("ShoppingCartProductPriceList").Preload("ShoppingCartProductModel3dList"). + Where("id IN ?", in.CartIds). + Where("user_id = ?", in.UserId). + Find(&shoppingCartList) + err = resShoppingCartFind.Error + if err != nil { + return err + } + shoppingCartListLen := len(shoppingCartList) + if shoppingCartListLen == 0 { + errorCode = *basic.CodeErrOrderCreatShoppingCartEmpty + return errors.New(errorCode.Message) + } + if shoppingCartListLen != len(in.CartIds) { + errorCode = *basic.CodeErrOrderCreatShoppingCartNotMatched + return errors.New(errorCode.Message) + } + + var orderProductList []*gmodel.OrderProduct + + for _, shoppingCart := range shoppingCartList { + // 购物车快照 + var shoppingCartSnapshot shopping_cart.CartSnapshot + // 购物车商品价格 + var shoppingCartProductPrice *gmodel.FsProductPrice + // 购物车商品模型 + var shoppingCartProductModel3d *gmodel.FsProductModel3d + if shoppingCart.Snapshot != nil { + json.Unmarshal([]byte(*shoppingCart.Snapshot), &shoppingCartSnapshot) + } + // 商品异常 + if shoppingCart.ShoppingCartProduct == nil || (shoppingCart.ShoppingCartProduct != nil && *shoppingCart.ShoppingCartProduct.IsShelf == 0) { + errorCode = *basic.CodeErrOrderCreatProductAbsent + errorCode.Message = "create order failed, product '" + shoppingCartSnapshot.ProductInfo.ProductName + "'is absent。" + return errors.New(errorCode.Message) + } + // 商品价格异常 + if len(shoppingCart.ShoppingCartProductPriceList) == 0 { + errorCode = *basic.CodeErrOrderCreatProductPriceAbsent + errorCode.Message = "create order failed, price of product '" + shoppingCartSnapshot.ProductInfo.ProductName + "'is absent。" + return errors.New(errorCode.Message) + } else { + var isProductPrice bool + for _, shoppingCartProductPriceInfo := range shoppingCart.ShoppingCartProductPriceList { + if shoppingCart.SizeId == shoppingCartProductPriceInfo.SizeId { + shoppingCartProductPrice = shoppingCartProductPriceInfo + isProductPrice = true + break + } + } + if !isProductPrice { + errorCode = *basic.CodeErrOrderCreatProductPriceAbsent + errorCode.Message = "create order failed, price of product '" + shoppingCartSnapshot.ProductInfo.ProductName + "'is absent。" + return errors.New(errorCode.Message) + } + shoppingCart.ShoppingCartProductPriceList = []*gmodel.FsProductPrice{shoppingCartProductPrice} + } + + // 商品模型异常 + if len(shoppingCart.ShoppingCartProductModel3dList) == 0 { + errorCode = *basic.CodeErrOrderCreatProductAccessoryAbsent + errorCode.Message = "create order failed, accessoryof product '" + shoppingCartSnapshot.ProductInfo.ProductName + "'is absent。" + return errors.New(errorCode.Message) + } else { + var isProductModel bool + for _, shoppingCartProductModel3dInfo := range shoppingCart.ShoppingCartProductModel3dList { + if shoppingCart.SizeId == shoppingCartProductModel3dInfo.SizeId { + shoppingCartProductModel3d = shoppingCartProductModel3dInfo + isProductModel = true + break + } + } + if !isProductModel { + errorCode = *basic.CodeErrOrderCreatProductAccessoryAbsent + errorCode.Message = "create order failed, accessoryof product '" + shoppingCartSnapshot.ProductInfo.ProductName + "'is absent。" + return errors.New(errorCode.Message) + } + shoppingCart.ShoppingCartProductModel3dList = []*gmodel.FsProductModel3d{shoppingCartProductModel3d} + } + + var purchaseQuantity float64 = float64(*shoppingCart.PurchaseQuantity) + var eachBoxNum float64 = float64(*shoppingCartProductPrice.EachBoxNum) + var boxNum int64 = math.Ceil(purchaseQuantity / eachBoxNum) + + // 存储订单商品 + orderProductList = append(orderProductList, &gmodel.OrderProduct{}) + } + + return nil + }) + if err != nil { + + } + return &CreateRes{ + ErrorCode: errorCode, + }, nil +} diff --git a/utils/basic/basic.go b/utils/basic/basic.go index 795f04ba..dc6f383b 100644 --- a/utils/basic/basic.go +++ b/utils/basic/basic.go @@ -99,6 +99,13 @@ var ( CodeLogoCombineErr = &StatusResponse{5115, "logo combine fail"} // 合图失败 CodeLogoCombineNoFoundErr = &StatusResponse{5116, "template record not found"} // 模版不存在 + + CodeErrOrder = &StatusResponse{5300, "ocreate order failed"} // 订单错误 + CodeErrOrderCreatShoppingCartEmpty = &StatusResponse{5301, "ocreate order failed, shopping cart is empty"} // 订单创建失败,购物车为空 + CodeErrOrderCreatShoppingCartNotMatched = &StatusResponse{5302, "ocreate order failed, shopping cart not matched"} // 订单创建失败,购物车不相符 + CodeErrOrderCreatProductAbsent = &StatusResponse{5303, "ocreate order failed, product is absent"} // 订单创建失败,商品不存在 + CodeErrOrderCreatProductPriceAbsent = &StatusResponse{5304, "ocreate order failed, price of product is absent"} // 订单创建失败,商品价格不存在 + CodeErrOrderCreatProductAccessoryAbsent = &StatusResponse{5305, "ocreate order failed, accessory of product is absent"} // 订单创建失败,商品配件不存在 ) type Response struct { diff --git a/utils/configs/order.go b/utils/configs/order.go index eb1f8d6b..347bbe4c 100644 --- a/utils/configs/order.go +++ b/utils/configs/order.go @@ -2,13 +2,7 @@ package configs import ( "context" - "encoding/json" - "errors" - "fusenapi/constants" - "fusenapi/model/gmodel" - "strconv" - "github.com/zeromicro/go-zero/core/logx" "gorm.io/gorm" ) @@ -27,49 +21,49 @@ type WebSetTimeInfoData struct { } func GetOrderTimeConfig(ctx context.Context, db *gorm.DB) (res WebSetTimeInfo, err error) { - resData, err := gmodel.NewFsWebSetModel(db).FindValueByKey(ctx, string(constants.WEBSET_TIME_INFO)) - if err != nil { - if errors.Is(err, gorm.ErrRecordNotFound) { - res.ProductDay = int64(constants.ORDER_PRODUCT_DAY) - res.FactoryDeliverDay = int64(constants.ORDER_FACTORY_DELIVER_DAY) - res.DeliverUpsDay = int64(constants.ORDER_DELIVER_UPS_DAY) - res.UpsTransDay = int64(constants.ORDER_UPS_TRANS_DAY) - return res, nil - } - logx.Error(err) - return res, err - } else { - var timeInfo WebSetTimeInfoData - err = json.Unmarshal([]byte(*resData.Value), &timeInfo) - if err != nil { - logx.Error(err) - return res, err - } - productDay, err := strconv.Atoi(timeInfo.ProductDay) - if err != nil { - logx.Error(err) - return res, err - } - factoryDeliverDay, err := strconv.Atoi(timeInfo.FactoryDeliverDay) - if err != nil { - logx.Error(err) - return res, err - } - deliverUpsDay, err := strconv.Atoi(timeInfo.DeliverUpsDay) - if err != nil { - logx.Error(err) - return res, err - } - upsTransDay, err := strconv.Atoi(timeInfo.UpsTransDay) - if err != nil { - logx.Error(err) - return res, err - } - res.ProductDay = int64(productDay) - res.FactoryDeliverDay = int64(factoryDeliverDay) - res.DeliverUpsDay = int64(deliverUpsDay) - res.UpsTransDay = int64(upsTransDay) - } + // resData, err := gmodel.NewFsWebSetModel(db).FindValueByKey(ctx, string(constants.WEBSET_TIME_INFO)) + // if err != nil { + // if errors.Is(err, gorm.ErrRecordNotFound) { + // res.ProductDay = int64(constants.ORDER_PRODUCT_DAY) + // res.FactoryDeliverDay = int64(constants.ORDER_FACTORY_DELIVER_DAY) + // res.DeliverUpsDay = int64(constants.ORDER_DELIVER_UPS_DAY) + // res.UpsTransDay = int64(constants.ORDER_UPS_TRANS_DAY) + // return res, nil + // } + // logx.Error(err) + // return res, err + // } else { + // var timeInfo WebSetTimeInfoData + // err = json.Unmarshal([]byte(*resData.Value), &timeInfo) + // if err != nil { + // logx.Error(err) + // return res, err + // } + // productDay, err := strconv.Atoi(timeInfo.ProductDay) + // if err != nil { + // logx.Error(err) + // return res, err + // } + // factoryDeliverDay, err := strconv.Atoi(timeInfo.FactoryDeliverDay) + // if err != nil { + // logx.Error(err) + // return res, err + // } + // deliverUpsDay, err := strconv.Atoi(timeInfo.DeliverUpsDay) + // if err != nil { + // logx.Error(err) + // return res, err + // } + // upsTransDay, err := strconv.Atoi(timeInfo.UpsTransDay) + // if err != nil { + // logx.Error(err) + // return res, err + // } + // res.ProductDay = int64(productDay) + // res.FactoryDeliverDay = int64(factoryDeliverDay) + // res.DeliverUpsDay = int64(deliverUpsDay) + // res.UpsTransDay = int64(upsTransDay) + // } return res, nil } diff --git a/utils/order/order.go b/utils/order/order.go index 175f0c10..bcd3bbaa 100644 --- a/utils/order/order.go +++ b/utils/order/order.go @@ -1 +1,25 @@ package order + +import ( + "fusenapi/constants" + "fusenapi/model/gmodel" + "strconv" +) + +func GetAmountCurrency(req *gmodel.AmountCurrency) (*float64, error) { + if req.CurrentCurrency == req.OriginalCurrency { + req.CurrentAmount = req.OriginalAmount + } else { + f1, err1 := strconv.ParseFloat(string(req.OriginalAmount), 64) + if err1 != nil { + return nil, err1 + } + f2, err2 := strconv.ParseFloat(string(req.OriginalAmount), 64) + if err2 != nil { + return nil, err2 + } + result := f1 * f2 + req.CurrentAmount = constants.AmountUnit(strconv.FormatFloat(result, 'f', -1, 64)) + } + return nil +} From ab6f3249a2a1ed1c92880afaf51dc55433e74891 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Fri, 15 Sep 2023 17:59:33 +0800 Subject: [PATCH 25/59] fix --- .../shopping-cart/internal/handler/routes.go | 5 +++++ server/shopping-cart/internal/types/types.go | 19 ++++++++++++++++++ server_api/shopping-cart.api | 20 +++++++++++++++++++ 3 files changed, 44 insertions(+) diff --git a/server/shopping-cart/internal/handler/routes.go b/server/shopping-cart/internal/handler/routes.go index 9857154b..3a4188d6 100644 --- a/server/shopping-cart/internal/handler/routes.go +++ b/server/shopping-cart/internal/handler/routes.go @@ -32,6 +32,11 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { Path: "/api/shopping-cart/get_carts", Handler: GetCartsHandler(serverCtx), }, + { + Method: http.MethodPost, + Path: "/api/shopping-cart/calculate_cart_price", + Handler: CalculateCartPriceHandler(serverCtx), + }, }, ) } diff --git a/server/shopping-cart/internal/types/types.go b/server/shopping-cart/internal/types/types.go index db117d2a..231c717e 100644 --- a/server/shopping-cart/internal/types/types.go +++ b/server/shopping-cart/internal/types/types.go @@ -80,6 +80,25 @@ type DiyInformation struct { Slogan string `json:"slogan"` } +type CalculateCartPriceReq struct { + CalculateList []CalculateItem `json:"calculate_list"` +} + +type CalculateItem struct { + CartId int64 `json:"cart_id"` //购物车id + PurchaseQuantity int64 `json:"purchase_quantity"` //数量 +} + +type CalculateCartPriceRsp struct { + CalculateResultList []CalculateResultItem `json:"calculate_result_list"` +} + +type CalculateResultItem struct { + CartId int64 `json:"cart_id"` //购物车id + ItemPrice string `json:"item_price"` //单价 + TotalPrice string `json:"total_price"` //总价 +} + type Request struct { } diff --git a/server_api/shopping-cart.api b/server_api/shopping-cart.api index 27249f45..5c3da538 100644 --- a/server_api/shopping-cart.api +++ b/server_api/shopping-cart.api @@ -21,6 +21,9 @@ service shopping-cart { //获取购物车列表 @handler GetCartsHandler get /api/shopping-cart/get_carts(GetCartsReq) returns (response); + //计算购物车价格 + @handler CalculateCartPriceHandler + post /api/shopping-cart/calculate_cart_price(CalculateCartPriceReq) returns (response); } //加入购物车 @@ -90,4 +93,21 @@ type DiyInformation { Website string `json:"website"` Qrcode string `json:"qrcode"` Slogan string `json:"slogan"` +} + +//计算购物车价格 +type CalculateCartPriceReq { + CalculateList []CalculateItem `json:"calculate_list"` +} +type CalculateItem { + CartId int64 `json:"cart_id"` //购物车id + PurchaseQuantity int64 `json:"purchase_quantity"` //数量 +} +type CalculateCartPriceRsp { + CalculateResultList []CalculateResultItem `json:"calculate_result_list"` +} +type CalculateResultItem { + CartId int64 `json:"cart_id"` //购物车id + ItemPrice string `json:"item_price"` //单价 + TotalPrice string `json:"total_price"` //总价 } \ No newline at end of file From 43c34159ce34782226897e572db552b4429731f3 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Fri, 15 Sep 2023 18:19:01 +0800 Subject: [PATCH 26/59] fix --- .../handler/calculatecartpricehandler.go | 35 ++++++++ .../internal/logic/calculatecartpricelogic.go | 86 +++++++++++++++++++ 2 files changed, 121 insertions(+) create mode 100644 server/shopping-cart/internal/handler/calculatecartpricehandler.go create mode 100644 server/shopping-cart/internal/logic/calculatecartpricelogic.go diff --git a/server/shopping-cart/internal/handler/calculatecartpricehandler.go b/server/shopping-cart/internal/handler/calculatecartpricehandler.go new file mode 100644 index 00000000..4f56e7d9 --- /dev/null +++ b/server/shopping-cart/internal/handler/calculatecartpricehandler.go @@ -0,0 +1,35 @@ +package handler + +import ( + "net/http" + "reflect" + + "fusenapi/utils/basic" + + "fusenapi/server/shopping-cart/internal/logic" + "fusenapi/server/shopping-cart/internal/svc" + "fusenapi/server/shopping-cart/internal/types" +) + +func CalculateCartPriceHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + + var req types.CalculateCartPriceReq + userinfo, err := basic.RequestParse(w, r, svcCtx, &req) + if err != nil { + return + } + + // 创建一个业务逻辑层实例 + l := logic.NewCalculateCartPriceLogic(r.Context(), svcCtx) + + rl := reflect.ValueOf(l) + basic.BeforeLogic(w, r, rl) + + resp := l.CalculateCartPrice(&req, userinfo) + + if !basic.AfterLogic(w, r, rl, resp) { + basic.NormalAfterLogic(w, r, resp) + } + } +} diff --git a/server/shopping-cart/internal/logic/calculatecartpricelogic.go b/server/shopping-cart/internal/logic/calculatecartpricelogic.go new file mode 100644 index 00000000..0c35521d --- /dev/null +++ b/server/shopping-cart/internal/logic/calculatecartpricelogic.go @@ -0,0 +1,86 @@ +package logic + +import ( + "context" + "fmt" + "fusenapi/model/gmodel" + "fusenapi/utils/auth" + "fusenapi/utils/basic" + + "fusenapi/server/shopping-cart/internal/svc" + "fusenapi/server/shopping-cart/internal/types" + + "github.com/zeromicro/go-zero/core/logx" +) + +type CalculateCartPriceLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +func NewCalculateCartPriceLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CalculateCartPriceLogic { + return &CalculateCartPriceLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +// 处理进入前逻辑w,r +// func (l *CalculateCartPriceLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) { +// } + +func (l *CalculateCartPriceLogic) CalculateCartPrice(req *types.CalculateCartPriceReq, userinfo *auth.UserInfo) (resp *basic.Response) { + if !userinfo.IsUser() { + return resp.SetStatusWithMessage(basic.CodeUnAuth, "please sign in") + } + if len(req.CalculateList) == 0 { + return resp.SetStatusWithMessage(basic.CodeOK, "success", types.CalculateCartPriceRsp{CalculateResultList: []types.CalculateResultItem{}}) + } + cartIds := make([]int64, 0, len(req.CalculateList)) + for _, v := range req.CalculateList { + cartIds = append(cartIds, v.CartId) + } + //获取购物车列表 + carts, _, err := l.svcCtx.AllModels.FsShoppingCart.GetAllCartsByParam(l.ctx, gmodel.GetAllCartsByParamReq{ + Ids: cartIds, + Fields: "id,size_id,product_id", + UserId: userinfo.UserId, + Page: 1, + Limit: len(cartIds), + }) + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get cart list") + } + sizeIds := make([]int64, 0, len(carts)) + productIds := make([]int64, 0, len(carts)) + fittingIds := make([]int64, 0, len(carts)) + for _, v := range carts { + sizeIds = append(sizeIds, *v.SizeId) + productIds = append(productIds, *v.ProductId) + if *v.FittingId > 0 { + fittingIds = append(fittingIds, *v.FittingId) + } + } + //根据sizeid获取价格列表 + priceList, err := l.svcCtx.AllModels.FsProductPrice.GetPriceListByProductIdsSizeIds(l.ctx, productIds, sizeIds) + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get price list") + } + mapPrice := make(map[string]int) + for k, v := range priceList { + mapPrice[fmt.Sprintf("%d_%d", *v.ProductId, *v.SizeId)] = k + } + //获取配件列表 + // todo 下周写 + /*fittingList, err := l.svcCtx.AllModels.FsProductModel3d.GetAllByIdsTag()*/ + return resp.SetStatus(basic.CodeOK) +} + +// 处理逻辑后 w,r 如:重定向, resp 必须重新处理 +// func (l *CalculateCartPriceLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) { +// // httpx.OkJsonCtx(r.Context(), w, resp) +// } From 95b826d8a6276ad23fef507ae6fa7f4d0a5ef463 Mon Sep 17 00:00:00 2001 From: momo <1012651275@qq.com> Date: Fri, 15 Sep 2023 18:30:45 +0800 Subject: [PATCH 27/59] =?UTF-8?q?fix:=E5=90=88=E5=B9=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- service/repositories/order.go | 34 ++++++++++++++++++++++++++++------ utils/order/order.go | 26 ++++++++++---------------- 2 files changed, 38 insertions(+), 22 deletions(-) diff --git a/service/repositories/order.go b/service/repositories/order.go index 1a34308e..b92668b8 100644 --- a/service/repositories/order.go +++ b/service/repositories/order.go @@ -7,6 +7,7 @@ import ( "fusenapi/model/gmodel" "fusenapi/utils/basic" "fusenapi/utils/shopping_cart" + "fusenapi/utils/step_price" "math" "github.com/aws/aws-sdk-go/aws/session" @@ -85,13 +86,13 @@ func (d *defaultOrder) Create(ctx context.Context, in *CreateReq) (res *CreateRe // 商品异常 if shoppingCart.ShoppingCartProduct == nil || (shoppingCart.ShoppingCartProduct != nil && *shoppingCart.ShoppingCartProduct.IsShelf == 0) { errorCode = *basic.CodeErrOrderCreatProductAbsent - errorCode.Message = "create order failed, product '" + shoppingCartSnapshot.ProductInfo.ProductName + "'is absent。" + errorCode.Message = "create order failed, product '" + shoppingCartSnapshot.ProductInfo.ProductName + "'is absent" return errors.New(errorCode.Message) } // 商品价格异常 if len(shoppingCart.ShoppingCartProductPriceList) == 0 { errorCode = *basic.CodeErrOrderCreatProductPriceAbsent - errorCode.Message = "create order failed, price of product '" + shoppingCartSnapshot.ProductInfo.ProductName + "'is absent。" + errorCode.Message = "create order failed, price of product '" + shoppingCartSnapshot.ProductInfo.ProductName + "'is absent" return errors.New(errorCode.Message) } else { var isProductPrice bool @@ -104,7 +105,7 @@ func (d *defaultOrder) Create(ctx context.Context, in *CreateReq) (res *CreateRe } if !isProductPrice { errorCode = *basic.CodeErrOrderCreatProductPriceAbsent - errorCode.Message = "create order failed, price of product '" + shoppingCartSnapshot.ProductInfo.ProductName + "'is absent。" + errorCode.Message = "create order failed, price of product '" + shoppingCartSnapshot.ProductInfo.ProductName + "'is absent" return errors.New(errorCode.Message) } shoppingCart.ShoppingCartProductPriceList = []*gmodel.FsProductPrice{shoppingCartProductPrice} @@ -113,7 +114,7 @@ func (d *defaultOrder) Create(ctx context.Context, in *CreateReq) (res *CreateRe // 商品模型异常 if len(shoppingCart.ShoppingCartProductModel3dList) == 0 { errorCode = *basic.CodeErrOrderCreatProductAccessoryAbsent - errorCode.Message = "create order failed, accessoryof product '" + shoppingCartSnapshot.ProductInfo.ProductName + "'is absent。" + errorCode.Message = "create order failed, accessoryof product '" + shoppingCartSnapshot.ProductInfo.ProductName + "'is absent" return errors.New(errorCode.Message) } else { var isProductModel bool @@ -126,7 +127,7 @@ func (d *defaultOrder) Create(ctx context.Context, in *CreateReq) (res *CreateRe } if !isProductModel { errorCode = *basic.CodeErrOrderCreatProductAccessoryAbsent - errorCode.Message = "create order failed, accessoryof product '" + shoppingCartSnapshot.ProductInfo.ProductName + "'is absent。" + errorCode.Message = "create order failed, accessory of product '" + shoppingCartSnapshot.ProductInfo.ProductName + "'is absent" return errors.New(errorCode.Message) } shoppingCart.ShoppingCartProductModel3dList = []*gmodel.FsProductModel3d{shoppingCartProductModel3d} @@ -134,7 +135,28 @@ func (d *defaultOrder) Create(ctx context.Context, in *CreateReq) (res *CreateRe var purchaseQuantity float64 = float64(*shoppingCart.PurchaseQuantity) var eachBoxNum float64 = float64(*shoppingCartProductPrice.EachBoxNum) - var boxNum int64 = math.Ceil(purchaseQuantity / eachBoxNum) + var boxNum float64 = math.Ceil(purchaseQuantity / eachBoxNum) + var stepNum []int + var stepPrice []int + if *shoppingCartProductPrice.StepNum == "" { + errorCode = *basic.CodeErrOrderCreatProductPriceAbsent + errorCode.Message = "create order failed, step num of product '" + shoppingCartSnapshot.ProductInfo.ProductName + "'is failed" + return errors.New(errorCode.Message) + } else { + json.Unmarshal([]byte(*shoppingCartProductPrice.StepNum), &stepNum) + } + if *shoppingCartProductPrice.StepPrice == "" { + errorCode = *basic.CodeErrOrderCreatProductPriceAbsent + errorCode.Message = "create order failed, step price of product '" + shoppingCartSnapshot.ProductInfo.ProductName + "'is failed" + return errors.New(errorCode.Message) + } else { + json.Unmarshal([]byte(*shoppingCartProductPrice.StepPrice), &stepPrice) + } + // 商品单价 + productPrice := step_price.GetCentStepPrice(int(boxNum), stepNum, stepPrice) + + // 商品总价 + productTotalPrice := productPrice * *shoppingCart.PurchaseQuantity // 存储订单商品 orderProductList = append(orderProductList, &gmodel.OrderProduct{}) diff --git a/utils/order/order.go b/utils/order/order.go index bcd3bbaa..ca040188 100644 --- a/utils/order/order.go +++ b/utils/order/order.go @@ -1,25 +1,19 @@ package order -import ( - "fusenapi/constants" - "fusenapi/model/gmodel" - "strconv" -) +type AmountCurrency struct { + ExchangeRate float64 `json:"exchange_rate"` // 换算汇率 + CurrentAmount float64 `json:"current_amount"` // 当前金额 + OriginalAmount float64 `json:"original_amount"` // 原始金额 + CurrentCurrency string `json:"current_currency"` // 当前货币 + OriginalCurrency string `json:"original_currency"` // 原始货币 +} -func GetAmountCurrency(req *gmodel.AmountCurrency) (*float64, error) { +// 汇率换算 +func GetAmountCurrency(req *AmountCurrency) error { if req.CurrentCurrency == req.OriginalCurrency { req.CurrentAmount = req.OriginalAmount } else { - f1, err1 := strconv.ParseFloat(string(req.OriginalAmount), 64) - if err1 != nil { - return nil, err1 - } - f2, err2 := strconv.ParseFloat(string(req.OriginalAmount), 64) - if err2 != nil { - return nil, err2 - } - result := f1 * f2 - req.CurrentAmount = constants.AmountUnit(strconv.FormatFloat(result, 'f', -1, 64)) + req.CurrentAmount = req.OriginalAmount * req.ExchangeRate } return nil } From b07473478bf8c36a182ca8dbbaf05d7b44e5e397 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Mon, 18 Sep 2023 11:45:29 +0800 Subject: [PATCH 28/59] fix --- .../internal/logic/getcartslogic.go | 91 ++++++++++++++----- server/shopping-cart/internal/types/types.go | 10 +- server_api/shopping-cart.api | 9 +- .../verify_shopping_cart_channged.go | 2 +- 4 files changed, 87 insertions(+), 25 deletions(-) diff --git a/server/shopping-cart/internal/logic/getcartslogic.go b/server/shopping-cart/internal/logic/getcartslogic.go index 0a52ba1e..2ed45ff5 100644 --- a/server/shopping-cart/internal/logic/getcartslogic.go +++ b/server/shopping-cart/internal/logic/getcartslogic.go @@ -2,6 +2,7 @@ package logic import ( "context" + "encoding/json" "errors" "fmt" "fusenapi/constants" @@ -9,6 +10,7 @@ import ( "fusenapi/utils/auth" "fusenapi/utils/basic" "fusenapi/utils/format" + "fusenapi/utils/s3url_to_s3id" "fusenapi/utils/shopping_cart" "fusenapi/utils/step_price" "math" @@ -39,6 +41,7 @@ func NewGetCartsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetCarts // } func (l *GetCartsLogic) GetCarts(req *types.GetCartsReq, userinfo *auth.UserInfo) (resp *basic.Response) { + userinfo.UserId = 39 if req.CurrentPage <= 0 { req.CurrentPage = constants.DEFAULT_PAGE } @@ -66,20 +69,22 @@ func (l *GetCartsLogic) GetCarts(req *types.GetCartsReq, userinfo *auth.UserInfo }) } var ( - mapSize = make(map[int64]gmodel.FsProductSize) - mapModel = make(map[int64]gmodel.FsProductModel3d) - mapTemplate = make(map[int64]gmodel.FsProductTemplateV2) - mapSizePrice = make(map[string]gmodel.FsProductPrice) - mapProduct = make(map[int64]struct{}) + mapSize = make(map[int64]gmodel.FsProductSize) + mapModel = make(map[int64]gmodel.FsProductModel3d) + mapTemplate = make(map[int64]gmodel.FsProductTemplateV2) + mapSizePrice = make(map[string]gmodel.FsProductPrice) + mapProduct = make(map[int64]gmodel.FsProduct) + mapResourceMetadata = make(map[string]interface{}) ) //获取相关信息 err = l.GetRelationInfo(GetRelationInfoReq{ - Carts: carts, - MapSize: mapSize, - MapModel: mapModel, - MapTemplate: mapTemplate, - MapSizePrice: mapSizePrice, - MapProduct: mapProduct, + Carts: carts, + MapSize: mapSize, + MapModel: mapModel, + MapTemplate: mapTemplate, + MapSizePrice: mapSizePrice, + MapProduct: mapProduct, + MapResourceMetadata: mapResourceMetadata, }) if err != nil { return resp.SetStatusWithMessage(basic.CodeServiceErr, err.Error()) @@ -137,6 +142,10 @@ func (l *GetCartsLogic) GetCarts(req *types.GetCartsReq, userinfo *auth.UserInfo stepQuantityList = append(stepQuantityList, tmpQuantity) tmpMinBuyNum++ } + sizeCapacity := snapShot.SizeInfo.Capacity + if sizeInfo, ok := mapSize[*cart.SizeId]; ok { + sizeCapacity = *sizeInfo.Capacity + } //根据数量获取阶梯价格中对应的价格 itemPrice := step_price.GetCentStepPrice(boxQuantity, stepNum, stepPrice) //如果有配件,单价也要加入配件价格 @@ -145,12 +154,34 @@ func (l *GetCartsLogic) GetCarts(req *types.GetCartsReq, userinfo *auth.UserInfo itemPrice += *curFittingInfo.Price } } + fittingName := snapShot.FittingInfo.FittingName + if fittingInfo, ok := mapModel[*cart.FittingId]; ok { + fittingName = *fittingInfo.Name + } totalPrice := itemPrice * (*cart.PurchaseQuantity) + productCover := "" //产品封面图 + productName := snapShot.ProductInfo.ProductName + productSn := snapShot.ProductInfo.ProductSn + var productCoverMetadata interface{} + if productInfo, ok := mapProduct[*cart.ProductId]; ok { + productCover = *productInfo.Cover + productName = *productInfo.Title + productSn = *productInfo.Sn + if metadata, ok := mapResourceMetadata[*productInfo.Cover]; ok { + productCoverMetadata = metadata + } + } item := types.CartItem{ - ProductId: *cart.ProductId, + ProductInfo: types.ProductInfo{ + ProductId: *cart.ProductId, + ProductName: productName, + ProductSn: productSn, + ProductCover: productCover, + ProductCoverMetadata: productCoverMetadata, + }, SizeInfo: types.SizeInfo{ SizeId: *cart.SizeId, - Capacity: snapShot.SizeInfo.Capacity, + Capacity: sizeCapacity, Title: types.SizeTitle{ Cm: snapShot.SizeInfo.Cm, Inch: snapShot.SizeInfo.Inch, @@ -158,7 +189,7 @@ func (l *GetCartsLogic) GetCarts(req *types.GetCartsReq, userinfo *auth.UserInfo }, FittingInfo: types.FittingInfo{ FittingId: *cart.FittingId, - FittingName: snapShot.FittingInfo.FittingName, + FittingName: fittingName, }, ItemPrice: fmt.Sprintf("%.3f", format.CentitoDollar(itemPrice)), TotalPrice: fmt.Sprintf("%.3f", format.CentitoDollar(totalPrice)), @@ -194,12 +225,13 @@ func (l *GetCartsLogic) GetCarts(req *types.GetCartsReq, userinfo *auth.UserInfo // 获取相关信息 type GetRelationInfoReq struct { - Carts []gmodel.FsShoppingCart - MapSize map[int64]gmodel.FsProductSize - MapModel map[int64]gmodel.FsProductModel3d - MapTemplate map[int64]gmodel.FsProductTemplateV2 - MapSizePrice map[string]gmodel.FsProductPrice - MapProduct map[int64]struct{} + Carts []gmodel.FsShoppingCart + MapSize map[int64]gmodel.FsProductSize + MapModel map[int64]gmodel.FsProductModel3d + MapTemplate map[int64]gmodel.FsProductTemplateV2 + MapSizePrice map[string]gmodel.FsProductPrice + MapProduct map[int64]gmodel.FsProduct + MapResourceMetadata map[string]interface{} } func (l *GetCartsLogic) GetRelationInfo(req GetRelationInfoReq) error { @@ -215,13 +247,28 @@ func (l *GetCartsLogic) GetRelationInfo(req GetRelationInfoReq) error { productIds = append(productIds, *req.Carts[index].ProductId) } //获取产品集合 - productList, err := l.svcCtx.AllModels.FsProduct.GetProductListByIds(l.ctx, productIds, "", "id") + productList, err := l.svcCtx.AllModels.FsProduct.GetProductListByIds(l.ctx, productIds, "") if err != nil { logx.Error(err) return errors.New("failed to get product list") } + resourceIds := make([]string, 0, len(productList)) for _, v := range productList { - req.MapProduct[v.Id] = struct{}{} + req.MapProduct[v.Id] = v + resourceIds = append(resourceIds, s3url_to_s3id.GetS3ResourceIdFormUrl(*v.Cover)) + } + //根据resourceUrls找到对应的元数据 + resourceMetadataList, err := l.svcCtx.AllModels.FsResource.FindAllByResourceIds(l.ctx, resourceIds) + if err != nil { + logx.Error(err) + return errors.New("failed to get resource list") + } + for _, v := range resourceMetadataList { + var metadata interface{} + if v.Metadata != nil { + _ = json.Unmarshal(*v.Metadata, &metadata) + } + req.MapResourceMetadata[*v.ResourceUrl] = metadata } //获取尺寸列表 sizeList, err := l.svcCtx.AllModels.FsProductSize.GetAllByIds(l.ctx, sizeIds, "") diff --git a/server/shopping-cart/internal/types/types.go b/server/shopping-cart/internal/types/types.go index 231c717e..ec1ed92b 100644 --- a/server/shopping-cart/internal/types/types.go +++ b/server/shopping-cart/internal/types/types.go @@ -44,7 +44,7 @@ type GetCartsRsp struct { } type CartItem struct { - ProductId int64 `json:"product_id"` //产品id + ProductInfo ProductInfo `json:"product_info"` //产品信息 SizeInfo SizeInfo `json:"size_info"` //尺寸信息 FittingInfo FittingInfo `json:"fitting_info"` //配件信息 ItemPrice string `json:"item_price"` //单价 @@ -56,6 +56,14 @@ type CartItem struct { InvalidDescription string `json:"invalid_description"` //无效原因 } +type ProductInfo struct { + ProductId int64 `json:"product_id"` //产品id + ProductName string `json:"product_name"` + ProductSn string `json:"product_sn"` + ProductCover string `json:"product_cover"` //产品图 + ProductCoverMetadata interface{} `json:"product_cover_metadata"` //产品图元数据 +} + type SizeInfo struct { SizeId int64 `json:"size_id"` //尺寸id Capacity string `json:"capacity"` //尺寸名称 diff --git a/server_api/shopping-cart.api b/server_api/shopping-cart.api index 5c3da538..bd595d74 100644 --- a/server_api/shopping-cart.api +++ b/server_api/shopping-cart.api @@ -63,7 +63,7 @@ type GetCartsRsp { CartList []CartItem `json:"cart_list"` } type CartItem { - ProductId int64 `json:"product_id"` //产品id + ProductInfo ProductInfo `json:"product_info"` //产品信息 SizeInfo SizeInfo `json:"size_info"` //尺寸信息 FittingInfo FittingInfo `json:"fitting_info"` //配件信息 ItemPrice string `json:"item_price"` //单价 @@ -74,6 +74,13 @@ type CartItem { IsInvalid bool `json:"is_invalid"` //是否无效 InvalidDescription string `json:"invalid_description"` //无效原因 } +type ProductInfo { + ProductId int64 `json:"product_id"` //产品id + ProductName string `json:"product_name"` + ProductSn string `json:"product_sn"` + ProductCover string `json:"product_cover"` //产品图 + ProductCoverMetadata interface{} `json:"product_cover_metadata"` //产品图元数据 +} type SizeInfo { SizeId int64 `json:"size_id"` //尺寸id Capacity string `json:"capacity"` //尺寸名称 diff --git a/utils/shopping_cart/verify_shopping_cart_channged.go b/utils/shopping_cart/verify_shopping_cart_channged.go index 10315ffe..fc43c0fa 100644 --- a/utils/shopping_cart/verify_shopping_cart_channged.go +++ b/utils/shopping_cart/verify_shopping_cart_channged.go @@ -15,7 +15,7 @@ type VerifyShoppingCartSnapshotDataChangeReq struct { MapTemplate map[int64]gmodel.FsProductTemplateV2 MapCartChange map[int64]string MapSnapshot map[int64]CartSnapshot - MapProduct map[int64]struct{} + MapProduct map[int64]gmodel.FsProduct } func VerifyShoppingCartSnapshotDataChange(req VerifyShoppingCartSnapshotDataChangeReq) error { From 1a7ce5013e4f3558e0180b96ea20a98b94409565 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Mon, 18 Sep 2023 12:31:51 +0800 Subject: [PATCH 29/59] fix --- model/gmodel/fs_product_model3d_logic.go | 8 +- .../internal/logic/calculatecartpricelogic.go | 84 +++++++++++++++++-- .../internal/logic/getcartslogic.go | 9 +- server/shopping-cart/internal/types/types.go | 1 + server_api/shopping-cart.api | 1 + service/repositories/order.go | 3 +- 6 files changed, 90 insertions(+), 16 deletions(-) diff --git a/model/gmodel/fs_product_model3d_logic.go b/model/gmodel/fs_product_model3d_logic.go index 5ff31216..74ffe4e6 100755 --- a/model/gmodel/fs_product_model3d_logic.go +++ b/model/gmodel/fs_product_model3d_logic.go @@ -37,11 +37,15 @@ func (d *FsProductModel3dModel) GetAllByIdsWithoutStatus(ctx context.Context, id err = db.Find(&resp).Error return resp, err } -func (d *FsProductModel3dModel) GetAllByIdsTag(ctx context.Context, ids []int64, tag int64) (resp []FsProductModel3d, err error) { +func (d *FsProductModel3dModel) GetAllByIdsTag(ctx context.Context, ids []int64, tag int64, fields ...string) (resp []FsProductModel3d, err error) { if len(ids) == 0 { return } - err = d.db.WithContext(ctx).Model(&FsProductModel3d{}).Where("`id` in (?) and `status` = ? and `tag` = ?", ids, 1, tag).Find(&resp).Error + db := d.db.WithContext(ctx).Model(&FsProductModel3d{}).Where("`id` in (?) and `status` = ? and `tag` = ?", ids, 1, tag) + if len(fields) > 0 { + db = db.Select(fields[0]) + } + err = db.Find(&resp).Error return resp, err } diff --git a/server/shopping-cart/internal/logic/calculatecartpricelogic.go b/server/shopping-cart/internal/logic/calculatecartpricelogic.go index 0c35521d..3b68a93c 100644 --- a/server/shopping-cart/internal/logic/calculatecartpricelogic.go +++ b/server/shopping-cart/internal/logic/calculatecartpricelogic.go @@ -3,9 +3,14 @@ package logic import ( "context" "fmt" + "fusenapi/constants" "fusenapi/model/gmodel" "fusenapi/utils/auth" "fusenapi/utils/basic" + "fusenapi/utils/format" + "fusenapi/utils/step_price" + "math" + "strings" "fusenapi/server/shopping-cart/internal/svc" "fusenapi/server/shopping-cart/internal/types" @@ -32,6 +37,7 @@ func NewCalculateCartPriceLogic(ctx context.Context, svcCtx *svc.ServiceContext) // } func (l *CalculateCartPriceLogic) CalculateCartPrice(req *types.CalculateCartPriceReq, userinfo *auth.UserInfo) (resp *basic.Response) { + userinfo.UserId = 39 if !userinfo.IsUser() { return resp.SetStatusWithMessage(basic.CodeUnAuth, "please sign in") } @@ -39,13 +45,18 @@ func (l *CalculateCartPriceLogic) CalculateCartPrice(req *types.CalculateCartPri return resp.SetStatusWithMessage(basic.CodeOK, "success", types.CalculateCartPriceRsp{CalculateResultList: []types.CalculateResultItem{}}) } cartIds := make([]int64, 0, len(req.CalculateList)) + mapCalculateQuantity := make(map[int64]int64) for _, v := range req.CalculateList { cartIds = append(cartIds, v.CartId) + if v.PurchaseQuantity <= 0 { + return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "purchase quantity must grater than 0") + } + mapCalculateQuantity[v.CartId] = v.PurchaseQuantity } //获取购物车列表 carts, _, err := l.svcCtx.AllModels.FsShoppingCart.GetAllCartsByParam(l.ctx, gmodel.GetAllCartsByParamReq{ Ids: cartIds, - Fields: "id,size_id,product_id", + Fields: "id,size_id,product_id,fitting_id", UserId: userinfo.UserId, Page: 1, Limit: len(cartIds), @@ -54,6 +65,9 @@ func (l *CalculateCartPriceLogic) CalculateCartPrice(req *types.CalculateCartPri logx.Error(err) return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get cart list") } + if len(carts) < len(req.CalculateList) { + return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "please refresh page for the shopping cart has changed!!") + } sizeIds := make([]int64, 0, len(carts)) productIds := make([]int64, 0, len(carts)) fittingIds := make([]int64, 0, len(carts)) @@ -70,14 +84,68 @@ func (l *CalculateCartPriceLogic) CalculateCartPrice(req *types.CalculateCartPri logx.Error(err) return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get price list") } - mapPrice := make(map[string]int) - for k, v := range priceList { - mapPrice[fmt.Sprintf("%d_%d", *v.ProductId, *v.SizeId)] = k + mapPrice := make(map[string]gmodel.FsProductPrice) + for _, v := range priceList { + mapPrice[fmt.Sprintf("%d_%d", *v.ProductId, *v.SizeId)] = v } - //获取配件列表 - // todo 下周写 - /*fittingList, err := l.svcCtx.AllModels.FsProductModel3d.GetAllByIdsTag()*/ - return resp.SetStatus(basic.CodeOK) + //获取配件列表(只有id跟价格) + fittingList, err := l.svcCtx.AllModels.FsProductModel3d.GetAllByIdsTag(l.ctx, fittingIds, constants.TAG_PARTS, "id,price") + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get fitting list") + } + mapFitting := make(map[int64]int64) + for _, v := range fittingList { + mapFitting[v.Id] = *v.Price + } + //开始计算价格 + calculateResultList := make([]types.CalculateResultItem, 0, len(req.CalculateList)) + sumPrice := int64(0) + for _, cart := range carts { + sizePrice, ok := mapPrice[fmt.Sprintf("%d_%d", *cart.ProductId, *cart.SizeId)] + if !ok { + return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, fmt.Sprintf("there carts contain some one which have no price info:%d_%d", *cart.ProductId, *cart.SizeId)) + } + //阶梯数量切片 + stepNum, err := format.StrSlicToIntSlice(strings.Split(*sizePrice.StepNum, ",")) + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeServiceErr, fmt.Sprintf("failed to parse step number:%d_%d", *cart.ProductId, *cart.SizeId)) + } + lenStepNum := len(stepNum) + //阶梯价格切片 + stepPrice, err := format.StrSlicToIntSlice(strings.Split(*sizePrice.StepPrice, ",")) + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeServiceErr, fmt.Sprintf("failed to parse step price:%d_%d", *cart.ProductId, *cart.SizeId)) + } + lenStepPrice := len(stepPrice) + if lenStepPrice == 0 || lenStepNum == 0 { + return resp.SetStatusWithMessage(basic.CodeServiceErr, fmt.Sprintf("step price or step number is not set:%d_%d", *cart.ProductId, *cart.SizeId)) + } + //购买箱数 + boxQuantity := int(math.Ceil(float64(mapCalculateQuantity[cart.Id]) / float64(*sizePrice.EachBoxNum))) + //根据数量获取阶梯价格中对应的价格 + itemPrice := step_price.GetCentStepPrice(boxQuantity, stepNum, stepPrice) + //如果有配件,单价也要加入配件价格 + if *cart.FittingId > 0 { + if fittingPrice, ok := mapFitting[*cart.FittingId]; ok { + itemPrice += fittingPrice + } + } + //单个购物车总价 + totalPrice := itemPrice * mapCalculateQuantity[cart.Id] + calculateResultList = append(calculateResultList, types.CalculateResultItem{ + CartId: cart.Id, + ItemPrice: fmt.Sprintf("%.3f", format.CentitoDollar(itemPrice)), + TotalPrice: fmt.Sprintf("%.3f", format.CentitoDollar(totalPrice)), + }) + sumPrice += totalPrice + } + return resp.SetStatusWithMessage(basic.CodeOK, "success", types.CalculateCartPriceRsp{ + SumPrice: fmt.Sprintf("%.3f", format.CentitoDollar(sumPrice)), + CalculateResultList: calculateResultList, + }) } // 处理逻辑后 w,r 如:重定向, resp 必须重新处理 diff --git a/server/shopping-cart/internal/logic/getcartslogic.go b/server/shopping-cart/internal/logic/getcartslogic.go index 2ed45ff5..303716f4 100644 --- a/server/shopping-cart/internal/logic/getcartslogic.go +++ b/server/shopping-cart/internal/logic/getcartslogic.go @@ -41,7 +41,6 @@ func NewGetCartsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetCarts // } func (l *GetCartsLogic) GetCarts(req *types.GetCartsReq, userinfo *auth.UserInfo) (resp *basic.Response) { - userinfo.UserId = 39 if req.CurrentPage <= 0 { req.CurrentPage = constants.DEFAULT_PAGE } @@ -112,24 +111,24 @@ func (l *GetCartsLogic) GetCarts(req *types.GetCartsReq, userinfo *auth.UserInfo snapShot := mapSnapshot[cart.Id] sizePrice, ok := mapSizePrice[fmt.Sprintf("%d_%d", *cart.ProductId, *cart.SizeId)] if !ok { - return resp.SetStatusWithMessage(basic.CodeServiceErr, fmt.Sprintf("the size`s price info is not exists:%d", *cart.SizeId)) + return resp.SetStatusWithMessage(basic.CodeServiceErr, fmt.Sprintf("the size`s price info is not exists:%d_%d", *cart.ProductId, *cart.SizeId)) } //阶梯数量切片 stepNum, err := format.StrSlicToIntSlice(strings.Split(*sizePrice.StepNum, ",")) if err != nil { logx.Error(err) - return resp.SetStatusWithMessage(basic.CodeServiceErr, fmt.Sprintf("failed to parse step number:%d", *cart.SizeId)) + return resp.SetStatusWithMessage(basic.CodeServiceErr, fmt.Sprintf("failed to parse step number:%d_%d", *cart.ProductId, *cart.SizeId)) } lenStepNum := len(stepNum) //阶梯价格切片 stepPrice, err := format.StrSlicToIntSlice(strings.Split(*sizePrice.StepPrice, ",")) if err != nil { logx.Error(err) - return resp.SetStatusWithMessage(basic.CodeServiceErr, fmt.Sprintf("failed to parse step price:%d", *cart.SizeId)) + return resp.SetStatusWithMessage(basic.CodeServiceErr, fmt.Sprintf("failed to parse step price:%d_%d", *cart.ProductId, *cart.SizeId)) } lenStepPrice := len(stepPrice) if lenStepPrice == 0 || lenStepNum == 0 { - return resp.SetStatusWithMessage(basic.CodeServiceErr, fmt.Sprintf("step price or step number is not set:%d ", *cart.SizeId)) + return resp.SetStatusWithMessage(basic.CodeServiceErr, fmt.Sprintf("step price or step number is not set:%d_%d ", *cart.ProductId, *cart.SizeId)) } //购买箱数 boxQuantity := int(math.Ceil(float64(*cart.PurchaseQuantity) / float64(*sizePrice.EachBoxNum))) diff --git a/server/shopping-cart/internal/types/types.go b/server/shopping-cart/internal/types/types.go index ec1ed92b..c8630940 100644 --- a/server/shopping-cart/internal/types/types.go +++ b/server/shopping-cart/internal/types/types.go @@ -98,6 +98,7 @@ type CalculateItem struct { } type CalculateCartPriceRsp struct { + SumPrice string `json:"sum_price"` CalculateResultList []CalculateResultItem `json:"calculate_result_list"` } diff --git a/server_api/shopping-cart.api b/server_api/shopping-cart.api index bd595d74..523e734f 100644 --- a/server_api/shopping-cart.api +++ b/server_api/shopping-cart.api @@ -111,6 +111,7 @@ type CalculateItem { PurchaseQuantity int64 `json:"purchase_quantity"` //数量 } type CalculateCartPriceRsp { + SumPrice string `json:"sum_price"` CalculateResultList []CalculateResultItem `json:"calculate_result_list"` } type CalculateResultItem { diff --git a/service/repositories/order.go b/service/repositories/order.go index b92668b8..02cbe08b 100644 --- a/service/repositories/order.go +++ b/service/repositories/order.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "errors" + "fmt" "fusenapi/model/gmodel" "fusenapi/utils/basic" "fusenapi/utils/shopping_cart" @@ -157,7 +158,7 @@ func (d *defaultOrder) Create(ctx context.Context, in *CreateReq) (res *CreateRe // 商品总价 productTotalPrice := productPrice * *shoppingCart.PurchaseQuantity - + fmt.Println(productTotalPrice) // 存储订单商品 orderProductList = append(orderProductList, &gmodel.OrderProduct{}) } From 5e2760849c4eb188a1d90b97f81b0490f92734f4 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Mon, 18 Sep 2023 14:23:57 +0800 Subject: [PATCH 30/59] fix --- .../internal/logic/getproducttemplatetagslogic.go | 3 +++ server/product-template-tag/internal/types/types.go | 9 +++++---- server_api/product-template-tag.api | 1 + 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/server/product-template-tag/internal/logic/getproducttemplatetagslogic.go b/server/product-template-tag/internal/logic/getproducttemplatetagslogic.go index 4a24ce61..c0384d90 100644 --- a/server/product-template-tag/internal/logic/getproducttemplatetagslogic.go +++ b/server/product-template-tag/internal/logic/getproducttemplatetagslogic.go @@ -54,6 +54,7 @@ func (l *GetProductTemplateTagsLogic) GetProductTemplateTags(req *types.GetProdu logx.Error(err) return } + var colors interface{} if logoInfo.Metadata == nil || *logoInfo.Metadata == "" { // 返回固定模板A1a productTemplateTags, err = l.svcCtx.AllModels.FsProductTemplateTags.GetListByTagNames(l.ctx, []string{"A1"}, req.Limit, 1, "`id` DESC") @@ -68,6 +69,7 @@ func (l *GetProductTemplateTagsLogic) GetProductTemplateTags(req *types.GetProdu logx.Error(err) return resp.SetStatusWithMessage(basic.CodeJsonErr, "failed to parse user metadata") } + colors = metaData["colors"] var templateTagNameList []string b, _ := json.Marshal(metaData["template_tagid"]) if err = json.Unmarshal(b, &templateTagNameList); err != nil { @@ -106,6 +108,7 @@ func (l *GetProductTemplateTagsLogic) GetProductTemplateTags(req *types.GetProdu TemplateTag: *v.TemplateTag, Cover: *v.Cover, CoverMetadata: mapResourceMetadata[*v.Cover], + Colors: colors, }) } return resp.SetStatusWithMessage(basic.CodeOK, "success", list) diff --git a/server/product-template-tag/internal/types/types.go b/server/product-template-tag/internal/types/types.go index 6c7f6950..e81cb040 100644 --- a/server/product-template-tag/internal/types/types.go +++ b/server/product-template-tag/internal/types/types.go @@ -14,6 +14,7 @@ type GetProductTemplateTagsRsp struct { TemplateTag string `json:"template_tag"` Cover string `json:"cover"` CoverMetadata interface{} `json:"cover_metadata"` + Colors interface{} `json:"colors"` } type Request struct { @@ -39,10 +40,10 @@ type File struct { } type Meta struct { - TotalCount int64 `json:"totalCount"` - PageCount int64 `json:"pageCount"` - CurrentPage int `json:"currentPage"` - PerPage int `json:"perPage"` + TotalCount int64 `json:"total_count"` + PageCount int64 `json:"page_count"` + CurrentPage int `json:"current_page"` + PerPage int `json:"per_page"` } // Set 设置Response的Code和Message值 diff --git a/server_api/product-template-tag.api b/server_api/product-template-tag.api index bdc513b7..d663e109 100644 --- a/server_api/product-template-tag.api +++ b/server_api/product-template-tag.api @@ -24,4 +24,5 @@ type GetProductTemplateTagsRsp { TemplateTag string `json:"template_tag"` Cover string `json:"cover"` CoverMetadata interface{} `json:"cover_metadata"` + Colors interface{} `json:"colors"` } \ No newline at end of file From 43f394250820aeceabf4e033a2e140e906e417a8 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Mon, 18 Sep 2023 14:27:55 +0800 Subject: [PATCH 31/59] fix --- service/repositories/order.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/service/repositories/order.go b/service/repositories/order.go index b92668b8..02cbe08b 100644 --- a/service/repositories/order.go +++ b/service/repositories/order.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "errors" + "fmt" "fusenapi/model/gmodel" "fusenapi/utils/basic" "fusenapi/utils/shopping_cart" @@ -157,7 +158,7 @@ func (d *defaultOrder) Create(ctx context.Context, in *CreateReq) (res *CreateRe // 商品总价 productTotalPrice := productPrice * *shoppingCart.PurchaseQuantity - + fmt.Println(productTotalPrice) // 存储订单商品 orderProductList = append(orderProductList, &gmodel.OrderProduct{}) } From 9476414e68226424afaff5a141f26e7da02603ab Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Mon, 18 Sep 2023 14:53:15 +0800 Subject: [PATCH 32/59] fix --- server/shopping-cart/internal/logic/calculatecartpricelogic.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/server/shopping-cart/internal/logic/calculatecartpricelogic.go b/server/shopping-cart/internal/logic/calculatecartpricelogic.go index 3b68a93c..8a9fe327 100644 --- a/server/shopping-cart/internal/logic/calculatecartpricelogic.go +++ b/server/shopping-cart/internal/logic/calculatecartpricelogic.go @@ -131,6 +131,8 @@ func (l *CalculateCartPriceLogic) CalculateCartPrice(req *types.CalculateCartPri if *cart.FittingId > 0 { if fittingPrice, ok := mapFitting[*cart.FittingId]; ok { itemPrice += fittingPrice + } else { + return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "cart contain some one witch lose fitting:%d", *cart.FittingId) } } //单个购物车总价 From ceec00c5286d365bdb3e9948a9589c80be7426ee Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Mon, 18 Sep 2023 15:18:55 +0800 Subject: [PATCH 33/59] fix --- .../shopping-cart/internal/logic/calculatecartpricelogic.go | 6 +++--- server/shopping-cart/internal/types/types.go | 2 +- server_api/shopping-cart.api | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/server/shopping-cart/internal/logic/calculatecartpricelogic.go b/server/shopping-cart/internal/logic/calculatecartpricelogic.go index 8a9fe327..25102872 100644 --- a/server/shopping-cart/internal/logic/calculatecartpricelogic.go +++ b/server/shopping-cart/internal/logic/calculatecartpricelogic.go @@ -100,7 +100,7 @@ func (l *CalculateCartPriceLogic) CalculateCartPrice(req *types.CalculateCartPri } //开始计算价格 calculateResultList := make([]types.CalculateResultItem, 0, len(req.CalculateList)) - sumPrice := int64(0) + subTotalPrice := int64(0) for _, cart := range carts { sizePrice, ok := mapPrice[fmt.Sprintf("%d_%d", *cart.ProductId, *cart.SizeId)] if !ok { @@ -142,10 +142,10 @@ func (l *CalculateCartPriceLogic) CalculateCartPrice(req *types.CalculateCartPri ItemPrice: fmt.Sprintf("%.3f", format.CentitoDollar(itemPrice)), TotalPrice: fmt.Sprintf("%.3f", format.CentitoDollar(totalPrice)), }) - sumPrice += totalPrice + subTotalPrice += totalPrice } return resp.SetStatusWithMessage(basic.CodeOK, "success", types.CalculateCartPriceRsp{ - SumPrice: fmt.Sprintf("%.3f", format.CentitoDollar(sumPrice)), + SubTotalPrice: fmt.Sprintf("%.3f", format.CentitoDollar(subTotalPrice)), CalculateResultList: calculateResultList, }) } diff --git a/server/shopping-cart/internal/types/types.go b/server/shopping-cart/internal/types/types.go index c8630940..1ed8b661 100644 --- a/server/shopping-cart/internal/types/types.go +++ b/server/shopping-cart/internal/types/types.go @@ -98,7 +98,7 @@ type CalculateItem struct { } type CalculateCartPriceRsp struct { - SumPrice string `json:"sum_price"` + SubTotalPrice string `json:"sub_total_price"` CalculateResultList []CalculateResultItem `json:"calculate_result_list"` } diff --git a/server_api/shopping-cart.api b/server_api/shopping-cart.api index 523e734f..216bdfe2 100644 --- a/server_api/shopping-cart.api +++ b/server_api/shopping-cart.api @@ -111,7 +111,7 @@ type CalculateItem { PurchaseQuantity int64 `json:"purchase_quantity"` //数量 } type CalculateCartPriceRsp { - SumPrice string `json:"sum_price"` + SubTotalPrice string `json:"sub_total_price"` CalculateResultList []CalculateResultItem `json:"calculate_result_list"` } type CalculateResultItem { From 990c7d335992af0649ee42c5c400c4608a63e80f Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Mon, 18 Sep 2023 15:19:42 +0800 Subject: [PATCH 34/59] fix --- server/shopping-cart/internal/logic/calculatecartpricelogic.go | 1 - 1 file changed, 1 deletion(-) diff --git a/server/shopping-cart/internal/logic/calculatecartpricelogic.go b/server/shopping-cart/internal/logic/calculatecartpricelogic.go index 25102872..ce0bfc13 100644 --- a/server/shopping-cart/internal/logic/calculatecartpricelogic.go +++ b/server/shopping-cart/internal/logic/calculatecartpricelogic.go @@ -37,7 +37,6 @@ func NewCalculateCartPriceLogic(ctx context.Context, svcCtx *svc.ServiceContext) // } func (l *CalculateCartPriceLogic) CalculateCartPrice(req *types.CalculateCartPriceReq, userinfo *auth.UserInfo) (resp *basic.Response) { - userinfo.UserId = 39 if !userinfo.IsUser() { return resp.SetStatusWithMessage(basic.CodeUnAuth, "please sign in") } From 826514014837c07c7d5f1889f2d212709610dc42 Mon Sep 17 00:00:00 2001 From: momo <1012651275@qq.com> Date: Mon, 18 Sep 2023 15:39:12 +0800 Subject: [PATCH 35/59] =?UTF-8?q?fix:=E8=B4=AD=E7=89=A9=E8=BD=A6=E4=B8=8B?= =?UTF-8?q?=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- constants/orders.go | 5 +- model/gmodel/fs_order_logic.go | 87 +++----------------- model/gmodel/fs_product_logic.go | 9 +++ model/gmodel/fs_shopping_cart_logic.go | 2 +- service/repositories/order.go | 108 ++++++++++++++++++++++--- utils/order/order.go | 82 ++++++++++++++++--- 6 files changed, 194 insertions(+), 99 deletions(-) diff --git a/constants/orders.go b/constants/orders.go index 7fe2de34..c2bc07b2 100644 --- a/constants/orders.go +++ b/constants/orders.go @@ -8,7 +8,10 @@ const ( ) // 金额单位 -type AmountUnit string +type AmountUnit interface{} + +// 汇率单位 +type ExchangeRateUnit interface{} // 交易方式 type PayMethods string diff --git a/model/gmodel/fs_order_logic.go b/model/gmodel/fs_order_logic.go index 78f82f1d..5cad94b5 100644 --- a/model/gmodel/fs_order_logic.go +++ b/model/gmodel/fs_order_logic.go @@ -59,22 +59,20 @@ type PayInfo struct { // 金额明细 type AmountInfo struct { - ExchangeRate string `json:"exchange_rate"` // 换算汇率 - Change constants.AmountUnit `json:"change,omitempty"` // 变动金额 - ChangeRemark string `json:"change_remark,omitempty"` // 变动备注状态编码 - Currency string `json:"currency"` // 货币 - Current constants.AmountUnit `json:"current"` // 当前金额 - Initiate constants.AmountUnit `json:"initiate"` // 初始金额 + Change AmountCurrency `json:"change,omitempty"` // 变动金额 + ChangeRemark string `json:"change_remark,omitempty"` // 变动备注 + Current AmountCurrency `json:"current"` // 当前金额 + Initiate AmountCurrency `json:"initiate"` // 初始金额 Metadata map[string]interface{} `json:"metadata"` // 额外明细 } // 金额货币 type AmountCurrency struct { - CurrentAmount constants.AmountUnit `json:"current_amount"` // 当前金额 - CurrentCurrency string `json:"current_currency"` // 当前货币 - ExchangeRate string `json:"exchange_rate"` // 换算汇率 - OriginalAmount constants.AmountUnit `json:"original_amount"` // 原始金额 - OriginalCurrency string `json:"original_currency"` // 原始货币 + ExchangeRate constants.ExchangeRateUnit `json:"exchange_rate"` // 换算汇率 + CurrentCurrency string `json:"current_currency"` // 当前货币 + CurrentAmount constants.AmountUnit `json:"current_amount"` // 当前金额 + OriginalCurrency string `json:"original_currency"` // 原始货币 + OriginalAmount constants.AmountUnit `json:"original_amount"` // 原始金额 } // 支付状态 @@ -108,16 +106,16 @@ type OrderStatus struct { // 订单商品 type OrderProduct struct { - Amount AmountCurrency `json:"amount"` // 商品总价 + Amount AmountInfo `json:"amount"` // 商品总价 ExpectedDeliveryTime string `json:"expected_delivery_time"` // 预计到货时间 Number int64 `json:"number"` // 商品数量 - ProductID string `json:"product_id"` // 商品ID + ProductID int64 `json:"product_id"` // 商品ID ProductLogo string `json:"product_logo"` // 商品logo ProductLogoResource *Resource `json:"product_logo_resource"` // 商品封面--资源详情 ProductName string `json:"product_name"` // 商品名称 - ProductPrice AmountCurrency `json:"product_price"` // 商品单价 + ProductPrice AmountInfo `json:"product_price"` // 商品单价 ProductSnapshot map[string]interface{} `json:"product_snapshot"` // 商品快照 - ShoppingCartSnapshot *ShoppingCartSnapshot `json:"shopping_cart_snapshot"` // 购物车快照 + ShoppingCartSnapshot *FsShoppingCart `json:"shopping_cart_snapshot"` // 购物车快照 Unit string `json:"unit"` // 商品单位 } @@ -128,62 +126,3 @@ type Resource struct { ResourceType string `json:"resource_type"` // 资源类型 ResourceURL string `json:"resource_url"` // 资源地址 } - -// 购物车 -type ShoppingCartSnapshot struct { - Ctime string `json:"ctime"` // 创建时间 - FittingID int64 `json:"fitting_id"` // 配件id - ID int64 `json:"id"` // 购物车ID - IsHighlyCustomized int64 `json:"is_highly_customized"` // 是否高度定制 0非 1是(针对客人高度定制只能后台增加如购物车) - ModelID int64 `json:"model_id"` // 模型id - ProductID int64 `json:"product_id"` // 产品id - PurchaseQuantity int64 `json:"purchase_quantity"` // 购买数量 - SizeID int64 `json:"size_id"` // 尺寸id - Snapshot Snapshot `json:"snapshot"` // 购物车快照数据 - TemplateID int64 `json:"template_id"` // 模板id - UserID int64 `json:"user_id"` // 用户id - Utime string `json:"utime"` // 更新时间 -} - -// 购物车快照 -type Snapshot struct { - CombineImage string `json:"combine_image"` // 刀版图地址 - FittingInfo FittingInfo `json:"fitting_info"` - Logo string `json:"logo"` // logo地址 - ModelInfo ModelInfo `json:"model_info"` - RenderImage string `json:"render_image"` // 模板数据 - SizeInfo SizeInfo `json:"size_info"` - TemplateInfo TemplateInfo `json:"template_info"` - UserDiyInformation UserDiyInformation `json:"user_diy_information"` -} - -// 配件信息 -type FittingInfo struct { - FittingJSON string `json:"fitting_json"` -} - -// 模型数据 -type ModelInfo struct { - ModelJSON string `json:"model_json"` -} - -// 尺寸信息 -type SizeInfo struct { - CM string `json:"cm"` - Inch string `json:"inch"` -} - -// 模板数据 -type TemplateInfo struct { - TemplateJSON string `json:"template_json"` - TemplateTag string `json:"template_tag"` -} - -// DIY数据 -type UserDiyInformation struct { - Address string `json:"address"` // 地址 - Phone string `json:"phone"` // 电话 - Qrcode string `json:"qrcode"` // 二维码 - Slogan string `json:"slogan"` // slogan - Website string `json:"website"` // 网站 -} diff --git a/model/gmodel/fs_product_logic.go b/model/gmodel/fs_product_logic.go index dcd6d497..314886c0 100755 --- a/model/gmodel/fs_product_logic.go +++ b/model/gmodel/fs_product_logic.go @@ -2,6 +2,15 @@ package gmodel import "context" +type RelaFsProduct struct { + FsProduct + CoverResource *FsResource `json:"cover_resource" gorm:"foreignkey:cover;references:resource_id"` +} + +func (m *FsProductModel) TableName() string { + return m.name +} + func (p *FsProductModel) FindOne(ctx context.Context, id int64, fields ...string) (resp *FsProduct, err error) { db := p.db.WithContext(ctx).Model(&FsProduct{}).Where("`id` = ? ", id) if len(fields) != 0 { diff --git a/model/gmodel/fs_shopping_cart_logic.go b/model/gmodel/fs_shopping_cart_logic.go index a8184c5d..8f13c0aa 100644 --- a/model/gmodel/fs_shopping_cart_logic.go +++ b/model/gmodel/fs_shopping_cart_logic.go @@ -6,7 +6,7 @@ import ( type RelaFsShoppingCart struct { FsShoppingCart - ShoppingCartProduct *FsProduct `json:"shopping_cart_product" gorm:"foreignkey:product_id;references:id"` + ShoppingCartProduct *RelaFsProduct `json:"shopping_cart_product" gorm:"foreignkey:product_id;references:id"` ShoppingCartProductPriceList []*FsProductPrice `json:"shopping_cart_product_price_list" gorm:"foreignkey:product_id;references:product_id"` ShoppingCartProductModel3dList []*FsProductModel3d `json:"shopping_cart_product_model3d_list" gorm:"foreignkey:product_id;references:product_id"` } diff --git a/service/repositories/order.go b/service/repositories/order.go index b92668b8..fcc76367 100644 --- a/service/repositories/order.go +++ b/service/repositories/order.go @@ -4,8 +4,10 @@ import ( "context" "encoding/json" "errors" + "fmt" "fusenapi/model/gmodel" "fusenapi/utils/basic" + "fusenapi/utils/order" "fusenapi/utils/shopping_cart" "fusenapi/utils/step_price" "math" @@ -33,12 +35,13 @@ type ( /* 下单 */ CreateReq struct { - CurrentCurrency string `json:"current_currency"` // 当前货币 - ExchangeRate string `json:"exchange_rate"` // 换算汇率 - OriginalCurrency string `json:"original_currency"` // 原始货币 - UserId int64 `json:"user_id"` - CartIds []int64 `json:"cart_ids"` - DeliveryMethod string `json:"delivery_method"` + ExpectedDeliveryTime string `json:"expected_delivery_time"` // 预计到货时间 + ExchangeRate int64 `json:"exchange_rate"` // 换算汇率(厘) + CurrentCurrency string `json:"current_currency"` // 当前货币 + OriginalCurrency string `json:"original_currency"` // 原始货币 + UserId int64 `json:"user_id"` + CartIds []int64 `json:"cart_ids"` + DeliveryMethod string `json:"delivery_method"` } CreateRes struct { ErrorCode basic.StatusResponse @@ -53,7 +56,9 @@ func (d *defaultOrder) Create(ctx context.Context, in *CreateReq) (res *CreateRe err = d.MysqlConn.WithContext(ctx).Transaction(func(tx *gorm.DB) error { // 查询购物车 var shoppingCartList []*gmodel.RelaFsShoppingCart - resShoppingCartFind := tx.Preload("ShoppingCartProduct").Preload("ShoppingCartProductPriceList").Preload("ShoppingCartProductModel3dList"). + resShoppingCartFind := tx.Preload("ShoppingCartProduct", func(dbPreload *gorm.DB) *gorm.DB { + return dbPreload.Table(gmodel.NewFsProductModel(tx).TableName()).Preload("CoverResource") + }).Preload("ShoppingCartProductPriceList").Preload("ShoppingCartProductModel3dList"). Where("id IN ?", in.CartIds). Where("user_id = ?", in.UserId). Find(&shoppingCartList) @@ -71,8 +76,29 @@ func (d *defaultOrder) Create(ctx context.Context, in *CreateReq) (res *CreateRe return errors.New(errorCode.Message) } + // 订单商品列表 var orderProductList []*gmodel.OrderProduct + var shippingFee gmodel.AmountInfo + // 订单税费总价(厘) + var shippingFeeTotal int64 + + var tax = gmodel.AmountInfo{} + // 订单邮费总价(厘) + var taxTotal int64 + + var discount gmodel.AmountInfo + // 订单折扣总价(厘) + var discountTotal int64 + + var subtotal gmodel.AmountInfo + // 订单商品总价(厘) + var orderProductTotal int64 + + var total gmodel.AmountInfo + // 订单总价(厘) + var orderTotal int64 + for _, shoppingCart := range shoppingCartList { // 购物车快照 var shoppingCartSnapshot shopping_cart.CartSnapshot @@ -152,16 +178,76 @@ func (d *defaultOrder) Create(ctx context.Context, in *CreateReq) (res *CreateRe } else { json.Unmarshal([]byte(*shoppingCartProductPrice.StepPrice), &stepPrice) } - // 商品单价 + // 商品单价(厘) productPrice := step_price.GetCentStepPrice(int(boxNum), stepNum, stepPrice) - // 商品总价 + // 商品总价(厘) productTotalPrice := productPrice * *shoppingCart.PurchaseQuantity - // 存储订单商品 - orderProductList = append(orderProductList, &gmodel.OrderProduct{}) + // 订单商品总价(厘) + orderProductTotal = orderProductTotal + productTotalPrice + + // 订单商品 + var productLogoResource *gmodel.Resource + if shoppingCart.ShoppingCartProduct.CoverResource != nil { + var coverResourceMetadata map[string]interface{} + if shoppingCart.ShoppingCartProduct.CoverResource.Metadata != nil { + json.Unmarshal(*shoppingCart.ShoppingCartProduct.CoverResource.Metadata, &coverResourceMetadata) + } + productLogoResource = &gmodel.Resource{ + Metadata: coverResourceMetadata, + ResourceID: shoppingCart.ShoppingCartProduct.CoverResource.ResourceId, + ResourceType: *shoppingCart.ShoppingCartProduct.CoverResource.ResourceType, + ResourceURL: *shoppingCart.ShoppingCartProduct.CoverResource.ResourceUrl, + } + } + var productSnapshot = make(map[string]interface{}, 1) + productSnapshot["product_snapshot"] = shoppingCart.ShoppingCartProduct + + orderProductList = append(orderProductList, &gmodel.OrderProduct{ + Amount: order.GetAmountInfo(order.GetAmountInfoReq{ + ExchangeRate: in.ExchangeRate, + Initiate: productTotalPrice, + Current: productTotalPrice, + CurrentCurrency: in.CurrentCurrency, + OriginalCurrency: in.OriginalCurrency, + }), + ExpectedDeliveryTime: in.ExpectedDeliveryTime, + Number: *shoppingCart.PurchaseQuantity, + ProductID: *shoppingCart.ProductId, + ProductLogo: *shoppingCart.ShoppingCartProduct.Cover, + ProductLogoResource: productLogoResource, + ProductName: *shoppingCart.ShoppingCartProduct.Title, + ProductPrice: order.GetAmountInfo(order.GetAmountInfoReq{ + ExchangeRate: in.ExchangeRate, + Initiate: productPrice, + Current: productPrice, + CurrentCurrency: in.CurrentCurrency, + OriginalCurrency: in.OriginalCurrency, + }), + ProductSnapshot: productSnapshot, + ShoppingCartSnapshot: &shoppingCart.FsShoppingCart, + }) } + subtotal = order.GetAmountInfo(order.GetAmountInfoReq{ + ExchangeRate: in.ExchangeRate, + Initiate: orderProductTotal, + Current: orderProductTotal, + CurrentCurrency: in.CurrentCurrency, + OriginalCurrency: in.OriginalCurrency, + }) + + orderTotal = orderProductTotal + shippingFeeTotal + taxTotal - discountTotal + total = order.GetAmountInfo(order.GetAmountInfoReq{ + ExchangeRate: in.ExchangeRate, + Initiate: orderTotal, + Current: orderTotal, + CurrentCurrency: in.CurrentCurrency, + OriginalCurrency: in.OriginalCurrency, + }) + fmt.Println(shippingFee, shippingFeeTotal, tax, taxTotal, discount, discountTotal, subtotal, orderProductTotal, total) + return nil }) if err != nil { diff --git a/utils/order/order.go b/utils/order/order.go index ca040188..20e62d8d 100644 --- a/utils/order/order.go +++ b/utils/order/order.go @@ -1,19 +1,77 @@ package order -type AmountCurrency struct { - ExchangeRate float64 `json:"exchange_rate"` // 换算汇率 - CurrentAmount float64 `json:"current_amount"` // 当前金额 - OriginalAmount float64 `json:"original_amount"` // 原始金额 - CurrentCurrency string `json:"current_currency"` // 当前货币 - OriginalCurrency string `json:"original_currency"` // 原始货币 +import ( + "fusenapi/model/gmodel" +) + +type AmountCurrencyReq struct { + ExchangeRate int64 `json:"exchange_rate"` // 换算汇率 + CurrentAmount int64 `json:"current_amount"` // 当前金额 + OriginalAmount int64 `json:"original_amount"` // 原始金额 + CurrentCurrency string `json:"current_currency"` // 当前货币 + OriginalCurrency string `json:"original_currency"` // 原始货币 } // 汇率换算 -func GetAmountCurrency(req *AmountCurrency) error { - if req.CurrentCurrency == req.OriginalCurrency { - req.CurrentAmount = req.OriginalAmount - } else { - req.CurrentAmount = req.OriginalAmount * req.ExchangeRate +func GetAmountCurrency(req *AmountCurrencyReq) gmodel.AmountCurrency { + if req.CurrentAmount != 0 { + if req.CurrentCurrency == req.OriginalCurrency { + req.CurrentAmount = req.OriginalAmount + } else { + req.CurrentAmount = req.OriginalAmount * req.ExchangeRate + } + } + + return gmodel.AmountCurrency{ + ExchangeRate: req.ExchangeRate, + CurrentAmount: req.CurrentAmount, + OriginalAmount: req.OriginalAmount, + CurrentCurrency: req.CurrentCurrency, + OriginalCurrency: req.OriginalCurrency, + } +} + +type GetAmountInfoReq struct { + ExchangeRate int64 + Initiate int64 + Current int64 + Change int64 + ChangeRemark string + Metadata map[string]interface{} + CurrentCurrency string + OriginalCurrency string +} + +// Change AmountCurrency `json:"change,omitempty"` // 变动金额 +// ChangeRemark string `json:"change_remark,omitempty"` // 变动备注 +// Current AmountCurrency `json:"current"` // 当前金额 +// Initiate AmountCurrency `json:"initiate"` // 初始金额 +// Metadata map[string]interface{} `json:"metadata"` // 额外明细 + +func GetAmountInfo(req GetAmountInfoReq) gmodel.AmountInfo { + return gmodel.AmountInfo{ + Change: GetAmountCurrency(&AmountCurrencyReq{ + ExchangeRate: req.ExchangeRate, + CurrentAmount: req.Change, + OriginalAmount: req.Change, + CurrentCurrency: req.OriginalCurrency, + OriginalCurrency: req.OriginalCurrency, + }), + ChangeRemark: req.ChangeRemark, + Current: GetAmountCurrency(&AmountCurrencyReq{ + ExchangeRate: req.ExchangeRate, + CurrentAmount: req.Current, + OriginalAmount: req.Current, + CurrentCurrency: req.OriginalCurrency, + OriginalCurrency: req.OriginalCurrency, + }), + Initiate: GetAmountCurrency(&AmountCurrencyReq{ + ExchangeRate: req.ExchangeRate, + CurrentAmount: req.Initiate, + OriginalAmount: req.Initiate, + CurrentCurrency: req.OriginalCurrency, + OriginalCurrency: req.OriginalCurrency, + }), + Metadata: req.Metadata, } - return nil } From 832440a58e14aaec7f7fb88f8ce601cce1022527 Mon Sep 17 00:00:00 2001 From: momo <1012651275@qq.com> Date: Mon, 18 Sep 2023 15:40:56 +0800 Subject: [PATCH 36/59] =?UTF-8?q?fix:=E8=B4=AD=E7=89=A9=E8=BD=A6=E4=B8=8B?= =?UTF-8?q?=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- service/repositories/order.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/service/repositories/order.go b/service/repositories/order.go index b9e4f3f5..8a22f5c5 100644 --- a/service/repositories/order.go +++ b/service/repositories/order.go @@ -246,7 +246,7 @@ func (d *defaultOrder) Create(ctx context.Context, in *CreateReq) (res *CreateRe CurrentCurrency: in.CurrentCurrency, OriginalCurrency: in.OriginalCurrency, }) - fmt.Println(shippingFee, shippingFeeTotal, tax, taxTotal, discount, discountTotal, subtotal, orderProductTotal, total) + fmt.Println(orderProductList, shippingFee, shippingFeeTotal, tax, taxTotal, discount, discountTotal, subtotal, orderProductTotal, total) return nil }) From 49cc50ff4e7191199736e660eb7ddd2ed685bf32 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Mon, 18 Sep 2023 15:57:36 +0800 Subject: [PATCH 37/59] fix --- .../logic/getproducttemplatetagslogic.go | 50 +++++++++---------- .../internal/types/types.go | 19 +++++-- server_api/product-template-tag.api | 17 +++++-- 3 files changed, 50 insertions(+), 36 deletions(-) diff --git a/server/product-template-tag/internal/logic/getproducttemplatetagslogic.go b/server/product-template-tag/internal/logic/getproducttemplatetagslogic.go index c0384d90..6563272a 100644 --- a/server/product-template-tag/internal/logic/getproducttemplatetagslogic.go +++ b/server/product-template-tag/internal/logic/getproducttemplatetagslogic.go @@ -54,33 +54,31 @@ func (l *GetProductTemplateTagsLogic) GetProductTemplateTags(req *types.GetProdu logx.Error(err) return } - var colors interface{} + var colors map[string][]types.ColorsItem if logoInfo.Metadata == nil || *logoInfo.Metadata == "" { - // 返回固定模板A1a - productTemplateTags, err = l.svcCtx.AllModels.FsProductTemplateTags.GetListByTagNames(l.ctx, []string{"A1"}, req.Limit, 1, "`id` DESC") - if err != nil { - logx.Error(err) - return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get template tags") - } - } else { - //解析元数据 - var metaData map[string]interface{} - if err = json.Unmarshal([]byte(*logoInfo.Metadata), &metaData); err != nil { - logx.Error(err) - return resp.SetStatusWithMessage(basic.CodeJsonErr, "failed to parse user metadata") - } - colors = metaData["colors"] - var templateTagNameList []string - b, _ := json.Marshal(metaData["template_tagid"]) - if err = json.Unmarshal(b, &templateTagNameList); err != nil { - logx.Error(err) - return resp.SetStatusWithMessage(basic.CodeJsonErr, "invalid format of metadata`s template_tagid") - } - productTemplateTags, err = l.svcCtx.AllModels.FsProductTemplateTags.GetListByTagNames(l.ctx, templateTagNameList, req.Limit, 1, "id DESC") - if err != nil { - logx.Error(err) - return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get template tags") - } + return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "logo info`s metadata is not set") + } + //解析元数据 + var metaData map[string]interface{} + if err = json.Unmarshal([]byte(*logoInfo.Metadata), &metaData); err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeJsonErr, "failed to parse user metadata") + } + b, _ := json.Marshal(metaData["colors"]) + if err = json.Unmarshal(b, &colors); err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeJsonErr, "invalid format of metadata`s colors") + } + var templateTagNameList []string + b, _ = json.Marshal(metaData["template_tagid"]) + if err = json.Unmarshal(b, &templateTagNameList); err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeJsonErr, "invalid format of metadata`s template_tagid") + } + productTemplateTags, err = l.svcCtx.AllModels.FsProductTemplateTags.GetListByTagNames(l.ctx, templateTagNameList, req.Limit, 1, "id DESC") + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get template tags") } //资源id集合 resourceIds := make([]string, 0, 5) diff --git a/server/product-template-tag/internal/types/types.go b/server/product-template-tag/internal/types/types.go index e81cb040..eeca764b 100644 --- a/server/product-template-tag/internal/types/types.go +++ b/server/product-template-tag/internal/types/types.go @@ -10,11 +10,20 @@ type GetProductTemplateTagsReq struct { } type GetProductTemplateTagsRsp struct { - Id int64 `json:"id"` - TemplateTag string `json:"template_tag"` - Cover string `json:"cover"` - CoverMetadata interface{} `json:"cover_metadata"` - Colors interface{} `json:"colors"` + Id int64 `json:"id"` + TemplateTag string `json:"template_tag"` + Cover string `json:"cover"` + CoverMetadata interface{} `json:"cover_metadata"` + Colors map[string][]ColorsItem `json:"colors"` +} + +type ColorsItem struct { + Color []ColorItem `json:"color"` +} + +type ColorItem struct { + Value string `json:"value"` + Selected bool `json:"selected"` } type Request struct { diff --git a/server_api/product-template-tag.api b/server_api/product-template-tag.api index d663e109..94d2d35e 100644 --- a/server_api/product-template-tag.api +++ b/server_api/product-template-tag.api @@ -20,9 +20,16 @@ type GetProductTemplateTagsReq { Limit int `form:"limit"` } type GetProductTemplateTagsRsp { - Id int64 `json:"id"` - TemplateTag string `json:"template_tag"` - Cover string `json:"cover"` - CoverMetadata interface{} `json:"cover_metadata"` - Colors interface{} `json:"colors"` + Id int64 `json:"id"` + TemplateTag string `json:"template_tag"` + Cover string `json:"cover"` + CoverMetadata interface{} `json:"cover_metadata"` + Colors map[string][]ColorsItem `json:"colors"` +} +type ColorsItem { + Color []ColorItem `json:"color"` +} +type ColorItem { + Value string `json:"value"` + Selected bool `json:"selected"` } \ No newline at end of file From 49785df983771f7068df30bac834e1840e3cb80f Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Mon, 18 Sep 2023 17:53:05 +0800 Subject: [PATCH 38/59] fix --- .../logic/getproducttemplatetagslogic.go | 38 +++++++++++++++---- .../internal/types/types.go | 18 ++++----- server_api/product-template-tag.api | 17 ++++----- service/repositories/image_handle.go | 16 +++++--- 4 files changed, 56 insertions(+), 33 deletions(-) diff --git a/server/product-template-tag/internal/logic/getproducttemplatetagslogic.go b/server/product-template-tag/internal/logic/getproducttemplatetagslogic.go index 6563272a..fd123c82 100644 --- a/server/product-template-tag/internal/logic/getproducttemplatetagslogic.go +++ b/server/product-template-tag/internal/logic/getproducttemplatetagslogic.go @@ -36,6 +36,16 @@ func NewGetProductTemplateTagsLogic(ctx context.Context, svcCtx *svc.ServiceCont // func (l *GetProductTemplateTagsLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) { // // httpx.OkJsonCtx(r.Context(), w, resp) // } +type logoSelect struct { + LogoSelected struct { + LogoSelectedId int `json:"logo_selected_id"` + TemplateTagSelected struct { + TemplateTag string `json:"template_tag"` + Color [][]string `json:"color"` + SelectedIndex int `json:"selected_index"` + } `json:"template_tag_selected"` + } `json:"logo_selected"` +} func (l *GetProductTemplateTagsLogic) GetProductTemplateTags(req *types.GetProductTemplateTagsReq, userinfo *auth.UserInfo) (resp *basic.Response) { if req.Limit <= 0 || req.Limit > 100 { @@ -54,7 +64,6 @@ func (l *GetProductTemplateTagsLogic) GetProductTemplateTags(req *types.GetProdu logx.Error(err) return } - var colors map[string][]types.ColorsItem if logoInfo.Metadata == nil || *logoInfo.Metadata == "" { return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "logo info`s metadata is not set") } @@ -64,16 +73,29 @@ func (l *GetProductTemplateTagsLogic) GetProductTemplateTags(req *types.GetProdu logx.Error(err) return resp.SetStatusWithMessage(basic.CodeJsonErr, "failed to parse user metadata") } - b, _ := json.Marshal(metaData["colors"]) - if err = json.Unmarshal(b, &colors); err != nil { + var mapTemplateTag map[string][]types.ColorsItem + b, _ := json.Marshal(metaData["template_tag"]) + if err = json.Unmarshal(b, &mapTemplateTag); err != nil { logx.Error(err) return resp.SetStatusWithMessage(basic.CodeJsonErr, "invalid format of metadata`s colors") } + //获取选中的颜色数据 + if logoInfo.UserInfoMetadata != nil && *logoInfo.UserInfoMetadata != "" { + var logoSelectInfo logoSelect + if err = json.Unmarshal([]byte(*logoInfo.UserInfoMetadata), &logoSelectInfo); err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeJsonErr, "failed to parse user info metadata") + } + //设置选中 + key := logoSelectInfo.LogoSelected.TemplateTagSelected.TemplateTag + index := logoSelectInfo.LogoSelected.TemplateTagSelected.SelectedIndex + if _, ok := mapTemplateTag[key]; ok { + mapTemplateTag[key][index].Selected = true + } + } var templateTagNameList []string - b, _ = json.Marshal(metaData["template_tagid"]) - if err = json.Unmarshal(b, &templateTagNameList); err != nil { - logx.Error(err) - return resp.SetStatusWithMessage(basic.CodeJsonErr, "invalid format of metadata`s template_tagid") + for templateTag, _ := range mapTemplateTag { + templateTagNameList = append(templateTagNameList, templateTag) } productTemplateTags, err = l.svcCtx.AllModels.FsProductTemplateTags.GetListByTagNames(l.ctx, templateTagNameList, req.Limit, 1, "id DESC") if err != nil { @@ -101,6 +123,8 @@ func (l *GetProductTemplateTagsLogic) GetProductTemplateTags(req *types.GetProdu } list := make([]types.GetProductTemplateTagsRsp, 0, len(productTemplateTags)) for _, v := range productTemplateTags { + colors := make([]types.ColorsItem, 0, 10) + colors = append(colors, mapTemplateTag[*v.TemplateTag]...) list = append(list, types.GetProductTemplateTagsRsp{ Id: v.Id, TemplateTag: *v.TemplateTag, diff --git a/server/product-template-tag/internal/types/types.go b/server/product-template-tag/internal/types/types.go index eeca764b..574a34c6 100644 --- a/server/product-template-tag/internal/types/types.go +++ b/server/product-template-tag/internal/types/types.go @@ -10,20 +10,16 @@ type GetProductTemplateTagsReq struct { } type GetProductTemplateTagsRsp struct { - Id int64 `json:"id"` - TemplateTag string `json:"template_tag"` - Cover string `json:"cover"` - CoverMetadata interface{} `json:"cover_metadata"` - Colors map[string][]ColorsItem `json:"colors"` + Id int64 `json:"id"` + TemplateTag string `json:"template_tag"` + Cover string `json:"cover"` + CoverMetadata interface{} `json:"cover_metadata"` + Colors []ColorsItem `json:"colors"` } type ColorsItem struct { - Color []ColorItem `json:"color"` -} - -type ColorItem struct { - Value string `json:"value"` - Selected bool `json:"selected"` + Color []string `json:"color"` + Selected bool `json:"selected"` } type Request struct { diff --git a/server_api/product-template-tag.api b/server_api/product-template-tag.api index 94d2d35e..30329047 100644 --- a/server_api/product-template-tag.api +++ b/server_api/product-template-tag.api @@ -20,16 +20,13 @@ type GetProductTemplateTagsReq { Limit int `form:"limit"` } type GetProductTemplateTagsRsp { - Id int64 `json:"id"` - TemplateTag string `json:"template_tag"` - Cover string `json:"cover"` - CoverMetadata interface{} `json:"cover_metadata"` - Colors map[string][]ColorsItem `json:"colors"` + Id int64 `json:"id"` + TemplateTag string `json:"template_tag"` + Cover string `json:"cover"` + CoverMetadata interface{} `json:"cover_metadata"` + Colors []ColorsItem `json:"colors"` } type ColorsItem { - Color []ColorItem `json:"color"` -} -type ColorItem { - Value string `json:"value"` - Selected bool `json:"selected"` + Color []string `json:"color"` + Selected bool `json:"selected"` } \ No newline at end of file diff --git a/service/repositories/image_handle.go b/service/repositories/image_handle.go index a18c70de..c47f600d 100644 --- a/service/repositories/image_handle.go +++ b/service/repositories/image_handle.go @@ -54,15 +54,16 @@ type ( GuestId int64 `json:"guest_id"` } LogoInfoRes struct { - Metadata *string `json:"metadata"` - LogoUrl *string `json:"logo_url"` + Metadata *string `json:"metadata"` + LogoUrl *string `json:"logo_url"` + UserInfoMetadata *string `json:"user_info_metadata"` } ) func (l *defaultImageHandle) LogoInfo(ctx context.Context, in *LogoInfoReq) (*LogoInfoRes, error) { var metadata *string var logoUrl *string - + var userInfoMetadata *string // 更新用户信息 var module = "profile" userInfoGorm := l.MysqlConn.Where("module = ?", module) @@ -82,6 +83,10 @@ func (l *defaultImageHandle) LogoInfo(ctx context.Context, in *LogoInfoReq) (*Lo return nil, err } } + if userInfo.Id != 0 { + tmp := string(*userInfo.Metadata) + userInfoMetadata = &tmp + } var userMaterialInfo gmodel.FsUserMaterial userMaterialModel := gmodel.NewFsUserMaterialModel(l.MysqlConn) @@ -134,8 +139,9 @@ func (l *defaultImageHandle) LogoInfo(ctx context.Context, in *LogoInfoReq) (*Lo logoUrl = userMaterialInfo.ResourceUrl } return &LogoInfoRes{ - Metadata: metadata, - LogoUrl: logoUrl, + Metadata: metadata, + LogoUrl: logoUrl, + UserInfoMetadata: userInfoMetadata, }, nil } From c12c24d03bf7afae4d4e5ade8b1e97f3c8a37791 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Mon, 18 Sep 2023 18:18:30 +0800 Subject: [PATCH 39/59] fix --- .../logic/getproducttemplatetagslogic.go | 32 +++++++++++++------ 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/server/product-template-tag/internal/logic/getproducttemplatetagslogic.go b/server/product-template-tag/internal/logic/getproducttemplatetagslogic.go index fd123c82..c76f2048 100644 --- a/server/product-template-tag/internal/logic/getproducttemplatetagslogic.go +++ b/server/product-template-tag/internal/logic/getproducttemplatetagslogic.go @@ -48,6 +48,7 @@ type logoSelect struct { } func (l *GetProductTemplateTagsLogic) GetProductTemplateTags(req *types.GetProductTemplateTagsReq, userinfo *auth.UserInfo) (resp *basic.Response) { + userinfo.UserId = 127 if req.Limit <= 0 || req.Limit > 100 { req.Limit = 5 } @@ -73,13 +74,14 @@ func (l *GetProductTemplateTagsLogic) GetProductTemplateTags(req *types.GetProdu logx.Error(err) return resp.SetStatusWithMessage(basic.CodeJsonErr, "failed to parse user metadata") } - var mapTemplateTag map[string][]types.ColorsItem + var mapTemplateTag map[string][][]string b, _ := json.Marshal(metaData["template_tag"]) if err = json.Unmarshal(b, &mapTemplateTag); err != nil { logx.Error(err) - return resp.SetStatusWithMessage(basic.CodeJsonErr, "invalid format of metadata`s colors") + return resp.SetStatusWithMessage(basic.CodeJsonErr, "invalid format of metadata`s template_tag") } //获取选中的颜色数据 + mapSelectColor := make(map[string]int) //key是模板标签val是选中的索引 if logoInfo.UserInfoMetadata != nil && *logoInfo.UserInfoMetadata != "" { var logoSelectInfo logoSelect if err = json.Unmarshal([]byte(*logoInfo.UserInfoMetadata), &logoSelectInfo); err != nil { @@ -88,9 +90,8 @@ func (l *GetProductTemplateTagsLogic) GetProductTemplateTags(req *types.GetProdu } //设置选中 key := logoSelectInfo.LogoSelected.TemplateTagSelected.TemplateTag - index := logoSelectInfo.LogoSelected.TemplateTagSelected.SelectedIndex if _, ok := mapTemplateTag[key]; ok { - mapTemplateTag[key][index].Selected = true + mapSelectColor[key] = logoSelectInfo.LogoSelected.TemplateTagSelected.SelectedIndex } } var templateTagNameList []string @@ -122,14 +123,25 @@ func (l *GetProductTemplateTagsLogic) GetProductTemplateTags(req *types.GetProdu mapResourceMetadata[*v.ResourceUrl] = metadata } list := make([]types.GetProductTemplateTagsRsp, 0, len(productTemplateTags)) - for _, v := range productTemplateTags { + for _, templateInfo := range productTemplateTags { colors := make([]types.ColorsItem, 0, 10) - colors = append(colors, mapTemplateTag[*v.TemplateTag]...) + for index, v := range mapTemplateTag[*templateInfo.TemplateTag] { + selected := false + if selectIndex, ok := mapSelectColor[*templateInfo.TemplateTag]; ok { + if index == selectIndex { + selected = true + } + } + colors = append(colors, types.ColorsItem{ + Color: v, + Selected: selected, + }) + } list = append(list, types.GetProductTemplateTagsRsp{ - Id: v.Id, - TemplateTag: *v.TemplateTag, - Cover: *v.Cover, - CoverMetadata: mapResourceMetadata[*v.Cover], + Id: templateInfo.Id, + TemplateTag: *templateInfo.TemplateTag, + Cover: *templateInfo.Cover, + CoverMetadata: mapResourceMetadata[*templateInfo.Cover], Colors: colors, }) } From beaba9afa9d43d28bb07957502855bc4c84c66f9 Mon Sep 17 00:00:00 2001 From: eson <9673575+githubcontent@user.noreply.gitee.com> Date: Mon, 18 Sep 2023 18:44:12 +0800 Subject: [PATCH 40/59] =?UTF-8?q?=E6=9B=B4=E6=96=B0=20config=20=E6=9C=80?= =?UTF-8?q?=E6=96=B0=E9=85=8D=E7=BD=AE=E6=9C=8D=E5=8A=A1=E4=B8=8A=E5=8E=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 4 +- fs_nacos_etc_pack.sh | 25 +++++++ go.mod | 14 ++++ go.sum | 32 +++++++++ server/auth/internal/logic/websocket_test.go | 2 +- utils/fsconfig/.gitignore | 1 + utils/fsconfig/config.go | 53 +++++++++++++++ utils/fsconfig/config_test.go | 70 ++++++++++++++++++++ 8 files changed, 199 insertions(+), 2 deletions(-) create mode 100755 fs_nacos_etc_pack.sh create mode 100644 utils/fsconfig/.gitignore create mode 100644 utils/fsconfig/config.go create mode 100644 utils/fsconfig/config_test.go diff --git a/.gitignore b/.gitignore index d89fb0f1..2f86e838 100644 --- a/.gitignore +++ b/.gitignore @@ -54,4 +54,6 @@ server/shopping-cart-confirmation/shopping-cart-confirmation server/upload/upload server/webset/webset -shared-state \ No newline at end of file +shared-state + +*.zip \ No newline at end of file diff --git a/fs_nacos_etc_pack.sh b/fs_nacos_etc_pack.sh new file mode 100755 index 00000000..6e8d6fcf --- /dev/null +++ b/fs_nacos_etc_pack.sh @@ -0,0 +1,25 @@ +#!/bin/bash + +CURRENT_DIR=`pwd` +SOURCE_DIR="server" +TEMP_DIR="/tmp" +DEST_DIR="FS-SERVER-API" +ZIP_FILE="FS-SERVER-API.zip" + +mkdir -p $TEMP_DIR/$DEST_DIR + +# 查找并复制文件 +find "$SOURCE_DIR" -type d -name "etc" -exec sh -c 'cp "$0"/*.yaml "$1"' {} "$TEMP_DIR/$DEST_DIR" \; + +cd $TEMP_DIR +# 打包目标文件夹 +zip -r "$ZIP_FILE" "$DEST_DIR" + +#返回当前目录 +cd $CURRENT_DIR + +# 移动到当前目录 +mv "$TEMP_DIR/$ZIP_FILE" . + +# 清理临时文件夹 +rm "$TEMP_DIR/$DEST_DIR" -rf \ No newline at end of file diff --git a/go.mod b/go.mod index 01c94f65..8bf4cb92 100644 --- a/go.mod +++ b/go.mod @@ -14,6 +14,7 @@ require ( github.com/gorilla/websocket v1.5.0 github.com/hashicorp/raft v1.5.0 github.com/lni/dragonboat/v4 v4.0.0-20230709075559-54497b9553be + github.com/nacos-group/nacos-sdk-go/v2 v2.2.3 github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e github.com/streadway/amqp v1.1.0 @@ -31,14 +32,17 @@ require ( github.com/DataDog/zstd v1.4.5 // indirect github.com/HdrHistogram/hdrhistogram-go v1.1.2 // indirect github.com/VictoriaMetrics/metrics v1.18.1 // indirect + github.com/aliyun/alibaba-cloud-sdk-go v1.61.1704 // indirect github.com/andybalholm/brotli v1.0.5 // indirect github.com/armon/go-metrics v0.4.1 // indirect + github.com/buger/jsonparser v1.1.1 // indirect github.com/cockroachdb/errors v1.9.0 // indirect github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f // indirect github.com/cockroachdb/pebble v0.0.0-20221207173255-0f086d933dac // indirect github.com/cockroachdb/redact v1.1.3 // indirect github.com/getsentry/sentry-go v0.12.0 // indirect github.com/gogo/protobuf v1.3.2 // indirect + github.com/golang/mock v1.6.0 // indirect github.com/golang/snappy v0.0.4 // indirect github.com/google/btree v1.0.0 // indirect github.com/hashicorp/errwrap v1.1.0 // indirect @@ -50,12 +54,15 @@ require ( github.com/hashicorp/golang-lru v0.5.1 // indirect github.com/hashicorp/memberlist v0.3.1 // indirect github.com/jmespath/go-jmespath v0.4.0 // indirect + github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/compress v1.15.15 // indirect github.com/kr/pretty v0.3.1 // indirect github.com/kr/text v0.2.0 // indirect github.com/lni/goutils v1.3.1-0.20220604063047-388d67b4dbc4 // indirect github.com/lni/vfs v0.2.1-0.20220616104132-8852fd867376 // indirect github.com/miekg/dns v1.1.26 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect github.com/pierrec/lz4/v4 v4.1.17 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/rogpeppe/go-internal v1.9.0 // indirect @@ -64,11 +71,18 @@ require ( github.com/valyala/fastrand v1.1.0 // indirect github.com/valyala/histogram v1.2.0 // indirect go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.14.0 // indirect + go.uber.org/atomic v1.10.0 // indirect + go.uber.org/multierr v1.9.0 // indirect + go.uber.org/zap v1.24.0 // indirect golang.org/x/crypto v0.11.0 // indirect golang.org/x/exp v0.0.0-20230728194245-b0cb94b80691 // indirect + golang.org/x/sync v0.2.0 // indirect + golang.org/x/time v0.3.0 // indirect google.golang.org/appengine v1.6.7 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20230530153820-e85fd2cbaebc // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20230530153820-e85fd2cbaebc // indirect + gopkg.in/ini.v1 v1.66.2 // indirect + gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect ) require ( diff --git a/go.sum b/go.sum index 67d9f1b0..06dd5c40 100644 --- a/go.sum +++ b/go.sum @@ -41,6 +41,7 @@ github.com/474420502/random v0.4.1 h1:HUUyLXRWMijVb7CJoEC16f0aFQOW25Lkr80Mut6PoK github.com/474420502/requests v1.42.0 h1:aUj0rWhfldbOOlGHDIcqT9zgXEoSlK4IBmRF3LxI1+Y= github.com/474420502/requests v1.42.0/go.mod h1:2SCVzim0ONFYG09g/GrM7RTeJIC6qTyZfnohsjnG5C8= github.com/AndreasBriese/bbloom v0.0.0-20190306092124-e2d15f34fcf9/go.mod h1:bOvUY6CB00SOBii9/FifXqc0awNKxLFCL/+pkDPuyl8= +github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/CloudyKit/fastprinter v0.0.0-20170127035650-74b38d55f37a/go.mod h1:EFZQ978U7x8IRnstaskI3IysnWY5Ao3QgZUKOXlsAdw= @@ -69,6 +70,8 @@ github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRF github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/alicebob/gopher-json v0.0.0-20200520072559-a9ecdc9d1d3a h1:HbKu58rmZpUGpz5+4FfNmIU+FmZg2P3Xaj2v2bfNWmk= github.com/alicebob/miniredis/v2 v2.30.4 h1:8S4/o1/KoUArAGbGwPxcwf0krlzceva2XVOSchFS7Eo= +github.com/aliyun/alibaba-cloud-sdk-go v1.61.1704 h1:PpfENOj/vPfhhy9N2OFRjpue0hjM5XqAp2thFmkXXIk= +github.com/aliyun/alibaba-cloud-sdk-go v1.61.1704/go.mod h1:RcDobYh8k5VP6TNybz9m++gL3ijVI5wueVr0EM10VsU= github.com/andybalholm/brotli v1.0.5 h1:8uQZIdzKmjc/iuPu7O2ioW48L81FgatrcpfFmiq/cCs= github.com/andybalholm/brotli v1.0.5/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig= github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= @@ -79,10 +82,13 @@ github.com/armon/go-metrics v0.4.1/go.mod h1:E6amYzXo6aW1tqzoZGT755KkbgrJsSdpwZ+ github.com/aws/aws-sdk-go v1.44.295 h1:SGjU1+MqttXfRiWHD6WU0DRhaanJgAFY+xIhEaugV8Y= github.com/aws/aws-sdk-go v1.44.295/go.mod h1:aVsgQcEevwlmQ7qHE9I3h+dtQgpqhFB+i8Phjh7fkwI= github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= +github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= +github.com/buger/jsonparser v1.1.1 h1:2PnMjfWD7wBILjqQbt530v576A/cAbQvEW9gGIpYMUs= +github.com/buger/jsonparser v1.1.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0= github.com/bwmarrin/snowflake v0.3.0 h1:xm67bEhkKh6ij1790JB83OujPR5CzNe8QuQqAgISZN0= github.com/bwmarrin/snowflake v0.3.0/go.mod h1:NdZxfVWX+oR6y2K0o6qAYv6gIOP9rjG0/E9WsDpxqwE= github.com/cenkalti/backoff/v4 v4.2.0 h1:HN5dHm3WBOgndBH6E8V0q2jIYIR3s9yglV8k/+MN3u4= @@ -202,6 +208,7 @@ github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXP github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= github.com/gogo/status v1.1.0/go.mod h1:BFv9nrluPLmrS0EmGVvLaPNmRosr9KapBYd5/hpY1WM= +github.com/goji/httpauth v0.0.0-20160601135302-2da839ab0f4d/go.mod h1:nnjvkQ9ptGaCkuDUx6wNykzzlUixGxvkme+H/lnzb+A= github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY= github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I= github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOWzg= @@ -220,6 +227,8 @@ github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt github.com/golang/mock v1.4.1/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= +github.com/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc= +github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= @@ -330,12 +339,16 @@ github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGwWFoC7ycTf1rcQZHOlsJ6N8= github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= +github.com/json-iterator/go v1.1.5/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= @@ -413,11 +426,16 @@ github.com/miekg/dns v1.1.26/go.mod h1:bPDLeHnStXmXAq1m/Ch/hvfNHr14JKNPMBo3VZKju github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/moul/http2curl v1.0.0/go.mod h1:8UbvGypXm98wA/IqH45anm5Y2Z6ep6O31QGOAZ3H0fQ= github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/nacos-group/nacos-sdk-go/v2 v2.2.3 h1:sUQx4f1bXDeeOOEQZjGAitzxYApbYY9fVDbxVCaBW+I= +github.com/nacos-group/nacos-sdk-go/v2 v2.2.3/go.mod h1:UL4U89WYdnyajgKJUMpuT1Rr6iNmbjrxOO40JRgtA00= github.com/nats-io/jwt v0.3.0/go.mod h1:fRYCDE99xlTsqUzISS1Bi75UBJ6ljOJQOAAu5VglpSg= github.com/nats-io/nats.go v1.8.1/go.mod h1:BrFz9vVn0fU3AcH9Vn4Kd7W0NpJ651tD5omQ3M8LwxM= github.com/nats-io/nats.go v1.9.1/go.mod h1:ZjDU1L/7fJ09jvUSRVBR2e7+RnLiiIQyqyzEE/Zbp4w= @@ -598,9 +616,15 @@ go.opentelemetry.io/otel/trace v1.14.0/go.mod h1:8avnQLK+CG77yNLUae4ea2JDQ6iT+go go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI= go.opentelemetry.io/proto/otlp v0.19.0 h1:IVN6GR+mhC4s5yfcTbmzHYODqvWAp3ZedA2SJPI1Nnw= go.opentelemetry.io/proto/otlp v0.19.0/go.mod h1:H7XAot3MsfNsj7EXtrA2q5xSNQ10UqI405h3+duxN4U= +go.uber.org/atomic v1.10.0 h1:9qC72Qh0+3MqyJbAn8YU5xVq1frD8bn3JtD2oXtafVQ= +go.uber.org/atomic v1.10.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.uber.org/automaxprocs v1.5.2 h1:2LxUOGiR3O6tw8ui5sZa2LAaHnsviZdVOUZw4fvbnME= go.uber.org/automaxprocs v1.5.2/go.mod h1:eRbA25aqJrxAbsLO0xy5jVwPt7FQnRgjW+efnwa1WM0= go.uber.org/goleak v1.2.1 h1:NBol2c7O1ZokfZ0LEU9K6Whx/KnwvepVetCUhtKja4A= +go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI= +go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTVQ= +go.uber.org/zap v1.24.0 h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60= +go.uber.org/zap v1.24.0/go.mod h1:2kMP+WWQ8aoFoedH3T2sq6iJ2yDWpHbP0f6MQbS9Gkg= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= @@ -721,6 +745,7 @@ golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.2.0 h1:PUR+T4wwASmuSTYdKjYHI5TD22Wy5ogLU5qZCOLxBrI= +golang.org/x/sync v0.2.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -798,6 +823,8 @@ golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxb golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20201208040808-7e3f01d25324/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4= +golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180525024113-a5b4c53f6e8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -847,6 +874,7 @@ golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -969,7 +997,11 @@ gopkg.in/go-playground/assert.v1 v1.2.1/go.mod h1:9RXL0bg/zibRAgZUYszZSwO/z8Y/a8 gopkg.in/go-playground/validator.v8 v8.18.2/go.mod h1:RX2a/7Ha8BgOhfk7j780h4/u/RRjR0eouCJSH80/M2Y= gopkg.in/h2non/gock.v1 v1.1.2 h1:jBbHXgGBK/AoPVfJh5x4r/WxIrElvbLel8TCZkkZJoY= gopkg.in/ini.v1 v1.51.1/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +gopkg.in/ini.v1 v1.66.2 h1:XfR1dOYubytKy4Shzc2LHrrGhU0lDCfDGG1yLPmpgsI= +gopkg.in/ini.v1 v1.66.2/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/mgo.v2 v2.0.0-20180705113604-9856a29383ce/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA= +gopkg.in/natefinch/lumberjack.v2 v2.0.0 h1:1Lc07Kr7qY4U2YPouBjpCLxpiyxIVoxqXgkXLknAOE8= +gopkg.in/natefinch/lumberjack.v2 v2.0.0/go.mod h1:l0ndWWf7gzL7RNwBG7wST/UCcT4T24xpD6X8LsfU/+k= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/server/auth/internal/logic/websocket_test.go b/server/auth/internal/logic/websocket_test.go index c74a5736..17f6ba2a 100644 --- a/server/auth/internal/logic/websocket_test.go +++ b/server/auth/internal/logic/websocket_test.go @@ -143,7 +143,7 @@ func TestSql(t *testing.T) { } conn := initalize.InitMysql("fsreaderwriter:XErSYmLELKMnf3Dh@tcp(fusen.cdmigcvz3rle.us-east-2.rds.amazonaws.com:3306)/fusen") - log.Println(conn.Model(&gmodel.FsUser{})) + log.Println() log.Println(conn.NamingStrategy.TableName(reflect.TypeOf(gmodel.FsUser{}).Name())) updatesql := `UPDATE %s diff --git a/utils/fsconfig/.gitignore b/utils/fsconfig/.gitignore new file mode 100644 index 00000000..fbf828d6 --- /dev/null +++ b/utils/fsconfig/.gitignore @@ -0,0 +1 @@ +log \ No newline at end of file diff --git a/utils/fsconfig/config.go b/utils/fsconfig/config.go new file mode 100644 index 00000000..116043dc --- /dev/null +++ b/utils/fsconfig/config.go @@ -0,0 +1,53 @@ +package fsconfig + +import ( + "fmt" + "log" + "os" + + "gopkg.in/yaml.v2" +) + +type EnvConfig struct { + Host string `yaml:"host"` + Port uint64 `yaml:"port"` + + UserName string `yaml:"username"` + Password string `yaml:"password"` + NamespaceId string `yaml:"namespace"` + DataId string `yaml:"dataid"` + Group string `yaml:"group"` +} + +var OptPathDir = "/opt" + +var nacosConfig *EnvConfig + +func GetEnvCofing() *EnvConfig { + return nacosConfig +} + +func init() { + if OptPathDir[len(OptPathDir)-1] != '/' { + OptPathDir = OptPathDir + "/" + } + + for _, yname := range []string{"env.yaml", "env.yml"} { + f, err := os.Open(OptPathDir + "/" + yname) + if err != nil { + log.Println(err) + continue + } + cfg := &EnvConfig{} + err = yaml.NewDecoder(f).Decode(&cfg) + if err != nil { + log.Println(err) + continue + } + + nacosConfig = cfg + return + } + + panic(fmt.Sprintf("can't find %s(env.yaml|env.yml) ", OptPathDir)) +} diff --git a/utils/fsconfig/config_test.go b/utils/fsconfig/config_test.go new file mode 100644 index 00000000..f285c6bb --- /dev/null +++ b/utils/fsconfig/config_test.go @@ -0,0 +1,70 @@ +package fsconfig_test + +import ( + "fusenapi/utils/fsconfig" + "log" + "testing" + + "github.com/nacos-group/nacos-sdk-go/v2/clients" + "github.com/nacos-group/nacos-sdk-go/v2/common/constant" + "github.com/nacos-group/nacos-sdk-go/v2/vo" +) + +func TestCase1(t *testing.T) { + + env := fsconfig.GetEnvCofing() + + // 创建serverConfig + // 支持多个;至少一个ServerConfig + serverConfig := []constant.ServerConfig{ + { + IpAddr: env.Host, + Port: uint64(env.Port), + }, + } + + // 创建clientConfig + clientConfig := constant.ClientConfig{ + NamespaceId: env.NamespaceId, // 如果需要支持多namespace,我们可以场景多个client,它们有不同的NamespaceId。当namespace是public时,此处填空字符串。 + TimeoutMs: 50000, + NotLoadCacheAtStart: true, + LogLevel: "debug", + LogDir: "/tmp/nacos", + CacheDir: "/tmp/nacos", + Username: env.UserName, + Password: env.Password, + } + + // 创建服务发现客户端的另一种方式 (推荐) + // namingClient, err := clients.NewNamingClient( + // vo.NacosClientParam{ + // ClientConfig: &clientConfig, + // ServerConfigs: serverConfig, + // }, + // ) + // if err != nil { + // log.Fatalf("初始化nacos失败: %s", err.Error()) + // } + + // log.Println(namingClient) + + // 创建 Nacos 配置客户端 + configClient, err := clients.CreateConfigClient(map[string]interface{}{ + "clientConfig": clientConfig, + "serverConfigs": serverConfig, + }) + if err != nil { + log.Fatalf("Failed to create Nacos config client: %v", err) + } + + // 获取配置 + content, err := configClient.GetConfig(vo.ConfigParam{ + DataId: "auth.yaml", + Group: env.Group, + }) + if err != nil { + log.Fatalf("Failed to get config from Nacos: %v", err) + } + log.Println(content) + +} From f82f8b0d24dfb0ed64d39cd84e2098ecab36ee8c Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Mon, 18 Sep 2023 18:46:18 +0800 Subject: [PATCH 41/59] fix --- .../internal/logic/ws_render_image.go | 7 ++++- utils/websocket_data/render_data.go | 27 +++++++++++-------- 2 files changed, 22 insertions(+), 12 deletions(-) diff --git a/server/websocket/internal/logic/ws_render_image.go b/server/websocket/internal/logic/ws_render_image.go index 3b1f6c28..39bb7fbf 100644 --- a/server/websocket/internal/logic/ws_render_image.go +++ b/server/websocket/internal/logic/ws_render_image.go @@ -96,10 +96,15 @@ func (w *wsConnectItem) renderImage(data []byte) { //logx.Info("消费渲染数据:", string(data)) var renderImageData websocket_data.RenderImageReqMsg if err := json.Unmarshal(data, &renderImageData); err != nil { - w.incomeDataFormatErrResponse("invalid format of render data:" + string(data)) + w.renderErrResponse("", "", "", "数据格式错误", 0, 0, 0, 0, 0, 0, 0) logx.Error("invalid format of websocket render image message", err) return } + lenColor := len(renderImageData.RenderData.TemplateTagColor.Color) + if renderImageData.RenderData.TemplateTagColor.SelectedIndex >= lenColor || lenColor == 0 { + w.renderErrResponse("", "", "", "请传入模板标签选择的颜色", 0, 0, 0, 0, 0, 0, 0) + return + } //获取产品信息(部分字段) productInfo, err := w.logic.svcCtx.AllModels.FsProduct.FindOne(w.logic.ctx, renderImageData.RenderData.ProductId, "id,is_customization") if err != nil { diff --git a/utils/websocket_data/render_data.go b/utils/websocket_data/render_data.go index 16f3326b..d79032d5 100644 --- a/utils/websocket_data/render_data.go +++ b/utils/websocket_data/render_data.go @@ -15,17 +15,22 @@ type RenderImageReqMsg struct { RenderData RenderData `json:"render_data"` } type RenderData struct { - TemplateTag string `json:"template_tag"` //模板标签(必须) - ProductId int64 `json:"product_id"` //产品id(必须) - Website string `json:"website"` //网站(可选) - Slogan string `json:"slogan"` //slogan(可选) - Address string `json:"address"` //地址(可选) - Phone string `json:"phone"` //电话(可选) - Qrcode string `json:"qrcode"` //二维码(可选) - ProductSizeId int64 `json:"product_size_id"` //尺寸id(可选) - UserId int64 `json:"user_id"` //用户id(websocket连接建立再赋值) - GuestId int64 `json:"guest_id"` //游客id(websocket连接建立再赋值) - Logo string `json:"logo"` //log资源地址(websocket连接建立再赋值) + TemplateTag string `json:"template_tag"` //模板标签(必须) + TemplateTagColor TemplateTagColor `json:"template_tag_color"` //模板标签组合颜色 + ProductId int64 `json:"product_id"` //产品id(必须) + Website string `json:"website"` //网站(可选) + Slogan string `json:"slogan"` //slogan(可选) + Address string `json:"address"` //地址(可选) + Phone string `json:"phone"` //电话(可选) + Qrcode string `json:"qrcode"` //二维码(可选) + ProductSizeId int64 `json:"product_size_id"` //尺寸id(可选) + UserId int64 `json:"user_id"` //用户id(websocket连接建立再赋值) + GuestId int64 `json:"guest_id"` //游客id(websocket连接建立再赋值) + Logo string `json:"logo"` //log资源地址(websocket连接建立再赋值) +} +type TemplateTagColor struct { + Color [][]string `json:"color"` //颜色组合 + SelectedIndex int `json:"selected_index"` //主色的下标索引 } // websocket发送渲染完的数据 From 573a199878ce839951e9ca577d6f00d4b413ba17 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Mon, 18 Sep 2023 18:57:37 +0800 Subject: [PATCH 42/59] fix --- service/repositories/image_handle.go | 29 ++++++++++++++++++---------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/service/repositories/image_handle.go b/service/repositories/image_handle.go index c47f600d..fa71fbd4 100644 --- a/service/repositories/image_handle.go +++ b/service/repositories/image_handle.go @@ -187,16 +187,17 @@ func (l *defaultImageHandle) LogoInfoSet(ctx context.Context, in *LogoInfoSetReq /* logo合图 */ type ( LogoCombineReq struct { - UserId int64 `json:"user_id"` - GuestId int64 `json:"guest_id"` - TemplateId int64 `json:"template_id"` - TemplateTag string `json:"template_tag"` - Website string `json:"website"` // 合图参数 - Slogan string `json:"slogan"` // 合图参数 - Address string `json:"address"` // 合图参数 - Phone string `json:"phone"` // 合图参数 - Qrcode string `json:"qrcode"` // 合图参数 - LogoUrl string `json:"logo_url"` // 合图参数 + UserId int64 `json:"user_id"` + GuestId int64 `json:"guest_id"` + TemplateId int64 `json:"template_id"` + TemplateTag string `json:"template_tag"` + Website string `json:"website"` // 合图参数 + Slogan string `json:"slogan"` // 合图参数 + Address string `json:"address"` // 合图参数 + Phone string `json:"phone"` // 合图参数 + Qrcode string `json:"qrcode"` // 合图参数 + LogoUrl string `json:"logo_url"` // 合图参数 + TemplateTagColor TemplateTagColor `json:"template_tag_color"` } LogoCombineRes struct { ResourceId string @@ -206,6 +207,10 @@ type ( DiffTimeUploadFile int64 } ) +type TemplateTagColor struct { + Color [][]string `json:"color"` + Index int `json:"index"` +} func (l *defaultImageHandle) LogoCombine(ctx context.Context, in *LogoCombineReq) (*LogoCombineRes, error) { // 查询logo最新基础信息 @@ -308,6 +313,10 @@ func (l *defaultImageHandle) LogoCombine(ctx context.Context, in *LogoCombineReq combineParam["phone"] = in.Phone combineParam["address"] = in.Address combineParam["qrcode"] = in.Qrcode + combineParam["template_tag_selected"] = map[string]interface{}{ + "template_tag": in.TemplateTag, + "color": in.TemplateTagColor, + } var postMap = make(map[string]interface{}, 2) postMap["module_data"] = moduleDataMap From 389794500f35d38c0b7b1e39e885cb0bc2ab2ccb Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Mon, 18 Sep 2023 18:59:29 +0800 Subject: [PATCH 43/59] fix --- server/websocket/internal/logic/ws_render_image.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/server/websocket/internal/logic/ws_render_image.go b/server/websocket/internal/logic/ws_render_image.go index 39bb7fbf..85ff5572 100644 --- a/server/websocket/internal/logic/ws_render_image.go +++ b/server/websocket/internal/logic/ws_render_image.go @@ -197,6 +197,10 @@ func (w *wsConnectItem) renderImage(data []byte) { Phone: renderImageData.RenderData.Phone, Qrcode: renderImageData.RenderData.Qrcode, LogoUrl: renderImageData.RenderData.Logo, + TemplateTagColor: repositories.TemplateTagColor{ + Color: renderImageData.RenderData.TemplateTagColor.Color, + Index: renderImageData.RenderData.TemplateTagColor.SelectedIndex, + }, } res, err := w.logic.svcCtx.Repositories.ImageHandle.LogoCombine(w.logic.ctx, &combineReq) if err != nil { From bdef106f091560f8394140ac0034598fcefce197 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Mon, 18 Sep 2023 19:03:52 +0800 Subject: [PATCH 44/59] fix --- server/websocket/internal/logic/ws_render_image.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/server/websocket/internal/logic/ws_render_image.go b/server/websocket/internal/logic/ws_render_image.go index 85ff5572..6793528c 100644 --- a/server/websocket/internal/logic/ws_render_image.go +++ b/server/websocket/internal/logic/ws_render_image.go @@ -96,13 +96,13 @@ func (w *wsConnectItem) renderImage(data []byte) { //logx.Info("消费渲染数据:", string(data)) var renderImageData websocket_data.RenderImageReqMsg if err := json.Unmarshal(data, &renderImageData); err != nil { - w.renderErrResponse("", "", "", "数据格式错误", 0, 0, 0, 0, 0, 0, 0) + w.renderErrResponse(renderImageData.RenderId, renderImageData.RenderData.TemplateTag, "", "数据格式错误", renderImageData.RenderData.ProductId, w.userId, w.guestId, 0, 0, 0, 0) logx.Error("invalid format of websocket render image message", err) return } lenColor := len(renderImageData.RenderData.TemplateTagColor.Color) if renderImageData.RenderData.TemplateTagColor.SelectedIndex >= lenColor || lenColor == 0 { - w.renderErrResponse("", "", "", "请传入模板标签选择的颜色", 0, 0, 0, 0, 0, 0, 0) + w.renderErrResponse(renderImageData.RenderId, renderImageData.RenderData.TemplateTag, "", "请传入模板标签选择的颜色", renderImageData.RenderData.ProductId, w.userId, w.guestId, 0, 0, 0, 0) return } //获取产品信息(部分字段) From 3de3d896e8584a699f4f26bb1a79765d8fbdd917 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Mon, 18 Sep 2023 19:06:46 +0800 Subject: [PATCH 45/59] fix --- server/websocket/internal/logic/ws_render_image.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/server/websocket/internal/logic/ws_render_image.go b/server/websocket/internal/logic/ws_render_image.go index 6793528c..6ce69165 100644 --- a/server/websocket/internal/logic/ws_render_image.go +++ b/server/websocket/internal/logic/ws_render_image.go @@ -101,10 +101,14 @@ func (w *wsConnectItem) renderImage(data []byte) { return } lenColor := len(renderImageData.RenderData.TemplateTagColor.Color) - if renderImageData.RenderData.TemplateTagColor.SelectedIndex >= lenColor || lenColor == 0 { + if lenColor == 0 { w.renderErrResponse(renderImageData.RenderId, renderImageData.RenderData.TemplateTag, "", "请传入模板标签选择的颜色", renderImageData.RenderData.ProductId, w.userId, w.guestId, 0, 0, 0, 0) return } + if renderImageData.RenderData.TemplateTagColor.SelectedIndex >= lenColor || renderImageData.RenderData.TemplateTagColor.SelectedIndex < 0 { + w.renderErrResponse(renderImageData.RenderId, renderImageData.RenderData.TemplateTag, "", "选择的模板标签颜色索引越界", renderImageData.RenderData.ProductId, w.userId, w.guestId, 0, 0, 0, 0) + return + } //获取产品信息(部分字段) productInfo, err := w.logic.svcCtx.AllModels.FsProduct.FindOne(w.logic.ctx, renderImageData.RenderData.ProductId, "id,is_customization") if err != nil { From 157f05e43d36b90790f24c2950a1a0190b3719e9 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Tue, 19 Sep 2023 10:04:35 +0800 Subject: [PATCH 46/59] fix --- goctl_template/api/etc.tpl | 2 +- server/base/etc/base.yaml | 2 +- server/info/etc/info.yaml | 2 +- server/resource/etc/resource.yaml | 2 +- server/shopping-cart/etc/shopping-cart.yaml | 2 +- server/websocket/etc/websocket.yaml | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/goctl_template/api/etc.tpl b/goctl_template/api/etc.tpl index 86e74e0a..c2409e1f 100644 --- a/goctl_template/api/etc.tpl +++ b/goctl_template/api/etc.tpl @@ -3,7 +3,7 @@ Host: {{.host}} Port: {{.port}} Timeout: 15000 #服务超时时间(毫秒) SourceMysql: fsreaderwriter:XErSYmLELKMnf3Dh@tcp(fusen.cdmigcvz3rle.us-east-2.rds.amazonaws.com:3306)/fusen -SourceRabbitMq: amqp://rabbit001:rabbit001129@110.41.19.98:5672 +SourceRabbitMq: "" Auth: AccessSecret: fusen2023 AccessExpire: 2592000 diff --git a/server/base/etc/base.yaml b/server/base/etc/base.yaml index 4de0596c..36054478 100644 --- a/server/base/etc/base.yaml +++ b/server/base/etc/base.yaml @@ -10,4 +10,4 @@ Auth: AccessSecret: fusen2023 AccessExpire: 2592000 RefreshAfter: 1592000 -SourceRabbitMq: "amqp://rabbit001:rabbit001129@110.41.19.98:5672" \ No newline at end of file +SourceRabbitMq: "" \ No newline at end of file diff --git a/server/info/etc/info.yaml b/server/info/etc/info.yaml index 24d7b2ad..3fa5aea3 100644 --- a/server/info/etc/info.yaml +++ b/server/info/etc/info.yaml @@ -4,7 +4,7 @@ Port: 9988 Timeout: 15000 #服务超时时间(毫秒) ReplicaId: 200 SourceMysql: fsreaderwriter:XErSYmLELKMnf3Dh@tcp(fusen.cdmigcvz3rle.us-east-2.rds.amazonaws.com:3306)/fusen -SourceRabbitMq: amqp://rabbit001:rabbit001129@110.41.19.98:5672 +SourceRabbitMq: Log: Stat: false Auth: diff --git a/server/resource/etc/resource.yaml b/server/resource/etc/resource.yaml index e03a9f70..3353fd9f 100644 --- a/server/resource/etc/resource.yaml +++ b/server/resource/etc/resource.yaml @@ -10,7 +10,7 @@ Auth: AccessSecret: fusen2023 AccessExpire: 2592000 RefreshAfter: 1592000 -SourceRabbitMq: "amqp://rabbit001:rabbit001129@110.41.19.98:5672" +SourceRabbitMq: "" AWS: S3: Credentials: diff --git a/server/shopping-cart/etc/shopping-cart.yaml b/server/shopping-cart/etc/shopping-cart.yaml index 2b0db3dd..2fb861be 100644 --- a/server/shopping-cart/etc/shopping-cart.yaml +++ b/server/shopping-cart/etc/shopping-cart.yaml @@ -3,7 +3,7 @@ Host: 0.0.0.0 Port: 9918 Timeout: 15000 #服务超时时间(毫秒) SourceMysql: fsreaderwriter:XErSYmLELKMnf3Dh@tcp(fusen.cdmigcvz3rle.us-east-2.rds.amazonaws.com:3306)/fusen -SourceRabbitMq: amqp://rabbit001:rabbit001129@110.41.19.98:5672 +SourceRabbitMq: Log: Stat: false Auth: diff --git a/server/websocket/etc/websocket.yaml b/server/websocket/etc/websocket.yaml index e7b4197d..85f9ed0b 100644 --- a/server/websocket/etc/websocket.yaml +++ b/server/websocket/etc/websocket.yaml @@ -12,7 +12,7 @@ Auth: AccessSecret: fusen2023 AccessExpire: 2592000 RefreshAfter: 1592000 -SourceRabbitMq: "amqp://rabbit001:rabbit001129@110.41.19.98:5672" +SourceRabbitMq: "" AWS: S3: Credentials: From 498f4550f095ce8375252b9a295e11b8299b9bca Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Tue, 19 Sep 2023 10:09:22 +0800 Subject: [PATCH 47/59] fix --- .../websocket/internal/logic/ws_allocation_processing_factory.go | 1 + 1 file changed, 1 insertion(+) diff --git a/server/websocket/internal/logic/ws_allocation_processing_factory.go b/server/websocket/internal/logic/ws_allocation_processing_factory.go index 18cce02b..68cf7e49 100644 --- a/server/websocket/internal/logic/ws_allocation_processing_factory.go +++ b/server/websocket/internal/logic/ws_allocation_processing_factory.go @@ -6,6 +6,7 @@ import ( // 消息分发工厂 type allocationProcessorFactory interface { + //分配数据到缓冲队列 allocationMessage(w *wsConnectItem, data []byte) } From 34befce2f3e5d57ce4f85a29b74fb0087302d431 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Tue, 19 Sep 2023 10:18:17 +0800 Subject: [PATCH 48/59] fix --- .../websocket/internal/logic/datatransferlogic.go | 6 +++--- server/websocket/internal/logic/ws_render_image.go | 14 +++++++------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/server/websocket/internal/logic/datatransferlogic.go b/server/websocket/internal/logic/datatransferlogic.go index 9c7f1548..65a3121c 100644 --- a/server/websocket/internal/logic/datatransferlogic.go +++ b/server/websocket/internal/logic/datatransferlogic.go @@ -195,9 +195,9 @@ func (l *DataTransferLogic) setConnPool(conn *websocket.Conn, userInfo *auth.Use guestId: userInfo.GuestId, extendRenderProperty: extendRenderProperty{ //renderImageTask: make(map[string]*renderTask), - renderImageTaskCtlChan: make(chan renderImageControlChanItem, renderImageTaskCtlChanLen), - renderChan: make(chan []byte, renderChanLen), - renderConsumeTickTime: 1, //默认1纳秒,后面需要根据不同用户不同触发速度 + //renderImageTaskCtlChan: make(chan renderImageControlChanItem, renderImageTaskCtlChanLen), + renderChan: make(chan []byte, renderChanLen), + renderConsumeTickTime: 1, //默认1纳秒,后面需要根据不同用户不同触发速度 }, } //保存连接 diff --git a/server/websocket/internal/logic/ws_render_image.go b/server/websocket/internal/logic/ws_render_image.go index 6ce69165..c8fdcd25 100644 --- a/server/websocket/internal/logic/ws_render_image.go +++ b/server/websocket/internal/logic/ws_render_image.go @@ -33,27 +33,27 @@ type renderProcessor struct { // 云渲染属性 type extendRenderProperty struct { //renderImageTask map[string]*renderTask //需要渲染的图片任务 key是taskId val 是renderId - renderImageTaskCtlChan chan renderImageControlChanItem //渲染任务新增/回调结果移除任务/更新渲染耗时属性的控制通道(由于任务map无法读写并发) - renderChan chan []byte //渲染消息入口的缓冲队列 - renderConsumeTickTime time.Duration //消费渲染消息时钟间隔(纳秒),用于后期控制不同类型用户渲染速度限制 + //renderImageTaskCtlChan chan renderImageControlChanItem //渲染任务新增/回调结果移除任务/更新渲染耗时属性的控制通道(由于任务map无法读写并发) + renderChan chan []byte //渲染消息入口的缓冲队列 + renderConsumeTickTime time.Duration //消费渲染消息时钟间隔(纳秒),用于后期控制不同类型用户渲染速度限制 } // 渲染任务新增移除的控制通道的数据 -type renderImageControlChanItem struct { +/*type renderImageControlChanItem struct { option int // 0删除 1添加 2修改耗时属性 taskId string //map的key(必须传) renderId string // map的val(增加任务时候传) renderNotifyImageUrl string //渲染回调数据(删除任务时候传) taskProperty renderTask //渲染任务的属性 -} +}*/ // 渲染任务属性 -type renderTask struct { +/*type renderTask struct { renderId string //渲染id(新增任务传) unityRenderBeginTime int64 //发送给unity时间 unityRenderEndTime int64 //unity回调结果时间 uploadUnityRenderImageTakesTime int64 //上传unity渲染结果图时间 -} +}*/ // 处理分发到这里的数据 func (r *renderProcessor) allocationMessage(w *wsConnectItem, data []byte) { From 19958a80de9ce37b6daed0dc251eb4cc32231d43 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Tue, 19 Sep 2023 10:36:33 +0800 Subject: [PATCH 49/59] fix --- .../internal/logic/getproducttemplatetagslogic.go | 12 +++++------- server/product-template-tag/internal/types/types.go | 4 ++-- server_api/product-template-tag.api | 4 ++-- 3 files changed, 9 insertions(+), 11 deletions(-) diff --git a/server/product-template-tag/internal/logic/getproducttemplatetagslogic.go b/server/product-template-tag/internal/logic/getproducttemplatetagslogic.go index c76f2048..351fce2b 100644 --- a/server/product-template-tag/internal/logic/getproducttemplatetagslogic.go +++ b/server/product-template-tag/internal/logic/getproducttemplatetagslogic.go @@ -125,16 +125,13 @@ func (l *GetProductTemplateTagsLogic) GetProductTemplateTags(req *types.GetProdu list := make([]types.GetProductTemplateTagsRsp, 0, len(productTemplateTags)) for _, templateInfo := range productTemplateTags { colors := make([]types.ColorsItem, 0, 10) - for index, v := range mapTemplateTag[*templateInfo.TemplateTag] { - selected := false + SelectedIndex := 0 + for _, colorsSet := range mapTemplateTag[*templateInfo.TemplateTag] { if selectIndex, ok := mapSelectColor[*templateInfo.TemplateTag]; ok { - if index == selectIndex { - selected = true - } + SelectedIndex = selectIndex } colors = append(colors, types.ColorsItem{ - Color: v, - Selected: selected, + Color: colorsSet, }) } list = append(list, types.GetProductTemplateTagsRsp{ @@ -143,6 +140,7 @@ func (l *GetProductTemplateTagsLogic) GetProductTemplateTags(req *types.GetProdu Cover: *templateInfo.Cover, CoverMetadata: mapResourceMetadata[*templateInfo.Cover], Colors: colors, + SelectedIndex: SelectedIndex, }) } return resp.SetStatusWithMessage(basic.CodeOK, "success", list) diff --git a/server/product-template-tag/internal/types/types.go b/server/product-template-tag/internal/types/types.go index 574a34c6..7474e8da 100644 --- a/server/product-template-tag/internal/types/types.go +++ b/server/product-template-tag/internal/types/types.go @@ -15,11 +15,11 @@ type GetProductTemplateTagsRsp struct { Cover string `json:"cover"` CoverMetadata interface{} `json:"cover_metadata"` Colors []ColorsItem `json:"colors"` + SelectedIndex int `json:"selected_index"` } type ColorsItem struct { - Color []string `json:"color"` - Selected bool `json:"selected"` + Color []string `json:"color"` } type Request struct { diff --git a/server_api/product-template-tag.api b/server_api/product-template-tag.api index 30329047..6c88a573 100644 --- a/server_api/product-template-tag.api +++ b/server_api/product-template-tag.api @@ -25,8 +25,8 @@ type GetProductTemplateTagsRsp { Cover string `json:"cover"` CoverMetadata interface{} `json:"cover_metadata"` Colors []ColorsItem `json:"colors"` + SelectedIndex int `json:"selected_index"` } type ColorsItem { - Color []string `json:"color"` - Selected bool `json:"selected"` + Color []string `json:"color"` } \ No newline at end of file From 93e95d1a1507e59383826ac7f78bdf13001b5283 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Tue, 19 Sep 2023 10:41:15 +0800 Subject: [PATCH 50/59] fix --- .../internal/logic/ws_render_image.go | 13 -------- service/repositories/image_handle.go | 30 +++++++------------ utils/websocket_data/render_data.go | 27 +++++++---------- 3 files changed, 22 insertions(+), 48 deletions(-) diff --git a/server/websocket/internal/logic/ws_render_image.go b/server/websocket/internal/logic/ws_render_image.go index c8fdcd25..a8f86d2f 100644 --- a/server/websocket/internal/logic/ws_render_image.go +++ b/server/websocket/internal/logic/ws_render_image.go @@ -100,15 +100,6 @@ func (w *wsConnectItem) renderImage(data []byte) { logx.Error("invalid format of websocket render image message", err) return } - lenColor := len(renderImageData.RenderData.TemplateTagColor.Color) - if lenColor == 0 { - w.renderErrResponse(renderImageData.RenderId, renderImageData.RenderData.TemplateTag, "", "请传入模板标签选择的颜色", renderImageData.RenderData.ProductId, w.userId, w.guestId, 0, 0, 0, 0) - return - } - if renderImageData.RenderData.TemplateTagColor.SelectedIndex >= lenColor || renderImageData.RenderData.TemplateTagColor.SelectedIndex < 0 { - w.renderErrResponse(renderImageData.RenderId, renderImageData.RenderData.TemplateTag, "", "选择的模板标签颜色索引越界", renderImageData.RenderData.ProductId, w.userId, w.guestId, 0, 0, 0, 0) - return - } //获取产品信息(部分字段) productInfo, err := w.logic.svcCtx.AllModels.FsProduct.FindOne(w.logic.ctx, renderImageData.RenderData.ProductId, "id,is_customization") if err != nil { @@ -201,10 +192,6 @@ func (w *wsConnectItem) renderImage(data []byte) { Phone: renderImageData.RenderData.Phone, Qrcode: renderImageData.RenderData.Qrcode, LogoUrl: renderImageData.RenderData.Logo, - TemplateTagColor: repositories.TemplateTagColor{ - Color: renderImageData.RenderData.TemplateTagColor.Color, - Index: renderImageData.RenderData.TemplateTagColor.SelectedIndex, - }, } res, err := w.logic.svcCtx.Repositories.ImageHandle.LogoCombine(w.logic.ctx, &combineReq) if err != nil { diff --git a/service/repositories/image_handle.go b/service/repositories/image_handle.go index fa71fbd4..642f590d 100644 --- a/service/repositories/image_handle.go +++ b/service/repositories/image_handle.go @@ -187,17 +187,16 @@ func (l *defaultImageHandle) LogoInfoSet(ctx context.Context, in *LogoInfoSetReq /* logo合图 */ type ( LogoCombineReq struct { - UserId int64 `json:"user_id"` - GuestId int64 `json:"guest_id"` - TemplateId int64 `json:"template_id"` - TemplateTag string `json:"template_tag"` - Website string `json:"website"` // 合图参数 - Slogan string `json:"slogan"` // 合图参数 - Address string `json:"address"` // 合图参数 - Phone string `json:"phone"` // 合图参数 - Qrcode string `json:"qrcode"` // 合图参数 - LogoUrl string `json:"logo_url"` // 合图参数 - TemplateTagColor TemplateTagColor `json:"template_tag_color"` + UserId int64 `json:"user_id"` + GuestId int64 `json:"guest_id"` + TemplateId int64 `json:"template_id"` + TemplateTag string `json:"template_tag"` + Website string `json:"website"` // 合图参数 + Slogan string `json:"slogan"` // 合图参数 + Address string `json:"address"` // 合图参数 + Phone string `json:"phone"` // 合图参数 + Qrcode string `json:"qrcode"` // 合图参数 + LogoUrl string `json:"logo_url"` // 合图参数 } LogoCombineRes struct { ResourceId string @@ -207,10 +206,6 @@ type ( DiffTimeUploadFile int64 } ) -type TemplateTagColor struct { - Color [][]string `json:"color"` - Index int `json:"index"` -} func (l *defaultImageHandle) LogoCombine(ctx context.Context, in *LogoCombineReq) (*LogoCombineRes, error) { // 查询logo最新基础信息 @@ -313,10 +308,7 @@ func (l *defaultImageHandle) LogoCombine(ctx context.Context, in *LogoCombineReq combineParam["phone"] = in.Phone combineParam["address"] = in.Address combineParam["qrcode"] = in.Qrcode - combineParam["template_tag_selected"] = map[string]interface{}{ - "template_tag": in.TemplateTag, - "color": in.TemplateTagColor, - } + //combineParam["template_tag_selected"] = var postMap = make(map[string]interface{}, 2) postMap["module_data"] = moduleDataMap diff --git a/utils/websocket_data/render_data.go b/utils/websocket_data/render_data.go index d79032d5..16f3326b 100644 --- a/utils/websocket_data/render_data.go +++ b/utils/websocket_data/render_data.go @@ -15,22 +15,17 @@ type RenderImageReqMsg struct { RenderData RenderData `json:"render_data"` } type RenderData struct { - TemplateTag string `json:"template_tag"` //模板标签(必须) - TemplateTagColor TemplateTagColor `json:"template_tag_color"` //模板标签组合颜色 - ProductId int64 `json:"product_id"` //产品id(必须) - Website string `json:"website"` //网站(可选) - Slogan string `json:"slogan"` //slogan(可选) - Address string `json:"address"` //地址(可选) - Phone string `json:"phone"` //电话(可选) - Qrcode string `json:"qrcode"` //二维码(可选) - ProductSizeId int64 `json:"product_size_id"` //尺寸id(可选) - UserId int64 `json:"user_id"` //用户id(websocket连接建立再赋值) - GuestId int64 `json:"guest_id"` //游客id(websocket连接建立再赋值) - Logo string `json:"logo"` //log资源地址(websocket连接建立再赋值) -} -type TemplateTagColor struct { - Color [][]string `json:"color"` //颜色组合 - SelectedIndex int `json:"selected_index"` //主色的下标索引 + TemplateTag string `json:"template_tag"` //模板标签(必须) + ProductId int64 `json:"product_id"` //产品id(必须) + Website string `json:"website"` //网站(可选) + Slogan string `json:"slogan"` //slogan(可选) + Address string `json:"address"` //地址(可选) + Phone string `json:"phone"` //电话(可选) + Qrcode string `json:"qrcode"` //二维码(可选) + ProductSizeId int64 `json:"product_size_id"` //尺寸id(可选) + UserId int64 `json:"user_id"` //用户id(websocket连接建立再赋值) + GuestId int64 `json:"guest_id"` //游客id(websocket连接建立再赋值) + Logo string `json:"logo"` //log资源地址(websocket连接建立再赋值) } // websocket发送渲染完的数据 From 88d06f68f6f89ae579cb3919417ed8548db26f1f Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Tue, 19 Sep 2023 10:53:48 +0800 Subject: [PATCH 51/59] fix --- .../internal/logic/getproducttemplatetagslogic.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/server/product-template-tag/internal/logic/getproducttemplatetagslogic.go b/server/product-template-tag/internal/logic/getproducttemplatetagslogic.go index 351fce2b..0ecca97e 100644 --- a/server/product-template-tag/internal/logic/getproducttemplatetagslogic.go +++ b/server/product-template-tag/internal/logic/getproducttemplatetagslogic.go @@ -68,7 +68,7 @@ func (l *GetProductTemplateTagsLogic) GetProductTemplateTags(req *types.GetProdu if logoInfo.Metadata == nil || *logoInfo.Metadata == "" { return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "logo info`s metadata is not set") } - //解析元数据 + //解析用户素材元数据 var metaData map[string]interface{} if err = json.Unmarshal([]byte(*logoInfo.Metadata), &metaData); err != nil { logx.Error(err) @@ -83,6 +83,7 @@ func (l *GetProductTemplateTagsLogic) GetProductTemplateTags(req *types.GetProdu //获取选中的颜色数据 mapSelectColor := make(map[string]int) //key是模板标签val是选中的索引 if logoInfo.UserInfoMetadata != nil && *logoInfo.UserInfoMetadata != "" { + //解析用户信息元数据 var logoSelectInfo logoSelect if err = json.Unmarshal([]byte(*logoInfo.UserInfoMetadata), &logoSelectInfo); err != nil { logx.Error(err) From dc4f6dda5040b9e9111322d312a13c905099be5c Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Tue, 19 Sep 2023 10:56:30 +0800 Subject: [PATCH 52/59] fix --- .../internal/logic/getproducttemplatetagslogic.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/product-template-tag/internal/logic/getproducttemplatetagslogic.go b/server/product-template-tag/internal/logic/getproducttemplatetagslogic.go index 0ecca97e..30f5f07b 100644 --- a/server/product-template-tag/internal/logic/getproducttemplatetagslogic.go +++ b/server/product-template-tag/internal/logic/getproducttemplatetagslogic.go @@ -80,7 +80,7 @@ func (l *GetProductTemplateTagsLogic) GetProductTemplateTags(req *types.GetProdu logx.Error(err) return resp.SetStatusWithMessage(basic.CodeJsonErr, "invalid format of metadata`s template_tag") } - //获取选中的颜色数据 + //从用户元数据获取选中的颜色数据 mapSelectColor := make(map[string]int) //key是模板标签val是选中的索引 if logoInfo.UserInfoMetadata != nil && *logoInfo.UserInfoMetadata != "" { //解析用户信息元数据 From 4e0a484e7fe61c2f1d47c82516ceff361427e6f3 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Tue, 19 Sep 2023 10:59:53 +0800 Subject: [PATCH 53/59] fix --- .../internal/logic/getproducttemplatetagslogic.go | 1 - 1 file changed, 1 deletion(-) diff --git a/server/product-template-tag/internal/logic/getproducttemplatetagslogic.go b/server/product-template-tag/internal/logic/getproducttemplatetagslogic.go index 30f5f07b..828f3ab5 100644 --- a/server/product-template-tag/internal/logic/getproducttemplatetagslogic.go +++ b/server/product-template-tag/internal/logic/getproducttemplatetagslogic.go @@ -48,7 +48,6 @@ type logoSelect struct { } func (l *GetProductTemplateTagsLogic) GetProductTemplateTags(req *types.GetProductTemplateTagsReq, userinfo *auth.UserInfo) (resp *basic.Response) { - userinfo.UserId = 127 if req.Limit <= 0 || req.Limit > 100 { req.Limit = 5 } From b4672bbed79c594a0e543793308ab27397b5a6f0 Mon Sep 17 00:00:00 2001 From: eson <9673575+githubcontent@user.noreply.gitee.com> Date: Tue, 19 Sep 2023 11:41:38 +0800 Subject: [PATCH 54/59] nacos config --- env.yaml | 7 + goctl_template/api/main.tpl | 5 +- goctl_template/gateway/main.tpl | 2 +- goctl_template/rpc/main.tpl | 4 +- goctl_template_backend/api/main.tpl | 5 +- goctl_template_backend/gateway/main.tpl | 2 +- goctl_template_backend/rpc/main.tpl | 4 +- server/auth/auth.go | 5 +- server/base/base.go | 4 +- server/canteen/canteen.go | 5 +- server/data-transfer/data-transfer.go | 2 - server/home-user-auth/home-user-auth.go | 5 +- server/info/info.go | 5 +- server/map-library/map-library.go | 4 +- server/pay/pay.go | 5 +- server/product-model/product-model.go | 4 +- .../product-template-tag.go | 5 +- server/product-template/product-template.go | 4 +- server/product/product.go | 4 +- server/resource/resource.go | 5 +- server/shopping-cart/shopping-cart.go | 5 +- server/upload/upload.go | 4 +- server/webset/webset.go | 4 +- server/websocket/websocket.go | 5 +- utils/autoconfig/autoconfig.go | 2 +- utils/autoconfig/autoconfig_test.go | 7 +- utils/collect/collect.go | 4 +- utils/fsconfig/config.go | 153 ++++++++++++++---- utils/fsconfig/config_test.go | 62 +------ 29 files changed, 208 insertions(+), 124 deletions(-) create mode 100644 env.yaml diff --git a/env.yaml b/env.yaml new file mode 100644 index 00000000..b61412d6 --- /dev/null +++ b/env.yaml @@ -0,0 +1,7 @@ +nacos: + - server.fusen.3718.cn:8848 + - server.fusen.3718.cn:8849 +username: ... +password: ... +namespace: fs_server_api_dev +group: FS-SERVER-API diff --git a/goctl_template/api/main.tpl b/goctl_template/api/main.tpl index f4a688cb..057d55c7 100644 --- a/goctl_template/api/main.tpl +++ b/goctl_template/api/main.tpl @@ -7,6 +7,7 @@ import ( "time" "fusenapi/utils/auth" + "fusenapi/utils/fsconfig" {{.importPackages}} ) @@ -16,8 +17,10 @@ var configFile = flag.String("f", "etc/{{.serviceName}}.yaml", "the config file" func main() { flag.Parse() + cfgContent := fsconfig.StartNacosConfig(configFile,nil) var c config.Config - conf.MustLoad(*configFile, &c) + conf.LoadConfigFromYamlBytes([]byte(cfgContent),&c) + c.Timeout = int64(time.Second * 15) server := rest.MustNewServer(c.RestConf, rest.WithCustomCors(auth.FsCors, func(w http.ResponseWriter) { })) diff --git a/goctl_template/gateway/main.tpl b/goctl_template/gateway/main.tpl index dafdd982..33c303b8 100644 --- a/goctl_template/gateway/main.tpl +++ b/goctl_template/gateway/main.tpl @@ -13,7 +13,7 @@ func main() { flag.Parse() var c gateway.GatewayConf - conf.MustLoad(*configFile, &c) + c.Timeout = int64(time.Second * 15) gw := gateway.MustNewServer(c) defer gw.Stop() diff --git a/goctl_template/rpc/main.tpl b/goctl_template/rpc/main.tpl index f095b259..13fbae92 100644 --- a/goctl_template/rpc/main.tpl +++ b/goctl_template/rpc/main.tpl @@ -18,8 +18,10 @@ var configFile = flag.String("f", "etc/{{.serviceName}}.yaml", "the config file" func main() { flag.Parse() + cfgContent := fsconfig.StartNacosConfig(configFile,nil) var c config.Config - conf.MustLoad(*configFile, &c) + conf.LoadConfigFromYamlBytes([]byte(cfgContent),&c) + c.Timeout = int64(time.Second * 15) ctx := svc.NewServiceContext(c) diff --git a/goctl_template_backend/api/main.tpl b/goctl_template_backend/api/main.tpl index 71e4fb99..6cc7a21c 100644 --- a/goctl_template_backend/api/main.tpl +++ b/goctl_template_backend/api/main.tpl @@ -7,6 +7,7 @@ import ( "time" "fusenapi/utils/auth" + "fusenapi/utils/fsconfig" {{.importPackages}} ) @@ -16,8 +17,10 @@ var configFile = flag.String("f", "etc/{{.serviceName}}.yaml", "the config file" func main() { flag.Parse() + cfgContent := fsconfig.StartNacosConfig(configFile,nil) var c config.Config - conf.MustLoad(*configFile, &c) + conf.LoadConfigFromYamlBytes([]byte(cfgContent),&c) + c.Timeout = int64(time.Second * 15) server := rest.MustNewServer(c.RestConf, rest.WithCustomCors(auth.FsCors, func(w http.ResponseWriter) { diff --git a/goctl_template_backend/gateway/main.tpl b/goctl_template_backend/gateway/main.tpl index dafdd982..33c303b8 100644 --- a/goctl_template_backend/gateway/main.tpl +++ b/goctl_template_backend/gateway/main.tpl @@ -13,7 +13,7 @@ func main() { flag.Parse() var c gateway.GatewayConf - conf.MustLoad(*configFile, &c) + c.Timeout = int64(time.Second * 15) gw := gateway.MustNewServer(c) defer gw.Stop() diff --git a/goctl_template_backend/rpc/main.tpl b/goctl_template_backend/rpc/main.tpl index f095b259..13fbae92 100644 --- a/goctl_template_backend/rpc/main.tpl +++ b/goctl_template_backend/rpc/main.tpl @@ -18,8 +18,10 @@ var configFile = flag.String("f", "etc/{{.serviceName}}.yaml", "the config file" func main() { flag.Parse() + cfgContent := fsconfig.StartNacosConfig(configFile,nil) var c config.Config - conf.MustLoad(*configFile, &c) + conf.LoadConfigFromYamlBytes([]byte(cfgContent),&c) + c.Timeout = int64(time.Second * 15) ctx := svc.NewServiceContext(c) diff --git a/server/auth/auth.go b/server/auth/auth.go index 34623035..1c1278f1 100644 --- a/server/auth/auth.go +++ b/server/auth/auth.go @@ -6,6 +6,7 @@ import ( "net/http" "fusenapi/utils/auth" + "fusenapi/utils/fsconfig" "fusenapi/server/auth/internal/config" "fusenapi/server/auth/internal/handler" @@ -20,8 +21,10 @@ var configFile = flag.String("f", "etc/auth.yaml", "the config file") func main() { flag.Parse() + cfgContent := fsconfig.StartNacosConfig(*configFile, nil) var c config.Config - conf.MustLoad(*configFile, &c) + conf.LoadConfigFromYamlBytes([]byte(cfgContent), &c) + server := rest.MustNewServer(c.RestConf, rest.WithCustomCors(auth.FsCors, func(w http.ResponseWriter) { })) defer server.Stop() diff --git a/server/base/base.go b/server/base/base.go index 1d3f1af1..7db23d4a 100644 --- a/server/base/base.go +++ b/server/base/base.go @@ -6,6 +6,7 @@ import ( "net/http" "fusenapi/utils/auth" + "fusenapi/utils/fsconfig" "fusenapi/server/base/internal/config" "fusenapi/server/base/internal/handler" @@ -20,8 +21,9 @@ var configFile = flag.String("f", "etc/base.yaml", "the config file") func main() { flag.Parse() + cfgContent := fsconfig.StartNacosConfig(*configFile, nil) var c config.Config - conf.MustLoad(*configFile, &c) + conf.LoadConfigFromYamlBytes([]byte(cfgContent), &c) server := rest.MustNewServer(c.RestConf, rest.WithCustomCors(auth.FsCors, func(w http.ResponseWriter) { })) diff --git a/server/canteen/canteen.go b/server/canteen/canteen.go index eb2e1f27..2261a4ad 100644 --- a/server/canteen/canteen.go +++ b/server/canteen/canteen.go @@ -9,6 +9,7 @@ import ( "fusenapi/server/canteen/internal/handler" "fusenapi/server/canteen/internal/svc" "fusenapi/utils/auth" + "fusenapi/utils/fsconfig" "github.com/zeromicro/go-zero/core/conf" "github.com/zeromicro/go-zero/rest" @@ -19,9 +20,9 @@ var configFile = flag.String("f", "etc/canteen.yaml", "the config file") func main() { flag.Parse() + cfgContent := fsconfig.StartNacosConfig(*configFile, nil) var c config.Config - - conf.MustLoad(*configFile, &c) + conf.LoadConfigFromYamlBytes([]byte(cfgContent), &c) server := rest.MustNewServer(c.RestConf, rest.WithCustomCors(auth.FsCors, func(w http.ResponseWriter) { diff --git a/server/data-transfer/data-transfer.go b/server/data-transfer/data-transfer.go index 8ad3fa67..db2a4230 100644 --- a/server/data-transfer/data-transfer.go +++ b/server/data-transfer/data-transfer.go @@ -9,7 +9,6 @@ import ( "fusenapi/utils/auth" "net/http" - "github.com/zeromicro/go-zero/core/conf" "github.com/zeromicro/go-zero/rest" ) @@ -19,7 +18,6 @@ func main() { flag.Parse() var c config2.Config - conf.MustLoad(*configFile, &c) server := rest.MustNewServer(c.RestConf, rest.WithCustomCors(auth.FsCors, func(w http.ResponseWriter) { diff --git a/server/home-user-auth/home-user-auth.go b/server/home-user-auth/home-user-auth.go index 911ae5de..16c3a315 100644 --- a/server/home-user-auth/home-user-auth.go +++ b/server/home-user-auth/home-user-auth.go @@ -9,6 +9,7 @@ import ( "fusenapi/server/home-user-auth/internal/handler" "fusenapi/server/home-user-auth/internal/svc" "fusenapi/utils/auth" + "fusenapi/utils/fsconfig" "github.com/zeromicro/go-zero/core/conf" "github.com/zeromicro/go-zero/rest" @@ -19,9 +20,9 @@ var configFile = flag.String("f", "etc/home-user-auth.yaml", "the config file") func main() { flag.Parse() + cfgContent := fsconfig.StartNacosConfig(*configFile, nil) var c config.Config - - conf.MustLoad(*configFile, &c) + conf.LoadConfigFromYamlBytes([]byte(cfgContent), &c) server := rest.MustNewServer(c.RestConf, rest.WithCustomCors(auth.FsCors, func(w http.ResponseWriter) { diff --git a/server/info/info.go b/server/info/info.go index 4571550d..613b74a1 100644 --- a/server/info/info.go +++ b/server/info/info.go @@ -7,6 +7,7 @@ import ( "time" "fusenapi/utils/auth" + "fusenapi/utils/fsconfig" "fusenapi/server/info/internal/config" "fusenapi/server/info/internal/handler" @@ -21,8 +22,10 @@ var configFile = flag.String("f", "etc/info.yaml", "the config file") func main() { flag.Parse() + cfgContent := fsconfig.StartNacosConfig(*configFile, nil) var c config.Config - conf.MustLoad(*configFile, &c) + conf.LoadConfigFromYamlBytes([]byte(cfgContent), &c) + c.Timeout = int64(time.Second * 15) server := rest.MustNewServer(c.RestConf, rest.WithCustomCors(auth.FsCors, func(w http.ResponseWriter) { })) diff --git a/server/map-library/map-library.go b/server/map-library/map-library.go index b8f7e38b..a7ac3fd3 100644 --- a/server/map-library/map-library.go +++ b/server/map-library/map-library.go @@ -9,6 +9,7 @@ import ( "fusenapi/server/map-library/internal/handler" "fusenapi/server/map-library/internal/svc" "fusenapi/utils/auth" + "fusenapi/utils/fsconfig" "github.com/zeromicro/go-zero/core/conf" "github.com/zeromicro/go-zero/rest" @@ -19,8 +20,9 @@ var configFile = flag.String("f", "etc/map-library.yaml", "the config file") func main() { flag.Parse() + cfgContent := fsconfig.StartNacosConfig(*configFile, nil) var c config.Config - conf.MustLoad(*configFile, &c) + conf.LoadConfigFromYamlBytes([]byte(cfgContent), &c) server := rest.MustNewServer(c.RestConf, rest.WithCustomCors(auth.FsCors, func(w http.ResponseWriter) { diff --git a/server/pay/pay.go b/server/pay/pay.go index ecfedfef..5b57352c 100644 --- a/server/pay/pay.go +++ b/server/pay/pay.go @@ -6,6 +6,7 @@ import ( "net/http" "fusenapi/utils/auth" + "fusenapi/utils/fsconfig" "fusenapi/server/pay/internal/config" "fusenapi/server/pay/internal/handler" @@ -20,8 +21,10 @@ var configFile = flag.String("f", "etc/pay.yaml", "the config file") func main() { flag.Parse() + cfgContent := fsconfig.StartNacosConfig(*configFile, nil) var c config.Config - conf.MustLoad(*configFile, &c) + conf.LoadConfigFromYamlBytes([]byte(cfgContent), &c) + server := rest.MustNewServer(c.RestConf, rest.WithCustomCors(auth.FsCors, func(w http.ResponseWriter) { })) defer server.Stop() diff --git a/server/product-model/product-model.go b/server/product-model/product-model.go index a6374de1..0d71e15a 100644 --- a/server/product-model/product-model.go +++ b/server/product-model/product-model.go @@ -9,6 +9,7 @@ import ( "fusenapi/server/product-model/internal/handler" "fusenapi/server/product-model/internal/svc" "fusenapi/utils/auth" + "fusenapi/utils/fsconfig" "github.com/zeromicro/go-zero/core/conf" "github.com/zeromicro/go-zero/rest" @@ -19,8 +20,9 @@ var configFile = flag.String("f", "etc/product-model.yaml", "the config file") func main() { flag.Parse() + cfgContent := fsconfig.StartNacosConfig(*configFile, nil) var c config.Config - conf.MustLoad(*configFile, &c) + conf.LoadConfigFromYamlBytes([]byte(cfgContent), &c) server := rest.MustNewServer(c.RestConf, rest.WithCustomCors(auth.FsCors, func(w http.ResponseWriter) { diff --git a/server/product-template-tag/product-template-tag.go b/server/product-template-tag/product-template-tag.go index 5f1bd6cd..fa892576 100644 --- a/server/product-template-tag/product-template-tag.go +++ b/server/product-template-tag/product-template-tag.go @@ -6,6 +6,7 @@ import ( "net/http" "fusenapi/utils/auth" + "fusenapi/utils/fsconfig" "fusenapi/server/product-template-tag/internal/config" "fusenapi/server/product-template-tag/internal/handler" @@ -20,8 +21,10 @@ var configFile = flag.String("f", "etc/product-template-tag.yaml", "the config f func main() { flag.Parse() + cfgContent := fsconfig.StartNacosConfig(*configFile, nil) var c config.Config - conf.MustLoad(*configFile, &c) + conf.LoadConfigFromYamlBytes([]byte(cfgContent), &c) + server := rest.MustNewServer(c.RestConf, rest.WithCustomCors(auth.FsCors, func(w http.ResponseWriter) { })) defer server.Stop() diff --git a/server/product-template/product-template.go b/server/product-template/product-template.go index 3819752a..260b7c56 100644 --- a/server/product-template/product-template.go +++ b/server/product-template/product-template.go @@ -9,6 +9,7 @@ import ( "fusenapi/server/product-template/internal/handler" "fusenapi/server/product-template/internal/svc" "fusenapi/utils/auth" + "fusenapi/utils/fsconfig" "github.com/zeromicro/go-zero/core/conf" "github.com/zeromicro/go-zero/rest" @@ -19,8 +20,9 @@ var configFile = flag.String("f", "etc/product-template.yaml", "the config file" func main() { flag.Parse() + cfgContent := fsconfig.StartNacosConfig(*configFile, nil) var c config.Config - conf.MustLoad(*configFile, &c) + conf.LoadConfigFromYamlBytes([]byte(cfgContent), &c) server := rest.MustNewServer(c.RestConf, rest.WithCustomCors(auth.FsCors, func(w http.ResponseWriter) { diff --git a/server/product/product.go b/server/product/product.go index 13fba403..adc4c782 100644 --- a/server/product/product.go +++ b/server/product/product.go @@ -9,6 +9,7 @@ import ( "fusenapi/server/product/internal/handler" "fusenapi/server/product/internal/svc" "fusenapi/utils/auth" + "fusenapi/utils/fsconfig" "github.com/zeromicro/go-zero/core/conf" "github.com/zeromicro/go-zero/rest" @@ -19,8 +20,9 @@ var configFile = flag.String("f", "etc/product.yaml", "the config file") func main() { flag.Parse() + cfgContent := fsconfig.StartNacosConfig(*configFile, nil) var c config.Config - conf.MustLoad(*configFile, &c) + conf.LoadConfigFromYamlBytes([]byte(cfgContent), &c) server := rest.MustNewServer(c.RestConf, rest.WithCustomCors(auth.FsCors, func(w http.ResponseWriter) { diff --git a/server/resource/resource.go b/server/resource/resource.go index 29887332..e40a9db7 100644 --- a/server/resource/resource.go +++ b/server/resource/resource.go @@ -6,6 +6,7 @@ import ( "net/http" "fusenapi/utils/auth" + "fusenapi/utils/fsconfig" "fusenapi/server/resource/internal/config" "fusenapi/server/resource/internal/handler" @@ -20,8 +21,10 @@ var configFile = flag.String("f", "etc/resource.yaml", "the config file") func main() { flag.Parse() + cfgContent := fsconfig.StartNacosConfig(*configFile, nil) var c config.Config - conf.MustLoad(*configFile, &c) + conf.LoadConfigFromYamlBytes([]byte(cfgContent), &c) + server := rest.MustNewServer(c.RestConf, rest.WithCustomCors(auth.FsCors, func(w http.ResponseWriter) { })) defer server.Stop() diff --git a/server/shopping-cart/shopping-cart.go b/server/shopping-cart/shopping-cart.go index f7a8cb3f..bf9dabc1 100644 --- a/server/shopping-cart/shopping-cart.go +++ b/server/shopping-cart/shopping-cart.go @@ -7,6 +7,7 @@ import ( "time" "fusenapi/utils/auth" + "fusenapi/utils/fsconfig" "fusenapi/server/shopping-cart/internal/config" "fusenapi/server/shopping-cart/internal/handler" @@ -21,8 +22,10 @@ var configFile = flag.String("f", "etc/shopping-cart.yaml", "the config file") func main() { flag.Parse() + cfgContent := fsconfig.StartNacosConfig(*configFile, nil) var c config.Config - conf.MustLoad(*configFile, &c) + conf.LoadConfigFromYamlBytes([]byte(cfgContent), &c) + c.Timeout = int64(time.Second * 15) server := rest.MustNewServer(c.RestConf, rest.WithCustomCors(auth.FsCors, func(w http.ResponseWriter) { })) diff --git a/server/upload/upload.go b/server/upload/upload.go index bea4af45..42a589d6 100644 --- a/server/upload/upload.go +++ b/server/upload/upload.go @@ -9,6 +9,7 @@ import ( "fusenapi/server/upload/internal/handler" "fusenapi/server/upload/internal/svc" "fusenapi/utils/auth" + "fusenapi/utils/fsconfig" "github.com/zeromicro/go-zero/core/conf" "github.com/zeromicro/go-zero/rest" @@ -19,8 +20,9 @@ var configFile = flag.String("f", "etc/upload.yaml", "the config file") func main() { flag.Parse() + cfgContent := fsconfig.StartNacosConfig(*configFile, nil) var c config.Config - conf.MustLoad(*configFile, &c) + conf.LoadConfigFromYamlBytes([]byte(cfgContent), &c) server := rest.MustNewServer(c.RestConf, rest.WithCustomCors(auth.FsCors, func(w http.ResponseWriter) { diff --git a/server/webset/webset.go b/server/webset/webset.go index ab154b3b..be0cfcd0 100644 --- a/server/webset/webset.go +++ b/server/webset/webset.go @@ -9,6 +9,7 @@ import ( "fusenapi/server/webset/internal/handler" "fusenapi/server/webset/internal/svc" "fusenapi/utils/auth" + "fusenapi/utils/fsconfig" "github.com/zeromicro/go-zero/core/conf" "github.com/zeromicro/go-zero/rest" @@ -19,8 +20,9 @@ var configFile = flag.String("f", "etc/webset.yaml", "the config file") func main() { flag.Parse() + cfgContent := fsconfig.StartNacosConfig(*configFile, nil) var c config.Config - conf.MustLoad(*configFile, &c) + conf.LoadConfigFromYamlBytes([]byte(cfgContent), &c) server := rest.MustNewServer(c.RestConf, rest.WithCustomCors(auth.FsCors, func(w http.ResponseWriter) { diff --git a/server/websocket/websocket.go b/server/websocket/websocket.go index d77e9242..6dbc99a2 100644 --- a/server/websocket/websocket.go +++ b/server/websocket/websocket.go @@ -8,6 +8,7 @@ import ( "net/http" "fusenapi/utils/auth" + "fusenapi/utils/fsconfig" "fusenapi/server/websocket/internal/config" "fusenapi/server/websocket/internal/handler" @@ -22,8 +23,10 @@ var configFile = flag.String("f", "etc/websocket.yaml", "the config file") func main() { flag.Parse() + cfgContent := fsconfig.StartNacosConfig(*configFile, nil) var c config.Config - conf.MustLoad(*configFile, &c) + conf.LoadConfigFromYamlBytes([]byte(cfgContent), &c) + server := rest.MustNewServer(c.RestConf, rest.WithCustomCors(auth.FsCors, func(w http.ResponseWriter) { })) defer server.Stop() diff --git a/utils/autoconfig/autoconfig.go b/utils/autoconfig/autoconfig.go index 72442729..97fc2c05 100644 --- a/utils/autoconfig/autoconfig.go +++ b/utils/autoconfig/autoconfig.go @@ -74,7 +74,7 @@ func AutoGetEtcYaml() *string { dirs = dirs[0 : len(dirs)-1] // 列出所有 curPath 下的文件夹 - files, err := ioutil.ReadDir(curPath) + files, err := os.ReadDir(curPath) if err != nil { log.Println(err) continue diff --git a/utils/autoconfig/autoconfig_test.go b/utils/autoconfig/autoconfig_test.go index 7f118a8a..0a72aab0 100644 --- a/utils/autoconfig/autoconfig_test.go +++ b/utils/autoconfig/autoconfig_test.go @@ -1,7 +1,10 @@ package autoconfig -import "testing" +import ( + "log" + "testing" +) func TestAutoConfig(t *testing.T) { - AutoGetEtcYaml() + log.Println(*AutoGetEtcYaml()) } diff --git a/utils/collect/collect.go b/utils/collect/collect.go index b0502d61..c3630e5c 100644 --- a/utils/collect/collect.go +++ b/utils/collect/collect.go @@ -119,7 +119,7 @@ func Array2MapByKey[KEY comparable, VALUE any](arrSrc []VALUE, fieldName string) } fv := srcv.FieldByName(fieldName) k := fv.Interface().(KEY) - result[k] = srcv.Interface().(VALUE) + result[k] = arr.Index(i).Interface().(VALUE) } return result @@ -166,7 +166,7 @@ func Array2MapByKeyTag[KEY comparable, VALUE any](arrSrc []VALUE, tag string) (r fv = fv.Elem() } k := fv.Interface().(KEY) - result[k] = srcv.Interface().(VALUE) + result[k] = arr.Index(i).Interface().(VALUE) } return diff --git a/utils/fsconfig/config.go b/utils/fsconfig/config.go index 116043dc..66f5841e 100644 --- a/utils/fsconfig/config.go +++ b/utils/fsconfig/config.go @@ -1,53 +1,142 @@ package fsconfig import ( - "fmt" "log" "os" + "path/filepath" + "strconv" + "strings" + "github.com/nacos-group/nacos-sdk-go/v2/clients" + "github.com/nacos-group/nacos-sdk-go/v2/common/constant" + "github.com/nacos-group/nacos-sdk-go/v2/vo" "gopkg.in/yaml.v2" ) type EnvConfig struct { - Host string `yaml:"host"` - Port uint64 `yaml:"port"` - - UserName string `yaml:"username"` - Password string `yaml:"password"` - NamespaceId string `yaml:"namespace"` - DataId string `yaml:"dataid"` - Group string `yaml:"group"` + NacosServers []string `yaml:"nacos"` + UserName string `yaml:"username"` + Password string `yaml:"password"` + NamespaceId string `yaml:"namespace"` + DataId string `yaml:"dataid"` + Group string `yaml:"group"` } -var OptPathDir = "/opt" +var optPathDirs = []string{"/opt", "./", "../", "../../"} var nacosConfig *EnvConfig func GetEnvCofing() *EnvConfig { - return nacosConfig + + if nacosConfig != nil { + return nacosConfig + } + + for _, optDir := range optPathDirs { + if optDir[len(optDir)-1] != '/' { + optDir = optDir + "/" + } + + for _, yname := range []string{"env.yaml", "env.yml"} { + f, err := os.Open(optDir + yname) + if err != nil { + // log.Println(err) + continue + } + cfg := &EnvConfig{} + err = yaml.NewDecoder(f).Decode(&cfg) + if err != nil { + // log.Println(err) + continue + } + + nacosConfig = cfg + return nacosConfig + } + } + + panic("Can't find env.yaml or env.yml in the specified directories") + } func init() { - if OptPathDir[len(OptPathDir)-1] != '/' { - OptPathDir = OptPathDir + "/" - } - for _, yname := range []string{"env.yaml", "env.yml"} { - f, err := os.Open(OptPathDir + "/" + yname) - if err != nil { - log.Println(err) - continue - } - cfg := &EnvConfig{} - err = yaml.NewDecoder(f).Decode(&cfg) - if err != nil { - log.Println(err) - continue - } - - nacosConfig = cfg - return - } - - panic(fmt.Sprintf("can't find %s(env.yaml|env.yml) ", OptPathDir)) +} + +func StartNacosConfig(configFile string, OnChange func(namespace, group, dataId, data string)) string { + env := GetEnvCofing() + + // 创建serverConfig + // 支持多个;至少一个ServerConfig + var serverConfig []constant.ServerConfig + + for _, s := range env.NacosServers { + + sp := strings.Split(s, ":") + host := sp[0] + port, err := strconv.ParseUint(sp[1], 10, 64) + if err != nil { + panic(err) + } + + serverConfig = append(serverConfig, constant.ServerConfig{ + IpAddr: host, + Port: port, + }) + } + + // 创建clientConfig + clientConfig := constant.ClientConfig{ + NamespaceId: env.NamespaceId, // 如果需要支持多namespace,我们可以场景多个client,它们有不同的NamespaceId。当namespace是public时,此处填空字符串。 + TimeoutMs: 50000, + NotLoadCacheAtStart: true, + LogLevel: "debug", + LogDir: "/tmp/nacos/log", + CacheDir: "/tmp/nacos/cache", + Username: env.UserName, + Password: env.Password, + } + + // 创建服务发现客户端的另一种方式 (推荐) + // namingClient, err := clients.NewNamingClient( + // vo.NacosClientParam{ + // ClientConfig: &clientConfig, + // ServerConfigs: serverConfig, + // }, + // ) + // if err != nil { + // log.Fatalf("初始化nacos失败: %s", err.Error()) + // } + + // log.Println(namingClient) + + // 创建 Nacos 配置客户端 + configClient, err := clients.CreateConfigClient(map[string]interface{}{ + "clientConfig": clientConfig, + "serverConfigs": serverConfig, + }) + if err != nil { + log.Fatalf("Failed to create Nacos config client: %v", err) + } + + cfgYamls := strings.Split(configFile, "/") + cfgYaml := cfgYamls[len(cfgYamls)-1] + yamlExt := filepath.Ext(cfgYaml) + if !(yamlExt == ".yaml" || yamlExt == ".yml") { + log.Panic(configFile) + } + + // 获取配置 + content, err := configClient.GetConfig(vo.ConfigParam{ + DataId: cfgYaml, + Group: env.Group, + OnChange: OnChange, + }) + if err != nil { + log.Fatalf("Failed to get config from Nacos: %v", err) + } + + return content + + // log.Println(content) } diff --git a/utils/fsconfig/config_test.go b/utils/fsconfig/config_test.go index f285c6bb..8ffaaffb 100644 --- a/utils/fsconfig/config_test.go +++ b/utils/fsconfig/config_test.go @@ -2,69 +2,9 @@ package fsconfig_test import ( "fusenapi/utils/fsconfig" - "log" "testing" - - "github.com/nacos-group/nacos-sdk-go/v2/clients" - "github.com/nacos-group/nacos-sdk-go/v2/common/constant" - "github.com/nacos-group/nacos-sdk-go/v2/vo" ) func TestCase1(t *testing.T) { - - env := fsconfig.GetEnvCofing() - - // 创建serverConfig - // 支持多个;至少一个ServerConfig - serverConfig := []constant.ServerConfig{ - { - IpAddr: env.Host, - Port: uint64(env.Port), - }, - } - - // 创建clientConfig - clientConfig := constant.ClientConfig{ - NamespaceId: env.NamespaceId, // 如果需要支持多namespace,我们可以场景多个client,它们有不同的NamespaceId。当namespace是public时,此处填空字符串。 - TimeoutMs: 50000, - NotLoadCacheAtStart: true, - LogLevel: "debug", - LogDir: "/tmp/nacos", - CacheDir: "/tmp/nacos", - Username: env.UserName, - Password: env.Password, - } - - // 创建服务发现客户端的另一种方式 (推荐) - // namingClient, err := clients.NewNamingClient( - // vo.NacosClientParam{ - // ClientConfig: &clientConfig, - // ServerConfigs: serverConfig, - // }, - // ) - // if err != nil { - // log.Fatalf("初始化nacos失败: %s", err.Error()) - // } - - // log.Println(namingClient) - - // 创建 Nacos 配置客户端 - configClient, err := clients.CreateConfigClient(map[string]interface{}{ - "clientConfig": clientConfig, - "serverConfigs": serverConfig, - }) - if err != nil { - log.Fatalf("Failed to create Nacos config client: %v", err) - } - - // 获取配置 - content, err := configClient.GetConfig(vo.ConfigParam{ - DataId: "auth.yaml", - Group: env.Group, - }) - if err != nil { - log.Fatalf("Failed to get config from Nacos: %v", err) - } - log.Println(content) - + fsconfig.StartNacosConfig("auth.yaml", nil) } From c0b773634a7238b1ea26e4230ed4fc91be64c6ed Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Tue, 19 Sep 2023 11:42:10 +0800 Subject: [PATCH 55/59] =?UTF-8?q?=E5=90=88=E5=B9=B6develop?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- server/shopping-cart/internal/logic/getcartslogic.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/server/shopping-cart/internal/logic/getcartslogic.go b/server/shopping-cart/internal/logic/getcartslogic.go index 303716f4..f79d8db3 100644 --- a/server/shopping-cart/internal/logic/getcartslogic.go +++ b/server/shopping-cart/internal/logic/getcartslogic.go @@ -41,6 +41,9 @@ func NewGetCartsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetCarts // } func (l *GetCartsLogic) GetCarts(req *types.GetCartsReq, userinfo *auth.UserInfo) (resp *basic.Response) { + if !userinfo.IsUser() { + return resp.SetStatusWithMessage(basic.CodeUnAuth, "please sign in") + } if req.CurrentPage <= 0 { req.CurrentPage = constants.DEFAULT_PAGE } From 3c33a9603749112242675a007334d4514a05a181 Mon Sep 17 00:00:00 2001 From: eson <9673575+githubcontent@user.noreply.gitee.com> Date: Tue, 19 Sep 2023 11:48:38 +0800 Subject: [PATCH 56/59] nacos config --- utils/fsconfig/config.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/utils/fsconfig/config.go b/utils/fsconfig/config.go index 66f5841e..3c933bb5 100644 --- a/utils/fsconfig/config.go +++ b/utils/fsconfig/config.go @@ -136,6 +136,8 @@ func StartNacosConfig(configFile string, OnChange func(namespace, group, dataId, log.Fatalf("Failed to get config from Nacos: %v", err) } + log.Println("加载成功:", cfgYaml) + return content // log.Println(content) From 7fd65d9ac76680c3ac9f48d3fc6ce794d86897a5 Mon Sep 17 00:00:00 2001 From: eson <9673575+githubcontent@user.noreply.gitee.com> Date: Tue, 19 Sep 2023 12:01:37 +0800 Subject: [PATCH 57/59] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E6=96=B0=E7=9A=84?= =?UTF-8?q?=E5=8A=A0=E8=BD=BD=E4=BE=9D=E8=B5=96=E6=96=B9=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 14 -------------- run_all_server.sh | 5 +++-- server/auth/.gitignore | 1 + server/base/.gitignore | 1 + server/canteen/.gitignore | 1 + server/data-transfer/.gitignore | 1 + server/home-user-auth/.gitignore | 1 + server/info/.gitignore | 1 + server/map-library/.gitignore | 1 + server/pay/.gitignore | 1 + server/product-model/.gitignore | 1 + server/product-template-tag/.gitignore | 1 + server/product-template/.gitignore | 1 + server/product/.gitignore | 1 + server/resource/.gitignore | 1 + server/shopping-cart/.gitignore | 1 + server/upload/.gitignore | 1 + server/webset/.gitignore | 1 + server/websocket/.gitignore | 1 + 19 files changed, 20 insertions(+), 16 deletions(-) create mode 100644 server/auth/.gitignore create mode 100644 server/base/.gitignore create mode 100644 server/canteen/.gitignore create mode 100644 server/data-transfer/.gitignore create mode 100644 server/home-user-auth/.gitignore create mode 100644 server/info/.gitignore create mode 100644 server/map-library/.gitignore create mode 100644 server/pay/.gitignore create mode 100644 server/product-model/.gitignore create mode 100644 server/product-template-tag/.gitignore create mode 100644 server/product-template/.gitignore create mode 100644 server/product/.gitignore create mode 100644 server/resource/.gitignore create mode 100644 server/shopping-cart/.gitignore create mode 100644 server/upload/.gitignore create mode 100644 server/webset/.gitignore create mode 100644 server/websocket/.gitignore diff --git a/.gitignore b/.gitignore index 2f86e838..d25a14ce 100644 --- a/.gitignore +++ b/.gitignore @@ -40,20 +40,6 @@ screenlog.* proxyserver/proxyserver -server/backend/backend -server/canteen/canteen -server/data-transfer/data-transfer -server/home-user-auth/home-user-auth -server/inventory/inventory -server/map-library/map-library -server/orders/orders -server/product/product -server/product-model/product-model -server/product-template/product-template -server/shopping-cart-confirmation/shopping-cart-confirmation -server/upload/upload -server/webset/webset - shared-state *.zip \ No newline at end of file diff --git a/run_all_server.sh b/run_all_server.sh index fc8318dc..1cf70b31 100755 --- a/run_all_server.sh +++ b/run_all_server.sh @@ -15,8 +15,10 @@ run_server() { # 导航到相应的目录 cd server/$server_name + go build + echo $server_name > .gitignore # 使用 screen 运行 go run