From 5fc251a847ccc0540da8b112ed2bddba846455d8 Mon Sep 17 00:00:00 2001
From: pan <antony1029@163.com>
Date: 星期一, 17 十一月 2025 20:39:49 +0800
Subject: [PATCH] 提交

---
 项目代码/WMS无仓储版/WIDESEA_WMSServer/WIDESEA_OutboundService/OutboundPickingService.cs |  746 +++++++++++++++++++++++++++++++++++++--------------------
 1 files changed, 485 insertions(+), 261 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/OutboundPickingService.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/OutboundPickingService.cs"
index cf875b6..8c52841 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/OutboundPickingService.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/OutboundPickingService.cs"
@@ -1,6 +1,7 @@
 锘縰sing Dm.filter;
 using MailKit.Search;
 using Microsoft.AspNetCore.Http;
+using Microsoft.Extensions.Logging;
 using SqlSugar;
 using System;
 using System.Collections.Generic;
@@ -10,10 +11,12 @@
 using WIDESEA_Common.LocationEnum;
 using WIDESEA_Common.OrderEnum;
 using WIDESEA_Common.StockEnum;
+using WIDESEA_Common.TaskEnum;
 using WIDESEA_Core;
 using WIDESEA_Core.BaseRepository;
 using WIDESEA_Core.BaseServices;
 using WIDESEA_Core.Helper;
+using WIDESEA_DTO.Basic;
 using WIDESEA_DTO.Outbound;
 using WIDESEA_IBasicService;
 using WIDESEA_IOutboundService;
@@ -39,9 +42,26 @@
         private readonly IOutboundOrderService _outboundOrderService;
         private readonly ISplitPackageService _splitPackageService;
         private readonly IRepository<Dt_Task> _taskRepository;
+        private readonly IESSApiService _eSSApiService;
 
 
-        public OutboundPickingService(IRepository<Dt_PickingRecord> BaseDal, IUnitOfWorkManage unitOfWorkManage, IStockInfoService stockInfoService, IStockService stockService, IOutStockLockInfoService outStockLockInfoService, IStockInfoDetailService stockInfoDetailService, ILocationInfoService locationInfoService, IOutboundOrderDetailService outboundOrderDetailService, ISplitPackageService splitPackageService, IOutboundOrderService outboundOrderService, IRepository<Dt_Task> taskRepository) : base(BaseDal)
+        private readonly ILogger<OutboundPickingService> _logger;
+
+        private Dictionary<string, string> stations = new Dictionary<string, string>
+        {
+            {"2-1","2-9" },
+            {"3-1","3-9" },
+
+        };
+
+        private Dictionary<string, string> movestations = new Dictionary<string, string>
+        {
+            {"2-1","2-5" },
+            {"3-1","3-5" },
+
+        };
+
+        public OutboundPickingService(IRepository<Dt_PickingRecord> BaseDal, IUnitOfWorkManage unitOfWorkManage, IStockInfoService stockInfoService, IStockService stockService, IOutStockLockInfoService outStockLockInfoService, IStockInfoDetailService stockInfoDetailService, ILocationInfoService locationInfoService, IOutboundOrderDetailService outboundOrderDetailService, ISplitPackageService splitPackageService, IOutboundOrderService outboundOrderService, IRepository<Dt_Task> taskRepository, IESSApiService eSSApiService, ILogger<OutboundPickingService> logger) : base(BaseDal)
         {
             _unitOfWorkManage = unitOfWorkManage;
             _stockInfoService = stockInfoService;
@@ -53,6 +73,8 @@
             _splitPackageService = splitPackageService;
             _outboundOrderService = outboundOrderService;
             _taskRepository = taskRepository;
+            _eSSApiService = eSSApiService;
+            _logger = logger;
         }
 
 
@@ -117,157 +139,79 @@
             }
         }
 
-        /// <summary>
-        /// 鎵爜鎷i�夌‘璁� 
-        /// </summary>
-        public async Task<WebResponseContent> ConfirmPicking(PickingConfirmRequest request)
-        {
-            try
-            {
-                _unitOfWorkManage.BeginTran();
-
-                // 1. 楠岃瘉鏉$爜鏈夋晥鎬�
-                var stockDetail = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
-                    .Where(x => x.Barcode == request.Barcode && x.MaterielCode == request.MaterielCode)
-                    .FirstAsync();
-
-                if (stockDetail == null)
-                    return WebResponseContent.Instance.Error("鏃犳晥鐨勬潯鐮佹垨鐗╂枡缂栫爜");
-
-                // 2. 妫�鏌ュ簱瀛樺彲鐢ㄦ暟閲�
-                decimal availableQuantity = stockDetail.StockQuantity - stockDetail.OutboundQuantity;
-                if (request.PickQuantity > availableQuantity)
-                    return WebResponseContent.Instance.Error($"鎷i�夋暟閲忚秴杩囧彲鐢ㄥ簱瀛橈紝鍙敤鏁伴噺锛歿availableQuantity}");
-
-                // 3. 鏌ユ壘鐩稿叧鐨勫嚭搴撻攣瀹氫俊鎭紙鏀寔鎷嗗寘鍚庣殑鏂版潯鐮侊級
-                var lockInfo = await FindLockInfoByBarcode(request.OrderDetailId, request.Barcode, request.MaterielCode);
-
-                if (lockInfo == null)
-                    return WebResponseContent.Instance.Error("鏈壘鍒扮浉鍏崇殑鍑哄簱閿佸畾淇℃伅");
-
-                // 4. 妫�鏌ラ攣瀹氭暟閲�
-                decimal remainingLockQuantity = lockInfo.AssignQuantity - lockInfo.PickedQty;
-                if (request.PickQuantity > remainingLockQuantity)
-                    return WebResponseContent.Instance.Error($"鎷i�夋暟閲忚秴杩囬攣瀹氭暟閲忥紝鍓╀綑鍙嫞閫夛細{remainingLockQuantity}");
-
-                // 5. 鏇存柊閿佸畾淇℃伅鐨勫凡鎷i�夋暟閲�
-                lockInfo.PickedQty += request.PickQuantity;
-                await _outStockLockInfoService.Db.Updateable(lockInfo).ExecuteCommandAsync();
-
-                // 6. 鏇存柊搴撳瓨鍑哄簱鏁伴噺 - 瀹為檯鍑忓皯搴撳瓨
-                stockDetail.OutboundQuantity += request.PickQuantity;
-                await _stockInfoService.Db.Updateable(stockDetail).ExecuteCommandAsync();
-
-                // 7. 鏇存柊鍑哄簱鍗曟槑缁�
-                var orderDetail = await _outboundOrderDetailService.Db.Queryable<Dt_OutboundOrderDetail>()
-                    .Where(x => x.Id == request.OrderDetailId)
-                    .FirstAsync();
-
-                orderDetail.OverOutQuantity += request.PickQuantity;
-                orderDetail.LockQuantity -= request.PickQuantity;
-
-                // 妫�鏌ユ槸鍚﹀畬鎴愬嚭搴�
-                if (Math.Abs(orderDetail.OverOutQuantity - orderDetail.OrderQuantity) < 0.001m)
-                {
-                    orderDetail.OrderDetailStatus = (int)OrderDetailStatusEnum.Over;
-                    orderDetail.LockQuantity = 0;
-
-                    // 鏇存柊鐩稿叧鐨勯攣瀹氫俊鎭姸鎬佷负宸插嚭搴�
-                    var relatedLockInfos = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
-                        .Where(x => x.OrderDetailId == request.OrderDetailId &&
-                                   x.Status == (int)OutLockStockStatusEnum.鍑哄簱涓�)
-                        .ToListAsync();
-
-                    foreach (var relatedLock in relatedLockInfos)
-                    {
-                        relatedLock.Status = (int)OutLockStockStatusEnum.宸插嚭搴�;
-                    }
-                    await _outStockLockInfoService.Db.Updateable(relatedLockInfos).ExecuteCommandAsync();
-                }
-
-                await _outboundOrderDetailService.Db.Updateable(orderDetail).ExecuteCommandAsync();
-
-                // 8. 璁板綍鎷i�夊巻鍙�
-                var pickHistory = new Dt_PickingRecord
-                {
-                    OrderDetailId = request.OrderDetailId,
-                    Barcode = request.Barcode,
-                    PickQuantity = request.PickQuantity,
-                    PickTime = DateTime.Now,
-
-                    LocationCode = request.LocationCode,
-                    StockId = stockDetail.StockId
-                };
-                await Db.Insertable(pickHistory).ExecuteCommandAsync();
-
-                _unitOfWorkManage.CommitTran();
-
-                return WebResponseContent.Instance.OK("鎷i�夌‘璁ゆ垚鍔�");
-            }
-            catch (Exception ex)
-            {
-                _unitOfWorkManage.RollbackTran();
-                return WebResponseContent.Instance.Error($"鎷i�夌‘璁ゅけ璐�: {ex.Message}");
-            }
-        }
 
         public async Task<WebResponseContent> ConfirmPicking(string orderNo, string palletCode, string barcode)
         {
             try
             {
                 _unitOfWorkManage.BeginTran();
-                // 1. 楠岃瘉鏉$爜鏈夋晥鎬�
+                var lockInfo = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
+                  .Where(it => it.OrderNo == orderNo &&
+                             it.Status == (int)OutLockStockStatusEnum.鍑哄簱涓� &&
+                             it.PalletCode == palletCode &&
+                             it.CurrentBarcode == barcode)
+                  .FirstAsync();
+
+                if (lockInfo == null)
+                {
+                    var splitBarcode = await _splitPackageService.Db.Queryable<Dt_SplitPackageRecord>()
+                   .Where(it => it.NewBarcode == barcode && it.Status == 1)
+                   .FirstAsync();
+
+                    if (splitBarcode != null)
+                    {
+                        // 閫氳繃鎷嗗寘鏉$爜璁板綍鎵惧埌瀵瑰簲鐨勫嚭搴撻攣瀹氳褰�
+                        lockInfo = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
+                            .Where(it => it.ParentLockId == splitBarcode.OutStockLockInfoId)
+                            .FirstAsync();
+
+                        if (lockInfo == null)
+                            throw new Exception($"鏈壘鍒版媶鍖呮潯鐮亄barcode}瀵瑰簲鐨勫嚭搴撻攣瀹氳褰�");
+                    }
+                    else
+                    {
+                        throw new Exception($"鏉$爜{barcode}涓嶅睘浜庢墭鐩榹palletCode}鎴栦笉瀛樺湪寰呭垎鎷h褰�");
+                    }
+
+                }
+                if (lockInfo.PalletCode != palletCode)
+                    throw new Exception($"鏉$爜{barcode}涓嶅睘浜庢墭鐩榹palletCode}");
+
                 var stockDetail = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
-                        .Where(x => x.Barcode == barcode)
+                        .Where(x => x.Barcode == barcode && x.StockId == lockInfo.StockId)
                         .FirstAsync();
 
                 if (stockDetail == null)
                     return WebResponseContent.Instance.Error("鏃犳晥鐨勬潯鐮佹垨鐗╂枡缂栫爜");
 
-                //// 2. 妫�鏌ュ簱瀛樺彲鐢ㄦ暟閲�
-                //var availableQty = stockDetail.StockQuantity - stockDetail.OutboundQuantity;
-                //if (availableQty <= 0)
-                //    return WebResponseContent.Instance.Error("搴撳瓨鏁伴噺涓嶈冻");
 
-                // 3. 鏌ユ壘鐩稿叧鐨勫嚭搴撹鎯呬俊鎭�
-                var outStockInfo = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
-                    .Where(x => x.OrderNo == orderNo &&
-                               x.PalletCode == palletCode &&
-                               x.CurrentBarcode == barcode &&
-                               x.Status == (int)OutLockStockStatusEnum.鍑哄簱涓� &&
-                               x.AssignQuantity - x.PickedQty > 0)
-                    .FirstAsync();
+                decimal actualQty = lockInfo.AssignQuantity - lockInfo.PickedQty;
 
+                // 4. 鏇存柊搴撳瓨
+                stockDetail.StockQuantity -= actualQty;
+                stockDetail.OutboundQuantity -= actualQty;
+                await _stockInfoDetailService.Db.Updateable(stockDetail).ExecuteCommandAsync();
 
-                if (outStockInfo == null)
-                    return WebResponseContent.Instance.Error("鏈壘鍒板搴旂殑鎷i�変俊鎭垨宸叉嫞閫夊畬鎴�");
+                lockInfo.PickedQty += actualQty;
+                lockInfo.Status = (int)OutLockStockStatusEnum.鎷i�夊畬鎴�;
+                await _outStockLockInfoService.Db.Updateable(lockInfo).ExecuteCommandAsync();
 
-                // 4. 妫�鏌ュ嚭搴撹鎯呴攣瀹氭暟閲�
-                if (outStockInfo.RemainQuantity <= 0)
-                    return WebResponseContent.Instance.Error("璇ユ潯鐮佸凡鏃犲墿浣欏彲鎷i�夋暟閲�");
+                var splitBarcodeRecord = await _splitPackageService.Db.Queryable<Dt_SplitPackageRecord>()
+               .Where(it => it.NewBarcode == barcode)
+               .FirstAsync();
 
-                // 5. 鏇存柊鍑哄簱璇︽儏鐨勫凡鎷i�夋暟閲�
-                outStockInfo.PickedQty = outStockInfo.AssignQuantity;
-                outStockInfo.Status = (int)OutLockStockStatusEnum.宸叉嫞閫�;
-                await _outStockLockInfoService.Db.Updateable(outStockInfo).ExecuteCommandAsync();
-
-                //// 6. 鏇存柊搴撳瓨鍑哄簱鏁伴噺
-                //await _stockInfoDetailService.Db.Updateable<Dt_StockInfoDetail>()
-                //    .SetColumns(x => x.OutboundQuantity == x.OutboundQuantity + outStockInfo.AssignQuantity)
-                //    .Where(x => x.Id == stockDetail.Id)
-                //    .ExecuteCommandAsync();
-
-                // 7. 鏇存柊鍑哄簱鍗曟槑缁�
-                var orderDetail = await _outboundOrderDetailService.Db.Queryable<Dt_OutboundOrderDetail>()
-                    .Where(x => x.Id == outStockInfo.OrderDetailId)
-                    .FirstAsync();
-                if (orderDetail != null)
+                if (splitBarcodeRecord != null)
                 {
-                    orderDetail.OverOutQuantity += outStockInfo.AssignQuantity;
-                    orderDetail.LockQuantity -= outStockInfo.AssignQuantity;
-                    await _outboundOrderDetailService.Db.Updateable(orderDetail).ExecuteCommandAsync();
+                    splitBarcodeRecord.Status = 2;
+                    await _splitPackageService.Db.Updateable(splitBarcodeRecord).ExecuteCommandAsync();
                 }
-                // 8. 妫�鏌ユ槸鍚﹀畬鎴愬嚭搴�
+
+                await _outboundOrderDetailService.Db.Updateable<Dt_OutboundOrderDetail>()
+               .SetColumns(it => it.PickedQty == it.PickedQty + actualQty)
+               .Where(it => it.Id == lockInfo.OrderDetailId)
+               .ExecuteCommandAsync();
+
+
                 await CheckAndUpdateOrderStatus(orderNo);
 
                 //鏌ヨ浠诲姟琛� 
@@ -275,19 +219,19 @@
                 // 9. 璁板綍鎷i�夊巻鍙�
                 var pickingHistory = new Dt_PickingRecord
                 {
-                    FactoryArea = outStockInfo.FactoryArea,
+                    FactoryArea = lockInfo.FactoryArea,
                     TaskNo = task?.TaskNum ?? 0,
                     LocationCode = task?.SourceAddress ?? "",
                     StockId = stockDetail.Id,
                     OrderNo = orderNo,
-                    OrderDetailId = orderDetail?.Id ?? 0,
+                    OrderDetailId = lockInfo.OrderDetailId,
                     PalletCode = palletCode,
                     Barcode = barcode,
-                    MaterielCode = outStockInfo.MaterielCode,
-                    PickQuantity = outStockInfo.AssignQuantity,
+                    MaterielCode = lockInfo.MaterielCode,
+                    PickQuantity = lockInfo.AssignQuantity,
                     PickTime = DateTime.Now,
                     Operator = App.User.UserName,
-                    OutStockLockId = outStockInfo.Id
+                    OutStockLockId = lockInfo.Id
                 };
                 await Db.Insertable(pickingHistory).ExecuteCommandAsync();
 
@@ -327,6 +271,396 @@
                     .ExecuteCommandAsync();
             }
         }
+
+
+        /// <summary>
+        /// 鍥炲簱鎿嶄綔  
+        /// </summary>
+        //public async Task<WebResponseContent> ReturnRemaining(string orderNo, string palletCode, string reason)
+        //{
+        //    try
+        //    {
+        //        // 1. 鑾峰彇鎵�鏈夋湭鍒嗘嫞鐨勫嚭搴撻攣瀹氳褰曪紝鍖呮嫭鎷嗗寘浜х敓鐨勮褰�
+        //        var remainingLocks = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
+        //            .Where(it => it.OrderNo == orderNo && it.Status == 1)
+        //            .ToListAsync();
+
+        //        if (!remainingLocks.Any())
+        //        {
+        //            return WebResponseContent.Instance.Error("娌℃湁闇�瑕佸洖搴撶殑鍓╀綑璐х墿");
+        //        }
+        //        var tasks = new List<Dt_Task>();
+        //        // 鎸夋墭鐩樺垎缁�
+        //        var palletGroups = remainingLocks.GroupBy(x => x.PalletCode);
+        //        //鏌ヨ浠诲姟琛� 
+        //        var task = _taskRepository.QueryData(x => x.TaskNum == remainingLocks.First().TaskNum).FirstOrDefault();
+        //        foreach (var group in palletGroups)
+        //        {
+        //            if (group.Key == palletCode)
+        //            {
+        //                var totalReturnQty = group.Sum(x => x.AssignQuantity - x.PickedQty);
+
+        //                if (totalReturnQty <= 0) continue;
+
+        //                // 鍒嗛厤鏂拌揣浣�
+        //                var newLocation = _locationInfoService.AssignLocation();
+
+        //                // 鏇存柊鍑哄簱閿佸畾璁板綍鐘舵��
+        //                var lockIds = group.Where(x => x.PalletCode == palletCode).Select(x => x.Id).ToList();
+        //                await _outStockLockInfoService.Db.Updateable<Dt_OutStockLockInfo>()
+        //                    .SetColumns(it => new Dt_OutStockLockInfo { Status = OutLockStockStatusEnum.鍥炲簱涓�.ObjToInt() })
+        //                    .Where(it => lockIds.Contains(it.Id))
+        //                    .ExecuteCommandAsync();
+
+        //                // 鏇存柊鎷嗗寘鏉$爜璁板綍鐘舵��
+        //                var splitBarcodes = await _splitPackageService.Db.Queryable<Dt_SplitPackageRecord>()
+        //                    .Where(it => lockIds.Contains(it.OutStockLockInfoId))
+        //                    .ToListAsync();
+
+        //                foreach (var splitBarcode in splitBarcodes)
+        //                {
+        //                    splitBarcode.Status = 3;
+        //                    await _splitPackageService.Db.Updateable(splitBarcode).ExecuteCommandAsync();
+        //                }
+
+        //                foreach (var lockInfo in group)
+        //                {
+        //                    if (lockInfo.PalletCode == palletCode)
+        //                    {
+        //                        decimal returnQty = lockInfo.AssignQuantity - lockInfo.PickedQty;
+
+        //                        // 妫�鏌ュ簱瀛樿褰曟槸鍚﹀瓨鍦�
+        //                        var existingStock = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
+        //                            .Where(it => it.Barcode == lockInfo.CurrentBarcode && it.StockId == lockInfo.StockId)
+        //                            .FirstAsync();
+
+        //                        if (existingStock != null)
+        //                        {
+        //                            // 搴撳瓨璁板綍瀛樺湪锛屾仮澶嶉攣瀹氭暟閲�
+        //                            await _stockInfoDetailService.Db.Updateable<Dt_StockInfoDetail>()
+        //                                .SetColumns(it => new Dt_StockInfoDetail
+        //                                {
+        //                                    OutboundQuantity = it.OutboundQuantity - returnQty
+        //                                })
+        //                                .Where(it => it.Barcode == lockInfo.CurrentBarcode && it.StockId == lockInfo.StockId)
+        //                                .ExecuteCommandAsync();
+        //                        }
+        //                        else
+        //                        {
+        //                            // 搴撳瓨璁板綍涓嶅瓨鍦紙鍙兘鏄媶鍖呬骇鐢熺殑鏂版潯鐮侊級锛屽垱寤烘柊鐨勫簱瀛樿褰�
+        //                            var newStockDetail = new Dt_StockInfoDetail
+        //                            {
+        //                                StockId = lockInfo.StockId,
+        //                                MaterielCode = lockInfo.MaterielCode,
+        //                                OrderNo = lockInfo.OrderNo,
+        //                                BatchNo = lockInfo.BatchNo,
+        //                                StockQuantity = returnQty, // 瀹為檯搴撳瓨鏁伴噺
+        //                                OutboundQuantity = 0, // 鍥炲簱鍚庝笉鍐嶉攣瀹�
+        //                                Barcode = lockInfo.CurrentBarcode,
+        //                                InboundOrderRowNo = "0",
+        //                                Status = StockStatusEmun.鍏ュ簱纭.ObjToInt(),
+
+        //                            };
+        //                            await _stockInfoDetailService.Db.Insertable(newStockDetail).ExecuteCommandAsync();
+        //                        }
+        //                    }
+        //                }
+
+
+        //                Dt_Task newtask = new()
+        //                {
+        //                    CurrentAddress = stations[task.TargetAddress],
+        //                    Grade = 0,
+        //                    PalletCode = palletCode,
+        //                    NextAddress = "",
+        //                    OrderNo= task.OrderNo,
+        //                    Roadway = newLocation.RoadwayNo,
+        //                    SourceAddress = stations[task.TargetAddress],
+        //                    TargetAddress = newLocation.LocationCode,
+        //                    TaskStatus = TaskStatusEnum.New.ObjToInt(),
+        //                    TaskType = TaskTypeEnum.InPick.ObjToInt(),
+        //                    // TaskNum = BaseDal.GetTaskNum(nameof(SequenceEnum.SeqTaskNum)),
+        //                    PalletType = task.PalletType,
+        //                    WarehouseId = task.WarehouseId,
+        //                };
+        //                tasks.Add(newtask);
+
+        //            }
+        //        }
+        //        try
+        //        {
+        //            await _taskRepository.Db.Insertable(tasks).ExecuteCommandAsync();
+        //            //鍒犻櫎 鍑哄簱鐨�  task
+
+
+        //            //缁� ess  娴佸姩淇″彿  鍜屽垱寤轰换鍔�
+
+
+        //        }
+        //        catch (Exception ex)
+        //        {
+
+        //        }
+
+
+
+
+        //        return WebResponseContent.Instance.OK();
+        //    }
+        //    catch (Exception ex)
+        //    {
+        //        return WebResponseContent.Instance.Error($"鍥炲簱鎿嶄綔澶辫触: {ex.Message}");
+        //    }
+        //}
+
+        public async Task<WebResponseContent> ReturnRemaining(string orderNo, string palletCode, string reason)
+        {
+            try
+            {
+                // 1. 鑾峰彇鎵�鏈夋湭鍒嗘嫞鐨勫嚭搴撻攣瀹氳褰曪紝鍖呮嫭鎷嗗寘浜х敓鐨勮褰�
+                var remainingLocks = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
+                    .Where(it => it.OrderNo == orderNo && it.Status == 1)
+                    .ToListAsync();
+
+                var stockinfo = _stockInfoService.Db.Queryable<Dt_StockInfo>().First(x => x.PalletCode == palletCode);
+
+                // 2. 妫�鏌ユ墭鐩樹笂鏄惁鏈夊叾浠栭潪鍑哄簱璐х墿锛堝簱瀛樿揣鐗╋級
+                var palletStockGoods = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
+                    .Where(it => it.StockId == stockinfo.Id && it.Status == StockStatusEmun.鍏ュ簱纭.ObjToInt())
+                    .Where(it => it.OutboundQuantity == 0 || it.OutboundQuantity < it.StockQuantity) // 鏈畬鍏ㄥ嚭搴撶殑
+                    .ToListAsync();
+
+                // 3. 濡傛灉娌℃湁闇�瑕佸洖搴撶殑璐х墿锛堟棦鏃犳湭鍒嗘嫞鍑哄簱璐х墿锛屼篃鏃犲叾浠栧簱瀛樿揣鐗╋級
+                if (!remainingLocks.Any() && !palletStockGoods.Any())
+                {
+                    return WebResponseContent.Instance.Error("娌℃湁闇�瑕佸洖搴撶殑鍓╀綑璐х墿");
+                }
+
+                var tasks = new List<Dt_Task>();
+
+                // 鏌ヨ浠诲姟琛�
+                var task = remainingLocks.Any()
+                    ? _taskRepository.QueryData(x => x.TaskNum == remainingLocks.First().TaskNum).FirstOrDefault()
+                    : _taskRepository.QueryData(x => x.PalletCode == palletCode).FirstOrDefault();
+
+                if (task == null)
+                {
+                    return WebResponseContent.Instance.Error("鏈壘鍒板搴旂殑浠诲姟淇℃伅");
+                }
+                var firstlocation = _locationInfoService.Db.Queryable<Dt_LocationInfo>().First(x => x.LocationCode == task.SourceAddress);
+                decimal totalReturnQty = 0;
+                var hasRemainingLocks = remainingLocks.Any(x => x.PalletCode == palletCode);
+
+                // 鎯呭喌1锛氬鐞嗘湭鍒嗘嫞鐨勫嚭搴撻攣瀹氳褰�
+                if (hasRemainingLocks)
+                {
+                    var palletLocks = remainingLocks.Where(x => x.PalletCode == palletCode).ToList();
+                    totalReturnQty = palletLocks.Sum(x => x.AssignQuantity - x.PickedQty);
+
+                    if (totalReturnQty > 0)
+                    {
+                        // 鍒嗛厤鏂拌揣浣�
+                        var newLocation = _locationInfoService.AssignLocation(firstlocation.LocationType);
+
+                        // 鏇存柊鍑哄簱閿佸畾璁板綍鐘舵��
+                        var lockIds = palletLocks.Select(x => x.Id).ToList();
+                        await _outStockLockInfoService.Db.Updateable<Dt_OutStockLockInfo>()
+                            .SetColumns(it => new Dt_OutStockLockInfo { Status = OutLockStockStatusEnum.鍥炲簱涓�.ObjToInt() })
+                            .Where(it => lockIds.Contains(it.Id))
+                            .ExecuteCommandAsync();
+
+                        // 鏇存柊鎷嗗寘鏉$爜璁板綍鐘舵��
+                        var splitBarcodes = await _splitPackageService.Db.Queryable<Dt_SplitPackageRecord>()
+                            .Where(it => lockIds.Contains(it.OutStockLockInfoId))
+                            .ToListAsync();
+
+                        foreach (var splitBarcode in splitBarcodes)
+                        {
+                            splitBarcode.Status = 3;
+                            await _splitPackageService.Db.Updateable(splitBarcode).ExecuteCommandAsync();
+                        }
+
+                        // 澶勭悊搴撳瓨璁板綍
+                        foreach (var lockInfo in palletLocks)
+                        {
+                            decimal returnQty = lockInfo.AssignQuantity - lockInfo.PickedQty;
+
+                            // 妫�鏌ュ簱瀛樿褰曟槸鍚﹀瓨鍦�
+                            var existingStock = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
+                                .Where(it => it.Barcode == lockInfo.CurrentBarcode && it.StockId == lockInfo.StockId)
+                                .FirstAsync();
+
+                            if (existingStock != null)
+                            {
+                                // 搴撳瓨璁板綍瀛樺湪锛屾仮澶嶉攣瀹氭暟閲�
+                                await _stockInfoDetailService.Db.Updateable<Dt_StockInfoDetail>()
+                                    .SetColumns(it => new Dt_StockInfoDetail
+                                    {
+                                        OutboundQuantity = it.OutboundQuantity - returnQty
+                                    })
+                                    .Where(it => it.Barcode == lockInfo.CurrentBarcode && it.StockId == lockInfo.StockId)
+                                    .ExecuteCommandAsync();
+                            }
+                            else
+                            {
+                                // 搴撳瓨璁板綍涓嶅瓨鍦紙鍙兘鏄媶鍖呬骇鐢熺殑鏂版潯鐮侊級锛屽垱寤烘柊鐨勫簱瀛樿褰�
+                                var newStockDetail = new Dt_StockInfoDetail
+                                {
+                                    StockId = lockInfo.StockId,
+                                    MaterielCode = lockInfo.MaterielCode,
+                                    OrderNo = lockInfo.OrderNo,
+                                    BatchNo = lockInfo.BatchNo,
+                                    StockQuantity = returnQty,
+                                    OutboundQuantity = 0,
+                                    Barcode = lockInfo.CurrentBarcode,
+                                    InboundOrderRowNo = "0",
+                                    Status = StockStatusEmun.鍏ュ簱纭.ObjToInt(),
+
+                                };
+                                await _stockInfoDetailService.Db.Insertable(newStockDetail).ExecuteCommandAsync();
+                            }
+                        }
+
+                        // 鍒涘缓鍥炲簱浠诲姟
+                        CreateReturnTask(tasks, task, palletCode, newLocation);
+                    }
+                }
+
+                // 鎯呭喌2锛氬嚭搴撹揣鐗╁凡鍒嗘嫞瀹岋紝浣嗘墭鐩樹笂杩樻湁鍏朵粬搴撳瓨璐х墿闇�瑕佸洖搴�
+                if (!hasRemainingLocks && palletStockGoods.Any())
+                {
+                    // 鍒嗛厤鏂拌揣浣�
+                    var newLocation = _locationInfoService.AssignLocation(firstlocation.LocationType);
+
+                    // 鍒涘缓鍥炲簱浠诲姟
+                    CreateReturnTask(tasks, task, palletCode, newLocation);
+
+                    totalReturnQty = palletStockGoods.Sum(x => x.StockQuantity - x.OutboundQuantity);
+                }
+
+                // 淇濆瓨浠诲姟
+                if (tasks.Any())
+                {
+                    try
+                    {
+                        await _taskRepository.Db.Insertable(tasks).ExecuteCommandAsync();
+                        var targetAddress = task.TargetAddress;
+                        _taskRepository.DeleteData(task);
+                        // 缁� ESS 娴佸姩淇″彿鍜屽垱寤轰换鍔�
+                        try
+                        {
+                            var result = await _eSSApiService.MoveContainerAsync(new WIDESEA_DTO.Basic.MoveContainerRequest
+                            {
+                                slotCode = movestations[targetAddress],
+                                containerCode = palletCode
+                            });
+                            if (result)
+                            {
+                                TaskModel esstask = new TaskModel()
+                                {
+                                    taskType = "putaway",
+                                    taskGroupCode = "",
+                                    groupPriority = 0,
+                                    tasks = new List<TasksType>
+                                    {
+                                        new()
+                                        {
+                                            taskCode = tasks.First().TaskNum.ToString(),
+                                            taskPriority = 0,
+                                            taskDescribe = new TaskDescribeType {
+                                                containerCode = palletCode,
+                                                containerType = "CT_KUBOT_STANDARD",
+                                                fromLocationCode = stations.GetValueOrDefault(targetAddress) ?? "",
+                                                toStationCode = "",
+                                                toLocationCode = tasks.First().TargetAddress,
+                                                deadline = 0, storageTag = ""
+                                            }
+                                        }
+                                    }
+                                };
+
+
+                                var resulttask = await _eSSApiService.CreateTaskAsync(esstask);
+
+                                _logger.LogInformation("ReturnRemaining 鍒涘缓浠诲姟杩斿洖:  " + resulttask);
+                            }
+                        }
+                        catch (Exception ex)
+                        {
+                            _logger.LogInformation("ReturnRemaining 鍒涘缓浠诲姟杩斿洖 catch err:  " + ex.Message);
+
+                        }
+
+
+                        return WebResponseContent.Instance.OK($"鍥炲簱鎿嶄綔鎴愬姛锛屽叡鍥炲簱鏁伴噺锛歿totalReturnQty}");
+                    }
+                    catch (Exception ex)
+                    {
+                        return WebResponseContent.Instance.Error($"鍒涘缓鍥炲簱浠诲姟澶辫触: {ex.Message}");
+                    }
+                }
+
+                return WebResponseContent.Instance.Error("鏈垱寤轰换浣曞洖搴撲换鍔�");
+            }
+            catch (Exception ex)
+            {
+                return WebResponseContent.Instance.Error($"鍥炲簱鎿嶄綔澶辫触: {ex.Message}");
+            }
+        }
+
+        /// <summary>
+        /// 鍒涘缓鍥炲簱浠诲姟
+        /// </summary>
+        private void CreateReturnTask(List<Dt_Task> tasks, Dt_Task originalTask, string palletCode, Dt_LocationInfo newLocation)
+        {
+            Dt_Task newTask = new()
+            {
+                CurrentAddress = stations[originalTask.TargetAddress],
+                Grade = 0,
+                PalletCode = palletCode,
+                NextAddress = "",
+                OrderNo = originalTask.OrderNo,
+                Roadway = newLocation.RoadwayNo,
+                SourceAddress = stations[originalTask.TargetAddress],
+                TargetAddress = newLocation.LocationCode,
+                TaskStatus = TaskStatusEnum.New.ObjToInt(),
+                TaskType = TaskTypeEnum.InPick.ObjToInt(),
+                PalletType = originalTask.PalletType,
+                WarehouseId = originalTask.WarehouseId,
+
+            };
+            tasks.Add(newTask);
+        }
+
+        /// <summary>
+        /// 妫�鏌ユ墭鐩樻槸鍚﹂渶瑕佸洖搴撶殑杈呭姪鏂规硶
+        /// </summary>
+        public async Task<bool> CheckPalletNeedReturn(string orderNo, string palletCode)
+        {
+            // 1. 妫�鏌ユ槸鍚︽湁鏈垎鎷g殑鍑哄簱璁板綍
+            var hasUnpickedLocks = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
+                .Where(it => it.OrderNo == orderNo && it.PalletCode == palletCode && it.Status == 1)
+                .AnyAsync();
+
+            if (hasUnpickedLocks)
+                return true;
+
+            // 2. 妫�鏌ュ嚭搴撴槸鍚﹀凡瀹屾垚浣嗘墭鐩樿繕鏈夊簱瀛樿揣鐗�
+            var outboundFinished = !await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
+                .Where(it => it.PalletCode == palletCode && it.Status == 1)
+                .AnyAsync();
+
+            var stockinfo = _stockInfoService.Db.Queryable<Dt_StockInfo>().First(x => x.PalletCode == palletCode);
+
+
+            var hasRemainingGoods = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
+                .Where(it => it.StockId == stockinfo.Id && it.Status == StockStatusEmun.鍏ュ簱纭.ObjToInt())
+                .Where(it => it.OutboundQuantity == 0 || it.OutboundQuantity < it.StockQuantity)
+                .AnyAsync();
+
+            return outboundFinished && hasRemainingGoods;
+        }
+
         // 鍙栨秷鎷i�夊姛鑳�
         public async Task<WebResponseContent> CancelPicking(string orderNo, string palletCode, string barcode)
         {
@@ -338,7 +672,7 @@
                         .Where(x => x.OrderNo == orderNo &&
                                    x.PalletCode == palletCode &&
                                    x.CurrentBarcode == barcode &&
-                                   x.Status == 2)
+                                   x.Status == 6)
                         .FirstAsync();
 
                 if (outStockInfo == null)
@@ -349,11 +683,15 @@
                 outStockInfo.Status = 1;
                 await _outStockLockInfoService.Db.Updateable(outStockInfo).ExecuteCommandAsync();
 
-                //// 杩樺師搴撳瓨鍑哄簱鏁伴噺
-                //await _stockInfoDetailService.Db.Updateable<Dt_StockInfoDetail>()
-                //        .SetColumns(x => x.OutboundQuantity == x.OutboundQuantity - outStockInfo.AssignQuantity)
-                //        .Where(x => x.Barcode == barcode)
-                //        .ExecuteCommandAsync();
+
+                var stockDetail = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
+                       .Where(x => x.Barcode == barcode && x.StockId == outStockInfo.StockId)
+                       .FirstAsync();
+           
+                stockDetail.StockQuantity += outStockInfo.AssignQuantity;
+                stockDetail.OutboundQuantity += outStockInfo.AssignQuantity;
+                await _stockInfoDetailService.Db.Updateable(stockDetail).ExecuteCommandAsync();
+         
 
                 // 杩樺師鍑哄簱鍗曟槑缁�
                 var orderDetail = await _outboundOrderDetailService.Db.Queryable<Dt_OutboundOrderDetail>()
@@ -377,19 +715,6 @@
                 return WebResponseContent.Instance.Error($"鍙栨秷鎷i�夊け璐ワ細{ex.Message}");
             }
         }
-        /// <summary>
-        /// 鏍规嵁鏉$爜鏌ユ壘閿佸畾淇℃伅
-        /// </summary>
-        private async Task<Dt_OutStockLockInfo> FindLockInfoByBarcode(int orderDetailId, string barcode, string materielCode)
-        {
-            return await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
-                .Where(x => x.OrderDetailId == orderDetailId &&
-                           x.MaterielCode == materielCode &&
-                           x.CurrentBarcode == barcode &&
-                           x.Status == (int)OutLockStockStatusEnum.鍑哄簱涓� &&
-                           x.AssignQuantity > x.PickedQty)
-                .FirstAsync();
-        }
 
         // 鑾峰彇鏈嫞閫夊垪琛�
         public async Task<List<Dt_OutStockLockInfo>> GetUnpickedList(string orderNo, string palletCode)
@@ -408,36 +733,17 @@
             var list = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
                 .Where(x => x.OrderNo == orderNo &&
                            x.PalletCode == palletCode &&
-                           x.Status == 2)
+                           x.Status == 6)
                 .ToListAsync();
             return list;
         }
-
-        public async Task<object> GetPickingSummary(string orderNo, string palletCode)
-        {
-            var summary = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
-                .Where(x => x.OrderNo == orderNo &&
-                           x.PalletCode == palletCode && x.Status == 1)
-                .GroupBy(x => new { x.PalletCode, x.MaterielCode })
-                .Select(x => new
-                {
-                    PalletCode = x.PalletCode,
-                    MaterielCode = x.MaterielCode,
-                    UnpickedCount = SqlFunc.AggregateCount(x.Id),
-                    UnpickedQuantity = SqlFunc.AggregateSum(x.AssignQuantity) - SqlFunc.AggregateSum(x.PickedQty)
-                })
-                .FirstAsync();
-
-            return summary;
-        }
-
         // 鑾峰彇鎷i�夋眹鎬�
         public async Task<object> GetPickingSummary(ConfirmPickingDto dto)
         {
             var picked = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
              .WhereIF(!string.IsNullOrEmpty(dto.OrderNo), x => x.OrderNo == dto.OrderNo)
              .WhereIF(!string.IsNullOrEmpty(dto.PalletCode), x => x.PalletCode == dto.PalletCode)
-             .Where(x => x.Status == 2)
+             .Where(x => x.Status == 6)
              .GroupBy(x => new { x.PalletCode, x.MaterielCode })
              .Select(x => new SummaryPickingDto
              {
@@ -489,88 +795,6 @@
                 .ToListAsync();
         }
 
-        public async Task GetPalletPickingSummary(string orderNo, string palletCode)
-        {
-            var summary = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
-                .Where(x => x.OrderNo == orderNo && x.PalletCode == palletCode)
-                .GroupBy(x => new { x.PalletCode, x.Status })
-                .Select(x => new
-                {
-                    PalletCode = x.PalletCode,
-                    Status = x.Status,
-                    TotalAssignQty = SqlFunc.AggregateSum(x.AssignQuantity),
-                    TotalPickedQty = SqlFunc.AggregateSum(x.PickedQty)
-                })
-                .ToListAsync();
-
-            //   return summary;
-        }
-
-
-
-        /// <summary>
-        /// 鎾ら攢鎷i��
-        /// </summary>
-        public async Task<WebResponseContent> CancelPicking(CancelPickingRequest request)
-        {
-            // 瀹炵幇鎾ら攢鎷i�夌殑閫昏緫锛岄渶瑕侊細
-            // 1. 鎭㈠搴撳瓨鍑哄簱鏁伴噺
-            // 2. 鎭㈠閿佸畾淇℃伅鐨勫凡鎷i�夋暟閲�
-            // 3. 鎭㈠鍑哄簱鍗曟槑缁嗙殑宸插嚭鏁伴噺鍜岄攣瀹氭暟閲�
-            // 4. 鍒犻櫎鎴栨爣璁版嫞閫夊巻鍙茶褰�
-            // 娉ㄦ剰锛氳繖閲岄渶瑕佷簨鍔″鐞�
-            try
-            {
-                _unitOfWorkManage.BeginTran();
-
-                var pickHistory = await Db.Queryable<Dt_PickingRecord>()
-                    .Where(x => x.Id == request.PickingHistoryId)
-                    .FirstAsync();
-
-                if (pickHistory == null)
-                    return WebResponseContent.Instance.Error("鏈壘鍒版嫞閫夎褰�");
-
-                // 鎭㈠搴撳瓨
-                var stockDetail = await _stockInfoService.Db.Queryable<Dt_StockInfoDetail>()
-                    .Where(x => x.Barcode == pickHistory.Barcode && x.StockId == pickHistory.StockId)
-                    .FirstAsync();
-                if (stockDetail != null)
-                {
-                    stockDetail.OutboundQuantity -= pickHistory.PickQuantity;
-                    await _stockInfoService.Db.Updateable(stockDetail).ExecuteCommandAsync();
-                }
-                // 鎭㈠閿佸畾淇℃伅
-                var lockInfo = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
-                    .Where(x => x.OrderDetailId == pickHistory.OrderDetailId && x.StockId == pickHistory.StockId)
-                    .FirstAsync();
-                lockInfo.PickedQty -= pickHistory.PickQuantity;
-                await _outStockLockInfoService.Db.Updateable(lockInfo).ExecuteCommandAsync();
-
-                // 鎭㈠鍑哄簱鍗曟槑缁�
-                var orderDetail = await _outboundOrderDetailService.Db.Queryable<Dt_OutboundOrderDetail>()
-                    .Where(x => x.Id == pickHistory.OrderDetailId)
-                    .FirstAsync();
-                orderDetail.OverOutQuantity -= pickHistory.PickQuantity;
-                orderDetail.LockQuantity += pickHistory.PickQuantity;
-                if (orderDetail.OverOutQuantity < orderDetail.OrderQuantity)
-                {
-                    orderDetail.OrderDetailStatus = orderDetail.LockQuantity > 0 ?
-                        (int)OrderDetailStatusEnum.Outbound : (int)OrderDetailStatusEnum.AssignOverPartial;
-                }
-                await _outboundOrderDetailService.Db.Updateable(orderDetail).ExecuteCommandAsync();
-
-                // 鍒犻櫎鎷i�夊巻鍙茶褰�
-                await Db.Deleteable<Dt_PickingRecord>().Where(x => x.Id == request.PickingHistoryId).ExecuteCommandAsync();
-
-                _unitOfWorkManage.CommitTran();
-                return WebResponseContent.Instance.OK("鎾ら攢鎴愬姛");
-            }
-            catch (Exception ex)
-            {
-                _unitOfWorkManage.RollbackTran();
-                return WebResponseContent.Instance.Error($"鎾ら攢澶辫触: {ex.Message}");
-            }
-        }
 
         /// <summary>
         /// 鑾峰彇鎵樼洏鐨勫嚭搴撶姸鎬佷俊鎭�
@@ -687,7 +911,7 @@
                     {
                         orderDetail.OverOutQuantity = item.TotalQuantity;
                         orderDetail.LockQuantity = 0;
-                        orderDetail.OrderDetailStatus = (int)OrderDetailStatusEnum.Over;                      
+                        orderDetail.OrderDetailStatus = (int)OrderDetailStatusEnum.Over;
                         await _outboundOrderDetailService.Db.Updateable(orderDetail).ExecuteCommandAsync();
                     }
                 }

--
Gitblit v1.9.3