ISbd-21 Gordeev I.V. LabWork_06 Base #10

Closed
Igor_Gordeev wants to merge 2 commits from Lab_06 into Lab_05
77 changed files with 2713 additions and 1027 deletions

View File

@ -1,4 +1,5 @@
namespace SushiBarView

namespace SushiBarView
{
partial class FormClients
{
@ -29,55 +30,63 @@
private void InitializeComponent()
{
dataGridView = new DataGridView();
buttonRefresh = new Button();
buttonDelete = new Button();
buttonDel = new Button();
buttonRef = new Button();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// dataGridView
//
dataGridView.BackgroundColor = Color.AntiqueWhite;
dataGridView.AllowUserToAddRows = false;
dataGridView.AllowUserToDeleteRows = false;
dataGridView.BackgroundColor = SystemColors.ControlLightLight;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Dock = DockStyle.Left;
dataGridView.Location = new Point(0, 0);
dataGridView.Margin = new Padding(4, 3, 4, 3);
dataGridView.Name = "dataGridView";
dataGridView.ReadOnly = true;
dataGridView.RowHeadersVisible = false;
dataGridView.RowHeadersWidth = 51;
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.Size = new Size(615, 450);
dataGridView.Size = new Size(609, 360);
dataGridView.TabIndex = 0;
//
// buttonRefresh
// buttonDel
//
buttonRefresh.Location = new Point(669, 53);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(144, 54);
buttonRefresh.TabIndex = 1;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += buttonRefresh_Click;
buttonDel.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonDel.Location = new Point(639, 14);
buttonDel.Margin = new Padding(4, 3, 4, 3);
buttonDel.Name = "buttonDel";
buttonDel.Size = new Size(88, 27);
buttonDel.TabIndex = 3;
buttonDel.Text = "Удалить";
buttonDel.UseVisualStyleBackColor = true;
buttonDel.Click += ButtonDel_Click;
//
// buttonDelete
// buttonRef
//
buttonDelete.Location = new Point(669, 160);
buttonDelete.Name = "buttonDelete";
buttonDelete.Size = new Size(144, 54);
buttonDelete.TabIndex = 2;
buttonDelete.Text = "Удалить";
buttonDelete.UseVisualStyleBackColor = true;
buttonDelete.Click += buttonDelete_Click;
buttonRef.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonRef.Location = new Point(639, 61);
buttonRef.Margin = new Padding(4, 3, 4, 3);
buttonRef.Name = "buttonRef";
buttonRef.Size = new Size(88, 27);
buttonRef.TabIndex = 4;
buttonRef.Text = "Обновить";
buttonRef.UseVisualStyleBackColor = true;
buttonRef.Click += ButtonRef_Click;
//
// FormClients
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
BackColor = Color.BurlyWood;
ClientSize = new Size(862, 450);
Controls.Add(buttonDelete);
Controls.Add(buttonRefresh);
ClientSize = new Size(761, 360);
Controls.Add(buttonRef);
Controls.Add(buttonDel);
Controls.Add(dataGridView);
Margin = new Padding(4, 3, 4, 3);
Name = "FormClients";
Text = "FormClients";
StartPosition = FormStartPosition.CenterScreen;
Text = "Клиенты";
Load += FormClients_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
@ -85,8 +94,8 @@
#endregion
private DataGridView dataGridView;
private Button buttonRefresh;
private Button buttonDelete;
private System.Windows.Forms.DataGridView dataGridView;
private System.Windows.Forms.Button buttonDel;
private System.Windows.Forms.Button buttonRef;
}
}

View File

@ -1,28 +1,21 @@
using Microsoft.Extensions.Logging;
using SushiBarContracts.BindingModel;
using SushiBarContracts.BusinessLogicsContracts;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SushiBarView
{
public partial class FormClients : Form
{
private readonly ILogger _logger;
private readonly IClientLogic _clientLogic;
private readonly IClientLogic _logic;
public FormClients(ILogger<FormClients> logger, IClientLogic logic)
{
_logger = logger;
_clientLogic = logic;
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormClients_Load(object sender, EventArgs e)
@ -34,53 +27,48 @@ namespace SushiBarView
{
try
{
var list = _clientLogic.ReadList(null);
var list = _logic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
_logger.LogInformation("Клиенты успешно загружены");
}
_logger.LogInformation("Загрузка клиентов");
}
catch (Exception ex)
{
_logger.LogError(ex.Message, "Ошибка загрузки клиентов");
MessageBox.Show(ex.Message, "Ошибка загрузки клиентов");
_logger.LogError(ex, "Ошибка загрузки клиентов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonDelete_Click(object sender, EventArgs e)
private void ButtonDel_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Вы серьезно хотите удалить клиента? :_) та за что...", "Вопрос",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
try
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation($"Удален клиент под номером {id}");
if (!_clientLogic.Delete(new ClientBindingModel
{
Id = id
}))
if (!_logic.Delete(new ClientBindingModel { Id = id }))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
_logger.LogInformation("Удаление клиента");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Не удалось удалить клиента");
_logger.LogError(ex.Message, "Не удалось удалить клиента");
_logger.LogError(ex, "Ошибка удаления клиента");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
LoadData();
}
}
}
private void buttonRefresh_Click(object sender, EventArgs e)
private void ButtonRef_Click(object sender, EventArgs e)
{
LoadData();
}

View File

@ -0,0 +1,167 @@
namespace SushiBarView
{
partial class FormImplementer
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.textBoxFIO = new System.Windows.Forms.TextBox();
this.labelFIO = new System.Windows.Forms.Label();
this.textBoxPassword = new System.Windows.Forms.TextBox();
this.labelPassword = new System.Windows.Forms.Label();
this.labelWorkExperience = new System.Windows.Forms.Label();
this.numericUpDownWorkExperience = new System.Windows.Forms.NumericUpDown();
this.numericUpDownQualification = new System.Windows.Forms.NumericUpDown();
this.labelQualification = new System.Windows.Forms.Label();
this.buttonCancel = new System.Windows.Forms.Button();
this.buttonSave = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWorkExperience)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownQualification)).BeginInit();
this.SuspendLayout();
//
// textBoxFIO
//
this.textBoxFIO.Location = new System.Drawing.Point(157, 12);
this.textBoxFIO.Name = "textBoxFIO";
this.textBoxFIO.Size = new System.Drawing.Size(382, 27);
this.textBoxFIO.TabIndex = 3;
//
// labelFIO
//
this.labelFIO.AutoSize = true;
this.labelFIO.Location = new System.Drawing.Point(12, 15);
this.labelFIO.Name = "labelFIO";
this.labelFIO.Size = new System.Drawing.Size(139, 20);
this.labelFIO.TabIndex = 2;
this.labelFIO.Text = "ФИО исполнителя:";
//
// textBoxPassword
//
this.textBoxPassword.Location = new System.Drawing.Point(157, 50);
this.textBoxPassword.Name = "textBoxPassword";
this.textBoxPassword.Size = new System.Drawing.Size(205, 27);
this.textBoxPassword.TabIndex = 5;
//
// labelPassword
//
this.labelPassword.AutoSize = true;
this.labelPassword.Location = new System.Drawing.Point(12, 53);
this.labelPassword.Name = "labelPassword";
this.labelPassword.Size = new System.Drawing.Size(65, 20);
this.labelPassword.TabIndex = 4;
this.labelPassword.Text = "Пароль:";
//
// labelWorkExperience
//
this.labelWorkExperience.AutoSize = true;
this.labelWorkExperience.Location = new System.Drawing.Point(12, 99);
this.labelWorkExperience.Name = "labelWorkExperience";
this.labelWorkExperience.Size = new System.Drawing.Size(105, 20);
this.labelWorkExperience.TabIndex = 6;
this.labelWorkExperience.Text = "Опыт работы:";
//
// numericUpDownWorkExperience
//
this.numericUpDownWorkExperience.Location = new System.Drawing.Point(157, 97);
this.numericUpDownWorkExperience.Name = "numericUpDownWorkExperience";
this.numericUpDownWorkExperience.Size = new System.Drawing.Size(124, 27);
this.numericUpDownWorkExperience.TabIndex = 8;
//
// numericUpDownQualification
//
this.numericUpDownQualification.Location = new System.Drawing.Point(157, 142);
this.numericUpDownQualification.Name = "numericUpDownQualification";
this.numericUpDownQualification.Size = new System.Drawing.Size(124, 27);
this.numericUpDownQualification.TabIndex = 10;
//
// labelQualification
//
this.labelQualification.AutoSize = true;
this.labelQualification.Location = new System.Drawing.Point(12, 144);
this.labelQualification.Name = "labelQualification";
this.labelQualification.Size = new System.Drawing.Size(114, 20);
this.labelQualification.TabIndex = 9;
this.labelQualification.Text = "Квалификация:";
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(422, 203);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(136, 40);
this.buttonCancel.TabIndex = 12;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(265, 203);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(130, 40);
this.buttonSave.TabIndex = 11;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.buttonSave_Click);
//
// FormImplementer
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(570, 255);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.numericUpDownQualification);
this.Controls.Add(this.labelQualification);
this.Controls.Add(this.numericUpDownWorkExperience);
this.Controls.Add(this.labelWorkExperience);
this.Controls.Add(this.textBoxPassword);
this.Controls.Add(this.labelPassword);
this.Controls.Add(this.textBoxFIO);
this.Controls.Add(this.labelFIO);
this.Name = "FormImplementer";
this.Text = "Исполнитель";
this.Load += new System.EventHandler(this.FormImplementer_Load);
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWorkExperience)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownQualification)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private TextBox textBoxFIO;
private Label labelFIO;
private TextBox textBoxPassword;
private Label labelPassword;
private Label labelWorkExperience;
private NumericUpDown numericUpDownWorkExperience;
private NumericUpDown numericUpDownQualification;
private Label labelQualification;
private Button buttonCancel;
private Button buttonSave;
}
}

View File

@ -0,0 +1,95 @@
using Microsoft.Extensions.Logging;
using SushiBarContracts.BindingModels;
using SushiBarContracts.BusinessLogicsContracts;
using SushiBarContracts.SearchModels;
using SushiBarDataModels.Models;
namespace SushiBarView
{
public partial class FormImplementer : Form
{
private readonly ILogger _logger;
private readonly IImplementerLogic _logic;
private int? _id;
public int Id { set { _id = value; } }
public FormImplementer(ILogger<FormImplementer> logger, IImplementerLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormImplementer_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
try
{
_logger.LogInformation("Получение исполнителя");
var view = _logic.ReadElement(new ImplementerSearchModel
{
Id = _id.Value
});
if (view != null)
{
textBoxFIO.Text = view.ImplementerFIO;
textBoxPassword.Text = view.Password;
numericUpDownWorkExperience.Value = view.WorkExperience;
numericUpDownQualification.Value = view.Qualification;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения исполнителя");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void buttonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxFIO.Text))
{
MessageBox.Show("Заполните ФИО", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxPassword.Text))
{
MessageBox.Show("Заполните пароль", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение исполнителя");
try
{
var model = new ImplementerBindingModel
{
Id = _id ?? 0,
ImplementerFIO = textBoxFIO.Text,
Password = textBoxPassword.Text,
WorkExperience = (int)numericUpDownWorkExperience.Value,
Qualification = (int)numericUpDownQualification.Value
};
var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model);
if (!operationResult)
{
throw new Exception("Ошибка при создании или обновлении. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения исполнителя");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonCancel_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,130 @@
namespace SushiBarView
{
partial class FormImplementers
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.ToolsPanel = new System.Windows.Forms.Panel();
this.buttonRef = new System.Windows.Forms.Button();
this.buttonDel = new System.Windows.Forms.Button();
this.buttonUpd = new System.Windows.Forms.Button();
this.buttonAdd = new System.Windows.Forms.Button();
this.dataGridView = new System.Windows.Forms.DataGridView();
this.ToolsPanel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
//
// ToolsPanel
//
this.ToolsPanel.Controls.Add(this.buttonRef);
this.ToolsPanel.Controls.Add(this.buttonDel);
this.ToolsPanel.Controls.Add(this.buttonUpd);
this.ToolsPanel.Controls.Add(this.buttonAdd);
this.ToolsPanel.Location = new System.Drawing.Point(608, 12);
this.ToolsPanel.Name = "ToolsPanel";
this.ToolsPanel.Size = new System.Drawing.Size(180, 426);
this.ToolsPanel.TabIndex = 3;
//
// buttonRef
//
this.buttonRef.Location = new System.Drawing.Point(31, 206);
this.buttonRef.Name = "buttonRef";
this.buttonRef.Size = new System.Drawing.Size(126, 36);
this.buttonRef.TabIndex = 3;
this.buttonRef.Text = "Обновить";
this.buttonRef.UseVisualStyleBackColor = true;
this.buttonRef.Click += new System.EventHandler(this.buttonRef_Click);
//
// buttonDel
//
this.buttonDel.Location = new System.Drawing.Point(31, 142);
this.buttonDel.Name = "buttonDel";
this.buttonDel.Size = new System.Drawing.Size(126, 36);
this.buttonDel.TabIndex = 2;
this.buttonDel.Text = "Удалить";
this.buttonDel.UseVisualStyleBackColor = true;
this.buttonDel.Click += new System.EventHandler(this.buttonDel_Click);
//
// buttonUpd
//
this.buttonUpd.Location = new System.Drawing.Point(31, 76);
this.buttonUpd.Name = "buttonUpd";
this.buttonUpd.Size = new System.Drawing.Size(126, 36);
this.buttonUpd.TabIndex = 1;
this.buttonUpd.Text = "Изменить";
this.buttonUpd.UseVisualStyleBackColor = true;
this.buttonUpd.Click += new System.EventHandler(this.buttonUpd_Click);
//
// buttonAdd
//
this.buttonAdd.Location = new System.Drawing.Point(31, 16);
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(126, 36);
this.buttonAdd.TabIndex = 0;
this.buttonAdd.Text = "Добавить";
this.buttonAdd.UseVisualStyleBackColor = true;
this.buttonAdd.Click += new System.EventHandler(this.buttonAdd_Click);
//
// dataGridView
//
this.dataGridView.AllowUserToAddRows = false;
this.dataGridView.AllowUserToDeleteRows = false;
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Location = new System.Drawing.Point(12, 12);
this.dataGridView.Name = "dataGridView";
this.dataGridView.ReadOnly = true;
this.dataGridView.RowHeadersWidth = 51;
this.dataGridView.RowTemplate.Height = 29;
this.dataGridView.Size = new System.Drawing.Size(590, 426);
this.dataGridView.TabIndex = 2;
//
// FormImplementers
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.ToolsPanel);
this.Controls.Add(this.dataGridView);
this.Name = "FormImplementers";
this.Text = "Исполнители";
this.Load += new System.EventHandler(this.FormImplementers_Load);
this.ToolsPanel.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.ResumeLayout(false);
}
#endregion
private Panel ToolsPanel;
private Button buttonRef;
private Button buttonDel;
private Button buttonUpd;
private Button buttonAdd;
private DataGridView dataGridView;
}
}

View File

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

View File

@ -0,0 +1,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

@ -32,11 +32,13 @@
справочникиToolStripMenuItem = new ToolStripMenuItem();
ингредиентыToolStripMenuItem = new ToolStripMenuItem();
сушиToolStripMenuItem = new ToolStripMenuItem();
клиентыToolStripMenuItem = new ToolStripMenuItem();
исполнителиToolStripMenuItem = new ToolStripMenuItem();
начатьРаботуToolStripMenuItem = new ToolStripMenuItem();
отчетыToolStripMenuItem = new ToolStripMenuItem();
списокСушиToolStripMenuItem = new ToolStripMenuItem();
сушиСИнгредиентамиToolStripMenuItem = new ToolStripMenuItem();
списокЗаказовToolStripMenuItem = new ToolStripMenuItem();
клиентыToolStripMenuItem = new ToolStripMenuItem();
buttonUpdate = new Button();
buttonSetToFinish = new Button();
buttonSetToDone = new Button();
@ -49,7 +51,7 @@
//
// menuStrip
//
menuStrip.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчетыToolStripMenuItem, клиентыToolStripMenuItem });
menuStrip.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчетыToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(1112, 24);
@ -58,7 +60,7 @@
//
// справочникиToolStripMenuItem
//
справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { ингредиентыToolStripMenuItem, сушиToolStripMenuItem });
справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { ингредиентыToolStripMenuItem, сушиToolStripMenuItem, клиентыToolStripMenuItem, исполнителиToolStripMenuItem, начатьРаботуToolStripMenuItem });
справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem";
справочникиToolStripMenuItem.Size = new Size(94, 20);
справочникиToolStripMenuItem.Text = "Справочники";
@ -66,17 +68,38 @@
// ингредиентыToolStripMenuItem
//
ингредиентыToolStripMenuItem.Name = "ингредиентыToolStripMenuItem";
ингредиентыToolStripMenuItem.Size = new Size(148, 22);
ингредиентыToolStripMenuItem.Size = new Size(180, 22);
ингредиентыToolStripMenuItem.Text = "Ингредиенты";
ингредиентыToolStripMenuItem.Click += IngredientsToolStripMenuItem_Click;
//
// сушиToolStripMenuItem
//
сушиToolStripMenuItem.Name = "сушиToolStripMenuItem";
сушиToolStripMenuItem.Size = new Size(148, 22);
сушиToolStripMenuItem.Size = new Size(180, 22);
сушиToolStripMenuItem.Text = "Суши";
сушиToolStripMenuItem.Click += SushiToolStripMenuItem_Click;
//
// клиентыToolStripMenuItem
//
клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem";
клиентыToolStripMenuItem.Size = new Size(180, 22);
клиентыToolStripMenuItem.Text = "Клиенты";
клиентыToolStripMenuItem.Click += клиентыToolStripMenuItem_Click;
//
// исполнителиToolStripMenuItem
//
исполнителиToolStripMenuItem.Name = сполнителиToolStripMenuItem";
исполнителиToolStripMenuItem.Size = new Size(180, 22);
исполнителиToolStripMenuItem.Text = "Исполнители";
исполнителиToolStripMenuItem.Click += employersToolStripMenuItem_Click;
//
// начатьРаботуToolStripMenuItem
//
начатьРаботуToolStripMenuItem.Name = ачатьРаботуToolStripMenuItem";
начатьРаботуToolStripMenuItem.Size = new Size(180, 22);
начатьРаботуToolStripMenuItem.Text = "Начать работу";
начатьРаботуToolStripMenuItem.Click += startWorkToolStripMenuItem_Click;
//
// отчетыToolStripMenuItem
//
отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокСушиToolStripMenuItem, сушиСИнгредиентамиToolStripMenuItem, списокЗаказовToolStripMenuItem });
@ -105,13 +128,6 @@
списокЗаказовToolStripMenuItem.Text = "Список заказов";
списокЗаказовToolStripMenuItem.Click += OrdersToolStripMenuItem_Click;
//
// клиентыToolStripMenuItem
//
клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem";
клиентыToolStripMenuItem.Size = new Size(67, 20);
клиентыToolStripMenuItem.Text = "Клиенты";
клиентыToolStripMenuItem.Click += клиентыToolStripMenuItem_Click;
//
// buttonUpdate
//
buttonUpdate.Anchor = AnchorStyles.Top | AnchorStyles.Right;
@ -224,5 +240,7 @@
private ToolStripMenuItem сушиСИнгредиентамиToolStripMenuItem;
private ToolStripMenuItem списокЗаказовToolStripMenuItem;
private ToolStripMenuItem клиентыToolStripMenuItem;
private ToolStripMenuItem исполнителиToolStripMenuItem;
private ToolStripMenuItem начатьРаботуToolStripMenuItem;
}
}

View File

@ -9,13 +9,16 @@ namespace SushiBarView
private readonly ILogger _logger;
private readonly IOrderLogic _orderLogic;
private readonly IReportLogic _reportLogic;
private readonly IWorkProcess _workProcess;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic)
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess)
{
InitializeComponent();
_logger = logger;
_orderLogic = orderLogic;
_reportLogic = reportLogic;
_workProcess = workProcess;
_workProcess = workProcess;
}
private void FormMain_Load(object sender, EventArgs e)
{
@ -31,6 +34,7 @@ namespace SushiBarView
{
dataGridView.DataSource = list;
dataGridView.Columns["SushiId"].Visible = false;
dataGridView.Columns["Implementerid"].Visible=false;
}
_logger.LogInformation("Загрузка заказов");
}
@ -181,5 +185,19 @@ namespace SushiBarView
form.ShowDialog();
}
}
private void employersToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormImplementers));
if (service is FormImplementers form)
{
form.ShowDialog();
}
}
private void startWorkToolStripMenuItem_Click(object sender, EventArgs e)
{
_workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic);
MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}

View File

@ -43,13 +43,15 @@ namespace SushiBarView
services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<ISushiStorage, SushiStorage>();
services.AddTransient<IClientStorage, ClientStorage>();
services.AddTransient<IImplementerStorage, ImplementerStorage>();
services.AddTransient<IIngredientLogic, IngredientLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<ISushiLogic, SushiLogic>();
services.AddTransient<IClientLogic, ClientLogic>();
services.AddTransient<IReportLogic, ReportLogic>();
services.AddTransient<IImplementerLogic, ImplementerLogic>();
services.AddTransient<IWorkProcess, WorkModeling>();
services.AddTransient<FormMain>();
services.AddTransient<FormIngredient>();
@ -60,9 +62,11 @@ namespace SushiBarView
services.AddTransient<FormListSushi>();
services.AddTransient<FormClients>();
services.AddTransient<FormReportSushiIngredients>();
services.AddTransient<FormReportOrders>();
services.AddTransient<FormReportOrders>();
services.AddTransient<FormImplementers>();
services.AddTransient<FormImplementer>();
services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
services.AddTransient<AbstractSaveToWord, SaveToWord>();
services.AddTransient<AbstractSaveToPdf, SaveToPdf>();

View File

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

View File

@ -12,7 +12,7 @@ namespace SushiBarBusinessLogic.BusinessLogics
{
private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage;
static readonly object _locker = new object();
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage)
{
_logger = logger;
@ -20,7 +20,8 @@ namespace SushiBarBusinessLogic.BusinessLogics
}
public List<OrderViewModel>? ReadList(OrderSearchModel? model)
{
_logger.LogInformation("Order. OrderID:{Id}", model?.Id);
_logger.LogInformation("ReadList. ClientId:{ClientId}.Status:{Status}.ImplementerId:{ImplementerId}.DateFrom:{DateFrom}.DateTo:{DateTo}OrderId:{Id}",
model?.ClientId, model?.Status, model?.ImplementerId, model?.DateFrom, model?.DateTo, model?.Id);
var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model);
if (list == null)
{
@ -30,24 +31,38 @@ namespace SushiBarBusinessLogic.BusinessLogics
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public bool CreateOrder(OrderBindingModel model)
{
CheckModel(model);
if (model.Status != OrderStatus.Неизвестен)
{
_logger.LogWarning("Insert operation failed. Order status incorrect.");
return false;
}
model.Status = OrderStatus.Принят;
if (_orderStorage.Insert(model) == null)
{
model.Status = OrderStatus.Неизвестен;
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool TakeOrderInWork(OrderBindingModel model)
{
lock (_locker)
{
return ChangeStatus(model, OrderStatus.Выполняется);
}
}
public bool FinishOrder(OrderBindingModel model)
{
return ChangeStatus(model, OrderStatus.Готов);
}
public bool DeliveryOrder(OrderBindingModel model)
{
return ChangeStatus(model, OrderStatus.Выдан);
}
private void CheckModel(OrderBindingModel model, bool withParams = true)
{
if (model == null)
@ -58,62 +73,79 @@ namespace SushiBarBusinessLogic.BusinessLogics
{
return;
}
if (model.SushiId < 0)
{
throw new ArgumentNullException("Некорректный идентификатор у суши", nameof(model.SushiId));
}
if (model.Count <= 0)
{
throw new ArgumentNullException("Количество суши в заказе должно быть больше 0", nameof(model.Count));
throw new ArgumentException("Колличество пиццы в заказе не может быть меньше 1", nameof(model.Count));
}
if (model.Sum <= 0)
{
throw new ArgumentNullException("Сумма заказа должна быть больше 0", nameof(model.Sum));
throw new ArgumentException("Стоимость заказа на может быть меньше 1", nameof(model.Sum));
}
_logger.LogInformation("Order. OrderID:{Id}. Sum:{ Sum}. SushiId: { SushiId}", model.Id, model.Sum, model.SushiId);
if (model.DateImplement.HasValue && model.DateImplement < model.DateCreate)
{
throw new ArithmeticException($"Дата выдачи заказа {model.DateImplement} не может быть раньше даты его создания {model.DateCreate}");
}
_logger.LogInformation("Sushi. SushiId:{SushiId}.Count:{Count}.Sum:{Sum}Id:{Id}",
model.SushiId, model.Count, model.Sum, model.Id);
}
public bool StatusUpdate(OrderBindingModel model, OrderStatus newStatus)
private bool ChangeStatus(OrderBindingModel model, OrderStatus requiredStatus)
{
var viewModel = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id });
if (viewModel == null)
CheckModel(model, false);
var element = _orderStorage.GetElement(new OrderSearchModel()
{
Id = model.Id
});
if (element == null)
{
throw new InvalidOperationException(nameof(element));
}
model.DateCreate = element.DateCreate;
model.SushiId = element.SushiId;
model.DateImplement = element.DateImplement;
model.ClientId = element.ClientId;
if (!model.ImplementerId.HasValue)
{
model.ImplementerId = element.ImplementerId;
}
model.Status = element.Status;
model.Count = element.Count;
model.Sum = element.Sum;
if (requiredStatus - model.Status == 1)
{
model.Status = requiredStatus;
if (model.Status == OrderStatus.Готов)
{
model.DateImplement = DateTime.Now;
}
if (_orderStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
_logger.LogWarning("Changing status operation faled: Current-{Status}:required-{requiredStatus}.", model.Status, requiredStatus);
throw new InvalidOperationException($"Невозможно приствоить статус {requiredStatus} заказу с текущим статусом {model.Status}");
}
public OrderViewModel? ReadElement(OrderSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (viewModel.Status + 1 != newStatus)
_logger.LogInformation("ReadElement. ClientId:{ClientId}.Status:{Status}.ImplementerId:{ImplementerId}.DateFrom:{DateFrom}.DateTo:{DateTo}OrderId:{Id}",
model.ClientId, model.Status, model.ImplementerId, model.DateFrom, model.DateTo, model.Id);
var element = _orderStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("Status update to " + newStatus.ToString() + " operation failed. Order status incorrect.");
return false;
_logger.LogWarning("ReadElement element not found");
return null;
}
model.Status = newStatus;
if (model.Status == OrderStatus.Готов) model.DateImplement = DateTime.Now;
else
{
model.DateImplement = viewModel.DateImplement;
}
CheckModel(model, false);
if (_orderStorage.Update(model) == null)
{
model.Status--;
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool TakeOrderInWork(OrderBindingModel model)
{
return StatusUpdate(model, OrderStatus.Выполняется);
}
public bool DeliveryOrder(OrderBindingModel model)
{
return StatusUpdate(model, OrderStatus.Выдан);
}
public bool FinishOrder(OrderBindingModel model)
{
return StatusUpdate(model, OrderStatus.Готов);
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
}
}

View File

@ -0,0 +1,139 @@
using Microsoft.Extensions.Logging;
using SushiBarContracts.BindingModels;
using SushiBarContracts.BusinessLogicsContracts;
using SushiBarContracts.SearchModels;
using SushiBarContracts.ViewModels;
using SushiBarDataModels.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SushiBarBusinessLogic
{
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
});
}
// кто-то мог уже перехватить заказ, игнорируем ошибку
catch (InvalidOperationException ex)
{
_logger.LogWarning(ex, "Error try get work");
}
// заканчиваем выполнение имитации в случае иной ошибки
catch (Exception ex)
{
_logger.LogError(ex, "Error while do work");
throw;
}
// отдыхаем
Thread.Sleep(implementer.Qualification * _rnd.Next(10, 100));
}
});
}
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

@ -1,20 +1,21 @@
using Newtonsoft.Json;
using SushiBarContracts.ViewModels;
using System.Net.Http.Headers;
using System.Net.Http.Headers;
using System.Text;
using SushiBarContracts.ViewModels;
using Newtonsoft.Json;
namespace SushiBarClientApp
{
public static class APIClient
public class APIClient
{
private static readonly HttpClient _client = new();
public static ClientViewModel? Client { get; set; } = null;
public static void Connect(IConfiguration configuration)
{
_client.BaseAddress = new Uri(configuration["IPAddress"]);
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
_client.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue("application/json"));
}
public static T? GetRequest<T>(string requestUrl)
{
@ -42,4 +43,5 @@ namespace SushiBarClientApp
}
}
}
}
}

View File

@ -20,7 +20,8 @@ namespace SushiBarClientApp.Controllers
{
return Redirect("~/Home/Enter");
}
return View(APIClient.GetRequest<List<OrderViewModel>>($"api/main/getorders?clientId={APIClient.Client.Id}"));
return
View(APIClient.GetRequest<List<OrderViewModel>>($"api/main/getorders?clientId={APIClient.Client.Id}"));
}
[HttpGet]
public IActionResult Privacy()
@ -44,7 +45,7 @@ namespace SushiBarClientApp.Controllers
throw new Exception("Введите логин, пароль и ФИО");
}
APIClient.PostRequest("api/client/updatedata", new
ClientBindingModel
ClientBindingModel
{
Id = APIClient.Client.Id,
ClientFIO = fio,

View File

@ -8,7 +8,7 @@ APIClient.Connect(builder.Configuration);
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
// The default HSTS value is 30 days. You may want to change this for sushiion scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();

View File

@ -1,22 +1,21 @@
{
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:22876",
"sslPort": 44352
}
},
"profiles": {
"http": {
"SushiBarClientApp": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7121;http://localhost:5109",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"dotnetRunMessages": true,
"applicationUrl": "http://localhost:5222"
},
"https": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"dotnetRunMessages": true,
"applicationUrl": "https://localhost:7084;http://localhost:5222"
}
},
"IIS Express": {
"commandName": "IISExpress",
@ -25,14 +24,5 @@
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
},
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:41478",
"sslPort": 44302
}
}
}
}

View File

@ -1,21 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="8.0.4" />
<PackageReference Include="Microsoft.CodeAnalysis.Common" Version="4.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SushiBarContracts\SushiBarContracts.csproj" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SushiBarContracts\SushiBarContracts.csproj" />
</ItemGroup>
</Project>

View File

@ -1,60 +1,50 @@
@{
ViewData["Title"] = "Create";
ViewData["Title"] = "Create";
}
<div class="text-center">
<h2 class="display-4">Создание заказа</h2>
<h2 class="display-4">Создание заказа</h2>
</div>
<form method="post">
<div class="row">
<div class="col-4">Суши:</div>
<div class="col-8">
<select id="sushi" name="sushi" class="form-control">
@foreach (var sushi in ViewBag.Sushis)
{
<option value="@sushi.Id">@sushi.SushiName</option>
}
</select>
</div>
</div>
<div class="row">
<div class="col-4">Количество:</div>
<div class="col-8">
<input type="text" name="count" id="count" />
</div>
</div>
<div class="row">
<div class="col-4">Сумма:</div>
<div class="col-8">
<input type="text" id="sum" name="sum" readonly />
</div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4">
<input type="submit" value="Создать" class="btn btn-primary" />
</div>
</div>
<div class="row">
<div class="col-4">Изделие:</div>
<div class="col-8">
<select id="sushi" name="sushi" class="form-control" asp-items="@(new SelectList(@ViewBag.Sushis,"Id", "SushiName"))"></select>
</div>
</div>
<div class="row">
<div class="col-4">Количество:</div>
<div class="col-8"><input type="text" name="count" id="count" /></div>
</div>
<div class="row">
<div class="col-4">Сумма:</div>
<div class="col-8"><input type="text" id="sum" name="sum" readonly /></div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4"><input type="submit" value="Создать" class="btn btn-primary" /></div>
</div>
</form>
<script>
$('#sushi').on('change', function () {
check();
});
$('#count').on('change', function () {
check();
});
function check() {
var count = $('#count').val();
var sushi = $('#sushi').val();
if (count && sushi) {
$.ajax({
method: "POST",
url: "/Home/Calc",
data: { count: count, sushi: sushi },
success: function (result) {
var roundedResult = parseFloat(result).toFixed(2);
$("#sum").val(roundedResult);
}
});
};
}
$('#sushi').on('change', function () {
check();
});
$('#count').on('change', function () {
check();
});
function check() {
var count = $('#count').val();
var sushi = $('#sushi').val();
if (count && sushi) {
$.ajax({
method: "POST",
url: "/Home/Calc",
data: { count: count, sushi: sushi },
success: function (result) {
$("#sum").val(result);
}
});
};
}
</script>

View File

@ -1,20 +1,21 @@
@{
ViewData["Title"] = "Enter";
ViewData["Title"] = "Enter";
}
<div class="text-center">
<h2 class="display-4">Вход в приложение</h2>
<h2 class="display-4">Вход в приложение</h2>
</div>
<form method="post">
<div class="row">
<div class="col-4">Логин:</div>
<div class="col-8"><input type="text" name="login" /></div>
</div>
<div class="row">
<div class="col-4">Пароль:</div>
<div class="col-8"><input type="password" name="password" /></div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4"><input type="submit" value="Вход" class="btn btnprimary" /></div>
</div>
<div class="row">
<div class="col-4">Логин:</div>
<div class="col-8"><input type="text" name="login" /></div>
</div>
<div class="row">
<div class="col-4">Пароль:</div>
<div class="col-8"><input type="password" name="password" /></div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4"><input type="submit" value="Вход" class="btn btn-primary" /></div>
</div>
</form>

View File

@ -1,75 +1,75 @@
@using SushiBarContracts.ViewModels
@model List<OrderViewModel>
@{
ViewData["Title"] = "Home Page";
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Заказы</h1>
<h1 class="display-4">Заказы</h1>
</div>
<div class="text-center">
@{
if (Model == null)
{
<h3 class="display-4">Авторизируйтесь</h3>
return;
}
<p>
<a asp-action="Create">Создать заказ</a>
</p>
<table class="table">
<thead>
<tr>
<th>
Номер
</th>
<th>
Суши
</th>
<th>
Дата создания
</th>
<th>
Количество
</th>
<th>
Сумма
</th>
<th>
Статус
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem =>
item.Id)
</td>
<td>
@Html.DisplayFor(modelItem =>
item.SushiName)
</td>
<td>
@Html.DisplayFor(modelItem =>
item.DateCreate)
</td>
<td>
@Html.DisplayFor(modelItem =>
item.Count)
</td>
<td>
@Html.DisplayFor(modelItem =>
item.Sum)
</td>
<td>
@Html.DisplayFor(modelItem =>
item.Status)
</td>
</tr>
}
</tbody>
</table>
}
@{
if (Model == null)
{
<h3 class="display-4">Авторизируйтесь</h3>
return;
}
<p>
<a asp-action="Create">Создать заказ</a>
</p>
<table class="table">
<thead>
<tr>
<th>
Номер
</th>
<th>
Суши
</th>
<th>
Дата создания
</th>
<th>
Количество
</th>
<th>
Сумма
</th>
<th>
Статус
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Id)
</td>
<td>
@Html.DisplayFor(modelItem => item.SushiName)
</td>
<td>
@Html.DisplayFor(modelItem => item.DateCreate)
</td>
<td>
@Html.DisplayFor(modelItem => item.Count)
</td>
<td>
@Html.DisplayFor(modelItem => item.Sum)
</td>
<td>
@Html.DisplayFor(modelItem => item.Status)
</td>
</tr>
}
</tbody>
</table>
}
</div>

View File

@ -1,37 +1,27 @@
@using SushiBarContracts.ViewModels
@model ClientViewModel
@{
ViewData["Title"] = "Privacy Policy";
ViewData["Title"] = "Privacy Policy";
}
<div class="text-center">
<h2 class="display-4">Личные данные</h2>
<h2 class="display-4">Личные данные</h2>
</div>
<form method="post">
<div class="row">
<div class="col-4">Логин:</div>
<div class="col-8">
<input type="text" name="login"
value="@Model.Email" />
</div>
</div>
<div class="row">
<div class="col-4">Пароль:</div>
<div class="col-8">
<input type="password" name="password"
value="@Model.Password" />
</div>
</div>
<div class="row">
<div class="col-4">ФИО:</div>
<div class="col-8">
<input type="text" name="fio"
value="@Model.ClientFIO" />
</div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4">
<input type="submit" value="Сохранить" class="btn btn-primary" />
</div>
</div>
<div class="row">
<div class="col-4">Логин:</div>
<div class="col-8"><input type="text" name="login" value="@Model.Email" /></div>
</div>
<div class="row">
<div class="col-4">Пароль:</div>
<div class="col-8"><input type="password" name="password" value="@Model.Password" /></div>
</div>
<div class="row">
<div class="col-4">ФИО:</div>
<div class="col-8"><input type="text" name="fio" value="@Model.ClientFIO" /></div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4"><input type="submit" value="Сохранить" class="btn btn-primary" /></div>
</div>
</form>

View File

@ -1,27 +1,25 @@
@{
ViewData["Title"] = "Register";
ViewData["Title"] = "Register";
}
<div class="text-center">
<h2 class="display-4">Регистрация</h2>
<h2 class="display-4">Регистрация</h2>
</div>
<form method="post">
<div class="row">
<div class="col-4">Логин:</div>
<div class="col-8"><input type="text" name="login" /></div>
</div>
<div class="row">
<div class="col-4">Пароль:</div>
<div class="col-8"><input type="password" name="password" /></div>
</div>
<div class="row">
<div class="col-4">ФИО:</div>
<div class="col-8"><input type="text" name="fio" /></div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4">
<input type="submit" value="Регистрация"
class="btn btn-primary" />
</div>
</div>
<div class="row">
<div class="col-4">Логин:</div>
<div class="col-8"><input type="text" name="login" /></div>
</div>
<div class="row">
<div class="col-4">Пароль:</div>
<div class="col-8"><input type="password" name="password" /></div>
</div>
<div class="row">
<div class="col-4">ФИО:</div>
<div class="col-8"><input type="text" name="fio" /></div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4"><input type="submit" value="Регистрация" class="btn btn-primary" /></div>
</div>
</form>

View File

@ -22,4 +22,4 @@
It can result in displaying sensitive information from exceptions to end users.
For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
and restarting the app.
</p>
</p>

View File

@ -5,32 +5,33 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - SushiBarClientApp</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" />
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
<link rel="stylesheet" href="~/SushiBarClientApp.styles.css" asp-append-version="true" />
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<header>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bgwhite border-bottom box-shadow mb-3">
<div class="container">
<a class="navbar-brand" asp-area="" asp-controller="Home" aspaction="Index">Суши бар</a>
<button class="navbar-toggler" type="button" datatoggle="collapse" data-target=".navbar-collapse" ariacontrols="navbarSupportedContent"
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
<div class="container-fluid">
<a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">Суши-Бар</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse d-sm-inline-flex flex-smrow-reverse">
<div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asparea="" asp-controller="Home" asp-action="Index">Заказы</a>
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Заказы</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asparea="" asp-controller="Home" asp-action="Privacy">Личные данные</a>
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Личные данные</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asparea="" asp-controller="Home" asp-action="Enter">Вход</a>
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Enter">Вход</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asparea="" asp-controller="Home" asp-action="Register">Регистрация</a>
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Register">Регистрация</a>
</li>
</ul>
</div>
@ -42,12 +43,15 @@
@RenderBody()
</main>
</div>
<footer class="border-top footer text-muted">
<div class="container">
&copy; 2020 - Суши бар - <a asp-area="" aspcontroller="Home" asp-action="Privacy">Личные данные</a>
&copy; 2024 - SushiBarClientApp - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</div>
</footer>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
@RenderSection("Scripts", required: false)
@await RenderSectionAsync("Scripts", required: false)
</body>
</html>

View File

@ -1,4 +1,4 @@
/* Please see documentation at https://learn.microsoft.com/aspnet/core/client-side/bundling-and-minification
/* Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification
for details on configuring this project to bundle and minify static web assets. */
a.navbar-brand {

View File

@ -6,6 +6,5 @@
}
},
"AllowedHosts": "*",
"IPAddress": "http://localhost:5262/"
}
"IPAddress": "http://localhost:5037/"
}

View File

@ -8,10 +8,6 @@ html {
}
}
.btn:focus, .btn:active:focus, .btn-link.nav-link:focus, .form-control:focus, .form-check-input:focus {
box-shadow: 0 0 0 0.1rem white, 0 0 0 0.25rem #258cfb;
}
html {
position: relative;
min-height: 100%;

View File

@ -1,4 +1,4 @@
// Please see documentation at https://learn.microsoft.com/aspnet/core/client-side/bundling-and-minification
// Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification
// for details on configuring this project to bundle and minify static web assets.
// Write your JavaScript code.

View File

@ -1,23 +1,12 @@
The MIT License (MIT)
Copyright (c) .NET Foundation. All rights reserved.
Copyright (c) .NET Foundation and Contributors
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
these files except in compliance with the License. You may obtain a copy of the
License at
All rights reserved.
http://www.apache.org/licenses/LICENSE-2.0
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.

View File

@ -1,10 +1,7 @@
/**
* @license
* Unobtrusive validation support library for jQuery and jQuery Validate
* Copyright (c) .NET Foundation. All rights reserved.
* Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
* @version v4.0.0
*/
// Unobtrusive validation support library for jQuery and jQuery Validate
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// @version v3.2.11
/*jslint white: true, browser: true, onevar: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, newcap: true, immed: true, strict: false */
/*global document: false, jQuery: false */

File diff suppressed because one or more lines are too long

View File

@ -1,5 +1,13 @@
Copyright JS Foundation and other contributors, https://js.foundation/
Copyright OpenJS Foundation and other contributors, https://openjsf.org/
This software consists of voluntary contributions made by many
individuals. For exact contribution history, see the revision history
available at https://github.com/jquery/jquery
The following license applies to all parts of this software except as
documented below:
====
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
@ -18,4 +26,11 @@ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
====
All files located in the node_modules and external directories are
externally maintained libraries used by this software which have their
own licenses; we recommend you read them, as their terms may differ from
the terms above.

View File

@ -1,15 +1,15 @@
/*!
* jQuery JavaScript Library v3.6.0
* jQuery JavaScript Library v3.5.1
* https://jquery.com/
*
* Includes Sizzle.js
* https://sizzlejs.com/
*
* Copyright OpenJS Foundation and other contributors
* Copyright JS Foundation and other contributors
* Released under the MIT license
* https://jquery.org/license
*
* Date: 2021-03-02T17:08Z
* Date: 2020-05-04T22:49Z
*/
( function( global, factory ) {
@ -76,16 +76,12 @@ var support = {};
var isFunction = function isFunction( obj ) {
// Support: Chrome <=57, Firefox <=52
// In some browsers, typeof returns "function" for HTML <object> elements
// (i.e., `typeof document.createElement( "object" ) === "function"`).
// We don't want to classify *any* DOM node as a function.
// Support: QtWeb <=3.8.5, WebKit <=534.34, wkhtmltopdf tool <=0.12.5
// Plus for old WebKit, typeof returns "function" for HTML collections
// (e.g., `typeof document.getElementsByTagName("div") === "function"`). (gh-4756)
return typeof obj === "function" && typeof obj.nodeType !== "number" &&
typeof obj.item !== "function";
};
// Support: Chrome <=57, Firefox <=52
// In some browsers, typeof returns "function" for HTML <object> elements
// (i.e., `typeof document.createElement( "object" ) === "function"`).
// We don't want to classify *any* DOM node as a function.
return typeof obj === "function" && typeof obj.nodeType !== "number";
};
var isWindow = function isWindow( obj ) {
@ -151,7 +147,7 @@ function toType( obj ) {
var
version = "3.6.0",
version = "3.5.1",
// Define a local copy of jQuery
jQuery = function( selector, context ) {
@ -405,7 +401,7 @@ jQuery.extend( {
if ( isArrayLike( Object( arr ) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
[ arr ] : arr
);
} else {
push.call( ret, arr );
@ -500,9 +496,9 @@ if ( typeof Symbol === "function" ) {
// Populate the class2type map
jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ),
function( _i, name ) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
} );
function( _i, name ) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
} );
function isArrayLike( obj ) {
@ -522,14 +518,14 @@ function isArrayLike( obj ) {
}
var Sizzle =
/*!
* Sizzle CSS Selector Engine v2.3.6
* Sizzle CSS Selector Engine v2.3.5
* https://sizzlejs.com/
*
* Copyright JS Foundation and other contributors
* Released under the MIT license
* https://js.foundation/
*
* Date: 2021-02-16
* Date: 2020-03-14
*/
( function( window ) {
var i,
@ -1112,8 +1108,8 @@ support = Sizzle.support = {};
* @returns {Boolean} True iff elem is a non-HTML XML node
*/
isXML = Sizzle.isXML = function( elem ) {
var namespace = elem && elem.namespaceURI,
docElem = elem && ( elem.ownerDocument || elem ).documentElement;
var namespace = elem.namespaceURI,
docElem = ( elem.ownerDocument || elem ).documentElement;
// Support: IE <=8
// Assume HTML when documentElement doesn't yet exist, such as inside loading iframes
@ -3028,9 +3024,9 @@ var rneedsContext = jQuery.expr.match.needsContext;
function nodeName( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
}
};
var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i );
@ -4001,8 +3997,8 @@ jQuery.extend( {
resolveContexts = Array( i ),
resolveValues = slice.call( arguments ),
// the primary Deferred
primary = jQuery.Deferred(),
// the master Deferred
master = jQuery.Deferred(),
// subordinate callback factory
updateFunc = function( i ) {
@ -4010,30 +4006,30 @@ jQuery.extend( {
resolveContexts[ i ] = this;
resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
if ( !( --remaining ) ) {
primary.resolveWith( resolveContexts, resolveValues );
master.resolveWith( resolveContexts, resolveValues );
}
};
};
// Single- and empty arguments are adopted like Promise.resolve
if ( remaining <= 1 ) {
adoptValue( singleValue, primary.done( updateFunc( i ) ).resolve, primary.reject,
adoptValue( singleValue, master.done( updateFunc( i ) ).resolve, master.reject,
!remaining );
// Use .then() to unwrap secondary thenables (cf. gh-3000)
if ( primary.state() === "pending" ||
if ( master.state() === "pending" ||
isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) {
return primary.then();
return master.then();
}
}
// Multiple arguments are aggregated like Promise.all array elements
while ( i-- ) {
adoptValue( resolveValues[ i ], updateFunc( i ), primary.reject );
adoptValue( resolveValues[ i ], updateFunc( i ), master.reject );
}
return primary.promise();
return master.promise();
}
} );
@ -4184,8 +4180,8 @@ var access = function( elems, fn, key, value, chainable, emptyGet, raw ) {
for ( ; i < len; i++ ) {
fn(
elems[ i ], key, raw ?
value :
value.call( elems[ i ], i, fn( elems[ i ], key ) )
value :
value.call( elems[ i ], i, fn( elems[ i ], key ) )
);
}
}
@ -5093,7 +5089,10 @@ function buildFragment( elems, context, scripts, selection, ignored ) {
}
var rtypenamespace = /^([^.]*)(?:\.(.+)|)/;
var
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)/;
function returnTrue() {
return true;
@ -5388,8 +5387,8 @@ jQuery.event = {
event = jQuery.event.fix( nativeEvent ),
handlers = (
dataPriv.get( this, "events" ) || Object.create( null )
)[ event.type ] || [],
dataPriv.get( this, "events" ) || Object.create( null )
)[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
@ -5513,12 +5512,12 @@ jQuery.event = {
get: isFunction( hook ) ?
function() {
if ( this.originalEvent ) {
return hook( this.originalEvent );
return hook( this.originalEvent );
}
} :
function() {
if ( this.originalEvent ) {
return this.originalEvent[ name ];
return this.originalEvent[ name ];
}
},
@ -5657,13 +5656,7 @@ function leverageNative( el, type, expectSync ) {
// Cancel the outer synthetic event
event.stopImmediatePropagation();
event.preventDefault();
// Support: Chrome 86+
// In Chrome, if an element having a focusout handler is blurred by
// clicking outside of it, it invokes the handler synchronously. If
// that handler calls `.remove()` on the element, the data is cleared,
// leaving `result` undefined. We need to guard against this.
return result && result.value;
return result.value;
}
// If this is an inner synthetic event for an event with a bubbling surrogate
@ -5828,7 +5821,34 @@ jQuery.each( {
targetTouches: true,
toElement: true,
touches: true,
which: true
which: function( event ) {
var button = event.button;
// Add which for key events
if ( event.which == null && rkeyEvent.test( event.type ) ) {
return event.charCode != null ? event.charCode : event.keyCode;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
if ( !event.which && button !== undefined && rmouseEvent.test( event.type ) ) {
if ( button & 1 ) {
return 1;
}
if ( button & 2 ) {
return 3;
}
if ( button & 4 ) {
return 2;
}
return 0;
}
return event.which;
}
}, jQuery.event.addProp );
jQuery.each( { focus: "focusin", blur: "focusout" }, function( type, delegateType ) {
@ -5854,12 +5874,6 @@ jQuery.each( { focus: "focusin", blur: "focusout" }, function( type, delegateTyp
return true;
},
// Suppress native focus or blur as it's already being fired
// in leverageNative.
_default: function() {
return true;
},
delegateType: delegateType
};
} );
@ -6527,10 +6541,6 @@ var rboxStyle = new RegExp( cssExpand.join( "|" ), "i" );
// set in CSS while `offset*` properties report correct values.
// Behavior in IE 9 is more subtle than in newer versions & it passes
// some versions of this test; make sure not to make it pass there!
//
// Support: Firefox 70+
// Only Firefox includes border widths
// in computed dimensions. (gh-4529)
reliableTrDimensions: function() {
var table, tr, trChild, trStyle;
if ( reliableTrDimensionsVal == null ) {
@ -6538,32 +6548,17 @@ var rboxStyle = new RegExp( cssExpand.join( "|" ), "i" );
tr = document.createElement( "tr" );
trChild = document.createElement( "div" );
table.style.cssText = "position:absolute;left:-11111px;border-collapse:separate";
tr.style.cssText = "border:1px solid";
// Support: Chrome 86+
// Height set through cssText does not get applied.
// Computed height then comes back as 0.
table.style.cssText = "position:absolute;left:-11111px";
tr.style.height = "1px";
trChild.style.height = "9px";
// Support: Android 8 Chrome 86+
// In our bodyBackground.html iframe,
// display for all div elements is set to "inline",
// which causes a problem only in Android 8 Chrome 86.
// Ensuring the div is display: block
// gets around this issue.
trChild.style.display = "block";
documentElement
.appendChild( table )
.appendChild( tr )
.appendChild( trChild );
trStyle = window.getComputedStyle( tr );
reliableTrDimensionsVal = ( parseInt( trStyle.height, 10 ) +
parseInt( trStyle.borderTopWidth, 10 ) +
parseInt( trStyle.borderBottomWidth, 10 ) ) === tr.offsetHeight;
reliableTrDimensionsVal = parseInt( trStyle.height ) > 3;
documentElement.removeChild( table );
}
@ -7027,10 +7022,10 @@ jQuery.each( [ "height", "width" ], function( _i, dimension ) {
// Running getBoundingClientRect on a disconnected node
// in IE throws an error.
( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ?
swap( elem, cssShow, function() {
return getWidthOrHeight( elem, dimension, extra );
} ) :
getWidthOrHeight( elem, dimension, extra );
swap( elem, cssShow, function() {
return getWidthOrHeight( elem, dimension, extra );
} ) :
getWidthOrHeight( elem, dimension, extra );
}
},
@ -7089,7 +7084,7 @@ jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft,
swap( elem, { marginLeft: 0 }, function() {
return elem.getBoundingClientRect().left;
} )
) + "px";
) + "px";
}
}
);
@ -7228,7 +7223,7 @@ Tween.propHooks = {
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.nodeType === 1 && (
jQuery.cssHooks[ tween.prop ] ||
jQuery.cssHooks[ tween.prop ] ||
tween.elem.style[ finalPropName( tween.prop ) ] != null ) ) {
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
} else {
@ -7473,7 +7468,7 @@ function defaultPrefilter( elem, props, opts ) {
anim.done( function() {
/* eslint-enable no-loop-func */
/* eslint-enable no-loop-func */
// The final step of a "hide" animation is actually hiding the element
if ( !hidden ) {
@ -7593,7 +7588,7 @@ function Animation( elem, properties, options ) {
tweens: [],
createTween: function( prop, end ) {
var tween = jQuery.Tween( elem, animation.opts, prop, end,
animation.opts.specialEasing[ prop ] || animation.opts.easing );
animation.opts.specialEasing[ prop ] || animation.opts.easing );
animation.tweens.push( tween );
return tween;
},
@ -7766,8 +7761,7 @@ jQuery.fn.extend( {
anim.stop( true );
}
};
doAnimation.finish = doAnimation;
doAnimation.finish = doAnimation;
return empty || optall.queue === false ?
this.each( doAnimation ) :
@ -8407,8 +8401,8 @@ jQuery.fn.extend( {
if ( this.setAttribute ) {
this.setAttribute( "class",
className || value === false ?
"" :
dataPriv.get( this, "__className__" ) || ""
"" :
dataPriv.get( this, "__className__" ) || ""
);
}
}
@ -8423,7 +8417,7 @@ jQuery.fn.extend( {
while ( ( elem = this[ i++ ] ) ) {
if ( elem.nodeType === 1 &&
( " " + stripAndCollapse( getClass( elem ) ) + " " ).indexOf( className ) > -1 ) {
return true;
return true;
}
}
@ -8713,7 +8707,9 @@ jQuery.extend( jQuery.event, {
special.bindType || type;
// jQuery handler
handle = ( dataPriv.get( cur, "events" ) || Object.create( null ) )[ event.type ] &&
handle = (
dataPriv.get( cur, "events" ) || Object.create( null )
)[ event.type ] &&
dataPriv.get( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
@ -8860,7 +8856,7 @@ var rquery = ( /\?/ );
// Cross-browser xml parsing
jQuery.parseXML = function( data ) {
var xml, parserErrorElem;
var xml;
if ( !data || typeof data !== "string" ) {
return null;
}
@ -8869,17 +8865,12 @@ jQuery.parseXML = function( data ) {
// IE throws on parseFromString with invalid input.
try {
xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" );
} catch ( e ) {}
} catch ( e ) {
xml = undefined;
}
parserErrorElem = xml && xml.getElementsByTagName( "parsererror" )[ 0 ];
if ( !xml || parserErrorElem ) {
jQuery.error( "Invalid XML: " + (
parserErrorElem ?
jQuery.map( parserErrorElem.childNodes, function( el ) {
return el.textContent;
} ).join( "\n" ) :
data
) );
if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
};
@ -8980,14 +8971,16 @@ jQuery.fn.extend( {
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop( this, "elements" );
return elements ? jQuery.makeArray( elements ) : this;
} ).filter( function() {
} )
.filter( function() {
var type = this.type;
// Use .is( ":disabled" ) so that fieldset[disabled] works
return this.name && !jQuery( this ).is( ":disabled" ) &&
rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
( this.checked || !rcheckableType.test( type ) );
} ).map( function( _i, elem ) {
} )
.map( function( _i, elem ) {
var val = jQuery( this ).val();
if ( val == null ) {
@ -9040,8 +9033,7 @@ var
// Anchor tag for parsing the document origin
originAnchor = document.createElement( "a" );
originAnchor.href = location.href;
originAnchor.href = location.href;
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
@ -9422,8 +9414,8 @@ jQuery.extend( {
// Context for global events is callbackContext if it is a DOM node or jQuery collection
globalEventContext = s.context &&
( callbackContext.nodeType || callbackContext.jquery ) ?
jQuery( callbackContext ) :
jQuery.event,
jQuery( callbackContext ) :
jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
@ -9735,10 +9727,8 @@ jQuery.extend( {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// Use a noop converter for missing script but not if jsonp
if ( !isSuccess &&
jQuery.inArray( "script", s.dataTypes ) > -1 &&
jQuery.inArray( "json", s.dataTypes ) < 0 ) {
// Use a noop converter for missing script
if ( !isSuccess && jQuery.inArray( "script", s.dataTypes ) > -1 ) {
s.converters[ "text script" ] = function() {};
}
@ -10476,6 +10466,12 @@ jQuery.offset = {
options.using.call( elem, props );
} else {
if ( typeof props.top === "number" ) {
props.top += "px";
}
if ( typeof props.left === "number" ) {
props.left += "px";
}
curElem.css( props );
}
}
@ -10644,11 +10640,8 @@ jQuery.each( [ "top", "left" ], function( _i, prop ) {
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
jQuery.each( {
padding: "inner" + name,
content: type,
"": "outer" + name
}, function( defaultExtra, funcName ) {
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name },
function( defaultExtra, funcName ) {
// Margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function( margin, value ) {
@ -10733,8 +10726,7 @@ jQuery.fn.extend( {
}
} );
jQuery.each(
( "blur focus focusin focusout resize scroll click dblclick " +
jQuery.each( ( "blur focus focusin focusout resize scroll click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup contextmenu" ).split( " " ),
function( _i, name ) {
@ -10745,8 +10737,7 @@ jQuery.each(
this.on( name, null, data, fn ) :
this.trigger( name );
};
}
);
} );

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

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

View File

@ -15,5 +15,7 @@ namespace SushiBarContracts.BindingModels
public int ClientId { get; set; }
public string ClientFIO { get; set; } = string.Empty;
public int? ImplementerId { get; set; }
}
}

View File

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

@ -11,5 +11,6 @@ namespace SushiBarContracts.BusinessLogicsContracts
bool TakeOrderInWork(OrderBindingModel model);
bool FinishOrder(OrderBindingModel model);
bool DeliveryOrder(OrderBindingModel model);
OrderViewModel? ReadElement(OrderSearchModel model);
}
}

View File

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

View File

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

View File

@ -1,12 +1,16 @@

using SushiBarDataModels.Enums;
namespace SushiBarContracts.SearchModels
{
public class OrderSearchModel
{
public int? Id { get; set; }
public DateTime? DateTo { get; set; }
public DateTime? DateFrom { get; set; }
public int? ClientId { get; set; }
public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }
public OrderStatus? Status { get; set; }
public int? ImplementerId { get; set; }
}
}

View File

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

View File

@ -8,21 +8,30 @@ namespace SushiBarContracts.ViewModels
{
[DisplayName("Номер")]
public int Id { get; set; }
public int ClientId { get; set; }
[DisplayName("Имя клиента")]
public string ClientFIO { get; set; } = string.Empty;
public int? ImplementerId { get; set; }
[DisplayName("Исполнитель")]
public string? ImplementerFIO { get; set; } = null;
public int SushiId { get; set; }
[DisplayName("Суши")]
public int ClientId { get; set; }
[DisplayName("ФИО клиента")]
public string ClientFIO { get; set; } = string.Empty;
[DisplayName("Изделие")]
public string SushiName { get; set; } = string.Empty;
[DisplayName("Количество")]
public int Count { get; set; }
[DisplayName("Сумма")]
public double Sum { get; set; }
[DisplayName("Статус")]
public OrderStatus Status { get; set; } = OrderStatus.Неизвестен;
[DisplayName("Дата создания")]
public DateTime DateCreate { get; set; } = DateTime.Now;
[DisplayName("Дата выполнения")]
public DateTime? DateImplement { get; set; }
}

View File

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

View File

@ -11,5 +11,6 @@ namespace SushiBarDataModels.Models
OrderStatus Status { get; }
DateTime DateCreate { get; }
DateTime? DateImplement { get; }
int? ImplementerId { get; }
}
}

View File

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

View File

@ -40,74 +40,46 @@ namespace SushiBarDatabaseImplement.Implements
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
using var context = new SushiBarDatabase();
if (!model.Id.HasValue && model.DateFrom.HasValue && model.DateTo.HasValue)
if ((!model.DateFrom.HasValue || !model.DateTo.HasValue) && !model.ClientId.HasValue && !model.Status.HasValue)
{
return context.Orders
.Include(x => x.Sushi)
.Include(x => x.Client)
.Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo)
.Select(x => x.GetViewModel)
.ToList();
return new();
}
else if (model.Id.HasValue)
{
return context.Orders
.Include(x => x.Sushi)
.Include(x => x.Client)
.Where(x => x.Id == model.Id)
.Select(x => x.GetViewModel)
.ToList();
}
else if (model.ClientId.HasValue)
{
return context.Orders
.Include(x => x.Sushi)
.Include(x => x.Client)
.Where(x => x.ClientId == model.ClientId)
.Select(x => x.GetViewModel)
.ToList();
}
return new();
return context.Orders.Include(x => x.Sushi).Include(x => x.Client).Include(x => x.Implementer).Where(x =>
(model.DateFrom.HasValue && model.DateTo.HasValue && x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo) ||
(model.ClientId.HasValue && x.ClientId == model.ClientId) ||
(model.Status.HasValue && x.Status == model.Status))
.Select(x => x.GetViewModel).ToList();
}
public List<OrderViewModel> GetFullList()
{
using var context = new SushiBarDatabase();
return context.Orders
.Include(x => x.Sushi)
.Include(x => x.Client)
.Select(x => x.GetViewModel)
.ToList();
return context.Orders.Include(x => x.Sushi).Include(x => x.Client).Include(y => y.Implementer).Select(x => x.GetViewModel).ToList();
}
public OrderViewModel? Insert(OrderBindingModel model)
{
var newOrder = Order.Create(model);
using var context = new SushiBarDatabase();
if (model == null)
return null;
var newOrder = Order.Create(context, model);
if (newOrder == null)
{
return null;
}
using var context = new SushiBarDatabase();
context.Orders.Add(newOrder);
context.SaveChanges();
return context.Orders
.Include(x => x.Sushi)
.Include(x => x.Client)
.FirstOrDefault(x => x.Id == newOrder.Id)
?.GetViewModel;
return newOrder.GetViewModel;
}
public OrderViewModel? Update(OrderBindingModel model)
{
using var context = new SushiBarDatabase();
var order = context.Orders
.Include(x => x.Sushi)
.Include(x => x.Client)
.FirstOrDefault(x => x.Id == model.Id);
var order = context.Orders.FirstOrDefault(x => x.Id == model.Id);
if (order == null)
{
return null;
}
order.Update(model);
order.Update(context, model);
context.SaveChanges();
return order.GetViewModel;
}

View File

@ -1,171 +0,0 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SushiBarDatabaseImplement;
#nullable disable
namespace SushiBarDatabaseImplement.Migrations
{
[DbContext(typeof(SushiBarDatabase))]
[Migration("20240403125318_InitialCreate")]
partial class InitialCreate
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.3")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("SushiBarDatabaseImplement.Models.Ingredient", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<double>("Cost")
.HasColumnType("float");
b.Property<string>("IngredientName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Ingredients");
});
modelBuilder.Entity("SushiBarDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.Property<int>("SushiId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("SushiId");
b.ToTable("Orders");
});
modelBuilder.Entity("SushiBarDatabaseImplement.Models.Sushi", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<double>("Price")
.HasColumnType("float");
b.Property<string>("SushiName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("ListSushi");
});
modelBuilder.Entity("SushiBarDatabaseImplement.Models.SushiIngredient", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("IngredientId")
.HasColumnType("int");
b.Property<int>("SushiId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("IngredientId");
b.HasIndex("SushiId");
b.ToTable("SushiIngredients");
});
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.SushiIngredient", b =>
{
b.HasOne("SushiBarDatabaseImplement.Models.Ingredient", "Ingredient")
.WithMany("SushiIngredients")
.HasForeignKey("IngredientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SushiBarDatabaseImplement.Models.Sushi", "Sushi")
.WithMany("Ingredients")
.HasForeignKey("SushiId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Ingredient");
b.Navigation("Sushi");
});
modelBuilder.Entity("SushiBarDatabaseImplement.Models.Ingredient", b =>
{
b.Navigation("SushiIngredients");
});
modelBuilder.Entity("SushiBarDatabaseImplement.Models.Sushi", b =>
{
b.Navigation("Ingredients");
b.Navigation("Orders");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -1,68 +0,0 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SushiBarDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class Add_client : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "ClientId",
table: "Orders",
type: "int",
nullable: false,
defaultValue: 0);
migrationBuilder.CreateTable(
name: "Clients",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ClientFIO = table.Column<string>(type: "nvarchar(max)", nullable: false),
Email = table.Column<string>(type: "nvarchar(max)", nullable: false),
Password = table.Column<string>(type: "nvarchar(max)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Clients", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_Orders_ClientId",
table: "Orders",
column: "ClientId");
migrationBuilder.AddForeignKey(
name: "FK_Orders_Clients_ClientId",
table: "Orders",
column: "ClientId",
principalTable: "Clients",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Orders_Clients_ClientId",
table: "Orders");
migrationBuilder.DropTable(
name: "Clients");
migrationBuilder.DropIndex(
name: "IX_Orders_ClientId",
table: "Orders");
migrationBuilder.DropColumn(
name: "ClientId",
table: "Orders");
}
}
}

View File

@ -12,8 +12,8 @@ using SushiBarDatabaseImplement;
namespace SushiBarDatabaseImplement.Migrations
{
[DbContext(typeof(SushiBarDatabase))]
[Migration("20240501085423_Add_client")]
partial class Add_client
[Migration("20240512150027_6Lab")]
partial class _6Lab
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
@ -25,6 +25,33 @@ namespace SushiBarDatabaseImplement.Migrations
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("SushiBarDataModels.Models.Implementer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ImplementerFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("Qualification")
.HasColumnType("int");
b.Property<int>("WorkExperience")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Implementers");
});
modelBuilder.Entity("SushiBarDatabaseImplement.Models.Client", b =>
{
b.Property<int>("Id")
@ -90,6 +117,9 @@ namespace SushiBarDatabaseImplement.Migrations
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int?>("ImplementerId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
@ -103,6 +133,8 @@ namespace SushiBarDatabaseImplement.Migrations
b.HasIndex("ClientId");
b.HasIndex("ImplementerId");
b.HasIndex("SushiId");
b.ToTable("Orders");
@ -162,6 +194,10 @@ namespace SushiBarDatabaseImplement.Migrations
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SushiBarDataModels.Models.Implementer", "Implementer")
.WithMany("Order")
.HasForeignKey("ImplementerId");
b.HasOne("SushiBarDatabaseImplement.Models.Sushi", "Sushi")
.WithMany("Orders")
.HasForeignKey("SushiId")
@ -170,6 +206,8 @@ namespace SushiBarDatabaseImplement.Migrations
b.Navigation("Client");
b.Navigation("Implementer");
b.Navigation("Sushi");
});
@ -192,6 +230,11 @@ namespace SushiBarDatabaseImplement.Migrations
b.Navigation("Sushi");
});
modelBuilder.Entity("SushiBarDataModels.Models.Implementer", b =>
{
b.Navigation("Order");
});
modelBuilder.Entity("SushiBarDatabaseImplement.Models.Client", b =>
{
b.Navigation("Orders");

View File

@ -6,11 +6,42 @@ using Microsoft.EntityFrameworkCore.Migrations;
namespace SushiBarDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class InitialCreate : Migration
public partial class _6Lab : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Clients",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ClientFIO = table.Column<string>(type: "nvarchar(max)", nullable: false),
Email = table.Column<string>(type: "nvarchar(max)", nullable: false),
Password = table.Column<string>(type: "nvarchar(max)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Clients", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Implementers",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ImplementerFIO = table.Column<string>(type: "nvarchar(max)", nullable: false),
Password = table.Column<string>(type: "nvarchar(max)", nullable: false),
WorkExperience = table.Column<int>(type: "int", nullable: false),
Qualification = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Implementers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Ingredients",
columns: table => new
@ -47,14 +78,27 @@ namespace SushiBarDatabaseImplement.Migrations
.Annotation("SqlServer:Identity", "1, 1"),
SushiId = table.Column<int>(type: "int", nullable: false),
Count = table.Column<int>(type: "int", nullable: false),
ClientId = table.Column<int>(type: "int", nullable: false),
Sum = table.Column<double>(type: "float", nullable: false),
Status = table.Column<int>(type: "int", nullable: false),
DateCreate = table.Column<DateTime>(type: "datetime2", nullable: false),
DateImplement = table.Column<DateTime>(type: "datetime2", nullable: true)
DateImplement = table.Column<DateTime>(type: "datetime2", nullable: true),
ImplementerId = table.Column<int>(type: "int", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Orders", x => x.Id);
table.ForeignKey(
name: "FK_Orders_Clients_ClientId",
column: x => x.ClientId,
principalTable: "Clients",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Orders_Implementers_ImplementerId",
column: x => x.ImplementerId,
principalTable: "Implementers",
principalColumn: "Id");
table.ForeignKey(
name: "FK_Orders_ListSushi_SushiId",
column: x => x.SushiId,
@ -90,6 +134,16 @@ namespace SushiBarDatabaseImplement.Migrations
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Orders_ClientId",
table: "Orders",
column: "ClientId");
migrationBuilder.CreateIndex(
name: "IX_Orders_ImplementerId",
table: "Orders",
column: "ImplementerId");
migrationBuilder.CreateIndex(
name: "IX_Orders_SushiId",
table: "Orders",
@ -115,6 +169,12 @@ namespace SushiBarDatabaseImplement.Migrations
migrationBuilder.DropTable(
name: "SushiIngredients");
migrationBuilder.DropTable(
name: "Clients");
migrationBuilder.DropTable(
name: "Implementers");
migrationBuilder.DropTable(
name: "Ingredients");

View File

@ -22,6 +22,33 @@ namespace SushiBarDatabaseImplement.Migrations
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("SushiBarDataModels.Models.Implementer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ImplementerFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("Qualification")
.HasColumnType("int");
b.Property<int>("WorkExperience")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Implementers");
});
modelBuilder.Entity("SushiBarDatabaseImplement.Models.Client", b =>
{
b.Property<int>("Id")
@ -87,6 +114,9 @@ namespace SushiBarDatabaseImplement.Migrations
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int?>("ImplementerId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
@ -100,6 +130,8 @@ namespace SushiBarDatabaseImplement.Migrations
b.HasIndex("ClientId");
b.HasIndex("ImplementerId");
b.HasIndex("SushiId");
b.ToTable("Orders");
@ -159,6 +191,10 @@ namespace SushiBarDatabaseImplement.Migrations
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SushiBarDataModels.Models.Implementer", "Implementer")
.WithMany("Order")
.HasForeignKey("ImplementerId");
b.HasOne("SushiBarDatabaseImplement.Models.Sushi", "Sushi")
.WithMany("Orders")
.HasForeignKey("SushiId")
@ -167,6 +203,8 @@ namespace SushiBarDatabaseImplement.Migrations
b.Navigation("Client");
b.Navigation("Implementer");
b.Navigation("Sushi");
});
@ -189,6 +227,11 @@ namespace SushiBarDatabaseImplement.Migrations
b.Navigation("Sushi");
});
modelBuilder.Entity("SushiBarDataModels.Models.Implementer", b =>
{
b.Navigation("Order");
});
modelBuilder.Entity("SushiBarDatabaseImplement.Models.Client", b =>
{
b.Navigation("Orders");

View File

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

View File

@ -24,7 +24,11 @@ namespace SushiBarDatabaseImplement.Models
public int Id { get; set; }
public virtual Client? Client { get; set; }
public Sushi? Sushi { get; set; }
public static Order? Create(OrderBindingModel? model)
public int? ImplementerId { get; private set; }
public virtual Implementer? Implementer { get; set; } = new();
public static Order? Create(SushiBarDatabase context, OrderBindingModel? model)
{
if (model == null)
{
@ -39,11 +43,13 @@ namespace SushiBarDatabaseImplement.Models
Status = model.Status,
DateCreate = model.DateCreate,
DateImplement = model.DateImplement,
ClientId = model.ClientId
ClientId = model.ClientId,
ImplementerId = model.ImplementerId,
Implementer = model.ImplementerId.HasValue ? context.Implementers.First(x => x.Id == model.ImplementerId) : null,
};
}
public void Update(OrderBindingModel? model)
public void Update(SushiBarDatabase context, OrderBindingModel? model)
{
if (model == null)
{
@ -51,20 +57,30 @@ namespace SushiBarDatabaseImplement.Models
}
Status = model.Status;
DateImplement = model.DateImplement;
ImplementerId = model.ImplementerId;
Implementer = model.ImplementerId.HasValue ? context.Implementers.First(x => x.Id == model.ImplementerId) : null;
}
public OrderViewModel GetViewModel => new()
public OrderViewModel GetViewModel
{
Id = Id,
SushiId = SushiId,
SushiName=Sushi.SushiName,
Count = Count,
Sum = Sum,
Status = Status,
DateCreate = DateCreate,
DateImplement = DateImplement,
ClientId = ClientId,
ClientFIO = Client.ClientFIO,
};
get {
using var context = new SushiBarDatabase();
return new OrderViewModel
{
Id = Id,
ClientId = ClientId,
ClientFIO = context.Clients.FirstOrDefault(x => x.Id == ClientId)?.ClientFIO ?? string.Empty,
SushiId = SushiId,
SushiName = context.ListSushi.FirstOrDefault(x => x.Id == SushiId)?.SushiName ?? string.Empty,
ImplementerId = ImplementerId,
ImplementerFIO = Implementer?.ImplementerFIO ?? string.Empty,
Count = Count,
Sum = Sum,
Status = Status,
DateCreate = DateCreate,
DateImplement = DateImplement,
};
}
}
}
}

View File

@ -1,5 +1,6 @@
using Microsoft.EntityFrameworkCore;
using SushiBarDatabaseImplement.Models;
using SushiBarDataModels.Models;
namespace SushiBarDatabaseImplement
{
@ -21,5 +22,6 @@ namespace SushiBarDatabaseImplement
public virtual DbSet<SushiIngredient> SushiIngredients { set; get; }
public virtual DbSet<Order> Orders { set; get; }
public virtual DbSet<Client> Clients { set; get; }
public virtual DbSet<Implementer> Implementers { set; get; }
}
}

View File

@ -10,10 +10,12 @@ namespace SushiBarFileImplement
private readonly string OrderFileName = "Order.xml";
private readonly string SushiFileName = "Sushi.xml";
private readonly string ClientFileName = "Client.xml";
private readonly string ImplementerFileName = "Implementer.xml";
public List<Ingredient> Ingredients { get; private set; }
public List<Order> Orders { get; private set; }
public List<Sushi> ListSushi { get; private set; }
public List<Client> Clients { get; private set; }
public List<Implementer> Implementers { get; private set; }
public static DataFileSingleton GetInstance()
{
@ -29,12 +31,15 @@ namespace SushiBarFileImplement
"ListSushi", x => x.GetXElement);
public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement);
public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", x => x.GetXElement);
public void SaveImplementers() => SaveData(Implementers, ImplementerFileName, "Implementers", x => x.GetXElement);
private DataFileSingleton()
{
Ingredients = LoadData(IngredientFileName, "Ingredient", x => Ingredient.Create(x)!)!;
ListSushi = LoadData(SushiFileName, "Sushi", x => Sushi.Create(x)!)!;
Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!;
Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!;
Implementers = LoadData(ImplementerFileName, "Implementer", x => Implementer.Create(x)!)!;
}
private static List<T>? LoadData<T>(string filename, string xmlNodeName,
Func<XElement, T> selectFunction)

View File

@ -0,0 +1,99 @@
using SushiBarContracts.BindingModels;
using SushiBarContracts.SearchModels;
using SushiBarContracts.StoragesContracts;
using SushiBarContracts.ViewModels;
using SushiBarFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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 (model == null)
{
return new();
}
if (model.Id.HasValue)
{
var res = GetElement(model);
return res != null ? new() { res } : new();
}
if (model.ImplementerFIO != null)
{
return _source.Implementers
.Where(x => x.ImplementerFIO.Equals(model.ImplementerFIO))
.Select(x => x.GetViewModel)
.ToList();
}
return new();
}
public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{
if (model.Id.HasValue)
{
return _source.Implementers.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
}
if (model.ImplementerFIO != null && model.Password != null)
{
return _source.Implementers.FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO) && x.Password.Equals(model.Password))?.GetViewModel;
}
if (model.ImplementerFIO != null)
{
return _source.Implementers.FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO))?.GetViewModel;
}
return null;
}
public ImplementerViewModel? Insert(ImplementerBindingModel model)
{
model.Id = _source.Implementers.Count > 0 ? _source.Implementers.Max(x => x.Id) + 1 : 1;
var res = Implementer.Create(model);
if (res != null)
{
_source.Implementers.Add(res);
_source.SaveImplementers();
}
return res?.GetViewModel;
}
public ImplementerViewModel? Update(ImplementerBindingModel model)
{
var res = _source.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (res != null)
{
res.Update(model);
_source.SaveImplementers();
}
return res?.GetViewModel;
}
public ImplementerViewModel? Delete(ImplementerBindingModel model)
{
var res = _source.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (res != null)
{
_source.Implementers.Remove(res);
_source.SaveImplementers();
}
return res?.GetViewModel;
}
}
}

View File

@ -0,0 +1,87 @@
using SushiBarContracts.BindingModels;
using SushiBarContracts.ViewModels;
using SushiBarDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace SushiBarFileImplement.Models
{
public class Implementer : IImplementerModel
{
public int Id { get; private set; }
public string ImplementerFIO { get; private set; } = string.Empty;
public string Password { get; private set; } = string.Empty;
public int WorkExperience { get; private set; }
public int Qualification { get; private set; }
public static Implementer? Create(XElement element)
{
if (element == null)
{
return null;
}
return new()
{
ImplementerFIO = element.Element("FIO")!.Value,
Password = element.Element("Password")!.Value,
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
Qualification = Convert.ToInt32(element.Element("Qualification")!.Value),
WorkExperience = Convert.ToInt32(element.Element("WorkExperience")!.Value),
};
}
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,
};
public XElement GetXElement => new("Client",
new XAttribute("Id", Id),
new XElement("Password", Password),
new XElement("FIO", ImplementerFIO),
new XElement("Qualification", Qualification),
new XElement("WorkExperience", WorkExperience)
);
}
}

View File

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

View File

@ -10,12 +10,14 @@ namespace SushiBarListImplement
public List<Order> Orders { get; set; }
public List<Sushi> ListSushi { get; set; }
public List<Client> Clients { get; set; }
public List<Implementer> Implementers { get; set; }
private DataListSingleton()
{
Ingredients = new List<Ingredient>();
Orders = new List<Order>();
ListSushi = new List<Sushi>();
Clients = new List<Client>();
Implementers = new List<Implementer>();
}
public static DataListSingleton GetInstance()
{

View File

@ -0,0 +1,123 @@
using SushiBarContracts.BindingModels;
using SushiBarContracts.SearchModels;
using SushiBarContracts.StoragesContracts;
using SushiBarContracts.ViewModels;
using SushiBarListImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SushiBarListImplement.Implements
{
public class ImplementerStorage : IImplementerStorage
{
private readonly DataListSingleton _source;
public ImplementerStorage()
{
_source = DataListSingleton.GetInstance();
}
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;
}
public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{
foreach (var x in _source.Implementers)
{
if (model.Id.HasValue && x.Id == model.Id)
{
return x.GetViewModel;
}
if (model.ImplementerFIO != null && model.Password != null && x.ImplementerFIO.Equals(model.ImplementerFIO) && x.Password.Equals(model.Password))
{
return x.GetViewModel;
}
if (model.ImplementerFIO != null && x.ImplementerFIO.Equals(model.ImplementerFIO))
{
return x.GetViewModel;
}
}
return null;
}
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();
}
List<ImplementerViewModel> result = new();
if (model.ImplementerFIO != null)
{
foreach (var implementer in _source.Implementers)
{
if (implementer.ImplementerFIO.Equals(model.ImplementerFIO))
{
result.Add(implementer.GetViewModel);
}
}
}
return result;
}
public List<ImplementerViewModel> GetFullList()
{
var result = new List<ImplementerViewModel>();
foreach (var implementer in _source.Implementers)
{
result.Add(implementer.GetViewModel);
}
return result;
}
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 res = Implementer.Create(model);
if (res != null)
{
_source.Implementers.Add(res);
}
return res?.GetViewModel;
}
public ImplementerViewModel? Update(ImplementerBindingModel model)
{
foreach (var implementer in _source.Implementers)
{
if (implementer.Id == model.Id)
{
implementer.Update(model);
return implementer.GetViewModel;
}
}
return null;
}
}
}

View File

@ -0,0 +1,60 @@
using SushiBarContracts.BindingModels;
using SushiBarContracts.ViewModels;
using SushiBarDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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; private set; } = string.Empty;
public int WorkExperience { get; private set; }
public int Qualification { get; private set; }
public static Implementer? Create(ImplementerBindingModel model)
{
if (model == null)
{
return null;
}
return new()
{
Id = model.Id,
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,
};
}
}

View File

@ -15,6 +15,7 @@ namespace SushiBarListImplement.Models
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен;
public DateTime DateCreate { get; private set; } = DateTime.Now;
public DateTime? DateImplement { get; private set; }
public int? ImplementerId { get; private set; }
public static Order? Create(OrderBindingModel? model)
{
if (model == null)
@ -31,6 +32,7 @@ namespace SushiBarListImplement.Models
DateImplement = model.DateImplement,
Id = model.Id,
ClientId = model.ClientId,
ImplementerId = model.ImplementerId,
};
}
public void Update(OrderBindingModel? model)
@ -57,6 +59,7 @@ namespace SushiBarListImplement.Models
DateCreate = DateCreate,
DateImplement = DateImplement,
ClientId = ClientId,
ImplementerId = ImplementerId,
};
}
}

View File

@ -4,62 +4,65 @@ using SushiBarContracts.BusinessLogicsContracts;
using SushiBarContracts.SearchModel;
using SushiBarContracts.ViewModels;
namespace SushiBarRestApi.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class ClientController : Controller
{
private readonly ILogger _logger;
private readonly IClientLogic _logic;
public ClientController(IClientLogic logic, ILogger<ClientController>
logger)
[Route("api/[controller]/[action]")]
[ApiController]
public class ClientController : Controller
{
_logger = logger;
_logic = logic;
}
[HttpGet]
public ClientViewModel? Login(string login, string password)
{
try
private readonly ILogger _logger;
private readonly IClientLogic _logic;
public ClientController(IClientLogic logic, ILogger<ClientController>
logger)
{
return _logic.ReadElement(new ClientSearchModel
_logger = logger;
_logic = logic;
}
[HttpGet]
public ClientViewModel? Login(string login, string password)
{
try
{
Email = login,
Password = password
});
return _logic.ReadElement(new ClientSearchModel
{
Email = login,
Password = password
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка входа в систему");
throw;
}
}
catch (Exception ex)
[HttpPost]
public void Register(ClientBindingModel model)
{
_logger.LogError(ex, "Ошибка входа в систему");
throw;
try
{
_logic.Create(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка регистрации");
throw;
}
}
}
[HttpPost]
public void Register(ClientBindingModel model)
{
try
[HttpPost]
public void UpdateData(ClientBindingModel model)
{
_logic.Create(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка регистрации");
throw;
}
}
[HttpPost]
public void UpdateData(ClientBindingModel model)
{
try
{
_logic.Update(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка обновления данных");
throw;
try
{
_logic.Update(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка обновления данных");
throw;
}
}
}
}
}

View File

@ -0,0 +1,107 @@
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 : Controller
{
private readonly ILogger _logger;
private readonly IOrderLogic _order;
private readonly IImplementerLogic _logic;
public ImplementerController(IOrderLogic order, IImplementerLogic logic, ILogger<ImplementerController> logger)
{
_logger = logger;
_order = order;
_logic = logic;
}
[HttpGet]
public ImplementerViewModel? Login(string login, string password)
{
try
{
return _logic.ReadElement(new ImplementerSearchModel
{
ImplementerFIO = login,
Password = password
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка авторизации сотрудника");
throw;
}
}
[HttpGet]
public List<OrderViewModel>? GetNewOrders()
{
try
{
return _order.ReadList(new OrderSearchModel
{
Status = OrderStatus.Принят
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения новых заказов");
throw;
}
}
[HttpGet]
public OrderViewModel? GetImplementerOrder(int implementerId)
{
try
{
return _order.ReadElement(new OrderSearchModel
{
ImplementerId = implementerId
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения текущего заказа исполнителя");
throw;
}
}
[HttpPost]
public void TakeOrderInWork(OrderBindingModel model)
{
try
{
_order.TakeOrderInWork(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка перевода заказа с №{Id} в работу", model.Id);
throw;
}
}
[HttpPost]
public void FinishOrder(OrderBindingModel model)
{
try
{
_order.FinishOrder(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о готовности заказа с №{Id}", model.Id);
throw;
}
}
}
}

View File

@ -1,84 +1,83 @@
using DocumentFormat.OpenXml.Office2010.Excel;
using Microsoft.AspNetCore.Mvc;
using SushiBarContracts.BindingModel;
using SushiBarContracts.BindingModels;
using SushiBarContracts.BusinessLogicsContracts;
using SushiBarContracts.SearchModel;
using SushiBarContracts.SearchModels;
using SushiBarContracts.ViewModels;
namespace SushiBarRestApi.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class MainController : Controller
{
private readonly ILogger _logger;
private readonly IOrderLogic _order;
private readonly ISushiLogic _sushi;
public MainController(ILogger<MainController> logger, IOrderLogic order, ISushiLogic sushi)
[Route("api/[controller]/[action]")]
[ApiController]
public class MainController : Controller
{
_logger = logger;
_order = order;
_sushi = sushi;
}
[HttpGet]
public List<SushiViewModel>? GetSushiList()
{
try
private readonly ILogger _logger;
private readonly IOrderLogic _order;
private readonly ISushiLogic _sushi;
public MainController(ILogger<MainController> logger, IOrderLogic order, ISushiLogic sushi)
{
return _sushi.ReadList(null);
_logger = logger;
_order = order;
_sushi = sushi;
}
catch (Exception ex)
[HttpGet]
public List<SushiViewModel>? GetSushiList()
{
_logger.LogError(ex, "Ошибка получения списка продуктов");
throw;
}
}
[HttpGet]
public SushiViewModel? GetSushi(int sushiId)
{
try
{
return _sushi.ReadElement(new SushiSearchModel
try
{
Id = sushiId
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения суши по id={Id}", sushiId);
throw;
}
}
[HttpGet]
public List<OrderViewModel>? GetOrders(int clientId)
{
try
{
return _order.ReadList(new OrderSearchModel
return _sushi.ReadList(null);
}
catch (Exception ex)
{
ClientId = clientId
});
_logger.LogError(ex, "Ошибка получения списка продуктов");
throw;
}
}
catch (Exception ex)
[HttpGet]
public SushiViewModel? GetSushi(int sushiId)
{
_logger.LogError(ex, "Ошибка получения списка заказов клиента id = {Id} ", clientId);
try
{
return _sushi.ReadElement(new SushiSearchModel
{
Id =
sushiId
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения продукта по id={Id}", sushiId);
throw;
}
}
[HttpGet]
public List<OrderViewModel>? GetOrders(int clientId)
{
try
{
return _order.ReadList(new OrderSearchModel
{
ClientId = clientId
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения списка заказов id ={ Id} ", clientId);
throw;
}
}
}
[HttpPost]
public void CreateOrder(OrderBindingModel model)
{
try
[HttpPost]
public void CreateOrder(OrderBindingModel model)
{
_order.CreateOrder(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка создания заказа");
throw;
try
{
_order.CreateOrder(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка создания заказа");
throw;
}
}
}
}
}

View File

@ -1,20 +1,23 @@
using SushiBarContracts.BusinessLogicsContracts;
using SushiBarContracts.StoragesContracts;
using SushiBarDatabaseImplement.Implements;
using Microsoft.OpenApi.Models;
using SushiBarBusinessLogic;
using SushiBarBusinessLogic.BusinessLogics;
using SushiBarContracts.BusinessLogicsContracts;
using SushiBarContracts.StoragesContracts;
using SushiBarDatabaseImplement.Implements;
var builder = WebApplication.CreateBuilder(args);
builder.Logging.SetMinimumLevel(LogLevel.Trace);
builder.Logging.AddLog4Net("log4net.config");
// Add services to the container.
builder.Services.AddTransient<IClientStorage, ClientStorage>();
builder.Services.AddTransient<IOrderStorage, OrderStorage>();
builder.Services.AddTransient<ISushiStorage, SushiStorage>();
builder.Services.AddTransient<IOrderLogic, OrderLogic>();
builder.Services.AddTransient<IClientLogic, ClientLogic>();
builder.Services.AddTransient<ISushiLogic, SushiLogic>();
builder.Services.AddTransient<IImplementerStorage, ImplementerStorage>();
builder.Services.AddTransient<IImplementerLogic, ImplementerLogic>();
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
@ -22,19 +25,20 @@ builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "SushiBarRestApi",
Version = "v1"
Title = "AbstractShopRestApi",
Version
= "v1"
});
});
builder.Services.AddApplicationInsightsTelemetry();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "SushiBarRestApi v1"));
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json",
"AbstractShopRestApi v1"));
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
app.Run();

View File

@ -1,30 +1,20 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:2876",
"sslPort": 44332
"applicationUrl": "http://localhost:5419",
"sslPort": 44379
}
},
"profiles": {
"http": {
"SushiBarRestApi": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5262",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7106;http://localhost:5262",
"applicationUrl": "https://localhost:7100;http://localhost:5037",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}

View File

@ -1,3 +0,0 @@
{
"dependencies": {}
}

View File

@ -1,3 +0,0 @@
{
"dependencies": {}
}

View File

@ -1,22 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.21.0" />
<PackageReference Include="Microsoft.CodeAnalysis.Common" Version="4.9.2" />
<PackageReference Include="Microsoft.Extensions.Logging.Log4Net.AspNetCore" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SushiBarBusinessLogic\SushiBarBusinessLogic.csproj" />
<ProjectReference Include="..\SushiBarDatabaseImplement\SushiBarDatabaseImplement.csproj" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SushiBarBusinessLogic\SushiBarBusinessLogic.csproj" />
<ProjectReference Include="..\SushiBarDatabaseImplement\SushiBarDatabaseImplement.csproj" />
</ItemGroup>
</Project>

View File

@ -1,6 +0,0 @@
@SushiBarRestApi_HostAddress = http://localhost:5262
GET {{SushiBarRestApi_HostAddress}}/weatherforecast/
Accept: application/json
###

View File

@ -1,20 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<log4net>
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
<file value="logs/SushiBarRestApi.log" />
<appendToFile value="true" />
<maximumFileSize value="100KB" />
<maxSizeRollBackups value="2" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %5level %logger.%method [%line] - MESSAGE: %message%newline %exception" />
</layout>
</appender>
<root>
<level value="TRACE" />
<appender-ref ref="RollingFile" />
</root>
</log4net>
</configuration>