PIbd-21. Makarov D.V. Lab work 06. Hard #15

Closed
DavidMakarov wants to merge 10 commits from hard_lab6 into hard_lab5
46 changed files with 2096 additions and 197 deletions

View File

@ -103,6 +103,7 @@ namespace FlowerShopView
{
var operationResult = _logicO.CreateOrder(new OrderBindingModel
{
ClientId = Convert.ToInt32(comboBoxClient.SelectedValue),
FlowerId = Convert.ToInt32(comboBoxFlower.SelectedValue),
Count = Convert.ToInt32(textBoxCount.Text),
Sum = Convert.ToDouble(textBoxSum.Text)

View File

@ -0,0 +1,172 @@
namespace FlowerShopView
{
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()
{
FioTextBox = new TextBox();
FioLabel = new Label();
PasswordTextBox = new TextBox();
PasswordLabel = new Label();
WorkExperienceLabel = new Label();
WorkExperienceNumericUpDown = new NumericUpDown();
QualificationNumericUpDown = new NumericUpDown();
QualificationLabel = new Label();
CancelButton = new Button();
SaveButton = new Button();
((System.ComponentModel.ISupportInitialize)WorkExperienceNumericUpDown).BeginInit();
((System.ComponentModel.ISupportInitialize)QualificationNumericUpDown).BeginInit();
SuspendLayout();
//
// FioTextBox
//
FioTextBox.Location = new Point(137, 9);
FioTextBox.Margin = new Padding(3, 2, 3, 2);
FioTextBox.Name = "FioTextBox";
FioTextBox.Size = new Size(335, 23);
FioTextBox.TabIndex = 3;
//
// FioLabel
//
FioLabel.AutoSize = true;
FioLabel.Location = new Point(10, 12);
FioLabel.Name = "FioLabel";
FioLabel.Size = new Size(112, 15);
FioLabel.TabIndex = 2;
FioLabel.Text = "ФИО исполнителя:";
//
// PasswordTextBox
//
PasswordTextBox.Location = new Point(137, 40);
PasswordTextBox.Margin = new Padding(3, 2, 3, 2);
PasswordTextBox.Name = "PasswordTextBox";
PasswordTextBox.Size = new Size(335, 23);
PasswordTextBox.TabIndex = 5;
//
// PasswordLabel
//
PasswordLabel.AutoSize = true;
PasswordLabel.Location = new Point(10, 43);
PasswordLabel.Name = "PasswordLabel";
PasswordLabel.Size = new Size(52, 15);
PasswordLabel.TabIndex = 4;
PasswordLabel.Text = "Пароль:";
//
// WorkExperienceLabel
//
WorkExperienceLabel.AutoSize = true;
WorkExperienceLabel.Location = new Point(10, 75);
WorkExperienceLabel.Name = "WorkExperienceLabel";
WorkExperienceLabel.Size = new Size(84, 15);
WorkExperienceLabel.TabIndex = 6;
WorkExperienceLabel.Text = "Опыт работы:";
//
// WorkExperienceNumericUpDown
//
WorkExperienceNumericUpDown.Location = new Point(137, 73);
WorkExperienceNumericUpDown.Margin = new Padding(3, 2, 3, 2);
WorkExperienceNumericUpDown.Name = "WorkExperienceNumericUpDown";
WorkExperienceNumericUpDown.Size = new Size(108, 23);
WorkExperienceNumericUpDown.TabIndex = 8;
//
// QualificationNumericUpDown
//
QualificationNumericUpDown.Location = new Point(137, 106);
QualificationNumericUpDown.Margin = new Padding(3, 2, 3, 2);
QualificationNumericUpDown.Name = "QualificationNumericUpDown";
QualificationNumericUpDown.Size = new Size(108, 23);
QualificationNumericUpDown.TabIndex = 10;
//
// QualificationLabel
//
QualificationLabel.AutoSize = true;
QualificationLabel.Location = new Point(10, 108);
QualificationLabel.Name = "QualificationLabel";
QualificationLabel.Size = new Size(91, 15);
QualificationLabel.TabIndex = 9;
QualificationLabel.Text = "Квалификация:";
//
// CancelButton
//
CancelButton.Location = new Point(353, 142);
CancelButton.Margin = new Padding(3, 2, 3, 2);
CancelButton.Name = "CancelButton";
CancelButton.Size = new Size(119, 30);
CancelButton.TabIndex = 12;
CancelButton.Text = "Отмена";
CancelButton.UseVisualStyleBackColor = true;
CancelButton.Click += CancelButton_Click;
//
// SaveButton
//
SaveButton.Location = new Point(233, 142);
SaveButton.Margin = new Padding(3, 2, 3, 2);
SaveButton.Name = "SaveButton";
SaveButton.Size = new Size(114, 30);
SaveButton.TabIndex = 11;
SaveButton.Text = "Сохранить";
SaveButton.UseVisualStyleBackColor = true;
SaveButton.Click += SaveButton_Click;
//
// FormImplementer
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(482, 183);
Controls.Add(CancelButton);
Controls.Add(SaveButton);
Controls.Add(QualificationNumericUpDown);
Controls.Add(QualificationLabel);
Controls.Add(WorkExperienceNumericUpDown);
Controls.Add(WorkExperienceLabel);
Controls.Add(PasswordTextBox);
Controls.Add(PasswordLabel);
Controls.Add(FioTextBox);
Controls.Add(FioLabel);
Margin = new Padding(3, 2, 3, 2);
Name = "FormImplementer";
Text = "Исполнитель";
Load += FormImplementer_Load;
((System.ComponentModel.ISupportInitialize)WorkExperienceNumericUpDown).EndInit();
((System.ComponentModel.ISupportInitialize)QualificationNumericUpDown).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private TextBox FioTextBox;
private Label FioLabel;
private TextBox PasswordTextBox;
private Label PasswordLabel;
private Label WorkExperienceLabel;
private NumericUpDown WorkExperienceNumericUpDown;
private NumericUpDown QualificationNumericUpDown;
private Label QualificationLabel;
private Button CancelButton;
private Button SaveButton;
}
}

View File

@ -0,0 +1,105 @@
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.BusinessLogicsContracts;
using FlowerShopContracts.SearchModels;
using Microsoft.Extensions.Logging;
namespace FlowerShopView
{
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)
{
FioTextBox.Text = View.ImplementerFIO;
PasswordTextBox.Text = View.Password;
WorkExperienceNumericUpDown.Value = View.WorkExperience;
QualificationNumericUpDown.Value = View.Qualification;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения исполнителя");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void SaveButton_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(FioTextBox.Text))
{
MessageBox.Show("Заполните ФИО", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(PasswordTextBox.Text))
{
MessageBox.Show("Заполните пароль", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение исполнителя");
try
{
var Model = new ImplementerBindingModel
{
Id = _id ?? 0,
ImplementerFIO = FioTextBox.Text,
Password = PasswordTextBox.Text,
WorkExperience = (int)WorkExperienceNumericUpDown.Value,
Qualification = (int)QualificationNumericUpDown.Value
};
var OperationResult = _id.HasValue ? _logic.Update(Model) : _logic.Create(Model);
if (!OperationResult)
{
throw new Exception("Ошибка при создании или обновлении. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения исполнителя");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void CancelButton_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<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,135 @@
namespace FlowerShopView
{
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()
{
ToolsPanel = new Panel();
RefreshButton = new Button();
DeleteButton = new Button();
UpdateButton = new Button();
AddButton = new Button();
DataGridView = new DataGridView();
ToolsPanel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)DataGridView).BeginInit();
SuspendLayout();
//
// ToolsPanel
//
ToolsPanel.Controls.Add(RefreshButton);
ToolsPanel.Controls.Add(DeleteButton);
ToolsPanel.Controls.Add(UpdateButton);
ToolsPanel.Controls.Add(AddButton);
ToolsPanel.Location = new Point(532, 9);
ToolsPanel.Margin = new Padding(3, 2, 3, 2);
ToolsPanel.Name = "ToolsPanel";
ToolsPanel.Size = new Size(116, 320);
ToolsPanel.TabIndex = 3;
//
// RefreshButton
//
RefreshButton.Location = new Point(3, 126);
RefreshButton.Margin = new Padding(3, 2, 3, 2);
RefreshButton.Name = "RefreshButton";
RefreshButton.Size = new Size(110, 27);
RefreshButton.TabIndex = 3;
RefreshButton.Text = "Обновить";
RefreshButton.UseVisualStyleBackColor = true;
RefreshButton.Click += RefreshButton_Click;
//
// DeleteButton
//
DeleteButton.Location = new Point(3, 84);
DeleteButton.Margin = new Padding(3, 2, 3, 2);
DeleteButton.Name = "DeleteButton";
DeleteButton.Size = new Size(110, 27);
DeleteButton.TabIndex = 2;
DeleteButton.Text = "Удалить";
DeleteButton.UseVisualStyleBackColor = true;
DeleteButton.Click += DeleteButton_Click;
//
// UpdateButton
//
UpdateButton.Location = new Point(3, 42);
UpdateButton.Margin = new Padding(3, 2, 3, 2);
UpdateButton.Name = "UpdateButton";
UpdateButton.Size = new Size(110, 27);
UpdateButton.TabIndex = 1;
UpdateButton.Text = "Изменить";
UpdateButton.UseVisualStyleBackColor = true;
UpdateButton.Click += UpdateButton_Click;
//
// AddButton
//
AddButton.Location = new Point(3, 2);
AddButton.Margin = new Padding(3, 2, 3, 2);
AddButton.Name = "AddButton";
AddButton.Size = new Size(110, 27);
AddButton.TabIndex = 0;
AddButton.Text = "Добавить";
AddButton.UseVisualStyleBackColor = true;
AddButton.Click += AddButton_Click;
//
// DataGridView
//
DataGridView.AllowUserToAddRows = false;
DataGridView.AllowUserToDeleteRows = false;
DataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
DataGridView.Location = new Point(10, 9);
DataGridView.Margin = new Padding(3, 2, 3, 2);
DataGridView.Name = "DataGridView";
DataGridView.ReadOnly = true;
DataGridView.RowHeadersWidth = 51;
DataGridView.RowTemplate.Height = 29;
DataGridView.Size = new Size(516, 320);
DataGridView.TabIndex = 2;
//
// FormImplementers
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(653, 338);
Controls.Add(ToolsPanel);
Controls.Add(DataGridView);
Margin = new Padding(3, 2, 3, 2);
Name = "FormImplementers";
Text = "Исполнители";
Load += FormImplementers_Load;
ToolsPanel.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)DataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private Panel ToolsPanel;
private Button RefreshButton;
private Button DeleteButton;
private Button UpdateButton;
private Button AddButton;
private DataGridView DataGridView;
}
}

View File

@ -0,0 +1,111 @@
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
namespace FlowerShopView
{
public partial class FormImplementers : Form
{
private readonly ILogger _logger;
private readonly IImplementerLogic _implementerLogic;
public FormImplementers(ILogger<FormImplementers> Logger, IImplementerLogic ImplementerLogic)
{
InitializeComponent();
_logger = Logger;
_implementerLogic = ImplementerLogic;
}
private void LoadData()
{
try
{
var List = _implementerLogic.ReadList(null);
if (List != null)
{
DataGridView.DataSource = List;
DataGridView.Columns["Id"].Visible = false;
DataGridView.Columns["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка исполнителей");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки исполнителей");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void FormImplementers_Load(object sender, EventArgs e)
{
LoadData();
}
private void AddButton_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 UpdateButton_Click(object sender, EventArgs e)
{
if (DataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormImplementers));
if (service is FormImplementer Form)
{
Form.Id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value);
if (Form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
}
private void DeleteButton_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 (!_implementerLogic.Delete(new ImplementerBindingModel
{
Id = Id
}))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления исполнителя");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void RefreshButton_Click(object sender, EventArgs e)
{
LoadData();
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing"">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<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

@ -34,6 +34,7 @@
КомпонентыToolStripMenuItem = new ToolStripMenuItem();
магазиныToolStripMenuItem = new ToolStripMenuItem();
клиентыToolStripMenuItem = new ToolStripMenuItem();
исполнителиToolStripMenuItem1 = new ToolStripMenuItem();
отчётыToolStripMenuItem = new ToolStripMenuItem();
списокЦветковToolStripMenuItem = new ToolStripMenuItem();
компонентыПоЦветамToolStripMenuItem = new ToolStripMenuItem();
@ -41,14 +42,13 @@
списокМагазиновToolStripMenuItem = new ToolStripMenuItem();
загруженностьМагазиновToolStripMenuItem = new ToolStripMenuItem();
заказыПоДатамToolStripMenuItem = new ToolStripMenuItem();
dataGridView = new DataGridView();
buttonCreateOrder = new Button();
buttonTakeOrderInWork = new Button();
buttonOrderReady = new Button();
buttonIssuedOrder = new Button();
buttonRef = new Button();
пополнениеМагазинаToolStripMenuItem = new ToolStripMenuItem();
продажаЦветовToolStripMenuItem = new ToolStripMenuItem();
запускРаботToolStripMenuItem = new ToolStripMenuItem();
dataGridView = new DataGridView();
buttonCreateOrder = new Button();
buttonIssuedOrder = new Button();
buttonRef = new Button();
menuStrip1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
@ -56,7 +56,7 @@
// menuStrip1
//
menuStrip1.ImageScalingSize = new Size(20, 20);
menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчётыToolStripMenuItem, пополнениеМагазинаToolStripMenuItem, продажаЦветовToolStripMenuItem });
menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчётыToolStripMenuItem, пополнениеМагазинаToolStripMenuItem, продажаЦветовToolStripMenuItem, запускРаботToolStripMenuItem });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Padding = new Padding(7, 3, 0, 3);
@ -66,7 +66,7 @@
//
// справочникиToolStripMenuItem
//
справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { ЦветыToolStripMenuItem, КомпонентыToolStripMenuItem, магазиныToolStripMenuItem, клиентыToolStripMenuItem });
справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { ЦветыToolStripMenuItem, КомпонентыToolStripMenuItem, магазиныToolStripMenuItem, клиентыToolStripMenuItem, исполнителиToolStripMenuItem1 });
справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem";
справочникиToolStripMenuItem.Size = new Size(117, 24);
справочникиToolStripMenuItem.Text = "Справочники";
@ -74,31 +74,38 @@
// ЦветыToolStripMenuItem
//
ЦветыToolStripMenuItem.Name = "ЦветыToolStripMenuItem";
ЦветыToolStripMenuItem.Size = new Size(182, 26);
ЦветыToolStripMenuItem.Size = new Size(224, 26);
ЦветыToolStripMenuItem.Text = "Цветы";
ЦветыToolStripMenuItem.Click += ЦветыToolStripMenuItem_Click;
//
// КомпонентыToolStripMenuItem
//
КомпонентыToolStripMenuItem.Name = "КомпонентыToolStripMenuItem";
КомпонентыToolStripMenuItem.Size = new Size(182, 26);
КомпонентыToolStripMenuItem.Size = new Size(224, 26);
КомпонентыToolStripMenuItem.Text = "Компоненты";
КомпонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click;
//
// магазиныToolStripMenuItem
//
магазиныToolStripMenuItem.Name = агазиныToolStripMenuItem";
магазиныToolStripMenuItem.Size = new Size(182, 26);
магазиныToolStripMenuItem.Size = new Size(224, 26);
магазиныToolStripMenuItem.Text = "Магазины";
магазиныToolStripMenuItem.Click += магазиныToolStripMenuItem_Click;
//
// клиентыToolStripMenuItem
//
клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem";
клиентыToolStripMenuItem.Size = new Size(182, 26);
клиентыToolStripMenuItem.Size = new Size(224, 26);
клиентыToolStripMenuItem.Text = "Клиенты";
клиентыToolStripMenuItem.Click += клиентыToolStripMenuItem_Click;
//
// исполнителиToolStripMenuItem1
//
исполнителиToolStripMenuItem1.Name = сполнителиToolStripMenuItem1";
исполнителиToolStripMenuItem1.Size = new Size(224, 26);
исполнителиToolStripMenuItem1.Text = "Исполнители";
исполнителиToolStripMenuItem1.Click += исполнителиToolStripMenuItem1_Click;
//
// отчётыToolStripMenuItem
//
отчётыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокЦветковToolStripMenuItem, компонентыПоЦветамToolStripMenuItem, списокЗаказовToolStripMenuItem, списокМагазиновToolStripMenuItem, загруженностьМагазиновToolStripMenuItem, заказыПоДатамToolStripMenuItem });
@ -148,6 +155,27 @@
заказыПоДатамToolStripMenuItem.Text = "Заказы по датам";
заказыПоДатамToolStripMenuItem.Click += заказыПоДатамToolStripMenuItem_Click;
//
// пополнениеМагазинаToolStripMenuItem
//
пополнениеМагазинаToolStripMenuItem.Name = "пополнениеМагазинаToolStripMenuItem";
пополнениеМагазинаToolStripMenuItem.Size = new Size(182, 24);
пополнениеМагазинаToolStripMenuItem.Text = "Пополнение магазина";
пополнениеМагазинаToolStripMenuItem.Click += пополнениеМагазинаToolStripMenuItem_Click;
//
// продажаЦветовToolStripMenuItem
//
продажаЦветовToolStripMenuItem.Name = "продажаЦветовToolStripMenuItem";
продажаЦветовToolStripMenuItem.Size = new Size(139, 24);
продажаЦветовToolStripMenuItem.Text = "Продажа цветов";
продажаЦветовToolStripMenuItem.Click += продажаЦветовToolStripMenuItem_Click;
//
// запускРаботToolStripMenuItem
//
запускРаботToolStripMenuItem.Name = апускРаботToolStripMenuItem";
запускРаботToolStripMenuItem.Size = new Size(114, 24);
запускРаботToolStripMenuItem.Text = "Запуск работ";
запускРаботToolStripMenuItem.Click += запускРаботToolStripMenuItem_Click;
//
// dataGridView
//
dataGridView.BackgroundColor = Color.White;
@ -171,31 +199,9 @@
buttonCreateOrder.UseVisualStyleBackColor = true;
buttonCreateOrder.Click += ButtonCreateOrder_Click;
//
// buttonTakeOrderInWork
//
buttonTakeOrderInWork.Location = new Point(886, 147);
buttonTakeOrderInWork.Margin = new Padding(3, 4, 3, 4);
buttonTakeOrderInWork.Name = "buttonTakeOrderInWork";
buttonTakeOrderInWork.Size = new Size(181, 45);
buttonTakeOrderInWork.TabIndex = 3;
buttonTakeOrderInWork.Text = "Отдать на выполнение";
buttonTakeOrderInWork.UseVisualStyleBackColor = true;
buttonTakeOrderInWork.Click += ButtonTakeOrderInWork_Click;
//
// buttonOrderReady
//
buttonOrderReady.Location = new Point(886, 224);
buttonOrderReady.Margin = new Padding(3, 4, 3, 4);
buttonOrderReady.Name = "buttonOrderReady";
buttonOrderReady.Size = new Size(181, 45);
buttonOrderReady.TabIndex = 4;
buttonOrderReady.Text = "Заказ готов";
buttonOrderReady.UseVisualStyleBackColor = true;
buttonOrderReady.Click += ButtonOrderReady_Click;
//
// buttonIssuedOrder
//
buttonIssuedOrder.Location = new Point(886, 307);
buttonIssuedOrder.Location = new Point(886, 146);
buttonIssuedOrder.Margin = new Padding(3, 4, 3, 4);
buttonIssuedOrder.Name = "buttonIssuedOrder";
buttonIssuedOrder.Size = new Size(181, 45);
@ -206,7 +212,7 @@
//
// buttonRef
//
buttonRef.Location = new Point(886, 385);
buttonRef.Location = new Point(886, 224);
buttonRef.Margin = new Padding(3, 4, 3, 4);
buttonRef.Name = "buttonRef";
buttonRef.Size = new Size(181, 45);
@ -215,20 +221,6 @@
buttonRef.UseVisualStyleBackColor = true;
buttonRef.Click += ButtonRef_Click;
//
// пополнениеМагазинаToolStripMenuItem
//
пополнениеМагазинаToolStripMenuItem.Name = "пополнениеМагазинаToolStripMenuItem";
пополнениеМагазинаToolStripMenuItem.Size = new Size(182, 24);
пополнениеМагазинаToolStripMenuItem.Text = "Пополнение магазина";
пополнениеМагазинаToolStripMenuItem.Click += пополнениеМагазинаToolStripMenuItem_Click;
//
// продажаЦветовToolStripMenuItem
//
продажаЦветовToolStripMenuItem.Name = "продажаЦветовToolStripMenuItem";
продажаЦветовToolStripMenuItem.Size = new Size(139, 24);
продажаЦветовToolStripMenuItem.Text = "Продажа цветов";
продажаЦветовToolStripMenuItem.Click += продажаЦветовToolStripMenuItem_Click;
//
// FormMain
//
AutoScaleDimensions = new SizeF(8F, 20F);
@ -236,8 +228,6 @@
ClientSize = new Size(1102, 600);
Controls.Add(buttonRef);
Controls.Add(buttonIssuedOrder);
Controls.Add(buttonOrderReady);
Controls.Add(buttonTakeOrderInWork);
Controls.Add(buttonCreateOrder);
Controls.Add(dataGridView);
Controls.Add(menuStrip1);
@ -253,33 +243,28 @@
PerformLayout();
}
private void ПродажаЦветовToolStripMenuItem_Click(object sender, EventArgs e)
{
throw new NotImplementedException();
}
#endregion
private MenuStrip menuStrip1;
private ToolStripMenuItem справочникиToolStripMenuItem;
private ToolStripMenuItem ЦветыToolStripMenuItem;
private ToolStripMenuItem КомпонентыToolStripMenuItem;
private ToolStripMenuItem справочникиToolStripMenuItem;
private ToolStripMenuItem ЦветыToolStripMenuItem;
private ToolStripMenuItem КомпонентыToolStripMenuItem;
private ToolStripMenuItem отчётыToolStripMenuItem;
private ToolStripMenuItem списокЦветковToolStripMenuItem;
private ToolStripMenuItem компонентыПоЦветамToolStripMenuItem;
private ToolStripMenuItem списокЗаказовToolStripMenuItem;
private DataGridView dataGridView;
private Button buttonCreateOrder;
private Button buttonTakeOrderInWork;
private Button buttonOrderReady;
private Button buttonIssuedOrder;
private Button buttonRef;
private Button buttonCreateOrder;
private Button buttonIssuedOrder;
private Button buttonRef;
private ToolStripMenuItem клиентыToolStripMenuItem;
private ToolStripMenuItem списокМагазиновToolStripMenuItem;
private ToolStripMenuItem загруженностьМагазиновToolStripMenuItem;
private ToolStripMenuItem заказыПоДатамToolStripMenuItem;
private ToolStripMenuItem магазиныToolStripMenuItem;
private ToolStripMenuItem клиентыToolStripMenuItem;
private ToolStripMenuItem пополнениеМагазинаToolStripMenuItem;
private ToolStripMenuItem продажаЦветовToolStripMenuItem;
private ToolStripMenuItem исполнителиToolStripMenuItem1;
private ToolStripMenuItem запускРаботToolStripMenuItem;
}
}

View File

@ -9,12 +9,14 @@ namespace FlowerShopView
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 FlowerShopView
dataGridView.DataSource = list;
dataGridView.Columns["FlowerId"].Visible = false;
dataGridView.Columns["ClientId"].Visible = false;
dataGridView.Columns["ImplementerId"].Visible = false;
}
}
catch (Exception ex)
@ -64,55 +67,6 @@ namespace FlowerShopView
LoadData();
}
}
private void ButtonTakeOrderInWork_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id);
try
{
var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel { Id = id });
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка передачи заказа в работу");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonOrderReady_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'",
id);
try
{
var operationResult = _orderLogic.FinishOrder(new
OrderBindingModel
{ Id = id });
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о готовности заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonIssuedOrder_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
@ -193,6 +147,15 @@ namespace FlowerShopView
}
}
private void клиентыToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormClients));
if (service is FormClients form)
{
form.ShowDialog();
}
}
private void заказыПоДатамToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportGroupedOrders));
@ -211,14 +174,6 @@ namespace FlowerShopView
}
}
private void клиентыToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormClients));
if (service is FormClients form)
{
form.ShowDialog();
}
}
private void пополнениеМагазинаToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormMakeSupply));
@ -236,5 +191,20 @@ namespace FlowerShopView
form.ShowDialog();
}
}
private void исполнителиToolStripMenuItem1_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormImplementers));
if (service is FormImplementers form)
{
form.ShowDialog();
}
}
private void запускРаботToolStripMenuItem_Click(object sender, EventArgs e)
{
_workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic);
MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}

View File

@ -32,6 +32,7 @@ namespace FlowerShopView
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["ShopName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["ViewFlowers"].Visible = false;
dataGridView.Columns["ShopFlowers"].Visible = false;
}
_logger.LogInformation("Shops loading");

View File

@ -40,6 +40,7 @@ namespace FlowerShopView
services.AddTransient<IFlowerStorage, FlowerStorage>();
services.AddTransient<IShopStorage, ShopStorage>();
services.AddTransient<IClientStorage, ClientStorage>();
services.AddTransient<IImplementerStorage, ImplementerStorage>();
services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
@ -48,6 +49,8 @@ namespace FlowerShopView
services.AddTransient<IReportLogic, ReportLogic>();
services.AddTransient<IReportLogic, ReportLogic>();
services.AddTransient<IClientLogic, ClientLogic>();
services.AddTransient<IImplementerLogic, ImplementerLogic>();
services.AddTransient<IWorkProcess, WorkModeling>();
services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
services.AddTransient<AbstractSaveToPdf, SaveToPdf>();
@ -78,6 +81,8 @@ namespace FlowerShopView
services.AddTransient<FormReportOrders>();
services.AddTransient<FormReportFlowerComponents>();
services.AddTransient<FormClients>();
services.AddTransient<FormImplementer>();
services.AddTransient<FormImplementers>();
}
}
}

View File

@ -0,0 +1,128 @@
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.BusinessLogicsContracts;
using FlowerShopContracts.SearchModels;
using FlowerShopContracts.StoragesContracts;
using FlowerShopContracts.ViewModels;
using Microsoft.Extensions.Logging;
namespace FlowerShopBusinessLogic.BusinessLogics
{
public class ImplementerLogic : IImplementerLogic
{
private readonly ILogger _logger;
private readonly IImplementerStorage _implementerStorage;
public ImplementerLogic(ILogger<IImplementerLogic> Logger, IImplementerStorage ImplementerStorage)
{
_logger = Logger;
_implementerStorage = ImplementerStorage;
}
public List<ImplementerViewModel>? ReadList(ImplementerSearchModel? Model)
{
_logger.LogInformation("ReadList. ImplementerFIO: {ImplementerFIO}. Password: {Password}. Id: {Id}",
Model?.ImplementerFIO, Model?.Password?.Length, Model?.Id);
var List = Model == null ? _implementerStorage.GetFullList() : _implementerStorage.GetFilteredList(Model);
if (List == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count: {Count}", List.Count);
return List;
}
public ImplementerViewModel? ReadElement(ImplementerSearchModel Model)
{
if (Model is null)
{
throw new ArgumentNullException(nameof(Model));
}
_logger.LogInformation("ReadElement. ImplementerFIO: {ImplementerFIO}. Password: {Password}. Id: {Id}",
Model?.ImplementerFIO, Model?.Password?.Length, Model?.Id);
var Element = _implementerStorage.GetElement(Model);
if (Element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id: {Id}", Element.Id);
return Element;
}
public bool Create(ImplementerBindingModel Model)
{
CheckModel(Model);
if (_implementerStorage.Insert(Model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Update(ImplementerBindingModel Model)
{
CheckModel(Model);
if (_implementerStorage.Update(Model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool Delete(ImplementerBindingModel Model)
{
CheckModel(Model, false);
_logger.LogInformation("Delete. Id:{Id}", Model.Id);
if (_implementerStorage.Delete(Model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
private void CheckModel(ImplementerBindingModel Model, bool WithParams = true)
{
if (Model == null)
throw new ArgumentNullException(nameof(Model));
if (!WithParams)
return;
if (string.IsNullOrEmpty(Model.ImplementerFIO))
throw new ArgumentNullException("Нет ФИО исполнителя", nameof(Model.ImplementerFIO));
if (string.IsNullOrEmpty(Model.Password))
throw new ArgumentNullException("Нет пароля исполнителя", nameof(Model.Password));
if (Model.WorkExperience < 0)
throw new ArgumentNullException("Стаж должен быть неотрицательным целым числом", nameof(Model.WorkExperience));
if (Model.Qualification < 0)
throw new ArgumentNullException("Квалификация должна быть неотрицательным целым числом", nameof(Model.Qualification));
_logger.LogInformation("Implementer. ImplementerFIO: {ImplementerFIO}. Password: {Password}. WorkExperience: {WorkExperience}. Qualification: {Qualification}. Id: {Id}",
Model.ImplementerFIO, Model.Password, Model.WorkExperience, Model.Qualification, Model.Id);
var Implementer = _implementerStorage.GetElement(new ImplementerSearchModel
{
ImplementerFIO = Model.ImplementerFIO
});
if (Implementer != null && Implementer.Id != Model.Id)
{
throw new InvalidOperationException("Исполнитель с таким ФИО уже есть");
}
}
}
}

View File

@ -16,7 +16,8 @@ namespace FlowerShopBusinessLogic.BusinessLogics
private readonly IFlowerStorage _flowerStorage;
private readonly IShopStorage _shopStorage;
private readonly IShopLogic _shopLogic;
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage, IFlowerStorage flowerStorage, IShopStorage shopStorage, IShopLogic shopLogic)
static readonly object _locker = new object();
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage, IFlowerStorage flowerStorage, IShopStorage shopStorage, IShopLogic shopLogic)
{
_logger = logger;
_orderStorage = orderStorage;
@ -36,7 +37,28 @@ namespace FlowerShopBusinessLogic.BusinessLogics
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public bool CreateOrder(OrderBindingModel model)
public OrderViewModel? ReadElement(OrderSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadList. ClientId: {ClientId}. Status: {Status}. ImplementerId: {ImplementerId}. DateFrom: {DateFrom}. DateTo: {DateTo}. OrderId: {Id}",
model?.ClientId, model?.Status, model?.ImplementerId, model?.DateFrom, model?.DateTo, model?.Id);
var Order = _orderStorage.GetElement(model);
if (Order == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id: {Id}", Order.Id);
return Order;
}
public bool CreateOrder(OrderBindingModel model)
{
CheckModel(model);
if (model.Status != OrderStatus.Неизвестен)
@ -52,7 +74,10 @@ namespace FlowerShopBusinessLogic.BusinessLogics
}
public bool TakeOrderInWork(OrderBindingModel model)
{
return ToNextStatus(model, OrderStatus.Выполняется);
lock (_locker)
{
return ToNextStatus(model, OrderStatus.Выполняется);
}
}
public bool FinishOrder(OrderBindingModel model)
{
@ -78,13 +103,16 @@ namespace FlowerShopBusinessLogic.BusinessLogics
model.FlowerId = element.FlowerId;
model.DateCreate = element.DateCreate;
model.DateImplement = element.DateImplement;
model.ClientId = element.ClientId;
if (!model.ImplementerId.HasValue) model.ImplementerId = element.ImplementerId;
model.Status = element.Status;
model.Count = element.Count;
model.Sum = element.Sum;
if (model.Status != orderStatus - 1)
if ((model.Status + 1 != orderStatus && model.Status != OrderStatus.Ожидание)
|| (model.Status == OrderStatus.Ожидание && orderStatus != OrderStatus.Выдан))
{
_logger.LogWarning("Status update to " + orderStatus + " operation failed");
_logger.LogWarning("Change status operation failed");
return false;
}
if (orderStatus == OrderStatus.Выдан)
@ -96,12 +124,17 @@ namespace FlowerShopBusinessLogic.BusinessLogics
}
if (!SupplyFlowers(flower, model.Count))
{
_logger.LogWarning("Change status operation failed. Flowers delivery operation failed");
return false;
}
_logger.LogWarning("Change status operation failed. Ice creams delivery operation failed");
model.Status = OrderStatus.Ожидание;
if (_orderStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
}
return false;
}
}
model.Status = orderStatus;
if (model.Status == OrderStatus.Готов)
if (model.Status == OrderStatus.Выдан)
{
model.DateImplement = DateTime.Now;
}

View File

@ -0,0 +1,195 @@
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.BusinessLogicsContracts;
using FlowerShopContracts.SearchModels;
using FlowerShopContracts.ViewModels;
using FlowerShopDataModels.Enums;
using Microsoft.Extensions.Logging;
namespace FlowerShopBusinessLogic.BusinessLogics
{
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;
}
List<OrderViewModel>? orders = new();
orders.AddRange(_orderLogic.ReadList(new() { Status = OrderStatus.Принят }) ?? new());
orders.AddRange(_orderLogic.ReadList(new() { Status = OrderStatus.Выполняется }) ?? new());
orders.AddRange(_orderLogic.ReadList(new() { Status = OrderStatus.Ожидание }) ?? new());
if (orders.Count == 0)
{
_logger.LogWarning("DoWork. Orders is empty");
return;
}
_logger.LogDebug("DoWork for {Count} orders", orders.Count);
foreach (var implementer in implementers)
{
Task.Run(() => WorkerWorkAsync(implementer, orders));
}
}
private async Task WorkerWorkAsync(ImplementerViewModel implementer, List<OrderViewModel> orders)
{
if (_orderLogic == null || implementer == null)
{
return;
}
await RunWaitingOrders(implementer);
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);
bool AcquireResult = _orderLogic.TakeOrderInWork(new OrderBindingModel
{
Id = order.Id,
ImplementerId = implementer.Id
});
if (!AcquireResult)
{
_logger.LogDebug("WorkerWorkAsync. Worker {Id} tried to get order {Order} but it's already acquired by other worker", implementer.Id, order.Id);
continue;
}
// делаем работу
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
});
_logger.LogDebug("DoWork. Order {Order} delivery", order.Id);
_orderLogic.DeliveryOrder(new OrderBindingModel
{
Id = order.Id
});
// отдыхаем
Thread.Sleep(implementer.Qualification * _rnd.Next(10, 100));
}
// кто-то мог уже перехватить заказ, игнорируем ошибку
catch (InvalidOperationException ex)
{
_logger.LogWarning(ex, "Error try get work");
}
// заканчиваем выполнение имитации в случае иной ошибки
catch (Exception ex)
{
_logger.LogError(ex, "Error while do work");
throw;
}
}
});
}
private async Task RunOrderInWork(ImplementerViewModel Implementer)
{
if (_orderLogic == null || Implementer == null)
return;
try
{
var RunOrder = await Task.Run(() => _orderLogic.ReadElement(new OrderSearchModel
{
ImplementerId = Implementer.Id,
Status = OrderStatus.Выполняется
}));
if (RunOrder == null)
{
return;
}
_logger.LogDebug("RunOrderInWork. Worker {Id} back to order {Order}", Implementer.Id, RunOrder.Id);
Thread.Sleep(Implementer.WorkExperience * _rnd.Next(100, 300) * RunOrder.Count);
_logger.LogDebug("RunOrderInWork. Worker {Id} finish order {Order}", Implementer.Id, RunOrder.Id);
_orderLogic.FinishOrder(new OrderBindingModel
{
Id = RunOrder.Id
});
_logger.LogDebug("DoWork. Order {Order} delivery", RunOrder.Id);
_orderLogic.DeliveryOrder(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;
}
}
private async Task RunWaitingOrders(ImplementerViewModel implementer)
{
if (_orderLogic == null || implementer == null)
{
return;
}
var waitingOrders = await Task.Run(() => _orderLogic.ReadList(new OrderSearchModel
{
ImplementerId = implementer.Id,
Status = OrderStatus.Ожидание
}));
if (waitingOrders == null || waitingOrders.Count == 0)
{
return;
}
_logger.LogDebug("RunWaitingOrders for {Count} orders. Implementer: {id}.", waitingOrders.Count, implementer.Id);
foreach (var waitingOrder in waitingOrders)
{
try
{
_logger.LogInformation("RunWaitingOrders. Order {Order} delivery", waitingOrder.Id);
_orderLogic.DeliveryOrder(new OrderBindingModel
{
Id = waitingOrder.Id
});
_logger.LogDebug("DoWork. Order {Order} delivery", waitingOrder.Id);
_orderLogic.DeliveryOrder(new OrderBindingModel
{
Id = waitingOrder.Id
});
}
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 FlowerShopDataModels.Models;
namespace FlowerShopContracts.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

@ -8,7 +8,8 @@ namespace FlowerShopContracts.BindingModels
public int Id { get; set; }
public int FlowerId { get; set; }
public int ClientId { get; set; }
public int Count { get; set; }
public int? ImplementerId { get; set; }
public int Count { get; set; }
public double Sum { get; set; }
public OrderStatus Status { get; set; } = OrderStatus.Неизвестен;
public DateTime DateCreate { get; set; } = DateTime.Now;

View File

@ -0,0 +1,15 @@
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.SearchModels;
using FlowerShopContracts.ViewModels;
namespace FlowerShopContracts.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 FlowerShopContracts.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,8 @@
namespace FlowerShopContracts.BusinessLogicsContracts
{
public interface IWorkProcess
{
void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic);
}
}

View File

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

View File

@ -1,10 +1,14 @@
namespace FlowerShopContracts.SearchModels
using FlowerShopDataModels.Enums;
namespace FlowerShopContracts.SearchModels
{
public class OrderSearchModel
{
public int? Id { get; set; }
public int? ClientId { get; set; }
public int? ImplementerId { get; set; }
public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }
public OrderStatus? Status { get; set; }
}
}

View File

@ -0,0 +1,16 @@
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.SearchModels;
using FlowerShopContracts.ViewModels;
namespace FlowerShopContracts.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,18 @@
using FlowerShopDataModels.Models;
using System.ComponentModel;
namespace FlowerShopContracts.ViewModels
{
public class ImplementerViewModel : IImplementerModel
{
public int Id { get; set; }
[DisplayName("ФИО исполнителя")]
public string ImplementerFIO { get; set; } = string.Empty;
[DisplayName("Пароль")]
public string Password { get; set; } = string.Empty;
[DisplayName("Опыт исполнителя")]
public int WorkExperience { get; set; }
[DisplayName("Квалификация исполнителя")]
public int Qualification { get; set; }
}
}

View File

@ -10,12 +10,15 @@ namespace FlowerShopContracts.ViewModels
public int Id { get; set; }
public int FlowerId { get; set; }
public int ClientId { get; set; }
public int? ImplementerId { get; set; }
[DisplayName("Изделие")]
public string FlowerName { get; set; } = string.Empty;
[DisplayName("ФИО клиента")]
public string ClientFIO { get; set; } = string.Empty;
[DisplayName("Количество")]
public int Count { get; set; }
[DisplayName("ФИО исполнителя")]
public string ImplementerFIO { get; set; }=string.Empty;
[DisplayName("Количество")]
public int Count { get; set; }
[DisplayName("Сумма")]
public double Sum { get; set; }
[DisplayName("Статус")]

View File

@ -6,6 +6,7 @@
Принят = 0,
Выполняется = 1,
Готов = 2,
Выдан = 3
Выдан = 3,
Ожидание = 4
}
}

View File

@ -0,0 +1,11 @@
namespace FlowerShopDataModels.Models
{
public interface IImplementerModel : IId
{
string ImplementerFIO { get; }
string Password { get; }
int WorkExperience { get; }
int Qualification { get; }
}
}

View File

@ -6,6 +6,7 @@ namespace FlowerShopDataModels.Models
{
int FlowerId { get; }
int ClientId { get; }
int? ImplementerId { get; }
int Count { get; }
double Sum { get; }
OrderStatus Status { get; }

View File

@ -23,5 +23,6 @@ namespace FlowerShopDatabaseImplement
public virtual DbSet<Shop> Shops { set; get; }
public virtual DbSet<ShopFlower> ShopFlowers { set; get; }
public virtual DbSet<Client> Clients { set; get; }
public virtual DbSet<Implementer> Implementers { set; get; }
}
}

View File

@ -0,0 +1,90 @@
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.SearchModels;
using FlowerShopContracts.StoragesContracts;
using FlowerShopContracts.ViewModels;
using FlowerShopDatabaseImplement.Models;
namespace FlowerShopDatabaseImplement.Implements
{
public class ImplementerStorage : IImplementerStorage
{
public List<ImplementerViewModel> GetFullList()
{
using var Context = new FlowerShopDatabase();
return Context.Implementers.Select(x => x.GetViewModel).ToList();
}
public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model)
{
if (string.IsNullOrEmpty(model.ImplementerFIO))
{
return new();
}
using var Context = new FlowerShopDatabase();
return Context.Implementers.Where(x => x.ImplementerFIO.Contains(model.ImplementerFIO)).Select(x => x.GetViewModel).ToList();
}
public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{
if (string.IsNullOrEmpty(model.ImplementerFIO) && !model.Id.HasValue)
{
return null;
}
using var Context = new FlowerShopDatabase();
return Context.Implementers.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.ImplementerFIO) && x.ImplementerFIO == model.ImplementerFIO && (!string.IsNullOrEmpty(model.Password) ? x.Password == model.Password : true)) ||
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public ImplementerViewModel? Insert(ImplementerBindingModel model)
{
var NewImplementer = Implementer.Create(model);
if (NewImplementer == null)
{
return null;
}
using var Context = new FlowerShopDatabase();
Context.Implementers.Add(NewImplementer);
Context.SaveChanges();
return NewImplementer.GetViewModel;
}
public ImplementerViewModel? Update(ImplementerBindingModel model)
{
using var Context = new FlowerShopDatabase();
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 FlowerShopDatabase();
var Implementer = Context.Implementers.FirstOrDefault(rec => rec.Id == model.Id);
if (Implementer == null)
{
return null;
}
Context.Implementers.Remove(Implementer);
Context.SaveChanges();
return Implementer.GetViewModel;
}
}
}

View File

@ -3,6 +3,7 @@ using FlowerShopContracts.SearchModels;
using FlowerShopContracts.StoragesContracts;
using FlowerShopContracts.ViewModels;
using FlowerShopDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
namespace FlowerShopDatabaseImplement.Implements
{
@ -12,95 +13,96 @@ namespace FlowerShopDatabaseImplement.Implements
{
using var context = new FlowerShopDatabase();
return context.Orders
.Select(x => AccessFlowerStorage(x.GetViewModel))
.ToList();
.Include(x => x.Flower)
.Include(x => x.Client)
.Include(x => x.Implementer)
.Select(x => x.GetViewModel)
.ToList();
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
if (!model.Id.HasValue && !model.DateFrom.HasValue && !model.DateTo.HasValue && !model.ClientId.HasValue)
{
return new();
}
using var context = new FlowerShopDatabase();
if (model.DateFrom.HasValue)
{
return context.Orders
.Include(x => x.Flower)
.Include(x => x.Client)
.Include(x => x.Implementer)
.Where(x => (x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo)
&& (!model.ClientId.HasValue || x.ClientId == model.ClientId))
.Select(x => AccessFlowerStorage(x.GetViewModel)).ToList();
&& (!model.ClientId.HasValue || x.ClientId == model.ClientId))
.Select(x => x.GetViewModel)
.ToList();
}
return context.Orders
.Include(x => x.Flower)
.Include(x => x.Client)
.Include(x => x.Implementer)
.Where(x => (model.Id.HasValue && x.Id == model.Id)
|| (model.ClientId.HasValue && x.ClientId == model.ClientId))
.Select(x => AccessFlowerStorage(x.GetViewModel)).ToList();
|| (model.ClientId.HasValue && x.ClientId == model.ClientId)
|| (model.ImplementerId.HasValue && x.ImplementerId == model.ImplementerId)
|| (model.Status.HasValue && x.Status == model.Status))
.Select(x => x.GetViewModel)
.ToList();
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
if (!model.Id.HasValue && !model.ImplementerId.HasValue && !model.Status.HasValue)
return null;
}
using var context = new FlowerShopDatabase();
return AccessFlowerStorage(context.Orders.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel);
return context.Orders
.Include(x => x.Flower)
.Include(x => x.Client)
.Include(x => x.Implementer)
.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id)
|| (model.ImplementerId.HasValue && model.Status.HasValue && x.ImplementerId == model.ImplementerId && x.Status == model.Status))?
.GetViewModel;
}
public OrderViewModel? Insert(OrderBindingModel model)
{
if (model == null)
return null;
var newOrder = Order.Create(model);
if (newOrder == null)
{
return null;
}
using var context = new FlowerShopDatabase();
context.Orders.Add(newOrder);
context.SaveChanges();
return AccessFlowerStorage(newOrder.GetViewModel);
return context.Orders.Include(x => x.Flower).Include(x => x.Client).Include(x => x.Implementer).FirstOrDefault(x => x.Id == newOrder.Id)?.GetViewModel;
}
public OrderViewModel? Update(OrderBindingModel model)
{
using var context = new FlowerShopDatabase();
var order = context.Orders.FirstOrDefault(x => x.Id ==
model.Id);
var order = context.Orders.FirstOrDefault(x => x.Id == model.Id);
if (order == null)
{
return null;
}
order.Update(model);
context.SaveChanges();
return AccessFlowerStorage(order.GetViewModel);
return context.Orders.Include(x => x.Flower).Include(x => x.Client).Include(x => x.Implementer).FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
}
public OrderViewModel? Delete(OrderBindingModel model)
{
using var context = new FlowerShopDatabase();
var element = context.Orders.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Orders.Remove(element);
context.SaveChanges();
return AccessFlowerStorage(element.GetViewModel);
}
return null;
}
var order = context.Orders.Include(x => x.Flower).Include(x => x.Client).Include(x => x.Implementer).FirstOrDefault(rec => rec.Id == model.Id);
public static OrderViewModel AccessFlowerStorage(OrderViewModel model)
{
if (model == null)
if (order == null)
return null;
using var context = new FlowerShopDatabase();
foreach (var Flower in context.Flowers)
{
if (Flower.Id == model.FlowerId)
{
model.FlowerName = Flower.FlowerName;
break;
}
}
foreach (var client in context.Clients)
{
if (client.Id == model.ClientId)
{
model.ClientFIO = client.ClientFIO;
return model;
}
}
return model;
context.Orders.Remove(order);
context.SaveChanges();
return order.GetViewModel;
}
}
}

View File

@ -12,7 +12,7 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace FlowerShopDatabaseImplement.Migrations
{
[DbContext(typeof(FlowerShopDatabase))]
[Migration("20240517110214_InitCreate")]
[Migration("20240617101659_InitCreate")]
partial class InitCreate
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
@ -115,6 +115,33 @@ namespace FlowerShopDatabaseImplement.Migrations
b.ToTable("FlowerComponents");
});
modelBuilder.Entity("FlowerShopDatabaseImplement.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("FlowerShopDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
@ -138,6 +165,9 @@ namespace FlowerShopDatabaseImplement.Migrations
b.Property<int>("FlowerId")
.HasColumnType("integer");
b.Property<int?>("ImplementerId")
.HasColumnType("integer");
b.Property<int>("Status")
.HasColumnType("integer");
@ -150,6 +180,8 @@ namespace FlowerShopDatabaseImplement.Migrations
b.HasIndex("FlowerId");
b.HasIndex("ImplementerId");
b.ToTable("Orders");
});
@ -239,9 +271,15 @@ namespace FlowerShopDatabaseImplement.Migrations
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("FlowerShopDatabaseImplement.Models.Implementer", "Implementer")
.WithMany("Order")
.HasForeignKey("ImplementerId");
b.Navigation("Client");
b.Navigation("Flower");
b.Navigation("Implementer");
});
modelBuilder.Entity("FlowerShopDatabaseImplement.Models.ShopFlower", b =>
@ -280,6 +318,11 @@ namespace FlowerShopDatabaseImplement.Migrations
b.Navigation("Orders");
});
modelBuilder.Entity("FlowerShopDatabaseImplement.Models.Implementer", b =>
{
b.Navigation("Order");
});
modelBuilder.Entity("FlowerShopDatabaseImplement.Models.Shop", b =>
{
b.Navigation("Flowers");

View File

@ -53,6 +53,22 @@ namespace FlowerShopDatabaseImplement.Migrations
table.PrimaryKey("PK_Flowers", x => x.Id);
});
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),
Password = table.Column<string>(type: "text", nullable: false),
WorkExperience = table.Column<int>(type: "integer", nullable: false),
Qualification = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Implementers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Shops",
columns: table => new
@ -104,6 +120,7 @@ namespace FlowerShopDatabaseImplement.Migrations
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
FlowerId = table.Column<int>(type: "integer", nullable: false),
ClientId = table.Column<int>(type: "integer", nullable: false),
ImplementerId = table.Column<int>(type: "integer", nullable: true),
Count = table.Column<int>(type: "integer", nullable: false),
Sum = table.Column<double>(type: "double precision", nullable: false),
Status = table.Column<int>(type: "integer", nullable: false),
@ -125,6 +142,11 @@ namespace FlowerShopDatabaseImplement.Migrations
principalTable: "Flowers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Orders_Implementers_ImplementerId",
column: x => x.ImplementerId,
principalTable: "Implementers",
principalColumn: "Id");
});
migrationBuilder.CreateTable(
@ -174,6 +196,11 @@ namespace FlowerShopDatabaseImplement.Migrations
table: "Orders",
column: "FlowerId");
migrationBuilder.CreateIndex(
name: "IX_Orders_ImplementerId",
table: "Orders",
column: "ImplementerId");
migrationBuilder.CreateIndex(
name: "IX_ShopFlowers_FlowerId",
table: "ShopFlowers",
@ -202,6 +229,9 @@ namespace FlowerShopDatabaseImplement.Migrations
migrationBuilder.DropTable(
name: "Clients");
migrationBuilder.DropTable(
name: "Implementers");
migrationBuilder.DropTable(
name: "Flowers");

View File

@ -113,6 +113,33 @@ namespace FlowerShopDatabaseImplement.Migrations
b.ToTable("FlowerComponents");
});
modelBuilder.Entity("FlowerShopDatabaseImplement.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("FlowerShopDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
@ -136,6 +163,9 @@ namespace FlowerShopDatabaseImplement.Migrations
b.Property<int>("FlowerId")
.HasColumnType("integer");
b.Property<int?>("ImplementerId")
.HasColumnType("integer");
b.Property<int>("Status")
.HasColumnType("integer");
@ -148,6 +178,8 @@ namespace FlowerShopDatabaseImplement.Migrations
b.HasIndex("FlowerId");
b.HasIndex("ImplementerId");
b.ToTable("Orders");
});
@ -237,9 +269,15 @@ namespace FlowerShopDatabaseImplement.Migrations
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("FlowerShopDatabaseImplement.Models.Implementer", "Implementer")
.WithMany("Order")
.HasForeignKey("ImplementerId");
b.Navigation("Client");
b.Navigation("Flower");
b.Navigation("Implementer");
});
modelBuilder.Entity("FlowerShopDatabaseImplement.Models.ShopFlower", b =>
@ -278,6 +316,11 @@ namespace FlowerShopDatabaseImplement.Migrations
b.Navigation("Orders");
});
modelBuilder.Entity("FlowerShopDatabaseImplement.Models.Implementer", b =>
{
b.Navigation("Order");
});
modelBuilder.Entity("FlowerShopDatabaseImplement.Models.Shop", b =>
{
b.Navigation("Flowers");

View File

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

View File

@ -10,11 +10,13 @@ namespace FlowerShopDatabaseImplement.Models
{
public int Id { get; private set; }
[Required]
public int FlowerId { get; private set; }
public virtual Flower Flower { get; set; }
public int FlowerId { get; private set; }
[Required]
public int ClientId { get; private set; }
public virtual Client Client { get; set; }
public int? ImplementerId { get; private set; }
public virtual Implementer? Implementer { get; set; }
[Required]
public int Count { get; set; }
[Required]
@ -35,6 +37,7 @@ namespace FlowerShopDatabaseImplement.Models
Id = model.Id,
FlowerId = model.FlowerId,
ClientId = model.ClientId,
ImplementerId = model.ImplementerId,
Count = model.Count,
Sum = model.Sum,
Status = model.Status,
@ -48,6 +51,7 @@ namespace FlowerShopDatabaseImplement.Models
{
return;
}
ImplementerId = model.ImplementerId;
Status = model.Status;
DateImplement = model.DateImplement;
}
@ -56,6 +60,10 @@ namespace FlowerShopDatabaseImplement.Models
Id = Id,
FlowerId = FlowerId,
ClientId = ClientId,
ImplementerId = ImplementerId,
FlowerName = Flower.FlowerName,
ClientFIO = Client.ClientFIO,
ImplementerFIO = Implementer?.ImplementerFIO,
Count = Count,
Sum = Sum,
Status = Status,

View File

@ -10,11 +10,13 @@ namespace FlowerShopFileImplement
private readonly string OrderFileName = "Order.xml";
private readonly string FlowerFileName = "Flower.xml";
private readonly string ClientFileName = "Client.xml";
private readonly string ImplementerFileName = "Implementer.xml";
private readonly string ShopFileName = "Shop.xml";
public List<Component> Components { get; private set; }
public List<Order> Orders { get; private set; }
public List<Flower> Flowers { get; private set; }
public List<Client> Clients { get; private set; }
public List<Implementer> Implementers { get; private set; }
public List<Shop> Shops { get; private set; }
public static DataFileSingleton GetInstance()
{
@ -28,6 +30,7 @@ namespace FlowerShopFileImplement
public void SaveFlowers() => SaveData(Flowers, FlowerFileName, "Flowers", x => x.GetXElement);
public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement);
public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", x => x.GetXElement);
public void SaveImplementers() => SaveData(Implementers, ImplementerFileName, "Implementers", x => x.GetXElement);
public void SaveShops() => SaveData(Shops, ShopFileName, "Shops", x => x.GetXElement);
private DataFileSingleton()
{
@ -35,6 +38,7 @@ namespace FlowerShopFileImplement
Flowers = LoadData(FlowerFileName, "Flower", x => Flower.Create(x)!)!;
Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!;
Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!;
Implementers = LoadData(ImplementerFileName, "Implementer", x => Implementer.Create(x)!)!;
Shops = LoadData(ShopFileName, "Shop", x => Shop.Create(x)!)!;
}
private static List<T>? LoadData<T>(string filename, string xmlNodeName, Func<XElement, T> selectFunction)

View File

@ -0,0 +1,97 @@
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.SearchModels;
using FlowerShopContracts.StoragesContracts;
using FlowerShopContracts.ViewModels;
using FlowerShopFileImplement.Models;
namespace FlowerShopFileImplement.Implements
{
public class ImplementerStorage : IImplementerStorage
{
private readonly DataFileSingleton _source;
public ImplementerStorage()
{
_source = DataFileSingleton.GetInstance();
}
public List<ImplementerViewModel> GetFullList()
{
return _source.Implementers.Select(x => x.GetViewModel).ToList();
}
public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel Model)
{
if (Model == null)
return new();
if (Model.Id.HasValue)
{
var Res = GetElement(Model);
return Res != null ? new() { Res } : new();
}
if (Model.ImplementerFIO != null)
{
return _source.Implementers
.Where(x => x.ImplementerFIO.Equals(Model.ImplementerFIO))
.Select(x => x.GetViewModel)
.ToList();
}
return new();
}
public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{
if (model.Id.HasValue)
return _source.Implementers.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
if (model.ImplementerFIO != null && model.Password != null)
return _source.Implementers.FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO) && x.Password.Equals(model.Password))?.GetViewModel;
if (model.ImplementerFIO != null)
return _source.Implementers.FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO))?.GetViewModel;
return null;
}
public ImplementerViewModel? Insert(ImplementerBindingModel model)
{
model.Id = _source.Implementers.Count > 0 ? _source.Implementers.Max(x => x.Id) + 1 : 1;
var Res = Implementer.Create(model);
if (Res != null)
{
_source.Implementers.Add(Res);
_source.SaveImplementers();
}
return Res?.GetViewModel;
}
public ImplementerViewModel? Update(ImplementerBindingModel model)
{
var Res = _source.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (Res != null)
{
Res.Update(model);
_source.SaveImplementers();
}
return Res?.GetViewModel;
}
public ImplementerViewModel? Delete(ImplementerBindingModel model)
{
var Res = _source.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (Res != null)
{
_source.Implementers.Remove(Res);
_source.SaveImplementers();
}
return Res?.GetViewModel;
}
}
}

View File

@ -22,12 +22,16 @@ namespace FlowerShopFileImplement.Implements
if (model.DateFrom.HasValue)
{
return source.Orders
.Where(x => (x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo) && (!model.ClientId.HasValue || x.ClientId == model.ClientId))
.Where(x => (x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo)
&& (!model.ClientId.HasValue || x.ClientId == model.ClientId)
&& (!model.ImplementerId.HasValue || x.ImplementerId == model.ImplementerId))
.Select(GetViewModel)
.ToList();
}
return source.Orders
.Where(x => (model.Id.HasValue && x.Id == model.Id) || (model.ClientId.HasValue && x.ClientId == model.ClientId))
.Where(x => (model.Id.HasValue && x.Id == model.Id)
|| (model.ClientId.HasValue && x.ClientId == model.ClientId)
|| (model.ImplementerId.HasValue && x.ImplementerId == model.ImplementerId))
.Select(GetViewModel)
.ToList();
}

View File

@ -0,0 +1,70 @@
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.ViewModels;
using FlowerShopDataModels.Models;
using System.Xml.Linq;
namespace FlowerShopFileImplement.Models
{
public class Implementer : IImplementerModel
{
public int Id { get; private set; }
public string ImplementerFIO { get; private set; } = string.Empty;
public string Password { get; private set; } = string.Empty;
public int WorkExperience { get; private set; }
public int Qualification { get; private set; }
public static Implementer? Create(ImplementerBindingModel Model)
{
if (Model == null)
return null;
return new()
{
Id = Model.Id,
ImplementerFIO = Model.ImplementerFIO,
Password = Model.Password,
WorkExperience = Model.WorkExperience,
Qualification = Model.Qualification,
};
}
public static Implementer? Create(XElement Element)
{
if (Element == null)
return null;
return new()
{
Id = Convert.ToInt32(Element.Attribute("Id")!.Value),
ImplementerFIO = Element.Element("ImplementerFIO")!.Value,
Password = Element.Element("Password")!.Value,
WorkExperience = Convert.ToInt32(Element.Element("WorkExperience")!.Value),
Qualification = Convert.ToInt32(Element.Element("Qualification")!.Value),
};
}
public void Update(ImplementerBindingModel Model)
{
if (Model == null)
return;
ImplementerFIO = Model.ImplementerFIO;
Password = Model.Password;
WorkExperience = Model.WorkExperience;
Qualification = Model.Qualification;
}
public ImplementerViewModel GetViewModel => new()
{
Id = Id,
ImplementerFIO = ImplementerFIO,
Password = Password,
WorkExperience = WorkExperience,
Qualification = Qualification,
};
public XElement GetXElement => new(
"Implementer",
new XAttribute("Id", Id),
new XElement("ImplementerFIO", ImplementerFIO),
new XElement("Password", Password),
new XElement("WorkExperience", WorkExperience),
new XElement("Qualification", Qualification)
);
}
}

View File

@ -11,6 +11,7 @@ namespace FlowerShopFileImplement.Models
public int Id { get; private set; }
public int FlowerId { get; private set; }
public int ClientId { get; private set; }
public int? ImplementerId { get; private set; }
public int Count { get; private set; }
public double Sum { get; set; }
public OrderStatus Status { get; set; }
@ -27,6 +28,7 @@ namespace FlowerShopFileImplement.Models
Id = model.Id,
FlowerId = model.FlowerId,
ClientId = model.ClientId,
ImplementerId = model.ImplementerId,
Count = model.Count,
Sum = model.Sum,
Status = model.Status,
@ -45,6 +47,7 @@ namespace FlowerShopFileImplement.Models
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
FlowerId = Convert.ToInt32(element.Element("FlowerId")!.Value),
ClientId = Convert.ToInt32(element.Element("ClientId")!.Value),
ImplementerId = Convert.ToInt32(element.Element("ImplementerId")!.Value),
Count = Convert.ToInt32(element.Element("Count")!.Value),
Sum = Convert.ToDouble(element.Element("Sum")!.Value),
Status = (OrderStatus) Enum.Parse(typeof(OrderStatus), element.Element("Status")!.Value),
@ -61,6 +64,7 @@ namespace FlowerShopFileImplement.Models
Id = model.Id;
FlowerId = model.FlowerId;
ClientId = model.ClientId;
ImplementerId = model.ImplementerId;
Count = model.Count;
Sum = model.Sum;
Status = model.Status;
@ -72,6 +76,7 @@ namespace FlowerShopFileImplement.Models
Id = Id,
FlowerId = FlowerId,
ClientId = ClientId,
ImplementerId = ImplementerId,
Count = Count,
Sum = Sum,
Status = Status,
@ -83,7 +88,8 @@ namespace FlowerShopFileImplement.Models
new XAttribute("Id", Id),
new XElement("FlowerId", FlowerId.ToString()),
new XElement("ClientId", ClientId.ToString()),
new XElement("Count", Count.ToString()),
new XElement("ImplementerId", ImplementerId.ToString()),
new XElement("Count", Count.ToString()),
new XElement("Sum", Sum.ToString()),
new XElement("Status", Status.ToString()),
new XElement("DateCreate", DateCreate.ToString()),

View File

@ -9,6 +9,7 @@ namespace FlowerShopListImplement
public List<Order> Orders { get; set; }
public List<Flower> Flowers { get; set; }
public List<Client> Clients { get; set; }
public List<Implementer> Implementers { get; set; }
public List<Shop> Shops { get; set; }
private DataListSingleton()
{
@ -16,6 +17,7 @@ namespace FlowerShopListImplement
Orders = new List<Order>();
Flowers = new List<Flower>();
Clients = new List<Client>();
Implementers = new List<Implementer>();
Shops = new List<Shop>();
}
public static DataListSingleton GetInstance()

View File

@ -0,0 +1,104 @@
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.SearchModels;
using FlowerShopContracts.StoragesContracts;
using FlowerShopContracts.ViewModels;
using FlowerShopListImplement.Models;
namespace FlowerShopListImplement.Implements
{
public class ImplementerStorage : IImplementerStorage
{
private readonly DataListSingleton _source;
public ImplementerStorage()
{
_source = DataListSingleton.GetInstance();
}
public List<ImplementerViewModel> GetFullList()
{
var Result = new List<ImplementerViewModel>();
foreach (var Implementer in _source.Implementers)
{
Result.Add(Implementer.GetViewModel);
}
return Result;
}
public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model)
{
if (string.IsNullOrEmpty(model.ImplementerFIO))
return new();
return _source.Implementers
.Where(x => (!string.IsNullOrEmpty(model.ImplementerFIO) && x.ImplementerFIO.Contains(model.ImplementerFIO)))
.Select(x => x.GetViewModel)
.ToList();
}
public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{
foreach (var Implementer in _source.Implementers)
{
if ((model.Id.HasValue && Implementer.Id == model.Id) ||
(!string.IsNullOrEmpty(model.ImplementerFIO) && Implementer.ImplementerFIO == model.ImplementerFIO))
{
return Implementer.GetViewModel;
}
}
return null;
}
public ImplementerViewModel? Insert(ImplementerBindingModel model)
{
model.Id = 1;
foreach (var Implementer in _source.Implementers)
{
if (model.Id <= Implementer.Id)
{
model.Id = Implementer.Id + 1;
}
}
var NewImplementer = Implementer.Create(model);
if (NewImplementer == null)
return null;
_source.Implementers.Add(NewImplementer);
return NewImplementer.GetViewModel;
}
public ImplementerViewModel? Update(ImplementerBindingModel model)
{
foreach (var Implementer in _source.Implementers)
{
if (Implementer.Id == model.Id)
{
Implementer.Update(model);
return Implementer.GetViewModel;
}
}
return null;
}
public ImplementerViewModel? Delete(ImplementerBindingModel model)
{
for (int i = 0; i < _source.Implementers.Count; ++i)
{
if (_source.Implementers[i].Id == model.Id)
{
var Implementer = _source.Implementers[i];
_source.Implementers.RemoveAt(i);
return Implementer.GetViewModel;
}
}
return null;
}
}
}

View File

@ -28,12 +28,16 @@ namespace FlowerShopListImplement.Implements
if (model.DateFrom.HasValue)
{
return _source.Orders
.Where(x => (x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo) && (!model.ClientId.HasValue || x.ClientId == model.ClientId))
.Where(x => (x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo)
&& (!model.ClientId.HasValue || x.ClientId == model.ClientId)
&& (!model.ImplementerId.HasValue || x.ImplementerId == model.ImplementerId))
.Select(x => AttachNames(x.GetViewModel))
.ToList();
}
return _source.Orders
.Where(x => (model.Id.HasValue && x.Id == model.Id) || (model.ClientId.HasValue && x.ClientId == model.ClientId))
.Where(x => (model.Id.HasValue && x.Id == model.Id)
|| (model.ClientId.HasValue && x.ClientId == model.ClientId)
|| (model.ImplementerId.HasValue && x.ImplementerId == model.ImplementerId))
.Select(x => AttachNames(x.GetViewModel))
.ToList();
}

View File

@ -0,0 +1,49 @@
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.ViewModels;
using FlowerShopDataModels.Models;
namespace FlowerShopListImplement.Models
{
public class Implementer : IImplementerModel
{
public int Id { get; private set; }
public string ImplementerFIO { get; private set; }
public string Password { get; private set; }
public int WorkExperience { get; private set; }
public int Qualification { get; private set; }
public static Implementer? Create(ImplementerBindingModel? model)
{
if (model == null)
{
return null;
}
return new Implementer()
{
Id = model.Id,
ImplementerFIO = model.ImplementerFIO,
Password = model.Password,
WorkExperience = model.WorkExperience,
Qualification = model.Qualification,
};
}
public void Update(ImplementerBindingModel? model)
{
if (model == null)
{
return;
}
ImplementerFIO = model.ImplementerFIO;
Password = model.Password;
WorkExperience = model.WorkExperience;
Qualification = model.Qualification;
}
public ImplementerViewModel GetViewModel => new()
{
Id = Id,
ImplementerFIO = ImplementerFIO,
Password = Password,
WorkExperience = WorkExperience,
Qualification = Qualification,
};
}
}

View File

@ -10,6 +10,7 @@ namespace FlowerShopListImplement.Models
public int Id { get; private set; }
public int FlowerId { get; private set; }
public int ClientId { get; private set; }
public int? ImplementerId { get; private set; }
public int Count { get; set; }
public double Sum { get; private set; }
public OrderStatus Status { get; set; }
@ -26,6 +27,7 @@ namespace FlowerShopListImplement.Models
Id = model.Id,
FlowerId = model.FlowerId,
ClientId = model.ClientId,
ImplementerId = model.ImplementerId,
Count = model.Count,
Sum = model.Sum,
Status = model.Status,
@ -42,6 +44,7 @@ namespace FlowerShopListImplement.Models
Id = model.Id;
FlowerId = model.FlowerId;
ClientId = model.ClientId;
ImplementerId = model.ImplementerId;
Count = model.Count;
Sum = model.Sum;
Status = model.Status;
@ -53,6 +56,7 @@ namespace FlowerShopListImplement.Models
Id = Id,
FlowerId = FlowerId,
ClientId = ClientId,
ImplementerId = ImplementerId,
Count = Count,
Sum = Sum,
Status = Status,

View File

@ -0,0 +1,100 @@
using DocumentFormat.OpenXml.Office2010.Excel;
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.BusinessLogicsContracts;
using FlowerShopContracts.SearchModels;
using FlowerShopContracts.ViewModels;
using FlowerShopDataModels.Enums;
using Microsoft.AspNetCore.Mvc;
namespace FlowerShopRestApi.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;
}
}
}
}