Compare commits

..

No commits in common. "main" and "dev-implementer" have entirely different histories.

47 changed files with 105 additions and 2173 deletions

View File

@ -102,6 +102,9 @@ 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

View File

@ -110,6 +110,9 @@ 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));

View File

@ -1,7 +1,6 @@
using ComputerShopBusinessLogic.OfficePackage;
using ComputerShopBusinessLogic.OfficePackage.HelperModels;
using ComputerShopContracts.BindingModels;
using ComputerShopContracts.BindingModels;
using ComputerShopContracts.BusinessLogicContracts;
using ComputerShopContracts.SearchModels;
using ComputerShopContracts.StorageContracts;
using ComputerShopContracts.ViewModels;
@ -11,70 +10,35 @@ namespace ComputerShopBusinessLogic.BusinessLogics
{
private readonly IComponentStorage _componentStorage;
private readonly AbstractSaveToExcelGuarantor _saveToExcel;
private readonly AbstractSaveToWordGuarantor _saveToWord;
private readonly AbstractSaveToPdfGuarantor _saveToPdf;
public ReportGuarantorLogic(IComponentStorage ComponentStorage,
AbstractSaveToExcelGuarantor SaveToExcel, AbstractSaveToWordGuarantor SaveToWord, AbstractSaveToPdfGuarantor SaveToPdf)
public ReportGuarantorLogic(IComponentStorage ComponentStorage)
{
_componentStorage = ComponentStorage;
_saveToExcel = SaveToExcel;
_saveToWord = SaveToWord;
_saveToPdf = SaveToPdf;
}
/// <summary>
/// Получение отчёта для Word или Excel
/// </summary>
public List<ReportComponentWithShipmentViewModel> GetReportComponentsWithShipments(List<int> SelectedComponentIds)
public List<ReportComponentWithShipmentViewModel> GetReportComponentsWithShipments(List<ComponentSearchModel> SelectedComponents)
{
return _componentStorage.GetComponentsWithShipments(SelectedComponentIds);
return _componentStorage.GetComponentsWithShipments(SelectedComponents);
}
/// <summary>
/// Получение отчёта для отправки на почту
/// </summary>
public List<ReportComponentByDateViewModel> GetReportComponentsByRequestDate(ReportBindingModel Model)
public List<ReportComponentByDateViewModel> GetReportComponentsByRequestDate(UserSearchModel CurrentUser, ReportBindingModel Report)
{
return _componentStorage.GetComponentsByShipmentDate(Model);
return _componentStorage.GetComponentsByShipmentDate(Report, CurrentUser);
}
public void SaveReportToWordFile(ReportBindingModel Model)
{
_saveToWord.CreateDoc(new WordInfoGuarantor
{
Filename = Model.FileName,
Title = "Список партий товаров по выбранным компонентам",
ShipmentComponents = GetReportComponentsWithShipments(Model.Ids!)
});
throw new NotImplementedException();
}
public void SaveReportToExcelFile(ReportBindingModel Model)
{
_saveToExcel.CreateReport(new ExcelInfoGuarantor
{
Filename = Model.FileName,
ShipmentComponents = GetReportComponentsWithShipments(Model.Ids!)
});
}
public void SaveReportComponentsByRequestDateToPdfFile(ReportBindingModel Model)
{
if (Model.DateFrom == null)
throw new ArgumentException("Дата начала не задана");
if (Model.DateTo == null)
throw new ArgumentException("Дата окончания не задана");
_saveToPdf.CreateDoc(new PdfInfoGuarantor
{
Filename = Model.FileName,
Title = "Отчёт по комплектующим за период",
DateFrom = Model.DateFrom!.Value,
DateTo = Model.DateTo!.Value,
ComponentsByDate = GetReportComponentsByRequestDate(Model)
});
throw new NotImplementedException();
}
}
}

View File

@ -1,150 +0,0 @@
using ComputerShopBusinessLogic.OfficePackage.HelperEnums;
using ComputerShopBusinessLogic.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
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "F",
RowIndex = RowIndex,
Text = Shipment.ProductName,
StyleInfo = ExcelStyleInfoType.Text
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "G",
RowIndex = RowIndex,
Text = Shipment.ProductPrice.ToString(),
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);
}
}

View File

@ -1,55 +0,0 @@
using ComputerShopBusinessLogic.OfficePackage.HelperEnums;
using ComputerShopBusinessLogic.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<string> { "3cm", "2cm", "2cm", "2cm", "2cm", "2cm", "2.5cm", "2.5cm", "3cm", "4cm" });
CreateRow(new PdfRowParameters
{
Texts = new List<string> { "ID комплектующей", "Название", "Стоимость", "ID сборки", "Название сборки", "Цена сборки", "Категория", "ID заявки", "Дата заявки", "Клиент" },
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
foreach (var ComponentByDate in Info.ComponentsByDate)
{
CreateRow(new PdfRowParameters
{
Texts = new List<string>
{
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,
},
});
}
SavePdf(Info);
}
protected abstract void CreatePdf(DocumentInfo Info);
protected abstract void CreateParagraph(PdfParagraph Paragraph);
protected abstract void CreateTable(List<string> Columns);
protected abstract void CreateRow(PdfRowParameters RowParameters);
protected abstract void SavePdf(DocumentInfo Info);
}
}

View File

@ -1,83 +0,0 @@
using ComputerShopBusinessLogic.OfficePackage.HelperEnums;
using ComputerShopBusinessLogic.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" }),
(Shipment.ProductName + " - ", new WordTextProperties { Size = "24" }),
(Shipment.ProductPrice.ToString(), new WordTextProperties { Size = "24" }),
},
TextProperties = new WordTextProperties
{
Size = "24",
JustificationType = WordJustificationType.Both
}
});
}
}
}
SaveWord(Info);
}
/// <summary>
/// Создание doc-файла
/// </summary>
/// <param name="info"></param>
protected abstract void CreateWord(DocumentInfo Info);
/// <summary>
/// Создание абзаца с текстом
/// </summary>
/// <param name="paragraph"></param>
/// <returns></returns>
protected abstract void CreateParagraph(WordParagraph paragraph);
/// <summary>
/// Сохранение файла
/// </summary>
/// <param name="info"></param>
protected abstract void SaveWord(DocumentInfo Info);
}
}

View File

@ -1,23 +0,0 @@
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<ReportComponentWithShipmentViewModel> ShipmentComponents { get; set; } = new();
}
}

View File

@ -1,9 +0,0 @@
namespace ComputerShopBusinessLogic.OfficePackage.HelperModels
{
public class DocumentInfo
{
public string Filename { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
}
}

View File

@ -1,13 +0,0 @@
using ComputerShopContracts.ViewModels;
namespace ComputerShopBusinessLogic.OfficePackage.HelperModels
{
public class PdfInfoGuarantor : DocumentInfo
{
public DateTime DateFrom { get; set; }
public DateTime DateTo { get; set; }
public List<ReportComponentByDateViewModel> ComponentsByDate { get; set; } = new();
}
}

View File

@ -1,9 +0,0 @@
using ComputerShopContracts.ViewModels;
namespace ComputerShopBusinessLogic.OfficePackage.HelperModels
{
public class WordInfoGuarantor : DocumentInfo
{
public List<ReportComponentWithShipmentViewModel> ShipmentComponents { get; set; } = new();
}
}

View File

@ -1,291 +0,0 @@
using ComputerShopBusinessLogic.OfficePackage.HelperEnums;
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;
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<WorkbookStylesPart>();
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<SharedStringTablePart>().Any()
? _spreadsheetDocument.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First()
: _spreadsheetDocument.WorkbookPart.AddNewPart<SharedStringTablePart>();
if (_shareStringPart.SharedStringTable == null)
{
_shareStringPart.SharedStringTable = new SharedStringTable();
}
var worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
Columns lstColumns = worksheetPart.Worksheet.GetFirstChild<Columns>();
if (lstColumns == null)
{
lstColumns = new Columns();
}
lstColumns.Append(new Column() { Min = 1, Max = 1, Width = 20, CustomWidth = true });
lstColumns.Append(new Column() { Min = 2, Max = 2, Width = 20, CustomWidth = true });
lstColumns.Append(new Column() { Min = 3, Max = 3, Width = 20, CustomWidth = true });
lstColumns.Append(new Column() { Min = 4, Max = 4, Width = 20, CustomWidth = true });
lstColumns.Append(new Column() { Min = 5, Max = 5, Width = 20, CustomWidth = true });
lstColumns.Append(new Column() { Min = 6, Max = 6, Width = 25, 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<SheetData>();
if (sheetData == null)
{
return;
}
Row row;
if (sheetData.Elements<Row>().Where(r => r.RowIndex! == ExcelParams.RowIndex).Any())
{
row = sheetData.Elements<Row>().Where(r => r.RowIndex! == ExcelParams.RowIndex).First();
}
else
{
row = new Row() { RowIndex = ExcelParams.RowIndex };
sheetData.Append(row);
}
Cell cell;
if (row.Elements<Cell>().Where(c => c.CellReference!.Value == ExcelParams.CellReference).Any())
{
cell = row.Elements<Cell>().Where(c => c.CellReference!.Value == ExcelParams.CellReference).First();
}
else
{
Cell? refCell = null;
foreach (Cell rowCell in row.Elements<Cell>())
{
if (string.Compare(rowCell.CellReference!.Value, ExcelParams.CellReference, true) > 0)
{
refCell = rowCell;
break;
}
}
var newCell = new Cell() { CellReference = ExcelParams.CellReference };
row.InsertBefore(newCell, refCell);
cell = newCell;
}
_shareStringPart.SharedStringTable.AppendChild(new SharedStringItem(new Text(ExcelParams.Text)));
_shareStringPart.SharedStringTable.Save();
cell.CellValue = new CellValue((_shareStringPart.SharedStringTable.Elements<SharedStringItem>().Count() - 1).ToString());
cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
cell.StyleIndex = GetStyleValue(ExcelParams.StyleInfo);
}
protected override void MergeCells(ExcelMergeParameters ExcelParams)
{
if (_worksheet == null)
{
return;
}
MergeCells MergeCells;
if (_worksheet.Elements<MergeCells>().Any())
{
MergeCells = _worksheet.Elements<MergeCells>().First();
}
else
{
MergeCells = new MergeCells();
if (_worksheet.Elements<CustomSheetView>().Any())
{
_worksheet.InsertAfter(MergeCells, _worksheet.Elements<CustomSheetView>().First());
}
else
{
_worksheet.InsertAfter(MergeCells, _worksheet.Elements<SheetData>().First());
}
}
var MergeCell = new MergeCell()
{
Reference = new StringValue(ExcelParams.Merge)
};
MergeCells.Append(MergeCell);
}
protected override void SaveExcel(DocumentInfo Info)
{
if (_spreadsheetDocument == null)
{
return;
}
_spreadsheetDocument.WorkbookPart!.Workbook.Save();
_spreadsheetDocument.Close();
}
}
}

View File

@ -1,109 +0,0 @@
using ComputerShopBusinessLogic.OfficePackage.HelperEnums;
using ComputerShopBusinessLogic.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 = 10;
style = document.Styles.AddStyle("NormalTitle", "Normal");
style.Font.Bold = true;
}
protected override void CreatePdf(HelperModels.DocumentInfo Info)
{
_document = new Document();
_document.DefaultPageSetup.Orientation = Orientation.Landscape;
DefineStyles(_document);
_section = _document.AddSection();
}
protected override void CreateParagraph(PdfParagraph pdfParagraph)
{
if (_section == null)
{
return;
}
var paragraph = _section.AddParagraph(pdfParagraph.Text);
paragraph.Format.SpaceAfter = "0.5cm";
paragraph.Format.Alignment = GetParagraphAlignment(pdfParagraph.ParagraphAlignment);
paragraph.Style = pdfParagraph.Style;
}
protected override void CreateTable(List<string> 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);
}
}
}

View File

@ -1,121 +0,0 @@
using ComputerShopBusinessLogic.OfficePackage.HelperEnums;
using ComputerShopBusinessLogic.OfficePackage.HelperModels;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
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,
};
}
/// <summary>
/// Настройки страницы
/// </summary>
/// <returns></returns>
private static SectionProperties CreateSectionProperties()
{
var Properties = new SectionProperties();
var PageSize = new PageSize
{
Orient = PageOrientationValues.Portrait
};
Properties.AppendChild(PageSize);
return Properties;
}
/// <summary>
/// Задание форматирования для абзаца
/// </summary>
/// <param name="ParagraphProperties"></param>
/// <returns></returns>
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();
}
}
}

View File

@ -14,6 +14,8 @@ namespace ComputerShopContracts.BindingModels
public string Category { get; set; } = string.Empty;
public Dictionary<int, ComponentBindingModel> AssemblyComponents { get; set; } = new();
public Dictionary<int, IComponentModel> AssemblyComponents { get; set; } = new();
public Dictionary<int, int> Test { get; set; } = new();
}
}

View File

@ -16,6 +16,6 @@ namespace ComputerShopContracts.BindingModels
public int Warranty { get; set; }
public Dictionary<int, ComponentBindingModel> ProductComponents { get; set; } = new();
public Dictionary<int, IComponentModel> ProductComponents { get; set; } = new();
}
}

View File

@ -1,4 +1,5 @@
using ComputerShopContracts.BindingModels;
using ComputerShopContracts.SearchModels;
using ComputerShopContracts.ViewModels;
namespace ComputerShopContracts.BusinessLogicContracts
@ -8,17 +9,15 @@ namespace ComputerShopContracts.BusinessLogicContracts
/// <summary>
/// Получение отчёта для Word или Excel
/// </summary>
List<ReportComponentWithShipmentViewModel> GetReportComponentsWithShipments(List<int> SelectedComponentIds);
List<ReportComponentWithShipmentViewModel> GetReportComponentsWithShipments(List<ComponentSearchModel> SelectedComponents);
/// <summary>
/// Получение отчёта для отправки на почту
/// </summary>
List<ReportComponentByDateViewModel> GetReportComponentsByRequestDate(ReportBindingModel Model);
List<ReportComponentByDateViewModel> GetReportComponentsByRequestDate(UserSearchModel CurrentUser, ReportBindingModel Report);
void SaveReportToWordFile(ReportBindingModel Model);
void SaveReportToExcelFile(ReportBindingModel Model);
void SaveReportComponentsByRequestDateToPdfFile(ReportBindingModel Model);
}
}

View File

@ -18,8 +18,8 @@ namespace ComputerShopContracts.StorageContracts
ComponentViewModel? Delete(ComponentBindingModel Model);
List<ReportComponentWithShipmentViewModel> GetComponentsWithShipments(List<int> ComponentIds);
List<ReportComponentWithShipmentViewModel> GetComponentsWithShipments(List<ComponentSearchModel> Models);
List<ReportComponentByDateViewModel> GetComponentsByShipmentDate(ReportBindingModel ReportModel);
List<ReportComponentByDateViewModel> GetComponentsByShipmentDate(ReportBindingModel ReportModel, UserSearchModel UserModel);
}
}

View File

@ -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<int, ComponentViewModel> AssemblyComponents { get; set; } = new();
}
public Dictionary<int, IComponentModel> AssemblyComponents { get; set; } = new();
}
}

View File

@ -23,6 +23,6 @@ namespace ComputerShopContracts.ViewModels
[DisplayName("Гарантия (мес.)")]
public int Warranty { get; set; }
public Dictionary<int, ComponentViewModel> ProductComponents { get; set; } = new();
public Dictionary<int, IComponentModel> ProductComponents { get; set; } = new();
}
}

View File

@ -8,6 +8,6 @@
public double ComponentCost { get; set; }
public List<(string ProductName, double ProductPrice, string ProviderName, DateTime ShipmentDate)> Shipments { get; set; } = new();
public List<(int Count, string ProductName, double ProductPrice, string ProviderName, DateTime ShipmentDate)> Shipments { get; set; } = new();
}
}

View File

@ -24,5 +24,10 @@
/// Категория
/// </summary>
string Category { get; }
/// <summary>
/// Список комплектующих
/// </summary>
Dictionary<int, IComponentModel> AssemblyComponents { get; }
}
}

View File

@ -25,6 +25,11 @@
/// </summary>
int Warranty { get; }
/// <summary>
/// Список комплектующих
/// </summary>
Dictionary<int, IComponentModel> ProductComponents { get; }
/// <summary>
/// Привязка товара к партии товаров
/// </summary>

View File

@ -88,7 +88,7 @@ namespace ComputerShopDatabaseImplement.Implements
return ExistingComponent.ViewModel;
}
public List<ReportComponentWithShipmentViewModel> GetComponentsWithShipments(List<int> ComponentIds)
public List<ReportComponentWithShipmentViewModel> GetComponentsWithShipments(List<ComponentSearchModel> Models)
{
using var Context = new ComputerShopDatabase();
@ -96,9 +96,9 @@ namespace ComputerShopDatabaseImplement.Implements
.Include(x => x.ProductComponents)
.ThenInclude(x => x.Product)
.ThenInclude(x => x.Shipment)
.Where(x =>
ComponentIds.Contains(x.Id) // Компонент, указанный пользователем,
)//&& x.ProductComponents.Any(y => y.Product.Shipment != null)) // который содержится в товаре, имеющем партию товаров
.Where(x =>
Models.Select(x => x.Id).Contains(x.Id) // Компонент, указанный пользователем,
&& x.ProductComponents.Any(y => y.Product.Shipment != null)) // который содержится в товаре, имеющем партию товаров
.ToList()
.Select(x => new ReportComponentWithShipmentViewModel
{
@ -106,19 +106,18 @@ namespace ComputerShopDatabaseImplement.Implements
ComponentName = x.ComponentName,
ComponentCost = x.Cost,
Shipments = x.ProductComponents
.Where(y => y.Product.Shipment != null)
.Select(y => (y.Product.ProductName, y.Product.Price, y.Product.Shipment!.ProviderName, y.Product.Shipment.DateShipment))
.Select(y => (0, y.Product.ProductName, y.Product.Price, y.Product.Shipment!.ProviderName, y.Product.Shipment.DateShipment))
.ToList(),
})
.ToList();
.ToList();
}
public List<ReportComponentByDateViewModel> GetComponentsByShipmentDate(ReportBindingModel ReportModel)
public List<ReportComponentByDateViewModel> GetComponentsByShipmentDate(ReportBindingModel ReportModel, UserSearchModel UserModel)
{
using var Context = new ComputerShopDatabase();
return Context.Components
.Where(c => c.UserId == ReportModel.UserId)
.Where(c => c.UserId == UserModel.Id)
.Include(c => c.AssemblyComponents)
.ThenInclude(ac => ac.Assembly)
.ThenInclude(a => a.Requests.Where(r => r.DateRequest >= ReportModel.DateFrom && r.DateRequest <= ReportModel.DateTo))

View File

@ -28,10 +28,10 @@ namespace ComputerShopDatabaseImplement.Models
[ForeignKey("AssemblyId")]
public virtual List<AssemblyComponent> Components { get; set; } = new();
private Dictionary<int, Component>? _assemblyComponents;
private Dictionary<int, IComponentModel>? _assemblyComponents;
[NotMapped]
public Dictionary<int, Component> AssemblyComponents
public Dictionary<int, IComponentModel> AssemblyComponents
{
get
{
@ -39,7 +39,7 @@ namespace ComputerShopDatabaseImplement.Models
{
_assemblyComponents = Components.ToDictionary(
AsmComp => AsmComp.ComponentId,
AsmComp => AsmComp.Component
AsmComp => AsmComp.Component as IComponentModel
);
}
@ -88,14 +88,13 @@ namespace ComputerShopDatabaseImplement.Models
AssemblyName = AssemblyName,
Price = Price,
Category = Category,
AssemblyComponents = AssemblyComponents.ToDictionary(x => x.Key, x => x.Value.ViewModel),
AssemblyComponents = AssemblyComponents,
};
public void UpdateComponents(ComputerShopDatabase Context, AssemblyBindingModel Model)
{
// Сначала подсчитывается новая цена, т.к. Model.AssemblyComponents далее может измениться
double NewPrice = Context.Components
.ToList()
// Сначала подсчитывается новая цена, т.к. Model.AssemblyComponents далее может измениться
double NewPrice = Context.Components
.Where(x => Model.AssemblyComponents.ContainsKey(x.Id))
.Sum(x => x.Cost);
@ -133,5 +132,21 @@ namespace ComputerShopDatabaseImplement.Models
_assemblyComponents = null;
}
private void CalculatePrice(
ComputerShopDatabase Context,
Dictionary<int, IComponentModel> ModelComponents,
out List<AssemblyComponent> 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);
}
}
}

View File

@ -29,10 +29,10 @@ namespace ComputerShopDatabaseImplement.Models
[ForeignKey("ProductId")]
public virtual List<ProductComponent> Components { get; set; } = new();
private Dictionary<int, Component>? _productComponents;
private Dictionary<int, IComponentModel>? _productComponents;
[NotMapped]
public Dictionary<int, Component> ProductComponents
public Dictionary<int, IComponentModel> ProductComponents
{
get
{
@ -40,7 +40,7 @@ namespace ComputerShopDatabaseImplement.Models
{
_productComponents = Components.ToDictionary(
ProdComp => ProdComp.ComponentId,
ProdComp => ProdComp.Component
ProdComp => ProdComp.Component as IComponentModel
);
}
@ -64,7 +64,7 @@ namespace ComputerShopDatabaseImplement.Models
UserId = Model.UserId,
ShipmentId = Model.ShipmentId,
ProductName = Model.ProductName,
Price = Price,
Price = Model.Price,
Warranty = Model.Warranty,
Components = Components,
};
@ -87,17 +87,15 @@ namespace ComputerShopDatabaseImplement.Models
UserId = UserId,
ShipmentId = ShipmentId,
ProviderName = Shipment?.ProviderName,
ProductName = ProductName,
Price = Price,
Warranty = Warranty,
ProductComponents = ProductComponents.ToDictionary(x => x.Key, x => x.Value.ViewModel),
ProductComponents = ProductComponents,
};
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);

View File

@ -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"));
}

View File

@ -11,9 +11,7 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ComputerShopBusinessLogic\ComputerShopBusinessLogic.csproj" />
<ProjectReference Include="..\ComputerShopContracts\ComputerShopContracts.csproj" />
<ProjectReference Include="..\ComputerShopDatabaseImplement\ComputerShopDatabaseImplement.csproj" />
</ItemGroup>
</Project>

View File

@ -1,7 +1,4 @@
using ComputerShopContracts.BindingModels;
using ComputerShopContracts.BusinessLogicContracts;
using ComputerShopContracts.ViewModels;
using ComputerShopGuarantorApp.Models;
using ComputerShopGuarantorApp.Models;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
@ -10,470 +7,20 @@ namespace ComputerShopGuarantorApp.Controllers
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly IReportGuarantorLogic _reportLogic;
public HomeController(ILogger<HomeController> logger, IReportGuarantorLogic ReportLogic)
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
_reportLogic = ReportLogic;
}
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<List<ComponentViewModel>>($"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<ComponentViewModel>($"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");
}
[HttpPost]
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<List<AssemblyViewModel>>($"api/assembly/getassemblies?userId={ApiUser.User.Id}");
return View(Assemblies);
}
public IActionResult CreateAssembly()
{
if (ApiUser.User == null)
throw new Exception("Вход только авторизованным");
ViewBag.Components = ApiUser.GetRequest<List<ComponentViewModel>>($"api/component/getcomponents?userId={ApiUser.User.Id}");
return View("Assembly");
}
[HttpPost]
public void CreateAssembly(string AssemblyName, double Price, string Category, List<int> 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<List<ComponentViewModel>>($"api/component/getcomponents?userId={ApiUser.User.Id}");
return View("Assembly", ApiUser.GetRequest<AssemblyViewModel>($"api/assembly/getassembly?id={Id}"));
}
[HttpPost]
public void UpdateAssembly(int Id, string AssemblyName, double Price, string Category, List<int> 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");
}
[HttpPost]
public void DeleteAssembly(int Id)
public IActionResult Index()
{
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<List<ProductViewModel>>($"api/product/getproducts?userId={ApiUser.User.Id}");
return View(Products);
}
public IActionResult CreateProduct()
{
if (ApiUser.User == null)
throw new Exception("Вход только авторизованным");
ViewBag.Components = ApiUser.GetRequest<List<ComponentViewModel>>($"api/component/getcomponents?userId={ApiUser.User.Id}");
ViewBag.Shipments = ApiUser.GetRequest<List<ShipmentViewModel>>($"api/shipment/getshipments?userId=-1");
return View("Product");
}
[HttpPost]
public void CreateProduct(string ProductName, int ShipmentId, double Price, int Warranty, List<int> 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<List<ComponentViewModel>>($"api/component/getcomponents?userId={ApiUser.User.Id}");
ViewBag.Shipments = ApiUser.GetRequest<List<ShipmentViewModel>>($"api/shipment/getshipments?userId=-1");
return View("Product", ApiUser.GetRequest<ProductViewModel>($"api/product/getproduct?id={Id}"));
}
[HttpPost]
public void UpdateProduct(int Id, int ShipmentId, string ProductName, double Price, int Warranty, List<int> 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");
}
[HttpPost]
public void DeleteProduct(int Id)
{
ApiUser.PostRequest($"api/product/deleteproduct", new ProductBindingModel { Id = Id });
Response.Redirect("../Products");
}
/*------------------------------------------------------
* Отчеты
*-----------------------------------------------------*/
public IActionResult ReportComponentsWithShipments()
{
if (ApiUser.User == null)
return Redirect("~/Home/Enter");
ViewBag.Components = ApiUser.GetRequest<List<ComponentViewModel>>($"api/component/getcomponents?userId={ApiUser.User.Id}");
return View();
}
public IActionResult GetWordFile()
{
return PhysicalFile("C:\\!КУРСОВАЯ\\Партии товаров по выбранным компонентам.docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "Партии товаров по выбранным компонентам.docx");
}
public IActionResult GetExcelFile()
{
return PhysicalFile("C:\\!КУРСОВАЯ\\Партии товаров по выбранным компонентам.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Партии товаров по выбранным компонентам.xlsx");
}
[HttpPost]
public IActionResult ReportComponentsWithShipments(int[] ComponentIds, string Type)
{
if (ApiUser.User == null)
Redirect("Index");
if (ComponentIds.Length > 0 && !string.IsNullOrEmpty(Type))
{
if (Type == "docx")
{
ApiUser.PostRequest("api/component/createreporttowordfile", new ReportBindingModel
{
Ids = ComponentIds.ToList(),
FileName = "C:\\!КУРСОВАЯ\\Партии товаров по выбранным компонентам.docx"
});
return GetWordFile();
}
if (Type == "xlsx")
{
ApiUser.PostRequest("api/component/createreporttoexcelfile", new ReportBindingModel
{
Ids = ComponentIds.ToList(),
FileName = "C:\\!КУРСОВАЯ\\Партии товаров по выбранным компонентам.xlsx"
});
return GetExcelFile();
}
}
return Redirect("Index");
}
public IActionResult ReportComponentsByRequestDate()
{
if (ApiUser.User == null)
return Redirect("~/Home/Enter");
return View();
}
[HttpGet]
public string GetComponentsByRequestDate(DateTime DateFrom, DateTime DateTo)
{
if (ApiUser.User == null)
throw new Exception("Вход только авторизованным");
if (DateFrom != DateTime.MinValue && DateTo != DateTime.MinValue)
{
List<ReportComponentByDateViewModel> Result;
Result = _reportLogic.GetReportComponentsByRequestDate(new ReportBindingModel
{
UserId = ApiUser.User.Id,
DateFrom = DateFrom,
DateTo = DateTo
});
string Table = string.Empty;
Table += $"<table class=\"u-table-entity\">";
Table += "<colgroup>";
// ID комплектующей
Table += "<col width=\"7%\" />";
// Название
Table += "<col width=\"8%\" />";
// Стоимость
Table += "<col width=\"8%\" />";
// ID сборки
Table += "<col width=\"7%\" />";
// Название сборки
Table += "<col width=\"13%\" />";
// Цена сборки
Table += "<col width=\"10%\" />";
// Категория
Table += "<col width=\"8%\" />";
// ID заявки
Table += "<col width=\"8%\" />";
// Дата заявки
Table += "<col width=\"10%\" />";
// ФИО клиента
Table += "<col width=\"12%\" />";
Table += "</colgroup>";
Table += "<thead class=\"u-custom-color-1 u-table-header u-table-header-1\">";
Table += "<tr style=\"height: 31px\">";
Table += $"<th class=\"u-border-1 u-border-grey-50 u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">ID комплектующей</th>";
Table += $"<th class=\"u-border-1 u-border-grey-50 u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">Название</th>";
Table += $"<th class=\"u-border-1 u-border-grey-50 u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">Стоимость</th>";
Table += $"<th class=\"u-border-1 u-border-grey-50 u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">ID сборки</th>";
Table += $"<th class=\"u-border-1 u-border-grey-50 u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">Название сборки</th>";
Table += $"<th class=\"u-border-1 u-border-grey-50 u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">Цена сборки</th>";
Table += $"<th class=\"u-border-1 u-border-grey-50 u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">Категория</th>";
Table += $"<th class=\"u-border-1 u-border-grey-50 u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">ID заявки</th>";
Table += $"<th class=\"u-border-1 u-border-grey-50 u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">Дата заявки</th>";
Table += $"<th class=\"u-border-1 u-border-grey-50 u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">Клиент</th>";
Table += "</tr>";
Table += "</thead>";
Table += "<tbody class=\"u-table-body\">";
foreach (var ComponentByDate in Result)
{
Table += "<tr style=\"height: 75px\">";
Table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{ComponentByDate.ComponentId}</td>";
Table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{ComponentByDate.ComponentName}</td>";
Table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{ComponentByDate.ComponentCost}</td>";
Table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{ComponentByDate.AssemblyId}</td>";
Table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{ComponentByDate.AssemblyName}</td>";
Table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{ComponentByDate.AssemblyPrice}</td>";
Table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{ComponentByDate.AssemblyCategory}</td>";
Table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{ComponentByDate.RequestId}</td>";
Table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{ComponentByDate.DateRequest.ToShortDateString()}</td>";
Table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{ComponentByDate.ClientFIO}</td>";
Table += "</tr>";
}
Table += "</table>";
return Table;
}
return "";
}
[HttpPost]
public void ReportComponentsByRequestDate(DateTime DateFrom, DateTime DateTo)
{
if (ApiUser.User == null)
{
throw new Exception("Вход только авторизованным");
}
if (DateFrom != DateTime.MinValue && DateTo != DateTime.MinValue)
{
ApiUser.PostRequest("api/component/createreporttopdffile", new ReportBindingModel
{
FileName = "C:\\!КУРСОВАЯ\\Отчёт за период.pdf",
DateFrom = DateFrom,
DateTo = DateTo,
UserId = ApiUser.User.Id
});
ApiUser.PostRequest("api/component/sendpdftomail", new MailSendInfoBindingModel
{
MailAddress = ApiUser.User.Email,
Subject = "Отчет за период",
Text = "Отчет по компонентам с " + DateFrom.ToShortDateString() + " по " + DateTo.ToShortDateString()
});
}
Response.Redirect("Index");
}
[HttpGet]
public IActionResult Privacy()
{
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");
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
@ -481,55 +28,5 @@ 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<UserViewModel>($"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<UserViewModel>($"api/user/loginguarantor?login={Login}&password={Password}");
if (ApiUser.User == null)
Response.Redirect("Enter");
Response.Redirect("Index");
return;
}
public void Logout()
{
ApiUser.User = null;
Response.Redirect("Index");
}
}
}

View File

@ -1,21 +1,7 @@
using ComputerShopBusinessLogic.BusinessLogics;
using ComputerShopBusinessLogic.OfficePackage;
using ComputerShopBusinessLogic.OfficePackage.Implements;
using ComputerShopContracts.BusinessLogicContracts;
using ComputerShopContracts.StorageContracts;
using ComputerShopDatabaseImplement.Implements;
using ComputerShopGuarantorApp;
var Builder = WebApplication.CreateBuilder(args);
//Builder.Services.AddTransient<IUserStorage, UserStorage>();
Builder.Services.AddTransient<IComponentStorage, ComponentStorage>();
Builder.Services.AddTransient<IReportGuarantorLogic, ReportGuarantorLogic>();
Builder.Services.AddTransient<AbstractSaveToWordGuarantor, SaveToWordGuarantor>();
Builder.Services.AddTransient<AbstractSaveToExcelGuarantor, SaveToExcelGuarantor>();
Builder.Services.AddTransient<AbstractSaveToPdfGuarantor, SaveToPdfGuarantor>();
// Add services to the container.
Builder.Services.AddControllersWithViews();
@ -32,7 +18,9 @@ if (!App.Environment.IsDevelopment())
App.UseHttpsRedirection();
App.UseStaticFiles();
App.UseRouting();
App.UseAuthorization();
App.MapControllerRoute(

View File

@ -1,61 +0,0 @@
@using ComputerShopContracts.ViewModels;
@model List<AssemblyViewModel>
@{
ViewData["Title"] = "Сборки";
}
<div class="container-md py-4 mb-4">
<div class="text-center">
<h2>Список сборок</h2>
<p class="lead text-muted">Просматривайте список сборок и создавайте новые, а также выбирайте сборку для изменения или удаления</p>
</div>
@{
if (Model == null)
{
<h3 class="display-4">Авторизируйтесь</h3>
return;
}
<p>
<a class="btn btn-primary" asp-action="CreateAssembly">Создать сборку</a>
</p>
<table class="table table-striped">
<thead>
<tr>
<th>Номер</th>
<th class="w-25">Название</th>
<th class="w-25">Цена</th>
<th>Категория</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var Item in Model)
{
<tr>
<td>
@Html.DisplayFor(ModelItem => Item.Id)
</td>
<td>
@Html.DisplayFor(ModelItem => Item.AssemblyName)
</td>
<td>
@Html.DisplayFor(ModelItem => Item.Price)
</td>
<td>
@Html.DisplayFor(ModelItem => Item.Category)
</td>
<td>
<a asp-action="UpdateAssembly" asp-route-Id="@(Item.Id)" role="button"><i class="bi bi-pen-fill"></i></a>
</td>
<td>
<a asp-action="DeleteAssembly" asp-route-Id="@(Item.Id)" role="button"><i class="bi bi-trash-fill"></i></a>
</td>
</tr>
}
</tbody>
</table>
}
</div>

View File

@ -1,56 +0,0 @@
@using ComputerShopContracts.ViewModels;
@model AssemblyViewModel
@{
ViewData["Title"] = "Сборка";
}
<div class="container-md py-4 mb-4">
<div class="text-center">
@if (Model == null)
{
<h2>Создание сборки</h2>
}
else
{
<h2>Редактирование сборки</h2>
}
</div>
<form method="post">
<div class="form-group">
<label class="mb-1">Название:</label>
<input type="text" name="assemblyName" class="mb-3 form-control" value="@(Model?.AssemblyName ?? "")">
</div>
<div class="form-group">
<label class="mb-1">Цена:</label>
<input type="number" name="price" class="mb-3 form-control" value="@(Model?.Price ?? 0.00)" readonly>
</div>
<div class="form-group">
<label class="mb-1">Категория:</label>
<input type="text" name="category" class="mb-3 form-control" value="@(Model?.Category ?? "")">
</div>
<div class="form-group">
<label class="mb-1">Комплектующие:</label>
<select name="componentIds" class="form-control border border-dark rounded mb-3" multiple size="6">
@foreach (var Component in ViewBag.Components)
{
@if (Model != null && Model.AssemblyComponents.Values.Any(x => Component.Id == x.Id))
{
<option value="@Component.Id" selected="selected">@Component.ComponentName</option>
}
else
{
<option value="@Component.Id">@Component.ComponentName</option>
}
}
</select>
</div>
<input type="submit" value="Сохранить" class="btn btn-primary my-2" />
</form>
</div>

View File

@ -1,34 +0,0 @@
@using ComputerShopContracts.ViewModels;
@model ComponentViewModel
@{
ViewData["Title"] = "Комплектующая";
}
<div class="container-md py-4 mb-4">
<div class="text-center">
@if (Model == null)
{
<h2>Создание комплектующей</h2>
}
else
{
<h2>Редактирование комплектующей</h2>
}
</div>
<form method="post">
<div class="form-group">
<label class="mb-1">Наименование:</label>
<input type="text" name="componentName" class="mb-3 form-control" value="@(Model == null ? "" : Model.ComponentName)">
</div>
<div class="form-group">
<label class="mb-1">Стоимость:</label>
<input type="number" name="cost" class="mb-3 form-control" step="1" value="@(Model == null ? 0 : Model.Cost)">
</div>
<input type="submit" value="Сохранить" class="btn btn-primary my-2" />
</form>
</div>

View File

@ -1,57 +0,0 @@
@using ComputerShopContracts.ViewModels;
@model List<ComponentViewModel>
@{
ViewData["Title"] = "Комплектующие";
}
<div class="container-md py-4 mb-4">
<div class="text-center">
<h2>Список комплектующих</h2>
<p class="lead text-muted">Просматривайте список комплектующих и добавляйте новые, а также выбирайте комплектующую для изменения или удаления</p>
</div>
@{
if (Model == null)
{
<h3 class="display-4">Авторизируйтесь</h3>
return;
}
<p>
<a class="btn btn-primary" asp-action="CreateComponent">Создать комплектующую</a>
</p>
<table class="table table-striped">
<thead>
<tr>
<th>Номер</th>
<th>Наименование</th>
<th>Стоимость</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var Item in Model)
{
<tr>
<td>
@Html.DisplayFor(ModelItem => Item.Id)
</td>
<td>
@Html.DisplayFor(ModelItem => Item.ComponentName)
</td>
<td>
@Html.DisplayFor(ModelItem => Item.Cost)
</td>
<td>
<a asp-action="UpdateComponent" asp-route-Id="@(Item.Id)" role="button"><i class="bi bi-pen-fill"></i></a>
</td>
<td>
<a asp-action="DeleteComponent" asp-route-Id="@(Item.Id)" role="button"><i class="bi bi-trash-fill"></i></a>
</td>
</tr>
}
</tbody>
</table>
}
</div>

View File

@ -1,54 +0,0 @@
@{
ViewData["Title"] = "Вход";
}
<div class="container-sm py-4">
<div class="text-center">
<h2>Вход в аккаунт</h2>
<p class="lead text-muted">Войдите в ваш аккаунт чтобы иметь доступ к комплектующим, сборкам и товарам</p>
</div>
<div class="row justify-content-center mt-5">
<div class="col-lg-4">
<div class="card">
<div class="card-body">
<div class="d-flex flex-row justify-content-center">
<i class="bi bi-person-circle login-icon text-primary" style="font-size: 30px"></i>
<p class="lead my-auto ms-3 text-primary">Вход</p>
</div>
<form method="post" class="my-3">
<label for="email" class="form-label">Логин</label>
<div class="input-group mb-3">
<span class="input-group-text"><i class="bi bi-envelope-fill"></i></span>
<input type="text" class="form-control" name="login">
</div>
<label for="password" class="form-label">Пароль</label>
<div class="input-group mb-3">
<span class="input-group-text"><i class="bi bi-lock-fill"></i></span>
<input type="password" class="form-control" name="password">
<div class="input-group-text" id="hidePassword">
<a href=""><i class="bi bi-eye-fill"></i></a>
</div>
</div>
<div class="input-group mt-4 d-flex justify-content-between">
<div class="form-check">
<input type="checkbox" class="form-check-input" id="formCheck">
<label for="formCheck" class="form-check-label text-secondary"><small>Запомнить на этом компьютере</small></label>
</div>
<div class="forgot">
<p class="btn btn-sm text-primary p-0 border-0">Забыли пароль?</p>
</div>
</div>
<div class="text-center mt-5">
<input type="submit" value="Вход" class="btn btn-primary" />
</div>
</form>
</div>
</div>
</div>
</div>
</div>

View File

@ -3,6 +3,6 @@
}
<div class="text-center">
<h1 class="display-4">Добро пожаловать в приложение поручителя магазина "Ты ж программист"</h1>
<p>Выберите страницу из верхнего меню</p>
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>

View File

@ -1,34 +1,6 @@
@using ComputerShopContracts.ViewModels
@model UserViewModel
@{
ViewData["Title"] = "Профиль";
@{
ViewData["Title"] = "Privacy Policy";
}
<h1>@ViewData["Title"]</h1>
<div class="container-md py-4 mb-4">
<div class="text-center">
<h2>Профиль поручителя</h2>
<p class="lead text-muted">На этой странице можно изменить данные или выйти из аккаунта</p>
</div>
<form method="post">
<div class="form-group">
<label class="mb-1">Логин:</label>
<input type="text" name="login" class="mb-3 form-control" value="@Model.Login" />
</div>
<div class="form-group">
<label class="mb-1">Почта:</label>
<input type="email" name="email" class="mb-3 form-control" value="@Model.Email" />
</div>
<div class="form-group">
<label class="mb-1">Пароль:</label>
<input type="password" name="password" class="mb-3 form-control" value="@Model.Password" />
</div>
<div class="flex-column mt-2">
<input type="submit" value="Сохранить" class="btn btn-primary" />
<a class="btn btn-danger ms-2" asp-area="" asp-controller="Home" asp-action="Logout">Выйти</a>
</div>
</form>
</div>
<p>Use this page to detail your site's privacy policy.</p>

View File

@ -1,73 +0,0 @@
@using ComputerShopContracts.ViewModels;
@model ProductViewModel
@{
ViewData["Title"] = "Товар";
}
<div class="container-md py-4 mb-4">
<div class="text-center">
@if (Model == null)
{
<h2>Создание товара</h2>
}
else
{
<h2>Редактирование товара</h2>
}
</div>
<form method="post">
<div class="form-group">
<label class="mb-1">Название:</label>
<input type="text" name="productName" class="mb-3 form-control" value="@(Model?.ProductName ?? "")">
</div>
<div class="form-group">
<label class="mb-1">Цена:</label>
<input type="number" name="price" class="mb-3 form-control" value="@(Model?.Price ?? 0.00)" readonly>
</div>
<div class="form-group">
<label class="mb-1">Гарантия:</label>
<input type="number" name="warranty" class="mb-3 form-control" value="@(Model?.Warranty ?? 0)">
</div>
<div class="form-group">
<label class="mb-1">Комплектующие:</label>
<select name="componentIds" class="form-control border border-dark rounded mb-3" multiple size="6">
@foreach (var Component in ViewBag.Components)
{
@if (Model != null && Model.ProductComponents.Values.Any(x => Component.Id == x.Id))
{
<option value="@Component.Id" selected="selected">@Component.ComponentName</option>
}
else
{
<option value="@Component.Id">@Component.ComponentName</option>
}
}
</select>
</div>
<div class="form-group">
<label class="mb-1">Поставщик:</label>
<select name="shipmentId" class="form-control border border-dark rounded mb-3" size="4">
@foreach (var Shipment in ViewBag.Shipments)
{
@if (Model != null && Model.ShipmentId == Shipment.Id)
{
<option value="@Shipment.Id" selected="selected">@Shipment.ProviderName</option>
}
else
{
<option value="@Shipment.Id">@Shipment.ProviderName</option>
}
}
</select>
</div>
<input type="submit" value="Сохранить" class="btn btn-primary my-2" />
</form>
</div>

View File

@ -1,66 +0,0 @@
@using ComputerShopContracts.ViewModels;
@model List<ProductViewModel>
@{
ViewData["Title"] = "Товары";
}
<div class="container-md py-4 mb-4">
<div class="text-center">
<h2>Список товаров</h2>
<p class="lead text-muted">Просматривайте список товаров и добавляйте новые, а также выбирайте товар для изменения или удаления</p>
</div>
@{
if (Model == null)
{
<h3 class="display-4">Авторизируйтесь</h3>
return;
}
<p>
<a class="btn btn-primary" asp-action="CreateProduct">Добавить товар</a>
</p>
<table class="table table-striped">
<thead>
<tr>
<th>Номер</th>
<th class="w-25">Название</th>
<th class="w-25">Поставщик</th>
<th class="w-25">Цена</th>
<th>Гарантия</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var Item in Model)
{
<tr>
<td>
@Html.DisplayFor(ModelItem => Item.Id)
</td>
<td>
@Html.DisplayFor(ModelItem => Item.ProductName)
</td>
<td>
@Html.DisplayFor(ModelItem => Item.ProviderName)
</td>
<td>
@Html.DisplayFor(ModelItem => Item.Price)
</td>
<td>
@Html.DisplayFor(ModelItem => Item.Warranty)
</td>
<td>
<a asp-action="UpdateProduct" asp-route-Id="@(Item.Id)" role="button"><i class="bi bi-pen-fill"></i></a>
</td>
<td>
<a asp-action="DeleteProduct" asp-route-Id="@(Item.Id)" role="button"><i class="bi bi-trash-fill"></i></a>
</td>
</tr>
}
</tbody>
</table>
}
</div>

View File

@ -1,60 +0,0 @@
@{
ViewData["Title"] = "Регистрация";
}
<div class="container-sm py-4">
<div class="text-center">
<h2>Регистрация аккаунта</h2>
<p class="lead text-muted">Зарегистрируйте аккаунт поручителя, чтобы управлять комплектующими, сборками и товарами</p>
</div>
<div class="row justify-content-center mt-5">
<div class="col-lg-4">
<div class="card">
<div class="card-body">
<div class="d-flex flex-row justify-content-center">
<i class="bi bi-people-fill login-icon text-primary" style="font-size: 30px"></i>
<p class="lead my-auto ms-3 text-primary">Регистрация</p>
</div>
<form method="post" class="my-3">
<label for="login" class="form-label">Логин</label>
<div class="input-group mb-3">
<span class="input-group-text"><i class="bi bi-chat-square-quote-fill"></i></span>
<input type="text" class="form-control" name="login">
</div>
<label for="email" class="form-label">Почта</label>
<div class="input-group mb-3">
<span class="input-group-text"><i class="bi bi-envelope-fill"></i></span>
<input type="email" class="form-control" name="email" placeholder="myemail@mail.com">
</div>
<label for="password" class="form-label">Пароль</label>
<div class="input-group mb-3">
<span class="input-group-text"><i class="bi bi-lock-fill"></i></span>
<input type="password" class="form-control" name="password">
<div class="input-group-text" id="hidePassword">
<a href=""><i class="bi bi-eye-fill"></i></a>
</div>
</div>
<div class="input-group mt-4 d-flex justify-content-between">
<div class="form-check">
<input type="checkbox" class="form-check-input" id="formCheck">
<label for="formCheck" class="form-check-label text-secondary"><small>Запомнить на этом компьютере</small></label>
</div>
<div class="forgot">
<p class="btn btn-sm text-primary p-0 border-0">Забыли пароль?</p>
</div>
</div>
<div class="text-center mt-5">
<input type="submit" value="Зарегистрироваться" class="btn btn-primary" />
</div>
</form>
</div>
</div>
</div>
</div>
</div>

View File

@ -1,54 +0,0 @@
@using ComputerShopContracts.ViewModels
@{
ViewData["Title"] = "Комплектующие по дате поставки";
}
<div class="container-md py-4 mb-4">
<div class="text-center">
<h2>Получение сведений за период по комплектующим</h2>
<p class="lead text-muted">Информация о комплектующих, которые указывались в сборках и заявках</p>
</div>
<form method="post">
<div class="form-group">
<label class="mb-3" for="dateFrom">Начальная дата:</label>
<input type="datetime-local" placeholder="Выберите дату начала периода" id="dateFrom" name="dateFrom" />
</div>
<div class="form-group">
<label class="mb-3" for="dateTo">Конечная дата:</label>
<input type="datetime-local" placeholder="Выберите дату окончания периода" id="dateTo" name="dateTo" />
</div>
<div class="flex-column mt-2">
<input type="submit" value="Отправить на почту" class="btn btn-primary" />
<button class="btn btn-dark ms-2" type="button" id="show">Вывести</button>
</div>
</form>
</div>
<div class="mt-3" id="report">
</div>
<script>
function check() {
console.log('Check was called!');
var dateFrom = $('#dateFrom').val();
var dateTo = $('#dateTo').val();
if (dateFrom && dateTo) {
$.ajax({
method: "GET",
url: "/Home/GetComponentsByRequestDate",
data: { dateFrom: dateFrom, dateTo: dateTo },
success: function (result) {
if (result != null) {
$('#report').html(result);
}
}
});
};
}
check();
$('#show').on('click', (e) => check());
</script>

View File

@ -1,43 +0,0 @@
@using ComputerShopContracts.ViewModels
@{
ViewData["Title"] = "Комплектующие";
}
<div class="container-md py-4 mb-4">
<div class="text-center">
<h2>Получение списка партий товаров по выбранным комплектующим</h2>
<p class="lead text-muted">Укажите комплектующие, для который вы хотите получить список партий товаров, и выберите тип файла для отчета</p>
</div>
<form method="post">
<div class="form-group">
<label class="pt-3 mb-3">Выберите комплектующие:</label>
<select multiple name="componentIds" class="form-control mb-3">
@foreach (var Component in ViewBag.Components)
{
<option value="@Component.Id">[@Component.Id] @Component.ComponentName</option>
}
</select>
</div>
<div class="pb-3">
<label class="u-label u-text-custom-color-1 u-label-1">
Выберите формат файла:
</label>
<div class="form-check form-check-inline ms-3">
<input class="form-check-input" type="radio" name="type" value="docx" checked>
<label class="u-label u-text-custom-color-1 u-label-1" for="docx">
Word-файл
</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="type" value="xlsx" id="xlsx">
<label class="u-label u-text-custom-color-1 u-label-1" for="xlsx">
Excel-файл
</label>
</div>
</div>
<p>
<input type="submit" value="Получить отчёт" class="btn btn-primary" />
</p>
</form>
</div>

View File

@ -5,20 +5,14 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - Поручитель</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.9.1/font/bootstrap-icons.css">
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
<link rel="stylesheet" href="~/ComputerShopGuarantorApp.styles.css" asp-append-version="true" />
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<body class="d-flex flex-column min-vh-100" padding="56px">
<header>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<nav class="navbar fixed-top navbar-expand-lg navbar-dark bg-dark">
<div class="container-md">
<a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">
<i class="bi bi-pc-display-horizontal pt-5" style="font-size:30px; line-height:0px"></i>
<span class="fw-bold text-uppercase ms-2">Ты ж программист</span>
</a>
<a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index"><span class="fw-bold text-uppercase ms-2">Приложение поручителя</span></a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
@ -26,39 +20,17 @@
<div class="collapse navbar-collapse justify-content-end align-center" id="main-nav">
<ul class="navbar-nav">
<li class="nav-item me-3">
<a class="nav-link" asp-area="" asp-controller="Home" asp-action="Components">Комплектующие</a>
<a class="nav-link" asp-area="" asp-controller="Home" asp-action="Index">Главная</a>
</li>
<li class="nav-item me-3">
<a class="nav-link" asp-area="" asp-controller="Home" asp-action="Assemblies">Сборки</a>
<a class="nav-link" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</li>
<li class="nav-item me-3">
<a class="nav-link" asp-area="" asp-controller="Home" asp-action="Products">Товары</a>
</li>
<li class="nav-item me-3">
<a class="nav-link" asp-area="" asp-controller="Home" asp-action="ReportComponentsWithShipments">Получение списка</a>
<li class="nav-item d-lg-none">
<a class="nav-link text-light" asp-area="" asp-controller="Home" asp-action="Privacy">Вход в аккаунт</a>
</li>
<li class="nav-item me-3">
<a class="nav-link" asp-area="" asp-controller="Home" asp-action="ReportComponentsByRequestDate">Сведения за период</a>
<li class="nav-item d-none d-lg-inline">
<a class="btn btn-light" asp-area="" asp-controller="Home" asp-action="Privacy">Вход в аккаунт</a>
</li>
@if (ApiUser.User == null)
{
<li class="nav-item me-3">
<a class="nav-link" asp-area="" asp-controller="Home" asp-action="Register">Регистрация</a>
</li>
<li class="nav-item d-lg-none">
<a class="nav-link text-light" asp-area="" asp-controller="Home" asp-action="Enter">Вход в аккаунт</a>
</li>
<li class="nav-item d-none d-lg-inline">
<a class="btn btn-light" asp-area="" asp-controller="Home" asp-action="Enter">Вход в аккаунт</a>
</li>
}
else
{
<li class="nav-item me-3">
<a class="nav-link" asp-area="" asp-controller="Home" asp-action="Privacy">Профиль</a>
</li>
}
</ul>
</div>
</div>
@ -70,9 +42,9 @@
</main>
</div>
<footer class="bg-dark text-light mt-auto footer">
<footer class="border-top footer text-muted">
<div class="container">
&copy; 2024 - "Ты ж программист"
&copy; 2024 - ComputerShopGuarantorApp - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</div>
</footer>
<script src="~/lib/jquery/dist/jquery.min.js"></script>

View File

@ -6,5 +6,5 @@
}
},
"AllowedHosts": "*",
"IpAddress": "http://localhost:5055"
"IPAddress": "http://localhost:5024"
}

View File

@ -97,7 +97,7 @@ namespace ComputerShopRestApi.Controllers
}
}
[HttpPost]
[HttpDelete]
public void DeleteAssembly(AssemblyBindingModel Model)
{
try

View File

@ -1,5 +1,4 @@
using ComputerShopBusinessLogic.MailWorker;
using ComputerShopContracts.BindingModels;
using ComputerShopContracts.BindingModels;
using ComputerShopContracts.BusinessLogicContracts;
using ComputerShopContracts.SearchModels;
using ComputerShopContracts.ViewModels;
@ -13,15 +12,11 @@ namespace ComputerShopRestApi.Controllers
{
private readonly ILogger _logger;
private readonly IComponentLogic _componentLogic;
private readonly IReportGuarantorLogic _reportLogic;
private readonly AbstractMailWorker _mailWorker;
public ComponentController(IComponentLogic Logic, ILogger<ComponentController> Logger, IReportGuarantorLogic ReportLogic, AbstractMailWorker MailWorker)
public ComponentController(IComponentLogic Logic, ILogger<ComponentController> Logger)
{
_logger = Logger;
_componentLogic = Logic;
_reportLogic = ReportLogic;
_mailWorker = MailWorker;
}
[HttpGet]
@ -86,7 +81,7 @@ namespace ComputerShopRestApi.Controllers
}
}
[HttpPost]
[HttpDelete]
public void DeleteComponent(ComponentBindingModel Model)
{
try
@ -99,62 +94,5 @@ namespace ComputerShopRestApi.Controllers
throw;
}
}
[HttpPost]
public void CreateReportToWordFile(ReportBindingModel Model)
{
try
{
_reportLogic.SaveReportToWordFile(Model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка создания отчета");
throw;
}
}
[HttpPost]
public void CreateReportToExcelFile(ReportBindingModel Model)
{
try
{
_reportLogic.SaveReportToExcelFile(Model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка создания отчета");
throw;
}
}
[HttpPost]
public void CreateReportToPdfFile(ReportBindingModel Model)
{
try
{
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
_reportLogic.SaveReportComponentsByRequestDateToPdfFile(Model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка создания отчета");
throw;
}
}
[HttpPost]
public void SendPdfToMail(MailSendInfoBindingModel Model)
{
try
{
_mailWorker.MailSendAsync(Model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отправки письма");
throw;
}
}
}
}

View File

@ -58,7 +58,6 @@ namespace ComputerShopRestApi.Controllers
{
try
{
if (Model.ShipmentId == 0) Model.ShipmentId = null;
_productLogic.Create(Model);
}
catch (Exception ex)
@ -82,7 +81,7 @@ namespace ComputerShopRestApi.Controllers
}
}
[HttpPost]
[HttpDelete]
public void DeleteProduct(ProductBindingModel Model)
{
try

View File

@ -42,10 +42,6 @@ Builder.Services.AddTransient<AbstractSaveToExcelImplementer, SaveToExcelImpleme
Builder.Services.AddTransient<AbstractSaveToWordImplementer, SaveToWordImplementer>();
Builder.Services.AddTransient<AbstractSaveToPdfImplementer, SaveToPdfImplementer>();
Builder.Services.AddTransient<AbstractSaveToExcelGuarantor, SaveToExcelGuarantor>();
Builder.Services.AddTransient<AbstractSaveToWordGuarantor, SaveToWordGuarantor>();
Builder.Services.AddTransient<AbstractSaveToPdfGuarantor, SaveToPdfGuarantor>();
Builder.Services.AddSingleton<AbstractMailWorker, MailKitWorker>();
Builder.Services.AddControllers();