diff --git a/ProjectWorkshop/ProjectWorkshop/Entities/AssemblerShift.cs b/ProjectWorkshop/ProjectWorkshop/Entities/AssemblerShift.cs index 2f418a9..917889c 100644 --- a/ProjectWorkshop/ProjectWorkshop/Entities/AssemblerShift.cs +++ b/ProjectWorkshop/ProjectWorkshop/Entities/AssemblerShift.cs @@ -10,14 +10,17 @@ public class AssemblerShift public int ShiftID_Shift { get; private set; } - public static AssemblerShift CreateOperation(int id, int workHours, int assemblerID, int shiftID_Shift) + public DateTime AssemblerShiftDate { get; private set; } + + public static AssemblerShift CreateOperation(int id, int workHours, int assemblerID, int shiftID_Shift, DateTime? shiftDate = null) { return new AssemblerShift { ID = id, WorkHours = workHours, AssemblerID_Assembler = assemblerID, - ShiftID_Shift = shiftID_Shift + ShiftID_Shift = shiftID_Shift, + AssemblerShiftDate = shiftDate ?? DateTime.Now }; } } diff --git a/ProjectWorkshop/ProjectWorkshop/Entities/Assembly.cs b/ProjectWorkshop/ProjectWorkshop/Entities/Assembly.cs index a843867..f634168 100644 --- a/ProjectWorkshop/ProjectWorkshop/Entities/Assembly.cs +++ b/ProjectWorkshop/ProjectWorkshop/Entities/Assembly.cs @@ -12,14 +12,30 @@ public class Assembly public IEnumerable ProductAssembly { get; private set; } = []; - public static Assembly CreateOperation(int id, int count, int assemblerID, IEnumerable productAssembly) + public DateTime AssemblyDate { get; private set; } + + public static Assembly CreateOperation(int id, int count, int assemblerID, IEnumerable productAssembly, DateTime? assemblyDate = null) { return new Assembly { ID = id, - Count = count, + Count = count, AssemblerID_Assembler = assemblerID, - ProductAssembly = productAssembly + ProductAssembly = productAssembly, + AssemblyDate = assemblyDate ?? DateTime.Now + }; + } + + + public static Assembly CreateOperation(TempProductAssembly tempProductAssembly, IEnumerable productAssemblies) + { + return new Assembly + { + ID = tempProductAssembly.ID, + Count = tempProductAssembly.Count, + AssemblerID_Assembler = tempProductAssembly.AssemblyID_Assembly, + ProductAssembly = productAssemblies, + AssemblyDate = tempProductAssembly.AssemblyDate }; } } diff --git a/ProjectWorkshop/ProjectWorkshop/Entities/TempProductAssembly.cs b/ProjectWorkshop/ProjectWorkshop/Entities/TempProductAssembly.cs new file mode 100644 index 0000000..50303a4 --- /dev/null +++ b/ProjectWorkshop/ProjectWorkshop/Entities/TempProductAssembly.cs @@ -0,0 +1,21 @@ +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; } +} + \ No newline at end of file diff --git a/ProjectWorkshop/ProjectWorkshop/FormWorkshop.Designer.cs b/ProjectWorkshop/ProjectWorkshop/FormWorkshop.Designer.cs index 4782f7a..8bf422a 100644 --- a/ProjectWorkshop/ProjectWorkshop/FormWorkshop.Designer.cs +++ b/ProjectWorkshop/ProjectWorkshop/FormWorkshop.Designer.cs @@ -37,6 +37,9 @@ AssemblyToolStripMenuItem = new ToolStripMenuItem(); AssemblerShiftToolStripMenuItem = new ToolStripMenuItem(); отчетыToolStripMenuItem = new ToolStripMenuItem(); + DirectoryReportToolStripMenuItem = new ToolStripMenuItem(); + AssembliesReportToolStripMenuItem = new ToolStripMenuItem(); + AssemblyDestributionToolStripMenuItem = new ToolStripMenuItem(); menuStrip.SuspendLayout(); SuspendLayout(); // @@ -46,7 +49,8 @@ menuStrip.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, операцииToolStripMenuItem, отчетыToolStripMenuItem }); menuStrip.Location = new Point(0, 0); menuStrip.Name = "menuStrip"; - menuStrip.Size = new Size(1354, 42); + menuStrip.Padding = new Padding(3, 1, 0, 1); + menuStrip.Size = new Size(729, 24); menuStrip.TabIndex = 0; menuStrip.Text = "menuStrip1"; // @@ -54,27 +58,27 @@ // справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { AssemblersToolStripMenuItem, ShiftsToolStripMenuItem, ProductsToolStripMenuItem }); справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; - справочникиToolStripMenuItem.Size = new Size(184, 38); + справочникиToolStripMenuItem.Size = new Size(94, 22); справочникиToolStripMenuItem.Text = "Справочники"; // // AssemblersToolStripMenuItem // AssemblersToolStripMenuItem.Name = "AssemblersToolStripMenuItem"; - AssemblersToolStripMenuItem.Size = new Size(359, 44); + AssemblersToolStripMenuItem.Size = new Size(134, 22); AssemblersToolStripMenuItem.Text = "Сборщики"; AssemblersToolStripMenuItem.Click += AssemblersToolStripMenuItem_Click; // // ShiftsToolStripMenuItem // ShiftsToolStripMenuItem.Name = "ShiftsToolStripMenuItem"; - ShiftsToolStripMenuItem.Size = new Size(359, 44); + ShiftsToolStripMenuItem.Size = new Size(134, 22); ShiftsToolStripMenuItem.Text = "Смены"; ShiftsToolStripMenuItem.Click += ShiftsToolStripMenuItem_Click; // // ProductsToolStripMenuItem // ProductsToolStripMenuItem.Name = "ProductsToolStripMenuItem"; - ProductsToolStripMenuItem.Size = new Size(359, 44); + ProductsToolStripMenuItem.Size = new Size(134, 22); ProductsToolStripMenuItem.Text = "Изделия"; ProductsToolStripMenuItem.Click += ProductsToolStripMenuItem_Click_1; // @@ -82,38 +86,64 @@ // операцииToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { AssemblyToolStripMenuItem, AssemblerShiftToolStripMenuItem }); операцииToolStripMenuItem.Name = "операцииToolStripMenuItem"; - операцииToolStripMenuItem.Size = new Size(147, 38); + операцииToolStripMenuItem.Size = new Size(75, 22); операцииToolStripMenuItem.Text = "Операции"; // // AssemblyToolStripMenuItem // AssemblyToolStripMenuItem.Name = "AssemblyToolStripMenuItem"; - AssemblyToolStripMenuItem.Size = new Size(330, 44); + AssemblyToolStripMenuItem.Size = new Size(165, 22); AssemblyToolStripMenuItem.Text = "Сборка"; AssemblyToolStripMenuItem.Click += AssemblyToolStripMenuItem_Click; // // AssemblerShiftToolStripMenuItem // AssemblerShiftToolStripMenuItem.Name = "AssemblerShiftToolStripMenuItem"; - AssemblerShiftToolStripMenuItem.Size = new Size(330, 44); + AssemblerShiftToolStripMenuItem.Size = new Size(165, 22); AssemblerShiftToolStripMenuItem.Text = "Выйти на смену "; AssemblerShiftToolStripMenuItem.Click += AssemblerShiftToolStripMenuItem_Click; // // отчетыToolStripMenuItem // + отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { DirectoryReportToolStripMenuItem, AssembliesReportToolStripMenuItem, AssemblyDestributionToolStripMenuItem }); отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem"; - отчетыToolStripMenuItem.Size = new Size(116, 38); + отчетыToolStripMenuItem.Size = new Size(60, 22); отчетыToolStripMenuItem.Text = "Отчеты"; // + // DirectoryReportToolStripMenuItem + // + DirectoryReportToolStripMenuItem.Name = "DirectoryReportToolStripMenuItem"; + DirectoryReportToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.W; + DirectoryReportToolStripMenuItem.Size = new Size(280, 22); + DirectoryReportToolStripMenuItem.Text = "Документ со справочниками"; + DirectoryReportToolStripMenuItem.Click += DirectoryReportToolStripMenuItem_Click; + // + // AssembliesReportToolStripMenuItem + // + AssembliesReportToolStripMenuItem.Name = "AssembliesReportToolStripMenuItem"; + AssembliesReportToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.E; + AssembliesReportToolStripMenuItem.Size = new Size(280, 22); + AssembliesReportToolStripMenuItem.Text = "Отчет по сборкам"; + AssembliesReportToolStripMenuItem.Click += AssembliesReportToolStripMenuItem_Click; + // + // AssemblyDestributionToolStripMenuItem + // + AssemblyDestributionToolStripMenuItem.Name = "AssemblyDestributionToolStripMenuItem"; + AssemblyDestributionToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.P; + AssemblyDestributionToolStripMenuItem.Size = new Size(280, 22); + AssemblyDestributionToolStripMenuItem.Text = "Распределение сборок"; + AssemblyDestributionToolStripMenuItem.Click += AssemblyDestributionToolStripMenuItem_Click; + // // FormWorkshop // - AutoScaleDimensions = new SizeF(13F, 32F); + AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; BackgroundImage = Properties.Resources.цех; BackgroundImageLayout = ImageLayout.Stretch; - ClientSize = new Size(1354, 785); + ClientSize = new Size(729, 368); Controls.Add(menuStrip); MainMenuStrip = menuStrip; + Margin = new Padding(2, 1, 2, 1); Name = "FormWorkshop"; StartPosition = FormStartPosition.CenterScreen; Text = "Цех"; @@ -134,5 +164,8 @@ private ToolStripMenuItem AssemblersToolStripMenuItem; private ToolStripMenuItem ShiftsToolStripMenuItem; private ToolStripMenuItem ProductsToolStripMenuItem; + private ToolStripMenuItem DirectoryReportToolStripMenuItem; + private ToolStripMenuItem AssembliesReportToolStripMenuItem; + private ToolStripMenuItem AssemblyDestributionToolStripMenuItem; } } diff --git a/ProjectWorkshop/ProjectWorkshop/FormWorkshop.cs b/ProjectWorkshop/ProjectWorkshop/FormWorkshop.cs index f6a8c7c..c9c9f4f 100644 --- a/ProjectWorkshop/ProjectWorkshop/FormWorkshop.cs +++ b/ProjectWorkshop/ProjectWorkshop/FormWorkshop.cs @@ -73,5 +73,42 @@ namespace ProjectWorkshop MessageBox.Show(ex.Message, "Ошибка при загрузке", MessageBoxButtons.OK, MessageBoxIcon.Error); } } + + private void DirectoryReportToolStripMenuItem_Click(object sender, EventArgs e) + { + try + { + _container.Resolve().ShowDialog(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка при загрузке", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void AssembliesReportToolStripMenuItem_Click(object sender, EventArgs e) + { + try + { + _container.Resolve().ShowDialog(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка при загрузке", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + + } + + private void AssemblyDestributionToolStripMenuItem_Click(object sender, EventArgs e) + { + try + { + _container.Resolve().ShowDialog(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка при загрузке", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } } } diff --git a/ProjectWorkshop/ProjectWorkshop/Forms/FormAssemblerShift.cs b/ProjectWorkshop/ProjectWorkshop/Forms/FormAssemblerShift.cs index 02c30d3..10943c1 100644 --- a/ProjectWorkshop/ProjectWorkshop/Forms/FormAssemblerShift.cs +++ b/ProjectWorkshop/ProjectWorkshop/Forms/FormAssemblerShift.cs @@ -43,10 +43,14 @@ namespace ProjectWorkshop.Forms throw new Exception("Имеются незаполненные поля"); } + var selectedShift = (dynamic)comboBoxShiftDate.SelectedItem; + DateTime shiftDate = selectedShift.ShiftDate; + var assemblerShift = AssemblerShift.CreateOperation(0, (int)numericUpDownWorkHours.Value, (int)comboBoxAssembler.SelectedValue!, - (int)comboBoxShiftDate.SelectedValue!); + (int)comboBoxShiftDate.SelectedValue!, + shiftDate); _assemblerShiftRepository.CreateAssemblerShift(assemblerShift); @@ -58,6 +62,7 @@ namespace ProjectWorkshop.Forms } } + private void ButtonCancel_Click(object sender, EventArgs e) { Close(); diff --git a/ProjectWorkshop/ProjectWorkshop/Forms/FormAssemblersReport.Designer.cs b/ProjectWorkshop/ProjectWorkshop/Forms/FormAssemblersReport.Designer.cs new file mode 100644 index 0000000..8fd7381 --- /dev/null +++ b/ProjectWorkshop/ProjectWorkshop/Forms/FormAssemblersReport.Designer.cs @@ -0,0 +1,172 @@ +namespace ProjectWorkshop.Forms +{ + partial class FormAssemblersReport + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + 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(); + labelAssembler = new Label(); + comboBoxAssembler = new ComboBox(); + SuspendLayout(); + // + // labelFilePath + // + labelFilePath.AutoSize = true; + labelFilePath.Location = new Point(27, 22); + labelFilePath.Margin = new Padding(2, 0, 2, 0); + labelFilePath.Name = "labelFilePath"; + labelFilePath.Size = new Size(90, 15); + labelFilePath.TabIndex = 0; + labelFilePath.Text = "Путь до файла:"; + // + // labelDateFrom + // + labelDateFrom.AutoSize = true; + labelDateFrom.Location = new Point(27, 94); + labelDateFrom.Margin = new Padding(2, 0, 2, 0); + labelDateFrom.Name = "labelDateFrom"; + labelDateFrom.Size = new Size(77, 15); + labelDateFrom.TabIndex = 1; + labelDateFrom.Text = "Дата начала:"; + // + // dateTimePickerStart + // + dateTimePickerStart.Location = new Point(137, 91); + dateTimePickerStart.Margin = new Padding(2, 1, 2, 1); + dateTimePickerStart.Name = "dateTimePickerStart"; + dateTimePickerStart.Size = new Size(217, 23); + dateTimePickerStart.TabIndex = 2; + // + // textBoxFilePath + // + textBoxFilePath.Location = new Point(137, 22); + textBoxFilePath.Margin = new Padding(2, 1, 2, 1); + textBoxFilePath.Name = "textBoxFilePath"; + textBoxFilePath.Size = new Size(217, 23); + textBoxFilePath.TabIndex = 3; + // + // buttonSelectFilePath + // + buttonSelectFilePath.Location = new Point(356, 22); + buttonSelectFilePath.Margin = new Padding(2, 1, 2, 1); + buttonSelectFilePath.Name = "buttonSelectFilePath"; + buttonSelectFilePath.Size = new Size(23, 18); + buttonSelectFilePath.TabIndex = 4; + buttonSelectFilePath.UseVisualStyleBackColor = true; + buttonSelectFilePath.Click += ButtonSelectFilePath_Click; + // + // buttonBuild + // + buttonBuild.Location = new Point(137, 175); + buttonBuild.Margin = new Padding(2, 1, 2, 1); + buttonBuild.Name = "buttonBuild"; + buttonBuild.Size = new Size(103, 25); + buttonBuild.TabIndex = 5; + buttonBuild.Text = "Сформировать"; + buttonBuild.UseVisualStyleBackColor = true; + buttonBuild.Click += ButtonBuild_Click; + // + // dateTimePickerEnd + // + dateTimePickerEnd.Location = new Point(137, 130); + dateTimePickerEnd.Margin = new Padding(2, 1, 2, 1); + dateTimePickerEnd.Name = "dateTimePickerEnd"; + dateTimePickerEnd.Size = new Size(217, 23); + dateTimePickerEnd.TabIndex = 7; + // + // labelDateTo + // + labelDateTo.AutoSize = true; + labelDateTo.Location = new Point(27, 132); + labelDateTo.Margin = new Padding(2, 0, 2, 0); + labelDateTo.Name = "labelDateTo"; + labelDateTo.Size = new Size(71, 15); + labelDateTo.TabIndex = 6; + labelDateTo.Text = "Дата конца:"; + // + // labelAssembler + // + labelAssembler.AutoSize = true; + labelAssembler.Location = new Point(42, 60); + labelAssembler.Margin = new Padding(2, 0, 2, 0); + labelAssembler.Name = "labelAssembler"; + labelAssembler.Size = new Size(63, 15); + labelAssembler.TabIndex = 8; + labelAssembler.Text = "Сборщик:"; + // + // comboBoxAssembler + // + comboBoxAssembler.FormattingEnabled = true; + comboBoxAssembler.Location = new Point(137, 59); + comboBoxAssembler.Margin = new Padding(2, 1, 2, 1); + comboBoxAssembler.Name = "comboBoxAssembler"; + comboBoxAssembler.Size = new Size(217, 23); + comboBoxAssembler.TabIndex = 9; + // + // FormAssemblersReport + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(431, 211); + Controls.Add(comboBoxAssembler); + Controls.Add(labelAssembler); + Controls.Add(dateTimePickerEnd); + Controls.Add(labelDateTo); + Controls.Add(buttonBuild); + Controls.Add(buttonSelectFilePath); + Controls.Add(textBoxFilePath); + Controls.Add(dateTimePickerStart); + Controls.Add(labelDateFrom); + Controls.Add(labelFilePath); + Margin = new Padding(2, 1, 2, 1); + Name = "FormAssemblersReport"; + 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 labelAssembler; + private ComboBox comboBoxAssembler; + } +} \ No newline at end of file diff --git a/ProjectWorkshop/ProjectWorkshop/Forms/FormAssemblersReport.cs b/ProjectWorkshop/ProjectWorkshop/Forms/FormAssemblersReport.cs new file mode 100644 index 0000000..ae893d0 --- /dev/null +++ b/ProjectWorkshop/ProjectWorkshop/Forms/FormAssemblersReport.cs @@ -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 FormAssemblersReport : Form + { + private readonly IUnityContainer _container; + public FormAssemblersReport(IUnityContainer container, IAssemblerRepository assemblerRepository) + { + InitializeComponent(); + _container = container ?? throw new ArgumentNullException(nameof(container)); + + comboBoxAssembler.DataSource = assemblerRepository.ReadAssemblers(); + comboBoxAssembler.DisplayMember = "Name"; + comboBoxAssembler.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 (comboBoxAssembler.SelectedIndex < 0) + { + throw new Exception("Не выбран сборщик"); + } + + if (_container.Resolve().CreateTable(textBoxFilePath.Text, (int)comboBoxAssembler.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); + } + } + } +} diff --git a/ProjectWorkshop/ProjectWorkshop/Forms/FormAssemblersReport.resx b/ProjectWorkshop/ProjectWorkshop/Forms/FormAssemblersReport.resx new file mode 100644 index 0000000..8b2ff64 --- /dev/null +++ b/ProjectWorkshop/ProjectWorkshop/Forms/FormAssemblersReport.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/ProjectWorkshop/ProjectWorkshop/Forms/FormAssembly.Designer.cs b/ProjectWorkshop/ProjectWorkshop/Forms/FormAssembly.Designer.cs index f58fa09..7299601 100644 --- a/ProjectWorkshop/ProjectWorkshop/Forms/FormAssembly.Designer.cs +++ b/ProjectWorkshop/ProjectWorkshop/Forms/FormAssembly.Designer.cs @@ -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; } } \ No newline at end of file diff --git a/ProjectWorkshop/ProjectWorkshop/Forms/FormAssembly.cs b/ProjectWorkshop/ProjectWorkshop/Forms/FormAssembly.cs index 954eab9..d0aecf4 100644 --- a/ProjectWorkshop/ProjectWorkshop/Forms/FormAssembly.cs +++ b/ProjectWorkshop/ProjectWorkshop/Forms/FormAssembly.cs @@ -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(); diff --git a/ProjectWorkshop/ProjectWorkshop/Forms/FormAssembly.resx b/ProjectWorkshop/ProjectWorkshop/Forms/FormAssembly.resx index 4c1a834..03b2936 100644 --- a/ProjectWorkshop/ProjectWorkshop/Forms/FormAssembly.resx +++ b/ProjectWorkshop/ProjectWorkshop/Forms/FormAssembly.resx @@ -123,10 +123,4 @@ True - - True - - - True - \ No newline at end of file diff --git a/ProjectWorkshop/ProjectWorkshop/Forms/FormAssemblyDistributionReport.Designer.cs b/ProjectWorkshop/ProjectWorkshop/Forms/FormAssemblyDistributionReport.Designer.cs new file mode 100644 index 0000000..d6a74bf --- /dev/null +++ b/ProjectWorkshop/ProjectWorkshop/Forms/FormAssemblyDistributionReport.Designer.cs @@ -0,0 +1,107 @@ +namespace ProjectWorkshop.Forms +{ + partial class FormAssemblyDistributionReport + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + buttonSelectFileName = new Button(); + labelFileName = new Label(); + labelDate = new Label(); + dateTimePickerDate = new DateTimePicker(); + buttonCreate = new Button(); + SuspendLayout(); + // + // buttonSelectFileName + // + buttonSelectFileName.Location = new Point(37, 29); + buttonSelectFileName.Name = "buttonSelectFileName"; + buttonSelectFileName.Size = new Size(75, 23); + buttonSelectFileName.TabIndex = 0; + buttonSelectFileName.Text = "Выбрать"; + buttonSelectFileName.UseVisualStyleBackColor = true; + buttonSelectFileName.Click += ButtonSelectFileName_Click; + // + // labelFileName + // + labelFileName.AutoSize = true; + labelFileName.Location = new Point(132, 33); + labelFileName.Name = "labelFileName"; + labelFileName.Size = new Size(36, 15); + labelFileName.TabIndex = 1; + labelFileName.Text = "Файл"; + // + // labelDate + // + labelDate.AutoSize = true; + labelDate.Location = new Point(37, 83); + labelDate.Name = "labelDate"; + labelDate.Size = new Size(35, 15); + labelDate.TabIndex = 2; + labelDate.Text = "Дата:"; + // + // dateTimePickerDate + // + dateTimePickerDate.Location = new Point(89, 77); + dateTimePickerDate.Name = "dateTimePickerDate"; + dateTimePickerDate.Size = new Size(200, 23); + dateTimePickerDate.TabIndex = 3; + // + // buttonCreate + // + buttonCreate.Location = new Point(105, 141); + buttonCreate.Name = "buttonCreate"; + buttonCreate.Size = new Size(110, 23); + buttonCreate.TabIndex = 4; + buttonCreate.Text = "Сформировать"; + buttonCreate.UseVisualStyleBackColor = true; + buttonCreate.Click += ButtonCreate_Click; + // + // FormAssemblyDistributionReport + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(333, 193); + Controls.Add(buttonCreate); + Controls.Add(dateTimePickerDate); + Controls.Add(labelDate); + Controls.Add(labelFileName); + Controls.Add(buttonSelectFileName); + Name = "FormAssemblyDistributionReport"; + Text = "Распределение сборок"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Button buttonSelectFileName; + private Label labelFileName; + private Label labelDate; + private DateTimePicker dateTimePickerDate; + private Button buttonCreate; + } +} \ No newline at end of file diff --git a/ProjectWorkshop/ProjectWorkshop/Forms/FormAssemblyDistributionReport.cs b/ProjectWorkshop/ProjectWorkshop/Forms/FormAssemblyDistributionReport.cs new file mode 100644 index 0000000..0882477 --- /dev/null +++ b/ProjectWorkshop/ProjectWorkshop/Forms/FormAssemblyDistributionReport.cs @@ -0,0 +1,71 @@ +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 FormAssemblyDistributionReport : Form + { + + private string _fileName = string.Empty; + private readonly IUnityContainer _container; + + public FormAssemblyDistributionReport(IUnityContainer container) + { + InitializeComponent(); + _container = container ?? + throw new ArgumentNullException(nameof(container)); + } + + private void ButtonSelectFileName_Click(object sender, EventArgs e) + { + var sfd = new SaveFileDialog() + { + Filter = "Pdf Files | *.pdf" + }; + if (sfd.ShowDialog() == DialogResult.OK) + { + _fileName = sfd.FileName; + labelFileName.Text = Path.GetFileName(_fileName); + } + } + + private void ButtonCreate_Click(object sender, EventArgs e) + { + try + { + if (string.IsNullOrWhiteSpace(_fileName)) + { + throw new Exception("Отсутствует имя файла для отчета"); + } + if + (_container.Resolve().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); + } + } + } +} diff --git a/ProjectWorkshop/ProjectWorkshop/Forms/FormAssemblyDistributionReport.resx b/ProjectWorkshop/ProjectWorkshop/Forms/FormAssemblyDistributionReport.resx new file mode 100644 index 0000000..8b2ff64 --- /dev/null +++ b/ProjectWorkshop/ProjectWorkshop/Forms/FormAssemblyDistributionReport.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/ProjectWorkshop/ProjectWorkshop/Forms/FormDirectoryReport.Designer.cs b/ProjectWorkshop/ProjectWorkshop/Forms/FormDirectoryReport.Designer.cs new file mode 100644 index 0000000..2c091fa --- /dev/null +++ b/ProjectWorkshop/ProjectWorkshop/Forms/FormDirectoryReport.Designer.cs @@ -0,0 +1,99 @@ +namespace ProjectWorkshop.Forms +{ + partial class FormDirectoryReport + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + 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; + } +} \ No newline at end of file diff --git a/ProjectWorkshop/ProjectWorkshop/Forms/FormDirectoryReport.cs b/ProjectWorkshop/ProjectWorkshop/Forms/FormDirectoryReport.cs new file mode 100644 index 0000000..daeb71c --- /dev/null +++ b/ProjectWorkshop/ProjectWorkshop/Forms/FormDirectoryReport.cs @@ -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().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); + } + } + } +} diff --git a/ProjectWorkshop/ProjectWorkshop/Forms/FormDirectoryReport.resx b/ProjectWorkshop/ProjectWorkshop/Forms/FormDirectoryReport.resx new file mode 100644 index 0000000..8b2ff64 --- /dev/null +++ b/ProjectWorkshop/ProjectWorkshop/Forms/FormDirectoryReport.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/ProjectWorkshop/ProjectWorkshop/ProjectWorkshop.csproj b/ProjectWorkshop/ProjectWorkshop/ProjectWorkshop.csproj index c42d821..d018469 100644 --- a/ProjectWorkshop/ProjectWorkshop/ProjectWorkshop.csproj +++ b/ProjectWorkshop/ProjectWorkshop/ProjectWorkshop.csproj @@ -10,11 +10,13 @@ + + diff --git a/ProjectWorkshop/ProjectWorkshop/Reports/ChartReport.cs b/ProjectWorkshop/ProjectWorkshop/Reports/ChartReport.cs new file mode 100644 index 0000000..fc1e7ca --- /dev/null +++ b/ProjectWorkshop/ProjectWorkshop/Reports/ChartReport.cs @@ -0,0 +1,68 @@ +using Microsoft.Extensions.Logging; +using ProjectWorkshop.Repositories; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace ProjectWorkshop.Reports +{ + internal class ChartReport + { + private readonly IAssemblyRepository _assemblyRepository; + private readonly IAssemblerRepository _assemblerRepository; + private readonly ILogger _logger; + + public ChartReport(IAssemblyRepository assemblyRepository, IAssemblerRepository assemblerRepository, ILogger logger) + { + _assemblyRepository = assemblyRepository ?? + throw new ArgumentNullException(nameof(assemblyRepository)); + _assemblerRepository = assemblerRepository ?? + throw new ArgumentNullException(nameof(assemblerRepository)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + public bool CreateChart(string filePath, DateTime dateTime) + { + try + { + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + + var data = GetData(dateTime); + + new PdfBuilder(filePath) + .AddHeader("Сборки изделий") + .AddPieChart("Количество сборок по сборщикам", data) + .Build(); + + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при формировании документа"); + return false; + } + } + + private List<(string Caption, double Value)> GetData(DateTime dateTime) + { + var assemblies = _assemblyRepository + .ReadAssemblies() + .Where(x => x.AssemblyDate.Date == dateTime.Date) + .GroupBy(x => x.AssemblerID_Assembler) + .Select(group => new + { + AssemblerId = group.Key, + AssemblyCount = group.Count() + }) + .ToList(); + + var assemblerNames = _assemblerRepository.ReadAssemblers() + .ToDictionary(a => a.ID, a => a.FullName); + + return assemblies + .Select(x => (assemblerNames.ContainsKey(x.AssemblerId) ? assemblerNames[x.AssemblerId] : $"Сборщик {x.AssemblerId}", (double)x.AssemblyCount)) + .ToList(); + } + } +} diff --git a/ProjectWorkshop/ProjectWorkshop/Reports/DocReport.cs b/ProjectWorkshop/ProjectWorkshop/Reports/DocReport.cs new file mode 100644 index 0000000..a8776cd --- /dev/null +++ b/ProjectWorkshop/ProjectWorkshop/Reports/DocReport.cs @@ -0,0 +1,84 @@ +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 _logger; + + public DocReport(IAssemblerRepository assemblerRepository, IProductRepository productRepository, IShiftRepository shiftRepository, ILogger 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 GetProducts() + { + return [ + ["Название изделия", "Стоимость", "Дата сборки"], + .. _productRepository + .ReadProducts() + .Select(x => new string[] { x.ProductName, x.Price.ToString(), x.ProductType.ToString()}), + ]; + } + + + private List GetAssemblers() + { + return [ + ["ФИО Сборщика", "Разряд", "Стаж работы"], + .. _assemblerRepository + .ReadAssemblers() + .Select(x => new string[] { x.FullName, x.AssemblerRank.ToString(), x.WorkExperience.ToString() }), + ]; + } + + private List GetShifts() + { + return [ + ["Дата выхода на смену"], + .. _shiftRepository + .ReadShifts() + .Select(x => new string[] { x.ShiftDate.ToString()}), + ]; + } +} diff --git a/ProjectWorkshop/ProjectWorkshop/Reports/ExcelBuilder.cs b/ProjectWorkshop/ProjectWorkshop/Reports/ExcelBuilder.cs new file mode 100644 index 0000000..61b2ead --- /dev/null +++ b/ProjectWorkshop/ProjectWorkshop/Reports/ExcelBuilder.cs @@ -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 ProjectLibrary.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 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.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().First()); + } + } + + private static void GenerateStyle(WorkbookPart workbookPart) + { + var workbookStylesPart = workbookPart.AddNewPart(); + 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.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.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.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().FirstOrDefault(r => r.RowIndex! == rowIndex); + if (row == null) + { + row = new Row() { RowIndex = rowIndex }; + _sheetData.Append(row); + } + var newCell = row.Elements().FirstOrDefault(c => c.CellReference != null && + c.CellReference.Value == columnName + rowIndex); + if (newCell == null) + { + Cell? refCell = null; + foreach (Cell cell in row.Elements()) + { + 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; + } +} diff --git a/ProjectWorkshop/ProjectWorkshop/Reports/PdfBuilder.cs b/ProjectWorkshop/ProjectWorkshop/Reports/PdfBuilder.cs new file mode 100644 index 0000000..2fc920f --- /dev/null +++ b/ProjectWorkshop/ProjectWorkshop/Reports/PdfBuilder.cs @@ -0,0 +1,71 @@ +using MigraDoc.DocumentObjectModel; +using MigraDoc.DocumentObjectModel.Shapes.Charts; +using MigraDoc.Rendering; + +namespace ProjectWorkshop.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() + { + 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; + } +} diff --git a/ProjectWorkshop/ProjectWorkshop/Reports/TableReport.cs b/ProjectWorkshop/ProjectWorkshop/Reports/TableReport.cs new file mode 100644 index 0000000..1b8e919 --- /dev/null +++ b/ProjectWorkshop/ProjectWorkshop/Reports/TableReport.cs @@ -0,0 +1,124 @@ +using Microsoft.Extensions.Logging; +using ProjectLibrary.Reports; +using ProjectWorkshop.Repositories; +using ProjectWorkshop.Repositories.Implementations; +using System; +using System.Collections.Generic; +using System.Linq; + +namespace ProjectWorkshop.Reports +{ + internal class TableReport + { + private readonly IAssemblerRepository _assemblerRepository; + private readonly IAssemblerShiftRepository _assemblerShiftRepository; + private readonly IAssemblyRepository _assemblyRepository; + private readonly ILogger _logger; + + internal static readonly string[] Headers = { "Сборщик", "Стаж", "Разряд", "Кол-во сборок", "Собрано изделий", "Смены" }; + + public TableReport(IAssemblerRepository assemblerRepository, + IAssemblerShiftRepository assemblerShiftRepository, + ILogger logger, + IAssemblyRepository assemblyRepository) + { + _assemblerRepository = assemblerRepository ?? throw new ArgumentNullException(nameof(assemblerRepository)); + _assemblerShiftRepository = assemblerShiftRepository ?? throw new ArgumentNullException(nameof(assemblerShiftRepository)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _assemblyRepository = assemblyRepository ?? throw new ArgumentNullException(nameof(assemblyRepository)); + } + + 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[] { 25, 15, 15, 20, 20, 20 }, data) + .Build(); + + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при формировании документа"); + return false; + } + } + + private List GetData(int assemblerID, DateTime startDate, DateTime endDate) + { + var assembler = _assemblerRepository.ReadAssemblers().FirstOrDefault(a => a.ID == assemblerID); + if (assembler == null) + throw new Exception($"Сборщик с ID {assemblerID} не найден."); + + var shiftData = _assemblerShiftRepository + .ReadAssemblerShifts() + .Where(x => x.AssemblerShiftDate >= startDate && x.AssemblerShiftDate <= endDate && x.AssemblerID_Assembler == assemblerID) + .OrderBy(x => x.AssemblerShiftDate) + .ToList(); + + var result = new List + { + Headers + }; + + int totalAssemblies = 0; + int totalProducts = 0; + + foreach (var shift in shiftData) + { + var assemblyDataForDay = _assemblyRepository + .ReadAssemblies() + .Where(x => x.AssemblyDate.Date == shift.AssemblerShiftDate.Date && x.AssemblerID_Assembler == assemblerID) + .ToList(); + + int totalAssembliesForDay = assemblyDataForDay.Count(); + int totalProductsForDay = assemblyDataForDay.Sum(x => x.Count); + + result.Add(new[] + { + assembler.FullName, + assembler.WorkExperience.ToString("F"), + assembler.AssemblerRank.ToString("G"), + totalAssembliesForDay.ToString("N0"), + totalProductsForDay.ToString("N0"), + shift.AssemblerShiftDate.ToString("dd.MM.yyyy") + }); + + totalAssemblies += totalAssembliesForDay; + totalProducts += totalProductsForDay; + } + + if (!shiftData.Any()) + { + result.Add(new[] + { + assembler.FullName, + assembler.WorkExperience.ToString("F"), + assembler.AssemblerRank.ToString("G"), + "0", + "0", + "Нет смен" + }); + } + + result.Add(new[] + { + "ИТОГО", + "", + "", + totalAssemblies.ToString("N0"), + totalProducts.ToString("N0"), + "" + }); + + return result; + } + + } +} + diff --git a/ProjectWorkshop/ProjectWorkshop/Reports/WordBuilder.cs b/ProjectWorkshop/ProjectWorkshop/Reports/WordBuilder.cs new file mode 100644 index 0000000..58ee803 --- /dev/null +++ b/ProjectWorkshop/ProjectWorkshop/Reports/WordBuilder.cs @@ -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 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.Single), Size = 12 }, + new BottomBorder() { Val = new EnumValue(BorderValues.Single), Size = 12 }, + new LeftBorder() { Val = new EnumValue(BorderValues.Single), Size = 12 }, + new RightBorder() { Val = new EnumValue(BorderValues.Single), Size = 12 }, + new InsideHorizontalBorder() { Val = new EnumValue(BorderValues.Single), Size = 12 }, + new InsideVerticalBorder() { Val = new EnumValue(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; + } + +} diff --git a/ProjectWorkshop/ProjectWorkshop/Repositories/IAssemblyRepository.cs b/ProjectWorkshop/ProjectWorkshop/Repositories/IAssemblyRepository.cs index fb61dce..93f082c 100644 --- a/ProjectWorkshop/ProjectWorkshop/Repositories/IAssemblyRepository.cs +++ b/ProjectWorkshop/ProjectWorkshop/Repositories/IAssemblyRepository.cs @@ -3,7 +3,7 @@ namespace ProjectWorkshop.Repositories; public interface IAssemblyRepository { - IEnumerable ReadAssemblies(int? productID = null, int? assemblyID = null, int? count = null); + IEnumerable ReadAssemblies(DateTime? dateFrom = null, DateTime? dateTo = null, int? productID = null, int? assemblyID = null, int? count = null); void CreateAssembly(Assembly assembly); diff --git a/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/AssemblerShiftRepository.cs b/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/AssemblerShiftRepository.cs index c53bab3..78667ea 100644 --- a/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/AssemblerShiftRepository.cs +++ b/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/AssemblerShiftRepository.cs @@ -28,8 +28,8 @@ public class AssemblerShiftRepository : IAssemblerShiftRepository { using var connection = new NpgsqlConnection(_connectionString.ConnectionString); var queryInsert = @" - INSERT INTO AssemblerShift (WorkHours, AssemblerID_Assembler, ShiftID_Shift) - VALUES (@WorkHours, @AssemblerID_Assembler, @ShiftID_Shift)"; + INSERT INTO AssemblerShift (WorkHours, AssemblerID_Assembler, ShiftID_Shift, AssemblerShiftDate) + VALUES (@WorkHours, @AssemblerID_Assembler, @ShiftID_Shift, @AssemblerShiftDate)"; connection.Execute(queryInsert, assemblerShift); } catch (Exception ex) diff --git a/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/AssemblyRepository.cs b/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/AssemblyRepository.cs index abc33b7..4e1a799 100644 --- a/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/AssemblyRepository.cs +++ b/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/AssemblyRepository.cs @@ -33,18 +33,19 @@ public class AssemblyRepository : IAssemblyRepository 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(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 +66,7 @@ public class AssemblyRepository : IAssemblyRepository } } + public void DeleteAssembly(int id) { _logger.LogInformation("Удаление объекта"); @@ -84,16 +86,15 @@ public class AssemblyRepository : IAssemblyRepository } } - public IEnumerable ReadAssemblies(int? id = null, int? assemblyID = null, int? count = null) + public IEnumerable 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(querySelect); - _logger.LogDebug("Полученные объекты: {json}", - JsonConvert.SerializeObject(assemblies)); + var selectQuery = @"SELECT * FROM Assembly"; + var assemblies = connection.Query(selectQuery); + _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(assemblies)); return assemblies; } catch (Exception ex) @@ -103,21 +104,4 @@ public class AssemblyRepository : IAssemblyRepository } } - public IEnumerable GetAssemblers() - { - _logger.LogInformation("Получение всех сборщиков"); - try - { - using var connection = new NpgsqlConnection(_connectionString.ConnectionString); - var query = "SELECT ID, Name FROM Assembler"; - var assemblers = connection.Query(query); - _logger.LogDebug("Полученные сборщики: {json}", JsonConvert.SerializeObject(assemblers)); - return assemblers; - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка при получении сборщиков"); - throw; - } - } } diff --git a/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/ProductRepository.cs b/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/ProductRepository.cs index 40a0942..fb2a04b 100644 --- a/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/ProductRepository.cs +++ b/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/ProductRepository.cs @@ -31,7 +31,7 @@ public class ProductRepository : IProductRepository using var connection = new NpgsqlConnection(_connectionString.ConnectionString); var queryInsert = @" INSERT INTO Product (ProductName, Price, ProductType) - VALUES (@ProductName, @Price, @ProductType) + VALUES (@ProductName, @Price, @ProductType) RETURNING ID"; connection.Execute(queryInsert, product); }