From f0c1a6f0d4870d9de6506f0f03a987faacf2be87 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A0=D0=BE=D0=BC=D0=B0=20=D0=9F=D0=B5=D1=80=D0=BC=D1=8F?= =?UTF-8?q?=D0=BA=D0=BE=D0=B2?= Date: Mon, 9 Dec 2024 13:05:48 +0400 Subject: [PATCH] =?UTF-8?q?=D0=B2=D1=82=D0=BE=D1=80=D0=BE=D0=B9=20=D1=8D?= =?UTF-8?q?=D1=82=D0=B0=D0=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../FormGeneral.Designer.cs | 12 +- .../RealEstateTransactions/FormGeneral.cs | 12 + .../Forms/FormPriceReport.Designer.cs | 167 +++++++++ .../Forms/FormPriceReport.cs | 65 ++++ .../Forms/FormPriceReport.resx | 120 +++++++ .../Reports/ExcelBuilder.cs | 320 ++++++++++++++++++ .../Reports/TableReport.cs | 78 +++++ 7 files changed, 773 insertions(+), 1 deletion(-) create mode 100644 RealEstateTransactions/RealEstateTransactions/Forms/FormPriceReport.Designer.cs create mode 100644 RealEstateTransactions/RealEstateTransactions/Forms/FormPriceReport.cs create mode 100644 RealEstateTransactions/RealEstateTransactions/Forms/FormPriceReport.resx create mode 100644 RealEstateTransactions/RealEstateTransactions/Reports/ExcelBuilder.cs create mode 100644 RealEstateTransactions/RealEstateTransactions/Reports/TableReport.cs diff --git a/RealEstateTransactions/RealEstateTransactions/FormGeneral.Designer.cs b/RealEstateTransactions/RealEstateTransactions/FormGeneral.Designer.cs index e47545e..ef7a25a 100644 --- a/RealEstateTransactions/RealEstateTransactions/FormGeneral.Designer.cs +++ b/RealEstateTransactions/RealEstateTransactions/FormGeneral.Designer.cs @@ -38,6 +38,7 @@ сделкиToolStripMenuItem = new ToolStripMenuItem(); отчётToolStripMenuItem = new ToolStripMenuItem(); DirectoryReportToolStripMenuItem = new ToolStripMenuItem(); + PriceReportToolStripMenuItem = new ToolStripMenuItem(); menuStrip1.SuspendLayout(); SuspendLayout(); // @@ -102,7 +103,7 @@ // // отчётToolStripMenuItem // - отчётToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { DirectoryReportToolStripMenuItem }); + отчётToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { DirectoryReportToolStripMenuItem, PriceReportToolStripMenuItem }); отчётToolStripMenuItem.Name = "отчётToolStripMenuItem"; отчётToolStripMenuItem.Size = new Size(73, 24); отчётToolStripMenuItem.Text = "Отчёты"; @@ -115,6 +116,14 @@ DirectoryReportToolStripMenuItem.Text = "Документ по справочникам"; DirectoryReportToolStripMenuItem.Click += DirectoryReportToolStripMenuItem_Click; // + // PriceReportToolStripMenuItem + // + PriceReportToolStripMenuItem.Name = "PriceReportToolStripMenuItem"; + PriceReportToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.E; + PriceReportToolStripMenuItem.Size = new Size(343, 26); + PriceReportToolStripMenuItem.Text = "Документ по доходам"; + PriceReportToolStripMenuItem.Click += PriceReportToolStripMenuItem_Click; + // // FormGeneral // AutoScaleDimensions = new SizeF(8F, 20F); @@ -146,5 +155,6 @@ private ToolStripMenuItem услугиToolStripMenuItem; private ToolStripMenuItem сделкиToolStripMenuItem; private ToolStripMenuItem DirectoryReportToolStripMenuItem; + private ToolStripMenuItem PriceReportToolStripMenuItem; } } diff --git a/RealEstateTransactions/RealEstateTransactions/FormGeneral.cs b/RealEstateTransactions/RealEstateTransactions/FormGeneral.cs index 3a92158..96bd90a 100644 --- a/RealEstateTransactions/RealEstateTransactions/FormGeneral.cs +++ b/RealEstateTransactions/RealEstateTransactions/FormGeneral.cs @@ -85,5 +85,17 @@ namespace RealEstateTransactions MessageBox.Show(ex.Message, " ", MessageBoxButtons.OK, MessageBoxIcon.Error); } } + + private void PriceReportToolStripMenuItem_Click(object sender, EventArgs e) + { + try + { + _container.Resolve().ShowDialog(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, " ", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } } } \ No newline at end of file diff --git a/RealEstateTransactions/RealEstateTransactions/Forms/FormPriceReport.Designer.cs b/RealEstateTransactions/RealEstateTransactions/Forms/FormPriceReport.Designer.cs new file mode 100644 index 0000000..5589d96 --- /dev/null +++ b/RealEstateTransactions/RealEstateTransactions/Forms/FormPriceReport.Designer.cs @@ -0,0 +1,167 @@ +namespace RealEstateTransactions.Forms +{ + partial class FormPriceReport + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + textBoxFilePath = new TextBox(); + buttonSelectFilePath = new Button(); + labelFilePath = new Label(); + labelApartmentId = new Label(); + comboBoxApartmentId = new ComboBox(); + labelDateStart = new Label(); + labelDateEnd = new Label(); + dateTimePickerDateStart = new DateTimePicker(); + dateTimePickerDateEnd = new DateTimePicker(); + buttonMakeReport = new Button(); + SuspendLayout(); + // + // textBoxFilePath + // + textBoxFilePath.BorderStyle = BorderStyle.FixedSingle; + textBoxFilePath.Location = new Point(125, 12); + textBoxFilePath.Name = "textBoxFilePath"; + textBoxFilePath.ReadOnly = true; + textBoxFilePath.Size = new Size(182, 27); + textBoxFilePath.TabIndex = 0; + textBoxFilePath.TabStop = false; + // + // buttonSelectFilePath + // + buttonSelectFilePath.Location = new Point(313, 10); + buttonSelectFilePath.Name = "buttonSelectFilePath"; + buttonSelectFilePath.Size = new Size(30, 29); + buttonSelectFilePath.TabIndex = 0; + buttonSelectFilePath.Text = "..."; + buttonSelectFilePath.UseVisualStyleBackColor = true; + buttonSelectFilePath.Click += ButtonSelectFilePath_Click; + // + // labelFilePath + // + labelFilePath.AutoSize = true; + labelFilePath.Location = new Point(12, 14); + labelFilePath.Name = "labelFilePath"; + labelFilePath.Size = new Size(112, 20); + labelFilePath.TabIndex = 1; + labelFilePath.Text = "Путь до файла:"; + // + // labelApartmentId + // + labelApartmentId.AutoSize = true; + labelApartmentId.Location = new Point(12, 60); + labelApartmentId.Name = "labelApartmentId"; + labelApartmentId.Size = new Size(78, 20); + labelApartmentId.TabIndex = 2; + labelApartmentId.Text = "Квартира:"; + // + // comboBoxApartmentId + // + comboBoxApartmentId.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxApartmentId.FormattingEnabled = true; + comboBoxApartmentId.Location = new Point(125, 57); + comboBoxApartmentId.Name = "comboBoxApartmentId"; + comboBoxApartmentId.Size = new Size(218, 28); + comboBoxApartmentId.TabIndex = 1; + // + // labelDateStart + // + labelDateStart.AutoSize = true; + labelDateStart.Location = new Point(12, 112); + labelDateStart.Name = "labelDateStart"; + labelDateStart.Size = new Size(97, 20); + labelDateStart.TabIndex = 3; + labelDateStart.Text = "Дата начала:"; + // + // labelDateEnd + // + labelDateEnd.AutoSize = true; + labelDateEnd.Location = new Point(12, 157); + labelDateEnd.Name = "labelDateEnd"; + labelDateEnd.Size = new Size(90, 20); + labelDateEnd.TabIndex = 4; + labelDateEnd.Text = "Дата конца:"; + // + // dateTimePickerDateStart + // + dateTimePickerDateStart.Location = new Point(125, 107); + dateTimePickerDateStart.Name = "dateTimePickerDateStart"; + dateTimePickerDateStart.Size = new Size(218, 27); + dateTimePickerDateStart.TabIndex = 2; + // + // dateTimePickerDateEnd + // + dateTimePickerDateEnd.Location = new Point(125, 152); + dateTimePickerDateEnd.Name = "dateTimePickerDateEnd"; + dateTimePickerDateEnd.Size = new Size(218, 27); + dateTimePickerDateEnd.TabIndex = 3; + // + // buttonMakeReport + // + buttonMakeReport.Location = new Point(125, 201); + buttonMakeReport.Name = "buttonMakeReport"; + buttonMakeReport.Size = new Size(125, 29); + buttonMakeReport.TabIndex = 4; + buttonMakeReport.Text = "сформировать"; + buttonMakeReport.UseVisualStyleBackColor = true; + buttonMakeReport.Click += ButtonMakeReport_Click; + // + // FormPriceReport + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(360, 246); + Controls.Add(buttonMakeReport); + Controls.Add(dateTimePickerDateEnd); + Controls.Add(dateTimePickerDateStart); + Controls.Add(labelDateEnd); + Controls.Add(labelDateStart); + Controls.Add(comboBoxApartmentId); + Controls.Add(labelApartmentId); + Controls.Add(labelFilePath); + Controls.Add(buttonSelectFilePath); + Controls.Add(textBoxFilePath); + Name = "FormPriceReport"; + StartPosition = FormStartPosition.CenterParent; + Text = "Отчёт по доходу"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private TextBox textBoxFilePath; + private Button buttonSelectFilePath; + private Label labelFilePath; + private Label labelApartmentId; + private ComboBox comboBoxApartmentId; + private Label labelDateStart; + private Label labelDateEnd; + private DateTimePicker dateTimePickerDateStart; + private DateTimePicker dateTimePickerDateEnd; + private Button buttonMakeReport; + } +} \ No newline at end of file diff --git a/RealEstateTransactions/RealEstateTransactions/Forms/FormPriceReport.cs b/RealEstateTransactions/RealEstateTransactions/Forms/FormPriceReport.cs new file mode 100644 index 0000000..d34a365 --- /dev/null +++ b/RealEstateTransactions/RealEstateTransactions/Forms/FormPriceReport.cs @@ -0,0 +1,65 @@ +using RealEstateTransactions.Reports; +using RealEstateTransactions.Repositories; +using Unity; + +namespace RealEstateTransactions.Forms +{ + public partial class FormPriceReport : Form + { + private readonly IUnityContainer _container; + + public FormPriceReport(IUnityContainer container, IApartmentRepository repository) + { + InitializeComponent(); + _container = container ?? throw new ArgumentNullException(nameof(container)); + comboBoxApartmentId.DataSource = repository.ReadApartments(); + comboBoxApartmentId.DisplayMember = "Id"; + comboBoxApartmentId.ValueMember = "Id"; + } + + private void ButtonSelectFilePath_Click(object sender, EventArgs e) + { + var sfd = new SaveFileDialog() + { + Filter = "Excel Files | *.xlsx" + }; + + if (sfd.ShowDialog() != DialogResult.OK) return; + + textBoxFilePath.Text = sfd.FileName; + } + + private void ButtonMakeReport_Click(object sender, EventArgs e) + { + try + { + if (string.IsNullOrWhiteSpace(textBoxFilePath.Text)) + throw new Exception("Отсутствует имя файла для отчета"); + + if (comboBoxApartmentId.SelectedIndex < 0) + throw new Exception("Не выбрана квартира"); + + if (dateTimePickerDateEnd.Value <= dateTimePickerDateStart.Value) + throw new Exception("Дата начала должна быть раньше даты окончания"); + + if (_container.Resolve().CreateTable(textBoxFilePath.Text, + (int)comboBoxApartmentId.SelectedValue!, + dateTimePickerDateStart.Value, dateTimePickerDateEnd.Value)) + { + MessageBox.Show("Документ сформирован", "Формирование документа", + MessageBoxButtons.OK, MessageBoxIcon.Information); + } + else + { + MessageBox.Show("Возникли ошибки при формировании документа.Подробности в логах", + "Формирование документа", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка при создании очета", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } +} \ No newline at end of file diff --git a/RealEstateTransactions/RealEstateTransactions/Forms/FormPriceReport.resx b/RealEstateTransactions/RealEstateTransactions/Forms/FormPriceReport.resx new file mode 100644 index 0000000..8b2ff64 --- /dev/null +++ b/RealEstateTransactions/RealEstateTransactions/Forms/FormPriceReport.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/RealEstateTransactions/RealEstateTransactions/Reports/ExcelBuilder.cs b/RealEstateTransactions/RealEstateTransactions/Reports/ExcelBuilder.cs new file mode 100644 index 0000000..93dad63 --- /dev/null +++ b/RealEstateTransactions/RealEstateTransactions/Reports/ExcelBuilder.cs @@ -0,0 +1,320 @@ +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Spreadsheet; +using DocumentFormat.OpenXml; + +namespace RealEstateTransactions.Reports +{ + public class ExcelBuilder + { + private readonly string _filePath; + + private readonly SheetData _sheetData; + + private readonly MergeCells _mergeCells; + + private readonly Columns _columns; + + private uint _rowIndex = 0; + + public ExcelBuilder(string filePath) + { + if (string.IsNullOrWhiteSpace(filePath)) + throw new ArgumentNullException(nameof(filePath)); + + if (File.Exists(filePath)) File.Delete(filePath); + + _filePath = filePath; + _sheetData = new SheetData(); + _mergeCells = new MergeCells(); + _columns = new Columns(); + _rowIndex = 1; + } + + public ExcelBuilder AddHeader(string header, int startIndex, int count) + { + CreateCell(startIndex, _rowIndex, header, StyleIndex.BoldTextWithoutBobder); + for (int i = startIndex + 1; i < startIndex + count; ++i) + CreateCell(i, _rowIndex, "", StyleIndex.BoldTextWithoutBobder); + + _mergeCells.Append(new MergeCell() + { + Reference = new StringValue($"{GetExcelColumnName(startIndex)}{_rowIndex}:" + + $"{GetExcelColumnName(startIndex + count - 1)}{_rowIndex}") + }); + _rowIndex++; + return this; + } + + public ExcelBuilder AddParagraph(string text, int columnIndex) + { + CreateCell(columnIndex, _rowIndex++, text, StyleIndex.SimpleTextWithoutBorder); + return this; + } + + public ExcelBuilder AddTable(int[] columnsWidths, List data) + { + if (columnsWidths == null || columnsWidths.Length == 0) + throw new ArgumentNullException(nameof(columnsWidths)); + + if (data == null || data.Count == 0) + throw new ArgumentNullException(nameof(data)); + + if (data.Any(x => x.Length != columnsWidths.Length)) + throw new InvalidOperationException("widths.Length != data.Length"); + + uint counter = 1; + int coef = 2; + _columns.Append(columnsWidths.Select(x => new Column + { + Min = counter, + Max = counter++, + Width = x * coef, + CustomWidth = true + })); + + for (var j = 0; j < data.First().Length; ++j) + CreateCell(j, _rowIndex, data.First()[j], StyleIndex.BoldTextWithBorder); + + _rowIndex++; + + for (var i = 1; i < data.Count - 1; ++i) + { + for (var j = 0; j < data[i].Length; ++j) + { + CreateCell(j, _rowIndex, data[i][j], StyleIndex.SimpleTextWithBorder); + } + _rowIndex++; + } + + for (var j = 0; j < data.Last().Length; ++j) + { + CreateCell(j, _rowIndex, data.Last()[j], StyleIndex.BoldTextWithBorder); + } + + _rowIndex++; + return this; + } + + public void Build() + { + using var spreadsheetDocument = SpreadsheetDocument.Create(_filePath, + SpreadsheetDocumentType.Workbook); + var workbookpart = spreadsheetDocument.AddWorkbookPart(); + GenerateStyle(workbookpart); + workbookpart.Workbook = new Workbook(); + var worksheetPart = workbookpart.AddNewPart(); + worksheetPart.Worksheet = new Worksheet(); + if (_columns.HasChildren) worksheetPart.Worksheet.Append(_columns); + worksheetPart.Worksheet.Append(_sheetData); + var sheets = spreadsheetDocument.WorkbookPart!.Workbook.AppendChild(new Sheets()); + var sheet = new Sheet() + { + Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), + SheetId = 1, + Name = "Лист 1" + }; + + sheets.Append(sheet); + if (_mergeCells.HasChildren) + { + worksheetPart.Worksheet.InsertAfter(_mergeCells, + worksheetPart.Worksheet.Elements().First()); + } + } + + private static void GenerateStyle(WorkbookPart workbookPart) + { + var workbookStylesPart = workbookPart.AddNewPart(); + workbookStylesPart.Stylesheet = new Stylesheet(); + var fonts = new Fonts() + { + Count = 2, + KnownFonts = BooleanValue.FromBoolean(true) + }; + + fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font + { + FontSize = new FontSize() { Val = 11 }, + FontName = new FontName() { Val = "Calibri" }, + FontFamilyNumbering = new FontFamilyNumbering() { Val = 2 }, + FontScheme = new FontScheme() + { + Val = new EnumValue(FontSchemeValues.Minor) + } + }); + + fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font + { + FontSize = new FontSize() { Val = 11 }, + FontName = new FontName() { Val = "Calibri" }, + FontFamilyNumbering = new FontFamilyNumbering() { Val = 2 }, + FontScheme = new FontScheme() + { + Val = new EnumValue(FontSchemeValues.Minor) + }, + Bold = new Bold() + }); + workbookStylesPart.Stylesheet.Append(fonts); + + var fills = new Fills() { Count = 1 }; + fills.Append(new Fill + { + PatternFill = new PatternFill() + { + PatternType = new EnumValue(PatternValues.None) + } + }); + workbookStylesPart.Stylesheet.Append(fills); + + var borders = new Borders() { Count = 2 }; + borders.Append(new Border + { + LeftBorder = new LeftBorder(), + RightBorder = new RightBorder(), + TopBorder = new TopBorder(), + BottomBorder = new BottomBorder(), + DiagonalBorder = new DiagonalBorder() + }); + + borders.Append(new Border() + { + LeftBorder = new LeftBorder() { Style = BorderStyleValues.Thin }, + RightBorder = new RightBorder() { Style = BorderStyleValues.Thin }, + TopBorder = new TopBorder() { Style = BorderStyleValues.Thin }, + BottomBorder = new BottomBorder() { Style = BorderStyleValues.Thin }, + DiagonalBorder = new DiagonalBorder() + }); + workbookStylesPart.Stylesheet.Append(borders); + + var cellFormats = new CellFormats() { Count = 4 }; + cellFormats.Append(new CellFormat + { + NumberFormatId = 0, + FormatId = 0, + FontId = 0, + BorderId = 0, + FillId = 0, + Alignment = new Alignment() + { + Horizontal = HorizontalAlignmentValues.Left, + Vertical = VerticalAlignmentValues.Center, + WrapText = true + } + }); + + cellFormats.Append(new CellFormat + { + NumberFormatId = 0, + FormatId = 0, + FontId = 1, + BorderId = 0, + FillId = 0, + Alignment = new Alignment() + { + Horizontal = HorizontalAlignmentValues.Left, + Vertical = VerticalAlignmentValues.Center, + WrapText = true + } + }); + + cellFormats.Append(new CellFormat + { + NumberFormatId = 0, + FormatId = 0, + FontId = 1, + BorderId = 1, + FillId = 0, + Alignment = new Alignment() + { + Horizontal = HorizontalAlignmentValues.Left, + Vertical = VerticalAlignmentValues.Center, + WrapText = true + } + }); + + cellFormats.Append(new CellFormat + { + NumberFormatId = 0, + FormatId = 0, + FontId = 0, + BorderId = 1, + FillId = 0, + Alignment = new Alignment() + { + Horizontal = HorizontalAlignmentValues.Left, + Vertical = VerticalAlignmentValues.Center, + WrapText = true + } + }); + workbookStylesPart.Stylesheet.Append(cellFormats); + } + + private enum StyleIndex + { + SimpleTextWithoutBorder = 0, + BoldTextWithoutBobder = 1, + BoldTextWithBorder = 2, + SimpleTextWithBorder = 3 + } + + private void CreateCell(int columnIndex, uint rowIndex, string text, + StyleIndex styleIndex) + { + var columnName = GetExcelColumnName(columnIndex); + var cellReference = columnName + rowIndex; + var row = _sheetData.Elements().FirstOrDefault(r => + r.RowIndex! == rowIndex); + + if (row == null) + { + row = new Row() { RowIndex = rowIndex }; + _sheetData.Append(row); + } + + var newCell = row.Elements() + .FirstOrDefault(c => c.CellReference != null && + c.CellReference.Value == columnName + rowIndex); + + if (newCell == null) + { + Cell? refCell = null; + foreach (Cell cell in row.Elements()) + { + if (cell.CellReference?.Value != null && + cell.CellReference.Value.Length == cellReference.Length) + { + if (string.Compare(cell.CellReference.Value, + cellReference, true) > 0) + { + refCell = cell; + break; + } + } + } + newCell = new Cell() { CellReference = cellReference }; + row.InsertBefore(newCell, refCell); + } + + newCell.CellValue = new CellValue(text); + newCell.DataType = CellValues.String; + newCell.StyleIndex = (uint)styleIndex; + } + + private static string GetExcelColumnName(int columnNumber) + { + columnNumber += 1; + int dividend = columnNumber; + string columnName = string.Empty; + int modulo; + + while (dividend > 0) + { + modulo = (dividend - 1) % 26; + columnName = Convert.ToChar(65 + modulo).ToString() + columnName; + dividend = (dividend - modulo) / 26; + } + + return columnName; + } + } +} \ No newline at end of file diff --git a/RealEstateTransactions/RealEstateTransactions/Reports/TableReport.cs b/RealEstateTransactions/RealEstateTransactions/Reports/TableReport.cs new file mode 100644 index 0000000..aeaadbd --- /dev/null +++ b/RealEstateTransactions/RealEstateTransactions/Reports/TableReport.cs @@ -0,0 +1,78 @@ +using Microsoft.Extensions.Logging; +using RealEstateTransactions.Repositories; + +namespace RealEstateTransactions.Reports +{ + public class TableReport + { + private readonly IDealRepository _dealRepository; + + private readonly IPreSalesServicesRepository _preSalesServicesRepository; + + private readonly ILogger _logger; + + internal static readonly string[] item = ["Сделка", "Дата", "Доход от сделки", "Доход от допродажных услуг"]; + + public TableReport(IDealRepository dealRepository, + IPreSalesServicesRepository preSalesServicesRepository, ILogger logger) + { + _dealRepository = dealRepository ?? throw new + ArgumentNullException(nameof(dealRepository)); + _preSalesServicesRepository = preSalesServicesRepository ?? throw new + ArgumentNullException(nameof(preSalesServicesRepository)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + public bool CreateTable(string filePath, int apartmentId, DateTime startDate, + DateTime endDate) + { + try + { + new ExcelBuilder(filePath) + .AddHeader("Сводка по доходу от продажи квартиры", 0, 4) + .AddParagraph("за период", 0) + .AddTable([10, 10, 10, 15], GetData(apartmentId, startDate, + endDate)) + .Build(); + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при формировании документа"); + return false; + } + } + + private List GetData(int apartmentId, DateTime startDate, DateTime + endDate) + { + var data = _dealRepository + .ReadDeals() + .Where(x => x.Deal_date >= startDate && x.Deal_date <= endDate && + x.Apartment_ID == apartmentId) + .Select(x => new { + DealId = (int?)x.Id, Date = (DateTime?)x.Deal_date, DealPrice = (float?)x.Deal_price, ServicesPrice = (float?)null + }) + .Union( + _preSalesServicesRepository + .ReadPreSalesServices() + .Where(x => x.Apartment_ID == apartmentId) + .Select(x => new { + DealId = (int?)null, Date = (DateTime?)null, DealPrice = (float?)null, ServicesPrice = (float?)x.Cost + })) + .OrderBy(x => x.Date); + + return + new List() { item } + .Union( + data + .Select(x => new string[] { + x.DealId?.ToString() ?? string.Empty, x.Date?.ToString() ?? string.Empty, + x.DealPrice?.ToString() ?? string.Empty, x.ServicesPrice?.ToString() ?? string.Empty})) + .Union( + [["Всего", "", data.Sum(x => x.DealPrice ?? 0).ToString(), + data.Sum(x => x.ServicesPrice ?? 0).ToString()]]) + .ToList(); + } + } +} \ No newline at end of file