diff --git a/CarpentryWorkshop/CarpentryWorkshop/FormMain.Designer.cs b/CarpentryWorkshop/CarpentryWorkshop/FormMain.Designer.cs index 08dbbfe..e50250d 100644 --- a/CarpentryWorkshop/CarpentryWorkshop/FormMain.Designer.cs +++ b/CarpentryWorkshop/CarpentryWorkshop/FormMain.Designer.cs @@ -32,6 +32,9 @@ справочники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(); @@ -47,13 +50,14 @@ menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem }); menuStrip1.Location = new Point(0, 0); menuStrip1.Name = "menuStrip1"; - menuStrip1.Size = new Size(896, 24); + menuStrip1.Padding = new Padding(5, 2, 0, 2); + menuStrip1.Size = new Size(1134, 24); menuStrip1.TabIndex = 0; menuStrip1.Text = "menuStrip1"; // // справочникиToolStripMenuItem // - справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { КомпонентыToolStripMenuItem, ИзделияToolStripMenuItem }); + справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { КомпонентыToolStripMenuItem, ИзделияToolStripMenuItem, магазиныToolStripMenuItem, поставкиToolStripMenuItem, продажиToolStripMenuItem }); справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; справочникиToolStripMenuItem.Size = new Size(94, 20); справочникиToolStripMenuItem.Text = "Справочники"; @@ -72,6 +76,27 @@ ИзделияToolStripMenuItem.Text = "Изделия"; ИзделияToolStripMenuItem.Click += ИзделияToolStripMenuItem_Click; // + // магазиныToolStripMenuItem + // + магазиныToolStripMenuItem.Name = "магазиныToolStripMenuItem"; + магазиныToolStripMenuItem.Size = new Size(180, 22); + магазиныToolStripMenuItem.Text = "Магазины"; + магазиныToolStripMenuItem.Click += магазиныToolStripMenuItem_Click; + // + // поставкиToolStripMenuItem + // + поставкиToolStripMenuItem.Name = "поставкиToolStripMenuItem"; + поставкиToolStripMenuItem.Size = new Size(180, 22); + поставкиToolStripMenuItem.Text = "Поставки"; + поставкиToolStripMenuItem.Click += поставкиToolStripMenuItem_Click; + // + // продажиToolStripMenuItem + // + продажиToolStripMenuItem.Name = "продажиToolStripMenuItem"; + продажиToolStripMenuItem.Size = new Size(180, 22); + продажиToolStripMenuItem.Text = "Продажи"; + продажиToolStripMenuItem.Click += продажиToolStripMenuItem_Click; + // // dataGridView // dataGridView.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; @@ -174,5 +199,8 @@ private Button ButtonRef; private ToolStripMenuItem КомпонентыToolStripMenuItem; private ToolStripMenuItem ИзделияToolStripMenuItem; + private ToolStripMenuItem магазиныToolStripMenuItem; + private ToolStripMenuItem поставкиToolStripMenuItem; + private ToolStripMenuItem продажиToolStripMenuItem; } } \ No newline at end of file diff --git a/CarpentryWorkshop/CarpentryWorkshop/FormMain.cs b/CarpentryWorkshop/CarpentryWorkshop/FormMain.cs index 73d980e..e7ad7c8 100644 --- a/CarpentryWorkshop/CarpentryWorkshop/FormMain.cs +++ b/CarpentryWorkshop/CarpentryWorkshop/FormMain.cs @@ -151,5 +151,31 @@ namespace CarpentryWorkshopView { LoadData(); } + + private void магазиныToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormShops)); + if (service is FormShops form) + { + form.ShowDialog(); + } + } + + private void поставкиToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormSupply)); + if (service is FormSupply form) + { + form.ShowDialog(); + } + } + private void продажиToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormWoodSale)); + if (service is FormWoodSale form) + { + form.ShowDialog(); + } + } } } diff --git a/CarpentryWorkshop/CarpentryWorkshop/FormSell.Designer.cs b/CarpentryWorkshop/CarpentryWorkshop/FormSell.Designer.cs new file mode 100644 index 0000000..945e17b --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshop/FormSell.Designer.cs @@ -0,0 +1,117 @@ +namespace CarpentryWorkshopView +{ + 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() + { + WoodComboBox = new ComboBox(); + WoodLabel = new Label(); + CountLabel = new Label(); + CountTextBox = new TextBox(); + SaveButton = new Button(); + CancelButton = new Button(); + SuspendLayout(); + // + // WoodComboBox + // + WoodComboBox.FormattingEnabled = true; + WoodComboBox.Location = new Point(99, 12); + WoodComboBox.Name = "WoodComboBox"; + WoodComboBox.Size = new Size(121, 23); + WoodComboBox.TabIndex = 0; + // + // WoodLabel + // + WoodLabel.AutoSize = true; + WoodLabel.Location = new Point(12, 20); + WoodLabel.Name = "WoodLabel"; + WoodLabel.Size = new Size(81, 15); + WoodLabel.TabIndex = 1; + WoodLabel.Text = "Изделие"; + // + // CountLabel + // + CountLabel.AutoSize = true; + CountLabel.Location = new Point(21, 49); + CountLabel.Name = "CountLabel"; + CountLabel.Size = new Size(72, 15); + CountLabel.TabIndex = 2; + CountLabel.Text = "Количество"; + // + // CountTextBox + // + CountTextBox.Location = new Point(99, 41); + CountTextBox.Name = "CountTextBox"; + CountTextBox.Size = new Size(121, 23); + CountTextBox.TabIndex = 3; + // + // SaveButton + // + SaveButton.Location = new Point(64, 73); + SaveButton.Name = "SaveButton"; + SaveButton.Size = new Size(75, 23); + SaveButton.TabIndex = 4; + SaveButton.Text = "Сохранить"; + SaveButton.UseVisualStyleBackColor = true; + SaveButton.Click += SaveButton_Click; + // + // CancelButton + // + CancelButton.Location = new Point(145, 73); + CancelButton.Name = "CancelButton"; + CancelButton.Size = new Size(75, 23); + CancelButton.TabIndex = 5; + CancelButton.Text = "Отмена"; + CancelButton.UseVisualStyleBackColor = true; + // + // FormSell + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(224, 108); + Controls.Add(CancelButton); + Controls.Add(SaveButton); + Controls.Add(CountTextBox); + Controls.Add(CountLabel); + Controls.Add(WoodLabel); + Controls.Add(WoodComboBox); + Name = "FormSell"; + Text = "Форма продажи"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private ComboBox WoodComboBox; + private Label WoodLabel; + private Label CountLabel; + private TextBox CountTextBox; + private Button SaveButton; + private Button CancelButton; + } +} \ No newline at end of file diff --git a/CarpentryWorkshop/CarpentryWorkshop/FormSell.cs b/CarpentryWorkshop/CarpentryWorkshop/FormSell.cs new file mode 100644 index 0000000..89c3d3d --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshop/FormSell.cs @@ -0,0 +1,115 @@ +using CarpentryWorkshopContracts.BusinessLogicsContracts; +using CarpentryWorkshopContracts.ViewModels; +using CarpentryWorkshopDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace CarpentryWorkshopView +{ + public partial class FormSell : Form + { + private readonly List? _woodList; + IShopLogic _shopLogic; + IWoodLogic _woodLogic; + public FormSell(IWoodLogic woodLogic, IShopLogic shopLogic) + { + InitializeComponent(); + _shopLogic = shopLogic; + _woodLogic = woodLogic; + _woodList = woodLogic.ReadList(null); + if (_woodList != null) + { + WoodComboBox.DisplayMember = "WoodName"; + WoodComboBox.ValueMember = "Id"; + WoodComboBox.DataSource = _woodList; + WoodComboBox.SelectedItem = null; + } + } + public int WoodId + { + get + { + return Convert.ToInt32(WoodComboBox.SelectedValue); + } + set + { + WoodComboBox.SelectedValue = value; + } + } + + public IWoodModel? WoodModel + { + get + { + if (_woodList == null) + { + return null; + } + foreach (var elem in _woodList) + { + if (elem.Id == WoodId) + { + return elem; + } + } + return null; + } + } + + + public int Count + { + get { return Convert.ToInt32(CountTextBox.Text); } + set + { CountTextBox.Text = value.ToString(); } + } + + private void SaveButton_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(CountTextBox.Text)) + { + MessageBox.Show("Заполните поле Количество", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (WoodComboBox.SelectedValue == null) + { + MessageBox.Show("Выберите изделие", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + + try + { + int count = Convert.ToInt32(CountTextBox.Text); + + bool res = _shopLogic.MakeSell( + _woodLogic.ReadElement(new() { Id = Convert.ToInt32(WoodComboBox.SelectedValue) }), + count + ); + + if (!res) + { + throw new Exception("Ошибка при продаже."); + } + + MessageBox.Show("Продажа прошла успешно"); + DialogResult = DialogResult.OK; + Close(); + + } + catch (Exception err) + { + MessageBox.Show("Ошибка продажи"); + return; + } + } + } +} diff --git a/CarpentryWorkshop/CarpentryWorkshop/FormSell.resx b/CarpentryWorkshop/CarpentryWorkshop/FormSell.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshop/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/CarpentryWorkshop/CarpentryWorkshop/FormShop.Designer.cs b/CarpentryWorkshop/CarpentryWorkshop/FormShop.Designer.cs new file mode 100644 index 0000000..5a8b4ca --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshop/FormShop.Designer.cs @@ -0,0 +1,221 @@ +namespace CarpentryWorkshopView +{ + 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(); + Column1 = new DataGridViewTextBoxColumn(); + Название = new DataGridViewTextBoxColumn(); + Цена = new DataGridViewTextBoxColumn(); + Количество = new DataGridViewTextBoxColumn(); + CapacityUpDown = new NumericUpDown(); + CapacityLabel = new Label(); + ((System.ComponentModel.ISupportInitialize)DataGridView).BeginInit(); + ((System.ComponentModel.ISupportInitialize)CapacityUpDown).BeginInit(); + SuspendLayout(); + // + // DateTimePicker + // + DateTimePicker.Location = new Point(85, 70); + DateTimePicker.Name = "DateTimePicker"; + DateTimePicker.Size = new Size(318, 23); + DateTimePicker.TabIndex = 0; + // + // NameTextBox + // + NameTextBox.Location = new Point(85, 12); + NameTextBox.Name = "NameTextBox"; + NameTextBox.Size = new Size(318, 23); + NameTextBox.TabIndex = 1; + // + // AddressTextBox + // + AddressTextBox.Location = new Point(85, 41); + AddressTextBox.Name = "AddressTextBox"; + AddressTextBox.Size = new Size(318, 23); + AddressTextBox.TabIndex = 2; + // + // NameLabel + // + NameLabel.AutoSize = true; + NameLabel.Location = new Point(12, 15); + NameLabel.Name = "NameLabel"; + NameLabel.Size = new Size(59, 15); + NameLabel.TabIndex = 3; + NameLabel.Text = "Название"; + // + // AdressLabel + // + AdressLabel.AutoSize = true; + AdressLabel.Location = new Point(12, 44); + AdressLabel.Name = "AdressLabel"; + AdressLabel.Size = new Size(40, 15); + AdressLabel.TabIndex = 4; + AdressLabel.Text = "Адрес"; + // + // DateLabel + // + DateLabel.AutoSize = true; + DateLabel.Location = new Point(12, 76); + DateLabel.Name = "DateLabel"; + DateLabel.Size = new Size(32, 15); + DateLabel.TabIndex = 5; + DateLabel.Text = "Дата"; + // + // SaveButton + // + SaveButton.Location = new Point(247, 284); + SaveButton.Name = "SaveButton"; + SaveButton.Size = new Size(75, 23); + SaveButton.TabIndex = 6; + SaveButton.Text = "Сохранить"; + SaveButton.UseVisualStyleBackColor = true; + SaveButton.Click += ButtonSave_Click; + // + // CancelButton + // + CancelButton.Location = new Point(328, 284); + CancelButton.Name = "CancelButton"; + CancelButton.Size = new Size(75, 23); + CancelButton.TabIndex = 7; + CancelButton.Text = "Отмена"; + CancelButton.UseVisualStyleBackColor = true; + CancelButton.Click += ButtonCancel_Click; + // + // DataGridView + // + DataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + DataGridView.Columns.AddRange(new DataGridViewColumn[] { Column1, Название, Цена, Количество }); + DataGridView.Location = new Point(12, 128); + DataGridView.Name = "DataGridView"; + DataGridView.RowHeadersWidth = 51; + DataGridView.Size = new Size(391, 150); + DataGridView.TabIndex = 8; + // + // Column1 + // + Column1.HeaderText = "Column1"; + Column1.MinimumWidth = 6; + Column1.Name = "Column1"; + Column1.Visible = false; + Column1.Width = 125; + // + // Название + // + Название.HeaderText = "Название"; + Название.MinimumWidth = 6; + Название.Name = "Название"; + Название.ReadOnly = true; + Название.Width = 150; + // + // Цена + // + Цена.HeaderText = "Цена"; + Цена.MinimumWidth = 6; + Цена.Name = "Цена"; + Цена.ReadOnly = true; + Цена.Width = 125; + // + // Количество + // + Количество.HeaderText = "Количество"; + Количество.MinimumWidth = 6; + Количество.Name = "Количество"; + Количество.ReadOnly = true; + Количество.Width = 125; + // + // CapacityUpDown + // + CapacityUpDown.Location = new Point(98, 99); + CapacityUpDown.Maximum = new decimal(new int[] { 10000, 0, 0, 0 }); + CapacityUpDown.Name = "CapacityUpDown"; + CapacityUpDown.Size = new Size(120, 23); + CapacityUpDown.TabIndex = 9; + // + // CapacityLabel + // + CapacityLabel.AutoSize = true; + CapacityLabel.Location = new Point(12, 107); + CapacityLabel.Name = "CapacityLabel"; + CapacityLabel.Size = new Size(80, 15); + CapacityLabel.TabIndex = 10; + CapacityLabel.Text = "Вместимость"; + // + // FormShop + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(411, 315); + Controls.Add(CapacityLabel); + Controls.Add(CapacityUpDown); + 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); + 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 Column1; + private DataGridViewTextBoxColumn Название; + private DataGridViewTextBoxColumn Цена; + private DataGridViewTextBoxColumn Количество; + private NumericUpDown CapacityUpDown; + private Label CapacityLabel; + } +} \ No newline at end of file diff --git a/CarpentryWorkshop/CarpentryWorkshop/FormShop.cs b/CarpentryWorkshop/CarpentryWorkshop/FormShop.cs new file mode 100644 index 0000000..0de17b6 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshop/FormShop.cs @@ -0,0 +1,133 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.BusinessLogicsContracts; +using CarpentryWorkshopContracts.SearchModels; +using CarpentryWorkshopDataModels.Models; +using Microsoft.Extensions.Logging; +using System.Windows.Forms; + +namespace CarpentryWorkshopView +{ + public partial class FormShop : Form + { + private readonly ILogger _logger; + + private readonly IShopLogic _logic; + + private int? _id; + + private Dictionary _shopWoods; + + public int Id { set { _id = value; } } + + public FormShop(ILogger logger, IShopLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + _shopWoods = new Dictionary(); + } + + private void FormShop_Load(object sender, EventArgs e) + { + if (_id.HasValue) + { + _logger.LogInformation("Shop loading"); + try + { + var view = _logic.ReadElement(new ShopSearchModel { Id = _id.Value }); + if (view != null) + { + NameTextBox.Text = view.ShopName; + AddressTextBox.Text = view.Address; + DateTimePicker.Value = view.DateOpen; + CapacityUpDown.Text = view.WoodMaxCount.ToString(); + _shopWoods = view.ShopWoods ?? new Dictionary(); + LoadData(); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Shop loading error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + + private void LoadData() + { + _logger.LogInformation("Shop ice creams loading"); + try + { + if (_shopWoods != null) + { + DataGridView.Rows.Clear(); + foreach (var wood in _shopWoods) + { + DataGridView.Rows.Add(new object[] { wood.Key, wood.Value.Item1.WoodName, wood.Value.Item2 }); + } + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Shop ice creams loading error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ButtonSave_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; + } + if (string.IsNullOrEmpty(DateTimePicker.Text)) + { + MessageBox.Show("Заполните дату", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (string.IsNullOrEmpty(CapacityUpDown.Text)) + { + MessageBox.Show("Заполните максимальное количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Shop saving"); + try + { + var model = new ShopBindingModel + { + Id = _id ?? 0, + ShopName = NameTextBox.Text, + Address = AddressTextBox.Text, + DateOpen = DateTimePicker.Value, + WoodMaxCount = Convert.ToInt32(CapacityUpDown.Text), + ShopWoods = _shopWoods + }; + 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, "Shop saving error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ButtonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } +} diff --git a/CarpentryWorkshop/CarpentryWorkshop/FormShop.resx b/CarpentryWorkshop/CarpentryWorkshop/FormShop.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshop/FormShop.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/CarpentryWorkshop/CarpentryWorkshop/FormShops.Designer.cs b/CarpentryWorkshop/CarpentryWorkshop/FormShops.Designer.cs new file mode 100644 index 0000000..b1ec242 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshop/FormShops.Designer.cs @@ -0,0 +1,117 @@ +namespace CarpentryWorkshopView +{ + 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(12, 12); + DataGridView.Name = "DataGridView"; + DataGridView.Size = new Size(393, 374); + DataGridView.TabIndex = 0; + // + // AddButton + // + AddButton.Location = new Point(411, 12); + AddButton.Name = "AddButton"; + AddButton.Size = new Size(114, 23); + AddButton.TabIndex = 1; + AddButton.Text = "Добавить"; + AddButton.UseVisualStyleBackColor = true; + AddButton.Click += ButtonAdd_Click; + // + // UpdateButton + // + UpdateButton.Location = new Point(411, 41); + UpdateButton.Name = "UpdateButton"; + UpdateButton.Size = new Size(114, 23); + UpdateButton.TabIndex = 2; + UpdateButton.Text = "Изменить"; + UpdateButton.UseVisualStyleBackColor = true; + UpdateButton.Click += ButtonEdit_Click; + // + // RefreshButton + // + RefreshButton.Location = new Point(411, 70); + RefreshButton.Name = "RefreshButton"; + RefreshButton.Size = new Size(114, 23); + RefreshButton.TabIndex = 3; + RefreshButton.Text = "Обновить"; + RefreshButton.UseVisualStyleBackColor = true; + RefreshButton.Click += ButtonUpd_Click; + // + // DeleteButton + // + DeleteButton.Location = new Point(411, 99); + DeleteButton.Name = "DeleteButton"; + DeleteButton.Size = new Size(114, 23); + DeleteButton.TabIndex = 4; + DeleteButton.Text = "Удалить"; + DeleteButton.UseVisualStyleBackColor = true; + DeleteButton.Click += ButtonDel_Click; + // + // ShopsForm + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(539, 403); + Controls.Add(DeleteButton); + Controls.Add(RefreshButton); + Controls.Add(UpdateButton); + Controls.Add(AddButton); + Controls.Add(DataGridView); + Name = "FormShops"; + Text = "FormShops"; + 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; + private DataGridViewTextBoxColumn Column1; + private DataGridViewTextBoxColumn Column2; + private DataGridViewTextBoxColumn Column3; + private DataGridViewTextBoxColumn Column4; + private DataGridViewTextBoxColumn Column5; + } +} \ No newline at end of file diff --git a/CarpentryWorkshop/CarpentryWorkshop/FormShops.cs b/CarpentryWorkshop/CarpentryWorkshop/FormShops.cs new file mode 100644 index 0000000..76ae5c2 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshop/FormShops.cs @@ -0,0 +1,106 @@ +using CarpentryWorkshop; +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using System.Windows.Forms; + +namespace CarpentryWorkshopView +{ + 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 FormShops_Load(object sender, EventArgs e) + { + LoadData(); + } + + private void LoadData() + { + try + { + var list = _logic.ReadList(null); + if (list != null) + { + DataGridView.DataSource = list; + DataGridView.Columns["Id"].Visible = false; + DataGridView.Columns["ShopName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + DataGridView.Columns["ShopWoods"].Visible = false; + } + _logger.LogInformation("Shops loading"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Shops loading error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ButtonAdd_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormShop)); + if (service is FormShop form) + { + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + + private void ButtonEdit_Click(object sender, EventArgs e) + { + if (DataGridView.SelectedRows.Count == 1) + { + var service = Program.ServiceProvider?.GetService(typeof(FormShop)); + if (service is FormShop form) + { + form.Id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + } + + private void ButtonDel_Click(object sender, EventArgs e) + { + if (DataGridView.SelectedRows.Count == 1) + { + if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + int id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Deletion of shop"); + try + { + if (!_logic.Delete(new ShopBindingModel { Id = id })) + { + throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Shop deletion error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } + + private void ButtonUpd_Click(object sender, EventArgs e) + { + LoadData(); + } + } +} diff --git a/CarpentryWorkshop/CarpentryWorkshop/FormShops.resx b/CarpentryWorkshop/CarpentryWorkshop/FormShops.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshop/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/CarpentryWorkshop/CarpentryWorkshop/FormSupply.Designer.cs b/CarpentryWorkshop/CarpentryWorkshop/FormSupply.Designer.cs new file mode 100644 index 0000000..5f858ea --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshop/FormSupply.Designer.cs @@ -0,0 +1,109 @@ +namespace CarpentryWorkshopView +{ + 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(); + WoodComboBox = new ComboBox(); + CountTextBox = new TextBox(); + SaveButton = new Button(); + CancelButton = new Button(); + SuspendLayout(); + // + // ShopComboBox + // + ShopComboBox.FormattingEnabled = true; + ShopComboBox.Location = new Point(12, 12); + ShopComboBox.Name = "ShopComboBox"; + ShopComboBox.Size = new Size(331, 23); + ShopComboBox.TabIndex = 0; + ShopComboBox.DropDownStyle = ComboBoxStyle.DropDownList; + ShopComboBox.FormattingEnabled = true; + // + // WoodComboBox + // + WoodComboBox.FormattingEnabled = true; + WoodComboBox.Location = new Point(12, 41); + WoodComboBox.Name = "WoodComboBox"; + WoodComboBox.Size = new Size(331, 23); + WoodComboBox.TabIndex = 1; + WoodComboBox.DropDownStyle = ComboBoxStyle.DropDownList; + WoodComboBox.FormattingEnabled = true; + // + // CountTextBox + // + CountTextBox.Location = new Point(12, 70); + CountTextBox.Name = "CountTextBox"; + CountTextBox.Size = new Size(331, 23); + CountTextBox.TabIndex = 2; + // + // SaveButton + // + SaveButton.Location = new Point(187, 99); + SaveButton.Name = "SaveButton"; + SaveButton.Size = new Size(75, 23); + SaveButton.TabIndex = 3; + SaveButton.Text = "Сохранить"; + SaveButton.UseVisualStyleBackColor = true; + SaveButton.Click += SaveButton_Click; + // + // CancelButton + // + CancelButton.Location = new Point(268, 99); + CancelButton.Name = "CancelButton"; + CancelButton.Size = new Size(75, 23); + CancelButton.TabIndex = 4; + CancelButton.Text = "Отмена"; + CancelButton.UseVisualStyleBackColor = true; + CancelButton.Click += CancelButton_Click; + // + // FormSupply + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(355, 136); + Controls.Add(CancelButton); + Controls.Add(SaveButton); + Controls.Add(CountTextBox); + Controls.Add(WoodComboBox); + Controls.Add(ShopComboBox); + Name = "FormSupply"; + Text = "SupplyForm"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private ComboBox ShopComboBox; + private ComboBox WoodComboBox; + private TextBox CountTextBox; + private Button SaveButton; + private Button CancelButton; + } +} \ No newline at end of file diff --git a/CarpentryWorkshop/CarpentryWorkshop/FormSupply.cs b/CarpentryWorkshop/CarpentryWorkshop/FormSupply.cs new file mode 100644 index 0000000..8297b97 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshop/FormSupply.cs @@ -0,0 +1,150 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.BusinessLogicsContracts; +using CarpentryWorkshopContracts.SearchModels; +using CarpentryWorkshopContracts.ViewModels; +using CarpentryWorkshopDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace CarpentryWorkshopView +{ + public partial class FormSupply : Form + { + private readonly List? _woodList; + private readonly List? _shopsList; + IShopLogic _shopLogic; + IWoodLogic _woodLogic; + public int ShopId + { + get + { + return Convert.ToInt32(ShopComboBox.SelectedValue); + } + set + { + ShopComboBox.SelectedValue = value; + } + } + public int WoodId + { + get + { + return Convert.ToInt32(WoodComboBox.SelectedValue); + } + set + { + WoodComboBox.SelectedValue = value; + } + } + + public IWoodModel? WoodModel + { + get + { + if (_woodList == null) + { + return null; + } + foreach (var elem in _woodList) + { + if (elem.Id == WoodId) + { + return elem; + } + } + return null; + } + } + + + public int Count + { + get { return Convert.ToInt32(CountTextBox.Text); } + set + { CountTextBox.Text = value.ToString(); } + } + public FormSupply(IWoodLogic woodLogic, IShopLogic shopLogic) + { + InitializeComponent(); + _shopLogic = shopLogic; + _woodLogic = woodLogic; + _woodList = woodLogic.ReadList(null); + _shopsList = shopLogic.ReadList(null); + if (_woodList != null) + { + WoodComboBox.DisplayMember = "WoodName"; + WoodComboBox.ValueMember = "Id"; + WoodComboBox.DataSource = _woodList; + WoodComboBox.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 (WoodComboBox.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) }, + _woodLogic.ReadElement(new() { Id = Convert.ToInt32(WoodComboBox.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/CarpentryWorkshop/CarpentryWorkshop/FormSupply.resx b/CarpentryWorkshop/CarpentryWorkshop/FormSupply.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshop/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/CarpentryWorkshop/CarpentryWorkshop/FormWoodSale.Designer.cs b/CarpentryWorkshop/CarpentryWorkshop/FormWoodSale.Designer.cs new file mode 100644 index 0000000..df9ee7a --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshop/FormWoodSale.Designer.cs @@ -0,0 +1,127 @@ +namespace CarpentryWorkshopView +{ + partial class FormWoodSale + { + /// + /// 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() + { + buttonCancel = new Button(); + buttonSale = new Button(); + textBoxCount = new TextBox(); + labelCount = new Label(); + comboBoxWood = new ComboBox(); + labelWood = new Label(); + SuspendLayout(); + // + // buttonCancel + // + buttonCancel.Location = new Point(253, 83); + buttonCancel.Margin = new Padding(4, 3, 4, 3); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(88, 27); + buttonCancel.TabIndex = 17; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += ButtonCancel_Click; + // + // buttonSale + // + buttonSale.Location = new Point(159, 83); + buttonSale.Margin = new Padding(4, 3, 4, 3); + buttonSale.Name = "buttonSale"; + buttonSale.Size = new Size(88, 27); + buttonSale.TabIndex = 16; + buttonSale.Text = "Продать"; + buttonSale.UseVisualStyleBackColor = true; + buttonSale.Click += ButtonSale_Click; + // + // textBoxCount + // + textBoxCount.Location = new Point(101, 51); + textBoxCount.Margin = new Padding(4, 3, 4, 3); + textBoxCount.Name = "textBoxCount"; + textBoxCount.Size = new Size(252, 23); + textBoxCount.TabIndex = 15; + // + // labelCount + // + labelCount.AutoSize = true; + labelCount.Location = new Point(13, 54); + labelCount.Margin = new Padding(4, 0, 4, 0); + labelCount.Name = "labelCount"; + labelCount.Size = new Size(78, 15); + labelCount.TabIndex = 14; + labelCount.Text = "Количество :"; + // + // comboBoxWood + // + comboBoxWood.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxWood.FormattingEnabled = true; + comboBoxWood.Location = new Point(101, 15); + comboBoxWood.Margin = new Padding(4, 3, 4, 3); + comboBoxWood.Name = "comboBoxWood"; + comboBoxWood.Size = new Size(252, 23); + comboBoxWood.TabIndex = 13; + // + // labelWood + // + labelWood.AutoSize = true; + labelWood.Location = new Point(13, 19); + labelWood.Margin = new Padding(4, 0, 4, 0); + labelWood.Name = "labelWood"; + labelWood.Size = new Size(80, 15); + labelWood.TabIndex = 12; + labelWood.Text = "Изделие :"; + // + // FormWoodSale + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(373, 123); + Controls.Add(buttonCancel); + Controls.Add(buttonSale); + Controls.Add(textBoxCount); + Controls.Add(labelCount); + Controls.Add(comboBoxWood); + Controls.Add(labelWood); + Name = "FormWoodSale"; + StartPosition = FormStartPosition.CenterScreen; + Text = "Продажа изделий"; + Load += FormWoodSale_Load; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Button buttonCancel; + private Button buttonSale; + private TextBox textBoxCount; + private Label labelCount; + private ComboBox comboBoxWood; + private Label labelWood; + } +} \ No newline at end of file diff --git a/CarpentryWorkshop/CarpentryWorkshop/FormWoodSale.cs b/CarpentryWorkshop/CarpentryWorkshop/FormWoodSale.cs new file mode 100644 index 0000000..3d7352c --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshop/FormWoodSale.cs @@ -0,0 +1,96 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace CarpentryWorkshopView +{ + public partial class FormWoodSale : Form + { + private readonly ILogger _logger; + + private readonly IWoodLogic _logicWood; + + private readonly IShopLogic _logicShop; + + public FormWoodSale(ILogger logger, IWoodLogic logicWood, IShopLogic logicShop) + { + InitializeComponent(); + _logger = logger; + _logicWood = logicWood; + _logicShop = logicShop; + } + + private void FormWoodSale_Load(object sender, EventArgs e) + { + _logger.LogInformation("Ice creams loading"); + try + { + var list = _logicWood.ReadList(null); + if (list != null) + { + comboBoxWood.DisplayMember = "WoodName"; + comboBoxWood.ValueMember = "Id"; + comboBoxWood.DataSource = list; + comboBoxWood.SelectedItem = null; + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ice creams loading error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ButtonSale_Click(object sender, EventArgs e) + { + if (comboBoxWood.SelectedValue == null) + { + MessageBox.Show("Выберите мороженое", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (string.IsNullOrEmpty(textBoxCount.Text)) + { + MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Ice cream sale"); + try + { + var operationResult = _logicShop.MakeSell( + new WoodBindingModel + { + Id = Convert.ToInt32(comboBoxWood.SelectedValue) + }, + Convert.ToInt32(textBoxCount.Text) + ); + if (!operationResult) + { + throw new Exception("Ошибка при продаже."); + } + MessageBox.Show("Продажа прошла успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + Close(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Wood sale error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ButtonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } +} diff --git a/CarpentryWorkshop/CarpentryWorkshop/FormWoodSale.resx b/CarpentryWorkshop/CarpentryWorkshop/FormWoodSale.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshop/FormWoodSale.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/CarpentryWorkshop/CarpentryWorkshop/Program.cs b/CarpentryWorkshop/CarpentryWorkshop/Program.cs index 8759e1b..8901fba 100644 --- a/CarpentryWorkshop/CarpentryWorkshop/Program.cs +++ b/CarpentryWorkshop/CarpentryWorkshop/Program.cs @@ -39,10 +39,12 @@ namespace CarpentryWorkshop services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -51,6 +53,10 @@ namespace CarpentryWorkshop services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); } } } \ No newline at end of file diff --git a/CarpentryWorkshop/CarpentryWorkshopBusinessLogic/BusinessLogics/OrderLogic.cs b/CarpentryWorkshop/CarpentryWorkshopBusinessLogic/BusinessLogics/OrderLogic.cs index 66a3eee..f9da371 100644 --- a/CarpentryWorkshop/CarpentryWorkshopBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/CarpentryWorkshop/CarpentryWorkshopBusinessLogic/BusinessLogics/OrderLogic.cs @@ -4,6 +4,7 @@ using CarpentryWorkshopContracts.SearchModels; using CarpentryWorkshopContracts.StoragesContracts; using CarpentryWorkshopContracts.ViewModels; using CarpentryWorkshopDataModels.Enums; +using CarpentryWorkshopDataModels.Models; using Microsoft.Extensions.Logging; namespace CarpentryWorkshopBusinessLogic.BusinessLogics @@ -12,11 +13,18 @@ namespace CarpentryWorkshopBusinessLogic.BusinessLogics { private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; + private readonly IShopStorage _shopStorage; + private readonly IShopLogic _shopLogic; + private readonly IWoodStorage _woodStorage; - public OrderLogic(ILogger logger, IOrderStorage orderStorage) + public OrderLogic(IOrderStorage orderStorage, IShopStorage shopStorage, + IShopLogic shopLogic, IWoodStorage woodStorage, ILogger logger) { _logger = logger; _orderStorage = orderStorage; + _shopStorage = shopStorage; + _shopLogic = shopLogic; + _woodStorage = woodStorage; } public List? ReadList(OrderSearchModel? model) @@ -60,6 +68,20 @@ namespace CarpentryWorkshopBusinessLogic.BusinessLogics _logger.LogWarning("Status change operation failed"); throw new InvalidOperationException("Текущий статус заказа не может быть переведен в выбранный"); } + if (element.Status == OrderStatus.Готов) + { + var wood = _woodStorage.GetElement(new WoodSearchModel() { Id = model.WoodId }); + if (wood == null) + { + _logger.LogWarning("Status update to " + status.ToString() + " operation failed. Document not found."); + return false; + } + if (CheckSupply(wood, 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); @@ -81,8 +103,66 @@ namespace CarpentryWorkshopBusinessLogic.BusinessLogics return ChangeStatus(model, OrderStatus.Выдан); } - private void CheckModel(OrderBindingModel model, bool withParams = -true) + public bool CheckSupply(IWoodModel wood, int count) + { + if (count <= 0) + { + _logger.LogWarning("Check then supply operation error. Wood count < 0."); + return false; + } + + int sumCapacity = 0; + int sumCount = 0; + sumCapacity = _shopStorage.GetFullList().Select(x => x.WoodMaxCount).Sum(); + sumCount = _shopStorage.GetFullList().Select(x => x.ShopWoods.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 Wood in shops."); + return false; + } + + foreach (var shop in _shopStorage.GetFullList()) + { + freeSpace = shop.WoodMaxCount; + foreach (var doc in shop.ShopWoods) + { + freeSpace -= doc.Value.Item2; + } + if (freeSpace == 0) + { + continue; + } + if (freeSpace - count >= 0) + { + if (_shopLogic.MakeSupply(new() { Id = shop.Id }, wood, count)) + count = 0; + else + { + _logger.LogWarning("Supply error"); + return false; + } + } + if (freeSpace - count < 0) + { + if (_shopLogic.MakeSupply(new() { Id = shop.Id }, wood, freeSpace)) + count -= freeSpace; + else + { + _logger.LogWarning("Supply error"); + return false; + } + } + if (count <= 0) + { + return true; + } + } + return false; + } + + private void CheckModel(OrderBindingModel model, bool withParams = true) { if (model == null) { diff --git a/CarpentryWorkshop/CarpentryWorkshopBusinessLogic/BusinessLogics/ShopLogic.cs b/CarpentryWorkshop/CarpentryWorkshopBusinessLogic/BusinessLogics/ShopLogic.cs new file mode 100644 index 0000000..1499e2c --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopBusinessLogic/BusinessLogics/ShopLogic.cs @@ -0,0 +1,170 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.BusinessLogicsContracts; +using CarpentryWorkshopContracts.SearchModels; +using CarpentryWorkshopContracts.StoragesContracts; +using CarpentryWorkshopContracts.ViewModels; +using CarpentryWorkshopDataModels.Models; +using Microsoft.Extensions.Logging; + +namespace CarpentryWorkshopBusinessLogic.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?.ShopName, 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, IWoodModel wood, int count) + { + + if (model == null) + throw new ArgumentNullException(nameof(model)); + if (wood == null) + throw new ArgumentNullException(nameof(wood)); + if (count <= 0) + throw new ArgumentNullException("Количество должно быть положительным числом"); + + ShopViewModel curModel = _shopStorage.GetElement(model); + if (curModel == null) + throw new ArgumentNullException(nameof(curModel)); + var countItems = curModel.ShopWoods.Select(x => x.Value.Item2).Sum(); + if (curModel.WoodMaxCount - countItems >= count) + { + if (curModel.ShopWoods.TryGetValue(wood.Id, out var sameDocument)) + { + curModel.ShopWoods[wood.Id] = (wood, sameDocument.Item2 + count); + _logger.LogInformation("Same wood found by supply. Added {0} of {1} in {2} shop", count, wood.WoodName, curModel.ShopName); + } + else + { + curModel.ShopWoods[wood.Id] = (wood, count); + _logger.LogInformation("New wood added by supply. Added {0} of {1} in {2} shop", count, wood.WoodName, curModel.ShopName); + } + _shopStorage.Update(new() + { + Id = curModel.Id, + ShopName = curModel.ShopName, + Address = curModel.Address, + DateOpen = curModel.DateOpen, + ShopWoods = curModel.ShopWoods, + WoodMaxCount = curModel.WoodMaxCount + }); + } + else + { + _logger.LogWarning("Required shop is overflowed"); + return false; + } + return true; + } + + public bool MakeSell(IWoodModel wood, int count) + { + return _shopStorage.SellWoods(wood, count); + } + + public ShopViewModel ReadElement(ShopSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + _logger.LogInformation("ReadElement. ShopName:{ShopName}.Id:{ Id}", model.ShopName, 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.ShopName)); + } + if (model.DateOpen == null) + { + throw new ArgumentNullException("Нет даты открытия магазина", nameof(model.ShopName)); + } + _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 + { + ShopName = model.ShopName + }); + if (element != null && element.Id != model.Id) + { + throw new InvalidOperationException("Магазин с таким названием уже есть"); + } + } + + } +} diff --git a/CarpentryWorkshop/CarpentryWorkshopContracts/BindingModels/ShopBindingModel.cs b/CarpentryWorkshop/CarpentryWorkshopContracts/BindingModels/ShopBindingModel.cs new file mode 100644 index 0000000..1ca3279 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopContracts/BindingModels/ShopBindingModel.cs @@ -0,0 +1,14 @@ +using CarpentryWorkshopDataModels.Models; + +namespace CarpentryWorkshopContracts.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 Dictionary ShopWoods { get; set; } = new(); + public int WoodMaxCount { get; set; } + } +} diff --git a/CarpentryWorkshop/CarpentryWorkshopContracts/BindingModels/SupplyBindingModel .cs b/CarpentryWorkshop/CarpentryWorkshopContracts/BindingModels/SupplyBindingModel .cs new file mode 100644 index 0000000..d824da7 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopContracts/BindingModels/SupplyBindingModel .cs @@ -0,0 +1,11 @@ +using CarpentryWorkshopDataModels.Models; + +namespace CarpentryWorkshopContracts.BindingModels +{ + public class SupplyBindingModel : ISupplyModel + { + public int ShopId { get; set; } + public int WoodId { get; set; } + public int Count { get; set; } + } +} diff --git a/CarpentryWorkshop/CarpentryWorkshopContracts/BusinessLogicsContracts/IShopLogic.cs b/CarpentryWorkshop/CarpentryWorkshopContracts/BusinessLogicsContracts/IShopLogic.cs new file mode 100644 index 0000000..f223e12 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopContracts/BusinessLogicsContracts/IShopLogic.cs @@ -0,0 +1,18 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.SearchModels; +using CarpentryWorkshopContracts.ViewModels; +using CarpentryWorkshopDataModels.Models; + +namespace CarpentryWorkshopContracts.BusinessLogicsContracts +{ + 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, IWoodModel wood, int count); + bool MakeSell(IWoodModel wood, int count); + } +} diff --git a/CarpentryWorkshop/CarpentryWorkshopContracts/SearchModels/ShopSearchModel.cs b/CarpentryWorkshop/CarpentryWorkshopContracts/SearchModels/ShopSearchModel.cs new file mode 100644 index 0000000..71d0ee2 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopContracts/SearchModels/ShopSearchModel.cs @@ -0,0 +1,8 @@ +namespace CarpentryWorkshopContracts.SearchModels +{ + public class ShopSearchModel + { + public int? Id { get; set; } + public string? ShopName { get; set; } + } +} diff --git a/CarpentryWorkshop/CarpentryWorkshopContracts/SearchModels/SupplySearchModel.cs b/CarpentryWorkshop/CarpentryWorkshopContracts/SearchModels/SupplySearchModel.cs new file mode 100644 index 0000000..27b4eeb --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopContracts/SearchModels/SupplySearchModel.cs @@ -0,0 +1,8 @@ +namespace CarpentryWorkshopContracts.SearchModels +{ + public class SupplySearchModel + { + public int? WoodId { get; set; } + public int? Count { get; set; } + } +} diff --git a/CarpentryWorkshop/CarpentryWorkshopContracts/StoragesContracts/IShopStorage.cs b/CarpentryWorkshop/CarpentryWorkshopContracts/StoragesContracts/IShopStorage.cs new file mode 100644 index 0000000..2ff6ee3 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopContracts/StoragesContracts/IShopStorage.cs @@ -0,0 +1,23 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.SearchModels; +using CarpentryWorkshopContracts.ViewModels; +using CarpentryWorkshopDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CarpentryWorkshopContracts.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 SellWoods(IWoodModel model, int count); + } +} diff --git a/CarpentryWorkshop/CarpentryWorkshopContracts/ViewModels/ShopViewModel.cs b/CarpentryWorkshop/CarpentryWorkshopContracts/ViewModels/ShopViewModel.cs new file mode 100644 index 0000000..ec8eed1 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopContracts/ViewModels/ShopViewModel.cs @@ -0,0 +1,19 @@ +using CarpentryWorkshopDataModels.Models; +using System.ComponentModel; + +namespace CarpentryWorkshopContracts.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; } + public Dictionary ShopWoods { get; set; } = new(); + [DisplayName("Вместимость")] + public int WoodMaxCount { get; set; } + } +} diff --git a/CarpentryWorkshop/CarpentryWorkshopDataModels/Models/IShopModel.cs b/CarpentryWorkshop/CarpentryWorkshopDataModels/Models/IShopModel.cs new file mode 100644 index 0000000..b6a8824 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopDataModels/Models/IShopModel.cs @@ -0,0 +1,11 @@ +namespace CarpentryWorkshopDataModels.Models +{ + public interface IShopModel : IId + { + string ShopName { get; } + string Address { get; } + DateTime DateOpen { get; } + Dictionary ShopWoods { get; } + public int WoodMaxCount { get; } + } +} diff --git a/CarpentryWorkshop/CarpentryWorkshopDataModels/Models/ISupplyModel.cs b/CarpentryWorkshop/CarpentryWorkshopDataModels/Models/ISupplyModel.cs new file mode 100644 index 0000000..8d0e414 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopDataModels/Models/ISupplyModel.cs @@ -0,0 +1,9 @@ +namespace CarpentryWorkshopDataModels.Models +{ + public interface ISupplyModel + { + int ShopId { get; } + int WoodId { get; } + int Count { get; } + } +} diff --git a/CarpentryWorkshop/CarpentryWorkshopFileImplement/DataFileSingleton.cs b/CarpentryWorkshop/CarpentryWorkshopFileImplement/DataFileSingleton.cs index 3d9819c..87c458e 100644 --- a/CarpentryWorkshop/CarpentryWorkshopFileImplement/DataFileSingleton.cs +++ b/CarpentryWorkshop/CarpentryWorkshopFileImplement/DataFileSingleton.cs @@ -9,9 +9,11 @@ namespace CarpentryWorkshopFileImplement private readonly string ComponentFileName = "Component.xml"; private readonly string OrderFileName = "Order.xml"; private readonly string WoodFileName = "Wood.xml"; + private readonly string ShopFileName = "Shop.xml"; public List Components { get; private set; } public List Orders { get; private set; } public List Woods { get; private set; } + public List Shops { get; private set; } public static DataFileSingleton GetInstance() { if (instance == null) @@ -26,6 +28,8 @@ namespace CarpentryWorkshopFileImplement "Woods", 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 => @@ -34,6 +38,8 @@ namespace CarpentryWorkshopFileImplement Wood.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/CarpentryWorkshop/CarpentryWorkshopFileImplement/Implements/OrderStorage.cs b/CarpentryWorkshop/CarpentryWorkshopFileImplement/Implements/OrderStorage.cs index 2befeac..533e58b 100644 --- a/CarpentryWorkshop/CarpentryWorkshopFileImplement/Implements/OrderStorage.cs +++ b/CarpentryWorkshop/CarpentryWorkshopFileImplement/Implements/OrderStorage.cs @@ -78,14 +78,10 @@ namespace CarpentryWorkshopFileImplement.Implements { if (model == null) return null; - foreach (var wood in source.Woods) - { - if (wood.Id == model.WoodId) - { - model.WoodName = wood.WoodName; - break; - } - } + var wood = source.Woods.FirstOrDefault(x => (x.Id == model.WoodId)); + if (wood == null) + return model; + model.WoodName = wood.WoodName; return model; } } diff --git a/CarpentryWorkshop/CarpentryWorkshopFileImplement/Implements/ShopStorage.cs b/CarpentryWorkshop/CarpentryWorkshopFileImplement/Implements/ShopStorage.cs new file mode 100644 index 0000000..6733450 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopFileImplement/Implements/ShopStorage.cs @@ -0,0 +1,127 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.SearchModels; +using CarpentryWorkshopContracts.StoragesContracts; +using CarpentryWorkshopContracts.ViewModels; +using CarpentryWorkshopDataModels.Models; +using CarpentryWorkshopFileImplement.Models; + +namespace CarpentryWorkshopFileImplement.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.ShopName)) + { + return new(); + } + return source.Shops.Where(x => x.ShopName.Contains(model.ShopName)).Select(x => x.GetViewModel).ToList(); + } + public ShopViewModel? GetElement(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.ShopName) && !model.Id.HasValue) + { + return null; + } + return source.Shops.FirstOrDefault(x => + (!string.IsNullOrEmpty(model.ShopName) && x.ShopName == model.ShopName) || + (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 shop = source.Shops.FirstOrDefault(x => x.Id == model.Id); + if (shop == null) + { + return null; + } + shop.Update(model); + source.SaveShops(); + return shop.GetViewModel; + } + + public ShopViewModel? Delete(ShopBindingModel model) + { + var shop = source.Shops.FirstOrDefault(x => x.Id == model.Id); + if (shop != null) + { + source.Shops.Remove(shop); + source.SaveShops(); + return shop.GetViewModel; + } + return null; + } + + public bool CheckAvailability(int woodId, int count) + { + int minus = source.Shops.Select(x => x.ShopWoods.Select(y => (y.Value.Item1.Id == woodId ? y.Value.Item2 : 0)).Sum()).Sum(); + count -= minus; + return count <= 0; + } + + public bool SellWoods(IWoodModel model, int count) + { + var wood = source.Woods.FirstOrDefault(x => x.Id == model.Id); + + if (wood == null || !CheckAvailability(wood.Id, count)) + { + return false; + } + + for (int i = 0; i < source.Shops.Count; i++) + { + var shop = source.Shops[i]; + var woods = shop.ShopWoods; + + foreach (var wod in woods.Where(x => x.Value.Item1.Id == wood.Id)) + { + var min = Math.Min(wod.Value.Item2, count); + woods[wod.Value.Item1.Id] = (wod.Value.Item1, wod.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, + WoodMaxCount = shop.WoodMaxCount, + ShopWoods = woods + }); + } + source.SaveShops(); + return true; + } + } +} diff --git a/CarpentryWorkshop/CarpentryWorkshopFileImplement/Models/Shop.cs b/CarpentryWorkshop/CarpentryWorkshopFileImplement/Models/Shop.cs new file mode 100644 index 0000000..6a19218 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopFileImplement/Models/Shop.cs @@ -0,0 +1,103 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.ViewModels; +using CarpentryWorkshopDataModels.Models; +using System.Xml.Linq; + +namespace CarpentryWorkshopFileImplement.Models +{ + public class Shop : IShopModel + { + public int Id { get; private set; } + public string ShopName { get; private set; } = string.Empty; + public string Address { get; private set; } = string.Empty; + public DateTime DateOpen { get; private set; } + public Dictionary Woods { get; private set; } = new(); + private Dictionary? _shopWoods = null; + + public Dictionary ShopWoods + { + get + { + if (_shopWoods == null) + { + var source = DataFileSingleton.GetInstance(); + _shopWoods = Woods.ToDictionary(x => x.Key, + y => ((source.Woods.FirstOrDefault(z => z.Id == y.Key) as IWoodModel)!, y.Value)); + } + return _shopWoods; + } + } + + public int WoodMaxCount { get; private set; } + + 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, + Woods = model.ShopWoods.ToDictionary(x => x.Key, x => x.Value.Item2), + WoodMaxCount = model.WoodMaxCount + }; + } + + 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, + DateOpen = Convert.ToDateTime(element.Element("DateOpen")!.Value), + WoodMaxCount = Convert.ToInt32(element.Element("WoodMaxCount")!.Value), + Woods = element.Element("ShopWoods")!.Elements("ShopWood") + .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; + WoodMaxCount = model.WoodMaxCount; + Woods = model.ShopWoods.ToDictionary(x => x.Key, x => x.Value.Item2); + _shopWoods = null; + } + + public ShopViewModel GetViewModel => new() + { + Id = Id, + ShopName = ShopName, + Address = Address, + DateOpen = DateOpen, + ShopWoods = ShopWoods, + WoodMaxCount = WoodMaxCount + }; + + public XElement GetXElement => new("Shop", + new XAttribute("Id", Id), + new XElement("ShopName", ShopName), + new XElement("Address", Address), + new XElement("DateOpen", DateOpen.ToString()), + new XElement("WoodMaxCount", WoodMaxCount.ToString()), + new XElement("ShopWoods", + Woods.Select(x => new XElement("ShopWood", + new XElement("Key", x.Key), + new XElement("Value", x.Value))).ToArray())); + } +} diff --git a/CarpentryWorkshop/CarpentryWorkshopListImplement/DataListSingleton.cs b/CarpentryWorkshop/CarpentryWorkshopListImplement/DataListSingleton.cs index 9813b2a..1d3857e 100644 --- a/CarpentryWorkshop/CarpentryWorkshopListImplement/DataListSingleton.cs +++ b/CarpentryWorkshop/CarpentryWorkshopListImplement/DataListSingleton.cs @@ -8,11 +8,13 @@ namespace CarpentryWorkshopListImplement public List Components { get; set; } public List Orders { get; set; } public List Woods { get; set; } + public List Shops { get; set; } private DataListSingleton() { Components = new List(); Orders = new List(); Woods = new List(); + Shops = new List(); } public static DataListSingleton GetInstance() { diff --git a/CarpentryWorkshop/CarpentryWorkshopListImplement/Implements/ShopStorage.cs b/CarpentryWorkshop/CarpentryWorkshopListImplement/Implements/ShopStorage.cs new file mode 100644 index 0000000..586314c --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopListImplement/Implements/ShopStorage.cs @@ -0,0 +1,149 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.SearchModels; +using CarpentryWorkshopContracts.StoragesContracts; +using CarpentryWorkshopContracts.ViewModels; +using CarpentryWorkshopDataModels.Models; +using CarpentryWorkshopListImplement.Models; + +namespace CarpentryWorkshopListImplement.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.ShopName)) + { + return result; + } + foreach (var shop in _source.Shops) + { + if (shop.ShopName.Contains(model.ShopName)) + { + result.Add(shop.GetViewModel); + } + } + return result; + } + public ShopViewModel? GetElement(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.ShopName) && !model.Id.HasValue) + { + return null; + } + foreach (var shop in _source.Shops) + { + if ((!string.IsNullOrEmpty(model.ShopName) && + shop.ShopName == model.ShopName) || + (model.Id.HasValue && shop.Id == model.Id)) + { + return shop.GetViewModel; + } + } + return null; + } + public ShopViewModel? Insert(ShopBindingModel model) + { + model.Id = 1; + foreach (var shop in _source.Shops) + { + if (model.Id <= shop.Id) + { + model.Id = shop.Id + 1; + } + } + var newShop = Shop.Create(model); + if (newShop == null) + { + return null; + } + _source.Shops.Add(newShop); + return newShop.GetViewModel; + } + public ShopViewModel? Update(ShopBindingModel model) + { + foreach (var shop in _source.Shops) + { + if (shop.Id == model.Id) + { + shop.Update(model); + return shop.GetViewModel; + } + } + return null; + } + public ShopViewModel? Delete(ShopBindingModel model) + { + for (int i = 0; i < _source.Shops.Count; ++i) + { + if (_source.Shops[i].Id == model.Id) + { + var element = _source.Shops[i]; + _source.Shops.RemoveAt(i); + return element.GetViewModel; + } + } + return null; + } + public bool CheckAvailability(int woodId, int count) + { + int minus = _source.Shops.Select(x => x.ShopWoods.Select(y => (y.Value.Item1.Id == woodId ? y.Value.Item2 : 0)).Sum()).Sum(); + count -= minus; + return count <= 0; + } + + public bool SellWoods(IWoodModel model, int count) + { + var wood = _source.Woods.FirstOrDefault(x => x.Id == model.Id); + + if (wood == null || !CheckAvailability(wood.Id, count)) + { + return false; + } + + for (int i = 0; i < _source.Shops.Count; i++) + { + var shop = _source.Shops[i]; + var woods = shop.ShopWoods; + + foreach (var wod in woods.Where(x => x.Value.Item1.Id == wood.Id)) + { + var min = Math.Min(wod.Value.Item2, count); + woods[wod.Value.Item1.Id] = (wod.Value.Item1, wod.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, + WoodMaxCount = shop.WoodMaxCount, + ShopWoods = woods + }); + } + return true; + } + } +} diff --git a/CarpentryWorkshop/CarpentryWorkshopListImplement/Models/Shop.cs b/CarpentryWorkshop/CarpentryWorkshopListImplement/Models/Shop.cs new file mode 100644 index 0000000..c14e7b6 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopListImplement/Models/Shop.cs @@ -0,0 +1,56 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.ViewModels; +using CarpentryWorkshopDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CarpentryWorkshopListImplement.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 WoodMaxCount { get; private set; } + public Dictionary ShopWoods { 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, + ShopWoods = new() + }; + } + + public void Update(ShopBindingModel? model) + { + if (model == null) + { + return; + } + ShopName = model.ShopName; + Address = model.Address; + DateOpen = model.DateOpen; + ShopWoods = model.ShopWoods; + } + + public ShopViewModel GetViewModel => new() + { + Id = Id, + ShopName = ShopName, + Address = Address, + DateOpen = DateOpen, + ShopWoods = ShopWoods + }; + } +}