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

---
 项目代码/WMS无仓储版/WIDESEA_WMSServer/WIDESEA_BasicService/InvokeMESService.cs |  306 +++++++++++++++++++++++++++++++++++++++++++++++++-
 1 files changed, 295 insertions(+), 11 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 a14fd53..34e8220 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"
@@ -10,6 +10,8 @@
 using System.Security.Policy;
 using System.Text;
 using System.Threading.Tasks;
+using WIDESEA_Common.OrderEnum;
+using WIDESEA_Common.StockEnum;
 using WIDESEA_Core;
 using WIDESEA_Core.BaseRepository;
 using WIDESEA_DTO.Allocate;
@@ -17,6 +19,7 @@
 using WIDESEA_DTO.Inbound;
 using WIDESEA_DTO.Outbound;
 using WIDESEA_IBasicService;
+using WIDESEA_IOutboundService;
 using WIDESEA_Model.Models;
 
 namespace WIDESEA_BasicService
@@ -32,7 +35,11 @@
         private readonly IRepository<Dt_StockInfoDetail> _stockInfoDetailRepository;
         private readonly IRepository<Dt_StockInfo> _stockInfoRepository;
         private readonly IRepository<Dt_InboundOrder> _inboundOrderRepository;
-        public InvokeMESService(IHttpClientFactory httpClientFactory, ILogger<InvokeMESService> logger, IRepository<Dt_FeedbackToMes> feedbacktomesRepository, IRepository<Dt_StockInfoDetail> stockInfoDetailRepository, IRepository<Dt_StockInfo> stockInfoRepository, IRepository<Dt_InboundOrder> inboundOrderRepository)
+
+        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)
         {
             _httpClientFactory = httpClientFactory;
             _logger = logger;
@@ -40,6 +47,9 @@
             _stockInfoDetailRepository = stockInfoDetailRepository;
             _stockInfoRepository = stockInfoRepository;
             _inboundOrderRepository = inboundOrderRepository;
+            _outboundOrderService = outboundOrderService;
+            _outboundOrderDetailService = outboundOrderDetailService;
+            _outStockLockInfoService = outStockLockInfoService;
         }
 
         /// <summary>
@@ -50,8 +60,8 @@
         /// <exception cref="HttpRequestException"></exception>
         public async Task<ResponseModel> FeedbackInbound(FeedbackInboundRequestModel model)
         {
-            string json =JsonConvert.SerializeObject(model, new JsonSerializerSettings
-            {           
+            string json = JsonConvert.SerializeObject(model, new JsonSerializerSettings
+            {
                 ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
             });
             var content = new StringContent(json, Encoding.UTF8, "application/json");
@@ -70,7 +80,7 @@
 
             return JsonConvert.DeserializeObject<ResponseModel>(body);
         }
-             
+
         /// <summary>
         /// 鍑哄簱鍙嶉
         /// </summary>
@@ -103,7 +113,7 @@
             return JsonConvert.DeserializeObject<ResponseModel>(body);
         }
 
-        public  async Task<ResponseModel> FeedbackAllocate(AllocateDto model)
+        public async Task<ResponseModel> FeedbackAllocate(AllocateDto model)
         {
             string json = JsonConvert.SerializeObject(model, new JsonSerializerSettings
             {
@@ -224,7 +234,8 @@
                                         .ToList();
                         var feeds = _feedbacktomesRepository.Db.Queryable<Dt_FeedbackToMes>().Where(x => x.OrderNo == orderNo && x.ReportStatus == 1).Select(o => o.PalletCode).ToList();
                         var unreports = stockinfos.Where(x => !feeds.Contains(x.PalletCode)).ToList();
-                        if (unreports!=null && !unreports.Any()) {
+                        if (unreports != null && !unreports.Any())
+                        {
                             return WebResponseContent.Instance.Error("娌℃湁闇�瑕佸洖浼犵殑鏁版嵁");
                         }
                         foreach (var item in unreports)
@@ -241,14 +252,14 @@
                                         reqTime = DateTime.Now.ToString(),
                                         business_type = inboundOrder.BusinessType,
                                         factoryArea = inboundOrder.FactoryArea,
-                                        operationType=1,
-                                        Operator= inboundOrder.Operator,
+                                        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
                                        {
@@ -256,9 +267,9 @@
                                            supplyCode = group.Key.SupplyCode,
                                            batchNo = group.Key.BatchNo,
                                            lineNo = group.Key.InboundOrderRowNo,
-                                           qty = group.Sum(x=>x.BarcodeQty),
+                                           qty = group.Sum(x => x.BarcodeQty),
                                            // warehouseCode = group.Key.WarehouseCode=="0"?"1072": group.Key.WarehouseCode,
-                                           warehouseCode =group.Key.WarehouseCode,
+                                           warehouseCode = group.Key.WarehouseCode,
                                            unit = group.Key.BarcodeUnit,
                                            barcodes = group.Select(row => new FeedbackBarcodesModel
                                            {
@@ -284,7 +295,280 @@
 
                 }
             }
+            else if (inout == 2)
+            {
+                foreach (var orderNo in orderNos)
+                {
+                    var outboundOrder = await _outboundOrderService.Db.Queryable<Dt_OutboundOrder>().FirstAsync(x => x.OrderNo == orderNo);
+                    if (outboundOrder != null && outboundOrder.IsBatch == 0)
+                    {
+                        await HandleOutboundOrderToMESCompletion(outboundOrder, orderNo);
+                    }
+                    else if (outboundOrder != null && outboundOrder.IsBatch == 1)
+                    {
+                        await HandleOutboundOrderBatchToMESCompletion(outboundOrder, orderNo);
+                    }
+                }
+
+            }
             return WebResponseContent.Instance.OK();
         }
+        private async Task HandleOutboundOrderBatchToMESCompletion(Dt_OutboundOrder outboundOrder, string orderNo)
+        {
+
+            try
+            {
+                if (outboundOrder.ReturnToMESStatus == 1)
+                {
+                    return;
+                }
+                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 (detail.OverOutQuantity >= detail.NeedOutQuantity)
+                    {
+                        detailids.Add(detail.Id);
+                    }
+                    else
+                    {
+                        allCompleted = false;
+                    }
+                }
+                if (orderDetails.Any(x => x.ReturnToMESStatus == 2))
+                {
+                    allCompleted = false;
+                }
+
+                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 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,
+                    orderNo = outboundOrder.UpperOrderNo,
+                    documentsNO = documentno,
+                    status = outboundOrder.OrderStatus,
+                    details = new List<FeedbackOutboundDetailsModel>()
+                };
+
+
+                foreach (var detail in orderDetails.Where(x => detailids.Contains(x.Id)).ToList())
+                {
+                    // 鑾峰彇璇ユ槑缁嗗搴旂殑鏉$爜淇℃伅锛堜粠閿佸畾璁板綍锛�
+                    var detailLocks = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
+                        .Where(x => x.OrderNo == orderNo && detailids.Contains(x.OrderDetailId) &&
+                                   x.Status == (int)OutLockStockStatusEnum.鎷i�夊畬鎴�)
+                        .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
+                        {
+                            barcode = lockInfo.CurrentBarcode,
+                            supplyCode = lockInfo.SupplyCode,
+                            batchNo = lockInfo.BatchNo,
+                            unit = lockInfo.Unit,
+                            qty = lockInfo.PickedQty // 鏉$爜绾у埆鐨勬暟閲忎粛鐢ㄩ攣瀹氳褰�
+                        }).ToList()
+                    };
+
+                    feedmodel.details.Add(detailModel);
+                }
+
+                var result = await FeedbackOutbound(feedmodel);
+                if (result != null && result.code == 200)
+                {
+
+                    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 => x.ReturnToMESStatus == 1)
+                          .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();
+                }
+
+            }
+            catch (Exception ex)
+            {
+                _logger.LogError($"CheckAndUpdateOrderStatus澶辫触 - OrderNo: {orderNo}, Error: {ex.Message}");
+            }
+        }
+
+
+        private async Task HandleOutboundOrderToMESCompletion(Dt_OutboundOrder outboundOrder, string orderNo)
+        {
+
+            try
+            {
+                if (outboundOrder.ReturnToMESStatus == 1)
+                {
+                    return;
+                }
+                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();
+
+                bool allCompleted = true;
+                foreach (var detail in orderDetails)
+                {
+                    if (detail.OverOutQuantity < detail.NeedOutQuantity)
+                    {
+                        allCompleted = false;
+                        break;
+                    }
+                }
+
+                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();
+
+                }
+                //鍙湁姝e父鍒嗘嫞瀹屾垚鏃舵墠鍚慚ES鍙嶉
+                if (allCompleted && newStatus == (int)OutOrderStatusEnum.鍑哄簱瀹屾垚)
+                {
+                    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,
+                        orderNo = outboundOrder.UpperOrderNo,
+                        documentsNO = outboundOrder.OrderNo,
+                        status = outboundOrder.OrderStatus,
+                        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�夊畬鎴�)
+                            .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
+                            {
+                                barcode = lockInfo.CurrentBarcode,
+                                supplyCode = lockInfo.SupplyCode,
+                                batchNo = lockInfo.BatchNo,
+                                unit = lockInfo.Unit,
+                                qty = lockInfo.PickedQty // 鏉$爜绾у埆鐨勬暟閲忎粛鐢ㄩ攣瀹氳褰�
+                            }).ToList()
+                        };
+
+                        feedmodel.details.Add(detailModel);
+                    }
+
+                    var result = await FeedbackOutbound(feedmodel);
+                    if (result != null && result.code == 200)
+                    {
+                        await _outboundOrderDetailService.Db.Updateable<Dt_OutboundOrderDetail>()
+                            .SetColumns(x => x.ReturnToMESStatus == 1)
+                            .Where(x => x.OrderId == outboundOrder.Id)
+                            .ExecuteCommandAsync();
+
+                        await _outboundOrderService.Db.Updateable<Dt_OutboundOrder>()
+                            .SetColumns(x => x.ReturnToMESStatus == 1)
+                            .Where(x => x.OrderNo == orderNo)
+                            .ExecuteCommandAsync();
+                    }
+                }
+            }
+            catch (Exception ex)
+            {
+                _logger.LogError($"CheckAndUpdateOrderStatus澶辫触 - OrderNo: {orderNo}, Error: {ex.Message}");
+            }
+
+        }
+
+    }
+
+    public static class UniqueValueGenerator
+    {
+        // 鍘熷瓙璁℃暟鍣紙绾跨▼瀹夊叏锛屾瘡娆¢�掑1锛岄伩鍏嶅悓涓�Ticks閲嶅锛�
+        private static long _counter = 0;
+
+        /// <summary>
+        /// 鐢熸垚鍞竴鍊硷紙鏀寔楂樺苟鍙戯級
+        /// </summary>
+        /// <returns>鏍煎紡锛歽yyyMMdd + Ticks + 3浣嶈鏁板櫒锛堝2025112563867890123001锛�</returns>
+        public static string Generate()
+        {
+            var now = DateTime.Now;
+            string datePart = now.ToString("yyyyMMdd");
+            long ticksPart = now.Ticks;
+
+            // 鍘熷瓙閫掑璁℃暟鍣紙鍙栨ā1000锛岀‘淇濊鏁板櫒浠�3浣嶏紝鎺у埗闀垮害锛�
+            long counterPart = Interlocked.Increment(ref _counter) % 1000;
+
+            // 鎷兼帴锛氳鏁板櫒琛�0涓�3浣嶏紙閬垮厤浣嶆暟涓嶄竴鑷达級
+            return $"{datePart}{ticksPart}{counterPart:D3}";
+        }
     }
 }

--
Gitblit v1.9.3