ПИбд-23 Салин Олег Алексеевич Лабораторная работа №6 (Усложненная) #23

Closed
Oleja123 wants to merge 13 commits from Lab6_Hard into Lab5_Hard
52 changed files with 2527 additions and 570 deletions

View File

@ -0,0 +1,162 @@
namespace IceCreamShop
{
partial class ImplementerForm
{
/// <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();
PasswordTextBox = new TextBox();
QualificationTextBox = new TextBox();
WorkExperienceTextBox = new TextBox();
label1 = new Label();
label2 = new Label();
label3 = new Label();
label4 = new Label();
SaveButton = new Button();
CancelButton = new Button();
SuspendLayout();
//
// FIOTextBox
//
FIOTextBox.Location = new Point(124, 19);
FIOTextBox.Name = "FIOTextBox";
FIOTextBox.Size = new Size(411, 27);
FIOTextBox.TabIndex = 0;
//
// PasswordTextBox
//
PasswordTextBox.Location = new Point(124, 52);
PasswordTextBox.Name = "PasswordTextBox";
PasswordTextBox.Size = new Size(411, 27);
PasswordTextBox.TabIndex = 1;
//
// QualificationTextBox
//
QualificationTextBox.Location = new Point(124, 85);
QualificationTextBox.Name = "QualificationTextBox";
QualificationTextBox.Size = new Size(411, 27);
QualificationTextBox.TabIndex = 2;
//
// WorkExperienceTextBox
//
WorkExperienceTextBox.Location = new Point(124, 118);
WorkExperienceTextBox.Name = "WorkExperienceTextBox";
WorkExperienceTextBox.Size = new Size(411, 27);
WorkExperienceTextBox.TabIndex = 3;
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(9, 19);
label1.Name = "label1";
label1.Size = new Size(42, 20);
label1.TabIndex = 4;
label1.Text = "ФИО";
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(9, 52);
label2.Name = "label2";
label2.Size = new Size(62, 20);
label2.TabIndex = 5;
label2.Text = "Пароль";
//
// label3
//
label3.AutoSize = true;
label3.Location = new Point(9, 85);
label3.Name = "label3";
label3.Size = new Size(111, 20);
label3.TabIndex = 6;
label3.Text = "Квалификация";
//
// label4
//
label4.AutoSize = true;
label4.Location = new Point(9, 118);
label4.Name = "label4";
label4.Size = new Size(99, 20);
label4.TabIndex = 7;
label4.Text = "Стаж работы";
//
// SaveButton
//
SaveButton.Location = new Point(341, 151);
SaveButton.Name = "SaveButton";
SaveButton.Size = new Size(94, 29);
SaveButton.TabIndex = 8;
SaveButton.Text = "Сохранить";
SaveButton.UseVisualStyleBackColor = true;
SaveButton.Click += SaveButton_Click;
//
// CancelButton
//
CancelButton.Location = new Point(441, 151);
CancelButton.Name = "CancelButton";
CancelButton.Size = new Size(94, 29);
CancelButton.TabIndex = 9;
CancelButton.Text = "Отмена";
CancelButton.UseVisualStyleBackColor = true;
CancelButton.Click += CancelButton_Click;
//
// ImplementerForm
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(548, 186);
Controls.Add(CancelButton);
Controls.Add(SaveButton);
Controls.Add(label4);
Controls.Add(label3);
Controls.Add(label2);
Controls.Add(label1);
Controls.Add(WorkExperienceTextBox);
Controls.Add(QualificationTextBox);
Controls.Add(PasswordTextBox);
Controls.Add(FIOTextBox);
Name = "ImplementerForm";
Text = "Исполнитель";
Load += ImplementerForm_Load;
ResumeLayout(false);
PerformLayout();
}
#endregion
private TextBox FIOTextBox;
private TextBox PasswordTextBox;
private TextBox QualificationTextBox;
private TextBox WorkExperienceTextBox;
private Label label1;
private Label label2;
private Label label3;
private Label label4;
private Button SaveButton;
private Button CancelButton;
}
}

View File

@ -0,0 +1,109 @@
using IceCreamShopContracts.BindingModels;
using IceCreamShopContracts.BusinessLogicsContracts;
using IceCreamShopContracts.SearchModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace IceCreamShop
{
public partial class ImplementerForm : Form
{
private readonly ILogger _logger;
private readonly IImplementerLogic _logic;
private int? _id;
public int Id { set { _id = value; } }
public ImplementerForm(ILogger<ImplementerForm> logger, IImplementerLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void ImplementerForm_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
try
{
_logger.LogInformation("Получение исполнителя");
var view = _logic.ReadElement(new ImplementerSearchModel
{
Id =
_id.Value
});
if (view != null)
{
FIOTextBox.Text = view.ImplementerFIO;
PasswordTextBox.Text = view.Password;
QualificationTextBox.Text = view.Qualification.ToString();
WorkExperienceTextBox.Text = view.WorkExperience.ToString();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения исполнителя");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void SaveButton_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(FIOTextBox.Text))
{
MessageBox.Show("Заполните ФИО", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(PasswordTextBox.Text))
{
MessageBox.Show("Заполните пароль", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение компонента");
try
{
var model = new ImplementerBindingModel
{
Id = _id ?? 0,
ImplementerFIO = FIOTextBox.Text,
Password = PasswordTextBox.Text,
Qualification = Convert.ToInt32(QualificationTextBox.Text),
WorkExperience = Convert.ToInt32(WorkExperienceTextBox.Text),
};
var operationResult = _id.HasValue ? _logic.Update(model) :
_logic.Create(model);
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение",
MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения исполнителя");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void CancelButton_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

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,114 @@
namespace IceCreamShop
{
partial class ImplementersForm
{
/// <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()
{
dataGridView1 = new DataGridView();
CreateButton = new Button();
ChangeButton = new Button();
DeleteButton = new Button();
RefreshButton = new Button();
((System.ComponentModel.ISupportInitialize)dataGridView1).BeginInit();
SuspendLayout();
//
// dataGridView1
//
dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView1.Location = new Point(12, 12);
dataGridView1.Name = "dataGridView1";
dataGridView1.RowHeadersWidth = 51;
dataGridView1.RowTemplate.Height = 29;
dataGridView1.Size = new Size(565, 426);
dataGridView1.TabIndex = 0;
//
// CreateButton
//
CreateButton.Location = new Point(583, 12);
CreateButton.Name = "CreateButton";
CreateButton.Size = new Size(205, 29);
CreateButton.TabIndex = 1;
CreateButton.Text = "Создать";
CreateButton.UseVisualStyleBackColor = true;
CreateButton.Click += CreateButton_Click;
//
// ChangeButton
//
ChangeButton.Location = new Point(583, 47);
ChangeButton.Name = "ChangeButton";
ChangeButton.Size = new Size(205, 29);
ChangeButton.TabIndex = 2;
ChangeButton.Text = "Изменить";
ChangeButton.UseVisualStyleBackColor = true;
ChangeButton.Click += ChangeButton_Click;
//
// DeleteButton
//
DeleteButton.Location = new Point(583, 82);
DeleteButton.Name = "DeleteButton";
DeleteButton.Size = new Size(205, 29);
DeleteButton.TabIndex = 3;
DeleteButton.Text = "Удалить";
DeleteButton.UseVisualStyleBackColor = true;
DeleteButton.Click += DeleteButton_Click;
//
// RefreshButton
//
RefreshButton.Location = new Point(583, 117);
RefreshButton.Name = "RefreshButton";
RefreshButton.Size = new Size(205, 29);
RefreshButton.TabIndex = 4;
RefreshButton.Text = "Обновить";
RefreshButton.UseVisualStyleBackColor = true;
RefreshButton.Click += RefreshButton_Click;
//
// ImplementersForm
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(RefreshButton);
Controls.Add(DeleteButton);
Controls.Add(ChangeButton);
Controls.Add(CreateButton);
Controls.Add(dataGridView1);
Name = "ImplementersForm";
Text = "Исполнители";
Load += ImplementersForm_Load;
((System.ComponentModel.ISupportInitialize)dataGridView1).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView dataGridView1;
private Button CreateButton;
private Button ChangeButton;
private Button DeleteButton;
private Button RefreshButton;
}
}

View File

@ -0,0 +1,125 @@
using IceCreamShopContracts.BindingModels;
using IceCreamShopContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace IceCreamShop
{
public partial class ImplementersForm : Form
{
private readonly ILogger _logger;
private readonly IImplementerLogic _logic;
public ImplementersForm(ILogger<ImplementersForm> logger, IImplementerLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void ImplementersForm_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
dataGridView1.DataSource = list;
dataGridView1.Columns["Id"].Visible = false;
dataGridView1.Columns["ImplementerFIO"].AutoSizeMode =
DataGridViewAutoSizeColumnMode.Fill;
dataGridView1.Columns["Password"].AutoSizeMode =
DataGridViewAutoSizeColumnMode.Fill;
dataGridView1.Columns["Qualification"].AutoSizeMode =
DataGridViewAutoSizeColumnMode.Fill;
dataGridView1.Columns["WorkExperience"].AutoSizeMode =
DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка компонентов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки исполнителей");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void CreateButton_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(ImplementerForm));
if (service is ImplementerForm form)
{
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
private void ChangeButton_Click(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows.Count == 1)
{
var service =
Program.ServiceProvider?.GetService(typeof(ImplementerForm));
if (service is ImplementerForm form)
{
form.Id =
Convert.ToInt32(dataGridView1.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
}
private void DeleteButton_Click(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
int id =
Convert.ToInt32(dataGridView1.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Удаление компонента");
try
{
if (!_logic.Delete(new ImplementerBindingModel
{
Id = id
}))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления исполнителя");
MessageBox.Show(ex.Message, "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void RefreshButton_Click(object sender, EventArgs e)
{
LoadData();
}
}
}

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

@ -1,24 +1,24 @@
namespace IceCreamShop
{
partial class MainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
partial class MainForm
{
/// <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);
}
/// <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
@ -33,25 +33,22 @@
КомпонентыStripMenuItem = new ToolStripMenuItem();
МороженноеStripMenuItem = new ToolStripMenuItem();
клиентыToolStripMenuItem = new ToolStripMenuItem();
магазиныToolStripMenuItem1 = new ToolStripMenuItem();
поставкиToolStripMenuItem1 = new ToolStripMenuItem();
товарыToolStripMenuItem = new ToolStripMenuItem();
исполнителиToolStripMenuItem = new ToolStripMenuItem();
отчетыToolStripMenuItem = new ToolStripMenuItem();
списокМороженногоToolStripMenuItem = new ToolStripMenuItem();
компонентыПоМороженнымToolStripMenuItem = new ToolStripMenuItem();
списокЗаказовToolStripMenuItem = new ToolStripMenuItem();
запускРаботToolStripMenuItem = new ToolStripMenuItem();
DataGridView = new DataGridView();
CreateOrderButton = new Button();
IssuedButton = new Button();
RefreshButton = new Button();
магазиныToolStripMenuItem = new ToolStripMenuItem();
поставкиToolStripMenuItem = new ToolStripMenuItem();
товарыToolStripMenuItem = new ToolStripMenuItem();
списокМагазиновToolStripMenuItem = new ToolStripMenuItem();
мороженноеПоМагазинамToolStripMenuItem = new ToolStripMenuItem();
заказыПоДатамToolStripMenuItem = new ToolStripMenuItem();
магазиныToolStripMenuItem = new ToolStripMenuItem();
поставкиToolStripMenuItem = new ToolStripMenuItem();
продажиToolStripMenuItem = new ToolStripMenuItem();
DataGridView = new DataGridView();
CreateOrderButton = new Button();
TakeInWorkButton = new Button();
ReadyButton = new Button();
IssuedButton = new Button();
RefreshButton = new Button();
menuStrip1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)DataGridView).BeginInit();
SuspendLayout();
@ -59,7 +56,7 @@
// menuStrip1
//
menuStrip1.ImageScalingSize = new Size(20, 20);
menuStrip1.Items.AddRange(new ToolStripItem[] { ToolStripMenu, отчетыToolStripMenuItem });
menuStrip1.Items.AddRange(new ToolStripItem[] { ToolStripMenu, отчетыToolStripMenuItem, запускРаботToolStripMenuItem });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Padding = new Padding(6, 3, 0, 3);
@ -69,7 +66,7 @@
//
// ToolStripMenu
//
ToolStripMenu.DropDownItems.AddRange(new ToolStripItem[] { КомпонентыStripMenuItem, МороженноеStripMenuItem, клиентыToolStripMenuItem, магазиныToolStripMenuItem1, поставкиToolStripMenuItem1, товарыToolStripMenuItem });
ToolStripMenu.DropDownItems.AddRange(new ToolStripItem[] { КомпонентыStripMenuItem, МороженноеStripMenuItem, клиентыToolStripMenuItem, исполнителиToolStripMenuItem, магазиныToolStripMenuItem, поставкиToolStripMenuItem, товарыToolStripMenuItem });
ToolStripMenu.Name = "ToolStripMenu";
ToolStripMenu.Size = new Size(117, 24);
ToolStripMenu.Text = "Справочники";
@ -95,26 +92,12 @@
клиентыToolStripMenuItem.Text = "Клиенты";
клиентыToolStripMenuItem.Click += клиентыToolStripMenuItem_Click;
//
// магазиныToolStripMenuItem1
// исполнителиToolStripMenuItem
//
магазиныToolStripMenuItem1.Name = агазиныToolStripMenuItem1";
магазиныToolStripMenuItem1.Size = new Size(224, 26);
магазиныToolStripMenuItem1.Text = "Магазины";
магазиныToolStripMenuItem1.Click += магазиныToolStripMenuItem_Click;
//
// поставкиToolStripMenuItem1
//
поставкиToolStripMenuItem1.Name = "поставкиToolStripMenuItem1";
поставкиToolStripMenuItem1.Size = new Size(224, 26);
поставкиToolStripMenuItem1.Text = "Поставки";
поставкиToolStripMenuItem1.Click += поставкиToolStripMenuItem_Click;
//
// товарыToolStripMenuItem
//
товарыToolStripMenuItem.Name = оварыToolStripMenuItem";
товарыToolStripMenuItem.Size = new Size(224, 26);
товарыToolStripMenuItem.Text = "Товары";
товарыToolStripMenuItem.Click += продажиToolStripMenuItem_Click;
исполнителиToolStripMenuItem.Name = сполнителиToolStripMenuItem";
исполнителиToolStripMenuItem.Size = new Size(224, 26);
исполнителиToolStripMenuItem.Text = "Исполнители";
исполнителиToolStripMenuItem.Click += исполнителиToolStripMenuItem_Click;
//
// отчетыToolStripMenuItem
//
@ -144,47 +127,12 @@
списокЗаказовToolStripMenuItem.Text = "Список заказов";
списокЗаказовToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click;
//
// списокМагазиновToolStripMenuItem
// запускРаботToolStripMenuItem
//
списокМагазиновToolStripMenuItem.Name = "списокМагазиновToolStripMenuItem";
списокМагазиновToolStripMenuItem.Size = new Size(305, 26);
списокМагазиновToolStripMenuItem.Text = "Список магазинов";
списокМагазиновToolStripMenuItem.Click += списокМагазиновToolStripMenuItem_Click;
//
// мороженноеПоМагазинамToolStripMenuItem
//
мороженноеПоМагазинамToolStripMenuItem.Name = ороженноеПоМагазинамToolStripMenuItem";
мороженноеПоМагазинамToolStripMenuItem.Size = new Size(305, 26);
мороженноеПоМагазинамToolStripMenuItem.Text = "Мороженное по магазинам";
мороженноеПоМагазинамToolStripMenuItem.Click += мороженноеПоМагазинамToolStripMenuItem_Click;
//
// заказыПоДатамToolStripMenuItem
//
заказыПоДатамToolStripMenuItem.Name = аказыПоДатамToolStripMenuItem";
заказыПоДатамToolStripMenuItem.Size = new Size(305, 26);
заказыПоДатамToolStripMenuItem.Text = "Заказы по датам";
заказыПоДатамToolStripMenuItem.Click += заказыПоДатамToolStripMenuItem_Click;
//
// магазиныToolStripMenuItem
//
магазиныToolStripMenuItem.Name = агазиныToolStripMenuItem";
магазиныToolStripMenuItem.Size = new Size(186, 26);
магазиныToolStripMenuItem.Text = "Магазины";
магазиныToolStripMenuItem.Click += магазиныToolStripMenuItem_Click;
//
// поставкиToolStripMenuItem
//
поставкиToolStripMenuItem.Name = "поставкиToolStripMenuItem";
поставкиToolStripMenuItem.Size = new Size(186, 26);
поставкиToolStripMenuItem.Text = "Поставки";
поставкиToolStripMenuItem.Click += поставкиToolStripMenuItem_Click;
//
// продажиToolStripMenuItem
//
продажиToolStripMenuItem.Name = "продажиToolStripMenuItem";
продажиToolStripMenuItem.Size = new Size(186, 26);
продажиToolStripMenuItem.Text = "Продажи";
продажиToolStripMenuItem.Click += продажиToolStripMenuItem_Click;
запускРаботToolStripMenuItem.Name = апускРаботToolStripMenuItem";
запускРаботToolStripMenuItem.Size = new Size(114, 24);
запускРаботToolStripMenuItem.Text = "Запуск работ";
запускРаботToolStripMenuItem.Click += запускРаботToolStripMenuItem_Click;
//
// DataGridView
//
@ -205,29 +153,9 @@
CreateOrderButton.UseVisualStyleBackColor = true;
CreateOrderButton.Click += CreateOrderButton_Click;
//
// TakeInWorkButton
//
TakeInWorkButton.Location = new Point(1025, 67);
TakeInWorkButton.Name = "TakeInWorkButton";
TakeInWorkButton.Size = new Size(259, 29);
TakeInWorkButton.TabIndex = 3;
TakeInWorkButton.Text = "Отдать заказ в работу";
TakeInWorkButton.UseVisualStyleBackColor = true;
TakeInWorkButton.Click += TakeInWorkButton_Click;
//
// ReadyButton
//
ReadyButton.Location = new Point(1025, 101);
ReadyButton.Name = "ReadyButton";
ReadyButton.Size = new Size(259, 29);
ReadyButton.TabIndex = 4;
ReadyButton.Text = "Заказ готов";
ReadyButton.UseVisualStyleBackColor = true;
ReadyButton.Click += ReadyButton_Click;
//
// IssuedButton
//
IssuedButton.Location = new Point(1025, 136);
IssuedButton.Location = new Point(1024, 66);
IssuedButton.Name = "IssuedButton";
IssuedButton.Size = new Size(259, 29);
IssuedButton.TabIndex = 5;
@ -237,7 +165,7 @@
//
// RefreshButton
//
RefreshButton.Location = new Point(1025, 171);
RefreshButton.Location = new Point(1025, 101);
RefreshButton.Name = "RefreshButton";
RefreshButton.Size = new Size(259, 29);
RefreshButton.TabIndex = 6;
@ -245,6 +173,48 @@
RefreshButton.UseVisualStyleBackColor = true;
RefreshButton.Click += RefreshButton_Click;
//
// магазиныToolStripMenuItem
//
магазиныToolStripMenuItem.Name = агазиныToolStripMenuItem";
магазиныToolStripMenuItem.Size = new Size(224, 26);
магазиныToolStripMenuItem.Text = "Магазины";
магазиныToolStripMenuItem.Click += магазиныToolStripMenuItem_Click;
//
// поставкиToolStripMenuItem
//
поставкиToolStripMenuItem.Name = "поставкиToolStripMenuItem";
поставкиToolStripMenuItem.Size = new Size(224, 26);
поставкиToolStripMenuItem.Text = "Поставки";
поставкиToolStripMenuItem.Click += поставкиToolStripMenuItem_Click;
//
// товарыToolStripMenuItem
//
товарыToolStripMenuItem.Name = оварыToolStripMenuItem";
товарыToolStripMenuItem.Size = new Size(224, 26);
товарыToolStripMenuItem.Text = "Товары";
товарыToolStripMenuItem.Click += продажиToolStripMenuItem_Click;
//
// списокМагазиновToolStripMenuItem
//
списокМагазиновToolStripMenuItem.Name = "списокМагазиновToolStripMenuItem";
списокМагазиновToolStripMenuItem.Size = new Size(305, 26);
списокМагазиновToolStripMenuItem.Text = "Список магазинов";
списокМагазиновToolStripMenuItem.Click += списокМагазиновToolStripMenuItem_Click;
//
// мороженноеПоМагазинамToolStripMenuItem
//
мороженноеПоМагазинамToolStripMenuItem.Name = ороженноеПоМагазинамToolStripMenuItem";
мороженноеПоМагазинамToolStripMenuItem.Size = new Size(305, 26);
мороженноеПоМагазинамToolStripMenuItem.Text = "Мороженное по магазинам";
мороженноеПоМагазинамToolStripMenuItem.Click += списокМороженногоToolStripMenuItem_Click;
//
// заказыПоДатамToolStripMenuItem
//
заказыПоДатамToolStripMenuItem.Name = аказыПоДатамToolStripMenuItem";
заказыПоДатамToolStripMenuItem.Size = new Size(305, 26);
заказыПоДатамToolStripMenuItem.Text = "Заказы по датам";
заказыПоДатамToolStripMenuItem.Click += заказыПоДатамToolStripMenuItem_Click;
//
// MainForm
//
AutoScaleDimensions = new SizeF(8F, 20F);
@ -252,8 +222,6 @@
ClientSize = new Size(1296, 451);
Controls.Add(RefreshButton);
Controls.Add(IssuedButton);
Controls.Add(ReadyButton);
Controls.Add(TakeInWorkButton);
Controls.Add(CreateOrderButton);
Controls.Add(DataGridView);
Controls.Add(menuStrip1);
@ -271,28 +239,25 @@
#endregion
private MenuStrip menuStrip1;
private ToolStripMenuItem ToolStripMenu;
private ToolStripMenuItem КомпонентыStripMenuItem;
private ToolStripMenuItem МороженноеStripMenuItem;
private DataGridView DataGridView;
private Button CreateOrderButton;
private Button TakeInWorkButton;
private Button ReadyButton;
private Button IssuedButton;
private Button RefreshButton;
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 ToolStripMenuItem клиентыToolStripMenuItem;
private ToolStripMenuItem магазиныToolStripMenuItem1;
private ToolStripMenuItem поставкиToolStripMenuItem1;
private ToolStripMenuItem ToolStripMenu;
private ToolStripMenuItem КомпонентыStripMenuItem;
private ToolStripMenuItem МороженноеStripMenuItem;
private DataGridView DataGridView;
private Button CreateOrderButton;
private Button IssuedButton;
private Button RefreshButton;
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 ToolStripMenuItem списокМагазиновToolStripMenuItem;
private ToolStripMenuItem мороженноеПоМагазинамToolStripMenuItem;
private ToolStripMenuItem заказыПоДатамToolStripMenuItem;
}
}

View File

@ -16,175 +16,178 @@ using System.Windows.Forms;
namespace IceCreamShop
{
public partial class MainForm : Form
{
private readonly ILogger _logger;
private readonly IOrderLogic _orderLogic;
private readonly IReportLogic _reportLogic;
public MainForm(ILogger<MainForm> logger, IOrderLogic orderLogic, IReportLogic reportLogic)
{
InitializeComponent();
_logger = logger;
_orderLogic = orderLogic;
_reportLogic = reportLogic;
}
public partial class MainForm : Form
{
private readonly ILogger _logger;
private readonly IOrderLogic _orderLogic;
private readonly IReportLogic _reportLogic;
private readonly IWorkProcess _workProcess;
public MainForm(ILogger<MainForm> logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess)
{
InitializeComponent();
_logger = logger;
_orderLogic = orderLogic;
_reportLogic = reportLogic;
_workProcess = workProcess;
}
private void КомпонентыStripMenuItem_Click(object sender, EventArgs e)
{
var service =
private void КомпонентыStripMenuItem_Click(object sender, EventArgs e)
{
var service =
Program.ServiceProvider?.GetService(typeof(ComponentsForm));
if (service is ComponentsForm form)
{
form.ShowDialog();
}
if (service is ComponentsForm form)
{
form.ShowDialog();
}
}
}
private void MainForm_Load(object sender, EventArgs e)
{
LoadData();
}
private void MainForm_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
_logger.LogInformation("Загрузка заказов");
try
{
var list = _orderLogic.ReadList(null);
if (list != null)
{
DataGridView.DataSource = list;
DataGridView.Columns["IceCreamId"].Visible = false;
DataGridView.Columns["ClientId"].Visible = false;
DataGridView.Columns["IceCreamName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка заказов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки заказов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadData()
{
_logger.LogInformation("Загрузка заказов");
try
{
var list = _orderLogic.ReadList(null);
if (list != null)
{
DataGridView.DataSource = list;
DataGridView.Columns["IceCreamId"].Visible = false;
DataGridView.Columns["ClientId"].Visible = false;
DataGridView.Columns["ImplementerId"].Visible = false;
DataGridView.Columns["IceCreamName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка заказов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки заказов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void МороженноеStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(IceCreamsForm));
if (service is IceCreamsForm form)
{
form.ShowDialog();
}
}
private void МороженноеStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(IceCreamsForm));
if (service is IceCreamsForm form)
{
form.ShowDialog();
}
}
private void CreateOrderButton_Click(object sender, EventArgs e)
{
var service =
private void CreateOrderButton_Click(object sender, EventArgs e)
{
var service =
Program.ServiceProvider?.GetService(typeof(OrderForm));
if (service is OrderForm form)
{
form.ShowDialog();
LoadData();
}
}
if (service is OrderForm form)
{
form.ShowDialog();
LoadData();
}
}
private OrderBindingModel CreateBindingModel(int id, bool isDone = false)
{
return new OrderBindingModel
{
Id = id,
IceCreamId = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["IceCreamId"].Value),
ClientId = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["ClientId"].Value),
Status = Enum.Parse<OrderStatus>(DataGridView.SelectedRows[0].Cells["Status"].Value.ToString()),
Count = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Count"].Value),
Sum = double.Parse(DataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()),
DateCreate = DateTime.Parse(DataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()),
};
}
private OrderBindingModel CreateBindingModel(int id, bool isDone = false)
{
return new OrderBindingModel
{
Id = id,
IceCreamId = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["IceCreamId"].Value),
ClientId = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["ClientId"].Value),
Status = Enum.Parse<OrderStatus>(DataGridView.SelectedRows[0].Cells["Status"].Value.ToString()),
Count = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Count"].Value),
Sum = double.Parse(DataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()),
DateCreate = DateTime.Parse(DataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()),
};
}
private void TakeInWorkButton_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(CreateBindingModel(id));
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка передачи заказа в работу");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void TakeInWorkButton_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(CreateBindingModel(id));
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка передачи заказа в работу");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
}
private void ReadyButton_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(CreateBindingModel(id));
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о готовности заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void ReadyButton_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(CreateBindingModel(id));
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о готовности заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void IssuedButton_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.DeliveryOrder(CreateBindingModel(id));
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
_logger.LogInformation("Заказ №{id} выдан", id);
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о выдачи заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void IssuedButton_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.DeliveryOrder(CreateBindingModel(id));
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
_logger.LogInformation("Заказ №{id} выдан", id);
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о выдачи заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
}
private void RefreshButton_Click(object sender, EventArgs e)
{
LoadData();
}
private void RefreshButton_Click(object sender, EventArgs e)
{
LoadData();
}
private void магазиныToolStripMenuItem_Click(object sender, EventArgs e)
{
@ -226,27 +229,27 @@ Program.ServiceProvider?.GetService(typeof(OrderForm));
MessageBoxIcon.Information);
}
}
}
private void компонентыПоМороженнымToolStripMenuItem_Click(object sender, EventArgs e)
{
var service =
private void компонентыПоМороженнымToolStripMenuItem_Click(object sender, EventArgs e)
{
var service =
Program.ServiceProvider?.GetService(typeof(ReportIceCreamComponentForm));
if (service is ReportIceCreamComponentForm form)
{
form.ShowDialog();
}
if (service is ReportIceCreamComponentForm form)
{
form.ShowDialog();
}
}
}
private void списокЗаказовToolStripMenuItem_Click(object sender, EventArgs e)
{
var service =
private void списокЗаказовToolStripMenuItem_Click(object sender, EventArgs e)
{
var service =
Program.ServiceProvider?.GetService(typeof(ReportOrdersForm));
if (service is ReportOrdersForm form)
{
form.ShowDialog();
}
if (service is ReportOrdersForm form)
{
form.ShowDialog();
}
}
@ -284,14 +287,34 @@ Program.ServiceProvider?.GetService(typeof(ReportDateOrdersForm));
}
}
private void клиентыToolStripMenuItem_Click(object sender, EventArgs e)
{
var service =
private void клиентыToolStripMenuItem_Click(object sender, EventArgs e)
{
var service =
Program.ServiceProvider?.GetService(typeof(ClientsForm));
if (service is ClientsForm form)
{
form.ShowDialog();
}
}
}
if (service is ClientsForm form)
{
form.ShowDialog();
}
}
private void исполнителиToolStripMenuItem_Click(object sender, EventArgs e)
{
var service =
Program.ServiceProvider?.GetService(typeof(ImplementersForm));
if (service is ImplementersForm 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

@ -44,14 +44,19 @@ namespace IceCreamShop
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<IReportLogic, ReportLogic>();
services.AddTransient<IIceCreamLogic, IceCreamLogic>();
services.AddTransient<IClientLogic, ClientLogic>();
services.AddTransient<IImplementerLogic, ImplementerLogic>();
services.AddTransient<IImplementerStorage, ImplementerStorage>();
services.AddTransient<IClientLogic, ClientLogic>();
services.AddTransient<IClientStorage, ClientStorage>();
services.AddTransient<MainForm>();
services.AddTransient<IWorkProcess, WorkModeling>();
services.AddTransient<MainForm>();
services.AddTransient<ComponentForm>();
services.AddTransient<ComponentsForm>();
services.AddTransient<OrderForm>();
services.AddTransient<IceCreamForm>();
services.AddTransient<ClientsForm>();
services.AddTransient<ImplementersForm>();
services.AddTransient<ImplementerForm>();
services.AddTransient<ClientsForm>();
services.AddTransient<IceCreamComponentForm>();
services.AddTransient<IceCreamsForm>();
services.AddTransient<ShopForm>();

View File

@ -105,8 +105,9 @@ namespace IceCreamShop
Address = AddressTextBox.Text,
DateOpen = DateTimePicker.Value.Date,
MaxCapacity = Convert.ToInt32(CapacityUpDown.Value),
ShopIceCreams = null
};
if (_id.HasValue)
model.ShopIceCreams = null;
var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model);
if (!operationResult)
{

View File

@ -18,10 +18,10 @@ namespace IceCreamShopBusinessLogic.BusinessLogic
private readonly ILogger _logger;
private readonly IClientStorage _clientStorage;
public ClientLogic(ILogger<ClientLogic> logger, IClientStorage
componentStorage)
clientStorage)
{
_logger = logger;
_clientStorage = componentStorage;
_clientStorage = clientStorage;
}
public List<ClientViewModel>? ReadList(ClientSearchModel? model)
{

View File

@ -0,0 +1,128 @@
using IceCreamShopContracts.BindingModels;
using IceCreamShopContracts.BusinessLogicsContracts;
using IceCreamShopContracts.SearchModels;
using IceCreamShopContracts.StoragesContracts;
using IceCreamShopContracts.ViewModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IceCreamShopBusinessLogic.BusinessLogic
{
public class ImplementerLogic : IImplementerLogic
{
private readonly ILogger _logger;
private readonly IImplementerStorage _implementerStorage;
public ImplementerLogic(ILogger<ImplementerLogic> logger, IImplementerStorage
implementerStorage)
{
_logger = logger;
_implementerStorage = implementerStorage;
}
public List<ImplementerViewModel>? ReadList(ImplementerSearchModel? model)
{
_logger.LogInformation("ReadList. ImplementerFIO:{ClientFIO}. Id:{ Id}", model?.ImplementerFIO, model?.Id);
var list = model == null ? _implementerStorage.GetFullList() :
_implementerStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public ImplementerViewModel? ReadElement(ImplementerSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. ImplementerFIO:{ImplementerFIO}.Id:{ Id}", model.ImplementerFIO, model.Id);
var element = _implementerStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
public bool Create(ImplementerBindingModel model)
{
CheckModel(model);
if (_implementerStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Update(ImplementerBindingModel model)
{
CheckModel(model);
if (_implementerStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool Delete(ImplementerBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_implementerStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
private void CheckModel(ImplementerBindingModel model, bool withParams =
true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.ImplementerFIO))
{
throw new ArgumentNullException("Нет ФИО исполнителя",
nameof(model.ImplementerFIO));
}
if (string.IsNullOrEmpty(model.Password))
{
throw new ArgumentNullException("Нет пароля клиента",
nameof(model.Password));
}
if (model.WorkExperience < 0)
{
throw new ArgumentNullException("Стаж меньше 0",
nameof(model.WorkExperience));
}
if (model.Qualification < 0)
{
throw new ArgumentException("Квалификация меньше 0", nameof(model.Qualification));
}
_logger.LogInformation("Implementer. ImplementerFIO:{ImplementerFIO}." +
"Password:{ Password}. WorkExperience:{ WorkExperience}. Qualification:{ Qualification}. Id: { Id} ",
model.ImplementerFIO, model.Password, model.WorkExperience, model.Qualification, model.Id);
var element = _implementerStorage.GetElement(new ImplementerSearchModel
{
ImplementerFIO = model.ImplementerFIO,
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Исполнитель с таким ФИО уже есть");
}
}
}
}

View File

@ -15,178 +15,226 @@ using System.Threading.Tasks;
namespace IceCreamShopBusinessLogic.BusinessLogic
{
public class OrderLogic : IOrderLogic
{
private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage;
private readonly IShopStorage _shopStorage;
private readonly IShopLogic _shopLogic;
private readonly IIceCreamStorage _iceCreamStorage;
public class OrderLogic : IOrderLogic
{
private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage;
private readonly IShopStorage _shopStorage;
private readonly IShopLogic _shopLogic;
private readonly IIceCreamStorage _iceCreamStorage;
static readonly object locker = new object();
public OrderLogic(IOrderStorage orderStorage, IShopStorage shopStorage, IShopLogic shopLogic, IIceCreamStorage iceCreamStorage, ILogger<OrderLogic> logger)
{
_orderStorage = orderStorage;
_shopStorage = shopStorage;
_logger = logger;
_shopLogic = shopLogic;
_iceCreamStorage = iceCreamStorage;
}
public OrderLogic(IOrderStorage orderStorage, IShopStorage shopStorage, IShopLogic shopLogic, IIceCreamStorage iceCreamStorage, ILogger<OrderLogic> logger)
{
_orderStorage = orderStorage;
_shopStorage = shopStorage;
_logger = logger;
_shopLogic = shopLogic;
_iceCreamStorage = iceCreamStorage;
}
public OrderViewModel? ReadElement(OrderSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. Id:{ Id}", model.Id);
var element = _orderStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
public List<OrderViewModel>? ReadList(OrderSearchModel? model)
{
_logger.LogInformation("ReadList. Id:{ Id}", model?.Id);
var list = model == null ? _orderStorage.GetFullList() :
_orderStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public List<OrderViewModel>? ReadList(OrderSearchModel? model)
{
_logger.LogInformation("ReadList. Id:{ Id}", model?.Id);
var list = model == null ? _orderStorage.GetFullList() :
_orderStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public bool CreateOrder(OrderBindingModel model)
{
CheckModel(model);
if (model.Status != OrderStatus.Неизвестен) return false;
model.Status = OrderStatus.Принят;
if (_orderStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool CreateOrder(OrderBindingModel model)
{
CheckModel(model);
if (model.Status != OrderStatus.Неизвестен) return false;
model.Status = OrderStatus.Принят;
if (_orderStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool CheckSupply(IIceCreamModel iceCream, int count)
{
if (count <= 0)
{
_logger.LogWarning("Check then supply operation error. IceCream count < 0.");
return false;
}
public bool CheckSupply(IIceCreamModel iceCream, int count)
{
if (count <= 0)
{
_logger.LogWarning("Check then supply operation error. IceCream count < 0.");
return false;
}
int sumCapacity = 0;
int sumCount = 0;
sumCapacity = _shopStorage.GetFullList().Select(x => x.MaxCapacity).Sum();
sumCount = _shopStorage.GetFullList().Select(x => x.ShopIceCreams.Select(y => y.Value.Item2).Sum()).Sum();
int freeSpace = sumCapacity - sumCount;
int sumCapacity = 0;
int sumCount = 0;
sumCapacity = _shopStorage.GetFullList().Select(x => x.MaxCapacity).Sum();
sumCount = _shopStorage.GetFullList().Select(x => x.ShopIceCreams.Select(y => y.Value.Item2).Sum()).Sum();
int freeSpace = sumCapacity - sumCount;
if (freeSpace - count < 0)
{
_logger.LogWarning("Check then supply operation error. There's no place for new IceCream in shops.");
return false;
}
if (freeSpace - count < 0)
{
_logger.LogWarning("Check then supply operation error. There's no place for new IceCream in shops.");
return false;
}
foreach (var shop in _shopStorage.GetFullList())
{
freeSpace = shop.MaxCapacity;
foreach (var doc in shop.ShopIceCreams)
{
freeSpace -= doc.Value.Item2;
}
if (freeSpace == 0)
{
continue;
}
if (freeSpace - count >= 0)
{
if (_shopLogic.MakeSupply(new() { Id = shop.Id }, iceCream, count))
count = 0;
else
{
_logger.LogWarning("Supply error");
return false;
}
}
if (freeSpace - count < 0)
{
if (_shopLogic.MakeSupply(new() { Id = shop.Id }, iceCream, freeSpace))
count -= freeSpace;
else
{
_logger.LogWarning("Supply error");
return false;
}
}
if (count <= 0)
{
return true;
}
}
return false;
}
foreach (var shop in _shopStorage.GetFullList())
{
freeSpace = shop.MaxCapacity;
foreach (var doc in shop.ShopIceCreams)
{
freeSpace -= doc.Value.Item2;
}
if (freeSpace == 0)
{
continue;
}
if (freeSpace - count >= 0)
{
if (_shopLogic.MakeSupply(new() { Id = shop.Id }, iceCream, count))
count = 0;
else
{
_logger.LogWarning("Supply error");
return false;
}
}
if (freeSpace - count < 0)
{
if (_shopLogic.MakeSupply(new() { Id = shop.Id }, iceCream, freeSpace))
count -= freeSpace;
else
{
_logger.LogWarning("Supply error");
return false;
}
}
if (count <= 0)
{
return true;
}
}
return false;
}
public bool ChangeStatus(OrderBindingModel model, OrderStatus status)
{
CheckModel(model);
var element = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id });
if (element == null)
{
_logger.LogWarning("Read operation failed");
return false;
}
if (element.Status != status - 1)
{
_logger.LogWarning("Status change operation failed");
throw new InvalidOperationException("Текущий статус заказа не может быть переведен в выбранный");
}
if(element.Status == OrderStatus.Готов)
{
var icecream = _iceCreamStorage.GetElement(new IceCreamSearchModel() { Id = model.IceCreamId });
if (icecream == null)
{
_logger.LogWarning("Status update to " + status.ToString() + " operation failed. Document not found.");
return false;
}
if (CheckSupply(icecream, model.Count) == false)
{
_logger.LogWarning("Status update to " + status.ToString() + " operation failed. Shop supply error.");
return false;
}
}
model.Status = status;
if (model.Status == OrderStatus.Выдан) model.DateImplement = DateTime.Now;
_orderStorage.Update(model);
return true;
}
public bool ChangeStatus(OrderBindingModel model, OrderStatus status)
{
CheckModel(model, false);
var element = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id });
if (element == null)
{
_logger.LogWarning("Read operation failed");
return false;
}
if(element.Status == OrderStatus.Ожидается) {
if (status != OrderStatus.Готов)
{
_logger.LogWarning("Status change operation failed");
throw new InvalidOperationException("Текущий статус заказа не может быть переведен в выбранный");
}
}
else if(status == OrderStatus.Ожидается)
{
if (status != OrderStatus.Выполняется)
{
_logger.LogWarning("Status change operation failed");
throw new InvalidOperationException("Текущий статус заказа не может быть переведен в выбранный");
}
}
else if (element.Status != status - 1)
{
_logger.LogWarning("Status change operation failed");
throw new InvalidOperationException("Текущий статус заказа не может быть переведен в выбранный");
}
model.Sum = element.Sum;
model.Count = element.Count;
model.IceCreamId = element.IceCreamId;
model.DateCreate = element.DateCreate;
model.DateImplement = element.DateImplement;
if (element.ImplementerId.HasValue && element.ImplementerId != 0)
model.ImplementerId = element.ImplementerId;
if (status == OrderStatus.Готов)
{
var icecream = _iceCreamStorage.GetElement(new IceCreamSearchModel() { Id = model.IceCreamId });
if (icecream == null)
{
_logger.LogWarning("Status update to " + status.ToString() + " operation failed. Document not found.");
return false;
}
if (!CheckSupply(icecream, model.Count))
{
model.Status = OrderStatus.Ожидается;
_orderStorage.Update(model);
return false;
}
}
model.Status = status;
if (model.Status == OrderStatus.Выдан) model.DateImplement = DateTime.Now;
_orderStorage.Update(model);
return true;
}
public bool TakeOrderInWork(OrderBindingModel model)
{
return ChangeStatus(model, OrderStatus.Выполняется);
}
public bool TakeOrderInWork(OrderBindingModel model)
{
lock (locker)
{
return ChangeStatus(model, OrderStatus.Выполняется);
}
}
public bool FinishOrder(OrderBindingModel model)
{
return ChangeStatus(model, OrderStatus.Готов);
}
public bool FinishOrder(OrderBindingModel model)
{
return ChangeStatus(model, OrderStatus.Готов);
public bool DeliveryOrder(OrderBindingModel model)
{
return ChangeStatus(model, OrderStatus.Выдан);
}
}
public bool TakeOrderInWaiting(OrderBindingModel model)
{
return ChangeStatus(model, OrderStatus.Ожидается);
}
private void CheckModel(OrderBindingModel model, bool withParams =
public bool DeliveryOrder(OrderBindingModel model)
{
return ChangeStatus(model, OrderStatus.Выдан);
}
private void CheckModel(OrderBindingModel model, bool withParams =
true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (model.Sum <= 0)
{
throw new ArgumentNullException("Цена заказа должна быть больше 0", nameof(model.Sum));
}
if (model.Count <= 0)
{
throw new ArgumentNullException("Количество элементов в заказе должно быть больше 0", nameof(model.Count));
}
_logger.LogInformation("Order. Sum:{ Cost}. Id: { Id}", model.Sum, model.Id);
}
}
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (model.Sum <= 0)
{
throw new ArgumentNullException("Цена заказа должна быть больше 0", nameof(model.Sum));
}
if (model.Count <= 0)
{
throw new ArgumentNullException("Количество элементов в заказе должно быть больше 0", nameof(model.Count));
}
_logger.LogInformation("Order. Sum:{ Cost}. Id: { Id}", model.Sum, model.Id);
}
}
}

View File

@ -0,0 +1,180 @@
using IceCreamShopContracts.BindingModels;
using IceCreamShopContracts.BusinessLogicsContracts;
using IceCreamShopContracts.SearchModels;
using IceCreamShopContracts.ViewModels;
using IceCreamShopDataModels.Enums;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IceCreamShopBusinessLogic.BusinessLogic
{
public class WorkModeling : IWorkProcess
{
private readonly ILogger _logger;
private readonly Random _rnd;
private IOrderLogic? _orderLogic;
public WorkModeling(ILogger<WorkModeling> logger)
{
_logger = logger;
_rnd = new Random(1000);
}
public void DoWork(IImplementerLogic implementerLogic, IOrderLogic
orderLogic)
{
_orderLogic = orderLogic;
var implementers = implementerLogic.ReadList(null);
if (implementers == null)
{
_logger.LogWarning("DoWork. Implementers is null");
return;
}
var orders = _orderLogic.ReadList(new OrderSearchModel
{
Status =
OrderStatus.Принят
});
_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 RunWaitingOrder(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);
// пытаемся назначить заказ на исполнителя
_orderLogic.TakeOrderInWork(new OrderBindingModel
{
Id = order.Id,
ImplementerId = implementer.Id
});
// делаем работу
Thread.Sleep(implementer.WorkExperience * _rnd.Next(100,
1000) * order.Count);
_logger.LogDebug("DoWork. Worker {Id} finish order { Order}", implementer.Id, order.Id);
_orderLogic.FinishOrder(new OrderBindingModel
{
Id = order.Id
});
// отдыхаем
Thread.Sleep(implementer.Qualification * _rnd.Next(10, 100));
}
// кто-то мог уже перехватить заказ, игнорируем ошибку
catch (InvalidOperationException ex)
{
_logger.LogWarning(ex, "Error try get work");
}
// заканчиваем выполнение имитации в случае иной ошибки
catch (Exception ex)
{
_logger.LogError(ex, "Error while do work");
throw;
}
}
});
}
/// Ищем заказ, которые уже в работе (вдруг исполнителя прервали)
private async Task RunOrderInWork(ImplementerViewModel implementer)
{
if (_orderLogic == null || implementer == null)
{
return;
}
try
{
var runOrder = await Task.Run(() => _orderLogic.ReadElement(new
OrderSearchModel
{
ImplementerId = implementer.Id,
Status = OrderStatus.Выполняется
}));
if (runOrder == null)
{
return;
}
_logger.LogDebug("DoWork. Worker {Id} back to order {Order}",
implementer.Id, runOrder.Id);
// доделываем работу
Thread.Sleep(implementer.WorkExperience * _rnd.Next(100, 300) *
runOrder.Count);
_logger.LogDebug("DoWork. Worker {Id} finish order {Order}",
implementer.Id, runOrder.Id);
_orderLogic.FinishOrder(new OrderBindingModel
{
Id = runOrder.Id
});
// отдыхаем
Thread.Sleep(implementer.Qualification * _rnd.Next(10, 100));
}
// заказа может не быть, просто игнорируем ошибку
catch (InvalidOperationException ex)
{
_logger.LogWarning(ex, "Error try get work");
}
// а может возникнуть иная ошибка, тогда просто заканчиваем выполнение имитации
catch (Exception ex)
{
_logger.LogError(ex, "Error while do work");
throw;
}
}
private async Task RunWaitingOrder(ImplementerViewModel implementer)
{
if (_orderLogic == null || implementer == null)
{
return;
}
try
{
var orders = await Task.Run(() => _orderLogic.ReadList(new OrderSearchModel
{
ImplementerId = implementer.Id,
Status = OrderStatus.Ожидается,
}));
if (orders == null || orders.Count == 0)
{
return;
}
foreach (var order in orders)
{
_logger.LogDebug("DoWork. Worker {Id} finish order {Order}", implementer.Id, order.Id);
_orderLogic.FinishOrder(new OrderBindingModel
{
Id = order.Id,
ImplementerId = implementer.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

@ -113,6 +113,7 @@ namespace IceCreamShopClientApp.Controllers
[HttpGet]
public IActionResult Create()
{
var res = APIClient.GetRequest<List<IceCreamViewModel>>("api/main/geticecreamlist");
ViewBag.IceCreams =
APIClient.GetRequest<List<IceCreamViewModel>>("api/main/geticecreamlist");
return View();

View File

@ -0,0 +1,18 @@
using IceCreamShopDataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IceCreamShopContracts.BindingModels
{
public class ImplementerBindingModel : IImplementerModel
{
public int Id { get; set; }
public string ImplementerFIO { get; set; } = string.Empty;
public int WorkExperience { get; set; } = 0;
public int Qualification { get; set; } = 0;
public string Password { get; set; } = string.Empty;
}
}

View File

@ -13,7 +13,8 @@ namespace IceCreamShopContracts.BindingModels
{
public int Id { get; set; }
public int IceCreamId { get; set; }
public int ClientId { get; set; }
public int? ImplementerId { get; set; } = null;
public int ClientId { get; set; }
public int Count { get; set; }
public double Sum { get; set; }
public OrderStatus Status { get; set; } = OrderStatus.Неизвестен;

View File

@ -0,0 +1,20 @@
using IceCreamShopContracts.BindingModels;
using IceCreamShopContracts.SearchModels;
using IceCreamShopContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IceCreamShopContracts.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

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

View File

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IceCreamShopContracts.BusinessLogicsContracts
{
public interface IWorkProcess
{
void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic);
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IceCreamShopContracts.SearchModels
{
public class ImplementerSearchModel
{
public int? Id { get; set; }
public string? ImplementerFIO { get; set; } = string.Empty;
public string? Password { get; set; } = string.Empty;
}
}

View File

@ -1,4 +1,5 @@
using System;
using IceCreamShopDataModels.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -10,6 +11,8 @@ namespace IceCreamShopContracts.SearchModels
{
public int? Id { get; set; }
public int? ClientId { get; set; }
public int? ImplementerId { get; set; }
public OrderStatus? Status { get; set; }
public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }
}

View File

@ -0,0 +1,21 @@
using IceCreamShopContracts.BindingModels;
using IceCreamShopContracts.SearchModels;
using IceCreamShopContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IceCreamShopContracts.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,23 @@
using IceCreamShopDataModels;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IceCreamShopContracts.ViewModels
{
public class ImplementerViewModel : IImplementerModel
{
public int Id { get; set; }
[DisplayName("ФИО исполнителя")]
public string ImplementerFIO { get; set; } = string.Empty;
[DisplayName("Стаж работы")]
public int WorkExperience { get; set; } = 0;
[DisplayName("Квалификация")]
public int Qualification { get; set; } = 0;
[DisplayName("Пароль")]
public string Password { get; set; } = string.Empty;
}
}

View File

@ -16,11 +16,14 @@ namespace IceCreamShopContracts.ViewModels
public int Id { get; set; }
public int IceCreamId { get; set; }
public int ClientId { get; set; }
public int? ImplementerId { get; set; } = null;
[DisplayName("Клиент")]
public string ClientFIO { get; set; } = string.Empty;
[DisplayName("Мороженное")]
public string IceCreamName { get; set; } = string.Empty;
[DisplayName("Количество")]
[DisplayName("Исполнитель")]
public string ImplementerFIO { get; set; } = string.Empty;
[DisplayName("Количество")]
public int Count { get; set; }
[DisplayName("Сумма")]
public double Sum { get; set; }

View File

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

View File

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

View File

@ -10,6 +10,7 @@
Готов = 2,
Выдан = 3
Выдан = 3,
Ожидается = 4
}
}

View File

@ -27,6 +27,7 @@ optionsBuilder)
public virtual DbSet<Shop> Shops { set; get; }
public virtual DbSet<ShopIceCream> ShopIceCreams { set; get; }
public virtual DbSet<Client> Clients { set; get; }
public virtual DbSet<Implementer> Implementers { set; get; }
}
}
}

View File

@ -0,0 +1,87 @@
using IceCreamShopContracts.BindingModels;
using IceCreamShopContracts.SearchModels;
using IceCreamShopContracts.StoragesContracts;
using IceCreamShopContracts.ViewModels;
using IceCreamShopDatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IceCreamShopDatabaseImplement.Implements
{
public class ImplementerStorage : IImplementerStorage
{
public ImplementerViewModel? Delete(ImplementerBindingModel model)
{
using var context = new IceCreamShopDataBase();
var res = context.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (res != null)
{
context.Implementers.Remove(res);
context.SaveChanges();
}
return res?.GetViewModel;
}
public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{
if (string.IsNullOrEmpty(model.ImplementerFIO) && string.IsNullOrEmpty(model.Password) &&
!model.Id.HasValue)
{
return null;
}
using var context = new IceCreamShopDataBase();
return context.Implementers
.FirstOrDefault(x => (string.IsNullOrEmpty(model.ImplementerFIO) || x.ImplementerFIO == model.ImplementerFIO) &&
(!model.Id.HasValue || x.Id == model.Id) &&
(string.IsNullOrEmpty(model.Password) || x.Password == model.Password))
?.GetViewModel;
}
public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model)
{
if (model == null)
{
return new();
}
if (model.Id.HasValue)
{
var res = GetElement(model);
return res != null ? new() { res } : new();
}
return new();
}
public List<ImplementerViewModel> GetFullList()
{
using var context = new IceCreamShopDataBase();
return context.Implementers.Select(x => x.GetViewModel).ToList();
}
public ImplementerViewModel? Insert(ImplementerBindingModel model)
{
using var context = new IceCreamShopDataBase();
var res = Implementer.Create(model);
if (res != null)
{
context.Implementers.Add(res);
context.SaveChanges();
}
return res?.GetViewModel;
}
public ImplementerViewModel? Update(ImplementerBindingModel model)
{
using var context = new IceCreamShopDataBase();
var res = context.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (res != null)
{
res.Update(model);
context.SaveChanges();
}
return res?.GetViewModel;
}
}
}

View File

@ -18,7 +18,7 @@ namespace IceCreamShopDatabaseImplement.Implements
{
using var context = new IceCreamShopDataBase();
return context.Orders.Include(x => x.IceCream)
.Include(x => x.Client).Select(x => x.GetViewModel)
.Include(x => x.Client).Include(x => x.Implementer).Select(x => x.GetViewModel)
.ToList();
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
@ -27,25 +27,28 @@ namespace IceCreamShopDatabaseImplement.Implements
using var context = new IceCreamShopDataBase();
return context.Orders
.Include(x => x.IceCream)
.Include(x => x.Client).Where(x => (
.Include(x => x.Client).Include(x => x.Implementer).Where(x => (
(!model.Id.HasValue || x.Id == model.Id) &&
(!model.DateFrom.HasValue || x.DateCreate >= model.DateFrom) &&
(!model.DateTo.HasValue || x.DateCreate <= model.DateTo)
&&
(!model.ClientId.HasValue || x.ClientId == model.ClientId)
)
&&
(!model.Status.HasValue || x.Status == model.Status)
&&
(!model.ImplementerId.HasValue || x.ImplementerId == model.ImplementerId)
)
)
.Select(x => x.GetViewModel)
.ToList();
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new IceCreamShopDataBase();
return context.Orders.Include(x => x.IceCream).Include(x=> x.Client).FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
return context.Orders.Include(x => x.IceCream).Include(x=> x.Client).Include(x => x.Implementer).FirstOrDefault(
x => ((model.Id.HasValue && x.Id == model.Id) ||
(model.ImplementerId.HasValue && model.Status.HasValue &&
x.ImplementerId == model.ImplementerId && x.Status == model.Status)))?.GetViewModel;
}
public OrderViewModel? Insert(OrderBindingModel model)
{
@ -62,7 +65,7 @@ namespace IceCreamShopDatabaseImplement.Implements
public OrderViewModel? Update(OrderBindingModel model)
{
using var context = new IceCreamShopDataBase();
var order = context.Orders.Include(x => x.IceCream).Include(x => x.Client).FirstOrDefault(x => x.Id ==
var order = context.Orders.Include(x => x.IceCream).Include(x => x.Client).Include(x => x.Implementer).FirstOrDefault(x => x.Id ==
model.Id);
if (order == null)
{

View File

@ -12,7 +12,7 @@ using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace IceCreamShopDatabaseImplement.Migrations
{
[DbContext(typeof(IceCreamShopDataBase))]
[Migration("20240414075932_InitialCreate")]
[Migration("20240508064221_InitialCreate")]
partial class InitialCreate
{
/// <inheritdoc />
@ -116,6 +116,33 @@ namespace IceCreamShopDatabaseImplement.Migrations
b.ToTable("IceCreamComponents");
});
modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.Implementer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ImplementerFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("Qualification")
.HasColumnType("int");
b.Property<int>("WorkExperience")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Implementers");
});
modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
@ -139,6 +166,9 @@ namespace IceCreamShopDatabaseImplement.Migrations
b.Property<int>("IceCreamId")
.HasColumnType("int");
b.Property<int?>("ImplementerId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
@ -151,6 +181,8 @@ namespace IceCreamShopDatabaseImplement.Migrations
b.HasIndex("IceCreamId");
b.HasIndex("ImplementerId");
b.ToTable("Orders");
});
@ -240,9 +272,15 @@ namespace IceCreamShopDatabaseImplement.Migrations
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("IceCreamShopDatabaseImplement.Models.Implementer", "Implementer")
.WithMany("Orders")
.HasForeignKey("ImplementerId");
b.Navigation("Client");
b.Navigation("IceCream");
b.Navigation("Implementer");
});
modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.ShopIceCream", b =>
@ -283,6 +321,11 @@ namespace IceCreamShopDatabaseImplement.Migrations
b.Navigation("ShopIceCreams");
});
modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.Implementer", b =>
{
b.Navigation("Orders");
});
modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.Shop", b =>
{
b.Navigation("IceCreams");

View File

@ -54,6 +54,22 @@ namespace IceCreamShopDatabaseImplement.Migrations
table.PrimaryKey("PK_IceCreams", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Implementers",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ImplementerFIO = table.Column<string>(type: "nvarchar(max)", nullable: false),
Password = table.Column<string>(type: "nvarchar(max)", nullable: false),
Qualification = table.Column<int>(type: "int", nullable: false),
WorkExperience = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Implementers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Shops",
columns: table => new
@ -109,7 +125,8 @@ namespace IceCreamShopDatabaseImplement.Migrations
DateCreate = table.Column<DateTime>(type: "datetime2", nullable: false),
DateImplement = table.Column<DateTime>(type: "datetime2", nullable: true),
IceCreamId = table.Column<int>(type: "int", nullable: false),
ClientId = table.Column<int>(type: "int", nullable: false)
ClientId = table.Column<int>(type: "int", nullable: false),
ImplementerId = table.Column<int>(type: "int", nullable: true)
},
constraints: table =>
{
@ -126,6 +143,11 @@ namespace IceCreamShopDatabaseImplement.Migrations
principalTable: "IceCreams",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Orders_Implementers_ImplementerId",
column: x => x.ImplementerId,
principalTable: "Implementers",
principalColumn: "Id");
});
migrationBuilder.CreateTable(
@ -175,6 +197,11 @@ namespace IceCreamShopDatabaseImplement.Migrations
table: "Orders",
column: "IceCreamId");
migrationBuilder.CreateIndex(
name: "IX_Orders_ImplementerId",
table: "Orders",
column: "ImplementerId");
migrationBuilder.CreateIndex(
name: "IX_ShopIceCreams_IceCreamId",
table: "ShopIceCreams",
@ -204,6 +231,9 @@ namespace IceCreamShopDatabaseImplement.Migrations
migrationBuilder.DropTable(
name: "Clients");
migrationBuilder.DropTable(
name: "Implementers");
migrationBuilder.DropTable(
name: "IceCreams");

View File

@ -113,6 +113,33 @@ namespace IceCreamShopDatabaseImplement.Migrations
b.ToTable("IceCreamComponents");
});
modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.Implementer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ImplementerFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("Qualification")
.HasColumnType("int");
b.Property<int>("WorkExperience")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Implementers");
});
modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
@ -136,6 +163,9 @@ namespace IceCreamShopDatabaseImplement.Migrations
b.Property<int>("IceCreamId")
.HasColumnType("int");
b.Property<int?>("ImplementerId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
@ -148,6 +178,8 @@ namespace IceCreamShopDatabaseImplement.Migrations
b.HasIndex("IceCreamId");
b.HasIndex("ImplementerId");
b.ToTable("Orders");
});
@ -237,9 +269,15 @@ namespace IceCreamShopDatabaseImplement.Migrations
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("IceCreamShopDatabaseImplement.Models.Implementer", "Implementer")
.WithMany("Orders")
.HasForeignKey("ImplementerId");
b.Navigation("Client");
b.Navigation("IceCream");
b.Navigation("Implementer");
});
modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.ShopIceCream", b =>
@ -280,6 +318,11 @@ namespace IceCreamShopDatabaseImplement.Migrations
b.Navigation("ShopIceCreams");
});
modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.Implementer", b =>
{
b.Navigation("Orders");
});
modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.Shop", b =>
{
b.Navigation("IceCreams");

View File

@ -0,0 +1,65 @@
using IceCreamShopContracts.BindingModels;
using IceCreamShopContracts.ViewModels;
using IceCreamShopDataModels;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IceCreamShopDatabaseImplement.Models
{
public class Implementer : IImplementerModel
{
public int Id { get; private set; }
[Required]
public string ImplementerFIO { get; private set; } = string.Empty;
[Required]
public string Password { get; set; } = string.Empty;
[Required]
public int Qualification { get; set; } = 0;
[Required]
public int WorkExperience { get; set; } = 0;
[ForeignKey("ImplementerId")]
public virtual List<Order> Orders { get; set; } =
new();
public static Implementer? Create(ImplementerBindingModel model)
{
if (model == null)
{
return null;
}
return new()
{
Id = model.Id,
Password = model.Password,
Qualification = model.Qualification,
ImplementerFIO = model.ImplementerFIO,
WorkExperience = model.WorkExperience,
};
}
public void Update(ImplementerBindingModel model)
{
if (model == null)
{
return;
}
Password = model.Password;
Qualification = model.Qualification;
ImplementerFIO = model.ImplementerFIO;
WorkExperience = model.WorkExperience;
}
public ImplementerViewModel GetViewModel => new()
{
Id = Id,
Password = Password,
Qualification = Qualification,
ImplementerFIO = ImplementerFIO,
WorkExperience = WorkExperience,
};
}
}

View File

@ -29,7 +29,9 @@ namespace IceCreamShopDatabaseImplement.Models
[Required]
public int ClientId { get; private set; }
public virtual Client Client { get; private set; }
public static Order? Create(IceCreamShopDataBase context, OrderBindingModel model)
public int? ImplementerId { get; private set; } = null;
public virtual Implementer? Implementer { get; private set; }
public static Order? Create(IceCreamShopDataBase context, OrderBindingModel model)
{
if (model == null)
{
@ -47,6 +49,9 @@ namespace IceCreamShopDatabaseImplement.Models
IceCream = context.IceCreams.FirstOrDefault(x => x.Id == model.IceCreamId),
ClientId = model.ClientId,
Client = context.Clients.FirstOrDefault(x => x.Id == model.ClientId),
ImplementerId = model.ImplementerId,
Implementer = (model.ImplementerId.HasValue ? context.Implementers.FirstOrDefault(x => x.Id == model.ImplementerId)
: null),
};
}
@ -58,12 +63,14 @@ namespace IceCreamShopDatabaseImplement.Models
}
Status = model.Status;
DateImplement = model.DateImplement;
ImplementerId = model.ImplementerId;
}
public OrderViewModel GetViewModel => new()
{
IceCreamId = IceCreamId,
ClientId = ClientId,
ImplementerId = ImplementerId,
Count = Count,
Sum = Sum,
Status = Status,
@ -71,7 +78,8 @@ namespace IceCreamShopDatabaseImplement.Models
DateImplement = DateImplement,
IceCreamName = IceCream.IceCreamName,
Id = Id,
ClientFIO = Client.ClientFIO
ClientFIO = Client.ClientFIO,
ImplementerFIO = (Implementer != null ? Implementer.ImplementerFIO : string.Empty)
};
}

View File

@ -16,13 +16,15 @@ namespace IceCreamShopFileImplement
private readonly string IceCreamFileName = "IceCream.xml";
private readonly string ShopFileName = "Shops.xml";
private readonly string ClientFileName = "Client.xml";
public List<Component> Components { get; private set; }
private readonly string ImplementerFileName = "Implementer.xml";
public List<Component> Components { get; private set; }
public List<Order> Orders { get; private set; }
public List<IceCream> IceCreams { get; private set; }
public List<Shop> Shops { get; private set; }
public List<Client> Clients { get; private set; }
public List<Implementer> Implementers { get; private set; }
public static DataFileSingleton GetInstance()
public static DataFileSingleton GetInstance()
{
if (instance == null)
{
@ -41,7 +43,9 @@ namespace IceCreamShopFileImplement
"Shops", x => x.GetXElement);
public void SaveClients() => SaveData(Clients, ClientFileName,
"Clients", x => x.GetXElement);
private DataFileSingleton()
public void SaveImplementers() => SaveData(Implementers, ImplementerFileName,
"Implementers", x => x.GetXElement);
private DataFileSingleton()
{
Components = LoadData(ComponentFileName, "Component", x =>
Component.Create(x)!)!;
@ -53,7 +57,9 @@ namespace IceCreamShopFileImplement
Shop.Create(x)!)!;
Clients = LoadData(ClientFileName, "Client", x =>
Client.Create(x)!)!;
}
Implementers = LoadData(ImplementerFileName, "Implementer", x =>
Implementer.Create(x)!)!;
}
private static List<T>? LoadData<T>(string filename, string xmlNodeName,
Func<XElement, T> selectFunction)
{

View File

@ -0,0 +1,83 @@
using IceCreamShopContracts.BindingModels;
using IceCreamShopContracts.SearchModels;
using IceCreamShopContracts.StoragesContracts;
using IceCreamShopContracts.ViewModels;
using IceCreamShopFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IceCreamShopFileImplement.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 (string.IsNullOrEmpty(model.ImplementerFIO) && string.IsNullOrEmpty(model.Password))
{
return new();
}
return source.Implementers
.Where(x => (string.IsNullOrEmpty(model.ImplementerFIO) || x.ImplementerFIO.Contains(model.ImplementerFIO)) &&
(string.IsNullOrEmpty(model.Password) || x.Password.Contains(model.Password)))
.Select(x => x.GetViewModel)
.ToList();
}
public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{
return source.Implementers
.FirstOrDefault(x => (string.IsNullOrEmpty(model.ImplementerFIO) || x.ImplementerFIO == model.ImplementerFIO) &&
(!model.Id.HasValue || x.Id == model.Id) && (string.IsNullOrEmpty(model.Password) || x.Password == model.Password))
?.GetViewModel;
}
public ImplementerViewModel? Insert(ImplementerBindingModel model)
{
model.Id = source.Implementers.Count > 0 ? source.Implementers.Max(x =>
x.Id) + 1 : 1;
var newImplementer = Implementer.Create(model);
if (newImplementer == null)
{
return null;
}
source.Implementers.Add(newImplementer);
source.SaveImplementers();
return newImplementer.GetViewModel;
}
public ImplementerViewModel? Update(ImplementerBindingModel model)
{
var implementer = source.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (implementer == null)
{
return null;
}
implementer.Update(model);
source.SaveImplementers();
return implementer.GetViewModel;
}
public ImplementerViewModel? Delete(ImplementerBindingModel model)
{
var element = source.Implementers.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
source.Implementers.Remove(element);
source.SaveImplementers();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -22,7 +22,7 @@ namespace IceCreamShopFileImplement.Implements
public List<OrderViewModel> GetFullList()
{
return source.Orders
.Select(x => AccessIceCreamStorage(x.GetViewModel))
.Select(x => AccessStorage(x.GetViewModel))
.ToList();
}
@ -30,15 +30,17 @@ namespace IceCreamShopFileImplement.Implements
model)
{
return source.Orders
.Where(x => (
(!model.Id.HasValue || x.Id == model.Id) &&
(!model.DateFrom.HasValue || x.DateCreate >= model.DateFrom) &&
(!model.DateTo.HasValue || x.DateCreate <= model.DateTo)
&&
(!model.ClientId.HasValue || x.ClientId == model.ClientId)
)
)
.Select(x => AccessIceCreamStorage(x.GetViewModel))
.Where(x => (
(!model.Id.HasValue || x.Id == model.Id) &&
(!model.DateFrom.HasValue || x.DateCreate >= model.DateFrom) &&
(!model.DateTo.HasValue || x.DateCreate <= model.DateTo)
&&
(!model.ClientId.HasValue || x.ClientId == model.ClientId)
&&
(!model.Status.HasValue || x.Status == model.Status)
)
)
.Select(x => AccessStorage(x.GetViewModel))
.ToList();
}
@ -48,8 +50,11 @@ model)
{
return null;
}
return AccessIceCreamStorage(source.Orders
.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))?.GetViewModel);
return AccessStorage(source.Orders
.FirstOrDefault(
x => ((model.Id.HasValue && x.Id == model.Id) ||
(model.ImplementerId.HasValue && model.Status.HasValue &&
x.ImplementerId == model.ImplementerId && x.Status == model.Status)))?.GetViewModel);
}
public OrderViewModel? Insert(OrderBindingModel model)
@ -62,7 +67,7 @@ model)
}
source.Orders.Add(newOrder);
source.SaveOrders();
return AccessIceCreamStorage(newOrder.GetViewModel);
return AccessStorage(newOrder.GetViewModel);
}
public OrderViewModel? Update(OrderBindingModel model)
@ -74,7 +79,7 @@ model)
}
order.Update(model);
source.SaveOrders();
return AccessIceCreamStorage(order.GetViewModel);
return AccessStorage(order.GetViewModel);
}
public OrderViewModel? Delete(OrderBindingModel model)
{
@ -84,30 +89,25 @@ model)
{
source.Orders.Remove(element);
source.SaveOrders();
return AccessIceCreamStorage(element.GetViewModel);
return AccessStorage(element.GetViewModel);
}
return null;
}
public OrderViewModel AccessIceCreamStorage(OrderViewModel model)
public OrderViewModel AccessStorage(OrderViewModel model)
{
if (model == null)
return null;
var iceCream = source.IceCreams.FirstOrDefault(x => (x.Id == model.IceCreamId));
if (iceCream == null)
return model;
model.IceCreamName = iceCream.IceCreamName;
return model;
}
public OrderViewModel AccessClientStorage(OrderViewModel model)
{
if (model == null)
return null;
var client = source.Clients.FirstOrDefault(x => x.Id == model.Id);
if (client != null)
model.ClientFIO = client.ClientFIO;
return model;
var iceCream = source.IceCreams.FirstOrDefault(x => x.Id == model.Id);
var client = source.Clients.FirstOrDefault(x => x.Id == model.Id);
var implementer = source.Implementers.FirstOrDefault(x => x.Id == model.ImplementerId);
if (iceCream != null)
model.IceCreamName = iceCream.IceCreamName;
if (client != null)
model.ClientFIO = client.ClientFIO;
if (implementer != null)
model.ImplementerFIO = implementer.ImplementerFIO;
return model;
}
}
}

View File

@ -0,0 +1,78 @@
using IceCreamShopContracts.BindingModels;
using IceCreamShopContracts.ViewModels;
using IceCreamShopDataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace IceCreamShopFileImplement.Models
{
public class Implementer : IImplementerModel
{
public int Id { get; private set; }
public string ImplementerFIO { get; private set; } = string.Empty;
public string Password { get; set; } = string.Empty;
public int Qualification { get; set; } = 0;
public int WorkExperience { get; set; } = 0;
public static Implementer? Create(ImplementerBindingModel model)
{
if (model == null)
{
return null;
}
return new Implementer()
{
Id = model.Id,
ImplementerFIO = model.ImplementerFIO,
Password = model.Password,
WorkExperience = model.WorkExperience,
Qualification = model.Qualification
};
}
public void Update(ImplementerBindingModel model)
{
if (model == null)
{
return;
}
ImplementerFIO = model.ImplementerFIO;
Password = model.Password;
WorkExperience = model.WorkExperience;
Qualification = model.Qualification;
}
public ImplementerViewModel GetViewModel => new()
{
Id = Id,
ImplementerFIO = ImplementerFIO,
Password = Password,
WorkExperience = WorkExperience,
Qualification = Qualification
};
public static Implementer? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Implementer()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
ImplementerFIO = element.Element("ImplementerFIO")!.Value,
Password = element.Element("Password")!.Value,
Qualification = Convert.ToInt32(element.Element("Qualification")!.Value),
WorkExperience = Convert.ToInt32(element.Element("WorkExperience")!.Value)
};
}
public XElement GetXElement => new("Implementer",
new XAttribute("Id", Id),
new XElement("ImplementerFIO", ImplementerFIO),
new XElement("Password", Password),
new XElement("Qualification", Qualification.ToString()),
new XElement("WorkExperience", WorkExperience.ToString())
);
}
}

View File

@ -15,7 +15,8 @@ namespace IceCreamShopFileImplement.Models
{
public int Id { get; private set; }
public int IceCreamId { get; private set; }
public int ClientId { get; private set; }
public int? ImplementerId { get; private set; } = null;
public int ClientId { get; private set; }
public int Count { get; private set; }
public double Sum { get; private set; }
public OrderStatus Status { get; private set; }
@ -39,6 +40,7 @@ namespace IceCreamShopFileImplement.Models
Status = model.Status,
DateCreate = model.DateCreate,
DateImplement = model.DateImplement,
ImplementerId = model.ImplementerId,
};
}
public static Order? Create(XElement element)
@ -52,7 +54,8 @@ namespace IceCreamShopFileImplement.Models
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
IceCreamId = Convert.ToInt32(element.Element("IceCreamId")!.Value),
ClientId = Convert.ToInt32(element.Element("ClientId")!.Value),
Count = Convert.ToInt32(element.Element("Count")!.Value),
ImplementerId = Convert.ToInt32(element.Element("ImplementerId")!.Value),
Count = Convert.ToInt32(element.Element("Count")!.Value),
Sum = Convert.ToDouble(element.Element("Sum")!.Value),
Status = (OrderStatus)Enum.Parse(typeof(OrderStatus), element.Element("Status")!.Value.ToString()),
DateCreate = Convert.ToDateTime(element.Element("DateCreate")!.Value),
@ -73,6 +76,7 @@ namespace IceCreamShopFileImplement.Models
Id = Id,
IceCreamId = IceCreamId,
ClientId = ClientId,
ImplementerId = ImplementerId,
Count = Count,
Sum = Sum,
Status = Status,

View File

@ -15,14 +15,16 @@ namespace IceCreamShopListImplement
public List<IceCream> IceCreams { get; set; }
public List<Shop> Shops { get; set; }
public List<Client> Clients { get; set; }
private DataListSingleton()
public List<Implementer> Implementers { get; set; }
private DataListSingleton()
{
Components = new List<Component>();
Orders = new List<Order>();
IceCreams = new List<IceCream>();
Shops = new List<Shop>();
Clients = new List<Client>();
}
Implementers = new List<Implementer>();
}
public static DataListSingleton GetInstance()
{
if (_instance == null)

View File

@ -0,0 +1,103 @@
using IceCreamShopContracts.BindingModels;
using IceCreamShopContracts.SearchModels;
using IceCreamShopContracts.StoragesContracts;
using IceCreamShopContracts.ViewModels;
using IceCreamShopListImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IceCreamShopListImplement.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)
{
var result = new List<ImplementerViewModel>();
if (string.IsNullOrEmpty(model.ImplementerFIO) && string.IsNullOrEmpty(model.Password))
{
return result;
}
foreach (var implementer in _source.Implementers)
{
if (implementer.ImplementerFIO.Contains(model.ImplementerFIO))
{
result.Add(implementer.GetViewModel);
}
}
return result;
}
public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{
foreach (var implementer in _source.Implementers)
{
if ((string.IsNullOrEmpty(model.ImplementerFIO) || implementer.ImplementerFIO == model.ImplementerFIO) &&
(!model.Id.HasValue || implementer.Id == model.Id) && (string.IsNullOrEmpty(model.Password) || implementer.Password == model.Password))
{
return implementer.GetViewModel;
}
}
return null;
}
public ImplementerViewModel? Insert(ImplementerBindingModel model)
{
model.Id = 1;
foreach (var implementer in _source.Implementers)
{
if (model.Id <= implementer.Id)
{
model.Id = implementer.Id + 1;
}
}
var newImplementer = Implementer.Create(model);
if (newImplementer == null)
{
return null;
}
_source.Implementers.Add(newImplementer);
return newImplementer.GetViewModel;
}
public ImplementerViewModel? Update(ImplementerBindingModel model)
{
foreach (var implementer in _source.Implementers)
{
if (model.Id == implementer.Id)
{
implementer.Update(model);
return implementer.GetViewModel;
}
}
return null;
}
public ImplementerViewModel? Delete(ImplementerBindingModel model)
{
for (int i = 0; i < _source.Implementers.Count; ++i)
{
if (_source.Implementers[i].Id == model.Id)
{
var element = _source.Implementers[i];
_source.Implementers.RemoveAt(i);
return element.GetViewModel;
}
}
return null;
}
}
}

View File

@ -23,7 +23,7 @@ namespace IceCreamShopListImplement.Implements
var result = new List<OrderViewModel>();
foreach (var order in _source.Orders)
{
result.Add(AccessIceCreamStorage(order.GetViewModel));
result.Add(AccessStorage(order.GetViewModel));
}
return result;
}
@ -34,11 +34,14 @@ namespace IceCreamShopListImplement.Implements
foreach (var order in _source.Orders)
{
if ((!model.Id.HasValue || order.Id == model.Id) &&
(!model.DateFrom.HasValue || order.DateCreate >= model.DateFrom) &&
(!model.DateTo.HasValue || order.DateCreate <= model.DateTo) &&
(!model.ClientId.HasValue || order.ClientId == model.ClientId)) ;
(!model.DateFrom.HasValue || order.DateCreate >= model.DateFrom) &&
(!model.DateTo.HasValue || order.DateCreate <= model.DateTo)
&&
(!model.ClientId.HasValue || order.ClientId == model.ClientId)
&&
(!model.Status.HasValue || order.Status == model.Status)) ;
{
result.Add(AccessIceCreamStorage(order.GetViewModel));
result.Add(AccessStorage(order.GetViewModel));
}
}
return result;
@ -51,9 +54,11 @@ namespace IceCreamShopListImplement.Implements
}
foreach (var order in _source.Orders)
{
if (model.Id.HasValue && order.Id == model.Id)
if ((model.Id.HasValue && order.Id == model.Id) ||
(model.ImplementerId.HasValue && model.Status.HasValue &&
order.ImplementerId == model.ImplementerId && order.Status == model.Status))
{
return order.GetViewModel;
return AccessStorage(order.GetViewModel);
}
}
return null;
@ -102,28 +107,23 @@ namespace IceCreamShopListImplement.Implements
return null;
}
public OrderViewModel AccessIceCreamStorage(OrderViewModel model)
{
foreach (var iceCream in _source.IceCreams)
{
if (iceCream.Id == model.IceCreamId)
{
model.IceCreamName = iceCream.IceCreamName;
break;
}
}
return model;
}
public OrderViewModel AccessClientStorage(OrderViewModel model)
{
var client = _source.Clients.FirstOrDefault(x => x.Id == model.ClientId);
if (client != null)
model.ClientFIO = client.ClientFIO;
return model;
}
public OrderViewModel AccessStorage(OrderViewModel model)
{
if (model == null)
return null;
var iceCream = _source.IceCreams.FirstOrDefault(x => x.Id == model.Id);
var client = _source.Clients.FirstOrDefault(x => x.Id == model.Id);
var implementer = _source.Implementers.FirstOrDefault(x => x.Id == model.ImplementerId);
if (iceCream != null)
model.IceCreamName = iceCream.IceCreamName;
if (client != null)
model.ClientFIO = client.ClientFIO;
if (implementer != null)
model.ImplementerFIO = implementer.ImplementerFIO;
return model;
}
}
}
}

View File

@ -0,0 +1,54 @@
using IceCreamShopContracts.BindingModels;
using IceCreamShopContracts.ViewModels;
using IceCreamShopDataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IceCreamShopListImplement.Models
{
public class Implementer : IImplementerModel
{
public int Id { get; private set; }
public string ImplementerFIO { get; private set; } = string.Empty;
public string Password { get; set; } = string.Empty;
public int WorkExperience { get; set; } = 0;
public int Qualification { get; set; } = 0;
public static Implementer? Create(ImplementerBindingModel model)
{
if (model == null)
{
return null;
}
return new Implementer()
{
Id = model.Id,
ImplementerFIO = model.ImplementerFIO,
Password = model.Password,
WorkExperience = model.WorkExperience,
Qualification = model.Qualification
};
}
public void Update(ImplementerBindingModel model)
{
if (model == null)
{
return;
}
ImplementerFIO = model.ImplementerFIO;
Password = model.Password;
WorkExperience = model.WorkExperience;
Qualification = model.Qualification;
}
public ImplementerViewModel GetViewModel => new()
{
Id = Id,
ImplementerFIO = ImplementerFIO,
Password = Password,
WorkExperience = WorkExperience,
Qualification = Qualification
};
}
}

View File

@ -18,7 +18,8 @@ namespace IceCreamShopListImplement.Models
public int Id { get; private set; }
public int IceCreamId { get; private set; }
public int ClientId { get; private set; }
public int Count { get; private set; }
public int? ImplementerId { get; private set; }
public int Count { get; private set; }
public double Sum { get; private set; }
public OrderStatus Status { get; private set; }
public DateTime DateCreate { get; private set; }
@ -40,6 +41,7 @@ namespace IceCreamShopListImplement.Models
Status = model.Status,
DateCreate =model.DateCreate,
DateImplement = model.DateImplement,
ImplementerId = model.ImplementerId
};
}
public void Update(OrderBindingModel? model)
@ -55,12 +57,14 @@ namespace IceCreamShopListImplement.Models
Sum = model.Sum;
Status = model.Status;
DateImplement = model.DateImplement;
ImplementerId = model.ImplementerId;
}
public OrderViewModel GetViewModel => new()
{
Id = Id,
IceCreamId = IceCreamId,
ClientId = ClientId,
ImplementerId = ImplementerId,
Count = Count,
Sum = Sum,
Status = Status,

View File

@ -0,0 +1,105 @@
using DocumentFormat.OpenXml.Office2010.Excel;
using IceCreamShopContracts.BindingModels;
using IceCreamShopContracts.BusinessLogicsContracts;
using IceCreamShopContracts.SearchModels;
using IceCreamShopContracts.ViewModels;
using IceCreamShopDataModels.Enums;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace IceCreamShopRestApi.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class ImplementerController : ControllerBase
{
private readonly ILogger _logger;
private readonly IOrderLogic _order;
private readonly IImplementerLogic _logic;
public ImplementerController(IOrderLogic order, IImplementerLogic logic,
ILogger<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;
}
}
}
}