lab6 full

This commit is contained in:
MaxKarme 2023-04-11 09:29:12 +04:00
parent 9cfecca344
commit 6b5bd94e88
38 changed files with 1749 additions and 123 deletions

View File

@ -36,13 +36,15 @@
this.label1 = new System.Windows.Forms.Label();
this.textBoxSum = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.comboBoxClient = new System.Windows.Forms.ComboBox();
this.label4 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// comboBoxPizza
//
this.comboBoxPizza.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxPizza.FormattingEnabled = true;
this.comboBoxPizza.Location = new System.Drawing.Point(119, 34);
this.comboBoxPizza.Location = new System.Drawing.Point(110, 49);
this.comboBoxPizza.Name = "comboBoxPizza";
this.comboBoxPizza.Size = new System.Drawing.Size(224, 28);
this.comboBoxPizza.TabIndex = 18;
@ -50,7 +52,7 @@
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(249, 145);
this.buttonCancel.Location = new System.Drawing.Point(240, 160);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(94, 29);
this.buttonCancel.TabIndex = 17;
@ -60,7 +62,7 @@
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(135, 145);
this.buttonSave.Location = new System.Drawing.Point(126, 160);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(94, 29);
this.buttonSave.TabIndex = 16;
@ -70,7 +72,7 @@
//
// textBoxCount
//
this.textBoxCount.Location = new System.Drawing.Point(117, 68);
this.textBoxCount.Location = new System.Drawing.Point(108, 83);
this.textBoxCount.Name = "textBoxCount";
this.textBoxCount.Size = new System.Drawing.Size(225, 27);
this.textBoxCount.TabIndex = 15;
@ -79,7 +81,7 @@
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(22, 75);
this.label2.Location = new System.Drawing.Point(13, 90);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(93, 20);
this.label2.TabIndex = 14;
@ -88,7 +90,7 @@
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(22, 42);
this.label1.Location = new System.Drawing.Point(13, 57);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(71, 20);
this.label1.TabIndex = 13;
@ -96,7 +98,7 @@
//
// textBoxSum
//
this.textBoxSum.Location = new System.Drawing.Point(118, 101);
this.textBoxSum.Location = new System.Drawing.Point(109, 116);
this.textBoxSum.Name = "textBoxSum";
this.textBoxSum.ReadOnly = true;
this.textBoxSum.Size = new System.Drawing.Size(225, 27);
@ -105,17 +107,37 @@
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(23, 108);
this.label3.Location = new System.Drawing.Point(14, 123);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(58, 20);
this.label3.TabIndex = 19;
this.label3.Text = "Сумма:";
//
// comboBoxClient
//
this.comboBoxClient.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxClient.FormattingEnabled = true;
this.comboBoxClient.Location = new System.Drawing.Point(110, 15);
this.comboBoxClient.Name = "comboBoxClient";
this.comboBoxClient.Size = new System.Drawing.Size(224, 28);
this.comboBoxClient.TabIndex = 22;
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(13, 23);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(61, 20);
this.label4.TabIndex = 21;
this.label4.Text = "Клиент:";
//
// FormCreateOrder
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(379, 195);
this.ClientSize = new System.Drawing.Size(346, 205);
this.Controls.Add(this.comboBoxClient);
this.Controls.Add(this.label4);
this.Controls.Add(this.textBoxSum);
this.Controls.Add(this.label3);
this.Controls.Add(this.comboBoxPizza);
@ -142,5 +164,7 @@
private Label label1;
private TextBox textBoxSum;
private Label label3;
private ComboBox comboBoxClient;
private Label label4;
}
}

View File

@ -12,24 +12,36 @@ namespace Pizzeria
private readonly ILogger _logger;
private readonly IPizzaLogic _logicP;
private readonly IOrderLogic _logicO;
public FormCreateOrder(ILogger<FormCreateOrder> logger, IPizzaLogic logicP, IOrderLogic logicO)
private readonly IClientLogic _logicC;
public FormCreateOrder(ILogger<FormCreateOrder> logger, IPizzaLogic logicP, IOrderLogic logicO, IClientLogic logicC)
{
InitializeComponent();
_logger = logger;
_logicP = logicP;
_logicO = logicO;
_logicC = logicC;
}
private void FormCreateOrder_Load(object sender, EventArgs e)
{
_logger.LogInformation("Загрузка пицц для заказа");
List<PizzaViewModel> _list = _logicP.ReadList(null);
if (_list != null)
List<PizzaViewModel> _listPizzas = _logicP.ReadList(null);
if (_listPizzas != null)
{
comboBoxPizza.DisplayMember = "PizzaName";
comboBoxPizza.ValueMember = "Id";
comboBoxPizza.DataSource = _list;
comboBoxPizza.DataSource = _listPizzas;
comboBoxPizza.SelectedItem = null;
}
_logger.LogInformation("Загрузка клиентов для заказа");
List<ClientViewModel> _listClients = _logicC.ReadList(null);
if (_listClients != null)
{
comboBoxClient.DisplayMember = "ClientFIO";
comboBoxClient.ValueMember = "Id";
comboBoxClient.DataSource = _listClients;
comboBoxClient.SelectedItem = null;
}
}
private void CalcSum()
{
@ -82,6 +94,7 @@ namespace Pizzeria
{
var operationResult = _logicO.CreateOrder(new OrderBindingModel
{
ClientId = Convert.ToInt32(comboBoxClient.SelectedValue),
PizzaId = Convert.ToInt32(comboBoxPizza.SelectedValue),
Count = Convert.ToInt32(textBoxCount.Text),
Sum = Convert.ToDouble(textBoxSum.Text)

View File

@ -0,0 +1,164 @@
namespace Pizzeria
{
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.textBoxQualification = new System.Windows.Forms.TextBox();
this.textBoxExpirience = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.buttonCancel = new System.Windows.Forms.Button();
this.buttonSave = new System.Windows.Forms.Button();
this.textBoxPassword = new System.Windows.Forms.TextBox();
this.textBoxName = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// textBoxQualification
//
this.textBoxQualification.Location = new System.Drawing.Point(346, 88);
this.textBoxQualification.Name = "textBoxQualification";
this.textBoxQualification.Size = new System.Drawing.Size(78, 27);
this.textBoxQualification.TabIndex = 19;
//
// textBoxExpirience
//
this.textBoxExpirience.Location = new System.Drawing.Point(119, 88);
this.textBoxExpirience.Name = "textBoxExpirience";
this.textBoxExpirience.Size = new System.Drawing.Size(65, 27);
this.textBoxExpirience.TabIndex = 18;
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(227, 91);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(114, 20);
this.label4.TabIndex = 17;
this.label4.Text = "Квалификация:";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(11, 91);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(102, 20);
this.label3.TabIndex = 16;
this.label3.Text = "Стаж работы:";
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(317, 144);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(94, 29);
this.buttonCancel.TabIndex = 15;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.ButtonCancel_Click);
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(203, 144);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(94, 29);
this.buttonSave.TabIndex = 14;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.ButtonSave_Click);
//
// textBoxPassword
//
this.textBoxPassword.Location = new System.Drawing.Point(119, 55);
this.textBoxPassword.Name = "textBoxPassword";
this.textBoxPassword.Size = new System.Drawing.Size(305, 27);
this.textBoxPassword.TabIndex = 13;
//
// textBoxName
//
this.textBoxName.Location = new System.Drawing.Point(119, 22);
this.textBoxName.Name = "textBoxName";
this.textBoxName.Size = new System.Drawing.Size(305, 27);
this.textBoxName.TabIndex = 12;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(11, 62);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(65, 20);
this.label2.TabIndex = 11;
this.label2.Text = "Пароль:";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(11, 29);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(45, 20);
this.label1.TabIndex = 10;
this.label1.Text = "ФИО:";
//
// FormImplementer
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(439, 200);
this.Controls.Add(this.textBoxQualification);
this.Controls.Add(this.textBoxExpirience);
this.Controls.Add(this.label4);
this.Controls.Add(this.label3);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.textBoxPassword);
this.Controls.Add(this.textBoxName);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Name = "FormImplementer";
this.Text = "Исполнитель";
this.Load += new System.EventHandler(this.FormImplementer_Load);
this.Click += new System.EventHandler(this.FormImplementer_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private TextBox textBoxQualification;
private TextBox textBoxExpirience;
private Label label4;
private Label label3;
private Button buttonCancel;
private Button buttonSave;
private TextBox textBoxPassword;
private TextBox textBoxName;
private Label label2;
private Label label1;
}
}

View File

@ -0,0 +1,90 @@
using PizzeriaContracts.BindingModels;
using PizzeriaContracts.BusinessLogicsContracts;
using PizzeriaContracts.SearchModels;
using Microsoft.Extensions.Logging;
namespace Pizzeria
{
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)
{
textBoxName.Text = view.ImplementerFIO;
textBoxPassword.Text = view.Password;
textBoxExpirience.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(textBoxName.Text))
{
MessageBox.Show("Заполните название", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение исполнителя");
try
{
var model = new ImplementerBindingModel
{
Id = _id ?? 0,
ImplementerFIO = textBoxName.Text,
Password = textBoxPassword.Text,
Qualification = Convert.ToInt32(textBoxQualification.Text),
WorkExperience = Convert.ToInt32(textBoxExpirience.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,123 @@
namespace Pizzeria
{
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.button5 = new System.Windows.Forms.Button();
this.button4 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.button1 = new System.Windows.Forms.Button();
this.dataGridView = new System.Windows.Forms.DataGridView();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
//
// button5
//
this.button5.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.button5.Location = new System.Drawing.Point(665, 122);
this.button5.Name = "button5";
this.button5.Size = new System.Drawing.Size(94, 34);
this.button5.TabIndex = 10;
this.button5.Text = "Удалить";
this.button5.UseVisualStyleBackColor = true;
this.button5.Click += new System.EventHandler(this.ButtonDel_Click);
//
// button4
//
this.button4.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.button4.Location = new System.Drawing.Point(665, 169);
this.button4.Name = "button4";
this.button4.Size = new System.Drawing.Size(94, 34);
this.button4.TabIndex = 9;
this.button4.Text = "Обновить";
this.button4.UseVisualStyleBackColor = true;
this.button4.Click += new System.EventHandler(this.ButtonRef_Click);
//
// button2
//
this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.button2.Location = new System.Drawing.Point(665, 75);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(94, 34);
this.button2.TabIndex = 8;
this.button2.Text = "Изменить";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.ButtonUpd_Click);
//
// button1
//
this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.button1.Location = new System.Drawing.Point(665, 28);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(94, 34);
this.button1.TabIndex = 7;
this.button1.Text = "Добавить";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.ButtonAdd_Click);
//
// dataGridView
//
this.dataGridView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.dataGridView.BackgroundColor = System.Drawing.SystemColors.ControlLightLight;
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Location = new System.Drawing.Point(-1, 0);
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowHeadersWidth = 51;
this.dataGridView.RowTemplate.Height = 29;
this.dataGridView.Size = new System.Drawing.Size(629, 453);
this.dataGridView.TabIndex = 6;
//
// FormImplementers
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(792, 450);
this.Controls.Add(this.button5);
this.Controls.Add(this.button4);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
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 button5;
private Button button4;
private Button button2;
private Button button1;
private DataGridView dataGridView;
}
}

View File

@ -0,0 +1,103 @@
using PizzeriaContracts.BindingModels;
using PizzeriaContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
namespace Pizzeria
{
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

@ -30,9 +30,7 @@
{
this.components = new System.ComponentModel.Container();
this.dataGridView = new System.Windows.Forms.DataGridView();
this.button5 = new System.Windows.Forms.Button();
this.button4 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.button1 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this.contextMenuStrip = new System.Windows.Forms.ContextMenuStrip(this.components);
@ -40,11 +38,13 @@
this.справочникиToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.компонентыToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.изделияToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.клиентыToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.исполнителиToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.отчетыToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.списокКомпонентовToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.компонентовПоПиццамToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.списокЗаказовToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.клиентыToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.запускРаботToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
@ -60,24 +60,13 @@
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowHeadersWidth = 51;
this.dataGridView.RowTemplate.Height = 29;
this.dataGridView.Size = new System.Drawing.Size(1031, 383);
this.dataGridView.Size = new System.Drawing.Size(1203, 383);
this.dataGridView.TabIndex = 0;
//
// button5
//
this.button5.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.button5.Location = new System.Drawing.Point(1083, 143);
this.button5.Name = "button5";
this.button5.Size = new System.Drawing.Size(209, 29);
this.button5.TabIndex = 9;
this.button5.Text = "Заказ готов";
this.button5.UseVisualStyleBackColor = true;
this.button5.Click += new System.EventHandler(this.ButtonOrderReady_Click);
//
// button4
//
this.button4.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.button4.Location = new System.Drawing.Point(1083, 190);
this.button4.Location = new System.Drawing.Point(1255, 100);
this.button4.Name = "button4";
this.button4.Size = new System.Drawing.Size(209, 29);
this.button4.TabIndex = 8;
@ -85,21 +74,10 @@
this.button4.UseVisualStyleBackColor = true;
this.button4.Click += new System.EventHandler(this.ButtonIssuedOrder_Click);
//
// button2
//
this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.button2.Location = new System.Drawing.Point(1083, 96);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(209, 29);
this.button2.TabIndex = 7;
this.button2.Text = "Отдать на выполнение";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.ButtonTakeOrderInWork_Click);
//
// button1
//
this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.button1.Location = new System.Drawing.Point(1083, 49);
this.button1.Location = new System.Drawing.Point(1255, 49);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(209, 29);
this.button1.TabIndex = 6;
@ -110,7 +88,7 @@
// button3
//
this.button3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.button3.Location = new System.Drawing.Point(1083, 236);
this.button3.Location = new System.Drawing.Point(1255, 146);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(209, 29);
this.button3.TabIndex = 10;
@ -129,10 +107,11 @@
this.menuStrip1.ImageScalingSize = new System.Drawing.Size(20, 20);
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.справочникиToolStripMenuItem,
this.отчетыToolStripMenuItem});
this.отчетыToolStripMenuItem,
this.запускРаботToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(1329, 28);
this.menuStrip1.Size = new System.Drawing.Size(1501, 28);
this.menuStrip1.TabIndex = 11;
this.menuStrip1.Text = "menuStrip1";
//
@ -141,7 +120,8 @@
this.справочникиToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.компонентыToolStripMenuItem,
this.изделияToolStripMenuItem,
this.клиентыToolStripMenuItem});
this.клиентыToolStripMenuItem,
this.исполнителиToolStripMenuItem});
this.справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem";
this.справочникиToolStripMenuItem.Size = new System.Drawing.Size(117, 24);
this.справочникиToolStripMenuItem.Text = "Справочники";
@ -149,17 +129,31 @@
// компонентыToolStripMenuItem
//
this.компонентыToolStripMenuItem.Name = омпонентыToolStripMenuItem";
this.компонентыToolStripMenuItem.Size = new System.Drawing.Size(224, 26);
this.компонентыToolStripMenuItem.Size = new System.Drawing.Size(185, 26);
this.компонентыToolStripMenuItem.Text = "Компоненты";
this.компонентыToolStripMenuItem.Click += new System.EventHandler(this.КомпонентыToolStripMenuItem_Click);
//
// изделияToolStripMenuItem
//
this.изделияToolStripMenuItem.Name = "изделияToolStripMenuItem";
this.изделияToolStripMenuItem.Size = new System.Drawing.Size(224, 26);
this.изделияToolStripMenuItem.Size = new System.Drawing.Size(185, 26);
this.изделияToolStripMenuItem.Text = "Пиццы";
this.изделияToolStripMenuItem.Click += new System.EventHandler(this.ПиццыToolStripMenuItem_Click);
//
// клиентыToolStripMenuItem
//
this.клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem";
this.клиентыToolStripMenuItem.Size = new System.Drawing.Size(185, 26);
this.клиентыToolStripMenuItem.Text = "Клиенты";
this.клиентыToolStripMenuItem.Click += new System.EventHandler(this.клиентыToolStripMenuItem_Click);
//
// исполнителиToolStripMenuItem
//
this.исполнителиToolStripMenuItem.Name = сполнителиToolStripMenuItem";
this.исполнителиToolStripMenuItem.Size = new System.Drawing.Size(185, 26);
this.исполнителиToolStripMenuItem.Text = "Исполнители";
this.исполнителиToolStripMenuItem.Click += new System.EventHandler(this.исполнителиToolStripMenuItem_Click);
//
// отчетыToolStripMenuItem
//
this.отчетыToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
@ -191,23 +185,21 @@
this.списокЗаказовToolStripMenuItem.Text = "Список заказов";
this.списокЗаказовToolStripMenuItem.Click += new System.EventHandler(this.OrdersToolStripMenuItem_Click);
//
// клиентыToolStripMenuItem
// запускРаботToolStripMenuItem
//
this.клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem";
this.клиентыToolStripMenuItem.Size = new System.Drawing.Size(224, 26);
this.клиентыToolStripMenuItem.Text = "Клиенты";
this.клиентыToolStripMenuItem.Click += new System.EventHandler(this.клиентыToolStripMenuItem_Click);
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);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1329, 414);
this.ClientSize = new System.Drawing.Size(1501, 414);
this.Controls.Add(this.menuStrip1);
this.Controls.Add(this.button3);
this.Controls.Add(this.button5);
this.Controls.Add(this.button4);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.dataGridView);
this.MainMenuStrip = this.menuStrip1;
@ -225,9 +217,7 @@
#endregion
private DataGridView dataGridView;
private Button button5;
private Button button4;
private Button button2;
private Button button1;
private Button button3;
private ContextMenuStrip contextMenuStrip;
@ -240,5 +230,7 @@
private ToolStripMenuItem компонентовПоПиццамToolStripMenuItem;
private ToolStripMenuItem списокЗаказовToolStripMenuItem;
private ToolStripMenuItem клиентыToolStripMenuItem;
private ToolStripMenuItem запускРаботToolStripMenuItem;
private ToolStripMenuItem исполнителиToolStripMenuItem;
}
}

View File

@ -10,12 +10,14 @@ namespace Pizzeria
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();
_logger = logger;
_orderLogic = orderLogic;
_reportLogic = reportLogic;
_workProcess = workProcess;
}
private void FormMain_Load(object sender, EventArgs e)
{
@ -31,6 +33,7 @@ namespace Pizzeria
dataGridView.DataSource = list;
dataGridView.Columns["PizzaId"].Visible = false;
dataGridView.Columns["ClientId"].Visible = false;
dataGridView.Columns["ImplementerId"].Visible = false;
dataGridView.Columns["PizzaName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Çàãðóçêà çàêàçîâ");
@ -88,52 +91,6 @@ namespace Pizzeria
DateCreate = DateTime.SpecifyKind(DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()), DateTimeKind.Utc),
};
}
private void ButtonTakeOrderInWork_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Çàêàç ¹{id}. Ìåíÿåòñÿ ñòàòóñ íà 'Â ðàáîòå'", id);
try
{
var operationResult = _orderLogic.TakeOrderInWork(getBindingModel());
if (!operationResult)
{
throw new Exception("Îøèáêà ïðè ñîõðàíåíèè. Äîïîëíèòåëüíàÿ èíôîðìàöèÿ â ëîãàõ.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Îøèáêà ïåðåäà÷è çàêàçà â ðàáîòó");
MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void ButtonOrderReady_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Çàêàç ¹{id}. Ìåíÿåòñÿ ñòàòóñ íà 'Ãîòîâ'", id);
try
{
var operationResult = _orderLogic.FinishOrder(getBindingModel());
if (!operationResult)
{
throw new Exception("Îøèáêà ïðè ñîõðàíåíèè. Äîïîëíèòåëüíàÿ èíôîðìàöèÿ â ëîãàõ.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Îøèáêà îòìåòêè î ãîòîâíîñòè çàêàçà");
MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonIssuedOrder_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
@ -195,5 +152,20 @@ e)
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(FormImplementers));
if (service is FormImplementers form)
{
form.ShowDialog();
}
}
}
}

View File

@ -111,6 +111,7 @@
this.Controls.Add(this.dateTimePickerFrom);
this.Name = "FormReportOrders";
this.Text = "FormReportOrders";
this.Load += new System.EventHandler(this.FormReportOrders_Load);
this.ResumeLayout(false);
this.PerformLayout();

View File

@ -86,5 +86,9 @@ namespace Pizzeria
}
}
private void FormReportOrders_Load(object sender, EventArgs e)
{
}
}
}

View File

@ -40,11 +40,15 @@ namespace Pizzeria
services.AddTransient<IPizzaLogic, PizzaLogic>();
services.AddTransient<IClientLogic, ClientLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<IImplementerLogic, ImplementerLogic>();
services.AddTransient<IReportLogic, ReportLogic>();
services.AddTransient<IWorkProcess, WorkModeling>();
services.AddTransient<IComponentStorage, ComponentStorage>();
services.AddTransient<IPizzaStorage, PizzaStorage>();
services.AddTransient<IClientStorage, ClientStorage>();
services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<IReportLogic, ReportLogic>();
services.AddTransient<IImplementerStorage, ImplementerStorage>();
services.AddTransient<AbstractSaveToWord, SaveToWord>();
services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
@ -53,6 +57,8 @@ namespace Pizzeria
services.AddTransient<FormMain>();
services.AddTransient<FormComponent>();
services.AddTransient<FormComponents>();
services.AddTransient<FormImplementer>();
services.AddTransient<FormImplementers>();
services.AddTransient<FormCreateOrder>();
services.AddTransient<FormPizza>();
services.AddTransient<FormPizzas>();

View File

@ -0,0 +1,109 @@
using PizzeriaContracts.BindingModels;
using PizzeriaContracts.BusinessLogicsContracts;
using PizzeriaContracts.SearchModels;
using PizzeriaContracts.StoragesContracts;
using PizzeriaContracts.ViewModels;
using Microsoft.Extensions.Logging;
namespace PizzeriaBusinessLogic
{
public class ImplementerLogic : IImplementerLogic
{
private readonly ILogger _logger;
private readonly IImplementerStorage _implementerStorage;
public ImplementerLogic(ILogger<ImplementerLogic> logger, IImplementerStorage implementerStorage)
{
_logger = logger;
_implementerStorage = implementerStorage;
}
public List<ImplementerViewModel>? ReadList(ImplementerSearchModel? model)
{
_logger.LogInformation("ReadList. ImplementerFIO: {ImplementerFIO}. Id:{Id}", model?.ImplementerFIO, model?.Id);
var list = model == null ? _implementerStorage.GetFullList() : _implementerStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public 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.ImplementerFIO));
}
_logger.LogInformation("Implementer. ImplementerFIO:{ImplementerFIO}. Id: {id}", model.ImplementerFIO, model.Id);
var element = _implementerStorage.GetElement(new ImplementerSearchModel
{
ImplementerFIO = model.ImplementerFIO
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Исполнитель с таким именем уже есть");
}
}
}
}

View File

@ -30,6 +30,19 @@ namespace PizzeriaBusinessLogic
return list;
}
public OrderViewModel? ReadElement(OrderSearchModel model)
{
_logger.LogInformation("Id:{Id}", model?.Id);
OrderViewModel order = _orderStorage.GetElement(model);
if (order == null)
{
_logger.LogWarning("ReadElement return null");
return null;
}
_logger.LogInformation("ReadElement. OrderId:{Id}", order.Id);
return order;
}
public bool CreateOrder(OrderBindingModel model)
{
CheckModel(model);
@ -51,7 +64,20 @@ namespace PizzeriaBusinessLogic
}
public bool UpdateStatus(OrderBindingModel model, OrderStatus newStatus)
{
CheckModel(model);
CheckModel(model, false);
OrderViewModel? order = _orderStorage.GetElement(new OrderSearchModel {
Id = model.Id
});
if(order == null)
{
_logger.LogWarning("Status update to " + newStatus.ToString() + " operation failed. Order not found.");
return false;
}
model.Status = order.Status;
if(!model.ImplementerId.HasValue) model.ImplementerId = order.ImplementerId;
if(model.Status + 1 != newStatus)
{
@ -61,7 +87,7 @@ namespace PizzeriaBusinessLogic
model.Status = newStatus;
if(newStatus == OrderStatus.Выдан)
if(newStatus == OrderStatus.Готов)
{
model.DateImplement = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc);
}

View File

@ -95,7 +95,8 @@ namespace PizzeriaBusinessLogic
throw new ArgumentNullException("Цена компонента должна быть больше 0", nameof(model.Price));
}
_logger.LogInformation("Component. PizzaName:{PizzaName}. Price:{ Price}. Id: { Id}", model.PizzaName, model.Price, model.Id);
var element = _pizzaStorage.GetElement(new PizzaSearchModel{
var element = _pizzaStorage.GetElement(new PizzaSearchModel
{
PizzaName = model.PizzaName
});

View File

@ -0,0 +1,141 @@
using PizzeriaContracts.BindingModels;
using PizzeriaContracts.BusinessLogicsContracts;
using PizzeriaContracts.SearchModels;
using PizzeriaContracts.ViewModels;
using PizzeriaDataModels;
using Microsoft.Extensions.Logging;
namespace PizzeriaBusinessLogic
{
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
{
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));
}
}
/// <summary>
/// Иммитация работы исполнителя
/// </summary>
/// <param name="implementer"></param>
/// <param name="orders"></param>
private async Task WorkerWorkAsync(ImplementerViewModel implementer, List<OrderViewModel> 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;
}
// отдыхаем
}
});
}
/// <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,
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;
}
}
}
}

View File

@ -0,0 +1,13 @@
using PizzeriaDataModels.Models;
namespace PizzeriaContracts.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; }
}
}

View File

@ -12,6 +12,7 @@ namespace PizzeriaContracts.BindingModels
public int Id { get; set; }
public int PizzaId { 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.Неизвестен;

View File

@ -0,0 +1,15 @@
using PizzeriaContracts.BindingModels;
using PizzeriaContracts.SearchModels;
using PizzeriaContracts.ViewModels;
namespace PizzeriaContracts.BusinessLogicsContracts
{
public interface IImplementerLogic
{
List<ImplementerViewModel>? ReadList(ImplementerSearchModel? model);
ImplementerViewModel? ReadElement(ImplementerSearchModel model);
bool Create(ImplementerBindingModel model);
bool Update(ImplementerBindingModel model);
bool Delete(ImplementerBindingModel model);
}
}

View File

@ -7,6 +7,7 @@ namespace PizzeriaContracts.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,11 @@
namespace PizzeriaContracts.BusinessLogicsContracts
{
public interface IWorkProcess
{
/// <summary>
/// Запуск работ
/// </summary>
void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic);
}
}

View File

@ -0,0 +1,9 @@
namespace PizzeriaContracts.SearchModels
{
public class ImplementerSearchModel
{
public int? Id { get; set; }
public string? ImplementerFIO { get; set; }
public string? Password { get; set; }
}
}

View File

@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PizzeriaDataModels;
namespace PizzeriaContracts.SearchModels
{
@ -12,5 +8,7 @@ namespace PizzeriaContracts.SearchModels
public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }
public int? ClientId { get; set; }
public int? ImplementerId { get; set; }
public OrderStatus? Status { get; set; }
}
}

View File

@ -0,0 +1,17 @@
using PizzeriaContracts.BindingModels;
using PizzeriaContracts.SearchModels;
using PizzeriaContracts.ViewModels;
namespace PizzeriaContracts.StoragesContracts
{
public interface IImplementerStorage
{
List<ImplementerViewModel> GetFullList();
List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model);
ImplementerViewModel? GetElement(ImplementerSearchModel model);
ImplementerViewModel? Insert(ImplementerBindingModel model);
ImplementerViewModel? Update(ImplementerBindingModel model);
ImplementerViewModel? Delete(ImplementerBindingModel model);
}
}

View File

@ -0,0 +1,17 @@
using PizzeriaDataModels.Models;
using System.ComponentModel;
namespace PizzeriaContracts.ViewModels
{
public class ImplementerViewModel : IImplementerModel
{
public int Id { get; set; }
[DisplayName("ФИО исполнителя")]
public string ImplementerFIO { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty;
[DisplayName("Опыт исполнителя")]
public int WorkExperience { get; set; }
[DisplayName("Квалификация исполнителя")]
public int Qualification { get; set; }
}
}

View File

@ -16,6 +16,9 @@ namespace PizzeriaContracts.ViewModels
[DisplayName("Изделие")]
public string PizzaName { get; set; } = string.Empty;
public int ClientId { get; set; }
public int? ImplementerId { get; set; }
[DisplayName("Исполнитель")]
public string? ImplementerFIO { get; set; }
[DisplayName("ФИО клиента")]
public string ClientFIO { get; set; } = string.Empty;

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PizzeriaDataModels.Models
{
public interface IImplementerModel : IId
{
string ImplementerFIO { get; }
string Password { get; }
int WorkExperience { get; }
int Qualification { get; }
}
}

View File

@ -0,0 +1,83 @@
using PizzeriaContracts.BindingModels;
using PizzeriaContracts.SearchModels;
using PizzeriaContracts.StoragesContracts;
using PizzeriaContracts.ViewModels;
using PizzeriaDatabaseImplement.models;
namespace PizzeriaDatabaseImplement.Implements
{
public class ImplementerStorage : IImplementerStorage
{
public List<ImplementerViewModel> GetFullList()
{
using var context = new PizzeriaDatabase();
return context.Implementers
.Select(x => x.GetViewModel)
.ToList();
}
public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model)
{
if (string.IsNullOrEmpty(model.ImplementerFIO) &&
string.IsNullOrEmpty(model.Password))
{
return new();
}
using var context = new PizzeriaDatabase();
return context.Implementers
.Where(x => (string.IsNullOrEmpty(model.ImplementerFIO) || x.ImplementerFIO.Contains(model.ImplementerFIO) &&
string.IsNullOrEmpty(model.Password) || x.ImplementerFIO.Contains(model.Password)))
.Select(x => x.GetViewModel)
.ToList();
}
public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{
if (string.IsNullOrEmpty(model.ImplementerFIO) &&
string.IsNullOrEmpty(model.Password) &&
!model.Id.HasValue)
{
return null;
}
using var context = new PizzeriaDatabase();
return context.Implementers
.FirstOrDefault(x => (string.IsNullOrEmpty(model.ImplementerFIO) || x.ImplementerFIO == model.ImplementerFIO) &&
(string.IsNullOrEmpty(model.Password) || x.Password == model.Password) &&
(!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 PizzeriaDatabase();
context.Implementers.Add(newImplementer);
context.SaveChanges();
return newImplementer.GetViewModel;
}
public ImplementerViewModel? Update(ImplementerBindingModel model)
{
using var context = new PizzeriaDatabase();
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 PizzeriaDatabase();
var element = context.Implementers.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Implementers.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -16,6 +16,7 @@ namespace PizzeriaDatabaseImplement.Implements
return context.Orders
.Include(x => x.Pizza)
.Include(x => x.Client)
.Include(x => x.Implementer)
.Select(x => x.GetViewModel)
.ToList();
}
@ -23,6 +24,9 @@ namespace PizzeriaDatabaseImplement.Implements
{
using var context = new PizzeriaDatabase();
return context.Orders
.Include(x => x.Pizza)
.Include(x => x.Client)
.Include(x => x.Implementer)
.Where(x => (
(!model.Id.HasValue || x.Id == model.Id) &&
(!model.DateFrom.HasValue || x.DateCreate >= model.DateFrom) &&
@ -36,8 +40,12 @@ namespace PizzeriaDatabaseImplement.Implements
{
using var context = new PizzeriaDatabase();
return context.Orders
.FirstOrDefault(x =>
(model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
.Include(x => x.Pizza)
.Include(x => x.Client)
.Include(x => x.Implementer)
.FirstOrDefault(x => (!model.ImplementerId.HasValue || x.ImplementerId == model.ImplementerId) &&
(!model.Status.HasValue || x.Status == model.Status) &&
(!model.Id.HasValue || x.Id == model.Id))?.GetViewModel;
}
public OrderViewModel? Insert(OrderBindingModel model)
{
@ -53,7 +61,6 @@ namespace PizzeriaDatabaseImplement.Implements
{
using var context = new PizzeriaDatabase();
var order = context.Orders.FirstOrDefault(x => x.Id == model.Id);
model.ClientId = order.ClientId;
if (order == null)
{
return null;

View File

@ -0,0 +1,257 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using PizzeriaDatabaseImplement;
#nullable disable
namespace PizzeriaDatabaseImplement.Migrations
{
[DbContext(typeof(PizzeriaDatabase))]
[Migration("20230410193737_AddImplementer")]
partial class AddImplementer
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.3")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("PizzeriaDatabaseImplement.models.Client", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClientFIO")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Clients");
});
modelBuilder.Entity("PizzeriaDatabaseImplement.models.Component", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ComponentName")
.IsRequired()
.HasColumnType("text");
b.Property<double>("Cost")
.HasColumnType("double precision");
b.HasKey("Id");
b.ToTable("Components");
});
modelBuilder.Entity("PizzeriaDatabaseImplement.models.Implementer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ImplementerFIO")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("text");
b.Property<int>("Qualification")
.HasColumnType("integer");
b.Property<int>("WorkExperience")
.HasColumnType("integer");
b.HasKey("Id");
b.ToTable("Implementers");
});
modelBuilder.Entity("PizzeriaDatabaseImplement.models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("ClientId")
.HasColumnType("integer");
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<DateTime>("DateCreate")
.HasColumnType("timestamp with time zone");
b.Property<DateTime?>("DateImplement")
.HasColumnType("timestamp with time zone");
b.Property<int?>("ImplementerId")
.HasColumnType("integer");
b.Property<int>("PizzaId")
.HasColumnType("integer");
b.Property<int>("Status")
.HasColumnType("integer");
b.Property<double>("Sum")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("ClientId");
b.HasIndex("ImplementerId");
b.HasIndex("PizzaId");
b.ToTable("Orders");
});
modelBuilder.Entity("PizzeriaDatabaseImplement.models.Pizza", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("PizzaName")
.IsRequired()
.HasColumnType("text");
b.Property<double>("Price")
.HasColumnType("double precision");
b.HasKey("Id");
b.ToTable("Pizzas");
});
modelBuilder.Entity("PizzeriaDatabaseImplement.models.PizzaComponent", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("ComponentId")
.HasColumnType("integer");
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<int>("PizzaId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ComponentId");
b.HasIndex("PizzaId");
b.ToTable("PizzaComponents");
});
modelBuilder.Entity("PizzeriaDatabaseImplement.models.Order", b =>
{
b.HasOne("PizzeriaDatabaseImplement.models.Client", "Client")
.WithMany("Orders")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("PizzeriaDatabaseImplement.models.Implementer", "Implementer")
.WithMany("Orders")
.HasForeignKey("ImplementerId");
b.HasOne("PizzeriaDatabaseImplement.models.Pizza", "Pizza")
.WithMany("Orders")
.HasForeignKey("PizzaId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Client");
b.Navigation("Implementer");
b.Navigation("Pizza");
});
modelBuilder.Entity("PizzeriaDatabaseImplement.models.PizzaComponent", b =>
{
b.HasOne("PizzeriaDatabaseImplement.models.Component", "Component")
.WithMany("PizzaComponents")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("PizzeriaDatabaseImplement.models.Pizza", "Pizza")
.WithMany("Components")
.HasForeignKey("PizzaId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Component");
b.Navigation("Pizza");
});
modelBuilder.Entity("PizzeriaDatabaseImplement.models.Client", b =>
{
b.Navigation("Orders");
});
modelBuilder.Entity("PizzeriaDatabaseImplement.models.Component", b =>
{
b.Navigation("PizzaComponents");
});
modelBuilder.Entity("PizzeriaDatabaseImplement.models.Implementer", b =>
{
b.Navigation("Orders");
});
modelBuilder.Entity("PizzeriaDatabaseImplement.models.Pizza", b =>
{
b.Navigation("Components");
b.Navigation("Orders");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,68 @@
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace PizzeriaDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class AddImplementer : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "ImplementerId",
table: "Orders",
type: "integer",
nullable: true);
migrationBuilder.CreateTable(
name: "Implementers",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
ImplementerFIO = table.Column<string>(type: "text", nullable: false),
WorkExperience = table.Column<int>(type: "integer", nullable: false),
Qualification = table.Column<int>(type: "integer", nullable: false),
Password = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Implementers", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_Orders_ImplementerId",
table: "Orders",
column: "ImplementerId");
migrationBuilder.AddForeignKey(
name: "FK_Orders_Implementers_ImplementerId",
table: "Orders",
column: "ImplementerId",
principalTable: "Implementers",
principalColumn: "Id");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Orders_Implementers_ImplementerId",
table: "Orders");
migrationBuilder.DropTable(
name: "Implementers");
migrationBuilder.DropIndex(
name: "IX_Orders_ImplementerId",
table: "Orders");
migrationBuilder.DropColumn(
name: "ImplementerId",
table: "Orders");
}
}
}

View File

@ -67,6 +67,33 @@ namespace PizzeriaDatabaseImplement.Migrations
b.ToTable("Components");
});
modelBuilder.Entity("PizzeriaDatabaseImplement.models.Implementer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ImplementerFIO")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("text");
b.Property<int>("Qualification")
.HasColumnType("integer");
b.Property<int>("WorkExperience")
.HasColumnType("integer");
b.HasKey("Id");
b.ToTable("Implementers");
});
modelBuilder.Entity("PizzeriaDatabaseImplement.models.Order", b =>
{
b.Property<int>("Id")
@ -87,6 +114,9 @@ namespace PizzeriaDatabaseImplement.Migrations
b.Property<DateTime?>("DateImplement")
.HasColumnType("timestamp with time zone");
b.Property<int?>("ImplementerId")
.HasColumnType("integer");
b.Property<int>("PizzaId")
.HasColumnType("integer");
@ -100,6 +130,8 @@ namespace PizzeriaDatabaseImplement.Migrations
b.HasIndex("ClientId");
b.HasIndex("ImplementerId");
b.HasIndex("PizzaId");
b.ToTable("Orders");
@ -159,6 +191,10 @@ namespace PizzeriaDatabaseImplement.Migrations
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("PizzeriaDatabaseImplement.models.Implementer", "Implementer")
.WithMany("Orders")
.HasForeignKey("ImplementerId");
b.HasOne("PizzeriaDatabaseImplement.models.Pizza", "Pizza")
.WithMany("Orders")
.HasForeignKey("PizzaId")
@ -167,6 +203,8 @@ namespace PizzeriaDatabaseImplement.Migrations
b.Navigation("Client");
b.Navigation("Implementer");
b.Navigation("Pizza");
});
@ -199,6 +237,11 @@ namespace PizzeriaDatabaseImplement.Migrations
b.Navigation("PizzaComponents");
});
modelBuilder.Entity("PizzeriaDatabaseImplement.models.Implementer", b =>
{
b.Navigation("Orders");
});
modelBuilder.Entity("PizzeriaDatabaseImplement.models.Pizza", b =>
{
b.Navigation("Components");

View File

@ -16,6 +16,7 @@ namespace PizzeriaDatabaseImplement
public virtual DbSet<Component> Components { set; get; }
public virtual DbSet<Pizza> Pizzas { set; get; }
public virtual DbSet<Client> Clients { set; get; }
public virtual DbSet<Implementer> Implementers { set; get; }
public virtual DbSet<PizzaComponent> PizzaComponents { set; get; }
public virtual DbSet<Order> Orders { set; get; }
}

View File

@ -0,0 +1,70 @@
using PizzeriaContracts.BindingModels;
using PizzeriaContracts.ViewModels;
using PizzeriaDataModels.Models;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace PizzeriaDatabaseImplement.models
{
public class Implementer : IImplementerModel
{
public int Id { get; private set; }
[Required]
public string ImplementerFIO { get; private set; }
[Required]
public int WorkExperience { get; private set; }
[Required]
public int Qualification { get; private set; }
[Required]
public string Password { get; private set; }
[ForeignKey("ImplementerId")]
public virtual List<Order> Orders { get; set; } = new();
public static Implementer? Create(ImplementerBindingModel model)
{
if (model == null)
{
return null;
}
return new Implementer()
{
Id = model.Id,
ImplementerFIO = model.ImplementerFIO,
WorkExperience = model.WorkExperience,
Qualification = model.Qualification,
Password = model.Password
};
}
public static Implementer Create(ImplementerViewModel model)
{
return new Implementer
{
Id = model.Id,
ImplementerFIO = model.ImplementerFIO,
WorkExperience = model.WorkExperience,
Qualification = model.Qualification,
Password = model.Password
};
}
public void Update(ImplementerBindingModel model)
{
if (model == null)
{
return;
}
Id = model.Id;
ImplementerFIO = model.ImplementerFIO;
WorkExperience = model.WorkExperience;
Qualification = model.Qualification;
Password = model.Password;
}
public ImplementerViewModel GetViewModel => new()
{
Id = Id,
ImplementerFIO = ImplementerFIO,
WorkExperience = WorkExperience,
Qualification = Qualification,
Password = Password
};
}
}

View File

@ -7,12 +7,15 @@ namespace PizzeriaDatabaseImplement.models
{
public class Order : IOrderModel
{
public int Id { get; private set; }
[Required]
public int PizzaId { get; private set; }
[Required]
public int ClientId { get; private set; }
public int? ImplementerId { get; private set; }
[Required]
public int Count { get; private set; }
@ -29,8 +32,8 @@ namespace PizzeriaDatabaseImplement.models
public virtual Pizza Pizza { get; set; } = new();
public virtual Client Client { get; set; } = new();
public virtual Implementer? Implementer { get; set; } = new();
public int Id { get; private set; }
public static Order? Create(PizzeriaDatabase context, OrderBindingModel? model)
{
@ -45,6 +48,8 @@ namespace PizzeriaDatabaseImplement.models
Pizza = context.Pizzas.FirstOrDefault(x => x.Id == model.PizzaId),
ClientId = model.ClientId,
Client = context.Clients.FirstOrDefault(x => x.Id == model.ClientId),
ImplementerId = model.ImplementerId,
Implementer = context.Implementers.FirstOrDefault(x => x.Id == model.ImplementerId),
Count = model.Count,
Sum = model.Sum,
Status = model.Status,
@ -59,13 +64,9 @@ namespace PizzeriaDatabaseImplement.models
{
return;
}
PizzaId = model.PizzaId;
ClientId = model.ClientId;
Count = model.Count;
Sum = model.Sum;
ImplementerId = model.ImplementerId;
Status = model.Status;
DateCreate = model.DateCreate;
DateImplement = model.DateImplement;
if(DateImplement == null) DateImplement = model.DateImplement;
}
public OrderViewModel GetViewModel => new()
@ -73,6 +74,8 @@ namespace PizzeriaDatabaseImplement.models
Id = Id,
PizzaId = PizzaId,
ClientId = ClientId,
ImplementerId = ImplementerId,
ImplementerFIO = Implementer?.ImplementerFIO,
ClientFIO = Client.ClientFIO,
PizzaName = Pizza.PizzaName,
Count = Count,

View File

@ -0,0 +1,101 @@
using PizzeriaContracts.BindingModels;
using PizzeriaContracts.BusinessLogicsContracts;
using PizzeriaContracts.SearchModels;
using PizzeriaContracts.ViewModels;
using PizzeriaDataModels;
using Microsoft.AspNetCore.Mvc;
namespace PizzeriaRestApi.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
{
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;
}
}
}
}

View File

@ -11,7 +11,9 @@ builder.Logging.AddLog4Net("log4net.config");
builder.Services.AddTransient<IClientStorage, ClientStorage>();
builder.Services.AddTransient<IOrderStorage, OrderStorage>();
builder.Services.AddTransient<IPizzaStorage, PizzaStorage>();
builder.Services.AddTransient<IImplementerStorage, ImplementerStorage>();
builder.Services.AddTransient<IOrderLogic, OrderLogic>();
builder.Services.AddTransient<IImplementerLogic, ImplementerLogic>();
builder.Services.AddTransient<IClientLogic, ClientLogic>();
builder.Services.AddTransient<IPizzaLogic, PizzaLogic>();
builder.Services.AddControllers();