ПИбд-22 Боровков М В 6 лабораторная работа #7

Closed
bekodeg wants to merge 14 commits from labWork6 into labWork5
49 changed files with 1899 additions and 363 deletions

2
.gitignore vendored
View File

@ -371,6 +371,8 @@ healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017 # Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/ MigrationBackup/
Migrations/
# Ionide (cross platform F# VS Code tools) working folder # Ionide (cross platform F# VS Code tools) working folder
.ionide/ .ionide/

View File

@ -0,0 +1,173 @@
namespace SushiBar.Forms
{
partial class FormImplementer
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
FIOTextBox = new TextBox();
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.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
FIOTextBox.Location = new Point(124, 19);
FIOTextBox.Name = "FIOTextBox";
FIOTextBox.Size = new Size(411, 27);
FIOTextBox.TabIndex = 0;
//
// PasswordTextBox
//
PasswordTextBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
PasswordTextBox.Location = new Point(124, 52);
PasswordTextBox.Name = "PasswordTextBox";
PasswordTextBox.Size = new Size(411, 27);
PasswordTextBox.TabIndex = 1;
//
// QualificationTextBox
//
QualificationTextBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
QualificationTextBox.Location = new Point(124, 85);
QualificationTextBox.Name = "QualificationTextBox";
QualificationTextBox.Size = new Size(411, 27);
QualificationTextBox.TabIndex = 2;
//
// WorkExperienceTextBox
//
WorkExperienceTextBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
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.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
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.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
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
//
AllowDrop = true;
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);
MaximizeBox = false;
MinimizeBox = false;
Name = "ImplementerForm";
ShowInTaskbar = false;
Text = "Исполнитель";
TopMost = true;
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,96 @@
using Microsoft.Extensions.Logging;
using SushiBarContracts.BindingModels;
using SushiBarContracts.BusinessLogicsContracts;
using SushiBarContracts.SearchModels;
namespace SushiBar.Forms
{
public partial class FormImplementer : Form
{
private readonly ILogger _logger;
private readonly IImplementerLogic _logic;
private int? _id;
public int Id { set { _id = value; } }
public FormImplementer(ILogger<FormImplementer> 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,121 @@
namespace SushiBar.Forms
{
partial class FormImplementers
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
dataGridView = new DataGridView();
CreateButton = new Button();
ChangeButton = new Button();
DeleteButton = new Button();
RefreshButton = new Button();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// dataGridView
//
dataGridView.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(12, 12);
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersWidth = 51;
dataGridView.RowTemplate.Height = 29;
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.Size = new Size(565, 426);
dataGridView.TabIndex = 0;
//
// CreateButton
//
CreateButton.Anchor = AnchorStyles.Top | AnchorStyles.Right;
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.Anchor = AnchorStyles.Top | AnchorStyles.Right;
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.Anchor = AnchorStyles.Top | AnchorStyles.Right;
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.Anchor = AnchorStyles.Top | AnchorStyles.Right;
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;
//
// FormImplementers
//
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(dataGridView);
Name = "FormImplementers";
Text = "Исполнители";
WindowState = FormWindowState.Maximized;
Load += ImplementersForm_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
private Button CreateButton;
private Button ChangeButton;
private Button DeleteButton;
private Button RefreshButton;
}
}

View File

@ -0,0 +1,108 @@
using Microsoft.Extensions.Logging;
using SushiBarContracts.BindingModels;
using SushiBarContracts.BusinessLogicsContracts;
namespace SushiBar.Forms
{
public partial class FormImplementers : Form
{
private readonly ILogger _logger;
private readonly IImplementerLogic _logic;
public FormImplementers(ILogger<FormImplementers> logger, IImplementerLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void ImplementersForm_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["Password"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["Qualification"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.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(FormImplementer));
if (service is FormImplementer form)
{
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
private void ChangeButton_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormImplementer));
if (service is FormImplementer form)
{
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
}
private void DeleteButton_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Удаление компонента");
try
{
if (!_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

@ -33,6 +33,8 @@
toolStripMenuItem = new ToolStripMenuItem(); toolStripMenuItem = new ToolStripMenuItem();
sushiToolStripMenuItem = new ToolStripMenuItem(); sushiToolStripMenuItem = new ToolStripMenuItem();
componentsToolStripMenuItem = new ToolStripMenuItem(); componentsToolStripMenuItem = new ToolStripMenuItem();
clientsToolStripMenuItem = new ToolStripMenuItem();
implementersToolStripMenuItem = new ToolStripMenuItem();
отчётыToolStripMenuItem1 = new ToolStripMenuItem(); отчётыToolStripMenuItem1 = new ToolStripMenuItem();
sushisReportToolStripMenuItem = new ToolStripMenuItem(); sushisReportToolStripMenuItem = new ToolStripMenuItem();
componentsReportПоСушиToolStripMenuItem = new ToolStripMenuItem(); componentsReportПоСушиToolStripMenuItem = new ToolStripMenuItem();
@ -46,7 +48,7 @@
buttonOrderReady = new Button(); buttonOrderReady = new Button();
buttonIssuedOrder = new Button(); buttonIssuedOrder = new Button();
buttonRef = new Button(); buttonRef = new Button();
clientsToolStripMenuItem = new ToolStripMenuItem(); startWorksToolStripMenuItem = new ToolStripMenuItem();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
menuStrip1.SuspendLayout(); menuStrip1.SuspendLayout();
SuspendLayout(); SuspendLayout();
@ -66,7 +68,7 @@
// menuStrip1 // menuStrip1
// //
menuStrip1.ImageScalingSize = new Size(20, 20); menuStrip1.ImageScalingSize = new Size(20, 20);
menuStrip1.Items.AddRange(new ToolStripItem[] { toolStripMenuItem, отчётыToolStripMenuItem1 }); menuStrip1.Items.AddRange(new ToolStripItem[] { toolStripMenuItem, отчётыToolStripMenuItem1, startWorksToolStripMenuItem });
menuStrip1.Location = new Point(0, 0); menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1"; menuStrip1.Name = "menuStrip1";
menuStrip1.Size = new Size(1184, 28); menuStrip1.Size = new Size(1184, 28);
@ -75,7 +77,7 @@
// //
// toolStripMenuItem // toolStripMenuItem
// //
toolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { sushiToolStripMenuItem, componentsToolStripMenuItem, clientsToolStripMenuItem }); toolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { sushiToolStripMenuItem, componentsToolStripMenuItem, clientsToolStripMenuItem, implementersToolStripMenuItem });
toolStripMenuItem.Name = "toolStripMenuItem"; toolStripMenuItem.Name = "toolStripMenuItem";
toolStripMenuItem.Size = new Size(117, 24); toolStripMenuItem.Size = new Size(117, 24);
toolStripMenuItem.Text = "Справочники"; toolStripMenuItem.Text = "Справочники";
@ -94,6 +96,20 @@
componentsToolStripMenuItem.Text = "Компоненты"; componentsToolStripMenuItem.Text = "Компоненты";
componentsToolStripMenuItem.Click += ComponentsToolStripMenuItem_Click; componentsToolStripMenuItem.Click += ComponentsToolStripMenuItem_Click;
// //
// clientsToolStripMenuItem
//
clientsToolStripMenuItem.Name = "clientsToolStripMenuItem";
clientsToolStripMenuItem.Size = new Size(224, 26);
clientsToolStripMenuItem.Text = "Клиенты";
clientsToolStripMenuItem.Click += clientsToolStripMenuItem_Click;
//
// implementersToolStripMenuItem
//
implementersToolStripMenuItem.Name = "implementersToolStripMenuItem";
implementersToolStripMenuItem.Size = new Size(224, 26);
implementersToolStripMenuItem.Text = "Исполнители";
implementersToolStripMenuItem.Click += implementersToolStripMenuItem_Click;
//
// отчётыToolStripMenuItem1 // отчётыToolStripMenuItem1
// //
отчётыToolStripMenuItem1.DropDownItems.AddRange(new ToolStripItem[] { sushisReportToolStripMenuItem, componentsReportПоСушиToolStripMenuItem, orderReportToolStripMenuItem }); отчётыToolStripMenuItem1.DropDownItems.AddRange(new ToolStripItem[] { sushisReportToolStripMenuItem, componentsReportПоСушиToolStripMenuItem, orderReportToolStripMenuItem });
@ -197,12 +213,12 @@
buttonRef.UseVisualStyleBackColor = true; buttonRef.UseVisualStyleBackColor = true;
buttonRef.Click += ButtonRef_Click; buttonRef.Click += ButtonRef_Click;
// //
// clientsToolStripMenuItem // startWorksToolStripMenuItem
// //
clientsToolStripMenuItem.Name = "clientsToolStripMenuItem"; startWorksToolStripMenuItem.Name = "startWorksToolStripMenuItem";
clientsToolStripMenuItem.Size = new Size(224, 26); startWorksToolStripMenuItem.Size = new Size(114, 24);
clientsToolStripMenuItem.Text = "Клиенты"; startWorksToolStripMenuItem.Text = "Запуск работ";
clientsToolStripMenuItem.Click += clientsToolStripMenuItem_Click; startWorksToolStripMenuItem.Click += startWorksToolStripMenuItem_Click;
// //
// FormMain // FormMain
// //
@ -250,5 +266,7 @@
private ToolStripMenuItem componentsReportПоСушиToolStripMenuItem; private ToolStripMenuItem componentsReportПоСушиToolStripMenuItem;
private ToolStripMenuItem orderReportToolStripMenuItem; private ToolStripMenuItem orderReportToolStripMenuItem;
private ToolStripMenuItem clientsToolStripMenuItem; private ToolStripMenuItem clientsToolStripMenuItem;
private ToolStripMenuItem implementersToolStripMenuItem;
private ToolStripMenuItem startWorksToolStripMenuItem;
} }
} }

View File

@ -10,12 +10,14 @@ namespace SushiBar.Forms
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IOrderLogic _orderLogic; private readonly IOrderLogic _orderLogic;
private readonly IReportLogic _reportLogic; private readonly IReportLogic _reportLogic;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic) private readonly IWorkProcess _workProcess;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess)
{ {
InitializeComponent(); InitializeComponent();
_logger = logger; _logger = logger;
_orderLogic = orderLogic; _orderLogic = orderLogic;
_reportLogic = reportLogic; _reportLogic = reportLogic;
_workProcess = workProcess;
} }
private void FormMain_Load(object sender, EventArgs e) private void FormMain_Load(object sender, EventArgs e)
{ {
@ -31,6 +33,7 @@ namespace SushiBar.Forms
dataGridView.DataSource = list; dataGridView.DataSource = list;
dataGridView.Columns["SushiId"].Visible = false; dataGridView.Columns["SushiId"].Visible = false;
dataGridView.Columns["ClientId"].Visible = false; dataGridView.Columns["ClientId"].Visible = false;
dataGridView.Columns["ImplementerId"].Visible = false;
dataGridView.Columns["SushiName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dataGridView.Columns["SushiName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
} }
_logger.LogInformation("Загрузка заказов"); _logger.LogInformation("Загрузка заказов");
@ -177,5 +180,20 @@ namespace SushiBar.Forms
form.ShowDialog(); form.ShowDialog();
} }
} }
private void implementersToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormImplementers));
if (service is FormImplementers form)
{
form.ShowDialog();
}
}
private void startWorksToolStripMenuItem_Click(object sender, EventArgs e)
{
_workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic);
MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
} }
} }

View File

@ -1,4 +1,5 @@
using Microsoft.Extensions.DependencyInjection; using IceCreamShopContracts.StoragesContracts;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging; using NLog.Extensions.Logging;
using SushiBar.Forms; using SushiBar.Forms;
@ -40,12 +41,15 @@ namespace SushiBar
services.AddTransient<IOrderStorage, OrderStorage>(); services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<ISushiStorage, SushiStorage>(); services.AddTransient<ISushiStorage, SushiStorage>();
services.AddTransient<IClientStorage, ClientStorage>(); services.AddTransient<IClientStorage, ClientStorage>();
services.AddTransient<IImplementerStorage, ImplementerStorage>();
services.AddTransient<IComponentLogic, ComponentLogic>(); services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IOrderLogic, OrderLogic>(); services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<ISushiLogic, SushiLogic>(); services.AddTransient<ISushiLogic, SushiLogic>();
services.AddTransient<IReportLogic, ReportLogic>(); services.AddTransient<IReportLogic, ReportLogic>();
services.AddTransient<IClientLogic, ClientLogic>(); services.AddTransient<IClientLogic, ClientLogic>();
services.AddTransient<IImplementerLogic, ImplementerLogic>();
services.AddTransient<IWorkProcess, WorkModeling>();
services.AddTransient<FormMain>(); services.AddTransient<FormMain>();
services.AddTransient<FormComponent>(); services.AddTransient<FormComponent>();
@ -57,6 +61,8 @@ namespace SushiBar
services.AddTransient<FormSushis>(); services.AddTransient<FormSushis>();
services.AddTransient<FormReportSushiComponents>(); services.AddTransient<FormReportSushiComponents>();
services.AddTransient<FormReportOrders>(); services.AddTransient<FormReportOrders>();
services.AddTransient<FormImplementers>();
services.AddTransient<FormImplementer>();
services.AddTransient<AbstractSaveToExcel, SaveToExcel>(); services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
services.AddTransient<AbstractSaveToWord, SaveToWord>(); services.AddTransient<AbstractSaveToWord, SaveToWord>();

View File

@ -11,8 +11,7 @@ namespace SushiBarBusinessLogic.BusinessLogics
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IClientStorage _clientStorage; private readonly IClientStorage _clientStorage;
public ClientLogic(ILogger<ClientLogic> logger, IClientStorage public ClientLogic(ILogger<ClientLogic> logger, IClientStorage componentStorage)
componentStorage)
{ {
_logger = logger; _logger = logger;
_clientStorage = componentStorage; _clientStorage = componentStorage;

View File

@ -0,0 +1,116 @@
using IceCreamShopContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using SushiBarContracts.BindingModels;
using SushiBarContracts.BusinessLogicsContracts;
using SushiBarContracts.SearchModels;
using SushiBarContracts.ViewModels;
namespace SushiBarBusinessLogic.BusinessLogics
{
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

@ -30,6 +30,18 @@ namespace SushiBarBusinessLogic.BusinessLogics
_logger.LogInformation("ReadList. Count:{Count}", list.Count); _logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list; return list;
} }
public OrderViewModel? ReadElement(OrderSearchModel model)
{
_logger.LogInformation("ReadElement.");
var element = model == null ? null : _orderStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("ReadElement return null list");
return null;
}
_logger.LogInformation("ReadElement Id:{ Id}", element.Id);
return element;
}
public bool CreateOrder(OrderBindingModel model) public bool CreateOrder(OrderBindingModel model)
{ {
CheckModel(model); CheckModel(model);
@ -73,12 +85,19 @@ namespace SushiBarBusinessLogic.BusinessLogics
throw new ArgumentNullException(nameof(element)); throw new ArgumentNullException(nameof(element));
} }
if (element.ImplementerId != null && model.ImplementerId != null && model.ImplementerId != element.ImplementerId)
{
throw new InvalidOperationException(nameof(model.ImplementerId));
}
model.SushiId = element.SushiId; model.SushiId = element.SushiId;
model.DateCreate = element.DateCreate; model.DateCreate = element.DateCreate;
model.DateImplement = element.DateImplement; model.DateImplement = element.DateImplement;
model.Status = element.Status; model.Status = element.Status;
model.Count = element.Count; model.Count = element.Count;
model.Sum = element.Sum; model.Sum = element.Sum;
model.ClientId = element.ClientId;
model.ImplementerId = element.ImplementerId.HasValue ? element.ImplementerId : model.ImplementerId;
if (model.Status != orderStatus - 1) if (model.Status != orderStatus - 1)
{ {

View File

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

View File

@ -17,7 +17,6 @@ if (!app.Environment.IsDevelopment())
app.UseHsts(); app.UseHsts();
} }
app.UseHttpsRedirection();
app.UseStaticFiles(); app.UseStaticFiles();
app.UseRouting(); app.UseRouting();

View File

@ -13,7 +13,7 @@
"commandName": "Project", "commandName": "Project",
"dotnetRunMessages": true, "dotnetRunMessages": true,
"launchBrowser": true, "launchBrowser": true,
"applicationUrl": "http://localhost:5271", "applicationUrl": "http://localhost:5051",
"environmentVariables": { "environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development" "ASPNETCORE_ENVIRONMENT": "Development"
} }

View File

@ -0,0 +1,13 @@
using SushiBarDataModels.Models;
namespace SushiBarContracts.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,5 +13,6 @@ namespace SushiBarContracts.BindingModels
public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; public OrderStatus Status { get; set; } = OrderStatus.Неизвестен;
public DateTime DateCreate { get; set; } = DateTime.Now; public DateTime DateCreate { get; set; } = DateTime.Now;
public DateTime? DateImplement { get; set; } public DateTime? DateImplement { get; set; }
public int? ImplementerId { get; set; }
} }
} }

View File

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

View File

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

View File

@ -0,0 +1,7 @@
namespace SushiBarContracts.BusinessLogicsContracts
{
public interface IWorkProcess
{
void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic);
}
}

View File

@ -0,0 +1,9 @@
namespace SushiBarContracts.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,6 @@
namespace SushiBarContracts.SearchModels using SushiBarDataModels.Enums;
namespace SushiBarContracts.SearchModels
{ {
public class OrderSearchModel public class OrderSearchModel
{ {
@ -6,5 +8,7 @@
public int? ClientId { get; set; } public int? ClientId { get; set; }
public DateTime? DateFrom { get; set; } public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; } public DateTime? DateTo { get; set; }
public OrderStatus? Status { get; set; }
public int? ImplementerId { get; set; }
} }
} }

View File

@ -0,0 +1,16 @@
using SushiBarContracts.BindingModels;
using SushiBarContracts.SearchModels;
using SushiBarContracts.ViewModels;
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,18 @@
using SushiBarDataModels.Models;
using System.ComponentModel;
namespace SushiBarContracts.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

@ -10,10 +10,13 @@ namespace SushiBarContracts.ViewModels
public int Id { get; set; } public int Id { get; set; }
public int SushiId { get; set; } public int SushiId { get; set; }
public int ClientId { get; set; } public int ClientId { get; set; }
public int? ImplementerId { get; set; }
[DisplayName("Клиент")] [DisplayName("Клиент")]
public string ClientFIO { get; set; } = string.Empty; public string ClientFIO { get; set; } = string.Empty;
[DisplayName("Суши")] [DisplayName("Суши")]
public string SushiName { get; set; } = string.Empty; public string SushiName { get; set; } = string.Empty;
[DisplayName("Исполнитель")]
public string ImplementerName { get; set;} = string.Empty;
[DisplayName("Количество")] [DisplayName("Количество")]
public int Count { get; set; } public int Count { get; set; }
[DisplayName("Сумма")] [DisplayName("Сумма")]

View File

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

View File

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

View File

@ -0,0 +1,83 @@
using IceCreamShopContracts.StoragesContracts;
using SushiBarContracts.BindingModels;
using SushiBarContracts.SearchModels;
using SushiBarContracts.ViewModels;
using SushiBarDatabaseImplement.Models;
namespace SushiBarDatabaseImplement.Implements
{
public class ImplementerStorage : IImplementerStorage
{
public ImplementerViewModel? Delete(ImplementerBindingModel model)
{
using var context = new SushiBarDatabase();
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 SushiBarDatabase();
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 SushiBarDatabase();
return context.Implementers.Select(x => x.GetViewModel).ToList();
}
public ImplementerViewModel? Insert(ImplementerBindingModel model)
{
using var context = new SushiBarDatabase();
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 SushiBarDatabase();
var res = context.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (res != null)
{
res.Update(model);
context.SaveChanges();
}
return res?.GetViewModel;
}
}
}

View File

@ -16,6 +16,7 @@ namespace SushiBarDatabaseImplement.Implements
return context.Orders return context.Orders
.Include(o => o.Sushi) .Include(o => o.Sushi)
.Include(o => o.Client) .Include(o => o.Client)
.Include(o => o.Implementer)
.Select(o => o.GetViewModel) .Select(o => o.GetViewModel)
.ToList(); .ToList();
} }
@ -25,12 +26,13 @@ namespace SushiBarDatabaseImplement.Implements
return context.Orders return context.Orders
.Include(o => o.Sushi) .Include(o => o.Sushi)
.Include(o => o.Client) .Include(o => o.Client)
.Where(o => ( .Include(o => o.Implementer)
.Where(o =>
(!model.Id.HasValue || o.Id == model.Id) && (!model.Id.HasValue || o.Id == model.Id) &&
(!model.DateFrom.HasValue || o.DateCreate >= model.DateFrom) && (!model.DateFrom.HasValue || o.DateCreate >= model.DateFrom) &&
(!model.DateTo.HasValue || o.DateCreate <= model.DateTo) && (!model.DateTo.HasValue || o.DateCreate <= model.DateTo) &&
(!model.ClientId.HasValue || o.ClientId == model.ClientId) (!model.ClientId.HasValue || o.ClientId == model.ClientId) &&
)) (!model.Status.HasValue || o.Status == model.Status))
.Select(o => o.GetViewModel) .Select(o => o.GetViewModel)
.ToList(); .ToList();
} }
@ -38,9 +40,16 @@ namespace SushiBarDatabaseImplement.Implements
{ {
using var context = new SushiBarDatabase(); using var context = new SushiBarDatabase();
return context.Orders return context.Orders
.Include (o => o.Sushi) .Include(o => o.Sushi)
.Include(o => o.Client) .Include(o => o.Client)
.FirstOrDefault(o => o.Id == model.Id)?.GetViewModel; .Include(o => o.Implementer)
.FirstOrDefault(o =>
(!model.Id.HasValue || o.Id == model.Id) &&
(!model.DateFrom.HasValue || o.DateCreate >= model.DateFrom) &&
(!model.DateTo.HasValue || o.DateCreate <= model.DateTo) &&
(!model.ClientId.HasValue || o.ClientId == model.ClientId) &&
(!model.Status.HasValue || o.Status == model.Status))?
.GetViewModel;
} }
public OrderViewModel? Insert(OrderBindingModel model) public OrderViewModel? Insert(OrderBindingModel model)
{ {
@ -63,6 +72,7 @@ namespace SushiBarDatabaseImplement.Implements
var order = context.Orders var order = context.Orders
.Include(o => o.Sushi) .Include(o => o.Sushi)
.Include(o => o.Client) .Include(o => o.Client)
.Include(o => o.Implementer)
.FirstOrDefault(o => o.Id == model.Id); .FirstOrDefault(o => o.Id == model.Id);
if (order == null) if (order == null)
{ {
@ -85,6 +95,7 @@ namespace SushiBarDatabaseImplement.Implements
var element = context.Orders var element = context.Orders
.Include(o => o.Sushi) .Include(o => o.Sushi)
.Include(o => o.Client) .Include(o => o.Client)
.Include(o => o.Implementer)
.FirstOrDefault(o => o.Id == model.Id); .FirstOrDefault(o => o.Id == model.Id);
if (element != null) if (element != null)
{ {

View File

@ -1,171 +0,0 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using SushiBarDatabaseImplement;
#nullable disable
namespace SushiBarDatabaseImplement.Migrations
{
[DbContext(typeof(SushiBarDatabase))]
[Migration("20240424132544_InitialCreate")]
partial class InitialCreate
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.16")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("SushiBarDatabaseImplement.Models.Component", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ComponentName")
.IsRequired()
.HasColumnType("text");
b.Property<double>("Cost")
.HasColumnType("double precision");
b.HasKey("Id");
b.ToTable("Components");
});
modelBuilder.Entity("SushiBarDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<DateTime>("DateCreate")
.HasColumnType("timestamp without time zone");
b.Property<DateTime?>("DateImplement")
.HasColumnType("timestamp without time zone");
b.Property<int>("Status")
.HasColumnType("integer");
b.Property<double>("Sum")
.HasColumnType("double precision");
b.Property<int>("SushiId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("SushiId");
b.ToTable("Orders");
});
modelBuilder.Entity("SushiBarDatabaseImplement.Models.Sushi", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<double>("Price")
.HasColumnType("double precision");
b.Property<string>("SushiName")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Sushis");
});
modelBuilder.Entity("SushiBarDatabaseImplement.Models.SushiComponent", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("ComponentId")
.HasColumnType("integer");
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<int>("SushiId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ComponentId");
b.HasIndex("SushiId");
b.ToTable("SushiComponents");
});
modelBuilder.Entity("SushiBarDatabaseImplement.Models.Order", b =>
{
b.HasOne("SushiBarDatabaseImplement.Models.Sushi", "Sushi")
.WithMany("Orders")
.HasForeignKey("SushiId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Sushi");
});
modelBuilder.Entity("SushiBarDatabaseImplement.Models.SushiComponent", b =>
{
b.HasOne("SushiBarDatabaseImplement.Models.Component", "Component")
.WithMany("SushiComponents")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SushiBarDatabaseImplement.Models.Sushi", "Sushi")
.WithMany("Components")
.HasForeignKey("SushiId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Component");
b.Navigation("Sushi");
});
modelBuilder.Entity("SushiBarDatabaseImplement.Models.Component", b =>
{
b.Navigation("SushiComponents");
});
modelBuilder.Entity("SushiBarDatabaseImplement.Models.Sushi", b =>
{
b.Navigation("Components");
b.Navigation("Orders");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -1,126 +0,0 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace SushiBarDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class InitialCreate : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Components",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
ComponentName = table.Column<string>(type: "text", nullable: false),
Cost = table.Column<double>(type: "double precision", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Components", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Sushis",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
SushiName = table.Column<string>(type: "text", nullable: false),
Price = table.Column<double>(type: "double precision", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Sushis", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Orders",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Count = table.Column<int>(type: "integer", nullable: false),
Sum = table.Column<double>(type: "double precision", nullable: false),
Status = table.Column<int>(type: "integer", nullable: false),
DateCreate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
DateImplement = table.Column<DateTime>(type: "timestamp without time zone", nullable: true),
SushiId = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Orders", x => x.Id);
table.ForeignKey(
name: "FK_Orders_Sushis_SushiId",
column: x => x.SushiId,
principalTable: "Sushis",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "SushiComponents",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
SushiId = table.Column<int>(type: "integer", nullable: false),
ComponentId = table.Column<int>(type: "integer", nullable: false),
Count = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_SushiComponents", x => x.Id);
table.ForeignKey(
name: "FK_SushiComponents_Components_ComponentId",
column: x => x.ComponentId,
principalTable: "Components",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_SushiComponents_Sushis_SushiId",
column: x => x.SushiId,
principalTable: "Sushis",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Orders_SushiId",
table: "Orders",
column: "SushiId");
migrationBuilder.CreateIndex(
name: "IX_SushiComponents_ComponentId",
table: "SushiComponents",
column: "ComponentId");
migrationBuilder.CreateIndex(
name: "IX_SushiComponents_SushiId",
table: "SushiComponents",
column: "SushiId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Orders");
migrationBuilder.DropTable(
name: "SushiComponents");
migrationBuilder.DropTable(
name: "Components");
migrationBuilder.DropTable(
name: "Sushis");
}
}
}

View File

@ -12,8 +12,8 @@ using SushiBarDatabaseImplement;
namespace SushiBarDatabaseImplement.Migrations namespace SushiBarDatabaseImplement.Migrations
{ {
[DbContext(typeof(SushiBarDatabase))] [DbContext(typeof(SushiBarDatabase))]
[Migration("20240504135651_rezero")] [Migration("20240507181620_lab6")]
partial class rezero partial class lab6
{ {
/// <inheritdoc /> /// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder) protected override void BuildTargetModel(ModelBuilder modelBuilder)
@ -70,6 +70,33 @@ namespace SushiBarDatabaseImplement.Migrations
b.ToTable("Components"); b.ToTable("Components");
}); });
modelBuilder.Entity("SushiBarDatabaseImplement.Models.Implementer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ImplementerFIO")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("text");
b.Property<int>("Qualification")
.HasColumnType("integer");
b.Property<int>("WorkExperience")
.HasColumnType("integer");
b.HasKey("Id");
b.ToTable("Implementers");
});
modelBuilder.Entity("SushiBarDatabaseImplement.Models.Order", b => modelBuilder.Entity("SushiBarDatabaseImplement.Models.Order", b =>
{ {
b.Property<int>("Id") b.Property<int>("Id")
@ -90,6 +117,9 @@ namespace SushiBarDatabaseImplement.Migrations
b.Property<DateTime?>("DateImplement") b.Property<DateTime?>("DateImplement")
.HasColumnType("timestamp without time zone"); .HasColumnType("timestamp without time zone");
b.Property<int?>("ImplementerId")
.HasColumnType("integer");
b.Property<int>("Status") b.Property<int>("Status")
.HasColumnType("integer"); .HasColumnType("integer");
@ -103,6 +133,8 @@ namespace SushiBarDatabaseImplement.Migrations
b.HasIndex("ClientId"); b.HasIndex("ClientId");
b.HasIndex("ImplementerId");
b.HasIndex("SushiId"); b.HasIndex("SushiId");
b.ToTable("Orders"); b.ToTable("Orders");
@ -162,6 +194,10 @@ namespace SushiBarDatabaseImplement.Migrations
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
.IsRequired(); .IsRequired();
b.HasOne("SushiBarDatabaseImplement.Models.Implementer", "Implementer")
.WithMany("Orders")
.HasForeignKey("ImplementerId");
b.HasOne("SushiBarDatabaseImplement.Models.Sushi", "Sushi") b.HasOne("SushiBarDatabaseImplement.Models.Sushi", "Sushi")
.WithMany("Orders") .WithMany("Orders")
.HasForeignKey("SushiId") .HasForeignKey("SushiId")
@ -170,6 +206,8 @@ namespace SushiBarDatabaseImplement.Migrations
b.Navigation("Client"); b.Navigation("Client");
b.Navigation("Implementer");
b.Navigation("Sushi"); b.Navigation("Sushi");
}); });
@ -197,6 +235,11 @@ namespace SushiBarDatabaseImplement.Migrations
b.Navigation("SushiComponents"); b.Navigation("SushiComponents");
}); });
modelBuilder.Entity("SushiBarDatabaseImplement.Models.Implementer", b =>
{
b.Navigation("Orders");
});
modelBuilder.Entity("SushiBarDatabaseImplement.Models.Sushi", b => modelBuilder.Entity("SushiBarDatabaseImplement.Models.Sushi", b =>
{ {
b.Navigation("Components"); b.Navigation("Components");

View File

@ -7,7 +7,7 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace SushiBarDatabaseImplement.Migrations namespace SushiBarDatabaseImplement.Migrations
{ {
/// <inheritdoc /> /// <inheritdoc />
public partial class rezero : Migration public partial class lab6 : Migration
{ {
/// <inheritdoc /> /// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder) protected override void Up(MigrationBuilder migrationBuilder)
@ -41,6 +41,22 @@ namespace SushiBarDatabaseImplement.Migrations
table.PrimaryKey("PK_Components", x => x.Id); table.PrimaryKey("PK_Components", x => x.Id);
}); });
migrationBuilder.CreateTable(
name: "Implementers",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
ImplementerFIO = table.Column<string>(type: "text", nullable: false),
Password = table.Column<string>(type: "text", nullable: false),
Qualification = table.Column<int>(type: "integer", nullable: false),
WorkExperience = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Implementers", x => x.Id);
});
migrationBuilder.CreateTable( migrationBuilder.CreateTable(
name: "Sushis", name: "Sushis",
columns: table => new columns: table => new
@ -67,7 +83,8 @@ namespace SushiBarDatabaseImplement.Migrations
DateCreate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false), DateCreate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
DateImplement = table.Column<DateTime>(type: "timestamp without time zone", nullable: true), DateImplement = table.Column<DateTime>(type: "timestamp without time zone", nullable: true),
SushiId = table.Column<int>(type: "integer", nullable: false), SushiId = table.Column<int>(type: "integer", nullable: false),
ClientId = table.Column<int>(type: "integer", nullable: false) ClientId = table.Column<int>(type: "integer", nullable: false),
ImplementerId = table.Column<int>(type: "integer", nullable: true)
}, },
constraints: table => constraints: table =>
{ {
@ -78,6 +95,11 @@ namespace SushiBarDatabaseImplement.Migrations
principalTable: "Clients", principalTable: "Clients",
principalColumn: "Id", principalColumn: "Id",
onDelete: ReferentialAction.Cascade); onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Orders_Implementers_ImplementerId",
column: x => x.ImplementerId,
principalTable: "Implementers",
principalColumn: "Id");
table.ForeignKey( table.ForeignKey(
name: "FK_Orders_Sushis_SushiId", name: "FK_Orders_Sushis_SushiId",
column: x => x.SushiId, column: x => x.SushiId,
@ -118,6 +140,11 @@ namespace SushiBarDatabaseImplement.Migrations
table: "Orders", table: "Orders",
column: "ClientId"); column: "ClientId");
migrationBuilder.CreateIndex(
name: "IX_Orders_ImplementerId",
table: "Orders",
column: "ImplementerId");
migrationBuilder.CreateIndex( migrationBuilder.CreateIndex(
name: "IX_Orders_SushiId", name: "IX_Orders_SushiId",
table: "Orders", table: "Orders",
@ -146,6 +173,9 @@ namespace SushiBarDatabaseImplement.Migrations
migrationBuilder.DropTable( migrationBuilder.DropTable(
name: "Clients"); name: "Clients");
migrationBuilder.DropTable(
name: "Implementers");
migrationBuilder.DropTable( migrationBuilder.DropTable(
name: "Components"); name: "Components");

View File

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

View File

@ -0,0 +1,60 @@
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using SushiBarDataModels.Models;
using SushiBarContracts.BindingModels;
using SushiBarContracts.ViewModels;
namespace SushiBarDatabaseImplement.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

@ -24,6 +24,10 @@ namespace SushiBarDatabaseImplement.Models
public int ClientId { get; private set; } public int ClientId { get; private set; }
public virtual Client Client { get; private set; } public virtual Client Client { get; private set; }
public int? ImplementerId { get; private set; }
public virtual Implementer? Implementer { get; set; }
public static Order Create(SushiBarDatabase context, OrderBindingModel model) public static Order Create(SushiBarDatabase context, OrderBindingModel model)
{ {
if (model == null) if (model == null)
@ -41,7 +45,8 @@ namespace SushiBarDatabaseImplement.Models
SushiId = model.SushiId, SushiId = model.SushiId,
Sushi = context.Sushis.First(x => x.Id == model.SushiId), Sushi = context.Sushis.First(x => x.Id == model.SushiId),
ClientId = model.ClientId, ClientId = model.ClientId,
Client = context.Clients.FirstOrDefault(x => x.Id == model.ClientId) Client = context.Clients.First(x => x.Id == model.ClientId),
Implementer = model.ImplementerId == null ? null : context.Implementers.First(i => i.Id == model.ImplementerId)
}; };
} }
public void Update(OrderBindingModel model) public void Update(OrderBindingModel model)
@ -52,6 +57,8 @@ namespace SushiBarDatabaseImplement.Models
} }
Status = model.Status; Status = model.Status;
DateImplement = model.DateImplement; DateImplement = model.DateImplement;
ClientId = model.ClientId;
ImplementerId = model.ImplementerId;
} }
public OrderViewModel GetViewModel => new() public OrderViewModel GetViewModel => new()
{ {
@ -64,7 +71,9 @@ namespace SushiBarDatabaseImplement.Models
DateImplement = DateImplement, DateImplement = DateImplement,
SushiName = Sushi.SushiName, SushiName = Sushi.SushiName,
ClientId = Client.Id, ClientId = Client.Id,
ClientFIO = Client.ClientFIO ClientFIO = Client.ClientFIO,
ImplementerId = ImplementerId,
ImplementerName = Implementer == null ? string.Empty : Implementer.ImplementerFIO
}; };
} }
} }

View File

@ -9,7 +9,7 @@ namespace SushiBarDatabaseImplement
{ {
if (optionsBuilder.IsConfigured == false) if (optionsBuilder.IsConfigured == false)
{ {
optionsBuilder.UseNpgsql(@"Host=localhost;Database=SushiBar_db5;Username=postgres;Password=postgres"); optionsBuilder.UseNpgsql(@"Host=localhost;Database=SushiBar_db6;Username=postgres;Password=postgres");
} }
base.OnConfiguring(optionsBuilder); base.OnConfiguring(optionsBuilder);
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true); AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
@ -20,5 +20,6 @@ namespace SushiBarDatabaseImplement
public virtual DbSet<SushiComponent> SushiComponents { set; get; } public virtual DbSet<SushiComponent> SushiComponents { set; get; }
public virtual DbSet<Order> Orders { set; get; } public virtual DbSet<Order> Orders { set; get; }
public virtual DbSet<Client> Clients { set; get; } public virtual DbSet<Client> Clients { set; get; }
public virtual DbSet<Implementer> Implementers { set; get; }
} }
} }

View File

@ -10,11 +10,13 @@ namespace SushiBarFileImplement
private readonly string ComponentFileName = "Component.xml"; private readonly string ComponentFileName = "Component.xml";
private readonly string OrderFileName = "Order.xml"; private readonly string OrderFileName = "Order.xml";
private readonly string SushiFileName = "Sushi.xml"; private readonly string SushiFileName = "Sushi.xml";
private readonly string ImplementerFileName = "Implementer.xml";
private readonly string ClientFileName = "Client.xml"; private readonly string ClientFileName = "Client.xml";
public List<Component> Components { get; private set; } public List<Component> Components { get; private set; }
public List<Order> Orders { get; private set; } public List<Order> Orders { get; private set; }
public List<Sushi> Sushis { get; private set; } public List<Sushi> Sushis { get; private set; }
public List<Client> Clients { 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) if (instance == null)
@ -27,12 +29,14 @@ namespace SushiBarFileImplement
public void SaveSushis() => SaveData(Sushis, SushiFileName, "Sushis", x => x.GetXElement); public void SaveSushis() => SaveData(Sushis, SushiFileName, "Sushis", x => x.GetXElement);
public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement); public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement);
public void SaveClients() => SaveData(Clients, ClientFileName, "Client", x => x.GetXElement); public void SaveClients() => SaveData(Clients, ClientFileName, "Client", x => x.GetXElement);
public void SaveImplementers() => SaveData(Implementers, ImplementerFileName, "Implementers", x => x.GetXElement);
private DataFileSingleton() private DataFileSingleton()
{ {
Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!; Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!;
Sushis = LoadData(SushiFileName, "Sushi", x => Sushi.Create(x)!)!; Sushis = LoadData(SushiFileName, "Sushi", x => Sushi.Create(x)!)!;
Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!; Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!;
Clients = LoadData(ClientFileName, "Client", x => Client.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) private static List<T>? LoadData<T>(string filename, string xmlNodeName, Func<XElement, T> selectFunction)
{ {

View File

@ -0,0 +1,79 @@
using IceCreamShopContracts.StoragesContracts;
using SushiBarContracts.BindingModels;
using SushiBarContracts.SearchModels;
using SushiBarContracts.ViewModels;
using SushiBarFileImplement.Models;
namespace SushiBarFileImplement.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

@ -16,7 +16,7 @@ namespace SushiBarFileImplement.Implements
public List<OrderViewModel> GetFullList() public List<OrderViewModel> GetFullList()
{ {
return source.Orders return source.Orders
.Select(x => AccessClientStorage(AccessSushiStorage(x.GetViewModel))!) .Select(x => AccessStorage(x.GetViewModel))!
.ToList(); .ToList();
} }
public List<OrderViewModel> GetFilteredList(OrderSearchModel model) public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
@ -27,7 +27,7 @@ namespace SushiBarFileImplement.Implements
(!model.DateFrom.HasValue || o.DateCreate >= model.DateFrom) && (!model.DateFrom.HasValue || o.DateCreate >= model.DateFrom) &&
(!model.DateTo.HasValue || o.DateCreate <= model.DateTo) && (!model.DateTo.HasValue || o.DateCreate <= model.DateTo) &&
(!model.ClientId.HasValue || o.ClientId == model.ClientId)) (!model.ClientId.HasValue || o.ClientId == model.ClientId))
.Select(o => AccessClientStorage(AccessSushiStorage(o.GetViewModel))!) .Select(o => AccessStorage(o.GetViewModel)!)
.ToList(); .ToList();
} }
public OrderViewModel? GetElement(OrderSearchModel model) public OrderViewModel? GetElement(OrderSearchModel model)
@ -36,9 +36,8 @@ namespace SushiBarFileImplement.Implements
{ {
return null; return null;
} }
return AccessClientStorage(AccessSushiStorage( return AccessStorage(source.Orders
source.Orders .FirstOrDefault(x => x.Id == model.Id)?.GetViewModel!);
.FirstOrDefault(x => (x.Id == model.Id))?.GetViewModel));
} }
public OrderViewModel? Insert(OrderBindingModel model) public OrderViewModel? Insert(OrderBindingModel model)
{ {
@ -50,7 +49,7 @@ namespace SushiBarFileImplement.Implements
} }
source.Orders.Add(newOrder); source.Orders.Add(newOrder);
source.SaveOrders(); source.SaveOrders();
return AccessClientStorage(AccessSushiStorage(newOrder.GetViewModel)); return AccessStorage(newOrder.GetViewModel);
} }
public OrderViewModel? Update(OrderBindingModel model) public OrderViewModel? Update(OrderBindingModel model)
{ {
@ -61,7 +60,7 @@ namespace SushiBarFileImplement.Implements
} }
element.Update(model); element.Update(model);
source.SaveOrders(); source.SaveOrders();
return AccessClientStorage(AccessSushiStorage(element.GetViewModel)); return AccessStorage(element.GetViewModel);
} }
public OrderViewModel? Delete(OrderBindingModel model) public OrderViewModel? Delete(OrderBindingModel model)
{ {
@ -70,32 +69,23 @@ namespace SushiBarFileImplement.Implements
{ {
source.Orders.Remove(element); source.Orders.Remove(element);
source.SaveOrders(); source.SaveOrders();
return AccessClientStorage(AccessSushiStorage(element.GetViewModel)); return AccessStorage(element.GetViewModel);
} }
return null; return null;
} }
public OrderViewModel? AccessSushiStorage(OrderViewModel? model) public OrderViewModel AccessStorage(OrderViewModel model)
{
if (model == null)
return null;
foreach (var iceCream in source.Sushis)
{
if (iceCream.Id == model.SushiId)
{
model.SushiName = iceCream.SushiName;
break;
}
}
return model;
}
public OrderViewModel? AccessClientStorage(OrderViewModel? model)
{ {
if (model == null) if (model == null)
return null; return null;
var sushi = source.Sushis.FirstOrDefault(x => x.Id == model.Id);
var client = source.Clients.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 (sushi != null)
model.SushiName = sushi.SushiName;
if (client != null) if (client != null)
model.ClientFIO = client.ClientFIO; model.ClientFIO = client.ClientFIO;
if (implementer != null)
model.ImplementerName = implementer.ImplementerFIO;
return model; return model;
} }
} }

View File

@ -0,0 +1,73 @@
using SushiBarContracts.BindingModels;
using SushiBarContracts.ViewModels;
using SushiBarDataModels.Models;
using System.Xml.Linq;
namespace SushiBarFileImplement.Models
{
internal 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

@ -11,6 +11,7 @@ namespace SushiBarFileImplement.Models
public int Id { get; private set; } public int Id { get; private set; }
public int SushiId { get; private set; } public int SushiId { get; private set; }
public int ClientId { get; private set; } public int ClientId { get; private set; }
public int? ImplementerId { get; private set; }
public int Count { get; private set; } public int Count { get; private set; }
public double Sum { get; private set; } public double Sum { get; private set; }
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен; public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен;
@ -27,6 +28,7 @@ namespace SushiBarFileImplement.Models
Id = model.Id, Id = model.Id,
SushiId = model.SushiId, SushiId = model.SushiId,
ClientId = model.ClientId, ClientId = model.ClientId,
ImplementerId = model.ImplementerId,
Count = model.Count, Count = model.Count,
Sum = model.Sum, Sum = model.Sum,
Status = model.Status, Status = model.Status,
@ -45,6 +47,7 @@ namespace SushiBarFileImplement.Models
Id = Convert.ToInt32(element.Attribute("Id")!.Value), Id = Convert.ToInt32(element.Attribute("Id")!.Value),
SushiId = Convert.ToInt32(element.Element("SushiId")!.Value), SushiId = Convert.ToInt32(element.Element("SushiId")!.Value),
ClientId = Convert.ToInt32(element.Element("ClientId")!.Value), ClientId = Convert.ToInt32(element.Element("ClientId")!.Value),
ImplementerId = Convert.ToInt32(element.Element("ImplementerId")!.Value),
Count = Convert.ToInt32(element.Element("Count")!.Value), Count = Convert.ToInt32(element.Element("Count")!.Value),
Sum = Convert.ToDouble(element.Element("Sum")!.Value), Sum = Convert.ToDouble(element.Element("Sum")!.Value),
Status = (OrderStatus)Enum.Parse(typeof(OrderStatus), element.Element("Status")!.Value.ToString()), Status = (OrderStatus)Enum.Parse(typeof(OrderStatus), element.Element("Status")!.Value.ToString()),
@ -67,6 +70,7 @@ namespace SushiBarFileImplement.Models
Id = Id, Id = Id,
SushiId = SushiId, SushiId = SushiId,
ClientId = ClientId, ClientId = ClientId,
ImplementerId = ImplementerId,
Count = Count, Count = Count,
Sum = Sum, Sum = Sum,
Status = Status, Status = Status,
@ -77,6 +81,7 @@ namespace SushiBarFileImplement.Models
new XAttribute("Id", Id), new XAttribute("Id", Id),
new XElement("SushiId", SushiId), new XElement("SushiId", SushiId),
new XElement("ClientId", ClientId), new XElement("ClientId", ClientId),
new XElement("ImplementerId", ClientId),
new XElement("Count", Count), new XElement("Count", Count),
new XElement("Sum", Sum.ToString()), new XElement("Sum", Sum.ToString()),
new XElement("Status", Status.ToString()), new XElement("Status", Status.ToString()),

View File

@ -4,17 +4,19 @@ namespace SushiBarListImplement
{ {
public class DataListSingleton public class DataListSingleton
{ {
private static DataListSingleton _instance; private static DataListSingleton? _instance;
public List<Component> Components { get; set; } public List<Component> Components { get; set; }
public List<Order> Orders { get; set; } public List<Order> Orders { get; set; }
public List<Sushi> Sushis { get; set; } public List<Sushi> Sushis { get; set; }
public List<Client> Clients { get; set; } public List<Client> Clients { get; set; }
public List<Implementer> Implementers { get; set; }
private DataListSingleton() private DataListSingleton()
{ {
Components = new List<Component>(); Components = new List<Component>();
Orders = new List<Order>(); Orders = new List<Order>();
Sushis = new List<Sushi>(); Sushis = new List<Sushi>();
Clients = new List<Client>(); Clients = new List<Client>();
Implementers = new List<Implementer>();
} }
public static DataListSingleton GetInstance() public static DataListSingleton GetInstance()

View File

@ -0,0 +1,97 @@
using IceCreamShopContracts.StoragesContracts;
using SushiBarContracts.BindingModels;
using SushiBarContracts.SearchModels;
using SushiBarContracts.ViewModels;
using SushiBarListImplement.Models;
namespace SushiBarListImplement.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

@ -18,7 +18,7 @@ namespace SushiBarListImplement.Implements
var result = new List<OrderViewModel>(); var result = new List<OrderViewModel>();
foreach (var order in _source.Orders) foreach (var order in _source.Orders)
{ {
result.Add(AccessClientStorage(AccessSushiStorage(order.GetViewModel))); result.Add(AccessStorage(order.GetViewModel));
} }
return result; return result;
} }
@ -31,7 +31,7 @@ namespace SushiBarListImplement.Implements
(model.DateFrom.HasValue && model.DateTo.HasValue && (model.DateFrom.HasValue && model.DateTo.HasValue &&
model.DateFrom < order.DateCreate && order.DateCreate < model.DateTo)) model.DateFrom < order.DateCreate && order.DateCreate < model.DateTo))
{ {
result.Add(AccessClientStorage(AccessSushiStorage(order.GetViewModel))); result.Add(AccessStorage(order.GetViewModel));
} }
} }
return result; return result;
@ -46,7 +46,7 @@ namespace SushiBarListImplement.Implements
{ {
if (model.Id.HasValue && order.Id == model.Id) if (model.Id.HasValue && order.Id == model.Id)
{ {
return AccessClientStorage(AccessSushiStorage(order.GetViewModel)); return AccessStorage(order.GetViewModel);
} }
} }
return null; return null;
@ -67,7 +67,7 @@ namespace SushiBarListImplement.Implements
return null; return null;
} }
_source.Orders.Add(newOrder); _source.Orders.Add(newOrder);
return AccessClientStorage(AccessSushiStorage(newOrder.GetViewModel)); return AccessStorage(newOrder.GetViewModel);
} }
public OrderViewModel? Update(OrderBindingModel model) public OrderViewModel? Update(OrderBindingModel model)
{ {
@ -76,7 +76,7 @@ namespace SushiBarListImplement.Implements
if (order.Id == model.Id) if (order.Id == model.Id)
{ {
order.Update(model); order.Update(model);
return AccessClientStorage(AccessSushiStorage(order.GetViewModel)); return AccessStorage(order.GetViewModel);
} }
} }
return null; return null;
@ -89,7 +89,7 @@ namespace SushiBarListImplement.Implements
{ {
var element = _source.Orders[i]; var element = _source.Orders[i];
_source.Orders.RemoveAt(i); _source.Orders.RemoveAt(i);
return AccessClientStorage(AccessSushiStorage(element.GetViewModel)); return AccessStorage(element.GetViewModel);
} }
} }
return null; return null;
@ -107,11 +107,17 @@ namespace SushiBarListImplement.Implements
return model; return model;
} }
public OrderViewModel AccessClientStorage(OrderViewModel model) public OrderViewModel AccessStorage(OrderViewModel model)
{ {
var client = _source.Clients.FirstOrDefault(x => x.Id == model.ClientId); var iceCream = _source.Sushis.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.SushiName = iceCream.SushiName;
if (client != null) if (client != null)
model.ClientFIO = client.ClientFIO; model.ClientFIO = client.ClientFIO;
if (implementer != null)
model.ImplementerName = implementer.ImplementerFIO;
return model; return model;
} }
} }

View File

@ -0,0 +1,49 @@
using SushiBarContracts.BindingModels;
using SushiBarContracts.ViewModels;
using SushiBarDataModels.Models;
namespace SushiBarListImplement.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

@ -2,11 +2,6 @@
using SushiBarContracts.ViewModels; using SushiBarContracts.ViewModels;
using SushiBarDataModels.Enums; using SushiBarDataModels.Enums;
using SushiBarDataModels.Models; using SushiBarDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SushiBarListImplement.Models namespace SushiBarListImplement.Models
{ {
@ -15,6 +10,7 @@ namespace SushiBarListImplement.Models
public int Id { get; private set; } public int Id { get; private set; }
public int SushiId { get; private set; } public int SushiId { get; private set; }
public int ClientId { get; private set; } public int ClientId { get; private set; }
public int? ImplementerId { get; private set; }
public int Count { get; private set; } public int Count { get; private set; }
public double Sum { get; private set; } public double Sum { get; private set; }
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен; public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен;
@ -34,7 +30,8 @@ namespace SushiBarListImplement.Models
Sum = model.Sum, Sum = model.Sum,
Status = model.Status, Status = model.Status,
DateCreate = model.DateCreate, DateCreate = model.DateCreate,
DateImplement = model.DateImplement DateImplement = model.DateImplement,
ImplementerId = model.ImplementerId
}; };
} }
public void Update(OrderBindingModel? model) public void Update(OrderBindingModel? model)
@ -45,6 +42,7 @@ namespace SushiBarListImplement.Models
} }
SushiId = model.SushiId; SushiId = model.SushiId;
ClientId = model.ClientId; ClientId = model.ClientId;
ImplementerId = model.ImplementerId;
Count = model.Count; Count = model.Count;
Sum = model.Sum; Sum = model.Sum;
Status = model.Status; Status = model.Status;
@ -55,6 +53,7 @@ namespace SushiBarListImplement.Models
Id = Id, Id = Id,
SushiId = SushiId, SushiId = SushiId,
ClientId = ClientId, ClientId = ClientId,
ImplementerId = ImplementerId,
Count = Count, Count = Count,
Sum = Sum, Sum = Sum,
Status = Status, Status = Status,

View File

@ -0,0 +1,103 @@
using Microsoft.AspNetCore.Mvc;
using SushiBarContracts.BindingModels;
using SushiBarContracts.BusinessLogicsContracts;
using SushiBarContracts.SearchModels;
using SushiBarContracts.ViewModels;
using SushiBarDataModels.Enums;
namespace SushiBarRestApi.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;
}
}
}
}