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

Closed
bekodeg wants to merge 44 commits from labWork5 into labWork4
62 changed files with 2374 additions and 68 deletions

3
.gitignore vendored
View File

@ -36,7 +36,7 @@ bld/
# Visual Studio 2015/2017 cache/options directory # Visual Studio 2015/2017 cache/options directory
.vs/ .vs/
# Uncomment if you have tasks that create the project's static files in wwwroot # Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/ wwwroot/
# Visual Studio 2017 auto generated files # Visual Studio 2017 auto generated files
Generated\ Files/ Generated\ Files/
@ -397,3 +397,4 @@ FodyWeavers.xsd
# JetBrains Rider # JetBrains Rider
*.sln.iml *.sln.iml

View File

@ -17,6 +17,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SushiBarFileImplement", "Su
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SushiBarDatabaseImplement", "SushiBarDatabaseImplement\SushiBarDatabaseImplement.csproj", "{C9C66AFC-1246-4A0C-AB70-8D5C0CF311D9}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SushiBarDatabaseImplement", "SushiBarDatabaseImplement\SushiBarDatabaseImplement.csproj", "{C9C66AFC-1246-4A0C-AB70-8D5C0CF311D9}"
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SushiBarRestApi", "SushiBarRestApi\SushiBarRestApi.csproj", "{0895AC4A-6C0A-4244-92AB-CD3AFD8B691A}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SushiBarClientApi", "SushiBarClientApi\SushiBarClientApi.csproj", "{C9EF2604-E657-4223-A7C3-945E7A4E2341}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
@ -51,6 +55,14 @@ Global
{C9C66AFC-1246-4A0C-AB70-8D5C0CF311D9}.Debug|Any CPU.Build.0 = Debug|Any CPU {C9C66AFC-1246-4A0C-AB70-8D5C0CF311D9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C9C66AFC-1246-4A0C-AB70-8D5C0CF311D9}.Release|Any CPU.ActiveCfg = Release|Any CPU {C9C66AFC-1246-4A0C-AB70-8D5C0CF311D9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C9C66AFC-1246-4A0C-AB70-8D5C0CF311D9}.Release|Any CPU.Build.0 = Release|Any CPU {C9C66AFC-1246-4A0C-AB70-8D5C0CF311D9}.Release|Any CPU.Build.0 = Release|Any CPU
{0895AC4A-6C0A-4244-92AB-CD3AFD8B691A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0895AC4A-6C0A-4244-92AB-CD3AFD8B691A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0895AC4A-6C0A-4244-92AB-CD3AFD8B691A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0895AC4A-6C0A-4244-92AB-CD3AFD8B691A}.Release|Any CPU.Build.0 = Release|Any CPU
{C9EF2604-E657-4223-A7C3-945E7A4E2341}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C9EF2604-E657-4223-A7C3-945E7A4E2341}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C9EF2604-E657-4223-A7C3-945E7A4E2341}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C9EF2604-E657-4223-A7C3-945E7A4E2341}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE

View File

@ -0,0 +1,74 @@
namespace SushiBar.Forms
{
partial class FormClients
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
DataGridView = new DataGridView();
DeleteButton = new Button();
((System.ComponentModel.ISupportInitialize)DataGridView).BeginInit();
SuspendLayout();
//
// DataGridView
//
DataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
DataGridView.Location = new Point(12, 34);
DataGridView.Name = "DataGridView";
DataGridView.RowTemplate.Height = 25;
DataGridView.Size = new Size(776, 404);
DataGridView.TabIndex = 0;
//
// DeleteButton
//
DeleteButton.Location = new Point(12, 5);
DeleteButton.Name = "DeleteButton";
DeleteButton.Size = new Size(123, 23);
DeleteButton.TabIndex = 1;
DeleteButton.Text = "Удалить";
DeleteButton.UseVisualStyleBackColor = true;
DeleteButton.Click += DeleteButton_Click;
//
// ClientsForm
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(DeleteButton);
Controls.Add(DataGridView);
Name = "ClientsForm";
Text = "Клиенты";
Load += ClientsForm_Load;
((System.ComponentModel.ISupportInitialize)DataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView DataGridView;
private Button DeleteButton;
}
}

View File

@ -0,0 +1,77 @@
using Microsoft.Extensions.Logging;
using SushiBarContracts.BindingModels;
using SushiBarContracts.BusinessLogicsContracts;
namespace SushiBar.Forms
{
public partial class FormClients : Form
{
private readonly ILogger _logger;
private readonly IClientLogic _logic;
public FormClients(ILogger<FormClients> logger, IClientLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void LoadData()
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
DataGridView.DataSource = list;
DataGridView.Columns["Id"].Visible = false;
DataGridView.Columns["ClientFIO"].AutoSizeMode =
DataGridViewAutoSizeColumnMode.Fill;
DataGridView.Columns["Email"].AutoSizeMode =
DataGridViewAutoSizeColumnMode.Fill;
DataGridView.Columns["Password"].AutoSizeMode =
DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка клиентов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки клиентов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ClientsForm_Load(object sender, EventArgs e)
{
LoadData();
}
private void DeleteButton_Click(object sender, EventArgs e)
{
if (DataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
int id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Удаление клиента");
try
{
if (!_logic.Delete(new ClientBindingModel
{
Id = id
}))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления компонента");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -46,6 +46,7 @@
buttonOrderReady = new Button(); buttonOrderReady = new Button();
buttonIssuedOrder = new Button(); buttonIssuedOrder = new Button();
buttonRef = new Button(); buttonRef = new Button();
clientsToolStripMenuItem = new ToolStripMenuItem();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
menuStrip1.SuspendLayout(); menuStrip1.SuspendLayout();
SuspendLayout(); SuspendLayout();
@ -59,7 +60,7 @@
dataGridView.RowHeadersWidth = 51; dataGridView.RowHeadersWidth = 51;
dataGridView.RowTemplate.Height = 29; dataGridView.RowTemplate.Height = 29;
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.Size = new Size(992, 422); dataGridView.Size = new Size(986, 514);
dataGridView.TabIndex = 0; dataGridView.TabIndex = 0;
// //
// menuStrip1 // menuStrip1
@ -68,13 +69,13 @@
menuStrip1.Items.AddRange(new ToolStripItem[] { toolStripMenuItem, отчётыToolStripMenuItem1 }); menuStrip1.Items.AddRange(new ToolStripItem[] { toolStripMenuItem, отчётыToolStripMenuItem1 });
menuStrip1.Location = new Point(0, 0); menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1"; menuStrip1.Name = "menuStrip1";
menuStrip1.Size = new Size(1190, 28); menuStrip1.Size = new Size(1184, 28);
menuStrip1.TabIndex = 1; menuStrip1.TabIndex = 1;
menuStrip1.Text = "menuStrip1"; menuStrip1.Text = "menuStrip1";
// //
// toolStripMenuItem // toolStripMenuItem
// //
toolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { sushiToolStripMenuItem, componentsToolStripMenuItem }); toolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { sushiToolStripMenuItem, componentsToolStripMenuItem, clientsToolStripMenuItem });
toolStripMenuItem.Name = "toolStripMenuItem"; toolStripMenuItem.Name = "toolStripMenuItem";
toolStripMenuItem.Size = new Size(117, 24); toolStripMenuItem.Size = new Size(117, 24);
toolStripMenuItem.Text = "Справочники"; toolStripMenuItem.Text = "Справочники";
@ -82,14 +83,14 @@
// sushiToolStripMenuItem // sushiToolStripMenuItem
// //
sushiToolStripMenuItem.Name = "sushiToolStripMenuItem"; sushiToolStripMenuItem.Name = "sushiToolStripMenuItem";
sushiToolStripMenuItem.Size = new Size(182, 26); sushiToolStripMenuItem.Size = new Size(224, 26);
sushiToolStripMenuItem.Text = "Суши"; sushiToolStripMenuItem.Text = "Суши";
sushiToolStripMenuItem.Click += SushiToolStripMenuItem_Click; sushiToolStripMenuItem.Click += SushiToolStripMenuItem_Click;
// //
// componentsToolStripMenuItem // componentsToolStripMenuItem
// //
componentsToolStripMenuItem.Name = "componentsToolStripMenuItem"; componentsToolStripMenuItem.Name = "componentsToolStripMenuItem";
componentsToolStripMenuItem.Size = new Size(182, 26); componentsToolStripMenuItem.Size = new Size(224, 26);
componentsToolStripMenuItem.Text = "Компоненты"; componentsToolStripMenuItem.Text = "Компоненты";
componentsToolStripMenuItem.Click += ComponentsToolStripMenuItem_Click; componentsToolStripMenuItem.Click += ComponentsToolStripMenuItem_Click;
// //
@ -144,10 +145,10 @@
// buttonCreateOrder // buttonCreateOrder
// //
buttonCreateOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; buttonCreateOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonCreateOrder.Location = new Point(998, 31); buttonCreateOrder.Location = new Point(992, 28);
buttonCreateOrder.Name = "buttonCreateOrder"; buttonCreateOrder.Name = "buttonCreateOrder";
buttonCreateOrder.Size = new Size(180, 30); buttonCreateOrder.Size = new Size(180, 30);
buttonCreateOrder.TabIndex = 2; buttonCreateOrder.TabIndex = 8;
buttonCreateOrder.Text = "Создать заказ"; buttonCreateOrder.Text = "Создать заказ";
buttonCreateOrder.UseVisualStyleBackColor = true; buttonCreateOrder.UseVisualStyleBackColor = true;
buttonCreateOrder.Click += ButtonCreateOrder_Click; buttonCreateOrder.Click += ButtonCreateOrder_Click;
@ -155,10 +156,10 @@
// buttonTakeOrderInWork // buttonTakeOrderInWork
// //
buttonTakeOrderInWork.Anchor = AnchorStyles.Top | AnchorStyles.Right; buttonTakeOrderInWork.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonTakeOrderInWork.Location = new Point(998, 67); buttonTakeOrderInWork.Location = new Point(992, 64);
buttonTakeOrderInWork.Name = "buttonTakeOrderInWork"; buttonTakeOrderInWork.Name = "buttonTakeOrderInWork";
buttonTakeOrderInWork.Size = new Size(180, 30); buttonTakeOrderInWork.Size = new Size(180, 30);
buttonTakeOrderInWork.TabIndex = 3; buttonTakeOrderInWork.TabIndex = 9;
buttonTakeOrderInWork.Text = "Отдать на выполнение"; buttonTakeOrderInWork.Text = "Отдать на выполнение";
buttonTakeOrderInWork.UseVisualStyleBackColor = true; buttonTakeOrderInWork.UseVisualStyleBackColor = true;
buttonTakeOrderInWork.Click += ButtonTakeOrderInWork_Click; buttonTakeOrderInWork.Click += ButtonTakeOrderInWork_Click;
@ -166,10 +167,10 @@
// buttonOrderReady // buttonOrderReady
// //
buttonOrderReady.Anchor = AnchorStyles.Top | AnchorStyles.Right; buttonOrderReady.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonOrderReady.Location = new Point(998, 103); buttonOrderReady.Location = new Point(992, 100);
buttonOrderReady.Name = "buttonOrderReady"; buttonOrderReady.Name = "buttonOrderReady";
buttonOrderReady.Size = new Size(180, 30); buttonOrderReady.Size = new Size(180, 30);
buttonOrderReady.TabIndex = 4; buttonOrderReady.TabIndex = 10;
buttonOrderReady.Text = "Заказ готов"; buttonOrderReady.Text = "Заказ готов";
buttonOrderReady.UseVisualStyleBackColor = true; buttonOrderReady.UseVisualStyleBackColor = true;
buttonOrderReady.Click += ButtonOrderReady_Click; buttonOrderReady.Click += ButtonOrderReady_Click;
@ -177,10 +178,10 @@
// buttonIssuedOrder // buttonIssuedOrder
// //
buttonIssuedOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; buttonIssuedOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonIssuedOrder.Location = new Point(998, 139); buttonIssuedOrder.Location = new Point(992, 136);
buttonIssuedOrder.Name = "buttonIssuedOrder"; buttonIssuedOrder.Name = "buttonIssuedOrder";
buttonIssuedOrder.Size = new Size(180, 30); buttonIssuedOrder.Size = new Size(180, 30);
buttonIssuedOrder.TabIndex = 5; buttonIssuedOrder.TabIndex = 11;
buttonIssuedOrder.Text = "Заказ Выдан"; buttonIssuedOrder.Text = "Заказ Выдан";
buttonIssuedOrder.UseVisualStyleBackColor = true; buttonIssuedOrder.UseVisualStyleBackColor = true;
buttonIssuedOrder.Click += ButtonIssuedOrder_Click; buttonIssuedOrder.Click += ButtonIssuedOrder_Click;
@ -188,20 +189,27 @@
// buttonRef // buttonRef
// //
buttonRef.Anchor = AnchorStyles.Top | AnchorStyles.Right; buttonRef.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonRef.Location = new Point(998, 175); buttonRef.Location = new Point(992, 172);
buttonRef.Name = "buttonRef"; buttonRef.Name = "buttonRef";
buttonRef.Size = new Size(180, 30); buttonRef.Size = new Size(180, 30);
buttonRef.TabIndex = 6; buttonRef.TabIndex = 12;
buttonRef.Text = "Обновить список"; buttonRef.Text = "Обновить список";
buttonRef.UseVisualStyleBackColor = true; buttonRef.UseVisualStyleBackColor = true;
buttonRef.Click += ButtonRef_Click; buttonRef.Click += ButtonRef_Click;
// //
// clientsToolStripMenuItem
//
clientsToolStripMenuItem.Name = "clientsToolStripMenuItem";
clientsToolStripMenuItem.Size = new Size(224, 26);
clientsToolStripMenuItem.Text = "Клиенты";
clientsToolStripMenuItem.Click += clientsToolStripMenuItem_Click;
//
// FormMain // FormMain
// //
AllowDrop = true; AllowDrop = true;
AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1190, 450); ClientSize = new Size(1184, 554);
Controls.Add(buttonRef); Controls.Add(buttonRef);
Controls.Add(buttonIssuedOrder); Controls.Add(buttonIssuedOrder);
Controls.Add(buttonOrderReady); Controls.Add(buttonOrderReady);
@ -241,5 +249,6 @@
private ToolStripMenuItem sushisReportToolStripMenuItem; private ToolStripMenuItem sushisReportToolStripMenuItem;
private ToolStripMenuItem componentsReportПоСушиToolStripMenuItem; private ToolStripMenuItem componentsReportПоСушиToolStripMenuItem;
private ToolStripMenuItem orderReportToolStripMenuItem; private ToolStripMenuItem orderReportToolStripMenuItem;
private ToolStripMenuItem clientsToolStripMenuItem;
} }
} }

View File

@ -30,6 +30,7 @@ namespace SushiBar.Forms
{ {
dataGridView.DataSource = list; dataGridView.DataSource = list;
dataGridView.Columns["SushiId"].Visible = false; dataGridView.Columns["SushiId"].Visible = false;
dataGridView.Columns["ClientId"].Visible = false;
dataGridView.Columns["SushiName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dataGridView.Columns["SushiName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
} }
_logger.LogInformation("Загрузка заказов"); _logger.LogInformation("Загрузка заказов");
@ -167,5 +168,14 @@ namespace SushiBar.Forms
form.ShowDialog(); form.ShowDialog();
} }
} }
private void clientsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormClients));
if (service is FormClients form)
{
form.ShowDialog();
}
}
} }
} }

View File

@ -39,16 +39,19 @@ namespace SushiBar
services.AddTransient<IComponentStorage, ComponentStorage>(); services.AddTransient<IComponentStorage, ComponentStorage>();
services.AddTransient<IOrderStorage, OrderStorage>(); services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<ISushiStorage, SushiStorage>(); services.AddTransient<ISushiStorage, SushiStorage>();
services.AddTransient<IClientStorage, ClientStorage>();
services.AddTransient<IComponentLogic, ComponentLogic>(); services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IOrderLogic, OrderLogic>(); services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<ISushiLogic, SushiLogic>(); services.AddTransient<ISushiLogic, SushiLogic>();
services.AddTransient<IReportLogic, ReportLogic>(); services.AddTransient<IReportLogic, ReportLogic>();
services.AddTransient<IClientLogic, ClientLogic>();
services.AddTransient<FormMain>(); services.AddTransient<FormMain>();
services.AddTransient<FormComponent>(); services.AddTransient<FormComponent>();
services.AddTransient<FormComponents>(); services.AddTransient<FormComponents>();
services.AddTransient<FormCreateOrder>(); services.AddTransient<FormCreateOrder>();
services.AddTransient<FormClients>();
services.AddTransient<FormSushi>(); services.AddTransient<FormSushi>();
services.AddTransient<FormSushiComponent>(); services.AddTransient<FormSushiComponent>();
services.AddTransient<FormSushis>(); services.AddTransient<FormSushis>();

View File

@ -0,0 +1,117 @@
using Microsoft.Extensions.Logging;
using SushiBarContracts.BindingModels;
using SushiBarContracts.BusinessLogicsContracts;
using SushiBarContracts.SearchModels;
using SushiBarContracts.StoragesContracts;
using SushiBarContracts.ViewModels;
namespace SushiBarBusinessLogic.BusinessLogics
{
public class ClientLogic : IClientLogic
{
private readonly ILogger _logger;
private readonly IClientStorage _clientStorage;
public ClientLogic(ILogger<ClientLogic> logger, IClientStorage
componentStorage)
{
_logger = logger;
_clientStorage = componentStorage;
}
public List<ClientViewModel>? ReadList(ClientSearchModel? model)
{
_logger.LogInformation("ReadList. ClientFIO:{ClientFIO}. Id:{ Id}", model?.ClientFIO, model?.Id);
var list = model == null ? _clientStorage.GetFullList() :
_clientStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public ClientViewModel? ReadElement(ClientSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. Id:{ Id} ClientFIO:{ ClientFIO} email:{ email} password:{ password}.", model.Id, model.ClientFIO, model.Email, model.Password);
var element = _clientStorage.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(ClientBindingModel model)
{
CheckModel(model);
if (_clientStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Update(ClientBindingModel model)
{
CheckModel(model);
if (_clientStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool Delete(ClientBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_clientStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
private void CheckModel(ClientBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.ClientFIO))
{
throw new ArgumentNullException("Нет ФИО клиента",
nameof(model.ClientFIO));
}
if (string.IsNullOrEmpty(model.Email))
{
throw new ArgumentNullException("Нет Email клиента",
nameof(model.ClientFIO));
}
if (string.IsNullOrEmpty(model.Password))
{
throw new ArgumentNullException("Нет пароля клиента",
nameof(model.ClientFIO));
}
_logger.LogInformation("Client. ClientFIO:{ClientFIO}." +
"Email:{ Email}. Password:{ Password}. Id: { Id} ", model.ClientFIO, model.Email, model.Password, model.Id);
var element = _clientStorage.GetElement(new ClientSearchModel
{
Email = model.Email,
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Клиент с таким лоигном уже есть");
}
}
}
}

View File

@ -0,0 +1,44 @@
using Newtonsoft.Json;
using SushiBarContracts.ViewModels;
using System.Net.Http.Headers;
using System.Text;
namespace SushiBarClientApp
{
public static class APIClient
{
private static readonly HttpClient _client = new();
public static ClientViewModel? Client { get; set; } = null;
public static void Connect(IConfiguration configuration)
{
_client.BaseAddress = new Uri(configuration["IPAddress"]);
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public static T? GetRequest<T>(string requestUrl)
{
var response = _client.GetAsync(requestUrl);
var result = response.Result.Content.ReadAsStringAsync().Result;
if (response.Result.IsSuccessStatusCode)
{
return JsonConvert.DeserializeObject<T>(result);
}
else
{
throw new Exception(result);
}
}
public static void PostRequest<T>(string requestUrl, T model)
{
var json = JsonConvert.SerializeObject(model);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var response = _client.PostAsync(requestUrl, data);
var result = response.Result.Content.ReadAsStringAsync().Result;
if (!response.Result.IsSuccessStatusCode)
{
throw new Exception(result);
}
}
}
}

View File

@ -0,0 +1,147 @@
using Microsoft.AspNetCore.Mvc;
using SushiBarClientApp.Models;
using SushiBarContracts.BindingModels;
using SushiBarContracts.ViewModels;
using System.Diagnostics;
namespace SushiBarClientApp.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
return
View(APIClient.GetRequest<List<OrderViewModel>>($"api/main/getorders?clientId={APIClient.Client.Id}"));
}
[HttpGet]
public IActionResult Privacy()
{
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
return View(APIClient.Client);
}
[HttpPost]
public void Privacy(string login, string password, string fio)
{
if (APIClient.Client == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
if (string.IsNullOrEmpty(login) ||
string.IsNullOrEmpty(password) || string.IsNullOrEmpty(fio))
{
throw new Exception("Введите логин, пароль и ФИО");
}
APIClient.PostRequest("api/client/updatedata", new
ClientBindingModel
{
Id = APIClient.Client.Id,
ClientFIO = fio,
Email = login,
Password = password
});
APIClient.Client.ClientFIO = fio;
APIClient.Client.Email = login;
APIClient.Client.Password = password;
Response.Redirect("Index");
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel
{
RequestId =
Activity.Current?.Id ?? HttpContext.TraceIdentifier
});
}
[HttpGet]
public IActionResult Enter()
{
return View();
}
[HttpPost]
public void Enter(string login, string password)
{
if (string.IsNullOrEmpty(login) ||
string.IsNullOrEmpty(password))
{
throw new Exception("Введите логин и пароль");
}
APIClient.Client = APIClient.GetRequest<ClientViewModel>($"api/client/login?login={login}&password={password}");
if (APIClient.Client == null)
{
throw new Exception("Неверный логин/пароль");
}
Response.Redirect("Index");
}
[HttpGet]
public IActionResult Register()
{
return View();
}
[HttpPost]
public void Register(string login, string password, string fio)
{
if (string.IsNullOrEmpty(login) ||
string.IsNullOrEmpty(password) || string.IsNullOrEmpty(fio))
{
throw new Exception("Введите логин, пароль и ФИО");
}
APIClient.PostRequest("api/client/register", new
ClientBindingModel
{
ClientFIO = fio,
Email = login,
Password = password
});
Response.Redirect("Enter");
return;
}
[HttpGet]
public IActionResult Create()
{
ViewBag.Sushis = APIClient.GetRequest<List<SushiViewModel>>("api/main/getsushilist");
return View();
}
[HttpPost]
public void Create(int sushi, int count)
{
if (APIClient.Client == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
if (count <= 0)
{
throw new Exception("Количество и сумма должны быть больше 0");
}
APIClient.PostRequest("api/main/createorder", new
OrderBindingModel
{
ClientId = APIClient.Client.Id,
SushiId = sushi,
Count = count,
Sum = Calc(count, sushi)
});
Response.Redirect("Index");
}
[HttpPost]
public double Calc(int count, int sushi)
{
var _sushi =
APIClient.GetRequest<SushiViewModel>($"api/main/getsushi?sushiid={sushi}"
);
return Math.Round(count * (_sushi?.Price ?? 1), 2);
}
}
}

View File

@ -0,0 +1,9 @@
namespace SushiBarClientApp.Models
{
public class ErrorViewModel
{
public string? RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
}

View File

@ -0,0 +1,31 @@
using SushiBarClientApp;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
APIClient.Connect(builder.Configuration);
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();

View File

@ -0,0 +1,38 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:33714",
"sslPort": 44315
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5271",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7071;http://localhost:5051",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SushiBarContracts\SushiBarContracts.csproj" />
</ItemGroup>
</Project>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,25 @@
@model ErrorViewModel
@{
ViewData["Title"] = "Error";
}
<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>
@if (Model.ShowRequestId)
{
<p>
<strong>Request ID:</strong> <code>@Model.RequestId</code>
</p>
}
<h3>Development Mode</h3>
<p>
Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred.
</p>
<p>
<strong>The Development environment shouldn't be enabled for deployed applications.</strong>
It can result in displaying sensitive information from exceptions to end users.
For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
and restarting the app.
</p>

View File

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

View File

@ -0,0 +1,48 @@
/* Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification
for details on configuring this project to bundle and minify static web assets. */
a.navbar-brand {
white-space: normal;
text-align: center;
word-break: break-all;
}
a {
color: #0077cc;
}
.btn-primary {
color: #fff;
background-color: #1b6ec2;
border-color: #1861ac;
}
.nav-pills .nav-link.active, .nav-pills .show > .nav-link {
color: #fff;
background-color: #1b6ec2;
border-color: #1861ac;
}
.border-top {
border-top: 1px solid #e5e5e5;
}
.border-bottom {
border-bottom: 1px solid #e5e5e5;
}
.box-shadow {
box-shadow: 0 .25rem .75rem rgba(0, 0, 0, .05);
}
button.accept-policy {
font-size: 1rem;
line-height: inherit;
}
.footer {
position: absolute;
bottom: 0;
width: 100%;
white-space: nowrap;
line-height: 60px;
}

View File

@ -0,0 +1,2 @@
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>

View File

@ -0,0 +1,3 @@
@using SushiBarClientApp
@using SushiBarClientApp.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

View File

@ -0,0 +1,3 @@
@{
Layout = "_Layout";
}

View File

@ -0,0 +1,10 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"IPAddress": "http://localhost:5050"
}

View File

@ -0,0 +1,12 @@
using SushiBarDataModels.Models;
namespace SushiBarContracts.BindingModels
{
public class ClientBindingModel : IClientModel
{
public int Id { get; set; }
public string ClientFIO { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty;
}
}

View File

@ -7,6 +7,7 @@ namespace SushiBarContracts.BindingModels
{ {
public int Id { get; set; } public int Id { get; set; }
public int SushiId { get; set; } public int SushiId { get; set; }
public int ClientId { get; set; }
public int Count { get; set; } public int Count { get; set; }
public double Sum { get; set; } public double Sum { get; set; }
public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; public OrderStatus Status { get; set; } = OrderStatus.Неизвестен;

View File

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

View File

@ -0,0 +1,10 @@
namespace SushiBarContracts.SearchModels
{
public class ClientSearchModel
{
public int? Id { get; set; }
public string? ClientFIO { get; set; }
public string? Email { get; set; }
public string? Password { get; set; }
}
}

View File

@ -3,6 +3,7 @@
public class OrderSearchModel public class OrderSearchModel
{ {
public int? Id { get; set; } public int? Id { get; set; }
public int? ClientId { get; set; }
public DateTime? DateFrom { get; set; } public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; } public DateTime? DateTo { get; set; }
} }

View File

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

View File

@ -0,0 +1,16 @@
using System.ComponentModel;
namespace SushiBarContracts.ViewModels
{
public class ClientViewModel
{
public int Id { get; set; }
[DisplayName("ФИО клиента")]
public string ClientFIO { get; set; } = string.Empty;
[DisplayName("Логин (эл. почта)")]
public string Email { get; set; } = string.Empty;
[DisplayName("Пароль")]
public string Password { get; set; } = string.Empty;
}
}

View File

@ -9,6 +9,9 @@ namespace SushiBarContracts.ViewModels
[DisplayName("Номер")] [DisplayName("Номер")]
public int Id { get; set; } public int Id { get; set; }
public int SushiId { get; set; } public int SushiId { get; set; }
public int ClientId { get; set; }
[DisplayName("Клиент")]
public string ClientFIO { get; set; } = string.Empty;
[DisplayName("Суши")] [DisplayName("Суши")]
public string SushiName { get; set; } = string.Empty; public string SushiName { get; set; } = string.Empty;
[DisplayName("Количество")] [DisplayName("Количество")]

View File

@ -0,0 +1,9 @@
namespace SushiBarDataModels.Models
{
public interface IClientModel : IId
{
string ClientFIO { get; }
string Email { get; }
string Password { get; }
}
}

View File

@ -5,6 +5,7 @@ namespace SushiBarDataModels.Models
public interface IOrderModel : IId public interface IOrderModel : IId
{ {
int SushiId { get; } int SushiId { get; }
int ClientId { get; }
int Count { get; } int Count { get; }
double Sum { get; } double Sum { get; }
OrderStatus Status { get; } OrderStatus Status { get; }

View File

@ -0,0 +1,91 @@
using Microsoft.EntityFrameworkCore;
using SushiBarContracts.BindingModels;
using SushiBarContracts.SearchModels;
using SushiBarContracts.StoragesContracts;
using SushiBarContracts.ViewModels;
using SushiBarDatabaseImplement.Models;
namespace SushiBarDatabaseImplement.Implements
{
public class ClientStorage : IClientStorage
{
public List<ClientViewModel> GetFullList()
{
using var context = new SushiBarDatabase();
return context.Clients
.Select(c => c.GetViewModel)
.ToList();
}
public List<ClientViewModel> GetFilteredList(ClientSearchModel model)
{
using var context = new SushiBarDatabase();
return context.Clients
.Where(c =>
(!model.Id.HasValue || c.Id == model.Id) &&
(string.IsNullOrEmpty(model.ClientFIO) || c.ClientFIO.Contains(model.ClientFIO)) &&
(string.IsNullOrEmpty(model.Email) || c.Email.Contains(model.Email)) &&
(string.IsNullOrEmpty(model.Password) || c.Password.Equals(model.Password)))
.Select(c => c.GetViewModel)
.ToList();
}
public ClientViewModel? GetElement(ClientSearchModel model)
{
using var context = new SushiBarDatabase();
return context.Clients
.FirstOrDefault(c =>
(!model.Id.HasValue || c.Id == model.Id) &&
(string.IsNullOrEmpty(model.ClientFIO) || c.ClientFIO.Contains(model.ClientFIO)) &&
(string.IsNullOrEmpty(model.Email) || c.Email.Equals(model.Email)) &&
(string.IsNullOrEmpty(model.Password) || c.Password.Equals(model.Password)))?
.GetViewModel;
}
public ClientViewModel? Insert(ClientBindingModel model)
{
using var context = new SushiBarDatabase();
var newClient = Client.Create(model);
if (newClient == null)
{
return null;
}
context.Clients.Add(newClient);
context.SaveChanges();
return newClient.GetViewModel;
}
public ClientViewModel? Update(ClientBindingModel model)
{
using var context = new SushiBarDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
var client = context.Clients
.FirstOrDefault(c => c.Id == model.Id);
if (client == null)
{
return null;
}
client.Update(model);
context.SaveChanges();
transaction.Commit();
return client.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
}
public ClientViewModel? Delete(ClientBindingModel model)
{
using var context = new SushiBarDatabase();
var element = context.Clients
.FirstOrDefault(c => c.Id == model.Id);
if (element != null)
{
context.Clients.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -15,6 +15,7 @@ namespace SushiBarDatabaseImplement.Implements
using var context = new SushiBarDatabase(); using var context = new SushiBarDatabase();
return context.Orders return context.Orders
.Include(o => o.Sushi) .Include(o => o.Sushi)
.Include(o => o.Client)
.Select(o => o.GetViewModel) .Select(o => o.GetViewModel)
.ToList(); .ToList();
} }
@ -23,21 +24,22 @@ namespace SushiBarDatabaseImplement.Implements
using var context = new SushiBarDatabase(); using var context = new SushiBarDatabase();
return context.Orders return context.Orders
.Include(o => o.Sushi) .Include(o => o.Sushi)
.Where(o => .Include(o => o.Client)
(model.Id.HasValue && o.Id == model.Id) || .Where(o => (
(model.DateFrom.HasValue && model.DateTo.HasValue && model.DateFrom < o.DateCreate && o.DateCreate < model.DateTo)) (!model.Id.HasValue || o.Id == model.Id) &&
(!model.DateFrom.HasValue || o.DateCreate >= model.DateFrom) &&
(!model.DateTo.HasValue || o.DateCreate <= model.DateTo) &&
(!model.ClientId.HasValue || o.ClientId == model.ClientId)
))
.Select(o => o.GetViewModel) .Select(o => o.GetViewModel)
.ToList(); .ToList();
} }
public OrderViewModel? GetElement(OrderSearchModel model) public OrderViewModel? GetElement(OrderSearchModel model)
{ {
if (!model.Id.HasValue)
{
return null;
}
using var context = new SushiBarDatabase(); using var context = new SushiBarDatabase();
return context.Orders return context.Orders
.Include (o => o.Sushi) .Include (o => o.Sushi)
.Include(o => o.Client)
.FirstOrDefault(o => o.Id == model.Id)?.GetViewModel; .FirstOrDefault(o => o.Id == model.Id)?.GetViewModel;
} }
public OrderViewModel? Insert(OrderBindingModel model) public OrderViewModel? Insert(OrderBindingModel model)
@ -58,8 +60,10 @@ namespace SushiBarDatabaseImplement.Implements
using var transaction = context.Database.BeginTransaction(); using var transaction = context.Database.BeginTransaction();
try try
{ {
var order = context.Orders.Include(o => o.Sushi).FirstOrDefault(rec => var order = context.Orders
rec.Id == model.Id); .Include(o => o.Sushi)
.Include(o => o.Client)
.FirstOrDefault(o => o.Id == model.Id);
if (order == null) if (order == null)
{ {
return null; return null;
@ -80,6 +84,7 @@ namespace SushiBarDatabaseImplement.Implements
using var context = new SushiBarDatabase(); using var context = new SushiBarDatabase();
var element = context.Orders var element = context.Orders
.Include(o => o.Sushi) .Include(o => o.Sushi)
.Include(o => o.Client)
.FirstOrDefault(o => o.Id == model.Id); .FirstOrDefault(o => o.Id == model.Id);
if (element != null) if (element != null)
{ {

View File

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

View File

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

View File

@ -22,6 +22,31 @@ namespace SushiBarDatabaseImplement.Migrations
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("SushiBarDatabaseImplement.Models.Client", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClientFIO")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Clients");
});
modelBuilder.Entity("SushiBarDatabaseImplement.Models.Component", b => modelBuilder.Entity("SushiBarDatabaseImplement.Models.Component", b =>
{ {
b.Property<int>("Id") b.Property<int>("Id")
@ -50,6 +75,9 @@ namespace SushiBarDatabaseImplement.Migrations
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id")); NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("ClientId")
.HasColumnType("integer");
b.Property<int>("Count") b.Property<int>("Count")
.HasColumnType("integer"); .HasColumnType("integer");
@ -70,6 +98,8 @@ namespace SushiBarDatabaseImplement.Migrations
b.HasKey("Id"); b.HasKey("Id");
b.HasIndex("ClientId");
b.HasIndex("SushiId"); b.HasIndex("SushiId");
b.ToTable("Orders"); b.ToTable("Orders");
@ -123,12 +153,20 @@ namespace SushiBarDatabaseImplement.Migrations
modelBuilder.Entity("SushiBarDatabaseImplement.Models.Order", b => modelBuilder.Entity("SushiBarDatabaseImplement.Models.Order", b =>
{ {
b.HasOne("SushiBarDatabaseImplement.Models.Client", "Client")
.WithMany()
Review

Связь настроена не до конца

Связь настроена не до конца
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SushiBarDatabaseImplement.Models.Sushi", "Sushi") b.HasOne("SushiBarDatabaseImplement.Models.Sushi", "Sushi")
.WithMany("Orders") .WithMany("Orders")
.HasForeignKey("SushiId") .HasForeignKey("SushiId")
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
.IsRequired(); .IsRequired();
b.Navigation("Client");
b.Navigation("Sushi"); b.Navigation("Sushi");
}); });

View File

@ -0,0 +1,51 @@
using SushiBarContracts.BindingModels;
using SushiBarContracts.ViewModels;
using SushiBarDataModels.Models;
using System.ComponentModel.DataAnnotations;
namespace SushiBarDatabaseImplement.Models
{
public class Client : IClientModel
{
public int Id { get; private set; }
[Required]
public string ClientFIO { get; private set; } = string.Empty;
[Required]
public string Email { get; private set; } = string.Empty;
[Required]
public string Password { get; private set; } = string.Empty;
public static Client? Create(ClientBindingModel model)
{
if (model == null)
{
return null;
}
return new()
{
Id = model.Id,
ClientFIO = model.ClientFIO,
Email = model.Email,
Password = model.Password
};
}
public void Update(ClientBindingModel model)
{
if (model == null)
{
return;
}
ClientFIO = string.IsNullOrEmpty(model.ClientFIO) ? ClientFIO : model.ClientFIO;
Email = string.IsNullOrEmpty(model.Email) ? Email : model.Email;
Password = string.IsNullOrEmpty(model.Password) ? Password : model.Password;
}
public ClientViewModel GetViewModel => new()
{
Id = Id,
ClientFIO = ClientFIO,
Email = Email,
Password = Password
};
}
}

View File

@ -21,6 +21,9 @@ namespace SushiBarDatabaseImplement.Models
[Required] [Required]
public int SushiId { get; private set; } public int SushiId { get; private set; }
public virtual Sushi Sushi { get; set; } public virtual Sushi Sushi { get; set; }
public int ClientId { get; private set; }
public virtual Client Client { get; private set; }
public static Order Create(SushiBarDatabase context, OrderBindingModel model) public static Order Create(SushiBarDatabase context, OrderBindingModel model)
{ {
if (model == null) if (model == null)
@ -36,7 +39,9 @@ namespace SushiBarDatabaseImplement.Models
DateCreate = model.DateCreate, DateCreate = model.DateCreate,
DateImplement = model.DateImplement, DateImplement = model.DateImplement,
SushiId = model.SushiId, SushiId = model.SushiId,
Sushi = context.Sushis.First(x => x.Id == model.SushiId) Sushi = context.Sushis.First(x => x.Id == model.SushiId),
ClientId = model.ClientId,
Client = context.Clients.FirstOrDefault(x => x.Id == model.ClientId)
}; };
} }
public void Update(OrderBindingModel model) public void Update(OrderBindingModel model)
@ -51,13 +56,15 @@ namespace SushiBarDatabaseImplement.Models
public OrderViewModel GetViewModel => new() public OrderViewModel GetViewModel => new()
{ {
Id = Id, Id = Id,
SushiId = SushiId, SushiId = Sushi.Id,
Count = Count, Count = Count,
Sum = Sum, Sum = Sum,
Status = Status, Status = Status,
DateCreate = DateCreate, DateCreate = DateCreate,
DateImplement = DateImplement, DateImplement = DateImplement,
SushiName = Sushi.SushiName SushiName = Sushi.SushiName,
ClientId = Client.Id,
ClientFIO = Client.ClientFIO
}; };
} }
} }

View File

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

View File

@ -10,9 +10,11 @@ namespace SushiBarFileImplement
private readonly string ComponentFileName = "Component.xml"; private readonly string ComponentFileName = "Component.xml";
private readonly string OrderFileName = "Order.xml"; private readonly string OrderFileName = "Order.xml";
private readonly string SushiFileName = "Sushi.xml"; private readonly string SushiFileName = "Sushi.xml";
private readonly string ClientFileName = "Client.xml";
public List<Component> Components { get; private set; } public List<Component> Components { get; private set; }
public List<Order> Orders { get; private set; } public List<Order> Orders { get; private set; }
public List<Sushi> Sushis { get; private set; } public List<Sushi> Sushis { get; private set; }
public List<Client> Clients { get; private set; }
public static DataFileSingleton GetInstance() public static DataFileSingleton GetInstance()
{ {
if (instance == null) if (instance == null)
@ -24,11 +26,13 @@ namespace SushiBarFileImplement
public void SaveComponents() => SaveData(Components, ComponentFileName, "Components", x => x.GetXElement); public void SaveComponents() => SaveData(Components, ComponentFileName, "Components", x => x.GetXElement);
public void SaveSushis() => SaveData(Sushis, SushiFileName, "Sushis", x => x.GetXElement); public void SaveSushis() => SaveData(Sushis, SushiFileName, "Sushis", x => x.GetXElement);
public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement); public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement);
public void SaveClients() => SaveData(Clients, ClientFileName, "Client", x => x.GetXElement);
private DataFileSingleton() private DataFileSingleton()
{ {
Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!; Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!;
Sushis = LoadData(SushiFileName, "Sushi", x => Sushi.Create(x)!)!; Sushis = LoadData(SushiFileName, "Sushi", x => Sushi.Create(x)!)!;
Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!; Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!;
Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!;
} }
private static List<T>? LoadData<T>(string filename, string xmlNodeName, Func<XElement, T> selectFunction) private static List<T>? LoadData<T>(string filename, string xmlNodeName, Func<XElement, T> selectFunction)
{ {

View File

@ -0,0 +1,78 @@
using SushiBarContracts.BindingModels;
using SushiBarContracts.SearchModels;
using SushiBarContracts.ViewModels;
using SushiBarFileImplement.Models;
namespace SushiBarFileImplement.Implements
{
public class ClientStorage
{
private readonly DataFileSingleton source;
public ClientStorage()
{
source = DataFileSingleton.GetInstance();
}
public List<ClientViewModel> GetFullList()
{
return source.Clients
.Select(x => x.GetViewModel)
.ToList();
}
public List<ClientViewModel> GetFilteredList(ClientSearchModel model)
{
if (string.IsNullOrEmpty(model.ClientFIO) && string.IsNullOrEmpty(model.Email) && string.IsNullOrEmpty(model.Password))
{
return new();
}
return source.Clients
.Where(x => (string.IsNullOrEmpty(model.ClientFIO) || x.ClientFIO.Contains(model.ClientFIO) &&
string.IsNullOrEmpty(model.Email) || x.ClientFIO.Contains(model.Email) &&
string.IsNullOrEmpty(model.Password) || x.ClientFIO.Contains(model.Password)))
.Select(x => x.GetViewModel)
.ToList();
}
public ClientViewModel? GetElement(ClientSearchModel model)
{
return source.Clients
.FirstOrDefault(x => (string.IsNullOrEmpty(model.ClientFIO) || x.ClientFIO == model.ClientFIO) &&
(!model.Id.HasValue || x.Id == model.Id) && (string.IsNullOrEmpty(model.Email) || x.Email == model.Email) &&
(string.IsNullOrEmpty(model.Password) || x.Password == model.Password))
?.GetViewModel;
}
public ClientViewModel? Insert(ClientBindingModel model)
{
model.Id = source.Clients.Count > 0 ? source.Clients.Max(x =>
x.Id) + 1 : 1;
var newClient = Client.Create(model);
if (newClient == null)
{
return null;
}
source.Clients.Add(newClient);
source.SaveClients();
return newClient.GetViewModel;
}
public ClientViewModel? Update(ClientBindingModel model)
{
var client = source.Clients.FirstOrDefault(x => x.Id == model.Id);
if (client == null)
{
return null;
}
client.Update(model);
source.SaveClients();
return client.GetViewModel;
}
public ClientViewModel? Delete(ClientBindingModel model)
{
var element = source.Clients.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
source.Clients.Remove(element);
source.SaveClients();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -16,21 +16,18 @@ namespace SushiBarFileImplement.Implements
public List<OrderViewModel> GetFullList() public List<OrderViewModel> GetFullList()
{ {
return source.Orders return source.Orders
.Select(x => AttachSushiName(x.GetViewModel)) .Select(x => AccessClientStorage(AccessSushiStorage(x.GetViewModel))!)
.ToList(); .ToList();
} }
public List<OrderViewModel> GetFilteredList(OrderSearchModel model) public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{ {
if (!model.Id.HasValue)
{
return new();
}
return source.Orders return source.Orders
.Where(o => .Where(o =>
(model.Id.HasValue && o.Id == model.Id) || (!model.Id.HasValue || o.Id == model.Id) &&
(model.DateFrom.HasValue && model.DateTo.HasValue && (!model.DateFrom.HasValue || o.DateCreate >= model.DateFrom) &&
model.DateFrom < o.DateCreate && o.DateCreate < model.DateTo)) (!model.DateTo.HasValue || o.DateCreate <= model.DateTo) &&
.Select(x => AttachSushiName(x.GetViewModel)) (!model.ClientId.HasValue || o.ClientId == model.ClientId))
.Select(o => AccessClientStorage(AccessSushiStorage(o.GetViewModel))!)
.ToList(); .ToList();
} }
public OrderViewModel? GetElement(OrderSearchModel model) public OrderViewModel? GetElement(OrderSearchModel model)
@ -39,8 +36,9 @@ namespace SushiBarFileImplement.Implements
{ {
return null; return null;
} }
return AttachSushiName(source.Orders return AccessClientStorage(AccessSushiStorage(
.FirstOrDefault(x => (x.Id == model.Id))?.GetViewModel); source.Orders
.FirstOrDefault(x => (x.Id == model.Id))?.GetViewModel));
} }
public OrderViewModel? Insert(OrderBindingModel model) public OrderViewModel? Insert(OrderBindingModel model)
{ {
@ -52,18 +50,18 @@ namespace SushiBarFileImplement.Implements
} }
source.Orders.Add(newOrder); source.Orders.Add(newOrder);
source.SaveOrders(); source.SaveOrders();
return AttachSushiName(newOrder.GetViewModel); return AccessClientStorage(AccessSushiStorage(newOrder.GetViewModel));
} }
public OrderViewModel? Update(OrderBindingModel model) public OrderViewModel? Update(OrderBindingModel model)
{ {
var order = source.Orders.FirstOrDefault(x => x.Id == model.Id); var element = source.Orders.FirstOrDefault(x => x.Id == model.Id);
if (order == null) if (element == null)
{ {
return null; return null;
} }
order.Update(model); element.Update(model);
source.SaveOrders(); source.SaveOrders();
return AttachSushiName(order.GetViewModel); return AccessClientStorage(AccessSushiStorage(element.GetViewModel));
} }
public OrderViewModel? Delete(OrderBindingModel model) public OrderViewModel? Delete(OrderBindingModel model)
{ {
@ -72,14 +70,32 @@ namespace SushiBarFileImplement.Implements
{ {
source.Orders.Remove(element); source.Orders.Remove(element);
source.SaveOrders(); source.SaveOrders();
return AttachSushiName(element.GetViewModel); return AccessClientStorage(AccessSushiStorage(element.GetViewModel));
} }
return null; return null;
} }
private OrderViewModel AttachSushiName(OrderViewModel ?model) public OrderViewModel? AccessSushiStorage(OrderViewModel? model)
{ {
if (model == null) { return null; } if (model == null)
model.SushiName = source.Sushis.First(x => x.Id == model.SushiId).SushiName; return null;
foreach (var iceCream in source.Sushis)
{
if (iceCream.Id == model.SushiId)
{
model.SushiName = iceCream.SushiName;
break;
}
}
return model;
}
public OrderViewModel? AccessClientStorage(OrderViewModel? model)
{
if (model == null)
return null;
var client = source.Clients.FirstOrDefault(x => x.Id == model.Id);
if (client != null)
model.ClientFIO = client.ClientFIO;
return model; return model;
} }
} }

View File

@ -0,0 +1,66 @@
using SushiBarContracts.BindingModels;
using SushiBarContracts.ViewModels;
using System.Xml.Linq;
namespace SushiBarFileImplement.Models
{
public class Client
{
public int Id { get; private set; }
public string ClientFIO { get; private set; } = string.Empty;
public string Email { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty;
public static Client? Create(ClientBindingModel model)
{
if (model == null)
{
return null;
}
return new Client()
{
Id = model.Id,
ClientFIO = model.ClientFIO,
Email = model.Email,
Password = model.Password
};
}
public static Client? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Client()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
ClientFIO = element.Element("ClientFIO")!.Value,
Email = element.Element("Email")!.Value,
Password = element.Element("Password")!.Value
};
}
public void Update(ClientBindingModel model)
{
if (model == null)
{
return;
}
ClientFIO = model.ClientFIO;
Email = model.Email;
Password = model.Password;
}
public ClientViewModel GetViewModel => new()
{
Id = Id,
ClientFIO = ClientFIO,
Email = Email,
Password = Password
};
public XElement GetXElement => new("Client",
new XAttribute("Id", Id),
new XElement("ClientFIO", ClientFIO),
new XElement("Email", Email.ToString()),
new XElement("Password", Password.ToString())
);
}
}

View File

@ -2,11 +2,6 @@
using SushiBarContracts.ViewModels; using SushiBarContracts.ViewModels;
using SushiBarDataModels.Enums; using SushiBarDataModels.Enums;
using SushiBarDataModels.Models; using SushiBarDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq; using System.Xml.Linq;
namespace SushiBarFileImplement.Models namespace SushiBarFileImplement.Models
@ -15,6 +10,7 @@ namespace SushiBarFileImplement.Models
{ {
public int Id { get; private set; } public int Id { get; private set; }
public int SushiId { get; private set; } public int SushiId { get; private set; }
public int ClientId { get; private set; }
public int Count { get; private set; } public int Count { get; private set; }
public double Sum { get; private set; } public double Sum { get; private set; }
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен; public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен;
@ -30,6 +26,7 @@ namespace SushiBarFileImplement.Models
{ {
Id = model.Id, Id = model.Id,
SushiId = model.SushiId, SushiId = model.SushiId,
ClientId = model.ClientId,
Count = model.Count, Count = model.Count,
Sum = model.Sum, Sum = model.Sum,
Status = model.Status, Status = model.Status,
@ -47,6 +44,7 @@ namespace SushiBarFileImplement.Models
{ {
Id = Convert.ToInt32(element.Attribute("Id")!.Value), Id = Convert.ToInt32(element.Attribute("Id")!.Value),
SushiId = Convert.ToInt32(element.Element("SushiId")!.Value), SushiId = Convert.ToInt32(element.Element("SushiId")!.Value),
ClientId = Convert.ToInt32(element.Element("ClientId")!.Value),
Count = Convert.ToInt32(element.Element("Count")!.Value), Count = Convert.ToInt32(element.Element("Count")!.Value),
Sum = Convert.ToDouble(element.Element("Sum")!.Value), Sum = Convert.ToDouble(element.Element("Sum")!.Value),
Status = (OrderStatus)Enum.Parse(typeof(OrderStatus), element.Element("Status")!.Value.ToString()), Status = (OrderStatus)Enum.Parse(typeof(OrderStatus), element.Element("Status")!.Value.ToString()),
@ -68,6 +66,7 @@ namespace SushiBarFileImplement.Models
{ {
Id = Id, Id = Id,
SushiId = SushiId, SushiId = SushiId,
ClientId = ClientId,
Count = Count, Count = Count,
Sum = Sum, Sum = Sum,
Status = Status, Status = Status,
@ -77,6 +76,7 @@ namespace SushiBarFileImplement.Models
public XElement GetXElement => new("Order", public XElement GetXElement => new("Order",
new XAttribute("Id", Id), new XAttribute("Id", Id),
new XElement("SushiId", SushiId), new XElement("SushiId", SushiId),
new XElement("ClientId", ClientId),
new XElement("Count", Count), new XElement("Count", Count),
new XElement("Sum", Sum.ToString()), new XElement("Sum", Sum.ToString()),
new XElement("Status", Status.ToString()), new XElement("Status", Status.ToString()),

View File

@ -8,11 +8,13 @@ namespace SushiBarListImplement
public List<Component> Components { get; set; } public List<Component> Components { get; set; }
public List<Order> Orders { get; set; } public List<Order> Orders { get; set; }
public List<Sushi> Sushis { get; set; } public List<Sushi> Sushis { get; set; }
public List<Client> Clients { get; set; }
private DataListSingleton() private DataListSingleton()
{ {
Components = new List<Component>(); Components = new List<Component>();
Orders = new List<Order>(); Orders = new List<Order>();
Sushis = new List<Sushi>(); Sushis = new List<Sushi>();
Clients = new List<Client>();
} }
public static DataListSingleton GetInstance() public static DataListSingleton GetInstance()

View File

@ -0,0 +1,99 @@
using SushiBarContracts.BindingModels;
using SushiBarContracts.SearchModels;
using SushiBarContracts.StoragesContracts;
using SushiBarContracts.ViewModels;
using SushiBarListImplement.Models;
namespace SushiBarListImplement.Implements
{
public class ClientStorage : IClientStorage
{
private readonly DataListSingleton _source;
public ClientStorage()
{
_source = DataListSingleton.GetInstance();
}
public List<ClientViewModel> GetFullList()
{
var result = new List<ClientViewModel>();
foreach (var client in _source.Clients)
{
result.Add(client.GetViewModel);
}
return result;
}
public List<ClientViewModel> GetFilteredList(ClientSearchModel
model)
{
var result = new List<ClientViewModel>();
if (string.IsNullOrEmpty(model.ClientFIO) && string.IsNullOrEmpty(model.Email) && string.IsNullOrEmpty(model.Password))
{
return result;
}
foreach (var client in _source.Clients)
{
if (client.ClientFIO.Contains(model.ClientFIO))
{
result.Add(client.GetViewModel);
}
}
return result;
}
public ClientViewModel? GetElement(ClientSearchModel model)
{
foreach (var client in _source.Clients)
{
if ((string.IsNullOrEmpty(model.ClientFIO) || client.ClientFIO == model.ClientFIO) &&
(!model.Id.HasValue || client.Id == model.Id) && (string.IsNullOrEmpty(model.Email) || client.Email == model.Email) &&
(string.IsNullOrEmpty(model.Password) || client.Password == model.Password))
{
return client.GetViewModel;
}
}
return null;
}
public ClientViewModel? Insert(ClientBindingModel model)
{
model.Id = 1;
foreach (var client in _source.Clients)
{
if (model.Id <= client.Id)
{
model.Id = client.Id + 1;
}
}
var newClient = Client.Create(model);
if (newClient == null)
{
return null;
}
_source.Clients.Add(newClient);
return newClient.GetViewModel;
}
public ClientViewModel? Update(ClientBindingModel model)
{
foreach (var client in _source.Clients)
{
if (client.Id == model.Id)
{
client.Update(model);
return client.GetViewModel;
}
}
return null;
}
public ClientViewModel? Delete(ClientBindingModel model)
{
for (int i = 0; i < _source.Clients.Count; ++i)
{
if (_source.Clients[i].Id == model.Id)
{
var element = _source.Clients[i];
_source.Clients.RemoveAt(i);
return element.GetViewModel;
}
}
return null;
}
}
}

View File

@ -18,7 +18,7 @@ namespace SushiBarListImplement.Implements
var result = new List<OrderViewModel>(); var result = new List<OrderViewModel>();
foreach (var order in _source.Orders) foreach (var order in _source.Orders)
{ {
result.Add(AttachSushiName(order.GetViewModel)); result.Add(AccessClientStorage(AccessSushiStorage(order.GetViewModel)));
} }
return result; return result;
} }
@ -29,9 +29,9 @@ namespace SushiBarListImplement.Implements
{ {
if (order.Id == model.Id || if (order.Id == model.Id ||
(model.DateFrom.HasValue && model.DateTo.HasValue && (model.DateFrom.HasValue && model.DateTo.HasValue &&
model.DateFrom < order.DateCreate && order.DateCreate < model.DateTo))) model.DateFrom < order.DateCreate && order.DateCreate < model.DateTo))
{ {
result.Add(AttachSushiName(order.GetViewModel)); result.Add(AccessClientStorage(AccessSushiStorage(order.GetViewModel)));
} }
} }
return result; return result;
@ -46,7 +46,7 @@ namespace SushiBarListImplement.Implements
{ {
if (model.Id.HasValue && order.Id == model.Id) if (model.Id.HasValue && order.Id == model.Id)
{ {
return AttachSushiName(order.GetViewModel); return AccessClientStorage(AccessSushiStorage(order.GetViewModel));
} }
} }
return null; return null;
@ -67,7 +67,7 @@ namespace SushiBarListImplement.Implements
return null; return null;
} }
_source.Orders.Add(newOrder); _source.Orders.Add(newOrder);
return AttachSushiName(newOrder.GetViewModel); return AccessClientStorage(AccessSushiStorage(newOrder.GetViewModel));
} }
public OrderViewModel? Update(OrderBindingModel model) public OrderViewModel? Update(OrderBindingModel model)
{ {
@ -76,7 +76,7 @@ namespace SushiBarListImplement.Implements
if (order.Id == model.Id) if (order.Id == model.Id)
{ {
order.Update(model); order.Update(model);
return AttachSushiName(order.GetViewModel); return AccessClientStorage(AccessSushiStorage(order.GetViewModel));
} }
} }
return null; return null;
@ -89,21 +89,29 @@ namespace SushiBarListImplement.Implements
{ {
var element = _source.Orders[i]; var element = _source.Orders[i];
_source.Orders.RemoveAt(i); _source.Orders.RemoveAt(i);
return AttachSushiName(element.GetViewModel); return AccessClientStorage(AccessSushiStorage(element.GetViewModel));
} }
} }
return null; return null;
} }
private OrderViewModel AttachSushiName(OrderViewModel model) public OrderViewModel AccessSushiStorage(OrderViewModel model)
{ {
foreach (var sushi in _source.Sushis) foreach (var iceCream in _source.Sushis)
{ {
if (sushi.Id == model.SushiId) if (iceCream.Id == model.SushiId)
{ {
model.SushiName = sushi.SushiName; model.SushiName = iceCream.SushiName;
break;
}
}
return model; return model;
} }
}
public OrderViewModel AccessClientStorage(OrderViewModel model)
{
var client = _source.Clients.FirstOrDefault(x => x.Id == model.ClientId);
if (client != null)
model.ClientFIO = client.ClientFIO;
return model; return model;
} }
} }

View File

@ -0,0 +1,67 @@
using SushiBarContracts.BindingModels;
using SushiBarContracts.ViewModels;
using SushiBarDataModels.Models;
using System.Xml.Linq;
namespace SushiBarListImplement.Models
{
public class Client : IClientModel
{
public int Id { get; private set; }
public string ClientFIO { get; private set; } = string.Empty;
public string Email { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty;
public static Client? Create(ClientBindingModel model)
{
if (model == null)
{
return null;
}
return new Client()
{
Id = model.Id,
ClientFIO = model.ClientFIO,
Email = model.Email,
Password = model.Password
};
}
public static Client? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Client()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
ClientFIO = element.Element("ClientFIO")!.Value,
Email = element.Element("Email")!.Value,
Password = element.Element("Password")!.Value
};
}
public void Update(ClientBindingModel model)
{
if (model == null)
{
return;
}
ClientFIO = model.ClientFIO;
Email = model.Email;
Password = model.Password;
}
public ClientViewModel GetViewModel => new()
{
Id = Id,
ClientFIO = ClientFIO,
Email = Email,
Password = Password
};
public XElement GetXElement => new("Client",
new XAttribute("Id", Id),
new XElement("ClientFIO", ClientFIO),
new XElement("Email", Email.ToString()),
new XElement("Password", Password.ToString())
);
}
}

View File

@ -14,6 +14,7 @@ namespace SushiBarListImplement.Models
{ {
public int Id { get; private set; } public int Id { get; private set; }
public int SushiId { get; private set; } public int SushiId { get; private set; }
public int ClientId { get; private set; }
public int Count { get; private set; } public int Count { get; private set; }
public double Sum { get; private set; } public double Sum { get; private set; }
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен; public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен;
@ -28,6 +29,7 @@ namespace SushiBarListImplement.Models
{ {
Id = model.Id, Id = model.Id,
SushiId = model.SushiId, SushiId = model.SushiId,
ClientId = model.ClientId,
Count = model.Count, Count = model.Count,
Sum = model.Sum, Sum = model.Sum,
Status = model.Status, Status = model.Status,
@ -42,6 +44,7 @@ namespace SushiBarListImplement.Models
return; return;
} }
SushiId = model.SushiId; SushiId = model.SushiId;
ClientId = model.ClientId;
Count = model.Count; Count = model.Count;
Sum = model.Sum; Sum = model.Sum;
Status = model.Status; Status = model.Status;
@ -51,6 +54,7 @@ namespace SushiBarListImplement.Models
{ {
Id = Id, Id = Id,
SushiId = SushiId, SushiId = SushiId,
ClientId = ClientId,
Count = Count, Count = Count,
Sum = Sum, Sum = Sum,
Status = Status, Status = Status,

View File

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

View File

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

View File

@ -0,0 +1,36 @@
using SushiBarBusinessLogic.BusinessLogics;
using SushiBarContracts.BusinessLogicsContracts;
using SushiBarContracts.StoragesContracts;
using SushiBarDatabaseImplement.Implements;
var builder = WebApplication.CreateBuilder(args);
builder.Logging.SetMinimumLevel(LogLevel.Information);
builder.Logging.AddLog4Net("log4net.config");
// Add services to the container.
builder.Services.AddSingleton<IClientStorage, ClientStorage>();
builder.Services.AddSingleton<IOrderStorage, OrderStorage>();
builder.Services.AddSingleton<ISushiStorage, SushiStorage>();
builder.Services.AddSingleton<IOrderLogic, OrderLogic>();
builder.Services.AddSingleton<IClientLogic, ClientLogic>();
builder.Services.AddSingleton<ISushiLogic, SushiLogic>();
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseAuthorization();
app.MapControllers();
app.Run();

View File

@ -0,0 +1,41 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:29766",
"sslPort": 44390
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5056",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7070;http://localhost:5050",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Log4Net.AspNetCore" Version="8.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SushiBarBusinessLogic\SushiBarBusinessLogic.csproj" />
<ProjectReference Include="..\SushiBarContracts\SushiBarContracts.csproj" />
<ProjectReference Include="..\SushiBarDatabaseImplement\SushiBarDatabaseImplement.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}

View File

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