Compare commits

...

5 Commits

29 changed files with 1401 additions and 29 deletions

View File

@ -11,7 +11,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FlowerShopContracts", "Flow
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FlowerShopBusinessLogic", "FlowerShopBusinessLogic\FlowerShopBusinessLogic.csproj", "{D8084C04-7B2B-4C8D-A63A-71A3EE1BC065}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FlowerShopListImplement", "FlowerShopListImplement\FlowerShopListImplement.csproj", "{C58840E6-D68D-476E-AB3A-EB13F1740FC8}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FlowerShopListImplement", "FlowerShopListImplement\FlowerShopListImplement.csproj", "{C58840E6-D68D-476E-AB3A-EB13F1740FC8}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FlowerShopFileImplement", "FlowerShopFileImplement\FlowerShopFileImplement.csproj", "{87156689-2FDA-4065-90CC-749B2FE3C0D6}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -39,6 +41,10 @@ Global
{C58840E6-D68D-476E-AB3A-EB13F1740FC8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C58840E6-D68D-476E-AB3A-EB13F1740FC8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C58840E6-D68D-476E-AB3A-EB13F1740FC8}.Release|Any CPU.Build.0 = Release|Any CPU
{87156689-2FDA-4065-90CC-749B2FE3C0D6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{87156689-2FDA-4065-90CC-749B2FE3C0D6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{87156689-2FDA-4065-90CC-749B2FE3C0D6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{87156689-2FDA-4065-90CC-749B2FE3C0D6}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@ -17,6 +17,7 @@
<ProjectReference Include="..\FlowerShopBusinessLogic\FlowerShopBusinessLogic.csproj" />
<ProjectReference Include="..\FlowerShopContracts\FlowerShopContracts.csproj" />
<ProjectReference Include="..\FlowerShopDataModels\FlowerShopDataModels.csproj" />
<ProjectReference Include="..\FlowerShopFileImplement\FlowerShopFileImplement.csproj" />
<ProjectReference Include="..\FlowerShopListImplement\FlowerShopListImplement.csproj" />
</ItemGroup>

View File

@ -40,6 +40,7 @@
this.bouquetsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.shopsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.buttonSupplyShop = new System.Windows.Forms.Button();
this.buttonSellBouquets = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.menuStrip.SuspendLayout();
this.SuspendLayout();
@ -135,21 +136,21 @@
// componentsToolStripMenuItem
//
this.componentsToolStripMenuItem.Name = "componentsToolStripMenuItem";
this.componentsToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
this.componentsToolStripMenuItem.Size = new System.Drawing.Size(145, 22);
this.componentsToolStripMenuItem.Text = "Компоненты";
this.componentsToolStripMenuItem.Click += new System.EventHandler(this.componentsToolStripMenuItem_Click);
//
// bouquetsToolStripMenuItem
//
this.bouquetsToolStripMenuItem.Name = "bouquetsToolStripMenuItem";
this.bouquetsToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
this.bouquetsToolStripMenuItem.Size = new System.Drawing.Size(145, 22);
this.bouquetsToolStripMenuItem.Text = "Букеты";
this.bouquetsToolStripMenuItem.Click += new System.EventHandler(this.bouquetsToolStripMenuItem_Click);
//
// shopsToolStripMenuItem
//
this.shopsToolStripMenuItem.Name = "shopsToolStripMenuItem";
this.shopsToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
this.shopsToolStripMenuItem.Size = new System.Drawing.Size(145, 22);
this.shopsToolStripMenuItem.Text = "Магазины";
this.shopsToolStripMenuItem.Click += new System.EventHandler(this.shopsToolStripMenuItem_Click);
//
@ -163,11 +164,22 @@
this.buttonSupplyShop.UseVisualStyleBackColor = true;
this.buttonSupplyShop.Click += new System.EventHandler(this.buttonSupplyShop_Click);
//
// buttonSellBouquets
//
this.buttonSellBouquets.Location = new System.Drawing.Point(891, 238);
this.buttonSellBouquets.Name = "buttonSellBouquets";
this.buttonSellBouquets.Size = new System.Drawing.Size(150, 30);
this.buttonSellBouquets.TabIndex = 8;
this.buttonSellBouquets.Text = "Продажа букетов";
this.buttonSellBouquets.UseVisualStyleBackColor = true;
this.buttonSellBouquets.Click += new System.EventHandler(this.buttonSellBouquets_Click);
//
// FormMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1071, 401);
this.Controls.Add(this.buttonSellBouquets);
this.Controls.Add(this.buttonSupplyShop);
this.Controls.Add(this.buttonRefresh);
this.Controls.Add(this.buttonPut);
@ -203,5 +215,6 @@
private Button buttonReady;
private ToolStripMenuItem shopsToolStripMenuItem;
private Button buttonSupplyShop;
private Button buttonSellBouquets;
}
}

View File

@ -171,5 +171,14 @@ namespace FlowerShop
form.ShowDialog();
}
}
private void buttonSellBouquets_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShopSell));
if (service is FormShopSell form)
{
form.ShowDialog();
}
}
}
}

View File

@ -40,6 +40,8 @@
this.buttonSave = new System.Windows.Forms.Button();
this.openDateTimePicker = new System.Windows.Forms.DateTimePicker();
this.openDateLabel = new System.Windows.Forms.Label();
this.maxCountLabel = new System.Windows.Forms.Label();
this.textBoxMaxCount = new System.Windows.Forms.TextBox();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
//
@ -84,7 +86,7 @@
this.ColumnId,
this.ColumnBouquetName,
this.ColumnCount});
this.dataGridView.Location = new System.Drawing.Point(12, 99);
this.dataGridView.Location = new System.Drawing.Point(13, 133);
this.dataGridView.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowHeadersWidth = 51;
@ -116,7 +118,7 @@
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(200, 327);
this.buttonCancel.Location = new System.Drawing.Point(199, 361);
this.buttonCancel.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(136, 31);
@ -127,7 +129,7 @@
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(42, 327);
this.buttonSave.Location = new System.Drawing.Point(43, 361);
this.buttonSave.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(136, 31);
@ -152,11 +154,29 @@
this.openDateLabel.TabIndex = 14;
this.openDateLabel.Text = "Дата открытия:";
//
// maxCountLabel
//
this.maxCountLabel.AutoSize = true;
this.maxCountLabel.Location = new System.Drawing.Point(13, 98);
this.maxCountLabel.Name = "maxCountLabel";
this.maxCountLabel.Size = new System.Drawing.Size(155, 15);
this.maxCountLabel.TabIndex = 15;
this.maxCountLabel.Text = "Макс. количество букетов:";
//
// textBoxMaxCount
//
this.textBoxMaxCount.Location = new System.Drawing.Point(174, 95);
this.textBoxMaxCount.Name = "textBoxMaxCount";
this.textBoxMaxCount.Size = new System.Drawing.Size(189, 23);
this.textBoxMaxCount.TabIndex = 16;
//
// FormShop
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(389, 367);
this.ClientSize = new System.Drawing.Size(389, 403);
this.Controls.Add(this.textBoxMaxCount);
this.Controls.Add(this.maxCountLabel);
this.Controls.Add(this.openDateLabel);
this.Controls.Add(this.openDateTimePicker);
this.Controls.Add(this.buttonCancel);
@ -190,5 +210,7 @@
private DataGridViewTextBoxColumn ColumnCount;
private DateTimePicker openDateTimePicker;
private Label openDateLabel;
private Label maxCountLabel;
private TextBox textBoxMaxCount;
}
}

View File

@ -38,6 +38,7 @@ namespace FlowerShop
textBoxName.Text = view.Name;
textBoxAddress.Text = view.Address;
openDateTimePicker.Value = view.OpeningDate;
textBoxMaxCount.Text = view.MaxCountBouquets.ToString();
_shopBouquets = view.ShopBouquets ?? new Dictionary<int, (IBouquetModel, int)>();
LoadData();
}
@ -86,6 +87,12 @@ namespace FlowerShop
return;
}
if (string.IsNullOrEmpty(textBoxMaxCount.Text))
{
MessageBox.Show("Заполните макс. количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Saving shop");
try
@ -96,6 +103,7 @@ namespace FlowerShop
Name = textBoxName.Text,
Address = textBoxAddress.Text,
OpeningDate = openDateTimePicker.Value,
MaxCountBouquets = Convert.ToInt32(textBoxMaxCount.Text),
ShopBouquets = _shopBouquets
};

View File

@ -0,0 +1,124 @@
namespace FlowerShop
{
partial class FormShopSell
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.labelCount = new System.Windows.Forms.Label();
this.labelBouquet = new System.Windows.Forms.Label();
this.comboBoxBouquet = new System.Windows.Forms.ComboBox();
this.textBoxCount = new System.Windows.Forms.TextBox();
this.buttonSell = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// labelCount
//
this.labelCount.AutoSize = true;
this.labelCount.Location = new System.Drawing.Point(20, 57);
this.labelCount.Name = "labelCount";
this.labelCount.Size = new System.Drawing.Size(75, 15);
this.labelCount.TabIndex = 1;
this.labelCount.Text = "Количество:";
//
// labelBouquet
//
this.labelBouquet.AutoSize = true;
this.labelBouquet.Location = new System.Drawing.Point(20, 18);
this.labelBouquet.Name = "labelBouquet";
this.labelBouquet.Size = new System.Drawing.Size(40, 15);
this.labelBouquet.TabIndex = 2;
this.labelBouquet.Text = "Букет:";
//
// comboBoxBouquet
//
this.comboBoxBouquet.FormattingEnabled = true;
this.comboBoxBouquet.Location = new System.Drawing.Point(108, 18);
this.comboBoxBouquet.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.comboBoxBouquet.Name = "comboBoxBouquet";
this.comboBoxBouquet.Size = new System.Drawing.Size(244, 23);
this.comboBoxBouquet.TabIndex = 4;
//
// textBoxCount
//
this.textBoxCount.Location = new System.Drawing.Point(108, 55);
this.textBoxCount.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.textBoxCount.Name = "textBoxCount";
this.textBoxCount.Size = new System.Drawing.Size(244, 23);
this.textBoxCount.TabIndex = 5;
//
// buttonSell
//
this.buttonSell.Location = new System.Drawing.Point(206, 106);
this.buttonSell.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonSell.Name = "buttonSell";
this.buttonSell.Size = new System.Drawing.Size(89, 31);
this.buttonSell.TabIndex = 6;
this.buttonSell.Text = "Продажа";
this.buttonSell.UseVisualStyleBackColor = true;
this.buttonSell.Click += new System.EventHandler(this.buttonSell_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(301, 106);
this.buttonCancel.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(89, 31);
this.buttonCancel.TabIndex = 7;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// FormShopSell
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(402, 148);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSell);
this.Controls.Add(this.textBoxCount);
this.Controls.Add(this.comboBoxBouquet);
this.Controls.Add(this.labelBouquet);
this.Controls.Add(this.labelCount);
this.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.Name = "FormShopSell";
this.Text = "Продажа из магазина";
this.Load += new System.EventHandler(this.FormShopSell_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Label labelCount;
private Label labelBouquet;
private ComboBox comboBoxBouquet;
private TextBox textBoxCount;
private Button buttonSell;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,93 @@
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
namespace FlowerShop
{
public partial class FormShopSell : Form
{
private readonly ILogger _logger;
private readonly IBouquetLogic _logicBouquet;
private readonly IShopLogic _logicShop;
public FormShopSell(ILogger<FormShopSell> logger, IBouquetLogic logicBouquet, IShopLogic logicShop)
{
InitializeComponent();
_logger = logger;
_logicBouquet = logicBouquet;
_logicShop = logicShop;
}
private void FormShopSell_Load(object sender, EventArgs e)
{
_logger.LogInformation("Loading bouquets for selling");
try
{
var list = _logicBouquet.ReadList(null);
if (list != null)
{
comboBoxBouquet.DisplayMember = "BouquetName";
comboBoxBouquet.ValueMember = "Id";
comboBoxBouquet.DataSource = list;
comboBoxBouquet.SelectedItem = null;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error during loading bouquets for selling");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonSell_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCount.Text))
{
MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxBouquet.SelectedValue == null)
{
MessageBox.Show("Выберите букет", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Создание продажи");
try
{
var operationResult = _logicShop.SellBouquet(
new BouquetBindingModel
{
Id = Convert.ToInt32(comboBoxBouquet.SelectedValue)
},
Convert.ToInt32(textBoxCount.Text)
);
if (!operationResult)
{
throw new Exception("Ошибка при создании продажи. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка создания продажи");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

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

View File

@ -1,11 +1,10 @@
using FlowerShopContracts.StoragesContracts;
using Microsoft.Extensions.DependencyInjection;
using FlowerShopListImplement.Implements;
using FlowerShopFileImplement.Implements;
using FlowerShopBusinessLogic.BusinessLogics;
using FlowerShopContracts.BusinessLogicsContracts;
using NLog.Extensions.Logging;
using Microsoft.Extensions.Logging;
using System.Windows.Forms;
namespace FlowerShop
{
@ -13,9 +12,7 @@ namespace FlowerShop
{
private static ServiceProvider? _serviceProvider;
public static ServiceProvider? ServiceProvider => _serviceProvider;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
@ -50,6 +47,7 @@ namespace FlowerShop
services.AddTransient<FormShop>();
services.AddTransient<FormShops>();
services.AddTransient<FormShopSupply>();
services.AddTransient<FormShopSell>();
}
}
}

View File

@ -3,8 +3,10 @@ using FlowerShopContracts.BusinessLogicsContracts;
using FlowerShopContracts.SearchModels;
using FlowerShopContracts.StoragesContracts;
using FlowerShopContracts.ViewModels;
using FlowerShopDataModels.Models;
using FlowerShopDataModels.Enums;
using Microsoft.Extensions.Logging;
using System.Text;
namespace FlowerShopBusinessLogic.BusinessLogics
{
@ -12,11 +14,17 @@ namespace FlowerShopBusinessLogic.BusinessLogics
{
private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage;
private readonly IShopStorage _shopStorage;
private readonly IShopLogic _shopLogic;
private readonly IBouquetStorage _bouquetStorage;
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage)
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage, IShopLogic shopLogic, IBouquetStorage bouquetStorage, IShopStorage shopStorage)
{
_logger = logger;
_orderStorage = orderStorage;
_shopLogic = shopLogic;
_bouquetStorage = bouquetStorage;
_shopStorage = shopStorage;
}
public List<OrderViewModel>? ReadList(OrderSearchModel? model)
@ -84,6 +92,19 @@ namespace FlowerShopBusinessLogic.BusinessLogics
return false;
}
var bouquet = _bouquetStorage.GetElement(new BouquetSearchModel() { Id = model.BouquetId });
if (bouquet == null)
{
_logger.LogWarning("Status update to Готов operation failed. Bouquet not found");
return false;
}
if (!CheckThenSupplyMany(bouquet, model.Count))
{
_logger.LogWarning("Status update to Готов operation failed. Shop supply error.");
return false;
}
model.Status = OrderStatus.Готов;
model.DateImplement = DateTime.Now;
@ -143,5 +164,72 @@ namespace FlowerShopBusinessLogic.BusinessLogics
throw new InvalidOperationException("Заказ с таким идентификатором уже есть");
}
}
public bool CheckThenSupplyMany(IBouquetModel bouquet, int count)
{
if (count <= 0)
{
_logger.LogWarning("Check then supply operation error. Bouquet count < 0.");
return false;
}
int freeSpace = 0;
foreach (var shop in _shopStorage.GetFullList())
{
freeSpace += shop.MaxCountBouquets;
foreach (var doc in shop.ShopBouquets)
{
freeSpace -= doc.Value.Item2;
}
}
if (freeSpace - count < 0)
{
_logger.LogWarning("Check then supply operation error. There's no place for new bouquets in shops.");
return false;
}
foreach (var shop in _shopStorage.GetFullList())
{
freeSpace = shop.MaxCountBouquets;
foreach (var bouq in shop.ShopBouquets)
{
freeSpace -= bouq.Value.Item2;
}
if (freeSpace == 0)
{
continue;
}
if (freeSpace - count >= 0)
{
if (_shopLogic.SupplyBouquets(new() { Id = shop.Id }, bouquet, count)) count = 0;
else
{
_logger.LogWarning("Supply error");
return false;
}
}
if (freeSpace - count < 0)
{
if (_shopLogic.SupplyBouquets(new() { Id = shop.Id }, bouquet, freeSpace)) count -= freeSpace;
else
{
_logger.LogWarning("Supply error");
return false;
}
}
if (count <= 0)
{
return true;
}
}
return false;
}
}
}

View File

@ -83,26 +83,40 @@ namespace FlowerShopBusinessLogic.BusinessLogics
_logger.LogInformation("Shop element found. ID: {0}, Name: {1}", shopElement.Id, shopElement.Name);
if (shopElement.ShopBouquets.TryGetValue(bouquet.Id, out var sameBouquet))
var countBouquets = 0;
foreach (var bouq in shopElement.ShopBouquets)
{
shopElement.ShopBouquets[bouquet.Id] = (bouquet, sameBouquet.Item2 + count);
_logger.LogInformation("Same bouquet found by supply. Added {0} of {1} in {2} shop", count, bouquet.BouquetName, shopElement.Name);
countBouquets += bouq.Value.Item2;
}
if (shopElement.MaxCountBouquets - countBouquets > count)
{
if (shopElement.ShopBouquets.TryGetValue(bouquet.Id, out var sameBouquet))
{
shopElement.ShopBouquets[bouquet.Id] = (bouquet, sameBouquet.Item2 + count);
_logger.LogInformation("Same bouquet found by supply. Added {0} of {1} in {2} shop", count, bouquet.BouquetName, shopElement.Name);
}
else
{
shopElement.ShopBouquets[bouquet.Id] = (bouquet, count);
_logger.LogInformation("New bouquet added by supply. Added {0} of {1} in {2} shop", count, bouquet.BouquetName, shopElement.Name);
}
_shopStorage.Update(new()
{
Id = shopElement.Id,
Name = shopElement.Name,
Address = shopElement.Address,
OpeningDate = shopElement.OpeningDate,
ShopBouquets = shopElement.ShopBouquets
});
}
else
{
shopElement.ShopBouquets[bouquet.Id] = (bouquet, count);
_logger.LogInformation("New bouquet added by supply. Added {0} of {1} in {2} shop", count, bouquet.BouquetName, shopElement.Name);
_logger.LogWarning("Required shop is overflowed");
return false;
}
_shopStorage.Update(new()
{
Id = shopElement.Id,
Name = shopElement.Name,
Address = shopElement.Address,
OpeningDate = shopElement.OpeningDate,
ShopBouquets = shopElement.ShopBouquets
});
return true;
}
@ -145,6 +159,11 @@ namespace FlowerShopBusinessLogic.BusinessLogics
return true;
}
private bool SellBouquet(IBouquetModel bouquet, int count)
{
return _shopStorage.SellBouquet(bouquet, count);
}
private void CheckModel(ShopBindingModel model, bool withParams = true)
{
if (model == null)
@ -162,6 +181,11 @@ namespace FlowerShopBusinessLogic.BusinessLogics
throw new ArgumentNullException("Нет названия магазина!", nameof(model.Name));
}
if (model.MaxCountBouquets < 0)
{
throw new InvalidOperationException("Магазин с отрицательным числом максимального количества букетов!")
}
_logger.LogInformation("Shop. Name: {0}, Address: {1}, ID: {2}", model.Name, model.Address, model.Id);
var element = _shopStorage.GetElement(new ShopSearchModel

View File

@ -12,6 +12,8 @@ namespace FlowerShopContracts.BindingModels
public DateTime OpeningDate { get; set; }
public int MaxCountBouquets { get; set; }
public Dictionary<int, (IBouquetModel, int)> ShopBouquets { get; set; }
}
}

View File

@ -13,5 +13,6 @@ namespace FlowerShopContracts.BusinessLogicsContracts
bool Update(ShopBindingModel model);
bool Delete(ShopBindingModel model);
bool SupplyBouquets(ShopSearchModel model, IBouquetModel bouquet, int count);
bool SellBouquet(IBouquetModel bouquet, int count);
}
}

View File

@ -1,6 +1,7 @@
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.SearchModels;
using FlowerShopContracts.ViewModels;
using FlowerShopDataModels.Models;
namespace FlowerShopContracts.StoragesContracts
{
@ -12,5 +13,6 @@ namespace FlowerShopContracts.StoragesContracts
ShopViewModel? Insert(ShopBindingModel model);
ShopViewModel? Update(ShopBindingModel model);
ShopViewModel? Delete(ShopBindingModel model);
bool SellBouquet(IBouquetModel model, int count);
}
}

View File

@ -17,5 +17,8 @@ namespace FlowerShopContracts.ViewModels
public DateTime OpeningDate { get; set; }
public Dictionary<int, (IBouquetModel, int)> ShopBouquets { get; set; } = new();
[DisplayName("Макс. букетов в магазине")]
public int MaxCountBouquets { get; set; }
}
}

View File

@ -5,6 +5,7 @@
string Name { get; }
string Address { get; }
DateTime OpeningDate { get; }
int MaxCountBouquets { get; }
Dictionary<int, (IBouquetModel, int)> ShopBouquets { get; }
}
}

View File

@ -0,0 +1,63 @@
using FlowerShopFileImplement.Models;
using System.Xml.Linq;
namespace FlowerShopFileImplement
{
public class DataFileSingleton
{
private static DataFileSingleton instance;
private readonly string ComponentFileName = "Component.xml";
private readonly string OrderFileName = "Order.xml";
private readonly string BouquetFileName = "Bouquet.xml";
private readonly string ShopFileName = "Shop.xml";
public List<Component> Components { get; private set; }
public List<Order> Orders { get; private set; }
public List<Bouquet> Bouquets { get; private set; }
public List<Shop> Shops { get; private set; }
public static DataFileSingleton GetInstance()
{
if (instance == null)
{
instance = new DataFileSingleton();
}
return instance;
}
public void SaveComponents() => SaveData(Components, ComponentFileName, "Components", x => x.GetXElement);
public void SaveBouquets() => SaveData(Bouquets, BouquetFileName, "Bouquets", x => x.GetXElement);
public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement);
public void SaveShops() => SaveData(Shops, ShopFileName, "Shops", x => x.GetXElement);
private DataFileSingleton()
{
Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!;
Bouquets = LoadData(BouquetFileName, "Bouquet", x => Bouquet.Create(x)!)!;
Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!;
Shops = LoadData(ShopFileName, "Shop", x => Shop.Create(x)!)!;
}
private static List<T>? LoadData<T>(string filename, string xmlNodeName, Func<XElement, T> selectFunction)
{
if (File.Exists(filename))
{
return XDocument.Load(filename)?.Root?.Elements(xmlNodeName)?.Select(selectFunction)?.ToList();
}
return new List<T>();
}
private static void SaveData<T>(List<T> data, string filename, string xmlNodeName, Func<T, XElement> selectFunction)
{
if (data != null)
{
new XDocument(new XElement(xmlNodeName, data.Select(selectFunction).ToArray())).Save(filename);
}
}
}
}

View File

@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\FlowerShopContracts\FlowerShopContracts.csproj" />
<ProjectReference Include="..\FlowerShopDataModels\FlowerShopDataModels.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,85 @@
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.SearchModels;
using FlowerShopContracts.StoragesContracts;
using FlowerShopContracts.ViewModels;
using FlowerShopFileImplement.Models;
namespace FlowerShopFileImplement.Implements
{
public class BouquetStorage : IBouquetStorage
{
private readonly DataFileSingleton source;
public BouquetStorage()
{
source = DataFileSingleton.GetInstance();
}
public BouquetViewModel? GetElement(BouquetSearchModel model)
{
if (string.IsNullOrEmpty(model.BouquetName) && !model.Id.HasValue)
{
return null;
}
return source.Bouquets.FirstOrDefault(x => (!string.IsNullOrEmpty(model.BouquetName) && x.BouquetName == model.BouquetName) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public List<BouquetViewModel> GetFilteredList(BouquetSearchModel model)
{
if (string.IsNullOrEmpty(model.BouquetName))
{
return new();
}
return source.Bouquets.Where(x => x.BouquetName.Contains(model.BouquetName)).Select(x => x.GetViewModel).ToList();
}
public List<BouquetViewModel> GetFullList()
{
return source.Bouquets.Select(x => x.GetViewModel).ToList();
}
public BouquetViewModel? Insert(BouquetBindingModel model)
{
model.Id = source.Bouquets.Count > 0 ? source.Bouquets.Max(x => x.Id) + 1 : 1;
var newBouquet = Bouquet.Create(model);
if (newBouquet == null)
{
return null;
}
source.Bouquets.Add(newBouquet);
source.SaveBouquets();
return newBouquet.GetViewModel;
}
public BouquetViewModel? Update(BouquetBindingModel model)
{
var bouquet = source.Bouquets.FirstOrDefault(x => x.Id == model.Id);
if (bouquet == null)
{
return null;
}
bouquet.Update(model);
source.SaveBouquets();
return bouquet.GetViewModel;
}
public BouquetViewModel? Delete(BouquetBindingModel model)
{
var bouquet = source.Bouquets.FirstOrDefault(x => x.Id == model.Id);
if (bouquet == null)
{
return null;
}
source.Bouquets.Remove(bouquet);
source.SaveBouquets();
return bouquet.GetViewModel;
}
}
}

View File

@ -0,0 +1,88 @@
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.SearchModels;
using FlowerShopContracts.StoragesContracts;
using FlowerShopContracts.ViewModels;
using FlowerShopFileImplement.Models;
using System.Linq;
namespace FlowerShopFileImplement.Implements
{
public class ComponentStorage : IComponentStorage
{
private readonly DataFileSingleton source;
public ComponentStorage()
{
source = DataFileSingleton.GetInstance();
}
public ComponentViewModel? GetElement(ComponentSearchModel model)
{
if (string.IsNullOrEmpty(model.ComponentName) && !model.Id.HasValue)
{
return null;
}
return source.Components.FirstOrDefault(x => (!string.IsNullOrEmpty(model.ComponentName) && x.ComponentName == model.ComponentName) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public List<ComponentViewModel> GetFilteredList(ComponentSearchModel model)
{
if (string.IsNullOrEmpty(model.ComponentName))
{
return new();
}
return source.Components.Where(x => x.ComponentName.Contains(model.ComponentName)).Select(x => x.GetViewModel).ToList();
}
public List<ComponentViewModel> GetFullList()
{
return source.Components.Select(x => x.GetViewModel).ToList();
}
public ComponentViewModel? Insert(ComponentBindingModel model)
{
model.Id = source.Components.Count > 0 ? source.Components.Max(x => x.Id) + 1 : 1;
var newComponent = Component.Create(model);
if (newComponent == null)
{
return null;
}
source.Components.Add(newComponent);
source.SaveComponents();
return newComponent.GetViewModel;
}
public ComponentViewModel? Update(ComponentBindingModel model)
{
var component = source.Components.FirstOrDefault(x => x.Id == model.Id);
if (component == null)
{
return null;
}
component.Update(model);
source.SaveComponents();
return component.GetViewModel;
}
public ComponentViewModel? Delete(ComponentBindingModel model)
{
var component = source.Components.FirstOrDefault(x => x.Id == model.Id);
if (component == null)
{
return null;
}
source.Components.Remove(component);
source.SaveComponents();
return component.GetViewModel;
}
}
}

View File

@ -0,0 +1,100 @@
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.SearchModels;
using FlowerShopContracts.StoragesContracts;
using FlowerShopContracts.ViewModels;
using FlowerShopFileImplement.Models;
namespace FlowerShopFileImplement.Implements
{
public class OrderStorage : IOrderStorage
{
private readonly DataFileSingleton source;
public OrderStorage()
{
source = DataFileSingleton.GetInstance();
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
return AttachBouquetName(source.Orders.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))?.GetViewModel);
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return new();
}
return source.Orders.Where(x => x.Id == model.Id).Select(x => AttachBouquetName(x.GetViewModel)).ToList();
}
public List<OrderViewModel> GetFullList()
{
return source.Orders.Select(x => x.GetViewModel).ToList();
}
public OrderViewModel? Update(OrderBindingModel model)
{
var order = source.Orders.FirstOrDefault(x => x.Id == model.Id);
if (order == null)
{
return null;
}
order.Update(model);
source.SaveOrders();
return AttachBouquetName(order.GetViewModel);
}
public OrderViewModel? Insert(OrderBindingModel model)
{
model.Id = source.Orders.Count > 0 ? source.Orders.Max(x => x.Id) + 1 : 1;
var newOrder = Order.Create(model);
if (newOrder == null)
{
return null;
}
source.Orders.Add(newOrder);
source.SaveOrders();
return newOrder.GetViewModel;
}
public OrderViewModel? Delete(OrderBindingModel model)
{
var order = source.Orders.FirstOrDefault(x => x.Id == model.Id);
if (order == null)
{
return null;
}
source.Orders.Remove(order);
source.SaveOrders();
return order.GetViewModel;
}
private OrderViewModel AttachBouquetName(OrderViewModel? model)
{
if (model == null)
{
return null;
}
var bouquet = source.Bouquets.Find(b => b.Id == model.BouquetId);
model.BouquetName = bouquet is null ? String.Empty : bouquet.BouquetName;
return model;
}
}
}

View File

@ -0,0 +1,156 @@
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.SearchModels;
using FlowerShopContracts.StoragesContracts;
using FlowerShopContracts.ViewModels;
using FlowerShopDataModels.Models;
namespace FlowerShopFileImplement.Implements
{
public class ShopStorage : IShopStorage
{
private readonly DataFileSingleton source;
public ShopStorage()
{
source = DataFileSingleton.GetInstance();
}
public ShopViewModel? GetElement(ShopSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
return source.Shops.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)?.GetViewModel;
}
public List<ShopViewModel> GetFilteredList(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.Name))
{
return new();
}
return source.Shops.Select(x => x.GetViewModel).Where(x => x.Name.Contains(model.Name ?? string.Empty)).ToList();
}
public List<ShopViewModel> GetFullList()
{
return source.Shops.Select(shop => shop.GetViewModel).ToList();
}
public ShopViewModel? Insert(ShopBindingModel model)
{
model.Id = source.Shops.Count > 0 ? source.Shops.Max(x => x.Id) + 1 : 1;
var newShop = Shop.Create(model);
if (newShop == null)
{
return null;
}
source.Shops.Add(newShop);
source.SaveShops();
return newShop.GetViewModel;
}
public ShopViewModel? Update(ShopBindingModel model)
{
var shop = source.Shops.FirstOrDefault(x => x.Id == model.Id);
if (shop == null)
{
return null;
}
shop.Update(model);
source.SaveShops();
return shop.GetViewModel;
}
public ShopViewModel? Delete(ShopBindingModel model)
{
var shop = source.Shops.FirstOrDefault(x => x.Id == model.Id);
if (shop == null)
{
return null;
}
source.Shops.Remove(shop);
source.SaveShops();
return shop.GetViewModel;
}
public bool SellBouquet(IBouquetModel model, int count)
{
var bouquet = source.Bouquets.FirstOrDefault(x => x.Id == model.Id);
var countStore = count;
if (bouquet == null)
{
return false;
}
foreach (var shop in source.Shops)
{
foreach (var bouq in shop.ShopBouquets)
{
if (bouq.Value.Item1.Id == bouquet.Id)
{
count -= bouq.Value.Item2;
}
if (count <= 0)
{
break;
}
}
}
if (count > 0)
{
return false;
}
count = countStore;
for (int i = 0; i < source.Shops.Count; i++)
{
var shop = source.Shops[i];
var bouquets = shop.ShopBouquets;
foreach (var bouq in bouquets.Where(x => x.Value.Item1.Id == bouquet.Id))
{
var min = Math.Min(bouq.Value.Item2, count);
bouquets[bouq.Value.Item1.Id] = (bouq.Value.Item1, doc.Value.Item2 - min);
count -= min;
if (count <= 0)
{
break;
}
}
shop.Update(new ShopBindingModel
{
Id = shop.Id,
Name = shop.Name,
Address = shop.Address,
OpeningDate = shop.OpeningDate,
MaxCountBouquets = shop.MaxCountBouquets,
ShopBouquets = bouquets
});
source.SaveShops();
}
if (count > 0)
{
return false;
}
return true;
}
}
}

View File

@ -0,0 +1,104 @@
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.ViewModels;
using FlowerShopDataModels.Models;
using System.Xml.Linq;
using System.Linq;
namespace FlowerShopFileImplement.Models
{
public class Bouquet : IBouquetModel
{
public string BouquetName { get; private set; } = string.Empty;
public double Price { get; private set; }
public int Id { get; private set; }
public Dictionary<int, int> Components { get; private set; } = new();
private Dictionary<int, (IComponentModel, int)>? _bouquetComponents = new();
public Dictionary<int, (IComponentModel, int)> BouquetComponents
{
get
{
if (_bouquetComponents == null)
{
var source = DataFileSingleton.GetInstance();
_bouquetComponents = Components.ToDictionary(
x => x.Key,
y => ((source.Components.FirstOrDefault(z => z.Id == y.Key) as IComponentModel)!, y.Value)
);
}
return _bouquetComponents;
}
}
public static Bouquet? Create(BouquetBindingModel? model)
{
if (model == null)
{
return null;
}
return new Bouquet()
{
Id = model.Id,
BouquetName = model.BouquetName,
Price = model.Price,
Components = model.BouquetComponents.ToDictionary(x => x.Key, x => x.Value.Item2)
};
}
public static Bouquet? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Bouquet()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
BouquetName = element.Attribute("BouquetName")!.Value,
Price = Convert.ToDouble(element.Element("Price")!.Value),
Components = element.Element("BouquetComponents")!.Elements("BouquetComponent").ToDictionary(
x => Convert.ToInt32(x.Element("Key")?.Value),
x => Convert.ToInt32(x.Element("Value")?.Value)
)
};
}
public void Update(BouquetBindingModel? model)
{
if (model == null)
{
return;
}
BouquetName = model.BouquetName;
Price = model.Price;
Components = model.BouquetComponents.ToDictionary(x => x.Key, x => x.Value.Item2);
_bouquetComponents = null;
}
public BouquetViewModel GetViewModel => new()
{
Id = Id,
BouquetName = BouquetName,
Price = Price,
BouquetComponents = BouquetComponents
};
public XElement GetXElement => new(
"Bouquet",
new XAttribute("Id", Id),
new XElement("BouquetName", BouquetName),
new XElement("Price", Price.ToString()),
new XElement("BouquetComponents", Components.Select(x =>
new XElement("BouquetComponent",
new XElement("Key", x.Key),
new XElement("Value", x.Value))).ToArray())
);
}
}

View File

@ -0,0 +1,72 @@
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.ViewModels;
using FlowerShopDataModels.Models;
using System.Xml.Linq;
using System.Linq;
namespace FlowerShopFileImplement.Models
{
public class Component : IComponentModel
{
public string ComponentName { get; private set; } = String.Empty;
public double Cost { get; set; }
public int Id { get; private set; }
public static Component? Create(ComponentBindingModel? model)
{
if (model == null)
{
return null;
}
return new Component()
{
Id = model.Id,
ComponentName = model.ComponentName,
Cost = model.Cost
};
}
public static Component? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Component()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
ComponentName = element.Element("ComponentName")!.Value,
Cost = Convert.ToDouble(element.Element("Cost")!.Value)
};
}
public void Update(ComponentBindingModel? model)
{
if (model == null)
{
return;
}
ComponentName = model.ComponentName;
Cost = model.Cost;
}
public ComponentViewModel GetViewModel => new()
{
Id = Id,
ComponentName = ComponentName,
Cost = Cost
};
public XElement GetXElement => new(
"Component",
new XAttribute("Id", Id),
new XElement("ComponentName", ComponentName),
new XElement("Cost", Cost.ToString())
);
}
}

View File

@ -0,0 +1,101 @@
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.ViewModels;
using FlowerShopDataModels.Enums;
using FlowerShopDataModels.Models;
using System.Xml.Linq;
namespace FlowerShopFileImplement.Models
{
public class Order : IOrderModel
{
public int BouquetId { get; private set; }
public int Count { get; private set; }
public double Sum { get; private set; }
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен;
public DateTime DateCreate { get; private set; } = DateTime.Now;
public DateTime? DateImplement { get; private set; }
public int Id { get; private set; }
public static Order? Create(OrderBindingModel? model)
{
if (model == null)
{
return null;
}
return new Order
{
BouquetId = model.BouquetId,
Count = model.Count,
Sum = model.Sum,
Status = model.Status,
DateCreate = model.DateCreate,
DateImplement = model.DateImplement,
Id = model.Id,
};
}
public static Order? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Order()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
BouquetId = Convert.ToInt32(element.Element("BouquetId")!.Value),
Sum = Convert.ToDouble(element.Element("Sum")!.Value),
Count = Convert.ToInt32(element.Element("Count")!.Value),
Status = (OrderStatus)Enum.Parse(typeof(OrderStatus), element.Element("Status")!.Value),
DateCreate = Convert.ToDateTime(element.Element("DateCreate")!.Value),
DateImplement = string.IsNullOrEmpty(element.Element("DateImplement")!.Value) ? null : Convert.ToDateTime(element.Element("DateImplement")!.Value)
};
}
public void Update(OrderBindingModel? model)
{
if (model == null)
{
return;
}
BouquetId = model.BouquetId;
Count = model.Count;
Sum = model.Sum;
Status = model.Status;
DateCreate = model.DateCreate;
DateImplement = model.DateImplement;
Id = model.Id;
}
public OrderViewModel GetViewModel => new()
{
BouquetId = BouquetId,
Count = Count,
Sum = Sum,
DateCreate = DateCreate,
DateImplement = DateImplement,
Id = Id,
Status = Status,
};
public XElement GetXElement => new(
"Order",
new XAttribute("Id", Id),
new XElement("BouquetId", BouquetId.ToString()),
new XElement("Count", Count.ToString()),
new XElement("Sum", Sum.ToString()),
new XElement("Status", Status.ToString()),
new XElement("DateCreate", DateCreate.ToString()),
new XElement("DateImplement", DateImplement.ToString())
);
}
}

View File

@ -0,0 +1,123 @@
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.ViewModels;
using FlowerShopDataModels.Models;
using System.Xml.Linq;
namespace FlowerShopFileImplement.Models
{
public class Shop : IShopModel
{
public int Id { get; private set; }
public string Name { get; private set; } = string.Empty;
public string Address { get; private set; } = string.Empty;
public int MaxCountBouquets { get; private set; }
public DateTime OpeningDate { get; private set; }
public Dictionary<int, int> Bouquets { get; private set; } = new();
private Dictionary<int, (IBouquetModel, int)>? _shopBouquets = null;
public Dictionary<int, (IBouquetModel, int)> ShopBouquets
{
get
{
if (_shopBouquets == null)
{
var source = DataFileSingleton.GetInstance();
_shopBouquets = Bouquets.ToDictionary(
x => x.Key,
y => ((source.Bouquets.FirstOrDefault(z => z.Id == y.Key) as IBouquetModel)!, y.Value)
);
}
return _shopBouquets;
}
}
public static Shop? Create(ShopBindingModel? model)
{
if (model == null)
{
return null;
}
return new Shop()
{
Id = model.Id,
Name = model.Name,
Address = model.Address,
MaxCountBouquets = model.MaxCountBouquets,
OpeningDate = model.OpeningDate,
Bouquets = model.ShopBouquets.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),
Name = element.Element("Name")!.Value,
Address = element.Element("Address")!.Value,
MaxCountBouquets = Convert.ToInt32(element.Element("MaxCountBouquets")!.Value),
OpeningDate = Convert.ToDateTime(element.Element("OpeningDate")!.Value),
Bouquets = element.Element("ShopBouquets")!.Elements("ShopBouquet").ToDictionary(
x => Convert.ToInt32(x.Element("Key")?.Value),
x => Convert.ToInt32(x.Element("Value")?.Value)
)
};
}
public void Update(ShopBindingModel? model)
{
if (model == null)
{
return;
}
Name = model.Name;
Address = model.Address;
OpeningDate = model.OpeningDate;
MaxCountBouquets = model.MaxCountBouquets;
if (model.ShopBouquets.Count > 0)
{
Bouquets = model.ShopBouquets.ToDictionary(x => x.Key, x => x.Value.Item2);
_shopBouquets = null;
}
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
Name = Name,
Address = Address,
OpeningDate = OpeningDate,
ShopBouquets = ShopBouquets,
MaxCountBouquets = MaxCountBouquets
};
public XElement GetXElement => new(
"Shop",
new XAttribute("Id", Id),
new XElement("Name", Name),
new XElement("Address", Address),
new XElement("MaxCountBouquets", MaxCountBouquets),
new XElement("OpeningDate", OpeningDate.ToString()),
new XElement("ShopBouquets", Bouquets.Select(x =>
new XElement("ShopBouquet",
new XElement("Key", x.Key),
new XElement("Value", x.Value)))
.ToArray())
);
}
}

View File

@ -2,6 +2,7 @@
using FlowerShopContracts.SearchModels;
using FlowerShopContracts.StoragesContracts;
using FlowerShopContracts.ViewModels;
using FlowerShopDataModels.Models;
using FlowerShopListImplement.Models;
@ -117,5 +118,10 @@ namespace FlowerShopListImplement.Implements
return null;
}
public bool SellBouquet(IBouquetModel model, int count)
{
throw new NotImplementedException();
}
}
}

View File

@ -14,6 +14,8 @@ namespace FlowerShopListImplement.Models
public DateTime OpeningDate { get; private set; }
public int MaxCountBouquets { get; private set; }
public Dictionary<int, (IBouquetModel, int)> ShopBouquets { get; private set; } = new();
public static Shop? Create(ShopBindingModel model)
@ -29,6 +31,7 @@ namespace FlowerShopListImplement.Models
Name = model.Name,
Address = model.Address,
OpeningDate = model.OpeningDate,
MaxCountBouquets = model.MaxCountBouquets,
ShopBouquets = new()
};
}
@ -43,6 +46,7 @@ namespace FlowerShopListImplement.Models
Name = model.Name;
Address = model.Address;
ShopBouquets = model.ShopBouquets;
MaxCountBouquets = model.MaxCountBouquets;
}
public ShopViewModel GetViewModel => new()
@ -51,7 +55,8 @@ namespace FlowerShopListImplement.Models
Name = Name,
Address = Address,
OpeningDate = OpeningDate,
ShopBouquets = ShopBouquets
ShopBouquets = ShopBouquets,
MaxCountBouquets = MaxCountBouquets
};
}
}