(1)页面数据加载缓慢新增job后台执行web
WebApi修改Job调用服务器
[Route("QueryOrderThirtyStatistics"), HttpPost] [ResponseType(typeof(List<BossModel>))] public async Task<HttpResponseMessage> QueryOrderThirtyStatistics(List<string> workerNos) { var bossService = new BossService(); var result = await bossService.QueryOrderThirtyStatistics(workerNos).ConfigureAwait(false); return OkResult(result); }
修改成app
public class BossOrderThirtyStatisticsJob : Job { public override TimeSpan? MinimumExecutingTime => TimeSpan.FromDays(1); protected override async Task<JobContinueAction> Run(CancellationToken token) { var bossService = new BossService(); List<string> workerNo = new List<string>(); workerNo.Add("-1"); await bossService.QueryOrderStatisticByNumOrMoney(workerNo).ConfigureAwait(false); return JobContinueAction.Default; } }
(2)导入商品信息async
Controllerside
[Route("skuImports"), HttpPost] [ResponseType(typeof(bool))] public async Task<HttpResponseMessage> ImportSku() { var hfc = System.Web.HttpContext.Current.Request.Files; var file = hfc[0]; if (file == null) { throw new DomainException("文件不存在"); } if (file.ContentLength == 0) { throw new DomainException("上传的文件内容不能为空"); } const int maxImageSize = 200 * 1024 * 1024; if (file.ContentLength > maxImageSize) { throw new DomainException("文件不能大于200M"); } var extension = Path.GetExtension(file.FileName); var isAllowed = extension.EqualsWith(".xlsx"); if (!isAllowed) { throw new DomainException($"不支持的文件类型: {extension}"); } var datas = ExcelHelper.ReadAsList<ImportSkuModel>(file.InputStream, "SkuData"); var errors = datas.Errors; var importResult = new ImportSkuResult(); if (errors.IsNullOrEmpty()) { var skuService = new SkuService(); importResult = await skuService.ImportSkus(datas.Data, User.UserOperator).ConfigureAwait(false); } else { importResult.ErrorMessages = errors.ToList(); } if (importResult.ErrorMessages.Count > 1000) { importResult.ErrorMessages = importResult.ErrorMessages.Take(1000).ToList(); importResult.ErrorMessages.Insert(0, "错误信息超过1000条,只显示前1000条"); } return OkResult(importResult); }
Servicesui
public async Task<ImportSkuResult> ImportSkus(ICollection<ImportSkuModel> importSku, UserOperator userOperator) { if (importSku.IsNullOrEmpty()) { throw new DomainException("没有能够导入的数据"); } var dupNames = importSku.GroupBy(m => m.Name, StringComparer.OrdinalIgnoreCase) .Select(g => new { Name = g.Key, Count = g.Count() }).Where(m => m.Count > 1).ToList(); if (dupNames.Any()) { var resul = new ImportSkuResult() { ErrorMessages = dupNames.Select(m => $"重复的商品名称:[{m.Name}]").ToList() }; return resul; } var skuDicts = importSku.GroupBy(m => m.SkuCode, StringComparer.OrdinalIgnoreCase) .ToDictionary(g => g.Key, g => g.ToList()); var errorMessages = new List<string>(); var successSkus = new Dictionary<ImportSkuModel, ICollection<ImportSkuModel>>(); ValidImportSkus(skuDicts, errorMessages, successSkus); if (successSkus.Any()) { var skuCodes = successSkus.Select(m => m.Key.SkuCode).ToList(); var names = successSkus.Select(m => m.Key.Name).ToList(); using (var trans = TransactionFactory.Default()) using (var db = Db.Products) { var dupSkus = db.Skus.Where(m => skuCodes.Contains(m.SkuCode)).Select(m => m.SkuCode).ToList(); foreach (var dupSkuCode in dupSkus) { errorMessages.Add($"与现有Sku重复的Sku:{dupSkuCode}"); } var theDupNames = db.Skus.Where(m => names.Contains(m.Name)).Select(m => m.Name).ToList(); errorMessages.AddRange(theDupNames.Select(m => $"重复的商品名称:{m}")); var newImportSkuInfos = successSkus.Where(m => !dupSkus.Any(x => x.EqualsWith(m.Key.SkuCode))) .ToList(); newImportSkuInfos = newImportSkuInfos.Where(m => !theDupNames.Any(x => x.EqualsWith(m.Key.Name))).ToList(); var partSkus = newImportSkuInfos.Partition(50); foreach (var thePartOrder in partSkus) { var skus = new List<Sku>(); foreach (var newImportOrderInfo in thePartOrder) { var skuBaseInfo = newImportOrderInfo.Key; var declarationModel = new Declaration(); declarationModel.ChineseName = skuBaseInfo.ChineseName; declarationModel.EnglishName = skuBaseInfo.EnglishName; declarationModel.DeclaredValue = skuBaseInfo.DeclaredValue; declarationModel.HsCode = skuBaseInfo.HsCode; var sku = Sku.CreateNewSku(skuBaseInfo.SkuCode, skuBaseInfo.Name, skuBaseInfo.Length, skuBaseInfo.Width, skuBaseInfo.Height, skuBaseInfo.CostPrice ?? 0M, skuBaseInfo.Weight, skuBaseInfo.ImageUrl, declarationModel, skuBaseInfo.ProductCycle, skuBaseInfo.SeasonalProductBeginMonth, skuBaseInfo.SeasonalProductEndMonth, userOperator, null, null); if (skuBaseInfo.IsGroupSku == "是") { sku.IsGroupSku = true; } else if (skuBaseInfo.IsGroupSku == "否") { sku.IsGroupSku = false; } else { errorMessages.Add($"Sku:{skuBaseInfo.SkuCode},是否为组合商品字段导入错误"); continue; } sku.Status = SkuStatus.Normal; skus.Add(sku); } db.Skus.AddRange(skus); await db.SaveChangesAsync().ConfigureAwait(false); } trans.Complete(); } } var result = new ImportSkuResult() { TotalCount = skuDicts.Count, FailedCount = errorMessages.Count, ErrorMessages = errorMessages }; return result; } private static void ValidImportSkus(Dictionary<string, List<ImportSkuModel>> skuDicts, List<string> errorMessages, Dictionary<ImportSkuModel, ICollection<ImportSkuModel>> successSkus) { foreach (var skuDict in skuDicts) { var skuCode = skuDict.Key; if (skuDict.Value.Count > 1) { errorMessages.Add($"表格数据重复Sku:{skuDict.Key}"); continue; } var firstOkSku = skuDict.Value.FirstOrDefault(m => m.CostPrice.HasValue); if (firstOkSku == null) { errorMessages.Add($"Sku:{skuCode}.采购价不能为空"); continue; } var skuErrorMessages = new List<string>(); if (firstOkSku.SkuCode.IsNullOrWhiteSpace()) { skuErrorMessages.Add("商品SKU代码不能为空"); continue; } if (firstOkSku.Name.IsNullOrWhiteSpace()) { skuErrorMessages.Add("商品名称不能为空"); continue; } if (firstOkSku.Weight < 1) { skuErrorMessages.Add("重量不能小于1"); continue; } if (firstOkSku.IsGroupSku.IsNullOrWhiteSpace()) { skuErrorMessages.Add("是否为组合商品不能为空"); continue; } if (firstOkSku.IsGroupSku != "是" && firstOkSku.IsGroupSku != "否") { skuErrorMessages.Add("是否为组合商品导入值错误"); continue; } if (firstOkSku.Length < 1) { skuErrorMessages.Add("长度不能小于0"); continue; } if (firstOkSku.Width < 1) { skuErrorMessages.Add("宽度不能小于0"); continue; } if (firstOkSku.Height < 1) { skuErrorMessages.Add("高度不能小于0"); continue; } if (firstOkSku.CostPrice < 1) { skuErrorMessages.Add("采购价不能小于0"); continue; } if (firstOkSku.ChineseName.IsNullOrWhiteSpace()) { skuErrorMessages.Add("中文报关名不能为空"); } if (firstOkSku.EnglishName.IsNullOrWhiteSpace()) { skuErrorMessages.Add("英文报关名不能为空"); } if (firstOkSku.EnglishName.IsMatch(@"[\u4e00-\u9fa5]")) { skuErrorMessages.Add("英文报关名不能包含中文"); } if (firstOkSku.ImageUrl.IsNullOrWhiteSpace()) { skuErrorMessages.Add("图片连接不能为空"); } if (skuErrorMessages.Any()) { errorMessages.Add($"sku:{skuCode},错误:{skuErrorMessages.JoinWith(";")}"); } else { successSkus.Add(firstOkSku, skuDict.Value); } } }
(3)导入图片压缩包url
Controllersspa
[Route("ImportSkuImage"), HttpPost] [ResponseType(typeof(bool))] public async Task<HttpResponseMessage> ImportSkuImage() { var hfc = System.Web.HttpContext.Current.Request.Files; if (hfc.Count < 1){ throw new DomainException("文件不存在"); } var file = hfc[0]; if (file == null) { throw new DomainException("文件不存在"); } if (file.ContentLength == 0) { throw new DomainException("上传的文件内容不能为空"); } var extension = Path.GetExtension(file.FileName); var allowExts = new string[] { ".zip", ".rar" }; var isAllowed = allowExts.Any(x => x.EqualsWith(extension)); if (!isAllowed) { throw new DomainException($"不支持的文件类型: {extension}"); } var skuService = new SkuService(); var Result = await skuService.ImportSkuImage(file,User.UserOperator, HttpContext.Current).ConfigureAwait(false); return OkResult(Result); }
Services( 导入图片压缩包,解压上传到服务器)3d
public async Task<ImportSkuResult> ImportSkuImage(HttpPostedFile file, UserOperator userOperator, System.Web.HttpContext httpContext) { ImportSkuResult Result = new ImportSkuResult(); Result.ErrorMessages = new List<string>(); using (var db = Db.Products) { using (var trans = TransactionFactory.Default()) { string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()).Replace("\\", "/"); //string webroot = HttpContext.Current.Server.MapPath("~").Replace("\\", "/"); //ZIP路径 string zipPath = @"/Upload/Image/"; string path = tempPath + zipPath; using (var archive = new ZipArchive(file.InputStream, ZipArchiveMode.Read)) { archive.ExtractToDirectory(path); } List<ZipSkuInfo> ZipSkuInfos = new List<ZipSkuInfo>(); SearchDicretory(path, ZipSkuInfos); Result.TotalCount = ZipSkuInfos.Count; foreach (var zipSkuInfo in ZipSkuInfos) { //获取skuid var sku = db.Skus.FirstOrDefault(m => m.SkuCode.Equals(zipSkuInfo.SkuCode)); if (sku != null) { try { //查询是否重复 var skuImages = db.SkuImages.Where(m => m.SkuId == sku.Id); if (skuImages.Any()) { db.SkuImages.RemoveRange(skuImages); await db.SaveChangesAsync().ConfigureAwait(false); } zipSkuInfo.FileList.Sort(); int i = 0; foreach (var fileList in zipSkuInfo.FileList) { // 获取文件后缀名 string format = Path.GetExtension(fileList); string guid = Guid.NewGuid().ToString().ToLower(); //获取当前用户 var user = db.Users.FirstOrDefault(m => m.Id == userOperator.UserId); //将图片添加到skuImage中 string url = $"http://erp.demarkt.com.cn:8011/upload/product/8888/{sku.Id}/{guid}{format}"; bool isMain = (i == 0); var skuImage = SkuImage.CreateSkuImage(sku.Id, url, i, user?.Id ?? 0, isMain); db.SkuImages.Add(skuImage); //绝对路径 string localPath = httpContext.Server.MapPath($"/upload/product/8888/{sku.Id}"); //判断是否存在文件夹,没有则建立 if (!Directory.Exists(localPath)) Directory.CreateDirectory(localPath); //将图片拷贝到绝对路径上 File.Copy(fileList,Path.Combine(localPath, guid + format)); i++; } await db.SaveChangesAsync().ConfigureAwait(false); } catch (Exception e) { Result.FailedCount++; Result.ErrorMessages.Add(e.Message); } } else { Result.FailedCount++; Result.ErrorMessages.Add("未找到SkuCode对应的数据"); } } trans.Complete(); } } return Result; } public void SearchDicretory(string dicretoryPath, List<ZipSkuInfo> ZipSkuInfos) { DirectoryInfo Folder = new DirectoryInfo(dicretoryPath); FileInfo[] thefileInfo = Folder.GetFiles("*.jpg", SearchOption.TopDirectoryOnly); FileInfo[] thefileInfo2 = Folder.GetFiles("*.png", SearchOption.TopDirectoryOnly); //判断是否有图片 if (thefileInfo.Length > 0 || thefileInfo2.Length > 0) { //有图片 ZipSkuInfo skuInfo = new ZipSkuInfo() { SkuCode = Folder.Name, FileList = thefileInfo.Select(x => x.FullName).ToList() }; skuInfo.FileList.AddRange(thefileInfo2.Select(x => x.FullName).ToList()); ZipSkuInfos.Add(skuInfo); } else { DirectoryInfo[] dirInfo = Folder.GetDirectories(); foreach (var dirItem in dirInfo) { SearchDicretory(dirItem.FullName, ZipSkuInfos); } } }
(4)导出商品信息code
Controllers
[Route("skuExport"), HttpGet] [ResponseType(typeof(bool))] public async Task<HttpResponseMessage> ExportSkus([FromUri(Name = "")]AllSkuListQueryModel queryModel, string skuIds = null) { var theSkuIds = skuIds.EnsureTrim().EnsureNotNull().Split(",").Select(long.Parse).ToList(); var skuService = new SkuService(); var skus = await skuService.GetExportSkus(theSkuIds, queryModel).ConfigureAwait(false); var ms = ExcelHelper.Export(skus); var result = Request.CreateResponse(HttpStatusCode.OK); result.Content = new ByteArrayContent(ms.ToArray()); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = $"SKU导出_{DateTimeOffset.Now:yyyyMMddHHmmss}.xlsx" }; result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); return result; }
Services(获取导出的数据)
public async Task<IList<SkuExportListModel>> GetExportSkus(List<long> skuIds, AllSkuListQueryModel queryModel) { using (var db = Db.Products) { IQueryable<Sku> baseQuery; if (skuIds.IsNullOrEmpty()) { baseQuery = await InnerSkuQuery(queryModel.ShippingAttribute, queryModel.SearchType, queryModel.SearchText, queryModel.SearchUnusualType, queryModel.SkuHasPruchaseUrl, queryModel.SkuHasCombine, queryModel.CompleteStatus, queryModel.IsHasImage, queryModel.SelectAuditComponent, db) .ConfigureAwait(false); } else { baseQuery = db.Skus.Where(m => skuIds.Contains(m.Id)); } var totalCount = await baseQuery.CountNoLockAsync(); if (totalCount > 100000) { throw new DomainException("导出数量超过100000条"); } var skus = await baseQuery.AsNoTracking().ToListNoLockAsync(); var exportSkuDatas = new List<SkuExportListModel>(); foreach (var skuData in skus) { var exportSku = new SkuExportListModel() { Id = skuData.Id, }; exportSku.SkuCode = skuData.SkuCode; exportSku.Name = skuData.Name; exportSku.ShippingAttributes = skuData.ShippingAttributes.Split(",") .Select(s => s.As<ShippingAttributeType>().ToDescription()).JoinWith(","); exportSku.Length = skuData.Length; exportSku.Width = skuData.Width; exportSku.Height = skuData.Height; exportSku.Weight = skuData.Weight; exportSku.ImageUrl = skuData.ImageUrl; exportSku.IsGroupSku = skuData.IsGroupSku ? "是" : "否"; exportSku.CostPrice = skuData.CostPrice.ToString("f2"); exportSku.ChineseName = skuData.Declaration.ChineseName; exportSku.EnglishName = skuData.Declaration.EnglishName; exportSku.DeclaredValue = skuData.Declaration.DeclaredValue?.ToString("f2"); exportSku.HsCode = skuData.Declaration.HsCode; exportSkuDatas.Add(exportSku); } return exportSkuDatas; } }
Lambda
1.查询name
var names = successSkus.Select(m => m.Key.Name).ToList();
2.查询name包含
var dupSkus = db.Skus.Where(m => skuCodes.Contains(m.SkuCode)).Select(m => m.SkuCode).ToList();
LinQ
1.根据日期查询最近的数据
select * from(
select ROW_NUMBER() over(order by id) as rows,* from( select * from (select top 10* from [shipping_product].[dbo].[SelectedShippingServices] order by CreatedTime desc)as t )as tt) as ttt where rows <10
2.查询前10条用户组总和
(from i in Inventories
join w in Warehouses on i.WarehouseId equals w.Id select new { WarehouseName = w.Name, Quantity = i.TotalQuantity }).Take(10).GroupBy(m=>m.WarehouseName).Select(g=>new { g.Key, TotalQuantity = g.Sum(x=>x.Quantity) })