Compare commits

...

67 Commits

Author SHA1 Message Date
f235681f4d Лишнее 2023-03-19 12:44:49 +04:00
726036b570 Merge branch 'LabWork02Hard' into LabWork03Hard 2023-03-19 12:39:55 +04:00
f6e1a161e0 Ошибка 2023-03-19 12:38:29 +04:00
f1f1d11272 Ошибка 2023-03-19 12:37:08 +04:00
eb48ee2c52 Ошибка 2023-03-19 12:35:15 +04:00
90dd93ef7a Модель 2023-03-19 12:23:06 +04:00
f997e6fc06 Модель 2023-03-19 12:20:57 +04:00
50c0cdc17e Штуки 2023-03-19 12:15:43 +04:00
d528524f2c Merge branch 'LabWork02Hard' into LabWork03Hard 2023-03-19 12:11:21 +04:00
586c0905ed Фолс 2023-03-19 12:10:30 +04:00
02d95d40f4 Merge branch 'LabWork02Hard' into LabWork03Hard 2023-03-18 20:22:04 +04:00
2e7b0aacaa Фолс 2023-03-18 20:21:39 +04:00
0d26301504 Спасение приложения 2023-03-14 13:05:56 +04:00
e934dc229f Merge branch 'LabWork02Hard' into LabWork03Hard 2023-03-14 12:44:17 +04:00
ad9256c5a6 Тру 2023-03-14 02:21:39 +04:00
48552db0b2 Исправление ошибок прошлого 2023-03-14 02:19:41 +04:00
50e45e7fb3 Merge branch 'LabWork03' into LabWork03Hard 2023-03-10 18:40:55 +04:00
eaafd9b703 Исправление имен 2023-03-10 16:44:26 +04:00
b2185dd836 Merge branch 'LabWork02Hard' into LabWork03Hard 2023-03-09 15:07:35 +04:00
75e4c71d5d Исправление ошибок прошлого 2023-03-09 13:13:48 +04:00
edd859332e Merge branch 'LabWork02Hard' into LabWork03Hard 2023-03-07 21:29:35 +04:00
1db299c9b1 Исправления статуса "Готов" и обнуления изделий. 2023-03-07 21:28:41 +04:00
9399a68fc9 Что-то работает, но не все 2023-03-07 19:27:57 +04:00
522bff8245 Промежуточное фиксирование. Добавление классов, связанных с магазином 2023-03-07 17:20:16 +04:00
84525a17da Merge branch 'LabWork03' into LabWork03Hard 2023-03-07 12:46:17 +04:00
6447cc832d Исправление пространства имен 2023-03-04 10:46:26 +04:00
80c35aa762 Красота 2023-03-04 10:40:57 +04:00
5939957007 Дофига всего сделала, забыла уже что сделала(короче у меня был какой-то план и я его придерживалась) 2023-03-04 10:35:49 +04:00
9d5759527e Дофига всего сделала, забыла уже что сделала(короче у меня был какой-то план и я его придерживалась) 2023-03-04 10:34:01 +04:00
186dab5087 Создание ветки 2023-03-01 20:22:06 +04:00
e962963589 Исправление модели отображения заказа 2023-03-01 20:14:15 +04:00
1a41ad5ce3 Может быть так будет лучше 2023-02-28 12:38:33 +04:00
9450ae2f6f ЛР3 2023-02-27 23:42:56 +04:00
3f49eade0f ЛР3 2023-02-27 22:36:23 +04:00
46b8e09d6a ЛР3 2023-02-27 22:24:18 +04:00
c1f92ed0c6 ЛР3 2023-02-27 22:16:28 +04:00
8841a10725 Merge branch 'LabWork01' into LabWork02 2023-02-14 12:32:37 +04:00
96ab46bf0c Merge branch 'LabWork01' into LabWork01Hard 2023-02-14 12:31:43 +04:00
12ca78bbe5 Исправления 2023-02-14 12:31:20 +04:00
cb4a75d90d Исправление FormMain 2023-02-14 12:28:32 +04:00
77bb780e69 Фикс бага в отображении даты 2023-02-14 12:10:14 +04:00
777cc9f4ad Merge branch 'LabWork01' into LabWork02 2023-02-14 11:47:10 +04:00
480fcea5d1 Merge branch 'LabWork01' into LabWork01Hard 2023-02-14 11:45:00 +04:00
2591be00fd Фикс меню суши 2023-02-14 11:44:33 +04:00
863deea987 Удаление лишнего using 2023-02-14 11:36:38 +04:00
2b8ef3fac0 Название формы поменено. 2023-02-14 11:25:23 +04:00
a4a2c34044 Изменение логики FormShop. Исправление форматирования в некоторых классах 2023-02-14 00:26:18 +04:00
65d38414ee Форматирование FormShop 2023-02-13 23:38:41 +04:00
9353ee3b06 Вроде работает 2023-02-13 23:13:13 +04:00
db19d63b37 ShopLogic 2023-02-13 20:45:17 +04:00
e378dbb4e9 ЛР2 2023-02-12 16:27:41 +04:00
5b9722bae2 Слияние 2023-02-12 16:26:50 +04:00
4a2b0c5192 Изменение пространства имен 2023-02-12 16:23:30 +04:00
b91edc375c Исправление заказа 2023-02-12 16:00:47 +04:00
a8888dd285 ЛР2 2023-02-12 15:29:29 +04:00
58f59670cd Merge branch 'LabWork01' into LabWork02 2023-02-12 15:00:42 +04:00
b95a2c4173 Ну это точно все 2023-02-12 14:58:35 +04:00
8a1e2acacb Временный вариант 2023-02-12 14:57:32 +04:00
5cf4115a8e Надеюсь это все 2023-02-12 13:11:05 +04:00
df37126b54 Последние фиксы 2023-02-12 12:33:09 +04:00
218ba80bf6 Последние фиксы 2023-02-12 12:27:26 +04:00
9af0c201fb Последние фиксы 2023-02-12 12:11:49 +04:00
f550a6900b Фиксы 2023-02-07 12:55:45 +04:00
4a72fab709 Фиксы 2023-02-01 14:58:05 +04:00
6306b20430 Фиксы 2023-02-01 12:16:22 +04:00
0c05166def Фиксы 2023-01-31 18:07:09 +04:00
6b93115ff3 Готовая ЛР1 2023-01-31 15:23:18 +04:00
112 changed files with 8114 additions and 184 deletions

View File

@ -3,7 +3,19 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.3.32929.385
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SushiBar", "SushiBar\SushiBar.csproj", "{021299FA-4932-4367-A9A7-378EB340D8BC}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SushiBarView", "SushiBar\SushiBarView.csproj", "{021299FA-4932-4367-A9A7-378EB340D8BC}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SushiBarDataModels", "SushiBarDataModels\SushiBarDataModels.csproj", "{8DD9F541-A4FA-4C0B-8E7D-8525C0D77E1C}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SushiBarContracts", "SushiBarContracts\SushiBarContracts.csproj", "{1B31E006-79D1-4376-AEEB-55AF60806AB1}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SushiBarBusinessLogic", "SushiBarBusinessLogic\SushiBarBusinessLogic.csproj", "{2755BF17-8728-4D7E-A4EE-BC8810C508F6}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SushiBarListImplement", "SushiBarListImplement\SushiBarListImplement.csproj", "{81A91405-3721-40EF-A47C-CEBD92C0A4D0}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SushiBarFileImplement", "SushiBarFileImplement\SushiBarFileImplement.csproj", "{A26B0D9A-31CB-4845-ABC3-D84E60BECE46}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SushiBarDatabaseImplement", "SushiBarDatabaseImplement\SushiBarDatabaseImplement.csproj", "{206B0A13-956D-4E9A-88CD-17F89158E0E7}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -15,6 +27,30 @@ Global
{021299FA-4932-4367-A9A7-378EB340D8BC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{021299FA-4932-4367-A9A7-378EB340D8BC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{021299FA-4932-4367-A9A7-378EB340D8BC}.Release|Any CPU.Build.0 = Release|Any CPU
{8DD9F541-A4FA-4C0B-8E7D-8525C0D77E1C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8DD9F541-A4FA-4C0B-8E7D-8525C0D77E1C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8DD9F541-A4FA-4C0B-8E7D-8525C0D77E1C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8DD9F541-A4FA-4C0B-8E7D-8525C0D77E1C}.Release|Any CPU.Build.0 = Release|Any CPU
{1B31E006-79D1-4376-AEEB-55AF60806AB1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1B31E006-79D1-4376-AEEB-55AF60806AB1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1B31E006-79D1-4376-AEEB-55AF60806AB1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1B31E006-79D1-4376-AEEB-55AF60806AB1}.Release|Any CPU.Build.0 = Release|Any CPU
{2755BF17-8728-4D7E-A4EE-BC8810C508F6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2755BF17-8728-4D7E-A4EE-BC8810C508F6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2755BF17-8728-4D7E-A4EE-BC8810C508F6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2755BF17-8728-4D7E-A4EE-BC8810C508F6}.Release|Any CPU.Build.0 = Release|Any CPU
{81A91405-3721-40EF-A47C-CEBD92C0A4D0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{81A91405-3721-40EF-A47C-CEBD92C0A4D0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{81A91405-3721-40EF-A47C-CEBD92C0A4D0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{81A91405-3721-40EF-A47C-CEBD92C0A4D0}.Release|Any CPU.Build.0 = Release|Any CPU
{A26B0D9A-31CB-4845-ABC3-D84E60BECE46}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A26B0D9A-31CB-4845-ABC3-D84E60BECE46}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A26B0D9A-31CB-4845-ABC3-D84E60BECE46}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A26B0D9A-31CB-4845-ABC3-D84E60BECE46}.Release|Any CPU.Build.0 = Release|Any CPU
{206B0A13-956D-4E9A-88CD-17F89158E0E7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{206B0A13-956D-4E9A-88CD-17F89158E0E7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{206B0A13-956D-4E9A-88CD-17F89158E0E7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{206B0A13-956D-4E9A-88CD-17F89158E0E7}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@ -1,39 +0,0 @@
namespace SushiBar
{
partial class Form1
{
/// <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.components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Text = "Form1";
}
#endregion
}
}

View File

@ -1,10 +0,0 @@
namespace SushiBar
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}

View File

@ -1,120 +0,0 @@
<?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,149 @@
namespace SushiBarView
{
partial class FormCreateOrder
{
/// <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.buttonCancel = new System.Windows.Forms.Button();
this.buttonSave = new System.Windows.Forms.Button();
this.textBoxSum = new System.Windows.Forms.TextBox();
this.textBoxCount = new System.Windows.Forms.TextBox();
this.comboBoxSushi = new System.Windows.Forms.ComboBox();
this.labelSum = new System.Windows.Forms.Label();
this.labelCount = new System.Windows.Forms.Label();
this.labelName = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(241, 90);
this.buttonCancel.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(82, 22);
this.buttonCancel.TabIndex = 15;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.ButtonCancel_Click);
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(153, 90);
this.buttonSave.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(82, 22);
this.buttonSave.TabIndex = 14;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.ButtonSave_Click);
//
// textBoxSum
//
this.textBoxSum.Location = new System.Drawing.Point(93, 63);
this.textBoxSum.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.textBoxSum.Name = "textBoxSum";
this.textBoxSum.Size = new System.Drawing.Size(230, 23);
this.textBoxSum.TabIndex = 13;
//
// textBoxCount
//
this.textBoxCount.Location = new System.Drawing.Point(93, 36);
this.textBoxCount.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.textBoxCount.Name = "textBoxCount";
this.textBoxCount.Size = new System.Drawing.Size(230, 23);
this.textBoxCount.TabIndex = 12;
this.textBoxCount.TextChanged += new System.EventHandler(this.TextBoxCount_TextChanged);
//
// comboBoxSushi
//
this.comboBoxSushi.FormattingEnabled = true;
this.comboBoxSushi.Location = new System.Drawing.Point(93, 9);
this.comboBoxSushi.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.comboBoxSushi.Name = "comboBoxSushi";
this.comboBoxSushi.Size = new System.Drawing.Size(230, 23);
this.comboBoxSushi.TabIndex = 11;
this.comboBoxSushi.SelectedIndexChanged += new System.EventHandler(this.ComboBoxSushi_SelectedIndexChanged);
//
// labelSum
//
this.labelSum.AutoSize = true;
this.labelSum.Location = new System.Drawing.Point(12, 63);
this.labelSum.Name = "labelSum";
this.labelSum.Size = new System.Drawing.Size(48, 15);
this.labelSum.TabIndex = 10;
this.labelSum.Text = "Сумма:";
//
// labelCount
//
this.labelCount.AutoSize = true;
this.labelCount.Location = new System.Drawing.Point(12, 36);
this.labelCount.Name = "labelCount";
this.labelCount.Size = new System.Drawing.Size(75, 15);
this.labelCount.TabIndex = 9;
this.labelCount.Text = "Количество:";
//
// labelName
//
this.labelName.AutoSize = true;
this.labelName.Location = new System.Drawing.Point(12, 9);
this.labelName.Name = "labelName";
this.labelName.Size = new System.Drawing.Size(42, 15);
this.labelName.TabIndex = 8;
this.labelName.Text = "Суши:";
//
// FormCreateOrder
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(343, 128);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.textBoxSum);
this.Controls.Add(this.textBoxCount);
this.Controls.Add(this.comboBoxSushi);
this.Controls.Add(this.labelSum);
this.Controls.Add(this.labelCount);
this.Controls.Add(this.labelName);
this.Name = "FormCreateOrder";
this.Text = "Заказ";
this.Load += new System.EventHandler(this.FormCreateOrder_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Button buttonCancel;
private Button buttonSave;
private TextBox textBoxSum;
private TextBox textBoxCount;
private ComboBox comboBoxSushi;
private Label labelSum;
private Label labelCount;
private Label labelName;
}
}

View File

@ -0,0 +1,116 @@
using Microsoft.Extensions.Logging;
using SushiBarContracts.BindingModels;
using SushiBarContracts.BusinessLogicsContracts;
using SushiBarContracts.SearchModels;
namespace SushiBarView
{
public partial class FormCreateOrder : Form
{
private readonly ILogger _logger;
private readonly ISushiLogic _logicS;
private readonly IOrderLogic _logicO;
public FormCreateOrder(ILogger<FormCreateOrder> logger, ISushiLogic logicS, IOrderLogic logicO)
{
InitializeComponent();
_logger = logger;
_logicS = logicS;
_logicO = logicO;
}
private void FormCreateOrder_Load(object sender, EventArgs e)
{
_logger.LogInformation("Загрузка суши для заказа");
try
{
var list = _logicS.ReadList(null);
if (list != null)
{
comboBoxSushi.DisplayMember = "SushiName";
comboBoxSushi.ValueMember = "Id";
comboBoxSushi.DataSource = list;
comboBoxSushi.SelectedItem = null;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка суши");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void CalcSum()
{
if (comboBoxSushi.SelectedValue != null && !string.IsNullOrEmpty(textBoxCount.Text))
{
try
{
int id = Convert.ToInt32(comboBoxSushi.SelectedValue);
var sushi = _logicS.ReadElement(new SushiSearchModel
{
Id = id
});
int count = Convert.ToInt32(textBoxCount.Text);
textBoxSum.Text = Math.Round(count * (sushi?.Price ?? 0), 2).ToString();
_logger.LogInformation("Расчет суммы заказа");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка расчета суммы заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void TextBoxCount_TextChanged(object sender, EventArgs e)
{
CalcSum();
}
private void ComboBoxSushi_SelectedIndexChanged(object sender, EventArgs e)
{
CalcSum();
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCount.Text))
{
MessageBox.Show("Заполните поле 'Количество'", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxSushi.SelectedValue == null)
{
MessageBox.Show("Выберите суши", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Создание заказа");
try
{
var operationResult = _logicO.CreateOrder(new OrderBindingModel
{
SushiId = Convert.ToInt32(comboBoxSushi.SelectedValue),
Count = Convert.ToInt32(textBoxCount.Text),
Sum = Convert.ToDouble(textBoxSum.Text)
});
if (!operationResult)
{
throw new Exception("Ошибка при создании заказа. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение",
MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка создания заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,123 @@
namespace SushiBarView
{
partial class FormIngredient
{
/// <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.buttonCancel = new System.Windows.Forms.Button();
this.buttonSave = new System.Windows.Forms.Button();
this.textBoxCost = new System.Windows.Forms.TextBox();
this.textBoxName = new System.Windows.Forms.TextBox();
this.labelPrice = new System.Windows.Forms.Label();
this.labelBlankName = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(200, 73);
this.buttonCancel.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(82, 22);
this.buttonCancel.TabIndex = 11;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.ButtonCancel_Click);
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(112, 73);
this.buttonSave.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(82, 22);
this.buttonSave.TabIndex = 10;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.ButtonSave_Click);
//
// textBoxCost
//
this.textBoxCost.Location = new System.Drawing.Point(111, 38);
this.textBoxCost.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.textBoxCost.Name = "textBoxCost";
this.textBoxCost.Size = new System.Drawing.Size(183, 23);
this.textBoxCost.TabIndex = 9;
//
// textBoxName
//
this.textBoxName.Location = new System.Drawing.Point(111, 11);
this.textBoxName.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.textBoxName.Name = "textBoxName";
this.textBoxName.Size = new System.Drawing.Size(329, 23);
this.textBoxName.TabIndex = 8;
//
// labelPrice
//
this.labelPrice.AutoSize = true;
this.labelPrice.Location = new System.Drawing.Point(12, 37);
this.labelPrice.Name = "labelPrice";
this.labelPrice.Size = new System.Drawing.Size(38, 15);
this.labelPrice.TabIndex = 7;
this.labelPrice.Text = "Цена:";
//
// labelBlankName
//
this.labelBlankName.AutoSize = true;
this.labelBlankName.Location = new System.Drawing.Point(12, 14);
this.labelBlankName.Name = "labelBlankName";
this.labelBlankName.Size = new System.Drawing.Size(62, 15);
this.labelBlankName.TabIndex = 6;
this.labelBlankName.Text = "Название:";
//
// FormIngredient
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(448, 106);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.textBoxCost);
this.Controls.Add(this.textBoxName);
this.Controls.Add(this.labelPrice);
this.Controls.Add(this.labelBlankName);
this.Name = "FormIngredient";
this.Text = "Ингредиент";
this.Load += new System.EventHandler(this.FormIngredient_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Button buttonCancel;
private Button buttonSave;
private TextBox textBoxCost;
private TextBox textBoxName;
private Label labelPrice;
private Label labelBlankName;
}
}

View File

@ -0,0 +1,87 @@
using SushiBarContracts.BindingModels;
using SushiBarContracts.SearchModels;
using Microsoft.Extensions.Logging;
using SushiBarContracts.BusinessLogicsContracts;
namespace SushiBarView
{
public partial class FormIngredient : Form
{
private readonly ILogger _logger;
private readonly IIngredientLogic _logic;
private int? _id;
public int Id { set { _id = value; } }
public FormIngredient(ILogger<FormIngredient> logger, IIngredientLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormIngredient_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
try
{
_logger.LogInformation("Получение ингредиента");
var view = _logic.ReadElement(new IngredientSearchModel
{
Id = _id.Value
});
if (view != null)
{
textBoxName.Text = view.IngredientName;
textBoxCost.Text = view.Cost.ToString();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения ингредиента");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxName.Text))
{
MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение ингредиента");
try
{
var model = new IngredientBindingModel
{
Id = _id ?? 0,
IngredientName = textBoxName.Text,
Cost = Convert.ToDouble(textBoxCost.Text)
};
var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model);
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения ингредиента");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,122 @@
namespace SushiBarView
{
partial class FormIngredients
{
/// <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.buttonUpdate = new System.Windows.Forms.Button();
this.buttonDelete = new System.Windows.Forms.Button();
this.buttonEdit = new System.Windows.Forms.Button();
this.buttonAdd = new System.Windows.Forms.Button();
this.dataGridView = new System.Windows.Forms.DataGridView();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
//
// buttonUpdate
//
this.buttonUpdate.Location = new System.Drawing.Point(432, 186);
this.buttonUpdate.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonUpdate.Name = "buttonUpdate";
this.buttonUpdate.Size = new System.Drawing.Size(130, 22);
this.buttonUpdate.TabIndex = 9;
this.buttonUpdate.Text = "Обновить";
this.buttonUpdate.UseVisualStyleBackColor = true;
this.buttonUpdate.Click += new System.EventHandler(this.ButtonRef_Click);
//
// buttonDelete
//
this.buttonDelete.Location = new System.Drawing.Point(432, 160);
this.buttonDelete.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonDelete.Name = "buttonDelete";
this.buttonDelete.Size = new System.Drawing.Size(130, 22);
this.buttonDelete.TabIndex = 8;
this.buttonDelete.Text = "Удалить";
this.buttonDelete.UseVisualStyleBackColor = true;
this.buttonDelete.Click += new System.EventHandler(this.ButtonDel_Click);
//
// buttonEdit
//
this.buttonEdit.Location = new System.Drawing.Point(432, 134);
this.buttonEdit.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonEdit.Name = "buttonEdit";
this.buttonEdit.Size = new System.Drawing.Size(130, 22);
this.buttonEdit.TabIndex = 7;
this.buttonEdit.Text = "Изменить";
this.buttonEdit.UseVisualStyleBackColor = true;
this.buttonEdit.Click += new System.EventHandler(this.ButtonUpd_Click);
//
// buttonAdd
//
this.buttonAdd.Location = new System.Drawing.Point(432, 108);
this.buttonAdd.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(130, 22);
this.buttonAdd.TabIndex = 6;
this.buttonAdd.Text = "Добавить";
this.buttonAdd.UseVisualStyleBackColor = true;
this.buttonAdd.Click += new System.EventHandler(this.ButtonAdd_Click);
//
// dataGridView
//
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Dock = System.Windows.Forms.DockStyle.Left;
this.dataGridView.GridColor = System.Drawing.Color.White;
this.dataGridView.Location = new System.Drawing.Point(0, 0);
this.dataGridView.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowHeadersWidth = 51;
this.dataGridView.RowTemplate.Height = 29;
this.dataGridView.Size = new System.Drawing.Size(426, 348);
this.dataGridView.TabIndex = 5;
//
// FormIngredients
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(571, 348);
this.Controls.Add(this.dataGridView);
this.Controls.Add(this.buttonUpdate);
this.Controls.Add(this.buttonDelete);
this.Controls.Add(this.buttonEdit);
this.Controls.Add(this.buttonAdd);
this.Name = "FormIngredients";
this.Text = "Ингредиенты";
this.Load += new System.EventHandler(this.FormIngredients_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.ResumeLayout(false);
}
#endregion
private Button buttonUpdate;
private Button buttonDelete;
private Button buttonEdit;
private Button buttonAdd;
private DataGridView dataGridView;
}
}

View File

@ -0,0 +1,99 @@
using Microsoft.Extensions.Logging;
using SushiBarContracts.BindingModels;
using SushiBarContracts.BusinessLogicsContracts;
namespace SushiBarView
{
public partial class FormIngredients : Form
{
private readonly ILogger _logger;
private readonly IIngredientLogic _logic;
public FormIngredients(ILogger<FormIngredients> logger, IIngredientLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormIngredients_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["IngredientName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка ингредиентов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки ингредиентов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormIngredient));
if (service is FormIngredient 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(FormIngredient));
if (service is FormIngredient 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 IngredientBindingModel
{
Id = id
}))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления ингредиента");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void ButtonRef_Click(object sender, EventArgs e)
{
LoadData();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,122 @@
namespace SushiBarView
{
partial class FormListSushi
{
/// <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.dataGridView = new System.Windows.Forms.DataGridView();
this.buttonUpdate = new System.Windows.Forms.Button();
this.buttonDelete = new System.Windows.Forms.Button();
this.buttonEdit = new System.Windows.Forms.Button();
this.buttonAdd = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
//
// dataGridView
//
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Dock = System.Windows.Forms.DockStyle.Left;
this.dataGridView.GridColor = System.Drawing.Color.White;
this.dataGridView.Location = new System.Drawing.Point(0, 0);
this.dataGridView.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowHeadersWidth = 51;
this.dataGridView.RowTemplate.Height = 29;
this.dataGridView.Size = new System.Drawing.Size(426, 345);
this.dataGridView.TabIndex = 10;
//
// buttonUpdate
//
this.buttonUpdate.Location = new System.Drawing.Point(432, 183);
this.buttonUpdate.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonUpdate.Name = "buttonUpdate";
this.buttonUpdate.Size = new System.Drawing.Size(130, 22);
this.buttonUpdate.TabIndex = 14;
this.buttonUpdate.Text = "Обновить";
this.buttonUpdate.UseVisualStyleBackColor = true;
this.buttonUpdate.Click += new System.EventHandler(this.ButtonUpdate_Click);
//
// buttonDelete
//
this.buttonDelete.Location = new System.Drawing.Point(432, 157);
this.buttonDelete.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonDelete.Name = "buttonDelete";
this.buttonDelete.Size = new System.Drawing.Size(130, 22);
this.buttonDelete.TabIndex = 13;
this.buttonDelete.Text = "Удалить";
this.buttonDelete.UseVisualStyleBackColor = true;
this.buttonDelete.Click += new System.EventHandler(this.ButtonDelete_Click);
//
// buttonEdit
//
this.buttonEdit.Location = new System.Drawing.Point(432, 131);
this.buttonEdit.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonEdit.Name = "buttonEdit";
this.buttonEdit.Size = new System.Drawing.Size(130, 22);
this.buttonEdit.TabIndex = 12;
this.buttonEdit.Text = "Изменить";
this.buttonEdit.UseVisualStyleBackColor = true;
this.buttonEdit.Click += new System.EventHandler(this.ButtonEdit_Click);
//
// buttonAdd
//
this.buttonAdd.Location = new System.Drawing.Point(432, 105);
this.buttonAdd.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(130, 22);
this.buttonAdd.TabIndex = 11;
this.buttonAdd.Text = "Добавить";
this.buttonAdd.UseVisualStyleBackColor = true;
this.buttonAdd.Click += new System.EventHandler(this.ButtonAdd_Click);
//
// FormListSushi
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(570, 345);
this.Controls.Add(this.dataGridView);
this.Controls.Add(this.buttonUpdate);
this.Controls.Add(this.buttonDelete);
this.Controls.Add(this.buttonEdit);
this.Controls.Add(this.buttonAdd);
this.Name = "FormListSushi";
this.Text = "Список суши";
this.Load += new System.EventHandler(this.FormDocuments_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
private Button buttonUpdate;
private Button buttonDelete;
private Button buttonEdit;
private Button buttonAdd;
}
}

View File

@ -0,0 +1,104 @@
using Microsoft.Extensions.Logging;
using SushiBarContracts.BindingModels;
using SushiBarContracts.BusinessLogicsContracts;
namespace SushiBarView
{
public partial class FormListSushi : Form
{
private readonly ILogger _logger;
private readonly ISushiLogic _logic;
public FormListSushi(ILogger<FormListSushi> logger, ISushiLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormDocuments_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["SushiName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["SushiIngredients"].Visible = false;
}
_logger.LogInformation("Загрузка суши");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки суши");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSushi));
if (service is FormSushi form)
{
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
private void ButtonEdit_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSushi));
if (service is FormSushi form)
{
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
}
private void ButtonDelete_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 SushiBindingModel
{
Id = id
}))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления суши");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void ButtonUpdate_Click(object sender, EventArgs e)
{
LoadData();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

220
SushiBar/SushiBar/FormMain.Designer.cs generated Normal file
View File

@ -0,0 +1,220 @@
namespace SushiBarView
{
partial class FormMain
{
/// <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.menuStrip = new System.Windows.Forms.MenuStrip();
this.справочникиToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.ингредиентыToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.сушиToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.shopsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.buttonUpdate = new System.Windows.Forms.Button();
this.buttonSetToFinish = new System.Windows.Forms.Button();
this.buttonSetToDone = new System.Windows.Forms.Button();
this.buttonSetToWork = new System.Windows.Forms.Button();
this.buttonCreateOrder = new System.Windows.Forms.Button();
this.dataGridView = new System.Windows.Forms.DataGridView();
this.buttonAddSushiInShop = new System.Windows.Forms.Button();
this.buttonSellSushi = new System.Windows.Forms.Button();
this.menuStrip.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
//
// menuStrip
//
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.справочникиToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.Name = "menuStrip";
this.menuStrip.Size = new System.Drawing.Size(974, 24);
this.menuStrip.TabIndex = 0;
this.menuStrip.Text = "menuStrip1";
//
// справочникиToolStripMenuItem
//
this.справочникиToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.ингредиентыToolStripMenuItem,
this.сушиToolStripMenuItem,
this.shopsToolStripMenuItem});
this.справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem";
this.справочникиToolStripMenuItem.Size = new System.Drawing.Size(94, 20);
this.справочникиToolStripMenuItem.Text = "Справочники";
//
// ингредиентыToolStripMenuItem
//
this.ингредиентыToolStripMenuItem.Name = "ингредиентыToolStripMenuItem";
this.ингредиентыToolStripMenuItem.Size = new System.Drawing.Size(148, 22);
this.ингредиентыToolStripMenuItem.Text = "Ингредиенты";
this.ингредиентыToolStripMenuItem.Click += new System.EventHandler(this.IngredientsToolStripMenuItem_Click);
//
// сушиToolStripMenuItem
//
this.сушиToolStripMenuItem.Name = "сушиToolStripMenuItem";
this.сушиToolStripMenuItem.Size = new System.Drawing.Size(148, 22);
this.сушиToolStripMenuItem.Text = "Суши";
this.сушиToolStripMenuItem.Click += new System.EventHandler(this.SushiToolStripMenuItem_Click);
//
// shopsToolStripMenuItem
//
this.shopsToolStripMenuItem.Name = "shopsToolStripMenuItem";
this.shopsToolStripMenuItem.Size = new System.Drawing.Size(148, 22);
this.shopsToolStripMenuItem.Text = "Магазины";
this.shopsToolStripMenuItem.Click += new System.EventHandler(this.ShopsToolStripMenuItem_Click);
//
// buttonUpdate
//
this.buttonUpdate.Location = new System.Drawing.Point(778, 212);
this.buttonUpdate.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonUpdate.Name = "buttonUpdate";
this.buttonUpdate.Size = new System.Drawing.Size(170, 32);
this.buttonUpdate.TabIndex = 12;
this.buttonUpdate.Text = "Обновить";
this.buttonUpdate.UseVisualStyleBackColor = true;
this.buttonUpdate.Click += new System.EventHandler(this.ButtonRef_Click);
//
// buttonSetToFinish
//
this.buttonSetToFinish.Location = new System.Drawing.Point(778, 176);
this.buttonSetToFinish.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonSetToFinish.Name = "buttonSetToFinish";
this.buttonSetToFinish.Size = new System.Drawing.Size(170, 32);
this.buttonSetToFinish.TabIndex = 11;
this.buttonSetToFinish.Text = "Заказ выдан";
this.buttonSetToFinish.UseVisualStyleBackColor = true;
this.buttonSetToFinish.Click += new System.EventHandler(this.ButtonIssuedOrder_Click);
//
// buttonSetToDone
//
this.buttonSetToDone.Location = new System.Drawing.Point(778, 140);
this.buttonSetToDone.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonSetToDone.Name = "buttonSetToDone";
this.buttonSetToDone.Size = new System.Drawing.Size(170, 32);
this.buttonSetToDone.TabIndex = 10;
this.buttonSetToDone.Text = "Заказ готов";
this.buttonSetToDone.UseVisualStyleBackColor = true;
this.buttonSetToDone.Click += new System.EventHandler(this.ButtonOrderReady_Click);
//
// buttonSetToWork
//
this.buttonSetToWork.Location = new System.Drawing.Point(778, 104);
this.buttonSetToWork.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonSetToWork.Name = "buttonSetToWork";
this.buttonSetToWork.Size = new System.Drawing.Size(170, 32);
this.buttonSetToWork.TabIndex = 9;
this.buttonSetToWork.Text = "Отдать на выполнение";
this.buttonSetToWork.UseVisualStyleBackColor = true;
this.buttonSetToWork.Click += new System.EventHandler(this.ButtonTakeOrderInWork_Click);
//
// buttonCreateOrder
//
this.buttonCreateOrder.Location = new System.Drawing.Point(778, 68);
this.buttonCreateOrder.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonCreateOrder.Name = "buttonCreateOrder";
this.buttonCreateOrder.Size = new System.Drawing.Size(170, 32);
this.buttonCreateOrder.TabIndex = 8;
this.buttonCreateOrder.Text = "Создать заказ";
this.buttonCreateOrder.UseVisualStyleBackColor = true;
this.buttonCreateOrder.Click += new System.EventHandler(this.ButtonCreateOrder_Click);
//
// dataGridView
//
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Dock = System.Windows.Forms.DockStyle.Left;
this.dataGridView.Location = new System.Drawing.Point(0, 24);
this.dataGridView.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowHeadersWidth = 51;
this.dataGridView.RowTemplate.Height = 29;
this.dataGridView.Size = new System.Drawing.Size(755, 358);
this.dataGridView.TabIndex = 7;
//
// buttonAddSushiInShop
//
this.buttonAddSushiInShop.Location = new System.Drawing.Point(778, 248);
this.buttonAddSushiInShop.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonAddSushiInShop.Name = "buttonAddSushiInShop";
this.buttonAddSushiInShop.Size = new System.Drawing.Size(170, 32);
this.buttonAddSushiInShop.TabIndex = 13;
this.buttonAddSushiInShop.Text = "Добавить суши в магазин";
this.buttonAddSushiInShop.UseVisualStyleBackColor = true;
this.buttonAddSushiInShop.Click += new System.EventHandler(this.ButtonAddSushiInShop_Click);
//
// buttonSellSushi
//
this.buttonSellSushi.Location = new System.Drawing.Point(778, 284);
this.buttonSellSushi.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonSellSushi.Name = "buttonSellSushi";
this.buttonSellSushi.Size = new System.Drawing.Size(170, 32);
this.buttonSellSushi.TabIndex = 14;
this.buttonSellSushi.Text = "Продать суши";
this.buttonSellSushi.UseVisualStyleBackColor = true;
this.buttonSellSushi.Click += new System.EventHandler(this.ButtonSellSushi_Click);
//
// FormMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(974, 382);
this.Controls.Add(this.buttonSellSushi);
this.Controls.Add(this.buttonAddSushiInShop);
this.Controls.Add(this.buttonUpdate);
this.Controls.Add(this.buttonSetToFinish);
this.Controls.Add(this.buttonSetToDone);
this.Controls.Add(this.buttonSetToWork);
this.Controls.Add(this.buttonCreateOrder);
this.Controls.Add(this.dataGridView);
this.Controls.Add(this.menuStrip);
this.MainMenuStrip = this.menuStrip;
this.Name = "FormMain";
this.Text = "Суши-бар";
this.Load += new System.EventHandler(this.FormMain_Load);
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private MenuStrip menuStrip;
private ToolStripMenuItem справочникиToolStripMenuItem;
private ToolStripMenuItem ингредиентыToolStripMenuItem;
private ToolStripMenuItem сушиToolStripMenuItem;
private Button buttonUpdate;
private Button buttonSetToFinish;
private Button buttonSetToDone;
private Button buttonSetToWork;
private Button buttonCreateOrder;
private DataGridView dataGridView;
private ToolStripMenuItem shopsToolStripMenuItem;
private Button buttonAddSushiInShop;
private Button buttonSellSushi;
}
}

View File

@ -0,0 +1,174 @@
using Microsoft.Extensions.Logging;
using SushiBarContracts.BindingModels;
using SushiBarContracts.BusinessLogicsContracts;
using SushiBarDataModels.Enums;
namespace SushiBarView
{
public partial class FormMain : Form
{
private readonly ILogger _logger;
private readonly IOrderLogic _orderLogic;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic)
{
InitializeComponent();
_logger = logger;
_orderLogic = orderLogic;
}
private void FormMain_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
_logger.LogInformation("Загрузка заказов");
try
{
var list = _orderLogic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["SushiId"].Visible = false;
}
_logger.LogInformation("Загрузка заказов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки заказов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void IngredientsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormIngredients));
if (service is FormIngredients form)
{
form.ShowDialog();
}
}
private void SushiToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormListSushi));
if (service is FormListSushi form)
{
form.ShowDialog();
}
}
private void ButtonCreateOrder_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder));
if (service is FormCreateOrder form)
{
form.ShowDialog();
LoadData();
}
}
private void ButtonTakeOrderInWork_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id);
try
{
var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel
{
Id = id
});
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка передачи заказа в работу");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonOrderReady_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'", id);
try
{
var operationResult = _orderLogic.FinishOrder(new OrderBindingModel
{
Id = id
});
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о готовности заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonIssuedOrder_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id);
try
{
var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel
{
Id = id
});
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
_logger.LogInformation("Заказ №{id} выдан", id);
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о выдачи заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonRef_Click(object sender, EventArgs e)
{
LoadData();
}
private void ShopsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShops));
if (service is FormShops form)
{
form.ShowDialog();
}
}
private void ButtonAddSushiInShop_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShopSushi));
if (service is FormShopSushi form)
{
form.ShowDialog();
}
}
private void ButtonSellSushi_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSellSushi));
if (service is FormSellSushi form)
{
form.ShowDialog();
LoadData();
}
}
}
}

View File

@ -0,0 +1,63 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
</root>

View File

@ -0,0 +1,126 @@
namespace SushiBarView
{
partial class FormSellSushi
{
/// <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.labelSushi = new System.Windows.Forms.Label();
this.labelCount = new System.Windows.Forms.Label();
this.comboBoxSushi = new System.Windows.Forms.ComboBox();
this.textBoxCount = new System.Windows.Forms.TextBox();
this.buttonSave = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// labelSushi
//
this.labelSushi.AutoSize = true;
this.labelSushi.Location = new System.Drawing.Point(9, 11);
this.labelSushi.Name = "labelSushi";
this.labelSushi.Size = new System.Drawing.Size(39, 15);
this.labelSushi.TabIndex = 0;
this.labelSushi.Text = "Суши";
//
// labelCount
//
this.labelCount.AutoSize = true;
this.labelCount.Location = new System.Drawing.Point(11, 51);
this.labelCount.Name = "labelCount";
this.labelCount.Size = new System.Drawing.Size(72, 15);
this.labelCount.TabIndex = 1;
this.labelCount.Text = "Количество";
//
// comboBoxSushi
//
this.comboBoxSushi.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxSushi.FormattingEnabled = true;
this.comboBoxSushi.Location = new System.Drawing.Point(100, 11);
this.comboBoxSushi.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.comboBoxSushi.Name = "comboBoxSushi";
this.comboBoxSushi.Size = new System.Drawing.Size(230, 23);
this.comboBoxSushi.TabIndex = 3;
//
// textBoxCount
//
this.textBoxCount.Location = new System.Drawing.Point(100, 51);
this.textBoxCount.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.textBoxCount.Name = "textBoxCount";
this.textBoxCount.Size = new System.Drawing.Size(230, 23);
this.textBoxCount.TabIndex = 4;
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(160, 78);
this.buttonSave.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(82, 22);
this.buttonSave.TabIndex = 6;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.ButtonSave_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(248, 78);
this.buttonCancel.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(82, 22);
this.buttonCancel.TabIndex = 7;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.ButtonCancel_Click);
//
// FormSellSushi
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(349, 119);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.textBoxCount);
this.Controls.Add(this.comboBoxSushi);
this.Controls.Add(this.labelCount);
this.Controls.Add(this.labelSushi);
this.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.Name = "FormSellSushi";
this.Text = "Продажа суши";
this.Load += new System.EventHandler(this.FormSellSushi_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Label labelSushi;
private Label labelCount;
private ComboBox comboBoxSushi;
private TextBox textBoxCount;
private Button buttonSave;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,81 @@
using Microsoft.Extensions.Logging;
using SushiBarContracts.BusinessLogicsContracts;
using SushiBarContracts.SearchModels;
namespace SushiBarView
{
public partial class FormSellSushi : Form
{
private readonly ILogger _logger;
private readonly ISushiLogic _logicSushi;
private readonly IShopLogic _logicShop;
public FormSellSushi(ILogger<FormSellSushi> logger, ISushiLogic logicSushi, IShopLogic logicShop)
{
InitializeComponent();
_logger = logger;
_logicSushi = logicSushi;
_logicShop = logicShop;
}
private void FormSellSushi_Load(object sender, EventArgs e)
{
_logger.LogInformation("Загрузка списка суши для продажи");
try
{
var list = _logicSushi.ReadList(null);
if (list != null)
{
comboBoxSushi.DisplayMember = "SushiName";
comboBoxSushi.ValueMember = "Id";
comboBoxSushi.DataSource = list;
comboBoxSushi.SelectedItem = null;
}
}
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(textBoxCount.Text))
{
MessageBox.Show("Заполните поле 'Количество'", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxSushi.SelectedValue == null)
{
MessageBox.Show("Выберите суши", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Продажа суши");
try
{
var operationResult = _logicShop.SellSushi(_logicSushi.ReadElement(new SushiSearchModel()
{
Id = Convert.ToInt32(comboBoxSushi.SelectedValue)
})!, Convert.ToInt32(textBoxCount.Text));
if (!operationResult)
{
throw new Exception("Ошибка при продаже суши. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка продажи суши");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

212
SushiBar/SushiBar/FormShop.Designer.cs generated Normal file
View File

@ -0,0 +1,212 @@
namespace SushiBarView
{
partial class FormShop
{
/// <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.buttonSave = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.textBoxAddress = new System.Windows.Forms.TextBox();
this.labelTime = new System.Windows.Forms.Label();
this.labelAddress = new System.Windows.Forms.Label();
this.dataGridView = new System.Windows.Forms.DataGridView();
this.ColumnID = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnSushiName = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnCount = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.labelShop = new System.Windows.Forms.Label();
this.textBoxShop = new System.Windows.Forms.TextBox();
this.dateTimePicker = new System.Windows.Forms.DateTimePicker();
this.labelCount = new System.Windows.Forms.Label();
this.numericUpDownCount = new System.Windows.Forms.NumericUpDown();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownCount)).BeginInit();
this.SuspendLayout();
//
// buttonSave
//
this.buttonSave.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonSave.Location = new System.Drawing.Point(364, 303);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(120, 22);
this.buttonSave.TabIndex = 17;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.ButtonSave_Click);
//
// buttonCancel
//
this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonCancel.Location = new System.Drawing.Point(490, 302);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(103, 23);
this.buttonCancel.TabIndex = 16;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.ButtonCancel_Click);
//
// textBoxAddress
//
this.textBoxAddress.Location = new System.Drawing.Point(159, 27);
this.textBoxAddress.Name = "textBoxAddress";
this.textBoxAddress.Size = new System.Drawing.Size(141, 23);
this.textBoxAddress.TabIndex = 14;
//
// labelTime
//
this.labelTime.AutoSize = true;
this.labelTime.Location = new System.Drawing.Point(306, 9);
this.labelTime.Name = "labelTime";
this.labelTime.Size = new System.Drawing.Size(87, 15);
this.labelTime.TabIndex = 13;
this.labelTime.Text = "Дата открытия";
//
// labelAddress
//
this.labelAddress.AutoSize = true;
this.labelAddress.Location = new System.Drawing.Point(159, 9);
this.labelAddress.Name = "labelAddress";
this.labelAddress.Size = new System.Drawing.Size(40, 15);
this.labelAddress.TabIndex = 12;
this.labelAddress.Text = "Адрес";
//
// dataGridView
//
this.dataGridView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.ColumnID,
this.ColumnSushiName,
this.ColumnCount});
this.dataGridView.Location = new System.Drawing.Point(12, 56);
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowTemplate.Height = 25;
this.dataGridView.Size = new System.Drawing.Size(581, 240);
this.dataGridView.TabIndex = 11;
//
// ColumnID
//
this.ColumnID.HeaderText = "ID";
this.ColumnID.Name = "ColumnID";
this.ColumnID.Visible = false;
//
// ColumnSushiName
//
this.ColumnSushiName.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.ColumnSushiName.HeaderText = "Суши";
this.ColumnSushiName.Name = "ColumnSushiName";
//
// ColumnCount
//
this.ColumnCount.HeaderText = "Количество";
this.ColumnCount.Name = "ColumnCount";
//
// labelShop
//
this.labelShop.AutoSize = true;
this.labelShop.Location = new System.Drawing.Point(12, 9);
this.labelShop.Name = "labelShop";
this.labelShop.Size = new System.Drawing.Size(54, 15);
this.labelShop.TabIndex = 9;
this.labelShop.Text = "Магазин";
//
// textBoxShop
//
this.textBoxShop.Location = new System.Drawing.Point(12, 27);
this.textBoxShop.Name = "textBoxShop";
this.textBoxShop.Size = new System.Drawing.Size(141, 23);
this.textBoxShop.TabIndex = 18;
//
// dateTimePicker
//
this.dateTimePicker.Location = new System.Drawing.Point(306, 27);
this.dateTimePicker.Name = "dateTimePicker";
this.dateTimePicker.Size = new System.Drawing.Size(141, 23);
this.dateTimePicker.TabIndex = 19;
//
// labelCount
//
this.labelCount.AutoSize = true;
this.labelCount.Location = new System.Drawing.Point(453, 9);
this.labelCount.Name = "labelCount";
this.labelCount.Size = new System.Drawing.Size(134, 15);
this.labelCount.TabIndex = 20;
this.labelCount.Text = "Вместимость магазина";
//
// numericUpDownCount
//
this.numericUpDownCount.Location = new System.Drawing.Point(453, 27);
this.numericUpDownCount.Name = "numericUpDownCount";
this.numericUpDownCount.Size = new System.Drawing.Size(140, 23);
this.numericUpDownCount.TabIndex = 21;
//
// FormShop
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(605, 337);
this.Controls.Add(this.numericUpDownCount);
this.Controls.Add(this.labelCount);
this.Controls.Add(this.dateTimePicker);
this.Controls.Add(this.textBoxShop);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.textBoxAddress);
this.Controls.Add(this.labelTime);
this.Controls.Add(this.labelAddress);
this.Controls.Add(this.dataGridView);
this.Controls.Add(this.labelShop);
this.Name = "FormShop";
this.Text = "Магазин";
this.Load += new System.EventHandler(this.FormShop_Load);
this.Click += new System.EventHandler(this.FormShop_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownCount)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Button buttonSave;
private Button buttonCancel;
private TextBox textBoxAddress;
private Label labelTime;
private Label labelAddress;
private DataGridView dataGridView;
private Label labelShop;
private TextBox textBoxShop;
private DateTimePicker dateTimePicker;
private DataGridViewTextBoxColumn ColumnID;
private DataGridViewTextBoxColumn ColumnSushiName;
private DataGridViewTextBoxColumn ColumnCount;
private Label labelCount;
private NumericUpDown numericUpDownCount;
}
}

View File

@ -0,0 +1,122 @@
using Microsoft.Extensions.Logging;
using SushiBarContracts.BindingModels;
using SushiBarContracts.BusinessLogicsContracts;
using SushiBarContracts.SearchModels;
using SushiBarDataModels.Models;
namespace SushiBarView
{
public partial class FormShop : Form
{
private readonly ILogger _logger;
private readonly IShopLogic _logic;
private int? _id;
private Dictionary<int, (ISushiModel, int)> _shopListSushi;
public int Id { set { _id = value; } }
public FormShop(ILogger<FormShop> logger, IShopLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
_shopListSushi = new();
}
private void FormShop_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
_logger.LogInformation("Загрузка магазина");
try
{
var view = _logic.ReadElement(new ShopSearchModel
{
Id = _id.Value
});
if (view != null)
{
textBoxShop.Text = view.ShopName;
textBoxAddress.Text = view.Address;
dateTimePicker.Text = view.DateOpening.ToString();
numericUpDownCount.Value = view.MaxCountSushi;
_shopListSushi = view.ListSushi ?? new Dictionary<int, (ISushiModel, int)>();
LoadData();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки магазина");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void LoadData()
{
_logger.LogInformation("Загрузка суши магазина");
try
{
if (_shopListSushi != null)
{
dataGridView.Rows.Clear();
foreach (var elem in _shopListSushi)
{
dataGridView.Rows.Add(new object[] { elem.Key, elem.Value.Item1.SushiName, elem.Value.Item2 });
}
}
}
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(textBoxShop.Text))
{
MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxAddress.Text))
{
MessageBox.Show("Заполните адрес", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение магазина");
try
{
var model = new ShopBindingModel
{
Id = _id ?? 0,
ShopName = textBoxShop.Text,
Address = textBoxAddress.Text,
DateOpening = dateTimePicker.Value.Date,
MaxCountSushi = (int)numericUpDownCount.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,69 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="ColumnID.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnSushiName.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnCount.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root>

View File

@ -0,0 +1,151 @@
namespace SushiBarView
{
partial class FormShopSushi
{
/// <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.numericUpDownCount = new System.Windows.Forms.NumericUpDown();
this.comboBoxSushi = new System.Windows.Forms.ComboBox();
this.labelCount = new System.Windows.Forms.Label();
this.labelSushi = new System.Windows.Forms.Label();
this.comboBoxShop = new System.Windows.Forms.ComboBox();
this.labelShop = new System.Windows.Forms.Label();
this.buttonCancel = new System.Windows.Forms.Button();
this.buttonSave = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownCount)).BeginInit();
this.SuspendLayout();
//
// numericUpDownCount
//
this.numericUpDownCount.Location = new System.Drawing.Point(87, 62);
this.numericUpDownCount.Maximum = new decimal(new int[] {
1410065408,
2,
0,
0});
this.numericUpDownCount.Name = "numericUpDownCount";
this.numericUpDownCount.Size = new System.Drawing.Size(344, 23);
this.numericUpDownCount.TabIndex = 13;
//
// comboBoxSushi
//
this.comboBoxSushi.FormattingEnabled = true;
this.comboBoxSushi.Location = new System.Drawing.Point(86, 35);
this.comboBoxSushi.Name = "comboBoxSushi";
this.comboBoxSushi.Size = new System.Drawing.Size(345, 23);
this.comboBoxSushi.TabIndex = 12;
//
// labelCount
//
this.labelCount.AutoSize = true;
this.labelCount.Location = new System.Drawing.Point(9, 64);
this.labelCount.Name = "labelCount";
this.labelCount.Size = new System.Drawing.Size(72, 15);
this.labelCount.TabIndex = 11;
this.labelCount.Text = "Количество";
//
// labelSushi
//
this.labelSushi.AutoSize = true;
this.labelSushi.Location = new System.Drawing.Point(41, 38);
this.labelSushi.Name = "labelSushi";
this.labelSushi.Size = new System.Drawing.Size(39, 15);
this.labelSushi.TabIndex = 10;
this.labelSushi.Text = "Суши";
//
// comboBoxShop
//
this.comboBoxShop.FormattingEnabled = true;
this.comboBoxShop.Location = new System.Drawing.Point(86, 8);
this.comboBoxShop.Name = "comboBoxShop";
this.comboBoxShop.Size = new System.Drawing.Size(345, 23);
this.comboBoxShop.TabIndex = 9;
//
// labelShop
//
this.labelShop.AutoSize = true;
this.labelShop.Location = new System.Drawing.Point(26, 11);
this.labelShop.Name = "labelShop";
this.labelShop.Size = new System.Drawing.Size(54, 15);
this.labelShop.TabIndex = 8;
this.labelShop.Text = "Магазин";
//
// buttonCancel
//
this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonCancel.Location = new System.Drawing.Point(356, 94);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(75, 23);
this.buttonCancel.TabIndex = 15;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.ButtonCancel_Click);
//
// buttonSave
//
this.buttonSave.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonSave.Location = new System.Drawing.Point(275, 94);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(75, 23);
this.buttonSave.TabIndex = 14;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.ButtonSave_Click);
//
// FormShopSushi
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(443, 129);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.numericUpDownCount);
this.Controls.Add(this.comboBoxSushi);
this.Controls.Add(this.labelCount);
this.Controls.Add(this.labelSushi);
this.Controls.Add(this.comboBoxShop);
this.Controls.Add(this.labelShop);
this.Name = "FormShopSushi";
this.Text = "Поступление суши в суши-бар";
((System.ComponentModel.ISupportInitialize)(this.numericUpDownCount)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private NumericUpDown numericUpDownCount;
private ComboBox comboBoxSushi;
private Label labelCount;
private Label labelSushi;
private ComboBox comboBoxShop;
private Label labelShop;
private Button buttonCancel;
private Button buttonSave;
}
}

View File

@ -0,0 +1,90 @@
using Microsoft.Extensions.Logging;
using SushiBarContracts.BusinessLogicsContracts;
using SushiBarContracts.ViewModels;
namespace SushiBarView
{
public partial class FormShopSushi : Form
{
private readonly ILogger _logger;
private readonly IShopLogic _shopLogic;
private readonly ISushiLogic _sushiLogic;
private readonly List<ShopViewModel>? _listShops;
private readonly List<SushiViewModel>? _listSushi;
public FormShopSushi(ILogger<FormShopSushi> logger, IShopLogic shopLogic, ISushiLogic sushiLogic)
{
InitializeComponent();
_shopLogic = shopLogic;
_sushiLogic = sushiLogic;
_logger = logger;
_listShops = shopLogic.ReadList(null);
if (_listShops != null)
{
comboBoxShop.DisplayMember = "ShopName";
comboBoxShop.ValueMember = "Id";
comboBoxShop.DataSource = _listShops;
comboBoxShop.SelectedItem = null;
}
_listSushi = sushiLogic.ReadList(null);
if (_listSushi != null)
{
comboBoxSushi.DisplayMember = "SushiName";
comboBoxSushi.ValueMember = "Id";
comboBoxSushi.DataSource = _listSushi;
comboBoxSushi.SelectedItem = null;
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (comboBoxShop.SelectedValue == null)
{
MessageBox.Show("Выберите магазин", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxSushi.SelectedValue == null)
{
MessageBox.Show("Выберите суши", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Добавление суши в магазин");
try
{
var sushi = _sushiLogic.ReadElement(new()
{
Id = (int)comboBoxSushi.SelectedValue
});
if (sushi == null)
{
throw new Exception("Не найдено суши. Дополнительная информация в логах.");
}
var resultOperation = _shopLogic.AddSushiInShop(
model: new() { Id = (int)comboBoxShop.SelectedValue },
sushi: sushi,
count: (int)numericUpDownCount.Value
);
if (!resultOperation)
{
throw new Exception("Ошибка при добавлении. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение",
MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения суши");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

122
SushiBar/SushiBar/FormShops.Designer.cs generated Normal file
View File

@ -0,0 +1,122 @@
namespace SushiBarView
{
partial class FormShops
{
/// <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.dataGridView = new System.Windows.Forms.DataGridView();
this.buttonUpdate = new System.Windows.Forms.Button();
this.buttonDelete = new System.Windows.Forms.Button();
this.buttonEdit = new System.Windows.Forms.Button();
this.buttonAdd = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
//
// dataGridView
//
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Dock = System.Windows.Forms.DockStyle.Left;
this.dataGridView.GridColor = System.Drawing.Color.White;
this.dataGridView.Location = new System.Drawing.Point(0, 0);
this.dataGridView.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowHeadersWidth = 51;
this.dataGridView.RowTemplate.Height = 29;
this.dataGridView.Size = new System.Drawing.Size(426, 333);
this.dataGridView.TabIndex = 10;
//
// buttonUpdate
//
this.buttonUpdate.Location = new System.Drawing.Point(432, 175);
this.buttonUpdate.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonUpdate.Name = "buttonUpdate";
this.buttonUpdate.Size = new System.Drawing.Size(130, 22);
this.buttonUpdate.TabIndex = 14;
this.buttonUpdate.Text = "Обновить";
this.buttonUpdate.UseVisualStyleBackColor = true;
this.buttonUpdate.Click += new System.EventHandler(this.ButtonRef_Click);
//
// buttonDelete
//
this.buttonDelete.Location = new System.Drawing.Point(432, 149);
this.buttonDelete.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonDelete.Name = "buttonDelete";
this.buttonDelete.Size = new System.Drawing.Size(130, 22);
this.buttonDelete.TabIndex = 13;
this.buttonDelete.Text = "Удалить";
this.buttonDelete.UseVisualStyleBackColor = true;
this.buttonDelete.Click += new System.EventHandler(this.ButtonDel_Click);
//
// buttonEdit
//
this.buttonEdit.Location = new System.Drawing.Point(432, 123);
this.buttonEdit.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonEdit.Name = "buttonEdit";
this.buttonEdit.Size = new System.Drawing.Size(130, 22);
this.buttonEdit.TabIndex = 12;
this.buttonEdit.Text = "Изменить";
this.buttonEdit.UseVisualStyleBackColor = true;
this.buttonEdit.Click += new System.EventHandler(this.ButtonUpd_Click);
//
// buttonAdd
//
this.buttonAdd.Location = new System.Drawing.Point(432, 97);
this.buttonAdd.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(130, 22);
this.buttonAdd.TabIndex = 11;
this.buttonAdd.Text = "Добавить";
this.buttonAdd.UseVisualStyleBackColor = true;
this.buttonAdd.Click += new System.EventHandler(this.ButtonAdd_Click);
//
// FormShops
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(566, 333);
this.Controls.Add(this.dataGridView);
this.Controls.Add(this.buttonUpdate);
this.Controls.Add(this.buttonDelete);
this.Controls.Add(this.buttonEdit);
this.Controls.Add(this.buttonAdd);
this.Name = "FormShops";
this.Text = "Магазины";
this.Load += new System.EventHandler(this.FormShops_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
private Button buttonUpdate;
private Button buttonDelete;
private Button buttonEdit;
private Button buttonAdd;
}
}

View File

@ -0,0 +1,102 @@
using Microsoft.Extensions.Logging;
using SushiBarContracts.BindingModels;
using SushiBarContracts.BusinessLogicsContracts;
namespace SushiBarView
{
public partial class FormShops : Form
{
private readonly ILogger _logger;
private readonly IShopLogic _logic;
public FormShops(ILogger<FormShops> logger, IShopLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormShops_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["ListSushi"].Visible = false;
dataGridView.Columns["ShopName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка магазинов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки магазинов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShop));
if (service is FormShop 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(FormShop));
if (service is FormShop 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 ShopBindingModel
{
Id = id
}))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления магазина");
MessageBox.Show(ex.Message, "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void ButtonRef_Click(object sender, EventArgs e)
{
LoadData();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

246
SushiBar/SushiBar/FormSushi.Designer.cs generated Normal file
View File

@ -0,0 +1,246 @@
namespace SushiBarView
{
partial class FormSushi
{
/// <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.textBoxPrice = new System.Windows.Forms.TextBox();
this.textBoxName = new System.Windows.Forms.TextBox();
this.labelPrice = new System.Windows.Forms.Label();
this.labelName = new System.Windows.Forms.Label();
this.groupBoxIngredients = new System.Windows.Forms.GroupBox();
this.buttonCancel = new System.Windows.Forms.Button();
this.buttonSave = new System.Windows.Forms.Button();
this.buttonUpdate = new System.Windows.Forms.Button();
this.buttonDelete = new System.Windows.Forms.Button();
this.buttonEdit = new System.Windows.Forms.Button();
this.buttonAdd = new System.Windows.Forms.Button();
this.dataGridView = new System.Windows.Forms.DataGridView();
this.ID = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnIngredientName = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnCount = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.groupBoxIngredients.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
//
// textBoxPrice
//
this.textBoxPrice.Location = new System.Drawing.Point(90, 36);
this.textBoxPrice.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.textBoxPrice.Name = "textBoxPrice";
this.textBoxPrice.Size = new System.Drawing.Size(138, 23);
this.textBoxPrice.TabIndex = 7;
//
// textBoxName
//
this.textBoxName.Location = new System.Drawing.Point(90, 11);
this.textBoxName.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.textBoxName.Name = "textBoxName";
this.textBoxName.Size = new System.Drawing.Size(276, 23);
this.textBoxName.TabIndex = 6;
//
// labelPrice
//
this.labelPrice.AutoSize = true;
this.labelPrice.Location = new System.Drawing.Point(14, 41);
this.labelPrice.Name = "labelPrice";
this.labelPrice.Size = new System.Drawing.Size(70, 15);
this.labelPrice.TabIndex = 5;
this.labelPrice.Text = "Стоимость:";
//
// labelName
//
this.labelName.AutoSize = true;
this.labelName.Location = new System.Drawing.Point(14, 14);
this.labelName.Name = "labelName";
this.labelName.Size = new System.Drawing.Size(62, 15);
this.labelName.TabIndex = 4;
this.labelName.Text = "Название:";
//
// groupBoxIngredients
//
this.groupBoxIngredients.Controls.Add(this.buttonCancel);
this.groupBoxIngredients.Controls.Add(this.buttonSave);
this.groupBoxIngredients.Controls.Add(this.buttonUpdate);
this.groupBoxIngredients.Controls.Add(this.buttonDelete);
this.groupBoxIngredients.Controls.Add(this.buttonEdit);
this.groupBoxIngredients.Controls.Add(this.buttonAdd);
this.groupBoxIngredients.Controls.Add(this.dataGridView);
this.groupBoxIngredients.Dock = System.Windows.Forms.DockStyle.Bottom;
this.groupBoxIngredients.Location = new System.Drawing.Point(0, 70);
this.groupBoxIngredients.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.groupBoxIngredients.Name = "groupBoxIngredients";
this.groupBoxIngredients.Padding = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.groupBoxIngredients.Size = new System.Drawing.Size(592, 206);
this.groupBoxIngredients.TabIndex = 8;
this.groupBoxIngredients.TabStop = false;
this.groupBoxIngredients.Text = "Компоненты";
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(504, 176);
this.buttonCancel.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(79, 22);
this.buttonCancel.TabIndex = 6;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.ButtonCancel_Click);
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(504, 150);
this.buttonSave.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(79, 22);
this.buttonSave.TabIndex = 5;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.ButtonSave_Click);
//
// buttonUpdate
//
this.buttonUpdate.Location = new System.Drawing.Point(504, 98);
this.buttonUpdate.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonUpdate.Name = "buttonUpdate";
this.buttonUpdate.Size = new System.Drawing.Size(79, 22);
this.buttonUpdate.TabIndex = 4;
this.buttonUpdate.Text = "Обновить";
this.buttonUpdate.UseVisualStyleBackColor = true;
this.buttonUpdate.Click += new System.EventHandler(this.ButtonRef_Click);
//
// buttonDelete
//
this.buttonDelete.Location = new System.Drawing.Point(504, 72);
this.buttonDelete.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonDelete.Name = "buttonDelete";
this.buttonDelete.Size = new System.Drawing.Size(79, 22);
this.buttonDelete.TabIndex = 3;
this.buttonDelete.Text = "Удалить";
this.buttonDelete.UseVisualStyleBackColor = true;
this.buttonDelete.Click += new System.EventHandler(this.ButtonDel_Click);
//
// buttonEdit
//
this.buttonEdit.Location = new System.Drawing.Point(504, 46);
this.buttonEdit.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonEdit.Name = "buttonEdit";
this.buttonEdit.Size = new System.Drawing.Size(79, 22);
this.buttonEdit.TabIndex = 2;
this.buttonEdit.Text = "Изменить";
this.buttonEdit.UseVisualStyleBackColor = true;
this.buttonEdit.Click += new System.EventHandler(this.ButtonUpd_Click);
//
// buttonAdd
//
this.buttonAdd.Location = new System.Drawing.Point(504, 20);
this.buttonAdd.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(79, 22);
this.buttonAdd.TabIndex = 1;
this.buttonAdd.Text = "Добавить";
this.buttonAdd.UseVisualStyleBackColor = true;
this.buttonAdd.Click += new System.EventHandler(this.ButtonAdd_Click);
//
// dataGridView
//
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.ID,
this.ColumnIngredientName,
this.ColumnCount});
this.dataGridView.Location = new System.Drawing.Point(5, 20);
this.dataGridView.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowHeadersWidth = 51;
this.dataGridView.RowTemplate.Height = 29;
this.dataGridView.Size = new System.Drawing.Size(493, 182);
this.dataGridView.TabIndex = 0;
//
// ID
//
this.ID.HeaderText = "ID";
this.ID.MinimumWidth = 6;
this.ID.Name = "ID";
this.ID.Visible = false;
this.ID.Width = 125;
//
// ColumnIngredientName
//
this.ColumnIngredientName.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None;
this.ColumnIngredientName.HeaderText = "Ингредиент";
this.ColumnIngredientName.MinimumWidth = 6;
this.ColumnIngredientName.Name = "ColumnIngredientName";
this.ColumnIngredientName.Resizable = System.Windows.Forms.DataGridViewTriState.True;
this.ColumnIngredientName.Width = 312;
//
// ColumnCount
//
this.ColumnCount.HeaderText = "Количество";
this.ColumnCount.MinimumWidth = 6;
this.ColumnCount.Name = "ColumnCount";
this.ColumnCount.Width = 125;
//
// FormSushi
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(592, 276);
this.Controls.Add(this.groupBoxIngredients);
this.Controls.Add(this.textBoxPrice);
this.Controls.Add(this.textBoxName);
this.Controls.Add(this.labelPrice);
this.Controls.Add(this.labelName);
this.Name = "FormSushi";
this.Text = "Суши";
this.Load += new System.EventHandler(this.FormSushi_Load);
this.groupBoxIngredients.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private TextBox textBoxPrice;
private TextBox textBoxName;
private Label labelPrice;
private Label labelName;
private GroupBox groupBoxIngredients;
private Button buttonUpdate;
private Button buttonDelete;
private Button buttonEdit;
private Button buttonAdd;
private DataGridView dataGridView;
private Button buttonCancel;
private Button buttonSave;
private DataGridViewTextBoxColumn ID;
private DataGridViewTextBoxColumn ColumnIngredientName;
private DataGridViewTextBoxColumn ColumnCount;
}
}

View File

@ -0,0 +1,198 @@
using Microsoft.Extensions.Logging;
using SushiBarContracts.BindingModels;
using SushiBarContracts.BusinessLogicsContracts;
using SushiBarContracts.SearchModels;
using SushiBarDataModels.Models;
namespace SushiBarView
{
public partial class FormSushi : Form
{
private readonly ILogger _logger;
private readonly ISushiLogic _logic;
private int? _id;
private Dictionary<int, (IIngredientModel, int)> _sushiIngredients;
public int Id { set { _id = value; } }
public FormSushi(ILogger<FormSushi> logger, ISushiLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
_sushiIngredients = new Dictionary<int, (IIngredientModel, int)>();
}
private void FormSushi_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
_logger.LogInformation("Загрузка суши");
try
{
var view = _logic.ReadElement(new SushiSearchModel
{
Id = _id.Value
});
if (view != null)
{
textBoxName.Text = view.SushiName;
textBoxPrice.Text = view.Price.ToString();
_sushiIngredients = view.SushiIngredients ?? new Dictionary<int, (IIngredientModel, int)>();
LoadData();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки суши");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void LoadData()
{
_logger.LogInformation("Загрузка ингредиентов суши");
try
{
if (_sushiIngredients != null)
{
dataGridView.Rows.Clear();
foreach (var sc in _sushiIngredients)
{
dataGridView.Rows.Add(new object[] { sc.Key, sc.Value.Item1.IngredientName, sc.Value.Item2 });
}
textBoxPrice.Text = CalcPrice().ToString();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки ингредиентов суши");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSushiIngredients));
if (service is FormSushiIngredients form)
{
if (form.ShowDialog() == DialogResult.OK)
{
if (form.IngredientModel == null)
{
return;
}
_logger.LogInformation("Добавление нового ингредиента: { IngredientName} - { Count}", form.IngredientModel.IngredientName, form.Count);
if (_sushiIngredients.ContainsKey(form.Id))
{
_sushiIngredients[form.Id] = (form.IngredientModel, form.Count);
}
else
{
_sushiIngredients.Add(form.Id, (form.IngredientModel, form.Count));
}
LoadData();
}
}
}
private void ButtonUpd_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSushiIngredients));
if (service is FormSushiIngredients form)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value);
form.Id = id;
form.Count = _sushiIngredients[id].Item2;
if (form.ShowDialog() == DialogResult.OK)
{
if (form.IngredientModel == null)
{
return;
}
_logger.LogInformation("Изменение ингредиента: { IngredientName} - { Count} ", form.IngredientModel.IngredientName, form.Count);
_sushiIngredients[form.Id] = (form.IngredientModel, form.Count);
LoadData();
}
}
}
}
private void ButtonDel_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
try
{
_logger.LogInformation("Удаление ингредиента: { IngredientName} - { Count} ",
dataGridView.SelectedRows[0].Cells[1].Value); _sushiIngredients?.Remove(Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
LoadData();
}
}
}
private void ButtonRef_Click(object sender, EventArgs e)
{
LoadData();
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxName.Text))
{
MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxPrice.Text))
{
MessageBox.Show("Заполните цену", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (_sushiIngredients == null || _sushiIngredients.Count == 0)
{
MessageBox.Show("Заполните ингредиенты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение суши");
try
{
var model = new SushiBindingModel
{
Id = _id ?? 0,
SushiName = textBoxName.Text,
Price = Convert.ToDouble(textBoxPrice.Text),
SushiIngredients = _sushiIngredients
};
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();
}
private double CalcPrice()
{
double price = 0;
foreach (var elem in _sushiIngredients)
{
price += ((elem.Value.Item1?.Cost ?? 0) * elem.Value.Item2);
}
return Math.Round(price * 1.1, 2);
}
}
}

View File

@ -0,0 +1,69 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="ID.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnIngredientName.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnCount.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root>

View File

@ -0,0 +1,123 @@
namespace SushiBarView
{
partial class FormSushiIngredients
{
/// <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.buttonCancel = new System.Windows.Forms.Button();
this.buttonSave = new System.Windows.Forms.Button();
this.textBoxCount = new System.Windows.Forms.TextBox();
this.comboBoxIngredient = new System.Windows.Forms.ComboBox();
this.labelCount = new System.Windows.Forms.Label();
this.labelIngredient = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(319, 80);
this.buttonCancel.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(80, 22);
this.buttonCancel.TabIndex = 11;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.ButtonCancel_Click);
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(233, 80);
this.buttonSave.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(80, 22);
this.buttonSave.TabIndex = 10;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.ButtonSave_Click);
//
// textBoxCount
//
this.textBoxCount.Location = new System.Drawing.Point(116, 43);
this.textBoxCount.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.textBoxCount.Name = "textBoxCount";
this.textBoxCount.Size = new System.Drawing.Size(283, 23);
this.textBoxCount.TabIndex = 9;
//
// comboBoxIngredient
//
this.comboBoxIngredient.FormattingEnabled = true;
this.comboBoxIngredient.Location = new System.Drawing.Point(116, 11);
this.comboBoxIngredient.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.comboBoxIngredient.Name = "comboBoxIngredient";
this.comboBoxIngredient.Size = new System.Drawing.Size(282, 23);
this.comboBoxIngredient.TabIndex = 8;
//
// labelCount
//
this.labelCount.AutoSize = true;
this.labelCount.Location = new System.Drawing.Point(10, 46);
this.labelCount.Name = "labelCount";
this.labelCount.Size = new System.Drawing.Size(75, 15);
this.labelCount.TabIndex = 7;
this.labelCount.Text = "Количество:";
//
// labelIngredient
//
this.labelIngredient.AutoSize = true;
this.labelIngredient.Location = new System.Drawing.Point(10, 14);
this.labelIngredient.Name = "labelIngredient";
this.labelIngredient.Size = new System.Drawing.Size(75, 15);
this.labelIngredient.TabIndex = 6;
this.labelIngredient.Text = "Ингредиент:";
//
// FormSushiIngredients
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(410, 115);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.textBoxCount);
this.Controls.Add(this.comboBoxIngredient);
this.Controls.Add(this.labelCount);
this.Controls.Add(this.labelIngredient);
this.Name = "FormSushiIngredients";
this.Text = "Ингредиент суши";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Button buttonCancel;
private Button buttonSave;
private TextBox textBoxCount;
private ComboBox comboBoxIngredient;
private Label labelCount;
private Label labelIngredient;
}
}

View File

@ -0,0 +1,79 @@
using SushiBarContracts.BusinessLogicsContracts;
using SushiBarContracts.ViewModels;
using SushiBarDataModels.Models;
namespace SushiBarView
{
public partial class FormSushiIngredients : Form
{
private readonly List<IngredientViewModel>? _list;
public int Id
{
get
{
return Convert.ToInt32(comboBoxIngredient.SelectedValue);
}
set
{
comboBoxIngredient.SelectedValue = value;
}
}
public IIngredientModel? IngredientModel
{
get
{
if (_list == null)
{
return null;
}
foreach (var elem in _list)
{
if (elem.Id == Id)
{
return elem;
}
}
return null;
}
}
public int Count
{
get { return Convert.ToInt32(textBoxCount.Text); }
set { textBoxCount.Text = value.ToString(); }
}
public FormSushiIngredients(IIngredientLogic logic)
{
InitializeComponent();
_list = logic.ReadList(null);
if (_list != null)
{
comboBoxIngredient.DisplayMember = "IngredientName";
comboBoxIngredient.ValueMember = "Id";
comboBoxIngredient.DataSource = _list;
comboBoxIngredient.SelectedItem = null;
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCount.Text))
{
MessageBox.Show("Заполните поле 'Количество'", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxIngredient.SelectedValue == null)
{
MessageBox.Show("Выберите ингредиент", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
DialogResult = DialogResult.OK;
Close();
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -1,7 +1,17 @@
namespace SushiBar
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using SushiBarBusinessLogic.BusinessLogics;
using SushiBarContracts.BusinessLogicsContracts;
using SushiBarContracts.StoragesContracts;
using SushiBarDatabaseImplement.Implements;
namespace SushiBarView
{
internal static class Program
{
private static ServiceProvider? _serviceProvider;
public static ServiceProvider? ServiceProvider => _serviceProvider;
/// <summary>
/// The main entry point for the application.
/// </summary>
@ -11,7 +21,41 @@ namespace SushiBar
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
}
var services = new ServiceCollection();
ConfigureServices(services);
_serviceProvider = services.BuildServiceProvider();
Application.Run(_serviceProvider.GetRequiredService<FormMain>());
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
services.AddTransient<IIngredientStorage, IngredientStorage>();
services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<ISushiStorage, SushiStorage>();
services.AddTransient<IShopStorage, ShopStorage>();
services.AddTransient<IIngredientLogic, IngredientLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<ISushiLogic, SushiLogic>();
services.AddTransient<IShopLogic, ShopLogic>();
services.AddTransient<FormMain>();
services.AddTransient<FormIngredient>();
services.AddTransient<FormIngredients>();
services.AddTransient<FormCreateOrder>();
services.AddTransient<FormSushi>();
services.AddTransient<FormSushiIngredients>();
services.AddTransient<FormListSushi>();
services.AddTransient<FormShopSushi>();
services.AddTransient<FormShops>();
services.AddTransient<FormShop>();
services.AddTransient<FormSellSushi>();
}
}
}

View File

@ -1,11 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,32 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.2.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SushiBarBusinessLogic\SushiBarBusinessLogic.csproj" />
<ProjectReference Include="..\SushiBarContracts\SushiBarContracts.csproj" />
<ProjectReference Include="..\SushiBarDatabaseImplement\SushiBarDatabaseImplement.csproj" />
<ProjectReference Include="..\SushiBarFileImplement\SushiBarFileImplement.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,112 @@
using Microsoft.Extensions.Logging;
using SushiBarContracts.BindingModels;
using SushiBarContracts.BusinessLogicsContracts;
using SushiBarContracts.SearchModels;
using SushiBarContracts.StoragesContracts;
using SushiBarContracts.ViewModels;
namespace SushiBarBusinessLogic.BusinessLogics
{
public class IngredientLogic : IIngredientLogic
{
private readonly ILogger _logger;
private readonly IIngredientStorage _componentStorage;
public IngredientLogic(ILogger<IngredientLogic> logger, IIngredientStorage componentStorage)
{
_logger = logger;
_componentStorage = componentStorage;
}
public List<IngredientViewModel>? ReadList(IngredientSearchModel? model)
{
_logger.LogInformation("ReadList. IngredientName: {IngredientName}. Id: {Id}",
model?.IngredientName, model?.Id);
var list = model == null ? _componentStorage.GetFullList() :
_componentStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count: {Count}", list.Count);
return list;
}
public IngredientViewModel? ReadElement(IngredientSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. IngredientName: {IngredientName}. Id: {Id}",
model.IngredientName, model.Id);
var element = _componentStorage.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(IngredientBindingModel model)
{
CheckModel(model);
if (_componentStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Update(IngredientBindingModel model)
{
CheckModel(model);
if (_componentStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool Delete(IngredientBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id: {Id}", model.Id);
if (_componentStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
private void CheckModel(IngredientBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.IngredientName))
{
throw new ArgumentNullException("Нет названия ингредиента", nameof(model.IngredientName));
}
if (model.Cost <= 0)
{
throw new ArgumentNullException("Цена ингредиента должна быть больше 0",
nameof(model.Cost));
}
_logger.LogInformation("Ingredient. IngredientName: {IngredientName}. Cost: {Cost}. Id: {Id}",
model.IngredientName, model.Cost, model.Id);
var element = _componentStorage.GetElement(new IngredientSearchModel
{
IngredientName = model.IngredientName
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Ингридиент с таким названием уже есть");
}
}
}
}

View File

@ -0,0 +1,135 @@
using Microsoft.Extensions.Logging;
using SushiBarContracts.BindingModels;
using SushiBarContracts.BusinessLogicsContracts;
using SushiBarContracts.SearchModels;
using SushiBarContracts.StoragesContracts;
using SushiBarContracts.ViewModels;
using SushiBarDataModels.Enums;
namespace SushiBarBusinessLogic.BusinessLogics
{
public class OrderLogic : IOrderLogic
{
private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage;
private readonly IShopLogic _shopLogic;
private readonly ISushiStorage _sushiStorage;
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage, IShopLogic shopLogic, ISushiStorage sushiStorage)
{
_logger = logger;
_orderStorage = orderStorage;
_shopLogic = shopLogic;
_sushiStorage = sushiStorage;
}
public List<OrderViewModel>? ReadList(OrderSearchModel? model)
{
_logger.LogInformation("Order. OrderID:{Id}", model?.Id);
var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public bool CreateOrder(OrderBindingModel model)
{
CheckModel(model);
if (model.Status != OrderStatus.Неизвестен)
{
_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;
}
private void CheckModel(OrderBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (model.SushiId < 0)
{
throw new ArgumentNullException("Некорректный идентификатор у суши", nameof(model.SushiId));
}
if (model.Count <= 0)
{
throw new ArgumentNullException("Количество суши в заказе должно быть больше 0", nameof(model.Count));
}
if (model.Sum <= 0)
{
throw new ArgumentNullException("Сумма заказа должна быть больше 0", nameof(model.Sum));
}
_logger.LogInformation("Order. OrderID:{Id}. Sum:{ Sum}. SushiId: { SushiId}", model.Id, model.Sum, model.SushiId);
}
public bool StatusUpdate(OrderBindingModel model, OrderStatus newStatus)
{
var viewModel = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id });
if (viewModel == null)
{
throw new ArgumentNullException(nameof(model));
}
if (viewModel.Status + 1 != newStatus)
{
_logger.LogWarning("Status update to " + newStatus.ToString() + " operation failed. Order status incorrect.");
return false;
}
model.Status = newStatus;
if (model.Status == OrderStatus.Готов)
{
model.DateImplement = DateTime.Now;
var sushi = _sushiStorage.GetElement(new() { Id = viewModel.SushiId });
if (sushi == null)
{
throw new ArgumentNullException(nameof(sushi));
}
if (!_shopLogic.AddSushi(sushi, viewModel.Count))
{
throw new Exception($"AddSushi operation failed. Shop is full.");
}
}
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.Готов);
}
}
}

View File

@ -0,0 +1,216 @@
using Microsoft.Extensions.Logging;
using SushiBarContracts.BindingModels;
using SushiBarContracts.BusinessLogicsContracts;
using SushiBarContracts.SearchModels;
using SushiBarContracts.StoragesContracts;
using SushiBarContracts.ViewModels;
using SushiBarDataModels.Models;
namespace SushiBarBusinessLogic.BusinessLogics
{
public class ShopLogic : IShopLogic
{
private readonly ILogger _logger;
private readonly IShopStorage _shopStorage;
public ShopLogic(ILogger<ShopLogic> logger, IShopStorage shopStorage)
{
_logger = logger;
_shopStorage = shopStorage;
}
public List<ShopViewModel>? ReadList(ShopSearchModel? model)
{
_logger.LogInformation("ReadList. ShopName: {ShopName}. Id: {Id}",
model?.ShopName, model?.Id);
var list = model == null ? _shopStorage.GetFullList() :
_shopStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count: {Count}", list.Count);
return list;
}
public ShopViewModel? ReadElement(ShopSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. ShopName: {ShopName}. Id: {Id}",
model.ShopName, model.Id);
var element = _shopStorage.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(ShopBindingModel model)
{
CheckModel(model);
if (_shopStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Update(ShopBindingModel model)
{
CheckModel(model);
if (_shopStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool Delete(ShopBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id: {Id}", model.Id);
if (_shopStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
private void CheckModel(ShopBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.ShopName))
{
throw new ArgumentNullException("Нет названия магазина", nameof(model.ShopName));
}
if (model.MaxCountSushi < 0)
{
throw new ArgumentException(
"Максимальное количество суши в магазине не может быть меньше нуля",
nameof(model.MaxCountSushi));
}
_logger.LogInformation("Shop. ShopName:{0}.Address:{1}. Id: {2}",
model.ShopName, model.Address, model.Id);
var element = _shopStorage.GetElement(new ShopSearchModel
{
ShopName = model.ShopName
});
if (element != null && element.Id != model.Id && element.ShopName == model.ShopName)
{
throw new InvalidOperationException("Магазин с таким названием уже есть");
}
}
public bool AddSushiInShop(ShopSearchModel model, ISushiModel sushi, int count)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (count <= 0)
{
throw new ArgumentException("Количество суши должно быть больше 0", nameof(count));
}
_logger.LogInformation("AddSushiInShop. ShopName:{ShopName}.Id:{ Id}",
model.ShopName, model.Id);
var element = _shopStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("AddSushiInShop element not found");
return false;
}
if (element.MaxCountSushi -
element.ListSushi.Select(x => x.Value.Item2).Sum() < count)
{
throw new ArgumentNullException("Магазин переполнен", nameof(count));
}
_logger.LogInformation("AddSushiInShop find. Id:{Id}", element.Id);
if (element.ListSushi.TryGetValue(sushi.Id, out var pair))
{
element.ListSushi[sushi.Id] = (sushi, count + pair.Item2);
_logger.LogInformation(
"AddSushiInShop. Added {count} {sushi} to '{ShopName}' shop",
count, sushi.SushiName, element.ShopName);
}
else
{
element.ListSushi[sushi.Id] = (sushi, count);
_logger.LogInformation(
"AddSushiInShop. Added {count} new sushi {sushi} to '{ShopName}' shop",
count, sushi.SushiName, element.ShopName);
}
_shopStorage.Update(new() {
Id = element.Id,
Address = element.Address,
ShopName = element.ShopName,
DateOpening = element.DateOpening,
MaxCountSushi = element.MaxCountSushi,
ListSushi = element.ListSushi,
});
return true;
}
public bool AddSushi(ISushiModel model, int count)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (count <= 0)
{
throw new ArgumentException("Количество суши должно быть больше 0", nameof(count));
}
var freeCount = _shopStorage.GetFullList()
.Select(x => x.MaxCountSushi - x.ListSushi
.Select(p => p.Value.Item2).Sum()).Sum() - count;
if (freeCount < 0)
{
_logger.LogInformation("AddSushi. Не удалось добавить изделия в магазины, они переполнены.");
return false;
}
foreach (var shop in _shopStorage.GetFullList())
{
int countFree = shop.MaxCountSushi - shop.ListSushi.Select(x => x.Value.Item2).Sum();
if (countFree < count)
{
if (!AddSushiInShop(new() { Id = shop.Id }, model, countFree))
{
_logger.LogWarning("AddSushiInShop operation failed.");
return false;
}
count -= countFree;
}
else
{
if (!AddSushiInShop(new() { Id = shop.Id }, model, count))
{
_logger.LogWarning("AddSushiInShop operation failed.");
return false;
}
count = 0;
}
if (count == 0)
{
return true;
}
}
return false;
}
public bool SellSushi(ISushiModel model, int count)
{
return _shopStorage.SellSushi(model, count);
}
}
}

View File

@ -0,0 +1,112 @@
using Microsoft.Extensions.Logging;
using SushiBarContracts.BindingModels;
using SushiBarContracts.BusinessLogicsContracts;
using SushiBarContracts.SearchModels;
using SushiBarContracts.StoragesContracts;
using SushiBarContracts.ViewModels;
namespace SushiBarBusinessLogic.BusinessLogics
{
public class SushiLogic : ISushiLogic
{
private readonly ILogger _logger;
private readonly ISushiStorage _sushiStorage;
public SushiLogic(ILogger<SushiLogic> logger, ISushiStorage sushiStorage)
{
_logger = logger;
_sushiStorage = sushiStorage;
}
public List<SushiViewModel>? ReadList(SushiSearchModel? model)
{
_logger.LogInformation("ReadList. SushiName: {SushiName}. Id: {Id}",
model?.SushiName, model?.Id);
var list = model == null ? _sushiStorage.GetFullList() :
_sushiStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count: {Count}", list.Count);
return list;
}
public SushiViewModel? ReadElement(SushiSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. SushiName: {SushiName}. Id: {Id}",
model.SushiName, model.Id);
var element = _sushiStorage.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(SushiBindingModel model)
{
CheckModel(model);
if (_sushiStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Update(SushiBindingModel model)
{
CheckModel(model);
if (_sushiStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool Delete(SushiBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id: {Id}", model.Id);
if (_sushiStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
private void CheckModel(SushiBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.SushiName))
{
throw new ArgumentNullException("Нет названия суши", nameof(model.SushiName));
}
if (model.Price <= 0)
{
throw new ArgumentNullException("Цена суши должна быть больше 0",
nameof(model.Price));
}
_logger.LogInformation("Sushi. SushiName: {SushiName}. Cost: {Cost}. Id: {Id}",
model.SushiName, model.Price, model.Id);
var element = _sushiStorage.GetElement(new SushiSearchModel
{
SushiName = model.SushiName
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Суши с таким названием уже есть");
}
}
}
}

View File

@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.2.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SushiBarContracts\SushiBarContracts.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,12 @@
using SushiBarDataModels.Models;
namespace SushiBarContracts.BindingModels
{
public class IngredientBindingModel : IIngredientModel
{
public int Id { get; set; }
public string IngredientName { get; set; } = string.Empty;
public double Cost { get; set; }
}
}

View File

@ -0,0 +1,16 @@
using SushiBarDataModels.Enums;
using SushiBarDataModels.Models;
namespace SushiBarContracts.BindingModels
{
public class OrderBindingModel : IOrderModel
{
public int SushiId { get; set; }
public int Count { get; set; }
public double Sum { get; set; }
public OrderStatus Status { get; set; } = OrderStatus.Неизвестен;
public DateTime DateCreate { get; set; } = DateTime.Now;
public DateTime? DateImplement { get; set; }
public int Id { get; set; }
}
}

View File

@ -0,0 +1,22 @@
using SushiBarDataModels.Models;
namespace SushiBarContracts.BindingModels
{
public class ShopBindingModel : IShopModel
{
public int Id { get; set; }
public string ShopName { get; set; } = string.Empty;
public string Address { get; set; } = string.Empty;
public DateTime DateOpening { get; set; } = DateTime.Now;
public Dictionary<int, (ISushiModel, int)> ListSushi
{
get;
set;
} = new();
public int MaxCountSushi { get; set; }
}
}

View File

@ -0,0 +1,17 @@
using SushiBarDataModels.Models;
namespace SushiBarContracts.BindingModels
{
public class SushiBindingModel : ISushiModel
{
public int Id { get; set; }
public string SushiName { get; set; } = string.Empty;
public double Price { get; set; }
public Dictionary<int, (IIngredientModel, int)> SushiIngredients
{
get;
set;
} = new();
}
}

View File

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

View File

@ -0,0 +1,15 @@
using SushiBarContracts.BindingModels;
using SushiBarContracts.SearchModels;
using SushiBarContracts.ViewModels;
namespace SushiBarContracts.BusinessLogicsContracts
{
public interface IOrderLogic
{
List<OrderViewModel>? ReadList(OrderSearchModel? model);
bool CreateOrder(OrderBindingModel model);
bool TakeOrderInWork(OrderBindingModel model);
bool FinishOrder(OrderBindingModel model);
bool DeliveryOrder(OrderBindingModel model);
}
}

View File

@ -0,0 +1,19 @@
using SushiBarContracts.BindingModels;
using SushiBarContracts.SearchModels;
using SushiBarContracts.ViewModels;
using SushiBarDataModels.Models;
namespace SushiBarContracts.BusinessLogicsContracts
{
public interface IShopLogic
{
List<ShopViewModel>? ReadList(ShopSearchModel? model);
ShopViewModel? ReadElement(ShopSearchModel model);
bool Create(ShopBindingModel model);
bool Update(ShopBindingModel model);
bool Delete(ShopBindingModel model);
bool AddSushiInShop(ShopSearchModel model, ISushiModel sushi, int count);
bool AddSushi(ISushiModel sushi, int count);
bool SellSushi(ISushiModel sushi, int count);
}
}

View File

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

View File

@ -0,0 +1,9 @@
namespace SushiBarContracts.SearchModels
{
public class IngredientSearchModel
{
public int? Id { get; set; }
public string? IngredientName { get; set; }
}
}

View File

@ -0,0 +1,8 @@
namespace SushiBarContracts.SearchModels
{
public class OrderSearchModel
{
public int? Id { get; set; }
}
}

View File

@ -0,0 +1,8 @@
namespace SushiBarContracts.SearchModels
{
public class ShopSearchModel
{
public int? Id { get; set; }
public string? ShopName { get; set; }
}
}

View File

@ -0,0 +1,8 @@
namespace SushiBarContracts.SearchModels
{
public class SushiSearchModel
{
public int? Id { get; set; }
public string? SushiName { get; set; }
}
}

View File

@ -0,0 +1,16 @@
using SushiBarContracts.BindingModels;
using SushiBarContracts.SearchModels;
using SushiBarContracts.ViewModels;
namespace SushiBarContracts.StoragesContracts
{
public interface IIngredientStorage
{
List<IngredientViewModel> GetFullList();
List<IngredientViewModel> GetFilteredList(IngredientSearchModel model);
IngredientViewModel? GetElement(IngredientSearchModel model);
IngredientViewModel? Insert(IngredientBindingModel model);
IngredientViewModel? Update(IngredientBindingModel model);
IngredientViewModel? Delete(IngredientBindingModel model);
}
}

View File

@ -0,0 +1,16 @@
using SushiBarContracts.BindingModels;
using SushiBarContracts.SearchModels;
using SushiBarContracts.ViewModels;
namespace SushiBarContracts.StoragesContracts
{
public interface IOrderStorage
{
List<OrderViewModel> GetFullList();
List<OrderViewModel> GetFilteredList(OrderSearchModel model);
OrderViewModel? GetElement(OrderSearchModel model);
OrderViewModel? Insert(OrderBindingModel model);
OrderViewModel? Update(OrderBindingModel model);
OrderViewModel? Delete(OrderBindingModel model);
}
}

View File

@ -0,0 +1,18 @@
using SushiBarContracts.BindingModels;
using SushiBarContracts.SearchModels;
using SushiBarContracts.ViewModels;
using SushiBarDataModels.Models;
namespace SushiBarContracts.StoragesContracts
{
public interface IShopStorage
{
List<ShopViewModel> GetFullList();
List<ShopViewModel> GetFilteredList(ShopSearchModel model);
ShopViewModel? GetElement(ShopSearchModel model);
ShopViewModel? Insert(ShopBindingModel model);
ShopViewModel? Update(ShopBindingModel model);
ShopViewModel? Delete(ShopBindingModel model);
bool SellSushi(ISushiModel model, int count);
}
}

View File

@ -0,0 +1,16 @@
using SushiBarContracts.BindingModels;
using SushiBarContracts.SearchModels;
using SushiBarContracts.ViewModels;
namespace SushiBarContracts.StoragesContracts
{
public interface ISushiStorage
{
List<SushiViewModel> GetFullList();
List<SushiViewModel> GetFilteredList(SushiSearchModel model);
SushiViewModel? GetElement(SushiSearchModel model);
SushiViewModel? Insert(SushiBindingModel model);
SushiViewModel? Update(SushiBindingModel model);
SushiViewModel? Delete(SushiBindingModel model);
}
}

View File

@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.2.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SushiBarDataModels\SushiBarDataModels.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,14 @@
using SushiBarDataModels.Models;
using System.ComponentModel;
namespace SushiBarContracts.ViewModels
{
public class IngredientViewModel : IIngredientModel
{
public int Id { get; set; }
[DisplayName("Название ингредиента")]
public string IngredientName { get; set; } = string.Empty;
[DisplayName("Цена")]
public double Cost { get; set; }
}
}

View File

@ -0,0 +1,25 @@
using SushiBarDataModels.Enums;
using SushiBarDataModels.Models;
using System.ComponentModel;
namespace SushiBarContracts.ViewModels
{
public class OrderViewModel : IOrderModel
{
[DisplayName("Номер")]
public int Id { get; set; }
public int SushiId { get; set; }
[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,26 @@
using SushiBarDataModels.Models;
using System.ComponentModel;
namespace SushiBarContracts.ViewModels
{
public class ShopViewModel : IShopModel
{
public int Id { get; set; }
[DisplayName("Название магазина")]
public string ShopName { get; set; } = string.Empty;
[DisplayName("Адрес магазина")]
public string Address { get; set; } = string.Empty;
[DisplayName("Дата открытия")]
public DateTime DateOpening { get; set; } = DateTime.Now;
[DisplayName("Максимальное количество суши")]
public int MaxCountSushi { get; set; }
public Dictionary<int, (ISushiModel, int)> ListSushi
{
get;
set;
} = new();
}
}

View File

@ -0,0 +1,19 @@
using SushiBarDataModels.Models;
using System.ComponentModel;
namespace SushiBarContracts.ViewModels
{
public class SushiViewModel : ISushiModel
{
public int Id { get; set; }
[DisplayName("Название изделия")]
public string SushiName { get; set; } = string.Empty;
[DisplayName("Цена")]
public double Price { get; set; }
public Dictionary<int, (IIngredientModel, int)> SushiIngredients
{
get;
set;
} = new();
}
}

View File

@ -0,0 +1,11 @@
namespace SushiBarDataModels.Enums
{
public enum OrderStatus
{
Неизвестен = -1,
Принят = 0,
Выполняется = 1,
Готов = 2,
Выдан = 3,
}
}

View File

@ -0,0 +1,7 @@
namespace SushiBarDataModels
{
public interface IId
{
int Id { get; }
}
}

View File

@ -0,0 +1,8 @@
namespace SushiBarDataModels.Models
{
public interface IIngredientModel : IId
{
string IngredientName { get; }
double Cost { get; }
}
}

View File

@ -0,0 +1,14 @@
using SushiBarDataModels.Enums;
namespace SushiBarDataModels.Models
{
public interface IOrderModel : IId
{
int SushiId { get; }
int Count { get; }
double Sum { get; }
OrderStatus Status { get; }
DateTime DateCreate { get; }
DateTime? DateImplement { get; }
}
}

View File

@ -0,0 +1,11 @@
namespace SushiBarDataModels.Models
{
public interface IShopModel : IId
{
string ShopName { get; }
string Address { get; }
DateTime DateOpening { get; }
Dictionary<int, (ISushiModel, int)> ListSushi { get; }
int MaxCountSushi { get; }
}
}

View File

@ -0,0 +1,9 @@
namespace SushiBarDataModels.Models
{
public interface ISushiModel : IId
{
string SushiName { get; }
double Price { get; }
Dictionary<int, (IIngredientModel, int)> SushiIngredients { get; }
}
}

View File

@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.2.1" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,83 @@
using SushiBarContracts.BindingModels;
using SushiBarContracts.SearchModels;
using SushiBarContracts.StoragesContracts;
using SushiBarContracts.ViewModels;
using SushiBarDatabaseImplement.Models;
namespace SushiBarDatabaseImplement.Implements
{
public class IngredientStorage : IIngredientStorage
{
public List<IngredientViewModel> GetFullList()
{
using var context = new SushiBarDatabase();
return context.Ingredients
.Select(x => x.GetViewModel)
.ToList();
}
public List<IngredientViewModel> GetFilteredList(IngredientSearchModel model)
{
if (string.IsNullOrEmpty(model.IngredientName))
{
return new();
}
using var context = new SushiBarDatabase();
return context.Ingredients
.Where(x => x.IngredientName.Contains(model.IngredientName))
.Select(x => x.GetViewModel)
.ToList();
}
public IngredientViewModel? GetElement(IngredientSearchModel model)
{
if (string.IsNullOrEmpty(model.IngredientName) && !model.Id.HasValue)
{
return null;
}
using var context = new SushiBarDatabase();
return context.Ingredients
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.IngredientName) && x.IngredientName == model.IngredientName) ||
(model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public IngredientViewModel? Insert(IngredientBindingModel model)
{
var newIngredient = Ingredient.Create(model);
if (newIngredient == null)
{
return null;
}
using var context = new SushiBarDatabase();
context.Ingredients.Add(newIngredient);
context.SaveChanges();
return newIngredient.GetViewModel;
}
public IngredientViewModel? Update(IngredientBindingModel model)
{
using var context = new SushiBarDatabase();
var ingredient = context.Ingredients.FirstOrDefault(x => x.Id == model.Id);
if (ingredient == null)
{
return null;
}
ingredient.Update(model);
context.SaveChanges();
return ingredient.GetViewModel;
}
public IngredientViewModel? Delete(IngredientBindingModel model)
{
using var context = new SushiBarDatabase();
var element = context.Ingredients.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Ingredients.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -0,0 +1,93 @@
using Microsoft.EntityFrameworkCore;
using SushiBarContracts.BindingModels;
using SushiBarContracts.SearchModels;
using SushiBarContracts.StoragesContracts;
using SushiBarContracts.ViewModels;
using SushiBarDatabaseImplement.Models;
namespace SushiBarDatabaseImplement.Implements
{
public class OrderStorage : IOrderStorage
{
public OrderViewModel? Delete(OrderBindingModel model)
{
using var context = new SushiBarDatabase();
var element = context.Orders
.Include(x => x.Sushi)
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Orders.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new SushiBarDatabase();
return context.Orders
.Include(x => x.Sushi)
.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)
?.GetViewModel;
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return new();
}
using var context = new SushiBarDatabase();
return context.Orders
.Include(x => x.Sushi)
.Where(x => x.Id == model.Id)
.Select(x => x.GetViewModel)
.ToList();
}
public List<OrderViewModel> GetFullList()
{
using var context = new SushiBarDatabase();
return context.Orders
.Include(x => x.Sushi)
.Select(x => x.GetViewModel)
.ToList();
}
public OrderViewModel? Insert(OrderBindingModel model)
{
var newOrder = Order.Create(model);
if (newOrder == null)
{
return null;
}
using var context = new SushiBarDatabase();
context.Orders.Add(newOrder);
context.SaveChanges();
return context.Orders
.Include(x => x.Sushi)
.FirstOrDefault(x => x.Id == newOrder.Id)
?.GetViewModel;
}
public OrderViewModel? Update(OrderBindingModel model)
{
using var context = new SushiBarDatabase();
var order = context.Orders
.Include(x => x.Sushi)
.FirstOrDefault(x => x.Id == model.Id);
if (order == null)
{
return null;
}
order.Update(model);
context.SaveChanges();
return order.GetViewModel;
}
}
}

View File

@ -0,0 +1,152 @@
using Microsoft.EntityFrameworkCore;
using SushiBarContracts.BindingModels;
using SushiBarContracts.SearchModels;
using SushiBarContracts.StoragesContracts;
using SushiBarContracts.ViewModels;
using SushiBarDatabaseImplement.Models;
using SushiBarDataModels.Models;
using System.Collections.Generic;
using System.Xml.Linq;
namespace SushiBarDatabaseImplement.Implements
{
public class ShopStorage : IShopStorage
{
public List<ShopViewModel> GetFullList()
{
using var context = new SushiBarDatabase();
return context.Shops
.Include(x => x.ListSushiFk)
.ThenInclude(x => x.Sushi)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public List<ShopViewModel> GetFilteredList(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.ShopName))
{
return new();
}
using var context = new SushiBarDatabase();
return context.Shops
.Include(x => x.ListSushiFk)
.ThenInclude(x => x.Sushi)
.Where(x => x.ShopName.Contains(model.ShopName))
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public ShopViewModel? GetElement(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.ShopName) && !model.Id.HasValue)
{
return null;
}
using var context = new SushiBarDatabase();
return context.Shops
.Include(x => x.ListSushiFk)
.ThenInclude(x => x.Sushi)
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.ShopName) && x.ShopName == model.ShopName) ||
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public ShopViewModel? Insert(ShopBindingModel model)
{
using var context = new SushiBarDatabase();
var newShop = Shop.Create(context, model);
if (newShop == null)
{
return null;
}
context.Shops.Add(newShop);
context.SaveChanges();
return newShop.GetViewModel;
}
public ShopViewModel? Update(ShopBindingModel model)
{
using var context = new SushiBarDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
var shop = context.Shops.FirstOrDefault(rec => rec.Id == model.Id);
if (shop == null)
{
return null;
}
shop.Update(model);
context.SaveChanges();
shop.UpdateSushi(context, model);
transaction.Commit();
return shop.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
}
public ShopViewModel? Delete(ShopBindingModel model)
{
using var context = new SushiBarDatabase();
var element = context.Shops
.Include(x => x.ListSushiFk)
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Shops.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
public bool SellSushi(ISushiModel model, int count)
{
using var context = new SushiBarDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
foreach (var shop in context.Shops
.Include(x => x.ListSushiFk)
.ThenInclude(x => x.Sushi)
.ToList()
.Where(x => x.ListSushi.ContainsKey(model.Id)))
{
int countInCurrentShop = shop.ListSushi[model.Id].Item2;
if (countInCurrentShop <= count)
{
var elem = context.ShopSushi
.Where(x => x.SushiId == model.Id)
.FirstOrDefault(x => x.ShopId == shop.Id);
context.ShopSushi.Remove(elem);
shop.ListSushi.Remove(model.Id);
count -= countInCurrentShop;
}
else
{
shop.ListSushi[model.Id] = (shop.ListSushi[model.Id].Item1, countInCurrentShop - count);
count = 0;
shop.UpdateSushi(context, new()
{
Id = shop.Id,
ListSushi = shop.ListSushi,
});
}
if (count == 0)
{
context.SaveChanges();
transaction.Commit();
return true;
}
}
transaction.Rollback();
return false;
}
catch
{
transaction.Rollback();
throw;
}
}
}
}

View File

@ -0,0 +1,108 @@
using Microsoft.EntityFrameworkCore;
using SushiBarContracts.BindingModels;
using SushiBarContracts.SearchModels;
using SushiBarContracts.StoragesContracts;
using SushiBarContracts.ViewModels;
using SushiBarDatabaseImplement.Models;
using SushiBarDataModels.Models;
namespace SushiBarDatabaseImplement.Implements
{
public class SushiStorage : ISushiStorage
{
public List<SushiViewModel> GetFullList()
{
using var context = new SushiBarDatabase();
return context.ListSushi
.Include(x => x.Ingredients)
.ThenInclude(x => x.Ingredient)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public List<SushiViewModel> GetFilteredList(SushiSearchModel model)
{
if (string.IsNullOrEmpty(model.SushiName))
{
return new();
}
using var context = new SushiBarDatabase();
return context.ListSushi
.Include(x => x.Ingredients)
.ThenInclude(x => x.Ingredient)
.Where(x => x.SushiName.Contains(model.SushiName))
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public SushiViewModel? GetElement(SushiSearchModel model)
{
if (string.IsNullOrEmpty(model.SushiName) && !model.Id.HasValue)
{
return null;
}
using var context = new SushiBarDatabase();
return context.ListSushi
.Include(x => x.Ingredients)
.ThenInclude(x => x.Ingredient)
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.SushiName) && x.SushiName == model.SushiName) ||
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public SushiViewModel? Insert(SushiBindingModel model)
{
using var context = new SushiBarDatabase();
var newSushi = Sushi.Create(context, model);
if (newSushi == null)
{
return null;
}
context.ListSushi.Add(newSushi);
context.SaveChanges();
return newSushi.GetViewModel;
}
public SushiViewModel? Update(SushiBindingModel model)
{
using var context = new SushiBarDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
var sushi = context.ListSushi.FirstOrDefault(rec => rec.Id == model.Id);
if (sushi == null)
{
return null;
}
sushi.Update(model);
context.SaveChanges();
sushi.UpdateIngredients(context, model);
transaction.Commit();
return sushi.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
}
public SushiViewModel? Delete(SushiBindingModel model)
{
using var context = new SushiBarDatabase();
var element = context.ListSushi
.Include(x => x.Ingredients)
.Include(x => x.Orders)
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.ListSushi.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -0,0 +1,156 @@
// <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("20230227162916_InitMigration")]
partial class InitMigration
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.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.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.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");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,114 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SushiBarDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class InitMigration : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Ingredients",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
IngredientName = table.Column<string>(type: "nvarchar(max)", nullable: false),
Cost = table.Column<double>(type: "float", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Ingredients", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Orders",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
SushiId = table.Column<int>(type: "int", nullable: false),
Count = 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)
},
constraints: table =>
{
table.PrimaryKey("PK_Orders", x => x.Id);
});
migrationBuilder.CreateTable(
name: "ListSushi",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
SushiName = table.Column<string>(type: "nvarchar(max)", nullable: false),
Price = table.Column<double>(type: "float", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ListSushi", x => x.Id);
});
migrationBuilder.CreateTable(
name: "SushiIngredients",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
SushiId = table.Column<int>(type: "int", nullable: false),
IngredientId = table.Column<int>(type: "int", nullable: false),
Count = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_SushiIngredients", x => x.Id);
table.ForeignKey(
name: "FK_SushiIngredients_Ingredients_IngredientId",
column: x => x.IngredientId,
principalTable: "Ingredients",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_SushiIngredients_ListSushi_SushiId",
column: x => x.SushiId,
principalTable: "ListSushi",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_SushiIngredients_IngredientId",
table: "SushiIngredients",
column: "IngredientId");
migrationBuilder.CreateIndex(
name: "IX_SushiIngredients_SushiId",
table: "SushiIngredients",
column: "SushiId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Orders");
migrationBuilder.DropTable(
name: "SushiIngredients");
migrationBuilder.DropTable(
name: "Ingredients");
migrationBuilder.DropTable(
name: "ListSushi");
}
}
}

View File

@ -0,0 +1,171 @@
// <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("20230227181342_SecondMigration")]
partial class SecondMigration
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.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

@ -0,0 +1,39 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SushiBarDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class SecondMigration : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateIndex(
name: "IX_Orders_SushiId",
table: "Orders",
column: "SushiId");
migrationBuilder.AddForeignKey(
name: "FK_Orders_ListSushi_SushiId",
table: "Orders",
column: "SushiId",
principalTable: "ListSushi",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Orders_ListSushi_SushiId",
table: "Orders");
migrationBuilder.DropIndex(
name: "IX_Orders_SushiId",
table: "Orders");
}
}
}

View File

@ -0,0 +1,248 @@
// <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("20230314085708_ShopMigration")]
partial class ShopMigration
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.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.Shop", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("Address")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("DateOpening")
.HasColumnType("datetime2");
b.Property<int>("MaxCountSushi")
.HasColumnType("int");
b.Property<string>("ShopName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Shops");
});
modelBuilder.Entity("SushiBarDatabaseImplement.Models.ShopSushi", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("ShopId")
.HasColumnType("int");
b.Property<int>("SushiId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ShopId");
b.HasIndex("SushiId");
b.ToTable("ShopSushi");
});
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.ShopSushi", b =>
{
b.HasOne("SushiBarDatabaseImplement.Models.Shop", "Shop")
.WithMany("ListSushiFk")
.HasForeignKey("ShopId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SushiBarDatabaseImplement.Models.Sushi", "Sushi")
.WithMany()
.HasForeignKey("SushiId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Shop");
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.Shop", b =>
{
b.Navigation("ListSushiFk");
});
modelBuilder.Entity("SushiBarDatabaseImplement.Models.Sushi", b =>
{
b.Navigation("Ingredients");
b.Navigation("Orders");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,78 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SushiBarDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class ShopMigration : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Shops",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ShopName = table.Column<string>(type: "nvarchar(max)", nullable: false),
Address = table.Column<string>(type: "nvarchar(max)", nullable: false),
DateOpening = table.Column<DateTime>(type: "datetime2", nullable: false),
MaxCountSushi = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Shops", x => x.Id);
});
migrationBuilder.CreateTable(
name: "ShopSushi",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
SushiId = table.Column<int>(type: "int", nullable: false),
ShopId = table.Column<int>(type: "int", nullable: false),
Count = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ShopSushi", x => x.Id);
table.ForeignKey(
name: "FK_ShopSushi_ListSushi_SushiId",
column: x => x.SushiId,
principalTable: "ListSushi",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_ShopSushi_Shops_ShopId",
column: x => x.ShopId,
principalTable: "Shops",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_ShopSushi_ShopId",
table: "ShopSushi",
column: "ShopId");
migrationBuilder.CreateIndex(
name: "IX_ShopSushi_SushiId",
table: "ShopSushi",
column: "SushiId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ShopSushi");
migrationBuilder.DropTable(
name: "Shops");
}
}
}

View File

@ -0,0 +1,245 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SushiBarDatabaseImplement;
#nullable disable
namespace SushiBarDatabaseImplement.Migrations
{
[DbContext(typeof(SushiBarDatabase))]
partial class SushiBarDatabaseModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.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.Shop", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("Address")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("DateOpening")
.HasColumnType("datetime2");
b.Property<int>("MaxCountSushi")
.HasColumnType("int");
b.Property<string>("ShopName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Shops");
});
modelBuilder.Entity("SushiBarDatabaseImplement.Models.ShopSushi", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("ShopId")
.HasColumnType("int");
b.Property<int>("SushiId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ShopId");
b.HasIndex("SushiId");
b.ToTable("ShopSushi");
});
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.ShopSushi", b =>
{
b.HasOne("SushiBarDatabaseImplement.Models.Shop", "Shop")
.WithMany("ListSushiFk")
.HasForeignKey("ShopId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SushiBarDatabaseImplement.Models.Sushi", "Sushi")
.WithMany()
.HasForeignKey("SushiId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Shop");
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.Shop", b =>
{
b.Navigation("ListSushiFk");
});
modelBuilder.Entity("SushiBarDatabaseImplement.Models.Sushi", b =>
{
b.Navigation("Ingredients");
b.Navigation("Orders");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,63 @@
using SushiBarContracts.BindingModels;
using SushiBarContracts.ViewModels;
using SushiBarDataModels.Models;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace SushiBarDatabaseImplement.Models
{
public class Ingredient : IIngredientModel
{
public int Id { get; private set; }
[Required]
public string IngredientName { get; private set; } = string.Empty;
[Required]
public double Cost { get; set; }
[ForeignKey("IngredientId")]
public virtual List<SushiIngredient> SushiIngredients { get; set; } = new();
public static Ingredient? Create(IngredientBindingModel model)
{
if (model == null)
{
return null;
}
return new Ingredient()
{
Id = model.Id,
IngredientName = model.IngredientName,
Cost = model.Cost
};
}
public static Ingredient Create(IngredientViewModel model)
{
return new Ingredient
{
Id = model.Id,
IngredientName = model.IngredientName,
Cost = model.Cost
};
}
public void Update(IngredientBindingModel model)
{
if (model == null)
{
return;
}
IngredientName = model.IngredientName;
Cost = model.Cost;
}
public IngredientViewModel GetViewModel => new()
{
Id = Id,
IngredientName = IngredientName,
Cost = Cost
};
}
}

View File

@ -0,0 +1,64 @@
using SushiBarContracts.BindingModels;
using SushiBarContracts.ViewModels;
using SushiBarDataModels.Enums;
using SushiBarDataModels.Models;
using System.ComponentModel.DataAnnotations;
namespace SushiBarDatabaseImplement.Models
{
public class Order : IOrderModel
{
[Required]
public int SushiId { get; set; }
[Required]
public int Count { get; set; }
[Required]
public double Sum { get; set; }
[Required]
public OrderStatus Status { get; set; }
[Required]
public DateTime DateCreate { get; set; }
public DateTime? DateImplement { get; set; }
public int Id { get; set; }
public Sushi Sushi { get; set; }
public static Order? Create(OrderBindingModel? model)
{
if (model == null)
{
return null;
}
return new Order()
{
Id = model.Id,
SushiId = model.SushiId,
Count = model.Count,
Sum = model.Sum,
Status = model.Status,
DateCreate = model.DateCreate,
DateImplement = model.DateImplement,
};
}
public void Update(OrderBindingModel? model)
{
if (model == null)
{
return;
}
Status = model.Status;
DateImplement = model.DateImplement;
}
public OrderViewModel GetViewModel => new()
{
SushiId = SushiId,
Count = Count,
Sum = Sum,
DateCreate = DateCreate,
DateImplement = DateImplement,
Id = Id,
Status = Status,
SushiName = Sushi.SushiName,
};
}
}

View File

@ -0,0 +1,105 @@
using SushiBarContracts.BindingModels;
using SushiBarContracts.ViewModels;
using SushiBarDataModels.Models;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using System.Xml.Linq;
namespace SushiBarDatabaseImplement.Models
{
public class Shop : IShopModel
{
public int Id { get; private set; }
[Required]
public string ShopName { get; private set; } = string.Empty;
[Required]
public string Address { get; private set; } = string.Empty;
[Required]
public DateTime DateOpening { get; private set; }
[Required]
public int MaxCountSushi { get; private set; }
private Dictionary<int, (ISushiModel, int)>? _shopSushi = null;
[NotMapped]
public Dictionary<int, (ISushiModel, int)> ListSushi
{
get
{
if (_shopSushi == null)
{
_shopSushi = ListSushiFk
.ToDictionary(recPC => recPC.SushiId, recPC => (recPC.Sushi as ISushiModel, recPC.Count));
}
return _shopSushi;
}
}
[ForeignKey("ShopId")]
public virtual List<ShopSushi> ListSushiFk { get; set; } = new();
public static Shop Create(SushiBarDatabase context, ShopBindingModel model)
{
return new Shop()
{
Id = model.Id,
ShopName = model.ShopName,
Address = model.Address,
DateOpening = model.DateOpening,
MaxCountSushi = model.MaxCountSushi,
ListSushiFk = model.ListSushi.Select(x => new ShopSushi
{
Sushi = context.ListSushi.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList()
};
}
public void Update(ShopBindingModel model)
{
ShopName = model.ShopName;
Address = model.Address;
DateOpening = model.DateOpening;
MaxCountSushi = model.MaxCountSushi;
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
ShopName = ShopName,
Address = Address,
DateOpening = DateOpening,
MaxCountSushi = MaxCountSushi,
ListSushi = ListSushi
};
public void UpdateSushi(SushiBarDatabase context, ShopBindingModel model)
{
var shopSushi = context.ShopSushi.Where(rec => rec.ShopId == model.Id).ToList();
if (shopSushi != null && shopSushi.Count > 0)
{ // удалили те, которых нет в модели
context.ShopSushi.RemoveRange(shopSushi.Where(rec => !model.ListSushi.ContainsKey(rec.SushiId)));
context.SaveChanges();
// обновили количество у существующих записей
foreach (var updateSushi in shopSushi)
{
updateSushi.Count = model.ListSushi[updateSushi.SushiId].Item2;
model.ListSushi.Remove(updateSushi.SushiId);
}
context.SaveChanges();
}
var shop = context.Shops.First(x => x.Id == Id);
foreach (var ss in model.ListSushi)
{
context.ShopSushi.Add(new ShopSushi
{
Shop = shop,
Sushi = context.ListSushi.First(x => x.Id == ss.Key),
Count = ss.Value.Item2
});
context.SaveChanges();
}
_shopSushi = null;
}
}
}

View File

@ -0,0 +1,22 @@
using System.ComponentModel.DataAnnotations;
namespace SushiBarDatabaseImplement.Models
{
public class ShopSushi
{
public int Id { get; set; }
[Required]
public int SushiId { get; set; }
[Required]
public int ShopId { get; set; }
[Required]
public int Count { get; set; }
public virtual Shop Shop { get; set; } = new();
public virtual Sushi Sushi { get; set; } = new();
}
}

View File

@ -0,0 +1,98 @@
using SushiBarContracts.BindingModels;
using SushiBarContracts.ViewModels;
using SushiBarDataModels.Models;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace SushiBarDatabaseImplement.Models
{
public class Sushi : ISushiModel
{
public int Id { get; set; }
[Required]
public string SushiName { get; set; } = string.Empty;
[Required]
public double Price { get; set; }
private Dictionary<int, (IIngredientModel, int)>? _sushiIngredients = null;
[NotMapped]
public Dictionary<int, (IIngredientModel, int)> SushiIngredients
{
get
{
if (_sushiIngredients == null)
{
_sushiIngredients = Ingredients
.ToDictionary(recPC => recPC.IngredientId, recPC => (recPC.Ingredient as IIngredientModel, recPC.Count));
}
return _sushiIngredients;
}
}
[ForeignKey("SushiId")]
public virtual List<SushiIngredient> Ingredients { get; set; } = new();
[ForeignKey("SushiId")]
public virtual List<Order> Orders { get; set; } = new();
public static Sushi Create(SushiBarDatabase context, SushiBindingModel model)
{
return new Sushi()
{
Id = model.Id,
SushiName = model.SushiName,
Price = model.Price,
Ingredients = model.SushiIngredients.Select(x => new SushiIngredient
{
Ingredient = context.Ingredients.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList()
};
}
public void Update(SushiBindingModel model)
{
SushiName = model.SushiName;
Price = model.Price;
}
public SushiViewModel GetViewModel => new()
{
Id = Id,
SushiName = SushiName,
Price = Price,
SushiIngredients = SushiIngredients
};
public void UpdateIngredients(SushiBarDatabase context, SushiBindingModel model)
{
var sushiIngredients = context.SushiIngredients.Where(rec => rec.SushiId == model.Id).ToList();
if (sushiIngredients != null && sushiIngredients.Count > 0)
{ // удалили те, которых нет в модели
context.SushiIngredients.RemoveRange(sushiIngredients.Where(rec => !model.SushiIngredients.ContainsKey(rec.IngredientId)));
context.SaveChanges();
// обновили количество у существующих записей
foreach (var updateIngredient in sushiIngredients)
{
updateIngredient.Count = model.SushiIngredients[updateIngredient.IngredientId].Item2;
model.SushiIngredients.Remove(updateIngredient.IngredientId);
}
context.SaveChanges();
}
var sushi = context.ListSushi.First(x => x.Id == Id);
foreach (var si in model.SushiIngredients)
{
context.SushiIngredients.Add(new SushiIngredient
{
Sushi = sushi,
Ingredient = context.Ingredients.First(x => x.Id == si.Key),
Count = si.Value.Item2
});
context.SaveChanges();
}
_sushiIngredients = null;
}
}
}

View File

@ -0,0 +1,22 @@
using System.ComponentModel.DataAnnotations;
namespace SushiBarDatabaseImplement.Models
{
public class SushiIngredient
{
public int Id { get; set; }
[Required]
public int SushiId { get; set; }
[Required]
public int IngredientId { get; set; }
[Required]
public int Count { get; set; }
public virtual Ingredient Ingredient { get; set; } = new();
public virtual Sushi Sushi { get; set; } = new();
}
}

View File

@ -0,0 +1,29 @@
using Microsoft.EntityFrameworkCore;
using SushiBarDatabaseImplement.Models;
namespace SushiBarDatabaseImplement
{
public class SushiBarDatabase : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (optionsBuilder.IsConfigured == false)
{
optionsBuilder.UseSqlServer(@"Data Source=DESKTOP-D8KMQQU\SQLEXPRESS;Initial Catalog=SushiBarDatabase;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True");
}
base.OnConfiguring(optionsBuilder);
}
public virtual DbSet<Ingredient> Ingredients { set; get; }
public virtual DbSet<Sushi> ListSushi { set; get; }
public virtual DbSet<SushiIngredient> SushiIngredients { set; get; }
public virtual DbSet<Order> Orders { set; get; }
public virtual DbSet<Shop> Shops { set; get; }
public virtual DbSet<ShopSushi> ShopSushi { set; get; }
}
}

View File

@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SushiBarContracts\SushiBarContracts.csproj" />
<ProjectReference Include="..\SushiBarDataModels\SushiBarDataModels.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,57 @@
using SushiBarFileImplement.Models;
using System.Xml.Linq;
namespace SushiBarFileImplement
{
public class DataFileSingleton
{
private static DataFileSingleton? instance;
private readonly string IngredientFileName = "Ingredient.xml";
private readonly string OrderFileName = "Order.xml";
private readonly string SushiFileName = "Sushi.xml";
private readonly string ShopFileName = "Shop.xml";
public List<Ingredient> Ingredients { get; private set; }
public List<Order> Orders { get; private set; }
public List<Sushi> ListSushi { get; private set; }
public List<Shop> Shops { get; private set; }
public static DataFileSingleton GetInstance()
{
if (instance == null)
{
instance = new DataFileSingleton();
}
return instance;
}
public void SaveIngredients() => SaveData(Ingredients, IngredientFileName,
"Ingredients", x => x.GetXElement);
public void SaveListSushi() => SaveData(ListSushi, SushiFileName,
"ListSushi", x => x.GetXElement);
public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement);
public void SaveShops() => SaveData(Shops, ShopFileName, "Shops", 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)!)!;
Shops = LoadData(ShopFileName, "Shop", x => Shop.Create(x)!)!;
}
private static List<T>? LoadData<T>(string filename, string xmlNodeName,
Func<XElement, T> selectFunction)
{
if (File.Exists(filename))
{
return
XDocument.Load(filename)?.Root?.Elements(xmlNodeName)?.Select(selectFunction)?.ToList();
}
return new List<T>();
}
private static void SaveData<T>(List<T> data, string filename, string
xmlNodeName, Func<T, XElement> selectFunction)
{
if (data != null)
{
new XDocument(new XElement(xmlNodeName, data.Select(selectFunction).ToArray())).Save(filename);
}
}
}
}

View File

@ -0,0 +1,74 @@
using SushiBarContracts.BindingModels;
using SushiBarContracts.SearchModels;
using SushiBarContracts.StoragesContracts;
using SushiBarContracts.ViewModels;
using SushiBarFileImplement.Models;
namespace SushiBarFileImplement.Implements
{
public class IngredientStorage : IIngredientStorage
{
private readonly DataFileSingleton source;
public IngredientStorage()
{
source = DataFileSingleton.GetInstance();
}
public List<IngredientViewModel> GetFullList()
{
return source.Ingredients.Select(x => x.GetViewModel).ToList();
}
public List<IngredientViewModel> GetFilteredList(IngredientSearchModel model)
{
if (string.IsNullOrEmpty(model.IngredientName))
{
return new();
}
return source.Ingredients.Where(x =>
x.IngredientName.Contains(model.IngredientName)).Select(x => x.GetViewModel).ToList();
}
public IngredientViewModel? GetElement(IngredientSearchModel model)
{
if (string.IsNullOrEmpty(model.IngredientName) && !model.Id.HasValue)
{
return null;
}
return source.Ingredients.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.IngredientName) && x.IngredientName ==
model.IngredientName) || (model.Id.HasValue && x.Id == model.Id)) ?.GetViewModel;
}
public IngredientViewModel? Insert(IngredientBindingModel model)
{
model.Id = source.Ingredients.Count > 0 ? source.Ingredients.Max(x => x.Id) + 1 : 1;
var newIngredient = Ingredient.Create(model);
if (newIngredient == null)
{
return null;
}
source.Ingredients.Add(newIngredient);
source.SaveIngredients();
return newIngredient.GetViewModel;
}
public IngredientViewModel? Update(IngredientBindingModel model)
{
var ingredient = source.Ingredients.FirstOrDefault(x => x.Id == model.Id);
if (ingredient == null)
{
return null;
}
ingredient.Update(model);
source.SaveIngredients();
return ingredient.GetViewModel;
}
public IngredientViewModel? Delete(IngredientBindingModel model)
{
var element = source.Ingredients.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
source.Ingredients.Remove(element);
source.SaveIngredients();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -0,0 +1,85 @@
using SushiBarContracts.BindingModels;
using SushiBarContracts.SearchModels;
using SushiBarContracts.StoragesContracts;
using SushiBarContracts.ViewModels;
using SushiBarFileImplement.Models;
namespace SushiBarFileImplement.Implements
{
public class OrderStorage : IOrderStorage
{
private readonly DataFileSingleton source;
public OrderStorage()
{
source = DataFileSingleton.GetInstance();
}
public List<OrderViewModel> GetFullList()
{
return source.Orders.Select(x => GetViewModel(x)).ToList();
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return new();
}
return source.Orders.Where(x => x.Id.Equals(model.Id)).Select(x => GetViewModel(x)).ToList();
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
return source.Orders.FirstOrDefault(x =>
(model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
private OrderViewModel GetViewModel(Order order)
{
var viewModel = order.GetViewModel;
var sushi = source.ListSushi.FirstOrDefault(x => x.Id == order.SushiId);
if (sushi != null) viewModel.SushiName = sushi.SushiName;
return viewModel;
}
public OrderViewModel? Insert(OrderBindingModel model)
{
model.Id = source.Orders.Count > 0 ? source.Orders.Max(x => x.Id) + 1 : 1;
var newOrder = Order.Create(model);
if (newOrder == null)
{
return null;
}
source.Orders.Add(newOrder);
source.SaveOrders();
return GetViewModel(newOrder);
}
public OrderViewModel? Update(OrderBindingModel model)
{
var order = source.Orders.FirstOrDefault(x => x.Id == model.Id);
if (order == null)
{
return null;
}
order.Update(model);
source.SaveOrders();
return GetViewModel(order);
}
public OrderViewModel? Delete(OrderBindingModel model)
{
var element = source.Orders.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
source.Orders.Remove(element);
source.SaveOrders();
return GetViewModel(element);
}
return null;
}
}
}

View File

@ -0,0 +1,102 @@
using SushiBarContracts.BindingModels;
using SushiBarContracts.SearchModels;
using SushiBarContracts.StoragesContracts;
using SushiBarContracts.ViewModels;
using SushiBarDataModels.Models;
using SushiBarFileImplement.Models;
namespace SushiBarFileImplement.Implements
{
public class ShopStorage : IShopStorage
{
private readonly DataFileSingleton source;
public ShopStorage()
{
source = DataFileSingleton.GetInstance();
}
public List<ShopViewModel> GetFullList()
{
return source.Shops.Select(x => x.GetViewModel).ToList();
}
public List<ShopViewModel> GetFilteredList(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.ShopName))
{
return new();
}
return source.Shops.Where(x =>
x.ShopName.Contains(model.ShopName)).Select(x => x.GetViewModel).ToList();
}
public ShopViewModel? GetElement(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.ShopName) && !model.Id.HasValue)
{
return null;
}
return source.Shops.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.ShopName) && x.ShopName ==
model.ShopName) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public ShopViewModel? Insert(ShopBindingModel model)
{
model.Id = source.Shops.Count > 0 ? source.Shops.Max(x => x.Id) + 1 : 1;
var newShop = Shop.Create(model);
if (newShop == null)
{
return null;
}
source.Shops.Add(newShop);
source.SaveShops();
return newShop.GetViewModel;
}
public ShopViewModel? Update(ShopBindingModel model)
{
var shop = source.Shops.FirstOrDefault(x => x.Id == model.Id);
if (shop == null)
{
return null;
}
shop.Update(model);
source.SaveShops();
return shop.GetViewModel;
}
public ShopViewModel? Delete(ShopBindingModel model)
{
var element = source.Shops.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
source.Shops.Remove(element);
source.SaveShops();
return element.GetViewModel;
}
return null;
}
public bool SellSushi(ISushiModel model, int count)
{
if (source.Shops.Select(x => x.ListSushi.FirstOrDefault(y => y.Key == model.Id).Value.Item2).Sum() < count)
{
return false;
}
foreach (var shop in source.Shops.Where(x => x.ListSushi.ContainsKey(model.Id)))
{
int countInCurrentShop = shop.ListSushi[model.Id].Item2;
if (countInCurrentShop <= count)
{
shop.ListSushi.Remove(model.Id);
count -= countInCurrentShop;
}
else
{
shop.ListSushi[model.Id] = (shop.ListSushi[model.Id].Item1, countInCurrentShop - count);
count = 0;
}
if (count == 0)
{
return true;
}
}
return false;
}
}
}

View File

@ -0,0 +1,76 @@
using SushiBarContracts.BindingModels;
using SushiBarContracts.SearchModels;
using SushiBarContracts.StoragesContracts;
using SushiBarContracts.ViewModels;
using SushiBarDataModels.Models;
using SushiBarFileImplement.Models;
using System.Reflection;
namespace SushiBarFileImplement.Implements
{
public class SushiStorage : ISushiStorage
{
private readonly DataFileSingleton source;
public SushiStorage()
{
source = DataFileSingleton.GetInstance();
}
public List<SushiViewModel> GetFullList()
{
return source.ListSushi.Select(x => x.GetViewModel).ToList();
}
public List<SushiViewModel> GetFilteredList(SushiSearchModel model)
{
if (string.IsNullOrEmpty(model.SushiName))
{
return new();
}
return source.ListSushi.Where(x =>
x.SushiName.Contains(model.SushiName)).Select(x => x.GetViewModel).ToList();
}
public SushiViewModel? GetElement(SushiSearchModel model)
{
if (string.IsNullOrEmpty(model.SushiName) && !model.Id.HasValue)
{
return null;
}
return source.ListSushi.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.SushiName) && x.SushiName ==
model.SushiName) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public SushiViewModel? Insert(SushiBindingModel model)
{
model.Id = source.ListSushi.Count > 0 ? source.ListSushi.Max(x => x.Id) + 1 : 1;
var newSushi = Sushi.Create(model);
if (newSushi == null)
{
return null;
}
source.ListSushi.Add(newSushi);
source.SaveListSushi();
return newSushi.GetViewModel;
}
public SushiViewModel? Update(SushiBindingModel model)
{
var sushi = source.ListSushi.FirstOrDefault(x => x.Id == model.Id);
if (sushi == null)
{
return null;
}
sushi.Update(model);
source.SaveListSushi();
return sushi.GetViewModel;
}
public SushiViewModel? Delete(SushiBindingModel model)
{
var element = source.ListSushi.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
source.ListSushi.Remove(element);
source.SaveListSushi();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -0,0 +1,59 @@
using SushiBarContracts.BindingModels;
using SushiBarContracts.ViewModels;
using SushiBarDataModels.Models;
using System.Xml.Linq;
namespace SushiBarFileImplement.Models
{
public class Ingredient : IIngredientModel
{
public int Id { get; private set; }
public string IngredientName { get; private set; } = string.Empty;
public double Cost { get; set; }
public static Ingredient? Create(IngredientBindingModel model)
{
if (model == null)
{
return null;
}
return new Ingredient()
{
Id = model.Id,
IngredientName = model.IngredientName,
Cost = model.Cost
};
}
public static Ingredient? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Ingredient()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
IngredientName = element.Element("IngredientName")!.Value,
Cost = Convert.ToDouble(element.Element("Cost")!.Value)
};
}
public void Update(IngredientBindingModel model)
{
if (model == null)
{
return;
}
IngredientName = model.IngredientName;
Cost = model.Cost;
}
public IngredientViewModel GetViewModel => new()
{
Id = Id,
IngredientName = IngredientName,
Cost = Cost
};
public XElement GetXElement => new("Ingredient",
new XAttribute("Id", Id),
new XElement("IngredientName", IngredientName),
new XElement("Cost", Cost.ToString()));
}
}

View File

@ -0,0 +1,84 @@
using SushiBarContracts.BindingModels;
using SushiBarContracts.ViewModels;
using SushiBarDataModels.Enums;
using SushiBarDataModels.Models;
using System.Xml.Linq;
namespace SushiBarFileImplement.Models
{
public class Order : IOrderModel
{
public int Id { get; private set; }
public int SushiId { get; private set; }
public int Count { get; private set; }
public double Sum { get; private set; }
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен;
public DateTime DateCreate { get; private set; } = DateTime.Now;
public DateTime? DateImplement { get; private set; }
public static Order? Create(OrderBindingModel? model)
{
if (model == null)
{
return null;
}
return new Order()
{
Id = model.Id,
SushiId = model.SushiId,
Count = model.Count,
Sum = model.Sum,
Status = model.Status,
DateCreate = model.DateCreate,
DateImplement = model.DateImplement,
};
}
public static Order? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Order()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
SushiId = Convert.ToInt32(element.Element("SushiId")!.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),
DateCreate = Convert.ToDateTime(element.Element("DateCreate")!.Value),
DateImplement = string.IsNullOrEmpty(element.Element("DateImplement")!.Value) ? null : Convert.ToDateTime(element.Element("DateImplement")!.Value)
};
}
public void Update(OrderBindingModel? model)
{
if (model == null)
{
return;
}
Status = model.Status;
DateImplement = model.DateImplement;
}
public OrderViewModel GetViewModel => new()
{
SushiId = SushiId,
Count = Count,
Sum = Sum,
DateCreate = DateCreate,
DateImplement = DateImplement,
Id = Id,
Status = Status,
};
public XElement GetXElement => new("Order",
new XAttribute("Id", Id),
new XElement("SushiId", SushiId),
new XElement("Count", Count.ToString()),
new XElement("Sum", Sum.ToString()),
new XElement("Status", Status.ToString()),
new XElement("DateCreate", DateCreate.ToString()),
new XElement("DateImplement", DateImplement.ToString()));
}
}

View File

@ -0,0 +1,107 @@

using SushiBarContracts.BindingModels;
using SushiBarContracts.ViewModels;
using SushiBarDataModels.Models;
using System.Reflection.Metadata;
using System.Xml.Linq;
namespace SushiBarFileImplement.Models
{
public class Shop : IShopModel
{
public int Id { get; private set; }
public string ShopName { get; private set; } = string.Empty;
public string Address { get; private set; } = string.Empty;
public DateTime DateOpening { get; private set; }
public int MaxCountSushi { get; private set; }
public Dictionary<int, int> CountSushi
{
get;
private set;
} = new();
private Dictionary<int, (ISushiModel, int)>? _shopSushi = null;
public Dictionary<int, (ISushiModel, int)> ListSushi
{
get
{
if (_shopSushi == null)
{
var source = DataFileSingleton.GetInstance();
_shopSushi =
CountSushi.ToDictionary(x => x.Key,
y => ((source.ListSushi.FirstOrDefault(z => z.Id == y.Key) as ISushiModel)!, y.Value));
}
return _shopSushi;
}
}
public static Shop? Create(ShopBindingModel? model)
{
if (model == null)
{
return null;
}
return new Shop()
{
Id = model.Id,
ShopName = model.ShopName,
Address = model.Address,
MaxCountSushi = model.MaxCountSushi,
DateOpening = model.DateOpening,
CountSushi = model.ListSushi.ToDictionary(x => x.Key, x => x.Value.Item2)
};
}
public static Shop? Create(XElement element)
{
if (element == null)
{
return null;
}
return new()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
ShopName = element.Element("ShopName")!.Value,
Address = element.Element("Address")!.Value,
DateOpening = Convert.ToDateTime(element.Element("DateOpening")!.Value),
MaxCountSushi = Convert.ToInt32(element.Element("MaxCountSushi")!.Value),
CountSushi = element.Element("ListSushi")!.Elements("Sushi").ToDictionary(
x => Convert.ToInt32(x.Element("Key")?.Value),
x => Convert.ToInt32(x.Element("Value")?.Value))
};
}
public void Update(ShopBindingModel? model)
{
if (model == null)
{
return;
}
ShopName = model.ShopName;
Address = model.Address;
DateOpening = model.DateOpening;
MaxCountSushi = model.MaxCountSushi;
CountSushi = model.ListSushi.ToDictionary(x => x.Key, x => x.Value.Item2);
_shopSushi = null;
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
ShopName = ShopName,
Address = Address,
ListSushi = ListSushi,
DateOpening = DateOpening,
MaxCountSushi = MaxCountSushi,
};
public XElement GetXElement => new("Shop",
new XAttribute("Id", Id),
new XElement("ShopName", ShopName),
new XElement("Address", Address),
new XElement("DateOpening", DateOpening),
new XElement("MaxCountSushi", MaxCountSushi),
new XElement("ListSushi", CountSushi
.Select(x => new XElement("Sushi",
new XElement("Key", x.Key),
new XElement("Value", x.Value))
).ToArray()));
}
}

Some files were not shown because too many files have changed in this diff Show More