lab-3 done

This commit is contained in:
strwbrry1 2024-12-24 21:05:59 +04:00
parent 37facf0620
commit 1767165e0b
8 changed files with 470 additions and 4 deletions

View File

@ -40,6 +40,7 @@
отчетыToolStripMenuItem = new ToolStripMenuItem();
документСоСправочникамиToolStripMenuItem = new ToolStripMenuItem();
таблицаСОперациямиToolStripMenuItem = new ToolStripMenuItem();
графикToolStripMenuItem = new ToolStripMenuItem();
menuStrip1.SuspendLayout();
SuspendLayout();
//
@ -112,7 +113,7 @@
//
// отчетыToolStripMenuItem
//
отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { документСоСправочникамиToolStripMenuItem, таблицаСОперациямиToolStripMenuItem });
отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { документСоСправочникамиToolStripMenuItem, таблицаСОперациямиToolStripMenuItem, графикToolStripMenuItem });
отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem";
отчетыToolStripMenuItem.Size = new Size(60, 20);
отчетыToolStripMenuItem.Text = "Отчеты";
@ -121,18 +122,26 @@
//
документСоСправочникамиToolStripMenuItem.Name = окументСоСправочникамиToolStripMenuItem";
документСоСправочникамиToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.W;
документСоСправочникамиToolStripMenuItem.Size = new Size(280, 22);
документСоСправочникамиToolStripMenuItem.Size = new Size(312, 22);
документСоСправочникамиToolStripMenuItem.Text = "Документ со справочниками";
документСоСправочникамиToolStripMenuItem.Click += документСоСправочникамиToolStripMenuItem_Click;
//
// таблицаСОперациямиToolStripMenuItem
//
таблицаСОперациямиToolStripMenuItem.Name = аблицаСОперациямиToolStripMenuItem";
таблицаСОперациямиToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.T;
таблицаСОперациямиToolStripMenuItem.Size = new Size(280, 22);
таблицаСОперациямиToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.E;
таблицаСОперациямиToolStripMenuItem.Size = new Size(312, 22);
таблицаСОперациямиToolStripMenuItem.Text = "Таблица с операциями";
таблицаСОперациямиToolStripMenuItem.Click += таблицаСОперациямиToolStripMenuItem_Click;
//
// графикToolStripMenuItem
//
графикToolStripMenuItem.Name = "графикToolStripMenuItem";
графикToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.P;
графикToolStripMenuItem.Size = new Size(312, 22);
графикToolStripMenuItem.Text = "График распределения материалов";
графикToolStripMenuItem.Click += графикToolStripMenuItem_Click;
//
// FormPublishing
//
AutoScaleDimensions = new SizeF(7F, 15F);
@ -163,5 +172,6 @@
private ToolStripMenuItem заказToolStripMenuItem;
private ToolStripMenuItem документСоСправочникамиToolStripMenuItem;
private ToolStripMenuItem таблицаСОперациямиToolStripMenuItem;
private ToolStripMenuItem графикToolStripMenuItem;
}
}

View File

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

View File

@ -0,0 +1,107 @@
namespace ProjectPublishing.Forms
{
partial class FormMaterialDistributionReport
{
/// <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()
{
buttonSelectFilePath = new Button();
labelFileNameText = new Label();
dateTimePicker = new DateTimePicker();
label1 = new Label();
buttonMakeReport = new Button();
SuspendLayout();
//
// buttonSelectFilePath
//
buttonSelectFilePath.Location = new Point(12, 12);
buttonSelectFilePath.Name = "buttonSelectFilePath";
buttonSelectFilePath.Size = new Size(94, 28);
buttonSelectFilePath.TabIndex = 0;
buttonSelectFilePath.Text = "Выбрать";
buttonSelectFilePath.UseVisualStyleBackColor = true;
buttonSelectFilePath.Click += ButtonSelectFilePath_Click;
//
// labelFileNameText
//
labelFileNameText.AutoSize = true;
labelFileNameText.Location = new Point(134, 19);
labelFileNameText.Name = "labelFileNameText";
labelFileNameText.Size = new Size(36, 15);
labelFileNameText.TabIndex = 1;
labelFileNameText.Text = "файл";
//
// dateTimePicker
//
dateTimePicker.Location = new Point(72, 71);
dateTimePicker.Name = "dateTimePicker";
dateTimePicker.Size = new Size(189, 23);
dateTimePicker.TabIndex = 2;
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(12, 77);
label1.Name = "label1";
label1.Size = new Size(32, 15);
label1.TabIndex = 3;
label1.Text = "Дата";
//
// buttonMakeReport
//
buttonMakeReport.Location = new Point(114, 129);
buttonMakeReport.Name = "buttonMakeReport";
buttonMakeReport.Size = new Size(116, 23);
buttonMakeReport.TabIndex = 4;
buttonMakeReport.Text = "Сформировать";
buttonMakeReport.UseVisualStyleBackColor = true;
buttonMakeReport.Click += ButtonMakeReport_Click;
//
// FormMaterialDistributionReport
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(344, 164);
Controls.Add(buttonMakeReport);
Controls.Add(label1);
Controls.Add(dateTimePicker);
Controls.Add(labelFileNameText);
Controls.Add(buttonSelectFilePath);
Name = "FormMaterialDistributionReport";
Text = "FormMaterialDistributionReport";
ResumeLayout(false);
PerformLayout();
}
#endregion
private Button buttonSelectFilePath;
private Label labelFileNameText;
private DateTimePicker dateTimePicker;
private Label label1;
private Button buttonMakeReport;
}
}

View File

@ -0,0 +1,67 @@
using ProjectPublishing.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 ProjectPublishing.Forms
{
public partial class FormMaterialDistributionReport : Form
{
private string _fileName = string.Empty;
private readonly IUnityContainer _container;
public FormMaterialDistributionReport(IUnityContainer container)
{
InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container));
}
private void ButtonSelectFilePath_Click(object sender, EventArgs e)
{
var sfd = new SaveFileDialog()
{
Filter = "Pdf Files | *.pdf"
};
if (sfd.ShowDialog() == DialogResult.OK)
{
_fileName = sfd.FileName;
labelFileNameText.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

@ -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,57 @@
using Microsoft.Extensions.Logging;
using ProjectPublishing.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectPublishing.Reports
{
public class ChartReport
{
private readonly IMaterialAdmissionRepository _materialRepository;
private readonly ILogger<ChartReport> _logger;
public ChartReport(IMaterialAdmissionRepository materialRepository,
ILogger<ChartReport> logger)
{
_materialRepository = materialRepository ??
throw new ArgumentNullException(nameof(materialRepository));
_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 _materialRepository
.ReadMaterialsAdmission()
.Where(x => x.DateTime.Date == dateTime.Date)
.GroupBy(x => x.MaterialId, (key, group) => new
{
Id = key,
Count = group.Sum(x => x.Amount)
})
.Select(x => (x.Id.ToString(), (double)x.Count))
.ToList();
}
}
}

View File

@ -0,0 +1,92 @@
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 ProjectPublishing.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;
}
}
}