From 064c1aac6fe47bf4e6d576fbe6a7c78a70cda2dd Mon Sep 17 00:00:00 2001
From: heshaofeng <heshaofeng@hnkhzn.com>
Date: 星期三, 03 十二月 2025 10:44:21 +0800
Subject: [PATCH] 1

---
 项目代码/WMS无仓储版/WIDESEA_WMSServer/WIDESEA_BasicService/InvokeMESService.cs |  585 ++++++++++++++++++++++++++++++++++++++++++++--------------
 1 files changed, 442 insertions(+), 143 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_BasicService/InvokeMESService.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_BasicService/InvokeMESService.cs"
index 4ad3447..81ba670 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_BasicService/InvokeMESService.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_BasicService/InvokeMESService.cs"
@@ -1,4 +1,6 @@
-锘縰sing Microsoft.Extensions.Logging;
+锘縰sing Dm.filter;
+using MailKit.Search;
+using Microsoft.Extensions.Logging;
 using Newtonsoft.Json;
 using Org.BouncyCastle.Asn1.Ocsp;
 using SqlSugar;
@@ -7,6 +9,7 @@
 using System.Linq;
 using System.Net;
 using System.Net.Http;
+using System.Reflection.Metadata;
 using System.Security.Policy;
 using System.Text;
 using System.Threading.Tasks;
@@ -14,6 +17,7 @@
 using WIDESEA_Common.StockEnum;
 using WIDESEA_Core;
 using WIDESEA_Core.BaseRepository;
+using WIDESEA_Core.Helper;
 using WIDESEA_DTO.Allocate;
 using WIDESEA_DTO.Basic;
 using WIDESEA_DTO.Inbound;
@@ -24,6 +28,30 @@
 
 namespace WIDESEA_BasicService
 {
+    public class TransferDataDto
+    {
+        public DateTime TransferTime { get; set; }
+        public List<TransferItemDto> Items { get; set; }
+    }
+
+    public class TransferItemDto
+    {
+        public string MaterialCode { get; set; }
+        public decimal TotalQuantity { get; set; }
+        public List<LocationInfoDto> Locations { get; set; }
+    }
+    public class LocationInfoDto
+    {
+        public string LocationCode { get; set; }
+        public decimal Quantity { get; set; }
+        public List<BarcodeInfoDto> Barcodes { get; set; }
+    }
+
+    public class BarcodeInfoDto
+    {
+        public string Barcode { get; set; }
+        public decimal Quantity { get; set; }
+    }
     public class InvokeMESService : IInvokeMESService
     {
         private readonly IHttpClientFactory _httpClientFactory;
@@ -35,11 +63,12 @@
         private readonly IRepository<Dt_StockInfoDetail> _stockInfoDetailRepository;
         private readonly IRepository<Dt_StockInfo> _stockInfoRepository;
         private readonly IRepository<Dt_InboundOrder> _inboundOrderRepository;
-
+        private readonly IRepository<Dt_PickingRecord> _pickingRecoreRepository;
+        private readonly IMaterialUnitService _materialUnitService;
         private readonly IOutboundOrderService _outboundOrderService;
         private readonly IOutboundOrderDetailService _outboundOrderDetailService;
         private readonly IOutStockLockInfoService _outStockLockInfoService;
-        public InvokeMESService(IHttpClientFactory httpClientFactory, ILogger<InvokeMESService> logger, IRepository<Dt_FeedbackToMes> feedbacktomesRepository, IRepository<Dt_StockInfoDetail> stockInfoDetailRepository, IRepository<Dt_StockInfo> stockInfoRepository, IRepository<Dt_InboundOrder> inboundOrderRepository, IOutboundOrderService outboundOrderService, IOutboundOrderDetailService outboundOrderDetailService, IOutStockLockInfoService outStockLockInfoService)
+        public InvokeMESService(IHttpClientFactory httpClientFactory, ILogger<InvokeMESService> logger, IRepository<Dt_FeedbackToMes> feedbacktomesRepository, IRepository<Dt_StockInfoDetail> stockInfoDetailRepository, IRepository<Dt_StockInfo> stockInfoRepository, IRepository<Dt_InboundOrder> inboundOrderRepository, IOutboundOrderService outboundOrderService, IOutboundOrderDetailService outboundOrderDetailService, IOutStockLockInfoService outStockLockInfoService, IMaterialUnitService materialUnitService, IRepository<Dt_PickingRecord> pickingRecoreRepository)
         {
             _httpClientFactory = httpClientFactory;
             _logger = logger;
@@ -50,6 +79,8 @@
             _outboundOrderService = outboundOrderService;
             _outboundOrderDetailService = outboundOrderDetailService;
             _outStockLockInfoService = outStockLockInfoService;
+            _materialUnitService = materialUnitService;
+            _pickingRecoreRepository = pickingRecoreRepository;
         }
 
         /// <summary>
@@ -108,7 +139,7 @@
 
                 throw new HttpRequestException(body);
             }
-
+            _logger.LogInformation("InvokeMESService  FeedbackOutbound  body:  " + body);
 
             return JsonConvert.DeserializeObject<ResponseModel>(body);
         }
@@ -218,6 +249,58 @@
         }
 
         /// <summary>
+        /// 鍑嗗鍥炰紶鏁版嵁
+        /// </summary>
+        private TransferDataDto PrepareTransferData(List<Dt_PickingRecord> pickingRecords)
+        {
+            var transferData = new TransferDataDto
+            {
+                TransferTime = DateTime.Now,
+                Items = new List<TransferItemDto>()
+            };
+
+            // 鎸夌墿鏂欏垎缁�
+            var materialGroups = pickingRecords
+                .GroupBy(x => x.MaterielCode)
+                .ToList();
+
+            foreach (var group in materialGroups)
+            {
+                var item = new TransferItemDto
+                {
+                    MaterialCode = group.Key,
+                    TotalQuantity = group.Sum(x => x.PickQuantity),
+                    Locations = new List<LocationInfoDto>()
+                };
+
+                // 鎸夎揣浣嶅垎缁�
+                var locationGroups = group
+                    .GroupBy(x => x.LocationCode)
+                    .ToList();
+
+                foreach (var locationGroup in locationGroups)
+                {
+                    var location = new LocationInfoDto
+                    {
+                        LocationCode = locationGroup.Key,
+                        Quantity = locationGroup.Sum(x => x.PickQuantity),
+                        Barcodes = locationGroup.Select(x => new BarcodeInfoDto
+                        {
+                            Barcode = x.Barcode,
+                            Quantity = x.PickQuantity
+                        }).ToList()
+                    };
+
+                    item.Locations.Add(location);
+                }
+
+                transferData.Items.Add(item);
+            }
+
+            return transferData;
+        }
+
+        /// <summary>
         /// 
         /// </summary>
         /// <param name="orderNos"></param>
@@ -248,42 +331,88 @@
                                 var inboundOrder = _inboundOrderRepository.Db.Queryable<Dt_InboundOrder>().First(x => x.InboundOrderNo == lists.FirstOrDefault().OrderNo);
                                 if (inboundOrder != null)
                                 {
-                                    var feedmodel = new FeedbackInboundRequestModel
+                                    if (inboundOrder.OrderType == (int)InOrderTypeEnum.AllocatInbound)//璋冩嫧鍏ュ簱
                                     {
-                                        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 allocate = SqlSugarHelper.DbWMS.Queryable<Dt_AllocateOrder>().Where(x => x.OrderNo == inboundOrder.InboundOrderNo).First();
+                                        var allocatefeedmodel = new AllocateDto
+                                        {
+                                            ReqCode = Guid.NewGuid().ToString(),
+                                            ReqTime = DateTime.Now.ToString(),
+                                            BusinessType = "2",
+                                            FactoryArea = inboundOrder.FactoryArea,
+                                            OperationType = 1,
+                                            Operator = inboundOrder.Operator,
+                                            OrderNo = inboundOrder.UpperOrderNo,
+                                            fromWarehouse = allocate?.FromWarehouse ?? "",
+                                            toWarehouse = allocate?.ToWarehouse ?? "",
+                                            Details = new List<AllocateDtoDetail>()
 
-                                    };
+                                        };
 
-                                    var groupedData = lists.GroupBy(item => new { item.MaterielCode, item.SupplyCode, item.BatchNo, item.InboundOrderRowNo, item.BarcodeUnit, item.WarehouseCode })
-                                       .Select(group => new FeedbackInboundDetailsModel
-                                       {
-                                           materialCode = group.Key.MaterielCode,
-                                           supplyCode = group.Key.SupplyCode,
-                                           batchNo = group.Key.BatchNo,
-                                           lineNo = group.Key.InboundOrderRowNo,
-                                           qty = group.Sum(x => x.BarcodeQty),
-                                           // warehouseCode = group.Key.WarehouseCode=="0"?"1072": group.Key.WarehouseCode,
-                                           warehouseCode = group.Key.WarehouseCode,
-                                           unit = group.Key.BarcodeUnit,
-                                           barcodes = group.Select(row => new FeedbackBarcodesModel
+                                        var groupedData = lists.GroupBy(item => new { item.MaterielCode, item.InboundOrderRowNo, item.BarcodeUnit, item.WarehouseCode })
+                                           .Select(group => new AllocateDtoDetail
                                            {
-                                               barcode = row.Barcode,
-                                               qty = row.BarcodeQty
-                                           }).ToList()
-                                       }).ToList();
-                                    feedmodel.details = groupedData;
-                                    var result = await FeedbackInbound(feedmodel);
-                                    if (result != null && result.code == 200)
+                                               MaterialCode = group.Key.MaterielCode,
+                                               LineNo = group.Key.InboundOrderRowNo,
+                                               WarehouseCode = group.Key.WarehouseCode,
+                                               Qty = group.Sum(x => x.BarcodeQty),
+                                               Unit = group.Key.BarcodeUnit,
+                                               Barcodes = group.Select(row => new BarcodeInfo
+                                               {
+                                                   Barcode = row.Barcode,
+                                                   Qty = row.BarcodeQty,
+                                                   BatchNo = row.BatchNo,
+                                                   SupplyCode = row.SupplyCode,
+                                                   Unit = row.BarcodeUnit
+                                               }).ToList()
+                                           }).ToList();
+                                        allocatefeedmodel.Details = groupedData;
+
+                                        var result = await FeedbackAllocate(allocatefeedmodel);
+                                        if (result != null && result.code == 200)
+                                        {
+                                            _feedbacktomesRepository.Db.Insertable(new Dt_FeedbackToMes { OrderNo = orderNo, PalletCode = item.PalletCode, ReportStatus = 1 }).ExecuteCommand();
+                                        }
+                                    }
+                                    else
                                     {
-                                        _feedbacktomesRepository.Db.Insertable(new Dt_FeedbackToMes { OrderNo = orderNo, PalletCode = item.PalletCode, ReportStatus = 1 }).ExecuteCommand();
+                                        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 = lists.GroupBy(item => new { item.MaterielCode, item.SupplyCode, item.BatchNo, item.InboundOrderRowNo, item.BarcodeUnit, item.WarehouseCode })
+                                           .Select(group => new FeedbackInboundDetailsModel
+                                           {
+                                               materialCode = group.Key.MaterielCode,
+                                               supplyCode = group.Key.SupplyCode,
+                                               batchNo = group.Key.BatchNo,
+                                               lineNo = group.Key.InboundOrderRowNo,
+                                               qty = group.Sum(x => x.BarcodeQty),
+                                               // warehouseCode = group.Key.WarehouseCode=="0"?"1072": group.Key.WarehouseCode,
+                                               warehouseCode = group.Key.WarehouseCode,
+                                               unit = group.Key.BarcodeUnit,
+                                               barcodes = group.Select(row => new FeedbackBarcodesModel
+                                               {
+                                                   barcode = row.Barcode,
+                                                   qty = row.BarcodeQty
+                                               }).ToList()
+                                           }).ToList();
+                                        feedmodel.details = groupedData;
+                                        var result = await FeedbackInbound(feedmodel);
+                                        if (result != null && result.code == 200)
+                                        {
+                                            _feedbacktomesRepository.Db.Insertable(new Dt_FeedbackToMes { OrderNo = orderNo, PalletCode = item.PalletCode, ReportStatus = 1 }).ExecuteCommand();
+                                        }
                                     }
                                 }
                             }
@@ -304,161 +433,314 @@
                     var outboundOrder = await _outboundOrderService.Db.Queryable<Dt_OutboundOrder>().FirstAsync(x => x.OrderNo == orderNo);
                     if (outboundOrder != null && outboundOrder.IsBatch == 0)
                     {
-                        await HandleOutboundOrderToMESCompletion(outboundOrder, orderNo);
+                        var result = await HandleOutboundOrderToMESCompletion(outboundOrder, orderNo);
+                        return result;
                     }
                     else if (outboundOrder != null && outboundOrder.IsBatch == 1)
                     {
-                        await HandleOutboundOrderBatchToMESCompletion(outboundOrder, orderNo);
+                        var result = await HandleOutboundOrderBatchToMESCompletion(outboundOrder, orderNo);
+                        return result;
                     }
                 }
 
             }
             return WebResponseContent.Instance.OK();
         }
-        private async Task HandleOutboundOrderBatchToMESCompletion(Dt_OutboundOrder outboundOrder, string orderNo)
-        {
 
+        private async Task<WebResponseContent> HandleOutboundOrderBatchToMESCompletion(Dt_OutboundOrder outboundOrder, string orderNo)
+        {
+            // 瀹氫箟榛樿杩斿洖锛堟垚鍔熸�侊級
+            WebResponseContent response = WebResponseContent.Instance.OK("鍥炰紶MES澶勭悊瀹屾垚");
+            //0 = 鏈洖浼狅紝1 = 宸插洖浼犳垚鍔燂紝2 = 鍥炰紶澶辫触 
             try
             {
+                // 鏍¢獙锛氬凡鍥炰紶鐩存帴杩斿洖閿欒
                 if (outboundOrder.ReturnToMESStatus == 1)
                 {
-                    return;
+                    return WebResponseContent.Instance.Error("璇ュ崟宸茬粡鍥炰紶锛�");
                 }
+
+                // 鏌ヨ璁㈠崟鏄庣粏锛堜粎鏌ヨ鏈洖浼犳垚鍔熺殑锛�
                 var orderDetails = await _outboundOrderDetailService.Db.Queryable<Dt_OutboundOrderDetail>()
                     .LeftJoin<Dt_OutboundOrder>((o, item) => o.OrderId == item.Id)
                     .Where((o, item) => item.OrderNo == orderNo && item.ReturnToMESStatus != 1)
                     .Select((o, item) => o)
                     .ToListAsync();
 
-                var detailids = new List<int>();
-                var allCompleted = true;
-                foreach (var detail in orderDetails.Where(x => x.ReturnToMESStatus == 0).ToList())
+                if (!orderDetails.Any())
                 {
-                    if (detail.OverOutQuantity >= detail.NeedOutQuantity)
-                    {
-                        detailids.Add(detail.Id);
-                    }
-                    else
-                    {
-                        allCompleted = false;
-                    }
-                }
-                if (orderDetails.Any(x => x.ReturnToMESStatus == 2))
-                {
-                    allCompleted = false;
+                    return WebResponseContent.Instance.Error("鏆傛棤闇�瑕佸鐞嗙殑璁㈠崟鏄庣粏");
                 }
 
-                int newStatus = allCompleted ? (int)OutOrderStatusEnum.鍑哄簱瀹屾垚 : (int)OutOrderStatusEnum.鍑哄簱涓�;
 
-                if (outboundOrder.OrderStatus != newStatus)
-                {
-                    await _outboundOrderService.Db.Updateable<Dt_OutboundOrder>()
-                        .SetColumns(x => x.OrderStatus == newStatus)
-                        .Where(x => x.OrderNo == orderNo)
-                        .ExecuteCommandAsync();
+                var pickingRecords = await _pickingRecoreRepository.Db.Queryable<Dt_PickingRecord>().Where(x => x.OrderNo == orderNo && x.ReturnToMESStatus != 1 && !x.IsCancelled).ToListAsync();
 
-                }
-                var documentno = UniqueValueGenerator.Generate();
-                var feedmodel = new FeedbackOutboundRequestModel
+                if (!pickingRecords.Any())
+                    return WebResponseContent.Instance.Error("娌℃湁闇�瑕佸洖浼犵殑鍒嗘嫞璁板綍");
+
+
+                var documentNo = UniqueValueGenerator.Generate();
+
+
+                var feedModel = new FeedbackOutboundRequestModel
                 {
                     reqCode = Guid.NewGuid().ToString(),
                     reqTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                     business_type = outboundOrder.BusinessType,
                     factoryArea = outboundOrder.FactoryArea,
                     operationType = 1,
-                    Operator = outboundOrder.Operator,
+                    Operator = outboundOrder.Operator!=""? outboundOrder.Operator:App.User.UserName,
                     orderNo = outboundOrder.UpperOrderNo,
-                    documentsNO = documentno,
+                    documentsNO = documentNo,
                     status = outboundOrder.OrderStatus,
                     details = new List<FeedbackOutboundDetailsModel>()
                 };
-
-
-                foreach (var detail in orderDetails.Where(x => detailids.Contains(x.Id)).ToList())
+                var detailIds = new List<int>();
+                // 濉厖鏄庣粏鍜屾潯鐮佷俊鎭�
+                foreach (var detail in orderDetails)
                 {
-                    // 鑾峰彇璇ユ槑缁嗗搴旂殑鏉$爜淇℃伅锛堜粠閿佸畾璁板綍锛�
-                    var detailLocks = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
-                        .Where(x => x.OrderNo == orderNo && detailids.Contains(x.OrderDetailId) &&
-                                   x.Status == (int)OutLockStockStatusEnum.鎷i�夊畬鎴�)
-                        .ToListAsync();
-
+                    // 鏌ヨ璇ユ槑缁嗗搴旂殑閿佸畾鏉$爜璁板綍
+                    var detailPicks = pickingRecords.Where(x => x.OrderNo == orderNo
+                                   && detail.Id == x.OrderDetailId).ToList();
+                    if (!detailPicks.Any())
+                    {
+                        continue;
+                    }
                     var detailModel = new FeedbackOutboundDetailsModel
                     {
                         materialCode = detail.MaterielCode,
-                        lineNo = detail.lineNo, // 娉ㄦ剰锛氳繖閲屽彲鑳介渶瑕佽皟鏁村瓧娈靛悕
+                        lineNo = detail.lineNo,
                         warehouseCode = detail.WarehouseCode,
-                        qty = detail.OverOutQuantity, // 浣跨敤璁㈠崟鏄庣粏鐨勫凡鍑哄簱鏁伴噺
-                        currentDeliveryQty = detail.OverOutQuantity,
-                        unit = detail.Unit,
-                        barcodes = detailLocks.Select(lockInfo => new WIDESEA_DTO.Outbound.BarcodesModel
-                        {
-                            barcode = lockInfo.CurrentBarcode,
-                            supplyCode = lockInfo.SupplyCode,
-                            batchNo = lockInfo.BatchNo,
-                            unit = lockInfo.Unit,
-                            qty = lockInfo.PickedQty // 鏉$爜绾у埆鐨勬暟閲忎粛鐢ㄩ攣瀹氳褰�
-                        }).ToList()
+                        qty = 0,
+                        currentDeliveryQty = 0,
+                        unit = detail.BarcodeUnit,
+                        barcodes = new List<WIDESEA_DTO.Outbound.BarcodesModel>()
                     };
 
-                    feedmodel.details.Add(detailModel);
+                    // 濉厖鏉$爜淇℃伅锛堝惈鍗曚綅杞崲锛�
+                    foreach (var item in detailPicks)
+                    {
+                        if (item.PickQuantity <= 0)
+                        {
+                            continue;
+                        }
+                        var barModel = new WIDESEA_DTO.Outbound.BarcodesModel
+                        {
+                            barcode = item.Barcode,
+                            supplyCode = item.SupplyCode,
+                            batchNo = item.BatchNo,
+                            unit = item.BarcodeUnit,
+                            qty = item.PickQuantity
+                        };
+
+                        // 鍗曚綅涓嶄竴鑷存椂杞崲
+                        if (detail.BarcodeUnit != detail.Unit)
+                        {
+                            var convertResult = await _materialUnitService.ConvertAsync(
+                                item.MaterielCode, item.PickQuantity, detail.Unit, detail.BarcodeUnit);
+                            barModel.unit = convertResult.Unit;
+                            barModel.qty = convertResult.Quantity;
+                        }
+                        else
+                        {
+                            barModel.qty = item.PickQuantity;
+                        }
+                        detailModel.qty += barModel.qty;
+                        detailModel.currentDeliveryQty += barModel.qty;
+                        detailModel.barcodes.Add(barModel);
+                    }
+                    detailIds.Add(detail.Id);
+                    feedModel.details.Add(detailModel);
                 }
 
-                var result = await FeedbackOutbound(feedmodel);
-                if (result != null && result.code == 200)
+                feedModel.details = feedModel.details.GroupBy(item => new { item.materialCode, item.lineNo, item.warehouseCode, item.unit }).Select(group => new FeedbackOutboundDetailsModel
+                {
+                    materialCode = group.Key.materialCode,
+                    lineNo = group.Key.lineNo,
+                    warehouseCode = group.Key.warehouseCode,
+                    qty = group.Sum(x => x.qty),
+                    currentDeliveryQty = group.Sum(x => x.currentDeliveryQty),
+                    unit = group.Key.unit,
+                    barcodes = group.SelectMany(x => x.barcodes.GroupBy(o => new { o.barcode, o.supplyCode, o.batchNo, o.unit }).Select(row => new WIDESEA_DTO.Outbound.BarcodesModel
+                    {
+                        barcode = row.Key.barcode,
+                        supplyCode = row.Key.supplyCode,
+                        batchNo = row.Key.batchNo,
+                        unit = row.Key.unit,
+                        qty = row.Sum(y => y.qty)
+                    })).ToList()
+                }).ToList();
+
+                var allCompleted = true;
+
+                // 绛涢�夊緟鍥炰紶鐨勬槑缁嗭紙ReturnToMESStatus=0锛�
+                var pendingDetails = orderDetails.Where(x => x.ReturnToMESStatus == 0).ToList();
+                foreach (var detail in pendingDetails)
+                {
+                    if (detail.OverOutQuantity < detail.NeedOutQuantity)
+                    {
+                        allCompleted = false;
+                    }
+                }
+
+                // 瀛樺湪鍥炰紶澶辫触鐨勬槑缁嗭紙ReturnToMESStatus=2锛夛紝鏍囪鏈畬鎴�
+                if (orderDetails.Any(x => x.ReturnToMESStatus == 2))
+                {
+                    allCompleted = false;
+                }
+
+                //  鏇存柊璁㈠崟鐘舵��
+                int newStatus = allCompleted ? (int)OutOrderStatusEnum.鍑哄簱瀹屾垚 : (int)OutOrderStatusEnum.鍑哄簱涓�;
+                if (outboundOrder.OrderStatus != newStatus)
                 {
 
-                    await _outboundOrderDetailService.Db.Updateable<Dt_OutboundOrderDetail>()
-                           .SetColumns(it => new Dt_OutboundOrderDetail
-                           {
-                               ReturnToMESStatus = 1,
-                               documentsNO = documentno,
-                           })
-                        .Where(x => detailids.Contains(x.Id))
+                    int updateCount = await _outboundOrderService.Db.Updateable<Dt_OutboundOrder>()
+                        .SetColumns(x => x.OrderStatus == newStatus)
+                        .Where(x => x.OrderNo == orderNo)
                         .ExecuteCommandAsync();
 
-                    if (allCompleted && newStatus == (int)OutOrderStatusEnum.鍑哄簱瀹屾垚)
+                    if (updateCount <= 0)
                     {
-                        await _outboundOrderService.Db.Updateable<Dt_OutboundOrder>()
-                          .SetColumns(x => x.ReturnToMESStatus == 1)
-                          .Where(x => x.OrderNo == orderNo)
-                          .ExecuteCommandAsync();
+                        _logger.LogWarning($"鏇存柊鍑哄簱鍗曠姸鎬佸け璐� - OrderNo: {orderNo}, 鐩爣鐘舵��: {newStatus}");
+
                     }
+                }
+
+
+                // 璋冪敤MES鍥炰紶鎺ュ彛
+                var mesResult = await FeedbackOutbound(feedModel);
+                if (mesResult == null || mesResult.code != 200)
+                {
+
+                    // 鏇存柊鏄庣粏涓哄洖浼犲け璐ワ紙ReturnToMESStatus=2锛�
+                    await _outboundOrderDetailService.Db.Updateable<Dt_OutboundOrderDetail>()
+                        .SetColumns(it => new Dt_OutboundOrderDetail
+                        {
+                            ReturnToMESStatus = 2,
+                            documentsNO = documentNo,
+                        })
+                        .Where(x => detailIds.Contains(x.Id))
+                        .ExecuteCommandAsync();
+
+                    return WebResponseContent.Instance.Error($"鍥炰紶MES澶辫触");
+                }
+                foreach (var record in pickingRecords.Where(x => detailIds.Contains(x.OrderDetailId)).ToList())
+                {
+                    record.ReturnToMESStatus = 1;
+                }
+                var updates = pickingRecords.Where(x => detailIds.Contains(x.OrderDetailId)).ToList();
+                updates.ForEach(x =>
+                {
+                    x.ReturnToMESStatus = 1;
+                });
+                await _pickingRecoreRepository.Db.Updateable(updates).ExecuteCommandAsync();
+                if (allCompleted)
+                {
+                    //MES鍥炰紶鎴愬姛锛氭洿鏂版槑缁嗕负鍥炰紶鎴愬姛鐘舵��
+                    await _outboundOrderDetailService.Db.Updateable<Dt_OutboundOrderDetail>()
+                        .SetColumns(it => new Dt_OutboundOrderDetail
+                        {
+                            ReturnToMESStatus = 1,
+                            documentsNO = documentNo,
+                        })
+                        .Where(x => detailIds.Contains(x.Id))
+                        .ExecuteCommandAsync();
+                }
+                // 鏍¢獙鏄惁鎵�鏈夋槑缁嗛兘瀹屾垚锛屾洿鏂拌鍗曟渶缁堢姸鎬�
+                if (allCompleted && newStatus == (int)OutOrderStatusEnum.鍑哄簱瀹屾垚)
+                {
+                    await _outboundOrderService.Db.Updateable<Dt_OutboundOrder>()
+                        .SetColumns(x => new Dt_OutboundOrder
+                        {
+                            ReturnToMESStatus = 1,
+                            OrderStatus = newStatus
+                        })
+                        .Where(x => x.OrderNo == orderNo)
+                        .ExecuteCommandAsync();
                 }
                 else
                 {
-                    await _outboundOrderDetailService.Db.Updateable<Dt_OutboundOrderDetail>()
-                         .SetColumns(it => new Dt_OutboundOrderDetail
-                         {
-                             ReturnToMESStatus = 2,
-                             documentsNO = documentno,
-                         })
-                      .Where(x => detailids.Contains(x.Id))
-                      .ExecuteCommandAsync();
+                    // 浜屾鏍¢獙鏄惁鎵�鏈夋湭鍥炰紶鏄庣粏閮藉凡瀹屾垚
+                    var dbOrderDetails = await _outboundOrderDetailService.Db.Queryable<Dt_OutboundOrderDetail>()
+                        .LeftJoin<Dt_OutboundOrder>((o, item) => o.OrderId == item.Id)
+                        .Where((o, item) => item.OrderNo == orderNo && item.ReturnToMESStatus != 1)
+                        .Select((o, item) => o)
+                        .ToListAsync();
+
+                    var secAllCompleted = true;
+                    foreach (var detail in dbOrderDetails.Where(x => x.ReturnToMESStatus == 0).ToList())
+                    {
+                        if (detail.OverOutQuantity < detail.NeedOutQuantity)
+                        {
+                            secAllCompleted = false;
+                            break;
+                        }
+                    }
+
+                    if (secAllCompleted)
+                    {
+                        await _outboundOrderService.Db.Updateable<Dt_OutboundOrder>()
+                            .SetColumns(it => new Dt_OutboundOrder
+                            {
+                                ReturnToMESStatus = 1,
+                                OrderStatus = OutOrderStatusEnum.鍑哄簱瀹屾垚.ObjToInt(),
+                            })
+                            .Where(x => x.OrderNo == orderNo)
+                            .ExecuteCommandAsync();
+                    }
                 }
 
+                // 鍥炰紶鎴愬姛鐨勬渶缁堣繑鍥�
+                response = WebResponseContent.Instance.OK($"鍥炰紶MES鎴愬姛锛屽崟鎹彿锛歿documentNo}");
             }
             catch (Exception ex)
             {
-                _logger.LogError($"CheckAndUpdateOrderStatus澶辫触 - OrderNo: {orderNo}, Error: {ex.Message}");
+                // 鍏ㄥ眬寮傚父鎹曡幏锛氳褰曡缁嗘棩蹇� + 杩斿洖閿欒
+                string errorMsg = $"澶勭悊鍑哄簱鍗曞洖浼燤ES鏃跺彂鐢熷紓甯� - OrderNo: {orderNo}, Error: {ex.Message}, StackTrace: {ex.StackTrace}";
+                _logger.LogError(ex, errorMsg); // 璁板綍甯﹀紓甯稿爢鏍堢殑鏃ュ織
+
+                // 寮傚父杩斿洖锛堢粰鍓嶇鐨勫弸濂芥彁绀猴紝闅愯棌鍫嗘爤淇℃伅锛�
+                response = WebResponseContent.Instance.Error("澶勭悊鍥炰紶MES鏃跺彂鐢熷紓甯革紝璇疯仈绯荤鐞嗗憳");
             }
+
+            return response;
         }
 
-
-        private async Task HandleOutboundOrderToMESCompletion(Dt_OutboundOrder outboundOrder, string orderNo)
+        private async Task<WebResponseContent> HandleOutboundOrderToMESCompletion(Dt_OutboundOrder outboundOrder, string orderNo)
         {
+            // 鍓嶇疆鍙傛暟鏍¢獙锛氱┖鍊肩洿鎺ヨ繑鍥為敊璇�
+            if (outboundOrder == null)
+            {
+                return WebResponseContent.Instance.Error("鍑哄簱鍗曞疄浣撲负绌猴紝鏃犳硶澶勭悊鍥炰紶MES");
+            }
+
+            if (string.IsNullOrWhiteSpace(orderNo))
+            {
+                return WebResponseContent.Instance.Error("璁㈠崟鍙蜂负绌猴紝鏃犳硶澶勭悊鍥炰紶MES");
+            }
 
             try
             {
+
                 if (outboundOrder.ReturnToMESStatus == 1)
                 {
-                    return;
+                    return WebResponseContent.Instance.Error($"OrderNo: {orderNo}, 璇ュ崟宸茬粡鍥炰紶锛�");
                 }
+
+
                 var orderDetails = await _outboundOrderDetailService.Db.Queryable<Dt_OutboundOrderDetail>()
                     .LeftJoin<Dt_OutboundOrder>((o, item) => o.OrderId == item.Id)
                     .Where((o, item) => item.OrderNo == orderNo)
                     .Select((o, item) => o)
                     .ToListAsync();
 
+                // 鏃犳槑缁嗗満鏅繑鍥炶鍛�
+                if (!orderDetails.Any())
+                {
+                    return WebResponseContent.Instance.Error($"OrderNo: {orderNo} 鏈煡璇㈠埌璁㈠崟鏄庣粏");
+                }
+
+                // 鍒ゆ柇鏄惁鎵�鏈夋槑缁嗗畬鎴愬嚭搴�
                 bool allCompleted = true;
                 foreach (var detail in orderDetails)
                 {
@@ -469,17 +751,17 @@
                     }
                 }
 
+                //  鏇存柊璁㈠崟鐘舵�侊紙淇璇硶閿欒锛�== 鈫� =锛�
                 int newStatus = allCompleted ? (int)OutOrderStatusEnum.鍑哄簱瀹屾垚 : (int)OutOrderStatusEnum.鍑哄簱涓�;
-
                 if (outboundOrder.OrderStatus != newStatus)
                 {
                     await _outboundOrderService.Db.Updateable<Dt_OutboundOrder>()
-                        .SetColumns(x => x.OrderStatus == newStatus)
+                        .SetColumns(x => x.OrderStatus == newStatus) // 鍏抽敭淇锛氳祴鍊艰�岄潪鍒ゆ柇
                         .Where(x => x.OrderNo == orderNo)
                         .ExecuteCommandAsync();
-
                 }
-                //鍙湁姝e父鍒嗘嫞瀹屾垚鏃舵墠鍚慚ES鍙嶉
+
+                // 浠呭垎鎷e畬鎴愭椂鍚慚ES鍙嶉
                 if (allCompleted && newStatus == (int)OutOrderStatusEnum.鍑哄簱瀹屾垚)
                 {
                     var feedmodel = new FeedbackOutboundRequestModel
@@ -496,40 +778,47 @@
                         details = new List<FeedbackOutboundDetailsModel>()
                     };
 
-
+                    // 鏋勫缓鏄庣粏鏁版嵁
                     foreach (var detail in orderDetails)
                     {
-                        // 鑾峰彇璇ユ槑缁嗗搴旂殑鏉$爜淇℃伅锛堜粠閿佸畾璁板綍锛�
                         var detailLocks = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
                             .Where(x => x.OrderNo == orderNo &&
                                        x.OrderDetailId == detail.Id &&
-                                       x.Status == (int)OutLockStockStatusEnum.鎷i�夊畬鎴�)
+                                       (x.Status == (int)OutLockStockStatusEnum.鎷i�夊畬鎴� || x.Status == (int)OutLockStockStatusEnum.宸插洖搴�))
                             .ToListAsync();
 
-                        var detailModel = new FeedbackOutboundDetailsModel
-                        {
-                            materialCode = detail.MaterielCode,
-                            lineNo = detail.lineNo, // 娉ㄦ剰锛氳繖閲屽彲鑳介渶瑕佽皟鏁村瓧娈靛悕
-                            warehouseCode = detail.WarehouseCode,
-                            qty = detail.OverOutQuantity, // 浣跨敤璁㈠崟鏄庣粏鐨勫凡鍑哄簱鏁伴噺
-                            currentDeliveryQty = detail.OverOutQuantity,
-                            unit = detail.Unit,
-                            barcodes = detailLocks.Select(lockInfo => new WIDESEA_DTO.Outbound.BarcodesModel
+                        var groupdata = detailLocks.GroupBy(item => new { item.MaterielCode, item.lineNo, item.BarcodeUnit, item.WarehouseCode })
+                            .Select(group => new FeedbackOutboundDetailsModel
                             {
-                                barcode = lockInfo.CurrentBarcode,
-                                supplyCode = lockInfo.SupplyCode,
-                                batchNo = lockInfo.BatchNo,
-                                unit = lockInfo.Unit,
-                                qty = lockInfo.PickedQty // 鏉$爜绾у埆鐨勬暟閲忎粛鐢ㄩ攣瀹氳褰�
-                            }).ToList()
-                        };
+                                materialCode = group.Key.MaterielCode,
+                                lineNo = group.Key.lineNo,
+                                warehouseCode = group.Key.WarehouseCode,
+                                qty = group.Sum(x => x.PickedQty),
+                                currentDeliveryQty = group.Sum(x => x.PickedQty),
+                                unit = group.Key.BarcodeUnit,
+                                barcodes = group.Select(lockInfo => new WIDESEA_DTO.Outbound.BarcodesModel
+                                {
+                                    barcode = lockInfo.CurrentBarcode,
+                                    supplyCode = lockInfo.SupplyCode,
+                                    batchNo = lockInfo.BatchNo,
+                                    unit = lockInfo.BarcodeUnit,
+                                    qty = lockInfo.PickedQty
+                                }).ToList()
+                            }).ToList();
 
-                        feedmodel.details.Add(detailModel);
+                        feedmodel.details.AddRange(groupdata);
                     }
 
+                    //  璋冪敤MES鎺ュ彛
                     var result = await FeedbackOutbound(feedmodel);
-                    if (result != null && result.code == 200)
+                    if (result == null)
                     {
+                        return WebResponseContent.Instance.Error($"OrderNo: {orderNo} MES鍥炰紶鎺ュ彛杩斿洖绌�");
+                    }
+
+                    if (result.code == 200)
+                    {
+                        //  鍥炰紶鎴愬姛锛氭洿鏂板洖浼犵姸鎬�
                         await _outboundOrderDetailService.Db.Updateable<Dt_OutboundOrderDetail>()
                             .SetColumns(x => x.ReturnToMESStatus == 1)
                             .Where(x => x.OrderId == outboundOrder.Id)
@@ -539,16 +828,26 @@
                             .SetColumns(x => x.ReturnToMESStatus == 1)
                             .Where(x => x.OrderNo == orderNo)
                             .ExecuteCommandAsync();
+
+                        return WebResponseContent.Instance.OK("鍥炰紶MES鎴愬姛");
+                    }
+                    else
+                    {
+                        var errorMsg = $"OrderNo: {orderNo} 鍥炰紶MES澶辫触锛岄敊璇爜锛歿result.code}锛岄敊璇俊鎭細{result.message ?? "鏃�"}";
+                        _logger.LogError(errorMsg);
+                        return WebResponseContent.Instance.Error(errorMsg);
                     }
                 }
+                return WebResponseContent.Instance.OK("璁㈠崟鐘舵�佸凡鏇存柊锛屾湭瀹屽叏瀹屾垚鍒嗘嫞鏃犻渶鍥炰紶MES");
             }
             catch (Exception ex)
             {
-                _logger.LogError($"CheckAndUpdateOrderStatus澶辫触 - OrderNo: {orderNo}, Error: {ex.Message}");
+                // 鍏ㄥ眬寮傚父鎹曡幏锛氳繑鍥為敊璇�+璁板綍璇︾粏鏃ュ織
+                var errorMsg = $"OrderNo: {orderNo} 澶勭悊鍥炰紶MES鏃跺彂鐢熷紓甯革細{ex.Message}";
+                _logger.LogError(ex, errorMsg); // 璁板綍鍫嗘爤淇℃伅渚夸簬鎺掓煡
+                return WebResponseContent.Instance.Error("澶勭悊鍥炰紶MES鏃跺彂鐢熷紓甯革紝璇疯仈绯荤鐞嗗憳");
             }
-
         }
-
     }
 
     public static class UniqueValueGenerator

--
Gitblit v1.9.3