From fc3313955a083c9480e4ea74398f72f9ba6addcd Mon Sep 17 00:00:00 2001
From: zhangqian <zhangqian@123.com>
Date: 星期四, 01 八月 2024 20:29:51 +0800
Subject: [PATCH] 月度统计查询多单位数据计算改查询。

---
 models/location_product_amount.go |  216 +++++++++++++++++++++++++++++++++++++++++++++++------
 1 files changed, 191 insertions(+), 25 deletions(-)

diff --git a/models/location_product_amount.go b/models/location_product_amount.go
index 00c7b92..279ab69 100644
--- a/models/location_product_amount.go
+++ b/models/location_product_amount.go
@@ -1,6 +1,7 @@
 package models
 
 import (
+	"encoding/json"
 	"fmt"
 	"github.com/shopspring/decimal"
 	"gorm.io/gorm"
@@ -9,19 +10,21 @@
 )
 
 type (
+	// LocationProductAmount 搴撳瓨浜у搧鏁伴噺
 	LocationProductAmount struct {
 		WmsModel
-		Id int `json:"id"  gorm:"column:id;primary_key;AUTO_INCREMENT"`
-		//LocationProductId int             `json:"locationProductId" gorm:"type:int;not null;comment:涓婃灦瑙勫垯id"` //涓婃灦瑙勫垯id
-		//LocationProduct   LocationProduct `json:"locationProduct" gorm:"foreignKey:LocationProductId;references:Id"`
-		LocationId        int             `json:"locationId" gorm:"type:int;not null;comment:浣嶇疆id"` //浣嶇疆id
+		Id                int             `json:"id"  gorm:"column:id;primary_key;AUTO_INCREMENT"`
+		LocationId        int             `json:"locationId" gorm:"type:int;not null;comment:浣嶇疆id"`            //浣嶇疆id
+		WarehouseId       int             `json:"warehouseId" gorm:"type:int;not null;default:0;comment:浠撳簱id"` // 浠撳簱id
 		Location          Location        `json:"location" gorm:"foreignKey:LocationId;references:id"`
 		ProductCategoryID int             `json:"productCategoryId" gorm:"type:int;not null;comment:浜у搧绉嶇被id"` //浜у搧绉嶇被id
-		ProductCategory   ProductCategory `json:"productCategory"`
+		ProductCategory   ProductCategory `json:"productCategory" gorm:"foreignKey:ProductCategoryID;references:Id"`
 		ProductId         string          `json:"productId" gorm:"type:varchar(191);not null;comment:浜у搧id"` //浜у搧id
 		Product           Material        `json:"product" gorm:"foreignKey:ProductId;references:ID"`
 		Amount            decimal.Decimal `json:"amount" gorm:"type:decimal(20,2);not null;comment:搴撳瓨鏁伴噺"` //搴撳瓨鏁伴噺
-		CreateDate        string          `json:"createDate" gorm:"type:varchar(63);comment:鏃ユ湡"`          //鏃ユ湡
+		MoreUnitList      []UnitItems     `json:"amountMoreUnits" gorm:"-"`                               //鍦ㄥ簱鏁伴噺澶氬崟浣�
+		MoreUnitValue     string          `json:"-" gorm:"type:varchar(255);comment:澶氬崟浣嶅��"`
+		CreateDate        string          `json:"createDate" gorm:"type:varchar(63);comment:鏃ユ湡"` //鏃ユ湡
 	}
 
 	LocationProductAmountSearch struct {
@@ -33,7 +36,13 @@
 		Orm      *gorm.DB
 		Preload  bool
 		//LocationProductIds []int
-		LocationIds []int
+		LocationIds     []int
+		ProductIds      []string
+		Ids             []int
+		Query           string
+		Fields          string
+		CategoryIds     []int
+		JoinedMaterials bool
 	}
 
 	LocationProductAmountWithOperation struct {
@@ -44,18 +53,51 @@
 		ProductId               string                     `json:"productId" gorm:"column:product_id"`
 		ProductName             string                     `json:"productName" gorm:"column:product_name"`
 		Amount                  decimal.Decimal            `json:"amount" gorm:"column:amount"`
-		Unit                    string                     `json:"unit" gorm:"column:unit"`
-		CreateDate              string                     `json:"createDate" gorm:"column:create_date"`
-		AdjustAmount            decimal.Decimal            `json:"adjustAmount" gorm:"column:adjust_amount"`
-		DifferenceAmount        decimal.Decimal            `json:"differenceAmount" gorm:"-"`
-		OperationId             int                        `json:"operationId" gorm:"column:operation_id"`
-		Status                  constvar.OperationStatus   `json:"status" gorm:"status"`
-		BaseOperationType       constvar.BaseOperationType `json:"baseOperationType" gorm:"base_operation_type"`
+		AmountMoreUnits         []UnitItems                `json:"amountMoreUnits" gorm:"-"` //鍦ㄥ簱鏁伴噺澶氬崟浣�
+		Unit                    string                     `json:"unit" gorm:"column:unit;size:50;comment:鐗╁搧鍗曚綅"`
+		CreateDate              string                     `json:"createDate" gorm:"column:create_date;size:50;comment:鍒涘缓鏃堕棿"`
+		AdjustAmount            decimal.Decimal            `json:"adjustAmount" gorm:"column:adjust_amount"` //宸��
+		DifferenceAmount        decimal.Decimal            `json:"differenceAmount" gorm:"-"`                //璁℃暟鏁伴噺
+		OperationId             int                        `json:"operationId" gorm:"column:operation_id;comment:搴撳瓨鎿嶄綔璁板綍"`
+		Status                  constvar.OperationStatus   `json:"status" gorm:";comment:鎿嶄綔鐘舵��(3灏辩华銆�4瀹屾垚銆�5鍙栨秷)"`                    // 鎿嶄綔鐘舵��
+		BaseOperationType       constvar.BaseOperationType `json:"baseOperationType" gorm:"base_operation_type;comment:鍩虹浣滀笟绫诲瀷"` // 鍩虹浣滀笟绫诲瀷
+		Weight                  decimal.Decimal            `gorm:"type:decimal(20,3);comment:閲嶉噺" json:"weight"`                 //閲嶉噺
 	}
 )
 
 func (slf *LocationProductAmount) TableName() string {
 	return "wms_location_product_amount"
+}
+
+func (slf *LocationProductAmount) AfterFind(tx *gorm.DB) (err error) {
+	if slf.MoreUnitValue != "" {
+		var arr []UnitItems
+		err := json.Unmarshal([]byte(slf.MoreUnitValue), &arr)
+		if err != nil {
+			return err
+		}
+		slf.MoreUnitList = arr
+	}
+
+	return
+}
+
+func (slf *LocationProductAmount) BeforeCreate(tx *gorm.DB) (err error) {
+	if len(slf.MoreUnitList) != 0 {
+		items := make([]UnitItems, 0)
+		for k, item := range slf.MoreUnitList {
+			if item.Unit != "" && !item.Amount.IsZero() {
+				items = append(items, slf.MoreUnitList[k])
+			}
+		}
+
+		str, err := json.Marshal(items)
+		if err != nil {
+			return err
+		}
+		slf.MoreUnitValue = string(str)
+	}
+	return
 }
 
 func NewLocationProductAmountSearch() *LocationProductAmountSearch {
@@ -82,6 +124,11 @@
 	return slf
 }
 
+func (slf *LocationProductAmountSearch) SetIds(ids []int) *LocationProductAmountSearch {
+	slf.Ids = ids
+	return slf
+}
+
 func (slf *LocationProductAmountSearch) SetKeyword(keyword string) *LocationProductAmountSearch {
 	slf.Keyword = keyword
 	return slf
@@ -102,13 +149,33 @@
 	return slf
 }
 
-//func (slf *LocationProductAmountSearch) SetLocationProductIds(ids []int) *LocationProductAmountSearch {
-//	slf.LocationProductIds = ids
-//	return slf
-//}
+func (slf *LocationProductAmountSearch) SetProductIds(ids []string) *LocationProductAmountSearch {
+	slf.ProductIds = ids
+	return slf
+}
 
 func (slf *LocationProductAmountSearch) SetLocationIds(ids []int) *LocationProductAmountSearch {
 	slf.LocationIds = ids
+	return slf
+}
+
+func (slf *LocationProductAmountSearch) SetQuery(query string) *LocationProductAmountSearch {
+	slf.Query = query
+	return slf
+}
+
+func (slf *LocationProductAmountSearch) SetWarehouseId(wid int) *LocationProductAmountSearch {
+	slf.WarehouseId = wid
+	return slf
+}
+
+func (slf *LocationProductAmountSearch) SetFields(fields string) *LocationProductAmountSearch {
+	slf.Fields = fields
+	return slf
+}
+
+func (slf *LocationProductAmountSearch) SetCategoryIds(ids []int) *LocationProductAmountSearch {
+	slf.CategoryIds = ids
 	return slf
 }
 
@@ -123,18 +190,24 @@
 	}
 
 	if slf.Keyword != "" {
-		db = db.Where("product_name like ?", fmt.Sprintf("%%%v%%", slf.Keyword))
+		if !slf.JoinedMaterials {
+			db = db.Joins("left join material on wms_location_product_amount.product_id = material.id")
+			slf.JoinedMaterials = true
+		}
+		db = db.Joins("left join wms_location on wms_location_product_amount.location_id = wms_location.id").
+			Joins("left join material on wms_location_product_amount.product_id = material.id").
+			Joins("left join wms_product_category on wms_location_product_amount.product_category_id = wms_product_category.id").
+			Where("wms_location.name like ?", "%"+slf.Keyword+"%").Or("material.name like ?", "%"+slf.Keyword+"%").
+			Or("wms_product_category.name like ?", "%"+slf.Keyword+"%")
 	}
 
 	if slf.Preload {
 		db = db.Model(&LocationProductAmount{}).Preload("Location").Preload("Product").Preload("ProductCategory")
 	}
-	//if slf.LocationProductId != 0 {
-	//	db = db.Where("location_product_id=?", slf.LocationProductId)
-	//}
-	//if len(slf.LocationProductIds) > 0 {
-	//	db = db.Where("location_product_id in (?)", slf.LocationProductIds)
-	//}
+
+	if len(slf.ProductIds) > 0 {
+		db = db.Where("product_id in (?)", slf.ProductIds)
+	}
 
 	if len(slf.LocationIds) > 0 {
 		db = db.Where("location_id in (?)", slf.LocationIds)
@@ -146,6 +219,30 @@
 
 	if slf.ProductId != "" {
 		db = db.Where("product_id=?", slf.ProductId)
+	}
+
+	if len(slf.Ids) > 0 {
+		db = db.Where("id in (?)", slf.Ids)
+	}
+
+	if slf.Query != "" {
+		db = db.Where(slf.Query)
+	}
+
+	if slf.WarehouseId != 0 {
+		db = db.Where("warehouse_id = ?", slf.WarehouseId)
+	}
+
+	if slf.Fields != "" {
+		db = db.Select(slf.Fields)
+	}
+
+	if len(slf.CategoryIds) > 0 {
+		if !slf.JoinedMaterials {
+			db = db.Joins("left join material on wms_location_product_amount.product_id = material.id")
+			slf.JoinedMaterials = true
+		}
+		db = db.Where("material.category_id in ?", slf.CategoryIds)
 	}
 
 	return db
@@ -227,6 +324,22 @@
 		db      = slf.build()
 	)
 
+	if slf.PageNum*slf.PageSize > 0 {
+		db = db.Offset((slf.PageNum - 1) * slf.PageSize).Limit(slf.PageSize)
+	}
+	if err := db.Find(&records).Error; err != nil {
+		return records, fmt.Errorf("find records err: %v", err)
+	}
+
+	return records, nil
+}
+
+func (slf *LocationProductAmountSearch) FindAll() ([]*LocationProductAmount, error) {
+	var (
+		records = make([]*LocationProductAmount, 0)
+		db      = slf.build()
+	)
+
 	if err := db.Find(&records).Error; err != nil {
 		return records, fmt.Errorf("find records err: %v", err)
 	}
@@ -242,3 +355,56 @@
 
 	return record, db.First(&record)
 }
+
+func (slf *LocationProductAmountSearch) Count() (int64, error) {
+	var (
+		total int64
+		db    = slf.build()
+	)
+	err := db.Count(&total).Error
+	return total, err
+}
+
+func (slf *LocationProductAmountSearch) UpdateByMap(upMap map[string]interface{}) error {
+	var (
+		db = slf.build()
+	)
+
+	if err := db.Updates(upMap).Error; err != nil {
+		return fmt.Errorf("update by map err: %v, upMap: %+v", err, upMap)
+	}
+
+	return nil
+}
+
+func (slf *LocationProductAmountSearch) GroupCount(field string) ([]*GroupCount, error) {
+	var (
+		db     = slf.build()
+		result = make([]*GroupCount, 0)
+	)
+	if err := db.Select("count(*) as total, " + field + " as class").Group(field).Scan(&result).Error; err != nil {
+		return nil, fmt.Errorf("select group err: %v", err)
+	}
+	return result, nil
+}
+
+func (slf *LocationProductAmountSearch) GroupSum(groupField string, sumField string) ([]*GroupSum, error) {
+	var (
+		db     = slf.build()
+		result = make([]*GroupSum, 0)
+	)
+	if err := db.Select("sum(" + sumField + ") as sum, " + groupField + " as class").Group(groupField).Scan(&result).Error; err != nil {
+		return nil, fmt.Errorf("select group err: %v", err)
+	}
+	return result, nil
+}
+
+func (slf *LocationProductAmountSearch) Save(record *LocationProductAmount) error {
+	var db = slf.build()
+
+	if err := db.Omit("CreatedAt").Save(record).Error; err != nil {
+		return fmt.Errorf("save err: %v, record: %+v", err, record)
+	}
+
+	return nil
+}

--
Gitblit v1.8.0