From 495cc259ca0232eba71cce2dbaaece2db80579d8 Mon Sep 17 00:00:00 2001 From: RomaEredavkin <145482422+RomaEredavkin@users.noreply.github.com> Date: Wed, 18 Dec 2024 15:21:46 +0400 Subject: [PATCH] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=B0=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D0=BD=D0=BE=D0=BC=D0=B5=D1=80?= =?UTF-8?q?=203?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Entities/RoutSheet.cs | 20 +- .../Entities/TempRoutSheetBus.cs | 22 ++ .../Entities/To.cs | 4 +- .../FormBus.Designer.cs | 31 ++ .../FormBus.cs | 39 ++- .../Forms/FormBusReport.Designer.cs | 163 +++++++++ .../Forms/FormBusReport.cs | 82 +++++ .../Forms/FormBusReport.resx | 120 +++++++ .../Forms/FormDirectoryReport.Designer.cs | 99 ++++++ .../Forms/FormDirectoryReport.cs | 63 ++++ .../Forms/FormDirectoryReport.resx | 120 +++++++ .../Forms/FormTO.cs | 2 +- .../FormToDistributionReport.Designer.cs | 107 ++++++ .../Forms/FormToDistributionReport.cs | 66 ++++ .../Forms/FormToDistributionReport.resx | 120 +++++++ .../PIbd-24_EredavkinRA_BusBusiness.csproj | 2 + .../Reports/ChartReport.cs | 52 +++ .../Reports/DocReport.cs | 103 ++++++ .../Reports/ExcelBuilder.cs | 328 ++++++++++++++++++ .../Reports/PdfBuilder.cs | 93 +++++ .../Reports/TableReport.cs | 98 ++++++ .../Reports/WordBuilder.cs | 107 ++++++ .../Implementations/RoutSheetRepository.cs | 8 +- 23 files changed, 1840 insertions(+), 9 deletions(-) create mode 100644 PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Entities/TempRoutSheetBus.cs create mode 100644 PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Forms/FormBusReport.Designer.cs create mode 100644 PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Forms/FormBusReport.cs create mode 100644 PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Forms/FormBusReport.resx create mode 100644 PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Forms/FormDirectoryReport.Designer.cs create mode 100644 PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Forms/FormDirectoryReport.cs create mode 100644 PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Forms/FormDirectoryReport.resx create mode 100644 PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Forms/FormToDistributionReport.Designer.cs create mode 100644 PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Forms/FormToDistributionReport.cs create mode 100644 PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Forms/FormToDistributionReport.resx create mode 100644 PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Reports/ChartReport.cs create mode 100644 PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Reports/DocReport.cs create mode 100644 PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Reports/ExcelBuilder.cs create mode 100644 PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Reports/PdfBuilder.cs create mode 100644 PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Reports/TableReport.cs create mode 100644 PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Reports/WordBuilder.cs diff --git a/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Entities/RoutSheet.cs b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Entities/RoutSheet.cs index d6057f0..e9fe613 100644 --- a/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Entities/RoutSheet.cs +++ b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Entities/RoutSheet.cs @@ -1,4 +1,5 @@ -using System; +using DocumentFormat.OpenXml.Bibliography; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -25,7 +26,22 @@ public class RoutSheet ConductorId = conductorid, RoutId = routid, RoutSheetBus = RoutSheetBus, - BusDate = busDate, + BusDate = busDate }; } + + public static RoutSheet CreatOpeartion(TempRoutSheetBus tempRoutSheetBus, IEnumerable RoutSheetBus) + { + return new RoutSheet + { + Id = tempRoutSheetBus.Id, + DriverId = tempRoutSheetBus.DriverId, + ConductorId = tempRoutSheetBus.ConductorId, + RoutId = tempRoutSheetBus.RoutId, + RoutSheetBus = RoutSheetBus, + BusDate = tempRoutSheetBus.BusDate + }; + } + + } diff --git a/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Entities/TempRoutSheetBus.cs b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Entities/TempRoutSheetBus.cs new file mode 100644 index 0000000..bdf759c --- /dev/null +++ b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Entities/TempRoutSheetBus.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PIbd_24_EredavkinRA_BusBusiness.Entities; + +public class TempRoutSheetBus +{ + public int Id { get; private set; } + + public int DriverId { get; private set; } + public int ConductorId { get; private set; } + + public int RoutId { get; private set; } + + public DateTime BusDate { get; private set; } + + public int BusId { get; private set; } + public decimal Cost { get; private set; } +} diff --git a/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Entities/To.cs b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Entities/To.cs index f1e84e9..7ebadad 100644 --- a/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Entities/To.cs +++ b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Entities/To.cs @@ -18,14 +18,14 @@ public class To public double Cost { get; private set; } public DateTime DateTo { get; private set; } - public static To CreatOperation(int id, string discription, double cost, int busid, int staffid) + public static To CreatOperation(int id, string discription, double cost, DateTime dateTo, int busid, int staffid) { return new To() { Id = id, Discription = discription ?? string.Empty, Cost = cost, - DateTo = DateTime.Now, + DateTo = dateTo, BusID = busid, StaffID = staffid }; diff --git a/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/FormBus.Designer.cs b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/FormBus.Designer.cs index 5c66fc4..8e8c2fd 100644 --- a/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/FormBus.Designer.cs +++ b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/FormBus.Designer.cs @@ -37,6 +37,9 @@ RoutSheetToolStripMenuItem = new ToolStripMenuItem(); ToesToolStripMenuItem = new ToolStripMenuItem(); отчетыToolStripMenuItem = new ToolStripMenuItem(); + DirectoryReportToolStripMenuItem = new ToolStripMenuItem(); + ToolStripMenuItem = new ToolStripMenuItem(); + ToolStripMenuItemTo = new ToolStripMenuItem(); menuStrip1.SuspendLayout(); SuspendLayout(); // @@ -100,10 +103,35 @@ // // отчетыToolStripMenuItem // + отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { DirectoryReportToolStripMenuItem, ToolStripMenuItem, ToolStripMenuItemTo }); отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem"; отчетыToolStripMenuItem.Size = new Size(60, 20); отчетыToolStripMenuItem.Text = "Отчеты"; // + // DirectoryReportToolStripMenuItem + // + DirectoryReportToolStripMenuItem.Name = "DirectoryReportToolStripMenuItem"; + DirectoryReportToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.W; + DirectoryReportToolStripMenuItem.Size = new Size(362, 22); + DirectoryReportToolStripMenuItem.Text = "Документ со справочниками"; + DirectoryReportToolStripMenuItem.Click += DirectoryReportToolStripMenuItem_Click; + // + // ToolStripMenuItem + // + ToolStripMenuItem.Name = "ToolStripMenuItem"; + ToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.E; + ToolStripMenuItem.Size = new Size(362, 22); + ToolStripMenuItem.Text = "Сводка по Автобусам"; + ToolStripMenuItem.Click += ToolStripMenuItem_Click; + // + // ToolStripMenuItemTo + // + ToolStripMenuItemTo.Name = "ToolStripMenuItemTo"; + ToolStripMenuItemTo.ShortcutKeys = Keys.Control | Keys.P; + ToolStripMenuItemTo.Size = new Size(362, 22); + ToolStripMenuItemTo.Text = "Распределение Технического обслуживания"; + ToolStripMenuItemTo.Click += ToolStripMenuItemTo_Click; + // // FormBus // AutoScaleDimensions = new SizeF(7F, 15F); @@ -133,5 +161,8 @@ private ToolStripMenuItem отчетыToolStripMenuItem; private ToolStripMenuItem ToesToolStripMenuItem; private ToolStripMenuItem ToToolStripMenuItem; + private ToolStripMenuItem DirectoryReportToolStripMenuItem; + private ToolStripMenuItem ToolStripMenuItem; + private ToolStripMenuItem ToolStripMenuItemTo; } } diff --git a/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/FormBus.cs b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/FormBus.cs index 00904a9..14b12f0 100644 --- a/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/FormBus.cs +++ b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/FormBus.cs @@ -51,7 +51,7 @@ public partial class FormBus : Form } } - + private void RoutSheetToolStripMenuItem_Click(object sender, EventArgs e) { @@ -77,4 +77,41 @@ public partial class FormBus : Form MessageBox.Show(ex.Message, " ", MessageBoxButtons.OK, MessageBoxIcon.Error); } } + + private void DirectoryReportToolStripMenuItem_Click(object sender, EventArgs e) + { + try + { + _container.Resolve().ShowDialog(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, " ", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + + } + + private void ToolStripMenuItem_Click(object sender, EventArgs e) + { + try + { + _container.Resolve().ShowDialog(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, " ", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ToolStripMenuItemTo_Click(object sender, EventArgs e) + { + try + { + _container.Resolve().ShowDialog(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, " ", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } } diff --git a/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Forms/FormBusReport.Designer.cs b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Forms/FormBusReport.Designer.cs new file mode 100644 index 0000000..3789662 --- /dev/null +++ b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Forms/FormBusReport.Designer.cs @@ -0,0 +1,163 @@ +namespace PIbd_24_EredavkinRA_BusBusiness.Forms +{ + partial class FormBusReport + { + /// + /// 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() + { + dateTimePickerDateBegin = new DateTimePicker(); + dateTimePickerDateEnd = new DateTimePicker(); + comboBoxBus = new ComboBox(); + textBoxFilePath = new TextBox(); + buttonSelectFilePath = new Button(); + label1 = new Label(); + label2 = new Label(); + label3 = new Label(); + label4 = new Label(); + buttonMakeReport = new Button(); + SuspendLayout(); + // + // dateTimePickerDateBegin + // + dateTimePickerDateBegin.Location = new Point(123, 115); + dateTimePickerDateBegin.Name = "dateTimePickerDateBegin"; + dateTimePickerDateBegin.Size = new Size(278, 23); + dateTimePickerDateBegin.TabIndex = 0; + // + // dateTimePickerDateEnd + // + dateTimePickerDateEnd.Location = new Point(123, 156); + dateTimePickerDateEnd.Name = "dateTimePickerDateEnd"; + dateTimePickerDateEnd.Size = new Size(278, 23); + dateTimePickerDateEnd.TabIndex = 1; + // + // comboBoxBus + // + comboBoxBus.FormattingEnabled = true; + comboBoxBus.Location = new Point(123, 56); + comboBoxBus.Name = "comboBoxBus"; + comboBoxBus.Size = new Size(278, 23); + comboBoxBus.TabIndex = 2; + // + // textBoxFilePath + // + textBoxFilePath.Location = new Point(123, 9); + textBoxFilePath.Name = "textBoxFilePath"; + textBoxFilePath.ReadOnly = true; + textBoxFilePath.Size = new Size(208, 23); + textBoxFilePath.TabIndex = 3; + // + // buttonSelectFilePath + // + buttonSelectFilePath.Location = new Point(337, 12); + buttonSelectFilePath.Name = "buttonSelectFilePath"; + buttonSelectFilePath.Size = new Size(64, 24); + buttonSelectFilePath.TabIndex = 4; + buttonSelectFilePath.Text = "..."; + buttonSelectFilePath.UseVisualStyleBackColor = true; + buttonSelectFilePath.Click += ButtonSelectFilePath_Click; + // + // label1 + // + label1.AutoSize = true; + label1.Location = new Point(12, 9); + label1.Name = "label1"; + label1.Size = new Size(87, 15); + label1.TabIndex = 5; + label1.Text = "Путь до файла"; + // + // label2 + // + label2.AutoSize = true; + label2.Location = new Point(37, 64); + label2.Name = "label2"; + label2.Size = new Size(52, 15); + label2.TabIndex = 6; + label2.Text = "Автобус"; + // + // label3 + // + label3.AutoSize = true; + label3.Location = new Point(31, 115); + label3.Name = "label3"; + label3.Size = new Size(74, 15); + label3.TabIndex = 7; + label3.Text = "Дата начала"; + // + // label4 + // + label4.AutoSize = true; + label4.Location = new Point(37, 162); + label4.Name = "label4"; + label4.Size = new Size(68, 15); + label4.TabIndex = 8; + label4.Text = "Дата конца"; + // + // buttonMakeReport + // + buttonMakeReport.Location = new Point(123, 204); + buttonMakeReport.Name = "buttonMakeReport"; + buttonMakeReport.Size = new Size(204, 23); + buttonMakeReport.TabIndex = 9; + buttonMakeReport.Text = "Сформировать"; + buttonMakeReport.UseVisualStyleBackColor = true; + buttonMakeReport.Click += ButtonMakeReport_Click; + // + // FormBusReport + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(425, 243); + Controls.Add(buttonMakeReport); + Controls.Add(label4); + Controls.Add(label3); + Controls.Add(label2); + Controls.Add(label1); + Controls.Add(buttonSelectFilePath); + Controls.Add(textBoxFilePath); + Controls.Add(comboBoxBus); + Controls.Add(dateTimePickerDateEnd); + Controls.Add(dateTimePickerDateBegin); + Name = "FormBusReport"; + Text = "FormBusReport"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private DateTimePicker dateTimePickerDateBegin; + private DateTimePicker dateTimePickerDateEnd; + private ComboBox comboBoxBus; + private TextBox textBoxFilePath; + private Button buttonSelectFilePath; + private Label label1; + private Label label2; + private Label label3; + private Label label4; + private Button buttonMakeReport; + } +} \ No newline at end of file diff --git a/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Forms/FormBusReport.cs b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Forms/FormBusReport.cs new file mode 100644 index 0000000..5f3c724 --- /dev/null +++ b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Forms/FormBusReport.cs @@ -0,0 +1,82 @@ +using PIbd_24_EredavkinRA_BusBusiness.Reports; +using PIbd_24_EredavkinRA_BusBusiness.Repositories; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using Unity; + +namespace PIbd_24_EredavkinRA_BusBusiness.Forms; + + +public partial class FormBusReport : Form +{ + private readonly IUnityContainer _container; + public FormBusReport(IUnityContainer container, IBusRepository busRepository) + { + InitializeComponent(); + _container = container ?? + throw new ArgumentNullException(nameof(container)); + comboBoxBus.DataSource = busRepository.ReadBus(); + comboBoxBus.DisplayMember = "N_Z"; + comboBoxBus.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 (comboBoxBus.SelectedIndex < 0) + { + throw new Exception("Не выбран автобус"); + } + + if (dateTimePickerDateEnd.Value <= dateTimePickerDateBegin.Value) + { + throw new Exception("Дата начала должна быть раньше даты окончания"); + } + + if (_container.Resolve().CreateTable(textBoxFilePath.Text, + (int)comboBoxBus.SelectedValue!, dateTimePickerDateBegin.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); + } + } + + +} + diff --git a/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Forms/FormBusReport.resx b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Forms/FormBusReport.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Forms/FormBusReport.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/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Forms/FormDirectoryReport.Designer.cs b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Forms/FormDirectoryReport.Designer.cs new file mode 100644 index 0000000..ef2741f --- /dev/null +++ b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Forms/FormDirectoryReport.Designer.cs @@ -0,0 +1,99 @@ +namespace PIbd_24_EredavkinRA_BusBusiness.Forms +{ + partial class FormDirectoryReport + { + /// + /// 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() + { + checkBoxStaff = new CheckBox(); + checkBoxRout = new CheckBox(); + checkBoxBus = new CheckBox(); + buttonBuild = new Button(); + SuspendLayout(); + // + // checkBoxStaff + // + checkBoxStaff.AutoSize = true; + checkBoxStaff.Location = new Point(12, 12); + checkBoxStaff.Name = "checkBoxStaff"; + checkBoxStaff.Size = new Size(92, 19); + checkBoxStaff.TabIndex = 0; + checkBoxStaff.Text = "Сотрудники"; + checkBoxStaff.UseVisualStyleBackColor = true; + // + // checkBoxRout + // + checkBoxRout.AutoSize = true; + checkBoxRout.Location = new Point(12, 53); + checkBoxRout.Name = "checkBoxRout"; + checkBoxRout.Size = new Size(88, 19); + checkBoxRout.TabIndex = 1; + checkBoxRout.Text = "Маршруты"; + checkBoxRout.UseVisualStyleBackColor = true; + // + // checkBoxBus + // + checkBoxBus.AutoSize = true; + checkBoxBus.Location = new Point(12, 98); + checkBoxBus.Name = "checkBoxBus"; + checkBoxBus.Size = new Size(83, 19); + checkBoxBus.TabIndex = 2; + checkBoxBus.Text = "Автобусы "; + checkBoxBus.UseVisualStyleBackColor = true; + // + // buttonBuild + // + buttonBuild.Location = new Point(193, 53); + buttonBuild.Name = "buttonBuild"; + buttonBuild.Size = new Size(134, 23); + buttonBuild.TabIndex = 3; + buttonBuild.Text = "Сформировать"; + buttonBuild.UseVisualStyleBackColor = true; + buttonBuild.Click += buttonBuild_Click; + // + // FormDirectoryReport + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(372, 142); + Controls.Add(buttonBuild); + Controls.Add(checkBoxBus); + Controls.Add(checkBoxRout); + Controls.Add(checkBoxStaff); + Name = "FormDirectoryReport"; + Text = "FormDirectoryReport"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private CheckBox checkBoxStaff; + private CheckBox checkBoxRout; + private CheckBox checkBoxBus; + private Button buttonBuild; + } +} \ No newline at end of file diff --git a/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Forms/FormDirectoryReport.cs b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Forms/FormDirectoryReport.cs new file mode 100644 index 0000000..f561f23 --- /dev/null +++ b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Forms/FormDirectoryReport.cs @@ -0,0 +1,63 @@ +using PIbd_24_EredavkinRA_BusBusiness.Reports; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using Unity; + +namespace PIbd_24_EredavkinRA_BusBusiness.Forms +{ + public partial class FormDirectoryReport : Form + { + private readonly IUnityContainer _container; + public FormDirectoryReport(IUnityContainer container) + { + InitializeComponent(); + _container = container ?? + throw new ArgumentNullException(nameof(container)); + } + + private void buttonBuild_Click(object sender, EventArgs e) + { + try + { + if (!checkBoxBus.Checked && !checkBoxStaff.Checked && !checkBoxRout.Checked) + { + throw new Exception("Не выбран ни один справочник для выгрузки"); + } + + var sfd = new SaveFileDialog() + { + Filter = "Docx Files | *.docx" + }; + + if (sfd.ShowDialog() != DialogResult.OK) + { + throw new Exception("Не выбран файла для отчета"); + } + + if (_container.Resolve().CreateDoc(sfd.FileName, checkBoxBus.Checked, + checkBoxRout.Checked, checkBoxStaff.Checked)) + { + MessageBox.Show("Документ сформирован", "Формирование документа", + MessageBoxButtons.OK, MessageBoxIcon.Information); + } + else + { + MessageBox.Show("Возникли ошибки при формировании документа.Подробности в логах", + "Формирование документа", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка при создании отчета", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + + } + } +} diff --git a/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Forms/FormDirectoryReport.resx b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Forms/FormDirectoryReport.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Forms/FormDirectoryReport.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/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Forms/FormTO.cs b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Forms/FormTO.cs index 2fa5203..e2a56a0 100644 --- a/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Forms/FormTO.cs +++ b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Forms/FormTO.cs @@ -31,7 +31,7 @@ public partial class FormTO : Form { throw new Exception("Имеются не заполненые поля"); } - _toRepository.CreateTo(To.CreatOperation(0, textBoxDescription.Text, Convert.ToDouble(numericUpDownCost.Value), (int)comboBoxBus.SelectedValue!, + _toRepository.CreateTo(To.CreatOperation(0, textBoxDescription.Text, Convert.ToDouble(numericUpDownCost.Value), dateTimePicker1.Value, (int)comboBoxBus.SelectedValue!, (int)comboBoxStaff.SelectedValue!)); Close(); } diff --git a/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Forms/FormToDistributionReport.Designer.cs b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Forms/FormToDistributionReport.Designer.cs new file mode 100644 index 0000000..9582be5 --- /dev/null +++ b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Forms/FormToDistributionReport.Designer.cs @@ -0,0 +1,107 @@ +namespace PIbd_24_EredavkinRA_BusBusiness.Forms +{ + partial class FormToDistributionReport + { + /// + /// 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() + { + dateTimePicker = new DateTimePicker(); + ButtonChoice = new Button(); + labelFileName = new Label(); + label2 = new Label(); + buttontoform = new Button(); + SuspendLayout(); + // + // dateTimePicker + // + dateTimePicker.Location = new Point(100, 72); + dateTimePicker.Name = "dateTimePicker"; + dateTimePicker.Size = new Size(168, 23); + dateTimePicker.TabIndex = 0; + // + // ButtonChoice + // + ButtonChoice.Location = new Point(23, 25); + ButtonChoice.Name = "ButtonChoice"; + ButtonChoice.Size = new Size(75, 23); + ButtonChoice.TabIndex = 1; + ButtonChoice.Text = "Выбрать"; + ButtonChoice.UseVisualStyleBackColor = true; + ButtonChoice.Click += ButtonChoice_Click; + // + // labelFileName + // + labelFileName.AutoSize = true; + labelFileName.Location = new Point(120, 29); + labelFileName.Name = "labelFileName"; + labelFileName.Size = new Size(36, 15); + labelFileName.TabIndex = 2; + labelFileName.Text = "Файл"; + // + // label2 + // + label2.AutoSize = true; + label2.Location = new Point(23, 78); + label2.Name = "label2"; + label2.Size = new Size(32, 15); + label2.TabIndex = 3; + label2.Text = "Дата"; + // + // buttontoform + // + buttontoform.Location = new Point(70, 139); + buttontoform.Name = "buttontoform"; + buttontoform.Size = new Size(117, 23); + buttontoform.TabIndex = 4; + buttontoform.Text = "Сформировать"; + buttontoform.UseVisualStyleBackColor = true; + buttontoform.Click += buttontoform_Click; + // + // FormToDistributionReport + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(280, 209); + Controls.Add(buttontoform); + Controls.Add(label2); + Controls.Add(labelFileName); + Controls.Add(ButtonChoice); + Controls.Add(dateTimePicker); + Name = "FormToDistributionReport"; + Text = "FormToDistributionReport"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private DateTimePicker dateTimePicker; + private Button ButtonChoice; + private Label labelFileName; + private Label label2; + private Button buttontoform; + } +} \ No newline at end of file diff --git a/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Forms/FormToDistributionReport.cs b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Forms/FormToDistributionReport.cs new file mode 100644 index 0000000..49281e7 --- /dev/null +++ b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Forms/FormToDistributionReport.cs @@ -0,0 +1,66 @@ +using PIbd_24_EredavkinRA_BusBusiness.Reports; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using Unity; + +namespace PIbd_24_EredavkinRA_BusBusiness.Forms; + +public partial class FormToDistributionReport : Form +{ + private string _fileName = string.Empty; + + private readonly IUnityContainer _container; + public FormToDistributionReport(IUnityContainer container) + { + InitializeComponent(); + _container = container ?? + throw new ArgumentNullException(nameof(container)); + } + private void ButtonChoice_Click(object sender, EventArgs e) + { + var sfd = new SaveFileDialog() + { + Filter = "Pdf Files | *.pdf" + }; + + if (sfd.ShowDialog() == DialogResult.OK) + { + _fileName = sfd.FileName; + labelFileName.Text = Path.GetFileName(_fileName); + } + } + private void buttontoform_Click(object sender, EventArgs e) + { + try + { + if (string.IsNullOrWhiteSpace(_fileName)) + { + throw new Exception("Отсутствует имя файла для отчета"); + } + + if (_container.Resolve().CreateChart(_fileName, dateTimePicker.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); + } + } + + +} diff --git a/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Forms/FormToDistributionReport.resx b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Forms/FormToDistributionReport.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Forms/FormToDistributionReport.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/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness.csproj b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness.csproj index 4bc2224..5c66109 100644 --- a/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness.csproj +++ b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness.csproj @@ -11,11 +11,13 @@ + + diff --git a/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Reports/ChartReport.cs b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Reports/ChartReport.cs new file mode 100644 index 0000000..7d68980 --- /dev/null +++ b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Reports/ChartReport.cs @@ -0,0 +1,52 @@ +using Microsoft.Extensions.Logging; +using PIbd_24_EredavkinRA_BusBusiness.Repositories; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PIbd_24_EredavkinRA_BusBusiness.Reports; + +internal class ChartReport +{ + private readonly IToRepository _toRepository; + + private readonly ILogger _logger; + + public ChartReport(IToRepository toRepository, ILogger logger) + { + _toRepository = toRepository ?? + throw new ArgumentNullException(nameof(toRepository)); + _logger = logger ?? + throw new ArgumentNullException(nameof(logger)); + } + + public bool CreateChart(string filePath, DateTime dateTime) + { + try + { + new PdfBuilder(filePath) + .AddHeader("Количество Обслуживаний Автобуса за день") + .AddPieChart("Автобусы", GetData(dateTime)) + .Build(); + + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при формировании документа"); + return false; + } + } + + private List<(string Caption, double Value)> GetData(DateTime dateTime) + { + return _toRepository + .ReadTo() + .Where(x => x.DateTo.Date == dateTime.Date) + .GroupBy(x => x.BusID, (key, cost) => new { Id = key, Count = cost.Count() }) + .Select(x => (x.Id.ToString(), (double)x.Count)) + .ToList(); + } +} diff --git a/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Reports/DocReport.cs b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Reports/DocReport.cs new file mode 100644 index 0000000..c773a57 --- /dev/null +++ b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Reports/DocReport.cs @@ -0,0 +1,103 @@ +using Microsoft.Extensions.Logging; +using PIbd_24_EredavkinRA_BusBusiness.Repositories; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PIbd_24_EredavkinRA_BusBusiness.Reports; + +internal class DocReport +{ + private readonly IBusRepository _busRepository; + + private readonly IRoutRepositories _routRepository; + + private readonly IStaffRepositories _staffRepository; + + private readonly ILogger _logger; + + public DocReport(IBusRepository busRepository, + IRoutRepositories routRepository, IStaffRepositories staffRepository, ILogger logger) + { + _busRepository = busRepository ?? + throw new ArgumentNullException(nameof(busRepository)); + _routRepository = routRepository ?? + throw new ArgumentNullException(nameof(routRepository)); + _staffRepository = staffRepository ?? + throw new ArgumentNullException(nameof(staffRepository)); + _logger = logger ?? + throw new ArgumentNullException(nameof(logger)); + } + public bool CreateDoc(string filePath, bool includeBus, bool includeRout, + bool includeStaff) + { + try + { + var builder = new WordBuilder(filePath) + .AddHeader("Документ со справочниками"); + + if (includeBus) + { + builder.AddParagraph("Автобусы") + .AddTable([1200, 2400, 1200], GetBuses()); + } + + if (includeRout) + { + builder.AddParagraph("Маршруты") + .AddTable([2400, 2400, 2400], GetRout()); + } + + if (includeStaff) + { + builder.AddParagraph("Сотрудники") + .AddTable([2400, 2400, 2400], GetStaff()); + } + + + + builder.Build(); + + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при формировании документа"); + return false; + } + } + + private List GetBuses() + { + return [ + ["Модель", "Номерной знак", "Количество мест"], + .. _busRepository + .ReadBus() + .Select(x => new string[] { x.ModelType.ToString(), x.N_Z, x.Capacity.ToString() }), + ]; + } + + + + private List GetStaff() + { + return [ + ["Фамилия", "Имя", "Должность"], + .. _staffRepository + .ReadStaff() + .Select(x => new string[] { x.LastName, x.FirstName, x.EmployeePost.ToString() }), + ]; + } + + private List GetRout() + { + return [ + ["Номер Маршрута", "Начальная остановка", "Конечная остановка"], + .. _routRepository + .ReadRout() + .Select(x => new string[] { x.NumberRout.ToString(), x.StartStop, x.EndStop }), + ]; + } +} diff --git a/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Reports/ExcelBuilder.cs b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Reports/ExcelBuilder.cs new file mode 100644 index 0000000..ecf07cb --- /dev/null +++ b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Reports/ExcelBuilder.cs @@ -0,0 +1,328 @@ +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Spreadsheet; +using DocumentFormat.OpenXml; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PIbd_24_EredavkinRA_BusBusiness.Reports; + +internal 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.BoldTextWithoutBorder); + for (int i = startIndex + 1; i < startIndex + count; ++i) + { + CreateCell(i, _rowIndex, "", StyleIndex.SimpleTextWithoutBorder); + } + + _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("columnsWidths.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() { Val = true } + }); + + workbookStylesPart.Stylesheet.Append(fonts); + + // Default Fill + var fills = new Fills() { Count = 1 }; + fills.Append(new Fill + { + PatternFill = new PatternFill() { PatternType = new EnumValue(PatternValues.None) } + }); + workbookStylesPart.Stylesheet.Append(fills); + + // Default Border + 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); + + // Default cell format and a date cell format + 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 = 0, + BorderId = 1, + FillId = 0, + Alignment = new Alignment() + { + Horizontal = HorizontalAlignmentValues.Right, + Vertical = VerticalAlignmentValues.Center, + WrapText = true + } + }); + + cellFormats.Append(new CellFormat + { + NumberFormatId = 0, + FormatId = 0, + FontId = 1, + BorderId = 0, + FillId = 0, + Alignment = new Alignment() + { + Horizontal = HorizontalAlignmentValues.Center, + Vertical = VerticalAlignmentValues.Center, + WrapText = true + } + }); + + cellFormats.Append(new CellFormat + { + NumberFormatId = 0, + FormatId = 0, + FontId = 1, + BorderId = 1, + FillId = 0, + Alignment = new Alignment() + { + Horizontal = HorizontalAlignmentValues.Center, + Vertical = VerticalAlignmentValues.Center, + WrapText = true + } + }); + workbookStylesPart.Stylesheet.Append(cellFormats); + } + + private enum StyleIndex + { + SimpleTextWithoutBorder = 0, + SimpleTextWithBorder = 1, + BoldTextWithoutBorder = 2, + BoldTextWithBorder = 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; + } + +} diff --git a/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Reports/PdfBuilder.cs b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Reports/PdfBuilder.cs new file mode 100644 index 0000000..3542cb3 --- /dev/null +++ b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Reports/PdfBuilder.cs @@ -0,0 +1,93 @@ +using MigraDoc.DocumentObjectModel; +using MigraDoc.Rendering; +using MigraDoc.DocumentObjectModel.Shapes.Charts; +using System.Text; +using System.Threading.Tasks; + +namespace PIbd_24_EredavkinRA_BusBusiness.Reports; + +internal class PdfBuilder +{ + private readonly string _filePath; + + private readonly Document _document; + + public PdfBuilder(string filePath) + { + if (string.IsNullOrWhiteSpace(filePath)) + { + throw new ArgumentNullException(nameof(filePath)); + } + + if (File.Exists(filePath)) + { + File.Delete(filePath); + } + + _filePath = filePath; + _document = new Document(); + DefineStyles(); + } + + public PdfBuilder AddHeader(string header) + { + _document.AddSection().AddParagraph(header, "NormalBold"); + return this; + } + + public PdfBuilder AddPieChart(string title, List<(string Caption, double Value)> data) + { + if (data == null || data.Count == 0) + { + return this; + } + + var chart = new Chart(ChartType.Pie2D); + var series = chart.SeriesCollection.AddSeries(); + series.Add(data.Select(x => x.Value).ToArray()); + + var xseries = chart.XValues.AddXSeries(); + xseries.Add(data.Select(x => x.Caption).ToArray()); + + chart.DataLabel.Type = DataLabelType.Percent; + chart.DataLabel.Position = DataLabelPosition.OutsideEnd; + + chart.Width = Unit.FromCentimeter(16); + chart.Height = Unit.FromCentimeter(12); + + chart.TopArea.AddParagraph(title); + + chart.XAxis.MajorTickMark = TickMarkType.Outside; + + chart.YAxis.MajorTickMark = TickMarkType.Outside; + chart.YAxis.HasMajorGridlines = true; + + chart.PlotArea.LineFormat.Width = 1; + chart.PlotArea.LineFormat.Visible = true; + + chart.TopArea.AddLegend(); + + _document.LastSection.Add(chart); + + return this; + } + + public void Build() + { + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + var renderer = new PdfDocumentRenderer(true) + { + Document = _document + }; + + renderer.RenderDocument(); + renderer.PdfDocument.Save(_filePath); + } + + private void DefineStyles() + { + var headerStyle = _document.Styles.AddStyle("NormalBold", "Normal"); + headerStyle.Font.Bold = true; + headerStyle.Font.Size = 14; + } +} diff --git a/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Reports/TableReport.cs b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Reports/TableReport.cs new file mode 100644 index 0000000..f5dcebb --- /dev/null +++ b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Reports/TableReport.cs @@ -0,0 +1,98 @@ +using Microsoft.Extensions.Logging; +using PIbd_24_EredavkinRA_BusBusiness.Entities; +using PIbd_24_EredavkinRA_BusBusiness.Repositories; +using PIbd_24_EredavkinRA_BusBusiness.Repositories.Implementations; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PIbd_24_EredavkinRA_BusBusiness.Reports; + +internal class TableReport +{ + private readonly IRoutSheetRepository _routsheetRepository; + + private readonly IToRepository _toRepository; + + private readonly IBusRepository _busRepository; + + private readonly ILogger _logger; + + internal static readonly string[] item = ["Дата", "Номер Маршрута", "Стоимость ремонта"]; + + public TableReport(IRoutSheetRepository routsheetRepository, IToRepository toRepository, IBusRepository busRepository, ILogger logger) + { + _routsheetRepository = routsheetRepository ?? + throw new ArgumentNullException(nameof(routsheetRepository)); + _toRepository = toRepository ?? + throw new ArgumentNullException(nameof(toRepository)); + _busRepository = busRepository ?? + throw new ArgumentNullException(nameof(busRepository)); + + + _logger = logger ?? + throw new ArgumentNullException(nameof(logger)); + } + + public bool CreateTable(string filePath, int busId, DateTime startDate, DateTime endDate) + { + try + { + new ExcelBuilder(filePath) + .AddHeader("Общая сводка за Автобусами", 0, 3) + .AddParagraph("за период", 0) + .AddTable([15, 10, 10], GetData(busId, startDate, endDate)) + .Build(); + + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при формировании документа"); + return false; + } + } + + public List GetData(int busId, DateTime startDate, DateTime endDate) + { + var data = _routsheetRepository + .ReadRoutSheet() + .Where(x => x.BusDate >= startDate && x.BusDate <= endDate && x.RoutSheetBus.Any(y => y.BusID == busId)) + .Select(x => new { + Date = x.BusDate, + Rout = (int?)x.RoutId, + Cost = (decimal?)null + }) + .Union( + _toRepository + .ReadTo() + .Where(x => x.DateTo >= startDate && x.DateTo <= endDate && x.BusID == busId) + .Select(x => new { + Date = x.DateTo, + Rout = (int?)null, + Cost = (decimal?)x.Cost + })) + .OrderBy(x => x.Date); + + return new List { item } + .Union( + data.Select(x => new string[] + { + x.Date.ToString("dd.MM.yyyy"), + x.Rout?.ToString() ?? string.Empty, + x.Cost?.ToString() ?? string.Empty + })) + .Union(new[] { new string[] { "Всего", "", data.Sum(x => x.Cost ?? 0).ToString() } }) + .ToList(); + + + } + + + + + + +} diff --git a/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Reports/WordBuilder.cs b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Reports/WordBuilder.cs new file mode 100644 index 0000000..f8040d5 --- /dev/null +++ b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Reports/WordBuilder.cs @@ -0,0 +1,107 @@ +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Wordprocessing; +using DocumentFormat.OpenXml; + + +namespace PIbd_24_EredavkinRA_BusBusiness.Reports; + +internal class WordBuilder +{ + private readonly string _filePath; + + private readonly Document _document; + + private readonly Body _body; + + public WordBuilder(string filePath) + { + if (string.IsNullOrWhiteSpace(filePath)) + { + throw new ArgumentNullException(nameof(filePath)); + } + + if (File.Exists(filePath)) + { + File.Delete(filePath); + } + + _filePath = filePath; + _document = new Document(); + _body = _document.AppendChild(new Body()); + } + + public WordBuilder AddHeader(string header) + { + var paragraph = _body.AppendChild(new Paragraph()); + var run = paragraph.AppendChild(new Run()); + run.AppendChild(new RunProperties(new Bold())); + run.AppendChild(new Text(header)); + + return this; + } + + public WordBuilder AddParagraph(string text) + { + var paragraph = _body.AppendChild(new Paragraph()); + var run = paragraph.AppendChild(new Run()); + run.AppendChild(new Text(text)); + + return this; + } + + public WordBuilder AddTable(int[] widths, List data) + { + if (widths == null || widths.Length == 0) + { + throw new ArgumentNullException(nameof(widths)); + } + + if (data == null || data.Count == 0) + { + throw new ArgumentNullException(nameof(data)); + } + + if (data.Any(x => x.Length != widths.Length)) + { + throw new InvalidOperationException("widths.Length != data.Length"); + } + + var table = new Table(); + table.AppendChild(new TableProperties( + new TableBorders( + new TopBorder() { Val = new EnumValue(BorderValues.Single), Size = 12 }, + new BottomBorder() { Val = new EnumValue(BorderValues.Single), Size = 12 }, + new LeftBorder() { Val = new EnumValue(BorderValues.Single), Size = 12 }, + new RightBorder() { Val = new EnumValue(BorderValues.Single), Size = 12 }, + new InsideHorizontalBorder() { Val = new EnumValue(BorderValues.Single), Size = 12 }, + new InsideVerticalBorder() { Val = new EnumValue(BorderValues.Single), Size = 12 } + ) + )); + + //Заголовок + var tr = new TableRow(); + for (var j = 0; j < widths.Length; ++j) + { + tr.Append(new TableCell( + new TableCellProperties(new TableCellWidth() { Width = widths[j].ToString() }), + new Paragraph(new Run(new RunProperties(new Bold()), new Text(data.First()[j]))))); + } + table.Append(tr); + + // Данные + table.Append(data.Skip(1).Select(x => + new TableRow(x.Select(y => new TableCell(new Paragraph(new Run(new Text(y)))))))); + + _body.Append(table); + + return this; + } + + public void Build() + { + using var wordDocument = WordprocessingDocument.Create(_filePath, WordprocessingDocumentType.Document); + var mainPart = wordDocument.AddMainDocumentPart(); + mainPart.Document = _document; + } + +} diff --git a/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Repositories/Implementations/RoutSheetRepository.cs b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Repositories/Implementations/RoutSheetRepository.cs index f689175..2e366cb 100644 --- a/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Repositories/Implementations/RoutSheetRepository.cs +++ b/PIbd-24_EredavkinRA_BusBusiness/PIbd-24_EredavkinRA_BusBusiness/Repositories/Implementations/RoutSheetRepository.cs @@ -1,4 +1,5 @@ using Dapper; +using DocumentFormat.OpenXml.Bibliography; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Npgsql; @@ -58,10 +59,11 @@ public class RoutSheetRepository : IRoutSheetRepository try { using var connection = new NpgsqlConnection(_connectionString.ConnectionString); - var querySelect = "SELECT * FROM RoutSheet"; - var routsheet = connection.Query(querySelect); + var querySelect = @"SELECT cs.*, dcs.BusId FROM RoutSheet cs + INNER JOIN RoutSheetBus dcs ON dcs.RoutSheetId = cs.Id"; + var routsheet = connection.Query(querySelect); _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(routsheet)); - return routsheet; + return routsheet.GroupBy(x => x.Id, y => y, (key, value) => RoutSheet.CreatOpeartion(value.First(), value.Select(z => RoutSheetBus.CreateElement(0, z.BusId)))).ToList(); } catch (Exception ex) {