вроде done

This commit is contained in:
Baryshev Dmitry 2024-12-18 01:56:55 +04:00
parent 2ef7829897
commit 2803143064
26 changed files with 1876 additions and 9 deletions

View File

@ -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;

View File

@ -23,4 +23,15 @@ public class FuelReplenishment
FuelFuelReplenishments = fuelFuelReplenishments
};
}
public static FuelReplenishment CreateOpeartion(TempFuelReplenishment tempFuelReplenishment, IEnumerable<FuelFuelReplenishment> fuelFuelReplenishments)
{
return new FuelReplenishment
{
Id = tempFuelReplenishment.Id,
DriverId = tempFuelReplenishment.DriverId,
ReplenishmentDate = tempFuelReplenishment.ReplenishmentDate,
FuelFuelReplenishments = fuelFuelReplenishments
};
}
}

View File

@ -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; }
}

View File

@ -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;
}
}

View File

@ -91,5 +91,44 @@ namespace ProjectGarage
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void DirectoryReportToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormDirectorReport>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void FuelReportToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormFuelReport>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void DistributionReportToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormTransportationDistributionReport>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

View File

@ -0,0 +1,112 @@
namespace ProjectGarage.Forms
{
partial class FormDirectorReport
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
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;
}
}

View File

@ -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<DocReport>().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);
}
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,162 @@
namespace ProjectGarage.Forms
{
partial class FormFuelReport
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
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;
}
}

View File

@ -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<TableReport>().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;
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -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();
}
}
}

View File

@ -0,0 +1,107 @@
namespace ProjectGarage.Forms
{
partial class FormTransportationDistributionReport
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
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;
}
}

View File

@ -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<ChartReport>().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);
}
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -10,11 +10,13 @@
<ItemGroup>
<PackageReference Include="Dapper" Version="2.1.35" />
<PackageReference Include="DocumentFormat.OpenXml" Version="3.2.0" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Npgsql" Version="9.0.1" />
<PackageReference Include="PdfSharp.MigraDoc.Standard" Version="1.51.15" />
<PackageReference Include="Serilog" Version="4.0.2" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.4" />

View File

@ -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<ChartReport> _logger;
public ChartReport(ITransportationRepository transportationRepository, ILogger<ChartReport> 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();
}
}

View File

@ -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<DocReport> _logger;
public DocReport(IFuelRepository fuelRepository, IDriverRepository driverRepository,
IRouteRepository routeRepository,ITruckRepository truckRepository,IConnectionString connectionstring,
ILogger<DocReport> 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<string[]> GetTrucks()
{
return [
["Тип топлива", "Название топлива", "Цена"],
.. _fuelRepository
.ReadFuels()
.Select(x => new string[] { x.FuelType.ToString(), x.FuelName, x.Price.ToString() }),
];
}
private List<string[]> GetFuels()
{
return [
["Тип топлива", "Название топлива", "Цена"],
.. _fuelRepository
.ReadFuels()
.Select(x => new string[] { x.FuelType.ToString(), x.FuelName, x.Price.ToString() }),
];
}
private List<string[]> GetDrivers()
{
return [
["Имя", "Фамилия", "Номера машины"],
.. _driverRepository
.ReadDrivers()
.Select(x => new string[] { x.Fname, x.Lname, x.TruckId.ToString() }),
];
}
private List<string[]> GetRoutes()
{
return [
["Начальная т.", "Конечная т.", "Протяженность"],
.. _routeRepository
.ReadRoute()
.Select(x => new string[] { x.StartP, x.FinalP, x.Length.ToString() }),
];
}
}

View File

@ -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<string[]> 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>();
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<SheetData>().First());
}
}
private static void GenerateStyle(WorkbookPart workbookPart)
{
var workbookStylesPart =
workbookPart.AddNewPart<WorkbookStylesPart>();
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>(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>(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>(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<Row>().FirstOrDefault(r => r.RowIndex!
== rowIndex);
if (row == null)
{
row = new Row() { RowIndex = rowIndex };
_sheetData.Append(row);
}
var newCell = row.Elements<Cell>()
.FirstOrDefault(c => c.CellReference != null &&
c.CellReference.Value == columnName + rowIndex);
if (newCell == null)
{
Cell? refCell = null;
foreach (Cell cell in row.Elements<Cell>())
{
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;
}
}

View File

@ -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;
}
}

View File

@ -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<TableReport> _logger;
internal static readonly string[] item = ["Водитель", "Дата", " пришло", "Количество ушло"];
public TableReport(IReplenishmentRepository replenishmentRepository,
ITransportationRepository transportationRepository, ILogger<TableReport> 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<string[]> 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<string[]>() { 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();
}
}

View File

@ -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<string[]> 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>(BorderValues.Single),
Size = 12
},
new BottomBorder()
{
Val = new
EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new LeftBorder()
{
Val = new
EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new RightBorder()
{
Val = new
EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new InsideHorizontalBorder()
{
Val = new
EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new InsideVerticalBorder()
{
Val = new
EnumValue<BorderValues>(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;
}
}

View File

@ -86,11 +86,15 @@ public IEnumerable<FuelReplenishment> ReadFuelReplenishment(DateTime? dateForm =
{
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT * FROM fuelreplenishment";
var replenishments = connection.Query<FuelReplenishment>(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<TempFuelReplenishment>(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)
{

Binary file not shown.

BIN
Отчеты_лаб3/fs.pdf Normal file

Binary file not shown.

Binary file not shown.