From 80399cca5efd2c4ebcef693947875ca9600d041b Mon Sep 17 00:00:00 2001 From: goldfest Date: Fri, 5 Apr 2024 00:15:35 +0400 Subject: [PATCH] =?UTF-8?q?=D0=B4=D0=BE=20=D0=BA=D0=BE=D0=BD=D1=86=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)