diff --git a/app/admin/models/purchase.go b/app/admin/models/purchase.go index 712bc8a..1a5bfc9 100644 --- a/app/admin/models/purchase.go +++ b/app/admin/models/purchase.go @@ -1832,594 +1832,6 @@ func FinishErpPurchaseDemand(req *FinishErpPurchaseDemandReq, sysUser *SysUser) return nil } -//// GetErpPurchaseDemand 获取采购需求 -//func GetErpPurchaseDemand(req *GetErpPurchaseDemandReq) (*GetErpPurchaseDemandResp, error) { -// resp := &GetErpPurchaseDemandResp{ -// PageIndex: req.PageIndex, -// PageSize: req.PageSize, -// } -// page := req.PageIndex - 1 -// if page < 0 { -// page = 0 -// } -// if req.PageSize == 0 { -// req.PageSize = 10 -// } -// -// qs := orm.Eloquent.Debug().Table("erp_commodity") -// if req.ErpCategoryId != 0 { -// qs = qs.Where("erp_category_id=?", req.ErpCategoryId) -// } -// -// var commodities []ErpCommodity -// err := qs.Order("id DESC").Offset(page * req.PageSize).Limit(req.PageSize).Find(&commodities).Error -// if err != nil && err != RecordNotFound { -// //logger.Error("erp commodity list err:", err) -// return resp, err -// } -// -// // 组合数据 -// resp, err = convertToDemandResp(commodities) -// -// return resp, nil -//} -// -//func convertToDemandResp(commodities []ErpCommodity) (*GetErpPurchaseDemandResp, error) { -// resp := new(GetErpPurchaseDemandResp) -// var demandData DemandData -// var demandList []DemandData -// -// // 查询所有在线门店信息 -// var stores []Store -// err := orm.Eloquent.Table("store").Where("is_online = ?", 1).Find(&stores).Error -// if err != nil { -// logger.Error("stores err:", logger.Field("err", err)) -// return nil, err -// } -// -// demandData.List = make([]struct { -// StoreID uint32 `json:"store_id"` -// StoreName string `json:"store_name"` -// LastMonthSales uint32 `json:"last_month_sales"` -// StockCount uint32 `json:"stock_count"` -// NeedCount uint32 `json:"need_count"` -// }, len(stores)) -// -// var totalCount uint32 // 总需采购数量 -// -// // 遍历所有商品 -// for _, v := range commodities { -// // 初始化 NeedCount 为 0 -// var totalNeedCount uint32 -// -// for i, store := range stores { -// demandData.List[i].StoreID = store.ID -// demandData.List[i].StoreName = store.Name -// -// // 初始化 NeedCount 为 0 -// demandData.List[i].NeedCount = 0 -// -// // 设置商品相关信息 -// demandData.ErpCommodityID = v.ID -// demandData.ErpCommoditySerialNumber = v.SerialNumber -// demandData.ErpCommodityName = v.Name -// demandData.ErpCategoryID = v.ErpCategoryId -// demandData.ErpCategoryName = v.ErpCategoryName -// demandData.RetailPrice = v.RetailPrice -// // 最近采购价 -// demandData.LastWholesalePrice, _ = GetCommodityLastWholesalePrice(v.ID) -// -// // 查询采购需求单 -// var demand []ErpPurchaseDemand -// err = orm.Eloquent.Table("erp_purchase_demand").Where("erp_commodity_id = ? AND state = 1 AND store_id = ?", -// v.ID, store.ID).Find(&demand).Error -// if err != nil { -// logger.Error("query erp_purchase_demand err:", logger.Field("err", err)) -// return nil, err -// } -// -// if len(demand) > 0 { -// totalNeedCount += demand[0].Total -// demandData.List[i].NeedCount = demand[0].Total -// } -// -// // 查询某个门店某个商品的库存情况 -// demandData.List[i].StockCount, _ = GetCommodityStockByStoreId(v.ID, store.ID) -// // 查询某个门店某件商品的上月销售数量 -// demandData.List[i].LastMonthSales, _ = GetCommodityLastMonthSalesByStoreId(v.ID, store.ID) -// } -// totalCount += totalNeedCount -// demandData.TotalCount = totalCount -// demandData.TotalAmount = float64(totalCount) * demandData.LastWholesalePrice -// demandList = append(demandList, demandData) -// } -// resp.List = demandList -// -// return resp, nil -//} -// -//// GetCommodityStockByStoreId 查询某个门店某个商品的库存情况 -//func GetCommodityStockByStoreId(commodityId, storeId uint32) (uint32, error) { -// var count int64 -// err := orm.Eloquent.Table("erp_stock_commodity").Where("erp_commodity_id = ? and store_id = ? and state = 1", -// commodityId, storeId).Total(&count).Error -// if err != nil { -// logger.Error("GetCommodityStockByStoreId count err:", logger.Field("err", err)) -// return 0, err -// } -// -// return uint32(count), nil -//} -// -//// GetCommodityLastMonthSalesByStoreId 查询某个门店某件商品的上月销售数量 -//func GetCommodityLastMonthSalesByStoreId(commodityId, storeId uint32) (uint32, error) { -// var lastMonthSales uint32 -// -// // 获取当前时间 -// now := time.Now() -// year, month, _ := now.Date() -// firstDay := time.Date(year, month-1, 1, 0, 0, 0, 0, now.Location()) -// lastDay := firstDay.AddDate(0, 1, -1) -// -// // 执行查询 -// err := orm.Eloquent.Model(&ErpOrderCommodity{}). -// Joins("JOIN erp_order ON erp_order_commodity.erp_order_id = erp_order.id"). -// Select("SUM(erp_order_commodity.count) AS last_month_sales"). -// Where("erp_order.pay_status = ? AND erp_order_commodity.erp_commodity_id = ? AND erp_order.store_id = ? "+ -// "AND erp_order_commodity.created_at BETWEEN ? AND ?", -// HavePaid, commodityId, storeId, firstDay, lastDay). -// Scan(&lastMonthSales).Error -// if err != nil { -// logger.Error("GetCommodityLastMonthSalesByStoreId err:", logger.Field("err", err)) -// return 0, err -// } -// -// return lastMonthSales, nil -//} -// -//// GetCommodityLastWholesalePrice 查询某个商品的最近采购价 -//func GetCommodityLastWholesalePrice(commodityId uint32) (float64, error) { -// var implementationPrice float64 -// -// // 执行查询 -// err := orm.Eloquent.Table("erp_purchase_inventory"). -// Select("implementation_price"). -// Where("erp_commodity_id = ? AND purchase_type = ?", 167, "procure"). -// Order("created_at DESC"). -// Limit(1). -// Scan(&implementationPrice).Error -// if err != nil { -// logger.Error("GetCommodityLastMonthSalesByStoreId err:", logger.Field("err", err)) -// return 0, err -// } -// -// return implementationPrice, nil -//} - -// 222222222 -//// GetErpPurchaseDemand 获取采购需求 -//func GetErpPurchaseDemand(req *GetErpPurchaseDemandReq) (*GetErpPurchaseDemandResp, error) { -// resp := &GetErpPurchaseDemandResp{ -// PageIndex: req.PageIndex, -// PageSize: req.PageSize, -// } -// page := req.PageIndex - 1 -// if page < 0 { -// page = 0 -// } -// if req.PageSize == 0 { -// req.PageSize = 10 -// } -// -// qs := orm.Eloquent.Debug().Table("erp_commodity") -// if req.ErpCategoryId != 0 { -// qs = qs.Where("erp_category_id=?", req.ErpCategoryId) -// } -// -// var commodities []ErpCommodity -// err := qs.Order("id DESC").Offset(page * req.PageSize).Limit(req.PageSize).Find(&commodities).Error -// if err != nil && err != RecordNotFound { -// return resp, err -// } -// -// // 批量查询门店信息 -// stores, err := GetOnlineStores() -// if err != nil { -// return nil, err -// } -// -// // 批量查询商品信息 -// demandDataList := make([]DemandData, 0, len(commodities)) -// for _, v := range commodities { -// demandData, err := convertToDemandData(v, stores) -// if err != nil { -// return nil, err -// } -// demandDataList = append(demandDataList, demandData) -// } -// -// resp.List = demandDataList -// -// return resp, nil -//} -// -//// convertToDemandData 将商品转换为采购需求数据 -//func convertToDemandData(commodity ErpCommodity, stores []Store) (DemandData, error) { -// demandData := DemandData{ -// ErpCommodityID: commodity.ID, -// ErpCommoditySerialNumber: commodity.SerialNumber, -// ErpCommodityName: commodity.Name, -// ErpCategoryID: commodity.ErpCategoryId, -// ErpCategoryName: commodity.ErpCategoryName, -// RetailPrice: commodity.RetailPrice, -// } -// -// // 批量查询最近采购价 -// lastWholesalePrices, err := GetCommodityLastWholesalePrices(commodity.ID) -// if err != nil { -// return DemandData{}, err -// } -// -// for i, store := range stores { -// demandData.List = append(demandData.List, struct { -// StoreID uint32 `json:"store_id"` -// StoreName string `json:"store_name"` -// LastMonthSales uint32 `json:"last_month_sales"` -// StockCount uint32 `json:"stock_count"` -// NeedCount uint32 `json:"need_count"` -// }{ -// StoreID: store.ID, -// StoreName: store.Name, -// }) -// -// // 批量查询库存情况 -// stockCounts, err := GetCommodityStocksByStoreID(commodity.ID, store.ID) -// if err != nil { -// return DemandData{}, err -// } -// demandData.List[i].StockCount = stockCounts[store.ID] -// -// // 批量查询上月销售数量 -// lastMonthSales, err := GetCommodityLastMonthSales(commodity.ID, store.ID) -// if err != nil { -// return DemandData{}, err -// } -// demandData.List[i].LastMonthSales = lastMonthSales -// -// // 设置最近采购价 -// demandData.LastWholesalePrice = lastWholesalePrices[commodity.ID] -// } -// -// return demandData, nil -//} -// -//// GetCommodityLastWholesalePrices 批量查询商品的最近采购价 -//func GetCommodityLastWholesalePrices(commodityID uint32) (map[uint32]float64, error) { -// // 查询最近采购价 -// var prices []struct { -// CommodityID uint32 -// Price float64 -// } -// err := orm.Eloquent.Table("erp_purchase_inventory"). -// Select("erp_commodity_id, implementation_price AS price"). -// Where("erp_commodity_id IN (?) AND purchase_type = ?", commodityID, "procure"). -// Group("erp_commodity_id"). -// Order("created_at DESC"). -// Find(&prices).Error -// if err != nil { -// return nil, err -// } -// -// // 构建结果 -// result := make(map[uint32]float64) -// for _, p := range prices { -// result[p.CommodityID] = p.Price -// } -// return result, nil -//} -// -//// GetCommodityStocksByStoreID 批量查询商品的库存情况 -//func GetCommodityStocksByStoreID(commodityID, storeID uint32) (map[uint32]uint32, error) { -// // 查询库存情况 -// var stocks []struct { -// StoreID uint32 -// CommodityID uint32 -// StockCount uint32 -// } -// err := orm.Eloquent.Table("erp_stock_commodity"). -// Select("store_id, erp_commodity_id, COUNT(*) AS stock_count"). -// Where("erp_commodity_id IN (?) AND store_id = ? AND state = 1", commodityID, storeID). -// Group("store_id, erp_commodity_id"). -// Find(&stocks).Error -// if err != nil { -// return nil, err -// } -// -// // 构建结果 -// result := make(map[uint32]uint32) -// for _, s := range stocks { -// result[s.StoreID] = s.StockCount -// } -// return result, nil -//} -// -//// GetCommodityLastMonthSales 批量查询商品的上月销售数量 -//func GetCommodityLastMonthSales(commodityID, storeID uint32) (uint32, error) { -// // 获取上个月的时间范围 -// firstDay, lastDay := GetLastMonthRange() -// -// // 查询上月销售数量 -// var lastMonthSales struct { -// Sales uint32 -// } -// err := orm.Eloquent.Table("erp_order_commodity"). -// Joins("JOIN erp_order ON erp_order_commodity.erp_order_id = erp_order.id"). -// Where("erp_order.pay_status = ? AND erp_order_commodity.erp_commodity_id = ? AND erp_order.store_id = ? "+ -// "AND erp_order_commodity.created_at BETWEEN ? AND ?", -// HavePaid, commodityID, storeID, firstDay, lastDay). -// Select("SUM(erp_order_commodity.count) AS sales"). -// Scan(&lastMonthSales).Error -// if err != nil { -// return 0, err -// } -// -// return lastMonthSales.Sales, nil -//} -// -//// GetLastMonthRange 获取上个月的时间范围 -//func GetLastMonthRange() (time.Time, time.Time) { -// now := time.Now() -// year, month, _ := now.Date() -// firstDay := time.Date(year, month-1, 1, 0, 0, 0, 0, now.Location()) -// lastDay := firstDay.AddDate(0, 1, -1) -// return firstDay, lastDay -//} -// -//// GetOnlineStores 查询所有在线门店信息 -//func GetOnlineStores() ([]Store, error) { -// var stores []Store -// err := orm.Eloquent.Table("store").Where("is_online = ?", 1).Find(&stores).Error -// if err != nil { -// return nil, err -// } -// return stores, nil -//} - -// 3333 -//// GetErpPurchaseDemand 获取采购需求 -//func GetErpPurchaseDemand(req *GetErpPurchaseDemandReq) (*GetErpPurchaseDemandResp, error) { -// resp := &GetErpPurchaseDemandResp{ -// PageIndex: req.PageIndex, -// PageSize: req.PageSize, -// } -// page := req.PageIndex - 1 -// if page < 0 { -// page = 0 -// } -// if req.PageSize == 0 { -// req.PageSize = 10 -// } -// -// qs := orm.Eloquent.Debug().Table("erp_commodity") -// if req.ErpCategoryId != 0 { -// qs = qs.Where("erp_category_id=?", req.ErpCategoryId) -// } -// -// var commodities []ErpCommodity -// err := qs.Order("id DESC").Offset(page * req.PageSize).Limit(req.PageSize).Find(&commodities).Error -// if err != nil && err != RecordNotFound { -// return resp, err -// } -// -// // 批量查询门店信息 -// stores, err := GetOnlineStores() -// if err != nil { -// return nil, err -// } -// -// // 并行查询需求数据 -// var wg sync.WaitGroup -// demandDataList := make([]DemandData, len(commodities)) -// -// for i, v := range commodities { -// wg.Add(1) -// go func(index int, commodity ErpCommodity) { -// defer wg.Done() -// demandData, err := convertToDemandData(commodity, stores) -// if err != nil { -// // Handle error -// return -// } -// demandDataList[index] = demandData -// }(i, v) -// } -// -// wg.Wait() -// -// resp.List = demandDataList -// -// return resp, nil -//} -// -//// convertToDemandData 将商品转换为采购需求数据 -//func convertToDemandData(commodity ErpCommodity, stores []Store) (DemandData, error) { -// demandData := DemandData{ -// ErpCommodityID: commodity.ID, -// ErpCommoditySerialNumber: commodity.SerialNumber, -// ErpCommodityName: commodity.Name, -// ErpCategoryID: commodity.ErpCategoryId, -// ErpCategoryName: commodity.ErpCategoryName, -// RetailPrice: commodity.RetailPrice, -// } -// -// // 并行查询最近采购价、库存情况、上月销售数量 -// var wg sync.WaitGroup -// wg.Add(3) -// -// var lastWholesalePrices map[uint32]float64 -// var stockCounts map[uint32]uint32 -// var lastMonthSales uint32 -// var err1, err2, err3 error -// -// go func() { -// defer wg.Done() -// lastWholesalePrices, err1 = GetCommodityLastWholesalePrices(commodity.ID) -// }() -// -// go func() { -// defer wg.Done() -// stockCounts, err2 = GetCommodityStocksByStoreID(commodity.ID, stores) -// }() -// -// go func() { -// defer wg.Done() -// lastMonthSales, err3 = GetCommodityLastMonthSales(commodity.ID, stores) -// }() -// -// wg.Wait() -// -// if err1 != nil || err2 != nil || err3 != nil { -// // Handle error -// return DemandData{}, err1 -// } -// -// // 构建需求数据 -// demandData.List = make([]struct { -// StoreID uint32 `json:"store_id"` -// StoreName string `json:"store_name"` -// LastMonthSales uint32 `json:"last_month_sales"` -// StockCount uint32 `json:"stock_count"` -// NeedCount uint32 `json:"need_count"` -// }, len(stores)) -// -// for i, store := range stores { -// demandData.List[i].StoreID = store.ID -// demandData.List[i].StoreName = store.Name -// -// demandData.List[i].StockCount = stockCounts[store.ID] -// demandData.List[i].LastMonthSales = lastMonthSales -// -// // 设置最近采购价 -// demandData.LastWholesalePrice = lastWholesalePrices[commodity.ID] -// } -// -// return demandData, nil -//} -// -//// GetCommodityLastWholesalePrices 批量查询商品的最近采购价 -//func GetCommodityLastWholesalePrices(commodityID uint32) (map[uint32]float64, error) { -// // 查询最近采购价 -// var prices []struct { -// CommodityID uint32 -// Price float64 -// } -// err := orm.Eloquent.Table("erp_purchase_inventory"). -// Select("erp_commodity_id, implementation_price AS price"). -// Where("erp_commodity_id IN (?) AND purchase_type = ?", commodityID, "procure"). -// Group("erp_commodity_id"). -// Order("created_at DESC"). -// Find(&prices).Error -// if err != nil { -// return nil, err -// } -// -// // 构建结果 -// result := make(map[uint32]float64) -// for _, p := range prices { -// result[p.CommodityID] = p.Price -// } -// return result, nil -//} -// -//// GetCommodityStocksByStoreID 批量查询商品的库存情况 -//func GetCommodityStocksByStoreID(commodityID uint32, stores []Store) (map[uint32]uint32, error) { -// // 并行查询库存情况 -// var wg sync.WaitGroup -// wg.Add(len(stores)) -// -// result := make(map[uint32]uint32) -// -// for _, store := range stores { -// go func(storeID uint32) { -// defer wg.Done() -// // 查询库存情况 -// var stockCount int64 -// err := orm.Eloquent.Table("erp_stock_commodity"). -// Where("erp_commodity_id = ? AND store_id = ? AND state = 1", commodityID, storeID). -// Total(&stockCount).Error -// if err != nil { -// // Handle error -// return -// } -// result[storeID] = uint32(stockCount) -// }(store.ID) -// } -// -// wg.Wait() -// -// return result, nil -//} -// -//// GetCommodityLastMonthSales 批量查询商品的上月销售数量 -//func GetCommodityLastMonthSales(commodityID uint32, stores []Store) (uint32, error) { -// // 获取上个月的时间范围 -// firstDay, lastDay := GetLastMonthRange() -// -// // 并行查询上月销售数量 -// var wg sync.WaitGroup -// wg.Add(len(stores)) -// -// var totalSales uint32 -// var mu sync.Mutex // 用于保护 totalSales 的并发访问 -// -// for _, store := range stores { -// go func(storeID uint32) { -// defer wg.Done() -// // 查询上月销售数量 -// var sales uint32 -// err := orm.Eloquent.Table("erp_order_commodity"). -// Joins("JOIN erp_order ON erp_order_commodity.erp_order_id = erp_order.id"). -// Where("erp_order.pay_status = ? AND erp_order_commodity.erp_commodity_id = ? AND erp_order.store_id = ? "+ -// "AND erp_order_commodity.created_at BETWEEN ? AND ?", -// HavePaid, commodityID, storeID, firstDay, lastDay). -// Select("SUM(erp_order_commodity.count) AS sales"). -// Scan(&sales).Error -// if err != nil { -// // Handle error -// return -// } -// -// // 累加销售数量 -// mu.Lock() -// totalSales += sales -// mu.Unlock() -// }(store.ID) -// } -// -// wg.Wait() -// -// return totalSales, nil -//} -// -//// GetLastMonthRange 获取上个月的时间范围 -//func GetLastMonthRange() (time.Time, time.Time) { -// now := time.Now() -// year, month, _ := now.Date() -// firstDay := time.Date(year, month-1, 1, 0, 0, 0, 0, now.Location()) -// lastDay := firstDay.AddDate(0, 1, -1) -// return firstDay, lastDay -//} -// -//// GetOnlineStores 查询所有在线门店信息 -//func GetOnlineStores() ([]Store, error) { -// var stores []Store -// err := orm.Eloquent.Table("store").Where("is_online = ?", 1).Find(&stores).Error -// if err != nil { -// return nil, err -// } -// return stores, nil -//} - // GetErpPurchaseDemand 获取采购需求 func GetErpPurchaseDemand(req *GetErpPurchaseDemandReq, c *gin.Context) (*GetErpPurchaseDemandResp, error) { var err error @@ -2445,12 +1857,20 @@ func getErpPurchaseDemandAll(req *GetErpPurchaseDemandReq, c *gin.Context) (*Get if req.PageSize == 0 { req.PageSize = 10 } - resp := &GetErpPurchaseDemandResp{ PageIndex: page + 1, PageSize: req.PageSize, } + // 批量查询门店信息 + stores, err := GetOnlineStores(c) + if err != nil { + return nil, err + } + if len(stores) == 0 { + return nil, errors.New("无有效门店,请配置门店信息") + } + qs := orm.Eloquent.Debug().Table("erp_commodity") if req.ErpCategoryId != 0 { categoryInfo, err := GetErpCategory(req.ErpCategoryId) @@ -2476,7 +1896,7 @@ func getErpPurchaseDemandAll(req *GetErpPurchaseDemandReq, c *gin.Context) (*Get } var commodities []ErpCommodity - err := qs.Order("id DESC").Find(&commodities).Error + err = qs.Order("id DESC").Find(&commodities).Error if err != nil && err != RecordNotFound { return resp, err } @@ -2494,7 +1914,6 @@ func getErpPurchaseDemandAll(req *GetErpPurchaseDemandReq, c *gin.Context) (*Get // 商品编号排序 SortCommoditiesAsc(commodities) } - if req.CallType != 2 { if req.SortField == "erp_supplier_id" { switch req.SortType { @@ -2514,15 +1933,114 @@ func getErpPurchaseDemandAll(req *GetErpPurchaseDemandReq, c *gin.Context) (*Get } } - // 批量查询门店信息 - stores, err := GetOnlineStores(c) + // 批量查询商品上月销售数量 + var soldOutCommodities []ErpStockCommodity + firstDay, lastDay := GetLastMonthRange() // 获取上个月的时间范围 + // 组合门店信息 + var storeIdList []uint32 + for _, item := range stores { + storeIdList = append(storeIdList, item.ID) + } + if len(storeIdList) > 1 { + err = orm.Eloquent.Table("erp_stock_commodity"). + Where("state = ? AND updated_at BETWEEN ? AND ? AND store_id in (?)", + SoldOut, firstDay, lastDay, storeIdList).Find(&soldOutCommodities).Error + } else { + err = orm.Eloquent.Table("erp_stock_commodity"). + Where("state = ? AND updated_at BETWEEN ? AND ? AND store_id = ?", + SoldOut, firstDay, lastDay, storeIdList[0]).Find(&soldOutCommodities).Error + } + if err != nil { + return nil, err + } + // 按照 商品id-门店id:销售数量 组合信息 + soldOutMap := make(map[string]uint32) + for _, item := range soldOutCommodities { + key := fmt.Sprintf("%d-%d", item.ErpCommodityId, item.StoreId) + _, exist := soldOutMap[key] + if exist { // 存在 + soldOutMap[key] += 1 + } else { // 不存在 + soldOutMap[key] = 1 + } + } + + // 批量查询商品的库存情况 + var stockCommodities []ErpStockCommodity + if len(storeIdList) > 1 { + err = orm.Eloquent.Table("erp_stock_commodity"). + Where("state = ? AND store_id in (?)", + InStock, storeIdList).Find(&stockCommodities).Error + } else { + err = orm.Eloquent.Table("erp_stock_commodity"). + Where("state = ? AND store_id = ?", + InStock, storeIdList[0]).Find(&stockCommodities).Error + } + if err != nil { + return nil, err + } + // 按照 商品id-门店id:库存数量 组合信息 + inStockMap := make(map[string]uint32) + for _, item := range stockCommodities { + key := fmt.Sprintf("%d-%d", item.ErpCommodityId, item.StoreId) + _, exist := inStockMap[key] + if exist { // 存在 + inStockMap[key] += 1 + } else { // 不存在 + inStockMap[key] = 0 + } + } + + // 查询采购需求单信息 + var demand []ErpPurchaseDemand + demandQs := orm.Eloquent.Table("erp_purchase_demand"). + Where("state = 1").Where("count <> 0") + if len(storeIdList) > 0 { + if len(storeIdList) == 1 { + demandQs = demandQs.Where("store_id = ?", storeIdList[0]) + } else { + demandQs = demandQs.Where("store_id IN (?)", storeIdList) + } + } + err = demandQs.Find(&demand).Error if err != nil { return nil, err } + // 查询采购备注信息 + var demandRemarkInfo []ErpPurchaseDemandRemark + demandRemarkQs := orm.Eloquent.Table("erp_purchase_demand_remark"). + Where("state = 1"). + Where("remark IS NOT NULL"). + Where("remark <> ''") + err = demandRemarkQs.Find(&demandRemarkInfo).Error + if err != nil { + return nil, err + } + + // 按照 商品ID-门店ID:采购信息 组合 + demandsMap := make(map[string]ErpPurchaseDemand) + storesMap := make(map[uint32][]uint32) // 按照 商品id:门店id列表 组合 + demandRemarksMap := make(map[uint32]ErpPurchaseDemandRemark) // 按照 商品id:采购备注信息 组合 + + for _, d := range demand { + key := fmt.Sprintf("%d-%d", d.ErpCommodityId, d.StoreId) + demandsMap[key] = d + + // 更新 storesMap + if _, exists := storesMap[d.ErpCommodityId]; !exists { + storesMap[d.ErpCommodityId] = []uint32{d.StoreId} + } else { + storesMap[d.ErpCommodityId] = append(storesMap[d.ErpCommodityId], d.StoreId) + } + } + + for _, r := range demandRemarkInfo { + demandRemarksMap[r.ErpCommodityId] = r + } + // 并行查询需求数据 var wg sync.WaitGroup - var tempCommodities []ErpCommodity if req.IsExport == 1 { tempCommodities = commodities @@ -2541,7 +2059,8 @@ func getErpPurchaseDemandAll(req *GetErpPurchaseDemandReq, c *gin.Context) (*Get wg.Add(1) go func(index int, commodity ErpCommodity) { defer wg.Done() - demandData, err := convertToDemandDataAll(commodity, stores) + demandData, err := convertToDemandDataAll(commodity, storesMap[commodity.ID], stores, soldOutMap, inStockMap, + demandsMap, demandRemarksMap) if err != nil { // Handle error return @@ -2549,7 +2068,6 @@ func getErpPurchaseDemandAll(req *GetErpPurchaseDemandReq, c *gin.Context) (*Get demandDataList[index] = demandData }(i, v) } - wg.Wait() if req.IsExport == 1 { // 导出excel @@ -2565,14 +2083,6 @@ func getErpPurchaseDemandAll(req *GetErpPurchaseDemandReq, c *gin.Context) (*Get return nil, err } } else { - //// 计算分页所需的切片索引 - //startIndex := page * req.PageSize - //endIndex := (page + 1) * req.PageSize - //if endIndex > len(demandDataList) { - // endIndex = len(demandDataList) - //} - //resp.List = demandDataList[startIndex:endIndex] - resp.List = demandDataList resp.Total = count } @@ -2581,16 +2091,8 @@ func getErpPurchaseDemandAll(req *GetErpPurchaseDemandReq, c *gin.Context) (*Get } // convertToDemandDataAll 将商品转换为采购需求数据 -func convertToDemandDataAll(commodity ErpCommodity, stores []Store) (DemandData, error) { - // 查询采购商品的备注信息 - var demandRemarkInfo ErpPurchaseDemandRemark - err := orm.Eloquent.Table("erp_purchase_demand_remark").Where("erp_commodity_id = ? and state = 1", - commodity.ID).Find(&demandRemarkInfo).Error - if err != nil { - logger.Error("query erp_purchase_demand_remark err:", logger.Field("err", err)) - return DemandData{}, err - } - +func convertToDemandDataAll(commodity ErpCommodity, usedStore []uint32, stores []Store, soldOutMap, stockMap map[string]uint32, + demandMap map[string]ErpPurchaseDemand, demandRemarkMap map[uint32]ErpPurchaseDemandRemark) (DemandData, error) { demandData := DemandData{ ErpSupplierId: commodity.ErpSupplierId, ErpSupplierName: commodity.ErpSupplierName, @@ -2600,47 +2102,23 @@ func convertToDemandDataAll(commodity ErpCommodity, stores []Store) (DemandData, ErpCategoryID: commodity.ErpCategoryId, ErpCategoryName: commodity.ErpCategoryName, RetailPrice: commodity.RetailPrice, - Remark: demandRemarkInfo.Remark, + Remark: demandRemarkMap[commodity.ID].Remark, } - // 查询采购需求单 - demands, err := GetCommodityPurchaseDemands(commodity.ID, stores) - if err != nil { - // Handle error - return DemandData{}, err + var demands []ErpPurchaseDemand + for _, store := range usedStore { + key := fmt.Sprintf("%d-%d", commodity.ID, store) + v, ok := demandMap[key] + if !ok { + continue + } + + demands = append(demands, v) } - //if len(demands) != 0 { - // demandData.Remark = demands[0].Remark - //} - - //使用 WaitGroup 进行并行查询 - var wg sync.WaitGroup - wg.Add(3) + // 查询最近采购价 var lastWholesalePrices map[uint32]float64 - var stockCounts map[uint32]uint32 - var lastMonthSales map[uint32]uint32 - - go func() { - defer wg.Done() - lastWholesalePrices, err = GetCommodityLastWholesalePrices(commodity.ID) - }() - - go func() { - defer wg.Done() - stockCounts, err = GetCommodityStocksByStoreIDAll(commodity.ID, stores) - }() - - go func() { - defer wg.Done() - lastMonthSales, err = GetCommodityLastMonthSalesAll(commodity.ID, stores) - }() - - wg.Wait() - if err != nil { - // Handle error - //return DemandData{}, err 备注:有时会提示没记录,不做处理 - } + lastWholesalePrices, _ = GetCommodityLastWholesalePrices(commodity.ID) var totalCount uint32 // 总需采购数量 // 构建需求数据 @@ -2656,8 +2134,9 @@ func convertToDemandDataAll(commodity ErpCommodity, stores []Store) (DemandData, demandData.StoreList[i].StoreID = store.ID demandData.StoreList[i].StoreName = store.Name - demandData.StoreList[i].StockCount = stockCounts[store.ID] - demandData.StoreList[i].LastMonthSales = lastMonthSales[store.ID] + key := fmt.Sprintf("%d-%d", commodity.ID, store.ID) + demandData.StoreList[i].StockCount = stockMap[key] + demandData.StoreList[i].LastMonthSales = soldOutMap[key] // 设置最近采购价 demandData.LastWholesalePrice = lastWholesalePrices[commodity.ID] @@ -2693,43 +2172,42 @@ func getErpPurchaseDemandHide(req *GetErpPurchaseDemandReq, c *gin.Context) (*Ge PageSize: req.PageSize, } - // 查询采购需求单信息,筛选出有采购需求的商品id - var demand []ErpPurchaseDemand - var demandRemarkInfo []ErpPurchaseDemandRemark - demandQs := orm.Eloquent.Table("erp_purchase_demand"). - Where("state = 1").Where("count <> 0") - demandRemarkQs := orm.Eloquent.Table("erp_purchase_demand_remark"). - Where("state = 1"). - Where("remark IS NOT NULL"). - Where("remark <> ''") - - // 非管理员才判断所属门店 - if !(tools.GetRoleName(c) == "admin" || tools.GetRoleName(c) == "系统管理员") { - sysUser, err := GetSysUserByCtx(c) - if err != nil { - return nil, errors.New("操作失败:" + err.Error()) - } - - // 返回sysUser未过期的门店id列表 - storeList := GetValidStoreIDs(sysUser.StoreData) - if len(storeList) > 0 { - if len(storeList) == 1 { - demandQs = demandQs.Where("store_id = ?", storeList[0]) - demandRemarkQs = demandRemarkQs.Where("store_id = ?", storeList[0]) - } else { - demandQs = demandQs.Where("store_id IN (?)", storeList) - demandRemarkQs = demandRemarkQs.Where("store_id IN (?)", storeList) - } - } else { - return nil, errors.New("用户未绑定门店") - } + // 批量查询门店信息 + stores, err := GetOnlineStores(c) + if err != nil { + return nil, err + } + if len(stores) == 0 { + return nil, errors.New("无有效门店,请配置门店信息") + } + // 组合门店信息 + var storeIdList []uint32 + for _, item := range stores { + storeIdList = append(storeIdList, item.ID) } - err := demandQs.Find(&demand).Error + // 查询采购需求单信息,筛选出有采购需求的商品id + var demand []ErpPurchaseDemand + demandQs := orm.Eloquent.Table("erp_purchase_demand"). + Where("state = 1").Where("count <> 0") + if len(storeIdList) > 0 { + if len(storeIdList) == 1 { + demandQs = demandQs.Where("store_id = ?", storeIdList[0]) + } else { + demandQs = demandQs.Where("store_id IN (?)", storeIdList) + } + } + err = demandQs.Find(&demand).Error if err != nil { return nil, err } + // 查询采购需求备注信息 + var demandRemarkInfo []ErpPurchaseDemandRemark + demandRemarkQs := orm.Eloquent.Table("erp_purchase_demand_remark"). + Where("state = 1"). + Where("remark IS NOT NULL"). + Where("remark <> ''") err = demandRemarkQs.Find(&demandRemarkInfo).Error if err != nil { return nil, err @@ -2839,12 +2317,6 @@ func getErpPurchaseDemandHide(req *GetErpPurchaseDemandReq, c *gin.Context) (*Ge } } - // 批量查询门店信息 - stores, err := GetOnlineStores(c) - if err != nil { - return nil, err - } - // 并行查询需求数据 var wg sync.WaitGroup var tempCommodities []ErpCommodity @@ -2898,7 +2370,8 @@ func getErpPurchaseDemandHide(req *GetErpPurchaseDemandReq, c *gin.Context) (*Ge } // convertToDemandData 将商品转换为采购需求数据 -func convertToDemandData(commodity ErpCommodity, usedStore []uint32, stores []Store, demandRemarksMap map[uint32]ErpPurchaseDemandRemark, demandMap map[string]ErpPurchaseDemand) (DemandData, error) { +func convertToDemandData(commodity ErpCommodity, usedStore []uint32, stores []Store, + demandRemarksMap map[uint32]ErpPurchaseDemandRemark, demandMap map[string]ErpPurchaseDemand) (DemandData, error) { demandData := DemandData{ ErpSupplierId: commodity.ErpSupplierId, ErpSupplierName: commodity.ErpSupplierName, @@ -2970,24 +2443,6 @@ func GetCommodityPurchaseDemands(commodityID uint32, stores []Store) ([]ErpPurch var demands []ErpPurchaseDemand wg.Add(len(stores)) - //for _, store := range stores { - // go func(storeID uint32) { - // defer wg.Done() - // var demand ErpPurchaseDemand - // err := orm.Eloquent.Table("erp_purchase_demand"). - // Where("erp_commodity_id = ? AND state = 1 AND store_id = ?", commodityID, storeID). - // First(&demand).Error - // if err != nil { - // // Handle error - // return - // } - // - // mu.Lock() - // defer mu.Unlock() - // demands = append(demands, demand) - // }(store.ID) - //} - for _, store := range stores { go func(storeID uint32) { defer wg.Done() @@ -3118,72 +2573,6 @@ func GetCommodityLastMonthSales(commodityID uint32, stores []uint32) (map[uint32 return result, nil } -// GetCommodityStocksByStoreIDAll 批量查询商品的库存情况 -func GetCommodityStocksByStoreIDAll(commodityID uint32, stores []Store) (map[uint32]uint32, error) { - // 并行查询库存情况 - var wg sync.WaitGroup - wg.Add(len(stores)) - - result := make(map[uint32]uint32) - - for _, store := range stores { - go func(storeID uint32) { - defer wg.Done() - // 查询库存情况 - var stockCount int64 - err := orm.Eloquent.Table("erp_stock_commodity"). - Where("erp_commodity_id = ? AND store_id = ? AND state = 1", commodityID, storeID). - Count(&stockCount).Error - if err != nil { - // Handle error - return - } - result[storeID] = uint32(stockCount) - }(store.ID) - } - - wg.Wait() - - return result, nil -} - -// GetCommodityLastMonthSalesAll 批量查询商品的上月销售数量 -func GetCommodityLastMonthSalesAll(commodityID uint32, stores []Store) (map[uint32]uint32, error) { - // 获取上个月的时间范围 - firstDay, lastDay := GetLastMonthRange() - - // 并行查询上月销售数量 - var wg sync.WaitGroup - wg.Add(len(stores)) - - result := make(map[uint32]uint32) - var mu sync.Mutex // 用于保护 totalSales 的并发访问 - - for _, store := range stores { - go func(storeID uint32) { - defer wg.Done() - // 查询上月销售数量 - var sales int64 - err := orm.Eloquent.Table("erp_stock_commodity"). - Where("state = ? AND erp_commodity_id = ? AND store_id = ? AND updated_at BETWEEN ? AND ?", - SoldOut, commodityID, storeID, firstDay, lastDay).Count(&sales).Error - if err != nil { - // Handle error - return - } - - // 保护 totalSales 的并发访问 - mu.Lock() - defer mu.Unlock() - result[storeID] = uint32(sales) - }(store.ID) - } - - wg.Wait() - - return result, nil -} - // GetLastMonthRange 获取上个月的时间范围 func GetLastMonthRange() (time.Time, time.Time) { now := time.Now()