using JiepeiWMS.IServices; using JiepeiWMS.Model.Models; using JiepeiWMS.Services.BASE; using JiepeiWMS.IRepository.Base; using System.Threading.Tasks; using System.Linq; using JiepeiWMS.IRepository.UnitOfWork; using JiepeiWMS.Common.Enums; using System; using JiepeiWMS.IRepository; using System.Collections.Generic; using JiepeiWMS.Common.HttpContextUser; using JiepeiWMS.Common; using JiepeiWMS.Common.Helper; using JiepeiWMS.Model.ViewModels; using JiepeiWMS.Model.Result; using System.Threading; using Microsoft.Extensions.Logging; using JiepeiWMS.Common.HttpRestSharp; using JiepeiWMS.Extends; using Newtonsoft.Json; namespace JiepeiWMS.Services { public class WMPurchaseQuoteDetailServices : BaseServices, IWMPurchaseQuoteDetailServices { private readonly IBaseRepository _dal; private readonly IWMQuoteInfoLogRepository _BllWMQuoteInfoLog; private readonly IWMPurchaseInfoRepository _BllWMPurchaseInfo; private readonly IWMQuoteInfoRepository _BllWMQuoteInfo; private readonly IWMProductInfoRepository _BllWMProductInfo; private readonly IWMProductListRepository _BllWMProductList; private readonly IWMStockLogRepository _BllWMStockLog; private readonly IBaseRepository _BllSysUserInfo; private readonly IWMPurchaseInfoLogRepository _BllWMPurchaseInfoLog; private readonly IUnitOfWork _DB; private readonly IBaseRepository _BllWMSupplier; private readonly IWMInInventoryRepository _BllWMInInventory; private readonly IWMInInventoryInfoRepository _BllWMInInventoryInfo; private readonly IUser _user; private readonly ISysUserInfoServices _sysUserInfoServices; private readonly ILogger _logger; private readonly IBaseRepository _BllWMWareHouse; public WMPurchaseQuoteDetailServices( IBaseRepository dal, IWMQuoteInfoRepository BllWMQuoteInfo, IWMPurchaseInfoRepository BllWMPurchaseInfo, IWMQuoteInfoLogRepository BllWMQuoteInfoLog, IWMProductInfoRepository BllWMProductInfo, IWMProductListRepository BllWMProductList, IWMStockLogRepository BllWMStockLog, IWMPurchaseInfoLogRepository BllWMPurchaseInfoLog, IBaseRepository BllSysUserInfo, IUnitOfWork DB, IBaseRepository BllWMSupplier, IWMInInventoryRepository BllWMInInventory, IWMInInventoryInfoRepository BllWMInInventoryInfo, IUser user, ISysUserInfoServices sysUserInfoServices, ILogger logger, IBaseRepository BllWMWareHouse ) { this._dal = dal; base.BaseDal = dal; _BllWMPurchaseInfo = BllWMPurchaseInfo; _BllWMQuoteInfoLog = BllWMQuoteInfoLog; _BllWMQuoteInfo = BllWMQuoteInfo; _BllWMProductInfo = BllWMProductInfo; _BllWMProductList = BllWMProductList; _BllWMStockLog = BllWMStockLog; _BllSysUserInfo = BllSysUserInfo; _BllWMPurchaseInfoLog = BllWMPurchaseInfoLog; _DB = DB; _BllWMSupplier = BllWMSupplier; _BllWMInInventory = BllWMInInventory; _BllWMInInventoryInfo = BllWMInInventoryInfo; _user = user; _sysUserInfoServices = sysUserInfoServices; _logger = logger; _BllWMWareHouse = BllWMWareHouse; } private string purchaseinUrl = "/uapws/rest/ic/manage/purchasein/add"; /// /// 入库 /// /// 详细信息列表 /// 当前用户 /// 错误信息 public async Task Enter(WMPurchaseQuoteDetail[] Details, int UserId) { var ids = Details.Select(t => t.Id).Distinct(); if (ids.Contains(0)) { return "入库信息中存在编号不能为0"; } var details = await Query(t => ids.Contains(t.Id)); if (details.Count == 0) { return "找不到入库信息"; } //检测入库信息状态必须为采购中80或入库中90(EnumWMPurchaseDetailStatus) var statusPurchasing = EnumWMPurchaseDetailStatus.Purchasing.GetHashCode(); var statusStorageing = EnumWMPurchaseDetailStatus.Storageing.GetHashCode(); var detail = details.FirstOrDefault(t => t.Status == statusPurchasing || t.Status == statusStorageing); if (detail == null) { return "入库信息中该采购编号的状态必需为采购中或入库中"; } //读取报价单列表 var quotedetaillist = details.GroupBy(t => t.QuoteId ?? 0); var quoteids = quotedetaillist.Select(t => t.Key); var quotes = await _BllWMQuoteInfo.Query(t => quoteids.Contains(t.Id)); //检测是否存在没有报价单的详细信息 var quoteid = quoteids.FirstOrDefault(t => !quotes.Exists(x => x.Id == t)); if (quoteid > 0) { return "入库信息中找不到对应的报价单,具体入库信息编号为(" + string.Join(",", details.Where(t => t.QuoteId == quoteid).Select(t => t.Id.ToString())) + ")"; } //检测入库信息状态必须为采购中80或入库中90(EnumWMPurchaseDetailStatus) var quote = quotes.FirstOrDefault(t => t.Status == statusPurchasing || t.Status == statusStorageing); if (quote == null) { return "入库信息中该报价编号的状态必需为采购中或入库中"; } //检测产品信息是否存在 var productids = details.Select(t => t.ProductId); var productinfos = await _BllWMProductInfo.Query(t => productids.Contains(t.ProductListId)); var productid = productids.FirstOrDefault(t => !productinfos.Exists(x => x.ProductListId == t)); if (productid > 0) { return "入库信息中找不到对应的产品信息,具体产品编号为(" + productid + ")"; } var productlists = await _BllWMProductList.Query(t => productids.Contains(t.Id)); productid = productids.FirstOrDefault(t => !productlists.Exists(x => x.Id == t)); if (productid > 0) { return "入库信息中找不到对应的产品信息,具体产品编号为(" + productid + ")"; } var inTime = Details[0].InTime; if (inTime == null) { return "请选择入库时间"; } var outInType = Details[0].OutInType; if (outInType <= 0) { return "请选择入库类型"; } if (Details.Where(x => x.LocationId <= 0 || x.LocationId == null).ToList().Count() > 0) { return "请选择所在库位"; } //获取采购信息 var purchaseids = details.Select(t => t.PurchaseId); var purchaseinfos = await _BllWMPurchaseInfo.Query(t => purchaseids.Contains(t.Id)); _DB.BeginTran(); try { var result = 0; var stocklogs = new List(); var inInventoryInfoList = new List(); var PurchaseQuoteDetailList = new List(); var code = await _BllWMInInventory.GetInInventoryMaxId(); //生成入库单 WMInInventory inInventory = new WMInInventory { Id = 0, InInventoryCode = "INI000" + (code + 1), OutInType = Details[0].OutInType, EmployeeId = Details[0].EmployeeId, WareHouseId = Details[0].WareHouseId.Value, DepartmentId = Details[0].DepartmentId, SupplierId = Details[0].SupplierId, InTime = Details[0].InTime.Value, Remark = Details[0].InRemark, AdminId = UserId, CreateTime = DateTime.Now, SysOrgId = _user.SysOrgId }; result = await _BllWMInInventory.Add(inInventory); if (result <= 0) { _DB.RollbackTran(); return "生成入库单失败"; } //更新入库价格 foreach (var item in Details) { var srcitem = details.Where(p => p.Id == item.Id).FirstOrDefault(); if (item.inputNum == 0) { continue; }//入库数为0时跳过 //读取库存信息 var productinfo = productinfos.FirstOrDefault(t => t.ProductListId == srcitem.ProductId && t.WareHouseId == item.WareHouseId.Value); if (productinfo == null) { _DB.RollbackTran(); return "未获取到商品库存"; } //设置状态 var StorageNum = item.StorageNum ?? 0; if (item.CheckNum > (StorageNum + item.inputNum)) { srcitem.Status = EnumWMPurchaseDetailStatus.Purchasing.GetHashCode(); } else { srcitem.Status = EnumWMPurchaseDetailStatus.Finish.GetHashCode(); } item.WareHouseId = productinfo.WareHouseId; //原库存单价 var srcprice = productinfo.PurchasePrice; //原库存数 var srcquantity = productinfo.Quantity ?? 0; //原总价=原库存单价*原库存数 var srctotalprice = srcprice * srcquantity; //新报价单入库总数=当前入库数+原报价单入库总数 srcitem.StorageNum = (srcitem.StorageNum ?? 0) + item.inputNum; //新库存数=原库存数+当前入库数; productinfo.Quantity = srcquantity + item.inputNum; //新总价=原库存单价*原库存数+当前单价*当前入库数 var totalprice = srcprice * srcquantity + (srcitem.Price ?? 0) * item.inputNum; //新库存单价=新总价/(原库存数+当前入库数) productinfo.PurchasePrice = totalprice / (srcquantity + item.inputNum); //读取产品信息 var productlist = productlists.FirstOrDefault(t => t.Id == srcitem.ProductId); productlist.Price = productinfo.PurchasePrice;//平均值 productlist.PurchasePrice = srcitem.Price ?? 0;//采购价 //采购信息 var purchaseinfo = purchaseinfos.FirstOrDefault(t => t.Id == srcitem.PurchaseId); //增加库存流水日志 WMStockLog wmstocklog = new WMStockLog(); wmstocklog.Id = 0; wmstocklog.ProductId = srcitem.ProductId; wmstocklog.Type = EnumWMStockType.QuoteStock.GetHashCode(); wmstocklog.Operation = 1; wmstocklog.Quantity = item.inputNum; wmstocklog.Price = srcitem.Price; wmstocklog.TotalPrice = srctotalprice; wmstocklog.RemainQuantity = productinfo.Quantity; wmstocklog.RemainPrice = productinfo.PurchasePrice; wmstocklog.TotalRemainPrice = totalprice; wmstocklog.AdminId = UserId; wmstocklog.CreateTime = DateTime.Now; wmstocklog.ProductListId = productinfo.ProductListId; wmstocklog.ProductSpecId = productinfo.ProductSpecId; if (purchaseinfo != null) { wmstocklog.WareHouseId = purchaseinfo.WareHouseId; } wmstocklog.Remark = "【商品入库】新增库存:" + item.inputNum + " -> 入库商品单价:" + srcitem.Price; wmstocklog.OrderId = srcitem.QuoteId; wmstocklog.DepId = srcitem.DepartmentId; stocklogs.Add(wmstocklog); //生成入库单信息 WMInInventoryInfo inInventoryInfo = new WMInInventoryInfo(); inInventoryInfo.InInventoryId = result; inInventoryInfo.ProductId = srcitem.ProductId; inInventoryInfo.WareHouseId = purchaseinfo.WareHouseId; inInventoryInfo.PurchaseUnit = srcitem.PurchaseUnit; inInventoryInfo.Price = srcitem.Price.Value; inInventoryInfo.Quantity = srcitem.Quantity; inInventoryInfo.CheckNum = srcitem.CheckNum.Value; inInventoryInfo.PurchaseNum = srcitem.PurchaseNum; inInventoryInfo.StorageNum = item.inputNum;//入库数 inInventoryInfo.Remark = srcitem.Remark; inInventoryInfo.LocationId = item.LocationId.Value; inInventoryInfo.InTime = item.InTime.Value; inInventoryInfo.CreateTime = DateTime.Now; inInventoryInfoList.Add(inInventoryInfo); PurchaseQuoteDetailList.Add(item); } var quoteinfoModel = quotes.FirstOrDefault(); var PurchaseinResult = new Tuple("", true); //根据配置是否调用NC接口 var NCInterfaceSecret = Appsettings.app("AppSettings", "NCInterfaceSecret").ToString(); if (NCInterfaceSecret == "True") //调NC采购入库接口 PurchaseinResult = await BeginPurchaseinInNC(quoteinfoModel, PurchaseQuoteDetailList); if (!PurchaseinResult.Item2 && !string.IsNullOrWhiteSpace(PurchaseinResult.Item1)) { //如果接口失败删除入库单 await _BllWMInInventory.DeleteById(result); _DB.RollbackTran(); return PurchaseinResult.Item1; } var ok = await _dal.Update(details); if (!ok) { _DB.RollbackTran(); return "更新详细信息失败"; } ok = await _BllWMProductInfo.Update(productinfos); if (!ok) { _DB.RollbackTran(); return "更新产品库存失败"; } ok = await _BllWMProductList.Update(productlists); if (!ok) { _DB.RollbackTran(); return "更新产品信息失败"; } var count = await _BllWMStockLog.Add(stocklogs); if (count <= 0) { _DB.RollbackTran(); return "添加库存日志失败"; } var count1 = await _BllWMInInventoryInfo.Add(inInventoryInfoList); if (count1 <= 0) { _DB.RollbackTran(); return "添加入库单信息失败"; } //采购单入库日志 var quotelogs = new List(); foreach (var quoteinfo in quotes) { var detailModel = details.Where(p => p.QuoteId == quoteinfo.Id).FirstOrDefault(); var detailsList = await _dal.Query(p => p.PurchaseId == detailModel.PurchaseId); //全部入库状态自动出库完成 if (detailsList.Select(x => x.CheckNum).Sum() > (detailsList.Select(x => x.StorageNum).Sum() + detailsList.Select(x => x.inputNum).Sum())) { quoteinfo.Status = EnumWMPurchaseDetailStatus.Storageing.GetHashCode(); } else { quoteinfo.Status = EnumWMPurchaseDetailStatus.Finish.GetHashCode(); } var quoteinfolog = new WMQuoteInfoLog(); quoteinfolog.OrderId = quoteinfo.Id; quoteinfolog.AdminId = UserId; quoteinfolog.Content = "【报价入库】设置状态为" + ((EnumWMPurchaseDetailStatus)quoteinfo.Status)._GetDescriptionByEnumValue(); quoteinfolog.CreateTime = DateTime.Now; quotelogs.Add(quoteinfolog); } await _BllWMQuoteInfo.Update(quotes); if (!ok) { _DB.RollbackTran(); return "更新报价信息失败"; } count = await _BllWMQuoteInfoLog.Add(quotelogs); if (count <= 0) { _DB.RollbackTran(); return "添加报价单日志失败"; } _DB.CommitTran(); } catch (Exception ex) { _DB.RollbackTran(); return ex.ToString(); } return string.Empty; } /// /// 设置审核不通过 /// /// 设置为审核不通过 /// 操作人 /// 错误信息,空则正常 public async Task SetNoPass(int[] Ids, int UserId) { var models = await Query(t => Ids.Contains(t.Id)); if (models.Count <= 0) { return "信息不存在"; } var statusCheckedNoPass = EnumWMPurchaseDetailStatus.CheckedNoPass.GetHashCode(); foreach (var mod in models) { mod.Status = statusCheckedNoPass; } var ok = await Update(models); if (!ok) { return "操作失败"; } return string.Empty; } /// /// 调用友采购入库接口 /// /// public async Task> BeginPurchaseinInNC(WMQuoteInfo infoModel, List detailList) { try { #region NCPurchaseinViewModels pos = new NCPurchaseinViewModels(); NCPurchaseinViewModels.Ufinterface uface = new NCPurchaseinViewModels.Ufinterface(); NCPurchaseinViewModels.Bill bill = new NCPurchaseinViewModels.Bill(); NCPurchaseinViewModels.Billhead head = new NCPurchaseinViewModels.Billhead(); NCPurchaseinViewModels.Cgeneralbid cgeneralbid = new NCPurchaseinViewModels.Cgeneralbid(); List item = new List(); var UnitCode = ""; var SupplierUnifiedCode = ""; var SupplierTaxRate = ""; decimal TaxRate = 1.3m; var WareHouseName = "01"; var SupplierModel = new WMSupplier(); var ProductListModel = new WMProductList(); if (infoModel != null && infoModel.SupplierId > 0) { SupplierModel = await _BllWMSupplier.QueryById(infoModel.SupplierId); if (SupplierModel != null && !string.IsNullOrWhiteSpace(SupplierModel.UnifiedCode)) { SupplierUnifiedCode = SupplierModel.UnifiedCode; SupplierTaxRate = SupplierModel.TaxRate; } } //var detailModel = detailList.FirstOrDefault(); //if (detailModel != null && detailModel.WareHouseId > 0) //{ // WareHouseName = (await _BllWMWareHouse.QueryById(detailModel.WareHouseId)).Name; //} //赋uface uface.account = "JPKJ"; uface.billtype = "45";//采购入库 uface.groupcode = "JPKJ"; uface.isexchange = "Y"; uface.replace = "Y"; uface.sender = "JPKJ001"; //赋head head.pk_group = "JPKJ"; head.freplenishflag = "N"; head.cpayfinorgoid = "1001"; head.cpayfinorgvid = "1001"; head.cfanaceorgoid = "1001"; head.cfanaceorgvid = "1001"; head.cvendorid = SupplierUnifiedCode; head.ctrantypeid = "45-01"; head.csendcountryid = "CN"; head.crececountryid = "CN"; head.ctaxcountryid = "CN"; head.fbuysellflag = "2"; head.btriatradeflag = "N"; head.cwarehouseid = WareHouseName; head.BITINBILL = "N"; head.vtrantypecode = "45-01"; head.fbillflag = "2";//公司最新版本 head.corpvid = "1001";//公司 head.corpoid = "1001"; head.pk_org = "1001"; head.pk_org_v = "1001"; //赋item foreach (var detailItem in detailList) { if (detailItem.ProductId > 0) { ProductListModel = await _BllWMProductList.QueryById(detailItem.ProductId); if (ProductListModel != null) { var qt = await QueryTable("select UnitCode from WMProductUnit where id=" + ProductListModel.Unit); UnitCode = qt.Rows._Select(t => t["UnitCode"]._ToDbStr()).FirstOrDefault(); } } if (!string.IsNullOrWhiteSpace(SupplierTaxRate)) { var Number = StringHelper.GetNumberInt(SupplierTaxRate); if (Number > 0) TaxRate = Number / 100; } //本币算法 decimal bbdanjia = detailItem.Price ?? 0;//本币含税单价 decimal bbjine = detailItem.Amount ?? 0;//本币含税金额 decimal bbwsdanjia = Math.Round(bbdanjia - (bbdanjia * TaxRate), 4);//本币无税单价=本币含税单价*税率(一般13%) decimal bbwsjine = bbwsdanjia * detailItem.inputNum;//本币无税金额=本币无税单价*实收数量 decimal bbshuie = bbjine - bbwsjine;//本币税额=本币含税金额-本币无税金额 var ItemModel = new NCPurchaseinViewModels.Item(); ItemModel.pk_group = "JPKJ"; ItemModel.corpoid = "1001"; ItemModel.corpvid = "1001"; ItemModel.cmaterialoid = ProductListModel.Code; ItemModel.cmaterialvid = ProductListModel.Code; ItemModel.cunitid = UnitCode; ItemModel.castunitid = UnitCode; ItemModel.vchangerate = "1/1"; ItemModel.nshouldnum = detailItem.inputNum.ObjToString(); ItemModel.nshouldassistnum = detailItem.inputNum.ObjToString(); ItemModel.nnum = detailItem.inputNum.ObjToString(); ItemModel.nassistnum = detailItem.Quantity.ObjToString(); ItemModel.pk_org = "1001"; ItemModel.pk_org_v = "1001"; ItemModel.flargess = "N"; ItemModel.bsourcelargess = "N"; ItemModel.cvendorid = SupplierUnifiedCode; ItemModel.bbarcodeclose = "N"; ItemModel.bonroadflag = "N"; ItemModel.cbodytranstypecode = "45-01"; ItemModel.pk_org = "1001"; ItemModel.pk_org_v = "1001"; ItemModel.cbodywarehouseid = WareHouseName;//库存仓库 ItemModel.pk_creqwareid = WareHouseName;//需求仓库 ItemModel.creqstoorgoid = "1001"; ItemModel.creqstoorgvid = "1001"; ItemModel.borrowinflag = "N"; ItemModel.corigcurrencyid = "CNY"; ItemModel.nchangestdrate = "1.00";//折本汇率 ItemModel.ccurrencyid = "CNY"; ItemModel.cqtunitid = UnitCode; ItemModel.vqtunitrate = "1.00/1.00"; ItemModel.nitemdiscountrate = (detailItem.Discount ?? 0).ObjToString(); ItemModel.nmny = bbwsjine.ToString();//本币无税金额 ItemModel.ntaxmny = bbjine.ToString();//本币价税合计 ItemModel.ntax = bbshuie.ToString();//本币税额 ItemModel.ntaxrate = TaxRate.ToString();//税率 ItemModel.ftaxtypeflag = "1";//扣税类别 ItemModel.bassetcard = "N"; ItemModel.bfixedasset = "N"; ItemModel.ctaxcodeid = "CN01"; ItemModel.nnosubtaxrate = (double)TaxRate * 10;//不可抵扣税率 ItemModel.bopptaxflag = "N"; item.Add(ItemModel); } //所有集合赋值 cgeneralbid.item = item; head.cgeneralbid = cgeneralbid; bill.billhead = head; uface.bill = bill; pos.ufinterface = uface; var json = JsonConvert.SerializeObject(pos); //采购入库接口 var apioahost = Appsettings.app("AppSettings", "ApiNCHost"); NCJsonResult jsonResult = HttpHelper.PostApi(apioahost + purchaseinUrl, pos); Thread.Sleep(300); #endregion var resultdescription = jsonResult.data.ufinterface.sendresult[0].resultdescription; if (jsonResult.data != null && jsonResult.data.ufinterface.successful == "Y") { return new Tuple("用友采购入库接口成功", true); } else { string[] strArray = resultdescription.Split("异常信息:"); return new Tuple("用友采购入库接口失败:" + strArray[1], false); } } catch (Exception ex) { _logger.LogError(ex, ex.ToString()); return new Tuple(ex.ToString(), false); } } } }