Лабораторная работа №3 (2) Финал

This commit is contained in:
Егор 2024-12-09 08:40:29 +04:00
parent 2d3d9a7203
commit aa64ffa1c0
9 changed files with 465 additions and 4 deletions

View File

@ -39,6 +39,7 @@
отчётыToolStripMenuItem = new ToolStripMenuItem(); отчётыToolStripMenuItem = new ToolStripMenuItem();
DirectoryReportToolStripMenuItem = new ToolStripMenuItem(); DirectoryReportToolStripMenuItem = new ToolStripMenuItem();
productReportToolStripMenuItem = new ToolStripMenuItem(); productReportToolStripMenuItem = new ToolStripMenuItem();
productDistributionToolStripMenuItem = new ToolStripMenuItem();
menuStrip1.SuspendLayout(); menuStrip1.SuspendLayout();
SuspendLayout(); SuspendLayout();
// //
@ -103,7 +104,7 @@
// //
// отчётыToolStripMenuItem // отчётыToolStripMenuItem
// //
отчётыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { DirectoryReportToolStripMenuItem, productReportToolStripMenuItem }); отчётыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { DirectoryReportToolStripMenuItem, productReportToolStripMenuItem, productDistributionToolStripMenuItem });
отчётыToolStripMenuItem.Name = "отчётыToolStripMenuItem"; отчётыToolStripMenuItem.Name = "отчётыToolStripMenuItem";
отчётыToolStripMenuItem.Size = new Size(73, 24); отчётыToolStripMenuItem.Size = new Size(73, 24);
отчётыToolStripMenuItem.Text = "Отчёты"; отчётыToolStripMenuItem.Text = "Отчёты";
@ -124,6 +125,14 @@
productReportToolStripMenuItem.Text = "Движение изделий"; productReportToolStripMenuItem.Text = "Движение изделий";
productReportToolStripMenuItem.Click += ProductReportToolStripMenuItem_Click; productReportToolStripMenuItem.Click += ProductReportToolStripMenuItem_Click;
// //
// productDistributionToolStripMenuItem
//
productDistributionToolStripMenuItem.Name = "распределениеИзделийToolStripMenuItem";
productDistributionToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.P;
productDistributionToolStripMenuItem.Size = new Size(350, 26);
productDistributionToolStripMenuItem.Text = "Распределение изделий";
productDistributionToolStripMenuItem.Click += ProductDistributionToolStripMenuItem_Click;
//
// FormFurnitureCompany // FormFurnitureCompany
// //
AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleDimensions = new SizeF(8F, 20F);
@ -155,5 +164,6 @@
private ToolStripMenuItem DeliveryToolStripMenuItem; private ToolStripMenuItem DeliveryToolStripMenuItem;
private ToolStripMenuItem DirectoryReportToolStripMenuItem; private ToolStripMenuItem DirectoryReportToolStripMenuItem;
private ToolStripMenuItem productReportToolStripMenuItem; private ToolStripMenuItem productReportToolStripMenuItem;
private ToolStripMenuItem productDistributionToolStripMenuItem;
} }
} }

View File

@ -97,5 +97,17 @@ namespace FurnitureCompany
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
private void ProductDistributionToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormProductClientDistributionReport>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
} }
} }

View File

@ -0,0 +1,107 @@
namespace FurnitureCompany.Forms
{
partial class FormProductClientDistributionReport
{
/// <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()
{
dateTimePickerDate = new DateTimePicker();
buttonCreate = new Button();
labelDate = new Label();
labelFile = new Label();
buttonSelectFileName = new Button();
SuspendLayout();
//
// dateTimePickerDate
//
dateTimePickerDate.Location = new Point(76, 71);
dateTimePickerDate.Name = "dateTimePickerDate";
dateTimePickerDate.Size = new Size(210, 27);
dateTimePickerDate.TabIndex = 0;
//
// buttonCreate
//
buttonCreate.Location = new Point(88, 124);
buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(125, 29);
buttonCreate.TabIndex = 1;
buttonCreate.Text = "Сформировать";
buttonCreate.UseVisualStyleBackColor = true;
buttonCreate.Click += ButtonCreate_Click;
//
// labelDate
//
labelDate.AutoSize = true;
labelDate.Location = new Point(26, 76);
labelDate.Name = "labelDate";
labelDate.Size = new Size(44, 20);
labelDate.TabIndex = 2;
labelDate.Text = "Дата:";
//
// labelFile
//
labelFile.AutoSize = true;
labelFile.Location = new Point(178, 27);
labelFile.Name = "labelFile";
labelFile.Size = new Size(45, 20);
labelFile.TabIndex = 3;
labelFile.Text = "Файл";
//
// buttonSelectFileName
//
buttonSelectFileName.Location = new Point(55, 23);
buttonSelectFileName.Name = "buttonSelectFileName";
buttonSelectFileName.Size = new Size(94, 29);
buttonSelectFileName.TabIndex = 4;
buttonSelectFileName.Text = "Выбрать";
buttonSelectFileName.UseVisualStyleBackColor = true;
buttonSelectFileName.Click += ButtonSelectFileName_Click;
//
// FormProductClientDistributionReport
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(319, 190);
Controls.Add(buttonSelectFileName);
Controls.Add(labelFile);
Controls.Add(labelDate);
Controls.Add(buttonCreate);
Controls.Add(dateTimePickerDate);
Name = "FormProductClientDistributionReport";
Text = "Распределение изделий";
ResumeLayout(false);
PerformLayout();
}
#endregion
private DateTimePicker dateTimePickerDate;
private Button buttonCreate;
private Label labelDate;
private Label labelFile;
private Button buttonSelectFileName;
}
}

View File

@ -0,0 +1,67 @@
using FurnitureCompany.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 FurnitureCompany.Forms
{
public partial class FormProductClientDistributionReport : Form
{
private string _fileName = string.Empty;
private readonly IUnityContainer _container;
public FormProductClientDistributionReport(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;
labelFile.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, dateTimePickerDate.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

@ -17,6 +17,7 @@
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.0" /> <PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Npgsql" Version="9.0.2" /> <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" Version="4.2.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" /> <PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.4" /> <PackageReference Include="Serilog.Settings.Configuration" Version="8.0.4" />

View File

@ -0,0 +1,50 @@
using FurnitureCompany.Repositories;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FurnitureCompany.Reports;
internal class ChartReport
{
private readonly IInvoiceRepository _invoiceRepository;
private readonly ILogger<ChartReport> _logger;
public ChartReport(IInvoiceRepository invoiceRepository, ILogger<ChartReport> logger)
{
_invoiceRepository = invoiceRepository ??
throw new ArgumentNullException(nameof(invoiceRepository));
_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 _invoiceRepository
.ReadInvoices()
.Where(x => x.Date.Date == dateTime.Date)
.GroupBy(x => x.ClientId, (key, group) => new { Id = key, Count = group.Sum(x => x.CountProduct) })
.Select(x => (x.Id.ToString(), (double)x.Count))
.ToList();
}
}

View File

@ -0,0 +1,94 @@
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 FurnitureCompany.Reports;
internal class PdfBuilder
{
private readonly string _filePath;
private readonly Document _document;
public PdfBuilder(string filePath)
{
if (string.IsNullOrWhiteSpace(filePath))
{
throw new ArgumentNullException(nameof(filePath));
}
if (File.Exists(filePath))
{
File.Delete(filePath);
}
_filePath = filePath;
_document = new Document();
DefineStyles();
}
public PdfBuilder AddHeader(string header)
{
_document.AddSection().AddParagraph(header, "NormalBold");
return this;
}
public PdfBuilder AddPieChart(string title, List<(string Caption, double Value)> data)
{
if (data == null || data.Count == 0)
{
return this;
}
var chart = new Chart(ChartType.Pie2D);
var series = chart.SeriesCollection.AddSeries();
series.Add(data.Select(x => x.Value).ToArray());
var xseries = chart.XValues.AddXSeries();
xseries.Add(data.Select(x => x.Caption).ToArray());
chart.DataLabel.Type = DataLabelType.Percent;
chart.DataLabel.Position = DataLabelPosition.OutsideEnd;
chart.Width = Unit.FromCentimeter(16);
chart.Height = Unit.FromCentimeter(12);
chart.TopArea.AddParagraph(title);
chart.XAxis.MajorTickMark = TickMarkType.Outside;
chart.YAxis.MajorTickMark = TickMarkType.Outside;
chart.YAxis.HasMajorGridlines = true;
chart.PlotArea.LineFormat.Width = 1;
chart.PlotArea.LineFormat.Visible = true;
chart.TopArea.AddLegend();
_document.LastSection.Add(chart);
return this;
}
public void Build()
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var renderer = new PdfDocumentRenderer(true)
{
Document = _document
};
renderer.RenderDocument();
renderer.PdfDocument.Save(_filePath);
}
private void DefineStyles()
{
var headerStyle = _document.Styles.AddStyle("NormalBold", "Normal");
headerStyle.Font.Bold = true;
headerStyle.Font.Size = 14;
}
}

View File

@ -34,9 +34,9 @@ internal class TableReport
try try
{ {
new ExcelBuilder(filePath) new ExcelBuilder(filePath)
.AddHeader("Сводка по доставке изделий", 0, 2) .AddHeader("Сводка по доставке изделий", 0, 4)
.AddParagraph("за период", 0) .AddParagraph("за период", 0)
.AddTable([10, 10, 15], GetData(productId, startDate, endDate)) .AddTable([10, 10, 15, 15], GetData(productId, startDate, endDate))
.Build(); .Build();
return true; return true;
@ -66,7 +66,7 @@ internal class TableReport
data data
.Select(x => new string[] { x.WorkerId.ToString(), x.Date.ToString(), x.CountIn?.ToString() ?? string.Empty, x.CountOut?.ToString() ?? string.Empty })) .Select(x => new string[] { x.WorkerId.ToString(), x.Date.ToString(), x.CountIn?.ToString() ?? string.Empty, x.CountOut?.ToString() ?? string.Empty }))
.Union( .Union(
[["Всего", data.Sum(x => x.CountIn ?? 0).ToString(), data.Sum(x => x.CountOut ?? 0).ToString()]]) [["Всего", "", data.Sum(x => x.CountIn ?? 0).ToString(), data.Sum(x => x.CountOut ?? 0).ToString()]])
.ToList(); .ToList();
} }
} }