diff --git a/Course/BusinessLogic/BusinessLogic.csproj b/Course/BusinessLogic/BusinessLogic.csproj index 75a93ab..ae71d8d 100644 --- a/Course/BusinessLogic/BusinessLogic.csproj +++ b/Course/BusinessLogic/BusinessLogic.csproj @@ -7,7 +7,9 @@ + + diff --git a/Course/BusinessLogic/OfficePackage/AbstractSaveToExcel.cs b/Course/BusinessLogic/OfficePackage/AbstractSaveToExcel.cs new file mode 100644 index 0000000..22b8e14 --- /dev/null +++ b/Course/BusinessLogic/OfficePackage/AbstractSaveToExcel.cs @@ -0,0 +1,84 @@ +using BusinessLogic.OfficePackage.HelperEnums; +using BusinessLogic.OfficePackage.HelperModels; + +namespace BusinessLogic.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.DressComponents) + { + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = rowIndex, + Text = pc.DressName, + StyleInfo = ExcelStyleInfoType.Text + }); + rowIndex++; + + foreach (var (Dress, Count) in pc.Components) + { + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "B", + RowIndex = rowIndex, + Text = Dress, + StyleInfo = ExcelStyleInfoType.TextWithBorder + }); + + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "C", + RowIndex = rowIndex, + Text = Count.ToString(), + StyleInfo = ExcelStyleInfoType.TextWithBorder + }); + + rowIndex++; + } + + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = rowIndex, + Text = "Итого", + StyleInfo = ExcelStyleInfoType.Text + }); + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "C", + RowIndex = rowIndex, + Text = pc.TotalCount.ToString(), + StyleInfo = ExcelStyleInfoType.Text + }); + 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); + } +} diff --git a/Course/BusinessLogic/OfficePackage/AbstractSaveToPdf.cs b/Course/BusinessLogic/OfficePackage/AbstractSaveToPdf.cs new file mode 100644 index 0000000..71043d9 --- /dev/null +++ b/Course/BusinessLogic/OfficePackage/AbstractSaveToPdf.cs @@ -0,0 +1,48 @@ +using BusinessLogic.OfficePackage.HelperEnums; +using BusinessLogic.OfficePackage.HelperModels; +using System.Collections.Generic; +using System.Linq; + +namespace BusinessLogic.OfficePackage +{ + public abstract class AbstractSaveToPdf + { + public void CreateDoc(PdfInfo info) + { + CreatePdf(info); + CreateParagraph(new PdfParagraph { Text = info.Title, Style = "NormalTitle", ParagraphAlignment = PdfParagraphAlignmentType.Center }); + CreateParagraph(new PdfParagraph { Text = $"с {info.DateFrom.ToShortDateString()} по {info.DateTo.ToShortDateString()}", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Center }); + + CreateTable(new List { "2cm", "3cm", "6cm", "4cm", "3cm" }); + + CreateRow(new PdfRowParameters + { + Texts = new List { "Номер", "Дата заказа", "Изделие", "Статус", "Сумма" }, + Style = "NormalTitle", + ParagraphAlignment = PdfParagraphAlignmentType.Center + }); + + /* foreach (var order in info.Orders) + { + CreateRow(new PdfRowParameters + { + Texts = new List { order.Id.ToString(), order.DateCreate.ToShortDateString(), order.DressName, order.Status.ToString(), order.Sum.ToString() }, + Style = "Normal", + ParagraphAlignment = PdfParagraphAlignmentType.Left + }); + } + CreateParagraph(new PdfParagraph { Text = $"Итого: {info.Orders.Sum(x => x.Sum)}\t", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Right }); +*/ + SavePdf(info); + } + protected abstract void CreatePdf(PdfInfo info); + + protected abstract void CreateParagraph(PdfParagraph paragraph); + + protected abstract void CreateTable(List columns); + + protected abstract void CreateRow(PdfRowParameters rowParameters); + + protected abstract void SavePdf(PdfInfo info); + } +} diff --git a/Course/BusinessLogic/OfficePackage/AbstractSaveToWord.cs b/Course/BusinessLogic/OfficePackage/AbstractSaveToWord.cs new file mode 100644 index 0000000..8841686 --- /dev/null +++ b/Course/BusinessLogic/OfficePackage/AbstractSaveToWord.cs @@ -0,0 +1,46 @@ +using BusinessLogic.OfficePackage.HelperEnums; +using BusinessLogic.OfficePackage.HelperModels; + +namespace BusinessLogic.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.Both + } + }); + /*foreach (var dress in info.Dresses) + { + CreateParagraph(new WordParagraph + { + Texts = new List<(string, WordTextProperties)> + { + ($"{dress.DressName} - ", new WordTextProperties { Size = "24", Bold = true}), + (dress.Price.ToString(), new WordTextProperties { 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); + } +} diff --git a/Course/BusinessLogic/OfficePackage/HelperEnums/ExcelStyleInfoType.cs b/Course/BusinessLogic/OfficePackage/HelperEnums/ExcelStyleInfoType.cs new file mode 100644 index 0000000..8013cb4 --- /dev/null +++ b/Course/BusinessLogic/OfficePackage/HelperEnums/ExcelStyleInfoType.cs @@ -0,0 +1,10 @@ + +namespace BusinessLogic.OfficePackage.HelperEnums +{ + public enum ExcelStyleInfoType + { + Title, + Text, + TextWithBorder + } +} diff --git a/Course/BusinessLogic/OfficePackage/HelperEnums/PdfParagraphAlignmentType.cs b/Course/BusinessLogic/OfficePackage/HelperEnums/PdfParagraphAlignmentType.cs new file mode 100644 index 0000000..8895a3d --- /dev/null +++ b/Course/BusinessLogic/OfficePackage/HelperEnums/PdfParagraphAlignmentType.cs @@ -0,0 +1,9 @@ +namespace BusinessLogic.OfficePackage.HelperEnums +{ + public enum PdfParagraphAlignmentType + { + Center, + Left, + Right + } +} diff --git a/Course/BusinessLogic/OfficePackage/HelperEnums/WordJustificationType.cs b/Course/BusinessLogic/OfficePackage/HelperEnums/WordJustificationType.cs new file mode 100644 index 0000000..e459beb --- /dev/null +++ b/Course/BusinessLogic/OfficePackage/HelperEnums/WordJustificationType.cs @@ -0,0 +1,8 @@ +namespace BusinessLogic.OfficePackage.HelperEnums +{ + public enum WordJustificationType + { + Center, + Both + } +} diff --git a/Course/BusinessLogic/OfficePackage/HelperModels/ExcelCellParameters.cs b/Course/BusinessLogic/OfficePackage/HelperModels/ExcelCellParameters.cs new file mode 100644 index 0000000..ff71053 --- /dev/null +++ b/Course/BusinessLogic/OfficePackage/HelperModels/ExcelCellParameters.cs @@ -0,0 +1,14 @@ + +using BusinessLogic.OfficePackage.HelperEnums; + +namespace BusinessLogic.OfficePackage.HelperModels +{ + public class ExcelCellParameters + { + public string ColumnName { get; set; } = string.Empty; + public uint RowIndex { get; set; } + public string Text { get; set; } = string.Empty; + public string CellReference => $"{ColumnName}{RowIndex}"; + public ExcelStyleInfoType StyleInfo { get; set; } + } +} diff --git a/Course/BusinessLogic/OfficePackage/HelperModels/ExcelInfo.cs b/Course/BusinessLogic/OfficePackage/HelperModels/ExcelInfo.cs new file mode 100644 index 0000000..e04c2a4 --- /dev/null +++ b/Course/BusinessLogic/OfficePackage/HelperModels/ExcelInfo.cs @@ -0,0 +1,11 @@ +using Contracts.ViewModels; + +namespace BusinessLogic.OfficePackage.HelperModels +{ + public class ExcelInfo + { + public string FileName { get; set; } = string.Empty; + public string Title { get; set; } = string.Empty; + //public List DressComponents { get; set; } = new(); + } +} diff --git a/Course/BusinessLogic/OfficePackage/HelperModels/ExcelMergeParameters.cs b/Course/BusinessLogic/OfficePackage/HelperModels/ExcelMergeParameters.cs new file mode 100644 index 0000000..e14eb60 --- /dev/null +++ b/Course/BusinessLogic/OfficePackage/HelperModels/ExcelMergeParameters.cs @@ -0,0 +1,10 @@ + +namespace BusinessLogic.OfficePackage.HelperModels +{ + public class ExcelMergeParameters + { + public string CellFromName { get; set; } = string.Empty; + public string CellToName { get; set; } = string.Empty; + public string Merge => $"{CellFromName}:{CellToName}"; + } +} diff --git a/Course/BusinessLogic/OfficePackage/HelperModels/PdfInfo.cs b/Course/BusinessLogic/OfficePackage/HelperModels/PdfInfo.cs new file mode 100644 index 0000000..dfc02f9 --- /dev/null +++ b/Course/BusinessLogic/OfficePackage/HelperModels/PdfInfo.cs @@ -0,0 +1,13 @@ +using Contracts.ViewModels; + +namespace BusinessLogic.OfficePackage.HelperModels +{ + public class PdfInfo + { + public string FileName { get; set; } = string.Empty; + public string Title { get; set; } = string.Empty; + public DateTime DateFrom { get; set; } + public DateTime DateTo { get; set; } + //public List Orders { get; set; } = new(); + } +} diff --git a/Course/BusinessLogic/OfficePackage/HelperModels/PdfParagraph.cs b/Course/BusinessLogic/OfficePackage/HelperModels/PdfParagraph.cs new file mode 100644 index 0000000..c021855 --- /dev/null +++ b/Course/BusinessLogic/OfficePackage/HelperModels/PdfParagraph.cs @@ -0,0 +1,11 @@ +using BusinessLogic.OfficePackage.HelperEnums; + +namespace BusinessLogic.OfficePackage.HelperModels +{ + public class PdfParagraph + { + public string Text { get; set; } = string.Empty; + public string Style { get; set; } = string.Empty; + public PdfParagraphAlignmentType ParagraphAlignment { get; set; } + } +} diff --git a/Course/BusinessLogic/OfficePackage/HelperModels/PdfRowParameters.cs b/Course/BusinessLogic/OfficePackage/HelperModels/PdfRowParameters.cs new file mode 100644 index 0000000..eb25d67 --- /dev/null +++ b/Course/BusinessLogic/OfficePackage/HelperModels/PdfRowParameters.cs @@ -0,0 +1,11 @@ +using BusinessLogic.OfficePackage.HelperEnums; + +namespace BusinessLogic.OfficePackage.HelperModels +{ + public class PdfRowParameters + { + public List Texts { get; set; } = new(); + public string Style { get; set; } = string.Empty; + public PdfParagraphAlignmentType ParagraphAlignment { get; set; } + } +} diff --git a/Course/BusinessLogic/OfficePackage/HelperModels/WordInfo.cs b/Course/BusinessLogic/OfficePackage/HelperModels/WordInfo.cs new file mode 100644 index 0000000..14fabfc --- /dev/null +++ b/Course/BusinessLogic/OfficePackage/HelperModels/WordInfo.cs @@ -0,0 +1,9 @@ +namespace BusinessLogic.OfficePackage.HelperModels +{ + public class WordInfo + { + public string FileName { get; set; } = string.Empty; + public string Title { get; set; } = string.Empty; + //public List Dresses { get; set; } = new(); + } +} diff --git a/Course/BusinessLogic/OfficePackage/HelperModels/WordParagraph.cs b/Course/BusinessLogic/OfficePackage/HelperModels/WordParagraph.cs new file mode 100644 index 0000000..0b50a51 --- /dev/null +++ b/Course/BusinessLogic/OfficePackage/HelperModels/WordParagraph.cs @@ -0,0 +1,9 @@ + +namespace BusinessLogic.OfficePackage.HelperModels +{ + public class WordParagraph + { + public List<(string, WordTextProperties)> Texts { get; set; } = new(); + public WordTextProperties? TextProperties { get; set; } + } +} diff --git a/Course/BusinessLogic/OfficePackage/HelperModels/WordTextProperties.cs b/Course/BusinessLogic/OfficePackage/HelperModels/WordTextProperties.cs new file mode 100644 index 0000000..7eea2f6 --- /dev/null +++ b/Course/BusinessLogic/OfficePackage/HelperModels/WordTextProperties.cs @@ -0,0 +1,11 @@ +using BusinessLogic.OfficePackage.HelperEnums; + +namespace BusinessLogic.OfficePackage.HelperModels +{ + public class WordTextProperties + { + public string Size { get; set; } = string.Empty; + public bool Bold { get; set; } + public WordJustificationType JustificationType { get; set; } + } +} diff --git a/Course/BusinessLogic/OfficePackage/Implements/SaveToExcel.cs b/Course/BusinessLogic/OfficePackage/Implements/SaveToExcel.cs new file mode 100644 index 0000000..3d431d6 --- /dev/null +++ b/Course/BusinessLogic/OfficePackage/Implements/SaveToExcel.cs @@ -0,0 +1,283 @@ +using BusinessLogic.OfficePackage.HelperModels; +using BusinessLogic.OfficePackage.HelperEnums; +using DocumentFormat.OpenXml.Office2010.Excel; +using DocumentFormat.OpenXml.Office2013.Excel; +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Spreadsheet; +using DocumentFormat.OpenXml; + +namespace BusinessLogic.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(); + 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.TextWithBorder => 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().Any() + ? _spreadsheetDocument.WorkbookPart.GetPartsOfType().First() + : _spreadsheetDocument.WorkbookPart.AddNewPart(); + + // Создаем SharedStringTable, если его нет + if (_shareStringPart.SharedStringTable == null) + { + _shareStringPart.SharedStringTable = new SharedStringTable(); + } + + // Создаем лист в книгу + var worksheetPart = workbookpart.AddNewPart(); + 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) + { + if (_worksheet == null || _shareStringPart == null) + { + return; + } + var sheetData = _worksheet.GetFirstChild(); + if (sheetData == null) + { + return; + } + + // Ищем строку, либо добавляем ее + Row row; + if (sheetData.Elements().Where(r => r.RowIndex! == excelParams.RowIndex).Any()) + { + row = sheetData.Elements().Where(r => r.RowIndex! == excelParams.RowIndex).First(); + } + else + { + row = new Row() { RowIndex = excelParams.RowIndex }; + sheetData.Append(row); + } + + // Ищем нужную ячейку + Cell cell; + if (row.Elements().Where(c => c.CellReference!.Value == excelParams.CellReference).Any()) + { + cell = row.Elements().Where(c => c.CellReference!.Value == excelParams.CellReference).First(); + } + else + { + // Все ячейки должны быть последовательно друг за другом расположены + // нужно определить, после какой вставлять + Cell? refCell = null; + foreach (Cell rowCell in row.Elements()) + { + 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().Count() - 1).ToString()); + cell.DataType = new EnumValue(CellValues.SharedString); + cell.StyleIndex = GetStyleValue(excelParams.StyleInfo); + } + + protected override void MergeCells(ExcelMergeParameters excelParams) + { + if (_worksheet == null) + { + return; + } + MergeCells mergeCells; + + if (_worksheet.Elements().Any()) + { + mergeCells = _worksheet.Elements().First(); + } + else + { + mergeCells = new MergeCells(); + + if (_worksheet.Elements().Any()) + { + _worksheet.InsertAfter(mergeCells, _worksheet.Elements().First()); + } + else + { + _worksheet.InsertAfter(mergeCells, _worksheet.Elements().First()); + } + } + + var mergeCell = new MergeCell() + { + Reference = new StringValue(excelParams.Merge) + }; + mergeCells.Append(mergeCell); + } + + protected override void SaveExcel(ExcelInfo info) + { + if (_spreadsheetDocument == null) + { + return; + } + _spreadsheetDocument.WorkbookPart!.Workbook.Save(); + _spreadsheetDocument.Dispose(); + } + } +} diff --git a/Course/BusinessLogic/OfficePackage/Implements/SaveToPdf.cs b/Course/BusinessLogic/OfficePackage/Implements/SaveToPdf.cs new file mode 100644 index 0000000..15b36ac --- /dev/null +++ b/Course/BusinessLogic/OfficePackage/Implements/SaveToPdf.cs @@ -0,0 +1,114 @@ +using BusinessLogic.OfficePackage.HelperEnums; +using BusinessLogic.OfficePackage.HelperModels; +using MigraDoc.DocumentObjectModel; +using MigraDoc.DocumentObjectModel.Tables; +using MigraDoc.Rendering; + +namespace BusinessLogic.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, + PdfParagraphAlignmentType.Right => ParagraphAlignment.Right, + _ => ParagraphAlignment.Justify, + }; + } + + /// + /// Создание стилей для документа + /// + /// + private static void DefineStyles(Document document) + { + var style = document.Styles["Normal"]; + style.Font.Name = "Times New Roman"; + style.Font.Size = 14; + + 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) + { + if (_section == null) + { + return; + } + var paragraph = _section.AddParagraph(pdfParagraph.Text); + paragraph.Format.SpaceAfter = "1cm"; + paragraph.Format.Alignment = GetParagraphAlignment(pdfParagraph.ParagraphAlignment); + paragraph.Style = pdfParagraph.Style; + } + + protected override void CreateTable(List columns) + { + if (_document == null) + { + return; + } + _table = _document.LastSection.AddTable(); + + foreach (var elem in columns) + { + _table.AddColumn(elem); + } + } + + protected override void CreateRow(PdfRowParameters rowParameters) + { + if (_table == null) + { + return; + } + 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); + } + } +} \ No newline at end of file diff --git a/Course/BusinessLogic/OfficePackage/Implements/SaveToWord.cs b/Course/BusinessLogic/OfficePackage/Implements/SaveToWord.cs new file mode 100644 index 0000000..aac8665 --- /dev/null +++ b/Course/BusinessLogic/OfficePackage/Implements/SaveToWord.cs @@ -0,0 +1,121 @@ +using BusinessLogic.OfficePackage.HelperEnums; +using BusinessLogic.OfficePackage.HelperModels; +using DocumentFormat.OpenXml; +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Wordprocessing; + +namespace BusinessLogic.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? paragraphProperties) + { + if (paragraphProperties == null) + { + return null; + } + + var properties = new ParagraphProperties(); + + properties.AppendChild(new Justification() + { + Val = GetJustificationValues(paragraphProperties.JustificationType) + }); + + properties.AppendChild(new SpacingBetweenLines + { + LineRule = LineSpacingRuleValues.Auto + }); + + properties.AppendChild(new Indentation()); + + var paragraphMarkRunProperties = new ParagraphMarkRunProperties(); + if (!string.IsNullOrEmpty(paragraphProperties.Size)) + { + paragraphMarkRunProperties.AppendChild(new FontSize { Val = paragraphProperties.Size }); + } + properties.AppendChild(paragraphMarkRunProperties); + + return properties; + } + + 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 (_docBody == null || paragraph == null) + { + return; + } + 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) + { + if (_docBody == null || _wordDocument == null) + { + return; + } + _docBody.AppendChild(CreateSectionProperties()); + + _wordDocument.MainDocumentPart!.Document.Save(); + + _wordDocument.Dispose(); + } + } +} diff --git a/Course/Contracts/SearchModels/ImplementerSearchModel.cs b/Course/Contracts/SearchModels/ImplementerSearchModel.cs index 4fba103..deb4f46 100644 --- a/Course/Contracts/SearchModels/ImplementerSearchModel.cs +++ b/Course/Contracts/SearchModels/ImplementerSearchModel.cs @@ -10,5 +10,6 @@ namespace Contracts.SearchModels { public int? Id { get; set; } public string? Login { get; set; } + public string? Password { get; set; } } } diff --git a/Course/Contracts/ViewModels/ProductViewModel.cs b/Course/Contracts/ViewModels/ProductViewModel.cs index 6ac9be4..8598255 100644 --- a/Course/Contracts/ViewModels/ProductViewModel.cs +++ b/Course/Contracts/ViewModels/ProductViewModel.cs @@ -17,6 +17,7 @@ namespace Contracts.ViewModels public double Cost { get; set; } public int UserId { get; set; } public int? MachineId { get; set; } + public string? MachineName { get; set; } public Dictionary DetailProducts { get; set; } = new(); } } diff --git a/Course/DatabaseImplement/DatabaseImplement.csproj b/Course/DatabaseImplement/DatabaseImplement.csproj index b4206ce..dfc5a94 100644 --- a/Course/DatabaseImplement/DatabaseImplement.csproj +++ b/Course/DatabaseImplement/DatabaseImplement.csproj @@ -7,6 +7,7 @@ + diff --git a/Course/DatabaseImplement/Implements/DetailStorage.cs b/Course/DatabaseImplement/Implements/DetailStorage.cs index 2260591..2b888e5 100644 --- a/Course/DatabaseImplement/Implements/DetailStorage.cs +++ b/Course/DatabaseImplement/Implements/DetailStorage.cs @@ -22,7 +22,7 @@ namespace DatabaseImplement.Implements public DetailViewModel? GetElement(DetailSearchModel model) { using var context = new FactoryGoWorkDatabase(); - return context.Details.FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name) && x.Name.Contains(model.Name)) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; + return context.Details.FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name) && x.Name.Equals(model.Name)) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; } public List GetFilteredList(DetailSearchModel model) @@ -33,9 +33,9 @@ namespace DatabaseImplement.Implements } using var context = new FactoryGoWorkDatabase(); if (model.DateFrom.HasValue) - return context.Details.Where(x => x.UserId == model.Id).Where(x => x.DateCreate < model.DateTo && x.DateCreate > model.DateFrom).Select(x => x.GetViewModel).ToList(); + return context.Details.Where(x => x.UserId == model.UserId).Where(x => x.DateCreate <= model.DateTo && x.DateCreate >= model.DateFrom).Select(x => x.GetViewModel).ToList(); else - return context.Details.Where(x => x.UserId == model.Id).Select(x => x.GetViewModel).ToList(); + return context.Details.Where(x => x.UserId == model.UserId).Select(x => x.GetViewModel).ToList(); } diff --git a/Course/DatabaseImplement/Implements/ImplementerStorage.cs b/Course/DatabaseImplement/Implements/ImplementerStorage.cs index c96278d..05db08c 100644 --- a/Course/DatabaseImplement/Implements/ImplementerStorage.cs +++ b/Course/DatabaseImplement/Implements/ImplementerStorage.cs @@ -23,7 +23,7 @@ namespace DatabaseImplement.Implements { if (!model.Id.HasValue && string.IsNullOrEmpty(model.Login)) { return null; } using var context = new FactoryGoWorkDatabase(); - return context.Implementers.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id) || (!string.IsNullOrEmpty(model.Login) && x.Login.Equals(model.Login)))?.GetViewModel; ; + return context.Implementers.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id) || (!string.IsNullOrEmpty(model.Login) && !string.IsNullOrEmpty(model.Password) && x.Login.Equals(model.Login) && x.Password.Equals(model.Password)))?.GetViewModel; ; } public List GetFilteredList(ImplementerSearchModel model) diff --git a/Course/DatabaseImplement/Implements/ProductStorage.cs b/Course/DatabaseImplement/Implements/ProductStorage.cs index 93ad8c6..da482e2 100644 --- a/Course/DatabaseImplement/Implements/ProductStorage.cs +++ b/Course/DatabaseImplement/Implements/ProductStorage.cs @@ -24,7 +24,7 @@ namespace DatabaseImplement.Implements public ProductViewModel? GetElement(ProductSearchModel model) { using var context = new FactoryGoWorkDatabase(); - return context.Products.Include(p => p.Details).ThenInclude(p => p.Detail).FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name) && x.Name.Contains(model.Name)) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; + return context.Products.Include(p => p.Details).ThenInclude(p => p.Detail).Include(p => p.Machine).FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name) && x.Name.Contains(model.Name)) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; } public List GetFilteredList(ProductSearchModel model) @@ -35,11 +35,11 @@ namespace DatabaseImplement.Implements } using var context = new FactoryGoWorkDatabase(); if (model.DetailId.HasValue) - return context.Products.Include(p => p.Details).ThenInclude(p => p.Detail).Where(x => x.UserId == model.Id).Where(x => x.Details.FirstOrDefault(y => y.DetailId == model.DetailId) != null).Select(x => x.GetViewModel).ToList(); + return context.Products.Include(p => p.Details).ThenInclude(p => p.Detail).Include(p => p.Machine).Where(x => x.UserId == model.UserId).Where(x => x.Details.FirstOrDefault(y => y.DetailId == model.DetailId) != null).Select(x => x.GetViewModel).ToList(); else if (model.WorkerId.HasValue) return context.Products.Where(p => p.MachineId.HasValue).Include(p => p.Machine).ThenInclude(p => p.Workers).Where(x => x.Machine.Workers.FirstOrDefault(y => y.WorkerId == model.WorkerId) != null).Select(x => x.GetViewModel).ToList(); else - return context.Products.Include(p => p.Details).ThenInclude(p => p.Detail).Where(x => x.UserId == model.Id).Select(x => x.GetViewModel).ToList(); + return context.Products.Include(p => p.Details).ThenInclude(p => p.Detail).Include(p => p.Machine).Where(x => x.UserId == model.UserId).Select(x => x.GetViewModel).ToList(); } public List GetFullList() diff --git a/Course/DatabaseImplement/Models/Product.cs b/Course/DatabaseImplement/Models/Product.cs index 1543963..d27299b 100644 --- a/Course/DatabaseImplement/Models/Product.cs +++ b/Course/DatabaseImplement/Models/Product.cs @@ -72,7 +72,7 @@ namespace DatabaseImplement.Models return; Name = model.Name; Cost = model.Cost; - MachineId = model.MachineId; + MachineId = model.MachineId == null ? MachineId : model.MachineId; } public ProductViewModel GetViewModel => new() { @@ -81,7 +81,8 @@ namespace DatabaseImplement.Models Cost = Cost, UserId = UserId, DetailProducts = DetailProducts, - MachineId= MachineId + MachineId= MachineId, + MachineName = Machine == null ? null : Machine.Title }; public void UpdateDetails(FactoryGoWorkDatabase context, ProductBindingModel model) { diff --git a/Course/ImplemenerLogic/DataToLogic.cs b/Course/ImplemenerLogic/DataToLogic.cs new file mode 100644 index 0000000..19211af --- /dev/null +++ b/Course/ImplemenerLogic/DataToLogic.cs @@ -0,0 +1,13 @@ +using DatabaseImplement.Implements; +using BusinessLogic.BusinessLogic; + +namespace ImplemenerLogic +{ + public static class DataToLogic + { + public static DetailLogic detailLogic() + { + return + } + } +} diff --git a/Course/ImplemenerLogic/ImplemenerLogic.csproj b/Course/ImplemenerLogic/ImplemenerLogic.csproj new file mode 100644 index 0000000..b2c1bac --- /dev/null +++ b/Course/ImplemenerLogic/ImplemenerLogic.csproj @@ -0,0 +1,14 @@ + + + + net6.0 + enable + enable + + + + + + + + diff --git a/Course/ImplementerApp/Controllers/HomeController.cs b/Course/ImplementerApp/Controllers/HomeController.cs index 54266c8..485577f 100644 --- a/Course/ImplementerApp/Controllers/HomeController.cs +++ b/Course/ImplementerApp/Controllers/HomeController.cs @@ -5,174 +5,301 @@ using BusinessLogic.BusinessLogic; using Contracts.BusinessLogicsContracts; using Contracts.ViewModels; using DataModels.Models; +using Contracts.BindingModels; +using DatabaseImplement.Models; namespace ImplementerApp.Controllers { public class HomeController : Controller { private readonly ILogger _logger; - private readonly IDetailLogic _detailLogic; - private readonly IImplementerLogic _userLogic; - private readonly IProductLogic _productLogic; - private readonly IProductionLogic _productionLogic; - - - public HomeController(ILogger logger) + private readonly ImplementerData _data; + public HomeController(ILogger logger, ImplementerData data) { _logger = logger; + _data = data; + } + private bool IsLoggedIn { get {return UserImplementer.user != null; } } + private int UserId { get { return UserImplementer.user!.Id; } } + public IActionResult IndexNonReg() + { + if (!IsLoggedIn) + return View(); + return RedirectToAction("Index"); } - public IActionResult Index() { + if (!IsLoggedIn) + return RedirectToAction("IndexNonReg"); return View(); } + [HttpGet] public IActionResult Enter() { - return View(); + if (!IsLoggedIn) + return View(); + return RedirectToAction("Index"); } + [HttpPost] + public void Enter(string login, string password) + { + var user = _data.Login(login, password); + if (user != null) + { + UserImplementer.user = user; + Response.Redirect("Index"); + } + } + [HttpGet] public IActionResult Register() { return View(); } + public IActionResult Logout() + { + UserImplementer.user = null; + return RedirectToAction("IndexNonReg"); + } + [HttpPost] + public void Register(string name, string login, string email, string password1, string password2) + { + if (password1 == password2 && _data.Register(new() { Email = email, Login = login, Name = name, Password = password1 })) + { + Response.Redirect("Index"); + } + } + [HttpGet] public IActionResult IndexDetail() { - var details = new List(); - details.Add(new DetailViewModel + if (UserImplementer.user != null) { - Id = 1, - Name = "Test", - Cost = 55.5, - UserId = 1 - }); - details.Add(new DetailViewModel - { - Id = 2, - Name = "Test1", - Cost = 32, - UserId = 2 - }); - return View(details); + var list = _data.GetDetails(UserImplementer.user.Id); + if (list != null) + return View(list); + return View(new List()); + } + return RedirectToAction("IndexNonReg"); } - public IActionResult CreateDetail() - { - return View(); + [HttpPost] + public void IndexDetail(int id) + { + if (UserImplementer.user != null) + { + _data.DeleteDetail(id); + } + Response.Redirect("IndexDetail"); + } + [HttpGet] + public IActionResult CreateDetail(int id) + { + if (id != 0) + { + var value = _data.GetDetail(id); + if (value != null) + return View(value); + } + return View(new DetailViewModel()); } - + [HttpPost] + public IActionResult CreateDetail(DetailBindingModel model) + { + if (model.Id == 0) + { + model.DateCreate = DateTime.Now; + model.UserId = UserImplementer.user!.Id; + if (_data.CreateDetail(model)) + return RedirectToAction("IndexDetail"); + } + else + { + if (_data.UpdateDetail(model)) + return RedirectToAction("IndexDetail"); + } + return View(); + } + [HttpGet] public IActionResult IndexProduct() { - List products = new List - { - new ProductViewModel - { - Id = 1, - Name = "Изделие 1", - Cost = 10.99, - UserId = 1, - MachineId = 1 - }, - new ProductViewModel - { - Id = 2, - Name = "Изделие 2", - Cost = 19.99, - UserId = 2, - MachineId = 2 - } - }; - return View(products); - } - public IActionResult CreateProduct() + if (IsLoggedIn) { + var products = _data.GetProducts(UserImplementer.user!.Id); + return View(products); + } + return RedirectToAction("IndexNonReg"); + } + [HttpPost] + public IActionResult IndexProduct(int id) + { + _data.DeleteProduct(id); + return RedirectToAction("IndexProduct"); + } + [HttpGet] + public IActionResult CreateProduct(int id) { - var details = new List(); - details.Add(new DetailViewModel - { - Id = 1, - Name = "Test", - Cost = 55.5, - UserId = 1 - }); - details.Add(new DetailViewModel - { - Id = 2, - Name = "Test1", - Cost = 32, - UserId = 2 - }); - return View(details); + var details = _data.GetDetails(UserImplementer.user!.Id); + ViewBag.AllDetails = details; + if (id != 0) + { + var value = _data.GetProduct(id); + if (value != null) + return View(value); + } + return View(new ProductViewModel()); } + [HttpPost] + public IActionResult CreateProduct(int id, string title, int[] detailIds, int[] counts) + { + ProductBindingModel model = new ProductBindingModel(); + model.Id = id; + model.Name = title; + model.UserId = UserImplementer.user!.Id; + var details = _data.GetDetails(UserImplementer.user!.Id); + double sum = 0; + for (int i = 0; i < detailIds.Length; i++) + { + var detail = details!.FirstOrDefault(x => x.Id == detailIds[i])!; + if (counts[i] <= 0) + continue; + model.ProductDetails[detailIds[i]] = (detail, counts[i]); + sum += detail.Cost * counts[i]; + } + if (model.ProductDetails.Count == 0) + return RedirectToAction("IndexProduct"); + model.Cost = sum; + if (id != 0) + { + _data.UpdateProduct(model); + } + else + { + _data.CreateProduct(model); + } + return RedirectToAction("IndexProduct"); + } + [HttpGet] public IActionResult IndexProduction() { - List productionViewModels = new List + if (UserImplementer.user != null) { - new ProductionViewModel - { - Id = 1, - Name = "Производство А", - Cost = 1000.00, - UserId = 1 - }, - new ProductionViewModel - { - Id = 2, - Name = "Производство Б", - Cost = 1500.00, - UserId = 2 - } - }; - return View(productionViewModels); - } - public IActionResult CreateProduction() + var productions = _data.GetProductions(UserImplementer.user.Id); + return View(productions); + } + return RedirectToAction("IndexNonReg"); + } + [HttpPost] + public IActionResult IndexProduction(int id) + { + _data.DeleteProduction(id); + return RedirectToAction("IndexProduction"); + } + [HttpGet] + public IActionResult CreateProduction(int id) { - var details = new List(); - details.Add(new DetailViewModel - { - Id = 1, - Name = "Test", - Cost = 55.5, - UserId = 1 - }); - details.Add(new DetailViewModel - { - Id = 2, - Name = "Test1", - Cost = 32, - UserId = 2 - }); - return View(details); + var details = _data.GetDetails(UserImplementer.user!.Id); + ViewBag.AllDetails = details; + if (id != 0) + { + var value = _data.GetProduction(id); + if (value != null) + return View(value); + } + return View(new ProductionViewModel()); } + [HttpPost] + public IActionResult CreateProduction(int id, string title, int[] detailIds) + { + ProductionBindingModel model = new ProductionBindingModel(); + model.Id = id; + model.Name = title; + model.UserId = UserImplementer.user!.Id; + var details = _data.GetDetails(UserImplementer.user!.Id); + double sum = 0; + for (int i = 0; i < detailIds.Length; i++) + { + var detail = details!.FirstOrDefault(x => x.Id == detailIds[i])!; + model.ProductionDetails[detailIds[i]] = detail; + sum += detail.Cost; + } + model.Cost = sum; + bool changed = false; + if (model.ProductionDetails.Count > 0) + { + if (id != 0) + { + changed = _data.UpdateProduction(model); + } + else + { + changed = _data.CreateProduction(model); + } + } + if (changed) + return RedirectToAction("IndexProduction"); + else + { + ViewBag.AllDetails = details; + return View(model); + } + } + [HttpGet] public IActionResult Privacy() { - ImplementerViewModel user = new() - { - Email = "mail@mail.ru", - Login = "Login", - Password = "password", - Name = "User" - - }; - - return View(user); + if (IsLoggedIn) + return View(UserImplementer.user); + return RedirectToAction("IndexNonReg"); } - public IActionResult DetailTimeReport() + [HttpPost] + public IActionResult Privacy(int id, string login, string email, string password, string name) { - List detailTimeReports = new List - { - new DetailTimeReport - { - DetailName = "Деталь А", - Productions = new List { "Производство 1", "Производство 2" }, - Products = new List { "Машина X", "Машина Y" } - }, - new DetailTimeReport - { - DetailName = "Деталь B", - Productions = new List { "Производство 3", "Производство 4" }, - Products = new List { "Машина Z", "Машина W" } - } - }; - return View(detailTimeReports); + if (!IsLoggedIn) + return RedirectToAction("IndexNonReg"); + ImplementerBindingModel user = new() { Id = id, Login = login, Email = email, Password = password, Name = name }; + if (_data.UpdateUser(user)) + { + UserImplementer.user = new ImplementerViewModel { Id = id, Login = login, Password = password, Name = name, Email = email }; + } + return View(user); } - public IActionResult DetailWorkshopReport() + [HttpGet] + public IActionResult DetailTimeChoose() + { + if (!IsLoggedIn) + return RedirectToAction("IndexNonReg"); + return View(); + } + [HttpPost] + public IActionResult SendReport(DateTime startDate, DateTime endDate) + { + + return Ok(); + } + [HttpPost] + public IActionResult TimeReportWeb(DateTime startDate, DateTime endDate) + { + if (!IsLoggedIn) + return RedirectToAction("IndexNonReg"); + + + HttpContext.Session.SetString("StartDate", startDate.ToString()); + HttpContext.Session.SetString("EndDate", endDate.ToString()); + + return RedirectToAction("DetailTimeReport"); + } + [HttpGet] + public IActionResult DetailTimeReport() + { + var startDateStr = HttpContext.Session.GetString("StartDate"); + var endDateStr = HttpContext.Session.GetString("EndDate"); + var startDate = DateTime.Parse(startDateStr); + var endDate = DateTime.Parse(endDateStr).AddDays(1); + + var values = _data.GetTimeReport(startDate, endDate, UserId); + + ViewBag.StartDate = startDate; + ViewBag.EndDate = endDate; + + return View(values); + } + public IActionResult DetailWorkshopReport() { List detailWorkshopReports = new List { @@ -193,29 +320,29 @@ namespace ImplementerApp.Controllers { return View(); } - public IActionResult ProductMachineAdd() + [HttpGet] + public IActionResult ProductMachineAdd(int id) { - List machines = new List - { - new MachineViewModel - { - Id = 1, - Title = "Токарный станок", - Country = "Германия", - UserId = 1, - WorkerMachines = new() - }, - new MachineViewModel - { - Id = 2, - Title = "Фрезерный станок", - Country = "Япония", - UserId = 2, - WorkerMachines = new() - } - }; + if (!IsLoggedIn) + return RedirectToAction("IndexNonReg"); + var product = _data.GetProduct(id); + ViewBag.Product = product; + var machines = _data.GetMachines(); return View(machines); } + [HttpPost] + public IActionResult ProductMachineAdd(int productId, int machineId) + { + if (!IsLoggedIn) + return RedirectToAction("IndexNonReg"); + var product = _data.GetProduct(productId); + if (product == null) + return RedirectToAction("Index"); + ProductBindingModel productBinding = new() { Id = productId, Cost = product.Cost, Name = product.Name, UserId = product.UserId, ProductDetails = product.DetailProducts, MachineId = machineId }; + _data.UpdateProduct(productBinding); + return RedirectToAction("IndexProduct"); + + } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() diff --git a/Course/ImplementerApp/ImplementerApp.csproj b/Course/ImplementerApp/ImplementerApp.csproj index cbd6681..ac4c132 100644 --- a/Course/ImplementerApp/ImplementerApp.csproj +++ b/Course/ImplementerApp/ImplementerApp.csproj @@ -8,11 +8,14 @@ + + + diff --git a/Course/ImplementerApp/ImplementerData.cs b/Course/ImplementerApp/ImplementerData.cs new file mode 100644 index 0000000..6d872a4 --- /dev/null +++ b/Course/ImplementerApp/ImplementerData.cs @@ -0,0 +1,134 @@ +using Contracts.BusinessLogicsContracts; +using Contracts.ViewModels; +using Contracts.BindingModels; +using Contracts.StoragesContracts; +using Contracts.SearchModels; + +namespace ImplementerApp +{ + public class ImplementerData + { + private readonly ILogger _logger; + private readonly IImplementerLogic _implementerLogic; + private readonly IDetailLogic _detailLogic; + private readonly IProductionLogic _productionLogic; + private readonly IProductLogic _productLogic; + private readonly IMachineLogic _machineLogic; + + public ImplementerData(ILogger logger, IImplementerLogic implementerLogic, IDetailLogic detailLogic, IProductionLogic productionLogic, IProductLogic productLogic, IMachineLogic machineLogic) + { + _logger = logger; + _implementerLogic = implementerLogic; + _detailLogic = detailLogic; + _productionLogic = productionLogic; + _productLogic = productLogic; + _machineLogic = machineLogic; + } + + public ImplementerViewModel? Login(string login, string password) + { + return _implementerLogic.ReadElement(new() + { + Login = login, + Password = password + }); + } + public bool Register(ImplementerBindingModel model) + { + return _implementerLogic.Create(model); + } + public bool UpdateUser(ImplementerBindingModel model) + { + return _implementerLogic.Update(model); + } + + public List? GetDetails(int userId) + { + return _detailLogic.ReadList(new DetailSearchModel() { UserId = userId }); + } + public bool DeleteDetail(int detailId) + { + return _detailLogic.Delete(new() { Id = detailId }); + } + public bool CreateDetail(DetailBindingModel model) + { + return _detailLogic.Create(model); + } + public bool UpdateDetail(DetailBindingModel model) + { + return _detailLogic.Update(model); + } + public DetailViewModel? GetDetail(int id) + { + return _detailLogic.ReadElement(new() { Id= id }); + } + + public List? GetProducts(int userId) + { + return _productLogic.ReadList(new ProductSearchModel() { UserId = userId }); + } + public ProductViewModel? GetProduct(int id) + { + return _productLogic.ReadElement(new() { Id = id }); + } + public bool UpdateProduct(ProductBindingModel model) + { + return _productLogic.Update(model); + } + public bool DeleteProduct(int productId) + { + return _productLogic.Delete(new() { Id = productId }); + } + public bool CreateProduct(ProductBindingModel model) + { + return _productLogic.Create(model); + } + + public List? GetProductions(int userId) + { + return _productionLogic.ReadList(new() { UserId = userId }); + } + public ProductionViewModel? GetProduction(int id) + { + return _productionLogic.ReadElement(new() { Id = id }); + } + public bool CreateProduction(ProductionBindingModel model) + { + return _productionLogic.Create(model); + } + public bool UpdateProduction(ProductionBindingModel model) + { + return _productionLogic.Update(model); + } + public bool DeleteProduction(int productionId) + { + return _productionLogic.Delete(new() { Id = productionId}); + } + + public List? GetMachines() + { + return _machineLogic.ReadList(null); + } + + public List GetTimeReport(DateTime? startDate, DateTime? endDate, int UserId) + { + var details = _detailLogic.ReadList(new() { DateFrom = startDate, DateTo = endDate, UserId = UserId }); + if (details == null) + return new(); + List detailTimeReports = new List(); + foreach (var detail in details) + { + var report = new DetailTimeReport(); + report.DetailName = detail.Name; + var products = _productLogic.ReadList(new() { DetailId = detail.Id, UserId = UserId }); + if (products != null) + report.Products = products.Select(p => p.Name).ToList(); + var productions = _productionLogic.ReadList(new() { DetailId = detail.Id, UserId = UserId }); + if (productions != null) + report.Productions = productions.Select(p => p.Name).ToList(); + detailTimeReports.Add(report); + } + return detailTimeReports; + } + } +} diff --git a/Course/ImplementerApp/Program.cs b/Course/ImplementerApp/Program.cs index 36efc00..cdae25d 100644 --- a/Course/ImplementerApp/Program.cs +++ b/Course/ImplementerApp/Program.cs @@ -1,9 +1,36 @@ +using BusinessLogic.BusinessLogic; using Contracts.BusinessLogicsContracts; +using Contracts.StoragesContracts; +using DatabaseImplement.Implements; +using ImplementerApp; +using Microsoft.Extensions.Options; var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllersWithViews().AddRazorRuntimeCompilation(); +builder.Logging.SetMinimumLevel(LogLevel.Trace); +builder.Logging.AddLog4Net("log4net.config"); + +builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddTransient(); + +builder.Services.AddSession(options => +{ + options.IdleTimeout = TimeSpan.FromMinutes(30); + options.Cookie.HttpOnly = true; + options.Cookie.IsEssential = true; +}); + var app = builder.Build(); if (!app.Environment.IsDevelopment()) @@ -16,7 +43,7 @@ app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); - +app.UseSession(); app.UseAuthorization(); app.MapControllerRoute( diff --git a/Course/ImplementerApp/UserImplementer.cs b/Course/ImplementerApp/UserImplementer.cs new file mode 100644 index 0000000..ea8c905 --- /dev/null +++ b/Course/ImplementerApp/UserImplementer.cs @@ -0,0 +1,9 @@ +using Contracts.ViewModels; + +namespace ImplementerApp +{ + public static class UserImplementer + { + public static ImplementerViewModel? user { get; set; } + } +} diff --git a/Course/ImplementerApp/Views/Home/CreateDetail.cshtml b/Course/ImplementerApp/Views/Home/CreateDetail.cshtml index bf68c93..3bb2e17 100644 --- a/Course/ImplementerApp/Views/Home/CreateDetail.cshtml +++ b/Course/ImplementerApp/Views/Home/CreateDetail.cshtml @@ -1,20 +1,57 @@ -@{ - ViewData["Title"] = "CreateDetail"; +@using Contracts.ViewModels; +@{ + ViewData["Title"] = "CreateDetail"; } +@model DetailViewModel;
-

Создание детали

+

Деталь

-
-
-
Название:
-
-
-
-
Цена:
-
-
-
-
-
-
-
\ No newline at end of file +
+ +
+
Название:
+
+ + +
+
+
+
Цена:
+
+ + +
+
+
+
+
+
+
+ + + diff --git a/Course/ImplementerApp/Views/Home/CreateProduct.cshtml b/Course/ImplementerApp/Views/Home/CreateProduct.cshtml index 0033b22..17473cf 100644 --- a/Course/ImplementerApp/Views/Home/CreateProduct.cshtml +++ b/Course/ImplementerApp/Views/Home/CreateProduct.cshtml @@ -1,45 +1,62 @@ @using Contracts.ViewModels -@model List +@model ProductViewModel; @{ - ViewData["Title"] = "CreateProduct"; + ViewData["Title"] = "CreateProduct"; + ViewBag.Details = Model.DetailProducts; }
-

Создание изделия

+

Создание изделия

-
-
-
Название:
-
-
+ +
+
Название:
+
+ + +
+
Детали
- + + - @foreach (var detail in Model) + @foreach (var detail in ViewBag.Details) { - + - + + }
Выбор Название КоличествоСтоимостьУдалить
- + + @detail.Value.Item1.Name @detail.Name - + + @detail.Value.Item1.Cost +
+ +
Сумма:
@@ -55,6 +72,96 @@ \ No newline at end of file + diff --git a/Course/ImplementerApp/Views/Home/CreateProduction.cshtml b/Course/ImplementerApp/Views/Home/CreateProduction.cshtml index de8b108..bb64739 100644 --- a/Course/ImplementerApp/Views/Home/CreateProduction.cshtml +++ b/Course/ImplementerApp/Views/Home/CreateProduction.cshtml @@ -1,41 +1,56 @@ @using Contracts.ViewModels -@model List +@model ProductionViewModel @{ ViewData["Title"] = "CreateProduction"; + ViewBag.Details = Model.DetailProductions; }

Создание производства

- +
Название:
-
+
+ + +
-
Details
+
Детали
- + + - @foreach (var detail in Model) + @foreach (var detail in ViewBag.Details) { - + - + + }
Выбор НазваниеСтоимостьУдалить
- + + @detail.Value.Name @detail.Name@detail.Value.Cost
+ +
Сумма:
@@ -51,6 +66,87 @@ \ No newline at end of file + diff --git a/Course/ImplementerApp/Views/Home/DetailTimeChoose.cshtml b/Course/ImplementerApp/Views/Home/DetailTimeChoose.cshtml new file mode 100644 index 0000000..b05f0e8 --- /dev/null +++ b/Course/ImplementerApp/Views/Home/DetailTimeChoose.cshtml @@ -0,0 +1,76 @@ +@{ + ViewData["Title"] = "Создание отчета"; +} + +
+

Создание отчета

+
+ +
+
+ +
+
+ + +
+
+
+
+ +
+
+ + +
+
+
+
+ +
+
+ + + + diff --git a/Course/ImplementerApp/Views/Home/Index.cshtml b/Course/ImplementerApp/Views/Home/Index.cshtml index b3e0f4b..8c21602 100644 --- a/Course/ImplementerApp/Views/Home/Index.cshtml +++ b/Course/ImplementerApp/Views/Home/Index.cshtml @@ -3,14 +3,14 @@ }
-

Приложение "Завод "Иди работать". Исполнитель"

+

Главное меню

diff --git a/Course/ImplementerApp/Views/Home/IndexDetail.cshtml b/Course/ImplementerApp/Views/Home/IndexDetail.cshtml index ac228d1..f24d465 100644 --- a/Course/ImplementerApp/Views/Home/IndexDetail.cshtml +++ b/Course/ImplementerApp/Views/Home/IndexDetail.cshtml @@ -18,7 +18,7 @@ return; }

- Создать деталь + Создать деталь

@@ -57,7 +57,10 @@ Изменить } diff --git a/Course/ImplementerApp/Views/Home/IndexNonReg.cshtml b/Course/ImplementerApp/Views/Home/IndexNonReg.cshtml new file mode 100644 index 0000000..3d737d5 --- /dev/null +++ b/Course/ImplementerApp/Views/Home/IndexNonReg.cshtml @@ -0,0 +1,10 @@ +@{ + ViewData["Title"] = "Home Page"; +} + + diff --git a/Course/ImplementerApp/Views/Home/IndexProduct.cshtml b/Course/ImplementerApp/Views/Home/IndexProduct.cshtml index 820b716..c75d75f 100644 --- a/Course/ImplementerApp/Views/Home/IndexProduct.cshtml +++ b/Course/ImplementerApp/Views/Home/IndexProduct.cshtml @@ -10,7 +10,6 @@

Изделия

-ProductMachineAdd
@{ if (Model == null) @@ -19,7 +18,7 @@ ProductMachineAdd return; }

- Создать изделие + Создать изделие

- Удалить +
+ + +
@@ -33,6 +32,9 @@ ProductMachineAdd + @@ -57,6 +59,9 @@ ProductMachineAdd + @@ -64,7 +69,10 @@ ProductMachineAdd Изменить } diff --git a/Course/ImplementerApp/Views/Home/IndexProduction.cshtml b/Course/ImplementerApp/Views/Home/IndexProduction.cshtml index 6bdc916..3ef96cf 100644 --- a/Course/ImplementerApp/Views/Home/IndexProduction.cshtml +++ b/Course/ImplementerApp/Views/Home/IndexProduction.cshtml @@ -18,7 +18,7 @@ return; }

- Создать производство + Создать производство

Цена + Станок + Привязка станка к изделию @Html.DisplayFor(modelItem => item.Cost) + @Html.DisplayFor(modelItem => item.MachineName) + Привязать станок - Удалить +
+ + +
@@ -57,7 +57,10 @@ Изменить } diff --git a/Course/ImplementerApp/Views/Home/Privacy.cshtml b/Course/ImplementerApp/Views/Home/Privacy.cshtml index dcde174..fa5d1b6 100644 --- a/Course/ImplementerApp/Views/Home/Privacy.cshtml +++ b/Course/ImplementerApp/Views/Home/Privacy.cshtml @@ -2,27 +2,87 @@ ViewData["Title"] = "Privacy Policy"; }
-

Личные данные

+

Личные данные

- -
-
Логин:
-
-
-
-
Почта:
-
-
-
-
Пароль:
-
-
-
-
ФИО:
-
-
-
-
-
-
- \ No newline at end of file + + +
+
Логин:
+
+ + +
+
+
+
Почта:
+
+ + +
+
+
+
Пароль:
+
+ + +
+
+
+
ФИО:
+
+ + +
+
+
+
+
+
+ + + + diff --git a/Course/ImplementerApp/Views/Home/ProductMachineAdd.cshtml b/Course/ImplementerApp/Views/Home/ProductMachineAdd.cshtml index 37daa6a..2ecb2c8 100644 --- a/Course/ImplementerApp/Views/Home/ProductMachineAdd.cshtml +++ b/Course/ImplementerApp/Views/Home/ProductMachineAdd.cshtml @@ -7,7 +7,7 @@ }
-

Изделие - @ViewBag.Product

+

Изделие - @ViewBag.Product.Name

@@ -19,8 +19,9 @@
@machine.Title
-
- + + +
diff --git a/Course/ImplementerApp/Views/Home/Register.cshtml b/Course/ImplementerApp/Views/Home/Register.cshtml index 924d990..06d2595 100644 --- a/Course/ImplementerApp/Views/Home/Register.cshtml +++ b/Course/ImplementerApp/Views/Home/Register.cshtml @@ -1,33 +1,103 @@ @{ - ViewData["Title"] = "Register"; + ViewData["Title"] = "Register"; }
-

Регистрация

+

Регистрация

-
-
-
Имя:
-
-
-
-
Логин:
-
-
-
-
Почта:
-
-
-
-
Пароль:
-
-
-
-
Повтор пароля:
-
-
-
-
-
-
- \ No newline at end of file +
+
+
Имя:
+
+ + +
+
+
+
Логин:
+
+ + +
+
+
+
Почта:
+
+ + +
+
+
+
Пароль:
+
+ + +
+
+
+
Повтор пароля:
+
+ + +
+
+
+
+
+
+ + + + diff --git a/Course/ImplementerApp/Views/Home/ReportsMenu.cshtml b/Course/ImplementerApp/Views/Home/ReportsMenu.cshtml index caac5d0..dfbef55 100644 --- a/Course/ImplementerApp/Views/Home/ReportsMenu.cshtml +++ b/Course/ImplementerApp/Views/Home/ReportsMenu.cshtml @@ -6,6 +6,6 @@

Меню создания отчетов

diff --git a/Course/ImplementerApp/Views/Shared/_Layout.cshtml b/Course/ImplementerApp/Views/Shared/_Layout.cshtml index ca5b590..ee64ee1 100644 --- a/Course/ImplementerApp/Views/Shared/_Layout.cshtml +++ b/Course/ImplementerApp/Views/Shared/_Layout.cshtml @@ -1,4 +1,8 @@ - +@{ + ViewData["Name"] = UserImplementer.user == null ? "Пользователь" : UserImplementer.user.Name; +} + + @@ -13,7 +17,8 @@ diff --git a/Course/ImplementerApp/log4net.config b/Course/ImplementerApp/log4net.config new file mode 100644 index 0000000..1fd1998 --- /dev/null +++ b/Course/ImplementerApp/log4net.config @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + \ No newline at end of file
- Удалить +
+ + +