From e354b5938f49ac90b237289923dcde923d22daf5 Mon Sep 17 00:00:00 2001
From: heshaofeng <heshaofeng@hnkhzn.com>
Date: 星期四, 20 十一月 2025 09:08:27 +0800
Subject: [PATCH] Merge branch 'master' of http://115.159.85.185:8098/r/ZhongRui/ALDbanyunxiangmu

---
 项目代码/WMS无仓储版/WIDESEA_WMSServer/WIDESEA_TaskInfoService/TaskService.cs |  769 +++++++++++++++++++++++++++++++++++++++-------------------
 1 files changed, 515 insertions(+), 254 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_TaskInfoService/TaskService.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_TaskInfoService/TaskService.cs"
index a7b5dca..f8217d5 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_TaskInfoService/TaskService.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_TaskInfoService/TaskService.cs"
@@ -16,12 +16,17 @@
 #endregion << 鐗� 鏈� 娉� 閲� >>
 
 using AutoMapper;
+using Dm.filter;
 using MailKit.Search;
 using Microsoft.Extensions.Logging;
 using Newtonsoft.Json;
 using Org.BouncyCastle.Asn1.Ocsp;
+using Org.BouncyCastle.Asn1.Pkcs;
 using SqlSugar;
+using System.Reflection;
+using System.Reflection.Emit;
 using System.Threading.Tasks;
+using System.Xml.Linq;
 using WIDESEA_Common.CommonEnum;
 using WIDESEA_Common.LocationEnum;
 using WIDESEA_Common.OrderEnum;
@@ -31,8 +36,10 @@
 using WIDESEA_Core;
 using WIDESEA_Core.BaseRepository;
 using WIDESEA_Core.BaseServices;
+using WIDESEA_Core.Enums;
 using WIDESEA_Core.Helper;
 using WIDESEA_DTO.Basic;
+using WIDESEA_DTO.Inbound;
 using WIDESEA_DTO.Task;
 using WIDESEA_IBasicService;
 using WIDESEA_IInboundService;
@@ -53,8 +60,17 @@
         private readonly IRepository<Dt_StockInfo> _stockRepository;
         private readonly ILocationInfoService _locationInfoService;
         private readonly IInboundOrderService _inboundOrderService;
+        private readonly IInboundOrderDetailService _inboundOrderDetailService;
+
+        private readonly IOutboundOrderService _outboundOrderService;
+        private readonly IOutboundOrderDetailService _outboundOrderDetailService;
+        private readonly IOutStockLockInfoService _outStockLockInfoService;
         private readonly ILocationStatusChangeRecordService _locationStatusChangeRecordService;
         private readonly IESSApiService _eSSApiService;
+        private readonly IStockService _stockService;
+        private readonly IRecordService _recordService;
+
+        private readonly IInvokeMESService _invokeMESService;
         public IRepository<Dt_Task> Repository => BaseDal;
 
         private Dictionary<string, SqlSugar.OrderByType> _taskOrderBy = new()
@@ -66,15 +82,15 @@
         private Dictionary<string, string> stations = new Dictionary<string, string>
         {
             {"3-5","3-9" },
-             {"2-5","2-9" },
-              {"1-11","1-1" },
+            {"2-5","2-9" },
+            {"1-11","1-1" },
         };
 
         public List<int> TaskTypes => typeof(TaskTypeEnum).GetEnumIndexList();
 
         public List<int> TaskOutboundTypes => typeof(TaskTypeEnum).GetEnumIndexList();
 
-        public TaskService(IRepository<Dt_Task> BaseDal, IMapper mapper, IUnitOfWorkManage unitOfWorkManage, IRepository<Dt_StockInfo> stockRepository, ILocationInfoService locationInfoService, IInboundOrderService inboundOrderService, ILocationStatusChangeRecordService locationStatusChangeRecordService, IESSApiService eSSApiService, ILogger<TaskService> logger) : base(BaseDal)
+        public TaskService(IRepository<Dt_Task> BaseDal, IMapper mapper, IUnitOfWorkManage unitOfWorkManage, IRepository<Dt_StockInfo> stockRepository, ILocationInfoService locationInfoService, IInboundOrderService inboundOrderService, ILocationStatusChangeRecordService locationStatusChangeRecordService, IESSApiService eSSApiService, ILogger<TaskService> logger, IStockService stockService, IRecordService recordService, IInboundOrderDetailService inboundOrderDetailService, IOutboundOrderService outboundOrderService, IOutboundOrderDetailService outboundOrderDetailService, IInvokeMESService invokeMESService, IOutStockLockInfoService outStockLockInfoService) : base(BaseDal)
         {
             _mapper = mapper;
             _unitOfWorkManage = unitOfWorkManage;
@@ -84,270 +100,271 @@
             _locationStatusChangeRecordService = locationStatusChangeRecordService;
             _eSSApiService = eSSApiService;
             _logger = logger;
+            _stockService = stockService;
+            _recordService = recordService;
+            _inboundOrderDetailService = inboundOrderDetailService;
+            _outboundOrderService = outboundOrderService;
+            _outboundOrderDetailService = outboundOrderDetailService;
+            _invokeMESService = invokeMESService;
+            _outStockLockInfoService = outStockLockInfoService;
         }
 
-        public async Task<WebResponseContent> RequestInboundTask(string palletCode, string stationCode)
-        {
-            try
-            {
-                Dt_Task dbtask = Repository.QueryFirst(x => x.PalletCode == palletCode);
-                if (dbtask != null)
-                {
-                    return WebResponseContent.Instance.Error($"璇ユ墭鐩樺凡鐢熸垚浠诲姟");
-                }
-
-                Dt_StockInfo stockInfo = _stockRepository.Db.Queryable<Dt_StockInfo>().Where(x => x.PalletCode == palletCode).Includes(x => x.Details).First();
-                if (stockInfo == null)
-                {
-                    return WebResponseContent.Instance.Error($"鏈壘鍒扮粍鐩樹俊鎭�");
-                }
-
-                if (stockInfo.StockStatus != StockStatusEmun.缁勭洏鏆傚瓨.ObjToInt() && stockInfo.StockStatus != StockStatusEmun.鎵嬪姩缁勭洏鏆傚瓨.ObjToInt() && stockInfo.StockStatus != StockStatusEmun.鎷i�夊畬鎴�.ObjToInt())
-                {
-                    return WebResponseContent.Instance.Error($"璇ユ墭鐩樼姸鎬佷笉姝g‘,涓嶅彲鐢宠鍏ュ簱");
-                }
-                if (!string.IsNullOrEmpty(stockInfo.LocationCode))
-                {
-                    return WebResponseContent.Instance.Error($"璇ユ墭鐩樺凡缁戝畾璐т綅");
-                }
-
-                Dt_LocationInfo? locationInfo = _locationInfoService.AssignLocation();
-                if (locationInfo == null)
-                {
-                    return WebResponseContent.Instance.Error($"璐т綅鍒嗛厤澶辫触,鏈壘鍒板彲鍒嗛厤璐т綅");
-                }
-
-
-                var newTask = new Dt_Task()
-                {
-                    CurrentAddress = stationCode,
-                    Grade = 0,
-                    NextAddress = stations.GetValueOrDefault(stationCode) ?? "",
-                    PalletCode = palletCode,
-                    Roadway = locationInfo.RoadwayNo,
-                    SourceAddress = stationCode,
-                    TargetAddress = locationInfo.LocationCode,
-                    TaskType = TaskTypeEnum.Inbound.ObjToInt(),
-                    TaskStatus = TaskStatusEnum.New.ObjToInt(),
-                    WarehouseId = stockInfo.WarehouseId,
-                    PalletType = stockInfo.PalletType,
-                };
-
-                if (stockInfo.PalletType == PalletTypeEnum.Empty.ObjToInt())
-                {
-                    _unitOfWorkManage.BeginTran();
-                    int taskId = BaseDal.AddData(newTask);
-                    newTask.TaskId = taskId;
-
-                    locationInfo.LocationStatus = LocationStatusEnum.Lock.ObjToInt();
-                    _locationInfoService.UpdateData(locationInfo);
-                    stockInfo.StockStatus = StockStatusEmun.鍏ュ簱纭.ObjToInt();
-                    _stockRepository.UpdateData(stockInfo);
-                    _unitOfWorkManage.CommitTran();
-                }
-                else
-                {
-                    //鑾峰彇鏄惁瀛樺湪鍏ュ簱鍗�
-                    Dt_InboundOrder? inboundOrder = null;
-                    if (stockInfo != null && stockInfo.Details.Count > 0)
-                    {
-                        string? orderNo = stockInfo.Details.FirstOrDefault()?.OrderNo ?? "";
-                        inboundOrder = _inboundOrderService.Repository.QueryFirst(x => x.InboundOrderNo == orderNo && x.OrderStatus < InOrderStatusEnum.鍏ュ簱瀹屾垚.ObjToInt());
-                    }
-
-                    if (inboundOrder != null)
-                    {
-                        if (inboundOrder.OrderType == InOrderTypeEnum.Allocat.ObjToInt())
-                        {
-                            newTask.TaskType = TaskTypeEnum.InAllocate.ObjToInt();
-                        }
-                        else if (inboundOrder.OrderType == InOrderTypeEnum.Return.ObjToInt())
-                        {
-                            newTask.TaskType = TaskTypeEnum.ProductionReturn.ObjToInt();
-                        }
-                    }
-                    if (stockInfo.StockStatus == StockStatusEmun.鎵嬪姩缁勭洏鏆傚瓨.ObjToInt())
-                    {
-                        stockInfo.StockStatus = StockStatusEmun.鎵嬪姩缁勭洏鍏ュ簱纭.ObjToInt();
-                    }
-                    else if (stockInfo.StockStatus == StockStatusEmun.MES閫�搴�.ObjToInt())
-                    {
-                        newTask.TaskType = TaskTypeEnum.MesMatReturn.ObjToInt();
-                    }
-                    else if (stockInfo.StockStatus == StockStatusEmun.鎷i�夊畬鎴�.ObjToInt())
-                    {
-                        stockInfo.StockStatus = StockStatusEmun.鍏ュ簱纭.ObjToInt();
-                        newTask.TaskType = TaskTypeEnum.InPick.ObjToInt();
-                    }
-                    else if (stockInfo.StockStatus == StockStatusEmun.閫佹搴撳瓨瀹屾垚.ObjToInt())
-                    {
-                        stockInfo.StockStatus = StockStatusEmun.鎵嬪姩缁勭洏鍏ュ簱纭.ObjToInt();
-                        newTask.TaskType = TaskTypeEnum.InQuality.ObjToInt();
-                    }
-                    else if (stockInfo.StockStatus == StockStatusEmun.鐩樼偣搴撳瓨瀹屾垚.ObjToInt())
-                    {
-                        stockInfo.StockStatus = StockStatusEmun.鎵嬪姩缁勭洏鍏ュ簱纭.ObjToInt();
-                        newTask.TaskType = TaskTypeEnum.InInventory.ObjToInt();
-                    }
-                    else
-                    {
-                        stockInfo.StockStatus = StockStatusEmun.鍏ュ簱纭.ObjToInt();
-                    }
-
-                    LocationStatusEnum lastStatus = (LocationStatusEnum)locationInfo.LocationStatus;
-                    _unitOfWorkManage.BeginTran();
-                    int taskId = BaseDal.AddData(newTask);
-                    newTask.TaskId = taskId;
-
-                    _locationStatusChangeRecordService.AddLocationStatusChangeRecord(locationInfo, locationInfo.LocationStatus, StockChangeType.Inbound.ObjToInt(), inboundOrder.InboundOrderNo, newTask.TaskNum);
-
-                    locationInfo.LocationStatus = LocationStatusEnum.Lock.ObjToInt();
-                    _locationInfoService.UpdateData(locationInfo);
-
-                    _stockRepository.UpdateData(stockInfo);
-                    _unitOfWorkManage.CommitTran();
-                }
-                TaskModel esstask = new TaskModel()
-                {
-                    taskType = "putaway",
-                    taskGroupCode = "",
-                    groupPriority = 0,
-                    tasks = new List<TasksType>
-                    {
-                            new()
-                            {
-                                taskCode=newTask.TaskNum.ToString(),
-                                taskPriority=0,
-                                taskDescribe=new TaskDescribeType{
-                                containerCode=palletCode,
-                                containerType= "CT_KUBOT_STANDARD",
-                                fromLocationCode=stations.GetValueOrDefault(stationCode)??"",
-                                toStationCode="",
-                                toLocationCode=locationInfo.LocationCode,
-                                deadline=0,storageTag=""
-                                }
-                            }
-                    }
-                };
-                _logger.LogInformation("鍒涘缓浠诲姟Request:  " + JsonConvert.SerializeObject(esstask));
-                var result = await _eSSApiService.CreateTaskAsync(esstask);
-
-                _logger.LogInformation("鍒涘缓浠诲姟杩斿洖:  " + result);
-                if (result)
-                {
-                    return WebResponseContent.Instance.OK();
-                }
-                else
-                {
-                    return WebResponseContent.Instance.Error("涓嬪彂鏈哄櫒浜轰换鍔″け璐ワ紒");
-                }
-            }
-            catch (Exception ex)
-            {
-                return WebResponseContent.Instance.Error(ex.Message);
-            }
-        }
-
-        /// <summary>
-        /// 鍏ョ┖绠�
-        /// </summary>
-        /// <param name="palletCode"></param>
-        /// <param name="address"></param>
-        /// <param name="WarehouseId"></param>
-        /// <returns></returns>
-        public WebResponseContent InEmpty(string palletCode, string address, int WarehouseId)
-        {
-            try
-            {
-
-                Dt_Task dbtask = Repository.QueryFirst(x => x.PalletCode == palletCode);
-                if (dbtask != null)
-                {
-                    return WebResponseContent.Instance.Error($"璇ユ墭鐩樺凡鐢熸垚浠诲姟");
-                }
-
-                Dt_StockInfo stockInfo = _stockRepository.Db.Queryable<Dt_StockInfo>().Where(x => x.PalletCode == palletCode).First();
-                if (stockInfo == null)
-                {
-                    return WebResponseContent.Instance.Error($"鏈壘鍒扮粍鐩樹俊鎭�");
-                }
-                if (stockInfo.StockStatus != StockStatusEmun.缁勭洏鏆傚瓨.ObjToInt() && stockInfo.StockStatus != StockStatusEmun.鎵嬪姩缁勭洏鏆傚瓨.ObjToInt() && stockInfo.StockStatus != StockStatusEmun.鎷i�夊畬鎴�.ObjToInt())
-                {
-                    return WebResponseContent.Instance.Error($"璇ユ墭鐩樼姸鎬佷笉姝g‘,涓嶅彲鐢宠鍏ュ簱");
-                }
-                if (!string.IsNullOrEmpty(stockInfo.LocationCode))
-                {
-                    return WebResponseContent.Instance.Error($"璇ユ墭鐩樺凡缁戝畾璐т綅");
-                }
-                //stockInfo = new Dt_StockInfo()
-                //{
-                //    PalletCode = barcode,
-                //    StockStatus = StockStatusEmun.鍏ュ簱纭.ObjToInt(),
-                //    WarehouseId = WarehouseId,
-                //    PalletType = PalletTypeEnum.Empty.ObjToInt(),
-                //    Details = new List<Dt_StockInfoDetail>()
-                //};
-
-                var locationInfo = _locationInfoService.AssignLocation();
-                if (locationInfo == null)
-                {
-                    return WebResponseContent.Instance.Error($"璐т綅鍒嗛厤澶辫触,鏈壘鍒板彲鍒嗛厤璐т綅");
-                }
-
-                Dt_Task newTask = new Dt_Task()
-                {
-                    CurrentAddress = address,
-                    Grade = 0,
-                    NextAddress = locationInfo.LocationCode,
-                    PalletCode = palletCode,
-                    Roadway = locationInfo.RoadwayNo,
-                    SourceAddress = address,
-                    TargetAddress = locationInfo.LocationCode,
-                    TaskType = TaskTypeEnum.InEmpty.ObjToInt(),
-                    TaskStatus = TaskStatusEnum.New.ObjToInt(),
-                    WarehouseId = stockInfo.WarehouseId,
-                    PalletType = stockInfo.PalletType
-                };
-                locationInfo.LocationStatus = LocationStatusEnum.Lock.ObjToInt();
-                _unitOfWorkManage.BeginTran();
-                int taskId = BaseDal.AddData(newTask);
-                newTask.TaskId = taskId;
-                _locationInfoService.UpdateData(locationInfo);
-                stockInfo.StockStatus = StockStatusEmun.鍏ュ簱纭.ObjToInt();
-                _stockRepository.AddData(stockInfo);
-                _unitOfWorkManage.CommitTran();
-
-
-                return WebResponseContent.Instance.OK();
-            }
-            catch (Exception ex)
-            {
-                _unitOfWorkManage.RollbackTran();
-                return WebResponseContent.Instance.Error(ex.Message);
-            }
-        }
 
         /// <summary>
         /// 
         /// </summary>
         /// <param name="taskNum"></param>
         /// <returns></returns>
-        public async Task<WebResponseContent> TaskCompleted(int taskNum)
+        public async Task<WebResponseContent> TaskCompleted(string taskNum)
         {
+            try
+            {
+                Dt_Task task;
+
+                if (int.TryParse(taskNum, out var newTaskNum))
+                {
+                    task = BaseDal.QueryFirst(x => x.TaskNum == newTaskNum);
+                    if (task == null)
+                    {
+                        return WebResponseContent.Instance.Error("鏈壘鍒颁换鍔′俊鎭�");
+                    }
+                }
+                else
+                {
+                    return WebResponseContent.Instance.Error("鏈壘鍒颁换鍔′俊鎭�");
+                }
+                _logger.LogInformation($"TaskService TaskCompleted: {JsonConvert.SerializeObject(task)} , {task.TaskType} ");
+
+                MethodInfo? methodInfo = GetType().GetMethod(((TaskTypeEnum)task.TaskType) + "TaskCompleted");
+                if (methodInfo != null)
+                {
+                    WebResponseContent? responseContent = (WebResponseContent?)methodInfo.Invoke(this, new object[] { task });
+                    if (responseContent != null)
+                    {
+                        return responseContent;
+                    }
+                }
+                return WebResponseContent.Instance.Error("鏈壘鍒颁换鍔$被鍨嬪搴斾笟鍔″鐞嗛�昏緫");
+            }
+            catch (Exception ex)
+            {
+                _logger.LogError($"TaskService TaskCompleted:  {ex.Message} ");
+                return WebResponseContent.Instance.Error(ex.Message);
+            }
+        }
+        /// <summary>
+        /// 鍏ュ簱瀹屾垚
+        /// </summary>
+        /// <param name="task"></param>
+        /// <returns></returns>
+        public async Task<WebResponseContent> InboundTaskCompleted(Dt_Task task)
+        {
+            decimal beforeQuantity = 0;
+
+            //鏌ュ簱瀛�
+            Dt_StockInfo stockInfo = _stockRepository.Db.Queryable<Dt_StockInfo>().Includes(x => x.Details).Where(x => x.PalletCode == task.PalletCode && x.WarehouseId == task.WarehouseId).First();
+            if (stockInfo == null)
+            {
+                return WebResponseContent.Instance.Error($"鏈壘鍒版墭鐩樺搴旂殑缁勭洏淇℃伅");
+            }
+            if (stockInfo.Details.Count == 0 && stockInfo.PalletType != PalletTypeEnum.Empty.ObjToInt())
+            {
+                return WebResponseContent.Instance.Error($"鏈壘鍒拌鎵樼洏搴撳瓨鏄庣粏淇℃伅");
+            }
+            //鏌ヨ揣浣�
+            Dt_LocationInfo locationInfo = _locationInfoService.Repository.QueryFirst(x => x.LocationCode == task.TargetAddress);
+            if (locationInfo == null)
+            {
+                return WebResponseContent.Instance.Error($"鏈壘鍒板搴旂殑缁堢偣璐т綅淇℃伅");
+            }
+
+            var ordernos = stockInfo.Details.GroupBy(x => x.OrderNo).Select(o => o.Key).ToList();
+            var inboundOrders = _inboundOrderService.Repository.Db.Queryable<Dt_InboundOrder>().Where(x => ordernos.Contains(x.InboundOrderNo)).Includes(x => x.Details).ToList();
+            Dt_InboundOrderDetail? inboundOrderDetail = null;
+
+            foreach (var inboundOrder in inboundOrders)
+            {
+                //鏍囧噯鍏ュ簱娴佺▼鏌ユ壘鍏ュ簱鍗曟嵁
+                if (inboundOrder != null && stockInfo.StockStatus == StockStatusEmun.鍏ュ簱纭.ObjToInt())
+                {
+                    foreach (var item in stockInfo.Details.Where(x => x.OrderNo == inboundOrder.InboundOrderNo).ToList())
+                    {
+                        var inbounddetail = inboundOrder.Details.Where(x => x.lineNo == item.InboundOrderRowNo && x.Barcode == item.Barcode).FirstOrDefault();
+                        if (inbounddetail != null)
+                        {
+                            inbounddetail.OverInQuantity += item.StockQuantity;
+                            if (inbounddetail.OverInQuantity == inbounddetail.OrderQuantity)
+                            {
+                                inbounddetail.OrderDetailStatus = OrderDetailStatusEnum.Over.ObjToInt();
+                            }
+                            else if (inbounddetail.OrderDetailStatus == OrderDetailStatusEnum.New.ObjToInt())
+                            {
+                                inbounddetail.OrderDetailStatus = OrderDetailStatusEnum.Inbounding.ObjToInt();
+                            }
+                            _inboundOrderDetailService.UpdateData(inbounddetail);
+                        }
+                    }
+                    if (inboundOrder.Details.Count == inboundOrder.Details.Where(x => x.OrderQuantity == x.OverInQuantity).Count())
+                    {
+                        inboundOrder.OrderStatus = InOrderStatusEnum.鍏ュ簱瀹屾垚.ObjToInt();
+                    }
+                    else if (inboundOrder.OrderStatus == InOrderStatusEnum.鏈紑濮�.ObjToInt())
+                    {
+                        inboundOrder.OrderStatus = InOrderStatusEnum.鍏ュ簱涓�.ObjToInt();
+                    }
+                    _inboundOrderService.UpdateData(inboundOrder);
+                }
+            }
+            stockInfo.LocationCode = task.TargetAddress;
+            stockInfo.StockStatus = StockStatusEmun.鍏ュ簱瀹屾垚.ObjToInt();
+            stockInfo.Details.ForEach(x =>
+            {
+                x.Status = StockStatusEmun.鍏ュ簱瀹屾垚.ObjToInt();
+            });
+            _stockService.StockInfoService.Repository.UpdateData(stockInfo);
+            _stockService.StockInfoDetailService.Repository.UpdateData(stockInfo.Details);
+
+            beforeQuantity = stockInfo.Details.Where(x => x.Id != 0).Sum(x => x.StockQuantity);
+
+            int beforeStatus = locationInfo.LocationStatus;
+            if (stockInfo.PalletType == PalletTypeEnum.Empty.ObjToInt())
+            {
+                locationInfo.LocationStatus = LocationStatusEnum.Pallet.ObjToInt();
+            }
+            else
+            {
+                locationInfo.LocationStatus = LocationStatusEnum.InStock.ObjToInt();
+            }
+            _locationInfoService.Repository.UpdateData(locationInfo);
+
+            task.TaskStatus = TaskStatusEnum.Finish.ObjToInt();
+
+            BaseDal.DeleteAndMoveIntoHty(task, App.User.UserId == 0 ? OperateTypeEnum.鑷姩瀹屾垚 : OperateTypeEnum.浜哄伐瀹屾垚);
+
+            _locationStatusChangeRecordService.AddLocationStatusChangeRecord(locationInfo, beforeStatus, StockChangeType.Inbound.ObjToInt(), "", task.TaskNum);
+
+            _recordService.StockQuantityChangeRecordService.AddStockChangeRecord(stockInfo, stockInfo.Details, beforeQuantity, stockInfo.Details.Sum(x => x.StockQuantity) + beforeQuantity, WIDESEA_Common.StockEnum.StockChangeType.MaterielGroup);
+            try
+            {
+                foreach (var inboundOrder in inboundOrders)
+                {
+                    if (inboundOrder.OrderType == InOrderTypeEnum.Allocat.ObjToInt())//璋冩嫧鍏ュ簱
+                    {
+
+                    }
+                    else if (inboundOrder.OrderType == InOrderTypeEnum.ReCheck.ObjToInt()) //閲嶆鍏ュ簱
+                    {
+
+                    }
+                    else
+                    {
+                        if (inboundOrder != null && inboundOrder.OrderStatus == InOrderStatusEnum.鍏ュ簱瀹屾垚.ObjToInt())
+                        {
+                            var feedmodel = new FeedbackInboundRequestModel
+                            {
+                                reqCode = Guid.NewGuid().ToString(),
+                                reqTime = DateTime.Now.ToString(),
+                                business_type = inboundOrder.BusinessType,
+                                factoryArea = inboundOrder.FactoryArea,
+                                operationType = 1,
+                                Operator = inboundOrder.Operator,
+                                orderNo = inboundOrder.UpperOrderNo,
+                                status = inboundOrder.OrderStatus,
+                                details = new List<FeedbackInboundDetailsModel>()
+
+                            };
+
+                            var groupedData = inboundOrder.Details.GroupBy(item => new { item.MaterielCode, item.SupplyCode, item.BatchNo, item.lineNo, item.BarcodeUnit, item.WarehouseCode })
+                               .Select(group => new FeedbackInboundDetailsModel
+                               {
+                                   materialCode = group.Key.MaterielCode,
+                                   supplyCode = group.Key.SupplyCode,
+                                   batchNo = group.Key.BatchNo,
+                                   lineNo = group.Key.lineNo,
+                                   warehouseCode = group.Key.WarehouseCode,
+                                   qty = group.Sum(x => x.BarcodeQty),
+                                   // warehouseCode= "1072",
+                                   unit = group.Key.BarcodeUnit,
+                                   barcodes = group.Select(row => new FeedbackBarcodesModel
+                                   {
+                                       barcode = row.Barcode,
+                                       qty = row.BarcodeQty
+                                   }).ToList()
+                               }).ToList();
+                            feedmodel.details = groupedData;
+
+                            var result= await _invokeMESService.FeedbackInbound(feedmodel);
+                            if (result != null && result.code == 200)
+                            {
+                                _inboundOrderService.Db.Updateable<Dt_InboundOrder>().SetColumns(it => new Dt_InboundOrder { ReturnToMESStatus = 1 })
+                                .Where(it => it.Id== inboundOrder.Id).ExecuteCommand();
+                                _inboundOrderDetailService.Db.Updateable<Dt_InboundOrderDetail>().SetColumns(it => new Dt_InboundOrderDetail { ReturnToMESStatus = 1 })
+                                .Where(it => it.OrderId == inboundOrder.Id).ExecuteCommand();
+                            }
+                        }
+                    }
+
+                }
+            }
+            catch (Exception ex)
+            {
+                _logger.LogInformation("InboundTaskCompleted 鍥炲啓MES澶辫触:  " + ex.Message);
+            }
+
+            return WebResponseContent.Instance.OK();
+        }
+
+        public WebResponseContent OutboundTaskCompleted(Dt_Task task)
+        {
+            _logger.LogInformation($"TaskService  OutboundTaskCompleted: {task.TaskNum}");
+            //鏌ヨ揣浣�
+            Dt_LocationInfo locationInfo = _locationInfoService.Repository.QueryFirst(x => x.LocationCode == task.SourceAddress);
+            if (locationInfo == null)
+            {
+                return WebResponseContent.Instance.Error($"鏈壘鍒板搴旂殑缁堢偣璐т綅淇℃伅");
+            }
+            locationInfo.LocationStatus = LocationStatusEnum.Free.ObjToInt();
+            _locationInfoService.Repository.UpdateData(locationInfo);
+
+            var outloks = _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>().Where(x => x.TaskNum == task.TaskNum).ToList();
+
+            var stockids = outloks.Select(x => x.StockId).ToList();
+            
+            _stockService.StockInfoService.Db.Updateable<Dt_StockInfo>()
+                                  .SetColumns(it => new Dt_StockInfo
+                                  {
+                                      StockStatus = StockStatusEmun.鍑哄簱閿佸畾.ObjToInt()
+                                  })
+                                  .Where(it => stockids.Contains(it.Id))
+                                  .ExecuteCommand();
+
+            _stockService.StockInfoDetailService.Db.Updateable<Dt_StockInfoDetail>()
+                                  .SetColumns(it => new Dt_StockInfoDetail
+                                  {
+                                      Status = StockStatusEmun.鍑哄簱閿佸畾.ObjToInt()
+                                  })
+                                  .Where(it => stockids.Contains( it.StockId))
+                                  .ExecuteCommand();
+ 
+
+
+            return WebResponseContent.Instance.OK();
+
+
+        }
+        public async Task<WebResponseContent> InEmptyTaskCompleted(Dt_Task task)
+        {
+
             WebResponseContent content = new WebResponseContent();
             try
             {
-                Dt_Task task = await Repository.QueryFirstAsync(x => x.TaskNum == taskNum);
-                if (task == null)
-                {
-                    return await Task.FromResult(WebResponseContent.Instance.Error($"鏈壘鍒颁换鍔′俊鎭�"));
-                }
+
                 Dt_LocationInfo locationInfo = _locationInfoService.Repository.QueryFirst(x => x.LocationCode == task.TargetAddress);
                 if (locationInfo == null)
                 {
                     return content.Error($"鏈壘鍒板搴旂殑缁堢偣璐т綅淇℃伅");
                 }
-                Dt_StockInfo stockInfo = _stockRepository.Db.Queryable<Dt_StockInfo>().Where(x => x.PalletCode == task.PalletCode && x.WarehouseId == task.WarehouseId).Includes(x => x.Details).First();
+                Dt_StockInfo stockInfo = _stockRepository.Db.Queryable<Dt_StockInfo>().Where(x => x.PalletCode == task.PalletCode && x.WarehouseId == task.WarehouseId).First();
                 if (stockInfo == null)
                 {
                     return WebResponseContent.Instance.Error($"鏈壘鍒版墭鐩樺搴旂殑缁勭洏淇℃伅");
@@ -361,13 +378,24 @@
                 {
                     return WebResponseContent.Instance.Error($"璐т綅鐘舵�佷笉姝g‘");
                 }
-                LocationStatusEnum lastStatus = (LocationStatusEnum)locationInfo.LocationStatus;
-                locationInfo.LocationStatus = LocationStatusEnum.InStock.ObjToInt();
+
+
+                var beforelocationStatus = locationInfo.LocationStatus;
+                locationInfo.LocationStatus = LocationStatusEnum.Pallet.ObjToInt();
+                _locationInfoService.Repository.UpdateData(locationInfo);
 
                 stockInfo.LocationCode = locationInfo.LocationCode;
+                stockInfo.PalletCode = task.PalletCode;
+                stockInfo.LocationCode = task.TargetAddress;
+                stockInfo.StockStatus = StockStatusEmun.鍏ュ簱瀹屾垚.ObjToInt();
+                _stockRepository.UpdateData(stockInfo);
 
-                Dt_InboundOrder? inboundOrder = _inboundOrderService.Repository.Db.Queryable<Dt_InboundOrder>().Where(x => x.InboundOrderNo == stockInfo.Details.FirstOrDefault().OrderNo).Includes(x => x.Details).First();
-                Dt_InboundOrderDetail? inboundOrderDetail = null;
+                task.TaskStatus = TaskStatusEnum.Finish.ObjToInt();
+                BaseDal.DeleteAndMoveIntoHty(task, App.User.UserId == 0 ? WIDESEA_Core.Enums.OperateTypeEnum.鑷姩瀹屾垚 : OperateTypeEnum.浜哄伐瀹屾垚);
+
+                _locationStatusChangeRecordService.AddLocationStatusChangeRecord(locationInfo, beforelocationStatus, StockChangeType.Inbound.ObjToInt(), "", task.TaskNum);
+
+
 
                 return content;
             }
@@ -376,5 +404,238 @@
                 return await Task.FromResult(WebResponseContent.Instance.Error(ex.Message));
             }
         }
+
+        public WebResponseContent InPickTaskCompleted(Dt_Task task)
+        {
+            _logger.LogInformation($"TaskService  InPickTaskCompleted: {task.TaskNum}");
+            //鏌ュ簱瀛�
+            Dt_StockInfo stockInfo = _stockRepository.Db.Queryable<Dt_StockInfo>().Includes(x => x.Details).Where(x => x.PalletCode == task.PalletCode).First();
+            if (stockInfo == null)
+            {
+                return WebResponseContent.Instance.Error($"鏈壘鍒版墭鐩樺搴旂殑缁勭洏淇℃伅");
+            }
+            if (stockInfo.Details.Count == 0 && stockInfo.PalletType != PalletTypeEnum.Empty.ObjToInt())
+            {
+                return WebResponseContent.Instance.Error($"鏈壘鍒拌鎵樼洏搴撳瓨鏄庣粏淇℃伅");
+            }
+
+            //鏌ヨ揣浣�
+            Dt_LocationInfo locationInfo = _locationInfoService.Repository.QueryFirst(x => x.LocationCode == task.TargetAddress);
+            if (locationInfo == null)
+            {
+                return WebResponseContent.Instance.Error($"鏈壘鍒板搴旂殑缁堢偣璐т綅淇℃伅");
+            }
+            stockInfo.LocationCode = task.TargetAddress;
+            stockInfo.StockStatus = StockStatusEmun.鍏ュ簱瀹屾垚.ObjToInt();
+            stockInfo.Details.ForEach(x =>
+            {
+                x.Status = StockStatusEmun.鍏ュ簱瀹屾垚.ObjToInt();
+            });
+            _stockService.StockInfoService.Repository.UpdateData(stockInfo);
+            _stockService.StockInfoDetailService.Repository.UpdateData(stockInfo.Details);
+
+            if (stockInfo.PalletType == PalletTypeEnum.Empty.ObjToInt())
+            {
+                locationInfo.LocationStatus = LocationStatusEnum.Pallet.ObjToInt();
+            }
+            else
+            {
+                locationInfo.LocationStatus = LocationStatusEnum.InStock.ObjToInt();
+            }
+            _locationInfoService.Repository.UpdateData(locationInfo);
+
+            task.TaskStatus = TaskStatusEnum.Finish.ObjToInt();
+
+            BaseDal.DeleteAndMoveIntoHty(task, App.User.UserId == 0 ? OperateTypeEnum.鑷姩瀹屾垚 : OperateTypeEnum.浜哄伐瀹屾垚);
+
+            return WebResponseContent.Instance.OK();
+        }
+
+        public async Task<WebResponseContent> OutEmptyTaskCompleted(Dt_Task task)
+        {
+            WebResponseContent content = new WebResponseContent();
+            try
+            {
+                Dt_StockInfo stockInfo = _stockRepository.Db.Queryable<Dt_StockInfo>().Where(x => x.PalletCode == task.PalletCode).First();
+                if (stockInfo == null)
+                {
+                    return WebResponseContent.Instance.Error($"鏈壘鍒版墭鐩樺搴旂殑搴撳瓨淇℃伅");
+                }
+                Dt_LocationInfo locationInfo = _locationInfoService.Repository.QueryFirst(x => x.LocationCode == task.SourceAddress);
+
+                if (locationInfo == null)
+                {
+                    return content.Error($"鏈壘鍒板搴旂殑缁堢偣璐т綅淇℃伅");
+                }
+
+
+                int beforeStatus = locationInfo.LocationStatus;
+
+                locationInfo.LocationStatus = LocationStatusEnum.Free.ObjToInt();
+
+                _locationInfoService.Repository.UpdateData(locationInfo);
+
+
+                task.TaskStatus = TaskStatusEnum.Finish.ObjToInt();
+                BaseDal.DeleteAndMoveIntoHty(task, App.User.UserId == 0 ? OperateTypeEnum.鑷姩瀹屾垚 : OperateTypeEnum.浜哄伐瀹屾垚);
+                _stockService.StockInfoService.Repository.DeleteAndMoveIntoHty(stockInfo, App.User.UserId == 0 ? OperateTypeEnum.鑷姩瀹屾垚 : OperateTypeEnum.浜哄伐瀹屾垚);
+                _stockRepository.Db.Deleteable(stockInfo).ExecuteCommand();
+
+                _locationStatusChangeRecordService.AddLocationStatusChangeRecord(locationInfo, beforeStatus, StockChangeType.Outbound.ObjToInt(), stockInfo.Details.FirstOrDefault()?.OrderNo ?? "", task.TaskNum);
+
+                return WebResponseContent.Instance.OK();
+
+            }
+            catch (Exception ex)
+            {
+                _logger.LogError($"TaskService OutEmptyTaskCompleted:  {ex.Message} ");
+                return await Task.FromResult(WebResponseContent.Instance.Error(ex.Message));
+            }
+        }
+
+
+
+
+        /// <summary>
+        /// 鍥炲簱瀹屾垚鍥炶皟 
+        public async Task<WebResponseContent> BackToStockComplete(Dt_Task task)
+        {
+            try
+            {
+                _unitOfWorkManage.BeginTran();
+
+                // 鑾峰彇鐩稿叧鐨勫嚭搴撻攣瀹氫俊鎭�
+                var lockInfos = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
+                    .Where(x => x.TaskNum == task.TaskNum &&
+                               x.Status == (int)OutLockStockStatusEnum.鍥炲簱涓�)
+                    .ToListAsync();
+
+                if (!lockInfos.Any())
+                    return WebResponseContent.Instance.Error("鏈壘鍒板洖搴撲腑鐨勯攣瀹氫俊鎭�");
+
+                //  鎭㈠搴撳瓨鍑哄簱鏁伴噺锛堝洖搴撶殑閮ㄥ垎锛�
+                await RestoreStockOutboundQuantity(lockInfos);
+
+                //  鏇存柊鍑哄簱鍗曟槑缁嗙殑閿佸畾鏁伴噺
+                var orderDetailGroups = lockInfos.GroupBy(x => x.OrderDetailId);
+
+                foreach (var group in orderDetailGroups)
+                {
+                    var orderDetailId = group.Key;
+                    var totalUnpicked = group.Sum(x => x.AssignQuantity - x.PickedQty);
+
+                    if (totalUnpicked > 0)
+                    {
+                        var orderDetail = await _outboundOrderService.Db.Queryable<Dt_OutboundOrderDetail>()
+                            .Where(x => x.Id == orderDetailId)
+                            .FirstAsync();
+                        orderDetail.LockQuantity -= totalUnpicked;
+
+                        // 鎭㈠鐘舵��
+                        if (orderDetail.LockQuantity <= 0 && orderDetail.OverOutQuantity <= 0)
+                        {
+                            orderDetail.OrderDetailStatus = (int)OrderDetailStatusEnum.New;
+                        }
+                        else if (orderDetail.OverOutQuantity > 0)
+                        {
+                            orderDetail.OrderDetailStatus = (int)OrderDetailStatusEnum.AssignOverPartial;
+                        }
+
+                        await _outboundOrderService.Db.Updateable(orderDetail).ExecuteCommandAsync();
+                    }
+                }
+
+                //  鏇存柊閿佸畾淇℃伅鐘舵�佷负宸插洖搴�
+                foreach (var lockInfo in lockInfos)
+                {
+                    lockInfo.Status = (int)OutLockStockStatusEnum.宸插洖搴�;
+                }
+                await _outStockLockInfoService.Db.Updateable(lockInfos).ExecuteCommandAsync();
+
+                // 6. 鏇存柊搴撳瓨鐘舵��
+                var stockIds = lockInfos.Select(x => x.StockId).Distinct().ToList();
+                var stocks = await _stockService.StockInfoService.Db.Queryable<Dt_StockInfo>()
+                    .Where(x => stockIds.Contains(x.Id))
+                    .ToListAsync();
+
+                foreach (var stock in stocks)
+                {
+                    stock.StockStatus = (int)StockStatusEmun.鍏ュ簱瀹屾垚;
+                    stock.LocationCode = task.TargetAddress; // 鏇存柊璐т綅
+                }
+                await _stockService.StockInfoService.Db.Updateable(stocks).ExecuteCommandAsync();
+
+                // 7. 鏇存柊璐т綅鐘舵��
+                var location = await _locationInfoService.Db.Queryable<Dt_LocationInfo>()
+                    .Where(x => x.LocationCode == task.TargetAddress)
+                    .FirstAsync();
+                if (location != null)
+                {
+                    location.LocationStatus = (int)LocationStatusEnum.InStock;
+                    await _locationInfoService.Db.Updateable(location).ExecuteCommandAsync();
+                }
+
+                //  鏇存柊浠诲姟鐘舵�佷负宸插畬鎴�
+                task.TaskStatus = (int)TaskStatusEnum.Finish;
+
+                await Db.Updateable(task).ExecuteCommandAsync();
+
+                _unitOfWorkManage.CommitTran();
+
+                return WebResponseContent.Instance.OK("鍥炲簱瀹屾垚", new
+                {
+                    TaskNum = task.TaskNum,
+                    PalletCode = task.PalletCode,
+                    RestoredQuantity = lockInfos.Sum(x => x.AssignQuantity - x.PickedQty)
+                });
+            }
+            catch (Exception ex)
+            {
+                _unitOfWorkManage.RollbackTran();
+                return WebResponseContent.Instance.Error($"鍥炲簱瀹屾垚澶勭悊澶辫触: {ex.Message}");
+            }
+        }
+
+        /// <summary>
+        /// 鎭㈠搴撳瓨鍑哄簱鏁伴噺锛堝洖搴撶殑閮ㄥ垎锛�
+        /// </summary>
+        private async Task RestoreStockOutboundQuantity(List<Dt_OutStockLockInfo> lockInfos)
+        {
+            // 鎸夊簱瀛業D鍜岀墿鏂欏垎缁�
+            var stockGroups = lockInfos.GroupBy(x => new { x.StockId, x.MaterielCode });
+
+            foreach (var group in stockGroups)
+            {
+                var stockId = group.Key.StockId;
+                var materielCode = group.Key.MaterielCode;
+                var totalUnpicked = group.Sum(x => x.AssignQuantity - x.PickedQty);
+
+                if (totalUnpicked <= 0) continue;
+
+                // 鑾峰彇璇ョ墿鏂欏湪搴撳瓨涓殑鎵�鏈夋潯鐮�
+                var stockDetails = await _stockService.StockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
+                    .Where(x => x.StockId == stockId && x.MaterielCode == materielCode)
+                    .ToListAsync();
+
+                if (!stockDetails.Any()) continue;
+
+                // 鎸夊嚭搴撴暟閲忕殑姣斾緥鍒嗛厤鎭㈠鏁伴噺
+                var totalOutbound = stockDetails.Sum(x => x.OutboundQuantity);
+
+                if (totalOutbound <= 0) continue;
+
+                foreach (var detail in stockDetails)
+                {
+                    if (detail.OutboundQuantity <= 0) continue;
+
+                    decimal ratio = detail.OutboundQuantity / totalOutbound;
+                    decimal restoreAmount = Math.Min(detail.OutboundQuantity, totalUnpicked * ratio);
+
+                    detail.OutboundQuantity -= restoreAmount;
+                    await _stockService.StockInfoDetailService.Db.Updateable(detail).ExecuteCommandAsync();
+                }
+            }
+        }
+
     }
 }

--
Gitblit v1.9.3