diff --git a/ComputerShopBusinessLogic/BusinessLogics/AssemblyLogic.cs b/ComputerShopBusinessLogic/BusinessLogics/AssemblyLogic.cs index 5d36982..dca0b6b 100644 --- a/ComputerShopBusinessLogic/BusinessLogics/AssemblyLogic.cs +++ b/ComputerShopBusinessLogic/BusinessLogics/AssemblyLogic.cs @@ -102,9 +102,6 @@ namespace ComputerShopBusinessLogic.BusinessLogics if (string.IsNullOrEmpty(Model.Category)) throw new ArgumentException($"У сборки отсутствует категория"); - if (Model.Price < 0) - throw new ArgumentException("Цена сборки должна быть больше 0", nameof(Model.Price)); - var Element = _assemblyStorage.GetElement(new AssemblySearchModel { AssemblyName = Model.AssemblyName diff --git a/ComputerShopBusinessLogic/BusinessLogics/ProductLogic.cs b/ComputerShopBusinessLogic/BusinessLogics/ProductLogic.cs index 19db180..4083bfb 100644 --- a/ComputerShopBusinessLogic/BusinessLogics/ProductLogic.cs +++ b/ComputerShopBusinessLogic/BusinessLogics/ProductLogic.cs @@ -110,9 +110,6 @@ namespace ComputerShopBusinessLogic.BusinessLogics if (string.IsNullOrEmpty(Model.ProductName)) throw new ArgumentException($"У товара отсутствует название"); - if (Model.Price < 0) - throw new ArgumentException("Цена товара должна быть больше 0", nameof(Model.Price)); - if (Model.Warranty <= 0) throw new ArgumentException("Гарантия на товар должна быть больше 0", nameof(Model.Warranty)); diff --git a/ComputerShopBusinessLogic/OfficePackage/AbstractSaveToExcelGuarantor.cs b/ComputerShopBusinessLogic/OfficePackage/AbstractSaveToExcelGuarantor.cs new file mode 100644 index 0000000..010c213 --- /dev/null +++ b/ComputerShopBusinessLogic/OfficePackage/AbstractSaveToExcelGuarantor.cs @@ -0,0 +1,137 @@ +using ComputerShopBusinessLogic.OfficePackage.HelperModels; +using GarmentFactoryBusinessLogic.OfficePackage.HelperEnums; +using GarmentFactoryBusinessLogic.OfficePackage.HelperModels; + +namespace ComputerShopBusinessLogic.OfficePackage +{ + public abstract class AbstractSaveToExcelGuarantor + { + public void CreateReport(ExcelInfoGuarantor Info) + { + CreateExcel(Info); + + //!!!2 абзаца ниже - настройка заголовков, исправить скорее всего + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = 1, + Text = Info.Title1, + StyleInfo = ExcelStyleInfoType.Title + }); + + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "B", + RowIndex = 1, + Text = Info.Title2, + StyleInfo = ExcelStyleInfoType.Title + }); + + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "C", + RowIndex = 1, + Text = Info.Title3, + StyleInfo = ExcelStyleInfoType.Title + }); + + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "D", + RowIndex = 1, + Text = Info.Title4, + StyleInfo = ExcelStyleInfoType.Title + }); + + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "E", + RowIndex = 1, + Text = Info.Title5, + StyleInfo = ExcelStyleInfoType.Title + }); + + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "F", + RowIndex = 1, + Text = Info.Title6, + StyleInfo = ExcelStyleInfoType.Title + }); + + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "G", + RowIndex = 1, + Text = Info.Title7, + StyleInfo = ExcelStyleInfoType.Title + }); + + uint RowIndex = 2; + foreach (var ComponentWithShipments in Info.ShipmentComponents) + { + int ShipmentsNum = ComponentWithShipments.Shipments.Count; + int ShipmentIndex = 0; + + foreach (var Shipment in ComponentWithShipments.Shipments) + { + if (!string.IsNullOrEmpty(Shipment.ProviderName)) + { + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = RowIndex, + Text = ComponentWithShipments.ComponentId.ToString(), + StyleInfo = ExcelStyleInfoType.Text + }); + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "B", + RowIndex = RowIndex, + Text = ComponentWithShipments.ComponentName, + StyleInfo = ExcelStyleInfoType.Text + }); + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "C", + RowIndex = RowIndex, + Text = ComponentWithShipments.ComponentCost.ToString(), + StyleInfo = ExcelStyleInfoType.Text + }); + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "D", + RowIndex = RowIndex, + Text = Shipment.ProviderName, + StyleInfo = ExcelStyleInfoType.Text + }); + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "E", + RowIndex = RowIndex, + Text = Shipment.ShipmentDate.ToShortDateString(), + StyleInfo = ExcelStyleInfoType.Text + }); + } + ShipmentIndex++; + if (ShipmentIndex < ShipmentsNum && !string.IsNullOrEmpty(Shipment.ProviderName)) + { + RowIndex++; + } + } + + RowIndex++; + } + + SaveExcel(Info); + } + + protected abstract void CreateExcel(DocumentInfo Info); + + protected abstract void InsertCellInWorksheet(ExcelCellParameters ExcelParams); + + protected abstract void MergeCells(ExcelMergeParameters ExcelParams); + + protected abstract void SaveExcel(DocumentInfo Info); + } +} diff --git a/ComputerShopBusinessLogic/OfficePackage/AbstractSaveToPdfGuarantor.cs b/ComputerShopBusinessLogic/OfficePackage/AbstractSaveToPdfGuarantor.cs new file mode 100644 index 0000000..d9c131e --- /dev/null +++ b/ComputerShopBusinessLogic/OfficePackage/AbstractSaveToPdfGuarantor.cs @@ -0,0 +1,58 @@ +using ComputerShopBusinessLogic.OfficePackage.HelperModels; +using GarmentFactoryBusinessLogic.OfficePackage.HelperEnums; +using GarmentFactoryBusinessLogic.OfficePackage.HelperModels; + +namespace ComputerShopBusinessLogic.OfficePackage +{ + public abstract class AbstractSaveToPdfGuarantor + { + public void CreateDoc(PdfInfoGuarantor 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", "2.5cm", "2cm", "2cm", "2cm", "4cm", "2.5cm", "3.5cm", "3.5cm", "2.5cm" }); + + CreateRow(new PdfRowParameters + { + Texts = new List { "ID комплектующей", "Название", "Стоимость", "ID сборки", "Название сборки", "Цена сборки", "Категория", "ID заявки", "Дата заявки", "Клиент" }, + Style = "NormalTitle", + ParagraphAlignment = PdfParagraphAlignmentType.Center + }); + + foreach (var ComponentByDate in Info.ComponentsByDate) + { + CreateRow(new PdfRowParameters + { + Texts = new List + { + ComponentByDate.ComponentId.ToString(), + ComponentByDate.ComponentName, + ComponentByDate.ComponentCost.ToString(), + ComponentByDate.AssemblyId.ToString(), + ComponentByDate.AssemblyName, + ComponentByDate.AssemblyPrice.ToString(), + ComponentByDate.AssemblyCategory, + ComponentByDate.RequestId.ToString(), + ComponentByDate.DateRequest.ToShortDateString(), + ComponentByDate.ClientFIO, + }, + Style = "Normal", + ParagraphAlignment = PdfParagraphAlignmentType.Left + }); + } + + SavePdf(Info); + } + + protected abstract void CreatePdf(DocumentInfo Info); + + protected abstract void CreateParagraph(PdfParagraph Paragraph); + + protected abstract void CreateTable(List Columns); + + protected abstract void CreateRow(PdfRowParameters RowParameters); + + protected abstract void SavePdf(DocumentInfo Info); + } +} diff --git a/ComputerShopBusinessLogic/OfficePackage/AbstractSaveToWordGuarantor.cs b/ComputerShopBusinessLogic/OfficePackage/AbstractSaveToWordGuarantor.cs new file mode 100644 index 0000000..86bd334 --- /dev/null +++ b/ComputerShopBusinessLogic/OfficePackage/AbstractSaveToWordGuarantor.cs @@ -0,0 +1,83 @@ +using ComputerShopBusinessLogic.OfficePackage.HelperModels; +using GarmentFactoryBusinessLogic.OfficePackage.HelperEnums; +using GarmentFactoryBusinessLogic.OfficePackage.HelperModels; + +namespace ComputerShopBusinessLogic.OfficePackage +{ + public abstract class AbstractSaveToWordGuarantor + { + public void CreateDoc(WordInfoGuarantor 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 ComponentWithShipments in Info.ShipmentComponents) + { + CreateParagraph(new WordParagraph + { + Texts = new List<(string, WordTextProperties)> + { + ("Комплектующая №" + ComponentWithShipments.ComponentId.ToString() + " - " + + ComponentWithShipments.ComponentName.ToString() + " - " + + ComponentWithShipments.ComponentCost.ToString() + " - ", new WordTextProperties {Size = "24", Bold=true}) + }, + TextProperties = new WordTextProperties + { + Size = "24", + JustificationType = WordJustificationType.Both + } + }); + + foreach (var Shipment in ComponentWithShipments.Shipments) + { + if (!string.IsNullOrEmpty(Shipment.ProviderName)) + { + CreateParagraph(new WordParagraph + { + Texts = new List<(string, WordTextProperties)> { + (Shipment.ProviderName + " - ", new WordTextProperties { Size = "24" }), + (Shipment.ShipmentDate.ToShortDateString() + " - ", new WordTextProperties { Size = "24" }) + }, + TextProperties = new WordTextProperties + { + Size = "24", + JustificationType = WordJustificationType.Both + } + }); + } + + } + } + + SaveWord(Info); + } + + /// + /// Создание doc-файла + /// + /// + protected abstract void CreateWord(DocumentInfo Info); + + /// + /// Создание абзаца с текстом + /// + /// + /// + protected abstract void CreateParagraph(WordParagraph paragraph); + + /// + /// Сохранение файла + /// + /// + protected abstract void SaveWord(DocumentInfo Info); + } +} diff --git a/ComputerShopBusinessLogic/OfficePackage/HelperModels/ExcelInfoGuarantor.cs b/ComputerShopBusinessLogic/OfficePackage/HelperModels/ExcelInfoGuarantor.cs new file mode 100644 index 0000000..b3d1fcb --- /dev/null +++ b/ComputerShopBusinessLogic/OfficePackage/HelperModels/ExcelInfoGuarantor.cs @@ -0,0 +1,23 @@ +using ComputerShopContracts.ViewModels; + +namespace ComputerShopBusinessLogic.OfficePackage.HelperModels +{ + public class ExcelInfoGuarantor : DocumentInfo + { + public string Title1 { get; set; } = "ID заказа"; + + public string Title2 { get; set; } = "Дата заказа"; + + public string Title3 { get; set; } = "Стоимость заказа"; + + public string Title4 { get; set; } = "Статус заказа"; + + public string Title5 { get; set; } = "Название сборки"; + + public string Title6 { get; set; } = "Категория сборки"; + + public string Title7 { get; set; } = "Цена сборки"; + + public List ShipmentComponents { get; set; } = new(); + } +} diff --git a/ComputerShopBusinessLogic/OfficePackage/HelperModels/IDocumentInfo.cs b/ComputerShopBusinessLogic/OfficePackage/HelperModels/IDocumentInfo.cs new file mode 100644 index 0000000..446ac19 --- /dev/null +++ b/ComputerShopBusinessLogic/OfficePackage/HelperModels/IDocumentInfo.cs @@ -0,0 +1,9 @@ +namespace ComputerShopBusinessLogic.OfficePackage.HelperModels +{ + public class DocumentInfo + { + public string Filename { get; set; } = string.Empty; + + public string Title { get; set; } = string.Empty; + } +} diff --git a/ComputerShopBusinessLogic/OfficePackage/HelperModels/PdfInfoGuarantor.cs b/ComputerShopBusinessLogic/OfficePackage/HelperModels/PdfInfoGuarantor.cs new file mode 100644 index 0000000..53af2ae --- /dev/null +++ b/ComputerShopBusinessLogic/OfficePackage/HelperModels/PdfInfoGuarantor.cs @@ -0,0 +1,13 @@ +using ComputerShopContracts.ViewModels; + +namespace ComputerShopBusinessLogic.OfficePackage.HelperModels +{ + public class PdfInfoGuarantor : DocumentInfo + { + public DateTime DateFrom { get; set; } + + public DateTime DateTo { get; set; } + + public List ComponentsByDate { get; set; } = new(); + } +} diff --git a/ComputerShopBusinessLogic/OfficePackage/HelperModels/WordInfoGuarantor.cs b/ComputerShopBusinessLogic/OfficePackage/HelperModels/WordInfoGuarantor.cs new file mode 100644 index 0000000..3e379d3 --- /dev/null +++ b/ComputerShopBusinessLogic/OfficePackage/HelperModels/WordInfoGuarantor.cs @@ -0,0 +1,9 @@ +using ComputerShopContracts.ViewModels; + +namespace ComputerShopBusinessLogic.OfficePackage.HelperModels +{ + public class WordInfoGuarantor : DocumentInfo + { + public List ShipmentComponents { get; set; } = new(); + } +} diff --git a/ComputerShopBusinessLogic/OfficePackage/Implements/SaveToExcelGuarantor.cs b/ComputerShopBusinessLogic/OfficePackage/Implements/SaveToExcelGuarantor.cs new file mode 100644 index 0000000..a48eca0 --- /dev/null +++ b/ComputerShopBusinessLogic/OfficePackage/Implements/SaveToExcelGuarantor.cs @@ -0,0 +1,292 @@ +using ComputerShopBusinessLogic.OfficePackage.HelperModels; +using DocumentFormat.OpenXml; +using DocumentFormat.OpenXml.Office2010.Excel; +using DocumentFormat.OpenXml.Office2013.Excel; +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Spreadsheet; +using GarmentFactoryBusinessLogic.OfficePackage.HelperEnums; +using GarmentFactoryBusinessLogic.OfficePackage.HelperModels; + +namespace ComputerShopBusinessLogic.OfficePackage.Implements +{ + public class SaveToExcelGuarantor : AbstractSaveToExcelGuarantor + { + 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 }; + + // Создание шрифтов для основного текста и заголовка (в ячейке A1) + 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); + + // Создание 3 стилей ячеек + 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(DocumentInfo 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(); + + if (_shareStringPart.SharedStringTable == null) + { + _shareStringPart.SharedStringTable = new SharedStringTable(); + } + + var worksheetPart = workbookpart.AddNewPart(); + worksheetPart.Worksheet = new Worksheet(new SheetData()); + + Columns lstColumns = worksheetPart.Worksheet.GetFirstChild(); + if (lstColumns == null) + { + lstColumns = new Columns(); + } + + lstColumns.Append(new Column() { Min = 1, Max = 1, Width = 10, CustomWidth = true }); + lstColumns.Append(new Column() { Min = 2, Max = 2, Width = 10, CustomWidth = true }); + lstColumns.Append(new Column() { Min = 3, Max = 3, Width = 20, CustomWidth = true }); + lstColumns.Append(new Column() { Min = 4, Max = 4, Width = 10, CustomWidth = true }); + lstColumns.Append(new Column() { Min = 5, Max = 5, Width = 20, CustomWidth = true }); + lstColumns.Append(new Column() { Min = 6, Max = 6, Width = 20, CustomWidth = true }); + lstColumns.Append(new Column() { Min = 7, Max = 7, Width = 20, CustomWidth = true }); + worksheetPart.Worksheet.InsertAt(lstColumns, 0); + + 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(DocumentInfo Info) + { + if (_spreadsheetDocument == null) + { + return; + } + _spreadsheetDocument.WorkbookPart!.Workbook.Save(); + _spreadsheetDocument.Close(); + } + } +} diff --git a/ComputerShopBusinessLogic/OfficePackage/Implements/SaveToPdfGuarantor.cs b/ComputerShopBusinessLogic/OfficePackage/Implements/SaveToPdfGuarantor.cs new file mode 100644 index 0000000..9c21bdc --- /dev/null +++ b/ComputerShopBusinessLogic/OfficePackage/Implements/SaveToPdfGuarantor.cs @@ -0,0 +1,109 @@ +using ComputerShopBusinessLogic.OfficePackage.HelperModels; +using GarmentFactoryBusinessLogic.OfficePackage.HelperEnums; +using GarmentFactoryBusinessLogic.OfficePackage.HelperModels; +using MigraDoc.DocumentObjectModel; +using MigraDoc.DocumentObjectModel.Tables; +using MigraDoc.Rendering; + +namespace ComputerShopBusinessLogic.OfficePackage.Implements +{ + public class SaveToPdfGuarantor : AbstractSaveToPdfGuarantor + { + 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.Rigth => 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(HelperModels.DocumentInfo 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(HelperModels.DocumentInfo Info) + { + var Renderer = new PdfDocumentRenderer(true) + { + Document = _document + }; + Renderer.RenderDocument(); + Renderer.PdfDocument.Save(Info.Filename); + } + } +} diff --git a/ComputerShopBusinessLogic/OfficePackage/Implements/SaveToWordGuarantor.cs b/ComputerShopBusinessLogic/OfficePackage/Implements/SaveToWordGuarantor.cs new file mode 100644 index 0000000..842aa5e --- /dev/null +++ b/ComputerShopBusinessLogic/OfficePackage/Implements/SaveToWordGuarantor.cs @@ -0,0 +1,122 @@ +using ComputerShopBusinessLogic.OfficePackage.HelperModels; +using DocumentFormat.OpenXml; +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Wordprocessing; +using GarmentFactoryBusinessLogic.OfficePackage.HelperEnums; +using GarmentFactoryBusinessLogic.OfficePackage.HelperModels; + +namespace ComputerShopBusinessLogic.OfficePackage.Implements +{ + public class SaveToWordGuarantor : AbstractSaveToWordGuarantor + { + 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(DocumentInfo 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(DocumentInfo Info) + { + if (_docBody == null || _wordDocument == null) + { + return; + } + _docBody.AppendChild(CreateSectionProperties()); + _wordDocument.MainDocumentPart!.Document.Save(); + _wordDocument.Close(); + } + } +} diff --git a/ComputerShopContracts/BindingModels/AssemblyBindingModel.cs b/ComputerShopContracts/BindingModels/AssemblyBindingModel.cs index b007899..334c8a8 100644 --- a/ComputerShopContracts/BindingModels/AssemblyBindingModel.cs +++ b/ComputerShopContracts/BindingModels/AssemblyBindingModel.cs @@ -14,8 +14,6 @@ namespace ComputerShopContracts.BindingModels public string Category { get; set; } = string.Empty; - public Dictionary AssemblyComponents { get; set; } = new(); - - public Dictionary Test { get; set; } = new(); + public Dictionary AssemblyComponents { get; set; } = new(); } } diff --git a/ComputerShopContracts/BindingModels/ProductBindingModel.cs b/ComputerShopContracts/BindingModels/ProductBindingModel.cs index 1fb28ec..73c3eb8 100644 --- a/ComputerShopContracts/BindingModels/ProductBindingModel.cs +++ b/ComputerShopContracts/BindingModels/ProductBindingModel.cs @@ -16,6 +16,6 @@ namespace ComputerShopContracts.BindingModels public int Warranty { get; set; } - public Dictionary ProductComponents { get; set; } = new(); + public Dictionary ProductComponents { get; set; } = new(); } } diff --git a/ComputerShopContracts/ViewModels/AssemblyViewModel.cs b/ComputerShopContracts/ViewModels/AssemblyViewModel.cs index e536e9a..178a06e 100644 --- a/ComputerShopContracts/ViewModels/AssemblyViewModel.cs +++ b/ComputerShopContracts/ViewModels/AssemblyViewModel.cs @@ -3,7 +3,7 @@ using System.ComponentModel; namespace ComputerShopContracts.ViewModels { - public class AssemblyViewModel : IAssemblyModel + public class AssemblyViewModel : IAssemblyModel { public int Id { get; set; } @@ -18,6 +18,6 @@ namespace ComputerShopContracts.ViewModels [DisplayName("Категория")] public string Category { get; set; } = string.Empty; - public Dictionary AssemblyComponents { get; set; } = new(); - } + public Dictionary AssemblyComponents { get; set; } = new(); + } } diff --git a/ComputerShopContracts/ViewModels/ProductViewModel.cs b/ComputerShopContracts/ViewModels/ProductViewModel.cs index a5d4498..1c60c49 100644 --- a/ComputerShopContracts/ViewModels/ProductViewModel.cs +++ b/ComputerShopContracts/ViewModels/ProductViewModel.cs @@ -23,6 +23,6 @@ namespace ComputerShopContracts.ViewModels [DisplayName("Гарантия (мес.)")] public int Warranty { get; set; } - public Dictionary ProductComponents { get; set; } = new(); + public Dictionary ProductComponents { get; set; } = new(); } } diff --git a/ComputerShopContracts/ViewModels/ReportComponentWithShipmentViewModel.cs b/ComputerShopContracts/ViewModels/ReportComponentWithShipmentViewModel.cs index 6ff7178..866c520 100644 --- a/ComputerShopContracts/ViewModels/ReportComponentWithShipmentViewModel.cs +++ b/ComputerShopContracts/ViewModels/ReportComponentWithShipmentViewModel.cs @@ -8,6 +8,6 @@ public double ComponentCost { get; set; } - public List<(int Count, string ProductName, double ProductPrice, string ProviderName, DateTime ShipmentDate)> Shipments { get; set; } = new(); + public List<(string ProductName, double ProductPrice, string ProviderName, DateTime ShipmentDate)> Shipments { get; set; } = new(); } } diff --git a/ComputerShopDataModels/Models/IAssemblyModel.cs b/ComputerShopDataModels/Models/IAssemblyModel.cs index 8ad19f7..09c7ce1 100644 --- a/ComputerShopDataModels/Models/IAssemblyModel.cs +++ b/ComputerShopDataModels/Models/IAssemblyModel.cs @@ -24,10 +24,5 @@ /// Категория /// string Category { get; } - - /// - /// Список комплектующих - /// - Dictionary AssemblyComponents { get; } } } diff --git a/ComputerShopDataModels/Models/IProductModel.cs b/ComputerShopDataModels/Models/IProductModel.cs index 7e82289..1ec0616 100644 --- a/ComputerShopDataModels/Models/IProductModel.cs +++ b/ComputerShopDataModels/Models/IProductModel.cs @@ -25,11 +25,6 @@ /// int Warranty { get; } - /// - /// Список комплектующих - /// - Dictionary ProductComponents { get; } - /// /// Привязка товара к партии товаров /// diff --git a/ComputerShopDatabaseImplement/Models/Assembly.cs b/ComputerShopDatabaseImplement/Models/Assembly.cs index 4cbe166..d580ef1 100644 --- a/ComputerShopDatabaseImplement/Models/Assembly.cs +++ b/ComputerShopDatabaseImplement/Models/Assembly.cs @@ -28,10 +28,10 @@ namespace ComputerShopDatabaseImplement.Models [ForeignKey("AssemblyId")] public virtual List Components { get; set; } = new(); - private Dictionary? _assemblyComponents; + private Dictionary? _assemblyComponents; [NotMapped] - public Dictionary AssemblyComponents + public Dictionary AssemblyComponents { get { @@ -39,7 +39,7 @@ namespace ComputerShopDatabaseImplement.Models { _assemblyComponents = Components.ToDictionary( AsmComp => AsmComp.ComponentId, - AsmComp => AsmComp.Component as IComponentModel + AsmComp => AsmComp.Component ); } @@ -88,13 +88,14 @@ namespace ComputerShopDatabaseImplement.Models AssemblyName = AssemblyName, Price = Price, Category = Category, - AssemblyComponents = AssemblyComponents, + AssemblyComponents = AssemblyComponents.ToDictionary(x => x.Key, x => x.Value.ViewModel), }; public void UpdateComponents(ComputerShopDatabase Context, AssemblyBindingModel Model) { - // Сначала подсчитывается новая цена, т.к. Model.AssemblyComponents далее может измениться - double NewPrice = Context.Components + // Сначала подсчитывается новая цена, т.к. Model.AssemblyComponents далее может измениться + double NewPrice = Context.Components + .ToList() .Where(x => Model.AssemblyComponents.ContainsKey(x.Id)) .Sum(x => x.Cost); @@ -132,21 +133,5 @@ namespace ComputerShopDatabaseImplement.Models _assemblyComponents = null; } - - private void CalculatePrice( - ComputerShopDatabase Context, - Dictionary ModelComponents, - out List OutComponents, - out double OutPrice) - { - OutComponents = ModelComponents - .Select(x => new AssemblyComponent - { - Component = Context.Components.First(y => y.Id == x.Key) - }) - .ToList(); - - OutPrice = Components.Sum(x => x.Component.Cost); - } } } diff --git a/ComputerShopDatabaseImplement/Models/Product.cs b/ComputerShopDatabaseImplement/Models/Product.cs index 24df409..4871f04 100644 --- a/ComputerShopDatabaseImplement/Models/Product.cs +++ b/ComputerShopDatabaseImplement/Models/Product.cs @@ -29,10 +29,10 @@ namespace ComputerShopDatabaseImplement.Models [ForeignKey("ProductId")] public virtual List Components { get; set; } = new(); - private Dictionary? _productComponents; + private Dictionary? _productComponents; [NotMapped] - public Dictionary ProductComponents + public Dictionary ProductComponents { get { @@ -40,7 +40,7 @@ namespace ComputerShopDatabaseImplement.Models { _productComponents = Components.ToDictionary( ProdComp => ProdComp.ComponentId, - ProdComp => ProdComp.Component as IComponentModel + ProdComp => ProdComp.Component ); } @@ -64,7 +64,7 @@ namespace ComputerShopDatabaseImplement.Models UserId = Model.UserId, ShipmentId = Model.ShipmentId, ProductName = Model.ProductName, - Price = Model.Price, + Price = Price, Warranty = Model.Warranty, Components = Components, }; @@ -87,15 +87,17 @@ namespace ComputerShopDatabaseImplement.Models UserId = UserId, ShipmentId = ShipmentId, ProviderName = Shipment?.ProviderName, + ProductName = ProductName, Price = Price, Warranty = Warranty, - ProductComponents = ProductComponents, + ProductComponents = ProductComponents.ToDictionary(x => x.Key, x => x.Value.ViewModel), }; public void UpdateComponents(ComputerShopDatabase Context, ProductBindingModel Model) { // Сначала подсчитывается новая цена, т.к. Model.ProductComponents далее может измениться double NewPrice = Context.Components + .ToList() .Where(x => Model.ProductComponents.ContainsKey(x.Id)) .Sum(x => x.Cost); diff --git a/ComputerShopGuarantorApp/ApiUser.cs b/ComputerShopGuarantorApp/ApiUser.cs index d03f794..31c69ea 100644 --- a/ComputerShopGuarantorApp/ApiUser.cs +++ b/ComputerShopGuarantorApp/ApiUser.cs @@ -13,7 +13,7 @@ namespace ComputerShopGuarantorApp public static void Connect(IConfiguration Configuration) { - _client.BaseAddress = new Uri(Configuration["IPAddress"]); + _client.BaseAddress = new Uri(Configuration["IpAddress"]); _client.DefaultRequestHeaders.Accept.Clear(); _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); } diff --git a/ComputerShopGuarantorApp/Controllers/HomeController.cs b/ComputerShopGuarantorApp/Controllers/HomeController.cs index 819565d..e603287 100644 --- a/ComputerShopGuarantorApp/Controllers/HomeController.cs +++ b/ComputerShopGuarantorApp/Controllers/HomeController.cs @@ -1,4 +1,6 @@ -using ComputerShopGuarantorApp.Models; +using ComputerShopContracts.BindingModels; +using ComputerShopContracts.ViewModels; +using ComputerShopGuarantorApp.Models; using Microsoft.AspNetCore.Mvc; using System.Diagnostics; @@ -13,14 +15,297 @@ namespace ComputerShopGuarantorApp.Controllers _logger = logger; } - public IActionResult Index() - { - return View(); + public IActionResult Index() + { + if (ApiUser.User == null) + { + return Redirect("~/Home/Enter"); + } + return View(); + } + + /*------------------------------------------------------ + * Комплектующие + *-----------------------------------------------------*/ + + public IActionResult Components() + { + if (ApiUser.User == null) + return Redirect("~/Home/Enter"); + + return View(ApiUser.GetRequest>($"api/component/getcomponents?userId={ApiUser.User.Id}")); + } + + public IActionResult CreateComponent() + { + return View("Component"); + } + + [HttpPost] + public void CreateComponent(string ComponentName, double Cost) + { + if (ApiUser.User == null) + throw new Exception("Вход только авторизованным"); + + ApiUser.PostRequest("api/component/createcomponent", new ComponentBindingModel + { + UserId = ApiUser.User.Id, + ComponentName = ComponentName, + Cost = Cost, + }); + Response.Redirect("Components"); + } + + public IActionResult UpdateComponent(int Id) + { + if (ApiUser.User == null) + return Redirect("~/Home/Enter"); + + return View("Component", ApiUser.GetRequest($"api/component/getcomponent?id={Id}")); + } + + [HttpPost] + public void UpdateComponent(int Id, string ComponentName, double Cost) + { + if (ApiUser.User == null) + throw new Exception("Вход только авторизованным"); + + if (Id == 0) + throw new Exception("Комплектующая не указана"); + + if (string.IsNullOrEmpty(ComponentName)) + throw new Exception("Наименование комплектующей не указано"); + + if (Cost <= 0.0) + throw new Exception("Стоимость должна быть больше нуля"); + + ApiUser.PostRequest("api/component/updatecomponent", new ComponentBindingModel + { + Id = Id, + UserId = ApiUser.User.Id, + ComponentName = ComponentName, + Cost = Cost, + }); + Response.Redirect("../Components"); + } + + public void DeleteComponent(int Id) + { + ApiUser.PostRequest($"api/component/deletecomponent", new ComponentBindingModel { Id = Id }); + Response.Redirect("../Components"); } + /*------------------------------------------------------ + * Сборки + *-----------------------------------------------------*/ + + public IActionResult Assemblies() + { + if (ApiUser.User == null) + return Redirect("~/Home/Enter"); + + var Assemblies = ApiUser.GetRequest>($"api/assembly/getassemblies?userId={ApiUser.User.Id}"); + return View(Assemblies); + } + + public IActionResult CreateAssembly() + { + if (ApiUser.User == null) + throw new Exception("Вход только авторизованным"); + + ViewBag.Components = ApiUser.GetRequest>($"api/component/getcomponents?userId={ApiUser.User.Id}"); + return View("Assembly"); + } + + [HttpPost] + public void CreateAssembly(string AssemblyName, double Price, string Category, List ComponentIds) + { + if (ApiUser.User == null) + throw new Exception("Вход только авторизованным"); + + var SelectedComponents = ComponentIds.ToDictionary(Id => Id, Id => new ComponentBindingModel { Id = Id }); + ApiUser.PostRequest("api/assembly/createassembly", new AssemblyBindingModel + { + UserId = ApiUser.User.Id, + AssemblyName = AssemblyName, + Price = Price, + Category = Category, + AssemblyComponents = SelectedComponents, + }); + Response.Redirect("Assemblies"); + } + + public IActionResult UpdateAssembly(int Id) + { + if (ApiUser.User == null) + return Redirect("~/Home/Enter"); + + ViewBag.Components = ApiUser.GetRequest>($"api/component/getcomponents?userId={ApiUser.User.Id}"); + return View("Assembly", ApiUser.GetRequest($"api/assembly/getassembly?id={Id}")); + } + + [HttpPost] + public void UpdateAssembly(int Id, string AssemblyName, double Price, string Category, List ComponentIds) + { + if (ApiUser.User == null) + throw new Exception("Вход только авторизованным"); + + if (Id == 0) + throw new Exception("Сборка не указана"); + + if (string.IsNullOrEmpty(AssemblyName)) + throw new Exception("Название сборки не указано"); + + if (string.IsNullOrEmpty(Category)) + throw new Exception("Категория не указана"); + + var SelectedComponents = ComponentIds.ToDictionary(Id => Id, Id => new ComponentBindingModel { Id = Id }); + ApiUser.PostRequest("api/assembly/updateassembly", new AssemblyBindingModel + { + Id = Id, + UserId = ApiUser.User.Id, + AssemblyName = AssemblyName, + Price = Price, + Category = Category, + AssemblyComponents = SelectedComponents, + }); + Response.Redirect("../Assemblies"); + } + + public void DeleteAssembly(int Id) + { + ApiUser.PostRequest($"api/assembly/deleteassembly", new AssemblyBindingModel { Id = Id }); + Response.Redirect("../Assemblies"); + } + + /*------------------------------------------------------ + * Товары + *-----------------------------------------------------*/ + + public IActionResult Products() + { + if (ApiUser.User == null) + return Redirect("~/Home/Enter"); + + var Products = ApiUser.GetRequest>($"api/product/getproducts?userId={ApiUser.User.Id}"); + return View(Products); + } + + public IActionResult CreateProduct() + { + if (ApiUser.User == null) + throw new Exception("Вход только авторизованным"); + + ViewBag.Components = ApiUser.GetRequest>($"api/component/getcomponents?userId={ApiUser.User.Id}"); + ViewBag.Shipments = ApiUser.GetRequest>($"api/shipment/getshipments?userId={ApiUser.User.Id}"); + return View("Product"); + } + + [HttpPost] + public void CreateProduct(string ProductName, int ShipmentId, double Price, int Warranty, List ComponentIds) + { + if (ApiUser.User == null) + throw new Exception("Вход только авторизованным"); + + var SelectedComponents = ComponentIds.ToDictionary(Id => Id, Id => new ComponentBindingModel { Id = Id }); + ApiUser.PostRequest("api/product/createproduct", new ProductBindingModel + { + UserId = ApiUser.User.Id, + ShipmentId = ShipmentId != 0 ? ShipmentId : null, + ProductName = ProductName, + Price = Price, + Warranty = Warranty, + ProductComponents = SelectedComponents, + }); + Response.Redirect("Products"); + } + + public IActionResult UpdateProduct(int Id) + { + if (ApiUser.User == null) + return Redirect("~/Home/Enter"); + + ViewBag.Components = ApiUser.GetRequest>($"api/component/getcomponents?userId={ApiUser.User.Id}"); + ViewBag.Shipments = ApiUser.GetRequest>($"api/shipment/getshipments?userId={ApiUser.User.Id}"); + return View("Product", ApiUser.GetRequest($"api/product/getproduct?id={Id}")); + } + + [HttpPost] + public void UpdateProduct(int Id, int ShipmentId, string ProductName, double Price, int Warranty, List ComponentIds) + { + if (ApiUser.User == null) + throw new Exception("Вход только авторизованным"); + + if (Id == 0) + throw new Exception("Товар не указан"); + + if (string.IsNullOrEmpty(ProductName)) + throw new Exception("Название товара не указано"); + + if (Warranty < 0) + throw new Exception("Некорректное значение гарантии"); + + var SelectedComponents = ComponentIds.ToDictionary(Id => Id, Id => new ComponentBindingModel { Id = Id }); + ApiUser.PostRequest("api/product/updateproduct", new ProductBindingModel + { + Id = Id, + UserId = ApiUser.User.Id, + ShipmentId = ShipmentId != 0 ? ShipmentId : null, + ProductName = ProductName, + Price = Price, + Warranty = Warranty, + ProductComponents = SelectedComponents, + }); + Response.Redirect("../Products"); + } + + public void DeleteProduct(int Id) + { + ApiUser.PostRequest($"api/product/deleteproduct", new ProductBindingModel { Id = Id }); + Response.Redirect("../Products"); + } + + /*------------------------------------------------------ + * Отчеты + *-----------------------------------------------------*/ + + + + // ОСТАЛЬНОЕ ОСТАЛЬНОЕ ОСТАЛЬНОЕ ОСТАЛЬНОЕ ОСТАЛЬНОЕ ОСТАЛЬНОЕ ОСТАЛЬНОЕ + + [HttpGet] public IActionResult Privacy() { - return View(); + if (ApiUser.User == null) + { + return Redirect("~/Home/Enter"); + } + return View(ApiUser.User); + } + + [HttpPost] + public void Privacy(string Login, string Password, string Email) + { + if (ApiUser.User == null) + { + throw new Exception("Вход только авторизованным"); + } + if (string.IsNullOrEmpty(Login) || string.IsNullOrEmpty(Password) || string.IsNullOrEmpty(Email)) + { + throw new Exception("Введите логин, пароль и почту"); + } + ApiUser.PostRequest("api/user/updatedata", new UserBindingModel + { + Id = ApiUser.User.Id, + Login = Login, + Password = Password, + Email = Email + }); + + ApiUser.User.Login = Login; + ApiUser.User.Password = Password; + ApiUser.User.Email = Email; + Response.Redirect("Index"); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] @@ -28,5 +313,52 @@ namespace ComputerShopGuarantorApp.Controllers { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } + + public IActionResult Enter() + { + return View(); + } + + [HttpPost] + public void Enter(string Login, string Password) + { + if (string.IsNullOrEmpty(Login) || string.IsNullOrEmpty(Password)) + { + throw new Exception("Введите логин и пароль"); + } + ApiUser.User = ApiUser.GetRequest($"api/user/loginguarantor?login={Login}&password={Password}"); + if (ApiUser.User == null) + { + throw new Exception("Неверный логин или пароль"); + } + Response.Redirect("Index"); + } + + public IActionResult Register() + { + return View(); + } + + [HttpPost] + public void Register(string Login, string Password, string Email) + { + if (string.IsNullOrEmpty(Login) || string.IsNullOrEmpty(Password) || string.IsNullOrEmpty(Email)) + { + throw new Exception("Введите логин, пароль и почту"); + } + ApiUser.PostRequest("api/user/registerguarantor", new UserBindingModel + { + Login = Login, + Password = Password, + Email = Email + }); + ApiUser.User = ApiUser.GetRequest($"api/user/loginguarantor?login={Login}&password={Password}"); + if (ApiUser.User == null) + { + Response.Redirect("Enter"); + } + Response.Redirect("Index"); + return; + } } } diff --git a/ComputerShopGuarantorApp/Program.cs b/ComputerShopGuarantorApp/Program.cs index 385aaf2..81f11e0 100644 --- a/ComputerShopGuarantorApp/Program.cs +++ b/ComputerShopGuarantorApp/Program.cs @@ -18,9 +18,7 @@ if (!App.Environment.IsDevelopment()) App.UseHttpsRedirection(); App.UseStaticFiles(); - App.UseRouting(); - App.UseAuthorization(); App.MapControllerRoute( diff --git a/ComputerShopGuarantorApp/Views/Home/Assemblies.cshtml b/ComputerShopGuarantorApp/Views/Home/Assemblies.cshtml new file mode 100644 index 0000000..f9fb2e0 --- /dev/null +++ b/ComputerShopGuarantorApp/Views/Home/Assemblies.cshtml @@ -0,0 +1,61 @@ +@using ComputerShopContracts.ViewModels; + +@model List +@{ + ViewData["Title"] = "Сборки"; +} + +
+
+

Список сборок

+

Просматривайте список сборок и создавайте новые, а также выбирайте сборку для изменения или удаления

+
+ + @{ + if (Model == null) + { +

Авторизируйтесь

+ return; + } +

+ Создать сборку +

+ + + + + + + + + + + + + @foreach (var Item in Model) + { + + + + + + + + + } + +
НомерНазваниеЦенаКатегория
+ @Html.DisplayFor(ModelItem => Item.Id) + + @Html.DisplayFor(ModelItem => Item.AssemblyName) + + @Html.DisplayFor(ModelItem => Item.Price) + + @Html.DisplayFor(ModelItem => Item.Category) + + + + +
+ } +
diff --git a/ComputerShopGuarantorApp/Views/Home/Assembly.cshtml b/ComputerShopGuarantorApp/Views/Home/Assembly.cshtml new file mode 100644 index 0000000..95ef8f7 --- /dev/null +++ b/ComputerShopGuarantorApp/Views/Home/Assembly.cshtml @@ -0,0 +1,61 @@ +@using ComputerShopContracts.ViewModels; + +@model AssemblyViewModel + +@{ + ViewData["Title"] = "Сборка"; +} + +
+
+ @if (Model == null) + { +

Создание сборки

+ } + else + { +

Редактирование сборки

+ } +
+ +
+
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+
+
+ +
+
+
+
diff --git a/ComputerShopGuarantorApp/Views/Home/Component.cshtml b/ComputerShopGuarantorApp/Views/Home/Component.cshtml new file mode 100644 index 0000000..48ede93 --- /dev/null +++ b/ComputerShopGuarantorApp/Views/Home/Component.cshtml @@ -0,0 +1,39 @@ +@using ComputerShopContracts.ViewModels; + +@model ComponentViewModel + +@{ + ViewData["Title"] = "Комплектующая"; +} + +
+
+ @if (Model == null) + { +

Создание комплектующей

+ } + else + { +

Редактирование комплектующей

+ } +
+ +
+
+ + +
+ +
+ + +
+ +
+
+
+ +
+
+
+
diff --git a/ComputerShopGuarantorApp/Views/Home/Components.cshtml b/ComputerShopGuarantorApp/Views/Home/Components.cshtml new file mode 100644 index 0000000..068a636 --- /dev/null +++ b/ComputerShopGuarantorApp/Views/Home/Components.cshtml @@ -0,0 +1,57 @@ +@using ComputerShopContracts.ViewModels; + +@model List +@{ + ViewData["Title"] = "Комплектующие"; +} + +
+
+

Список комплектующих

+

Просматривайте список комплектующих и добавляйте новые, а также выбирайте комплектующую для изменения или удаления

+
+ + @{ + if (Model == null) + { +

Авторизируйтесь

+ return; + } +

+ Создать комплектующую +

+ + + + + + + + + + + + @foreach (var Item in Model) + { + + + + + + + + } + +
НомерНаименованиеСтоимость
+ @Html.DisplayFor(ModelItem => Item.Id) + + @Html.DisplayFor(ModelItem => Item.ComponentName) + + @Html.DisplayFor(ModelItem => Item.Cost) + + + + +
+ } +
diff --git a/ComputerShopGuarantorApp/Views/Home/Enter.cshtml b/ComputerShopGuarantorApp/Views/Home/Enter.cshtml new file mode 100644 index 0000000..c1e7068 --- /dev/null +++ b/ComputerShopGuarantorApp/Views/Home/Enter.cshtml @@ -0,0 +1,54 @@ +@{ + ViewData["Title"] = "Вход"; +} + +
+
+

Вход в аккаунт

+

Войдите в ваш аккаунт чтобы иметь доступ к комплектующим, сборкам и товарам

+
+ +
+
+
+
+
+ +

Вход

+
+ +
+ +
+ + +
+ + +
+ + +
+ +
+
+ +
+
+ + +
+
+

Забыли пароль?

+
+
+ +
+ +
+
+
+
+
+
+
diff --git a/ComputerShopGuarantorApp/Views/Home/Index.cshtml b/ComputerShopGuarantorApp/Views/Home/Index.cshtml index d2d19bd..bdcd2a7 100644 --- a/ComputerShopGuarantorApp/Views/Home/Index.cshtml +++ b/ComputerShopGuarantorApp/Views/Home/Index.cshtml @@ -3,6 +3,6 @@ }
-

Welcome

-

Learn about building Web apps with ASP.NET Core.

+

Добро пожаловать в приложение поручителя магазина "Ты ж программист"

+

Выберите страницу из верхнего меню

diff --git a/ComputerShopGuarantorApp/Views/Home/Product.cshtml b/ComputerShopGuarantorApp/Views/Home/Product.cshtml new file mode 100644 index 0000000..4515873 --- /dev/null +++ b/ComputerShopGuarantorApp/Views/Home/Product.cshtml @@ -0,0 +1,78 @@ +@using ComputerShopContracts.ViewModels; + +@model ProductViewModel + +@{ + ViewData["Title"] = "Товар"; +} + +
+
+ @if (Model == null) + { +

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

+ } + else + { +

Редактирование товара

+ } +
+ +
+
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+
+
+ +
+
+
+
diff --git a/ComputerShopGuarantorApp/Views/Home/Products.cshtml b/ComputerShopGuarantorApp/Views/Home/Products.cshtml new file mode 100644 index 0000000..dd43f68 --- /dev/null +++ b/ComputerShopGuarantorApp/Views/Home/Products.cshtml @@ -0,0 +1,66 @@ +@using ComputerShopContracts.ViewModels; + +@model List + +@{ + ViewData["Title"] = "Товары"; +} + +
+
+

Список товаров

+

Просматривайте список товаров и добавляйте новые, а также выбирайте товар для изменения или удаления

+
+ + @{ + if (Model == null) + { +

Авторизируйтесь

+ return; + } +

+ Добавить товар +

+ + + + + + + + + + + + + + @foreach (var Item in Model) + { + + + + + + + + + + } + +
НомерНазваниеПоставщикЦенаГарантия
+ @Html.DisplayFor(ModelItem => Item.Id) + + @Html.DisplayFor(ModelItem => Item.ProductName) + + @Html.DisplayFor(ModelItem => Item.ProviderName) + + @Html.DisplayFor(ModelItem => Item.Price) + + @Html.DisplayFor(ModelItem => Item.Warranty) + + + + +
+ } +
diff --git a/ComputerShopGuarantorApp/Views/Home/Register.cshtml b/ComputerShopGuarantorApp/Views/Home/Register.cshtml new file mode 100644 index 0000000..a1c1b89 --- /dev/null +++ b/ComputerShopGuarantorApp/Views/Home/Register.cshtml @@ -0,0 +1,60 @@ +@{ + ViewData["Title"] = "Регистрация"; +} + +
+
+

Регистрация аккаунта

+

Зарегистрируйте аккаунт поручителя, чтобы управлять комплектующими, сборками и товарами

+
+ +
+
+
+
+
+ +

Регистрация

+
+ +
+ +
+ + +
+ + +
+ + +
+ + +
+ + +
+ +
+
+ +
+
+ + +
+
+

Забыли пароль?

+
+
+ +
+ +
+
+
+
+
+
+
diff --git a/ComputerShopGuarantorApp/Views/Shared/_Layout.cshtml b/ComputerShopGuarantorApp/Views/Shared/_Layout.cshtml index c77bae2..e3e9b14 100644 --- a/ComputerShopGuarantorApp/Views/Shared/_Layout.cshtml +++ b/ComputerShopGuarantorApp/Views/Shared/_Layout.cshtml @@ -5,14 +5,18 @@ @ViewData["Title"] - Поручитель + - +
-