using BPA.Franchisee.Application.FranchiseeCenter.GoodsServices; using BPA.SAAS.Manage.Application.DataBase.Dtos.Batching; using BPA.SAAS.Manage.Application.DataBase.Dtos.Bom; using BPA.SAAS.Manage.Application.DataBase.Dtos.Goods; using BPA.SAAS.Manage.Application.DataBase.Dtos.GoodsAttribute; using BPA.SAAS.Manage.Application.DataBase.Interface; using BPA.SAAS.Manage.Application.System.Dtos; using BPA.SAAS.Manage.Application.System.Interface; using BPA.SAAS.Manage.Application.System.Services; using BPA.SAAS.Manage.Comm.Const; using BPA.SAAS.Manage.Comm.Enum; using BPA.SAAS.Manage.Comm.Util; using BPA.SAAS.Manage.Core.Base; using BPA.SAAS.Manage.Core.DataBase; using BPA.SAAS.Manage.Core.Device; using BPA.SAAS.Manage.Core.Product; using Furion.ClayObject.Extensions; using Newtonsoft.Json; using Npoi.Mapper; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.SS.Util; using NPOI.XSSF.UserModel; using Org.BouncyCastle.Asn1.Cms; using System; using System.Collections; using System.ComponentModel.DataAnnotations.Schema; using System.Data; using System.Drawing; using System.Drawing.Imaging; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace BPA.SAAS.Manage.Application.DataBase.Services { public class GoodsService: IGoodsService, ITransient { private readonly ISqlSugarClient _db; IGoodsAttributeService _goodsAttributeService; ISystemConfigService _SystemConfigService; public GoodsService(ISqlSugarClient db, IGoodsAttributeService goodsAttributeService, ISystemConfigService SystemConfigService) { _db=db; _goodsAttributeService=goodsAttributeService; _SystemConfigService = SystemConfigService; } /// /// 分页查询 /// /// /// public async Task GetGoodsPage(GoodsQueryDto dto) { List conModels = new List(); #region 条件查询 if (!string.IsNullOrEmpty(dto.Name)) { conModels.Add(new ConditionalModel() { FieldName = "a.Name", ConditionalType = ConditionalType.Like, FieldValue = dto.Name }); } if (!string.IsNullOrEmpty(dto.GoodsTypeName)) { conModels.Add(new ConditionalModel() { FieldName = "a.GoodsTypeId", ConditionalType = ConditionalType.Equal, FieldValue = dto.GoodsTypeName }); } if (!string.IsNullOrEmpty(dto.Status)) { conModels.Add(new ConditionalModel() { FieldName = "a.Status", ConditionalType = ConditionalType.Like, FieldValue = dto.Status }); } if (!string.IsNullOrEmpty(dto.Descritption)) { conModels.Add(new ConditionalModel() { FieldName = "a.Descritption", ConditionalType = ConditionalType.Like, FieldValue = dto.Descritption }); } #endregion RefAsync total = 0; var res =await _db.Queryable((a, b) => new JoinQueryInfos( JoinType.Left, a.GoodsTypeId == b.Id )) .WhereIF(!string.IsNullOrWhiteSpace(dto.Code), (a, b) => a.Code.Contains(dto.Code)) // .WhereIF(dto.CreateAt.HasValue, (a, b) => SqlFunc.DateIsSame(a.CreateAt, Convert.ToDateTime(dto.CreateAt), DateType.Day)) .Where(conModels) .OrderBy(a => a.CreateAt, OrderByType.Desc) .Select((a, b) => new { Id = a.Id, Code = a.Code, Name = a.Name, Price = a.Price, ImgUrl = a.ImgUrl, Status = a.Status, GoodsTypeId = b.IsDeleted == 0 ? a.GoodsTypeId : "", GoodsTypeName = b.IsDeleted == 0 ? b.Name : "", Descritption = a.Descritption, IsDeleted = a.IsDeleted, a.GroupId, // CreateAt = a.CreateAt, GoodsUintId = a.GoodsUintId, ForeignKeyRe = a.ForeignKeyRe, Design = a.Design, IsWeigh = a.IsWeigh, DefaultMate = a.DefaultMate, IsAttrubute = a.IsAttrubute, Goodstechnology = SqlFunc.Subqueryable().Where(p => p.GoodsId == a.Id).WhereIF(!string.IsNullOrWhiteSpace(dto.DeviceId),p=>p.DeviceId== dto.DeviceId).ToList(), }) .ToPageListAsync(dto.Current, dto.PageSize, total); PageUtil util = new PageUtil() { Total = total, Data = res }; return util; } /// /// 查询所有商品 /// /// public async Task> GetGoodsList() { var res = await _db.Queryable().ToListAsync(); return res; } /// /// 添加商品 /// /// /// public async Task AddGoods(GoodsDto dto) { if (string.IsNullOrWhiteSpace(dto.Id)) { var resEntity = new BPA_GoodsInfo(); resEntity.Id = Guid.NewGuid().ToString(); resEntity.GoodsTypeId = dto.GoodsTypeId; resEntity.Name = dto.Name; resEntity.Descritption = dto.Descritption; resEntity.ImgUrl = dto.ImgUrl; resEntity.Price = dto.Price; resEntity.IsWeigh = dto.IsWeigh; resEntity.GoodsUintId = dto.GoodsUintId; resEntity.IsAttrubute = dto.IsAttrubute; resEntity.Code = GetNumber2(8); var data = _db.Queryable().Max(x => x.AutoKey); //if (data == 0) data = 1000; //else data = data + 1; // resEntity.AutoKey = data; var res = await _db.Insertable(resEntity).CallEntityMethod(m => m.Create()).ExecuteCommandAsync(); return res > 0; } else { return await UpdateGoods(dto); } } /// /// 更新商品 /// /// /// public async Task UpdateGoods(GoodsDto dto) { // 查询数据库中是否存在未删除的商品类型 var resEntity = _db.Queryable().Where(it => it.IsDeleted == 0).First(it => it.Id == dto.Id); if (null == resEntity) { throw Oops.Oh("商品不存在"); } resEntity.GoodsTypeId = dto.GoodsTypeId; resEntity.Name = dto.Name; resEntity.Descritption = dto.Descritption; resEntity.ImgUrl = dto.ImgUrl; resEntity.Price = dto.Price; resEntity.IsWeigh = dto.IsWeigh; resEntity.GoodsUintId = dto.GoodsUintId; resEntity.IsAttrubute = Convert.ToBoolean(dto.IsAttrubute); if (!string.IsNullOrWhiteSpace(dto.Status)) { resEntity.Status = (CommonStatus)Enum.ToObject(typeof(CommonStatus), int.Parse(dto.Status)); } var res = await _db.Updateable(resEntity).ExecuteCommandAsync(); return res > 0; } /// /// 删除商品 /// /// /// public async Task DeleteGoods(string id) { try { _db.Ado.BeginTran(); var goods = _db.Queryable().Where(x => x.Id == id).First(); if (goods == null) throw Oops.Oh("商品不存在"); var goodsbom = _db.Queryable().Where(x => x.Goods_Id == id).ToList(); var goodsTechnology = _db.Queryable().Where(x => x.GoodsId == id).ToList(); //var FoodMenuGoods = _db.Queryable().Where(x => x.GoodsId == id).ToList(); await _db.Deleteable(goodsbom).ExecuteCommandAsync(); await _db.Deleteable(goodsTechnology).ExecuteCommandAsync(); //await _db.Deleteable(FoodMenuGoods).ExecuteCommandAsync(); var res = await _db.Deleteable(goods).ExecuteCommandAsync(); _db.Ado.CommitTran(); return res > 0; } catch (Exception) { _db.Ado.RollbackTran(); throw Oops.Oh("删除失败"); } } /// /// 查询商品单位 /// /// public async Task> GetGoodsUintList() { var res = await _db.Queryable().Select(x => new { id = x.Id, name = x.Name }).ToListAsync(); return res; } public async Task> GetGoodsUintList_alm() { var groupId = App.HttpContext.Request.Headers["groupId"].ToString(); if (string.IsNullOrWhiteSpace(groupId)) throw Oops.Oh("加盟商id不能为空"); var res = await _db.Queryable().Where(x=>x.GroupId== groupId).Select(x => new { id = x.Id, name = x.Name }).ToListAsync(); return res; } /// /// 添加商品单位 /// /// /// public async Task AddGoodsUint(GoodsUintDto dto) { var productCode = _db.Queryable().Where(x =>x.Name == dto.Name).ToList(); if (productCode.Count() > 0) { throw Oops.Oh("商品单位已存在"); } try { BPA_GoodsUint bPA_Product = new BPA_GoodsUint(); bPA_Product.Name = dto.Name; var res = await _db.Insertable(bPA_Product).CallEntityMethod(m => m.Create()).ExecuteCommandAsync(); return res > 0; } catch (Exception ex) { throw Oops.Oh("添加失败"); } } /// /// 商品配方 /// /// /// public async Task GetGoodsBomPageAsync(GoodsBomQueryDto dto) { RefAsync total = 0; var res =await _db.Queryable((a, b) => new JoinQueryInfos( JoinType.Left, a.Id == b.BoomId )) .WhereIF(!string.IsNullOrWhiteSpace(dto.GoodsId), (a, b) => b.GoodsId==dto.GoodsId) .WhereIF(!string.IsNullOrWhiteSpace(dto.Name), (a, b) => a.Name.Contains(dto.Name)) .WhereIF(!string.IsNullOrWhiteSpace(dto.GoodsAttributeValue), (a, b) => b.GoodsAttributeValue.Contains(dto.GoodsAttributeValue)) .Select((a, b) => new GoodsBomPageView { Id = b.Id, Name = a.Name, BomId= b.BoomId, IsMain = a.IsMain, GoodsAttributeValueId=b.GoodsAttributeValueId, GoodsAttributeValue=b.GoodsAttributeValue, }) .ToPageListAsync(dto.Current, dto.PageSize, total); PageUtil util = new PageUtil() { Total = total, Data = res }; return util; } /// /// 删除商品配方 /// /// /// public async Task BatchDelGoodsBomAsync(string Ids) { // var GoodsBom=_db.Queryable().Where(x => x.Id == Ids).First(); var model=_db.Queryable().Where(x => x.Id == Ids).First(); if(model==null) throw Oops.Oh("配方不存在"); _db.Deleteable().Where(x => x.Goods_Id == model.GoodsId && x.BomId== model.BoomId).ExecuteCommand(); // 查询数据库中是否存在未删除的商品 var res = _db.Deleteable().In(Ids).ExecuteCommand(); return res > 0; } /// /// 添加商品配方 /// /// /// public async Task AddGoodsBomAttribute(GoodsBomAttributeDto dto) { _db.Ado.BeginTran(); try { if(dto.Type== "add") { var sortMax = _db.Queryable().Max(x => x.Sort); BPA_Bom newbPA_BOM = new BPA_Bom { Name = dto.BomName, Code = GetNumber2(), IsMain = dto.BomType == "1" ? true : false, Sort = sortMax + 1, Id = Guid.NewGuid().ToString(), CreateAt = DateTime.Now, Status = CommonStatus.ENABLE, }; //添加配方 var res = _db.Insertable(newbPA_BOM).CallEntityMethod(m => m.Create()).ExecuteCommand(); //添加配方分类 var list = dto.BomtypeList.Select(item => new BPA_BomTypeInfo() { BomId = newbPA_BOM.Id, BomTypeId = item }).ToList(); _db.Insertable(list).CallEntityMethod(m => m.Create()).ExecuteCommand(); BPA_GoodsBom bom = new BPA_GoodsBom(); bom.Goods_Id = dto.GoodsId; bom.BomId = newbPA_BOM.Id; bom.Status = CommonStatus.ENABLE; //添加商品配方关系 _db.Insertable(bom).CallEntityMethod(m => m.Create()).ExecuteCommand(); List BOMEntryList = new(); if (dto.Mate.Count > 0) { for (int i = 0; i < dto.Mate.Count; i++) { BPA_BomEntry newbPA_BOMEnty = new BPA_BomEntry { BatchingId = dto.Mate[i].batchingId, //BatchingKey = dto.Mate[i].AutoKey, BomQty = dto.Mate[i].dosage, BomId = newbPA_BOM.Id, Status = CommonStatus.ENABLE, IsReplace = false, }; BOMEntryList.Add(newbPA_BOMEnty); } } //添加配方物料关系 _db.Insertable(BOMEntryList).CallEntityMethod(m => m.Create()).ExecuteCommand(); BPA_BomAttributeValueRe bPA_BomAttributeValueRe = new(); bPA_BomAttributeValueRe.Id = Guid.NewGuid().ToString(); bPA_BomAttributeValueRe.GoodsId = dto.GoodsId; bPA_BomAttributeValueRe.BoomId = newbPA_BOM.Id; bPA_BomAttributeValueRe.GoodsAttributeValueId = string.Join(",", dto.Shuxing); bPA_BomAttributeValueRe.GoodsAttributeValue = dto.GoodsAttributeValue; //添加商品配方属性关系 _db.Insertable(bPA_BomAttributeValueRe).ExecuteCommand(); } else { if (string.IsNullOrWhiteSpace(dto.BomId)) throw Oops.Oh("请选择配方"); if (!string.IsNullOrWhiteSpace(dto.BomId)) { var check=_db.Queryable().Where(x => x.Goods_Id == dto.GoodsId && x.BomId == dto.BomId).Any(); if (!check) { BPA_GoodsBom bom = new BPA_GoodsBom(); bom.Goods_Id = dto.GoodsId; bom.BomId = dto.BomId; bom.Status = CommonStatus.ENABLE; //添加商品配方关系 _db.Insertable(bom).CallEntityMethod(m => m.Create()).ExecuteCommand(); } string vid = string.Join(",", dto.Shuxing); var checkvid = _db.Queryable().Where(x => x.GoodsId == dto.GoodsId && x.BoomId == dto.BomId && x.GoodsAttributeValueId== vid).Any(); if(checkvid) throw Oops.Oh("该配方已经存在"); //添加商品配方属性关系 BPA_BomAttributeValueRe bPA_BomAttributeValueRe = new(); bPA_BomAttributeValueRe.Id = Guid.NewGuid().ToString(); bPA_BomAttributeValueRe.GoodsId = dto.GoodsId; bPA_BomAttributeValueRe.BoomId = dto.BomId; bPA_BomAttributeValueRe.GoodsAttributeValueId = vid; bPA_BomAttributeValueRe.GoodsAttributeValue = dto.GoodsAttributeValue; _db.Insertable(bPA_BomAttributeValueRe).ExecuteCommand(); } } _db.Ado.CommitTran(); return true; } catch (Exception e) { _db.Ado.RollbackTran(); throw Oops.Oh("添加失败,失败信息:" + e.Message); } } public async Task AddGoodsBom(GoodsBomDto dto) { var res = false; List list = new(); if (dto.BomId.Count() > 0) { for (int i = 0; i < dto.BomId.Count; i++) { BPA_GoodsBom goodsBom = new(); goodsBom.BomId = dto.BomId[i]; goodsBom.Goods_Id= dto.GoodsId; goodsBom.Status = CommonStatus.ENABLE; list.Add(goodsBom); } } if (list.Count>0) { res=await _db.Insertable(list).CallEntityMethod(m => m.Create()).ExecuteCommandAsync()>0; } return res; } /// /// 根据id查询商品信息 /// /// /// public async Task GetGoods(string id) { var res = await _db.Queryable() .Where((a) => a.IsDeleted == 0 && a.Id == id) .OrderBy(a => a.CreateAt, OrderByType.Desc) .Select((a) => new GoodsInfoBaseView { Id = a.Id, Code = a.Code, Name = a.Name, Price = a.Price, ImgUrl = a.ImgUrl, Status = a.Status, GoodsTypeId = a.GoodsTypeId, GoodsTypeName = SqlFunc.Subqueryable().Where(s => s.Id == a.GoodsTypeId && s.IsDeleted == 0).Select(s => s.Name), Remark = a.Descritption, // CreateAt = a.CreateAt, GoodsUintId = a.GoodsUintId, IsAttrubute = a.IsAttrubute, GoodsUintName = SqlFunc.Subqueryable().Where(s => s.Id == a.GoodsUintId && s.IsDeleted == 0).Select(s => s.Name), //GoodsAttributeList = new List() }).FirstAsync(); if (res!=null&&!res.IsAttrubute) { res.GoodsAttributeList = await _goodsAttributeService.GetByNameAttribute("默认属性"); } else { res.GoodsAttributeList = await _goodsAttributeService.GetByGoodsIdAttribute(res.Id); } return res; } /// /// 更具id查询商品信息 /// /// /// public async Task> GetGoodsListByIds(List ids) { var res = await _db.Queryable() .Where((a) => a.IsDeleted == 0 && ids.Contains(a.Id)) .OrderBy(a => a.CreateAt, OrderByType.Desc) .Select((a) => new GoodsInfoBaseView { Id = a.Id, Code = a.Code, Name = a.Name, Price = a.Price, ImgUrl = a.ImgUrl, Status = a.Status, GoodsTypeId = a.GoodsTypeId, GoodsTypeName = SqlFunc.Subqueryable().Where(s => s.Id == a.GoodsTypeId && s.IsDeleted == 0).Select(s => s.Name), Remark = a.Descritption, // CreateAt = a.CreateAt, GoodsUintId = a.GoodsUintId, IsAttrubute = a.IsAttrubute, GoodsUintName = SqlFunc.Subqueryable().Where(s => s.Id == a.GoodsUintId && s.IsDeleted == 0).Select(s => s.Name), //GoodsAttributeList = new List() }).ToListAsync(); foreach (var item in res) { if (!item.IsAttrubute) { item.GoodsAttributeList = await _goodsAttributeService.GetByNameAttribute("默认属性"); } else { item.GoodsAttributeList = await _goodsAttributeService.GetByGoodsIdAttribute(item.Id); } } return res; } public async Task ExportGood(IFormFile file) { bool isReplace = true; try { //var groupId = string.IsNullOrWhiteSpace(CurrentUser.TenantId) //? App.User?.FindFirst(ClaimConst.GroupId)?.Value // : CurrentUser.TenantId; var userId = App.User?.FindFirst(ClaimConst.CLAINM_USERID)?.Value; if (string.IsNullOrEmpty(userId)) { userId = ""; } var source = file.OpenReadStream(); var mapper = new Mapper(source); _db.Ado.BeginTran(); //添加 商品_物料信息 #region 添加 商品_物料信息 //1.查询并且添加类型 var nonLiquid = await _db.Queryable() .Where(x => x.Name == "非液体" ).FirstAsync(); if (nonLiquid == null) { nonLiquid = new BPA_BatchingType() { IsDeleted = 0, Name = "非液体", }; await _db.Insertable(nonLiquid).CallEntityMethod(m => m.Create()).ExecuteCommandAsync(); } var liquid = await _db.Queryable() .Where(x => x.Name == "液体料").FirstAsync(); if (liquid == null) { liquid = new BPA_BatchingType { IsDeleted = 0, Name = "液体料", }; await _db.Insertable(liquid).CallEntityMethod(m => m.Create()).ExecuteCommandAsync(); } //单位 var unit = await _db.Queryable().Where(x => x.Name == "默认单位").FirstAsync(); if (unit == null) { unit = new BPA_BatchingUint { IsDeleted = 0, Name = "默认单位", }; await _db.Insertable(unit).CallEntityMethod(m => m.Create()).ExecuteCommandAsync(); } //3.物料 ReadExcel readGoodBaseModelExcel = new(); var GoodBaseModellist = readGoodBaseModelExcel.ExcelToList(source, mapper, "商品_物料信息"); List batchingList = GoodBaseModellist.Select(t => new BPA_Batching() { Aittribute = 0, Batching_Name = t.BatchingName, Code = GetNumber2(), IsDeleted = 0, netrecovery = 0, outstockUint = unit.Id, Price = 0, proportion = 0, Specs = "默认规格", Status = 0, StockUint = unit.Id, TypeID = t.BatchingType == "液体料" ? liquid.Id : nonLiquid.Id, }).ToList(); var batchingNameList = batchingList.Select(x => x.Batching_Name).ToList(); var batchingListrDb = _db.Queryable().Where(x => batchingNameList.Contains(x.Batching_Name)) .ToList(); //替换 if (isReplace) { foreach (var item2 in batchingList) { var thisitem = batchingListrDb.FirstOrDefault(x => x.Batching_Name == item2.Batching_Name); if (thisitem != null) { item2.Id = thisitem.Id; item2.GroupId = thisitem.GroupId; item2.CreateBy = string.IsNullOrEmpty(item2.CreateBy) ? "" : item2.CreateBy; _db.Updateable(item2).ExecuteCommand(); } else { _db.Insertable(item2).CallEntityMethod(m => m.Create()).ExecuteCommand(); } } } else { var batchingListrDbName = batchingListrDb.Select(x => x.Batching_Name).ToList(); batchingList = batchingList.Where(x => !batchingListrDbName.Contains(x.Batching_Name)).ToList(); await _db.Insertable(batchingList).ExecuteCommandAsync(); } #endregion //添加 商品_基础信息 #region 添加 商品_基础信息 //1.查询大分类 和小分类 var type = new BPA_GoodsType(); var parentType = await _db.Queryable() .Where(x => x.Name == "默认分类" && x.GroupId == x.GroupId).FirstAsync(); if (parentType == null) { parentType = new BPA_GoodsType() { IsDeleted = 0, Name = "默认分类", Remark = "", Sort = 0, Status = 0, Pid="0" }; type=await _db.Insertable(parentType).CallEntityMethod(m => m.Create()).ExecuteReturnEntityAsync(); parentType = type; } //属性 var goodsAttribute = await _db.Queryable() .Where(x => x.AttributeName == "默认属性" ).FirstAsync(); if (goodsAttribute == null) { goodsAttribute = new BPA_GoodsAttribute() { AttributeName = "默认属性", GoodsTypeId = parentType.Id, IsDeleted = 0, Sort = 0, }; _db.Insertable(goodsAttribute).CallEntityMethod(m => m.Create()).ExecuteCommand(); } var goodsattributevalue = await _db.Queryable() .FirstAsync(x => x.AttributeValue == "默认属性值" && x.GoodsAttributeId == goodsAttribute.Id && x.IsDeleted == 0); if (goodsattributevalue == null) { goodsattributevalue = new BPA_GoodsAttributeValue() { AttributeValue = "默认属性值", GoodsAttributeId = goodsAttribute.Id, IsDeleted = 0, Sort = 1, }; _db.Insertable(goodsattributevalue).CallEntityMethod(m => m.Create()).ExecuteCommand(); } ReadExcel readGoodModelExcel = new(); var oodModellist = readGoodModelExcel.ExcelToList(source, mapper, "商品_基础信息"); List goodsInfo = new List(); int index = 1; foreach (var item in oodModellist.Where(x => !string.IsNullOrEmpty(x.Name))) { //单位 var goodsUint = await _db.Queryable().Where(x => x.Name == "默认单位").FirstAsync(); if (goodsUint == null) { goodsUint = new BPA_GoodsUint() { IsDeleted = 0, Name = "默认单位", Status = 0, }; await _db.Insertable(goodsUint).CallEntityMethod(m => m.Create()).ExecuteCommandAsync(); } Console.WriteLine("数据解析完成,开始解析图片"); var images = await ExcelToDatatable(file.OpenReadStream(), Path.GetExtension(file.FileName), "商品_基础信息"); var imagePath = images.FirstOrDefault(x => x.Index == index); goodsInfo.Add(new BPA_GoodsInfo() { Code = GetNumber2(), CreateAt = DateTime.Now, CreateBy = userId, DefaultMate = null, Design = "默认规格", ForeignKeyRe = null, GoodsUintId = goodsUint.Id, Descritption = "", ImgMode = 0, ImgUrl = imagePath?.ImgesPath, Name = item.Name, Sort = 0, GoodsTypeId = parentType.Id, Price = 0, IsAttrubute = false, IsDeleted = 0, IsWeigh = false, Key = null, Status = 0, }); index++; } var ngoodsInfoName = goodsInfo.Select(x => x.Name).ToList(); var goodsInfoListDb = _db.Queryable().Where(x => ngoodsInfoName.Contains(x.Name)).ToList(); //替换 if (isReplace) { foreach (var item2 in goodsInfo) { var thisitem = goodsInfoListDb.FirstOrDefault(x => x.Name == item2.Name); if (thisitem != null) { item2.Id = thisitem.Id; item2.AutoKey = thisitem.AutoKey; item2.GroupId= thisitem.GroupId; _db.Updateable(item2).ExecuteCommand(); } else { await _db.Insertable(item2).CallEntityMethod(m => m.Create()).ExecuteCommandAsync(); } } } else { var goodsInfoListDbName = goodsInfoListDb.Select(x => x.Name).ToList(); goodsInfo = goodsInfo.Where(x => !goodsInfoListDbName.Contains(x.Name)).ToList(); await _db.Insertable(goodsInfo).CallEntityMethod(m => m.Create()).ExecuteCommandAsync(); } #endregion //添加设备商品仓位 #region 添加设备商品仓位 ReadExcel deviceGoodsPositionModelExcel = new(); var deviceGoodsPosition = deviceGoodsPositionModelExcel.ExcelToList(source, mapper, "设备物料仓位"); var _deviceNames = deviceGoodsPosition.Select(x => x.DeviceName).ToList(); var _goodsName = deviceGoodsPosition.Select(x => x.GoodsName).Distinct().ToList(); var _deviceList = _db.Queryable() .Where(x => _deviceNames.Contains(x.DeviceName)) .ToList(); var _goodsNameList = _db.Queryable() .Where(x => _goodsName.Contains(x.Name)) .ToList(); var deviceGoodsPositionList = new List(); foreach (var item in deviceGoodsPosition) { var thisDevice = _deviceList.FirstOrDefault(x => x.DeviceName == item.DeviceName); var thisGoods = _goodsNameList.FirstOrDefault(x => x.Name == item.GoodsName); deviceGoodsPositionList.Add(new BPA_DeviceGoodsPosition() { DeviceId = thisDevice?.Id, GoodsId = thisGoods?.Id, Id = Guid.NewGuid().ToString(), Position1 = item.Position1, Position2 = item.Position2, Position3 = item.Position3, Position4 = item.Position4, }); } var deviceGoodsPositionListDb = _db.Queryable().ToList(); foreach (var item in deviceGoodsPositionList) { var dGPDb = deviceGoodsPositionListDb.FirstOrDefault(x => x.DeviceId == item.DeviceId && x.GoodsId == x.GoodsId); if (dGPDb != null) { item.Id = dGPDb.Id; await _db.Updateable(item).ExecuteCommandAsync(); } else { await _db.Insertable(item).CallEntityMethod(m => m.Create()).ExecuteCommandAsync(); } } #endregion //添加 功能_{商品名称} var tableName = ExcelToShtteName(file.OpenReadStream(), Path.GetExtension(file.FileName)); #region 添加 工艺_{商品名称} foreach (var name in tableName) { var nameList = name.Split('_'); //查询设备 var name1 = nameList[1]; var name2 = nameList[2]; var device = await _db.Queryable().FirstAsync(x => x.DeviceName == name1 && x.IsDeleted == 0); if (device == null) { throw Oops.Oh(nameList + " 设备【" + nameList[1] + "】不存在"); } ReadExcel goodTechnologyModelExcel = new(); var goodTechnologyModel = goodTechnologyModelExcel.ExcelToList(source, mapper, name); var goodstechnologyactionDto = new List(); var cName = ""; var info = new List(); var namestr = nameList[2]; var goods = await _db.Queryable().Where(x => x.Name == namestr).FirstAsync(); var goodsId = goods == null ? "" : goods.Id; _db.Deleteable().Where(x => x.GoodsId == goodsId).ExecuteCommand(); var goodTechnologyIndex = 0; for (int i = 0; i < goodTechnologyModel.Count; i++) { var thisName = goodTechnologyModel[i].Name == null ? cName : goodTechnologyModel[i].Name; var data = await _db.Queryable() .Where(x => x.Name == thisName && x.DeviceVersionId == device.ProductVersionId).FirstAsync(); if (data == null) throw Oops.Oh("该设备还没有设置工艺基础信息"); var data2 = await _db.Queryable() .Where(x => x.ActionName == goodTechnologyModel[i].Configuration && x.TechnologyId == data.Id).FirstAsync(); var batching = new BPA_Batching(); var IsBatch = goodTechnologyModel[i].Name != "液体料"; if (!string.IsNullOrEmpty(goodTechnologyModel[i].Name)) { goodTechnologyIndex++; cName = goodTechnologyModel[i].Name; GoodsTechnologyActionDto item = new GoodsTechnologyActionDto() { ActionJson = "", ChnologyId = data?.Id, GoodsAttributeId = goodsattributevalue.Id, GoodsId = goods?.Id, IsBatch = IsBatch, IsDeleted = 0, Sort = goodTechnologyIndex, DeviceId = device?.Id, StepName = goodTechnologyModel[i].Name, Index = goodTechnologyIndex.ToString(), }; info.Add(new ActionJson { chnologyId = data?.Id, actionName = goodTechnologyModel[i].Configuration, actionValue = goodTechnologyModel[i].Value, technologyactionId = !IsBatch ? batching.Id : data2?.Id, index = goodTechnologyIndex.ToString(), }); goodstechnologyactionDto.Add(item); } else { info.Add(new ActionJson { chnologyId = data?.Id, actionName = goodTechnologyModel[i].Configuration, actionValue = goodTechnologyModel[i].Value, technologyactionId = !IsBatch ? batching.Id : data2?.Id, index = goodTechnologyIndex.ToString(), }); ; } } foreach (var thisItem in goodstechnologyactionDto) { var json = info.Where(x => x.chnologyId == thisItem.ChnologyId && x.index == thisItem.Index).ToList(); //if (thisItem.StepName == "液体料") //{ // foreach (var item in json) // { // var batching = await _db.Queryable() // .FirstAsync(x => x.Batching_Name == item.actionName); // item.technologyactionId = batching?.Id; // } //} if (thisItem.StepName == "主料") { var v1 = json.FirstOrDefault(x => x.actionName == "主料名称"); var v2 = deviceGoodsPosition.FirstOrDefault(x => x.GoodsName == name2 && x.DeviceName == name1); var jsondb = await _db.Queryable() .Where(x => x.TechnologyId == thisItem.ChnologyId) .ToListAsync(); foreach (var item in from item in jsondb let insertableJsondb = json.FirstOrDefault(x => x.technologyactionId == item.Id) where insertableJsondb == null select item) { json.Add(new ActionJson() { actionName = item.ActionName, actionValue = item.ActionName == "主料重量" ? "0" : item.ActionValue, chnologyId = item.TechnologyId, index = thisItem.Index, technologyactionId = item.Id }); } foreach (var thisitem2 in json) { if (thisitem2.actionName == "主料位置") { if (v2 == null) { throw Oops.Oh(v1.actionValue + "物料没有确定位置"); } thisitem2.actionValue = GetPositionMaterial(v2, v1.actionValue); if (string.IsNullOrEmpty(thisitem2.actionValue)) { throw Oops.Oh(v1.actionValue + "物料没有确定位置"); } } } } thisItem.ActionJson = JsonConvert.SerializeObject(json); } var insertableDta = goodstechnologyactionDto.Adapt>(); await _db.Insertable(insertableDta).CallEntityMethod(m => m.Create()).ExecuteCommandAsync(); } #endregion _db.Ado.CommitTran(); return true; } catch (Exception e) { _db.Ado.RollbackTran(); throw Oops.Oh("导入失败,失败信息:" + e.Message); } } /// /// 获取 物料仓位 /// /// private string GetPositionMaterial(DeviceGoodsPositionModel item, string goodsName) { var properties = item.GetType().GetProperties(); foreach (var item2 in properties) { var value = item.GetType().GetProperty(item2.Name)?.GetValue(item); if (value == null) { value = ""; } if (value.ToString().Trim() == goodsName?.Trim()) { //ColumnAttribute attribute = (ColumnAttribute)item2.GetCustomAttribute(typeof(ColumnAttribute), false); //return attribute?.Name; if (item2.IsDefined(typeof(Npoi.Mapper.Attributes.ColumnAttribute), false)) { Npoi.Mapper.Attributes.ColumnAttribute attribute = (Npoi.Mapper.Attributes.ColumnAttribute)item2.GetCustomAttribute(typeof(Npoi.Mapper.Attributes.ColumnAttribute), false); return attribute.Name; } } } return ""; } /// /// 导出 设备工艺流程 /// /// public async Task TechnologyTemplateExport(string deviceId) { var result = ""; //查询设备 var device = await _db.Queryable().FirstAsync(x => x.Id == deviceId); //设备类型 var dictData = await _db.Queryable().FirstAsync(x => x.DeviceVersionId == device.ProductVersionId); return dictData?.TemplatePath ?? ""; } /// /// 设备 版本 工序模型导入 /// /// public async Task DeviceVersionTemplateImport(DeviceVersionTemplateImportInputDto inputDto) { var file = inputDto.file; try { _db.Ado.BeginTran(); //if (inputDto.IsAddGoodsTemplate) //{ //} //else //{ var source = file.OpenReadStream(); var mapper = new Mapper(source); var deviceVersion = await _db.Queryable().FirstAsync(x => x.ProductId == inputDto.DeviceClientType && x.Vesion == inputDto.Version); //添加 设备_烹饪工序模型 #region 添加 设备_烹饪工序模型 ReadExcel readGoodstechnologyExcel = new(); var GoodstechnologyModellist = readGoodstechnologyExcel.ExcelToList(source, mapper); List GoodsTechnologyList = new(); List GoodsTechnologyActionList = new(); var GoodsTechnologyListDB = await _db.Queryable() .Where(x => x.DeviceVersionId == deviceVersion.Id).ToListAsync(); string currennaid = ""; string currennaname = ""; for (int i = 0; i < GoodstechnologyModellist.Count; i++) { var goodsTechnologyId = GoodsTechnologyListDB.FirstOrDefault(x => x.Name == GoodstechnologyModellist[i].Name); if (!string.IsNullOrWhiteSpace(GoodstechnologyModellist[i].Name)) { BPA_Technology item = new BPA_Technology() { Id = goodsTechnologyId == null ? Guid.NewGuid().ToString() : goodsTechnologyId.Id, Name = GoodstechnologyModellist[i].Name, DeviceVersionId = deviceVersion.Id }; GoodsTechnologyList.Add(item); currennaid = item.Id; currennaname = item.Name; } var actvalueary = GoodstechnologyModellist[i].ActionValue?.Split('、'); if (string.IsNullOrEmpty(GoodstechnologyModellist[i].ActionType) && currennaname != "液体料") { throw Oops.Oh($"类型错误"); } BPA_TechnologyAction technologyAction = new() { Id = Guid.NewGuid().ToString(), TechnologyId = currennaid, ActionName = GoodstechnologyModellist[i].ActionName, ActionType = CharacterConversion(GoodstechnologyModellist[i].ActionType), Sort = i, TechnologyType = GoodstechnologyModellist[i].TechnologyType == "物料" ? TechnologyEnums.Batch : TechnologyEnums.Other, CreateAt = DateTime.Now, //ActionValue = GoodstechnologyModellist[i].ActionValue, }; List ActionValueModelList = new(); if (actvalueary != null) { foreach (var item in actvalueary) { ActionValueModelList.Add(new ActionValueModel() { actionValueName = item }); } technologyAction.ActionValue = JsonConvert.SerializeObject(ActionValueModelList); } GoodsTechnologyActionList.Add(technologyAction); } //修改添加 主表 foreach (var item in GoodsTechnologyList) { var thisitem = GoodsTechnologyListDB.FirstOrDefault(x => x.Name == item.Name); if (thisitem != null) { item.Id = thisitem.Id; item.CreateAt = DateTime.Now; _db.Updateable(item).ExecuteCommand(); } else { //item.Id = Guid.NewGuid().ToString(); item.CreateAt = DateTime.Now; await _db.Insertable(item).ExecuteCommandAsync(); } } //修改添从表 GoodsTechnologyActionList = GoodsTechnologyActionList.Where(x => !string.IsNullOrEmpty(x.ActionName)).ToList(); var goodstechnologyIds = GoodsTechnologyList.Select(x => x.Id).ToList(); var GoodsTechnologyActionListDb = await _db.Queryable() .Where(x => goodstechnologyIds.Contains(x.TechnologyId)).ToListAsync(); foreach (var item in GoodsTechnologyActionList) { var thisitem = GoodsTechnologyActionListDb.FirstOrDefault(x => item.TechnologyId == x.TechnologyId && item.ActionName == x.ActionName); if (thisitem != null) { item.Id = thisitem.Id; item.CreateAt = DateTime.Now; _db.Updateable(item).ExecuteCommand(); } else { item.Id = Guid.NewGuid().ToString(); item.CreateAt= DateTime.Now; await _db.Insertable(item).ExecuteCommandAsync(); } } #endregion var path = await _SystemConfigService.GetCosImgesURL(file); var TechnologyExportRecode = _db.Queryable().Where(x=>x.DeviceVersionId == inputDto.Id).First(); if (TechnologyExportRecode != null) { TechnologyExportRecode.CreateAt= DateTime.Now; TechnologyExportRecode.TemplatePath = path; var vvv= await _db.Updateable(TechnologyExportRecode).ExecuteCommandAsync(); } else { BPA_TechnologyExportRecode _TechnologyExportRecode = new(); _TechnologyExportRecode.Id = Guid.NewGuid().ToString(); _TechnologyExportRecode.CreateAt = DateTime.Now; _TechnologyExportRecode.ProductId = inputDto.DeviceClientType; _TechnologyExportRecode.DeviceVersionId = inputDto.Id; _TechnologyExportRecode.TemplatePath= path; await _db.Insertable(_TechnologyExportRecode).ExecuteCommandAsync(); //await _db.Updateable() // .SetColumns(it => it.TemplatePath == path) // .Where(it => it.Id == inputDto.Id) // .ExecuteCommandAsync(); } //} _db.Ado.CommitTran(); } catch (Exception e) { _db.Ado.RollbackTran(); throw Oops.Oh($"Excel导入错误," + e.Message); } return true; } public string GetValueStr(string str) { try { var obj = JsonConvert.DeserializeObject>(str); var result = String.Join(",", obj.Select(x => x.ActionValueName).ToArray()); return result; } catch (Exception e) { return ""; } } public string CharacterConversion(string str) { switch (str) { case "下拉框": return "select"; case "数字输入框": return "digit"; case "文本框": return "text"; case "开关": return "switch"; case "文字域": return "textarea"; default: break; } return ""; } /// /// 设置excel的下拉框 /// /// /// /// private void SetExcelSelect(ISheet sheet, List selectData, int firstRow, int lastRow, int firstCol, int lastCol) { var count = selectData.Sum(item => item.Count()); if (count > 180) { return; } //设置生成下拉框的行和列 var cellRegions = new CellRangeAddressList(1, 65535, firstCol, lastCol); //设置 下拉框内容 DVConstraint constraint = DVConstraint.CreateExplicitListConstraint(selectData.ToArray()); //绑定下拉框和作用区域,并设置错误提示信息 HSSFDataValidation dataValidate = new HSSFDataValidation(cellRegions, constraint); dataValidate.CreateErrorBox("输入不合法", "请输入或选择下拉列表中的值。"); dataValidate.ShowPromptBox = true; sheet.AddValidationData(dataValidate); } /// /// 将 Stream 写入文件 /// private void StreamToFile(byte[] bytes, string filepath) { // 把 byte[] 写入文件 FileStream fs = new FileStream(filepath, FileMode.Create); BinaryWriter bw = new BinaryWriter(fs); bw.Write(bytes); bw.Close(); fs.Close(); } /// /// 获取 shtte name /// /// /// /// /// /// private List ExcelToShtteName(Stream stream, string fileType, bool isGY = true) { var result = new List(); ISheet sheet = null; IWorkbook workbook = null; var shellCount = 0; try { #region 判断excel版本 //2007以上版本excel if (fileType == ".xlsx") { workbook = new XSSFWorkbook(stream); shellCount = ((XSSFWorkbook)workbook).Count; } //2007以下版本excel else if (fileType == ".xls") { workbook = new HSSFWorkbook(stream); shellCount = ((HSSFWorkbook)workbook).Count; } else { throw Oops.Oh($"传入的不是Excel文件"); } #endregion for (int sheetI = 0; sheetI < shellCount; sheetI++) { sheet = workbook.GetSheetAt(sheetI); if (isGY) { if (sheet.SheetName.Contains("工艺")) { result.Add(sheet.SheetName); } } else { result.Add(sheet.SheetName); } } } catch (Exception ex) { throw Oops.Oh($"Excel操作错误" + ex.Message); } return result; } /// /// 将Excel单表转为Datatable /// /// /// /// /// /// public async Task> ExcelToDatatable(Stream stream, string fileType, string sheetName = null) { var result = new List(); ISheet sheet = null; IWorkbook workbook = null; try { #region 判断excel版本 //2007以上版本excel if (fileType == ".xlsx") { workbook = new XSSFWorkbook(stream); } //2007以下版本excel else if (fileType == ".xls") { workbook = new HSSFWorkbook(stream); } else { throw new Exception("传入的不是Excel文件!"); } #endregion Console.WriteLine("已确定解析格式,开始解析"); if (workbook == null) { Console.WriteLine("已确定解析格式,工具"); } IList pictures = workbook.GetAllPictures(); Console.WriteLine("已确定解析格式,成功解析" + JsonConvert.SerializeObject(pictures)); int i = 1; foreach (XSSFPictureData pic in pictures) { Console.WriteLine("讲数据流转化为图片"); Image jpg1 = Image.FromStream(new MemoryStream(pic.Data));//从pic.Data数据流创建图片 Console.WriteLine("转化成功"); var imagePath = await GetCosImgesURL(PhotoImageInsert(jpg1)); Console.WriteLine("图片路径" + imagePath); result.Add(new ExcelDtoImagDto() { ImgesPath = imagePath, Index = i }); i++; } } catch (Exception ex) { throw new Exception(ex.Message); } return result; } //将Image转换成流数据,并保存为byte[] public byte[] PhotoImageInsert(Image imgPhoto) { MemoryStream mstream = new MemoryStream(); imgPhoto.Save(mstream, ImageFormat.Bmp); byte[] byData = new Byte[mstream.Length]; mstream.Position = 0; mstream.Read(byData, 0, byData.Length); mstream.Close(); return byData; } public async Task GetCosImgesURL(byte[] data) { var result = ""; TransferUploadObjectModel m = new TransferUploadObjectModel(_db); /// 高级接口上传对象 result = await m.TransferUploadFile(new FileInputInfoDto() { Directory = "goods", FileExtension = "png", Method = "PUT", }, data); return result; } private string GetNumber2(int Length = 10) { byte[] buffer = Guid.NewGuid().ToByteArray(); var ram = BitConverter.ToInt64(buffer, 0); var str = string.Format("{0}", ram.ToString().Substring(0, Length)); return str; } } }