(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) })