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; 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, 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 needQuantity = item.TotalNeedQuantity; // 获取可用库存(已按先进先出排序) List 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); // 检查分配结果 if (residueQuantity > 0) { var allocatedQuantity = needQuantity - residueQuantity; throw new Exception($"物料[{item.MaterielCode}]库存不足,需要{needQuantity},实际分配{allocatedQuantity}"); } 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 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}"); } } /// /// 出库库存分配后,更新数据库数据 /// /// /// /// /// /// /// /// 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); } } public override PageGridData GetPageData(PageDataOptions options) { //var pageGridData = base.GetPageData(options); ISugarQueryable sugarQueryable1 = BaseDal.Db.Queryable(); if (!string.IsNullOrEmpty(options.Wheres)) { List searchParametersList = options.Wheres.DeserializeObject>(); 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(totalCount, dataList); } } } } return new PageGridData(); } public (List, Dt_OutboundOrderDetail, List, List) AssignStockOutbound(Dt_OutboundOrderDetail outboundOrderDetail, List 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 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 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 outStockLockInfos = _outStockLockInfoService.GetOutStockLockInfos(outboundOrder, outboundOrderDetail, outStocks); List locationInfos = _locationInfoService.GetLocationInfos(outStocks.Select(x => x.LocationCode).ToList()); return (outStocks, outboundOrderDetail, outStockLockInfos, locationInfos); } private (bool, string) CheckSelectStockDeital(Dt_OutboundOrderDetail outboundOrderDetail, List 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, "成功"); } } }