diff --git a/SoftwareInstallation/FormComponent.Designer.cs b/SoftwareInstallation/FormComponent.Designer.cs index fae63e4..58c17c0 100644 --- a/SoftwareInstallation/FormComponent.Designer.cs +++ b/SoftwareInstallation/FormComponent.Designer.cs @@ -1,4 +1,4 @@ -namespace SoftwareInstallation.Forms +namespace SoftwareInstallationView { partial class FormComponent { @@ -28,95 +28,91 @@ /// private void InitializeComponent() { - buttonSave = new Button(); - buttonCancel = new Button(); - label1 = new Label(); - label2 = new Label(); + labelName = new Label(); textBoxName = new TextBox(); textBoxCost = new TextBox(); + labelCost = new Label(); + buttonSave = new Button(); + buttonCancel = new Button(); SuspendLayout(); // - // buttonSave + // labelName // - buttonSave.Location = new Point(217, 119); - buttonSave.Margin = new Padding(3, 4, 3, 4); - buttonSave.Name = "buttonSave"; - buttonSave.Size = new Size(98, 34); - buttonSave.TabIndex = 0; - buttonSave.Text = "Сохранить"; - buttonSave.UseVisualStyleBackColor = true; - buttonSave.Click += buttonSave_Click; - // - // buttonCancel - // - buttonCancel.Location = new Point(325, 119); - buttonCancel.Margin = new Padding(3, 4, 3, 4); - buttonCancel.Name = "buttonCancel"; - buttonCancel.Size = new Size(98, 34); - buttonCancel.TabIndex = 1; - buttonCancel.Text = "Отмена"; - buttonCancel.UseVisualStyleBackColor = true; - buttonCancel.Click += buttonCancel_Click; - // - // label1 - // - label1.AutoSize = true; - label1.Location = new Point(24, 30); - label1.Name = "label1"; - label1.Size = new Size(80, 20); - label1.TabIndex = 2; - label1.Text = "Название:"; - // - // label2 - // - label2.AutoSize = true; - label2.Location = new Point(24, 69); - label2.Name = "label2"; - label2.Size = new Size(48, 20); - label2.TabIndex = 3; - label2.Text = "Цена:"; + labelName.AutoSize = true; + labelName.Location = new Point(11, 9); + labelName.Name = "labelName"; + labelName.Size = new Size(80, 20); + labelName.TabIndex = 0; + labelName.Text = "Название:"; // // textBoxName // - textBoxName.Location = new Point(118, 26); - textBoxName.Margin = new Padding(3, 4, 3, 4); + textBoxName.Location = new Point(98, 9); textBoxName.Name = "textBoxName"; - textBoxName.Size = new Size(305, 27); - textBoxName.TabIndex = 4; + textBoxName.Size = new Size(366, 27); + textBoxName.TabIndex = 1; // // textBoxCost // - textBoxCost.Location = new Point(118, 65); - textBoxCost.Margin = new Padding(3, 4, 3, 4); + textBoxCost.Location = new Point(98, 43); textBoxCost.Name = "textBoxCost"; - textBoxCost.Size = new Size(186, 27); - textBoxCost.TabIndex = 5; + textBoxCost.Size = new Size(133, 27); + textBoxCost.TabIndex = 3; + // + // labelCost + // + labelCost.AutoSize = true; + labelCost.Location = new Point(11, 43); + labelCost.Name = "labelCost"; + labelCost.Size = new Size(45, 20); + labelCost.TabIndex = 2; + labelCost.Text = "Цена"; + // + // buttonSave + // + buttonSave.Location = new Point(171, 91); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(130, 40); + buttonSave.TabIndex = 4; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += ButtonSave_Click; + // + // buttonCancel + // + buttonCancel.Location = new Point(328, 91); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(136, 40); + buttonCancel.TabIndex = 5; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += ButtonCancel_Click; // // FormComponent // AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(462, 174); - Controls.Add(textBoxCost); - Controls.Add(textBoxName); - Controls.Add(label2); - Controls.Add(label1); + ClientSize = new Size(478, 141); Controls.Add(buttonCancel); Controls.Add(buttonSave); - Margin = new Padding(3, 4, 3, 4); + Controls.Add(textBoxCost); + Controls.Add(labelCost); + Controls.Add(textBoxName); + Controls.Add(labelName); Name = "FormComponent"; Text = "Компонент"; + Load += FormComponent_Load; ResumeLayout(false); PerformLayout(); } #endregion - private Button buttonSave; - private Button buttonCancel; - private Label label1; - private Label label2; + private Label labelName; private TextBox textBoxName; private TextBox textBoxCost; + private Label labelCost; + private Button buttonSave; + private Button buttonCancel; } } \ No newline at end of file diff --git a/SoftwareInstallation/FormComponent.cs b/SoftwareInstallation/FormComponent.cs index 30b4bc0..c62d9d5 100644 --- a/SoftwareInstallation/FormComponent.cs +++ b/SoftwareInstallation/FormComponent.cs @@ -1,4 +1,8 @@ -using System; +using Microsoft.Extensions.Logging; +using SoftwareInstallationContracts.BindingModels; +using SoftwareInstallationContracts.BusinessLogicsContracts; +using SoftwareInstallationContracts.SearchModels; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; @@ -7,13 +11,8 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; -using Microsoft.Extensions.Logging; -using SoftwareInstallationContracts.BusinessLogicsContracts; -using Microsoft.VisualBasic.Logging; -using SoftwareInstallationContracts.SearchModels; -using SoftwareInstallationContracts.BindingModels; -namespace SoftwareInstallation.Forms +namespace SoftwareInstallationView { public partial class FormComponent : Form { @@ -21,6 +20,7 @@ namespace SoftwareInstallation.Forms private readonly IComponentLogic _logic; private int? _id; public int Id { set { _id = value; } } + public FormComponent(ILogger logger, IComponentLogic logic) { InitializeComponent(); @@ -34,7 +34,7 @@ namespace SoftwareInstallation.Forms { try { - _logger.LogInformation("Получение компонента"); + _logger.LogInformation("Получение ингридиента"); var view = _logic.ReadElement(new ComponentSearchModel { Id = _id.Value @@ -47,21 +47,20 @@ namespace SoftwareInstallation.Forms } catch (Exception ex) { - _logger.LogError(ex, "Ошибка получения компонента"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, - MessageBoxIcon.Error); + _logger.LogError(ex, "Ошибка получения ингридиента"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } - private void buttonSave_Click(object sender, EventArgs e) + private void ButtonSave_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(textBoxName.Text)) { MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } - _logger.LogInformation("Сохранение компонента"); + _logger.LogInformation("Сохранение ингридиента"); try { var model = new ComponentBindingModel @@ -81,12 +80,12 @@ namespace SoftwareInstallation.Forms } catch (Exception ex) { - _logger.LogError(ex, "Ошибка сохранения компонента"); + _logger.LogError(ex, "Ошибка сохранения ингридиента"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } - private void buttonCancel_Click(object sender, EventArgs e) + private void ButtonCancel_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; Close(); diff --git a/SoftwareInstallation/FormComponents.Designer.cs b/SoftwareInstallation/FormComponents.Designer.cs index 8be76d3..2813dab 100644 --- a/SoftwareInstallation/FormComponents.Designer.cs +++ b/SoftwareInstallation/FormComponents.Designer.cs @@ -1,4 +1,4 @@ -namespace SoftwareInstallation.Forms +namespace SoftwareInstallationView { partial class FormComponents { @@ -29,93 +29,101 @@ private void InitializeComponent() { dataGridView = new DataGridView(); + ToolsPanel = new Panel(); + buttonUpdate = new Button(); + buttonDelete = new Button(); + buttonEdit = new Button(); buttonAdd = new Button(); - buttonUpd = new Button(); - buttonDel = new Button(); - buttonRef = new Button(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + ToolsPanel.SuspendLayout(); SuspendLayout(); // // dataGridView // + dataGridView.AllowUserToAddRows = false; + dataGridView.AllowUserToDeleteRows = false; dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; - dataGridView.Location = new Point(-1, -2); - dataGridView.Margin = new Padding(3, 4, 3, 4); + dataGridView.Location = new Point(11, 12); dataGridView.Name = "dataGridView"; dataGridView.ReadOnly = true; dataGridView.RowHeadersWidth = 51; - dataGridView.RowTemplate.Height = 24; - dataGridView.Size = new Size(499, 568); + dataGridView.RowTemplate.Height = 29; + dataGridView.Size = new Size(590, 427); dataGridView.TabIndex = 0; // + // ToolsPanel + // + ToolsPanel.Controls.Add(buttonUpdate); + ToolsPanel.Controls.Add(buttonDelete); + ToolsPanel.Controls.Add(buttonEdit); + ToolsPanel.Controls.Add(buttonAdd); + ToolsPanel.Location = new Point(608, 12); + ToolsPanel.Name = "ToolsPanel"; + ToolsPanel.Size = new Size(181, 427); + ToolsPanel.TabIndex = 1; + // + // buttonUpdate + // + buttonUpdate.Location = new Point(31, 205); + buttonUpdate.Name = "buttonUpdate"; + buttonUpdate.Size = new Size(126, 36); + buttonUpdate.TabIndex = 3; + buttonUpdate.Text = "Обновить"; + buttonUpdate.UseVisualStyleBackColor = true; + buttonUpdate.Click += ButtonRef_Click; + // + // buttonDelete + // + buttonDelete.Location = new Point(31, 141); + buttonDelete.Name = "buttonDelete"; + buttonDelete.Size = new Size(126, 36); + buttonDelete.TabIndex = 2; + buttonDelete.Text = "Удалить"; + buttonDelete.UseVisualStyleBackColor = true; + buttonDelete.Click += ButtonDel_Click; + // + // buttonEdit + // + buttonEdit.Location = new Point(31, 76); + buttonEdit.Name = "buttonEdit"; + buttonEdit.Size = new Size(126, 36); + buttonEdit.TabIndex = 1; + buttonEdit.Text = "Изменить"; + buttonEdit.UseVisualStyleBackColor = true; + buttonEdit.Click += ButtonUpd_Click; + // // buttonAdd // - buttonAdd.Location = new Point(525, 48); - buttonAdd.Margin = new Padding(3, 4, 3, 4); + buttonAdd.Location = new Point(31, 16); buttonAdd.Name = "buttonAdd"; - buttonAdd.Size = new Size(125, 35); - buttonAdd.TabIndex = 1; + buttonAdd.Size = new Size(126, 36); + buttonAdd.TabIndex = 0; buttonAdd.Text = "Добавить"; buttonAdd.UseVisualStyleBackColor = true; - buttonAdd.Click += buttonAdd_Click; - // - // buttonUpd - // - buttonUpd.Location = new Point(525, 98); - buttonUpd.Margin = new Padding(3, 4, 3, 4); - buttonUpd.Name = "buttonUpd"; - buttonUpd.Size = new Size(125, 35); - buttonUpd.TabIndex = 2; - buttonUpd.Text = "Изменить"; - buttonUpd.UseVisualStyleBackColor = true; - buttonUpd.Click += buttonUpd_Click; - // - // buttonDel - // - buttonDel.Location = new Point(525, 150); - buttonDel.Margin = new Padding(3, 4, 3, 4); - buttonDel.Name = "buttonDel"; - buttonDel.Size = new Size(125, 35); - buttonDel.TabIndex = 3; - buttonDel.Text = "Удалить"; - buttonDel.UseVisualStyleBackColor = true; - buttonDel.Click += buttonDel_Click; - // - // buttonRef - // - buttonRef.Location = new Point(525, 201); - buttonRef.Margin = new Padding(3, 4, 3, 4); - buttonRef.Name = "buttonRef"; - buttonRef.Size = new Size(125, 35); - buttonRef.TabIndex = 4; - buttonRef.Text = "Обновить"; - buttonRef.UseVisualStyleBackColor = true; - buttonRef.Click += buttonRef_Click; + buttonAdd.Click += ButtonAdd_Click; // // FormComponents // AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(676, 562); - Controls.Add(buttonRef); - Controls.Add(buttonDel); - Controls.Add(buttonUpd); - Controls.Add(buttonAdd); + ClientSize = new Size(800, 451); + Controls.Add(ToolsPanel); Controls.Add(dataGridView); - Margin = new Padding(3, 4, 3, 4); Name = "FormComponents"; - Text = "Список компонентов"; + Text = "Компоненты"; Load += FormComponents_Load; ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ToolsPanel.ResumeLayout(false); ResumeLayout(false); } #endregion private DataGridView dataGridView; + private Panel ToolsPanel; + private Button buttonUpdate; + private Button buttonDelete; + private Button buttonEdit; private Button buttonAdd; - private Button buttonUpd; - private Button buttonDel; - private Button buttonRef; } } \ No newline at end of file diff --git a/SoftwareInstallation/FormComponents.cs b/SoftwareInstallation/FormComponents.cs index b79da69..ad09b43 100644 --- a/SoftwareInstallation/FormComponents.cs +++ b/SoftwareInstallation/FormComponents.cs @@ -1,22 +1,15 @@ -using SoftwareInstallationContracts.BindingModels; +using Microsoft.Extensions.Logging; +using SoftwareInstallation; +using SoftwareInstallationContracts.BindingModels; using SoftwareInstallationContracts.BusinessLogicsContracts; -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows.Forms; -namespace SoftwareInstallation.Forms +namespace SoftwareInstallationView { public partial class FormComponents : Form { private readonly ILogger _logger; private readonly IComponentLogic _logic; + public FormComponents(ILogger logger, IComponentLogic logic) { InitializeComponent(); @@ -38,18 +31,20 @@ namespace SoftwareInstallation.Forms { dataGridView.DataSource = list; dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["ComponentName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + dataGridView.Columns["ComponentName"].AutoSizeMode = + DataGridViewAutoSizeColumnMode.Fill; } - _logger.LogInformation("Загрузка компонентов"); + _logger.LogInformation("Загрузка ингридиентов"); } catch (Exception ex) { - _logger.LogError(ex, "Ошибка загрузки компонентов"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError(ex, "Ошибка загрузки ингридиентов"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); } } - private void buttonAdd_Click(object sender, EventArgs e) + private void ButtonAdd_Click(object sender, EventArgs e) { var service = Program.ServiceProvider?.GetService(typeof(FormComponent)); if (service is FormComponent form) @@ -61,14 +56,15 @@ namespace SoftwareInstallation.Forms } } - private void buttonUpd_Click(object sender, EventArgs e) + private void ButtonUpd_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) { var service = Program.ServiceProvider?.GetService(typeof(FormComponent)); if (service is FormComponent form) { - form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + form.Id = + Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); if (form.ShowDialog() == DialogResult.OK) { LoadData(); @@ -77,15 +73,16 @@ namespace SoftwareInstallation.Forms } } - private void buttonDel_Click(object sender, EventArgs e) + private void ButtonDel_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) { - if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + if (MessageBox.Show("Удалить запись?", "Вопрос", + MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { int id = - Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Удаление компонента"); + Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Удаление ингридиента"); try { if (!_logic.Delete(new ComponentBindingModel @@ -99,13 +96,15 @@ namespace SoftwareInstallation.Forms } catch (Exception ex) { - _logger.LogError(ex, "Ошибка удаления компонента"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError(ex, "Ошибка удаления ингридиента"); + MessageBox.Show(ex.Message, "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); } } } } - private void buttonRef_Click(object sender, EventArgs e) + + private void ButtonRef_Click(object sender, EventArgs e) { LoadData(); } diff --git a/SoftwareInstallation/FormCreateOrder.Designer.cs b/SoftwareInstallation/FormCreateOrder.Designer.cs index dedb200..f21401d 100644 --- a/SoftwareInstallation/FormCreateOrder.Designer.cs +++ b/SoftwareInstallation/FormCreateOrder.Designer.cs @@ -1,4 +1,4 @@ -namespace SoftwareInstallation.Forms +namespace SoftwareInstallationView { partial class FormCreateOrder { @@ -28,101 +28,101 @@ /// private void InitializeComponent() { - label1 = new Label(); - label2 = new Label(); - label3 = new Label(); + labelPackage = new Label(); + comboBoxPackage = new ComboBox(); + labelCount = new Label(); textBoxCount = new TextBox(); - comboBoxPackage= new ComboBox(); + labelSum = new Label(); textBoxSum = new TextBox(); - buttonSave = new Button(); buttonCancel = new Button(); + buttonSave = new Button(); SuspendLayout(); // - // label1 + // labelPackage // - label1.AutoSize = true; - label1.Location = new Point(19, 12); - label1.Name = "label1"; - label1.Size = new Size(56, 15); - label1.TabIndex = 0; - label1.Text = "Изделие:"; - // - // label2 - // - label2.AutoSize = true; - label2.Location = new Point(19, 44); - label2.Name = "label2"; - label2.Size = new Size(75, 15); - label2.TabIndex = 1; - label2.Text = "Количество:"; - // - // label3 - // - label3.AutoSize = true; - label3.Location = new Point(19, 70); - label3.Name = "label3"; - label3.Size = new Size(48, 15); - label3.TabIndex = 2; - label3.Text = "Сумма:"; - // - // textBoxCount - // - textBoxCount.Location = new Point(103, 41); - textBoxCount.Name = "textBoxCount"; - textBoxCount.Size = new Size(246, 23); - textBoxCount.TabIndex = 3; - textBoxCount.TextChanged += textBoxCount_TextChanged; + labelPackage.AutoSize = true; + labelPackage.Location = new Point(11, 15); + labelPackage.Name = "labelPackage"; + labelPackage.Size = new Size(71, 20); + labelPackage.TabIndex = 0; + labelPackage.Text = "Изделие:"; // // comboBoxPackage // comboBoxPackage.FormattingEnabled = true; - comboBoxPackage.Location = new Point(103, 10); + comboBoxPackage.Location = new Point(115, 12); comboBoxPackage.Name = "comboBoxPackage"; - comboBoxPackage.Size = new Size(246, 23); - comboBoxPackage.TabIndex = 4; + comboBoxPackage.Size = new Size(358, 28); + comboBoxPackage.TabIndex = 1; comboBoxPackage.SelectedIndexChanged += ComboBoxPackage_SelectedIndexChanged; // + // labelCount + // + labelCount.AutoSize = true; + labelCount.Location = new Point(11, 49); + labelCount.Name = "labelCount"; + labelCount.Size = new Size(97, 20); + labelCount.TabIndex = 2; + labelCount.Text = "Количество: "; + // + // textBoxCount + // + textBoxCount.Location = new Point(115, 45); + textBoxCount.Name = "textBoxCount"; + textBoxCount.Size = new Size(358, 27); + textBoxCount.TabIndex = 3; + textBoxCount.TextChanged += TextBoxCount_TextChanged; + // + // labelSum + // + labelSum.AutoSize = true; + labelSum.Location = new Point(11, 80); + labelSum.Name = "labelSum"; + labelSum.Size = new Size(62, 20); + labelSum.TabIndex = 4; + labelSum.Text = "Сумма: "; + // // textBoxSum // - textBoxSum.Location = new Point(103, 70); + textBoxSum.Location = new Point(115, 80); textBoxSum.Name = "textBoxSum"; textBoxSum.ReadOnly = true; - textBoxSum.Size = new Size(246, 23); + textBoxSum.Size = new Size(358, 27); textBoxSum.TabIndex = 5; // - // buttonSave - // - buttonSave.Location = new Point(150, 101); - buttonSave.Name = "buttonSave"; - buttonSave.Size = new Size(94, 26); - buttonSave.TabIndex = 6; - buttonSave.Text = "Сохранить"; - buttonSave.UseVisualStyleBackColor = true; - buttonSave.Click += buttonSave_Click; - // // buttonCancel // - buttonCancel.Location = new Point(249, 101); + buttonCancel.Location = new Point(337, 113); buttonCancel.Name = "buttonCancel"; - buttonCancel.Size = new Size(94, 26); - buttonCancel.TabIndex = 7; + buttonCancel.Size = new Size(110, 32); + buttonCancel.TabIndex = 6; buttonCancel.Text = "Отмена"; buttonCancel.UseVisualStyleBackColor = true; - buttonCancel.Click += buttonCancel_Click; + buttonCancel.Click += ButtonCancel_Click; + // + // buttonSave + // + buttonSave.Location = new Point(221, 113); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(110, 32); + buttonSave.TabIndex = 7; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += ButtonSave_Click; // // FormCreateOrder // - AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(374, 136); - Controls.Add(buttonCancel); + ClientSize = new Size(485, 157); Controls.Add(buttonSave); + Controls.Add(buttonCancel); Controls.Add(textBoxSum); - Controls.Add(comboBoxPackage); + Controls.Add(labelSum); Controls.Add(textBoxCount); - Controls.Add(label3); - Controls.Add(label2); - Controls.Add(label1); + Controls.Add(labelCount); + Controls.Add(comboBoxPackage); + Controls.Add(labelPackage); Name = "FormCreateOrder"; Text = "Заказ"; Load += FormCreateOrder_Load; @@ -132,13 +132,13 @@ #endregion - private Label label1; - private Label label2; - private Label label3; - private TextBox textBoxCount; + private Label labelPackage; private ComboBox comboBoxPackage; + private Label labelCount; + private TextBox textBoxCount; + private Label labelSum; private TextBox textBoxSum; - private Button buttonSave; private Button buttonCancel; + private Button buttonSave; } } \ No newline at end of file diff --git a/SoftwareInstallation/FormCreateOrder.cs b/SoftwareInstallation/FormCreateOrder.cs index 2779d64..c44aed2 100644 --- a/SoftwareInstallation/FormCreateOrder.cs +++ b/SoftwareInstallation/FormCreateOrder.cs @@ -1,7 +1,8 @@ -using SoftwareInstallationContracts.BindingModels; +using Microsoft.Extensions.Logging; +using SoftwareInstallationContracts.BindingModels; using SoftwareInstallationContracts.BusinessLogicsContracts; using SoftwareInstallationContracts.SearchModels; -using Microsoft.Extensions.Logging; +using SoftwareInstallationContracts.ViewModels; using System; using System.Collections.Generic; using System.ComponentModel; @@ -12,13 +13,15 @@ using System.Text; using System.Threading.Tasks; using System.Windows.Forms; -namespace SoftwareInstallation.Forms +namespace SoftwareInstallationView { public partial class FormCreateOrder : Form { private readonly ILogger _logger; private readonly IPackageLogic _logicP; private readonly IOrderLogic _logicO; + private List? _list; + public FormCreateOrder(ILogger logger, IPackageLogic logicP, IOrderLogic logicO) { InitializeComponent(); @@ -29,23 +32,17 @@ namespace SoftwareInstallation.Forms private void FormCreateOrder_Load(object sender, EventArgs e) { - try + _list = _logicP.ReadList(null); + if (_list != null) { - var list = _logicP.ReadList(null); - if (list != null) - { - comboBoxPackage.DisplayMember = "PackageName"; - comboBoxPackage.ValueMember = "Id"; - comboBoxPackage.DataSource = list; - comboBoxPackage.SelectedItem = null; - _logger.LogInformation("Загрузка изделий для заказа"); - } - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки списка изделий"); + comboBoxPackage.DisplayMember = "PackageName"; + comboBoxPackage.ValueMember = "Id"; + comboBoxPackage.DataSource = _list; + comboBoxPackage.SelectedItem = null; + _logger.LogInformation("Загрузка пиццы для заказа"); } } + private void CalcSum() { if (comboBoxPackage.SelectedValue != null && !string.IsNullOrEmpty(textBoxCount.Text)) @@ -68,7 +65,8 @@ namespace SoftwareInstallation.Forms } } } - private void textBoxCount_TextChanged(object sender, EventArgs e) + + private void TextBoxCount_TextChanged(object sender, EventArgs e) { CalcSum(); } @@ -78,7 +76,7 @@ namespace SoftwareInstallation.Forms CalcSum(); } - private void buttonSave_Click(object sender, EventArgs e) + private void ButtonSave_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(textBoxCount.Text)) { @@ -87,7 +85,7 @@ namespace SoftwareInstallation.Forms } if (comboBoxPackage.SelectedValue == null) { - MessageBox.Show("Выберите изделие", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("Выберите пиццу", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } _logger.LogInformation("Создание заказа"); @@ -109,15 +107,15 @@ namespace SoftwareInstallation.Forms } catch (Exception ex) { - _logger.LogError(ex, "Ошибка создания заказа"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError(ex, "Ошибка создания заказа"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } - private void buttonCancel_Click(object sender, EventArgs e) + private void ButtonCancel_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; Close(); } - } } diff --git a/SoftwareInstallation/FormCreateSupply.Designer.cs b/SoftwareInstallation/FormCreateSupply.Designer.cs new file mode 100644 index 0000000..b0dc380 --- /dev/null +++ b/SoftwareInstallation/FormCreateSupply.Designer.cs @@ -0,0 +1,143 @@ +namespace SoftwareInstallationView +{ + partial class FormCreateSupply + { + /// + /// 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.labelShop = new System.Windows.Forms.Label(); + this.labelPackage = new System.Windows.Forms.Label(); + this.comboBoxPackage = new System.Windows.Forms.ComboBox(); + this.labelCount = new System.Windows.Forms.Label(); + this.textBoxCount = new System.Windows.Forms.TextBox(); + this.buttonCancel = new System.Windows.Forms.Button(); + this.buttonSave = new System.Windows.Forms.Button(); + this.SuspendLayout(); + // + // comboBoxShop + // + this.comboBoxShop.FormattingEnabled = true; + this.comboBoxShop.Location = new System.Drawing.Point(115, 12); + this.comboBoxShop.Name = "comboBoxShop"; + this.comboBoxShop.Size = new System.Drawing.Size(344, 28); + this.comboBoxShop.TabIndex = 0; + // + // labelShop + // + this.labelShop.AutoSize = true; + this.labelShop.Location = new System.Drawing.Point(12, 15); + this.labelShop.Name = "labelShop"; + this.labelShop.Size = new System.Drawing.Size(76, 20); + this.labelShop.TabIndex = 1; + this.labelShop.Text = "Магазин: "; + // + // labelPackage + // + this.labelPackage.AutoSize = true; + this.labelPackage.Location = new System.Drawing.Point(12, 49); + this.labelPackage.Name = "labelPackage"; + this.labelPackage.Size = new System.Drawing.Size(75, 20); + this.labelPackage.TabIndex = 2; + this.labelPackage.Text = "Изделие: "; + // + // comboBoxPackage + // + this.comboBoxPackage.FormattingEnabled = true; + this.comboBoxPackage.Location = new System.Drawing.Point(115, 46); + this.comboBoxPackage.Name = "comboBoxPackage"; + this.comboBoxPackage.Size = new System.Drawing.Size(344, 28); + this.comboBoxPackage.TabIndex = 3; + // + // labelCount + // + this.labelCount.AutoSize = true; + this.labelCount.Location = new System.Drawing.Point(12, 83); + this.labelCount.Name = "labelCount"; + this.labelCount.Size = new System.Drawing.Size(97, 20); + this.labelCount.TabIndex = 4; + this.labelCount.Text = "Количество: "; + // + // textBoxCount + // + this.textBoxCount.Location = new System.Drawing.Point(115, 80); + this.textBoxCount.Name = "textBoxCount"; + this.textBoxCount.Size = new System.Drawing.Size(344, 27); + this.textBoxCount.TabIndex = 5; + // + // buttonCancel + // + this.buttonCancel.Location = new System.Drawing.Point(300, 113); + this.buttonCancel.Name = "buttonCancel"; + this.buttonCancel.Size = new System.Drawing.Size(116, 39); + this.buttonCancel.TabIndex = 6; + this.buttonCancel.Text = "Отмена"; + this.buttonCancel.UseVisualStyleBackColor = true; + this.buttonCancel.Click += new System.EventHandler(this.ButtonCancel_Click); + // + // buttonSave + // + this.buttonSave.Location = new System.Drawing.Point(168, 113); + this.buttonSave.Name = "buttonSave"; + this.buttonSave.Size = new System.Drawing.Size(116, 39); + this.buttonSave.TabIndex = 7; + this.buttonSave.Text = "Сохранить"; + this.buttonSave.UseVisualStyleBackColor = true; + this.buttonSave.Click += new System.EventHandler(this.ButtonSave_Click); + // + // FormCreateSupply + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(471, 164); + this.Controls.Add(this.buttonSave); + this.Controls.Add(this.buttonCancel); + this.Controls.Add(this.textBoxCount); + this.Controls.Add(this.labelCount); + this.Controls.Add(this.comboBoxPackage); + this.Controls.Add(this.labelPackage); + this.Controls.Add(this.labelShop); + this.Controls.Add(this.comboBoxShop); + this.Name = "FormCreateSupply"; + this.Text = "Создание поставки"; + this.Load += new System.EventHandler(this.FormCreateSupply_Load); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private ComboBox comboBoxShop; + private Label labelShop; + private Label labelPackage; + private ComboBox comboBoxPackage; + private Label labelCount; + private TextBox textBoxCount; + private Button buttonCancel; + private Button buttonSave; + } +} \ No newline at end of file diff --git a/SoftwareInstallation/FormCreateSupply.cs b/SoftwareInstallation/FormCreateSupply.cs new file mode 100644 index 0000000..d117b7a --- /dev/null +++ b/SoftwareInstallation/FormCreateSupply.cs @@ -0,0 +1,99 @@ +using Microsoft.Extensions.Logging; +using SoftwareInstallationContracts.BindingModels; +using SoftwareInstallationContracts.BusinessLogicsContracts; +using SoftwareInstallationContracts.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; +using static System.Windows.Forms.VisualStyles.VisualStyleElement; + +namespace SoftwareInstallationView +{ + public partial class FormCreateSupply : Form + { + private readonly ILogger _logger; + private readonly IPackageLogic _logicP; + private readonly IShopLogic _logicS; + private List _shopList = new List(); + private List _pizzaList = new List(); + + public FormCreateSupply(ILogger logger, IPackageLogic logicP, IShopLogic logicS) + { + InitializeComponent(); + _logger = logger; + _logicP = logicP; + _logicS = logicS; + } + + private void FormCreateSupply_Load(object sender, EventArgs e) + { + _shopList = _logicS.ReadList(null); + _pizzaList = _logicP.ReadList(null); + if (_shopList != null) + { + comboBoxShop.DisplayMember = "ShopName"; + comboBoxShop.ValueMember = "Id"; + comboBoxShop.DataSource = _shopList; + comboBoxShop.SelectedItem = null; + _logger.LogInformation("Загрузка магазинов для поставок"); + } + if (_pizzaList != null) + { + comboBoxPackage.DisplayMember = "PackageName"; + comboBoxPackage.ValueMember = "Id"; + comboBoxPackage.DataSource = _pizzaList; + comboBoxPackage.SelectedItem = null; + _logger.LogInformation("Загрузка пиццы для поставок"); + } + } + + private void ButtonSave_Click(object sender, EventArgs e) + { + if (comboBoxShop.SelectedValue == null) + { + MessageBox.Show("Выберите магазин", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (comboBoxPackage.SelectedValue == null) + { + MessageBox.Show("Выберите изделие", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Создание поставки"); + try + { + var operationResult = _logicS.MakeSupply(new SupplyBindingModel + { + ShopId = Convert.ToInt32(comboBoxShop.SelectedValue), + PackageId = Convert.ToInt32(comboBoxPackage.SelectedValue), + Count = Convert.ToInt32(textBoxCount.Text) + }); + if (!operationResult) + { + throw new Exception("Ошибка при создании поставки. Дополнительная информация в логах."); + } + MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + Close(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка создания поставки"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ButtonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } +} diff --git a/SoftwareInstallation/FormCreateSupply.resx b/SoftwareInstallation/FormCreateSupply.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/SoftwareInstallation/FormCreateSupply.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/SoftwareInstallation/FormMain.Designer.cs b/SoftwareInstallation/FormMain.Designer.cs index ddf56f8..bf6e25c 100644 --- a/SoftwareInstallation/FormMain.Designer.cs +++ b/SoftwareInstallation/FormMain.Designer.cs @@ -1,4 +1,4 @@ -namespace SoftwareInstallation.Forms +namespace SoftwareInstallationView { partial class FormMain { @@ -28,141 +28,165 @@ /// private void InitializeComponent() { - System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormMain)); - toolStrip1 = new ToolStrip(); - toolStripDropDownButton1 = new ToolStripDropDownButton(); - компонентыToolStripMenuItem = new ToolStripMenuItem(); - ПутёвкиToolStripMenuItem = new ToolStripMenuItem(); + menuStrip1 = new MenuStrip(); + bookToolStripMenuItem = new ToolStripMenuItem(); + ingridientsToolStripMenuItem = new ToolStripMenuItem(); + pizzasToolStripMenuItem = new ToolStripMenuItem(); + shopsToolStripMenuItem = new ToolStripMenuItem(); + operationToolStripMenuItem = new ToolStripMenuItem(); + transactionToolStripMenuItem = new ToolStripMenuItem(); + продажаToolStripMenuItem = new ToolStripMenuItem(); + dataGridView = new DataGridView(); buttonCreateOrder = new Button(); buttonTakeOrderInWork = new Button(); buttonOrderReady = new Button(); buttonIssuedOrder = new Button(); buttonRef = new Button(); - dataGridView = new DataGridView(); - toolStrip1.SuspendLayout(); + menuStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); SuspendLayout(); // - // toolStrip1 + // menuStrip1 // - toolStrip1.ImageScalingSize = new Size(20, 20); - toolStrip1.Items.AddRange(new ToolStripItem[] { toolStripDropDownButton1 }); - toolStrip1.Location = new Point(0, 0); - toolStrip1.Name = "toolStrip1"; - toolStrip1.Size = new Size(1107, 27); - toolStrip1.TabIndex = 0; - toolStrip1.Text = "toolStrip1"; + menuStrip1.ImageScalingSize = new Size(20, 20); + menuStrip1.Items.AddRange(new ToolStripItem[] { bookToolStripMenuItem, operationToolStripMenuItem }); + menuStrip1.Location = new Point(0, 0); + menuStrip1.Name = "menuStrip1"; + menuStrip1.Padding = new Padding(6, 3, 0, 3); + menuStrip1.Size = new Size(1313, 30); + menuStrip1.TabIndex = 0; + menuStrip1.Text = "menuStrip1"; // - // toolStripDropDownButton1 + // bookToolStripMenuItem // - toolStripDropDownButton1.DisplayStyle = ToolStripItemDisplayStyle.Text; - toolStripDropDownButton1.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, ПутёвкиToolStripMenuItem }); - toolStripDropDownButton1.Image = (Image)resources.GetObject("toolStripDropDownButton1.Image"); - toolStripDropDownButton1.ImageTransparentColor = Color.Magenta; - toolStripDropDownButton1.Name = "toolStripDropDownButton1"; - toolStripDropDownButton1.Size = new Size(108, 24); - toolStripDropDownButton1.Text = "Справочник"; + bookToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { ingridientsToolStripMenuItem, pizzasToolStripMenuItem, shopsToolStripMenuItem }); + bookToolStripMenuItem.Name = "bookToolStripMenuItem"; + bookToolStripMenuItem.Size = new Size(108, 24); + bookToolStripMenuItem.Text = "Справочник"; // - // компонентыToolStripMenuItem + // ingridientsToolStripMenuItem // - компонентыToolStripMenuItem.Name = "компонентыToolStripMenuItem"; - компонентыToolStripMenuItem.Size = new Size(224, 26); - компонентыToolStripMenuItem.Text = "Компоненты"; - компонентыToolStripMenuItem.Click += компонентыToolStripMenuItem_Click; + ingridientsToolStripMenuItem.Name = "ingridientsToolStripMenuItem"; + ingridientsToolStripMenuItem.Size = new Size(224, 26); + ingridientsToolStripMenuItem.Text = "Компоненты"; + ingridientsToolStripMenuItem.Click += IngridentsToolStripMenuItem_Click; // - // ПутёвкиToolStripMenuItem + // pizzasToolStripMenuItem // - ПутёвкиToolStripMenuItem.Name = "ПутёвкиToolStripMenuItem"; - ПутёвкиToolStripMenuItem.Size = new Size(224, 26); - ПутёвкиToolStripMenuItem.Text = "ПО"; - ПутёвкиToolStripMenuItem.Click += консервыToolStripMenuItem_Click; + pizzasToolStripMenuItem.Name = "pizzasToolStripMenuItem"; + pizzasToolStripMenuItem.Size = new Size(224, 26); + pizzasToolStripMenuItem.Text = "ПО"; + pizzasToolStripMenuItem.Click += PackagesToolStripMenuItem_Click; // - // buttonCreateOrder + // shopsToolStripMenuItem // - buttonCreateOrder.Location = new Point(914, 75); - buttonCreateOrder.Margin = new Padding(3, 4, 3, 4); - buttonCreateOrder.Name = "buttonCreateOrder"; - buttonCreateOrder.Size = new Size(161, 32); - buttonCreateOrder.TabIndex = 1; - buttonCreateOrder.Text = "Создать заказ"; - buttonCreateOrder.UseVisualStyleBackColor = true; - buttonCreateOrder.Click += buttonCreateOrder_Click; + shopsToolStripMenuItem.Name = "shopsToolStripMenuItem"; + shopsToolStripMenuItem.Size = new Size(224, 26); + shopsToolStripMenuItem.Text = "Магазины"; + shopsToolStripMenuItem.Click += shopsToolStripMenuItem_Click; // - // buttonTakeOrderInWork + // operationToolStripMenuItem // - buttonTakeOrderInWork.Location = new Point(914, 133); - buttonTakeOrderInWork.Margin = new Padding(3, 4, 3, 4); - buttonTakeOrderInWork.Name = "buttonTakeOrderInWork"; - buttonTakeOrderInWork.Size = new Size(161, 32); - buttonTakeOrderInWork.TabIndex = 2; - buttonTakeOrderInWork.Text = "Отдать на выполнение"; - buttonTakeOrderInWork.UseVisualStyleBackColor = true; - buttonTakeOrderInWork.Click += buttonTakeOrderInWork_Click; + operationToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { transactionToolStripMenuItem, продажаToolStripMenuItem }); + operationToolStripMenuItem.Name = "operationToolStripMenuItem"; + operationToolStripMenuItem.Size = new Size(95, 24); + operationToolStripMenuItem.Text = "Операции"; // - // buttonOrderReady + // transactionToolStripMenuItem // - buttonOrderReady.Location = new Point(914, 189); - buttonOrderReady.Margin = new Padding(3, 4, 3, 4); - buttonOrderReady.Name = "buttonOrderReady"; - buttonOrderReady.Size = new Size(161, 32); - buttonOrderReady.TabIndex = 3; - buttonOrderReady.Text = "Заказ готов"; - buttonOrderReady.UseVisualStyleBackColor = true; - buttonOrderReady.Click += buttonOrderReady_Click; + transactionToolStripMenuItem.Name = "transactionToolStripMenuItem"; + transactionToolStripMenuItem.Size = new Size(224, 26); + transactionToolStripMenuItem.Text = "Поставка"; + transactionToolStripMenuItem.Click += transactionToolStripMenuItem_Click; // - // buttonIssuedOrder + // продажаToolStripMenuItem // - buttonIssuedOrder.Location = new Point(914, 241); - buttonIssuedOrder.Margin = new Padding(3, 4, 3, 4); - buttonIssuedOrder.Name = "buttonIssuedOrder"; - buttonIssuedOrder.Size = new Size(161, 32); - buttonIssuedOrder.TabIndex = 4; - buttonIssuedOrder.Text = "Заказ выдан"; - buttonIssuedOrder.UseVisualStyleBackColor = true; - buttonIssuedOrder.Click += buttonIssuedOrder_Click; - // - // buttonRef - // - buttonRef.Location = new Point(914, 296); - buttonRef.Margin = new Padding(3, 4, 3, 4); - buttonRef.Name = "buttonRef"; - buttonRef.Size = new Size(161, 32); - buttonRef.TabIndex = 5; - buttonRef.Text = "Обновить список"; - buttonRef.UseVisualStyleBackColor = true; - buttonRef.Click += buttonRef_Click; + продажаToolStripMenuItem.Name = "продажаToolStripMenuItem"; + продажаToolStripMenuItem.Size = new Size(224, 26); + продажаToolStripMenuItem.Text = "Продажа"; + продажаToolStripMenuItem.Click += SellToolStripMenuItem_Click; // // dataGridView // + dataGridView.AllowUserToAddRows = false; + dataGridView.AllowUserToDeleteRows = false; dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; - dataGridView.Location = new Point(0, 35); - dataGridView.Margin = new Padding(3, 4, 3, 4); + dataGridView.Location = new Point(11, 31); dataGridView.Name = "dataGridView"; dataGridView.ReadOnly = true; dataGridView.RowHeadersWidth = 51; - dataGridView.RowTemplate.Height = 24; - dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; - dataGridView.Size = new Size(872, 580); - dataGridView.TabIndex = 6; + dataGridView.RowTemplate.Height = 29; + dataGridView.Size = new Size(977, 381); + dataGridView.TabIndex = 1; + // + // buttonCreateOrder + // + buttonCreateOrder.Location = new Point(1026, 71); + buttonCreateOrder.Name = "buttonCreateOrder"; + buttonCreateOrder.Size = new Size(247, 29); + buttonCreateOrder.TabIndex = 2; + buttonCreateOrder.Text = "Создать заказ"; + buttonCreateOrder.UseVisualStyleBackColor = true; + buttonCreateOrder.Click += ButtonCreateOrder_Click; + // + // buttonTakeOrderInWork + // + buttonTakeOrderInWork.Location = new Point(1026, 123); + buttonTakeOrderInWork.Name = "buttonTakeOrderInWork"; + buttonTakeOrderInWork.Size = new Size(247, 29); + buttonTakeOrderInWork.TabIndex = 3; + buttonTakeOrderInWork.Text = "Отдать на выполнение"; + buttonTakeOrderInWork.UseVisualStyleBackColor = true; + buttonTakeOrderInWork.Click += ButtonTakeOrderInWork_Click; + // + // buttonOrderReady + // + buttonOrderReady.Location = new Point(1026, 172); + buttonOrderReady.Name = "buttonOrderReady"; + buttonOrderReady.Size = new Size(247, 29); + buttonOrderReady.TabIndex = 4; + buttonOrderReady.Text = "Заказ готов"; + buttonOrderReady.UseVisualStyleBackColor = true; + buttonOrderReady.Click += ButtonOrderReady_Click; + // + // buttonIssuedOrder + // + buttonIssuedOrder.Location = new Point(1026, 225); + buttonIssuedOrder.Name = "buttonIssuedOrder"; + buttonIssuedOrder.Size = new Size(247, 29); + buttonIssuedOrder.TabIndex = 5; + buttonIssuedOrder.Text = "Заказ выдан"; + buttonIssuedOrder.UseVisualStyleBackColor = true; + buttonIssuedOrder.Click += ButtonIssuedOrder_Click; + // + // buttonRef + // + buttonRef.Location = new Point(1026, 280); + buttonRef.Name = "buttonRef"; + buttonRef.Size = new Size(247, 29); + buttonRef.TabIndex = 6; + buttonRef.Text = "Обновить список"; + buttonRef.UseVisualStyleBackColor = true; + buttonRef.Click += ButtonRef_Click; // // FormMain // AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1107, 615); - Controls.Add(dataGridView); + ClientSize = new Size(1313, 425); Controls.Add(buttonRef); Controls.Add(buttonIssuedOrder); Controls.Add(buttonOrderReady); Controls.Add(buttonTakeOrderInWork); Controls.Add(buttonCreateOrder); - Controls.Add(toolStrip1); - Margin = new Padding(3, 4, 3, 4); + Controls.Add(dataGridView); + Controls.Add(menuStrip1); + MainMenuStrip = menuStrip1; Name = "FormMain"; Text = "Установка ПО"; Load += FormMain_Load; - toolStrip1.ResumeLayout(false); - toolStrip1.PerformLayout(); + menuStrip1.ResumeLayout(false); + menuStrip1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); ResumeLayout(false); PerformLayout(); @@ -170,15 +194,19 @@ #endregion - private ToolStrip toolStrip1; + private MenuStrip menuStrip1; + private ToolStripMenuItem bookToolStripMenuItem; + private ToolStripMenuItem ingridientsToolStripMenuItem; + private ToolStripMenuItem pizzasToolStripMenuItem; + private DataGridView dataGridView; private Button buttonCreateOrder; private Button buttonTakeOrderInWork; private Button buttonOrderReady; private Button buttonIssuedOrder; private Button buttonRef; - private DataGridView dataGridView; - private ToolStripDropDownButton toolStripDropDownButton1; - private ToolStripMenuItem компонентыToolStripMenuItem; - private ToolStripMenuItem ПутёвкиToolStripMenuItem; + private ToolStripMenuItem shopsToolStripMenuItem; + private ToolStripMenuItem operationToolStripMenuItem; + private ToolStripMenuItem transactionToolStripMenuItem; + private ToolStripMenuItem продажаToolStripMenuItem; } } \ No newline at end of file diff --git a/SoftwareInstallation/FormMain.cs b/SoftwareInstallation/FormMain.cs index fa780a1..e13c859 100644 --- a/SoftwareInstallation/FormMain.cs +++ b/SoftwareInstallation/FormMain.cs @@ -1,54 +1,49 @@ -using SoftwareInstallationContracts.BindingModels; +using Microsoft.Extensions.Logging; +using SoftwareInstallation; +using SoftwareInstallationContracts.BindingModels; using SoftwareInstallationContracts.BusinessLogicsContracts; -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows.Forms; -namespace SoftwareInstallation.Forms +namespace SoftwareInstallationView { public partial class FormMain : Form { private readonly ILogger _logger; private readonly IOrderLogic _orderLogic; + public FormMain(ILogger logger, IOrderLogic orderLogic) { InitializeComponent(); _logger = logger; _orderLogic = orderLogic; } + private void FormMain_Load(object sender, EventArgs e) { LoadData(); } + private void LoadData() { - _logger.LogInformation("Загрузка заказов"); try { var list = _orderLogic.ReadList(null); - if (list != null) { dataGridView.DataSource = list; dataGridView.Columns["PackageId"].Visible = false; - dataGridView.Columns["PackageName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + dataGridView.Columns["PackageName"].AutoSizeMode = + DataGridViewAutoSizeColumnMode.Fill; } - _logger.LogInformation("Загрузка заказов"); } catch (Exception ex) { _logger.LogError(ex, "Ошибка загрузки заказов"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } - private void компонентыToolStripMenuItem_Click(object sender, EventArgs e) + + private void IngridentsToolStripMenuItem_Click(object sender, EventArgs e) { var service = Program.ServiceProvider?.GetService(typeof(FormComponents)); if (service is FormComponents form) @@ -56,16 +51,17 @@ namespace SoftwareInstallation.Forms form.ShowDialog(); } } - private void консервыToolStripMenuItem_Click(object sender, EventArgs e) + + private void PackagesToolStripMenuItem_Click(object sender, EventArgs e) { var service = Program.ServiceProvider?.GetService(typeof(FormPackages)); - if (service is FormPackages form) { form.ShowDialog(); } } - private void buttonCreateOrder_Click(object sender, EventArgs e) + + private void ButtonCreateOrder_Click(object sender, EventArgs e) { var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); if (service is FormCreateOrder form) @@ -74,17 +70,18 @@ namespace SoftwareInstallation.Forms LoadData(); } } - private void buttonTakeOrderInWork_Click(object sender, EventArgs e) + + private void ButtonTakeOrderInWork_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) { int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id); + _logger.LogInformation("Заказ No{id}. Меняется статус на 'В работе'", id); try { var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel { - Id = id, + Id = id }); if (!operationResult) { @@ -99,16 +96,19 @@ namespace SoftwareInstallation.Forms } } } - private void buttonOrderReady_Click(object sender, EventArgs e) + + private void ButtonOrderReady_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) { - int id = - Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'", id); + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Заказ No{id}. Меняется статус на 'Готов'", id); try { - var operationResult = _orderLogic.FinishOrder(new OrderBindingModel { Id = id }); + var operationResult = _orderLogic.FinishOrder(new OrderBindingModel + { + Id = id + }); if (!operationResult) { throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); @@ -122,12 +122,13 @@ namespace SoftwareInstallation.Forms } } } - private void buttonIssuedOrder_Click(object sender, EventArgs e) + + private void ButtonIssuedOrder_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) { int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id); + _logger.LogInformation("Заказ No{id}. Меняется статус на 'Выдан'", id); try { var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel @@ -138,18 +139,47 @@ namespace SoftwareInstallation.Forms { throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); } - _logger.LogInformation("Заказ №{id} выдан", id); + _logger.LogInformation("Заказ No{id} выдан", id); LoadData(); } catch (Exception ex) { - _logger.LogError(ex, "Ошибка отметки о выдачи заказа"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError(ex, "Ошибка отметки о выдачи заказа"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } - private void buttonRef_Click(object sender, EventArgs e) + + private void ButtonRef_Click(object sender, EventArgs e) { LoadData(); } + + private void shopsToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormShops)); + if (service is FormShops form) + { + form.ShowDialog(); + } + } + + private void transactionToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormCreateSupply)); + if (service is FormCreateSupply form) + { + form.ShowDialog(); + } + } + + private void SellToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormSellPackage)); + if (service is FormSellPackage form) + { + form.ShowDialog(); + } + } } } diff --git a/SoftwareInstallation/FormMain.resx b/SoftwareInstallation/FormMain.resx index 672dbc1..a0623c8 100644 --- a/SoftwareInstallation/FormMain.resx +++ b/SoftwareInstallation/FormMain.resx @@ -117,26 +117,7 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - + 17, 17 - - - - iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8 - YQUAAAAJcEhZcwAAEnQAABJ0Ad5mH3gAAAIDSURBVDhPpZLrS5NhGMb3j4SWh0oRQVExD4gonkDpg4hG - YKxG6WBogkMZKgPNCEVJFBGdGETEvgwyO9DJE5syZw3PIlPEE9pgBCLZ5XvdMB8Ew8gXbl54nuf63dd9 - 0OGSnwCahxbPRNPAPMw9Xpg6ZmF46kZZ0xSKzJPIrhpDWsVnpBhGkKx3nAX8Pv7z1zg8OoY/cITdn4fw - bf/C0kYAN3Ma/w3gWfZL5kzTKBxjWyK2DftwI9tyMYCZKXbNHaD91bLYJrDXsYbrWfUKwJrPE9M2M1Oc - VzOOpHI7Jr376Hi9ogHqFIANO0/MmmmbmSmm9a8ze+I4MrNWAdjtoJgWcx+PSzg166yZZ8xM8XvXDix9 - c4jIqFYAjoriBV9AhEPv1mH/sonogha0afbZMMZz+yreTGyhpusHwtNNCsA5U1zS4BLxzJIfg299qO32 - Ir7UJtZfftyATqeT+8o2D8JSjQrAJblrncYL7ZJ2+bfaFnC/1S1NjL3diRat7qrO7wLRP3HjWsojBeCo - mDEo5mNjuweFGvjWg2EBhCbpkW78htSHHwRyNdmgAFzPEee2iFkzayy2OLXzT4gr6UdUnlXrullsxxQ+ - kx0g8BTA3aZlButjSTyjODq/WcQcW/B/Je4OQhLvKQDnzN1mp0nnkvAhR8VuMzNrpm1mpjgkoVwB/v8D - TgDQASA1MVpwzwAAAABJRU5ErkJggg== - - - - 56 - \ No newline at end of file diff --git a/SoftwareInstallation/FormPackage.Designer.cs b/SoftwareInstallation/FormPackage.Designer.cs index 70b2169..ab3459f 100644 --- a/SoftwareInstallation/FormPackage.Designer.cs +++ b/SoftwareInstallation/FormPackage.Designer.cs @@ -1,4 +1,4 @@ -namespace SoftwareInstallation.Forms +namespace SoftwareInstallationView { partial class FormPackage { @@ -28,109 +28,153 @@ /// private void InitializeComponent() { - label1 = new Label(); - label2 = new Label(); - buttonAdd = new Button(); - buttonUpd = new Button(); - buttonDel = new Button(); + labelName = new Label(); + textBoxName = new TextBox(); + labelPrice = new Label(); + textBoxPrice = new TextBox(); + groupBoxComponents = new GroupBox(); buttonRef = new Button(); + buttonDel = new Button(); + buttonUpd = new Button(); + buttonAdd = new Button(); dataGridView = new DataGridView(); - Number = new DataGridViewTextBoxColumn(); + buttonCancel = new Button(); + buttonSave = new Button(); + id = new DataGridViewTextBoxColumn(); Component = new DataGridViewTextBoxColumn(); Count = new DataGridViewTextBoxColumn(); - textBoxName = new TextBox(); - textBoxPrice = new TextBox(); - groupBox1 = new GroupBox(); - buttonSave = new Button(); - buttonCancel = new Button(); + groupBoxComponents.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); - groupBox1.SuspendLayout(); SuspendLayout(); // - // label1 + // labelName // - label1.AutoSize = true; - label1.Location = new Point(18, 20); - label1.Name = "label1"; - label1.Size = new Size(80, 20); - label1.TabIndex = 0; - label1.Text = "Название:"; + labelName.AutoSize = true; + labelName.Location = new Point(16, 15); + labelName.Name = "labelName"; + labelName.Size = new Size(84, 20); + labelName.TabIndex = 0; + labelName.Text = "Название: "; // - // label2 + // textBoxName // - label2.AutoSize = true; - label2.Location = new Point(18, 55); - label2.Name = "label2"; - label2.Size = new Size(86, 20); - label2.TabIndex = 1; - label2.Text = "Стоимость:"; + textBoxName.Location = new Point(112, 12); + textBoxName.Name = "textBoxName"; + textBoxName.Size = new Size(293, 27); + textBoxName.TabIndex = 1; // - // buttonAdd + // labelPrice // - buttonAdd.Location = new Point(656, 59); - buttonAdd.Margin = new Padding(3, 4, 3, 4); - buttonAdd.Name = "buttonAdd"; - buttonAdd.Size = new Size(111, 37); - buttonAdd.TabIndex = 0; - buttonAdd.Text = "Добавить"; - buttonAdd.UseVisualStyleBackColor = true; - buttonAdd.Click += buttonAdd_Click; + labelPrice.AutoSize = true; + labelPrice.Location = new Point(16, 51); + labelPrice.Name = "labelPrice"; + labelPrice.Size = new Size(90, 20); + labelPrice.TabIndex = 2; + labelPrice.Text = "Стоимость: "; // - // buttonUpd + // textBoxPrice // - buttonUpd.Location = new Point(656, 120); - buttonUpd.Margin = new Padding(3, 4, 3, 4); - buttonUpd.Name = "buttonUpd"; - buttonUpd.Size = new Size(111, 37); - buttonUpd.TabIndex = 1; - buttonUpd.Text = "Изменить"; - buttonUpd.UseVisualStyleBackColor = true; - buttonUpd.Click += buttonUpd_Click; + textBoxPrice.Location = new Point(112, 51); + textBoxPrice.Name = "textBoxPrice"; + textBoxPrice.Size = new Size(171, 27); + textBoxPrice.TabIndex = 3; // - // buttonDel + // groupBoxComponents // - buttonDel.Location = new Point(656, 179); - buttonDel.Margin = new Padding(3, 4, 3, 4); - buttonDel.Name = "buttonDel"; - buttonDel.Size = new Size(111, 37); - buttonDel.TabIndex = 2; - buttonDel.Text = "Удалить"; - buttonDel.UseVisualStyleBackColor = true; - buttonDel.Click += buttonDel_Click; + groupBoxComponents.Controls.Add(buttonRef); + groupBoxComponents.Controls.Add(buttonDel); + groupBoxComponents.Controls.Add(buttonUpd); + groupBoxComponents.Controls.Add(buttonAdd); + groupBoxComponents.Controls.Add(dataGridView); + groupBoxComponents.Location = new Point(11, 84); + groupBoxComponents.Name = "groupBoxComponents"; + groupBoxComponents.Size = new Size(661, 319); + groupBoxComponents.TabIndex = 4; + groupBoxComponents.TabStop = false; + groupBoxComponents.Text = "Ингредиенты"; // // buttonRef // - buttonRef.Location = new Point(656, 231); - buttonRef.Margin = new Padding(3, 4, 3, 4); + buttonRef.Location = new Point(502, 211); buttonRef.Name = "buttonRef"; - buttonRef.Size = new Size(111, 37); - buttonRef.TabIndex = 3; + buttonRef.Size = new Size(126, 35); + buttonRef.TabIndex = 4; buttonRef.Text = "Обновить"; buttonRef.UseVisualStyleBackColor = true; - buttonRef.Click += buttonRef_Click; + buttonRef.Click += ButtonRef_Click; + // + // buttonDel + // + buttonDel.Location = new Point(502, 157); + buttonDel.Name = "buttonDel"; + buttonDel.Size = new Size(126, 35); + buttonDel.TabIndex = 3; + buttonDel.Text = "Удалить"; + buttonDel.UseVisualStyleBackColor = true; + buttonDel.Click += ButtonDel_Click; + // + // buttonUpd + // + buttonUpd.Location = new Point(502, 101); + buttonUpd.Name = "buttonUpd"; + buttonUpd.Size = new Size(126, 35); + buttonUpd.TabIndex = 2; + buttonUpd.Text = "Изменить"; + buttonUpd.UseVisualStyleBackColor = true; + buttonUpd.Click += ButtonUpd_Click; + // + // buttonAdd + // + buttonAdd.Location = new Point(502, 47); + buttonAdd.Name = "buttonAdd"; + buttonAdd.Size = new Size(126, 35); + buttonAdd.TabIndex = 1; + buttonAdd.Text = "Добавить"; + buttonAdd.UseVisualStyleBackColor = true; + buttonAdd.Click += ButtonAdd_Click; // // dataGridView // + dataGridView.AllowUserToAddRows = false; + dataGridView.AllowUserToDeleteRows = false; + dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; - dataGridView.Columns.AddRange(new DataGridViewColumn[] { Number, Component, Count }); - dataGridView.Location = new Point(0, 27); - dataGridView.Margin = new Padding(3, 4, 3, 4); + dataGridView.Columns.AddRange(new DataGridViewColumn[] { id, Component, Count }); + dataGridView.Location = new Point(6, 27); dataGridView.Name = "dataGridView"; dataGridView.ReadOnly = true; dataGridView.RowHeadersWidth = 51; - dataGridView.RowTemplate.Height = 24; - dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; - dataGridView.ShowEditingIcon = false; - dataGridView.Size = new Size(627, 443); - dataGridView.TabIndex = 4; + dataGridView.RowTemplate.Height = 29; + dataGridView.Size = new Size(475, 287); + dataGridView.TabIndex = 0; // - // Number + // buttonCancel // - Number.HeaderText = "Номер"; - Number.MinimumWidth = 6; - Number.Name = "Number"; - Number.ReadOnly = true; - Number.Width = 60; + buttonCancel.Location = new Point(514, 417); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(126, 35); + buttonCancel.TabIndex = 5; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += ButtonCancel_Click; + // + // buttonSave + // + buttonSave.Location = new Point(368, 417); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(126, 35); + buttonSave.TabIndex = 6; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += ButtonSave_Click; + // + // id + // + id.HeaderText = "id"; + id.MinimumWidth = 6; + id.Name = "id"; + id.ReadOnly = true; + id.Visible = false; // // Component // @@ -138,110 +182,52 @@ Component.MinimumWidth = 6; Component.Name = "Component"; Component.ReadOnly = true; - Component.Width = 125; // // Count // - Count.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; Count.HeaderText = "Количество"; Count.MinimumWidth = 6; Count.Name = "Count"; Count.ReadOnly = true; // - // textBoxName - // - textBoxName.Location = new Point(107, 19); - textBoxName.Margin = new Padding(3, 4, 3, 4); - textBoxName.Name = "textBoxName"; - textBoxName.Size = new Size(281, 27); - textBoxName.TabIndex = 3; - // - // textBoxPrice - // - textBoxPrice.Location = new Point(107, 52); - textBoxPrice.Margin = new Padding(3, 4, 3, 4); - textBoxPrice.Name = "textBoxPrice"; - textBoxPrice.ReadOnly = true; - textBoxPrice.Size = new Size(97, 27); - textBoxPrice.TabIndex = 4; - textBoxPrice.TabStop = false; - // - // groupBox1 - // - groupBox1.Controls.Add(buttonRef); - groupBox1.Controls.Add(buttonDel); - groupBox1.Controls.Add(dataGridView); - groupBox1.Controls.Add(buttonUpd); - groupBox1.Controls.Add(buttonAdd); - groupBox1.Location = new Point(16, 95); - groupBox1.Margin = new Padding(3, 4, 3, 4); - groupBox1.Name = "groupBox1"; - groupBox1.Padding = new Padding(3, 4, 3, 4); - groupBox1.Size = new Size(787, 489); - groupBox1.TabIndex = 5; - groupBox1.TabStop = false; - groupBox1.Text = "Компоненты"; - // - // buttonSave - // - buttonSave.Location = new Point(454, 605); - buttonSave.Margin = new Padding(3, 4, 3, 4); - buttonSave.Name = "buttonSave"; - buttonSave.Size = new Size(130, 37); - buttonSave.TabIndex = 0; - buttonSave.Text = "Сохранить"; - buttonSave.UseVisualStyleBackColor = true; - buttonSave.Click += buttonSave_Click; - // - // buttonCancel - // - buttonCancel.Location = new Point(609, 605); - buttonCancel.Margin = new Padding(3, 4, 3, 4); - buttonCancel.Name = "buttonCancel"; - buttonCancel.Size = new Size(130, 37); - buttonCancel.TabIndex = 0; - buttonCancel.Text = "Отмена"; - buttonCancel.UseVisualStyleBackColor = true; - buttonCancel.Click += buttonCancel_Click; - // // FormPackage // AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(813, 663); - Controls.Add(groupBox1); - Controls.Add(textBoxPrice); - Controls.Add(textBoxName); - Controls.Add(label2); - Controls.Add(buttonCancel); + ClientSize = new Size(685, 463); Controls.Add(buttonSave); - Controls.Add(label1); - Margin = new Padding(3, 4, 3, 4); + Controls.Add(buttonCancel); + Controls.Add(groupBoxComponents); + Controls.Add(textBoxPrice); + Controls.Add(labelPrice); + Controls.Add(textBoxName); + Controls.Add(labelName); Name = "FormPackage"; Text = "ПО"; Load += FormPackage_Load; + groupBoxComponents.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); - groupBox1.ResumeLayout(false); ResumeLayout(false); PerformLayout(); } + #endregion - private Label label1; - private Label label2; + private Label labelName; + private TextBox textBoxName; + private Label labelPrice; + private TextBox textBoxPrice; + private GroupBox groupBoxComponents; private Button buttonRef; private Button buttonDel; private Button buttonUpd; private Button buttonAdd; private DataGridView dataGridView; - private TextBox textBoxName; - private TextBox textBoxPrice; - private GroupBox groupBox1; - private DataGridViewTextBoxColumn Number; + private Button buttonCancel; + private Button buttonSave; + private DataGridViewTextBoxColumn id; private DataGridViewTextBoxColumn Component; private DataGridViewTextBoxColumn Count; - private Button buttonSave; - private Button buttonCancel; } } \ No newline at end of file diff --git a/SoftwareInstallation/FormPackage.cs b/SoftwareInstallation/FormPackage.cs index 3ead7fd..30ddf42 100644 --- a/SoftwareInstallation/FormPackage.cs +++ b/SoftwareInstallation/FormPackage.cs @@ -1,41 +1,33 @@ -using SoftwareInstallationDataModels.Models; -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows.Forms; +using Microsoft.Extensions.Logging; +using SoftwareInstallation; +using SoftwareInstallationContracts.BindingModels; using SoftwareInstallationContracts.BusinessLogicsContracts; using SoftwareInstallationContracts.SearchModels; -using SoftwareInstallationContracts.BindingModels; -using SoftwareInstallation; using SoftwareInstallationDataModels.Models; -namespace SoftwareInstallation.Forms +namespace SoftwareInstallationView { public partial class FormPackage : Form { private readonly ILogger _logger; private readonly IPackageLogic _logic; private int? _id; - private Dictionary _productComponents; + private Dictionary _PackageComponents; public int Id { set { _id = value; } } + public FormPackage(ILogger logger, IPackageLogic logic) { InitializeComponent(); _logger = logger; _logic = logic; - _productComponents = new Dictionary(); + _PackageComponents = new Dictionary(); } + private void FormPackage_Load(object sender, EventArgs e) { if (_id.HasValue) { - _logger.LogInformation("Загрузка изделия"); + _logger.LogInformation("Загрузка пиццы"); try { var view = _logic.ReadElement(new PackageSearchModel @@ -46,25 +38,29 @@ namespace SoftwareInstallation.Forms { textBoxName.Text = view.PackageName; textBoxPrice.Text = view.Price.ToString(); - _productComponents = view.PackageComponents ?? new Dictionary(); + _PackageComponents = view.PackageComponents ?? new + Dictionary(); LoadData(); } } catch (Exception ex) { - _logger.LogError(ex, "Ошибка загрузки изделия"); + _logger.LogError(ex, "Ошибка загрузки пиццы"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); } } } + private void LoadData() { - _logger.LogInformation("Загрузка компонент изделия"); + _logger.LogInformation("Загрузка ингредиент пиццы"); try { - if (_productComponents != null) + if (_PackageComponents != null) { dataGridView.Rows.Clear(); - foreach (var pc in _productComponents) + foreach (var pc in _PackageComponents) { dataGridView.Rows.Add(new object[] { pc.Key, pc.Value.Item1.ComponentName, pc.Value.Item2 }); } @@ -73,10 +69,13 @@ namespace SoftwareInstallation.Forms } catch (Exception ex) { - _logger.LogError(ex, "Ошибка загрузки компонент изделия"); + _logger.LogError(ex, "Ошибка загрузки ингредиента пиццы"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); } } - private void buttonAdd_Click(object sender, EventArgs e) + + private void ButtonAdd_Click(object sender, EventArgs e) { var service = Program.ServiceProvider?.GetService(typeof(FormPackageComponent)); if (service is FormPackageComponent form) @@ -87,20 +86,23 @@ namespace SoftwareInstallation.Forms { return; } - _logger.LogInformation("Добавление нового компонента: { ComponentName} - { Count} ", form.ComponentModel.ComponentName, form.Count); - if (_productComponents.ContainsKey(form.Id)) + _logger.LogInformation("Добавление нового ингредиента:{ ComponentName}-{ Count}", form.ComponentModel.ComponentName, form.Count); + if (_PackageComponents.ContainsKey(form.Id)) { - _productComponents[form.Id] = (form.ComponentModel, form.Count); + _PackageComponents[form.Id] = (form.ComponentModel, + form.Count); } else { - _productComponents.Add(form.Id, (form.ComponentModel, form.Count)); + _PackageComponents.Add(form.Id, (form.ComponentModel, + form.Count)); } LoadData(); } } } - private void buttonUpd_Click(object sender, EventArgs e) + + private void ButtonUpd_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) { @@ -109,21 +111,22 @@ namespace SoftwareInstallation.Forms { int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value); form.Id = id; - form.Count = _productComponents[id].Item2; + form.Count = _PackageComponents[id].Item2; if (form.ShowDialog() == DialogResult.OK) { if (form.ComponentModel == null) { return; } - _logger.LogInformation("Изменение компонента: { ComponentName} - { Count}", form.ComponentModel.ComponentName, form.Count); - _productComponents[form.Id] = (form.ComponentModel, form.Count); + _logger.LogInformation("Изменение ингредиента:{ ComponentName}-{ Count}", form.ComponentModel.ComponentName, form.Count); + _PackageComponents[form.Id] = (form.ComponentModel, form.Count); LoadData(); } } } } - private void buttonDel_Click(object sender, EventArgs e) + + private void ButtonDel_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) { @@ -131,22 +134,25 @@ namespace SoftwareInstallation.Forms { try { - _logger.LogInformation("Удаление компонента: { ComponentName} - { Count}", dataGridView.SelectedRows[0].Cells[1].Value); - _productComponents?.Remove(Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value)); + _logger.LogInformation("Удаление ингредиента:{ ComponentName}-{ Count}", dataGridView.SelectedRows[0].Cells[1].Value); + _PackageComponents?.Remove(Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value)); } catch (Exception ex) { - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(ex.Message, "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); } LoadData(); } } } - private void buttonRef_Click(object sender, EventArgs e) + + private void ButtonRef_Click(object sender, EventArgs e) { LoadData(); } - private void buttonSave_Click(object sender, EventArgs e) + + private void ButtonSave_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(textBoxName.Text)) { @@ -158,12 +164,12 @@ namespace SoftwareInstallation.Forms MessageBox.Show("Заполните цену", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } - if (_productComponents == null || _productComponents.Count == 0) + if (_PackageComponents == null || _PackageComponents.Count == 0) { - MessageBox.Show("Заполните компоненты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("Заполните ингредиенты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } - _logger.LogInformation("Сохранение изделия"); + _logger.LogInformation("Сохранение пиццы"); try { var model = new PackageBindingModel @@ -171,24 +177,26 @@ namespace SoftwareInstallation.Forms Id = _id ?? 0, PackageName = textBoxName.Text, Price = Convert.ToDouble(textBoxPrice.Text), - PackageComponents = _productComponents + PackageComponents = _PackageComponents }; - var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model); + var operationResult = _id.HasValue ? _logic.Update(model) : + _logic.Create(model); if (!operationResult) { throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); } - MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); DialogResult = DialogResult.OK; + MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; Close(); } catch (Exception ex) { - _logger.LogError(ex, "Ошибка сохранения изделия"); + _logger.LogError(ex, "Ошибка сохранения пиццы"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } - private void buttonCancel_Click(object sender, EventArgs e) + private void ButtonCancel_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; Close(); @@ -197,11 +205,11 @@ namespace SoftwareInstallation.Forms private double CalcPrice() { double price = 0; - foreach (var elem in _productComponents) + foreach (var elem in _PackageComponents) { price += ((elem.Value.Item1?.Cost ?? 0) * elem.Value.Item2); } return Math.Round(price * 1.1, 2); } } -} \ No newline at end of file +} diff --git a/SoftwareInstallation/FormPackage.resx b/SoftwareInstallation/FormPackage.resx index 27104e8..af32865 100644 --- a/SoftwareInstallation/FormPackage.resx +++ b/SoftwareInstallation/FormPackage.resx @@ -117,22 +117,4 @@ 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/SoftwareInstallation/FormPackageComponent.Designer.cs b/SoftwareInstallation/FormPackageComponent.Designer.cs index c9af534..9efe136 100644 --- a/SoftwareInstallation/FormPackageComponent.Designer.cs +++ b/SoftwareInstallation/FormPackageComponent.Designer.cs @@ -1,4 +1,4 @@ -namespace SoftwareInstallation.Forms +namespace SoftwareInstallationView { partial class FormPackageComponent { @@ -28,96 +28,91 @@ /// private void InitializeComponent() { - buttonSave = new Button(); - buttonCancel = new Button(); - label1 = new Label(); - label2 = new Label(); + labelComponent = new Label(); comboBoxComponent = new ComboBox(); + labelCount = new Label(); textBoxCount = new TextBox(); + buttonCancel = new Button(); + buttonSave = new Button(); SuspendLayout(); // - // buttonSave + // labelComponent // - buttonSave.Location = new Point(199, 100); - buttonSave.Margin = new Padding(3, 4, 3, 4); - buttonSave.Name = "buttonSave"; - buttonSave.Size = new Size(98, 36); - buttonSave.TabIndex = 0; - buttonSave.Text = "Сохранить"; - buttonSave.UseVisualStyleBackColor = true; - buttonSave.Click += this.buttonSave_Click; - // - // buttonCancel - // - buttonCancel.Location = new Point(309, 100); - buttonCancel.Margin = new Padding(3, 4, 3, 4); - buttonCancel.Name = "buttonCancel"; - buttonCancel.Size = new Size(98, 36); - buttonCancel.TabIndex = 1; - buttonCancel.Text = "Отмена"; - buttonCancel.UseVisualStyleBackColor = true; - buttonCancel.Click += this.buttonCancel_Click; - // - // label1 - // - label1.AutoSize = true; - label1.Location = new Point(14, 19); - label1.Name = "label1"; - label1.Size = new Size(91, 20); - label1.TabIndex = 2; - label1.Text = "Компонент:"; - // - // label2 - // - label2.AutoSize = true; - label2.Location = new Point(14, 59); - label2.Name = "label2"; - label2.Size = new Size(93, 20); - label2.TabIndex = 3; - label2.Text = "Количество:"; + labelComponent.AutoSize = true; + labelComponent.Location = new Point(11, 9); + labelComponent.Name = "labelComponent"; + labelComponent.Size = new Size(91, 20); + labelComponent.TabIndex = 0; + labelComponent.Text = "Компонент:"; // // comboBoxComponent // comboBoxComponent.FormattingEnabled = true; - comboBoxComponent.Location = new Point(121, 12); - comboBoxComponent.Margin = new Padding(3, 4, 3, 4); + comboBoxComponent.Location = new Point(119, 9); comboBoxComponent.Name = "comboBoxComponent"; - comboBoxComponent.Size = new Size(285, 28); - comboBoxComponent.TabIndex = 4; + comboBoxComponent.Size = new Size(355, 28); + comboBoxComponent.TabIndex = 1; + // + // labelCount + // + labelCount.AutoSize = true; + labelCount.Location = new Point(11, 51); + labelCount.Name = "labelCount"; + labelCount.Size = new Size(93, 20); + labelCount.TabIndex = 2; + labelCount.Text = "Количество:"; // // textBoxCount // - textBoxCount.Location = new Point(121, 59); - textBoxCount.Margin = new Padding(3, 4, 3, 4); + textBoxCount.Location = new Point(119, 51); textBoxCount.Name = "textBoxCount"; - textBoxCount.Size = new Size(285, 27); - textBoxCount.TabIndex = 5; + textBoxCount.Size = new Size(355, 27); + textBoxCount.TabIndex = 3; // - // FormPackage + // buttonCancel + // + buttonCancel.Location = new Point(317, 93); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(136, 41); + buttonCancel.TabIndex = 4; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += ButtonCancel_Click; + // + // buttonSave + // + buttonSave.Location = new Point(175, 93); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(136, 41); + buttonSave.TabIndex = 5; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += ButtonSave_Click; + // + // FormPackageComponent // AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(426, 149); - Controls.Add(textBoxCount); - Controls.Add(comboBoxComponent); - Controls.Add(label2); - Controls.Add(label1); - Controls.Add(buttonCancel); + ClientSize = new Size(486, 147); Controls.Add(buttonSave); - Margin = new Padding(3, 4, 3, 4); - Name = "FormPackage"; - Text = "Компонент ПО"; + Controls.Add(buttonCancel); + Controls.Add(textBoxCount); + Controls.Add(labelCount); + Controls.Add(comboBoxComponent); + Controls.Add(labelComponent); + Name = "FormPackageComponent"; + Text = "ПО"; ResumeLayout(false); PerformLayout(); } #endregion - private Button buttonSave; - private Button buttonCancel; - private Label label1; - private Label label2; + private Label labelComponent; private ComboBox comboBoxComponent; + private Label labelCount; private TextBox textBoxCount; + private Button buttonCancel; + private Button buttonSave; } } \ No newline at end of file diff --git a/SoftwareInstallation/FormPackageComponent.cs b/SoftwareInstallation/FormPackageComponent.cs index 96a8f17..e6a2b6a 100644 --- a/SoftwareInstallation/FormPackageComponent.cs +++ b/SoftwareInstallation/FormPackageComponent.cs @@ -11,11 +11,12 @@ using System.Text; using System.Threading.Tasks; using System.Windows.Forms; -namespace SoftwareInstallation.Forms +namespace SoftwareInstallationView { public partial class FormPackageComponent : Form { private readonly List? _list; + public int Id { get @@ -27,6 +28,7 @@ namespace SoftwareInstallation.Forms comboBoxComponent.SelectedValue = value; } } + public IComponentModel? ComponentModel { get @@ -45,11 +47,8 @@ namespace SoftwareInstallation.Forms return null; } } - public int Count - { - get { return Convert.ToInt32(textBoxCount.Text); } - set { textBoxCount.Text = value.ToString(); } - } + + public int Count { get { return Convert.ToInt32(textBoxCount.Text); } set { textBoxCount.Text = value.ToString(); } } public FormPackageComponent(IComponentLogic logic) { @@ -65,7 +64,7 @@ namespace SoftwareInstallation.Forms } } - private void buttonSave_Click(object sender, EventArgs e) + private void ButtonSave_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(textBoxCount.Text)) { @@ -74,13 +73,14 @@ namespace SoftwareInstallation.Forms } if (comboBoxComponent.SelectedValue == null) { - MessageBox.Show("Выберите компонент", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("Выберите ингредиент", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } DialogResult = DialogResult.OK; Close(); } - private void buttonCancel_Click(object sender, EventArgs e) + + private void ButtonCancel_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; Close(); diff --git a/SoftwareInstallation/FormPackages.Designer.cs b/SoftwareInstallation/FormPackages.Designer.cs index 49839d2..2b1901a 100644 --- a/SoftwareInstallation/FormPackages.Designer.cs +++ b/SoftwareInstallation/FormPackages.Designer.cs @@ -1,4 +1,4 @@ -namespace SoftwareInstallation.Forms +namespace SoftwareInstallationView { partial class FormPackages { @@ -28,89 +28,98 @@ /// private void InitializeComponent() { + ToolsPanel = new Panel(); buttonRef = new Button(); buttonDel = new Button(); buttonUpd = new Button(); buttonAdd = new Button(); dataGridView = new DataGridView(); + ToolsPanel.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); SuspendLayout(); // + // ToolsPanel + // + ToolsPanel.Controls.Add(buttonRef); + ToolsPanel.Controls.Add(buttonDel); + ToolsPanel.Controls.Add(buttonUpd); + ToolsPanel.Controls.Add(buttonAdd); + ToolsPanel.Location = new Point(608, 12); + ToolsPanel.Name = "ToolsPanel"; + ToolsPanel.Size = new Size(180, 426); + ToolsPanel.TabIndex = 3; + // // buttonRef // - buttonRef.Location = new Point(741, 180); - buttonRef.Margin = new Padding(3, 4, 3, 4); + buttonRef.Location = new Point(31, 206); buttonRef.Name = "buttonRef"; - buttonRef.Size = new Size(128, 35); - buttonRef.TabIndex = 9; + buttonRef.Size = new Size(126, 36); + buttonRef.TabIndex = 3; buttonRef.Text = "Обновить"; buttonRef.UseVisualStyleBackColor = true; - buttonRef.Click += buttonRef_Click; + buttonRef.Click += ButtonRef_Click; // // buttonDel // - buttonDel.Location = new Point(741, 129); - buttonDel.Margin = new Padding(3, 4, 3, 4); + buttonDel.Location = new Point(31, 142); buttonDel.Name = "buttonDel"; - buttonDel.Size = new Size(128, 35); - buttonDel.TabIndex = 8; + buttonDel.Size = new Size(126, 36); + buttonDel.TabIndex = 2; buttonDel.Text = "Удалить"; buttonDel.UseVisualStyleBackColor = true; - buttonDel.Click += buttonDel_Click; + buttonDel.Click += ButtonDel_Click; // // buttonUpd // - buttonUpd.Location = new Point(741, 77); - buttonUpd.Margin = new Padding(3, 4, 3, 4); + buttonUpd.Location = new Point(31, 76); buttonUpd.Name = "buttonUpd"; - buttonUpd.Size = new Size(128, 35); - buttonUpd.TabIndex = 7; + buttonUpd.Size = new Size(126, 36); + buttonUpd.TabIndex = 1; buttonUpd.Text = "Изменить"; buttonUpd.UseVisualStyleBackColor = true; - buttonUpd.Click += buttonUpd_Click; + buttonUpd.Click += ButtonUpd_Click; // // buttonAdd // - buttonAdd.Location = new Point(741, 27); - buttonAdd.Margin = new Padding(3, 4, 3, 4); + buttonAdd.Location = new Point(31, 16); buttonAdd.Name = "buttonAdd"; - buttonAdd.Size = new Size(128, 35); - buttonAdd.TabIndex = 6; + buttonAdd.Size = new Size(126, 36); + buttonAdd.TabIndex = 0; buttonAdd.Text = "Добавить"; buttonAdd.UseVisualStyleBackColor = true; - buttonAdd.Click += buttonAdd_Click; + buttonAdd.Click += ButtonAdd_Click; // // dataGridView // + dataGridView.AllowUserToAddRows = false; + dataGridView.AllowUserToDeleteRows = false; dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; - dataGridView.Location = new Point(-1, 0); - dataGridView.Margin = new Padding(3, 4, 3, 4); + dataGridView.Location = new Point(12, 12); dataGridView.Name = "dataGridView"; dataGridView.ReadOnly = true; dataGridView.RowHeadersWidth = 51; - dataGridView.RowTemplate.Height = 24; - dataGridView.Size = new Size(709, 568); - dataGridView.TabIndex = 5; + dataGridView.RowTemplate.Height = 29; + dataGridView.Size = new Size(590, 426); + dataGridView.TabIndex = 2; // - // SoftwareInstallation + // FormPackages // AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(895, 571); - Controls.Add(buttonRef); - Controls.Add(buttonDel); - Controls.Add(buttonUpd); - Controls.Add(buttonAdd); + ClientSize = new Size(800, 450); + Controls.Add(ToolsPanel); Controls.Add(dataGridView); - Name = "SoftwareInstallation"; - Text = "Список пакетов установок"; - Load += FormPackages_Load; + Name = "FormPackages"; + Text = "ПО"; + Load += FormPackage_Load; + ToolsPanel.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); ResumeLayout(false); } #endregion + private Panel ToolsPanel; private Button buttonRef; private Button buttonDel; private Button buttonUpd; diff --git a/SoftwareInstallation/FormPackages.cs b/SoftwareInstallation/FormPackages.cs index 0e330db..437f6bb 100644 --- a/SoftwareInstallation/FormPackages.cs +++ b/SoftwareInstallation/FormPackages.cs @@ -1,23 +1,15 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows.Forms; +using Microsoft.Extensions.Logging; using SoftwareInstallation; using SoftwareInstallationContracts.BindingModels; using SoftwareInstallationContracts.BusinessLogicsContracts; -using Microsoft.Extensions.Logging; -namespace SoftwareInstallation.Forms +namespace SoftwareInstallationView { public partial class FormPackages : Form { private readonly ILogger _logger; private readonly IPackageLogic _logic; + public FormPackages(ILogger logger, IPackageLogic logic) { InitializeComponent(); @@ -25,7 +17,7 @@ namespace SoftwareInstallation.Forms _logic = logic; } - private void FormPackages_Load(object sender, EventArgs e) + private void FormPackage_Load(object sender, EventArgs e) { LoadData(); } @@ -40,17 +32,19 @@ namespace SoftwareInstallation.Forms dataGridView.DataSource = list; dataGridView.Columns["Id"].Visible = false; dataGridView.Columns["PackageComponents"].Visible = false; - dataGridView.Columns["PackageName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + dataGridView.Columns["PackageName"].AutoSizeMode = + DataGridViewAutoSizeColumnMode.Fill; } - _logger.LogInformation("Загрузка консерв"); + _logger.LogInformation("Загрузка пиццы"); } catch (Exception ex) { - _logger.LogError(ex, "Ошибка загрузки компонентов"); + _logger.LogError(ex, "Ошибка загрузки пиццы"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } - private void buttonAdd_Click(object sender, EventArgs e) + private void ButtonAdd_Click(object sender, EventArgs e) { var service = Program.ServiceProvider?.GetService(typeof(FormPackage)); if (service is FormPackage form) @@ -62,7 +56,7 @@ namespace SoftwareInstallation.Forms } } - private void buttonUpd_Click(object sender, EventArgs e) + private void ButtonUpd_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) { @@ -78,15 +72,14 @@ namespace SoftwareInstallation.Forms } } - private void buttonDel_Click(object sender, EventArgs e) + 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("Удаление консервы"); + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Удаление пиццы"); try { if (!_logic.Delete(new PackageBindingModel @@ -100,14 +93,14 @@ namespace SoftwareInstallation.Forms } catch (Exception ex) { - _logger.LogError(ex, "Ошибка удаления консервы"); + _logger.LogError(ex, "Ошибка удаления пиццы"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } } - private void buttonRef_Click(object sender, EventArgs e) + private void ButtonRef_Click(object sender, EventArgs e) { LoadData(); } diff --git a/SoftwareInstallation/FormSellSoftwareInstallation.Designer.cs b/SoftwareInstallation/FormSellSoftwareInstallation.Designer.cs new file mode 100644 index 0000000..efc2742 --- /dev/null +++ b/SoftwareInstallation/FormSellSoftwareInstallation.Designer.cs @@ -0,0 +1,119 @@ +namespace SoftwareInstallationView +{ + partial class FormSellPackage + { + /// + /// 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() + { + labelPackage = new Label(); + comboBoxPackage = new ComboBox(); + labelCount = new Label(); + textBoxCount = new TextBox(); + buttonSell = new Button(); + buttonCancel = new Button(); + SuspendLayout(); + // + // labelPackage + // + labelPackage.AutoSize = true; + labelPackage.Location = new Point(12, 14); + labelPackage.Name = "labelPackage"; + labelPackage.Size = new Size(38, 20); + labelPackage.TabIndex = 0; + labelPackage.Text = "ПО: "; + // + // comboBoxPackage + // + comboBoxPackage.FormattingEnabled = true; + comboBoxPackage.Location = new Point(115, 11); + comboBoxPackage.Name = "comboBoxPackage"; + comboBoxPackage.Size = new Size(239, 28); + comboBoxPackage.TabIndex = 1; + // + // labelCount + // + labelCount.AutoSize = true; + labelCount.Location = new Point(12, 55); + labelCount.Name = "labelCount"; + labelCount.Size = new Size(97, 20); + labelCount.TabIndex = 2; + labelCount.Text = "Количество: "; + // + // textBoxCount + // + textBoxCount.Location = new Point(115, 52); + textBoxCount.Name = "textBoxCount"; + textBoxCount.Size = new Size(239, 27); + textBoxCount.TabIndex = 3; + // + // buttonSell + // + buttonSell.Location = new Point(128, 99); + buttonSell.Name = "buttonSell"; + buttonSell.Size = new Size(94, 29); + buttonSell.TabIndex = 4; + buttonSell.Text = "Продать"; + buttonSell.UseVisualStyleBackColor = true; + buttonSell.Click += ButtonSell_Click; + // + // buttonCancel + // + buttonCancel.Location = new Point(242, 99); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(94, 29); + buttonCancel.TabIndex = 5; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += ButtonCancel_Click; + // + // FormSellPackage + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(366, 140); + Controls.Add(buttonCancel); + Controls.Add(buttonSell); + Controls.Add(textBoxCount); + Controls.Add(labelCount); + Controls.Add(comboBoxPackage); + Controls.Add(labelPackage); + Name = "FormSellPackage"; + Text = "Продажа ПО"; + Load += FormSellingPackage_Load; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Label labelPackage; + private ComboBox comboBoxPackage; + private Label labelCount; + private TextBox textBoxCount; + private Button buttonSell; + private Button buttonCancel; + } +} \ No newline at end of file diff --git a/SoftwareInstallation/FormSellSoftwareInstallation.cs b/SoftwareInstallation/FormSellSoftwareInstallation.cs new file mode 100644 index 0000000..ad3ca77 --- /dev/null +++ b/SoftwareInstallation/FormSellSoftwareInstallation.cs @@ -0,0 +1,88 @@ +using Microsoft.Extensions.Logging; +using SoftwareInstallationContracts.BusinessLogicsContracts; +using SoftwareInstallationContracts.SearchModels; +using SoftwareInstallationContracts.StoragesContracts; +using SoftwareInstallationContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace SoftwareInstallationView +{ + public partial class FormSellPackage : Form + { + private readonly ILogger _logger; + private readonly IPackageLogic _logicP; + private readonly IShopLogic _logicS; + private List _pizzaList = new List(); + + public FormSellPackage(ILogger logger, IPackageLogic logicP, IShopLogic logicS) + { + InitializeComponent(); + _logger = logger; + _logicP = logicP; + _logicS = logicS; + } + + private void FormSellingPackage_Load(object sender, EventArgs e) + { + _pizzaList = _logicP.ReadList(null); + if (_pizzaList != null) + { + comboBoxPackage.DisplayMember = "PackageName"; + comboBoxPackage.ValueMember = "Id"; + comboBoxPackage.DataSource = _pizzaList; + comboBoxPackage.SelectedItem = null; + _logger.LogInformation("Загрузка пиццы для продажи"); + } + } + + private void ButtonSell_Click(object sender, EventArgs e) + { + if (comboBoxPackage.SelectedValue == null) + { + MessageBox.Show("Выберите пиццу", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Создание покупки"); + try + { + bool resout = _logicS.Sale(new SupplySearchModel + { + PackageId = Convert.ToInt32(comboBoxPackage.SelectedValue), + Count = Convert.ToInt32(textBoxCount.Text) + }); + if (resout) + { + _logger.LogInformation("Проверка пройдена, продажа проведена"); + MessageBox.Show("Продажа проведена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + Close(); + } + else + { + _logger.LogInformation("Проверка не пройдена"); + MessageBox.Show("Продажа не может быть создана.", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Warning); + } + } + 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(); + } + } +} \ No newline at end of file diff --git a/SoftwareInstallation/FormSellSoftwareInstallation.resx b/SoftwareInstallation/FormSellSoftwareInstallation.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/SoftwareInstallation/FormSellSoftwareInstallation.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/SoftwareInstallation/FormShop.Designer.cs b/SoftwareInstallation/FormShop.Designer.cs new file mode 100644 index 0000000..b4224e9 --- /dev/null +++ b/SoftwareInstallation/FormShop.Designer.cs @@ -0,0 +1,214 @@ +namespace SoftwareInstallationView +{ + 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() + { + labelName = new Label(); + textBoxName = new TextBox(); + textBoxAdress = new TextBox(); + labelAdress = new Label(); + buttonCancel = new Button(); + buttonSave = new Button(); + dataGridView = new DataGridView(); + label1 = new Label(); + dateTimeOpen = new DateTimePicker(); + label2 = new Label(); + numericUpPackageMaxCount = new NumericUpDown(); + id = new DataGridViewTextBoxColumn(); + PackageName = new DataGridViewTextBoxColumn(); + Count = new DataGridViewTextBoxColumn(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + ((System.ComponentModel.ISupportInitialize)numericUpPackageMaxCount).BeginInit(); + SuspendLayout(); + // + // labelName + // + labelName.AutoSize = true; + labelName.Location = new Point(11, 15); + labelName.Name = "labelName"; + labelName.Size = new Size(84, 20); + labelName.TabIndex = 0; + labelName.Text = "Название: "; + // + // textBoxName + // + textBoxName.Location = new Point(102, 12); + textBoxName.Name = "textBoxName"; + textBoxName.Size = new Size(276, 27); + textBoxName.TabIndex = 1; + // + // textBoxAdress + // + textBoxAdress.Location = new Point(102, 59); + textBoxAdress.Name = "textBoxAdress"; + textBoxAdress.Size = new Size(427, 27); + textBoxAdress.TabIndex = 3; + // + // labelAdress + // + labelAdress.AutoSize = true; + labelAdress.Location = new Point(11, 61); + labelAdress.Name = "labelAdress"; + labelAdress.Size = new Size(58, 20); + labelAdress.TabIndex = 2; + labelAdress.Text = "Адрес: "; + // + // buttonCancel + // + buttonCancel.Location = new Point(451, 457); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(130, 44); + buttonCancel.TabIndex = 5; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += buttonCancel_Click; + // + // buttonSave + // + buttonSave.Location = new Point(315, 457); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(130, 44); + buttonSave.TabIndex = 6; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += buttonSave_Click; + // + // dataGridView + // + dataGridView.AllowUserToAddRows = false; + dataGridView.AllowUserToDeleteRows = false; + dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Columns.AddRange(new DataGridViewColumn[] { id, PackageName, Count }); + dataGridView.Location = new Point(12, 185); + dataGridView.Name = "dataGridView"; + dataGridView.ReadOnly = true; + dataGridView.RowHeadersBorderStyle = DataGridViewHeaderBorderStyle.None; + dataGridView.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToDisplayedHeaders; + dataGridView.RowTemplate.Height = 29; + dataGridView.Size = new Size(569, 266); + dataGridView.TabIndex = 7; + // + // label1 + // + label1.AutoSize = true; + label1.Location = new Point(12, 103); + label1.Name = "label1"; + label1.Size = new Size(110, 20); + label1.TabIndex = 8; + label1.Text = "Дата открытия"; + // + // dateTimeOpen + // + dateTimeOpen.Location = new Point(128, 103); + dateTimeOpen.Name = "dateTimeOpen"; + dateTimeOpen.Size = new Size(401, 27); + dateTimeOpen.TabIndex = 9; + // + // label2 + // + label2.AutoSize = true; + label2.Location = new Point(12, 148); + label2.Name = "label2"; + label2.Size = new Size(100, 20); + label2.TabIndex = 10; + label2.Text = "Вместимость"; + // + // numericUpPackageMaxCount + // + numericUpPackageMaxCount.Location = new Point(128, 146); + numericUpPackageMaxCount.Maximum = new decimal(new int[] { 10000, 0, 0, 0 }); + numericUpPackageMaxCount.Name = "numericUpPackageMaxCount"; + numericUpPackageMaxCount.Size = new Size(401, 27); + numericUpPackageMaxCount.TabIndex = 11; + // + // id + // + id.HeaderText = "id"; + id.MinimumWidth = 6; + id.Name = "id"; + id.ReadOnly = true; + id.Visible = false; + // + // PackageName + // + PackageName.HeaderText = "ПО"; + PackageName.MinimumWidth = 6; + PackageName.Name = "PackageName"; + PackageName.ReadOnly = true; + // + // Count + // + Count.HeaderText = "Количество"; + Count.MinimumWidth = 6; + Count.Name = "Count"; + Count.ReadOnly = true; + // + // FormShop + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(593, 513); + Controls.Add(numericUpPackageMaxCount); + Controls.Add(label2); + Controls.Add(dateTimeOpen); + Controls.Add(label1); + Controls.Add(dataGridView); + Controls.Add(buttonSave); + Controls.Add(buttonCancel); + Controls.Add(textBoxAdress); + Controls.Add(labelAdress); + Controls.Add(textBoxName); + Controls.Add(labelName); + Name = "FormShop"; + Text = "Магазин"; + Load += FormShop_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ((System.ComponentModel.ISupportInitialize)numericUpPackageMaxCount).EndInit(); + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Label labelName; + private TextBox textBoxName; + private TextBox textBoxAdress; + private Label labelAdress; + private Button buttonCancel; + private Button buttonSave; + private DataGridView dataGridView; + private Label label1; + private DateTimePicker dateTimeOpen; + private Label label2; + private NumericUpDown numericUpPackageMaxCount; + private DataGridViewTextBoxColumn id; + private DataGridViewTextBoxColumn PackageName; + private DataGridViewTextBoxColumn Count; + } +} \ No newline at end of file diff --git a/SoftwareInstallation/FormShop.cs b/SoftwareInstallation/FormShop.cs new file mode 100644 index 0000000..2e78773 --- /dev/null +++ b/SoftwareInstallation/FormShop.cs @@ -0,0 +1,127 @@ +using SoftwareInstallationDataModels.Models; +using Microsoft.Extensions.Logging; +using SoftwareInstallationContracts.BindingModels; +using SoftwareInstallationContracts.BusinessLogicsContracts; +using SoftwareInstallationContracts.SearchModels; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace SoftwareInstallationView +{ + public partial class FormShop : Form + { + private readonly ILogger _logger; + private readonly IShopLogic _logic; + private int? _id; + public int Id { set { _id = value; } } + private Dictionary _ShopPackages; + private DateTime? _openingDate = null; + public FormShop(ILogger logger, IShopLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + _ShopPackages = new Dictionary(); + } + 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) + { + textBoxName.Text = view.ShopName; + textBoxAdress.Text = view.Adress; + dateTimeOpen.Value = view.OpeningDate; + numericUpPackageMaxCount.Value = view.PackageMaxCount; + _ShopPackages = view.ShopPackages ?? new Dictionary(); + LoadData(); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки магазина"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + + private void LoadData() + { + _logger.LogInformation("Загрузка изделий в магазине"); + try + { + if (_ShopPackages != null) + { + dataGridView.Rows.Clear(); + foreach (var sr in _ShopPackages) + { + dataGridView.Rows.Add(new object[] { sr.Key, sr.Value.Item1.PackageName, sr.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(textBoxName.Text)) + { + MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (string.IsNullOrEmpty(textBoxAdress.Text)) + { + MessageBox.Show("Заполните адрес", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Сохранение магазина"); + try + { + var model = new ShopBindingModel + { + Id = _id ?? 0, + ShopName = textBoxName.Text, + Adress = textBoxAdress.Text, + OpeningDate = dateTimeOpen.Value, + PackageMaxCount = (int)numericUpPackageMaxCount.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(); + } + } +} diff --git a/SoftwareInstallation/FormShop.resx b/SoftwareInstallation/FormShop.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/SoftwareInstallation/FormShop.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/SoftwareInstallation/FormShops.Designer.cs b/SoftwareInstallation/FormShops.Designer.cs new file mode 100644 index 0000000..eb63ed2 --- /dev/null +++ b/SoftwareInstallation/FormShops.Designer.cs @@ -0,0 +1,130 @@ +namespace SoftwareInstallationView +{ + 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.ToolsPanel = new System.Windows.Forms.Panel(); + 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(); + this.ToolsPanel.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); + this.SuspendLayout(); + // + // ToolsPanel + // + this.ToolsPanel.Controls.Add(this.buttonRef); + this.ToolsPanel.Controls.Add(this.buttonDel); + this.ToolsPanel.Controls.Add(this.buttonUpd); + this.ToolsPanel.Controls.Add(this.buttonAdd); + this.ToolsPanel.Location = new System.Drawing.Point(608, 12); + this.ToolsPanel.Name = "ToolsPanel"; + this.ToolsPanel.Size = new System.Drawing.Size(180, 426); + this.ToolsPanel.TabIndex = 3; + // + // buttonRef + // + this.buttonRef.Location = new System.Drawing.Point(31, 206); + this.buttonRef.Name = "buttonRef"; + this.buttonRef.Size = new System.Drawing.Size(126, 36); + this.buttonRef.TabIndex = 3; + this.buttonRef.Text = "Обновить"; + this.buttonRef.UseVisualStyleBackColor = true; + this.buttonRef.Click += new System.EventHandler(this.ButtonRef_Click); + // + // buttonDel + // + this.buttonDel.Location = new System.Drawing.Point(31, 142); + this.buttonDel.Name = "buttonDel"; + this.buttonDel.Size = new System.Drawing.Size(126, 36); + this.buttonDel.TabIndex = 2; + this.buttonDel.Text = "Удалить"; + this.buttonDel.UseVisualStyleBackColor = true; + this.buttonDel.Click += new System.EventHandler(this.ButtonDel_Click); + // + // buttonUpd + // + this.buttonUpd.Location = new System.Drawing.Point(31, 76); + this.buttonUpd.Name = "buttonUpd"; + this.buttonUpd.Size = new System.Drawing.Size(126, 36); + this.buttonUpd.TabIndex = 1; + this.buttonUpd.Text = "Изменить"; + this.buttonUpd.UseVisualStyleBackColor = true; + this.buttonUpd.Click += new System.EventHandler(this.ButtonUpd_Click); + // + // buttonAdd + // + this.buttonAdd.Location = new System.Drawing.Point(31, 16); + this.buttonAdd.Name = "buttonAdd"; + this.buttonAdd.Size = new System.Drawing.Size(126, 36); + this.buttonAdd.TabIndex = 0; + this.buttonAdd.Text = "Добавить"; + this.buttonAdd.UseVisualStyleBackColor = true; + this.buttonAdd.Click += new System.EventHandler(this.ButtonAdd_Click); + // + // dataGridView + // + this.dataGridView.AllowUserToAddRows = false; + this.dataGridView.AllowUserToDeleteRows = false; + this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView.Location = new System.Drawing.Point(12, 12); + this.dataGridView.Name = "dataGridView"; + this.dataGridView.ReadOnly = true; + this.dataGridView.RowHeadersWidth = 51; + this.dataGridView.RowTemplate.Height = 29; + this.dataGridView.Size = new System.Drawing.Size(590, 426); + this.dataGridView.TabIndex = 2; + // + // FormShops + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 450); + this.Controls.Add(this.ToolsPanel); + this.Controls.Add(this.dataGridView); + this.Name = "FormShops"; + this.Text = "Магазины"; + this.Load += new System.EventHandler(this.FormShops_Load); + this.ToolsPanel.ResumeLayout(false); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit(); + this.ResumeLayout(false); + + } + + #endregion + + private Panel ToolsPanel; + private Button buttonRef; + private Button buttonDel; + private Button buttonUpd; + private Button buttonAdd; + private DataGridView dataGridView; + } +} \ No newline at end of file diff --git a/SoftwareInstallation/FormShops.cs b/SoftwareInstallation/FormShops.cs new file mode 100644 index 0000000..71140dc --- /dev/null +++ b/SoftwareInstallation/FormShops.cs @@ -0,0 +1,117 @@ +using Microsoft.Extensions.Logging; +using SoftwareInstallation; +using SoftwareInstallationContracts.BindingModels; +using SoftwareInstallationContracts.BusinessLogicsContracts; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace SoftwareInstallationView +{ + 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["ShopPackages"].Visible = false; + dataGridView.Columns["ShopName"].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/SoftwareInstallation/FormShops.resx b/SoftwareInstallation/FormShops.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/SoftwareInstallation/FormShops.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/SoftwareInstallation/Program.cs b/SoftwareInstallation/Program.cs index e73efc2..f84a878 100644 --- a/SoftwareInstallation/Program.cs +++ b/SoftwareInstallation/Program.cs @@ -1,11 +1,11 @@ -using SoftwareInstallation.Forms; -using SoftwareInstallationContracts.BusinessLogicsContracts; -using SoftwareInstallationBusinessLogic.BusinessLogic; -using SoftwareInstallationContracts.StoragesContracts; -using SoftwareInstallationDatabaseImplement.Implements; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; +using SoftwareInstallationBusinessLogic.BusinessLogics; +using SoftwareInstallationContracts.BusinessLogicsContracts; +using SoftwareInstallationContracts.StoragesContracts; +using SoftwareInstallationDatabaseImplement.Implements; +using SoftwareInstallationView; namespace SoftwareInstallation { @@ -14,7 +14,7 @@ namespace SoftwareInstallation private static ServiceProvider? _serviceProvider; public static ServiceProvider? ServiceProvider => _serviceProvider; /// - /// The main entry point for the application. + /// The main entry point for the application. /// [STAThread] static void Main() @@ -25,9 +25,9 @@ namespace SoftwareInstallation var services = new ServiceCollection(); ConfigureServices(services); _serviceProvider = services.BuildServiceProvider(); - Application.Run(_serviceProvider.GetRequiredService()); } + private static void ConfigureServices(ServiceCollection services) { services.AddLogging(option => @@ -35,19 +35,26 @@ namespace SoftwareInstallation option.SetMinimumLevel(LogLevel.Information); option.AddNLog("nlog.config"); }); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); - services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); } } } \ No newline at end of file diff --git a/SoftwareInstallation/nlog.config b/SoftwareInstallation/nlog.config index af70d20..85797a7 100644 --- a/SoftwareInstallation/nlog.config +++ b/SoftwareInstallation/nlog.config @@ -5,7 +5,7 @@ autoReload="true" internalLogLevel="Info"> - + diff --git a/SoftwareInstallationBusinessLogic/BusinessLogic/ComponentLogic.cs b/SoftwareInstallationBusinessLogic/BusinessLogics/ComponentLogic.cs similarity index 79% rename from SoftwareInstallationBusinessLogic/BusinessLogic/ComponentLogic.cs rename to SoftwareInstallationBusinessLogic/BusinessLogics/ComponentLogic.cs index 261d831..c3faae6 100644 --- a/SoftwareInstallationBusinessLogic/BusinessLogic/ComponentLogic.cs +++ b/SoftwareInstallationBusinessLogic/BusinessLogics/ComponentLogic.cs @@ -1,25 +1,31 @@ -using SoftwareInstallationContracts.BindingModels; +using Microsoft.Extensions.Logging; +using SoftwareInstallationContracts.BindingModels; using SoftwareInstallationContracts.BusinessLogicsContracts; using SoftwareInstallationContracts.SearchModels; using SoftwareInstallationContracts.StoragesContracts; using SoftwareInstallationContracts.ViewModels; -using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; -namespace SoftwareInstallationBusinessLogic.BusinessLogic +namespace SoftwareInstallationBusinessLogic.BusinessLogics { public class ComponentLogic : IComponentLogic { private readonly ILogger _logger; private readonly IComponentStorage _componentStorage; - public ComponentLogic(ILogger logger, IComponentStorage - componentStorage) + + public ComponentLogic(ILogger logger, IComponentStorage componentStorage) { _logger = logger; _componentStorage = componentStorage; } + public List? ReadList(ComponentSearchModel? model) { - _logger.LogInformation("ReadList. ComponentName:{ComponentName}.Id:{Id}", model?.ComponentName, model?.Id); + _logger.LogInformation("ReadList. ComponentName:{ComponentName}.Id:{ Id}", model?.ComponentName, model?.Id); var list = model == null ? _componentStorage.GetFullList() : _componentStorage.GetFilteredList(model); if (list == null) { @@ -36,7 +42,7 @@ namespace SoftwareInstallationBusinessLogic.BusinessLogic { throw new ArgumentNullException(nameof(model)); } - _logger.LogInformation("ReadElement. ComponentName:{ComponentName}.Id:{Id}", model.ComponentName, model.Id); + _logger.LogInformation("ReadElement. ComponentName:{ComponentName}.Id:{ Id}", model.ComponentName, model.Id); var element = _componentStorage.GetElement(model); if (element == null) { @@ -93,21 +99,21 @@ namespace SoftwareInstallationBusinessLogic.BusinessLogic } if (string.IsNullOrEmpty(model.ComponentName)) { - throw new ArgumentNullException("Нет названия компонента", nameof(model.ComponentName)); + throw new ArgumentNullException("Нет названия ингредиента", nameof(model.ComponentName)); } if (model.Cost <= 0) { - throw new ArgumentNullException("Цена компонента должна быть больше 0", nameof(model.Cost)); + throw new ArgumentNullException("Цена ингредиента должна быть больше 0", nameof(model.Cost)); } - _logger.LogInformation("Component. ComponentName:{ComponentName}.Cost:{Cost}. Id: {Id}", model.ComponentName, model.Cost, model.Id); + _logger.LogInformation("Component. ComponentName:{ComponentName}.Cost:{ Cost}.Id: { Id}", model.ComponentName, model.Cost, model.Id); var element = _componentStorage.GetElement(new ComponentSearchModel { - ComponentName = model.ComponentName + ComponentName = model.ComponentName }); if (element != null && element.Id != model.Id) { - throw new InvalidOperationException("Компонент с таким названием уже есть"); + throw new InvalidOperationException("Ингредиент с таким названием уже есть"); } } } -} \ No newline at end of file +} diff --git a/SoftwareInstallationBusinessLogic/BusinessLogic/OrderLogic.cs b/SoftwareInstallationBusinessLogic/BusinessLogics/OrderLogic.cs similarity index 57% rename from SoftwareInstallationBusinessLogic/BusinessLogic/OrderLogic.cs rename to SoftwareInstallationBusinessLogic/BusinessLogics/OrderLogic.cs index a09428d..b6b1680 100644 --- a/SoftwareInstallationBusinessLogic/BusinessLogic/OrderLogic.cs +++ b/SoftwareInstallationBusinessLogic/BusinessLogics/OrderLogic.cs @@ -1,33 +1,30 @@ -using SoftwareInstallationContracts.BindingModels; +using Microsoft.Extensions.Logging; +using SoftwareInstallationContracts.BindingModels; using SoftwareInstallationContracts.BusinessLogicsContracts; using SoftwareInstallationContracts.SearchModels; using SoftwareInstallationContracts.StoragesContracts; using SoftwareInstallationContracts.ViewModels; using SoftwareInstallationDataModels.Enums; -using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; -namespace SoftwareInstallationBusinessLogic.BusinessLogic +namespace SoftwareInstallationBusinessLogic.BusinessLogics { public class OrderLogic : IOrderLogic { - //Класс с логикой для заказов будет отвечать за получение списка заказов, - //создания заказа и смены его статусов. Следует учитывать, что у заказа можно - //менять статус на новый, если его текущий статус предшествует новому - private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; + private readonly IShopStorage _shopStorage; - public OrderLogic(ILogger logger, IOrderStorage orderStorage) + public OrderLogic(ILogger logger, IOrderStorage orderStorage, IShopStorage shopStorage) { _logger = logger; _orderStorage = orderStorage; + _shopStorage = shopStorage; } - public List? ReadList(OrderSearchModel? model) { _logger.LogInformation("ReadList. OrderId:{Id}", model?.Id); @@ -40,18 +37,14 @@ namespace SoftwareInstallationBusinessLogic.BusinessLogic _logger.LogInformation("ReadList. Count:{Count}", list.Count); return list; } - public bool CreateOrder(OrderBindingModel model) { CheckModel(model); - if (model.Status != OrderStatus.Неизвестен) return false; model.Status = OrderStatus.Принят; - if (_orderStorage.Insert(model) == null) { - model.Status = OrderStatus.Неизвестен; _logger.LogWarning("Insert operation failed"); return false; } @@ -60,57 +53,34 @@ namespace SoftwareInstallationBusinessLogic.BusinessLogic public bool TakeOrderInWork(OrderBindingModel model) { - return ToNextStatus(model, OrderStatus.Выполняется); + return ChangeStatus(model, OrderStatus.Выполняется); } public bool FinishOrder(OrderBindingModel model) { - return ToNextStatus(model, OrderStatus.Готов); + return ChangeStatus(model, OrderStatus.Готов); } public bool DeliveryOrder(OrderBindingModel model) { - return ToNextStatus(model, OrderStatus.Выдан); - } - - public bool ToNextStatus(OrderBindingModel model, OrderStatus orderStatus) - { - CheckModel(model, false); - var element = _orderStorage.GetElement(new OrderSearchModel() + var order = _orderStorage.GetElement(new OrderSearchModel { - Id = model.Id + Id = model.Id, }); - if (element == null) + if (order == null) { - throw new ArgumentNullException(nameof(element)); + throw new ArgumentNullException(nameof(order)); + } + if (!_shopStorage.RestockingShops(new SupplyBindingModel + { + PackageId = order.PackageId, + Count = order.Count + })) + { + throw new ArgumentException("Недостаточно места"); } - model.PackageId = element.PackageId; - model.DateCreate = element.DateCreate; - model.DateImplement = element.DateImplement; - model.Status = element.Status; - model.Count = element.Count; - model.Sum = element.Sum; - - if (model.Status != orderStatus - 1) - { - _logger.LogWarning("Status update to " + orderStatus + " operation failed"); - return false; - } - model.Status = orderStatus; - - if (model.Status == OrderStatus.Выдан) - { - model.DateImplement = DateTime.Now; - } - - if (_orderStorage.Update(model) == null) - { - model.Status--; - _logger.LogWarning("Changing status operation faled"); - return false; - } - return true; + return ChangeStatus(model, OrderStatus.Выдан); } private void CheckModel(OrderBindingModel model, bool withParams = true) @@ -125,17 +95,51 @@ namespace SoftwareInstallationBusinessLogic.BusinessLogic } if (model.Count <= 0) { - throw new ArgumentNullException("Количество изделий должно быть больше 0", nameof(model.Count)); + throw new ArgumentException("Колличество пиццы в заказе не может быть меньше 1", nameof(model.Count)); } if (model.Sum <= 0) { - throw new ArgumentNullException("Цена заказа должна быть больше 0", nameof(model.Sum)); + throw new ArgumentException("Стоимость заказа на может быть меньше 1", nameof(model.Sum)); } if (model.DateImplement.HasValue && model.DateImplement < model.DateCreate) { - throw new ArithmeticException($"Дата выдачи заказа {model.DateImplement} должна быть позже даты его создания {model.DateCreate}"); + throw new ArithmeticException($"Дата выдачи заказа {model.DateImplement} не может быть раньше даты его создания {model.DateCreate}"); } - _logger.LogInformation("Package. PackageId:{PackageId}.Count:{Count}.Sum:{Sum}Id:{Id}", model.PackageId, model.Count, model.Sum, model.Id); + _logger.LogInformation("Package. PackageId:{PackageId}.Count:{Count}.Sum:{Sum}Id:{Id}", + model.PackageId, model.Count, model.Sum, model.Id); + } + + private bool ChangeStatus(OrderBindingModel model, OrderStatus requiredStatus) + { + CheckModel(model, false); + var element = _orderStorage.GetElement(new OrderSearchModel() + { + Id = model.Id + }); + if (element == null) + { + throw new ArgumentNullException(nameof(element)); + } + model.DateCreate = element.DateCreate; + model.PackageId = element.PackageId; + model.DateImplement = element.DateImplement; + model.Status = element.Status; + model.Count = element.Count; + model.Sum = element.Sum; + if (requiredStatus - model.Status == 1) + { + model.Status = requiredStatus; + if (model.Status == OrderStatus.Выдан) + model.DateImplement = DateTime.Now; + if (_orderStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + return true; + } + _logger.LogWarning("Changing status operation faled: Current-{Status}:required-{requiredStatus}.", model.Status, requiredStatus); + throw new ArgumentException($"Невозможно присвоить статус {requiredStatus} заказу с текущим статусом {model.Status}"); } } } diff --git a/SoftwareInstallationBusinessLogic/BusinessLogic/PackageLogic.cs b/SoftwareInstallationBusinessLogic/BusinessLogics/PackageLogic.cs similarity index 79% rename from SoftwareInstallationBusinessLogic/BusinessLogic/PackageLogic.cs rename to SoftwareInstallationBusinessLogic/BusinessLogics/PackageLogic.cs index ea87d3b..e03c5b4 100644 --- a/SoftwareInstallationBusinessLogic/BusinessLogic/PackageLogic.cs +++ b/SoftwareInstallationBusinessLogic/BusinessLogics/PackageLogic.cs @@ -1,30 +1,29 @@ -using SoftwareInstallationContracts.BindingModels; +using Microsoft.Extensions.Logging; +using SoftwareInstallationContracts.BindingModels; using SoftwareInstallationContracts.BusinessLogicsContracts; using SoftwareInstallationContracts.SearchModels; using SoftwareInstallationContracts.StoragesContracts; using SoftwareInstallationContracts.ViewModels; -using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; -namespace SoftwareInstallationBusinessLogic.BusinessLogic +namespace SoftwareInstallationBusinessLogic.BusinessLogics { public class PackageLogic : IPackageLogic { private readonly ILogger _logger; private readonly IPackageStorage _PackageStorage; - public PackageLogic(ILogger logger, IPackageStorage - PackageStorage) + public PackageLogic(ILogger logger, IPackageStorage PackageStorage) { _logger = logger; _PackageStorage = PackageStorage; } public List? ReadList(PackageSearchModel? model) { - _logger.LogInformation("ReadList. PackageName:{PackageName}.Id:{Id}", model?.PackageName, model?.Id); + _logger.LogInformation("ReadList. PackageName:{PackageName}.Id:{ Id}", model?.PackageName, model?.Id); var list = model == null ? _PackageStorage.GetFullList() : _PackageStorage.GetFilteredList(model); if (list == null) { @@ -34,14 +33,13 @@ namespace SoftwareInstallationBusinessLogic.BusinessLogic _logger.LogInformation("ReadList. Count:{Count}", list.Count); return list; } - public PackageViewModel? ReadElement(PackageSearchModel model) { if (model == null) { throw new ArgumentNullException(nameof(model)); } - _logger.LogInformation("ReadElement. PackageName:{PackageName}.Id:{Id}", model.PackageName, model.Id); + _logger.LogInformation("ReadElement. PackageName:{PackageName}.Id:{ Id}", model.PackageName, model.Id); var element = _PackageStorage.GetElement(model); if (element == null) { @@ -51,7 +49,6 @@ namespace SoftwareInstallationBusinessLogic.BusinessLogic _logger.LogInformation("ReadElement find. Id:{Id}", element.Id); return element; } - public bool Create(PackageBindingModel model) { CheckModel(model); @@ -62,7 +59,6 @@ namespace SoftwareInstallationBusinessLogic.BusinessLogic } return true; } - public bool Update(PackageBindingModel model) { CheckModel(model); @@ -73,7 +69,6 @@ namespace SoftwareInstallationBusinessLogic.BusinessLogic } return true; } - public bool Delete(PackageBindingModel model) { CheckModel(model, false); @@ -85,7 +80,6 @@ namespace SoftwareInstallationBusinessLogic.BusinessLogic } return true; } - private void CheckModel(PackageBindingModel model, bool withParams = true) { if (model == null) @@ -98,20 +92,24 @@ namespace SoftwareInstallationBusinessLogic.BusinessLogic } if (string.IsNullOrEmpty(model.PackageName)) { - throw new ArgumentNullException("Нет названия изделия", nameof(model.PackageName)); + throw new ArgumentNullException("Нет названия пиццы", nameof(model.PackageName)); } if (model.Price <= 0) { - throw new ArgumentNullException("Цена изделия должна быть больше 0", nameof(model.Price)); + throw new ArgumentNullException("Цена пиццы должна быть больше 0", nameof(model.Price)); } - _logger.LogInformation("Package. PackageName:{PackageName}.Price:{Cost}. Id: {Id}", model.PackageName, model.Price, model.Id); + if (model.PackageComponents == null || model.PackageComponents.Count == 0) + { + throw new ArgumentNullException("Перечень ингредиентов не может быть пустым", nameof(model.PackageComponents)); + } + _logger.LogInformation("Package. PackageName:{PackageName}.Price:{Price}.Id: { Id}", model.PackageName, model.Price, model.Id); var element = _PackageStorage.GetElement(new PackageSearchModel { PackageName = model.PackageName }); if (element != null && element.Id != model.Id) { - throw new InvalidOperationException("Изделие с таким названием уже есть"); + throw new InvalidOperationException("ПО с таким названием уже есть"); } } } diff --git a/SoftwareInstallationBusinessLogic/BusinessLogics/ShopLogic.cs b/SoftwareInstallationBusinessLogic/BusinessLogics/ShopLogic.cs new file mode 100644 index 0000000..f5176b4 --- /dev/null +++ b/SoftwareInstallationBusinessLogic/BusinessLogics/ShopLogic.cs @@ -0,0 +1,187 @@ +using Microsoft.Extensions.Logging; +using SoftwareInstallationContracts.BindingModels; +using SoftwareInstallationContracts.BusinessLogicsContracts; +using SoftwareInstallationContracts.SearchModels; +using SoftwareInstallationContracts.StoragesContracts; +using SoftwareInstallationContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SoftwareInstallationBusinessLogic.BusinessLogics +{ + public class ShopLogic : IShopLogic + { + private readonly ILogger _logger; + private readonly IShopStorage _shopStorage; + private readonly IPackageStorage _pizzaStorage; + + public ShopLogic(ILogger logger, IShopStorage shopStorage, IPackageStorage pizzaStorage) + { + _logger = logger; + _shopStorage = shopStorage; + _pizzaStorage = pizzaStorage; + } + + public List? ReadList(ShopSearchModel? model) + { + _logger.LogInformation("ReadList. ShopName:{ShopName}.Id:{ Id}", model?.ShopName, model?.Id); + var list = model == null ? _shopStorage.GetFullList() : _shopStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + _logger.LogInformation("ReadList. Count:{Count}", list.Count); + return list; + } + + public ShopViewModel? ReadElement(ShopSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + _logger.LogInformation("ReadElement. ShopName:{ShopName}.Id:{ Id}", model.ShopName, model.Id); + var element = _shopStorage.GetElement(model); + if (element == null) + { + _logger.LogWarning("ReadElement element not found"); + return null; + } + _logger.LogInformation("ReadElement find. Id:{Id}", element.Id); + return element; + } + + public bool Create(ShopBindingModel model) + { + CheckModel(model); + if (_shopStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } + + public bool Update(ShopBindingModel model) + { + CheckModel(model); + if (_shopStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + return true; + } + + public bool Delete(ShopBindingModel model) + { + CheckModel(model, false); + _logger.LogInformation("Delete. Id:{Id}", model.Id); + if (_shopStorage.Delete(model) == null) + { + _logger.LogWarning("Delete operation failed"); + return false; + } + return true; + } + + public bool MakeSupply(SupplyBindingModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (model.Count <= 0) + { + throw new ArgumentException("Количество изделий должно быть больше 0"); + } + var shop = _shopStorage.GetElement(new ShopSearchModel + { + Id = model.ShopId + }); + if (shop == null) + { + throw new ArgumentException("Магазина не существует"); + } + if (shop.ShopPackages.ContainsKey(model.PackageId)) + { + var oldValue = shop.ShopPackages[model.PackageId]; + oldValue.Item2 += model.Count; + shop.ShopPackages[model.PackageId] = oldValue; + } + else + { + var pizza = _pizzaStorage.GetElement(new PackageSearchModel + { + Id = model.PackageId + }); + if (pizza == null) + { + throw new ArgumentException($"Поставка: Товар с id:{model.PackageId} не найденн"); + } + shop.ShopPackages.Add(model.PackageId, (pizza, model.Count)); + } + + _shopStorage.Update(new ShopBindingModel() + { + Id = shop.Id, + ShopName = shop.ShopName, + Adress = shop.Adress, + OpeningDate = shop.OpeningDate, + ShopPackages = shop.ShopPackages, + PackageMaxCount = shop.PackageMaxCount, + }); + + 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.Adress)) + { + throw new ArgumentException("Адрес магазина длжен быть заполнен", nameof(model.Adress)); + } + if (string.IsNullOrEmpty(model.ShopName)) + { + throw new ArgumentException("Название магазина должно быть заполнено", nameof(model.ShopName)); + } + _logger.LogInformation("Shop. ShopName:{ShopName}.Adres:{Adres}.OpeningDate:{OpeningDate}.Id:{ Id}", model.ShopName, model.Adress, model.OpeningDate, model.Id); + var element = _shopStorage.GetElement(new ShopSearchModel + { + ShopName = model.ShopName + }); + if (element != null && element.Id != model.Id) + { + throw new InvalidOperationException("Магазин с таким названием уже есть"); + } + } + + public bool Sale(SupplySearchModel model) + { + if (!model.PackageId.HasValue || !model.Count.HasValue) + { + return false; + } + _logger.LogInformation("Check pizza count in all shops"); + if (_shopStorage.Sale(model)) + { + _logger.LogInformation("Selling sucsess"); + return true; + } + _logger.LogInformation("Selling failed"); + return false; + } + } +} diff --git a/SoftwareInstallationContracts/BindingModels/ComponentBindingModel.cs b/SoftwareInstallationContracts/BindingModels/ComponentBindingModel.cs index f1da9cf..2d1912d 100644 --- a/SoftwareInstallationContracts/BindingModels/ComponentBindingModel.cs +++ b/SoftwareInstallationContracts/BindingModels/ComponentBindingModel.cs @@ -13,4 +13,4 @@ namespace SoftwareInstallationContracts.BindingModels public string ComponentName { get; set; } = string.Empty; public double Cost { get; set; } } -} +} \ No newline at end of file diff --git a/SoftwareInstallationContracts/BindingModels/OrderBindingModel.cs b/SoftwareInstallationContracts/BindingModels/OrderBindingModel.cs index d53ff55..779cd14 100644 --- a/SoftwareInstallationContracts/BindingModels/OrderBindingModel.cs +++ b/SoftwareInstallationContracts/BindingModels/OrderBindingModel.cs @@ -13,9 +13,9 @@ namespace SoftwareInstallationContracts.BindingModels public int Id { get; set; } public int PackageId { get; set; } public int Count { get; set; } - public double Sum { get; set; } + public double Sum { get; set; } public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; public DateTime DateCreate { get; set; } = DateTime.Now; public DateTime? DateImplement { get; set; } } -} +} \ No newline at end of file diff --git a/SoftwareInstallationContracts/BindingModels/PackageBindingModel.cs b/SoftwareInstallationContracts/BindingModels/PackageBindingModel.cs index 4650e41..49a174b 100644 --- a/SoftwareInstallationContracts/BindingModels/PackageBindingModel.cs +++ b/SoftwareInstallationContracts/BindingModels/PackageBindingModel.cs @@ -14,4 +14,4 @@ namespace SoftwareInstallationContracts.BindingModels public double Price { get; set; } public Dictionary PackageComponents { get; set; } = new(); } -} +} \ No newline at end of file diff --git a/SoftwareInstallationContracts/BindingModels/ShopBindingModel.cs b/SoftwareInstallationContracts/BindingModels/ShopBindingModel.cs new file mode 100644 index 0000000..06e81f4 --- /dev/null +++ b/SoftwareInstallationContracts/BindingModels/ShopBindingModel.cs @@ -0,0 +1,19 @@ +using SoftwareInstallationDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SoftwareInstallationContracts.BindingModels +{ + public class ShopBindingModel : IShopModel + { + public int Id { get; set; } + public string ShopName { get; set; } = string.Empty; + public string Adress { get; set; } = string.Empty; + public DateTime OpeningDate { get; set; } = DateTime.Now; + public Dictionary ShopPackages { get; set; } = new(); + public int PackageMaxCount { get; set; } + } +} \ No newline at end of file diff --git a/SoftwareInstallationContracts/BindingModels/SupplyBindingModel.cs b/SoftwareInstallationContracts/BindingModels/SupplyBindingModel.cs new file mode 100644 index 0000000..7e61624 --- /dev/null +++ b/SoftwareInstallationContracts/BindingModels/SupplyBindingModel.cs @@ -0,0 +1,16 @@ +using SoftwareInstallationDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SoftwareInstallationContracts.BindingModels +{ + public class SupplyBindingModel : ISupplyModel + { + public int ShopId { get; set; } + public int PackageId { get; set; } + public int Count { get; set; } + } +} \ No newline at end of file diff --git a/SoftwareInstallationContracts/BusinessLogicsContracts/IComponentLogic.cs b/SoftwareInstallationContracts/BusinessLogicsContracts/IComponentLogic.cs index 94d4a7d..f4d7d10 100644 --- a/SoftwareInstallationContracts/BusinessLogicsContracts/IComponentLogic.cs +++ b/SoftwareInstallationContracts/BusinessLogicsContracts/IComponentLogic.cs @@ -3,7 +3,6 @@ using SoftwareInstallationContracts.SearchModels; using SoftwareInstallationContracts.ViewModels; using System; using System.Collections.Generic; -using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; diff --git a/SoftwareInstallationContracts/BusinessLogicsContracts/IOrderLogic.cs b/SoftwareInstallationContracts/BusinessLogicsContracts/IOrderLogic.cs index c589fe2..41bc7f7 100644 --- a/SoftwareInstallationContracts/BusinessLogicsContracts/IOrderLogic.cs +++ b/SoftwareInstallationContracts/BusinessLogicsContracts/IOrderLogic.cs @@ -14,17 +14,7 @@ namespace SoftwareInstallationContracts.BusinessLogicsContracts List? ReadList(OrderSearchModel? model); bool CreateOrder(OrderBindingModel model); bool TakeOrderInWork(OrderBindingModel model); - /// - /// Готов - /// - /// - /// bool FinishOrder(OrderBindingModel model); - /// - /// Доставлен - /// - /// - /// bool DeliveryOrder(OrderBindingModel model); } } diff --git a/SoftwareInstallationContracts/BusinessLogicsContracts/IShopLogic.cs b/SoftwareInstallationContracts/BusinessLogicsContracts/IShopLogic.cs new file mode 100644 index 0000000..8ba0904 --- /dev/null +++ b/SoftwareInstallationContracts/BusinessLogicsContracts/IShopLogic.cs @@ -0,0 +1,22 @@ +using SoftwareInstallationContracts.BindingModels; +using SoftwareInstallationContracts.SearchModels; +using SoftwareInstallationContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SoftwareInstallationContracts.BusinessLogicsContracts +{ + public interface IShopLogic + { + List? ReadList(ShopSearchModel? model); + ShopViewModel? ReadElement(ShopSearchModel model); + bool Create(ShopBindingModel model); + bool Update(ShopBindingModel model); + bool Delete(ShopBindingModel model); + bool MakeSupply(SupplyBindingModel model); + bool Sale(SupplySearchModel model); + } +} \ No newline at end of file diff --git a/SoftwareInstallationContracts/SearchModels/ComponentSearchModel.cs b/SoftwareInstallationContracts/SearchModels/ComponentSearchModel.cs index c15aff8..daf4ae4 100644 --- a/SoftwareInstallationContracts/SearchModels/ComponentSearchModel.cs +++ b/SoftwareInstallationContracts/SearchModels/ComponentSearchModel.cs @@ -11,4 +11,4 @@ namespace SoftwareInstallationContracts.SearchModels public int? Id { get; set; } public string? ComponentName { get; set; } } -} +} \ No newline at end of file diff --git a/SoftwareInstallationContracts/SearchModels/OrderSearchModel.cs b/SoftwareInstallationContracts/SearchModels/OrderSearchModel.cs index b2831f6..1b8352b 100644 --- a/SoftwareInstallationContracts/SearchModels/OrderSearchModel.cs +++ b/SoftwareInstallationContracts/SearchModels/OrderSearchModel.cs @@ -10,4 +10,4 @@ namespace SoftwareInstallationContracts.SearchModels { public int? Id { get; set; } } -} +} \ No newline at end of file diff --git a/SoftwareInstallationContracts/SearchModels/PackageSearchModel.cs b/SoftwareInstallationContracts/SearchModels/PackageSearchModel.cs index 43c90d4..7f28726 100644 --- a/SoftwareInstallationContracts/SearchModels/PackageSearchModel.cs +++ b/SoftwareInstallationContracts/SearchModels/PackageSearchModel.cs @@ -11,4 +11,4 @@ namespace SoftwareInstallationContracts.SearchModels public int? Id { get; set; } public string? PackageName { get; set; } } -} +} \ No newline at end of file diff --git a/SoftwareInstallationContracts/SearchModels/ShopSearchModel.cs b/SoftwareInstallationContracts/SearchModels/ShopSearchModel.cs new file mode 100644 index 0000000..4613740 --- /dev/null +++ b/SoftwareInstallationContracts/SearchModels/ShopSearchModel.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SoftwareInstallationContracts.SearchModels +{ + public class ShopSearchModel + { + public int? Id { get; set; } + public string? ShopName { get; set; } + } +} \ No newline at end of file diff --git a/SoftwareInstallationContracts/SearchModels/SupplySearchModel.cs b/SoftwareInstallationContracts/SearchModels/SupplySearchModel.cs new file mode 100644 index 0000000..7ed1705 --- /dev/null +++ b/SoftwareInstallationContracts/SearchModels/SupplySearchModel.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SoftwareInstallationContracts.SearchModels +{ + public class SupplySearchModel + { + public int? PackageId { get; set; } + public int? Count { get; set; } + } +} \ No newline at end of file diff --git a/SoftwareInstallationContracts/StoragesContracts/IComponentStorage.cs b/SoftwareInstallationContracts/StoragesContracts/IComponentStorage.cs index b07927d..6e6115e 100644 --- a/SoftwareInstallationContracts/StoragesContracts/IComponentStorage.cs +++ b/SoftwareInstallationContracts/StoragesContracts/IComponentStorage.cs @@ -17,6 +17,5 @@ namespace SoftwareInstallationContracts.StoragesContracts ComponentViewModel? Insert(ComponentBindingModel model); ComponentViewModel? Update(ComponentBindingModel model); ComponentViewModel? Delete(ComponentBindingModel model); - } } diff --git a/SoftwareInstallationContracts/StoragesContracts/IShopStorage.cs b/SoftwareInstallationContracts/StoragesContracts/IShopStorage.cs new file mode 100644 index 0000000..dcb6db0 --- /dev/null +++ b/SoftwareInstallationContracts/StoragesContracts/IShopStorage.cs @@ -0,0 +1,23 @@ +using SoftwareInstallationContracts.BindingModels; +using SoftwareInstallationContracts.SearchModels; +using SoftwareInstallationContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SoftwareInstallationContracts.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 Sale(SupplySearchModel model); + bool RestockingShops(SupplyBindingModel model); + } +} \ No newline at end of file diff --git a/SoftwareInstallationContracts/ViewModels/ComponentViewModel.cs b/SoftwareInstallationContracts/ViewModels/ComponentViewModel.cs index 083b3c3..dd92c34 100644 --- a/SoftwareInstallationContracts/ViewModels/ComponentViewModel.cs +++ b/SoftwareInstallationContracts/ViewModels/ComponentViewModel.cs @@ -11,9 +11,11 @@ namespace SoftwareInstallationContracts.ViewModels public class ComponentViewModel : IComponentModel { public int Id { get; set; } - [DisplayName("Название компонента")] + + [DisplayName("Название ингредиента")] public string ComponentName { get; set; } = string.Empty; + [DisplayName("Цена")] public double Cost { get; set; } } -} +} \ No newline at end of file diff --git a/SoftwareInstallationContracts/ViewModels/OrderViewModel.cs b/SoftwareInstallationContracts/ViewModels/OrderViewModel.cs index e4c9a67..ad942d4 100644 --- a/SoftwareInstallationContracts/ViewModels/OrderViewModel.cs +++ b/SoftwareInstallationContracts/ViewModels/OrderViewModel.cs @@ -1,4 +1,5 @@ using SoftwareInstallationDataModels.Enums; +using SoftwareInstallationDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel; @@ -8,22 +9,29 @@ using System.Threading.Tasks; namespace SoftwareInstallationContracts.ViewModels { - public class OrderViewModel + public class OrderViewModel : IOrderModel { [DisplayName("Номер")] public int Id { get; set; } + public int PackageId { get; set; } - [DisplayName("Изделие")] + + [DisplayName("ПО")] public string PackageName { get; set; } = string.Empty; + [DisplayName("Количество")] public int Count { get; set; } + [DisplayName("Сумма")] public double Sum { get; set; } + [DisplayName("Статус")] public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; + [DisplayName("Дата создания")] public DateTime DateCreate { get; set; } = DateTime.Now; + [DisplayName("Дата выполнения")] public DateTime? DateImplement { get; set; } } -} +} \ No newline at end of file diff --git a/SoftwareInstallationContracts/ViewModels/PackageViewModel.cs b/SoftwareInstallationContracts/ViewModels/PackageViewModel.cs index 12a29dc..3c4e4b4 100644 --- a/SoftwareInstallationContracts/ViewModels/PackageViewModel.cs +++ b/SoftwareInstallationContracts/ViewModels/PackageViewModel.cs @@ -11,11 +11,13 @@ namespace SoftwareInstallationContracts.ViewModels public class PackageViewModel : IPackageModel { public int Id { get; set; } - [DisplayName("Название изделия")] - public string PackageName { get; set; } + + [DisplayName("Название пиццы")] + public string PackageName { get; set; } = string.Empty; + [DisplayName("Цена")] public double Price { get; set; } - public Dictionary PackageComponents { get; set; } = new(); + public Dictionary PackageComponents { get; set; } = new(); } -} +} \ No newline at end of file diff --git a/SoftwareInstallationContracts/ViewModels/ShopViewModel.cs b/SoftwareInstallationContracts/ViewModels/ShopViewModel.cs new file mode 100644 index 0000000..b3cc482 --- /dev/null +++ b/SoftwareInstallationContracts/ViewModels/ShopViewModel.cs @@ -0,0 +1,24 @@ +using SoftwareInstallationDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SoftwareInstallationContracts.ViewModels +{ + public class ShopViewModel : IShopModel + { + public int Id { get; set; } + [DisplayName("Название")] + public string ShopName { get; set; } = string.Empty; + [DisplayName("Адрес")] + public string Adress { get; set; } = string.Empty; + [DisplayName("Дата открытия")] + public DateTime OpeningDate { get; set; } + public Dictionary ShopPackages { get; set; } = new(); + [DisplayName("Вместимость")] + public int PackageMaxCount { get; set; } + } +} \ No newline at end of file diff --git a/SoftwareInstallationDataModels/Enums/OrderStatus.cs b/SoftwareInstallationDataModels/Enums/OrderStatus.cs index 13c4efe..83360ae 100644 --- a/SoftwareInstallationDataModels/Enums/OrderStatus.cs +++ b/SoftwareInstallationDataModels/Enums/OrderStatus.cs @@ -1,4 +1,10 @@ -namespace SoftwareInstallationDataModels.Enums +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SoftwareInstallationDataModels.Enums { public enum OrderStatus { @@ -6,6 +12,6 @@ Принят = 0, Выполняется = 1, Готов = 2, - Выдан = 3, + Выдан = 3 } } \ No newline at end of file diff --git a/SoftwareInstallationDataModels/IId.cs b/SoftwareInstallationDataModels/IId.cs index 4c444f5..da727f0 100644 --- a/SoftwareInstallationDataModels/IId.cs +++ b/SoftwareInstallationDataModels/IId.cs @@ -10,4 +10,4 @@ namespace SoftwareInstallationDataModels { int Id { get; } } -} +} \ No newline at end of file diff --git a/SoftwareInstallationDataModels/Models/IComponentModel.cs b/SoftwareInstallationDataModels/Models/IComponentModel.cs index 5d18120..0441f68 100644 --- a/SoftwareInstallationDataModels/Models/IComponentModel.cs +++ b/SoftwareInstallationDataModels/Models/IComponentModel.cs @@ -1,3 +1,9 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + namespace SoftwareInstallationDataModels.Models { public interface IComponentModel : IId @@ -5,4 +11,4 @@ namespace SoftwareInstallationDataModels.Models string ComponentName { get; } double Cost { get; } } -} +} \ No newline at end of file diff --git a/SoftwareInstallationDataModels/Models/IOrderModel.cs b/SoftwareInstallationDataModels/Models/IOrderModel.cs index 95ae88f..46e35ee 100644 --- a/SoftwareInstallationDataModels/Models/IOrderModel.cs +++ b/SoftwareInstallationDataModels/Models/IOrderModel.cs @@ -1,4 +1,9 @@ -using SoftwareInstallationDataModels.Enums; +using SoftwareInstallationDataModels.Enums; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; namespace SoftwareInstallationDataModels.Models { diff --git a/SoftwareInstallationDataModels/Models/IPackageModel.cs b/SoftwareInstallationDataModels/Models/IPackageModel.cs index 6d2a4f9..2b70758 100644 --- a/SoftwareInstallationDataModels/Models/IPackageModel.cs +++ b/SoftwareInstallationDataModels/Models/IPackageModel.cs @@ -1,9 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + namespace SoftwareInstallationDataModels.Models { - public interface IPackageModel : IId - { - string PackageName { get; } - double Price { get; } - Dictionary PackageComponents { get; } - } -} + public interface IPackageModel : IId + { + string PackageName { get; } + double Price { get; } + Dictionary PackageComponents { get; } + } +} \ No newline at end of file diff --git a/SoftwareInstallationDataModels/Models/IShopModel.cs b/SoftwareInstallationDataModels/Models/IShopModel.cs new file mode 100644 index 0000000..b0eafab --- /dev/null +++ b/SoftwareInstallationDataModels/Models/IShopModel.cs @@ -0,0 +1,19 @@ +using SoftwareInstallationDataModels; +using SoftwareInstallationDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SoftwareInstallationDataModels.Models +{ + public interface IShopModel : IId + { + string ShopName { get; } + string Adress { get; } + DateTime OpeningDate { get; } + Dictionary ShopPackages { get; } + public int PackageMaxCount { get; } + } +} \ No newline at end of file diff --git a/SoftwareInstallationDataModels/Models/ISupplyModel.cs b/SoftwareInstallationDataModels/Models/ISupplyModel.cs new file mode 100644 index 0000000..34f1546 --- /dev/null +++ b/SoftwareInstallationDataModels/Models/ISupplyModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SoftwareInstallationDataModels.Models +{ + public interface ISupplyModel + { + int ShopId { get; } + int PackageId { get; } + int Count { get; } + } +} \ No newline at end of file diff --git a/SoftwareInstallationDatabaseImplement/Implements/ComponentStorage.cs b/SoftwareInstallationDatabaseImplement/Implements/ComponentStorage.cs index a4a1a54..fcd35c9 100644 --- a/SoftwareInstallationDatabaseImplement/Implements/ComponentStorage.cs +++ b/SoftwareInstallationDatabaseImplement/Implements/ComponentStorage.cs @@ -3,11 +3,6 @@ using SoftwareInstallationContracts.SearchModels; using SoftwareInstallationContracts.StoragesContracts; using SoftwareInstallationContracts.ViewModels; using SoftwareInstallationDatabaseImplement.Models; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace SoftwareInstallationDatabaseImplement.Implements { @@ -15,38 +10,33 @@ namespace SoftwareInstallationDatabaseImplement.Implements { public List GetFullList() { - using var context = new SoftwareInstallationDataBase(); - return context.Components - .Select(x => x.GetViewModel) - .ToList(); + using var context = new SoftwareInstallationDatabase(); + return context.Components.Select(x => x.GetViewModel).ToList(); } - public List GetFilteredList(ComponentSearchModel - model) + + public List GetFilteredList(ComponentSearchModel model) { if (string.IsNullOrEmpty(model.ComponentName)) { return new(); } - using var context = new SoftwareInstallationDataBase(); - return context.Components - .Where(x => x.ComponentName.Contains(model.ComponentName)) - .Select(x => x.GetViewModel) - .ToList(); + using var context = new SoftwareInstallationDatabase(); + return context.Components.Where(x => x.ComponentName.Contains(model.ComponentName)).Select(x => x.GetViewModel).ToList(); } + public ComponentViewModel? GetElement(ComponentSearchModel model) { if (string.IsNullOrEmpty(model.ComponentName) && !model.Id.HasValue) { return null; } - using var context = new SoftwareInstallationDataBase(); - return context.Components - .FirstOrDefault(x => - (!string.IsNullOrEmpty(model.ComponentName) && x.ComponentName == - model.ComponentName) || + using var context = new SoftwareInstallationDatabase(); + return context.Components.FirstOrDefault(x => + (!string.IsNullOrEmpty(model.ComponentName) && x.ComponentName == model.ComponentName) || (model.Id.HasValue && x.Id == model.Id)) - ?.GetViewModel; + ?.GetViewModel; } + public ComponentViewModel? Insert(ComponentBindingModel model) { var newComponent = Component.Create(model); @@ -54,16 +44,16 @@ namespace SoftwareInstallationDatabaseImplement.Implements { return null; } - using var context = new SoftwareInstallationDataBase(); + using var context = new SoftwareInstallationDatabase(); context.Components.Add(newComponent); context.SaveChanges(); return newComponent.GetViewModel; } + public ComponentViewModel? Update(ComponentBindingModel model) { - using var context = new SoftwareInstallationDataBase(); - var component = context.Components.FirstOrDefault(x => x.Id == - model.Id); + using var context = new SoftwareInstallationDatabase(); + var component = context.Components.FirstOrDefault(x => x.Id == model.Id); if (component == null) { return null; @@ -72,11 +62,11 @@ namespace SoftwareInstallationDatabaseImplement.Implements context.SaveChanges(); return component.GetViewModel; } + public ComponentViewModel? Delete(ComponentBindingModel model) { - using var context = new SoftwareInstallationDataBase(); - var element = context.Components.FirstOrDefault(rec => rec.Id == - model.Id); + using var context = new SoftwareInstallationDatabase(); + var element = context.Components.FirstOrDefault(rec => rec.Id == model.Id); if (element != null) { context.Components.Remove(element); @@ -86,6 +76,4 @@ namespace SoftwareInstallationDatabaseImplement.Implements return null; } } - - } diff --git a/SoftwareInstallationDatabaseImplement/Implements/OrderStorage.cs b/SoftwareInstallationDatabaseImplement/Implements/OrderStorage.cs index 3cee65c..2ca33b7 100644 --- a/SoftwareInstallationDatabaseImplement/Implements/OrderStorage.cs +++ b/SoftwareInstallationDatabaseImplement/Implements/OrderStorage.cs @@ -3,11 +3,7 @@ using SoftwareInstallationContracts.SearchModels; using SoftwareInstallationContracts.StoragesContracts; using SoftwareInstallationContracts.ViewModels; using SoftwareInstallationDatabaseImplement.Models; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; namespace SoftwareInstallationDatabaseImplement.Implements { @@ -15,85 +11,69 @@ namespace SoftwareInstallationDatabaseImplement.Implements { public List GetFullList() { - using var context = new SoftwareInstallationDataBase(); - return context.Orders - .Select(x => AccessPackageStorage(x.GetViewModel)) - .ToList(); + using var context = new SoftwareInstallationDatabase(); + return context.Orders.Include(x => x.Package).Select(x => x.GetViewModel).ToList(); } + public List GetFilteredList(OrderSearchModel model) { if (!model.Id.HasValue) { return new(); } - using var context = new SoftwareInstallationDataBase(); - return context.Orders - .Where(x => x.Id == model.Id) - .Select(x => AccessPackageStorage(x.GetViewModel)) - .ToList(); + using var context = new SoftwareInstallationDatabase(); + return context.Orders.Include(x => x.Package).Where(x => x.Id == model.Id).Select(x => x.GetViewModel).ToList(); } + public OrderViewModel? GetElement(OrderSearchModel model) { if (!model.Id.HasValue) { - return null; + return new(); } - using var context = new SoftwareInstallationDataBase(); - return AccessPackageStorage(context.Orders.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel); + using var context = new SoftwareInstallationDatabase(); + return context.Orders.Include(x => x.Package).FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; } + public OrderViewModel? Insert(OrderBindingModel model) { - var newOrder = Order.Create(model); + using var context = new SoftwareInstallationDatabase(); + if (model == null) + return null; + var newOrder = Order.Create(context, model); if (newOrder == null) { return null; } - using var context = new SoftwareInstallationDataBase(); context.Orders.Add(newOrder); context.SaveChanges(); - return AccessPackageStorage(newOrder.GetViewModel); + return newOrder.GetViewModel; } + public OrderViewModel? Update(OrderBindingModel model) { - using var context = new SoftwareInstallationDataBase(); - var order = context.Orders.FirstOrDefault(x => x.Id == - model.Id); + using var context = new SoftwareInstallationDatabase(); + var order = context.Orders.FirstOrDefault(x => x.Id == model.Id); if (order == null) { return null; } order.Update(model); context.SaveChanges(); - return AccessPackageStorage(order.GetViewModel); + return order.GetViewModel; } + public OrderViewModel? Delete(OrderBindingModel model) { - using var context = new SoftwareInstallationDataBase(); - var element = context.Orders.FirstOrDefault(rec => rec.Id == - model.Id); - if (element != null) + using var context = new SoftwareInstallationDatabase(); + var order = context.Orders.FirstOrDefault(rec => rec.Id == model.Id); + if (order != null) { - context.Orders.Remove(element); + context.Orders.Remove(order); context.SaveChanges(); - return AccessPackageStorage(element.GetViewModel); + return order.GetViewModel; } return null; } - - public static OrderViewModel AccessPackageStorage(OrderViewModel model) - { - if (model == null) - return null; - using var context = new SoftwareInstallationDataBase(); - foreach (var Package in context.Packages) - { - if (Package.Id == model.PackageId) - { - model.PackageName = Package.PackageName; - break; - } - } - return model; - } } } diff --git a/SoftwareInstallationDatabaseImplement/Implements/PackageStorage.cs b/SoftwareInstallationDatabaseImplement/Implements/PackageStorage.cs index c26a8b4..7a5ef2d 100644 --- a/SoftwareInstallationDatabaseImplement/Implements/PackageStorage.cs +++ b/SoftwareInstallationDatabaseImplement/Implements/PackageStorage.cs @@ -4,11 +4,6 @@ using SoftwareInstallationContracts.StoragesContracts; using SoftwareInstallationContracts.ViewModels; using SoftwareInstallationDatabaseImplement.Models; using Microsoft.EntityFrameworkCore; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace SoftwareInstallationDatabaseImplement.Implements { @@ -16,48 +11,39 @@ namespace SoftwareInstallationDatabaseImplement.Implements { public List GetFullList() { - using var context = new SoftwareInstallationDataBase(); - return context.Packages - .Include(x => x.Components) - .ThenInclude(x => x.Component) - .ToList() - .Select(x => x.GetViewModel) - .ToList(); + using var context = new SoftwareInstallationDatabase(); + return context.Packages.Include(x => x.Components).ThenInclude(x => x.Component).ToList() + .Select(x => x.GetViewModel).ToList(); } + public List GetFilteredList(PackageSearchModel model) { if (string.IsNullOrEmpty(model.PackageName)) { return new(); } - using var context = new SoftwareInstallationDataBase(); - return context.Packages.Include(x => x.Components) - .ThenInclude(x => x.Component) - .Where(x => x.PackageName.Contains(model.PackageName)) - .ToList() - .Select(x => x.GetViewModel) - .ToList(); + using var context = new SoftwareInstallationDatabase(); + return context.Packages.Include(x => x.Components).ThenInclude(x => x.Component) + .Where(x => x.PackageName.Contains(model.PackageName)).ToList().Select(x => x.GetViewModel).ToList(); } + public PackageViewModel? GetElement(PackageSearchModel model) { - if (string.IsNullOrEmpty(model.PackageName) && - !model.Id.HasValue) + if (string.IsNullOrEmpty(model.PackageName) && !model.Id.HasValue) { return null; } - using var context = new SoftwareInstallationDataBase(); - return context.Packages - .Include(x => x.Components) - .ThenInclude(x => x.Component) - .FirstOrDefault(x => (!string.IsNullOrEmpty(model.PackageName) && - x.PackageName == model.PackageName) || - (model.Id.HasValue && x.Id == - model.Id)) - ?.GetViewModel; + using var context = new SoftwareInstallationDatabase(); + return context.Packages.Include(x => x.Components).ThenInclude(x => x.Component) + .FirstOrDefault(x => + (!string.IsNullOrEmpty(model.PackageName) && x.PackageName == model.PackageName) || + (model.Id.HasValue && x.Id == model.Id)) + ?.GetViewModel; } + public PackageViewModel? Insert(PackageBindingModel model) { - using var context = new SoftwareInstallationDataBase(); + using var context = new SoftwareInstallationDatabase(); var newPackage = Package.Create(context, model); if (newPackage == null) { @@ -67,14 +53,14 @@ namespace SoftwareInstallationDatabaseImplement.Implements context.SaveChanges(); return newPackage.GetViewModel; } + public PackageViewModel? Update(PackageBindingModel model) { - using var context = new SoftwareInstallationDataBase(); + using var context = new SoftwareInstallationDatabase(); using var transaction = context.Database.BeginTransaction(); try { - var Package = context.Packages.FirstOrDefault(rec => - rec.Id == model.Id); + var Package = context.Packages.FirstOrDefault(rec => rec.Id == model.Id); if (Package == null) { return null; @@ -91,12 +77,11 @@ namespace SoftwareInstallationDatabaseImplement.Implements throw; } } + public PackageViewModel? Delete(PackageBindingModel model) { - using var context = new SoftwareInstallationDataBase(); - var element = context.Packages - .Include(x => x.Components) - .FirstOrDefault(rec => rec.Id == model.Id); + using var context = new SoftwareInstallationDatabase(); + var element = context.Packages.Include(x => x.Components).FirstOrDefault(rec => rec.Id == model.Id); if (element != null) { context.Packages.Remove(element); @@ -107,4 +92,3 @@ namespace SoftwareInstallationDatabaseImplement.Implements } } } - diff --git a/SoftwareInstallationDatabaseImplement/Implements/ShopStorage.cs b/SoftwareInstallationDatabaseImplement/Implements/ShopStorage.cs new file mode 100644 index 0000000..1f857be --- /dev/null +++ b/SoftwareInstallationDatabaseImplement/Implements/ShopStorage.cs @@ -0,0 +1,185 @@ +using Microsoft.EntityFrameworkCore; +using SoftwareInstallationContracts.BindingModels; +using SoftwareInstallationContracts.SearchModels; +using SoftwareInstallationContracts.StoragesContracts; +using SoftwareInstallationContracts.ViewModels; +using SoftwareInstallationDatabaseImplement.Models; + +namespace SoftwareInstallationDatabaseImplement.Implements +{ + public class ShopStorage : IShopStorage + { + public List GetFullList() + { + using var context = new SoftwareInstallationDatabase(); + return context.Shops.Include(x => x.Packages).ThenInclude(x => x.Package).ToList(). + Select(x => x.GetViewModel).ToList(); + } + + public List GetFilteredList(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.ShopName)) + { + return new(); + } + using var context = new SoftwareInstallationDatabase(); + return context.Shops.Include(x => x.Packages).ThenInclude(x => x.Package).Where(x => x.ShopName.Contains(model.ShopName)). + ToList().Select(x => x.GetViewModel).ToList(); + } + + public ShopViewModel? GetElement(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.ShopName) && !model.Id.HasValue) + { + return new(); + } + using var context = new SoftwareInstallationDatabase(); + return context.Shops.Include(x => x.Packages).ThenInclude(x => x.Package) + .FirstOrDefault(x => + (!string.IsNullOrEmpty(model.ShopName) && x.ShopName == model.ShopName) || + (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; + } + + public ShopViewModel? Insert(ShopBindingModel model) + { + using var context = new SoftwareInstallationDatabase(); + 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 SoftwareInstallationDatabase(); + using var transaction = context.Database.BeginTransaction(); + try + { + var shop = context.Shops.FirstOrDefault(x => x.Id == model.Id); + if (shop == null) + { + return null; + } + shop.Update(model); + context.SaveChanges(); + shop.UpdatePackages(context, model); + transaction.Commit(); + return shop.GetViewModel; + } + catch + { + transaction.Rollback(); + throw; + } + } + + public ShopViewModel? Delete(ShopBindingModel model) + { + using var context = new SoftwareInstallationDatabase(); + var shop = context.Shops.Include(x => x.Packages).FirstOrDefault(x => x.Id == model.Id); + if (shop != null) + { + context.Shops.Remove(shop); + context.SaveChanges(); + return shop.GetViewModel; + } + return null; + } + + public bool RestockingShops(SupplyBindingModel model) + { + using var context = new SoftwareInstallationDatabase(); + var transaction = context.Database.BeginTransaction(); + var Shops = context.Shops.Include(x => x.Packages).ThenInclude(x => x.Package).ToList(). + Where(x => x.PackageMaxCount > x.ShopPackages.Select(x => x.Value.Item2).Sum()).ToList(); + if (model == null) + { + return false; + } + try + { + foreach (Shop shop in Shops) + { + int difference = shop.PackageMaxCount - shop.ShopPackages.Select(x => x.Value.Item2).Sum(); + int refill = Math.Min(difference, model.Count); + model.Count -= refill; + if (shop.ShopPackages.ContainsKey(model.PackageId)) + { + var datePair = shop.ShopPackages[model.PackageId]; + datePair.Item2 += refill; + shop.ShopPackages[model.PackageId] = datePair; + } + else + { + var pizza = context.Packages.First(x => x.Id == model.PackageId); + shop.ShopPackages.Add(model.PackageId, (pizza, refill)); + } + shop.PackagesDictionatyUpdate(context); + if (model.Count == 0) + { + transaction.Commit(); + return true; + } + } + transaction.Rollback(); + return false; + } + catch + { + transaction.Rollback(); + throw; + } + } + + public bool Sale(SupplySearchModel model) + { + using var context = new SoftwareInstallationDatabase(); + var transaction = context.Database.BeginTransaction(); + try + { + var shops = context.Shops.Include(x => x.Packages).ThenInclude(x => x.Package).ToList(). + Where(x => x.ShopPackages.ContainsKey(model.PackageId.Value)).OrderByDescending(x => x.ShopPackages[model.PackageId.Value].Item2).ToList(); + + foreach (var shop in shops) + { + int residue = model.Count.Value - shop.ShopPackages[model.PackageId.Value].Item2; + if (residue > 0) + { + shop.ShopPackages.Remove(model.PackageId.Value); + shop.PackagesDictionatyUpdate(context); + context.SaveChanges(); + model.Count = residue; + + } + else + { + if (residue == 0) + shop.ShopPackages.Remove(model.PackageId.Value); + else + { + var dataPair = shop.ShopPackages[model.PackageId.Value]; + dataPair.Item2 = -residue; + shop.ShopPackages[model.PackageId.Value] = dataPair; + } + + shop.PackagesDictionatyUpdate(context); + transaction.Commit(); + return true; + } + } + transaction.Rollback(); + return false; + } + catch + { + transaction.Rollback(); + throw; + } + } + + } +} diff --git a/SoftwareInstallationDatabaseImplement/Migrations/20240308202100_InitialCreate.Designer.cs b/SoftwareInstallationDatabaseImplement/Migrations/20240304162421_InitialCreate.Designer.cs similarity index 96% rename from SoftwareInstallationDatabaseImplement/Migrations/20240308202100_InitialCreate.Designer.cs rename to SoftwareInstallationDatabaseImplement/Migrations/20240304162421_InitialCreate.Designer.cs index ff57b77..9137f61 100644 --- a/SoftwareInstallationDatabaseImplement/Migrations/20240308202100_InitialCreate.Designer.cs +++ b/SoftwareInstallationDatabaseImplement/Migrations/20240304162421_InitialCreate.Designer.cs @@ -11,8 +11,8 @@ using SoftwareInstallationDatabaseImplement; namespace SoftwareInstallationDatabaseImplement.Migrations { - [DbContext(typeof(SoftwareInstallationDataBase))] - [Migration("20240308202100_InitialCreate")] + [DbContext(typeof(SoftwareInstallationDatabase))] + [Migration("20240304162421_InitialCreate")] partial class InitialCreate { /// @@ -20,7 +20,7 @@ namespace SoftwareInstallationDatabaseImplement.Migrations { #pragma warning disable 612, 618 modelBuilder - .HasAnnotation("ProductVersion", "8.0.2") + .HasAnnotation("ProductVersion", "7.0.3") .HasAnnotation("Relational:MaxIdentifierLength", 128); SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); @@ -62,15 +62,15 @@ namespace SoftwareInstallationDatabaseImplement.Migrations b.Property("DateImplement") .HasColumnType("datetime2"); + b.Property("PackageId") + .HasColumnType("int"); + b.Property("Status") .HasColumnType("int"); b.Property("Sum") .HasColumnType("float"); - b.Property("PackageId") - .HasColumnType("int"); - b.HasKey("Id"); b.HasIndex("PackageId"); @@ -86,13 +86,13 @@ namespace SoftwareInstallationDatabaseImplement.Migrations SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); - b.Property("Price") - .HasColumnType("float"); - b.Property("PackageName") .IsRequired() .HasColumnType("nvarchar(max)"); + b.Property("Price") + .HasColumnType("float"); + b.HasKey("Id"); b.ToTable("Packages"); @@ -126,11 +126,13 @@ namespace SoftwareInstallationDatabaseImplement.Migrations modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.Order", b => { - b.HasOne("SoftwareInstallationDatabaseImplement.Models.Package", null) + b.HasOne("SoftwareInstallationDatabaseImplement.Models.Package", "Package") .WithMany("Orders") .HasForeignKey("PackageId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); + + b.Navigation("Package"); }); modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.PackageComponent", b => diff --git a/SoftwareInstallationDatabaseImplement/Migrations/20240308202100_InitialCreate.cs b/SoftwareInstallationDatabaseImplement/Migrations/20240304162421_InitialCreate.cs similarity index 99% rename from SoftwareInstallationDatabaseImplement/Migrations/20240308202100_InitialCreate.cs rename to SoftwareInstallationDatabaseImplement/Migrations/20240304162421_InitialCreate.cs index 9269a8b..1f19007 100644 --- a/SoftwareInstallationDatabaseImplement/Migrations/20240308202100_InitialCreate.cs +++ b/SoftwareInstallationDatabaseImplement/Migrations/20240304162421_InitialCreate.cs @@ -45,12 +45,12 @@ namespace SoftwareInstallationDatabaseImplement.Migrations { Id = table.Column(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), + PackageId = table.Column(type: "int", 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), - PackageId = table.Column(type: "int", nullable: false) + DateImplement = table.Column(type: "datetime2", nullable: true) }, constraints: table => { diff --git a/SoftwareInstallationDatabaseImplement/Migrations/20240305050232_Hard_init.Designer.cs b/SoftwareInstallationDatabaseImplement/Migrations/20240305050232_Hard_init.Designer.cs new file mode 100644 index 0000000..f052298 --- /dev/null +++ b/SoftwareInstallationDatabaseImplement/Migrations/20240305050232_Hard_init.Designer.cs @@ -0,0 +1,248 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using SoftwareInstallationDatabaseImplement; + +#nullable disable + +namespace SoftwareInstallationDatabaseImplement.Migrations +{ + [DbContext(typeof(SoftwareInstallationDatabase))] + [Migration("20240305050232_Hard_init")] + partial class Hard_init + { + /// + 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("SoftwareInstallationDatabaseImplement.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("SoftwareInstallationDatabaseImplement.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("PackageId") + .HasColumnType("int"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("Sum") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.HasIndex("PackageId"); + + b.ToTable("Orders"); + }); + + modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.Package", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("PackageName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Price") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.PackageComponent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ComponentId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("PackageId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ComponentId"); + + b.HasIndex("PackageId"); + + b.ToTable("PackageComponents"); + }); + + modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.Shop", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Adress") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("OpeningDate") + .HasColumnType("datetime2"); + + b.Property("PackageMaxCount") + .HasColumnType("int"); + + b.Property("ShopName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Shops"); + }); + + modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.ShopPackages", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("PackageId") + .HasColumnType("int"); + + b.Property("ShopId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("PackageId"); + + b.HasIndex("ShopId"); + + b.ToTable("ShopPackages"); + }); + + modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.Order", b => + { + b.HasOne("SoftwareInstallationDatabaseImplement.Models.Package", "Package") + .WithMany("Orders") + .HasForeignKey("PackageId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.PackageComponent", b => + { + b.HasOne("SoftwareInstallationDatabaseImplement.Models.Component", "Component") + .WithMany("PackageComponents") + .HasForeignKey("ComponentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("SoftwareInstallationDatabaseImplement.Models.Package", "Package") + .WithMany("Components") + .HasForeignKey("PackageId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Component"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.ShopPackages", b => + { + b.HasOne("SoftwareInstallationDatabaseImplement.Models.Package", "Package") + .WithMany("ShopPackages") + .HasForeignKey("PackageId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("SoftwareInstallationDatabaseImplement.Models.Shop", "Shop") + .WithMany("Packages") + .HasForeignKey("ShopId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + + b.Navigation("Shop"); + }); + + modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.Component", b => + { + b.Navigation("PackageComponents"); + }); + + modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.Package", b => + { + b.Navigation("Components"); + + b.Navigation("Orders"); + }); + + modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.Shop", b => + { + b.Navigation("Packages"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/SoftwareInstallationDatabaseImplement/Migrations/20240305050232_Hard_init.cs b/SoftwareInstallationDatabaseImplement/Migrations/20240305050232_Hard_init.cs new file mode 100644 index 0000000..f8cfc54 --- /dev/null +++ b/SoftwareInstallationDatabaseImplement/Migrations/20240305050232_Hard_init.cs @@ -0,0 +1,78 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace SoftwareInstallationDatabaseImplement.Migrations +{ + /// + public partial class Hard_init : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Shops", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + ShopName = table.Column(type: "nvarchar(max)", nullable: false), + Adress = table.Column(type: "nvarchar(max)", nullable: false), + OpeningDate = table.Column(type: "datetime2", nullable: false), + PackageMaxCount = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Shops", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "ShopPackages", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + PackageId = table.Column(type: "int", nullable: false), + ShopId = table.Column(type: "int", nullable: false), + Count = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ShopPackages", x => x.Id); + table.ForeignKey( + name: "FK_ShopPackages_Packages_PackageId", + column: x => x.PackageId, + principalTable: "Packages", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_ShopPackages_Shops_ShopId", + column: x => x.ShopId, + principalTable: "Shops", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_ShopPackages_PackageId", + table: "ShopPackages", + column: "PackageId"); + + migrationBuilder.CreateIndex( + name: "IX_ShopPackages_ShopId", + table: "ShopPackages", + column: "ShopId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ShopPackages"); + + migrationBuilder.DropTable( + name: "Shops"); + } + } +} diff --git a/SoftwareInstallationDatabaseImplement/Migrations/TravelCompanyDataBaseModelSnapshot.cs b/SoftwareInstallationDatabaseImplement/Migrations/PizzeriaDatabaseModelSnapshot.cs similarity index 65% rename from SoftwareInstallationDatabaseImplement/Migrations/TravelCompanyDataBaseModelSnapshot.cs rename to SoftwareInstallationDatabaseImplement/Migrations/PizzeriaDatabaseModelSnapshot.cs index 16d6f3d..43a9bd5 100644 --- a/SoftwareInstallationDatabaseImplement/Migrations/TravelCompanyDataBaseModelSnapshot.cs +++ b/SoftwareInstallationDatabaseImplement/Migrations/PizzeriaDatabaseModelSnapshot.cs @@ -10,14 +10,14 @@ using SoftwareInstallationDatabaseImplement; namespace SoftwareInstallationDatabaseImplement.Migrations { - [DbContext(typeof(SoftwareInstallationDataBase))] - partial class SoftwareInstallationDataBaseModelSnapshot : ModelSnapshot + [DbContext(typeof(SoftwareInstallationDatabase))] + partial class SoftwareInstallationDatabaseModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder - .HasAnnotation("ProductVersion", "8.0.2") + .HasAnnotation("ProductVersion", "7.0.3") .HasAnnotation("Relational:MaxIdentifierLength", 128); SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); @@ -59,15 +59,15 @@ namespace SoftwareInstallationDatabaseImplement.Migrations b.Property("DateImplement") .HasColumnType("datetime2"); + b.Property("PackageId") + .HasColumnType("int"); + b.Property("Status") .HasColumnType("int"); b.Property("Sum") .HasColumnType("float"); - b.Property("PackageId") - .HasColumnType("int"); - b.HasKey("Id"); b.HasIndex("PackageId"); @@ -83,13 +83,13 @@ namespace SoftwareInstallationDatabaseImplement.Migrations SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); - b.Property("Price") - .HasColumnType("float"); - b.Property("PackageName") .IsRequired() .HasColumnType("nvarchar(max)"); + b.Property("Price") + .HasColumnType("float"); + b.HasKey("Id"); b.ToTable("Packages"); @@ -121,13 +121,68 @@ namespace SoftwareInstallationDatabaseImplement.Migrations b.ToTable("PackageComponents"); }); + modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.Shop", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Adress") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("OpeningDate") + .HasColumnType("datetime2"); + + b.Property("PackageMaxCount") + .HasColumnType("int"); + + b.Property("ShopName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Shops"); + }); + + modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.ShopPackages", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("PackageId") + .HasColumnType("int"); + + b.Property("ShopId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("PackageId"); + + b.HasIndex("ShopId"); + + b.ToTable("ShopPackages"); + }); + modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.Order", b => { - b.HasOne("SoftwareInstallationDatabaseImplement.Models.Package", null) + b.HasOne("SoftwareInstallationDatabaseImplement.Models.Package", "Package") .WithMany("Orders") .HasForeignKey("PackageId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); + + b.Navigation("Package"); }); modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.PackageComponent", b => @@ -149,6 +204,25 @@ namespace SoftwareInstallationDatabaseImplement.Migrations b.Navigation("Package"); }); + modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.ShopPackages", b => + { + b.HasOne("SoftwareInstallationDatabaseImplement.Models.Package", "Package") + .WithMany("ShopPackages") + .HasForeignKey("PackageId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("SoftwareInstallationDatabaseImplement.Models.Shop", "Shop") + .WithMany("Packages") + .HasForeignKey("ShopId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + + b.Navigation("Shop"); + }); + modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.Component", b => { b.Navigation("PackageComponents"); @@ -160,6 +234,11 @@ namespace SoftwareInstallationDatabaseImplement.Migrations b.Navigation("Orders"); }); + + modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.Shop", b => + { + b.Navigation("Packages"); + }); #pragma warning restore 612, 618 } } diff --git a/SoftwareInstallationDatabaseImplement/Models/Component.cs b/SoftwareInstallationDatabaseImplement/Models/Component.cs index 433f0d4..ca375c7 100644 --- a/SoftwareInstallationDatabaseImplement/Models/Component.cs +++ b/SoftwareInstallationDatabaseImplement/Models/Component.cs @@ -1,13 +1,8 @@ using SoftwareInstallationContracts.BindingModels; using SoftwareInstallationContracts.ViewModels; -using SoftwareInstallationDataModels.Models; -using System; -using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using SoftwareInstallationDataModels.Models; namespace SoftwareInstallationDatabaseImplement.Models { @@ -19,8 +14,8 @@ namespace SoftwareInstallationDatabaseImplement.Models [Required] public double Cost { get; set; } [ForeignKey("ComponentId")] - public virtual List PackageComponents { get; set; } = - new(); + public virtual List PackageComponents { get; set; } = new(); + public static Component? Create(ComponentBindingModel model) { if (model == null) @@ -34,6 +29,7 @@ namespace SoftwareInstallationDatabaseImplement.Models Cost = model.Cost }; } + public static Component Create(ComponentViewModel model) { return new Component @@ -43,6 +39,7 @@ namespace SoftwareInstallationDatabaseImplement.Models Cost = model.Cost }; } + public void Update(ComponentBindingModel model) { if (model == null) @@ -52,6 +49,7 @@ namespace SoftwareInstallationDatabaseImplement.Models ComponentName = model.ComponentName; Cost = model.Cost; } + public ComponentViewModel GetViewModel => new() { Id = Id, @@ -60,4 +58,3 @@ namespace SoftwareInstallationDatabaseImplement.Models }; } } - diff --git a/SoftwareInstallationDatabaseImplement/Models/Order.cs b/SoftwareInstallationDatabaseImplement/Models/Order.cs index f15544f..9d38730 100644 --- a/SoftwareInstallationDatabaseImplement/Models/Order.cs +++ b/SoftwareInstallationDatabaseImplement/Models/Order.cs @@ -2,45 +2,45 @@ using SoftwareInstallationContracts.ViewModels; using SoftwareInstallationDataModels.Enums; using SoftwareInstallationDataModels.Models; -using System; -using System.Collections.Generic; using System.ComponentModel.DataAnnotations; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace SoftwareInstallationDatabaseImplement.Models { public class Order : IOrderModel { public int Id { get; private set; } - [Required] - public int Count { get; private set; } - [Required] - public double Sum { get; private set; } - [Required] - public OrderStatus Status { get; private set; } - [Required] - public DateTime DateCreate { get; private set; } - public DateTime? DateImplement { get; private set; } + [Required] public int PackageId { get; private set; } - public static Order? Create(OrderBindingModel model) + public virtual Package Package { get; set; } = new(); + + [Required] + public int Count { get; private set; } + + [Required] + public double Sum { get; private set; } + + [Required] + public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен; + + [Required] + public DateTime DateCreate { get; private set; } = DateTime.Now; + + public DateTime? DateImplement { get; private set; } + + public static Order Create(SoftwareInstallationDatabase context, OrderBindingModel model) { - if (model == null) - { - return null; - } return new Order() { Id = model.Id, + PackageId = model.PackageId, + Package = context.Packages.First(x => x.Id == model.PackageId), Count = model.Count, Sum = model.Sum, Status = model.Status, DateCreate = model.DateCreate, DateImplement = model.DateImplement, - PackageId = model.PackageId, }; } @@ -56,14 +56,14 @@ namespace SoftwareInstallationDatabaseImplement.Models public OrderViewModel GetViewModel => new() { + Id = Id, PackageId = PackageId, + PackageName = Package.PackageName, Count = Count, Sum = Sum, Status = Status, DateCreate = DateCreate, DateImplement = DateImplement, - Id = Id, }; - } } diff --git a/SoftwareInstallationDatabaseImplement/Models/Package.cs b/SoftwareInstallationDatabaseImplement/Models/Package.cs index 768457d..9a3f464 100644 --- a/SoftwareInstallationDatabaseImplement/Models/Package.cs +++ b/SoftwareInstallationDatabaseImplement/Models/Package.cs @@ -1,13 +1,8 @@ using SoftwareInstallationContracts.BindingModels; using SoftwareInstallationContracts.ViewModels; using SoftwareInstallationDataModels.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; +using System.ComponentModel.DataAnnotations; namespace SoftwareInstallationDatabaseImplement.Models { @@ -18,47 +13,51 @@ namespace SoftwareInstallationDatabaseImplement.Models public string PackageName { get; set; } = string.Empty; [Required] public double Price { get; set; } - private Dictionary? _PackageComponents = - null; + + private Dictionary? _pizzaComponents = null; [NotMapped] public Dictionary PackageComponents { get { - if (_PackageComponents == null) + if (_pizzaComponents == null) { - _PackageComponents = Components - .ToDictionary(recPC => recPC.ComponentId, recPC => - (recPC.Component as IComponentModel, recPC.Count)); + _pizzaComponents = Components.ToDictionary(recPC => recPC.ComponentId, recPC => + (recPC.Component as IComponentModel, recPC.Count)); } - return _PackageComponents; + return _pizzaComponents; } } [ForeignKey("PackageId")] public virtual List Components { get; set; } = new(); [ForeignKey("PackageId")] public virtual List Orders { get; set; } = new(); - public static Package Create(SoftwareInstallationDataBase context, - PackageBindingModel model) + + [ForeignKey("PackageId")] + public virtual List ShopPackages { get; set; } = new(); + + public static Package + Create(SoftwareInstallationDatabase context, PackageBindingModel model) { return new Package() { Id = model.Id, PackageName = model.PackageName, Price = model.Price, - Components = model.PackageComponents.Select(x => new - PackageComponent + Components = model.PackageComponents.Select(x => new PackageComponent { Component = context.Components.First(y => y.Id == x.Key), Count = x.Value.Item2 }).ToList() }; } + public void Update(PackageBindingModel model) { PackageName = model.PackageName; Price = model.Price; } + public PackageViewModel GetViewModel => new() { Id = Id, @@ -66,38 +65,35 @@ namespace SoftwareInstallationDatabaseImplement.Models Price = Price, PackageComponents = PackageComponents }; - public void UpdateComponents(SoftwareInstallationDataBase context, - PackageBindingModel model) - { - var PackageComponents = context.PackageComponents.Where(rec => - rec.PackageId == model.Id).ToList(); - if (PackageComponents != null && PackageComponents.Count > 0) - { - context.PackageComponents.RemoveRange(PackageComponents.Where(rec -=> !model.PackageComponents.ContainsKey(rec.ComponentId))); + public void UpdateComponents(SoftwareInstallationDatabase context, PackageBindingModel model) + { + var pizzaComponents = context.PackageComponents.Where(rec => rec.PackageId == model.Id).ToList(); + + if (pizzaComponents != null && pizzaComponents.Count > 0) + { + context.PackageComponents.RemoveRange(pizzaComponents.Where(rec => !model.PackageComponents.ContainsKey(rec.ComponentId))); context.SaveChanges(); - foreach (var updateComponent in PackageComponents) + foreach (var updateComponent in pizzaComponents) { - updateComponent.Count = - model.PackageComponents[updateComponent.ComponentId].Item2; + updateComponent.Count = model.PackageComponents[updateComponent.ComponentId].Item2; model.PackageComponents.Remove(updateComponent.ComponentId); } context.SaveChanges(); } - var Package = context.Packages.First(x => x.Id == Id); + + var pizza = context.Packages.First(x => x.Id == Id); foreach (var pc in model.PackageComponents) { context.PackageComponents.Add(new PackageComponent { - Package = Package, + Package = pizza, Component = context.Components.First(x => x.Id == pc.Key), Count = pc.Value.Item2 }); context.SaveChanges(); } - _PackageComponents = null; + _pizzaComponents = null; } } } - diff --git a/SoftwareInstallationDatabaseImplement/Models/PackageComponent.cs b/SoftwareInstallationDatabaseImplement/Models/PackageComponent.cs index 1a77b44..9e93c65 100644 --- a/SoftwareInstallationDatabaseImplement/Models/PackageComponent.cs +++ b/SoftwareInstallationDatabaseImplement/Models/PackageComponent.cs @@ -1,14 +1,9 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.ComponentModel.DataAnnotations; namespace SoftwareInstallationDatabaseImplement.Models { public class PackageComponent - {//мы создаем этот доп класс, он содержит информацию сущностей Component и Package и создаем доп элементы которые будут в таблице(многие-ко-многим) + { public int Id { get; set; } [Required] public int PackageId { get; set; } diff --git a/SoftwareInstallationDatabaseImplement/Models/Shop.cs b/SoftwareInstallationDatabaseImplement/Models/Shop.cs new file mode 100644 index 0000000..7896df5 --- /dev/null +++ b/SoftwareInstallationDatabaseImplement/Models/Shop.cs @@ -0,0 +1,114 @@ +using SoftwareInstallationContracts.BindingModels; +using SoftwareInstallationContracts.ViewModels; +using SoftwareInstallationDataModels.Models; +using System.ComponentModel.DataAnnotations.Schema; + +namespace SoftwareInstallationDatabaseImplement.Models +{ + public class Shop : IShopModel + { + public int Id { get; set; } + public string ShopName { get; set; } = string.Empty; + + public string Adress { get; set; } = string.Empty; + + public DateTime OpeningDate { get; set; } + + public int PackageMaxCount { get; set; } + + private Dictionary? _shopPackages = null; + + public Dictionary ShopPackages + { + get + { + if (_shopPackages == null) + { + if (_shopPackages == null) + { + _shopPackages = Packages + .ToDictionary(recSP => recSP.PackageId, recSP => (recSP.Package as IPackageModel, recSP.Count)); + } + return _shopPackages; + } + return _shopPackages; + } + } + + [ForeignKey("ShopId")] + public List Packages { get; set; } = new(); + + public static Shop Create(SoftwareInstallationDatabase context, ShopBindingModel model) + { + return new Shop() + { + Id = model.Id, + ShopName = model.ShopName, + Adress = model.Adress, + OpeningDate = model.OpeningDate, + Packages = model.ShopPackages.Select(x => new ShopPackages + { + Package = context.Packages.First(y => y.Id == x.Key), + Count = x.Value.Item2 + }).ToList(), + PackageMaxCount = model.PackageMaxCount + }; + } + + public void Update(ShopBindingModel model) + { + ShopName = model.ShopName; + Adress = model.Adress; + OpeningDate = model.OpeningDate; + PackageMaxCount = model.PackageMaxCount; + } + + public ShopViewModel GetViewModel => new() + { + Id = Id, + ShopName = ShopName, + Adress = Adress, + OpeningDate = OpeningDate, + ShopPackages = ShopPackages, + PackageMaxCount = PackageMaxCount + }; + + public void UpdatePackages(SoftwareInstallationDatabase context, ShopBindingModel model) + { + var ShopPackages = context.ShopPackages.Where(rec => rec.ShopId == model.Id).ToList(); + if (ShopPackages != null && ShopPackages.Count > 0) + { + context.ShopPackages.RemoveRange(ShopPackages.Where(rec => !model.ShopPackages.ContainsKey(rec.PackageId))); + context.SaveChanges(); + ShopPackages = context.ShopPackages.Where(rec => rec.ShopId == model.Id).ToList(); + foreach (var updatePackage in ShopPackages) + { + updatePackage.Count = model.ShopPackages[updatePackage.PackageId].Item2; + model.ShopPackages.Remove(updatePackage.PackageId); + } + context.SaveChanges(); + } + var shop = context.Shops.First(x => x.Id == Id); + foreach (var ar in model.ShopPackages) + { + context.ShopPackages.Add(new ShopPackages + { + Shop = shop, + Package = context.Packages.First(x => x.Id == ar.Key), + Count = ar.Value.Item2 + }); + context.SaveChanges(); + } + _shopPackages = null; + } + + public void PackagesDictionatyUpdate(SoftwareInstallationDatabase context) + { + UpdatePackages(context, new ShopBindingModel + { + Id = Id, + ShopPackages = ShopPackages, + }); + } + } +} diff --git a/SoftwareInstallationDatabaseImplement/Models/ShopPackages.cs b/SoftwareInstallationDatabaseImplement/Models/ShopPackages.cs new file mode 100644 index 0000000..a601c4d --- /dev/null +++ b/SoftwareInstallationDatabaseImplement/Models/ShopPackages.cs @@ -0,0 +1,22 @@ +using System.ComponentModel.DataAnnotations; + +namespace SoftwareInstallationDatabaseImplement.Models +{ + public class ShopPackages + { + public int Id { get; set; } + + [Required] + public int PackageId { get; set; } + + [Required] + public int ShopId { get; set; } + + [Required] + public int Count { get; set; } + + public virtual Shop Shop { get; set; } = new(); + + public virtual Package Package { get; set; } = new(); + } +} diff --git a/SoftwareInstallationDatabaseImplement/SoftwareInstallationDataBase.cs b/SoftwareInstallationDatabaseImplement/SoftwareInstallationDataBase.cs index 6591ef3..d812c69 100644 --- a/SoftwareInstallationDatabaseImplement/SoftwareInstallationDataBase.cs +++ b/SoftwareInstallationDatabaseImplement/SoftwareInstallationDataBase.cs @@ -1,29 +1,24 @@ using SoftwareInstallationDatabaseImplement.Models; using Microsoft.EntityFrameworkCore; -using System; using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace SoftwareInstallationDatabaseImplement -{//здесь определяются сущности и подключение к серверу - public class SoftwareInstallationDataBase : DbContext +{ + public class SoftwareInstallationDatabase : DbContext { - protected override void OnConfiguring(DbContextOptionsBuilder -optionsBuilder) + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { - if (optionsBuilder.IsConfigured == false) + if (!optionsBuilder.IsConfigured) { - optionsBuilder.UseSqlServer(@"Data Source=LAPTOP-952S2NGN;Initial Catalog=SoftwareInstallationDatabase;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True"); + optionsBuilder.UseSqlServer(@"Data Source=LAPTOP-952S2NGN;Initial Catalog=SoftHard;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True"); } base.OnConfiguring(optionsBuilder); } - public virtual DbSet Components { set; get; } - public virtual DbSet Packages { set; get; } - public virtual DbSet PackageComponents { set; get; } - public virtual DbSet Orders { set; get; } - + public virtual DbSet Components { get; set; } + public virtual DbSet Packages { get; set; } + public virtual DbSet PackageComponents { get; set; } + public virtual DbSet Orders { get; set; } + public virtual DbSet Shops { get; set; } + public virtual DbSet ShopPackages { get; set; } } } diff --git a/SoftwareInstallationFileImplement/DataFileSingleton.cs b/SoftwareInstallationFileImplement/DataFileSingleton.cs index e22643d..01b4c33 100644 --- a/SoftwareInstallationFileImplement/DataFileSingleton.cs +++ b/SoftwareInstallationFileImplement/DataFileSingleton.cs @@ -1,9 +1,4 @@ using SoftwareInstallationFileImplement.Models; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using System.Xml.Linq; namespace SoftwareInstallationFileImplement @@ -14,9 +9,12 @@ namespace SoftwareInstallationFileImplement private readonly string ComponentFileName = "Component.xml"; private readonly string OrderFileName = "Order.xml"; private readonly string PackageFileName = "Package.xml"; + private readonly string ShopFileName = "Shop.xml"; public List Components { get; private set; } public List Orders { get; private set; } public List Packages { get; private set; } + public List Shops { get; private set; } + public static DataFileSingleton GetInstance() { if (instance == null) @@ -25,24 +23,29 @@ namespace SoftwareInstallationFileImplement } return instance; } + public void SaveComponents() => SaveData(Components, ComponentFileName, "Components", x => x.GetXElement); public void SavePackages() => SaveData(Packages, PackageFileName, "Packages", x => x.GetXElement); public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement); + public void SaveShops() => SaveData(Shops, ShopFileName, "Shops", x => x.GetXElement); + private DataFileSingleton() { Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!; Packages = LoadData(PackageFileName, "Package", x => Package.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) { if (File.Exists(filename)) { - return - XDocument.Load(filename)?.Root?.Elements(xmlNodeName)?.Select(selectFunction)?.ToList(); + return XDocument.Load(filename)?.Root?.Elements(xmlNodeName)?.Select(selectFunction)?.ToList(); } return new List(); } + private static void SaveData(List data, string filename, string xmlNodeName, Func selectFunction) { if (data != null) @@ -51,4 +54,4 @@ namespace SoftwareInstallationFileImplement } } } -} +} \ No newline at end of file diff --git a/SoftwareInstallationFileImplement/Implements/ComponentStorage.cs b/SoftwareInstallationFileImplement/Implements/ComponentStorage.cs index 105a8cb..d5d2688 100644 --- a/SoftwareInstallationFileImplement/Implements/ComponentStorage.cs +++ b/SoftwareInstallationFileImplement/Implements/ComponentStorage.cs @@ -1,27 +1,30 @@ -using SoftwareInstallationContracts.BindingModels; -using SoftwareInstallationContracts.SearchModels; -using SoftwareInstallationContracts.StoragesContracts; -using SoftwareInstallationContracts.ViewModels; -using SoftwareInstallationFileImplement.Models; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using SoftwareInstallationContracts.BindingModels; +using SoftwareInstallationContracts.SearchModels; +using SoftwareInstallationContracts.StoragesContracts; +using SoftwareInstallationContracts.ViewModels; +using SoftwareInstallationFileImplement.Models; namespace SoftwareInstallationFileImplement.Implements { public class ComponentStorage : IComponentStorage { private readonly DataFileSingleton source; + public ComponentStorage() { source = DataFileSingleton.GetInstance(); } + public List GetFullList() { return source.Components.Select(x => x.GetViewModel).ToList(); } + public List GetFilteredList(ComponentSearchModel model) { if (string.IsNullOrEmpty(model.ComponentName)) @@ -30,15 +33,19 @@ namespace SoftwareInstallationFileImplement.Implements } return source.Components.Where(x => x.ComponentName.Contains(model.ComponentName)).Select(x => x.GetViewModel).ToList(); } + public ComponentViewModel? GetElement(ComponentSearchModel model) { if (string.IsNullOrEmpty(model.ComponentName) && !model.Id.HasValue) { return null; } - return source.Components.FirstOrDefault(x => (!string.IsNullOrEmpty(model.ComponentName) && x.ComponentName == model.ComponentName) || - (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; + return source.Components.FirstOrDefault(x => + (!string.IsNullOrEmpty(model.ComponentName) && x.ComponentName == model.ComponentName) || + (model.Id.HasValue && x.Id == model.Id)) + ?.GetViewModel; } + public ComponentViewModel? Insert(ComponentBindingModel model) { model.Id = source.Components.Count > 0 ? source.Components.Max(x => x.Id) + 1 : 1; @@ -51,6 +58,7 @@ namespace SoftwareInstallationFileImplement.Implements source.SaveComponents(); return newComponent.GetViewModel; } + public ComponentViewModel? Update(ComponentBindingModel model) { var component = source.Components.FirstOrDefault(x => x.Id == model.Id); @@ -62,6 +70,7 @@ namespace SoftwareInstallationFileImplement.Implements source.SaveComponents(); return component.GetViewModel; } + public ComponentViewModel? Delete(ComponentBindingModel model) { var element = source.Components.FirstOrDefault(x => x.Id == model.Id); @@ -73,6 +82,5 @@ namespace SoftwareInstallationFileImplement.Implements } return null; } - } } diff --git a/SoftwareInstallationFileImplement/Implements/OrderStorage.cs b/SoftwareInstallationFileImplement/Implements/OrderStorage.cs index d83efa0..f9b5f61 100644 --- a/SoftwareInstallationFileImplement/Implements/OrderStorage.cs +++ b/SoftwareInstallationFileImplement/Implements/OrderStorage.cs @@ -3,11 +3,6 @@ using SoftwareInstallationContracts.SearchModels; using SoftwareInstallationContracts.StoragesContracts; using SoftwareInstallationContracts.ViewModels; using SoftwareInstallationFileImplement.Models; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace SoftwareInstallationFileImplement.Implements { @@ -20,14 +15,7 @@ namespace SoftwareInstallationFileImplement.Implements source = DataFileSingleton.GetInstance(); } - public OrderViewModel? GetElement(OrderSearchModel model) - { - if (!model.Id.HasValue) - { - return null; - } - return GetViewModel(source.Orders.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)); - } + public List GetFullList() => source.Orders.Select(x => AttachPackageName(x.GetViewModel)).ToList(); public List GetFilteredList(OrderSearchModel model) { @@ -35,12 +23,16 @@ namespace SoftwareInstallationFileImplement.Implements { return new(); } - return source.Orders.Where(x => x.Id == model.Id).Select(x => GetViewModel(x)).ToList(); + return source.Orders.Where(x => x.Id == model.Id).Select(x => AttachPackageName(x.GetViewModel)).ToList(); } - public List GetFullList() + public OrderViewModel? GetElement(OrderSearchModel model) { - return source.Orders.Select(x => GetViewModel(x)).ToList(); + if (!model.Id.HasValue) + { + return new(); + } + return AttachPackageName(source.Orders.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel); } public OrderViewModel? Insert(OrderBindingModel model) @@ -53,7 +45,7 @@ namespace SoftwareInstallationFileImplement.Implements } source.Orders.Add(newOrder); source.SaveOrders(); - return GetViewModel(newOrder); + return AttachPackageName(newOrder.GetViewModel); } public OrderViewModel? Update(OrderBindingModel model) @@ -65,32 +57,34 @@ namespace SoftwareInstallationFileImplement.Implements } order.Update(model); source.SaveOrders(); - return GetViewModel(order); + return AttachPackageName(order.GetViewModel); } + public OrderViewModel? Delete(OrderBindingModel model) { var order = source.Orders.FirstOrDefault(x => x.Id == model.Id); - if (order == null) + if (order != null) + { + source.Orders.Remove(order); + source.SaveOrders(); + return AttachPackageName(order.GetViewModel); + } + return null; + } + + private OrderViewModel? AttachPackageName(OrderViewModel? model) + { + if (model == null) { return null; } - order.Update(model); - source.SaveOrders(); - return GetViewModel(order); - } - - private OrderViewModel GetViewModel(Order order) - { - var viewModel = order.GetViewModel; - foreach (var comp in source.Packages) + var pizza = source.Packages.FirstOrDefault(x => x.Id == model.PackageId); + if (pizza != null) { - if (comp.Id == order.PackageId) - { - viewModel.PackageName = comp.PackageName; - break; - } + model.PackageName = pizza.PackageName; } - return viewModel; + return model; } } -} + +} \ No newline at end of file diff --git a/SoftwareInstallationFileImplement/Implements/TravelStorage.cs b/SoftwareInstallationFileImplement/Implements/PackageStorage.cs similarity index 66% rename from SoftwareInstallationFileImplement/Implements/TravelStorage.cs rename to SoftwareInstallationFileImplement/Implements/PackageStorage.cs index 67cc3f1..3e15276 100644 --- a/SoftwareInstallationFileImplement/Implements/TravelStorage.cs +++ b/SoftwareInstallationFileImplement/Implements/PackageStorage.cs @@ -3,11 +3,6 @@ using SoftwareInstallationContracts.SearchModels; using SoftwareInstallationContracts.StoragesContracts; using SoftwareInstallationContracts.ViewModels; using SoftwareInstallationFileImplement.Models; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace SoftwareInstallationFileImplement.Implements { @@ -20,13 +15,9 @@ namespace SoftwareInstallationFileImplement.Implements source = DataFileSingleton.GetInstance(); } - public PackageViewModel? GetElement(PackageSearchModel model) + public List GetFullList() { - if (string.IsNullOrEmpty(model.PackageName) && !model.Id.HasValue) - { - return null; - } - return source.Packages.FirstOrDefault(x => (!string.IsNullOrEmpty(model.PackageName) && x.PackageName == model.PackageName) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; + return source.Packages.Select(x => x.GetViewModel).ToList(); } public List GetFilteredList(PackageSearchModel model) @@ -38,45 +29,53 @@ namespace SoftwareInstallationFileImplement.Implements return source.Packages.Where(x => x.PackageName.Contains(model.PackageName)).Select(x => x.GetViewModel).ToList(); } - public List GetFullList() + public PackageViewModel? GetElement(PackageSearchModel model) { - return source.Packages.Select(x => x.GetViewModel).ToList(); + if (string.IsNullOrEmpty(model.PackageName) && !model.Id.HasValue) + { + return null; + } + return source.Packages.FirstOrDefault(x => + (!string.IsNullOrEmpty(model.PackageName) && x.PackageName == model.PackageName) || + (model.Id.HasValue && x.Id == model.Id)) + ?.GetViewModel; } public PackageViewModel? Insert(PackageBindingModel model) { model.Id = source.Packages.Count > 0 ? source.Packages.Max(x => x.Id) + 1 : 1; - var newDoc = Package.Create(model); - if (newDoc == null) + var newPackage = Package.Create(model); + if (newPackage == null) { return null; } - source.Packages.Add(newDoc); + source.Packages.Add(newPackage); source.SavePackages(); - return newDoc.GetViewModel; + return newPackage.GetViewModel; } public PackageViewModel? Update(PackageBindingModel model) { - var document = source.Packages.FirstOrDefault(x => x.Id == model.Id); - if (document == null) + var Package = source.Packages.FirstOrDefault(x => x.Id == model.Id); + if (Package == null) { return null; } - document.Update(model); + Package.Update(model); source.SavePackages(); - return document.GetViewModel; + return Package.GetViewModel; } + public PackageViewModel? Delete(PackageBindingModel model) { - var document = source.Packages.FirstOrDefault(x => x.Id == model.Id); - if (document == null) + var Package = source.Packages.FirstOrDefault(x => x.Id == model.Id); + if (Package != null) { - return null; + source.Packages.Remove(Package); + source.SavePackages(); + return Package.GetViewModel; } - document.Update(model); - source.SavePackages(); - return document.GetViewModel; + return null; } } -} +} \ No newline at end of file diff --git a/SoftwareInstallationFileImplement/Implements/ShopStorage.cs b/SoftwareInstallationFileImplement/Implements/ShopStorage.cs new file mode 100644 index 0000000..99dc7e1 --- /dev/null +++ b/SoftwareInstallationFileImplement/Implements/ShopStorage.cs @@ -0,0 +1,154 @@ +using SoftwareInstallationContracts.BindingModels; +using SoftwareInstallationContracts.SearchModels; +using SoftwareInstallationContracts.StoragesContracts; +using SoftwareInstallationContracts.ViewModels; +using SoftwareInstallationFileImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SoftwareInstallationFileImplement.Implements +{ + public class ShopStorage : IShopStorage + { + private readonly DataFileSingleton source; + + public ShopStorage() + { + source = DataFileSingleton.GetInstance(); + } + + public List GetFullList() + { + return source.Shops.Select(x => x.GetViewModel).ToList(); + } + + public List GetFilteredList(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.ShopName)) + { + return new(); + } + return source.Shops.Where(x => x.ShopName.Contains(model.ShopName)).Select(x => x.GetViewModel).ToList(); + } + + public ShopViewModel? GetElement(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.ShopName) && !model.Id.HasValue) + { + return null; + } + return source.Shops.FirstOrDefault(x => + (!string.IsNullOrEmpty(model.ShopName) && x.ShopName == model.ShopName) || + (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; + } + + public ShopViewModel? Insert(ShopBindingModel model) + { + model.Id = source.Shops.Count > 0 ? source.Shops.Max(x => x.Id) + 1 : 1; + var newShop = Shop.Create(model); + if (newShop == null) + { + return null; + } + source.Shops.Add(newShop); + source.SaveShops(); + return newShop.GetViewModel; + } + + public ShopViewModel? Update(ShopBindingModel model) + { + var shop = source.Shops.FirstOrDefault(x => x.Id == model.Id); + if (shop == null) + { + return null; + } + shop.Update(model); + source.SaveShops(); + return shop.GetViewModel; + } + + public ShopViewModel? Delete(ShopBindingModel model) + { + var shop = source.Shops.FirstOrDefault(x => x.Id == model.Id); + if (shop != null) + { + source.Shops.Remove(shop); + source.SaveShops(); + return shop.GetViewModel; + } + return null; + } + + public bool Sale(SupplySearchModel model) + { + if (model == null || !model.PackageId.HasValue || !model.Count.HasValue) + return false; + int remainingSpace = source.Shops.Select(x => x.Packages.ContainsKey(model.PackageId.Value) ? x.Packages[model.PackageId.Value] : 0).Sum(); + if (remainingSpace < model.Count) + { + return false; + } + var shops = source.Shops.Where(x => x.Packages.ContainsKey(model.PackageId.Value)).OrderByDescending(x => x.Packages[model.PackageId.Value]).ToList(); + foreach (var shop in shops) + { + int residue = model.Count.Value - shop.Packages[model.PackageId.Value]; + if (residue > 0) + { + shop.Packages.Remove(model.PackageId.Value); + shop.PackagesUpdate(); + model.Count = residue; + } + else + { + if (residue == 0) + { + shop.Packages.Remove(model.PackageId.Value); + } + else + { + shop.Packages[model.PackageId.Value] = -residue; + } + shop.PackagesUpdate(); + source.SaveShops(); + return true; + } + } + source.SaveShops(); + return false; + } + + public bool RestockingShops(SupplyBindingModel model) + { + if (model == null || source.Shops.Select(x => x.PackageMaxCount - x.ShopPackages.Select(y => y.Value.Item2).Sum()).Sum() < model.Count) + { + return false; + } + foreach (Shop shop in source.Shops) + { + int free_places = shop.PackageMaxCount - shop.ShopPackages.Select(x => x.Value.Item2).Sum(); + if (free_places <= 0) + continue; + free_places = Math.Min(free_places, model.Count); + model.Count -= free_places; + if (shop.Packages.ContainsKey(model.PackageId)) + { + shop.Packages[model.PackageId] += free_places; + } + else + { + shop.Packages.Add(model.PackageId, free_places); + } + shop.PackagesUpdate(); + if (model.Count == 0) + { + source.SaveShops(); + return true; + } + } + return false; + } + } +} \ No newline at end of file diff --git a/SoftwareInstallationFileImplement/Models/Component.cs b/SoftwareInstallationFileImplement/Models/Component.cs index fe76abf..9560948 100644 --- a/SoftwareInstallationFileImplement/Models/Component.cs +++ b/SoftwareInstallationFileImplement/Models/Component.cs @@ -1,11 +1,6 @@ using SoftwareInstallationContracts.BindingModels; using SoftwareInstallationContracts.ViewModels; using SoftwareInstallationDataModels.Models; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using System.Xml.Linq; namespace SoftwareInstallationFileImplement.Models @@ -15,6 +10,7 @@ namespace SoftwareInstallationFileImplement.Models public int Id { get; private set; } public string ComponentName { get; private set; } = string.Empty; public double Cost { get; set; } + public static Component? Create(ComponentBindingModel model) { if (model == null) @@ -28,6 +24,7 @@ namespace SoftwareInstallationFileImplement.Models Cost = model.Cost }; } + public static Component? Create(XElement element) { if (element == null) @@ -41,6 +38,7 @@ namespace SoftwareInstallationFileImplement.Models Cost = Convert.ToDouble(element.Element("Cost")!.Value) }; } + public void Update(ComponentBindingModel model) { if (model == null) @@ -50,15 +48,17 @@ namespace SoftwareInstallationFileImplement.Models ComponentName = model.ComponentName; Cost = model.Cost; } + public ComponentViewModel GetViewModel => new() { Id = Id, ComponentName = ComponentName, Cost = Cost }; + public XElement GetXElement => new("Component", - new XAttribute("Id", Id), - new XElement("ComponentName", ComponentName), - new XElement("Cost", Cost.ToString())); + new XAttribute("Id", Id), + new XElement("ComponentName", ComponentName), + new XElement("Cost", Cost.ToString())); } -} +} \ No newline at end of file diff --git a/SoftwareInstallationFileImplement/Models/Order.cs b/SoftwareInstallationFileImplement/Models/Order.cs index 20132c7..2b24652 100644 --- a/SoftwareInstallationFileImplement/Models/Order.cs +++ b/SoftwareInstallationFileImplement/Models/Order.cs @@ -1,31 +1,20 @@ -using SoftwareInstallationContracts.BindingModels; -using SoftwareInstallationContracts.ViewModels; -using SoftwareInstallationDataModels.Enums; +using SoftwareInstallationDataModels.Enums; using SoftwareInstallationDataModels.Models; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using SoftwareInstallationContracts.BindingModels; +using SoftwareInstallationContracts.ViewModels; using System.Xml.Linq; namespace SoftwareInstallationFileImplement.Models { public class Order : IOrderModel { - public int PackageId { get; private set; } - - public int Count { get; private set; } - - public double Sum { get; private set; } - - public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен; - - public DateTime DateCreate { get; private set; } = DateTime.Now; - - public DateTime? DateImplement { get; private set; } - public int Id { get; private set; } + public int PackageId { get; private set; } + public int Count { get; private set; } + public double Sum { get; private set; } + public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен; + public DateTime DateCreate { get; private set; } = DateTime.Now; + public DateTime? DateImplement { get; private set; } public static Order? Create(OrderBindingModel? model) { @@ -41,7 +30,7 @@ namespace SoftwareInstallationFileImplement.Models Sum = model.Sum, Status = model.Status, DateCreate = model.DateCreate, - DateImplement = model.DateImplement + DateImplement = model.DateImplement, }; } @@ -51,24 +40,18 @@ namespace SoftwareInstallationFileImplement.Models { return null; } - var order = new Order() + string dateImplement = element.Element("DateImplement")!.Value; + return new Order() { Id = Convert.ToInt32(element.Attribute("Id")!.Value), PackageId = Convert.ToInt32(element.Element("PackageId")!.Value), Count = Convert.ToInt32(element.Element("Count")!.Value), Sum = Convert.ToDouble(element.Element("Sum")!.Value), - DateCreate = DateTime.ParseExact(element.Element("DateCreate")!.Value, "G", null), + Status = (OrderStatus)(Enum.Parse(typeof(OrderStatus), element.Element("Status")!.Value)), + DateCreate = Convert.ToDateTime(element.Element("DateCreate")!.Value), + DateImplement = (dateImplement == "" || dateImplement is null) ? Convert.ToDateTime(null) : Convert.ToDateTime(dateImplement) }; - DateTime.TryParse(element.Element("DateImplement")!.Value, out DateTime dateImpl); - order.DateImplement = dateImpl; - - if (!Enum.TryParse(element.Element("Status")!.Value, out OrderStatus status)) - { - return null; - } - order.Status = status; - return order; } public void Update(OrderBindingModel? model) @@ -78,7 +61,7 @@ namespace SoftwareInstallationFileImplement.Models return; } Status = model.Status; - DateImplement = model.DateImplement; + if (model.Status == OrderStatus.Выдан) DateImplement = model.DateImplement; } public OrderViewModel GetViewModel => new() @@ -89,16 +72,16 @@ namespace SoftwareInstallationFileImplement.Models Sum = Sum, Status = Status, DateCreate = DateCreate, - DateImplement = DateImplement + DateImplement = DateImplement, }; public XElement GetXElement => new("Order", - new XAttribute("Id", Id), - new XElement("PackageId", PackageId), - new XElement("Count", Count.ToString()), - new XElement("Sum", Sum.ToString()), - new XElement("Status", Status.ToString()), - new XElement("DateCreate", DateCreate.ToString()), - new XElement("DateImplement", DateImplement.ToString())); + new XAttribute("Id", Id), + new XElement("PackageId", PackageId.ToString()), + new XElement("Count", Count.ToString()), + new XElement("Sum", Sum.ToString()), + new XElement("Status", Status.ToString()), + new XElement("DateCreate", DateCreate.ToString()), + new XElement("DateImplement", DateImplement.ToString())); } -} +} \ No newline at end of file diff --git a/SoftwareInstallationFileImplement/Models/Package.cs b/SoftwareInstallationFileImplement/Models/Package.cs index 7d04cd7..aeb2aa2 100644 --- a/SoftwareInstallationFileImplement/Models/Package.cs +++ b/SoftwareInstallationFileImplement/Models/Package.cs @@ -1,11 +1,6 @@ using SoftwareInstallationContracts.BindingModels; using SoftwareInstallationContracts.ViewModels; using SoftwareInstallationDataModels.Models; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using System.Xml.Linq; namespace SoftwareInstallationFileImplement.Models @@ -16,19 +11,17 @@ namespace SoftwareInstallationFileImplement.Models public string PackageName { get; private set; } = string.Empty; public double Price { get; private set; } public Dictionary Components { get; private set; } = new(); - private Dictionary? _PackageComponents = null; + private Dictionary? _pizzaComponents = null; public Dictionary PackageComponents { get { - if (_PackageComponents == null) + if (_pizzaComponents == null) { var source = DataFileSingleton.GetInstance(); - _PackageComponents = Components.ToDictionary(x => x.Key, y => - ((source.Components.FirstOrDefault(z => z.Id == y.Key) as IComponentModel)!, - y.Value)); + _pizzaComponents = Components.ToDictionary(x => x.Key, y => ((source.Components.FirstOrDefault(z => z.Id == y.Key) as IComponentModel)!, y.Value)); } - return _PackageComponents; + return _pizzaComponents; } } public static Package? Create(PackageBindingModel model) @@ -42,8 +35,7 @@ namespace SoftwareInstallationFileImplement.Models Id = model.Id, PackageName = model.PackageName, Price = model.Price, - Components = model.PackageComponents.ToDictionary(x => x.Key, x - => x.Value.Item2) + Components = model.PackageComponents.ToDictionary(x => x.Key, x => x.Value.Item2) }; } public static Package? Create(XElement element) @@ -57,11 +49,8 @@ namespace SoftwareInstallationFileImplement.Models Id = Convert.ToInt32(element.Attribute("Id")!.Value), PackageName = element.Element("PackageName")!.Value, Price = Convert.ToDouble(element.Element("Price")!.Value), - Components = - element.Element("PackageComponents")!.Elements("PackageComponent") - .ToDictionary(x => - Convert.ToInt32(x.Element("Key")?.Value), x => - Convert.ToInt32(x.Element("Value")?.Value)) + Components = element.Element("PackageComponents")!.Elements("PackageComponent").ToDictionary(x => Convert.ToInt32(x.Element("Key")?.Value), + x => Convert.ToInt32(x.Element("Value")?.Value)) }; } public void Update(PackageBindingModel model) @@ -72,9 +61,8 @@ namespace SoftwareInstallationFileImplement.Models } PackageName = model.PackageName; Price = model.Price; - Components = model.PackageComponents.ToDictionary(x => x.Key, x => - x.Value.Item2); - _PackageComponents = null; + Components = model.PackageComponents.ToDictionary(x => x.Key, x => x.Value.Item2); + _pizzaComponents = null; } public PackageViewModel GetViewModel => new() { @@ -84,12 +72,10 @@ namespace SoftwareInstallationFileImplement.Models PackageComponents = PackageComponents }; public XElement GetXElement => new("Package", - new XAttribute("Id", Id), - new XElement("PackageName", PackageName), - new XElement("Price", Price.ToString()), - new XElement("PackageComponents", Components.Select(x => new XElement("PackageComponent", new XElement("Key", x.Key), new XElement("Value", x.Value))) - - .ToArray())); - + new XAttribute("Id", Id), + new XElement("PackageName", PackageName), + new XElement("Price", Price.ToString()), + new XElement("PackageComponents", Components.Select( + x => new XElement("PackageComponent", new XElement("Key", x.Key), new XElement("Value", x.Value))).ToArray())); } -} +} \ No newline at end of file diff --git a/SoftwareInstallationFileImplement/Models/Shop.cs b/SoftwareInstallationFileImplement/Models/Shop.cs new file mode 100644 index 0000000..5fac795 --- /dev/null +++ b/SoftwareInstallationFileImplement/Models/Shop.cs @@ -0,0 +1,111 @@ +using SoftwareInstallationDataModels.Models; +using SoftwareInstallationContracts.BindingModels; +using SoftwareInstallationContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace SoftwareInstallationFileImplement.Models +{ + public class Shop : IShopModel + { + public int Id { get; private set; } + public string ShopName { get; private set; } = string.Empty; + public string Adress { get; private set; } = string.Empty; + public DateTime OpeningDate { get; private set; } + public Dictionary Packages { get; private set; } = new(); + private Dictionary? _shopPackages = null; + + public Dictionary ShopPackages + { + get + { + if (_shopPackages == null) + { + var source = DataFileSingleton.GetInstance(); + _shopPackages = Packages.ToDictionary(x => x.Key, y => ((source.Packages.FirstOrDefault(z => z.Id == y.Key) as IPackageModel)!, y.Value)); + } + return _shopPackages; + } + } + + public int PackageMaxCount { get; private set; } + + public static Shop? Create(ShopBindingModel? model) + { + if (model == null) + { + return null; + } + return new Shop() + { + Id = model.Id, + ShopName = model.ShopName, + Adress = model.Adress, + OpeningDate = model.OpeningDate, + Packages = model.ShopPackages.ToDictionary(x => x.Key, x => x.Value.Item2), + PackageMaxCount = model.PackageMaxCount + }; + } + + public static Shop? Create(XElement element) + { + if (element == null) + { + return null; + } + return new() + { + Id = Convert.ToInt32(element.Attribute("Id")!.Value), + ShopName = element.Element("ShopName")!.Value, + Adress = element.Element("Adress")!.Value, + OpeningDate = Convert.ToDateTime(element.Element("OpeningDate")!.Value), + Packages = element.Element("ShopPackages")!.Elements("ShopPackage")!.ToDictionary(x => Convert.ToInt32(x.Element("Key")?.Value), + x => Convert.ToInt32(x.Element("Value")?.Value)), + PackageMaxCount = Convert.ToInt32(element.Element("PackageMaxCount")!.Value) + }; + } + + public void Update(ShopBindingModel? model) + { + if (model == null) + { + return; + } + ShopName = model.ShopName; + Adress = model.Adress; + OpeningDate = model.OpeningDate; + PackageMaxCount = model.PackageMaxCount; + Packages = model.ShopPackages.ToDictionary(x => x.Key, x => x.Value.Item2); + _shopPackages = null; + } + + public ShopViewModel GetViewModel => new() + { + Id = Id, + ShopName = ShopName, + Adress = Adress, + OpeningDate = OpeningDate, + ShopPackages = ShopPackages, + PackageMaxCount = PackageMaxCount + }; + + public XElement GetXElement => new("Shop", + new XAttribute("Id", Id), + new XElement("ShopName", ShopName), + new XElement("Adress", Adress), + new XElement("OpeningDate", OpeningDate.ToString()), + new XElement("ShopPackages", Packages.Select( + x => new XElement("ShopPackage", new XElement("Key", x.Key), new XElement("Value", x.Value))).ToArray()), + new XElement("PackageMaxCount", PackageMaxCount.ToString()) + ); + + public void PackagesUpdate() + { + _shopPackages = null; + } + } +} \ No newline at end of file diff --git a/SoftwareInstallationListImplement/DataListSingleton.cs b/SoftwareInstallationListImplement/DataListSingleton.cs index 76fc819..341f6c4 100644 --- a/SoftwareInstallationListImplement/DataListSingleton.cs +++ b/SoftwareInstallationListImplement/DataListSingleton.cs @@ -7,18 +7,22 @@ using System.Threading.Tasks; namespace SoftwareInstallationListImplement { - internal class DataListSingleton + public class DataListSingleton { private static DataListSingleton? _instance; public List Components { get; set; } public List Orders { get; set; } public List Packages { get; set; } + public List Shops { get; set; } + private DataListSingleton() { Components = new List(); Orders = new List(); Packages = new List(); + Shops = new List(); } + public static DataListSingleton GetInstance() { if (_instance == null) diff --git a/SoftwareInstallationListImplement/Implements/ComponentStorage.cs b/SoftwareInstallationListImplement/Implements/ComponentStorage.cs index 9c26614..24725d9 100644 --- a/SoftwareInstallationListImplement/Implements/ComponentStorage.cs +++ b/SoftwareInstallationListImplement/Implements/ComponentStorage.cs @@ -1,6 +1,6 @@ -using SoftwareInstallationContracts.StoragesContracts; -using SoftwareInstallationContracts.BindingModels; +using SoftwareInstallationContracts.BindingModels; using SoftwareInstallationContracts.SearchModels; +using SoftwareInstallationContracts.StoragesContracts; using SoftwareInstallationContracts.ViewModels; using SoftwareInstallationListImplement.Models; using System; @@ -14,10 +14,12 @@ namespace SoftwareInstallationListImplement.Implements public class ComponentStorage : IComponentStorage { private readonly DataListSingleton _source; + public ComponentStorage() { _source = DataListSingleton.GetInstance(); } + public List GetFullList() { var result = new List(); @@ -27,6 +29,7 @@ namespace SoftwareInstallationListImplement.Implements } return result; } + public List GetFilteredList(ComponentSearchModel model) { var result = new List(); @@ -43,6 +46,7 @@ namespace SoftwareInstallationListImplement.Implements } return result; } + public ComponentViewModel? GetElement(ComponentSearchModel model) { if (string.IsNullOrEmpty(model.ComponentName) && !model.Id.HasValue) @@ -52,13 +56,14 @@ namespace SoftwareInstallationListImplement.Implements foreach (var component in _source.Components) { if ((!string.IsNullOrEmpty(model.ComponentName) && component.ComponentName == model.ComponentName) || - (model.Id.HasValue && component.Id == model.Id)) + (model.Id.HasValue && component.Id == model.Id)) { return component.GetViewModel; } } return null; } + public ComponentViewModel? Insert(ComponentBindingModel model) { model.Id = 1; @@ -77,6 +82,7 @@ namespace SoftwareInstallationListImplement.Implements _source.Components.Add(newComponent); return newComponent.GetViewModel; } + public ComponentViewModel? Update(ComponentBindingModel model) { foreach (var component in _source.Components) @@ -89,6 +95,7 @@ namespace SoftwareInstallationListImplement.Implements } return null; } + public ComponentViewModel? Delete(ComponentBindingModel model) { for (int i = 0; i < _source.Components.Count; ++i) diff --git a/SoftwareInstallationListImplement/Implements/OrderStorage.cs b/SoftwareInstallationListImplement/Implements/OrderStorage.cs index a3afef2..1b84352 100644 --- a/SoftwareInstallationListImplement/Implements/OrderStorage.cs +++ b/SoftwareInstallationListImplement/Implements/OrderStorage.cs @@ -111,11 +111,11 @@ namespace SoftwareInstallationListImplement.Implements private OrderViewModel AttachPackageName(OrderViewModel model) { - foreach (var Package in _source.Packages) + foreach (var pizza in _source.Packages) { - if (Package.Id == model.PackageId) + if (pizza.Id == model.PackageId) { - model.PackageName = Package.PackageName; + model.PackageName = pizza.PackageName; return model; } } diff --git a/SoftwareInstallationListImplement/Implements/PackageStorage.cs b/SoftwareInstallationListImplement/Implements/PackageStorage.cs index 97a39fb..8c2ed0e 100644 --- a/SoftwareInstallationListImplement/Implements/PackageStorage.cs +++ b/SoftwareInstallationListImplement/Implements/PackageStorage.cs @@ -11,13 +11,91 @@ using System.Threading.Tasks; namespace SoftwareInstallationListImplement.Implements { - public class PackageStorage : IPackageStorage { + public class PackageStorage : IPackageStorage + { private readonly DataListSingleton _source; + public PackageStorage() { _source = DataListSingleton.GetInstance(); } + public List GetFullList() + { + var result = new List(); + foreach (var pizzas in _source.Packages) + { + result.Add(pizzas.GetViewModel); + } + return result; + } + + public List GetFilteredList(PackageSearchModel model) + { + var result = new List(); + if (string.IsNullOrEmpty(model.PackageName)) + { + return result; + } + foreach (var pizzas in _source.Packages) + { + if (pizzas.PackageName.Contains(model.PackageName)) + { + result.Add(pizzas.GetViewModel); + } + } + return result; + } + + public PackageViewModel? GetElement(PackageSearchModel model) + { + if (string.IsNullOrEmpty(model.PackageName) && !model.Id.HasValue) + { + return null; + } + foreach (var pizzas in _source.Packages) + { + if ((!string.IsNullOrEmpty(model.PackageName) && pizzas.PackageName == model.PackageName) || + (model.Id.HasValue && pizzas.Id == model.Id)) + { + return pizzas.GetViewModel; + } + } + return null; + } + + public PackageViewModel? Insert(PackageBindingModel model) + { + model.Id = 1; + foreach (var pizzas in _source.Packages) + { + if (model.Id <= pizzas.Id) + { + model.Id = pizzas.Id + 1; + } + } + var newPackages = Package.Create(model); + if (newPackages == null) + { + return null; + } + _source.Packages.Add(newPackages); + return newPackages.GetViewModel; + } + + public PackageViewModel? Update(PackageBindingModel model) + { + foreach (var pizzas in _source.Packages) + { + if (pizzas.Id == model.Id) + { + pizzas.Update(model); + return pizzas.GetViewModel; + } + } + return null; + } + public PackageViewModel? Delete(PackageBindingModel model) { for (int i = 0; i < _source.Packages.Count; ++i) @@ -31,81 +109,5 @@ namespace SoftwareInstallationListImplement.Implements } return null; } - - public PackageViewModel? GetElement(PackageSearchModel model) - { - if (string.IsNullOrEmpty(model.PackageName) && !model.Id.HasValue) - { - return null; - } - foreach (var Package in _source.Packages) - { - if ((!string.IsNullOrEmpty(model.PackageName) && Package.PackageName == model.PackageName) || - (model.Id.HasValue && Package.Id == model.Id)) - { - return Package.GetViewModel; - } - } - return null; - } - - public List GetFilteredList(PackageSearchModel model) - { - var result = new List(); - if (string.IsNullOrEmpty(model.PackageName)) - { - return result; - } - foreach (var Package in _source.Packages) - { - if (Package.PackageName.Contains(model.PackageName)) - { - result.Add(Package.GetViewModel); - } - } - return result; - } - - public List GetFullList() - { - var result = new List(); - foreach (var Package in _source.Packages) - { - result.Add(Package.GetViewModel); - } - return result; - } - - public PackageViewModel? Insert(PackageBindingModel model) - { - model.Id = 1; - foreach (var Package in _source.Packages) - { - if (model.Id <= Package.Id) - { - model.Id = Package.Id + 1; - } - } - var newPackage = Package.Create(model); - if (newPackage == null) - { - return null; - } - _source.Packages.Add(newPackage); - return newPackage.GetViewModel; - } - - public PackageViewModel? Update(PackageBindingModel model) - { - foreach (var Package in _source.Packages) - { - if (Package.Id == model.Id) - { - Package.Update(model); - return Package.GetViewModel; - } - } - return null; - } } } diff --git a/SoftwareInstallationListImplement/Implements/ShopStorage.cs b/SoftwareInstallationListImplement/Implements/ShopStorage.cs new file mode 100644 index 0000000..0586953 --- /dev/null +++ b/SoftwareInstallationListImplement/Implements/ShopStorage.cs @@ -0,0 +1,123 @@ +using SoftwareInstallationContracts.BindingModels; +using SoftwareInstallationContracts.SearchModels; +using SoftwareInstallationContracts.StoragesContracts; +using SoftwareInstallationContracts.ViewModels; +using SoftwareInstallationListImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SoftwareInstallationListImplement.Implements +{ + public class ShopStorage : IShopStorage + { + private readonly DataListSingleton _source; + + public ShopStorage() + { + _source = DataListSingleton.GetInstance(); + } + + public List GetFullList() + { + var result = new List(); + foreach (var shop in _source.Shops) + { + result.Add(shop.GetViewModel); + } + return result; + } + + public List GetFilteredList(ShopSearchModel model) + { + var result = new List(); + if (string.IsNullOrEmpty(model.ShopName)) + { + return result; + } + foreach (var shop in _source.Shops) + { + if (shop.ShopName.Contains(model.ShopName)) + { + result.Add(shop.GetViewModel); + } + } + return result; + } + + public ShopViewModel? GetElement(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.ShopName) && !model.Id.HasValue) + { + return null; + } + foreach (var shop in _source.Shops) + { + if ((!string.IsNullOrEmpty(model.ShopName) && shop.ShopName == model.ShopName) || + (model.Id.HasValue && shop.Id == model.Id)) + { + return shop.GetViewModel; + } + } + return null; + } + + public ShopViewModel? Insert(ShopBindingModel model) + { + model.Id = 1; + foreach (var shop in _source.Shops) + { + if (model.Id <= shop.Id) + { + model.Id = shop.Id + 1; + } + } + var newShop = Shop.Create(model); + if (newShop == null) + { + return null; + } + _source.Shops.Add(newShop); + return newShop.GetViewModel; + } + + public ShopViewModel? Update(ShopBindingModel model) + { + foreach (var shop in _source.Shops) + { + if (shop.Id == model.Id) + { + shop.Update(model); + return shop.GetViewModel; + } + } + return null; + } + + public ShopViewModel? Delete(ShopBindingModel model) + { + for (int i = 0; i < _source.Shops.Count; ++i) + { + if (_source.Shops[i].Id == model.Id) + { + var element = _source.Shops[i]; + _source.Shops.RemoveAt(i); + return element.GetViewModel; + } + } + return null; + } + + public bool Sale(SupplySearchModel model) + { + throw new NotImplementedException(); + } + + public bool RestockingShops(SupplyBindingModel model) + { + throw new NotImplementedException(); + } + } +} diff --git a/SoftwareInstallationListImplement/Models/Component.cs b/SoftwareInstallationListImplement/Models/Component.cs index 4a114fb..90247de 100644 --- a/SoftwareInstallationListImplement/Models/Component.cs +++ b/SoftwareInstallationListImplement/Models/Component.cs @@ -1,6 +1,11 @@ using SoftwareInstallationContracts.BindingModels; using SoftwareInstallationContracts.ViewModels; using SoftwareInstallationDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; namespace SoftwareInstallationListImplement.Models { @@ -8,7 +13,8 @@ namespace SoftwareInstallationListImplement.Models { public int Id { get; private set; } public string ComponentName { get; private set; } = string.Empty; - public double Cost { get; set; } + public double Cost { get; private set; } + public static Component? Create(ComponentBindingModel? model) { if (model == null) @@ -38,4 +44,4 @@ namespace SoftwareInstallationListImplement.Models Cost = Cost }; } -} \ No newline at end of file +} diff --git a/SoftwareInstallationListImplement/Models/Order.cs b/SoftwareInstallationListImplement/Models/Order.cs index fe7cccd..95f298a 100644 --- a/SoftwareInstallationListImplement/Models/Order.cs +++ b/SoftwareInstallationListImplement/Models/Order.cs @@ -5,7 +5,6 @@ using SoftwareInstallationDataModels.Models; using System; using System.Collections.Generic; using System.Linq; -using System.Reflection; using System.Text; using System.Threading.Tasks; @@ -17,9 +16,10 @@ namespace SoftwareInstallationListImplement.Models public int PackageId { get; private set; } public int Count { get; private set; } public double Sum { get; private set; } - public OrderStatus Status { get; private set; } - public DateTime DateCreate { get; private set; } + public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен; + public DateTime DateCreate { get; private set; } = DateTime.Now; public DateTime? DateImplement { get; private set; } + public static Order? Create(OrderBindingModel? model) { if (model == null) @@ -37,19 +37,17 @@ namespace SoftwareInstallationListImplement.Models DateImplement = model.DateImplement, }; } + public void Update(OrderBindingModel? model) { if (model == null) { return; } - PackageId = model.PackageId; - Count = model.Count; - Sum = model.Sum; Status = model.Status; - DateCreate = model.DateCreate; - DateImplement = model.DateImplement; + if (model.Status == OrderStatus.Выдан) DateImplement = model.DateImplement; } + public OrderViewModel GetViewModel => new() { Id = Id, diff --git a/SoftwareInstallationListImplement/Models/Package.cs b/SoftwareInstallationListImplement/Models/Package.cs index 3d51572..9e55215 100644 --- a/SoftwareInstallationListImplement/Models/Package.cs +++ b/SoftwareInstallationListImplement/Models/Package.cs @@ -9,16 +9,13 @@ using System.Threading.Tasks; namespace SoftwareInstallationListImplement.Models { - internal class Package : IPackageModel + public class Package : IPackageModel { public int Id { get; private set; } public string PackageName { get; private set; } = string.Empty; public double Price { get; private set; } - public Dictionary PackageComponents - { - get; - private set; - } = new Dictionary(); + public Dictionary PackageComponents { get; private set; } = new Dictionary(); + public static Package? Create(PackageBindingModel? model) { if (model == null) @@ -30,9 +27,10 @@ namespace SoftwareInstallationListImplement.Models Id = model.Id, PackageName = model.PackageName, Price = model.Price, - PackageComponents = model.PackageComponents + PackageComponents = model.PackageComponents, }; } + public void Update(PackageBindingModel? model) { if (model == null) @@ -43,6 +41,7 @@ namespace SoftwareInstallationListImplement.Models Price = model.Price; PackageComponents = model.PackageComponents; } + public PackageViewModel GetViewModel => new() { Id = Id, @@ -50,6 +49,5 @@ namespace SoftwareInstallationListImplement.Models Price = Price, PackageComponents = PackageComponents }; - } } diff --git a/SoftwareInstallationListImplement/Models/Shop.cs b/SoftwareInstallationListImplement/Models/Shop.cs new file mode 100644 index 0000000..cef4da1 --- /dev/null +++ b/SoftwareInstallationListImplement/Models/Shop.cs @@ -0,0 +1,59 @@ +using SoftwareInstallationDataModels.Models; +using SoftwareInstallationContracts.BindingModels; +using SoftwareInstallationContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SoftwareInstallationListImplement.Models +{ + public class Shop : IShopModel + { + public int Id { get; private set; } + public string ShopName { get; private set; } = string.Empty; + public string Adress { get; private set; } = string.Empty; + public DateTime OpeningDate { get; private set; } + public Dictionary ShopPackages { get; private set; } = new(); + public int PackageMaxCount { get; private set; } + + public static Shop? Create(ShopBindingModel? model) + { + if (model == null) + { + return null; + } + return new Shop() + { + Id = model.Id, + ShopName = model.ShopName, + Adress = model.Adress, + OpeningDate = model.OpeningDate, + PackageMaxCount = model.PackageMaxCount, + }; + } + + public void Update(ShopBindingModel? model) + { + if (model == null) + { + return; + } + ShopName = model.ShopName; + Adress = model.Adress; + OpeningDate = model.OpeningDate; + PackageMaxCount = model.PackageMaxCount; + } + + public ShopViewModel GetViewModel => new() + { + Id = Id, + ShopName = ShopName, + Adress = Adress, + OpeningDate = OpeningDate, + ShopPackages = ShopPackages, + PackageMaxCount = PackageMaxCount, + }; + } +}