From c5bcf9d6760735f1080b197f94a4ed1014f0beda Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Tue, 27 Jun 2023 14:25:25 +0800 Subject: [PATCH 1/5] fix --- constants/cloud_order.go | 26 ++++ go.mod | 1 + go.sum | 2 + model/gmodel/fs_cloud_pick_up_logic.go | 31 +++- model/gmodel/fs_user_stock_logic.go | 24 +++- server/inventory/etc/inventory.yaml | 8 ++ server/inventory/internal/config/config.go | 9 ++ server/inventory/internal/handler/routes.go | 22 +++ .../inventory/internal/handler/takehandler.go | 78 +++++++++++ server/inventory/internal/logic/takelogic.go | 132 ++++++++++++++++++ .../inventory/internal/svc/servicecontext.go | 60 ++++++++ server/inventory/internal/types/types.go | 71 ++++++++++ server/inventory/inventory.go | 49 +++++++ server_api/inventory.api | 12 +- utils/snow_id_generator/snowflake.go | 16 +++ 15 files changed, 536 insertions(+), 5 deletions(-) create mode 100644 constants/cloud_order.go create mode 100644 server/inventory/etc/inventory.yaml create mode 100644 server/inventory/internal/config/config.go create mode 100644 server/inventory/internal/handler/routes.go create mode 100644 server/inventory/internal/handler/takehandler.go create mode 100644 server/inventory/internal/logic/takelogic.go create mode 100644 server/inventory/internal/svc/servicecontext.go create mode 100644 server/inventory/internal/types/types.go create mode 100644 server/inventory/inventory.go create mode 100644 utils/snow_id_generator/snowflake.go diff --git a/constants/cloud_order.go b/constants/cloud_order.go new file mode 100644 index 00000000..2600fc30 --- /dev/null +++ b/constants/cloud_order.go @@ -0,0 +1,26 @@ +package constants + +type cloud int64 + +// 已下单 +const STATUS_ORDERD cloud = 1 + +// 运输中 +const STATUS_SHIPPING cloud = 2 + +// ups待提货 +const STATUS_PICK_UP cloud = 3 + +// 已到达 +const STATUS_ARRIVAL cloud = 4 + +/** + * 状态对应中文 + * @var string[] + */ +var CloudOrderMap = map[cloud]string{ + STATUS_ORDERD: "已下单", + STATUS_SHIPPING: "运输中", + STATUS_PICK_UP: "UPS已发货", + STATUS_ARRIVAL: "已到达", +} diff --git a/go.mod b/go.mod index d4a3e687..8bba335f 100644 --- a/go.mod +++ b/go.mod @@ -15,6 +15,7 @@ require ( ) require ( + github.com/bwmarrin/snowflake v0.3.0 // indirect github.com/google/uuid v1.3.0 // indirect github.com/schollz/progressbar v1.0.0 // indirect ) diff --git a/go.sum b/go.sum index e5372365..01f352c9 100644 --- a/go.sum +++ b/go.sum @@ -45,6 +45,8 @@ github.com/alicebob/miniredis/v2 v2.30.2 h1:lc1UAUT9ZA7h4srlfBmBt2aorm5Yftk9nBjx github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= 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/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= github.com/cenkalti/backoff/v4 v4.2.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= diff --git a/model/gmodel/fs_cloud_pick_up_logic.go b/model/gmodel/fs_cloud_pick_up_logic.go index e68225aa..51202633 100644 --- a/model/gmodel/fs_cloud_pick_up_logic.go +++ b/model/gmodel/fs_cloud_pick_up_logic.go @@ -1,2 +1,31 @@ package gmodel -// TODO: 使用model的属性做你想做的 \ No newline at end of file + +import ( + "context" + "gorm.io/gorm" +) + +// TODO: 使用model的属性做你想做的 + +func (p *FsCloudPickUpModel) SavePickUpWithTransaction(ctx context.Context, pickUpData *FsCloudPickUp, stockList []FsUserStock, pickUpDetailAddList []FsCloudPickUpDetail) error { + return p.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { + //保存总提单信息 + if err := tx.Model(&FsCloudPickUp{}).Create(&pickUpData).Error; err != nil { + return err + } + //更新云仓库存 + for _, v := range stockList { + if err := tx.Model(&FsUserStock{}).Where("`id` = ?", v.Id).Updates(&v).Error; err != nil { + return err + } + } + //添加提单详情 + for _, v := range pickUpDetailAddList { + v.PickId = &pickUpData.Id //外面没赋值在这需要赋值 + if err := tx.Model(&FsCloudPickUpDetail{}).Create(&v).Error; err != nil { + return err + } + } + return nil + }) +} diff --git a/model/gmodel/fs_user_stock_logic.go b/model/gmodel/fs_user_stock_logic.go index e68225aa..f83b3e1c 100644 --- a/model/gmodel/fs_user_stock_logic.go +++ b/model/gmodel/fs_user_stock_logic.go @@ -1,2 +1,24 @@ package gmodel -// TODO: 使用model的属性做你想做的 \ No newline at end of file + +import "context" + +// TODO: 使用model的属性做你想做的 + +func (s *FsUserStockModel) GetUserAllStockByIds(ctx context.Context, ids []int64, userId int64) (resp []FsUserStock, err error) { + if len(ids) == 0 { + return nil, nil + } + if userId <= 0 { + return nil, nil + } + err = s.db.WithContext(ctx).Model(&FsUserStock{}).Where("`id` in (?) and `user_id` = ?", ids, userId).Find(&resp).Error + return resp, err +} +func (s *FsUserStockModel) FindOne(ctx context.Context, id int64, userId int64, lock ...bool) (resp *FsUserStock, err error) { + db := s.db.WithContext(ctx).Model(&FsUserStock{}).Where("`id` = ? and `user_id` = ?", id, userId) + if len(lock) != 0 && lock[0] { + db = db.Set("gorm:query_option", "FOR UPDATE") + } + err = db.First(&resp).Error + return resp, err +} diff --git a/server/inventory/etc/inventory.yaml b/server/inventory/etc/inventory.yaml new file mode 100644 index 00000000..611a0d7e --- /dev/null +++ b/server/inventory/etc/inventory.yaml @@ -0,0 +1,8 @@ +Name: inventory +Host: 0.0.0.0 +Port: 8898 +SourceMysql: fusentest:XErSYmLELKMnf3Dh@tcp(110.41.19.98:3306)/fusentest +Auth: + AccessSecret: fusen2023 + AccessExpire: 604800 + RefreshAfter: 345600 \ No newline at end of file diff --git a/server/inventory/internal/config/config.go b/server/inventory/internal/config/config.go new file mode 100644 index 00000000..b24bb7d7 --- /dev/null +++ b/server/inventory/internal/config/config.go @@ -0,0 +1,9 @@ +package config + +import "github.com/zeromicro/go-zero/rest" + +type Config struct { + rest.RestConf + SourceMysql string + Auth types.Auth +} diff --git a/server/inventory/internal/handler/routes.go b/server/inventory/internal/handler/routes.go new file mode 100644 index 00000000..8122eebb --- /dev/null +++ b/server/inventory/internal/handler/routes.go @@ -0,0 +1,22 @@ +// Code generated by goctl. DO NOT EDIT. +package handler + +import ( + "net/http" + + "fusenapi/server/inventory/internal/svc" + + "github.com/zeromicro/go-zero/rest" +) + +func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { + server.AddRoutes( + []rest.Route{ + { + Method: http.MethodPost, + Path: "/inventory/take", + Handler: TakeHandler(serverCtx), + }, + }, + ) +} diff --git a/server/inventory/internal/handler/takehandler.go b/server/inventory/internal/handler/takehandler.go new file mode 100644 index 00000000..2ff8d910 --- /dev/null +++ b/server/inventory/internal/handler/takehandler.go @@ -0,0 +1,78 @@ +package handler + +import ( + "errors" + "net/http" + + "github.com/zeromicro/go-zero/core/logx" + "github.com/zeromicro/go-zero/rest/httpx" + + "fusenapi/utils/auth" + "fusenapi/utils/basic" + + "fusenapi/server/inventory/internal/logic" + "fusenapi/server/inventory/internal/svc" + "fusenapi/server/inventory/internal/types" +) + +func TakeHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + + var ( + // 定义错误变量 + err error + // 定义用户信息变量 + userinfo *auth.UserInfo + ) + // 解析JWT token,并对空用户进行判断 + claims, err := svcCtx.ParseJwtToken(r) + // 如果解析JWT token出错,则返回未授权的JSON响应并记录错误消息 + if err != nil { + httpx.OkJsonCtx(r.Context(), w, &basic.Response{ + Code: 401, // 返回401状态码,表示未授权 + Message: "unauthorized", // 返回未授权信息 + }) + logx.Info("unauthorized:", err.Error()) // 记录错误日志 + return + } + + if claims != nil { + // 从token中获取对应的用户信息 + userinfo, err = auth.GetUserInfoFormMapClaims(claims) + // 如果获取用户信息出错,则返回未授权的JSON响应并记录错误消息 + if err != nil { + httpx.OkJsonCtx(r.Context(), w, &basic.Response{ + Code: 401, + Message: "unauthorized", + }) + logx.Info("unauthorized:", err.Error()) + return + } + } else { + // 如果claims为nil,则认为用户身份为白板用户 + userinfo = &auth.UserInfo{UserId: 0, GuestId: 0} + } + + var req types.TakeReq + // 如果端点有请求结构体,则使用httpx.Parse方法从HTTP请求体中解析请求数据 + if err := httpx.Parse(r, &req); err != nil { + httpx.OkJsonCtx(r.Context(), w, &basic.Response{ + Code: 510, + Message: "parameter error", + }) + logx.Info(err) + return + } + // 创建一个业务逻辑层实例 + l := logic.NewTakeLogic(r.Context(), svcCtx) + resp := l.Take(&req, userinfo) + // 如果响应不为nil,则使用httpx.OkJsonCtx方法返回JSON响应; + if resp != nil { + httpx.OkJsonCtx(r.Context(), w, resp) + } else { + err := errors.New("server logic is error, resp must not be nil") + httpx.ErrorCtx(r.Context(), w, err) + logx.Error(err) + } + } +} diff --git a/server/inventory/internal/logic/takelogic.go b/server/inventory/internal/logic/takelogic.go new file mode 100644 index 00000000..b4f9bdbe --- /dev/null +++ b/server/inventory/internal/logic/takelogic.go @@ -0,0 +1,132 @@ +package logic + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "fusenapi/constants" + "fusenapi/model/gmodel" + "fusenapi/server/inventory/internal/types" + "fusenapi/utils/auth" + "fusenapi/utils/basic" + "fusenapi/utils/snow_id_generator" + "github.com/bwmarrin/snowflake" + "gorm.io/gorm" + "time" + + "fusenapi/server/inventory/internal/svc" + "github.com/zeromicro/go-zero/core/logx" +) + +type TakeLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +func NewTakeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *TakeLogic { + return &TakeLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *TakeLogic) Take(req *types.TakeReq, userinfo *auth.UserInfo) (resp *basic.Response) { + if userinfo.GetIdType() != auth.IDTYPE_User { + return resp.SetStatusWithMessage(basic.CodeServiceErr, "please login first") + } + if len(req.Form) == 0 { + return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "param err :form can`t be empty array") + } + if req.AddressId <= 0 { + return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "param err :address_id is required") + } + //获取地址信息 + addressInfo, err := l.svcCtx.AllModels.FsAddress.GetOne(l.ctx, req.AddressId, userinfo.UserId) + if err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, "your address is not exists") + } + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get address info") + } + stockIds := make([]int64, 0, len(req.Form)) + for _, v := range req.Form { + stockIds = append(stockIds, v.Id) + } + //提货单总单 + addressInfoBytes, _ := json.Marshal(addressInfo) + addressInfoJson := string(addressInfoBytes) + trackNum, err := snow_id_generator.GenSnowId() + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to gen trackNum") + } + status := int64(constants.STATUS_ORDERD) + now := time.Now().Unix() + pickUpData := gmodel.FsCloudPickUp{ + UserId: &userinfo.UserId, + TrackNum: &trackNum, + AddressId: &req.AddressId, + AddressInfo: &addressInfoJson, + Status: &status, + Ctime: &now, + } + //开启事务 + //箱数验证 + boxes := int64(0) + //需要更新的库存信息 + stockUpdateList := make([]gmodel.FsUserStock, 0, len(req.Form)) + //需要新增的提货详情单 + pickUpDetailAddList := make([]gmodel.FsCloudPickUpDetail, 0, len(req.Form)) + for k, val := range req.Form { + formItem := val + //验证提取数量 + if formItem.Num <= 0 { + return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, fmt.Sprintf("row %d inventory data`s take num can`be less than 0", k+1)) + } + //获取库存信息(枷锁) + stockInfo, err := l.svcCtx.AllModels.FsUserStock.FindOne(l.ctx, v.Id, userinfo.UserId, true) + if err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, fmt.Sprintf("row %d inventory data is not availabled for you", k+1)) + } + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeDbSqlErr, fmt.Sprintf("failed to get row %d`s stock info ", k+1)) + } + //校验取货数量 + if *stockInfo.Stick < formItem.Num { + return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, fmt.Sprintf("row %d inventory data is shortage", k+1)) + } + if *stockInfo.EachBoxNum <= 0 { + return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, fmt.Sprintf("row %d inventory data each box num can`t be less than 0", k+1)) + } + boxes += (formItem.Num / *stockInfo.EachBoxNum) + //库存变更 + newStick := *stockInfo.Stick - formItem.Num + newTransNum := *stockInfo.TransNum + formItem.Num + stockUpdateList = append(stockUpdateList, gmodel.FsUserStock{ + Id: stockInfo.Id, + Stick: &newStick, + TransNum: &newTransNum, + }) + //提货详情单 + detailBoxes := formItem.Num / *stockInfo.EachBoxNum + pickUpDetailAddList = append(pickUpDetailAddList, gmodel.FsCloudPickUpDetail{ + PickId: nil, //到model里方法会给他赋值pick总单id + StockId: &formItem.Id, + Num: &formItem.Num, + Boxes: &detailBoxes, + Ctime: &now, + }) + } + //事务处理数据 + err = l.svcCtx.AllModels.FsCloudPickUp.SavePickUpWithTransaction(l.ctx, &pickUpData, stockUpdateList, pickUpDetailAddList) + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to take your goods") + } + return resp.SetStatusWithMessage(basic.CodeOK, "success", []int64{}) +} diff --git a/server/inventory/internal/svc/servicecontext.go b/server/inventory/internal/svc/servicecontext.go new file mode 100644 index 00000000..f30de860 --- /dev/null +++ b/server/inventory/internal/svc/servicecontext.go @@ -0,0 +1,60 @@ +package svc + +import ( + "errors" + "fmt" + "fusenapi/server/inventory/internal/config" + "net/http" + + "fusenapi/initalize" + "fusenapi/model/gmodel" + + "github.com/golang-jwt/jwt" + "gorm.io/gorm" +) + +type ServiceContext struct { + Config config.Config + + MysqlConn *gorm.DB + AllModels *gmodel.AllModelsGen +} + +func NewServiceContext(c config.Config) *ServiceContext { + + return &ServiceContext{ + Config: c, + MysqlConn: initalize.InitMysql(c.SourceMysql), + AllModels: gmodel.NewAllModels(initalize.InitMysql(c.SourceMysql)), + } +} + +func (svcCtx *ServiceContext) ParseJwtToken(r *http.Request) (jwt.MapClaims, error) { + AuthKey := r.Header.Get("Authorization") + if AuthKey == "" { + return nil, nil + } + + if len(AuthKey) <= 50 { + return nil, errors.New(fmt.Sprint("Error parsing token, len:", len(AuthKey))) + } + + token, err := jwt.Parse(AuthKey, func(token *jwt.Token) (interface{}, error) { + // 检查签名方法是否为 HS256 + if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { + return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) + } + // 返回用于验证签名的密钥 + return []byte(svcCtx.Config.Auth.AccessSecret), nil + }) + if err != nil { + return nil, errors.New(fmt.Sprint("Error parsing token:", err)) + } + + // 验证成功返回 + if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid { + return claims, nil + } + + return nil, errors.New(fmt.Sprint("Invalid token", err)) +} diff --git a/server/inventory/internal/types/types.go b/server/inventory/internal/types/types.go new file mode 100644 index 00000000..02ad0eb0 --- /dev/null +++ b/server/inventory/internal/types/types.go @@ -0,0 +1,71 @@ +// Code generated by goctl. DO NOT EDIT. +package types + +import ( + "fusenapi/utils/basic" +) + +type TakeReq struct { + Form []TakeForm `json:"form"` + AddressId int64 `json:"address_id"` +} + +type TakeForm struct { + Id int64 `json:"id"` + Num int64 `json:"num"` +} + +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"` +} + +// 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/inventory/inventory.go b/server/inventory/inventory.go new file mode 100644 index 00000000..83d3d6ed --- /dev/null +++ b/server/inventory/inventory.go @@ -0,0 +1,49 @@ +package main + +import ( + "flag" + "fmt" + + "fusenapi/server/inventory/internal/config" + "fusenapi/server/inventory/internal/handler" + "fusenapi/server/inventory/internal/svc" + + "github.com/zeromicro/go-zero/core/conf" + "github.com/zeromicro/go-zero/rest" +) + +var configFile = flag.String("f", "etc/inventory.yaml", "the config file") + +func main() { + flag.Parse() + + var c config.Config + conf.MustLoad(*configFile, &c) + + server := rest.MustNewServer(c.RestConf) + defer server.Stop() + + ctx := svc.NewServiceContext(c) + handler.RegisterHandlers(server, ctx) + + fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port) + server.Start() +} + +// var testConfigFile = flag.String("f", "../etc/inventory.yaml", "the config file") +// var cnf config.Config + +// func GetTestServer() *rest.Server { +// flag.Parse() + +// conf.MustLoad(*testConfigFile, &cnf) + +// server := rest.MustNewServer(cnf.RestConf) +// defer server.Stop() + +// ctx := svc.NewServiceContext(cnf) +// handler.RegisterHandlers(server, ctx) + +// fmt.Printf("Starting server at %s:%d...\n", cnf.Host, cnf.Port) +// return server +// } diff --git a/server_api/inventory.api b/server_api/inventory.api index 07d6bceb..3bea4665 100644 --- a/server_api/inventory.api +++ b/server_api/inventory.api @@ -8,12 +8,18 @@ info ( ) import "basic.api" -service canteen { +service inventory { //提取云仓货物 @handler TakeHandler post /inventory/take(TakeReq) returns (response); } -//提取云仓货物 -type TakeReq{ +//提取云仓货物 +type TakeReq { + Form []TakeForm `json:"form"` + AddressId int64 `json:"address_id"` +} +type TakeForm { + Id int64 `json:"id"` + Num int64 `json:"num"` } \ No newline at end of file diff --git a/utils/snow_id_generator/snowflake.go b/utils/snow_id_generator/snowflake.go new file mode 100644 index 00000000..465c9e21 --- /dev/null +++ b/utils/snow_id_generator/snowflake.go @@ -0,0 +1,16 @@ +package snow_id_generator + +import ( + "fmt" + "github.com/bwmarrin/snowflake" + "time" +) + +// 雪花算法生成id +func GenSnowId() (string, error) { + node, err := snowflake.NewNode(1) + if err != nil { + return "", err + } + return fmt.Sprintf("%s%s", time.Now().Format("20060102"), node.Generate().Base58()), nil +} From 3a2fb3bc5dda73f04699dfdb1efd04a1beda59e6 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Tue, 27 Jun 2023 14:28:52 +0800 Subject: [PATCH 2/5] fix --- server/inventory/internal/config/config.go | 5 ++++- server/inventory/internal/logic/takelogic.go | 3 +-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/server/inventory/internal/config/config.go b/server/inventory/internal/config/config.go index b24bb7d7..34c626d1 100644 --- a/server/inventory/internal/config/config.go +++ b/server/inventory/internal/config/config.go @@ -1,6 +1,9 @@ package config -import "github.com/zeromicro/go-zero/rest" +import ( + "fusenapi/server/inventory/internal/types" + "github.com/zeromicro/go-zero/rest" +) type Config struct { rest.RestConf diff --git a/server/inventory/internal/logic/takelogic.go b/server/inventory/internal/logic/takelogic.go index b4f9bdbe..799486e5 100644 --- a/server/inventory/internal/logic/takelogic.go +++ b/server/inventory/internal/logic/takelogic.go @@ -11,7 +11,6 @@ import ( "fusenapi/utils/auth" "fusenapi/utils/basic" "fusenapi/utils/snow_id_generator" - "github.com/bwmarrin/snowflake" "gorm.io/gorm" "time" @@ -88,7 +87,7 @@ func (l *TakeLogic) Take(req *types.TakeReq, userinfo *auth.UserInfo) (resp *bas return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, fmt.Sprintf("row %d inventory data`s take num can`be less than 0", k+1)) } //获取库存信息(枷锁) - stockInfo, err := l.svcCtx.AllModels.FsUserStock.FindOne(l.ctx, v.Id, userinfo.UserId, true) + stockInfo, err := l.svcCtx.AllModels.FsUserStock.FindOne(l.ctx, formItem.Id, userinfo.UserId, true) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return resp.SetStatusWithMessage(basic.CodeDbRecordNotFoundErr, fmt.Sprintf("row %d inventory data is not availabled for you", k+1)) From 9050b4ab0edd6287c8ae143261bc88152e81502e Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Tue, 27 Jun 2023 15:26:23 +0800 Subject: [PATCH 3/5] fix --- server/inventory/internal/logic/takelogic.go | 12 +++++------- utils/id_generator/pickup_track_num.go | 13 +++++++++++++ utils/snow_id_generator/snowflake.go | 16 ---------------- 3 files changed, 18 insertions(+), 23 deletions(-) create mode 100644 utils/id_generator/pickup_track_num.go delete mode 100644 utils/snow_id_generator/snowflake.go diff --git a/server/inventory/internal/logic/takelogic.go b/server/inventory/internal/logic/takelogic.go index 799486e5..2abbceee 100644 --- a/server/inventory/internal/logic/takelogic.go +++ b/server/inventory/internal/logic/takelogic.go @@ -10,7 +10,7 @@ import ( "fusenapi/server/inventory/internal/types" "fusenapi/utils/auth" "fusenapi/utils/basic" - "fusenapi/utils/snow_id_generator" + "fusenapi/utils/id_generator" "gorm.io/gorm" "time" @@ -58,11 +58,7 @@ func (l *TakeLogic) Take(req *types.TakeReq, userinfo *auth.UserInfo) (resp *bas //提货单总单 addressInfoBytes, _ := json.Marshal(addressInfo) addressInfoJson := string(addressInfoBytes) - trackNum, err := snow_id_generator.GenSnowId() - if err != nil { - logx.Error(err) - return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to gen trackNum") - } + trackNum := id_generator.GenPickUpTrackNum() status := int64(constants.STATUS_ORDERD) now := time.Now().Unix() pickUpData := gmodel.FsCloudPickUp{ @@ -73,7 +69,6 @@ func (l *TakeLogic) Take(req *types.TakeReq, userinfo *auth.UserInfo) (resp *bas Status: &status, Ctime: &now, } - //开启事务 //箱数验证 boxes := int64(0) //需要更新的库存信息 @@ -121,6 +116,9 @@ func (l *TakeLogic) Take(req *types.TakeReq, userinfo *auth.UserInfo) (resp *bas Ctime: &now, }) } + if boxes < 3 { + return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "Take out more than three boxes") + } //事务处理数据 err = l.svcCtx.AllModels.FsCloudPickUp.SavePickUpWithTransaction(l.ctx, &pickUpData, stockUpdateList, pickUpDetailAddList) if err != nil { diff --git a/utils/id_generator/pickup_track_num.go b/utils/id_generator/pickup_track_num.go new file mode 100644 index 00000000..0e7d3037 --- /dev/null +++ b/utils/id_generator/pickup_track_num.go @@ -0,0 +1,13 @@ +package id_generator + +import ( + "fmt" + "math/rand" + "strings" + "time" +) + +func GenPickUpTrackNum() string { + a := fmt.Sprintf("%s%.8d", time.Now().Format("20060102150405.000"), rand.Intn(1000000)) + return strings.ReplaceAll(a, ".", "") +} diff --git a/utils/snow_id_generator/snowflake.go b/utils/snow_id_generator/snowflake.go deleted file mode 100644 index 465c9e21..00000000 --- a/utils/snow_id_generator/snowflake.go +++ /dev/null @@ -1,16 +0,0 @@ -package snow_id_generator - -import ( - "fmt" - "github.com/bwmarrin/snowflake" - "time" -) - -// 雪花算法生成id -func GenSnowId() (string, error) { - node, err := snowflake.NewNode(1) - if err != nil { - return "", err - } - return fmt.Sprintf("%s%s", time.Now().Format("20060102"), node.Generate().Base58()), nil -} From 66ed48724967d58861147c0b3214a3af96cc5487 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Tue, 27 Jun 2023 17:04:58 +0800 Subject: [PATCH 4/5] fix --- constants/paging.go | 7 + model/gmodel/fs_product_logic.go | 18 ++- model/gmodel/fs_product_model3d_logic.go | 11 ++ model/gmodel/fs_product_size_logic.go | 20 +++ model/gmodel/fs_product_template_v2_logic.go | 10 ++ model/gmodel/fs_user_stock_logic.go | 34 +++-- .../internal/handler/getcloudlisthandler.go | 78 +++++++++++ server/inventory/internal/handler/routes.go | 5 + .../internal/logic/getcloudlistlogic.go | 123 ++++++++++++++++++ server/inventory/internal/types/types.go | 46 +++++++ server_api/basic.api | 8 ++ server_api/inventory.api | 39 ++++++ 12 files changed, 390 insertions(+), 9 deletions(-) create mode 100644 constants/paging.go create mode 100644 server/inventory/internal/handler/getcloudlisthandler.go create mode 100644 server/inventory/internal/logic/getcloudlistlogic.go diff --git a/constants/paging.go b/constants/paging.go new file mode 100644 index 00000000..001a1923 --- /dev/null +++ b/constants/paging.go @@ -0,0 +1,7 @@ +package constants + +// 分页默认当前页 +const DEFAULT_PAGE = 1 + +// 默认每页数量 +const DEFAULT_PAGE_SIZE = 20 diff --git a/model/gmodel/fs_product_logic.go b/model/gmodel/fs_product_logic.go index 255a2e82..92ada4c3 100755 --- a/model/gmodel/fs_product_logic.go +++ b/model/gmodel/fs_product_logic.go @@ -23,7 +23,23 @@ func (p *FsProductModel) GetProductListByIds(ctx context.Context, productIds []i } return } - +func (p *FsProductModel) GetProductListByIdsWithoutStatus(ctx context.Context, productIds []int64, sort string) (resp []FsProduct, err error) { + if len(productIds) == 0 { + return + } + db := p.db.Model(&FsProduct{}).WithContext(ctx). + Where("`id` in (?) ", productIds) + switch sort { + case "sort-asc": + db = db.Order("`sort` ASC") + case "sort-desc": + db = db.Order("`sort` DESC") + } + if err = db.Find(&resp).Error; err != nil { + return nil, err + } + return +} func (p *FsProductModel) GetProductListByTypeIds(ctx context.Context, productTypes []int64, sort string) (resp []FsProduct, err error) { if len(productTypes) == 0 { return diff --git a/model/gmodel/fs_product_model3d_logic.go b/model/gmodel/fs_product_model3d_logic.go index bd95ceb2..c1af4b26 100755 --- a/model/gmodel/fs_product_model3d_logic.go +++ b/model/gmodel/fs_product_model3d_logic.go @@ -19,6 +19,17 @@ func (d *FsProductModel3dModel) GetAllByIds(ctx context.Context, ids []int64, fi err = db.Find(&resp).Error return resp, err } +func (d *FsProductModel3dModel) GetAllByIdsWithoutStatus(ctx context.Context, ids []int64, fields ...string) (resp []FsProductModel3d, err error) { + if len(ids) == 0 { + return + } + db := d.db.WithContext(ctx).Model(&FsProductModel3d{}).Where("`id` in (?)", ids) + if len(fields) > 0 { + db = db.Select(fields[0]) + } + err = db.Find(&resp).Error + return resp, err +} func (d *FsProductModel3dModel) GetAllByIdsTag(ctx context.Context, ids []int64, tag int64) (resp []FsProductModel3d, err error) { if len(ids) == 0 { return diff --git a/model/gmodel/fs_product_size_logic.go b/model/gmodel/fs_product_size_logic.go index bf008f69..ae6f1cf3 100755 --- a/model/gmodel/fs_product_size_logic.go +++ b/model/gmodel/fs_product_size_logic.go @@ -32,6 +32,9 @@ func (s *FsProductSizeModel) CountByStatus(ctx context.Context, status int) (tot return } func (s *FsProductSizeModel) GetAllByProductIds(ctx context.Context, productIds []int64, sort string) (resp []FsProductSize, err error) { + if len(productIds) == 0 { + return nil, nil + } db := s.db.WithContext(ctx).Model(&FsProductSize{}).Where("`product_id` in(?) and `status` = ?", productIds, 1) switch sort { case "sort-asc": @@ -45,6 +48,23 @@ func (s *FsProductSizeModel) GetAllByProductIds(ctx context.Context, productIds } return } +func (s *FsProductSizeModel) GetAllByProductIdsWithoutStatus(ctx context.Context, productIds []int64, sort string) (resp []FsProductSize, err error) { + if len(productIds) == 0 { + return nil, nil + } + db := s.db.WithContext(ctx).Model(&FsProductSize{}).Where("`product_id` in(?)", productIds) + switch sort { + case "sort-asc": + db = db.Order("`sort` ASC") + case "sort-desc": + db = db.Order("`sort` DESC") + } + err = db.Find(&resp).Error + if err != nil { + return nil, err + } + return +} type CapacityId struct { Id int64 `json:"id"` diff --git a/model/gmodel/fs_product_template_v2_logic.go b/model/gmodel/fs_product_template_v2_logic.go index 92289072..dbff11a0 100755 --- a/model/gmodel/fs_product_template_v2_logic.go +++ b/model/gmodel/fs_product_template_v2_logic.go @@ -24,6 +24,16 @@ func (t *FsProductTemplateV2Model) FindAllByIds(ctx context.Context, ids []int64 } return } +func (t *FsProductTemplateV2Model) FindAllByIdsWithoutStatus(ctx context.Context, ids []int64) (resp []FsProductTemplateV2, err error) { + if len(ids) == 0 { + return + } + err = t.db.WithContext(ctx).Model(&FsProductTemplateV2{}).Where("`id` in (?) ", ids).Find(&resp).Error + if err != nil { + return nil, err + } + return +} func (t *FsProductTemplateV2Model) FindOne(ctx context.Context, id int64) (resp *FsProductTemplateV2, err error) { err = t.db.WithContext(ctx).Model(&FsProductTemplateV2{}).Where("`id` = ? ", id).Find(&resp).Error diff --git a/model/gmodel/fs_user_stock_logic.go b/model/gmodel/fs_user_stock_logic.go index f83b3e1c..bc122752 100644 --- a/model/gmodel/fs_user_stock_logic.go +++ b/model/gmodel/fs_user_stock_logic.go @@ -3,19 +3,37 @@ package gmodel import "context" // TODO: 使用model的属性做你想做的 +type GetStockListReq struct { + UserId int64 + Ids []int64 + Status *int64 + Page int + Limit int +} -func (s *FsUserStockModel) GetUserAllStockByIds(ctx context.Context, ids []int64, userId int64) (resp []FsUserStock, err error) { - if len(ids) == 0 { - return nil, nil +func (s *FsUserStockModel) GetStockList(ctx context.Context, req GetStockListReq) (resp []FsUserStock, total int64, err error) { + db := s.db.WithContext(ctx).Model(&FsUserStock{}) + if req.UserId > 0 { + db = db.Where("`user_id` = ?", req.UserId) } - if userId <= 0 { - return nil, nil + if len(req.Ids) > 0 { + db = db.Where("`id` in (?)", req.Ids) } - err = s.db.WithContext(ctx).Model(&FsUserStock{}).Where("`id` in (?) and `user_id` = ?", ids, userId).Find(&resp).Error - return resp, err + if req.Status != nil { + db = db.Where("`status` = ?", *req.Status) + } + 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 + if err != nil { + return nil, 0, err + } + return } func (s *FsUserStockModel) FindOne(ctx context.Context, id int64, userId int64, lock ...bool) (resp *FsUserStock, err error) { - db := s.db.WithContext(ctx).Model(&FsUserStock{}).Where("`id` = ? and `user_id` = ?", id, userId) + db := s.db.WithContext(ctx).Model(&FsUserStock{}).Where("`id` = ? and `user_id` = ? and `status` = ?", id, userId, 1) if len(lock) != 0 && lock[0] { db = db.Set("gorm:query_option", "FOR UPDATE") } diff --git a/server/inventory/internal/handler/getcloudlisthandler.go b/server/inventory/internal/handler/getcloudlisthandler.go new file mode 100644 index 00000000..5d39c8f0 --- /dev/null +++ b/server/inventory/internal/handler/getcloudlisthandler.go @@ -0,0 +1,78 @@ +package handler + +import ( + "errors" + "net/http" + + "github.com/zeromicro/go-zero/core/logx" + "github.com/zeromicro/go-zero/rest/httpx" + + "fusenapi/utils/auth" + "fusenapi/utils/basic" + + "fusenapi/server/inventory/internal/logic" + "fusenapi/server/inventory/internal/svc" + "fusenapi/server/inventory/internal/types" +) + +func GetCloudListHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + + var ( + // 定义错误变量 + err error + // 定义用户信息变量 + userinfo *auth.UserInfo + ) + // 解析JWT token,并对空用户进行判断 + claims, err := svcCtx.ParseJwtToken(r) + // 如果解析JWT token出错,则返回未授权的JSON响应并记录错误消息 + if err != nil { + httpx.OkJsonCtx(r.Context(), w, &basic.Response{ + Code: 401, // 返回401状态码,表示未授权 + Message: "unauthorized", // 返回未授权信息 + }) + logx.Info("unauthorized:", err.Error()) // 记录错误日志 + return + } + + if claims != nil { + // 从token中获取对应的用户信息 + userinfo, err = auth.GetUserInfoFormMapClaims(claims) + // 如果获取用户信息出错,则返回未授权的JSON响应并记录错误消息 + if err != nil { + httpx.OkJsonCtx(r.Context(), w, &basic.Response{ + Code: 401, + Message: "unauthorized", + }) + logx.Info("unauthorized:", err.Error()) + return + } + } else { + // 如果claims为nil,则认为用户身份为白板用户 + userinfo = &auth.UserInfo{UserId: 0, GuestId: 0} + } + + var req types.GetCloudListReq + // 如果端点有请求结构体,则使用httpx.Parse方法从HTTP请求体中解析请求数据 + if err := httpx.Parse(r, &req); err != nil { + httpx.OkJsonCtx(r.Context(), w, &basic.Response{ + Code: 510, + Message: "parameter error", + }) + logx.Info(err) + return + } + // 创建一个业务逻辑层实例 + l := logic.NewGetCloudListLogic(r.Context(), svcCtx) + resp := l.GetCloudList(&req, userinfo) + // 如果响应不为nil,则使用httpx.OkJsonCtx方法返回JSON响应; + if resp != nil { + httpx.OkJsonCtx(r.Context(), w, resp) + } else { + err := errors.New("server logic is error, resp must not be nil") + httpx.ErrorCtx(r.Context(), w, err) + logx.Error(err) + } + } +} diff --git a/server/inventory/internal/handler/routes.go b/server/inventory/internal/handler/routes.go index 8122eebb..f71306ed 100644 --- a/server/inventory/internal/handler/routes.go +++ b/server/inventory/internal/handler/routes.go @@ -17,6 +17,11 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { Path: "/inventory/take", Handler: TakeHandler(serverCtx), }, + { + Method: http.MethodGet, + Path: "/inventory/list", + Handler: GetCloudListHandler(serverCtx), + }, }, ) } diff --git a/server/inventory/internal/logic/getcloudlistlogic.go b/server/inventory/internal/logic/getcloudlistlogic.go new file mode 100644 index 00000000..880d15fc --- /dev/null +++ b/server/inventory/internal/logic/getcloudlistlogic.go @@ -0,0 +1,123 @@ +package logic + +import ( + "fusenapi/constants" + "fusenapi/model/gmodel" + "fusenapi/utils/auth" + "fusenapi/utils/basic" + + "context" + + "fusenapi/server/inventory/internal/svc" + "fusenapi/server/inventory/internal/types" + + "github.com/zeromicro/go-zero/core/logx" +) + +type GetCloudListLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +func NewGetCloudListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetCloudListLogic { + return &GetCloudListLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *GetCloudListLogic) GetCloudList(req *types.GetCloudListReq, userinfo *auth.UserInfo) (resp *basic.Response) { + if userinfo.GetIdType() != auth.IDTYPE_User { + return resp.SetStatusWithMessage(basic.CodeServiceErr, "please login first") + } + if req.Page <= 0 { + req.Page = constants.DEFAULT_PAGE + } + if req.PageSize <= 0 || req.PageSize > 200 { + req.Page = constants.DEFAULT_PAGE_SIZE + } + //获取个人云仓列表 + stockList, total, err := l.svcCtx.AllModels.FsUserStock.GetStockList(l.ctx, gmodel.GetStockListReq{ + UserId: userinfo.UserId, + Page: int(req.Page), + Limit: int(req.PageSize), + }) + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get user stock list") + } + if len(stockList) == 0 { + return resp.SetStatusWithMessage(basic.CodeOK, "success", types.GetCloudListRsp{ + ListData: []types.ListDataItem{}, + }) + } + designIds := make([]int64, 0, len(stockList)) + for _, v := range stockList { + designIds = append(designIds, *v.DesignId) + } + //获取设计数据 + productDesignList, err := l.svcCtx.AllModels.FsProductDesign.GetAllByIds(l.ctx, designIds) + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get product design list") + } + //尺寸ids + sizeIds := make([]int64, 0, len(productDesignList)) + //产品ids + productIds := make([]int64, 0, len(productDesignList)) + //模板ids + templateIds := make([]int64, 0, len(productDesignList)) + //配件ids + optionalIds := make([]int64, 0, len(productDesignList)) + mapProductDesign := make(map[int64]int) + for k, v := range productDesignList { + sizeIds = append(sizeIds, *v.SizeId) + productIds = append(productIds, *v.ProductId) + templateIds = append(templateIds, *v.TemplateId) + optionalIds = append(optionalIds, *v.OptionalId) + mapProductDesign[v.Id] = k + } + //获取尺寸信息 + sizeList, err := l.svcCtx.AllModels.FsProductSize.GetAllByProductIdsWithoutStatus(l.ctx, sizeIds, "") + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get product size list") + } + mapSize := make(map[int64]int) + for k, v := range sizeList { + mapSize[v.Id] = k + } + //获取产品信息 + productList, err := l.svcCtx.AllModels.FsProduct.GetProductListByIdsWithoutStatus(l.ctx, productIds, "") + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get product list") + } + mapProduct := make(map[int64]int) + for k, v := range productList { + mapProduct[v.Id] = k + } + //获取模板信息 + productTemplateList, err := l.svcCtx.AllModels.FsProductTemplateV2.FindAllByIdsWithoutStatus(l.ctx, templateIds) + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get product template list") + } + mapTemplate := make(map[int64]int) + for k, v := range productTemplateList { + mapTemplate[v.Id] = k + } + //获取配件列表 + productModel3dList, err := l.svcCtx.AllModels.FsProductModel3d.GetAllByIdsWithoutStatus(l.ctx, optionalIds) + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get product 3d model list") + } + mapProductModel := make(map[int64]int) + for k, v := range productModel3dList { + mapProductModel[v.Id] = k + } + return resp.SetStatus(basic.CodeOK) +} diff --git a/server/inventory/internal/types/types.go b/server/inventory/internal/types/types.go index 02ad0eb0..c7fc0c67 100644 --- a/server/inventory/internal/types/types.go +++ b/server/inventory/internal/types/types.go @@ -15,6 +15,45 @@ type TakeForm struct { Num int64 `json:"num"` } +type GetCloudListReq struct { + Page int64 `json:"page"` + PageSize int64 `json:"page_size"` + Size int64 `json:"size"` +} + +type GetCloudListRsp struct { + WarehouseBoxes int64 `json:"warehouse_boxes"` + TransitBoxes int64 `json:"transit_boxes"` + MinTakeNum int64 `json:"minTakeNum"` + ListData []ListDataItem `json:"listData"` + Pagnation Pagnation `json:"pagnation"` +} + +type ListDataItem struct { + Id int64 `json:"id"` + Sn string `json:"sn"` + Cover string `json:"cover"` + Name string `json:"name"` + DesignSn string `json:"design_sn"` + Fitting string `json:"fitting"` + Production int64 `json:"production"` + ProductionBox int64 `json:"production_box"` + EachBoxNum int64 `json:"each_box_num"` + Stick int64 `json:"stick"` + StickBox int64 `json:"stick_box"` + Type int64 `json:"type"` + TakeNum int64 `json:"takeNum"` + Size string `json:"size"` + IsStop int64 `json:"is_stop"` + PriceList []PriceItem `json:"price"` +} + +type PriceItem struct { + Num int `json:"num"` + TotalNum int `json:"total_num"` + Price int `json:"price"` +} + type Request struct { } @@ -30,6 +69,13 @@ type Auth struct { RefreshAfter int64 `json:"refreshAfter"` } +type Pagnation struct { + TotalCount int64 `json:"total_count"` + TotalPage int64 `json:"total_page"` + CurPage int64 `json:"cur_page"` + PageSize int64 `json:"page_size"` +} + // Set 设置Response的Code和Message值 func (resp *Response) Set(Code int, Message string) *Response { return &Response{ diff --git a/server_api/basic.api b/server_api/basic.api index 5c84f3c7..a827855d 100644 --- a/server_api/basic.api +++ b/server_api/basic.api @@ -25,3 +25,11 @@ type Auth { RefreshAfter int64 `json:"refreshAfter"` } +// 统一分页 +type Pagnation{ + TotalCount int64 `json:"total_count"` + TotalPage int64 `json:"total_page"` + CurPage int64 `json:"cur_page"` + PageSize int64 `json:"page_size"` +} + diff --git a/server_api/inventory.api b/server_api/inventory.api index 3bea4665..0e9908eb 100644 --- a/server_api/inventory.api +++ b/server_api/inventory.api @@ -12,6 +12,9 @@ service inventory { //提取云仓货物 @handler TakeHandler post /inventory/take(TakeReq) returns (response); + //获取云仓库存列表 + @handler GetCloudListHandler + get /inventory/list(GetCloudListReq) returns (response); } //提取云仓货物 @@ -22,4 +25,40 @@ type TakeReq { type TakeForm { Id int64 `json:"id"` Num int64 `json:"num"` +} +//获取云仓库存列表 +type GetCloudListReq { + Page int64 `json:"page"` + PageSize int64 `json:"page_size"` + Size int64 `json:"size"` +} +type GetCloudListRsp { + WarehouseBoxes int64 `json:"warehouse_boxes"` + TransitBoxes int64 `json:"transit_boxes"` + MinTakeNum int64 `json:"minTakeNum"` + ListData []ListDataItem `json:"listData"` + Pagnation Pagnation `json:"pagnation"` +} +type ListDataItem { + Id int64 `json:"id"` + Sn string `json:"sn"` + Cover string `json:"cover"` + Name string `json:"name"` + DesignSn string `json:"design_sn"` + Fitting string `json:"fitting"` + Production int64 `json:"production"` + ProductionBox int64 `json:"production_box"` + EachBoxNum int64 `json:"each_box_num"` + Stick int64 `json:"stick"` + StickBox int64 `json:"stick_box"` + Type int64 `json:"type"` + TakeNum int64 `json:"takeNum"` + Size string `json:"size"` + IsStop int64 `json:"is_stop"` + PriceList []PriceItem `json:"price"` +} +type PriceItem { + Num int `json:"num"` + TotalNum int `json:"total_num"` + Price int `json:"price"` } \ No newline at end of file From 84088a7a12d6da277887e35ff5e76a6e8c8b64c2 Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Tue, 27 Jun 2023 17:47:44 +0800 Subject: [PATCH 5/5] fix --- .../internal/logic/getcloudlistlogic.go | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/server/inventory/internal/logic/getcloudlistlogic.go b/server/inventory/internal/logic/getcloudlistlogic.go index 880d15fc..47be6dd1 100644 --- a/server/inventory/internal/logic/getcloudlistlogic.go +++ b/server/inventory/internal/logic/getcloudlistlogic.go @@ -5,6 +5,8 @@ import ( "fusenapi/model/gmodel" "fusenapi/utils/auth" "fusenapi/utils/basic" + "fusenapi/utils/format" + "strings" "context" @@ -119,5 +121,34 @@ func (l *GetCloudListLogic) GetCloudList(req *types.GetCloudListReq, userinfo *a for k, v := range productModel3dList { mapProductModel[v.Id] = k } + //根据产品ids获取产品价格 + priceList, err := l.svcCtx.AllModels.FsProductPrice.GetPriceListByProductIds(l.ctx, productIds) + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get product price list") + } + for _, v := range priceList { + if *v.StepNum == "" || *v.StepPrice == "" { + return resp.SetStatusWithMessage(basic.CodeServiceErr, "price data`s step num or step price is empty") + } + stepNum, err := format.StrSlicToIntSlice(strings.Split(*v.StepNum, ",")) + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeServiceErr, "parse step num err") + } + lenStepNum := len(stepNum) + stepPrice, err := format.StrSlicToIntSlice(strings.Split(*v.StepPrice, ",")) + if err != nil { + logx.Error(err) + return resp.SetStatusWithMessage(basic.CodeServiceErr, "parse step price err") + } + lenStepPrice := len(stepPrice) + for *v.MinBuyNum < int64(stepPrice[lenStepPrice-1]+5) { + //根据材质,尺寸,价格计算阶梯价 + + *v.MinBuyNum++ + } + + } return resp.SetStatus(basic.CodeOK) }