From 155f70979af20ca520a55b89c6ec8cd46c43f8a5 Mon Sep 17 00:00:00 2001
From: zhangqian <zhangqian@123.com>
Date: 星期三, 31 七月 2024 15:47:33 +0800
Subject: [PATCH] 产品流水表增加多单位存储

---
 controllers/product_controller.go |  232 ++++++++++++++++++++++++++++++++++++++++++++++++++++-----
 1 files changed, 210 insertions(+), 22 deletions(-)

diff --git a/controllers/product_controller.go b/controllers/product_controller.go
index 1549251..fa48b5f 100644
--- a/controllers/product_controller.go
+++ b/controllers/product_controller.go
@@ -7,6 +7,8 @@
 	"github.com/shopspring/decimal"
 	"github.com/spf13/cast"
 	"gorm.io/gorm"
+	"io"
+	"net/url"
 	"strconv"
 	"time"
 	"wms/constvar"
@@ -20,6 +22,7 @@
 	"wms/request"
 	"wms/response"
 	"wms/service"
+	"wms/utils/http"
 )
 
 type ProductController struct {
@@ -53,6 +56,13 @@
 	if params.Unit == "" {
 		util.ResponseFormat(c, code.RequestParamError, "鍗曚綅涓嶈兘涓虹┖")
 		return
+	}
+	if params.BarCode != "" {
+		m, err := models.NewMaterialSearch().SetBarCode(params.BarCode).First()
+		if err == nil && m.ID != "" { //鏌ュ嚭鐗╂枡琛ㄦ槸鐗╂枡宸插瓨鍦�
+			util.ResponseFormat(c, code.RequestParamError, "鏉″舰鐮佸凡缁忚浣跨敤")
+			return
+		}
 	}
 	//params.ID = utils.GetUUID()
 
@@ -99,6 +109,7 @@
 // @Summary   鑾峰彇浜у搧鍒楄〃
 // @Produce   application/json
 // @Param     object  body  request.GetProductList true  "鏌ヨ鍙傛暟"
+// @Param     Authorization	header string true "token"
 // @Success   200 {object} util.ResponseList{data=[]models.Material}	"鎴愬姛"
 // @Router    /api-wms/v1/product/getProductList [post]
 func (slf ProductController) GetProductList(c *gin.Context) {
@@ -111,7 +122,12 @@
 	if params.PageInfo.Check() {
 		search.SetPage(params.Page, params.PageSize)
 	}
-	products, total, err := search.SetPreload(true).SetKeyword(params.KeyWord).SetCategoryId(params.CategoryId).SetOrder("created_at desc").Find()
+	products, total, err := search.SetPreload(true).
+		SetKeyword(params.KeyWord).
+		SetCategoryId(params.CategoryId).
+		SetCategoryIds(params.CategoryIds).
+		SetOrder("created_at desc").
+		Find()
 	if err != nil {
 		util.ResponseFormat(c, code.RequestParamError, "鏌ユ壘澶辫触")
 		return
@@ -126,32 +142,28 @@
 		util.ResponseFormat(c, code.RequestParamError, "浜у搧绫诲瀷鏌ユ壘澶辫触")
 		return
 	}
+	categoryMap := models.CategoryMap(categories)
 	for _, product := range products {
-		for _, category := range categories {
-			if product.CategoryId == int(category.ID) {
-				product.CategoryName = category.Name
-			}
+		if product.CategoryId != 0 && categoryMap[product.CategoryId] != nil {
+			product.CategoryName = categoryMap[product.CategoryId].Name
 		}
-		var reorderAmount request.ProductStatisticsAmount
-		if err := models.NewOperationSearch().Orm.
-			Table("wms_operation_details").
+		var totalAmount decimal.Decimal
+		db := models.NewOperationSearch().Orm
+		if err := db.Table("wms_operation_details").
 			InnerJoins("INNER JOIN wms_operation on wms_operation_details.operation_id=wms_operation.id").
-			Select("wms_operation_details.product_id,SUM(wms_operation_details.amount) as total_count").
+			Select("IFNULL(SUM(wms_operation_details.amount), 0) as total_count").
 			Where("wms_operation_details.product_id=? and wms_operation.`status`=? and wms_operation.base_operation_type in (?)", product.ID, constvar.OperationStatus_Ready, []constvar.BaseOperationType{constvar.BaseOperationTypeIncoming, constvar.BaseOperationTypeOutgoing, constvar.BaseOperationTypeDisuse}).
-			Group("wms_operation_details.product_id").
-			//Order("wms_operation_details.product_id").
-			First(&reorderAmount).Error; err != nil {
+			Scan(&totalAmount).Error; err != nil {
 			if !errors.Is(err, gorm.ErrRecordNotFound) {
 				util.ResponseFormat(c, code.RequestParamError, "浜у搧鏁版嵁缁熻澶辫触")
 				return
-			} else {
-				reorderAmount.TotalAmount = decimal.NewFromInt(0)
 			}
 		}
-		product.PredictionAmount = product.Amount.Add(reorderAmount.TotalAmount)
+		product.PredictionAmount = product.Amount.Add(totalAmount)
 
 		var statisticsList []*request.ProductStatistics
-		if err := models.NewOperationSearch().Orm.Table("wms_operation").
+		db2 := models.NewOperationSearch().Orm
+		if err := db2.Table("wms_operation").
 			InnerJoins("INNER JOIN wms_operation_details on wms_operation_details.operation_id=wms_operation.id").
 			Select("SUM(wms_operation_details.amount) as total_amount,wms_operation.base_operation_type").
 			Where("wms_operation_details.product_id=? and wms_operation.`status`=? and wms_operation.base_operation_type in (?)", product.ID, constvar.OperationStatus_Finish, []constvar.BaseOperationType{constvar.BaseOperationTypeIncoming, constvar.BaseOperationTypeOutgoing, constvar.BaseOperationTypeDisuse}).
@@ -218,8 +230,9 @@
 
 // GetProductDetails
 // @Tags      浜у搧
-// @Summary   鑾峰彇浜у搧璇︽儏
+// @Summary   閫氳繃浜у搧/鍟嗗搧/鐗╂枡 ID鑾峰彇浜у搧璇︽儏
 // @Produce   application/json
+// @Param     Authorization	header string true "token"
 // @Param		id	path		string			true	"id"  "鏌ヨ鍙傛暟"
 // @Success   200 {object} util.Response{data=models.Material}	"鎴愬姛"
 // @Router    /api-wms/v1/product/getProductDetails/{id} [get]
@@ -233,6 +246,96 @@
 	if err != nil {
 		util.ResponseFormat(c, code.RequestParamError, "鏌ユ壘澶辫触")
 		return
+	}
+	attributeValues, err := models.NewAttributeValueSearch().SetEntityID(material.ID).FindNotTotal()
+	if err != nil {
+		util.ResponseFormat(c, code.RequestParamError, "鏌ユ壘澶辫触")
+		return
+	}
+	aids := make([]uint, 0)
+	for _, v := range attributeValues {
+		aids = append(aids, v.AttributeID)
+	}
+	attributes, err := models.NewAttributeSearch().SetIDs(aids).FindNotTotal()
+	attributesMap := make(map[uint]*models.Attribute, len(attributes))
+	for _, v := range attributes {
+		attributesMap[v.ID] = v
+	}
+	if err != nil {
+		util.ResponseFormat(c, code.RequestParamError, "鏈煡鍔ㄦ�佸睘鎬�")
+	}
+	for _, v1 := range attributeValues {
+		attribute := attributesMap[v1.AttributeID]
+		if attribute == nil {
+			continue
+		}
+		//product.Attributes = append(product.Attributes,v1)
+		material.Attributes = append(material.Attributes, models.Attribute{
+			Model:        gorm.Model{ID: v1.ID, CreatedAt: v1.CreatedAt, UpdatedAt: v1.UpdatedAt, DeletedAt: v1.DeletedAt},
+			Name:         attribute.Name,
+			DataType:     attribute.DataType,
+			EntityType:   attribute.EntityType,
+			SelectValues: attribute.SelectValues,
+			SelectValue:  attribute.SelectValue,
+			//Value:        v1.Value,
+			Value: v1.Value,
+		})
+	}
+	util.ResponseFormat(c, code.Success, material)
+}
+
+// GetProductDetailsByBarCode
+// @Tags      浜у搧
+// @Summary   閫氳繃浜у搧/鍟嗗搧/鐗╂枡 鏉″舰鐮� 鑾峰彇浜у搧璇︽儏
+// @Produce   application/json
+// @Param     Authorization	header string true "token"
+// @Param		barCode	path		string			true	"barCode"  "鏌ヨ鍙傛暟"
+// @Success   200 {object} util.Response{data=models.Material}	"鎴愬姛"
+// @Router    /api-wms/v1/product/getProductDetailsByBarCode/{barCode} [get]
+func (slf ProductController) GetProductDetailsByBarCode(c *gin.Context) {
+	barCode := c.Param("barCode")
+	if barCode == "" {
+		util.ResponseFormat(c, code.RequestParamError, "鏃犳晥鏉″舰鐮�")
+		return
+	}
+	material, err := models.NewMaterialSearch().SetBarCode(barCode).SetPreload(true).First()
+	if err != nil {
+		util.ResponseFormat(c, code.RequestParamError, "鏌ユ壘澶辫触")
+		return
+	}
+	attributeValues, err := models.NewAttributeValueSearch().SetEntityID(material.ID).FindNotTotal()
+	if err != nil {
+		util.ResponseFormat(c, code.RequestParamError, "鏌ユ壘澶辫触")
+		return
+	}
+	aids := make([]uint, 0)
+	for _, v := range attributeValues {
+		aids = append(aids, v.AttributeID)
+	}
+	attributes, err := models.NewAttributeSearch().SetIDs(aids).FindNotTotal()
+	attributesMap := make(map[uint]*models.Attribute, len(attributes))
+	for _, v := range attributes {
+		attributesMap[v.ID] = v
+	}
+	if err != nil {
+		util.ResponseFormat(c, code.RequestParamError, "鏈煡鍔ㄦ�佸睘鎬�")
+	}
+	for _, v1 := range attributeValues {
+		attribute := attributesMap[v1.AttributeID]
+		if attribute == nil {
+			continue
+		}
+		//product.Attributes = append(product.Attributes,v1)
+		material.Attributes = append(material.Attributes, models.Attribute{
+			Model:        gorm.Model{ID: v1.ID, CreatedAt: v1.CreatedAt, UpdatedAt: v1.UpdatedAt, DeletedAt: v1.DeletedAt},
+			Name:         attribute.Name,
+			DataType:     attribute.DataType,
+			EntityType:   attribute.EntityType,
+			SelectValues: attribute.SelectValues,
+			SelectValue:  attribute.SelectValue,
+			//Value:        v1.Value,
+			Value: v1.Value,
+		})
 	}
 	util.ResponseFormat(c, code.Success, material)
 }
@@ -261,6 +364,13 @@
 	if params.Unit == "" {
 		util.ResponseFormat(c, code.RequestParamError, "鍗曚綅涓嶈兘涓虹┖")
 		return
+	}
+	if params.BarCode != "" {
+		m, err := models.NewMaterialSearch().SetBarCode(params.BarCode).First()
+		if err == nil && m.ID != params.ID { //鏌ュ嚭鐗╂枡涓擨D涓嶄竴鏍�,
+			util.ResponseFormat(c, code.RequestParamError, "鏉″舰鐮佸凡缁忚浣跨敤")
+			return
+		}
 	}
 	err := models.NewMaterialSearch().SetID(params.ID).Save(&params)
 	if err != nil {
@@ -330,7 +440,7 @@
 
 // DeleteProduct
 // @Tags      浜у搧
-// @Summary   鍒犻櫎浜у搧
+// @Summary   閫氳繃浜у搧/鍟嗗搧/鐗╂枡 ID鍒犻櫎浜у搧
 // @Produce   application/json
 // @Param		id	path		string			true	"id"  "鏌ヨ鍙傛暟"
 // @Success   200 {object} util.Response "鎴愬姛"
@@ -341,7 +451,37 @@
 		util.ResponseFormat(c, code.RequestParamError, "鏃犳晥id")
 		return
 	}
-	err := models.NewMaterialSearch().SetID(id).Delete()
+	err := models.WithTransaction(func(tx *gorm.DB) error {
+		if err := models.NewMaterialSearch().SetOrm(tx).SetID(id).Delete(); err != nil {
+			return err
+		}
+		if err := models.NewAttributeValueSearch().SetOrm(tx).SetEntityID(id).Delete(); err != nil { //鍒犻櫎鐗╂枡瀵瑰簲鐨勫姩鎬佸睘鎬�
+			return err
+		}
+		return nil
+	})
+
+	if err != nil {
+		util.ResponseFormat(c, code.RequestParamError, "鍒犻櫎澶辫触")
+		return
+	}
+	util.ResponseFormat(c, code.Success, "鍒犻櫎鎴愬姛")
+}
+
+// DeleteProductByBarCode
+// @Tags      浜у搧
+// @Summary    閫氳繃浜у搧/鍟嗗搧/鐗╂枡 鏉″舰鐮佸垹闄や骇鍝�
+// @Produce   application/json
+// @Param		barCode	path		string			true	"barCode"  "鏌ヨ鍙傛暟"
+// @Success   200 {object} util.Response "鎴愬姛"
+// @Router    /api-wms/v1/product/deleteProductByBarCode/{barCode} [delete]
+func (slf ProductController) DeleteProductByBarCode(c *gin.Context) {
+	barCode := c.Param("barCode")
+	if barCode == "" {
+		util.ResponseFormat(c, code.RequestParamError, "鏃犳晥id")
+		return
+	}
+	err := models.NewMaterialSearch().SetBarCode(barCode).Delete()
 	if err != nil {
 		util.ResponseFormat(c, code.RequestParamError, "鍒犻櫎澶辫触")
 		return
@@ -663,6 +803,7 @@
 				return errors.New(fmt.Sprintf("浜у搧锛�%v,搴撳瓨锛�%v,鎶ュ簾锛�%v,鏁伴噺涓嶅锛屾棤娉曞畬鎴愭姤搴熸搷浣�", v.Product.Name, v.Product.Amount.String(), v.Amount.String()))
 			}
 			listDetails[k].Product.Amount = listDetails[k].Product.Amount.Sub(v.Amount)
+			listDetails[k].Product.StockMoreUnitList = service.SubMoreUnit(listDetails[k].Product.StockMoreUnitList, v.MoreUnitList)
 			if err := tx.Save(&listDetails[k].Product).Error; err != nil {
 				return err
 			}
@@ -888,6 +1029,16 @@
 		v.Sort = i + 1
 	}
 
+	//鏍¢獙閲嶅
+	m := make(map[string]struct{})
+	for _, v := range params {
+		if _, ok := m[v.Name]; ok {
+			util.ResponseFormat(c, code.RequestParamError, "鍗曚綅閲嶅锛�"+v.Name)
+			return
+		}
+		m[v.Name] = struct{}{}
+	}
+
 	err := models.WithTransaction(func(tx *gorm.DB) error {
 		err := models.NewUnitDictSearch().SetOrm(tx).Delete()
 		if err != nil {
@@ -901,7 +1052,7 @@
 		return nil
 	})
 	if err != nil {
-		util.ResponseFormat(c, code.RequestParamError, "鍒犻櫎澶辫触")
+		util.ResponseFormat(c, code.RequestParamError, "淇濆瓨澶辫触")
 		return
 	}
 
@@ -910,8 +1061,8 @@
 
 // InputProduct
 //
-//	@Tags		鐗╂枡绠$悊
-//	@Summary	瀵煎叆鐗╂枡
+//	@Tags		浜у搧
+//	@Summary	瀵煎叆鐗╂枡/浜у搧
 //
 // @Accept multipart/form-data
 // @Param file formData file true "file"
@@ -937,3 +1088,40 @@
 	resp.InputCount = insertCount
 	util.ResponseFormat(c, code.Success, resp)
 }
+
+// DownloadInputFormat
+//
+//	@Tags		浜у搧
+//	@Summary	涓嬭浇瀵煎叆鐗╂枡/浜у搧妯℃澘
+//
+// @Param     Authorization	header string true "token"
+//
+//	@Success	200		{object}	util.Response 	"鎴愬姛"
+//	@Router		/api-wms/v1/product/downloadInputFormat [get]
+func (slf ProductController) DownloadInputFormat(c *gin.Context) {
+	template, err := models.NewFileTemplateAttachmentSearch().SetCategory(constvar.FileWarehouseCategory_JialianInput3).First() //鐗╂枡瀵煎叆妯℃澘
+	if err != nil {
+		util.ResponseFormat(c, code.NoTemplateError, "鑾峰彇妯$増璁板綍澶辫触:"+err.Error())
+		return
+	}
+	readerCloser, err := http.HttpGetWithReadCloser(template.FileUrl)
+	if err != nil {
+		util.ResponseFormat(c, code.NoTemplateError, "鑾峰彇妯$増璁板綍澶辫触:"+err.Error())
+		return
+	}
+
+	fileContentDisposition := "attachment;filename=\"" + url.QueryEscape("鐗╂枡瀵煎叆.xlsx") + "\""
+	w := c.Writer
+	w.Header().Set("Content-Type", "application/octet-stream")
+	w.Header().Set("Content-Disposition", fileContentDisposition)
+	w.Header().Set("Content-Transfer-Encoding", "binary")
+	w.Header().Set("Cache-Control", "no-cache")
+	_, err = io.Copy(w, readerCloser)
+	if err != nil {
+		util.ResponseFormat(c, code.NoTemplateError, "涓嬭浇澶辫触:"+err.Error())
+		return
+	}
+	w.Flush()
+	_ = readerCloser.Close()
+	util.ResponseFormat(c, code.Success, "")
+}

--
Gitblit v1.8.0