diff --git a/ProjectWarehouse/ProjectWarehouse/Entities/Components_Production.cs b/ProjectWarehouse/ProjectWarehouse/Entities/Components_Production.cs index 8c7bd1d..d9c4219 100644 --- a/ProjectWarehouse/ProjectWarehouse/Entities/Components_Production.cs +++ b/ProjectWarehouse/ProjectWarehouse/Entities/Components_Production.cs @@ -4,6 +4,8 @@ public class Components_Production { public int Id { get; set; } + public int ProductionId { get; private set; } + public int ComponentsId { get; private set; } public int Count { get; private set; } @@ -13,6 +15,7 @@ public class Components_Production return new Components_Production { Id = id, + ProductionId = componentsID, ComponentsId = componentsID, Count = count }; diff --git a/ProjectWarehouse/ProjectWarehouse/Entities/Inventory.cs b/ProjectWarehouse/ProjectWarehouse/Entities/Inventory.cs index 9d3e519..538727b 100644 --- a/ProjectWarehouse/ProjectWarehouse/Entities/Inventory.cs +++ b/ProjectWarehouse/ProjectWarehouse/Entities/Inventory.cs @@ -10,6 +10,8 @@ public class Inventory public int ComponentsId { get; private set; } + public DateTime Date { get; set; } + public static Inventory CreateEntity(int id, double quantity, bool isDefect, int ComponentsID) { return new Inventory @@ -17,6 +19,7 @@ public class Inventory Id = id, Quantity = quantity, IsDefect = isDefect, + Date = DateTime.Now, ComponentsId = ComponentsID }; } diff --git a/ProjectWarehouse/ProjectWarehouse/Entities/OrderRequest.cs b/ProjectWarehouse/ProjectWarehouse/Entities/OrderRequest.cs index 91aa390..976e02a 100644 --- a/ProjectWarehouse/ProjectWarehouse/Entities/OrderRequest.cs +++ b/ProjectWarehouse/ProjectWarehouse/Entities/OrderRequest.cs @@ -8,7 +8,7 @@ public class OrderRequest public DateTime DateOrder { get; private set; } - public int ComponentsID { get; private set; } + public int ComponentsId { get; private set; } public static OrderRequest CreateEntity(int id, double quantity, int componentsID) { @@ -17,7 +17,7 @@ public class OrderRequest Id = id, Quantity = quantity, DateOrder = DateTime.Now, - ComponentsID = componentsID + ComponentsId = componentsID }; } } diff --git a/ProjectWarehouse/ProjectWarehouse/Entities/Production.cs b/ProjectWarehouse/ProjectWarehouse/Entities/Production.cs index 1d2c877..d67de7f 100644 --- a/ProjectWarehouse/ProjectWarehouse/Entities/Production.cs +++ b/ProjectWarehouse/ProjectWarehouse/Entities/Production.cs @@ -10,9 +10,11 @@ public class Production public int EmployeeId { get; private set; } + public DateTime Date { get; set; } + public IEnumerable Components_Productions { get; private set; } = []; - public static Production CreateEntity(int id, string name, string description, int employeeId, IEnumerable components_Productions) + public static Production CreateEntity(int id, string name, string description, int employeeId, IEnumerable components_Productions) { return new Production { @@ -20,6 +22,17 @@ public class Production Name = name, Description = description ?? string.Empty, EmployeeId = employeeId, + Date = DateTime.Now, + Components_Productions = components_Productions + }; + } + + public static Production CreateEntity(TempComponents_Production tempComponents_Production, IEnumerable components_Productions) + { + return new Production + { + Id = tempComponents_Production.Id, + Date = tempComponents_Production.Date, Components_Productions = components_Productions }; } diff --git a/ProjectWarehouse/ProjectWarehouse/Entities/TempComponents_Production.cs b/ProjectWarehouse/ProjectWarehouse/Entities/TempComponents_Production.cs new file mode 100644 index 0000000..0a70c97 --- /dev/null +++ b/ProjectWarehouse/ProjectWarehouse/Entities/TempComponents_Production.cs @@ -0,0 +1,12 @@ +namespace ProjectWarehouse.Entities; + +public class TempComponents_Production +{ + public int Id { get; private set; } + + public DateTime Date { get; private set; } + + public int ComponentsId { get; private set; } + + public int Count { get; private set; } +} diff --git a/ProjectWarehouse/ProjectWarehouse/FormWarehouse.Designer.cs b/ProjectWarehouse/ProjectWarehouse/FormWarehouse.Designer.cs index 8373b15..856c7b1 100644 --- a/ProjectWarehouse/ProjectWarehouse/FormWarehouse.Designer.cs +++ b/ProjectWarehouse/ProjectWarehouse/FormWarehouse.Designer.cs @@ -35,14 +35,18 @@ операцииToolStripMenuItem = new ToolStripMenuItem(); InventoryToolStripMenuItem = new ToolStripMenuItem(); Components_ProductionToolStripMenuItem = new ToolStripMenuItem(); - заявкиToolStripMenuItem = new ToolStripMenuItem(); + OrderRequestToolStripMenuItem = new ToolStripMenuItem(); + отчетыToolStripMenuItem = new ToolStripMenuItem(); + DirectoryReportToolStripMenuItem = new ToolStripMenuItem(); + componentReportToolStripMenuItem = new ToolStripMenuItem(); + componentsDistributionToolStripMenuItem = new ToolStripMenuItem(); menuStrip.SuspendLayout(); SuspendLayout(); // // menuStrip // menuStrip.ImageScalingSize = new Size(20, 20); - menuStrip.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, операцииToolStripMenuItem, заявкиToolStripMenuItem }); + menuStrip.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, операцииToolStripMenuItem, отчетыToolStripMenuItem }); menuStrip.Location = new Point(0, 0); menuStrip.Name = "menuStrip"; menuStrip.Size = new Size(784, 24); @@ -59,20 +63,20 @@ // ComponentToolStripMenuItem // ComponentToolStripMenuItem.Name = "ComponentToolStripMenuItem"; - ComponentToolStripMenuItem.Size = new Size(180, 22); + ComponentToolStripMenuItem.Size = new Size(168, 22); ComponentToolStripMenuItem.Text = "Комплектующие"; ComponentToolStripMenuItem.Click += ComponentToolStripMenuItem_Click; // // EmployeeToolStripMenuItem // EmployeeToolStripMenuItem.Name = "EmployeeToolStripMenuItem"; - EmployeeToolStripMenuItem.Size = new Size(180, 22); + EmployeeToolStripMenuItem.Size = new Size(168, 22); EmployeeToolStripMenuItem.Text = "Работники"; EmployeeToolStripMenuItem.Click += EmployeeToolStripMenuItem_Click; // // операцииToolStripMenuItem // - операцииToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { InventoryToolStripMenuItem, Components_ProductionToolStripMenuItem }); + операцииToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { InventoryToolStripMenuItem, Components_ProductionToolStripMenuItem, OrderRequestToolStripMenuItem }); операцииToolStripMenuItem.Name = "операцииToolStripMenuItem"; операцииToolStripMenuItem.Size = new Size(75, 20); операцииToolStripMenuItem.Text = "Операции"; @@ -91,12 +95,43 @@ Components_ProductionToolStripMenuItem.Text = "Добавление продукции"; Components_ProductionToolStripMenuItem.Click += Components_ProductionToolStripMenuItem_Click; // - // заявкиToolStripMenuItem + // OrderRequestToolStripMenuItem // - заявкиToolStripMenuItem.Name = "заявкиToolStripMenuItem"; - заявкиToolStripMenuItem.Size = new Size(57, 20); - заявкиToolStripMenuItem.Text = "Заявки"; - заявкиToolStripMenuItem.Click += OrderRequestToolStripMenuItem_Click; + OrderRequestToolStripMenuItem.Name = "OrderRequestToolStripMenuItem"; + OrderRequestToolStripMenuItem.Size = new Size(204, 22); + OrderRequestToolStripMenuItem.Text = "Формирование заявки"; + OrderRequestToolStripMenuItem.Click += OrderRequestToolStripMenuItem_Click; + // + // отчетыToolStripMenuItem + // + отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { DirectoryReportToolStripMenuItem, componentReportToolStripMenuItem, componentsDistributionToolStripMenuItem }); + отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem"; + отчетыToolStripMenuItem.Size = new Size(60, 20); + отчетыToolStripMenuItem.Text = "Отчеты"; + // + // DirectoryReportToolStripMenuItem + // + DirectoryReportToolStripMenuItem.Name = "DirectoryReportToolStripMenuItem"; + DirectoryReportToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.W; + DirectoryReportToolStripMenuItem.Size = new Size(280, 22); + DirectoryReportToolStripMenuItem.Text = "Документ со справочниками"; + DirectoryReportToolStripMenuItem.Click += DirectoryReportToolStripMenuItem_Click; + // + // componentReportToolStripMenuItem + // + componentReportToolStripMenuItem.Name = "componentReportToolStripMenuItem"; + componentReportToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.E; + componentReportToolStripMenuItem.Size = new Size(280, 22); + componentReportToolStripMenuItem.Text = "Движение компонентов"; + componentReportToolStripMenuItem.Click += ComponentReportToolStripMenuItem_Click; + // + // componentsDistributionToolStripMenuItem + // + componentsDistributionToolStripMenuItem.Name = "componentsDistributionToolStripMenuItem"; + componentsDistributionToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.P; + componentsDistributionToolStripMenuItem.Size = new Size(280, 22); + componentsDistributionToolStripMenuItem.Text = "Распределение компонентов"; + componentsDistributionToolStripMenuItem.Click += ComponentsDistributionToolStripMenuItem_Click; // // FormWarehouse // @@ -121,10 +156,14 @@ private MenuStrip menuStrip; private ToolStripMenuItem справочникиToolStripMenuItem; private ToolStripMenuItem операцииToolStripMenuItem; - private ToolStripMenuItem заявкиToolStripMenuItem; private ToolStripMenuItem ComponentToolStripMenuItem; private ToolStripMenuItem InventoryToolStripMenuItem; private ToolStripMenuItem EmployeeToolStripMenuItem; private ToolStripMenuItem Components_ProductionToolStripMenuItem; + private ToolStripMenuItem отчетыToolStripMenuItem; + private ToolStripMenuItem DirectoryReportToolStripMenuItem; + private ToolStripMenuItem OrderRequestToolStripMenuItem; + private ToolStripMenuItem componentReportToolStripMenuItem; + private ToolStripMenuItem componentsDistributionToolStripMenuItem; } } diff --git a/ProjectWarehouse/ProjectWarehouse/FormWarehouse.cs b/ProjectWarehouse/ProjectWarehouse/FormWarehouse.cs index 69c14f4..2e0d597 100644 --- a/ProjectWarehouse/ProjectWarehouse/FormWarehouse.cs +++ b/ProjectWarehouse/ProjectWarehouse/FormWarehouse.cs @@ -38,23 +38,22 @@ namespace ProjectWarehouse } } - private void OrderRequestToolStripMenuItem_Click(object sender, EventArgs e) + private void EmployeeToolStripMenuItem_Click(object sender, EventArgs e) { try { - _container.Resolve().ShowDialog(); + _container.Resolve().ShowDialog(); } catch (Exception ex) { MessageBox.Show(ex.Message, " ", MessageBoxButtons.OK, MessageBoxIcon.Error); } } - - private void EmployeeToolStripMenuItem_Click(object sender, EventArgs e) + private void OrderRequestToolStripMenuItem_Click(object sender, EventArgs e) { try { - _container.Resolve().ShowDialog(); + _container.Resolve().ShowDialog(); } catch (Exception ex) { @@ -73,5 +72,41 @@ namespace ProjectWarehouse 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 ComponentReportToolStripMenuItem_Click(object sender, EventArgs e) + { + try + { + _container.Resolve().ShowDialog(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, " ", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ComponentsDistributionToolStripMenuItem_Click(object sender, EventArgs e) + { + try + { + _container.Resolve().ShowDialog(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, " ", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } } } diff --git a/ProjectWarehouse/ProjectWarehouse/Forms/FormComponentReport.Designer.cs b/ProjectWarehouse/ProjectWarehouse/Forms/FormComponentReport.Designer.cs new file mode 100644 index 0000000..f81177a --- /dev/null +++ b/ProjectWarehouse/ProjectWarehouse/Forms/FormComponentReport.Designer.cs @@ -0,0 +1,163 @@ +namespace ProjectWarehouse.Forms +{ + partial class FormComponentReport + { + /// + /// 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() + { + labelPath = new Label(); + labelComponent = new Label(); + labelDateStart = new Label(); + labelDateEnd = new Label(); + comboBoxComponent = new ComboBox(); + dateTimePickerStart = new DateTimePicker(); + dateTimePickerEnd = new DateTimePicker(); + buttonSelectFilePath = new Button(); + textBoxFilePath = new TextBox(); + buttonMakeReport = new Button(); + SuspendLayout(); + // + // labelPath + // + labelPath.AutoSize = true; + labelPath.Location = new Point(40, 24); + labelPath.Name = "labelPath"; + labelPath.Size = new Size(90, 15); + labelPath.TabIndex = 0; + labelPath.Text = "Путь до файла:"; + // + // labelComponent + // + labelComponent.AutoSize = true; + labelComponent.Location = new Point(40, 67); + labelComponent.Name = "labelComponent"; + labelComponent.Size = new Size(72, 15); + labelComponent.TabIndex = 1; + labelComponent.Text = "Компонент:"; + // + // labelDateStart + // + labelDateStart.AutoSize = true; + labelDateStart.Location = new Point(40, 108); + labelDateStart.Name = "labelDateStart"; + labelDateStart.Size = new Size(77, 15); + labelDateStart.TabIndex = 2; + labelDateStart.Text = "Дата начала:"; + // + // labelDateEnd + // + labelDateEnd.AutoSize = true; + labelDateEnd.Location = new Point(40, 150); + labelDateEnd.Name = "labelDateEnd"; + labelDateEnd.Size = new Size(71, 15); + labelDateEnd.TabIndex = 3; + labelDateEnd.Text = "Дата конца:"; + // + // comboBoxComponent + // + comboBoxComponent.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxComponent.FormattingEnabled = true; + comboBoxComponent.Location = new Point(149, 64); + comboBoxComponent.Name = "comboBoxComponent"; + comboBoxComponent.Size = new Size(193, 23); + comboBoxComponent.TabIndex = 4; + // + // dateTimePickerStart + // + dateTimePickerStart.Location = new Point(149, 108); + dateTimePickerStart.Name = "dateTimePickerStart"; + dateTimePickerStart.Size = new Size(193, 23); + dateTimePickerStart.TabIndex = 5; + // + // dateTimePickerEnd + // + dateTimePickerEnd.Location = new Point(149, 150); + dateTimePickerEnd.Name = "dateTimePickerEnd"; + dateTimePickerEnd.Size = new Size(193, 23); + dateTimePickerEnd.TabIndex = 6; + // + // buttonSelectFilePath + // + buttonSelectFilePath.Location = new Point(319, 20); + buttonSelectFilePath.Name = "buttonSelectFilePath"; + buttonSelectFilePath.Size = new Size(23, 23); + buttonSelectFilePath.TabIndex = 7; + buttonSelectFilePath.Text = "..."; + buttonSelectFilePath.UseVisualStyleBackColor = true; + buttonSelectFilePath.Click += ButtonSelectFilePath_Click; + // + // textBoxFilePath + // + textBoxFilePath.Location = new Point(149, 20); + textBoxFilePath.Name = "textBoxFilePath"; + textBoxFilePath.Size = new Size(164, 23); + textBoxFilePath.TabIndex = 8; + // + // buttonMakeReport + // + buttonMakeReport.Location = new Point(117, 205); + buttonMakeReport.Name = "buttonMakeReport"; + buttonMakeReport.Size = new Size(143, 23); + buttonMakeReport.TabIndex = 9; + buttonMakeReport.Text = "Сформировать"; + buttonMakeReport.UseVisualStyleBackColor = true; + buttonMakeReport.Click += ButtonMakeReport_Click; + // + // FormComponentReport + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(390, 251); + Controls.Add(buttonMakeReport); + Controls.Add(textBoxFilePath); + Controls.Add(buttonSelectFilePath); + Controls.Add(dateTimePickerEnd); + Controls.Add(dateTimePickerStart); + Controls.Add(comboBoxComponent); + Controls.Add(labelDateEnd); + Controls.Add(labelDateStart); + Controls.Add(labelComponent); + Controls.Add(labelPath); + Name = "FormComponentReport"; + Text = "FormComponentReport"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Label labelPath; + private Label labelComponent; + private Label labelDateStart; + private Label labelDateEnd; + private ComboBox comboBoxComponent; + private DateTimePicker dateTimePickerStart; + private DateTimePicker dateTimePickerEnd; + private Button buttonSelectFilePath; + private TextBox textBoxFilePath; + private Button buttonMakeReport; + } +} \ No newline at end of file diff --git a/ProjectWarehouse/ProjectWarehouse/Forms/FormComponentReport.cs b/ProjectWarehouse/ProjectWarehouse/Forms/FormComponentReport.cs new file mode 100644 index 0000000..d9be44d --- /dev/null +++ b/ProjectWarehouse/ProjectWarehouse/Forms/FormComponentReport.cs @@ -0,0 +1,71 @@ + + +using ProjectWarehouse.Reports; +using ProjectWarehouse.Repositories; +using Unity; + +namespace ProjectWarehouse.Forms +{ + public partial class FormComponentReport : Form + { + private readonly IUnityContainer _container; + + public FormComponentReport(IUnityContainer container, IComponentsRepository componentsRepository) + { + InitializeComponent(); + _container = container ?? + throw new ArgumentNullException(nameof(container)); + + comboBoxComponent.DataSource = componentsRepository.ReadComponents(); + comboBoxComponent.DisplayMember = "Name"; + comboBoxComponent.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 ButtonMakeReport_Click(object sender, EventArgs e) + { + try + { + if (string.IsNullOrWhiteSpace(textBoxFilePath.Text)) + { + throw new Exception("Отсутствует имя файла для отчета"); + } + if (comboBoxComponent.SelectedIndex < 0) + { + throw new Exception("Не выбран корм"); + } + if (dateTimePickerEnd.Value <= dateTimePickerStart.Value) + { + throw new Exception("Дата начала должна быть раньше даты окончания"); + } + if + (_container.Resolve().CreateTable(textBoxFilePath.Text, (int)comboBoxComponent.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/ProjectWarehouse/ProjectWarehouse/Forms/FormComponentReport.resx b/ProjectWarehouse/ProjectWarehouse/Forms/FormComponentReport.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/ProjectWarehouse/ProjectWarehouse/Forms/FormComponentReport.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/ProjectWarehouse/ProjectWarehouse/Forms/FormDirectoryReport.Designer.cs b/ProjectWarehouse/ProjectWarehouse/Forms/FormDirectoryReport.Designer.cs new file mode 100644 index 0000000..16c0a46 --- /dev/null +++ b/ProjectWarehouse/ProjectWarehouse/Forms/FormDirectoryReport.Designer.cs @@ -0,0 +1,86 @@ +namespace ProjectWarehouse.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() + { + checkBoxComponents = new CheckBox(); + checkBoxEmployee = new CheckBox(); + buttonBuild = new Button(); + SuspendLayout(); + // + // checkBoxComponents + // + checkBoxComponents.AutoSize = true; + checkBoxComponents.Location = new Point(32, 30); + checkBoxComponents.Name = "checkBoxComponents"; + checkBoxComponents.Size = new Size(120, 19); + checkBoxComponents.TabIndex = 0; + checkBoxComponents.Text = "Комплектующие"; + checkBoxComponents.UseVisualStyleBackColor = true; + // + // checkBoxEmployee + // + checkBoxEmployee.AutoSize = true; + checkBoxEmployee.Location = new Point(32, 75); + checkBoxEmployee.Name = "checkBoxEmployee"; + checkBoxEmployee.Size = new Size(85, 19); + checkBoxEmployee.TabIndex = 1; + checkBoxEmployee.Text = "Работники"; + checkBoxEmployee.UseVisualStyleBackColor = true; + // + // buttonBuild + // + buttonBuild.Location = new Point(188, 56); + buttonBuild.Name = "buttonBuild"; + buttonBuild.Size = new Size(117, 23); + buttonBuild.TabIndex = 2; + buttonBuild.Text = "Сформировать"; + buttonBuild.UseVisualStyleBackColor = true; + buttonBuild.Click += ButtonBuild_Click; + // + // FormDirectoryReport + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(328, 135); + Controls.Add(buttonBuild); + Controls.Add(checkBoxEmployee); + Controls.Add(checkBoxComponents); + Name = "FormDirectoryReport"; + Text = "Выгрузка справочников"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private CheckBox checkBoxComponents; + private CheckBox checkBoxEmployee; + private Button buttonBuild; + } +} \ No newline at end of file diff --git a/ProjectWarehouse/ProjectWarehouse/Forms/FormDirectoryReport.cs b/ProjectWarehouse/ProjectWarehouse/Forms/FormDirectoryReport.cs new file mode 100644 index 0000000..69a1646 --- /dev/null +++ b/ProjectWarehouse/ProjectWarehouse/Forms/FormDirectoryReport.cs @@ -0,0 +1,57 @@ +using ProjectWarehouse.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 ProjectWarehouse.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 (!checkBoxEmployee.Checked && !checkBoxComponents.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, checkBoxEmployee.Checked, checkBoxComponents.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/ProjectWarehouse/ProjectWarehouse/Forms/FormDirectoryReport.resx b/ProjectWarehouse/ProjectWarehouse/Forms/FormDirectoryReport.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/ProjectWarehouse/ProjectWarehouse/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/ProjectWarehouse/ProjectWarehouse/Forms/FormInventoryDistributionReport.Designer.cs b/ProjectWarehouse/ProjectWarehouse/Forms/FormInventoryDistributionReport.Designer.cs new file mode 100644 index 0000000..5ba7025 --- /dev/null +++ b/ProjectWarehouse/ProjectWarehouse/Forms/FormInventoryDistributionReport.Designer.cs @@ -0,0 +1,111 @@ +namespace ProjectWarehouse.Forms +{ + partial class FormInventoryDistributionReport + { + /// + /// 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(); + dateTimePicker = new DateTimePicker(); + buttonCreate = new Button(); + SuspendLayout(); + // + // buttonSelectFileName + // + buttonSelectFileName.Location = new Point(51, 44); + buttonSelectFileName.Margin = new Padding(3, 4, 3, 4); + buttonSelectFileName.Name = "buttonSelectFileName"; + buttonSelectFileName.Size = new Size(86, 31); + buttonSelectFileName.TabIndex = 0; + buttonSelectFileName.Text = "Выбрать"; + buttonSelectFileName.UseVisualStyleBackColor = true; + buttonSelectFileName.Click += ButtonSelectFileName_Click; + // + // labelFileName + // + labelFileName.AutoSize = true; + labelFileName.Location = new Point(187, 49); + labelFileName.Name = "labelFileName"; + labelFileName.Size = new Size(45, 20); + labelFileName.TabIndex = 1; + labelFileName.Text = "Файл"; + // + // labelDate + // + labelDate.AutoSize = true; + labelDate.Location = new Point(51, 107); + labelDate.Name = "labelDate"; + labelDate.Size = new Size(44, 20); + labelDate.TabIndex = 2; + labelDate.Text = "Дата:"; + // + // dateTimePicker + // + dateTimePicker.Location = new Point(137, 99); + dateTimePicker.Margin = new Padding(3, 4, 3, 4); + dateTimePicker.Name = "dateTimePicker"; + dateTimePicker.Size = new Size(166, 27); + dateTimePicker.TabIndex = 3; + // + // buttonCreate + // + buttonCreate.Location = new Point(89, 158); + buttonCreate.Margin = new Padding(3, 4, 3, 4); + buttonCreate.Name = "buttonCreate"; + buttonCreate.Size = new Size(130, 31); + buttonCreate.TabIndex = 4; + buttonCreate.Text = "Сформировать"; + buttonCreate.UseVisualStyleBackColor = true; + buttonCreate.Click += ButtonCreate_Click; + // + // FormInventoryDistributionReport + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(332, 227); + Controls.Add(buttonCreate); + Controls.Add(dateTimePicker); + Controls.Add(labelDate); + Controls.Add(labelFileName); + Controls.Add(buttonSelectFileName); + Margin = new Padding(3, 4, 3, 4); + Name = "FormInventoryDistributionReport"; + Text = "FormInventoryDistributionReport"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Button buttonSelectFileName; + private Label labelFileName; + private Label labelDate; + private DateTimePicker dateTimePicker; + private Button buttonCreate; + } +} \ No newline at end of file diff --git a/ProjectWarehouse/ProjectWarehouse/Forms/FormInventoryDistributionReport.cs b/ProjectWarehouse/ProjectWarehouse/Forms/FormInventoryDistributionReport.cs new file mode 100644 index 0000000..2520cb2 --- /dev/null +++ b/ProjectWarehouse/ProjectWarehouse/Forms/FormInventoryDistributionReport.cs @@ -0,0 +1,66 @@ +using ProjectWarehouse.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 ProjectWarehouse.Forms +{ + public partial class FormInventoryDistributionReport : Form + { + private string _fileName = string.Empty; + + private readonly IUnityContainer _container; + + public FormInventoryDistributionReport(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, dateTimePicker.Value)) + { + MessageBox.Show("Документ сформирован", "Формирование документа", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + else + { + MessageBox.Show("Возникли ошибки при формировании документа.Подробности в логах", "Формирование документа", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка при создании очета", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } +} \ No newline at end of file diff --git a/ProjectWarehouse/ProjectWarehouse/Forms/FormInventoryDistributionReport.resx b/ProjectWarehouse/ProjectWarehouse/Forms/FormInventoryDistributionReport.resx new file mode 100644 index 0000000..8b2ff64 --- /dev/null +++ b/ProjectWarehouse/ProjectWarehouse/Forms/FormInventoryDistributionReport.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/ProjectWarehouse/ProjectWarehouse/Forms/FormProduction.cs b/ProjectWarehouse/ProjectWarehouse/Forms/FormProduction.cs index 28b9d40..0f1c271 100644 --- a/ProjectWarehouse/ProjectWarehouse/Forms/FormProduction.cs +++ b/ProjectWarehouse/ProjectWarehouse/Forms/FormProduction.cs @@ -59,7 +59,8 @@ namespace ProjectWarehouse.Forms Convert.ToInt32(row.Cells["ColumnComponents"].Value), Convert.ToInt32(row.Cells["ColumnCount"].Value))); } - return list; + return list.GroupBy(x => x.ComponentsId, x => x.Count, (id, counts) => + Components_Production.CreateElement(0, id, counts.Sum())).ToList(); } } -} +} \ No newline at end of file diff --git a/ProjectWarehouse/ProjectWarehouse/Program.cs b/ProjectWarehouse/ProjectWarehouse/Program.cs index 3fcdd22..f697c09 100644 --- a/ProjectWarehouse/ProjectWarehouse/Program.cs +++ b/ProjectWarehouse/ProjectWarehouse/Program.cs @@ -3,6 +3,7 @@ using Microsoft.Extensions.Logging; using ProjectWarehouse.Repositories; using ProjectWarehouse.Repositories.Implementations; using Serilog; +using System.Text; using Unity; using Unity.Lifetime; using Unity.Microsoft.Logging; @@ -27,6 +28,8 @@ namespace ProjectWarehouse { var container = new UnityContainer(); + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + container.AddExtension(new LoggingExtension(CreateLoggerFactory())); container.RegisterType(new TransientLifetimeManager()); diff --git a/ProjectWarehouse/ProjectWarehouse/ProjectWarehouse.csproj b/ProjectWarehouse/ProjectWarehouse/ProjectWarehouse.csproj index cbeb2ed..fd70d03 100644 --- a/ProjectWarehouse/ProjectWarehouse/ProjectWarehouse.csproj +++ b/ProjectWarehouse/ProjectWarehouse/ProjectWarehouse.csproj @@ -10,11 +10,13 @@ + + diff --git a/ProjectWarehouse/ProjectWarehouse/Reports/ChartReport.cs b/ProjectWarehouse/ProjectWarehouse/Reports/ChartReport.cs new file mode 100644 index 0000000..12f994a --- /dev/null +++ b/ProjectWarehouse/ProjectWarehouse/Reports/ChartReport.cs @@ -0,0 +1,50 @@ +using Microsoft.Extensions.Logging; +using ProjectWarehouse.Repositories; + +namespace ProjectWarehouse.Reports; + +internal class ChartReport +{ + private readonly IInventoryRepository _inventoryRepository; + + private readonly ILogger _logger; + + public ChartReport(IInventoryRepository inventoryRepository, ILogger logger) + { + _inventoryRepository = inventoryRepository ?? + throw new ArgumentNullException(nameof(inventoryRepository)); + _logger = logger ?? + throw new ArgumentNullException(nameof(logger)); + } + + public bool CreateChart(string filePath, DateTime dateTime) + { + try + { + new PdfBuilder(filePath) + .AddHeader("Пополнение склада") + .AddPieChart("Полученные компоненты", GetData(dateTime)) + .Build(); + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при формировании документа"); + return false; + } + } + + private List<(string Caption, double Value)> GetData(DateTime dateTime) + { + return _inventoryRepository + .ReadInventory() + .Where(x => x.Date.Date == dateTime.Date) + .GroupBy(x => x.ComponentsId) + .Select(group => ( + Caption: $"Компонент {group.Key}", + Value: group.Sum(x => x.Quantity) + )) + .ToList(); + } + +} diff --git a/ProjectWarehouse/ProjectWarehouse/Reports/DocReport.cs b/ProjectWarehouse/ProjectWarehouse/Reports/DocReport.cs new file mode 100644 index 0000000..7289c91 --- /dev/null +++ b/ProjectWarehouse/ProjectWarehouse/Reports/DocReport.cs @@ -0,0 +1,68 @@ +using Microsoft.Extensions.Logging; +using ProjectWarehouse.Repositories; + +namespace ProjectWarehouse.Reports; + +internal class DocReport +{ + private readonly IEmployeeRepository _employeeRepository; + private readonly IComponentsRepository _componentsRepository; + + private readonly ILogger _logger; + + public DocReport(IEmployeeRepository employeeRepository, IComponentsRepository componentsRepository, ILogger logger) + { + _employeeRepository = employeeRepository ?? + throw new ArgumentNullException(nameof(employeeRepository)); + _componentsRepository = componentsRepository ?? + throw new ArgumentNullException(nameof(componentsRepository)); + _logger = logger ?? + throw new ArgumentNullException(nameof(logger)); + } + + public bool CreateDoc(string filePath, bool includeEmployee, bool includeComponents) + { + try + { + var builder = new WordBuilder(filePath) + .AddHeader("Документ со справочниками"); + if (includeEmployee) + { + builder.AddParagraph("Работники") + .AddTable([2400, 2400, 2400], GetEmployee()); + } + if (includeComponents) + { + builder.AddParagraph("Комплектующие") + .AddTable([2400, 2400, 1200, 1200], GetComponents()); + } + builder.Build(); + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при формировании документа"); + return false; + } + } + + private List GetEmployee() + { + return [ + ["Имя", "Фамилия", "Должность"], + .. _employeeRepository + .ReadEmployees() + .Select(x => new string[] { x.FirstName, x.LastName, x.EmployeePostId.ToString() }), + ]; + } + + private List GetComponents() + { + return [ + ["Название", "Цена", "Количество", "Тип комплектующего"], + .. _componentsRepository + .ReadComponents() + .Select(x => new string[] { x.Name, x.Price.ToString(), x.Count.ToString(), x.TypeComponentsId.ToString() }), + ]; + } +} \ No newline at end of file diff --git a/ProjectWarehouse/ProjectWarehouse/Reports/ExcelBuilder.cs b/ProjectWarehouse/ProjectWarehouse/Reports/ExcelBuilder.cs new file mode 100644 index 0000000..916eaa4 --- /dev/null +++ b/ProjectWarehouse/ProjectWarehouse/Reports/ExcelBuilder.cs @@ -0,0 +1,331 @@ +using DocumentFormat.OpenXml; +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Spreadsheet; + +namespace ProjectWarehouse.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.SimpleTextWithoutBorder); + 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.BoldTextWithBorders); // жирный + } + + _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.SimpleTextWithBorders); + } + + _rowIndex++; + } + for (var j = 0; j < data.Last().Length; ++j) + { + CreateCell(j, _rowIndex, data.Last()[j], + StyleIndex.BoldTextWithBorders); // жирным сделать + } + _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() + }); + + workbookStylesPart.Stylesheet.Append(fonts); + + // Заливка + var fills = new Fills() { Count = 1 }; + fills.Append(new Fill + { + PatternFill = new PatternFill() + { + PatternType = new EnumValue(PatternValues.None) + } + }); + workbookStylesPart.Stylesheet.Append(fills); + + // Границы + 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); + + // Формат ячеек + 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.Left, + Vertical = VerticalAlignmentValues.Center, + WrapText = true + } + }); + cellFormats.Append(new CellFormat + { + NumberFormatId = 0, + FormatId = 0, + FontId = 1, + BorderId = 0, + FillId = 0, + Alignment = new Alignment() + { + Horizontal = HorizontalAlignmentValues.Left, + Vertical = VerticalAlignmentValues.Center, + WrapText = true + } + }); + cellFormats.Append(new CellFormat + { + NumberFormatId = 0, + FormatId = 0, + FontId = 1, + BorderId = 1, + FillId = 0, + Alignment = new Alignment() + { + Horizontal = HorizontalAlignmentValues.Left, + Vertical = VerticalAlignmentValues.Center, + WrapText = true + } + }); + + workbookStylesPart.Stylesheet.Append(cellFormats); + } + + private enum StyleIndex + { + SimpleTextWithoutBorder = 0, + SimpleTextWithBorders = 1, + BoldTextWithoutBorders = 2, + BoldTextWithBorders = 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; + } +} \ No newline at end of file diff --git a/ProjectWarehouse/ProjectWarehouse/Reports/PdfBuilder.cs b/ProjectWarehouse/ProjectWarehouse/Reports/PdfBuilder.cs new file mode 100644 index 0000000..871eb67 --- /dev/null +++ b/ProjectWarehouse/ProjectWarehouse/Reports/PdfBuilder.cs @@ -0,0 +1,87 @@ +using MigraDoc.DocumentObjectModel.Shapes.Charts; +using MigraDoc.DocumentObjectModel; +using MigraDoc.Rendering; + +namespace ProjectWarehouse.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; + } + +} diff --git a/ProjectWarehouse/ProjectWarehouse/Reports/TableReport.cs b/ProjectWarehouse/ProjectWarehouse/Reports/TableReport.cs new file mode 100644 index 0000000..05322a5 --- /dev/null +++ b/ProjectWarehouse/ProjectWarehouse/Reports/TableReport.cs @@ -0,0 +1,126 @@ +using Microsoft.Extensions.Logging; +using ProjectWarehouse.Repositories; +using System.Linq; + +namespace ProjectWarehouse.Reports; + +public class MovementData +{ + public DateTime Date { get; set; } + public double? CountIn { get; set; } + public double? CountOut { get; set; } + + public int? EmployeeId { get; set; } +} + +internal class TableReport +{ + private readonly IProductionRepository _productionRepository; + + private readonly IInventoryRepository _inventoryRepository; + + private readonly IOrderRequestRepository _orderRequestRepository; + + private readonly ILogger _logger; + + internal static readonly string[] item = ["", "Дата", "Количество пришло", "Количество ушло"]; + + public TableReport(IProductionRepository productionRepository, IInventoryRepository inventoryRepository, IOrderRequestRepository orderRequestRepository, ILogger logger) + { + _productionRepository = productionRepository ?? + throw new ArgumentNullException(nameof(productionRepository)); + _inventoryRepository = inventoryRepository ?? + throw new ArgumentNullException(nameof(inventoryRepository)); + _orderRequestRepository = orderRequestRepository ?? + throw new ArgumentNullException(nameof(orderRequestRepository)); + _logger = logger ?? + throw new ArgumentNullException(nameof(logger)); + } + + public bool CreateTable(string filePath, int componentsId, DateTime startDate, DateTime endDate) + { + try + { + new ExcelBuilder(filePath) + .AddHeader("Сводка по движению комлектующих", 0, 4) + .AddParagraph("за период", 0). + AddTable([10, 10, 15, 15], GetData(componentsId, startDate, endDate)).Build(); + + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при формировании документа"); + return false; + } + + } + + private List GetData(int componentsId, DateTime startDate, DateTime endDate) + { + // Получаем данные по приходам (Production) + var productionData = _productionRepository + .ReadProduction() + .Where(x => x.Date >= startDate && x.Date <= endDate && x.Components_Productions.Any(y => y.ComponentsId == componentsId)) + .Select(x => new MovementData + { + Date = x.Date, + CountIn = x.Components_Productions.FirstOrDefault(y => y.ComponentsId == componentsId)?.Count, + CountOut = null + }) + .ToList(); + + var orderRequestData = _orderRequestRepository + .ReadOrderRequest() + .Where(x => x.DateOrder >= startDate && x.DateOrder <= endDate && x.ComponentsId == componentsId) + .Select(x => new MovementData + { + Date = x.DateOrder, + CountIn = null, + CountOut = x.Quantity + }) + .ToList(); + + var inventoryData = _inventoryRepository + .ReadInventory() + .Where(x => x.Date >= startDate && x.Date <= endDate && x.ComponentsId == componentsId) + .Select(x => new MovementData + { + Date = x.Date, + CountIn = x.IsDefect ? 0 : x.Quantity, + CountOut = x.IsDefect ? x.Quantity : 0 + }) + .ToList(); + + var combinedData = productionData + .Union(orderRequestData) + .Union(inventoryData) + .OrderBy(x => x.Date) + .ToList(); + + return new List + { + item + } + .Union( + combinedData.Select(x => new string[] + { + "", + x.Date.ToString("yyyy-MM-dd"), + x.CountIn?.ToString("F2") ?? string.Empty, + x.CountOut?.ToString("F2") ?? string.Empty + }) + ) + .Union(new[] { + new string[] + { + "Всего", "", + combinedData.Sum(x => x.CountIn ?? 0).ToString("F2"), + combinedData.Sum(x => x.CountOut ?? 0).ToString("F2") + } + }) + .ToList(); + } + + +} \ No newline at end of file diff --git a/ProjectWarehouse/ProjectWarehouse/Reports/WordBuilder.cs b/ProjectWarehouse/ProjectWarehouse/Reports/WordBuilder.cs new file mode 100644 index 0000000..f5b9a5f --- /dev/null +++ b/ProjectWarehouse/ProjectWarehouse/Reports/WordBuilder.cs @@ -0,0 +1,94 @@ +using DocumentFormat.OpenXml; +using DocumentFormat.OpenXml.Drawing.Charts; +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Wordprocessing; + +namespace ProjectWarehouse.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()); + run.RunProperties = new RunProperties(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/ProjectWarehouse/ProjectWarehouse/Repositories/Implementations/InventoryRepository.cs b/ProjectWarehouse/ProjectWarehouse/Repositories/Implementations/InventoryRepository.cs index 054c4df..f05dd71 100644 --- a/ProjectWarehouse/ProjectWarehouse/Repositories/Implementations/InventoryRepository.cs +++ b/ProjectWarehouse/ProjectWarehouse/Repositories/Implementations/InventoryRepository.cs @@ -27,8 +27,8 @@ public class InventoryRepository : IInventoryRepository using var connection = new Npgsql.NpgsqlConnection(_connectionString.ConnectionString); connection.Open(); var queryInsert = @" - INSERT INTO Inventory (Quantity, IsDefect, ComponentsId) - VALUES (@Quantity, @IsDefect, @ComponentsId)"; + INSERT INTO Inventory (Quantity, IsDefect, ComponentsId, Date) + VALUES (@Quantity, @IsDefect, @ComponentsId, @Date)"; connection.Execute(queryInsert, inventory); } catch (Exception ex) diff --git a/ProjectWarehouse/ProjectWarehouse/Repositories/Implementations/ProductionRepository.cs b/ProjectWarehouse/ProjectWarehouse/Repositories/Implementations/ProductionRepository.cs index 7b09c80..1489808 100644 --- a/ProjectWarehouse/ProjectWarehouse/Repositories/Implementations/ProductionRepository.cs +++ b/ProjectWarehouse/ProjectWarehouse/Repositories/Implementations/ProductionRepository.cs @@ -27,8 +27,8 @@ public class ProductionRepository : IProductionRepository connection.Open(); using var transaction = connection.BeginTransaction(); var queryInsert = @" - INSERT INTO Production (Name, Description, EmployeeId) - VALUES (@Name, @Description, @EmployeeId); + INSERT INTO Production (Name, Description, EmployeeId, Date) + VALUES (@Name, @Description, @EmployeeId, @Date); SELECT MAX(id) FROM Production"; var productionId = connection.QueryFirst(queryInsert, production, transaction); var querySubInsert = @" @@ -79,11 +79,14 @@ public class ProductionRepository : IProductionRepository try { using var connection = new Npgsql.NpgsqlConnection(_connectionString.ConnectionString); - var querySelect = @"SELECT * FROM Production"; - var production = - connection.Query(querySelect); + var querySelect = @" + SELECT fr.*, ffr.ComponentsId, ffr.Count FROM Production fr + INNER JOIN Components_Production ffr ON ffr.ProductionId = fr.Id"; + var production = connection.Query(querySelect); _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(production)); - return production; + return production.GroupBy(x => x.Id, y => y, + (key, value) => Production.CreateEntity(value.First(), + value.Select(z => Components_Production.CreateElement(0, z.ComponentsId, z.Count)))).ToList(); } catch (Exception ex) {