лаба 3 готова

This commit is contained in:
sheymuh 2024-12-17 21:20:21 +04:00
parent ff6b73068f
commit 240ea12b6b
17 changed files with 617 additions and 68 deletions

5
.gitignore vendored
View File

@ -402,3 +402,8 @@ FodyWeavers.xsd
/edit.png
/minus.jpg
/plus.jpg
/docAll1.docx
/docBus1.docx
/docBuses1.docx
/excel1.xlsx
/pdf1.pdf

View File

@ -39,6 +39,7 @@
отчётыToolStripMenuItem = new ToolStripMenuItem();
directoryReportToolStripMenuItem = new ToolStripMenuItem();
busesReportToolStripMenuItem = new ToolStripMenuItem();
serviceReportToolStripMenuItem = new ToolStripMenuItem();
menuStrip1.SuspendLayout();
SuspendLayout();
//
@ -90,20 +91,20 @@
// StartingShiftsToolStripMenuItem
//
StartingShiftsToolStripMenuItem.Name = "StartingShiftsToolStripMenuItem";
StartingShiftsToolStripMenuItem.Size = new Size(315, 40);
StartingShiftsToolStripMenuItem.Size = new Size(314, 40);
StartingShiftsToolStripMenuItem.Text = "Начало смены";
StartingShiftsToolStripMenuItem.Click += StartingShiftsToolStripMenuItem_Click;
//
// GoToServicesToolStripMenuItem
//
GoToServicesToolStripMenuItem.Name = "GoToServicesToolStripMenuItem";
GoToServicesToolStripMenuItem.Size = new Size(315, 40);
GoToServicesToolStripMenuItem.Size = new Size(314, 40);
GoToServicesToolStripMenuItem.Text = "Тех. обслуживание";
GoToServicesToolStripMenuItem.Click += GoToServicesToolStripMenuItem_Click;
//
// отчётыToolStripMenuItem
//
отчётыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { directoryReportToolStripMenuItem, busesReportToolStripMenuItem });
отчётыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { directoryReportToolStripMenuItem, busesReportToolStripMenuItem, serviceReportToolStripMenuItem });
отчётыToolStripMenuItem.Name = "отчётыToolStripMenuItem";
отчётыToolStripMenuItem.Size = new Size(103, 34);
отчётыToolStripMenuItem.Text = "Отчёты";
@ -124,6 +125,14 @@
busesReportToolStripMenuItem.Text = "Работа автобусов";
busesReportToolStripMenuItem.Click += BusesReportToolStripMenuItem_Click;
//
// serviceReportToolStripMenuItem
//
serviceReportToolStripMenuItem.Name = "serviceReportToolStripMenuItem";
serviceReportToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.P;
serviceReportToolStripMenuItem.Size = new Size(490, 40);
serviceReportToolStripMenuItem.Text = "Сломанные элементы";
serviceReportToolStripMenuItem.Click += ServiceReportToolStripMenuItem_Click;
//
// FormPassengerTransportation
//
AutoScaleDimensions = new SizeF(12F, 30F);
@ -155,5 +164,6 @@
private ToolStripMenuItem GoToServicesToolStripMenuItem;
private ToolStripMenuItem directoryReportToolStripMenuItem;
private ToolStripMenuItem busesReportToolStripMenuItem;
private ToolStripMenuItem serviceReportToolStripMenuItem;
}
}

View File

@ -89,7 +89,19 @@ namespace ProjectPassengerTransportation
{
try
{
_container.Resolve<FormBusesReport>().ShowDialog();
_container.Resolve<FormWorkReport>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ServiceReportToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormServiceReport>().ShowDialog();
}
catch (Exception ex)
{

View File

@ -126,7 +126,7 @@
Controls.Add(comboBoxPost);
Name = "FormEmployee";
StartPosition = FormStartPosition.CenterParent;
Text = "FormEmployee";
Text = "Сотрудник";
ResumeLayout(false);
PerformLayout();
}

View File

@ -0,0 +1,107 @@
namespace ProjectPassengerTransportation.Forms
{
partial class FormServiceReport
{
/// <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()
{
buttonSelectFile = new Button();
labelFileName = new Label();
dateTimePicker = new DateTimePicker();
labelDate = new Label();
buttonMakeReport = new Button();
SuspendLayout();
//
// buttonSelectFile
//
buttonSelectFile.Location = new Point(36, 36);
buttonSelectFile.Name = "buttonSelectFile";
buttonSelectFile.Size = new Size(131, 40);
buttonSelectFile.TabIndex = 0;
buttonSelectFile.Text = "Выбрать";
buttonSelectFile.UseVisualStyleBackColor = true;
buttonSelectFile.Click += ButtonSelectFile_Click;
//
// labelFileName
//
labelFileName.AutoSize = true;
labelFileName.Location = new Point(195, 41);
labelFileName.Name = "labelFileName";
labelFileName.Size = new Size(62, 30);
labelFileName.TabIndex = 1;
labelFileName.Text = "Файл";
//
// dateTimePicker
//
dateTimePicker.Location = new Point(144, 127);
dateTimePicker.Name = "dateTimePicker";
dateTimePicker.Size = new Size(311, 35);
dateTimePicker.TabIndex = 2;
//
// labelDate
//
labelDate.AutoSize = true;
labelDate.Location = new Point(49, 131);
labelDate.Name = "labelDate";
labelDate.Size = new Size(64, 30);
labelDate.TabIndex = 3;
labelDate.Text = "Дата:";
//
// buttonMakeReport
//
buttonMakeReport.Location = new Point(168, 205);
buttonMakeReport.Name = "buttonMakeReport";
buttonMakeReport.Size = new Size(178, 46);
buttonMakeReport.TabIndex = 4;
buttonMakeReport.Text = "Сформировать";
buttonMakeReport.UseVisualStyleBackColor = true;
buttonMakeReport.Click += ButtonMakeReport_Click;
//
// FormServiceReport
//
AutoScaleDimensions = new SizeF(12F, 30F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(511, 276);
Controls.Add(buttonMakeReport);
Controls.Add(labelDate);
Controls.Add(dateTimePicker);
Controls.Add(labelFileName);
Controls.Add(buttonSelectFile);
Name = "FormServiceReport";
Text = "Отчет по тех обслуживанию";
ResumeLayout(false);
PerformLayout();
}
#endregion
private Button buttonSelectFile;
private Label labelFileName;
private DateTimePicker dateTimePicker;
private Label labelDate;
private Button buttonMakeReport;
}
}

View File

@ -0,0 +1,60 @@
using ProjectPassengerTransportation.Reports;
using Unity;
namespace ProjectPassengerTransportation.Forms
{
public partial class FormServiceReport : Form
{
private string _fileName = string.Empty;
private readonly IUnityContainer _container;
public FormServiceReport(IUnityContainer container)
{
InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container));
}
private void ButtonSelectFile_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 ButtonMakeReport_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(_fileName))
{
throw new Exception("Отсутствует имя файла отчета");
}
if
(_container.Resolve<ChartReport>().CreateChart(_fileName, dateTimePicker.Value))
{
MessageBox.Show("Документ сформирован", "Формирование документа",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Возникли ошибки при формировании документа.Подробности в логах",
"Формирование документа", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при создании очета",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

View File

@ -1,6 +1,6 @@
namespace ProjectPassengerTransportation.Forms
{
partial class FormBusesReport
partial class FormWorkReport
{
/// <summary>
/// Required designer variable.
@ -31,13 +31,15 @@
labelFilePath = new Label();
textBoxFilePath = new TextBox();
buttonSelectFilePath = new Button();
comboBoxShift = new ComboBox();
dateTimePickerBeginDate = new DateTimePicker();
dateTimePickerEndDate = new DateTimePicker();
labelShift = new Label();
labelEmployee = new Label();
labelBeginDate = new Label();
labelEndDate = new Label();
buttonMakeReport = new Button();
comboBoxEmployee = new ComboBox();
comboBoxBus = new ComboBox();
labelBus = new Label();
SuspendLayout();
//
// labelFilePath
@ -54,12 +56,12 @@
textBoxFilePath.Location = new Point(203, 37);
textBoxFilePath.Name = "textBoxFilePath";
textBoxFilePath.ReadOnly = true;
textBoxFilePath.Size = new Size(284, 35);
textBoxFilePath.Size = new Size(361, 35);
textBoxFilePath.TabIndex = 1;
//
// buttonSelectFilePath
//
buttonSelectFilePath.Location = new Point(493, 35);
buttonSelectFilePath.Location = new Point(570, 32);
buttonSelectFilePath.Name = "buttonSelectFilePath";
buttonSelectFilePath.Size = new Size(40, 40);
buttonSelectFilePath.TabIndex = 2;
@ -67,41 +69,33 @@
buttonSelectFilePath.UseVisualStyleBackColor = true;
buttonSelectFilePath.Click += ButtonSelectFilePath_Click;
//
// comboBoxShift
//
comboBoxShift.FormattingEnabled = true;
comboBoxShift.Location = new Point(203, 114);
comboBoxShift.Name = "comboBoxShift";
comboBoxShift.Size = new Size(330, 38);
comboBoxShift.TabIndex = 3;
//
// dateTimePickerBeginDate
//
dateTimePickerBeginDate.Location = new Point(203, 190);
dateTimePickerBeginDate.Location = new Point(203, 271);
dateTimePickerBeginDate.Name = "dateTimePickerBeginDate";
dateTimePickerBeginDate.Size = new Size(330, 35);
dateTimePickerBeginDate.Size = new Size(407, 35);
dateTimePickerBeginDate.TabIndex = 4;
//
// dateTimePickerEndDate
//
dateTimePickerEndDate.Location = new Point(203, 262);
dateTimePickerEndDate.Location = new Point(203, 343);
dateTimePickerEndDate.Name = "dateTimePickerEndDate";
dateTimePickerEndDate.Size = new Size(330, 35);
dateTimePickerEndDate.Size = new Size(407, 35);
dateTimePickerEndDate.TabIndex = 5;
//
// labelShift
// labelEmployee
//
labelShift.AutoSize = true;
labelShift.Location = new Point(23, 117);
labelShift.Name = "labelShift";
labelShift.Size = new Size(75, 30);
labelShift.TabIndex = 6;
labelShift.Text = "Смена";
labelEmployee.AutoSize = true;
labelEmployee.Location = new Point(23, 117);
labelEmployee.Name = "labelEmployee";
labelEmployee.Size = new Size(103, 30);
labelEmployee.TabIndex = 6;
labelEmployee.Text = "Работник";
//
// labelBeginDate
//
labelBeginDate.AutoSize = true;
labelBeginDate.Location = new Point(23, 194);
labelBeginDate.Location = new Point(23, 275);
labelBeginDate.Name = "labelBeginDate";
labelBeginDate.Size = new Size(133, 30);
labelBeginDate.TabIndex = 7;
@ -110,7 +104,7 @@
// labelEndDate
//
labelEndDate.AutoSize = true;
labelEndDate.Location = new Point(23, 266);
labelEndDate.Location = new Point(23, 347);
labelEndDate.Name = "labelEndDate";
labelEndDate.Size = new Size(123, 30);
labelEndDate.TabIndex = 8;
@ -118,7 +112,7 @@
//
// buttonMakeReport
//
buttonMakeReport.Location = new Point(203, 329);
buttonMakeReport.Location = new Point(203, 410);
buttonMakeReport.Name = "buttonMakeReport";
buttonMakeReport.Size = new Size(177, 40);
buttonMakeReport.TabIndex = 9;
@ -126,23 +120,50 @@
buttonMakeReport.UseVisualStyleBackColor = true;
buttonMakeReport.Click += ButtonMakeReport_Click;
//
// FormBusesReport
// comboBoxEmployee
//
comboBoxEmployee.FormattingEnabled = true;
comboBoxEmployee.Location = new Point(203, 114);
comboBoxEmployee.Name = "comboBoxEmployee";
comboBoxEmployee.Size = new Size(407, 38);
comboBoxEmployee.TabIndex = 10;
//
// comboBoxBus
//
comboBoxBus.FormattingEnabled = true;
comboBoxBus.Location = new Point(203, 191);
comboBoxBus.Name = "comboBoxBus";
comboBoxBus.Size = new Size(407, 38);
comboBoxBus.TabIndex = 12;
//
// labelBus
//
labelBus.AutoSize = true;
labelBus.Location = new Point(23, 194);
labelBus.Name = "labelBus";
labelBus.Size = new Size(91, 30);
labelBus.TabIndex = 11;
labelBus.Text = "Автобус";
//
// FormWorkReport
//
AutoScaleDimensions = new SizeF(12F, 30F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(576, 393);
ClientSize = new Size(646, 466);
Controls.Add(comboBoxBus);
Controls.Add(labelBus);
Controls.Add(comboBoxEmployee);
Controls.Add(buttonMakeReport);
Controls.Add(labelEndDate);
Controls.Add(labelBeginDate);
Controls.Add(labelShift);
Controls.Add(labelEmployee);
Controls.Add(dateTimePickerEndDate);
Controls.Add(dateTimePickerBeginDate);
Controls.Add(comboBoxShift);
Controls.Add(buttonSelectFilePath);
Controls.Add(textBoxFilePath);
Controls.Add(labelFilePath);
Name = "FormBusesReport";
Text = "Отчёт по работе автобусов";
Name = "FormWorkReport";
Text = "Отчёт по работе сотрудников и автобусов";
ResumeLayout(false);
PerformLayout();
}
@ -152,12 +173,14 @@
private Label labelFilePath;
private TextBox textBoxFilePath;
private Button buttonSelectFilePath;
private ComboBox comboBoxShift;
private DateTimePicker dateTimePickerBeginDate;
private DateTimePicker dateTimePickerEndDate;
private Label labelShift;
private Label labelEmployee;
private Label labelBeginDate;
private Label labelEndDate;
private Button buttonMakeReport;
private ComboBox comboBoxEmployee;
private ComboBox comboBoxBus;
private Label labelBus;
}
}

View File

@ -4,17 +4,21 @@ using Unity;
namespace ProjectPassengerTransportation.Forms
{
public partial class FormBusesReport : Form
public partial class FormWorkReport : Form
{
private readonly IUnityContainer _container;
public FormBusesReport(IUnityContainer container, IStartingShiftRepository startingShiftRepository)
public FormWorkReport(IUnityContainer container, IEmployeeRepository employeeRepository,
IBusRepository busRepository)
{
InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container));
comboBoxShift.DataSource = startingShiftRepository.ReadShifts();
comboBoxShift.DisplayMember = "Id";
comboBoxShift.ValueMember = "Id";
comboBoxEmployee.DataSource = employeeRepository.ReadEmployees();
comboBoxEmployee.DisplayMember = "First_name";
comboBoxEmployee.ValueMember = "Id";
comboBoxBus.DataSource = busRepository.ReadBuses();
comboBoxBus.DisplayMember = "Licence_plate";
comboBoxBus.ValueMember = "Id";
}
private void ButtonSelectFilePath_Click(object sender, EventArgs e)
@ -38,16 +42,17 @@ namespace ProjectPassengerTransportation.Forms
{
throw new Exception("Отсутствует имя файла для отчета");
}
if (comboBoxShift.SelectedIndex < 0)
if (comboBoxEmployee.SelectedIndex < 0 || comboBoxBus.SelectedIndex < 0)
{
throw new Exception("Не выбран корм");
throw new Exception("Не выбран сотрудник или автобус");
}
if (dateTimePickerEndDate.Value <= dateTimePickerBeginDate.Value)
{
throw new Exception("Дата начала должна быть раньше даты окончания");
}
if (_container.Resolve<TableReport>().CreateTable(textBoxFilePath.Text,
(int)comboBoxShift.SelectedValue!, dateTimePickerBeginDate.Value, dateTimePickerEndDate.Value))
(int)comboBoxEmployee.SelectedValue!, (int)comboBoxBus.SelectedValue!,
dateTimePickerBeginDate.Value, dateTimePickerEndDate.Value))
{
MessageBox.Show("Документ сформирован", "Формирование документа",
MessageBoxButtons.OK, MessageBoxIcon.Information);

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

@ -16,6 +16,7 @@
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Npgsql" Version="9.0.2" />
<PackageReference Include="PdfSharp.MigraDoc.Standard" Version="1.51.15" />
<PackageReference Include="Serilog" Version="4.2.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="9.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="9.0.0" />

View File

@ -0,0 +1,48 @@
using Microsoft.Extensions.Logging;
using ProjectPassengerTransportation.Repositories;
namespace ProjectPassengerTransportation.Reports;
public class ChartReport
{
private readonly IGoToServiceRepository _goToServiceRepository;
private readonly ILogger<ChartReport> _logger;
public ChartReport(IGoToServiceRepository goToServiceRepository, ILogger<ChartReport> logger)
{
_goToServiceRepository = goToServiceRepository ?? throw new ArgumentNullException(nameof(goToServiceRepository));
_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 _goToServiceRepository
.ReadServices()
.Where(x => x.Date.Date == dateTime.Date)
.GroupBy(x => x.Bus_id, (key, group) => new {
Id = key,
Elements = group.Sum(x => (double)x.Broken_elements)
})
.Select(x => (x.Id.ToString(), (double)x.Elements))
.ToList();
}
}

View File

@ -153,7 +153,17 @@ public class ExcelBuilder
FontFamilyNumbering = new FontFamilyNumbering() { Val = 2 },
FontScheme = new FontScheme() { Val = new EnumValue<FontSchemeValues>(FontSchemeValues.Minor) }
});
// TODO добавить шрифт с жирным
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
@ -177,7 +187,14 @@ public class ExcelBuilder
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
@ -196,14 +213,57 @@ public class ExcelBuilder
WrapText = true
}
});
// TODO дополнить форматы
cellFormats.Append(new CellFormat
{
NumberFormatId = 0,
FormatId = 0,
FontId = 0,
BorderId = 1,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Right,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
cellFormats.Append(new CellFormat
{
NumberFormatId = 0,
FormatId = 0,
FontId = 1,
BorderId = 0,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Center,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
cellFormats.Append(new CellFormat
{
NumberFormatId = 0,
FormatId = 0,
FontId = 1,
BorderId = 1,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Center,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
workbookStylesPart.Stylesheet.Append(cellFormats);
}
private enum StyleIndex
{
SimpleTextWithoutBorder = 0,
// TODO дополнить стили
SimpleTextWithBorder = 1,
BoldTextWithoutBorder = 2,
BoldTextWithBorder = 3
}
private void CreateCell(int columnIndex, uint rowIndex, string text, StyleIndex styleIndex)

View File

@ -0,0 +1,92 @@
using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Shapes.Charts;
using MigraDoc.Rendering;
using System.Text;
namespace ProjectPassengerTransportation.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

@ -1,5 +1,6 @@
using Microsoft.Extensions.Logging;
using ProjectPassengerTransportation.Repositories;
using System.Linq;
namespace ProjectPassengerTransportation.Reports;
@ -11,7 +12,7 @@ public class TableReport
private readonly ILogger<TableReport> _logger;
internal static readonly string[] item = ["Автобус", "Дата", "Отработано часов", "Потрачено на тех обслуживание"];
internal static readonly string[] item = ["Работник", "Автобус", "Дата", "Отработано часов", "Потрачено на тех обслуживание"];
public TableReport(IStartingShiftRepository startingShiftRepository,
IGoToServiceRepository goToServiceRepository, ILogger<TableReport> logger)
@ -21,14 +22,14 @@ public class TableReport
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public bool CreateTable(string filePath, int startingShiftId, DateTime startDate, DateTime endDate)
public bool CreateTable(string filePath, int employeeId, int busId, DateTime startDate, DateTime endDate)
{
try
{
new ExcelBuilder(filePath)
.AddHeader("Сводка по работе автобусов", 0, 4)
new ExcelBuilder(filePath)
.AddHeader("Сводка по работникам и автобусам", 0, 5)
.AddParagraph("за период", 0)
.AddTable([10, 10, 15, 15], GetData(startingShiftId, startDate, endDate))
.AddTable([10, 10, 10, 15, 15], GetData(employeeId, busId, startDate, endDate))
.Build();
return true;
}
@ -39,23 +40,24 @@ public class TableReport
}
}
private List<string[]> GetData(int startingShiftId, DateTime startDate, DateTime endDate)
private List<string[]> GetData(int employeeId, int busId, DateTime startDate, DateTime endDate)
{
int busId = 0;
var data = _startingShiftRepository
.ReadShifts()
.Where(x => x.Date >= startDate && x.Date <= endDate && x.Starting_shift_employees.Any(y => y.Starting_shift_id == startingShiftId))
.Where(x => x.Date >= startDate && x.Date <= endDate && x.Starting_shift_employees.Any(y => y.Employee_id == employeeId))
.Select(x => new {
busId = x.Bus_id,
EmployeeId = (int?)employeeId,
BusId = (int?)null,
x.Date,
WorkHours = x.Starting_shift_employees.FirstOrDefault(y => y.Starting_shift_id == startingShiftId)?.Work_time,
WorkHours = x.Starting_shift_employees.FirstOrDefault(y => y.Employee_id == employeeId)?.Work_time,
Price = (int?)null
})
.Union(_goToServiceRepository
.ReadServices()
.Where(x => x.Date >= startDate && x.Date <= endDate && x.Bus_id == busId)
.Select(x => new {
busId = x.Bus_id,
EmployeeId = (int?)null,
BusId = (int?)busId,
x.Date,
WorkHours = (int?)null,
Price = (int?)x.Price
@ -64,11 +66,12 @@ public class TableReport
return new List<string[]>() { item }
.Union(data
.Select(x => new string[] {
x.busId.ToString(),
x.EmployeeId.ToString() ?? string.Empty,
x.BusId.ToString() ?? string.Empty,
x.Date.ToString(),
x.WorkHours?.ToString() ?? string.Empty,
x.Price?.ToString() ?? string.Empty}))
.Union([["Всего", "", data.Sum(x => x.WorkHours ?? 0).ToString(), data.Sum(x => x.Price ?? 0).ToString()]])
.Union([["Всего", "", "", data.Sum(x => x.WorkHours ?? 0).ToString(), data.Sum(x => x.Price ?? 0).ToString()]])
.ToList();
}
}

View File

@ -32,7 +32,10 @@ public class WordBuilder
{
var paragraph = _body.AppendChild(new Paragraph());
var run = paragraph.AppendChild(new Run());
// TODO прописать настройки под жирный текст
var runProperties = run.AppendChild(new RunProperties());
runProperties.AppendChild(new Bold());
run.AppendChild(new Text(header));
return this;

View File

@ -57,12 +57,12 @@ VALUES (@Starting_shift_id, @Employee_id, @Work_time)";
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT ss.*, sse.employee_id, sse.work_time FROM starting_shift ss
SELECT sse.starting_shift_id, ss.date, ss.route_list_id, ss.bus_id, sse.employee_id, sse.work_time FROM starting_shift ss
INNER JOIN starting_shift_employee sse ON sse.starting_shift_id = ss.id";
var startingShifts = connection.Query<TempStartingShiftEmployee>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(startingShifts));
return startingShifts.GroupBy(x => x.Starting_shift_id, y => y,
(key, value) => StartingShift.CreateOperation(value.First(),
(key, value) => StartingShift.CreateOperation(value.First(),
value.Select(z => StartingShiftEmployee.CreateElement(0, z.Employee_id, z.Work_time)))).ToList();
}
catch (Exception ex)