From 35acc1dee9581fca57ad983f5b1fd7d970601b81 Mon Sep 17 00:00:00 2001 From: Yunusov_Niyaz Date: Thu, 14 Mar 2024 19:28:27 +0400 Subject: [PATCH 1/5] =?UTF-8?q?=D0=92=D1=81=D1=91=20=D1=81=D0=B4=D0=B5?= =?UTF-8?q?=D0=BB=D0=B0=D0=BD=D0=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../CarRepairShop/FormMain.Designer.cs | 33 ++- CarRepairShop/CarRepairShop/FormMain.cs | 24 ++ .../CarRepairShop/FormSell.Designer.cs | 126 ++++++++++ CarRepairShop/CarRepairShop/FormSell.cs | 108 +++++++++ CarRepairShop/CarRepairShop/FormSell.resx | 120 +++++++++ .../CarRepairShop/FormShop.Designer.cs | 228 ++++++++++++++++++ CarRepairShop/CarRepairShop/FormShop.cs | 115 +++++++++ CarRepairShop/CarRepairShop/FormShop.resx | 120 +++++++++ .../CarRepairShop/FormShops.Designer.cs | 126 ++++++++++ CarRepairShop/CarRepairShop/FormShops.cs | 118 +++++++++ CarRepairShop/CarRepairShop/FormShops.resx | 120 +++++++++ .../CarRepairShop/FormSupply.Designer.cs | 150 ++++++++++++ CarRepairShop/CarRepairShop/FormSupply.cs | 142 +++++++++++ CarRepairShop/CarRepairShop/FormSupply.resx | 120 +++++++++ CarRepairShop/CarRepairShop/Program.cs | 6 + .../CarRepairShopBusinessLogic/OrderLogic.cs | 84 ++++++- .../CarRepairShopBusinessLogic/ShopLogic.cs | 166 +++++++++++++ .../BindingModels/ShopBindingModel.cs | 15 ++ .../BusinessLogicsContracts/IShopLogic.cs | 18 ++ .../SearchModels/ShopSearchModel.cs | 14 ++ .../StoragesContracts/IShopStorage.cs | 18 ++ .../ViewModels/ShopViewModel.cs | 20 ++ .../CarRepairShopDataModels/IShopModel.cs | 13 + .../DataFileSingleton.cs | 6 + .../Implements/ShopStorage.cs | 119 +++++++++ .../CarRepairShopFileImplement/Models/Shop.cs | 97 ++++++++ .../DataListSingleton.cs | 2 + .../Implements/ShopStorage.cs | 108 +++++++++ .../CarRepairShopListImplement/Models/Shop.cs | 52 ++++ 29 files changed, 2383 insertions(+), 5 deletions(-) create mode 100644 CarRepairShop/CarRepairShop/FormSell.Designer.cs create mode 100644 CarRepairShop/CarRepairShop/FormSell.cs create mode 100644 CarRepairShop/CarRepairShop/FormSell.resx create mode 100644 CarRepairShop/CarRepairShop/FormShop.Designer.cs create mode 100644 CarRepairShop/CarRepairShop/FormShop.cs create mode 100644 CarRepairShop/CarRepairShop/FormShop.resx create mode 100644 CarRepairShop/CarRepairShop/FormShops.Designer.cs create mode 100644 CarRepairShop/CarRepairShop/FormShops.cs create mode 100644 CarRepairShop/CarRepairShop/FormShops.resx create mode 100644 CarRepairShop/CarRepairShop/FormSupply.Designer.cs create mode 100644 CarRepairShop/CarRepairShop/FormSupply.cs create mode 100644 CarRepairShop/CarRepairShop/FormSupply.resx create mode 100644 CarRepairShop/CarRepairShopBusinessLogic/ShopLogic.cs create mode 100644 CarRepairShop/CarRepairShopContracts/BindingModels/ShopBindingModel.cs create mode 100644 CarRepairShop/CarRepairShopContracts/BusinessLogicsContracts/IShopLogic.cs create mode 100644 CarRepairShop/CarRepairShopContracts/SearchModels/ShopSearchModel.cs create mode 100644 CarRepairShop/CarRepairShopContracts/StoragesContracts/IShopStorage.cs create mode 100644 CarRepairShop/CarRepairShopContracts/ViewModels/ShopViewModel.cs create mode 100644 CarRepairShop/CarRepairShopDataModels/IShopModel.cs create mode 100644 CarRepairShop/CarRepairShopFileImplement/Implements/ShopStorage.cs create mode 100644 CarRepairShop/CarRepairShopFileImplement/Models/Shop.cs create mode 100644 CarRepairShop/CarRepairShopListImplement/Implements/ShopStorage.cs create mode 100644 CarRepairShop/CarRepairShopListImplement/Models/Shop.cs diff --git a/CarRepairShop/CarRepairShop/FormMain.Designer.cs b/CarRepairShop/CarRepairShop/FormMain.Designer.cs index eb2ee1b..9526fc9 100644 --- a/CarRepairShop/CarRepairShop/FormMain.Designer.cs +++ b/CarRepairShop/CarRepairShop/FormMain.Designer.cs @@ -32,6 +32,9 @@ справочникиToolStripMenuItem = new ToolStripMenuItem(); компонентыToolStripMenuItem = new ToolStripMenuItem(); ремонтToolStripMenuItem = new ToolStripMenuItem(); + ShopsToolStripMenuItem = new ToolStripMenuItem(); + SupplyToolStripMenuItem = new ToolStripMenuItem(); + SellsToolStripMenuItem = new ToolStripMenuItem(); dataGridView = new DataGridView(); buttonCreateOrder = new Button(); buttonTakeOrderInWork = new Button(); @@ -54,7 +57,7 @@ // // справочникиToolStripMenuItem // - справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, ремонтToolStripMenuItem }); + справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, ремонтToolStripMenuItem, ShopsToolStripMenuItem, SupplyToolStripMenuItem, SellsToolStripMenuItem }); справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; справочникиToolStripMenuItem.Size = new Size(117, 24); справочникиToolStripMenuItem.Text = "Справочники"; @@ -62,17 +65,38 @@ // компонентыToolStripMenuItem // компонентыToolStripMenuItem.Name = "компонентыToolStripMenuItem"; - компонентыToolStripMenuItem.Size = new Size(182, 26); + компонентыToolStripMenuItem.Size = new Size(224, 26); компонентыToolStripMenuItem.Text = "Компоненты"; компонентыToolStripMenuItem.Click += ComponentsToolStripMenuItem_Click; // // ремонтToolStripMenuItem // ремонтToolStripMenuItem.Name = "ремонтToolStripMenuItem"; - ремонтToolStripMenuItem.Size = new Size(182, 26); + ремонтToolStripMenuItem.Size = new Size(224, 26); ремонтToolStripMenuItem.Text = "Ремонт"; ремонтToolStripMenuItem.Click += RepairToolStripMenuItem_Click; // + // ShopsToolStripMenuItem + // + ShopsToolStripMenuItem.Name = "ShopsToolStripMenuItem"; + ShopsToolStripMenuItem.Size = new Size(224, 26); + ShopsToolStripMenuItem.Text = "Магазины"; + ShopsToolStripMenuItem.Click += ShopsToolStripMenuItem_Click; + // + // SupplyToolStripMenuItem + // + SupplyToolStripMenuItem.Name = "SupplyToolStripMenuItem"; + SupplyToolStripMenuItem.Size = new Size(224, 26); + SupplyToolStripMenuItem.Text = "Поставки"; + SupplyToolStripMenuItem.Click += SupplyToolStripMenuItem_Click; + // + // SellsToolStripMenuItem + // + SellsToolStripMenuItem.Name = "SellsToolStripMenuItem"; + SellsToolStripMenuItem.Size = new Size(224, 26); + SellsToolStripMenuItem.Text = "Продажи"; + SellsToolStripMenuItem.Click += SellToolStripMenuItem_Click; + // // dataGridView // dataGridView.AllowUserToAddRows = false; @@ -171,5 +195,8 @@ private Button buttonOrderReady; private Button buttonIssuedOrder; private Button buttonRefresh; + private ToolStripMenuItem ShopsToolStripMenuItem; + private ToolStripMenuItem SupplyToolStripMenuItem; + private ToolStripMenuItem SellsToolStripMenuItem; } } \ No newline at end of file diff --git a/CarRepairShop/CarRepairShop/FormMain.cs b/CarRepairShop/CarRepairShop/FormMain.cs index 893ec0f..b5173c9 100644 --- a/CarRepairShop/CarRepairShop/FormMain.cs +++ b/CarRepairShop/CarRepairShop/FormMain.cs @@ -156,5 +156,29 @@ namespace CarRepairShop { LoadData(); } + private void SellToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormSell)); + if (service is FormSell form) + { + form.ShowDialog(); + } + } + private void ShopsToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormShops)); + if (service is FormShops form) + { + form.ShowDialog(); + } + } + private void SupplyToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormSupply)); + if (service is FormSupply form) + { + form.ShowDialog(); + } + } } } diff --git a/CarRepairShop/CarRepairShop/FormSell.Designer.cs b/CarRepairShop/CarRepairShop/FormSell.Designer.cs new file mode 100644 index 0000000..9258cd0 --- /dev/null +++ b/CarRepairShop/CarRepairShop/FormSell.Designer.cs @@ -0,0 +1,126 @@ +namespace CarRepairShop +{ + partial class FormSell + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + RepairComboBox = new ComboBox(); + RepairLabel = new Label(); + CountLabel = new Label(); + CountTextBox = new TextBox(); + SaveButton = new Button(); + CancelButton = new Button(); + SuspendLayout(); + // + // RepairComboBox + // + RepairComboBox.DropDownStyle = ComboBoxStyle.DropDownList; + RepairComboBox.FormattingEnabled = true; + RepairComboBox.Location = new Point(139, 19); + RepairComboBox.Margin = new Padding(3, 4, 3, 4); + RepairComboBox.Name = "RepairComboBox"; + RepairComboBox.Size = new Size(138, 28); + RepairComboBox.TabIndex = 0; + // + // RepairLabel + // + RepairLabel.AutoSize = true; + RepairLabel.Location = new Point(14, 27); + RepairLabel.Name = "RepairLabel"; + RepairLabel.Size = new Size(71, 20); + RepairLabel.TabIndex = 1; + RepairLabel.Text = "Ремонты"; + // + // CountLabel + // + CountLabel.AutoSize = true; + CountLabel.Location = new Point(12, 62); + CountLabel.Name = "CountLabel"; + CountLabel.Size = new Size(90, 20); + CountLabel.TabIndex = 2; + CountLabel.Text = "Количество"; + // + // CountTextBox + // + CountTextBox.Location = new Point(139, 55); + CountTextBox.Margin = new Padding(3, 4, 3, 4); + CountTextBox.Name = "CountTextBox"; + CountTextBox.Size = new Size(138, 27); + CountTextBox.TabIndex = 3; + // + // SaveButton + // + SaveButton.Location = new Point(80, 97); + SaveButton.Margin = new Padding(3, 4, 3, 4); + SaveButton.Name = "SaveButton"; + SaveButton.Size = new Size(95, 31); + SaveButton.TabIndex = 4; + SaveButton.Text = "Сохранить"; + SaveButton.UseVisualStyleBackColor = true; + SaveButton.Click += SaveButton_Click; + // + // CancelButton + // + CancelButton.Location = new Point(191, 97); + CancelButton.Margin = new Padding(3, 4, 3, 4); + CancelButton.Name = "CancelButton"; + CancelButton.Size = new Size(86, 31); + CancelButton.TabIndex = 5; + CancelButton.Text = "Отмена"; + CancelButton.UseVisualStyleBackColor = true; + CancelButton.Click += CancelButton_Click; + // + // FormSell + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(299, 144); + Controls.Add(CancelButton); + Controls.Add(SaveButton); + Controls.Add(CountTextBox); + Controls.Add(CountLabel); + Controls.Add(RepairLabel); + Controls.Add(RepairComboBox); + Margin = new Padding(3, 4, 3, 4); + Name = "FormSell"; + StartPosition = FormStartPosition.CenterScreen; + Text = "Форма продажи"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private ComboBox RepairComboBox; + private Label RepairLabel; + private Label CountLabel; + private TextBox CountTextBox; + private Button SaveButton; + private Button CancelButton; + + } +} \ No newline at end of file diff --git a/CarRepairShop/CarRepairShop/FormSell.cs b/CarRepairShop/CarRepairShop/FormSell.cs new file mode 100644 index 0000000..b512ace --- /dev/null +++ b/CarRepairShop/CarRepairShop/FormSell.cs @@ -0,0 +1,108 @@ +using CarRepairShopContracts.BusinessLogicsContracts; +using CarRepairShopContracts.ViewModels; +using CarRepairShopDataModels.Models; + +namespace CarRepairShop +{ + public partial class FormSell : Form + { + private readonly List? _RepairList; + IShopLogic _shopLogic; + IRepairLogic _RepairLogic; + public FormSell(IRepairLogic RepairLogic, IShopLogic shopLogic) + { + InitializeComponent(); + _shopLogic = shopLogic; + _RepairLogic = RepairLogic; + _RepairList = RepairLogic.ReadList(null); + if (_RepairList != null) + { + RepairComboBox.DisplayMember = "RepairName"; + RepairComboBox.ValueMember = "Id"; + RepairComboBox.DataSource = _RepairList; + RepairComboBox.SelectedItem = null; + } + } + public int RepairId + { + get + { + return Convert.ToInt32(RepairComboBox.SelectedValue); + } + set + { + RepairComboBox.SelectedValue = value; + } + } + + public IRepairModel? RepairModel + { + get + { + if (_RepairList == null) + { + return null; + } + foreach (var elem in _RepairList) + { + if (elem.Id == RepairId) + { + return elem; + } + } + return null; + } + } + public int Count + { + get { return Convert.ToInt32(CountTextBox.Text); } + set { CountTextBox.Text = value.ToString(); } + } + + private void CancelButton_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + + private void SaveButton_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(CountTextBox.Text)) + { + MessageBox.Show("Заполните поле Количество", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (RepairComboBox.SelectedValue == null) + { + MessageBox.Show("Выберите ремонт", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + + try + { + int count = Convert.ToInt32(CountTextBox.Text); + var repair = _RepairLogic.ReadElement(new() { Id = Convert.ToInt32(RepairComboBox.SelectedValue) }); + if (repair == null) + return; + bool res = _shopLogic.MakeSell(repair, count); + + if (!res) + { + throw new Exception("Ошибка при продаже."); + } + + MessageBox.Show("Продажа прошла успешно"); + DialogResult = DialogResult.OK; + Close(); + + } + catch (Exception err) + { + MessageBox.Show("Ошибка продажи"); + return; + } +} + } +} diff --git a/CarRepairShop/CarRepairShop/FormSell.resx b/CarRepairShop/CarRepairShop/FormSell.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/CarRepairShop/CarRepairShop/FormSell.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/CarRepairShop/CarRepairShop/FormShop.Designer.cs b/CarRepairShop/CarRepairShop/FormShop.Designer.cs new file mode 100644 index 0000000..49e6d4d --- /dev/null +++ b/CarRepairShop/CarRepairShop/FormShop.Designer.cs @@ -0,0 +1,228 @@ +namespace CarRepairShop +{ + partial class FormShop + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + dateTimePicker = new DateTimePicker(); + textBoxName = new TextBox(); + textBoxAdress = new TextBox(); + labelName = new Label(); + labelAdress = new Label(); + labelDate = new Label(); + buttonSave = new Button(); + buttonCancel = new Button(); + dataGridView = new DataGridView(); + ColumnId = new DataGridViewTextBoxColumn(); + ShopName = new DataGridViewTextBoxColumn(); + ColumnCost = new DataGridViewTextBoxColumn(); + ColumnCount = new DataGridViewTextBoxColumn(); + CapacityUpDown = new NumericUpDown(); + CapacityLabel = new Label(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + ((System.ComponentModel.ISupportInitialize)CapacityUpDown).BeginInit(); + SuspendLayout(); + // + // dateTimePicker + // + dateTimePicker.Location = new Point(97, 93); + dateTimePicker.Margin = new Padding(3, 4, 3, 4); + dateTimePicker.Name = "dateTimePicker"; + dateTimePicker.Size = new Size(363, 27); + dateTimePicker.TabIndex = 0; + // + // textBoxName + // + textBoxName.Location = new Point(97, 16); + textBoxName.Margin = new Padding(3, 4, 3, 4); + textBoxName.Name = "textBoxName"; + textBoxName.Size = new Size(363, 27); + textBoxName.TabIndex = 1; + // + // textBoxAdress + // + textBoxAdress.Location = new Point(97, 55); + textBoxAdress.Margin = new Padding(3, 4, 3, 4); + textBoxAdress.Name = "textBoxAdress"; + textBoxAdress.Size = new Size(363, 27); + textBoxAdress.TabIndex = 2; + // + // labelName + // + labelName.AutoSize = true; + labelName.Location = new Point(14, 20); + labelName.Name = "labelName"; + labelName.Size = new Size(77, 20); + labelName.TabIndex = 3; + labelName.Text = "Название"; + // + // labelAdress + // + labelAdress.AutoSize = true; + labelAdress.Location = new Point(14, 59); + labelAdress.Name = "labelAdress"; + labelAdress.Size = new Size(51, 20); + labelAdress.TabIndex = 4; + labelAdress.Text = "Адрес"; + // + // labelDate + // + labelDate.AutoSize = true; + labelDate.Location = new Point(14, 101); + labelDate.Name = "labelDate"; + labelDate.Size = new Size(41, 20); + labelDate.TabIndex = 5; + labelDate.Text = "Дата"; + // + // buttonSave + // + buttonSave.Location = new Point(272, 430); + buttonSave.Margin = new Padding(3, 4, 3, 4); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(91, 31); + buttonSave.TabIndex = 6; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += SaveButton_Click; + // + // buttonCancel + // + buttonCancel.Location = new Point(369, 430); + buttonCancel.Margin = new Padding(3, 4, 3, 4); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(86, 31); + buttonCancel.TabIndex = 7; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += CancelButton_Click; + // + // dataGridView + // + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Columns.AddRange(new DataGridViewColumn[] { ColumnId, ShopName, ColumnCost, ColumnCount }); + dataGridView.Location = new Point(14, 161); + dataGridView.Margin = new Padding(3, 4, 3, 4); + dataGridView.Name = "dataGridView"; + dataGridView.RowHeadersWidth = 51; + dataGridView.Size = new Size(447, 261); + dataGridView.TabIndex = 8; + // + // ColumnId + // + ColumnId.HeaderText = "Идентификатор"; + ColumnId.MinimumWidth = 6; + ColumnId.Name = "ColumnId"; + ColumnId.Visible = false; + ColumnId.Width = 125; + // + // ShopName + // + ShopName.HeaderText = "Название"; + ShopName.MinimumWidth = 6; + ShopName.Name = "ShopName"; + ShopName.ReadOnly = true; + ShopName.Width = 150; + // + // ColumnCost + // + ColumnCost.HeaderText = "Цена"; + ColumnCost.MinimumWidth = 6; + ColumnCost.Name = "ColumnCost"; + ColumnCost.ReadOnly = true; + ColumnCost.Width = 125; + // + // ColumnCount + // + ColumnCount.HeaderText = "Количество"; + ColumnCount.MinimumWidth = 6; + ColumnCount.Name = "ColumnCount"; + ColumnCount.ReadOnly = true; + ColumnCount.Width = 125; + // + // CapacityUpDown + // + CapacityUpDown.Location = new Point(118, 130); + CapacityUpDown.Maximum = new decimal(new int[] { 10000, 0, 0, 0 }); + CapacityUpDown.Name = "CapacityUpDown"; + CapacityUpDown.Size = new Size(120, 27); + CapacityUpDown.TabIndex = 9; + // + // CapacityLabel + // + CapacityLabel.AutoSize = true; + CapacityLabel.Location = new Point(12, 137); + CapacityLabel.Name = "CapacityLabel"; + CapacityLabel.Size = new Size(100, 20); + CapacityLabel.TabIndex = 10; + CapacityLabel.Text = "Вместимость"; + // + // FormShop + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(471, 474); + Controls.Add(dataGridView); + Controls.Add(buttonCancel); + Controls.Add(buttonSave); + Controls.Add(labelDate); + Controls.Add(labelAdress); + Controls.Add(labelName); + Controls.Add(textBoxAdress); + Controls.Add(textBoxName); + Controls.Add(dateTimePicker); + Controls.Add(CapacityLabel); + Controls.Add(CapacityUpDown); + Margin = new Padding(3, 4, 3, 4); + Name = "FormShop"; + StartPosition = FormStartPosition.CenterScreen; + Text = "Магазин"; + Load += FormShop_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ((System.ComponentModel.ISupportInitialize)CapacityUpDown).EndInit(); + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private DateTimePicker dateTimePicker; + private TextBox textBoxName; + private TextBox textBoxAdress; + private Label labelName; + private Label labelAdress; + private Label labelDate; + private Button buttonSave; + private Button buttonCancel; + private DataGridView dataGridView; + private DataGridViewTextBoxColumn ColumnId; + private DataGridViewTextBoxColumn ShopName; + private DataGridViewTextBoxColumn ColumnCost; + private DataGridViewTextBoxColumn ColumnCount; + private NumericUpDown CapacityUpDown; + private Label CapacityLabel; + } +} \ No newline at end of file diff --git a/CarRepairShop/CarRepairShop/FormShop.cs b/CarRepairShop/CarRepairShop/FormShop.cs new file mode 100644 index 0000000..1ebba07 --- /dev/null +++ b/CarRepairShop/CarRepairShop/FormShop.cs @@ -0,0 +1,115 @@ +using CarRepairShopContracts.BindingModels; +using CarRepairShopContracts.BusinessLogicsContracts; +using CarRepairShopContracts.SearchModels; +using CarRepairShopDataModels.Models; +using Microsoft.Extensions.Logging; + +namespace CarRepairShop +{ + public partial class FormShop : Form + { + private readonly ILogger _logger; + private readonly IShopLogic _logic; + public int? _id; + private Dictionary _repairs; + public FormShop(ILogger logger, IShopLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + private void FormShop_Load(object sender, EventArgs e) + { + if (_id.HasValue) + { + _logger.LogInformation("Загрузка магазина"); + try + { + var shop = _logic.ReadElement(new ShopSearchModel { Id = _id }); + if (shop != null) + { + textBoxName.Text = shop.ShopName; + textBoxAdress.Text = shop.Address; + dateTimePicker.Text = shop.DateOpen.ToString(); + CapacityUpDown.Value = shop.MaxCapacity; + _repairs = shop.ShopRepairs ?? new Dictionary(); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки магазина"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + } + + private void LoadData() + { + _logger.LogInformation("Загрузка товаров магазина"); + try + { + if (_repairs != null) + { + foreach (var repair in _repairs) + { + dataGridView.Rows.Add(new object[] { repair.Key, repair.Value.Item1.RepairName, repair.Value.Item1.Price, repair.Value.Item2 }); + } + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки ремонтов магазина"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + + private void CancelButton_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + + private void SaveButton_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(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, + Address = textBoxAdress.Text, + DateOpen = dateTimePicker.Value.Date, + MaxCapacity = Convert.ToInt32(CapacityUpDown.Value), + }; + var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + Close(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка сохранения магазина"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } +} diff --git a/CarRepairShop/CarRepairShop/FormShop.resx b/CarRepairShop/CarRepairShop/FormShop.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/CarRepairShop/CarRepairShop/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/CarRepairShop/CarRepairShop/FormShops.Designer.cs b/CarRepairShop/CarRepairShop/FormShops.Designer.cs new file mode 100644 index 0000000..a98bfcd --- /dev/null +++ b/CarRepairShop/CarRepairShop/FormShops.Designer.cs @@ -0,0 +1,126 @@ +namespace CarRepairShop +{ + partial class FormShops + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + dataGridView = new DataGridView(); + buttonAdd = new Button(); + buttonUpdate = new Button(); + buttonRefresh = new Button(); + buttonDelete = new Button(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // dataGridView + // + dataGridView.BackgroundColor = Color.White; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(14, 16); + dataGridView.Margin = new Padding(3, 4, 3, 4); + dataGridView.Name = "dataGridView"; + dataGridView.RowHeadersWidth = 51; + dataGridView.Size = new Size(449, 499); + dataGridView.TabIndex = 0; + // + // buttonAdd + // + buttonAdd.Location = new Point(470, 16); + buttonAdd.Margin = new Padding(3, 4, 3, 4); + buttonAdd.Name = "buttonAdd"; + buttonAdd.Size = new Size(130, 31); + buttonAdd.TabIndex = 1; + buttonAdd.Text = "Добавить"; + buttonAdd.UseVisualStyleBackColor = true; + buttonAdd.Click += ButtonAdd_Click; + // + // buttonUpdate + // + buttonUpdate.Location = new Point(470, 55); + buttonUpdate.Margin = new Padding(3, 4, 3, 4); + buttonUpdate.Name = "buttonUpdate"; + buttonUpdate.Size = new Size(130, 31); + buttonUpdate.TabIndex = 2; + buttonUpdate.Text = "Изменить"; + buttonUpdate.UseVisualStyleBackColor = true; + buttonUpdate.Click += ButtonUpdate_Click; + // + // buttonRefresh + // + buttonRefresh.Location = new Point(470, 93); + buttonRefresh.Margin = new Padding(3, 4, 3, 4); + buttonRefresh.Name = "buttonRefresh"; + buttonRefresh.Size = new Size(130, 31); + buttonRefresh.TabIndex = 3; + buttonRefresh.Text = "Обновить"; + buttonRefresh.UseVisualStyleBackColor = true; + buttonRefresh.Click += ButtonRefresh_Click; + // + // buttonDelete + // + buttonDelete.Location = new Point(470, 132); + buttonDelete.Margin = new Padding(3, 4, 3, 4); + buttonDelete.Name = "buttonDelete"; + buttonDelete.Size = new Size(130, 31); + buttonDelete.TabIndex = 4; + buttonDelete.Text = "Удалить"; + buttonDelete.UseVisualStyleBackColor = true; + buttonDelete.Click += ButtonDelete_Click; + // + // FormShops + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(616, 537); + Controls.Add(buttonDelete); + Controls.Add(buttonRefresh); + Controls.Add(buttonUpdate); + Controls.Add(buttonAdd); + Controls.Add(dataGridView); + Margin = new Padding(3, 4, 3, 4); + Name = "FormShops"; + StartPosition = FormStartPosition.CenterScreen; + Text = "Магазины"; + Load += FormShops_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView; + private Button buttonAdd; + private Button buttonUpdate; + private Button buttonRefresh; + private Button buttonDelete; + private DataGridViewTextBoxColumn Column1; + private DataGridViewTextBoxColumn Column2; + private DataGridViewTextBoxColumn Column3; + private DataGridViewTextBoxColumn Column4; + private DataGridViewTextBoxColumn Column5; + } +} \ No newline at end of file diff --git a/CarRepairShop/CarRepairShop/FormShops.cs b/CarRepairShop/CarRepairShop/FormShops.cs new file mode 100644 index 0000000..f4990c7 --- /dev/null +++ b/CarRepairShop/CarRepairShop/FormShops.cs @@ -0,0 +1,118 @@ +using CarRepairShopContracts.BindingModels; +using CarRepairShopContracts.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 CarRepairShop +{ + public partial class FormShops : Form + { + private readonly ILogger _logger; + private readonly IShopLogic _logic; + public FormShops(ILogger logger, IShopLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + + private void LoadData() + { + try + { + var list = _logic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["Id"].Visible = false; + dataGridView.Columns["ShopName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + dataGridView.Columns["Address"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + dataGridView.Columns["DateOpen"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + dataGridView.Columns["ShopRepairs"].Visible = false; + } + _logger.LogInformation("Загрузка магазинов"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки магазинов"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void FormShops_Load(object sender, EventArgs e) + { + LoadData(); + } + + private void 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 ButtonUpdate_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + var service = Program.ServiceProvider?.GetService(typeof(FormShop)); + if (service is FormShop form) + { + var tmp = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + form._id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + } + + private void ButtonRefresh_Click(object sender, EventArgs e) + { + LoadData(); + } + + private void ButtonDelete_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Удаление магазина"); + try + { + if (!_logic.Delete(new ShopBindingModel + { + Id = id + })) + { + throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка удаления магазина"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } + } +} diff --git a/CarRepairShop/CarRepairShop/FormShops.resx b/CarRepairShop/CarRepairShop/FormShops.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/CarRepairShop/CarRepairShop/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/CarRepairShop/CarRepairShop/FormSupply.Designer.cs b/CarRepairShop/CarRepairShop/FormSupply.Designer.cs new file mode 100644 index 0000000..2b20b8c --- /dev/null +++ b/CarRepairShop/CarRepairShop/FormSupply.Designer.cs @@ -0,0 +1,150 @@ +namespace CarRepairShop +{ + partial class FormSupply + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + comboBoxShop = new ComboBox(); + comboBoxRepair = new ComboBox(); + textBoxCount = new TextBox(); + buttonSave = new Button(); + buttonCancel = new Button(); + labelShop = new Label(); + labelRepair = new Label(); + labelCount = new Label(); + SuspendLayout(); + // + // comboBoxShop + // + comboBoxShop.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxShop.FormattingEnabled = true; + comboBoxShop.Location = new Point(110, 16); + comboBoxShop.Margin = new Padding(3, 4, 3, 4); + comboBoxShop.Name = "comboBoxShop"; + comboBoxShop.Size = new Size(282, 28); + comboBoxShop.TabIndex = 0; + // + // comboBoxRepair + // + comboBoxRepair.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxRepair.FormattingEnabled = true; + comboBoxRepair.Location = new Point(110, 55); + comboBoxRepair.Margin = new Padding(3, 4, 3, 4); + comboBoxRepair.Name = "comboBoxRepair"; + comboBoxRepair.Size = new Size(282, 28); + comboBoxRepair.TabIndex = 1; + // + // textBoxCount + // + textBoxCount.Location = new Point(110, 93); + textBoxCount.Margin = new Padding(3, 4, 3, 4); + textBoxCount.Name = "textBoxCount"; + textBoxCount.Size = new Size(282, 27); + textBoxCount.TabIndex = 2; + // + // buttonSave + // + buttonSave.Location = new Point(204, 132); + buttonSave.Margin = new Padding(3, 4, 3, 4); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(96, 31); + buttonSave.TabIndex = 3; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += SaveButton_Click; + // + // buttonCancel + // + buttonCancel.Location = new Point(306, 132); + buttonCancel.Margin = new Padding(3, 4, 3, 4); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(86, 31); + buttonCancel.TabIndex = 4; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += CancelButton_Click; + // + // labelShop + // + labelShop.AutoSize = true; + labelShop.Location = new Point(12, 16); + labelShop.Name = "labelShop"; + labelShop.Size = new Size(72, 20); + labelShop.TabIndex = 5; + labelShop.Text = "Магазин:"; + // + // labelRepair + // + labelRepair.AutoSize = true; + labelRepair.Location = new Point(12, 55); + labelRepair.Name = "labelRepair"; + labelRepair.Size = new Size(63, 20); + labelRepair.TabIndex = 6; + labelRepair.Text = "Ремонт:"; + // + // labelCount + // + labelCount.AutoSize = true; + labelCount.Location = new Point(12, 93); + labelCount.Name = "labelCount"; + labelCount.Size = new Size(93, 20); + labelCount.TabIndex = 7; + labelCount.Text = "Количество:"; + // + // FormSupply + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(406, 181); + Controls.Add(labelCount); + Controls.Add(labelRepair); + Controls.Add(labelShop); + Controls.Add(buttonCancel); + Controls.Add(buttonSave); + Controls.Add(textBoxCount); + Controls.Add(comboBoxRepair); + Controls.Add(comboBoxShop); + Margin = new Padding(3, 4, 3, 4); + Name = "FormSupply"; + StartPosition = FormStartPosition.CenterScreen; + Text = "Поставки"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private ComboBox comboBoxShop; + private ComboBox comboBoxRepair; + private TextBox textBoxCount; + private Button buttonSave; + private Button buttonCancel; + private Label labelShop; + private Label labelRepair; + private Label labelCount; + } +} \ No newline at end of file diff --git a/CarRepairShop/CarRepairShop/FormSupply.cs b/CarRepairShop/CarRepairShop/FormSupply.cs new file mode 100644 index 0000000..ce6aa68 --- /dev/null +++ b/CarRepairShop/CarRepairShop/FormSupply.cs @@ -0,0 +1,142 @@ +using CarRepairShopContracts.BusinessLogicsContracts; +using CarRepairShopContracts.SearchModels; +using CarRepairShopContracts.ViewModels; +using CarRepairShopDataModels.Models; + +namespace CarRepairShop +{ + public partial class FormSupply : Form + { + private readonly List? _repairList; + private readonly List? _shopsList; + IShopLogic _shopLogic; + IRepairLogic _repairLogic; + public int ShopId + { + get + { + return + Convert.ToInt32(comboBoxShop.SelectedValue); + } + set + { + comboBoxShop.SelectedValue = value; + } + } + public int RepairId + { + get + { + return + Convert.ToInt32(comboBoxRepair.SelectedValue); + } + set + { + comboBoxRepair.SelectedValue = value; + } + } + + public IRepairModel? RepairModel + { + get + { + if (_repairList == null) + { + return null; + } + foreach (var elem in _repairList) + { + if (elem.Id == RepairId) + { + return elem; + } + } + return null; + } + } + + + public int Count + { + get { return Convert.ToInt32(textBoxCount.Text); } + set + { textBoxCount.Text = value.ToString(); } + } + public FormSupply(IRepairLogic repairLogic, IShopLogic shopLogic) + { + InitializeComponent(); + _shopLogic = shopLogic; + _repairLogic = repairLogic; + _repairList = repairLogic.ReadList(null); + _shopsList = shopLogic.ReadList(null); + if (_repairList != null) + { + comboBoxRepair.DisplayMember = "RepairName"; + comboBoxRepair.ValueMember = "Id"; + comboBoxRepair.DataSource = _repairList; + comboBoxRepair.SelectedItem = null; + } + if (_shopsList != null) + { + comboBoxShop.DisplayMember = "ShopName"; + comboBoxShop.ValueMember = "Id"; + comboBoxShop.DataSource = _shopsList; + comboBoxShop.SelectedItem = null; + } + } + + private void SaveButton_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxCount.Text)) + { + MessageBox.Show("Заполните поле Количество", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (comboBoxRepair.SelectedValue == null) + { + MessageBox.Show("Выберите ремонт", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (comboBoxShop.SelectedValue == null) + { + MessageBox.Show("Выберите магазин", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + + try + { + int count = Convert.ToInt32(textBoxCount.Text); + + bool res = _shopLogic.MakeSupply( + new ShopSearchModel() { Id = Convert.ToInt32(comboBoxShop.SelectedValue) }, + _repairLogic.ReadElement(new() { Id = Convert.ToInt32(comboBoxRepair.SelectedValue) }), + count + ); + + if (!res) + { + throw new Exception("Ошибка при пополнении. Дополнительная информация в логах"); + } + + MessageBox.Show("Пополнение прошло успешно"); + DialogResult = DialogResult.OK; + Close(); + + } + catch (Exception err) + { + MessageBox.Show("Ошибка пополнения"); + return; + } + } + + private void CancelButton_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } +} diff --git a/CarRepairShop/CarRepairShop/FormSupply.resx b/CarRepairShop/CarRepairShop/FormSupply.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/CarRepairShop/CarRepairShop/FormSupply.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/CarRepairShop/CarRepairShop/Program.cs b/CarRepairShop/CarRepairShop/Program.cs index 5f77e56..4bdfc87 100644 --- a/CarRepairShop/CarRepairShop/Program.cs +++ b/CarRepairShop/CarRepairShop/Program.cs @@ -34,6 +34,8 @@ namespace CarRepairShop option.AddNLog("nlog.config"); }); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -46,6 +48,10 @@ namespace CarRepairShop services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); } } } \ No newline at end of file diff --git a/CarRepairShop/CarRepairShopBusinessLogic/OrderLogic.cs b/CarRepairShop/CarRepairShopBusinessLogic/OrderLogic.cs index c00d197..743f42d 100644 --- a/CarRepairShop/CarRepairShopBusinessLogic/OrderLogic.cs +++ b/CarRepairShop/CarRepairShopBusinessLogic/OrderLogic.cs @@ -4,6 +4,7 @@ using CarRepairShopContracts.SearchModels; using CarRepairShopContracts.StoragesContracts; using CarRepairShopContracts.ViewModels; using CarRepairShopDataModels.Enums; +using CarRepairShopDataModels.Models; using Microsoft.Extensions.Logging; namespace CarRepairShopBusinessLogic @@ -12,11 +13,18 @@ namespace CarRepairShopBusinessLogic { private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; + private readonly IShopStorage _shopStorage; + private readonly IShopLogic _shopLogic; + private readonly IRepairStorage _repairStorage; - public OrderLogic(ILogger logger, IOrderStorage orderStorage) + public OrderLogic(IOrderStorage orderStorage, IShopStorage shopStorage, IShopLogic shopLogic, IRepairStorage repairStorage, ILogger logger) { _logger = logger; _orderStorage = orderStorage; + _shopStorage = shopStorage; + _logger = logger; + _shopLogic = shopLogic; + _repairStorage = repairStorage; } public List? ReadList(OrderSearchModel? model) @@ -46,7 +54,7 @@ namespace CarRepairShopBusinessLogic return true; } - public bool ChangeStatus(OrderBindingModel model, OrderStatus status) + private bool ChangeStatus(OrderBindingModel model, OrderStatus status) { CheckModel(model); var element = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id }); @@ -60,6 +68,20 @@ namespace CarRepairShopBusinessLogic _logger.LogWarning("Status change operation failed"); throw new InvalidOperationException("Текущий статус заказа не может быть переведен в выбранный"); } + if (element.Status == OrderStatus.Готов) + { + var repair = _repairStorage.GetElement(new RepairSearchModel() { Id = model.RepairId }); + if (repair == null) + { + _logger.LogWarning("Status update to " + status.ToString() + " operation failed. Document not found."); + return false; + } + if (CheckSupply(repair, model.Count) == false) + { + _logger.LogWarning("Status update to " + status.ToString() + " operation failed. Shop supply error."); + return false; + } + } model.Status = status; if (model.Status == OrderStatus.Выдан) model.DateImplement = DateTime.Now; _orderStorage.Update(model); @@ -101,5 +123,63 @@ namespace CarRepairShopBusinessLogic } _logger.LogInformation("Order. Sum:{ Cost}. Id: { Id}", model.Sum, model.Id); } + private bool CheckSupply(IRepairModel Repair, int count) + { + if (count <= 0) + { + _logger.LogWarning("Check then supply operation error. Repair count < 0."); + return false; + } + + int sumCapacity = 0; + int sumCount = 0; + sumCapacity = _shopStorage.GetFullList().Select(x => x.MaxCapacity).Sum(); + sumCount = _shopStorage.GetFullList().Select(x => x.ShopRepairs.Select(y => y.Value.Item2).Sum()).Sum(); + int freeSpace = sumCapacity - sumCount; + + if (freeSpace - count < 0) + { + _logger.LogWarning("Check then supply operation error. There's no place for new Repair in shops."); + return false; + } + + foreach (var shop in _shopStorage.GetFullList()) + { + freeSpace = shop.MaxCapacity; + foreach (var doc in shop.ShopRepairs) + { + freeSpace -= doc.Value.Item2; + } + if (freeSpace == 0) + { + continue; + } + if (freeSpace - count >= 0) + { + if (_shopLogic.MakeSupply(new() { Id = shop.Id }, Repair, count)) + count = 0; + else + { + _logger.LogWarning("Supply error"); + return false; + } + } + if (freeSpace - count < 0) + { + if (_shopLogic.MakeSupply(new() { Id = shop.Id }, Repair, freeSpace)) + count -= freeSpace; + else + { + _logger.LogWarning("Supply error"); + return false; + } + } + if (count <= 0) + { + return true; + } + } + return false; + } } } diff --git a/CarRepairShop/CarRepairShopBusinessLogic/ShopLogic.cs b/CarRepairShop/CarRepairShopBusinessLogic/ShopLogic.cs new file mode 100644 index 0000000..f2f55be --- /dev/null +++ b/CarRepairShop/CarRepairShopBusinessLogic/ShopLogic.cs @@ -0,0 +1,166 @@ +using CarRepairShopContracts.BindingModels; +using CarRepairShopContracts.BusinessLogicsContracts; +using CarRepairShopContracts.SearchModels; +using CarRepairShopContracts.StoragesContracts; +using CarRepairShopContracts.ViewModels; +using CarRepairShopDataModels.Models; +using Microsoft.Extensions.Logging; + +namespace CarRepairShopBusinessLogic +{ + public class ShopLogic : IShopLogic + { + private readonly ILogger _logger; + private readonly IShopStorage _shopStorage; + + public ShopLogic(ILogger logger, IShopStorage shopStorage) + { + _logger = logger; + _shopStorage = shopStorage; + } + + public List ReadList(ShopSearchModel model) + { + _logger.LogInformation("ReadList. ShopName:{Name}. Id:{ Id}", model?.Name, model?.Id); + var list = model == null ? _shopStorage.GetFullList() : _shopStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + _logger.LogInformation("ReadList. Count:{Count}", list.Count); + return list; + + } + + public bool MakeSupply(ShopSearchModel model, IRepairModel repair, int count) + { + if (model == null) + throw new ArgumentNullException(nameof(model)); + if (repair == null) + throw new ArgumentNullException(nameof(repair)); + if (count <= 0) + throw new ArgumentNullException("Количество должно быть положительным числом"); + ShopViewModel curModel = _shopStorage.GetElement(model); + if (curModel == null) + throw new ArgumentNullException(nameof(curModel)); + var countItems = curModel.ShopRepairs.Select(x => x.Value.Item2).Sum(); + if (curModel.MaxCapacity - countItems >= count) + { + if (curModel.ShopRepairs.TryGetValue(repair.Id, out var sameDocument)) + { + curModel.ShopRepairs[repair.Id] = (repair, sameDocument.Item2 + count); + _logger.LogInformation("Same repair found by supply. Added {0} of {1} in {2} shop", count, repair.RepairName, curModel.ShopName); + } + else + { + curModel.ShopRepairs[repair.Id] = (repair, count); + _logger.LogInformation("New repair added by supply. Added {0} of {1} in {2} shop", count, repair.RepairName, curModel.ShopName); + } + _shopStorage.Update(new() + { + Id = curModel.Id, + ShopName = curModel.ShopName, + Address = curModel.Address, + DateOpen = curModel.DateOpen, + ShopRepairs = curModel.ShopRepairs, + MaxCapacity = curModel.MaxCapacity + }); + } + else + { + _logger.LogWarning("Required shop is overflowed"); + return false; + } + return true; + } + public ShopViewModel ReadElement(ShopSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + _logger.LogInformation("ReadElement. ShopName:{ShopName}.Id:{ Id}", model.Name, model.Id); + var element = _shopStorage.GetElement(model); + if (element == null) + { + _logger.LogWarning("ReadElement element not found"); + return null; + } + _logger.LogInformation("ReadElement find. Id:{Id}", element.Id); + return element; + } + + public bool Create(ShopBindingModel model) + { + CheckModel(model); + if (_shopStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } + + public bool Update(ShopBindingModel model) + { + CheckModel(model); + if (_shopStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + return true; + } + public bool Delete(ShopBindingModel model) + { + CheckModel(model, false); + _logger.LogInformation("Delete. Id:{Id}", model.Id); + if (_shopStorage.Delete(model) == null) + { + _logger.LogWarning("Delete operation failed"); + return false; + } + return true; + } + private void CheckModel(ShopBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (!withParams) + { + return; + } + if (string.IsNullOrEmpty(model.ShopName)) + { + throw new ArgumentNullException("Нет названия магазина", + nameof(model.ShopName)); + } + if (string.IsNullOrEmpty(model.Address)) + { + throw new ArgumentNullException("Нет адресса магазина", + nameof(model.ShopName)); + } + if (model.DateOpen == null) + { + throw new ArgumentNullException("Нет даты открытия магазина", + nameof(model.ShopName)); + } + _logger.LogInformation("Shop. ShopName:{ShopName}.Address:{Address}. DateOpen:{DateOpen}. Id: { Id}", model.ShopName, model.Address, model.DateOpen, model.Id); + var element = _shopStorage.GetElement(new ShopSearchModel + { + Name = model.ShopName + }); + if (element != null && element.Id != model.Id) + { + throw new InvalidOperationException("Магазин с таким названием уже есть"); + } + } + public bool MakeSell(IRepairModel repeir, int count) + { + return _shopStorage.SellRepairs(repeir, count); + } + } +} diff --git a/CarRepairShop/CarRepairShopContracts/BindingModels/ShopBindingModel.cs b/CarRepairShop/CarRepairShopContracts/BindingModels/ShopBindingModel.cs new file mode 100644 index 0000000..2efa13b --- /dev/null +++ b/CarRepairShop/CarRepairShopContracts/BindingModels/ShopBindingModel.cs @@ -0,0 +1,15 @@ +using CarRepairShopDataModels; +using CarRepairShopDataModels.Models; + +namespace CarRepairShopContracts.BindingModels +{ + public class ShopBindingModel : IShopModel + { + public int Id { get; set; } + public string ShopName { get; set; } + public string Address { get; set; } + public DateTime DateOpen { get; set; } + public int MaxCapacity { get; set; } + public Dictionary ShopRepairs { get; set; } = new(); + } +} diff --git a/CarRepairShop/CarRepairShopContracts/BusinessLogicsContracts/IShopLogic.cs b/CarRepairShop/CarRepairShopContracts/BusinessLogicsContracts/IShopLogic.cs new file mode 100644 index 0000000..538f85f --- /dev/null +++ b/CarRepairShop/CarRepairShopContracts/BusinessLogicsContracts/IShopLogic.cs @@ -0,0 +1,18 @@ +using CarRepairShopContracts.BindingModels; +using CarRepairShopContracts.SearchModels; +using CarRepairShopContracts.ViewModels; +using CarRepairShopDataModels.Models; + +namespace CarRepairShopContracts.BusinessLogicsContracts +{ + public interface IShopLogic + { + List? ReadList(ShopSearchModel? model); + ShopViewModel? ReadElement(ShopSearchModel model); + bool Create(ShopBindingModel model); + bool Update(ShopBindingModel model); + bool Delete(ShopBindingModel model); + bool MakeSupply(ShopSearchModel model, IRepairModel repair, int count); + bool MakeSell(IRepairModel repair, int count); + } +} diff --git a/CarRepairShop/CarRepairShopContracts/SearchModels/ShopSearchModel.cs b/CarRepairShop/CarRepairShopContracts/SearchModels/ShopSearchModel.cs new file mode 100644 index 0000000..88aa7d5 --- /dev/null +++ b/CarRepairShop/CarRepairShopContracts/SearchModels/ShopSearchModel.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CarRepairShopContracts.SearchModels +{ + public class ShopSearchModel + { + public int? Id { get; set; } + public string? Name { get; set; } + } +} diff --git a/CarRepairShop/CarRepairShopContracts/StoragesContracts/IShopStorage.cs b/CarRepairShop/CarRepairShopContracts/StoragesContracts/IShopStorage.cs new file mode 100644 index 0000000..60d2295 --- /dev/null +++ b/CarRepairShop/CarRepairShopContracts/StoragesContracts/IShopStorage.cs @@ -0,0 +1,18 @@ +using CarRepairShopContracts.BindingModels; +using CarRepairShopContracts.SearchModels; +using CarRepairShopContracts.ViewModels; +using CarRepairShopDataModels.Models; + +namespace CarRepairShopContracts.StoragesContracts +{ + public interface IShopStorage + { + List GetFullList(); + List GetFilteredList(ShopSearchModel model); + ShopViewModel? GetElement(ShopSearchModel model); + ShopViewModel? Insert(ShopBindingModel model); + ShopViewModel? Update(ShopBindingModel model); + ShopViewModel? Delete(ShopBindingModel model); + public bool SellRepairs(IRepairModel model, int count); + } +} diff --git a/CarRepairShop/CarRepairShopContracts/ViewModels/ShopViewModel.cs b/CarRepairShop/CarRepairShopContracts/ViewModels/ShopViewModel.cs new file mode 100644 index 0000000..d2f3fd6 --- /dev/null +++ b/CarRepairShop/CarRepairShopContracts/ViewModels/ShopViewModel.cs @@ -0,0 +1,20 @@ +using CarRepairShopDataModels; +using CarRepairShopDataModels.Models; +using System.ComponentModel; + +namespace CarRepairShopContracts.ViewModels +{ + public class ShopViewModel : IShopModel + { + public int Id { get; set; } + [DisplayName("Название магазина")] + public string ShopName { get; set; } + [DisplayName("Адрес магазина")] + public string Address { get; set; } + [DisplayName("Дата открытия")] + public DateTime DateOpen { get; set; } + [DisplayName("Вместимость")] + public int MaxCapacity { get; set; } + public Dictionary ShopRepairs { get; set; } = new(); + } +} diff --git a/CarRepairShop/CarRepairShopDataModels/IShopModel.cs b/CarRepairShop/CarRepairShopDataModels/IShopModel.cs new file mode 100644 index 0000000..7e104af --- /dev/null +++ b/CarRepairShop/CarRepairShopDataModels/IShopModel.cs @@ -0,0 +1,13 @@ +using CarRepairShopDataModels.Models; + +namespace CarRepairShopDataModels +{ + public interface IShopModel : IId + { + string ShopName { get; } + string Address { get; } + DateTime DateOpen { get; } + Dictionary ShopRepairs { get; } + int MaxCapacity { get; } + } +} diff --git a/CarRepairShop/CarRepairShopFileImplement/DataFileSingleton.cs b/CarRepairShop/CarRepairShopFileImplement/DataFileSingleton.cs index 2210ec9..55111ec 100644 --- a/CarRepairShop/CarRepairShopFileImplement/DataFileSingleton.cs +++ b/CarRepairShop/CarRepairShopFileImplement/DataFileSingleton.cs @@ -9,9 +9,11 @@ namespace CarRepairShopFileImplement private readonly string ComponentFileName = "Component.xml"; private readonly string OrderFileName = "Order.xml"; private readonly string RepairFileName = "Repair.xml"; + private readonly string ShopFileName = "Shops.xml"; public List Components { get; private set; } public List Orders { get; private set; } public List Repairs { get; private set; } + public List Shops { get; private set; } public static DataFileSingleton GetInstance() { if (instance == null) @@ -26,6 +28,8 @@ namespace CarRepairShopFileImplement "Repairs", x => x.GetXElement); public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement); + public void SaveShops() => SaveData(Shops, ShopFileName, + "Shops", x => x.GetXElement); private DataFileSingleton() { Components = LoadData(ComponentFileName, "Component", x => @@ -34,6 +38,8 @@ namespace CarRepairShopFileImplement Repair.Create(x)!)!; Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!; + Shops = LoadData(ShopFileName, "Shop", x => + Shop.Create(x)!)!; } private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) diff --git a/CarRepairShop/CarRepairShopFileImplement/Implements/ShopStorage.cs b/CarRepairShop/CarRepairShopFileImplement/Implements/ShopStorage.cs new file mode 100644 index 0000000..1ce51c7 --- /dev/null +++ b/CarRepairShop/CarRepairShopFileImplement/Implements/ShopStorage.cs @@ -0,0 +1,119 @@ +using CarRepairShopContracts.BindingModels; +using CarRepairShopContracts.SearchModels; +using CarRepairShopContracts.StoragesContracts; +using CarRepairShopContracts.ViewModels; +using CarRepairShopDataModels.Models; +using CarRepairShopFileImplement.Models; + +namespace CarRepairShopFileImplement.Implements +{ + public class ShopStorage : IShopStorage + { + private readonly DataFileSingleton _source; + public ShopStorage() + { + _source = DataFileSingleton.GetInstance(); + } + public List GetFullList() + { + return _source.Shops.Select(x => x.GetViewModel).ToList(); + } + public List GetFilteredList(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.Name)) + { + return new(); + } + return _source.Shops.Where(x => x.ShopName.Contains(model.Name)).Select(x => x.GetViewModel).ToList(); ; + } + public ShopViewModel? GetElement(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.Name) && !model.Id.HasValue) + { + return null; + } + return _source.Shops.FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name) && x.ShopName == model.Name) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; + } + public ShopViewModel? Insert(ShopBindingModel model) + { + model.Id = _source.Shops.Count > 0 ? _source.Shops.Max(x => x.Id) + 1 : 1; + var newShop = Shop.Create(model); + if (newShop == null) + { + return null; + } + _source.Shops.Add(newShop); + _source.SaveShops(); + return newShop.GetViewModel; + } + public ShopViewModel? Update(ShopBindingModel model) + { + var component = _source.Shops.FirstOrDefault(x => x.Id == model.Id); + if (component == null) + { + return null; + } + component.Update(model); + _source.SaveShops(); + return component.GetViewModel; + } + public ShopViewModel? Delete(ShopBindingModel model) + { + var element = _source.Shops.FirstOrDefault(x => x.Id == + model.Id); + if (element != null) + { + _source.Shops.Remove(element); + _source.SaveShops(); + return element.GetViewModel; + } + return null; + } + + public bool CheckAvailability(int repairId, int count) + { + count -= _source.Shops.Select(x => x.ShopRepairs.Select(y => (y.Value.Item1.Id == repairId ? y.Value.Item2 : 0)).Sum()).Sum(); + return count <= 0; + } + + public bool SellRepairs(IRepairModel model, int count) + { + var neededRepair = _source.Repairs.FirstOrDefault(x => x.Id == model.Id); + + if (neededRepair == null || !CheckAvailability(neededRepair.Id, count)) + { + return false; + } + + for (int i = 0; i < _source.Shops.Count; i++) + { + var shop = _source.Shops[i]; + var repairs = shop.ShopRepairs; + + foreach (var repair in repairs.Where(x => x.Value.Item1.Id == neededRepair.Id)) + { + var min = Math.Min(repair.Value.Item2, count); + repairs[repair.Value.Item1.Id] = (repair.Value.Item1, repair.Value.Item2 - min); + count -= min; + + if (count <= 0) + { + break; + } + } + + shop.Update(new ShopBindingModel + { + Id = shop.Id, + ShopName = shop.ShopName, + Address = shop.Address, + DateOpen = shop.DateOpen, + MaxCapacity = shop.MaxCapacity, + ShopRepairs = repairs + }); + } + _source.SaveShops(); + return true; + } + } +} diff --git a/CarRepairShop/CarRepairShopFileImplement/Models/Shop.cs b/CarRepairShop/CarRepairShopFileImplement/Models/Shop.cs new file mode 100644 index 0000000..e9c2a55 --- /dev/null +++ b/CarRepairShop/CarRepairShopFileImplement/Models/Shop.cs @@ -0,0 +1,97 @@ +using CarRepairShopContracts.BindingModels; +using CarRepairShopContracts.ViewModels; +using CarRepairShopDataModels; +using CarRepairShopDataModels.Models; +using System.Xml.Linq; + +namespace CarRepairShopFileImplement.Models +{ + public class Shop : IShopModel + { + public int Id { get; private set; } + public string ShopName { get; private set; } = string.Empty; + public string Address { get; private set; } = string.Empty; + public DateTime DateOpen { get; private set; } + public Dictionary Repairs { get; private set; } = new(); + private Dictionary? _shopRepairs = null; + public Dictionary ShopRepairs + { + get + { + if (_shopRepairs == null) + { + var source = DataFileSingleton.GetInstance(); + _shopRepairs = Repairs.ToDictionary(x => x.Key, y => + ((source.Repairs.FirstOrDefault(z => z.Id == y.Key) as IRepairModel)!, + y.Value)); + } + return _shopRepairs; + } + } + public int MaxCapacity { get; private set; } + public static Shop? Create(ShopBindingModel model) + { + if (model == null) + return null; + return new Shop() + { + Id = model.Id, + ShopName = model.ShopName, + Address = model.Address, + DateOpen = model.DateOpen, + MaxCapacity = model.MaxCapacity, + Repairs = model.ShopRepairs.ToDictionary(x => x.Key, x => x.Value.Item2) + }; + } + public static Shop? Create(XElement element) + { + if (element == null) + { + return null; + } + return new Shop() + { + Id = Convert.ToInt32(element.Attribute("Id")!.Value), + ShopName = element.Element("ShopName")!.Value, + Address = element.Element("Address")!.Value, + MaxCapacity = Convert.ToInt32(element.Element("MaxCapacity")!.Value), + DateOpen = Convert.ToDateTime(element.Element("DateOpen")!.Value), + Repairs = element.Element("ShopRepairs")!.Elements("ShopRepair").ToDictionary(x => + Convert.ToInt32(x.Element("Key")?.Value), x => + Convert.ToInt32(x.Element("Value")?.Value)) + }; + } + public void Update(ShopBindingModel model) + { + if (model == null) + { + return; + } + ShopName = model.ShopName; + Address = model.Address; + DateOpen = model.DateOpen; + MaxCapacity = model.MaxCapacity; + if (model.ShopRepairs.Count > 0) + { + Repairs = model.ShopRepairs.ToDictionary(x => x.Key, x => x.Value.Item2); + _shopRepairs = null; + } + } + public ShopViewModel GetViewModel => new() + { + Id = Id, + ShopName = ShopName, + Address = Address, + DateOpen = DateOpen, + MaxCapacity = MaxCapacity, + ShopRepairs = ShopRepairs + }; + public XElement GetXElement => new("Shop", + new XAttribute("Id", Id), + new XElement("ShopName", ShopName), + new XElement("Address", Address), + new XElement("DateOpen", DateOpen), + new XElement("MaxCapacity", MaxCapacity), + new XElement("ShopRepairs", Repairs.Select(x => new XElement("ShopRepair",new XElement("Key", x.Key),new XElement("Value", x.Value))).ToArray())); + } +} diff --git a/CarRepairShop/CarRepairShopListImplement/DataListSingleton.cs b/CarRepairShop/CarRepairShopListImplement/DataListSingleton.cs index d2f576d..d38839e 100644 --- a/CarRepairShop/CarRepairShopListImplement/DataListSingleton.cs +++ b/CarRepairShop/CarRepairShopListImplement/DataListSingleton.cs @@ -8,11 +8,13 @@ namespace CarRepairShopListImplement public List Components { get; set; } public List Orders { get; set; } public List Repairs { get; set; } + public List Shops { get; set; } private DataListSingleton() { Components = new List(); Orders = new List(); Repairs = new List(); + Shops = new List(); } public static DataListSingleton GetInstance() { diff --git a/CarRepairShop/CarRepairShopListImplement/Implements/ShopStorage.cs b/CarRepairShop/CarRepairShopListImplement/Implements/ShopStorage.cs new file mode 100644 index 0000000..fb4bb28 --- /dev/null +++ b/CarRepairShop/CarRepairShopListImplement/Implements/ShopStorage.cs @@ -0,0 +1,108 @@ +using CarRepairShopContracts.BindingModels; +using CarRepairShopContracts.SearchModels; +using CarRepairShopContracts.StoragesContracts; +using CarRepairShopContracts.ViewModels; +using CarRepairShopDataModels.Models; +using CarRepairShopListImplement.Models; + +namespace CarRepairShopListImplement.Implements +{ + public class ShopStorage : IShopStorage + { + private readonly DataListSingleton _source; + public ShopStorage() + { + _source = DataListSingleton.GetInstance(); + } + public List GetFullList() + { + var result = new List(); + foreach (var shop in _source.Shops) + { + result.Add(shop.GetViewModel); + } + return result; + } + public List GetFilteredList(ShopSearchModel + model) + { + var result = new List(); + if (string.IsNullOrEmpty(model.Name)) + { + return result; + } + foreach (var shop in _source.Shops) + { + if (shop.ShopName.Contains(model.Name)) + { + result.Add(shop.GetViewModel); + } + } + return result; + } + public ShopViewModel? GetElement(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.Name) && !model.Id.HasValue) + { + return null; + } + foreach (var shop in _source.Shops) + { + if ((!string.IsNullOrEmpty(model.Name) && + shop.ShopName == model.Name) || + (model.Id.HasValue && shop.Id == model.Id)) + { + return shop.GetViewModel; + } + } + return null; + } + public ShopViewModel? Insert(ShopBindingModel model) + { + model.Id = 1; + foreach (var shop in _source.Shops) + { + if (model.Id <= shop.Id) + { + model.Id = shop.Id + 1; + } + } + var newShop = Shop.Create(model); + if (newShop == null) + { + return null; + } + _source.Shops.Add(newShop); + return newShop.GetViewModel; + } + public ShopViewModel? Update(ShopBindingModel model) + { + foreach (var shop in _source.Shops) + { + if (shop.Id == model.Id) + { + shop.Update(model); + return shop.GetViewModel; + } + } + return null; + } + public ShopViewModel? Delete(ShopBindingModel model) + { + for (int i = 0; i < _source.Shops.Count; ++i) + { + if (_source.Shops[i].Id == model.Id) + { + var element = _source.Shops[i]; + _source.Shops.RemoveAt(i); + return element.GetViewModel; + } + } + return null; + } + public bool SellRepairs(IRepairModel model, int count) + { + throw new NotImplementedException(); + } + } +} diff --git a/CarRepairShop/CarRepairShopListImplement/Models/Shop.cs b/CarRepairShop/CarRepairShopListImplement/Models/Shop.cs new file mode 100644 index 0000000..03444d7 --- /dev/null +++ b/CarRepairShop/CarRepairShopListImplement/Models/Shop.cs @@ -0,0 +1,52 @@ +using CarRepairShopContracts.BindingModels; +using CarRepairShopContracts.ViewModels; +using CarRepairShopDataModels; +using CarRepairShopDataModels.Models; + +namespace CarRepairShopListImplement.Models +{ + public class Shop : IShopModel + { + public int Id { get; private set; } + public string ShopName { get; private set; } + public string Address { get; private set; } + public DateTime DateOpen { get; private set; } + public Dictionary ShopRepairs { get; private set; } = new(); + + public static Shop? Create(ShopBindingModel model) + { + if (model == null) + return null; + return new Shop() + { + Id = model.Id, + ShopName = model.ShopName, + Address = model.Address, + DateOpen = model.DateOpen, + ShopRepairs = new() + }; + } + + public void Update(ShopBindingModel? model) + { + if (model == null) + { + return; + } + ShopName = model.ShopName; + Address = model.Address; + DateOpen = model.DateOpen; + ShopRepairs = model.ShopRepairs; + } + + public ShopViewModel GetViewModel => new() + { + Id = Id, + ShopName = ShopName, + Address = Address, + DateOpen = DateOpen, + ShopRepairs = ShopRepairs + }; + public int MaxCapacity => throw new NotImplementedException(); + } +} From 538000e2578e585ca8e3689e4aae94645f141746 Mon Sep 17 00:00:00 2001 From: Yunusov_Niyaz Date: Mon, 25 Mar 2024 21:16:58 +0400 Subject: [PATCH 2/5] =?UTF-8?q?=D0=93=D0=BE=D1=82=D0=BE=D0=B2=D0=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Implements/OrderStorage.cs | 12 +- .../Implements/ShopStorage.cs | 153 ++++++++++++++++++ ... 20240325165319_InitialCreate.Designer.cs} | 81 +++++++++- ...ate.cs => 20240325165319_InitialCreate.cs} | 59 +++++++ .../RepairsShopDatabaseModelSnapshot.cs | 79 +++++++++ .../Models/Repair.cs | 2 + .../Models/Shop.cs | 111 +++++++++++++ .../Models/ShopRepair.cs | 22 +++ .../RepairsShopDatabase.cs | 4 +- 9 files changed, 514 insertions(+), 9 deletions(-) create mode 100644 CarRepairShop/CarRepairShopDatabaseImplement/Implements/ShopStorage.cs rename CarRepairShop/CarRepairShopDatabaseImplement/Migrations/{20240324163100_InitialCreate.Designer.cs => 20240325165319_InitialCreate.Designer.cs} (67%) rename CarRepairShop/CarRepairShopDatabaseImplement/Migrations/{20240324163100_InitialCreate.cs => 20240325165319_InitialCreate.cs} (66%) create mode 100644 CarRepairShop/CarRepairShopDatabaseImplement/Models/Shop.cs create mode 100644 CarRepairShop/CarRepairShopDatabaseImplement/Models/ShopRepair.cs diff --git a/CarRepairShop/CarRepairShopDatabaseImplement/Implements/OrderStorage.cs b/CarRepairShop/CarRepairShopDatabaseImplement/Implements/OrderStorage.cs index f6fc350..9e47c2e 100644 --- a/CarRepairShop/CarRepairShopDatabaseImplement/Implements/OrderStorage.cs +++ b/CarRepairShop/CarRepairShopDatabaseImplement/Implements/OrderStorage.cs @@ -23,7 +23,7 @@ namespace CarRepairShopDatabaseImplement.Implements return new(); } using var context = new RepairsShopDatabase(); - return context.Orders + return context.Orders.Include (x => x.Repair) .Where(x => x.Id == model.Id) .Select(x => x.GetViewModel) .ToList(); @@ -35,12 +35,12 @@ namespace CarRepairShopDatabaseImplement.Implements return null; } using var context = new RepairsShopDatabase(); - return context.Orders.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; + return context.Orders.Include(x => x.Repair).FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; } public OrderViewModel? Insert(OrderBindingModel model) { using var context = new RepairsShopDatabase(); - var newOrder = Order.Create(context, model); + var newOrder = Order.Create(model); if (newOrder == null) { return null; @@ -52,8 +52,7 @@ namespace CarRepairShopDatabaseImplement.Implements public OrderViewModel? Update(OrderBindingModel model) { using var context = new RepairsShopDatabase(); - var order = context.Orders.FirstOrDefault(x => x.Id == - model.Id); + var order = context.Orders.Include(x => x.Repair).FirstOrDefault(x => x.Id == model.Id); if (order == null) { return null; @@ -65,8 +64,7 @@ namespace CarRepairShopDatabaseImplement.Implements public OrderViewModel? Delete(OrderBindingModel model) { using var context = new RepairsShopDatabase(); - var element = context.Orders.FirstOrDefault(rec => rec.Id == - model.Id); + var element = context.Orders.Include(x => x.Repair).FirstOrDefault(rec => rec.Id == model.Id); if (element != null) { context.Orders.Remove(element); diff --git a/CarRepairShop/CarRepairShopDatabaseImplement/Implements/ShopStorage.cs b/CarRepairShop/CarRepairShopDatabaseImplement/Implements/ShopStorage.cs new file mode 100644 index 0000000..df9821b --- /dev/null +++ b/CarRepairShop/CarRepairShopDatabaseImplement/Implements/ShopStorage.cs @@ -0,0 +1,153 @@ +using CarRepairShopContracts.BindingModels; +using CarRepairShopContracts.SearchModels; +using CarRepairShopContracts.StoragesContracts; +using CarRepairShopContracts.ViewModels; +using CarRepairShopDatabaseImplement.Models; +using CarRepairShopDataModels.Models; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CarRepairShopDatabaseImplement.Implements +{ + public class ShopStorage : IShopStorage + { + public ShopViewModel? Delete(ShopBindingModel model) + { + using var context = new RepairsShopDatabase(); + var element = context.Shops.FirstOrDefault(x => x.Id == model.Id); + if (element != null) + { + context.Shops.Remove(element); + context.SaveChanges(); + return element.GetViewModel; + } + return null; + } + + public ShopViewModel? GetElement(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.Name) && !model.Id.HasValue) + { + return null; + } + using var context = new RepairsShopDatabase(); + return context.Shops + .Include(x => x.Repairs) + .ThenInclude(x => x.Repair) + .FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id) + ?.GetViewModel; + } + + public List GetFilteredList(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.Name)) + { + return new(); + } + using var context = new RepairsShopDatabase(); + return context.Shops + .Include(x => x.Repairs) + .ThenInclude(x => x.Repair) + .Select(x => x.GetViewModel) + .Where(x => x.ShopName.Contains(model.Name ?? string.Empty)) + .ToList(); + } + + public List GetFullList() + { + using var context = new RepairsShopDatabase(); + return context.Shops + .Include(x => x.Repairs) + .ThenInclude(x => x.Repair) + .Select(x => x.GetViewModel) + .ToList(); + } + + public ShopViewModel? Insert(ShopBindingModel model) + { + using var context = new RepairsShopDatabase(); + try + { + var newShop = Shop.Create(context, model); + if (newShop == null) + { + return null; + } + if (context.Shops.Any(x => x.ShopName == newShop.ShopName)) + { + throw new Exception("Не должно быть два магазина с одним названием"); + } + context.Shops.Add(newShop); + context.SaveChanges(); + return newShop.GetViewModel; + } + catch + { + throw; + } + } + + public ShopViewModel? Update(ShopBindingModel model) + { + using var context = new RepairsShopDatabase(); + var shop = context.Shops.FirstOrDefault(x => x.Id == model.Id); + if (shop == null) + { + return null; + } + try + { + if (context.Shops.Any(x => (x.ShopName == model.ShopName && x.Id != model.Id))) + { + throw new Exception("Не должно быть два магазина с одним названием"); + } + shop.Update(model); + shop.UpdateRepairs(context, model); + context.SaveChanges(); + return shop.GetViewModel; + } + catch + { + throw; + } + } + public bool SellRepairs(IRepairModel model, int count) + { + if (model == null) + return false; + using var context = new RepairsShopDatabase(); + using var transaction = context.Database.BeginTransaction(); + List lst = new List(); + foreach (var el in context.ShopRepairs.Where(x => x.RepairId == model.Id)) + { + int dif = count; + if (el.Count < dif) + dif = el.Count; + el.Count -= dif; + count -= dif; + if (el.Count == 0) + { + lst.Add(el); + } + if (count == 0) + break; + } + if (count > 0) + { + transaction.Rollback(); + return false; + } + foreach (var el in lst) + { + context.ShopRepairs.Remove(el); + } + context.SaveChanges(); + transaction.Commit(); + return true; + } + } +} diff --git a/CarRepairShop/CarRepairShopDatabaseImplement/Migrations/20240324163100_InitialCreate.Designer.cs b/CarRepairShop/CarRepairShopDatabaseImplement/Migrations/20240325165319_InitialCreate.Designer.cs similarity index 67% rename from CarRepairShop/CarRepairShopDatabaseImplement/Migrations/20240324163100_InitialCreate.Designer.cs rename to CarRepairShop/CarRepairShopDatabaseImplement/Migrations/20240325165319_InitialCreate.Designer.cs index b8e7c4d..a43096b 100644 --- a/CarRepairShop/CarRepairShopDatabaseImplement/Migrations/20240324163100_InitialCreate.Designer.cs +++ b/CarRepairShop/CarRepairShopDatabaseImplement/Migrations/20240325165319_InitialCreate.Designer.cs @@ -12,7 +12,7 @@ using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace CarRepairShopDatabaseImplement.Migrations { [DbContext(typeof(RepairsShopDatabase))] - [Migration("20240324163100_InitialCreate")] + [Migration("20240325165319_InitialCreate")] partial class InitialCreate { /// @@ -124,6 +124,59 @@ namespace CarRepairShopDatabaseImplement.Migrations b.ToTable("RepairComponents"); }); + modelBuilder.Entity("CarRepairShopDatabaseImplement.Models.Shop", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Address") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("DateOpen") + .HasColumnType("datetime2"); + + b.Property("MaxCapacity") + .HasColumnType("int"); + + b.Property("ShopName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Shops"); + }); + + modelBuilder.Entity("CarRepairShopDatabaseImplement.Models.ShopRepair", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("RepairId") + .HasColumnType("int"); + + b.Property("ShopId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("RepairId"); + + b.HasIndex("ShopId"); + + b.ToTable("ShopRepairs"); + }); + modelBuilder.Entity("CarRepairShopDatabaseImplement.Models.Order", b => { b.HasOne("CarRepairShopDatabaseImplement.Models.Repair", "Repair") @@ -154,6 +207,25 @@ namespace CarRepairShopDatabaseImplement.Migrations b.Navigation("Repair"); }); + modelBuilder.Entity("CarRepairShopDatabaseImplement.Models.ShopRepair", b => + { + b.HasOne("CarRepairShopDatabaseImplement.Models.Repair", "Repair") + .WithMany("ShopRepairs") + .HasForeignKey("RepairId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("CarRepairShopDatabaseImplement.Models.Shop", "Shop") + .WithMany("Repairs") + .HasForeignKey("ShopId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Repair"); + + b.Navigation("Shop"); + }); + modelBuilder.Entity("CarRepairShopDatabaseImplement.Models.Component", b => { b.Navigation("RepairComponents"); @@ -164,6 +236,13 @@ namespace CarRepairShopDatabaseImplement.Migrations b.Navigation("Components"); b.Navigation("Orders"); + + b.Navigation("ShopRepairs"); + }); + + modelBuilder.Entity("CarRepairShopDatabaseImplement.Models.Shop", b => + { + b.Navigation("Repairs"); }); #pragma warning restore 612, 618 } diff --git a/CarRepairShop/CarRepairShopDatabaseImplement/Migrations/20240324163100_InitialCreate.cs b/CarRepairShop/CarRepairShopDatabaseImplement/Migrations/20240325165319_InitialCreate.cs similarity index 66% rename from CarRepairShop/CarRepairShopDatabaseImplement/Migrations/20240324163100_InitialCreate.cs rename to CarRepairShop/CarRepairShopDatabaseImplement/Migrations/20240325165319_InitialCreate.cs index fe70c1e..b0dad02 100644 --- a/CarRepairShop/CarRepairShopDatabaseImplement/Migrations/20240324163100_InitialCreate.cs +++ b/CarRepairShop/CarRepairShopDatabaseImplement/Migrations/20240325165319_InitialCreate.cs @@ -39,6 +39,22 @@ namespace CarRepairShopDatabaseImplement.Migrations table.PrimaryKey("PK_Repairs", x => x.Id); }); + migrationBuilder.CreateTable( + name: "Shops", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + ShopName = table.Column(type: "nvarchar(max)", nullable: false), + Address = table.Column(type: "nvarchar(max)", nullable: false), + DateOpen = table.Column(type: "datetime2", nullable: false), + MaxCapacity = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Shops", x => x.Id); + }); + migrationBuilder.CreateTable( name: "Orders", columns: table => new @@ -90,6 +106,33 @@ namespace CarRepairShopDatabaseImplement.Migrations onDelete: ReferentialAction.Cascade); }); + migrationBuilder.CreateTable( + name: "ShopRepairs", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + RepairId = 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_ShopRepairs", x => x.Id); + table.ForeignKey( + name: "FK_ShopRepairs_Repairs_RepairId", + column: x => x.RepairId, + principalTable: "Repairs", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_ShopRepairs_Shops_ShopId", + column: x => x.ShopId, + principalTable: "Shops", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + migrationBuilder.CreateIndex( name: "IX_Orders_RepairId", table: "Orders", @@ -104,6 +147,16 @@ namespace CarRepairShopDatabaseImplement.Migrations name: "IX_RepairComponents_RepairId", table: "RepairComponents", column: "RepairId"); + + migrationBuilder.CreateIndex( + name: "IX_ShopRepairs_RepairId", + table: "ShopRepairs", + column: "RepairId"); + + migrationBuilder.CreateIndex( + name: "IX_ShopRepairs_ShopId", + table: "ShopRepairs", + column: "ShopId"); } /// @@ -115,11 +168,17 @@ namespace CarRepairShopDatabaseImplement.Migrations migrationBuilder.DropTable( name: "RepairComponents"); + migrationBuilder.DropTable( + name: "ShopRepairs"); + migrationBuilder.DropTable( name: "Components"); migrationBuilder.DropTable( name: "Repairs"); + + migrationBuilder.DropTable( + name: "Shops"); } } } diff --git a/CarRepairShop/CarRepairShopDatabaseImplement/Migrations/RepairsShopDatabaseModelSnapshot.cs b/CarRepairShop/CarRepairShopDatabaseImplement/Migrations/RepairsShopDatabaseModelSnapshot.cs index e88cd6a..c81622a 100644 --- a/CarRepairShop/CarRepairShopDatabaseImplement/Migrations/RepairsShopDatabaseModelSnapshot.cs +++ b/CarRepairShop/CarRepairShopDatabaseImplement/Migrations/RepairsShopDatabaseModelSnapshot.cs @@ -121,6 +121,59 @@ namespace CarRepairShopDatabaseImplement.Migrations b.ToTable("RepairComponents"); }); + modelBuilder.Entity("CarRepairShopDatabaseImplement.Models.Shop", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Address") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("DateOpen") + .HasColumnType("datetime2"); + + b.Property("MaxCapacity") + .HasColumnType("int"); + + b.Property("ShopName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Shops"); + }); + + modelBuilder.Entity("CarRepairShopDatabaseImplement.Models.ShopRepair", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("RepairId") + .HasColumnType("int"); + + b.Property("ShopId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("RepairId"); + + b.HasIndex("ShopId"); + + b.ToTable("ShopRepairs"); + }); + modelBuilder.Entity("CarRepairShopDatabaseImplement.Models.Order", b => { b.HasOne("CarRepairShopDatabaseImplement.Models.Repair", "Repair") @@ -151,6 +204,25 @@ namespace CarRepairShopDatabaseImplement.Migrations b.Navigation("Repair"); }); + modelBuilder.Entity("CarRepairShopDatabaseImplement.Models.ShopRepair", b => + { + b.HasOne("CarRepairShopDatabaseImplement.Models.Repair", "Repair") + .WithMany("ShopRepairs") + .HasForeignKey("RepairId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("CarRepairShopDatabaseImplement.Models.Shop", "Shop") + .WithMany("Repairs") + .HasForeignKey("ShopId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Repair"); + + b.Navigation("Shop"); + }); + modelBuilder.Entity("CarRepairShopDatabaseImplement.Models.Component", b => { b.Navigation("RepairComponents"); @@ -161,6 +233,13 @@ namespace CarRepairShopDatabaseImplement.Migrations b.Navigation("Components"); b.Navigation("Orders"); + + b.Navigation("ShopRepairs"); + }); + + modelBuilder.Entity("CarRepairShopDatabaseImplement.Models.Shop", b => + { + b.Navigation("Repairs"); }); #pragma warning restore 612, 618 } diff --git a/CarRepairShop/CarRepairShopDatabaseImplement/Models/Repair.cs b/CarRepairShop/CarRepairShopDatabaseImplement/Models/Repair.cs index e979943..022fc21 100644 --- a/CarRepairShop/CarRepairShopDatabaseImplement/Models/Repair.cs +++ b/CarRepairShop/CarRepairShopDatabaseImplement/Models/Repair.cs @@ -32,6 +32,8 @@ namespace CarRepairShopDatabaseImplement.Models public virtual List Components { get; set; } = new(); [ForeignKey("RepairId")] public virtual List Orders { get; set; } = new(); + [ForeignKey("RepairId")] + public virtual List ShopRepairs { get; set; } = new(); public static Repair Create(RepairsShopDatabase context, RepairBindingModel model) { return new Repair() diff --git a/CarRepairShop/CarRepairShopDatabaseImplement/Models/Shop.cs b/CarRepairShop/CarRepairShopDatabaseImplement/Models/Shop.cs new file mode 100644 index 0000000..8ed8e30 --- /dev/null +++ b/CarRepairShop/CarRepairShopDatabaseImplement/Models/Shop.cs @@ -0,0 +1,111 @@ +using CarRepairShopContracts.BindingModels; +using CarRepairShopContracts.ViewModels; +using CarRepairShopDataModels; +using System.ComponentModel.DataAnnotations.Schema; +using System.ComponentModel.DataAnnotations; +using CarRepairShopDataModels.Models; + +namespace CarRepairShopDatabaseImplement.Models +{ + public class Shop : IShopModel + { + public int Id { get; private set; } + [Required] + public string ShopName { get; private set; } + [Required] + public string Address { get; private set; } + [Required] + public DateTime DateOpen { get; private set; } + [Required] + public int MaxCapacity { get; private set; } + private Dictionary? _shopRepairs = + null; + [NotMapped] + public Dictionary ShopRepairs + { + get + { + if (_shopRepairs == null) + { + _shopRepairs = Repairs + .ToDictionary(x => x.RepairId, x => + (x.Repair as IRepairModel, x.Count)); + } + return _shopRepairs; + } + } + [ForeignKey("ShopId")] + public virtual List Repairs { get; set; } = new(); + public static Shop? Create(RepairsShopDatabase context, ShopBindingModel model) + { + if (model == null) + return null; + return new Shop() + { + Id = model.Id, + ShopName = model.ShopName, + Address = model.Address, + DateOpen = model.DateOpen, + MaxCapacity = model.MaxCapacity, + Repairs = model.ShopRepairs.Select(x => new ShopRepair + { + Repair = context.Repairs.First(y => y.Id == x.Key), + Count = x.Value.Item2 + }).ToList() + }; + } + + public void Update(ShopBindingModel? model) + { + if (model == null) + { + return; + } + ShopName = model.ShopName; + Address = model.Address; + DateOpen = model.DateOpen; + MaxCapacity = model.MaxCapacity; + } + + public ShopViewModel GetViewModel => new() + { + Id = Id, + ShopName = ShopName, + Address = Address, + DateOpen = DateOpen, + ShopRepairs = ShopRepairs, + MaxCapacity = MaxCapacity + }; + + public void UpdateRepairs(RepairsShopDatabase context, ShopBindingModel model) + { + var shopRepairs = context.ShopRepairs.Where(rec => + rec.ShopId == model.Id).ToList(); + if (shopRepairs != null && shopRepairs.Count > 0) + { + context.ShopRepairs.RemoveRange(shopRepairs.Where(rec => !model.ShopRepairs.ContainsKey(rec.ShopId))); + + context.SaveChanges(); + foreach (var updateRepair in shopRepairs) + { + updateRepair.Count = + model.ShopRepairs[updateRepair.RepairId].Item2; + model.ShopRepairs.Remove(updateRepair.RepairId); + } + context.SaveChanges(); + } + var shop = context.Shops.First(x => x.Id == Id); + foreach (var pc in model.ShopRepairs) + { + context.ShopRepairs.Add(new ShopRepair + { + Shop = shop, + Repair = context.Repairs.First(x => x.Id == pc.Key), + Count = pc.Value.Item2 + }); + context.SaveChanges(); + } + _shopRepairs = null; + } + } +} diff --git a/CarRepairShop/CarRepairShopDatabaseImplement/Models/ShopRepair.cs b/CarRepairShop/CarRepairShopDatabaseImplement/Models/ShopRepair.cs new file mode 100644 index 0000000..c11c849 --- /dev/null +++ b/CarRepairShop/CarRepairShopDatabaseImplement/Models/ShopRepair.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CarRepairShopDatabaseImplement.Models +{ + public class ShopRepair + { + public int Id { get; set; } + [Required] + public int RepairId { get; set; } + [Required] + public int ShopId { get; set; } + [Required] + public int Count { get; set; } + public virtual Shop Shop { get; set; } = new(); + public virtual Repair Repair { get; set; } = new(); + } +} diff --git a/CarRepairShop/CarRepairShopDatabaseImplement/RepairsShopDatabase.cs b/CarRepairShop/CarRepairShopDatabaseImplement/RepairsShopDatabase.cs index 089eea5..a55d844 100644 --- a/CarRepairShop/CarRepairShopDatabaseImplement/RepairsShopDatabase.cs +++ b/CarRepairShop/CarRepairShopDatabaseImplement/RepairsShopDatabase.cs @@ -9,7 +9,7 @@ namespace CarRepairShopDatabaseImplement { if (optionsBuilder.IsConfigured == false) { - optionsBuilder.UseSqlServer(@"Data Source=localhost\SQLEXPRESS;Initial Catalog=RepairsShopDataBase;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True" + optionsBuilder.UseSqlServer(@"Data Source=localhost\SQLEXPRESS;Initial Catalog=RepairsShopDataBaseHard;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True" ); } base.OnConfiguring(optionsBuilder); @@ -18,5 +18,7 @@ namespace CarRepairShopDatabaseImplement public virtual DbSet Repairs { set; get; } public virtual DbSet RepairComponents { set; get; } public virtual DbSet Orders { set; get; } + public virtual DbSet Shops { set; get; } + public virtual DbSet ShopRepairs { set; get; } } } From 8f116075d8e882722516361efc38b3778638b797 Mon Sep 17 00:00:00 2001 From: Yunusov_Niyaz Date: Mon, 25 Mar 2024 22:06:48 +0400 Subject: [PATCH 3/5] =?UTF-8?q?=D0=93=D0=BE=D1=82=D0=BE=D0=B2=D0=BE2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...e.Designer.cs => 20240325180251_InitialCreate.Designer.cs} | 2 +- ...65319_InitialCreate.cs => 20240325180251_InitialCreate.cs} | 0 CarRepairShop/CarRepairShopDatabaseImplement/Models/Order.cs | 4 ++-- 3 files changed, 3 insertions(+), 3 deletions(-) rename CarRepairShop/CarRepairShopDatabaseImplement/Migrations/{20240325165319_InitialCreate.Designer.cs => 20240325180251_InitialCreate.Designer.cs} (99%) rename CarRepairShop/CarRepairShopDatabaseImplement/Migrations/{20240325165319_InitialCreate.cs => 20240325180251_InitialCreate.cs} (100%) diff --git a/CarRepairShop/CarRepairShopDatabaseImplement/Migrations/20240325165319_InitialCreate.Designer.cs b/CarRepairShop/CarRepairShopDatabaseImplement/Migrations/20240325180251_InitialCreate.Designer.cs similarity index 99% rename from CarRepairShop/CarRepairShopDatabaseImplement/Migrations/20240325165319_InitialCreate.Designer.cs rename to CarRepairShop/CarRepairShopDatabaseImplement/Migrations/20240325180251_InitialCreate.Designer.cs index a43096b..eb79454 100644 --- a/CarRepairShop/CarRepairShopDatabaseImplement/Migrations/20240325165319_InitialCreate.Designer.cs +++ b/CarRepairShop/CarRepairShopDatabaseImplement/Migrations/20240325180251_InitialCreate.Designer.cs @@ -12,7 +12,7 @@ using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace CarRepairShopDatabaseImplement.Migrations { [DbContext(typeof(RepairsShopDatabase))] - [Migration("20240325165319_InitialCreate")] + [Migration("20240325180251_InitialCreate")] partial class InitialCreate { /// diff --git a/CarRepairShop/CarRepairShopDatabaseImplement/Migrations/20240325165319_InitialCreate.cs b/CarRepairShop/CarRepairShopDatabaseImplement/Migrations/20240325180251_InitialCreate.cs similarity index 100% rename from CarRepairShop/CarRepairShopDatabaseImplement/Migrations/20240325165319_InitialCreate.cs rename to CarRepairShop/CarRepairShopDatabaseImplement/Migrations/20240325180251_InitialCreate.cs diff --git a/CarRepairShop/CarRepairShopDatabaseImplement/Models/Order.cs b/CarRepairShop/CarRepairShopDatabaseImplement/Models/Order.cs index 8a0e069..86c3047 100644 --- a/CarRepairShop/CarRepairShopDatabaseImplement/Models/Order.cs +++ b/CarRepairShop/CarRepairShopDatabaseImplement/Models/Order.cs @@ -19,7 +19,7 @@ namespace CarRepairShopDatabaseImplement.Models public DateTime? DateImplement { get; private set; } [Required] public int RepairId { get; private set; } - public virtual Repair Repair { get; set; } = new(); + public virtual Repair? Repair { get; set; } public static Order? Create(OrderBindingModel model) { @@ -48,7 +48,7 @@ namespace CarRepairShopDatabaseImplement.Models public OrderViewModel GetViewModel => new() { RepairId = RepairId, - RepairName = Repair.RepairName, + RepairName = Repair?.RepairName ?? string.Empty, Count = Count, Sum = Sum, Status = Status, From 93b92ab4b09947a30433fbfe4aa7f53ec772379c Mon Sep 17 00:00:00 2001 From: Yunusov_Niyaz Date: Wed, 27 Mar 2024 16:35:29 +0400 Subject: [PATCH 4/5] =?UTF-8?q?=D0=A1=D0=B4=D0=B0=D0=BD=D0=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../CarRepairShopDatabaseImplement/Implements/ShopStorage.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/CarRepairShop/CarRepairShopDatabaseImplement/Implements/ShopStorage.cs b/CarRepairShop/CarRepairShopDatabaseImplement/Implements/ShopStorage.cs index df9821b..2e9ae97 100644 --- a/CarRepairShop/CarRepairShopDatabaseImplement/Implements/ShopStorage.cs +++ b/CarRepairShop/CarRepairShopDatabaseImplement/Implements/ShopStorage.cs @@ -125,8 +125,7 @@ namespace CarRepairShopDatabaseImplement.Implements foreach (var el in context.ShopRepairs.Where(x => x.RepairId == model.Id)) { int dif = count; - if (el.Count < dif) - dif = el.Count; + if (el.Count < dif) dif = el.Count; el.Count -= dif; count -= dif; if (el.Count == 0) From cfe9ebfe99d333eba7022c9fc4afe2160fb4bc1e Mon Sep 17 00:00:00 2001 From: Yunusov_Niyaz Date: Sun, 31 Mar 2024 14:06:46 +0400 Subject: [PATCH 5/5] =?UTF-8?q?=D0=9F=D1=83=D0=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CarRepairShop/CarRepairShopDatabaseImplement/Models/Shop.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/CarRepairShop/CarRepairShopDatabaseImplement/Models/Shop.cs b/CarRepairShop/CarRepairShopDatabaseImplement/Models/Shop.cs index 8ed8e30..d93b6a9 100644 --- a/CarRepairShop/CarRepairShopDatabaseImplement/Models/Shop.cs +++ b/CarRepairShop/CarRepairShopDatabaseImplement/Models/Shop.cs @@ -18,8 +18,7 @@ namespace CarRepairShopDatabaseImplement.Models public DateTime DateOpen { get; private set; } [Required] public int MaxCapacity { get; private set; } - private Dictionary? _shopRepairs = - null; + private Dictionary? _shopRepairs = null; [NotMapped] public Dictionary ShopRepairs {