pan
4 天以前 e4e304318532574e418bc01b5a45b8836dac3e1a
ÏîÄ¿´úÂë/WMSÎÞ²Ö´¢°æ/WIDESEA_WMSServer/WIDESEA_OutboundService/OutboundOrderDetailService.cs
@@ -1,4 +1,5 @@
using Microsoft.Extensions.Logging;
using Autofac.Core;
using Microsoft.Extensions.Logging;
using SqlSugar;
using WIDESEA_Common.LocationEnum;
using WIDESEA_Common.OrderEnum;
@@ -77,13 +78,14 @@
            // æŒ‰ç‰©æ–™å’Œæ‰¹æ¬¡åˆ†ç»„处理
            var groupDetails = outboundOrderDetails
                .GroupBy(x => new { x.MaterielCode, x.BatchNo, x.SupplyCode })
                .GroupBy(x => new { x.MaterielCode, x.BatchNo, x.SupplyCode,x.WarehouseCode })
                .Select(x => new
                {
                    MaterielCode = x.Key.MaterielCode,
                    BatchNo = x.Key.BatchNo,
                    SupplyCode = x.Key.SupplyCode,
                    Details = x.ToList(),
                    WarehouseCode=x.Key.WarehouseCode,
                    TotalNeedQuantity = CalculateReassignNeedQuantity(x.ToList())
                })
                .Where(x => x.TotalNeedQuantity > 0)
@@ -92,9 +94,9 @@
            foreach (var item in groupDetails)
            {
                var needQuantity = item.TotalNeedQuantity;
                // èŽ·å–å¯ç”¨åº“å­˜ï¼ˆæŒ‰å…ˆè¿›å…ˆå‡ºæŽ’åºï¼‰
                List<Dt_StockInfo> stockInfos = _stockService.StockInfoService.GetUseableStocks(item.MaterielCode, item.BatchNo, item.SupplyCode);
                List<Dt_StockInfo> stockInfos = _stockService.StockInfoService.GetUseableStocks(item.MaterielCode, item.BatchNo, item.SupplyCode,item.WarehouseCode, outboundOrder.FactoryArea);
                if (!stockInfos.Any())
                {
@@ -123,6 +125,10 @@
                // æ›´æ–°å‡ºåº“单明细状态
                UpdateOrderDetailStatus(item.Details, allocatedQuantity, needQuantity);
                // æ›´æ–°åº“存和托盘状态
               UpdateNormalStocksAndPalletsStatus(autoAssignStocks, stockAllocations);
            }
            if (outStocks.Any())
@@ -133,7 +139,27 @@
            return (outStocks, outboundOrderDetails, outStockLockInfos, locationInfos);
        }
        /// <summary>
        /// æ›´æ–°åº“存和托盘状态
        /// </summary>
        private void UpdateNormalStocksAndPalletsStatus(List<Dt_StockInfo> stocks, Dictionary<int, decimal> stockAllocations)
        {
            foreach (var stock in stocks)
            {
                var stockDetail = stock.Details.First();
                if (stockAllocations.TryGetValue(stockDetail.Id, out decimal allocatedQty) && allocatedQty > 0)
                {
                      _stockService.StockInfoService.Db.Updateable<Dt_StockInfo>()
                        .SetColumns(x => new Dt_StockInfo
                        {
                            StockStatus = (int)StockStatusEmun.出库锁定,
                        })
                        .Where(x => x.Id == stock.Id)
                        .ExecuteCommand();
                }
            }
        }
        /// <summary>
        /// æ£€æŸ¥è®¢å•是否允许重新分配
        /// </summary>
@@ -286,12 +312,13 @@
            // æŒ‰ç‰©æ–™å’Œæ‰¹æ¬¡åˆ†ç»„处理(这里只有一个明细)
            var groupDetails = new List<Dt_OutboundOrderDetail> { orderDetail }
                .GroupBy(x => new { x.MaterielCode, x.BatchNo, x.SupplyCode })
                .GroupBy(x => new { x.MaterielCode, x.BatchNo, x.SupplyCode ,x.WarehouseCode})
                .Select(x => new
                {
                    MaterielCode = x.Key.MaterielCode,
                    BatchNo = x.Key.BatchNo,
                    SupplyCode = x.Key.SupplyCode,
                    WarehouseCode=x.Key.WarehouseCode,
                    Details = x.ToList(),
                    TotalNeedQuantity = batchQuantity  // ä½¿ç”¨åˆ†æ‰¹æ•°é‡
                })
@@ -303,7 +330,7 @@
                var needQuantity = item.TotalNeedQuantity;
                // èŽ·å–å¯ç”¨åº“å­˜ï¼ˆæŒ‰å…ˆè¿›å…ˆå‡ºæŽ’åºï¼‰
                List<Dt_StockInfo> stockInfos = _stockService.StockInfoService.GetUseableStocks(item.MaterielCode, item.BatchNo, item.SupplyCode);
                List<Dt_StockInfo> stockInfos = _stockService.StockInfoService.GetUseableStocks(item.MaterielCode, item.BatchNo, item.SupplyCode,item.WarehouseCode,outboundOrder.FactoryArea);
                if (!stockInfos.Any())
                {
                    throw new Exception($"物料[{item.MaterielCode}]批次[{item.BatchNo}]未找到可分配库存");
@@ -331,6 +358,9 @@
                // æ›´æ–°å‡ºåº“单明细状态
                UpdateOrderDetailStatus(item.Details, allocatedQuantity, needQuantity);
                // æ›´æ–°åº“存和托盘状态为出库锁定
                await UpdateStocksAndPalletsStatus(autoAssignStocks, stockAllocations);
            }
            if (outStocks.Any())
@@ -343,7 +373,27 @@
            return (outStocks, groupDetails.SelectMany(x => x.Details).ToList(), outStockLockInfos, locationInfos);
        }
        /// <summary>
        /// æ›´æ–°åº“存和托盘状态
        /// </summary>
        private async Task UpdateStocksAndPalletsStatus(List<Dt_StockInfo> stocks, Dictionary<int, decimal> stockAllocations)
        {
            foreach (var stock in stocks)
            {
                var stockDetail = stock.Details.First();
                if (stockAllocations.TryGetValue(stockDetail.Id, out decimal allocatedQty) && allocatedQty > 0)
                {
                    await _stockService.StockInfoService.Db.Updateable<Dt_StockInfo>()
                        .SetColumns(x => new Dt_StockInfo
                        {
                            StockStatus = (int)StockStatusEmun.出库锁定,
                        })
                        .Where(x => x.Id == stock.Id)
                        .ExecuteCommandAsync();
                }
            }
        }
        /// <summary>
        /// æŒ‰å…ˆè¿›å…ˆå‡ºåŽŸåˆ™åˆ†é…é”å®šæ•°é‡
        /// </summary>
@@ -558,8 +608,7 @@
        }
        public (List<Dt_StockInfo>, Dt_OutboundOrderDetail, List<Dt_OutStockLockInfo>, List<Dt_LocationInfo>)
       AssignStockOutbound(Dt_OutboundOrderDetail outboundOrderDetail, List<StockSelectViewDTO> stockSelectViews)
        public (List<Dt_StockInfo>, Dt_OutboundOrderDetail, List<Dt_OutStockLockInfo>, List<Dt_LocationInfo>)AssignStockOutbound(Dt_OutboundOrderDetail outboundOrderDetail, List<StockSelectViewDTO> stockSelectViews)
        {
            // éªŒè¯ç”¨æˆ·é€‰æ‹©
            (bool, string) checkResult = CheckSelectStockDeital(outboundOrderDetail, stockSelectViews);
@@ -575,12 +624,9 @@
            decimal totalAssignedFromUserSelection = 0;
            // æŒ‰å…ˆè¿›å…ˆå‡ºæŽ’序用户选择的库存
            var userSelectedStocks = _stockService.StockInfoService.GetStockInfosByPalletCodes(
                stockSelectViews.Select(x => x.PalletCode).ToList());
            var userSelectedStocks = _stockService.StockInfoService.GetStockInfosByPalletCodes(stockSelectViews.Select(x => x.PalletCode).ToList());
            var sortedUserSelectedStocks = userSelectedStocks
                .OrderBy(x => x.CreateDate)
                .ToList();
            var sortedUserSelectedStocks = userSelectedStocks.OrderBy(x => x.CreateDate).ToList();
            // åˆ†é…ç”¨æˆ·é€‰æ‹©çš„库存
            foreach (var stock in sortedUserSelectedStocks)
@@ -592,26 +638,25 @@
                if (userSelection == null) continue;
                // è®¡ç®—该托盘实际可用数量
                var availableQuantity = CalculateAvailableQuantity(stock, outboundOrderDetail.MaterielCode,
                    outboundOrderDetail.BatchNo, outboundOrderDetail.SupplyCode);
                var availableQuantity = CalculateAvailableQuantityByBarcode(stock, outboundOrderDetail.MaterielCode,
           outboundOrderDetail.BatchNo, outboundOrderDetail.SupplyCode, userSelection.Barcode);
                // ç¡®å®šåˆ†é…æ•°é‡ï¼šå–用户选择数量、可用数量和剩余需求的最小值
                var assignQuantity = Math.Min(
                    Math.Min(userSelection.UseableQuantity, availableQuantity),
                    remainingNeedQuantity);
                var assignQuantity = Math.Min(Math.Min(userSelection.UseableQuantity, availableQuantity), remainingNeedQuantity);
                if (assignQuantity <= 0) continue;
                // æ‰§è¡Œåˆ†é…
                var actualAssigned = AssignStockQuantity(stock, outboundOrderDetail, assignQuantity);
                // æ‰§è¡Œåˆ†é…ï¼Œä½¿ç”¨ç”¨æˆ·é€‰æ‹©çš„æ¡ç 
                var actualAssigned = AssignStockQuantity(stock, outboundOrderDetail, assignQuantity, userSelection.Barcode);
                if (actualAssigned > 0)
                {
                    outStocks.Add(stock);
                    totalAssignedFromUserSelection += actualAssigned;
                    remainingNeedQuantity -= actualAssigned;
                    // åˆ›å»ºé”å®šè®°å½•
                    var lockInfo = CreateOutStockLockInfo(outboundOrder, outboundOrderDetail, stock, actualAssigned);
                    // åˆ›å»ºé”å®šè®°å½•,使用用户选择的条码
                    var lockInfo = CreateOutStockLockInfo(outboundOrder, outboundOrderDetail, stock, actualAssigned, userSelection.Barcode);
                    outStockLockInfos.Add(lockInfo);
                }
            }
@@ -623,48 +668,41 @@
            }
            // å¦‚果用户选择的库存不够,自动分配剩余部分
            decimal autoAssignedQuantity = 0;
            if (remainingNeedQuantity > 0)
            {
                List<Dt_StockInfo> autoStocks = _stockService.StockInfoService.GetUseableStocks(
                    outboundOrderDetail.MaterielCode, outboundOrderDetail.BatchNo, "");
                // æŽ’除用户已选择的托盘
                autoStocks = autoStocks
                    .Where(x => !stockSelectViews.Select(v => v.PalletCode).Contains(x.PalletCode))
                    .ToList();
                var (autoAssignStocks, stockAllocations) = _stockService.StockInfoService.GetOutboundStocks(
                    autoStocks, outboundOrderDetail.MaterielCode, remainingNeedQuantity, out decimal residueQuantity);
                // æ£€æŸ¥è‡ªåŠ¨åˆ†é…ç»“æžœ
                autoAssignedQuantity = remainingNeedQuantity - residueQuantity;
                if (autoAssignedQuantity <= 0 && remainingNeedQuantity > 0)
                {
                    // éƒ¨åˆ†åˆ†é…æ˜¯å¯ä»¥æŽ¥å—的,记录警告但不报错
                    _logger.LogWarning($"自动分配失败,剩余需求{remainingNeedQuantity}无法满足");
                }
                else if (autoAssignedQuantity > 0)
                {
                    outStocks.AddRange(autoAssignStocks);
                    // ä¸ºè‡ªåŠ¨åˆ†é…çš„åº“å­˜åˆ›å»ºé”å®šè®°å½•
                    var autoLockInfos = CreateLockInfosForAutoAssign(outboundOrder, outboundOrderDetail, autoAssignStocks, stockAllocations);
                    outStockLockInfos.AddRange(autoLockInfos);
                }
            }
            // æ›´æ–°é”å®šæ•°é‡
            outboundOrderDetail.LockQuantity += totalAssignedFromUserSelection + autoAssignedQuantity;
            outboundOrderDetail.LockQuantity += totalAssignedFromUserSelection;
            // æ›´æ–°çŠ¶æ€
            UpdateOrderDetailStatus(outboundOrderDetail, remainingNeedQuantity - autoAssignedQuantity);
            UpdateOrderDetailStatus(outboundOrderDetail, remainingNeedQuantity);
            List<Dt_LocationInfo> locationInfos = _locationInfoService.GetLocationInfos(outStocks.Select(x => x.LocationCode).ToList());
            return (outStocks, outboundOrderDetail, outStockLockInfos, locationInfos);
        }
        private decimal CalculateAvailableQuantityByBarcode(Dt_StockInfo stock, string materielCode, string batchNo, string supplyCode, string barcode)
        {
            var query = stock.Details.AsQueryable()
                .Where(d => d.MaterielCode == materielCode &&
                           (d.StockQuantity - d.OutboundQuantity) > 0 &&
                           d.Barcode == barcode);
            if (!string.IsNullOrEmpty(batchNo))
            {
                query = query.Where(x => x.BatchNo == batchNo);
            }
            if (!string.IsNullOrEmpty(supplyCode))
            {
                query = query.Where(d => d.SupplyCode == supplyCode);
            }
            return query.Sum(d => d.StockQuantity - d.OutboundQuantity);
        }
        // è¾…助方法
        private decimal CalculateAvailableQuantity(Dt_StockInfo stock, string materielCode, string batchNo, string supplyCode)
        {
@@ -677,23 +715,28 @@
            return relevantDetails.Sum(d => d.StockQuantity - d.OutboundQuantity);
        }
        private decimal AssignStockQuantity(Dt_StockInfo stock, Dt_OutboundOrderDetail detail, decimal assignQuantity)
        private decimal AssignStockQuantity(Dt_StockInfo stock, Dt_OutboundOrderDetail detail, decimal assignQuantity, string barcode)
        {
            decimal remainingAssign = assignQuantity;
            // æŒ‰å…ˆè¿›å…ˆå‡ºåˆ†é…åº“存明细
            var sorteds = stock.Details
            // æŒ‰å…ˆè¿›å…ˆå‡ºåˆ†é…æŒ‡å®šæ¡ç çš„库存明细
            var query = stock.Details.AsQueryable()
                .Where(d => d.MaterielCode == detail.MaterielCode &&
                           (d.StockQuantity - d.OutboundQuantity) > 0);
               // .OrderBy(d => d.CreateDate);
                           (d.StockQuantity - d.OutboundQuantity) > 0 &&
                           d.Barcode == barcode); // åªåˆ†é…æŒ‡å®šæ¡ç 
            query = query.Where(x => x.WarehouseCode == detail.WarehouseCode);
            if (!string.IsNullOrEmpty(detail.BatchNo))
            {
                sorteds= stock.Details.Where(x => x.BatchNo == detail.BatchNo);
                query = query.Where(x => x.BatchNo == detail.BatchNo);
            }
            var sortedDetails= sorteds.ToList().OrderBy(d => d.CreateDate);
            // å¦‚果出库单有供应商要求,按供应商过滤
            if (!string.IsNullOrEmpty(detail.SupplyCode))
            {
                query = query.Where(d => d.SupplyCode == detail.SupplyCode);
            }
            var sortedDetails = query.ToList().OrderBy(d => d.CreateDate);
            foreach (var stockDetail in sortedDetails)
            {
@@ -709,13 +752,52 @@
            return assignQuantity - remainingAssign; // è¿”回实际分配数量
        }
        private Dt_OutStockLockInfo CreateOutStockLockInfo(Dt_OutboundOrder outboundOrder, Dt_OutboundOrderDetail detail,
            Dt_StockInfo stock, decimal quantity)
        private (decimal assignedQuantity, string barcode) AssignStockQuantity(Dt_StockInfo stock, Dt_OutboundOrderDetail detail, decimal assignQuantity)
        {
            var barcode = stock.Details
                .Where(d => !string.IsNullOrEmpty(d.Barcode))
                .Select(d => d.Barcode)
                .FirstOrDefault();
            decimal remainingAssign = assignQuantity;
            string assignedBarcode = string.Empty;
            // æŒ‰å…ˆè¿›å…ˆå‡ºåˆ†é…åº“存明细
            var query = stock.Details.AsQueryable()
                .Where(d => d.MaterielCode == detail.MaterielCode &&
                           (d.StockQuantity - d.OutboundQuantity) > 0);
               // .OrderBy(d => d.CreateDate);
            if (!string.IsNullOrEmpty(detail.BatchNo))
            {
                query = query.Where(x => x.BatchNo == detail.BatchNo);
            }
            // å¦‚果出库单有供应商要求,按供应商过滤
            if (!string.IsNullOrEmpty(detail.SupplyCode))
            {
                query = query.Where(d => d.SupplyCode == detail.SupplyCode);
            }
            var sortedDetails= query.ToList().OrderBy(d => d.CreateDate);
            foreach (var stockDetail in sortedDetails)
            {
                if (remainingAssign <= 0) break;
                var available = stockDetail.StockQuantity - stockDetail.OutboundQuantity;
                var assign = Math.Min(available, remainingAssign);
                stockDetail.OutboundQuantity += assign;
                remainingAssign -= assign;
                if (string.IsNullOrEmpty(assignedBarcode) && assign > 0)
                {
                    assignedBarcode = stockDetail.Barcode;
                }
            }
            return (assignQuantity - remainingAssign, assignedBarcode);
        }
        private Dt_OutStockLockInfo CreateOutStockLockInfo(Dt_OutboundOrder outboundOrder, Dt_OutboundOrderDetail detail,
            Dt_StockInfo stock, decimal quantity,string barcode="")
        {
            return _outStockLockInfoService.GetOutStockLockInfo(outboundOrder, detail, stock, quantity, barcode);
        }
@@ -779,8 +861,8 @@
                    return (false, $"托盘[{selection.PalletCode}]不存在");
                }
                var available = CalculateAvailableQuantity(stock, outboundOrderDetail.MaterielCode,
                    outboundOrderDetail.BatchNo, outboundOrderDetail.SupplyCode);
                var available = CalculateAvailableQuantityByBarcode(stock, outboundOrderDetail.MaterielCode,
                    outboundOrderDetail.BatchNo, outboundOrderDetail.SupplyCode,selection.Barcode);
                if (available <= 0)
                {