diff --git a/PrecastConcretePlant/PrecastConcretePlant/FormMain.Designer.cs b/PrecastConcretePlant/PrecastConcretePlant/FormMain.Designer.cs index 58f7f6f..5f4a91f 100644 --- a/PrecastConcretePlant/PrecastConcretePlant/FormMain.Designer.cs +++ b/PrecastConcretePlant/PrecastConcretePlant/FormMain.Designer.cs @@ -32,6 +32,7 @@ this.СправочникиToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.ИзделияToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.КомпонентыToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.магазиныToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.отчетыToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.списокДокументовToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.компонентыПоДокументамToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); @@ -42,6 +43,8 @@ this.OrderReadyButton = new System.Windows.Forms.Button(); this.IssuedOrderButton = new System.Windows.Forms.Button(); this.UpdateListButton = new System.Windows.Forms.Button(); + this.ButtonAddReinforcedInShop = new System.Windows.Forms.Button(); + this.SellReinforcedButton = new System.Windows.Forms.Button(); this.MenuStrip.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.DataGridView)).BeginInit(); this.SuspendLayout(); @@ -63,7 +66,8 @@ // this.СправочникиToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.ИзделияToolStripMenuItem, - this.КомпонентыToolStripMenuItem}); + this.КомпонентыToolStripMenuItem, + this.магазиныToolStripMenuItem}); this.СправочникиToolStripMenuItem.Name = "СправочникиToolStripMenuItem"; this.СправочникиToolStripMenuItem.Size = new System.Drawing.Size(117, 24); this.СправочникиToolStripMenuItem.Text = "Cправочники"; @@ -72,12 +76,14 @@ // this.ИзделияToolStripMenuItem.Name = "ИзделияToolStripMenuItem"; this.ИзделияToolStripMenuItem.Size = new System.Drawing.Size(182, 26); + this.ИзделияToolStripMenuItem.Size = new System.Drawing.Size(145, 22); this.ИзделияToolStripMenuItem.Text = "Изделия"; this.ИзделияToolStripMenuItem.Click += new System.EventHandler(this.ИзделияToolStripMenuItem_Click); // // КомпонентыToolStripMenuItem // this.КомпонентыToolStripMenuItem.Name = "КомпонентыToolStripMenuItem"; + this.КомпонентыToolStripMenuItem.Size = new System.Drawing.Size(145, 22); this.КомпонентыToolStripMenuItem.Size = new System.Drawing.Size(182, 26); this.КомпонентыToolStripMenuItem.Text = "Компоненты"; this.КомпонентыToolStripMenuItem.Click += new System.EventHandler(this.КомпонентыToolStripMenuItem_Click); @@ -179,11 +185,31 @@ this.UpdateListButton.UseVisualStyleBackColor = true; this.UpdateListButton.Click += new System.EventHandler(this.UpdateListButton_Click); // + // ButtonAddReinforcedInShop + // + this.ButtonAddReinforcedInShop.Location = new System.Drawing.Point(905, 228); + this.ButtonAddReinforcedInShop.Name = "ButtonAddReinforcedInShop"; + this.ButtonAddReinforcedInShop.Size = new System.Drawing.Size(125, 42); + this.ButtonAddReinforcedInShop.TabIndex = 7; + this.ButtonAddReinforcedInShop.Text = "Пополнение магазина"; + this.ButtonAddReinforcedInShop.UseVisualStyleBackColor = true; + this.ButtonAddReinforcedInShop.Click += new System.EventHandler(this.ButtonAddReinforcedInShop_Click); + // + // SellReinforcedButton + // + this.SellReinforcedButton.Location = new System.Drawing.Point(905, 276); + this.SellReinforcedButton.Name = "SellReinforcedButton"; + this.SellReinforcedButton.Size = new System.Drawing.Size(125, 29); + this.SellReinforcedButton.TabIndex = 8; + this.SellReinforcedButton.Text = "Продать изделие"; + this.SellReinforcedButton.UseVisualStyleBackColor = true; + this.SellReinforcedButton.Click += new System.EventHandler(this.SellReinforcedButton_Click); + // // FormMain // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(1191, 600); + this.ClientSize = new System.Drawing.Size(1042, 450); this.Controls.Add(this.UpdateListButton); this.Controls.Add(this.IssuedOrderButton); this.Controls.Add(this.OrderReadyButton); @@ -216,9 +242,5 @@ private Button OrderReadyButton; private Button IssuedOrderButton; private Button UpdateListButton; - private ToolStripMenuItem отчетыToolStripMenuItem; - private ToolStripMenuItem списокДокументовToolStripMenuItem; - private ToolStripMenuItem компонентыПоДокументамToolStripMenuItem; - private ToolStripMenuItem списокЗаказовToolStripMenuItem; } } \ No newline at end of file diff --git a/PrecastConcretePlant/PrecastConcretePlant/FormMain.cs b/PrecastConcretePlant/PrecastConcretePlant/FormMain.cs index 27bd923..f4e4232 100644 --- a/PrecastConcretePlant/PrecastConcretePlant/FormMain.cs +++ b/PrecastConcretePlant/PrecastConcretePlant/FormMain.cs @@ -1,4 +1,5 @@ -using Microsoft.Extensions.Logging; + +using Microsoft.Extensions.Logging; using PrecastConcretePlantBusinessLogic.BusinessLogic; using PrecastConcretePlantContracts.BindingModels; using PrecastConcretePlantContracts.BusinessLogicsContracts; @@ -169,7 +170,7 @@ namespace PrecastConcretePlantView try { var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel - { + { Id = id, ReinforcedId = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["ReinforcedId"].Value), ReinforcedName = DataGridView.SelectedRows[0].Cells["ReinforcedName"].Value.ToString(), @@ -200,6 +201,34 @@ namespace PrecastConcretePlantView LoadData(); } + private void ButtonAddReinforcedInShop_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReinforcedShop)); + if (service is FormReinforcedShop form) + { + form.ShowDialog(); + } + } + + private void магазиныToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormShops)); + if (service is FormShops form) + { + form.ShowDialog(); + } + } + + private void SellReinforcedButton_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormSellReinforced)); + + if (service is FormSellReinforced form) + { + form.ShowDialog(); + } + } + private void списокДокументовToolStripMenuItem_Click(object sender, EventArgs e) { using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; diff --git a/PrecastConcretePlant/PrecastConcretePlant/FormReinforcedShop.Designer.cs b/PrecastConcretePlant/PrecastConcretePlant/FormReinforcedShop.Designer.cs new file mode 100644 index 0000000..ece5061 --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlant/FormReinforcedShop.Designer.cs @@ -0,0 +1,151 @@ +namespace PrecastConcretePlantView +{ + partial class FormReinforcedShop + { + /// + /// 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() + { + this.comboBoxShop = new System.Windows.Forms.ComboBox(); + this.label1 = new System.Windows.Forms.Label(); + this.label2 = new System.Windows.Forms.Label(); + this.label3 = new System.Windows.Forms.Label(); + this.comboBoxReinforced = new System.Windows.Forms.ComboBox(); + this.numericUpDownCount = new System.Windows.Forms.NumericUpDown(); + this.buttonSave = new System.Windows.Forms.Button(); + this.buttonCancel = new System.Windows.Forms.Button(); + ((System.ComponentModel.ISupportInitialize)(this.numericUpDownCount)).BeginInit(); + this.SuspendLayout(); + // + // comboBoxShop + // + this.comboBoxShop.FormattingEnabled = true; + this.comboBoxShop.Location = new System.Drawing.Point(214, 17); + this.comboBoxShop.Name = "comboBoxShop"; + this.comboBoxShop.Size = new System.Drawing.Size(222, 23); + this.comboBoxShop.TabIndex = 3; + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(84, 20); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(124, 15); + this.label1.TabIndex = 2; + this.label1.Text = "Выбранный магазин:"; + // + // label2 + // + this.label2.AutoSize = true; + this.label2.Location = new System.Drawing.Point(12, 47); + this.label2.Name = "label2"; + this.label2.Size = new System.Drawing.Size(196, 15); + this.label2.TabIndex = 4; + this.label2.Text = "Изделие которое нужно добавить:"; + // + // label3 + // + this.label3.AutoSize = true; + this.label3.Location = new System.Drawing.Point(133, 73); + this.label3.Name = "label3"; + this.label3.Size = new System.Drawing.Size(75, 15); + this.label3.TabIndex = 5; + this.label3.Text = "Количество:"; + // + // comboBoxReinforced + // + this.comboBoxReinforced.FormattingEnabled = true; + this.comboBoxReinforced.Location = new System.Drawing.Point(214, 44); + this.comboBoxReinforced.Name = "comboBoxReinforced"; + this.comboBoxReinforced.Size = new System.Drawing.Size(222, 23); + this.comboBoxReinforced.TabIndex = 6; + // + // numericUpDownCount + // + this.numericUpDownCount.Location = new System.Drawing.Point(215, 71); + this.numericUpDownCount.Maximum = new decimal(new int[] { + 1410065408, + 2, + 0, + 0}); + this.numericUpDownCount.Name = "numericUpDownCount"; + this.numericUpDownCount.Size = new System.Drawing.Size(221, 23); + this.numericUpDownCount.TabIndex = 7; + // + // buttonSave + // + this.buttonSave.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); + this.buttonSave.Location = new System.Drawing.Point(280, 123); + this.buttonSave.Name = "buttonSave"; + this.buttonSave.Size = new System.Drawing.Size(75, 23); + this.buttonSave.TabIndex = 8; + this.buttonSave.Text = "Сохранить"; + this.buttonSave.UseVisualStyleBackColor = true; + this.buttonSave.Click += new System.EventHandler(this.ButtonSave_Click); + // + // buttonCancel + // + this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); + this.buttonCancel.Location = new System.Drawing.Point(361, 123); + this.buttonCancel.Name = "buttonCancel"; + this.buttonCancel.Size = new System.Drawing.Size(75, 23); + this.buttonCancel.TabIndex = 9; + this.buttonCancel.Text = "Отмена"; + this.buttonCancel.UseVisualStyleBackColor = true; + this.buttonCancel.Click += new System.EventHandler(this.ButtonCancel_Click); + // + // FormReinforcedShop + // + this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(448, 158); + this.Controls.Add(this.buttonCancel); + this.Controls.Add(this.buttonSave); + this.Controls.Add(this.numericUpDownCount); + this.Controls.Add(this.comboBoxReinforced); + this.Controls.Add(this.label3); + this.Controls.Add(this.label2); + this.Controls.Add(this.comboBoxShop); + this.Controls.Add(this.label1); + this.Name = "FormReinforcedShop"; + this.Text = "Пополнение магазина"; + ((System.ComponentModel.ISupportInitialize)(this.numericUpDownCount)).EndInit(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private ComboBox comboBoxShop; + private Label label1; + private Label label2; + private Label label3; + private ComboBox comboBoxReinforced; + private NumericUpDown numericUpDownCount; + private Button buttonSave; + private Button buttonCancel; + } +} \ No newline at end of file diff --git a/PrecastConcretePlant/PrecastConcretePlant/FormReinforcedShop.cs b/PrecastConcretePlant/PrecastConcretePlant/FormReinforcedShop.cs new file mode 100644 index 0000000..e8122ce --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlant/FormReinforcedShop.cs @@ -0,0 +1,100 @@ +using Microsoft.Extensions.Logging; +using PrecastConcretePlantContracts.BusinessLogicsContracts; +using PrecastConcretePlantContracts.ViewModels; +using System; +using System.Collections; +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 PrecastConcretePlantView +{ + public partial class FormReinforcedShop : Form + { + private readonly ILogger _logger; + private readonly IShopLogic _shopLogic; + private readonly IReinforcedLogic _reinforcedLogic; + private readonly List? _listShops; + private readonly List? _listReinforcedies; + + public FormReinforcedShop(ILogger logger, IShopLogic shopLogic, IReinforcedLogic reinforcedLogic) + { + InitializeComponent(); + _shopLogic = shopLogic; + _reinforcedLogic = reinforcedLogic; + _logger = logger; + _listShops = shopLogic.ReadList(null); + if (_listShops != null) + { + comboBoxShop.DisplayMember = "Name"; + comboBoxShop.ValueMember = "Id"; + comboBoxShop.DataSource = _listShops; + comboBoxShop.SelectedItem = null; + } + + _listReinforcedies = reinforcedLogic.ReadList(null); + if (_listReinforcedies != null) + { + comboBoxReinforced.DisplayMember = "ReinforcedName"; + comboBoxReinforced.ValueMember= "Id"; + comboBoxReinforced.DataSource = _listReinforcedies; + comboBoxReinforced.SelectedItem = null; + } + } + + private void ButtonSave_Click(object sender, EventArgs e) + { + if (comboBoxShop.SelectedValue == null) + { + MessageBox.Show("Выберите магазин", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (comboBoxReinforced.SelectedValue == null) + { + MessageBox.Show("Выберите изделие", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Добавление изделия в магазин"); + try + { + var reinforced = _reinforcedLogic.ReadElement(new() + { + Id = (int)comboBoxReinforced.SelectedValue + }); + if (reinforced == null) + { + throw new Exception("Не найдено изделие. Дополнительная информация в логах."); + } + var resultOperation = _shopLogic.AddReinforced( + model: new() { Id = (int)comboBoxShop.SelectedValue }, + reinforced: reinforced, + count: (int)numericUpDownCount.Value + ); + if (!resultOperation) + { + throw new Exception("Ошибка при добавлении. Дополнительная информация в логах."); + } + MessageBox.Show("Сохранение прошло успешно", "Сообщение", + MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + Close(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка сохранения изделия"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ButtonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } +} diff --git a/PrecastConcretePlant/PrecastConcretePlant/FormReinforcedShop.resx b/PrecastConcretePlant/PrecastConcretePlant/FormReinforcedShop.resx new file mode 100644 index 0000000..f298a7b --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlant/FormReinforcedShop.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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/PrecastConcretePlant/PrecastConcretePlant/FormSellReinforced.Designer.cs b/PrecastConcretePlant/PrecastConcretePlant/FormSellReinforced.Designer.cs new file mode 100644 index 0000000..4326b57 --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlant/FormSellReinforced.Designer.cs @@ -0,0 +1,125 @@ +namespace PrecastConcretePlantView +{ + partial class FormSellReinforced + { + /// + /// 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() + { + this.ReinforcedLabel = new System.Windows.Forms.Label(); + this.QuantityLabel = new System.Windows.Forms.Label(); + this.ReindorcedСomboBox = new System.Windows.Forms.ComboBox(); + this.SaveButton = new System.Windows.Forms.Button(); + this.ButtonCancel = new System.Windows.Forms.Button(); + this.numericUpDownCount = new System.Windows.Forms.NumericUpDown(); + ((System.ComponentModel.ISupportInitialize)(this.numericUpDownCount)).BeginInit(); + this.SuspendLayout(); + // + // ReinforcedLabel + // + this.ReinforcedLabel.AutoSize = true; + this.ReinforcedLabel.Location = new System.Drawing.Point(14, 24); + this.ReinforcedLabel.Name = "ReinforcedLabel"; + this.ReinforcedLabel.Size = new System.Drawing.Size(71, 20); + this.ReinforcedLabel.TabIndex = 0; + this.ReinforcedLabel.Text = "Изделие:"; + // + // QuantityLabel + // + this.QuantityLabel.AutoSize = true; + this.QuantityLabel.Location = new System.Drawing.Point(14, 68); + this.QuantityLabel.Name = "QuantityLabel"; + this.QuantityLabel.Size = new System.Drawing.Size(93, 20); + this.QuantityLabel.TabIndex = 1; + this.QuantityLabel.Text = "Количество:"; + // + // ReindorcedСomboBox + // + this.ReindorcedСomboBox.FormattingEnabled = true; + this.ReindorcedСomboBox.Location = new System.Drawing.Point(101, 20); + this.ReindorcedСomboBox.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); + this.ReindorcedСomboBox.Name = "ReindorcedСomboBox"; + this.ReindorcedСomboBox.Size = new System.Drawing.Size(210, 28); + this.ReindorcedСomboBox.TabIndex = 2; + // + // SaveButton + // + this.SaveButton.Location = new System.Drawing.Point(82, 133); + this.SaveButton.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); + this.SaveButton.Name = "SaveButton"; + this.SaveButton.Size = new System.Drawing.Size(111, 39); + this.SaveButton.TabIndex = 4; + this.SaveButton.Text = "Сохранить"; + this.SaveButton.UseVisualStyleBackColor = true; + this.SaveButton.Click += new System.EventHandler(this.SaveButton_Click); + // + // ButtonCancel + // + this.ButtonCancel.Location = new System.Drawing.Point(200, 133); + this.ButtonCancel.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); + this.ButtonCancel.Name = "ButtonCancel"; + this.ButtonCancel.Size = new System.Drawing.Size(111, 39); + this.ButtonCancel.TabIndex = 5; + this.ButtonCancel.Text = "Отмена"; + this.ButtonCancel.UseVisualStyleBackColor = true; + this.ButtonCancel.Click += new System.EventHandler(this.ButtonCancel_Click); + // + // numericUpDownCount + // + this.numericUpDownCount.Location = new System.Drawing.Point(113, 68); + this.numericUpDownCount.Name = "numericUpDownCount"; + this.numericUpDownCount.Size = new System.Drawing.Size(198, 27); + this.numericUpDownCount.TabIndex = 7; + // + // FormSellReinforced + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(325, 188); + this.Controls.Add(this.numericUpDownCount); + this.Controls.Add(this.ButtonCancel); + this.Controls.Add(this.SaveButton); + this.Controls.Add(this.ReindorcedСomboBox); + this.Controls.Add(this.QuantityLabel); + this.Controls.Add(this.ReinforcedLabel); + this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); + this.Name = "FormSellReinforced"; + this.Text = "Продать Изделие"; + ((System.ComponentModel.ISupportInitialize)(this.numericUpDownCount)).EndInit(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private Label ReinforcedLabel; + private Label QuantityLabel; + private ComboBox ReindorcedСomboBox; + private Button SaveButton; + private Button ButtonCancel; + private NumericUpDown numericUpDownCount; + } +} \ No newline at end of file diff --git a/PrecastConcretePlant/PrecastConcretePlant/FormSellReinforced.cs b/PrecastConcretePlant/PrecastConcretePlant/FormSellReinforced.cs new file mode 100644 index 0000000..f814ce2 --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlant/FormSellReinforced.cs @@ -0,0 +1,97 @@ +using Microsoft.Extensions.Logging; +using PrecastConcretePlantBusinessLogic.BusinessLogic; +using PrecastConcretePlantContracts.BusinessLogicsContracts; +using PrecastConcretePlantContracts.SearchModels; + +namespace PrecastConcretePlantView +{ + public partial class FormSellReinforced : Form + { + private readonly ILogger _logger; + private readonly IReinforcedLogic _logicReinforced; + private readonly IShopLogic _logicShop; + public FormSellReinforced(ILogger logger, IReinforcedLogic logicReinforced, IShopLogic logicShop) + { + InitializeComponent(); + _logger = logger; + _logicReinforced = logicReinforced; + _logicShop = logicShop; + LoadData(); + } + + private void FormSellReinforced_Load(object sender, EventArgs e) + { + LoadData(); + } + + private void LoadData() + { + _logger.LogInformation("Loading reinforcediss for sale."); + + try + { + var list = _logicReinforced.ReadList(null); + if (list != null) + { + ReindorcedСomboBox.DisplayMember = "ReinforcedName"; + ReindorcedСomboBox.ValueMember = "Id"; + ReindorcedСomboBox.DataSource = list; + ReindorcedСomboBox.SelectedItem = null; + } + } + catch (Exception ex) + { + _logger.LogError(ex, "List loading error."); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void SaveButton_Click(object sender, EventArgs e) + { + if (ReindorcedСomboBox.SelectedValue == null) + { + MessageBox.Show("Выберите изделие", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (string.IsNullOrEmpty(numericUpDownCount.Text)) + { + MessageBox.Show("Заполните количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Продажа изделий"); + try + { + var reinforced = _logicReinforced.ReadElement(new() + { + Id = (int)ReindorcedСomboBox.SelectedValue + }); + if (reinforced == null) + { + throw new Exception("Изделие не найдено. Дополнительная информация в логах."); + } + var operationResult = _logicShop.SellReinforced( + reinforced: reinforced, + quantity: (int)numericUpDownCount.Value + ); + if (!operationResult) + { + throw new Exception("Ошибка при продаже изделий. Дополнительная информация в логах."); + } + MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + Close(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка сохранения поездки"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ButtonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } +} diff --git a/PrecastConcretePlant/PrecastConcretePlant/FormSellReinforced.resx b/PrecastConcretePlant/PrecastConcretePlant/FormSellReinforced.resx new file mode 100644 index 0000000..f298a7b --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlant/FormSellReinforced.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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/PrecastConcretePlant/PrecastConcretePlant/FormShop.Designer.cs b/PrecastConcretePlant/PrecastConcretePlant/FormShop.Designer.cs new file mode 100644 index 0000000..00602f5 --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlant/FormShop.Designer.cs @@ -0,0 +1,224 @@ +namespace PrecastConcretePlantView +{ + 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() + { + this.label1 = new System.Windows.Forms.Label(); + this.comboBoxShop = new System.Windows.Forms.ComboBox(); + this.dataGridView = new System.Windows.Forms.DataGridView(); + this.PastryName = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.Price = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.Count = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.label2 = new System.Windows.Forms.Label(); + this.label3 = new System.Windows.Forms.Label(); + this.textBoxAddress = new System.Windows.Forms.TextBox(); + this.buttonCancel = new System.Windows.Forms.Button(); + this.buttonSave = new System.Windows.Forms.Button(); + this.textBoxDateOpening = new System.Windows.Forms.DateTimePicker(); + this.ReinforcedMaxCountLable = new System.Windows.Forms.Label(); + this.VolumeNumericUpDown = new System.Windows.Forms.NumericUpDown(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.VolumeNumericUpDown)).BeginInit(); + this.SuspendLayout(); + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(14, 12); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(150, 20); + this.label1.TabIndex = 0; + this.label1.Text = "Название магазина:"; + // + // comboBoxShop + // + this.comboBoxShop.Location = new System.Drawing.Point(14, 39); + this.comboBoxShop.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); + this.comboBoxShop.Name = "comboBoxShop"; + this.comboBoxShop.Size = new System.Drawing.Size(138, 28); + this.comboBoxShop.TabIndex = 12; + // + // dataGridView + // + this.dataGridView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { + this.PastryName, + this.Price, + this.Count}); + this.dataGridView.Location = new System.Drawing.Point(14, 155); + this.dataGridView.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); + this.dataGridView.Name = "dataGridView"; + this.dataGridView.RowHeadersWidth = 51; + this.dataGridView.RowTemplate.Height = 25; + this.dataGridView.Size = new System.Drawing.Size(666, 332); + this.dataGridView.TabIndex = 2; + // + // PastryName + // + this.PastryName.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; + this.PastryName.HeaderText = "Имя изделия"; + this.PastryName.MinimumWidth = 6; + this.PastryName.Name = "PastryName"; + // + // Price + // + this.Price.HeaderText = "Цена"; + this.Price.MinimumWidth = 6; + this.Price.Name = "Price"; + this.Price.Width = 125; + // + // Count + // + this.Count.HeaderText = "Количество"; + this.Count.MinimumWidth = 6; + this.Count.Name = "Count"; + this.Count.Width = 125; + // + // label2 + // + this.label2.AutoSize = true; + this.label2.Location = new System.Drawing.Point(182, 12); + this.label2.Name = "label2"; + this.label2.Size = new System.Drawing.Size(124, 20); + this.label2.TabIndex = 3; + this.label2.Text = "Адрес магазина:"; + // + // label3 + // + this.label3.AutoSize = true; + this.label3.Location = new System.Drawing.Point(441, 12); + this.label3.Name = "label3"; + this.label3.Size = new System.Drawing.Size(126, 20); + this.label3.TabIndex = 4; + this.label3.Text = "Время открытия:"; + // + // textBoxAddress + // + this.textBoxAddress.Location = new System.Drawing.Point(182, 36); + this.textBoxAddress.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); + this.textBoxAddress.Name = "textBoxAddress"; + this.textBoxAddress.Size = new System.Drawing.Size(252, 27); + this.textBoxAddress.TabIndex = 5; + // + // buttonCancel + // + this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); + this.buttonCancel.Location = new System.Drawing.Point(562, 495); + this.buttonCancel.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); + this.buttonCancel.Name = "buttonCancel"; + this.buttonCancel.Size = new System.Drawing.Size(118, 31); + this.buttonCancel.TabIndex = 7; + this.buttonCancel.Text = "Отмена"; + this.buttonCancel.UseVisualStyleBackColor = true; + this.buttonCancel.Click += new System.EventHandler(this.ButtonCancel_Click); + // + // buttonSave + // + this.buttonSave.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); + this.buttonSave.Location = new System.Drawing.Point(418, 496); + this.buttonSave.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); + this.buttonSave.Name = "buttonSave"; + this.buttonSave.Size = new System.Drawing.Size(137, 29); + this.buttonSave.TabIndex = 8; + this.buttonSave.Text = "Сохранить"; + this.buttonSave.UseVisualStyleBackColor = true; + this.buttonSave.Click += new System.EventHandler(this.ButtonSave_Click); + // + // textBoxDateOpening + // + this.textBoxDateOpening.Location = new System.Drawing.Point(441, 36); + this.textBoxDateOpening.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); + this.textBoxDateOpening.Name = "textBoxDateOpening"; + this.textBoxDateOpening.Size = new System.Drawing.Size(228, 27); + this.textBoxDateOpening.TabIndex = 9; + // + // ReinforcedMaxCountLable + // + this.ReinforcedMaxCountLable.AutoSize = true; + this.ReinforcedMaxCountLable.Location = new System.Drawing.Point(14, 71); + this.ReinforcedMaxCountLable.Name = "ReinforcedMaxCountLable"; + this.ReinforcedMaxCountLable.Size = new System.Drawing.Size(177, 20); + this.ReinforcedMaxCountLable.TabIndex = 10; + this.ReinforcedMaxCountLable.Text = "Вместимость магазина: "; + // + // VolumeNumericUpDown + // + this.VolumeNumericUpDown.Location = new System.Drawing.Point(14, 95); + this.VolumeNumericUpDown.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); + this.VolumeNumericUpDown.Name = "VolumeNumericUpDown"; + this.VolumeNumericUpDown.Size = new System.Drawing.Size(161, 27); + this.VolumeNumericUpDown.TabIndex = 11; + // + // FormShop + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(694, 540); + this.Controls.Add(this.VolumeNumericUpDown); + this.Controls.Add(this.ReinforcedMaxCountLable); + this.Controls.Add(this.textBoxDateOpening); + this.Controls.Add(this.buttonSave); + this.Controls.Add(this.buttonCancel); + this.Controls.Add(this.textBoxAddress); + this.Controls.Add(this.label3); + this.Controls.Add(this.label2); + this.Controls.Add(this.dataGridView); + this.Controls.Add(this.comboBoxShop); + this.Controls.Add(this.label1); + this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); + this.Name = "FormShop"; + this.Text = "Просмотр изделий магазина"; + this.Load += new System.EventHandler(this.FormShop_Load); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.VolumeNumericUpDown)).EndInit(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private Label label1; + private ComboBox comboBoxShop; + private DataGridView dataGridView; + private Label label2; + private Label label3; + private TextBox textBoxAddress; + private Button buttonCancel; + private Button buttonSave; + private DataGridViewTextBoxColumn PastryName; + private DataGridViewTextBoxColumn Price; + private DataGridViewTextBoxColumn Count; + private DateTimePicker textBoxDateOpening; + private Label ReinforcedMaxCountLable; + private NumericUpDown VolumeNumericUpDown; + } +} \ No newline at end of file diff --git a/PrecastConcretePlant/PrecastConcretePlant/FormShop.cs b/PrecastConcretePlant/PrecastConcretePlant/FormShop.cs new file mode 100644 index 0000000..e1a4b16 --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlant/FormShop.cs @@ -0,0 +1,132 @@ +using Microsoft.Extensions.Logging; +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.BusinessLogicsContracts; +using PrecastConcretePlantContracts.SearchModels; +using PrecastConcretePlantContracts.ViewModels; +using PrecastConcretePlantDataModels.Models; +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace PrecastConcretePlantView +{ + public partial class FormShop : Form + { + private readonly IShopLogic _logic; + private readonly ILogger _logger; + private int? _id; + private Dictionary _listShops; + public int Id { set { _id = value; } } + public FormShop(ILogger logger, IShopLogic logic) + { + InitializeComponent(); + _logger = logger; + _listShops = new(); + _logic = logic; + } + + private void LoadData(bool extendDate = true) + { + _logger.LogInformation("Загрузка изделий магазина"); + try + { + if (_listShops != null) + { + dataGridView.Rows.Clear(); + foreach (var elem in _listShops) + { + dataGridView.Rows.Add(new object[] { elem.Key, elem.Value.Item1.ReinforcedName, elem.Value.Item2 }); + } + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки изделий магазина"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ButtonSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(comboBoxShop.Text)) + { + MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (string.IsNullOrEmpty(textBoxAddress.Text)) + { + MessageBox.Show("Заполните адрес", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Сохранение магазина"); + try + { + var model = new ShopBindingModel + { + Id = _id ?? 0, + Name = comboBoxShop.Text, + Address = textBoxAddress.Text, + DateOpening = textBoxDateOpening.Value.Date, + ReinforcedMaxCount = (int)VolumeNumericUpDown.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); + } + } + + private void ButtonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + + private void FormShop_Load(object sender, EventArgs e) + { + if (_id.HasValue) + { + _logger.LogInformation("Загрузка магазина"); + try + { + var view = _logic.ReadElement(new ShopSearchModel + { + Id = _id.Value + }); + if (view != null) + { + comboBoxShop.Text = view.Name; + textBoxAddress.Text = view.Address; + textBoxDateOpening.Text = view.DateOpening.ToString(); + VolumeNumericUpDown.Value = view.ReinforcedMaxCount; + _listShops = view.ShopReinforcedies ?? new Dictionary(); + LoadData(); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки магазина"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + } + } +} diff --git a/PrecastConcretePlant/PrecastConcretePlant/FormShop.resx b/PrecastConcretePlant/PrecastConcretePlant/FormShop.resx new file mode 100644 index 0000000..36577c7 --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlant/FormShop.resx @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + True + + \ No newline at end of file diff --git a/PrecastConcretePlant/PrecastConcretePlant/FormShop.resx.bak b/PrecastConcretePlant/PrecastConcretePlant/FormShop.resx.bak new file mode 100644 index 0000000..7dafd55 --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlant/FormShop.resx.bak @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + True + + + True + + + True + + + True + + + True + + \ No newline at end of file diff --git a/PrecastConcretePlant/PrecastConcretePlant/FormShops.Designer.cs b/PrecastConcretePlant/PrecastConcretePlant/FormShops.Designer.cs new file mode 100644 index 0000000..c9657ae --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlant/FormShops.Designer.cs @@ -0,0 +1,121 @@ +namespace PrecastConcretePlantView +{ + 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() + { + this.buttonRef = new System.Windows.Forms.Button(); + this.buttonDel = new System.Windows.Forms.Button(); + this.buttonUpd = new System.Windows.Forms.Button(); + this.buttonAdd = new System.Windows.Forms.Button(); + this.dataGridView = new System.Windows.Forms.DataGridView(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); + this.SuspendLayout(); + // + // buttonRef + // + this.buttonRef.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); + this.buttonRef.Location = new System.Drawing.Point(685, 202); + this.buttonRef.Name = "buttonRef"; + this.buttonRef.Size = new System.Drawing.Size(90, 37); + this.buttonRef.TabIndex = 14; + this.buttonRef.Text = "Обновить"; + this.buttonRef.UseVisualStyleBackColor = true; + this.buttonRef.Click += new System.EventHandler(this.ButtonRef_Click); + // + // buttonDel + // + this.buttonDel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); + this.buttonDel.Location = new System.Drawing.Point(685, 151); + this.buttonDel.Name = "buttonDel"; + this.buttonDel.Size = new System.Drawing.Size(90, 33); + this.buttonDel.TabIndex = 13; + this.buttonDel.Text = "Удалить"; + this.buttonDel.UseVisualStyleBackColor = true; + this.buttonDel.Click += new System.EventHandler(this.ButtonDel_Click); + // + // buttonUpd + // + this.buttonUpd.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); + this.buttonUpd.Location = new System.Drawing.Point(685, 102); + this.buttonUpd.Name = "buttonUpd"; + this.buttonUpd.Size = new System.Drawing.Size(90, 34); + this.buttonUpd.TabIndex = 12; + this.buttonUpd.Text = "Изменить"; + this.buttonUpd.UseVisualStyleBackColor = true; + this.buttonUpd.Click += new System.EventHandler(this.ButtonUpd_Click); + // + // buttonAdd + // + this.buttonAdd.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); + this.buttonAdd.Location = new System.Drawing.Point(685, 57); + this.buttonAdd.Name = "buttonAdd"; + this.buttonAdd.Size = new System.Drawing.Size(90, 30); + this.buttonAdd.TabIndex = 11; + this.buttonAdd.Text = "Добавить"; + this.buttonAdd.UseVisualStyleBackColor = true; + this.buttonAdd.Click += new System.EventHandler(this.ButtonAdd_Click); + // + // dataGridView + // + this.dataGridView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView.Location = new System.Drawing.Point(12, 12); + this.dataGridView.Name = "dataGridView"; + this.dataGridView.RowTemplate.Height = 25; + this.dataGridView.Size = new System.Drawing.Size(540, 379); + this.dataGridView.TabIndex = 10; + // + // FormViewShops + // + this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(787, 403); + this.Controls.Add(this.buttonRef); + this.Controls.Add(this.buttonDel); + this.Controls.Add(this.buttonUpd); + this.Controls.Add(this.buttonAdd); + this.Controls.Add(this.dataGridView); + this.Name = "FormViewShops"; + this.Text = "Просмотр магазинов"; + this.Load += new System.EventHandler(this.FormShops_Load); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit(); + this.ResumeLayout(false); + + } + + #endregion + + private Button buttonRef; + private Button buttonDel; + private Button buttonUpd; + private Button buttonAdd; + private DataGridView dataGridView; + } +} \ No newline at end of file diff --git a/PrecastConcretePlant/PrecastConcretePlant/FormShops.cs b/PrecastConcretePlant/PrecastConcretePlant/FormShops.cs new file mode 100644 index 0000000..b3fb52f --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlant/FormShops.cs @@ -0,0 +1,106 @@ +using Microsoft.Extensions.Logging; +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.BusinessLogicsContracts; +using PrecastConcretePlantView; + +namespace PrecastConcretePlantView +{ + 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["ShopReinforcedies"].Visible = false; + dataGridView.Columns["Name"].AutoSizeMode = + DataGridViewAutoSizeColumnMode.Fill; + } + _logger.LogInformation("Загрузка магазинов"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки магазинов"); + 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 ButtonUpd_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("Удаление магазина"); + 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); + } + } + } + } + private void ButtonRef_Click(object sender, EventArgs e) + { + LoadData(); + } + } +} diff --git a/PrecastConcretePlant/PrecastConcretePlant/FormShops.resx b/PrecastConcretePlant/PrecastConcretePlant/FormShops.resx new file mode 100644 index 0000000..f298a7b --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlant/FormShops.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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/PrecastConcretePlant/PrecastConcretePlant/Program.cs b/PrecastConcretePlant/PrecastConcretePlant/Program.cs index d1764f5..0f9f86e 100644 --- a/PrecastConcretePlant/PrecastConcretePlant/Program.cs +++ b/PrecastConcretePlant/PrecastConcretePlant/Program.cs @@ -36,6 +36,7 @@ namespace PrecastConcretePlantView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -43,6 +44,7 @@ namespace PrecastConcretePlantView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -50,8 +52,6 @@ namespace PrecastConcretePlantView services.AddTransient(); services.AddTransient(); services.AddTransient(); - services.AddTransient(); - services.AddTransient(); } } } diff --git a/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/BusinessLogic/OrderLogic.cs b/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/BusinessLogic/OrderLogic.cs index d308c19..fc3415c 100644 --- a/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/BusinessLogic/OrderLogic.cs +++ b/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/BusinessLogic/OrderLogic.cs @@ -17,11 +17,14 @@ namespace PrecastConcretePlantBusinessLogic.BusinessLogic { private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; - - public OrderLogic(ILogger logger, IOrderStorage orderStorage) + private readonly IShopLogic _shopLogic; + private readonly IReinforcedStorage _reinforcedStorage; + public OrderLogic(ILogger logger, IOrderStorage orderStorage, IReinforcedStorage reinforcedStorage, IShopLogic shopLogic) { _logger = logger; _orderStorage = orderStorage; + _shopLogic = shopLogic; + _reinforcedStorage = reinforcedStorage; } public bool CreateOrder(OrderBindingModel model) @@ -48,9 +51,14 @@ namespace PrecastConcretePlantBusinessLogic.BusinessLogic public bool StatusUpdate(OrderBindingModel model, OrderStatus newStatus) { - CheckModel(model); + var viewModel = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id }); - if (model.Status + 1 != newStatus) + if (viewModel == null) + { + throw new ArgumentNullException(nameof(model)); + } + + if (viewModel.Status + 1 != newStatus) { _logger.LogWarning("Status update to " + newStatus.ToString() + " operation failed. Order status incorrect."); return false; @@ -58,13 +66,34 @@ namespace PrecastConcretePlantBusinessLogic.BusinessLogic model.Status = newStatus; - if (model.Status == OrderStatus.Выдан) + if (model.Status == OrderStatus.Готов) + { model.DateImplement = DateTime.Now; + var reinforced = _reinforcedStorage.GetElement(new() { Id = viewModel.ReinforcedId }); + + if (reinforced == null) + { + throw new ArgumentNullException(nameof(reinforced)); + } + + if (!_shopLogic.AddReinforced(reinforced, viewModel.Count)) + { + throw new Exception($"AddReinforced operation failed. Shop is full."); + } + } + else + { + model.DateImplement = viewModel.DateImplement; + } + + CheckModel(model, false); + if (_orderStorage.Update(model) == null) { model.Status--; _logger.LogWarning("Update operation failed"); + return false; } diff --git a/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/BusinessLogic/ShopLogic.cs b/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/BusinessLogic/ShopLogic.cs new file mode 100644 index 0000000..4e6aaa7 --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/BusinessLogic/ShopLogic.cs @@ -0,0 +1,228 @@ +using Microsoft.Extensions.Logging; +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.BusinessLogicsContracts; +using PrecastConcretePlantContracts.SearchModels; +using PrecastConcretePlantContracts.StoragesContracts; +using PrecastConcretePlantContracts.ViewModels; +using PrecastConcretePlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + + +namespace PrecastConcretePlantBusinessLogic.BusinessLogic +{ + 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. Name:{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 ShopViewModel? ReadElement(ShopSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + _logger.LogInformation("ReadElement. Name:{Name}.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); + model.ShopReinforcedies = new(); + if (_shopStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } + public bool SellReinforced(IReinforcedModel reinforced, int count) + { + return _shopStorage.SellReinforced(reinforced, count); + } + public bool Update(ShopBindingModel model) + { + CheckModel(model, false); + if (string.IsNullOrEmpty(model.Name)) + { + throw new ArgumentNullException("Нет названия магазина", + nameof(model.Name)); + } + + 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.Name)) + { + throw new ArgumentNullException("Нет названия магазина", + nameof(model.Name)); + } + if (model.ReinforcedMaxCount < 0) + { + throw new ArgumentException("Максимальное количество изделий в магазине не может быть меньше нуля", nameof(model.ReinforcedMaxCount)); + } + _logger.LogInformation("Shop. Name:{0}.Address:{1}. Id: {2}", + model.Name, model.Address, model.Id); + var element = _shopStorage.GetElement(new ShopSearchModel + { + Name = model.Name + }); + if (element != null && element.Id != model.Id && element.Name == model.Name) + { + throw new InvalidOperationException("Магазин с таким названием уже есть"); + } + } + + public bool AddReinforced(ShopSearchModel model, IReinforcedModel reinforced, int count) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + + if (count <= 0) + { + throw new ArgumentException("Количество изделий должно быть больше 0", nameof(count)); + } + + _logger.LogInformation("AddReinforced. Name:{Name}.Id:{ Id}", model.Name, model.Id); + var element = _shopStorage.GetElement(model); + + if (element == null) + { + _logger.LogWarning("AddReinforced element not found"); + return false; + } + + if (element.ReinforcedMaxCount - element.ShopReinforcedies.Select(x => x.Value.Item2).Sum() < count) + { + throw new ArgumentNullException("Магазин переполнен", nameof(count)); + } + + _logger.LogInformation("AddReinforced find. Id:{Id}", element.Id); + + if (element.ShopReinforcedies.TryGetValue(reinforced.Id, out var pair)) + { + element.ShopReinforcedies[reinforced.Id] = (reinforced, count + pair.Item2); + _logger.LogInformation("AddReinforced. Added {count} {reinforced} to '{Name}' shop", count, reinforced.ReinforcedName, element.Name); + } + else + { + element.ShopReinforcedies[reinforced.Id] = (reinforced, count); + _logger.LogInformation("AddReinforced. Added {count} new reinforced {reinforced} to '{Name}' shop", count, reinforced.ReinforcedName, element.Name); + } + + _shopStorage.Update(new() + { + Id = element.Id, + Address = element.Address, + Name = element.Name, + DateOpening = element.DateOpening, + ReinforcedMaxCount = element.ReinforcedMaxCount, + ShopReinforcedies = element.ShopReinforcedies, + }); + + return true; + } + public bool AddReinforced(IReinforcedModel reinforced, int count) + { + if (reinforced == null) + { + throw new ArgumentNullException(nameof(reinforced)); + } + + if (count <= 0) + { + throw new ArgumentException("Количество добавляемого изделия должно быть больше 0", nameof(count)); + } + + var freePlaces = _shopStorage.GetFullList() + .Select(x => x.ReinforcedMaxCount - x.ShopReinforcedies + .Select(p => p.Value.Item2).Sum()).Sum() - count; + + if (freePlaces < 0) + { + _logger.LogInformation("AddReinforced. Failed to add reinforced to shop. It's full."); + return false; + } + + foreach (var shop in _shopStorage.GetFullList()) + { + var temp = Math.Min(count, shop.ReinforcedMaxCount - shop.ShopReinforcedies.Select(x => x.Value.Item2).Sum()); + + if (temp <= 0) + { + continue; + } + + if (!AddReinforced(new() { Id = shop.Id }, reinforced, temp)) + { + _logger.LogWarning("An error occurred while adding reinforced to shops"); + return false; + } + + count -= temp; + + if (count == 0) + { + return true; + } + } + return true; + } + } +} diff --git a/PrecastConcretePlant/PrecastConcretePlantContracts/BindingModels/ShopBindingModel.cs b/PrecastConcretePlant/PrecastConcretePlantContracts/BindingModels/ShopBindingModel.cs new file mode 100644 index 0000000..9d4213f --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantContracts/BindingModels/ShopBindingModel.cs @@ -0,0 +1,24 @@ +using PrecastConcretePlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantContracts.BindingModels +{ + public class ShopBindingModel : IShopModel + { + public string Name { get; set; } = string.Empty; + + public string Address { get; set; } = string.Empty; + public int ReinforcedMaxCount { get; set; } + + public DateTime DateOpening { get; set; } = DateTime.Now; + + public Dictionary ShopReinforcedies { get; set; } = new(); + + + public int Id { get; set; } + } +} diff --git a/PrecastConcretePlant/PrecastConcretePlantContracts/BusinessLogicsContracts/IShopLogic.cs b/PrecastConcretePlant/PrecastConcretePlantContracts/BusinessLogicsContracts/IShopLogic.cs new file mode 100644 index 0000000..f55386f --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantContracts/BusinessLogicsContracts/IShopLogic.cs @@ -0,0 +1,25 @@ +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.SearchModels; +using PrecastConcretePlantContracts.ViewModels; +using PrecastConcretePlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantContracts.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 AddReinforced(ShopSearchModel model, IReinforcedModel reinforced, int count); + bool AddReinforced(IReinforcedModel reinforced, int quantity); + bool SellReinforced(IReinforcedModel reinforced, int quantity); + + } +} diff --git a/PrecastConcretePlant/PrecastConcretePlantContracts/SearchModels/ShopSearchModel.cs b/PrecastConcretePlant/PrecastConcretePlantContracts/SearchModels/ShopSearchModel.cs new file mode 100644 index 0000000..c08ab42 --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantContracts/SearchModels/ShopSearchModel.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantContracts.SearchModels +{ + public class ShopSearchModel + { + public int? Id { get; set; } + public string? Name { get; set; } + } +} diff --git a/PrecastConcretePlant/PrecastConcretePlantContracts/StoragesContracts/IShopStorage.cs b/PrecastConcretePlant/PrecastConcretePlantContracts/StoragesContracts/IShopStorage.cs new file mode 100644 index 0000000..142cb4f --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantContracts/StoragesContracts/IShopStorage.cs @@ -0,0 +1,23 @@ +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.SearchModels; +using PrecastConcretePlantContracts.ViewModels; +using PrecastConcretePlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantContracts.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); + bool SellReinforced(IReinforcedModel model, int quantity); + } +} diff --git a/PrecastConcretePlant/PrecastConcretePlantContracts/ViewModels/ShopViewModel.cs b/PrecastConcretePlant/PrecastConcretePlantContracts/ViewModels/ShopViewModel.cs new file mode 100644 index 0000000..1708dfc --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantContracts/ViewModels/ShopViewModel.cs @@ -0,0 +1,30 @@ +using PrecastConcretePlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantContracts.ViewModels +{ + public class ShopViewModel : IShopModel + { + [DisplayName("Название магазина")] + public string Name { get; set; } = string.Empty; + + [DisplayName("Адрес магазина")] + public string Address { get; set; } = string.Empty; + + [DisplayName("Время открытия")] + public DateTime DateOpening { get; set; } + + [DisplayName("Вместимость магазина")] + public int ReinforcedMaxCount { get; set; } + + public Dictionary ShopReinforcedies { get; set; } = new(); + + + public int Id { get; set; } + } +} diff --git a/PrecastConcretePlant/PrecastConcretePlantDataModels/Models/IShopModel.cs b/PrecastConcretePlant/PrecastConcretePlantDataModels/Models/IShopModel.cs new file mode 100644 index 0000000..5d055cf --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantDataModels/Models/IShopModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantDataModels.Models +{ + public interface IShopModel : IId + { + string Name { get; } + string Address { get; } + public int ReinforcedMaxCount { get; } + DateTime DateOpening { get; } + Dictionary ShopReinforcedies { get; } + + } +} diff --git a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Implements/ReinforcedStorage.cs b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Implements/ReinforcedStorage.cs index 50c3dd6..1925846 100644 --- a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Implements/ReinforcedStorage.cs +++ b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Implements/ReinforcedStorage.cs @@ -19,11 +19,11 @@ namespace PrecastConcretePlantDatabaseImplement.Implements { using var context = new PrecastConcretePlantDataBase(); - var element = context.Reinforceds.Include(x => x.Components).FirstOrDefault(rec => rec.Id == model.Id); + var element = context.Reinforcedies.Include(x => x.Components).FirstOrDefault(rec => rec.Id == model.Id); if (element != null) { - context.Reinforceds.Remove(element); + context.Reinforcedies.Remove(element); context.SaveChanges(); return element.GetViewModel; } @@ -40,7 +40,7 @@ namespace PrecastConcretePlantDatabaseImplement.Implements using var context = new PrecastConcretePlantDataBase(); - return context.Reinforceds.Include(x => x.Components).ThenInclude(x => x.Component).FirstOrDefault(x => (!string.IsNullOrEmpty(model.ReinforcedName) && x.ReinforcedName == model.ReinforcedName) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; + return context.Reinforcedies.Include(x => x.Components).ThenInclude(x => x.Component).FirstOrDefault(x => (!string.IsNullOrEmpty(model.ReinforcedName) && x.ReinforcedName == model.ReinforcedName) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; } public List GetFilteredList(ReinforcedSearchModel model) @@ -52,14 +52,14 @@ namespace PrecastConcretePlantDatabaseImplement.Implements using var context = new PrecastConcretePlantDataBase(); - return context.Reinforceds.Include(x => x.Components).ThenInclude(x => x.Component).Where(x => x.ReinforcedName.Contains(model.ReinforcedName)).ToList().Select(x => x.GetViewModel).ToList(); + return context.Reinforcedies.Include(x => x.Components).ThenInclude(x => x.Component).Where(x => x.ReinforcedName.Contains(model.ReinforcedName)).ToList().Select(x => x.GetViewModel).ToList(); } public List GetFullList() { using var context = new PrecastConcretePlantDataBase(); - return context.Reinforceds.Include(x => x.Components).ThenInclude(x => x.Component).ToList().Select(x => x.GetViewModel).ToList(); + return context.Reinforcedies.Include(x => x.Components).ThenInclude(x => x.Component).ToList().Select(x => x.GetViewModel).ToList(); } public ReinforcedViewModel? Insert(ReinforcedBindingModel model) @@ -73,7 +73,7 @@ namespace PrecastConcretePlantDatabaseImplement.Implements return null; } - context.Reinforceds.Add(newReinforced); + context.Reinforcedies.Add(newReinforced); context.SaveChanges(); return newReinforced.GetViewModel; @@ -87,7 +87,7 @@ namespace PrecastConcretePlantDatabaseImplement.Implements try { - var reinforced = context.Reinforceds.FirstOrDefault(rec => rec.Id == model.Id); + var reinforced = context.Reinforcedies.FirstOrDefault(rec => rec.Id == model.Id); if (reinforced == null) { diff --git a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Implements/ShopStorage.cs b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Implements/ShopStorage.cs new file mode 100644 index 0000000..b694e88 --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Implements/ShopStorage.cs @@ -0,0 +1,156 @@ +using Microsoft.EntityFrameworkCore; +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.SearchModels; +using PrecastConcretePlantContracts.StoragesContracts; +using PrecastConcretePlantContracts.ViewModels; +using PrecastConcretePlantDatabaseImplement.Models; +using PrecastConcretePlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantDatabaseImplement.Implements +{ + public class ShopStorage : IShopStorage + { + public List GetFullList() + { + using var context = new PrecastConcretePlantDataBase(); + return context.Shops + .Include(x => x.Reinforcedies) + .ThenInclude(x => x.Reinforced) + .ToList() + .Select(x => x.GetViewModel) + .ToList(); + } + + public List GetFilteredList(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.Name)) + { + return new(); + } + using var context = new PrecastConcretePlantDataBase(); + return context.Shops + .Include(x => x.Reinforcedies) + .ThenInclude(x => x.Reinforced) + .Where(x => x.Name.Contains(model.Name)) + .ToList() + .Select(x => x.GetViewModel) + .ToList(); + } + + public ShopViewModel? GetElement(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.Name) && !model.Id.HasValue) + { + return null; + } + using var context = new PrecastConcretePlantDataBase(); + return context.Shops + .Include(x => x.Reinforcedies) + .ThenInclude(x => x.Reinforced) + .FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name) && x.Name == model.Name) || + (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; + } + + public ShopViewModel? Insert(ShopBindingModel model) + { + using var context = new PrecastConcretePlantDataBase(); + var newShop = Shop.Create(context, model); + if (newShop == null) + { + return null; + } + context.Shops.Add(newShop); + context.SaveChanges(); + return newShop.GetViewModel; + } + + public ShopViewModel? Update(ShopBindingModel model) + { + using var context = new PrecastConcretePlantDataBase(); + using var transaction = context.Database.BeginTransaction(); + try + { + var shop = context.Shops.FirstOrDefault(rec => rec.Id == model.Id); + if (shop == null) + { + return null; + } + shop.Update(model); + context.SaveChanges(); + shop.UpdateReinforcedies(context, model); + transaction.Commit(); + return shop.GetViewModel; + } + catch + { + transaction.Rollback(); + throw; + } + } + + public ShopViewModel? Delete(ShopBindingModel model) + { + using var context = new PrecastConcretePlantDataBase(); + var element = context.Shops + .Include(x => x.Reinforcedies) + .FirstOrDefault(rec => rec.Id == model.Id); + if (element != null) + { + context.Shops.Remove(element); + context.SaveChanges(); + return element.GetViewModel; + } + return null; + } + + public bool SellReinforced(IReinforcedModel model, int count) + { + using var context = new PrecastConcretePlantDataBase(); + using var transaction = context.Database.BeginTransaction(); + try + { + var shops = context.ShopReinforcedies + .Include(x => x.Shop) + .ToList() + .Where(rec => rec.ReinforcedId == model.Id); + if (shops == null) + { + return false; + } + foreach (var shop in shops) + { + if (shop.Count < count) + { + shop.Count = 0; + count -= shop.Count; + } + else + { + shop.Count = shop.Count - count; + count -= count; + } + if (count == 0) + { + + context.SaveChanges(); + transaction.Commit(); + return true; + } + } + transaction.Rollback(); + return false; + } + catch + { + transaction.Rollback(); + throw; + } + } + + } +} diff --git a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Migrations/20230327065744_Restart.Designer.cs b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Migrations/20230327065744_Restart.Designer.cs deleted file mode 100644 index dd0a7df..0000000 --- a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Migrations/20230327065744_Restart.Designer.cs +++ /dev/null @@ -1,175 +0,0 @@ -// -using System; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Metadata; -using Microsoft.EntityFrameworkCore.Migrations; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; -using PrecastConcretePlantDatabaseImplement; - -#nullable disable - -namespace PrecastConcretePlantDatabaseImplement.Migrations -{ - [DbContext(typeof(PrecastConcretePlantDataBase))] - [Migration("20230327065744_Restart")] - partial class Restart - { - /// - protected override void BuildTargetModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder - .HasAnnotation("ProductVersion", "7.0.3") - .HasAnnotation("Relational:MaxIdentifierLength", 128); - - SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); - - modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.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("PrecastConcretePlantDatabaseImplement.Models.Order", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("int"); - - SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); - - b.Property("Count") - .HasColumnType("int"); - - b.Property("DateCreate") - .HasColumnType("datetime2"); - - b.Property("DateImplement") - .HasColumnType("datetime2"); - - b.Property("ReinforcedId") - .HasColumnType("int"); - - b.Property("ReinforcedName") - .IsRequired() - .HasColumnType("nvarchar(max)"); - - b.Property("Status") - .HasColumnType("int"); - - b.Property("Sum") - .HasColumnType("float"); - - b.HasKey("Id"); - - b.HasIndex("ReinforcedId"); - - b.ToTable("Orders"); - }); - - modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Reinforced", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("int"); - - SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); - - b.Property("Price") - .HasColumnType("float"); - - b.Property("ReinforcedName") - .IsRequired() - .HasColumnType("nvarchar(max)"); - - b.HasKey("Id"); - - b.ToTable("Reinforceds"); - }); - - modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.ReinforcedComponent", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("int"); - - SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); - - b.Property("ComponentId") - .HasColumnType("int"); - - b.Property("Count") - .HasColumnType("int"); - - b.Property("ReinforcedId") - .HasColumnType("int"); - - b.HasKey("Id"); - - b.HasIndex("ComponentId"); - - b.HasIndex("ReinforcedId"); - - b.ToTable("ReinforcedComponents"); - }); - - modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Order", b => - { - b.HasOne("PrecastConcretePlantDatabaseImplement.Models.Reinforced", "Reinforced") - .WithMany("Orders") - .HasForeignKey("ReinforcedId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Reinforced"); - }); - - modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.ReinforcedComponent", b => - { - b.HasOne("PrecastConcretePlantDatabaseImplement.Models.Component", "Component") - .WithMany("ReinforcedComponents") - .HasForeignKey("ComponentId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("PrecastConcretePlantDatabaseImplement.Models.Reinforced", "Reinforced") - .WithMany("Components") - .HasForeignKey("ReinforcedId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Component"); - - b.Navigation("Reinforced"); - }); - - modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Component", b => - { - b.Navigation("ReinforcedComponents"); - }); - - modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Reinforced", b => - { - b.Navigation("Components"); - - b.Navigation("Orders"); - }); -#pragma warning restore 612, 618 - } - } -} diff --git a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Migrations/20230327065744_Restart.cs b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Migrations/20230327065744_Restart.cs deleted file mode 100644 index d6af164..0000000 --- a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Migrations/20230327065744_Restart.cs +++ /dev/null @@ -1,126 +0,0 @@ -using System; -using Microsoft.EntityFrameworkCore.Migrations; - -#nullable disable - -namespace PrecastConcretePlantDatabaseImplement.Migrations -{ - /// - public partial class Restart : 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: "Reinforceds", - columns: table => new - { - Id = table.Column(type: "int", nullable: false) - .Annotation("SqlServer:Identity", "1, 1"), - ReinforcedName = table.Column(type: "nvarchar(max)", nullable: false), - Price = table.Column(type: "float", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Reinforceds", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "Orders", - columns: table => new - { - Id = table.Column(type: "int", nullable: false) - .Annotation("SqlServer:Identity", "1, 1"), - ReinforcedId = table.Column(type: "int", nullable: false), - ReinforcedName = table.Column(type: "nvarchar(max)", nullable: false), - 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) - }, - constraints: table => - { - table.PrimaryKey("PK_Orders", x => x.Id); - table.ForeignKey( - name: "FK_Orders_Reinforceds_ReinforcedId", - column: x => x.ReinforcedId, - principalTable: "Reinforceds", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "ReinforcedComponents", - columns: table => new - { - Id = table.Column(type: "int", nullable: false) - .Annotation("SqlServer:Identity", "1, 1"), - ReinforcedId = 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_ReinforcedComponents", x => x.Id); - table.ForeignKey( - name: "FK_ReinforcedComponents_Components_ComponentId", - column: x => x.ComponentId, - principalTable: "Components", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - table.ForeignKey( - name: "FK_ReinforcedComponents_Reinforceds_ReinforcedId", - column: x => x.ReinforcedId, - principalTable: "Reinforceds", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateIndex( - name: "IX_Orders_ReinforcedId", - table: "Orders", - column: "ReinforcedId"); - - migrationBuilder.CreateIndex( - name: "IX_ReinforcedComponents_ComponentId", - table: "ReinforcedComponents", - column: "ComponentId"); - - migrationBuilder.CreateIndex( - name: "IX_ReinforcedComponents_ReinforcedId", - table: "ReinforcedComponents", - column: "ReinforcedId"); - } - - /// - protected override void Down(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropTable( - name: "Orders"); - - migrationBuilder.DropTable( - name: "ReinforcedComponents"); - - migrationBuilder.DropTable( - name: "Components"); - - migrationBuilder.DropTable( - name: "Reinforceds"); - } - } -} diff --git a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Migrations/PrecastConcretePlantDataBaseModelSnapshot.cs b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Migrations/PrecastConcretePlantDataBaseModelSnapshot.cs index 9f8ee2e..1f2e84a 100644 --- a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Migrations/PrecastConcretePlantDataBaseModelSnapshot.cs +++ b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Migrations/PrecastConcretePlantDataBaseModelSnapshot.cs @@ -96,7 +96,7 @@ namespace PrecastConcretePlantDatabaseImplement.Migrations b.HasKey("Id"); - b.ToTable("Reinforceds"); + b.ToTable("Reinforcedies"); }); modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.ReinforcedComponent", b => @@ -125,6 +125,59 @@ namespace PrecastConcretePlantDatabaseImplement.Migrations b.ToTable("ReinforcedComponents"); }); + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Shop", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Address") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("DateOpening") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ReinforcedMaxCount") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.ToTable("Shops"); + }); + + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.ShopReinforced", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("ReinforcedId") + .HasColumnType("int"); + + b.Property("ShopId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ReinforcedId"); + + b.HasIndex("ShopId"); + + b.ToTable("ShopReinforcedies"); + }); + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Order", b => { b.HasOne("PrecastConcretePlantDatabaseImplement.Models.Reinforced", "Reinforced") @@ -155,6 +208,25 @@ namespace PrecastConcretePlantDatabaseImplement.Migrations b.Navigation("Reinforced"); }); + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.ShopReinforced", b => + { + b.HasOne("PrecastConcretePlantDatabaseImplement.Models.Reinforced", "Reinforced") + .WithMany() + .HasForeignKey("ReinforcedId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("PrecastConcretePlantDatabaseImplement.Models.Shop", "Shop") + .WithMany("Reinforcedies") + .HasForeignKey("ShopId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Reinforced"); + + b.Navigation("Shop"); + }); + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Component", b => { b.Navigation("ReinforcedComponents"); @@ -166,6 +238,11 @@ namespace PrecastConcretePlantDatabaseImplement.Migrations b.Navigation("Orders"); }); + + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Shop", b => + { + b.Navigation("Reinforcedies"); + }); #pragma warning restore 612, 618 } } diff --git a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Models/Reinforced.cs b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Models/Reinforced.cs index b7978a0..1c91633 100644 --- a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Models/Reinforced.cs +++ b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Models/Reinforced.cs @@ -87,7 +87,7 @@ namespace PrecastConcretePlantDatabaseImplement.Models context.SaveChanges(); } - var reinforced = context.Reinforceds.First(x => x.Id == Id); + var reinforced = context.Reinforcedies.First(x => x.Id == Id); foreach (var pc in model.ReinforcedComponents) { diff --git a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Models/Shop.cs b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Models/Shop.cs new file mode 100644 index 0000000..4b737e8 --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Models/Shop.cs @@ -0,0 +1,106 @@ +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.ViewModels; +using PrecastConcretePlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantDatabaseImplement.Models +{ + public class Shop : IShopModel + { + public int Id { get; set; } + [Required] + public string Name { get; set; } = string.Empty; + [Required] + public string Address { get; set; } = string.Empty; + [Required] + public DateTime DateOpening { get; set; } + [Required] + public int ReinforcedMaxCount { get; set; } + + private Dictionary? _shopReinforcedies = null; + + [NotMapped] + public Dictionary ShopReinforcedies + { + get + { + if (_shopReinforcedies == null) + { + _shopReinforcedies = Reinforcedies.ToDictionary(recST => recST.ReinforcedId, recST => (recST.Reinforced as IReinforcedModel, recST.Count)); + } + return _shopReinforcedies; + } + } + [ForeignKey("ShopId")] + public virtual List Reinforcedies { get; set; } = new(); + public static Shop Create(PrecastConcretePlantDataBase context, ShopBindingModel model) + { + return new Shop() + { + Id = model.Id, + Name = model.Name, + Address = model.Address, + DateOpening = model.DateOpening, + ReinforcedMaxCount = model.ReinforcedMaxCount, + Reinforcedies = model.ShopReinforcedies.Select(x => new ShopReinforced + { + Reinforced = context.Reinforcedies.First(y => y.Id == x.Key), + Count = x.Value.Item2 + }).ToList() + }; + } + + public void Update(ShopBindingModel model) + { + Name = model.Name; + Address = model.Address; + DateOpening = model.DateOpening; + ReinforcedMaxCount = model.ReinforcedMaxCount; + } + + public ShopViewModel GetViewModel => new() + { + Id = Id, + Name = Name, + Address = Address, + DateOpening = DateOpening, + ReinforcedMaxCount = ReinforcedMaxCount, + ShopReinforcedies = ShopReinforcedies + }; + + public void UpdateReinforcedies(PrecastConcretePlantDataBase context, ShopBindingModel model) + { + var shopReinforcedies = context.ShopReinforcedies.Where(rec => rec.ShopId == model.Id).ToList(); + if (shopReinforcedies != null && shopReinforcedies.Count > 0) + { + context.ShopReinforcedies.RemoveRange(shopReinforcedies.Where(rec => !model.ShopReinforcedies.ContainsKey(rec.ReinforcedId))); + context.SaveChanges(); + + foreach (var updateReinforced in shopReinforcedies) + { + updateReinforced.Count = model.ShopReinforcedies[updateReinforced.ReinforcedId].Item2; + model.ShopReinforcedies.Remove(updateReinforced.ReinforcedId); + } + context.SaveChanges(); + } + var shop = context.Shops.First(x => x.Id == Id); + foreach (var st in model.ShopReinforcedies) + { + context.ShopReinforcedies.Add(new ShopReinforced + { + Shop = shop, + Reinforced = context.Reinforcedies.First(x => x.Id == st.Key), + Count = st.Value.Item2 + }); + context.SaveChanges(); + } + _shopReinforcedies = null; + } + } +} diff --git a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Models/ShopReinforced.cs b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Models/ShopReinforced.cs new file mode 100644 index 0000000..8f00eda --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Models/ShopReinforced.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantDatabaseImplement.Models +{ + public class ShopReinforced + { + public int Id { get; set; } + [Required] + public int ReinforcedId { get; set; } + [Required] + public int ShopId { get; set; } + [Required] + public int Count { get; set; } + + public virtual Shop Shop { get; set; } = new(); + public virtual Reinforced Reinforced { get; set; } = new(); + } +} diff --git a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/PrecastConcretePlantDataBase.cs b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/PrecastConcretePlantDataBase.cs index 0e7da02..320c1e6 100644 --- a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/PrecastConcretePlantDataBase.cs +++ b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/PrecastConcretePlantDataBase.cs @@ -14,13 +14,15 @@ namespace PrecastConcretePlantDatabaseImplement { if (optionsBuilder.IsConfigured == false) { - optionsBuilder.UseSqlServer(@"Data Source=MAKSIM\SQLEXPRESS;Initial Catalog=PrecastConcretePlantDataBaseFull;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True"); + optionsBuilder.UseSqlServer(@"Data Source=MAKSIM\SQLEXPRESS;Initial Catalog=PrecastConcretePlantDataBaseFullHard;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True"); } base.OnConfiguring(optionsBuilder); } public virtual DbSet Components { set; get; } - public virtual DbSet Reinforceds { set; get; } + public virtual DbSet Reinforcedies { set; get; } public virtual DbSet ReinforcedComponents { set; get; } public virtual DbSet Orders { set; get; } + public virtual DbSet Shops { set; get; } + public virtual DbSet ShopReinforcedies { set; get; } } } \ No newline at end of file diff --git a/PrecastConcretePlant/PrecastConcretePlantFileImplement/DataFileSingleton.cs b/PrecastConcretePlant/PrecastConcretePlantFileImplement/DataFileSingleton.cs index 7a32b41..b68cfdd 100644 --- a/PrecastConcretePlant/PrecastConcretePlantFileImplement/DataFileSingleton.cs +++ b/PrecastConcretePlant/PrecastConcretePlantFileImplement/DataFileSingleton.cs @@ -15,9 +15,11 @@ namespace PrecastConcretePlantFileImplement private readonly string ComponentFileName = "Component.xml"; private readonly string OrderFileName = "Order.xml"; private readonly string ReinforcedFileName = "Reinforced.xml"; + private readonly string ShopFileName = "Shop.xml"; public List Components { get; private set; } public List Orders { get; private set; } public List Reinforceds { get; private set; } + public List Shops { get; private set; } public static DataFileSingleton GetInstance() { if (instance == null) @@ -32,6 +34,7 @@ namespace PrecastConcretePlantFileImplement "Reinforceds", 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 => @@ -39,6 +42,7 @@ namespace PrecastConcretePlantFileImplement Reinforceds = LoadData(ReinforcedFileName, "Reinforced", x => Reinforced.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/PrecastConcretePlant/PrecastConcretePlantFileImplement/Implements/ShopStorage.cs b/PrecastConcretePlant/PrecastConcretePlantFileImplement/Implements/ShopStorage.cs new file mode 100644 index 0000000..19f21ac --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantFileImplement/Implements/ShopStorage.cs @@ -0,0 +1,112 @@ +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.SearchModels; +using PrecastConcretePlantContracts.StoragesContracts; +using PrecastConcretePlantContracts.ViewModels; +using PrecastConcretePlantDataModels.Models; +using PrecastConcretePlantFileImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantFileImplement.Implements +{ + public class ShopStorage : IShopStorage + { + private readonly DataFileSingleton source; + + public ShopStorage() + { + source = DataFileSingleton.GetInstance(); + } + 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; + } + + 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.Name == + model.Name) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; + } + + public List GetFilteredList(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.Name)) + { + return new(); + } + return source.Shops.Where(x => x.Name.Contains(model.Name)).Select(x => x.GetViewModel).ToList(); + } + + public List GetFullList() + { + return source.Shops.Select(x => x.GetViewModel).ToList(); + } + + public ShopViewModel? Insert(ShopBindingModel model) + { + model.Id = source.Shops.Count > 0 ? source.Shops.Max(x => x.Id) + 1 : 1; + var newShop = Shop.Create(model); + if (newShop == null) + { + return null; + } + source.Shops.Add(newShop); + source.SaveShops(); + return newShop.GetViewModel; + } + + public bool SellReinforced(IReinforcedModel model, int quantity) + { + if (source.Shops.Select(x => x.ShopReinforcedies.FirstOrDefault(y => y.Key == model.Id).Value.Item2).Sum() < quantity) + { + return false; + } + foreach (var shop in source.Shops.Where(x => x.ShopReinforcedies.ContainsKey(model.Id))) + { + int QuantityInCurrentShop = shop.ShopReinforcedies[model.Id].Item2; + if (QuantityInCurrentShop <= quantity) + { + shop.ShopReinforcedies.Remove(model.Id); + quantity -= QuantityInCurrentShop; + } + else + { + shop.ShopReinforcedies[model.Id] = (shop.ShopReinforcedies[model.Id].Item1, QuantityInCurrentShop - quantity); + quantity = 0; + } + if (quantity == 0) + { + return true; + } + } + return false; + } + + 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; + } + } +} diff --git a/PrecastConcretePlant/PrecastConcretePlantFileImplement/Models/Shop.cs b/PrecastConcretePlant/PrecastConcretePlantFileImplement/Models/Shop.cs new file mode 100644 index 0000000..d262c11 --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantFileImplement/Models/Shop.cs @@ -0,0 +1,107 @@ +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.ViewModels; +using PrecastConcretePlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace PrecastConcretePlantFileImplement.Models +{ + public class Shop : IShopModel + { + public string Name { get; private set; } = string.Empty; + public string Address { get; private set; } = string.Empty; + + public DateTime DateOpening { get; private set; } + public Dictionary Reinforcedies { get; private set; } = new(); + + public Dictionary _shopReinforcedies = null; + public Dictionary ShopReinforcedies + { + get + { + if (_shopReinforcedies == null) + { + var source = DataFileSingleton.GetInstance(); + _shopReinforcedies = Reinforcedies.ToDictionary(x => x.Key, y => ((source.Reinforceds.FirstOrDefault(z => z.Id == y.Key) as IReinforcedModel)!, y.Value)); + } + return _shopReinforcedies; + } + } + + public int Id { get; private set; } + + public int ReinforcedMaxCount { get; private set; } + + public static Shop? Create(ShopBindingModel? model) + { + if (model == null) + { + return null; + } + return new Shop() + { + Id = model.Id, + Name = model.Name, + Address = model.Address, + ReinforcedMaxCount = model.ReinforcedMaxCount, + DateOpening = model.DateOpening, + Reinforcedies = model.ShopReinforcedies.ToDictionary(x => x.Key, x => x.Value.Item2) + }; + } + public static Shop? Create(XElement element) + { + if (element == null) + { + return null; + } + return new() + { + Id = Convert.ToInt32(element.Attribute("Id")!.Value), + Name = element.Element("Name")!.Value, + Address = element.Element("Address")!.Value, + DateOpening = Convert.ToDateTime(element.Element("DateOpening")!.Value), + ReinforcedMaxCount = Convert.ToInt32(element.Element("ReinforcedMaxCount")!.Value), + Reinforcedies = element.Element("ShopReinforcedies")!.Elements("Reinforced").ToDictionary( + x => Convert.ToInt32(x.Element("Key")?.Value), + x => Convert.ToInt32(x.Element("Value")?.Value)) + }; + } + public void Update(ShopBindingModel? model) + { + if (model == null) + { + return; + } + Name = model.Name; + Address = model.Address; + DateOpening = model.DateOpening; + ReinforcedMaxCount = model.ReinforcedMaxCount; + Reinforcedies = model.ShopReinforcedies.ToDictionary(x => x.Key, x => x.Value.Item2); + _shopReinforcedies = null; + } + public ShopViewModel GetViewModel => new() + { + Id = Id, + Name = Name, + Address = Address, + ShopReinforcedies = ShopReinforcedies, + DateOpening = DateOpening, + ReinforcedMaxCount = ReinforcedMaxCount, + }; + public XElement GetXElement => new("Shop", + new XAttribute("Id", Id), + new XElement("Name", Name), + new XElement("Address", Address), + new XElement("DateOpening", DateOpening), + new XElement("ReinforcedMaxCount", ReinforcedMaxCount), + new XElement("ShopReinforcedies", Reinforcedies + .Select(x => new XElement("Reinforced", + new XElement("Key", x.Key), + new XElement("Value", x.Value)) + ).ToArray())); + } +} diff --git a/PrecastConcretePlant/PrecastConcretePlantListImplement/DataListSingleton.cs b/PrecastConcretePlant/PrecastConcretePlantListImplement/DataListSingleton.cs index 9353b4e..8c30fd4 100644 --- a/PrecastConcretePlant/PrecastConcretePlantListImplement/DataListSingleton.cs +++ b/PrecastConcretePlant/PrecastConcretePlantListImplement/DataListSingleton.cs @@ -13,11 +13,13 @@ namespace PrecastConcretePlantListImplement public List Components { get; set; } public List Orders { get; set; } public List Reinforceds { get; set; } + public List Shops { get; set; } private DataListSingleton() { Components = new List(); Orders = new List(); Reinforceds = new List(); + Shops = new List(); } public static DataListSingleton GetInstance() { diff --git a/PrecastConcretePlant/PrecastConcretePlantListImplement/Implements/ShopStorage.cs b/PrecastConcretePlant/PrecastConcretePlantListImplement/Implements/ShopStorage.cs new file mode 100644 index 0000000..5a8cbb5 --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantListImplement/Implements/ShopStorage.cs @@ -0,0 +1,117 @@ +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.SearchModels; +using PrecastConcretePlantContracts.StoragesContracts; +using PrecastConcretePlantContracts.ViewModels; +using PrecastConcretePlantDataModels.Models; +using PrecastConcretePlantListImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantListImplement.Implements +{ + public class ShopStorage : IShopStorage + { + private readonly DataListSingleton _source; + public ShopStorage() + { + _source = DataListSingleton.GetInstance(); + } + + 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 SellReinforced(IReinforcedModel model, int quantity) + { + throw new NotImplementedException(); + } + 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.Name == model.Name) || + (model.Id.HasValue && shop.Id == model.Id)) + { + return shop.GetViewModel; + } + } + return null; + } + + public List GetFilteredList(ShopSearchModel model) + { + var result = new List(); + if (string.IsNullOrEmpty(model.Name)) + { + return result; + } + foreach (var shop in _source.Shops) + { + if (shop.Name.Contains(model.Name ?? string.Empty)) + { + result.Add(shop.GetViewModel); + } + } + return result; + } + + public List GetFullList() + { + var result = new List(); + foreach (var shop in _source.Shops) + { + result.Add(shop.GetViewModel); + } + return result; + } + + 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; + } + } +} diff --git a/PrecastConcretePlant/PrecastConcretePlantListImplement/Models/Shop.cs b/PrecastConcretePlant/PrecastConcretePlantListImplement/Models/Shop.cs new file mode 100644 index 0000000..a8895f2 --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantListImplement/Models/Shop.cs @@ -0,0 +1,60 @@ +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.ViewModels; +using PrecastConcretePlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantListImplement.Models +{ + public class Shop : IShopModel + { + public string Name { get; private set; } = string.Empty; + + public string Address { get; private set; } = string.Empty; + + public DateTime DateOpening { get; private set; } + + public Dictionary ShopReinforcedies { get; private set; } = new(); + + public int Id { get; private set; } + + public static Shop? Create(ShopBindingModel? model) + { + if (model == null) + { + return null; + } + return new Shop() + { + Id = model.Id, + Name = model.Name, + Address = model.Address, + DateOpening = model.DateOpening, + ShopReinforcedies = new() + }; + } + public void Update(ShopBindingModel? model) + { + if (model == null) + { + return; + } + Name = model.Name; + Address = model.Address; + DateOpening = model.DateOpening; + ShopReinforcedies = model.ShopReinforcedies; + } + public ShopViewModel GetViewModel => new() + { + Id = Id, + Name = Name, + Address = Address, + ShopReinforcedies = ShopReinforcedies, + DateOpening = DateOpening, + }; + public int ReinforcedMaxCount => throw new NotImplementedException(); + } +}