diff --git a/ComputersShop/ComputersShop/FormMain.Designer.cs b/ComputersShop/ComputersShop/FormMain.Designer.cs index bd23346..f092b8a 100644 --- a/ComputersShop/ComputersShop/FormMain.Designer.cs +++ b/ComputersShop/ComputersShop/FormMain.Designer.cs @@ -32,12 +32,15 @@ справочникиToolStripMenuItem = new ToolStripMenuItem(); компоненты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(); buttonRefresh = new Button(); + SellsToolStripMenuItem = new ToolStripMenuItem(); menuStrip.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); SuspendLayout(); @@ -54,7 +57,7 @@ // // справочникиToolStripMenuItem // - справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, компьютерыToolStripMenuItem }); + справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, компьютерыToolStripMenuItem, магазиныToolStripMenuItem, поставкиToolStripMenuItem, SellsToolStripMenuItem }); справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; справочникиToolStripMenuItem.Size = new Size(117, 24); справочникиToolStripMenuItem.Text = "Справочники"; @@ -62,17 +65,31 @@ // компонентыToolStripMenuItem // компонентыToolStripMenuItem.Name = "компонентыToolStripMenuItem"; - компонентыToolStripMenuItem.Size = new Size(184, 26); + компонентыToolStripMenuItem.Size = new Size(224, 26); компонентыToolStripMenuItem.Text = "Компоненты"; компонентыToolStripMenuItem.Click += ComponentsStripMenuItem_Click; // // компьютерыToolStripMenuItem // компьютерыToolStripMenuItem.Name = "компьютерыToolStripMenuItem"; - компьютерыToolStripMenuItem.Size = new Size(184, 26); + компьютерыToolStripMenuItem.Size = new Size(224, 26); компьютерыToolStripMenuItem.Text = "Компьютеры"; компьютерыToolStripMenuItem.Click += ComputersStripMenuItem_Click; // + // магазиныToolStripMenuItem + // + магазиныToolStripMenuItem.Name = "магазиныToolStripMenuItem"; + магазиныToolStripMenuItem.Size = new Size(224, 26); + магазиныToolStripMenuItem.Text = "Магазины"; + магазиныToolStripMenuItem.Click += ShopsToolStripMenuItem_Click; + // + // поставкиToolStripMenuItem + // + поставкиToolStripMenuItem.Name = "поставкиToolStripMenuItem"; + поставкиToolStripMenuItem.Size = new Size(224, 26); + поставкиToolStripMenuItem.Text = "Поставки"; + поставкиToolStripMenuItem.Click += SupplyToolStripMenuItem_Click; + // // dataGridView // dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; @@ -133,6 +150,13 @@ buttonRefresh.UseVisualStyleBackColor = true; buttonRefresh.Click += RefreshButton_Click; // + // SellsToolStripMenuItem + // + SellsToolStripMenuItem.Name = "SellsToolStripMenuItem"; + SellsToolStripMenuItem.Size = new Size(224, 26); + SellsToolStripMenuItem.Text = "Продажи"; + SellsToolStripMenuItem.Click += SellToolStripMenuItem_Click; + // // FormMain // AutoScaleDimensions = new SizeF(8F, 20F); @@ -168,5 +192,8 @@ private Button buttonOrderReady; private Button buttonIssuedOrder; private Button buttonRefresh; + private ToolStripMenuItem магазиныToolStripMenuItem; + private ToolStripMenuItem поставкиToolStripMenuItem; + private ToolStripMenuItem SellsToolStripMenuItem; } } \ No newline at end of file diff --git a/ComputersShop/ComputersShop/FormMain.cs b/ComputersShop/ComputersShop/FormMain.cs index d55f106..135adfd 100644 --- a/ComputersShop/ComputersShop/FormMain.cs +++ b/ComputersShop/ComputersShop/FormMain.cs @@ -69,6 +69,33 @@ namespace ComputersShop } } + private void SellToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormSell)); + if (service is FormSell form) + { + form.ShowDialog(); + } + } + + private void ShopsToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormShops)); + if (service is FormShops form) + { + form.ShowDialog(); + } + } + + private void SupplyToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormSupply)); + if (service is FormSupply form) + { + form.ShowDialog(); + } + } + private void CreateOrderButton_Click(object sender, EventArgs e) { var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); diff --git a/ComputersShop/ComputersShop/FormSell.Designer.cs b/ComputersShop/ComputersShop/FormSell.Designer.cs new file mode 100644 index 0000000..7742a33 --- /dev/null +++ b/ComputersShop/ComputersShop/FormSell.Designer.cs @@ -0,0 +1,125 @@ +namespace ComputersShop +{ + partial class FormSell + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + ComputerComboBox = new ComboBox(); + ComputerLabel = new Label(); + CountLabel = new Label(); + CountTextBox = new TextBox(); + SaveButton = new Button(); + CancelButton = new Button(); + SuspendLayout(); + // + // ComputerComboBox + // + ComputerComboBox.DropDownStyle = ComboBoxStyle.DropDownList; + ComputerComboBox.FormattingEnabled = true; + ComputerComboBox.Location = new Point(139, 19); + ComputerComboBox.Margin = new Padding(3, 4, 3, 4); + ComputerComboBox.Name = "ComputerComboBox"; + ComputerComboBox.Size = new Size(138, 28); + ComputerComboBox.TabIndex = 0; + // + // ComputerLabel + // + ComputerLabel.AutoSize = true; + ComputerLabel.Location = new Point(14, 27); + ComputerLabel.Name = "ComputerLabel"; + ComputerLabel.Size = new Size(101, 20); + ComputerLabel.TabIndex = 1; + ComputerLabel.Text = "Компьютеры"; + // + // CountLabel + // + CountLabel.AutoSize = true; + CountLabel.Location = new Point(24, 65); + CountLabel.Name = "CountLabel"; + CountLabel.Size = new Size(90, 20); + CountLabel.TabIndex = 2; + CountLabel.Text = "Количество"; + // + // CountTextBox + // + CountTextBox.Location = new Point(139, 55); + CountTextBox.Margin = new Padding(3, 4, 3, 4); + CountTextBox.Name = "CountTextBox"; + CountTextBox.Size = new Size(138, 27); + CountTextBox.TabIndex = 3; + // + // SaveButton + // + SaveButton.Location = new Point(73, 97); + SaveButton.Margin = new Padding(3, 4, 3, 4); + SaveButton.Name = "SaveButton"; + SaveButton.Size = new Size(86, 31); + SaveButton.TabIndex = 4; + SaveButton.Text = "Сохранить"; + SaveButton.UseVisualStyleBackColor = true; + SaveButton.Click += SaveButton_Click; + // + // CancelButton + // + CancelButton.Location = new Point(166, 97); + CancelButton.Margin = new Padding(3, 4, 3, 4); + CancelButton.Name = "CancelButton"; + CancelButton.Size = new Size(86, 31); + CancelButton.TabIndex = 5; + CancelButton.Text = "Отмена"; + CancelButton.UseVisualStyleBackColor = true; + CancelButton.Click += CancelButton_Click; + // + // FormSell + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(299, 144); + Controls.Add(CancelButton); + Controls.Add(SaveButton); + Controls.Add(CountTextBox); + Controls.Add(CountLabel); + Controls.Add(ComputerLabel); + Controls.Add(ComputerComboBox); + Margin = new Padding(3, 4, 3, 4); + Name = "FormSell"; + Text = "Форма продажи"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private ComboBox ComputerComboBox; + private Label ComputerLabel; + private Label CountLabel; + private TextBox CountTextBox; + private Button SaveButton; + private Button CancelButton; + + } +} \ No newline at end of file diff --git a/ComputersShop/ComputersShop/FormSell.cs b/ComputersShop/ComputersShop/FormSell.cs new file mode 100644 index 0000000..eb134fc --- /dev/null +++ b/ComputersShop/ComputersShop/FormSell.cs @@ -0,0 +1,121 @@ +using ComputersShopContracts.BisnessLogicsContracts; +using ComputersShopContracts.ViewModels; +using ComputersShopDataModels; +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? _ComputerList; + IShopLogic _shopLogic; + IComputerLogic _ComputerLogic; + public FormSell(IComputerLogic ComputerLogic, IShopLogic shopLogic) + { + InitializeComponent(); + _shopLogic = shopLogic; + _ComputerLogic = ComputerLogic; + _ComputerList = ComputerLogic.ReadList(null); + if (_ComputerList != null) + { + ComputerComboBox.DisplayMember = "ComputerName"; + ComputerComboBox.ValueMember = "Id"; + ComputerComboBox.DataSource = _ComputerList; + ComputerComboBox.SelectedItem = null; + } + } + public int ComputerId + { + get + { + return + Convert.ToInt32(ComputerComboBox.SelectedValue); + } + set + { + ComputerComboBox.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(CountTextBox.Text); } + set + { CountTextBox.Text = value.ToString(); } + } + + private void CancelButton_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + + private void SaveButton_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(CountTextBox.Text)) + { + MessageBox.Show("Заполните поле Количество", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (ComputerComboBox.SelectedValue == null) + { + MessageBox.Show("Выберите компьютер", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + + try + { + int count = Convert.ToInt32(CountTextBox.Text); + var computer = _ComputerLogic.ReadElement(new() { Id = Convert.ToInt32(ComputerComboBox.SelectedValue) }); + if (computer == null) + return; + bool res = _shopLogic.MakeSell(computer, count); + + if (!res) + { + throw new Exception("Ошибка при продаже."); + } + + MessageBox.Show("Продажа прошла успешно"); + DialogResult = DialogResult.OK; + Close(); + + } + catch (Exception err) + { + MessageBox.Show("Ошибка продажи"); + return; + } + } + } +} diff --git a/ComputersShop/ComputersShop/FormSell.resx b/ComputersShop/ComputersShop/FormSell.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/ComputersShop/ComputersShop/FormSell.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/ComputersShop/ComputersShop/FormShop.Designer.cs b/ComputersShop/ComputersShop/FormShop.Designer.cs new file mode 100644 index 0000000..b268142 --- /dev/null +++ b/ComputersShop/ComputersShop/FormShop.Designer.cs @@ -0,0 +1,227 @@ +namespace ComputersShop +{ + partial class FormShop + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + DateTimePicker = new DateTimePicker(); + NameTextBox = new TextBox(); + AddressTextBox = new TextBox(); + NameLabel = new Label(); + AdressLabel = new Label(); + DateLabel = new Label(); + SaveButton = new Button(); + CancelButton = new Button(); + DataGridView = new DataGridView(); + ID = new DataGridViewTextBoxColumn(); + ComputerName = new DataGridViewTextBoxColumn(); + Price = new DataGridViewTextBoxColumn(); + Count = new DataGridViewTextBoxColumn(); + CapacityUpDown = new NumericUpDown(); + CapacityLabel = new Label(); + ((System.ComponentModel.ISupportInitialize)DataGridView).BeginInit(); + ((System.ComponentModel.ISupportInitialize)CapacityUpDown).BeginInit(); + SuspendLayout(); + // + // DateTimePicker + // + DateTimePicker.Location = new Point(97, 93); + DateTimePicker.Margin = new Padding(3, 4, 3, 4); + DateTimePicker.Name = "DateTimePicker"; + DateTimePicker.Size = new Size(363, 27); + DateTimePicker.TabIndex = 0; + // + // NameTextBox + // + NameTextBox.Location = new Point(97, 16); + NameTextBox.Margin = new Padding(3, 4, 3, 4); + NameTextBox.Name = "NameTextBox"; + NameTextBox.Size = new Size(363, 27); + NameTextBox.TabIndex = 1; + // + // AddressTextBox + // + AddressTextBox.Location = new Point(97, 55); + AddressTextBox.Margin = new Padding(3, 4, 3, 4); + AddressTextBox.Name = "AddressTextBox"; + AddressTextBox.Size = new Size(363, 27); + AddressTextBox.TabIndex = 2; + // + // NameLabel + // + NameLabel.AutoSize = true; + NameLabel.Location = new Point(14, 20); + NameLabel.Name = "NameLabel"; + NameLabel.Size = new Size(77, 20); + NameLabel.TabIndex = 3; + NameLabel.Text = "Название"; + // + // AdressLabel + // + AdressLabel.AutoSize = true; + AdressLabel.Location = new Point(14, 59); + AdressLabel.Name = "AdressLabel"; + AdressLabel.Size = new Size(51, 20); + AdressLabel.TabIndex = 4; + AdressLabel.Text = "Адрес"; + // + // DateLabel + // + DateLabel.AutoSize = true; + DateLabel.Location = new Point(14, 101); + DateLabel.Name = "DateLabel"; + DateLabel.Size = new Size(41, 20); + DateLabel.TabIndex = 5; + DateLabel.Text = "Дата"; + // + // SaveButton + // + SaveButton.Location = new Point(282, 381); + SaveButton.Margin = new Padding(3, 4, 3, 4); + SaveButton.Name = "SaveButton"; + SaveButton.Size = new Size(86, 31); + SaveButton.TabIndex = 6; + SaveButton.Text = "Сохранить"; + SaveButton.UseVisualStyleBackColor = true; + SaveButton.Click += SaveButton_Click; + // + // CancelButton + // + CancelButton.Location = new Point(375, 381); + CancelButton.Margin = new Padding(3, 4, 3, 4); + CancelButton.Name = "CancelButton"; + CancelButton.Size = new Size(86, 31); + CancelButton.TabIndex = 7; + CancelButton.Text = "Отмена"; + CancelButton.UseVisualStyleBackColor = true; + CancelButton.Click += CancelButton_Click; + // + // DataGridView + // + DataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + DataGridView.Columns.AddRange(new DataGridViewColumn[] { ID, ComputerName, Price, Count }); + DataGridView.Location = new Point(14, 173); + DataGridView.Margin = new Padding(3, 4, 3, 4); + DataGridView.Name = "DataGridView"; + DataGridView.RowHeadersWidth = 51; + DataGridView.Size = new Size(447, 200); + DataGridView.TabIndex = 8; + // + // ID + // + ID.HeaderText = "id"; + ID.MinimumWidth = 6; + ID.Name = "ID"; + ID.Visible = false; + ID.Width = 125; + // + // ComputerName + // + ComputerName.HeaderText = "Название"; + ComputerName.MinimumWidth = 6; + ComputerName.Name = "ComputerName"; + ComputerName.ReadOnly = true; + ComputerName.Width = 150; + // + // Price + // + Price.HeaderText = "Цена"; + Price.MinimumWidth = 6; + Price.Name = "Price"; + Price.ReadOnly = true; + Price.Width = 125; + // + // Count + // + Count.HeaderText = "Количество"; + Count.MinimumWidth = 6; + Count.Name = "Count"; + Count.ReadOnly = true; + Count.Width = 125; + // + // CapacityUpDown + // + CapacityUpDown.Location = new Point(118, 130); + CapacityUpDown.Maximum = new decimal(new int[] { 10000, 0, 0, 0 }); + CapacityUpDown.Name = "CapacityUpDown"; + CapacityUpDown.Size = new Size(120, 27); + CapacityUpDown.TabIndex = 9; + // + // CapacityLabel + // + CapacityLabel.AutoSize = true; + CapacityLabel.Location = new Point(12, 137); + CapacityLabel.Name = "CapacityLabel"; + CapacityLabel.Size = new Size(100, 20); + CapacityLabel.TabIndex = 10; + CapacityLabel.Text = "Вместимость"; + // + // FormShop + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(470, 422); + Controls.Add(DataGridView); + Controls.Add(CancelButton); + Controls.Add(SaveButton); + Controls.Add(DateLabel); + Controls.Add(AdressLabel); + Controls.Add(NameLabel); + Controls.Add(AddressTextBox); + Controls.Add(NameTextBox); + Controls.Add(DateTimePicker); + Controls.Add(CapacityLabel); + Controls.Add(CapacityUpDown); + Margin = new Padding(3, 4, 3, 4); + Name = "FormShop"; + Text = "Магазин"; + Load += FormShop_Load; + ((System.ComponentModel.ISupportInitialize)DataGridView).EndInit(); + ((System.ComponentModel.ISupportInitialize)CapacityUpDown).EndInit(); + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private DateTimePicker DateTimePicker; + private TextBox NameTextBox; + private TextBox AddressTextBox; + private Label NameLabel; + private Label AdressLabel; + private Label DateLabel; + private Button SaveButton; + private Button CancelButton; + private DataGridView DataGridView; + private DataGridViewTextBoxColumn ID; + private DataGridViewTextBoxColumn ComputerName; + private DataGridViewTextBoxColumn Price; + private DataGridViewTextBoxColumn Count; + private NumericUpDown CapacityUpDown; + private Label CapacityLabel; + } +} \ No newline at end of file diff --git a/ComputersShop/ComputersShop/FormShop.cs b/ComputersShop/ComputersShop/FormShop.cs new file mode 100644 index 0000000..57ba413 --- /dev/null +++ b/ComputersShop/ComputersShop/FormShop.cs @@ -0,0 +1,124 @@ +using ComputersShopContracts.BindingModels; +using ComputersShopContracts.BisnessLogicsContracts; +using ComputersShopContracts.SearchModels; +using ComputersShopDataModels; +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 ILogger _logger; + private readonly IShopLogic _logic; + public int? _id; + private Dictionary _Computers; + public FormShop(ILogger logger, IShopLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + private void FormShop_Load(object sender, EventArgs e) + { + if (_id.HasValue) + { + _logger.LogInformation("Загрузка магазина"); + try + { + var shop = _logic.ReadElement(new ShopSearchModel { Id = _id }); + if (shop != null) + { + NameTextBox.Text = shop.ShopName; + AddressTextBox.Text = shop.Address; + DateTimePicker.Text = shop.DateOpen.ToString(); + CapacityUpDown.Value = shop.MaxCapacity; + _Computers = shop.ShopComputers ?? new Dictionary(); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки магазина"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + } + + private void LoadData() + { + _logger.LogInformation("Загрузка товаров магазина"); + try + { + if (_Computers != null) + { + foreach (var Computer in _Computers) + { + DataGridView.Rows.Add(new object[] { Computer.Key, Computer.Value.Item1.ComputerName, Computer.Value.Item1.Price, Computer.Value.Item2 }); + } + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки компьютеров магазина"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + + private void CancelButton_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + + private void SaveButton_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(NameTextBox.Text)) + { + MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (string.IsNullOrEmpty(AddressTextBox.Text)) + { + MessageBox.Show("Заполните адрес", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Сохранение магазина"); + try + { + var model = new ShopBindingModel + { + Id = _id ?? 0, + ShopName = NameTextBox.Text, + Address = AddressTextBox.Text, + DateOpen = DateTimePicker.Value.Date, + MaxCapacity = Convert.ToInt32(CapacityUpDown.Value), + }; + var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + Close(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка сохранения магазина"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } +} diff --git a/ComputersShop/ComputersShop/FormShop.resx b/ComputersShop/ComputersShop/FormShop.resx new file mode 100644 index 0000000..17b1a67 --- /dev/null +++ b/ComputersShop/ComputersShop/FormShop.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + True + + \ No newline at end of file diff --git a/ComputersShop/ComputersShop/FormShops.Designer.cs b/ComputersShop/ComputersShop/FormShops.Designer.cs new file mode 100644 index 0000000..dab691c --- /dev/null +++ b/ComputersShop/ComputersShop/FormShops.Designer.cs @@ -0,0 +1,119 @@ +namespace ComputersShop +{ + partial class FormShops + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + DataGridView = new DataGridView(); + AddButton = new Button(); + UpdateButton = new Button(); + RefreshButton = new Button(); + DeleteButton = new Button(); + ((System.ComponentModel.ISupportInitialize)DataGridView).BeginInit(); + SuspendLayout(); + // + // DataGridView + // + DataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + DataGridView.Location = new Point(14, 16); + DataGridView.Margin = new Padding(3, 4, 3, 4); + DataGridView.Name = "DataGridView"; + DataGridView.RowHeadersWidth = 51; + DataGridView.Size = new Size(449, 499); + DataGridView.TabIndex = 0; + // + // AddButton + // + AddButton.Location = new Point(470, 16); + AddButton.Margin = new Padding(3, 4, 3, 4); + AddButton.Name = "AddButton"; + AddButton.Size = new Size(130, 31); + AddButton.TabIndex = 1; + AddButton.Text = "Добавить"; + AddButton.UseVisualStyleBackColor = true; + AddButton.Click += AddButton_Click; + // + // UpdateButton + // + UpdateButton.Location = new Point(470, 55); + UpdateButton.Margin = new Padding(3, 4, 3, 4); + UpdateButton.Name = "UpdateButton"; + UpdateButton.Size = new Size(130, 31); + UpdateButton.TabIndex = 2; + UpdateButton.Text = "Изменить"; + UpdateButton.UseVisualStyleBackColor = true; + UpdateButton.Click += UpdateButton_Click; + // + // RefreshButton + // + RefreshButton.Location = new Point(470, 93); + RefreshButton.Margin = new Padding(3, 4, 3, 4); + RefreshButton.Name = "RefreshButton"; + RefreshButton.Size = new Size(130, 31); + RefreshButton.TabIndex = 3; + RefreshButton.Text = "Обновить"; + RefreshButton.UseVisualStyleBackColor = true; + RefreshButton.Click += RefreshButton_Click; + // + // DeleteButton + // + DeleteButton.Location = new Point(470, 132); + DeleteButton.Margin = new Padding(3, 4, 3, 4); + DeleteButton.Name = "DeleteButton"; + DeleteButton.Size = new Size(130, 31); + DeleteButton.TabIndex = 4; + DeleteButton.Text = "Удалить"; + DeleteButton.UseVisualStyleBackColor = true; + DeleteButton.Click += DeleteButton_Click; + // + // FormShops + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(616, 537); + Controls.Add(DeleteButton); + Controls.Add(RefreshButton); + Controls.Add(UpdateButton); + Controls.Add(AddButton); + Controls.Add(DataGridView); + Margin = new Padding(3, 4, 3, 4); + Name = "FormShops"; + Text = "Магазины"; + Load += FormShops_Load; + ((System.ComponentModel.ISupportInitialize)DataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView DataGridView; + private Button AddButton; + private Button UpdateButton; + private Button RefreshButton; + private Button DeleteButton; + } +} \ No newline at end of file diff --git a/ComputersShop/ComputersShop/FormShops.cs b/ComputersShop/ComputersShop/FormShops.cs new file mode 100644 index 0000000..a938087 --- /dev/null +++ b/ComputersShop/ComputersShop/FormShops.cs @@ -0,0 +1,118 @@ +using ComputersShopContracts.BindingModels; +using ComputersShopContracts.BisnessLogicsContracts; +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 logger, IShopLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + + private void LoadData() + { + try + { + var list = _logic.ReadList(null); + if (list != null) + { + DataGridView.DataSource = list; + DataGridView.Columns["Id"].Visible = false; + DataGridView.Columns["ShopName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + DataGridView.Columns["Address"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + DataGridView.Columns["DateOpen"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + DataGridView.Columns["ShopComputers"].Visible = false; + } + _logger.LogInformation("Загрузка магазинов"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки магазинов"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void FormShops_Load(object sender, EventArgs e) + { + LoadData(); + } + + private void AddButton_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 UpdateButton_Click(object sender, EventArgs e) + { + if (DataGridView.SelectedRows.Count == 1) + { + var service = Program.ServiceProvider?.GetService(typeof(FormShop)); + if (service is FormShop form) + { + var tmp = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value); + form._id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + } + + private void RefreshButton_Click(object sender, EventArgs e) + { + LoadData(); + } + + private void DeleteButton_Click(object sender, EventArgs e) + { + if (DataGridView.SelectedRows.Count == 1) + { + if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + int id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Удаление магазина"); + try + { + if (!_logic.Delete(new ShopBindingModel + { + Id = id + })) + { + throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка удаления магазина"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } + } +} diff --git a/ComputersShop/ComputersShop/FormShops.resx b/ComputersShop/ComputersShop/FormShops.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/ComputersShop/ComputersShop/FormShops.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/ComputersShop/ComputersShop/FormSupply.Designer.cs b/ComputersShop/ComputersShop/FormSupply.Designer.cs new file mode 100644 index 0000000..96a26b4 --- /dev/null +++ b/ComputersShop/ComputersShop/FormSupply.Designer.cs @@ -0,0 +1,149 @@ +namespace ComputersShop +{ + partial class FormSupply + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + ShopComboBox = new ComboBox(); + ComputerComboBox = new ComboBox(); + CountTextBox = new TextBox(); + SaveButton = new Button(); + CancelButton = new Button(); + labelShop = new Label(); + labelComputer = new Label(); + labelCount = new Label(); + SuspendLayout(); + // + // ShopComboBox + // + ShopComboBox.DropDownStyle = ComboBoxStyle.DropDownList; + ShopComboBox.FormattingEnabled = true; + ShopComboBox.Location = new Point(176, 21); + ShopComboBox.Margin = new Padding(3, 4, 3, 4); + ShopComboBox.Name = "ShopComboBox"; + ShopComboBox.Size = new Size(378, 28); + ShopComboBox.TabIndex = 0; + // + // ComputerComboBox + // + ComputerComboBox.DropDownStyle = ComboBoxStyle.DropDownList; + ComputerComboBox.FormattingEnabled = true; + ComputerComboBox.Location = new Point(176, 60); + ComputerComboBox.Margin = new Padding(3, 4, 3, 4); + ComputerComboBox.Name = "ComputerComboBox"; + ComputerComboBox.Size = new Size(378, 28); + ComputerComboBox.TabIndex = 1; + // + // CountTextBox + // + CountTextBox.Location = new Point(176, 98); + CountTextBox.Margin = new Padding(3, 4, 3, 4); + CountTextBox.Name = "CountTextBox"; + CountTextBox.Size = new Size(378, 27); + CountTextBox.TabIndex = 2; + // + // SaveButton + // + SaveButton.Location = new Point(376, 137); + SaveButton.Margin = new Padding(3, 4, 3, 4); + SaveButton.Name = "SaveButton"; + SaveButton.Size = new Size(86, 31); + SaveButton.TabIndex = 3; + SaveButton.Text = "Сохранить"; + SaveButton.UseVisualStyleBackColor = true; + SaveButton.Click += SaveButton_Click; + // + // CancelButton + // + CancelButton.Location = new Point(468, 137); + CancelButton.Margin = new Padding(3, 4, 3, 4); + CancelButton.Name = "CancelButton"; + CancelButton.Size = new Size(86, 31); + CancelButton.TabIndex = 4; + CancelButton.Text = "Отмена"; + CancelButton.UseVisualStyleBackColor = true; + CancelButton.Click += CancelButton_Click; + // + // labelShop + // + labelShop.AutoSize = true; + labelShop.Location = new Point(40, 24); + labelShop.Name = "labelShop"; + labelShop.Size = new Size(69, 20); + labelShop.TabIndex = 5; + labelShop.Text = "Магазин"; + // + // labelComputer + // + labelComputer.AutoSize = true; + labelComputer.Location = new Point(40, 63); + labelComputer.Name = "labelComputer"; + labelComputer.Size = new Size(90, 20); + labelComputer.TabIndex = 6; + labelComputer.Text = "Компьютер"; + // + // labelCount + // + labelCount.AutoSize = true; + labelCount.Location = new Point(40, 101); + labelCount.Name = "labelCount"; + labelCount.Size = new Size(90, 20); + labelCount.TabIndex = 7; + labelCount.Text = "Количество"; + // + // FormSupply + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(607, 181); + Controls.Add(labelCount); + Controls.Add(labelComputer); + Controls.Add(labelShop); + Controls.Add(CancelButton); + Controls.Add(SaveButton); + Controls.Add(CountTextBox); + Controls.Add(ComputerComboBox); + Controls.Add(ShopComboBox); + Margin = new Padding(3, 4, 3, 4); + Name = "FormSupply"; + Text = "Поставки"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private ComboBox ShopComboBox; + private ComboBox ComputerComboBox; + private TextBox CountTextBox; + private Button SaveButton; + private Button CancelButton; + private Label labelShop; + private Label labelComputer; + private Label labelCount; + } +} \ No newline at end of file diff --git a/ComputersShop/ComputersShop/FormSupply.cs b/ComputersShop/ComputersShop/FormSupply.cs new file mode 100644 index 0000000..7986576 --- /dev/null +++ b/ComputersShop/ComputersShop/FormSupply.cs @@ -0,0 +1,151 @@ +using ComputersShopContracts.BisnessLogicsContracts; +using ComputersShopContracts.SearchModels; +using ComputersShopContracts.ViewModels; +using ComputersShopDataModels; +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 FormSupply : Form + { + private readonly List? _ComputerList; + private readonly List? _shopsList; + IShopLogic _shopLogic; + IComputerLogic _ComputerLogic; + public int ShopId + { + get + { + return + Convert.ToInt32(ShopComboBox.SelectedValue); + } + set + { + ShopComboBox.SelectedValue = value; + } + } + public int ComputerId + { + get + { + return + Convert.ToInt32(ComputerComboBox.SelectedValue); + } + set + { + ComputerComboBox.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(CountTextBox.Text); } + set + { CountTextBox.Text = value.ToString(); } + } + public FormSupply(IComputerLogic ComputerLogic, IShopLogic shopLogic) + { + InitializeComponent(); + _shopLogic = shopLogic; + _ComputerLogic = ComputerLogic; + _ComputerList = ComputerLogic.ReadList(null); + _shopsList = shopLogic.ReadList(null); + if (_ComputerList != null) + { + ComputerComboBox.DisplayMember = "ComputerName"; + ComputerComboBox.ValueMember = "Id"; + ComputerComboBox.DataSource = _ComputerList; + ComputerComboBox.SelectedItem = null; + } + if (_shopsList != null) + { + ShopComboBox.DisplayMember = "ShopName"; + ShopComboBox.ValueMember = "Id"; + ShopComboBox.DataSource = _shopsList; + ShopComboBox.SelectedItem = null; + } + } + + private void SaveButton_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(CountTextBox.Text)) + { + MessageBox.Show("Заполните поле Количество", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (ComputerComboBox.SelectedValue == null) + { + MessageBox.Show("Выберите компьютер", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (ShopComboBox.SelectedValue == null) + { + MessageBox.Show("Выберите магазин", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + + try + { + int count = Convert.ToInt32(CountTextBox.Text); + + bool res = _shopLogic.MakeSupply( + new ShopSearchModel() { Id = Convert.ToInt32(ShopComboBox.SelectedValue) }, + _ComputerLogic.ReadElement(new() { Id = Convert.ToInt32(ComputerComboBox.SelectedValue) }), + count + ); + + if (!res) + { + throw new Exception("Ошибка при пополнении. Дополнительная информация в логах"); + } + + MessageBox.Show("Пополнение прошло успешно"); + DialogResult = DialogResult.OK; + Close(); + + } + catch (Exception err) + { + MessageBox.Show("Ошибка пополнения"); + return; + } + } + + private void CancelButton_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } +} diff --git a/ComputersShop/ComputersShop/FormSupply.resx b/ComputersShop/ComputersShop/FormSupply.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/ComputersShop/ComputersShop/FormSupply.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/ComputersShop/ComputersShop/Program.cs b/ComputersShop/ComputersShop/Program.cs index 8131e37..6026f6a 100644 --- a/ComputersShop/ComputersShop/Program.cs +++ b/ComputersShop/ComputersShop/Program.cs @@ -41,6 +41,8 @@ namespace ComputersShop services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -48,6 +50,10 @@ namespace ComputersShop services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); } } diff --git a/ComputersShop/ComputersShopBusinessLogic/BusinessLogics/OrderLogic.cs b/ComputersShop/ComputersShopBusinessLogic/BusinessLogics/OrderLogic.cs index 23307d6..484709d 100644 --- a/ComputersShop/ComputersShopBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/ComputersShop/ComputersShopBusinessLogic/BusinessLogics/OrderLogic.cs @@ -3,6 +3,7 @@ using ComputersShopContracts.BisnessLogicsContracts; using ComputersShopContracts.SearchModels; using ComputersShopContracts.StoragesContracts; using ComputersShopContracts.ViewModels; +using ComputersShopDataModels; using ComputersShopDataModels.Enums; using Microsoft.Extensions.Logging; @@ -12,11 +13,18 @@ namespace ComputersShopBusinessLogic.BusinessLogics { private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; + private readonly IShopStorage _shopStorage; + private readonly IShopLogic _shopLogic; + private readonly IComputerStorage _computerStorage; - public OrderLogic(ILogger logger, IOrderStorage orderStorage) + public OrderLogic(IOrderStorage orderStorage, IShopStorage shopStorage, IShopLogic shopLogic, IComputerStorage computerStorage, ILogger logger) { _logger = logger; _orderStorage = orderStorage; + _shopStorage = shopStorage; + _logger = logger; + _shopLogic = shopLogic; + _computerStorage = computerStorage; } public List? ReadList(OrderSearchModel? model) @@ -45,8 +53,66 @@ namespace ComputersShopBusinessLogic.BusinessLogics } return true; } + private bool CheckSupply(IComputerModel Computer, int count) + { + if (count <= 0) + { + _logger.LogWarning("Check then supply operation error. Computer count < 0."); + return false; + } - public bool ChangeStatus(OrderBindingModel model, OrderStatus status) + int sumCapacity = 0; + int sumCount = 0; + sumCapacity = _shopStorage.GetFullList().Select(x => x.MaxCapacity).Sum(); + sumCount = _shopStorage.GetFullList().Select(x => x.ShopComputers.Select(y => y.Value.Item2).Sum()).Sum(); + int freeSpace = sumCapacity - sumCount; + + if (freeSpace - count < 0) + { + _logger.LogWarning("Check then supply operation error. There's no place for new Computer in shops."); + return false; + } + + foreach (var shop in _shopStorage.GetFullList()) + { + freeSpace = shop.MaxCapacity; + foreach (var doc in shop.ShopComputers) + { + freeSpace -= doc.Value.Item2; + } + if (freeSpace == 0) + { + continue; + } + if (freeSpace - count >= 0) + { + if (_shopLogic.MakeSupply(new() { Id = shop.Id }, Computer, count)) + count = 0; + else + { + _logger.LogWarning("Supply error"); + return false; + } + } + if (freeSpace - count < 0) + { + if (_shopLogic.MakeSupply(new() { Id = shop.Id }, Computer, freeSpace)) + count -= freeSpace; + else + { + _logger.LogWarning("Supply error"); + return false; + } + } + if (count <= 0) + { + return true; + } + } + return false; + } + + private bool ChangeStatus(OrderBindingModel model, OrderStatus status) { CheckModel(model); var element = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id }); @@ -60,6 +126,20 @@ namespace ComputersShopBusinessLogic.BusinessLogics _logger.LogWarning("Status change operation failed"); throw new InvalidOperationException("Текущий статус заказа не может быть переведен в выбранный"); } + if (element.Status == OrderStatus.Готов) + { + var computer = _computerStorage.GetElement(new ComputerSearchModel() { Id = model.ComputerId }); + if (computer == null) + { + _logger.LogWarning("Status update to " + status.ToString() + " operation failed. Document not found."); + return false; + } + if (CheckSupply(computer, model.Count) == false) + { + _logger.LogWarning("Status update to " + status.ToString() + " operation failed. Shop supply error."); + return false; + } + } model.Status = status; if (model.Status == OrderStatus.Выдан) model.DateImplement = DateTime.Now; _orderStorage.Update(model); diff --git a/ComputersShop/ComputersShopBusinessLogic/BusinessLogics/ShopLogic.cs b/ComputersShop/ComputersShopBusinessLogic/BusinessLogics/ShopLogic.cs new file mode 100644 index 0000000..bf48a5c --- /dev/null +++ b/ComputersShop/ComputersShopBusinessLogic/BusinessLogics/ShopLogic.cs @@ -0,0 +1,176 @@ +using ComputersShopContracts.BindingModels; +using ComputersShopContracts.BisnessLogicsContracts; +using ComputersShopContracts.SearchModels; +using ComputersShopContracts.StoragesContracts; +using ComputersShopContracts.ViewModels; +using ComputersShopDataModels; +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 logger, IShopStorage shopStorage) + { + _logger = logger; + _shopStorage = shopStorage; + } + + public List ReadList(ShopSearchModel model) + { + _logger.LogInformation("ReadList. ShopName:{Name}. Id:{ Id}", model?.Name, model?.Id); + var list = model == null ? _shopStorage.GetFullList() : _shopStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + _logger.LogInformation("ReadList. Count:{Count}", list.Count); + return list; + + } + + public bool MakeSupply(ShopSearchModel model, 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("Количество должно быть положительным числом"); + + ShopViewModel curModel = _shopStorage.GetElement(model); + if (curModel == null) + throw new ArgumentNullException(nameof(curModel)); + var countItems = curModel.ShopComputers.Select(x => x.Value.Item2).Sum(); + if (curModel.MaxCapacity - countItems >= count) + { + if (curModel.ShopComputers.TryGetValue(computer.Id, out var sameDocument)) + { + curModel.ShopComputers[computer.Id] = (computer, sameDocument.Item2 + count); + _logger.LogInformation("Same computer found by supply. Added {0} of {1} in {2} shop", count, computer.ComputerName, curModel.ShopName); + } + else + { + curModel.ShopComputers[computer.Id] = (computer, count); + _logger.LogInformation("New computer added by supply. Added {0} of {1} in {2} shop", count, computer.ComputerName, curModel.ShopName); + } + _shopStorage.Update(new() + { + Id = curModel.Id, + ShopName = curModel.ShopName, + Address = curModel.Address, + DateOpen = curModel.DateOpen, + ShopComputers = curModel.ShopComputers, + MaxCapacity = curModel.MaxCapacity + }); + } + else + { + _logger.LogWarning("Required shop is overflowed"); + return false; + } + return true; + } + + public ShopViewModel ReadElement(ShopSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + _logger.LogInformation("ReadElement. ShopName:{ShopName}.Id:{ Id}", model.Name, model.Id); + var element = _shopStorage.GetElement(model); + if (element == null) + { + _logger.LogWarning("ReadElement element not found"); + return null; + } + _logger.LogInformation("ReadElement find. Id:{Id}", element.Id); + return element; + } + + public bool Create(ShopBindingModel model) + { + CheckModel(model); + if (_shopStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } + + public bool Update(ShopBindingModel model) + { + CheckModel(model); + if (_shopStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + return true; + } + public bool Delete(ShopBindingModel model) + { + CheckModel(model, false); + _logger.LogInformation("Delete. Id:{Id}", model.Id); + if (_shopStorage.Delete(model) == null) + { + _logger.LogWarning("Delete operation failed"); + return false; + } + return true; + } + + private void CheckModel(ShopBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (!withParams) + { + return; + } + if (string.IsNullOrEmpty(model.ShopName)) + { + throw new ArgumentNullException("Нет названия магазина", + nameof(model.ShopName)); + } + if (string.IsNullOrEmpty(model.Address)) + { + throw new ArgumentNullException("Нет адресса магазина", + nameof(model.Address)); + } + if (model.DateOpen == null) + { + throw new ArgumentNullException("Нет даты открытия магазина", + nameof(model.DateOpen)); + } + _logger.LogInformation("Shop. ShopName:{ShopName}.Address:{Address}. DateOpen:{DateOpen}. Id: { Id}", model.ShopName, model.Address, model.DateOpen, model.Id); + var element = _shopStorage.GetElement(new ShopSearchModel + { + Name = model.ShopName + }); + if (element != null && element.Id != model.Id) + { + throw new InvalidOperationException("Магазин с таким названием уже есть"); + } + } + + public bool MakeSell(IComputerModel computer, int count) + { + return _shopStorage.SellComputers(computer, count); + } + } +} diff --git a/ComputersShop/ComputersShopContracts/BindingModels/ShopBindingModel.cs b/ComputersShop/ComputersShopContracts/BindingModels/ShopBindingModel.cs new file mode 100644 index 0000000..a32128b --- /dev/null +++ b/ComputersShop/ComputersShopContracts/BindingModels/ShopBindingModel.cs @@ -0,0 +1,19 @@ +using ComputersShopDataModels; +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; } + public int MaxCapacity { get; set; } + public Dictionary ShopComputers { get; set; } = new(); + } +} diff --git a/ComputersShop/ComputersShopContracts/BisnessLogicsContracts/IShopLogic.cs b/ComputersShop/ComputersShopContracts/BisnessLogicsContracts/IShopLogic.cs new file mode 100644 index 0000000..bb6f5c5 --- /dev/null +++ b/ComputersShop/ComputersShopContracts/BisnessLogicsContracts/IShopLogic.cs @@ -0,0 +1,24 @@ +using ComputersShopContracts.BindingModels; +using ComputersShopContracts.SearchModels; +using ComputersShopContracts.ViewModels; +using ComputersShopDataModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopContracts.BisnessLogicsContracts +{ + public interface IShopLogic + { + List? ReadList(ShopSearchModel? model); + ShopViewModel? ReadElement(ShopSearchModel model); + bool Create(ShopBindingModel model); + bool Update(ShopBindingModel model); + bool Delete(ShopBindingModel model); + bool MakeSupply(ShopSearchModel model, IComputerModel computer, int count); + bool MakeSell(IComputerModel computer, int count); + + } +} diff --git a/ComputersShop/ComputersShopContracts/SearchModels/ShopSearchModel.cs b/ComputersShop/ComputersShopContracts/SearchModels/ShopSearchModel.cs new file mode 100644 index 0000000..228bd84 --- /dev/null +++ b/ComputersShop/ComputersShopContracts/SearchModels/ShopSearchModel.cs @@ -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; } + } +} diff --git a/ComputersShop/ComputersShopContracts/StoragesContracts/IShopStorage.cs b/ComputersShop/ComputersShopContracts/StoragesContracts/IShopStorage.cs new file mode 100644 index 0000000..74de3c0 --- /dev/null +++ b/ComputersShop/ComputersShopContracts/StoragesContracts/IShopStorage.cs @@ -0,0 +1,24 @@ +using ComputersShopContracts.BindingModels; +using ComputersShopContracts.SearchModels; +using ComputersShopContracts.ViewModels; +using ComputersShopDataModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopContracts.StoragesContracts +{ + public interface IShopStorage + { + List GetFullList(); + List GetFilteredList(ShopSearchModel model); + ShopViewModel? GetElement(ShopSearchModel model); + ShopViewModel? Insert(ShopBindingModel model); + ShopViewModel? Update(ShopBindingModel model); + ShopViewModel? Delete(ShopBindingModel model); + public bool SellComputers(IComputerModel model, int count); + + } +} diff --git a/ComputersShop/ComputersShopContracts/ViewModels/ShopViewModel.cs b/ComputersShop/ComputersShopContracts/ViewModels/ShopViewModel.cs new file mode 100644 index 0000000..4e874a5 --- /dev/null +++ b/ComputersShop/ComputersShopContracts/ViewModels/ShopViewModel.cs @@ -0,0 +1,24 @@ +using ComputersShopDataModels; +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; } + [DisplayName("Адрес магазина")] + public string Address { get; set; } + [DisplayName("Дата открытия")] + public DateTime DateOpen { get; set; } + [DisplayName("Вместимость")] + public int MaxCapacity { get; set; } + public Dictionary ShopComputers { get; set; } = new(); + } +} diff --git a/ComputersShop/ComputersShopDataModels/IShopModel.cs b/ComputersShop/ComputersShopDataModels/IShopModel.cs new file mode 100644 index 0000000..aa0c78d --- /dev/null +++ b/ComputersShop/ComputersShopDataModels/IShopModel.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopDataModels +{ + public interface IShopModel : IId + { + string ShopName { get; } + string Address { get; } + DateTime DateOpen { get; } + int MaxCapacity { get; } + Dictionary ShopComputers { get; } + } +} diff --git a/ComputersShop/ComputersShopFileImplement/DataFileSingleton.cs b/ComputersShop/ComputersShopFileImplement/DataFileSingleton.cs index 71f410d..a884739 100644 --- a/ComputersShop/ComputersShopFileImplement/DataFileSingleton.cs +++ b/ComputersShop/ComputersShopFileImplement/DataFileSingleton.cs @@ -14,9 +14,13 @@ namespace ComputersShopFileImplement private readonly string ComponentFileName = "Component.xml"; private readonly string OrderFileName = "Order.xml"; private readonly string ComputerFileName = "Computer.xml"; + private readonly string ShopFileName = "Shops.xml"; + public List Components { get; private set; } public List Orders { get; private set; } public List Computers { get; private set; } + public List Shops { get; private set; } + public static DataFileSingleton GetInstance() { if (instance == null) @@ -28,11 +32,13 @@ namespace ComputersShopFileImplement public void SaveComponents() => SaveData(Components, ComponentFileName, "Components", x => x.GetXElement); public void SaveComputers() => SaveData(Computers, ComputerFileName, "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? LoadData(string filename, string xmlNodeName, Func selectFunction) { diff --git a/ComputersShop/ComputersShopFileImplement/Implements/ShopStorage.cs b/ComputersShop/ComputersShopFileImplement/Implements/ShopStorage.cs new file mode 100644 index 0000000..83221c2 --- /dev/null +++ b/ComputersShop/ComputersShopFileImplement/Implements/ShopStorage.cs @@ -0,0 +1,124 @@ +using ComputersShopContracts.BindingModels; +using ComputersShopContracts.SearchModels; +using ComputersShopContracts.StoragesContracts; +using ComputersShopContracts.ViewModels; +using ComputersShopDataModels; +using ComputersShopFileImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopFileImplement.Implements +{ + public class ShopStorage : IShopStorage + { + private readonly DataFileSingleton _source; + public ShopStorage() + { + _source = DataFileSingleton.GetInstance(); + } + public List GetFullList() + { + return _source.Shops.Select(x => x.GetViewModel).ToList(); + } + public List GetFilteredList(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.Name)) + { + return new(); + } + return _source.Shops.Where(x => x.ShopName.Contains(model.Name)).Select(x => x.GetViewModel).ToList(); + } + public ShopViewModel? GetElement(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.Name) && !model.Id.HasValue) + { + return null; + } + return _source.Shops.FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name) && x.ShopName == model.Name) || (model.Id.HasValue && x.Id == model.Id)) ?.GetViewModel; + } + public ShopViewModel? Insert(ShopBindingModel model) + { + model.Id = _source.Shops.Count > 0 ? _source.Shops.Max(x => x.Id) + 1 : 1; + var newShop = Shop.Create(model); + if (newShop == null) + { + return null; + } + _source.Shops.Add(newShop); + _source.SaveShops(); + return newShop.GetViewModel; + } + public ShopViewModel? Update(ShopBindingModel model) + { + var component = _source.Shops.FirstOrDefault(x => x.Id == model.Id); + if (component == null) + { + return null; + } + component.Update(model); + _source.SaveShops(); + return component.GetViewModel; + } + public ShopViewModel? Delete(ShopBindingModel model) + { + var element = _source.Shops.FirstOrDefault(x => x.Id == + model.Id); + if (element != null) + { + _source.Shops.Remove(element); + _source.SaveShops(); + return element.GetViewModel; + } + return null; + } + + private bool CheckAvailability(int ComputerId, int count) + { + count -= _source.Shops.Select(x => x.ShopComputers.Select(y => (y.Value.Item1.Id == ComputerId ? y.Value.Item2 : 0)).Sum()).Sum(); + return count <= 0; + } + + public bool SellComputers(IComputerModel model, int count) + { + var NeededComputer = _source.Computers.FirstOrDefault(x => x.Id == model.Id); + + if (NeededComputer == null || !CheckAvailability(NeededComputer.Id, count)) + { + return false; + } + + for (int i = 0; i < _source.Shops.Count; i++) + { + var shop = _source.Shops[i]; + var Computers = shop.ShopComputers; + + foreach (var computer in Computers.Where(x => x.Value.Item1.Id == NeededComputer.Id)) + { + var min = Math.Min(computer.Value.Item2, count); + Computers[computer.Value.Item1.Id] = (computer.Value.Item1, computer.Value.Item2 - min); + count -= min; + + if (count <= 0) + { + break; + } + } + + shop.Update(new ShopBindingModel + { + Id = shop.Id, + ShopName = shop.ShopName, + Address = shop.Address, + DateOpen = shop.DateOpen, + MaxCapacity = shop.MaxCapacity, + ShopComputers = Computers + }); + } + _source.SaveShops(); + return true; + } + } +} diff --git a/ComputersShop/ComputersShopFileImplement/Models/Shop.cs b/ComputersShop/ComputersShopFileImplement/Models/Shop.cs new file mode 100644 index 0000000..eea6973 --- /dev/null +++ b/ComputersShop/ComputersShopFileImplement/Models/Shop.cs @@ -0,0 +1,114 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; +using ComputersShopContracts.BindingModels; +using ComputersShopContracts.ViewModels; +using ComputersShopDataModels; + +namespace ComputersShopFileImplement.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 MaxCapacity { get; private set; } + public Dictionary Computers { get; private set; } = new(); + private Dictionary? _shopComputers = null; + public Dictionary 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, + DateOpen = model.DateOpen, + MaxCapacity = model.MaxCapacity, + 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), + ShopName = element.Element("ShopName")!.Value, + Address = element.Element("Address")!.Value, + MaxCapacity = Convert.ToInt32(element.Element("MaxCapacity")!.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; + DateOpen = model.DateOpen; + MaxCapacity = model.MaxCapacity; + 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, + DateOpen = DateOpen, + MaxCapacity = MaxCapacity, + ShopComputers = ShopComputers + }; + + public XElement GetXElement => new("Shop", + new XAttribute("Id", Id), + new XElement("ShopName", ShopName), + new XElement("Address", Address), + new XElement("DateOpen", DateOpen), + new XElement("MaxCapacity", MaxCapacity), + new XElement("ShopComputers", Computers + .Select(x => new XElement("ShopComputer", + new XElement("Key", x.Key), + new XElement("Value", x.Value)) + ).ToArray())); + + } +} diff --git a/ComputersShop/ComputersShopListImplement/DataListSingleton.cs b/ComputersShop/ComputersShopListImplement/DataListSingleton.cs index 1b0012b..a84abe3 100644 --- a/ComputersShop/ComputersShopListImplement/DataListSingleton.cs +++ b/ComputersShop/ComputersShopListImplement/DataListSingleton.cs @@ -8,11 +8,14 @@ namespace ComputersShopListImplement public List Components { get; set; } public List Orders { get; set; } public List Computers { get; set; } + public List Shops { get; set; } + private DataListSingleton() { Components = new List(); Orders = new List(); Computers = new List(); + Shops = new List(); } public static DataListSingleton GetInstance() { diff --git a/ComputersShop/ComputersShopListImplement/Implements/ShopStorage.cs b/ComputersShop/ComputersShopListImplement/Implements/ShopStorage.cs new file mode 100644 index 0000000..5e2c4df --- /dev/null +++ b/ComputersShop/ComputersShopListImplement/Implements/ShopStorage.cs @@ -0,0 +1,113 @@ +using ComputersShopContracts.BindingModels; +using ComputersShopContracts.SearchModels; +using ComputersShopContracts.StoragesContracts; +using ComputersShopContracts.ViewModels; +using ComputersShopDataModels; +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 GetFullList() + { + var result = new List(); + foreach (var shop in _source.Shops) + { + result.Add(shop.GetViewModel); + } + return result; + } + public List GetFilteredList(ShopSearchModel model) + { + var result = new List(); + 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 SellComputers(IComputerModel model, int count) + { + throw new NotImplementedException(); + } + } +} diff --git a/ComputersShop/ComputersShopListImplement/Models/Shop.cs b/ComputersShop/ComputersShopListImplement/Models/Shop.cs new file mode 100644 index 0000000..7aa5029 --- /dev/null +++ b/ComputersShop/ComputersShopListImplement/Models/Shop.cs @@ -0,0 +1,57 @@ +using ComputersShopContracts.BindingModels; +using ComputersShopContracts.ViewModels; +using ComputersShopDataModels; +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 Dictionary 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, + ShopComputers = new() + }; + } + + public void Update(ShopBindingModel? model) + { + if (model == null) + { + return; + } + ShopName = model.ShopName; + Address = model.Address; + DateOpen = model.DateOpen; + ShopComputers = model.ShopComputers; + } + + public ShopViewModel GetViewModel => new() + { + Id = Id, + ShopName = ShopName, + Address = Address, + DateOpen = DateOpen, + ShopComputers = ShopComputers + }; + + public int MaxCapacity => throw new NotImplementedException(); + } +}