Лабораторная шесть. До миграции: переделаны Order и его методы + добавлены формы + ImplementerController в web-клиенте.

This commit is contained in:
ksenianeva 2023-05-15 02:51:05 +04:00
parent 383bdaac36
commit ebae5db13a
27 changed files with 1210 additions and 54 deletions

View File

@ -0,0 +1,173 @@
namespace TravelCompany
{
partial class FormImplementer
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.textBoxPassword = new System.Windows.Forms.TextBox();
this.textBoxFIO = new System.Windows.Forms.TextBox();
this.labelPassword = new System.Windows.Forms.Label();
this.labelFIO = new System.Windows.Forms.Label();
this.buttonCancel = new System.Windows.Forms.Button();
this.buttonSave = new System.Windows.Forms.Button();
this.textBoxQualification = new System.Windows.Forms.TextBox();
this.textBoxWorkExperience = new System.Windows.Forms.TextBox();
this.labelQualification = new System.Windows.Forms.Label();
this.labelWorkExpirience = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// textBoxPassword
//
this.textBoxPassword.Location = new System.Drawing.Point(122, 57);
this.textBoxPassword.Margin = new System.Windows.Forms.Padding(2);
this.textBoxPassword.Name = "textBoxPassword";
this.textBoxPassword.Size = new System.Drawing.Size(381, 27);
this.textBoxPassword.TabIndex = 9;
//
// textBoxFIO
//
this.textBoxFIO.Location = new System.Drawing.Point(122, 11);
this.textBoxFIO.Margin = new System.Windows.Forms.Padding(2);
this.textBoxFIO.Name = "textBoxFIO";
this.textBoxFIO.Size = new System.Drawing.Size(381, 27);
this.textBoxFIO.TabIndex = 8;
//
// labelPassword
//
this.labelPassword.AutoSize = true;
this.labelPassword.Location = new System.Drawing.Point(56, 57);
this.labelPassword.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.labelPassword.Name = "labelPassword";
this.labelPassword.Size = new System.Drawing.Size(62, 20);
this.labelPassword.TabIndex = 7;
this.labelPassword.Text = "Пароль";
//
// labelFIO
//
this.labelFIO.AutoSize = true;
this.labelFIO.Location = new System.Drawing.Point(76, 14);
this.labelFIO.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.labelFIO.Name = "labelFIO";
this.labelFIO.Size = new System.Drawing.Size(42, 20);
this.labelFIO.TabIndex = 6;
this.labelFIO.Text = "ФИО";
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(413, 189);
this.buttonCancel.Margin = new System.Windows.Forms.Padding(2);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(90, 27);
this.buttonCancel.TabIndex = 11;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(297, 189);
this.buttonSave.Margin = new System.Windows.Forms.Padding(2);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(112, 27);
this.buttonSave.TabIndex = 10;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.buttonSave_Click);
//
// textBoxQualification
//
this.textBoxQualification.Location = new System.Drawing.Point(122, 141);
this.textBoxQualification.Margin = new System.Windows.Forms.Padding(2);
this.textBoxQualification.Name = "textBoxQualification";
this.textBoxQualification.Size = new System.Drawing.Size(381, 27);
this.textBoxQualification.TabIndex = 15;
//
// textBoxWorkExperience
//
this.textBoxWorkExperience.Location = new System.Drawing.Point(122, 98);
this.textBoxWorkExperience.Margin = new System.Windows.Forms.Padding(2);
this.textBoxWorkExperience.Name = "textBoxWorkExperience";
this.textBoxWorkExperience.Size = new System.Drawing.Size(381, 27);
this.textBoxWorkExperience.TabIndex = 14;
//
// labelQualification
//
this.labelQualification.AutoSize = true;
this.labelQualification.Location = new System.Drawing.Point(7, 141);
this.labelQualification.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.labelQualification.Name = "labelQualification";
this.labelQualification.Size = new System.Drawing.Size(111, 20);
this.labelQualification.TabIndex = 13;
this.labelQualification.Text = "Квалификация";
//
// labelWorkExpirience
//
this.labelWorkExpirience.AutoSize = true;
this.labelWorkExpirience.Location = new System.Drawing.Point(72, 98);
this.labelWorkExpirience.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.labelWorkExpirience.Name = "labelWorkExpirience";
this.labelWorkExpirience.Size = new System.Drawing.Size(46, 20);
this.labelWorkExpirience.TabIndex = 12;
this.labelWorkExpirience.Text = "Опыт";
//
// FormImplementer
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(514, 227);
this.Controls.Add(this.textBoxQualification);
this.Controls.Add(this.textBoxWorkExperience);
this.Controls.Add(this.labelQualification);
this.Controls.Add(this.labelWorkExpirience);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.textBoxPassword);
this.Controls.Add(this.textBoxFIO);
this.Controls.Add(this.labelPassword);
this.Controls.Add(this.labelFIO);
this.Name = "FormImplementer";
this.Text = "Исполнитель";
this.Load += new System.EventHandler(this.FormImplementer_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private TextBox textBoxPassword;
private TextBox textBoxFIO;
private Label labelPassword;
private Label labelFIO;
private Button buttonCancel;
private Button buttonSave;
private TextBox textBoxQualification;
private TextBox textBoxWorkExperience;
private Label labelQualification;
private Label labelWorkExpirience;
}
}

View File

@ -0,0 +1,109 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TravelCompanyContracts.SearchModels;
using Microsoft.Extensions.Logging;
using TravelCompanyContracts.BusinessLogicsContracts;
using TravelCompanyContracts.BindingModels;
namespace TravelCompany
{
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<FormImplementer> 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;
textBoxWorkExperience.Text = view.WorkExperience.ToString();
textBoxQualification.Text = view.Qualification.ToString();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения компонента");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void buttonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxFIO.Text))
{
MessageBox.Show("Заполните ФИО", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxPassword.Text))
{
MessageBox.Show("Заполните пароль", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxWorkExperience.Text))
{
MessageBox.Show("Заполните опыт работы", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxQualification.Text))
{
MessageBox.Show("Заполните опыт квалификацию", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение исполнителя");
try
{
var model = new ImplementerBindingModel
{
Id = _id ?? 0,
ImplementerFIO = textBoxFIO.Text,
Password = textBoxPassword.Text,
WorkExperience = Convert.ToInt32(textBoxWorkExperience.Text),
Qualification = Convert.ToInt32(textBoxQualification.Text)
};
var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model);
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения исполнителя");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,124 @@
namespace TravelCompany
{
partial class FormImplementers
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
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();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
//
// buttonRef
//
this.buttonRef.Location = new System.Drawing.Point(552, 196);
this.buttonRef.Margin = new System.Windows.Forms.Padding(2);
this.buttonRef.Name = "buttonRef";
this.buttonRef.Size = new System.Drawing.Size(90, 27);
this.buttonRef.TabIndex = 9;
this.buttonRef.Text = "Обновить";
this.buttonRef.UseVisualStyleBackColor = true;
this.buttonRef.Click += new System.EventHandler(this.buttonRef_Click);
//
// buttonDel
//
this.buttonDel.Location = new System.Drawing.Point(552, 129);
this.buttonDel.Margin = new System.Windows.Forms.Padding(2);
this.buttonDel.Name = "buttonDel";
this.buttonDel.Size = new System.Drawing.Size(90, 27);
this.buttonDel.TabIndex = 8;
this.buttonDel.Text = "Удалить";
this.buttonDel.UseVisualStyleBackColor = true;
this.buttonDel.Click += new System.EventHandler(this.buttonDel_Click);
//
// buttonUpd
//
this.buttonUpd.Location = new System.Drawing.Point(552, 69);
this.buttonUpd.Margin = new System.Windows.Forms.Padding(2);
this.buttonUpd.Name = "buttonUpd";
this.buttonUpd.Size = new System.Drawing.Size(90, 27);
this.buttonUpd.TabIndex = 7;
this.buttonUpd.Text = "Изменить";
this.buttonUpd.UseVisualStyleBackColor = true;
this.buttonUpd.Click += new System.EventHandler(this.buttonUpd_Click);
//
// buttonAdd
//
this.buttonAdd.Location = new System.Drawing.Point(552, 11);
this.buttonAdd.Margin = new System.Windows.Forms.Padding(2);
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(90, 27);
this.buttonAdd.TabIndex = 6;
this.buttonAdd.Text = "Добавить";
this.buttonAdd.UseVisualStyleBackColor = true;
this.buttonAdd.Click += new System.EventHandler(this.buttonAdd_Click);
//
// dataGridView
//
this.dataGridView.BackgroundColor = System.Drawing.Color.White;
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Location = new System.Drawing.Point(11, 11);
this.dataGridView.Margin = new System.Windows.Forms.Padding(2);
this.dataGridView.MultiSelect = false;
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowHeadersVisible = false;
this.dataGridView.RowHeadersWidth = 62;
this.dataGridView.RowTemplate.Height = 33;
this.dataGridView.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.dataGridView.Size = new System.Drawing.Size(522, 424);
this.dataGridView.TabIndex = 5;
//
// FormImplementers
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(657, 446);
this.Controls.Add(this.buttonRef);
this.Controls.Add(this.buttonDel);
this.Controls.Add(this.buttonUpd);
this.Controls.Add(this.buttonAdd);
this.Controls.Add(this.dataGridView);
this.Name = "FormImplementers";
this.Text = "Исполнители";
this.Load += new System.EventHandler(this.FormImplementers_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.ResumeLayout(false);
}
#endregion
private Button buttonRef;
private Button buttonDel;
private Button buttonUpd;
private Button buttonAdd;
private DataGridView dataGridView;
}
}

View File

@ -0,0 +1,109 @@
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;
using TravelCompanyContracts.BindingModels;
using TravelCompanyContracts.BusinessLogicsContracts;
namespace TravelCompany
{
public partial class FormImplementers : Form
{
private readonly ILogger _logger;
private readonly IImplementerLogic _logic;
public FormImplementers(ILogger<FormImplementers> logger, IImplementerLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormImplementers_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка компонентов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки исполнителей");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonAdd_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormImplementer));
if (service is FormImplementer form)
{
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
private void buttonUpd_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormImplementer));
if (service is FormImplementer form)
{
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
}
private void buttonDel_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Удаление исполнителя");
try
{
if (!_logic.Delete(new ImplementerBindingModel { Id = id }))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления исполнителя");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void buttonRef_Click(object sender, EventArgs e)
{
LoadData();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -43,6 +43,7 @@
this.ButtonOrderReady = new System.Windows.Forms.Button();
this.ButtonIssuedOrder = new System.Windows.Forms.Button();
this.ButtonRef = new System.Windows.Forms.Button();
this.запускРаботToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.menuStrip.SuspendLayout();
this.SuspendLayout();
@ -52,7 +53,7 @@
this.dataGridView.BackgroundColor = System.Drawing.Color.White;
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Location = new System.Drawing.Point(3, 36);
this.dataGridView.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.dataGridView.Margin = new System.Windows.Forms.Padding(2);
this.dataGridView.MultiSelect = false;
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowHeadersVisible = false;
@ -67,7 +68,8 @@
this.menuStrip.ImageScalingSize = new System.Drawing.Size(24, 24);
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.справочникиToolStripMenuItem,
this.отчетToolStripMenuItem});
this.отчетToolStripMenuItem,
this.запускРаботToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.Name = "menuStrip";
this.menuStrip.Padding = new System.Windows.Forms.Padding(5, 2, 0, 2);
@ -140,7 +142,7 @@
// buttonCreateOrder
//
this.buttonCreateOrder.Location = new System.Drawing.Point(1224, 36);
this.buttonCreateOrder.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.buttonCreateOrder.Margin = new System.Windows.Forms.Padding(2);
this.buttonCreateOrder.Name = "buttonCreateOrder";
this.buttonCreateOrder.Size = new System.Drawing.Size(173, 27);
this.buttonCreateOrder.TabIndex = 2;
@ -151,7 +153,7 @@
// ButtonTakeOrderInWork
//
this.ButtonTakeOrderInWork.Location = new System.Drawing.Point(1224, 91);
this.ButtonTakeOrderInWork.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.ButtonTakeOrderInWork.Margin = new System.Windows.Forms.Padding(2);
this.ButtonTakeOrderInWork.Name = "ButtonTakeOrderInWork";
this.ButtonTakeOrderInWork.Size = new System.Drawing.Size(173, 27);
this.ButtonTakeOrderInWork.TabIndex = 3;
@ -162,7 +164,7 @@
// ButtonOrderReady
//
this.ButtonOrderReady.Location = new System.Drawing.Point(1224, 154);
this.ButtonOrderReady.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.ButtonOrderReady.Margin = new System.Windows.Forms.Padding(2);
this.ButtonOrderReady.Name = "ButtonOrderReady";
this.ButtonOrderReady.Size = new System.Drawing.Size(173, 27);
this.ButtonOrderReady.TabIndex = 4;
@ -173,7 +175,7 @@
// ButtonIssuedOrder
//
this.ButtonIssuedOrder.Location = new System.Drawing.Point(1224, 206);
this.ButtonIssuedOrder.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.ButtonIssuedOrder.Margin = new System.Windows.Forms.Padding(2);
this.ButtonIssuedOrder.Name = "ButtonIssuedOrder";
this.ButtonIssuedOrder.Size = new System.Drawing.Size(173, 27);
this.ButtonIssuedOrder.TabIndex = 5;
@ -184,7 +186,7 @@
// ButtonRef
//
this.ButtonRef.Location = new System.Drawing.Point(1224, 262);
this.ButtonRef.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.ButtonRef.Margin = new System.Windows.Forms.Padding(2);
this.ButtonRef.Name = "ButtonRef";
this.ButtonRef.Size = new System.Drawing.Size(173, 27);
this.ButtonRef.TabIndex = 6;
@ -192,6 +194,13 @@
this.ButtonRef.UseVisualStyleBackColor = true;
this.ButtonRef.Click += new System.EventHandler(this.ButtonRef_Click);
//
// запускРаботToolStripMenuItem
//
this.запускРаботToolStripMenuItem.Name = апускРаботToolStripMenuItem";
this.запускРаботToolStripMenuItem.Size = new System.Drawing.Size(114, 24);
this.запускРаботToolStripMenuItem.Text = "Запуск работ";
this.запускРаботToolStripMenuItem.Click += new System.EventHandler(this.запускРаботToolStripMenuItem_Click);
//
// FormMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
@ -205,7 +214,7 @@
this.Controls.Add(this.dataGridView);
this.Controls.Add(this.menuStrip);
this.MainMenuStrip = this.menuStrip;
this.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.Margin = new System.Windows.Forms.Padding(2);
this.Name = "FormMain";
this.Text = "Туристическая фирма";
this.Load += new System.EventHandler(this.FormMain_Load);
@ -234,5 +243,6 @@
private ToolStripMenuItem условияПоПоездкамToolStripMenuItem;
private ToolStripMenuItem списокЗаказовToolStripMenuItem;
private ToolStripMenuItem клиентыToolStripMenuItem;
private ToolStripMenuItem запускРаботToolStripMenuItem;
}
}

View File

@ -11,12 +11,14 @@ namespace TravelCompany
private readonly ILogger _logger;
private readonly IOrderLogic _orderLogic;
private readonly IReportLogic _reportLogic;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic)
private readonly IWorkProcess _workProcess;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess)
{
InitializeComponent();
_reportLogic = reportLogic;
_logger = logger;
_orderLogic = orderLogic;
_workProcess = workProcess;
}
private void FormMain_Load(object sender, EventArgs e)
{
@ -187,5 +189,14 @@ namespace TravelCompany
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);
}
}
}

View File

@ -39,11 +39,14 @@ namespace TravelCompany
services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<ITravelStorage, TravelStorage>();
services.AddTransient<IClientStorage, ClientStorage>();
services.AddTransient<IImplementerStorage, ImplementerStorage>();
services.AddTransient<IConditionLogic, ConditionLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<ITravelLogic, TravelLogic>();
services.AddTransient<IReportLogic, ReportLogic>();
services.AddTransient<IClientLogic, ClientLogic>();
services.AddTransient<IWorkProcess, WorkModeling>();
services.AddTransient<IImplementerLogic, ImplementerLogic>();
services.AddTransient<FormMain>();
services.AddTransient<FormCondition>();
services.AddTransient<FormConditions>();
@ -54,6 +57,8 @@ namespace TravelCompany
services.AddTransient<FormReportTravelConditions>();
services.AddTransient<FormReportOrders>();
services.AddTransient<FormClients>();
services.AddTransient<FormImplementers>();
services.AddTransient<FormImplementer>();
services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
services.AddTransient<AbstractSaveToWord, SaveToWord>();
services.AddTransient<AbstractSaveToPdf, SaveToPdf>();

View File

@ -0,0 +1,129 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TravelCompanyContracts.BindingModels;
using TravelCompanyContracts.BusinessLogicsContracts;
using TravelCompanyContracts.SearchModels;
using TravelCompanyContracts.StoragesContracts;
using TravelCompanyContracts.ViewModels;
using Microsoft.Extensions.Logging;
namespace TravelCompanyBusinessLogic.BusinessLogic
{
public class ImplementerLogic : IImplementerLogic
{
private readonly ILogger _logger;
private readonly IImplementerStorage _implementerStorage;
public ImplementerLogic(ILogger<ImplementerLogic> logger, IImplementerStorage implementerStorage)
{
_logger = logger;
_implementerStorage = implementerStorage;
}
public bool Create(ImplementerBindingModel model)
{
CheckModel(model);
if (_implementerStorage.Insert(model) == null)
{
_logger.LogWarning("Insert 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;
}
public ImplementerViewModel? ReadElement(ImplementerSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. Id:{Id}. ImplementerFIO:{ImplementerFIO}. " +
"Password:{Password}", model.Id, model.ImplementerFIO, model.Password);
var element = _implementerStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
public List<ImplementerViewModel>? ReadList(ImplementerSearchModel? model)
{
_logger.LogInformation("ReadList. Id:{Id}. ImplementerFIO:{ImplementerFIO}." +
" Password:{Password}", model?.Id, model?.ImplementerFIO, model?.Password);
var list = model == null ? _implementerStorage.GetFullList() : _implementerStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public bool Update(ImplementerBindingModel model)
{
CheckModel(model);
if (_implementerStorage.Update(model) == null)
{
_logger.LogWarning("Update 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("Квалификация не может быть меньше 0 лет!", nameof(model.Qualification));
}
_logger.LogInformation("Implementer. ImplementerFIO:{ImplementerFIO}." +
" Password:{Password}. Id:{Id}", model.ImplementerFIO, model.Password, model.Id);
var element = _implementerStorage.GetElement(new ImplementerSearchModel
{
ImplementerFIO = model.ImplementerFIO
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Исполнитель с таким ФИО уже зарегестрирован!");
}
}
}
}

View File

@ -17,6 +17,7 @@ namespace TravelCompanyBusinessLogic.BusinessLogic
{
private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage;
static readonly object _lock = new object();
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage)
{
_logger = logger;
@ -76,6 +77,7 @@ namespace TravelCompanyBusinessLogic.BusinessLogic
throw new InvalidOperationException("Статус заказа 'Готов' может быть присвоен только заказам со статусом 'Выполняется'!");
}
model.Status = OrderStatus.Готов;
model.DateImplement = DateTime.Now;
_orderStorage.Update(model);
return true;
}
@ -93,26 +95,46 @@ namespace TravelCompanyBusinessLogic.BusinessLogic
return list;
}
public bool TakeOrderInWork(OrderBindingModel model)
public OrderViewModel? ReadElement(OrderSearchModel? model)
{
CheckModel(model, false);
var element = _orderStorage.GetElement(new OrderSearchModel
if (model == null)
{
Id = model.Id
});
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. ImplementerId:{ImplementerId}. OrderStatus:{OrderStatus}. Id:{Id}", model.ImplementerId, model.OrderStatus, model.Id);
var element = _orderStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("Read operation failed");
return false;
_logger.LogWarning("ReadElement element not found");
return null;
}
if (element.Status != OrderStatus.Принят)
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
public bool TakeOrderInWork(OrderBindingModel model)
{
lock (_lock)
{
_logger.LogWarning("Status change operation failed");
throw new InvalidOperationException("Статус заказа 'Выполняется' может быть присвоен только заказам со статусом 'Принят'!");
CheckModel(model, false);
var element = _orderStorage.GetElement(new OrderSearchModel
{
Id = model.Id
});
if (element == null)
{
_logger.LogWarning("Read operation failed");
return false;
}
if (element.Status != OrderStatus.Принят)
{
_logger.LogWarning("Status change operation failed");
throw new InvalidOperationException("Заказ должен быть переведен в статус принятого перед его выполнением!");
}
model.Status = OrderStatus.Выполняется;
_orderStorage.Update(model);
return true;
}
model.Status = OrderStatus.Выполняется;
_orderStorage.Update(model);
return true;
}
private void CheckModel(OrderBindingModel model, bool withParams = true)

View File

@ -0,0 +1,151 @@
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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<WorkModeling> 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 { OrderStatus = 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));
}
}
/// <summary>
/// Иммитация работы исполнителя
/// </summary>
/// <param name="implementer"></param>
/// <param name="orders"></param>
private async Task WorkerWorkAsync(ImplementerViewModel implementer, List<OrderViewModel>? orders)
{
if (_orderLogic == null || implementer == null || orders == null)
{
return;
}
await RunOrderInWork(implementer);
if (orders == null || orders.Count == 0)
return;
await Task.Run(async () =>
{
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
});
// делаем работу
await Task.Delay(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;
}
// отдыхаем
await Task.Delay(implementer.Qualification * _rnd.Next(10, 100));
}
});
}
/// <summary>
/// Ищем заказ, которые уже в работе (вдруг исполнителя прервали)
/// </summary>
/// <param name="implementer"></param>
/// <returns></returns>
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,
OrderStatus = OrderStatus.Выполняется
}));
if (runOrder == null)
{
return;
}
_logger.LogDebug("DoWork. Worker {Id} back to order {Order}", implementer.Id, runOrder.Id);
// доделываем работу
await Task.Delay(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
});
// отдыхаем
await Task.Delay(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;
}
}
}
}

View File

@ -18,5 +18,6 @@ namespace TravelCompanyContracts.BindingModels
public DateTime DateCreate { get; set; } = DateTime.Now;
public DateTime? DateImplement { get; set; }
public int ClientId { get; set; }
public int? ImplementerId { get; set; }
}
}

View File

@ -12,6 +12,7 @@ namespace TravelCompanyContracts.BusinessLogicsContracts
public interface IOrderLogic
{
List<OrderViewModel>? ReadList(OrderSearchModel? model);
OrderViewModel? ReadElement(OrderSearchModel? model);
bool CreateOrder(OrderBindingModel model);
bool TakeOrderInWork(OrderBindingModel model);
bool FinishOrder(OrderBindingModel model);

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TravelCompanyContracts.BusinessLogicsContracts
{
public interface IWorkProcess
{
/// <summary>
/// Запуск работ
/// </summary>
void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic);
}
}

View File

@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TravelCompanyDataModels.Enums;
namespace TravelCompanyContracts.SearchModels
{
@ -12,5 +13,7 @@ namespace TravelCompanyContracts.SearchModels
public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }
public int? ClientId { get; set; }
public int? ImplementerId { get; set; }
public OrderStatus? OrderStatus { get; set; }
}
}

View File

@ -21,6 +21,9 @@ namespace TravelCompanyContracts.ViewModels
public int Count { get; set; }
[DisplayName("Сумма")]
public double Sum { get; set; }
public int? ImplementerId { get; set; }
[DisplayName("ФИО Исполнителя")]
public string? ImplementerFIO { get; set; }
[DisplayName("ФИО клиента")]
public string ClientFIO { get; set; } = string.Empty;
[DisplayName("Статус")]

View File

@ -16,5 +16,6 @@ namespace TravelCompanyDataModels.Models
DateTime DateCreate { get; }
DateTime? DateImplement { get; }
int ClientId { get; }
int? ImplementerId { get; }
}
}

View File

@ -17,21 +17,30 @@ namespace TravelCompanyDatabaseImplement.Implements
public List<OrderViewModel> GetFullList()
{
using var context = new TravelCompanyDatabase();
return context.Orders.Include(x => x.Client)
return context.Orders.Include(x => x.Client).Include(x => x.Implementer)
.Select(x => AccessTravelStorage(x.GetViewModel, context))
.ToList();
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
if (!model.ClientId.HasValue && !model.DateFrom.HasValue && !model.DateTo.HasValue)
if (!model.ClientId.HasValue && !model.DateFrom.HasValue && !model.DateTo.HasValue
&& !model.OrderStatus.HasValue)
{
return new();
}
if (model.DateFrom.HasValue && model.DateTo.HasValue)
if (model.OrderStatus.HasValue)
{
using var context = new TravelCompanyDatabase();
return context.Orders.Include(x => x.Client).Include(x => x.Implementer)
.Where(x => x.Status == model.OrderStatus)
.Select(x => AccessTravelStorage(x.GetViewModel, context))
.ToList();
}
else if (model.DateFrom.HasValue && model.DateTo.HasValue)
{
using var context = new TravelCompanyDatabase();
return context.Orders.Include(x => x.Client)
return context.Orders.Include(x => x.Client).Include(x => x.Implementer)
.Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo)
.Select(x => AccessTravelStorage(x.GetViewModel, context))
.ToList();
@ -39,7 +48,7 @@ namespace TravelCompanyDatabaseImplement.Implements
if (model.ClientId.HasValue)
{
using var context = new TravelCompanyDatabase();
return context.Orders.Include(x => x.Client)
return context.Orders.Include(x => x.Client).Include(x => x.Implementer)
.Where(x => x.ClientId == model.ClientId)
.Select(x => AccessTravelStorage(x.GetViewModel, context))
.ToList();
@ -47,7 +56,7 @@ namespace TravelCompanyDatabaseImplement.Implements
else
{
using var context = new TravelCompanyDatabase();
return context.Orders.Include(x => x.Client)
return context.Orders.Include(x => x.Client).Include(x => x.Implementer)
.Where(x => x.Id == model.Id)
.Select(x => AccessTravelStorage(x.GetViewModel, context))
.ToList();
@ -56,15 +65,24 @@ namespace TravelCompanyDatabaseImplement.Implements
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
if (!model.Id.HasValue && !model.ImplementerId.HasValue && !model.OrderStatus.HasValue)
{
return new();
}
using var context = new TravelCompanyDatabase();
return AccessTravelStorage(context.Orders.Include(x => x.Client)
.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)
?.GetViewModel, context);
if (!model.Id.HasValue)
{
return AccessTravelStorage(context.Orders.Include(x => x.Client).Include(x => x.Implementer)
.FirstOrDefault(x => model.ImplementerId.HasValue && model.OrderStatus.HasValue
&& x.Status == model.OrderStatus && x.ImplementerId == model.ImplementerId)
?.GetViewModel, context);
}
else
{
return AccessTravelStorage(context.Orders.Include(x => x.Client).Include(x => x.Implementer)
.FirstOrDefault(x => x.Id == model.Id)
?.GetViewModel, context);
}
}
public OrderViewModel? Insert(OrderBindingModel model)
{
@ -86,7 +104,7 @@ namespace TravelCompanyDatabaseImplement.Implements
{
return null;
}
order.Update(model);
order.Update(model, context);
context.SaveChanges();
return AccessTravelStorage(order.GetViewModel, context);
}

View File

@ -29,6 +29,8 @@ namespace TravelCompanyDatabaseImplement.Models
[Required]
public int ClientId { get; set; }
public virtual Client Client { get; set; } = new();
public int? ImplementerId { get; set; }
public virtual Implementer? Implementer { get; set; } = new();
public static Order? Create(OrderBindingModel? model, TravelCompanyDatabase context)
{
@ -47,15 +49,20 @@ namespace TravelCompanyDatabaseImplement.Models
DateImplement = model.DateImplement,
ClientId = model.ClientId,
Client = context.Clients.First(x => x.Id == model.ClientId),
ImplementerId = model.ImplementerId,
Implementer = model.ImplementerId.HasValue ?
context.Implementers.First(x => x.Id == model.ImplementerId) : null,
};
}
public void Update(OrderBindingModel? model)
public void Update(OrderBindingModel? model, TravelCompanyDatabase context)
{
if (model == null)
{
return;
}
Status = model.Status;
if (model.ImplementerId.HasValue) ImplementerId = model.ImplementerId;
if (model.ImplementerId.HasValue) Implementer = context.Implementers.First(x => x.Id == model.ImplementerId);
if (model.DateImplement.HasValue) DateImplement = model.DateImplement;
}
public OrderViewModel GetViewModel => new()
@ -69,6 +76,8 @@ namespace TravelCompanyDatabaseImplement.Models
DateImplement = DateImplement,
ClientId = ClientId,
ClientFIO = Client.ClientFIO,
ImplementerId = ImplementerId,
ImplementerFIO = Implementer?.ImplementerFIO
};
}

View File

@ -15,7 +15,7 @@ namespace TravelCompanyDatabaseImplement
{
if (optionsBuilder.IsConfigured == false)
{
optionsBuilder.UseSqlServer(@"Data Source=localhost\SQLEXPRESS;Initial Catalog=TravelCompanyDatabaseFull;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True");
optionsBuilder.UseSqlServer(@"Data Source=localhost\SQLEXPRESS;Initial Catalog=TravelCompanyDatabaseFullLab6;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True");
}
base.OnConfiguring(optionsBuilder);
}

View File

@ -1,4 +1,5 @@
using System;
using DocumentFormat.OpenXml.Bibliography;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
@ -29,14 +30,14 @@ namespace TravelCompanyFileImplement.Implements
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
if (!model.Id.HasValue && !model.DateFrom.HasValue && !model.DateTo.HasValue)
if (!model.Id.HasValue || !model.DateFrom.HasValue || !model.DateTo.HasValue || !model.OrderStatus.HasValue)
{
return new();
}
if (model.ClientId.HasValue)
if (model.OrderStatus.HasValue)
{
return _source.Orders
.Where(x => x.ClientId == model.ClientId)
.Where(x => x.ImplementerId == model.ImplementerId)
.Select(x => InsertTravelName(x.GetViewModel))
.ToList();
}
@ -58,13 +59,23 @@ namespace TravelCompanyFileImplement.Implements
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
if (!model.Id.HasValue && !model.ImplementerId.HasValue && !model.OrderStatus.HasValue)
{
return null;
}
return InsertTravelName(_source.Orders
.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)
?.GetViewModel);
if (!model.Id.HasValue)
{
return InsertTravelName(_source.Orders
.FirstOrDefault(x => model.ImplementerId.HasValue && model.OrderStatus.HasValue
&& x.ImplementerId == model.ImplementerId && x.Status == model.OrderStatus)
?.GetViewModel);
}
else
{
return InsertTravelName(_source.Orders
.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)
?.GetViewModel);
}
}
public OrderViewModel? Insert(OrderBindingModel model)
{

View File

@ -22,6 +22,7 @@ namespace TravelCompanyFileImplement.Models
public DateTime DateCreate { get; set; }
public DateTime? DateImplement { get; set; }
public int ClientId { get; private set; }
public int? ImplementerId { get; private set; }
public static Order? Create(OrderBindingModel model)
{
if (model == null)
@ -38,6 +39,7 @@ namespace TravelCompanyFileImplement.Models
DateCreate = model.DateCreate,
DateImplement = model.DateImplement,
ClientId = model.ClientId,
ImplementerId = model.ImplementerId,
};
}
public static Order? Create(XElement element)
@ -57,6 +59,7 @@ namespace TravelCompanyFileImplement.Models
DateImplement = string.IsNullOrEmpty(element.Element("DateImplement")!.Value)
? null : Convert.ToDateTime(element.Element("DateImplement")!.Value),
ClientId = Convert.ToInt32(element.Element("ClientId")!.Value),
ImplementerId = Convert.ToInt32(element.Element("ImplementerId")!.Value),
};
}
public void Update(OrderBindingModel model)
@ -66,6 +69,7 @@ namespace TravelCompanyFileImplement.Models
return;
}
Status = model.Status;
ImplementerId = model.ImplementerId;
if (model.DateImplement.HasValue) { DateImplement = model.DateImplement; }
}
public OrderViewModel GetViewModel => new()
@ -78,6 +82,7 @@ namespace TravelCompanyFileImplement.Models
DateCreate = DateCreate,
DateImplement = DateImplement,
ClientId = ClientId,
ImplementerId = ImplementerId,
};
public XElement GetXElement => new("Order",
new XAttribute("Id", Id),
@ -88,6 +93,8 @@ namespace TravelCompanyFileImplement.Models
new XElement("DateCreate", DateCreate.ToString()),
new XElement("DateImplement", DateImplement.ToString(),
new XElement("ClientId", ClientId)));
new XElement("ImplementerId", ImplementerId.ToString()),
}
}

View File

@ -7,6 +7,7 @@ using TravelCompanyContracts.BindingModels;
using TravelCompanyContracts.SearchModels;
using TravelCompanyContracts.StoragesContracts;
using TravelCompanyContracts.ViewModels;
using TravelCompanyListImplement.Models;
namespace TravelCompanyListImplement.Implements
{

View File

@ -30,21 +30,21 @@ namespace TravelCompanyListImplement.Implements
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
var result = new List<OrderViewModel>();
if (!model.Id.HasValue && !model.DateFrom.HasValue && !model.DateTo.HasValue)
if (!model.Id.HasValue && !model.DateFrom.HasValue && !model.DateTo.HasValue && !model.OrderStatus.HasValue)
{
return result;
}
if (model.ClientId.HasValue)
if (model.ImplementerId.HasValue && model.OrderStatus.HasValue)
{
foreach (var order in _source.Orders)
{
if (order.ClientId == model.ClientId)
if (order.Status == model.OrderStatus)
{
result.Add(InsertTravelName(order.GetViewModel));
}
}
}
if (!model.DateFrom.HasValue || !model.DateTo.HasValue)
else if (!model.DateFrom.HasValue || !model.DateTo.HasValue)
{
foreach (var order in _source.Orders)
{
@ -68,15 +68,29 @@ namespace TravelCompanyListImplement.Implements
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
if (!model.Id.HasValue && !model.ImplementerId.HasValue && !model.OrderStatus.HasValue)
{
return null;
}
foreach (var order in _source.Orders)
if (!model.Id.HasValue)
{
if (model.Id.HasValue && order.Id == model.Id)
foreach (var order in _source.Orders)
{
return InsertTravelName(order.GetViewModel);
if (model.ImplementerId.HasValue && model.OrderStatus.HasValue
&& order.ImplementerId == model.ImplementerId && order.Status == model.OrderStatus)
{
return InsertTravelName(order.GetViewModel);
}
}
}
else
{
foreach (var order in _source.Orders)
{
if (model.Id.HasValue && order.Id == model.Id)
{
return InsertTravelName(order.GetViewModel);
}
}
}
return null;

View File

@ -22,6 +22,7 @@ namespace TravelCompanyListImplement.Models
public DateTime DateCreate { get; set; }
public DateTime? DateImplement { get; set; }
public int ClientId { get; set; }
public int? ImplementerId { get; private set; }
public static Order? Create(OrderBindingModel? model)
{
if (model == null)
@ -38,6 +39,7 @@ namespace TravelCompanyListImplement.Models
DateCreate = model.DateCreate,
DateImplement = model.DateImplement,
ClientId = model.ClientId,
ImplementerId = model.ImplementerId,
};
}
public void Update(OrderBindingModel? model)
@ -47,6 +49,8 @@ namespace TravelCompanyListImplement.Models
return;
}
Status = model.Status;
DateCreate = model.DateCreate;
ImplementerId = model.ImplementerId;
DateImplement = model.DateImplement;
}
public OrderViewModel GetViewModel => new()
@ -59,6 +63,7 @@ namespace TravelCompanyListImplement.Models
DateCreate = DateCreate,
DateImplement = DateImplement,
ClientId = ClientId,
ImplementerId = ImplementerId,
};
}
}

View File

@ -0,0 +1,103 @@
using DocumentFormat.OpenXml.Office2010.Excel;
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<ImplementerController> 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<OrderViewModel>? GetNewOrders()
{
try
{
return _order.ReadList(new OrderSearchModel
{
OrderStatus = 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;
}
}
}
}