Esempio n. 1
0
        /// <summary>
        /// 采购完成后重新领料
        /// </summary>
        /// <param name="orderID"></param>
        /// <param name="currentUser"></param>
        /// <returns></returns>
        public async Task <ResponseObject <NOEntity> > RePick(int orderID, CurrentUser currentUser)
        {
            try
            {
                TMMProductionOrderMainDbModel tMMProductionOrderMainDbModel = _db.Instance.Queryable <TMMProductionOrderMainDbModel>().Where(p => p.ID == orderID).First();

                if (tMMProductionOrderMainDbModel.IsPickAll == true)
                {
                    throw new Exception("已全部转领料");
                }

                TMMPurchaseApplyMainDbModel purchaseEntity = await _db.Instance.Queryable <TMMPurchaseApplyMainDbModel>().Where(p => p.SourceId == orderID && p.CompanyId == currentUser.CompanyID && p.DeleteFlag == false).FirstAsync();

                NOEntity nOEntity = new NOEntity();
                if (purchaseEntity == null)
                {
                    throw new Exception("还没采购,或者无需采购");
                }

                if (purchaseEntity.TransferFlag == true)
                {
                    throw new Exception("采购流程未完成");
                }
                else
                {
                    int producePurchaseId = purchaseEntity.ID;
                    if (_db.Instance.Queryable <TPSMPurchaseOrderMainDbModel>().Any(p => p.DeleteFlag == false && p.TransferStatus == true && p.SourceId == purchaseEntity.ID))
                    {
                        throw new Exception("采购流程未完成");
                    }
                    var allTWMPurchase = _db.Instance.Queryable <TWMPurchaseDetailDbModel, TWMPurchaseMainDbModel>((t, t1) => new object[] { JoinType.Inner, t.MainId == t1.ID }).
                                         Where((t, t1) => t1.DeleteFlag == false && SqlFunc.Subqueryable <TPSMPurchaseOrderMainDbModel>().
                                               Where(p1 => p1.SourceId == producePurchaseId && t1.SourceId == p1.ID).Any()).Select((t, t1) => new { Main = t1, Deatail = t }).ToList();

                    if (allTWMPurchase.Any(p => p.Main.AuditStatus != 2))
                    {
                        throw new Exception("采购流程未完成");
                    }
                    else
                    {
                        var basicMe  = BasicCacheGet.GetMaterial(currentUser);
                        var groupSum = allTWMPurchase.Select(p => p.Deatail).GroupBy(x => x.MaterialId);

                        List <TMMPickApplyDetailDbModel> PickApplyList = new List <TMMPickApplyDetailDbModel>();
                        foreach (var item in groupSum)
                        {
                            var key          = item.Key;
                            var itemDeatails = item.ToList();
                            var firstItem    = itemDeatails.FirstOrDefault();

                            decimal total = item.Sum(p => p.ActualNum);
                            var     me    = basicMe.Where(p => p.ID == item.Key).FirstOrDefault();

                            decimal ProduceTotal = UnitChange.TranserUnit(me, UnitType.Warehouse, UnitType.Produce, total);

                            TMMPickApplyDetailDbModel ApplyDetail = new TMMPickApplyDetailDbModel();
                            ApplyDetail.ApplyNum   = ProduceTotal;
                            ApplyDetail.MaterialId = key;
                            ApplyDetail.TransNum   = ProduceTotal;
                            PickApplyList.Add(ApplyDetail);
                        }

                        if (PickApplyList.Count() > 0)
                        {
                            TMMPickApplyMainDbModel tMMPickApplyMainDbModel = new TMMPickApplyMainDbModel();
                            tMMPickApplyMainDbModel.DeleteFlag = false;
                            tMMPickApplyMainDbModel.SourceId   = orderID;
                            //tMMPickApplyMainDbModel.PickNo = OrderGenerator.Generator(OrderEnum.PMR, currentUser.CompanyID);
                            string code = _codeMakers.Where(p => p.ProvideName == OrderEnum.PMR.GetDescription()).FirstOrDefault()?.MakeNo(currentUser.CompanyID);
                            tMMPickApplyMainDbModel.PickNo       = code;
                            tMMPickApplyMainDbModel.ApplyDate    = DateTime.Now;
                            tMMPickApplyMainDbModel.OperatorId   = currentUser.UserID;
                            tMMPickApplyMainDbModel.OperatorTime = DateTime.Now;
                            tMMPickApplyMainDbModel.AuditStatus  = 2;
                            tMMPickApplyMainDbModel.CompanyId    = currentUser.CompanyID;
                            tMMPickApplyMainDbModel.TransferFlag = true;

                            int mId = _db.Instance.Insertable(tMMPickApplyMainDbModel).ExecuteReturnIdentity();

                            PickApplyList.ForEach((x) =>
                            {
                                x.MainId = mId;
                            });

                            _db.Instance.Insertable(PickApplyList).ExecuteCommand();

                            _db.Instance.Updateable <TMMProductionOrderMainDbModel>().SetColumns(p => new TMMProductionOrderMainDbModel {
                                IsPickAll = true
                            }).Where(p => p.ID == orderID).ExecuteCommand();

                            nOEntity.ID = tMMPickApplyMainDbModel.ID;
                            nOEntity.NO = tMMPickApplyMainDbModel.PickNo;
                        }
                    }
                }

                _db.Instance.CommitTran();
                return(ResponseUtil <NOEntity> .SuccessResult(nOEntity));
            }
            catch (Exception ex)
            {
                _db.Instance.RollbackTran();
                return(ResponseUtil <NOEntity> .FailResult(null, ex.Message));
            }
        }
Esempio n. 2
0
        /// <summary>
        /// 修改T_WM_ProductionWhMain数据
        /// </summary>
        /// <param name="requestObject">Put请求参数</param>
        /// <returns>返回响应结果对象,包括响应代码,修改操作结果</returns>
        public async Task <ResponseObject <TWMProductionWhMainQueryModel> > PutAsync(RequestPut <TWMProductionWhMainEditModel> requestObject, CurrentUser currentUser)
        {
            var currDb = _db.Instance;//事务需要使用同一个 SqlSugarClient对象实例

            try
            {
                if (requestObject.PostData == null)
                {
                    return(ResponseUtil <TWMProductionWhMainQueryModel> .FailResult(null, "PostData不能为null"));
                }
                if (requestObject.PostData.ChildList == null || requestObject.PostData.ChildList.Count < 1)
                {
                    return(ResponseUtil <TWMProductionWhMainQueryModel> .FailResult(null, "PostData.ChildList至少包含一条数据"));
                }
                //开启事务
                currDb.BeginTran();
                //修改主表信息
                var mainModel = _mapper.Map <TWMProductionWhMainDbModel>(requestObject.PostData);
                //修改主表信息
                mainModel.Number = requestObject.PostData.ChildList.Sum(p => p.ActualNum);
                mainModel.Amount = requestObject.PostData.ChildList.Sum(p => p.Amount);

                var mainFlag = await currDb.Updateable(mainModel).UpdateColumns(p => new
                {
                    p.WarehousingDate,
                    p.Number,
                    p.Amount,
                    p.WhAdminId,
                    p.ReceiptId
                }).ExecuteCommandAsync() > 0;

                /*
                 * 修改明细逻辑
                 * 1.根据主单ID查询现有明细数据
                 * 2.PostData.ChildList中明细ID <= 0的新增
                 * 3.PostData.ChildList中明细ID > 0的修改
                 * 4.删除不在PostData.CihldList中的数据
                 */

                var mainEntity = _db.Instance.Queryable <TWMProductionWhMainDbModel>().Where(P => P.ID == requestObject.PostData.ID).First();

                var detailFlag   = true;
                var detailModels = _mapper.Map <List <TWMProductionWhDetailEditModel>,
                                                List <TWMProductionWhDetailDbModel> >(requestObject.PostData.ChildList);

                var listItem = _db.Instance.Queryable <TMMWhApplyDetailDbModel>().Where(t => t.MainId == mainEntity.SourceId).ToList();

                var materList = BasicCacheGet.GetMaterial(currentUser);

                List <TMMWhApplyDetailDbModel> toEdit = new List <TMMWhApplyDetailDbModel>();


                foreach (var item in detailModels)
                {
                    var me = materList.Where(p => p.ID == item.MaterialId).FirstOrDefault();
                    var procudeMaterial = listItem.Where(p => p.ID == item.ProOrderDetailId).FirstOrDefault();//生产单明细
                    if (!detailFlag)
                    {
                        break;
                    }
                    item.MainId = mainModel.ID;

                    if (item.ID <= 0)                                                                                                      //新增
                    {
                        decimal proNum = UnitChange.TranserUnit(me, UnitType.Warehouse, UnitType.Produce, item.ActualNum);                 //实际转出数量(生产)

                        decimal wareTransNum = UnitChange.TranserUnit(me, UnitType.Produce, UnitType.Warehouse, procudeMaterial.TransNum); //可转的数量(仓库单位)

                        if (item.ActualNum > wareTransNum)
                        {
                            throw new Exception($"物料代码{me.MaterialCode} 入库数量不能大于{wareTransNum }");
                        }
                        else if (item.ActualNum == wareTransNum)
                        {
                            item.ProActualNum        = procudeMaterial.TransNum;
                            procudeMaterial.TransNum = 0;
                        }
                        else
                        {
                            if (proNum > procudeMaterial.TransNum)
                            {
                                item.ProActualNum        = procudeMaterial.TransNum;
                                procudeMaterial.TransNum = 0;
                            }
                            else
                            {
                                item.ProActualNum        = proNum;
                                procudeMaterial.TransNum = procudeMaterial.TransNum - proNum;
                            }
                        }

                        toEdit.Add(procudeMaterial);
                    }
                    else //修改
                    {
                        var dModel = _db.Instance.Queryable <TWMProductionWhDetailDbModel>().Where(p => p.ID == item.ID).First();
                        if (dModel != null)
                        {
                            if (dModel.ActualNum != item.ActualNum)
                            {
                                decimal proNum = UnitChange.TranserUnit(me, UnitType.Warehouse, UnitType.Produce, item.ActualNum); //实际转出数量(生产单位)

                                decimal TransNum = procudeMaterial.TransNum + dModel.ProActualNum;                                 //可转数量(生产单位)

                                decimal wareTransNum = UnitChange.TranserUnit(me, UnitType.Produce, UnitType.Warehouse, TransNum); //可转的数量(仓库单位)

                                if (item.ActualNum > wareTransNum)
                                {
                                    throw new Exception($"物料代码{me.MaterialCode} 入库数量不能大于{wareTransNum }");
                                }
                                else if (item.ActualNum == wareTransNum)
                                {
                                    item.ProActualNum        = TransNum;
                                    procudeMaterial.TransNum = 0;
                                }
                                else
                                {
                                    if (proNum > TransNum)
                                    {
                                        item.ProActualNum        = TransNum;
                                        procudeMaterial.TransNum = 0;
                                    }
                                    else
                                    {
                                        item.ProActualNum        = proNum;
                                        procudeMaterial.TransNum = TransNum - proNum;
                                    }
                                }

                                toEdit.Add(procudeMaterial);
                            }
                            else
                            {
                                item.ProActualNum = dModel.ProActualNum;
                            }
                        }
                    }

                    //新增或修改明细数据
                    detailFlag = item.ID <= 0
                        ? await currDb.Insertable(item).ExecuteCommandIdentityIntoEntityAsync()
                        : await currDb.Updateable(item).ExecuteCommandAsync() > 0;
                }

                //删除明细数据
                if (detailFlag)
                {
                    var detailIds    = detailModels.Select(p => p.ID).ToList();
                    var whDetailList = currDb.Queryable <TWMProductionWhDetailDbModel>().Where(p => !detailIds.Contains(p.ID) && p.MainId == mainModel.ID).ToList();

                    foreach (var item in whDetailList)
                    {
                        var dModel          = _db.Instance.Queryable <TWMProductionWhDetailDbModel>().Where(p => p.ID == item.ID).First();
                        var me              = materList.Where(p => p.ID == item.MaterialId).FirstOrDefault();
                        var procudeMaterial = listItem.Where(p => p.ID == item.ProOrderDetailId).FirstOrDefault();//生产单明细

                        procudeMaterial.TransNum = procudeMaterial.TransNum + dModel.ProActualNum;
                        toEdit.Add(procudeMaterial);
                    }

                    detailFlag = currDb.Deleteable <TWMProductionWhDetailDbModel>()
                                 .Where(p => !detailIds.Contains(p.ID) && p.MainId == mainModel.ID)
                                 .ExecuteCommand() >= 0;
                }

                if (toEdit != null && toEdit.Count() > 0)
                {
                    _db.Instance.Updateable <TMMWhApplyDetailDbModel>(toEdit).ExecuteCommand();
                }



                if (!_db.Instance.Queryable <TMMWhApplyDetailDbModel>().Any(p => p.TransNum > 0 && p.MainId == mainEntity.SourceId))
                {
                    _db.Instance.Updateable <TMMWhApplyMainDbModel>().Where(p => p.ID == mainEntity.SourceId).SetColumns(p => p.TransferFlag == false).ExecuteCommand();
                }
                else
                {
                    _db.Instance.Updateable <TMMWhApplyMainDbModel>().Where(p => p.ID == mainEntity.SourceId).SetColumns(p => p.TransferFlag == true).ExecuteCommand();
                }



                //提交事务
                currDb.CommitTran();

                var res = await GetWholeMainData(mainModel.ID, currentUser);

                //返回执行结果
                return(ResponseUtil <TWMProductionWhMainQueryModel> .SuccessResult(res.Data));
            }
            catch (Exception ex)
            {
                //回滚事务
                currDb.RollbackTran();
                //返回异常结果
                return(ResponseUtil <TWMProductionWhMainQueryModel> .FailResult(null, ex.Message));
            }
        }
Esempio n. 3
0
        /// <summary>
        /// 自动计算
        /// </summary>
        /// <param name="orderID">生产订单ID</param>
        /// <param name="Type">1,表示有配色,2表示无配色</param>
        /// <param name="currentUser">当前用户</param>
        /// <returns>计算是否成功</returns>
        public async Task <ResponseObject <MrpResultModel> > AutoComputeMRP(int orderID, int Type, CurrentUser currentUser)
        {
            try
            {
                TMMProductionOrderMainDbModel mainEntity = _db.Instance.Queryable <TMMProductionOrderMainDbModel>().Where(p => p.ID == orderID &&
                                                                                                                          p.CompanyId == currentUser.CompanyID && p.MRPStatus == false).First();

                if (mainEntity == null)
                {
                    return(ResponseUtil <MrpResultModel> .FailResult(null, "生产订单不存在,或MRP已经算过了不能重复计算"));
                }

                List <TBMMaterialFileCacheModel> MMaterialList = BasicCacheGet.GetMaterial(currentUser);

                _db.Instance.BeginTran();



                var bomResult = await _iTMMProductionOrderMainService.CreateOrderBom(mainEntity.ID, currentUser); //生成BOM清单

                if (!bomResult.Result)
                {
                    throw new Exception(bomResult.ErrorInfo);
                }

                //数据字典
                var tBMDictionary = _db.Instance.Queryable <TBMDictionaryDbModel>().Where(p => p.CompanyId == currentUser.CompanyID).ToList().ToDictionary(p => p.ID, p => p.DicValue);

                //仓库
                var warehouseDic = _db.Instance.Queryable <TBMWarehouseFileDbModel>().Where(t => SqlFunc.IsNull(t.DeleteFlag, false) != true &&
                                                                                            t.CompanyId == currentUser.CompanyID).ToList().ToDictionary(p => p.ID, p => new { Name = p.WarehouseName, Code = p.Code });

                List <InventoryResultModel> result = new List <InventoryResultModel>();

                //其他出入库
                var otherCount = _db.Instance.Queryable <TWMOtherCountDbModel>().
                                 Select(p => new InAndOutModel()
                {
                    MaterialId   = p.MaterialId,
                    WarehouseId  = p.WarehouseId,
                    WhNumber     = p.WhNumber,
                    WhSendNumber = p.WhSendNumber
                });

                //盘亏盘盈出入库
                var pCount = _db.Instance.Queryable <TWMProfitDeficitCountDbModel>().
                             Select(p => new InAndOutModel()
                {
                    MaterialId   = p.MaterialId,
                    WarehouseId  = p.WarehouseId,
                    WhNumber     = p.WhNumber,
                    WhSendNumber = p.WhSendNumber
                });

                //销售出入库
                var SaleCount = _db.Instance.Queryable <TWMSalesCountDbModel>().
                                Select(p => new InAndOutModel()
                {
                    MaterialId   = p.MaterialId,
                    WarehouseId  = p.WarehouseId,
                    WhNumber     = p.WhNumber,
                    WhSendNumber = p.WhSendNumber
                });

                //采购出入库
                var PurchaseCount = _db.Instance.Queryable <TWMPurchaseCountDbModel>().
                                    Select(p => new InAndOutModel()
                {
                    MaterialId   = p.MaterialId,
                    WarehouseId  = p.WarehouseId,
                    WhNumber     = p.WhNumber,
                    WhSendNumber = p.WhSendNumber
                });

                //生产出入库
                var ProductCount = _db.Instance.Queryable <TWMProductionCountDbModel>().
                                   Select(p => new InAndOutModel()
                {
                    MaterialId   = p.MaterialId,
                    WarehouseId  = p.WarehouseId,
                    WhNumber     = p.WhNumber,
                    WhSendNumber = p.WhSendNumber
                });

                //出入库数量
                var allCount = _db.Instance.UnionAll(otherCount, pCount, SaleCount, PurchaseCount, ProductCount).GroupBy(p => new { p.MaterialId }).
                               Select(p => new TradeInventoryModel()
                {
                    TradeNumber = SqlFunc.AggregateSum(p.WhNumber) - SqlFunc.AggregateSum(p.WhSendNumber),
                    MaterialId  = p.MaterialId,
                }).AS("t100");

                var materialFileQuery = _db.Instance.Queryable <TMMProductionOrderBOMSumDbModel>().Where(p => p.ProOrderId == orderID);

                var ts = _db.Instance.Queryable(materialFileQuery, allCount, JoinType.Inner, (p1, p2) => p1.MaterialId == p2.MaterialId).Select((p1, p2) => new InventoryOut
                {
                    MaterialId = p2.MaterialId,
                    Amount     = p2.TradeNumber
                });

                //销售单 所有物料的出入库数量
                var tsout1 = ts.ToList();
                var tsOut  = tsout1.GroupBy(p => p.MaterialId).Select(p => new InventoryOut()
                {
                    MaterialId = p.Key, Amount = p.Sum(m => m.Amount)
                }).ToList();

                #region 待出库数量

                //其他待出库
                var otherToOut = _db.Instance.Queryable <TWMOtherWhSendMainDbModel, TWMOtherWhSendDetailDbModel>((t1, t2) =>
                                                                                                                 new object[] { JoinType.Inner, t1.ID == t2.MainId }).Where((t1, t2) =>
                                                                                                                                                                            t1.AuditStatus != 2 &&
                                                                                                                                                                            t1.DeleteFlag == false).Select((t1, t2) => new InventoryOut {
                    MaterialId = t2.MaterialId, Amount = t2.ActualNumber
                });

                //盘亏出库
                var deficitToOut = _db.Instance.Queryable <TWMDeficitMainDbModel, TWMDeficitDetailDbModel>((t1, t2) =>
                                                                                                           new object[] { JoinType.Inner, t1.ID == t2.MainId }).Where((t1, t2) =>
                                                                                                                                                                      t1.AuditStatus != 2 &&
                                                                                                                                                                      t1.DeleteFlag == false).Select((t1, t2) => new InventoryOut {
                    MaterialId = t2.MaterialId, Amount = t2.ActualNumber
                });

                //销售出库
                var saleToOut = _db.Instance.Queryable <TWMSalesMainDbModel, TWMSalesDetailDbModel>((t1, t2) =>
                                                                                                    new object[] { JoinType.Inner, t1.ID == t2.MainId }).Where((t1, t2) =>
                                                                                                                                                               t1.AuditStatus != 2 &&
                                                                                                                                                               t1.DeleteFlag == false).Select((t1, t2) => new InventoryOut {
                    MaterialId = t2.MaterialId, Amount = t2.ActualNum
                });

                //生产待出库
                var productToOut = _db.Instance.Queryable <TWMProductionMainDbModel, TWMProductionDetailDbModel>((t1, t2) =>
                                                                                                                 new object[] { JoinType.Inner, t1.ID == t2.MainId }).Where((t1, t2) =>
                                                                                                                                                                            t1.AuditStatus != 2 &&
                                                                                                                                                                            t1.DeleteFlag == false).Select((t1, t2) => new InventoryOut {
                    MaterialId = t2.MaterialId, Amount = t2.ActualNum
                });

                var allToOut = _db.Instance.UnionAll(otherToOut, deficitToOut, saleToOut, productToOut).AS("t101");

                var materialFileQuery1 = _db.Instance.Queryable <TMMProductionOrderBOMSumDbModel>().Where(p => p.ProOrderId == orderID);

                var tsToOut = _db.Instance.Queryable(materialFileQuery1, allToOut, JoinType.Inner, (p1, p2) => p1.ID == p2.MaterialId).Select((p1, p2) => new InventoryOut
                {
                    MaterialId = p2.MaterialId,
                    Amount     = p2.Amount
                });



                //销售单所有物料的待出库数量
                var tsToOutSum = tsToOut.ToList().GroupBy(p => p.MaterialId).Select(p => new InventoryOut()
                {
                    MaterialId = p.Key, Amount = p.Sum(m => m.Amount)
                }).ToList();


                #endregion

                //期初
                List <InventoryOut> prime = _db.Instance.Queryable <TMMProductionOrderBOMSumDbModel, TWMPrimeCountDbModel>((t, t1) => new object[] {
                    JoinType.Inner, t.MaterialId == t1.MaterialId
                }).Select((t, t1) => t1).Distinct().ToList().GroupBy(p => p.MaterialId).Select(p => new InventoryOut()
                {
                    MaterialId = p.Key, Amount = p.Sum(m => m.PrimeNum)
                }).ToList();;


                var Allmaterial = _db.Instance.Queryable <TMMProductionOrderBOMSumDbModel>().Where(p => p.ProOrderId == orderID).ToList();


                Dictionary <int, string> colorSolution = _db.Instance.Queryable <TMMColorSolutionMainDbModel, TBMPackageDbModel>((t1, t2) =>
                                                                                                                                 new object[] { JoinType.Inner, t1.PackageId == t2.ID }).
                                                         Where((t1, t2) => t2.CompanyId == currentUser.CompanyID).ToList().ToDictionary(p => p.ID, p => p.SolutionCode);

                List <int> colorIDS = colorSolution.Keys.ToList();

                //生产订单的所有物料
                List <TMMProductionOrderBOMSumDbModel> sumList = _db.Instance.Queryable <TMMProductionOrderBOMSumDbModel>().Where(p => p.ProOrderId == orderID).ToList();


                foreach (var item in sumList)
                {
                    decimal primeAmount = 0; //期初数量
                    decimal TradeNumber = 0; //出入库数量
                    decimal toOutAmount = 0; //待出数量

                    TBMMaterialFileCacheModel materialFile = MMaterialList.Where(p => p.ID == item.MaterialId).FirstOrDefault();
                    if (materialFile == null)
                    {
                        throw new Exception($"物料ID:{item.MaterialId},不存在");
                    }


                    InventoryOut primeEntity = prime.Where(p => p.MaterialId == item.MaterialId).FirstOrDefault();
                    if (primeEntity != null)
                    {
                        primeAmount = primeEntity.Amount;
                    }


                    InventoryOut tradeEntity = tsOut.Where(p => p.MaterialId == item.MaterialId).FirstOrDefault();
                    if (tradeEntity != null)
                    {
                        TradeNumber = tradeEntity.Amount;
                    }

                    InventoryOut toOutEntity = tsToOutSum.Where(p => p.MaterialId == item.MaterialId).FirstOrDefault();
                    if (toOutEntity != null)
                    {
                        toOutAmount = toOutEntity.Amount;
                    }

                    decimal avaibleAmountUnit = primeAmount + TradeNumber - toOutAmount;                                                   //仓库数量

                    decimal avaibleAmount = UnitChange.TranserUnit(materialFile, UnitType.Warehouse, UnitType.Produce, avaibleAmountUnit); //生产数量

                    if (avaibleAmount >= item.TotalValue)
                    {
                        item.PurchaseNum = 0;
                        item.PickNum     = item.TotalValue;
                    }
                    else
                    {
                        if (avaibleAmount < 0)
                        {
                            avaibleAmount = 0;
                        }
                        item.PurchaseNum = item.TotalValue - avaibleAmount;
                        item.PickNum     = avaibleAmount;
                    }

                    item.PurchaseTransNum = 0;
                    item.PickTransNum     = 0;
                }

                if (sumList.Count() > 0)
                {
                    _db.Instance.Updateable(sumList).ExecuteCommand();
                }

                mainEntity.MRPStatus = true;
                mainEntity.MRPTime   = DateTime.Now;

                _db.Instance.Updateable(mainEntity).UpdateColumns(p => new { p.MRPStatus, p.MRPTime }).ExecuteCommand();

                _db.Instance.CommitTran();

                MrpResultModel bomList;
                if (Type == 1)
                {
                    bomList = GetProcuctBomByOrderID(orderID, currentUser);
                }
                else
                {
                    bomList = GetProcuctBomByOrderID(orderID, currentUser);
                }
                return(ResponseUtil <MrpResultModel> .SuccessResult(bomList));
            }
            catch (Exception ex)
            {
                _db.Instance.RollbackTran();
                return(ResponseUtil <MrpResultModel> .FailResult(null, ex.Message));
            }
        }
Esempio n. 4
0
        /// <summary>
        /// 新增T_WM_ProductionWhMain数据
        /// </summary>
        /// <param name="requestObject">Post请求参数</param>
        /// <returns>返回响应结果对象,包括响应代码,新增操作结果</returns>
        public async Task <ResponseObject <TWMProductionWhMainQueryModel> > PostAsync(RequestPost <TWMProductionWhMainAddModel> requestObject, CurrentUser currentUser)
        {
            var currDb = _db.Instance;//事务需要使用同一个 SqlSugarClient对象实例

            try
            {
                //没有新增数据,返回错误信息
                if (requestObject.PostData == null)
                {
                    return(ResponseUtil <TWMProductionWhMainQueryModel> .FailResult(null, "PostData不能为null"));
                }
                //开启事务
                currDb.BeginTran();
                //插入主表数据
                var mapMainModel = _mapper.Map <TWMProductionWhMainDbModel>(requestObject.PostData);
                mapMainModel.CompanyId       = currentUser.CompanyID;
                mapMainModel.OperatorId      = currentUser.UserID;
                mapMainModel.Number          = requestObject.PostData.ChildList.Sum(p => p.ActualNum);
                mapMainModel.Amount          = requestObject.PostData.ChildList.Sum(p => p.Amount);
                mapMainModel.AuditStatus     = 0;
                mapMainModel.WarehousingType = 1;
                var mainId = await currDb.Insertable(mapMainModel).ExecuteReturnIdentityAsync();

                //更新明细表外键ID值
                requestObject.PostData.ChildList.ForEach(p => p.MainId = mainId);
                //插入从表数据
                var mapDetailModelList = _mapper.Map <List <TWMProductionWhDetailAddModel>, List <TWMProductionWhDetailDbModel> >(requestObject.PostData.ChildList);


                var listItem = _db.Instance.Queryable <TMMWhApplyDetailDbModel>().Where(t => t.MainId == mapMainModel.SourceId).ToList();

                var materList = BasicCacheGet.GetMaterial(currentUser);

                List <TMMWhApplyDetailDbModel> toEdit = new List <TMMWhApplyDetailDbModel>();

                foreach (var item in mapDetailModelList)
                {
                    var procudeMaterial = listItem.Where(p => p.ID == item.ProOrderDetailId).FirstOrDefault();                         //生产单明细

                    var me = materList.Where(p => p.ID == item.MaterialId).FirstOrDefault();                                           //物料

                    decimal wareTransNum = UnitChange.TranserUnit(me, UnitType.Produce, UnitType.Warehouse, procudeMaterial.TransNum); //可转的数量(仓库单位)
                    decimal proNum       = UnitChange.TranserUnit(me, UnitType.Warehouse, UnitType.Produce, item.ActualNum);           //实际转数量(生产单位)

                    if (item.ActualNum > wareTransNum)
                    {
                        throw new Exception($"物料代码{me.MaterialCode} 入库数量不能大于{wareTransNum }");
                    }
                    else if (item.ActualNum == wareTransNum)
                    {
                        item.ProActualNum        = procudeMaterial.TransNum;
                        procudeMaterial.TransNum = 0;
                    }
                    else
                    {
                        if (proNum > procudeMaterial.TransNum)
                        {
                            item.ProActualNum        = procudeMaterial.TransNum;
                            procudeMaterial.TransNum = 0;
                        }
                        else
                        {
                            item.ProActualNum        = proNum;
                            procudeMaterial.TransNum = procudeMaterial.TransNum - proNum;
                        }
                    }

                    toEdit.Add(procudeMaterial);
                }

                if (toEdit != null && toEdit.Count() > 0)
                {
                    _db.Instance.Updateable <TMMWhApplyDetailDbModel>(toEdit).ExecuteCommand();
                }

                if (!_db.Instance.Queryable <TMMWhApplyDetailDbModel>().Any(p => p.TransNum > 0 && p.MainId == mapMainModel.SourceId))
                {
                    _db.Instance.Updateable <TMMWhApplyMainDbModel>().Where(p => p.ID == mapMainModel.SourceId).SetColumns(p => p.TransferFlag == false).ExecuteCommand();
                }

                var result = await currDb.Insertable(mapDetailModelList).ExecuteCommandAsync() > 0;

                //提交事务
                currDb.CommitTran();

                var res = await GetWholeMainData(mainId, currentUser);

                //返回执行结果
                return(ResponseUtil <TWMProductionWhMainQueryModel> .SuccessResult(res.Data));
            }
            catch (Exception ex)
            {
                //回滚事务
                currDb.RollbackTran();
                //返回异常结果
                return(ResponseUtil <TWMProductionWhMainQueryModel> .FailResult(null, ex.Message));
            }
        }
        private async Task <ResponseObject <List <TPSMPurchaseOrderDetailQueryModel> > > GetDetialList(int requestObject, CurrentUser currentUser)
        {
            try
            {
                //查询结果集对象
                List <TPSMPurchaseOrderDetailQueryModel> queryData = null;
                //总记录数
                RefAsync <int> totalNumber = -1;

                var query = _db.Instance.Queryable <TPSMPurchaseOrderDetailDbModel, TBMMaterialFileDbModel,
                                                    TBMDictionaryDbModel, TBMDictionaryDbModel, TBMDictionaryDbModel, TBMDictionaryDbModel,
                                                    TBMDictionaryDbModel, TPSMPurchaseOrderMainDbModel, TBMSupplierFileDbModel>(
                    (t, t0, t1, t2, t3, t4, t5, t6, t7) => new object[]
                {
                    JoinType.Left, t.MaterialId == t0.ID,
                    JoinType.Left, t0.MaterialTypeId == t1.ID,
                    JoinType.Left, t0.ColorId == t2.ID,
                    JoinType.Left, t0.BaseUnitId == t3.ID,
                    JoinType.Left, t0.PurchaseUnitId == t4.ID,
                    JoinType.Left, t0.WarehouseUnitId == t5.ID,
                    JoinType.Inner, t.MainId == t6.ID,
                    JoinType.Left, t.SupplierId == t7.ID
                });

                //执行查询
                queryData = await query
                            .Select((t, t0, t1, t2, t3, t4, t5, t6, t7) => new TPSMPurchaseOrderDetailQueryModel
                {
                    ID                = t.ID,
                    MainId            = t.MainId,
                    SupplierId        = t.SupplierId,
                    SupplierName      = t7.SupplierName,
                    MaterialId        = t.MaterialId,
                    MaterialName      = t0.MaterialName,
                    MaterialCode      = t0.MaterialCode,
                    MaterialTypeId    = t0.MaterialTypeId,
                    MaterialTypeName  = t1.DicValue,
                    ColorId           = t0.ColorId,
                    ColorName         = t2.DicValue,
                    Spec              = t0.Spec,
                    BaseUnitId        = t0.BaseUnitId,
                    BaseUnitName      = t3.DicValue,
                    PurchaseUnitId    = t0.PurchaseUnitId,
                    PurchaseUnitName  = SqlFunc.IsNullOrEmpty(t4.ID) ? t3.DicValue : t4.DicValue,
                    PurchaseRate      = t0.PurchaseRate,
                    WarehouseUnitId   = t0.WarehouseUnitId,
                    WarehouseUnitName = SqlFunc.IsNullOrEmpty(t5.ID) ? t3.DicValue : t5.DicValue,
                    WarehouseRate     = t0.WarehouseRate,
                    UnitPrice         = t.UnitPrice,
                    PurchaseAmount    = t.PurchaseAmount,
                    PurchaseNum       = t.PurchaseNum,
                    DeliveryPeriod    = t.DeliveryPeriod,
                    TransferNum       = t.TransferNum,
                    Remark            = t.Remark,
                    ProduceRate       = t0.ProduceRate,
                    ProduceUnitId     = t0.ProduceUnitId,
                    AuditStatus       = t6.AuditStatus
                })
                            .Where(t => t.MainId == requestObject)
                            .ToListAsync();


                var mainEntity = _db.Instance.Queryable <TPSMPurchaseOrderMainDbModel>().Where(p => p.ID == requestObject).First();

                List <TBMMaterialFileCacheModel> mList = BasicCacheGet.GetMaterial(currentUser);

                //计算生产采购申请单转生产采购单数量
                var prodList = await _db.Instance.Queryable <TMMPurchaseApplyDetailDbModel, TMMPurchaseApplyMainDbModel>
                                   ((t, t0) => new object[] { JoinType.Left, t.MainId == t0.ID })
                               .Where((t, t0) => t0.ID == SqlFunc.Subqueryable <TPSMPurchaseOrderMainDbModel>().Where(p => p.ID == requestObject).Select(p => (int)p.SourceId))
                               .ToListAsync();

                queryData.ForEach(p =>
                {
                    var me = mList.Where(x => x.ID == p.MaterialId).FirstOrDefault();
                    if (mainEntity.SourceId > 0)
                    {
                        p.ProdTransNum = prodList.Where(p1 => p1.MaterialId == p.MaterialId).First().TransNum;
                    }

                    p.TransferWareNum = UnitChange.TranserUnit(me, UnitType.Purchase, UnitType.Warehouse, p.TransferNum);
                });

                //返回执行结果
                return(ResponseUtil <List <TPSMPurchaseOrderDetailQueryModel> > .SuccessResult(queryData, totalNumber));
            }
            catch (Exception ex)
            {
                //返回查询异常结果
                return(ResponseUtil <List <TPSMPurchaseOrderDetailQueryModel> > .FailResult(null, ex.Message));
            }
        }
        /// <summary>
        /// 修改T_WM_SalesMain数据
        /// </summary>
        /// <param name="requestObject">Put请求参数</param>
        /// <returns>返回响应结果对象,包括响应代码,修改操作结果</returns>
        public async Task <ResponseObject <TWMSalesMainQueryModel> > PutAsync(RequestPut <TWMSalesMainEditModel> requestObject, CurrentUser currentUser)
        {
            var currDb = _db.Instance;//事务需要使用同一个 SqlSugarClient对象实例

            try
            {
//#if DEBUG

//#else
//                     return null;
//#endif

                if (requestObject.PostData == null)
                {
                    return(ResponseUtil <TWMSalesMainQueryModel> .FailResult(null, "PostData不能为null"));
                }
                if (requestObject.PostData.ChildList == null || requestObject.PostData.ChildList.Count < 1)
                {
                    return(ResponseUtil <TWMSalesMainQueryModel> .FailResult(null, "PostData.ChildList至少包含一条数据"));
                }
                //开启事务
                currDb.BeginTran();

                //修改主表信息
                var mainModel = _mapper.Map <TWMSalesMainDbModel>(requestObject.PostData);
                mainModel.Number = requestObject.PostData.ChildList.Sum(p => p.ActualNum);
                mainModel.Amount = requestObject.PostData.ChildList.Sum(p => p.Amount);

                var mainFlag = await currDb.Updateable(mainModel).UpdateColumns(p => new
                {
                    p.WhSendDate,
                    p.Number,
                    p.Amount,
                    p.SendId,
                    p.WhAdminId,
                    p.ReceiptAddress
                }).ExecuteCommandAsync() > 0;

                /*
                 * 修改明细逻辑
                 * 1.根据主单ID查询现有明细数据
                 * 2.PostData.ChildList中明细ID <= 0的新增
                 * 3.PostData.ChildList中明细ID > 0的修改
                 * 4.删除不在PostData.CihldList中的数据
                 */
                var detailFlag   = true;
                var detailModels = _mapper.Map <List <TWMSalesDetailEditModel>,
                                                List <TWMSalesDetailDbModel> >(requestObject.PostData.ChildList);

                var mainEntity = _db.Instance.Queryable <TWMSalesMainDbModel>().Where(p => p.ID == mainModel.ID).First();

                var listItem = _db.Instance.Queryable <TSSMSalesOrderDetailDbModel>().Where(t => t.MainId == mainEntity.SourceId).ToList();

                var materList = BasicCacheGet.GetMaterial(currentUser);

                List <TSSMSalesOrderDetailDbModel> toEdit = new List <TSSMSalesOrderDetailDbModel>();

                foreach (var item in detailModels)
                {
                    if (!detailFlag)
                    {
                        break;
                    }
                    item.MainId = mainModel.ID;
                    var procudeMaterial = listItem.Where(p => p.ID == item.SalesOrderDetailId).FirstOrDefault();//销售合同明细
                    var me = materList.Where(p => p.ID == item.MaterialId).FirstOrDefault();

                    if (!detailFlag)
                    {
                        break;
                    }
                    item.MainId = mainModel.ID;

                    if (item.ID <= 0) //新增
                    {
                        decimal proNum = UnitChange.TranserUnit(me, UnitType.Warehouse, UnitType.Sales, item.ActualNum);

                        decimal wareTransNum = UnitChange.TranserUnit(me, UnitType.Sales, UnitType.Warehouse, procudeMaterial.TransferNum);//可转的数量(仓库单位)
                        if (item.ActualNum > wareTransNum)
                        {
                            throw new Exception($"物料代码{me.MaterialCode} 出库数量不能大于{wareTransNum }");
                        }
                        else if (item.ActualNum == wareTransNum)
                        {
                            item.SalesOrderActualNum    = procudeMaterial.TransferNum;
                            procudeMaterial.TransferNum = 0;
                        }
                        else
                        {
                            if (proNum > procudeMaterial.TransferNum)
                            {
                                item.SalesOrderActualNum    = procudeMaterial.TransferNum;
                                procudeMaterial.TransferNum = 0;
                            }
                            else
                            {
                                item.SalesOrderActualNum    = proNum;
                                procudeMaterial.TransferNum = procudeMaterial.TransferNum - proNum;
                            }
                        }
                        toEdit.Add(procudeMaterial);
                        //decimal proNum = UnitChange.TranserUnit(me, UnitType.Warehouse, UnitType.Sales, item.ActualNum);

                        //var m = listItem.Where(p => p.MaterialId == item.MaterialId).FirstOrDefault();
                        //if (m != null)
                        //{
                        //    if (m.TransferNum < proNum)
                        //    {
                        //        throw new Exception($"物料代码{me.MaterialCode} 出库数量不能大于{proNum }");
                        //    }
                        //    m.TransferNum = m.TransferNum - proNum;

                        //    toEdit.Add(m);
                        //}
                    }
                    else //修改
                    {
                        var dModel = _db.Instance.Queryable <TWMSalesDetailDbModel>().Where(p => p.ID == item.ID).First();
                        if (dModel != null)
                        {
                            if (dModel.ActualNum != item.ActualNum)
                            {
                                #region

                                ////原出库数量(销售单位)
                                //decimal oldActualNumPro = UnitChange.TranserUnit(me, UnitType.Warehouse, UnitType.Sales, dModel.ActualNum);
                                //decimal TransNum = procudeMaterial.TransferNum + item.SalesOrderActualNum; //可转数量(生产单位)
                                ////现出库数量(销售单位)
                                //decimal nowActualNumPro = UnitChange.TranserUnit(me, UnitType.Warehouse, UnitType.Sales, item.ActualNum);


                                //if (item.ActualNum > nowActualNumPro)
                                //{
                                //    throw new Exception($"物料代码{me.MaterialCode} 入库数量不能大于{nowActualNumPro }");
                                //}
                                //else if (item.ActualNum == nowActualNumPro)
                                //{
                                //    item.SalesOrderActualNum = TransNum;
                                //    procudeMaterial.TransferNum = 0;
                                //}
                                //else
                                //{
                                //    if (oldActualNumPro > TransNum)
                                //    {
                                //        item.SalesOrderActualNum = TransNum;
                                //        procudeMaterial.TransferNum = 0;
                                //    }
                                //    else
                                //    {
                                //        item.SalesOrderActualNum = oldActualNumPro;
                                //        procudeMaterial.TransferNum = TransNum - oldActualNumPro;
                                //    }
                                //}

                                #endregion

                                decimal saleNum = UnitChange.TranserUnit(me, UnitType.Warehouse, UnitType.Sales, item.ActualNum); //实际转出数量(销售单位)

                                decimal TransNum = procudeMaterial.TransferNum + dModel.SalesOrderActualNum;                      //可转数量(生产单位)

                                decimal wareTransNum = UnitChange.TranserUnit(me, UnitType.Sales, UnitType.Warehouse, TransNum);  //可转的数量(仓库单位)

                                if (item.ActualNum > wareTransNum)
                                {
                                    throw new Exception($"物料代码{me.MaterialCode} 入库数量不能大于{wareTransNum }");
                                }
                                else if (item.ActualNum == wareTransNum)
                                {
                                    item.SalesOrderActualNum    = TransNum;
                                    procudeMaterial.TransferNum = 0;
                                }
                                else
                                {
                                    if (saleNum > TransNum)
                                    {
                                        item.SalesOrderActualNum    = TransNum;
                                        procudeMaterial.TransferNum = 0;
                                    }
                                    else
                                    {
                                        item.SalesOrderActualNum    = saleNum;
                                        procudeMaterial.TransferNum = TransNum - saleNum;
                                    }
                                }

                                toEdit.Add(procudeMaterial);
                                //var m = listItem.Where(p => p.MaterialId == item.MaterialId).FirstOrDefault();
                                //if (m != null)
                                //{
                                //    if (m.TransferNum + oldActualNumPro < nowActualNumPro)
                                //    {
                                //        throw new Exception($"物料代码{me.MaterialCode} 出库数量不能大于{m.TransferNum + oldActualNumPro }");
                                //    }
                                //    m.TransferNum = m.TransferNum + oldActualNumPro - nowActualNumPro;

                                //    toEdit.Add(m);
                                //}
                            }
                            else
                            {
                                item.SalesOrderActualNum = dModel.SalesOrderActualNum;
                            }
                        }
                    }



                    //新增或修改明细数据
                    detailFlag = item.ID <= 0
                        ? await currDb.Insertable(item).ExecuteCommandIdentityIntoEntityAsync()
                        : await currDb.Updateable(item).ExecuteCommandAsync() > 0;
                }


                //删除明细数据
                if (detailFlag)
                {
                    var detailIds    = detailModels.Select(p => p.ID).ToList();
                    var whDetailList = currDb.Queryable <TWMSalesDetailDbModel>().Where(p => !detailIds.Contains(p.ID) && p.MainId == mainModel.ID).ToList();

                    foreach (var item in whDetailList)
                    {
                        var me = materList.Where(p => p.ID == item.MaterialId).FirstOrDefault();
                        //decimal proNum = UnitChange.TranserUnit(me, UnitType.Warehouse, UnitType.Sales, item.ActualNum);

                        var m = listItem.Where(p => p.MaterialId == item.MaterialId).FirstOrDefault();
                        if (m != null)
                        {
                            m.TransferNum = m.TransferNum + item.SalesOrderActualNum;
                            toEdit.Add(m);
                        }
                    }

                    detailFlag = currDb.Deleteable <TWMSalesDetailDbModel>()
                                 .Where(p => !detailIds.Contains(p.ID) && p.MainId == mainModel.ID)
                                 .ExecuteCommand() >= 0;
                }

                #region 检查出库是否超过可用量

                int?iMainId = mainModel.ID;
                var mList   = BasicCacheGet.GetMaterial(currentUser);

                var details = requestObject.PostData.ChildList.GroupBy(p => new { p.MaterialId, p.WarehouseId }).Select(p => new TWMOtherCountDbModel
                {
                    MaterialId   = p.Key.MaterialId,
                    WarehouseId  = p.Key.WarehouseId,
                    WhSendNumber = p.Sum(p1 => p1.ActualNum)
                }).ToList();

                foreach (var item in details)
                {
                    TWMStaQuery tWMStaQuery = new TWMStaQuery();
                    tWMStaQuery.EditID      = iMainId;
                    tWMStaQuery.MaterialId  = item.MaterialId;
                    tWMStaQuery.WarehouseId = item.WarehouseId;

                    decimal AvaiableNum = _staticInventory.GeTWMCountModel(tWMStaQuery).AvaiableNum;
                    if (AvaiableNum < 0)
                    {
                        var me = materList.Where(p => p.ID == item.MaterialId).FirstOrDefault();
                        throw new Exception($"物料代码:{me.MaterialCode},物料名称{me.MaterialName}的物料可用量不足");
                    }
                    if (item.WhSendNumber > AvaiableNum)
                    {
                        var me = mList.Where(p => p.ID == item.MaterialId).FirstOrDefault();
                        throw new Exception($"物料代码:{me.MaterialCode},物料名称{me.MaterialName}的物料出库数量不能大于{AvaiableNum}");
                    }
                }

                #endregion

                if (toEdit.Count() > 0)
                {
                    _db.Instance.Updateable(toEdit).ExecuteCommand();
                }

                if (!_db.Instance.Queryable <TSSMSalesOrderDetailDbModel>().Any(p => p.TransferNum > 0 && p.MainId == mainEntity.SourceId))
                {
                    _db.Instance.Updateable <TSSMSalesOrderMainDbModel>().Where(p => p.ID == mainEntity.SourceId).SetColumns(p => p.TransferStatus == false).ExecuteCommand();
                }
                else
                {
                    _db.Instance.Updateable <TSSMSalesOrderMainDbModel>().Where(p => p.ID == mainEntity.SourceId).SetColumns(p => p.TransferStatus == true).ExecuteCommand();
                }

                //提交事务
                currDb.CommitTran();

                var resultTemp = await GetWholeMainData(requestObject.PostData.ID, currentUser);

                return(ResponseUtil <TWMSalesMainQueryModel> .SuccessResult(resultTemp.Data));
            }
            catch (Exception ex)
            {
                //回滚事务
                currDb.RollbackTran();
                //返回异常结果
                return(ResponseUtil <TWMSalesMainQueryModel> .FailResult(null, ex.Message));
            }
        }
        /// <summary>
        /// 新增T_WM_SalesMain数据
        /// </summary>
        /// <param name="requestObject">Post请求参数</param>
        /// <returns>返回响应结果对象,包括响应代码,新增操作结果</returns>
        public async Task <ResponseObject <TWMSalesMainQueryModel> > PostAsync(RequestPost <TWMSalesMainAddModel> requestObject, CurrentUser currentUser)
        {
            var currDb = _db.Instance;//事务需要使用同一个 SqlSugarClient对象实例

            try
            {
                //没有新增数据,返回错误信息
                if (requestObject.PostData == null)
                {
                    return(ResponseUtil <TWMSalesMainQueryModel> .FailResult(null, "PostData不能为null"));
                }
                //开启事务
                currDb.BeginTran();
                //插入主表数据
                var mapMainModel = _mapper.Map <TWMSalesMainDbModel>(requestObject.PostData);
                mapMainModel.CompanyId   = currentUser.CompanyID;
                mapMainModel.OperatorId  = currentUser.UserID;
                mapMainModel.Number      = requestObject.PostData.ChildList.Sum(p => p.ActualNum);
                mapMainModel.Amount      = requestObject.PostData.ChildList.Sum(p => p.Amount);
                mapMainModel.AuditStatus = 0;
                var mainId = await currDb.Insertable(mapMainModel).ExecuteReturnIdentityAsync();

                //更新明细表外键ID值
                requestObject.PostData.ChildList.ForEach(p => p.MainId = mainId);
                //插入从表数据
                var mapDetailModelList = _mapper.Map <List <TWMSalesDetailAddModel>, List <TWMSalesDetailDbModel> >(requestObject.PostData.ChildList);

                #region 检查出库是否超过可用量

                int?iMainId   = mainId;
                var materList = BasicCacheGet.GetMaterial(currentUser);

                var details = requestObject.PostData.ChildList.GroupBy(p => new { p.MaterialId, p.WarehouseId }).Select(p => new TWMOtherCountDbModel
                {
                    MaterialId   = p.Key.MaterialId,
                    WarehouseId  = p.Key.WarehouseId,
                    WhSendNumber = p.Sum(p1 => p1.ActualNum)
                }).ToList();

                foreach (var item in details)
                {
                    TWMStaQuery tWMStaQuery = new TWMStaQuery();
                    tWMStaQuery.EditID      = iMainId;
                    tWMStaQuery.MaterialId  = item.MaterialId;
                    tWMStaQuery.WarehouseId = item.WarehouseId;

                    decimal AvaiableNum = _staticInventory.GeTWMCountModel(tWMStaQuery).AvaiableNum;
                    if (AvaiableNum < 0)
                    {
                        var me = materList.Where(p => p.ID == item.MaterialId).FirstOrDefault();
                        throw new Exception($"物料代码:{me.MaterialCode},物料名称{me.MaterialName}的物料可用量不足");
                    }
                    if (item.WhSendNumber > AvaiableNum)
                    {
                        var me = materList.Where(p => p.ID == item.MaterialId).FirstOrDefault();
                        throw new Exception($"物料代码:{me.MaterialCode},物料名称{me.MaterialName}的物料出库数量不能大于{AvaiableNum}");
                    }
                }

                #endregion
                #region 处理销售单的可转单数量


                var listItem = _db.Instance.Queryable <TSSMSalesOrderDetailDbModel>().Where(t => t.MainId == mapMainModel.SourceId).ToList();//来源单据


                List <TSSMSalesOrderDetailDbModel> toEdit = new List <TSSMSalesOrderDetailDbModel>();

                foreach (var item in mapDetailModelList)
                {
                    var procudeMaterial = listItem.Where(p => p.ID == item.SalesOrderDetailId).FirstOrDefault(); //销售合同明细

                    var me = materList.Where(p => p.ID == item.MaterialId).FirstOrDefault();                     //物料

                    decimal proNum       = UnitChange.TranserUnit(me, UnitType.Warehouse, UnitType.Sales, item.ActualNum);
                    decimal wareTransNum = UnitChange.TranserUnit(me, UnitType.Sales, UnitType.Warehouse, procudeMaterial.TransferNum);//可转的数量(仓库单位)

                    if (item.ActualNum > wareTransNum)
                    {
                        throw new Exception($"物料代码{me.MaterialCode} 出库数量不能大于{wareTransNum }");
                    }
                    else if (item.ActualNum == wareTransNum)
                    {
                        item.SalesOrderActualNum    = procudeMaterial.TransferNum;
                        procudeMaterial.TransferNum = 0;
                    }
                    else
                    {
                        if (proNum > procudeMaterial.TransferNum)
                        {
                            item.SalesOrderActualNum    = procudeMaterial.TransferNum;
                            procudeMaterial.TransferNum = 0;
                        }
                        else
                        {
                            item.SalesOrderActualNum    = proNum;
                            procudeMaterial.TransferNum = procudeMaterial.TransferNum - proNum;
                        }
                    }

                    toEdit.Add(procudeMaterial);
                    //var m = listItem.Where(p => p.MaterialId == item.MaterialId).FirstOrDefault();
                    //if (m != null)
                    //{
                    //    if (m.TransferNum < proNum)
                    //    {
                    //        throw new Exception($"物料代码{me.MaterialCode} 出库数量不能大于{proNum }");
                    //    }
                    //    m.TransferNum = m.TransferNum - proNum;

                    //    toEdit.Add(m);
                    //}
                }

                if (toEdit.Count() > 0)
                {
                    _db.Instance.Updateable(toEdit).ExecuteCommand();
                }

                if (!_db.Instance.Queryable <TSSMSalesOrderDetailDbModel>().Any(p => p.TransferNum > 0 && p.MainId == mapMainModel.SourceId))
                {
                    _db.Instance.Updateable <TSSMSalesOrderMainDbModel>().Where(p => p.ID == mapMainModel.SourceId).SetColumns(p => p.TransferStatus == false).ExecuteCommand();
                }

                #endregion

                var result = await currDb.Insertable(mapDetailModelList).ExecuteCommandAsync() > 0;

                //提交事务
                currDb.CommitTran();
                //返回执行结果

                var resultTemp = await GetWholeMainData(mainId, currentUser);

                return(ResponseUtil <TWMSalesMainQueryModel> .SuccessResult(resultTemp.Data));
            }
            catch (Exception ex)
            {
                //回滚事务
                currDb.RollbackTran();
                //返回异常结果
                return(ResponseUtil <TWMSalesMainQueryModel> .FailResult(null, ex.Message));
            }
        }
        /// <summary>
        /// 删除T_WM_PurchaseMain数据
        /// </summary>
        /// <param name="requestObject">Delete请求参数</param>
        /// <returns>返回响应结果对象,包括响应代码,删除操作结果</returns>
        public async Task <ResponseObject <bool> > DeleteAsync(RequestDelete <DeleteModel> requestObject, CurrentUser currentUser)
        {
            var currDb = _db.Instance;//事务需要使用同一个 SqlSugarClient对象实例

            try
            {
                if (requestObject.PostData == null && requestObject.PostDataList == null)
                {
                    return(ResponseUtil <bool> .FailResult(false, "PostData、PostDataList不能都为null"));
                }
                //开启事务
                currDb.BeginTran();

                //删除标识
                List <int> IDS       = new List <int>();
                var        materList = BasicCacheGet.GetMaterial(currentUser);

                if (requestObject.PostDataList != null && requestObject.PostDataList.Count > 0)
                {
                    IDS = requestObject.PostDataList.Select(p => p.ID).ToList();
                    //批量删除
                    var mainIds = requestObject.PostDataList.Select(p => p.ID).ToList();
                    await _db.Instance.Updateable <TWMPurchaseMainDbModel>()
                    .SetColumns(p => p.DeleteFlag == true)
                    .Where(p => mainIds.Contains(p.ID))
                    .ExecuteCommandAsync();
                }
                else
                {
                    IDS.Add(requestObject.PostData.ID);
                    //单条删除
                    await _db.Instance.Updateable <TWMPurchaseMainDbModel>()
                    .SetColumns(p => p.DeleteFlag == true)
                    .Where(p => p.ID == requestObject.PostData.ID)
                    .ExecuteCommandAsync();
                }

                foreach (int ids in IDS)
                {
                    List <TPSMPurchaseOrderDetailDbModel> toEdit = new List <TPSMPurchaseOrderDetailDbModel>();         //可采购售单详细信息
                    var mainEntity = _db.Instance.Queryable <TWMPurchaseMainDbModel>().Where(P => P.ID == ids).First(); //可采购售单主表

                    var listItem = _db.Instance.Queryable <TPSMPurchaseOrderDetailDbModel>().
                                   Where(t => t.MainId == mainEntity.SourceId).ToList(); //可采购售单详细信息

                    var whDetailList = currDb.Queryable <TWMPurchaseDetailDbModel>().Where(p => p.MainId == ids).ToList();

                    foreach (var item in whDetailList)
                    {
                        var     me     = materList.Where(p => p.ID == item.MaterialId).FirstOrDefault();
                        decimal proNum = UnitChange.TranserUnit(me, UnitType.Warehouse, UnitType.Purchase, item.ActualNum);

                        var m = listItem.Where(p => p.ID == item.PurchaseDetailId).FirstOrDefault();
                        if (m != null)
                        {
                            m.TransferNum = m.TransferNum + proNum;
                            toEdit.Add(m);
                        }
                    }

                    if (toEdit.Count() > 0)
                    {
                        _db.Instance.Updateable(toEdit).ExecuteCommand();
                    }

                    if (!_db.Instance.Queryable <TPSMPurchaseOrderDetailDbModel>().Any(p => p.TransferNum > 0 && p.MainId == mainEntity.SourceId))
                    {
                        _db.Instance.Updateable <TPSMPurchaseOrderMainDbModel>().Where(p => p.ID == mainEntity.SourceId).SetColumns(p => p.TransferStatus == false).ExecuteCommand();
                    }
                    else
                    {
                        _db.Instance.Updateable <TPSMPurchaseOrderMainDbModel>().Where(p => p.ID == mainEntity.SourceId).SetColumns(p => p.TransferStatus == true).ExecuteCommand();
                    }
                }

                //提交事务
                currDb.CommitTran();
                //返回执行结果
                return(ResponseUtil <bool> .SuccessResult(true));
            }
            catch (Exception ex)
            {
                //回滚事务
                currDb.RollbackTran();
                //返回异常结果
                return(ResponseUtil <bool> .FailResult(false, ex.Message));
            }
        }