using Microsoft.Extensions.Logging; using WIDESEA_Common.LocationEnum; using WIDESEA_Common.StockEnum; using WIDESEA_Core; using WIDESEA_Core.BaseRepository; using WIDESEA_Core.BaseServices; using WIDESEA_IBasicService; using WIDESEA_IOutboundService; using WIDESEA_IRecordService; using WIDESEA_IStockService; using WIDESEA_Model.Models; namespace WIDESEA_OutboundService { public partial class OutboundOrderDetailService : ServiceBase>, IOutboundOrderDetailService { private readonly IUnitOfWorkManage _unitOfWorkManage; public IRepository 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; private readonly ILogger _logger; public OutboundOrderDetailService(IRepository BaseDal, IUnitOfWorkManage unitOfWorkManage, IStockService stockService, IOutStockLockInfoService outStockLockInfoService, IBasicService basicService, IRecordService recordService, ILocationInfoService locationInfoService, ILocationStatusChangeRecordService locationStatusChangeRecordService, IOutboundOrderService outboundOrderService, ILogger logger) : base(BaseDal) { _unitOfWorkManage = unitOfWorkManage; _stockService = stockService; _outStockLockInfoService = outStockLockInfoService; _basicService = basicService; _recordService = recordService; _locationInfoService = locationInfoService; _locationStatusChangeRecordService = locationStatusChangeRecordService; _outboundOrderService = outboundOrderService; _logger = logger; } /// /// 分配出库库存 按先进先出原则分配 /// public (List, List, List, List) AssignStockOutbound(List outboundOrderDetails) { if (!outboundOrderDetails.Any()) { throw new Exception("未找到出库单明细信息"); } if (outboundOrderDetails.GroupBy(x => x.OrderId).Count() > 1) { throw new Exception("请勿同时操作多个单据明细"); } var outboundOrder = _outboundOrderService.Db.Queryable() .First(x => x.Id == outboundOrderDetails.First().OrderId); List outStocks = new List(); List outStockLockInfos = new List(); List locationInfos = new List(); // 按物料和批次分组处理 var groupDetails = outboundOrderDetails .GroupBy(x => new { x.MaterielCode, x.BatchNo }) .Select(x => new { MaterielCode = x.Key.MaterielCode, BatchNo = x.Key.BatchNo, 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 needQuantity = item.TotalNeedQuantity; // 获取可用库存(按先进先出排序) List stockInfos = _stockService.StockInfoService.GetUseableStocks(item.MaterielCode, item.BatchNo); if (!stockInfos.Any()) { throw new Exception($"物料[{item.MaterielCode}]批次[{item.BatchNo}]未找到可分配库存"); } // 分配库存(按先进先出) var (autoAssignStocks, stockAllocations) = _stockService.StockInfoService.GetOutboundStocks( stockInfos, item.MaterielCode, needQuantity, out decimal residueQuantity); if (residueQuantity > 0 && residueQuantity == needQuantity) { throw new Exception($"物料[{item.MaterielCode}]库存不足,需要{needQuantity},可用{needQuantity - residueQuantity}"); } outStocks.AddRange(autoAssignStocks); // 按先进先出原则分配锁定数量到各个明细 DistributeLockQuantityByFIFO(item.Details, autoAssignStocks, stockAllocations, outStockLockInfos, outboundOrder); } locationInfos.AddRange(_locationInfoService.GetLocationInfos(outStocks.Select(x => x.LocationCode).Distinct().ToList())); return (outStocks, outboundOrderDetails, outStockLockInfos, locationInfos); } /// /// 按先进先出原则分配锁定数量到各个明细 /// private void DistributeLockQuantityByFIFO( List details, List assignStocks, Dictionary stockAllocations, List outStockLockInfos, Dt_OutboundOrder outboundOrder) { // 按先进先出排序出库单明细(假设先创建的明细需要优先满足) var sortedDetails = details .Where(d => d.OrderQuantity - d.OverOutQuantity - d.LockQuantity -d.MoveQty> 0) // 只处理还需要分配的数量 .OrderBy(x => x.Id) .ToList(); if (!sortedDetails.Any()) return; // 获取所有分配了库存的明细,按先进先出排序 var allocatedStockDetails = assignStocks .SelectMany(x => x.Details) .Where(x => stockAllocations.ContainsKey(x.Id)) .OrderBy(x => x.CreateDate) .ThenBy(x => x.StockId) .ToList(); // 为每个库存明细创建分配记录 foreach (var stockDetail in allocatedStockDetails) { if (!stockAllocations.TryGetValue(stockDetail.Id, out decimal allocatedQuantity)) continue; if (allocatedQuantity <= 0) continue; var stockInfo = assignStocks.First(x => x.Id == stockDetail.StockId); decimal remainingAllocate = allocatedQuantity; // 按顺序分配给各个出库单明细 foreach (var detail in sortedDetails) { if (remainingAllocate <= 0) break; // 计算这个明细还需要分配的数量 var detailNeed = detail.OrderQuantity - detail.OverOutQuantity - detail.LockQuantity; if (detailNeed <= 0) continue; // 分配数量 var assignQuantity = Math.Min(remainingAllocate, detailNeed); // 验证条码是否存在 if (string.IsNullOrEmpty(stockDetail.Barcode)) { throw new Exception($"库存明细ID[{stockDetail.Id}]的条码为空"); } // 创建出库锁定信息 var lockInfo = _outStockLockInfoService.GetOutStockLockInfo( outboundOrder, detail, stockInfo, assignQuantity, stockDetail.Barcode); outStockLockInfos.Add(lockInfo); // 更新明细的锁定数量 detail.LockQuantity += assignQuantity; remainingAllocate -= assignQuantity; } // 如果还有剩余分配数量,重新分配或记录警告 if (remainingAllocate > 0) { // 重新分配给其他需要分配的明细 foreach (var detail in sortedDetails) { if (remainingAllocate <= 0) break; var detailNeed = detail.OrderQuantity - detail.OverOutQuantity - detail.LockQuantity; if (detailNeed <= 0) continue; var assignQuantity = Math.Min(remainingAllocate, detailNeed); var lockInfo = _outStockLockInfoService.GetOutStockLockInfo( outboundOrder, detail, stockInfo, assignQuantity, stockDetail.Barcode); outStockLockInfos.Add(lockInfo); detail.LockQuantity += assignQuantity; remainingAllocate -= assignQuantity; } // 如果还有剩余,记录警告但不抛出异常 if (remainingAllocate > 0) { _logger.LogWarning($"库存分配后仍有剩余数量未分配: {remainingAllocate}, 条码: {stockDetail.Barcode}"); } } } } /// /// 出库库存分配后,更新数据库数据 /// /// /// /// /// /// /// /// public WebResponseContent LockOutboundStockDataUpdate(List stockInfos, List outboundOrderDetails, List outStockLockInfos, List locationInfos, LocationStatusEnum locationStatus = LocationStatusEnum.Lock, List? tasks = null) { try { // 更新库存状态 stockInfos.ForEach(x => x.StockStatus = (int)StockStatusEmun.出库锁定); _stockService.StockInfoService.Repository.UpdateData(stockInfos); // 更新库存明细 var stockDetails = stockInfos.SelectMany(x => x.Details).ToList(); _stockService.StockInfoDetailService.Repository.UpdateData(stockDetails); BaseDal.UpdateData(outboundOrderDetails); List addOutStockLockInfos = outStockLockInfos.Where(x => x.Id == 0).ToList(); if (addOutStockLockInfos != null && addOutStockLockInfos.Any()) { if (tasks != null) { addOutStockLockInfos.ForEach(x => { x.TaskNum = tasks.FirstOrDefault(v => v.PalletCode == x.PalletCode)?.TaskNum; }); } _outStockLockInfoService.Repository.AddData(addOutStockLockInfos); } List updateOutStockLockInfos = outStockLockInfos.Where(x => x.Id > 0).ToList(); if (updateOutStockLockInfos != null && updateOutStockLockInfos.Any()) { _outStockLockInfoService.Repository.UpdateData(updateOutStockLockInfos); } _locationStatusChangeRecordService.AddLocationStatusChangeRecord(locationInfos, locationStatus, LocationChangeType.OutboundAssignLocation, "", tasks?.Select(x => x.TaskNum).ToList()); _locationInfoService.UpdateLocationStatus(locationInfos, locationStatus); return WebResponseContent.Instance.OK(); } catch (Exception ex) { return WebResponseContent.Instance.Error(ex.Message); } } } }