Compare commits

...

5 Commits

29 changed files with 2264 additions and 24 deletions

View File

@ -14,9 +14,11 @@ namespace ComputersShopFileImplements
public readonly string ComponentFileName = "Component.xml";
public readonly string OrderFileName = "Order.xml";
public readonly string ComputerFileName = "Computer.xml";
public readonly string ShopFileName = "Shop.xml";
public List<Component> Components { get; private set; }
public List<Order> Orders { get; private set; }
public List<Computer> Computers { get; private set; }
public List<Shop> Shops { get; private set; }
public static DataFileSingleton GetInstance()
{
if (instance == null)
@ -31,14 +33,16 @@ namespace ComputersShopFileImplements
"Computers", 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)!)!;
Computers = LoadData(ComputerFileName, "Computer", x => Computer.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)
private static List<T>? LoadData<T>(string filename, string xmlNodeName, Func<XElement, T> selectFunction)
{
if (File.Exists(filename))
{

View File

@ -0,0 +1,127 @@
using ComputersShopContracts.BindingModels;
using ComputersShopContracts.SearchModels;
using ComputersShopContracts.StoragesContracts;
using ComputersShopContracts.ViewModels;
using ComputersShopDataModels.Models;
using ComputersShopFileImplements.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputersShopFileImplements.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> GetFiltredList(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.SaveComputers();
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.SaveComputers();
return shop.GetViewModel;
}
public ShopViewModel? Delete(ShopBindingModel model)
{
var element = source.Shops.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
source.Shops.Remove(element);
source.SaveComputers();
return element.GetViewModel;
}
return null;
}
public bool CheckAvailability(int computerId, int count)
{
int store = source.Shops.Select(x => x.ShopComputers.Select(y => (y.Value.Item1.Id == computerId ? y.Value.Item2 : 0)).Sum()).Sum();
return store >= count;
}
public bool SellComputers(IComputerModel model, int count)
{
var computer = source.Computers.FirstOrDefault(x => x.Id == model.Id);
if (computer == null || !CheckAvailability(model.Id, count))
{
return false;
}
for (int i = 0; i < source.Shops.Count; i++)
{
var shop = source.Shops[i];
var computers = shop.ShopComputers;
foreach (var comp in computers.Where(x => x.Value.Item1.Id == computer.Id))
{
var selling = Math.Min(comp.Value.Item2, count);
computers[comp.Value.Item1.Id] = (comp.Value.Item1, comp.Value.Item2 - selling);
count -= selling;
if (count <= 0)
{
break;
}
}
shop.Update(new ShopBindingModel
{
Id = model.Id,
ShopName = shop.ShopName,
Address = shop.Address,
MaxCount = shop.MaxCount,
DateOpen = shop.DateOpen,
ShopComputers = computers
});
}
source.SaveShops();
return true;
}
}
}

View File

@ -0,0 +1,102 @@
using ComputersShopContracts.BindingModels;
using ComputersShopContracts.ViewModels;
using ComputersShopDataModels.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace ComputersShopFileImplements.Models
{
public class Shop: IShopModel
{
public int Id { get; set; }
public string ShopName { get; set;}
public string Address { get; set;}
public DateTime DateOpen { get; set;}
public int MaxCount { get; set;}
public Dictionary<int, int> Computers { get; private set; } = new();
private Dictionary<int, (IComputerModel, int)>? _shopComputers = null;
public Dictionary<int, (IComputerModel, int)> ShopComputers
{
get
{
if (_shopComputers == null)
{
var source = DataFileSingleton.GetInstance();
_shopComputers = Computers.ToDictionary(x => x.Key, y => ((source.Computers.FirstOrDefault(z => z.Id == y.Key) as IComputerModel)!, y.Value));
}
return _shopComputers;
}
}
public static Shop? Create(ShopBindingModel model)
{
if (model == null)
{
return null;
}
return new Shop()
{
Id = model.Id,
ShopName = model.ShopName,
Address = model.Address,
MaxCount = model.MaxCount,
DateOpen = model.DateOpen,
Computers = model.ShopComputers.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),
MaxCount = Convert.ToInt32(element.Element("MaxCount")!.Value),
ShopName = element.Element("ShopName")!.Value,
Address = element.Element("Address")!.Value,
DateOpen = Convert.ToDateTime(element.Element("DateOpen")!.Value),
Computers = element.Element("ShopComputers")!.Elements("ShopComputer").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;
MaxCount = model.MaxCount;
DateOpen = model.DateOpen;
if (model.ShopComputers.Count > 0)
{
Computers = model.ShopComputers.ToDictionary(x => x.Key, x => x.Value.Item2);
_shopComputers = null;
}
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
ShopName = ShopName,
Address = Address,
MaxCount = MaxCount,
DateOpen = DateOpen,
ShopComputers = ShopComputers
};
public XElement GetXElement => new("Shop",
new XAttribute("Id", Id),
new XElement("ShopName", ShopName),
new XElement("Address", Address.ToString()),
new XElement("MaxCount", MaxCount.ToString()),
new XElement("DateOpen", DateOpen.ToString()),
new XElement("ShopComputers", Computers.Select(x => new XElement("ShopComputer", new XElement("Key", x.Key),
new XElement("Value", x.Value))).ToArray()));
}
}

View File

@ -32,12 +32,15 @@
справочникиToolStripMenuItem = new ToolStripMenuItem();
компонентыToolStripMenuItem = new ToolStripMenuItem();
комьютерыToolStripMenuItem = new ToolStripMenuItem();
магазиныToolStripMenuItem = new ToolStripMenuItem();
dataGridView = new DataGridView();
buttonCreateOrder = new Button();
buttonTakeOrderInWork = new Button();
buttonOrderReady = new Button();
buttonIssuedOrder = new Button();
buttonUpdate = new Button();
buttonSupplyShop = new Button();
buttonSell = new Button();
menuStrip.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
@ -53,7 +56,7 @@
//
// справочникиToolStripMenuItem
//
справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, комьютерыToolStripMenuItem });
справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, комьютерыToolStripMenuItem, магазиныToolStripMenuItem });
справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem";
справочникиToolStripMenuItem.Size = new Size(94, 20);
справочникиToolStripMenuItem.Text = "Справочники";
@ -72,6 +75,13 @@
комьютерыToolStripMenuItem.Text = "Комьютеры";
комьютерыToolStripMenuItem.Click += КомпьютерыToolStripMenuItem_Click;
//
// магазиныToolStripMenuItem
//
магазиныToolStripMenuItem.Name = агазиныToolStripMenuItem";
магазиныToolStripMenuItem.Size = new Size(145, 22);
магазиныToolStripMenuItem.Text = "Магазины";
магазиныToolStripMenuItem.Click += МагазиныToolStripMenuItem_Click;
//
// dataGridView
//
dataGridView.AllowUserToAddRows = false;
@ -138,11 +148,33 @@
buttonUpdate.UseVisualStyleBackColor = true;
buttonUpdate.Click += ButtonUpd_Click;
//
// buttonSupplyShop
//
buttonSupplyShop.Location = new Point(792, 327);
buttonSupplyShop.Name = "buttonSupplyShop";
buttonSupplyShop.Size = new Size(180, 35);
buttonSupplyShop.TabIndex = 7;
buttonSupplyShop.Text = "Пополнение магазина";
buttonSupplyShop.UseVisualStyleBackColor = true;
buttonSupplyShop.Click += buttonSupplyShop_Click;
//
// buttonSell
//
buttonSell.Location = new Point(792, 387);
buttonSell.Name = "buttonSell";
buttonSell.Size = new Size(180, 35);
buttonSell.TabIndex = 8;
buttonSell.Text = "Продажа";
buttonSell.UseVisualStyleBackColor = true;
buttonSell.Click += buttonSell_Click;
//
// FormMain
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(984, 450);
Controls.Add(buttonSell);
Controls.Add(buttonSupplyShop);
Controls.Add(buttonUpdate);
Controls.Add(buttonIssuedOrder);
Controls.Add(buttonOrderReady);
@ -173,5 +205,8 @@
private Button buttonOrderReady;
private Button buttonIssuedOrder;
private Button buttonUpdate;
private ToolStripMenuItem магазиныToolStripMenuItem;
private Button buttonSupplyShop;
private Button buttonSell;
}
}

View File

@ -68,6 +68,14 @@ namespace ComputersShop
form.ShowDialog();
}
}
private void МагазиныToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShops));
if (service is FormShops form)
{
form.ShowDialog();
}
}
private void ButtonCreateOrder_Click(object sender, EventArgs e)
{
@ -107,10 +115,12 @@ namespace ComputersShop
if (dataGridView.SelectedRows.Count == 1)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
var computerId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["ComputerId"].Value);
var count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value);
_logger.LogInformation("Order №{id}. Status changes to 'Готов'", id);
try
{
var operationResult = _orderLogic.FinishOrder(new OrderBindingModel { Id = id });
var operationResult = _orderLogic.FinishOrder(new OrderBindingModel { Id = id, ComputerId = computerId, Count = count });
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
@ -153,5 +163,23 @@ namespace ComputersShop
{
LoadData();
}
private void buttonSupplyShop_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShopSupply));
if (service is FormShopSupply form)
{
form.ShowDialog();
}
}
private void buttonSell_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSell));
if (service is FormSell form)
{
form.ShowDialog();
}
}
}
}

View File

@ -0,0 +1,119 @@
namespace ComputersShop
{
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()
{
labelComputer = new Label();
comboBoxComputer = new ComboBox();
buttonCancel = new Button();
buttonSave = new Button();
textBoxCount = new TextBox();
labelCount = new Label();
SuspendLayout();
//
// labelComputer
//
labelComputer.AutoSize = true;
labelComputer.Location = new Point(12, 9);
labelComputer.Name = "labelComputer";
labelComputer.Size = new Size(74, 15);
labelComputer.TabIndex = 23;
labelComputer.Text = "Компьютер:";
//
// comboBoxComputer
//
comboBoxComputer.FormattingEnabled = true;
comboBoxComputer.Location = new Point(90, 6);
comboBoxComputer.Margin = new Padding(3, 2, 3, 2);
comboBoxComputer.Name = "comboBoxComputer";
comboBoxComputer.Size = new Size(280, 23);
comboBoxComputer.TabIndex = 22;
//
// buttonCancel
//
buttonCancel.Location = new Point(270, 70);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(100, 30);
buttonCancel.TabIndex = 19;
buttonCancel.Text = "Отменить";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += buttonCancel_Click;
//
// buttonSave
//
buttonSave.Location = new Point(160, 70);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(100, 30);
buttonSave.TabIndex = 18;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += buttonSave_Click;
//
// textBoxCount
//
textBoxCount.Location = new Point(90, 34);
textBoxCount.Name = "textBoxCount";
textBoxCount.Size = new Size(280, 23);
textBoxCount.TabIndex = 17;
//
// labelCount
//
labelCount.AutoSize = true;
labelCount.Location = new Point(12, 37);
labelCount.Name = "labelCount";
labelCount.Size = new Size(75, 15);
labelCount.TabIndex = 16;
labelCount.Text = "Количество:";
//
// FormSell
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(385, 116);
Controls.Add(labelComputer);
Controls.Add(comboBoxComputer);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(textBoxCount);
Controls.Add(labelCount);
Name = "FormSell";
Text = "FormSell";
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label labelComputer;
private ComboBox comboBoxComputer;
private Button buttonCancel;
private Button buttonSave;
private TextBox textBoxCount;
private Label labelCount;
}
}

View File

@ -0,0 +1,124 @@
using ComputersShopContracts.BuisnessLogicsContracts;
using ComputersShopContracts.BusinessLogicsContracts;
using ComputersShopContracts.ViewModels;
using ComputersShopDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ComputersShop
{
public partial class FormSell : Form
{
private readonly List<ComputerViewModel>? _computerList;
IShopLogic _shopLogic;
IComputerLogic _computerLogic;
public FormSell(IComputerLogic computerLogic, IShopLogic shopLogic)
{
InitializeComponent();
_computerLogic = computerLogic;
_shopLogic = shopLogic;
_computerList = computerLogic.ReadList(null);
if (_computerList != null)
{
comboBoxComputer.DisplayMember = "ComputerName";
comboBoxComputer.ValueMember = "Id";
comboBoxComputer.DataSource = _computerList;
comboBoxComputer.SelectedItem = null;
}
}
public int ComputerId
{
get
{
return Convert.ToInt32(comboBoxComputer.SelectedValue);
}
set
{
comboBoxComputer.SelectedValue = value;
}
}
public IComputerModel? ComputerModel
{
get
{
if (_computerList == null)
{
return null;
}
foreach (var elem in _computerList)
{
if (elem.Id == ComputerId)
{
return elem;
}
}
return null;
}
}
public int Count
{
get
{
return Convert.ToInt32(textBoxCount.Text);
}
set
{
textBoxCount.Text = value.ToString();
}
}
private void buttonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCount.Text))
{
MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxComputer.SelectedValue == null)
{
MessageBox.Show("Выберите компьютер", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
int count = Convert.ToInt32(textBoxCount.Text);
bool res = _shopLogic.MakeSell(_computerLogic.ReadElement(new()
{
Id = Convert.ToInt32(comboBoxComputer.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)
{
Close();
}
}
}

View File

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

View File

@ -0,0 +1,212 @@
namespace ComputersShop
{
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()
{
textBoxName = new TextBox();
labelAddress = new Label();
labelName = new Label();
DateTimePickerDateOpen = new DateTimePicker();
labelDateOpen = new Label();
dataGridView = new DataGridView();
ColumnId = new DataGridViewTextBoxColumn();
ColumnComputer = new DataGridViewTextBoxColumn();
ColumnCount = new DataGridViewTextBoxColumn();
buttonCancel = new Button();
buttonSave = new Button();
textBoxAddress = new TextBox();
labelMaxCount = new Label();
numericUpDownMaxCount = new NumericUpDown();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownMaxCount).BeginInit();
SuspendLayout();
//
// textBoxName
//
textBoxName.Location = new Point(105, 6);
textBoxName.Name = "textBoxName";
textBoxName.Size = new Size(235, 23);
textBoxName.TabIndex = 11;
//
// labelAddress
//
labelAddress.AutoSize = true;
labelAddress.Location = new Point(12, 42);
labelAddress.Name = "labelAddress";
labelAddress.Size = new Size(43, 15);
labelAddress.TabIndex = 9;
labelAddress.Text = "Адрес:";
//
// labelName
//
labelName.AutoSize = true;
labelName.Location = new Point(12, 9);
labelName.Name = "labelName";
labelName.Size = new Size(62, 15);
labelName.TabIndex = 8;
labelName.Text = "Название:";
//
// DateTimePickerDateOpen
//
DateTimePickerDateOpen.Location = new Point(105, 72);
DateTimePickerDateOpen.Name = "DateTimePickerDateOpen";
DateTimePickerDateOpen.Size = new Size(235, 23);
DateTimePickerDateOpen.TabIndex = 15;
//
// labelDateOpen
//
labelDateOpen.AutoSize = true;
labelDateOpen.Location = new Point(12, 75);
labelDateOpen.Name = "labelDateOpen";
labelDateOpen.Size = new Size(87, 15);
labelDateOpen.TabIndex = 16;
labelDateOpen.Text = "Дата открытия";
//
// dataGridView
//
dataGridView.AllowUserToAddRows = false;
dataGridView.AllowUserToDeleteRows = false;
dataGridView.BackgroundColor = SystemColors.ButtonHighlight;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Columns.AddRange(new DataGridViewColumn[] { ColumnId, ColumnComputer, ColumnCount });
dataGridView.Location = new Point(12, 160);
dataGridView.MultiSelect = false;
dataGridView.Name = "dataGridView";
dataGridView.ReadOnly = true;
dataGridView.RowHeadersVisible = false;
dataGridView.RowTemplate.Height = 25;
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.Size = new Size(535, 250);
dataGridView.TabIndex = 17;
//
// ColumnId
//
ColumnId.HeaderText = "Id";
ColumnId.Name = "ColumnId";
ColumnId.ReadOnly = true;
ColumnId.Visible = false;
//
// ColumnComputer
//
ColumnComputer.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
ColumnComputer.HeaderText = "Компьютер";
ColumnComputer.Name = "ColumnComputer";
ColumnComputer.ReadOnly = true;
//
// ColumnCount
//
ColumnCount.HeaderText = "Количество";
ColumnCount.Name = "ColumnCount";
ColumnCount.ReadOnly = true;
//
// buttonCancel
//
buttonCancel.Location = new Point(445, 420);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(100, 30);
buttonCancel.TabIndex = 19;
buttonCancel.Text = "Отменить";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += buttonCancel_Click;
//
// buttonSave
//
buttonSave.Location = new Point(335, 420);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(100, 30);
buttonSave.TabIndex = 18;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += buttonSave_Click;
//
// textBoxAddress
//
textBoxAddress.Location = new Point(105, 39);
textBoxAddress.Name = "textBoxAddress";
textBoxAddress.Size = new Size(235, 23);
textBoxAddress.TabIndex = 20;
//
// labelMaxCount
//
labelMaxCount.AutoSize = true;
labelMaxCount.Location = new Point(12, 108);
labelMaxCount.Name = "labelMaxCount";
labelMaxCount.Size = new Size(80, 15);
labelMaxCount.TabIndex = 21;
labelMaxCount.Text = "Макс. кол-во";
//
// numericUpDownMaxCount
//
numericUpDownMaxCount.Location = new Point(105, 105);
numericUpDownMaxCount.Name = "numericUpDownMaxCount";
numericUpDownMaxCount.Size = new Size(235, 23);
numericUpDownMaxCount.TabIndex = 22;
//
// FormShop
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(559, 461);
Controls.Add(numericUpDownMaxCount);
Controls.Add(labelMaxCount);
Controls.Add(textBoxAddress);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(dataGridView);
Controls.Add(labelDateOpen);
Controls.Add(DateTimePickerDateOpen);
Controls.Add(textBoxName);
Controls.Add(labelAddress);
Controls.Add(labelName);
Name = "FormShop";
Text = "Магазин";
Load += FormShop_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownMaxCount).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private TextBox textBoxName;
private Label labelAddress;
private Label labelName;
private DateTimePicker DateTimePickerDateOpen;
private Label labelDateOpen;
private DataGridView dataGridView;
private DataGridViewTextBoxColumn ColumnId;
private DataGridViewTextBoxColumn ColumnComputer;
private DataGridViewTextBoxColumn ColumnCount;
private Button buttonCancel;
private Button buttonSave;
private TextBox textBoxAddress;
private Label labelMaxCount;
private NumericUpDown numericUpDownMaxCount;
}
}

View File

@ -0,0 +1,136 @@
using ComputersShopContracts.BindingModels;
using ComputersShopContracts.BusinessLogicsContracts;
using ComputersShopContracts.SearchModels;
using ComputersShopDataModels.Models;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ComputersShop
{
public partial class FormShop : Form
{
private readonly IShopLogic _logic;
private readonly ILogger _logger;
private Dictionary<int, (IComputerModel, int)> _shopComputers;
private int? _id;
public int Id { set { _id = value; } }
public FormShop(ILogger<FormShop> logger, IShopLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
_shopComputers = new();
}
private void FormShop_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
_logger.LogInformation("Loading shop");
try
{
var shop = _logic.ReadElement(new ShopSearchModel { Id = _id });
if (shop != null)
{
textBoxName.Text = shop.ShopName;
textBoxAddress.Text = shop.Address;
DateTimePickerDateOpen.Value = shop.DateOpen;
numericUpDownMaxCount.Value = shop.MaxCount;
_shopComputers = shop.ShopComputers ?? new Dictionary<int, (IComputerModel, int)>();
LoadData();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error during loading shop");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void LoadData()
{
_logger.LogInformation("Loading shop's bouquets");
try
{
if (_shopComputers != null)
{
dataGridView.Rows.Clear();
foreach (var computer in _shopComputers)
{
dataGridView.Rows.Add(new object[] { computer.Key, computer.Value.Item1.ComputerName, computer.Value.Item2 });
}
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error during loading shop's computers");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxName.Text))
{
MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxAddress.Text))
{
MessageBox.Show("Заполните адрес", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Saving shop");
try
{
var model = new ShopBindingModel
{
Id = _id ?? 0,
ShopName = textBoxName.Text,
Address = textBoxAddress.Text,
DateOpen = DateTimePickerDateOpen.Value,
MaxCount = (int)numericUpDownMaxCount.Value,
ShopComputers = _shopComputers
};
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, "Error during saving shop");
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,78 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="ColumnId.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnComputer.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnCount.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnId.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnComputer.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnCount.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root>

View File

@ -0,0 +1,147 @@
namespace ComputersShop
{
partial class FormShopSupply
{
/// <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()
{
buttonCancel = new Button();
buttonSave = new Button();
textBoxCount = new TextBox();
labelCount = new Label();
labelShop = new Label();
comboBoxShop = new ComboBox();
comboBoxComputer = new ComboBox();
labelComputer = new Label();
SuspendLayout();
//
// buttonCancel
//
buttonCancel.Location = new Point(270, 100);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(100, 30);
buttonCancel.TabIndex = 11;
buttonCancel.Text = "Отменить";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += buttonCancel_Click;
//
// buttonSave
//
buttonSave.Location = new Point(160, 100);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(100, 30);
buttonSave.TabIndex = 10;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += buttonSave_Click;
//
// textBoxCount
//
textBoxCount.Location = new Point(90, 64);
textBoxCount.Name = "textBoxCount";
textBoxCount.Size = new Size(280, 23);
textBoxCount.TabIndex = 9;
//
// labelCount
//
labelCount.AutoSize = true;
labelCount.Location = new Point(12, 67);
labelCount.Name = "labelCount";
labelCount.Size = new Size(75, 15);
labelCount.TabIndex = 7;
labelCount.Text = "Количество:";
//
// labelShop
//
labelShop.AutoSize = true;
labelShop.Location = new Point(12, 9);
labelShop.Name = "labelShop";
labelShop.Size = new Size(57, 15);
labelShop.TabIndex = 12;
labelShop.Text = "Магазин:";
//
// comboBoxShop
//
comboBoxShop.FormattingEnabled = true;
comboBoxShop.Location = new Point(90, 6);
comboBoxShop.Margin = new Padding(3, 2, 3, 2);
comboBoxShop.Name = "comboBoxShop";
comboBoxShop.Size = new Size(280, 23);
comboBoxShop.TabIndex = 13;
//
// comboBoxComputer
//
comboBoxComputer.FormattingEnabled = true;
comboBoxComputer.Location = new Point(90, 36);
comboBoxComputer.Margin = new Padding(3, 2, 3, 2);
comboBoxComputer.Name = "comboBoxComputer";
comboBoxComputer.Size = new Size(280, 23);
comboBoxComputer.TabIndex = 14;
//
// labelComputer
//
labelComputer.AutoSize = true;
labelComputer.Location = new Point(12, 39);
labelComputer.Name = "labelComputer";
labelComputer.Size = new Size(74, 15);
labelComputer.TabIndex = 15;
labelComputer.Text = "Компьютер:";
//
// FormShopSupply
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(384, 139);
Controls.Add(labelComputer);
Controls.Add(comboBoxComputer);
Controls.Add(comboBoxShop);
Controls.Add(labelShop);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(textBoxCount);
Controls.Add(labelCount);
Name = "FormShopSupply";
Text = "FormShopSupply";
Load += FormShopSupply_Load;
ResumeLayout(false);
PerformLayout();
}
#endregion
private Button buttonCancel;
private Button buttonSave;
private TextBox textBoxCount;
private TextBox textBoxName;
private Label labelCount;
private Label labelName;
private TextBox textBox1;
private Label labelShop;
private ComboBox comboBoxShop;
private ComboBox comboBoxComputer;
private Label labelComputer;
}
}

View File

@ -0,0 +1,127 @@
using ComputersShopContracts.BindingModels;
using ComputersShopContracts.BuisnessLogicsContracts;
using ComputersShopContracts.BusinessLogicsContracts;
using ComputersShopContracts.SearchModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ComputersShop
{
public partial class FormShopSupply : Form
{
private readonly ILogger _logger;
private readonly IComputerLogic _logicComputer;
private readonly IShopLogic _logicShop;
public FormShopSupply(ILogger<FormShopSupply> logger, IComputerLogic logicBouquet, IShopLogic logicShop)
{
InitializeComponent();
_logger = logger;
_logicComputer = logicBouquet;
_logicShop = logicShop;
}
private void FormShopSupply_Load(object sender, EventArgs e)
{
_logger.LogInformation("Loading computers for supplying");
try
{
var list = _logicComputer.ReadList(null);
if (list != null)
{
comboBoxComputer.DisplayMember = "ComputerName";
comboBoxComputer.ValueMember = "Id";
comboBoxComputer.DataSource = list;
comboBoxComputer.SelectedItem = null;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error during loading bouquets for supplying");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
_logger.LogInformation("Loading shops for supplying");
try
{
var list = _logicShop.ReadList(null);
if (list != null)
{
comboBoxShop.DisplayMember = "ShopName";
comboBoxShop.ValueMember = "Id";
comboBoxShop.DataSource = list;
comboBoxShop.SelectedItem = null;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error during loading shops for supplying");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCount.Text))
{
MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxComputer.SelectedValue == null)
{
MessageBox.Show("Выберите букет", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxShop.SelectedValue == null)
{
MessageBox.Show("Выберите магазин", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Creation of supply");
try
{
var operationResult = _logicShop.SupplyComputers(
new ShopSearchModel { Id = Convert.ToInt32(comboBoxShop.SelectedValue), Name = comboBoxShop.Text },
new ComputerBindingModel { Id = Convert.ToInt32(comboBoxComputer.SelectedValue), ComputerName = comboBoxComputer.Text },
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, "Error during creation of supply");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

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

View File

@ -0,0 +1,149 @@
namespace ComputersShop
{
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()
{
DataGridViewCellStyle dataGridViewCellStyle1 = new DataGridViewCellStyle();
DataGridViewCellStyle dataGridViewCellStyle2 = new DataGridViewCellStyle();
DataGridViewCellStyle dataGridViewCellStyle3 = new DataGridViewCellStyle();
buttonReload = new Button();
buttonDelete = new Button();
buttonUpdate = new Button();
buttonAdd = new Button();
dataGridView = new DataGridView();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// buttonReload
//
buttonReload.Location = new Point(432, 123);
buttonReload.Name = "buttonReload";
buttonReload.Size = new Size(140, 30);
buttonReload.TabIndex = 13;
buttonReload.Text = "Обновить";
buttonReload.UseVisualStyleBackColor = true;
buttonReload.Click += buttonUpdate_Click;
//
// buttonDelete
//
buttonDelete.Location = new Point(432, 87);
buttonDelete.Name = "buttonDelete";
buttonDelete.Size = new Size(140, 30);
buttonDelete.TabIndex = 12;
buttonDelete.Text = "Удалить";
buttonDelete.UseVisualStyleBackColor = true;
buttonDelete.Click += buttonDelete_Click;
//
// buttonUpdate
//
buttonUpdate.Location = new Point(432, 51);
buttonUpdate.Name = "buttonUpdate";
buttonUpdate.Size = new Size(140, 30);
buttonUpdate.TabIndex = 11;
buttonUpdate.Text = "Изменить";
buttonUpdate.UseVisualStyleBackColor = true;
buttonUpdate.Click += buttonEdit_Click;
//
// buttonAdd
//
buttonAdd.Location = new Point(432, 15);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(140, 30);
buttonAdd.TabIndex = 10;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += buttonAdd_Click;
//
// dataGridView
//
dataGridView.AllowUserToAddRows = false;
dataGridView.AllowUserToDeleteRows = false;
dataGridView.BackgroundColor = SystemColors.ButtonHighlight;
dataGridViewCellStyle1.Alignment = DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle1.BackColor = SystemColors.Control;
dataGridViewCellStyle1.Font = new Font("Segoe UI", 9F, FontStyle.Regular, GraphicsUnit.Point);
dataGridViewCellStyle1.ForeColor = SystemColors.WindowText;
dataGridViewCellStyle1.SelectionBackColor = SystemColors.Highlight;
dataGridViewCellStyle1.SelectionForeColor = SystemColors.HighlightText;
dataGridViewCellStyle1.WrapMode = DataGridViewTriState.True;
dataGridView.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle1;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewCellStyle2.Alignment = DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle2.BackColor = SystemColors.Window;
dataGridViewCellStyle2.Font = new Font("Segoe UI", 9F, FontStyle.Regular, GraphicsUnit.Point);
dataGridViewCellStyle2.ForeColor = SystemColors.ControlText;
dataGridViewCellStyle2.SelectionBackColor = SystemColors.Highlight;
dataGridViewCellStyle2.SelectionForeColor = SystemColors.HighlightText;
dataGridViewCellStyle2.WrapMode = DataGridViewTriState.False;
dataGridView.DefaultCellStyle = dataGridViewCellStyle2;
dataGridView.Dock = DockStyle.Left;
dataGridView.Location = new Point(0, 0);
dataGridView.MultiSelect = false;
dataGridView.Name = "dataGridView";
dataGridView.ReadOnly = true;
dataGridViewCellStyle3.Alignment = DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle3.BackColor = SystemColors.Control;
dataGridViewCellStyle3.Font = new Font("Segoe UI", 9F, FontStyle.Regular, GraphicsUnit.Point);
dataGridViewCellStyle3.ForeColor = SystemColors.WindowText;
dataGridViewCellStyle3.SelectionBackColor = SystemColors.Highlight;
dataGridViewCellStyle3.SelectionForeColor = SystemColors.HighlightText;
dataGridViewCellStyle3.WrapMode = DataGridViewTriState.True;
dataGridView.RowHeadersDefaultCellStyle = dataGridViewCellStyle3;
dataGridView.RowHeadersVisible = false;
dataGridView.RowTemplate.Height = 25;
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.Size = new Size(400, 361);
dataGridView.TabIndex = 9;
//
// FormShops
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(584, 361);
Controls.Add(buttonReload);
Controls.Add(buttonDelete);
Controls.Add(buttonUpdate);
Controls.Add(buttonAdd);
Controls.Add(dataGridView);
Name = "FormShops";
Text = "Магазины";
Load += FormShops_Load;
Click += FormShops_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private Button buttonReload;
private Button buttonDelete;
private Button buttonUpdate;
private Button buttonAdd;
private DataGridView dataGridView;
}
}

View File

@ -0,0 +1,122 @@
using ComputersShopContracts.BindingModels;
using ComputersShopContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ComputersShop
{
public partial class FormShops : Form
{
private readonly ILogger _logger;
private readonly IShopLogic _logic;
public FormShops(ILogger<FormShops> logger, IShopLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormShops_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["ShopName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["Address"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["DateOpen"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["ShopComputers"].Visible = false;
}
_logger.LogInformation("Loading shops");
}
catch (Exception ex)
{
_logger.LogError(ex, "Error during loading shops");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonUpdate_Click(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 buttonEdit_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShop));
if (service is FormShop form)
{
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
}
private void buttonDelete_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить магазин?", "Подтверждение", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Deleting shop");
try
{
if (!_logic.Delete(new ShopBindingModel { Id = id }))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error during deleting shop");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}
}

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,5 +1,6 @@
using ComputersShopBusinessLogic.BusinessLogics;
using ComputersShopContracts.BuisnessLogicsContracts;
using ComputersShopContracts.BusinessLogicsContracts;
using ComputersShopContracts.StoragesContracts;
using ComputersShopDatabaseImplements.Implements;
using Microsoft.Extensions.DependencyInjection;
@ -37,18 +38,24 @@ namespace ComputersShop
services.AddTransient<IComponentStorage, ComponentStorage>();
services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<IComputerStorage, ComputerStorage>();
services.AddTransient<IShopStorage, ShopStorage>();
services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<IComputerLogic, ComputerLogic>();
services.AddTransient<IShopLogic, ShopLogic>();
services.AddTransient<FormMain>();
services.AddTransient<FormMain>();
services.AddTransient<FormComponent>();
services.AddTransient<FormComponents>();
services.AddTransient<FormCreateOrder>();
services.AddTransient<FormComputer>();
services.AddTransient<FormComputerComponent>();
services.AddTransient<FormComputers>();
}
services.AddTransient<FormShop>();
services.AddTransient<FormShops>();
services.AddTransient<FormShopSupply>();
services.AddTransient<FormSell>();
}
}
}

View File

@ -1,9 +1,11 @@
using ComputersShopContracts.BindingModels;
using ComputersShopContracts.BuisnessLogicsContracts;
using ComputersShopContracts.BusinessLogicsContracts;
using ComputersShopContracts.SearchModels;
using ComputersShopContracts.StoragesContracts;
using ComputersShopContracts.ViewModels;
using ComputersShopDataModels.Enums;
using ComputersShopDataModels.Models;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
@ -17,10 +19,18 @@ namespace ComputersShopBusinessLogic.BusinessLogics
{
private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage;
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage)
private readonly IShopStorage _shopStorage;
private readonly IShopLogic _shopLogic;
private readonly IComputerStorage _computerStorage;
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage,
IShopStorage shopStorage, IShopLogic shopLogic, IComputerStorage computerStorage)
{
_logger = logger;
_orderStorage = orderStorage;
_shopStorage = shopStorage;
_shopLogic = shopLogic;
_computerStorage = computerStorage;
}
public List<OrderViewModel>? ReadList(OrderSearchModel? model)
{
@ -63,25 +73,26 @@ namespace ComputersShopBusinessLogic.BusinessLogics
return false;
}
if (newStatus == OrderStatus.Готов)
{
var computer = _computerStorage.GetElement(new ComputerSearchModel() { Id = model.ComputerId });
if (computer == null)
{
_logger.LogWarning("Status change error. Dress not found");
return false;
}
if (!CheckSupply(computer, model.Count))
{
_logger.LogWarning("Status change error. Shop doesnt have dresses");
return false;
}
}
model.Status = newStatus;
model.ComputerId = viewModel.ComputerId;
model.Count = viewModel.Count;
model.Sum = viewModel.Sum;
model.DateCreate = viewModel.DateCreate;
if (model.Status == OrderStatus.Готов)
if (model.Status == OrderStatus.Выдан)
{
model.DateImplement = DateTime.Now;
}
else
{
model.DateImplement = viewModel.DateImplement;
}
CheckModel(model, false);
if (_orderStorage.Update(model) == null)
{
_logger.LogWarning("Status change operation failed");
return false;
}
_orderStorage.Update(model);
return true;
}
public bool TakeOrderInWork(OrderBindingModel model)
@ -120,5 +131,64 @@ namespace ComputersShopBusinessLogic.BusinessLogics
}
_logger.LogInformation("Order. Id:{Id}. Sum:{Sum}. ComputerId:{ComputerId}", model.Id, model.Sum, model.ComputerId);
}
public bool CheckSupply(IComputerModel computer, int count)
{
if (count <= 0)
{
_logger.LogWarning("Check supply operation error. Dress count < 0");
return false;
}
int sumCapacity = _shopStorage.GetFullList().Select(x => x.MaxCount).Sum();
int sumCount = _shopStorage.GetFullList().Select(x => x.ShopComputers.Select(y => y.Value.Item2).Sum()).Sum();
int free = sumCapacity - sumCount;
if (free < count)
{
_logger.LogWarning("Check supply error. No place for new Computers");
return false;
}
foreach (var shop in _shopStorage.GetFullList())
{
free = shop.MaxCount;
foreach (var comp in shop.ShopComputers)
{
free -= comp.Value.Item2;
}
if (free == 0)
{
continue;
}
if (free >= count)
{
if (_shopLogic.SupplyComputers(new()
{
Id = shop.Id
}, computer, count))
{
count = 0;
}
else
{
_logger.LogWarning("Supply error");
return false;
}
}
else
{
if (_shopLogic.SupplyComputers(new() { Id = shop.Id }, computer, free))
count -= free;
else
{
_logger.LogWarning("Supply error");
return false;
}
}
if (count <= 0)
{
return true;
}
}
return false;
}
}
}

View File

@ -0,0 +1,173 @@
using ComputersShopContracts.BindingModels;
using ComputersShopContracts.BusinessLogicsContracts;
using ComputersShopContracts.SearchModels;
using ComputersShopContracts.StoragesContracts;
using ComputersShopContracts.ViewModels;
using ComputersShopDataModels.Models;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputersShopBusinessLogic.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. Id:{Id} Name:{Name}", model?.Id, model?.Name);
var list = model == null ? _shopStorage.GetFullList() : _shopStorage.GetFiltredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public ShopViewModel? ReadElement(ShopSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. ShopName:{ShopName}. Id:{Id}", model.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));
}
_logger.LogInformation("Computer. ComputerName:{ComputerName}. Cost:{Cost}. Id:{Id}", model.ShopName, model.Address, model.Id);
var element = _shopStorage.GetElement(new ShopSearchModel
{
Name = model.ShopName
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Магазин с таким названием уже есть");
}
}
public bool MakeSell(IComputerModel model, int count)
{
return _shopStorage.SellComputers(model, count);
}
public bool SupplyComputers(ShopSearchModel model, IComputerModel computer, int count)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (computer == null)
{
throw new ArgumentNullException(nameof(computer));
}
if (count <= 0)
{
throw new ArgumentNullException("Количесво товара должно быть больше 0");
}
ShopViewModel? currentShop = _shopStorage.GetElement(model);
if (currentShop == null)
{
throw new ArgumentNullException(nameof(currentShop));
}
_logger.LogInformation("Make Supply. Id: {Id}. ShopName: {Name}", model.Id, model.Name);
var countItems = currentShop.ShopComputers.Select(x => x.Value.Item2).Sum();
if (currentShop.MaxCount - countItems < count)
{
_logger.LogWarning("Shop is full");
return false;
}
if (currentShop.ShopComputers.TryGetValue(computer.Id, out var pair))
{
currentShop.ShopComputers[computer.Id] = (pair.Item1, pair.Item2 + count);
_logger.LogInformation("Add computers. ComputerName: {Name}. Count: {Name}", pair.Item1, pair.Item2 + count);
}
else
{
currentShop.ShopComputers.Add(computer.Id, (computer, count));
_logger.LogInformation("Add new computers. ComputerName: {Name}. Count: {Name}", pair.Item1, count);
}
return Update(new()
{
Id = currentShop.Id,
ShopName = currentShop.ShopName,
DateOpen = currentShop.DateOpen,
Address = currentShop.Address,
MaxCount = currentShop.MaxCount,
ShopComputers = currentShop.ShopComputers,
});
}
}
}

View File

@ -0,0 +1,20 @@
using ComputersShopDataModels.Enums;
using ComputersShopDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputersShopContracts.BindingModels
{
public class ShopBindingModel: IShopModel
{
public int Id { get; set; }
public string ShopName { get; set; }
public string Address { get; set; }
public DateTime DateOpen { get; set; } = DateTime.Now;
public int MaxCount { get; set; }
public Dictionary<int, (IComputerModel, int)> ShopComputers{ get; set; } = new();
}
}

View File

@ -0,0 +1,23 @@
using ComputersShopContracts.BindingModels;
using ComputersShopContracts.SearchModels;
using ComputersShopContracts.ViewModels;
using ComputersShopDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputersShopContracts.BusinessLogicsContracts
{
public interface IShopLogic
{
ShopViewModel? ReadElement(ShopSearchModel model);
List<ShopViewModel>? ReadList(ShopSearchModel? model);
bool Create(ShopBindingModel model);
bool Update(ShopBindingModel model);
bool Delete(ShopBindingModel model);
bool SupplyComputers(ShopSearchModel model, IComputerModel computer, int count);
bool MakeSell(IComputerModel model, int count);
}
}

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputersShopContracts.SearchModels
{
public class ShopSearchModel
{
public int? Id { get; set; }
public string? Name { get; set; }
}
}

View File

@ -0,0 +1,23 @@
using ComputersShopContracts.BindingModels;
using ComputersShopContracts.SearchModels;
using ComputersShopContracts.ViewModels;
using ComputersShopDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputersShopContracts.StoragesContracts
{
public interface IShopStorage
{
List<ShopViewModel> GetFullList();
List<ShopViewModel> GetFiltredList(ShopSearchModel model);
ShopViewModel? GetElement(ShopSearchModel model);
ShopViewModel? Insert(ShopBindingModel model);
ShopViewModel? Update(ShopBindingModel model);
ShopViewModel? Delete(ShopBindingModel model);
bool SellComputers(IComputerModel model, int count);
}
}

View File

@ -0,0 +1,27 @@
using ComputersShopDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputersShopContracts.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; } = DateTime.Now;
[DisplayName("Макс кол-во компьютеров")]
public int MaxCount { get; set; }
public Dictionary<int, (IComputerModel, int)> ShopComputers { get; set; } = new();
}
}

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputersShopDataModels.Models
{
public interface IShopModel: IId
{
string ShopName { get; }
string Address { get; }
DateTime DateOpen { get; }
int MaxCount { get; }
}
}

View File

@ -13,11 +13,13 @@ namespace ComputersShopListImplement
public List<Component> Components { get; set; }
public List<Order> Orders { get; set; }
public List<Computer> Computers { get; set; }
private DataListSingleton()
public List<Shop> Shops { get; set; }
private DataListSingleton()
{
Components = new List<Component>();
Orders = new List<Order>();
Computers = new List<Computer>();
Shops = new List<Shop>();
}
public static DataListSingleton GetInstance()
{

View File

@ -0,0 +1,115 @@
using ComputersShopContracts.BindingModels;
using ComputersShopContracts.SearchModels;
using ComputersShopContracts.StoragesContracts;
using ComputersShopContracts.ViewModels;
using ComputersShopDataModels.Models;
using ComputersShopListImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputersShopListImplement.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> GetFiltredList(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 CheckAvailability(int computerId, int count)
{
return true;
}
public bool SellComputers(IComputerModel model, int count)
{
return true;
}
}
}

View File

@ -0,0 +1,60 @@
using ComputersShopContracts.BindingModels;
using ComputersShopContracts.ViewModels;
using ComputersShopDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputersShopListImplement.Models
{
public class Shop: IShopModel
{
public int Id { get; private set; }
public string ShopName { get; private set; }
public string Address { get; private set; }
public DateTime DateOpen { get; private set; }
public int MaxCount { get; private set; }
public Dictionary<int, (IComputerModel, int)> ShopComputers { 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,
MaxCount = model.MaxCount,
ShopComputers = new()
};
}
public void Update(ShopBindingModel model)
{
if (model == null)
{
return;
}
ShopName = model.ShopName;
Address = model.Address;
DateOpen = model.DateOpen;
MaxCount = model.MaxCount;
ShopComputers = model.ShopComputers;
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
ShopName = ShopName,
Address = Address,
DateOpen = DateOpen,
MaxCount = MaxCount,
ShopComputers = ShopComputers
};
}
}