pan
2025-11-25 bbc4a3a07baf111c9074ceee7728158fb3eedf1a
ÏîÄ¿´úÂë/WMSÎÞ²Ö´¢°æ/WIDESEA_WMSServer/WIDESEA_OutboundService/OutboundOrderDetailService.cs
@@ -1,7 +1,13 @@
using WIDESEA_Common.LocationEnum;
using Microsoft.Extensions.Logging;
using SqlSugar;
using WIDESEA_Common.LocationEnum;
using WIDESEA_Common.OrderEnum;
using WIDESEA_Common.StockEnum;
using WIDESEA_Core;
using WIDESEA_Core.BaseRepository;
using WIDESEA_Core.BaseServices;
using WIDESEA_Core.Helper;
using WIDESEA_DTO.Stock;
using WIDESEA_IBasicService;
using WIDESEA_IOutboundService;
using WIDESEA_IRecordService;
@@ -15,15 +21,17 @@
        private readonly IUnitOfWorkManage _unitOfWorkManage;
        public IRepository<Dt_OutboundOrderDetail> Repository => BaseDal;
        private readonly IStockService _stockService;
        private readonly IOutStockLockInfoService _outStockLockInfoService;
        private readonly ILocationInfoService _locationInfoService;
        private readonly IBasicService _basicService;
        private readonly IRecordService _recordService;
        private readonly IOutboundOrderService _outboundOrderService;
        private readonly ILocationStatusChangeRecordService _locationStatusChangeRecordService;
        public OutboundOrderDetailService(IRepository<Dt_OutboundOrderDetail> BaseDal, IUnitOfWorkManage unitOfWorkManage, IStockService stockService, IOutStockLockInfoService outStockLockInfoService, IBasicService basicService, IRecordService recordService, ILocationInfoService locationInfoService, ILocationStatusChangeRecordService locationStatusChangeRecordService) : base(BaseDal)
        private readonly ILogger<OutboundOrderDetailService> _logger;
        public OutboundOrderDetailService(IRepository<Dt_OutboundOrderDetail> BaseDal, IUnitOfWorkManage unitOfWorkManage, IStockService stockService, IOutStockLockInfoService outStockLockInfoService, IBasicService basicService, IRecordService recordService, ILocationInfoService locationInfoService, ILocationStatusChangeRecordService locationStatusChangeRecordService, IOutboundOrderService outboundOrderService, ILogger<OutboundOrderDetailService> logger) : base(BaseDal)
        {
            _unitOfWorkManage = unitOfWorkManage;
            _stockService = stockService;
@@ -32,88 +40,145 @@
            _recordService = recordService;
            _locationInfoService = locationInfoService;
            _locationStatusChangeRecordService = locationStatusChangeRecordService;
            _outboundOrderService = outboundOrderService;
            _logger = logger;
        }
        /// <summary>
        ///
        /// åˆ†é…å‡ºåº“库存  æŒ‰å…ˆè¿›å…ˆå‡ºåŽŸåˆ™åˆ†é…
        /// </summary>
        /// <param name="outboundOrderDetails"></param>
        /// <returns></returns>
        public (List<Dt_StockInfo>, List<Dt_OutboundOrderDetail>, List<Dt_OutStockLockInfo>, List<Dt_LocationInfo>) AssignStockOutbound(List<Dt_OutboundOrderDetail> outboundOrderDetails)
        {
            if (!outboundOrderDetails.Any())
            {
                throw new Exception($"未找到出库单明细信息");
                throw new Exception("未找到出库单明细信息");
            }
            if (outboundOrderDetails.GroupBy(x => x.OrderId).Count() > 1)
            {
                throw new Exception($"请勿同时操作多个单据明细");
                throw new Exception("请勿同时操作多个单据明细");
            }
            Dt_OutboundOrder outboundOrder = Repository.Db.Queryable<Dt_OutboundOrder>().Where(x => x.Id == outboundOrderDetails.FirstOrDefault().OrderId).First();
            List<Dt_StockInfo> outStocks = new List<Dt_StockInfo>();
            List<Dt_OutboundOrderDetail> groupDetails = outboundOrderDetails.GroupBy(x => new { x.MaterielCode, x.BatchNo }).Select(x => new Dt_OutboundOrderDetail { OrderQuantity = x.Sum(v => v.OrderQuantity) - x.Sum(v => v.LockQuantity), MaterielCode = x.Key.MaterielCode, BatchNo = x.Key.BatchNo }).ToList();
            var outboundOrder = _outboundOrderService.Db.Queryable<Dt_OutboundOrder>()
                .First(x => x.Id == outboundOrderDetails.First().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 = outboundOrderDetails
                .GroupBy(x => new { x.MaterielCode, x.BatchNo, x.SupplyCode })
                .Select(x => new
                {
                    x.Key.MaterielCode,
                    x.Key.BatchNo,
                    x.Key.SupplyCode,
                    Details = x.ToList(),
                    TotalNeedQuantity = x.Sum(v => v.OrderQuantity - v.OverOutQuantity - v.LockQuantity - v.MoveQty)
                })
                .Where(x => x.TotalNeedQuantity > 0)
                .ToList();
            foreach (var item in groupDetails)
            {
                var originalNeedQuantity = item.OrderQuantity;
                var needQuantity = item.TotalNeedQuantity;
                var needQuantity = originalNeedQuantity;
                // èŽ·å–å¯ç”¨åº“å­˜ï¼ˆå·²æŒ‰å…ˆè¿›å…ˆå‡ºæŽ’åºï¼‰
                List<Dt_StockInfo> stockInfos = _stockService.StockInfoService.GetUseableStocks(
                    item.MaterielCode, item.BatchNo, item.SupplyCode);
                List<Dt_StockInfo> stockInfos = _stockService.StockInfoService.GetUseableStocks(item.MaterielCode, item.BatchNo);
                if (!stockInfos.Any())
                {
                    throw new Exception($"未找到可分配库存");
                    throw new Exception($"物料[{item.MaterielCode}]批次[{item.BatchNo}]未找到可分配库存");
                }
                List<Dt_StockInfo> autoAssignStocks = _stockService.StockInfoService.GetOutboundStocks(stockInfos, item.MaterielCode, needQuantity, out decimal residueQuantity);
                item.LockQuantity += needQuantity - residueQuantity;
                outStocks.AddRange(autoAssignStocks);
                var assignQuantity = needQuantity - residueQuantity;
                // åˆ†é…åº“å­˜
                var (autoAssignStocks, stockAllocations) = _stockService.StockInfoService.GetOutboundStocks(
                    stockInfos, item.MaterielCode, needQuantity, out decimal residueQuantity);
                List<Dt_OutboundOrderDetail> details = outboundOrderDetails.Where(x => !string.IsNullOrEmpty(x.BatchNo) ? x.BatchNo == item.BatchNo : true && x.MaterielCode == item.MaterielCode).ToList();
                for (int i = 0; i < details.Count; i++)
                // æ£€æŸ¥åˆ†é…ç»“æžœ
                if (residueQuantity > 0)
                {
                    var orderQuantity = details[i].OrderQuantity;
                    for (int j = 0; j < autoAssignStocks.Count; j++)
                    {
                        var detailAssignQuantity = outStockLockInfos.Where(x => !string.IsNullOrEmpty(x.BatchNo) ? x.BatchNo == item.BatchNo : true && x.MaterielCode == item.MaterielCode && x.OrderDetailId == details[i].Id).Sum(x => x.AssignQuantity);//出库订单明细已分配数量
                        var palletAssignQuantity = outStockLockInfos.Where(x => x.BatchNo == item.BatchNo && x.MaterielCode == item.MaterielCode && x.PalletCode == autoAssignStocks[j].PalletCode).Sum(x => x.AssignQuantity);//出库详情已分配数量
                        if (string.IsNullOrEmpty(item.BatchNo))
                        {
                            palletAssignQuantity = outStockLockInfos.Where(x => x.MaterielCode == item.MaterielCode && x.PalletCode == autoAssignStocks[j].PalletCode).Sum(x => x.AssignQuantity);//出库详情已分配数量
                        }
                        var palletOutboundQuantity = autoAssignStocks[j].Details.Sum(x => x.OutboundQuantity);
                        if (palletAssignQuantity < palletOutboundQuantity)//如果出库详情已分配数量小于托盘已分配数量,则可以继续添加该托盘出库信息
                        {
                            var orderDetailNeedQuantity = details[i].OrderQuantity - detailAssignQuantity;
                            if (orderDetailNeedQuantity > autoAssignStocks[j].Details.Sum(x => x.OutboundQuantity) - palletAssignQuantity)
                            {
                                details[i].LockQuantity += autoAssignStocks[j].Details.Sum(x => x.OutboundQuantity) - palletAssignQuantity;
                                Dt_OutStockLockInfo outStockLockInfo = _outStockLockInfoService.GetOutStockLockInfo(outboundOrder, details[i], autoAssignStocks[j], autoAssignStocks[j].Details.Sum(x => x.OutboundQuantity) - palletAssignQuantity);
                                outStockLockInfos.Add(outStockLockInfo);
                            }
                            else
                            {
                                Dt_OutStockLockInfo outStockLockInfo = _outStockLockInfoService.GetOutStockLockInfo(outboundOrder, details[i], autoAssignStocks[j], details[i].OrderQuantity - details[i].LockQuantity);
                                outStockLockInfos.Add(outStockLockInfo);
                                details[i].LockQuantity = details[i].OrderQuantity;
                                break;
                            }
                        }
                    }
                    var allocatedQuantity = needQuantity - residueQuantity;
                    throw new Exception($"物料[{item.MaterielCode}]库存不足,需要{needQuantity},实际分配{allocatedQuantity}");
                }
                outStocks.AddRange(autoAssignStocks);
                locationInfos.AddRange(_locationInfoService.GetLocationInfos(outStocks.Select(x => x.LocationCode).ToList()));
                // æŒ‰å…ˆè¿›å…ˆå‡ºåˆ†é…é”å®šæ•°é‡
                DistributeLockQuantityByFIFO(item.Details, autoAssignStocks, stockAllocations,
                    outStockLockInfos, outboundOrder);
            }
            locationInfos.AddRange(_locationInfoService.GetLocationInfos(
                outStocks.Select(x => x.LocationCode).Distinct().ToList()));
            return (outStocks, outboundOrderDetails, outStockLockInfos, locationInfos);
        }
        /// <summary>
        /// æŒ‰å…ˆè¿›å…ˆå‡ºåŽŸåˆ™åˆ†é…é”å®šæ•°é‡åˆ°å„ä¸ªæ˜Žç»†
        /// </summary>
        private void DistributeLockQuantityByFIFO(List<Dt_OutboundOrderDetail> details,List<Dt_StockInfo> assignStocks,Dictionary<int, decimal> stockAllocations,List<Dt_OutStockLockInfo> outStockLockInfos,
    Dt_OutboundOrder outboundOrder)
        {
            var sortedStocks = assignStocks.OrderBy(x => x.CreateDate).ToList();
            var totalNeedQuantity = details.Sum(d => d.OrderQuantity - d.OverOutQuantity - d.LockQuantity - d.MoveQty);
            decimal allocatedQuantity = 0;
            foreach (var stock in sortedStocks)
            {
                if (allocatedQuantity >= totalNeedQuantity) break;
                if (!stockAllocations.TryGetValue(stock.Id, out decimal stockAllocation) || stockAllocation <= 0)
                    continue;
                var sortedDetails = details
                    .Where(d => d.OrderQuantity - d.OverOutQuantity - d.LockQuantity - d.MoveQty > 0)
                    .OrderBy(x => x.Id)
                    .ToList();
                foreach (var detail in sortedDetails)
                {
                    if (stockAllocation <= 0) break;
                    var detailNeed = detail.OrderQuantity - detail.OverOutQuantity - detail.LockQuantity - detail.MoveQty;
                    if (detailNeed <= 0) continue;
                    var assignQuantity = Math.Min(stockAllocation, detailNeed);
                    // ä½¿ç”¨åº“存中的有效条码
                    var barcode = stock.Details
                        .Where(d => !string.IsNullOrEmpty(d.Barcode))
                        .Select(d => d.Barcode)
                        .FirstOrDefault();
                    if (string.IsNullOrEmpty(barcode))
                    {
                        throw new Exception($"库存ID[{stock.Id}]的条码为空");
                    }
                    var lockInfo = _outStockLockInfoService.GetOutStockLockInfo(
                        outboundOrder, detail, stock, assignQuantity, barcode);
                    outStockLockInfos.Add(lockInfo);
                    detail.LockQuantity += assignQuantity;
                    stockAllocation -= assignQuantity;
                    allocatedQuantity += assignQuantity;
                    if (allocatedQuantity >= totalNeedQuantity) break;
                }
            }
            // éªŒè¯æ˜¯å¦å®Œå…¨åˆ†é…
            if (allocatedQuantity < totalNeedQuantity)
            {
                _logger.LogWarning($"库存分配不完全,需要{totalNeedQuantity},实际分配{allocatedQuantity}");
            }
        }
        /// <summary>
@@ -126,30 +191,19 @@
        /// <param name="locationStatus"></param>
        /// <param name="tasks"></param>
        /// <returns></returns>
        public WebResponseContent LockOutboundStockDataUpdate(List<Dt_StockInfo> stockInfos, List<Dt_OutboundOrderDetail> outboundOrderDetails, List<Dt_OutStockLockInfo> outStockLockInfos, List<Dt_LocationInfo> locationInfos, LocationStatusEnum locationStatus = LocationStatusEnum.Lock, List<Dt_Task>? tasks = null)
        public WebResponseContent LockOutboundStockDataUpdate(List<Dt_StockInfo> stockInfos, List<Dt_OutboundOrderDetail> outboundOrderDetails,
            List<Dt_OutStockLockInfo> outStockLockInfos, List<Dt_LocationInfo> locationInfos,
            LocationStatusEnum locationStatus = LocationStatusEnum.Lock, List<Dt_Task>? tasks = null)
        {
            try
            {
                // æ›´æ–°åº“存状态
                stockInfos.ForEach(x => x.StockStatus = (int)StockStatusEmun.出库锁定);
                _stockService.StockInfoService.Repository.UpdateData(stockInfos);
                List<Dt_StockInfoDetail> stockInfoDetails = new List<Dt_StockInfoDetail>();
                foreach (var item in stockInfos)
                {
                    foreach (var detail in item.Details)
                    {
                        // è¿›è¡Œå®‰å…¨è½¬æ¢
                        if (detail.OutboundQuantity != null && decimal.TryParse(detail.OutboundQuantity.ToString(), out decimal outboundDecimal))
                        {
                            decimal outboundDecimal1 = Convert.ToDecimal(detail.OutboundQuantity);
                        }
                        else
                        {
                            detail.OutboundQuantity = 0; // é»˜è®¤å€¼æˆ–记录错误
                        }
                    }
                    stockInfoDetails.AddRange(item.Details);
                }
                _stockService.StockInfoDetailService.Repository.UpdateData(stockInfoDetails);
                // æ›´æ–°åº“存明细
                var stockDetails = stockInfos.SelectMany(x => x.Details).ToList();
                _stockService.StockInfoDetailService.Repository.UpdateData(stockDetails);
                BaseDal.UpdateData(outboundOrderDetails);
                List<Dt_OutStockLockInfo> addOutStockLockInfos = outStockLockInfos.Where(x => x.Id == 0).ToList();
@@ -181,5 +235,102 @@
            }
        }
        public override PageGridData<Dt_OutboundOrderDetail> GetPageData(PageDataOptions options)
        {
            //var  pageGridData = base.GetPageData(options);
            ISugarQueryable<Dt_OutboundOrderDetail> sugarQueryable1 = BaseDal.Db.Queryable<Dt_OutboundOrderDetail>();
            if (!string.IsNullOrEmpty(options.Wheres))
            {
                List<SearchParameters> searchParametersList = options.Wheres.DeserializeObject<List<SearchParameters>>();
                int totalCount = 0;
                if (searchParametersList.Count > 0)
                {
                    {
                        SearchParameters? searchParameters = searchParametersList.FirstOrDefault(x => x.Name == nameof(Dt_InboundOrderDetail.OrderId).FirstLetterToLower());
                        if (searchParameters != null)
                        {
                            sugarQueryable1 = sugarQueryable1.Where(x => x.OrderId == searchParameters.Value.ObjToInt());
                            var dataList = sugarQueryable1.ToPageList(options.Page, options.Rows, ref totalCount);
                            return new PageGridData<Dt_OutboundOrderDetail>(totalCount, dataList);
                        }
                    }
                }
            }
            return new PageGridData<Dt_OutboundOrderDetail>();
        }
        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);
            if (!checkResult.Item1) throw new Exception(checkResult.Item2);
            Dt_OutboundOrder outboundOrder = _outboundOrderService.Repository.QueryFirst(x => x.Id == outboundOrderDetail.OrderId);
            var originalNeedQuantity = outboundOrderDetail.OrderQuantity - outboundOrderDetail.LockQuantity - outboundOrderDetail.MoveQty;
            var needQuantity = originalNeedQuantity;
            List<Dt_StockInfo> outStocks = _stockService.StockInfoService.GetStockInfosByPalletCodes(stockSelectViews.Select(x => x.PalletCode).ToList());
            var assignQuantity = 0m;
            outStocks.ForEach(x =>
            {
                x.Details.ForEach(v =>
                {
                    assignQuantity += v.StockQuantity - v.OutboundQuantity;
                });
            });
            outboundOrderDetail.LockQuantity += assignQuantity;
            outStocks.ForEach(x =>
            {
                x.Details.ForEach(v =>
                {
                    v.OutboundQuantity = v.StockQuantity;
                });
            });
            needQuantity -= assignQuantity;
            if (outboundOrderDetail.OrderQuantity > outboundOrderDetail.LockQuantity)
            {
                List<Dt_StockInfo> stockInfos = _stockService.StockInfoService.GetUseableStocks(outboundOrderDetail.MaterielCode, outboundOrderDetail.BatchNo, "");
                stockInfos = stockInfos.Where(x => !stockSelectViews.Select(v => v.PalletCode).Contains(x.PalletCode)).ToList();
                var (autoAssignStocks, stockAllocations) = _stockService.StockInfoService.GetOutboundStocks(stockInfos, outboundOrderDetail.MaterielCode, needQuantity, out decimal residueQuantity);
                outboundOrderDetail.LockQuantity += needQuantity - residueQuantity;
                outStocks.AddRange(autoAssignStocks);
                outboundOrderDetail.OrderDetailStatus = OrderDetailStatusEnum.AssignOver.ObjToInt();
                if (residueQuantity > 0)
                {
                    outboundOrderDetail.OrderDetailStatus = OrderDetailStatusEnum.AssignOverPartial.ObjToInt();
                }
            }
            List<Dt_OutStockLockInfo> outStockLockInfos = _outStockLockInfoService.GetOutStockLockInfos(outboundOrder, outboundOrderDetail, outStocks);
            List<Dt_LocationInfo> locationInfos = _locationInfoService.GetLocationInfos(outStocks.Select(x => x.LocationCode).ToList());
            return (outStocks, outboundOrderDetail, outStockLockInfos, locationInfos);
        }
        private (bool, string) CheckSelectStockDeital(Dt_OutboundOrderDetail outboundOrderDetail, List<StockSelectViewDTO> stockSelectViews)
        {
            if (outboundOrderDetail == null)
            {
                return (false, "未找到出库单明细信息");
            }
            if (outboundOrderDetail.OrderDetailStatus != OrderDetailStatusEnum.New.ObjToInt() && outboundOrderDetail.OrderDetailStatus != OrderDetailStatusEnum.AssignOverPartial.ObjToInt())
            {
                return (false, "该明细不可操作");
            }
            //if (stockSelectViews.Sum(x => x.UseableQuantity) > outboundOrderDetail.OrderQuantity - outboundOrderDetail.LockQuantity - outboundOrderDetail.MoveQty)
            //{
            //    return (false, "选择数量超出单据数量");
            //}
            return (true, "成功");
        }
    }
}