From 6d93a6e65d04dc501678a18cf49b7bad1c8fecc3 Mon Sep 17 00:00:00 2001 From: li Date: Fri, 6 Jan 2023 10:03:56 +0800 Subject: [PATCH] fix: --- controller/erp_retail.go | 326 +++++++++ go.mod | 2 +- go.sum | 7 +- model/cashier.go | 52 ++ model/commodity.go | 1467 +++++++++++++++++++++++++++++++++++++ model/erp_retail_order.go | 276 +++++++ model/user.go | 4 +- router/router_app.go | 11 + 8 files changed, 2140 insertions(+), 5 deletions(-) create mode 100644 controller/erp_retail.go create mode 100644 model/cashier.go create mode 100644 model/commodity.go create mode 100644 model/erp_retail_order.go diff --git a/controller/erp_retail.go b/controller/erp_retail.go new file mode 100644 index 0000000..5728c8a --- /dev/null +++ b/controller/erp_retail.go @@ -0,0 +1,326 @@ +package controller + +import ( + "encoding/json" + "github.com/codinl/go-logger" + "github.com/gin-gonic/gin" + "mh-server/lib/auth" + "mh-server/lib/status" + "time" + + "mh-server/model" +) + +func ErpOrderList(c *gin.Context) { + req := &model.ErpOrderListReq{} + if err := c.ShouldBindJSON(&req); err != nil { + logger.Error(err) + RespJson(c, status.BadRequest, nil) + return + } + + resp, err := req.List() + if err != nil { + logger.Error("erp commodity list err:", err) + RespJson(c, status.InternalServerError, nil) + return + } + + RespOK(c, resp) + return +} + +func ErpOrderCreate(c *gin.Context) { + req := struct { + //StoreId uint32 `json:"store_id"` + Cashiers []model.ErpCashier `json:"cashiers" binding:"required"` + Salesman1 uint32 `json:"salesman_1" binding:"required"` + Salesman2 uint32 `json:"salesman_2"` + RetailType string `json:"retail_type" binding:"required"` + Tel string `json:"tel" binding:"required"` + MemberType string `json:"member_type"` // 会员类型: + ErpOrderCommodities []model.ErpOrderCommodity `json:"erp_order_commodities"` + }{} + if err := c.ShouldBindJSON(&req); err != nil { + logger.Error(err) + RespJson(c, status.BadRequest, nil) + return + } + + if len(req.Cashiers) == 0 { + logger.Error("cashiers is nil") + RespJson(c, status.BadRequest, nil) + return + } + if len(req.ErpOrderCommodities) == 0 { + logger.Error("commodities is nil") + RespJson(c, status.BadRequest, nil) + return + } + jCashier, err := json.Marshal(req.Cashiers) + if err != nil { + logger.Error("cashiers marshal err:", err) + RespJson(c, status.InternalServerError, nil) + return + } + + uc := auth.GetCurrentUser(c) + if uc == nil { + logger.Error("uc is nil") + RespJson(c, status.Unauthorized, nil) + return + } + + //uc = &auth.UserClaims{Uid: 8588420} + assistant := model.GetUserByUid(uc.Uid) + if assistant.UserType != 2 { + logger.Error("not assistant") + RespJson(c, status.InternalServerError, nil) + return + } + store, err := model.GetStore(uint32(assistant.StoreId)) + if err != nil { + logger.Error("assistant store err:", err) + RespJson(c, status.InternalServerError, nil) + return + } + erpOrder := &model.ErpOrder{ + BillSn: model.NewErpBillSn(), + RetailType: req.RetailType, + Tel: req.Tel, + StoreId: uint32(assistant.StoreId), + StoreName: store.Name, + MakerId: uint32(assistant.Uid), + MakerName: assistant.ShopAssistantName, + AuditTime: time.Now(), + AuditorId: assistant.Uid, + AuditorName: assistant.ShopAssistantName, + CashierList: string(jCashier), + Salesman1: req.Salesman1, + Salesman2: req.Salesman2, + MemberType: req.MemberType, + State: model.ErpOrderStateUnAudit, + } + + commodityMap := make(map[uint32]model.ErpCommodity) + if req.RetailType == model.RetailTypeSale { + commodityIds := make([]uint32, 0, len(req.ErpOrderCommodities)) + for i, _ := range req.ErpOrderCommodities { + commodityIds = append(commodityIds, req.ErpOrderCommodities[i].ErpCommodityId) + } + var commodities []model.ErpCommodity + err = model.DB.Table("erp_commodity").Where("id IN (?)", commodityIds).Find(&commodities).Error + if err != nil { + logger.Error("commodities err:", err) + RespJson(c, status.InternalServerError, nil) + return + } + + for i, _ := range commodities { + commodityMap[commodities[i].ID] = commodities[i] + } + + model.SetUserInfo(req.Tel) + } + + var orderCommodityMap map[uint32]model.ErpOrderCommodity + if req.RetailType == model.RetailTypeRejected { + ids := make([]uint32, 0, len(req.ErpOrderCommodities)) + for i, _ := range req.ErpOrderCommodities { + ids = append(ids, req.ErpOrderCommodities[i].RejectedOrderCommodityId) + } + orderCommodityMap, err = model.GetErpOrderCommodityMap(ids) + if err != nil { + logger.Error("order commodity map err:", err) + return + } + } + + begin := model.DB.Begin() + err = begin.Create(erpOrder).Error + if err != nil { + begin.Rollback() + logger.Error("create erp order err:", err) + RespJson(c, status.InternalServerError, nil) + return + } + + for i, _ := range req.ErpOrderCommodities { + req.ErpOrderCommodities[i].ErpOrderId = erpOrder.ID + + if req.RetailType == model.RetailTypeRejected { + v, ok := orderCommodityMap[req.ErpOrderCommodities[i].RejectedOrderCommodityId] + if ok { + v.RejectedPrice = req.ErpOrderCommodities[i].RejectedPrice + v.RejectedCount = req.ErpOrderCommodities[i].RejectedCount + v.RejectedAmount = v.RejectedCount * v.RejectedPrice + } else { + logger.Error("rejected order commodity id is null") + return + } + v.ID = 0 + req.ErpOrderCommodities[i] = v + // 添加库存 TODO + if req.ErpOrderCommodities[i].RejectedPrice > req.ErpOrderCommodities[i].RetailPrice { + logger.Error("rejected price gt retail price ") + RespJson(c, status.InternalServerError, nil) + return + } + if req.ErpOrderCommodities[i].RejectedCount > req.ErpOrderCommodities[i].Count { + logger.Error("rejected count gt retail count ") + RespJson(c, status.InternalServerError, nil) + return + } + + } else if req.RetailType == model.RetailTypeSale { + + v, ok := commodityMap[req.ErpOrderCommodities[i].ErpCommodityId] + if ok { + req.ErpOrderCommodities[i].ErpCommodityName = v.Name + req.ErpOrderCommodities[i].ErpCategoryId = v.ErpCategoryId + req.ErpOrderCommodities[i].ErpCategoryName = v.ErpCategoryName + req.ErpOrderCommodities[i].RetailPrice = v.RetailPrice + //req.ErpOrderCommodities[i].MemberPrice = v.MemberPrice + } + if req.ErpOrderCommodities[i].PresentType == 2 { + req.ErpOrderCommodities[i].RetailPrice = 0 + } + + // 减库存 TODO + if erpOrder.MemberType == model.ErpOrderMemberTypeMember { + req.ErpOrderCommodities[i].Amount = req.ErpOrderCommodities[i].Count * req.ErpOrderCommodities[i].MemberPrice + } else { + req.ErpOrderCommodities[i].Amount = req.ErpOrderCommodities[i].Count * req.ErpOrderCommodities[i].RetailPrice + } + } + + erpOrder.TotalAmount += req.ErpOrderCommodities[i].Amount + erpOrder.TotalCount += req.ErpOrderCommodities[i].Count + } + + err = begin.Create(&req.ErpOrderCommodities).Error + if err != nil { + begin.Rollback() + logger.Error("Create") + RespJson(c, status.InternalServerError, nil) + return + } + err = begin.Commit().Error + if err != nil { + begin.Rollback() + logger.Error("commit err:", err) + RespJson(c, status.InternalServerError, nil) + return + } + erpOrder.Commodities = req.ErpOrderCommodities + erpOrder.Cashiers = req.Cashiers + + RespOK(c, erpOrder) + return +} + +func ErpOrderDetail(c *gin.Context) { + req := &struct { + ErpOrderId uint32 `json:"erp_order_id"` + }{} + if err := c.ShouldBindJSON(&req); err != nil { + logger.Error(err) + RespJson(c, status.BadRequest, nil) + return + } + var order model.ErpOrder + err := model.DB.Table("erp_order").Where("id = ?", req.ErpOrderId).Find(&order).Error + if err != nil { + logger.Error("order err:", err) + RespJson(c, status.InternalServerError, nil) + return + } + var orderCommodities []model.ErpOrderCommodity + err = model.DB.Table("erp_order_commodity").Where("erp_order_id=?", req.ErpOrderId).Find(&orderCommodities).Error + if err != nil { + logger.Error("order commodities err:", err) + RespJson(c, status.InternalServerError, nil) + return + } + order.Commodities = orderCommodities + order.SetErpCashier() + + RespOK(c, order) + return +} + +func ErpOrderCommodityList(c *gin.Context) { + req := &struct { + Tel string `json:"tel"` + IMEI string `json:"imei"` + ErpCommodityName string `json:"erp_commodity_name"` + }{} + if err := c.ShouldBindJSON(&req); err != nil { + logger.Error(err) + RespJson(c, status.BadRequest, nil) + return + } + + var commodities []model.ErpOrderCommodity + qs := model.DB.Table("erp_order_commodity") + if req.Tel != "" { + qs = qs.Where("tel=?", req.Tel) + } + if req.IMEI != "" { + qs = qs.Where("imei=?", req.IMEI) + } + if req.ErpCommodityName != "" { + qs = qs.Where("erp_commodity_name=?", req.ErpCommodityName) + } + err := qs.Order("id DESC").Find(&commodities).Error + if err != nil { + logger.Error("erp commodity list err:", err) + RespJson(c, status.InternalServerError, nil) + return + } + + RespOK(c, commodities) + return +} + +func ShopAssistantList(c *gin.Context) { + req := &struct { + StoreId uint32 `json:"store_id"` + }{} + if err := c.ShouldBindJSON(&req); err != nil { + logger.Error(err) + RespJson(c, status.BadRequest, nil) + return + } + + uc := auth.GetCurrentUser(c) + if uc == nil { + logger.Error("uc is nil") + RespJson(c, status.Unauthorized, nil) + return + } + + //uc = &auth.UserClaims{Uid: 8588420} + assistant := model.GetUserByUid(uc.Uid) + if assistant.UserType != 2 { + logger.Error("not assistant") + RespJson(c, status.InternalServerError, nil) + return + } + req.StoreId = uint32(assistant.StoreId) + var users []model.User + qs := model.DB.Table("user").Where("user_type=2") + if req.StoreId != 0 { + qs = qs.Where("store_id=?", req.StoreId) + } + + err := qs.Order("id DESC").Find(&users).Error + if err != nil { + logger.Error("erp commodity list err:", err) + RespJson(c, status.InternalServerError, nil) + return + } + + RespOK(c, users) + return +} diff --git a/go.mod b/go.mod index 57cfcd3..41bc992 100644 --- a/go.mod +++ b/go.mod @@ -16,11 +16,11 @@ require ( github.com/qiniu/x v7.0.8+incompatible // indirect github.com/rs/zerolog v1.23.0 github.com/satori/go.uuid v1.2.0 // indirect - github.com/shopspring/decimal v1.3.1 github.com/spf13/cobra v1.1.3 github.com/spf13/viper v1.7.1 github.com/wechatpay-apiv3/wechatpay-go v0.2.6 github.com/xuri/excelize/v2 v2.6.0 golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9 + gorm.io/gorm v1.24.3 qiniupkg.com/x v7.0.8+incompatible // indirect ) diff --git a/go.sum b/go.sum index 05f9297..30a07ba 100644 --- a/go.sum +++ b/go.sum @@ -136,8 +136,9 @@ github.com/jinzhu/gorm v1.9.16 h1:+IyIjPEABKRpsu/F8OvDPy9fyQlgsg2luMV2ZIH5i5o= github.com/jinzhu/gorm v1.9.16/go.mod h1:G3LB3wezTOWM2ITLzPxEXgSkOXAntiLHS7UdBefADcs= github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= -github.com/jinzhu/now v1.0.1 h1:HjfetcXq097iXP0uoPCdnM4Efp5/9MsM0/M+XOTeR3M= github.com/jinzhu/now v1.0.1/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +github.com/jinzhu/now v1.1.4 h1:tHnRBy1i5F2Dh8BAFxqFzxKqqvezXrL2OW1TnX+Mlas= +github.com/jinzhu/now v1.1.4/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/json-iterator/go v1.1.9 h1:9yzud/Ht36ygwatGx56VwCZtlI/2AD15T1X2sjSuGns= @@ -227,8 +228,6 @@ github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb github.com/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww= github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= -github.com/shopspring/decimal v1.3.1 h1:2Usl1nmF/WZucqkFZhnfFYxxxu8LG21F6nPQBE5gKV8= -github.com/shopspring/decimal v1.3.1/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM= @@ -438,6 +437,8 @@ gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gorm.io/gorm v1.24.3 h1:WL2ifUmzR/SLp85CSURAfybcHnGZ+yLSGSxgYXlFBHg= +gorm.io/gorm v1.24.3/go.mod h1:DVrVomtaYTbqs7gB/x2uVvqnXzv0nqjB396B8cG4dBA= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/model/cashier.go b/model/cashier.go new file mode 100644 index 0000000..bcdd096 --- /dev/null +++ b/model/cashier.go @@ -0,0 +1,52 @@ +package model + +//go:generate goqueryset -in cashier.go +// gen:qs +type ErpCashier struct { + Model + + Name string `json:"name" gorm:"type:varchar(512)"` + BankName string `json:"bank_name" gorm:"type:varchar(512)"` + BankAccount string `json:"bank_account" gorm:"type:varchar(512)"` + State uint32 `json:"state"` // 状态:1-使用 2-未用 + Remark string `json:"remark" gorm:"type:varchar(512)"` + Type uint32 `json:"type"` // + //Description string `json:"description"` + // erp_cashier +} + +// gen:qs +type ErpStoreCashier struct { + Model + + ErpCashierId uint32 `json:"erp_cashier_id" gorm:"index"` + Name string `json:"name" gorm:"type:varchar(512)"` + BankName string `json:"bank_name" gorm:"type:varchar(512)"` + BankAccount string `json:"bank_account" gorm:"type:varchar(512)"` + StoreId uint32 `json:"store_id" gorm:"index"` + StoreName string `json:"store_name"` + State uint32 `json:"state"` // 状态:1-使用 2-未用 + Remark string `json:"remark" gorm:"type:varchar(512)"` + // erp_store_cashier +} + +type PayModeInfo struct { + StoreCashierId uint32 `json:"store_cashier_id"` + Amount uint32 `json:"amount"` + StoreCashier ErpStoreCashier `json:"store_cashier" gorm:"-"` +} + +type ErpCashierStoreListResp struct { + Total int `json:"total"` + PageNum int `json:"page_num"` + PageSize int `json:"page_size"` + List []ErpStoreCashier `json:"list"` + ExportUrl string `json:"export_url"` +} + +type ErpCashierListResp struct { + Total int `json:"total"` + PageNum int `json:"page_num"` + PageSize int `json:"page_size"` + List []ErpCashier `json:"list"` +} diff --git a/model/commodity.go b/model/commodity.go new file mode 100644 index 0000000..c03c862 --- /dev/null +++ b/model/commodity.go @@ -0,0 +1,1467 @@ +package model + +import ( + "time" +) + +//go:generate goqueryset -in commodity.go +// gen:qs +type ErpStock struct { + Model + + StoreId uint32 `json:"store_id" gorm:"index"` + StoreName string `json:"store_name"` + ErpCommodityId uint32 `json:"erp_commodity_id" gorm:"index"` + ErpCommodityName string `json:"erp_commodity_name"` + ErpCategoryId uint32 `json:"erp_category_id" gorm:"index"` + ErpCategoryName string `json:"erp_category_name"` + CommoditySerialNumber string `json:"commodity_serial_number" gorm:"index"` + IMEIType uint32 `json:"imei_type"` // 1-无串码 2-串码 + RetailPrice uint32 `json:"retail_price"` + MinRetailPrice uint32 `json:"min_retail_price"` + Count uint32 `json:"count"` + DispatchCount uint32 `json:"dispatch_count"` + //ErpSupplierId uint32 `json:"erp_supplier_id" gorm:"index"` + //ErpSupplierName string `json:"erp_supplier_name"` + //IMEI string `json:"imei"` + //StockTime time.Time `json:"stock_time"` + //StaffCostPrice uint32 `json:"staff_cost_price"` + //WholesalePrice uint32 `json:"wholesale_price"` + //OriginalSn string `json:"original_sn" gorm:"index"` + Commodities []ErpStockCommodity `json:"commodities" gorm:"-"` + + // erp_stock +} + +// gen:qs +type ErpStockCommodity struct { + Model + + ErpStockId uint32 `json:"erp_stock_id" gorm:"index"` + StoreId uint32 `json:"store_id" gorm:"index"` + StoreName string `json:"store_name"` + ErpCommodityId uint32 `json:"erp_commodity_id" gorm:"index"` + ErpCommodityName string `json:"erp_commodity_name"` + CommoditySerialNumber string `json:"commodity_serial_number" gorm:"index"` + ErpCategoryId uint32 `json:"erp_category_id" gorm:"index"` + ErpCategoryName string `json:"erp_category_name"` + IMEIType uint32 `json:"imei_type"` // 1-无串码 2-串码 + IMEI string `json:"imei"` + ErpSupplierId uint32 `json:"erp_supplier_id" gorm:"index"` + ErpSupplierName string `json:"erp_supplier_name"` + StockTime time.Time `json:"stock_time"` + RetailPrice uint32 `json:"retail_price"` + MinRetailPrice uint32 `json:"min_retail_price"` + StaffCostPrice uint32 `json:"staff_cost_price"` + WholesalePrice uint32 `json:"wholesale_price"` + OriginalSn string `json:"original_sn" gorm:"index"` + State uint32 `json:"state"` // 状态:1-在库 2-已售 3-采购退货 4-调拨中 + Count uint32 `json:"count"` + StockSn string `json:"stock_sn"` + StorageType uint32 `json:"storage_type"` //1-系统入库 2-采购入库 + FirstStockTime time.Time `json:"first_stock_time"` + Age uint32 `json:"age" gorm:"-"` + AllAge uint32 `json:"all_age" gorm:"-"` + + //DispatchCount uint32 `json:"dispatch_count"` + // erp_stock_commodity +} + +// gen:qs +type ErpCommodity struct { + Model + + SerialNumber string `json:"serial_number"` + Number uint32 `json:"number"` + Name string `json:"name"` + ErpCategoryId uint32 `json:"erp_category_id" gorm:"index"` + ErpCategoryName string `json:"erp_category_name"` + IMEIType uint32 `json:"imei_type"` // 1-无串码 2-串码 + IMEI string `json:"imei"` + ErpSupplierId uint32 `json:"erp_supplier_id" gorm:"index"` + ErpSupplierName string `json:"erp_supplier_name"` + RetailPrice uint32 `json:"retail_price"` + MinRetailPrice uint32 `json:"min_retail_price"` + StaffCostPrice uint32 `json:"staff_cost_price"` + WholesalePrice uint32 `json:"wholesale_price"` + Brokerage1 float64 `json:"brokerage_1"` + Brokerage2 float64 `json:"brokerage_2"` + MemberDiscount float64 `json:"member_discount"` // 会员优惠 + Origin string `json:"origin"` + Remark string `json:"remark" gorm:"type:varchar(512)"` + + ErpCategory *ErpCategory `json:"erp_category" gorm:"-"` + // erp_commodity +} + +// gen:qs +type ErpCategory struct { + Model + + Name string `json:"name"` // 名称 + Priority string `json:"priority"` // 分类 + Number uint32 `json:"number"` + FullNum uint32 `json:"full_num"` + State uint32 `json:"state"` // 1-未使用 2-使用 3-隐藏 + Level uint32 `json:"level"` // 分类层级 + Pid uint32 `json:"pid" gorm:"index"` + Sort uint32 `json:"sort"` + SubCats []ErpCategory `json:"sub_cats" gorm:"-"` // 子列表 + // erp_category +} + +// gen:qs +type ErpSupplier struct { + Model + + Number string `json:"number" gorm:"index"` + Name string `json:"name"` + Contact string `json:"contact"` + Tel string `json:"tel"` + Address string `json:"address"` + OpeningBank string `json:"opening_bank"` + BankAccount string `json:"bank_account"` + PaymentCycle uint32 `json:"payment_cycle"` + TaxNumber string `json:"tax_number"` + StoreIds string `json:"store_ids"` + Landline string `json:"landline"` + Email string `json:"email"` + CompanyWebsite string `json:"company_website"` + // erp_supplier +} + +// gen:qs +type ErpInventoryStock struct { + Model + + StoreId uint32 `json:"store_id" gorm:"index"` + StoreName string `json:"store_name"` + ErpCommodityId uint32 `json:"erp_commodity_id" gorm:"index"` + ErpCommodityName string `json:"erp_commodity_name"` + ErpCategoryId uint32 `json:"erp_category_id" gorm:"index"` + ErpCategoryName string `json:"erp_category_name"` + CommoditySerialNumber string `json:"commodity_serial_number" gorm:"index"` + IMEIType uint32 `json:"imei_type"` // 1-无串码 2-串码 + RetailPrice uint32 `json:"retail_price"` + MinRetailPrice uint32 `json:"min_retail_price"` + Count uint32 `json:"count"` + Sn string `json:"sn" gorm:"index"` + //ErpSupplierId uint32 `json:"erp_supplier_id" gorm:"index"` + //ErpSupplierName string `json:"erp_supplier_name"` + //IMEI string `json:"imei"` + //StockTime time.Time `json:"stock_time"` + //StaffCostPrice uint32 `json:"staff_cost_price"` + //WholesalePrice uint32 `json:"wholesale_price"` + // erp_inventory_stock +} + +// gen:qs +type ErpInventoryStockCommodity struct { + Model + + ErpInventoryStockId uint32 `json:"erp_inventory_stock_id" gorm:"index"` + ErpCommodityId uint32 `json:"erp_commodity_id" gorm:"index"` + ErpCommodityName string `json:"erp_commodity_name"` + CommoditySerialNumber string `json:"commodity_serial_number" gorm:"index"` + IMEIType uint32 `json:"imei_type"` // 1-无串码 2-串码 + IMEI string `json:"imei"` + ErpSupplierId uint32 `json:"erp_supplier_id" gorm:"index"` + ErpSupplierName string `json:"erp_supplier_name"` + StockTime time.Time `json:"stock_time"` + RetailPrice uint32 `json:"retail_price"` + MinRetailPrice uint32 `json:"min_retail_price"` + StaffCostPrice uint32 `json:"staff_cost_price"` + WholesalePrice uint32 `json:"wholesale_price"` + Count uint32 `json:"count"` + StorageType uint32 `json:"storage_type"` + Sn string `json:"sn" gorm:"index"` + //StoreId uint32 `json:"store_id" gorm:"index"` + //StoreName string `json:"store_name"` + //ErpCategoryId uint32 `json:"erp_category_id" gorm:"index"` + //ErpCategoryName string `json:"erp_category_name"` + // erp_inventory_stock_commodity +} + +//func (c *ErpCommodity) IdInit() { +// if c.ErpCategoryId != 0 { +// if c.ErpCategory == nil { +// category, err := GetErpCategory(c.ErpCategoryId) +// if err != nil { +// logger.Error("get erp category err:", err) +// return +// } +// c.ErpCategory = category +// } +// c.ErpCategoryName = c.ErpCategory.Name +// } +// +// if c.ErpSupplierId != 0 { +// supplier, err := GetErpSupplier(c.ErpSupplierId) +// if err != nil { +// logger.Error("get erp category err:", err) +// } else { +// c.ErpSupplierName = supplier.Name +// } +// } +//} + +//func GetErpCategory(id uint32) (*ErpCategory, error) { +// category := new(ErpCategory) +// err := orm.Eloquent.Table("erp_category").Where("id=?", id).Find(category).Error +// if err != nil { +// logger.Error("category err:", err) +// return category, err +// } +// return category, nil +//} +// +//func GetErpSupplier(id uint32) (*ErpSupplier, error) { +// supplier := new(ErpSupplier) +// err := orm.Eloquent.Table("erp_supplier").Where("id=?", id).Find(supplier).Error +// if err != nil { +// logger.Error("category err:", err) +// return supplier, err +// } +// return supplier, err +//} + +//func (c *ErpCommodity) SetErpCategory() error { +// if c.ErpCategoryId != 0 { +// category, err := GetErpCategory(c.ErpCategoryId) +// if err != nil { +// logger.Error("get erp category err:", err) +// return err +// } +// c.ErpCategory = category +// return nil +// } +// return errors.New("erp category id null") +//} + +//type ErpCommodityListReq struct { +// SerialNumber string `json:"serial_number"` +// Name string `json:"name"` +// ErpCategoryId uint32 `json:"erp_category_id"` +// IMEI string `json:"imei"` +// ErpSupplierId uint32 `json:"erp_supplier_id"` +// PageNum int `json:"page_num"` +// PageSize int `json:"page_size"` +// IsExport uint32 `json:"is_export"` // 1-导出 +//} +//type ErpCommodityListResp struct { +// List []ErpCommodity `json:"list"` +// Total int `json:"total"` +// PageNum int `json:"page_num"` +// PageSize int `json:"page_size"` +// ExportUrl string `json:"export_url"` +//} +// +//func (m *ErpCommodityListReq) List() (*ErpCommodityListResp, error) { +// resp := &ErpCommodityListResp{ +// PageNum: m.PageNum, +// PageSize: m.PageSize, +// } +// page := m.PageNum - 1 +// if page < 0 { +// page = 0 +// } +// if m.PageSize == 0 { +// m.PageSize = 10 +// } +// qs := orm.Eloquent.Table("erp_commodity") +// if m.SerialNumber != "" { +// qs = qs.Where("serial_number=?", m.SerialNumber) +// } +// if m.Name != "" { +// //qs = qs.Where("name Like %" + m.Name + "%") +// qs = qs.Where("name LIKE ?", m.Name) +// } +// if m.IMEI != "" { +// qs = qs.Where("imei=?", m.IMEI) +// } +// if m.ErpCategoryId != 0 { +// qs = qs.Where("erp_category_id=?", m.ErpCategoryId) +// } +// if m.ErpSupplierId != 0 { +// qs = qs.Where("erp_supplier_id=?", m.ErpSupplierId) +// } +// +// var count int64 +// err := qs.Count(&count).Error +// if err != nil { +// logger.Error("count err:", err) +// return resp, err +// } +// resp.Total = int(count)/m.PageSize + 1 +// var commodities []ErpCommodity +// +// if m.IsExport == 1 { +// err = qs.Order("id DESC").Find(&commodities).Error +// if err != nil && err != RecordNotFound { +// logger.Error("dailys err:", err) +// return resp, err +// } +// +// listExport, err := ErpCommodityListExport(commodities) +// if err != nil { +// logger.Error("list export err:", err) +// } +// resp.ExportUrl = listExport +// } else { +// err = qs.Order("id DESC").Offset(page * m.PageSize).Limit(m.PageSize).Find(&commodities).Error +// if err != nil && err != RecordNotFound { +// logger.Error("erp commodity list err:", err) +// return resp, err +// } +// resp.List = commodities +// } +// +// return resp, nil +//} +// +//type ErpCategoryListReq struct { +// ErpCategoryId uint32 `json:"erp_category_id"` +// Pid uint32 `json:"pid"` +// Level uint32 `json:"level"` // 分类层级 +// State uint32 `json:"state"` // 1-未使用 2-使用 3-隐藏 +// PageNum int `json:"page_num"` +// PageSize int `json:"page_size"` +// IsExport uint32 `json:"is_export"` // 1-导出 +//} +//type ErpCategoryListResp struct { +// List []ErpCategory `json:"list"` +// Total int `json:"total"` +// PageNum int `json:"page_num"` +// PageSize int `json:"page_size"` +// ExportUrl string `json:"export_url"` +//} +// +//func (m *ErpCategoryListReq) List() (*ErpCategoryListResp, error) { +// resp := &ErpCategoryListResp{ +// PageNum: m.PageNum, +// PageSize: m.PageSize, +// } +// //page := m.PageNum - 1 +// //if page < 0 { +// // page = 0 +// //} +// //if m.PageSize == 0 { +// // m.PageSize = 10 +// //} +// //qs := orm.Eloquent.Table("erp_category") +// //if m.Level != 0 { +// // qs = qs.Where("level=?", m.Level) +// //} +// ////if m.ErpCategoryId != 0 { +// //// qs = qs.IDEq(m.ErpCategoryId) +// ////} +// //if m.Pid != 0 { +// // qs = qs.Where("pid", m.Pid) +// //} +// //var count int64 +// //err := qs.Count(&count).Error +// //if err != nil { +// // logger.Error("count err:", err) +// // return resp, err +// //} +// //resp.Total = int(count)/m.PageSize + 1 +// //var categories []ErpCategory +// //err = qs.Order("id DESC").Offset(page * m.PageSize).Limit(m.PageSize).Find(&categories).Error +// //if err != nil && err != RecordNotFound { +// // logger.Error("erp commodity list err:", err) +// // return resp, err +// //} +// +// var categories []ErpCategory +// qs := orm.Eloquent.Table("erp_category").Where("level=?", 1) +// if m.Pid != 0 { +// qs = qs.Where("id=?", m.Pid) +// } +// if m.State != 0 { +// qs.Where("state=?", m.State) +// } +// +// err := qs.Order("sort DESC").Find(&categories).Error +// if err != nil { +// logger.Error("erp commodity list err:", err) +// return resp, err +// } +// pids := make([]uint32, 0) +// for i, _ := range categories { +// pids = append(pids, categories[i].ID) +// } +// +// var subCat []ErpCategory +// subQs := orm.Eloquent.Table("erp_category").Where("pid in (?)", pids) +// if m.State != 0 { +// subQs.Where("state=?", m.State) +// } +// err = subQs.Order("sort DESC").Find(&subCat).Error +// if err != nil { +// logger.Errorf("pCat err:%#v", err) +// return resp, err +// } +// +// pCatMap := make(map[uint32][]ErpCategory, 0) +// for i, _ := range subCat { +// pCatMap[subCat[i].Pid] = append(pCatMap[subCat[i].Pid], subCat[i]) +// } +// +// for i, _ := range categories { +// v, ok := pCatMap[categories[i].ID] +// +// if ok { +// categories[i].SubCats = v +// } +// } +// +// if m.IsExport == 1 { +// listExport, err := ErpCategoryListExport(categories) +// if err != nil { +// logger.Error("list export err:", err) +// } +// resp.ExportUrl = listExport +// } +// +// resp.List = categories +// return resp, nil +//} +// +//func GetErpCashierMap(ids []uint32) (map[uint32]*ErpCashier, error) { +// cashierMap := make(map[uint32]*ErpCashier, 0) +// if len(ids) == 0 { +// return cashierMap, nil +// } +// var erpCashiers []ErpCashier +// err := orm.Eloquent.Table("erp_cashier").Where("id IN (?)", ids).Find(&erpCashiers).Error +// if err != nil { +// logger.Error("erp cashiers err:", err) +// return cashierMap, err +// } +// for i, _ := range erpCashiers { +// cashierMap[erpCashiers[i].ID] = &erpCashiers[i] +// } +// +// return cashierMap, nil +//} +// +//var ErpCommodityFileExcelCols = []string{"category_1", "category_2", "name", "is_imei", "erp_supplier_name", +// "brokerage_1_string", "brokerage_2_string", "retail_price_string", "min_retail_price_string", +// "staff_cost_price_string", "wholesale_price_string", "origin", "remark"} +// +//type ErpCommodityFileExcel struct { +// Category1 string `json:"category_1"` +// Category2 string `json:"category_2"` +// IsIMEI string `json:"is_imei"` +// +// RetailPriceString string `json:"retail_price_string"` +// MinRetailPriceString string `json:"min_retail_price_string"` +// StaffCostPriceString string `json:"staff_cost_price_string"` +// WholesalePriceString string `json:"wholesale_price_string"` +// Brokerage1String string `json:"brokerage_1_string"` +// Brokerage2String string `json:"brokerage_2_string"` +// +// Code string `json:"code"` +// ErpCommodity +//} +// +//func (e *ErpCommodityFileExcel) Processing() { +// if e.IsIMEI == "是" { +// e.IMEIType = 2 +// } else if e.IsIMEI == "否" { +// e.IMEIType = 1 +// } +// +// e.RetailPrice = PercentFloatStringToUin32(e.RetailPriceString) +// e.MinRetailPrice = PercentFloatStringToUin32(e.MinRetailPriceString) +// e.StaffCostPrice = PercentFloatStringToUin32(e.StaffCostPriceString) +// e.WholesalePrice = PercentFloatStringToUin32(e.WholesalePriceString) +// e.Brokerage1 = PercentFloatStringToFloat(e.Brokerage1String) +// e.Brokerage2 = PercentFloatStringToFloat(e.Brokerage2String) +//} +// +//func PercentFloatStringToUin32(s string) uint32 { +// u := uint32(0) +// if s != "" { +// s = strings.ReplaceAll(s, "%", "") +// } +// f, err := strconv.ParseFloat(s, 64) +// if err != nil { +// logger.Error("parse float err:", err) +// return u +// } +// +// u = uint32(f * 100) +// return u +//} +// +//func PercentFloatStringToFloat(s string) float64 { +// //u := uint32(0) +// if s != "" { +// s = strings.ReplaceAll(s, "%", "") +// } +// f, err := strconv.ParseFloat(s, 64) +// if err != nil { +// logger.Error("parse float err:", err) +// return f +// } +// +// //u = uint32(f * 100) +// return f +//} +// +//func IntStringToUin32(s string) uint32 { +// u := uint32(0) +// if s != "" { +// s = strings.ReplaceAll(s, "%", "") +// } +// i, err := strconv.Atoi(s) +// if err != nil { +// logger.Error("parse float err:", err) +// return u +// } +// +// u = uint32(i) +// return u +//} +// +//type ErpCategorySub struct { +// Id uint32 `json:"id"` +// Name string `json:"name"` +// FullNum uint32 `json:"full_num"` +// SubMap map[string]ErpCategory +// //UnCodeMap map[string]uint32 +//} +// +//func ErpCommodityFileExcelListProcessing(list []ErpCommodityFileExcel) { +// allCategoriesMap, err := GetErpCategorySubMap() +// if err != nil { +// logger.Error("all categories map err:", err) +// return +// } +// fmt.Println("allCategoriesMap:", allCategoriesMap) +// unCodeMap1 := make(map[string]string, 0) +// unCodeMap2 := make(map[string]string, 0) +// numberCount := &CommodityNumberCount{} +// numberCount.NumberMap = make(map[uint32]uint32, 0) +// +// for i, _ := range list { +// //if i == 0 { +// // continue +// //} +// list[i].Processing() +// cat1 := list[i].Category1 +// unCode1, okUc1 := unCodeMap1[cat1] +// if okUc1 { +// cat1 = unCode1 +// } +// catSub, ok := allCategoriesMap[cat1] +// if ok { +// if list[i].Category2 != "" { +// cat2 := list[i].Category2 +// unCode2, okUc2 := unCodeMap2[cat2] +// if okUc2 { +// cat2 = unCode2 +// } +// sub, ok1 := catSub.SubMap[unCode2] +// //unCodeCat, ok2 := unCodeMap2[list[i].Category2] +// if ok1 { +// list[i].ErpCommodity.ErpCategoryId = sub.ID +// list[i].ErpCommodity.ErpCategory = &sub +// numberCommodity, err := numberCount.GetErpCommodityNumberByCategoryId(sub.ID) +// if err != nil { +// logger.Error("category2 create err:", err) +// return +// } +// list[i].ErpCommodity.Number = numberCommodity +// list[i].ErpCommodity.ErpCategoryName = cat2 +// +// } else { +// category2, err := ErpCategoryCreate(list[i].Category2, catSub.Id) +// if err != nil { +// logger.Error("category2 create err:", err) +// return +// } +// fmt.Println("分类id", category2.ID) +// list[i].ErpCommodity.ErpCategoryId = category2.ID +// list[i].ErpCommodity.ErpCategory = category2 +// allCategoriesMap, err = GetErpCategorySubMap() +// if err != nil { +// logger.Error("all categories map err:", err) +// return +// } +// numberCount.NumberMap[category2.ID] = 1 +// list[i].ErpCommodity.Number = 1 +// list[i].ErpCommodity.ErpCategoryName = cat2 +// unCodeMap2[list[i].Category2] = category2.Name +// } +// } else { +// list[i].ErpCommodity.ErpCategoryId = catSub.Id +// list[i].ErpCommodity.ErpCategory = &ErpCategory{Number: catSub.FullNum} // TODO +// numberCommodity, err := numberCount.GetErpCommodityNumberByCategoryId(catSub.Id) +// if err != nil { +// logger.Error("category2 create err:", err) +// return +// } +// list[i].ErpCommodity.Number = numberCommodity +// list[i].ErpCommodity.ErpCategoryName = catSub.Name +// } +// +// list[i].ErpCommodity.SerialNumber = fmt.Sprintf("%06d%04d", list[i].ErpCommodity.ErpCategory.FullNum, list[i].ErpCommodity.Number) +// } else { +// category1, err := ErpCategoryCreate(list[i].Category1, 0) +// if err != nil { +// logger.Error("category1 create err:", err) +// return +// } +// unCodeMap1[list[i].Category1] = category1.Name +// if list[i].Category2 != "" { +// category2, err := ErpCategoryCreate(list[i].Category2, category1.ID) +// if err != nil { +// logger.Error("category2 create err:", err) +// return +// } +// fmt.Println("分类id2", category2.ID) +// list[i].ErpCommodity.ErpCategoryId = category2.ID +// list[i].ErpCommodity.ErpCategoryName = list[i].Category2 +// list[i].ErpCommodity.ErpCategory = category2 +// unCodeMap2[list[i].Category2] = category2.Name +// +// numberCount.NumberMap[category2.ID] = 1 +// list[i].ErpCommodity.Number = 1 +// } else { +// list[i].ErpCommodity.ErpCategoryId = category1.ID +// list[i].ErpCommodity.ErpCategoryName = list[i].Category1 +// list[i].ErpCommodity.ErpCategory = category1 +// +// numberCount.NumberMap[category1.ID] = 1 +// list[i].ErpCommodity.Number = 1 +// } +// +// list[i].ErpCommodity.SerialNumber = fmt.Sprintf("%06d%04d", list[i].ErpCommodity.ErpCategory.FullNum, list[i].ErpCommodity.Number) +// allCategoriesMap, err = GetErpCategorySubMap() +// if err != nil { +// logger.Error("all categories map err:", err) +// return +// } +// } /**/ +// } +// +//} +// +//type CommodityNumberCount struct { +// NumberMap map[uint32]uint32 `json:"number_map"` +//} +// +//func (m *CommodityNumberCount) GetErpCommodityNumberByCategoryId(categoryId uint32) (uint32, error) { +// v, ok := m.NumberMap[categoryId] +// if ok { +// m.NumberMap[categoryId] = v + 1 +// return v + 1, nil +// } +// var commodity ErpCommodity +// err := orm.Eloquent.Raw(fmt.Sprintf( +// "SELECT number FROM erp_commodity WHERE erp_category_id=%d ORDER BY id DESC LIMIT 0,1;", categoryId)).Scan(&commodity).Error +// if err != nil { +// logger.Error("all categories map err:", err) +// return 0, err +// } +// m.NumberMap[categoryId] = commodity.Number + 1 +// return commodity.Number + 1, nil +//} +// +//func GetErpCategorySubMap() (map[string]*ErpCategorySub, error) { +// var erpCategories []ErpCategory +// err := orm.Eloquent.Table("erp_category").Find(&erpCategories).Error +// if err != nil { +// logger.Error("erp categories err:", err) +// return nil, err +// } +// categoriesMaps := make(map[string]*ErpCategorySub, 0) +// +// pidMap := make(map[uint32]string, 0) +// +// for i, _ := range erpCategories { +// if erpCategories[i].Level == 1 { +// if erpCategories[i].Pid != 0 { +// logger.Error("erp categories level 1 pid gt 0") +// return nil, errors.New("erp categories level 1 pid gt 0") +// } +// if _, ok := categoriesMaps[erpCategories[i].Name]; !ok { +// categoriesMaps[erpCategories[i].Name] = &ErpCategorySub{ +// Id: erpCategories[i].ID, +// Name: erpCategories[i].Name, +// FullNum: erpCategories[i].FullNum, +// SubMap: make(map[string]ErpCategory, 0), +// } +// pidMap[erpCategories[i].ID] = erpCategories[i].Name +// } +// +// } +// } +// +// for i, _ := range erpCategories { +// if erpCategories[i].Level == 2 { +// if erpCategories[i].Pid == 0 { +// logger.Error("erp categories level 2 pid is 0") +// return nil, errors.New("erp categories level 2 pid is 0") +// } +// name, ok := pidMap[erpCategories[i].Pid] +// if ok { +// categoriesMaps[name].SubMap[erpCategories[i].Name] = erpCategories[i] +// } +// } +// } +// +// return categoriesMaps, nil +//} +// +//func ErpCategoryCreate(name string, pid uint32) (*ErpCategory, error) { +// category := &ErpCategory{ +// Number: 0, +// State: 2, +// Level: 1, +// Pid: pid, +// } +// var ( +// pCategory ErpCategory +// sCategory ErpCategory +// ) +// qs := orm.Eloquent.Table("erp_category") +// if category.Pid != 0 { +// category.Level = 2 +// qs = qs.Where("id=?", pid) +// err := orm.Eloquent.Table("erp_category").Where("pid=?", pid).Order("id DESC").Limit(1).Find(&sCategory).Error +// if err != nil { +// logger.Error("s category err:", err) +// return category, err +// } +// } else { +// qs = qs.Where("level=1") +// } +// err := qs.Order("id DESC").Limit(1).Find(&pCategory).Error +// if err != nil && err != RecordNotFound { +// logger.Error("cat erp commodity err:", err) +// return category, err +// } +// +// if category.Level == 1 { +// category.Number = pCategory.Number + 1 +// category.FullNum = pCategory.FullNum + 1000 +// category.Name = fmt.Sprintf("%03d%s", category.Number, name) +// } else { +// category.Number = sCategory.Number + 1 +// category.Name = fmt.Sprintf("%03d-%03d%s", pCategory.Number, category.Number, name) +// category.FullNum = pCategory.FullNum + category.Number +// } +// +// err = orm.Eloquent.Create(category).Error +// if err != nil { +// logger.Error("create commodity err:", err) +// return category, err +// } +// return category, nil +//} +// +//type ErpSupplierListResp struct { +// List []ErpSupplier `json:"list"` +// Total int `json:"total"` +// PageNum int `json:"page_num"` +// PageSize int `json:"page_size"` +// ExportUrl string `json:"export_url"` +//} +// +//var ErpStockFileExcelCols = []string{"store_name", "erp_commodity_name", "erp_category_name", "serial_number", +// "is_imei", "imei", "erp_supplier_name", "stock_time_string", "retail_price_string", +// "min_retail_price_string", "staff_cost_price_string", "wholesale_price_string", "count_string", +//} +// +//var EsfLock sync.Mutex +//var EsStockLock sync.Mutex +// +//type StockImporter struct { +// CensusMap map[uint32]map[uint32]uint32 +// CommodityMap map[uint32]*ErpCommodity +// StoreMap map[uint32]string +// Inventories []*ErpInventoryStock +//} +// +//type ErpStockFileExcel struct { +// StockTimeString string `json:"stock_time_string"` +// IsIMEI string `json:"is_imei"` +// +// RetailPriceString string `json:"retail_price_string"` +// MinRetailPriceString string `json:"min_retail_price_string"` +// StaffCostPriceString string `json:"staff_cost_price_string"` +// WholesalePriceString string `json:"wholesale_price_string"` +// CountString string `json:"count_string"` +// +// //StoreName string `json:"store_name"` +// //ErpCommodityName string `json:"erp_commodity_name"` +// //ErpCategoryName string `json:"erp_category_name"` +// //SerialNumber string `json:"serial_number"` +// //IMEIType uint32 `json:"imei_type"` // 1-无串码 2-串码 +// //IMEI string `json:"imei"` +// //ErpSupplierName string `json:"erp_supplier_name"` +// +// ErpStockCommodity +//} +// +//func NewStockImporter() *StockImporter { +// return &StockImporter{ +// CensusMap: make(map[uint32]map[uint32]uint32, 0), +// CommodityMap: make(map[uint32]*ErpCommodity), +// StoreMap: make(map[uint32]string, 0), +// Inventories: make([]*ErpInventoryStock, 0), +// } +//} +// +//func (e *ErpStockFileExcel) Processing() { +// e.Count = IntStringToUin32(e.CountString) +// if e.IsIMEI == "是" { +// e.IMEIType = 2 +// e.Count = 1 +// } else if e.IsIMEI == "否" { +// e.IMEIType = 1 +// } +// //parseTime, err := time.Parse(DateTimeFormat, e.StockTimeString) +// //fmt.Println("StockTimeString:", e.StockTimeString) +// //parseTime, err := time.Parse("01-02-06", e.StockTimeString) +// format := "2006/01/02" +// parseTime, err := time.Parse(format, e.StockTimeString) +// if err != nil { +// logger.Error("parse err:", err) +// parseTime = time.Now() +// } +// e.StockTime = parseTime +// +// e.RetailPrice = PercentFloatStringToUin32(e.RetailPriceString) +// e.MinRetailPrice = PercentFloatStringToUin32(e.MinRetailPriceString) +// e.StaffCostPrice = PercentFloatStringToUin32(e.StaffCostPriceString) +// e.WholesalePrice = PercentFloatStringToUin32(e.WholesalePriceString) +// +//} +// +//func (m *StockImporter) ErpStockFileExcelListProcessing(list []ErpStockFileExcel) error { +// //allCategoriesMap, err := GetErpCategorySubMap() +// //if err != nil { +// // logger.Error("all categories map err:", err) +// // return +// //} +// // 加锁 +// //m.CensusMap = make(map[uint32]map[uint32]uint32, 0) +// storeNameMap := make(map[string]uint32, 0) +// erpCommodityMap := make(map[string]*ErpCommodity, 0) +// erpCategoryNameMap := make(map[string]uint32, 0) +// erpSupplierNameMap := make(map[string]uint32, 0) +// +// storeNames := make([]string, 0, len(list)) +// erpCommodityNames := make([]string, 0, len(list)) +// erpCategoryNames := make([]string, 0, len(list)) +// erpSupplierNames := make([]string, 0, len(list)) +// +// for i, _ := range list { +// list[i].Processing() +// _, ok1 := storeNameMap[list[i].StoreName] +// if !ok1 { +// storeNames = append(storeNames, list[i].StoreName) +// } +// _, ok2 := erpCommodityMap[list[i].ErpCommodityName] +// if !ok2 { +// erpCommodityNames = append(erpCommodityNames, list[i].ErpCommodityName) +// } +// _, ok3 := erpCategoryNameMap[list[i].ErpCategoryName] +// if !ok3 { +// erpCategoryNames = append(erpCategoryNames, list[i].ErpCategoryName) +// } +// _, ok4 := erpSupplierNameMap[list[i].ErpSupplierName] +// if !ok4 { +// erpSupplierNames = append(erpSupplierNames, list[i].ErpSupplierName) +// } +// storeNameMap[list[i].StoreName] = uint32(0) +// erpCommodityMap[list[i].ErpCommodityName] = nil +// erpCategoryNameMap[list[i].ErpCategoryName] = uint32(0) +// erpSupplierNameMap[list[i].ErpSupplierName] = uint32(0) +// +// } +// +// var stores []Store +// err := orm.Eloquent.Table("store").Where("name IN (?)", storeNames).Find(&stores).Error +// if err != nil { +// logger.Error("stores err:", err) +// return err +// } +// +// var erpCommodities []ErpCommodity +// err = orm.Eloquent.Table("erp_commodity").Where("name IN (?)", erpCommodityNames).Find(&erpCommodities).Error +// if err != nil { +// logger.Error("stores err:", err) +// return err +// } +// +// var erpCategories []ErpCategory +// err = orm.Eloquent.Table("erp_category").Where("name IN (?)", erpCategoryNames).Find(&erpCategories).Error +// if err != nil { +// logger.Error("stores err:", err) +// return err +// } +// +// var erpSuppliers []ErpSupplier +// err = orm.Eloquent.Table("erp_supplier").Debug().Where("name IN (?)", erpSupplierNames).Find(&erpSuppliers).Error +// if err != nil && err != RecordNotFound { +// logger.Error("stores err:", err) +// return err +// } +// +// for i, _ := range stores { +// storeNameMap[stores[i].Name] = stores[i].ID +// m.StoreMap[stores[i].ID] = stores[i].Name +// } +// +// for i, _ := range erpCommodities { +// erpCommodityMap[erpCommodities[i].Name] = &erpCommodities[i] +// m.CommodityMap[erpCommodities[i].ID] = &erpCommodities[i] +// } +// +// for i, _ := range erpCategories { +// erpCategoryNameMap[erpCategories[i].Name] = erpCategories[i].ID +// } +// +// for i, _ := range erpSuppliers { +// erpSupplierNameMap[erpSuppliers[i].Name] = erpSuppliers[i].ID +// } +// +// //categoryCommodityNumMap := make(map[uint32]uint32, 0) +// //for i, _ := range erpCommodities { +// // var commodity ErpCommodity +// // err = orm.Eloquent.Table("erp_commodity").Where("erp_category_id=?", erpCommodities[i].ErpCategoryId). +// // Order("id DESC").Limit(1).Find(&commodity).Error +// // if err != nil { +// // logger.Error("commodity err:", err) +// // } +// // categoryCommodityNumMap[erpCommodities[i].ErpCategoryId] = commodity.Number +// //} +// nowTime := time.Now() +// for i, _ := range list { +// v1, ok1 := storeNameMap[list[i].StoreName] +// +// v2, ok2 := erpCommodityMap[list[i].ErpCommodityName] +// +// v3, ok3 := erpCategoryNameMap[list[i].ErpCategoryName] +// +// v4, ok4 := erpSupplierNameMap[list[i].ErpSupplierName] +// +// if !ok1 { +// logger.Error("store name err") +// return errors.New("store name err") +// } +// if !ok2 && v2 == nil { +// logger.Error("erp commodity name err") +// return errors.New("erp commodity name err") +// } +// if !ok3 { +// logger.Error("erp category name err") +// return errors.New("erp category name err") +// } +// if !ok4 { +// logger.Error("erp supplier name err") +// return errors.New("erp supplier name err") +// } +// +// list[i].StoreId = v1 +// list[i].ErpCommodityId = v2.ID +// list[i].CommoditySerialNumber = v2.SerialNumber +// list[i].ErpCategoryId = v3 +// list[i].ErpSupplierId = v4 +// list[i].State = 1 +// list[i].StorageType = 1 +// list[i].FirstStockTime = nowTime +// +// //v6, ok6 := m.CommodityMap[v2] +// +// _, ok5 := m.CensusMap[list[i].StoreId] +// if ok5 { +// m.CensusMap[list[i].StoreId][list[i].ErpCommodityId] += list[i].Count +// } else { +// m.CensusMap[list[i].StoreId] = map[uint32]uint32{list[i].ErpCommodityId: list[i].Count} +// } +// //v5, ok5 := categoryCommodityNumMap[list[i].ErpCategoryId] +// //if !ok5 { +// // logger.Error("category commodity num err") +// // return errors.New("category commodity num err") +// //} +// +// } +// return nil +//} +// +//func (m *StockImporter) ErpStockCountUpdate(gdb *gorm.DB) error { +// for k1, v1 := range m.CensusMap { +// for k2, v2 := range v1 { +// exist, err := QueryRecordExist(fmt.Sprintf("SELECT * FROM erp_stock WHERE store_id=%d AND erp_commodity_id=%d", k1, k2)) +// if err != nil { +// logger.Error("exist err:", err) +// return err +// } +// v, ok := m.CommodityMap[k2] +// fmt.Println("CommodityMap", m.CommodityMap) +// fmt.Println("ok", ok) +// fmt.Println("v", v) +// if exist { +// err = gdb.Exec(fmt.Sprintf( +// "UPDATE erp_stock SET count=count+%d WHERE store_id=%d AND erp_commodity_id=%d;", v2, k1, k2)).Error +// if err != nil { +// logger.Error("update stock err:", err) +// return err +// } +// } else { +// if ok && v != nil { +// stock := &ErpStock{ +// StoreId: k1, +// StoreName: m.StoreMap[k1], +// ErpCommodityId: v.ID, +// ErpCommodityName: v.Name, +// ErpCategoryId: v.ErpCategoryId, +// ErpCategoryName: v.ErpCategoryName, +// CommoditySerialNumber: v.SerialNumber, +// IMEIType: v.IMEIType, +// RetailPrice: v.RetailPrice, +// MinRetailPrice: v.MinRetailPrice, +// Count: v2, +// DispatchCount: 0, +// } +// err = gdb.Create(stock).Error +// if err != nil { +// logger.Error("create stock err:", err) +// return err +// } +// } +// +// } +// if ok && v != nil { +// inventoryStock := &ErpInventoryStock{ +// StoreId: k1, +// StoreName: m.StoreMap[k1], +// ErpCommodityId: v.ID, +// ErpCommodityName: v.Name, +// ErpCategoryId: v.ErpCategoryId, +// ErpCategoryName: v.ErpCategoryName, +// CommoditySerialNumber: v.SerialNumber, +// IMEIType: v.IMEIType, +// RetailPrice: v.RetailPrice, +// MinRetailPrice: v.MinRetailPrice, +// Count: v2, +// } +// fmt.Println("inventoryStock", inventoryStock.Count) +// m.Inventories = append(m.Inventories, inventoryStock) +// } +// +// } +// } +// +// return nil +//} +// +//func (m *StockImporter) ErpInventoryStockCreate(gdb *gorm.DB, list []ErpStockFileExcel) error { +// defer func() { +// if err := recover(); err != nil { +// logger.Error("err:", err) +// return +// } +// }() +// +// inventoryStockIdMap := make(map[string]uint32, 0) +// for _, inventory := range m.Inventories { +// //err := gdb.Create(inventory).Error +// err := orm.Eloquent.Create(inventory).Error +// if err != nil { +// logger.Error("create erp inventory stock err:", err) +// return err +// } +// inventoryStockIdMap[fmt.Sprintf("%d_%d", inventory.StoreId, inventory.ErpCommodityId)] = inventory.ID +// } +// +// begin := orm.Eloquent.Begin() +// total := len(list) +// size := 500 +// page := total / size +// if total%size != 0 { +// page += 1 +// } +// +// errGroup := errgroup.Group{} +// for i := 0; i < page; i++ { +// if i == page-1 { +// stockList := ErpStockCommodityToInventory(inventoryStockIdMap, list[i*size:]) +// err := begin.Create(&stockList).Error +// if err != nil { +// begin.Rollback() +// logger.Error("create commodity err:", err) +// return err +// } +// } else { +// errGroup.Go(func() error { +// //stockList := list[i*size : (i+1)*size] +// stockList := ErpStockCommodityToInventory(inventoryStockIdMap, list[i*size:(i+1)*size]) +// err := begin.Create(&stockList).Error +// if err != nil { +// begin.Rollback() +// logger.Error("create commodity err:", err) +// return err +// } +// return nil +// }) +// } +// } +// err := errGroup.Wait() +// if err != nil { +// logger.Error("wait err:", err) +// return err +// } +// err = begin.Commit().Error +// if err != nil { +// logger.Error("commit err:", err) +// return err +// } +// +// //go func() { +// // //inventoryStockIdMap := make(map[string]uint32, 0) +// // //for _, inventory := range m.Inventories { +// // // //err := gdb.Create(inventory).Error +// // // err := orm.Eloquent.Create(inventory).Error +// // // if err != nil { +// // // logger.Error("create erp inventory stock err:", err) +// // // return +// // // } +// // // inventoryStockIdMap[fmt.Sprintf("%d_%d", inventory.StoreId, inventory.ErpCommodityId)] = inventory.ID +// // //} +// // +// // //stock := ErpStockFileExcel{} +// // //ErpInventoryStock +// // for i, _ := range list { +// // v, ok := inventoryStockIdMap[fmt.Sprintf("%d_%d", list[i].StoreId, list[i].ErpCommodityId)] +// // if ok { +// // inventoryCommodity := &ErpInventoryStockCommodity{ +// // ErpInventoryStockId: v, +// // ErpCommodityId: list[i].ErpCommodityId, +// // ErpCommodityName: list[i].ErpCommodityName, +// // SerialNumber: list[i].SerialNumber, +// // IMEIType: list[i].IMEIType, +// // IMEI: list[i].IMEI, +// // ErpSupplierId: list[i].ErpSupplierId, +// // ErpSupplierName: list[i].ErpSupplierName, +// // StockTime: list[i].StockTime, +// // RetailPrice: list[i].RetailPrice, +// // MinRetailPrice: list[i].MinRetailPrice, +// // StaffCostPrice: list[i].StaffCostPrice, +// // WholesalePrice: list[i].WholesalePrice, +// // Count: list[i].Count, +// // } +// // //err := gdb.Create(inventoryCommodity).Error +// // err := orm.Eloquent.Create(inventoryCommodity).Error +// // if err != nil { +// // logger.Error("create erp inventory stock commodity err:", err) +// // return +// // } +// // } +// // +// // } +// //}() +// return nil +//} +// +//func ErpStockCommodityToInventory(inventoryStockIdMap map[string]uint32, list []ErpStockFileExcel) []*ErpInventoryStockCommodity { +// inventoryList := make([]*ErpInventoryStockCommodity, 0, len(list)) +// for i, _ := range list { +// v, ok := inventoryStockIdMap[fmt.Sprintf("%d_%d", list[i].StoreId, list[i].ErpCommodityId)] +// if ok { +// inventoryCommodity := &ErpInventoryStockCommodity{ +// ErpInventoryStockId: v, +// ErpCommodityId: list[i].ErpCommodityId, +// ErpCommodityName: list[i].ErpCommodityName, +// CommoditySerialNumber: list[i].CommoditySerialNumber, +// IMEIType: list[i].IMEIType, +// IMEI: list[i].IMEI, +// ErpSupplierId: list[i].ErpSupplierId, +// ErpSupplierName: list[i].ErpSupplierName, +// StockTime: list[i].StockTime, +// RetailPrice: list[i].RetailPrice, +// MinRetailPrice: list[i].MinRetailPrice, +// StaffCostPrice: list[i].StaffCostPrice, +// WholesalePrice: list[i].WholesalePrice, +// Count: list[i].Count, +// } +// //err := gdb.Create(inventoryCommodity).Error +// inventoryList = append(inventoryList, inventoryCommodity) +// //err := orm.Eloquent.Create(inventoryCommodity).Error +// //if err != nil { +// // logger.Error("create erp inventory stock commodity err:", err) +// // return inventoryList +// //} +// } +// } +// return inventoryList +//} +// +//func GetErpCommodityMap(ids []uint32) (map[uint32]ErpCommodity, error) { +// commodityMap := make(map[uint32]ErpCommodity, 0) +// if len(ids) == 0 { +// return commodityMap, nil +// } +// var commodities []ErpCommodity +// err := orm.Eloquent.Table("erp_commodity").Where("id IN (?)", ids).Find(&commodities).Error +// if err != nil { +// logger.Error("commodities err:", err) +// return commodityMap, err +// } +// +// for i, _ := range commodities { +// commodityMap[commodities[i].ID] = commodities[i] +// } +// +// return commodityMap, nil +//} +// +//func ErpSupplierListExport(list []ErpSupplier) (string, error) { +// file := excelize.NewFile() +// streamWriter, err := file.NewStreamWriter("Sheet1") +// if err != nil { +// fmt.Println(err) +// } +// +// url := "http://39.108.188.218:8000/img/export/" +// fileName := time.Now().Format(TimeFormat) + "供应商" + ".xlsx" +// +// //title := []interface{}{"门店", "用户ID", "订单编号", "下单时间", "卡带", "说明", "回收价", "闲麦价", "审核时间", "审核人", "操作", "复核时间", "复核状态"} +// title := []interface{}{"供应商编号", "供应商名称", "联系人", "手机号", "地址", "开户银行", "银行账号", "付款周期/天"} +// cell, _ := excelize.CoordinatesToCellName(1, 1) +// if err = streamWriter.SetRow(cell, title); err != nil { +// fmt.Println(err) +// } +// var row []interface{} +// for rowId := 0; rowId < len(list); rowId++ { +// row = []interface{}{list[rowId].Number, list[rowId].Name, list[rowId].Contact, +// list[rowId].Tel, list[rowId].Address, list[rowId].OpeningBank, +// list[rowId].BankAccount, list[rowId].PaymentCycle} +// cell, _ := excelize.CoordinatesToCellName(1, rowId+2) +// if err := streamWriter.SetRow(cell, row); err != nil { +// fmt.Println(err) +// } +// } +// if err := streamWriter.Flush(); err != nil { +// fmt.Println(err) +// } +// if err := file.SaveAs("/www/server/images/export/" + fileName); err != nil { +// //if err := file.SaveAs("./" + fileName); err != nil { +// fmt.Println(err) +// } +// return url + fileName, nil +//} +// +//func ErpCommodityListExport(list []ErpCommodity) (string, error) { +// file := excelize.NewFile() +// streamWriter, err := file.NewStreamWriter("Sheet1") +// if err != nil { +// fmt.Println(err) +// } +// +// url := "http://39.108.188.218:8000/img/export/" +// fileName := time.Now().Format(TimeFormat) + "商品" + ".xlsx" +// +// //title := []interface{}{"供应商编号", "供应商名称", "联系人", "手机号", "地址", "开户银行", "银行账号", "付款周期/天"} +// title := []interface{}{"商品编号", "商品名称", "商品分类", "是否串码", "主供应商", "零售价", "最低零售价", "员工成本价", +// "采购价", "提成等级1", "提成等级2", "产地", "备注", "会员折扣(零售价的百分比)"} +// cell, _ := excelize.CoordinatesToCellName(1, 1) +// if err = streamWriter.SetRow(cell, title); err != nil { +// fmt.Println(err) +// } +// var row []interface{} +// for rowId := 0; rowId < len(list); rowId++ { +// isIMEI := "否" +// if list[rowId].IMEIType == 2 { +// isIMEI = "是" +// } +// +// row = []interface{}{list[rowId].SerialNumber, list[rowId].Name, list[rowId].ErpCategoryName, +// isIMEI, list[rowId].ErpSupplierName, list[rowId].RetailPrice, +// list[rowId].MinRetailPrice, list[rowId].StaffCostPrice, list[rowId].WholesalePrice, list[rowId].Brokerage1, +// list[rowId].Brokerage2, list[rowId].Origin, list[rowId].Remark, list[rowId].MemberDiscount} +// cell, _ := excelize.CoordinatesToCellName(1, rowId+2) +// if err := streamWriter.SetRow(cell, row); err != nil { +// fmt.Println(err) +// } +// } +// if err := streamWriter.Flush(); err != nil { +// fmt.Println(err) +// } +// if err := file.SaveAs("/www/server/images/export/" + fileName); err != nil { +// //if err := file.SaveAs("./" + fileName); err != nil { +// fmt.Println(err) +// } +// return url + fileName, nil +//} +// +//func ErpStoreCashierListExport(list []ErpStoreCashier) (string, error) { +// file := excelize.NewFile() +// streamWriter, err := file.NewStreamWriter("Sheet1") +// if err != nil { +// fmt.Println(err) +// } +// +// url := "http://39.108.188.218:8000/img/export/" +// fileName := time.Now().Format(TimeFormat) + "支付账号" + ".xlsx" +// +// //title := []interface{}{"门店", "用户ID", "订单编号", "下单时间", "卡带", "说明", "回收价", "闲麦价", "审核时间", "审核人", "操作", "复核时间", "复核状态"} +// title := []interface{}{"所属门店", "账号名称", "银行全称", "银行账号"} +// cell, _ := excelize.CoordinatesToCellName(1, 1) +// if err = streamWriter.SetRow(cell, title); err != nil { +// fmt.Println(err) +// } +// var row []interface{} +// for rowId := 0; rowId < len(list); rowId++ { +// row = []interface{}{list[rowId].StoreName, list[rowId].Name, list[rowId].BankName, +// list[rowId].BankAccount} +// cell, _ := excelize.CoordinatesToCellName(1, rowId+2) +// if err := streamWriter.SetRow(cell, row); err != nil { +// fmt.Println(err) +// } +// } +// if err := streamWriter.Flush(); err != nil { +// fmt.Println(err) +// } +// if err := file.SaveAs("/www/server/images/export/" + fileName); err != nil { +// //if err := file.SaveAs("./" + fileName); err != nil { +// fmt.Println(err) +// } +// return url + fileName, nil +//} +// +//func ErpCategoryListExport(list []ErpCategory) (string, error) { +// file := excelize.NewFile() +// streamWriter, err := file.NewStreamWriter("Sheet1") +// if err != nil { +// fmt.Println(err) +// } +// +// url := "http://39.108.188.218:8000/img/export/" +// fileName := time.Now().Format(TimeFormat) + "分类列表数据" + ".xlsx" +// +// //title := []interface{}{"门店", "用户ID", "订单编号", "下单时间", "卡带", "说明", "回收价", "闲麦价", "审核时间", "审核人", "操作", "复核时间", "复核状态"} +// title := []interface{}{"一级分类", "二级分类"} +// cell, _ := excelize.CoordinatesToCellName(1, 1) +// if err = streamWriter.SetRow(cell, title); err != nil { +// fmt.Println(err) +// } +// rowIdx := 2 +// var row []interface{} +// for rowId := 0; rowId < len(list); rowId++ { +// cats := list[rowId].SubCats +// for i := 0; i < len(cats); i++ { +// rowName := list[rowId].Name +// if i != 0 { +// rowName = "" +// } +// row = []interface{}{rowName, cats[i].Name} +// cell, _ := excelize.CoordinatesToCellName(1, rowIdx) +// if err := streamWriter.SetRow(cell, row); err != nil { +// fmt.Println(err) +// } +// rowIdx++ +// } +// } +// if err := streamWriter.Flush(); err != nil { +// fmt.Println(err) +// } +// if err := file.SaveAs("/www/server/images/export/" + fileName); err != nil { +// //if err := file.SaveAs("./" + fileName); err != nil { +// fmt.Println(err) +// } +// return url + fileName, nil +//} +// +//type ErpStockListReq struct { +// SerialNumber string `json:"serial_number"` +// CommodityName string `json:"commodity_name"` +// ErpCategoryId uint32 `json:"erp_category_id"` +// StockType uint32 `json:"stock_type"` // 库存:1-全部 2-有库存 3-无库存 +// PageNum int `json:"page_num"` +// PageSize int `json:"page_size"` +// IsExport uint32 `json:"is_export"` // 1-导出 +//} +//type ErpStockListResp struct { +// List []ErpStock `json:"list"` +// Total int `json:"total"` +// PageNum int `json:"page_num"` +// PageSize int `json:"page_size"` +// ExportUrl string `json:"export_url"` +//} +// +//func (m *ErpStockListReq) List() (*ErpStockListResp, error) { +// resp := &ErpStockListResp{ +// PageNum: m.PageNum, +// PageSize: m.PageSize, +// } +// page := m.PageNum - 1 +// if page < 0 { +// page = 0 +// } +// if m.PageSize == 0 { +// m.PageSize = 10 +// } +// qs := orm.Eloquent.Table("erp_stock") +// if m.SerialNumber != "" { +// qs = qs.Where("serial_number=?", m.SerialNumber) +// } +// if m.CommodityName != "" { +// qs = qs.Where("name Like %" + m.CommodityName + "%") +// } +// if m.ErpCategoryId != 0 { +// qs = qs.Where("erp_category_id=?", m.ErpCategoryId) +// } +// if m.StockType != 0 { +// if m.StockType == 2 { +// qs = qs.Where("count>0") +// } else if m.StockType == 3 { +// qs = qs.Where("count=0") +// } +// } +// var count int64 +// err := qs.Count(&count).Error +// if err != nil { +// logger.Error("count err:", err) +// return resp, err +// } +// resp.Total = int(count)/m.PageSize + 1 +// var commodities []ErpStock +// +// if m.IsExport == 1 { +// err = qs.Order("id DESC").Find(&commodities).Error +// if err != nil && err != RecordNotFound { +// logger.Error("dailys err:", err) +// return resp, err +// } +// +// //listExport, err := ErpCommodityListExport(commodities) +// //if err != nil { +// // logger.Error("list export err:", err) +// //} +// //resp.ExportUrl = listExport +// } else { +// err = qs.Order("id DESC").Offset(page * m.PageSize).Limit(m.PageSize).Find(&commodities).Error +// if err != nil && err != RecordNotFound { +// logger.Error("erp commodity list err:", err) +// return resp, err +// } +// resp.List = commodities +// } +// +// return resp, nil +//} +// +//func ErpStockCommodityListSetAge(commodities []ErpStockCommodity) { +// nowTime := time.Now() +// for i, _ := range commodities { +// commodities[i].Age = uint32(nowTime.Sub(commodities[i].StockTime).Hours()) / 24 +// commodities[i].AllAge = uint32(nowTime.Sub(commodities[i].FirstStockTime).Hours()) / 24 +// } +//} diff --git a/model/erp_retail_order.go b/model/erp_retail_order.go new file mode 100644 index 0000000..ca4526b --- /dev/null +++ b/model/erp_retail_order.go @@ -0,0 +1,276 @@ +package model + +import ( + "encoding/json" + "fmt" + "github.com/codinl/go-logger" + "math/rand" + + "time" +) + +const ( + ErpOrderStateUnAudit = "un_audit" + ErpOrderStateAudited = "audited" +) +const ( + ErpOrderMemberTypeGeneral = "general" + ErpOrderMemberTypeMember = "member" +) + +const ( + RetailTypeSale = "sale" + RetailTypeRejected = "rejected" +) + +type ErpOrder struct { + Model + + BillSn string `json:"bill_sn" gorm:"index"` + RetailType string `json:"retail_type"` // 销售类型: + Tel string `json:"tel" gorm:"index"` + StoreId uint32 `json:"store_id" gorm:"index"` + StoreName string `json:"store_name"` + MakerId uint32 `json:"maker_id" gorm:"index"` + MakerName string `json:"maker_name"` + AuditTime time.Time `json:"audit_time"` + AuditorId uint32 `json:"auditor_id" gorm:"index"` + AuditorName string `json:"auditor_name"` + //ErpCashierId uint32 `json:"erp_cashier_id" gorm:"index"` + //ErpCashierName string `json:"erp_cashier_name"` + CashierList string `json:"cashier_list" gorm:"type:text"` // 付款方式 + Salesman1 uint32 `json:"salesman_1"` + Salesman2 uint32 `json:"salesman_2"` + MemberType string `json:"member_type"` // 会员类型: + State string `json:"state" gorm:"index"` + TotalAmount uint32 `json:"total_amount"` // 包含退货 + TotalCount uint32 `json:"total_count"` // 包含退货 + SaleOrderId uint32 `json:"sale_order_id"` // 销售订单id + + //RejectedTotalAmount uint32 `json:"rejected_total_amount"` + //RejectedTotalCount uint32 `json:"rejected_total_count"` + + Commodities []ErpOrderCommodity `json:"commodities" gorm:"-"` + Cashiers []ErpCashier `json:"cashiers" gorm:"-"` + // erp_order +} + +type ErpOrderCommodity struct { + Model + + ErpOrderId uint32 `json:"erp_order_id"` + ErpCategoryId uint32 `json:"erp_category_id"` + ErpCategoryName string `json:"erp_category_name"` + ErpCommodityId uint32 `json:"erp_commodity_id"` + ErpCommodityName string `json:"erp_commodity_name"` + IMEIType uint32 `json:"imei_type"` // 1-无串码 2-串码 + IMEI string `json:"imei"` + PresentType uint32 `json:"present_type"` // 赠送类型:1-非赠送 2-赠送 + RetailPrice uint32 `json:"retail_price"` + MemberPrice uint32 `json:"member_price"` + Count uint32 `json:"count"` + Amount uint32 `json:"amount"` + Remark string `json:"remark"` + Tel string `json:"tel" gorm:"index"` + RejectedPrice uint32 `json:"rejected_price"` + RejectedCount uint32 `json:"rejected_count"` + RejectedAmount uint32 `json:"rejected_amount"` + RejectedOrderCommodityId uint32 `json:"rejected_order_commodity_id"` + + // erp_order_commodity +} + +type ErpOrderListReq struct { + BillSn string `json:"bill_sn"` + //Type string `json:"type"` + RetailType string `json:"retail_type"` + Tel string `json:"tel"` + StoreId uint32 `json:"store_id"` + State string `json:"state"` + StartTime string `json:"start_time"` + EndTime string `json:"end_time"` + PageNum int `json:"page_num"` + PageSize int `json:"page_size"` + IsExport uint32 `json:"is_export"` // 1-导出 + //StartTime time.Time `json:"start_time"` + //EndTime time.Time `json:"end_time"` +} +type ErpOrderListResp struct { + List []ErpOrder `json:"list"` + Total int `json:"total"` + PageNum int `json:"page_num"` + PageSize int `json:"page_size"` +} + +func (m *ErpOrderListReq) List() (*ErpOrderListResp, error) { + resp := &ErpOrderListResp{ + PageNum: m.PageNum, + PageSize: m.PageSize, + } + page := m.PageNum - 1 + if page < 0 { + page = 0 + } + if m.PageSize == 0 { + m.PageSize = 10 + } + qs := DB.Table("erp_order") + if m.BillSn != "" { + qs = qs.Where("bill_sn=?", m.BillSn) + } + //if m.Type != "" { + // qs = qs.Where("type=?", m.Type) + //} + if m.RetailType != "" { + qs = qs.Where("retail_type=?", m.RetailType) + } + if m.Tel != "" { + qs = qs.Where("tel=?", m.Tel) + } + if m.StoreId != 0 { + qs = qs.Where("store_id=?", m.StoreId) + } + if m.State != "" { + qs = qs.Where("state=?", m.State) + } + if m.StartTime != "" { + parse, err := time.Parse(DateTimeFormat, m.StartTime) + if err != nil { + logger.Errorf("err:", err) + //return users, 0, err + } + qs = qs.Where("created_at > ?", parse) + } + if m.EndTime != "" { + parse, err := time.Parse(DateTimeFormat, m.EndTime) + if err != nil { + logger.Errorf("err:", err) + //return users, 0, err + } + parse = parse.AddDate(0, 0, 1) + qs = qs.Where("created_at < ?", parse) + } + + var count int64 + err := qs.Count(&count).Error + if err != nil { + logger.Error("count err:", err) + return resp, err + } + resp.Total = int(count)/m.PageSize + 1 + var orders []ErpOrder + err = qs.Order("id DESC").Offset(page * m.PageSize).Limit(m.PageSize).Find(&orders).Error + if err != nil && err != RecordNotFound { + logger.Error("erp commodity list err:", err) + return resp, err + } + ErpOrderListSetCashier(orders) + + resp.List = orders + return resp, nil +} + +func NewErpBillSn() string { + nowTime := time.Now() + rand.Seed(nowTime.UnixNano()) + max := 1 + for { + if max > 5 { + logger.Error("create sn err") + return "" + } + random := rand.Int31n(9999) + 1000 + sn := fmt.Sprintf("%s%d", nowTime.Format("060102"), random) + exist, err := QueryRecordExist(fmt.Sprintf("SELECT * FROM erp_order WHERE bill_sn='%s'", sn)) + if err != nil { + logger.Error("exist sn err") + } + if !exist { + return sn + } + + max++ + } +} + +//func NewErpPurchaseSn() string { +// nowTime := time.Now() +// rand.Seed(nowTime.UnixNano()) +// max := 1 +// for { +// if max > 5 { +// logger.Error("create sn err") +// return "" +// } +// random := rand.Int31n(9999) + 1000 +// sn := fmt.Sprintf("%s%d", nowTime.Format("060102"), random) +// exist, err := QueryRecordExist(fmt.Sprintf("SELECT * FROM erp_purchase_order WHERE serial_number='%s'", sn)) +// if err != nil { +// logger.Error("exist sn err") +// } +// if !exist { +// return sn +// } +// +// max++ +// } +//} + +func ErpOrderListSetCashier(list []ErpOrder) { + for i, _ := range list { + //if list[i].CashierList != "" { + // var cashiers []ErpCashier + // err := json.Unmarshal([]byte(list[i].CashierList), &cashiers) + // if err != nil { + // logger.Error("unmarshal err:", err) + // } + // list[i].Cashiers = cashiers + // list[i].CashierList = "" + //} + list[i].SetErpCashier() + } +} + +func (m *ErpOrder) SetErpCashier() { + if m.CashierList != "" { + var cashiers []ErpCashier + err := json.Unmarshal([]byte(m.CashierList), &cashiers) + if err != nil { + logger.Error("unmarshal err:", err) + } + m.Cashiers = cashiers + m.CashierList = "" + } +} + +func GetErpOrderCommodityMap(ids []uint32) (map[uint32]ErpOrderCommodity, error) { + commodityMap := make(map[uint32]ErpOrderCommodity, 0) + if len(ids) == 0 { + return commodityMap, nil + } + var commodities []ErpOrderCommodity + err := DB.Table("erp_order_commodity").Where("id IN (?)", ids).Find(&commodities).Error + if err != nil { + logger.Error("commodities err:", err) + return commodityMap, err + } + for i, _ := range commodities { + commodityMap[commodities[i].ID] = commodities[i] + } + return commodityMap, nil +} + +func SetUserInfo(tel string) { + var user User + err := DB.Table("user").Where("tel=?", tel).Find(&user).Error + if err != nil { + logger.Error("user err:", err) + return + } + if user.FirstRetailOrder.IsZero() { + err := DB.Table("user").Where("uid=?", user.Uid).Update("first_retail_order", time.Now()).Error + if err != nil { + logger.Error("update user err:", err) + } + } +} diff --git a/model/user.go b/model/user.go index 388842f..01a8939 100644 --- a/model/user.go +++ b/model/user.go @@ -47,7 +47,9 @@ type User struct { ShopAssistantName string `json:"shop_assistant_name"` // 店员名称 //RenewalTime time.Time `json:"renewal_time"` //RenewalMemberLevel uint32 `json:"renewal_member_level"` - OpenMemberLevel uint32 `json:"open_member_level"` + OpenMemberLevel uint32 `json:"open_member_level"` + FirstRetailOrder time.Time `json:"first_retail_order"` + //MemberLevelString string `json:"member_level_string" gorm:"-"` // 会员类型 Version uint32 `json:"-"` // UserVm *UserVm `json:"user_vm" gorm:"-"` // diff --git a/router/router_app.go b/router/router_app.go index 3604c8b..6601867 100644 --- a/router/router_app.go +++ b/router/router_app.go @@ -281,4 +281,15 @@ func ConfigAppRouter(r gin.IRouter) { recycleConsole.POST("order/check", controller.RecycleCardOrderCheck) // 管理端 recycleConsole.POST("order/list", controller.ConsoleRecycleCardOrderList) } + retail := console.Group("retail") + { + retail.POST("order_commodity_list", controller.ErpOrderCommodityList) + + recycleConsole.Use(auth.UserAccessAuth) + retail.POST("order/list", controller.ErpOrderList) + retail.POST("order/create", controller.ErpOrderCreate) + retail.POST("order_detail", controller.ErpOrderDetail) + retail.POST("shop_assistant_list", controller.ShopAssistantList) + } + }