heshaofeng
7 天以前 461524a7a1def4532b9af4ab40733f899f360db7
ÏîÄ¿´úÂë/WMSÎÞ²Ö´¢°æ/WIDESEA_WMSServer/WIDESEA_TaskInfoService/TaskService_Outbound.cs
@@ -4,11 +4,13 @@
using OfficeOpenXml.FormulaParsing.Excel.Functions.RefAndLookup;
using SqlSugar;
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using WIDESEA_BasicService;
using WIDESEA_Common.CommonEnum;
using WIDESEA_Common.LocationEnum;
@@ -43,12 +45,47 @@
            WebResponseContent content = new WebResponseContent();
            try
            {
                var stockInfos = _stockRepository.Db.Queryable<Dt_StockInfo>().Where(x => x.PalletType == PalletTypeEnum.Empty.ObjToInt() && x.StockStatus == StockStatusEmun.入库完成.ObjToInt()).WhereIF(locationType != 0, x => x.LocationType == locationType).Take(num).ToList();
                Dictionary<string, SqlSugar.OrderByType> orderByDict = new Dictionary<string, SqlSugar.OrderByType>()
                {
                     { nameof(Dt_LocationInfo.Layer), SqlSugar.OrderByType.Asc },
                     { nameof(Dt_LocationInfo.Row), SqlSugar.OrderByType.Asc },
                     { nameof(Dt_LocationInfo.Column), SqlSugar.OrderByType.Asc },
                     { nameof(Dt_LocationInfo.Depth), SqlSugar.OrderByType.Desc },
                };
                if (stockInfos.Count() == 0)
                var query = _stockRepository.Db.Queryable<Dt_StockInfo>()
                    .Where(x => x.PalletType == PalletTypeEnum.Empty.ObjToInt()
                             && x.StockStatus == StockStatusEmun.入库完成.ObjToInt())
                    .WhereIF(locationType != 0, x => x.LocationType == locationType)
                    .LeftJoin<Dt_LocationInfo>((s, l) => s.LocationCode == l.LocationCode);
                if (query.Count() == 0)
                {
                    return WebResponseContent.Instance.Error("未找到空托盘库存");
                }
                bool isFirstOrder = true;
                foreach (var item in orderByDict)
                {
                    string fieldName = item.Key.Equals("Column", StringComparison.OrdinalIgnoreCase)
                        ? $"l.[{item.Key}]"
                        : $"l.{item.Key}";
                    string sortSql = $"{fieldName} {(item.Value == SqlSugar.OrderByType.Asc ? "ASC" : "DESC")}";
                    if (isFirstOrder)
                    {
                        query = query.OrderBy(sortSql);
                        isFirstOrder = false;
                    }
                    else
                    {
                        query = query.OrderBy(sortSql);
                    }
                }
                var stockInfos = await query.Take(num).ToListAsync();
                foreach (var stockInfo in stockInfos)
                {
                    Dt_LocationInfo locationInfo = _locationInfoService.Repository.QueryFirst(x => x.LocationCode == stockInfo.LocationCode);
@@ -88,33 +125,6 @@
                    _unitOfWorkManage.CommitTran();
                    //TaskModel esstask = new TaskModel()
                    //{
                    //    taskType = "carry",
                    //    taskGroupCode = "",
                    //    groupPriority = 0,
                    //    tasks = new List<TasksType>
                    //    {
                    //            new()
                    //            {
                    //                taskCode=task.TaskNum.ToString(),
                    //                taskPriority=0,
                    //                taskDescribe=new TaskDescribeType
                    //                {
                    //                    containerCode=stockInfo.PalletCode,
                    //                    containerType= "CT_KUBOT_STANDARD",
                    //                    fromLocationCode=stockInfo.LocationCode??"",
                    //                    toStationCode="",
                    //                    toLocationCode="1-2",
                    //                    deadline=0,
                    //                    storageTag=""
                    //                }
                    //            }
                    //    }
                    //};
                    //var result = await _eSSApiService.CreateTaskAsync(esstask);
                    //_logger.LogInformation("创建任务PalletOutboundTask è¿”回:  " + result);
                }
                return content.OK("空托出库成功!");
            }
@@ -123,6 +133,8 @@
                return WebResponseContent.Instance.Error(ex.Message);
            }
        }
        /// <summary>
@@ -830,7 +842,7 @@
        }
        #region åˆ†æ‰¹åˆ†é…åº“å­˜
        #region å†…存锁管理器
        private static readonly ConcurrentDictionary<string, SemaphoreSlim> _materialLocks =
@@ -1117,6 +1129,14 @@
            WebResponseContent content = new WebResponseContent();
            try
            {
                var allFactoryAreas = stockViews.SelectMany(sv => sv.Details)
                                                .Select(x => x.FactoryArea)
                                                .GroupBy(x => x)
                                                .ToList();
                if (allFactoryAreas.Count >= 2)
                {
                    return content.Error($"请选择同一厂区区域的库存进行盘点,当前涉及{allFactoryAreas.Count}个不同的厂区");
                }
                List<int> ids = stockViews.Select(x => x.StockId).ToList();
                //获取库存
                List<Dt_StockInfo> stockInfos = _stockRepository.Db.Queryable<Dt_StockInfo>().Where(x => ids.Contains(x.Id)).Includes(x => x.Details).ToList();
@@ -1149,9 +1169,9 @@
                        return content.Error($"未找到{item.PalletCode}库存明细数据");
                    }
                    Dt_LocationInfo? locationInfo = locationInfos.FirstOrDefault(x => x.LocationCode == item.LocationCode);
                    if (locationInfo == null && (locationInfo.EnableStatus == EnableStatusEnum.Disable.ObjToInt() || locationInfo.EnableStatus != EnableStatusEnum.Normal.ObjToInt()) && locationInfo.LocationStatus != LocationStatusEnum.InStock.ObjToInt() && item.StockStatus != StockStatusEmun.入库完成.ObjToInt())
                    if (locationInfo == null || (locationInfo.EnableStatus == EnableStatusEnum.Disable.ObjToInt() || locationInfo.EnableStatus != EnableStatusEnum.Normal.ObjToInt()) || locationInfo.LocationStatus != LocationStatusEnum.InStock.ObjToInt() || item.StockStatus != StockStatusEmun.入库完成.ObjToInt())
                    {
                        content.Error($"{item.PalletCode}货位或库存状态不满足出库条件");
                        return content.Error($"{item.PalletCode}货位或库存状态不满足出库条件");
                    }   
                }
                List<Dt_Task> tasks = GetTasks(stockInfos, TaskTypeEnum.OutInventory,outStation);
@@ -1224,7 +1244,7 @@
            catch (Exception ex)
            {
                _unitOfWorkManage.RollbackTran();
                content.Error(ex.Message);
                return await Task.FromResult(WebResponseContent.Instance.Error(ex.Message));
            }
            return content;
        }
@@ -1290,6 +1310,280 @@
                return code;
            }
        }
        /// <summary>
        /// é€‰å®šåº“存同区域移库
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<WebResponseContent> AreaOutbound(List<StockViewDTO> stockViews)
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                List<int> ids = stockViews.Select(x => x.StockId).ToList();
                //获取库存
                List<Dt_StockInfo> stockInfos = _stockRepository.Db.Queryable<Dt_StockInfo>().Where(x => ids.Contains(x.Id)).Includes(x => x.Details).ToList();
                if (stockInfos.Count != stockViews.Count)
                {
                    StockViewDTO? stockViewDTO = stockViews.FirstOrDefault(x => !stockInfos.Select(x => x.PalletCode).ToList().Contains(x.PalletCode));
                    return content.Error($"未找到{stockViewDTO?.PalletCode}库存");
                }
                //获取货位
                List<string> locStrs = stockInfos.Select(x => x.LocationCode).ToList();
                List<Dt_LocationInfo> locationInfos = _locationInfoService.Db.Queryable<Dt_LocationInfo>().Where(x => locStrs.Contains(x.LocationCode)).ToList();
                if (stockInfos.Count != locationInfos.Count)
                {
                    string? locStr = locStrs.FirstOrDefault(x => !locationInfos.Select(x => x.LocationCode).ToList().Contains(x));
                    return content.Error($"未找到{locStr}货位数据");
                }
                foreach (var item in stockInfos)
                {
                    Dt_LocationInfo? locationInfo = locationInfos.FirstOrDefault(x => x.LocationCode == item.LocationCode);
                    if (locationInfo == null || (locationInfo.EnableStatus == EnableStatusEnum.Disable.ObjToInt() || locationInfo.EnableStatus != EnableStatusEnum.Normal.ObjToInt()) || item.StockStatus != StockStatusEmun.入库完成.ObjToInt())
                    {
                        return content.Error($"{item.PalletCode}货位或库存状态不满足出库条件");
                    }
                }
                List<Dt_Task> tasks = AreaGetTasks(stockInfos, TaskTypeEnum.AreaRelocation);
                if (tasks == null || tasks.Count <= 0)
                {
                    return content.Error($"生成任务失败");
                }
                stockInfos.ForEach(x =>
                {
                    x.StockStatus = StockStatusEmun.出库锁定.ObjToInt();
                });
                tasks.ForEach(x =>
                {
                    x.OrderNo = "无单据移库";
                });
                locationInfos.ForEach(x =>
                {
                    x.LocationStatus = LocationStatusEnum.Lock.ObjToInt();
                });
                _unitOfWorkManage.BeginTran();
                //更新库存状态
                _stockRepository.UpdateData(stockInfos);
                //新建任务
                BaseDal.AddData(tasks);
                _locationInfoService.UpdateData(locationInfos);
                _unitOfWorkManage.CommitTran();
                content.OK();
            }
            catch (Exception ex)
            {
                _unitOfWorkManage.RollbackTran();
                return await Task.FromResult(WebResponseContent.Instance.Error(ex.Message));
            }
            return content;
        }
        public List<Dt_Task> AreaGetTasks(List<Dt_StockInfo> stockInfos, TaskTypeEnum taskType)
        {
            // ä½¿ç”¨ TransactionScope åŒ…裹整个操作,确保所有数据库操作在同一事务中
            using (var scope = new TransactionScope(TransactionScopeOption.Required,
                new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted }))
            {
                try
                {
                    List<Dt_Task> tasks = new List<Dt_Task>();
                    List<Dt_LocationInfo> locationInfos = _locationInfoService.Repository.QueryData(
                        x => stockInfos.Select(x => x.LocationCode).Contains(x.LocationCode));
                    for (int i = 0; i < stockInfos.Count; i++)
                    {
                        Dt_StockInfo stockInfo = stockInfos[i];
                        if (stockInfo != null)
                        {
                            Dt_LocationInfo? locationInfo = locationInfos.FirstOrDefault(x => x.LocationCode == stockInfo.LocationCode);
                            var newLocation = _locationInfoService.AssignLocation(stockInfo.LocationType);
                            if (newLocation == null)
                            {
                                throw new Exception($"在{stockInfo.PalletCode}时没有空闲库位可进行同区域移库,请检查或减少移库料箱");
                            }
                            if (!tasks.Exists(x => x.PalletCode == stockInfo.PalletCode))
                            {
                                Dt_Task task = new()
                                {
                                    CurrentAddress = stockInfo.LocationCode,
                                    Grade = 0,
                                    PalletCode = stockInfo.PalletCode,
                                    NextAddress = "",
                                    Roadway = locationInfo.RoadwayNo,
                                    SourceAddress = stockInfo.LocationCode,
                                    TargetAddress = newLocation.LocationCode,
                                    TaskStatus = TaskStatusEnum.New.ObjToInt(),
                                    TaskType = taskType.ObjToInt(),
                                    PalletType = stockInfo.PalletType,
                                    WarehouseId = stockInfo.WarehouseId,
                                };
                                tasks.Add(task);
                            }
                            newLocation.LocationStatus = LocationStatusEnum.Lock.ObjToInt();
                            _locationInfoService.UpdateData(newLocation);
                        }
                    }
                    // æäº¤äº‹åŠ¡
                    scope.Complete();
                    return tasks;
                }
                catch (Exception ex)
                {
                    // TransactionScope ä¼šè‡ªåŠ¨å›žæ»šäº‹åŠ¡ï¼Œæ— éœ€æ‰‹åŠ¨ Rollback
                    throw new Exception(ex.Message);
                }
            }
        }
        /// <summary>
        /// é€‰å®šåº“存跨区域移库
        /// </summary>
        /// <param name="stockViews"></param>
        /// <param name="targetLocationType">目标货位类型</param>
        /// <returns></returns>
        public async Task<WebResponseContent> CrossAreaOutbound(List<StockViewDTO> stockViews, int targetLocationType)
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                if(targetLocationType == (int)LocationTypeEnum.Electronic)
                {
                    return content.Error("电子仓不允许跨区域移库");
                }
                List<int> ids = stockViews.Select(x => x.StockId).ToList();
                List<Dt_StockInfo> stockInfos = _stockRepository.Db.Queryable<Dt_StockInfo>().Where(x => ids.Contains(x.Id)).Includes(x => x.Details).ToList();
                if (stockInfos.Count != stockViews.Count)
                {
                    StockViewDTO? stockViewDTO = stockViews.FirstOrDefault(x => !stockInfos.Select(x => x.PalletCode).Contains(x.PalletCode));
                    return content.Error($"未找到{stockViewDTO?.PalletCode}库存");
                }
                List<string> locStrs = stockInfos.Select(x => x.LocationCode).ToList();
                List<Dt_LocationInfo> locationInfos = _locationInfoService.Db.Queryable<Dt_LocationInfo>().Where(x => locStrs.Contains(x.LocationCode)).ToList();
                if (stockInfos.Count != locationInfos.Count)
                {
                    string? locStr = locStrs.FirstOrDefault(x => !locationInfos.Select(x => x.LocationCode).Contains(x));
                    return content.Error($"未找到{locStr}货位数据");
                }
                foreach (var item in stockInfos)
                {
                    if (item.PalletType != PalletTypeEnum.Empty.ObjToInt())
                    {
                        return content.Error($"托盘【{item.PalletCode}】非空箱,仅空箱允许跨区域移库!");
                    }
                    Dt_LocationInfo? locationInfo = locationInfos.FirstOrDefault(x => x.LocationCode == item.LocationCode);
                    if (locationInfo == null || locationInfo.EnableStatus != EnableStatusEnum.Normal.ObjToInt() || item.StockStatus != StockStatusEmun.入库完成.ObjToInt())
                    {
                        return content.Error($"{item.PalletCode}货位或库存状态不满足出库条件");
                    }
                }
                List<Dt_Task> tasks = CrossAreaGetTasks(stockInfos, targetLocationType, TaskTypeEnum.CrossAreaRelocation);
                if (tasks == null || tasks.Count <= 0)
                {
                    return content.Error("生成跨区域移库任务失败");
                }
                stockInfos.ForEach(x =>
                {
                    x.StockStatus = StockStatusEmun.出库锁定.ObjToInt();
                });
                tasks.ForEach(x =>
                {
                    x.OrderNo = "跨区域移库";
                });
                locationInfos.ForEach(x =>
                {
                    x.LocationStatus = LocationStatusEnum.Lock.ObjToInt();
                });
                _unitOfWorkManage.BeginTran();
                _stockRepository.UpdateData(stockInfos);
                BaseDal.AddData(tasks);
                _locationInfoService.UpdateData(locationInfos);
                _unitOfWorkManage.CommitTran();
                content.OK();
            }
            catch (Exception ex)
            {
                _unitOfWorkManage.RollbackTran();
                return await Task.FromResult(WebResponseContent.Instance.Error(ex.Message));
            }
            return content;
        }
        /// <summary>
        /// ç”Ÿæˆè·¨åŒºåŸŸç§»åº“任务
        /// </summary>
        /// <param name="stockInfos">库存列表</param>
        /// <param name="targetAreaCode">目标区域编码</param>
        /// <param name="taskType">任务类型</param>
        /// <returns></returns>
        public List<Dt_Task> CrossAreaGetTasks(List<Dt_StockInfo> stockInfos, int targetLocationType, TaskTypeEnum taskType)
        {
            using (var scope = new TransactionScope(TransactionScopeOption.Required,
                new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted }))
            {
                try
                {
                    List<Dt_Task> tasks = new List<Dt_Task>();
                    foreach (var stockInfo in stockInfos)
                    {
                        Dt_LocationInfo newLocation = _locationInfoService.AssignLocation(targetLocationType);
                        if (newLocation == null)
                        {
                            throw new Exception($"{stockInfo.PalletCode} æ²¡æœ‰ç©ºé—²è´§ä½å¯è¿›è¡Œè·¨åŒºåŸŸç§»åº“");
                        }
                        if (!tasks.Exists(x => x.PalletCode == stockInfo.PalletCode))
                        {
                            Dt_Task task = new()
                            {
                                CurrentAddress = stockInfo.LocationCode,
                                Grade = 0,
                                PalletCode = stockInfo.PalletCode,
                                NextAddress = "",
                                Roadway = newLocation.RoadwayNo,
                                SourceAddress = stockInfo.LocationCode,
                                TargetAddress = newLocation.LocationCode,
                                TaskStatus = TaskStatusEnum.New.ObjToInt(),
                                TaskType = taskType.ObjToInt(),
                                PalletType = stockInfo.PalletType,
                                WarehouseId = stockInfo.WarehouseId,
                            };
                            tasks.Add(task);
                        }
                        newLocation.LocationStatus = LocationStatusEnum.Lock.ObjToInt();
                        _locationInfoService.UpdateData(newLocation);
                    }
                    scope.Complete();
                    return tasks;
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }
        }
    }
}