diff --git a/ProjectGarage/Entities/Driver.cs b/ProjectGarage/Entities/Driver.cs index f5a5131..8909ff8 100644 --- a/ProjectGarage/Entities/Driver.cs +++ b/ProjectGarage/Entities/Driver.cs @@ -1,4 +1,9 @@ -using ProjectGarage.Entities.Enums; +using Dapper; +using DocumentFormat.OpenXml.Office2010.Excel; +using Newtonsoft.Json; +using Npgsql; +using ProjectGarage.Entities.Enums; +using ProjectGarage.Repositories; using System; using System.Collections.Generic; using System.Linq; diff --git a/ProjectGarage/Entities/FuelReplenishment.cs b/ProjectGarage/Entities/FuelReplenishment.cs index fbc4b34..4d7bb28 100644 --- a/ProjectGarage/Entities/FuelReplenishment.cs +++ b/ProjectGarage/Entities/FuelReplenishment.cs @@ -23,4 +23,15 @@ public class FuelReplenishment FuelFuelReplenishments = fuelFuelReplenishments }; } + + public static FuelReplenishment CreateOpeartion(TempFuelReplenishment tempFuelReplenishment, IEnumerable fuelFuelReplenishments) + { + return new FuelReplenishment + { + Id = tempFuelReplenishment.Id, + DriverId = tempFuelReplenishment.DriverId, + ReplenishmentDate = tempFuelReplenishment.ReplenishmentDate, + FuelFuelReplenishments = fuelFuelReplenishments + }; + } } diff --git a/ProjectGarage/Entities/TempFuelReplenishment.cs b/ProjectGarage/Entities/TempFuelReplenishment.cs new file mode 100644 index 0000000..e00b8fd --- /dev/null +++ b/ProjectGarage/Entities/TempFuelReplenishment.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectGarage.Entities; + +public class TempFuelReplenishment +{ + public int Id { get; private set; } + + public int DriverId { get; private set; } + + public DateTime ReplenishmentDate { get; private set; } + + public int FuelId { get; private set; } + + public int Amount { get; private set; } +} diff --git a/ProjectGarage/FormGarage.Designer.cs b/ProjectGarage/FormGarage.Designer.cs index 5fa1e37..8df389c 100644 --- a/ProjectGarage/FormGarage.Designer.cs +++ b/ProjectGarage/FormGarage.Designer.cs @@ -39,6 +39,9 @@ отправкаТопливаToolStripMenuItem = new ToolStripMenuItem(); получениеТопливаToolStripMenuItem = new ToolStripMenuItem(); отчетыToolStripMenuItem = new ToolStripMenuItem(); + directorReportToolStripMenuItem = new ToolStripMenuItem(); + fuelReportToolStripMenuItem = new ToolStripMenuItem(); + DistributionReporToolStripMenuItem = new ToolStripMenuItem(); menuStripGarage.SuspendLayout(); SuspendLayout(); // @@ -62,28 +65,28 @@ // водителиToolStripMenuItem // водителиToolStripMenuItem.Name = "водителиToolStripMenuItem"; - водителиToolStripMenuItem.Size = new Size(224, 26); + водителиToolStripMenuItem.Size = new Size(167, 26); водителиToolStripMenuItem.Text = "Водители"; водителиToolStripMenuItem.Click += DriversToolStripMenuItem_Click; // // фурыToolStripMenuItem // фурыToolStripMenuItem.Name = "фурыToolStripMenuItem"; - фурыToolStripMenuItem.Size = new Size(224, 26); + фурыToolStripMenuItem.Size = new Size(167, 26); фурыToolStripMenuItem.Text = "Фуры"; фурыToolStripMenuItem.Click += TrucksToolStripMenuItem_Click; // // маршрутыToolStripMenuItem // маршрутыToolStripMenuItem.Name = "маршрутыToolStripMenuItem"; - маршрутыToolStripMenuItem.Size = new Size(224, 26); + маршрутыToolStripMenuItem.Size = new Size(167, 26); маршрутыToolStripMenuItem.Text = "Маршруты"; маршрутыToolStripMenuItem.Click += RoutesToolStripMenuItem_Click; // // топливоToolStripMenuItem // топливоToolStripMenuItem.Name = "топливоToolStripMenuItem"; - топливоToolStripMenuItem.Size = new Size(224, 26); + топливоToolStripMenuItem.Size = new Size(167, 26); топливоToolStripMenuItem.Text = "Топливо"; топливоToolStripMenuItem.Click += FuelsToolStripMenuItem_Click; // @@ -110,10 +113,35 @@ // // отчетыToolStripMenuItem // + отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { directorReportToolStripMenuItem, fuelReportToolStripMenuItem, DistributionReporToolStripMenuItem }); отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem"; отчетыToolStripMenuItem.Size = new Size(73, 24); отчетыToolStripMenuItem.Text = "Отчеты"; // + // directorReportToolStripMenuItem + // + directorReportToolStripMenuItem.Name = "directorReportToolStripMenuItem"; + directorReportToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.W; + directorReportToolStripMenuItem.Size = new Size(350, 26); + directorReportToolStripMenuItem.Text = "Документ со справочниками"; + directorReportToolStripMenuItem.Click += DirectoryReportToolStripMenuItem_Click; + // + // fuelReportToolStripMenuItem + // + fuelReportToolStripMenuItem.Name = "fuelReportToolStripMenuItem"; + fuelReportToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.E; + fuelReportToolStripMenuItem.Size = new Size(350, 26); + fuelReportToolStripMenuItem.Text = "Движение топлива"; + fuelReportToolStripMenuItem.Click += FuelReportToolStripMenuItem_Click; + // + // DistributionReporToolStripMenuItem + // + DistributionReporToolStripMenuItem.Name = "DistributionReporToolStripMenuItem"; + DistributionReporToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.P; + DistributionReporToolStripMenuItem.Size = new Size(350, 26); + DistributionReporToolStripMenuItem.Text = "Распределение топлива"; + DistributionReporToolStripMenuItem.Click += DistributionReportToolStripMenuItem_Click; + // // FormGarage // AutoScaleDimensions = new SizeF(8F, 20F); @@ -143,5 +171,8 @@ private ToolStripMenuItem отправкаТопливаToolStripMenuItem; private ToolStripMenuItem получениеТопливаToolStripMenuItem; private ToolStripMenuItem отчетыToolStripMenuItem; + private ToolStripMenuItem directorReportToolStripMenuItem; + private ToolStripMenuItem fuelReportToolStripMenuItem; + private ToolStripMenuItem DistributionReporToolStripMenuItem; } } diff --git a/ProjectGarage/FormGarage.cs b/ProjectGarage/FormGarage.cs index cac09cb..59c8b9f 100644 --- a/ProjectGarage/FormGarage.cs +++ b/ProjectGarage/FormGarage.cs @@ -91,5 +91,44 @@ namespace ProjectGarage 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 FuelReportToolStripMenuItem_Click(object sender, EventArgs e) + { + try + { + _container.Resolve().ShowDialog(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, " ", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void DistributionReportToolStripMenuItem_Click(object sender, EventArgs e) + { + try + { + _container.Resolve().ShowDialog(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, " ", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } } } diff --git a/ProjectGarage/Forms/FormDirectorReport.Designer.cs b/ProjectGarage/Forms/FormDirectorReport.Designer.cs new file mode 100644 index 0000000..e2c6639 --- /dev/null +++ b/ProjectGarage/Forms/FormDirectorReport.Designer.cs @@ -0,0 +1,112 @@ +namespace ProjectGarage.Forms +{ + partial class FormDirectorReport + { + /// + /// 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() + { + checkBoxFuelReport = new CheckBox(); + checkBoxRouteReport = new CheckBox(); + checkBoxTruckReport = new CheckBox(); + ButtonBuild = new Button(); + checkBoxDriverReport = new CheckBox(); + SuspendLayout(); + // + // checkBoxFuelReport + // + checkBoxFuelReport.AutoSize = true; + checkBoxFuelReport.Location = new Point(29, 40); + checkBoxFuelReport.Name = "checkBoxFuelReport"; + checkBoxFuelReport.Size = new Size(91, 24); + checkBoxFuelReport.TabIndex = 0; + checkBoxFuelReport.Text = "Топливо"; + checkBoxFuelReport.UseVisualStyleBackColor = true; + // + // checkBoxRouteReport + // + checkBoxRouteReport.AutoSize = true; + checkBoxRouteReport.Location = new Point(29, 99); + checkBoxRouteReport.Name = "checkBoxRouteReport"; + checkBoxRouteReport.Size = new Size(106, 24); + checkBoxRouteReport.TabIndex = 1; + checkBoxRouteReport.Text = "Маршруты"; + checkBoxRouteReport.UseVisualStyleBackColor = true; + // + // checkBoxTruckReport + // + checkBoxTruckReport.AutoSize = true; + checkBoxTruckReport.Location = new Point(167, 40); + checkBoxTruckReport.Name = "checkBoxTruckReport"; + checkBoxTruckReport.Size = new Size(69, 24); + checkBoxTruckReport.TabIndex = 2; + checkBoxTruckReport.Text = "Фуры"; + checkBoxTruckReport.UseVisualStyleBackColor = true; + // + // ButtonBuild + // + ButtonBuild.Location = new Point(72, 138); + ButtonBuild.Name = "ButtonBuild"; + ButtonBuild.Size = new Size(132, 40); + ButtonBuild.TabIndex = 3; + ButtonBuild.Text = "Сформировать"; + ButtonBuild.UseVisualStyleBackColor = true; + ButtonBuild.Click += ButtonBuild_Click; + // + // checkBoxDriverReport + // + checkBoxDriverReport.AutoSize = true; + checkBoxDriverReport.Location = new Point(167, 99); + checkBoxDriverReport.Name = "checkBoxDriverReport"; + checkBoxDriverReport.Size = new Size(97, 24); + checkBoxDriverReport.TabIndex = 4; + checkBoxDriverReport.Text = "Водители"; + checkBoxDriverReport.UseVisualStyleBackColor = true; + // + // FormDirectorReport + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(300, 199); + Controls.Add(checkBoxDriverReport); + Controls.Add(ButtonBuild); + Controls.Add(checkBoxTruckReport); + Controls.Add(checkBoxRouteReport); + Controls.Add(checkBoxFuelReport); + Name = "FormDirectorReport"; + Text = "FormDirectorReport"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private CheckBox checkBoxFuelReport; + private CheckBox checkBoxRouteReport; + private CheckBox checkBoxTruckReport; + private Button ButtonBuild; + private CheckBox checkBoxDriverReport; + } +} \ No newline at end of file diff --git a/ProjectGarage/Forms/FormDirectorReport.cs b/ProjectGarage/Forms/FormDirectorReport.cs new file mode 100644 index 0000000..7be8193 --- /dev/null +++ b/ProjectGarage/Forms/FormDirectorReport.cs @@ -0,0 +1,65 @@ +using ProjectGarage.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 ProjectGarage.Forms +{ + public partial class FormDirectorReport : Form + { + private readonly IUnityContainer _container; + + public FormDirectorReport(IUnityContainer container) + { + InitializeComponent(); + _container = container ?? throw new ArgumentNullException(nameof(container)); _container = container; + } + + private void ButtonBuild_Click(object sender, EventArgs e) + { + try + { + if (!checkBoxFuelReport.Checked && !checkBoxTruckReport.Checked && + !checkBoxDriverReport.Checked && !checkBoxRouteReport.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, checkBoxFuelReport.Checked, + checkBoxDriverReport.Checked, checkBoxRouteReport.Checked, checkBoxTruckReport.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/ProjectGarage/Forms/FormDirectorReport.resx b/ProjectGarage/Forms/FormDirectorReport.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/ProjectGarage/Forms/FormDirectorReport.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/ProjectGarage/Forms/FormFuelReport.Designer.cs b/ProjectGarage/Forms/FormFuelReport.Designer.cs new file mode 100644 index 0000000..01a4bc3 --- /dev/null +++ b/ProjectGarage/Forms/FormFuelReport.Designer.cs @@ -0,0 +1,162 @@ +namespace ProjectGarage.Forms +{ + partial class FormFuelReport + { + /// + /// 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() + { + dateTimePickerStart = new DateTimePicker(); + dateTimePickerFinal = new DateTimePicker(); + buttonMakeReport = new Button(); + labelPathToFile = new Label(); + labelFuel = new Label(); + labelDateStart = new Label(); + label4 = new Label(); + buttonSelectFilePath = new Button(); + textBoxFilePath = new TextBox(); + comboBoxFuelReport = new ComboBox(); + SuspendLayout(); + // + // dateTimePickerStart + // + dateTimePickerStart.Location = new Point(180, 150); + dateTimePickerStart.Name = "dateTimePickerStart"; + dateTimePickerStart.Size = new Size(250, 27); + dateTimePickerStart.TabIndex = 0; + // + // dateTimePickerFinal + // + dateTimePickerFinal.Location = new Point(180, 201); + dateTimePickerFinal.Name = "dateTimePickerFinal"; + dateTimePickerFinal.Size = new Size(250, 27); + dateTimePickerFinal.TabIndex = 1; + // + // buttonMakeReport + // + buttonMakeReport.Location = new Point(141, 249); + buttonMakeReport.Name = "buttonMakeReport"; + buttonMakeReport.Size = new Size(145, 38); + buttonMakeReport.TabIndex = 2; + buttonMakeReport.Text = "Сформировать"; + buttonMakeReport.UseVisualStyleBackColor = true; + buttonMakeReport.Click += ButtonMakeReport_Click; + // + // labelPathToFile + // + labelPathToFile.AutoSize = true; + labelPathToFile.Location = new Point(34, 44); + labelPathToFile.Name = "labelPathToFile"; + labelPathToFile.Size = new Size(112, 20); + labelPathToFile.TabIndex = 3; + labelPathToFile.Text = "Путь до файла:"; + // + // labelFuel + // + labelFuel.AutoSize = true; + labelFuel.Location = new Point(34, 94); + labelFuel.Name = "labelFuel"; + labelFuel.Size = new Size(72, 20); + labelFuel.TabIndex = 4; + labelFuel.Text = "Топливо:"; + // + // labelDateStart + // + labelDateStart.AutoSize = true; + labelDateStart.Location = new Point(34, 150); + labelDateStart.Name = "labelDateStart"; + labelDateStart.Size = new Size(97, 20); + labelDateStart.TabIndex = 5; + labelDateStart.Text = "Дата начала:"; + // + // label4 + // + label4.AutoSize = true; + label4.Location = new Point(34, 201); + label4.Name = "label4"; + label4.Size = new Size(90, 20); + label4.TabIndex = 6; + label4.Text = "Дата конца:"; + // + // buttonSelectFilePath + // + buttonSelectFilePath.Location = new Point(405, 44); + buttonSelectFilePath.Name = "buttonSelectFilePath"; + buttonSelectFilePath.Size = new Size(25, 24); + buttonSelectFilePath.TabIndex = 7; + buttonSelectFilePath.Text = "..."; + buttonSelectFilePath.UseVisualStyleBackColor = true; + buttonSelectFilePath.Click += ButtonSelectFilePath_Click; + // + // textBoxFilePath + // + textBoxFilePath.Location = new Point(180, 43); + textBoxFilePath.Name = "textBoxFilePath"; + textBoxFilePath.Size = new Size(219, 27); + textBoxFilePath.TabIndex = 8; + // + // comboBoxFuelReport + // + comboBoxFuelReport.FormattingEnabled = true; + comboBoxFuelReport.Location = new Point(180, 94); + comboBoxFuelReport.Name = "comboBoxFuelReport"; + comboBoxFuelReport.Size = new Size(250, 28); + comboBoxFuelReport.TabIndex = 9; + // + // FormFuelReport + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(454, 311); + Controls.Add(comboBoxFuelReport); + Controls.Add(textBoxFilePath); + Controls.Add(buttonSelectFilePath); + Controls.Add(label4); + Controls.Add(labelDateStart); + Controls.Add(labelFuel); + Controls.Add(labelPathToFile); + Controls.Add(buttonMakeReport); + Controls.Add(dateTimePickerFinal); + Controls.Add(dateTimePickerStart); + Name = "FormFuelReport"; + Text = "FormFuelReport"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private DateTimePicker dateTimePickerStart; + private DateTimePicker dateTimePickerFinal; + private Button buttonMakeReport; + private Label labelPathToFile; + private Label labelFuel; + private Label labelDateStart; + private Label label4; + private Button buttonSelectFilePath; + private TextBox textBoxFilePath; + private ComboBox comboBoxFuelReport; + } +} \ No newline at end of file diff --git a/ProjectGarage/Forms/FormFuelReport.cs b/ProjectGarage/Forms/FormFuelReport.cs new file mode 100644 index 0000000..91da145 --- /dev/null +++ b/ProjectGarage/Forms/FormFuelReport.cs @@ -0,0 +1,82 @@ +using ProjectGarage.Reports; +using ProjectGarage.Repositories; +using ProjectGarage.Repositories.Implementations; +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 ProjectGarage.Forms +{ + public partial class FormFuelReport : Form + { + private readonly IUnityContainer _container; + + public FormFuelReport(IUnityContainer container, IFuelRepository fuelRepository) + { + InitializeComponent(); + _container = container ?? throw new ArgumentNullException(nameof(container)); + comboBoxFuelReport.DataSource = fuelRepository.ReadFuels(); + comboBoxFuelReport.DisplayMember = "FuelName"; + comboBoxFuelReport.ValueMember = "Id"; + } + + private void ButtonMakeReport_Click(object sender, EventArgs e) + { + try + { + if (string.IsNullOrWhiteSpace(textBoxFilePath.Text)) + { + throw new Exception("Отсутствует имя файла для отчета"); + } + if (comboBoxFuelReport.SelectedIndex < 0) + { + throw new Exception("Не выбран корм"); + } + if (dateTimePickerFinal.Value <= dateTimePickerStart.Value) + { + throw new Exception("Дата начала должна быть раньше даты окончания"); + } + if (_container.Resolve().CreateTable(textBoxFilePath.Text, + (int)comboBoxFuelReport.SelectedValue!, + dateTimePickerStart.Value, dateTimePickerFinal.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); + } + } + + 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; + } + } +} diff --git a/ProjectGarage/Forms/FormFuelReport.resx b/ProjectGarage/Forms/FormFuelReport.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/ProjectGarage/Forms/FormFuelReport.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/ProjectGarage/Forms/FormReplenishment.cs b/ProjectGarage/Forms/FormReplenishment.cs index f928f0a..62a7950 100644 --- a/ProjectGarage/Forms/FormReplenishment.cs +++ b/ProjectGarage/Forms/FormReplenishment.cs @@ -66,7 +66,8 @@ namespace ProjectGarage.Forms list.Add(FuelFuelReplenishment.CreateElement(0, Convert.ToInt32(row.Cells["ColumnFuel"].Value), Convert.ToInt32(row.Cells["ColumnAmount"].Value))); } - return list; + return list.GroupBy(x => x.FuelId, x => x.Amount, + (id, counts) => FuelFuelReplenishment.CreateElement(0, id, counts.Sum())).ToList(); } } } diff --git a/ProjectGarage/Forms/FormTransportationDistributionReport.Designer.cs b/ProjectGarage/Forms/FormTransportationDistributionReport.Designer.cs new file mode 100644 index 0000000..bd846c0 --- /dev/null +++ b/ProjectGarage/Forms/FormTransportationDistributionReport.Designer.cs @@ -0,0 +1,107 @@ +namespace ProjectGarage.Forms +{ + partial class FormTransportationDistributionReport + { + /// + /// 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() + { + buttonSelectFileName = new Button(); + dateTimePickerReport = new DateTimePicker(); + buttonCreate = new Button(); + labelFileName = new Label(); + labelDate = new Label(); + SuspendLayout(); + // + // buttonSelectFileName + // + buttonSelectFileName.Location = new Point(28, 28); + buttonSelectFileName.Name = "buttonSelectFileName"; + buttonSelectFileName.Size = new Size(94, 29); + buttonSelectFileName.TabIndex = 0; + buttonSelectFileName.Text = "Выбрать"; + buttonSelectFileName.UseVisualStyleBackColor = true; + buttonSelectFileName.Click += ButtonSelectFileName_Click; + // + // dateTimePickerReport + // + dateTimePickerReport.Location = new Point(90, 81); + dateTimePickerReport.Name = "dateTimePickerReport"; + dateTimePickerReport.Size = new Size(250, 27); + dateTimePickerReport.TabIndex = 1; + // + // buttonCreate + // + buttonCreate.Location = new Point(101, 126); + buttonCreate.Name = "buttonCreate"; + buttonCreate.Size = new Size(123, 29); + buttonCreate.TabIndex = 2; + buttonCreate.Text = "Сформировать"; + buttonCreate.UseVisualStyleBackColor = true; + buttonCreate.Click += ButtonCreate_Click; + // + // labelFileName + // + labelFileName.AutoSize = true; + labelFileName.Location = new Point(142, 32); + labelFileName.Name = "labelFileName"; + labelFileName.Size = new Size(45, 20); + labelFileName.TabIndex = 3; + labelFileName.Text = "Файл"; + // + // labelDate + // + labelDate.AutoSize = true; + labelDate.Location = new Point(28, 86); + labelDate.Name = "labelDate"; + labelDate.Size = new Size(44, 20); + labelDate.TabIndex = 4; + labelDate.Text = "Дата:"; + // + // FormTransportationDistributionReport + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(357, 178); + Controls.Add(labelDate); + Controls.Add(labelFileName); + Controls.Add(buttonCreate); + Controls.Add(dateTimePickerReport); + Controls.Add(buttonSelectFileName); + Name = "FormTransportationDistributionReport"; + Text = "FormTransportationDistributionReport"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Button buttonSelectFileName; + private DateTimePicker dateTimePickerReport; + private Button buttonCreate; + private Label labelFileName; + private Label labelDate; + } +} \ No newline at end of file diff --git a/ProjectGarage/Forms/FormTransportationDistributionReport.cs b/ProjectGarage/Forms/FormTransportationDistributionReport.cs new file mode 100644 index 0000000..ba5f8fd --- /dev/null +++ b/ProjectGarage/Forms/FormTransportationDistributionReport.cs @@ -0,0 +1,71 @@ +using ProjectGarage.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 ProjectGarage.Forms +{ + public partial class FormTransportationDistributionReport : Form + { + private string _fileName = string.Empty; + private readonly IUnityContainer _container; + + public FormTransportationDistributionReport(IUnityContainer container) + { + InitializeComponent(); + _container = container ?? throw new ArgumentNullException(nameof(container)); + } + + private void ButtonSelectFileName_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 ButtonCreate_Click(object sender, EventArgs e) + { + try + { + if (string.IsNullOrWhiteSpace(_fileName)) + { + throw new Exception("Отсутствует имя файла для отчета"); + } + if + (_container.Resolve().CreateChart(_fileName, dateTimePickerReport.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/ProjectGarage/Forms/FormTransportationDistributionReport.resx b/ProjectGarage/Forms/FormTransportationDistributionReport.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/ProjectGarage/Forms/FormTransportationDistributionReport.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/ProjectGarage/ProjectGarage.csproj b/ProjectGarage/ProjectGarage.csproj index c4cc11c..f9fed85 100644 --- a/ProjectGarage/ProjectGarage.csproj +++ b/ProjectGarage/ProjectGarage.csproj @@ -10,11 +10,13 @@ + + diff --git a/ProjectGarage/Reports/ChartReport.cs b/ProjectGarage/Reports/ChartReport.cs new file mode 100644 index 0000000..f9fd92e --- /dev/null +++ b/ProjectGarage/Reports/ChartReport.cs @@ -0,0 +1,51 @@ +using Microsoft.Extensions.Logging; +using ProjectGarage.Repositories; +using ProjectGarage.Repositories.Implementations; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectGarage.Reports; + +public class ChartReport +{ + private readonly ITransportationRepository _transportationRepository; + private readonly ILogger _logger; + public ChartReport(ITransportationRepository transportationRepository, ILogger logger) + { + _transportationRepository = transportationRepository ?? + throw new ArgumentNullException(nameof(transportationRepository)); + _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 _transportationRepository + .ReadTransportation() + .Where(x => x.TransportationDate.Date == dateTime.Date) + .GroupBy(x => x.FuelId, (key, group) => new { + Id = key, + Amount = group.Sum(x => x.Amount) + }) + .Select(x => (x.Id.ToString(), (double)x.Amount)) + .ToList(); + } + +} diff --git a/ProjectGarage/Reports/DocReport.cs b/ProjectGarage/Reports/DocReport.cs new file mode 100644 index 0000000..254d510 --- /dev/null +++ b/ProjectGarage/Reports/DocReport.cs @@ -0,0 +1,114 @@ +using Microsoft.Extensions.Logging; +using ProjectGarage.Repositories; +using ProjectGarage.Repositories.Implementations; +using Serilog.Core; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectGarage.Reports; + +public class DocReport +{ + private readonly IFuelRepository _fuelRepository; + private readonly IDriverRepository _driverRepository; + private readonly IRouteRepository _routeRepository; + private readonly ITruckRepository _truckRepository; + + private readonly ILogger _logger; + + + public DocReport(IFuelRepository fuelRepository, IDriverRepository driverRepository, + IRouteRepository routeRepository,ITruckRepository truckRepository,IConnectionString connectionstring, + ILogger logger) + { + _fuelRepository = fuelRepository ?? throw new ArgumentNullException(nameof(fuelRepository)); + _driverRepository = driverRepository ?? throw new ArgumentNullException(nameof(driverRepository)); + _routeRepository = routeRepository ?? throw new ArgumentNullException(nameof(routeRepository)); + _truckRepository = truckRepository ?? throw new ArgumentNullException(nameof(truckRepository)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + public bool CreateDoc(string filePath, bool includeFuels, bool includeDrivers, + bool includeRoutes, bool includeTrucks) + { + try + { + var builder = new WordBuilder(filePath) + .AddHeader("Документ со справочниками"); + if (includeTrucks) + { + builder.AddParagraph("Фуры") + .AddTable([2400, 2400, 2400], + GetTrucks()); + } + if (includeFuels) + { + builder.AddParagraph("Топлива") + .AddTable([2400, 1200, 1200], + GetFuels()); + } + if (includeDrivers) + { + builder.AddParagraph("Водители") + .AddTable([2400, 2400, 2400], + GetDrivers()); + } + if (includeRoutes) + { + builder.AddParagraph("Маршруты") + .AddTable([2400, 2400, 2400], + GetRoutes()); + } + builder.Build(); + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при формировании документа"); + return false; + } + } + + private List GetTrucks() + { + return [ + ["Тип топлива", "Название топлива", "Цена"], + .. _fuelRepository + .ReadFuels() + .Select(x => new string[] { x.FuelType.ToString(), x.FuelName, x.Price.ToString() }), + ]; + } + + private List GetFuels() + { + return [ + ["Тип топлива", "Название топлива", "Цена"], + .. _fuelRepository + .ReadFuels() + .Select(x => new string[] { x.FuelType.ToString(), x.FuelName, x.Price.ToString() }), + ]; + } + + private List GetDrivers() + { + return [ + ["Имя", "Фамилия", "Номера машины"], + .. _driverRepository + .ReadDrivers() + .Select(x => new string[] { x.Fname, x.Lname, x.TruckId.ToString() }), + ]; + } + + private List GetRoutes() + { + return [ + ["Начальная т.", "Конечная т.", "Протяженность"], + .. _routeRepository + .ReadRoute() + .Select(x => new string[] { x.StartP, x.FinalP, x.Length.ToString() }), + ]; + } +} diff --git a/ProjectGarage/Reports/ExcelBuilder.cs b/ProjectGarage/Reports/ExcelBuilder.cs new file mode 100644 index 0000000..c6afc71 --- /dev/null +++ b/ProjectGarage/Reports/ExcelBuilder.cs @@ -0,0 +1,321 @@ +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 ProjectGarage.Reports; + +public class ExcelBuilder +{ + private readonly string _filePath; + private readonly SheetData _sheetData; + private readonly MergeCells _mergeCells; + private readonly Columns _columns; + private uint _rowIndex = 0; + public ExcelBuilder(string filePath) + { + if (string.IsNullOrWhiteSpace(filePath)) + { + throw new ArgumentNullException(nameof(filePath)); + } + if (File.Exists(filePath)) + { + File.Delete(filePath); + } + _filePath = filePath; + _sheetData = new SheetData(); + _mergeCells = new MergeCells(); + _columns = new Columns(); + _rowIndex = 1; + } + public ExcelBuilder AddHeader(string header, int startIndex, int count) + { + CreateCell(startIndex, _rowIndex, header, + StyleIndex.SimpleTextWithoutBorder); + 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.SimpleTextWithoutBorder); + } + _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.SimpleTextWithoutBorder); + } + _rowIndex++; + } + for (var j = 0; j < data.Last().Length; ++j) + { + CreateCell(j, _rowIndex, data.Last()[j], + StyleIndex.SimpleTextWithoutBorder); + } + _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() + }); + // TODO добавить настройку с границами + 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 + } + }); + // TODO дополнить форматы + cellFormats.Append(new CellFormat + { + NumberFormatId = 0, + FormatId = 0, + FontId = 1, + BorderId = 0, + FillId = 0, + Alignment = new Alignment() + { + Horizontal = HorizontalAlignmentValues.Left, + Vertical = VerticalAlignmentValues.Center, + WrapText = true + } + }); + cellFormats.Append(new CellFormat + { + NumberFormatId = 0, + FormatId = 0, + FontId = 0, + BorderId = 1, + FillId = 0, + Alignment = new Alignment() + { + Horizontal = HorizontalAlignmentValues.Left, + Vertical = VerticalAlignmentValues.Center, + WrapText = true + } + }); + cellFormats.Append(new CellFormat + { + NumberFormatId = 0, + FormatId = 0, + FontId = 1, + BorderId = 1, + FillId = 0, + Alignment = new Alignment() + { + Horizontal = HorizontalAlignmentValues.Left, + Vertical = VerticalAlignmentValues.Center, + WrapText = true + } + }); + workbookStylesPart.Stylesheet.Append(cellFormats); + } + private enum StyleIndex + { + SimpleTextWithoutBorder = 0, + // TODO дополнить стили + BoldTextWithoutBorder = 1, + SimpleTextWithBorder = 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/ProjectGarage/Reports/PdfBuilder.cs b/ProjectGarage/Reports/PdfBuilder.cs new file mode 100644 index 0000000..85f677b --- /dev/null +++ b/ProjectGarage/Reports/PdfBuilder.cs @@ -0,0 +1,91 @@ +using MigraDoc.DocumentObjectModel; +using MigraDoc.DocumentObjectModel.Shapes.Charts; +using MigraDoc.Rendering; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectGarage.Reports; + +public 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/ProjectGarage/Reports/TableReport.cs b/ProjectGarage/Reports/TableReport.cs new file mode 100644 index 0000000..777acfd --- /dev/null +++ b/ProjectGarage/Reports/TableReport.cs @@ -0,0 +1,83 @@ +using Microsoft.Extensions.Logging; +using ProjectGarage.Repositories; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectGarage.Reports; + +public class TableReport +{ + private readonly IReplenishmentRepository _replenishmentRepository; + private readonly ITransportationRepository _transportationRepository; + private readonly ILogger _logger; + internal static readonly string[] item = ["Водитель", "Дата", " пришло", "Количество ушло"]; + public TableReport(IReplenishmentRepository replenishmentRepository, + ITransportationRepository transportationRepository, ILogger logger) + { + _replenishmentRepository = replenishmentRepository ?? + throw new ArgumentNullException(nameof(replenishmentRepository)); + _transportationRepository = transportationRepository ?? + throw new ArgumentNullException(nameof(transportationRepository)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + public bool CreateTable(string filePath, int fuelId, DateTime startDate, DateTime endDate) + { + try + { + new ExcelBuilder(filePath) + .AddHeader("Сводка по движению топлива", 0, 4) + .AddParagraph("за период", 0) + .AddTable([10, 10, 15, 15], GetData(fuelId, startDate, + endDate)) + .Build(); + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при формировании документа"); + return false; + } + } + + private List GetData(int fuelId, DateTime startDate, DateTime + endDate) + { + var data = _replenishmentRepository + .ReadFuelReplenishment() + .Where(x => x.ReplenishmentDate >= startDate && x.ReplenishmentDate <= endDate && + x.FuelFuelReplenishments.Any(y => y.FuelId == fuelId)) + .Select(x => new { + x.DriverId, + Date = x.ReplenishmentDate, + CountIn = x.FuelFuelReplenishments. + FirstOrDefault(y => y.FuelId == fuelId)?.Amount, + CountOut = (int?)null + }) + .Union( + _transportationRepository + .ReadTransportation() + .Where(x => x.TransportationDate >= startDate && + x.TransportationDate <= endDate && x.FuelId == fuelId) + .Select(x => new { + x.DriverId, + Date = x.TransportationDate, + CountIn = (int?)null, + CountOut = (int?)x.Amount + })) + .OrderBy(x => x.Date); + return + new List() { item } + .Union( + data + .Select(x => new string[] { + x.DriverId.ToString(), x.Date.ToString(), x.CountIn?.ToString() ?? + string.Empty, x.CountOut?.ToString() ?? string.Empty})) + .Union( + [["Всего", "", data.Sum(x => x.CountIn ?? 0).ToString(), + data.Sum(x => x.CountOut ?? 0).ToString()]]) + .ToList(); + } +} diff --git a/ProjectGarage/Reports/WordBuilder.cs b/ProjectGarage/Reports/WordBuilder.cs new file mode 100644 index 0000000..b119c68 --- /dev/null +++ b/ProjectGarage/Reports/WordBuilder.cs @@ -0,0 +1,135 @@ +using DocumentFormat.OpenXml; +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Wordprocessing; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectGarage.Reports; + +public 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/ProjectGarage/Repositories/Implementations/ReplenishmentRepository.cs b/ProjectGarage/Repositories/Implementations/ReplenishmentRepository.cs index 6bd66ab..03a1752 100644 --- a/ProjectGarage/Repositories/Implementations/ReplenishmentRepository.cs +++ b/ProjectGarage/Repositories/Implementations/ReplenishmentRepository.cs @@ -86,11 +86,15 @@ public IEnumerable ReadFuelReplenishment(DateTime? dateForm = { using var connection = new NpgsqlConnection(_connectionString.ConnectionString); - var querySelect = @"SELECT * FROM fuelreplenishment"; - var replenishments = connection.Query(querySelect); + var querySelect = @"SELECT fr.*, ffr.FuelId, ffr.Amount +FROM fuelreplenishment fr +INNER JOIN fuel_fuelReplenishment ffr ON ffr.ReplenishmentId = fr.Id"; + var replenishments = connection.Query(querySelect); _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(replenishments)); - return replenishments; + return replenishments.GroupBy(x => x.Id, y => y, + (key, value) => FuelReplenishment.CreateOpeartion(value.First(), + value.Select(z => FuelFuelReplenishment.CreateElement(0, z.FuelId, z.Amount)))).ToList(); } catch (Exception ex) { diff --git a/Отчеты_лаб3/all.docx b/Отчеты_лаб3/all.docx new file mode 100644 index 0000000..fd56112 Binary files /dev/null and b/Отчеты_лаб3/all.docx differ diff --git a/Отчеты_лаб3/fs.pdf b/Отчеты_лаб3/fs.pdf new file mode 100644 index 0000000..a679224 Binary files /dev/null and b/Отчеты_лаб3/fs.pdf differ diff --git a/Отчеты_лаб3/дтл.xlsx b/Отчеты_лаб3/дтл.xlsx new file mode 100644 index 0000000..653f695 Binary files /dev/null and b/Отчеты_лаб3/дтл.xlsx differ