diff --git a/CarpentryWorkshop/CarpentryWorkshop/FormImplementer.Designer.cs b/CarpentryWorkshop/CarpentryWorkshop/FormImplementer.Designer.cs new file mode 100644 index 0000000..a749799 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshop/FormImplementer.Designer.cs @@ -0,0 +1,168 @@ +namespace CarpentryWorkshopView +{ + partial class FormImplementer + { + /// + /// 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() + { + labelFIO = new Label(); + labelPassword = new Label(); + labelExperience = new Label(); + labelQualification = new Label(); + textBoxFIO = new TextBox(); + textBoxPassword = new TextBox(); + numericUpDownExperience = new NumericUpDown(); + numericUpDownQualification = new NumericUpDown(); + buttonSave = new Button(); + buttonCancel = new Button(); + ((System.ComponentModel.ISupportInitialize)numericUpDownExperience).BeginInit(); + ((System.ComponentModel.ISupportInitialize)numericUpDownQualification).BeginInit(); + SuspendLayout(); + // + // labelFIO + // + labelFIO.AutoSize = true; + labelFIO.Location = new System.Drawing.Point(16, 49); + labelFIO.Name = "labelFIO"; + labelFIO.Size = new System.Drawing.Size(45, 20); + labelFIO.TabIndex = 0; + labelFIO.Text = "ФИО:"; + // + // labelPassword + // + labelPassword.AutoSize = true; + labelPassword.Location = new System.Drawing.Point(16, 97); + labelPassword.Name = "labelPassword"; + labelPassword.Size = new System.Drawing.Size(65, 20); + labelPassword.TabIndex = 1; + labelPassword.Text = "Пароль:"; + // + // labelExperience + // + labelExperience.AutoSize = true; + labelExperience.Location = new System.Drawing.Point(16, 150); + labelExperience.Name = "labelWorkExperience"; + labelExperience.Size = new System.Drawing.Size(102, 20); + labelExperience.TabIndex = 2; + labelExperience.Text = "Стаж работы:"; + // + // labelQualification + // + labelQualification.AutoSize = true; + labelQualification.Location = new System.Drawing.Point(16, 201); + labelQualification.Name = "labelQualification"; + labelQualification.Size = new System.Drawing.Size(114, 20); + labelQualification.TabIndex = 3; + labelQualification.Text = "Квалификация:"; + // + // textBoxFIO + // + textBoxFIO.Location = new System.Drawing.Point(155, 42); + textBoxFIO.Name = "textBoxFIO"; + textBoxFIO.Size = new System.Drawing.Size(285, 27); + textBoxFIO.TabIndex = 4; + // + // textBoxPassword + // + textBoxPassword.Location = new System.Drawing.Point(155, 90); + textBoxPassword.Name = "textBoxPassword"; + textBoxPassword.Size = new System.Drawing.Size(285, 27); + textBoxPassword.TabIndex = 5; + // + // numericUpDownExperience + // + numericUpDownExperience.Location = new Point(155, 143); + numericUpDownExperience.Name = "numericUpDownExperience"; + numericUpDownExperience.Size = new Size(285, 27); + numericUpDownExperience.TabIndex = 6; + // + // numericUpDownQualification + // + numericUpDownQualification.Location = new Point(155, 194); + numericUpDownQualification.Name = "numericUpDownQualification"; + numericUpDownQualification.Size = new Size(285, 27); + numericUpDownQualification.TabIndex = 7; + // + // buttonSave + // + buttonSave.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; + buttonSave.Location = new Point(10, 342); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(140, 53); + buttonSave.TabIndex = 8; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += buttonSave_Click; + // + // buttonCancel + // + buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + buttonCancel.Location = new Point(346, 250); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(94, 29); + buttonCancel.TabIndex = 9; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += buttonCancel_Click; + // + // FormImplementer + // + AutoScaleDimensions = new SizeF(10F, 22F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(454, 292); + Controls.Add(buttonCancel); + Controls.Add(buttonSave); + Controls.Add(numericUpDownQualification); + Controls.Add(numericUpDownExperience); + Controls.Add(textBoxPassword); + Controls.Add(textBoxFIO); + Controls.Add(labelQualification); + Controls.Add(labelExperience); + Controls.Add(labelPassword); + Controls.Add(labelFIO); + Name = "FormImplementer"; + Text = "Исполнитель"; + Load += FormImplementer_Load; + ((System.ComponentModel.ISupportInitialize)numericUpDownExperience).EndInit(); + ((System.ComponentModel.ISupportInitialize)numericUpDownQualification).EndInit(); + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Label labelFIO; + private Label labelPassword; + private Label labelExperience; + private Label labelQualification; + private TextBox textBoxFIO; + private TextBox textBoxPassword; + private NumericUpDown numericUpDownExperience; + private NumericUpDown numericUpDownQualification; + private Button buttonSave; + private Button buttonCancel; + } +} \ No newline at end of file diff --git a/CarpentryWorkshop/CarpentryWorkshop/FormImplementer.cs b/CarpentryWorkshop/CarpentryWorkshop/FormImplementer.cs new file mode 100644 index 0000000..33dc671 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshop/FormImplementer.cs @@ -0,0 +1,101 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.BusinessLogicsContracts; +using CarpentryWorkshopContracts.SearchModels; +using Microsoft.Extensions.Logging; +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; + +namespace CarpentryWorkshopView +{ + public partial class FormImplementer : Form + { + private readonly ILogger _logger; + private readonly IImplementerLogic _implementerLogic; + private int? _id; + public int Id { set { _id = value; } } + public FormImplementer(ILogger logger, IImplementerLogic implementerLogic) + { + InitializeComponent(); + _logger = logger; + _implementerLogic = implementerLogic; + } + + private void buttonSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxPassword.Text)) + { + MessageBox.Show("Заполните пароль", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (string.IsNullOrEmpty(textBoxFIO.Text)) + { + MessageBox.Show("Заполните ФИО", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Сохранение исполнителя"); + try + { + var model = new ImplementerBindingModel + { + Id = _id ?? 0, + ImplementerFIO = textBoxFIO.Text, + Password = textBoxPassword.Text, + Qualification = (int)numericUpDownQualification.Value, + WorkExperience = (int)numericUpDownExperience.Value, + }; + var operationResult = _id.HasValue ? _implementerLogic.Update(model) : _implementerLogic.Create(model); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + Close(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка сохранения исполнителя"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void FormImplementer_Load(object sender, EventArgs e) + { + if (_id.HasValue) + { + try + { + _logger.LogInformation("Получение информации исполнителя"); + var view = _implementerLogic.ReadElement(new ImplementerSearchModel + { + Id = _id.Value + }); + if (view != null) + { + textBoxFIO.Text = view.ImplementerFIO; + textBoxPassword.Text = view.Password; + numericUpDownQualification.Value = view.Qualification; + numericUpDownExperience.Value = view.WorkExperience; + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения исполнителя"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + + private void buttonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; Close(); + } + } +} diff --git a/CarpentryWorkshop/CarpentryWorkshop/FormImplementer.resx b/CarpentryWorkshop/CarpentryWorkshop/FormImplementer.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshop/FormImplementer.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/CarpentryWorkshop/CarpentryWorkshop/FormImplementers.Designer.cs b/CarpentryWorkshop/CarpentryWorkshop/FormImplementers.Designer.cs new file mode 100644 index 0000000..d336194 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshop/FormImplementers.Designer.cs @@ -0,0 +1,114 @@ +namespace CarpentryWorkshopView +{ + partial class FormImplementers + { + /// + /// 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() + { + dataGridView = new DataGridView(); + buttonAdd = new Button(); + buttonUpdate = new Button(); + buttonDelete = new Button(); + buttonRefresh = new Button(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // dataGridView + // + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(0, 0); + dataGridView.Name = "dataGridView"; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 29; + dataGridView.Size = new Size(521, 454); + dataGridView.TabIndex = 1; + // + // buttonAdd + // + buttonAdd.Location = new Point(536, 45); + buttonAdd.Name = "buttonAdd"; + buttonAdd.Size = new Size(94, 29); + buttonAdd.TabIndex = 2; + buttonAdd.Text = "Добавить"; + buttonAdd.UseVisualStyleBackColor = true; + buttonAdd.Click += buttonAdd_Click; + // + // buttonUpdate + // + buttonUpdate.Location = new Point(536, 106); + buttonUpdate.Name = "buttonUpdate"; + buttonUpdate.Size = new Size(94, 29); + buttonUpdate.TabIndex = 3; + buttonUpdate.Text = "Изменить"; + buttonUpdate.UseVisualStyleBackColor = true; + buttonUpdate.Click += buttonUpdate_Click; + // + // buttonDelete + // + buttonDelete.Location = new Point(536, 160); + buttonDelete.Name = "buttonDelete"; + buttonDelete.Size = new Size(94, 29); + buttonDelete.TabIndex = 4; + buttonDelete.Text = "Удалить"; + buttonDelete.UseVisualStyleBackColor = true; + buttonDelete.Click += buttonDelete_Click; + // + // buttonRefresh + // + buttonRefresh.Location = new Point(536, 215); + buttonRefresh.Name = "buttonRefresh"; + buttonRefresh.Size = new Size(94, 29); + buttonRefresh.TabIndex = 5; + buttonRefresh.Text = "Обновить"; + buttonRefresh.UseVisualStyleBackColor = true; + buttonRefresh.Click += buttonRefresh_Click; + // + // FormImplementers + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(646, 450); + Controls.Add(buttonRefresh); + Controls.Add(buttonDelete); + Controls.Add(buttonUpdate); + Controls.Add(buttonAdd); + Controls.Add(dataGridView); + Name = "FormImplementers"; + Text = "Исполнители"; + Load += FormImplementers_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView; + private Button buttonAdd; + private Button buttonUpdate; + private Button buttonDelete; + private Button buttonRefresh; + } +} \ No newline at end of file diff --git a/CarpentryWorkshop/CarpentryWorkshop/FormImplementers.cs b/CarpentryWorkshop/CarpentryWorkshop/FormImplementers.cs new file mode 100644 index 0000000..d98a601 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshop/FormImplementers.cs @@ -0,0 +1,116 @@ +using CarpentryWorkshop; +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +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; + +namespace CarpentryWorkshopView +{ + public partial class FormImplementers : Form + { + private readonly ILogger _logger; + private readonly IImplementerLogic _logic; + + public FormImplementers(ILogger logger, IImplementerLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + private void buttonAdd_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormImplementer)); + if (service is FormImplementer form) + { + form.ShowDialog(); + } + LoadData(); + } + + private void buttonUpdate_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + var service = Program.ServiceProvider?.GetService(typeof(FormImplementer)); + if (service is FormImplementer form) + { + form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + } + + private void LoadData() + { + + try + { + var list = _logic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["Id"].Visible = false; + dataGridView.Columns["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + _logger.LogInformation("Загрузка исполнителей"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки исполнителей"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + + } + + private void FormImplementers_Load(object sender, EventArgs e) + { + LoadData(); + } + + private void buttonDelete_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Удаление исполнителя"); + try + { + if (!_logic.Delete(new ImplementerBindingModel + { + Id = id + })) + { + throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка удаления исполнителя"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } + + private void buttonRefresh_Click(object sender, EventArgs e) + { + LoadData(); + } + } +} diff --git a/CarpentryWorkshop/CarpentryWorkshop/FormImplementers.resx b/CarpentryWorkshop/CarpentryWorkshop/FormImplementers.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshop/FormImplementers.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/CarpentryWorkshop/CarpentryWorkshop/FormMain.Designer.cs b/CarpentryWorkshop/CarpentryWorkshop/FormMain.Designer.cs index 069bfa2..0aaf4b2 100644 --- a/CarpentryWorkshop/CarpentryWorkshop/FormMain.Designer.cs +++ b/CarpentryWorkshop/CarpentryWorkshop/FormMain.Designer.cs @@ -1,223 +1,213 @@ namespace CarpentryWorkshopView { - partial class FormMain - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; + partial class FormMain + { + /// + /// 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); - } + /// + /// 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 + #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() - { - menuStrip1 = new MenuStrip(); - справочникиToolStripMenuItem = new ToolStripMenuItem(); - КомпонентыToolStripMenuItem = new ToolStripMenuItem(); - ИзделияToolStripMenuItem = new ToolStripMenuItem(); - клиентыToolStripMenuItem = new ToolStripMenuItem(); - отчётыToolStripMenuItem = new ToolStripMenuItem(); - списокИзделийToolStripMenuItem = new ToolStripMenuItem(); - компонентыПоИзделиямToolStripMenuItem = new ToolStripMenuItem(); - списокЗаказовToolStripMenuItem = new ToolStripMenuItem(); - dataGridView = new DataGridView(); - ButtonCreateOrder = new Button(); - ButtonTakeOrderInWork = new Button(); - ButtonOrderReady = new Button(); - ButtonIssuedOrder = new Button(); - ButtonRef = new Button(); - menuStrip1.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); - SuspendLayout(); - // - // menuStrip1 - // - menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчётыToolStripMenuItem }); - menuStrip1.Location = new Point(0, 0); - menuStrip1.Name = "menuStrip1"; - menuStrip1.Size = new Size(896, 24); - menuStrip1.TabIndex = 0; - menuStrip1.Text = "menuStrip1"; - // - // справочникиToolStripMenuItem - // - справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { КомпонентыToolStripMenuItem, ИзделияToolStripMenuItem, клиентыToolStripMenuItem }); - справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; - справочникиToolStripMenuItem.Size = new Size(94, 20); - справочникиToolStripMenuItem.Text = "Справочники"; - // - // КомпонентыToolStripMenuItem - // - КомпонентыToolStripMenuItem.Name = "КомпонентыToolStripMenuItem"; - КомпонентыToolStripMenuItem.Size = new Size(145, 22); - КомпонентыToolStripMenuItem.Text = "Компоненты"; - КомпонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click; - // - // ИзделияToolStripMenuItem - // - ИзделияToolStripMenuItem.Name = "ИзделияToolStripMenuItem"; - ИзделияToolStripMenuItem.Size = new Size(145, 22); - ИзделияToolStripMenuItem.Text = "Изделия"; - ИзделияToolStripMenuItem.Click += ИзделияToolStripMenuItem_Click; - // - // клиентыToolStripMenuItem - // - клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; - клиентыToolStripMenuItem.Size = new Size(224, 26); - клиентыToolStripMenuItem.Text = "Клиенты"; - клиентыToolStripMenuItem.Click += КлиентыToolStripMenuItem_Click; - // - // отчётыToolStripMenuItem - // - отчётыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокИзделийToolStripMenuItem, компонентыПоИзделиямToolStripMenuItem, списокЗаказовToolStripMenuItem }); - отчётыToolStripMenuItem.Name = "отчётыToolStripMenuItem"; - отчётыToolStripMenuItem.Size = new Size(60, 20); - отчётыToolStripMenuItem.Text = "Отчёты"; - // - // списокИзделийToolStripMenuItem - // - списокИзделийToolStripMenuItem.Name = "списокИзделийToolStripMenuItem"; - списокИзделийToolStripMenuItem.Size = new Size(218, 22); - списокИзделийToolStripMenuItem.Text = "Список изделий"; - списокИзделийToolStripMenuItem.Click += списокИзделийToolStripMenuItem_Click; - // - // компонентыПоИзделиямToolStripMenuItem - // - компонентыПоИзделиямToolStripMenuItem.Name = "компонентыПоИзделиямToolStripMenuItem"; - компонентыПоИзделиямToolStripMenuItem.Size = new Size(218, 22); - компонентыПоИзделиямToolStripMenuItem.Text = "Компоненты по изделиям"; - компонентыПоИзделиямToolStripMenuItem.Click += компонентыПоИзделиямToolStripMenuItem_Click; - // - // списокЗаказовToolStripMenuItem - // - списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem"; - списокЗаказовToolStripMenuItem.Size = new Size(218, 22); - списокЗаказовToolStripMenuItem.Text = "Список заказов"; - списокЗаказовToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click; - // - // dataGridView - // - dataGridView.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - dataGridView.BackgroundColor = SystemColors.ButtonHighlight; - dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; - dataGridView.EnableHeadersVisualStyles = false; - dataGridView.Location = new Point(1, 32); - dataGridView.MultiSelect = false; - dataGridView.Name = "dataGridView"; - dataGridView.RowTemplate.Height = 25; - dataGridView.Size = new Size(755, 243); - dataGridView.TabIndex = 1; - // - // ButtonCreateOrder - // - ButtonCreateOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; - ButtonCreateOrder.Location = new Point(762, 44); - ButtonCreateOrder.Name = "ButtonCreateOrder"; - ButtonCreateOrder.Size = new Size(122, 23); - ButtonCreateOrder.TabIndex = 2; - ButtonCreateOrder.Text = "Создать заказ"; - ButtonCreateOrder.UseVisualStyleBackColor = true; - ButtonCreateOrder.Click += ButtonCreateOrder_Click; - // - // ButtonTakeOrderInWork - // - ButtonTakeOrderInWork.Anchor = AnchorStyles.Top | AnchorStyles.Right; - ButtonTakeOrderInWork.Location = new Point(762, 73); - ButtonTakeOrderInWork.Name = "ButtonTakeOrderInWork"; - ButtonTakeOrderInWork.Size = new Size(122, 42); - ButtonTakeOrderInWork.TabIndex = 3; - ButtonTakeOrderInWork.Text = "Отдать на выполнение"; - ButtonTakeOrderInWork.UseVisualStyleBackColor = true; - ButtonTakeOrderInWork.Click += ButtonTakeOrderInWork_Click; - // - // ButtonOrderReady - // - ButtonOrderReady.Anchor = AnchorStyles.Top | AnchorStyles.Right; - ButtonOrderReady.Location = new Point(762, 121); - ButtonOrderReady.Name = "ButtonOrderReady"; - ButtonOrderReady.Size = new Size(122, 23); - ButtonOrderReady.TabIndex = 4; - ButtonOrderReady.Text = "Заказ готов"; - ButtonOrderReady.UseVisualStyleBackColor = true; - ButtonOrderReady.Click += ButtonOrderReady_Click; - // - // ButtonIssuedOrder - // - ButtonIssuedOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; - ButtonIssuedOrder.Location = new Point(762, 150); - ButtonIssuedOrder.Name = "ButtonIssuedOrder"; - ButtonIssuedOrder.Size = new Size(122, 23); - ButtonIssuedOrder.TabIndex = 5; - ButtonIssuedOrder.Text = "Заказ выдан"; - ButtonIssuedOrder.UseVisualStyleBackColor = true; - ButtonIssuedOrder.Click += ButtonIssuedOrder_Click; - // - // ButtonRef - // - ButtonRef.Anchor = AnchorStyles.Top | AnchorStyles.Right; - ButtonRef.Location = new Point(762, 179); - ButtonRef.Name = "ButtonRef"; - ButtonRef.Size = new Size(122, 23); - ButtonRef.TabIndex = 6; - ButtonRef.Text = "Обновить список"; - ButtonRef.UseVisualStyleBackColor = true; - ButtonRef.Click += ButtonRef_Click; - // - // FormMain - // - AutoScaleDimensions = new SizeF(7F, 15F); - AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(896, 280); - Controls.Add(ButtonRef); - Controls.Add(ButtonIssuedOrder); - Controls.Add(ButtonOrderReady); - Controls.Add(ButtonTakeOrderInWork); - Controls.Add(ButtonCreateOrder); - Controls.Add(dataGridView); - Controls.Add(menuStrip1); - MainMenuStrip = menuStrip1; - Name = "FormMain"; - Text = "Сборка Набора"; - Load += FormMain_Load; - menuStrip1.ResumeLayout(false); - menuStrip1.PerformLayout(); - ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); - ResumeLayout(false); - PerformLayout(); - } + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + menuStrip1 = new MenuStrip(); + справочникиToolStripMenuItem = new ToolStripMenuItem(); + КомпонентыToolStripMenuItem = new ToolStripMenuItem(); + ИзделияToolStripMenuItem = new ToolStripMenuItem(); + клиентыToolStripMenuItem = new ToolStripMenuItem(); + исполнителиToolStripMenuItem = new ToolStripMenuItem(); + отчётыToolStripMenuItem = new ToolStripMenuItem(); + списокИзделийToolStripMenuItem = new ToolStripMenuItem(); + компонентыПоИзделиямToolStripMenuItem = new ToolStripMenuItem(); + списокЗаказовToolStripMenuItem = new ToolStripMenuItem(); + запускРаботToolStripMenuItem = new ToolStripMenuItem(); + dataGridView = new DataGridView(); + ButtonCreateOrder = new Button(); + ButtonIssuedOrder = new Button(); + ButtonRef = new Button(); + menuStrip1.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // menuStrip1 + // + menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчётыToolStripMenuItem, запускРаботToolStripMenuItem }); + menuStrip1.Location = new Point(0, 0); + menuStrip1.Name = "menuStrip1"; + menuStrip1.Size = new Size(896, 24); + menuStrip1.TabIndex = 0; + menuStrip1.Text = "menuStrip1"; + // + // справочникиToolStripMenuItem + // + справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { КомпонентыToolStripMenuItem, ИзделияToolStripMenuItem, клиентыToolStripMenuItem, исполнителиToolStripMenuItem }); + справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; + справочникиToolStripMenuItem.Size = new Size(94, 20); + справочникиToolStripMenuItem.Text = "Справочники"; + // + // КомпонентыToolStripMenuItem + // + КомпонентыToolStripMenuItem.Name = "КомпонентыToolStripMenuItem"; + КомпонентыToolStripMenuItem.Size = new Size(149, 22); + КомпонентыToolStripMenuItem.Text = "Компоненты"; + КомпонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click; + // + // ИзделияToolStripMenuItem + // + ИзделияToolStripMenuItem.Name = "ИзделияToolStripMenuItem"; + ИзделияToolStripMenuItem.Size = new Size(149, 22); + ИзделияToolStripMenuItem.Text = "Изделия"; + ИзделияToolStripMenuItem.Click += ИзделияToolStripMenuItem_Click; + // + // клиентыToolStripMenuItem + // + клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; + клиентыToolStripMenuItem.Size = new Size(149, 22); + клиентыToolStripMenuItem.Text = "Клиенты"; + клиентыToolStripMenuItem.Click += КлиентыToolStripMenuItem_Click; + // + // исполнителиToolStripMenuItem + // + исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; + исполнителиToolStripMenuItem.Size = new Size(149, 22); + исполнителиToolStripMenuItem.Text = "Исполнители"; + исполнителиToolStripMenuItem.Click += исполнителиToolStripMenuItem_Click; + // + // отчётыToolStripMenuItem + // + отчётыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокИзделийToolStripMenuItem, компонентыПоИзделиямToolStripMenuItem, списокЗаказовToolStripMenuItem }); + отчётыToolStripMenuItem.Name = "отчётыToolStripMenuItem"; + отчётыToolStripMenuItem.Size = new Size(60, 20); + отчётыToolStripMenuItem.Text = "Отчёты"; + // + // списокИзделийToolStripMenuItem + // + списокИзделийToolStripMenuItem.Name = "списокИзделийToolStripMenuItem"; + списокИзделийToolStripMenuItem.Size = new Size(218, 22); + списокИзделийToolStripMenuItem.Text = "Список изделий"; + списокИзделийToolStripMenuItem.Click += списокИзделийToolStripMenuItem_Click; + // + // компонентыПоИзделиямToolStripMenuItem + // + компонентыПоИзделиямToolStripMenuItem.Name = "компонентыПоИзделиямToolStripMenuItem"; + компонентыПоИзделиямToolStripMenuItem.Size = new Size(218, 22); + компонентыПоИзделиямToolStripMenuItem.Text = "Компоненты по изделиям"; + компонентыПоИзделиямToolStripMenuItem.Click += компонентыПоИзделиямToolStripMenuItem_Click; + // + // списокЗаказовToolStripMenuItem + // + списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem"; + списокЗаказовToolStripMenuItem.Size = new Size(218, 22); + списокЗаказовToolStripMenuItem.Text = "Список заказов"; + списокЗаказовToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click; + // + // запускРаботToolStripMenuItem + // + запускРаботToolStripMenuItem.Name = "запускРаботToolStripMenuItem"; + запускРаботToolStripMenuItem.Size = new Size(92, 20); + запускРаботToolStripMenuItem.Text = "Запуск Работ"; + запускРаботToolStripMenuItem.Click += запускРаботToolStripMenuItem_Click; + // + // dataGridView + // + dataGridView.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + dataGridView.BackgroundColor = SystemColors.ButtonHighlight; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.EnableHeadersVisualStyles = false; + dataGridView.Location = new Point(1, 32); + dataGridView.MultiSelect = false; + dataGridView.Name = "dataGridView"; + dataGridView.RowTemplate.Height = 25; + dataGridView.Size = new Size(755, 243); + dataGridView.TabIndex = 1; + // + // ButtonCreateOrder + // + ButtonCreateOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; + ButtonCreateOrder.Location = new Point(762, 44); + ButtonCreateOrder.Name = "ButtonCreateOrder"; + ButtonCreateOrder.Size = new Size(122, 23); + ButtonCreateOrder.TabIndex = 2; + ButtonCreateOrder.Text = "Создать заказ"; + ButtonCreateOrder.UseVisualStyleBackColor = true; + ButtonCreateOrder.Click += ButtonCreateOrder_Click; + // + // ButtonIssuedOrder + // + ButtonIssuedOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; + ButtonIssuedOrder.Location = new Point(762, 73); + ButtonIssuedOrder.Name = "ButtonIssuedOrder"; + ButtonIssuedOrder.Size = new Size(122, 23); + ButtonIssuedOrder.TabIndex = 5; + ButtonIssuedOrder.Text = "Заказ выдан"; + ButtonIssuedOrder.UseVisualStyleBackColor = true; + ButtonIssuedOrder.Click += ButtonIssuedOrder_Click; + // + // ButtonRef + // + ButtonRef.Anchor = AnchorStyles.Top | AnchorStyles.Right; + ButtonRef.Location = new Point(762, 102); + ButtonRef.Name = "ButtonRef"; + ButtonRef.Size = new Size(122, 23); + ButtonRef.TabIndex = 6; + ButtonRef.Text = "Обновить список"; + ButtonRef.UseVisualStyleBackColor = true; + ButtonRef.Click += ButtonRef_Click; + // + // FormMain + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(896, 280); + Controls.Add(ButtonRef); + Controls.Add(ButtonIssuedOrder); + Controls.Add(ButtonCreateOrder); + Controls.Add(dataGridView); + Controls.Add(menuStrip1); + MainMenuStrip = menuStrip1; + Name = "FormMain"; + Text = "Сборка Набора"; + Load += FormMain_Load; + menuStrip1.ResumeLayout(false); + menuStrip1.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + PerformLayout(); + } - #endregion - private MenuStrip menuStrip1; - private ToolStripMenuItem справочникиToolStripMenuItem; - private DataGridView dataGridView; - private Button ButtonCreateOrder; - private Button ButtonTakeOrderInWork; - private Button ButtonOrderReady; - private Button ButtonIssuedOrder; - private Button ButtonRef; - private ToolStripMenuItem КомпонентыToolStripMenuItem; - private ToolStripMenuItem ИзделияToolStripMenuItem; - private ToolStripMenuItem отчётыToolStripMenuItem; - private ToolStripMenuItem списокИзделийToolStripMenuItem; - private ToolStripMenuItem компонентыПоИзделиямToolStripMenuItem; - private ToolStripMenuItem списокЗаказовToolStripMenuItem; - private ToolStripMenuItem клиентыToolStripMenuItem; - } + #endregion + private MenuStrip menuStrip1; + private ToolStripMenuItem справочникиToolStripMenuItem; + private DataGridView dataGridView; + private Button ButtonCreateOrder; + private Button ButtonIssuedOrder; + private Button ButtonRef; + private ToolStripMenuItem КомпонентыToolStripMenuItem; + private ToolStripMenuItem ИзделияToolStripMenuItem; + private ToolStripMenuItem отчётыToolStripMenuItem; + private ToolStripMenuItem списокИзделийToolStripMenuItem; + private ToolStripMenuItem компонентыПоИзделиямToolStripMenuItem; + private ToolStripMenuItem списокЗаказовToolStripMenuItem; + private ToolStripMenuItem клиентыToolStripMenuItem; + private ToolStripMenuItem исполнителиToolStripMenuItem; + private ToolStripMenuItem запускРаботToolStripMenuItem; + } } \ No newline at end of file diff --git a/CarpentryWorkshop/CarpentryWorkshop/FormMain.cs b/CarpentryWorkshop/CarpentryWorkshop/FormMain.cs index 5cdf9ef..1aa93ed 100644 --- a/CarpentryWorkshop/CarpentryWorkshop/FormMain.cs +++ b/CarpentryWorkshop/CarpentryWorkshop/FormMain.cs @@ -6,198 +6,214 @@ using Microsoft.Extensions.Logging; namespace CarpentryWorkshopView { - public partial class FormMain : Form - { - private readonly ILogger _logger; - private readonly IOrderLogic _orderLogic; - private readonly IReportLogic _reportLogic; - public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic) - { - InitializeComponent(); - _logger = logger; - _orderLogic = orderLogic; - _reportLogic = reportLogic; - } - private void FormMain_Load(object sender, EventArgs e) - { - LoadData(); - } - private void LoadData() - { - _logger.LogInformation("Загрузка заказов"); - try - { - var list = _orderLogic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["WoodId"].Visible = false; - dataGridView.Columns["WoodName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - dataGridView.Columns["ClientId"].Visible = false; - dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + public partial class FormMain : Form + { + private readonly ILogger _logger; + private readonly IOrderLogic _orderLogic; + private readonly IReportLogic _reportLogic; + private readonly IWorkProcess _workProcess; + public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess) + { + InitializeComponent(); + _logger = logger; + _orderLogic = orderLogic; + _reportLogic = reportLogic; + _workProcess = workProcess; + } + private void FormMain_Load(object sender, EventArgs e) + { + LoadData(); + } + private void LoadData() + { + _logger.LogInformation("Загрузка заказов"); + try + { + var list = _orderLogic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["WoodId"].Visible = false; + dataGridView.Columns["WoodName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + dataGridView.Columns["ImplementerId"].Visible = false; + dataGridView.Columns["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + _logger.LogInformation("Загрузка изделий"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки изделий"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + private void КомпонентыToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormComponents)); + if (service is FormComponents form) + { + form.ShowDialog(); + } + } + private void ИзделияToolStripMenuItem_Click(object sender, EventArgs e) + { + // прописать логику + var service = Program.ServiceProvider?.GetService(typeof(FormWoods)); + if (service is FormWoods form) + { + form.ShowDialog(); + } + } - } - _logger.LogInformation("Загрузка изделий"); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки изделий"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - private void КомпонентыToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormComponents)); - if (service is FormComponents form) - { - form.ShowDialog(); - } - } - private void ИзделияToolStripMenuItem_Click(object sender, EventArgs e) - { - // прописать логику - var service = Program.ServiceProvider?.GetService(typeof(FormWoods)); - if (service is FormWoods form) - { - form.ShowDialog(); - } - } + private void КлиентыToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormClients)); + if (service is FormClients form) + { + form.ShowDialog(); + } + } + private void ButtonCreateOrder_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); + if (service is FormCreateOrder form) + { + form.ShowDialog(); + LoadData(); + } + } - private void КлиентыToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormClients)); - if (service is FormClients form) - { - form.ShowDialog(); - } - } - private void ButtonCreateOrder_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); - if (service is FormCreateOrder form) - { - form.ShowDialog(); - LoadData(); - } - } + private OrderBindingModel CreateBindingModel(int id, bool isDone = false) + { + return new OrderBindingModel + { + Id = id, + WoodId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["WoodId"].Value), + ClientId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["ClientId"].Value), + Status = Enum.Parse(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()), + Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value), + Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()), + DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()), + }; + } - private OrderBindingModel CreateBindingModel(int id, bool isDone = false) - { - return new OrderBindingModel - { - Id = id, - WoodId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["WoodId"].Value), - ClientId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["ClientId"].Value), - Status = Enum.Parse(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()), - Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value), - Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()), - DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()), - }; - } + private void ButtonTakeOrderInWork_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id); + try + { + var operationResult = _orderLogic.TakeOrderInWork(CreateBindingModel(id)); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка передачи заказа в работу"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + private void ButtonOrderReady_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'", id); + try + { + var operationResult = _orderLogic.FinishOrder(CreateBindingModel(id)); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка отметки о готовности заказа"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + private void ButtonIssuedOrder_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id); + try + { + var operationResult = _orderLogic.DeliveryOrder(CreateBindingModel(id)); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + _logger.LogInformation("Заказ №{id} выдан", id); + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка отметки о выдачи заказа"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } - private void ButtonTakeOrderInWork_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id); - try - { - var operationResult = _orderLogic.TakeOrderInWork(CreateBindingModel(id)); - if (!operationResult) - { - throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); - } - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка передачи заказа в работу"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } - private void ButtonOrderReady_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'", id); - try - { - var operationResult = _orderLogic.FinishOrder(CreateBindingModel(id)); - if (!operationResult) - { - throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); - } - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка отметки о готовности заказа"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } - private void ButtonIssuedOrder_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id); - try - { - var operationResult = _orderLogic.DeliveryOrder(CreateBindingModel(id)); - if (!operationResult) - { - throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); - } - _logger.LogInformation("Заказ №{id} выдан", id); - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка отметки о выдачи заказа"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } + private void списокИзделийToolStripMenuItem_Click(object sender, EventArgs e) + { + using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; + if (dialog.ShowDialog() == DialogResult.OK) + { + _reportLogic.SaveComponentsToWordFile(new ReportBindingModel + { + FileName = dialog.FileName + }); + MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); + } - private void списокИзделийToolStripMenuItem_Click(object sender, EventArgs e) - { - using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; - if (dialog.ShowDialog() == DialogResult.OK) - { - _reportLogic.SaveComponentsToWordFile(new ReportBindingModel - { - FileName = dialog.FileName - }); - MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); - } + } - } + private void компонентыПоИзделиямToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReportWoodComponents)); + if (service is FormReportWoodComponents form) + { + form.ShowDialog(); + } - private void компонентыПоИзделиямToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormReportWoodComponents)); - if (service is FormReportWoodComponents form) - { - form.ShowDialog(); - } + } - } + private void списокЗаказовToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders)); + if (service is FormReportOrders form) + { + form.ShowDialog(); + } - private void списокЗаказовToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders)); - if (service is FormReportOrders form) - { - form.ShowDialog(); - } - - } - private void ButtonRef_Click(object sender, EventArgs e) - { - LoadData(); - } - } + } + private void ButtonRef_Click(object sender, EventArgs e) + { + LoadData(); + } + private void исполнителиToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormImplementers)); + if (service is FormImplementers form) + { + form.ShowDialog(); + } + } + private void запускРаботToolStripMenuItem_Click(object sender, EventArgs e) + { + _workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic); + MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } } diff --git a/CarpentryWorkshop/CarpentryWorkshop/Program.cs b/CarpentryWorkshop/CarpentryWorkshop/Program.cs index 495d12f..658d126 100644 --- a/CarpentryWorkshop/CarpentryWorkshop/Program.cs +++ b/CarpentryWorkshop/CarpentryWorkshop/Program.cs @@ -42,14 +42,17 @@ namespace CarpentryWorkshop services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); - services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); - services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -57,8 +60,10 @@ namespace CarpentryWorkshop services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); - services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); diff --git a/CarpentryWorkshop/CarpentryWorkshopBusinessLogic/BusinessLogics/ImplementerLogic.cs b/CarpentryWorkshop/CarpentryWorkshopBusinessLogic/BusinessLogics/ImplementerLogic.cs new file mode 100644 index 0000000..42a0ac4 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopBusinessLogic/BusinessLogics/ImplementerLogic.cs @@ -0,0 +1,118 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.BusinessLogicsContracts; +using CarpentryWorkshopContracts.SearchModels; +using CarpentryWorkshopContracts.StoragesContracts; +using CarpentryWorkshopContracts.ViewModels; +using Microsoft.Extensions.Logging; + +namespace CarpentryWorkshopBusinessLogic.BusinessLogics +{ + public class ImplementerLogic : IImplementerLogic + { + private readonly ILogger _logger; + private readonly IImplementerStorage _implementerStorage; + public ImplementerLogic(ILogger logger, IImplementerStorage implementerStorage) + { + _logger = logger; + _implementerStorage = implementerStorage; + } + public bool Create(ImplementerBindingModel model) + { + CheckImplementer(model); + if (_implementerStorage.Insert(model) == null) + { + _logger.LogWarning("Не получилось создать исполнителя"); + return false; + } + return true; + } + public bool Update(ImplementerBindingModel model) + { + CheckImplementer(model); + if (_implementerStorage.Update(model) == null) + { + _logger.LogWarning("Исправить исполнителя не получилось - люди не меняются"); + return false; + } + return true; + } + public bool Delete(ImplementerBindingModel model) + { + CheckImplementer(model, false); + _logger.LogInformation("Удаление. Id:{Id}", model.Id); + if (_implementerStorage.Delete(model) == null) + { + _logger.LogWarning("Не получилось удалить исполнителя..."); + return false; + } + return true; + } + + public ImplementerViewModel? ReadElement(ImplementerSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + _logger.LogInformation("Прочитали исполнителя: Id:{Id}.ImplementerFIO:{ImplementerFIO}", model.Id, model.ImplementerFIO); + var element = _implementerStorage.GetElement(model); + if (element == null) + { + _logger.LogWarning("не найден такой исполнитель"); + return null; + } + return element; + } + + public List? ReadList(ImplementerSearchModel? model) + { + var list = (model == null) ? _implementerStorage.GetFullList() : _implementerStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("нет исполнителей вообще-то"); + return null; + } + _logger.LogInformation("Прочитан список исполнителей. Количество:{Count}", list.Count); + return list; + } + + public void CheckImplementer(ImplementerBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (!withParams) + { + return; + } + if (string.IsNullOrEmpty(model.ImplementerFIO)) + { + throw new ArgumentNullException("Имя исполнителя не может быть пустым!", nameof(model.ImplementerFIO)); + } + if (model.WorkExperience <= 0) + { + throw new ArgumentNullException("Опыт работы не может быть меньше или равен 0 лет..."); + } + if (model.Qualification <= 0) + { + throw new ArgumentNullException("Квалификация не может быть меньше или равен 0 лет..."); + } + if (string.IsNullOrEmpty(model.Password)) + { + throw new ArgumentNullException("Пароль исполнителя не может быть пустым!", nameof(model.Password)); + } + _logger.LogInformation("Исполнитель. ImplementerFIO:{ImplementerFIO}. Password:{Password}. WorkExperience:{WorkExperience}. Id:{Id} ", model.ImplementerFIO, model.Password, model.WorkExperience, model.Id); + + var element = _implementerStorage.GetElement(new ImplementerSearchModel + { + ImplementerFIO = model.ImplementerFIO + }); + + if (element != null && element.Id != model.Id) + { + throw new InvalidOperationException("Исполнитель с такими ФИО уже есть."); + } + } + } +} diff --git a/CarpentryWorkshop/CarpentryWorkshopBusinessLogic/BusinessLogics/OrderLogic.cs b/CarpentryWorkshop/CarpentryWorkshopBusinessLogic/BusinessLogics/OrderLogic.cs index 23d52a5..1b0ab25 100644 --- a/CarpentryWorkshop/CarpentryWorkshopBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/CarpentryWorkshop/CarpentryWorkshopBusinessLogic/BusinessLogics/OrderLogic.cs @@ -12,14 +12,32 @@ namespace CarpentryWorkshopBusinessLogic.BusinessLogics { private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; + static readonly object blocking = new object(); - public OrderLogic(ILogger logger, IOrderStorage orderStorage) + public OrderLogic(ILogger logger, IOrderStorage orderStorage) { _logger = logger; _orderStorage = orderStorage; } - public List? ReadList(OrderSearchModel? model) + public OrderViewModel? ReadElement(OrderSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + _logger.LogInformation("ReadElement. Id:{Id}", model.Id); + var elem = _orderStorage.GetElement(model); + if (elem == null) + { + _logger.LogWarning("ReadElement element not found"); + return null; + } + _logger.LogInformation("ReadElement found. Id:{Id}", elem.Id); + return elem; + } + + public List? ReadList(OrderSearchModel? model) { _logger.LogInformation("ReadList. Id:{ Id}", model?.Id); var list = model == null ? _orderStorage.GetFullList() : @@ -50,7 +68,9 @@ namespace CarpentryWorkshopBusinessLogic.BusinessLogics { CheckModel(model); var element = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id }); - if (element == null) + if (element.ImplementerId.HasValue) + model.ImplementerId = element.ImplementerId; + if (element == null) { _logger.LogWarning("Read operation failed"); return false; @@ -68,8 +88,11 @@ namespace CarpentryWorkshopBusinessLogic.BusinessLogics public bool TakeOrderInWork(OrderBindingModel model) { - return ChangeStatus(model, OrderStatus.Выполняется); - } + lock (blocking) + { + return ChangeStatus(model, OrderStatus.Выполняется); + } + } public bool FinishOrder(OrderBindingModel model) { diff --git a/CarpentryWorkshop/CarpentryWorkshopBusinessLogic/BusinessLogics/WorkModeling.cs b/CarpentryWorkshop/CarpentryWorkshopBusinessLogic/BusinessLogics/WorkModeling.cs new file mode 100644 index 0000000..1450a5e --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopBusinessLogic/BusinessLogics/WorkModeling.cs @@ -0,0 +1,139 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.BusinessLogicsContracts; +using CarpentryWorkshopContracts.SearchModels; +using CarpentryWorkshopContracts.ViewModels; +using CarpentryWorkshopDataModels.Enums; +using Microsoft.Extensions.Logging; + +namespace CarpentryWorkshopBusinessLogic.BusinessLogics +{ + public class WorkModeling : IWorkProcess + { + private readonly ILogger _logger; + private readonly Random _rnd; + private IOrderLogic? _orderLogic; + public WorkModeling(ILogger logger) + { + _logger = logger; + _rnd = new Random(1000); + } + public void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic) + { + _orderLogic = orderLogic; + var implementers = implementerLogic.ReadList(null); + if (implementers == null) + { + _logger.LogWarning("DoWork. Исполнитель равен null"); + return; + } + var orders = _orderLogic.ReadList(new OrderSearchModel + { + Status = OrderStatus.Принят + }); + if (orders == null || orders.Count == 0) + { + _logger.LogWarning("DoWork. Orders is null or empty"); + return; + } + _logger.LogDebug("DoWork for {Count} orders", orders.Count); + foreach (var implementer in implementers) + { + Task.Run(() => WorkerWorkAsync(implementer, orders)); + } + } + /// + /// Иммитация работы исполнителя + /// + /// + /// + private async Task WorkerWorkAsync(ImplementerViewModel implementer, List orders) + { + if (_orderLogic == null || implementer == null) + { + return; + } + await RunOrderInWork(implementer); + await Task.Run(() => + { + foreach (var order in orders) + { + try + { + _logger.LogDebug("DoWork. Worker {Id} try get order {Order} ", implementer.Id, order.Id); + // пытаемся назначить заказ на исполнителя + _orderLogic.TakeOrderInWork(new OrderBindingModel + { + Id = order.Id, + ImplementerId = implementer.Id + }); + // делаем работу + Thread.Sleep(implementer.WorkExperience * _rnd.Next(100, 1000) * order.Count); + _logger.LogDebug("DoWork. Worker {Id} finish order {Order} ", implementer.Id, order.Id); + _orderLogic.FinishOrder(new OrderBindingModel + { + Id = order.Id, + }); + // отдыхаем + Thread.Sleep(implementer.Qualification * _rnd.Next(10, 100)); + } + // кто-то мог уже перехватить заказ, игнорируем ошибку + catch (InvalidOperationException ex) + { + _logger.LogWarning(ex, "Error try get work"); + } + // заканчиваем выполнение имитации в случае иной ошибки + catch (Exception ex) + { + _logger.LogError(ex, "Error while do work"); + throw; + } + } + }); + } + /// + /// Ищем заказ, которые уже в работе (вдруг исполнителя прервали) + /// + /// + /// + private async Task RunOrderInWork(ImplementerViewModel implementer) + { + if (_orderLogic == null || implementer == null) + { + return; + } + try + { + var runOrder = await Task.Run(() => _orderLogic.ReadElement(new OrderSearchModel + { + ImplementerId = implementer.Id, + Status = OrderStatus.Выполняется + })); + if (runOrder == null) + { + return; + } + _logger.LogDebug("DoWork. Worker {Id} back to order {Order}", implementer.Id, runOrder.Id); + // доделываем работу + Thread.Sleep(implementer.WorkExperience * _rnd.Next(100, 300) * runOrder.Count); + _logger.LogDebug("DoWork. Worker {Id} finish order {Order}", implementer.Id, runOrder.Id); + _orderLogic.FinishOrder(new OrderBindingModel + { + Id = runOrder.Id + }); + // отдыхаем + Thread.Sleep(implementer.Qualification * _rnd.Next(10, 100)); + } + // заказа может не быть, просто игнорируем ошибку + catch (InvalidOperationException ex) + { + _logger.LogWarning(ex, "Error try get work"); + } + // а может возникнуть иная ошибка, тогда просто заканчиваем выполнение имитации + catch (Exception ex) + { + _logger.LogError(ex, "Error while do work"); + throw; + } + } + } +} diff --git a/CarpentryWorkshop/CarpentryWorkshopContracts/BindingModels/ImplementerBindingModel.cs b/CarpentryWorkshop/CarpentryWorkshopContracts/BindingModels/ImplementerBindingModel.cs new file mode 100644 index 0000000..d69b480 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopContracts/BindingModels/ImplementerBindingModel.cs @@ -0,0 +1,13 @@ +using CarpentryWorkshopDataModels.Models; + +namespace CarpentryWorkshopContracts.BindingModels +{ + public class ImplementerBindingModel : IImplementerModel + { + public int Id { get; set; } + public string ImplementerFIO { get; set; } = string.Empty; + public string Password { get; set; } = string.Empty; + public int WorkExperience { get; set; } + public int Qualification { get; set; } + } +} diff --git a/CarpentryWorkshop/CarpentryWorkshopContracts/BindingModels/OrderBindingModel.cs b/CarpentryWorkshop/CarpentryWorkshopContracts/BindingModels/OrderBindingModel.cs index 9028d5d..b5adc0c 100644 --- a/CarpentryWorkshop/CarpentryWorkshopContracts/BindingModels/OrderBindingModel.cs +++ b/CarpentryWorkshop/CarpentryWorkshopContracts/BindingModels/OrderBindingModel.cs @@ -8,8 +8,10 @@ namespace CarpentryWorkshopContracts.BindingModels public int Id { get; set; } public int WoodId { get; set; } public int ClientId { get; set; } - public string ClientFIO { get; set; } = string.Empty; - public int Count { get; set; } + public int? ImplementerId { get; set; } + public string ClientFIO { get; set; } = string.Empty; + public string? ImplementerFIO { get; set; } = string.Empty; + public int Count { get; set; } public double Sum { get; set; } public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; public DateTime DateCreate { get; set; } = DateTime.Now; diff --git a/CarpentryWorkshop/CarpentryWorkshopContracts/BusinessLogicsContracts/IImplementerLogic.cs b/CarpentryWorkshop/CarpentryWorkshopContracts/BusinessLogicsContracts/IImplementerLogic.cs new file mode 100644 index 0000000..a4b1a7c --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopContracts/BusinessLogicsContracts/IImplementerLogic.cs @@ -0,0 +1,15 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.SearchModels; +using CarpentryWorkshopContracts.ViewModels; + +namespace CarpentryWorkshopContracts.BusinessLogicsContracts +{ + public interface IImplementerLogic + { + List? ReadList(ImplementerSearchModel? model); + ImplementerViewModel? ReadElement(ImplementerSearchModel model); + bool Create(ImplementerBindingModel model); + bool Update(ImplementerBindingModel model); + bool Delete(ImplementerBindingModel model); + } +} diff --git a/CarpentryWorkshop/CarpentryWorkshopContracts/BusinessLogicsContracts/IOrderLogic.cs b/CarpentryWorkshop/CarpentryWorkshopContracts/BusinessLogicsContracts/IOrderLogic.cs index 07a7c17..3b90a15 100644 --- a/CarpentryWorkshop/CarpentryWorkshopContracts/BusinessLogicsContracts/IOrderLogic.cs +++ b/CarpentryWorkshop/CarpentryWorkshopContracts/BusinessLogicsContracts/IOrderLogic.cs @@ -6,7 +6,8 @@ namespace CarpentryWorkshopContracts.BusinessLogicsContracts { public interface IOrderLogic { - List? ReadList(OrderSearchModel? model); + OrderViewModel? ReadElement(OrderSearchModel model); + List? ReadList(OrderSearchModel? model); bool CreateOrder(OrderBindingModel model); bool TakeOrderInWork(OrderBindingModel model); bool FinishOrder(OrderBindingModel model); diff --git a/CarpentryWorkshop/CarpentryWorkshopContracts/BusinessLogicsContracts/IWorkProcess.cs b/CarpentryWorkshop/CarpentryWorkshopContracts/BusinessLogicsContracts/IWorkProcess.cs new file mode 100644 index 0000000..80391f4 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopContracts/BusinessLogicsContracts/IWorkProcess.cs @@ -0,0 +1,10 @@ +namespace CarpentryWorkshopContracts.BusinessLogicsContracts +{ + public interface IWorkProcess + { + /// + /// Запуск работ + /// + void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic); + } +} diff --git a/CarpentryWorkshop/CarpentryWorkshopContracts/SearchModels/ImplementerSearchModel.cs b/CarpentryWorkshop/CarpentryWorkshopContracts/SearchModels/ImplementerSearchModel.cs new file mode 100644 index 0000000..58de093 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopContracts/SearchModels/ImplementerSearchModel.cs @@ -0,0 +1,9 @@ +namespace CarpentryWorkshopContracts.SearchModels +{ + public class ImplementerSearchModel + { + public int? Id { get; set; } + public string? ImplementerFIO { get; set; } + public string? Password { get; set; } + } +} diff --git a/CarpentryWorkshop/CarpentryWorkshopContracts/SearchModels/OrderSearchModel.cs b/CarpentryWorkshop/CarpentryWorkshopContracts/SearchModels/OrderSearchModel.cs index 39520f2..9070aa4 100644 --- a/CarpentryWorkshop/CarpentryWorkshopContracts/SearchModels/OrderSearchModel.cs +++ b/CarpentryWorkshop/CarpentryWorkshopContracts/SearchModels/OrderSearchModel.cs @@ -1,4 +1,6 @@ -namespace CarpentryWorkshopContracts.SearchModels +using CarpentryWorkshopDataModels.Enums; + +namespace CarpentryWorkshopContracts.SearchModels { public class OrderSearchModel { @@ -6,5 +8,7 @@ public DateTime? DateFrom { get; set; } public DateTime? DateTo { get; set; } public int? ClientId { get; set; } - } + public int? ImplementerId { get; set; } + public OrderStatus? Status { get; set; } + } } \ No newline at end of file diff --git a/CarpentryWorkshop/CarpentryWorkshopContracts/StoragesContracts/IImplementerStorage.cs b/CarpentryWorkshop/CarpentryWorkshopContracts/StoragesContracts/IImplementerStorage.cs new file mode 100644 index 0000000..ffaea23 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopContracts/StoragesContracts/IImplementerStorage.cs @@ -0,0 +1,16 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.SearchModels; +using CarpentryWorkshopContracts.ViewModels; + +namespace CarpentryWorkshopContracts.StoragesContracts +{ + public interface IImplementerStorage + { + List GetFullList(); + List GetFilteredList(ImplementerSearchModel model); + ImplementerViewModel? GetElement(ImplementerSearchModel model); + ImplementerViewModel? Insert(ImplementerBindingModel model); + ImplementerViewModel? Update(ImplementerBindingModel model); + ImplementerViewModel? Delete(ImplementerBindingModel model); + } +} diff --git a/CarpentryWorkshop/CarpentryWorkshopContracts/ViewModels/ImplementerViewModel.cs b/CarpentryWorkshop/CarpentryWorkshopContracts/ViewModels/ImplementerViewModel.cs new file mode 100644 index 0000000..2627c9e --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopContracts/ViewModels/ImplementerViewModel.cs @@ -0,0 +1,21 @@ +using CarpentryWorkshopDataModels.Models; +using System.ComponentModel; + +namespace CarpentryWorkshopContracts.ViewModels +{ + public class ImplementerViewModel : IImplementerModel + { + public int Id { get; set; } + [DisplayName("Исполнитель ФИО")] + public string ImplementerFIO { get; set; } = string.Empty; + + [DisplayName("Пароль")] + public string Password { get; set; } = string.Empty; + + [DisplayName("Опыт работы")] + public int WorkExperience { get; set; } + + [DisplayName("Квалификация")] + public int Qualification { get; set; } + } +} diff --git a/CarpentryWorkshop/CarpentryWorkshopContracts/ViewModels/OrderViewModel.cs b/CarpentryWorkshop/CarpentryWorkshopContracts/ViewModels/OrderViewModel.cs index 6466268..ce52937 100644 --- a/CarpentryWorkshop/CarpentryWorkshopContracts/ViewModels/OrderViewModel.cs +++ b/CarpentryWorkshop/CarpentryWorkshopContracts/ViewModels/OrderViewModel.cs @@ -14,7 +14,10 @@ namespace CarpentryWorkshopContracts.ViewModels public int ClientId { get; set; } [DisplayName("Клиент")] public string ClientFIO { get; set; } = string.Empty; - [DisplayName("Количество")] + public int? ImplementerId { get; set; } + [DisplayName("Имя исполнителя")] + public string? ImplementerFIO { get; set; } + [DisplayName("Количество")] public int Count { get; set; } [DisplayName("Сумма")] public double Sum { get; set; } diff --git a/CarpentryWorkshop/CarpentryWorkshopDataModels/Models/IImplementerModel.cs b/CarpentryWorkshop/CarpentryWorkshopDataModels/Models/IImplementerModel.cs new file mode 100644 index 0000000..5ea830c --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopDataModels/Models/IImplementerModel.cs @@ -0,0 +1,10 @@ +namespace CarpentryWorkshopDataModels.Models +{ + public interface IImplementerModel : IId + { + string ImplementerFIO { get; } + string Password { get; } + int WorkExperience { get; } + int Qualification { get; } + } +} diff --git a/CarpentryWorkshop/CarpentryWorkshopDataModels/Models/IOrderModel.cs b/CarpentryWorkshop/CarpentryWorkshopDataModels/Models/IOrderModel.cs index e19c2aa..c60e29b 100644 --- a/CarpentryWorkshop/CarpentryWorkshopDataModels/Models/IOrderModel.cs +++ b/CarpentryWorkshop/CarpentryWorkshopDataModels/Models/IOrderModel.cs @@ -8,7 +8,9 @@ namespace CarpentryWorkshopDataModels.Models int ClientId { get; } - int Count { get; } + int? ImplementerId { get; } + + int Count { get; } double Sum { get; } diff --git a/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/CarpentryWorkshopDatabase.cs b/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/CarpentryWorkshopDatabase.cs index 1a399d1..c9e29ba 100644 --- a/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/CarpentryWorkshopDatabase.cs +++ b/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/CarpentryWorkshopDatabase.cs @@ -18,5 +18,6 @@ namespace CarpentryWorkshopDatabaseImplement public virtual DbSet WoodComponents { set; get; } public virtual DbSet Orders { set; get; } public virtual DbSet Clients { set; get; } - } + public virtual DbSet Implementers { set; get; } + } } diff --git a/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Implements/ImplementerStorage.cs b/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Implements/ImplementerStorage.cs new file mode 100644 index 0000000..ad9d31b --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Implements/ImplementerStorage.cs @@ -0,0 +1,84 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.SearchModels; +using CarpentryWorkshopContracts.StoragesContracts; +using CarpentryWorkshopContracts.ViewModels; +using CarpentryWorkshopDatabaseImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CarpentryWorkshopDatabaseImplement.Implements +{ + public class ImplementerStorage : IImplementerStorage + { + public ImplementerViewModel? GetElement(ImplementerSearchModel model) + { + using var context = new CarpentryWorkshopDatabase(); + if (model.Id.HasValue) return context.Implementers.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; + if (model.ImplementerFIO != null && model.Password != null) return context.Implementers.FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO) && x.Password.Equals(model.Password))?.GetViewModel; + if (model.ImplementerFIO != null) return context.Implementers.FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO))?.GetViewModel; + return null; + } + + public List GetFilteredList(ImplementerSearchModel model) + { + if (model == null) + { + return new(); + } + if (model.ImplementerFIO != null) + { + using var context = new CarpentryWorkshopDatabase(); + return context.Implementers + .Where(x => x.ImplementerFIO.Contains(model.ImplementerFIO)) + .Select(x => x.GetViewModel) + .ToList(); + } + return new(); + } + + public List GetFullList() + { + using var context = new CarpentryWorkshopDatabase(); + return context.Implementers.Select(x => x.GetViewModel).ToList(); + } + + public ImplementerViewModel? Insert(ImplementerBindingModel model) + { + using var context = new CarpentryWorkshopDatabase(); + var res = Implementer.Create(model); + if (res != null) + { + context.Implementers.Add(res); + context.SaveChanges(); + } + return res?.GetViewModel; + } + + public ImplementerViewModel? Update(ImplementerBindingModel model) + { + using var context = new CarpentryWorkshopDatabase(); + var res = context.Implementers.FirstOrDefault(x => x.Id == model.Id); + if (res != null) + { + res.Update(model); + context.SaveChanges(); + } + return res?.GetViewModel; + } + + public ImplementerViewModel? Delete(ImplementerBindingModel model) + { + using var context = new CarpentryWorkshopDatabase(); + var res = context.Implementers.FirstOrDefault(x => x.Id == model.Id); + if (res != null) + { + context.Implementers.Remove(res); + context.SaveChanges(); + } + return res?.GetViewModel; + } + } +} diff --git a/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Implements/OrderStorage.cs b/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Implements/OrderStorage.cs index ef8187b..f4e2c9f 100644 --- a/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Implements/OrderStorage.cs +++ b/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Implements/OrderStorage.cs @@ -16,28 +16,45 @@ namespace CarpentryWorkshopDatabaseImplement.Implements return null; } using var context = new CarpentryWorkshopDatabase(); - return context.Orders.Include(x => x.Wood).Include(x => x.Client).FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; + return context.Orders + .Include(x => x.Wood) + .Include(x => x.Client) + .Include(x => x.Implementer) + .FirstOrDefault(x => ( + model.Status == null || + model.Status != null && + model.Status.Equals(x.Status)) && + (model.ImplementerId.HasValue && x.ImplementerId == model.ImplementerId) || + (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; } public List GetFilteredList(OrderSearchModel model) { - if (!model.Id.HasValue && !model.DateFrom.HasValue && !model.DateTo.HasValue && !model.ClientId.HasValue) + if (!model.Id.HasValue && !model.DateFrom.HasValue && !model.DateTo.HasValue && !model.ClientId.HasValue && model.Status == null) { return new(); } using var context = new CarpentryWorkshopDatabase(); return context.Orders - .Where(x => x.Id == model.Id || model.DateFrom <= x.DateCreate && x.DateCreate <= model.DateTo || x.ClientId == model.ClientId) + .Where(x => x.Id == model.Id + || model.DateFrom <= x.DateCreate && x.DateCreate <= model.DateTo + || x.ClientId == model.ClientId + || model.Status.Equals(x.Status)) .Include(x => x.Wood) .Include(x => x.Client) - .Select(x => x.GetViewModel) + .Include(x => x.Implementer) + .Select(x => x.GetViewModel) .ToList(); } public List GetFullList() { using var context = new CarpentryWorkshopDatabase(); - return context.Orders.Include(x => x.Wood).Include(x => x.Client).Select(x => x.GetViewModel).ToList(); ; + return context.Orders + .Include(x => x.Wood) + .Include(x => x.Client) + .Include(x => x.Implementer) + .Select(x => x.GetViewModel).ToList(); } public OrderViewModel? Insert(OrderBindingModel model) @@ -50,7 +67,11 @@ namespace CarpentryWorkshopDatabaseImplement.Implements using var context = new CarpentryWorkshopDatabase(); context.Orders.Add(newOrder); context.SaveChanges(); - return context.Orders.Include(x => x.Wood).Include(x => x.Client).FirstOrDefault(x => x.Id == newOrder.Id)?.GetViewModel; + return context.Orders + .Include(x => x.Wood) + .Include(x => x.Client) + .Include(x => x.Implementer) + .FirstOrDefault(x => x.Id == newOrder.Id)?.GetViewModel; } public OrderViewModel? Update(OrderBindingModel model) @@ -63,7 +84,11 @@ namespace CarpentryWorkshopDatabaseImplement.Implements } order.Update(model); context.SaveChanges(); - return context.Orders.Include(x => x.Wood).Include(x => x.Client).FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; + return context.Orders + .Include(x => x.Wood) + .Include(x => x.Client) + .Include(x => x.Implementer) + .FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; } public OrderViewModel? Delete(OrderBindingModel model) { diff --git a/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Models/Implementer.cs b/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Models/Implementer.cs new file mode 100644 index 0000000..a64093f --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Models/Implementer.cs @@ -0,0 +1,63 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.ViewModels; +using CarpentryWorkshopDataModels.Models; +using System.ComponentModel.DataAnnotations.Schema; +using System.ComponentModel.DataAnnotations; + +namespace CarpentryWorkshopDatabaseImplement.Models +{ + public class Implementer : IImplementerModel + { + public int Id { get; private set; } + + [Required] + public string ImplementerFIO { get; private set; } = string.Empty; + + [Required] + public string Password { get; private set; } = string.Empty; + + [Required] + public int WorkExperience { get; private set; } + + [Required] + public int Qualification { get; private set; } + + [Required] + [ForeignKey("ImplementerId")] + public virtual List Orders { get; set; } = new(); + + public static Implementer? Create(ImplementerBindingModel? model) + { + if (model == null) + { + return null; + } + return new Implementer() + { + Id = model.Id, + ImplementerFIO = model.ImplementerFIO, + WorkExperience = model.WorkExperience, + Password = model.Password, + Qualification = model.Qualification, + }; + } + + public void Update(ImplementerBindingModel? model) + { + if (model == null) return; + ImplementerFIO = model.ImplementerFIO; + WorkExperience = model.WorkExperience; + Password = model.Password; + Qualification = model.Qualification; + } + + public ImplementerViewModel GetViewModel => new() + { + Id = Id, + ImplementerFIO = ImplementerFIO, + WorkExperience = WorkExperience, + Password = Password, + Qualification = Qualification, + }; + } +} diff --git a/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Models/Order.cs b/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Models/Order.cs index 462d76e..e9f1afc 100644 --- a/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Models/Order.cs +++ b/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Models/Order.cs @@ -13,7 +13,8 @@ namespace CarpentryWorkshopDatabaseImplement.Models public int WoodId { get; private set; } [Required] public int ClientId { get; private set; } - [Required] + public int? ImplementerId { get; set; } + [Required] public int Count { get; private set; } [Required] public double Sum { get; private set; } @@ -23,10 +24,11 @@ namespace CarpentryWorkshopDatabaseImplement.Models public DateTime DateCreate { get; private set; } = DateTime.Now; public DateTime? DateImplement { get; private set; } - public virtual Wood Wood { get; private set; } - public virtual Client Client { get; set; } + public virtual Wood? Wood { get; private set; } + public virtual Client? Client { get; set; } + public virtual Implementer? Implementer { get; set; } - public static Order? Create(OrderBindingModel? model) + public static Order? Create(OrderBindingModel? model) { if (model == null) { @@ -41,7 +43,8 @@ namespace CarpentryWorkshopDatabaseImplement.Models Status = model.Status, DateCreate = model.DateCreate, DateImplement = model.DateImplement, - Id = model.Id, + ImplementerId = model.ImplementerId, + Id = model.Id, }; } @@ -53,20 +56,23 @@ namespace CarpentryWorkshopDatabaseImplement.Models } Status = model.Status; DateImplement = model.DateImplement; - } + ImplementerId = model.ImplementerId; + } public OrderViewModel GetViewModel => new() { WoodId = WoodId, ClientId = ClientId, - ClientFIO = Client.ClientFIO, - Count = Count, + ClientFIO = Client?.ClientFIO ?? string.Empty, + Count = Count, Sum = Sum, DateCreate = DateCreate, DateImplement = DateImplement, Id = Id, Status = Status, - WoodName = Wood.WoodName - }; + WoodName = Wood?.WoodName ?? string.Empty, + ImplementerId = ImplementerId, + ImplementerFIO = Implementer?.ImplementerFIO ?? string.Empty + }; } } diff --git a/CarpentryWorkshop/CarpentryWorkshopFileImplement/DataFileSingleton.cs b/CarpentryWorkshop/CarpentryWorkshopFileImplement/DataFileSingleton.cs index a0f6b03..5c2fcda 100644 --- a/CarpentryWorkshop/CarpentryWorkshopFileImplement/DataFileSingleton.cs +++ b/CarpentryWorkshop/CarpentryWorkshopFileImplement/DataFileSingleton.cs @@ -10,11 +10,13 @@ namespace CarpentryWorkshopFileImplement private readonly string OrderFileName = "Order.xml"; private readonly string WoodFileName = "Wood.xml"; private readonly string ClientFileName = "Client.xml"; - public List Components { get; private set; } + private readonly string ImplementerFileName = "Implementer.xml"; + public List Components { get; private set; } public List Orders { get; private set; } public List Woods { get; private set; } public List Clients { get; private set; } - public static DataFileSingleton GetInstance() + public List Implementers { get; private set; } + public static DataFileSingleton GetInstance() { if (instance == null) { @@ -30,7 +32,9 @@ namespace CarpentryWorkshopFileImplement "Orders", x => x.GetXElement); public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", x => x.GetXElement); - private DataFileSingleton() + public void SaveImplementers() => SaveData(Implementers, ImplementerFileName, + "Implementers", x => x.GetXElement); + private DataFileSingleton() { Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!; @@ -40,7 +44,9 @@ namespace CarpentryWorkshopFileImplement Order.Create(x)!)!; Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!; - } + Implementers = LoadData(ImplementerFileName, "Implementer", + x => Implementer.Create(x)!)!; + } private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) { diff --git a/CarpentryWorkshop/CarpentryWorkshopFileImplement/Implements/ImplementerStorage.cs b/CarpentryWorkshop/CarpentryWorkshopFileImplement/Implements/ImplementerStorage.cs new file mode 100644 index 0000000..cea4fd4 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopFileImplement/Implements/ImplementerStorage.cs @@ -0,0 +1,72 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.SearchModels; +using CarpentryWorkshopContracts.StoragesContracts; +using CarpentryWorkshopContracts.ViewModels; +using CarpentryWorkshopFileImplement.Models; + +namespace CarpentryWorkshopFileImplement.Implements +{ + public class ImplementerStorage : IImplementerStorage + { + private readonly DataFileSingleton source; + public ImplementerStorage() + { + source = DataFileSingleton.GetInstance(); + } + public List GetFullList() + { + return source.Implementers.Select(x => x.GetViewModel).ToList(); + } + public List GetFilteredList(ImplementerSearchModel model) + { + if (string.IsNullOrEmpty(model.ImplementerFIO)) + { + return new(); + } + return source.Implementers.Where(x => x.ImplementerFIO.Contains(model.ImplementerFIO)).Select(x => x.GetViewModel).ToList(); + } + public ImplementerViewModel? GetElement(ImplementerSearchModel model) + { + if (string.IsNullOrEmpty(model.ImplementerFIO) && !model.Id.HasValue) + { + return null; + } + return source.Implementers.FirstOrDefault(x => (!string.IsNullOrEmpty(model.ImplementerFIO) && + x.ImplementerFIO == model.ImplementerFIO) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; + } + public ImplementerViewModel? Insert(ImplementerBindingModel model) + { + model.Id = source.Implementers.Count > 0 ? source.Implementers.Max(x => x.Id) + 1 : 1; + var newImplementer = Implementer.Create(model); + if (newImplementer == null) + { + return null; + } + source.Implementers.Add(newImplementer); + source.SaveImplementers(); + return newImplementer.GetViewModel; + } + public ImplementerViewModel? Update(ImplementerBindingModel model) + { + var client = source.Implementers.FirstOrDefault(x => x.Id == model.Id); + if (client == null) + { + return null; + } + client.Update(model); + source.SaveImplementers(); + return client.GetViewModel; + } + public ImplementerViewModel? Delete(ImplementerBindingModel model) + { + var element = source.Implementers.FirstOrDefault(x => x.Id == model.Id); + if (element != null) + { + source.Implementers.Remove(element); + source.SaveImplementers(); + return element.GetViewModel; + } + return null; + } + } +} diff --git a/CarpentryWorkshop/CarpentryWorkshopFileImplement/Models/Implementer.cs b/CarpentryWorkshop/CarpentryWorkshopFileImplement/Models/Implementer.cs new file mode 100644 index 0000000..80280fa --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopFileImplement/Models/Implementer.cs @@ -0,0 +1,73 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.ViewModels; +using CarpentryWorkshopDataModels.Models; +using System.Xml.Linq; + +namespace CarpentryWorkshopFileImplement.Models +{ + public class Implementer : IImplementerModel + { + public int Id { get; private set; } + public string ImplementerFIO { get; private set; } = string.Empty; + public string Password { get; private set; } = string.Empty; + public int WorkExperience { get; private set; } + public int Qualification { get; private set; } + public static Implementer? Create(ImplementerBindingModel model) + { + if (model == null) + { + return null; + } + return new Implementer() + { + Id = model.Id, + ImplementerFIO = model.ImplementerFIO, + WorkExperience = model.WorkExperience, + Password = model.Password, + Qualification = model.Qualification, + }; + } + public static Implementer? Create(XElement element) + { + if (element == null) + { + return null; + } + return new Implementer() + { + Id = Convert.ToInt32(element.Attribute("Id")!.Value), + ImplementerFIO = element.Element("ImplementerFIO")!.Value, + WorkExperience = Convert.ToInt32(element.Element("WorkExperience")!.Value), + Password = element.Element("Password")!.Value, + Qualification = Convert.ToInt32(element.Element("Qualification")!.Value), + }; + } + public void Update(ImplementerBindingModel model) + { + if (model == null) + { + return; + } + ImplementerFIO = model.ImplementerFIO; + Qualification = model.Qualification; + Password = model.Password; + WorkExperience = model.WorkExperience; + } + public ImplementerViewModel GetViewModel => new() + { + Id = Id, + ImplementerFIO = ImplementerFIO, + WorkExperience = WorkExperience, + Password = Password, + Qualification = Qualification + }; + public XElement GetXElement => + new("Implementer", + new XAttribute("Id", Id), + new XElement("ImplementerFIO", ImplementerFIO), + new XElement("WorkExperience", WorkExperience), + new XElement("Password", Password), + new XElement("Qualification", Qualification) + ); + } +} diff --git a/CarpentryWorkshop/CarpentryWorkshopFileImplement/Models/Order.cs b/CarpentryWorkshop/CarpentryWorkshopFileImplement/Models/Order.cs index b6a1893..feef652 100644 --- a/CarpentryWorkshop/CarpentryWorkshopFileImplement/Models/Order.cs +++ b/CarpentryWorkshop/CarpentryWorkshopFileImplement/Models/Order.cs @@ -12,7 +12,8 @@ namespace CarpentryWorkshopFileImplement.Models public int Id { get; private set; } public int WoodId { get; private set; } public int ClientId { get; private set; } - public int Count { get; private set; } + public int? ImplementerId { get; private set; } + public int Count { get; private set; } public double Sum { get; private set; } public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен; public DateTime DateCreate { get; private set; } = DateTime.Now; @@ -32,8 +33,9 @@ namespace CarpentryWorkshopFileImplement.Models Sum = model.Sum, Status = model.Status, DateCreate = model.DateCreate, - DateImplement = model.DateImplement - }; + DateImplement = model.DateImplement, + ImplementerId = model.ImplementerId + }; } public static Order? Create(XElement element) { @@ -48,7 +50,8 @@ namespace CarpentryWorkshopFileImplement.Models ClientId = Convert.ToInt32(element.Element("ClientId")!.Value), Count = Convert.ToInt32(element.Element("Count")!.Value), Sum = Convert.ToDouble(element.Element("Sum")!.Value), - Status = (OrderStatus)Convert.ToInt32(element.Element("Status").Value), + ImplementerId = Convert.ToInt32(element.Element("ImplementerId")!.Value), + Status = (OrderStatus)Convert.ToInt32(element.Element("Status").Value), DateCreate = Convert.ToDateTime(element.Element("DateCreate").Value), DateImplement = String.IsNullOrEmpty(element.Element("DateImplement").Value) ? DateTime.MinValue : Convert.ToDateTime(element.Element("DateImplement").Value) }; @@ -67,6 +70,7 @@ namespace CarpentryWorkshopFileImplement.Models Status = model.Status; DateCreate = model.DateCreate; DateImplement = model.DateImplement; + ImplementerId = model.ImplementerId; } public OrderViewModel GetViewModel => new() { @@ -78,12 +82,14 @@ namespace CarpentryWorkshopFileImplement.Models Status = Status, DateCreate = DateCreate, DateImplement = DateImplement, - }; + ImplementerId = ImplementerId, + }; public XElement GetXElement => new("Order", new XAttribute("Id", Id), new XElement("WoodId", WoodId), new XElement("ClientId", ClientId), - new XElement("Count", Count), + new XElement("ImplementerId", ImplementerId), + new XElement("Count", Count), new XElement("Sum", Sum.ToString()), new XElement("Status", (int)Status), new XElement("DateCreate", DateCreate), diff --git a/CarpentryWorkshop/CarpentryWorkshopListImplement/DataListSingleton.cs b/CarpentryWorkshop/CarpentryWorkshopListImplement/DataListSingleton.cs index 41c3e5e..aed78f9 100644 --- a/CarpentryWorkshop/CarpentryWorkshopListImplement/DataListSingleton.cs +++ b/CarpentryWorkshop/CarpentryWorkshopListImplement/DataListSingleton.cs @@ -9,13 +9,15 @@ namespace CarpentryWorkshopListImplement public List Orders { get; set; } public List Woods { get; set; } public List Clients { get; set; } - private DataListSingleton() + public List Implementers { get; set; } + private DataListSingleton() { Components = new List(); Orders = new List(); Woods = new List(); Clients = new List(); - } + Implementers = new List(); + } public static DataListSingleton GetInstance() { if (_instance == null) diff --git a/CarpentryWorkshop/CarpentryWorkshopListImplement/Implements/ImplementerStorage.cs b/CarpentryWorkshop/CarpentryWorkshopListImplement/Implements/ImplementerStorage.cs new file mode 100644 index 0000000..5f94716 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopListImplement/Implements/ImplementerStorage.cs @@ -0,0 +1,101 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.SearchModels; +using CarpentryWorkshopContracts.StoragesContracts; +using CarpentryWorkshopContracts.ViewModels; +using CarpentryWorkshopListImplement.Models; + +namespace CarpentryWorkshopListImplement.Implements +{ + public class ImplementerStorage : IImplementerStorage + { + private readonly DataListSingleton _source; + public ImplementerStorage() + { + _source = DataListSingleton.GetInstance(); + } + public List GetFullList() + { + var result = new List(); + foreach (var implementer in _source.Implementers) + { + result.Add(implementer.GetViewModel); + } + return result; + } + public List GetFilteredList(ImplementerSearchModel model) + { + var result = new List(); + if (string.IsNullOrEmpty(model.ImplementerFIO)) + { + return result; + } + foreach (var implementer in _source.Implementers) + { + if (implementer.ImplementerFIO.Contains(model.ImplementerFIO)) + { + result.Add(implementer.GetViewModel); + } + } + return result; + } + public ImplementerViewModel? GetElement(ImplementerSearchModel model) + { + if (string.IsNullOrEmpty(model.ImplementerFIO) && !model.Id.HasValue) + { + return null; + } + foreach (var implementer in _source.Implementers) + { + if (!string.IsNullOrEmpty(model.ImplementerFIO) && implementer.ImplementerFIO == model.ImplementerFIO || + model.Id.HasValue && implementer.ImplementerFIO == model.ImplementerFIO) + { + return implementer.GetViewModel; + } + } + return null; + } + public ImplementerViewModel? Insert(ImplementerBindingModel model) + { + model.Id = 1; + foreach (var implementer in _source.Implementers) + { + if (model.Id <= implementer.Id) + { + model.Id = implementer.Id + 1; + } + } + var newImplementer = Implementer.Create(model); + if (newImplementer == null) + { + return null; + } + _source.Implementers.Add(newImplementer); + return newImplementer.GetViewModel; + } + public ImplementerViewModel? Update(ImplementerBindingModel model) + { + foreach (var implementer in _source.Implementers) + { + if (implementer.Id == model.Id) + { + implementer.Update(model); + return implementer.GetViewModel; + } + } + return null; + } + public ImplementerViewModel? Delete(ImplementerBindingModel model) + { + for (int i = 0; i < _source.Implementers.Count; ++i) + { + if (_source.Implementers[i].Id == model.Id) + { + var element = _source.Implementers[i]; + _source.Implementers.RemoveAt(i); + return element.GetViewModel; + } + } + return null; + } + } +} diff --git a/CarpentryWorkshop/CarpentryWorkshopListImplement/Models/Implementer.cs b/CarpentryWorkshop/CarpentryWorkshopListImplement/Models/Implementer.cs new file mode 100644 index 0000000..1ac36dc --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopListImplement/Models/Implementer.cs @@ -0,0 +1,50 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.ViewModels; +using CarpentryWorkshopDataModels.Models; + +namespace CarpentryWorkshopListImplement.Models +{ + public class Implementer : IImplementerModel + { + public int Id { get; private set; } + public string ImplementerFIO { get; private set; } = string.Empty; + public string Password { get; set; } = string.Empty; + public int WorkExperience { get; set; } + public int Qualification { get; set; } + + public static Implementer? Create(ImplementerBindingModel? model) + { + if (model == null) + { + return null; + } + return new Implementer() + { + Id = model.Id, + ImplementerFIO = model.ImplementerFIO, + WorkExperience = model.WorkExperience, + Qualification = model.Qualification, + Password = model.Password, + }; + } + public void Update(ImplementerBindingModel? model) + { + if (model == null) + { + return; + } + ImplementerFIO = model.ImplementerFIO; + Password = model.Password; + WorkExperience = model.WorkExperience; + Qualification = model.Qualification; + } + public ImplementerViewModel GetViewModel => new() + { + Id = Id, + ImplementerFIO = ImplementerFIO, + WorkExperience = WorkExperience, + Password = Password, + Qualification = Qualification, + }; + } +} diff --git a/CarpentryWorkshop/CarpentryWorkshopListImplement/Models/Order.cs b/CarpentryWorkshop/CarpentryWorkshopListImplement/Models/Order.cs index 9940aa6..8942ecf 100644 --- a/CarpentryWorkshop/CarpentryWorkshopListImplement/Models/Order.cs +++ b/CarpentryWorkshop/CarpentryWorkshopListImplement/Models/Order.cs @@ -11,7 +11,8 @@ namespace CarpentryWorkshopListImplement.Models public int Id { get; set; } public int WoodId { get; set; } public int ClientId { get; set; } - public int Count { get; set; } + public int? ImplementerId { get; private set; } + public int Count { get; set; } public double Sum { get; set; } public OrderStatus Status { get; set; } public DateTime DateCreate { get; set; } @@ -31,8 +32,9 @@ namespace CarpentryWorkshopListImplement.Models Sum = model.Sum, Status = model.Status, DateCreate = model.DateCreate, - DateImplement = model.DateImplement - }; + DateImplement = model.DateImplement, + ImplementerId = model.ImplementerId, + }; } public void Update(OrderBindingModel? model) { @@ -47,7 +49,8 @@ namespace CarpentryWorkshopListImplement.Models Status = model.Status; DateCreate = model.DateCreate; DateImplement = model.DateImplement; - } + ImplementerId = model.ImplementerId; + } public OrderViewModel GetViewModel => new() { Id = Id, @@ -57,7 +60,8 @@ namespace CarpentryWorkshopListImplement.Models Sum = Sum, Status = Status, DateCreate = DateCreate, - DateImplement = DateImplement - }; + DateImplement = DateImplement, + ImplementerId = ImplementerId + }; } } \ No newline at end of file diff --git a/CarpentryWorkshop/CarpentryWorkshopRestApi/Controllers/ImplementerController.cs b/CarpentryWorkshop/CarpentryWorkshopRestApi/Controllers/ImplementerController.cs new file mode 100644 index 0000000..1b9fdc3 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopRestApi/Controllers/ImplementerController.cs @@ -0,0 +1,102 @@ +using DocumentFormat.OpenXml.Office2010.Excel; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using CarpentryWorkshopContracts.BindingModel; +using CarpentryWorkshopContracts.BusinessLogicsContracts; +using CarpentryWorkshopContracts.SearchModel; +using CarpentryWorkshopContracts.ViewModels; +using CarpentryWorkshopDataModels.Enums; + +namespace CarpentryWorkshopRestApi.Controllers +{ + [Route("api/[controller]/[action]")] + [ApiController] + public class ImplementerController : Controller + { + private readonly ILogger _logger; + private readonly IOrderLogic _order; + private readonly IImplementerLogic _logic; + public ImplementerController(IOrderLogic order, IImplementerLogic logic, ILogger logger) + { + _logger = logger; + _order = order; + _logic = logic; + } + [HttpGet] + public ImplementerViewModel? Login(string login, string password) + { + try + { + return _logic.ReadElement(new ImplementerSearchModel + { + ImplementerFIO = login, + Password = password + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка авторизации сотрудника"); + throw; + } + } + [HttpGet] + public List? GetNewOrders() + { + try + { + return _order.ReadList(new OrderSearchModel + { + Status = OrderStatus.Принят + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения новых заказов"); + throw; + } + } + [HttpGet] + public OrderViewModel? GetImplementerOrder(int implementerId) + { + try + { + return _order.ReadElement(new OrderSearchModel + { + ImplementerId = implementerId + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения текущего заказа исполнителя"); + + throw; + } + } + [HttpPost] + public void TakeOrderInWork(OrderBindingModel model) + { + try + { + _order.TakeOrderInWork(model); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка перевода заказа с №{Id} в работу", model.Id); + throw; + } + } + [HttpPost] + public void FinishOrder(OrderBindingModel model) + { + try + { + _order.FinishOrder(model); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка отметки о готовности заказа с №{ Id} ", model.Id); + throw; + } + } + } +}