pan
2025-11-30 c100108c13c74ebd99253c4c144b262720b55ecd
ÏîÄ¿´úÂë/WMSÎÞ²Ö´¢°æ/WIDESEA_WMSServer/WIDESEA_OutboundService/OutboundOrderDetailService.cs
@@ -66,6 +66,11 @@
            var outboundOrder = _outboundOrderService.Db.Queryable<Dt_OutboundOrder>()
                .First(x => x.Id == orderId);
            if (!CanReassignOrder(outboundOrder))
            {
                throw new Exception($"订单{outboundOrder.OrderNo}状态不允许重新分配库存");
            }
            List<Dt_StockInfo> outStocks = new List<Dt_StockInfo>();
            List<Dt_OutStockLockInfo> outStockLockInfos = new List<Dt_OutStockLockInfo>();
            List<Dt_LocationInfo> locationInfos = new List<Dt_LocationInfo>();
@@ -79,7 +84,7 @@
                    BatchNo = x.Key.BatchNo,
                    SupplyCode = x.Key.SupplyCode,
                    Details = x.ToList(),
                    TotalNeedQuantity = x.Sum(v => v.OrderQuantity - v.OverOutQuantity - v.LockQuantity - v.MoveQty)
                    TotalNeedQuantity = CalculateReassignNeedQuantity(x.ToList())
                })
                .Where(x => x.TotalNeedQuantity > 0)
                .ToList();
@@ -93,7 +98,7 @@
                if (!stockInfos.Any())
                {
                    throw new Exception($"物料[{item.MaterielCode}]批次[{item.BatchNo}]未找到可分配库存");
                    throw new Exception($"物料[{item.MaterielCode}]批次[{item.BatchNo}]供应商[{item.SupplyCode}]未找到可分配库存");
                }
                // åˆ†é…åº“存(按先进先出)
@@ -127,6 +132,39 @@
            }
            return (outStocks, outboundOrderDetails, outStockLockInfos, locationInfos);
        }
        /// <summary>
        /// æ£€æŸ¥è®¢å•是否允许重新分配
        /// </summary>
        private bool CanReassignOrder(Dt_OutboundOrder outboundOrder)
        {
            // å…è®¸é‡æ–°åˆ†é…çš„状态
            var allowedStatus = new[] {OutOrderStatusEnum.未开始, OutOrderStatusEnum.出库中,OutOrderStatusEnum.部分完成};
            return allowedStatus.Contains((OutOrderStatusEnum)outboundOrder.OrderStatus);
        }
        /// <summary>
        /// é‡æ–°è®¡ç®—需求数量(考虑重新分配的场景)
        /// </summary>
        private decimal CalculateReassignNeedQuantity(List<Dt_OutboundOrderDetail> details)
        {
            decimal totalNeed = 0;
            foreach (var detail in details)
            {
                // å…³é”®ä¿®æ”¹ï¼šé‡æ–°åˆ†é…æ—¶ï¼Œåªè€ƒè™‘未出库的部分,忽略锁定数量
                // å› ä¸ºé”å®šæ•°é‡åœ¨å›žåº“时已经被重置
                decimal remainingNeed = detail.OrderQuantity - detail.OverOutQuantity - detail.MoveQty;
                if (remainingNeed > 0)
                {
                    totalNeed += remainingNeed;
                }
            }
            return totalNeed;
        }
        private (bool success, string message) DistributeLockQuantityByFIFO(
           List<Dt_OutboundOrderDetail> details,
@@ -227,6 +265,190 @@
            return (true, "分配成功");
        }
        /// <summary>
        /// ä¸ºåˆ†æ‰¹åˆ†é…åº“å­˜
        /// </summary>
        public async Task<(List<Dt_StockInfo>, List<Dt_OutboundOrderDetail>, List<Dt_OutStockLockInfo>, List<Dt_LocationInfo>)>
            AssignStockForBatch(Dt_OutboundOrderDetail orderDetail, decimal batchQuantity, string batchNo)
        {
            if (orderDetail == null)
            {
                throw new Exception("未找到出库单明细信息");
            }
            var outboundOrder = await _outboundOrderService.Db.Queryable<Dt_OutboundOrder>()
                .FirstAsync(x => x.Id == orderDetail.OrderId);
            List<Dt_StockInfo> outStocks = new List<Dt_StockInfo>();
            List<Dt_OutStockLockInfo> outStockLockInfos = new List<Dt_OutStockLockInfo>();
            List<Dt_LocationInfo> locationInfos = new List<Dt_LocationInfo>();
            // æŒ‰ç‰©æ–™å’Œæ‰¹æ¬¡åˆ†ç»„处理(这里只有一个明细)
            var groupDetails = new List<Dt_OutboundOrderDetail> { orderDetail }
                .GroupBy(x => new { x.MaterielCode, x.BatchNo, x.SupplyCode })
                .Select(x => new
                {
                    MaterielCode = x.Key.MaterielCode,
                    BatchNo = x.Key.BatchNo,
                    SupplyCode = x.Key.SupplyCode,
                    Details = x.ToList(),
                    TotalNeedQuantity = batchQuantity  // ä½¿ç”¨åˆ†æ‰¹æ•°é‡
                })
                .Where(x => x.TotalNeedQuantity > 0)
                .ToList();
            foreach (var item in groupDetails)
            {
                var needQuantity = item.TotalNeedQuantity;
                // èŽ·å–å¯ç”¨åº“å­˜ï¼ˆæŒ‰å…ˆè¿›å…ˆå‡ºæŽ’åºï¼‰
                List<Dt_StockInfo> stockInfos = _stockService.StockInfoService.GetUseableStocks(item.MaterielCode, item.BatchNo, item.SupplyCode);
                if (!stockInfos.Any())
                {
                    throw new Exception($"物料[{item.MaterielCode}]批次[{item.BatchNo}]未找到可分配库存");
                }
                // åˆ†é…åº“存(按先进先出)
                var (autoAssignStocks, stockAllocations) = _stockService.StockInfoService.GetOutboundStocks(stockInfos, item.MaterielCode, needQuantity, out decimal residueQuantity);
                // æ£€æŸ¥åˆ†é…ç»“æžœ
                decimal allocatedQuantity = needQuantity - residueQuantity;
                if (allocatedQuantity <= 0)
                {
                    throw new Exception($"物料[{item.MaterielCode}]批次[{item.BatchNo}]库存不足,需要{needQuantity},但无法分配任何库存");
                }
                outStocks.AddRange(autoAssignStocks);
                // æŒ‰å…ˆè¿›å…ˆå‡ºåŽŸåˆ™åˆ†é…é”å®šæ•°é‡åˆ°å„ä¸ªæ˜Žç»†
                var distributionResult = DistributeLockQuantityByFIFO(item.Details, autoAssignStocks, stockAllocations, outStockLockInfos, outboundOrder, batchNo);
                if (!distributionResult.success)
                {
                    throw new Exception(distributionResult.message);
                }
                // æ›´æ–°å‡ºåº“单明细状态
                UpdateOrderDetailStatus(item.Details, allocatedQuantity, needQuantity);
            }
            if (outStocks.Any())
            {
                locationInfos.AddRange(_locationInfoService.GetLocationInfos(
                  outStocks.Select(x => x.LocationCode).Distinct().ToList()));
            }
            return (outStocks, groupDetails.SelectMany(x => x.Details).ToList(), outStockLockInfos, locationInfos);
        }
        /// <summary>
        /// æŒ‰å…ˆè¿›å…ˆå‡ºåŽŸåˆ™åˆ†é…é”å®šæ•°é‡
        /// </summary>
        private (bool success, string message) DistributeLockQuantityByFIFO(
            List<Dt_OutboundOrderDetail> details,
            List<Dt_StockInfo> assignStocks,
            Dictionary<int, decimal> stockAllocations,
            List<Dt_OutStockLockInfo> outStockLockInfos,
            Dt_OutboundOrder outboundOrder,
            string batchNo)
        {
            var sortedDetails = details
                .Where(d => d.OrderQuantity - d.OverOutQuantity - d.AllocatedQuantity > 0)
                .OrderBy(x => x.Id)
                .ToList();
            if (!sortedDetails.Any())
                return (true, "无需分配");
            // èŽ·å–æ‰€æœ‰åˆ†é…äº†åº“å­˜çš„æ˜Žç»†ï¼ŒæŒ‰å…ˆè¿›å…ˆå‡ºæŽ’åº
            var allocatedStockDetails = assignStocks
                .SelectMany(x => x.Details)
                .Where(x => stockAllocations.ContainsKey(x.Id) && stockAllocations[x.Id] > 0)
                .OrderBy(x => x.CreateDate)
                .ThenBy(x => x.StockId)
                .ToList();
            if (!allocatedStockDetails.Any())
            {
                return (false, "没有可分配的库存明细");
            }
            decimal totalNeedQuantity = sortedDetails.Sum(d =>
                d.OrderQuantity - d.OverOutQuantity - d.AllocatedQuantity);
            decimal allocatedQuantity = 0;
            // ä¸ºæ¯ä¸ªåº“存明细创建分配记录
            foreach (var stockDetail in allocatedStockDetails)
            {
                if (!stockAllocations.TryGetValue(stockDetail.Id, out decimal allocatedQuantityForStock))
                    continue;
                if (allocatedQuantityForStock <= 0) continue;
                var stockInfo = assignStocks.First(x => x.Id == stockDetail.StockId);
                decimal remainingAllocate = allocatedQuantityForStock;
                // æŒ‰é¡ºåºåˆ†é…ç»™å„个出库单明细
                foreach (var detail in sortedDetails)
                {
                    if (remainingAllocate <= 0) break;
                    // è®¡ç®—这个明细还需要分配的数量
                    var detailNeed = detail.OrderQuantity - detail.OverOutQuantity - detail.AllocatedQuantity;
                    if (detailNeed <= 0) continue;
                    // åˆ†é…æ•°é‡
                    var assignQuantity = Math.Min(remainingAllocate, detailNeed);
                    // éªŒè¯æ¡ç æ˜¯å¦å­˜åœ¨
                    if (string.IsNullOrEmpty(stockDetail.Barcode))
                    {
                        return (false, $"库存明细ID[{stockDetail.Id}]的条码为空");
                    }
                    // åˆ›å»ºå‡ºåº“锁定信息
                    var lockInfo = _outStockLockInfoService.GetOutStockLockInfo(
                        outboundOrder, detail, stockInfo, assignQuantity, stockDetail.Barcode, batchNo);
                    outStockLockInfos.Add(lockInfo);
                    // æ›´æ–°æ˜Žç»†çš„已分配数量
                    detail.AllocatedQuantity += assignQuantity;
                    detail.LockQuantity = detail.AllocatedQuantity;
                    remainingAllocate -= assignQuantity;
                    allocatedQuantity += assignQuantity;
                }
                // å¦‚果还有剩余分配数量,记录警告
                if (remainingAllocate > 0)
                {
                    _logger.LogWarning($"库存分配后仍有剩余数量未分配: {remainingAllocate}, æ¡ç : {stockDetail.Barcode}");
                }
            }
            // éªŒè¯æ˜¯å¦è‡³å°‘分配了一部分
            if (allocatedQuantity <= 0)
            {
                return (false, "库存分配失败,无法分配任何数量");
            }
            // è®°å½•分配结果
            if (allocatedQuantity < totalNeedQuantity)
            {
                _logger.LogWarning($"库存部分分配,需要{totalNeedQuantity},实际分配{allocatedQuantity}");
            }
            else
            {
                _logger.LogInformation($"库存完全分配,分配数量{allocatedQuantity}");
            }
            return (true, "分配成功");
        }
        private void UpdateOrderDetailStatus(List<Dt_OutboundOrderDetail> details,
    decimal allocatedQuantity, decimal needQuantity)
        {