From 07774c70a65bed6bacf936bdd66f756ba9c7f266 Mon Sep 17 00:00:00 2001
From: pan <antony1029@163.com>
Date: 星期二, 02 十二月 2025 10:15:48 +0800
Subject: [PATCH] 提交

---
 项目代码/WMS无仓储版/WIDESEA_WMSServer/WIDESEA_OutboundService/OutboundOrderDetailService.cs |  782 +++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 files changed, 778 insertions(+), 4 deletions(-)

diff --git "a/\351\241\271\347\233\256\344\273\243\347\240\201/WMS\346\227\240\344\273\223\345\202\250\347\211\210/WIDESEA_WMSServer/WIDESEA_OutboundService/OutboundOrderDetailService.cs" "b/\351\241\271\347\233\256\344\273\243\347\240\201/WMS\346\227\240\344\273\223\345\202\250\347\211\210/WIDESEA_WMSServer/WIDESEA_OutboundService/OutboundOrderDetailService.cs"
index 45c6d75..d222228 100644
--- "a/\351\241\271\347\233\256\344\273\243\347\240\201/WMS\346\227\240\344\273\223\345\202\250\347\211\210/WIDESEA_WMSServer/WIDESEA_OutboundService/OutboundOrderDetailService.cs"
+++ "b/\351\241\271\347\233\256\344\273\243\347\240\201/WMS\346\227\240\344\273\223\345\202\250\347\211\210/WIDESEA_WMSServer/WIDESEA_OutboundService/OutboundOrderDetailService.cs"
@@ -1,6 +1,17 @@
-锘縰sing WIDESEA_Core.BaseRepository;
+锘縰sing 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
@@ -8,13 +19,776 @@
     public partial class OutboundOrderDetailService : ServiceBase<Dt_OutboundOrderDetail, IRepository<Dt_OutboundOrderDetail>>, IOutboundOrderDetailService
     {
         private readonly IUnitOfWorkManage _unitOfWorkManage;
-
         public IRepository<Dt_OutboundOrderDetail> Repository => BaseDal;
 
-        public OutboundOrderDetailService(IRepository<Dt_OutboundOrderDetail> BaseDal, IUnitOfWorkManage unitOfWorkManage) : base(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<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;
+            _outStockLockInfoService = outStockLockInfoService;
+            _basicService = basicService;
+            _recordService = recordService;
+            _locationInfoService = locationInfoService;
+            _locationStatusChangeRecordService = locationStatusChangeRecordService;
+            _outboundOrderService = outboundOrderService;
+            _logger = logger;
+
         }
-       
+
+
+        /// <summary>
+        /// 鍒嗛厤鍑哄簱搴撳瓨  鎸夊厛杩涘厛鍑哄師鍒欏垎閰�
+        /// </summary>
+        public (List<Dt_StockInfo>, List<Dt_OutboundOrderDetail>, List<Dt_OutStockLockInfo>, List<Dt_LocationInfo>)
+       AssignStockOutbound(List<Dt_OutboundOrderDetail> outboundOrderDetails)
+        {
+            if (!outboundOrderDetails.Any())
+            {
+                throw new Exception("鏈壘鍒板嚭搴撳崟鏄庣粏淇℃伅");
+            }
+
+            if (outboundOrderDetails.GroupBy(x => x.OrderId).Count() > 1)
+            {
+                throw new Exception("璇峰嬁鍚屾椂鎿嶄綔澶氫釜鍗曟嵁鏄庣粏");
+            }
+
+            var orderId = outboundOrderDetails.First().OrderId;
+            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>();
+
+            // 鎸夌墿鏂欏拰鎵规鍒嗙粍澶勭悊
+            var groupDetails = outboundOrderDetails
+                .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 = CalculateReassignNeedQuantity(x.ToList())
+                })
+                .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}]渚涘簲鍟哰{item.SupplyCode}]鏈壘鍒板彲鍒嗛厤搴撳瓨");
+                }
+
+                // 鍒嗛厤搴撳瓨锛堟寜鍏堣繘鍏堝嚭锛�
+                var (autoAssignStocks, stockAllocations) = _stockService.StockInfoService.GetOutboundStocks(stockInfos, item.MaterielCode, needQuantity, out decimal residueQuantity);
+
+                // 妫�鏌ュ垎閰嶇粨鏋滐細濡傛灉瀹屽叏鏃犳硶鍒嗛厤锛堝垎閰嶆暟閲忎负0锛夛紝鍒欐姤閿�
+                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);
+
+                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, 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,
+           List<Dt_StockInfo> assignStocks,
+           Dictionary<int, decimal> stockAllocations,
+           List<Dt_OutStockLockInfo> outStockLockInfos,
+           Dt_OutboundOrder outboundOrder)
+        {
+            // 鎸夊厛杩涘厛鍑烘帓搴忓嚭搴撳崟鏄庣粏锛圛d灏忕殑浼樺厛锛�
+            var sortedDetails = details
+                .Where(d => d.OrderQuantity - d.OverOutQuantity - d.LockQuantity - d.MoveQty > 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.LockQuantity - d.MoveQty);
+            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.LockQuantity - detail.MoveQty;
+                    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);
+                    outStockLockInfos.Add(lockInfo);
+
+                    // 鏇存柊鏄庣粏鐨勯攣瀹氭暟閲�
+                    detail.LockQuantity += assignQuantity;
+                    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, "鍒嗛厤鎴愬姛");
+        }
+
+
+        /// <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)
+        {
+            foreach (var detail in details)
+            {
+                var detailNeed = detail.OrderQuantity - detail.LockQuantity - detail.OverOutQuantity - detail.MoveQty;
+
+                if (detailNeed <= 0)
+                {
+                    // 璇ユ槑缁嗗凡瀹屽叏鍒嗛厤
+                    detail.OrderDetailStatus = OrderDetailStatusEnum.AssignOver.ObjToInt();
+                }
+                else if (allocatedQuantity < needQuantity)
+                {
+                    // 鏁翠綋閮ㄥ垎鍒嗛厤锛岃鏄庣粏鍙兘杩樻湁闇�姹�
+                    detail.OrderDetailStatus = OrderDetailStatusEnum.AssignOverPartial.ObjToInt();
+                }
+                else
+                {
+                    // 鏁翠綋瀹屽叏鍒嗛厤
+                    detail.OrderDetailStatus = OrderDetailStatusEnum.AssignOver.ObjToInt();
+                }
+            }
+        }
+        /// <summary>
+        /// 鍑哄簱搴撳瓨鍒嗛厤鍚庯紝鏇存柊鏁版嵁搴撴暟鎹�
+        /// </summary>
+        /// <param name="stockInfos"></param>
+        /// <param name="outboundOrderDetails"></param>
+        /// <param name="outStockLockInfos"></param>
+        /// <param name="locationInfos"></param>
+        /// <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)
+        {
+            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<Dt_OutStockLockInfo> 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<Dt_OutStockLockInfo> 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<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;
+
+            List<Dt_StockInfo> outStocks = new List<Dt_StockInfo>();
+            List<Dt_OutStockLockInfo> outStockLockInfos = new List<Dt_OutStockLockInfo>();
+
+            decimal remainingNeedQuantity = originalNeedQuantity;
+            decimal totalAssignedFromUserSelection = 0;
+
+            // 鎸夊厛杩涘厛鍑烘帓搴忕敤鎴烽�夋嫨鐨勫簱瀛�
+            var userSelectedStocks = _stockService.StockInfoService.GetStockInfosByPalletCodes(
+                stockSelectViews.Select(x => x.PalletCode).ToList());
+
+            var sortedUserSelectedStocks = userSelectedStocks
+                .OrderBy(x => x.CreateDate)
+                .ToList();
+
+            // 鍒嗛厤鐢ㄦ埛閫夋嫨鐨勫簱瀛�
+            foreach (var stock in sortedUserSelectedStocks)
+            {
+                if (remainingNeedQuantity <= 0) break;
+
+                // 鑾峰彇鐢ㄦ埛瀵硅鎵樼洏鐨勯�夋嫨鏁伴噺
+                var userSelection = stockSelectViews.FirstOrDefault(x => x.PalletCode == stock.PalletCode);
+                if (userSelection == null) continue;
+
+                // 璁$畻璇ユ墭鐩樺疄闄呭彲鐢ㄦ暟閲�
+                var availableQuantity = CalculateAvailableQuantity(stock, outboundOrderDetail.MaterielCode,
+                    outboundOrderDetail.BatchNo, outboundOrderDetail.SupplyCode);
+
+                // 纭畾鍒嗛厤鏁伴噺锛氬彇鐢ㄦ埛閫夋嫨鏁伴噺銆佸彲鐢ㄦ暟閲忓拰鍓╀綑闇�姹傜殑鏈�灏忓��
+                var assignQuantity = Math.Min(
+                    Math.Min(userSelection.UseableQuantity, availableQuantity),
+                    remainingNeedQuantity);
+
+                if (assignQuantity <= 0) continue;
+
+                // 鎵ц鍒嗛厤
+                var actualAssigned = AssignStockQuantity(stock, outboundOrderDetail, assignQuantity);
+                if (actualAssigned > 0)
+                {
+                    outStocks.Add(stock);
+                    totalAssignedFromUserSelection += actualAssigned;
+                    remainingNeedQuantity -= actualAssigned;
+
+                    // 鍒涘缓閿佸畾璁板綍
+                    var lockInfo = CreateOutStockLockInfo(outboundOrder, outboundOrderDetail, stock, actualAssigned);
+                    outStockLockInfos.Add(lockInfo);
+                }
+            }
+
+            // 妫�鏌ョ敤鎴烽�夋嫨鏄惁鑷冲皯鍒嗛厤浜嗕竴閮ㄥ垎
+            if (totalAssignedFromUserSelection <= 0)
+            {
+                throw new Exception("鐢ㄦ埛閫夋嫨鐨勫簱瀛樻棤娉曞垎閰嶄换浣曟暟閲�");
+            }
+
+            // 濡傛灉鐢ㄦ埛閫夋嫨鐨勫簱瀛樹笉澶燂紝鑷姩鍒嗛厤鍓╀綑閮ㄥ垎
+            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;
+
+            // 鏇存柊鐘舵��
+            UpdateOrderDetailStatus(outboundOrderDetail, remainingNeedQuantity - autoAssignedQuantity);
+
+            List<Dt_LocationInfo> locationInfos = _locationInfoService.GetLocationInfos(outStocks.Select(x => x.LocationCode).ToList());
+
+            return (outStocks, outboundOrderDetail, outStockLockInfos, locationInfos);
+        }
+
+        // 杈呭姪鏂规硶
+        private decimal CalculateAvailableQuantity(Dt_StockInfo stock, string materielCode, string batchNo, string supplyCode)
+        {
+            var relevantDetails = stock.Details
+                .Where(d => d.MaterielCode == materielCode &&
+                           (string.IsNullOrEmpty(batchNo) || d.BatchNo == batchNo) &&
+                           (string.IsNullOrEmpty(supplyCode) || d.SupplyCode == supplyCode))
+                .ToList();
+
+            return relevantDetails.Sum(d => d.StockQuantity - d.OutboundQuantity);
+        }
+
+        private decimal AssignStockQuantity(Dt_StockInfo stock, Dt_OutboundOrderDetail detail, decimal assignQuantity)
+        {
+            decimal remainingAssign = assignQuantity;
+
+            // 鎸夊厛杩涘厛鍑哄垎閰嶅簱瀛樻槑缁�
+            var sorteds = stock.Details
+                .Where(d => d.MaterielCode == detail.MaterielCode &&
+                           (d.StockQuantity - d.OutboundQuantity) > 0);
+               // .OrderBy(d => d.CreateDate);             
+
+            if (!string.IsNullOrEmpty(detail.BatchNo))
+            {
+                sorteds= stock.Details.Where(x => x.BatchNo == detail.BatchNo);
+            }
+
+            var sortedDetails= sorteds.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;
+            }
+
+            return assignQuantity - remainingAssign; // 杩斿洖瀹為檯鍒嗛厤鏁伴噺
+        }
+
+        private Dt_OutStockLockInfo CreateOutStockLockInfo(Dt_OutboundOrder outboundOrder, Dt_OutboundOrderDetail detail,
+            Dt_StockInfo stock, decimal quantity)
+        {
+            var barcode = stock.Details
+                .Where(d => !string.IsNullOrEmpty(d.Barcode))
+                .Select(d => d.Barcode)
+                .FirstOrDefault();
+
+            return _outStockLockInfoService.GetOutStockLockInfo(outboundOrder, detail, stock, quantity, barcode);
+        }
+
+        private List<Dt_OutStockLockInfo> CreateLockInfosForAutoAssign(Dt_OutboundOrder outboundOrder,
+            Dt_OutboundOrderDetail detail, List<Dt_StockInfo> stocks, Dictionary<int, decimal> allocations)
+        {
+            var lockInfos = new List<Dt_OutStockLockInfo>();
+
+            foreach (var stock in stocks.OrderBy(x => x.CreateDate))
+            {
+                if (allocations.TryGetValue(stock.Id, out decimal quantity) && quantity > 0)
+                {
+                    var lockInfo = CreateOutStockLockInfo(outboundOrder, detail, stock, quantity);
+                    lockInfos.Add(lockInfo);
+                }
+            }
+
+            return lockInfos;
+        }
+
+        private void UpdateOrderDetailStatus(Dt_OutboundOrderDetail detail, decimal remainingQuantity)
+        {
+            if (remainingQuantity <= 0)
+            {
+                detail.OrderDetailStatus = OrderDetailStatusEnum.AssignOver.ObjToInt();
+            }
+            else
+            {
+                detail.OrderDetailStatus = OrderDetailStatusEnum.AssignOverPartial.ObjToInt();
+            }
+        }
+
+        private (bool, string) CheckSelectStockDeital(Dt_OutboundOrderDetail outboundOrderDetail, List<StockSelectViewDTO> stockSelectViews)
+        {
+            var needQuantity = outboundOrderDetail.OrderQuantity - outboundOrderDetail.LockQuantity - outboundOrderDetail.MoveQty;
+
+            if (needQuantity <= 0)
+            {
+                return (false, "鍑哄簱鍗曟槑缁嗘棤闇�鍒嗛厤搴撳瓨");
+            }
+
+            // 妫�鏌ユ�婚�夋嫨鏁伴噺鏄惁澶т簬0
+            var totalSelected = stockSelectViews.Sum(x => x.UseableQuantity);
+            if (totalSelected <= 0)
+            {
+                return (false, "鐢ㄦ埛閫夋嫨鐨勫簱瀛樻暟閲忓繀椤诲ぇ浜�0");
+            }
+
+            // 妫�鏌ユ瘡涓墭鐩樼殑鍙敤鏁伴噺
+            foreach (var selection in stockSelectViews)
+            {
+                if (selection.UseableQuantity <= 0)
+                {
+                    return (false, $"鎵樼洏[{selection.PalletCode}]鐨勯�夋嫨鏁伴噺蹇呴』澶т簬0");
+                }
+
+                var stock = _stockService.StockInfoService.GetStockInfoByPalletCode(selection.PalletCode);
+                if (stock == null)
+                {
+                    return (false, $"鎵樼洏[{selection.PalletCode}]涓嶅瓨鍦�");
+                }
+
+                var available = CalculateAvailableQuantity(stock, outboundOrderDetail.MaterielCode,
+                    outboundOrderDetail.BatchNo, outboundOrderDetail.SupplyCode);
+
+                if (available <= 0)
+                {
+                    return (false, $"鎵樼洏[{selection.PalletCode}]娌℃湁鍙敤搴撳瓨");
+                }
+            }
+
+            return (true, "楠岃瘉閫氳繃");
+        }
     }
 }

--
Gitblit v1.9.3