From 2cbfa9799d4ab83be144d90fd1c1483405920b0a Mon Sep 17 00:00:00 2001 From: goldfest Date: Thu, 2 May 2024 01:08:11 +0400 Subject: [PATCH 1/4] =?UTF-8?q?=D0=BA=D0=BE=D0=BC=D0=BC=D0=B8=D1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../TravelCompany/FormImplementer.Designer.cs | 167 ++++++++++++++++++ .../TravelCompany/FormImplementer.cs | 94 ++++++++++ .../TravelCompany/FormImplementer.resx | 120 +++++++++++++ .../FormImplementers.Designer.cs | 130 ++++++++++++++ .../TravelCompany/FormImplementers.cs | 118 +++++++++++++ .../TravelCompany/FormImplementers.resx | 120 +++++++++++++ .../TravelCompany/FormMain.Designer.cs | 34 +++- TravelCompany/TravelCompany/FormMain.cs | 24 ++- TravelCompany/TravelCompany/Program.cs | 9 +- .../BusinessLogic/ImplementerLogic.cs | 128 ++++++++++++++ .../BusinessLogic/OrderLogic.cs | 139 ++++++++------- .../BusinessLogic/WorkModeling.cs | 134 ++++++++++++++ .../BindingModels/ImplementerBindingModel.cs | 18 ++ .../BindingModels/OrderBindingModel.cs | 1 + .../IImplementerLogic.cs | 15 ++ .../BusinessLogicsContracts/IOrderLogic.cs | 1 + .../BusinessLogicsContracts/IWorkProcess.cs | 7 + .../SearchModels/ImplementerSearchModel.cs | 9 + .../SearchModels/OrderSearchModel.cs | 3 + .../StoragesContracts/IImplementerStorage.cs | 16 ++ .../ViewModels/ImplementerViewModel.cs | 27 +++ .../ViewModels/OrderViewModel.cs | 4 + .../Models/IImplementerModel.cs | 13 ++ .../Models/IOrderModel.cs | 1 + .../Implements/ImplementerStorage.cs | 79 +++++++++ .../Implements/OrderStorage.cs | 62 ++++--- ...20240501195930_Initial-Create.Designer.cs} | 45 ++++- ...te.cs => 20240501195930_Initial-Create.cs} | 30 ++++ .../TravelCompanyDataBaseModelSnapshot.cs | 43 +++++ .../Models/Implementer.cs | 65 +++++++ .../Models/Order.cs | 73 ++++---- .../TravelCompanyDataBase.cs | 3 +- .../DataFileSingleton.cs | 7 + .../Implements/ImplementerStorage.cs | 94 ++++++++++ .../Implements/OrderStorage.cs | 2 + .../Models/Implementer.cs | 87 +++++++++ .../Models/Order.cs | 6 + .../DataListSingleton.cs | 2 + .../Implements/ImplementerStorage.cs | 118 +++++++++++++ .../Models/Implementer.cs | 60 +++++++ .../Models/Order.cs | 4 + .../Controllers/ImplementerController.cs | 107 +++++++++++ TravelCompany/TravelCompanyRestApi/Program.cs | 3 + 43 files changed, 2083 insertions(+), 139 deletions(-) create mode 100644 TravelCompany/TravelCompany/FormImplementer.Designer.cs create mode 100644 TravelCompany/TravelCompany/FormImplementer.cs create mode 100644 TravelCompany/TravelCompany/FormImplementer.resx create mode 100644 TravelCompany/TravelCompany/FormImplementers.Designer.cs create mode 100644 TravelCompany/TravelCompany/FormImplementers.cs create mode 100644 TravelCompany/TravelCompany/FormImplementers.resx create mode 100644 TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/ImplementerLogic.cs create mode 100644 TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/WorkModeling.cs create mode 100644 TravelCompany/TravelCompanyContracts/BindingModels/ImplementerBindingModel.cs create mode 100644 TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IImplementerLogic.cs create mode 100644 TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IWorkProcess.cs create mode 100644 TravelCompany/TravelCompanyContracts/SearchModels/ImplementerSearchModel.cs create mode 100644 TravelCompany/TravelCompanyContracts/StoragesContracts/IImplementerStorage.cs create mode 100644 TravelCompany/TravelCompanyContracts/ViewModels/ImplementerViewModel.cs create mode 100644 TravelCompany/TravelCompanyDataModels/Models/IImplementerModel.cs create mode 100644 TravelCompany/TravelCompanyDatabaseImplement/Implements/ImplementerStorage.cs rename TravelCompany/TravelCompanyDatabaseImplement/Migrations/{20240418113410_InitialCreate.Designer.cs => 20240501195930_Initial-Create.Designer.cs} (82%) rename TravelCompany/TravelCompanyDatabaseImplement/Migrations/{20240418113410_InitialCreate.cs => 20240501195930_Initial-Create.cs} (82%) create mode 100644 TravelCompany/TravelCompanyDatabaseImplement/Models/Implementer.cs create mode 100644 TravelCompany/TravelCompanyFileImplement/Implements/ImplementerStorage.cs create mode 100644 TravelCompany/TravelCompanyFileImplement/Models/Implementer.cs create mode 100644 TravelCompany/TravelCompanyListImplement/Implements/ImplementerStorage.cs create mode 100644 TravelCompany/TravelCompanyListImplement/Models/Implementer.cs create mode 100644 TravelCompany/TravelCompanyRestApi/Controllers/ImplementerController.cs diff --git a/TravelCompany/TravelCompany/FormImplementer.Designer.cs b/TravelCompany/TravelCompany/FormImplementer.Designer.cs new file mode 100644 index 0000000..9a96ca8 --- /dev/null +++ b/TravelCompany/TravelCompany/FormImplementer.Designer.cs @@ -0,0 +1,167 @@ +namespace TravelCompany.Forms +{ + 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() + { + this.textBoxFIO = new System.Windows.Forms.TextBox(); + this.labelFIO = new System.Windows.Forms.Label(); + this.textBoxPassword = new System.Windows.Forms.TextBox(); + this.labelPassword = new System.Windows.Forms.Label(); + this.labelWorkExperience = new System.Windows.Forms.Label(); + this.numericUpDownWorkExperience = new System.Windows.Forms.NumericUpDown(); + this.numericUpDownQualification = new System.Windows.Forms.NumericUpDown(); + this.labelQualification = new System.Windows.Forms.Label(); + this.buttonCancel = new System.Windows.Forms.Button(); + this.buttonSave = new System.Windows.Forms.Button(); + ((System.ComponentModel.ISupportInitialize)(this.numericUpDownWorkExperience)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.numericUpDownQualification)).BeginInit(); + this.SuspendLayout(); + // + // textBoxFIO + // + this.textBoxFIO.Location = new System.Drawing.Point(157, 12); + this.textBoxFIO.Name = "textBoxFIO"; + this.textBoxFIO.Size = new System.Drawing.Size(382, 27); + this.textBoxFIO.TabIndex = 3; + // + // labelFIO + // + this.labelFIO.AutoSize = true; + this.labelFIO.Location = new System.Drawing.Point(12, 15); + this.labelFIO.Name = "labelFIO"; + this.labelFIO.Size = new System.Drawing.Size(139, 20); + this.labelFIO.TabIndex = 2; + this.labelFIO.Text = "ФИО исполнителя:"; + // + // textBoxPassword + // + this.textBoxPassword.Location = new System.Drawing.Point(157, 50); + this.textBoxPassword.Name = "textBoxPassword"; + this.textBoxPassword.Size = new System.Drawing.Size(205, 27); + this.textBoxPassword.TabIndex = 5; + // + // labelPassword + // + this.labelPassword.AutoSize = true; + this.labelPassword.Location = new System.Drawing.Point(12, 53); + this.labelPassword.Name = "labelPassword"; + this.labelPassword.Size = new System.Drawing.Size(65, 20); + this.labelPassword.TabIndex = 4; + this.labelPassword.Text = "Пароль:"; + // + // labelWorkExperience + // + this.labelWorkExperience.AutoSize = true; + this.labelWorkExperience.Location = new System.Drawing.Point(12, 99); + this.labelWorkExperience.Name = "labelWorkExperience"; + this.labelWorkExperience.Size = new System.Drawing.Size(105, 20); + this.labelWorkExperience.TabIndex = 6; + this.labelWorkExperience.Text = "Опыт работы:"; + // + // numericUpDownWorkExperience + // + this.numericUpDownWorkExperience.Location = new System.Drawing.Point(157, 97); + this.numericUpDownWorkExperience.Name = "numericUpDownWorkExperience"; + this.numericUpDownWorkExperience.Size = new System.Drawing.Size(124, 27); + this.numericUpDownWorkExperience.TabIndex = 8; + // + // numericUpDownQualification + // + this.numericUpDownQualification.Location = new System.Drawing.Point(157, 142); + this.numericUpDownQualification.Name = "numericUpDownQualification"; + this.numericUpDownQualification.Size = new System.Drawing.Size(124, 27); + this.numericUpDownQualification.TabIndex = 10; + // + // labelQualification + // + this.labelQualification.AutoSize = true; + this.labelQualification.Location = new System.Drawing.Point(12, 144); + this.labelQualification.Name = "labelQualification"; + this.labelQualification.Size = new System.Drawing.Size(114, 20); + this.labelQualification.TabIndex = 9; + this.labelQualification.Text = "Квалификация:"; + // + // buttonCancel + // + this.buttonCancel.Location = new System.Drawing.Point(422, 203); + this.buttonCancel.Name = "buttonCancel"; + this.buttonCancel.Size = new System.Drawing.Size(136, 40); + this.buttonCancel.TabIndex = 12; + this.buttonCancel.Text = "Отмена"; + this.buttonCancel.UseVisualStyleBackColor = true; + this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click); + // + // buttonSave + // + this.buttonSave.Location = new System.Drawing.Point(265, 203); + this.buttonSave.Name = "buttonSave"; + this.buttonSave.Size = new System.Drawing.Size(130, 40); + this.buttonSave.TabIndex = 11; + this.buttonSave.Text = "Сохранить"; + this.buttonSave.UseVisualStyleBackColor = true; + this.buttonSave.Click += new System.EventHandler(this.buttonSave_Click); + // + // FormImplementer + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(570, 255); + this.Controls.Add(this.buttonCancel); + this.Controls.Add(this.buttonSave); + this.Controls.Add(this.numericUpDownQualification); + this.Controls.Add(this.labelQualification); + this.Controls.Add(this.numericUpDownWorkExperience); + this.Controls.Add(this.labelWorkExperience); + this.Controls.Add(this.textBoxPassword); + this.Controls.Add(this.labelPassword); + this.Controls.Add(this.textBoxFIO); + this.Controls.Add(this.labelFIO); + this.Name = "FormImplementer"; + this.Text = "Исполнитель"; + this.Load += new System.EventHandler(this.FormImplementer_Load); + ((System.ComponentModel.ISupportInitialize)(this.numericUpDownWorkExperience)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.numericUpDownQualification)).EndInit(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private TextBox textBoxFIO; + private Label labelFIO; + private TextBox textBoxPassword; + private Label labelPassword; + private Label labelWorkExperience; + private NumericUpDown numericUpDownWorkExperience; + private NumericUpDown numericUpDownQualification; + private Label labelQualification; + private Button buttonCancel; + private Button buttonSave; + } +} \ No newline at end of file diff --git a/TravelCompany/TravelCompany/FormImplementer.cs b/TravelCompany/TravelCompany/FormImplementer.cs new file mode 100644 index 0000000..b93a786 --- /dev/null +++ b/TravelCompany/TravelCompany/FormImplementer.cs @@ -0,0 +1,94 @@ +using Microsoft.Extensions.Logging; +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.BusinessLogicsContracts; +using TravelCompanyContracts.SearchModels; + +namespace TravelCompany.Forms +{ + 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 FormImplementer_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; + numericUpDownWorkExperience.Value = view.WorkExperience; + numericUpDownQualification.Value = view.Qualification; + } + } + 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; + } + _logger.LogInformation("Сохранение исполнителя"); + try + { + var model = new ImplementerBindingModel + { + Id = _id ?? 0, + ImplementerFIO = textBoxFIO.Text, + Password = textBoxPassword.Text, + WorkExperience = (int)numericUpDownWorkExperience.Value, + Qualification = (int)numericUpDownQualification.Value + }; + 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/TravelCompany/TravelCompany/FormImplementer.resx b/TravelCompany/TravelCompany/FormImplementer.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/TravelCompany/TravelCompany/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/TravelCompany/TravelCompany/FormImplementers.Designer.cs b/TravelCompany/TravelCompany/FormImplementers.Designer.cs new file mode 100644 index 0000000..fcef1c5 --- /dev/null +++ b/TravelCompany/TravelCompany/FormImplementers.Designer.cs @@ -0,0 +1,130 @@ +namespace TravelCompany.Forms +{ + 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.ToolsPanel = new System.Windows.Forms.Panel(); + this.buttonRef = new System.Windows.Forms.Button(); + this.buttonDel = new System.Windows.Forms.Button(); + this.buttonUpd = new System.Windows.Forms.Button(); + this.buttonAdd = new System.Windows.Forms.Button(); + this.dataGridView = new System.Windows.Forms.DataGridView(); + this.ToolsPanel.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); + this.SuspendLayout(); + // + // ToolsPanel + // + this.ToolsPanel.Controls.Add(this.buttonRef); + this.ToolsPanel.Controls.Add(this.buttonDel); + this.ToolsPanel.Controls.Add(this.buttonUpd); + this.ToolsPanel.Controls.Add(this.buttonAdd); + this.ToolsPanel.Location = new System.Drawing.Point(608, 12); + this.ToolsPanel.Name = "ToolsPanel"; + this.ToolsPanel.Size = new System.Drawing.Size(180, 426); + this.ToolsPanel.TabIndex = 3; + // + // buttonRef + // + this.buttonRef.Location = new System.Drawing.Point(31, 206); + this.buttonRef.Name = "buttonRef"; + this.buttonRef.Size = new System.Drawing.Size(126, 36); + this.buttonRef.TabIndex = 3; + this.buttonRef.Text = "Обновить"; + this.buttonRef.UseVisualStyleBackColor = true; + this.buttonRef.Click += new System.EventHandler(this.buttonRef_Click); + // + // buttonDel + // + this.buttonDel.Location = new System.Drawing.Point(31, 142); + this.buttonDel.Name = "buttonDel"; + this.buttonDel.Size = new System.Drawing.Size(126, 36); + this.buttonDel.TabIndex = 2; + this.buttonDel.Text = "Удалить"; + this.buttonDel.UseVisualStyleBackColor = true; + this.buttonDel.Click += new System.EventHandler(this.buttonDel_Click); + // + // buttonUpd + // + this.buttonUpd.Location = new System.Drawing.Point(31, 76); + this.buttonUpd.Name = "buttonUpd"; + this.buttonUpd.Size = new System.Drawing.Size(126, 36); + this.buttonUpd.TabIndex = 1; + this.buttonUpd.Text = "Изменить"; + this.buttonUpd.UseVisualStyleBackColor = true; + this.buttonUpd.Click += new System.EventHandler(this.buttonUpd_Click); + // + // buttonAdd + // + this.buttonAdd.Location = new System.Drawing.Point(31, 16); + this.buttonAdd.Name = "buttonAdd"; + this.buttonAdd.Size = new System.Drawing.Size(126, 36); + this.buttonAdd.TabIndex = 0; + this.buttonAdd.Text = "Добавить"; + this.buttonAdd.UseVisualStyleBackColor = true; + this.buttonAdd.Click += new System.EventHandler(this.buttonAdd_Click); + // + // dataGridView + // + this.dataGridView.AllowUserToAddRows = false; + this.dataGridView.AllowUserToDeleteRows = false; + this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView.Location = new System.Drawing.Point(12, 12); + this.dataGridView.Name = "dataGridView"; + this.dataGridView.ReadOnly = true; + this.dataGridView.RowHeadersWidth = 51; + this.dataGridView.RowTemplate.Height = 29; + this.dataGridView.Size = new System.Drawing.Size(590, 426); + this.dataGridView.TabIndex = 2; + // + // FormImplementers + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 450); + this.Controls.Add(this.ToolsPanel); + this.Controls.Add(this.dataGridView); + this.Name = "FormImplementers"; + this.Text = "Исполнители"; + this.Load += new System.EventHandler(this.FormImplementers_Load); + this.ToolsPanel.ResumeLayout(false); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit(); + this.ResumeLayout(false); + + } + + #endregion + + private Panel ToolsPanel; + private Button buttonRef; + private Button buttonDel; + private Button buttonUpd; + private Button buttonAdd; + private DataGridView dataGridView; + } +} \ No newline at end of file diff --git a/TravelCompany/TravelCompany/FormImplementers.cs b/TravelCompany/TravelCompany/FormImplementers.cs new file mode 100644 index 0000000..35ebb2d --- /dev/null +++ b/TravelCompany/TravelCompany/FormImplementers.cs @@ -0,0 +1,118 @@ +using Microsoft.Extensions.Logging; +using TravelCompany; +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.BusinessLogicsContracts; +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 TravelCompany.Forms +{ + public partial class FormImplementers : Form + { + private readonly ILogger _logger; + private readonly IImplementerLogic _logic; + + public FormImplementers(ILogger logger, IImplementerLogic implementerLogic) + { + InitializeComponent(); + _logger = logger; + _logic = implementerLogic; + } + + 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 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/TravelCompany/TravelCompany/FormImplementers.resx b/TravelCompany/TravelCompany/FormImplementers.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/TravelCompany/TravelCompany/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/TravelCompany/TravelCompany/FormMain.Designer.cs b/TravelCompany/TravelCompany/FormMain.Designer.cs index e3b2b36..41add46 100644 --- a/TravelCompany/TravelCompany/FormMain.Designer.cs +++ b/TravelCompany/TravelCompany/FormMain.Designer.cs @@ -33,17 +33,19 @@ toolStripDropDownButton1 = new ToolStripDropDownButton(); компонентыToolStripMenuItem = new ToolStripMenuItem(); ПутёвкиToolStripMenuItem = new ToolStripMenuItem(); + клиентыToolStripMenuItem = new ToolStripMenuItem(); отчетыToolStripMenuItem = new ToolStripMenuItem(); списокКомпонентовToolStripMenuItem = new ToolStripMenuItem(); компонентыПоПутёвкамToolStripMenuItem = new ToolStripMenuItem(); списокЗаказовToolStripMenuItem = new ToolStripMenuItem(); + запускРаботToolStripMenuItem = new ToolStripMenuItem(); buttonCreateOrder = new Button(); buttonTakeOrderInWork = new Button(); buttonOrderReady = new Button(); buttonIssuedOrder = new Button(); buttonRef = new Button(); dataGridView = new DataGridView(); - клиентыToolStripMenuItem = new ToolStripMenuItem(); + исполнителиToolStripMenuItem = new ToolStripMenuItem(); toolStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); SuspendLayout(); @@ -51,7 +53,7 @@ // toolStrip1 // toolStrip1.ImageScalingSize = new Size(20, 20); - toolStrip1.Items.AddRange(new ToolStripItem[] { toolStripDropDownButton1, отчетыToolStripMenuItem }); + toolStrip1.Items.AddRange(new ToolStripItem[] { toolStripDropDownButton1, отчетыToolStripMenuItem, запускРаботToolStripMenuItem }); toolStrip1.Location = new Point(0, 0); toolStrip1.Name = "toolStrip1"; toolStrip1.Size = new Size(969, 25); @@ -61,7 +63,7 @@ // toolStripDropDownButton1 // toolStripDropDownButton1.DisplayStyle = ToolStripItemDisplayStyle.Text; - toolStripDropDownButton1.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, ПутёвкиToolStripMenuItem, клиентыToolStripMenuItem }); + toolStripDropDownButton1.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, ПутёвкиToolStripMenuItem, клиентыToolStripMenuItem, исполнителиToolStripMenuItem }); toolStripDropDownButton1.Image = (Image)resources.GetObject("toolStripDropDownButton1.Image"); toolStripDropDownButton1.ImageTransparentColor = Color.Magenta; toolStripDropDownButton1.Name = "toolStripDropDownButton1"; @@ -82,6 +84,13 @@ ПутёвкиToolStripMenuItem.Text = "Туристич. путёвки"; ПутёвкиToolStripMenuItem.Click += консервыToolStripMenuItem_Click; // + // клиентыToolStripMenuItem + // + клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; + клиентыToolStripMenuItem.Size = new Size(180, 22); + клиентыToolStripMenuItem.Text = "Клиенты"; + клиентыToolStripMenuItem.Click += клиентыToolStripMenuItem_Click; + // // отчетыToolStripMenuItem // отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокКомпонентовToolStripMenuItem, компонентыПоПутёвкамToolStripMenuItem, списокЗаказовToolStripMenuItem }); @@ -110,6 +119,13 @@ списокЗаказовToolStripMenuItem.Text = "Список заказов"; списокЗаказовToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click; // + // запускРаботToolStripMenuItem + // + запускРаботToolStripMenuItem.Name = "запускРаботToolStripMenuItem"; + запускРаботToolStripMenuItem.Size = new Size(92, 25); + запускРаботToolStripMenuItem.Text = "Запуск работ"; + запускРаботToolStripMenuItem.Click += startWorkToolStripMenuItem_Click; + // // buttonCreateOrder // buttonCreateOrder.Location = new Point(800, 56); @@ -172,12 +188,12 @@ dataGridView.Size = new Size(763, 435); dataGridView.TabIndex = 6; // - // клиентыToolStripMenuItem + // исполнителиToolStripMenuItem // - клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; - клиентыToolStripMenuItem.Size = new Size(180, 22); - клиентыToolStripMenuItem.Text = "Клиенты"; - клиентыToolStripMenuItem.Click += клиентыToolStripMenuItem_Click; + исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; + исполнителиToolStripMenuItem.Size = new Size(180, 22); + исполнителиToolStripMenuItem.Text = "Исполнители"; + исполнителиToolStripMenuItem.Click += employersToolStripMenuItem_Click; // // FormMain // @@ -218,5 +234,7 @@ private ToolStripMenuItem компонентыПоПутёвкамToolStripMenuItem; private ToolStripMenuItem списокЗаказовToolStripMenuItem; private ToolStripMenuItem клиентыToolStripMenuItem; + private ToolStripMenuItem запускРаботToolStripMenuItem; + private ToolStripMenuItem исполнителиToolStripMenuItem; } } \ No newline at end of file diff --git a/TravelCompany/TravelCompany/FormMain.cs b/TravelCompany/TravelCompany/FormMain.cs index dbe9ade..e3f5f41 100644 --- a/TravelCompany/TravelCompany/FormMain.cs +++ b/TravelCompany/TravelCompany/FormMain.cs @@ -19,12 +19,14 @@ namespace TravelCompany.Forms 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) { @@ -41,7 +43,10 @@ namespace TravelCompany.Forms { dataGridView.DataSource = list; dataGridView.Columns["TravelId"].Visible = false; - dataGridView.Columns["TravelName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["ImplementerId"].Visible = false; + dataGridView.Columns["TravelName"].AutoSizeMode = + DataGridViewAutoSizeColumnMode.Fill; } _logger.LogInformation("Загрузка заказов"); @@ -198,5 +203,20 @@ Program.ServiceProvider?.GetService(typeof(FormClients)); form.ShowDialog(); } } + private void employersToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormImplementers)); + if (service is FormImplementers form) + { + form.ShowDialog(); + } + } + + private void startWorkToolStripMenuItem_Click(object sender, EventArgs e) + { + _workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic); + MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } } diff --git a/TravelCompany/TravelCompany/Program.cs b/TravelCompany/TravelCompany/Program.cs index d57b9c3..c8948df 100644 --- a/TravelCompany/TravelCompany/Program.cs +++ b/TravelCompany/TravelCompany/Program.cs @@ -7,6 +7,7 @@ using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; using TravelCompanyBusinessLogic.OfficePackage.Implements; using TravelCompanyBusinessLogic.OfficePackage; +using Microsoft.EntityFrameworkCore.Design; namespace TravelCompany.Forms @@ -40,13 +41,16 @@ namespace TravelCompany.Forms 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(); @@ -61,6 +65,9 @@ namespace TravelCompany.Forms services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); } } diff --git a/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/ImplementerLogic.cs b/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/ImplementerLogic.cs new file mode 100644 index 0000000..222035b --- /dev/null +++ b/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/ImplementerLogic.cs @@ -0,0 +1,128 @@ +using Microsoft.Extensions.Logging; +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.BusinessLogicsContracts; +using TravelCompanyContracts.SearchModels; +using TravelCompanyContracts.StoragesContracts; +using TravelCompanyContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TravelCompanyBusinessLogic.BusinessLogic +{ + public class ImplementerLogic : IImplementerLogic + { + private readonly ILogger _logger; + private readonly IImplementerStorage _implementerStorage; + + public ImplementerLogic(ILogger logger, IImplementerStorage implementerStorage) + { + _logger = logger; + _implementerStorage = implementerStorage; + } + + public List? ReadList(ImplementerSearchModel? model) + { + _logger.LogInformation("ReadList. ImplementerFIO:{ImplementerFIO}.Password:{Password}.Id:{ Id}", model?.ImplementerFIO, model?.Password?.Length, 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 ImplementerViewModel? ReadElement(ImplementerSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + _logger.LogInformation("ReadElement. ImplementerFIO:{ImplementerFIO}.Password:{Password}.Id:{ Id}", model?.ImplementerFIO, model?.Password?.Length, 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 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 (string.IsNullOrEmpty(model.Password)) + { + throw new ArgumentNullException("Нет пароля исполнителя", nameof(model.Password)); + } + if (model.WorkExperience < 0) + { + throw new ArgumentNullException("Стаж должен быть больше 0", nameof(model.WorkExperience)); + } + if (model.Qualification < 0) + { + throw new ArgumentNullException("Квалификация должна быть положительной", nameof(model.Qualification)); + } + _logger.LogInformation("Implementer. ImplementerFIO:{ImplementerFIO}.Password:{Password}.WorkExperience:{WorkExperience}.Qualification:{Qualification}.Id: { Id}", + model.ImplementerFIO, model.Password, model.WorkExperience, model.Qualification, model.Id); + var element = _implementerStorage.GetElement(new ImplementerSearchModel + { + ImplementerFIO = model.ImplementerFIO + }); + if (element != null && element.Id != model.Id) + { + throw new InvalidOperationException("Исполнитель с таким ФИО уже есть"); + } + } + } +} diff --git a/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/OrderLogic.cs b/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/OrderLogic.cs index e7c1295..b24ebbf 100644 --- a/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/OrderLogic.cs +++ b/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/OrderLogic.cs @@ -1,36 +1,46 @@ -using TravelCompanyContracts.BindingModels; +using TravelCompanyDataModels.Enums; +using Microsoft.Extensions.Logging; +using TravelCompanyContracts.BindingModels; using TravelCompanyContracts.BusinessLogicsContracts; using TravelCompanyContracts.SearchModels; using TravelCompanyContracts.StoragesContracts; using TravelCompanyContracts.ViewModels; -using TravelCompanyDataModels.Enums; -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace TravelCompanyBusinessLogic.BusinessLogic { public class OrderLogic : IOrderLogic { - //Класс с логикой для заказов будет отвечать за получение списка заказов, - //создания заказа и смены его статусов. Следует учитывать, что у заказа можно - //менять статус на новый, если его текущий статус предшествует новому - private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; - + static readonly object _locker = new object(); public OrderLogic(ILogger logger, IOrderStorage orderStorage) { _logger = logger; _orderStorage = orderStorage; } + public OrderViewModel? ReadElement(OrderSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + _logger.LogInformation("ReadElement. ClientId:{ClientId}.Status:{Status}.ImplementerId:{ImplementerId}.DateFrom:{DateFrom}.DateTo:{DateTo}OrderId:{Id}", + model.ClientId, model.Status, model.ImplementerId, 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 List? ReadList(OrderSearchModel? model) { - _logger.LogInformation("ReadList. OrderId:{Id}", model?.Id); + _logger.LogInformation("ReadList. ClientId:{ClientId}.Status:{Status}.ImplementerId:{ImplementerId}.DateFrom:{DateFrom}.DateTo:{DateTo}OrderId:{Id}", + model?.ClientId, model?.Status, model?.ImplementerId, model?.DateFrom, model?.DateTo, model?.Id); var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model); if (list == null) { @@ -44,14 +54,11 @@ namespace TravelCompanyBusinessLogic.BusinessLogic public bool CreateOrder(OrderBindingModel model) { CheckModel(model); - if (model.Status != OrderStatus.Неизвестен) return false; model.Status = OrderStatus.Принят; - if (_orderStorage.Insert(model) == null) { - model.Status = OrderStatus.Неизвестен; _logger.LogWarning("Insert operation failed"); return false; } @@ -60,57 +67,20 @@ namespace TravelCompanyBusinessLogic.BusinessLogic public bool TakeOrderInWork(OrderBindingModel model) { - return ToNextStatus(model, OrderStatus.Выполняется); + lock (_locker) + { + return ChangeStatus(model, OrderStatus.Выполняется); + } } public bool FinishOrder(OrderBindingModel model) { - return ToNextStatus(model, OrderStatus.Готов); + return ChangeStatus(model, OrderStatus.Готов); } public bool DeliveryOrder(OrderBindingModel model) { - return ToNextStatus(model, OrderStatus.Выдан); - } - - public bool ToNextStatus(OrderBindingModel model, OrderStatus orderStatus) - { - CheckModel(model, false); - var element = _orderStorage.GetElement(new OrderSearchModel() - { - Id = model.Id - }); - if (element == null) - { - throw new ArgumentNullException(nameof(element)); - } - - model.TravelId = element.TravelId; - model.DateCreate = element.DateCreate; - model.DateImplement = element.DateImplement; - model.Status = element.Status; - model.Count = element.Count; - model.Sum = element.Sum; - - if (model.Status != orderStatus - 1) - { - _logger.LogWarning("Status update to " + orderStatus + " operation failed"); - return false; - } - model.Status = orderStatus; - - if (model.Status == OrderStatus.Выдан) - { - model.DateImplement = DateTime.Now; - } - - if (_orderStorage.Update(model) == null) - { - model.Status--; - _logger.LogWarning("Changing status operation faled"); - return false; - } - return true; + return ChangeStatus(model, OrderStatus.Выдан); } private void CheckModel(OrderBindingModel model, bool withParams = true) @@ -125,17 +95,58 @@ namespace TravelCompanyBusinessLogic.BusinessLogic } if (model.Count <= 0) { - throw new ArgumentNullException("Количество изделий должно быть больше 0", nameof(model.Count)); + throw new ArgumentException("Колличество пиццы в заказе не может быть меньше 1", nameof(model.Count)); } if (model.Sum <= 0) { - throw new ArgumentNullException("Цена заказа должна быть больше 0", nameof(model.Sum)); + throw new ArgumentException("Стоимость заказа на может быть меньше 1", nameof(model.Sum)); } if (model.DateImplement.HasValue && model.DateImplement < model.DateCreate) { - throw new ArithmeticException($"Дата выдачи заказа {model.DateImplement} должна быть позже даты его создания {model.DateCreate}"); + throw new ArithmeticException($"Дата выдачи заказа {model.DateImplement} не может быть раньше даты его создания {model.DateCreate}"); } - _logger.LogInformation("Travel. TravelId:{TravelId}.Count:{Count}.Sum:{Sum}Id:{Id}", model.TravelId, model.Count, model.Sum, model.Id); + _logger.LogInformation("Travel. TravelId:{TravelId}.Count:{Count}.Sum:{Sum}Id:{Id}", + model.TravelId, model.Count, model.Sum, model.Id); + } + + private bool ChangeStatus(OrderBindingModel model, OrderStatus requiredStatus) + { + CheckModel(model, false); + var element = _orderStorage.GetElement(new OrderSearchModel() + { + Id = model.Id + }); + if (element == null) + { + throw new InvalidOperationException(nameof(element)); + } + model.DateCreate = element.DateCreate; + model.TravelId = element.TravelId; + model.DateImplement = element.DateImplement; + model.ClientId = element.ClientId; + if (!model.ImplementerId.HasValue) + { + model.ImplementerId = element.ImplementerId; + } + model.Status = element.Status; + model.Count = element.Count; + model.Sum = element.Sum; + if (requiredStatus - model.Status == 1) + { + model.Status = requiredStatus; + if (model.Status == OrderStatus.Готов) + { + model.DateImplement = DateTime.Now; + } + if (_orderStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + return true; + } + _logger.LogWarning("Changing status operation faled: Current-{Status}:required-{requiredStatus}.", model.Status, requiredStatus); + throw new InvalidOperationException($"Невозможно приствоить статус {requiredStatus} заказу с текущим статусом {model.Status}"); } } } diff --git a/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/WorkModeling.cs b/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/WorkModeling.cs new file mode 100644 index 0000000..532d0eb --- /dev/null +++ b/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/WorkModeling.cs @@ -0,0 +1,134 @@ +using Microsoft.Extensions.Logging; +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.BusinessLogicsContracts; +using TravelCompanyContracts.SearchModels; +using TravelCompanyContracts.ViewModels; +using TravelCompanyDataModels.Enums; + +namespace TravelCompanyBusinessLogic.BusinessLogic +{ + 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 + }); + } + // кто-то мог уже перехватить заказ, игнорируем ошибку + catch (InvalidOperationException ex) + { + _logger.LogWarning(ex, "Error try get work"); + } + // заканчиваем выполнение имитации в случае иной ошибки + catch (Exception ex) + { + _logger.LogError(ex, "Error while do work"); + throw; + } + // отдыхаем + Thread.Sleep(implementer.Qualification * _rnd.Next(10, 100)); + } + }); + } + + 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/TravelCompany/TravelCompanyContracts/BindingModels/ImplementerBindingModel.cs b/TravelCompany/TravelCompanyContracts/BindingModels/ImplementerBindingModel.cs new file mode 100644 index 0000000..601dd04 --- /dev/null +++ b/TravelCompany/TravelCompanyContracts/BindingModels/ImplementerBindingModel.cs @@ -0,0 +1,18 @@ +using TravelCompanyDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TravelCompanyContracts.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/TravelCompany/TravelCompanyContracts/BindingModels/OrderBindingModel.cs b/TravelCompany/TravelCompanyContracts/BindingModels/OrderBindingModel.cs index 3fbeb01..1645eed 100644 --- a/TravelCompany/TravelCompanyContracts/BindingModels/OrderBindingModel.cs +++ b/TravelCompany/TravelCompanyContracts/BindingModels/OrderBindingModel.cs @@ -13,6 +13,7 @@ namespace TravelCompanyContracts.BindingModels public int Id { get; set; } public int TravelId { get; set; } public int ClientId { get; set; } + public int? ImplementerId { get; set; } public int Count { get; set; } public double Sum { get; set; } public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; diff --git a/TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IImplementerLogic.cs b/TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IImplementerLogic.cs new file mode 100644 index 0000000..2b4bcb1 --- /dev/null +++ b/TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IImplementerLogic.cs @@ -0,0 +1,15 @@ +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.SearchModels; +using TravelCompanyContracts.ViewModels; + +namespace TravelCompanyContracts.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/TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IOrderLogic.cs b/TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IOrderLogic.cs index 03a4beb..4b5e550 100644 --- a/TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IOrderLogic.cs +++ b/TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IOrderLogic.cs @@ -26,5 +26,6 @@ namespace TravelCompanyContracts.BusinessLogicsContracts /// /// bool DeliveryOrder(OrderBindingModel model); + OrderViewModel? ReadElement(OrderSearchModel model); } } diff --git a/TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IWorkProcess.cs b/TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IWorkProcess.cs new file mode 100644 index 0000000..1e62835 --- /dev/null +++ b/TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IWorkProcess.cs @@ -0,0 +1,7 @@ +namespace TravelCompanyContracts.BusinessLogicsContracts +{ + public interface IWorkProcess + { + void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic); + } +} diff --git a/TravelCompany/TravelCompanyContracts/SearchModels/ImplementerSearchModel.cs b/TravelCompany/TravelCompanyContracts/SearchModels/ImplementerSearchModel.cs new file mode 100644 index 0000000..25eba3c --- /dev/null +++ b/TravelCompany/TravelCompanyContracts/SearchModels/ImplementerSearchModel.cs @@ -0,0 +1,9 @@ +namespace TravelCompanyContracts.SearchModels +{ + public class ImplementerSearchModel + { + public int? Id { get; set; } + public string? ImplementerFIO { get; set; } + public string? Password { get; set; } + } +} diff --git a/TravelCompany/TravelCompanyContracts/SearchModels/OrderSearchModel.cs b/TravelCompany/TravelCompanyContracts/SearchModels/OrderSearchModel.cs index ffcf4c0..55c45ea 100644 --- a/TravelCompany/TravelCompanyContracts/SearchModels/OrderSearchModel.cs +++ b/TravelCompany/TravelCompanyContracts/SearchModels/OrderSearchModel.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using TravelCompanyDataModels.Enums; namespace TravelCompanyContracts.SearchModels { @@ -10,6 +11,8 @@ namespace TravelCompanyContracts.SearchModels { public int? Id { get; set; } public int? ClientId { get; set; } + public int? ImplementerId { get; set; } + public OrderStatus? Status { get; set; } public DateTime? DateFrom { get; set; } public DateTime? DateTo { get; set; } } diff --git a/TravelCompany/TravelCompanyContracts/StoragesContracts/IImplementerStorage.cs b/TravelCompany/TravelCompanyContracts/StoragesContracts/IImplementerStorage.cs new file mode 100644 index 0000000..6ab3892 --- /dev/null +++ b/TravelCompany/TravelCompanyContracts/StoragesContracts/IImplementerStorage.cs @@ -0,0 +1,16 @@ +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.SearchModels; +using TravelCompanyContracts.ViewModels; + +namespace TravelCompanyContracts.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/TravelCompany/TravelCompanyContracts/ViewModels/ImplementerViewModel.cs b/TravelCompany/TravelCompanyContracts/ViewModels/ImplementerViewModel.cs new file mode 100644 index 0000000..553921d --- /dev/null +++ b/TravelCompany/TravelCompanyContracts/ViewModels/ImplementerViewModel.cs @@ -0,0 +1,27 @@ +using TravelCompanyDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TravelCompanyContracts.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/TravelCompany/TravelCompanyContracts/ViewModels/OrderViewModel.cs b/TravelCompany/TravelCompanyContracts/ViewModels/OrderViewModel.cs index bc1f117..7664779 100644 --- a/TravelCompany/TravelCompanyContracts/ViewModels/OrderViewModel.cs +++ b/TravelCompany/TravelCompanyContracts/ViewModels/OrderViewModel.cs @@ -20,6 +20,10 @@ namespace TravelCompanyContracts.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; } = null; + [DisplayName("Путёвка")] public string TravelName { get; set; } = string.Empty; [DisplayName("Количество")] diff --git a/TravelCompany/TravelCompanyDataModels/Models/IImplementerModel.cs b/TravelCompany/TravelCompanyDataModels/Models/IImplementerModel.cs new file mode 100644 index 0000000..6bfdb52 --- /dev/null +++ b/TravelCompany/TravelCompanyDataModels/Models/IImplementerModel.cs @@ -0,0 +1,13 @@ +namespace TravelCompanyDataModels.Models +{ + public interface IImplementerModel : IId + { + string ImplementerFIO { get; } + + string Password { get; } + + int WorkExperience { get; } + + int Qualification { get; } + } +} diff --git a/TravelCompany/TravelCompanyDataModels/Models/IOrderModel.cs b/TravelCompany/TravelCompanyDataModels/Models/IOrderModel.cs index 5d9d8d9..a0bf921 100644 --- a/TravelCompany/TravelCompanyDataModels/Models/IOrderModel.cs +++ b/TravelCompany/TravelCompanyDataModels/Models/IOrderModel.cs @@ -6,6 +6,7 @@ namespace TravelCompanyDataModels.Models { int TravelId { get; } int ClientId { get; } + int? ImplementerId { get; } int Count { get; } double Sum { get; } OrderStatus Status { get; } diff --git a/TravelCompany/TravelCompanyDatabaseImplement/Implements/ImplementerStorage.cs b/TravelCompany/TravelCompanyDatabaseImplement/Implements/ImplementerStorage.cs new file mode 100644 index 0000000..2f6e092 --- /dev/null +++ b/TravelCompany/TravelCompanyDatabaseImplement/Implements/ImplementerStorage.cs @@ -0,0 +1,79 @@ +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.SearchModels; +using TravelCompanyContracts.StoragesContracts; +using TravelCompanyContracts.ViewModels; +using TravelCompanyDatabaseImplement.Models; + +namespace TravelCompanyDatabaseImplement.Implements +{ + public class ImplementerStorage : IImplementerStorage + { + public List GetFullList() + { + using var context = new TravelCompanyDataBase(); + return context.Implementers.Select(x => x.GetViewModel).ToList(); + } + + public List GetFilteredList(ImplementerSearchModel model) + { + if (string.IsNullOrEmpty(model.ImplementerFIO)) + { + return new(); + } + using var context = new TravelCompanyDataBase(); + return context.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; + } + using var context = new TravelCompanyDataBase(); + return context.Implementers.FirstOrDefault(x => + (!string.IsNullOrEmpty(model.ImplementerFIO) && x.ImplementerFIO == model.ImplementerFIO && (!string.IsNullOrEmpty(model.Password) ? x.Password == model.Password : true)) || + (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 TravelCompanyDataBase(); + context.Implementers.Add(newImplementer); + context.SaveChanges(); + return newImplementer.GetViewModel; + } + + public ImplementerViewModel? Update(ImplementerBindingModel model) + { + using var context = new TravelCompanyDataBase(); + var implementer = context.Implementers.FirstOrDefault(x => x.Id == model.Id); + if (implementer == null) + { + return null; + } + implementer.Update(model); + context.SaveChanges(); + return implementer.GetViewModel; + } + + public ImplementerViewModel? Delete(ImplementerBindingModel model) + { + using var context = new TravelCompanyDataBase(); + 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/TravelCompany/TravelCompanyDatabaseImplement/Implements/OrderStorage.cs b/TravelCompany/TravelCompanyDatabaseImplement/Implements/OrderStorage.cs index 1bc439c..7d733bf 100644 --- a/TravelCompany/TravelCompanyDatabaseImplement/Implements/OrderStorage.cs +++ b/TravelCompany/TravelCompanyDatabaseImplement/Implements/OrderStorage.cs @@ -4,11 +4,7 @@ using TravelCompanyContracts.StoragesContracts; using TravelCompanyContracts.ViewModels; using TravelCompanyDatabaseImplement.Models; using Microsoft.EntityFrameworkCore; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using TravelCompanyDatabaseImplement; namespace TravelCompanyDatabaseImplement.Implements { @@ -17,39 +13,41 @@ namespace TravelCompanyDatabaseImplement.Implements public List GetFullList() { using var context = new TravelCompanyDataBase(); - return context.Orders.Include(x => x.Travel) - .Include(x => x.Client).Select(x => x.GetViewModel) - .ToList(); + return context.Orders.Include(x => x.Travel).Include(x => x.Client).Include(y => y.Implementer).Select(x => x.GetViewModel).ToList(); } + public List GetFilteredList(OrderSearchModel model) { - using var context = new TravelCompanyDataBase(); - return context.Orders - .Include(x => x.Travel) - .Include(x => x.Client).Where(x => ( - (!model.Id.HasValue || x.Id == model.Id) && - (!model.DateFrom.HasValue || x.DateCreate >= model.DateFrom) && - (!model.DateTo.HasValue || x.DateCreate <= model.DateTo) - && - (!model.ClientId.HasValue || x.ClientId == model.ClientId) - ) - ) - .Select(x => x.GetViewModel) - .ToList(); + if ((!model.DateFrom.HasValue || !model.DateTo.HasValue) && !model.ClientId.HasValue && !model.Status.HasValue) + { + return new(); + } + return context.Orders.Include(x => x.Travel).Include(x => x.Client).Include(x => x.Implementer).Where(x => + (model.DateFrom.HasValue && model.DateTo.HasValue && x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo) || + (model.ClientId.HasValue && x.ClientId == model.ClientId) || + (model.Status.HasValue && x.Status == model.Status)) + .Select(x => x.GetViewModel).ToList(); } + public OrderViewModel? GetElement(OrderSearchModel model) { - if (!model.Id.HasValue) + if (!model.Id.HasValue && (!model.ImplementerId.HasValue || !model.Status.HasValue)) { - return null; + return new(); } using var context = new TravelCompanyDataBase(); - return context.Orders.Include(x => x.Travel).Include(x => x.Client).FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; + return context.Orders.Include(x => x.Travel).Include(x => x.Client).Include(x => x.Implementer).FirstOrDefault(x => + (model.Id.HasValue && x.Id == model.Id) || + (model.ImplementerId.HasValue && x.ImplementerId == model.ImplementerId && x.Status == model.Status)) + ?.GetViewModel; } + public OrderViewModel? Insert(OrderBindingModel model) { using var context = new TravelCompanyDataBase(); + if (model == null) + return null; var newOrder = Order.Create(context, model); if (newOrder == null) { @@ -59,29 +57,29 @@ namespace TravelCompanyDatabaseImplement.Implements context.SaveChanges(); return newOrder.GetViewModel; } + public OrderViewModel? Update(OrderBindingModel model) { using var context = new TravelCompanyDataBase(); - var order = context.Orders.Include(x => x.Travel).Include(x => x.Client).FirstOrDefault(x => x.Id == - model.Id); + var order = context.Orders.FirstOrDefault(x => x.Id == model.Id); if (order == null) { return null; } - order.Update(model); + order.Update(context, model); context.SaveChanges(); return order.GetViewModel; } + public OrderViewModel? Delete(OrderBindingModel model) { using var context = new TravelCompanyDataBase(); - var element = context.Orders.FirstOrDefault(rec => rec.Id == - model.Id); - if (element != null) + var order = context.Orders.FirstOrDefault(rec => rec.Id == model.Id); + if (order != null) { - context.Orders.Remove(element); + context.Orders.Remove(order); context.SaveChanges(); - return element.GetViewModel; + return order.GetViewModel; } return null; } diff --git a/TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240418113410_InitialCreate.Designer.cs b/TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240501195930_Initial-Create.Designer.cs similarity index 82% rename from TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240418113410_InitialCreate.Designer.cs rename to TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240501195930_Initial-Create.Designer.cs index be15232..be5ab92 100644 --- a/TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240418113410_InitialCreate.Designer.cs +++ b/TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240501195930_Initial-Create.Designer.cs @@ -12,7 +12,7 @@ using TravelCompanyDatabaseImplement; namespace TravelCompanyDatabaseImplement.Migrations { [DbContext(typeof(TravelCompanyDataBase))] - [Migration("20240418113410_InitialCreate")] + [Migration("20240501195930_Initial-Create")] partial class InitialCreate { /// @@ -70,6 +70,33 @@ namespace TravelCompanyDatabaseImplement.Migrations b.ToTable("Components"); }); + modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.Implementer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ImplementerFIO") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Password") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Qualification") + .HasColumnType("int"); + + b.Property("WorkExperience") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.ToTable("Implementers"); + }); + modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -90,6 +117,9 @@ namespace TravelCompanyDatabaseImplement.Migrations b.Property("DateImplement") .HasColumnType("datetime2"); + b.Property("ImplementerId") + .HasColumnType("int"); + b.Property("Status") .HasColumnType("int"); @@ -103,6 +133,8 @@ namespace TravelCompanyDatabaseImplement.Migrations b.HasIndex("ClientId"); + b.HasIndex("ImplementerId"); + b.HasIndex("TravelId"); b.ToTable("Orders"); @@ -162,6 +194,10 @@ namespace TravelCompanyDatabaseImplement.Migrations .OnDelete(DeleteBehavior.Cascade) .IsRequired(); + b.HasOne("TravelCompanyDatabaseImplement.Models.Implementer", "Implementer") + .WithMany("Order") + .HasForeignKey("ImplementerId"); + b.HasOne("TravelCompanyDatabaseImplement.Models.Travel", "Travel") .WithMany("Orders") .HasForeignKey("TravelId") @@ -170,6 +206,8 @@ namespace TravelCompanyDatabaseImplement.Migrations b.Navigation("Client"); + b.Navigation("Implementer"); + b.Navigation("Travel"); }); @@ -202,6 +240,11 @@ namespace TravelCompanyDatabaseImplement.Migrations b.Navigation("TravelComponents"); }); + modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.Implementer", b => + { + b.Navigation("Order"); + }); + modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.Travel", b => { b.Navigation("Components"); diff --git a/TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240418113410_InitialCreate.cs b/TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240501195930_Initial-Create.cs similarity index 82% rename from TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240418113410_InitialCreate.cs rename to TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240501195930_Initial-Create.cs index b9f0297..dc461ba 100644 --- a/TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240418113410_InitialCreate.cs +++ b/TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240501195930_Initial-Create.cs @@ -40,6 +40,22 @@ namespace TravelCompanyDatabaseImplement.Migrations table.PrimaryKey("PK_Components", x => x.Id); }); + migrationBuilder.CreateTable( + name: "Implementers", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + ImplementerFIO = table.Column(type: "nvarchar(max)", nullable: false), + Password = table.Column(type: "nvarchar(max)", nullable: false), + WorkExperience = table.Column(type: "int", nullable: false), + Qualification = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Implementers", x => x.Id); + }); + migrationBuilder.CreateTable( name: "Travels", columns: table => new @@ -66,6 +82,7 @@ namespace TravelCompanyDatabaseImplement.Migrations DateCreate = table.Column(type: "datetime2", nullable: false), DateImplement = table.Column(type: "datetime2", nullable: true), TravelId = table.Column(type: "int", nullable: false), + ImplementerId = table.Column(type: "int", nullable: true), ClientId = table.Column(type: "int", nullable: false) }, constraints: table => @@ -77,6 +94,11 @@ namespace TravelCompanyDatabaseImplement.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_Travels_TravelId", column: x => x.TravelId, @@ -117,6 +139,11 @@ namespace TravelCompanyDatabaseImplement.Migrations table: "Orders", column: "ClientId"); + migrationBuilder.CreateIndex( + name: "IX_Orders_ImplementerId", + table: "Orders", + column: "ImplementerId"); + migrationBuilder.CreateIndex( name: "IX_Orders_TravelId", table: "Orders", @@ -145,6 +172,9 @@ namespace TravelCompanyDatabaseImplement.Migrations migrationBuilder.DropTable( name: "Clients"); + migrationBuilder.DropTable( + name: "Implementers"); + migrationBuilder.DropTable( name: "Components"); diff --git a/TravelCompany/TravelCompanyDatabaseImplement/Migrations/TravelCompanyDataBaseModelSnapshot.cs b/TravelCompany/TravelCompanyDatabaseImplement/Migrations/TravelCompanyDataBaseModelSnapshot.cs index e5b8916..ff7cd8a 100644 --- a/TravelCompany/TravelCompanyDatabaseImplement/Migrations/TravelCompanyDataBaseModelSnapshot.cs +++ b/TravelCompany/TravelCompanyDatabaseImplement/Migrations/TravelCompanyDataBaseModelSnapshot.cs @@ -67,6 +67,33 @@ namespace TravelCompanyDatabaseImplement.Migrations b.ToTable("Components"); }); + modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.Implementer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ImplementerFIO") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Password") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Qualification") + .HasColumnType("int"); + + b.Property("WorkExperience") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.ToTable("Implementers"); + }); + modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -87,6 +114,9 @@ namespace TravelCompanyDatabaseImplement.Migrations b.Property("DateImplement") .HasColumnType("datetime2"); + b.Property("ImplementerId") + .HasColumnType("int"); + b.Property("Status") .HasColumnType("int"); @@ -100,6 +130,8 @@ namespace TravelCompanyDatabaseImplement.Migrations b.HasIndex("ClientId"); + b.HasIndex("ImplementerId"); + b.HasIndex("TravelId"); b.ToTable("Orders"); @@ -159,6 +191,10 @@ namespace TravelCompanyDatabaseImplement.Migrations .OnDelete(DeleteBehavior.Cascade) .IsRequired(); + b.HasOne("TravelCompanyDatabaseImplement.Models.Implementer", "Implementer") + .WithMany("Order") + .HasForeignKey("ImplementerId"); + b.HasOne("TravelCompanyDatabaseImplement.Models.Travel", "Travel") .WithMany("Orders") .HasForeignKey("TravelId") @@ -167,6 +203,8 @@ namespace TravelCompanyDatabaseImplement.Migrations b.Navigation("Client"); + b.Navigation("Implementer"); + b.Navigation("Travel"); }); @@ -199,6 +237,11 @@ namespace TravelCompanyDatabaseImplement.Migrations b.Navigation("TravelComponents"); }); + modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.Implementer", b => + { + b.Navigation("Order"); + }); + modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.Travel", b => { b.Navigation("Components"); diff --git a/TravelCompany/TravelCompanyDatabaseImplement/Models/Implementer.cs b/TravelCompany/TravelCompanyDatabaseImplement/Models/Implementer.cs new file mode 100644 index 0000000..48fb511 --- /dev/null +++ b/TravelCompany/TravelCompanyDatabaseImplement/Models/Implementer.cs @@ -0,0 +1,65 @@ +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.ViewModels; +using TravelCompanyDataModels.Models; +using System.ComponentModel.DataAnnotations.Schema; +using System.ComponentModel.DataAnnotations; + +namespace TravelCompanyDatabaseImplement.Models +{ + public class Implementer : IImplementerModel + { + public int Id { get; set; } + + [Required] + public string ImplementerFIO { get; set; } = string.Empty; + + [Required] + public string Password { get; set; } = string.Empty; + + [Required] + public int WorkExperience { get; set; } + + [Required] + public int Qualification { get; set; } + + [ForeignKey("ImplementerId")] + public virtual List Order { 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) + { + 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/TravelCompany/TravelCompanyDatabaseImplement/Models/Order.cs b/TravelCompany/TravelCompanyDatabaseImplement/Models/Order.cs index 837eedc..7b7a780 100644 --- a/TravelCompany/TravelCompanyDatabaseImplement/Models/Order.cs +++ b/TravelCompany/TravelCompanyDatabaseImplement/Models/Order.cs @@ -2,8 +2,6 @@ using TravelCompanyContracts.ViewModels; using TravelCompanyDataModels.Enums; using TravelCompanyDataModels.Models; -using System; -using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace TravelCompanyDatabaseImplement.Models @@ -11,43 +9,55 @@ namespace TravelCompanyDatabaseImplement.Models public class Order : IOrderModel { public int Id { get; private set; } - [Required] - public int Count { get; private set; } - [Required] - public double Sum { get; private set; } - [Required] - public OrderStatus Status { get; private set; } - [Required] - public DateTime DateCreate { get; private set; } - public DateTime? DateImplement { get; private set; } - [Required] - public int TravelId { get; private set; } - public virtual Travel Travel { get; private set; } + [Required] public int ClientId { get; private set; } - public virtual Client Client { get; private set; } - public static Order? Create(TravelCompanyDataBase context, OrderBindingModel model) + + public virtual Client Client { get; private set; } = new(); + + [Required] + public int TravelId { get; private set; } + + public virtual Travel Travel { get; set; } = new(); + + public int? ImplementerId { get; private set; } + + public virtual Implementer? Implementer { get; set; } = new(); + + [Required] + public int Count { get; private set; } + + [Required] + public double Sum { get; private set; } + + [Required] + public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен; + + [Required] + public DateTime DateCreate { get; private set; } = DateTime.Now; + + public DateTime? DateImplement { get; private set; } + + public static Order Create(TravelCompanyDataBase context, OrderBindingModel model) { - if (model == null) - { - return null; - } return new Order() { Id = model.Id, + ClientId = model.ClientId, + Client = context.Clients.First(x => x.Id == model.ClientId), + TravelId = model.TravelId, + Travel = context.Travels.First(x => x.Id == model.TravelId), + ImplementerId = model.ImplementerId, + Implementer = model.ImplementerId.HasValue ? context.Implementers.First(x => x.Id == model.ImplementerId) : null, Count = model.Count, Sum = model.Sum, Status = model.Status, DateCreate = model.DateCreate, DateImplement = model.DateImplement, - TravelId = model.TravelId, - Travel = context.Travels.FirstOrDefault(x => x.Id == model.TravelId), - ClientId = model.ClientId, - Client = context.Clients.FirstOrDefault(x => x.Id == model.ClientId), }; } - public void Update(OrderBindingModel? model) + public void Update(TravelCompanyDataBase context, OrderBindingModel? model) { if (model == null) { @@ -55,21 +65,24 @@ namespace TravelCompanyDatabaseImplement.Models } Status = model.Status; DateImplement = model.DateImplement; + ImplementerId = model.ImplementerId; + Implementer = model.ImplementerId.HasValue ? context.Implementers.First(x => x.Id == model.ImplementerId) : null; } public OrderViewModel GetViewModel => new() { - TravelId = TravelId, + Id = Id, ClientId = ClientId, + ClientFIO = Client.ClientFIO, + TravelId = TravelId, + TravelName = Travel.TravelName, + ImplementerId = ImplementerId, + ImplementerFIO = Implementer != null ? Implementer.ImplementerFIO : null, Count = Count, Sum = Sum, Status = Status, DateCreate = DateCreate, DateImplement = DateImplement, - TravelName = Travel.TravelName, - Id = Id, - ClientFIO = Client.ClientFIO }; - } } diff --git a/TravelCompany/TravelCompanyDatabaseImplement/TravelCompanyDataBase.cs b/TravelCompany/TravelCompanyDatabaseImplement/TravelCompanyDataBase.cs index 644f731..eca8a18 100644 --- a/TravelCompany/TravelCompanyDatabaseImplement/TravelCompanyDataBase.cs +++ b/TravelCompany/TravelCompanyDatabaseImplement/TravelCompanyDataBase.cs @@ -16,7 +16,7 @@ optionsBuilder) { if (optionsBuilder.IsConfigured == false) { - optionsBuilder.UseSqlServer(@"Data Source=DESKTOP-D5A5OOG\GOLDFEST;Initial Catalog=TravelCompanyDatabase;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True"); + optionsBuilder.UseSqlServer(@"Data Source=DESKTOP-D5A5OOG\GOLDFEST;Initial Catalog=TravelCompanyDatabase1;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True"); } base.OnConfiguring(optionsBuilder); } @@ -25,6 +25,7 @@ optionsBuilder) public virtual DbSet TravelComponents { set; get; } public virtual DbSet Orders { set; get; } public virtual DbSet Clients { set; get; } + public virtual DbSet Implementers { set; get; } } } diff --git a/TravelCompany/TravelCompanyFileImplement/DataFileSingleton.cs b/TravelCompany/TravelCompanyFileImplement/DataFileSingleton.cs index f7e2376..7c0d1a3 100644 --- a/TravelCompany/TravelCompanyFileImplement/DataFileSingleton.cs +++ b/TravelCompany/TravelCompanyFileImplement/DataFileSingleton.cs @@ -5,6 +5,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; +using TravelCompanyFileImplement.Models; namespace TravelCompanyFileImplement { @@ -15,10 +16,12 @@ namespace TravelCompanyFileImplement private readonly string OrderFileName = "Order.xml"; private readonly string TravelFileName = "Travel.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 Travels { get; private set; } public List Clients { get; private set; } + public List Implementers { get; private set; } public static DataFileSingleton GetInstance() { if (instance == null) @@ -32,6 +35,8 @@ namespace TravelCompanyFileImplement 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)!)!; @@ -39,6 +44,8 @@ namespace TravelCompanyFileImplement 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/TravelCompany/TravelCompanyFileImplement/Implements/ImplementerStorage.cs b/TravelCompany/TravelCompanyFileImplement/Implements/ImplementerStorage.cs new file mode 100644 index 0000000..2f50f08 --- /dev/null +++ b/TravelCompany/TravelCompanyFileImplement/Implements/ImplementerStorage.cs @@ -0,0 +1,94 @@ +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.SearchModels; +using TravelCompanyContracts.StoragesContracts; +using TravelCompanyContracts.ViewModels; +using TravelCompanyFileImplement.Models; + +namespace TravelCompanyFileImplement.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 (model == null) + { + return new(); + } + if (model.Id.HasValue) + { + var res = GetElement(model); + return res != null ? new() { res } : new(); + } + if (model.ImplementerFIO != null) + { + return _source.Implementers + .Where(x => x.ImplementerFIO.Equals(model.ImplementerFIO)) + .Select(x => x.GetViewModel) + .ToList(); + } + return new(); + } + + public ImplementerViewModel? GetElement(ImplementerSearchModel model) + { + if (model.Id.HasValue) + { + return _source.Implementers.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; + } + if (model.ImplementerFIO != null && model.Password != null) + { + return _source.Implementers.FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO) && x.Password.Equals(model.Password))?.GetViewModel; + } + if (model.ImplementerFIO != null) + { + return _source.Implementers.FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO))?.GetViewModel; + } + return null; + } + + public ImplementerViewModel? Insert(ImplementerBindingModel model) + { + model.Id = _source.Implementers.Count > 0 ? _source.Implementers.Max(x => x.Id) + 1 : 1; + var res = Implementer.Create(model); + if (res != null) + { + _source.Implementers.Add(res); + _source.SaveImplementers(); + } + return res?.GetViewModel; + } + + public ImplementerViewModel? Update(ImplementerBindingModel model) + { + var res = _source.Implementers.FirstOrDefault(x => x.Id == model.Id); + if (res != null) + { + res.Update(model); + _source.SaveImplementers(); + } + return res?.GetViewModel; + } + + public ImplementerViewModel? Delete(ImplementerBindingModel model) + { + var res = _source.Implementers.FirstOrDefault(x => x.Id == model.Id); + if (res != null) + { + _source.Implementers.Remove(res); + _source.SaveImplementers(); + } + return res?.GetViewModel; + } + } +} diff --git a/TravelCompany/TravelCompanyFileImplement/Implements/OrderStorage.cs b/TravelCompany/TravelCompanyFileImplement/Implements/OrderStorage.cs index 8ea5ea9..5a64a5f 100644 --- a/TravelCompany/TravelCompanyFileImplement/Implements/OrderStorage.cs +++ b/TravelCompany/TravelCompanyFileImplement/Implements/OrderStorage.cs @@ -36,6 +36,8 @@ model) (!model.DateTo.HasValue || x.DateCreate <= model.DateTo) && (!model.ClientId.HasValue || x.ClientId == model.ClientId) + && + (!model.ImplementerId.HasValue || x.ImplementerId == model.ImplementerId) ) ) .Select(x => AccessTravelStorage(x.GetViewModel)) diff --git a/TravelCompany/TravelCompanyFileImplement/Models/Implementer.cs b/TravelCompany/TravelCompanyFileImplement/Models/Implementer.cs new file mode 100644 index 0000000..7618081 --- /dev/null +++ b/TravelCompany/TravelCompanyFileImplement/Models/Implementer.cs @@ -0,0 +1,87 @@ +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.ViewModels; +using TravelCompanyDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace TravelCompanyFileImplement.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(XElement element) + { + if (element == null) + { + return null; + } + return new() + { + ImplementerFIO = element.Element("FIO")!.Value, + Password = element.Element("Password")!.Value, + Id = Convert.ToInt32(element.Attribute("Id")!.Value), + Qualification = Convert.ToInt32(element.Element("Qualification")!.Value), + WorkExperience = Convert.ToInt32(element.Element("WorkExperience")!.Value), + }; + } + + public static Implementer? Create(ImplementerBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Id = model.Id, + Password = model.Password, + Qualification = model.Qualification, + ImplementerFIO = model.ImplementerFIO, + WorkExperience = model.WorkExperience, + }; + } + + + + public void Update(ImplementerBindingModel model) + { + if (model == null) + { + return; + } + Password = model.Password; + Qualification = model.Qualification; + ImplementerFIO = model.ImplementerFIO; + WorkExperience = model.WorkExperience; + } + + public ImplementerViewModel GetViewModel => new() + { + Id = Id, + Password = Password, + Qualification = Qualification, + ImplementerFIO = ImplementerFIO, + }; + + public XElement GetXElement => new("Client", + new XAttribute("Id", Id), + new XElement("Password", Password), + new XElement("FIO", ImplementerFIO), + new XElement("Qualification", Qualification), + new XElement("WorkExperience", WorkExperience) + ); + } +} diff --git a/TravelCompany/TravelCompanyFileImplement/Models/Order.cs b/TravelCompany/TravelCompanyFileImplement/Models/Order.cs index e5a5ceb..13d0abd 100644 --- a/TravelCompany/TravelCompanyFileImplement/Models/Order.cs +++ b/TravelCompany/TravelCompanyFileImplement/Models/Order.cs @@ -15,6 +15,7 @@ namespace TravelCompanyFileImplement.Models { public int TravelId { get; private set; } public int ClientId { get; private set; } + public int? ImplementerId { get; set; } public int Count { get; private set; } @@ -39,6 +40,7 @@ namespace TravelCompanyFileImplement.Models Id = model.Id, TravelId = model.TravelId, ClientId = model.ClientId, + ImplementerId = model.ImplementerId, Count = model.Count, Sum = model.Sum, Status = model.Status, @@ -58,6 +60,7 @@ namespace TravelCompanyFileImplement.Models Id = Convert.ToInt32(element.Attribute("Id")!.Value), TravelId = Convert.ToInt32(element.Element("TravelId")!.Value), ClientId = Convert.ToInt32(element.Element("ClientId")!.Value), + ImplementerId = Convert.ToInt32(element.Element("ImplementerId")!.Value), Count = Convert.ToInt32(element.Element("Count")!.Value), Sum = Convert.ToDouble(element.Element("Sum")!.Value), Status = (OrderStatus)Enum.Parse(typeof(OrderStatus), element.Element("Status")!.Value.ToString()), @@ -81,6 +84,7 @@ namespace TravelCompanyFileImplement.Models Id = Id, TravelId = TravelId, ClientId = ClientId, + ImplementerId = ImplementerId, Count = Count, Sum = Sum, Status = Status, @@ -91,6 +95,8 @@ namespace TravelCompanyFileImplement.Models public XElement GetXElement => new("Order", new XAttribute("Id", Id), new XElement("TravelId", TravelId), + new XElement("ClientId", ClientId.ToString()), + new XElement("ImplementerId", ImplementerId), new XElement("Count", Count.ToString()), new XElement("Sum", Sum.ToString()), new XElement("Status", Status.ToString()), diff --git a/TravelCompany/TravelCompanyListImplement/DataListSingleton.cs b/TravelCompany/TravelCompanyListImplement/DataListSingleton.cs index 50570c7..055b60f 100644 --- a/TravelCompany/TravelCompanyListImplement/DataListSingleton.cs +++ b/TravelCompany/TravelCompanyListImplement/DataListSingleton.cs @@ -14,12 +14,14 @@ namespace TravelCompanyListImplement public List Orders { get; set; } public List Travels { get; set; } public List Clients { get; set; } + public List Implementers { get; set; } private DataListSingleton() { Components = new List(); Orders = new List(); Travels = new List(); Clients = new List(); + Implementers = new List(); } public static DataListSingleton GetInstance() { diff --git a/TravelCompany/TravelCompanyListImplement/Implements/ImplementerStorage.cs b/TravelCompany/TravelCompanyListImplement/Implements/ImplementerStorage.cs new file mode 100644 index 0000000..974b5e8 --- /dev/null +++ b/TravelCompany/TravelCompanyListImplement/Implements/ImplementerStorage.cs @@ -0,0 +1,118 @@ +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.SearchModels; +using TravelCompanyContracts.StoragesContracts; +using TravelCompanyContracts.ViewModels; +using TravelCompanyListImplement.Models; + +namespace TravelCompanyListImplement.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) + { + foreach (var x in _source.Implementers) + { + if (model.Id.HasValue && x.Id == model.Id) + { + return x.GetViewModel; + } + if (model.ImplementerFIO != null && model.Password != null && x.ImplementerFIO.Equals(model.ImplementerFIO) && x.Password.Equals(model.Password)) + { + return x.GetViewModel; + } + if (model.ImplementerFIO != null && x.ImplementerFIO.Equals(model.ImplementerFIO)) + { + return x.GetViewModel; + } + } + return null; + } + + public List GetFilteredList(ImplementerSearchModel model) + { + if (model == null) + { + return new(); + } + if (model.Id.HasValue) + { + var res = GetElement(model); + return res != null ? new() { res } : new(); + } + + List result = new(); + if (model.ImplementerFIO != null) + { + foreach (var implementer in _source.Implementers) + { + if (implementer.ImplementerFIO.Equals(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 res = Implementer.Create(model); + if (res != null) + { + _source.Implementers.Add(res); + } + return res?.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/TravelCompany/TravelCompanyListImplement/Models/Implementer.cs b/TravelCompany/TravelCompanyListImplement/Models/Implementer.cs new file mode 100644 index 0000000..6e428ab --- /dev/null +++ b/TravelCompany/TravelCompanyListImplement/Models/Implementer.cs @@ -0,0 +1,60 @@ +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.ViewModels; +using TravelCompanyDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TravelCompanyListImplement.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() + { + Id = model.Id, + Password = model.Password, + Qualification = model.Qualification, + ImplementerFIO = model.ImplementerFIO, + WorkExperience = model.WorkExperience, + }; + } + + public void Update(ImplementerBindingModel model) + { + if (model == null) + { + return; + } + Password = model.Password; + Qualification = model.Qualification; + ImplementerFIO = model.ImplementerFIO; + WorkExperience = model.WorkExperience; + } + + public ImplementerViewModel GetViewModel => new() + { + Id = Id, + Password = Password, + Qualification = Qualification, + ImplementerFIO = ImplementerFIO, + }; + } +} diff --git a/TravelCompany/TravelCompanyListImplement/Models/Order.cs b/TravelCompany/TravelCompanyListImplement/Models/Order.cs index f97a641..868e696 100644 --- a/TravelCompany/TravelCompanyListImplement/Models/Order.cs +++ b/TravelCompany/TravelCompanyListImplement/Models/Order.cs @@ -16,6 +16,7 @@ namespace TravelCompanyListImplement.Models public int Id { get; private set; } public int TravelId { get; private set; } public int ClientId { 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; } @@ -32,6 +33,7 @@ namespace TravelCompanyListImplement.Models Id = model.Id, TravelId = model.TravelId, ClientId = model.ClientId, + ImplementerId = model.ImplementerId, Count = model.Count, Sum = model.Sum, Status = model.Status, @@ -47,6 +49,7 @@ namespace TravelCompanyListImplement.Models } TravelId = model.TravelId; ClientId = model.ClientId; + ImplementerId = ImplementerId; Count = model.Count; Sum = model.Sum; Status = model.Status; @@ -58,6 +61,7 @@ namespace TravelCompanyListImplement.Models Id = Id, TravelId = TravelId, ClientId = ClientId, + ImplementerId = ImplementerId, Count = Count, Sum = Sum, Status = Status, diff --git a/TravelCompany/TravelCompanyRestApi/Controllers/ImplementerController.cs b/TravelCompany/TravelCompanyRestApi/Controllers/ImplementerController.cs new file mode 100644 index 0000000..c7732b7 --- /dev/null +++ b/TravelCompany/TravelCompanyRestApi/Controllers/ImplementerController.cs @@ -0,0 +1,107 @@ +using Microsoft.AspNetCore.Mvc; +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.BusinessLogicsContracts; +using TravelCompanyContracts.SearchModels; +using TravelCompanyContracts.ViewModels; +using TravelCompanyDataModels.Enums; + +namespace TravelCompanyRestApi.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; + } + } + } +} diff --git a/TravelCompany/TravelCompanyRestApi/Program.cs b/TravelCompany/TravelCompanyRestApi/Program.cs index 656951d..257c2e8 100644 --- a/TravelCompany/TravelCompanyRestApi/Program.cs +++ b/TravelCompany/TravelCompanyRestApi/Program.cs @@ -8,11 +8,14 @@ builder.Logging.SetMinimumLevel(LogLevel.Trace); builder.Logging.AddLog4Net("log4net.config"); // Add services to the container. 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 -- 2.25.1 From 4e5399d0e584939717277cf35f38515cb3068dba Mon Sep 17 00:00:00 2001 From: goldfest Date: Thu, 2 May 2024 13:46:28 +0400 Subject: [PATCH 2/4] =?UTF-8?q?Revert=20"=D0=BA=D0=BE=D0=BC=D0=BC=D0=B8?= =?UTF-8?q?=D1=82"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit 2cbfa9799d4ab83be144d90fd1c1483405920b0a. --- .../TravelCompany/FormImplementer.Designer.cs | 167 ------------------ .../TravelCompany/FormImplementer.cs | 94 ---------- .../TravelCompany/FormImplementer.resx | 120 ------------- .../FormImplementers.Designer.cs | 130 -------------- .../TravelCompany/FormImplementers.cs | 118 ------------- .../TravelCompany/FormImplementers.resx | 120 ------------- .../TravelCompany/FormMain.Designer.cs | 34 +--- TravelCompany/TravelCompany/FormMain.cs | 24 +-- TravelCompany/TravelCompany/Program.cs | 9 +- .../BusinessLogic/ImplementerLogic.cs | 128 -------------- .../BusinessLogic/OrderLogic.cs | 139 +++++++-------- .../BusinessLogic/WorkModeling.cs | 134 -------------- .../BindingModels/ImplementerBindingModel.cs | 18 -- .../BindingModels/OrderBindingModel.cs | 1 - .../IImplementerLogic.cs | 15 -- .../BusinessLogicsContracts/IOrderLogic.cs | 1 - .../BusinessLogicsContracts/IWorkProcess.cs | 7 - .../SearchModels/ImplementerSearchModel.cs | 9 - .../SearchModels/OrderSearchModel.cs | 3 - .../StoragesContracts/IImplementerStorage.cs | 16 -- .../ViewModels/ImplementerViewModel.cs | 27 --- .../ViewModels/OrderViewModel.cs | 4 - .../Models/IImplementerModel.cs | 13 -- .../Models/IOrderModel.cs | 1 - .../Implements/ImplementerStorage.cs | 79 --------- .../Implements/OrderStorage.cs | 64 +++---- ... 20240418113410_InitialCreate.Designer.cs} | 45 +---- ...ate.cs => 20240418113410_InitialCreate.cs} | 30 ---- .../TravelCompanyDataBaseModelSnapshot.cs | 43 ----- .../Models/Implementer.cs | 65 ------- .../Models/Order.cs | 63 +++---- .../TravelCompanyDataBase.cs | 3 +- .../DataFileSingleton.cs | 7 - .../Implements/ImplementerStorage.cs | 94 ---------- .../Implements/OrderStorage.cs | 2 - .../Models/Implementer.cs | 87 --------- .../Models/Order.cs | 6 - .../DataListSingleton.cs | 2 - .../Implements/ImplementerStorage.cs | 118 ------------- .../Models/Implementer.cs | 60 ------- .../Models/Order.cs | 4 - .../Controllers/ImplementerController.cs | 107 ----------- TravelCompany/TravelCompanyRestApi/Program.cs | 3 - 43 files changed, 135 insertions(+), 2079 deletions(-) delete mode 100644 TravelCompany/TravelCompany/FormImplementer.Designer.cs delete mode 100644 TravelCompany/TravelCompany/FormImplementer.cs delete mode 100644 TravelCompany/TravelCompany/FormImplementer.resx delete mode 100644 TravelCompany/TravelCompany/FormImplementers.Designer.cs delete mode 100644 TravelCompany/TravelCompany/FormImplementers.cs delete mode 100644 TravelCompany/TravelCompany/FormImplementers.resx delete mode 100644 TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/ImplementerLogic.cs delete mode 100644 TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/WorkModeling.cs delete mode 100644 TravelCompany/TravelCompanyContracts/BindingModels/ImplementerBindingModel.cs delete mode 100644 TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IImplementerLogic.cs delete mode 100644 TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IWorkProcess.cs delete mode 100644 TravelCompany/TravelCompanyContracts/SearchModels/ImplementerSearchModel.cs delete mode 100644 TravelCompany/TravelCompanyContracts/StoragesContracts/IImplementerStorage.cs delete mode 100644 TravelCompany/TravelCompanyContracts/ViewModels/ImplementerViewModel.cs delete mode 100644 TravelCompany/TravelCompanyDataModels/Models/IImplementerModel.cs delete mode 100644 TravelCompany/TravelCompanyDatabaseImplement/Implements/ImplementerStorage.cs rename TravelCompany/TravelCompanyDatabaseImplement/Migrations/{20240501195930_Initial-Create.Designer.cs => 20240418113410_InitialCreate.Designer.cs} (82%) rename TravelCompany/TravelCompanyDatabaseImplement/Migrations/{20240501195930_Initial-Create.cs => 20240418113410_InitialCreate.cs} (82%) delete mode 100644 TravelCompany/TravelCompanyDatabaseImplement/Models/Implementer.cs delete mode 100644 TravelCompany/TravelCompanyFileImplement/Implements/ImplementerStorage.cs delete mode 100644 TravelCompany/TravelCompanyFileImplement/Models/Implementer.cs delete mode 100644 TravelCompany/TravelCompanyListImplement/Implements/ImplementerStorage.cs delete mode 100644 TravelCompany/TravelCompanyListImplement/Models/Implementer.cs delete mode 100644 TravelCompany/TravelCompanyRestApi/Controllers/ImplementerController.cs diff --git a/TravelCompany/TravelCompany/FormImplementer.Designer.cs b/TravelCompany/TravelCompany/FormImplementer.Designer.cs deleted file mode 100644 index 9a96ca8..0000000 --- a/TravelCompany/TravelCompany/FormImplementer.Designer.cs +++ /dev/null @@ -1,167 +0,0 @@ -namespace TravelCompany.Forms -{ - 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() - { - this.textBoxFIO = new System.Windows.Forms.TextBox(); - this.labelFIO = new System.Windows.Forms.Label(); - this.textBoxPassword = new System.Windows.Forms.TextBox(); - this.labelPassword = new System.Windows.Forms.Label(); - this.labelWorkExperience = new System.Windows.Forms.Label(); - this.numericUpDownWorkExperience = new System.Windows.Forms.NumericUpDown(); - this.numericUpDownQualification = new System.Windows.Forms.NumericUpDown(); - this.labelQualification = new System.Windows.Forms.Label(); - this.buttonCancel = new System.Windows.Forms.Button(); - this.buttonSave = new System.Windows.Forms.Button(); - ((System.ComponentModel.ISupportInitialize)(this.numericUpDownWorkExperience)).BeginInit(); - ((System.ComponentModel.ISupportInitialize)(this.numericUpDownQualification)).BeginInit(); - this.SuspendLayout(); - // - // textBoxFIO - // - this.textBoxFIO.Location = new System.Drawing.Point(157, 12); - this.textBoxFIO.Name = "textBoxFIO"; - this.textBoxFIO.Size = new System.Drawing.Size(382, 27); - this.textBoxFIO.TabIndex = 3; - // - // labelFIO - // - this.labelFIO.AutoSize = true; - this.labelFIO.Location = new System.Drawing.Point(12, 15); - this.labelFIO.Name = "labelFIO"; - this.labelFIO.Size = new System.Drawing.Size(139, 20); - this.labelFIO.TabIndex = 2; - this.labelFIO.Text = "ФИО исполнителя:"; - // - // textBoxPassword - // - this.textBoxPassword.Location = new System.Drawing.Point(157, 50); - this.textBoxPassword.Name = "textBoxPassword"; - this.textBoxPassword.Size = new System.Drawing.Size(205, 27); - this.textBoxPassword.TabIndex = 5; - // - // labelPassword - // - this.labelPassword.AutoSize = true; - this.labelPassword.Location = new System.Drawing.Point(12, 53); - this.labelPassword.Name = "labelPassword"; - this.labelPassword.Size = new System.Drawing.Size(65, 20); - this.labelPassword.TabIndex = 4; - this.labelPassword.Text = "Пароль:"; - // - // labelWorkExperience - // - this.labelWorkExperience.AutoSize = true; - this.labelWorkExperience.Location = new System.Drawing.Point(12, 99); - this.labelWorkExperience.Name = "labelWorkExperience"; - this.labelWorkExperience.Size = new System.Drawing.Size(105, 20); - this.labelWorkExperience.TabIndex = 6; - this.labelWorkExperience.Text = "Опыт работы:"; - // - // numericUpDownWorkExperience - // - this.numericUpDownWorkExperience.Location = new System.Drawing.Point(157, 97); - this.numericUpDownWorkExperience.Name = "numericUpDownWorkExperience"; - this.numericUpDownWorkExperience.Size = new System.Drawing.Size(124, 27); - this.numericUpDownWorkExperience.TabIndex = 8; - // - // numericUpDownQualification - // - this.numericUpDownQualification.Location = new System.Drawing.Point(157, 142); - this.numericUpDownQualification.Name = "numericUpDownQualification"; - this.numericUpDownQualification.Size = new System.Drawing.Size(124, 27); - this.numericUpDownQualification.TabIndex = 10; - // - // labelQualification - // - this.labelQualification.AutoSize = true; - this.labelQualification.Location = new System.Drawing.Point(12, 144); - this.labelQualification.Name = "labelQualification"; - this.labelQualification.Size = new System.Drawing.Size(114, 20); - this.labelQualification.TabIndex = 9; - this.labelQualification.Text = "Квалификация:"; - // - // buttonCancel - // - this.buttonCancel.Location = new System.Drawing.Point(422, 203); - this.buttonCancel.Name = "buttonCancel"; - this.buttonCancel.Size = new System.Drawing.Size(136, 40); - this.buttonCancel.TabIndex = 12; - this.buttonCancel.Text = "Отмена"; - this.buttonCancel.UseVisualStyleBackColor = true; - this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click); - // - // buttonSave - // - this.buttonSave.Location = new System.Drawing.Point(265, 203); - this.buttonSave.Name = "buttonSave"; - this.buttonSave.Size = new System.Drawing.Size(130, 40); - this.buttonSave.TabIndex = 11; - this.buttonSave.Text = "Сохранить"; - this.buttonSave.UseVisualStyleBackColor = true; - this.buttonSave.Click += new System.EventHandler(this.buttonSave_Click); - // - // FormImplementer - // - this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(570, 255); - this.Controls.Add(this.buttonCancel); - this.Controls.Add(this.buttonSave); - this.Controls.Add(this.numericUpDownQualification); - this.Controls.Add(this.labelQualification); - this.Controls.Add(this.numericUpDownWorkExperience); - this.Controls.Add(this.labelWorkExperience); - this.Controls.Add(this.textBoxPassword); - this.Controls.Add(this.labelPassword); - this.Controls.Add(this.textBoxFIO); - this.Controls.Add(this.labelFIO); - this.Name = "FormImplementer"; - this.Text = "Исполнитель"; - this.Load += new System.EventHandler(this.FormImplementer_Load); - ((System.ComponentModel.ISupportInitialize)(this.numericUpDownWorkExperience)).EndInit(); - ((System.ComponentModel.ISupportInitialize)(this.numericUpDownQualification)).EndInit(); - this.ResumeLayout(false); - this.PerformLayout(); - - } - - #endregion - - private TextBox textBoxFIO; - private Label labelFIO; - private TextBox textBoxPassword; - private Label labelPassword; - private Label labelWorkExperience; - private NumericUpDown numericUpDownWorkExperience; - private NumericUpDown numericUpDownQualification; - private Label labelQualification; - private Button buttonCancel; - private Button buttonSave; - } -} \ No newline at end of file diff --git a/TravelCompany/TravelCompany/FormImplementer.cs b/TravelCompany/TravelCompany/FormImplementer.cs deleted file mode 100644 index b93a786..0000000 --- a/TravelCompany/TravelCompany/FormImplementer.cs +++ /dev/null @@ -1,94 +0,0 @@ -using Microsoft.Extensions.Logging; -using TravelCompanyContracts.BindingModels; -using TravelCompanyContracts.BusinessLogicsContracts; -using TravelCompanyContracts.SearchModels; - -namespace TravelCompany.Forms -{ - 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 FormImplementer_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; - numericUpDownWorkExperience.Value = view.WorkExperience; - numericUpDownQualification.Value = view.Qualification; - } - } - 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; - } - _logger.LogInformation("Сохранение исполнителя"); - try - { - var model = new ImplementerBindingModel - { - Id = _id ?? 0, - ImplementerFIO = textBoxFIO.Text, - Password = textBoxPassword.Text, - WorkExperience = (int)numericUpDownWorkExperience.Value, - Qualification = (int)numericUpDownQualification.Value - }; - 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/TravelCompany/TravelCompany/FormImplementer.resx b/TravelCompany/TravelCompany/FormImplementer.resx deleted file mode 100644 index 1af7de1..0000000 --- a/TravelCompany/TravelCompany/FormImplementer.resx +++ /dev/null @@ -1,120 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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/TravelCompany/TravelCompany/FormImplementers.Designer.cs b/TravelCompany/TravelCompany/FormImplementers.Designer.cs deleted file mode 100644 index fcef1c5..0000000 --- a/TravelCompany/TravelCompany/FormImplementers.Designer.cs +++ /dev/null @@ -1,130 +0,0 @@ -namespace TravelCompany.Forms -{ - 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.ToolsPanel = new System.Windows.Forms.Panel(); - this.buttonRef = new System.Windows.Forms.Button(); - this.buttonDel = new System.Windows.Forms.Button(); - this.buttonUpd = new System.Windows.Forms.Button(); - this.buttonAdd = new System.Windows.Forms.Button(); - this.dataGridView = new System.Windows.Forms.DataGridView(); - this.ToolsPanel.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); - this.SuspendLayout(); - // - // ToolsPanel - // - this.ToolsPanel.Controls.Add(this.buttonRef); - this.ToolsPanel.Controls.Add(this.buttonDel); - this.ToolsPanel.Controls.Add(this.buttonUpd); - this.ToolsPanel.Controls.Add(this.buttonAdd); - this.ToolsPanel.Location = new System.Drawing.Point(608, 12); - this.ToolsPanel.Name = "ToolsPanel"; - this.ToolsPanel.Size = new System.Drawing.Size(180, 426); - this.ToolsPanel.TabIndex = 3; - // - // buttonRef - // - this.buttonRef.Location = new System.Drawing.Point(31, 206); - this.buttonRef.Name = "buttonRef"; - this.buttonRef.Size = new System.Drawing.Size(126, 36); - this.buttonRef.TabIndex = 3; - this.buttonRef.Text = "Обновить"; - this.buttonRef.UseVisualStyleBackColor = true; - this.buttonRef.Click += new System.EventHandler(this.buttonRef_Click); - // - // buttonDel - // - this.buttonDel.Location = new System.Drawing.Point(31, 142); - this.buttonDel.Name = "buttonDel"; - this.buttonDel.Size = new System.Drawing.Size(126, 36); - this.buttonDel.TabIndex = 2; - this.buttonDel.Text = "Удалить"; - this.buttonDel.UseVisualStyleBackColor = true; - this.buttonDel.Click += new System.EventHandler(this.buttonDel_Click); - // - // buttonUpd - // - this.buttonUpd.Location = new System.Drawing.Point(31, 76); - this.buttonUpd.Name = "buttonUpd"; - this.buttonUpd.Size = new System.Drawing.Size(126, 36); - this.buttonUpd.TabIndex = 1; - this.buttonUpd.Text = "Изменить"; - this.buttonUpd.UseVisualStyleBackColor = true; - this.buttonUpd.Click += new System.EventHandler(this.buttonUpd_Click); - // - // buttonAdd - // - this.buttonAdd.Location = new System.Drawing.Point(31, 16); - this.buttonAdd.Name = "buttonAdd"; - this.buttonAdd.Size = new System.Drawing.Size(126, 36); - this.buttonAdd.TabIndex = 0; - this.buttonAdd.Text = "Добавить"; - this.buttonAdd.UseVisualStyleBackColor = true; - this.buttonAdd.Click += new System.EventHandler(this.buttonAdd_Click); - // - // dataGridView - // - this.dataGridView.AllowUserToAddRows = false; - this.dataGridView.AllowUserToDeleteRows = false; - this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; - this.dataGridView.Location = new System.Drawing.Point(12, 12); - this.dataGridView.Name = "dataGridView"; - this.dataGridView.ReadOnly = true; - this.dataGridView.RowHeadersWidth = 51; - this.dataGridView.RowTemplate.Height = 29; - this.dataGridView.Size = new System.Drawing.Size(590, 426); - this.dataGridView.TabIndex = 2; - // - // FormImplementers - // - this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(800, 450); - this.Controls.Add(this.ToolsPanel); - this.Controls.Add(this.dataGridView); - this.Name = "FormImplementers"; - this.Text = "Исполнители"; - this.Load += new System.EventHandler(this.FormImplementers_Load); - this.ToolsPanel.ResumeLayout(false); - ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit(); - this.ResumeLayout(false); - - } - - #endregion - - private Panel ToolsPanel; - private Button buttonRef; - private Button buttonDel; - private Button buttonUpd; - private Button buttonAdd; - private DataGridView dataGridView; - } -} \ No newline at end of file diff --git a/TravelCompany/TravelCompany/FormImplementers.cs b/TravelCompany/TravelCompany/FormImplementers.cs deleted file mode 100644 index 35ebb2d..0000000 --- a/TravelCompany/TravelCompany/FormImplementers.cs +++ /dev/null @@ -1,118 +0,0 @@ -using Microsoft.Extensions.Logging; -using TravelCompany; -using TravelCompanyContracts.BindingModels; -using TravelCompanyContracts.BusinessLogicsContracts; -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 TravelCompany.Forms -{ - public partial class FormImplementers : Form - { - private readonly ILogger _logger; - private readonly IImplementerLogic _logic; - - public FormImplementers(ILogger logger, IImplementerLogic implementerLogic) - { - InitializeComponent(); - _logger = logger; - _logic = implementerLogic; - } - - 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 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/TravelCompany/TravelCompany/FormImplementers.resx b/TravelCompany/TravelCompany/FormImplementers.resx deleted file mode 100644 index 1af7de1..0000000 --- a/TravelCompany/TravelCompany/FormImplementers.resx +++ /dev/null @@ -1,120 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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/TravelCompany/TravelCompany/FormMain.Designer.cs b/TravelCompany/TravelCompany/FormMain.Designer.cs index 41add46..e3b2b36 100644 --- a/TravelCompany/TravelCompany/FormMain.Designer.cs +++ b/TravelCompany/TravelCompany/FormMain.Designer.cs @@ -33,19 +33,17 @@ toolStripDropDownButton1 = new ToolStripDropDownButton(); компонентыToolStripMenuItem = new ToolStripMenuItem(); ПутёвкиToolStripMenuItem = new ToolStripMenuItem(); - клиентыToolStripMenuItem = new ToolStripMenuItem(); отчетыToolStripMenuItem = new ToolStripMenuItem(); списокКомпонентовToolStripMenuItem = new ToolStripMenuItem(); компонентыПоПутёвкамToolStripMenuItem = new ToolStripMenuItem(); списокЗаказовToolStripMenuItem = new ToolStripMenuItem(); - запускРаботToolStripMenuItem = new ToolStripMenuItem(); buttonCreateOrder = new Button(); buttonTakeOrderInWork = new Button(); buttonOrderReady = new Button(); buttonIssuedOrder = new Button(); buttonRef = new Button(); dataGridView = new DataGridView(); - исполнителиToolStripMenuItem = new ToolStripMenuItem(); + клиентыToolStripMenuItem = new ToolStripMenuItem(); toolStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); SuspendLayout(); @@ -53,7 +51,7 @@ // toolStrip1 // toolStrip1.ImageScalingSize = new Size(20, 20); - toolStrip1.Items.AddRange(new ToolStripItem[] { toolStripDropDownButton1, отчетыToolStripMenuItem, запускРаботToolStripMenuItem }); + toolStrip1.Items.AddRange(new ToolStripItem[] { toolStripDropDownButton1, отчетыToolStripMenuItem }); toolStrip1.Location = new Point(0, 0); toolStrip1.Name = "toolStrip1"; toolStrip1.Size = new Size(969, 25); @@ -63,7 +61,7 @@ // toolStripDropDownButton1 // toolStripDropDownButton1.DisplayStyle = ToolStripItemDisplayStyle.Text; - toolStripDropDownButton1.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, ПутёвкиToolStripMenuItem, клиентыToolStripMenuItem, исполнителиToolStripMenuItem }); + toolStripDropDownButton1.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, ПутёвкиToolStripMenuItem, клиентыToolStripMenuItem }); toolStripDropDownButton1.Image = (Image)resources.GetObject("toolStripDropDownButton1.Image"); toolStripDropDownButton1.ImageTransparentColor = Color.Magenta; toolStripDropDownButton1.Name = "toolStripDropDownButton1"; @@ -84,13 +82,6 @@ ПутёвкиToolStripMenuItem.Text = "Туристич. путёвки"; ПутёвкиToolStripMenuItem.Click += консервыToolStripMenuItem_Click; // - // клиентыToolStripMenuItem - // - клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; - клиентыToolStripMenuItem.Size = new Size(180, 22); - клиентыToolStripMenuItem.Text = "Клиенты"; - клиентыToolStripMenuItem.Click += клиентыToolStripMenuItem_Click; - // // отчетыToolStripMenuItem // отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокКомпонентовToolStripMenuItem, компонентыПоПутёвкамToolStripMenuItem, списокЗаказовToolStripMenuItem }); @@ -119,13 +110,6 @@ списокЗаказовToolStripMenuItem.Text = "Список заказов"; списокЗаказовToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click; // - // запускРаботToolStripMenuItem - // - запускРаботToolStripMenuItem.Name = "запускРаботToolStripMenuItem"; - запускРаботToolStripMenuItem.Size = new Size(92, 25); - запускРаботToolStripMenuItem.Text = "Запуск работ"; - запускРаботToolStripMenuItem.Click += startWorkToolStripMenuItem_Click; - // // buttonCreateOrder // buttonCreateOrder.Location = new Point(800, 56); @@ -188,12 +172,12 @@ dataGridView.Size = new Size(763, 435); dataGridView.TabIndex = 6; // - // исполнителиToolStripMenuItem + // клиентыToolStripMenuItem // - исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; - исполнителиToolStripMenuItem.Size = new Size(180, 22); - исполнителиToolStripMenuItem.Text = "Исполнители"; - исполнителиToolStripMenuItem.Click += employersToolStripMenuItem_Click; + клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; + клиентыToolStripMenuItem.Size = new Size(180, 22); + клиентыToolStripMenuItem.Text = "Клиенты"; + клиентыToolStripMenuItem.Click += клиентыToolStripMenuItem_Click; // // FormMain // @@ -234,7 +218,5 @@ private ToolStripMenuItem компонентыПоПутёвкамToolStripMenuItem; private ToolStripMenuItem списокЗаказовToolStripMenuItem; private ToolStripMenuItem клиентыToolStripMenuItem; - private ToolStripMenuItem запускРаботToolStripMenuItem; - private ToolStripMenuItem исполнителиToolStripMenuItem; } } \ No newline at end of file diff --git a/TravelCompany/TravelCompany/FormMain.cs b/TravelCompany/TravelCompany/FormMain.cs index e3f5f41..dbe9ade 100644 --- a/TravelCompany/TravelCompany/FormMain.cs +++ b/TravelCompany/TravelCompany/FormMain.cs @@ -19,14 +19,12 @@ namespace TravelCompany.Forms 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) + public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic) { InitializeComponent(); _logger = logger; _orderLogic = orderLogic; _reportLogic = reportLogic; - _workProcess = workProcess; } private void FormMain_Load(object sender, EventArgs e) { @@ -43,10 +41,7 @@ namespace TravelCompany.Forms { dataGridView.DataSource = list; dataGridView.Columns["TravelId"].Visible = false; - dataGridView.Columns["ClientId"].Visible = false; - dataGridView.Columns["ImplementerId"].Visible = false; - dataGridView.Columns["TravelName"].AutoSizeMode = - DataGridViewAutoSizeColumnMode.Fill; + dataGridView.Columns["TravelName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; } _logger.LogInformation("Загрузка заказов"); @@ -203,20 +198,5 @@ Program.ServiceProvider?.GetService(typeof(FormClients)); form.ShowDialog(); } } - private void employersToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormImplementers)); - if (service is FormImplementers form) - { - form.ShowDialog(); - } - } - - private void startWorkToolStripMenuItem_Click(object sender, EventArgs e) - { - _workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic); - MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); - } - } } diff --git a/TravelCompany/TravelCompany/Program.cs b/TravelCompany/TravelCompany/Program.cs index c8948df..d57b9c3 100644 --- a/TravelCompany/TravelCompany/Program.cs +++ b/TravelCompany/TravelCompany/Program.cs @@ -7,7 +7,6 @@ using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; using TravelCompanyBusinessLogic.OfficePackage.Implements; using TravelCompanyBusinessLogic.OfficePackage; -using Microsoft.EntityFrameworkCore.Design; namespace TravelCompany.Forms @@ -41,16 +40,13 @@ namespace TravelCompany.Forms 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(); @@ -65,9 +61,6 @@ namespace TravelCompany.Forms services.AddTransient(); services.AddTransient(); services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); } } diff --git a/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/ImplementerLogic.cs b/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/ImplementerLogic.cs deleted file mode 100644 index 222035b..0000000 --- a/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/ImplementerLogic.cs +++ /dev/null @@ -1,128 +0,0 @@ -using Microsoft.Extensions.Logging; -using TravelCompanyContracts.BindingModels; -using TravelCompanyContracts.BusinessLogicsContracts; -using TravelCompanyContracts.SearchModels; -using TravelCompanyContracts.StoragesContracts; -using TravelCompanyContracts.ViewModels; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace TravelCompanyBusinessLogic.BusinessLogic -{ - public class ImplementerLogic : IImplementerLogic - { - private readonly ILogger _logger; - private readonly IImplementerStorage _implementerStorage; - - public ImplementerLogic(ILogger logger, IImplementerStorage implementerStorage) - { - _logger = logger; - _implementerStorage = implementerStorage; - } - - public List? ReadList(ImplementerSearchModel? model) - { - _logger.LogInformation("ReadList. ImplementerFIO:{ImplementerFIO}.Password:{Password}.Id:{ Id}", model?.ImplementerFIO, model?.Password?.Length, 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 ImplementerViewModel? ReadElement(ImplementerSearchModel model) - { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - _logger.LogInformation("ReadElement. ImplementerFIO:{ImplementerFIO}.Password:{Password}.Id:{ Id}", model?.ImplementerFIO, model?.Password?.Length, 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 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 (string.IsNullOrEmpty(model.Password)) - { - throw new ArgumentNullException("Нет пароля исполнителя", nameof(model.Password)); - } - if (model.WorkExperience < 0) - { - throw new ArgumentNullException("Стаж должен быть больше 0", nameof(model.WorkExperience)); - } - if (model.Qualification < 0) - { - throw new ArgumentNullException("Квалификация должна быть положительной", nameof(model.Qualification)); - } - _logger.LogInformation("Implementer. ImplementerFIO:{ImplementerFIO}.Password:{Password}.WorkExperience:{WorkExperience}.Qualification:{Qualification}.Id: { Id}", - model.ImplementerFIO, model.Password, model.WorkExperience, model.Qualification, model.Id); - var element = _implementerStorage.GetElement(new ImplementerSearchModel - { - ImplementerFIO = model.ImplementerFIO - }); - if (element != null && element.Id != model.Id) - { - throw new InvalidOperationException("Исполнитель с таким ФИО уже есть"); - } - } - } -} diff --git a/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/OrderLogic.cs b/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/OrderLogic.cs index b24ebbf..e7c1295 100644 --- a/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/OrderLogic.cs +++ b/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/OrderLogic.cs @@ -1,46 +1,36 @@ -using TravelCompanyDataModels.Enums; -using Microsoft.Extensions.Logging; -using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.BindingModels; using TravelCompanyContracts.BusinessLogicsContracts; using TravelCompanyContracts.SearchModels; using TravelCompanyContracts.StoragesContracts; using TravelCompanyContracts.ViewModels; +using TravelCompanyDataModels.Enums; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; namespace TravelCompanyBusinessLogic.BusinessLogic { public class OrderLogic : IOrderLogic { + //Класс с логикой для заказов будет отвечать за получение списка заказов, + //создания заказа и смены его статусов. Следует учитывать, что у заказа можно + //менять статус на новый, если его текущий статус предшествует новому + private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; - static readonly object _locker = new object(); + public OrderLogic(ILogger logger, IOrderStorage orderStorage) { _logger = logger; _orderStorage = orderStorage; } - public OrderViewModel? ReadElement(OrderSearchModel model) - { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - _logger.LogInformation("ReadElement. ClientId:{ClientId}.Status:{Status}.ImplementerId:{ImplementerId}.DateFrom:{DateFrom}.DateTo:{DateTo}OrderId:{Id}", - model.ClientId, model.Status, model.ImplementerId, 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 List? ReadList(OrderSearchModel? model) { - _logger.LogInformation("ReadList. ClientId:{ClientId}.Status:{Status}.ImplementerId:{ImplementerId}.DateFrom:{DateFrom}.DateTo:{DateTo}OrderId:{Id}", - model?.ClientId, model?.Status, model?.ImplementerId, model?.DateFrom, model?.DateTo, model?.Id); + _logger.LogInformation("ReadList. OrderId:{Id}", model?.Id); var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model); if (list == null) { @@ -54,11 +44,14 @@ namespace TravelCompanyBusinessLogic.BusinessLogic public bool CreateOrder(OrderBindingModel model) { CheckModel(model); + if (model.Status != OrderStatus.Неизвестен) return false; model.Status = OrderStatus.Принят; + if (_orderStorage.Insert(model) == null) { + model.Status = OrderStatus.Неизвестен; _logger.LogWarning("Insert operation failed"); return false; } @@ -67,20 +60,57 @@ namespace TravelCompanyBusinessLogic.BusinessLogic public bool TakeOrderInWork(OrderBindingModel model) { - lock (_locker) - { - return ChangeStatus(model, OrderStatus.Выполняется); - } + return ToNextStatus(model, OrderStatus.Выполняется); } public bool FinishOrder(OrderBindingModel model) { - return ChangeStatus(model, OrderStatus.Готов); + return ToNextStatus(model, OrderStatus.Готов); } public bool DeliveryOrder(OrderBindingModel model) { - return ChangeStatus(model, OrderStatus.Выдан); + return ToNextStatus(model, OrderStatus.Выдан); + } + + public bool ToNextStatus(OrderBindingModel model, OrderStatus orderStatus) + { + CheckModel(model, false); + var element = _orderStorage.GetElement(new OrderSearchModel() + { + Id = model.Id + }); + if (element == null) + { + throw new ArgumentNullException(nameof(element)); + } + + model.TravelId = element.TravelId; + model.DateCreate = element.DateCreate; + model.DateImplement = element.DateImplement; + model.Status = element.Status; + model.Count = element.Count; + model.Sum = element.Sum; + + if (model.Status != orderStatus - 1) + { + _logger.LogWarning("Status update to " + orderStatus + " operation failed"); + return false; + } + model.Status = orderStatus; + + if (model.Status == OrderStatus.Выдан) + { + model.DateImplement = DateTime.Now; + } + + if (_orderStorage.Update(model) == null) + { + model.Status--; + _logger.LogWarning("Changing status operation faled"); + return false; + } + return true; } private void CheckModel(OrderBindingModel model, bool withParams = true) @@ -95,58 +125,17 @@ namespace TravelCompanyBusinessLogic.BusinessLogic } if (model.Count <= 0) { - throw new ArgumentException("Колличество пиццы в заказе не может быть меньше 1", nameof(model.Count)); + throw new ArgumentNullException("Количество изделий должно быть больше 0", nameof(model.Count)); } if (model.Sum <= 0) { - throw new ArgumentException("Стоимость заказа на может быть меньше 1", nameof(model.Sum)); + throw new ArgumentNullException("Цена заказа должна быть больше 0", nameof(model.Sum)); } if (model.DateImplement.HasValue && model.DateImplement < model.DateCreate) { - throw new ArithmeticException($"Дата выдачи заказа {model.DateImplement} не может быть раньше даты его создания {model.DateCreate}"); + throw new ArithmeticException($"Дата выдачи заказа {model.DateImplement} должна быть позже даты его создания {model.DateCreate}"); } - _logger.LogInformation("Travel. TravelId:{TravelId}.Count:{Count}.Sum:{Sum}Id:{Id}", - model.TravelId, model.Count, model.Sum, model.Id); - } - - private bool ChangeStatus(OrderBindingModel model, OrderStatus requiredStatus) - { - CheckModel(model, false); - var element = _orderStorage.GetElement(new OrderSearchModel() - { - Id = model.Id - }); - if (element == null) - { - throw new InvalidOperationException(nameof(element)); - } - model.DateCreate = element.DateCreate; - model.TravelId = element.TravelId; - model.DateImplement = element.DateImplement; - model.ClientId = element.ClientId; - if (!model.ImplementerId.HasValue) - { - model.ImplementerId = element.ImplementerId; - } - model.Status = element.Status; - model.Count = element.Count; - model.Sum = element.Sum; - if (requiredStatus - model.Status == 1) - { - model.Status = requiredStatus; - if (model.Status == OrderStatus.Готов) - { - model.DateImplement = DateTime.Now; - } - if (_orderStorage.Update(model) == null) - { - _logger.LogWarning("Update operation failed"); - return false; - } - return true; - } - _logger.LogWarning("Changing status operation faled: Current-{Status}:required-{requiredStatus}.", model.Status, requiredStatus); - throw new InvalidOperationException($"Невозможно приствоить статус {requiredStatus} заказу с текущим статусом {model.Status}"); + _logger.LogInformation("Travel. TravelId:{TravelId}.Count:{Count}.Sum:{Sum}Id:{Id}", model.TravelId, model.Count, model.Sum, model.Id); } } } diff --git a/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/WorkModeling.cs b/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/WorkModeling.cs deleted file mode 100644 index 532d0eb..0000000 --- a/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/WorkModeling.cs +++ /dev/null @@ -1,134 +0,0 @@ -using Microsoft.Extensions.Logging; -using TravelCompanyContracts.BindingModels; -using TravelCompanyContracts.BusinessLogicsContracts; -using TravelCompanyContracts.SearchModels; -using TravelCompanyContracts.ViewModels; -using TravelCompanyDataModels.Enums; - -namespace TravelCompanyBusinessLogic.BusinessLogic -{ - 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 - }); - } - // кто-то мог уже перехватить заказ, игнорируем ошибку - catch (InvalidOperationException ex) - { - _logger.LogWarning(ex, "Error try get work"); - } - // заканчиваем выполнение имитации в случае иной ошибки - catch (Exception ex) - { - _logger.LogError(ex, "Error while do work"); - throw; - } - // отдыхаем - Thread.Sleep(implementer.Qualification * _rnd.Next(10, 100)); - } - }); - } - - 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/TravelCompany/TravelCompanyContracts/BindingModels/ImplementerBindingModel.cs b/TravelCompany/TravelCompanyContracts/BindingModels/ImplementerBindingModel.cs deleted file mode 100644 index 601dd04..0000000 --- a/TravelCompany/TravelCompanyContracts/BindingModels/ImplementerBindingModel.cs +++ /dev/null @@ -1,18 +0,0 @@ -using TravelCompanyDataModels.Models; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace TravelCompanyContracts.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/TravelCompany/TravelCompanyContracts/BindingModels/OrderBindingModel.cs b/TravelCompany/TravelCompanyContracts/BindingModels/OrderBindingModel.cs index 1645eed..3fbeb01 100644 --- a/TravelCompany/TravelCompanyContracts/BindingModels/OrderBindingModel.cs +++ b/TravelCompany/TravelCompanyContracts/BindingModels/OrderBindingModel.cs @@ -13,7 +13,6 @@ namespace TravelCompanyContracts.BindingModels public int Id { get; set; } public int TravelId { get; set; } public int ClientId { get; set; } - public int? ImplementerId { get; set; } public int Count { get; set; } public double Sum { get; set; } public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; diff --git a/TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IImplementerLogic.cs b/TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IImplementerLogic.cs deleted file mode 100644 index 2b4bcb1..0000000 --- a/TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IImplementerLogic.cs +++ /dev/null @@ -1,15 +0,0 @@ -using TravelCompanyContracts.BindingModels; -using TravelCompanyContracts.SearchModels; -using TravelCompanyContracts.ViewModels; - -namespace TravelCompanyContracts.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/TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IOrderLogic.cs b/TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IOrderLogic.cs index 4b5e550..03a4beb 100644 --- a/TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IOrderLogic.cs +++ b/TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IOrderLogic.cs @@ -26,6 +26,5 @@ namespace TravelCompanyContracts.BusinessLogicsContracts /// /// bool DeliveryOrder(OrderBindingModel model); - OrderViewModel? ReadElement(OrderSearchModel model); } } diff --git a/TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IWorkProcess.cs b/TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IWorkProcess.cs deleted file mode 100644 index 1e62835..0000000 --- a/TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IWorkProcess.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace TravelCompanyContracts.BusinessLogicsContracts -{ - public interface IWorkProcess - { - void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic); - } -} diff --git a/TravelCompany/TravelCompanyContracts/SearchModels/ImplementerSearchModel.cs b/TravelCompany/TravelCompanyContracts/SearchModels/ImplementerSearchModel.cs deleted file mode 100644 index 25eba3c..0000000 --- a/TravelCompany/TravelCompanyContracts/SearchModels/ImplementerSearchModel.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace TravelCompanyContracts.SearchModels -{ - public class ImplementerSearchModel - { - public int? Id { get; set; } - public string? ImplementerFIO { get; set; } - public string? Password { get; set; } - } -} diff --git a/TravelCompany/TravelCompanyContracts/SearchModels/OrderSearchModel.cs b/TravelCompany/TravelCompanyContracts/SearchModels/OrderSearchModel.cs index 55c45ea..ffcf4c0 100644 --- a/TravelCompany/TravelCompanyContracts/SearchModels/OrderSearchModel.cs +++ b/TravelCompany/TravelCompanyContracts/SearchModels/OrderSearchModel.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; -using TravelCompanyDataModels.Enums; namespace TravelCompanyContracts.SearchModels { @@ -11,8 +10,6 @@ namespace TravelCompanyContracts.SearchModels { public int? Id { get; set; } public int? ClientId { get; set; } - public int? ImplementerId { get; set; } - public OrderStatus? Status { get; set; } public DateTime? DateFrom { get; set; } public DateTime? DateTo { get; set; } } diff --git a/TravelCompany/TravelCompanyContracts/StoragesContracts/IImplementerStorage.cs b/TravelCompany/TravelCompanyContracts/StoragesContracts/IImplementerStorage.cs deleted file mode 100644 index 6ab3892..0000000 --- a/TravelCompany/TravelCompanyContracts/StoragesContracts/IImplementerStorage.cs +++ /dev/null @@ -1,16 +0,0 @@ -using TravelCompanyContracts.BindingModels; -using TravelCompanyContracts.SearchModels; -using TravelCompanyContracts.ViewModels; - -namespace TravelCompanyContracts.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/TravelCompany/TravelCompanyContracts/ViewModels/ImplementerViewModel.cs b/TravelCompany/TravelCompanyContracts/ViewModels/ImplementerViewModel.cs deleted file mode 100644 index 553921d..0000000 --- a/TravelCompany/TravelCompanyContracts/ViewModels/ImplementerViewModel.cs +++ /dev/null @@ -1,27 +0,0 @@ -using TravelCompanyDataModels.Models; -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace TravelCompanyContracts.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/TravelCompany/TravelCompanyContracts/ViewModels/OrderViewModel.cs b/TravelCompany/TravelCompanyContracts/ViewModels/OrderViewModel.cs index 7664779..bc1f117 100644 --- a/TravelCompany/TravelCompanyContracts/ViewModels/OrderViewModel.cs +++ b/TravelCompany/TravelCompanyContracts/ViewModels/OrderViewModel.cs @@ -20,10 +20,6 @@ namespace TravelCompanyContracts.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; } = null; - [DisplayName("Путёвка")] public string TravelName { get; set; } = string.Empty; [DisplayName("Количество")] diff --git a/TravelCompany/TravelCompanyDataModels/Models/IImplementerModel.cs b/TravelCompany/TravelCompanyDataModels/Models/IImplementerModel.cs deleted file mode 100644 index 6bfdb52..0000000 --- a/TravelCompany/TravelCompanyDataModels/Models/IImplementerModel.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace TravelCompanyDataModels.Models -{ - public interface IImplementerModel : IId - { - string ImplementerFIO { get; } - - string Password { get; } - - int WorkExperience { get; } - - int Qualification { get; } - } -} diff --git a/TravelCompany/TravelCompanyDataModels/Models/IOrderModel.cs b/TravelCompany/TravelCompanyDataModels/Models/IOrderModel.cs index a0bf921..5d9d8d9 100644 --- a/TravelCompany/TravelCompanyDataModels/Models/IOrderModel.cs +++ b/TravelCompany/TravelCompanyDataModels/Models/IOrderModel.cs @@ -6,7 +6,6 @@ namespace TravelCompanyDataModels.Models { int TravelId { get; } int ClientId { get; } - int? ImplementerId { get; } int Count { get; } double Sum { get; } OrderStatus Status { get; } diff --git a/TravelCompany/TravelCompanyDatabaseImplement/Implements/ImplementerStorage.cs b/TravelCompany/TravelCompanyDatabaseImplement/Implements/ImplementerStorage.cs deleted file mode 100644 index 2f6e092..0000000 --- a/TravelCompany/TravelCompanyDatabaseImplement/Implements/ImplementerStorage.cs +++ /dev/null @@ -1,79 +0,0 @@ -using TravelCompanyContracts.BindingModels; -using TravelCompanyContracts.SearchModels; -using TravelCompanyContracts.StoragesContracts; -using TravelCompanyContracts.ViewModels; -using TravelCompanyDatabaseImplement.Models; - -namespace TravelCompanyDatabaseImplement.Implements -{ - public class ImplementerStorage : IImplementerStorage - { - public List GetFullList() - { - using var context = new TravelCompanyDataBase(); - return context.Implementers.Select(x => x.GetViewModel).ToList(); - } - - public List GetFilteredList(ImplementerSearchModel model) - { - if (string.IsNullOrEmpty(model.ImplementerFIO)) - { - return new(); - } - using var context = new TravelCompanyDataBase(); - return context.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; - } - using var context = new TravelCompanyDataBase(); - return context.Implementers.FirstOrDefault(x => - (!string.IsNullOrEmpty(model.ImplementerFIO) && x.ImplementerFIO == model.ImplementerFIO && (!string.IsNullOrEmpty(model.Password) ? x.Password == model.Password : true)) || - (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 TravelCompanyDataBase(); - context.Implementers.Add(newImplementer); - context.SaveChanges(); - return newImplementer.GetViewModel; - } - - public ImplementerViewModel? Update(ImplementerBindingModel model) - { - using var context = new TravelCompanyDataBase(); - var implementer = context.Implementers.FirstOrDefault(x => x.Id == model.Id); - if (implementer == null) - { - return null; - } - implementer.Update(model); - context.SaveChanges(); - return implementer.GetViewModel; - } - - public ImplementerViewModel? Delete(ImplementerBindingModel model) - { - using var context = new TravelCompanyDataBase(); - 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/TravelCompany/TravelCompanyDatabaseImplement/Implements/OrderStorage.cs b/TravelCompany/TravelCompanyDatabaseImplement/Implements/OrderStorage.cs index 7d733bf..1bc439c 100644 --- a/TravelCompany/TravelCompanyDatabaseImplement/Implements/OrderStorage.cs +++ b/TravelCompany/TravelCompanyDatabaseImplement/Implements/OrderStorage.cs @@ -4,7 +4,11 @@ using TravelCompanyContracts.StoragesContracts; using TravelCompanyContracts.ViewModels; using TravelCompanyDatabaseImplement.Models; using Microsoft.EntityFrameworkCore; -using TravelCompanyDatabaseImplement; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; namespace TravelCompanyDatabaseImplement.Implements { @@ -13,41 +17,39 @@ namespace TravelCompanyDatabaseImplement.Implements public List GetFullList() { using var context = new TravelCompanyDataBase(); - return context.Orders.Include(x => x.Travel).Include(x => x.Client).Include(y => y.Implementer).Select(x => x.GetViewModel).ToList(); + return context.Orders.Include(x => x.Travel) + .Include(x => x.Client).Select(x => x.GetViewModel) + .ToList(); } - public List GetFilteredList(OrderSearchModel model) { - using var context = new TravelCompanyDataBase(); - if ((!model.DateFrom.HasValue || !model.DateTo.HasValue) && !model.ClientId.HasValue && !model.Status.HasValue) - { - return new(); - } - return context.Orders.Include(x => x.Travel).Include(x => x.Client).Include(x => x.Implementer).Where(x => - (model.DateFrom.HasValue && model.DateTo.HasValue && x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo) || - (model.ClientId.HasValue && x.ClientId == model.ClientId) || - (model.Status.HasValue && x.Status == model.Status)) - .Select(x => x.GetViewModel).ToList(); - } + using var context = new TravelCompanyDataBase(); + return context.Orders + .Include(x => x.Travel) + .Include(x => x.Client).Where(x => ( + (!model.Id.HasValue || x.Id == model.Id) && + (!model.DateFrom.HasValue || x.DateCreate >= model.DateFrom) && + (!model.DateTo.HasValue || x.DateCreate <= model.DateTo) + && + (!model.ClientId.HasValue || x.ClientId == model.ClientId) + ) + ) + .Select(x => x.GetViewModel) + .ToList(); + } public OrderViewModel? GetElement(OrderSearchModel model) { - if (!model.Id.HasValue && (!model.ImplementerId.HasValue || !model.Status.HasValue)) + if (!model.Id.HasValue) { - return new(); + return null; } using var context = new TravelCompanyDataBase(); - return context.Orders.Include(x => x.Travel).Include(x => x.Client).Include(x => x.Implementer).FirstOrDefault(x => - (model.Id.HasValue && x.Id == model.Id) || - (model.ImplementerId.HasValue && x.ImplementerId == model.ImplementerId && x.Status == model.Status)) - ?.GetViewModel; + return context.Orders.Include(x => x.Travel).Include(x => x.Client).FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; } - public OrderViewModel? Insert(OrderBindingModel model) { using var context = new TravelCompanyDataBase(); - if (model == null) - return null; var newOrder = Order.Create(context, model); if (newOrder == null) { @@ -57,29 +59,29 @@ namespace TravelCompanyDatabaseImplement.Implements context.SaveChanges(); return newOrder.GetViewModel; } - public OrderViewModel? Update(OrderBindingModel model) { using var context = new TravelCompanyDataBase(); - var order = context.Orders.FirstOrDefault(x => x.Id == model.Id); + var order = context.Orders.Include(x => x.Travel).Include(x => x.Client).FirstOrDefault(x => x.Id == + model.Id); if (order == null) { return null; } - order.Update(context, model); + order.Update(model); context.SaveChanges(); return order.GetViewModel; } - public OrderViewModel? Delete(OrderBindingModel model) { using var context = new TravelCompanyDataBase(); - var order = context.Orders.FirstOrDefault(rec => rec.Id == model.Id); - if (order != null) + var element = context.Orders.FirstOrDefault(rec => rec.Id == + model.Id); + if (element != null) { - context.Orders.Remove(order); + context.Orders.Remove(element); context.SaveChanges(); - return order.GetViewModel; + return element.GetViewModel; } return null; } diff --git a/TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240501195930_Initial-Create.Designer.cs b/TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240418113410_InitialCreate.Designer.cs similarity index 82% rename from TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240501195930_Initial-Create.Designer.cs rename to TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240418113410_InitialCreate.Designer.cs index be5ab92..be15232 100644 --- a/TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240501195930_Initial-Create.Designer.cs +++ b/TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240418113410_InitialCreate.Designer.cs @@ -12,7 +12,7 @@ using TravelCompanyDatabaseImplement; namespace TravelCompanyDatabaseImplement.Migrations { [DbContext(typeof(TravelCompanyDataBase))] - [Migration("20240501195930_Initial-Create")] + [Migration("20240418113410_InitialCreate")] partial class InitialCreate { /// @@ -70,33 +70,6 @@ namespace TravelCompanyDatabaseImplement.Migrations b.ToTable("Components"); }); - modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.Implementer", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("int"); - - SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); - - b.Property("ImplementerFIO") - .IsRequired() - .HasColumnType("nvarchar(max)"); - - b.Property("Password") - .IsRequired() - .HasColumnType("nvarchar(max)"); - - b.Property("Qualification") - .HasColumnType("int"); - - b.Property("WorkExperience") - .HasColumnType("int"); - - b.HasKey("Id"); - - b.ToTable("Implementers"); - }); - modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -117,9 +90,6 @@ namespace TravelCompanyDatabaseImplement.Migrations b.Property("DateImplement") .HasColumnType("datetime2"); - b.Property("ImplementerId") - .HasColumnType("int"); - b.Property("Status") .HasColumnType("int"); @@ -133,8 +103,6 @@ namespace TravelCompanyDatabaseImplement.Migrations b.HasIndex("ClientId"); - b.HasIndex("ImplementerId"); - b.HasIndex("TravelId"); b.ToTable("Orders"); @@ -194,10 +162,6 @@ namespace TravelCompanyDatabaseImplement.Migrations .OnDelete(DeleteBehavior.Cascade) .IsRequired(); - b.HasOne("TravelCompanyDatabaseImplement.Models.Implementer", "Implementer") - .WithMany("Order") - .HasForeignKey("ImplementerId"); - b.HasOne("TravelCompanyDatabaseImplement.Models.Travel", "Travel") .WithMany("Orders") .HasForeignKey("TravelId") @@ -206,8 +170,6 @@ namespace TravelCompanyDatabaseImplement.Migrations b.Navigation("Client"); - b.Navigation("Implementer"); - b.Navigation("Travel"); }); @@ -240,11 +202,6 @@ namespace TravelCompanyDatabaseImplement.Migrations b.Navigation("TravelComponents"); }); - modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.Implementer", b => - { - b.Navigation("Order"); - }); - modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.Travel", b => { b.Navigation("Components"); diff --git a/TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240501195930_Initial-Create.cs b/TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240418113410_InitialCreate.cs similarity index 82% rename from TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240501195930_Initial-Create.cs rename to TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240418113410_InitialCreate.cs index dc461ba..b9f0297 100644 --- a/TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240501195930_Initial-Create.cs +++ b/TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240418113410_InitialCreate.cs @@ -40,22 +40,6 @@ namespace TravelCompanyDatabaseImplement.Migrations table.PrimaryKey("PK_Components", x => x.Id); }); - migrationBuilder.CreateTable( - name: "Implementers", - columns: table => new - { - Id = table.Column(type: "int", nullable: false) - .Annotation("SqlServer:Identity", "1, 1"), - ImplementerFIO = table.Column(type: "nvarchar(max)", nullable: false), - Password = table.Column(type: "nvarchar(max)", nullable: false), - WorkExperience = table.Column(type: "int", nullable: false), - Qualification = table.Column(type: "int", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Implementers", x => x.Id); - }); - migrationBuilder.CreateTable( name: "Travels", columns: table => new @@ -82,7 +66,6 @@ namespace TravelCompanyDatabaseImplement.Migrations DateCreate = table.Column(type: "datetime2", nullable: false), DateImplement = table.Column(type: "datetime2", nullable: true), TravelId = table.Column(type: "int", nullable: false), - ImplementerId = table.Column(type: "int", nullable: true), ClientId = table.Column(type: "int", nullable: false) }, constraints: table => @@ -94,11 +77,6 @@ namespace TravelCompanyDatabaseImplement.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_Travels_TravelId", column: x => x.TravelId, @@ -139,11 +117,6 @@ namespace TravelCompanyDatabaseImplement.Migrations table: "Orders", column: "ClientId"); - migrationBuilder.CreateIndex( - name: "IX_Orders_ImplementerId", - table: "Orders", - column: "ImplementerId"); - migrationBuilder.CreateIndex( name: "IX_Orders_TravelId", table: "Orders", @@ -172,9 +145,6 @@ namespace TravelCompanyDatabaseImplement.Migrations migrationBuilder.DropTable( name: "Clients"); - migrationBuilder.DropTable( - name: "Implementers"); - migrationBuilder.DropTable( name: "Components"); diff --git a/TravelCompany/TravelCompanyDatabaseImplement/Migrations/TravelCompanyDataBaseModelSnapshot.cs b/TravelCompany/TravelCompanyDatabaseImplement/Migrations/TravelCompanyDataBaseModelSnapshot.cs index ff7cd8a..e5b8916 100644 --- a/TravelCompany/TravelCompanyDatabaseImplement/Migrations/TravelCompanyDataBaseModelSnapshot.cs +++ b/TravelCompany/TravelCompanyDatabaseImplement/Migrations/TravelCompanyDataBaseModelSnapshot.cs @@ -67,33 +67,6 @@ namespace TravelCompanyDatabaseImplement.Migrations b.ToTable("Components"); }); - modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.Implementer", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("int"); - - SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); - - b.Property("ImplementerFIO") - .IsRequired() - .HasColumnType("nvarchar(max)"); - - b.Property("Password") - .IsRequired() - .HasColumnType("nvarchar(max)"); - - b.Property("Qualification") - .HasColumnType("int"); - - b.Property("WorkExperience") - .HasColumnType("int"); - - b.HasKey("Id"); - - b.ToTable("Implementers"); - }); - modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -114,9 +87,6 @@ namespace TravelCompanyDatabaseImplement.Migrations b.Property("DateImplement") .HasColumnType("datetime2"); - b.Property("ImplementerId") - .HasColumnType("int"); - b.Property("Status") .HasColumnType("int"); @@ -130,8 +100,6 @@ namespace TravelCompanyDatabaseImplement.Migrations b.HasIndex("ClientId"); - b.HasIndex("ImplementerId"); - b.HasIndex("TravelId"); b.ToTable("Orders"); @@ -191,10 +159,6 @@ namespace TravelCompanyDatabaseImplement.Migrations .OnDelete(DeleteBehavior.Cascade) .IsRequired(); - b.HasOne("TravelCompanyDatabaseImplement.Models.Implementer", "Implementer") - .WithMany("Order") - .HasForeignKey("ImplementerId"); - b.HasOne("TravelCompanyDatabaseImplement.Models.Travel", "Travel") .WithMany("Orders") .HasForeignKey("TravelId") @@ -203,8 +167,6 @@ namespace TravelCompanyDatabaseImplement.Migrations b.Navigation("Client"); - b.Navigation("Implementer"); - b.Navigation("Travel"); }); @@ -237,11 +199,6 @@ namespace TravelCompanyDatabaseImplement.Migrations b.Navigation("TravelComponents"); }); - modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.Implementer", b => - { - b.Navigation("Order"); - }); - modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.Travel", b => { b.Navigation("Components"); diff --git a/TravelCompany/TravelCompanyDatabaseImplement/Models/Implementer.cs b/TravelCompany/TravelCompanyDatabaseImplement/Models/Implementer.cs deleted file mode 100644 index 48fb511..0000000 --- a/TravelCompany/TravelCompanyDatabaseImplement/Models/Implementer.cs +++ /dev/null @@ -1,65 +0,0 @@ -using TravelCompanyContracts.BindingModels; -using TravelCompanyContracts.ViewModels; -using TravelCompanyDataModels.Models; -using System.ComponentModel.DataAnnotations.Schema; -using System.ComponentModel.DataAnnotations; - -namespace TravelCompanyDatabaseImplement.Models -{ - public class Implementer : IImplementerModel - { - public int Id { get; set; } - - [Required] - public string ImplementerFIO { get; set; } = string.Empty; - - [Required] - public string Password { get; set; } = string.Empty; - - [Required] - public int WorkExperience { get; set; } - - [Required] - public int Qualification { get; set; } - - [ForeignKey("ImplementerId")] - public virtual List Order { 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) - { - 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/TravelCompany/TravelCompanyDatabaseImplement/Models/Order.cs b/TravelCompany/TravelCompanyDatabaseImplement/Models/Order.cs index 7b7a780..837eedc 100644 --- a/TravelCompany/TravelCompanyDatabaseImplement/Models/Order.cs +++ b/TravelCompany/TravelCompanyDatabaseImplement/Models/Order.cs @@ -2,6 +2,8 @@ using TravelCompanyContracts.ViewModels; using TravelCompanyDataModels.Enums; using TravelCompanyDataModels.Models; +using System; +using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace TravelCompanyDatabaseImplement.Models @@ -9,55 +11,43 @@ namespace TravelCompanyDatabaseImplement.Models public class Order : IOrderModel { public int Id { get; private set; } - - [Required] - public int ClientId { get; private set; } - - public virtual Client Client { get; private set; } = new(); - - [Required] - public int TravelId { get; private set; } - - public virtual Travel Travel { get; set; } = new(); - - public int? ImplementerId { get; private set; } - - public virtual Implementer? Implementer { get; set; } = new(); - [Required] public int Count { get; private set; } - [Required] public double Sum { get; private set; } - [Required] - public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен; - + public OrderStatus Status { get; private set; } [Required] - public DateTime DateCreate { get; private set; } = DateTime.Now; - + public DateTime DateCreate { get; private set; } public DateTime? DateImplement { get; private set; } - - public static Order Create(TravelCompanyDataBase context, OrderBindingModel model) + [Required] + public int TravelId { get; private set; } + public virtual Travel Travel { get; private set; } + [Required] + public int ClientId { get; private set; } + public virtual Client Client { get; private set; } + public static Order? Create(TravelCompanyDataBase context, OrderBindingModel model) { + if (model == null) + { + return null; + } return new Order() { Id = model.Id, - ClientId = model.ClientId, - Client = context.Clients.First(x => x.Id == model.ClientId), - TravelId = model.TravelId, - Travel = context.Travels.First(x => x.Id == model.TravelId), - ImplementerId = model.ImplementerId, - Implementer = model.ImplementerId.HasValue ? context.Implementers.First(x => x.Id == model.ImplementerId) : null, Count = model.Count, Sum = model.Sum, Status = model.Status, DateCreate = model.DateCreate, DateImplement = model.DateImplement, + TravelId = model.TravelId, + Travel = context.Travels.FirstOrDefault(x => x.Id == model.TravelId), + ClientId = model.ClientId, + Client = context.Clients.FirstOrDefault(x => x.Id == model.ClientId), }; } - public void Update(TravelCompanyDataBase context, OrderBindingModel? model) + public void Update(OrderBindingModel? model) { if (model == null) { @@ -65,24 +55,21 @@ namespace TravelCompanyDatabaseImplement.Models } Status = model.Status; DateImplement = model.DateImplement; - ImplementerId = model.ImplementerId; - Implementer = model.ImplementerId.HasValue ? context.Implementers.First(x => x.Id == model.ImplementerId) : null; } public OrderViewModel GetViewModel => new() { - Id = Id, - ClientId = ClientId, - ClientFIO = Client.ClientFIO, TravelId = TravelId, - TravelName = Travel.TravelName, - ImplementerId = ImplementerId, - ImplementerFIO = Implementer != null ? Implementer.ImplementerFIO : null, + ClientId = ClientId, Count = Count, Sum = Sum, Status = Status, DateCreate = DateCreate, DateImplement = DateImplement, + TravelName = Travel.TravelName, + Id = Id, + ClientFIO = Client.ClientFIO }; + } } diff --git a/TravelCompany/TravelCompanyDatabaseImplement/TravelCompanyDataBase.cs b/TravelCompany/TravelCompanyDatabaseImplement/TravelCompanyDataBase.cs index eca8a18..644f731 100644 --- a/TravelCompany/TravelCompanyDatabaseImplement/TravelCompanyDataBase.cs +++ b/TravelCompany/TravelCompanyDatabaseImplement/TravelCompanyDataBase.cs @@ -16,7 +16,7 @@ optionsBuilder) { if (optionsBuilder.IsConfigured == false) { - optionsBuilder.UseSqlServer(@"Data Source=DESKTOP-D5A5OOG\GOLDFEST;Initial Catalog=TravelCompanyDatabase1;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True"); + optionsBuilder.UseSqlServer(@"Data Source=DESKTOP-D5A5OOG\GOLDFEST;Initial Catalog=TravelCompanyDatabase;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True"); } base.OnConfiguring(optionsBuilder); } @@ -25,7 +25,6 @@ optionsBuilder) public virtual DbSet TravelComponents { set; get; } public virtual DbSet Orders { set; get; } public virtual DbSet Clients { set; get; } - public virtual DbSet Implementers { set; get; } } } diff --git a/TravelCompany/TravelCompanyFileImplement/DataFileSingleton.cs b/TravelCompany/TravelCompanyFileImplement/DataFileSingleton.cs index 7c0d1a3..f7e2376 100644 --- a/TravelCompany/TravelCompanyFileImplement/DataFileSingleton.cs +++ b/TravelCompany/TravelCompanyFileImplement/DataFileSingleton.cs @@ -5,7 +5,6 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; -using TravelCompanyFileImplement.Models; namespace TravelCompanyFileImplement { @@ -16,12 +15,10 @@ namespace TravelCompanyFileImplement private readonly string OrderFileName = "Order.xml"; private readonly string TravelFileName = "Travel.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 Travels { get; private set; } public List Clients { get; private set; } - public List Implementers { get; private set; } public static DataFileSingleton GetInstance() { if (instance == null) @@ -35,8 +32,6 @@ namespace TravelCompanyFileImplement 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)!)!; @@ -44,8 +39,6 @@ namespace TravelCompanyFileImplement 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/TravelCompany/TravelCompanyFileImplement/Implements/ImplementerStorage.cs b/TravelCompany/TravelCompanyFileImplement/Implements/ImplementerStorage.cs deleted file mode 100644 index 2f50f08..0000000 --- a/TravelCompany/TravelCompanyFileImplement/Implements/ImplementerStorage.cs +++ /dev/null @@ -1,94 +0,0 @@ -using TravelCompanyContracts.BindingModels; -using TravelCompanyContracts.SearchModels; -using TravelCompanyContracts.StoragesContracts; -using TravelCompanyContracts.ViewModels; -using TravelCompanyFileImplement.Models; - -namespace TravelCompanyFileImplement.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 (model == null) - { - return new(); - } - if (model.Id.HasValue) - { - var res = GetElement(model); - return res != null ? new() { res } : new(); - } - if (model.ImplementerFIO != null) - { - return _source.Implementers - .Where(x => x.ImplementerFIO.Equals(model.ImplementerFIO)) - .Select(x => x.GetViewModel) - .ToList(); - } - return new(); - } - - public ImplementerViewModel? GetElement(ImplementerSearchModel model) - { - if (model.Id.HasValue) - { - return _source.Implementers.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; - } - if (model.ImplementerFIO != null && model.Password != null) - { - return _source.Implementers.FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO) && x.Password.Equals(model.Password))?.GetViewModel; - } - if (model.ImplementerFIO != null) - { - return _source.Implementers.FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO))?.GetViewModel; - } - return null; - } - - public ImplementerViewModel? Insert(ImplementerBindingModel model) - { - model.Id = _source.Implementers.Count > 0 ? _source.Implementers.Max(x => x.Id) + 1 : 1; - var res = Implementer.Create(model); - if (res != null) - { - _source.Implementers.Add(res); - _source.SaveImplementers(); - } - return res?.GetViewModel; - } - - public ImplementerViewModel? Update(ImplementerBindingModel model) - { - var res = _source.Implementers.FirstOrDefault(x => x.Id == model.Id); - if (res != null) - { - res.Update(model); - _source.SaveImplementers(); - } - return res?.GetViewModel; - } - - public ImplementerViewModel? Delete(ImplementerBindingModel model) - { - var res = _source.Implementers.FirstOrDefault(x => x.Id == model.Id); - if (res != null) - { - _source.Implementers.Remove(res); - _source.SaveImplementers(); - } - return res?.GetViewModel; - } - } -} diff --git a/TravelCompany/TravelCompanyFileImplement/Implements/OrderStorage.cs b/TravelCompany/TravelCompanyFileImplement/Implements/OrderStorage.cs index 5a64a5f..8ea5ea9 100644 --- a/TravelCompany/TravelCompanyFileImplement/Implements/OrderStorage.cs +++ b/TravelCompany/TravelCompanyFileImplement/Implements/OrderStorage.cs @@ -36,8 +36,6 @@ model) (!model.DateTo.HasValue || x.DateCreate <= model.DateTo) && (!model.ClientId.HasValue || x.ClientId == model.ClientId) - && - (!model.ImplementerId.HasValue || x.ImplementerId == model.ImplementerId) ) ) .Select(x => AccessTravelStorage(x.GetViewModel)) diff --git a/TravelCompany/TravelCompanyFileImplement/Models/Implementer.cs b/TravelCompany/TravelCompanyFileImplement/Models/Implementer.cs deleted file mode 100644 index 7618081..0000000 --- a/TravelCompany/TravelCompanyFileImplement/Models/Implementer.cs +++ /dev/null @@ -1,87 +0,0 @@ -using TravelCompanyContracts.BindingModels; -using TravelCompanyContracts.ViewModels; -using TravelCompanyDataModels.Models; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Xml.Linq; - -namespace TravelCompanyFileImplement.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(XElement element) - { - if (element == null) - { - return null; - } - return new() - { - ImplementerFIO = element.Element("FIO")!.Value, - Password = element.Element("Password")!.Value, - Id = Convert.ToInt32(element.Attribute("Id")!.Value), - Qualification = Convert.ToInt32(element.Element("Qualification")!.Value), - WorkExperience = Convert.ToInt32(element.Element("WorkExperience")!.Value), - }; - } - - public static Implementer? Create(ImplementerBindingModel model) - { - if (model == null) - { - return null; - } - return new() - { - Id = model.Id, - Password = model.Password, - Qualification = model.Qualification, - ImplementerFIO = model.ImplementerFIO, - WorkExperience = model.WorkExperience, - }; - } - - - - public void Update(ImplementerBindingModel model) - { - if (model == null) - { - return; - } - Password = model.Password; - Qualification = model.Qualification; - ImplementerFIO = model.ImplementerFIO; - WorkExperience = model.WorkExperience; - } - - public ImplementerViewModel GetViewModel => new() - { - Id = Id, - Password = Password, - Qualification = Qualification, - ImplementerFIO = ImplementerFIO, - }; - - public XElement GetXElement => new("Client", - new XAttribute("Id", Id), - new XElement("Password", Password), - new XElement("FIO", ImplementerFIO), - new XElement("Qualification", Qualification), - new XElement("WorkExperience", WorkExperience) - ); - } -} diff --git a/TravelCompany/TravelCompanyFileImplement/Models/Order.cs b/TravelCompany/TravelCompanyFileImplement/Models/Order.cs index 13d0abd..e5a5ceb 100644 --- a/TravelCompany/TravelCompanyFileImplement/Models/Order.cs +++ b/TravelCompany/TravelCompanyFileImplement/Models/Order.cs @@ -15,7 +15,6 @@ namespace TravelCompanyFileImplement.Models { public int TravelId { get; private set; } public int ClientId { get; private set; } - public int? ImplementerId { get; set; } public int Count { get; private set; } @@ -40,7 +39,6 @@ namespace TravelCompanyFileImplement.Models Id = model.Id, TravelId = model.TravelId, ClientId = model.ClientId, - ImplementerId = model.ImplementerId, Count = model.Count, Sum = model.Sum, Status = model.Status, @@ -60,7 +58,6 @@ namespace TravelCompanyFileImplement.Models Id = Convert.ToInt32(element.Attribute("Id")!.Value), TravelId = Convert.ToInt32(element.Element("TravelId")!.Value), ClientId = Convert.ToInt32(element.Element("ClientId")!.Value), - ImplementerId = Convert.ToInt32(element.Element("ImplementerId")!.Value), Count = Convert.ToInt32(element.Element("Count")!.Value), Sum = Convert.ToDouble(element.Element("Sum")!.Value), Status = (OrderStatus)Enum.Parse(typeof(OrderStatus), element.Element("Status")!.Value.ToString()), @@ -84,7 +81,6 @@ namespace TravelCompanyFileImplement.Models Id = Id, TravelId = TravelId, ClientId = ClientId, - ImplementerId = ImplementerId, Count = Count, Sum = Sum, Status = Status, @@ -95,8 +91,6 @@ namespace TravelCompanyFileImplement.Models public XElement GetXElement => new("Order", new XAttribute("Id", Id), new XElement("TravelId", TravelId), - new XElement("ClientId", ClientId.ToString()), - new XElement("ImplementerId", ImplementerId), new XElement("Count", Count.ToString()), new XElement("Sum", Sum.ToString()), new XElement("Status", Status.ToString()), diff --git a/TravelCompany/TravelCompanyListImplement/DataListSingleton.cs b/TravelCompany/TravelCompanyListImplement/DataListSingleton.cs index 055b60f..50570c7 100644 --- a/TravelCompany/TravelCompanyListImplement/DataListSingleton.cs +++ b/TravelCompany/TravelCompanyListImplement/DataListSingleton.cs @@ -14,14 +14,12 @@ namespace TravelCompanyListImplement public List Orders { get; set; } public List Travels { get; set; } public List Clients { get; set; } - public List Implementers { get; set; } private DataListSingleton() { Components = new List(); Orders = new List(); Travels = new List(); Clients = new List(); - Implementers = new List(); } public static DataListSingleton GetInstance() { diff --git a/TravelCompany/TravelCompanyListImplement/Implements/ImplementerStorage.cs b/TravelCompany/TravelCompanyListImplement/Implements/ImplementerStorage.cs deleted file mode 100644 index 974b5e8..0000000 --- a/TravelCompany/TravelCompanyListImplement/Implements/ImplementerStorage.cs +++ /dev/null @@ -1,118 +0,0 @@ -using TravelCompanyContracts.BindingModels; -using TravelCompanyContracts.SearchModels; -using TravelCompanyContracts.StoragesContracts; -using TravelCompanyContracts.ViewModels; -using TravelCompanyListImplement.Models; - -namespace TravelCompanyListImplement.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) - { - foreach (var x in _source.Implementers) - { - if (model.Id.HasValue && x.Id == model.Id) - { - return x.GetViewModel; - } - if (model.ImplementerFIO != null && model.Password != null && x.ImplementerFIO.Equals(model.ImplementerFIO) && x.Password.Equals(model.Password)) - { - return x.GetViewModel; - } - if (model.ImplementerFIO != null && x.ImplementerFIO.Equals(model.ImplementerFIO)) - { - return x.GetViewModel; - } - } - return null; - } - - public List GetFilteredList(ImplementerSearchModel model) - { - if (model == null) - { - return new(); - } - if (model.Id.HasValue) - { - var res = GetElement(model); - return res != null ? new() { res } : new(); - } - - List result = new(); - if (model.ImplementerFIO != null) - { - foreach (var implementer in _source.Implementers) - { - if (implementer.ImplementerFIO.Equals(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 res = Implementer.Create(model); - if (res != null) - { - _source.Implementers.Add(res); - } - return res?.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/TravelCompany/TravelCompanyListImplement/Models/Implementer.cs b/TravelCompany/TravelCompanyListImplement/Models/Implementer.cs deleted file mode 100644 index 6e428ab..0000000 --- a/TravelCompany/TravelCompanyListImplement/Models/Implementer.cs +++ /dev/null @@ -1,60 +0,0 @@ -using TravelCompanyContracts.BindingModels; -using TravelCompanyContracts.ViewModels; -using TravelCompanyDataModels.Models; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace TravelCompanyListImplement.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() - { - Id = model.Id, - Password = model.Password, - Qualification = model.Qualification, - ImplementerFIO = model.ImplementerFIO, - WorkExperience = model.WorkExperience, - }; - } - - public void Update(ImplementerBindingModel model) - { - if (model == null) - { - return; - } - Password = model.Password; - Qualification = model.Qualification; - ImplementerFIO = model.ImplementerFIO; - WorkExperience = model.WorkExperience; - } - - public ImplementerViewModel GetViewModel => new() - { - Id = Id, - Password = Password, - Qualification = Qualification, - ImplementerFIO = ImplementerFIO, - }; - } -} diff --git a/TravelCompany/TravelCompanyListImplement/Models/Order.cs b/TravelCompany/TravelCompanyListImplement/Models/Order.cs index 868e696..f97a641 100644 --- a/TravelCompany/TravelCompanyListImplement/Models/Order.cs +++ b/TravelCompany/TravelCompanyListImplement/Models/Order.cs @@ -16,7 +16,6 @@ namespace TravelCompanyListImplement.Models public int Id { get; private set; } public int TravelId { get; private set; } public int ClientId { 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; } @@ -33,7 +32,6 @@ namespace TravelCompanyListImplement.Models Id = model.Id, TravelId = model.TravelId, ClientId = model.ClientId, - ImplementerId = model.ImplementerId, Count = model.Count, Sum = model.Sum, Status = model.Status, @@ -49,7 +47,6 @@ namespace TravelCompanyListImplement.Models } TravelId = model.TravelId; ClientId = model.ClientId; - ImplementerId = ImplementerId; Count = model.Count; Sum = model.Sum; Status = model.Status; @@ -61,7 +58,6 @@ namespace TravelCompanyListImplement.Models Id = Id, TravelId = TravelId, ClientId = ClientId, - ImplementerId = ImplementerId, Count = Count, Sum = Sum, Status = Status, diff --git a/TravelCompany/TravelCompanyRestApi/Controllers/ImplementerController.cs b/TravelCompany/TravelCompanyRestApi/Controllers/ImplementerController.cs deleted file mode 100644 index c7732b7..0000000 --- a/TravelCompany/TravelCompanyRestApi/Controllers/ImplementerController.cs +++ /dev/null @@ -1,107 +0,0 @@ -using Microsoft.AspNetCore.Mvc; -using TravelCompanyContracts.BindingModels; -using TravelCompanyContracts.BusinessLogicsContracts; -using TravelCompanyContracts.SearchModels; -using TravelCompanyContracts.ViewModels; -using TravelCompanyDataModels.Enums; - -namespace TravelCompanyRestApi.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; - } - } - } -} diff --git a/TravelCompany/TravelCompanyRestApi/Program.cs b/TravelCompany/TravelCompanyRestApi/Program.cs index 257c2e8..656951d 100644 --- a/TravelCompany/TravelCompanyRestApi/Program.cs +++ b/TravelCompany/TravelCompanyRestApi/Program.cs @@ -8,14 +8,11 @@ builder.Logging.SetMinimumLevel(LogLevel.Trace); builder.Logging.AddLog4Net("log4net.config"); // Add services to the container. 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 -- 2.25.1 From 0d16f299143a477acd619edc75a565d4c4737c24 Mon Sep 17 00:00:00 2001 From: goldfest Date: Thu, 2 May 2024 14:54:56 +0400 Subject: [PATCH 3/4] ready --- .../TravelCompany/FormMain.Designer.cs | 34 +++- TravelCompany/TravelCompany/FormMain.cs | 24 ++- .../TravelCompany/ImplementerForm.Designer.cs | 162 ++++++++++++++++++ .../TravelCompany/ImplementerForm.cs | 109 ++++++++++++ .../TravelCompany/ImplementerForm.resx | 120 +++++++++++++ .../ImplementersForm.Designer.cs | 114 ++++++++++++ .../TravelCompany/ImplementersForm.cs | 125 ++++++++++++++ .../TravelCompany/ImplementersForm.resx | 120 +++++++++++++ TravelCompany/TravelCompany/Program.cs | 5 + .../BusinessLogic/ImplementerLogic.cs | 128 ++++++++++++++ .../BusinessLogic/OrderLogic.cs | 72 ++++---- .../BusinessLogic/WorkModeling.cs | 145 ++++++++++++++++ .../BindingModels/ImplementerBindingModel.cs | 18 ++ .../BindingModels/OrderBindingModel.cs | 1 + .../IImplementerLogic.cs | 20 +++ .../BusinessLogicsContracts/IOrderLogic.cs | 11 +- .../BusinessLogicsContracts/IWorkProcess.cs | 13 ++ .../SearchModels/ImplementerSearchModel.cs | 15 ++ .../SearchModels/OrderSearchModel.cs | 3 + .../StoragesContracts/IImplementerStorage.cs | 21 +++ .../ViewModels/ImplementerViewModel.cs | 23 +++ .../ViewModels/OrderViewModel.cs | 3 + .../Models/IImplementerModel.cs | 17 ++ .../Models/IOrderModel.cs | 1 + .../Implements/ImplementerStorage.cs | 87 ++++++++++ .../Implements/OrderStorage.cs | 17 +- ...20240502101530_Initial-Create.Designer.cs} | 45 ++++- ...te.cs => 20240502101530_Initial-Create.cs} | 32 +++- .../TravelCompanyDataBaseModelSnapshot.cs | 43 +++++ .../Models/Implementer.cs | 65 +++++++ .../Models/Order.cs | 11 +- .../TravelCompanyDataBase.cs | 3 +- .../DataFileSingleton.cs | 8 + .../Implements/ImplementerStorage.cs | 83 +++++++++ .../Models/Implementer.cs | 78 +++++++++ .../Models/Order.cs | 8 +- .../DataListSingleton.cs | 6 +- .../Implements/ImplementerStorage.cs | 103 +++++++++++ .../Implements/OrderStorage.cs | 36 ++-- .../Models/Implementer.cs | 54 ++++++ .../Models/Order.cs | 4 + .../Controllers/ImplementerController.cs | 105 ++++++++++++ 42 files changed, 1999 insertions(+), 93 deletions(-) create mode 100644 TravelCompany/TravelCompany/ImplementerForm.Designer.cs create mode 100644 TravelCompany/TravelCompany/ImplementerForm.cs create mode 100644 TravelCompany/TravelCompany/ImplementerForm.resx create mode 100644 TravelCompany/TravelCompany/ImplementersForm.Designer.cs create mode 100644 TravelCompany/TravelCompany/ImplementersForm.cs create mode 100644 TravelCompany/TravelCompany/ImplementersForm.resx create mode 100644 TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/ImplementerLogic.cs create mode 100644 TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/WorkModeling.cs create mode 100644 TravelCompany/TravelCompanyContracts/BindingModels/ImplementerBindingModel.cs create mode 100644 TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IImplementerLogic.cs create mode 100644 TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IWorkProcess.cs create mode 100644 TravelCompany/TravelCompanyContracts/SearchModels/ImplementerSearchModel.cs create mode 100644 TravelCompany/TravelCompanyContracts/StoragesContracts/IImplementerStorage.cs create mode 100644 TravelCompany/TravelCompanyContracts/ViewModels/ImplementerViewModel.cs create mode 100644 TravelCompany/TravelCompanyDataModels/Models/IImplementerModel.cs create mode 100644 TravelCompany/TravelCompanyDatabaseImplement/Implements/ImplementerStorage.cs rename TravelCompany/TravelCompanyDatabaseImplement/Migrations/{20240418113410_InitialCreate.Designer.cs => 20240502101530_Initial-Create.Designer.cs} (82%) rename TravelCompany/TravelCompanyDatabaseImplement/Migrations/{20240418113410_InitialCreate.cs => 20240502101530_Initial-Create.cs} (81%) create mode 100644 TravelCompany/TravelCompanyDatabaseImplement/Models/Implementer.cs create mode 100644 TravelCompany/TravelCompanyFileImplement/Implements/ImplementerStorage.cs create mode 100644 TravelCompany/TravelCompanyFileImplement/Models/Implementer.cs create mode 100644 TravelCompany/TravelCompanyListImplement/Implements/ImplementerStorage.cs create mode 100644 TravelCompany/TravelCompanyListImplement/Models/Implementer.cs create mode 100644 TravelCompany/TravelCompanyRestApi/Controllers/ImplementerController.cs diff --git a/TravelCompany/TravelCompany/FormMain.Designer.cs b/TravelCompany/TravelCompany/FormMain.Designer.cs index e3b2b36..3d1f849 100644 --- a/TravelCompany/TravelCompany/FormMain.Designer.cs +++ b/TravelCompany/TravelCompany/FormMain.Designer.cs @@ -33,17 +33,19 @@ toolStripDropDownButton1 = new ToolStripDropDownButton(); компонентыToolStripMenuItem = new ToolStripMenuItem(); ПутёвкиToolStripMenuItem = new ToolStripMenuItem(); + клиентыToolStripMenuItem = new ToolStripMenuItem(); отчетыToolStripMenuItem = new ToolStripMenuItem(); списокКомпонентовToolStripMenuItem = new ToolStripMenuItem(); компонентыПоПутёвкамToolStripMenuItem = new ToolStripMenuItem(); списокЗаказовToolStripMenuItem = new ToolStripMenuItem(); + запускРаботToolStripMenuItem = new ToolStripMenuItem(); buttonCreateOrder = new Button(); buttonTakeOrderInWork = new Button(); buttonOrderReady = new Button(); buttonIssuedOrder = new Button(); buttonRef = new Button(); dataGridView = new DataGridView(); - клиентыToolStripMenuItem = new ToolStripMenuItem(); + исполнителиToolStripMenuItem = new ToolStripMenuItem(); toolStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); SuspendLayout(); @@ -51,7 +53,7 @@ // toolStrip1 // toolStrip1.ImageScalingSize = new Size(20, 20); - toolStrip1.Items.AddRange(new ToolStripItem[] { toolStripDropDownButton1, отчетыToolStripMenuItem }); + toolStrip1.Items.AddRange(new ToolStripItem[] { toolStripDropDownButton1, отчетыToolStripMenuItem, запускРаботToolStripMenuItem }); toolStrip1.Location = new Point(0, 0); toolStrip1.Name = "toolStrip1"; toolStrip1.Size = new Size(969, 25); @@ -61,7 +63,7 @@ // toolStripDropDownButton1 // toolStripDropDownButton1.DisplayStyle = ToolStripItemDisplayStyle.Text; - toolStripDropDownButton1.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, ПутёвкиToolStripMenuItem, клиентыToolStripMenuItem }); + toolStripDropDownButton1.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, ПутёвкиToolStripMenuItem, клиентыToolStripMenuItem, исполнителиToolStripMenuItem }); toolStripDropDownButton1.Image = (Image)resources.GetObject("toolStripDropDownButton1.Image"); toolStripDropDownButton1.ImageTransparentColor = Color.Magenta; toolStripDropDownButton1.Name = "toolStripDropDownButton1"; @@ -82,6 +84,13 @@ ПутёвкиToolStripMenuItem.Text = "Туристич. путёвки"; ПутёвкиToolStripMenuItem.Click += консервыToolStripMenuItem_Click; // + // клиентыToolStripMenuItem + // + клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; + клиентыToolStripMenuItem.Size = new Size(180, 22); + клиентыToolStripMenuItem.Text = "Клиенты"; + клиентыToolStripMenuItem.Click += клиентыToolStripMenuItem_Click; + // // отчетыToolStripMenuItem // отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокКомпонентовToolStripMenuItem, компонентыПоПутёвкамToolStripMenuItem, списокЗаказовToolStripMenuItem }); @@ -110,6 +119,13 @@ списокЗаказовToolStripMenuItem.Text = "Список заказов"; списокЗаказовToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click; // + // запускРаботToolStripMenuItem + // + запускРаботToolStripMenuItem.Name = "запускРаботToolStripMenuItem"; + запускРаботToolStripMenuItem.Size = new Size(92, 25); + запускРаботToolStripMenuItem.Text = "Запуск работ"; + запускРаботToolStripMenuItem.Click += запускРаботToolStripMenuItem_Click; + // // buttonCreateOrder // buttonCreateOrder.Location = new Point(800, 56); @@ -172,12 +188,12 @@ dataGridView.Size = new Size(763, 435); dataGridView.TabIndex = 6; // - // клиентыToolStripMenuItem + // исполнителиToolStripMenuItem // - клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; - клиентыToolStripMenuItem.Size = new Size(180, 22); - клиентыToolStripMenuItem.Text = "Клиенты"; - клиентыToolStripMenuItem.Click += клиентыToolStripMenuItem_Click; + исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; + исполнителиToolStripMenuItem.Size = new Size(180, 22); + исполнителиToolStripMenuItem.Text = "Исполнители"; + исполнителиToolStripMenuItem.Click += исполнителиToolStripMenuItem_Click; // // FormMain // @@ -218,5 +234,7 @@ private ToolStripMenuItem компонентыПоПутёвкамToolStripMenuItem; private ToolStripMenuItem списокЗаказовToolStripMenuItem; private ToolStripMenuItem клиентыToolStripMenuItem; + private ToolStripMenuItem запускРаботToolStripMenuItem; + private ToolStripMenuItem исполнителиToolStripMenuItem; } } \ No newline at end of file diff --git a/TravelCompany/TravelCompany/FormMain.cs b/TravelCompany/TravelCompany/FormMain.cs index dbe9ade..42be528 100644 --- a/TravelCompany/TravelCompany/FormMain.cs +++ b/TravelCompany/TravelCompany/FormMain.cs @@ -19,12 +19,14 @@ namespace TravelCompany.Forms 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) { @@ -41,6 +43,8 @@ namespace TravelCompany.Forms { dataGridView.DataSource = list; dataGridView.Columns["TravelId"].Visible = false; + dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["ImplementerId"].Visible = false; dataGridView.Columns["TravelName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; } @@ -198,5 +202,23 @@ Program.ServiceProvider?.GetService(typeof(FormClients)); 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); + } + + private void исполнителиToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = +Program.ServiceProvider?.GetService(typeof(ImplementersForm)); + if (service is ImplementersForm form) + { + form.ShowDialog(); + } + } } } diff --git a/TravelCompany/TravelCompany/ImplementerForm.Designer.cs b/TravelCompany/TravelCompany/ImplementerForm.Designer.cs new file mode 100644 index 0000000..0d20fac --- /dev/null +++ b/TravelCompany/TravelCompany/ImplementerForm.Designer.cs @@ -0,0 +1,162 @@ +namespace TravelCompany.Forms +{ + partial class ImplementerForm + { + /// + /// 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() + { + FIOTextBox = new TextBox(); + PasswordTextBox = new TextBox(); + QualificationTextBox = new TextBox(); + WorkExperienceTextBox = new TextBox(); + label1 = new Label(); + label2 = new Label(); + label3 = new Label(); + label4 = new Label(); + SaveButton = new Button(); + CancelButton = new Button(); + SuspendLayout(); + // + // FIOTextBox + // + FIOTextBox.Location = new Point(124, 19); + FIOTextBox.Name = "FIOTextBox"; + FIOTextBox.Size = new Size(411, 27); + FIOTextBox.TabIndex = 0; + // + // PasswordTextBox + // + PasswordTextBox.Location = new Point(124, 52); + PasswordTextBox.Name = "PasswordTextBox"; + PasswordTextBox.Size = new Size(411, 27); + PasswordTextBox.TabIndex = 1; + // + // QualificationTextBox + // + QualificationTextBox.Location = new Point(124, 85); + QualificationTextBox.Name = "QualificationTextBox"; + QualificationTextBox.Size = new Size(411, 27); + QualificationTextBox.TabIndex = 2; + // + // WorkExperienceTextBox + // + WorkExperienceTextBox.Location = new Point(124, 118); + WorkExperienceTextBox.Name = "WorkExperienceTextBox"; + WorkExperienceTextBox.Size = new Size(411, 27); + WorkExperienceTextBox.TabIndex = 3; + // + // label1 + // + label1.AutoSize = true; + label1.Location = new Point(9, 19); + label1.Name = "label1"; + label1.Size = new Size(42, 20); + label1.TabIndex = 4; + label1.Text = "ФИО"; + // + // label2 + // + label2.AutoSize = true; + label2.Location = new Point(9, 52); + label2.Name = "label2"; + label2.Size = new Size(62, 20); + label2.TabIndex = 5; + label2.Text = "Пароль"; + // + // label3 + // + label3.AutoSize = true; + label3.Location = new Point(9, 85); + label3.Name = "label3"; + label3.Size = new Size(111, 20); + label3.TabIndex = 6; + label3.Text = "Квалификация"; + // + // label4 + // + label4.AutoSize = true; + label4.Location = new Point(9, 118); + label4.Name = "label4"; + label4.Size = new Size(99, 20); + label4.TabIndex = 7; + label4.Text = "Стаж работы"; + // + // SaveButton + // + SaveButton.Location = new Point(341, 151); + SaveButton.Name = "SaveButton"; + SaveButton.Size = new Size(94, 29); + SaveButton.TabIndex = 8; + SaveButton.Text = "Сохранить"; + SaveButton.UseVisualStyleBackColor = true; + SaveButton.Click += SaveButton_Click; + // + // CancelButton + // + CancelButton.Location = new Point(441, 151); + CancelButton.Name = "CancelButton"; + CancelButton.Size = new Size(94, 29); + CancelButton.TabIndex = 9; + CancelButton.Text = "Отмена"; + CancelButton.UseVisualStyleBackColor = true; + CancelButton.Click += CancelButton_Click; + // + // ImplementerForm + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(548, 186); + Controls.Add(CancelButton); + Controls.Add(SaveButton); + Controls.Add(label4); + Controls.Add(label3); + Controls.Add(label2); + Controls.Add(label1); + Controls.Add(WorkExperienceTextBox); + Controls.Add(QualificationTextBox); + Controls.Add(PasswordTextBox); + Controls.Add(FIOTextBox); + Name = "ImplementerForm"; + Text = "Исполнитель"; + Load += ImplementerForm_Load; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private TextBox FIOTextBox; + private TextBox PasswordTextBox; + private TextBox QualificationTextBox; + private TextBox WorkExperienceTextBox; + private Label label1; + private Label label2; + private Label label3; + private Label label4; + private Button SaveButton; + private Button CancelButton; + } +} \ No newline at end of file diff --git a/TravelCompany/TravelCompany/ImplementerForm.cs b/TravelCompany/TravelCompany/ImplementerForm.cs new file mode 100644 index 0000000..4d0496b --- /dev/null +++ b/TravelCompany/TravelCompany/ImplementerForm.cs @@ -0,0 +1,109 @@ +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.BusinessLogicsContracts; +using TravelCompanyContracts.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 TravelCompany.Forms +{ + public partial class ImplementerForm : Form + { + private readonly ILogger _logger; + private readonly IImplementerLogic _logic; + private int? _id; + public int Id { set { _id = value; } } + public ImplementerForm(ILogger logger, IImplementerLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + private void ImplementerForm_Load(object sender, EventArgs e) + { + if (_id.HasValue) + { + try + { + _logger.LogInformation("Получение исполнителя"); + var view = _logic.ReadElement(new ImplementerSearchModel + { + Id = + _id.Value + }); + if (view != null) + { + FIOTextBox.Text = view.ImplementerFIO; + PasswordTextBox.Text = view.Password; + QualificationTextBox.Text = view.Qualification.ToString(); + WorkExperienceTextBox.Text = view.WorkExperience.ToString(); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения исполнителя"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + } + + private void SaveButton_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(FIOTextBox.Text)) + { + MessageBox.Show("Заполните ФИО", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (string.IsNullOrEmpty(PasswordTextBox.Text)) + { + MessageBox.Show("Заполните пароль", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Сохранение компонента"); + try + { + var model = new ImplementerBindingModel + { + Id = _id ?? 0, + ImplementerFIO = FIOTextBox.Text, + Password = PasswordTextBox.Text, + Qualification = Convert.ToInt32(QualificationTextBox.Text), + WorkExperience = Convert.ToInt32(WorkExperienceTextBox.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 CancelButton_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } +} diff --git a/TravelCompany/TravelCompany/ImplementerForm.resx b/TravelCompany/TravelCompany/ImplementerForm.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/TravelCompany/TravelCompany/ImplementerForm.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/TravelCompany/TravelCompany/ImplementersForm.Designer.cs b/TravelCompany/TravelCompany/ImplementersForm.Designer.cs new file mode 100644 index 0000000..3327624 --- /dev/null +++ b/TravelCompany/TravelCompany/ImplementersForm.Designer.cs @@ -0,0 +1,114 @@ +namespace TravelCompany.Forms +{ + partial class ImplementersForm + { + /// + /// 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() + { + dataGridView1 = new DataGridView(); + CreateButton = new Button(); + ChangeButton = new Button(); + DeleteButton = new Button(); + RefreshButton = new Button(); + ((System.ComponentModel.ISupportInitialize)dataGridView1).BeginInit(); + SuspendLayout(); + // + // dataGridView1 + // + dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView1.Location = new Point(12, 12); + dataGridView1.Name = "dataGridView1"; + dataGridView1.RowHeadersWidth = 51; + dataGridView1.RowTemplate.Height = 29; + dataGridView1.Size = new Size(565, 426); + dataGridView1.TabIndex = 0; + // + // CreateButton + // + CreateButton.Location = new Point(583, 12); + CreateButton.Name = "CreateButton"; + CreateButton.Size = new Size(205, 29); + CreateButton.TabIndex = 1; + CreateButton.Text = "Создать"; + CreateButton.UseVisualStyleBackColor = true; + CreateButton.Click += CreateButton_Click; + // + // ChangeButton + // + ChangeButton.Location = new Point(583, 47); + ChangeButton.Name = "ChangeButton"; + ChangeButton.Size = new Size(205, 29); + ChangeButton.TabIndex = 2; + ChangeButton.Text = "Изменить"; + ChangeButton.UseVisualStyleBackColor = true; + ChangeButton.Click += ChangeButton_Click; + // + // DeleteButton + // + DeleteButton.Location = new Point(583, 82); + DeleteButton.Name = "DeleteButton"; + DeleteButton.Size = new Size(205, 29); + DeleteButton.TabIndex = 3; + DeleteButton.Text = "Удалить"; + DeleteButton.UseVisualStyleBackColor = true; + DeleteButton.Click += DeleteButton_Click; + // + // RefreshButton + // + RefreshButton.Location = new Point(583, 117); + RefreshButton.Name = "RefreshButton"; + RefreshButton.Size = new Size(205, 29); + RefreshButton.TabIndex = 4; + RefreshButton.Text = "Обновить"; + RefreshButton.UseVisualStyleBackColor = true; + RefreshButton.Click += RefreshButton_Click; + // + // ImplementersForm + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(800, 450); + Controls.Add(RefreshButton); + Controls.Add(DeleteButton); + Controls.Add(ChangeButton); + Controls.Add(CreateButton); + Controls.Add(dataGridView1); + Name = "ImplementersForm"; + Text = "Исполнители"; + Load += ImplementersForm_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView1).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView1; + private Button CreateButton; + private Button ChangeButton; + private Button DeleteButton; + private Button RefreshButton; + } +} \ No newline at end of file diff --git a/TravelCompany/TravelCompany/ImplementersForm.cs b/TravelCompany/TravelCompany/ImplementersForm.cs new file mode 100644 index 0000000..bcef90a --- /dev/null +++ b/TravelCompany/TravelCompany/ImplementersForm.cs @@ -0,0 +1,125 @@ +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.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 TravelCompany.Forms +{ + public partial class ImplementersForm : Form + { + private readonly ILogger _logger; + private readonly IImplementerLogic _logic; + public ImplementersForm(ILogger logger, IImplementerLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + private void ImplementersForm_Load(object sender, EventArgs e) + { + LoadData(); + } + + private void LoadData() + { + try + { + var list = _logic.ReadList(null); + if (list != null) + { + dataGridView1.DataSource = list; + dataGridView1.Columns["Id"].Visible = false; + dataGridView1.Columns["ImplementerFIO"].AutoSizeMode = + DataGridViewAutoSizeColumnMode.Fill; + dataGridView1.Columns["Password"].AutoSizeMode = + DataGridViewAutoSizeColumnMode.Fill; + dataGridView1.Columns["Qualification"].AutoSizeMode = + DataGridViewAutoSizeColumnMode.Fill; + dataGridView1.Columns["WorkExperience"].AutoSizeMode = + DataGridViewAutoSizeColumnMode.Fill; + } + _logger.LogInformation("Загрузка компонентов"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки исполнителей"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + private void CreateButton_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(ImplementerForm)); + if (service is ImplementerForm form) + { + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + + private void ChangeButton_Click(object sender, EventArgs e) + { + if (dataGridView1.SelectedRows.Count == 1) + { + var service = + Program.ServiceProvider?.GetService(typeof(ImplementerForm)); + if (service is ImplementerForm form) + { + form.Id = + Convert.ToInt32(dataGridView1.SelectedRows[0].Cells["Id"].Value); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + } + + private void DeleteButton_Click(object sender, EventArgs e) + { + if (dataGridView1.SelectedRows.Count == 1) + { + if (MessageBox.Show("Удалить запись?", "Вопрос", + MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + int id = + Convert.ToInt32(dataGridView1.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 RefreshButton_Click(object sender, EventArgs e) + { + LoadData(); + } + } +} diff --git a/TravelCompany/TravelCompany/ImplementersForm.resx b/TravelCompany/TravelCompany/ImplementersForm.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/TravelCompany/TravelCompany/ImplementersForm.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/TravelCompany/TravelCompany/Program.cs b/TravelCompany/TravelCompany/Program.cs index d57b9c3..7c0b2fc 100644 --- a/TravelCompany/TravelCompany/Program.cs +++ b/TravelCompany/TravelCompany/Program.cs @@ -47,6 +47,9 @@ namespace TravelCompany.Forms services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -61,6 +64,8 @@ namespace TravelCompany.Forms services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); } } diff --git a/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/ImplementerLogic.cs b/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/ImplementerLogic.cs new file mode 100644 index 0000000..3232fd7 --- /dev/null +++ b/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/ImplementerLogic.cs @@ -0,0 +1,128 @@ +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.BusinessLogicsContracts; +using TravelCompanyContracts.SearchModels; +using TravelCompanyContracts.StoragesContracts; +using TravelCompanyContracts.ViewModels; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TravelCompanyBusinessLogic.BusinessLogic +{ + public class ImplementerLogic : IImplementerLogic + { + private readonly ILogger _logger; + private readonly IImplementerStorage _implementerStorage; + public ImplementerLogic(ILogger logger, IImplementerStorage + implementerStorage) + { + _logger = logger; + _implementerStorage = implementerStorage; + } + public List? ReadList(ImplementerSearchModel? model) + { + _logger.LogInformation("ReadList. ImplementerFIO:{ClientFIO}. 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 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 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 (string.IsNullOrEmpty(model.Password)) + { + throw new ArgumentNullException("Нет пароля клиента", + nameof(model.Password)); + } + if (model.WorkExperience < 0) + { + throw new ArgumentNullException("Стаж меньше 0", + nameof(model.WorkExperience)); + } + if (model.Qualification < 0) + { + throw new ArgumentException("Квалификация меньше 0", nameof(model.Qualification)); + } + _logger.LogInformation("Implementer. ImplementerFIO:{ImplementerFIO}." + + "Password:{ Password}. WorkExperience:{ WorkExperience}. Qualification:{ Qualification}. Id: { Id} ", + model.ImplementerFIO, model.Password, model.WorkExperience, model.Qualification, model.Id); + var element = _implementerStorage.GetElement(new ImplementerSearchModel + { + ImplementerFIO = model.ImplementerFIO, + }); + if (element != null && element.Id != model.Id) + { + throw new InvalidOperationException("Исполнитель с таким ФИО уже есть"); + } + } + } +} diff --git a/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/OrderLogic.cs b/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/OrderLogic.cs index e7c1295..66fe06b 100644 --- a/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/OrderLogic.cs +++ b/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/OrderLogic.cs @@ -15,12 +15,9 @@ namespace TravelCompanyBusinessLogic.BusinessLogic { public class OrderLogic : IOrderLogic { - //Класс с логикой для заказов будет отвечать за получение списка заказов, - //создания заказа и смены его статусов. Следует учитывать, что у заказа можно - //менять статус на новый, если его текущий статус предшествует новому - private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; + static readonly object locker = new object(); public OrderLogic(ILogger logger, IOrderStorage orderStorage) { @@ -28,6 +25,23 @@ namespace TravelCompanyBusinessLogic.BusinessLogic _orderStorage = orderStorage; } + public OrderViewModel? ReadElement(OrderSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + _logger.LogInformation("ReadElement. Id:{ Id}", 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 List? ReadList(OrderSearchModel? model) { _logger.LogInformation("ReadList. OrderId:{Id}", model?.Id); @@ -51,7 +65,6 @@ namespace TravelCompanyBusinessLogic.BusinessLogic if (_orderStorage.Insert(model) == null) { - model.Status = OrderStatus.Неизвестен; _logger.LogWarning("Insert operation failed"); return false; } @@ -60,7 +73,10 @@ namespace TravelCompanyBusinessLogic.BusinessLogic public bool TakeOrderInWork(OrderBindingModel model) { - return ToNextStatus(model, OrderStatus.Выполняется); + lock (locker) + { + return ToNextStatus(model, OrderStatus.Выполняется); + } } public bool FinishOrder(OrderBindingModel model) @@ -76,40 +92,22 @@ namespace TravelCompanyBusinessLogic.BusinessLogic public bool ToNextStatus(OrderBindingModel model, OrderStatus orderStatus) { CheckModel(model, false); - var element = _orderStorage.GetElement(new OrderSearchModel() - { - Id = model.Id - }); + var element = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id }); if (element == null) { - throw new ArgumentNullException(nameof(element)); - } - - model.TravelId = element.TravelId; - model.DateCreate = element.DateCreate; - model.DateImplement = element.DateImplement; - model.Status = element.Status; - model.Count = element.Count; - model.Sum = element.Sum; - - if (model.Status != orderStatus - 1) - { - _logger.LogWarning("Status update to " + orderStatus + " operation failed"); + _logger.LogWarning("Read operation failed"); return false; } + if (element.Status != orderStatus - 1) + { + _logger.LogWarning("Status change operation failed"); + throw new InvalidOperationException("Текущий статус заказа не может быть переведен в выбранный"); + } model.Status = orderStatus; - - if (model.Status == OrderStatus.Выдан) - { - model.DateImplement = DateTime.Now; - } - - if (_orderStorage.Update(model) == null) - { - model.Status--; - _logger.LogWarning("Changing status operation faled"); - return false; - } + if (model.Status == OrderStatus.Готов) model.DateImplement = DateTime.Now; + if (element.ImplementerId.HasValue) + model.ImplementerId = element.ImplementerId; + _orderStorage.Update(model); return true; } @@ -130,10 +128,6 @@ namespace TravelCompanyBusinessLogic.BusinessLogic if (model.Sum <= 0) { throw new ArgumentNullException("Цена заказа должна быть больше 0", nameof(model.Sum)); - } - if (model.DateImplement.HasValue && model.DateImplement < model.DateCreate) - { - throw new ArithmeticException($"Дата выдачи заказа {model.DateImplement} должна быть позже даты его создания {model.DateCreate}"); } _logger.LogInformation("Travel. TravelId:{TravelId}.Count:{Count}.Sum:{Sum}Id:{Id}", model.TravelId, model.Count, model.Sum, model.Id); } diff --git a/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/WorkModeling.cs b/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/WorkModeling.cs new file mode 100644 index 0000000..1efc64b --- /dev/null +++ b/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/WorkModeling.cs @@ -0,0 +1,145 @@ +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.BusinessLogicsContracts; +using TravelCompanyContracts.SearchModels; +using TravelCompanyContracts.ViewModels; +using TravelCompanyDataModels.Enums; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TravelCompanyBusinessLogic.BusinessLogic +{ + 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/TravelCompany/TravelCompanyContracts/BindingModels/ImplementerBindingModel.cs b/TravelCompany/TravelCompanyContracts/BindingModels/ImplementerBindingModel.cs new file mode 100644 index 0000000..d2055d0 --- /dev/null +++ b/TravelCompany/TravelCompanyContracts/BindingModels/ImplementerBindingModel.cs @@ -0,0 +1,18 @@ +using TravelCompanyDataModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TravelCompanyContracts.BindingModels +{ + public class ImplementerBindingModel : IImplementerModel + { + public int Id { get; set; } + public string ImplementerFIO { get; set; } = string.Empty; + public int WorkExperience { get; set; } = 0; + public int Qualification { get; set; } = 0; + public string Password { get; set; } = string.Empty; + } +} diff --git a/TravelCompany/TravelCompanyContracts/BindingModels/OrderBindingModel.cs b/TravelCompany/TravelCompanyContracts/BindingModels/OrderBindingModel.cs index 3fbeb01..d340402 100644 --- a/TravelCompany/TravelCompanyContracts/BindingModels/OrderBindingModel.cs +++ b/TravelCompany/TravelCompanyContracts/BindingModels/OrderBindingModel.cs @@ -12,6 +12,7 @@ namespace TravelCompanyContracts.BindingModels { public int Id { get; set; } public int TravelId { get; set; } + public int? ImplementerId { get; set; } = null; public int ClientId { get; set; } public int Count { get; set; } public double Sum { get; set; } diff --git a/TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IImplementerLogic.cs b/TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IImplementerLogic.cs new file mode 100644 index 0000000..e9a6623 --- /dev/null +++ b/TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IImplementerLogic.cs @@ -0,0 +1,20 @@ +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.SearchModels; +using TravelCompanyContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TravelCompanyContracts.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/TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IOrderLogic.cs b/TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IOrderLogic.cs index 03a4beb..ec93b44 100644 --- a/TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IOrderLogic.cs +++ b/TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IOrderLogic.cs @@ -12,19 +12,10 @@ namespace TravelCompanyContracts.BusinessLogicsContracts public interface IOrderLogic { List? ReadList(OrderSearchModel? model); + OrderViewModel? ReadElement(OrderSearchModel model); bool CreateOrder(OrderBindingModel model); bool TakeOrderInWork(OrderBindingModel model); - /// - /// Готов - /// - /// - /// bool FinishOrder(OrderBindingModel model); - /// - /// Доставлен - /// - /// - /// bool DeliveryOrder(OrderBindingModel model); } } diff --git a/TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IWorkProcess.cs b/TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IWorkProcess.cs new file mode 100644 index 0000000..adeedae --- /dev/null +++ b/TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IWorkProcess.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TravelCompanyContracts.BusinessLogicsContracts +{ + public interface IWorkProcess + { + void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic); + } +} diff --git a/TravelCompany/TravelCompanyContracts/SearchModels/ImplementerSearchModel.cs b/TravelCompany/TravelCompanyContracts/SearchModels/ImplementerSearchModel.cs new file mode 100644 index 0000000..8dbf2b4 --- /dev/null +++ b/TravelCompany/TravelCompanyContracts/SearchModels/ImplementerSearchModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TravelCompanyContracts.SearchModels +{ + public class ImplementerSearchModel + { + public int? Id { get; set; } + public string? ImplementerFIO { get; set; } = string.Empty; + public string? Password { get; set; } = string.Empty; + } +} diff --git a/TravelCompany/TravelCompanyContracts/SearchModels/OrderSearchModel.cs b/TravelCompany/TravelCompanyContracts/SearchModels/OrderSearchModel.cs index ffcf4c0..55c45ea 100644 --- a/TravelCompany/TravelCompanyContracts/SearchModels/OrderSearchModel.cs +++ b/TravelCompany/TravelCompanyContracts/SearchModels/OrderSearchModel.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using TravelCompanyDataModels.Enums; namespace TravelCompanyContracts.SearchModels { @@ -10,6 +11,8 @@ namespace TravelCompanyContracts.SearchModels { public int? Id { get; set; } public int? ClientId { get; set; } + public int? ImplementerId { get; set; } + public OrderStatus? Status { get; set; } public DateTime? DateFrom { get; set; } public DateTime? DateTo { get; set; } } diff --git a/TravelCompany/TravelCompanyContracts/StoragesContracts/IImplementerStorage.cs b/TravelCompany/TravelCompanyContracts/StoragesContracts/IImplementerStorage.cs new file mode 100644 index 0000000..3482d94 --- /dev/null +++ b/TravelCompany/TravelCompanyContracts/StoragesContracts/IImplementerStorage.cs @@ -0,0 +1,21 @@ +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.SearchModels; +using TravelCompanyContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TravelCompanyContracts.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/TravelCompany/TravelCompanyContracts/ViewModels/ImplementerViewModel.cs b/TravelCompany/TravelCompanyContracts/ViewModels/ImplementerViewModel.cs new file mode 100644 index 0000000..f4fa3a2 --- /dev/null +++ b/TravelCompany/TravelCompanyContracts/ViewModels/ImplementerViewModel.cs @@ -0,0 +1,23 @@ +using TravelCompanyDataModels; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TravelCompanyContracts.ViewModels +{ + public class ImplementerViewModel : IImplementerModel + { + public int Id { get; set; } + [DisplayName("ФИО исполнителя")] + public string ImplementerFIO { get; set; } = string.Empty; + [DisplayName("Стаж работы")] + public int WorkExperience { get; set; } = 0; + [DisplayName("Квалификация")] + public int Qualification { get; set; } = 0; + [DisplayName("Пароль")] + public string Password { get; set; } = string.Empty; + } +} diff --git a/TravelCompany/TravelCompanyContracts/ViewModels/OrderViewModel.cs b/TravelCompany/TravelCompanyContracts/ViewModels/OrderViewModel.cs index bc1f117..652ff88 100644 --- a/TravelCompany/TravelCompanyContracts/ViewModels/OrderViewModel.cs +++ b/TravelCompany/TravelCompanyContracts/ViewModels/OrderViewModel.cs @@ -18,10 +18,13 @@ namespace TravelCompanyContracts.ViewModels public int Id { get; set; } public int TravelId { get; set; } public int ClientId { get; set; } + public int? ImplementerId { get; set; } = null; [DisplayName("Клиент")] public string ClientFIO { get; set; } = string.Empty; [DisplayName("Путёвка")] public string TravelName { get; set; } = string.Empty; + [DisplayName("Исполнитель")] + public string ImplementerFIO { get; set; } = string.Empty; [DisplayName("Количество")] public int Count { get; set; } [DisplayName("Сумма")] diff --git a/TravelCompany/TravelCompanyDataModels/Models/IImplementerModel.cs b/TravelCompany/TravelCompanyDataModels/Models/IImplementerModel.cs new file mode 100644 index 0000000..28258f8 --- /dev/null +++ b/TravelCompany/TravelCompanyDataModels/Models/IImplementerModel.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TravelCompanyDataModels +{ + public interface IImplementerModel + { + string ImplementerFIO { get; } + string Password { get; } + int WorkExperience { get; } + int Qualification { get; } + + } +} diff --git a/TravelCompany/TravelCompanyDataModels/Models/IOrderModel.cs b/TravelCompany/TravelCompanyDataModels/Models/IOrderModel.cs index 5d9d8d9..a0bf921 100644 --- a/TravelCompany/TravelCompanyDataModels/Models/IOrderModel.cs +++ b/TravelCompany/TravelCompanyDataModels/Models/IOrderModel.cs @@ -6,6 +6,7 @@ namespace TravelCompanyDataModels.Models { int TravelId { get; } int ClientId { get; } + int? ImplementerId { get; } int Count { get; } double Sum { get; } OrderStatus Status { get; } diff --git a/TravelCompany/TravelCompanyDatabaseImplement/Implements/ImplementerStorage.cs b/TravelCompany/TravelCompanyDatabaseImplement/Implements/ImplementerStorage.cs new file mode 100644 index 0000000..e3a997d --- /dev/null +++ b/TravelCompany/TravelCompanyDatabaseImplement/Implements/ImplementerStorage.cs @@ -0,0 +1,87 @@ +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.SearchModels; +using TravelCompanyContracts.StoragesContracts; +using TravelCompanyContracts.ViewModels; +using TravelCompanyDatabaseImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TravelCompanyDatabaseImplement.Implements +{ + public class ImplementerStorage : IImplementerStorage + { + public ImplementerViewModel? Delete(ImplementerBindingModel model) + { + using var context = new TravelCompanyDataBase(); + var res = context.Implementers.FirstOrDefault(x => x.Id == model.Id); + if (res != null) + { + context.Implementers.Remove(res); + context.SaveChanges(); + } + return res?.GetViewModel; + } + + public ImplementerViewModel? GetElement(ImplementerSearchModel model) + { + if (string.IsNullOrEmpty(model.ImplementerFIO) && string.IsNullOrEmpty(model.Password) && + !model.Id.HasValue) + { + return null; + } + using var context = new TravelCompanyDataBase(); + return context.Implementers + .FirstOrDefault(x => (string.IsNullOrEmpty(model.ImplementerFIO) || x.ImplementerFIO == model.ImplementerFIO) && + (!model.Id.HasValue || x.Id == model.Id) && + (string.IsNullOrEmpty(model.Password) || x.Password == model.Password)) + ?.GetViewModel; + } + + public List GetFilteredList(ImplementerSearchModel model) + { + if (model == null) + { + return new(); + } + if (model.Id.HasValue) + { + var res = GetElement(model); + return res != null ? new() { res } : new(); + } + return new(); + } + + public List GetFullList() + { + using var context = new TravelCompanyDataBase(); + return context.Implementers.Select(x => x.GetViewModel).ToList(); + } + + public ImplementerViewModel? Insert(ImplementerBindingModel model) + { + using var context = new TravelCompanyDataBase(); + 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 TravelCompanyDataBase(); + var res = context.Implementers.FirstOrDefault(x => x.Id == model.Id); + if (res != null) + { + res.Update(model); + context.SaveChanges(); + } + return res?.GetViewModel; + } + } +} diff --git a/TravelCompany/TravelCompanyDatabaseImplement/Implements/OrderStorage.cs b/TravelCompany/TravelCompanyDatabaseImplement/Implements/OrderStorage.cs index 1bc439c..8852ec4 100644 --- a/TravelCompany/TravelCompanyDatabaseImplement/Implements/OrderStorage.cs +++ b/TravelCompany/TravelCompanyDatabaseImplement/Implements/OrderStorage.cs @@ -18,7 +18,7 @@ namespace TravelCompanyDatabaseImplement.Implements { using var context = new TravelCompanyDataBase(); return context.Orders.Include(x => x.Travel) - .Include(x => x.Client).Select(x => x.GetViewModel) + .Include(x => x.Client).Include(x => x.Implementer).Select(x => x.GetViewModel) .ToList(); } public List GetFilteredList(OrderSearchModel model) @@ -27,12 +27,14 @@ namespace TravelCompanyDatabaseImplement.Implements using var context = new TravelCompanyDataBase(); return context.Orders .Include(x => x.Travel) - .Include(x => x.Client).Where(x => ( + .Include(x => x.Client).Include(x => x.Implementer).Where(x => ( (!model.Id.HasValue || x.Id == model.Id) && (!model.DateFrom.HasValue || x.DateCreate >= model.DateFrom) && (!model.DateTo.HasValue || x.DateCreate <= model.DateTo) && (!model.ClientId.HasValue || x.ClientId == model.ClientId) + && + (!model.Status.HasValue || x.Status == model.Status) ) ) .Select(x => x.GetViewModel) @@ -40,12 +42,11 @@ namespace TravelCompanyDatabaseImplement.Implements } public OrderViewModel? GetElement(OrderSearchModel model) { - if (!model.Id.HasValue) - { - return null; - } using var context = new TravelCompanyDataBase(); - return context.Orders.Include(x => x.Travel).Include(x => x.Client).FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; + return context.Orders.Include(x => x.Travel).Include(x => x.Client).Include(x => x.Implementer).FirstOrDefault( + x => ((model.Id.HasValue && x.Id == model.Id) || + (model.ImplementerId.HasValue && model.Status.HasValue && + x.ImplementerId == model.ImplementerId && x.Status == model.Status)))?.GetViewModel; } public OrderViewModel? Insert(OrderBindingModel model) { @@ -62,7 +63,7 @@ namespace TravelCompanyDatabaseImplement.Implements public OrderViewModel? Update(OrderBindingModel model) { using var context = new TravelCompanyDataBase(); - var order = context.Orders.Include(x => x.Travel).Include(x => x.Client).FirstOrDefault(x => x.Id == + var order = context.Orders.Include(x => x.Travel).Include(x => x.Client).Include(x => x.Implementer).FirstOrDefault(x => x.Id == model.Id); if (order == null) { diff --git a/TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240418113410_InitialCreate.Designer.cs b/TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240502101530_Initial-Create.Designer.cs similarity index 82% rename from TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240418113410_InitialCreate.Designer.cs rename to TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240502101530_Initial-Create.Designer.cs index be15232..a605010 100644 --- a/TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240418113410_InitialCreate.Designer.cs +++ b/TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240502101530_Initial-Create.Designer.cs @@ -12,7 +12,7 @@ using TravelCompanyDatabaseImplement; namespace TravelCompanyDatabaseImplement.Migrations { [DbContext(typeof(TravelCompanyDataBase))] - [Migration("20240418113410_InitialCreate")] + [Migration("20240502101530_Initial-Create")] partial class InitialCreate { /// @@ -70,6 +70,33 @@ namespace TravelCompanyDatabaseImplement.Migrations b.ToTable("Components"); }); + modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.Implementer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ImplementerFIO") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Password") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Qualification") + .HasColumnType("int"); + + b.Property("WorkExperience") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.ToTable("Implementers"); + }); + modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -90,6 +117,9 @@ namespace TravelCompanyDatabaseImplement.Migrations b.Property("DateImplement") .HasColumnType("datetime2"); + b.Property("ImplementerId") + .HasColumnType("int"); + b.Property("Status") .HasColumnType("int"); @@ -103,6 +133,8 @@ namespace TravelCompanyDatabaseImplement.Migrations b.HasIndex("ClientId"); + b.HasIndex("ImplementerId"); + b.HasIndex("TravelId"); b.ToTable("Orders"); @@ -162,6 +194,10 @@ namespace TravelCompanyDatabaseImplement.Migrations .OnDelete(DeleteBehavior.Cascade) .IsRequired(); + b.HasOne("TravelCompanyDatabaseImplement.Models.Implementer", "Implementer") + .WithMany("Orders") + .HasForeignKey("ImplementerId"); + b.HasOne("TravelCompanyDatabaseImplement.Models.Travel", "Travel") .WithMany("Orders") .HasForeignKey("TravelId") @@ -170,6 +206,8 @@ namespace TravelCompanyDatabaseImplement.Migrations b.Navigation("Client"); + b.Navigation("Implementer"); + b.Navigation("Travel"); }); @@ -202,6 +240,11 @@ namespace TravelCompanyDatabaseImplement.Migrations b.Navigation("TravelComponents"); }); + modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.Implementer", b => + { + b.Navigation("Orders"); + }); + modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.Travel", b => { b.Navigation("Components"); diff --git a/TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240418113410_InitialCreate.cs b/TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240502101530_Initial-Create.cs similarity index 81% rename from TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240418113410_InitialCreate.cs rename to TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240502101530_Initial-Create.cs index b9f0297..16190d0 100644 --- a/TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240418113410_InitialCreate.cs +++ b/TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240502101530_Initial-Create.cs @@ -40,6 +40,22 @@ namespace TravelCompanyDatabaseImplement.Migrations table.PrimaryKey("PK_Components", x => x.Id); }); + migrationBuilder.CreateTable( + name: "Implementers", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + ImplementerFIO = table.Column(type: "nvarchar(max)", nullable: false), + Password = table.Column(type: "nvarchar(max)", nullable: false), + Qualification = table.Column(type: "int", nullable: false), + WorkExperience = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Implementers", x => x.Id); + }); + migrationBuilder.CreateTable( name: "Travels", columns: table => new @@ -66,7 +82,8 @@ namespace TravelCompanyDatabaseImplement.Migrations DateCreate = table.Column(type: "datetime2", nullable: false), DateImplement = table.Column(type: "datetime2", nullable: true), TravelId = table.Column(type: "int", nullable: false), - ClientId = table.Column(type: "int", nullable: false) + ClientId = table.Column(type: "int", nullable: false), + ImplementerId = table.Column(type: "int", nullable: true) }, constraints: table => { @@ -77,6 +94,11 @@ namespace TravelCompanyDatabaseImplement.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_Travels_TravelId", column: x => x.TravelId, @@ -117,6 +139,11 @@ namespace TravelCompanyDatabaseImplement.Migrations table: "Orders", column: "ClientId"); + migrationBuilder.CreateIndex( + name: "IX_Orders_ImplementerId", + table: "Orders", + column: "ImplementerId"); + migrationBuilder.CreateIndex( name: "IX_Orders_TravelId", table: "Orders", @@ -145,6 +172,9 @@ namespace TravelCompanyDatabaseImplement.Migrations migrationBuilder.DropTable( name: "Clients"); + migrationBuilder.DropTable( + name: "Implementers"); + migrationBuilder.DropTable( name: "Components"); diff --git a/TravelCompany/TravelCompanyDatabaseImplement/Migrations/TravelCompanyDataBaseModelSnapshot.cs b/TravelCompany/TravelCompanyDatabaseImplement/Migrations/TravelCompanyDataBaseModelSnapshot.cs index e5b8916..47ece42 100644 --- a/TravelCompany/TravelCompanyDatabaseImplement/Migrations/TravelCompanyDataBaseModelSnapshot.cs +++ b/TravelCompany/TravelCompanyDatabaseImplement/Migrations/TravelCompanyDataBaseModelSnapshot.cs @@ -67,6 +67,33 @@ namespace TravelCompanyDatabaseImplement.Migrations b.ToTable("Components"); }); + modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.Implementer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ImplementerFIO") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Password") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Qualification") + .HasColumnType("int"); + + b.Property("WorkExperience") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.ToTable("Implementers"); + }); + modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -87,6 +114,9 @@ namespace TravelCompanyDatabaseImplement.Migrations b.Property("DateImplement") .HasColumnType("datetime2"); + b.Property("ImplementerId") + .HasColumnType("int"); + b.Property("Status") .HasColumnType("int"); @@ -100,6 +130,8 @@ namespace TravelCompanyDatabaseImplement.Migrations b.HasIndex("ClientId"); + b.HasIndex("ImplementerId"); + b.HasIndex("TravelId"); b.ToTable("Orders"); @@ -159,6 +191,10 @@ namespace TravelCompanyDatabaseImplement.Migrations .OnDelete(DeleteBehavior.Cascade) .IsRequired(); + b.HasOne("TravelCompanyDatabaseImplement.Models.Implementer", "Implementer") + .WithMany("Orders") + .HasForeignKey("ImplementerId"); + b.HasOne("TravelCompanyDatabaseImplement.Models.Travel", "Travel") .WithMany("Orders") .HasForeignKey("TravelId") @@ -167,6 +203,8 @@ namespace TravelCompanyDatabaseImplement.Migrations b.Navigation("Client"); + b.Navigation("Implementer"); + b.Navigation("Travel"); }); @@ -199,6 +237,11 @@ namespace TravelCompanyDatabaseImplement.Migrations b.Navigation("TravelComponents"); }); + modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.Implementer", b => + { + b.Navigation("Orders"); + }); + modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.Travel", b => { b.Navigation("Components"); diff --git a/TravelCompany/TravelCompanyDatabaseImplement/Models/Implementer.cs b/TravelCompany/TravelCompanyDatabaseImplement/Models/Implementer.cs new file mode 100644 index 0000000..246f216 --- /dev/null +++ b/TravelCompany/TravelCompanyDatabaseImplement/Models/Implementer.cs @@ -0,0 +1,65 @@ +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.ViewModels; +using TravelCompanyDataModels; +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 TravelCompanyDatabaseImplement.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; set; } = string.Empty; + [Required] + public int Qualification { get; set; } = 0; + [Required] + public int WorkExperience { get; set; } = 0; + [ForeignKey("ImplementerId")] + public virtual List Orders { get; set; } = + new(); + public static Implementer? Create(ImplementerBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Id = model.Id, + Password = model.Password, + Qualification = model.Qualification, + ImplementerFIO = model.ImplementerFIO, + WorkExperience = model.WorkExperience, + }; + } + + public void Update(ImplementerBindingModel model) + { + if (model == null) + { + return; + } + Password = model.Password; + Qualification = model.Qualification; + ImplementerFIO = model.ImplementerFIO; + WorkExperience = model.WorkExperience; + } + + public ImplementerViewModel GetViewModel => new() + { + Id = Id, + Password = Password, + Qualification = Qualification, + ImplementerFIO = ImplementerFIO, + WorkExperience = WorkExperience, + }; + } +} diff --git a/TravelCompany/TravelCompanyDatabaseImplement/Models/Order.cs b/TravelCompany/TravelCompanyDatabaseImplement/Models/Order.cs index 837eedc..bc0085c 100644 --- a/TravelCompany/TravelCompanyDatabaseImplement/Models/Order.cs +++ b/TravelCompany/TravelCompanyDatabaseImplement/Models/Order.cs @@ -26,6 +26,8 @@ namespace TravelCompanyDatabaseImplement.Models [Required] public int ClientId { get; private set; } public virtual Client Client { get; private set; } + public int? ImplementerId { get; private set; } = null; + public virtual Implementer? Implementer { get; private set; } public static Order? Create(TravelCompanyDataBase context, OrderBindingModel model) { if (model == null) @@ -44,6 +46,9 @@ namespace TravelCompanyDatabaseImplement.Models Travel = context.Travels.FirstOrDefault(x => x.Id == model.TravelId), ClientId = model.ClientId, Client = context.Clients.FirstOrDefault(x => x.Id == model.ClientId), + ImplementerId = model.ImplementerId, + Implementer = (model.ImplementerId.HasValue ? context.Implementers.FirstOrDefault(x => x.Id == model.ImplementerId) + : null), }; } @@ -55,12 +60,14 @@ namespace TravelCompanyDatabaseImplement.Models } Status = model.Status; DateImplement = model.DateImplement; + ImplementerId = model.ImplementerId; } public OrderViewModel GetViewModel => new() { TravelId = TravelId, ClientId = ClientId, + ImplementerId = ImplementerId, Count = Count, Sum = Sum, Status = Status, @@ -68,7 +75,9 @@ namespace TravelCompanyDatabaseImplement.Models DateImplement = DateImplement, TravelName = Travel.TravelName, Id = Id, - ClientFIO = Client.ClientFIO + ClientFIO = Client.ClientFIO, + ImplementerFIO = (Implementer != null ? Implementer.ImplementerFIO : string.Empty) + }; } diff --git a/TravelCompany/TravelCompanyDatabaseImplement/TravelCompanyDataBase.cs b/TravelCompany/TravelCompanyDatabaseImplement/TravelCompanyDataBase.cs index 644f731..eca8a18 100644 --- a/TravelCompany/TravelCompanyDatabaseImplement/TravelCompanyDataBase.cs +++ b/TravelCompany/TravelCompanyDatabaseImplement/TravelCompanyDataBase.cs @@ -16,7 +16,7 @@ optionsBuilder) { if (optionsBuilder.IsConfigured == false) { - optionsBuilder.UseSqlServer(@"Data Source=DESKTOP-D5A5OOG\GOLDFEST;Initial Catalog=TravelCompanyDatabase;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True"); + optionsBuilder.UseSqlServer(@"Data Source=DESKTOP-D5A5OOG\GOLDFEST;Initial Catalog=TravelCompanyDatabase1;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True"); } base.OnConfiguring(optionsBuilder); } @@ -25,6 +25,7 @@ optionsBuilder) public virtual DbSet TravelComponents { set; get; } public virtual DbSet Orders { set; get; } public virtual DbSet Clients { set; get; } + public virtual DbSet Implementers { set; get; } } } diff --git a/TravelCompany/TravelCompanyFileImplement/DataFileSingleton.cs b/TravelCompany/TravelCompanyFileImplement/DataFileSingleton.cs index f7e2376..34021a5 100644 --- a/TravelCompany/TravelCompanyFileImplement/DataFileSingleton.cs +++ b/TravelCompany/TravelCompanyFileImplement/DataFileSingleton.cs @@ -15,10 +15,14 @@ namespace TravelCompanyFileImplement private readonly string OrderFileName = "Order.xml"; private readonly string TravelFileName = "Travel.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 Travels { get; private set; } public List Clients { get; private set; } + public List Implementers { get; private set; } + public static DataFileSingleton GetInstance() { if (instance == null) @@ -32,6 +36,8 @@ namespace TravelCompanyFileImplement 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)!)!; @@ -39,6 +45,8 @@ namespace TravelCompanyFileImplement 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/TravelCompany/TravelCompanyFileImplement/Implements/ImplementerStorage.cs b/TravelCompany/TravelCompanyFileImplement/Implements/ImplementerStorage.cs new file mode 100644 index 0000000..11cc796 --- /dev/null +++ b/TravelCompany/TravelCompanyFileImplement/Implements/ImplementerStorage.cs @@ -0,0 +1,83 @@ +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.SearchModels; +using TravelCompanyContracts.StoragesContracts; +using TravelCompanyContracts.ViewModels; +using TravelCompanyFileImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TravelCompanyFileImplement.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) && string.IsNullOrEmpty(model.Password)) + { + return new(); + } + return source.Implementers + .Where(x => (string.IsNullOrEmpty(model.ImplementerFIO) || x.ImplementerFIO.Contains(model.ImplementerFIO)) && + (string.IsNullOrEmpty(model.Password) || x.Password.Contains(model.Password))) + .Select(x => x.GetViewModel) + .ToList(); + } + public ImplementerViewModel? GetElement(ImplementerSearchModel model) + { + return source.Implementers + .FirstOrDefault(x => (string.IsNullOrEmpty(model.ImplementerFIO) || x.ImplementerFIO == model.ImplementerFIO) && + (!model.Id.HasValue || x.Id == model.Id) && (string.IsNullOrEmpty(model.Password) || x.Password == model.Password)) + ?.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 implementer = source.Implementers.FirstOrDefault(x => x.Id == model.Id); + if (implementer == null) + { + return null; + } + implementer.Update(model); + source.SaveImplementers(); + return implementer.GetViewModel; + } + public ImplementerViewModel? Delete(ImplementerBindingModel model) + { + var element = source.Implementers.FirstOrDefault(rec => rec.Id == model.Id); + if (element != null) + { + source.Implementers.Remove(element); + source.SaveImplementers(); + return element.GetViewModel; + } + return null; + } + } +} diff --git a/TravelCompany/TravelCompanyFileImplement/Models/Implementer.cs b/TravelCompany/TravelCompanyFileImplement/Models/Implementer.cs new file mode 100644 index 0000000..f08719d --- /dev/null +++ b/TravelCompany/TravelCompanyFileImplement/Models/Implementer.cs @@ -0,0 +1,78 @@ +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.ViewModels; +using TravelCompanyDataModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace TravelCompanyFileImplement.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 Qualification { get; set; } = 0; + public int WorkExperience { get; set; } = 0; + 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 + }; + 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, + Qualification = Convert.ToInt32(element.Element("Qualification")!.Value), + WorkExperience = Convert.ToInt32(element.Element("WorkExperience")!.Value) + }; + } + + public XElement GetXElement => new("Implementer", + new XAttribute("Id", Id), + new XElement("ImplementerFIO", ImplementerFIO), + new XElement("Password", Password), + new XElement("Qualification", Qualification.ToString()), + new XElement("WorkExperience", WorkExperience.ToString()) + ); + } +} diff --git a/TravelCompany/TravelCompanyFileImplement/Models/Order.cs b/TravelCompany/TravelCompanyFileImplement/Models/Order.cs index e5a5ceb..1bfed3e 100644 --- a/TravelCompany/TravelCompanyFileImplement/Models/Order.cs +++ b/TravelCompany/TravelCompanyFileImplement/Models/Order.cs @@ -15,7 +15,7 @@ namespace TravelCompanyFileImplement.Models { public int TravelId { get; private set; } public int ClientId { get; private set; } - + public int? ImplementerId { get; private set; } = null; public int Count { get; private set; } public double Sum { get; private set; } @@ -43,7 +43,9 @@ namespace TravelCompanyFileImplement.Models Sum = model.Sum, Status = model.Status, DateCreate = model.DateCreate, - DateImplement = model.DateImplement + DateImplement = model.DateImplement, + ImplementerId = model.ImplementerId, + }; } @@ -58,6 +60,7 @@ namespace TravelCompanyFileImplement.Models Id = Convert.ToInt32(element.Attribute("Id")!.Value), TravelId = Convert.ToInt32(element.Element("TravelId")!.Value), ClientId = Convert.ToInt32(element.Element("ClientId")!.Value), + ImplementerId = Convert.ToInt32(element.Element("ImplementerId")!.Value), Count = Convert.ToInt32(element.Element("Count")!.Value), Sum = Convert.ToDouble(element.Element("Sum")!.Value), Status = (OrderStatus)Enum.Parse(typeof(OrderStatus), element.Element("Status")!.Value.ToString()), @@ -81,6 +84,7 @@ namespace TravelCompanyFileImplement.Models Id = Id, TravelId = TravelId, ClientId = ClientId, + ImplementerId = ImplementerId, Count = Count, Sum = Sum, Status = Status, diff --git a/TravelCompany/TravelCompanyListImplement/DataListSingleton.cs b/TravelCompany/TravelCompanyListImplement/DataListSingleton.cs index 50570c7..fff14df 100644 --- a/TravelCompany/TravelCompanyListImplement/DataListSingleton.cs +++ b/TravelCompany/TravelCompanyListImplement/DataListSingleton.cs @@ -14,12 +14,16 @@ namespace TravelCompanyListImplement public List Orders { get; set; } public List Travels { get; set; } public List Clients { get; set; } + public List Implementers { get; set; } + private DataListSingleton() { Components = new List(); Orders = new List(); Travels = new List(); - Clients = new List(); + Clients = new List(); + Implementers = new List(); + } public static DataListSingleton GetInstance() { diff --git a/TravelCompany/TravelCompanyListImplement/Implements/ImplementerStorage.cs b/TravelCompany/TravelCompanyListImplement/Implements/ImplementerStorage.cs new file mode 100644 index 0000000..2eab68c --- /dev/null +++ b/TravelCompany/TravelCompanyListImplement/Implements/ImplementerStorage.cs @@ -0,0 +1,103 @@ +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.SearchModels; +using TravelCompanyContracts.StoragesContracts; +using TravelCompanyContracts.ViewModels; +using TravelCompanyListImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TravelCompanyListImplement.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) && string.IsNullOrEmpty(model.Password)) + { + 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) + { + foreach (var implementer in _source.Implementers) + { + if ((string.IsNullOrEmpty(model.ImplementerFIO) || implementer.ImplementerFIO == model.ImplementerFIO) && + (!model.Id.HasValue || implementer.Id == model.Id) && (string.IsNullOrEmpty(model.Password) || implementer.Password == model.Password)) + { + 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 (model.Id == implementer.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/TravelCompany/TravelCompanyListImplement/Implements/OrderStorage.cs b/TravelCompany/TravelCompanyListImplement/Implements/OrderStorage.cs index f02deba..2eec3a7 100644 --- a/TravelCompany/TravelCompanyListImplement/Implements/OrderStorage.cs +++ b/TravelCompany/TravelCompanyListImplement/Implements/OrderStorage.cs @@ -23,7 +23,7 @@ namespace TravelCompanyListImplement.Implements var result = new List(); foreach (var order in _source.Orders) { - result.Add(AccessTravelStorage(order.GetViewModel)); + result.Add(AccessStorage(order.GetViewModel)); } return result; } @@ -38,7 +38,7 @@ namespace TravelCompanyListImplement.Implements (!model.DateTo.HasValue || order.DateCreate <= model.DateTo) && (!model.ClientId.HasValue || order.ClientId == model.ClientId)) ; { - result.Add(AccessTravelStorage(order.GetViewModel)); + result.Add(AccessStorage(order.GetViewModel)); } } return result; @@ -51,9 +51,11 @@ namespace TravelCompanyListImplement.Implements } foreach (var order in _source.Orders) { - if (model.Id.HasValue && order.Id == model.Id) + if ((model.Id.HasValue && order.Id == model.Id) || + (model.ImplementerId.HasValue && model.Status.HasValue && + order.ImplementerId == model.ImplementerId && order.Status == model.Status)) { - return order.GetViewModel; + return AccessStorage(order.GetViewModel); } } return null; @@ -102,28 +104,22 @@ namespace TravelCompanyListImplement.Implements return null; } - public OrderViewModel AccessTravelStorage(OrderViewModel model) + public OrderViewModel AccessStorage(OrderViewModel model) { - foreach (var Travel in _source.Travels) - { - if (Travel.Id == model.TravelId) - { - model.TravelName = Travel.TravelName; - break; - } - } - return model; - } - - public OrderViewModel AccessClientStorage(OrderViewModel model) - { - var client = _source.Clients.FirstOrDefault(x => x.Id == model.ClientId); + if (model == null) + return null; + var travel = _source.Travels.FirstOrDefault(x => x.Id == model.Id); + var client = _source.Clients.FirstOrDefault(x => x.Id == model.Id); + var implementer = _source.Implementers.FirstOrDefault(x => x.Id == model.ImplementerId); + if (travel != null) + model.TravelName = travel.TravelName; if (client != null) model.ClientFIO = client.ClientFIO; + if (implementer != null) + model.ImplementerFIO = implementer.ImplementerFIO; return model; } - } } diff --git a/TravelCompany/TravelCompanyListImplement/Models/Implementer.cs b/TravelCompany/TravelCompanyListImplement/Models/Implementer.cs new file mode 100644 index 0000000..90d2364 --- /dev/null +++ b/TravelCompany/TravelCompanyListImplement/Models/Implementer.cs @@ -0,0 +1,54 @@ +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.ViewModels; +using TravelCompanyDataModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TravelCompanyListImplement.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; } = 0; + public int Qualification { get; set; } = 0; + 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/TravelCompany/TravelCompanyListImplement/Models/Order.cs b/TravelCompany/TravelCompanyListImplement/Models/Order.cs index f97a641..2a4ecdc 100644 --- a/TravelCompany/TravelCompanyListImplement/Models/Order.cs +++ b/TravelCompany/TravelCompanyListImplement/Models/Order.cs @@ -16,6 +16,7 @@ namespace TravelCompanyListImplement.Models public int Id { get; private set; } public int TravelId { get; private set; } public int ClientId { 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; } @@ -37,6 +38,7 @@ namespace TravelCompanyListImplement.Models Status = model.Status, DateCreate = model.DateCreate, DateImplement = model.DateImplement, + ImplementerId = model.ImplementerId }; } public void Update(OrderBindingModel? model) @@ -52,12 +54,14 @@ namespace TravelCompanyListImplement.Models Status = model.Status; DateCreate = model.DateCreate; DateImplement = model.DateImplement; + ImplementerId = model.ImplementerId; } public OrderViewModel GetViewModel => new() { Id = Id, TravelId = TravelId, ClientId = ClientId, + ImplementerId = ImplementerId, Count = Count, Sum = Sum, Status = Status, diff --git a/TravelCompany/TravelCompanyRestApi/Controllers/ImplementerController.cs b/TravelCompany/TravelCompanyRestApi/Controllers/ImplementerController.cs new file mode 100644 index 0000000..096657d --- /dev/null +++ b/TravelCompany/TravelCompanyRestApi/Controllers/ImplementerController.cs @@ -0,0 +1,105 @@ +using DocumentFormat.OpenXml.Office2010.Excel; +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.BusinessLogicsContracts; +using TravelCompanyContracts.SearchModels; +using TravelCompanyContracts.ViewModels; +using TravelCompanyDataModels.Enums; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; + +namespace TravelCompanyRestApi.Controllers +{ + [Route("api/[controller]/[action]")] + [ApiController] + public class ImplementerController : ControllerBase + { + 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; + } + } + } +} -- 2.25.1 From e47a130624c6e6195d53ab4cd34fabe1f844be74 Mon Sep 17 00:00:00 2001 From: goldfest Date: Thu, 2 May 2024 15:03:43 +0400 Subject: [PATCH 4/4] =?UTF-8?q?=D0=BF=D0=BE=D0=B4=D1=80=D0=B5=D0=B4=D0=B0?= =?UTF-8?q?=D0=BA=D1=82=D0=B8=D1=80=D0=BE=D0=B2=D0=B0=D0=BB=20fileImplemen?= =?UTF-8?q?t?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Implements/OrderStorage.cs | 42 +++++++++---------- 1 file changed, 19 insertions(+), 23 deletions(-) diff --git a/TravelCompany/TravelCompanyFileImplement/Implements/OrderStorage.cs b/TravelCompany/TravelCompanyFileImplement/Implements/OrderStorage.cs index 8ea5ea9..bd65bc6 100644 --- a/TravelCompany/TravelCompanyFileImplement/Implements/OrderStorage.cs +++ b/TravelCompany/TravelCompanyFileImplement/Implements/OrderStorage.cs @@ -22,7 +22,7 @@ namespace TravelCompanyFileImplement.Implements public List GetFullList() { return source.Orders - .Select(x => AccessTravelStorage(x.GetViewModel)) + .Select(x => AccessStorage(x.GetViewModel)) .ToList(); } @@ -36,9 +36,11 @@ model) (!model.DateTo.HasValue || x.DateCreate <= model.DateTo) && (!model.ClientId.HasValue || x.ClientId == model.ClientId) + && + (!model.Status.HasValue || x.Status == model.Status) ) ) - .Select(x => AccessTravelStorage(x.GetViewModel)) + .Select(x => AccessStorage(x.GetViewModel)) .ToList(); } @@ -48,8 +50,11 @@ model) { return null; } - return AccessTravelStorage(source.Orders - .FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))?.GetViewModel); + return AccessStorage(source.Orders + .FirstOrDefault( + x => ((model.Id.HasValue && x.Id == model.Id) || + (model.ImplementerId.HasValue && model.Status.HasValue && + x.ImplementerId == model.ImplementerId && x.Status == model.Status)))?.GetViewModel); } public OrderViewModel? Insert(OrderBindingModel model) @@ -62,7 +67,7 @@ model) } source.Orders.Add(newOrder); source.SaveOrders(); - return AccessTravelStorage(newOrder.GetViewModel); + return AccessStorage(newOrder.GetViewModel); } public OrderViewModel? Update(OrderBindingModel model) @@ -74,7 +79,7 @@ model) } order.Update(model); source.SaveOrders(); - return AccessTravelStorage(order.GetViewModel); + return AccessStorage(order.GetViewModel); } public OrderViewModel? Delete(OrderBindingModel model) { @@ -84,33 +89,24 @@ model) { source.Orders.Remove(element); source.SaveOrders(); - return AccessTravelStorage(element.GetViewModel); + return AccessStorage(element.GetViewModel); } return null; } - public OrderViewModel AccessTravelStorage(OrderViewModel model) - { - if (model == null) - return null; - foreach (var Travel in source.Travels) - { - if (Travel.Id == model.TravelId) - { - model.TravelName = Travel.TravelName; - break; - } - } - return model; - } - - public OrderViewModel AccessClientStorage(OrderViewModel model) + public OrderViewModel AccessStorage(OrderViewModel model) { if (model == null) return null; + var iceCream = source.Travels.FirstOrDefault(x => x.Id == model.Id); var client = source.Clients.FirstOrDefault(x => x.Id == model.Id); + var implementer = source.Implementers.FirstOrDefault(x => x.Id == model.ImplementerId); + if (iceCream != null) + model.TravelName = iceCream.TravelName; if (client != null) model.ClientFIO = client.ClientFIO; + if (implementer != null) + model.ImplementerFIO = implementer.ImplementerFIO; return model; } } -- 2.25.1