diff --git a/SecuritySystem/FormImplementer.Designer.cs b/SecuritySystem/FormImplementer.Designer.cs new file mode 100644 index 0000000..b3cc63c --- /dev/null +++ b/SecuritySystem/FormImplementer.Designer.cs @@ -0,0 +1,162 @@ +namespace SecuritySystemView +{ + 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(); + textBoxFIO = new TextBox(); + labelPassword = new Label(); + textBoxPassword = new TextBox(); + textBoxWorkExperience = new TextBox(); + labelWorkExperience = new Label(); + labelQualification = new Label(); + textBoxQualification = new TextBox(); + buttonCancel = new Button(); + buttonSave = new Button(); + SuspendLayout(); + // + // labelFIO + // + labelFIO.AutoSize = true; + labelFIO.Location = new Point(12, 15); + labelFIO.Name = "labelFIO"; + labelFIO.Size = new Size(56, 25); + labelFIO.TabIndex = 0; + labelFIO.Text = "ФИО:"; + // + // textBoxFIO + // + textBoxFIO.Location = new Point(158, 12); + textBoxFIO.Name = "textBoxFIO"; + textBoxFIO.Size = new Size(422, 31); + textBoxFIO.TabIndex = 1; + // + // labelPassword + // + labelPassword.AutoSize = true; + labelPassword.Location = new Point(12, 63); + labelPassword.Name = "labelPassword"; + labelPassword.Size = new Size(78, 25); + labelPassword.TabIndex = 2; + labelPassword.Text = "Пароль:"; + // + // textBoxPassword + // + textBoxPassword.Location = new Point(158, 60); + textBoxPassword.Name = "textBoxPassword"; + textBoxPassword.Size = new Size(422, 31); + textBoxPassword.TabIndex = 3; + // + // textBoxWorkExperience + // + textBoxWorkExperience.Location = new Point(158, 108); + textBoxWorkExperience.Name = "textBoxWorkExperience"; + textBoxWorkExperience.Size = new Size(108, 31); + textBoxWorkExperience.TabIndex = 4; + // + // labelWorkExperience + // + labelWorkExperience.AutoSize = true; + labelWorkExperience.Location = new Point(12, 111); + labelWorkExperience.Name = "labelWorkExperience"; + labelWorkExperience.Size = new Size(122, 25); + labelWorkExperience.TabIndex = 5; + labelWorkExperience.Text = "Стаж работы:"; + // + // labelQualification + // + labelQualification.AutoSize = true; + labelQualification.Location = new Point(321, 111); + labelQualification.Name = "labelQualification"; + labelQualification.Size = new Size(134, 25); + labelQualification.TabIndex = 6; + labelQualification.Text = "Квалификация:"; + // + // textBoxQualification + // + textBoxQualification.Location = new Point(472, 108); + textBoxQualification.Name = "textBoxQualification"; + textBoxQualification.Size = new Size(108, 31); + textBoxQualification.TabIndex = 7; + // + // buttonCancel + // + buttonCancel.Location = new Point(468, 175); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(112, 34); + buttonCancel.TabIndex = 8; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += ButtonCancel_Click; + // + // buttonSave + // + buttonSave.Location = new Point(350, 175); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(112, 34); + buttonSave.TabIndex = 9; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += ButtonSave_Click; + // + // FormImplementer + // + AutoScaleDimensions = new SizeF(10F, 25F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(598, 221); + Controls.Add(buttonSave); + Controls.Add(buttonCancel); + Controls.Add(textBoxQualification); + Controls.Add(labelQualification); + Controls.Add(labelWorkExperience); + Controls.Add(textBoxWorkExperience); + Controls.Add(textBoxPassword); + Controls.Add(labelPassword); + Controls.Add(textBoxFIO); + Controls.Add(labelFIO); + Name = "FormImplementer"; + Text = "FormImplementer"; + Load += FormCondition_Load; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Label labelFIO; + private TextBox textBoxFIO; + private Label labelPassword; + private TextBox textBoxPassword; + private TextBox textBoxWorkExperience; + private Label labelWorkExperience; + private Label labelQualification; + private TextBox textBoxQualification; + private Button buttonCancel; + private Button buttonSave; + } +} \ No newline at end of file diff --git a/SecuritySystem/FormImplementer.cs b/SecuritySystem/FormImplementer.cs new file mode 100644 index 0000000..eb6f865 --- /dev/null +++ b/SecuritySystem/FormImplementer.cs @@ -0,0 +1,108 @@ +using SecuritySystemContracts.BindingModels; +using SecuritySystemContracts.BusinessLogicsContracts; +using SecuritySystemContracts.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 SecuritySystemView +{ + public partial class FormImplementer : Form + { + private readonly ILogger _logger; + private readonly IImplementerLogic _logic; + private int? _id; + public int Id { set { _id = value; } } + public FormImplementer(ILogger logger, IImplementerLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + private void FormCondition_Load(object sender, EventArgs e) + { + if (_id.HasValue) + { + try + { + _logger.LogInformation("Получение компонента"); + var view = _logic.ReadElement(new ImplementerSearchModel { Id = _id.Value }); + if (view != null) + { + textBoxFIO.Text = view.ImplementerFIO; + textBoxPassword.Text = view.Password; + textBoxWorkExperience.Text = view.WorkExperience.ToString(); + textBoxQualification.Text = view.Qualification.ToString(); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения компонента"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + } + private void ButtonSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxFIO.Text)) + { + MessageBox.Show("Заполните ФИО", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (string.IsNullOrEmpty(textBoxPassword.Text)) + { + MessageBox.Show("Заполните пароль", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (string.IsNullOrEmpty(textBoxWorkExperience.Text)) + { + MessageBox.Show("Заполните опыт работы", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (string.IsNullOrEmpty(textBoxQualification.Text)) + { + MessageBox.Show("Заполните квалификацию", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Сохранение исполнителя"); + try + { + var model = new ImplementerBindingModel + { + Id = _id ?? 0, + ImplementerFIO = textBoxFIO.Text, + Password = textBoxPassword.Text, + WorkExperience = Convert.ToInt32(textBoxWorkExperience.Text), + Qualification = Convert.ToInt32(textBoxQualification.Text) + }; + var operationResult = _id.HasValue ? _logic.Update(model) : + _logic.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 ButtonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } +} diff --git a/SecuritySystem/FormImplementer.resx b/SecuritySystem/FormImplementer.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/SecuritySystem/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/SecuritySystem/FormImplementers.Designer.cs b/SecuritySystem/FormImplementers.Designer.cs new file mode 100644 index 0000000..4258616 --- /dev/null +++ b/SecuritySystem/FormImplementers.Designer.cs @@ -0,0 +1,115 @@ +namespace SecuritySystemView +{ + 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() + { + this.dataGridView = new System.Windows.Forms.DataGridView(); + this.buttonAdd = new System.Windows.Forms.Button(); + this.buttonUpd = new System.Windows.Forms.Button(); + this.buttonDel = new System.Windows.Forms.Button(); + this.buttonRef = new System.Windows.Forms.Button(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); + this.SuspendLayout(); + // + // dataGridView + // + this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView.Location = new System.Drawing.Point(0, 0); + this.dataGridView.Name = "dataGridView"; + this.dataGridView.RowHeadersWidth = 62; + this.dataGridView.RowTemplate.Height = 33; + this.dataGridView.Size = new System.Drawing.Size(619, 449); + this.dataGridView.TabIndex = 1; + // + // buttonAdd + // + this.buttonAdd.Location = new System.Drawing.Point(651, 12); + this.buttonAdd.Name = "buttonAdd"; + this.buttonAdd.Size = new System.Drawing.Size(120, 50); + this.buttonAdd.TabIndex = 2; + this.buttonAdd.Text = "Добавить"; + this.buttonAdd.UseVisualStyleBackColor = true; + this.buttonAdd.Click += new System.EventHandler(this.ButtonAdd_Click); + // + // buttonUpd + // + this.buttonUpd.Location = new System.Drawing.Point(651, 79); + this.buttonUpd.Name = "buttonUpd"; + this.buttonUpd.Size = new System.Drawing.Size(120, 50); + this.buttonUpd.TabIndex = 3; + this.buttonUpd.Text = "Изменить"; + this.buttonUpd.UseVisualStyleBackColor = true; + this.buttonUpd.Click += new System.EventHandler(this.ButtonUpd_Click); + // + // buttonDel + // + this.buttonDel.Location = new System.Drawing.Point(651, 146); + this.buttonDel.Name = "buttonDel"; + this.buttonDel.Size = new System.Drawing.Size(120, 50); + this.buttonDel.TabIndex = 4; + this.buttonDel.Text = "Удалить"; + this.buttonDel.UseVisualStyleBackColor = true; + this.buttonDel.Click += new System.EventHandler(this.ButtonDel_Click); + // + // buttonRef + // + this.buttonRef.Location = new System.Drawing.Point(651, 214); + this.buttonRef.Name = "buttonRef"; + this.buttonRef.Size = new System.Drawing.Size(120, 50); + this.buttonRef.TabIndex = 5; + this.buttonRef.Text = "Обновить"; + this.buttonRef.UseVisualStyleBackColor = true; + this.buttonRef.Click += new System.EventHandler(this.ButtonRef_Click); + // + // FormImplementers + // + this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 450); + this.Controls.Add(this.buttonRef); + this.Controls.Add(this.buttonDel); + this.Controls.Add(this.buttonUpd); + this.Controls.Add(this.buttonAdd); + this.Controls.Add(this.dataGridView); + this.Name = "FormImplementers"; + this.Text = "Исполнители"; + this.Load += new System.EventHandler(this.FormImplementers_Load); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit(); + this.ResumeLayout(false); + + } + + #endregion + + private DataGridView dataGridView; + private Button buttonAdd; + private Button buttonUpd; + private Button buttonDel; + private Button buttonRef; + } +} \ No newline at end of file diff --git a/SecuritySystem/FormImplementers.cs b/SecuritySystem/FormImplementers.cs new file mode 100644 index 0000000..d9d93cc --- /dev/null +++ b/SecuritySystem/FormImplementers.cs @@ -0,0 +1,110 @@ +using SecuritySystemContracts.BindingModels; +using SecuritySystemContracts.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 SecuritySystemView +{ + 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 FormImplementers_Load(object sender, EventArgs e) + { + 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; + dataGridView.Columns["Password"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + dataGridView.Columns["WorkExperience"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + dataGridView.Columns["Qualification"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + _logger.LogInformation("Загрузка исполнителей"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки исполнителей"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + private void ButtonAdd_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormImplementer)); + if (service is FormImplementer form) + { + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + private void ButtonUpd_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 ButtonDel_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 ButtonRef_Click(object sender, EventArgs e) + { + LoadData(); + } + } +} diff --git a/SecuritySystem/FormImplementers.resx b/SecuritySystem/FormImplementers.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/SecuritySystem/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/SecuritySystem/FormMain.Designer.cs b/SecuritySystem/FormMain.Designer.cs index f00b9f4..f65232f 100644 --- a/SecuritySystem/FormMain.Designer.cs +++ b/SecuritySystem/FormMain.Designer.cs @@ -1,4 +1,7 @@ -namespace SecuritySystemView +using DocumentFormat.OpenXml.Spreadsheet; +using DocumentFormat.OpenXml.Wordprocessing; + +namespace SecuritySystemView { partial class FormMain { @@ -32,17 +35,17 @@ guideToolStripMenuItem = new ToolStripMenuItem(); componentsToolStripMenuItem = new ToolStripMenuItem(); goodsToolStripMenuItem = new ToolStripMenuItem(); + clientsToolStripMenuItem = new ToolStripMenuItem(); + implemntersToolStripMenuItem = new ToolStripMenuItem(); отчетыToolStripMenuItem = new ToolStripMenuItem(); componentListToolStripMenuItem = new ToolStripMenuItem(); componentsSecureToolStripMenuItem = new ToolStripMenuItem(); orderListToolStripMenuItem = new ToolStripMenuItem(); dataGridView = new DataGridView(); buttonCreateOrder = new Button(); - buttonTakeOrderInWork = new Button(); - buttonOrderReady = new Button(); buttonIssuedOrder = new Button(); buttonRef = new Button(); - clientsToolStripMenuItem = new ToolStripMenuItem(); + workToolStripMenuItem = new ToolStripMenuItem(); menuStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); SuspendLayout(); @@ -50,7 +53,7 @@ // menuStrip1 // menuStrip1.ImageScalingSize = new Size(20, 20); - menuStrip1.Items.AddRange(new ToolStripItem[] { guideToolStripMenuItem, отчетыToolStripMenuItem }); + menuStrip1.Items.AddRange(new ToolStripItem[] { guideToolStripMenuItem, отчетыToolStripMenuItem, workToolStripMenuItem }); menuStrip1.Location = new Point(0, 0); menuStrip1.Name = "menuStrip1"; menuStrip1.Padding = new Padding(5, 2, 0, 2); @@ -60,7 +63,7 @@ // // guideToolStripMenuItem // - guideToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { componentsToolStripMenuItem, goodsToolStripMenuItem, clientsToolStripMenuItem }); + guideToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { componentsToolStripMenuItem, goodsToolStripMenuItem, clientsToolStripMenuItem, implemntersToolStripMenuItem }); guideToolStripMenuItem.Name = "guideToolStripMenuItem"; guideToolStripMenuItem.Size = new Size(87, 20); guideToolStripMenuItem.Text = "Справочник"; @@ -79,6 +82,20 @@ goodsToolStripMenuItem.Text = "Изделия"; goodsToolStripMenuItem.Click += GoodsToolStripMenuItem_Click; // + // clientsToolStripMenuItem + // + clientsToolStripMenuItem.Name = "clientsToolStripMenuItem"; + clientsToolStripMenuItem.Size = new Size(180, 22); + clientsToolStripMenuItem.Text = "Клиенты"; + clientsToolStripMenuItem.Click += ClientsToolStripMenuItem_Click; + // + // implemntersToolStripMenuItem + // + implemntersToolStripMenuItem.Name = "implemntersToolStripMenuItem"; + implemntersToolStripMenuItem.Size = new Size(180, 22); + implemntersToolStripMenuItem.Text = "Исполнители"; + implemntersToolStripMenuItem.Click += ImplemntersToolStripMenuItem_Click; + // // отчетыToolStripMenuItem // отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { componentListToolStripMenuItem, componentsSecureToolStripMenuItem, orderListToolStripMenuItem }); @@ -90,7 +107,7 @@ // componentListToolStripMenuItem.Name = "componentListToolStripMenuItem"; componentListToolStripMenuItem.Size = new Size(218, 22); - componentListToolStripMenuItem.Text = "Список Компонентов"; + componentListToolStripMenuItem.Text = "Список компонентов"; componentListToolStripMenuItem.Click += ComponentListToolStripMenuItem_Click; // // componentsSecureToolStripMenuItem @@ -132,31 +149,9 @@ buttonCreateOrder.UseVisualStyleBackColor = true; buttonCreateOrder.Click += ButtonCreateOrder_Click; // - // buttonTakeOrderInWork - // - buttonTakeOrderInWork.Location = new Point(898, 92); - buttonTakeOrderInWork.Margin = new Padding(3, 2, 3, 2); - buttonTakeOrderInWork.Name = "buttonTakeOrderInWork"; - buttonTakeOrderInWork.Size = new Size(216, 22); - buttonTakeOrderInWork.TabIndex = 3; - buttonTakeOrderInWork.Text = "Отдать на выполнение"; - buttonTakeOrderInWork.UseVisualStyleBackColor = true; - buttonTakeOrderInWork.Click += ButtonTakeOrderInWork_Click; - // - // buttonOrderReady - // - buttonOrderReady.Location = new Point(898, 129); - buttonOrderReady.Margin = new Padding(3, 2, 3, 2); - buttonOrderReady.Name = "buttonOrderReady"; - buttonOrderReady.Size = new Size(216, 22); - buttonOrderReady.TabIndex = 4; - buttonOrderReady.Text = "Заказ готов"; - buttonOrderReady.UseVisualStyleBackColor = true; - buttonOrderReady.Click += ButtonOrderReady_Click; - // // buttonIssuedOrder // - buttonIssuedOrder.Location = new Point(898, 169); + buttonIssuedOrder.Location = new Point(898, 95); buttonIssuedOrder.Margin = new Padding(3, 2, 3, 2); buttonIssuedOrder.Name = "buttonIssuedOrder"; buttonIssuedOrder.Size = new Size(216, 22); @@ -167,7 +162,7 @@ // // buttonRef // - buttonRef.Location = new Point(898, 210); + buttonRef.Location = new Point(898, 136); buttonRef.Margin = new Padding(3, 2, 3, 2); buttonRef.Name = "buttonRef"; buttonRef.Size = new Size(216, 22); @@ -176,12 +171,12 @@ buttonRef.UseVisualStyleBackColor = true; buttonRef.Click += ButtonRef_Click; // - // clientsToolStripMenuItem + // workToolStripMenuItem // - clientsToolStripMenuItem.Name = "clientsToolStripMenuItem"; - clientsToolStripMenuItem.Size = new Size(180, 22); - clientsToolStripMenuItem.Text = "Клиенты"; - clientsToolStripMenuItem.Click += ClientsToolStripMenuItem_Click; + workToolStripMenuItem.Name = "workToolStripMenuItem"; + workToolStripMenuItem.Size = new Size(92, 20); + workToolStripMenuItem.Text = "Запуск работ"; + workToolStripMenuItem.Click += WorkStartToolStripMenuItem_Click; // // FormMain // @@ -190,8 +185,6 @@ ClientSize = new Size(1149, 319); Controls.Add(buttonRef); Controls.Add(buttonIssuedOrder); - Controls.Add(buttonOrderReady); - Controls.Add(buttonTakeOrderInWork); Controls.Add(buttonCreateOrder); Controls.Add(dataGridView); Controls.Add(menuStrip1); @@ -215,8 +208,6 @@ private ToolStripMenuItem goodsToolStripMenuItem; private DataGridView dataGridView; private Button buttonCreateOrder; - private Button buttonTakeOrderInWork; - private Button buttonOrderReady; private Button buttonIssuedOrder; private Button buttonRef; private ToolStripMenuItem отчетыToolStripMenuItem; @@ -224,5 +215,7 @@ private ToolStripMenuItem componentsSecureToolStripMenuItem; private ToolStripMenuItem orderListToolStripMenuItem; private ToolStripMenuItem clientsToolStripMenuItem; + private ToolStripMenuItem implemntersToolStripMenuItem; + private ToolStripMenuItem workToolStripMenuItem; } } \ No newline at end of file diff --git a/SecuritySystem/FormMain.cs b/SecuritySystem/FormMain.cs index 40671bc..f481c3f 100644 --- a/SecuritySystem/FormMain.cs +++ b/SecuritySystem/FormMain.cs @@ -7,13 +7,9 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; - +using SecuritySystemContracts.BusinessLogicsContracts; using Microsoft.Extensions.Logging; using SecuritySystemContracts.BindingModels; -using SecuritySystemContracts.BusinessLogicsContracts; - - -using SecuritySystemView; namespace SecuritySystemView { @@ -22,12 +18,14 @@ namespace SecuritySystemView private readonly ILogger _logger; private readonly IOrderLogic _orderLogic; private readonly IReportLogic _reportLogic; - public FormMain(ILogger logger, IOrderLogic orderLogic, 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) { @@ -43,6 +41,7 @@ namespace SecuritySystemView dataGridView.DataSource = list; dataGridView.Columns["SecureId"].Visible = false; dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["ImplementerId"].Visible = false; dataGridView.Columns["DateImplement"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; } _logger.LogInformation("Загрузка заказов"); @@ -86,56 +85,6 @@ namespace SecuritySystemView LoadData(); } } - 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("Заказ No {id}. Меняется статус на 'В работе'", id); - try - { - var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel - { - Id = 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("Заказ No {id}. Меняется статус на 'Готов'", id); - try - { - var operationResult = _orderLogic.FinishOrder(new OrderBindingModel - { - Id = 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) @@ -191,5 +140,18 @@ namespace SecuritySystemView form.ShowDialog(); } } + private void ImplemntersToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormImplementers)); + if (service is FormImplementers form) + { + form.ShowDialog(); + } + } + private void WorkStartToolStripMenuItem_Click(object sender, EventArgs e) + { + _workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic); + MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + } } } diff --git a/SecuritySystem/Program.cs b/SecuritySystem/Program.cs index 956e129..8c1283a 100644 --- a/SecuritySystem/Program.cs +++ b/SecuritySystem/Program.cs @@ -13,6 +13,9 @@ using SecuritySystemBusinessLogic.BusinessLogics; using SecuritySystemContracts.BusinessLogicsContracts; using SecuritySystemContracts.StorageContracts; using SecuritySystemView; +using SecuritySystemBusinessLogic.BusinessLogics; +using SecuritySystemContracts.BusinessLogicsContracts; +using SecuritySystemContracts.StorageContracts; namespace SecuritySystemView { @@ -46,11 +49,14 @@ namespace SecuritySystemView 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(); diff --git a/SecuritySystemBusinessLogic/BusinessLogics/ImplementerLogic.cs b/SecuritySystemBusinessLogic/BusinessLogics/ImplementerLogic.cs new file mode 100644 index 0000000..37c0b70 --- /dev/null +++ b/SecuritySystemBusinessLogic/BusinessLogics/ImplementerLogic.cs @@ -0,0 +1,121 @@ +using SecuritySystemContracts.BindingModels; +using SecuritySystemContracts.BusinessLogicsContracts; +using SecuritySystemContracts.SearchModels; +using SecuritySystemContracts.StorageContracts; +using SecuritySystemContracts.ViewModels; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemBusinessLogic.BusinessLogics +{ + public class ImplementerLogic : IImplementerLogic + { + private readonly ILogger _logger; + private readonly IImplementerStorage _implementerStorage; + public ImplementerLogic(ILogger logger, IImplementerStorage implementerStorage) + { + _logger = logger; + _implementerStorage = implementerStorage; + } + public ImplementerViewModel? ReadElement(ImplementerSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + _logger.LogInformation("ReadElement. ImplementerFIO:{ImplementerFIO}. Id:{Id}", model.ImplementerFIO, model.Id); + var element = _implementerStorage.GetElement(model); + if (element == null) + { + _logger.LogWarning("ReadElement element not found"); + return null; + } + _logger.LogInformation("ReadElement find. Id:{Id}", element.Id); + return element; + } + public List? ReadList(ImplementerSearchModel? model) + { + _logger.LogInformation("ReadList. ImplementerFIO:{ImplementerFIO}. Id:{Id}", model?.ImplementerFIO, model?.Id); + var list = model == null ? _implementerStorage.GetFullList() : _implementerStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + _logger.LogInformation("ReadList. Count:{Count}", list.Count); + return list; + } + public bool Create(ImplementerBindingModel model) + { + CheckModel(model); + if (_implementerStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } + public bool Update(ImplementerBindingModel model) + { + CheckModel(model); + if (_implementerStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + return true; + } + public bool Delete(ImplementerBindingModel model) + { + CheckModel(model, false); + _logger.LogInformation("Delete. Id:{Id}", model.Id); + if (_implementerStorage.Delete(model) == null) + { + _logger.LogWarning("Delete operation failed"); + return false; + } + return true; + } + private void CheckModel(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.Qualification <= 0) + { + throw new ArgumentNullException("Квалификация должна быть больше 0", nameof(model.Qualification)); + } + if (model.WorkExperience <= 0) + { + throw new ArgumentNullException("Стаж должен быть больше 0", nameof(model.WorkExperience)); + } + if (string.IsNullOrEmpty(model.Password)) + { + throw new ArgumentNullException("Нет пароля", nameof(model.Password)); + } + _logger.LogInformation("Implementer. ImplementerFIO:{ImplementerFIO}. Password:{Password}. Qualification:{Qualification}. WorkExperience:{WorkExperience}. Id:{Id}", + model.ImplementerFIO, model.Password, model.Qualification, 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/SecuritySystemBusinessLogic/BusinessLogics/OrderLogic.cs b/SecuritySystemBusinessLogic/BusinessLogics/OrderLogic.cs index 56668f7..b146ddb 100644 --- a/SecuritySystemBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/SecuritySystemBusinessLogic/BusinessLogics/OrderLogic.cs @@ -1,4 +1,16 @@ -using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using SecuritySystemContracts.BindingModels; +using SecuritySystemContracts.BusinessLogicsContracts; +using SecuritySystemContracts.SearchModels; +using SecuritySystemContracts.StorageContracts; +using SecuritySystemContracts.ViewModels; +using SecuritySystemDataModels.Enums; +using Microsoft.Extensions.Logging; using SecuritySystemContracts.BindingModels; using SecuritySystemContracts.BusinessLogicsContracts; using SecuritySystemContracts.SearchModels; @@ -12,13 +24,11 @@ namespace SecuritySystemBusinessLogic.BusinessLogics { private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; - public OrderLogic(ILogger logger, IOrderStorage orderStorage) { _logger = logger; _orderStorage = orderStorage; } - public List? ReadList(OrderSearchModel? model) { _logger.LogInformation("ReadList. OrderId:{Id}", model?.Id); @@ -31,40 +41,51 @@ namespace SecuritySystemBusinessLogic.BusinessLogics _logger.LogInformation("ReadList. Count:{Count}", list.Count); return list; } - + public OrderViewModel? ReadElement(OrderSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + _logger.LogInformation("ReadElement. DateFrom:{DateFrom}. DateTo:{DateTo}. Id:{Id}", model.DateFrom, model.DateTo, model.Id); + var element = _orderStorage.GetElement(model); + if (element == null) + { + _logger.LogWarning("ReadElement element not found"); + return null; + } + _logger.LogInformation("ReadElement find. Id:{Id}", element.Id); + return element; + } public bool CreateOrder(OrderBindingModel model) { CheckModel(model); - if (!CheckStatus(model, OrderStatus.Принят, false)) return false; + if (model.Status != OrderStatus.Неизвестен) + { + _logger.LogWarning("Insert operation failed. Order status is incorrect."); + return false; + } + model.Status = OrderStatus.Принят; if (_orderStorage.Insert(model) == null) { + model.Status = OrderStatus.Неизвестен; _logger.LogWarning("Insert operation failed"); return false; } return true; } - public bool TakeOrderInWork(OrderBindingModel model) { - CheckModel(model); - if (!CheckStatus(model, OrderStatus.Выполняется)) return false; - return true; + return StatusUpdate(model, OrderStatus.Выполняется); } - public bool DeliveryOrder(OrderBindingModel model) { - CheckModel(model); - if (!CheckStatus(model, OrderStatus.Выдан)) return false; - return true; + return StatusUpdate(model, OrderStatus.Выдан); } - public bool FinishOrder(OrderBindingModel model) { - CheckModel(model); - if (!CheckStatus(model, OrderStatus.Готов)) return false; - return true; + return StatusUpdate(model, OrderStatus.Готов); } - private void CheckModel(OrderBindingModel model, bool withParams = true) { if (model == null) @@ -77,36 +98,50 @@ namespace SecuritySystemBusinessLogic.BusinessLogics } if (model.SecureId < 0) { - throw new ArgumentNullException("Некорректный идентификатор камеры", nameof(model.SecureId)); + throw new ArgumentNullException("Некорректный идентификатор компьютера", nameof(model.SecureId)); } if (model.Count <= 0) { - throw new ArgumentNullException("Количество камер в заказе должно быть больше 0", nameof(model.Count)); + throw new ArgumentNullException("Количество компьютеров в заказе должно быть больше 0", nameof(model.Count)); } if (model.Sum <= 0) { throw new ArgumentNullException("Сумма заказа должна быть больше 0", nameof(model.Sum)); } - _logger.LogInformation("Order. OrderId:{Id}.Sum:{ Sum}. SecureId: { SecureId}", model.Id, model.Sum, model.SecureId); + _logger.LogInformation("Order. OrderId: {Id}.Sum: {Sum}. SecureId: {SecureId}", model.Id, model.Sum, model.SecureId); } - - private bool CheckStatus(OrderBindingModel model, OrderStatus newstatus, bool update = true) + private bool StatusUpdate(OrderBindingModel model, OrderStatus newStatus) { - if (model.Status != newstatus - 1) + var viewModel = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id }); + if (viewModel == null) { - _logger.LogWarning("Failed to change status"); - return false; + throw new ArgumentNullException(nameof(model)); } - model.Status = newstatus; - if (!update) return true; + if (viewModel.Status + 1 != newStatus) + { + _logger.LogWarning("Change status operation failed"); + throw new InvalidOperationException(); + } + model.Status = newStatus; + if (model.Status == OrderStatus.Готов) + { + model.DateImplement = DateTime.Now; + } + else + { + model.DateImplement = viewModel.DateImplement; + } + if (viewModel.ImplementerId.HasValue) + { + model.ImplementerId = viewModel.ImplementerId.Value; + } + CheckModel(model, false); if (_orderStorage.Update(model) == null) { - _logger.LogWarning("Insert operation failed"); + _logger.LogWarning("Change status operation failed"); return false; } - if (model.Status == OrderStatus.Выдан) model.DateImplement = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc); return true; } - } } diff --git a/SecuritySystemBusinessLogic/BusinessLogics/WorkModeling.cs b/SecuritySystemBusinessLogic/BusinessLogics/WorkModeling.cs new file mode 100644 index 0000000..cc8b50f --- /dev/null +++ b/SecuritySystemBusinessLogic/BusinessLogics/WorkModeling.cs @@ -0,0 +1,143 @@ +using SecuritySystemContracts.BindingModels; +using SecuritySystemContracts.BusinessLogicsContracts; +using SecuritySystemContracts.SearchModels; +using SecuritySystemContracts.ViewModels; +using SecuritySystemDataModels.Enums; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemBusinessLogic.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. Implementers is 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/SecuritySystemClientApp/Views/Shared/_Layout.cshtml b/SecuritySystemClientApp/Views/Shared/_Layout.cshtml index fe5cf5d..7299244 100644 --- a/SecuritySystemClientApp/Views/Shared/_Layout.cshtml +++ b/SecuritySystemClientApp/Views/Shared/_Layout.cshtml @@ -9,6 +9,7 @@ + @await RenderSectionAsync("Scripts", required: false) diff --git a/SecuritySystemContracts/BindingModels/ImplementerBindingModel.cs b/SecuritySystemContracts/BindingModels/ImplementerBindingModel.cs new file mode 100644 index 0000000..66a26e5 --- /dev/null +++ b/SecuritySystemContracts/BindingModels/ImplementerBindingModel.cs @@ -0,0 +1,18 @@ +using SecuritySystemDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemContracts.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/SecuritySystemContracts/BindingModels/OrderBindingModel.cs b/SecuritySystemContracts/BindingModels/OrderBindingModel.cs index 2c3503c..9ca49f5 100644 --- a/SecuritySystemContracts/BindingModels/OrderBindingModel.cs +++ b/SecuritySystemContracts/BindingModels/OrderBindingModel.cs @@ -14,5 +14,6 @@ namespace SecuritySystemContracts.BindingModels public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; public DateTime DateCreate { get; set; } = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc); public DateTime? DateImplement { get; set; } + public int? ImplementerId { get; set; } } } diff --git a/SecuritySystemContracts/BusinessLogicsContracts/IImplementerLogic.cs b/SecuritySystemContracts/BusinessLogicsContracts/IImplementerLogic.cs new file mode 100644 index 0000000..146beff --- /dev/null +++ b/SecuritySystemContracts/BusinessLogicsContracts/IImplementerLogic.cs @@ -0,0 +1,20 @@ +using SecuritySystemContracts.BindingModels; +using SecuritySystemContracts.SearchModels; +using SecuritySystemContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemContracts.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/SecuritySystemContracts/BusinessLogicsContracts/IOrderLogic.cs b/SecuritySystemContracts/BusinessLogicsContracts/IOrderLogic.cs index d63e239..945ab27 100644 --- a/SecuritySystemContracts/BusinessLogicsContracts/IOrderLogic.cs +++ b/SecuritySystemContracts/BusinessLogicsContracts/IOrderLogic.cs @@ -12,6 +12,7 @@ namespace SecuritySystemContracts.BusinessLogicsContracts public interface IOrderLogic { List? ReadList(OrderSearchModel? model); + OrderViewModel? ReadElement(OrderSearchModel? model); bool CreateOrder(OrderBindingModel model); bool TakeOrderInWork(OrderBindingModel model); bool FinishOrder(OrderBindingModel model); diff --git a/SecuritySystemContracts/BusinessLogicsContracts/IWorkProcess.cs b/SecuritySystemContracts/BusinessLogicsContracts/IWorkProcess.cs new file mode 100644 index 0000000..5f83c51 --- /dev/null +++ b/SecuritySystemContracts/BusinessLogicsContracts/IWorkProcess.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemContracts.BusinessLogicsContracts +{ + public interface IWorkProcess + { + /// + /// Запуск работ + /// + void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic); + } +} diff --git a/SecuritySystemContracts/SearchModels/ImplementerSearchModel.cs b/SecuritySystemContracts/SearchModels/ImplementerSearchModel.cs new file mode 100644 index 0000000..4738952 --- /dev/null +++ b/SecuritySystemContracts/SearchModels/ImplementerSearchModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemContracts.SearchModels +{ + public class ImplementerSearchModel + { + public int? Id { get; set; } + public string? ImplementerFIO { get; set; } + public string? Password { get; set; } + } +} diff --git a/SecuritySystemContracts/SearchModels/OrderSearchModel.cs b/SecuritySystemContracts/SearchModels/OrderSearchModel.cs index 4a70aaa..44446e5 100644 --- a/SecuritySystemContracts/SearchModels/OrderSearchModel.cs +++ b/SecuritySystemContracts/SearchModels/OrderSearchModel.cs @@ -1,4 +1,5 @@ -using System; +using SecuritySystemDataModels.Enums; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -10,7 +11,9 @@ namespace SecuritySystemContracts.SearchModels { public int? Id { get; set; } public int? ClientId { get; set; } + public int? ImplementerId { get; set; } public DateTime? DateFrom { get; set; } public DateTime? DateTo { get; set; } + public OrderStatus? Status { get; set; } } } diff --git a/SecuritySystemContracts/StorageContracts/IImplementerStorage.cs b/SecuritySystemContracts/StorageContracts/IImplementerStorage.cs new file mode 100644 index 0000000..8cf45df --- /dev/null +++ b/SecuritySystemContracts/StorageContracts/IImplementerStorage.cs @@ -0,0 +1,21 @@ +using SecuritySystemContracts.BindingModels; +using SecuritySystemContracts.SearchModels; +using SecuritySystemContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemContracts.StorageContracts +{ + 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/SecuritySystemContracts/ViewModels/ImplementerViewModel.cs b/SecuritySystemContracts/ViewModels/ImplementerViewModel.cs new file mode 100644 index 0000000..52bfb7f --- /dev/null +++ b/SecuritySystemContracts/ViewModels/ImplementerViewModel.cs @@ -0,0 +1,26 @@ +using SecuritySystemDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemContracts.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/SecuritySystemContracts/ViewModels/OrderViewModel.cs b/SecuritySystemContracts/ViewModels/OrderViewModel.cs index 62e6458..c3f4652 100644 --- a/SecuritySystemContracts/ViewModels/OrderViewModel.cs +++ b/SecuritySystemContracts/ViewModels/OrderViewModel.cs @@ -20,6 +20,9 @@ namespace SecuritySystemContracts.ViewModels public int ClientId { get; set; } [DisplayName("Клиент")] public string ClientFIO { get; set; } = string.Empty; + public int? ImplementerId { get; set; } + [DisplayName("ФИО исполнителя")] + public string? ImplementerFIO { get; set; } = string.Empty; public int Count { get; set; } [DisplayName("Сумма")] public double Sum { get; set; } diff --git a/SecuritySystemDataModels/Models/IImplementerModel.cs b/SecuritySystemDataModels/Models/IImplementerModel.cs new file mode 100644 index 0000000..a32a6eb --- /dev/null +++ b/SecuritySystemDataModels/Models/IImplementerModel.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemDataModels.Models +{ + public interface IImplementerModel : IId + { + string ImplementerFIO { get; } + string Password { get; } + int WorkExperience { get; } + int Qualification { get; } + } +} diff --git a/SecuritySystemDatabaseImplement/Implements/ImplementerStorage.cs b/SecuritySystemDatabaseImplement/Implements/ImplementerStorage.cs new file mode 100644 index 0000000..27c015b --- /dev/null +++ b/SecuritySystemDatabaseImplement/Implements/ImplementerStorage.cs @@ -0,0 +1,83 @@ +using SecuritySystemContracts.BindingModels; +using SecuritySystemContracts.SearchModels; +using SecuritySystemContracts.StorageContracts; +using SecuritySystemContracts.ViewModels; +using SecuritySystemDatabaseImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemDatabaseImplement.Implements +{ + public class ImplementerStorage : IImplementerStorage + { + public List GetFullList() + { + using var context = new SecuritySystemDatabase(); + return context.Implementers + .Select(x => x.GetViewModel) + .ToList(); + } + public List GetFilteredList(ImplementerSearchModel model) + { + using var context = new SecuritySystemDatabase(); + return context.Implementers + .Select(x => x.GetViewModel) + .ToList(); + } + public ImplementerViewModel? GetElement(ImplementerSearchModel model) + { + if (!model.Id.HasValue) + { + return null; + } + using var context = new SecuritySystemDatabase(); + return context.Implementers + .FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id) + ?.GetViewModel; + } + public ImplementerViewModel? Insert(ImplementerBindingModel model) + { + var newImplementer = Implementer.Create(model); + if (newImplementer == null) + { + return null; + } + using var context = new SecuritySystemDatabase(); + context.Implementers.Add(newImplementer); + context.SaveChanges(); + return context.Implementers + .FirstOrDefault(x => x.Id == newImplementer.Id) + ?.GetViewModel; + } + public ImplementerViewModel? Update(ImplementerBindingModel model) + { + using var context = new SecuritySystemDatabase(); + var implementer = context.Implementers.FirstOrDefault(x => x.Id == model.Id); + if (implementer == null) + { + return null; + } + implementer.Update(model); + context.SaveChanges(); + return context.Implementers + .FirstOrDefault(x => x.Id == model.Id) + ?.GetViewModel; + } + public ImplementerViewModel? Delete(ImplementerBindingModel model) + { + using var context = new SecuritySystemDatabase(); + var implementer = context.Implementers + .FirstOrDefault(rec => rec.Id == model.Id); + if (implementer != null) + { + context.Implementers.Remove(implementer); + context.SaveChanges(); + return implementer.GetViewModel; + } + return null; + } + } +} diff --git a/SecuritySystemDatabaseImplement/Implements/OrderStorage.cs b/SecuritySystemDatabaseImplement/Implements/OrderStorage.cs index e6b6983..4a9aca6 100644 --- a/SecuritySystemDatabaseImplement/Implements/OrderStorage.cs +++ b/SecuritySystemDatabaseImplement/Implements/OrderStorage.cs @@ -1,4 +1,7 @@ - +using SecuritySystemContracts.BindingModels; +using SecuritySystemContracts.SearchModels; +using SecuritySystemContracts.StorageContracts; +using SecuritySystemContracts.ViewModels; using Microsoft.EntityFrameworkCore; using SecuritySystemDatabaseImplement.Models; using SecuritySystemContracts.BindingModels; @@ -19,6 +22,7 @@ namespace SecuritySystemDatabaseImplement.Implements var deletedElement = context.Orders .Include(x => x.Secure) .Include(x => x.Client) + .Include(x => x.Implementer) .FirstOrDefault(x => x.Id == model.Id) ?.GetViewModel; context.Orders.Remove(element); @@ -34,11 +38,25 @@ namespace SecuritySystemDatabaseImplement.Implements return null; } using var context = new SecuritySystemDatabase(); - return context.Orders - .Include(x => x.Secure) - .Include(x => x.Client) - .FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id) - ?.GetViewModel; + if (model.Id.HasValue) + { + return context.Orders + .Include(x => x.Secure) + .Include(x => x.Client) + .Include(x => x.Implementer) + .FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id) + ?.GetViewModel; + } + else if (model.ImplementerId.HasValue && model.Status.HasValue) + { + return context.Orders + .Include(x => x.Secure) + .Include(x => x.Client) + .Include(x => x.Implementer) + .FirstOrDefault(x => x.ImplementerId == model.ImplementerId && x.Status == model.Status) + ?.GetViewModel; + } + return null; } public List GetFilteredList(OrderSearchModel model) { @@ -70,6 +88,14 @@ namespace SecuritySystemDatabaseImplement.Implements .Select(x => x.GetViewModel) .ToList(); } + else if (model.Status.HasValue) + { + return context.Orders + .Include(x => x.Secure) + .Include(x => x.Client) + .Include(x => x.Implementer) + .Where(x => x.Status == model.Status).Select(x => x.GetViewModel).ToList(); + } else { return new(); @@ -81,6 +107,7 @@ namespace SecuritySystemDatabaseImplement.Implements return context.Orders .Include(x => x.Secure) .Include(x => x.Client) + .Include(x => x.Implementer) .Select(x => x.GetViewModel) .ToList(); } @@ -97,6 +124,7 @@ namespace SecuritySystemDatabaseImplement.Implements return context.Orders .Include(x => x.Secure) .Include(x => x.Client) + .Include(x => x.Implementer) .FirstOrDefault(x => x.Id == newOrder.Id) ?.GetViewModel; } @@ -113,6 +141,7 @@ namespace SecuritySystemDatabaseImplement.Implements return context.Orders .Include(x => x.Secure) .Include(x => x.Client) + .Include(x => x.Implementer) .FirstOrDefault(x => x.Id == model.Id) ?.GetViewModel; } diff --git a/SecuritySystemDatabaseImplement/Migrations/20230423054524_with client.Designer.cs b/SecuritySystemDatabaseImplement/Migrations/20230501141820_lab6.Designer.cs similarity index 82% rename from SecuritySystemDatabaseImplement/Migrations/20230423054524_with client.Designer.cs rename to SecuritySystemDatabaseImplement/Migrations/20230501141820_lab6.Designer.cs index f9c945d..ff8131b 100644 --- a/SecuritySystemDatabaseImplement/Migrations/20230423054524_with client.Designer.cs +++ b/SecuritySystemDatabaseImplement/Migrations/20230501141820_lab6.Designer.cs @@ -12,8 +12,8 @@ using SecuritySystemDatabaseImplement; namespace SecuritySystemDatabaseImplement.Migrations { [DbContext(typeof(SecuritySystemDatabase))] - [Migration("20230423054524_with client")] - partial class withclient + [Migration("20230501141820_lab6")] + partial class lab6 { /// protected override void BuildTargetModel(ModelBuilder modelBuilder) @@ -70,6 +70,33 @@ namespace SecuritySystemDatabaseImplement.Migrations b.ToTable("Components"); }); + modelBuilder.Entity("SecuritySystemDatabaseImplement.Models.Implementer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ImplementerFIO") + .IsRequired() + .HasColumnType("text"); + + b.Property("Password") + .IsRequired() + .HasColumnType("text"); + + b.Property("Qualification") + .HasColumnType("integer"); + + b.Property("WorkExperience") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.ToTable("Implementers"); + }); + modelBuilder.Entity("SecuritySystemDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -90,6 +117,9 @@ namespace SecuritySystemDatabaseImplement.Migrations b.Property("DateImplement") .HasColumnType("timestamp with time zone"); + b.Property("ImplementerId") + .HasColumnType("integer"); + b.Property("SecureId") .HasColumnType("integer"); @@ -103,6 +133,8 @@ namespace SecuritySystemDatabaseImplement.Migrations b.HasIndex("ClientId"); + b.HasIndex("ImplementerId"); + b.HasIndex("SecureId"); b.ToTable("Orders"); @@ -162,6 +194,10 @@ namespace SecuritySystemDatabaseImplement.Migrations .OnDelete(DeleteBehavior.Cascade) .IsRequired(); + b.HasOne("SecuritySystemDatabaseImplement.Models.Implementer", "Implementer") + .WithMany("Orders") + .HasForeignKey("ImplementerId"); + b.HasOne("SecuritySystemDatabaseImplement.Models.Secure", "Secure") .WithMany("Orders") .HasForeignKey("SecureId") @@ -170,6 +206,8 @@ namespace SecuritySystemDatabaseImplement.Migrations b.Navigation("Client"); + b.Navigation("Implementer"); + b.Navigation("Secure"); }); @@ -202,6 +240,11 @@ namespace SecuritySystemDatabaseImplement.Migrations b.Navigation("SecureComponents"); }); + modelBuilder.Entity("SecuritySystemDatabaseImplement.Models.Implementer", b => + { + b.Navigation("Orders"); + }); + modelBuilder.Entity("SecuritySystemDatabaseImplement.Models.Secure", b => { b.Navigation("Components"); diff --git a/SecuritySystemDatabaseImplement/Migrations/20230423054524_with client.cs b/SecuritySystemDatabaseImplement/Migrations/20230501141820_lab6.cs similarity index 81% rename from SecuritySystemDatabaseImplement/Migrations/20230423054524_with client.cs rename to SecuritySystemDatabaseImplement/Migrations/20230501141820_lab6.cs index f262b4a..736e6cc 100644 --- a/SecuritySystemDatabaseImplement/Migrations/20230423054524_with client.cs +++ b/SecuritySystemDatabaseImplement/Migrations/20230501141820_lab6.cs @@ -7,7 +7,7 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; namespace SecuritySystemDatabaseImplement.Migrations { /// - public partial class withclient : Migration + public partial class lab6 : Migration { /// protected override void Up(MigrationBuilder migrationBuilder) @@ -41,6 +41,22 @@ namespace SecuritySystemDatabaseImplement.Migrations table.PrimaryKey("PK_Components", x => x.Id); }); + migrationBuilder.CreateTable( + name: "Implementers", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + ImplementerFIO = table.Column(type: "text", nullable: false), + Password = table.Column(type: "text", nullable: false), + WorkExperience = table.Column(type: "integer", nullable: false), + Qualification = table.Column(type: "integer", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Implementers", x => x.Id); + }); + migrationBuilder.CreateTable( name: "Secures", columns: table => new @@ -63,6 +79,7 @@ namespace SecuritySystemDatabaseImplement.Migrations .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), SecureId = table.Column(type: "integer", nullable: false), ClientId = table.Column(type: "integer", nullable: false), + ImplementerId = table.Column(type: "integer", nullable: true), Count = table.Column(type: "integer", nullable: false), Sum = table.Column(type: "double precision", nullable: false), Status = table.Column(type: "integer", nullable: false), @@ -78,6 +95,11 @@ namespace SecuritySystemDatabaseImplement.Migrations principalTable: "Clients", principalColumn: "Id", onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_Orders_Implementers_ImplementerId", + column: x => x.ImplementerId, + principalTable: "Implementers", + principalColumn: "Id"); table.ForeignKey( name: "FK_Orders_Secures_SecureId", column: x => x.SecureId, @@ -118,6 +140,11 @@ namespace SecuritySystemDatabaseImplement.Migrations table: "Orders", column: "ClientId"); + migrationBuilder.CreateIndex( + name: "IX_Orders_ImplementerId", + table: "Orders", + column: "ImplementerId"); + migrationBuilder.CreateIndex( name: "IX_Orders_SecureId", table: "Orders", @@ -146,6 +173,9 @@ namespace SecuritySystemDatabaseImplement.Migrations migrationBuilder.DropTable( name: "Clients"); + migrationBuilder.DropTable( + name: "Implementers"); + migrationBuilder.DropTable( name: "Components"); diff --git a/SecuritySystemDatabaseImplement/Migrations/SecuritySystemDatabaseModelSnapshot.cs b/SecuritySystemDatabaseImplement/Migrations/SecuritySystemDatabaseModelSnapshot.cs index 09ac6dc..0459874 100644 --- a/SecuritySystemDatabaseImplement/Migrations/SecuritySystemDatabaseModelSnapshot.cs +++ b/SecuritySystemDatabaseImplement/Migrations/SecuritySystemDatabaseModelSnapshot.cs @@ -67,6 +67,33 @@ namespace SecuritySystemDatabaseImplement.Migrations b.ToTable("Components"); }); + modelBuilder.Entity("SecuritySystemDatabaseImplement.Models.Implementer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ImplementerFIO") + .IsRequired() + .HasColumnType("text"); + + b.Property("Password") + .IsRequired() + .HasColumnType("text"); + + b.Property("Qualification") + .HasColumnType("integer"); + + b.Property("WorkExperience") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.ToTable("Implementers"); + }); + modelBuilder.Entity("SecuritySystemDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -87,6 +114,9 @@ namespace SecuritySystemDatabaseImplement.Migrations b.Property("DateImplement") .HasColumnType("timestamp with time zone"); + b.Property("ImplementerId") + .HasColumnType("integer"); + b.Property("SecureId") .HasColumnType("integer"); @@ -100,6 +130,8 @@ namespace SecuritySystemDatabaseImplement.Migrations b.HasIndex("ClientId"); + b.HasIndex("ImplementerId"); + b.HasIndex("SecureId"); b.ToTable("Orders"); @@ -159,6 +191,10 @@ namespace SecuritySystemDatabaseImplement.Migrations .OnDelete(DeleteBehavior.Cascade) .IsRequired(); + b.HasOne("SecuritySystemDatabaseImplement.Models.Implementer", "Implementer") + .WithMany("Orders") + .HasForeignKey("ImplementerId"); + b.HasOne("SecuritySystemDatabaseImplement.Models.Secure", "Secure") .WithMany("Orders") .HasForeignKey("SecureId") @@ -167,6 +203,8 @@ namespace SecuritySystemDatabaseImplement.Migrations b.Navigation("Client"); + b.Navigation("Implementer"); + b.Navigation("Secure"); }); @@ -199,6 +237,11 @@ namespace SecuritySystemDatabaseImplement.Migrations b.Navigation("SecureComponents"); }); + modelBuilder.Entity("SecuritySystemDatabaseImplement.Models.Implementer", b => + { + b.Navigation("Orders"); + }); + modelBuilder.Entity("SecuritySystemDatabaseImplement.Models.Secure", b => { b.Navigation("Components"); diff --git a/SecuritySystemDatabaseImplement/Models/Implementer.cs b/SecuritySystemDatabaseImplement/Models/Implementer.cs new file mode 100644 index 0000000..aa22756 --- /dev/null +++ b/SecuritySystemDatabaseImplement/Models/Implementer.cs @@ -0,0 +1,57 @@ +using SecuritySystemContracts.BindingModels; +using SecuritySystemContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations.Schema; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemDatabaseImplement.Models +{ + public class Implementer + { + 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; } + [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, + Password = model.Password, + WorkExperience = model.WorkExperience, + Qualification = model.Qualification, + }; + } + public void Update(ImplementerBindingModel model) + { + ImplementerFIO = model.ImplementerFIO; + Password = model.Password; + WorkExperience = model.WorkExperience; + Qualification = model.Qualification; + } + public ImplementerViewModel GetViewModel => new() + { + Id = Id, + ImplementerFIO = ImplementerFIO, + Password = Password, + WorkExperience = WorkExperience, + Qualification = Qualification, + }; + } +} diff --git a/SecuritySystemDatabaseImplement/Models/Order.cs b/SecuritySystemDatabaseImplement/Models/Order.cs index fbf58ad..013b299 100644 --- a/SecuritySystemDatabaseImplement/Models/Order.cs +++ b/SecuritySystemDatabaseImplement/Models/Order.cs @@ -2,6 +2,10 @@ using SecuritySystemContracts.ViewModels; using SecuritySystemDataModels.Enums; using SecuritySystemDataModels.Models; +using SecuritySystemContracts.BindingModels; +using SecuritySystemContracts.ViewModels; +using SecuritySystemDataModels.Enums; +using SecuritySystemDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; @@ -17,7 +21,9 @@ namespace SecuritySystemDatabaseImplement.Models public int Id { get; set; } [Required] public int SecureId { get; set; } + [Required] public int ClientId { get; set; } + public int? ImplementerId { get; set; } [Required] public int Count { get; set; } [Required] @@ -29,6 +35,7 @@ namespace SecuritySystemDatabaseImplement.Models public DateTime? DateImplement { get; set; } public virtual Secure Secure { get; set; } public virtual Client Client { get; set; } + public virtual Implementer? Implementer { get; set; } public static Order? Create(OrderBindingModel? model) { if (model == null) @@ -40,6 +47,7 @@ namespace SecuritySystemDatabaseImplement.Models Id = model.Id, SecureId = model.SecureId, ClientId = model.ClientId, + ImplementerId = model.ImplementerId, Count = model.Count, Sum = model.Sum, Status = model.Status, @@ -55,15 +63,20 @@ namespace SecuritySystemDatabaseImplement.Models } Status = model.Status; DateImplement = model.DateImplement; + if (model.ImplementerId.HasValue) + { + ImplementerId = model.ImplementerId; + } } - public OrderViewModel GetViewModel => - new() + public OrderViewModel GetViewModel => new() { Id = Id, SecureId = SecureId, SecureName = Secure.SecureName, ClientId = ClientId, ClientFIO = Client.ClientFIO, + ImplementerId = ImplementerId, + ImplementerFIO = Implementer == null ? null : Implementer.ImplementerFIO, Count = Count, Sum = Sum, Status = Status, diff --git a/SecuritySystemDatabaseImplement/SecuritySystemDatabase.cs b/SecuritySystemDatabaseImplement/SecuritySystemDatabase.cs index d1e71d7..74a8aaa 100644 --- a/SecuritySystemDatabaseImplement/SecuritySystemDatabase.cs +++ b/SecuritySystemDatabaseImplement/SecuritySystemDatabase.cs @@ -18,6 +18,6 @@ namespace SecuritySystemDatabaseImplement public virtual DbSet SecureComponents { set; get; } public virtual DbSet Orders { set; get; } public virtual DbSet Clients { set; get; } - + public virtual DbSet Implementers { set; get; } } } diff --git a/SecuritySystemFileImplement/DataFileSingletone.cs b/SecuritySystemFileImplement/DataFileSingletone.cs index 3fa222f..87e7906 100644 --- a/SecuritySystemFileImplement/DataFileSingletone.cs +++ b/SecuritySystemFileImplement/DataFileSingletone.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - + using SecuritySystemFileImplement.Models; using System.Xml.Linq; @@ -16,10 +11,12 @@ namespace SecuritySystemFileImplement private readonly string OrderFileName = "Order.xml"; private readonly string SecureFileName = "Secure.xml"; private readonly string ClientFileName = "Client.xml"; + private readonly string ImplementerFileName = "Implementer.xml"; public List Components { get; private set; } public List Orders { get; private set; } public List Secures { get; private set; } public List Clients { get; private set; } + public List Implementers { get; private set; } public static DataFileSingleton GetInstance() { if (instance == null) @@ -32,12 +29,14 @@ namespace SecuritySystemFileImplement public void SaveSecures() => SaveData(Secures, SecureFileName, "Secures", x => x.GetXElement); public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement); public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", x => x.GetXElement); + public void SaveImplementers() => SaveData(Implementers, ImplementerFileName, "Implementers", x => x.GetXElement); private DataFileSingleton() { Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!; Secures = LoadData(SecureFileName, "Secure", x => Secure.Create(x)!)!; Orders = LoadData(OrderFileName, "Order", x => 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/SecuritySystemFileImplement/Implements/ClientStorage.cs b/SecuritySystemFileImplement/Implements/ClientStorage.cs index 11e5bab..54ccb7d 100644 --- a/SecuritySystemFileImplement/Implements/ClientStorage.cs +++ b/SecuritySystemFileImplement/Implements/ClientStorage.cs @@ -1,6 +1,6 @@ using SecuritySystemContracts.BindingModels; using SecuritySystemContracts.SearchModels; -using SecuritySystemContracts.StorageContracts; +using SecuritySystemContracts.StoragesContracts; using SecuritySystemContracts.ViewModels; using SecuritySystemFileImplement.Models; using System; diff --git a/SecuritySystemFileImplement/Implements/ImplementerStorage.cs b/SecuritySystemFileImplement/Implements/ImplementerStorage.cs new file mode 100644 index 0000000..5566586 --- /dev/null +++ b/SecuritySystemFileImplement/Implements/ImplementerStorage.cs @@ -0,0 +1,83 @@ +using SecuritySystemContracts.BindingModels; +using SecuritySystemContracts.SearchModels; +using SecuritySystemContracts.StorageContracts; +using SecuritySystemContracts.ViewModels; +using SecuritySystemFileImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemFileImplement.Implements +{ + public class ImplementerStorage : IImplementerStorage + { + private readonly DataFileSingleton source; + public ImplementerStorage() + { + source = DataFileSingleton.GetInstance(); + } + 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; + } + 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 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 List GetFullList() + { + return source.Implementers.Select(x => x.GetViewModel).ToList(); + } + 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 implementer = source.Implementers.FirstOrDefault(x => x.Id == model.Id); + if (implementer == null) + { + return null; + } + implementer.Update(model); + source.SaveImplementers(); + return implementer.GetViewModel; + } + } +} diff --git a/SecuritySystemFileImplement/Models/Implementer.cs b/SecuritySystemFileImplement/Models/Implementer.cs new file mode 100644 index 0000000..ef7d9c9 --- /dev/null +++ b/SecuritySystemFileImplement/Models/Implementer.cs @@ -0,0 +1,76 @@ +using SecuritySystemContracts.BindingModels; +using SecuritySystemContracts.ViewModels; +using SecuritySystemDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace SecuritySystemFileImplement.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, + Password = model.Password, + WorkExperience = model.WorkExperience, + 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, + Password = element.Element("Password")!.Value, + WorkExperience = Convert.ToInt32(element.Element("WorkExperience")!.Value), + Qualification = Convert.ToInt32(element.Element("Qualification")!.Value) + }; + } + 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, + Password = Password, + WorkExperience = WorkExperience, + Qualification = Qualification + }; + public XElement GetXElement => new("Implementer", + new XAttribute("Id", Id), + new XElement("ImplementerFIO", ImplementerFIO), + new XElement("Password", Password), + new XElement("WorkExperience", WorkExperience), + new XElement("Qualification", Qualification)); + } +} diff --git a/SecuritySystemListImplement/DataListSingletone.cs b/SecuritySystemListImplement/DataListSingletone.cs index e687c2a..4673e48 100644 --- a/SecuritySystemListImplement/DataListSingletone.cs +++ b/SecuritySystemListImplement/DataListSingletone.cs @@ -15,12 +15,14 @@ namespace SecuritySystemListImplement public List Orders { get; set; } public List Secures { get; set; } public List Clients { get; set; } + public List Implementers { get; set; } private DataListSingleton() { Components = new List(); Orders = new List(); Secures = new List(); Clients = new List(); + Implementers = new List(); } public static DataListSingleton GetInstance() { diff --git a/SecuritySystemListImplement/Implements/ClientStorage.cs b/SecuritySystemListImplement/Implements/ClientStorage.cs index da94d79..48b1227 100644 --- a/SecuritySystemListImplement/Implements/ClientStorage.cs +++ b/SecuritySystemListImplement/Implements/ClientStorage.cs @@ -1,6 +1,6 @@ using SecuritySystemContracts.BindingModels; using SecuritySystemContracts.SearchModels; -using SecuritySystemContracts.StorageContracts; +using SecuritySystemContracts.StoragesContracts; using SecuritySystemContracts.ViewModels; using SecuritySystemListImplement.Models; diff --git a/SecuritySystemListImplement/Implements/ImplementerStorage.cs b/SecuritySystemListImplement/Implements/ImplementerStorage.cs new file mode 100644 index 0000000..0b93575 --- /dev/null +++ b/SecuritySystemListImplement/Implements/ImplementerStorage.cs @@ -0,0 +1,114 @@ +using SecuritySystemContracts.BindingModels; +using SecuritySystemContracts.SearchModels; +using SecuritySystemContracts.StorageContracts; +using SecuritySystemContracts.ViewModels; +using SecuritySystemListImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemListImplement.Implements +{ + public class ImplementerStorage : IImplementerStorage + { + private readonly DataListSingleton _source; + public ImplementerStorage() + { + _source = DataListSingleton.GetInstance(); + } + 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; + } + public ImplementerViewModel? GetElement(ImplementerSearchModel model) + { + if (model.Id.HasValue) + { + foreach (var implementer in _source.Implementers) + { + if (implementer.Id == model.Id) + { + return implementer.GetViewModel; + } + } + } + else if (!string.IsNullOrEmpty(model.ImplementerFIO)) + { + foreach (var implementer in _source.Implementers) + { + if (implementer.ImplementerFIO == model.ImplementerFIO) + { + return implementer.GetViewModel; + } + } + } + return null; + } + 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 List GetFullList() + { + var result = new List(); + foreach (var implementer in _source.Implementers) + { + result.Add(implementer.GetViewModel); + } + return result; + } + 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; + } + } +} diff --git a/SecuritySystemListImplement/Implements/OrderStorage.cs b/SecuritySystemListImplement/Implements/OrderStorage.cs index 02ab092..2c723f6 100644 --- a/SecuritySystemListImplement/Implements/OrderStorage.cs +++ b/SecuritySystemListImplement/Implements/OrderStorage.cs @@ -70,6 +70,26 @@ namespace SecuritySystemListImplement.Implements return Order.GetViewModel; } } + if (model.Id.HasValue) + { + foreach (var Order in _source.Orders) + { + if (Order.Id == model.Id) + { + return Order.GetViewModel; + } + } + } + else if (model.ImplementerId.HasValue && model.Status.HasValue) + { + foreach (var Order in _source.Orders) + { + if (Order.ImplementerId == model.ImplementerId && Order.Status == model.Status) + { + return Order.GetViewModel; + } + } + } return null; } public OrderViewModel? Insert(OrderBindingModel model) diff --git a/SecuritySystemListImplement/Models/Implementer.cs b/SecuritySystemListImplement/Models/Implementer.cs new file mode 100644 index 0000000..c43ed0e --- /dev/null +++ b/SecuritySystemListImplement/Models/Implementer.cs @@ -0,0 +1,54 @@ +using SecuritySystemContracts.BindingModels; +using SecuritySystemContracts.ViewModels; +using SecuritySystemDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SecuritySystemListImplement.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, + Password = model.Password, + WorkExperience = model.WorkExperience, + Qualification = model.Qualification, + }; + } + 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, + Password = Password, + WorkExperience = WorkExperience, + Qualification = Qualification + }; + } +} diff --git a/SecuritySystemListImplement/Models/Order.cs b/SecuritySystemListImplement/Models/Order.cs index cb02f22..119835c 100644 --- a/SecuritySystemListImplement/Models/Order.cs +++ b/SecuritySystemListImplement/Models/Order.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Reflection; using System.Text; using System.Threading.Tasks; @@ -18,6 +19,7 @@ namespace SecuritySystemListImplement.Models public int SecureId { get; private set; } public string SecureName { get; private set; } = string.Empty; public int ClientId { get; private set; } + public int? ImplementerId { get; private set; } public int Count { get; private set; } public double Sum { get; private set; } @@ -36,6 +38,8 @@ namespace SecuritySystemListImplement.Models Id = model.Id, SecureId = model.SecureId, SecureName = model.SecureName, + ClientId = model.ClientId, + ImplementerId = model.ImplementerId, Count = model.Count, Sum = model.Sum, Status = model.Status, @@ -52,14 +56,16 @@ namespace SecuritySystemListImplement.Models } Status = model.Status; - DateCreate = model.DateCreate; DateImplement = model.DateImplement; + ImplementerId = model.ImplementerId; } public OrderViewModel GetViewModel => new() { Id = Id, SecureId = SecureId, SecureName = SecureName, + ClientId = ClientId, + ImplementerId = ImplementerId, Count = Count, Sum = Sum, Status = Status, diff --git a/SecuritySystemRestApi/Controllers/ImplementerController.cs b/SecuritySystemRestApi/Controllers/ImplementerController.cs new file mode 100644 index 0000000..c0116e6 --- /dev/null +++ b/SecuritySystemRestApi/Controllers/ImplementerController.cs @@ -0,0 +1,99 @@ +using SecuritySystemContracts.BindingModels; +using SecuritySystemContracts.BusinessLogicsContracts; +using SecuritySystemContracts.SearchModels; +using SecuritySystemContracts.ViewModels; +using SecuritySystemDataModels.Enums; +using Microsoft.AspNetCore.Mvc; + +namespace SecuritySystemRestApi.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; + } + } + } +} \ No newline at end of file diff --git a/SecuritySystemRestApi/Program.cs b/SecuritySystemRestApi/Program.cs index 92655ba..fde90e8 100644 --- a/SecuritySystemRestApi/Program.cs +++ b/SecuritySystemRestApi/Program.cs @@ -3,6 +3,9 @@ using SecuritySystemContracts.BusinessLogicsContracts; using SecuritySystemContracts.StoragesContracts; using SecuritySystemDatabaseImplement.Implements; using Microsoft.OpenApi.Models; +using SecuritySystemBusinessLogic.BusinessLogics; +using SecuritySystemContracts.BusinessLogicsContracts; +using SecuritySystemContracts.StorageContracts; var builder = WebApplication.CreateBuilder(args); @@ -13,10 +16,12 @@ builder.Logging.AddLog4Net("log4net.config"); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddTransient(); builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle