Compare commits

...

10 Commits

32 changed files with 1167 additions and 63 deletions

View File

@ -1,4 +1,6 @@
using ServiceStationContracts.BindingModels; using ServiceStationBusinessLogic.OfficePackage;
using ServiceStationBusinessLogic.OfficePackage.HelperModels;
using ServiceStationContracts.BindingModels;
using ServiceStationContracts.BusinessLogicsContracts; using ServiceStationContracts.BusinessLogicsContracts;
using ServiceStationContracts.SearchModels; using ServiceStationContracts.SearchModels;
using ServiceStationContracts.StoragesContracts; using ServiceStationContracts.StoragesContracts;
@ -17,13 +19,19 @@ namespace ServiceStationBusinessLogic.BusinessLogics
private readonly ISparePartStorage _sparepartStorage; private readonly ISparePartStorage _sparepartStorage;
private readonly IRepairStorage _repairStorage; private readonly IRepairStorage _repairStorage;
private readonly ITechnicalWorkStorage _techWorkStorage; private readonly ITechnicalWorkStorage _techWorkStorage;
private readonly AbstractSaveToExcelGuarantor _saveToExcel;
private readonly AbstractSaveToWordGuarantor _saveToWord;
private readonly AbstractSaveToPdfGuarantor _saveToPdf;
public GuarantorReportLogic(IDefectStorage defectStorage, ISparePartStorage sparepartStorage, IRepairStorage repairStorage, ITechnicalWorkStorage techWorkStorage) public GuarantorReportLogic(IDefectStorage defectStorage, ISparePartStorage sparepartStorage, IRepairStorage repairStorage, ITechnicalWorkStorage techWorkStorage, AbstractSaveToExcelGuarantor saveToExcel, AbstractSaveToPdfGuarantor saveToPdf, AbstractSaveToWordGuarantor saveToWord)
{ {
_defectStorage = defectStorage; _defectStorage = defectStorage;
_sparepartStorage = sparepartStorage; _sparepartStorage = sparepartStorage;
_repairStorage = repairStorage; _repairStorage = repairStorage;
_techWorkStorage = techWorkStorage; _techWorkStorage = techWorkStorage;
_saveToExcel = saveToExcel;
_saveToWord = saveToWord;
_saveToPdf = saveToPdf;
} }
public List<ReportDefectsViewModel> GetDefects(List<int> Ids) public List<ReportDefectsViewModel> GetDefects(List<int> Ids)
@ -32,6 +40,8 @@ namespace ServiceStationBusinessLogic.BusinessLogics
List<ReportDefectsViewModel> allList = new List<ReportDefectsViewModel>(); List<ReportDefectsViewModel> allList = new List<ReportDefectsViewModel>();
double price = 0;
var defects = _defectStorage.GetFullList(); var defects = _defectStorage.GetFullList();
List<SparePartViewModel> spareparts = new List<SparePartViewModel>(); List<SparePartViewModel> spareparts = new List<SparePartViewModel>();
foreach (var sparepartId in Ids) foreach (var sparepartId in Ids)
@ -64,9 +74,11 @@ namespace ServiceStationBusinessLogic.BusinessLogics
if (repSpareParts.Id == sparepart.Id) if (repSpareParts.Id == sparepart.Id)
{ {
rec.DefectsInfo.Add(new(defect.DefectType, defect.DefectPrice)); rec.DefectsInfo.Add(new(defect.DefectType, defect.DefectPrice));
price += defect.DefectPrice;
} }
} }
} }
rec.FullPrice = price;
allList.Add(rec); allList.Add(rec);
} }
return allList; return allList;
@ -80,6 +92,7 @@ namespace ServiceStationBusinessLogic.BusinessLogics
{ {
DateFrom = model.DateFrom, DateFrom = model.DateFrom,
DateTo = model.DateTo, DateTo = model.DateTo,
GuarantorId = model.GuarantorId,
}); });
foreach (var repair in repairList) foreach (var repair in repairList)
@ -117,17 +130,43 @@ namespace ServiceStationBusinessLogic.BusinessLogics
public void SaveDefectsToWordFile(ReportGuarantorBindingModel model) public void SaveDefectsToWordFile(ReportGuarantorBindingModel model)
{ {
throw new NotImplementedException(); _saveToWord.CreateDoc(new WordInfoGuarantor
{
FileName = model.FileName,
Title = "Список неисправностей",
DefectsBySparePart = GetDefects(model.Ids!)
});
} }
public void SaveDefectsToExcelFile(ReportGuarantorBindingModel model) public void SaveDefectsToExcelFile(ReportGuarantorBindingModel model)
{ {
throw new NotImplementedException(); _saveToExcel.CreateReport(new ExcelInfoGuarantor
{
FileName = model.FileName,
Title = "Список работ",
DefectsBySparePart = GetDefects(model.Ids!)
});
} }
public void SaveSparePartsToPdfFile(ReportGuarantorBindingModel model) public void SaveSparePartsToPdfFile(ReportGuarantorBindingModel model)
{ {
throw new NotImplementedException(); 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,
SpareParts = GetSpareParts(model)
});
} }
} }
} }

View File

@ -0,0 +1,93 @@
using ServiceStationBusinessLogic.OfficePackage.HelperEnums;
using ServiceStationBusinessLogic.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ServiceStationBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToExcelGuarantor
{
public void CreateReport(ExcelInfoGuarantor info)
{
CreateExcel(info);
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = 1,
Text = info.Title,
StyleInfo = ExcelStyleInfoType.Title,
});
MergeCells(new ExcelMergeParameters
{
CellFromName = "A1",
CellToName = "B1"
});
uint rowIndex = 2;
foreach (var wc in info.DefectsBySparePart)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = rowIndex,
Text = wc.SparePartName,
StyleInfo = ExcelStyleInfoType.Title,
});
MergeCells(new ExcelMergeParameters
{
CellFromName = $"A{rowIndex}",
CellToName = $"B{rowIndex}"
});
rowIndex++;
foreach (var defect in wc.DefectsInfo)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = rowIndex,
Text = defect.Item1,
StyleInfo = ExcelStyleInfoType.TextWithBorder,
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "B",
RowIndex = rowIndex,
Text = defect.Item2.ToString(),
StyleInfo = ExcelStyleInfoType.TextWithBorder
});
rowIndex++;
}
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = rowIndex,
Text = "Итого:",
StyleInfo = ExcelStyleInfoType.TextWithBorder,
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "B",
RowIndex = rowIndex,
Text = wc.FullPrice.ToString(),
StyleInfo = ExcelStyleInfoType.TextWithBorder
});
rowIndex++;
}
SaveExcel(info);
}
protected abstract void CreateExcel(ExcelInfoGuarantor info);
protected abstract void InsertCellInWorksheet(ExcelCellParameters excelParams);
protected abstract void MergeCells(ExcelMergeParameters excelParams);
protected abstract void SaveExcel(ExcelInfoGuarantor info);
}
}

View File

@ -0,0 +1,56 @@
using ServiceStationBusinessLogic.OfficePackage.HelperEnums;
using ServiceStationBusinessLogic.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ServiceStationBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToPdfGuarantor
{
public void CreateDoc(PdfInfoGuarantor info)
{
CreatePdf(info);
CreateParagraph(new PdfParagraph { Text = info.Title, Style = "NormalTitle", ParagraphAligment = PdfParagraphAlignmentType.Center });
CreateParagraph(new PdfParagraph { Text = $"с {info.DateFrom.ToShortDateString()} по {info.DateTo.ToShortDateString()}", Style = "Normal", ParagraphAligment = PdfParagraphAlignmentType.Center });
CreateTable(new List<string> { "3cm", "2cm", "2cm", "2cm", "3cm", "3cm", "2cm" });
CreateRow(new PdfRowParameters
{
Texts = new List<string> { "Название запчасти", "Стоимость запчасти", "Название ремонта", "Цена ремонта", "Тип ТО", "Дата ТО", "Цена ТО" },
Style = "NormalTitle",
ParagraphAligment = PdfParagraphAlignmentType.Left
});
foreach (var sparepart in info.SpareParts)
{
bool isRepair = true;
if (sparepart.RepairPrice.ToString() == "0")
{
isRepair = false;
}
CreateRow(new PdfRowParameters
{
Texts = new List<string> { sparepart.SparePartName, sparepart.SparePartPrice.ToString(), isRepair is true ? sparepart.RepairName : "", isRepair is true ? sparepart.RepairPrice.ToString() : "",
sparepart.WorkType, isRepair is true ? "" : sparepart.TechnicalWorkDate.Value.ToShortDateString(), isRepair is true ? "" : sparepart.TechnicalWorkPrice.ToString()},
Style = "Normal",
ParagraphAligment = PdfParagraphAlignmentType.Center
});
}
SavePdf(info);
}
protected abstract void CreatePdf(PdfInfoGuarantor info);
protected abstract void CreateParagraph(PdfParagraph paragraph);
protected abstract void CreateTable(List<string> columns);
protected abstract void CreateRow(PdfRowParameters rowParameters);
protected abstract void SavePdf(PdfInfoGuarantor info);
}
}

View File

@ -0,0 +1,74 @@
using ServiceStationBusinessLogic.OfficePackage.HelperEnums;
using ServiceStationBusinessLogic.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ServiceStationBusinessLogic.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 sparepart in info.DefectsBySparePart)
{
CreateParagraph(new WordParagraph
{
Texts = new List<(string, WordTextProperties)> { (sparepart.SparePartName, new WordTextProperties { Bold = true, Size = "24", }) },
TextProperties = new WordTextProperties
{
Size = "24",
JustificationType = WordJustificationType.Center
}
});
foreach (var defect in sparepart.DefectsInfo)
{
CreateParagraph(new WordParagraph
{
Texts = new List<(string, WordTextProperties)>
{
(defect.Item1, new WordTextProperties{Size = "24", Bold = true}), (" " + defect.Item2.ToString(), new WordTextProperties{Size = "24"})
},
TextProperties = new WordTextProperties
{
Size = "24",
JustificationType = WordJustificationType.Both
}
});
}
CreateParagraph(new WordParagraph
{
Texts = new List<(string, WordTextProperties)>
{
("Итого: ", new WordTextProperties{Size = "24", Bold = true}), (sparepart.FullPrice.ToString(), new WordTextProperties{Size = "24", Bold = true})
},
TextProperties = new WordTextProperties
{
Size = "24",
JustificationType = WordJustificationType.Both
}
});
}
SaveWord(info);
}
protected abstract void CreateWord(WordInfoGuarantor info);
protected abstract void CreateParagraph(WordParagraph paragraph);
protected abstract void SaveWord(WordInfoGuarantor info);
}
}

View File

@ -0,0 +1,16 @@
using ServiceStationContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ServiceStationBusinessLogic.OfficePackage.HelperModels
{
public class ExcelInfoGuarantor
{
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public List<ReportDefectsViewModel> DefectsBySparePart { get; set; } = new();
}
}

View File

@ -0,0 +1,22 @@
using ServiceStationContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ServiceStationBusinessLogic.OfficePackage.HelperModels
{
public class PdfInfoGuarantor
{
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public DateTime DateFrom { get; set; }
public DateTime DateTo { get; set; }
public List<ReportSparePartsViewModel> SpareParts { get; set; } = new();
}
}

View File

@ -0,0 +1,16 @@
using ServiceStationContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ServiceStationBusinessLogic.OfficePackage.HelperModels
{
public class WordInfoGuarantor
{
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public List<ReportDefectsViewModel> DefectsBySparePart { get; set; } = new();
}
}

View File

@ -0,0 +1,316 @@
using DocumentFormat.OpenXml.Office2010.Excel;
using DocumentFormat.OpenXml.Office2013.Excel;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml;
using ServiceStationBusinessLogic.OfficePackage.HelperEnums;
using ServiceStationBusinessLogic.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ServiceStationBusinessLogic.OfficePackage.Implements
{
public class SaveToExcelGuarantor : AbstractSaveToExcelGuarantor
{
private SpreadsheetDocument? _spreadsheetDocument;
private SharedStringTablePart? _shareStringPart;
private Worksheet? _worksheet;
public static void CreateStyles(WorkbookPart workbookpart)
{
var sp = workbookpart.AddNewPart<WorkbookStylesPart>();
sp.Stylesheet = new Stylesheet();
var fonts = new Fonts() { Count = 2U, KnownFonts = true };
var fontUsual = new Font();
fontUsual.Append(new FontSize() { Val = 12D });
fontUsual.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Theme = 1U });
fontUsual.Append(new FontName() { Val = "Times New Roman" });
fontUsual.Append(new FontFamilyNumbering() { Val = 2 });
fontUsual.Append(new FontScheme() { Val = FontSchemeValues.Minor });
var fontTitle = new Font();
fontTitle.Append(new Bold());
fontTitle.Append(new FontSize() { Val = 14D });
fontTitle.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Theme = 1U });
fontTitle.Append(new FontName() { Val = "Times New Roman" });
fontTitle.Append(new FontFamilyNumbering() { Val = 2 });
fontTitle.Append(new FontScheme() { Val = FontSchemeValues.Minor });
fonts.Append(fontUsual);
fonts.Append(fontTitle);
var fills = new Fills() { Count = 2U };
var fill1 = new Fill();
fill1.Append(new PatternFill() { PatternType = PatternValues.None });
var fill2 = new Fill();
fill2.Append(new PatternFill() { PatternType = PatternValues.Gray125 });
fills.Append(fill1);
fills.Append(fill2);
var borders = new Borders() { Count = 2U };
var borderNoBorder = new Border();
borderNoBorder.Append(new LeftBorder());
borderNoBorder.Append(new RightBorder());
borderNoBorder.Append(new TopBorder());
borderNoBorder.Append(new BottomBorder());
borderNoBorder.Append(new DiagonalBorder());
var borderThin = new Border();
var leftBorder = new LeftBorder() { Style = BorderStyleValues.Thin };
leftBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
var rightBorder = new RightBorder() { Style = BorderStyleValues.Thin };
rightBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
var topBorder = new TopBorder() { Style = BorderStyleValues.Thin };
topBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
var bottomBorder = new BottomBorder() { Style = BorderStyleValues.Thin };
bottomBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
borderThin.Append(leftBorder);
borderThin.Append(rightBorder);
borderThin.Append(topBorder);
borderThin.Append(bottomBorder);
borderThin.Append(new DiagonalBorder());
borders.Append(borderNoBorder);
borders.Append(borderThin);
var cellStyleFormats = new CellStyleFormats() { Count = 1U };
var cellFormatStyle = new CellFormat() { NumberFormatId = 0U, FontId = 0U, FillId = 0U, BorderId = 0U };
cellStyleFormats.Append(cellFormatStyle);
var cellFormats = new CellFormats() { Count = 3U };
var cellFormatFont = new CellFormat()
{
NumberFormatId = 0U,
FontId = 0U,
FillId = 0U,
BorderId = 0U,
FormatId = 0U,
ApplyFont = true
};
var cellFormatFontAndBorder = new CellFormat()
{
NumberFormatId = 0U,
FontId = 0U,
FillId = 0U,
BorderId = 1U,
FormatId = 0U,
ApplyFont = true,
ApplyBorder = true
};
var cellFormatTitle = new CellFormat()
{
NumberFormatId = 0U,
FontId = 1U,
FillId = 0U,
BorderId = 0U,
FormatId = 0U,
Alignment = new Alignment()
{
Vertical = VerticalAlignmentValues.Center,
WrapText = true,
Horizontal = HorizontalAlignmentValues.Center
},
ApplyFont = true
};
cellFormats.Append(cellFormatFont);
cellFormats.Append(cellFormatFontAndBorder);
cellFormats.Append(cellFormatTitle);
var cellStyles = new CellStyles() { Count = 1U };
cellStyles.Append(new CellStyle()
{
Name = "Normal",
FormatId = 0U,
BuiltinId = 0U
});
var differentialFormats = new DocumentFormat.OpenXml.Office2013.Excel.DifferentialFormats() { Count = 0U };
var tableStyles = new TableStyles()
{
Count = 0U,
DefaultTableStyle = "TableStyleMedium2",
DefaultPivotStyle = "PivotStyleLight16"
};
var stylesheetExtensionList = new StylesheetExtensionList();
var stylesheetExtension1 = new StylesheetExtension()
{
Uri = "{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}"
};
stylesheetExtension1.AddNamespaceDeclaration("x14", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main");
stylesheetExtension1.Append(new SlicerStyles()
{
DefaultSlicerStyle = "SlicerStyleLight1"
});
var stylesheetExtension2 = new StylesheetExtension()
{
Uri = "{9260A510-F301-46a8-8635-F512D64BE5F5}"
};
stylesheetExtension2.AddNamespaceDeclaration("x15", "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main");
stylesheetExtension2.Append(new TimelineStyles()
{
DefaultTimelineStyle = "TimeSlicerStyleLight1"
});
stylesheetExtensionList.Append(stylesheetExtension1);
stylesheetExtensionList.Append(stylesheetExtension2);
sp.Stylesheet.Append(fonts);
sp.Stylesheet.Append(fills);
sp.Stylesheet.Append(borders);
sp.Stylesheet.Append(cellStyleFormats);
sp.Stylesheet.Append(cellFormats);
sp.Stylesheet.Append(cellStyles);
sp.Stylesheet.Append(differentialFormats);
sp.Stylesheet.Append(tableStyles);
sp.Stylesheet.Append(stylesheetExtensionList);
}
private static uint GetStyleValue(ExcelStyleInfoType styleInfo)
{
return styleInfo switch
{
ExcelStyleInfoType.Title => 2U,
ExcelStyleInfoType.TextWithBorder => 1U,
ExcelStyleInfoType.Text => 0U,
_ => 0U,
};
}
protected override void CreateExcel(ExcelInfoGuarantor 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());
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(ExcelInfoGuarantor info)
{
if (_spreadsheetDocument == null)
{
return;
}
_spreadsheetDocument.WorkbookPart!.Workbook.Save();
_spreadsheetDocument.Dispose();
}
}
}

View File

@ -0,0 +1,107 @@
using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Tables;
using MigraDoc.Rendering;
using ServiceStationBusinessLogic.OfficePackage.HelperEnums;
using ServiceStationBusinessLogic.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ServiceStationBusinessLogic.OfficePackage.Implements
{
public class SaveToPdfGuarantor : AbstractSaveToPdfGuarantor
{
private Document? _document;
private Section? _section;
private Table? _table;
private static ParagraphAlignment GetParagraphAligment(PdfParagraphAlignmentType type)
{
return type switch
{
PdfParagraphAlignmentType.Center => ParagraphAlignment.Center,
PdfParagraphAlignmentType.Left => ParagraphAlignment.Left,
PdfParagraphAlignmentType.Right => ParagraphAlignment.Right,
_ => ParagraphAlignment.Justify,
};
}
private static void DefineStyles(Document document)
{
var style = document.Styles["Normal"];
style.Font.Name = "Times New Roman";
style.Font.Size = 14;
style = document.Styles.AddStyle("NormalTitle", "Normal");
style.Font.Bold = true;
}
protected override void CreatePdf(PdfInfoGuarantor info)
{
_document = new Document();
DefineStyles(_document);
_section = _document.AddSection();
_section.PageSetup = _document.DefaultPageSetup.Clone();
_section.PageSetup.LeftMargin = 22;
}
protected override void CreateParagraph(PdfParagraph pdfParagraph)
{
if (_section == null)
{
return;
}
var paragraph = _section.AddParagraph(pdfParagraph.Text);
paragraph.Format.SpaceAfter = "1cm";
paragraph.Format.Alignment = GetParagraphAligment(pdfParagraph.ParagraphAligment);
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 = GetParagraphAligment(rowParameters.ParagraphAligment);
row.Cells[i].VerticalAlignment = VerticalAlignment.Center;
}
}
protected override void SavePdf(PdfInfoGuarantor info)
{
var renderer = new PdfDocumentRenderer(true);
renderer.Document = _document;
renderer.RenderDocument();
renderer.PdfDocument.Save(info.FileName);
}
}
}

View File

@ -0,0 +1,122 @@
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml;
using ServiceStationBusinessLogic.OfficePackage.HelperEnums;
using ServiceStationBusinessLogic.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ServiceStationBusinessLogic.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(WordInfoGuarantor 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(WordInfoGuarantor info)
{
if (_docBody == null || _wordDocument == null)
{
return;
}
_docBody.AppendChild(CreateSectionProperties());
_wordDocument.MainDocumentPart!.Document.Save();
_wordDocument.Dispose();
}
}
}

View File

@ -12,5 +12,7 @@ namespace ServiceStationContracts.BindingModels
public DateTime? DateFrom { get; set; } public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; } public DateTime? DateTo { get; set; }
public int GuarantorId { get; set; } public int GuarantorId { get; set; }
public List<int>? Ids { get; set; }
} }
} }

View File

@ -9,6 +9,7 @@ namespace ServiceStationContracts.ViewModels
public class ReportDefectsViewModel public class ReportDefectsViewModel
{ {
public string SparePartName { get; set; } = string.Empty; public string SparePartName { get; set; } = string.Empty;
public double FullPrice { get; set; }
public List<(string, double)> DefectsInfo { get; set; } = new(); public List<(string, double)> DefectsInfo { get; set; } = new();
} }
} }

View File

@ -1,5 +1,6 @@
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using ServiceStationContracts.BindingModels; using ServiceStationContracts.BindingModels;
using ServiceStationContracts.BusinessLogicsContracts;
using ServiceStationContracts.SearchModels; using ServiceStationContracts.SearchModels;
using ServiceStationContracts.ViewModels; using ServiceStationContracts.ViewModels;
using ServiceStationGuarantorApp.Models; using ServiceStationGuarantorApp.Models;
@ -11,10 +12,12 @@ namespace ServiceStationGuarantorApp.Controllers
public class HomeController : Controller public class HomeController : Controller
{ {
private readonly ILogger<HomeController> _logger; private readonly ILogger<HomeController> _logger;
private readonly IGuarantorReportLogic _report;
public HomeController(ILogger<HomeController> logger) public HomeController(ILogger<HomeController> logger, IGuarantorReportLogic guarantorReportLogic)
{ {
_logger = logger; _logger = logger;
_report = guarantorReportLogic;
} }
public IActionResult Index() public IActionResult Index()
@ -204,9 +207,68 @@ namespace ServiceStationGuarantorApp.Controllers
Response.Redirect("ListSpareParts"); Response.Redirect("ListSpareParts");
} }
//......................................................... Ремонт.............................................................................. [HttpGet]
public string GetSparePartsReport(DateTime dateFrom, DateTime dateTo)
{
if (APIGuarantor.Guarantor == null)
{
throw new Exception("Авторизуйтесь");
}
List<ReportSparePartsViewModel> spareparts;
try
{
spareparts = _report.GetSpareParts(new ReportGuarantorBindingModel
{
GuarantorId = APIGuarantor.Guarantor.Id,
DateFrom = dateFrom,
DateTo = dateTo,
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка создания отчета");
throw;
}
string table = "";
table += "<h2>Предварительный отчет</h2>";
table += "<table class=\"table\">";
table += "<thead class=\"thead-dark\">";
table += "<tr>";
table += "<th scope=\"col\">Название запчасти</th>";
table += "<th scope=\"col\">Стоимость запчасти</th>";
table += "<th scope=\"col\">Название ремонта</th>";
table += "<th scope=\"col\">Цена ремонта</th>";
table += "<th scope=\"col\">Тип ТО</th>";
table += "<th scope=\"col\">Дата ТО</th>";
table += "<th scope=\"col\">Цена ТО</th>";
table += "</tr>";
table += "</thead>";
foreach (var sparepart in spareparts)
{
bool isRepair = true;
if (sparepart.RepairPrice == 0)
{
isRepair = false;
}
table += "<tbody>";
table += "<tr>";
table += $"<td>{sparepart.SparePartName}</td>";
table += $"<td>{sparepart.SparePartPrice}</td>";
table += $"<td>{(isRepair ? sparepart.RepairName : string.Empty)}</td>";
table += $"<td>{(isRepair ? sparepart.RepairPrice : string.Empty)}</td>";
table += $"<td>{sparepart.WorkType}</td>";
table += $"<td>{(isRepair ? string.Empty : sparepart.TechnicalWorkDate)}</td>";
table += $"<td>{(isRepair ? string.Empty : sparepart.TechnicalWorkPrice)}</td>";
table += "</tr>";
table += "</tbody>";
}
table += "</table>";
return table;
}
public IActionResult ListRepairs() //......................................................... Ремонт..............................................................................
public IActionResult ListRepairs()
{ {
if (APIGuarantor.Guarantor == null) if (APIGuarantor.Guarantor == null)
{ {
@ -506,22 +568,124 @@ namespace ServiceStationGuarantorApp.Controllers
Response.Redirect("ListWorks"); Response.Redirect("ListWorks");
} }
[HttpGet] public IActionResult GetWordFile()
public IActionResult ListDefectSparePartToFile() {
{ return new PhysicalFileResult(Directory.GetCurrentDirectory() + "\\Reports\\wordfile.docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
return View(); }
} public IActionResult GetExcelFile()
{
[HttpGet] return new PhysicalFileResult(Directory.GetCurrentDirectory() + "\\Reports\\excelfile.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
public IActionResult ListSparePartsToPdfFile() }
{ public IActionResult GetPdfFile()
return View(); {
} return new PhysicalFileResult(Directory.GetCurrentDirectory() + "\\Reports\\pdffile.pdf", "application/pdf");
}
[HttpGet] [HttpGet]
public IActionResult ListDefectSparePartToFile()
{
if (APIGuarantor.Guarantor == null)
{
return RedirectToAction("Enter");
}
return View(APIGuarantor.GetRequest<List<SparePartViewModel>>($"api/main/getsparepartlist?guarantorId={APIGuarantor.Guarantor.Id}"));
}
[HttpPost]
public void ListDefectSparePartToFile(int[] Ids, string type)
{
if (APIGuarantor.Guarantor == null)
{
throw new Exception("Авторизуйтесь");
}
if (Ids.Length <= 0)
{
throw new Exception("Кол-во меньше нуля");
}
if (string.IsNullOrEmpty(type))
{
throw new Exception("Неопознанный тип");
}
List<int> res = new List<int>();
foreach (var id in Ids)
{
res.Add(id);
}
if (type == "docx")
{
APIGuarantor.PostRequest("api/report/createguarantorreporttoword", new ReportGuarantorBindingModel
{
Ids = res,
FileName = Directory.GetCurrentDirectory() + "\\Reports\\wordfile.docx"
});
Response.Redirect("GetWordFile");
}
else
{
APIGuarantor.PostRequest("api/report/createguarantorreporttoexcel", new ReportGuarantorBindingModel
{
Ids = res,
FileName = Directory.GetCurrentDirectory() + "\\Reports\\excelfile.xlsx"
});
Response.Redirect("GetExcelFile");
}
}
public IActionResult ListSparePartsToPdfFile()
{
if (APIGuarantor.Guarantor == null)
{
return RedirectToAction("Enter");
}
return View();
}
[HttpPost]
public void ListSparePartsToPdfFile(DateTime dateFrom, DateTime dateTo, string guarantorEmail)
{
if (APIGuarantor.Guarantor == null)
{
throw new Exception("Авторизуйтесь");
}
if (string.IsNullOrEmpty(guarantorEmail))
{
throw new Exception("Email пуст");
}
APIGuarantor.PostRequest("api/report/createguarantorreporttopdf", new ReportGuarantorBindingModel
{
FileName = Directory.GetCurrentDirectory() + "\\Reports\\pdffile.pdf",
DateFrom = dateFrom,
DateTo = dateTo,
GuarantorId = APIGuarantor.Guarantor.Id,
});
Response.Redirect("GetPdfFile");
}
public IActionResult BindingRepairToDefects() public IActionResult BindingRepairToDefects()
{ {
return View(); if (APIGuarantor.Guarantor == null)
{
return RedirectToAction("Enter");
}
return View(Tuple.Create(APIGuarantor.GetRequest<List<RepairViewModel>>($"api/main/getrepairlist?guarantorId={APIGuarantor.Guarantor.Id}"),
APIGuarantor.GetRequest<List<DefectViewModel>>("api/main/getdefects")));
}
[HttpPost]
public void BindingRepairToDefects(int repair, int defect)
{
if (APIGuarantor.Guarantor == null)
{
throw new Exception("Авторизуйтесь");
}
APIGuarantor.PostRequest("api/main/updatedefect", new DefectBindingModel
{
Id = defect,
RepairId = repair
});
} }
} }
} }

View File

@ -1,7 +1,23 @@
using ServiceStationBusinessLogic.BusinessLogics;
using ServiceStationBusinessLogic.OfficePackage;
using ServiceStationBusinessLogic.OfficePackage.Implements;
using ServiceStationContracts.BusinessLogicsContracts;
using ServiceStationContracts.StoragesContracts;
using ServiceStationDatabaseImplement.Implements;
using ServiceStationGuarantorApp; using ServiceStationGuarantorApp;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
builder.Services.AddTransient<IGuarantorReportLogic, GuarantorReportLogic>();
builder.Services.AddTransient<IDefectStorage, DefectStorage>();
builder.Services.AddTransient<ITechnicalWorkStorage, TechnicalWorkStorage>();
builder.Services.AddTransient<IRepairStorage, RepairStorage>();
builder.Services.AddTransient<IWorkStorage, WorkStorage>();
builder.Services.AddTransient<ISparePartStorage, SparePartStorage>();
builder.Services.AddTransient<AbstractSaveToExcelGuarantor, SaveToExcelGuarantor>();
builder.Services.AddTransient<AbstractSaveToPdfGuarantor, SaveToPdfGuarantor>();
builder.Services.AddTransient<AbstractSaveToWordGuarantor, SaveToWordGuarantor>();
// Add services to the container. // Add services to the container.
builder.Services.AddControllersWithViews(); builder.Services.AddControllersWithViews();

View File

@ -11,7 +11,13 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\ServiceStationBusinessLogic\ServiceStationBusinessLogic.csproj" />
<ProjectReference Include="..\ServiceStationContracts\ServiceStationContracts.csproj" /> <ProjectReference Include="..\ServiceStationContracts\ServiceStationContracts.csproj" />
<ProjectReference Include="..\ServiceStationDatabaseImplement\ServiceStationDatabaseImplement.csproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="Reports\" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -49,8 +49,5 @@
<div class="text-center pb-3"> <div class="text-center pb-3">
<input type="submit" value="Добавить" class="btn btn-outline-dark text-center w-100" /> <input type="submit" value="Добавить" class="btn btn-outline-dark text-center w-100" />
</div> </div>
<div class="text-center">
<input type="submit" value="Назад" class="btn btn-outline-dark text-center w-100" />
</div>
</form> </form>
</div> </div>

View File

@ -49,8 +49,5 @@
<div class="text-center pb-3"> <div class="text-center pb-3">
<input type="submit" value="Добавить" class="btn btn-outline-dark text-center w-100" /> <input type="submit" value="Добавить" class="btn btn-outline-dark text-center w-100" />
</div> </div>
<div class="text-center">
<input type="submit" value="Назад" class="btn btn-outline-dark text-center w-100" />
</div>
</form> </form>
</div> </div>

View File

@ -25,8 +25,5 @@
<div class="text-center pb-3"> <div class="text-center pb-3">
<input type="submit" value="Добавить" class="btn btn-outline-dark text-center w-100" /> <input type="submit" value="Добавить" class="btn btn-outline-dark text-center w-100" />
</div> </div>
<div class="text-center">
<input type="submit" value="Назад" class="btn btn-outline-dark text-center w-100" />
</div>
</form> </form>
</div> </div>

View File

@ -17,8 +17,5 @@
<div class="text-center pb-3"> <div class="text-center pb-3">
<input type="submit" value="Сохранить" class="btn btn-outline-dark text-center w-100" /> <input type="submit" value="Сохранить" class="btn btn-outline-dark text-center w-100" />
</div> </div>
<div class="text-center">
<input type="submit" value="Назад" class="btn btn-outline-dark text-center w-100" />
</div>
</div> </div>
</form> </form>

View File

@ -17,8 +17,5 @@
<div class="text-center pb-3"> <div class="text-center pb-3">
<input type="submit" value="Сохранить" class="btn btn-outline-dark text-center w-100" /> <input type="submit" value="Сохранить" class="btn btn-outline-dark text-center w-100" />
</div> </div>
<div class="text-center">
<input type="submit" value="Назад" class="btn btn-outline-dark text-center w-100" />
</div>
</div> </div>
</form> </form>

View File

@ -17,8 +17,5 @@
<div class="text-center pb-3"> <div class="text-center pb-3">
<input type="submit" value="Сохранить" class="btn btn-outline-dark text-center w-100" /> <input type="submit" value="Сохранить" class="btn btn-outline-dark text-center w-100" />
</div> </div>
<div class="text-center">
<input type="submit" value="Назад" class="btn btn-outline-dark text-center w-100" />
</div>
</div> </div>
</form> </form>

View File

@ -14,9 +14,6 @@
<div class="text-center pb-3"> <div class="text-center pb-3">
<input type="submit" value="Удалить" class="btn btn-outline-dark text-center w-100" /> <input type="submit" value="Удалить" class="btn btn-outline-dark text-center w-100" />
</div> </div>
<div class="text-center">
<input type="submit" value="Назад" class="btn btn-outline-dark text-center w-100" />
</div>
</div> </div>
</div> </div>
</form> </form>

View File

@ -14,9 +14,6 @@
<div class="text-center pb-3"> <div class="text-center pb-3">
<input type="submit" value="Удалить" class="btn btn-outline-dark text-center w-100" /> <input type="submit" value="Удалить" class="btn btn-outline-dark text-center w-100" />
</div> </div>
<div class="text-center">
<input type="submit" value="Назад" class="btn btn-outline-dark text-center w-100" />
</div>
</div> </div>
</div> </div>
</form> </form>

View File

@ -13,9 +13,6 @@
<div class="text-center pb-3"> <div class="text-center pb-3">
<input type="submit" value="Удалить" class="btn btn-outline-dark text-center w-100" /> <input type="submit" value="Удалить" class="btn btn-outline-dark text-center w-100" />
</div> </div>
<div class="text-center">
<input type="submit" value="Назад" class="btn btn-outline-dark text-center w-100" />
</div>
</div> </div>
</div> </div>
</form> </form>

View File

@ -39,9 +39,32 @@
<div class="row mb-4"> <div class="row mb-4">
<div class="col-md-8"></div> <div class="col-md-8"></div>
<div class="col-md-4"> <div class="col-md-4">
<button type="button" id="demonstrate" class="btn btn-outline-dark w-100 text-center d-flex justify-content-md-center">Предварительный просмотр</button> <button type="button" id="view" class="btn btn-outline-dark w-100 text-center d-flex justify-content-md-center">Предварительный просмотр</button>
</div> </div>
</div> </div>
<div id="report"></div> <div id="report"></div>
</form> </form>
@section Scripts {
<script>
function table() {
var dateFrom = $('#dateFrom').val();
var dateTo = $('#dateTo').val();
if (dateFrom && dateTo) {
$.ajax({
method: "GET",
url: "/Home/GetSparePartsReport",
data: { dateFrom: dateFrom, dateTo: dateTo },
success: function (result) {
if (result != null) {
$('#report').html(result);
}
}
});
};
}
table();
$('#view').on('click', (e) => table());
</script>
}

View File

@ -33,9 +33,6 @@
<div class="text-center pb-3"> <div class="text-center pb-3">
<input type="submit" value="Сохранить" class="btn btn-outline-dark text-center w-100" /> <input type="submit" value="Сохранить" class="btn btn-outline-dark text-center w-100" />
</div> </div>
<div class="text-center">
<input type="submit" value="Назад" class="btn btn-outline-dark text-center w-100" />
</div>
</div> </div>
</div> </div>
</form> </form>

View File

@ -22,9 +22,6 @@
<div class="text-center pb-3"> <div class="text-center pb-3">
<input type="submit" value="Сохранить" class="btn btn-outline-dark text-center w-100" /> <input type="submit" value="Сохранить" class="btn btn-outline-dark text-center w-100" />
</div> </div>
<div class="text-center">
<input type="submit" value="Назад" class="btn btn-outline-dark text-center w-100" />
</div>
</div> </div>
</div> </div>
</form> </form>

View File

@ -32,9 +32,6 @@
<div class="text-center pb-3"> <div class="text-center pb-3">
<input type="submit" value="Сохранить" class="btn btn-outline-dark text-center w-100" /> <input type="submit" value="Сохранить" class="btn btn-outline-dark text-center w-100" />
</div> </div>
<div class="text-center">
<input type="submit" value="Назад" class="btn btn-outline-dark text-center w-100" />
</div>
</div> </div>
</div> </div>
</form> </form>

View File

@ -16,9 +16,6 @@
<div class="text-center pb-3"> <div class="text-center pb-3">
<input name="status" type="submit" value="Готова" class="btn btn-outline-dark text-center w-100" /> <input name="status" type="submit" value="Готова" class="btn btn-outline-dark text-center w-100" />
</div> </div>
<div class="text-center">
<input name="status" type="submit" value="Назад" class="btn btn-outline-dark text-center w-100" />
</div>
</div> </div>
</div> </div>
</form> </form>

View File

@ -46,6 +46,21 @@ namespace ServiceStationRestApi.Controllers
throw; throw;
} }
} }
[HttpGet]
public List<DefectViewModel>? GetDefects()
{
try
{
return _dlogic.ReadList(null);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения списка неисправностей");
throw;
}
}
[HttpGet] [HttpGet]
public List<DefectViewModel>? GetDefectList(int executorId) public List<DefectViewModel>? GetDefectList(int executorId)
{ {

View File

@ -11,13 +11,15 @@ namespace ServiceStationRestApi.Controllers
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IExecutorReportLogic _executorReportLogic; private readonly IExecutorReportLogic _executorReportLogic;
private readonly IGuarantorReportLogic _guarantorReportLogic;
private readonly AbstractMailWorker _mailWorker; private readonly AbstractMailWorker _mailWorker;
public ReportController(ILogger<ReportController> logger, IExecutorReportLogic executorReportLogic, AbstractMailWorker abstractMailWorker) public ReportController(ILogger<ReportController> logger, IExecutorReportLogic executorReportLogic, AbstractMailWorker abstractMailWorker, IGuarantorLogic guarantorReportLogic)
{ {
_logger = logger; _logger = logger;
_executorReportLogic = executorReportLogic; _executorReportLogic = executorReportLogic;
_mailWorker = abstractMailWorker; _mailWorker = abstractMailWorker;
_guarantorReportLogic = guarantorReportLogic;
} }
[HttpPost] [HttpPost]
@ -78,5 +80,54 @@ namespace ServiceStationRestApi.Controllers
throw; throw;
} }
} }
[HttpPost]
public void CreateGuarantorReportToWord(ReportGuarantorBindingModel model)
{
try
{
_guarantorReportLogic.SaveDefectsToWordFile(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка создания отчета");
throw;
}
}
[HttpPost]
public void CreateGuarantorReportToExcel(ReportGuarantorBindingModel model)
{
try
{
_guarantorReportLogic.SaveDefectsToExcelFile(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка создания отчета");
throw;
}
}
[HttpPost]
public void CreateGuarantorReportToPdf(ReportGuarantorBindingModel model)
{
try
{
_guarantorReportLogic.SaveSparePartsToPdfFile(new ReportGuarantorBindingModel
{
FileName = model.FileName,
DateFrom = model.DateFrom,
DateTo = model.DateTo,
GuarantorId = model.GuarantorId,
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка создания отчета");
throw;
}
}
} }
} }

View File

@ -30,6 +30,7 @@ builder.Services.AddTransient<IDefectLogic, DefectLogic>();
builder.Services.AddTransient<IExecutorLogic, ExecutorLogic>(); builder.Services.AddTransient<IExecutorLogic, ExecutorLogic>();
builder.Services.AddTransient<ITechnicalWorkLogic, TechnicalWorkLogic>(); builder.Services.AddTransient<ITechnicalWorkLogic, TechnicalWorkLogic>();
builder.Services.AddTransient<IExecutorReportLogic, ExecutorReportLogic>(); builder.Services.AddTransient<IExecutorReportLogic, ExecutorReportLogic>();
builder.Services.AddTransient<IGuarantorReportLogic, GuarantorReportLogic>();
builder.Services.AddTransient<ISparePartLogic, SparePartLogic>(); builder.Services.AddTransient<ISparePartLogic, SparePartLogic>();
builder.Services.AddTransient<IGuarantorLogic, GuarantorLogic>(); builder.Services.AddTransient<IGuarantorLogic, GuarantorLogic>();
@ -40,8 +41,11 @@ builder.Services.AddTransient<AbstractSaveToExcelExecutor, SaveToExcelExecutor>(
builder.Services.AddTransient<AbstractSaveToWordExecutor, SaveToWordExecutor>(); builder.Services.AddTransient<AbstractSaveToWordExecutor, SaveToWordExecutor>();
builder.Services.AddTransient<AbstractSaveToPdfExecutor, SaveToPdfExecutor>(); builder.Services.AddTransient<AbstractSaveToPdfExecutor, SaveToPdfExecutor>();
builder.Services.AddSingleton<AbstractMailWorker, MailKitWorker>(); builder.Services.AddTransient<AbstractSaveToExcelGuarantor, SaveToExcelGuarantor>();
builder.Services.AddTransient<AbstractSaveToWordGuarantor, SaveToWordGuarantor>();
builder.Services.AddTransient<AbstractSaveToPdfGuarantor, SaveToPdfGuarantor>();
builder.Services.AddSingleton<AbstractMailWorker, MailKitWorker>();
builder.Services.AddControllers(); builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer(); builder.Services.AddEndpointsApiExplorer();