zhangqian
2024-06-12 e5df488268e29b272932e6cc1d2b1e7034590ba0
controllers/operation.go
@@ -2,16 +2,13 @@
import (
   "context"
   "encoding/json"
   "errors"
   "fmt"
   "github.com/gin-gonic/gin"
   uuid "github.com/satori/go.uuid"
   "github.com/shopspring/decimal"
   "github.com/xuri/excelize/v2"
   "google.golang.org/grpc"
   "google.golang.org/grpc/credentials/insecure"
   "gorm.io/gorm"
   "os"
   "sort"
   "strconv"
   "strings"
@@ -21,14 +18,17 @@
   "wms/extend/code"
   "wms/extend/util"
   "wms/models"
   "wms/opa"
   "wms/pkg/logx"
   "wms/pkg/mysqlx"
   "wms/pkg/structx"
   "wms/proto/client"
   "wms/proto/init_client"
   "wms/proto/inventory_order"
   "wms/proto/product_inventory"
   "wms/proto/purchase_wms"
   "wms/proto/supplier"
   "wms/request"
   "wms/response"
   "wms/service"
   "wms/utils/http"
   "wms/utils/upload"
@@ -59,6 +59,7 @@
      util.ResponseFormat(c, code.RequestParamError, err.Error())
      return
   }
   if err := slf.FormatLocation(&params); err != nil {
      util.ResponseFormat(c, code.RequestParamError, err.Error())
      return
@@ -76,8 +77,19 @@
   }
   params.Status = constvar.OperationStatus_Ready
   params.Number = strconv.FormatInt(time.Now().Unix(), 10)
   //params.Number = strconv.FormatInt(time.Now().Unix(), 10)
   params.BaseOperationType = operationType.BaseOperationType
   var numberNum int64
   if err := mysqlx.GetDB().Model(&models.Operation{}).Where("number=?", params.Number).Count(&numberNum).Error; err != nil {
      util.ResponseFormat(c, code.RequestParamError, err.Error())
      return
   }
   if numberNum > 0 {
      util.ResponseFormat(c, code.RequestParamError, "单号已存在")
      return
   }
   if err := models.NewOperationSearch().Create(&params); err != nil {
      logx.Errorf("Operation create err: %v", err)
      util.ResponseFormat(c, code.SaveFail, "添加失败:"+err.Error())
@@ -109,32 +121,41 @@
      return err
   }
   if operationType.BaseOperationType == constvar.BaseOperationTypeIncoming {
      if location, err := models.NewLocationSearch().SetType(int(constvar.LocationTypeVendor)).First(); err != nil {
      location, err := models.NewLocationSearch().SetType(int(constvar.LocationTypeVendor)).First()
      if err != nil {
         return err
      } else {
         params.FromLocationID = location.Id
      }
      if params.ToLocationID == 0 {
         return errors.New("请选择目标位置")
      for k, v := range params.Details {
         params.Details[k].FromLocationID = location.Id
         if v.ToLocationID == 0 {
            params.Details[k].ToLocationID = params.LocationID
         }
      }
   }
   if operationType.BaseOperationType == constvar.BaseOperationTypeOutgoing {
      if location, err := models.NewLocationSearch().SetType(int(constvar.LocationTypeCustomer)).First(); err != nil {
      location, err := models.NewLocationSearch().SetType(int(constvar.LocationTypeCustomer)).First()
      if err != nil {
         return err
      } else {
         params.ToLocationID = location.Id
      }
      if params.FromLocationID == 0 {
         return errors.New("请选择源位置")
      for k, v := range params.Details {
         params.Details[k].ToLocationID = location.Id
         if v.FromLocationID == 0 {
            return errors.New("请选择出库位置")
         }
      }
   }
   if operationType.BaseOperationType == constvar.BaseOperationTypeInternal {
      if params.ToLocationID == 0 {
         return errors.New("请选择目标位置")
      for _, v := range params.Details {
         if v.ToLocationID == 0 {
            return errors.New("请选择目标位置")
         }
         if v.FromLocationID == 0 {
            return errors.New("请选择源位置")
         }
      }
      if params.FromLocationID == 0 {
         return errors.New("请选择源位置")
      }
   }
   return nil
}
@@ -144,12 +165,20 @@
      return errors.New("请填入源单号")
   }
   if params.Number == "" {
      return errors.New("请填入单号")
   }
   if params.OperationTypeId == 0 && int(params.BaseOperationType) == 0 {
      return errors.New("未识别该记录类型")
   }
   if params.OperationDate == "" {
      return errors.New("请选择安排日期")
   }
   if params.LocationID == 0 {
      return errors.New("请选择源位置")
   }
   if len(params.Details) <= 0 {
@@ -363,8 +392,27 @@
      util.ResponseFormat(c, code.RequestError, "该出入库信息无法完成")
      return
   }
   if err := models.WithTransaction(func(tx *gorm.DB) error {
   listDetails, err := models.NewOperationDetailsSearch().SetOperationId(operation.Id).SetPreload(true).FindAll()
   if err != nil {
      util.ResponseFormat(c, code.RequestError, err.Error())
      return
   }
   var mapLocAmount map[string]*models.LocationProductAmount
   locAmountList, err := models.NewLocationProductAmountSearch().Find()
   if err != nil {
      util.ResponseFormat(c, code.RequestError, err.Error())
      return
   }
   if len(locAmountList) > 0 {
      mapLocAmount = make(map[string]*models.LocationProductAmount)
      for _, v := range locAmountList {
         mapLocAmount[strconv.Itoa(v.LocationId)+v.ProductId] = v
      }
   }
   err = models.WithTransaction(func(tx *gorm.DB) error {
      if err := models.NewOperationSearch().SetOrm(tx).SetID(id).Update(&models.Operation{Status: constvar.OperationStatus_Finish, AuditDate: time.Now().Format("2006-01-02 15:04:05")}); err != nil {
         return err
      }
@@ -372,360 +420,234 @@
         return err
      }
      var listProdtId []string
      var listProdt []*models.Material
      mapProdt := make(map[string]decimal.Decimal)
      listDetails, err := models.NewOperationDetailsSearch().SetOperationId(operation.Id).FindAll()
      if err != nil {
         return err
      }
      for _, v := range listDetails {
         listProdtId = append(listProdtId, v.ProductId)
         mapProdt[v.ProductId] = v.Amount
      }
      if err := models.NewMaterialSearch().Orm.Where("id IN ?", listProdtId).Find(&listProdt).Error; err != nil {
         return err
      }
      if operation.BaseOperationType == constvar.BaseOperationTypeIncoming {
         var operationInputs []*models.Operation
         for k, v := range listProdt {
            value, ok := mapProdt[v.ID]
            if !ok {
               return errors.New("产品种类异常")
         locationRoleList, err := models.NewLocationProductSearch().Find()
         if err != nil {
            return errors.New("获取上架规则信息失败")
         }
         var mapLocationRoleProduct, mapLocationRoleCategory map[string]*models.LocationProduct
         if len(locationRoleList) > 0 {
            mapLocationRoleProduct = make(map[string]*models.LocationProduct)
            mapLocationRoleCategory = make(map[string]*models.LocationProduct)
            for _, v := range locationRoleList {
               if v.RuleType == constvar.RuleType_Product {
                  mapLocationRoleProduct[strconv.Itoa(v.AreaId)+v.ProductId] = v
               }
               if v.RuleType == constvar.RuleType_ProductCategory {
                  mapLocationRoleCategory[strconv.Itoa(v.AreaId)+strconv.Itoa(v.ProductCategoryID)] = v
               }
            }
         }
            listProdt[k].Amount = listProdt[k].Amount.Add(value)
            if err := tx.Save(listProdt[k]).Error; err != nil {
         var details []*models.OperationDetails
         for k, v := range listDetails {
            listDetails[k].Product.Amount = listDetails[k].Product.Amount.Add(v.Amount)
            if err := tx.Save(&listDetails[k].Product).Error; err != nil {
               return err
            }
            locationRule, err := models.NewLocationProductSearch().SetProductId(v.ID).SetAreaId(operation.ToLocationID).First()
            if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
               return err
            }
            if err == nil {
               operationTransfer := &models.Operation{
                  Number:            operation.Number,
                  SourceNumber:      operation.SourceNumber,
                  OperationTypeId:   0,
                  OperationTypeName: operation.OperationTypeName,
                  Status:            constvar.OperationStatus_Finish,
                  FromLocationID:    locationRule.AreaId,
                  ToLocationID:      locationRule.LocationId,
                  OperationDate:     operation.OperationDate,
                  ContacterID:       operation.ContacterID,
                  ContacterName:     operation.ContacterName,
                  CompanyID:         operation.CompanyID,
                  CompanyName:       operation.CompanyName,
                  Comment:           operation.Comment,
                  BaseOperationType: constvar.BaseOperationTypeInternal,
                  Details: []*models.OperationDetails{
                     {
                        ProductId: v.ID,
                        Amount:    value,
                     },
                  },
            if roleProduct, ok := mapLocationRoleProduct[strconv.Itoa(operation.LocationID)+v.ProductId]; ok {
               detail := &models.OperationDetails{
                  ProductId:      v.ProductId,
                  Amount:         v.Amount,
                  FromLocationID: roleProduct.AreaId,
                  ToLocationID:   roleProduct.LocationId,
               }
               operationInputs = append(operationInputs, operationTransfer)
               details = append(details, detail)
               //if err := tx.Create(&operationTransfer).Error; err != nil {
               //   return err
               //}
               locAmount, err := models.NewLocationProductAmountSearch().
                  SetProductId(v.ID).
                  SetLocationId(locationRule.LocationId).
                  First()
               if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
                  return err
               }
               locAmount.LocationId = locationRule.LocationId
               locAmount.ProductId = v.ID
               locAmount.CreateDate = time.Now().Format("2006-01-02 15:04:05")
               locAmount.Amount = locAmount.Amount.Add(value)
               locAmount.ProductCategoryID = v.CategoryId
               if res := models.NewLocationProductAmountSearch().Orm.Where("id=?", locAmount.ID).Save(locAmount); res.Error != nil {
                  return res.Error
               }
            } else {
               locationRule, err = models.NewLocationProductSearch().SetProductCategoryId(v.CategoryId).SetAreaId(operation.ToLocationID).First()
               if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
                  return err
               }
               if err == nil {
                  operationTransfer := &models.Operation{
                     Number:            operation.Number,
                     SourceNumber:      operation.SourceNumber,
                     OperationTypeId:   0,
                     OperationTypeName: operation.OperationTypeName,
                     Status:            constvar.OperationStatus_Finish,
                     FromLocationID:    locationRule.AreaId,
                     ToLocationID:      locationRule.LocationId,
                     OperationDate:     operation.OperationDate,
                     ContacterID:       operation.ContacterID,
                     ContacterName:     operation.ContacterName,
                     CompanyID:         operation.CompanyID,
                     CompanyName:       operation.CompanyName,
                     Comment:           operation.Comment,
                     BaseOperationType: constvar.BaseOperationTypeInternal,
                     Details: []*models.OperationDetails{
                        {
                           ProductId: v.ID,
                           Amount:    value,
                        },
                     },
                  }
                  operationInputs = append(operationInputs, operationTransfer)
                  //if err := tx.Create(&operationTransfer).Error; err != nil {
                  //   return err
                  //}
                  locAmount, err := models.NewLocationProductAmountSearch().
                     SetProductId(v.ID).
                     SetLocationId(locationRule.LocationId).
                     First()
                  if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
                     return err
                  }
                  locAmount.LocationId = locationRule.LocationId
                  locAmount.ProductId = v.ID
                  locAmount.CreateDate = time.Now().Format("2006-01-02 15:04:05")
                  locAmount.Amount = locAmount.Amount.Add(value)
                  locAmount.ProductCategoryID = v.CategoryId
               if locAmount, aok := mapLocAmount[strconv.Itoa(roleProduct.LocationId)+v.ProductId]; aok {
                  locAmount.Amount = locAmount.Amount.Add(v.Amount)
                  if res := models.NewLocationProductAmountSearch().Orm.Where("id=?", locAmount.ID).Save(locAmount); res.Error != nil {
                     return res.Error
                  }
               } else {
                  locAmount, err := models.NewLocationProductAmountSearch().
                     SetProductId(v.ID).
                     SetLocationId(operation.ToLocationID).
                     First()
                  if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
                  if err := models.NewLocationProductAmountSearch().Create(&models.LocationProductAmount{
                     LocationId:        roleProduct.LocationId,
                     ProductCategoryID: v.Product.CategoryId,
                     ProductId:         v.ProductId,
                     Amount:            v.Amount,
                     CreateDate:        time.Now().Format("2006-01-02 15:04:05"),
                  }); err != nil {
                     return err
                  }
                  locAmount.LocationId = operation.ToLocationID
                  locAmount.ProductId = v.ID
                  locAmount.CreateDate = time.Now().Format("2006-01-02 15:04:05")
                  locAmount.Amount = locAmount.Amount.Add(value)
                  locAmount.ProductCategoryID = v.CategoryId
                  if res := models.NewLocationProductAmountSearch().Orm.Where("id=?", locAmount.ID).Save(locAmount); res.Error != nil {
                     return res.Error
               }
            } else {
               if roleCategory, cok := mapLocationRoleCategory[strconv.Itoa(operation.LocationID)+strconv.Itoa(v.Product.CategoryId)]; cok {
                  detail := &models.OperationDetails{
                     ProductId:      v.ProductId,
                     Amount:         v.Amount,
                     FromLocationID: roleCategory.AreaId,
                     ToLocationID:   roleCategory.LocationId,
                  }
                  details = append(details, detail)
                  if locAmount, aok := mapLocAmount[strconv.Itoa(roleCategory.LocationId)+v.ProductId]; aok {
                     locAmount.Amount = locAmount.Amount.Add(v.Amount)
                     if res := models.NewLocationProductAmountSearch().Orm.Where("id=?", locAmount.ID).Save(locAmount); res.Error != nil {
                        return res.Error
                     }
                  } else {
                     if err := models.NewLocationProductAmountSearch().Create(&models.LocationProductAmount{
                        LocationId:        roleCategory.LocationId,
                        ProductCategoryID: v.Product.CategoryId,
                        ProductId:         v.ProductId,
                        Amount:            v.Amount,
                        CreateDate:        time.Now().Format("2006-01-02 15:04:05"),
                     }); err != nil {
                        return err
                     }
                  }
               } else {
                  if locAmount, aok := mapLocAmount[strconv.Itoa(operation.LocationID)+v.ProductId]; aok {
                     locAmount.Amount = locAmount.Amount.Add(v.Amount)
                     if res := models.NewLocationProductAmountSearch().Orm.Where("id=?", locAmount.ID).Save(locAmount); res.Error != nil {
                        return res.Error
                     }
                  } else {
                     if err := models.NewLocationProductAmountSearch().Create(&models.LocationProductAmount{
                        LocationId:        operation.LocationID,
                        ProductCategoryID: v.Product.CategoryId,
                        ProductId:         v.ProductId,
                        Amount:            v.Amount,
                        CreateDate:        time.Now().Format("2006-01-02 15:04:05"),
                     }); err != nil {
                        return err
                     }
                  }
               }
            }
         }
         if len(operationInputs) > 0 {
            if err := tx.Create(&operationInputs).Error; err != nil {
         if len(details) > 0 {
            if err := tx.Create(&models.Operation{
               Number:            operation.Number,
               SourceNumber:      operation.SourceNumber,
               OperationTypeId:   0,
               OperationTypeName: operation.OperationTypeName,
               Status:            constvar.OperationStatus_Finish,
               OperationDate:     operation.OperationDate,
               ContacterID:       operation.ContacterID,
               ContacterName:     operation.ContacterName,
               CompanyID:         operation.CompanyID,
               CompanyName:       operation.CompanyName,
               Comment:           operation.Comment,
               BaseOperationType: constvar.BaseOperationTypeInternal,
               Details:           details,
            }).Error; err != nil {
               return err
            }
         }
         if operation.SourceNumber != "" {
            go UpdatePurchaseStatus(operation.SourceNumber)
         }
      }
      if operation.BaseOperationType == constvar.BaseOperationTypeOutgoing {
         for k, v := range listProdt {
            value, ok := mapProdt[v.ID]
            if !ok {
               return errors.New("产品种类异常")
            }
      if operation.BaseOperationType == constvar.BaseOperationTypeOutgoing || operation.BaseOperationType == constvar.BaseOperationTypeDisuse {
         for k, v := range listDetails {
            //todo 演示测试数据
            data, err := os.ReadFile("conf/input.json")
            if err != nil {
               return errors.New("文件读取失败")
            //data, err := os.ReadFile("conf/input.json")
            //if err != nil {
            //   return errors.New("文件读取失败")
            //}
            //m := make(map[string]interface{})
            //err = json.Unmarshal(data, &m)
            //if err != nil {
            //   return errors.New("格式转换失败")
            //}
            //if opa.OpaCheck(c, m, "operation") {
            //   if v.Product.Amount.LessThan(v.Amount) {
            //      return errors.New(fmt.Sprintf("产品:%v,库存:%v,出库:%v,数量不够,无法完成出库操作", v.Product.Name, v.Product.Amount.String(), v.Amount.String()))
            //   }
            //}
            //todo ================end===============================
            if v.Product.Amount.LessThan(v.Amount) {
               return errors.New(fmt.Sprintf("产品:%v,库存:%v,出库:%v,数量不够,无法完成出库操作", v.Product.Name, v.Product.Amount.String(), v.Amount.String()))
            }
            m := make(map[string]interface{})
            err = json.Unmarshal(data, &m)
            if err != nil {
               return errors.New("格式转换失败")
            listDetails[k].Product.Amount = listDetails[k].Product.Amount.Sub(v.Amount)
            if err := tx.Save(&listDetails[k].Product).Error; err != nil {
               return err
            }
            if opa.OpaCheck(c, m, "operation") {
               if v.Amount.LessThan(value) {
                  return errors.New(fmt.Sprintf("产品:%v,库存:%v,出库:%v,数量不够,无法完成出库操作", v.Name, v.Amount.String(), value.String()))
            if locAmount, aok := mapLocAmount[strconv.Itoa(v.FromLocationID)+v.ProductId]; aok {
               if locAmount.Amount.LessThan(v.Amount) {
                  return errors.New(fmt.Sprintf("产品:%v,库存:%v,出库:%v,数量不够,无法完成出库操作", v.Product.Name, locAmount.Amount.String(), v.Amount.String()))
               }
               locAmount.Amount = locAmount.Amount.Sub(v.Amount)
               if err := models.NewLocationProductAmountSearch().SetID(locAmount.Id).Update(locAmount); err != nil {
                  return err
               }
            } else {
               return errors.New("当前仓库没有该产品,请先入库")
            }
            listProdt[k].Amount = listProdt[k].Amount.Sub(value)
            if err := tx.Save(listProdt[k]).Error; err != nil {
               return err
            }
            locAmount, res := models.NewLocationProductAmountSearch().
               SetProductId(v.ID).
               SetLocationId(operation.ToLocationID).
               FirstRes()
            if res.Error != nil {
               return err
            }
            if locAmount.Amount.LessThan(value) {
               return errors.New(fmt.Sprintf("产品:%v,库存:%v,出库:%v,数量不够,无法完成出库操作", v.Name, v.Amount.String(), value.String()))
            }
            locAmount.Amount = locAmount.Amount.Sub(value)
            if err := models.NewLocationProductAmountSearch().SetID(locAmount.Id).Update(locAmount); err != nil {
               return err
            }
         }
         if operation.SourceNumber != "" {
            go UpdateSalesDetailStatus(operation.SourceNumber)
         }
      }
      if operation.BaseOperationType == constvar.BaseOperationTypeInternal {
         var operationInputs []*models.Operation
         for _, v := range listProdt {
            value, ok := mapProdt[v.ID]
            if !ok {
               return errors.New("产品种类异常")
            }
            //listProdt[k].Amount = listProdt[k].Amount.Add(value)
            //if err := tx.Save(listProdt[k]).Error; err != nil {
            //   return err
            //}
            fromLocAmount, res := models.NewLocationProductAmountSearch().
               SetProductId(v.ID).
               SetLocationId(operation.FromLocationID).
               FirstRes()
            if res.Error != nil {
               return err
            }
            if fromLocAmount.Amount.LessThan(value) {
               return errors.New(fmt.Sprintf("产品:%v,库存:%v,调拨:%v,数量不够,无法完成调拨操作", v.Name, v.Amount.String(), value.String()))
            }
            fromLocAmount.Amount = fromLocAmount.Amount.Sub(value)
            if err := models.NewLocationProductAmountSearch().SetID(fromLocAmount.Id).Update(fromLocAmount); err != nil {
               return err
            }
            locationRule, err := models.NewLocationProductSearch().SetProductId(v.ID).SetAreaId(operation.ToLocationID).First()
            if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
               return err
            }
            if err == nil {
               operationTransfer := &models.Operation{
                  Number:            operation.Number,
                  SourceNumber:      operation.SourceNumber,
                  OperationTypeId:   0,
                  OperationTypeName: operation.OperationTypeName,
                  Status:            constvar.OperationStatus_Finish,
                  FromLocationID:    locationRule.AreaId,
                  ToLocationID:      locationRule.LocationId,
                  OperationDate:     operation.OperationDate,
                  ContacterID:       operation.ContacterID,
                  ContacterName:     operation.ContacterName,
                  CompanyID:         operation.CompanyID,
                  CompanyName:       operation.CompanyName,
                  Comment:           operation.Comment,
                  BaseOperationType: constvar.BaseOperationTypeInternal,
                  Details: []*models.OperationDetails{
                     {
                        ProductId: v.ID,
                        Amount:    value,
                     },
                  },
         for _, v := range listDetails {
            if fromLocAmount, aok := mapLocAmount[strconv.Itoa(v.FromLocationID)+v.ProductId]; aok {
               if fromLocAmount.Amount.LessThan(v.Amount) {
                  return errors.New(fmt.Sprintf("产品:%v,库存:%v,出库:%v,数量不够,无法完成出库操作", v.Product.Name, fromLocAmount.Amount.String(), v.Amount.String()))
               }
               operationInputs = append(operationInputs, operationTransfer)
               //if err := tx.Create(&operationTransfer).Error; err != nil {
               //   return err
               //}
               locAmount, err := models.NewLocationProductAmountSearch().
                  SetProductId(v.ID).
                  SetLocationId(locationRule.LocationId).
                  First()
               if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
               fromLocAmount.Amount = fromLocAmount.Amount.Sub(v.Amount)
               if err := models.NewLocationProductAmountSearch().SetID(fromLocAmount.Id).Update(fromLocAmount); err != nil {
                  return err
               }
               locAmount.LocationId = locationRule.LocationId
               locAmount.ProductId = v.ID
               locAmount.CreateDate = time.Now().Format("2006-01-02 15:04:05")
               locAmount.Amount = locAmount.Amount.Add(value)
               locAmount.ProductCategoryID = v.CategoryId
            } else {
               return errors.New("当前仓库没有该产品,请先入库")
            }
            if toLocAmount, aok := mapLocAmount[strconv.Itoa(v.ToLocationID)+v.ProductId]; aok {
               toLocAmount.Amount = toLocAmount.Amount.Add(v.Amount)
               if err := models.NewLocationProductAmountSearch().SetID(toLocAmount.Id).Update(toLocAmount); err != nil {
                  return err
               }
            } else {
               if err := models.NewLocationProductAmountSearch().Create(&models.LocationProductAmount{
                  LocationId:        v.ToLocationID,
                  ProductCategoryID: v.Product.CategoryId,
                  ProductId:         v.ProductId,
                  Amount:            v.Amount,
                  CreateDate:        time.Now().Format("2006-01-02 15:04:05"),
               }); err != nil {
                  return err
               }
            }
         }
      }
      if operation.BaseOperationType == constvar.BaseOperationTypeAdjust {
         for _, v := range listDetails {
            if locAmount, aok := mapLocAmount[strconv.Itoa(v.ToLocationID)+v.ProductId]; aok {
               locAmount.Amount = v.Amount
               if res := models.NewLocationProductAmountSearch().Orm.Where("id=?", locAmount.ID).Save(locAmount); res.Error != nil {
                  return res.Error
               }
            } else {
               locationRule, err = models.NewLocationProductSearch().SetProductCategoryId(v.CategoryId).SetAreaId(operation.ToLocationID).First()
               if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
               if err := models.NewLocationProductAmountSearch().Create(&models.LocationProductAmount{
                  LocationId:        v.ToLocationID,
                  ProductCategoryID: v.Product.CategoryId,
                  ProductId:         v.ProductId,
                  Amount:            v.Amount,
                  CreateDate:        time.Now().Format("2006-01-02 15:04:05"),
               }); err != nil {
                  return err
               }
               if err == nil {
                  operationTransfer := &models.Operation{
                     Number:            operation.Number,
                     SourceNumber:      operation.SourceNumber,
                     OperationTypeId:   0,
                     OperationTypeName: operation.OperationTypeName,
                     Status:            constvar.OperationStatus_Finish,
                     FromLocationID:    locationRule.AreaId,
                     ToLocationID:      locationRule.LocationId,
                     OperationDate:     operation.OperationDate,
                     ContacterID:       operation.ContacterID,
                     ContacterName:     operation.ContacterName,
                     CompanyID:         operation.CompanyID,
                     CompanyName:       operation.CompanyName,
                     Comment:           operation.Comment,
                     BaseOperationType: constvar.BaseOperationTypeInternal,
                     Details: []*models.OperationDetails{
                        {
                           ProductId: v.ID,
                           Amount:    value,
                        },
                     },
                  }
                  operationInputs = append(operationInputs, operationTransfer)
                  //if err := tx.Create(&operationTransfer).Error; err != nil {
                  //   return err
                  //}
                  locAmount, err := models.NewLocationProductAmountSearch().
                     SetProductId(v.ID).
                     SetLocationId(locationRule.LocationId).
                     First()
                  if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
                     return err
                  }
                  locAmount.LocationId = locationRule.LocationId
                  locAmount.ProductId = v.ID
                  locAmount.CreateDate = time.Now().Format("2006-01-02 15:04:05")
                  locAmount.Amount = locAmount.Amount.Add(value)
                  locAmount.ProductCategoryID = v.CategoryId
                  if res := models.NewLocationProductAmountSearch().Orm.Where("id=?", locAmount.ID).Save(locAmount); res.Error != nil {
                     return res.Error
                  }
               } else {
                  locAmount, err := models.NewLocationProductAmountSearch().
                     SetProductId(v.ID).
                     SetLocationId(operation.ToLocationID).
                     First()
                  if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
                     return err
                  }
                  locAmount.LocationId = operation.ToLocationID
                  locAmount.ProductId = v.ID
                  locAmount.CreateDate = time.Now().Format("2006-01-02 15:04:05")
                  locAmount.Amount = locAmount.Amount.Add(value)
                  if res := models.NewLocationProductAmountSearch().Orm.Where("id=?", locAmount.ID).Save(locAmount); res.Error != nil {
                     return res.Error
                  }
               }
            }
         }
         if len(operationInputs) > 0 {
            if err := tx.Create(&operationInputs).Error; err != nil {
               return err
            }
         }
      }
      return nil
   }); err != nil {
   })
   if err != nil {
      util.ResponseFormat(c, code.RequestError, err.Error())
      return
   }
   //修改其他系统订单状态
   if operation.BaseOperationType == constvar.BaseOperationTypeIncoming {
      if operation.Source != "" {
         go UpdatePurchaseStatus(operation.Source, operation.SourceNumber)
         go UpdateOutsourceOrder(operation.Source, operation.SourceNumber, operation.Id, listDetails)
      }
   } else if operation.BaseOperationType == constvar.BaseOperationTypeOutgoing {
      if operation.Source != "" {
         go UpdateOutStatus(operation.Source, operation.SourceNumber, 4)
      }
   }
   util.ResponseFormat(c, code.Success, "操作成功")
@@ -733,6 +655,7 @@
func AddMoveHistory(operationList []*models.Operation, db *gorm.DB) error {
   var histories []*models.MoveHistory
   operationMap := make(map[int]*models.Operation, len(operationList))
   for _, operation := range operationList {
      for _, v := range operation.Details {
         history := &models.MoveHistory{
@@ -746,67 +669,108 @@
            Amount:            v.Amount,
            Unit:              v.Product.Unit,
            Weight:            operation.Weight,
            FromLocationId:    operation.FromLocationID,
            FromLocation:      operation.FromLocation.Name,
            ToLocationId:      operation.ToLocationID,
            ToLocation:        operation.ToLocation.Name,
            FromLocationId:    v.FromLocationID,
            FromLocation:      v.FromLocation.Name,
            ToLocationId:      v.ToLocationID,
            ToLocation:        v.ToLocation.Name,
         }
         histories = append(histories, history)
      }
      operationMap[operation.Id] = operation
   }
   if err := db.Model(&models.MoveHistory{}).Create(&histories).Error; err != nil {
      return err
   }
   for _, history := range histories {
      service.AddNewHistoryReportRecord(history.Id)
      service.AddNewHistoryReportRecord(history, operationMap[history.OperationId])
   }
   return nil
}
var (
   ProductInventoryServiceConn *grpc.ClientConn
   PurchaseServiceConn         *grpc.ClientConn
)
//var (
//   ProductInventoryServiceConn *grpc.ClientConn
//   PurchaseServiceConn         *grpc.ClientConn
//)
//
//func InitProductInventoryServiceConn() {
//   var err error
//   ProductInventoryServiceConn, err = grpc.Dial(conf.GrpcServerConf.CrmAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
//   if err != nil {
//      logx.Errorf("grpc dial product service error: %v", err.Error())
//      return
//   }
//   PurchaseServiceConn, err = grpc.Dial(conf.GrpcServerConf.SrmAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
//   if err != nil {
//      logx.Errorf("grpc dial product service error: %v", err.Error())
//      return
//   }
//}
//
//func CloseProductInventoryServiceConn() {
//   if ProductInventoryServiceConn != nil {
//      ProductInventoryServiceConn.Close()
//   }
//   if PurchaseServiceConn != nil {
//      PurchaseServiceConn.Close()
//   }
//}
func InitProductInventoryServiceConn() {
   var err error
   ProductInventoryServiceConn, err = grpc.Dial(conf.GrpcServerConf.CrmAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
   if err != nil {
      logx.Errorf("grpc dial product service error: %v", err.Error())
      return
func UpdateOutStatus(source, number string, status int64) {
   if source == "CRM" {
      cl := product_inventory.NewProductInventoryServiceClient(init_client.CrmConn)
      _, err := cl.UpdateSalesDetailStatus(context.Background(), &product_inventory.UpdateSalesDetailStatusRequest{
         Number:            number,
         SalesDetailStatus: "已出库",
      })
      if err != nil {
         logx.Errorf("grpc dial UpdateSalesDetailStatus service error: %v", err)
      }
   }
   PurchaseServiceConn, err = grpc.Dial(conf.GrpcServerConf.SrmAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
   if err != nil {
      logx.Errorf("grpc dial product service error: %v", err.Error())
      return
   if source == "APS_APPLY_MATERIAL" {
      cl := inventory_order.NewInventoryOrderServiceClient(init_client.ApsConn)
      _, err := cl.UpdateMaterialApplyStatus(context.Background(), &inventory_order.UpdateMaterialApplyStatusRequest{
         Number: number,
         Status: status,
      })
      if err != nil {
         logx.Errorf("grpc dial UpdateSalesDetailStatus service error: %v", err)
      }
   }
}
func CloseProductInventoryServiceConn() {
   if ProductInventoryServiceConn != nil {
      ProductInventoryServiceConn.Close()
   }
   if PurchaseServiceConn != nil {
      PurchaseServiceConn.Close()
func UpdatePurchaseStatus(source, number string) {
   if source == "SRM_PURCHASE" {
      count, err := models.NewOperationSearch().SetSourceNumber(number).SetStatus(constvar.OperationStatus_Ready).Count()
      if err != nil || count > 0 {
         return
      }
      cl := purchase_wms.NewPurchaseServiceClient(init_client.SrmConn)
      _, err = cl.UpdatePurchaseStatus(context.Background(), &purchase_wms.UpdatePurchaseStatusRequest{Number: number})
      if err != nil {
         logx.Errorf("grpc dial UpdatePurchaseStatus service error: %v", err)
      }
   }
}
func UpdateSalesDetailStatus(number string) {
   client := product_inventory.NewProductInventoryServiceClient(ProductInventoryServiceConn)
   _, err := client.UpdateSalesDetailStatus(context.Background(), &product_inventory.UpdateSalesDetailStatusRequest{
      Number:            number,
      SalesDetailStatus: "已出库",
   })
   if err != nil {
      logx.Errorf("grpc dial UpdateSalesDetailStatus service error: %v", err)
   }
}
func UpdatePurchaseStatus(number string) {
   client := purchase_wms.NewPurchaseServiceClient(PurchaseServiceConn)
   _, err := client.UpdatePurchaseStatus(context.Background(), &purchase_wms.UpdatePurchaseStatusRequest{Number: number})
   if err != nil {
      logx.Errorf("grpc dial UpdatePurchaseStatus service error: %v", err)
func UpdateOutsourceOrder(source, number string, operationId int, details []*models.OperationDetails) {
   if source == "APS_OUTSOURCING_RECEIVE" {
      products := make([]*inventory_order.OperationProduct, 0)
      for _, detail := range details {
         if operationId == detail.OperationID {
            var op inventory_order.OperationProduct
            op.ProductNumber = detail.ProductId
            op.Amount = detail.Amount.IntPart()
            products = append(products, &op)
         }
      }
      cl := inventory_order.NewInventoryOrderServiceClient(init_client.ApsConn)
      _, err := cl.UpdateOutsourceOrder(context.Background(), &inventory_order.UpdateOutsourceOrderRequest{
         OutsourceNumber: number,
         Products:        products,
      })
      if err != nil {
         logx.Errorf("grpc dial UpdateOutsourceOrder service error: %v", err)
      }
   }
}
@@ -889,6 +853,10 @@
      util.ResponseFormat(c, code.SaveFail, err.Error())
      return
   }
   //更新aps物料申请状态
   if operation.Source == "APS_APPLY_MATERIAL" {
      go UpdateOutStatus(operation.Source, operation.SourceNumber, 3)
   }
   util.ResponseFormat(c, code.Success, "操作成功")
}
@@ -921,32 +889,56 @@
   }
   var fileUrl string
   companyName := conf.WebConf.CompanyName
   if companyName == "" {
      util.ResponseFormat(c, code.RequestParamError, "缺少工厂名称配置")
      return
   }
   if operation.BaseOperationType == constvar.BaseOperationTypeIncoming {
      fileUrl, err = ExportInputSelfmade(constvar.FileTemplateCategory_Selfmade, operation)
      if err != nil {
         util.ResponseFormat(c, code.RequestParamError, err.Error())
         return
      if companyName == "jialian" {
         fileUrl, err = JialianOperation(constvar.FileTemplateCategory_JialianInput, operation)
         if err != nil {
            util.ResponseFormat(c, code.RequestParamError, err.Error())
            return
         }
      } else if companyName == "geruimi" {
         fileUrl, err = ExportInputSelfmade(constvar.FileTemplateCategory_Selfmade, operation)
         if err != nil {
            util.ResponseFormat(c, code.RequestParamError, err.Error())
            return
         }
      }
   } else if operation.BaseOperationType == constvar.BaseOperationTypeOutgoing {
      fileUrl, err = ExportOutputOperation(constvar.FileTemplateCategory_Output, operation)
      if err != nil {
         util.ResponseFormat(c, code.RequestParamError, err.Error())
         return
      if companyName == "jialian" {
         fileUrl, err = JialianOperation(constvar.FileTemplateCategory_JialianOutput, operation)
         if err != nil {
            util.ResponseFormat(c, code.RequestParamError, err.Error())
            return
         }
      } else if companyName == "geruimi" {
         fileUrl, err = ExportInputSelfmade(constvar.FileTemplateCategory_Output, operation)
         if err != nil {
            util.ResponseFormat(c, code.RequestParamError, err.Error())
            return
         }
      }
   } else {
      util.ResponseFormat(c, code.RequestParamError, "该记录不支持打印")
      return
   }
   util.ResponseFormat(c, code.Success, fileUrl)
   m := make(map[string]string)
   m["url"] = fileUrl
   m["name"] = companyName
   util.ResponseFormat(c, code.Success, m)
}
func ExportInputSelfmade(category constvar.FileTemplateCategory, operation *models.Operation) (string, error) {
   template, err := models.NewFileTemplateAttachmentSearch().SetPreload(true).SetCategory(category).First()
func JialianOperation(category constvar.FileTemplateCategory, operation *models.Operation) (string, error) {
   template, err := models.NewFileTemplateAttachmentSearch().SetCategory(category).First()
   if err != nil {
      return "", errors.New("获取模版记录失败:" + err.Error())
   }
   readerCloser, err := http.HttpGetWithReadCloser(template.Attachment.FileUrl)
   readerCloser, err := http.HttpGetWithReadCloser(template.FileUrl)
   if err != nil {
      return "", errors.New("获取模版失败:" + err.Error())
   }
@@ -956,6 +948,108 @@
      return "", errors.New("读取excel模版失败:" + err.Error())
   }
   readerCloser.Close()
   defer f.Close()
   f.SetCellValue("Sheet1", "H2", operation.OperationDate)
   f.SetCellValue("Sheet1", "O2", operation.Number)
   rowIndex := 5
   totalAmount := decimal.NewFromInt(0)
   totalPrice := decimal.NewFromInt(0)
   for i, v := range operation.Details {
      //设置表单最多9条数据
      if i > 8 {
         break
      }
      f.SetCellValue("Sheet1", "A"+strconv.Itoa(rowIndex), v.Product.Name)
      f.SetCellValue("Sheet1", "B"+strconv.Itoa(rowIndex), v.Product.Type)
      f.SetCellValue("Sheet1", "C"+strconv.Itoa(rowIndex), v.Product.Unit)
      f.SetCellValue("Sheet1", "D"+strconv.Itoa(rowIndex), v.Amount.String())
      f.SetCellValue("Sheet1", "E"+strconv.Itoa(rowIndex), v.Product.SalePrice.String())
      if !v.Product.SalePrice.IsZero() {
         ap := v.Amount.Mul(v.Product.SalePrice)
         totalPrice = totalPrice.Add(ap)
         price := ap.String()
         split := strings.Split(price, ".")
         if len(split) == 2 {
            for n, a := range split[1] {
               f.SetCellValue("Sheet1", string('M'+n)+strconv.Itoa(rowIndex), string(a))
            }
         }
         s := split[0]
         n := 0
         for j := len(s) - 1; j >= 0; j-- {
            if n == 6 {
               f.SetCellValue("Sheet1", string('L'-n)+strconv.Itoa(rowIndex), s[:j])
               break
            }
            f.SetCellValue("Sheet1", string('L'-n)+strconv.Itoa(rowIndex), string(s[j]))
            n++
         }
      }
      rowIndex++
      totalAmount = totalAmount.Add(v.Amount)
   }
   //合计
   if !totalPrice.IsZero() {
      price := totalPrice.String()
      split := strings.Split(price, ".")
      if len(split) == 2 {
         for n, a := range split[1] {
            f.SetCellValue("Sheet1", string('M'+n)+"14", string(a))
         }
      } else {
         f.SetCellValue("Sheet1", "M14", "0")
         f.SetCellValue("Sheet1", "N14", "0")
      }
      s := split[0]
      n := 0
      for j := len(s) - 1; j >= 0; j-- {
         if n == 6 {
            f.SetCellValue("Sheet1", string('L'-n)+"14", s[:j])
            break
         }
         f.SetCellValue("Sheet1", string('L'-n)+"14", string(s[j]))
         n++
      }
   }
   f.SetCellValue("Sheet1", "D14", totalAmount)
   f.SetCellValue("Sheet1", "B15", operation.Manager)
   f.SetCellValue("Sheet1", "D15", operation.Accountant)
   f.SetCellValue("Sheet1", "F15", operation.Custodian)
   buf, err := f.WriteToBuffer()
   if err != nil {
      return "", err
   }
   fileUrl, err := upload.UploadFileToSeaWeed(string(constvar.FileType_File), uuid.NewV4().String()+".xlsx", buf.Bytes())
   if err != nil {
      logx.Errorf("file upload err: %v", err)
      return "", err
   }
   return fileUrl, nil
}
func ExportInputSelfmade(category constvar.FileTemplateCategory, operation *models.Operation) (string, error) {
   template, err := models.NewFileTemplateAttachmentSearch().SetCategory(category).First()
   if err != nil {
      return "", errors.New("获取模版记录失败:" + err.Error())
   }
   readerCloser, err := http.HttpGetWithReadCloser(template.FileUrl)
   if err != nil {
      return "", errors.New("获取模版失败:" + err.Error())
   }
   f, err := excelize.OpenReader(readerCloser)
   if err != nil {
      return "", errors.New("读取excel模版失败:" + err.Error())
   }
   readerCloser.Close()
   defer f.Close()
   style, _ := f.NewStyle(&excelize.Style{
      Border: []excelize.Border{
@@ -988,7 +1082,7 @@
      f.SetCellValue("Sheet1", "C"+strconv.Itoa(rowIndex), v.Product.Specs)
      f.SetCellValue("Sheet1", "D"+strconv.Itoa(rowIndex), v.Product.Unit)
      f.SetCellValue("Sheet1", "E"+strconv.Itoa(rowIndex), v.Amount.String())
      f.SetCellValue("Sheet1", "H"+strconv.Itoa(rowIndex), operation.ToLocation.Name)
      f.SetCellValue("Sheet1", "H"+strconv.Itoa(rowIndex), v.ToLocation.Name)
      f.SetCellValue("Sheet1", "I"+strconv.Itoa(rowIndex), operation.Comment)
      rowIndex++
      totalAmount = totalAmount.Add(v.Amount)
@@ -1011,7 +1105,7 @@
      return "", err
   }
   fileUrl, err := upload.UploadFileToSeaWeed(string(constvar.FileType_File), "xlsx", buf.Bytes())
   fileUrl, err := upload.UploadFileToSeaWeed(string(constvar.FileType_File), uuid.NewV4().String()+".xlsx", buf.Bytes())
   if err != nil {
      logx.Errorf("file upload err: %v", err)
      return "", err
@@ -1021,12 +1115,12 @@
}
func ExportOutputOperation(category constvar.FileTemplateCategory, operation *models.Operation) (string, error) {
   repositoryLevels := strings.Split(operation.FromLocation.JointName, "/")
   template, err := models.NewFileTemplateAttachmentSearch().SetPreload(true).SetCategory(category).First()
   repositoryLevels := strings.Split(operation.Location.JointName, "/")
   template, err := models.NewFileTemplateAttachmentSearch().SetCategory(category).First()
   if err != nil {
      return "", errors.New("获取模版记录失败:" + err.Error())
   }
   readerCloser, err := http.HttpGetWithReadCloser(template.Attachment.FileUrl)
   readerCloser, err := http.HttpGetWithReadCloser(template.FileUrl)
   if err != nil {
      return "", errors.New("获取模版失败:" + err.Error())
   }
@@ -1036,6 +1130,7 @@
      return "", errors.New("读取excel模版失败:" + err.Error())
   }
   readerCloser.Close()
   defer f.Close()
   style, _ := f.NewStyle(&excelize.Style{
      Border: []excelize.Border{
@@ -1087,7 +1182,7 @@
      return "", err
   }
   fileUrl, err := upload.UploadFileToSeaWeed(string(constvar.FileType_File), "xlsx", buf.Bytes())
   fileUrl, err := upload.UploadFileToSeaWeed(string(constvar.FileType_File), uuid.NewV4().String()+".xlsx", buf.Bytes())
   if err != nil {
      logx.Errorf("file upload err: %v", err)
      return "", err
@@ -1106,7 +1201,7 @@
//
// @Router    /api-wms/v1/operation/getSupplierList [get]
func (slf OperationController) GetSupplierList(c *gin.Context) {
   cli := supplier.NewSupplierServiceClient(supplier.SupplierConn)
   cli := supplier.NewSupplierServiceClient(init_client.SrmConn)
   resp, err := cli.GetSupplierList(c, &supplier.SupplierListRequest{Status: 1})
   if err != nil {
      util.ResponseFormat(c, code.RequestParamError, "grpc调用失败:"+err.Error())
@@ -1124,7 +1219,7 @@
//
// @Router    /api-wms/v1/operation/getClientList [get]
func (slf OperationController) GetClientList(c *gin.Context) {
   cli := client.NewClientServiceClient(client.ClientConn)
   cli := client.NewClientServiceClient(init_client.CrmConn)
   resp, err := cli.GetClientList(c, &client.ClientListRequest{})
   if err != nil {
      util.ResponseFormat(c, code.RequestParamError, "grpc调用失败:"+err.Error())
@@ -1132,3 +1227,68 @@
   }
   util.ResponseFormat(c, code.Success, resp.List)
}
// ListByCondition
// @Tags      入库/出库
// @Summary   出入库明细
// @Produce   application/json
// @Param     object  body  request.OperationCondition true  "参数"
// @Success   200 {object} util.Response "成功"
// @Router    /api-wms/v1/operation/listByCondition [post]
func (slf OperationController) ListByCondition(c *gin.Context) {
   var params request.OperationCondition
   if err := c.BindJSON(&params); err != nil {
      util.ResponseFormat(c, code.RequestParamError, "参数解析失败,数据类型错误:"+err.Error())
      return
   }
   if !params.PageInfo.Check() {
      util.ResponseFormat(c, code.RequestParamError, "数据分页信息错误")
      return
   }
   db := mysqlx.GetDB().Table("wms_operation").
      Select("wms_operation.id as operation_id,wms_operation.number,wms_operation.base_operation_type,material.id AS product_id," +
         "material.`name` AS product_name,wms_operation_details.amount,material.unit,wms_operation_details.from_location_id," +
         "from_location.`name` AS from_location,wms_operation_details.to_location_id,to_location.`name` AS to_location," +
         "wms_operation.operation_date as date,wms_operation.`status`,material.weight,wms_operation.operation_type_name").
      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").
      InnerJoins("INNER JOIN wms_location AS from_location ON from_location.id = wms_operation_details.from_location_id").
      InnerJoins("INNER JOIN wms_location AS to_location ON to_location.id = wms_operation_details.to_location_id")
   if params.Condition != "" {
      db = db.Where("wms_operation.number like ? or wms_operation.source_number like ? or from_location.`name` like ? or to_location.`name` like ? or material.`name` like ? ", "%"+params.Condition+"%", "%"+params.Condition+"%", "%"+params.Condition+"%", "%"+params.Condition+"%", "%"+params.Condition+"%")
   }
   var (
      records = make([]*response.InventoryHistory, 0)
      total   int64
   )
   if err := db.Count(&total).Error; err != nil {
      util.ResponseFormat(c, code.RequestError, "查找失败:"+err.Error())
      return
   }
   if err := db.Offset((params.Page - 1) * params.PageSize).Limit(params.PageSize).Order("wms_operation.created_at desc").Find(&records).Error; err != nil {
      util.ResponseFormat(c, code.RequestError, "查找失败:"+err.Error())
      return
   }
   util.ResponseFormatListWithPage(c, code.Success, records, int(total), params.Page, params.PageSize)
}
// GetPersonnelList
// @Tags      入库/出库
// @Summary   获取人员列表
// @Produce   application/json
// @Param     object  body  request.OperationCondition true  "参数"
// @Success   200 {object} util.ResponseList{data=[]inventory_order.WorkerInfo} "成功"
// @Router    /api-wms/v1/operation/getPersonnelList [get]
func (slf OperationController) GetPersonnelList(c *gin.Context) {
   cli := inventory_order.NewInventoryOrderServiceClient(init_client.ApsConn)
   list, err := cli.GetWorkerList(context.Background(), &inventory_order.GetWorkerListRequest{})
   if err != nil {
      util.ResponseFormat(c, code.RequestParamError, "内部错误")
      logx.Error("grpc调用失败, GetPersonnelList err : " + err.Error())
      return
   }
   util.ResponseFormat(c, code.Success, list.List)
}