private void PopulateWorksheetWithPurchaseOrders(ExcelWorksheet worksheet, DayOfWeek day, IEnumerable <KeyValuePair <Guid, string> > clients, IEnumerable <Product> existingProducts, IEnumerable <PurchaseOrder> purchaseOrders) { AddHeadersRow(worksheet, DayHelper.GetDayFromEnum(day), clients); AddProductsRows(worksheet, clients, existingProducts, purchaseOrders); }
public async Task <Result <ResourceExportDto> > ExportAsync(RequestUser user, IQueryable <PurchaseOrder> purchaseOrdersQuery, CancellationToken token) { using (var excelPkg = new ExcelPackage()) { var purchaseOrders = await purchaseOrdersQuery.ToListAsync(token); var storeDeliveryDays = purchaseOrders .Where(po => po.SenderInfo.Kind == ProfileKind.Store) .GroupBy(po => po.ExpectedDelivery.ExpectedDeliveryDate.DayOfWeek); var products = await _context.Products .Where(p => !p.RemovedOn.HasValue && p.ProducerId == user.Id) .OrderBy(p => p.Name) .ToListAsync(token); foreach (var storeDeliveryDay in storeDeliveryDays) { var worksheet = excelPkg.Workbook.Worksheets.Add($"Commandes du {DayHelper.GetDayFromEnum(storeDeliveryDay.Key)}"); var clients = await _context.Agreements .Where(u => !u.RemovedOn.HasValue && u.ProducerId == user.Id && u.DeliveryMode.Kind == DeliveryKind.ProducerToStore && u.DeliveryMode.DeliveryHours.Any(oh => oh.Day == storeDeliveryDay.Key)) .Select(c => new KeyValuePair <Guid, string>(c.StoreId, c.Store.Name)) .OrderBy(c => c.Value) .ToListAsync(token); var storesPurchaseOrders = storeDeliveryDay.Select(d => d).ToList(); PopulateWorksheetWithPurchaseOrders(worksheet, storeDeliveryDay.Key, clients, products, storesPurchaseOrders); } var consumerDeliveryDays = purchaseOrders .Where(po => po.SenderInfo.Kind == ProfileKind.Consumer) .GroupBy(po => po.ExpectedDelivery.ExpectedDeliveryDate.DayOfWeek) .ToList(); if (consumerDeliveryDays.Any()) { var clients = consumerDeliveryDays .SelectMany(cpo => cpo.Select(c => new KeyValuePair <Guid, string>(c.ClientId, $"{c.SenderInfo.Name} ({c.Reference})"))) .OrderBy(c => c.Value) .ToList(); foreach (var consumerDeliveryDay in consumerDeliveryDays) { var worksheet = excelPkg.Workbook.Worksheets.Add($"Commandes conso du {DayHelper.GetDayFromEnum(consumerDeliveryDay.Key)}"); var consumersPurchaseOrders = consumerDeliveryDay.Select(d => d).ToList(); PopulateWorksheetWithPurchaseOrders(worksheet, consumerDeliveryDay.Key, clients, products, consumersPurchaseOrders); } } return(Success(new ResourceExportDto { Data = excelPkg.GetAsByteArray(), Extension = "xlsx", MimeType = "application/ms-excel" })); } }