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

---
 项目代码/WMS无仓储版/WIDESEA_WMSServer/WIDESEA_OutboundService/OutboundPickingService.cs |  654 +++++++++++++++++++++++++++++++++++++++++++++++++++--------
 1 files changed, 566 insertions(+), 88 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 fafc2a8..159cba4 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,4 +1,7 @@
-锘縰sing Microsoft.AspNetCore.Http;
+锘縰sing Dm.filter;
+using MailKit.Search;
+using Microsoft.AspNetCore.Http;
+using Microsoft.Extensions.Logging;
 using SqlSugar;
 using System;
 using System.Collections.Generic;
@@ -8,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;
@@ -36,9 +41,27 @@
         private readonly IOutboundOrderDetailService _outboundOrderDetailService;
         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) : 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;
@@ -49,6 +72,9 @@
             _outboundOrderDetailService = outboundOrderDetailService;
             _splitPackageService = splitPackageService;
             _outboundOrderService = outboundOrderService;
+            _taskRepository = taskRepository;
+            _eSSApiService = eSSApiService;
+            _logger = logger;
         }
 
 
@@ -114,8 +140,7 @@
         }
 
         /// <summary>
-        /// 鎵爜鎷i�夌‘璁� - 绠�鍖栫増鏈�
-        /// 鍙鐞嗗疄闄呮嫞閫夌殑搴撳瓨鎵e噺
+        /// 鎵爜鎷i�夌‘璁� 
         /// </summary>
         public async Task<WebResponseContent> ConfirmPicking(PickingConfirmRequest request)
         {
@@ -213,68 +238,93 @@
             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 == 0 &&
-                               x.RemainQuantity > 0)
-                    .FirstAsync();
+                decimal actualQty = lockInfo.AssignQuantity - lockInfo.PickedQty;
 
-                if (outStockInfo == null)
-                    return WebResponseContent.Instance.Error("鏈壘鍒板搴旂殑鎷i�変俊鎭垨宸叉嫞閫夊畬鎴�");
+                // 4. 鏇存柊搴撳瓨
+                stockDetail.StockQuantity -= actualQty;
+                stockDetail.OutboundQuantity -= actualQty;
+                await _stockInfoDetailService.Db.Updateable(stockDetail).ExecuteCommandAsync();
 
-                // 4. 妫�鏌ュ嚭搴撹鎯呴攣瀹氭暟閲�
-                if (outStockInfo.RemainQuantity <= 0)
-                    return WebResponseContent.Instance.Error("璇ユ潯鐮佸凡鏃犲墿浣欏彲鎷i�夋暟閲�");
+                lockInfo.PickedQty += actualQty;
+                lockInfo.Status = (int)OutLockStockStatusEnum.鎷i�夊畬鎴�;
+                await _outStockLockInfoService.Db.Updateable(lockInfo).ExecuteCommandAsync();
 
-                // 5. 鏇存柊鍑哄簱璇︽儏鐨勫凡鎷i�夋暟閲�
-                outStockInfo.PickedQty = outStockInfo.AssignQuantity;
-                outStockInfo.Status = 1;
-                await _outStockLockInfoService.Db.Updateable(outStockInfo).ExecuteCommandAsync();
+                var splitBarcodeRecord = await _splitPackageService.Db.Queryable<Dt_SplitPackageRecord>()
+               .Where(it => it.NewBarcode == barcode)
+               .FirstAsync();
 
-                // 6. 鏇存柊搴撳瓨鍑哄簱鏁伴噺
-                await _stockInfoDetailService.Db.Updateable<Dt_StockInfoDetail>()
-                    .SetColumns(x => x.OutboundQuantity == x.OutboundQuantity + outStockInfo.AssignQuantity)
-                    .Where(x => x.Id == stockDetail.Id)
-                    .ExecuteCommandAsync();
+                if (splitBarcodeRecord != null)
+                {
+                    splitBarcodeRecord.Status = 2;
+                    await _splitPackageService.Db.Updateable(splitBarcodeRecord).ExecuteCommandAsync();
+                }
 
-                // 7. 鏇存柊鍑哄簱鍗曟槑缁�
-                var orderDetail = await _outboundOrderDetailService.Db.Queryable<Dt_OutboundOrderDetail>()
-                    .Where(x => x.Id == outStockInfo.OrderDetailId)
-                    .FirstAsync();
+                await _outboundOrderDetailService.Db.Updateable<Dt_OutboundOrderDetail>()
+               .SetColumns(it => it.PickedQty == it.PickedQty + actualQty)
+               .Where(it => it.Id == lockInfo.OrderDetailId)
+               .ExecuteCommandAsync();
 
-                orderDetail.OverOutQuantity += outStockInfo.AssignQuantity;
-                await _outboundOrderDetailService.Db.Updateable(orderDetail).ExecuteCommandAsync();
 
-                // 8. 妫�鏌ユ槸鍚﹀畬鎴愬嚭搴�
                 await CheckAndUpdateOrderStatus(orderNo);
 
+                //鏌ヨ浠诲姟琛� 
+                var task = _taskRepository.QueryData(x => x.OrderNo == orderNo && x.PalletCode == palletCode).FirstOrDefault();
                 // 9. 璁板綍鎷i�夊巻鍙�
                 var pickingHistory = new Dt_PickingRecord
                 {
-
+                    FactoryArea = lockInfo.FactoryArea,
+                    TaskNo = task?.TaskNum ?? 0,
+                    LocationCode = task?.SourceAddress ?? "",
+                    StockId = stockDetail.Id,
                     OrderNo = orderNo,
+                    OrderDetailId = lockInfo.OrderDetailId,
                     PalletCode = palletCode,
                     Barcode = barcode,
-                    MaterielCode = outStockInfo.MaterielCode,
-                    PickQuantity = outStockInfo.AssignQuantity,
+                    MaterielCode = lockInfo.MaterielCode,
+                    PickQuantity = lockInfo.AssignQuantity,
                     PickTime = DateTime.Now,
-                    OutStockLockId = outStockInfo.Id
+                    Operator = App.User.UserName,
+                    OutStockLockId = lockInfo.Id
                 };
                 await Db.Insertable(pickingHistory).ExecuteCommandAsync();
 
@@ -314,6 +364,395 @@
                     .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();
+
+                        // 缁� ESS 娴佸姩淇″彿鍜屽垱寤轰换鍔�
+                        try
+                        {
+                            var result = await _eSSApiService.MoveContainerAsync(new WIDESEA_DTO.Basic.MoveContainerRequest
+                            {
+                                slotCode = movestations[task.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(task.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)
         {
@@ -325,7 +764,7 @@
                         .Where(x => x.OrderNo == orderNo &&
                                    x.PalletCode == palletCode &&
                                    x.CurrentBarcode == barcode &&
-                                   x.Status == 1)
+                                   x.Status == 2)
                         .FirstAsync();
 
                 if (outStockInfo == null)
@@ -333,14 +772,14 @@
 
                 // 杩樺師鍑哄簱璇︽儏鐘舵��
                 outStockInfo.PickedQty = 0;
-                outStockInfo.Status = 0;
+                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();
+                //// 杩樺師搴撳瓨鍑哄簱鏁伴噺
+                //await _stockInfoDetailService.Db.Updateable<Dt_StockInfoDetail>()
+                //        .SetColumns(x => x.OutboundQuantity == x.OutboundQuantity - outStockInfo.AssignQuantity)
+                //        .Where(x => x.Barcode == barcode)
+                //        .ExecuteCommandAsync();
 
                 // 杩樺師鍑哄簱鍗曟槑缁�
                 var orderDetail = await _outboundOrderDetailService.Db.Queryable<Dt_OutboundOrderDetail>()
@@ -384,10 +823,9 @@
             var list = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
                 .Where(x => x.OrderNo == orderNo &&
                            x.PalletCode == palletCode &&
-                           x.Status == 0 &&
-                       x.RemainQuantity > 0)
+                           x.Status == 1)
                 .ToListAsync();
-            return list;
+            return list.Where(x => x.RemainQuantity > 0).ToList();
         }
 
         // 鑾峰彇宸叉嫞閫夊垪琛�
@@ -396,26 +834,49 @@
             var list = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
                 .Where(x => x.OrderNo == orderNo &&
                            x.PalletCode == palletCode &&
-                           x.Status == 1)
+                           x.Status == 6)
                 .ToListAsync();
             return list;
         }
         // 鑾峰彇鎷i�夋眹鎬�
-        public async Task<object> GetPickingSummary(string orderNo)
+        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 == 6)
+             .GroupBy(x => new { x.PalletCode, x.MaterielCode })
+             .Select(x => new SummaryPickingDto
+             {
+                 PalletCode = x.PalletCode,
+                 MaterielCode = x.MaterielCode,
+                 pickedCount = SqlFunc.AggregateCount(x.Id)
+             }).FirstAsync();
+            if (picked == null)
+            {
+                picked = new SummaryPickingDto { pickedCount = 0 };
+            }
+
             var summary = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
-                .Where(x => x.OrderNo == orderNo && x.Status == 0)
+                .WhereIF(!string.IsNullOrEmpty(dto.OrderNo), x => x.OrderNo == dto.OrderNo)
+                .WhereIF(!string.IsNullOrEmpty(dto.PalletCode), x => x.PalletCode == dto.PalletCode)
+                .Where(x => x.Status == 1)
                 .GroupBy(x => new { x.PalletCode, x.MaterielCode })
-                .Select(x => new
+                .Select(x => new SummaryPickingDto
                 {
                     PalletCode = x.PalletCode,
                     MaterielCode = x.MaterielCode,
                     UnpickedCount = SqlFunc.AggregateCount(x.Id),
-                    UnpickedQuantity = SqlFunc.AggregateSum(x.RemainQuantity)
-                })
-                .ToListAsync();
+                    UnpickedQuantity = SqlFunc.AggregateSum(x.AssignQuantity) - SqlFunc.AggregateSum(x.PickedQty),
 
-            return  summary;
+                }).FirstAsync();
+            if (summary == null)
+            {
+                summary = new SummaryPickingDto { pickedCount = 0 };
+            }
+            summary.pickedCount = picked.pickedCount;
+
+            return summary;
         }
         /// <summary>
         /// 鑾峰彇鎷i�夊巻鍙�
@@ -587,50 +1048,59 @@
             {
                 _unitOfWorkManage.BeginTran();
 
-                // 1. 鑾峰彇鎵樼洏搴撳瓨淇℃伅
                 var stockInfo = await _stockInfoService.Db.Queryable<Dt_StockInfo>()
                     .Includes(x => x.Details)
-                    .Where(x => x.PalletCode == request.PalletCode)
-                    .FirstAsync();
+                    .Where(x => x.PalletCode == request.PalletCode).FirstAsync();
 
                 if (stockInfo == null)
                     return WebResponseContent.Instance.Error("鏈壘鍒版墭鐩樺簱瀛樹俊鎭�");
 
-                // 2. 鑾峰彇鐩稿叧鐨勫嚭搴撻攣瀹氫俊鎭�
+
                 var lockInfos = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
-                    .Where(x => x.PalletCode == request.PalletCode &&
-                               x.Status == (int)OutLockStockStatusEnum.鍑哄簱涓�)
+                    .Where(x => x.OrderNo == request.OrderNo && x.PalletCode == request.PalletCode)
                     .ToListAsync();
 
-                // 3. 鏁翠釜鎵樼洏鍑哄簱 - 璁剧疆鍑哄簱鏁伴噺绛変簬搴撳瓨鏁伴噺
-                foreach (var detail in stockInfo.Details)
-                {
-                    decimal outboundQuantity = detail.StockQuantity - detail.OutboundQuantity;
-                    detail.OutboundQuantity = detail.StockQuantity; // 鍏ㄩ儴鍑哄簱
-                    await _stockInfoDetailService.Db.Updateable(detail).ExecuteCommandAsync();
-                }
 
-                // 4. 鏇存柊鍑哄簱閿佸畾淇℃伅
                 foreach (var lockInfo in lockInfos)
                 {
-                    decimal unpicked = lockInfo.AssignQuantity - lockInfo.PickedQty;
-                    lockInfo.PickedQty += unpicked; // 鏍囪涓哄叏閮ㄦ嫞閫�
+                    if (lockInfo.Status == (int)OutLockStockStatusEnum.鍑哄簱涓�)
+                    {
+                        lockInfo.PickedQty = lockInfo.AssignQuantity;
+                    }
                     lockInfo.Status = (int)OutLockStockStatusEnum.宸插嚭搴�;
                     await _outStockLockInfoService.Db.Updateable(lockInfo).ExecuteCommandAsync();
 
-                    // 鏇存柊鍑哄簱鍗曟槑缁�
                     var orderDetail = await _outboundOrderDetailService.Db.Queryable<Dt_OutboundOrderDetail>()
-                        .Where(x => x.Id == lockInfo.OrderDetailId)
-                        .FirstAsync();
-                    orderDetail.OverOutQuantity += unpicked;
-                    orderDetail.LockQuantity -= unpicked;
-                    orderDetail.OrderDetailStatus = (int)OrderDetailStatusEnum.Over;
-                    orderDetail.LockQuantity = 0;
-
-                    await _outboundOrderDetailService.Db.Updateable(orderDetail).ExecuteCommandAsync();
+                    .Where(x => x.Id == lockInfo.OrderDetailId)
+                    .FirstAsync();
+                    if (orderDetail != null)
+                    {
+                        orderDetail.OverOutQuantity += lockInfo.PickedQty;
+                        orderDetail.LockQuantity -= lockInfo.PickedQty;
+                        orderDetail.OrderDetailStatus = (int)OrderDetailStatusEnum.Over;
+                        orderDetail.LockQuantity = 0;
+                        await _outboundOrderDetailService.Db.Updateable(orderDetail).ExecuteCommandAsync();
+                    }
+                }
+                var groupDetails = lockInfos.GroupBy(x => x.OrderDetailId).Select(x => new
+                {
+                    OrderDetailId = x.Key,
+                    TotalQuantity = x.Sum(o => o.PickedQty)
+                }).ToList();
+                foreach (var item in groupDetails)
+                {
+                    var orderDetail = await _outboundOrderDetailService.Db.Queryable<Dt_OutboundOrderDetail>().Where(x => x.Id == item.OrderDetailId).FirstAsync();
+                    if (orderDetail != null)
+                    {
+                        orderDetail.OverOutQuantity = item.TotalQuantity;
+                        orderDetail.LockQuantity = 0;
+                        orderDetail.OrderDetailStatus = (int)OrderDetailStatusEnum.Over;
+                        await _outboundOrderDetailService.Db.Updateable(orderDetail).ExecuteCommandAsync();
+                    }
                 }
 
-                // 5. 鏇存柊鎷嗗寘璁板綍鐘舵��
+                await CheckAndUpdateOrderStatus(request.OrderNo);
+
                 var lockInfoIds = lockInfos.Select(x => x.Id).ToList();
                 var splitRecords = await _splitPackageService.Db.Queryable<Dt_SplitPackageRecord>()
                     .Where(x => lockInfoIds.Contains(x.OutStockLockInfoId) &&
@@ -643,7 +1113,7 @@
                     await _splitPackageService.Db.Updateable(record).ExecuteCommandAsync();
                 }
 
-                // 6. 娓呯┖璐т綅
+
                 var location = await _locationInfoService.Db.Queryable<Dt_LocationInfo>()
                     .Where(x => x.LocationCode == stockInfo.LocationCode)
                     .FirstAsync();
@@ -653,6 +1123,14 @@
                     await _locationInfoService.Db.Updateable(location).ExecuteCommandAsync();
                 }
 
+                foreach (var detail in stockInfo.Details)
+                {
+                    await _stockInfoDetailService.Db.Deleteable(detail).ExecuteCommandAsync();
+                }
+                await _stockInfoService.Db.Deleteable(stockInfo).ExecuteCommandAsync();
+
+
+
                 _unitOfWorkManage.CommitTran();
                 return WebResponseContent.Instance.OK("鐩存帴鍑哄簱鎴愬姛");
             }

--
Gitblit v1.9.3