PIbd-21_Kudrinsky_O.S._LabWork_3 #6

Closed
8floom wants to merge 4 commits from LabWork_3 into LabWork_2
23 changed files with 1405 additions and 54 deletions
Showing only changes of commit 674cf8f42e - Show all commits

View File

@ -10,6 +10,8 @@ public class AssemblerShift
public int ShiftID_Shift { get; private set; }
public DateTime AssemblerShiftDate { get; private set; }
public static AssemblerShift CreateOperation(int id, int workHours, int assemblerID, int shiftID_Shift)
{
return new AssemblerShift
@ -17,7 +19,8 @@ public class AssemblerShift
ID = id,
WorkHours = workHours,
AssemblerID_Assembler = assemblerID,
ShiftID_Shift = shiftID_Shift
ShiftID_Shift = shiftID_Shift,
AssemblerShiftDate = DateTime.Now
};
}
}

View File

@ -12,14 +12,30 @@ public class Assembly
public IEnumerable<ProductAssembly> ProductAssembly { get; private set; } = [];
public static Assembly CreateOperation(int id, int count, int assemblerID, IEnumerable<ProductAssembly> productAssembly)
public DateTime AssemblyDate { get; private set; }
public static Assembly CreateOperation(int id, int count, int assemblerID, IEnumerable<ProductAssembly> productAssembly, DateTime? assemblyDate = null)
{
return new Assembly
{
ID = id,
Count = count,
AssemblerID_Assembler = assemblerID,
ProductAssembly = productAssembly
ProductAssembly = productAssembly,
AssemblyDate = assemblyDate ?? DateTime.Now
};
}
public static Assembly CreateOperation(TempProductAssembly tempProductAssembly, IEnumerable<ProductAssembly> productAssemblies)
{
return new Assembly
{
ID = tempProductAssembly.ID,
Count = tempProductAssembly.Count,
AssemblerID_Assembler = tempProductAssembly.AssemblyID_Assembly,
ProductAssembly = productAssemblies,
AssemblyDate = tempProductAssembly.AssemblyDate
};
}
}

View File

@ -10,8 +10,6 @@ public class Product
public double Price { get; private set; }
public DateTime AssemblyDate { get; private set; }
public ProductType ProductType { get; private set; }
@ -22,8 +20,7 @@ public class Product
ID = id,
ProductName = productName ?? string.Empty,
Price = price,
ProductType = productType,
AssemblyDate = DateTime.Now
ProductType = productType
};
}
}

View File

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectWorkshop.Entities;
public class TempProductAssembly
{
public int ID { get; private set; }
public int ProductID_Product { get; private set; }
public int AssemblyID_Assembly { get; private set; }
public int Count { get; private set; }
public DateTime AssemblyDate { get; private set; }
}

View File

@ -37,6 +37,8 @@
AssemblyToolStripMenuItem = new ToolStripMenuItem();
AssemblerShiftToolStripMenuItem = new ToolStripMenuItem();
отчетыToolStripMenuItem = new ToolStripMenuItem();
DirectoryReportToolStripMenuItem = new ToolStripMenuItem();
AssembliesReportToolStripMenuItem = new ToolStripMenuItem();
menuStrip.SuspendLayout();
SuspendLayout();
//
@ -60,21 +62,21 @@
// AssemblersToolStripMenuItem
//
AssemblersToolStripMenuItem.Name = "AssemblersToolStripMenuItem";
AssemblersToolStripMenuItem.Size = new Size(359, 44);
AssemblersToolStripMenuItem.Size = new Size(264, 44);
AssemblersToolStripMenuItem.Text = "Сборщики";
AssemblersToolStripMenuItem.Click += AssemblersToolStripMenuItem_Click;
//
// ShiftsToolStripMenuItem
//
ShiftsToolStripMenuItem.Name = "ShiftsToolStripMenuItem";
ShiftsToolStripMenuItem.Size = new Size(359, 44);
ShiftsToolStripMenuItem.Size = new Size(264, 44);
ShiftsToolStripMenuItem.Text = "Смены";
ShiftsToolStripMenuItem.Click += ShiftsToolStripMenuItem_Click;
//
// ProductsToolStripMenuItem
//
ProductsToolStripMenuItem.Name = "ProductsToolStripMenuItem";
ProductsToolStripMenuItem.Size = new Size(359, 44);
ProductsToolStripMenuItem.Size = new Size(264, 44);
ProductsToolStripMenuItem.Text = "Изделия";
ProductsToolStripMenuItem.Click += ProductsToolStripMenuItem_Click_1;
//
@ -101,10 +103,27 @@
//
// отчетыToolStripMenuItem
//
отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { DirectoryReportToolStripMenuItem, AssembliesReportToolStripMenuItem });
отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem";
отчетыToolStripMenuItem.Size = new Size(116, 38);
отчетыToolStripMenuItem.Text = "Отчеты";
//
// DirectoryReportToolStripMenuItem
//
DirectoryReportToolStripMenuItem.Name = "DirectoryReportToolStripMenuItem";
DirectoryReportToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.W;
DirectoryReportToolStripMenuItem.Size = new Size(559, 44);
DirectoryReportToolStripMenuItem.Text = "Документ со справочниками";
DirectoryReportToolStripMenuItem.Click += DirectoryReportToolStripMenuItem_Click;
//
// AssembliesReportToolStripMenuItem
//
AssembliesReportToolStripMenuItem.Name = "AssembliesReportToolStripMenuItem";
AssembliesReportToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.E;
AssembliesReportToolStripMenuItem.Size = new Size(559, 44);
AssembliesReportToolStripMenuItem.Text = "Отчет по сборкам";
AssembliesReportToolStripMenuItem.Click += AssembliesReportToolStripMenuItem_Click;
//
// FormWorkshop
//
AutoScaleDimensions = new SizeF(13F, 32F);
@ -134,5 +153,7 @@
private ToolStripMenuItem AssemblersToolStripMenuItem;
private ToolStripMenuItem ShiftsToolStripMenuItem;
private ToolStripMenuItem ProductsToolStripMenuItem;
private ToolStripMenuItem DirectoryReportToolStripMenuItem;
private ToolStripMenuItem AssembliesReportToolStripMenuItem;
}
}

View File

@ -73,5 +73,30 @@ namespace ProjectWorkshop
MessageBox.Show(ex.Message, "Ошибка при загрузке", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void DirectoryReportToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormDirectoryReport>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при загрузке", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void AssembliesReportToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormAssembliesReport>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при загрузке", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

View File

@ -0,0 +1,161 @@
namespace ProjectWorkshop.Forms
{
partial class FormAssembliesReport
{
/// <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()
{
labelFilePath = new Label();
labelDateFrom = new Label();
dateTimePickerStart = new DateTimePicker();
textBoxFilePath = new TextBox();
buttonSelectFilePath = new Button();
buttonBuild = new Button();
dateTimePickerEnd = new DateTimePicker();
labelDateTo = new Label();
labelAssembly = new Label();
comboBoxAssembly = new ComboBox();
SuspendLayout();
//
// labelFilePath
//
labelFilePath.AutoSize = true;
labelFilePath.Location = new Point(51, 48);
labelFilePath.Name = "labelFilePath";
labelFilePath.Size = new Size(178, 32);
labelFilePath.TabIndex = 0;
labelFilePath.Text = "Путь до файла:";
//
// labelDateFrom
//
labelDateFrom.AutoSize = true;
labelDateFrom.Location = new Point(51, 200);
labelDateFrom.Name = "labelDateFrom";
labelDateFrom.Size = new Size(154, 32);
labelDateFrom.TabIndex = 1;
labelDateFrom.Text = "Дата начала:";
//
// dateTimePickerStart
//
dateTimePickerStart.Location = new Point(255, 195);
dateTimePickerStart.Name = "dateTimePickerStart";
dateTimePickerStart.Size = new Size(400, 39);
dateTimePickerStart.TabIndex = 2;
//
// textBoxFilePath
//
textBoxFilePath.Location = new Point(255, 48);
textBoxFilePath.Name = "textBoxFilePath";
textBoxFilePath.Size = new Size(400, 39);
textBoxFilePath.TabIndex = 3;
//
// buttonSelectFilePath
//
buttonSelectFilePath.Location = new Point(661, 48);
buttonSelectFilePath.Name = "buttonSelectFilePath";
buttonSelectFilePath.Size = new Size(43, 39);
buttonSelectFilePath.TabIndex = 4;
buttonSelectFilePath.UseVisualStyleBackColor = true;
buttonSelectFilePath.Click += ButtonSelectFilePath_Click;
//
// buttonBuild
//
buttonBuild.Location = new Point(255, 373);
buttonBuild.Name = "buttonBuild";
buttonBuild.Size = new Size(192, 54);
buttonBuild.TabIndex = 5;
buttonBuild.Text = "Сформировать";
buttonBuild.UseVisualStyleBackColor = true;
buttonBuild.Click += ButtonBuild_Click;
//
// dateTimePickerEnd
//
dateTimePickerEnd.Location = new Point(255, 277);
dateTimePickerEnd.Name = "dateTimePickerEnd";
dateTimePickerEnd.Size = new Size(400, 39);
dateTimePickerEnd.TabIndex = 7;
//
// labelDateTo
//
labelDateTo.AutoSize = true;
labelDateTo.Location = new Point(51, 282);
labelDateTo.Name = "labelDateTo";
labelDateTo.Size = new Size(143, 32);
labelDateTo.TabIndex = 6;
labelDateTo.Text = "Дата конца:";
//
// labelAssembly
//
labelAssembly.AutoSize = true;
labelAssembly.Location = new Point(78, 129);
labelAssembly.Name = "labelAssembly";
labelAssembly.Size = new Size(100, 32);
labelAssembly.TabIndex = 8;
labelAssembly.Text = "Сборка:";
//
// comboBoxAssembly
//
comboBoxAssembly.FormattingEnabled = true;
comboBoxAssembly.Location = new Point(255, 126);
comboBoxAssembly.Name = "comboBoxAssembly";
comboBoxAssembly.Size = new Size(400, 40);
comboBoxAssembly.TabIndex = 9;
//
// FormAssembliesReport
//
AutoScaleDimensions = new SizeF(13F, 32F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(comboBoxAssembly);
Controls.Add(labelAssembly);
Controls.Add(dateTimePickerEnd);
Controls.Add(labelDateTo);
Controls.Add(buttonBuild);
Controls.Add(buttonSelectFilePath);
Controls.Add(textBoxFilePath);
Controls.Add(dateTimePickerStart);
Controls.Add(labelDateFrom);
Controls.Add(labelFilePath);
Name = "FormAssembliesReport";
Text = "Отчет по сборкам";
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label labelFilePath;
private Label labelDateFrom;
private DateTimePicker dateTimePickerStart;
private TextBox textBoxFilePath;
private Button buttonSelectFilePath;
private Button buttonBuild;
private DateTimePicker dateTimePickerEnd;
private Label labelDateTo;
private Label labelAssembly;
private ComboBox comboBoxAssembly;
}
}

View File

@ -0,0 +1,78 @@
using ProjectWorkshop.Reports;
using ProjectWorkshop.Repositories;
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 ProjectWorkshop.Forms
{
public partial class FormAssembliesReport : Form
{
private readonly IUnityContainer _container;
public FormAssembliesReport(IUnityContainer container, IAssemblyRepository assemblyRepository)
{
InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container));
comboBoxAssembly.DataSource = assemblyRepository.ReadAssemblies();
comboBoxAssembly.DisplayMember = "Name";
comboBoxAssembly.ValueMember = "ID";
}
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;
}
private void ButtonBuild_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(textBoxFilePath.Text))
{
throw new Exception("Отсутствует имя файла для отчета");
}
if (dateTimePickerEnd.Value < dateTimePickerStart.Value)
{
throw new Exception("Дата начала должна быть раньше даты окончания");
}
if (comboBoxAssembly.SelectedIndex < 0)
{
throw new Exception("Не выбрана сборка");
}
if (_container.Resolve<TableReport>().CreateTable(textBoxFilePath.Text, (int)comboBoxAssembly.SelectedValue!,
dateTimePickerStart.Value, dateTimePickerEnd.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

@ -36,6 +36,8 @@
ColumnCount = new DataGridViewTextBoxColumn();
buttonSave = new Button();
buttonCancel = new Button();
labelAssemblyDate = new Label();
dateTimePickerAssemblyDate = new DateTimePicker();
groupBox.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridViewAssemblies).BeginInit();
SuspendLayout();
@ -61,9 +63,9 @@
//
groupBox.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
groupBox.Controls.Add(dataGridViewAssemblies);
groupBox.Location = new Point(50, 160);
groupBox.Location = new Point(50, 177);
groupBox.Name = "groupBox";
groupBox.Size = new Size(618, 591);
groupBox.Size = new Size(618, 602);
groupBox.TabIndex = 2;
groupBox.TabStop = false;
//
@ -98,7 +100,7 @@
// buttonSave
//
buttonSave.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonSave.Location = new Point(82, 786);
buttonSave.Location = new Point(110, 823);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(150, 46);
buttonSave.TabIndex = 3;
@ -109,7 +111,7 @@
// buttonCancel
//
buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonCancel.Location = new Point(464, 786);
buttonCancel.Location = new Point(439, 823);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(150, 46);
buttonCancel.TabIndex = 4;
@ -117,11 +119,29 @@
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// labelAssemblyDate
//
labelAssemblyDate.AutoSize = true;
labelAssemblyDate.Location = new Point(50, 137);
labelAssemblyDate.Name = "labelAssemblyDate";
labelAssemblyDate.Size = new Size(156, 32);
labelAssemblyDate.TabIndex = 5;
labelAssemblyDate.Text = "Дата сборки:";
//
// dateTimePickerAssemblyDate
//
dateTimePickerAssemblyDate.Location = new Point(242, 132);
dateTimePickerAssemblyDate.Name = "dateTimePickerAssemblyDate";
dateTimePickerAssemblyDate.Size = new Size(386, 39);
dateTimePickerAssemblyDate.TabIndex = 6;
//
// FormAssembly
//
AutoScaleDimensions = new SizeF(13F, 32F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(715, 861);
ClientSize = new Size(715, 912);
Controls.Add(dateTimePickerAssemblyDate);
Controls.Add(labelAssemblyDate);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(groupBox);
@ -145,5 +165,7 @@
private DataGridViewTextBoxColumn ColumnCount;
private Button buttonSave;
private Button buttonCancel;
private Label labelAssemblyDate;
private DateTimePicker dateTimePickerAssemblyDate;
}
}

View File

@ -4,6 +4,7 @@ using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
@ -50,11 +51,13 @@ namespace ProjectWorkshop.Forms
}
var totalCount = productAssemblies.Sum(pa => pa.Count);
var assemblyDate = dateTimePickerAssemblyDate.Value; // Получение выбранной даты
_assemblyRepository.CreateAssembly(Assembly.CreateOperation(
id: 0,
count: totalCount,
assemblerID: (int)comboBoxAssembler.SelectedValue!,
assemblyDate: assemblyDate,
productAssembly: productAssemblies
));
@ -66,6 +69,7 @@ namespace ProjectWorkshop.Forms
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
Close();
@ -90,7 +94,17 @@ namespace ProjectWorkshop.Forms
}
return list;
return list
.GroupBy(
x => x.ProductID_Product,
x => x.Count,
(id, counts) => ProductAssembly.CreateElement(
id: 0,
productID: id,
assemblyID: 0,
count: counts.Sum()
))
.ToList();
}
}
}

View File

@ -123,10 +123,4 @@
<metadata name="ColumnCount.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnProductName.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnCount.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root>

View File

@ -0,0 +1,99 @@
namespace ProjectWorkshop.Forms
{
partial class FormDirectoryReport
{
/// <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()
{
checkBoxProducts = new CheckBox();
checkBoxAssemblers = new CheckBox();
checkBoxShifts = new CheckBox();
buttonBuild = new Button();
SuspendLayout();
//
// checkBoxProducts
//
checkBoxProducts.AutoSize = true;
checkBoxProducts.Location = new Point(63, 66);
checkBoxProducts.Name = "checkBoxProducts";
checkBoxProducts.Size = new Size(140, 36);
checkBoxProducts.TabIndex = 0;
checkBoxProducts.Text = "Изделия";
checkBoxProducts.UseVisualStyleBackColor = true;
//
// checkBoxAssemblers
//
checkBoxAssemblers.AutoSize = true;
checkBoxAssemblers.Location = new Point(63, 162);
checkBoxAssemblers.Name = "checkBoxAssemblers";
checkBoxAssemblers.Size = new Size(163, 36);
checkBoxAssemblers.TabIndex = 1;
checkBoxAssemblers.Text = "Сборщики";
checkBoxAssemblers.UseVisualStyleBackColor = true;
//
// checkBoxShifts
//
checkBoxShifts.AutoSize = true;
checkBoxShifts.Location = new Point(63, 262);
checkBoxShifts.Name = "checkBoxShifts";
checkBoxShifts.Size = new Size(122, 36);
checkBoxShifts.TabIndex = 2;
checkBoxShifts.Text = "Смены";
checkBoxShifts.UseVisualStyleBackColor = true;
//
// buttonBuild
//
buttonBuild.Location = new Point(370, 156);
buttonBuild.Name = "buttonBuild";
buttonBuild.Size = new Size(235, 46);
buttonBuild.TabIndex = 3;
buttonBuild.Text = "Сформировать";
buttonBuild.UseVisualStyleBackColor = true;
buttonBuild.Click += buttonBuild_Click;
//
// FormDirectoryReport
//
AutoScaleDimensions = new SizeF(13F, 32F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(712, 345);
Controls.Add(buttonBuild);
Controls.Add(checkBoxShifts);
Controls.Add(checkBoxAssemblers);
Controls.Add(checkBoxProducts);
Name = "FormDirectoryReport";
Text = "Выбор справочников";
ResumeLayout(false);
PerformLayout();
}
#endregion
private CheckBox checkBoxProducts;
private CheckBox checkBoxAssemblers;
private CheckBox checkBoxShifts;
private Button buttonBuild;
}
}

View File

@ -0,0 +1,66 @@
using ProjectWorkshop.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 ProjectWorkshop.Forms
{
public partial class FormDirectoryReport : Form
{
private readonly IUnityContainer _container;
public FormDirectoryReport(IUnityContainer container)
{
InitializeComponent();
_container = container ??
throw new ArgumentNullException(nameof(container));
}
private void buttonBuild_Click(object sender, EventArgs e)
{
try
{
if (!checkBoxProducts.Checked &&
!checkBoxAssemblers.Checked && !checkBoxShifts.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,
checkBoxProducts.Checked,
checkBoxAssemblers.Checked,
checkBoxShifts.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

@ -10,6 +10,7 @@
<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" />

View File

@ -0,0 +1,83 @@
using Microsoft.Extensions.Logging;
using ProjectWorkshop.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectWorkshop.Reports;
internal class DocReport
{
private readonly IAssemblerRepository _assemblerRepository;
private readonly IProductRepository _productRepository;
private readonly IShiftRepository _shiftRepository;
private readonly ILogger<DocReport> _logger;
public DocReport(IAssemblerRepository assemblerRepository, IProductRepository productRepository,IShiftRepository shiftRepository ,ILogger<DocReport> logger)
{
_assemblerRepository = assemblerRepository ?? throw new ArgumentNullException(nameof(assemblerRepository));
_productRepository = productRepository ?? throw new ArgumentNullException(nameof(productRepository));
_shiftRepository = shiftRepository ?? throw new ArgumentNullException(nameof(shiftRepository));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public bool CreateDoc(string filePath, bool incAssemblers, bool incProducts, bool incShifts)
{
try
{
var builder = new WordBuilder(filePath).AddHeader("Документ со справочниками");
if (incAssemblers)
{
builder.AddParagraph("Сборщики").AddTable([2400, 2400, 2400], GetAssemblers());
}
if (incProducts)
{
builder.AddParagraph("Изделия").AddTable([2400, 2400, 2400], GetProducts());
}
if (incShifts)
{
builder.AddParagraph("Смены").AddTable([7200], GetShifts());
}
builder.Build();
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при формировании документа");
return false;
}
}
private List<string[]> GetProducts()
{
return [
["Название изделия", "Стоимость", "Дата сборки"],
.. _productRepository
.ReadProducts()
.Select(x => new string[] { x.ProductName, x.Price.ToString()}),
];
}
private List<string[]> GetAssemblers()
{
return [
["ФИО Сборщика", "Разряд", "Стаж работы"],
.. _assemblerRepository
.ReadAssemblers()
.Select(x => new string[] { x.FullName, x.AssemblerRank.ToString(), x.WorkExperience.ToString() }),
];
}
private List<string[]> GetShifts()
{
return [
["Дата выхода на смену"],
.. _shiftRepository
.ReadShifts()
.Select(x => new string[] { x.ShiftDate.ToString()}),
];
}
}

View File

@ -0,0 +1,316 @@
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 ProjectWorkshop.Reports;
internal 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.BoldTextWithoutBorder);
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.BoldTextWithBorder);
}
_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.SimpleTextWithBorder);
}
_rowIndex++;
}
for (var j = 0; j < data.Last().Length; ++j)
{
CreateCell(j, _rowIndex, data.Last()[j], StyleIndex.BoldTextWithBorder);
}
_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()
});
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
}
});
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,
SimpleTextWithBorder = 1,
BoldTextWithoutBorder = 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,99 @@
using Microsoft.Extensions.Logging;
using ProjectWorkshop.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectWorkshop.Reports;
internal class TableReport
{
private readonly IAssemblyRepository _assemblyRepository;
private readonly IAssemblerShiftRepository _assemblerShiftRepository;
private readonly ILogger<TableReport> _logger;
internal static readonly string[] Headers = { "Дата", "Описание", "Количество сборок", "Количество часов смен" };
public TableReport(IAssemblyRepository assemblyRepository,
IAssemblerShiftRepository assemblerShiftRepository,
ILogger<TableReport> logger)
{
_assemblyRepository = assemblyRepository ?? throw new ArgumentNullException(nameof(assemblyRepository));
_assemblerShiftRepository = assemblerShiftRepository ?? throw new ArgumentNullException(nameof(assemblerShiftRepository));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public bool CreateTable(string filePath, int assemblerId, DateTime startDate, DateTime endDate)
{
try
{
var data = GetData(assemblerId, startDate, endDate);
new ExcelBuilder(filePath)
.AddHeader("Сводка по сборкам", 0, Headers.Length)
.AddParagraph($"за период с {startDate:dd.MM.yyyy} по {endDate:dd.MM.yyyy}", 0)
.AddTable(new[] { 15, 40, 20, 20 }, data)
.Build();
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при формировании документа");
return false;
}
}
private List<string[]> GetData(int assemblerId, DateTime startDate, DateTime endDate)
{
// Данные о сборках
var assemblyData = _assemblyRepository
.ReadAssemblies()
.Where(x => x.AssemblyDate >= startDate && x.AssemblyDate <= endDate && x.AssemblerID_Assembler == assemblerId)
.Select(x => new
{
Date = x.AssemblyDate,
Description = $"Сборка ID {x.ID}",
CountAssemblies = x.Count.ToString("N0"),
WorkHours = "-"
});
// Данные о сменах
var shiftData = _assemblerShiftRepository
.ReadAssemblerShifts()
.Where(x => x.AssemblerShiftDate >= startDate && x.AssemblerShiftDate <= endDate && x.AssemblerID_Assembler == assemblerId)
.Select(x => new
{
Date = x.AssemblerShiftDate,
Description = $"Смена ID {x.ShiftID_Shift}",
CountAssemblies = "-",
WorkHours = x.WorkHours.ToString("N0")
});
// Объединение и сортировка
var combinedData = assemblyData
.Union(shiftData)
.OrderBy(x => x.Date);
// Итоговые данные
var totalAssemblies = assemblyData.Sum(x => int.TryParse(x.CountAssemblies, out var count) ? count : 0);
var totalWorkHours = shiftData.Sum(x => int.TryParse(x.WorkHours, out var hours) ? hours : 0);
// Формирование таблицы
return new List<string[]> { Headers }
.Union(combinedData.Select(x => new[]
{
x.Date.ToString("dd.MM.yyyy"),
x.Description,
x.CountAssemblies,
x.WorkHours
}))
.Union(new List<string[]> { new[] { "Всего", "", totalAssemblies.ToString("N0"), totalWorkHours.ToString("N0") } })
.ToList();
}
}

View File

@ -0,0 +1,106 @@
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Wordprocessing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectWorkshop.Reports;
internal 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

@ -3,7 +3,7 @@ namespace ProjectWorkshop.Repositories;
public interface IAssemblyRepository
{
IEnumerable<Assembly> ReadAssemblies(int? productID = null, int? assemblyID = null, int? count = null);
IEnumerable<Assembly> ReadAssemblies(DateTime? dateFrom = null, DateTime? dateTo = null, int? productID = null, int? assemblyID = null, int? count = null);
void CreateAssembly(Assembly assembly);

View File

@ -32,19 +32,21 @@ public class AssemblyRepository : IAssemblyRepository
connection.Open();
using var transaction = connection.BeginTransaction();
// Добавляем дату сборки в запрос
var queryInsert = @"
INSERT INTO Assembly (Count, AssemblerID_Assembler)
VALUES (@Count, @AssemblerID_Assembler)
RETURNING ID";
INSERT INTO Assembly (Count, AssemblerID_Assembler, AssemblyDate)
VALUES (@Count, @AssemblerID_Assembler, @AssemblyDate)
RETURNING ID";
var assemblyId = connection.QueryFirst<int>(queryInsert, new
{
assembly.Count,
assembly.AssemblerID_Assembler
assembly.AssemblerID_Assembler,
assembly.AssemblyDate // Передаём дату сборки
}, transaction);
var querySubInsert = @"
INSERT INTO ProductAssembly (ProductID_Product, AssemblyID_Assembly, Count)
VALUES (@ProductID_Product, @AssemblyID_Assembly, @Count)";
INSERT INTO ProductAssembly (ProductID_Product, AssemblyID_Assembly, Count)
VALUES (@ProductID_Product, @AssemblyID_Assembly, @Count)";
foreach (var elem in assembly.ProductAssembly)
{
@ -65,6 +67,7 @@ public class AssemblyRepository : IAssemblyRepository
}
}
public void DeleteAssembly(int id)
{
_logger.LogInformation("Удаление объекта");
@ -84,17 +87,22 @@ public class AssemblyRepository : IAssemblyRepository
}
}
public IEnumerable<Assembly> ReadAssemblies(int? id = null, int? assemblyID = null, int? count = null)
public IEnumerable<Assembly> ReadAssemblies(DateTime? dateFrom = null, DateTime? dateTo = null, int? id = null, int? assemblyID = null, int? count = null)
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Assembly";
var assemblies = connection.Query<Assembly>(querySelect);
var querySelect = @"
SELECT fr.*, ffr.AssemblyID_Assembly, ffr.Count, a.AssemblyDate
FROM ProductAssembly fr
INNER JOIN ProductAssembly ffr ON ffr.AssemblyID_Assembly = fr.Id
INNER JOIN Assembly a ON fr.AssemblyID_Assembly = a.ID";
var assemblies = connection.Query<TempProductAssembly>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(assemblies));
return assemblies;
return assemblies.GroupBy(x => x.ID, y => y, (key, value) => Assembly.CreateOperation(value.First(), value.Select(
z => ProductAssembly.CreateElement(0, z.ProductID_Product, z.AssemblyID_Assembly, z.Count)))).ToList();
}
catch (Exception ex)
{
@ -102,22 +110,4 @@ public class AssemblyRepository : IAssemblyRepository
throw;
}
}
public IEnumerable<Assembler> GetAssemblers()
{
_logger.LogInformation("Получение всех сборщиков");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var query = "SELECT ID, Name FROM Assembler";
var assemblers = connection.Query<Assembler>(query);
_logger.LogDebug("Полученные сборщики: {json}", JsonConvert.SerializeObject(assemblers));
return assemblers;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при получении сборщиков");
throw;
}
}
}

View File

@ -30,8 +30,8 @@ public class ProductRepository : IProductRepository
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Product (ProductName, Price, AssemblyDate, ProductType)
VALUES (@ProductName, @Price, @AssemblyDate, @ProductType)
INSERT INTO Product (ProductName, Price, ProductType)
VALUES (@ProductName, @Price, @ProductType)
RETURNING ID";
connection.Execute(queryInsert, product);
}
@ -50,7 +50,7 @@ public class ProductRepository : IProductRepository
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Product
SET ProductName=@ProductName, Price=@Price, AssemblyDate=@AssemblyDate, ProductType=@ProductType
SET ProductName=@ProductName, Price=@Price, ProductType=@ProductType
WHERE ID=@ID";
connection.Execute(queryUpdate, product);
}