From 8d1763bee754d92d65fd733ab27be836ea7797e0 Mon Sep 17 00:00:00 2001 From: qkrlnt Date: Sun, 8 Dec 2024 23:35:29 +0400 Subject: [PATCH 1/4] =?UTF-8?q?=D0=BF=D1=80=D0=BE=D0=BC=D0=B5=D0=B6=D1=83?= =?UTF-8?q?=D1=82=D0=BE=D1=87=D0=BD=D1=8B=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../FuelAccounting/Entities/Equipage.cs | 14 + .../FuelAccounting/Entities/RoutesEqipage.cs | 4 +- .../Entities/TempRoutesEquipage.cs | 18 + .../FormFuelAccounting.Designer.cs | 33 +- .../FuelAccounting/FormFuelAccounting.cs | 26 ++ .../Forms/FormCarReport.Designer.cs | 164 +++++++++ .../FuelAccounting/Forms/FormCarReport.cs | 82 +++++ .../FuelAccounting/Forms/FormCarReport.resx | 120 +++++++ .../Forms/FormDirectoryReport.Designer.cs | 113 ++++++ .../Forms/FormDirectoryReport.cs | 60 ++++ .../Forms/FormDirectoryReport.resx | 120 +++++++ .../FuelAccounting/Forms/FormEquipage.cs | 3 +- .../FuelAccounting/FuelAccounting.csproj | 1 + .../FuelAccounting/Reports/DocReport.cs | 110 ++++++ .../FuelAccounting/Reports/ExcelBuilder.cs | 330 ++++++++++++++++++ .../FuelAccounting/Reports/TableReport.cs | 102 ++++++ .../FuelAccounting/Reports/WordBuilder.cs | 106 ++++++ .../Implementations/EquipageRepository.cs | 30 +- 18 files changed, 1417 insertions(+), 19 deletions(-) create mode 100644 FuelAccounting/FuelAccounting/Entities/TempRoutesEquipage.cs create mode 100644 FuelAccounting/FuelAccounting/Forms/FormCarReport.Designer.cs create mode 100644 FuelAccounting/FuelAccounting/Forms/FormCarReport.cs create mode 100644 FuelAccounting/FuelAccounting/Forms/FormCarReport.resx create mode 100644 FuelAccounting/FuelAccounting/Forms/FormDirectoryReport.Designer.cs create mode 100644 FuelAccounting/FuelAccounting/Forms/FormDirectoryReport.cs create mode 100644 FuelAccounting/FuelAccounting/Forms/FormDirectoryReport.resx create mode 100644 FuelAccounting/FuelAccounting/Reports/DocReport.cs create mode 100644 FuelAccounting/FuelAccounting/Reports/ExcelBuilder.cs create mode 100644 FuelAccounting/FuelAccounting/Reports/TableReport.cs create mode 100644 FuelAccounting/FuelAccounting/Reports/WordBuilder.cs diff --git a/FuelAccounting/FuelAccounting/Entities/Equipage.cs b/FuelAccounting/FuelAccounting/Entities/Equipage.cs index 181cc7d..caee5d6 100644 --- a/FuelAccounting/FuelAccounting/Entities/Equipage.cs +++ b/FuelAccounting/FuelAccounting/Entities/Equipage.cs @@ -26,4 +26,18 @@ public class Equipage EquipageDate = DateTime.Now }; } + + public static Equipage CreateOperation(TempRoutesEquipage tempRoutesEquipage, + IEnumerable routesEqipage) + { + return new Equipage + { + Id = tempRoutesEquipage.Id, + CarId = tempRoutesEquipage.CarId, + DriverId = tempRoutesEquipage.DriverId, + ShiftId = tempRoutesEquipage.ShiftId, + RoutesEqipage = routesEqipage, + EquipageDate = tempRoutesEquipage.EquipageDate + }; + } } diff --git a/FuelAccounting/FuelAccounting/Entities/RoutesEqipage.cs b/FuelAccounting/FuelAccounting/Entities/RoutesEqipage.cs index d704366..a65406b 100644 --- a/FuelAccounting/FuelAccounting/Entities/RoutesEqipage.cs +++ b/FuelAccounting/FuelAccounting/Entities/RoutesEqipage.cs @@ -4,7 +4,7 @@ public class RoutesEqipage { public int Id { get; private set; } - public int RouteID { get; private set; } + public int RouteId { get; private set; } public int Count { get; private set; } @@ -13,7 +13,7 @@ public class RoutesEqipage return new RoutesEqipage { Id = id, - RouteID = routeId, + RouteId = routeId, Count = count }; } diff --git a/FuelAccounting/FuelAccounting/Entities/TempRoutesEquipage.cs b/FuelAccounting/FuelAccounting/Entities/TempRoutesEquipage.cs new file mode 100644 index 0000000..56adc8c --- /dev/null +++ b/FuelAccounting/FuelAccounting/Entities/TempRoutesEquipage.cs @@ -0,0 +1,18 @@ +namespace FuelAccounting.Entities; + +public class TempRoutesEquipage +{ + public int Id { get; private set; } + + public int CarId { get; private set; } + + public int DriverId { get; private set; } + + public int ShiftId { get; private set; } + + public int RouteId { get; private set; } + + public int Count { get; private set; } + + public DateTime EquipageDate { get; private set; } +} diff --git a/FuelAccounting/FuelAccounting/FormFuelAccounting.Designer.cs b/FuelAccounting/FuelAccounting/FormFuelAccounting.Designer.cs index 9c86b78..bf07b7a 100644 --- a/FuelAccounting/FuelAccounting/FormFuelAccounting.Designer.cs +++ b/FuelAccounting/FuelAccounting/FormFuelAccounting.Designer.cs @@ -38,6 +38,8 @@ выездToolStripMenuItem = new ToolStripMenuItem(); заправкаToolStripMenuItem = new ToolStripMenuItem(); отчетыToolStripMenuItem = new ToolStripMenuItem(); + directoryReportToolStripMenuItem = new ToolStripMenuItem(); + CarSummaryToolStripMenuItem = new ToolStripMenuItem(); menuStrip.SuspendLayout(); SuspendLayout(); // @@ -60,28 +62,28 @@ // автомобилиToolStripMenuItem // автомобилиToolStripMenuItem.Name = "автомобилиToolStripMenuItem"; - автомобилиToolStripMenuItem.Size = new Size(180, 22); + автомобилиToolStripMenuItem.Size = new Size(144, 22); автомобилиToolStripMenuItem.Text = "Автомобили"; автомобилиToolStripMenuItem.Click += CarsToolStripMenuItem_Click; // // водителиToolStripMenuItem // водителиToolStripMenuItem.Name = "водителиToolStripMenuItem"; - водителиToolStripMenuItem.Size = new Size(180, 22); + водителиToolStripMenuItem.Size = new Size(144, 22); водителиToolStripMenuItem.Text = "Водители"; водителиToolStripMenuItem.Click += DriversToolStripMenuItem_Click; // // сменыToolStripMenuItem // сменыToolStripMenuItem.Name = "сменыToolStripMenuItem"; - сменыToolStripMenuItem.Size = new Size(180, 22); + сменыToolStripMenuItem.Size = new Size(144, 22); сменыToolStripMenuItem.Text = "Смены"; сменыToolStripMenuItem.Click += ShiftsToolStripMenuItem_Click; // // маршрутыToolStripMenuItem // маршрутыToolStripMenuItem.Name = "маршрутыToolStripMenuItem"; - маршрутыToolStripMenuItem.Size = new Size(180, 22); + маршрутыToolStripMenuItem.Size = new Size(144, 22); маршрутыToolStripMenuItem.Text = "Маршруты"; маршрутыToolStripMenuItem.Click += RoutesToolStripMenuItem_Click; // @@ -95,23 +97,40 @@ // выездToolStripMenuItem // выездToolStripMenuItem.Name = "выездToolStripMenuItem"; - выездToolStripMenuItem.Size = new Size(180, 22); + выездToolStripMenuItem.Size = new Size(125, 22); выездToolStripMenuItem.Text = "Выезд"; выездToolStripMenuItem.Click += EquipageToolStripMenuItem_Click; // // заправкаToolStripMenuItem // заправкаToolStripMenuItem.Name = "заправкаToolStripMenuItem"; - заправкаToolStripMenuItem.Size = new Size(180, 22); + заправкаToolStripMenuItem.Size = new Size(125, 22); заправкаToolStripMenuItem.Text = "Заправка"; заправкаToolStripMenuItem.Click += RefuelingToolStripMenuItem_Click; // // отчетыToolStripMenuItem // + отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { directoryReportToolStripMenuItem, CarSummaryToolStripMenuItem }); отчеты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(280, 22); + directoryReportToolStripMenuItem.Text = "Документ со справочниками"; + directoryReportToolStripMenuItem.Click += DirectoryReportToolStripMenuItem_Click; + // + // CarSummaryToolStripMenuItem + // + CarSummaryToolStripMenuItem.Name = "CarSummaryToolStripMenuItem"; + CarSummaryToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.E; + CarSummaryToolStripMenuItem.Size = new Size(280, 22); + CarSummaryToolStripMenuItem.Text = "Сводка по автомобилям"; + CarSummaryToolStripMenuItem.Click += CarSummaryToolStripMenuItem_Click; + // // FormFuelAccounting // AutoScaleDimensions = new SizeF(7F, 15F); @@ -142,5 +161,7 @@ private ToolStripMenuItem выездToolStripMenuItem; private ToolStripMenuItem заправкаToolStripMenuItem; private ToolStripMenuItem отчетыToolStripMenuItem; + private ToolStripMenuItem directoryReportToolStripMenuItem; + private ToolStripMenuItem CarSummaryToolStripMenuItem; } } \ No newline at end of file diff --git a/FuelAccounting/FuelAccounting/FormFuelAccounting.cs b/FuelAccounting/FuelAccounting/FormFuelAccounting.cs index 0f76a57..1ce58ce 100644 --- a/FuelAccounting/FuelAccounting/FormFuelAccounting.cs +++ b/FuelAccounting/FuelAccounting/FormFuelAccounting.cs @@ -106,5 +106,31 @@ namespace FuelAccounting } } + + 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 CarSummaryToolStripMenuItem_Click(object sender, EventArgs e) + { + try + { + _container.Resolve().ShowDialog(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка при загрузке", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } } } diff --git a/FuelAccounting/FuelAccounting/Forms/FormCarReport.Designer.cs b/FuelAccounting/FuelAccounting/Forms/FormCarReport.Designer.cs new file mode 100644 index 0000000..7a6daa8 --- /dev/null +++ b/FuelAccounting/FuelAccounting/Forms/FormCarReport.Designer.cs @@ -0,0 +1,164 @@ +namespace FuelAccounting.Forms +{ + partial class FormCarReport + { + /// + /// 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() + { + dateTimePickerBegin = new DateTimePicker(); + textBoxFilePath = new TextBox(); + label1 = new Label(); + buttonFilePath = new Button(); + label2 = new Label(); + comboBoxCar = new ComboBox(); + label3 = new Label(); + label4 = new Label(); + dateTimePickerEnd = new DateTimePicker(); + buttonBuild = new Button(); + SuspendLayout(); + // + // dateTimePickerBegin + // + dateTimePickerBegin.Location = new Point(129, 119); + dateTimePickerBegin.Name = "dateTimePickerBegin"; + dateTimePickerBegin.Size = new Size(207, 23); + dateTimePickerBegin.TabIndex = 0; + // + // textBoxFilePath + // + textBoxFilePath.Location = new Point(129, 26); + textBoxFilePath.Name = "textBoxFilePath"; + textBoxFilePath.ReadOnly = true; + textBoxFilePath.Size = new Size(175, 23); + textBoxFilePath.TabIndex = 1; + // + // label1 + // + label1.AutoSize = true; + label1.Location = new Point(21, 29); + label1.Name = "label1"; + label1.Size = new Size(90, 15); + label1.TabIndex = 2; + label1.Text = "Путь до файла:"; + // + // buttonFilePath + // + buttonFilePath.Location = new Point(310, 26); + buttonFilePath.Name = "buttonFilePath"; + buttonFilePath.Size = new Size(26, 23); + buttonFilePath.TabIndex = 3; + buttonFilePath.Text = "..."; + buttonFilePath.UseVisualStyleBackColor = true; + buttonFilePath.Click += ButtonFilePath_Click; + // + // label2 + // + label2.AutoSize = true; + label2.Location = new Point(21, 75); + label2.Name = "label2"; + label2.Size = new Size(79, 15); + label2.TabIndex = 4; + label2.Text = "Автомобиль:"; + // + // comboBoxCar + // + comboBoxCar.FormattingEnabled = true; + comboBoxCar.Location = new Point(129, 72); + comboBoxCar.Name = "comboBoxCar"; + comboBoxCar.Size = new Size(175, 23); + comboBoxCar.TabIndex = 5; + // + // label3 + // + label3.AutoSize = true; + label3.Location = new Point(21, 125); + label3.Name = "label3"; + label3.Size = new Size(77, 15); + label3.TabIndex = 6; + label3.Text = "Дата начала:"; + // + // label4 + // + label4.AutoSize = true; + label4.Location = new Point(21, 169); + label4.Name = "label4"; + label4.Size = new Size(71, 15); + label4.TabIndex = 7; + label4.Text = "Дата конца:"; + // + // dateTimePickerEnd + // + dateTimePickerEnd.Location = new Point(129, 169); + dateTimePickerEnd.Name = "dateTimePickerEnd"; + dateTimePickerEnd.Size = new Size(207, 23); + dateTimePickerEnd.TabIndex = 8; + // + // buttonBuild + // + buttonBuild.Location = new Point(21, 208); + buttonBuild.Name = "buttonBuild"; + buttonBuild.Size = new Size(315, 32); + buttonBuild.TabIndex = 9; + buttonBuild.Text = "Сформировать"; + buttonBuild.UseVisualStyleBackColor = true; + buttonBuild.Click += ButtonBuild_Click; + // + // FormCarReport + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(358, 252); + Controls.Add(buttonBuild); + Controls.Add(dateTimePickerEnd); + Controls.Add(label4); + Controls.Add(label3); + Controls.Add(comboBoxCar); + Controls.Add(label2); + Controls.Add(buttonFilePath); + Controls.Add(label1); + Controls.Add(textBoxFilePath); + Controls.Add(dateTimePickerBegin); + Name = "FormCarReport"; + StartPosition = FormStartPosition.CenterScreen; + Text = "Отчет до пройденным километрам"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private DateTimePicker dateTimePickerBegin; + private TextBox textBoxFilePath; + private Label label1; + private Button buttonFilePath; + private Label label2; + private ComboBox comboBoxCar; + private Label label3; + private Label label4; + private DateTimePicker dateTimePickerEnd; + private Button buttonBuild; + } +} \ No newline at end of file diff --git a/FuelAccounting/FuelAccounting/Forms/FormCarReport.cs b/FuelAccounting/FuelAccounting/Forms/FormCarReport.cs new file mode 100644 index 0000000..435e445 --- /dev/null +++ b/FuelAccounting/FuelAccounting/Forms/FormCarReport.cs @@ -0,0 +1,82 @@ +using FuelAccounting.Reports; +using FuelAccounting.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 FuelAccounting.Forms +{ + public partial class FormCarReport : Form + { + private readonly IUnityContainer _container; + + public FormCarReport(IUnityContainer container, ICarsRepository carsRepository) + { + InitializeComponent(); + _container = container ?? throw new ArgumentNullException(nameof(container)); + + comboBoxCar.DataSource = carsRepository.ReadCars(); + comboBoxCar.DisplayMember = "Model"; + comboBoxCar.ValueMember = "Id"; + } + + private void ButtonFilePath_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 ButtonBuild_Click(object sender, EventArgs e) + { + try + { + if (string.IsNullOrWhiteSpace(textBoxFilePath.Text)) + { + throw new Exception("Отсутствует имя файла или отчета"); + } + + if (comboBoxCar.SelectedIndex < 0) + { + throw new Exception("Не выбран автомобиль"); + } + + if (dateTimePickerBegin.Value >= dateTimePickerEnd.Value) + { + throw new Exception("Дата начала должна быть раньше даты окончания"); + } + + if (_container.Resolve().CreateTable(textBoxFilePath.Text, + (int)comboBoxCar.SelectedValue!, dateTimePickerBegin.Value, dateTimePickerEnd.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/FuelAccounting/FuelAccounting/Forms/FormCarReport.resx b/FuelAccounting/FuelAccounting/Forms/FormCarReport.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/FuelAccounting/FuelAccounting/Forms/FormCarReport.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/FuelAccounting/FuelAccounting/Forms/FormDirectoryReport.Designer.cs b/FuelAccounting/FuelAccounting/Forms/FormDirectoryReport.Designer.cs new file mode 100644 index 0000000..f852506 --- /dev/null +++ b/FuelAccounting/FuelAccounting/Forms/FormDirectoryReport.Designer.cs @@ -0,0 +1,113 @@ +namespace FuelAccounting.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() + { + checkBoxCars = new CheckBox(); + checkBoxDrivers = new CheckBox(); + checkBoxShifts = new CheckBox(); + checkBoxRoutes = new CheckBox(); + buttonBuild = new Button(); + SuspendLayout(); + // + // checkBoxCars + // + checkBoxCars.AutoSize = true; + checkBoxCars.Location = new Point(12, 12); + checkBoxCars.Name = "checkBoxCars"; + checkBoxCars.Size = new Size(96, 19); + checkBoxCars.TabIndex = 0; + checkBoxCars.Text = "Автомобили"; + checkBoxCars.UseVisualStyleBackColor = true; + // + // checkBoxDrivers + // + checkBoxDrivers.AutoSize = true; + checkBoxDrivers.Location = new Point(12, 57); + checkBoxDrivers.Name = "checkBoxDrivers"; + checkBoxDrivers.Size = new Size(78, 19); + checkBoxDrivers.TabIndex = 1; + checkBoxDrivers.Text = "Водители"; + checkBoxDrivers.UseVisualStyleBackColor = true; + // + // checkBoxShifts + // + checkBoxShifts.AutoSize = true; + checkBoxShifts.Location = new Point(12, 101); + checkBoxShifts.Name = "checkBoxShifts"; + checkBoxShifts.Size = new Size(65, 19); + checkBoxShifts.TabIndex = 2; + checkBoxShifts.Text = "Смены"; + checkBoxShifts.UseVisualStyleBackColor = true; + // + // checkBoxRoutes + // + checkBoxRoutes.AutoSize = true; + checkBoxRoutes.Location = new Point(12, 149); + checkBoxRoutes.Name = "checkBoxRoutes"; + checkBoxRoutes.Size = new Size(88, 19); + checkBoxRoutes.TabIndex = 3; + checkBoxRoutes.Text = "Маршруты"; + checkBoxRoutes.UseVisualStyleBackColor = true; + // + // buttonBuild + // + buttonBuild.Location = new Point(154, 12); + buttonBuild.Name = "buttonBuild"; + buttonBuild.Size = new Size(172, 156); + buttonBuild.TabIndex = 4; + buttonBuild.Text = "Сформировать"; + buttonBuild.UseVisualStyleBackColor = true; + buttonBuild.Click += ButtonBuild_Click; + // + // FormDirectoryReport + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(338, 184); + Controls.Add(buttonBuild); + Controls.Add(checkBoxRoutes); + Controls.Add(checkBoxShifts); + Controls.Add(checkBoxDrivers); + Controls.Add(checkBoxCars); + Name = "FormDirectoryReport"; + StartPosition = FormStartPosition.CenterScreen; + Text = "Выгрузка справочников"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private CheckBox checkBoxCars; + private CheckBox checkBoxDrivers; + private CheckBox checkBoxShifts; + private CheckBox checkBoxRoutes; + private Button buttonBuild; + } +} \ No newline at end of file diff --git a/FuelAccounting/FuelAccounting/Forms/FormDirectoryReport.cs b/FuelAccounting/FuelAccounting/Forms/FormDirectoryReport.cs new file mode 100644 index 0000000..b36d84d --- /dev/null +++ b/FuelAccounting/FuelAccounting/Forms/FormDirectoryReport.cs @@ -0,0 +1,60 @@ +using FuelAccounting.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 FuelAccounting.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 (!checkBoxCars.Checked && !checkBoxDrivers.Checked && !checkBoxRoutes.Checked && !checkBoxShifts.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, checkBoxCars.Checked, + checkBoxDrivers.Checked, checkBoxRoutes.Checked, checkBoxShifts.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/FuelAccounting/FuelAccounting/Forms/FormDirectoryReport.resx b/FuelAccounting/FuelAccounting/Forms/FormDirectoryReport.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/FuelAccounting/FuelAccounting/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/FuelAccounting/FuelAccounting/Forms/FormEquipage.cs b/FuelAccounting/FuelAccounting/Forms/FormEquipage.cs index 7887ea5..cca29ff 100644 --- a/FuelAccounting/FuelAccounting/Forms/FormEquipage.cs +++ b/FuelAccounting/FuelAccounting/Forms/FormEquipage.cs @@ -82,7 +82,8 @@ namespace FuelAccounting.Forms Convert.ToInt32(row.Cells["ColumnCount"].Value))); } - return list; + return list.GroupBy(x => x.RouteId, x => x.Count, (id, counts) => + RoutesEqipage.CreateElement(0, id, counts.Sum())).ToList(); } } } diff --git a/FuelAccounting/FuelAccounting/FuelAccounting.csproj b/FuelAccounting/FuelAccounting/FuelAccounting.csproj index ebed082..62b2a29 100644 --- a/FuelAccounting/FuelAccounting/FuelAccounting.csproj +++ b/FuelAccounting/FuelAccounting/FuelAccounting.csproj @@ -10,6 +10,7 @@ + diff --git a/FuelAccounting/FuelAccounting/Reports/DocReport.cs b/FuelAccounting/FuelAccounting/Reports/DocReport.cs new file mode 100644 index 0000000..8f4ec7d --- /dev/null +++ b/FuelAccounting/FuelAccounting/Reports/DocReport.cs @@ -0,0 +1,110 @@ +using FuelAccounting.Repositories; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FuelAccounting.Reports; + +internal class DocReport +{ + private readonly ICarsRepository _carsRepository; + private readonly IDriversRepository _driversRepository; + private readonly IShiftRepository _shiftRepository; + private readonly IRouteRepository _routeRepository; + + private readonly ILogger _logger; + + public DocReport (ICarsRepository carsRepository, IDriversRepository driversRepository, + IShiftRepository shiftRepository, IRouteRepository routeRepository, ILogger logger) + { + _carsRepository = carsRepository ?? + throw new ArgumentNullException(nameof(carsRepository)); + _driversRepository = driversRepository ?? + throw new ArgumentNullException(nameof(driversRepository)); + _shiftRepository = shiftRepository ?? + throw new ArgumentNullException(nameof(shiftRepository)); + _routeRepository = routeRepository ?? + throw new ArgumentNullException(nameof(routeRepository)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + public bool CreateDoc(string filePath, bool includeCars, bool includeDrivers, bool includeShift, bool includeRoute) + { + try + { + var builder = new WordBuilder(filePath).AddHeader("Документ со справочниками"); + + if (includeCars) + { + builder.AddParagraph("Автомобили").AddTable([2400, 1200, 1200], GetCars()); + } + + if (includeDrivers) + { + builder.AddParagraph("Водители").AddTable([2400, 2400, 1200], GetDrivers()); + } + + if (includeShift) + { + builder.AddParagraph("Смены").AddTable([1200, 2400], GetShift()); + } + + if (includeRoute) + { + builder.AddParagraph("Маршруты").AddTable([2400], GetRoute()); + } + + builder.Build(); + + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при формировании документа"); + return false; + } + } + + private List GetCars() + { + return [ + ["Модель", "Категория", "Id Водителя"], + .. _carsRepository + .ReadCars() + .Select(x => new string[] {x.Model, x.Category.ToString(), x.DriverID.ToString()}), + ]; + } + + private List GetDrivers() + { + return [ + ["Имя", "Фамилия", "Категория прав"], + .. _driversRepository + .ReadDrivers() + .Select(x => new string[] {x.FirstName, x.LastName, x.DriverLicenceCategory.ToString()}), + ]; + } + + private List GetShift() + { + return [ + ["Количество часов", "Описание"], + .. _shiftRepository + .ReadShifts() + .Select(x => new string[] {x.AmountOfHours.ToString(), x.Description}), + ]; + } + + private List GetRoute() + { + return [ + ["Описание"], + .. _routeRepository + .ReadRoutes() + .Select(x => new string[] {x.Description}), + ]; + } +} diff --git a/FuelAccounting/FuelAccounting/Reports/ExcelBuilder.cs b/FuelAccounting/FuelAccounting/Reports/ExcelBuilder.cs new file mode 100644 index 0000000..3fd717a --- /dev/null +++ b/FuelAccounting/FuelAccounting/Reports/ExcelBuilder.cs @@ -0,0 +1,330 @@ +using DocumentFormat.OpenXml; +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Spreadsheet; + +namespace FuelAccounting.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("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() { 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/FuelAccounting/FuelAccounting/Reports/TableReport.cs b/FuelAccounting/FuelAccounting/Reports/TableReport.cs new file mode 100644 index 0000000..47a0630 --- /dev/null +++ b/FuelAccounting/FuelAccounting/Reports/TableReport.cs @@ -0,0 +1,102 @@ +using FuelAccounting.Repositories; +using Microsoft.Extensions.Logging; +using System.Linq; + +namespace FuelAccounting.Reports; + +internal class TableReport +{ + private readonly IEquipageRepository _equipageRepository; + private readonly IRefuelingRepository _refuelingRepository; + + private readonly ILogger _logger; + + internal static readonly string[] item = ["Автомобиль", "Водитель", "Литров заправлено", "Дата"]; + + public TableReport(IEquipageRepository equipageRepository, + IRefuelingRepository refuelingRepository, ILogger logger) + { + _equipageRepository = equipageRepository ?? + throw new ArgumentNullException(nameof(equipageRepository)); + _refuelingRepository = refuelingRepository ?? + throw new ArgumentNullException(nameof(refuelingRepository)); + _logger = logger ?? throw new ArgumentNullException(nameof(_logger)); + } + + public bool CreateTable(string filePath, int carId, DateTime startDate, DateTime endDate) + { + try + { + new ExcelBuilder(filePath) + .AddHeader("Сводка по автомобилям", 0, 4) + .AddParagraph("За период", 0) + .AddTable([15, 15, 10, 15], GetData(carId, startDate, endDate)) + .Build(); + + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при формировании документа"); + return false; + } + } + + private List GetData(int carId, DateTime startDate, DateTime endDate) + { + // Получение данных об экипажах + var equipageData = _equipageRepository + .ReadEquipages() + .Where(x => x.EquipageDate >= startDate && x.EquipageDate <= endDate && x.CarId == carId) + .Select(x => new + { + CarId = x.CarId, + Driver = x.DriverId.ToString(), + Liters = 0.0, // Данные о заправке отсутствуют + Date = x.EquipageDate + }); + + // Получение данных о заправках + var refuelingData = _refuelingRepository + .ReadRefuelings() + .Where(x => x.RefuelingDate >= startDate && x.RefuelingDate <= endDate && x.CarId == carId) + .Select(x => new + { + x.CarId, + Driver = string.Empty, // Данные о водителе отсутствуют + Liters = (double)x.LitersSpent, + Date = x.RefuelingDate + }); + + // Объединение данных об экипажах и заправках + var mergedData = equipageData + .Union(refuelingData) + .GroupBy(x => new { x.CarId, x.Date }) // Группировка по дате и машине + .Select(g => new + { + g.Key.CarId, + Driver = string.Join(", ", g.Select(x => x.Driver).Where(d => !string.IsNullOrEmpty(d))), + Liters = g.Sum(x => x.Liters), + g.Key.Date + }) + .OrderBy(x => x.Date); + + // Формирование строк данных + return new List { item } + .Union( + mergedData.Select(x => new string[] + { + x.CarId.ToString(), + x.Driver, + x.Liters.ToString("F2"), // Форматирование до 2-х знаков после запятой + x.Date.ToString("dd.MM.yyyy") // Форматирование даты + })) + .Union( + new[] + { + new string[] { "Всего", string.Empty, mergedData.Sum(x => x.Liters).ToString("F2"), string.Empty } + }) + .ToList(); + } + +} diff --git a/FuelAccounting/FuelAccounting/Reports/WordBuilder.cs b/FuelAccounting/FuelAccounting/Reports/WordBuilder.cs new file mode 100644 index 0000000..ff1c868 --- /dev/null +++ b/FuelAccounting/FuelAccounting/Reports/WordBuilder.cs @@ -0,0 +1,106 @@ +using DocumentFormat.OpenXml; +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Wordprocessing; + +namespace FuelAccounting.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()); + var runProperties = run.AppendChild(new RunProperties()); + runProperties.AppendChild(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/FuelAccounting/FuelAccounting/Repositories/Implementations/EquipageRepository.cs b/FuelAccounting/FuelAccounting/Repositories/Implementations/EquipageRepository.cs index 29c6682..478231d 100644 --- a/FuelAccounting/FuelAccounting/Repositories/Implementations/EquipageRepository.cs +++ b/FuelAccounting/FuelAccounting/Repositories/Implementations/EquipageRepository.cs @@ -41,7 +41,7 @@ INSERT INTO RoutesEquipage (equipage_id, route_id, count) VALUES (@EquipageId, @RouteId, @Count)"; foreach (var elem in equipage.RoutesEqipage) { - connection.Execute(querySubInsert, new { EquipageId = equipageId, elem.RouteID, elem.Count }, transaction); + connection.Execute(querySubInsert, new { EquipageId = equipageId, elem.RouteId, elem.Count }, transaction); } transaction.Commit(); @@ -81,16 +81,15 @@ WHERE id = @id"; { using var connection = new NpgsqlConnection(_connectionString.ConnectionString); var querySelect = @" -SELECT - id, - car_id AS CarId, - driver_id AS DriverId, - shift_id AS ShiftId, - equipage_date AS EquipageDate -FROM Equipage"; - var equipages = connection.Query(querySelect); +SELECT e.id, e.car_id AS CarId, e.driver_id AS DriverId, e.shift_id AS ShiftId, + e.equipage_date AS EquipageDate, re.route_id AS RouteId, re.count AS Count +FROM Equipage e +INNER JOIN RoutesEquipage re ON re.equipage_id = e.id"; + var equipages = connection.Query(querySelect); _logger.LogDebug("Найденные объекты: {json}", JsonConvert.SerializeObject(equipages)); - return equipages; + return equipages.GroupBy(x => x.Id, y => y, + (key, value) => Equipage.CreateOperation(value.First(), + value.Select(z => RoutesEqipage.CreateElement(0, z.RouteId, z.CarId)))).ToList(); } catch (Exception ex) { @@ -99,3 +98,14 @@ FROM Equipage"; } } } +/* + +SELECT + id, + car_id AS CarId, + driver_id AS DriverId, + shift_id AS ShiftId, + equipage_date AS EquipageDate +FROM Equipage + + */ \ No newline at end of file -- 2.25.1 From 4662c2e508522f398765df078bc40ed30b0a600a Mon Sep 17 00:00:00 2001 From: qkrlnt Date: Mon, 9 Dec 2024 00:41:55 +0400 Subject: [PATCH 2/4] lab 3 done --- .../FormFuelAccounting.Designer.cs | 16 ++- .../FuelAccounting/FormFuelAccounting.cs | 13 ++ .../FormKilometersDrivenReport.Designer.cs | 108 ++++++++++++++++ .../Forms/FormKilometersDrivenReport.cs | 68 ++++++++++ .../Forms/FormKilometersDrivenReport.resx | 120 ++++++++++++++++++ .../FuelAccounting/FuelAccounting.csproj | 1 + .../FuelAccounting/Reports/ChartReport.cs | 47 +++++++ .../FuelAccounting/Reports/PdfBuilder.cs | 87 +++++++++++++ 8 files changed, 457 insertions(+), 3 deletions(-) create mode 100644 FuelAccounting/FuelAccounting/Forms/FormKilometersDrivenReport.Designer.cs create mode 100644 FuelAccounting/FuelAccounting/Forms/FormKilometersDrivenReport.cs create mode 100644 FuelAccounting/FuelAccounting/Forms/FormKilometersDrivenReport.resx create mode 100644 FuelAccounting/FuelAccounting/Reports/ChartReport.cs create mode 100644 FuelAccounting/FuelAccounting/Reports/PdfBuilder.cs diff --git a/FuelAccounting/FuelAccounting/FormFuelAccounting.Designer.cs b/FuelAccounting/FuelAccounting/FormFuelAccounting.Designer.cs index bf07b7a..4b8ba8a 100644 --- a/FuelAccounting/FuelAccounting/FormFuelAccounting.Designer.cs +++ b/FuelAccounting/FuelAccounting/FormFuelAccounting.Designer.cs @@ -40,6 +40,7 @@ отчетыToolStripMenuItem = new ToolStripMenuItem(); directoryReportToolStripMenuItem = new ToolStripMenuItem(); CarSummaryToolStripMenuItem = new ToolStripMenuItem(); + kilometersDrovenToolStripMenuItem = new ToolStripMenuItem(); menuStrip.SuspendLayout(); SuspendLayout(); // @@ -97,20 +98,20 @@ // выездToolStripMenuItem // выездToolStripMenuItem.Name = "выездToolStripMenuItem"; - выездToolStripMenuItem.Size = new Size(125, 22); + выездToolStripMenuItem.Size = new Size(180, 22); выездToolStripMenuItem.Text = "Выезд"; выездToolStripMenuItem.Click += EquipageToolStripMenuItem_Click; // // заправкаToolStripMenuItem // заправкаToolStripMenuItem.Name = "заправкаToolStripMenuItem"; - заправкаToolStripMenuItem.Size = new Size(125, 22); + заправкаToolStripMenuItem.Size = new Size(180, 22); заправкаToolStripMenuItem.Text = "Заправка"; заправкаToolStripMenuItem.Click += RefuelingToolStripMenuItem_Click; // // отчетыToolStripMenuItem // - отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { directoryReportToolStripMenuItem, CarSummaryToolStripMenuItem }); + отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { directoryReportToolStripMenuItem, CarSummaryToolStripMenuItem, kilometersDrovenToolStripMenuItem }); отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem"; отчетыToolStripMenuItem.Size = new Size(60, 20); отчетыToolStripMenuItem.Text = "Отчеты"; @@ -131,6 +132,14 @@ CarSummaryToolStripMenuItem.Text = "Сводка по автомобилям"; CarSummaryToolStripMenuItem.Click += CarSummaryToolStripMenuItem_Click; // + // kilometersDrovenToolStripMenuItem + // + kilometersDrovenToolStripMenuItem.Name = "kilometersDrovenToolStripMenuItem"; + kilometersDrovenToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.P; + kilometersDrovenToolStripMenuItem.Size = new Size(280, 22); + kilometersDrovenToolStripMenuItem.Text = "Сводка по километражу"; + kilometersDrovenToolStripMenuItem.Click += KilometersDrovenToolStripMenuItem_Click; + // // FormFuelAccounting // AutoScaleDimensions = new SizeF(7F, 15F); @@ -163,5 +172,6 @@ private ToolStripMenuItem отчетыToolStripMenuItem; private ToolStripMenuItem directoryReportToolStripMenuItem; private ToolStripMenuItem CarSummaryToolStripMenuItem; + private ToolStripMenuItem kilometersDrovenToolStripMenuItem; } } \ No newline at end of file diff --git a/FuelAccounting/FuelAccounting/FormFuelAccounting.cs b/FuelAccounting/FuelAccounting/FormFuelAccounting.cs index 1ce58ce..4d6a28e 100644 --- a/FuelAccounting/FuelAccounting/FormFuelAccounting.cs +++ b/FuelAccounting/FuelAccounting/FormFuelAccounting.cs @@ -132,5 +132,18 @@ namespace FuelAccounting MessageBoxButtons.OK, MessageBoxIcon.Error); } } + + private void KilometersDrovenToolStripMenuItem_Click(object sender, EventArgs e) + { + try + { + _container.Resolve().ShowDialog(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка при загрузке", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } } } diff --git a/FuelAccounting/FuelAccounting/Forms/FormKilometersDrivenReport.Designer.cs b/FuelAccounting/FuelAccounting/Forms/FormKilometersDrivenReport.Designer.cs new file mode 100644 index 0000000..9690781 --- /dev/null +++ b/FuelAccounting/FuelAccounting/Forms/FormKilometersDrivenReport.Designer.cs @@ -0,0 +1,108 @@ +namespace FuelAccounting.Forms +{ + partial class FormKilometersDrivenReport + { + /// + /// 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() + { + buttonSelectFilePath = new Button(); + labelFileName = new Label(); + label2 = new Label(); + dateTimePicker = new DateTimePicker(); + buttonBuild = new Button(); + SuspendLayout(); + // + // buttonSelectFilePath + // + buttonSelectFilePath.Location = new Point(25, 22); + buttonSelectFilePath.Name = "buttonSelectFilePath"; + buttonSelectFilePath.Size = new Size(98, 35); + buttonSelectFilePath.TabIndex = 0; + buttonSelectFilePath.Text = "Выбрать"; + buttonSelectFilePath.UseVisualStyleBackColor = true; + buttonSelectFilePath.Click += ButtonSelectFilePath_Click; + // + // labelFileName + // + labelFileName.AutoSize = true; + labelFileName.Location = new Point(150, 32); + labelFileName.Name = "labelFileName"; + labelFileName.Size = new Size(36, 15); + labelFileName.TabIndex = 1; + labelFileName.Text = "Файл"; + // + // label2 + // + label2.AutoSize = true; + label2.Location = new Point(25, 81); + label2.Name = "label2"; + label2.Size = new Size(38, 15); + label2.TabIndex = 2; + label2.Text = "Дата: "; + // + // dateTimePicker + // + dateTimePicker.Location = new Point(69, 75); + dateTimePicker.Name = "dateTimePicker"; + dateTimePicker.Size = new Size(200, 23); + dateTimePicker.TabIndex = 3; + // + // buttonBuild + // + buttonBuild.Location = new Point(25, 116); + buttonBuild.Name = "buttonBuild"; + buttonBuild.Size = new Size(244, 46); + buttonBuild.TabIndex = 4; + buttonBuild.Text = "Сформировать"; + buttonBuild.UseVisualStyleBackColor = true; + buttonBuild.Click += ButtonBuild_Click; + // + // FormKilometersDrivenReport + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(293, 182); + Controls.Add(buttonBuild); + Controls.Add(dateTimePicker); + Controls.Add(label2); + Controls.Add(labelFileName); + Controls.Add(buttonSelectFilePath); + Name = "FormKilometersDrivenReport"; + StartPosition = FormStartPosition.CenterScreen; + Text = "Километров пройдено"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Button buttonSelectFilePath; + private Label labelFileName; + private Label label2; + private DateTimePicker dateTimePicker; + private Button buttonBuild; + } +} \ No newline at end of file diff --git a/FuelAccounting/FuelAccounting/Forms/FormKilometersDrivenReport.cs b/FuelAccounting/FuelAccounting/Forms/FormKilometersDrivenReport.cs new file mode 100644 index 0000000..56d9010 --- /dev/null +++ b/FuelAccounting/FuelAccounting/Forms/FormKilometersDrivenReport.cs @@ -0,0 +1,68 @@ +using FuelAccounting.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 FuelAccounting.Forms +{ + public partial class FormKilometersDrivenReport : Form + { + private string _fileName = string.Empty; + + private readonly IUnityContainer _container; + + public FormKilometersDrivenReport(IUnityContainer container) + { + InitializeComponent(); + _container = container ?? + throw new ArgumentNullException(nameof(container)); + } + + private void ButtonSelectFilePath_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 ButtonBuild_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/FuelAccounting/FuelAccounting/Forms/FormKilometersDrivenReport.resx b/FuelAccounting/FuelAccounting/Forms/FormKilometersDrivenReport.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/FuelAccounting/FuelAccounting/Forms/FormKilometersDrivenReport.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/FuelAccounting/FuelAccounting/FuelAccounting.csproj b/FuelAccounting/FuelAccounting/FuelAccounting.csproj index 62b2a29..f9436c8 100644 --- a/FuelAccounting/FuelAccounting/FuelAccounting.csproj +++ b/FuelAccounting/FuelAccounting/FuelAccounting.csproj @@ -16,6 +16,7 @@ + diff --git a/FuelAccounting/FuelAccounting/Reports/ChartReport.cs b/FuelAccounting/FuelAccounting/Reports/ChartReport.cs new file mode 100644 index 0000000..04595da --- /dev/null +++ b/FuelAccounting/FuelAccounting/Reports/ChartReport.cs @@ -0,0 +1,47 @@ +using FuelAccounting.Repositories; +using Microsoft.Extensions.Logging; + +namespace FuelAccounting.Reports; + +internal class ChartReport +{ + private readonly IRefuelingRepository _refuelingRepository; + + private readonly ILogger _logger; + + public ChartReport(IRefuelingRepository refuelingRepository, ILogger logger) + { + _refuelingRepository = refuelingRepository ?? + throw new ArgumentNullException(nameof(refuelingRepository)); + _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 _refuelingRepository + .ReadRefuelings() + .Where(x => x.RefuelingDate == dateTime.Date) + .GroupBy(x => x.CarId, (key, group) => new { Id = key, Count = group.Sum(x => x.Kilometers) }) + .Select(x => (x.Id.ToString(), (double)x.Count)) + .ToList(); + } +} diff --git a/FuelAccounting/FuelAccounting/Reports/PdfBuilder.cs b/FuelAccounting/FuelAccounting/Reports/PdfBuilder.cs new file mode 100644 index 0000000..95bfab4 --- /dev/null +++ b/FuelAccounting/FuelAccounting/Reports/PdfBuilder.cs @@ -0,0 +1,87 @@ +using MigraDoc.DocumentObjectModel; +using MigraDoc.DocumentObjectModel.Shapes.Charts; +using MigraDoc.Rendering; +using System.Text; + +namespace FuelAccounting.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) + { + 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; + } +} -- 2.25.1 From 3a5139d0cf4e0b81db13e6793d1943cef71de14a Mon Sep 17 00:00:00 2001 From: qkrlnt Date: Mon, 9 Dec 2024 13:40:15 +0400 Subject: [PATCH 3/4] =?UTF-8?q?=D1=83=D0=B1=D1=80=D0=B0=D0=BB=20=D0=BB?= =?UTF-8?q?=D0=B8=D1=88=D0=BD=D0=B8=D0=B9=20=D0=BA=D0=BE=D0=BC=D0=BC=D0=B5?= =?UTF-8?q?=D0=BD=D1=82=D0=B0=D1=80=D0=B8=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Implementations/EquipageRepository.cs | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/FuelAccounting/FuelAccounting/Repositories/Implementations/EquipageRepository.cs b/FuelAccounting/FuelAccounting/Repositories/Implementations/EquipageRepository.cs index 478231d..2894252 100644 --- a/FuelAccounting/FuelAccounting/Repositories/Implementations/EquipageRepository.cs +++ b/FuelAccounting/FuelAccounting/Repositories/Implementations/EquipageRepository.cs @@ -97,15 +97,4 @@ INNER JOIN RoutesEquipage re ON re.equipage_id = e.id"; throw; } } -} -/* - -SELECT - id, - car_id AS CarId, - driver_id AS DriverId, - shift_id AS ShiftId, - equipage_date AS EquipageDate -FROM Equipage - - */ \ No newline at end of file +} \ No newline at end of file -- 2.25.1 From b8a2fd7c2c51d3fdfa662873a3002e37ea99199b Mon Sep 17 00:00:00 2001 From: qkrlnt Date: Fri, 13 Dec 2024 12:17:45 +0400 Subject: [PATCH 4/4] =?UTF-8?q?=D0=BF=D0=BE=D1=81=D0=BB=D0=B5=D0=B4=D0=BD?= =?UTF-8?q?=D0=B8=D0=B5=20=D0=BF=D1=80=D0=B0=D0=B2=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- FuelAccounting/FuelAccounting/Forms/FormCarReport.cs | 9 --------- .../FuelAccounting/Forms/FormDirectoryReport.cs | 9 --------- .../FuelAccounting/Forms/FormKilometersDrivenReport.cs | 9 --------- FuelAccounting/FuelAccounting/Reports/DocReport.cs | 5 ----- FuelAccounting/FuelAccounting/Reports/TableReport.cs | 1 - 5 files changed, 33 deletions(-) diff --git a/FuelAccounting/FuelAccounting/Forms/FormCarReport.cs b/FuelAccounting/FuelAccounting/Forms/FormCarReport.cs index 435e445..84ac9fd 100644 --- a/FuelAccounting/FuelAccounting/Forms/FormCarReport.cs +++ b/FuelAccounting/FuelAccounting/Forms/FormCarReport.cs @@ -1,14 +1,5 @@ using FuelAccounting.Reports; using FuelAccounting.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 FuelAccounting.Forms diff --git a/FuelAccounting/FuelAccounting/Forms/FormDirectoryReport.cs b/FuelAccounting/FuelAccounting/Forms/FormDirectoryReport.cs index b36d84d..6f15dff 100644 --- a/FuelAccounting/FuelAccounting/Forms/FormDirectoryReport.cs +++ b/FuelAccounting/FuelAccounting/Forms/FormDirectoryReport.cs @@ -1,13 +1,4 @@ using FuelAccounting.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 FuelAccounting.Forms; diff --git a/FuelAccounting/FuelAccounting/Forms/FormKilometersDrivenReport.cs b/FuelAccounting/FuelAccounting/Forms/FormKilometersDrivenReport.cs index 56d9010..4606a33 100644 --- a/FuelAccounting/FuelAccounting/Forms/FormKilometersDrivenReport.cs +++ b/FuelAccounting/FuelAccounting/Forms/FormKilometersDrivenReport.cs @@ -1,13 +1,4 @@ using FuelAccounting.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 FuelAccounting.Forms diff --git a/FuelAccounting/FuelAccounting/Reports/DocReport.cs b/FuelAccounting/FuelAccounting/Reports/DocReport.cs index 8f4ec7d..4d8f853 100644 --- a/FuelAccounting/FuelAccounting/Reports/DocReport.cs +++ b/FuelAccounting/FuelAccounting/Reports/DocReport.cs @@ -1,10 +1,5 @@ using FuelAccounting.Repositories; using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace FuelAccounting.Reports; diff --git a/FuelAccounting/FuelAccounting/Reports/TableReport.cs b/FuelAccounting/FuelAccounting/Reports/TableReport.cs index 47a0630..982cbb8 100644 --- a/FuelAccounting/FuelAccounting/Reports/TableReport.cs +++ b/FuelAccounting/FuelAccounting/Reports/TableReport.cs @@ -1,6 +1,5 @@ using FuelAccounting.Repositories; using Microsoft.Extensions.Logging; -using System.Linq; namespace FuelAccounting.Reports; -- 2.25.1