diff --git a/ProjectWorkshop/ProjectWorkshop/Entities/AssemblerShift.cs b/ProjectWorkshop/ProjectWorkshop/Entities/AssemblerShift.cs index 2f418a9..6b4dcd3 100644 --- a/ProjectWorkshop/ProjectWorkshop/Entities/AssemblerShift.cs +++ b/ProjectWorkshop/ProjectWorkshop/Entities/AssemblerShift.cs @@ -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 }; } } diff --git a/ProjectWorkshop/ProjectWorkshop/Entities/Assembly.cs b/ProjectWorkshop/ProjectWorkshop/Entities/Assembly.cs index a843867..cb66179 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, 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/Product.cs b/ProjectWorkshop/ProjectWorkshop/Entities/Product.cs index 38e90ad..923aef5 100644 --- a/ProjectWorkshop/ProjectWorkshop/Entities/Product.cs +++ b/ProjectWorkshop/ProjectWorkshop/Entities/Product.cs @@ -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 }; } } diff --git a/ProjectWorkshop/ProjectWorkshop/Entities/TempProductAssembly.cs b/ProjectWorkshop/ProjectWorkshop/Entities/TempProductAssembly.cs new file mode 100644 index 0000000..62b9990 --- /dev/null +++ b/ProjectWorkshop/ProjectWorkshop/Entities/TempProductAssembly.cs @@ -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; } +} diff --git a/ProjectWorkshop/ProjectWorkshop/FormWorkshop.Designer.cs b/ProjectWorkshop/ProjectWorkshop/FormWorkshop.Designer.cs index 4782f7a..8bbf9da 100644 --- a/ProjectWorkshop/ProjectWorkshop/FormWorkshop.Designer.cs +++ b/ProjectWorkshop/ProjectWorkshop/FormWorkshop.Designer.cs @@ -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; } } diff --git a/ProjectWorkshop/ProjectWorkshop/FormWorkshop.cs b/ProjectWorkshop/ProjectWorkshop/FormWorkshop.cs index f6a8c7c..7cf1233 100644 --- a/ProjectWorkshop/ProjectWorkshop/FormWorkshop.cs +++ b/ProjectWorkshop/ProjectWorkshop/FormWorkshop.cs @@ -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().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); + } + + } } } diff --git a/ProjectWorkshop/ProjectWorkshop/Forms/FormAssembliesReport.Designer.cs b/ProjectWorkshop/ProjectWorkshop/Forms/FormAssembliesReport.Designer.cs new file mode 100644 index 0000000..f0b6bf4 --- /dev/null +++ b/ProjectWorkshop/ProjectWorkshop/Forms/FormAssembliesReport.Designer.cs @@ -0,0 +1,161 @@ +namespace ProjectWorkshop.Forms +{ + partial class FormAssembliesReport + { + /// + /// 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(); + 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; + } +} \ No newline at end of file diff --git a/ProjectWorkshop/ProjectWorkshop/Forms/FormAssembliesReport.cs b/ProjectWorkshop/ProjectWorkshop/Forms/FormAssembliesReport.cs new file mode 100644 index 0000000..284f7db --- /dev/null +++ b/ProjectWorkshop/ProjectWorkshop/Forms/FormAssembliesReport.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 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().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); + } + } + } +} diff --git a/ProjectWorkshop/ProjectWorkshop/Forms/FormAssembliesReport.resx b/ProjectWorkshop/ProjectWorkshop/Forms/FormAssembliesReport.resx new file mode 100644 index 0000000..8b2ff64 --- /dev/null +++ b/ProjectWorkshop/ProjectWorkshop/Forms/FormAssembliesReport.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..2c8da3e 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(); @@ -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(); } } } 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/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..6b717ad 100644 --- a/ProjectWorkshop/ProjectWorkshop/ProjectWorkshop.csproj +++ b/ProjectWorkshop/ProjectWorkshop/ProjectWorkshop.csproj @@ -10,6 +10,7 @@ + diff --git a/ProjectWorkshop/ProjectWorkshop/Reports/DocReport.cs b/ProjectWorkshop/ProjectWorkshop/Reports/DocReport.cs new file mode 100644 index 0000000..209192a --- /dev/null +++ b/ProjectWorkshop/ProjectWorkshop/Reports/DocReport.cs @@ -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 _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()}), + ]; + } + + 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..3c05ab2 --- /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 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 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/TableReport.cs b/ProjectWorkshop/ProjectWorkshop/Reports/TableReport.cs new file mode 100644 index 0000000..f62f7e0 --- /dev/null +++ b/ProjectWorkshop/ProjectWorkshop/Reports/TableReport.cs @@ -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 _logger; + + internal static readonly string[] Headers = { "Дата", "Описание", "Количество сборок", "Количество часов смен" }; + + public TableReport(IAssemblyRepository assemblyRepository, + IAssemblerShiftRepository assemblerShiftRepository, + ILogger 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 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 { Headers } + .Union(combinedData.Select(x => new[] + { + x.Date.ToString("dd.MM.yyyy"), + x.Description, + x.CountAssemblies, + x.WorkHours + })) + .Union(new List { new[] { "Всего", "", totalAssemblies.ToString("N0"), totalWorkHours.ToString("N0") } }) + .ToList(); + } +} + + + 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/AssemblyRepository.cs b/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/AssemblyRepository.cs index abc33b7..5c751bd 100644 --- a/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/AssemblyRepository.cs +++ b/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/AssemblyRepository.cs @@ -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(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 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); + 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(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 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 c8f7af1..fb2a04b 100644 --- a/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/ProductRepository.cs +++ b/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/ProductRepository.cs @@ -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); }