pan
2025-12-03 61fb796ac4c84a5bbcc42583b4826bdd082487c1
ÏîÄ¿´úÂë/WMSÎÞ²Ö´¢°æ/WIDESEA_WMSServer/WIDESEA_BasicService/InvokeMESService.cs
@@ -1,4 +1,5 @@
using Dm.filter;
using MailKit.Search;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Org.BouncyCastle.Asn1.Ocsp;
@@ -8,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;
@@ -26,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;
@@ -37,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, IMaterialUnitService materialUnitService)
        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;
@@ -53,6 +80,7 @@
            _outboundOrderDetailService = outboundOrderDetailService;
            _outStockLockInfoService = outStockLockInfoService;
            _materialUnitService = materialUnitService;
            _pickingRecoreRepository = pickingRecoreRepository;
        }
        /// <summary>
@@ -101,7 +129,7 @@
            _client.DefaultRequestHeaders.Clear();
            _client.DefaultRequestHeaders.Add("Accept", "application/json");
            _logger.LogInformation("InvokeMESService  FeedbackOutbound :  " + json);
            _logger.LogInformation("InvokeMESService  FeedbackOutbound :  "+ model.orderNo +"  , " + json);
            var response = await _client.PostAsync("AldMaterialOutbound/MaterialOutbound", content);
            string body = await response.Content.ReadAsStringAsync();
@@ -111,7 +139,7 @@
                throw new HttpRequestException(body);
            }
            _logger.LogInformation("InvokeMESService  FeedbackOutbound  body:  " + body);
            return JsonConvert.DeserializeObject<ResponseModel>(body);
        }
@@ -220,6 +248,7 @@
            }
        }
        /// <summary>
        /// 
        /// </summary>
@@ -275,7 +304,7 @@
                                               MaterialCode = group.Key.MaterielCode,
                                               LineNo = group.Key.InboundOrderRowNo,
                                               WarehouseCode = group.Key.WarehouseCode,
                                               Qty = group.Sum(x => x.BarcodeQty),
                                               Qty = group.Sum(x => x.BarcodeQty),
                                               Unit = group.Key.BarcodeUnit,
                                               Barcodes = group.Select(row => new BarcodeInfo
                                               {
@@ -366,11 +395,12 @@
            }
            return WebResponseContent.Instance.OK();
        }
        private async Task<WebResponseContent> HandleOutboundOrderBatchToMESCompletion(Dt_OutboundOrder outboundOrder, string orderNo)
        {
            // å®šä¹‰é»˜è®¤è¿”回(成功态)
            WebResponseContent response = WebResponseContent.Instance.OK("回传MES处理完成");
            //0 = æœªå›žä¼ ï¼Œ1 = å·²å›žä¼ æˆåŠŸï¼Œ2 = å›žä¼ å¤±è´¥
            try
            {
                // æ ¡éªŒï¼šå·²å›žä¼ ç›´æŽ¥è¿”回错误
@@ -391,8 +421,104 @@
                    return WebResponseContent.Instance.Error("暂无需要处理的订单明细");
                }
                //  ç­›é€‰å·²å®Œæˆå‡ºåº“的明细ID
                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 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!=""? 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)
@@ -415,7 +541,7 @@
                int newStatus = allCompleted ? (int)OutOrderStatusEnum.出库完成 : (int)OutOrderStatusEnum.出库中;
                if (outboundOrder.OrderStatus != newStatus)
                {
                    // ä¿®æ­£åŽŸæœ‰è¯­æ³•é”™è¯¯ï¼šSetColumns æ˜¯èµ‹å€¼ï¼ˆ=)而非判断(==)
                    int updateCount = await _outboundOrderService.Db.Updateable<Dt_OutboundOrder>()
                        .SetColumns(x => x.OrderStatus == newStatus)
                        .Where(x => x.OrderNo == orderNo)
@@ -424,85 +550,16 @@
                    if (updateCount <= 0)
                    {
                        _logger.LogWarning($"更新出库单状态失败 - OrderNo: {orderNo}, ç›®æ ‡çŠ¶æ€: {newStatus}");
                        // çŠ¶æ€æ›´æ–°å¤±è´¥ä¸ä¸­æ–­æµç¨‹ï¼Œä½†è®°å½•è­¦å‘Š
                    }
                }
                // æž„建回传MES的模型
                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 )
                {
                    // æŸ¥è¯¢è¯¥æ˜Žç»†å¯¹åº”的锁定条码记录
                    var detailLocks = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
                        .Where(x => x.OrderNo == orderNo
                                   && detail.Id == x.OrderDetailId
                                   && (x.Status == (int)OutLockStockStatusEnum.拣选完成
                                       || x.Status == (int)OutLockStockStatusEnum.已回库))
                        .ToListAsync();
                    var detailModel = new FeedbackOutboundDetailsModel
                    {
                        materialCode = detail.MaterielCode,
                        lineNo = detail.lineNo,
                        warehouseCode = detail.WarehouseCode,
                        qty =0,
                        currentDeliveryQty = 0,
                        unit = detail.BarcodeUnit,
                        barcodes = new List<WIDESEA_DTO.Outbound.BarcodesModel>()
                    };
                    // å¡«å……条码信息(含单位转换)
                    foreach (var item in detailLocks)
                    {
                        if (item.PickedQty > 0)
                        {
                            var barModel = new WIDESEA_DTO.Outbound.BarcodesModel
                            {
                                barcode = item.CurrentBarcode,
                                supplyCode = item.SupplyCode,
                                batchNo = item.BatchNo,
                                unit = item.BarcodeUnit,
                                qty = item.BarcodeQty
                            };
                            // å•位不一致时转换
                            if (item.BarcodeUnit != item.Unit)
                            {
                                var convertResult = await _materialUnitService.ConvertAsync(
                                    item.MaterielCode, item.BarcodeQty, item.Unit, item.BarcodeUnit);
                                barModel.unit = convertResult.Unit;
                                barModel.qty = convertResult.Quantity;
                            }
                            detailModel.qty += barModel.qty;
                            detailModel.currentDeliveryQty += barModel.qty;
                            detailModel.barcodes.Add(barModel);
                        }
                    }
                    feedModel.details.Add(detailModel);
                }
                // è°ƒç”¨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
@@ -515,17 +572,28 @@
                    return WebResponseContent.Instance.Error($"回传MES失败");
                }
                //MES回传成功:更新明细为回传成功状态
                await _outboundOrderDetailService.Db.Updateable<Dt_OutboundOrderDetail>()
                    .SetColumns(it => new Dt_OutboundOrderDetail
                    {
                        ReturnToMESStatus = 1,
                        documentsNO = documentNo,
                    })
                    .Where(x => detailIds.Contains(x.Id))
                    .ExecuteCommandAsync();
                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.出库完成)
                {
@@ -673,8 +741,8 @@
                                materialCode = group.Key.MaterielCode,
                                lineNo = group.Key.lineNo,
                                warehouseCode = group.Key.WarehouseCode,
                                qty = group.Sum(x => x.BarcodeQty),
                                currentDeliveryQty = group.Sum(x => x.BarcodeQty),
                                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
                                {
@@ -682,7 +750,7 @@
                                    supplyCode = lockInfo.SupplyCode,
                                    batchNo = lockInfo.BatchNo,
                                    unit = lockInfo.BarcodeUnit,
                                    qty = lockInfo.BarcodeQty
                                    qty = lockInfo.PickedQty
                                }).ToList()
                            }).ToList();
@@ -709,6 +777,11 @@
                            .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
@@ -728,7 +801,7 @@
                return WebResponseContent.Instance.Error("处理回传MES时发生异常,请联系管理员");
            }
        }
    }
    }
    public static class UniqueValueGenerator
    {
@@ -742,14 +815,14 @@
        public static string Generate()
        {
            var now = DateTime.Now;
            string datePart = now.ToString("yyyyMMdd");
            string datePart = now.ToString("MMdd");
            long ticksPart = now.Ticks;
            // åŽŸå­é€’å¢žè®¡æ•°å™¨ï¼ˆå–æ¨¡1000,确保计数器仅3位,控制长度)
            long counterPart = Interlocked.Increment(ref _counter) % 1000;
            // æ‹¼æŽ¥ï¼šè®¡æ•°å™¨è¡¥0为3位(避免位数不一致)
            return $"{datePart}{ticksPart}{counterPart:D3}";
            return $"{datePart}{ticksPart}";
        }
    }
}