From 79aef24a785581d95343ccd99e9cb362b2bc9c97 Mon Sep 17 00:00:00 2001
From: yinbentan <yinbentan@live.com>
Date: 星期六, 06 七月 2024 21:31:59 +0800
Subject: [PATCH] 调整库存商品位置错误

---
 controllers/product_controller.go |  372 +++++++++++++++++++++++++++++++++++++++++++++++------
 1 files changed, 329 insertions(+), 43 deletions(-)

diff --git a/controllers/product_controller.go b/controllers/product_controller.go
index a99ac83..56f6e68 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"
@@ -18,6 +20,9 @@
 	"wms/pkg/mysqlx"
 	"wms/pkg/structx"
 	"wms/request"
+	"wms/response"
+	"wms/service"
+	"wms/utils/http"
 )
 
 type ProductController struct {
@@ -52,23 +57,48 @@
 		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()
-	err := models.NewMaterialSearch().Create(&params)
+
+	err := models.WithTransaction(func(tx *gorm.DB) error {
+		if err := models.NewMaterialSearch().SetOrm(tx).Create(&params); err != nil {
+			return err
+		}
+		materialAttachmentList := []*models.MaterialAttachment{}
+		for _, v := range params.AttachmentIDs {
+			ma := &models.MaterialAttachment{MaterialID: params.ID, AttachmentID: v}
+			materialAttachmentList = append(materialAttachmentList, ma)
+		}
+		if len(materialAttachmentList) > 0 {
+			if err := models.NewMaterialAttachmentSearch().SetOrm(tx).CreateBatch(materialAttachmentList); err != nil {
+				return err
+			}
+		}
+		avs := make([]*models.AttributeValue, 0)
+		for _, v := range params.Attributes {
+			av := models.AttributeValue{
+				Model:       gorm.Model{},
+				EntityID:    params.ID,
+				AttributeID: v.ID,
+				Value:       v.Value,
+			}
+			avs = append(avs, &av)
+
+		}
+		if err := models.NewAttributeValueSearch().SetOrm(tx).CreateBatch(avs); err != nil {
+			return err
+		}
+		return nil
+	})
 	if err != nil {
 		util.ResponseFormat(c, code.RequestParamError, "浜у搧淇℃伅淇濆瓨澶辫触")
 		return
-	}
-
-	materialAttachmentList := []*models.MaterialAttachment{}
-	for _, v := range params.AttachmentIDs {
-		ma := &models.MaterialAttachment{MaterialID: params.ID, AttachmentID: v}
-		materialAttachmentList = append(materialAttachmentList, ma)
-	}
-	if len(materialAttachmentList) > 0 {
-		if err := models.NewMaterialAttachmentSearch().CreateBatch(materialAttachmentList); err != nil {
-			util.ResponseFormat(c, code.SaveFail, "闄勪欢淇濆瓨澶辫触")
-			return
-		}
 	}
 
 	util.ResponseFormat(c, code.Success, "淇濆瓨鎴愬姛")
@@ -161,14 +191,46 @@
 			product.MaxInventoryRule = reorderRules[0].MaxInventory
 		}
 		product.ReorderRuleNum = rulesTotal
+		attributeValues, err := models.NewAttributeValueSearch().SetEntityID(product.ID).FindNotTotal()
+		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)
+			product.Attributes = append(product.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.ResponseFormatList(c, code.Success, products, int(total))
 }
 
 // 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]
@@ -182,6 +244,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)
 }
@@ -211,49 +363,82 @@
 		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 {
 		util.ResponseFormat(c, code.RequestParamError, "浜у搧淇℃伅鏇存柊澶辫触")
 		return
 	}
-
-	//鏇存柊鍦ㄥ簱鐨勪骇鍝佺被鍨�
-	if params.CategoryId > 0 {
-		find, _ := models.NewLocationProductAmountSearch().SetProductId(params.ID).Find()
-		if len(find) > 0 {
-			var ids []int
-			for _, f := range find {
-				if f.ProductCategoryID != params.CategoryId {
-					ids = append(ids, f.Id)
+	err = models.WithTransaction(func(tx *gorm.DB) error {
+		//鏇存柊鍦ㄥ簱鐨勪骇鍝佺被鍨�
+		if params.CategoryId > 0 {
+			find, _ := models.NewLocationProductAmountSearch().SetProductId(params.ID).Find()
+			if len(find) > 0 {
+				var ids []int
+				for _, f := range find {
+					if f.ProductCategoryID != params.CategoryId {
+						ids = append(ids, f.Id)
+					}
 				}
+				m := make(map[string]interface{})
+				m["productCategoryId"] = params.CategoryId
+				_ = models.NewLocationProductAmountSearch().SetOrm(tx).SetIds(ids).UpdateByMap(m)
 			}
-			m := make(map[string]interface{})
-			m["productCategoryId"] = params.CategoryId
-			_ = models.NewLocationProductAmountSearch().SetIds(ids).UpdateByMap(m)
 		}
-	}
+		materialAttachmentList := []*models.MaterialAttachment{}
+		for _, v := range params.AttachmentIDs {
+			ma := &models.MaterialAttachment{MaterialID: params.ID, AttachmentID: v}
+			materialAttachmentList = append(materialAttachmentList, ma)
+		}
+		if err := models.NewMaterialAttachmentSearch().SetOrm(tx).SetMaterialID(params.ID).Delete(); err != nil {
+			util.ResponseFormat(c, code.RequestParamError, "浜у搧闄勪欢娓呴櫎澶辫触")
+			return err
+		}
+		if len(materialAttachmentList) > 0 {
+			if err := models.NewMaterialAttachmentSearch().SetOrm(tx).CreateBatch(materialAttachmentList); err != nil {
+				util.ResponseFormat(c, code.RequestParamError, "浜у搧淇℃伅鏇存柊澶辫触")
+				return err
+			}
+		}
 
-	materialAttachmentList := []*models.MaterialAttachment{}
-	for _, v := range params.AttachmentIDs {
-		ma := &models.MaterialAttachment{MaterialID: params.ID, AttachmentID: v}
-		materialAttachmentList = append(materialAttachmentList, ma)
-	}
-	if err := models.NewMaterialAttachmentSearch().SetMaterialID(params.ID).Delete(); err != nil {
-		util.ResponseFormat(c, code.RequestParamError, "浜у搧闄勪欢娓呴櫎澶辫触")
+		/*attributeValueSearch := models.NewAttributeValueSearch()
+		//鍒犻櫎浠庢柊鎻掑叆
+		if err := attributeValueSearch.SetOrm(tx).SetEntityID(params.ID).Delete(); err != nil {
+			return err
+		}*/
+		//avs := make([]*models.AttributeValue, 0)
+		for _, v := range params.Attributes {
+			av := models.AttributeValue{
+				Model:       gorm.Model{ID: v.ID},
+				EntityID:    params.ID,
+				AttributeID: v.ID,
+				Value:       v.Value,
+			}
+			//avs = append(avs, &av)
+			if err := models.NewAttributeValueSearch().SetOrm(tx).Save(&av); err != nil {
+				return err
+			}
+		}
+
+		return nil
+	})
+	if err != nil {
+		util.ResponseFormat(c, code.RequestParamError, "浜у搧淇℃伅鏇存柊澶辫触")
 		return
 	}
-	if len(materialAttachmentList) > 0 {
-		if err := models.NewMaterialAttachmentSearch().CreateBatch(materialAttachmentList); err != nil {
-			util.ResponseFormat(c, code.RequestParamError, "浜у搧淇℃伅鏇存柊澶辫触")
-			return
-		}
-	}
+
 	util.ResponseFormat(c, code.Success, "鏇存柊鎴愬姛")
 }
 
 // DeleteProduct
 // @Tags      浜у搧
-// @Summary   鍒犻櫎浜у搧
+// @Summary   閫氳繃浜у搧/鍟嗗搧/鐗╂枡 ID鍒犻櫎浜у搧
 // @Produce   application/json
 // @Param		id	path		string			true	"id"  "鏌ヨ鍙傛暟"
 // @Success   200 {object} util.Response "鎴愬姛"
@@ -264,7 +449,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
@@ -480,6 +695,7 @@
 		OperationDate:     time.Now().Format("2006-01-02 15:04:05"),
 		Details:           []*models.OperationDetails{detail},
 		BaseOperationType: constvar.BaseOperationTypeDisuse,
+		OperationTypeName: "搴撳瓨鎶ュ簾",
 	}
 	if err := models.NewOperationSearch().Create(&operation); err != nil {
 		logx.Errorf("Operation create err: %v", err)
@@ -509,7 +725,10 @@
 
 	db := models.NewOperationSearch().Orm.
 		Table("wms_operation").
-		Select("wms_operation.id,wms_operation.number,wms_operation.source_number,wms_operation.status,wms_operation_details.from_location_id,wms_operation_details.to_location_id,wms_operation.operation_date,wms_operation.contacter_id,wms_operation.contacter_name,wms_operation.company_id,wms_operation.company_name,wms_operation.comment,wms_operation_details.product_id,material.name as product_name,material.unit,wms_operation_details.amount,wms_operation.base_operation_type").
+		Select("wms_operation.id,wms_operation.number,wms_operation.source_number,wms_operation.status,wms_operation_details.from_location_id,"+
+			"wms_operation_details.to_location_id,wms_operation.operation_date,wms_operation.contacter_id,wms_operation.contacter_name,"+
+			"wms_operation.company_id,wms_operation.company_name,wms_operation.comment,wms_operation_details.product_id,"+
+			"material.name as product_name,material.unit,wms_operation_details.amount,wms_operation.base_operation_type").
 		InnerJoins("inner join wms_operation_details on wms_operation_details.operation_id=wms_operation.id").
 		InnerJoins("inner join material on material.id=wms_operation_details.product_id").
 		Where("wms_operation.base_operation_type=?", constvar.BaseOperationTypeDisuse)
@@ -826,3 +1045,70 @@
 
 	util.ResponseFormat(c, code.Success, "娣诲姞鎴愬姛")
 }
+
+// InputProduct
+//
+//	@Tags		浜у搧
+//	@Summary	瀵煎叆鐗╂枡/浜у搧
+//
+// @Accept multipart/form-data
+// @Param file formData file true "file"
+// @Param     Authorization	header string true "token"
+//
+//	@Produce	application/xlsx
+//	@Success	200		{object}	util.Response 	"鎴愬姛"
+//	@Router		/api-wms/v1/product/inputProduct [post]
+func (slf ProductController) InputProduct(c *gin.Context) {
+	file, _, err := c.Request.FormFile("file")
+	if err != nil {
+		util.ResponseFormat(c, code.RequestParamError, err.Error())
+		return
+	}
+	defer file.Close()
+	resp := response.MaterialInputRes{InputCount: 0, ErrCount: 0, FileAddress: ""}
+	userInfo := middleware.GetUserInfo(c)
+	insertCount, err := service.InputMaterial(file, userInfo.Username)
+	if err != nil {
+		util.ResponseFormat(c, code.RequestParamError, err.Error())
+		return
+	}
+	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