From c890e8f5455ff0d8400421bd8abc6e7019d49812 Mon Sep 17 00:00:00 2001 From: Artyom_Yashin Date: Thu, 14 Mar 2024 19:27:45 +0400 Subject: [PATCH 1/5] =?UTF-8?q?=D0=A1=D0=B4=D0=B5=D0=BB=D0=B0=D0=BD=D0=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ComputersShop/FormMain.Designer.cs | 33 ++- ComputersShop/ComputersShop/FormMain.cs | 27 +++ .../ComputersShop/FormSell.Designer.cs | 125 ++++++++++ ComputersShop/ComputersShop/FormSell.cs | 121 ++++++++++ ComputersShop/ComputersShop/FormSell.resx | 120 +++++++++ .../ComputersShop/FormShop.Designer.cs | 227 ++++++++++++++++++ ComputersShop/ComputersShop/FormShop.cs | 124 ++++++++++ ComputersShop/ComputersShop/FormShop.resx | 123 ++++++++++ .../ComputersShop/FormShops.Designer.cs | 119 +++++++++ ComputersShop/ComputersShop/FormShops.cs | 118 +++++++++ ComputersShop/ComputersShop/FormShops.resx | 120 +++++++++ .../ComputersShop/FormSupply.Designer.cs | 149 ++++++++++++ ComputersShop/ComputersShop/FormSupply.cs | 151 ++++++++++++ ComputersShop/ComputersShop/FormSupply.resx | 120 +++++++++ ComputersShop/ComputersShop/Program.cs | 6 + .../BusinessLogics/OrderLogic.cs | 84 ++++++- .../BusinessLogics/ShopLogic.cs | 176 ++++++++++++++ .../BindingModels/ShopBindingModel.cs | 19 ++ .../BisnessLogicsContracts/IShopLogic.cs | 24 ++ .../SearchModels/ShopSearchModel.cs | 14 ++ .../StoragesContracts/IShopStorage.cs | 24 ++ .../ViewModels/ShopViewModel.cs | 24 ++ .../ComputersShopDataModels/IShopModel.cs | 17 ++ .../DataFileSingleton.cs | 6 + .../Implements/ShopStorage.cs | 124 ++++++++++ .../ComputersShopFileImplement/Models/Shop.cs | 114 +++++++++ .../DataListSingleton.cs | 3 + .../Implements/ShopStorage.cs | 113 +++++++++ .../ComputersShopListImplement/Models/Shop.cs | 57 +++++ 29 files changed, 2477 insertions(+), 5 deletions(-) create mode 100644 ComputersShop/ComputersShop/FormSell.Designer.cs create mode 100644 ComputersShop/ComputersShop/FormSell.cs create mode 100644 ComputersShop/ComputersShop/FormSell.resx create mode 100644 ComputersShop/ComputersShop/FormShop.Designer.cs create mode 100644 ComputersShop/ComputersShop/FormShop.cs create mode 100644 ComputersShop/ComputersShop/FormShop.resx create mode 100644 ComputersShop/ComputersShop/FormShops.Designer.cs create mode 100644 ComputersShop/ComputersShop/FormShops.cs create mode 100644 ComputersShop/ComputersShop/FormShops.resx create mode 100644 ComputersShop/ComputersShop/FormSupply.Designer.cs create mode 100644 ComputersShop/ComputersShop/FormSupply.cs create mode 100644 ComputersShop/ComputersShop/FormSupply.resx create mode 100644 ComputersShop/ComputersShopBusinessLogic/BusinessLogics/ShopLogic.cs create mode 100644 ComputersShop/ComputersShopContracts/BindingModels/ShopBindingModel.cs create mode 100644 ComputersShop/ComputersShopContracts/BisnessLogicsContracts/IShopLogic.cs create mode 100644 ComputersShop/ComputersShopContracts/SearchModels/ShopSearchModel.cs create mode 100644 ComputersShop/ComputersShopContracts/StoragesContracts/IShopStorage.cs create mode 100644 ComputersShop/ComputersShopContracts/ViewModels/ShopViewModel.cs create mode 100644 ComputersShop/ComputersShopDataModels/IShopModel.cs create mode 100644 ComputersShop/ComputersShopFileImplement/Implements/ShopStorage.cs create mode 100644 ComputersShop/ComputersShopFileImplement/Models/Shop.cs create mode 100644 ComputersShop/ComputersShopListImplement/Implements/ShopStorage.cs create mode 100644 ComputersShop/ComputersShopListImplement/Models/Shop.cs 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(); + } +} From 1ceed0d4e0ba374bc149ec79260142fe8760cc6d Mon Sep 17 00:00:00 2001 From: Artyom_Yashin Date: Mon, 25 Mar 2024 22:20:28 +0400 Subject: [PATCH 2/5] =?UTF-8?q?=D0=92=D1=80=D0=BE=D0=B4=D0=B5=20=D1=81?= =?UTF-8?q?=D0=B4=D0=B5=D0=BB=D0=B0=D0=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ComputersShopDatabase.cs | 4 +- .../Implements/ShopStorage.cs | 153 ++++++++++++++++++ ... 20240325181021_InitialCreate.Designer.cs} | 85 +++++++++- ...ate.cs => 20240325181021_InitialCreate.cs} | 59 +++++++ .../ComputersShopDatabaseModelSnapshot.cs | 83 +++++++++- .../Models/Computer.cs | 2 + .../Models/Shop.cs | 118 ++++++++++++++ .../Models/ShopComputer.cs | 22 +++ 8 files changed, 522 insertions(+), 4 deletions(-) create mode 100644 ComputersShop/ComputersShopDatabaseImplement/Implements/ShopStorage.cs rename ComputersShop/ComputersShopDatabaseImplement/Migrations/{20240325171651_InitialCreate.Designer.cs => 20240325181021_InitialCreate.Designer.cs} (66%) rename ComputersShop/ComputersShopDatabaseImplement/Migrations/{20240325171651_InitialCreate.cs => 20240325181021_InitialCreate.cs} (66%) create mode 100644 ComputersShop/ComputersShopDatabaseImplement/Models/Shop.cs create mode 100644 ComputersShop/ComputersShopDatabaseImplement/Models/ShopComputer.cs diff --git a/ComputersShop/ComputersShopDatabaseImplement/ComputersShopDatabase.cs b/ComputersShop/ComputersShopDatabaseImplement/ComputersShopDatabase.cs index f40121d..2fa9b47 100644 --- a/ComputersShop/ComputersShopDatabaseImplement/ComputersShopDatabase.cs +++ b/ComputersShop/ComputersShopDatabaseImplement/ComputersShopDatabase.cs @@ -9,7 +9,7 @@ namespace ComputersShopDatabaseImplement { if (optionsBuilder.IsConfigured == false) { - optionsBuilder.UseSqlServer(@"Data Source=localhost\SQLEXPRESS;Initial Catalog=ComputersShopDataBase;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True" + optionsBuilder.UseSqlServer(@"Data Source=localhost\SQLEXPRESS;Initial Catalog=ComputersShopDataBaseHard;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True" ); } base.OnConfiguring(optionsBuilder); @@ -18,5 +18,7 @@ namespace ComputersShopDatabaseImplement public virtual DbSet Computers { set; get; } public virtual DbSet ComputerComponents { set; get; } public virtual DbSet Orders { set; get; } + public virtual DbSet Shops { set; get; } + public virtual DbSet ShopComputers { set; get; } } } \ No newline at end of file diff --git a/ComputersShop/ComputersShopDatabaseImplement/Implements/ShopStorage.cs b/ComputersShop/ComputersShopDatabaseImplement/Implements/ShopStorage.cs new file mode 100644 index 0000000..467667a --- /dev/null +++ b/ComputersShop/ComputersShopDatabaseImplement/Implements/ShopStorage.cs @@ -0,0 +1,153 @@ +using ComputersShopContracts.BindingModels; +using ComputersShopContracts.SearchModels; +using ComputersShopContracts.StoragesContracts; +using ComputersShopContracts.ViewModels; +using ComputersShopDatabaseImplement.Models; +using ComputersShopDataModels; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopDatabaseImplement.Implements +{ + public class ShopStorage : IShopStorage + { + public ShopViewModel? Delete(ShopBindingModel model) + { + using var context = new ComputersShopDatabase(); + var element = context.Shops.FirstOrDefault(x => x.Id == model.Id); + if (element != null) + { + context.Shops.Remove(element); + context.SaveChanges(); + return element.GetViewModel; + } + return null; + } + + public ShopViewModel? GetElement(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.Name) && !model.Id.HasValue) + { + return null; + } + using var context = new ComputersShopDatabase(); + return context.Shops + .Include(x => x.Computers) + .ThenInclude(x => x.Computer) + .FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id) + ?.GetViewModel; + } + + public List GetFilteredList(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.Name)) + { + return new(); + } + using var context = new ComputersShopDatabase(); + return context.Shops + .Include(x => x.Computers) + .ThenInclude(x => x.Computer) + .Select(x => x.GetViewModel) + .Where(x => x.ShopName.Contains(model.Name ?? string.Empty)) + .ToList(); + } + + public List GetFullList() + { + using var context = new ComputersShopDatabase(); + return context.Shops + .Include(x => x.Computers) + .ThenInclude(x => x.Computer) + .Select(x => x.GetViewModel) + .ToList(); + } + + public ShopViewModel? Insert(ShopBindingModel model) + { + using var context = new ComputersShopDatabase(); + try + { + var newShop = Shop.Create(context, model); + if (newShop == null) + { + return null; + } + if (context.Shops.Any(x => x.ShopName == newShop.ShopName)) + { + throw new Exception("Не должно быть два магазина с одним названием"); + } + context.Shops.Add(newShop); + context.SaveChanges(); + return newShop.GetViewModel; + } + catch + { + throw; + } + } + + public ShopViewModel? Update(ShopBindingModel model) + { + using var context = new ComputersShopDatabase(); + var shop = context.Shops.FirstOrDefault(x => x.Id == model.Id); + if (shop == null) + { + return null; + } + try + { + if (context.Shops.Any(x => (x.ShopName == model.ShopName && x.Id != model.Id))) + { + throw new Exception("Не должно быть два магазина с одним названием"); + } + shop.Update(model); + shop.UpdateComputers(context, model); + context.SaveChanges(); + return shop.GetViewModel; + } + catch + { + throw; + } + } + public bool SellComputers(IComputerModel model, int count) + { + if (model == null) + return false; + using var context = new ComputersShopDatabase(); + using var transaction = context.Database.BeginTransaction(); + List lst = new List(); + foreach (var el in context.ShopComputers.Where(x => x.ComputerId == model.Id)) + { + int dif = count; + if (el.Count < dif) + dif = el.Count; + el.Count -= dif; + count -= dif; + if (el.Count == 0) + { + lst.Add(el); + } + if (count == 0) + break; + } + if (count > 0) + { + transaction.Rollback(); + return false; + } + foreach (var el in lst) + { + context.ShopComputers.Remove(el); + } + context.SaveChanges(); + transaction.Commit(); + return true; + } + } +} diff --git a/ComputersShop/ComputersShopDatabaseImplement/Migrations/20240325171651_InitialCreate.Designer.cs b/ComputersShop/ComputersShopDatabaseImplement/Migrations/20240325181021_InitialCreate.Designer.cs similarity index 66% rename from ComputersShop/ComputersShopDatabaseImplement/Migrations/20240325171651_InitialCreate.Designer.cs rename to ComputersShop/ComputersShopDatabaseImplement/Migrations/20240325181021_InitialCreate.Designer.cs index 4f48431..b99af49 100644 --- a/ComputersShop/ComputersShopDatabaseImplement/Migrations/20240325171651_InitialCreate.Designer.cs +++ b/ComputersShop/ComputersShopDatabaseImplement/Migrations/20240325181021_InitialCreate.Designer.cs @@ -12,7 +12,7 @@ using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace ComputersShopDatabaseImplement.Migrations { [DbContext(typeof(ComputersShopDatabase))] - [Migration("20240325171651_InitialCreate")] + [Migration("20240325181021_InitialCreate")] partial class InitialCreate { /// @@ -124,6 +124,59 @@ namespace ComputersShopDatabaseImplement.Migrations b.ToTable("Orders"); }); + modelBuilder.Entity("ComputersShopDatabaseImplement.Models.Shop", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Address") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("DateOpen") + .HasColumnType("datetime2"); + + b.Property("MaxCapacity") + .HasColumnType("int"); + + b.Property("ShopName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Shops"); + }); + + modelBuilder.Entity("ComputersShopDatabaseImplement.Models.ShopComputer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ComputerId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("ShopId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ComputerId"); + + b.HasIndex("ShopId"); + + b.ToTable("ShopComputers"); + }); + modelBuilder.Entity("ComputersShopDatabaseImplement.Models.ComputerComponent", b => { b.HasOne("ComputersShopDatabaseImplement.Models.Component", "Component") @@ -145,11 +198,32 @@ namespace ComputersShopDatabaseImplement.Migrations modelBuilder.Entity("ComputersShopDatabaseImplement.Models.Order", b => { - b.HasOne("ComputersShopDatabaseImplement.Models.Computer", null) + b.HasOne("ComputersShopDatabaseImplement.Models.Computer", "Computers") .WithMany("Orders") .HasForeignKey("ComputerId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); + + b.Navigation("Computers"); + }); + + modelBuilder.Entity("ComputersShopDatabaseImplement.Models.ShopComputer", b => + { + b.HasOne("ComputersShopDatabaseImplement.Models.Computer", "Computer") + .WithMany("ShopComputers") + .HasForeignKey("ComputerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("ComputersShopDatabaseImplement.Models.Shop", "Shop") + .WithMany("Computers") + .HasForeignKey("ShopId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Computer"); + + b.Navigation("Shop"); }); modelBuilder.Entity("ComputersShopDatabaseImplement.Models.Component", b => @@ -162,6 +236,13 @@ namespace ComputersShopDatabaseImplement.Migrations b.Navigation("Components"); b.Navigation("Orders"); + + b.Navigation("ShopComputers"); + }); + + modelBuilder.Entity("ComputersShopDatabaseImplement.Models.Shop", b => + { + b.Navigation("Computers"); }); #pragma warning restore 612, 618 } diff --git a/ComputersShop/ComputersShopDatabaseImplement/Migrations/20240325171651_InitialCreate.cs b/ComputersShop/ComputersShopDatabaseImplement/Migrations/20240325181021_InitialCreate.cs similarity index 66% rename from ComputersShop/ComputersShopDatabaseImplement/Migrations/20240325171651_InitialCreate.cs rename to ComputersShop/ComputersShopDatabaseImplement/Migrations/20240325181021_InitialCreate.cs index 6ef9716..4799465 100644 --- a/ComputersShop/ComputersShopDatabaseImplement/Migrations/20240325171651_InitialCreate.cs +++ b/ComputersShop/ComputersShopDatabaseImplement/Migrations/20240325181021_InitialCreate.cs @@ -39,6 +39,22 @@ namespace ComputersShopDatabaseImplement.Migrations table.PrimaryKey("PK_Computers", x => x.Id); }); + migrationBuilder.CreateTable( + name: "Shops", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + ShopName = table.Column(type: "nvarchar(max)", nullable: false), + Address = table.Column(type: "nvarchar(max)", nullable: false), + DateOpen = table.Column(type: "datetime2", nullable: false), + MaxCapacity = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Shops", x => x.Id); + }); + migrationBuilder.CreateTable( name: "ComputerComponents", columns: table => new @@ -90,6 +106,33 @@ namespace ComputersShopDatabaseImplement.Migrations onDelete: ReferentialAction.Cascade); }); + migrationBuilder.CreateTable( + name: "ShopComputers", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + ComputerId = table.Column(type: "int", nullable: false), + ShopId = table.Column(type: "int", nullable: false), + Count = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ShopComputers", x => x.Id); + table.ForeignKey( + name: "FK_ShopComputers_Computers_ComputerId", + column: x => x.ComputerId, + principalTable: "Computers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_ShopComputers_Shops_ShopId", + column: x => x.ShopId, + principalTable: "Shops", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + migrationBuilder.CreateIndex( name: "IX_ComputerComponents_ComponentId", table: "ComputerComponents", @@ -104,6 +147,16 @@ namespace ComputersShopDatabaseImplement.Migrations name: "IX_Orders_ComputerId", table: "Orders", column: "ComputerId"); + + migrationBuilder.CreateIndex( + name: "IX_ShopComputers_ComputerId", + table: "ShopComputers", + column: "ComputerId"); + + migrationBuilder.CreateIndex( + name: "IX_ShopComputers_ShopId", + table: "ShopComputers", + column: "ShopId"); } /// @@ -115,11 +168,17 @@ namespace ComputersShopDatabaseImplement.Migrations migrationBuilder.DropTable( name: "Orders"); + migrationBuilder.DropTable( + name: "ShopComputers"); + migrationBuilder.DropTable( name: "Components"); migrationBuilder.DropTable( name: "Computers"); + + migrationBuilder.DropTable( + name: "Shops"); } } } diff --git a/ComputersShop/ComputersShopDatabaseImplement/Migrations/ComputersShopDatabaseModelSnapshot.cs b/ComputersShop/ComputersShopDatabaseImplement/Migrations/ComputersShopDatabaseModelSnapshot.cs index 8b53269..f9b3016 100644 --- a/ComputersShop/ComputersShopDatabaseImplement/Migrations/ComputersShopDatabaseModelSnapshot.cs +++ b/ComputersShop/ComputersShopDatabaseImplement/Migrations/ComputersShopDatabaseModelSnapshot.cs @@ -121,6 +121,59 @@ namespace ComputersShopDatabaseImplement.Migrations b.ToTable("Orders"); }); + modelBuilder.Entity("ComputersShopDatabaseImplement.Models.Shop", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Address") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("DateOpen") + .HasColumnType("datetime2"); + + b.Property("MaxCapacity") + .HasColumnType("int"); + + b.Property("ShopName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Shops"); + }); + + modelBuilder.Entity("ComputersShopDatabaseImplement.Models.ShopComputer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ComputerId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("ShopId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ComputerId"); + + b.HasIndex("ShopId"); + + b.ToTable("ShopComputers"); + }); + modelBuilder.Entity("ComputersShopDatabaseImplement.Models.ComputerComponent", b => { b.HasOne("ComputersShopDatabaseImplement.Models.Component", "Component") @@ -142,11 +195,32 @@ namespace ComputersShopDatabaseImplement.Migrations modelBuilder.Entity("ComputersShopDatabaseImplement.Models.Order", b => { - b.HasOne("ComputersShopDatabaseImplement.Models.Computer", null) + b.HasOne("ComputersShopDatabaseImplement.Models.Computer", "Computers") .WithMany("Orders") .HasForeignKey("ComputerId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); + + b.Navigation("Computers"); + }); + + modelBuilder.Entity("ComputersShopDatabaseImplement.Models.ShopComputer", b => + { + b.HasOne("ComputersShopDatabaseImplement.Models.Computer", "Computer") + .WithMany("ShopComputers") + .HasForeignKey("ComputerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("ComputersShopDatabaseImplement.Models.Shop", "Shop") + .WithMany("Computers") + .HasForeignKey("ShopId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Computer"); + + b.Navigation("Shop"); }); modelBuilder.Entity("ComputersShopDatabaseImplement.Models.Component", b => @@ -159,6 +233,13 @@ namespace ComputersShopDatabaseImplement.Migrations b.Navigation("Components"); b.Navigation("Orders"); + + b.Navigation("ShopComputers"); + }); + + modelBuilder.Entity("ComputersShopDatabaseImplement.Models.Shop", b => + { + b.Navigation("Computers"); }); #pragma warning restore 612, 618 } diff --git a/ComputersShop/ComputersShopDatabaseImplement/Models/Computer.cs b/ComputersShop/ComputersShopDatabaseImplement/Models/Computer.cs index 3862d87..c7a874d 100644 --- a/ComputersShop/ComputersShopDatabaseImplement/Models/Computer.cs +++ b/ComputersShop/ComputersShopDatabaseImplement/Models/Computer.cs @@ -37,6 +37,8 @@ namespace ComputersShopDatabaseImplement.Models public virtual List Components { get; set; } = new(); [ForeignKey("ComputerId")] public virtual List Orders { get; set; } = new(); + [ForeignKey("ComputerId")] + public virtual List ShopComputers { get; set; } = new(); public static Computer Create(ComputersShopDatabase context, ComputerBindingModel model) { return new Computer() diff --git a/ComputersShop/ComputersShopDatabaseImplement/Models/Shop.cs b/ComputersShop/ComputersShopDatabaseImplement/Models/Shop.cs new file mode 100644 index 0000000..10b6b5c --- /dev/null +++ b/ComputersShop/ComputersShopDatabaseImplement/Models/Shop.cs @@ -0,0 +1,118 @@ +using ComputersShopContracts.BindingModels; +using ComputersShopContracts.ViewModels; +using ComputersShopDataModels; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations.Schema; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopDatabaseImplement.Models +{ + public class Shop : IShopModel + { + public int Id { get; private set; } + [Required] + public string ShopName { get; private set; } = string.Empty; + [Required] + public string Address { get; private set; } = string.Empty; + [Required] + public DateTime DateOpen { get; private set; } + [Required] + public int MaxCapacity { get; private set; } + private Dictionary? _shopComputers = + null; + [NotMapped] + public Dictionary ShopComputers + { + get + { + if (_shopComputers == null) + { + _shopComputers = Computers + .ToDictionary(x => x.ComputerId, x => + (x.Computer as IComputerModel, x.Count)); + } + return _shopComputers; + } + } + [ForeignKey("ShopId")] + public virtual List Computers { get; set; } = new(); + public static Shop? Create(ComputersShopDatabase context, 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.Select(x => new + ShopComputer + { + Computer = context.Computers.First(y => y.Id == x.Key), + Count = x.Value.Item2 + }).ToList() + }; + } + + public void Update(ShopBindingModel? model) + { + if (model == null) + { + return; + } + ShopName = model.ShopName; + Address = model.Address; + DateOpen = model.DateOpen; + MaxCapacity = model.MaxCapacity; + } + + public ShopViewModel GetViewModel => new() + { + Id = Id, + ShopName = ShopName, + Address = Address, + DateOpen = DateOpen, + ShopComputers = ShopComputers, + MaxCapacity = MaxCapacity + }; + + public void UpdateComputers(ComputersShopDatabase context, + ShopBindingModel model) + { + var shopComputers = context.ShopComputers.Where(rec => + rec.ShopId == model.Id).ToList(); + if (shopComputers != null && shopComputers.Count > 0) + { + context.ShopComputers.RemoveRange(shopComputers.Where(rec +=> !model.ShopComputers.ContainsKey(rec.ShopId))); + + context.SaveChanges(); + foreach (var updateComputer in shopComputers) + { + updateComputer.Count = + model.ShopComputers[updateComputer.ComputerId].Item2; + model.ShopComputers.Remove(updateComputer.ComputerId); + } + context.SaveChanges(); + } + var shop = context.Shops.First(x => x.Id == Id); + foreach (var pc in model.ShopComputers) + { + context.ShopComputers.Add(new ShopComputer + { + Shop = shop, + Computer = context.Computers.First(x => x.Id == pc.Key), + Count = pc.Value.Item2 + }); + context.SaveChanges(); + } + _shopComputers = null; + } + } +} diff --git a/ComputersShop/ComputersShopDatabaseImplement/Models/ShopComputer.cs b/ComputersShop/ComputersShopDatabaseImplement/Models/ShopComputer.cs new file mode 100644 index 0000000..3c476cc --- /dev/null +++ b/ComputersShop/ComputersShopDatabaseImplement/Models/ShopComputer.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopDatabaseImplement.Models +{ + public class ShopComputer + { + public int Id { get; set; } + [Required] + public int ComputerId { get; set; } + [Required] + public int ShopId { get; set; } + [Required] + public int Count { get; set; } + public virtual Shop Shop { get; set; } = new(); + public virtual Computer Computer { get; set; } = new(); + } +} From e312857476cdebbd1d5ca6ee4c32001d878a4a3b Mon Sep 17 00:00:00 2001 From: Artyom_Yashin Date: Fri, 5 Apr 2024 19:24:47 +0400 Subject: [PATCH 3/5] =?UTF-8?q?=D0=9D=D0=B0=D1=87=D0=B0=D0=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../20240326160834_InitialCreate.cs | 184 ------------------ .../ComputersShopDatabaseModelSnapshot.cs | 168 ---------------- 2 files changed, 352 deletions(-) delete mode 100644 ComputersShop/ComputersShopDatabaseImplement/Migrations/20240326160834_InitialCreate.cs delete mode 100644 ComputersShop/ComputersShopDatabaseImplement/Migrations/ComputersShopDatabaseModelSnapshot.cs diff --git a/ComputersShop/ComputersShopDatabaseImplement/Migrations/20240326160834_InitialCreate.cs b/ComputersShop/ComputersShopDatabaseImplement/Migrations/20240326160834_InitialCreate.cs deleted file mode 100644 index 4799465..0000000 --- a/ComputersShop/ComputersShopDatabaseImplement/Migrations/20240326160834_InitialCreate.cs +++ /dev/null @@ -1,184 +0,0 @@ -using System; -using Microsoft.EntityFrameworkCore.Migrations; - -#nullable disable - -namespace ComputersShopDatabaseImplement.Migrations -{ - /// - public partial class InitialCreate : Migration - { - /// - protected override void Up(MigrationBuilder migrationBuilder) - { - migrationBuilder.CreateTable( - name: "Components", - columns: table => new - { - Id = table.Column(type: "int", nullable: false) - .Annotation("SqlServer:Identity", "1, 1"), - ComponentName = table.Column(type: "nvarchar(max)", nullable: false), - Cost = table.Column(type: "float", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Components", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "Computers", - columns: table => new - { - Id = table.Column(type: "int", nullable: false) - .Annotation("SqlServer:Identity", "1, 1"), - ComputerName = table.Column(type: "nvarchar(max)", nullable: false), - Price = table.Column(type: "float", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Computers", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "Shops", - columns: table => new - { - Id = table.Column(type: "int", nullable: false) - .Annotation("SqlServer:Identity", "1, 1"), - ShopName = table.Column(type: "nvarchar(max)", nullable: false), - Address = table.Column(type: "nvarchar(max)", nullable: false), - DateOpen = table.Column(type: "datetime2", nullable: false), - MaxCapacity = table.Column(type: "int", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Shops", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "ComputerComponents", - columns: table => new - { - Id = table.Column(type: "int", nullable: false) - .Annotation("SqlServer:Identity", "1, 1"), - ComputerId = table.Column(type: "int", nullable: false), - ComponentId = table.Column(type: "int", nullable: false), - Count = table.Column(type: "int", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_ComputerComponents", x => x.Id); - table.ForeignKey( - name: "FK_ComputerComponents_Components_ComponentId", - column: x => x.ComponentId, - principalTable: "Components", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - table.ForeignKey( - name: "FK_ComputerComponents_Computers_ComputerId", - column: x => x.ComputerId, - principalTable: "Computers", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "Orders", - columns: table => new - { - Id = table.Column(type: "int", nullable: false) - .Annotation("SqlServer:Identity", "1, 1"), - Count = table.Column(type: "int", nullable: false), - Sum = table.Column(type: "float", nullable: false), - Status = table.Column(type: "int", nullable: false), - DateCreate = table.Column(type: "datetime2", nullable: false), - DateImplement = table.Column(type: "datetime2", nullable: true), - ComputerId = table.Column(type: "int", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Orders", x => x.Id); - table.ForeignKey( - name: "FK_Orders_Computers_ComputerId", - column: x => x.ComputerId, - principalTable: "Computers", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "ShopComputers", - columns: table => new - { - Id = table.Column(type: "int", nullable: false) - .Annotation("SqlServer:Identity", "1, 1"), - ComputerId = table.Column(type: "int", nullable: false), - ShopId = table.Column(type: "int", nullable: false), - Count = table.Column(type: "int", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_ShopComputers", x => x.Id); - table.ForeignKey( - name: "FK_ShopComputers_Computers_ComputerId", - column: x => x.ComputerId, - principalTable: "Computers", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - table.ForeignKey( - name: "FK_ShopComputers_Shops_ShopId", - column: x => x.ShopId, - principalTable: "Shops", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateIndex( - name: "IX_ComputerComponents_ComponentId", - table: "ComputerComponents", - column: "ComponentId"); - - migrationBuilder.CreateIndex( - name: "IX_ComputerComponents_ComputerId", - table: "ComputerComponents", - column: "ComputerId"); - - migrationBuilder.CreateIndex( - name: "IX_Orders_ComputerId", - table: "Orders", - column: "ComputerId"); - - migrationBuilder.CreateIndex( - name: "IX_ShopComputers_ComputerId", - table: "ShopComputers", - column: "ComputerId"); - - migrationBuilder.CreateIndex( - name: "IX_ShopComputers_ShopId", - table: "ShopComputers", - column: "ShopId"); - } - - /// - protected override void Down(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropTable( - name: "ComputerComponents"); - - migrationBuilder.DropTable( - name: "Orders"); - - migrationBuilder.DropTable( - name: "ShopComputers"); - - migrationBuilder.DropTable( - name: "Components"); - - migrationBuilder.DropTable( - name: "Computers"); - - migrationBuilder.DropTable( - name: "Shops"); - } - } -} diff --git a/ComputersShop/ComputersShopDatabaseImplement/Migrations/ComputersShopDatabaseModelSnapshot.cs b/ComputersShop/ComputersShopDatabaseImplement/Migrations/ComputersShopDatabaseModelSnapshot.cs deleted file mode 100644 index 3b34a31..0000000 --- a/ComputersShop/ComputersShopDatabaseImplement/Migrations/ComputersShopDatabaseModelSnapshot.cs +++ /dev/null @@ -1,168 +0,0 @@ -// -using System; -using ComputersShopDatabaseImplement; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Metadata; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; - -#nullable disable - -namespace ComputersShopDatabaseImplement.Migrations -{ - [DbContext(typeof(ComputersShopDatabase))] - partial class ComputersShopDatabaseModelSnapshot : ModelSnapshot - { - protected override void BuildModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder - .HasAnnotation("ProductVersion", "7.0.16") - .HasAnnotation("Relational:MaxIdentifierLength", 128); - - SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); - - modelBuilder.Entity("ComputersShopDatabaseImplement.Models.Component", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("int"); - - SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); - - b.Property("ComponentName") - .IsRequired() - .HasColumnType("nvarchar(max)"); - - b.Property("Cost") - .HasColumnType("float"); - - b.HasKey("Id"); - - b.ToTable("Components"); - }); - - modelBuilder.Entity("ComputersShopDatabaseImplement.Models.Computer", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("int"); - - SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); - - b.Property("ComputerName") - .IsRequired() - .HasColumnType("nvarchar(max)"); - - b.Property("Price") - .HasColumnType("float"); - - b.HasKey("Id"); - - b.ToTable("Computers"); - }); - - modelBuilder.Entity("ComputersShopDatabaseImplement.Models.ComputerComponent", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("int"); - - SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); - - b.Property("ComponentId") - .HasColumnType("int"); - - b.Property("ComputerId") - .HasColumnType("int"); - - b.Property("Count") - .HasColumnType("int"); - - b.HasKey("Id"); - - b.HasIndex("ComponentId"); - - b.HasIndex("ComputerId"); - - b.ToTable("ComputerComponents"); - }); - - modelBuilder.Entity("ComputersShopDatabaseImplement.Models.Order", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("int"); - - SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); - - b.Property("ComputerId") - .HasColumnType("int"); - - b.Property("Count") - .HasColumnType("int"); - - b.Property("DateCreate") - .HasColumnType("datetime2"); - - b.Property("DateImplement") - .HasColumnType("datetime2"); - - b.Property("Status") - .HasColumnType("int"); - - b.Property("Sum") - .HasColumnType("float"); - - b.HasKey("Id"); - - b.HasIndex("ComputerId"); - - b.ToTable("Orders"); - }); - - modelBuilder.Entity("ComputersShopDatabaseImplement.Models.ComputerComponent", b => - { - b.HasOne("ComputersShopDatabaseImplement.Models.Component", "Component") - .WithMany("ComputerComponents") - .HasForeignKey("ComponentId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("ComputersShopDatabaseImplement.Models.Computer", "Computer") - .WithMany("Components") - .HasForeignKey("ComputerId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Component"); - - b.Navigation("Computer"); - }); - - modelBuilder.Entity("ComputersShopDatabaseImplement.Models.Order", b => - { - b.HasOne("ComputersShopDatabaseImplement.Models.Computer", "Computers") - .WithMany("Orders") - .HasForeignKey("ComputerId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Computers"); - }); - - modelBuilder.Entity("ComputersShopDatabaseImplement.Models.Component", b => - { - b.Navigation("ComputerComponents"); - }); - - modelBuilder.Entity("ComputersShopDatabaseImplement.Models.Computer", b => - { - b.Navigation("Components"); - - b.Navigation("Orders"); - }); -#pragma warning restore 612, 618 - } - } -} From 8d4745944ed15cff2df398a5dfb27f284581d647 Mon Sep 17 00:00:00 2001 From: Artyom_Yashin Date: Sat, 6 Apr 2024 16:35:18 +0400 Subject: [PATCH 4/5] =?UTF-8?q?=D0=92=D1=80=D0=BE=D0=B4=D0=B5=20=D1=81?= =?UTF-8?q?=D0=B4=D0=B5=D0=BB=D0=B0=D0=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ComputersShop/FormMain.Designer.cs | 65 ++- ComputersShop/ComputersShop/FormMain.cs | 32 ++ .../FormReportDateOrders.Designer.cs | 82 ++++ .../ComputersShop/FormReportDateOrders.cs | 77 ++++ .../ComputersShop/FormReportDateOrders.resx | 120 ++++++ .../FormReportShopsComputers.Designer.cs | 103 +++++ .../ComputersShop/FormReportShopsComputers.cs | 88 ++++ .../FormReportShopsComputers.resx | 120 ++++++ ComputersShop/ComputersShop/Program.cs | 2 + .../ComputersShop/ReportOrdersByDate.rdlc | 400 ++++++++++++++++++ .../BusinessLogics/ReportLogic.cs | 68 ++- .../OfficePackage/AbstractSaveToExcel.cs | 65 +++ .../OfficePackage/AbstractSaveToPdf.cs | 34 ++ .../OfficePackage/AbstractSaveToWord.cs | 30 ++ .../OfficePackage/HelperModels/ExcelInfo.cs | 6 +- .../OfficePackage/HelperModels/PdfInfo.cs | 1 + .../OfficePackage/HelperModels/WordInfo.cs | 1 + .../OfficePackage/HelperModels/WordTable.cs | 15 + .../OfficePackage/Implements/SaveToWord.cs | 91 +++- .../BisnessLogicsContracts/IReportLogic.cs | 13 + .../ViewModels/ReportDateOrdersViewModel.cs | 15 + .../ViewModels/ReportShopComputerViewModel.cs | 15 + .../20240405152618_InitialCreate.Designer.cs | 250 +++++++++++ .../20240405152618_InitialCreate.cs | 184 ++++++++ .../ComputersShopDatabaseModelSnapshot.cs | 247 +++++++++++ 25 files changed, 2095 insertions(+), 29 deletions(-) create mode 100644 ComputersShop/ComputersShop/FormReportDateOrders.Designer.cs create mode 100644 ComputersShop/ComputersShop/FormReportDateOrders.cs create mode 100644 ComputersShop/ComputersShop/FormReportDateOrders.resx create mode 100644 ComputersShop/ComputersShop/FormReportShopsComputers.Designer.cs create mode 100644 ComputersShop/ComputersShop/FormReportShopsComputers.cs create mode 100644 ComputersShop/ComputersShop/FormReportShopsComputers.resx create mode 100644 ComputersShop/ComputersShop/ReportOrdersByDate.rdlc create mode 100644 ComputersShop/ComputersShopBusinessLogic/OfficePackage/HelperModels/WordTable.cs create mode 100644 ComputersShop/ComputersShopContracts/ViewModels/ReportDateOrdersViewModel.cs create mode 100644 ComputersShop/ComputersShopContracts/ViewModels/ReportShopComputerViewModel.cs create mode 100644 ComputersShop/ComputersShopDatabaseImplement/Migrations/20240405152618_InitialCreate.Designer.cs create mode 100644 ComputersShop/ComputersShopDatabaseImplement/Migrations/20240405152618_InitialCreate.cs create mode 100644 ComputersShop/ComputersShopDatabaseImplement/Migrations/ComputersShopDatabaseModelSnapshot.cs diff --git a/ComputersShop/ComputersShop/FormMain.Designer.cs b/ComputersShop/ComputersShop/FormMain.Designer.cs index 71861a1..9a35958 100644 --- a/ComputersShop/ComputersShop/FormMain.Designer.cs +++ b/ComputersShop/ComputersShop/FormMain.Designer.cs @@ -34,17 +34,20 @@ компьютерыToolStripMenuItem = new ToolStripMenuItem(); магазиныToolStripMenuItem = new ToolStripMenuItem(); поставкиToolStripMenuItem = new ToolStripMenuItem(); + SellsToolStripMenuItem = new ToolStripMenuItem(); отчетыToolStripMenuItem = new ToolStripMenuItem(); списокКомпонентовToolStripMenuItem = new ToolStripMenuItem(); компонентыПоКомпьютерам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(); @@ -80,9 +83,30 @@ компьютерыToolStripMenuItem.Text = "Компьютеры"; компьютерыToolStripMenuItem.Click += ComputersStripMenuItem_Click; // + // магазиныToolStripMenuItem + // + магазиныToolStripMenuItem.Name = "магазиныToolStripMenuItem"; + магазиныToolStripMenuItem.Size = new Size(184, 26); + магазиныToolStripMenuItem.Text = "Магазины"; + магазиныToolStripMenuItem.Click += ShopsToolStripMenuItem_Click; + // + // поставкиToolStripMenuItem + // + поставкиToolStripMenuItem.Name = "поставкиToolStripMenuItem"; + поставкиToolStripMenuItem.Size = new Size(184, 26); + поставкиToolStripMenuItem.Text = "Поставки"; + поставкиToolStripMenuItem.Click += SupplyToolStripMenuItem_Click; + // + // SellsToolStripMenuItem + // + SellsToolStripMenuItem.Name = "SellsToolStripMenuItem"; + SellsToolStripMenuItem.Size = new Size(184, 26); + SellsToolStripMenuItem.Text = "Продажи"; + SellsToolStripMenuItem.Click += SellToolStripMenuItem_Click; + // // отчетыToolStripMenuItem // - отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокКомпонентовToolStripMenuItem, компонентыПоКомпьютерамToolStripMenuItem, списокЗаказовToolStripMenuItem }); + отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокКомпонентовToolStripMenuItem, компонентыПоКомпьютерамToolStripMenuItem, списокЗаказовToolStripMenuItem, списокМагазиновToolStripMenuItem, компьютерыПоМагазинамToolStripMenuItem, заказыПоДатамToolStripMenuItem }); отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem"; отчетыToolStripMenuItem.Size = new Size(73, 24); отчетыToolStripMenuItem.Text = "Отчеты"; @@ -108,19 +132,26 @@ списокЗаказовToolStripMenuItem.Text = "Список заказов"; списокЗаказовToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click; // - // магазиныToolStripMenuItem + // списокМагазиновToolStripMenuItem // - магазиныToolStripMenuItem.Name = "магазиныToolStripMenuItem"; - магазиныToolStripMenuItem.Size = new Size(224, 26); - магазиныToolStripMenuItem.Text = "Магазины"; - магазиныToolStripMenuItem.Click += ShopsToolStripMenuItem_Click; + списокМагазиновToolStripMenuItem.Name = "списокМагазиновToolStripMenuItem"; + списокМагазиновToolStripMenuItem.Size = new Size(306, 26); + списокМагазиновToolStripMenuItem.Text = "Список магазинов"; + списокМагазиновToolStripMenuItem.Click += списокМагазиновToolStripMenuItem_Click; // - // поставкиToolStripMenuItem + // компьютерыПоМагазинамToolStripMenuItem // - поставкиToolStripMenuItem.Name = "поставкиToolStripMenuItem"; - поставкиToolStripMenuItem.Size = new Size(224, 26); - поставкиToolStripMenuItem.Text = "Поставки"; - поставкиToolStripMenuItem.Click += SupplyToolStripMenuItem_Click; + компьютерыПоМагазинамToolStripMenuItem.Name = "компьютерыПоМагазинамToolStripMenuItem"; + компьютерыПоМагазинамToolStripMenuItem.Size = new Size(306, 26); + компьютерыПоМагазинамToolStripMenuItem.Text = "Компьютеры по магазинам"; + компьютерыПоМагазинамToolStripMenuItem.Click += компьютерыПоМагазинамToolStripMenuItem_Click; + // + // заказыПоДатамToolStripMenuItem + // + заказыПоДатамToolStripMenuItem.Name = "заказыПоДатамToolStripMenuItem"; + заказыПоДатамToolStripMenuItem.Size = new Size(306, 26); + заказыПоДатамToolStripMenuItem.Text = "Заказы по датам"; + заказыПоДатамToolStripMenuItem.Click += заказыПоДатамToolStripMenuItem_Click; // // dataGridView // @@ -182,13 +213,6 @@ 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); @@ -231,5 +255,8 @@ private ToolStripMenuItem списокКомпонентовToolStripMenuItem; private ToolStripMenuItem компонентыПоКомпьютерамToolStripMenuItem; private ToolStripMenuItem списокЗаказовToolStripMenuItem; + private ToolStripMenuItem списокМагазиновToolStripMenuItem; + private ToolStripMenuItem компьютерыПоМагазинамToolStripMenuItem; + private ToolStripMenuItem заказыПоДатамToolStripMenuItem; } } \ No newline at end of file diff --git a/ComputersShop/ComputersShop/FormMain.cs b/ComputersShop/ComputersShop/FormMain.cs index a166791..eaf8d34 100644 --- a/ComputersShop/ComputersShop/FormMain.cs +++ b/ComputersShop/ComputersShop/FormMain.cs @@ -145,6 +145,38 @@ Program.ServiceProvider?.GetService(typeof(FormReportComputerComponents)); } + private void списокМагазиновToolStripMenuItem_Click(object sender, EventArgs e) + { + using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; + if (dialog.ShowDialog() == DialogResult.OK) + { + _reportLogic.SaveShopsToWordFile(new ReportBindingModel + { + FileName = dialog.FileName + }); + MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, + MessageBoxIcon.Information); + } + } + + private void компьютерыПоМагазинамToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReportShopsComputers)); + if (service is FormReportShopsComputers form) + { + form.ShowDialog(); + } + } + + private void заказыПоДатамToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReportDateOrders)); + if (service is FormReportDateOrders form) + { + form.ShowDialog(); + } + } + private OrderBindingModel CreateBindingModel(int id, bool isDone = false) { return new OrderBindingModel diff --git a/ComputersShop/ComputersShop/FormReportDateOrders.Designer.cs b/ComputersShop/ComputersShop/FormReportDateOrders.Designer.cs new file mode 100644 index 0000000..5766e27 --- /dev/null +++ b/ComputersShop/ComputersShop/FormReportDateOrders.Designer.cs @@ -0,0 +1,82 @@ +namespace ComputersShop +{ + partial class FormReportDateOrders + { + /// + /// 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() + { + panel = new Panel(); + MakeButton = new Button(); + ToPdfButton = new Button(); + SuspendLayout(); + // + // panel + // + panel.Location = new Point(12, 71); + panel.Name = "panel"; + panel.Size = new Size(776, 367); + panel.TabIndex = 0; + // + // MakeButton + // + MakeButton.Location = new Point(12, 36); + MakeButton.Name = "MakeButton"; + MakeButton.Size = new Size(131, 29); + MakeButton.TabIndex = 1; + MakeButton.Text = "Сформировать"; + MakeButton.UseVisualStyleBackColor = true; + MakeButton.Click += MakeButton_Click; + // + // ToPdfButton + // + ToPdfButton.Location = new Point(149, 36); + ToPdfButton.Name = "ToPdfButton"; + ToPdfButton.Size = new Size(94, 29); + ToPdfButton.TabIndex = 2; + ToPdfButton.Text = "В PDF"; + ToPdfButton.UseVisualStyleBackColor = true; + ToPdfButton.Click += ToPdfButton_Click; + // + // ReportDateOrdersForm + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(800, 450); + Controls.Add(ToPdfButton); + Controls.Add(MakeButton); + Controls.Add(panel); + Name = "FormReportDateOrders"; + Text = "Заказы по датам"; + ResumeLayout(false); + } + + #endregion + + private Panel panel; + private Button MakeButton; + private Button ToPdfButton; + } +} \ No newline at end of file diff --git a/ComputersShop/ComputersShop/FormReportDateOrders.cs b/ComputersShop/ComputersShop/FormReportDateOrders.cs new file mode 100644 index 0000000..6c21482 --- /dev/null +++ b/ComputersShop/ComputersShop/FormReportDateOrders.cs @@ -0,0 +1,77 @@ +using ComputersShopContracts.BindingModels; +using ComputersShopContracts.BisnessLogicsContracts; +using Microsoft.Extensions.Logging; +using Microsoft.Reporting.WinForms; +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 FormReportDateOrders : Form + { + private readonly ReportViewer reportViewer; + + private readonly ILogger _logger; + + private readonly IReportLogic _logic; + public FormReportDateOrders(ILogger logger, IReportLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + reportViewer = new ReportViewer + { + Dock = DockStyle.Fill + }; + reportViewer.LocalReport.LoadReportDefinition(new FileStream("ReportOrdersByDate.rdlc", FileMode.Open)); + panel.Controls.Add(reportViewer); + } + + private void MakeButton_Click(object sender, EventArgs e) + { + try + { + var dataSource = _logic.GetDatesOrders(); + var source = new ReportDataSource("DataSetOrders", dataSource); + reportViewer.LocalReport.DataSources.Clear(); + reportViewer.LocalReport.DataSources.Add(source); + reportViewer.RefreshReport(); + _logger.LogInformation("Загрузка списка заказов на весь период по датам"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки списка заказов на период"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ToPdfButton_Click(object sender, EventArgs e) + { + using var dialog = new SaveFileDialog { Filter = "pdf|*.pdf" }; + if (dialog.ShowDialog() == DialogResult.OK) + { + try + { + _logic.SaveDatesOrdersToPdfFile(new ReportBindingModel + { + FileName = dialog.FileName + }); + _logger.LogInformation("Сохранение списка заказов на весь период по датам"); + MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка сохранения списка заказов на период"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } +} diff --git a/ComputersShop/ComputersShop/FormReportDateOrders.resx b/ComputersShop/ComputersShop/FormReportDateOrders.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/ComputersShop/ComputersShop/FormReportDateOrders.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/FormReportShopsComputers.Designer.cs b/ComputersShop/ComputersShop/FormReportShopsComputers.Designer.cs new file mode 100644 index 0000000..ab4455a --- /dev/null +++ b/ComputersShop/ComputersShop/FormReportShopsComputers.Designer.cs @@ -0,0 +1,103 @@ +namespace ComputersShop +{ + partial class FormReportShopsComputers + { + /// + /// 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(); + ShopColumn = new DataGridViewTextBoxColumn(); + IceCreamColumn = new DataGridViewTextBoxColumn(); + CountColumn = new DataGridViewTextBoxColumn(); + SaveButton = new Button(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // dataGridView + // + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Columns.AddRange(new DataGridViewColumn[] { ShopColumn, IceCreamColumn, CountColumn }); + dataGridView.Location = new Point(12, 64); + dataGridView.Name = "dataGridView"; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 29; + dataGridView.Size = new Size(682, 374); + dataGridView.TabIndex = 0; + // + // ShopColumn + // + ShopColumn.HeaderText = "Магазин"; + ShopColumn.MinimumWidth = 6; + ShopColumn.Name = "ShopColumn"; + ShopColumn.Width = 250; + // + // IceCreamColumn + // + IceCreamColumn.HeaderText = "Компьютер"; + IceCreamColumn.MinimumWidth = 6; + IceCreamColumn.Name = "ComputerColumn"; + IceCreamColumn.Width = 250; + // + // CountColumn + // + CountColumn.HeaderText = "Количество"; + CountColumn.MinimumWidth = 6; + CountColumn.Name = "CountColumn"; + CountColumn.Width = 125; + // + // SaveButton + // + SaveButton.Location = new Point(12, 29); + SaveButton.Name = "SaveButton"; + SaveButton.Size = new Size(122, 29); + SaveButton.TabIndex = 1; + SaveButton.Text = "Сохранить в"; + SaveButton.UseVisualStyleBackColor = true; + SaveButton.Click += SaveButton_Click; + // + // FormReportShopsComputers + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(702, 450); + Controls.Add(SaveButton); + Controls.Add(dataGridView); + Name = "FormReportShopsComputers"; + Text = "Компьютеры по магазинам"; + Load += ReportShopsComputersForm_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView; + private Button SaveButton; + private DataGridViewTextBoxColumn ShopColumn; + private DataGridViewTextBoxColumn IceCreamColumn; + private DataGridViewTextBoxColumn CountColumn; + } +} \ No newline at end of file diff --git a/ComputersShop/ComputersShop/FormReportShopsComputers.cs b/ComputersShop/ComputersShop/FormReportShopsComputers.cs new file mode 100644 index 0000000..9bc0f5c --- /dev/null +++ b/ComputersShop/ComputersShop/FormReportShopsComputers.cs @@ -0,0 +1,88 @@ +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 FormReportShopsComputers : Form + { + private readonly ILogger _logger; + private readonly IReportLogic _logic; + + public FormReportShopsComputers(ILogger logger, IReportLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + + } + + private void ReportShopsComputersForm_Load(object sender, EventArgs e) + { + try + { + var dict = _logic.GetShopsComputers(); + if (dict != null) + { + dataGridView.Rows.Clear(); + foreach (var elem in dict) + { + dataGridView.Rows.Add(new object[] { elem.ShopName, "", "" }); + foreach (var listElem in elem.Computers) + { + dataGridView.Rows.Add(new object[] { "", listElem.Item1, listElem.Item2 }); + } + dataGridView.Rows.Add(new object[] { "Итого", "", elem.TotalCount }); + dataGridView.Rows.Add(Array.Empty()); + } + } + _logger.LogInformation("Загрузка списка компьютеров по магазинам"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки списка компьютеров по магазинам"); + + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + + } + private void SaveButton_Click(object sender, EventArgs e) + { + using var dialog = new SaveFileDialog + { + Filter = "xlsx|*.xlsx" + }; + if (dialog.ShowDialog() == DialogResult.OK) + { + try + { + _logic.SaveShopsComputersToExcelFile(new ReportBindingModel + { + FileName = dialog.FileName + }); + _logger.LogInformation("Сохранение списка сомпьютеров по магазинам"); + + MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, + MessageBoxIcon.Information); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка сохранения списка компьютеров по магазинам"); + + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + } + } +} diff --git a/ComputersShop/ComputersShop/FormReportShopsComputers.resx b/ComputersShop/ComputersShop/FormReportShopsComputers.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/ComputersShop/ComputersShop/FormReportShopsComputers.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 5967690..62b7375 100644 --- a/ComputersShop/ComputersShop/Program.cs +++ b/ComputersShop/ComputersShop/Program.cs @@ -59,6 +59,8 @@ namespace ComputersShop services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); diff --git a/ComputersShop/ComputersShop/ReportOrdersByDate.rdlc b/ComputersShop/ComputersShop/ReportOrdersByDate.rdlc new file mode 100644 index 0000000..f7156f4 --- /dev/null +++ b/ComputersShop/ComputersShop/ReportOrdersByDate.rdlc @@ -0,0 +1,400 @@ + + + + + + true + true + + + + + Заказы + + + + + + + 0.24cm + 1cm + 21cm + + + Middle + 2pt + 2pt + 2pt + 2pt + + + + + + + 3cm + + + 3cm + + + 7cm + + + + + 0.6cm + + + + + true + true + + + + + Дата + + + + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + Количество + + + + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + Сумма + + + + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + 0.6cm + + + + + true + true + + + + + =Fields!DateOfOrders.Value + + + + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + =Fields!Count.Value + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + =Fields!Sum.Value + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + + + + + + + + + + + + After + + + + + + + DataSetOrders + 2.72391cm + 0.55245cm + 1.2cm + 13cm + 1 + + + + + + true + true + + + + + Всего: + + + + + + + 4.24cm + 8.55245cm + 0.6cm + 2.5cm + 2 + + + 2pt + 2pt + 2pt + 2pt + + + + true + true + + + + + =Sum(Fields!Sum.Value, "DataSetOrders") + + + + + + + 4.24cm + 11.05245cm + 0.6cm + 2.5cm + 3 + + + 2pt + 2pt + 2pt + 2pt + + + + 2in +