From 1a28ceccbf65bc6bfe8378d7f01e306f7bb03482 Mon Sep 17 00:00:00 2001 From: goldfest Date: Thu, 4 Apr 2024 23:08:20 +0400 Subject: [PATCH 1/5] =?UTF-8?q?=D0=BE=D1=82=D0=BF=D1=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../FormCreateSupply.Designer.cs | 143 +++++++++++ .../TravelCompany/FormCreateSupply.cs | 99 ++++++++ .../TravelCompany/FormCreateSupply.resx | 120 ++++++++++ .../TravelCompany/FormMain.Designer.cs | 44 +++- TravelCompany/TravelCompany/FormMain.cs | 27 +++ .../TravelCompany/FormSellTravels.Designer.cs | 124 ++++++++++ .../TravelCompany/FormSellTravels.cs | 88 +++++++ .../TravelCompany/FormSellTravels.resx | 120 ++++++++++ .../TravelCompany/FormShop.Designer.cs | 222 ++++++++++++++++++ TravelCompany/TravelCompany/FormShop.cs | 127 ++++++++++ TravelCompany/TravelCompany/FormShop.resx | 120 ++++++++++ .../TravelCompany/FormShops.Designer.cs | 130 ++++++++++ TravelCompany/TravelCompany/FormShops.cs | 117 +++++++++ TravelCompany/TravelCompany/FormShops.resx | 120 ++++++++++ TravelCompany/TravelCompany/Program.cs | 7 + .../BusinessLogic/ShopLogic.cs | 176 ++++++++++++++ .../BindingModels/ShopBindingModel.cs | 19 ++ .../BindingModels/SupplyBindingModel.cs | 16 ++ .../BusinessLogicsContracts/IShopLogic.cs | 22 ++ .../SearchModels/ShopSearchModel.cs | 14 ++ .../SearchModels/SupplySearchModel.cs | 14 ++ .../StoragesContracts/IShopStorage.cs | 23 ++ .../ViewModels/ShopViewModel.cs | 24 ++ .../Models/IShopModel.cs | 19 ++ .../Models/ISupplyModel.cs | 15 ++ .../Implements/ShopStorage.cs | 185 +++++++++++++++ ... 20240404185254_InitialCreate.Designer.cs} | 79 ++++++- ...ate.cs => 20240404185254_InitialCreate.cs} | 59 +++++ .../TravelCompanyDataBaseModelSnapshot.cs | 77 ++++++ .../Models/Shop.cs | 114 +++++++++ .../Models/ShopTravels.cs | 22 ++ .../Models/Travel.cs | 8 +- .../TravelCompanyDataBase.cs | 10 +- .../DataFileSingleton.cs | 4 + .../Implements/ShopStorage.cs | 154 ++++++++++++ .../TravelCompanyFileImplement/Models/Shop.cs | 111 +++++++++ .../DataListSingleton.cs | 3 + .../Implements/ShopStorage.cs | 123 ++++++++++ .../TravelCompanyListImplement/Models/Shop.cs | 59 +++++ 39 files changed, 2941 insertions(+), 17 deletions(-) create mode 100644 TravelCompany/TravelCompany/FormCreateSupply.Designer.cs create mode 100644 TravelCompany/TravelCompany/FormCreateSupply.cs create mode 100644 TravelCompany/TravelCompany/FormCreateSupply.resx create mode 100644 TravelCompany/TravelCompany/FormSellTravels.Designer.cs create mode 100644 TravelCompany/TravelCompany/FormSellTravels.cs create mode 100644 TravelCompany/TravelCompany/FormSellTravels.resx create mode 100644 TravelCompany/TravelCompany/FormShop.Designer.cs create mode 100644 TravelCompany/TravelCompany/FormShop.cs create mode 100644 TravelCompany/TravelCompany/FormShop.resx create mode 100644 TravelCompany/TravelCompany/FormShops.Designer.cs create mode 100644 TravelCompany/TravelCompany/FormShops.cs create mode 100644 TravelCompany/TravelCompany/FormShops.resx create mode 100644 TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/ShopLogic.cs create mode 100644 TravelCompany/TravelCompanyContracts/BindingModels/ShopBindingModel.cs create mode 100644 TravelCompany/TravelCompanyContracts/BindingModels/SupplyBindingModel.cs create mode 100644 TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IShopLogic.cs create mode 100644 TravelCompany/TravelCompanyContracts/SearchModels/ShopSearchModel.cs create mode 100644 TravelCompany/TravelCompanyContracts/SearchModels/SupplySearchModel.cs create mode 100644 TravelCompany/TravelCompanyContracts/StoragesContracts/IShopStorage.cs create mode 100644 TravelCompany/TravelCompanyContracts/ViewModels/ShopViewModel.cs create mode 100644 TravelCompany/TravelCompanyDataModels/Models/IShopModel.cs create mode 100644 TravelCompany/TravelCompanyDataModels/Models/ISupplyModel.cs create mode 100644 TravelCompany/TravelCompanyDatabaseImplement/Implements/ShopStorage.cs rename TravelCompany/TravelCompanyDatabaseImplement/Migrations/{20240308202100_InitialCreate.Designer.cs => 20240404185254_InitialCreate.Designer.cs} (68%) rename TravelCompany/TravelCompanyDatabaseImplement/Migrations/{20240308202100_InitialCreate.cs => 20240404185254_InitialCreate.cs} (66%) create mode 100644 TravelCompany/TravelCompanyDatabaseImplement/Models/Shop.cs create mode 100644 TravelCompany/TravelCompanyDatabaseImplement/Models/ShopTravels.cs create mode 100644 TravelCompany/TravelCompanyFileImplement/Implements/ShopStorage.cs create mode 100644 TravelCompany/TravelCompanyFileImplement/Models/Shop.cs create mode 100644 TravelCompany/TravelCompanyListImplement/Implements/ShopStorage.cs create mode 100644 TravelCompany/TravelCompanyListImplement/Models/Shop.cs diff --git a/TravelCompany/TravelCompany/FormCreateSupply.Designer.cs b/TravelCompany/TravelCompany/FormCreateSupply.Designer.cs new file mode 100644 index 0000000..d7bebf1 --- /dev/null +++ b/TravelCompany/TravelCompany/FormCreateSupply.Designer.cs @@ -0,0 +1,143 @@ +namespace TravelCompany.Forms +{ + partial class FormCreateSupply + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.comboBoxShop = new System.Windows.Forms.ComboBox(); + this.labelShop = new System.Windows.Forms.Label(); + this.labelTravel = new System.Windows.Forms.Label(); + this.comboBoxTravel = new System.Windows.Forms.ComboBox(); + this.labelCount = new System.Windows.Forms.Label(); + this.textBoxCount = new System.Windows.Forms.TextBox(); + this.buttonCancel = new System.Windows.Forms.Button(); + this.buttonSave = new System.Windows.Forms.Button(); + this.SuspendLayout(); + // + // comboBoxShop + // + this.comboBoxShop.FormattingEnabled = true; + this.comboBoxShop.Location = new System.Drawing.Point(115, 12); + this.comboBoxShop.Name = "comboBoxShop"; + this.comboBoxShop.Size = new System.Drawing.Size(344, 28); + this.comboBoxShop.TabIndex = 0; + // + // labelShop + // + this.labelShop.AutoSize = true; + this.labelShop.Location = new System.Drawing.Point(12, 15); + this.labelShop.Name = "labelShop"; + this.labelShop.Size = new System.Drawing.Size(76, 20); + this.labelShop.TabIndex = 1; + this.labelShop.Text = "Магазин: "; + // + // labelTravel + // + this.labelTravel.AutoSize = true; + this.labelTravel.Location = new System.Drawing.Point(12, 49); + this.labelTravel.Name = "labelTravel"; + this.labelTravel.Size = new System.Drawing.Size(75, 20); + this.labelTravel.TabIndex = 2; + this.labelTravel.Text = "Изделие: "; + // + // comboBoxTravel + // + this.comboBoxTravel.FormattingEnabled = true; + this.comboBoxTravel.Location = new System.Drawing.Point(115, 46); + this.comboBoxTravel.Name = "comboBoxTravel"; + this.comboBoxTravel.Size = new System.Drawing.Size(344, 28); + this.comboBoxTravel.TabIndex = 3; + // + // labelCount + // + this.labelCount.AutoSize = true; + this.labelCount.Location = new System.Drawing.Point(12, 83); + this.labelCount.Name = "labelCount"; + this.labelCount.Size = new System.Drawing.Size(97, 20); + this.labelCount.TabIndex = 4; + this.labelCount.Text = "Количество: "; + // + // textBoxCount + // + this.textBoxCount.Location = new System.Drawing.Point(115, 80); + this.textBoxCount.Name = "textBoxCount"; + this.textBoxCount.Size = new System.Drawing.Size(344, 27); + this.textBoxCount.TabIndex = 5; + // + // buttonCancel + // + this.buttonCancel.Location = new System.Drawing.Point(300, 113); + this.buttonCancel.Name = "buttonCancel"; + this.buttonCancel.Size = new System.Drawing.Size(116, 39); + this.buttonCancel.TabIndex = 6; + this.buttonCancel.Text = "Отмена"; + this.buttonCancel.UseVisualStyleBackColor = true; + this.buttonCancel.Click += new System.EventHandler(this.ButtonCancel_Click); + // + // buttonSave + // + this.buttonSave.Location = new System.Drawing.Point(168, 113); + this.buttonSave.Name = "buttonSave"; + this.buttonSave.Size = new System.Drawing.Size(116, 39); + this.buttonSave.TabIndex = 7; + this.buttonSave.Text = "Сохранить"; + this.buttonSave.UseVisualStyleBackColor = true; + this.buttonSave.Click += new System.EventHandler(this.ButtonSave_Click); + // + // FormCreateSupply + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(471, 164); + this.Controls.Add(this.buttonSave); + this.Controls.Add(this.buttonCancel); + this.Controls.Add(this.textBoxCount); + this.Controls.Add(this.labelCount); + this.Controls.Add(this.comboBoxTravel); + this.Controls.Add(this.labelTravel); + this.Controls.Add(this.labelShop); + this.Controls.Add(this.comboBoxShop); + this.Name = "FormCreateSupply"; + this.Text = "Создание поставки"; + this.Load += new System.EventHandler(this.FormCreateSupply_Load); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private ComboBox comboBoxShop; + private Label labelShop; + private Label labelTravel; + private ComboBox comboBoxTravel; + private Label labelCount; + private TextBox textBoxCount; + private Button buttonCancel; + private Button buttonSave; + } +} \ No newline at end of file diff --git a/TravelCompany/TravelCompany/FormCreateSupply.cs b/TravelCompany/TravelCompany/FormCreateSupply.cs new file mode 100644 index 0000000..6ca4901 --- /dev/null +++ b/TravelCompany/TravelCompany/FormCreateSupply.cs @@ -0,0 +1,99 @@ +using Microsoft.Extensions.Logging; +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.BusinessLogicsContracts; +using TravelCompanyContracts.ViewModels; +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using static System.Windows.Forms.VisualStyles.VisualStyleElement; + +namespace TravelCompany.Forms +{ + public partial class FormCreateSupply : Form + { + private readonly ILogger _logger; + private readonly ITravelLogic _logicP; + private readonly IShopLogic _logicS; + private List _shopList = new List(); + private List _TravelList = new List(); + + public FormCreateSupply(ILogger logger, ITravelLogic logicP, IShopLogic logicS) + { + InitializeComponent(); + _logger = logger; + _logicP = logicP; + _logicS = logicS; + } + + private void FormCreateSupply_Load(object sender, EventArgs e) + { + _shopList = _logicS.ReadList(null); + _TravelList = _logicP.ReadList(null); + if (_shopList != null) + { + comboBoxShop.DisplayMember = "ShopName"; + comboBoxShop.ValueMember = "Id"; + comboBoxShop.DataSource = _shopList; + comboBoxShop.SelectedItem = null; + _logger.LogInformation("Загрузка магазинов для поставок"); + } + if (_TravelList != null) + { + comboBoxTravel.DisplayMember = "TravelName"; + comboBoxTravel.ValueMember = "Id"; + comboBoxTravel.DataSource = _TravelList; + comboBoxTravel.SelectedItem = null; + _logger.LogInformation("Загрузка путёвок для поставок"); + } + } + + private void ButtonSave_Click(object sender, EventArgs e) + { + if (comboBoxShop.SelectedValue == null) + { + MessageBox.Show("Выберите магазин", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (comboBoxTravel.SelectedValue == null) + { + MessageBox.Show("Выберите изделие", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Создание поставки"); + try + { + var operationResult = _logicS.MakeSupply(new SupplyBindingModel + { + ShopId = Convert.ToInt32(comboBoxShop.SelectedValue), + TravelId = Convert.ToInt32(comboBoxTravel.SelectedValue), + Count = Convert.ToInt32(textBoxCount.Text) + }); + if (!operationResult) + { + throw new Exception("Ошибка при создании поставки. Дополнительная информация в логах."); + } + MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + Close(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка создания поставки"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ButtonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } +} diff --git a/TravelCompany/TravelCompany/FormCreateSupply.resx b/TravelCompany/TravelCompany/FormCreateSupply.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/TravelCompany/TravelCompany/FormCreateSupply.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/TravelCompany/TravelCompany/FormMain.Designer.cs b/TravelCompany/TravelCompany/FormMain.Designer.cs index e2b8f72..5dc453b 100644 --- a/TravelCompany/TravelCompany/FormMain.Designer.cs +++ b/TravelCompany/TravelCompany/FormMain.Designer.cs @@ -39,6 +39,10 @@ buttonIssuedOrder = new Button(); buttonRef = new Button(); dataGridView = new DataGridView(); + магазиныToolStripMenuItem = new ToolStripMenuItem(); + operationToolStripMenuItem = new ToolStripMenuItem(); + transactionToolStripMenuItem = new ToolStripMenuItem(); + продажаToolStripMenuItem = new ToolStripMenuItem(); toolStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); SuspendLayout(); @@ -46,7 +50,7 @@ // toolStrip1 // toolStrip1.ImageScalingSize = new Size(20, 20); - toolStrip1.Items.AddRange(new ToolStripItem[] { toolStripDropDownButton1 }); + toolStrip1.Items.AddRange(new ToolStripItem[] { toolStripDropDownButton1, operationToolStripMenuItem }); toolStrip1.Location = new Point(0, 0); toolStrip1.Name = "toolStrip1"; toolStrip1.Size = new Size(969, 25); @@ -56,7 +60,7 @@ // toolStripDropDownButton1 // toolStripDropDownButton1.DisplayStyle = ToolStripItemDisplayStyle.Text; - toolStripDropDownButton1.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, ПутёвкиToolStripMenuItem }); + toolStripDropDownButton1.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, ПутёвкиToolStripMenuItem, магазиныToolStripMenuItem }); toolStripDropDownButton1.Image = (Image)resources.GetObject("toolStripDropDownButton1.Image"); toolStripDropDownButton1.ImageTransparentColor = Color.Magenta; toolStripDropDownButton1.Name = "toolStripDropDownButton1"; @@ -66,14 +70,14 @@ // компонентыToolStripMenuItem // компонентыToolStripMenuItem.Name = "компонентыToolStripMenuItem"; - компонентыToolStripMenuItem.Size = new Size(174, 22); + компонентыToolStripMenuItem.Size = new Size(180, 22); компонентыToolStripMenuItem.Text = "Компоненты"; компонентыToolStripMenuItem.Click += компонентыToolStripMenuItem_Click; // // ПутёвкиToolStripMenuItem // ПутёвкиToolStripMenuItem.Name = "ПутёвкиToolStripMenuItem"; - ПутёвкиToolStripMenuItem.Size = new Size(174, 22); + ПутёвкиToolStripMenuItem.Size = new Size(180, 22); ПутёвкиToolStripMenuItem.Text = "Туристич. путёвки"; ПутёвкиToolStripMenuItem.Click += консервыToolStripMenuItem_Click; // @@ -139,6 +143,34 @@ dataGridView.Size = new Size(763, 435); dataGridView.TabIndex = 6; // + // магазиныToolStripMenuItem + // + магазиныToolStripMenuItem.Name = "магазиныToolStripMenuItem"; + магазиныToolStripMenuItem.Size = new Size(180, 22); + магазиныToolStripMenuItem.Text = "Магазины"; + магазиныToolStripMenuItem.Click += shopsToolStripMenuItem_Click; + // + // operationToolStripMenuItem + // + operationToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { transactionToolStripMenuItem, продажаToolStripMenuItem }); + operationToolStripMenuItem.Name = "operationToolStripMenuItem"; + operationToolStripMenuItem.Size = new Size(75, 25); + operationToolStripMenuItem.Text = "Операции"; + // + // transactionToolStripMenuItem + // + transactionToolStripMenuItem.Name = "transactionToolStripMenuItem"; + transactionToolStripMenuItem.Size = new Size(180, 22); + transactionToolStripMenuItem.Text = "Поставка"; + transactionToolStripMenuItem.Click += transactionToolStripMenuItem_Click; + // + // продажаToolStripMenuItem + // + продажаToolStripMenuItem.Name = "продажаToolStripMenuItem"; + продажаToolStripMenuItem.Size = new Size(180, 22); + продажаToolStripMenuItem.Text = "Продажа"; + продажаToolStripMenuItem.Click += SellToolStripMenuItem_Click; + // // FormMain // AutoScaleDimensions = new SizeF(7F, 15F); @@ -173,5 +205,9 @@ private ToolStripDropDownButton toolStripDropDownButton1; private ToolStripMenuItem компонентыToolStripMenuItem; private ToolStripMenuItem ПутёвкиToolStripMenuItem; + private ToolStripMenuItem магазиныToolStripMenuItem; + private ToolStripMenuItem operationToolStripMenuItem; + private ToolStripMenuItem transactionToolStripMenuItem; + private ToolStripMenuItem продажаToolStripMenuItem; } } \ No newline at end of file diff --git a/TravelCompany/TravelCompany/FormMain.cs b/TravelCompany/TravelCompany/FormMain.cs index d25b396..db25bef 100644 --- a/TravelCompany/TravelCompany/FormMain.cs +++ b/TravelCompany/TravelCompany/FormMain.cs @@ -151,5 +151,32 @@ namespace TravelCompany.Forms { LoadData(); } + + private void shopsToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormShops)); + if (service is FormShops form) + { + form.ShowDialog(); + } + } + + private void transactionToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormCreateSupply)); + if (service is FormCreateSupply form) + { + form.ShowDialog(); + } + } + + private void SellToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormSellTravels)); + if (service is FormSellTravels form) + { + form.ShowDialog(); + } + } } } diff --git a/TravelCompany/TravelCompany/FormSellTravels.Designer.cs b/TravelCompany/TravelCompany/FormSellTravels.Designer.cs new file mode 100644 index 0000000..17577cf --- /dev/null +++ b/TravelCompany/TravelCompany/FormSellTravels.Designer.cs @@ -0,0 +1,124 @@ +namespace TravelCompany.Forms +{ + partial class FormSellTravels + { + /// + /// 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() + { + labelTravel = new Label(); + comboBoxTravel = new ComboBox(); + labelCount = new Label(); + textBoxCount = new TextBox(); + buttonSell = new Button(); + buttonCancel = new Button(); + SuspendLayout(); + // + // labelTravel + // + labelTravel.AutoSize = true; + labelTravel.Location = new Point(10, 10); + labelTravel.Name = "labelTravel"; + labelTravel.Size = new Size(57, 15); + labelTravel.TabIndex = 0; + labelTravel.Text = "Путёвка: "; + // + // comboBoxTravel + // + comboBoxTravel.FormattingEnabled = true; + comboBoxTravel.Location = new Point(101, 8); + comboBoxTravel.Margin = new Padding(3, 2, 3, 2); + comboBoxTravel.Name = "comboBoxTravel"; + comboBoxTravel.Size = new Size(210, 23); + comboBoxTravel.TabIndex = 1; + // + // labelCount + // + labelCount.AutoSize = true; + labelCount.Location = new Point(10, 41); + labelCount.Name = "labelCount"; + labelCount.Size = new Size(78, 15); + labelCount.TabIndex = 2; + labelCount.Text = "Количество: "; + // + // textBoxCount + // + textBoxCount.Location = new Point(101, 39); + textBoxCount.Margin = new Padding(3, 2, 3, 2); + textBoxCount.Name = "textBoxCount"; + textBoxCount.Size = new Size(210, 23); + textBoxCount.TabIndex = 3; + // + // buttonSell + // + buttonSell.Location = new Point(112, 74); + buttonSell.Margin = new Padding(3, 2, 3, 2); + buttonSell.Name = "buttonSell"; + buttonSell.Size = new Size(82, 22); + buttonSell.TabIndex = 4; + buttonSell.Text = "Продать"; + buttonSell.UseVisualStyleBackColor = true; + buttonSell.Click += ButtonSell_Click; + // + // buttonCancel + // + buttonCancel.Location = new Point(212, 74); + buttonCancel.Margin = new Padding(3, 2, 3, 2); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(82, 22); + buttonCancel.TabIndex = 5; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += ButtonCancel_Click; + // + // FormSellTravels + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(320, 105); + Controls.Add(buttonCancel); + Controls.Add(buttonSell); + Controls.Add(textBoxCount); + Controls.Add(labelCount); + Controls.Add(comboBoxTravel); + Controls.Add(labelTravel); + Margin = new Padding(3, 2, 3, 2); + Name = "FormSellTravels"; + Text = "Продажа путёвок"; + Load += FormSellingTravel_Load; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Label labelTravel; + private ComboBox comboBoxTravel; + private Label labelCount; + private TextBox textBoxCount; + private Button buttonSell; + private Button buttonCancel; + } +} \ No newline at end of file diff --git a/TravelCompany/TravelCompany/FormSellTravels.cs b/TravelCompany/TravelCompany/FormSellTravels.cs new file mode 100644 index 0000000..84128c5 --- /dev/null +++ b/TravelCompany/TravelCompany/FormSellTravels.cs @@ -0,0 +1,88 @@ +using Microsoft.Extensions.Logging; +using TravelCompanyContracts.BusinessLogicsContracts; +using TravelCompanyContracts.SearchModels; +using TravelCompanyContracts.StoragesContracts; +using TravelCompanyContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace TravelCompany.Forms +{ + public partial class FormSellTravels : Form + { + private readonly ILogger _logger; + private readonly ITravelLogic _logicP; + private readonly IShopLogic _logicS; + private List _TravelList = new List(); + + public FormSellTravels(ILogger logger, ITravelLogic logicP, IShopLogic logicS) + { + InitializeComponent(); + _logger = logger; + _logicP = logicP; + _logicS = logicS; + } + + private void FormSellingTravel_Load(object sender, EventArgs e) + { + _TravelList = _logicP.ReadList(null); + if (_TravelList != null) + { + comboBoxTravel.DisplayMember = "TravelName"; + comboBoxTravel.ValueMember = "Id"; + comboBoxTravel.DataSource = _TravelList; + comboBoxTravel.SelectedItem = null; + _logger.LogInformation("Загрузка путёвок для продажи"); + } + } + + private void ButtonSell_Click(object sender, EventArgs e) + { + if (comboBoxTravel.SelectedValue == null) + { + MessageBox.Show("Выберите пиццу", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Создание покупки"); + try + { + bool resout = _logicS.Sale(new SupplySearchModel + { + TravelId = Convert.ToInt32(comboBoxTravel.SelectedValue), + Count = Convert.ToInt32(textBoxCount.Text) + }); + if (resout) + { + _logger.LogInformation("Проверка пройдена, продажа проведена"); + MessageBox.Show("Продажа проведена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + Close(); + } + else + { + _logger.LogInformation("Проверка не пройдена"); + MessageBox.Show("Продажа не может быть создана.", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Warning); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка создания покупки"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + + } + + private void ButtonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } +} \ No newline at end of file diff --git a/TravelCompany/TravelCompany/FormSellTravels.resx b/TravelCompany/TravelCompany/FormSellTravels.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/TravelCompany/TravelCompany/FormSellTravels.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/TravelCompany/TravelCompany/FormShop.Designer.cs b/TravelCompany/TravelCompany/FormShop.Designer.cs new file mode 100644 index 0000000..3321d32 --- /dev/null +++ b/TravelCompany/TravelCompany/FormShop.Designer.cs @@ -0,0 +1,222 @@ +namespace TravelCompany.Forms +{ + partial class FormShop + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.labelName = new System.Windows.Forms.Label(); + this.textBoxName = new System.Windows.Forms.TextBox(); + this.textBoxAdress = new System.Windows.Forms.TextBox(); + this.labelAdress = new System.Windows.Forms.Label(); + this.buttonCancel = new System.Windows.Forms.Button(); + this.buttonSave = new System.Windows.Forms.Button(); + this.dataGridView = new System.Windows.Forms.DataGridView(); + this.id = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.TravelName = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.Count = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.label1 = new System.Windows.Forms.Label(); + this.dateTimeOpen = new System.Windows.Forms.DateTimePicker(); + this.label2 = new System.Windows.Forms.Label(); + this.numericUpTravelMaxCount = new System.Windows.Forms.NumericUpDown(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.numericUpTravelMaxCount)).BeginInit(); + this.SuspendLayout(); + // + // labelName + // + this.labelName.AutoSize = true; + this.labelName.Location = new System.Drawing.Point(11, 15); + this.labelName.Name = "labelName"; + this.labelName.Size = new System.Drawing.Size(84, 20); + this.labelName.TabIndex = 0; + this.labelName.Text = "Название: "; + // + // textBoxName + // + this.textBoxName.Location = new System.Drawing.Point(102, 12); + this.textBoxName.Name = "textBoxName"; + this.textBoxName.Size = new System.Drawing.Size(276, 27); + this.textBoxName.TabIndex = 1; + // + // textBoxAdress + // + this.textBoxAdress.Location = new System.Drawing.Point(102, 59); + this.textBoxAdress.Name = "textBoxAdress"; + this.textBoxAdress.Size = new System.Drawing.Size(427, 27); + this.textBoxAdress.TabIndex = 3; + // + // labelAdress + // + this.labelAdress.AutoSize = true; + this.labelAdress.Location = new System.Drawing.Point(11, 61); + this.labelAdress.Name = "labelAdress"; + this.labelAdress.Size = new System.Drawing.Size(58, 20); + this.labelAdress.TabIndex = 2; + this.labelAdress.Text = "Адрес: "; + // + // buttonCancel + // + this.buttonCancel.Location = new System.Drawing.Point(451, 457); + this.buttonCancel.Name = "buttonCancel"; + this.buttonCancel.Size = new System.Drawing.Size(130, 44); + this.buttonCancel.TabIndex = 5; + this.buttonCancel.Text = "Отмена"; + this.buttonCancel.UseVisualStyleBackColor = true; + this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click); + // + // buttonSave + // + this.buttonSave.Location = new System.Drawing.Point(315, 457); + this.buttonSave.Name = "buttonSave"; + this.buttonSave.Size = new System.Drawing.Size(130, 44); + this.buttonSave.TabIndex = 6; + this.buttonSave.Text = "Сохранить"; + this.buttonSave.UseVisualStyleBackColor = true; + this.buttonSave.Click += new System.EventHandler(this.buttonSave_Click); + // + // dataGridView + // + this.dataGridView.AllowUserToAddRows = false; + this.dataGridView.AllowUserToDeleteRows = false; + this.dataGridView.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill; + this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { + this.id, + this.TravelName, + this.Count}); + this.dataGridView.Location = new System.Drawing.Point(12, 185); + this.dataGridView.Name = "dataGridView"; + this.dataGridView.ReadOnly = true; + this.dataGridView.RowHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.None; + this.dataGridView.RowHeadersWidthSizeMode = System.Windows.Forms.DataGridViewRowHeadersWidthSizeMode.AutoSizeToDisplayedHeaders; + this.dataGridView.RowTemplate.Height = 29; + this.dataGridView.Size = new System.Drawing.Size(569, 266); + this.dataGridView.TabIndex = 7; + // + // id + // + this.id.HeaderText = "id"; + this.id.MinimumWidth = 6; + this.id.Name = "id"; + this.id.ReadOnly = true; + this.id.Visible = false; + // + // TravelName + // + this.TravelName.HeaderText = "Пицца"; + this.TravelName.MinimumWidth = 6; + this.TravelName.Name = "TravelName"; + this.TravelName.ReadOnly = true; + // + // Count + // + this.Count.HeaderText = "Количество"; + this.Count.MinimumWidth = 6; + this.Count.Name = "Count"; + this.Count.ReadOnly = true; + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(12, 103); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(110, 20); + this.label1.TabIndex = 8; + this.label1.Text = "Дата открытия"; + // + // dateTimeOpen + // + this.dateTimeOpen.Location = new System.Drawing.Point(128, 103); + this.dateTimeOpen.Name = "dateTimeOpen"; + this.dateTimeOpen.Size = new System.Drawing.Size(401, 27); + this.dateTimeOpen.TabIndex = 9; + // + // label2 + // + this.label2.AutoSize = true; + this.label2.Location = new System.Drawing.Point(12, 148); + this.label2.Name = "label2"; + this.label2.Size = new System.Drawing.Size(100, 20); + this.label2.TabIndex = 10; + this.label2.Text = "Вместимость"; + // + // numericUpTravelMaxCount + // + this.numericUpTravelMaxCount.Location = new System.Drawing.Point(128, 146); + this.numericUpTravelMaxCount.Maximum = new decimal(new int[] { + 10000, + 0, + 0, + 0}); + this.numericUpTravelMaxCount.Name = "numericUpTravelMaxCount"; + this.numericUpTravelMaxCount.Size = new System.Drawing.Size(401, 27); + this.numericUpTravelMaxCount.TabIndex = 11; + // + // FormShop + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(593, 513); + this.Controls.Add(this.numericUpTravelMaxCount); + this.Controls.Add(this.label2); + this.Controls.Add(this.dateTimeOpen); + this.Controls.Add(this.label1); + this.Controls.Add(this.dataGridView); + this.Controls.Add(this.buttonSave); + this.Controls.Add(this.buttonCancel); + this.Controls.Add(this.textBoxAdress); + this.Controls.Add(this.labelAdress); + this.Controls.Add(this.textBoxName); + this.Controls.Add(this.labelName); + this.Name = "FormShop"; + this.Text = "Магазин"; + this.Load += new System.EventHandler(this.FormShop_Load); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.numericUpTravelMaxCount)).EndInit(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private Label labelName; + private TextBox textBoxName; + private TextBox textBoxAdress; + private Label labelAdress; + private Button buttonCancel; + private Button buttonSave; + private DataGridView dataGridView; + private DataGridViewTextBoxColumn id; + private DataGridViewTextBoxColumn TravelName; + private DataGridViewTextBoxColumn Count; + private Label label1; + private DateTimePicker dateTimeOpen; + private Label label2; + private NumericUpDown numericUpTravelMaxCount; + } +} \ No newline at end of file diff --git a/TravelCompany/TravelCompany/FormShop.cs b/TravelCompany/TravelCompany/FormShop.cs new file mode 100644 index 0000000..e177fe6 --- /dev/null +++ b/TravelCompany/TravelCompany/FormShop.cs @@ -0,0 +1,127 @@ +using TravelCompanyDataModels.Models; +using Microsoft.Extensions.Logging; +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.BusinessLogicsContracts; +using TravelCompanyContracts.SearchModels; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace TravelCompany.Forms +{ + public partial class FormShop : Form + { + private readonly ILogger _logger; + private readonly IShopLogic _logic; + private int? _id; + public int Id { set { _id = value; } } + private Dictionary _ShopTravels; + private DateTime? _openingDate = null; + public FormShop(ILogger logger, IShopLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + _ShopTravels = new Dictionary(); + } + private void FormShop_Load(object sender, EventArgs e) + { + if (_id.HasValue) + { + _logger.LogInformation("Загрузка магазина"); + try + { + var view = _logic.ReadElement(new ShopSearchModel + { + Id = _id.Value + }); + if (view != null) + { + textBoxName.Text = view.ShopName; + textBoxAdress.Text = view.Adress; + dateTimeOpen.Value = view.OpeningDate; + numericUpTravelMaxCount.Value = view.TravelMaxCount; + _ShopTravels = view.ShopTravels ?? new Dictionary(); + LoadData(); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки магазина"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + + private void LoadData() + { + _logger.LogInformation("Загрузка изделий в магазине"); + try + { + if (_ShopTravels != null) + { + dataGridView.Rows.Clear(); + foreach (var sr in _ShopTravels) + { + dataGridView.Rows.Add(new object[] { sr.Key, sr.Value.Item1.TravelName, sr.Value.Item2 }); + } + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки изделий магазина"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void buttonSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxName.Text)) + { + MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (string.IsNullOrEmpty(textBoxAdress.Text)) + { + MessageBox.Show("Заполните адрес", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Сохранение магазина"); + try + { + var model = new ShopBindingModel + { + Id = _id ?? 0, + ShopName = textBoxName.Text, + Adress = textBoxAdress.Text, + OpeningDate = dateTimeOpen.Value, + TravelMaxCount = (int)numericUpTravelMaxCount.Value + }; + var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + Close(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка сохранения магазина"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + private void buttonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } +} diff --git a/TravelCompany/TravelCompany/FormShop.resx b/TravelCompany/TravelCompany/FormShop.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/TravelCompany/TravelCompany/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/TravelCompany/TravelCompany/FormShops.Designer.cs b/TravelCompany/TravelCompany/FormShops.Designer.cs new file mode 100644 index 0000000..ddcc07f --- /dev/null +++ b/TravelCompany/TravelCompany/FormShops.Designer.cs @@ -0,0 +1,130 @@ +namespace TravelCompany.Forms +{ + partial class FormShops + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.ToolsPanel = new System.Windows.Forms.Panel(); + this.buttonRef = new System.Windows.Forms.Button(); + this.buttonDel = new System.Windows.Forms.Button(); + this.buttonUpd = new System.Windows.Forms.Button(); + this.buttonAdd = new System.Windows.Forms.Button(); + this.dataGridView = new System.Windows.Forms.DataGridView(); + this.ToolsPanel.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); + this.SuspendLayout(); + // + // ToolsPanel + // + this.ToolsPanel.Controls.Add(this.buttonRef); + this.ToolsPanel.Controls.Add(this.buttonDel); + this.ToolsPanel.Controls.Add(this.buttonUpd); + this.ToolsPanel.Controls.Add(this.buttonAdd); + this.ToolsPanel.Location = new System.Drawing.Point(608, 12); + this.ToolsPanel.Name = "ToolsPanel"; + this.ToolsPanel.Size = new System.Drawing.Size(180, 426); + this.ToolsPanel.TabIndex = 3; + // + // buttonRef + // + this.buttonRef.Location = new System.Drawing.Point(31, 206); + this.buttonRef.Name = "buttonRef"; + this.buttonRef.Size = new System.Drawing.Size(126, 36); + this.buttonRef.TabIndex = 3; + this.buttonRef.Text = "Обновить"; + this.buttonRef.UseVisualStyleBackColor = true; + this.buttonRef.Click += new System.EventHandler(this.ButtonRef_Click); + // + // buttonDel + // + this.buttonDel.Location = new System.Drawing.Point(31, 142); + this.buttonDel.Name = "buttonDel"; + this.buttonDel.Size = new System.Drawing.Size(126, 36); + this.buttonDel.TabIndex = 2; + this.buttonDel.Text = "Удалить"; + this.buttonDel.UseVisualStyleBackColor = true; + this.buttonDel.Click += new System.EventHandler(this.ButtonDel_Click); + // + // buttonUpd + // + this.buttonUpd.Location = new System.Drawing.Point(31, 76); + this.buttonUpd.Name = "buttonUpd"; + this.buttonUpd.Size = new System.Drawing.Size(126, 36); + this.buttonUpd.TabIndex = 1; + this.buttonUpd.Text = "Изменить"; + this.buttonUpd.UseVisualStyleBackColor = true; + this.buttonUpd.Click += new System.EventHandler(this.ButtonUpd_Click); + // + // buttonAdd + // + this.buttonAdd.Location = new System.Drawing.Point(31, 16); + this.buttonAdd.Name = "buttonAdd"; + this.buttonAdd.Size = new System.Drawing.Size(126, 36); + this.buttonAdd.TabIndex = 0; + this.buttonAdd.Text = "Добавить"; + this.buttonAdd.UseVisualStyleBackColor = true; + this.buttonAdd.Click += new System.EventHandler(this.ButtonAdd_Click); + // + // dataGridView + // + this.dataGridView.AllowUserToAddRows = false; + this.dataGridView.AllowUserToDeleteRows = false; + this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView.Location = new System.Drawing.Point(12, 12); + this.dataGridView.Name = "dataGridView"; + this.dataGridView.ReadOnly = true; + this.dataGridView.RowHeadersWidth = 51; + this.dataGridView.RowTemplate.Height = 29; + this.dataGridView.Size = new System.Drawing.Size(590, 426); + this.dataGridView.TabIndex = 2; + // + // FormShops + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 450); + this.Controls.Add(this.ToolsPanel); + this.Controls.Add(this.dataGridView); + this.Name = "FormShops"; + this.Text = "Магазины"; + this.Load += new System.EventHandler(this.FormShops_Load); + this.ToolsPanel.ResumeLayout(false); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit(); + this.ResumeLayout(false); + + } + + #endregion + + private Panel ToolsPanel; + private Button buttonRef; + private Button buttonDel; + private Button buttonUpd; + private Button buttonAdd; + private DataGridView dataGridView; + } +} \ No newline at end of file diff --git a/TravelCompany/TravelCompany/FormShops.cs b/TravelCompany/TravelCompany/FormShops.cs new file mode 100644 index 0000000..14dc763 --- /dev/null +++ b/TravelCompany/TravelCompany/FormShops.cs @@ -0,0 +1,117 @@ +using Microsoft.Extensions.Logging; +using TravelCompany; +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.BusinessLogicsContracts; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace TravelCompany.Forms +{ + public partial class FormShops : Form + { + private readonly ILogger _logger; + private readonly IShopLogic _logic; + + public FormShops(ILogger logger, IShopLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + private void FormShops_Load(object sender, EventArgs e) + { + LoadData(); + } + + private void LoadData() + { + try + { + var list = _logic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["Id"].Visible = false; + dataGridView.Columns["ShopTravels"].Visible = false; + dataGridView.Columns["ShopName"].AutoSizeMode = + DataGridViewAutoSizeColumnMode.Fill; + } + _logger.LogInformation("Загрузка магазинов"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки магазинов"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ButtonAdd_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormShop)); + if (service is FormShop form) + { + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + + private void ButtonUpd_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + var service = Program.ServiceProvider?.GetService(typeof(FormShop)); + if (service is FormShop form) + { + form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + } + + private void ButtonDel_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Удаление магазина"); + try + { + if (!_logic.Delete(new ShopBindingModel + { + Id = id + })) + { + throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка удаления магазина"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } + + private void ButtonRef_Click(object sender, EventArgs e) + { + LoadData(); + } + } +} diff --git a/TravelCompany/TravelCompany/FormShops.resx b/TravelCompany/TravelCompany/FormShops.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/TravelCompany/TravelCompany/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/TravelCompany/TravelCompany/Program.cs b/TravelCompany/TravelCompany/Program.cs index 3419d03..e38627f 100644 --- a/TravelCompany/TravelCompany/Program.cs +++ b/TravelCompany/TravelCompany/Program.cs @@ -5,6 +5,7 @@ using TravelCompanyDatabaseImplement.Implements; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; +using TravelCompanyBusinessLogic.BusinessLogics; namespace TravelCompany.Forms @@ -50,6 +51,12 @@ namespace TravelCompany.Forms services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); } } } \ No newline at end of file diff --git a/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/ShopLogic.cs b/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/ShopLogic.cs new file mode 100644 index 0000000..82e6c71 --- /dev/null +++ b/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/ShopLogic.cs @@ -0,0 +1,176 @@ +using Microsoft.Extensions.Logging; +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.BusinessLogicsContracts; +using TravelCompanyContracts.SearchModels; +using TravelCompanyContracts.StoragesContracts; +using TravelCompanyContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TravelCompanyBusinessLogic.BusinessLogics +{ + public class ShopLogic : IShopLogic + { + private readonly ILogger _logger; + private readonly IShopStorage _shopStorage; + private readonly ITravelStorage _TravelStorage; + + public ShopLogic(ILogger logger, IShopStorage shopStorage, ITravelStorage TravelStorage) + { + _logger = logger; + _shopStorage = shopStorage; + _TravelStorage = TravelStorage; + } + + public List? ReadList(ShopSearchModel? model) + { + _logger.LogInformation("ReadList. ShopName:{ShopName}.Id:{ Id}", model?.ShopName, model?.Id); + var list = model == null ? _shopStorage.GetFullList() : _shopStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + _logger.LogInformation("ReadList. Count:{Count}", list.Count); + return list; + } + + public ShopViewModel? ReadElement(ShopSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + _logger.LogInformation("ReadElement. ShopName:{ShopName}.Id:{ Id}", model.ShopName, model.Id); + var element = _shopStorage.GetElement(model); + if (element == null) + { + _logger.LogWarning("ReadElement element not found"); + return null; + } + _logger.LogInformation("ReadElement find. Id:{Id}", element.Id); + return element; + } + + public bool Create(ShopBindingModel model) + { + CheckModel(model); + if (_shopStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } + + public bool Update(ShopBindingModel model) + { + CheckModel(model); + if (_shopStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + return true; + } + + public bool Delete(ShopBindingModel model) + { + CheckModel(model, false); + _logger.LogInformation("Delete. Id:{Id}", model.Id); + if (_shopStorage.Delete(model) == null) + { + _logger.LogWarning("Delete operation failed"); + return false; + } + return true; + } + + public bool MakeSupply(SupplyBindingModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (model.Count <= 0) + { + throw new ArgumentException("Количество изделий должно быть больше 0"); + } + var shop = _shopStorage.GetElement(new ShopSearchModel + { + Id = model.ShopId + }); + if (shop == null) + { + throw new ArgumentException("Магазина не существует"); + } + if (shop.ShopTravels.ContainsKey(model.TravelId)) + { + var oldValue = shop.ShopTravels[model.TravelId]; + oldValue.Item2 += model.Count; + shop.ShopTravels[model.TravelId] = oldValue; + } + else + { + var Travel = _TravelStorage.GetElement(new TravelSearchModel + { + Id = model.TravelId + }); + if (Travel == null) + { + throw new ArgumentException($"Поставка: Товар с id:{model.TravelId} не найденн"); + } + shop.ShopTravels.Add(model.TravelId, (Travel, model.Count)); + } + return true; + } + + private void CheckModel(ShopBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (!withParams) + { + return; + } + if (string.IsNullOrEmpty(model.Adress)) + { + throw new ArgumentException("Адрес магазина длжен быть заполнен", nameof(model.Adress)); + } + if (string.IsNullOrEmpty(model.ShopName)) + { + throw new ArgumentException("Название магазина должно быть заполнено", nameof(model.ShopName)); + } + _logger.LogInformation("Shop. ShopName:{ShopName}.Adres:{Adres}.OpeningDate:{OpeningDate}.Id:{ Id}", model.ShopName, model.Adress, model.OpeningDate, model.Id); + var element = _shopStorage.GetElement(new ShopSearchModel + { + ShopName = model.ShopName + }); + if (element != null && element.Id != model.Id) + { + throw new InvalidOperationException("Магазин с таким названием уже есть"); + } + } + + public bool Sale(SupplySearchModel model) + { + if (!model.TravelId.HasValue || !model.Count.HasValue) + { + return false; + } + _logger.LogInformation("Check Travel count in all shops"); + if (_shopStorage.Sale(model)) + { + _logger.LogInformation("Selling sucsess"); + return true; + } + _logger.LogInformation("Selling failed"); + return false; + } + } +} diff --git a/TravelCompany/TravelCompanyContracts/BindingModels/ShopBindingModel.cs b/TravelCompany/TravelCompanyContracts/BindingModels/ShopBindingModel.cs new file mode 100644 index 0000000..81615fa --- /dev/null +++ b/TravelCompany/TravelCompanyContracts/BindingModels/ShopBindingModel.cs @@ -0,0 +1,19 @@ +using TravelCompanyDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TravelCompanyContracts.BindingModels +{ + public class ShopBindingModel : IShopModel + { + public int Id { get; set; } + public string ShopName { get; set; } = string.Empty; + public string Adress { get; set; } = string.Empty; + public DateTime OpeningDate { get; set; } = DateTime.Now; + public Dictionary ShopTravels { get; set; } = new(); + public int TravelMaxCount { get; set; } + } +} \ No newline at end of file diff --git a/TravelCompany/TravelCompanyContracts/BindingModels/SupplyBindingModel.cs b/TravelCompany/TravelCompanyContracts/BindingModels/SupplyBindingModel.cs new file mode 100644 index 0000000..52ff0c1 --- /dev/null +++ b/TravelCompany/TravelCompanyContracts/BindingModels/SupplyBindingModel.cs @@ -0,0 +1,16 @@ +using TravelCompanyDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TravelCompanyContracts.BindingModels +{ + public class SupplyBindingModel : ISupplyModel + { + public int ShopId { get; set; } + public int TravelId { get; set; } + public int Count { get; set; } + } +} \ No newline at end of file diff --git a/TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IShopLogic.cs b/TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IShopLogic.cs new file mode 100644 index 0000000..33b18cf --- /dev/null +++ b/TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IShopLogic.cs @@ -0,0 +1,22 @@ +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.SearchModels; +using TravelCompanyContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TravelCompanyContracts.BusinessLogicsContracts +{ + public interface IShopLogic + { + List? ReadList(ShopSearchModel? model); + ShopViewModel? ReadElement(ShopSearchModel model); + bool Create(ShopBindingModel model); + bool Update(ShopBindingModel model); + bool Delete(ShopBindingModel model); + bool MakeSupply(SupplyBindingModel model); + bool Sale(SupplySearchModel model); + } +} \ No newline at end of file diff --git a/TravelCompany/TravelCompanyContracts/SearchModels/ShopSearchModel.cs b/TravelCompany/TravelCompanyContracts/SearchModels/ShopSearchModel.cs new file mode 100644 index 0000000..61660af --- /dev/null +++ b/TravelCompany/TravelCompanyContracts/SearchModels/ShopSearchModel.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TravelCompanyContracts.SearchModels +{ + public class ShopSearchModel + { + public int? Id { get; set; } + public string? ShopName { get; set; } + } +} \ No newline at end of file diff --git a/TravelCompany/TravelCompanyContracts/SearchModels/SupplySearchModel.cs b/TravelCompany/TravelCompanyContracts/SearchModels/SupplySearchModel.cs new file mode 100644 index 0000000..5da7c58 --- /dev/null +++ b/TravelCompany/TravelCompanyContracts/SearchModels/SupplySearchModel.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TravelCompanyContracts.SearchModels +{ + public class SupplySearchModel + { + public int? TravelId { get; set; } + public int? Count { get; set; } + } +} \ No newline at end of file diff --git a/TravelCompany/TravelCompanyContracts/StoragesContracts/IShopStorage.cs b/TravelCompany/TravelCompanyContracts/StoragesContracts/IShopStorage.cs new file mode 100644 index 0000000..c8619c1 --- /dev/null +++ b/TravelCompany/TravelCompanyContracts/StoragesContracts/IShopStorage.cs @@ -0,0 +1,23 @@ +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.SearchModels; +using TravelCompanyContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TravelCompanyContracts.StoragesContracts +{ + public interface IShopStorage + { + List GetFullList(); + List GetFilteredList(ShopSearchModel model); + ShopViewModel? GetElement(ShopSearchModel model); + ShopViewModel? Insert(ShopBindingModel model); + ShopViewModel? Update(ShopBindingModel model); + ShopViewModel? Delete(ShopBindingModel model); + bool Sale(SupplySearchModel model); + bool RestockingShops(SupplyBindingModel model); + } +} \ No newline at end of file diff --git a/TravelCompany/TravelCompanyContracts/ViewModels/ShopViewModel.cs b/TravelCompany/TravelCompanyContracts/ViewModels/ShopViewModel.cs new file mode 100644 index 0000000..48a091a --- /dev/null +++ b/TravelCompany/TravelCompanyContracts/ViewModels/ShopViewModel.cs @@ -0,0 +1,24 @@ +using TravelCompanyDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TravelCompanyContracts.ViewModels +{ + public class ShopViewModel : IShopModel + { + public int Id { get; set; } + [DisplayName("Название")] + public string ShopName { get; set; } = string.Empty; + [DisplayName("Адрес")] + public string Adress { get; set; } = string.Empty; + [DisplayName("Дата открытия")] + public DateTime OpeningDate { get; set; } + public Dictionary ShopTravels { get; set; } = new(); + [DisplayName("Вместимость")] + public int TravelMaxCount { get; set; } + } +} \ No newline at end of file diff --git a/TravelCompany/TravelCompanyDataModels/Models/IShopModel.cs b/TravelCompany/TravelCompanyDataModels/Models/IShopModel.cs new file mode 100644 index 0000000..0e861aa --- /dev/null +++ b/TravelCompany/TravelCompanyDataModels/Models/IShopModel.cs @@ -0,0 +1,19 @@ +using TravelCompanyDataModels; +using TravelCompanyDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TravelCompanyDataModels.Models +{ + public interface IShopModel : IId + { + string ShopName { get; } + string Adress { get; } + DateTime OpeningDate { get; } + Dictionary ShopTravels { get; } + public int TravelMaxCount { get; } + } +} \ No newline at end of file diff --git a/TravelCompany/TravelCompanyDataModels/Models/ISupplyModel.cs b/TravelCompany/TravelCompanyDataModels/Models/ISupplyModel.cs new file mode 100644 index 0000000..907597a --- /dev/null +++ b/TravelCompany/TravelCompanyDataModels/Models/ISupplyModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TravelCompanyDataModels.Models +{ + public interface ISupplyModel + { + int ShopId { get; } + int TravelId { get; } + int Count { get; } + } +} \ No newline at end of file diff --git a/TravelCompany/TravelCompanyDatabaseImplement/Implements/ShopStorage.cs b/TravelCompany/TravelCompanyDatabaseImplement/Implements/ShopStorage.cs new file mode 100644 index 0000000..d9c636e --- /dev/null +++ b/TravelCompany/TravelCompanyDatabaseImplement/Implements/ShopStorage.cs @@ -0,0 +1,185 @@ +using Microsoft.EntityFrameworkCore; +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.SearchModels; +using TravelCompanyContracts.StoragesContracts; +using TravelCompanyContracts.ViewModels; +using TravelCompanyDatabaseImplement.Models; + +namespace TravelCompanyDatabaseImplement.Implements +{ + public class ShopStorage : IShopStorage + { + public List GetFullList() + { + using var context = new TravelCompanyDataBase(); + return context.Shops.Include(x => x.Travels).ThenInclude(x => x.Travel).ToList(). + Select(x => x.GetViewModel).ToList(); + } + + public List GetFilteredList(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.ShopName)) + { + return new(); + } + using var context = new TravelCompanyDataBase(); + return context.Shops.Include(x => x.Travels).ThenInclude(x => x.Travel).Where(x => x.ShopName.Contains(model.ShopName)). + ToList().Select(x => x.GetViewModel).ToList(); + } + + public ShopViewModel? GetElement(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.ShopName) && !model.Id.HasValue) + { + return new(); + } + using var context = new TravelCompanyDataBase(); + return context.Shops.Include(x => x.Travels).ThenInclude(x => x.Travel) + .FirstOrDefault(x => + (!string.IsNullOrEmpty(model.ShopName) && x.ShopName == model.ShopName) || + (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; + } + + public ShopViewModel? Insert(ShopBindingModel model) + { + using var context = new TravelCompanyDataBase(); + var newShop = Shop.Create(context, model); + if (newShop == null) + { + return null; + } + context.Shops.Add(newShop); + context.SaveChanges(); + return newShop.GetViewModel; + } + + public ShopViewModel? Update(ShopBindingModel model) + { + using var context = new TravelCompanyDataBase(); + using var transaction = context.Database.BeginTransaction(); + try + { + var shop = context.Shops.FirstOrDefault(x => x.Id == model.Id); + if (shop == null) + { + return null; + } + shop.Update(model); + context.SaveChanges(); + shop.UpdateTravels(context, model); + transaction.Commit(); + return shop.GetViewModel; + } + catch + { + transaction.Rollback(); + throw; + } + } + + public ShopViewModel? Delete(ShopBindingModel model) + { + using var context = new TravelCompanyDataBase(); + var shop = context.Shops.Include(x => x.Travels).FirstOrDefault(x => x.Id == model.Id); + if (shop != null) + { + context.Shops.Remove(shop); + context.SaveChanges(); + return shop.GetViewModel; + } + return null; + } + + public bool RestockingShops(SupplyBindingModel model) + { + using var context = new TravelCompanyDataBase(); + var transaction = context.Database.BeginTransaction(); + var Shops = context.Shops.Include(x => x.Travels).ThenInclude(x => x.Travel).ToList(). + Where(x => x.TravelMaxCount > x.ShopTravels.Select(x => x.Value.Item2).Sum()).ToList(); + if (model == null) + { + return false; + } + try + { + foreach (Shop shop in Shops) + { + int difference = shop.TravelMaxCount - shop.ShopTravels.Select(x => x.Value.Item2).Sum(); + int refill = Math.Min(difference, model.Count); + model.Count -= refill; + if (shop.ShopTravels.ContainsKey(model.TravelId)) + { + var datePair = shop.ShopTravels[model.TravelId]; + datePair.Item2 += refill; + shop.ShopTravels[model.TravelId] = datePair; + } + else + { + var Travel = context.Travels.First(x => x.Id == model.TravelId); + shop.ShopTravels.Add(model.TravelId, (Travel, refill)); + } + shop.TravelsDictionatyUpdate(context); + if (model.Count == 0) + { + transaction.Commit(); + return true; + } + } + transaction.Rollback(); + return false; + } + catch + { + transaction.Rollback(); + throw; + } + } + + public bool Sale(SupplySearchModel model) + { + using var context = new TravelCompanyDataBase(); + var transaction = context.Database.BeginTransaction(); + try + { + var shops = context.Shops.Include(x => x.Travels).ThenInclude(x => x.Travel).ToList(). + Where(x => x.ShopTravels.ContainsKey(model.TravelId.Value)).OrderByDescending(x => x.ShopTravels[model.TravelId.Value].Item2).ToList(); + + foreach (var shop in shops) + { + int residue = model.Count.Value - shop.ShopTravels[model.TravelId.Value].Item2; + if (residue > 0) + { + shop.ShopTravels.Remove(model.TravelId.Value); + shop.TravelsDictionatyUpdate(context); + context.SaveChanges(); + model.Count = residue; + + } + else + { + if (residue == 0) + shop.ShopTravels.Remove(model.TravelId.Value); + else + { + var dataPair = shop.ShopTravels[model.TravelId.Value]; + dataPair.Item2 = -residue; + shop.ShopTravels[model.TravelId.Value] = dataPair; + } + + shop.TravelsDictionatyUpdate(context); + transaction.Commit(); + return true; + } + } + transaction.Rollback(); + return false; + } + catch + { + transaction.Rollback(); + throw; + } + } + + } +} diff --git a/TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240308202100_InitialCreate.Designer.cs b/TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240404185254_InitialCreate.Designer.cs similarity index 68% rename from TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240308202100_InitialCreate.Designer.cs rename to TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240404185254_InitialCreate.Designer.cs index 5e4c3df..ec6cc53 100644 --- a/TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240308202100_InitialCreate.Designer.cs +++ b/TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240404185254_InitialCreate.Designer.cs @@ -12,7 +12,7 @@ using TravelCompanyDatabaseImplement; namespace TravelCompanyDatabaseImplement.Migrations { [DbContext(typeof(TravelCompanyDataBase))] - [Migration("20240308202100_InitialCreate")] + [Migration("20240404185254_InitialCreate")] partial class InitialCreate { /// @@ -78,6 +78,59 @@ namespace TravelCompanyDatabaseImplement.Migrations b.ToTable("Orders"); }); + modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.Shop", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Adress") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("OpeningDate") + .HasColumnType("datetime2"); + + b.Property("ShopName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("TravelMaxCount") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.ToTable("Shops"); + }); + + modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.ShopTravels", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("ShopId") + .HasColumnType("int"); + + b.Property("TravelId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ShopId"); + + b.HasIndex("TravelId"); + + b.ToTable("ShopTravels"); + }); + modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.Travel", b => { b.Property("Id") @@ -133,6 +186,25 @@ namespace TravelCompanyDatabaseImplement.Migrations .IsRequired(); }); + modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.ShopTravels", b => + { + b.HasOne("TravelCompanyDatabaseImplement.Models.Shop", "Shop") + .WithMany("Travels") + .HasForeignKey("ShopId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("TravelCompanyDatabaseImplement.Models.Travel", "Travel") + .WithMany() + .HasForeignKey("TravelId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Shop"); + + b.Navigation("Travel"); + }); + modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.TravelComponent", b => { b.HasOne("TravelCompanyDatabaseImplement.Models.Component", "Component") @@ -157,6 +229,11 @@ namespace TravelCompanyDatabaseImplement.Migrations b.Navigation("TravelComponents"); }); + modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.Shop", b => + { + b.Navigation("Travels"); + }); + modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.Travel", b => { b.Navigation("Components"); diff --git a/TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240308202100_InitialCreate.cs b/TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240404185254_InitialCreate.cs similarity index 66% rename from TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240308202100_InitialCreate.cs rename to TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240404185254_InitialCreate.cs index 9b1d5c0..def300b 100644 --- a/TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240308202100_InitialCreate.cs +++ b/TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240404185254_InitialCreate.cs @@ -25,6 +25,22 @@ namespace TravelCompanyDatabaseImplement.Migrations table.PrimaryKey("PK_Components", 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), + Adress = table.Column(type: "nvarchar(max)", nullable: false), + OpeningDate = table.Column(type: "datetime2", nullable: false), + TravelMaxCount = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Shops", x => x.Id); + }); + migrationBuilder.CreateTable( name: "Travels", columns: table => new @@ -63,6 +79,33 @@ namespace TravelCompanyDatabaseImplement.Migrations onDelete: ReferentialAction.Cascade); }); + migrationBuilder.CreateTable( + name: "ShopTravels", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + TravelId = 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_ShopTravels", x => x.Id); + table.ForeignKey( + name: "FK_ShopTravels_Shops_ShopId", + column: x => x.ShopId, + principalTable: "Shops", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_ShopTravels_Travels_TravelId", + column: x => x.TravelId, + principalTable: "Travels", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + migrationBuilder.CreateTable( name: "TravelComponents", columns: table => new @@ -95,6 +138,16 @@ namespace TravelCompanyDatabaseImplement.Migrations table: "Orders", column: "TravelId"); + migrationBuilder.CreateIndex( + name: "IX_ShopTravels_ShopId", + table: "ShopTravels", + column: "ShopId"); + + migrationBuilder.CreateIndex( + name: "IX_ShopTravels_TravelId", + table: "ShopTravels", + column: "TravelId"); + migrationBuilder.CreateIndex( name: "IX_TravelComponents_ComponentId", table: "TravelComponents", @@ -112,9 +165,15 @@ namespace TravelCompanyDatabaseImplement.Migrations migrationBuilder.DropTable( name: "Orders"); + migrationBuilder.DropTable( + name: "ShopTravels"); + migrationBuilder.DropTable( name: "TravelComponents"); + migrationBuilder.DropTable( + name: "Shops"); + migrationBuilder.DropTable( name: "Components"); diff --git a/TravelCompany/TravelCompanyDatabaseImplement/Migrations/TravelCompanyDataBaseModelSnapshot.cs b/TravelCompany/TravelCompanyDatabaseImplement/Migrations/TravelCompanyDataBaseModelSnapshot.cs index 3cacb43..4b0dfa4 100644 --- a/TravelCompany/TravelCompanyDatabaseImplement/Migrations/TravelCompanyDataBaseModelSnapshot.cs +++ b/TravelCompany/TravelCompanyDatabaseImplement/Migrations/TravelCompanyDataBaseModelSnapshot.cs @@ -75,6 +75,59 @@ namespace TravelCompanyDatabaseImplement.Migrations b.ToTable("Orders"); }); + modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.Shop", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Adress") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("OpeningDate") + .HasColumnType("datetime2"); + + b.Property("ShopName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("TravelMaxCount") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.ToTable("Shops"); + }); + + modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.ShopTravels", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("ShopId") + .HasColumnType("int"); + + b.Property("TravelId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ShopId"); + + b.HasIndex("TravelId"); + + b.ToTable("ShopTravels"); + }); + modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.Travel", b => { b.Property("Id") @@ -130,6 +183,25 @@ namespace TravelCompanyDatabaseImplement.Migrations .IsRequired(); }); + modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.ShopTravels", b => + { + b.HasOne("TravelCompanyDatabaseImplement.Models.Shop", "Shop") + .WithMany("Travels") + .HasForeignKey("ShopId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("TravelCompanyDatabaseImplement.Models.Travel", "Travel") + .WithMany() + .HasForeignKey("TravelId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Shop"); + + b.Navigation("Travel"); + }); + modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.TravelComponent", b => { b.HasOne("TravelCompanyDatabaseImplement.Models.Component", "Component") @@ -154,6 +226,11 @@ namespace TravelCompanyDatabaseImplement.Migrations b.Navigation("TravelComponents"); }); + modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.Shop", b => + { + b.Navigation("Travels"); + }); + modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.Travel", b => { b.Navigation("Components"); diff --git a/TravelCompany/TravelCompanyDatabaseImplement/Models/Shop.cs b/TravelCompany/TravelCompanyDatabaseImplement/Models/Shop.cs new file mode 100644 index 0000000..0c5729c --- /dev/null +++ b/TravelCompany/TravelCompanyDatabaseImplement/Models/Shop.cs @@ -0,0 +1,114 @@ +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.ViewModels; +using TravelCompanyDataModels.Models; +using System.ComponentModel.DataAnnotations.Schema; + +namespace TravelCompanyDatabaseImplement.Models +{ + public class Shop : IShopModel + { + public int Id { get; set; } + public string ShopName { get; set; } = string.Empty; + + public string Adress { get; set; } = string.Empty; + + public DateTime OpeningDate { get; set; } + + public int TravelMaxCount { get; set; } + + private Dictionary? _shopTravels = null; + + public Dictionary ShopTravels + { + get + { + if (_shopTravels == null) + { + if (_shopTravels == null) + { + _shopTravels = Travels + .ToDictionary(recSP => recSP.TravelId, recSP => (recSP.Travel as ITravelModel, recSP.Count)); + } + return _shopTravels; + } + return _shopTravels; + } + } + + [ForeignKey("ShopId")] + public List Travels { get; set; } = new(); + + public static Shop Create(TravelCompanyDataBase context, ShopBindingModel model) + { + return new Shop() + { + Id = model.Id, + ShopName = model.ShopName, + Adress = model.Adress, + OpeningDate = model.OpeningDate, + Travels = model.ShopTravels.Select(x => new ShopTravels + { + Travel = context.Travels.First(y => y.Id == x.Key), + Count = x.Value.Item2 + }).ToList(), + TravelMaxCount = model.TravelMaxCount + }; + } + + public void Update(ShopBindingModel model) + { + ShopName = model.ShopName; + Adress = model.Adress; + OpeningDate = model.OpeningDate; + TravelMaxCount = model.TravelMaxCount; + } + + public ShopViewModel GetViewModel => new() + { + Id = Id, + ShopName = ShopName, + Adress = Adress, + OpeningDate = OpeningDate, + ShopTravels = ShopTravels, + TravelMaxCount = TravelMaxCount + }; + + public void UpdateTravels(TravelCompanyDataBase context, ShopBindingModel model) + { + var ShopTravels = context.ShopTravels.Where(rec => rec.ShopId == model.Id).ToList(); + if (ShopTravels != null && ShopTravels.Count > 0) + { + context.ShopTravels.RemoveRange(ShopTravels.Where(rec => !model.ShopTravels.ContainsKey(rec.TravelId))); + context.SaveChanges(); + ShopTravels = context.ShopTravels.Where(rec => rec.ShopId == model.Id).ToList(); + foreach (var updateTravel in ShopTravels) + { + updateTravel.Count = model.ShopTravels[updateTravel.TravelId].Item2; + model.ShopTravels.Remove(updateTravel.TravelId); + } + context.SaveChanges(); + } + var shop = context.Shops.First(x => x.Id == Id); + foreach (var ar in model.ShopTravels) + { + context.ShopTravels.Add(new ShopTravels + { + Shop = shop, + Travel = context.Travels.First(x => x.Id == ar.Key), + Count = ar.Value.Item2 + }); + context.SaveChanges(); + } + _shopTravels = null; + } + + public void TravelsDictionatyUpdate(TravelCompanyDataBase context) + { + UpdateTravels(context, new ShopBindingModel + { + Id = Id, + ShopTravels = ShopTravels, + }); + } + } +} diff --git a/TravelCompany/TravelCompanyDatabaseImplement/Models/ShopTravels.cs b/TravelCompany/TravelCompanyDatabaseImplement/Models/ShopTravels.cs new file mode 100644 index 0000000..b1578df --- /dev/null +++ b/TravelCompany/TravelCompanyDatabaseImplement/Models/ShopTravels.cs @@ -0,0 +1,22 @@ +using System.ComponentModel.DataAnnotations; + +namespace TravelCompanyDatabaseImplement.Models +{ + public class ShopTravels + { + public int Id { get; set; } + + [Required] + public int TravelId { get; set; } + + [Required] + public int ShopId { get; set; } + + [Required] + public int Count { get; set; } + + public virtual Shop Shop { get; set; } = new(); + + public virtual Travel Travel { get; set; } = new(); + } +} diff --git a/TravelCompany/TravelCompanyDatabaseImplement/Models/Travel.cs b/TravelCompany/TravelCompanyDatabaseImplement/Models/Travel.cs index 88ffaa3..69f7324 100644 --- a/TravelCompany/TravelCompanyDatabaseImplement/Models/Travel.cs +++ b/TravelCompany/TravelCompanyDatabaseImplement/Models/Travel.cs @@ -1,13 +1,8 @@ using TravelCompanyContracts.BindingModels; using TravelCompanyContracts.ViewModels; using TravelCompanyDataModels.Models; -using System; -using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace TravelCompanyDatabaseImplement.Models { @@ -38,6 +33,8 @@ namespace TravelCompanyDatabaseImplement.Models public virtual List Components { get; set; } = new(); [ForeignKey("TravelId")] public virtual List Orders { get; set; } = new(); + [ForeignKey("TravelId")] + public virtual List ShopTravels { get; set; } = new(); public static Travel Create(TravelCompanyDataBase context, TravelBindingModel model) { @@ -54,6 +51,7 @@ namespace TravelCompanyDatabaseImplement.Models }).ToList() }; } + public void Update(TravelBindingModel model) { TravelName = model.TravelName; diff --git a/TravelCompany/TravelCompanyDatabaseImplement/TravelCompanyDataBase.cs b/TravelCompany/TravelCompanyDatabaseImplement/TravelCompanyDataBase.cs index f533f89..850612f 100644 --- a/TravelCompany/TravelCompanyDatabaseImplement/TravelCompanyDataBase.cs +++ b/TravelCompany/TravelCompanyDatabaseImplement/TravelCompanyDataBase.cs @@ -1,11 +1,5 @@ using TravelCompanyDatabaseImplement.Models; using Microsoft.EntityFrameworkCore; -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace TravelCompanyDatabaseImplement { @@ -16,7 +10,7 @@ optionsBuilder) { if (optionsBuilder.IsConfigured == false) { - optionsBuilder.UseSqlServer(@"Data Source=DESKTOP-D5A5OOG\GOLDFEST;Initial Catalog=TravelCompanyDatabase;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True"); + optionsBuilder.UseSqlServer(@"Data Source=DESKTOP-D5A5OOG\GOLDFEST;Initial Catalog=TravelCompanyHard;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True"); } base.OnConfiguring(optionsBuilder); } @@ -24,6 +18,8 @@ optionsBuilder) public virtual DbSet Travels { set; get; } public virtual DbSet TravelComponents { set; get; } public virtual DbSet Orders { set; get; } + public virtual DbSet Shops { get; set; } + public virtual DbSet ShopTravels { get; set; } } } diff --git a/TravelCompany/TravelCompanyFileImplement/DataFileSingleton.cs b/TravelCompany/TravelCompanyFileImplement/DataFileSingleton.cs index 1bb27c6..eac4114 100644 --- a/TravelCompany/TravelCompanyFileImplement/DataFileSingleton.cs +++ b/TravelCompany/TravelCompanyFileImplement/DataFileSingleton.cs @@ -14,9 +14,11 @@ namespace TravelCompanyFileImplement private readonly string ComponentFileName = "Component.xml"; private readonly string OrderFileName = "Order.xml"; private readonly string TravelFileName = "Travel.xml"; + private readonly string ShopFileName = "Shop.xml"; public List Components { get; private set; } public List Orders { get; private set; } public List Travels { get; private set; } + public List Shops { get; private set; } public static DataFileSingleton GetInstance() { if (instance == null) @@ -28,11 +30,13 @@ namespace TravelCompanyFileImplement public void SaveComponents() => SaveData(Components, ComponentFileName, "Components", x => x.GetXElement); public void SaveTravels() => SaveData(Travels, TravelFileName, "Travels", x => x.GetXElement); public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement); + public void SaveShops() => SaveData(Shops, ShopFileName, "Shops", x => x.GetXElement); private DataFileSingleton() { Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!; Travels = LoadData(TravelFileName, "Travel", x => Travel.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/TravelCompany/TravelCompanyFileImplement/Implements/ShopStorage.cs b/TravelCompany/TravelCompanyFileImplement/Implements/ShopStorage.cs new file mode 100644 index 0000000..ded4265 --- /dev/null +++ b/TravelCompany/TravelCompanyFileImplement/Implements/ShopStorage.cs @@ -0,0 +1,154 @@ +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.SearchModels; +using TravelCompanyContracts.StoragesContracts; +using TravelCompanyContracts.ViewModels; +using TravelCompanyFileImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TravelCompanyFileImplement.Implements +{ + public class ShopStorage : IShopStorage + { + private readonly DataFileSingleton source; + + public ShopStorage() + { + source = DataFileSingleton.GetInstance(); + } + + public List GetFullList() + { + return source.Shops.Select(x => x.GetViewModel).ToList(); + } + + public List GetFilteredList(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.ShopName)) + { + return new(); + } + return source.Shops.Where(x => x.ShopName.Contains(model.ShopName)).Select(x => x.GetViewModel).ToList(); + } + + public ShopViewModel? GetElement(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.ShopName) && !model.Id.HasValue) + { + return null; + } + return source.Shops.FirstOrDefault(x => + (!string.IsNullOrEmpty(model.ShopName) && x.ShopName == model.ShopName) || + (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; + } + + public ShopViewModel? Insert(ShopBindingModel model) + { + model.Id = source.Shops.Count > 0 ? source.Shops.Max(x => x.Id) + 1 : 1; + var newShop = Shop.Create(model); + if (newShop == null) + { + return null; + } + source.Shops.Add(newShop); + source.SaveShops(); + return newShop.GetViewModel; + } + + public ShopViewModel? Update(ShopBindingModel model) + { + var shop = source.Shops.FirstOrDefault(x => x.Id == model.Id); + if (shop == null) + { + return null; + } + shop.Update(model); + source.SaveShops(); + return shop.GetViewModel; + } + + public ShopViewModel? Delete(ShopBindingModel model) + { + var shop = source.Shops.FirstOrDefault(x => x.Id == model.Id); + if (shop != null) + { + source.Shops.Remove(shop); + source.SaveShops(); + return shop.GetViewModel; + } + return null; + } + + public bool Sale(SupplySearchModel model) + { + if (model == null || !model.TravelId.HasValue || !model.Count.HasValue) + return false; + int remainingSpace = source.Shops.Select(x => x.Travels.ContainsKey(model.TravelId.Value) ? x.Travels[model.TravelId.Value] : 0).Sum(); + if (remainingSpace < model.Count) + { + return false; + } + var shops = source.Shops.Where(x => x.Travels.ContainsKey(model.TravelId.Value)).OrderByDescending(x => x.Travels[model.TravelId.Value]).ToList(); + foreach (var shop in shops) + { + int residue = model.Count.Value - shop.Travels[model.TravelId.Value]; + if (residue > 0) + { + shop.Travels.Remove(model.TravelId.Value); + shop.TravelsUpdate(); + model.Count = residue; + } + else + { + if (residue == 0) + { + shop.Travels.Remove(model.TravelId.Value); + } + else + { + shop.Travels[model.TravelId.Value] = -residue; + } + shop.TravelsUpdate(); + source.SaveShops(); + return true; + } + } + source.SaveShops(); + return false; + } + + public bool RestockingShops(SupplyBindingModel model) + { + if (model == null || source.Shops.Select(x => x.TravelMaxCount - x.ShopTravels.Select(y => y.Value.Item2).Sum()).Sum() < model.Count) + { + return false; + } + foreach (Shop shop in source.Shops) + { + int free_places = shop.TravelMaxCount - shop.ShopTravels.Select(x => x.Value.Item2).Sum(); + if (free_places <= 0) + continue; + free_places = Math.Min(free_places, model.Count); + model.Count -= free_places; + if (shop.Travels.ContainsKey(model.TravelId)) + { + shop.Travels[model.TravelId] += free_places; + } + else + { + shop.Travels.Add(model.TravelId, free_places); + } + shop.TravelsUpdate(); + if (model.Count == 0) + { + source.SaveShops(); + return true; + } + } + return false; + } + } +} \ No newline at end of file diff --git a/TravelCompany/TravelCompanyFileImplement/Models/Shop.cs b/TravelCompany/TravelCompanyFileImplement/Models/Shop.cs new file mode 100644 index 0000000..03ef8fb --- /dev/null +++ b/TravelCompany/TravelCompanyFileImplement/Models/Shop.cs @@ -0,0 +1,111 @@ +using TravelCompanyDataModels.Models; +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace TravelCompanyFileImplement.Models +{ + public class Shop : IShopModel + { + public int Id { get; private set; } + public string ShopName { get; private set; } = string.Empty; + public string Adress { get; private set; } = string.Empty; + public DateTime OpeningDate { get; private set; } + public Dictionary Travels { get; private set; } = new(); + private Dictionary? _shopTravels = null; + + public Dictionary ShopTravels + { + get + { + if (_shopTravels == null) + { + var source = DataFileSingleton.GetInstance(); + _shopTravels = Travels.ToDictionary(x => x.Key, y => ((source.Travels.FirstOrDefault(z => z.Id == y.Key) as ITravelModel)!, y.Value)); + } + return _shopTravels; + } + } + + public int TravelMaxCount { get; private set; } + + public static Shop? Create(ShopBindingModel? model) + { + if (model == null) + { + return null; + } + return new Shop() + { + Id = model.Id, + ShopName = model.ShopName, + Adress = model.Adress, + OpeningDate = model.OpeningDate, + Travels = model.ShopTravels.ToDictionary(x => x.Key, x => x.Value.Item2), + TravelMaxCount = model.TravelMaxCount + }; + } + + public static Shop? Create(XElement element) + { + if (element == null) + { + return null; + } + return new() + { + Id = Convert.ToInt32(element.Attribute("Id")!.Value), + ShopName = element.Element("ShopName")!.Value, + Adress = element.Element("Adress")!.Value, + OpeningDate = Convert.ToDateTime(element.Element("OpeningDate")!.Value), + Travels = element.Element("ShopTravels")!.Elements("ShopTravel")!.ToDictionary(x => Convert.ToInt32(x.Element("Key")?.Value), + x => Convert.ToInt32(x.Element("Value")?.Value)), + TravelMaxCount = Convert.ToInt32(element.Element("TravelMaxCount")!.Value) + }; + } + + public void Update(ShopBindingModel? model) + { + if (model == null) + { + return; + } + ShopName = model.ShopName; + Adress = model.Adress; + OpeningDate = model.OpeningDate; + TravelMaxCount = model.TravelMaxCount; + Travels = model.ShopTravels.ToDictionary(x => x.Key, x => x.Value.Item2); + _shopTravels = null; + } + + public ShopViewModel GetViewModel => new() + { + Id = Id, + ShopName = ShopName, + Adress = Adress, + OpeningDate = OpeningDate, + ShopTravels = ShopTravels, + TravelMaxCount = TravelMaxCount + }; + + public XElement GetXElement => new("Shop", + new XAttribute("Id", Id), + new XElement("ShopName", ShopName), + new XElement("Adress", Adress), + new XElement("OpeningDate", OpeningDate.ToString()), + new XElement("ShopTravels", Travels.Select( + x => new XElement("ShopTravel", new XElement("Key", x.Key), new XElement("Value", x.Value))).ToArray()), + new XElement("TravelMaxCount", TravelMaxCount.ToString()) + ); + + public void TravelsUpdate() + { + _shopTravels = null; + } + } +} \ No newline at end of file diff --git a/TravelCompany/TravelCompanyListImplement/DataListSingleton.cs b/TravelCompany/TravelCompanyListImplement/DataListSingleton.cs index 01817fb..0416d6e 100644 --- a/TravelCompany/TravelCompanyListImplement/DataListSingleton.cs +++ b/TravelCompany/TravelCompanyListImplement/DataListSingleton.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using TravelCompanyListImplement.Models; namespace TravelCompanyListImplement { @@ -13,11 +14,13 @@ namespace TravelCompanyListImplement public List Components { get; set; } public List Orders { get; set; } public List Travels { get; set; } + public List Shops { get; set; } private DataListSingleton() { Components = new List(); Orders = new List(); Travels = new List(); + Shops = new List(); } public static DataListSingleton GetInstance() { diff --git a/TravelCompany/TravelCompanyListImplement/Implements/ShopStorage.cs b/TravelCompany/TravelCompanyListImplement/Implements/ShopStorage.cs new file mode 100644 index 0000000..a785fb2 --- /dev/null +++ b/TravelCompany/TravelCompanyListImplement/Implements/ShopStorage.cs @@ -0,0 +1,123 @@ +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.SearchModels; +using TravelCompanyContracts.StoragesContracts; +using TravelCompanyContracts.ViewModels; +using TravelCompanyListImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TravelCompanyListImplement.Implements +{ + public class ShopStorage : IShopStorage + { + private readonly DataListSingleton _source; + + public ShopStorage() + { + _source = DataListSingleton.GetInstance(); + } + + public List GetFullList() + { + var result = new List(); + foreach (var shop in _source.Shops) + { + result.Add(shop.GetViewModel); + } + return result; + } + + public List GetFilteredList(ShopSearchModel model) + { + var result = new List(); + if (string.IsNullOrEmpty(model.ShopName)) + { + return result; + } + foreach (var shop in _source.Shops) + { + if (shop.ShopName.Contains(model.ShopName)) + { + result.Add(shop.GetViewModel); + } + } + return result; + } + + public ShopViewModel? GetElement(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.ShopName) && !model.Id.HasValue) + { + return null; + } + foreach (var shop in _source.Shops) + { + if ((!string.IsNullOrEmpty(model.ShopName) && shop.ShopName == model.ShopName) || + (model.Id.HasValue && shop.Id == model.Id)) + { + return shop.GetViewModel; + } + } + return null; + } + + public ShopViewModel? Insert(ShopBindingModel model) + { + model.Id = 1; + foreach (var shop in _source.Shops) + { + if (model.Id <= shop.Id) + { + model.Id = shop.Id + 1; + } + } + var newShop = Shop.Create(model); + if (newShop == null) + { + return null; + } + _source.Shops.Add(newShop); + return newShop.GetViewModel; + } + + public ShopViewModel? Update(ShopBindingModel model) + { + foreach (var shop in _source.Shops) + { + if (shop.Id == model.Id) + { + shop.Update(model); + return shop.GetViewModel; + } + } + return null; + } + + public ShopViewModel? Delete(ShopBindingModel model) + { + for (int i = 0; i < _source.Shops.Count; ++i) + { + if (_source.Shops[i].Id == model.Id) + { + var element = _source.Shops[i]; + _source.Shops.RemoveAt(i); + return element.GetViewModel; + } + } + return null; + } + + public bool Sale(SupplySearchModel model) + { + throw new NotImplementedException(); + } + + public bool RestockingShops(SupplyBindingModel model) + { + throw new NotImplementedException(); + } + } +} diff --git a/TravelCompany/TravelCompanyListImplement/Models/Shop.cs b/TravelCompany/TravelCompanyListImplement/Models/Shop.cs new file mode 100644 index 0000000..11a71b1 --- /dev/null +++ b/TravelCompany/TravelCompanyListImplement/Models/Shop.cs @@ -0,0 +1,59 @@ +using TravelCompanyDataModels.Models; +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TravelCompanyListImplement.Models +{ + public class Shop : IShopModel + { + public int Id { get; private set; } + public string ShopName { get; private set; } = string.Empty; + public string Adress { get; private set; } = string.Empty; + public DateTime OpeningDate { get; private set; } + public Dictionary ShopTravels { get; private set; } = new(); + public int TravelMaxCount { get; private set; } + + public static Shop? Create(ShopBindingModel? model) + { + if (model == null) + { + return null; + } + return new Shop() + { + Id = model.Id, + ShopName = model.ShopName, + Adress = model.Adress, + OpeningDate = model.OpeningDate, + TravelMaxCount = model.TravelMaxCount, + }; + } + + public void Update(ShopBindingModel? model) + { + if (model == null) + { + return; + } + ShopName = model.ShopName; + Adress = model.Adress; + OpeningDate = model.OpeningDate; + TravelMaxCount = model.TravelMaxCount; + } + + public ShopViewModel GetViewModel => new() + { + Id = Id, + ShopName = ShopName, + Adress = Adress, + OpeningDate = OpeningDate, + ShopTravels = ShopTravels, + TravelMaxCount = TravelMaxCount, + }; + } +} From f0850cfcbdcf03793239f0af9b88c423e048df9c Mon Sep 17 00:00:00 2001 From: goldfest Date: Thu, 4 Apr 2024 23:57:46 +0400 Subject: [PATCH 2/5] =?UTF-8?q?=D1=81=D0=B4=D0=B5=D0=BB=D0=B0=D0=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../TravelCompany/FormCreateOrder.Designer.cs | 3 - .../TravelCompany/FormCreateOrder.cs | 51 +++----- .../TravelCompany/FormTravels.Designer.cs | 5 - TravelCompany/TravelCompany/FormTravels.cs | 38 +++--- .../BusinessLogic/OrderLogic.cs | 119 +++++++++--------- .../BusinessLogic/ShopLogic.cs | 21 +++- .../BusinessLogic/TravelLogic.cs | 3 +- 7 files changed, 111 insertions(+), 129 deletions(-) diff --git a/TravelCompany/TravelCompany/FormCreateOrder.Designer.cs b/TravelCompany/TravelCompany/FormCreateOrder.Designer.cs index 1ec37f3..cd34044 100644 --- a/TravelCompany/TravelCompany/FormCreateOrder.Designer.cs +++ b/TravelCompany/TravelCompany/FormCreateOrder.Designer.cs @@ -71,7 +71,6 @@ textBoxCount.Name = "textBoxCount"; textBoxCount.Size = new Size(246, 23); textBoxCount.TabIndex = 3; - textBoxCount.TextChanged += textBoxCount_TextChanged; // // comboBoxTravel // @@ -98,7 +97,6 @@ buttonSave.TabIndex = 6; buttonSave.Text = "Сохранить"; buttonSave.UseVisualStyleBackColor = true; - buttonSave.Click += buttonSave_Click; // // buttonCancel // @@ -108,7 +106,6 @@ buttonCancel.TabIndex = 7; buttonCancel.Text = "Отмена"; buttonCancel.UseVisualStyleBackColor = true; - buttonCancel.Click += buttonCancel_Click; // // FormCreateOrder // diff --git a/TravelCompany/TravelCompany/FormCreateOrder.cs b/TravelCompany/TravelCompany/FormCreateOrder.cs index 8cff27f..099b516 100644 --- a/TravelCompany/TravelCompany/FormCreateOrder.cs +++ b/TravelCompany/TravelCompany/FormCreateOrder.cs @@ -1,16 +1,8 @@ -using TravelCompanyContracts.BindingModels; +using Microsoft.Extensions.Logging; +using TravelCompanyContracts.BindingModels; using TravelCompanyContracts.BusinessLogicsContracts; using TravelCompanyContracts.SearchModels; -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows.Forms; +using TravelCompanyContracts.ViewModels; namespace TravelCompany.Forms { @@ -19,6 +11,8 @@ namespace TravelCompany.Forms private readonly ILogger _logger; private readonly ITravelLogic _logicP; private readonly IOrderLogic _logicO; + private List? _list; + public FormCreateOrder(ILogger logger, ITravelLogic logicP, IOrderLogic logicO) { InitializeComponent(); @@ -29,23 +23,17 @@ namespace TravelCompany.Forms private void FormCreateOrder_Load(object sender, EventArgs e) { - try + _list = _logicP.ReadList(null); + if (_list != null) { - var list = _logicP.ReadList(null); - if (list != null) - { - comboBoxTravel.DisplayMember = "TravelName"; - comboBoxTravel.ValueMember = "Id"; - comboBoxTravel.DataSource = list; - comboBoxTravel.SelectedItem = null; - _logger.LogInformation("Загрузка изделий для заказа"); - } - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки списка изделий"); + comboBoxTravel.DisplayMember = "TravelName"; + comboBoxTravel.ValueMember = "Id"; + comboBoxTravel.DataSource = _list; + comboBoxTravel.SelectedItem = null; + _logger.LogInformation("Загрузка пиццы для заказа"); } } + private void CalcSum() { if (comboBoxTravel.SelectedValue != null && !string.IsNullOrEmpty(textBoxCount.Text)) @@ -68,7 +56,8 @@ namespace TravelCompany.Forms } } } - private void textBoxCount_TextChanged(object sender, EventArgs e) + + private void TextBoxCount_TextChanged(object sender, EventArgs e) { CalcSum(); } @@ -78,7 +67,7 @@ namespace TravelCompany.Forms CalcSum(); } - private void buttonSave_Click(object sender, EventArgs e) + private void ButtonSave_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(textBoxCount.Text)) { @@ -87,7 +76,7 @@ namespace TravelCompany.Forms } if (comboBoxTravel.SelectedValue == null) { - MessageBox.Show("Выберите изделие", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("Выберите пиццу", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } _logger.LogInformation("Создание заказа"); @@ -109,15 +98,15 @@ namespace TravelCompany.Forms } catch (Exception ex) { - _logger.LogError(ex, "Ошибка создания заказа"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError(ex, "Ошибка создания заказа"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } - private void buttonCancel_Click(object sender, EventArgs e) + private void ButtonCancel_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; Close(); } - } } diff --git a/TravelCompany/TravelCompany/FormTravels.Designer.cs b/TravelCompany/TravelCompany/FormTravels.Designer.cs index 053d8b3..2c27ec8 100644 --- a/TravelCompany/TravelCompany/FormTravels.Designer.cs +++ b/TravelCompany/TravelCompany/FormTravels.Designer.cs @@ -44,7 +44,6 @@ buttonRef.TabIndex = 9; buttonRef.Text = "Обновить"; buttonRef.UseVisualStyleBackColor = true; - buttonRef.Click += buttonRef_Click; // // buttonDel // @@ -54,7 +53,6 @@ buttonDel.TabIndex = 8; buttonDel.Text = "Удалить"; buttonDel.UseVisualStyleBackColor = true; - buttonDel.Click += buttonDel_Click; // // buttonUpd // @@ -64,7 +62,6 @@ buttonUpd.TabIndex = 7; buttonUpd.Text = "Изменить"; buttonUpd.UseVisualStyleBackColor = true; - buttonUpd.Click += buttonUpd_Click; // // buttonAdd // @@ -74,7 +71,6 @@ buttonAdd.TabIndex = 6; buttonAdd.Text = "Добавить"; buttonAdd.UseVisualStyleBackColor = true; - buttonAdd.Click += buttonAdd_Click; // // dataGridView // @@ -100,7 +96,6 @@ Margin = new Padding(3, 2, 3, 2); Name = "FormTravels"; Text = "Список туристических путёвок"; - Load += FormTravels_Load; ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); ResumeLayout(false); } diff --git a/TravelCompany/TravelCompany/FormTravels.cs b/TravelCompany/TravelCompany/FormTravels.cs index b772ffd..e83d830 100644 --- a/TravelCompany/TravelCompany/FormTravels.cs +++ b/TravelCompany/TravelCompany/FormTravels.cs @@ -1,16 +1,6 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows.Forms; -using TravelCompany; +using Microsoft.Extensions.Logging; using TravelCompanyContracts.BindingModels; using TravelCompanyContracts.BusinessLogicsContracts; -using Microsoft.Extensions.Logging; namespace TravelCompany.Forms { @@ -18,6 +8,7 @@ namespace TravelCompany.Forms { private readonly ILogger _logger; private readonly ITravelLogic _logic; + public FormTravels(ILogger logger, ITravelLogic logic) { InitializeComponent(); @@ -25,7 +16,7 @@ namespace TravelCompany.Forms _logic = logic; } - private void FormTravels_Load(object sender, EventArgs e) + private void FormTravel_Load(object sender, EventArgs e) { LoadData(); } @@ -40,17 +31,19 @@ namespace TravelCompany.Forms dataGridView.DataSource = list; dataGridView.Columns["Id"].Visible = false; dataGridView.Columns["TravelComponents"].Visible = false; - dataGridView.Columns["TravelName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + dataGridView.Columns["TravelName"].AutoSizeMode = + DataGridViewAutoSizeColumnMode.Fill; } - _logger.LogInformation("Загрузка путёвок"); + _logger.LogInformation("Загрузка пиццы"); } catch (Exception ex) { - _logger.LogError(ex, "Ошибка загрузки компонентов"); + _logger.LogError(ex, "Ошибка загрузки пиццы"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } - private void buttonAdd_Click(object sender, EventArgs e) + private void ButtonAdd_Click(object sender, EventArgs e) { var service = Program.ServiceProvider?.GetService(typeof(FormTravel)); if (service is FormTravel form) @@ -62,7 +55,7 @@ namespace TravelCompany.Forms } } - private void buttonUpd_Click(object sender, EventArgs e) + private void ButtonUpd_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) { @@ -78,15 +71,14 @@ namespace TravelCompany.Forms } } - private void buttonDel_Click(object sender, EventArgs e) + private void ButtonDel_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) { if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { - int id = - Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Удаление путёвок"); + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Удаление пиццы"); try { if (!_logic.Delete(new TravelBindingModel @@ -100,14 +92,14 @@ namespace TravelCompany.Forms } catch (Exception ex) { - _logger.LogError(ex, "Ошибка удаления путевки"); + _logger.LogError(ex, "Ошибка удаления пиццы"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } } - private void buttonRef_Click(object sender, EventArgs e) + private void ButtonRef_Click(object sender, EventArgs e) { LoadData(); } diff --git a/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/OrderLogic.cs b/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/OrderLogic.cs index e7c1295..2f2a393 100644 --- a/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/OrderLogic.cs +++ b/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/OrderLogic.cs @@ -1,33 +1,25 @@ -using TravelCompanyContracts.BindingModels; +using Microsoft.Extensions.Logging; +using TravelCompanyContracts.BindingModels; using TravelCompanyContracts.BusinessLogicsContracts; using TravelCompanyContracts.SearchModels; using TravelCompanyContracts.StoragesContracts; using TravelCompanyContracts.ViewModels; using TravelCompanyDataModels.Enums; -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace TravelCompanyBusinessLogic.BusinessLogic +namespace TravelCompanyBusinessLogic.BusinessLogics { public class OrderLogic : IOrderLogic { - //Класс с логикой для заказов будет отвечать за получение списка заказов, - //создания заказа и смены его статусов. Следует учитывать, что у заказа можно - //менять статус на новый, если его текущий статус предшествует новому - private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; + private readonly IShopStorage _shopStorage; - public OrderLogic(ILogger logger, IOrderStorage orderStorage) + public OrderLogic(ILogger logger, IOrderStorage orderStorage, IShopStorage shopStorage) { _logger = logger; _orderStorage = orderStorage; + _shopStorage = shopStorage; } - public List? ReadList(OrderSearchModel? model) { _logger.LogInformation("ReadList. OrderId:{Id}", model?.Id); @@ -40,18 +32,14 @@ namespace TravelCompanyBusinessLogic.BusinessLogic _logger.LogInformation("ReadList. Count:{Count}", list.Count); return list; } - public bool CreateOrder(OrderBindingModel model) { CheckModel(model); - if (model.Status != OrderStatus.Неизвестен) return false; model.Status = OrderStatus.Принят; - if (_orderStorage.Insert(model) == null) { - model.Status = OrderStatus.Неизвестен; _logger.LogWarning("Insert operation failed"); return false; } @@ -60,57 +48,34 @@ namespace TravelCompanyBusinessLogic.BusinessLogic public bool TakeOrderInWork(OrderBindingModel model) { - return ToNextStatus(model, OrderStatus.Выполняется); + return ChangeStatus(model, OrderStatus.Выполняется); } public bool FinishOrder(OrderBindingModel model) { - return ToNextStatus(model, OrderStatus.Готов); + return ChangeStatus(model, OrderStatus.Готов); } public bool DeliveryOrder(OrderBindingModel model) { - return ToNextStatus(model, OrderStatus.Выдан); - } - - public bool ToNextStatus(OrderBindingModel model, OrderStatus orderStatus) - { - CheckModel(model, false); - var element = _orderStorage.GetElement(new OrderSearchModel() + var order = _orderStorage.GetElement(new OrderSearchModel { - Id = model.Id + Id = model.Id, }); - if (element == null) + if (order == null) { - throw new ArgumentNullException(nameof(element)); + throw new ArgumentNullException(nameof(order)); + } + if (!_shopStorage.RestockingShops(new SupplyBindingModel + { + TravelId = order.TravelId, + Count = order.Count + })) + { + throw new ArgumentException("Недостаточно места"); } - model.TravelId = element.TravelId; - model.DateCreate = element.DateCreate; - model.DateImplement = element.DateImplement; - model.Status = element.Status; - model.Count = element.Count; - model.Sum = element.Sum; - - if (model.Status != orderStatus - 1) - { - _logger.LogWarning("Status update to " + orderStatus + " operation failed"); - return false; - } - model.Status = orderStatus; - - if (model.Status == OrderStatus.Выдан) - { - model.DateImplement = DateTime.Now; - } - - if (_orderStorage.Update(model) == null) - { - model.Status--; - _logger.LogWarning("Changing status operation faled"); - return false; - } - return true; + return ChangeStatus(model, OrderStatus.Выдан); } private void CheckModel(OrderBindingModel model, bool withParams = true) @@ -125,17 +90,51 @@ namespace TravelCompanyBusinessLogic.BusinessLogic } if (model.Count <= 0) { - throw new ArgumentNullException("Количество изделий должно быть больше 0", nameof(model.Count)); + throw new ArgumentException("Колличество пиццы в заказе не может быть меньше 1", nameof(model.Count)); } if (model.Sum <= 0) { - throw new ArgumentNullException("Цена заказа должна быть больше 0", nameof(model.Sum)); + throw new ArgumentException("Стоимость заказа на может быть меньше 1", nameof(model.Sum)); } if (model.DateImplement.HasValue && model.DateImplement < model.DateCreate) { - throw new ArithmeticException($"Дата выдачи заказа {model.DateImplement} должна быть позже даты его создания {model.DateCreate}"); + throw new ArithmeticException($"Дата выдачи заказа {model.DateImplement} не может быть раньше даты его создания {model.DateCreate}"); } - _logger.LogInformation("Travel. TravelId:{TravelId}.Count:{Count}.Sum:{Sum}Id:{Id}", model.TravelId, model.Count, model.Sum, model.Id); + _logger.LogInformation("Travel. TravelId:{TravelId}.Count:{Count}.Sum:{Sum}Id:{Id}", + model.TravelId, model.Count, model.Sum, model.Id); + } + + private bool ChangeStatus(OrderBindingModel model, OrderStatus requiredStatus) + { + CheckModel(model, false); + var element = _orderStorage.GetElement(new OrderSearchModel() + { + Id = model.Id + }); + if (element == null) + { + throw new ArgumentNullException(nameof(element)); + } + model.DateCreate = element.DateCreate; + model.TravelId = element.TravelId; + model.DateImplement = element.DateImplement; + model.Status = element.Status; + model.Count = element.Count; + model.Sum = element.Sum; + if (requiredStatus - model.Status == 1) + { + model.Status = requiredStatus; + if (model.Status == OrderStatus.Выдан) + model.DateImplement = DateTime.Now; + if (_orderStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + return true; + } + _logger.LogWarning("Changing status operation faled: Current-{Status}:required-{requiredStatus}.", model.Status, requiredStatus); + throw new ArgumentException($"Невозможно присвоить статус {requiredStatus} заказу с текущим статусом {model.Status}"); } } } diff --git a/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/ShopLogic.cs b/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/ShopLogic.cs index 82e6c71..1021630 100644 --- a/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/ShopLogic.cs +++ b/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/ShopLogic.cs @@ -1,14 +1,14 @@ using Microsoft.Extensions.Logging; -using TravelCompanyContracts.BindingModels; -using TravelCompanyContracts.BusinessLogicsContracts; -using TravelCompanyContracts.SearchModels; -using TravelCompanyContracts.StoragesContracts; -using TravelCompanyContracts.ViewModels; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.BusinessLogicsContracts; +using TravelCompanyContracts.SearchModels; +using TravelCompanyContracts.StoragesContracts; +using TravelCompanyContracts.ViewModels; namespace TravelCompanyBusinessLogic.BusinessLogics { @@ -125,6 +125,17 @@ namespace TravelCompanyBusinessLogic.BusinessLogics } shop.ShopTravels.Add(model.TravelId, (Travel, model.Count)); } + + _shopStorage.Update(new ShopBindingModel() + { + Id = shop.Id, + ShopName = shop.ShopName, + Adress = shop.Adress, + OpeningDate = shop.OpeningDate, + ShopTravels = shop.ShopTravels, + TravelMaxCount = shop.TravelMaxCount, + }); + return true; } diff --git a/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/TravelLogic.cs b/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/TravelLogic.cs index 69719fe..595b82b 100644 --- a/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/TravelLogic.cs +++ b/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/TravelLogic.cs @@ -16,8 +16,7 @@ namespace TravelCompanyBusinessLogic.BusinessLogic { private readonly ILogger _logger; private readonly ITravelStorage _TravelStorage; - public TravelLogic(ILogger logger, ITravelStorage - TravelStorage) + public TravelLogic(ILogger logger, ITravelStorage TravelStorage) { _logger = logger; _TravelStorage = TravelStorage; From 0e64524320c70ae9baf4e63c829e52346b683438 Mon Sep 17 00:00:00 2001 From: goldfest Date: Fri, 5 Apr 2024 00:04:55 +0400 Subject: [PATCH 3/5] =?UTF-8?q?=D0=B4=D0=BE=D0=B4=D0=B5=D0=BB=D0=B0=D0=BB3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../TravelCompanyBusinessLogic/BusinessLogic/ShopLogic.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/ShopLogic.cs b/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/ShopLogic.cs index 1021630..56cfe73 100644 --- a/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/ShopLogic.cs +++ b/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/ShopLogic.cs @@ -123,6 +123,10 @@ namespace TravelCompanyBusinessLogic.BusinessLogics { throw new ArgumentException($"Поставка: Товар с id:{model.TravelId} не найденн"); } + if (shop.ShopTravels.Sum(kv => kv.Value.Item2) + model.Count > shop.TravelMaxCount) + { + throw new ArgumentException("Превышена максимальная вместимость магазина"); + } shop.ShopTravels.Add(model.TravelId, (Travel, model.Count)); } @@ -139,6 +143,7 @@ namespace TravelCompanyBusinessLogic.BusinessLogics return true; } + private void CheckModel(ShopBindingModel model, bool withParams = true) { if (model == null) From d6bc4aca61eb0b5f9fdc6b1563a75254e5415ffd Mon Sep 17 00:00:00 2001 From: goldfest Date: Fri, 5 Apr 2024 00:09:31 +0400 Subject: [PATCH 4/5] =?UTF-8?q?=D0=B2=D1=8B=D1=8B=D0=B2=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../TravelCompanyBusinessLogic/BusinessLogic/ShopLogic.cs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/ShopLogic.cs b/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/ShopLogic.cs index 56cfe73..1021630 100644 --- a/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/ShopLogic.cs +++ b/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/ShopLogic.cs @@ -123,10 +123,6 @@ namespace TravelCompanyBusinessLogic.BusinessLogics { throw new ArgumentException($"Поставка: Товар с id:{model.TravelId} не найденн"); } - if (shop.ShopTravels.Sum(kv => kv.Value.Item2) + model.Count > shop.TravelMaxCount) - { - throw new ArgumentException("Превышена максимальная вместимость магазина"); - } shop.ShopTravels.Add(model.TravelId, (Travel, model.Count)); } @@ -143,7 +139,6 @@ namespace TravelCompanyBusinessLogic.BusinessLogics return true; } - private void CheckModel(ShopBindingModel model, bool withParams = true) { if (model == null) From 80399cca5efd2c4ebcef693947875ca9600d041b Mon Sep 17 00:00:00 2001 From: goldfest Date: Fri, 5 Apr 2024 00:15:35 +0400 Subject: [PATCH 5/5] =?UTF-8?q?=D0=B4=D0=BE=20=D0=BA=D0=BE=D0=BD=D1=86?= =?UTF-8?q?=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../TravelCompany/FormTravels.Designer.cs | 5 + TravelCompany/TravelCompany/FormTravels.cs | 38 +++--- .../BusinessLogic/OrderLogic.cs | 108 +++++++++++------- .../BusinessLogic/ShopLogic.cs | 5 + 4 files changed, 97 insertions(+), 59 deletions(-) diff --git a/TravelCompany/TravelCompany/FormTravels.Designer.cs b/TravelCompany/TravelCompany/FormTravels.Designer.cs index 2c27ec8..053d8b3 100644 --- a/TravelCompany/TravelCompany/FormTravels.Designer.cs +++ b/TravelCompany/TravelCompany/FormTravels.Designer.cs @@ -44,6 +44,7 @@ buttonRef.TabIndex = 9; buttonRef.Text = "Обновить"; buttonRef.UseVisualStyleBackColor = true; + buttonRef.Click += buttonRef_Click; // // buttonDel // @@ -53,6 +54,7 @@ buttonDel.TabIndex = 8; buttonDel.Text = "Удалить"; buttonDel.UseVisualStyleBackColor = true; + buttonDel.Click += buttonDel_Click; // // buttonUpd // @@ -62,6 +64,7 @@ buttonUpd.TabIndex = 7; buttonUpd.Text = "Изменить"; buttonUpd.UseVisualStyleBackColor = true; + buttonUpd.Click += buttonUpd_Click; // // buttonAdd // @@ -71,6 +74,7 @@ buttonAdd.TabIndex = 6; buttonAdd.Text = "Добавить"; buttonAdd.UseVisualStyleBackColor = true; + buttonAdd.Click += buttonAdd_Click; // // dataGridView // @@ -96,6 +100,7 @@ Margin = new Padding(3, 2, 3, 2); Name = "FormTravels"; Text = "Список туристических путёвок"; + Load += FormTravels_Load; ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); ResumeLayout(false); } diff --git a/TravelCompany/TravelCompany/FormTravels.cs b/TravelCompany/TravelCompany/FormTravels.cs index e83d830..b772ffd 100644 --- a/TravelCompany/TravelCompany/FormTravels.cs +++ b/TravelCompany/TravelCompany/FormTravels.cs @@ -1,6 +1,16 @@ -using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using TravelCompany; using TravelCompanyContracts.BindingModels; using TravelCompanyContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; namespace TravelCompany.Forms { @@ -8,7 +18,6 @@ namespace TravelCompany.Forms { private readonly ILogger _logger; private readonly ITravelLogic _logic; - public FormTravels(ILogger logger, ITravelLogic logic) { InitializeComponent(); @@ -16,7 +25,7 @@ namespace TravelCompany.Forms _logic = logic; } - private void FormTravel_Load(object sender, EventArgs e) + private void FormTravels_Load(object sender, EventArgs e) { LoadData(); } @@ -31,19 +40,17 @@ namespace TravelCompany.Forms dataGridView.DataSource = list; dataGridView.Columns["Id"].Visible = false; dataGridView.Columns["TravelComponents"].Visible = false; - dataGridView.Columns["TravelName"].AutoSizeMode = - DataGridViewAutoSizeColumnMode.Fill; + dataGridView.Columns["TravelName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; } - _logger.LogInformation("Загрузка пиццы"); + _logger.LogInformation("Загрузка путёвок"); } catch (Exception ex) { - _logger.LogError(ex, "Ошибка загрузки пиццы"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError(ex, "Ошибка загрузки компонентов"); } } - private void ButtonAdd_Click(object sender, EventArgs e) + private void buttonAdd_Click(object sender, EventArgs e) { var service = Program.ServiceProvider?.GetService(typeof(FormTravel)); if (service is FormTravel form) @@ -55,7 +62,7 @@ namespace TravelCompany.Forms } } - private void ButtonUpd_Click(object sender, EventArgs e) + private void buttonUpd_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) { @@ -71,14 +78,15 @@ namespace TravelCompany.Forms } } - private void ButtonDel_Click(object sender, EventArgs e) + private void buttonDel_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) { if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Удаление пиццы"); + int id = + Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Удаление путёвок"); try { if (!_logic.Delete(new TravelBindingModel @@ -92,14 +100,14 @@ namespace TravelCompany.Forms } catch (Exception ex) { - _logger.LogError(ex, "Ошибка удаления пиццы"); + _logger.LogError(ex, "Ошибка удаления путевки"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } } - private void ButtonRef_Click(object sender, EventArgs e) + private void buttonRef_Click(object sender, EventArgs e) { LoadData(); } diff --git a/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/OrderLogic.cs b/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/OrderLogic.cs index 2f2a393..7775715 100644 --- a/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/OrderLogic.cs +++ b/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/OrderLogic.cs @@ -1,15 +1,24 @@ -using Microsoft.Extensions.Logging; -using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.BindingModels; using TravelCompanyContracts.BusinessLogicsContracts; using TravelCompanyContracts.SearchModels; using TravelCompanyContracts.StoragesContracts; using TravelCompanyContracts.ViewModels; using TravelCompanyDataModels.Enums; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; -namespace TravelCompanyBusinessLogic.BusinessLogics +namespace TravelCompanyBusinessLogic.BusinessLogic { public class OrderLogic : IOrderLogic { + //Класс с логикой для заказов будет отвечать за получение списка заказов, + //создания заказа и смены его статусов. Следует учитывать, что у заказа можно + //менять статус на новый, если его текущий статус предшествует новому + private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; private readonly IShopStorage _shopStorage; @@ -20,6 +29,7 @@ namespace TravelCompanyBusinessLogic.BusinessLogics _orderStorage = orderStorage; _shopStorage = shopStorage; } + public List? ReadList(OrderSearchModel? model) { _logger.LogInformation("ReadList. OrderId:{Id}", model?.Id); @@ -32,14 +42,18 @@ namespace TravelCompanyBusinessLogic.BusinessLogics _logger.LogInformation("ReadList. Count:{Count}", list.Count); return list; } + public bool CreateOrder(OrderBindingModel model) { CheckModel(model); + if (model.Status != OrderStatus.Неизвестен) return false; model.Status = OrderStatus.Принят; + if (_orderStorage.Insert(model) == null) { + model.Status = OrderStatus.Неизвестен; _logger.LogWarning("Insert operation failed"); return false; } @@ -48,12 +62,12 @@ namespace TravelCompanyBusinessLogic.BusinessLogics public bool TakeOrderInWork(OrderBindingModel model) { - return ChangeStatus(model, OrderStatus.Выполняется); + return ToNextStatus(model, OrderStatus.Выполняется); } public bool FinishOrder(OrderBindingModel model) { - return ChangeStatus(model, OrderStatus.Готов); + return ToNextStatus(model, OrderStatus.Готов); } public bool DeliveryOrder(OrderBindingModel model) @@ -75,7 +89,47 @@ namespace TravelCompanyBusinessLogic.BusinessLogics throw new ArgumentException("Недостаточно места"); } - return ChangeStatus(model, OrderStatus.Выдан); + return ToNextStatus(model, OrderStatus.Выдан); + } + + public bool ToNextStatus(OrderBindingModel model, OrderStatus orderStatus) + { + CheckModel(model, false); + var element = _orderStorage.GetElement(new OrderSearchModel() + { + Id = model.Id + }); + if (element == null) + { + throw new ArgumentNullException(nameof(element)); + } + + model.TravelId = element.TravelId; + model.DateCreate = element.DateCreate; + model.DateImplement = element.DateImplement; + model.Status = element.Status; + model.Count = element.Count; + model.Sum = element.Sum; + + if (model.Status != orderStatus - 1) + { + _logger.LogWarning("Status update to " + orderStatus + " operation failed"); + return false; + } + model.Status = orderStatus; + + if (model.Status == OrderStatus.Выдан) + { + model.DateImplement = DateTime.Now; + } + + if (_orderStorage.Update(model) == null) + { + model.Status--; + _logger.LogWarning("Changing status operation faled"); + return false; + } + return true; } private void CheckModel(OrderBindingModel model, bool withParams = true) @@ -90,51 +144,17 @@ namespace TravelCompanyBusinessLogic.BusinessLogics } if (model.Count <= 0) { - throw new ArgumentException("Колличество пиццы в заказе не может быть меньше 1", nameof(model.Count)); + throw new ArgumentNullException("Количество изделий должно быть больше 0", nameof(model.Count)); } if (model.Sum <= 0) { - throw new ArgumentException("Стоимость заказа на может быть меньше 1", nameof(model.Sum)); + throw new ArgumentNullException("Цена заказа должна быть больше 0", nameof(model.Sum)); } if (model.DateImplement.HasValue && model.DateImplement < model.DateCreate) { - throw new ArithmeticException($"Дата выдачи заказа {model.DateImplement} не может быть раньше даты его создания {model.DateCreate}"); + throw new ArithmeticException($"Дата выдачи заказа {model.DateImplement} должна быть позже даты его создания {model.DateCreate}"); } - _logger.LogInformation("Travel. TravelId:{TravelId}.Count:{Count}.Sum:{Sum}Id:{Id}", - model.TravelId, model.Count, model.Sum, model.Id); - } - - private bool ChangeStatus(OrderBindingModel model, OrderStatus requiredStatus) - { - CheckModel(model, false); - var element = _orderStorage.GetElement(new OrderSearchModel() - { - Id = model.Id - }); - if (element == null) - { - throw new ArgumentNullException(nameof(element)); - } - model.DateCreate = element.DateCreate; - model.TravelId = element.TravelId; - model.DateImplement = element.DateImplement; - model.Status = element.Status; - model.Count = element.Count; - model.Sum = element.Sum; - if (requiredStatus - model.Status == 1) - { - model.Status = requiredStatus; - if (model.Status == OrderStatus.Выдан) - model.DateImplement = DateTime.Now; - if (_orderStorage.Update(model) == null) - { - _logger.LogWarning("Update operation failed"); - return false; - } - return true; - } - _logger.LogWarning("Changing status operation faled: Current-{Status}:required-{requiredStatus}.", model.Status, requiredStatus); - throw new ArgumentException($"Невозможно присвоить статус {requiredStatus} заказу с текущим статусом {model.Status}"); + _logger.LogInformation("Travel. TravelId:{TravelId}.Count:{Count}.Sum:{Sum}Id:{Id}", model.TravelId, model.Count, model.Sum, model.Id); } } } diff --git a/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/ShopLogic.cs b/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/ShopLogic.cs index 1021630..56cfe73 100644 --- a/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/ShopLogic.cs +++ b/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/ShopLogic.cs @@ -123,6 +123,10 @@ namespace TravelCompanyBusinessLogic.BusinessLogics { throw new ArgumentException($"Поставка: Товар с id:{model.TravelId} не найденн"); } + if (shop.ShopTravels.Sum(kv => kv.Value.Item2) + model.Count > shop.TravelMaxCount) + { + throw new ArgumentException("Превышена максимальная вместимость магазина"); + } shop.ShopTravels.Add(model.TravelId, (Travel, model.Count)); } @@ -139,6 +143,7 @@ namespace TravelCompanyBusinessLogic.BusinessLogics return true; } + private void CheckModel(ShopBindingModel model, bool withParams = true) { if (model == null)