This commit is contained in:
Denis 2023-05-20 12:11:48 +04:00
parent 19fb713cb8
commit 3e15c7b642
47 changed files with 1245 additions and 38 deletions

View File

@ -177,17 +177,6 @@ namespace CanteenBusinessLogic.BusinessLogics
public bool UpdateProducts(LunchBindingModel lunch, ProductBindingModel product, int count)
{
var _lunch = _lunchStorage.GetElement(new LunchSearchModel { Id = lunch.Id });
if (count == -1)
{
if (_lunch.LunchProducts.ContainsKey(product.Id))
{
_lunch.LunchProducts.Remove(product.Id);
}
}
else if (count > 0)
{
_lunch.LunchProducts[product.Id] = (product, count);
}
double allSum = 0;
foreach (var lunchProducts in _lunch.LunchProducts)
{
@ -195,6 +184,20 @@ namespace CanteenBusinessLogic.BusinessLogics
int _count = lunchProducts.Value.Item2;
allSum += _product.Price * _count;
}
if (count == -1)
{
if (_lunch.LunchProducts.ContainsKey(product.Id))
{
_lunch.LunchProducts.Remove(product.Id);
allSum -= product.Price * _lunch.LunchProducts[product.Id].Item2;
}
}
else if (count > 0)
{
_lunch.LunchProducts[product.Id] = (product, count);
allSum += product.Price * count;
}
if (_lunchStorage.Update(new()
{
Id = _lunch.Id,

View File

@ -0,0 +1,132 @@
using CanteenBusinessLogic.OfficePackage;
using CanteenBusinessLogic.OfficePackage.HelperModels;
using CanteenContracts.BindingModels;
using CanteenContracts.BusinessLogicsContracts;
using CanteenContracts.SearchModel;
using CanteenContracts.StoragesContracts;
using CanteenContracts.View;
using CanteenContracts.ViewModels;
namespace CanteenBusinessLogic.BusinessLogics
{
public class ReportLogic : IReportLogic
{
private readonly ILunchStorage lunchStorage;
private readonly IOrderStorage orderStorage;
private readonly ICookStorage cookStorage;
private readonly IProductStorage productStorage;
private readonly IVisitorStorage workerStorage;
private readonly AbstractSaveToPdf saveToPdf;
private readonly AbstractSaveToWord saveToWord;
private readonly AbstractSaveToExcel saveToExcel;
public ReportLogic(ILunchStorage lunchStorage, IOrderStorage orderStorage, ICookStorage cookStorage, IProductStorage productStorage,
IVisitorStorage workerStorage, AbstractSaveToPdf saveToPdf, AbstractSaveToWord saveToWord, AbstractSaveToExcel saveToExcel)
{
this.cookStorage = cookStorage;
this.orderStorage = orderStorage;
this.lunchStorage = lunchStorage;
this.productStorage = productStorage;
this.workerStorage = workerStorage;
this.saveToPdf = saveToPdf;
this.saveToWord = saveToWord;
this.saveToExcel = saveToExcel;
}
public List<ReportLunchesPCView> GetLunchesPCView(ReportBindingModel model)
{
var list = new List<ReportLunchesPCView>();
// Получаем список обедов (сущность 1) за указанный период и для указанного посетителя
var lunches = lunchStorage.GetFilteredList(new LunchSearchModel
{
DateFrom = (DateTime)model.DateAfter,
DateTo = model.DateBefore,
VisitorId = model.VisitorId
});
foreach (var lunch in lunches)
{
var record = new ReportLunchesPCView
{
DateCreate = lunch.DateCreate,
Sum = Convert.ToInt32(lunch.Sum),
Orders = new List<OrderViewModel>(),
Cooks = new List<CookViewModel>()
};
// Получаем связанные заказы (сущность 2) для текущего обеда
var orders = lunch.LunchOrders.Keys.ToList();
foreach (var orderId in orders)
{
// Получаем заказы (сущность 2) и добавляем их в список Orders
var order = orderStorage.GetElement(new OrderSearchModel { Id = orderId });
record.Orders.Add(order);
}
// Получаем связанных поваров (сущность 4) для текущих продуктов обеда
var lunchProducts = lunch.LunchProducts.Keys.ToList();
foreach (var productId in lunchProducts)
{
var product = productStorage.GetElement(new ProductSearchModel { Id = productId });
var productCooks = product.ProductCooks.Keys.ToList();
foreach (var cookId in productCooks)
{
// Получаем поваров (сущность 4) и добавляем их в список Cooks
var cook = cookStorage.GetElement(new CookSearchModel { Id = cookId });
record.Cooks.Add(cook);
}
}
list.Add(record);
}
return list;
}
public void saveLunchesToPdfFile(ReportBindingModel model)
{
saveToPdf.CreateDoc(new PdfInfo
{
FileName = model.FileName,
Title = "Список заказов",
DateAfter = model.DateAfter.Value,
DateBefore = model.DateBefore.Value,
Lunches = GetLunchesPCView(model)
});
}
public List<CookViewModel> GetCooksByLanches(ReportBindingModel model)
{
var list = new List<CookViewModel>();
var listCookIds = new List<int>();
foreach (var lunch in model.lunches)
{
var lunchProducts = lunch.LunchProducts.Keys.ToList().Select(rec => productStorage.GetElement(new ProductSearchModel { Id = rec }));
foreach (var elem in lunchProducts)
{
listCookIds.AddRange(elem.ProductCooks.Keys.ToList());
}
}
list = listCookIds.Distinct().ToList().Select(rec => cookStorage.GetElement(new CookSearchModel { Id = rec })).ToList();
return list;
}
public void saveCooksToExcel(ReportBindingModel model)
{
saveToExcel.CreateReport(new ExcelInfo()
{
FileName = model.FileName,
Title = "Список поваров:",
Cooks = GetCooksByLanches(model)
});
}
public void saveCooksToWord(ReportBindingModel model)
{
saveToWord.CreateDoc(new WordInfo()
{
FileName = model.FileName,
Title = "Список поваров",
Cooks = GetCooksByLanches(model)
});
}
}
}

View File

@ -7,7 +7,10 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="DocumentFormat.OpenXml" Version="2.20.0" />
<PackageReference Include="Magick.NET-Q16-AnyCPU" Version="13.1.2" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.0" />
<PackageReference Include="PDFsharp-MigraDoc-GDI" Version="1.50.5147" />
</ItemGroup>
<ItemGroup>
@ -15,4 +18,8 @@
<ProjectReference Include="..\CanteenDataModels\CanteenDataModels.csproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="OfficePackage\" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,66 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CanteenBusinessLogic.OfficePackage.HelperEnums;
using CanteenBusinessLogic.OfficePackage.HelperModels;
namespace CanteenBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToExcel
{
public void CreateReport(ExcelInfo info)
{
CreateExcel(info);
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = 1,
Text = info.Title,
StyleInfo = ExcelStyleInfoType.Title
});
MergeCells(new ExcelMergeParameters
{
CellFromName = "A1",
CellToName = "C1"
});
uint rowIndex = 2;
foreach (var pc in info.Cooks)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = rowIndex,
Text = pc.FIO,
StyleInfo = ExcelStyleInfoType.TextWithBroder
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "B",
RowIndex = rowIndex,
Text = "",
StyleInfo = ExcelStyleInfoType.TextWithBroder
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "C",
RowIndex = rowIndex,
Text = "",
StyleInfo = ExcelStyleInfoType.TextWithBroder
});
MergeCells(new ExcelMergeParameters
{
CellFromName = "A" + rowIndex,
CellToName = "C" + rowIndex
});
rowIndex++;
}
SaveExcel(info);
}
protected abstract void CreateExcel(ExcelInfo info);
protected abstract void InsertCellInWorksheet(ExcelCellParameters excelParams);
protected abstract void MergeCells(ExcelMergeParameters excelParams);
protected abstract void SaveExcel(ExcelInfo info);
}
}

View File

@ -0,0 +1,71 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CanteenBusinessLogic.OfficePackage.HelperEnums;
using CanteenBusinessLogic.OfficePackage.HelperModels;
namespace CanteenBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToPdf
{
public void CreateDoc(PdfInfo info)
{
CreatePdf(info);
CreateParagraph(new PdfParagraph
{
Text = info.Title,
Style = "NormalTitle"
});
CreateParagraph(new PdfParagraph
{
Text = $"с { info.DateAfter.ToShortDateString() } по { info.DateBefore.ToShortDateString() }", Style = "Normal"
});
CreateTable(new List<string> { "2cm", "2cm", "2cm", "5cm", "3cm", "3cm" });
CreateRow(new PdfRowParameters
{
Texts = new List<string> { "Дата обеда", "Стоимость обеда", "Заказ", "Повар"},
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
foreach (var lunch in info.Lunches)
{
CreateRow(new PdfRowParameters
{
Texts = new List<string> { lunch.DateCreate.ToShortDateString(), lunch.Sum.ToString(), "", ""},
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
// Вывод заказов для каждого обеда
foreach (var order in lunch.Orders)
{
CreateRow(new PdfRowParameters
{
Texts = new List<string> { "", "", order.Id.ToString(), ""},
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
// Вывод поваров для каждого заказа
foreach (var cook in order.OrderCooks)
{
CreateRow(new PdfRowParameters
{
Texts = new List<string> { "", "", "", cook.Value.FIO },
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
}
}
}
SavePdf(info);
}
protected abstract void CreatePdf(PdfInfo info);
protected abstract void CreateParagraph(PdfParagraph paragraph);
protected abstract void CreateTable(List<string> columns);
protected abstract void CreateRow(PdfRowParameters rowParameters);
protected abstract void SavePdf(PdfInfo info);
}
}

View File

@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CanteenBusinessLogic.OfficePackage.HelperEnums;
using CanteenBusinessLogic.OfficePackage.HelperModels;
namespace CanteenBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToWord
{
public void CreateDoc(WordInfo info)
{
CreateWord(info);
CreateParagraph(new WordParagraph
{
Texts = new List<(string, WordTextProperties)> { (info.Title, new WordTextProperties { Bold = true, Size = "24"}) },
TextProperties = new WordTextProperties
{
Size = "24",
JustificationType = WordJustificationType.Center
}
});
foreach (var component in info.Cooks)
{
CreateParagraph(new WordParagraph
{
Texts = new List<(string, WordTextProperties)> {("Повар: ", new WordTextProperties {Bold = true, Size = "24"}),
(component.FIO, new WordTextProperties {Bold = false, Size = "24"})},
TextProperties = new WordTextProperties
{
Size = "24",
JustificationType = WordJustificationType.Both
}
});
}
SaveWord(info);
}
protected abstract void CreateWord(WordInfo info);
protected abstract void CreateParagraph(WordParagraph paragraph);
protected abstract void SaveWord(WordInfo info);
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CanteenBusinessLogic.OfficePackage.HelperEnums
{
public enum ExcelStyleInfoType
{
Title,
Text,
TextWithBroder
}
}

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CanteenBusinessLogic.OfficePackage.HelperEnums
{
public enum PdfParagraphAlignmentType
{
Center,
Left
}
}

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CanteenBusinessLogic.OfficePackage.HelperEnums
{
public enum WordJustificationType
{
Center,
Both
}
}

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CanteenBusinessLogic.OfficePackage.HelperEnums;
namespace CanteenBusinessLogic.OfficePackage.HelperModels
{
public class ExcelCellParameters
{
public string ColumnName { get; set; }
public uint RowIndex { get; set; }
public string Text { get; set; }
public string CellReference => $"{ColumnName}{RowIndex}";
public ExcelStyleInfoType StyleInfo { get; set; }
}
}

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CanteenContracts.View;
using CanteenContracts.ViewModels;
namespace CanteenBusinessLogic.OfficePackage.HelperModels
{
public class ExcelInfo
{
public string FileName { get; set; }
public string Title { get; set; }
public List<CookViewModel> Cooks { get; set; }
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CanteenBusinessLogic.OfficePackage.HelperModels
{
public class ExcelMergeParameters
{
public string CellFromName { get; set; }
public string CellToName { get; set; }
public string Merge => $"{CellFromName}:{CellToName}";
}
}

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CanteenContracts.ViewModels;
namespace CanteenBusinessLogic.OfficePackage.HelperModels
{
public class PdfInfo
{
public string FileName { get; set; }
public string FilePath = "C:\\Reports";
public string Title { get; set; }
public DateTime DateAfter { get; set; }
public DateTime DateBefore { get; set; }
public List<ReportLunchesPCView> Lunches { get; set; }
}
}

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CanteenBusinessLogic.OfficePackage.HelperModels
{
public class PdfParagraph
{
public string Text { get; set; }
public string Style { get; set; }
}
}

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CanteenBusinessLogic.OfficePackage.HelperEnums;
namespace CanteenBusinessLogic.OfficePackage.HelperModels
{
public class PdfRowParameters
{
public List<string> Texts { get; set; }
public string Style { get; set; }
public PdfParagraphAlignmentType ParagraphAlignment { get; set; }
}
}

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CanteenContracts.View;
using CanteenContracts.ViewModels;
namespace CanteenBusinessLogic.OfficePackage.HelperModels
{
public class WordInfo
{
public string FileName { get; set; }
public string Title { get; set; }
public List<CookViewModel> Cooks { get; set; }
}
}

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CanteenBusinessLogic.OfficePackage.HelperModels
{
public class WordParagraph
{
public List<(string, WordTextProperties)> Texts { get; set; }
public WordTextProperties TextProperties { get; set; }
}
}

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CanteenBusinessLogic.OfficePackage.HelperEnums;
namespace CanteenBusinessLogic.OfficePackage.HelperModels
{
public class WordTextProperties
{
public string Size { get; set; }
public bool Bold { get; set; }
public WordJustificationType JustificationType { get; set; }
}
}

View File

@ -0,0 +1,298 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CanteenBusinessLogic.OfficePackage.HelperEnums;
using CanteenBusinessLogic.OfficePackage.HelperModels;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Office2010.Excel;
using DocumentFormat.OpenXml.Office2013.Excel;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
namespace CanteenBusinessLogic.OfficePackage.Implements
{
public class SaveToExcel : AbstractSaveToExcel
{
private SpreadsheetDocument spreadsheetDocument;
private SharedStringTablePart shareStringPart;
private Worksheet worksheet;
private static void CreateStyles(WorkbookPart workbookpart)
{
var sp = workbookpart.AddNewPart<WorkbookStylesPart>();
sp.Stylesheet = new Stylesheet();
var fonts = new Fonts() { Count = 2U, KnownFonts = true };
var fontUsual = new Font();
fontUsual.Append(new FontSize() { Val = 12D });
fontUsual.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color()
{
Theme = 1U
});
fontUsual.Append(new FontName() { Val = "Times New Roman" });
fontUsual.Append(new FontFamilyNumbering() { Val = 2 });
fontUsual.Append(new FontScheme() { Val = FontSchemeValues.Minor });
var fontTitle = new Font();
fontTitle.Append(new Bold());
fontTitle.Append(new FontSize() { Val = 14D });
fontTitle.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color()
{
Theme = 1U
});
fontTitle.Append(new FontName() { Val = "Times New Roman" });
fontTitle.Append(new FontFamilyNumbering() { Val = 2 });
fontTitle.Append(new FontScheme() { Val = FontSchemeValues.Minor });
fonts.Append(fontUsual);
fonts.Append(fontTitle);
var fills = new Fills() { Count = 2U };
var fill1 = new Fill();
fill1.Append(new PatternFill() { PatternType = PatternValues.None });
var fill2 = new Fill();
fill2.Append(new PatternFill() { PatternType = PatternValues.Gray125 });
fills.Append(fill1);
fills.Append(fill2);
var borders = new Borders() { Count = 2U };
var borderNoBorder = new Border();
borderNoBorder.Append(new LeftBorder());
borderNoBorder.Append(new RightBorder());
borderNoBorder.Append(new TopBorder());
borderNoBorder.Append(new BottomBorder());
borderNoBorder.Append(new DiagonalBorder());
var borderThin = new Border();
var leftBorder = new LeftBorder() { Style = BorderStyleValues.Thin };
leftBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color()
{
Indexed = 64U
});
var rightBorder = new RightBorder() { Style = BorderStyleValues.Thin };
rightBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color()
{
Indexed = 64U
});
var topBorder = new TopBorder() { Style = BorderStyleValues.Thin };
topBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color()
{
Indexed = 64U
});
var bottomBorder = new BottomBorder() { Style = BorderStyleValues.Thin };
bottomBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color()
{
Indexed = 64U
});
borderThin.Append(leftBorder);
borderThin.Append(rightBorder);
borderThin.Append(topBorder);
borderThin.Append(bottomBorder);
borderThin.Append(new DiagonalBorder());
borders.Append(borderNoBorder);
borders.Append(borderThin);
var cellStyleFormats = new CellStyleFormats() { Count = 1U };
var cellFormatStyle = new CellFormat()
{
NumberFormatId = 0U,
FontId = 0U,
FillId = 0U,
BorderId = 0U
};
cellStyleFormats.Append(cellFormatStyle);
var cellFormats = new CellFormats() { Count = 3U };
var cellFormatFont = new CellFormat()
{
NumberFormatId = 0U,
FontId = 0U,
FillId = 0U,
BorderId = 0U,
FormatId = 0U,
ApplyFont = true
};
var cellFormatFontAndBorder = new CellFormat()
{
NumberFormatId = 0U,
FontId = 0U,
FillId = 0U,
BorderId = 1U,
FormatId = 0U,
ApplyFont = true,
ApplyBorder = true
};
var cellFormatTitle = new CellFormat()
{
NumberFormatId = 0U,
FontId = 1U,
FillId = 0U,
BorderId = 0U,
FormatId = 0U,
Alignment = new Alignment()
{
Vertical = VerticalAlignmentValues.Center,
WrapText = true,
Horizontal = HorizontalAlignmentValues.Center
},
ApplyFont = true
};
cellFormats.Append(cellFormatFont);
cellFormats.Append(cellFormatFontAndBorder);
cellFormats.Append(cellFormatTitle);
var cellStyles = new CellStyles() { Count = 1U };
cellStyles.Append(new CellStyle()
{
Name = "Normal",
FormatId = 0U,
BuiltinId = 0U
});
var differentialFormats = new
DocumentFormat.OpenXml.Office2013.Excel.DifferentialFormats()
{ Count = 0U };
var tableStyles = new TableStyles()
{
Count = 0U,
DefaultTableStyle = "TableStyleMedium2",
DefaultPivotStyle = "PivotStyleLight16"
};
var stylesheetExtensionList = new StylesheetExtensionList();
var stylesheetExtension1 = new StylesheetExtension()
{
Uri = "{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}"
};
stylesheetExtension1.AddNamespaceDeclaration("x14", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main");
stylesheetExtension1.Append(new SlicerStyles()
{
DefaultSlicerStyle = "SlicerStyleLight1"
});
var stylesheetExtension2 = new StylesheetExtension()
{
Uri = "{9260A510-F301-46a8-8635-F512D64BE5F5}"
};
stylesheetExtension2.AddNamespaceDeclaration("x15", "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main");
stylesheetExtension2.Append(new TimelineStyles()
{
DefaultTimelineStyle = "TimeSlicerStyleLight1"
});
stylesheetExtensionList.Append(stylesheetExtension1);
stylesheetExtensionList.Append(stylesheetExtension2);
sp.Stylesheet.Append(fonts);
sp.Stylesheet.Append(fills);
sp.Stylesheet.Append(borders);
sp.Stylesheet.Append(cellStyleFormats);
sp.Stylesheet.Append(cellFormats);
sp.Stylesheet.Append(cellStyles);
sp.Stylesheet.Append(differentialFormats);
sp.Stylesheet.Append(tableStyles);
sp.Stylesheet.Append(stylesheetExtensionList);
}
private static uint GetStyleValue(ExcelStyleInfoType styleInfo)
{
return styleInfo switch
{
ExcelStyleInfoType.Title => 2U,
ExcelStyleInfoType.TextWithBroder => 1U,
ExcelStyleInfoType.Text => 0U,
_ => 0U,
};
}
protected override void CreateExcel(ExcelInfo info)
{
spreadsheetDocument = SpreadsheetDocument.Create(info.FileName, SpreadsheetDocumentType.Workbook);
// Создаем книгу (в ней хранятся листы)
var workbookpart = spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
CreateStyles(workbookpart);
// Получаем/создаем хранилище текстов для книги
shareStringPart = spreadsheetDocument.WorkbookPart.GetPartsOfType<SharedStringTablePart>().Any()?
spreadsheetDocument.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First() :
spreadsheetDocument.WorkbookPart.AddNewPart<SharedStringTablePart>();
// Создаем SharedStringTable, если его нет
if (shareStringPart.SharedStringTable == null)
{
shareStringPart.SharedStringTable = new SharedStringTable();
}
// Создаем лист в книгу
var worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
// Добавляем лист в книгу
var sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild(new Sheets());
var sheet = new Sheet()
{
Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Лист"
};
sheets.Append(sheet);
worksheet = worksheetPart.Worksheet;
}
protected override void InsertCellInWorksheet(ExcelCellParameters excelParams)
{
var sheetData = worksheet.GetFirstChild<SheetData>();
// Ищем строку, либо добавляем ее
Row row;
if (sheetData.Elements<Row>().Where(r => r.RowIndex == excelParams.RowIndex).Any())
{
row = sheetData.Elements<Row>().Where(r => r.RowIndex == excelParams.RowIndex).First();
}
else
{
row = new Row() { RowIndex = excelParams.RowIndex };
sheetData.Append(row);
}
// Ищем нужную ячейку
Cell cell;
if (row.Elements<Cell>().Where(c => c.CellReference.Value == excelParams.CellReference).Any())
{
cell = row.Elements<Cell>().Where(c => c.CellReference.Value == excelParams.CellReference).First();
}
else
{
// Все ячейки должны быть последовательно друг за другом расположены
// нужно определить, после какой вставлять
Cell refCell = null;
foreach (Cell rowCell in row.Elements<Cell>())
{
if (string.Compare(rowCell.CellReference.Value, excelParams.CellReference, true) > 0)
{
refCell = rowCell;
break;
}
}
var newCell = new Cell() { CellReference = excelParams.CellReference };
row.InsertBefore(newCell, refCell);
cell = newCell;
}
// вставляем новый текст
shareStringPart.SharedStringTable.AppendChild(new SharedStringItem(new Text(excelParams.Text)));
shareStringPart.SharedStringTable.Save();
cell.CellValue = new CellValue((shareStringPart.SharedStringTable.Elements<SharedStringItem>().Count() - 1).ToString());
cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
cell.StyleIndex = GetStyleValue(excelParams.StyleInfo);
}
protected override void MergeCells(ExcelMergeParameters excelParams)
{
MergeCells mergeCells;
if (worksheet.Elements<MergeCells>().Any())
{
mergeCells = worksheet.Elements<MergeCells>().First();
}
else
{
mergeCells = new MergeCells();
if (worksheet.Elements<CustomSheetView>().Any())
{
worksheet.InsertAfter(mergeCells, worksheet.Elements<CustomSheetView>().First());
}
else
{
worksheet.InsertAfter(mergeCells, worksheet.Elements<SheetData>().First());
}
}
var mergeCell = new MergeCell()
{
Reference = new StringValue(excelParams.Merge)
};
mergeCells.Append(mergeCell);
}
protected override void SaveExcel(ExcelInfo info)
{
spreadsheetDocument.WorkbookPart.Workbook.Save();
spreadsheetDocument.Close();
}
}
}

View File

@ -0,0 +1,87 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CanteenBusinessLogic.OfficePackage.HelperModels;
using CanteenBusinessLogic.OfficePackage.HelperEnums;
using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Tables;
using MigraDoc.Rendering;
namespace CanteenBusinessLogic.OfficePackage.Implements
{
public class SaveToPdf : AbstractSaveToPdf
{
private Document document;
private Section section;
private Table table;
private static ParagraphAlignment GetParagraphAlignment(PdfParagraphAlignmentType type)
{
return type switch
{
PdfParagraphAlignmentType.Center => ParagraphAlignment.Center,
PdfParagraphAlignmentType.Left => ParagraphAlignment.Left,
_ => ParagraphAlignment.Justify,
};
}
private static void DefineStyles(Document document)
{
var style = document.Styles["Normal"];
style.Font.Name = "Times New Roman";
style.Font.Size = 10;
style = document.Styles.AddStyle("NormalTitle", "Normal");
style.Font.Bold = true;
}
protected override void CreatePdf(PdfInfo info)
{
document = new Document();
DefineStyles(document);
section = document.AddSection();
}
protected override void CreateParagraph(PdfParagraph pdfParagraph)
{
var paragraph = section.AddParagraph(pdfParagraph.Text);
paragraph.Format.SpaceAfter = "1cm";
paragraph.Format.Alignment = ParagraphAlignment.Center;
paragraph.Style = pdfParagraph.Style;
}
protected override void CreateTable(List<string> columns)
{
table = document.LastSection.AddTable();
foreach (var elem in columns)
{
table.AddColumn(elem);
}
}
protected override void CreateRow(PdfRowParameters rowParameters)
{
var row = table.AddRow();
for (int i = 0; i < rowParameters.Texts.Count; ++i)
{
row.Cells[i].AddParagraph(rowParameters.Texts[i]);
if (!string.IsNullOrEmpty(rowParameters.Style))
{
row.Cells[i].Style = rowParameters.Style;
}
Unit borderWidth = 0.5;
row.Cells[i].Borders.Left.Width = borderWidth;
row.Cells[i].Borders.Right.Width = borderWidth;
row.Cells[i].Borders.Top.Width = borderWidth;
row.Cells[i].Borders.Bottom.Width = borderWidth;
row.Cells[i].Format.Alignment = GetParagraphAlignment(rowParameters.ParagraphAlignment);
row.Cells[i].VerticalAlignment = VerticalAlignment.Center;
}
}
protected override void SavePdf(PdfInfo info)
{
var renderer = new PdfDocumentRenderer(true)
{
Document = document
};
renderer.RenderDocument();
renderer.PdfDocument.Save(info.FileName);
}
}
}

View File

@ -0,0 +1,95 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CanteenBusinessLogic.OfficePackage.HelperEnums;
using CanteenBusinessLogic.OfficePackage.HelperModels;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
namespace CanteenBusinessLogic.OfficePackage.Implements
{
public class SaveToWord : AbstractSaveToWord
{
private WordprocessingDocument wordDocument;
private Body docBody;
private static JustificationValues GetJustificationValues(WordJustificationType type)
{
return type switch
{
WordJustificationType.Both => JustificationValues.Both,
WordJustificationType.Center => JustificationValues.Center,
_ => JustificationValues.Left
};
}
private static SectionProperties CreateSectionProperties()
{
var properties = new SectionProperties();
var pageSize = new PageSize
{
Orient = PageOrientationValues.Portrait
};
properties.AppendChild(pageSize);
return properties;
}
private static ParagraphProperties CreateParagraphProperties(WordTextProperties paragraphProperites)
{
if (paragraphProperites != null)
{
var properites = new ParagraphProperties();
properites.AppendChild(new Justification() { Val = GetJustificationValues(paragraphProperites.JustificationType) });
properites.AppendChild(new SpacingBetweenLines { LineRule = LineSpacingRuleValues.Auto });
properites.AppendChild(new Indentation());
var paragraphMarkRunProperties = new ParagraphMarkRunProperties();
if (!string.IsNullOrEmpty(paragraphProperites.Size))
{
paragraphMarkRunProperties.AppendChild(new FontSize { Val = paragraphProperites.Size });
}
properites.AppendChild(paragraphMarkRunProperties);
return properites;
}
return null;
}
protected override void CreateWord(WordInfo info)
{
wordDocument = WordprocessingDocument.Create(info.FileName, WordprocessingDocumentType.Document);
MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
mainPart.Document = new Document();
docBody = mainPart.Document.AppendChild(new Body());
}
protected override void CreateParagraph(WordParagraph paragraph)
{
if (paragraph != null)
{
var docParagraph = new Paragraph();
docParagraph.AppendChild(CreateParagraphProperties(paragraph.TextProperties));
foreach (var run in paragraph.Texts)
{
var docRun = new Run();
var properties = new RunProperties();
properties.AppendChild(new FontSize { Val = run.Item2.Size });
if (run.Item2.Bold)
{
properties.AppendChild(new Bold());
}
docRun.AppendChild(properties);
docRun.AppendChild(new Text
{
Text = run.Item1,
Space = SpaceProcessingModeValues.Preserve
});
docParagraph.AppendChild(docRun);
}
docBody.AppendChild(docParagraph);
}
}
protected override void SaveWord(WordInfo info)
{
docBody.AppendChild(CreateSectionProperties());
wordDocument.MainDocumentPart.Document.Save();
wordDocument.Close();
}
}
}

View File

@ -0,0 +1,18 @@
using CanteenContracts.View;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CanteenContracts.BindingModels
{
public class ReportBindingModel
{
public string FileName { get; set; }
public DateTime? DateAfter { get; set; }
public DateTime? DateBefore { get; set; }
public List<LunchViewModel>? lunches { get; set; }
public int VisitorId { get; set; }
}
}

View File

@ -0,0 +1,20 @@
using CanteenContracts.BindingModels;
using CanteenContracts.View;
using CanteenContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CanteenContracts.BusinessLogicsContracts
{
public interface IReportLogic
{
List<CookViewModel> GetCooksByLanches(ReportBindingModel model);
List<ReportLunchesPCView> GetLunchesPCView(ReportBindingModel model);
void saveLunchesToPdfFile(ReportBindingModel model);
void saveCooksToWord(ReportBindingModel model);
void saveCooksToExcel(ReportBindingModel model);
}
}

View File

@ -1,5 +1,6 @@
using CanteenDataModels.Enums;
using CanteenDataModels.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@ -26,5 +27,11 @@ namespace CanteenContracts.View
public DateTime? DateImplement { get; set; }
public Dictionary<int, (IProductModel, int)> LunchProducts { get; set; }
public Dictionary<int, IOrderModel> LunchOrders { get; set; }
public LunchViewModel() { }
[JsonConstructor]
public LunchViewModel(Dictionary<int, OrderViewModel> LunchOrders)
{
this.LunchOrders = LunchOrders.ToDictionary(x => x.Key, x => x.Value as IOrderModel);
}
}
}

View File

@ -0,0 +1,17 @@
using CanteenContracts.View;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CanteenContracts.ViewModels
{
public class ReportLunchesPCView
{
public DateTime DateCreate { get; set; }
public int Sum { get; set; }
public List<OrderViewModel> Orders { get; set; }
public List<CookViewModel> Cooks { get; set; }
}
}

View File

@ -54,10 +54,12 @@ namespace CanteenDatabaseImplement.Implements
using var context = new CanteenDatabase();
return context.Lunches
.Include(x => x.Products)
.ThenInclude(x => x.Product)
.Include(x => x.Orders)
.ThenInclude(x => x.Order)
.Include(x => x.Products)
.ThenInclude(x => x.Product)
.ThenInclude(x => x.Cooks)
.ThenInclude(x => x.Cook)
.Where(x =>
(x.DateCreate >= model.DateFrom && x.DateImplement <= model.DateTo) ||
(model.Id.HasValue && x.Id == model.Id) ||
@ -68,10 +70,10 @@ namespace CanteenDatabaseImplement.Implements
{
using var context = new CanteenDatabase();
return context.Lunches
.Include(x => x.Products)
.ThenInclude(x => x.Product)
.Include(x => x.Orders)
.ThenInclude(x => x.Order)
.Include(x => x.Products)
.ThenInclude(x => x.Product)
.Select(x => x.GetViewModel).ToList();
}
public LunchViewModel? Insert(LunchBindingModel model)

View File

@ -21,9 +21,9 @@ namespace CanteenDatabaseImplement.Models
[Required]
public string Position { get; private set; } = string.Empty;
[ForeignKey("CookId")]
public virtual List<ProductCook> Products { get; set; } = new();
public virtual List<ProductCook> Products { get; set; }
[ForeignKey("CookId")]
public virtual List<OrderCook> Orders { get; set; } = new();
public virtual List<OrderCook> Orders { get; set; }
public virtual Manager Manager { get; set; }
public static Cook Create(CookBindingModel model)

View File

@ -18,6 +18,6 @@ namespace CanteenDatabaseImplement.Models
[Required]
public int CountProducts { get; set; }
public virtual Dish Dish { get; set; }
public virtual Product Product { get; set; } = new();
public virtual Product Product { get; set; }
}
}

View File

@ -102,7 +102,8 @@ namespace CanteenDatabaseImplement.Models
Status = Status,
DateCreate = DateCreate,
DateImplement = DateImplement,
LunchProducts = LunchProducts
LunchProducts = LunchProducts,
LunchOrders = LunchOrders
};
public void UpdateProducts(CanteenDatabase context, LunchBindingModel model)

View File

@ -16,8 +16,8 @@ namespace CanteenDatabaseImplement.Models
[Required]
public int OrderId { get; set; }
[Required]
public virtual Lunch Lunch { get; set; } = new();
public virtual Order Order { get; set; } = new();
public virtual Lunch Lunch { get; set; }
public virtual Order Order { get; set; }
public LunchOrderViewModel GetViewModel => new()
{
Id = Id,

View File

@ -19,8 +19,8 @@ namespace CanteenDatabaseImplement.Models
[Required]
public int CountProducts { get; set; }
public virtual Lunch Lunch { get; set; } = new();
public virtual Lunch Lunch { get; set; }
public virtual Product Product { get; set; } = new();
public virtual Product Product { get; set; }
}
}

View File

@ -26,11 +26,11 @@ namespace CanteenDatabaseImplement.Models
public int Id { get; private set; }
[ForeignKey("ManagerId")]
public virtual List<Cook> Cooks { get; set; } = new();
public virtual List<Cook> Cooks { get; set; }
[ForeignKey("ManagerId")]
public virtual List<Product> Products { get; set; } = new();
public virtual List<Product> Products { get; set; }
[ForeignKey("ManagerId")]
public virtual List<Dish> Dishes { get; set; } = new();
public virtual List<Dish> Dishes { get; set; }
public static Manager? Create(ManagerBindingModel model)
{
if (model == null)

View File

@ -16,8 +16,8 @@ namespace CanteenDatabaseImplement.Models
public int CookId { get; set; }
[Required]
public int OrderId { get; set; }
public virtual Order Order { get; set; } = new();
public virtual Cook Cook { get; set; } = new();
public virtual Order Order { get; set; }
public virtual Cook Cook { get; set; }
public OrderCookViewModel GetViewModel => new()
{
Id = Id,

View File

@ -16,7 +16,7 @@ namespace CanteenDatabaseImplement.Models
public int TablewareId { get; set; }
[Required]
public int CountTablewares { get; set; }
public virtual Order Order { get; set; } = new();
public virtual Tableware Tableware { get; set; } = new();
public virtual Order Order { get; set; }
public virtual Tableware Tableware { get; set; }
}
}

View File

@ -40,9 +40,9 @@ namespace CanteenDatabaseImplement.Models
[ForeignKey("ProductId")]
public virtual List<ProductCook> Cooks { get; set; } = new();
[ForeignKey("ProductId")]
public virtual List<LunchProduct> Lunches { get; set; } = new();
public virtual List<LunchProduct> Lunches { get; set; }
[ForeignKey("ProductId")]
public virtual List<DishProduct> Dishes { get; set; } = new();
public virtual List<DishProduct> Dishes { get; set; }
public virtual Manager Manager { get; set; }
public static Product Create(CanteenDatabase context, ProductBindingModel model)

View File

@ -18,8 +18,8 @@ namespace CanteenDatabaseImplement.Models
[Required]
public int CookId { get; set; }
public virtual Product Product { get; set; } = new();
public virtual Product Product { get; set; }
public virtual Cook Cook { get; set; } = new();
public virtual Cook Cook { get; set; }
}
}

View File

@ -20,7 +20,7 @@ namespace CanteenDatabaseImplement.Models
[Required]
public string TablewareName { get; private set; } = string.Empty;
[ForeignKey("TablewareId")]
public virtual List<OrderTableware> Orders { get; set; } = new();
public virtual List<OrderTableware> Orders { get; set; }
public virtual Visitor Visitor { get; set; }
public static Tableware? Create(TablewareBindingModel model)
{

View File

@ -21,8 +21,9 @@ namespace CanteenRestApi.Controllers
private readonly IOrderLogic _order;
private readonly ILunchLogic _lunch;
private readonly IGraphicLogic _gl;
private readonly IReportLogic _reportLogic;
public MainController(ILogger<MainController> logger, ICookLogic cook, IDishLogic dish, IProductLogic product, ITablewareLogic tableware, IOrderLogic order, IGraphicLogic gl, ILunchLogic lunch)
public MainController(ILogger<MainController> logger, IReportLogic reportLogic, ICookLogic cook, IDishLogic dish, IProductLogic product, ITablewareLogic tableware, IOrderLogic order, IGraphicLogic gl, ILunchLogic lunch)
{
_logger = logger;
_cook = cook;
@ -32,6 +33,76 @@ namespace CanteenRestApi.Controllers
_order = order;
_gl = gl;
_lunch = lunch;
_reportLogic = reportLogic;
}
[HttpPost]
public void SavePDF(ReportBindingModel model)
{
try
{
_reportLogic.saveLunchesToPdfFile(new ReportBindingModel()
{
DateAfter = model.DateAfter,
DateBefore = model.DateBefore,
FileName = model.FileName,
VisitorId = model.VisitorId,
lunches = _lunch.ReadList(new LunchSearchModel { VisitorId = model.VisitorId}),
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Error during loading list of bouquets");
throw;
}
}
[HttpPost]
public IActionResult SaveXSL(ReportBindingModel model)
{
try
{
var excelFileName = $"{model.FileName}.xlsx";
var excelFilePath = excelFileName;
_reportLogic.saveCooksToExcel(new ReportBindingModel()
{
DateAfter = model.DateAfter,
DateBefore = model.DateBefore,
FileName = excelFilePath,
VisitorId = model.VisitorId,
lunches = _lunch.ReadList(new LunchSearchModel { VisitorId = model.VisitorId }),
});
byte[] fileBytes = System.IO.File.ReadAllBytes(excelFilePath);
return File(fileBytes, "application/octet-stream", excelFileName);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error during loading list of bouquets");
throw;
}
}
[HttpPost]
public void SaveWORD(ReportBindingModel model)
{
try
{
_reportLogic.saveCooksToWord(new ReportBindingModel()
{
DateAfter = model.DateAfter,
DateBefore = model.DateBefore,
FileName = model.FileName,
VisitorId = model.VisitorId,
lunches = _lunch.ReadList(new LunchSearchModel { VisitorId = model.VisitorId }),
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Error during loading list of bouquets");
throw;
}
}
[HttpGet]

View File

@ -1,5 +1,7 @@
using CanteenBusinessLogic.BusinessLogics;
using CanteenBusinessLogic.OfficePackage;
using CanteenBusinessLogic.OfficePackage.Implements;
using CanteenContracts.BusinessLogicsContracts;
using CanteenContracts.StoragesContracts;
using CanteenDatabaseImplement.Implements;
@ -28,6 +30,11 @@ builder.Services.AddTransient<ITablewareLogic, TablewareLogic>();
builder.Services.AddTransient<IOrderLogic, OrderLogic>();
builder.Services.AddTransient<IGraphicLogic, GraphicLogic>();
builder.Services.AddTransient<ILunchLogic, LunchLogic>();
builder.Services.AddTransient<IReportLogic, ReportLogic>();
builder.Services.AddTransient<AbstractSaveToPdf, SaveToPdf>();
builder.Services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
builder.Services.AddTransient<AbstractSaveToWord, SaveToWord>();
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -449,11 +449,11 @@ namespace CanteenVisitorApp.Controllers
{
throw new Exception("Количество продукта должно быть больше 0");
}
var product = APIClient.GetRequest<ProductViewModel>($"api/main/getproduct?Id={selectedProduct}");
APIClient.PostRequest("api/main/lunchaddproducts", Tuple.Create
(
new LunchBindingModel { Id = selectedLunch },
new ProductBindingModel { Id = selectedProduct },
new ProductBindingModel { Id = selectedProduct, Price = product.Price },
count
));
Response.Redirect("Lunches");
@ -498,5 +498,41 @@ namespace CanteenVisitorApp.Controllers
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
[HttpGet]
public IActionResult Report()
{
return View(new ReportBindingModel());
}
[HttpPost]
public void ReportPdf(ReportBindingModel model)
{
model.VisitorId = APIClient.Visitor.Id;
APIClient.PostRequest("api/main/SavePDF", model);
Response.Redirect("Index");
}
[HttpPost]
public void ReportXsl(ReportBindingModel model)
{
model.VisitorId = APIClient.Visitor.Id;
APIClient.PostRequest("api/main/SaveXSL", model);
Response.Redirect("Index");
}
[HttpPost]
public void ReportWord(ReportBindingModel model)
{
model.VisitorId = APIClient.Visitor.Id;
APIClient.PostRequest("api/main/SaveWORD", model);
Response.Redirect("Index");
}
[HttpPost]
public void ReportEmail(ReportBindingModel model)
{
APIClient.PostRequest("api/main/SaveEMAIL", model);
Response.Redirect("Index");
}
}
}

View File

@ -0,0 +1,31 @@
@using CanteenContracts.BindingModels;
@model ReportBindingModel
@{
ViewBag.Title = "Report";
}
<h2>Generate Report</h2>
@using (Html.BeginForm("Report", "Home", FormMethod.Post))
{
<div>
@Html.LabelFor(m => m.FileName)
@Html.TextBoxFor(m => m.FileName)
</div>
<div>
@Html.LabelFor(m => m.DateAfter)
@Html.TextBoxFor(m => m.DateAfter, new { type = "date" })
</div>
<div>
@Html.LabelFor(m => m.DateBefore)
@Html.TextBoxFor(m => m.DateBefore, new { type = "date" })
</div>
<button type="submit" formaction="@Url.Action("ReportPdf", "Home")">Сохранить в pfd</button>
<button type="submit" formaction="@Url.Action("ReportEmail", "Home")">Отправить по почте</button>
<button type="submit" formaction="@Url.Action("ReportXsl", "Home")">Сохранить в excel</button>
<button type="submit" formaction="@Url.Action("ReportWord", "Home")">Сохранить в word</button>
}

View File

@ -28,6 +28,9 @@
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Tablewares">Приборы</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Report">Отчеты</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Enter">Войти</a>
</li>