lab2-hard

This commit is contained in:
DeerElk 2024-06-20 06:10:16 +04:00
parent c30c2d570f
commit 7136015577
30 changed files with 2449 additions and 28 deletions

1
.gitignore vendored
View File

@ -398,3 +398,4 @@ FodyWeavers.xsd
# JetBrains Rider # JetBrains Rider
*.sln.iml *.sln.iml
/Confectionery/ImplementationExtensions

View File

@ -38,7 +38,10 @@
referencesToolStripMenuItem = new ToolStripMenuItem(); referencesToolStripMenuItem = new ToolStripMenuItem();
componentsToolStripMenuItem = new ToolStripMenuItem(); componentsToolStripMenuItem = new ToolStripMenuItem();
pastriesToolStripMenuItem = new ToolStripMenuItem(); pastriesToolStripMenuItem = new ToolStripMenuItem();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); shopsToolStripMenuItem = new ToolStripMenuItem();
supplyToolStripMenuItem = new ToolStripMenuItem();
sellToolStripMenuItem = new ToolStripMenuItem();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
menuStrip.SuspendLayout(); menuStrip.SuspendLayout();
SuspendLayout(); SuspendLayout();
// //
@ -118,10 +121,10 @@
menuStrip.Size = new Size(147, 33); menuStrip.Size = new Size(147, 33);
menuStrip.TabIndex = 8; menuStrip.TabIndex = 8;
menuStrip.Text = "menuStrip1"; menuStrip.Text = "menuStrip1";
// //
// referencesToolStripMenuItem // referencesToolStripMenuItem
// //
referencesToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { componentsToolStripMenuItem, pastriesToolStripMenuItem }); referencesToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { componentsToolStripMenuItem, pastriesToolStripMenuItem, shopsToolStripMenuItem, supplyToolStripMenuItem, sellToolStripMenuItem });
referencesToolStripMenuItem.Name = "referencesToolStripMenuItem"; referencesToolStripMenuItem.Name = "referencesToolStripMenuItem";
referencesToolStripMenuItem.Size = new Size(139, 29); referencesToolStripMenuItem.Size = new Size(139, 29);
referencesToolStripMenuItem.Text = "Справочники"; referencesToolStripMenuItem.Text = "Справочники";
@ -139,10 +142,31 @@
pastriesToolStripMenuItem.Size = new Size(298, 34); pastriesToolStripMenuItem.Size = new Size(298, 34);
pastriesToolStripMenuItem.Text = "Кондитерские изделия"; pastriesToolStripMenuItem.Text = "Кондитерские изделия";
pastriesToolStripMenuItem.Click += PastriesToolStripMenuItem_Click; pastriesToolStripMenuItem.Click += PastriesToolStripMenuItem_Click;
// //
// FormMain // shopsToolStripMenuItem
// //
AutoScaleDimensions = new SizeF(10F, 25F); shopsToolStripMenuItem.Name = "shopsToolStripMenuItem";
shopsToolStripMenuItem.Size = new Size(298, 34);
shopsToolStripMenuItem.Text = "Магазины";
shopsToolStripMenuItem.Click += ShopsToolStripMenuItem_Click;
//
// supplyToolStripMenuItem
//
supplyToolStripMenuItem.Name = "supplyToolStripMenuItem";
supplyToolStripMenuItem.Size = new Size(298, 34);
supplyToolStripMenuItem.Text = "Поставки";
supplyToolStripMenuItem.Click += SupplyToolStripMenuItem_Click;
//
// sellToolStripMenuItem
//
sellToolStripMenuItem.Name = "sellToolStripMenuItem";
sellToolStripMenuItem.Size = new Size(224, 26);
sellToolStripMenuItem.Text = "Продажи";
sellToolStripMenuItem.Click += SellToolStripMenuItem_Click;
//
// FormMain
//
AutoScaleDimensions = new SizeF(10F, 25F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1154, 442); ClientSize = new Size(1154, 442);
Controls.Add(menuStrip); Controls.Add(menuStrip);
@ -175,5 +199,8 @@
private ToolStripMenuItem referencesToolStripMenuItem; private ToolStripMenuItem referencesToolStripMenuItem;
private ToolStripMenuItem pastriesToolStripMenuItem; private ToolStripMenuItem pastriesToolStripMenuItem;
private ToolStripMenuItem componentsToolStripMenuItem; private ToolStripMenuItem componentsToolStripMenuItem;
} private ToolStripMenuItem shopsToolStripMenuItem;
private ToolStripMenuItem supplyToolStripMenuItem;
private ToolStripMenuItem sellToolStripMenuItem;
}
} }

View File

@ -60,7 +60,37 @@ namespace ConfectioneryView
form.ShowDialog(); form.ShowDialog();
} }
} }
private void ButtonCreateOrder_Click(object sender, EventArgs e) private void ShopsToolStripMenuItem_Click(object sender,
EventArgs e)
{
var service = Program.ServiceProvider?.GetService(
typeof(FormShops));
if (service is FormShops form)
{
form.ShowDialog();
}
}
private void SupplyToolStripMenuItem_Click(object sender,
EventArgs e)
{
var service = Program.ServiceProvider?.GetService(
typeof(FormSupply));
if (service is FormSupply form)
{
form.ShowDialog();
}
}
private void SellToolStripMenuItem_Click(object sender,
EventArgs e)
{
var service = Program.ServiceProvider?.GetService(
typeof(FormSell));
if (service is FormSell form)
{
form.ShowDialog();
}
}
private void ButtonCreateOrder_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService( var service = Program.ServiceProvider?.GetService(
typeof(FormCreateOrder)); typeof(FormCreateOrder));

View File

@ -0,0 +1,130 @@
namespace ConfectioneryView
{
partial class FormSell
{
/// <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()
{
comboBoxPastry = new ComboBox();
labelPastry = new Label();
labelCount = new Label();
textBoxCount = new TextBox();
buttonSave = new Button();
buttonCancel = new Button();
SuspendLayout();
//
// comboBoxPastry
//
comboBoxPastry.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
comboBoxPastry.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxPastry.FormattingEnabled = true;
comboBoxPastry.Location = new Point(245, 21);
comboBoxPastry.Margin = new Padding(4, 5, 4, 5);
comboBoxPastry.Name = "comboBoxPastry";
comboBoxPastry.Size = new Size(321, 33);
comboBoxPastry.TabIndex = 0;
//
// labelPastry
//
labelPastry.AutoSize = true;
labelPastry.Location = new Point(16, 21);
labelPastry.Margin = new Padding(4, 0, 4, 0);
labelPastry.Name = "labelPastry";
labelPastry.Size = new Size(201, 25);
labelPastry.TabIndex = 1;
labelPastry.Text = "Кондитерское изделие:";
//
// labelCount
//
labelCount.AutoSize = true;
labelCount.Location = new Point(16, 66);
labelCount.Margin = new Padding(4, 0, 4, 0);
labelCount.Name = "labelCount";
labelCount.Size = new Size(111, 25);
labelCount.TabIndex = 2;
labelCount.Text = "Количество:";
//
// textBoxCount
//
textBoxCount.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
textBoxCount.Location = new Point(245, 64);
textBoxCount.Margin = new Padding(4, 5, 4, 5);
textBoxCount.Name = "textBoxCount";
textBoxCount.Size = new Size(321, 31);
textBoxCount.TabIndex = 3;
//
// buttonSave
//
buttonSave.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonSave.Location = new Point(336, 148);
buttonSave.Margin = new Padding(4, 5, 4, 5);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(112, 34);
buttonSave.TabIndex = 4;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// buttonCancel
//
buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonCancel.Location = new Point(454, 148);
buttonCancel.Margin = new Padding(4, 5, 4, 5);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(112, 34);
buttonCancel.TabIndex = 5;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// FormSell
//
AutoScaleDimensions = new SizeF(10F, 25F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(578, 194);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(textBoxCount);
Controls.Add(labelCount);
Controls.Add(labelPastry);
Controls.Add(comboBoxPastry);
Margin = new Padding(4, 5, 4, 5);
Name = "FormSell";
Text = "Продажа";
ResumeLayout(false);
PerformLayout();
}
#endregion
private ComboBox comboBoxPastry;
private Label labelPastry;
private Label labelCount;
private TextBox textBoxCount;
private Button buttonSave;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,105 @@
using ConfectioneryContracts.BusinessLogicsContracts;
using ConfectioneryContracts.ViewModels;
using ConfectioneryDataModels.Models;
namespace ConfectioneryView
{
public partial class FormSell : Form
{
private readonly List<PastryViewModel>? _pastryList;
IShopLogic _shopLogic;
IPastryLogic _pastryLogic;
public FormSell(IPastryLogic PastryLogic, IShopLogic shopLogic)
{
InitializeComponent();
_shopLogic = shopLogic;
_pastryLogic = PastryLogic;
_pastryList = PastryLogic.ReadList(null);
if (_pastryList != null)
{
comboBoxPastry.DisplayMember = "PastryName";
comboBoxPastry.ValueMember = "Id";
comboBoxPastry.DataSource = _pastryList;
comboBoxPastry.SelectedItem = null;
}
}
public int PastryId
{
get
{
return Convert.ToInt32(comboBoxPastry.SelectedValue);
}
set
{
comboBoxPastry.SelectedValue = value;
}
}
public IPastryModel? PastryModel
{
get
{
if (_pastryList == null)
{
return null;
}
foreach (var elem in _pastryList)
{
if (elem.Id == PastryId)
{
return elem;
}
}
return null;
}
}
public int Count
{
get { return Convert.ToInt32(textBoxCount.Text); }
set
{ textBoxCount.Text = value.ToString(); }
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCount.Text))
{
MessageBox.Show("Заполните поле Количество", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxPastry.SelectedValue == null)
{
MessageBox.Show("Выберите кондитерское изделие", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
int count = Convert.ToInt32(textBoxCount.Text);
var pastry = _pastryLogic.ReadElement(new() {
Id = Convert.ToInt32(comboBoxPastry.SelectedValue) });
if (pastry == null)
return;
bool res = _shopLogic.MakeSell(pastry, count);
if (!res)
{
throw new Exception("Ошибка при продаже.");
}
MessageBox.Show("Продажа прошла успешно");
DialogResult = DialogResult.OK;
Close();
}
catch (Exception err)
{
MessageBox.Show("Ошибка продажи");
return;
}
}
}
}

View File

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

View File

@ -0,0 +1,237 @@
namespace ConfectioneryView
{
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()
{
dateTimePicker = new DateTimePicker();
textBoxName = new TextBox();
textBoxAddress = new TextBox();
NameLabel = new Label();
AdressLabel = new Label();
DateLabel = new Label();
buttonSave = new Button();
buttonCancel = new Button();
dataGridView = new DataGridView();
ID = new DataGridViewTextBoxColumn();
PastryName = new DataGridViewTextBoxColumn();
Price = new DataGridViewTextBoxColumn();
Count = new DataGridViewTextBoxColumn();
CapacityUpDown = new NumericUpDown();
CapacityLabel = new Label();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
((System.ComponentModel.ISupportInitialize)CapacityUpDown).BeginInit();
SuspendLayout();
//
// dateTimePicker
//
dateTimePicker.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
dateTimePicker.Location = new Point(170, 111);
dateTimePicker.Margin = new Padding(4, 5, 4, 5);
dateTimePicker.Name = "dateTimePicker";
dateTimePicker.Size = new Size(396, 31);
dateTimePicker.TabIndex = 0;
//
// textBoxName
//
textBoxName.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
textBoxName.Location = new Point(170, 21);
textBoxName.Margin = new Padding(4, 5, 4, 5);
textBoxName.Name = "textBoxName";
textBoxName.Size = new Size(396, 31);
textBoxName.TabIndex = 1;
//
// textBoxAddress
//
textBoxAddress.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
textBoxAddress.Location = new Point(170, 66);
textBoxAddress.Margin = new Padding(4, 5, 4, 5);
textBoxAddress.Name = "textBoxAddress";
textBoxAddress.Size = new Size(396, 31);
textBoxAddress.TabIndex = 2;
//
// NameLabel
//
NameLabel.AutoSize = true;
NameLabel.Location = new Point(16, 21);
NameLabel.Margin = new Padding(4, 0, 4, 0);
NameLabel.Name = "NameLabel";
NameLabel.Size = new Size(94, 25);
NameLabel.TabIndex = 3;
NameLabel.Text = "Название:";
//
// AdressLabel
//
AdressLabel.AutoSize = true;
AdressLabel.Location = new Point(16, 66);
AdressLabel.Margin = new Padding(4, 0, 4, 0);
AdressLabel.Name = "AdressLabel";
AdressLabel.Size = new Size(66, 25);
AdressLabel.TabIndex = 4;
AdressLabel.Text = "Адрес:";
//
// DateLabel
//
DateLabel.AutoSize = true;
DateLabel.Location = new Point(16, 111);
DateLabel.Margin = new Padding(4, 0, 4, 0);
DateLabel.Name = "DateLabel";
DateLabel.Size = new Size(53, 25);
DateLabel.TabIndex = 5;
DateLabel.Text = "Дата:";
//
// buttonSave
//
buttonSave.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonSave.Location = new Point(636, 404);
buttonSave.Margin = new Padding(4, 5, 4, 5);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(112, 34);
buttonSave.TabIndex = 6;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// buttonCancel
//
buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonCancel.Location = new Point(754, 404);
buttonCancel.Margin = new Padding(4, 5, 4, 5);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(112, 34);
buttonCancel.TabIndex = 7;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// dataGridView
//
dataGridView.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
dataGridView.BackgroundColor = SystemColors.Window;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Columns.AddRange(new DataGridViewColumn[] { ID, PastryName, Price, Count });
dataGridView.Location = new Point(16, 202);
dataGridView.Margin = new Padding(4, 5, 4, 5);
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersWidth = 51;
dataGridView.Size = new Size(850, 192);
dataGridView.TabIndex = 8;
//
// ID
//
ID.HeaderText = "id";
ID.MinimumWidth = 6;
ID.Name = "ID";
ID.Visible = false;
ID.Width = 125;
//
// PastryName
//
PastryName.HeaderText = "Название";
PastryName.MinimumWidth = 6;
PastryName.Name = "PastryName";
PastryName.ReadOnly = true;
PastryName.Width = 150;
//
// Price
//
Price.HeaderText = "Цена";
Price.MinimumWidth = 6;
Price.Name = "Price";
Price.ReadOnly = true;
Price.Width = 125;
//
// Count
//
Count.HeaderText = "Количество";
Count.MinimumWidth = 6;
Count.Name = "Count";
Count.ReadOnly = true;
Count.Width = 125;
//
// CapacityUpDown
//
CapacityUpDown.Location = new Point(170, 156);
CapacityUpDown.Maximum = new decimal(new int[] { 10000, 0, 0, 0 });
CapacityUpDown.Name = "CapacityUpDown";
CapacityUpDown.Size = new Size(120, 31);
CapacityUpDown.TabIndex = 9;
//
// CapacityLabel
//
CapacityLabel.AutoSize = true;
CapacityLabel.Location = new Point(16, 156);
CapacityLabel.Name = "CapacityLabel";
CapacityLabel.Size = new Size(121, 25);
CapacityLabel.TabIndex = 10;
CapacityLabel.Text = "Вместимость:";
//
// FormShop
//
AutoScaleDimensions = new SizeF(10F, 25F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(878, 444);
Controls.Add(dataGridView);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(DateLabel);
Controls.Add(AdressLabel);
Controls.Add(NameLabel);
Controls.Add(textBoxAddress);
Controls.Add(textBoxName);
Controls.Add(dateTimePicker);
Controls.Add(CapacityLabel);
Controls.Add(CapacityUpDown);
Margin = new Padding(4, 5, 4, 5);
Name = "FormShop";
Text = "Магазин";
Load += FormShop_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
((System.ComponentModel.ISupportInitialize)CapacityUpDown).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private DateTimePicker dateTimePicker;
private TextBox textBoxName;
private TextBox textBoxAddress;
private Label NameLabel;
private Label AdressLabel;
private Label DateLabel;
private Button buttonSave;
private Button buttonCancel;
private DataGridView dataGridView;
private DataGridViewTextBoxColumn ID;
private DataGridViewTextBoxColumn PastryName;
private DataGridViewTextBoxColumn Price;
private DataGridViewTextBoxColumn Count;
private NumericUpDown CapacityUpDown;
private Label CapacityLabel;
}
}

View File

@ -0,0 +1,122 @@
using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.BusinessLogicsContracts;
using ConfectioneryContracts.SearchModels;
using ConfectioneryDataModels.Models;
using Microsoft.Extensions.Logging;
using System.Windows.Forms;
namespace ConfectioneryView
{
public partial class FormShop : Form
{
private readonly ILogger _logger;
private readonly IShopLogic _logic;
public int? _id;
private Dictionary<int, (IPastryModel, int)> _pastries;
public FormShop(ILogger<FormShop> logger, IShopLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormShop_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
_logger.LogInformation("Загрузка магазина");
try
{
var shop = _logic.ReadElement(
new ShopSearchModel { Id = _id });
if (shop != null)
{
textBoxName.Text = shop.ShopName;
textBoxAddress.Text = shop.Address;
dateTimePicker.Text = shop.DateOpen.ToString();
CapacityUpDown.Value = shop.MaxCapacity;
_pastries = shop.ShopPastries ??
new Dictionary<int, (IPastryModel, int)>();
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки магазина");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void LoadData()
{
_logger.LogInformation("Загрузка товаров магазина");
try
{
if (_pastries != null)
{
foreach (var Pastry in _pastries)
{
dataGridView.Rows.Add(new object[] {
Pastry.Key, Pastry.Value.Item1.PastryName,
Pastry.Value.Item1.Price, Pastry.Value.Item2 });
}
}
}
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 void ButtonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxName.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 = textBoxName.Text,
Address = textBoxAddress.Text,
DateOpen = dateTimePicker.Value.Date,
MaxCapacity = Convert.ToInt32(CapacityUpDown.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);
}
}
}
}

View File

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

View File

@ -0,0 +1,125 @@
namespace ConfectioneryView
{
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()
{
dataGridView = new DataGridView();
buttonAdd = new Button();
buttonUpd = new Button();
buttonRef = new Button();
buttonDel = new Button();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// dataGridView
//
dataGridView.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
dataGridView.BackgroundColor = SystemColors.Window;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(0, 0);
dataGridView.Margin = new Padding(4, 5, 4, 5);
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersWidth = 51;
dataGridView.Size = new Size(742, 444);
dataGridView.TabIndex = 0;
//
// buttonAdd
//
buttonAdd.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonAdd.Location = new Point(754, 12);
buttonAdd.Margin = new Padding(4, 5, 4, 5);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(112, 56);
buttonAdd.TabIndex = 1;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// buttonUpd
//
buttonUpd.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonUpd.Location = new Point(754, 74);
buttonUpd.Margin = new Padding(4, 5, 4, 5);
buttonUpd.Name = "buttonUpd";
buttonUpd.Size = new Size(112, 56);
buttonUpd.TabIndex = 2;
buttonUpd.Text = "Изменить";
buttonUpd.UseVisualStyleBackColor = true;
buttonUpd.Click += ButtonUpd_Click;
//
// buttonRef
//
buttonRef.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonRef.Location = new Point(754, 136);
buttonRef.Margin = new Padding(4, 5, 4, 5);
buttonRef.Name = "buttonRef";
buttonRef.Size = new Size(112, 56);
buttonRef.TabIndex = 3;
buttonRef.Text = "Обновить";
buttonRef.UseVisualStyleBackColor = true;
buttonRef.Click += ButtonRef_Click;
//
// buttonDel
//
buttonDel.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonDel.Location = new Point(754, 198);
buttonDel.Margin = new Padding(4, 5, 4, 5);
buttonDel.Name = "buttonDel";
buttonDel.Size = new Size(112, 56);
buttonDel.TabIndex = 4;
buttonDel.Text = "Удалить";
buttonDel.UseVisualStyleBackColor = true;
buttonDel.Click += ButtonDel_Click;
//
// FormShops
//
AutoScaleDimensions = new SizeF(10F, 25F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(878, 444);
Controls.Add(buttonDel);
Controls.Add(buttonRef);
Controls.Add(buttonUpd);
Controls.Add(buttonAdd);
Controls.Add(dataGridView);
Margin = new Padding(4, 5, 4, 5);
Name = "FormShops";
Text = "Магазины";
Load += FormShops_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
private Button buttonAdd;
private Button buttonUpd;
private Button buttonRef;
private Button buttonDel;
}
}

View File

@ -0,0 +1,116 @@
using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
using System.Windows.Forms;
namespace ConfectioneryView
{
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 LoadData()
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["ShopName"].AutoSizeMode =
DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["Address"].AutoSizeMode =
DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["DateOpen"].AutoSizeMode =
DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["ShopPastries"].Visible = false;
}
_logger.LogInformation("Загрузка магазинов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки магазинов");
MessageBox.Show(ex.Message, "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void FormShops_Load(object sender, EventArgs e)
{
LoadData();
}
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)
{
var tmp = Convert.ToInt32(
dataGridView.SelectedRows[0].Cells["Id"].Value);
form._id = Convert.ToInt32(
dataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
}
private void ButtonRef_Click(object sender, EventArgs e)
{
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);
}
}
}
}
}
}

View File

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

View File

@ -0,0 +1,157 @@
namespace ConfectioneryView
{
partial class FormSupply
{
/// <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()
{
comboBoxShop = new ComboBox();
comboBoxPastry = new ComboBox();
textBoxCount = new TextBox();
buttonSave = new Button();
buttonCancel = new Button();
labelShop = new Label();
labelPastry = new Label();
labelCount = new Label();
SuspendLayout();
//
// comboBoxShop
//
comboBoxShop.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
comboBoxShop.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxShop.FormattingEnabled = true;
comboBoxShop.Location = new Point(229, 21);
comboBoxShop.Margin = new Padding(4, 5, 4, 5);
comboBoxShop.Name = "comboBoxShop";
comboBoxShop.Size = new Size(337, 33);
comboBoxShop.TabIndex = 0;
//
// comboBoxPastry
//
comboBoxPastry.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
comboBoxPastry.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxPastry.FormattingEnabled = true;
comboBoxPastry.Location = new Point(229, 66);
comboBoxPastry.Margin = new Padding(4, 5, 4, 5);
comboBoxPastry.Name = "comboBoxPastry";
comboBoxPastry.Size = new Size(337, 33);
comboBoxPastry.TabIndex = 1;
//
// textBoxCount
//
textBoxCount.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
textBoxCount.Location = new Point(229, 112);
textBoxCount.Margin = new Padding(4, 5, 4, 5);
textBoxCount.Name = "textBoxCount";
textBoxCount.Size = new Size(337, 31);
textBoxCount.TabIndex = 2;
//
// buttonSave
//
buttonSave.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonSave.Location = new Point(336, 148);
buttonSave.Margin = new Padding(4, 5, 4, 5);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(112, 34);
buttonSave.TabIndex = 3;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// buttonCancel
//
buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonCancel.Location = new Point(454, 148);
buttonCancel.Margin = new Padding(4, 5, 4, 5);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(112, 34);
buttonCancel.TabIndex = 4;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// labelShop
//
labelShop.AutoSize = true;
labelShop.Location = new Point(16, 21);
labelShop.Margin = new Padding(4, 0, 4, 0);
labelShop.Name = "labelShop";
labelShop.Size = new Size(85, 25);
labelShop.TabIndex = 5;
labelShop.Text = "Магазин:";
//
// labelPastry
//
labelPastry.AutoSize = true;
labelPastry.Location = new Point(16, 66);
labelPastry.Margin = new Padding(4, 0, 4, 0);
labelPastry.Name = "labelPastry";
labelPastry.Size = new Size(201, 25);
labelPastry.TabIndex = 6;
labelPastry.Text = "Кондитерское изделие:";
//
// labelCount
//
labelCount.AutoSize = true;
labelCount.Location = new Point(16, 112);
labelCount.Margin = new Padding(4, 0, 4, 0);
labelCount.Name = "labelCount";
labelCount.Size = new Size(111, 25);
labelCount.TabIndex = 7;
labelCount.Text = "Количество:";
//
// FormSupply
//
AutoScaleDimensions = new SizeF(10F, 25F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(578, 194);
Controls.Add(labelCount);
Controls.Add(labelPastry);
Controls.Add(labelShop);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(textBoxCount);
Controls.Add(comboBoxPastry);
Controls.Add(comboBoxShop);
Margin = new Padding(4, 5, 4, 5);
Name = "FormSupply";
Text = "Поставки";
ResumeLayout(false);
PerformLayout();
}
#endregion
private ComboBox comboBoxShop;
private ComboBox comboBoxPastry;
private TextBox textBoxCount;
private Button buttonSave;
private Button buttonCancel;
private Label labelShop;
private Label labelPastry;
private Label labelCount;
}
}

View File

@ -0,0 +1,132 @@
using ConfectioneryContracts.BusinessLogicsContracts;
using ConfectioneryContracts.SearchModels;
using ConfectioneryContracts.ViewModels;
using ConfectioneryDataModels.Models;
namespace ConfectioneryView
{
public partial class FormSupply : Form
{
private readonly List<PastryViewModel>? _pastryList;
private readonly List<ShopViewModel>? _shopsList;
IShopLogic _shopLogic;
IPastryLogic _pastryLogic;
public int ShopId
{
get
{
return Convert.ToInt32(comboBoxShop.SelectedValue);
}
set
{
comboBoxShop.SelectedValue = value;
}
}
public int PastryId
{
get
{
return Convert.ToInt32(comboBoxPastry.SelectedValue);
}
set
{
comboBoxPastry.SelectedValue = value;
}
}
public IPastryModel? PastryModel
{
get
{
if (_pastryList == null)
{
return null;
}
foreach (var elem in _pastryList)
{
if (elem.Id == PastryId)
{
return elem;
}
}
return null;
}
}
public int Count
{
get { return Convert.ToInt32(textBoxCount.Text); }
set
{ textBoxCount.Text = value.ToString(); }
}
public FormSupply(IPastryLogic PastryLogic, IShopLogic shopLogic)
{
InitializeComponent();
_shopLogic = shopLogic;
_pastryLogic = PastryLogic;
_pastryList = PastryLogic.ReadList(null);
_shopsList = shopLogic.ReadList(null);
if (_pastryList != null)
{
comboBoxPastry.DisplayMember = "PastryName";
comboBoxPastry.ValueMember = "Id";
comboBoxPastry.DataSource = _pastryList;
comboBoxPastry.SelectedItem = null;
}
if (_shopsList != null)
{
comboBoxShop.DisplayMember = "ShopName";
comboBoxShop.ValueMember = "Id";
comboBoxShop.DataSource = _shopsList;
comboBoxShop.SelectedItem = null;
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCount.Text))
{
MessageBox.Show("Заполните поле Количество", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxPastry.SelectedValue == null)
{
MessageBox.Show("Выберите кондитерское изделие", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxShop.SelectedValue == null)
{
MessageBox.Show("Выберите магазин", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
int count = Convert.ToInt32(textBoxCount.Text);
bool res = _shopLogic.MakeSupply(
new ShopSearchModel()
{ Id = Convert.ToInt32(comboBoxShop.SelectedValue) },
_pastryLogic.ReadElement(new()
{ Id = Convert.ToInt32(comboBoxPastry.SelectedValue) }),
count
);
if (!res)
{
throw new Exception("Ошибка при пополнении. " +
"Дополнительная информация в логах");
}
MessageBox.Show("Пополнение прошло успешно");
DialogResult = DialogResult.OK;
Close();
}
catch (Exception err)
{
MessageBox.Show("Ошибка пополнения");
return;
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

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

View File

@ -5,6 +5,7 @@ using ConfectioneryFileImplement.Implements;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging; using NLog.Extensions.Logging;
using PastriesShopBusinessLogic.BusinessLogics;
namespace ConfectioneryView namespace ConfectioneryView
{ {
internal static class Program internal static class Program
@ -36,16 +37,22 @@ namespace ConfectioneryView
services.AddTransient<IComponentStorage, ComponentStorage>(); services.AddTransient<IComponentStorage, ComponentStorage>();
services.AddTransient<IOrderStorage, OrderStorage>(); services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<IPastryStorage, PastryStorage>(); services.AddTransient<IPastryStorage, PastryStorage>();
services.AddTransient<IComponentLogic, ComponentLogic>(); services.AddTransient<IShopStorage, ShopStorage>();
services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IOrderLogic, OrderLogic>(); services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<IPastryLogic, PastryLogic>(); services.AddTransient<IPastryLogic, PastryLogic>();
services.AddTransient<FormMain>(); services.AddTransient<IShopLogic, ShopLogic>();
services.AddTransient<FormMain>();
services.AddTransient<FormComponent>(); services.AddTransient<FormComponent>();
services.AddTransient<FormComponents>(); services.AddTransient<FormComponents>();
services.AddTransient<FormCreateOrder>(); services.AddTransient<FormCreateOrder>();
services.AddTransient<FormPastry>(); services.AddTransient<FormPastry>();
services.AddTransient<FormPastryComponent>(); services.AddTransient<FormPastryComponent>();
services.AddTransient<FormPastries>(); services.AddTransient<FormPastries>();
} services.AddTransient<FormShop>();
services.AddTransient<FormShops>();
services.AddTransient<FormSupply>();
services.AddTransient<FormSell>();
}
} }
} }

View File

@ -4,6 +4,7 @@ using ConfectioneryContracts.SearchModels;
using ConfectioneryContracts.StoragesContracts; using ConfectioneryContracts.StoragesContracts;
using ConfectioneryContracts.ViewModels; using ConfectioneryContracts.ViewModels;
using ConfectioneryDataModels.Enums; using ConfectioneryDataModels.Enums;
using ConfectioneryDataModels.Models;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
namespace ConfectioneryBusinessLogic.BusinessLogics namespace ConfectioneryBusinessLogic.BusinessLogics
{ {
@ -11,12 +12,19 @@ namespace ConfectioneryBusinessLogic.BusinessLogics
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage; private readonly IOrderStorage _orderStorage;
public OrderLogic(ILogger<OrderLogic> logger, private readonly IShopStorage _shopStorage;
IOrderStorage orderStorage) private readonly IShopLogic _shopLogic;
private readonly IPastryStorage _pastryStorage;
public OrderLogic(ILogger<OrderLogic> logger,
IOrderStorage orderStorage, IShopStorage shopStorage,
IShopLogic shopLogic, IPastryStorage pastryStorage)
{ {
_logger = logger; _logger = logger;
_orderStorage = orderStorage; _orderStorage = orderStorage;
} _shopStorage = shopStorage;
_shopLogic = shopLogic;
_pastryStorage = pastryStorage;
}
public List<OrderViewModel>? ReadList(OrderSearchModel? model) public List<OrderViewModel>? ReadList(OrderSearchModel? model)
{ {
_logger.LogInformation("ReadList. Id:{ Id}", model?.Id); _logger.LogInformation("ReadList. Id:{ Id}", model?.Id);
@ -42,7 +50,7 @@ namespace ConfectioneryBusinessLogic.BusinessLogics
} }
return true; return true;
} }
public bool ChangeStatus(OrderBindingModel model, OrderStatus status) private bool ChangeStatus(OrderBindingModel model, OrderStatus status)
{ {
CheckModel(model); CheckModel(model);
var element = _orderStorage.GetElement( var element = _orderStorage.GetElement(
@ -58,7 +66,26 @@ namespace ConfectioneryBusinessLogic.BusinessLogics
throw new InvalidOperationException("Текущий статус заказа" + throw new InvalidOperationException("Текущий статус заказа" +
" не может быть переведен в выбранный"); " не может быть переведен в выбранный");
} }
model.Status = status; if (element.Status == OrderStatus.Готов)
{
var pastry = _pastryStorage.GetElement(new PastrySearchModel()
{ Id = model.PastryId });
if (pastry == null)
{
_logger.LogWarning("Status update to " +
status.ToString() +
" operation failed. Document not found.");
return false;
}
if (CheckSupply(pastry, model.Count) == false)
{
_logger.LogWarning("Status update to " +
status.ToString() +
" operation failed. Shop supply error.");
return false;
}
}
model.Status = status;
if (model.Status == OrderStatus.Выдан) if (model.Status == OrderStatus.Выдан)
model.DateImplement = DateTime.Now; model.DateImplement = DateTime.Now;
_orderStorage.Update(model); _orderStorage.Update(model);
@ -101,5 +128,70 @@ namespace ConfectioneryBusinessLogic.BusinessLogics
_logger.LogInformation("Order. Sum:{ Cost}. Id: { Id}", _logger.LogInformation("Order. Sum:{ Cost}. Id: { Id}",
model.Sum, model.Id); model.Sum, model.Id);
} }
} private bool CheckSupply(IPastryModel Pastry, int count)
{
if (count <= 0)
{
_logger.LogWarning(
"Check then supply operation error. Pastry count < 0.");
return false;
}
int sumCapacity = 0;
int sumCount = 0;
sumCapacity = _shopStorage.GetFullList()
.Select(x => x.MaxCapacity).Sum();
sumCount = _shopStorage.GetFullList()
.Select(x => x.ShopPastries
.Select(y => y.Value.Item2).Sum()).Sum();
int freeSpace = sumCapacity - sumCount;
if (freeSpace - count < 0)
{
_logger.LogWarning("Check then supply operation error. " +
"There's no place for new Pastry in shops.");
return false;
}
foreach (var shop in _shopStorage.GetFullList())
{
freeSpace = shop.MaxCapacity;
foreach (var doc in shop.ShopPastries)
{
freeSpace -= doc.Value.Item2;
}
if (freeSpace == 0)
{
continue;
}
if (freeSpace - count >= 0)
{
if (_shopLogic.MakeSupply(new() { Id = shop.Id },
Pastry, count))
count = 0;
else
{
_logger.LogWarning("Supply error");
return false;
}
}
if (freeSpace - count < 0)
{
if (_shopLogic.MakeSupply(new() { Id = shop.Id },
Pastry, freeSpace))
count -= freeSpace;
else
{
_logger.LogWarning("Supply error");
return false;
}
}
if (count <= 0)
{
return true;
}
}
return false;
}
}
} }

View File

@ -0,0 +1,178 @@
using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.BusinessLogicsContracts;
using ConfectioneryContracts.SearchModels;
using ConfectioneryContracts.StoragesContracts;
using ConfectioneryContracts.ViewModels;
using ConfectioneryDataModels.Models;
using Microsoft.Extensions.Logging;
namespace PastriesShopBusinessLogic.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:{Name}. Id:{ Id}",
model?.Name, 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 bool MakeSupply(ShopSearchModel model,
IPastryModel pastry, int count)
{
if (model == null)
throw new ArgumentNullException(nameof(model));
if (pastry == null)
throw new ArgumentNullException(nameof(pastry));
if (count <= 0)
throw new ArgumentNullException(
"Количество должно быть положительным числом");
ShopViewModel curModel = _shopStorage.GetElement(model);
if (curModel == null)
throw new ArgumentNullException(nameof(curModel));
var countItems = curModel.ShopPastries
.Select(x => x.Value.Item2).Sum();
if (curModel.MaxCapacity - countItems >= count)
{
if (curModel.ShopPastries.TryGetValue(
pastry.Id, out var sameDocument))
{
curModel.ShopPastries[pastry.Id] =
(pastry, sameDocument.Item2 + count);
_logger.LogInformation(
"Same pastry found by supply. " +
"Added {0} of {1} in {2} shop", count,
pastry.PastryName, curModel.ShopName);
}
else
{
curModel.ShopPastries[pastry.Id] = (pastry, count);
_logger.LogInformation("New pastry added by supply. " +
"Added {0} of {1} in {2} shop", count,
pastry.PastryName, curModel.ShopName);
}
_shopStorage.Update(new()
{
Id = curModel.Id,
ShopName = curModel.ShopName,
Address = curModel.Address,
DateOpen = curModel.DateOpen,
ShopPastries = curModel.ShopPastries,
MaxCapacity = curModel.MaxCapacity
});
}
else
{
_logger.LogWarning("Required shop is overflowed");
return false;
}
return true;
}
public ShopViewModel ReadElement(ShopSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation(
"ReadElement. ShopName:{ShopName}.Id:{ Id}",
model.Name, 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 (string.IsNullOrEmpty(model.Address))
{
throw new ArgumentNullException("Нет адресса магазина",
nameof(model.Address));
}
if (model.DateOpen == null)
{
throw new ArgumentNullException("Нет даты открытия магазина",
nameof(model.DateOpen));
}
_logger.LogInformation(
"Shop. ShopName:{ShopName}.Address:{Address}. " +
"DateOpen:{DateOpen}. Id: { Id}", model.ShopName,
model.Address, model.DateOpen, model.Id);
var element = _shopStorage.GetElement(new ShopSearchModel
{
Name = model.ShopName
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException(
"Магазин с таким названием уже есть");
}
}
public bool MakeSell(IPastryModel pastry, int count)
{
return _shopStorage.SellPastries(pastry, count);
}
}
}

View File

@ -0,0 +1,14 @@
using ConfectioneryDataModels.Models;
namespace ConfectioneryContracts.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 DateOpen { get; set; }
public int MaxCapacity { get; set; }
public Dictionary<int, (IPastryModel, int)>
ShopPastries { get; set; } = new();
}
}

View File

@ -0,0 +1,17 @@
using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.SearchModels;
using ConfectioneryContracts.ViewModels;
using ConfectioneryDataModels.Models;
namespace ConfectioneryContracts.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 MakeSupply(ShopSearchModel model, IPastryModel pastry, int count);
bool MakeSell(IPastryModel pastry, int count);
}
}

View File

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

View File

@ -0,0 +1,17 @@
using ConfectioneryDataModels.Models;
using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.SearchModels;
using ConfectioneryContracts.ViewModels;
namespace ConfectioneryContracts.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);
public bool SellPastries(IPastryModel model, int count);
}
}

View File

@ -0,0 +1,19 @@
using ConfectioneryDataModels.Models;
using System.ComponentModel;
namespace ConfectioneryContracts.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 DateOpen { get; set; }
[DisplayName("Вместимость")]
public int MaxCapacity { get; set; }
public Dictionary<int, (IPastryModel, int)>
ShopPastries { get; set; } = new();
}
}

View File

@ -0,0 +1,11 @@
namespace ConfectioneryDataModels.Models
{
public interface IShopModel : IId
{
string ShopName { get; }
string Address { get; }
DateTime DateOpen { get; }
int MaxCapacity { get; }
Dictionary<int, (IPastryModel, int)> ShopPastries { get; }
}
}

View File

@ -8,10 +8,12 @@ namespace ConfectioneryFileImplement
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 PastryFileName = "Pastry.xml"; private readonly string PastryFileName = "Pastry.xml";
public List<Component> Components { get; private set; } private readonly string ShopFileName = "Shops.xml";
public List<Component> Components { get; private set; }
public List<Order> Orders { get; private set; } public List<Order> Orders { get; private set; }
public List<Pastry> Pastries { get; private set; } public List<Pastry> Pastries { get; private set; }
public static DataFileSingleton GetInstance() public List<Shop> Shops { get; private set; }
public static DataFileSingleton GetInstance()
{ {
if (instance == null) if (instance == null)
{ {
@ -25,7 +27,9 @@ namespace ConfectioneryFileImplement
"Pastries", x => x.GetXElement); "Pastries", x => x.GetXElement);
public void SaveOrders() => SaveData(Orders, OrderFileName, public void SaveOrders() => SaveData(Orders, OrderFileName,
"Orders", x => x.GetXElement); "Orders", x => x.GetXElement);
private DataFileSingleton() public void SaveShops() => SaveData(Shops, ShopFileName,
"Shops", x => x.GetXElement);
private DataFileSingleton()
{ {
Components = LoadData(ComponentFileName, "Component", Components = LoadData(ComponentFileName, "Component",
x => Component.Create(x)!)!; x => Component.Create(x)!)!;
@ -33,8 +37,10 @@ namespace ConfectioneryFileImplement
x => Pastry.Create(x)!)!; x => Pastry.Create(x)!)!;
Orders = LoadData(OrderFileName, "Order", Orders = LoadData(OrderFileName, "Order",
x => Order.Create(x)!)!; x => Order.Create(x)!)!;
} Shops = LoadData(ShopFileName, "Shop",
private static List<T>? LoadData<T>(string filename, x => Shop.Create(x)!)!;
}
private static List<T>? LoadData<T>(string filename,
string xmlNodeName, Func<XElement, T> selectFunction) string xmlNodeName, Func<XElement, T> selectFunction)
{ {
if (File.Exists(filename)) if (File.Exists(filename))

View File

@ -0,0 +1,130 @@
using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.SearchModels;
using ConfectioneryContracts.StoragesContracts;
using ConfectioneryContracts.ViewModels;
using ConfectioneryFileImplement.Models;
using ConfectioneryDataModels.Models;
namespace ConfectioneryFileImplement.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.Name))
{
return new();
}
return _source.Shops.Where(
x => x.ShopName.Contains(model.Name))
.Select(x => x.GetViewModel).ToList();
}
public ShopViewModel? GetElement(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.Name) && !model.Id.HasValue)
{
return null;
}
return _source.Shops.FirstOrDefault(
x => (!string.IsNullOrEmpty(model.Name) &&
x.ShopName == model.Name) ||
(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 component = _source.Shops
.FirstOrDefault(x => x.Id == model.Id);
if (component == null)
{
return null;
}
component.Update(model);
_source.SaveShops();
return component.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;
}
private bool CheckAvailability(int PastryId, int count)
{
count -= _source.Shops.Select(
x => x.ShopPastries.Select(y =>
(y.Value.Item1.Id == PastryId ?
y.Value.Item2 : 0)).Sum()).Sum();
return count <= 0;
}
public bool SellPastries(IPastryModel model, int count)
{
var NeededPastry = _source.Pastries
.FirstOrDefault(x => x.Id == model.Id);
if (NeededPastry == null ||
!CheckAvailability(NeededPastry.Id, count))
{
return false;
}
for (int i = 0; i < _source.Shops.Count; i++)
{
var shop = _source.Shops[i];
var Pastries = shop.ShopPastries;
foreach (var pastry in Pastries
.Where(x => x.Value.Item1.Id == NeededPastry.Id))
{
var min = Math.Min(pastry.Value.Item2, count);
Pastries[pastry.Value.Item1.Id] =
(pastry.Value.Item1, pastry.Value.Item2 - min);
count -= min;
if (count <= 0)
{
break;
}
}
shop.Update(new ShopBindingModel
{
Id = shop.Id,
ShopName = shop.ShopName,
Address = shop.Address,
DateOpen = shop.DateOpen,
MaxCapacity = shop.MaxCapacity,
ShopPastries = Pastries
});
}
_source.SaveShops();
return true;
}
}
}

View File

@ -0,0 +1,105 @@
using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.ViewModels;
using ConfectioneryDataModels.Models;
using System.Xml.Linq;
namespace ConfectioneryFileImplement.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 DateOpen { get; private set; }
public int MaxCapacity { get; private set; }
public Dictionary<int, int> Pastries { get; private set; } = new();
private Dictionary<int, (IPastryModel, int)>? _shopPastries = null;
public Dictionary<int, (IPastryModel, int)> ShopPastries
{
get
{
if (_shopPastries == null)
{
var source = DataFileSingleton.GetInstance();
_shopPastries = Pastries.ToDictionary(
x => x.Key, y => ((source.Pastries
.FirstOrDefault(z => z.Id == y.Key) as IPastryModel)!,
y.Value));
}
return _shopPastries;
}
}
public static Shop? Create(ShopBindingModel model)
{
if (model == null)
return null;
return new Shop()
{
Id = model.Id,
ShopName = model.ShopName,
Address = model.Address,
DateOpen = model.DateOpen,
MaxCapacity = model.MaxCapacity,
Pastries = model.ShopPastries.ToDictionary(
x => x.Key, x => x.Value.Item2)
};
}
public static Shop? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Shop()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
ShopName = element.Element("ShopName")!.Value,
Address = element.Element("Address")!.Value,
MaxCapacity = Convert.ToInt32(
element.Element("MaxCapacity")!.Value),
DateOpen = Convert.ToDateTime(
element.Element("DateOpen")!.Value),
Pastries = element
.Element("ShopPastries")!.Elements("ShopPastry")
.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;
DateOpen = model.DateOpen;
MaxCapacity = model.MaxCapacity;
if (model.ShopPastries.Count > 0)
{
Pastries = model.ShopPastries
.ToDictionary(x => x.Key, x => x.Value.Item2);
_shopPastries = null;
}
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
ShopName = ShopName,
Address = Address,
DateOpen = DateOpen,
MaxCapacity = MaxCapacity,
ShopPastries = ShopPastries
};
public XElement GetXElement => new("Shop",
new XAttribute("Id", Id),
new XElement("ShopName", ShopName),
new XElement("Address", Address),
new XElement("DateOpen", DateOpen),
new XElement("MaxCapacity", MaxCapacity),
new XElement("ShopPastries", Pastries
.Select(x => new XElement("ShopPastry",
new XElement("Key", x.Key),
new XElement("Value", x.Value))).ToArray()));
}
}

View File

@ -7,13 +7,15 @@ namespace ConfectioneryListImplement
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<Pastry> Pastries { get; set; } public List<Pastry> Pastries { get; set; }
private DataListSingleton() public List<Shop> Shops { get; set; }
private DataListSingleton()
{ {
Components = new List<Component>(); Components = new List<Component>();
Orders = new List<Order>(); Orders = new List<Order>();
Pastries = new List<Pastry>(); Pastries = new List<Pastry>();
} Shops = new List<Shop>();
public static DataListSingleton GetInstance() }
public static DataListSingleton GetInstance()
{ {
if (_instance == null) if (_instance == null)
{ {

View File

@ -0,0 +1,106 @@
using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.SearchModels;
using ConfectioneryContracts.StoragesContracts;
using ConfectioneryContracts.ViewModels;
using ConfectioneryListImplement.Models;
using ConfectioneryDataModels.Models;
namespace ConfectioneryListImplement.Implements
{
public class ShopStorage : IShopStorage
{
private readonly DataListSingleton _source;
public ShopStorage()
{
_source = DataListSingleton.GetInstance();
}
public List<ShopViewModel> GetFullList()
{
var result = new List<ShopViewModel>();
foreach (var shop in _source.Shops)
{
result.Add(shop.GetViewModel);
}
return result;
}
public List<ShopViewModel> GetFilteredList(ShopSearchModel model)
{
var result = new List<ShopViewModel>();
if (string.IsNullOrEmpty(model.Name))
{
return result;
}
foreach (var shop in _source.Shops)
{
if (shop.ShopName.Contains(model.Name))
{
result.Add(shop.GetViewModel);
}
}
return result;
}
public ShopViewModel? GetElement(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.Name) && !model.Id.HasValue)
{
return null;
}
foreach (var shop in _source.Shops)
{
if ((!string.IsNullOrEmpty(model.Name) &&
shop.ShopName == model.Name) ||
(model.Id.HasValue && shop.Id == model.Id))
{
return shop.GetViewModel;
}
}
return null;
}
public ShopViewModel? Insert(ShopBindingModel model)
{
model.Id = 1;
foreach (var shop in _source.Shops)
{
if (model.Id <= shop.Id)
{
model.Id = shop.Id + 1;
}
}
var newShop = Shop.Create(model);
if (newShop == null)
{
return null;
}
_source.Shops.Add(newShop);
return newShop.GetViewModel;
}
public ShopViewModel? Update(ShopBindingModel model)
{
foreach (var shop in _source.Shops)
{
if (shop.Id == model.Id)
{
shop.Update(model);
return shop.GetViewModel;
}
}
return null;
}
public ShopViewModel? Delete(ShopBindingModel model)
{
for (int i = 0; i < _source.Shops.Count; ++i)
{
if (_source.Shops[i].Id == model.Id)
{
var element = _source.Shops[i];
_source.Shops.RemoveAt(i);
return element.GetViewModel;
}
}
return null;
}
public bool SellPastries(IPastryModel model, int count)
{
throw new NotImplementedException();
}
}
}

View File

@ -0,0 +1,47 @@
using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.ViewModels;
using ConfectioneryDataModels.Models;
namespace ConfectioneryListImplement.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 DateOpen { get; private set; }
public Dictionary<int, (IPastryModel, int)> ShopPastries { get; private set; } = new();
public static Shop? Create(ShopBindingModel model)
{
if (model == null)
return null;
return new Shop()
{
Id = model.Id,
ShopName = model.ShopName,
Address = model.Address,
DateOpen = model.DateOpen,
ShopPastries = new()
};
}
public void Update(ShopBindingModel? model)
{
if (model == null)
{
return;
}
ShopName = model.ShopName;
Address = model.Address;
DateOpen = model.DateOpen;
ShopPastries = model.ShopPastries;
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
ShopName = ShopName,
Address = Address,
DateOpen = DateOpen,
ShopPastries = ShopPastries
};
public int MaxCapacity => throw new NotImplementedException();
}
}