heshaofeng
2025-12-29 266e4bf654c55ce2f7e9271048e4625f1b8b49f6
ÏîÄ¿´úÂë/WMSÎÞ²Ö´¢°æ/WIDESEA_WMSServer/WIDESEA_BasicService/InvokeMESService.cs
@@ -19,10 +19,12 @@
using WIDESEA_Core;
using WIDESEA_Core.BaseRepository;
using WIDESEA_Core.Helper;
using WIDESEA_Core.Util;
using WIDESEA_DTO.Allocate;
using WIDESEA_DTO.Basic;
using WIDESEA_DTO.Inbound;
using WIDESEA_DTO.Outbound;
using WIDESEA_DTO.ReturnMES;
using WIDESEA_IBasicService;
using WIDESEA_IOutboundService;
using WIDESEA_Model.Models;
@@ -48,13 +50,15 @@
        private readonly IOutboundOrderDetailService _outboundOrderDetailService;
        private readonly IOutStockLockInfoService _outStockLockInfoService;
        private readonly IRepository<Dt_InterfaceLog> _interfacelogRepository;
        private readonly HttpClientHelper _httpClientHelper;
        private readonly IUnitOfWorkManage _unitOfWorkManage;
        // å­˜å‚¨èµ„源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, IRepository<Dt_InterfaceLog> interfacelogRepository, IRepository<Dt_InboundOrderDetail> inboundOrderDetailRepository)
        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, IRepository<Dt_InterfaceLog> interfacelogRepository, IRepository<Dt_InboundOrderDetail> inboundOrderDetailRepository, HttpClientHelper httpClientHelper, IUnitOfWorkManage unitOfWorkManage)
        {
            _httpClientFactory = httpClientFactory;
            _logger = logger;
@@ -69,6 +73,8 @@
            _pickingRecoreRepository = pickingRecoreRepository;
            _interfacelogRepository = interfacelogRepository;
            _inboundOrderDetailRepository = inboundOrderDetailRepository;
            _httpClientHelper = httpClientHelper;
            _unitOfWorkManage = unitOfWorkManage;
        }
        /// <summary>
@@ -288,7 +294,7 @@
                                            {
                                                ReqCode = Guid.NewGuid().ToString(),
                                                ReqTime = DateTime.Now.ToString(),
                                                BusinessType = "2",
                                                BusinessType = "3",
                                                FactoryArea = inboundOrder.FactoryArea,
                                                OperationType = 1,
                                                Operator = inboundOrder.Operator,
@@ -318,8 +324,10 @@
                                               }).ToList();
                                            allocatefeedmodel.Details = groupedData;
                                            var result = await FeedbackAllocate(allocatefeedmodel);
                                            if (result != null && result.code == 200)
                                            //var result = await FeedbackAllocate(allocatefeedmodel);
                                            var result = responseModel(inboundOrder, 3, null, allocatefeedmodel);
                                            //if (response != null && response.code == 200)
                                            if (result != null && result.IsSuccess)
                                            {
                                                _feedbacktomesRepository.Db.Insertable(new Dt_FeedbackToMes { OrderNo = orderNo, PalletCode = item.PalletCode, ReportStatus = 1 }).ExecuteCommand();
                                            }
@@ -358,14 +366,16 @@
                                                   }).ToList()
                                               }).ToList();
                                            feedmodel.details = groupedData;
                                            var result = await FeedbackInbound(feedmodel);
                                            if (result != null && result.code == 200)
                                            //var result = await FeedbackInbound(feedmodel);
                                            var response = responseModel(inboundOrder, 2, feedmodel);
                                            //if (result != null && result.code == 200)
                                            if (response != null && response.IsSuccess)
                                            {
                                                _feedbacktomesRepository.Db.Insertable(new Dt_FeedbackToMes { OrderNo = orderNo, PalletCode = item.PalletCode, ReportStatus = 1 }).ExecuteCommand();
                                                var feedstockinfos = _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();
                                                   .Where(it => SqlFunc.Subqueryable<Dt_StockInfoDetail>().Where(s => s.StockId == it.Id && s.OrderNo == orderNo).Any())
                                                   .ToList();
                                                var feedstomes = _feedbacktomesRepository.Db.Queryable<Dt_FeedbackToMes>().Where(x => x.OrderNo == orderNo && x.ReportStatus == 1).Select(o => o.PalletCode).ToList();
                                                var feedunreports = feedstockinfos.Where(x => !feedstomes.Contains(x.PalletCode)).ToList();
                                                if (feedunreports != null && !feedunreports.Any())
@@ -379,13 +389,15 @@
                                                             .Where(it => it.OrderId == feedinboundOrder.Id).ExecuteCommand();
                                                    }
                                                }
                                                return WebResponseContent.Instance.Error("回传成功!");
                                            }
                                            else
                                            {
                                                _inboundOrderRepository.Db.Updateable<Dt_InboundOrder>().SetColumns(it => new Dt_InboundOrder { ReturnToMESStatus = 2, Remark = result.message })
                                                _inboundOrderRepository.Db.Updateable<Dt_InboundOrder>().SetColumns(it => new Dt_InboundOrder { ReturnToMESStatus = 2 })
                                                .Where(it => it.Id == inboundOrder.Id).ExecuteCommand();
                                                _inboundOrderDetailRepository.Db.Updateable<Dt_InboundOrderDetail>().SetColumns(it => new Dt_InboundOrderDetail { ReturnToMESStatus = 2 })
                                              .Where(it => it.OrderId == inboundOrder.Id).ExecuteCommand();
                                                return WebResponseContent.Instance.Error("回传异常!");
                                            }
                                        }
                                    }
@@ -437,6 +449,61 @@
                // MemoryLockManager.ReleaseLock(orderNos[0]);
            }
            return WebResponseContent.Instance.OK();
        }
        public HttpResponseResult<MesResponseDTO> responseModel(Dt_InboundOrder order, int InterfaceType, FeedbackInboundRequestModel model = null, AllocateDto allocateDto = null)
        {
            HttpResponseResult<MesResponseDTO> httpResponseResult = new HttpResponseResult<MesResponseDTO>();
            string reqCode = Guid.NewGuid().ToString();
            string reqTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string requestData = string.Empty;
            string apiUrl = string.Empty;
            if (model != null)
            {
                apiUrl = AppSettings.GetValue("AldMaterialWarehousing");
                httpResponseResult = _httpClientHelper.Post<MesResponseDTO>(apiUrl, model.Serialize());
                requestData = model.Serialize();
            }
            else
            {
                apiUrl = AppSettings.GetValue("AldAllocationOperation");
                httpResponseResult = _httpClientHelper.Post<MesResponseDTO>(apiUrl, allocateDto.Serialize());
                requestData = allocateDto.Serialize();
            }
            httpResponseResult.ApiUrl = apiUrl;
            bool isSuccess = httpResponseResult.IsSuccess && httpResponseResult.Data.Code == "200";
            string message = "成功";
            if (!isSuccess)
            {
                if (!httpResponseResult.IsSuccess)
                {
                    message = $"MES接口返回错误,HTTP代码:{httpResponseResult.StatusCode},信息:{httpResponseResult.ErrorMessage}";
                }
                else if (httpResponseResult?.Data?.Code != "200")
                {
                    message = $"调用MES接口失败,代码:{httpResponseResult?.Data?.Code},信息:{httpResponseResult?.Data?.Message}";
                }
            }
            Dt_MesReturnRecord mesReturnRecord = new Dt_MesReturnRecord()
            {
                ApiUrl = httpResponseResult.ApiUrl,
                InterfaceType = InterfaceType,
                OrderId = order.Id,
                OrderNo = order.InboundOrderNo,
                RequestCode = reqCode,
                RequestData = requestData,
                FailureReason = message,
                LastReturnTime = DateTime.Now,
                HttpStatusCode = httpResponseResult.StatusCode.ObjToInt(),
                ResponseData = httpResponseResult.Content,
                ReturnType = 0,
                ReturnCount = 1,
                ReturnStatus = httpResponseResult.IsSuccess ? 1 : 2,
                SuccessTime = httpResponseResult.IsSuccess ? DateTime.Now : null
            };
            _unitOfWorkManage.Db.Insertable(mesReturnRecord).ExecuteCommand();
            return httpResponseResult;
        }
        private async Task<WebResponseContent> HandleOutboundOrderBatchToMESCompletion(Dt_OutboundOrder outboundOrder, string orderNo)
@@ -675,13 +742,13 @@
            var mesResult = await FeedbackOutbound(feedModel);
            if (mesResult == null || mesResult.code != 200)
            {
                var messages = mesResult?.message??"";
                var messages = mesResult?.message ?? "";
                await _outboundOrderService.Db.Updateable<Dt_OutboundOrder>()
                   .SetColumns(x => new Dt_OutboundOrder
                   {
                       ReturnToMESStatus = 2,
                       Remark = messages,
                       Remark = messages,
                   })
                   .Where(x => x.OrderNo == orderNo)
                   .ExecuteCommandAsync();
@@ -689,7 +756,7 @@
                await _outboundOrderDetailService.Db.Updateable<Dt_OutboundOrderDetail>()
                    .SetColumns(it => new Dt_OutboundOrderDetail
                    {
                        ReturnToMESStatus = 2,
                        ReturnToMESStatus = 2,
                        documentsNO = documentNo,
                    })
                    .Where(x => detailIds.Contains(x.Id))
@@ -697,7 +764,7 @@
                return (flowControl: false, value: WebResponseContent.Instance.Error($"回传MES失败"));
            }
            var updates = pickingRecords.Where(x => detailIds.Contains(x.OrderDetailId)).ToList();
            updates.ForEach(x =>
            {
@@ -727,7 +794,8 @@
                await _outboundOrderService.Db.Updateable<Dt_OutboundOrder>()
                    .SetColumns(x => new Dt_OutboundOrder
                    {
                        ReturnToMESStatus = 1,Remark="",
                        ReturnToMESStatus = 1,
                        Remark = "",
                        OrderStatus = newStatus
                    })
                    .Where(x => x.OrderNo == orderNo)
@@ -905,7 +973,7 @@
                        _logger.LogError(errorMsg);
                        await _outboundOrderDetailService.Db.Updateable<Dt_OutboundOrderDetail>()
                          .SetColumns(x => x.ReturnToMESStatus ==2)
                          .SetColumns(x => x.ReturnToMESStatus == 2)
                          .Where(x => x.OrderId == outboundOrder.Id)
                          .ExecuteCommandAsync();