From f692f869d5fe2e2aee9d3487dbba83e1821b7f6c Mon Sep 17 00:00:00 2001
From: pan <antony1029@163.com>
Date: 星期四, 04 十二月 2025 18:02:19 +0800
Subject: [PATCH] 提交

---
 项目代码/WMS无仓储版/WIDESEA_WMSServer/WIDESEA_BasicService/InvokeMESService.cs |  807 +++++++++++++++++++++++++++++++++++++++++++++++++++++----
 1 files changed, 747 insertions(+), 60 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 c6ee79d..7d8276f 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,21 +1,30 @@
-锘縰sing Microsoft.Extensions.Logging;
+锘縰sing Dm.filter;
+using MailKit.Search;
+using Microsoft.Extensions.Logging;
 using Newtonsoft.Json;
 using Org.BouncyCastle.Asn1.Ocsp;
 using SqlSugar;
 using System;
+using System.Collections.Concurrent;
 using System.Collections.Generic;
 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;
+using WIDESEA_Common.OrderEnum;
+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;
 using WIDESEA_DTO.Outbound;
 using WIDESEA_IBasicService;
+using WIDESEA_IOutboundService;
 using WIDESEA_Model.Models;
 
 namespace WIDESEA_BasicService
@@ -31,7 +40,18 @@
         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 IRepository<Dt_PickingRecord> _pickingRecoreRepository;
+        private readonly IMaterialUnitService _materialUnitService;
+        private readonly IOutboundOrderService _outboundOrderService;
+        private readonly IOutboundOrderDetailService _outboundOrderDetailService;
+        private readonly IOutStockLockInfoService _outStockLockInfoService;
+
+        // 瀛樺偍璧勬簮ID鍙婂叾瀵瑰簲鐨勯攣瀵硅薄銆備娇鐢� ConcurrentDictionary 纭繚瀵瑰瓧鍏告搷浣滄湰韬殑绾跨▼瀹夊叏銆�
+        private static readonly ConcurrentDictionary<string, object> _resourceLocks = new ConcurrentDictionary<string, object>();
+
+        // 鍏ㄥ眬闈欐�侀攣锛氱敤浜庝繚鎶� _resourceLocks 瀛楀吀涓� GetOrAdd 鎴� TryRemove 鏃剁殑绔炰簤
+        private static readonly object _globalLocker = new object();
+        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;
@@ -39,12 +59,23 @@
             _stockInfoDetailRepository = stockInfoDetailRepository;
             _stockInfoRepository = stockInfoRepository;
             _inboundOrderRepository = inboundOrderRepository;
+            _outboundOrderService = outboundOrderService;
+            _outboundOrderDetailService = outboundOrderDetailService;
+            _outStockLockInfoService = outStockLockInfoService;
+            _materialUnitService = materialUnitService;
+            _pickingRecoreRepository = pickingRecoreRepository;
         }
 
+        /// <summary>
+        /// 鍏ュ簱鍙嶉
+        /// </summary>
+        /// <param name="model"></param>
+        /// <returns></returns>
+        /// <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");
@@ -64,7 +95,13 @@
             return JsonConvert.DeserializeObject<ResponseModel>(body);
         }
 
-        public async Task FeedbackOutbound(FeedbackOutboundRequestModel model)
+        /// <summary>
+        /// 鍑哄簱鍙嶉
+        /// </summary>
+        /// <param name="model"></param>
+        /// <returns></returns>
+        /// <exception cref="HttpRequestException"></exception>
+        public async Task<ResponseModel> FeedbackOutbound(FeedbackOutboundRequestModel model)
         {
             string json = JsonConvert.SerializeObject(model, new JsonSerializerSettings
             {
@@ -75,6 +112,8 @@
             _client.DefaultRequestHeaders.Clear();
             _client.DefaultRequestHeaders.Add("Accept", "application/json");
 
+            _logger.LogInformation("InvokeMESService  FeedbackOutbound :  " + model.orderNo + "  , " + json);
+
             var response = await _client.PostAsync("AldMaterialOutbound/MaterialOutbound", content);
             string body = await response.Content.ReadAsStringAsync();
 
@@ -83,8 +122,34 @@
 
                 throw new HttpRequestException(body);
             }
+            _logger.LogInformation("InvokeMESService  FeedbackOutbound  body:  " + body);
 
-            // JsonConvert.DeserializeObject<ResponseModel>(body);
+            return JsonConvert.DeserializeObject<ResponseModel>(body);
+        }
+
+        public async Task<ResponseModel> FeedbackAllocate(AllocateDto model)
+        {
+            _logger.LogInformation($"InvokeMESService  FeedbackAllocate  搴忓垪鍖栧墠: {JsonConvert.SerializeObject(model)}");
+            string json = JsonConvert.SerializeObject(model, new JsonSerializerSettings
+            {
+                ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(),
+                NullValueHandling = NullValueHandling.Include
+            });
+            var content = new StringContent(json, Encoding.UTF8, "application/json");
+            var _client = _httpClientFactory.CreateClient("MESUrl");
+            _client.DefaultRequestHeaders.Clear();
+            _client.DefaultRequestHeaders.Add("Accept", "application/json");
+            _logger.LogInformation("InvokeMESService  FeedbackAllocate :  " + json);
+            var response = await _client.PostAsync("AldAllocationOperation/AllocationOperation", content);
+            string body = await response.Content.ReadAsStringAsync();
+            _logger.LogInformation("InvokeMESService  FeedbackAllocate  body:  " + body);
+            if (!response.IsSuccessStatusCode)
+            {
+
+                throw new HttpRequestException(body);
+            }
+
+            return JsonConvert.DeserializeObject<ResponseModel>(body);
         }
 
         public async Task<ResponseModel> NewMaterielToMes(MaterielToMesDTO model)
@@ -113,8 +178,11 @@
 
             var content = new StringContent(json, Encoding.UTF8, "application/json");
 
-            using var response = await client.PostAsync("", content);
+            _logger.LogInformation("InvokeMESService  NewMaterielToMes :  " + json);
+
+            using var response = await client.PostAsync("AldBarcodeInformation/BarcodeInformation", content);
             var responseText = await response.Content.ReadAsStringAsync();
+            _logger.LogInformation("InvokeMESService  NewMaterielToMes  body:  " + responseText);
             if (!response.IsSuccessStatusCode)
             {
                 throw new HttpRequestException(responseText);
@@ -163,6 +231,8 @@
             }
         }
 
+
+
         /// <summary>
         /// 
         /// </summary>
@@ -171,77 +241,694 @@
         /// <returns></returns>
         public async Task<WebResponseContent> BatchOrderFeedbackToMes(List<string> orderNos, int inout)
         {
-            if (inout == 1)
+            // 1. 銆愬唴瀛橀攣鎶㈠崰銆�
+            if (MemoryLockManager.TryAcquireLock(orderNos[0]))
             {
-                foreach (var orderNo in orderNos)
+                try
                 {
-                    try
+                    if (inout == 1)
                     {
-                        var stockinfos = _stockInfoRepository.Db.Queryable<Dt_StockInfo>("info").Where(info => info.StockStatus == 6)
-                                        .Where(it => SqlFunc.Subqueryable<Dt_StockInfoDetail>().Where(s => s.StockId == it.Id && s.OrderNo == orderNo).Any())
-                                        .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()) {
-                            return WebResponseContent.Instance.Error("娌℃湁闇�瑕佸洖浼犵殑鏁版嵁");
-                        }
-                        foreach (var item in unreports)
+                        foreach (var orderNo in orderNos)
                         {
-                            var lists = _stockInfoDetailRepository.Db.Queryable<Dt_StockInfoDetail>().Where(x => x.StockId == item.Id).ToList();
-                            if (lists.Any())
+                            try
                             {
-                                var inboundOrder = _inboundOrderRepository.Db.Queryable<Dt_InboundOrder>().First(x => x.InboundOrderNo == lists.FirstOrDefault().OrderNo);
-                                if (inboundOrder != null)
+                                var stockinfos = _stockInfoRepository.Db.Queryable<Dt_StockInfo>("info").Where(info => info.StockStatus == 6)
+                                                .Where(it => SqlFunc.Subqueryable<Dt_StockInfoDetail>().Where(s => s.StockId == it.Id && s.OrderNo == orderNo).Any())
+                                                .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())
                                 {
-                                    var feedmodel = new FeedbackInboundRequestModel
+                                    return WebResponseContent.Instance.Error("娌℃湁闇�瑕佸洖浼犵殑鏁版嵁");
+                                }
+                                foreach (var item in unreports)
+                                {
+                                    var lists = _stockInfoDetailRepository.Db.Queryable<Dt_StockInfoDetail>().Where(x => x.StockId == item.Id).ToList();
+                                    if (lists.Any())
                                     {
-                                        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 inboundOrder = _inboundOrderRepository.Db.Queryable<Dt_InboundOrder>().First(x => x.InboundOrderNo == lists.FirstOrDefault().OrderNo);
+                                        if (inboundOrder != null)
+                                        {
+                                            if (inboundOrder.OrderType == (int)InOrderTypeEnum.AllocatInbound)//璋冩嫧鍏ュ簱
+                                            {
+                                                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,
-                                           // 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();
+                                                };
+
+                                                var groupedData = lists.GroupBy(item => new { item.MaterielCode, item.InboundOrderRowNo, item.BarcodeUnit, item.WarehouseCode })
+                                                   .Select(group => new AllocateDtoDetail
+                                                   {
+                                                       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
+                                            {
+                                                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();
+                                                }
+                                            }
+                                        }
                                     }
                                 }
                             }
+                            catch (Exception ex)
+                            {
+                                _logger.LogInformation("InvokeMESService  BatchOrderFeedbackToMes 鍥炲啓MES澶辫触:  " + ex.Message);
+                                return WebResponseContent.Instance.Error(ex.Message);
+                            }
+
                         }
                     }
-                    catch (Exception ex)
+                    else if (inout == 2)
                     {
-                        _logger.LogInformation("InvokeMESService  BatchOrderFeedbackToMes 鍥炲啓MES澶辫触:  " + ex.Message);
-                        return WebResponseContent.Instance.Error(ex.Message);
+                        foreach (var orderNo in orderNos)
+                        {
+                            var outboundOrder = await _outboundOrderService.Db.Queryable<Dt_OutboundOrder>().FirstAsync(x => x.OrderNo == orderNo);
+                            if (outboundOrder != null && outboundOrder.IsBatch == 0)
+                            {
+                                var result = await HandleOutboundOrderToMESCompletion(outboundOrder, orderNo);
+                                return result;
+                            }
+                            else if (outboundOrder != null && outboundOrder.IsBatch == 1)
+                            {
+                                var result = await HandleOutboundOrderBatchToMESCompletion(outboundOrder, orderNo);
+                                return result;
+                            }
+                        }
+
                     }
+                }
+                finally
+                {
+                    // 2. 銆愰噴鏀惧唴瀛橀攣銆戞棤璁烘垚鍔熷け璐ワ紝蹇呴』閲婃斁
+                    MemoryLockManager.ReleaseLock(orderNos[0]);
+                }
+            }
+            else
+            {
+                // 鎶㈤攣澶辫触锛氳鏄庢湁鍙︿竴涓嚎绋嬶紙WCS鍥炶皟鎴栦汉宸ユ搷浣滐級姝e湪澶勭悊
+
+                return WebResponseContent.Instance.OK("WMS姝e湪澶勭悊姝ゅ洖浼犱换鍔★紝璇峰嬁閲嶅鎿嶄綔銆�");
+            }
+            return WebResponseContent.Instance.OK();
+        }
+
+        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 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();
+
+                if (!orderDetails.Any())
+                {
+                    return WebResponseContent.Instance.Error("鏆傛棤闇�瑕佸鐞嗙殑璁㈠崟鏄庣粏");
+                }
+
+
+                var pickingRecords = await _pickingRecoreRepository.Db.Queryable<Dt_PickingRecord>().Where(x => x.OrderNo == orderNo && x.ReturnToMESStatus != 1 && !x.IsCancelled).ToListAsync();
+
+                if (!pickingRecords.Any())
+                    return WebResponseContent.Instance.Error("娌℃湁闇�瑕佸洖浼犵殑鍒嗘嫞璁板綍");
+
+
+                var groups = pickingRecords.GroupBy(x => x.FeedBackMesDocumentNo).ToList();
+                foreach (var group in groups)
+                {
+                    
+                    List<Dt_PickingRecord> records = group.ToList(); // 璇ュ垎缁勪笅鐨勬墍鏈夎褰�
+                    if (string.IsNullOrEmpty(group.Key))
+                    {
+                        var emptydocumentNo = UniqueValueGenerator.Generate();
+                        records.ForEach(x => { x.FeedBackMesDocumentNo = emptydocumentNo; });
+                        var result=   await _pickingRecoreRepository.Db.Insertable(records).ExecuteCommandAsync();
+                        if (result > 0)
+                        {
+                            (bool _flowControl, WebResponseContent _value) = await FeedBackBatchToMes(outboundOrder, orderNo, orderDetails, pickingRecords, emptydocumentNo);
+                            if (!_flowControl)
+                            {
+                                return _value;
+                            }
+                        }
+                    }
+                    else
+                    {
+                        (bool _flowControl, WebResponseContent _value) = await FeedBackBatchToMes(outboundOrder, orderNo, orderDetails, pickingRecords, group.Key);
+                        if (!_flowControl)
+                        {
+                            return _value;
+                        }
+                    }
+                }
+
+
+                //var documentNo = UniqueValueGenerator.Generate();
+
+                //(bool flowControl, WebResponseContent value) = await FeedBackBatchToMes(outboundOrder, orderNo, orderDetails, pickingRecords, documentNo);
+                //if (!flowControl)
+                //{
+                //    return value;
+                //}
+
+                // 鍥炰紶鎴愬姛鐨勬渶缁堣繑鍥�
+                response = WebResponseContent.Instance.OK($"鍥炰紶MES鎴愬姛锛屽崟鎹彿锛歿orderNo}");
+            }
+            catch (Exception ex)
+            {
+                // 鍏ㄥ眬寮傚父鎹曡幏锛氳褰曡缁嗘棩蹇� + 杩斿洖閿欒
+                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<(bool flowControl, WebResponseContent value)> FeedBackBatchToMes(Dt_OutboundOrder outboundOrder, string orderNo, List<Dt_OutboundOrderDetail> orderDetails, List<Dt_PickingRecord> pickingRecords, string documentNo)
+        {
+            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 != "" ? outboundOrder.Operator : App.User.UserName,
+                orderNo = outboundOrder.UpperOrderNo,
+                documentsNO = documentNo,
+                status = outboundOrder.OrderStatus,
+                details = new List<FeedbackOutboundDetailsModel>()
+            };
+            var detailIds = new List<int>();
+            // 濉厖鏄庣粏鍜屾潯鐮佷俊鎭�
+            foreach (var detail in orderDetails)
+            {
+                // 鏌ヨ璇ユ槑缁嗗搴旂殑閿佸畾鏉$爜璁板綍
+                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,
+                    warehouseCode = detail.WarehouseCode,
+                    qty = detail.BarcodeQty,
+                    currentDeliveryQty = 0,
+                    unit = detail.BarcodeUnit,
+                    barcodes = new List<WIDESEA_DTO.Outbound.BarcodesModel>()
+                };
+
+                // 濉厖鏉$爜淇℃伅锛堝惈鍗曚綅杞崲锛�
+                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.currentDeliveryQty += barModel.qty;
+                    detailModel.barcodes.Add(barModel);
+                }
+                detailIds.Add(detail.Id);
+                feedModel.details.Add(detailModel);
+            }
+
+            feedModel.details = feedModel.details.GroupBy(item => new { item.materialCode, item.lineNo, item.warehouseCode, item.unit, item.qty }).Select(group => new FeedbackOutboundDetailsModel
+            {
+                materialCode = group.Key.materialCode,
+                lineNo = group.Key.lineNo,
+                warehouseCode = group.Key.warehouseCode,
+                qty = group.Key.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)
+            {
+
+                int updateCount = await _outboundOrderService.Db.Updateable<Dt_OutboundOrder>()
+                    .SetColumns(x => x.OrderStatus == newStatus)
+                    .Where(x => x.OrderNo == orderNo)
+                    .ExecuteCommandAsync();
+
+                if (updateCount <= 0)
+                {
+                    _logger.LogWarning($"鏇存柊鍑哄簱鍗曠姸鎬佸け璐� - OrderNo: {orderNo}, 鐩爣鐘舵��: {newStatus}");
 
                 }
             }
-            return WebResponseContent.Instance.OK();
+
+
+            // 璋冪敤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 (flowControl: false, value: 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
+            {
+                // 浜屾鏍¢獙鏄惁鎵�鏈夋湭鍥炰紶鏄庣粏閮藉凡瀹屾垚
+                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();
+                }
+            }
+
+            return (flowControl: true, value: null);
+        }
+
+        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 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)
+                {
+                    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�夊畬鎴� || x.Status == (int)OutLockStockStatusEnum.宸插洖搴�))
+                            .ToListAsync();
+
+                        var groupdata = detailLocks.GroupBy(item => new { item.MaterielCode, item.lineNo, item.BarcodeUnit, item.WarehouseCode })
+                            .Select(group => new FeedbackOutboundDetailsModel
+                            {
+                                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.AddRange(groupdata);
+                    }
+
+                    //  璋冪敤MES鎺ュ彛
+                    var result = await FeedbackOutbound(feedmodel);
+                    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)
+                            .ExecuteCommandAsync();
+
+                        await _outboundOrderService.Db.Updateable<Dt_OutboundOrder>()
+                            .SetColumns(x => x.ReturnToMESStatus == 1)
+                            .Where(x => x.OrderNo == orderNo)
+                            .ExecuteCommandAsync();
+
+                        await _pickingRecoreRepository.Db.Updateable<Dt_PickingRecord>()
+                                 .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)
+            {
+                // 鍏ㄥ眬寮傚父鎹曡幏锛氳繑鍥為敊璇�+璁板綍璇︾粏鏃ュ織
+                var errorMsg = $"OrderNo: {orderNo} 澶勭悊鍥炰紶MES鏃跺彂鐢熷紓甯革細{ex.Message}";
+                _logger.LogError(ex, errorMsg); // 璁板綍鍫嗘爤淇℃伅渚夸簬鎺掓煡
+                return WebResponseContent.Instance.Error("澶勭悊鍥炰紶MES鏃跺彂鐢熷紓甯革紝璇疯仈绯荤鐞嗗憳");
+            }
+        }
+    }
+
+    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("MMdd");
+            long ticksPart = now.Ticks;
+            // 鎷兼帴锛氳鏁板櫒琛�0涓�3浣嶏紙閬垮厤浣嶆暟涓嶄竴鑷达級
+            return $"{datePart}{ticksPart}";
+        }
+
+        public static string GenerateCount()
+        {
+            var now = DateTime.Now;
+            string datePart = now.ToString("yyyyMMddHHmmss");
+
+
+            // 鍘熷瓙閫掑璁℃暟鍣紙鍙栨ā1000锛岀‘淇濊鏁板櫒浠�3浣嶏紝鎺у埗闀垮害锛�
+            long counterPart = Interlocked.Increment(ref _counter) % 1000;
+
+            // 鎷兼帴锛氳鏁板櫒琛�0涓�3浣嶏紙閬垮厤浣嶆暟涓嶄竴鑷达級
+            return $"{datePart}{counterPart:D3}";
+        }
+    }
+
+
+    public static class MemoryLockManager
+    {
+        // 瀛樺偍璧勬簮ID鍙婂叾瀵瑰簲鐨勯攣瀵硅薄銆備娇鐢� ConcurrentDictionary 纭繚瀵瑰瓧鍏告搷浣滄湰韬殑绾跨▼瀹夊叏銆�
+        private static readonly ConcurrentDictionary<string, object> _resourceLocks = new ConcurrentDictionary<string, object>();
+
+        // 鍏ㄥ眬闈欐�侀攣锛氱敤浜庝繚鎶� _resourceLocks 瀛楀吀涓� GetOrAdd 鎴� TryRemove 鏃剁殑绔炰簤
+        private static readonly object _globalLocker = new object();
+
+        /// <summary>
+        /// 灏濊瘯閿佸畾涓�涓祫婧怚D銆�
+        /// </summary>
+        /// <param name="resourceId">瑕侀攣瀹氱殑璧勬簮ID锛堜緥濡� InboundRecord ID锛�</param>
+        /// <returns>鏄惁鎴愬姛鑾峰彇閿�</returns>
+        public static bool TryAcquireLock(string resourceId)
+        {
+            object lockObject = null;
+
+            // 鏍稿績鎬濊矾锛氫负姣忎釜璧勬簮鍒涘缓涓�涓敮涓�鐨勯攣瀵硅薄
+            lock (_globalLocker)
+            {
+                // 濡傛灉璧勬簮ID涓嶅湪瀛楀吀涓紝鍒欐坊鍔犱竴涓柊鐨勯攣瀵硅薄
+                // 鍚﹀垯锛屼娇鐢ㄥ凡瀛樺湪鐨勯攣瀵硅薄
+                lockObject = _resourceLocks.GetOrAdd(resourceId, new object());
+            }
+
+            // 灏濊瘯鑾峰彇璧勬簮鐗瑰畾鐨勯攣
+            // 浣跨敤 Monitor.TryEnter 閬垮厤闃诲锛屽苟瀹炵幇闈為樆濉炵殑鎶㈤攣
+            return Monitor.TryEnter(lockObject);
+        }
+
+        /// <summary>
+        /// 閲婃斁璧勬簮ID鐨勯攣瀹氥��
+        /// </summary>
+        /// <param name="resourceId">瑕侀噴鏀剧殑璧勬簮ID</param>
+        public static void ReleaseLock(string resourceId)
+        {
+            if (_resourceLocks.TryGetValue(resourceId, out object lockObject))
+            {
+                // 纭繚閲婃斁鐨勬槸褰撳墠绾跨▼鎸佹湁鐨勯攣
+                if (Monitor.IsEntered(lockObject))
+                {
+                    Monitor.Exit(lockObject);
+
+                    // 閲婃斁閿佸悗锛屽皾璇曚粠瀛楀吀涓Щ闄よ繖涓攣瀵硅薄锛屾竻鐞嗗唴瀛樸��
+                    // 蹇呴』鍦� Monitor.Exit 涔嬪悗鎵ц銆�
+                    lock (_globalLocker)
+                    {
+                        _resourceLocks.TryRemove(resourceId, out _);
+                    }
+                }
+            }
         }
     }
 }

--
Gitblit v1.9.3