pan
2025-11-25 cd6e1780b21f01990cec27a10fe65769bcf84dcc
ÏîÄ¿´úÂë/WMSÎÞ²Ö´¢°æ/WIDESEA_WMSServer/WIDESEA_OutboundService/OutboundPickingService.cs
@@ -237,7 +237,7 @@
                _unitOfWorkManage.CommitTran();
                return WebResponseContent.Instance.OK($"取消分拣成功,恢复数量:{pickingRecord.PickQuantity}");
                return WebResponseContent.Instance.OK($"取消分拣成功");
            }
            catch (Exception ex)
            {
@@ -738,7 +738,73 @@
        #endregion
        #region å–消分拣私有方法
        private async Task<ValidationResult<bool>> ValidateDataConsistencyBeforeCancel(CancelPickingContext context)
        {
            try
            {
                // 1. éªŒè¯è®¢å•明细数据
                var currentOrderDetail = await _outboundOrderDetailService.Db.Queryable<Dt_OutboundOrderDetail>()
                    .FirstAsync(x => x.Id == context.OrderDetail.Id);
                if (currentOrderDetail.OverOutQuantity < context.PickingRecord.PickQuantity)
                    return ValidationResult<bool>.Error($"订单明细已出库数量({currentOrderDetail.OverOutQuantity})小于取消数量({context.PickingRecord.PickQuantity})");
                if (currentOrderDetail.PickedQty < context.PickingRecord.PickQuantity)
                    return ValidationResult<bool>.Error($"订单明细已拣选数量({currentOrderDetail.PickedQty})小于取消数量({context.PickingRecord.PickQuantity})");
                // 2. éªŒè¯é”å®šä¿¡æ¯æ•°æ®
                var currentLockInfo = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
                    .FirstAsync(x => x.Id == context.LockInfo.Id);
                if (currentLockInfo.PickedQty < context.PickingRecord.PickQuantity)
                    return ValidationResult<bool>.Error($"锁定信息已拣选数量({currentLockInfo.PickedQty})小于取消数量({context.PickingRecord.PickQuantity})");
                // 3. éªŒè¯åº“存数据
                var currentStockDetail = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
                    .FirstAsync(x => x.Barcode == context.PickingRecord.Barcode && x.StockId == context.PickingRecord.StockId);
                if (currentStockDetail == null)
                    return ValidationResult<bool>.Error($"未找到对应的库存明细记录");
                if (currentStockDetail.Status == StockStatusEmun.入库确认.ObjToInt() ||
                    currentStockDetail.Status == StockStatusEmun.入库完成.ObjToInt())
                    return ValidationResult<bool>.Error($"条码{context.PickingRecord.Barcode}已经回库,无法取消分拣");
                // 4. éªŒè¯çŠ¶æ€æµè½¬çš„åˆæ³•æ€§
                if (!await CanCancelPicking(currentLockInfo, currentStockDetail))
                    return ValidationResult<bool>.Error($"当前状态不允许取消分拣");
                return ValidationResult<bool>.Success(true);
            }
            catch (Exception ex)
            {
                _logger.LogError($"取消分拣数据一致性验证失败: {ex.Message}");
                return ValidationResult<bool>.Error($"数据验证失败: {ex.Message}");
            }
        }
        private async Task<bool> CanCancelPicking(Dt_OutStockLockInfo lockInfo, Dt_StockInfoDetail stockDetail)
        {
            // é”å®šä¿¡æ¯çŠ¶æ€æ£€æŸ¥
            if (lockInfo.Status != (int)OutLockStockStatusEnum.拣选完成)
                return false;
            // åº“存状态检查
            if (stockDetail.Status == StockStatusEmun.出库完成.ObjToInt())
                return false;
            // å¦‚果是拆包记录,还需要检查父锁定信息状态
            if (lockInfo.IsSplitted == 1 && lockInfo.ParentLockId.HasValue)
            {
                var parentLock = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
                    .FirstAsync(x => x.Id == lockInfo.ParentLockId.Value);
                if (parentLock == null || parentLock.Status == (int)OutLockStockStatusEnum.回库中)
                    return false;
            }
            return true;
        }
        private async Task<ValidationResult<(Dt_PickingRecord, Dt_OutStockLockInfo, Dt_OutboundOrderDetail)>> ValidateCancelRequest(string orderNo, string palletCode, string barcode)
        {
            // åŸºç¡€å‚数验证
@@ -846,30 +912,25 @@
                   stockDetail.Status == StockStatusEmun.入库完成.ObjToInt();
        }
        private async Task ExecuteCancelLogic(Dt_OutStockLockInfo lockInfo, Dt_PickingRecord pickingRecord,
            Dt_OutboundOrderDetail orderDetail, string orderNo)
        Dt_OutboundOrderDetail orderDetail, string orderNo)
        {
            decimal cancelQty = pickingRecord.PickQuantity;
            var currentStockDetail = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
        .Where(it => it.Barcode == pickingRecord.Barcode && it.StockId == pickingRecord.StockId)
        .FirstAsync();
            if (currentStockDetail != null &&
                (currentStockDetail.Status == StockStatusEmun.入库确认.ObjToInt() ||
                 currentStockDetail.Status == StockStatusEmun.入库完成.ObjToInt()))
            // 1. æ•°æ®ä¸€è‡´æ€§éªŒè¯
            var context = new CancelPickingContext
            {
                throw new Exception($"条码{pickingRecord.Barcode}已经回库,无法取消分拣");
            }
            //   æ£€æŸ¥å–消后数量不会为负数
            decimal newOverOutQuantity = orderDetail.OverOutQuantity - cancelQty;
            decimal newPickedQty = orderDetail.PickedQty - cancelQty;
                LockInfo = lockInfo,
                PickingRecord = pickingRecord,
                OrderDetail = orderDetail,
                OrderNo = orderNo,
                CancelQuantity = cancelQty
            };
            if (newOverOutQuantity < 0 || newPickedQty < 0)
            {
                throw new Exception($"取消分拣将导致数据异常:已出库{newOverOutQuantity},已拣选{newPickedQty}");
            }
            var validationResult = await ValidateDataConsistencyBeforeCancel(context);
            if (!validationResult.IsValid)
                throw new Exception(validationResult.ErrorMessage);
            //  å¤„理不同类型的取消
            // 2. å¤„理不同类型的取消
            if (lockInfo.IsSplitted == 1 && lockInfo.ParentLockId.HasValue)
            {
                await HandleSplitBarcodeCancel(lockInfo, pickingRecord, cancelQty);
@@ -879,18 +940,25 @@
                await HandleNormalBarcodeCancel(lockInfo, pickingRecord, cancelQty);
            }
            // æ›´æ–°è®¢å•明细
            //  æ›´æ–°è®¢å•明细
            await UpdateOrderDetailOnCancel(pickingRecord.OrderDetailId, cancelQty);
            //  åˆ é™¤æ‹£é€‰è®°å½•
            await Db.Deleteable<Dt_PickingRecord>()
            var deleteResult = await Db.Deleteable<Dt_PickingRecord>()
                .Where(x => x.Id == pickingRecord.Id)
                .ExecuteCommandAsync();
            //  é‡æ–°æ£€æŸ¥è®¢å•状态
            await UpdateOrderStatusForReturn(orderNo);
        }
            if (deleteResult <= 0)
                throw new Exception("删除拣选记录失败");
            _logger.LogInformation($"删除拣选记录 - è®°å½•ID: {pickingRecord.Id}, æ¡ç : {pickingRecord.Barcode}");
            // é‡æ–°æ£€æŸ¥è®¢å•状态
            await UpdateOrderStatusForReturn(orderNo);
        }
        private async Task HandleSplitBarcodeCancel(Dt_OutStockLockInfo lockInfo, Dt_PickingRecord pickingRecord, decimal cancelQty)
        {
            // æŸ¥æ‰¾çˆ¶é”å®šä¿¡æ¯
@@ -901,61 +969,85 @@
            if (parentLockInfo == null)
                throw new Exception("未找到父锁定信息,无法取消拆包分拣");
            // æ£€æŸ¥çˆ¶æ¡ç å’Œæ‹†åŒ…条码的状态
            if (await IsLockInfoReturned(parentLockInfo))
            {
                throw new Exception($"父条码{parentLockInfo.CurrentBarcode}已经回库,无法取消拆包分拣");
            }
            if (await IsLockInfoReturned(lockInfo))
            {
                throw new Exception($"拆包条码{lockInfo.CurrentBarcode}已经回库,无法取消拆包分拣");
            }
            // æ¢å¤çˆ¶é”å®šä¿¡æ¯çš„分配数量
            parentLockInfo.AssignQuantity += cancelQty;
            parentLockInfo.Status = (int)OutLockStockStatusEnum.出库中; // æ¢å¤ä¸ºå‡ºåº“中状态
            await _outStockLockInfoService.Db.Updateable(parentLockInfo).ExecuteCommandAsync();
            // æ¢å¤åº“å­˜
            var stockDetail = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
            // æ¢å¤çˆ¶æ¡ç åº“å­˜
            var parentStockDetail = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
                .Where(x => x.Barcode == parentLockInfo.CurrentBarcode && x.StockId == parentLockInfo.StockId)
                .FirstAsync();
            if (stockDetail != null)
            if (parentStockDetail != null)
            {
                stockDetail.StockQuantity += cancelQty;
                stockDetail.OutboundQuantity = stockDetail.StockQuantity;
                stockDetail.Status = StockStatusEmun.出库锁定.ObjToInt();
                await _stockInfoDetailService.Db.Updateable(stockDetail).ExecuteCommandAsync();
                parentStockDetail.StockQuantity += cancelQty;
                parentStockDetail.OutboundQuantity = parentStockDetail.StockQuantity;
                parentStockDetail.Status = StockStatusEmun.出库锁定.ObjToInt();
                await _stockInfoDetailService.Db.Updateable(parentStockDetail).ExecuteCommandAsync();
                _logger.LogInformation($"恢复父条码库存 - æ¡ç : {parentStockDetail.Barcode}, æ¢å¤æ•°é‡: {cancelQty}, æ–°åº“å­˜: {parentStockDetail.StockQuantity}");
            }
            // å¤„理拆包产生的新条码库存
            var splitStockDetail = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
                .Where(x => x.Barcode == lockInfo.CurrentBarcode && x.StockId == lockInfo.StockId)
                .FirstAsync();
            if (splitStockDetail != null)
            {
                // åˆ é™¤æ‹†åŒ…产生的新条码库存记录
                await _stockInfoDetailService.Db.Deleteable(splitStockDetail).ExecuteCommandAsync();
                _logger.LogInformation($"删除拆包新条码库存 - æ¡ç : {splitStockDetail.Barcode}");
            }
            // æ›´æ–°æ‹†åŒ…记录状态
            await _splitPackageService.Db.Updateable<Dt_SplitPackageRecord>()
            var updateCount = await _splitPackageService.Db.Updateable<Dt_SplitPackageRecord>()
                .SetColumns(x => new Dt_SplitPackageRecord
                {
                    Status = (int)SplitPackageStatusEnum.已撤销,
                    IsReverted = true,
                    Operator = App.User.UserName,
                    RevertTime = DateTime.Now
                })
                .Where(x => x.NewBarcode == lockInfo.CurrentBarcode && !x.IsReverted)
                .ExecuteCommandAsync();
            _logger.LogInformation($"更新拆包记录状态 - æ›´æ–°è®°å½•æ•°: {updateCount}");
            // åˆ é™¤æ‹†åŒ…产生的锁定信息
            await _outStockLockInfoService.Db.Deleteable<Dt_OutStockLockInfo>()
                .Where(x => x.Id == lockInfo.Id)
                .ExecuteCommandAsync();
            await UpdateOrderDetailOnCancel(pickingRecord.OrderDetailId, cancelQty);
            _logger.LogInformation($"删除拆包锁定信息 - é”å®šID: {lockInfo.Id}, æ¡ç : {lockInfo.CurrentBarcode}");
        }
        private async Task HandleNormalBarcodeCancel(Dt_OutStockLockInfo lockInfo, Dt_PickingRecord pickingRecord, decimal cancelQty)
        {
            if (await IsLockInfoReturned(lockInfo))
            {
                throw new Exception($"条码{lockInfo.CurrentBarcode}已经回库,无法取消分拣");
            }
            // æ¢å¤é”å®šä¿¡æ¯
            lockInfo.PickedQty -= cancelQty;
            if (lockInfo.PickedQty < 0) lockInfo.PickedQty = 0;
            lockInfo.Status = (int)OutLockStockStatusEnum.出库中;
            // åªæœ‰å½“拣选数量完全取消时才恢复状态
            if (lockInfo.PickedQty == 0)
            {
                lockInfo.Status = (int)OutLockStockStatusEnum.出库中;
            }
            lockInfo.Operator = App.User.UserName;
            await _outStockLockInfoService.Db.Updateable(lockInfo).ExecuteCommandAsync();
            _logger.LogInformation($"恢复锁定信息 - é”å®šID: {lockInfo.Id}, æ‰£å‡æ‹£é€‰æ•°é‡: {cancelQty}, æ–°å·²æ‹£é€‰æ•°é‡: {lockInfo.PickedQty}");
            // æ¢å¤åº“å­˜
            var stockDetail = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
@@ -966,36 +1058,57 @@
            {
                stockDetail.StockQuantity += cancelQty;
                stockDetail.OutboundQuantity = stockDetail.StockQuantity;
                stockDetail.Status = StockStatusEmun.出库锁定.ObjToInt();
                // æ¢å¤åº“存状态
                if (stockDetail.Status == StockStatusEmun.出库完成.ObjToInt())
                {
                    stockDetail.Status = StockStatusEmun.出库锁定.ObjToInt();
                }
                await _stockInfoDetailService.Db.Updateable(stockDetail).ExecuteCommandAsync();
                _logger.LogInformation($"恢复库存 - æ¡ç : {stockDetail.Barcode}, æ¢å¤æ•°é‡: {cancelQty}, " +
                                      $"新库存: {stockDetail.StockQuantity}, æ–°çŠ¶æ€: {stockDetail.Status}");
            }
            else
            {
                _logger.LogWarning($"未找到库存记录 - æ¡ç : {pickingRecord.Barcode}, åº“å­˜ID: {pickingRecord.StockId}");
            }
        }
        private async Task UpdateOrderDetailOnCancel(int orderDetailId, decimal cancelQty)
        {
            // èŽ·å–æœ€æ–°çš„è®¢å•æ˜Žç»†æ•°æ®
            // èŽ·å–æœ€æ–°çš„è®¢å•æ˜Žç»†æ•°æ®ï¼ˆå¸¦é”ï¼‰
            var currentOrderDetail = await _outboundOrderDetailService.Db.Queryable<Dt_OutboundOrderDetail>()
                .With(SqlWith.RowLock)
                .FirstAsync(x => x.Id == orderDetailId);
            decimal newOverOutQuantity = currentOrderDetail.OverOutQuantity - cancelQty;
            decimal newPickedQty = currentOrderDetail.PickedQty - cancelQty;
            // æ£€æŸ¥å–消后数量不会为负数
            if (newOverOutQuantity < 0 || newPickedQty < 0)
            {
                throw new Exception($"取消分拣将导致已出库数量({newOverOutQuantity})或已拣选数量({newPickedQty})为负数");
            }
            // ä¸¥æ ¼æ£€æŸ¥å–消后数量不会为负数
            if (newOverOutQuantity < 0)
                throw new Exception($"取消分拣将导致已出库数量({newOverOutQuantity})为负数");
            await _outboundOrderDetailService.Db.Updateable<Dt_OutboundOrderDetail>()
            if (newPickedQty < 0)
                throw new Exception($"取消分拣将导致已拣选数量({newPickedQty})为负数");
            // æ›´æ–°è®¢å•明细
            var updateResult = await _outboundOrderDetailService.Db.Updateable<Dt_OutboundOrderDetail>()
                .SetColumns(it => new Dt_OutboundOrderDetail
                {
                    PickedQty = newPickedQty,
                    OverOutQuantity = newOverOutQuantity,
                    OverOutQuantity = newOverOutQuantity
                })
                .Where(it => it.Id == orderDetailId)
                .ExecuteCommandAsync();
        }
            if (updateResult <= 0)
                throw new Exception("更新订单明细失败");
            _logger.LogInformation($"更新订单明细 - OrderDetailId: {orderDetailId}, " +
                                  $"扣减已出库: {cancelQty}, æ–°å·²å‡ºåº“: {newOverOutQuantity}, " +
                                  $"扣减已拣选: {cancelQty}, æ–°å·²æ‹£é€‰: {newPickedQty}");
        }
        #endregion
        #region å›žåº“操作私有方法
@@ -1468,7 +1581,10 @@
                if (outboundOrder.OrderStatus != newStatus)
                {
                    await _outboundOrderService.Db.Updateable<Dt_OutboundOrder>()
                        .SetColumns(x => x.OrderStatus == newStatus)
                        .SetColumns( x=> new Dt_OutboundOrder {
                             OrderStatus = newStatus,
                             Operator = App.User.UserName,
                         })
                        .Where(x => x.OrderNo == orderNo)
                        .ExecuteCommandAsync();
@@ -1516,8 +1632,12 @@
                if (outboundOrder.OrderStatus != newStatus)
                {
                    await _outboundOrderService.Db.Updateable<Dt_OutboundOrder>()
                        .SetColumns(x => x.OrderStatus == newStatus)
                    await _outboundOrderService.Db.Updateable<Dt_OutboundOrder>()
                          .SetColumns(x => new Dt_OutboundOrder
                          {
                              OrderStatus = newStatus,
                              Operator = App.User.UserName,
                          })
                        .Where(x => x.OrderNo == orderNo)
                        .ExecuteCommandAsync();
@@ -1589,8 +1709,13 @@
                        .Where(x => x.OrderId == outboundOrder.Id)
                        .ExecuteCommandAsync();
                    await _outboundOrderService.Db.Updateable<Dt_OutboundOrder>()
                        .SetColumns(x => x.ReturnToMESStatus == 1)
                    await _outboundOrderService.Db.Updateable<Dt_OutboundOrder>()
                          .SetColumns(x => new Dt_OutboundOrder
                          {
                              ReturnToMESStatus = 1,
                              Operator = App.User.UserName,
                          })
                        .Where(x => x.OrderNo == orderNo)
                        .ExecuteCommandAsync();
                }
@@ -1732,6 +1857,7 @@
            if (outboundOrder != null && allCompleted && outboundOrder.OrderStatus != (int)OutOrderStatusEnum.出库完成)
            {
                outboundOrder.OrderStatus = (int)OutOrderStatusEnum.出库完成;
                outboundOrder.Operator = App.User.UserName;
                await _outboundOrderService.Db.Updateable(outboundOrder).ExecuteCommandAsync();
                _logger.LogInformation($"订单 {orderNo} å·²æ ‡è®°ä¸ºå‡ºåº“完成");
@@ -2159,5 +2285,29 @@
        public bool CanReturn => HasItemsToReturn && !HasActiveTasks;
        public bool CanRemove => IsEmptyPallet && !HasActiveTasks;
    }
    public class PickingContext
    {
        public string OrderNo { get; set; }
        public string PalletCode { get; set; }
        public string Barcode { get; set; }
        public string Operator { get; set; }
        public Dt_OutStockLockInfo LockInfo { get; set; }
        public Dt_OutboundOrderDetail OrderDetail { get; set; }
        public Dt_StockInfoDetail StockDetail { get; set; }
        public decimal ActualQuantity { get; set; }
        public string AdjustedReason { get; set; }
    }
    public class CancelPickingContext
    {
        public string OrderNo { get; set; }
        public string PalletCode { get; set; }
        public string Barcode { get; set; }
        public string Operator { get; set; }
        public decimal CancelQuantity { get; set; }
        public Dt_PickingRecord PickingRecord { get; set; }
        public Dt_OutStockLockInfo LockInfo { get; set; }
        public Dt_OutboundOrderDetail OrderDetail { get; set; }
    }
    #endregion
}