diff --git a/FoodOrders/FoodOrders/FoodOrdersView.csproj b/FoodOrders/FoodOrders/FoodOrdersView.csproj index 480e451..4581bf8 100644 --- a/FoodOrders/FoodOrders/FoodOrdersView.csproj +++ b/FoodOrders/FoodOrders/FoodOrdersView.csproj @@ -8,6 +8,16 @@ enable + + + + + + + Always + + + all diff --git a/FoodOrders/FoodOrders/FormComponent.cs b/FoodOrders/FoodOrders/FormComponent.cs index 03a5f08..29d6523 100644 --- a/FoodOrders/FoodOrders/FormComponent.cs +++ b/FoodOrders/FoodOrders/FormComponent.cs @@ -8,7 +8,7 @@ namespace FoodOrdersView public partial class FormComponent : Form { private readonly ILogger _logger; - private readonly IComponentLogic _logic; + private readonly IComponentLogic _logicC; private int? _id; public int Id { set { _id = value; } } @@ -16,7 +16,7 @@ namespace FoodOrdersView { InitializeComponent(); _logger = logger; - _logic = logic; + _logicC = logic; } private void FormComponent_Load(object sender, EventArgs e) @@ -26,7 +26,7 @@ namespace FoodOrdersView try { _logger.LogInformation("Получение блюда"); - var view = _logic.ReadElement(new ComponentSearchModel + var view = _logicC.ReadElement(new ComponentSearchModel { Id = _id.Value }); @@ -61,7 +61,7 @@ namespace FoodOrdersView ComponentName = textBoxName.Text, Cost = Convert.ToDouble(textBoxCost.Text) }; - var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model); + var operationResult = _id.HasValue ? _logicC.Update(model) : _logicC.Create(model); if (!operationResult) { throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); diff --git a/FoodOrders/FoodOrders/FormComponents.cs b/FoodOrders/FoodOrders/FormComponents.cs index 0f5f54b..4252aa5 100644 --- a/FoodOrders/FoodOrders/FormComponents.cs +++ b/FoodOrders/FoodOrders/FormComponents.cs @@ -7,12 +7,12 @@ namespace FoodOrdersView public partial class FormComponents : Form { private readonly ILogger _logger; - private readonly IComponentLogic _logic; + private readonly IComponentLogic _logicC; public FormComponents(ILogger logger, IComponentLogic logic) { InitializeComponent(); _logger = logger; - _logic = logic; + _logicC = logic; } private void FormComponents_Load(object sender, EventArgs e) { @@ -22,7 +22,7 @@ namespace FoodOrdersView { try { - var list = _logic.ReadList(null); + var list = _logicC.ReadList(null); if (list != null) { dataGridView.DataSource = list; @@ -74,10 +74,7 @@ namespace FoodOrdersView _logger.LogInformation("Удаление блюда"); try { - if (!_logic.Delete(new ComponentBindingModel - { - Id = id - })) + if (!_logicC.Delete(new ComponentBindingModel { Id = id })) { throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); } diff --git a/FoodOrders/FoodOrders/FormCreateOrder.Designer.cs b/FoodOrders/FoodOrders/FormCreateOrder.Designer.cs index dce3202..b4bba8f 100644 --- a/FoodOrders/FoodOrders/FormCreateOrder.Designer.cs +++ b/FoodOrders/FoodOrders/FormCreateOrder.Designer.cs @@ -65,6 +65,7 @@ this.textBoxSum.Location = new System.Drawing.Point(93, 63); this.textBoxSum.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); this.textBoxSum.Name = "textBoxSum"; + this.textBoxSum.ReadOnly = true; this.textBoxSum.Size = new System.Drawing.Size(230, 23); this.textBoxSum.TabIndex = 13; // @@ -110,7 +111,7 @@ this.labelName.AutoSize = true; this.labelName.Location = new System.Drawing.Point(12, 9); this.labelName.Name = "labelName"; - this.labelName.Size = new System.Drawing.Size(42, 15); + this.labelName.Size = new System.Drawing.Size(79, 15); this.labelName.TabIndex = 8; this.labelName.Text = "Набор блюд:"; // diff --git a/FoodOrders/FoodOrders/FormCreateOrder.cs b/FoodOrders/FoodOrders/FormCreateOrder.cs index 8ea24c8..b683deb 100644 --- a/FoodOrders/FoodOrders/FormCreateOrder.cs +++ b/FoodOrders/FoodOrders/FormCreateOrder.cs @@ -8,13 +8,13 @@ namespace FoodOrdersView public partial class FormCreateOrder : Form { private readonly ILogger _logger; - private readonly IDishLogic _logicS; + private readonly IDishLogic _logicD; private readonly IOrderLogic _logicO; public FormCreateOrder(ILogger logger, IDishLogic logicS, IOrderLogic logicO) { InitializeComponent(); _logger = logger; - _logicS = logicS; + _logicD = logicS; _logicO = logicO; } private void FormCreateOrder_Load(object sender, EventArgs e) @@ -22,7 +22,7 @@ namespace FoodOrdersView _logger.LogInformation("Загрузка Набор блюд для заказа"); try { - var list = _logicS.ReadList(null); + var list = _logicD.ReadList(null); if (list != null) { comboBoxDish.DisplayMember = "DishName"; @@ -45,10 +45,7 @@ namespace FoodOrdersView try { int id = Convert.ToInt32(comboBoxDish.SelectedValue); - var dish = _logicS.ReadElement(new DishSearchModel - { - Id = id - }); + var dish = _logicD.ReadElement(new DishSearchModel { Id = id }); int count = Convert.ToInt32(textBoxCount.Text); textBoxSum.Text = Math.Round(count * (dish?.Price ?? 0), 2).ToString(); _logger.LogInformation("Расчет суммы заказа"); diff --git a/FoodOrders/FoodOrders/FormDish.Designer.cs b/FoodOrders/FoodOrders/FormDish.Designer.cs index 4c0256c..f2d151a 100644 --- a/FoodOrders/FoodOrders/FormDish.Designer.cs +++ b/FoodOrders/FoodOrders/FormDish.Designer.cs @@ -52,6 +52,7 @@ this.textBoxPrice.Location = new System.Drawing.Point(90, 36); this.textBoxPrice.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); this.textBoxPrice.Name = "textBoxPrice"; + this.textBoxPrice.ReadOnly = true; this.textBoxPrice.Size = new System.Drawing.Size(138, 23); this.textBoxPrice.TabIndex = 7; // diff --git a/FoodOrders/FoodOrders/FormDish.cs b/FoodOrders/FoodOrders/FormDish.cs index 9182364..3d9ccee 100644 --- a/FoodOrders/FoodOrders/FormDish.cs +++ b/FoodOrders/FoodOrders/FormDish.cs @@ -9,7 +9,7 @@ namespace FoodOrdersView public partial class FormDish : Form { private readonly ILogger _logger; - private readonly IDishLogic _logic; + private readonly IDishLogic _logicD; private int? _id; private Dictionary _dishComponents; public int Id { set { _id = value; } } @@ -17,7 +17,7 @@ namespace FoodOrdersView { InitializeComponent(); _logger = logger; - _logic = logic; + _logicD = logic; _dishComponents = new Dictionary(); } private void FormDish_Load(object sender, EventArgs e) @@ -27,7 +27,7 @@ namespace FoodOrdersView _logger.LogInformation("Загрузка набор блюд"); try { - var view = _logic.ReadElement(new DishSearchModel + var view = _logicD.ReadElement(new DishSearchModel { Id = _id.Value }); @@ -35,6 +35,7 @@ namespace FoodOrdersView { textBoxName.Text = view.DishName; textBoxPrice.Text = view.Price.ToString(); + //если не null то слева, если null то справа _dishComponents = view.DishComponents ?? new Dictionary(); LoadData(); } @@ -55,9 +56,9 @@ namespace FoodOrdersView if (_dishComponents != null) { dataGridView.Rows.Clear(); - foreach (var sc in _dishComponents) + foreach (var dc in _dishComponents) { - dataGridView.Rows.Add(new object[] { sc.Key, sc.Value.Item1.ComponentName, sc.Value.Item2 }); + dataGridView.Rows.Add(new object[] { dc.Key, dc.Value.Item1.ComponentName, dc.Value.Item2 }); } textBoxPrice.Text = CalcPrice().ToString(); } @@ -82,13 +83,11 @@ namespace FoodOrdersView _logger.LogInformation("Добавление нового блюда: { ComponentName} - { Count}", form.ComponentModel.ComponentName, form.Count); if (_dishComponents.ContainsKey(form.Id)) { - _dishComponents[form.Id] = (form.ComponentModel, - form.Count); + _dishComponents[form.Id] = (form.ComponentModel, form.Count); } else { - _dishComponents.Add(form.Id, (form.ComponentModel, - form.Count)); + _dishComponents.Add(form.Id, (form.ComponentModel, form.Count)); } LoadData(); } @@ -101,8 +100,7 @@ namespace FoodOrdersView var service = Program.ServiceProvider?.GetService(typeof(FormDishComponents)); if (service is FormDishComponents form) { - int id = - Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value); + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value); form.Id = id; form.Count = _dishComponents[id].Item2; if (form.ShowDialog() == DialogResult.OK) @@ -127,8 +125,8 @@ namespace FoodOrdersView { try { - _logger.LogInformation("Удаление блюда: { ComponentName} - { Count} ", - dataGridView.SelectedRows[0].Cells[1].Value); _dishComponents?.Remove(Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value)); + _logger.LogInformation("Удаление блюда: { ComponentName} - { Count} ", dataGridView.SelectedRows[0].Cells[1].Value, dataGridView.SelectedRows[0].Cells[2].Value); + _dishComponents?.Remove(Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value)); } catch (Exception ex) { @@ -173,7 +171,7 @@ namespace FoodOrdersView Price = Convert.ToDouble(textBoxPrice.Text), DishComponents = _dishComponents }; - var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model); + var operationResult = _id.HasValue ? _logicD.Update(model) : _logicD.Create(model); if (!operationResult) { throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); diff --git a/FoodOrders/FoodOrders/FormDishes.cs b/FoodOrders/FoodOrders/FormDishes.cs index 8e4458e..d413b93 100644 --- a/FoodOrders/FoodOrders/FormDishes.cs +++ b/FoodOrders/FoodOrders/FormDishes.cs @@ -7,12 +7,12 @@ namespace FoodOrdersView public partial class FormDishes : Form { private readonly ILogger _logger; - private readonly IDishLogic _logic; + private readonly IDishLogic _logicD; public FormDishes(ILogger logger, IDishLogic logic) { InitializeComponent(); _logger = logger; - _logic = logic; + _logicD = logic; } private void FormDocuments_Load(object sender, EventArgs e) @@ -23,7 +23,7 @@ namespace FoodOrdersView { try { - var list = _logic.ReadList(null); + var list = _logicD.ReadList(null); if (list != null) { dataGridView.DataSource = list; @@ -78,7 +78,7 @@ namespace FoodOrdersView _logger.LogInformation("Удаление набор блюд"); try { - if (!_logic.Delete(new DishBindingModel + if (!_logicD.Delete(new DishBindingModel { Id = id })) diff --git a/FoodOrders/FoodOrders/FormMain.cs b/FoodOrders/FoodOrders/FormMain.cs index f614b59..d4e9a30 100644 --- a/FoodOrders/FoodOrders/FormMain.cs +++ b/FoodOrders/FoodOrders/FormMain.cs @@ -9,16 +9,15 @@ namespace FoodOrdersView public partial class FormMain : Form { private readonly ILogger _logger; + private readonly IOrderLogic _logicO; - private readonly IOrderLogic _orderLogic; - - private readonly IReportLogic _reportLogic; + private readonly IReportLogic _logicR; public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic) { InitializeComponent(); _logger = logger; - _orderLogic = orderLogic; - _reportLogic = reportLogic; + _logicO = orderLogic; + _logicR = reportLogic; } private void FormMain_Load(object sender, EventArgs e) { @@ -28,7 +27,7 @@ namespace FoodOrdersView { try { - var list = _orderLogic.ReadList(null); + var list = _logicO.ReadList(null); if (list != null) { dataGridView.DataSource = list; @@ -75,7 +74,7 @@ namespace FoodOrdersView _logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id); try { - var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel + var operationResult = _logicO.TakeOrderInWork(new OrderBindingModel { Id = id, DishId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["DishId"].Value), @@ -105,7 +104,7 @@ namespace FoodOrdersView _logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'", id); try { - var operationResult = _orderLogic.FinishOrder(new OrderBindingModel + var operationResult = _logicO.FinishOrder(new OrderBindingModel { Id = id, DishId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["DishId"].Value), @@ -135,7 +134,7 @@ namespace FoodOrdersView _logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id); try { - var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel + var operationResult = _logicO.DeliveryOrder(new OrderBindingModel { Id = id, DishId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["DishId"].Value), diff --git a/FoodOrders/FoodOrders/nlog.config b/FoodOrders/FoodOrders/nlog.config new file mode 100644 index 0000000..85797a7 --- /dev/null +++ b/FoodOrders/FoodOrders/nlog.config @@ -0,0 +1,15 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/FoodOrders/FoodOrdersBusinessLogic/BusinessLogics/ComponentLogic.cs b/FoodOrders/FoodOrdersBusinessLogic/BusinessLogics/ComponentLogic.cs index 7a86b71..b9f263b 100644 --- a/FoodOrders/FoodOrdersBusinessLogic/BusinessLogics/ComponentLogic.cs +++ b/FoodOrders/FoodOrdersBusinessLogic/BusinessLogics/ComponentLogic.cs @@ -19,10 +19,8 @@ namespace FoodOrdersBusinessLogic.BusinessLogics } public List? ReadList(ComponentSearchModel? model) { - _logger.LogInformation("ReadList. ComponentName:{ComponentName}. Id:{Id}", - model?.ComponentName, model?.Id); - var list = model == null ? _componentStorage.GetFullList() : - _componentStorage.GetFilteredList(model); + _logger.LogInformation("ReadList. ComponentName:{ComponentName}. Id:{Id}", model?.ComponentName, model?.Id); + var list = model == null ? _componentStorage.GetFullList() : _componentStorage.GetFilteredList(model); if (list == null) { _logger.LogWarning("ReadList return null list"); @@ -38,7 +36,7 @@ namespace FoodOrdersBusinessLogic.BusinessLogics throw new ArgumentNullException(nameof(model)); } _logger.LogInformation("ReadElement. ComponentName:{ComponentName}. Id:{Id}", model.ComponentName, model.Id); - var element = _componentStorage.GetElement(model); + var element = _componentStorage.GetElement(model); if (element == null) { _logger.LogWarning("ReadElement element not found"); @@ -78,8 +76,7 @@ namespace FoodOrdersBusinessLogic.BusinessLogics } return true; } - private void CheckModel(ComponentBindingModel model, bool withParams = - true) + private void CheckModel(ComponentBindingModel model, bool withParams = true) { if (model == null) { @@ -99,10 +96,10 @@ namespace FoodOrdersBusinessLogic.BusinessLogics throw new ArgumentNullException("Цена компонента должна быть больше 0", nameof(model.Cost)); } _logger.LogInformation("Component. ComponentName:{ComponentName}. Cost:{ Cost}. Id:{Id}", model.ComponentName, model.Cost, model.Id); - var element = _componentStorage.GetElement(new ComponentSearchModel - { - ComponentName = model.ComponentName - }); + var element = _componentStorage.GetElement(new ComponentSearchModel + { + ComponentName = model.ComponentName + }); if (element != null && element.Id != model.Id) { throw new InvalidOperationException("Компонент с таким названием уже есть"); diff --git a/FoodOrders/FoodOrdersBusinessLogic/BusinessLogics/DishLogic.cs b/FoodOrders/FoodOrdersBusinessLogic/BusinessLogics/DishLogic.cs index bd8e613..78cc2b7 100644 --- a/FoodOrders/FoodOrdersBusinessLogic/BusinessLogics/DishLogic.cs +++ b/FoodOrders/FoodOrdersBusinessLogic/BusinessLogics/DishLogic.cs @@ -24,10 +24,8 @@ namespace FoodOrdersBusinessLogic.BusinessLogics public List? ReadList(DishSearchModel? model) { - _logger.LogInformation("ReadList. DishName:{DishName}. Id:{Id}", - model?.DishName, model?.Id); - var list = model == null ? _dishStorage.GetFullList() : - _dishStorage.GetFilteredList(model); + _logger.LogInformation("ReadList. DishName:{DishName}. Id:{Id}", model?.DishName, model?.Id); + var list = model == null ? _dishStorage.GetFullList() : _dishStorage.GetFilteredList(model); if (list == null) { _logger.LogWarning("ReadList return null list"); @@ -111,7 +109,7 @@ namespace FoodOrdersBusinessLogic.BusinessLogics }); if (element != null && element.Id != model.Id) { - throw new InvalidOperationException("Прдукт с таким названием уже есть"); + throw new InvalidOperationException("Продукт с таким названием уже есть"); } } } diff --git a/FoodOrders/FoodOrdersBusinessLogic/BusinessLogics/OrderLogic.cs b/FoodOrders/FoodOrdersBusinessLogic/BusinessLogics/OrderLogic.cs index 43a2dfa..4ae8577 100644 --- a/FoodOrders/FoodOrdersBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/FoodOrders/FoodOrdersBusinessLogic/BusinessLogics/OrderLogic.cs @@ -20,7 +20,7 @@ namespace FoodOrdersBusinessLogic.BusinessLogics public List? ReadList(OrderSearchModel? model) { - _logger.LogInformation("ReadList. ComponentName:{ComponentName}. Id:{Id}", model?.Id); + _logger.LogInformation("ReadList. Id:{Id}", model?.Id); var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model); if (list == null) { @@ -89,7 +89,6 @@ namespace FoodOrdersBusinessLogic.BusinessLogics _logger.LogInformation("Order. OrderID:{Id}. Sum:{ Sum}. DishId: { DishId}", model.Id, model.Sum, model.Id); } - //??? public bool StatusUpdate(OrderBindingModel model, OrderStatus newStatus) { var viewModel = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id }); @@ -111,7 +110,7 @@ namespace FoodOrdersBusinessLogic.BusinessLogics { model.DateImplement = viewModel.DateImplement; } - CheckModel(model); + CheckModel(model, false); if (_orderStorage.Update(model) == null) { _logger.LogWarning("Change status operation failed"); diff --git a/FoodOrders/FoodOrdersContracts/BindingModels/DishBindingModel.cs b/FoodOrders/FoodOrdersContracts/BindingModels/DishBindingModel.cs index 982fcce..50c27f9 100644 --- a/FoodOrders/FoodOrdersContracts/BindingModels/DishBindingModel.cs +++ b/FoodOrders/FoodOrdersContracts/BindingModels/DishBindingModel.cs @@ -7,10 +7,6 @@ namespace FoodOrdersContracts.BindingModels public int Id { get; set; } public string DishName { get; set; } = string.Empty; public double Price { get; set; } - public Dictionary DishComponents - { - get; - set; - } = new(); + public Dictionary DishComponents { get; set; } = new(); } } diff --git a/FoodOrders/FoodOrdersContracts/BuisnessLogicsContracts/IComponentLogic.cs b/FoodOrders/FoodOrdersContracts/BuisnessLogicsContracts/IComponentLogic.cs index 2e830fd..adb0db5 100644 --- a/FoodOrders/FoodOrdersContracts/BuisnessLogicsContracts/IComponentLogic.cs +++ b/FoodOrders/FoodOrdersContracts/BuisnessLogicsContracts/IComponentLogic.cs @@ -6,6 +6,8 @@ namespace FoodOrdersContracts.BusinessLogicsContracts { public interface IComponentLogic { + //чтение листа, если модель есть то с фильтром, если модели нет то весь + // знак вопроса так как модет вернуть null, а в качестве параметра, так как модель может не передаваться List? ReadList(ComponentSearchModel? model); ComponentViewModel? ReadElement(ComponentSearchModel model); bool Create(ComponentBindingModel model); diff --git a/FoodOrders/FoodOrdersDataModels/Models/IDishModel.cs b/FoodOrders/FoodOrdersDataModels/Models/IDishModel.cs index cca6f22..3b4d8c4 100644 --- a/FoodOrders/FoodOrdersDataModels/Models/IDishModel.cs +++ b/FoodOrders/FoodOrdersDataModels/Models/IDishModel.cs @@ -3,6 +3,8 @@ namespace FoodOrdersDataModels.Models { public interface IDishModel : IId { + //в словаре первый int это id, то есть по id компонента найдём сам компонент + //дальше идёт кортеж в котором находиться уже копмонент и то сколько таких компонентов в данном блюде string DishName { get; } double Price { get; } Dictionary DishComponents { get; } diff --git a/FoodOrders/FoodOrdersDataModels/Models/IOrderModel.cs b/FoodOrders/FoodOrdersDataModels/Models/IOrderModel.cs index 134fd34..a0cfe81 100644 --- a/FoodOrders/FoodOrdersDataModels/Models/IOrderModel.cs +++ b/FoodOrders/FoodOrdersDataModels/Models/IOrderModel.cs @@ -9,6 +9,7 @@ namespace FoodOrdersDataModels.Models double Sum { get; } OrderStatus Status { get; } DateTime DateCreate { get; } + //через "?" обозначается что поле может быть null DateTime? DateImplement { get; } } } diff --git a/FoodOrders/FoodOrdersDatabaseImplement/Implements/ComponentStorage.cs b/FoodOrders/FoodOrdersDatabaseImplement/Implements/ComponentStorage.cs index cabf3f9..42bfaa2 100644 --- a/FoodOrders/FoodOrdersDatabaseImplement/Implements/ComponentStorage.cs +++ b/FoodOrders/FoodOrdersDatabaseImplement/Implements/ComponentStorage.cs @@ -37,8 +37,8 @@ namespace FoodOrdersDatabaseImplement.Implements } using var context = new FoodOrdersDatabase(); return context.Components - .FirstOrDefault(x => (!string.IsNullOrEmpty(model.ComponentName) && x.ComponentName == model.ComponentName) || - (model.Id.HasValue && x.Id == model.Id)) + .FirstOrDefault(x => (!string.IsNullOrEmpty(model.ComponentName) && x.ComponentName == model.ComponentName) || + (model.Id.HasValue && x.Id == model.Id)) ?.GetViewModel; } diff --git a/FoodOrders/FoodOrdersDatabaseImplement/Implements/OrderStorage.cs b/FoodOrders/FoodOrdersDatabaseImplement/Implements/OrderStorage.cs index 877b99f..a9e5222 100644 --- a/FoodOrders/FoodOrdersDatabaseImplement/Implements/OrderStorage.cs +++ b/FoodOrders/FoodOrdersDatabaseImplement/Implements/OrderStorage.cs @@ -9,30 +9,13 @@ namespace FoodOrdersDatabaseImplement.Implements { public class OrderStorage : IOrderStorage { - public OrderViewModel? Delete(OrderBindingModel model) + public List GetFullList() { - using var context = new FoodOrdersDatabase(); - var element = context.Orders - .FirstOrDefault(rec => rec.Id == model.Id); - if (element != null) - { - context.Orders.Remove(element); - context.SaveChanges(); - return element.GetViewModel; - } - return null; - } - - public OrderViewModel? GetElement(OrderSearchModel model) - { - if (!model.Id.HasValue) - { - return null; - } using var context = new FoodOrdersDatabase(); return context.Orders - .FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id) - ?.GetViewModel; + .Include(x => x.Dish) + .Select(x => x.GetViewModel) + .ToList(); } public List GetFilteredList(OrderSearchModel model) @@ -53,32 +36,17 @@ namespace FoodOrdersDatabaseImplement.Implements .ToList(); } - private static OrderViewModel GetViewModel(Order order) - { - var viewModel = order.GetViewModel; - using var context = new FoodOrdersDatabase(); - var element = context.Dishes - .FirstOrDefault(x => x.Id == order.DishId); - viewModel.DishName = element.DishName; - return viewModel; - } - - public List GetFullList() + public OrderViewModel? GetElement(OrderSearchModel model) { + if (!model.Id.HasValue) + { + return null; + } using var context = new FoodOrdersDatabase(); return context.Orders - .Select(x => new OrderViewModel - { - Id = x.Id, - DishId = x.DishId, - Count = x.Count, - Sum = x.Sum, - Status = x.Status, - DateCreate = x.DateCreate, - DateImplement = x.DateImplement, - DishName = x.Dish.DishName - }) - .ToList(); + .Include(x => x.Dish) + .FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id) + ?.GetViewModel; } public OrderViewModel? Insert(OrderBindingModel model) @@ -106,5 +74,17 @@ namespace FoodOrdersDatabaseImplement.Implements context.SaveChanges(); return order.GetViewModel; } + public OrderViewModel? Delete(OrderBindingModel model) + { + using var context = new FoodOrdersDatabase(); + var element = context.Orders.FirstOrDefault(rec => rec.Id == model.Id); + if (element != null) + { + context.Orders.Remove(element); + context.SaveChanges(); + return element.GetViewModel; + } + return null; + } } } diff --git a/FoodOrders/FoodOrdersDatabaseImplement/Models/Dish.cs b/FoodOrders/FoodOrdersDatabaseImplement/Models/Dish.cs index 9bbcaf4..43eadf7 100644 --- a/FoodOrders/FoodOrdersDatabaseImplement/Models/Dish.cs +++ b/FoodOrders/FoodOrdersDatabaseImplement/Models/Dish.cs @@ -18,6 +18,7 @@ namespace FoodOrdersDatabaseImplement.Models private Dictionary? _dishComponents = null; + //?? [NotMapped] public Dictionary DishComponents { @@ -25,8 +26,7 @@ namespace FoodOrdersDatabaseImplement.Models { if (_dishComponents == null) { - _dishComponents = Components - .ToDictionary(recPC => recPC.ComponentId, recPC => (recPC.Component as IComponentModel, recPC.Count)); + _dishComponents = Components.ToDictionary(recPC => recPC.ComponentId, recPC => (recPC.Component as IComponentModel, recPC.Count)); } return _dishComponents; } @@ -68,7 +68,7 @@ namespace FoodOrdersDatabaseImplement.Models { var dishComponents = context.DishComponents.Where(rec => rec.DishId == model.Id).ToList(); if (dishComponents != null && dishComponents.Count > 0) - { // удалили те, которых нет в модели + { // удалили те в бд, которых нет в модели context.DishComponents.RemoveRange(dishComponents.Where(rec => !model.DishComponents.ContainsKey(rec.ComponentId))); context.SaveChanges(); // обновили количество у существующих записей @@ -80,13 +80,14 @@ namespace FoodOrdersDatabaseImplement.Models context.SaveChanges(); } var dish = context.Dishes.First(x => x.Id == Id); - foreach (var pc in model.DishComponents) + //добавляем в бд блюда которые есть в моделе, но ещё нет в бд + foreach (var dc in model.DishComponents) { context.DishComponents.Add(new DishComponent { Dish = dish, - Component = context.Components.First(x => x.Id == pc.Key), - Count = pc.Value.Item2 + Component = context.Components.First(x => x.Id == dc.Key), + Count = dc.Value.Item2 }); context.SaveChanges(); } diff --git a/FoodOrders/FoodOrdersDatabaseImplement/Models/Order.cs b/FoodOrders/FoodOrdersDatabaseImplement/Models/Order.cs index 745dd07..9a5ac96 100644 --- a/FoodOrders/FoodOrdersDatabaseImplement/Models/Order.cs +++ b/FoodOrders/FoodOrdersDatabaseImplement/Models/Order.cs @@ -8,6 +8,8 @@ namespace FoodOrdersDatabaseImplement.Models { public class Order : IOrderModel { + public int Id { get; set; } + [Required] public int DishId { get; set; } @@ -27,8 +29,6 @@ namespace FoodOrdersDatabaseImplement.Models public DateTime? DateImplement { get; set; } - public int Id { get; set; } - public static Order? Create(OrderBindingModel? model) { if (model == null) diff --git a/FoodOrders/FoodOrdersFileImplement/DataFileSingleton.cs b/FoodOrders/FoodOrdersFileImplement/DataFileSingleton.cs index bbed037..b3e5803 100644 --- a/FoodOrders/FoodOrdersFileImplement/DataFileSingleton.cs +++ b/FoodOrders/FoodOrdersFileImplement/DataFileSingleton.cs @@ -19,37 +19,28 @@ namespace FoodOrdersFileImplement } return instance; } - public void SaveComponents() => SaveData(Components, ComponentFileName, - "Components", x => x.GetXElement); - public void SaveDishes() => SaveData(Dishes, DishFileName, - "Dishes", x => x.GetXElement); - public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x - => x.GetXElement); + public void SaveComponents() => SaveData(Components, ComponentFileName, "Components", x => x.GetXElement); + public void SaveDishes() => SaveData(Dishes, DishFileName, "Dishes", x => x.GetXElement); + public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement); private DataFileSingleton() { - Components = LoadData(ComponentFileName, "Component", x => - Component.Create(x)!)!; - Dishes = LoadData(DishFileName, "Dish", x => - Dish.Create(x)!)!; + Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!; + Dishes = LoadData(DishFileName, "Dish", x => Dish.Create(x)!)!; Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!; } - private static List? LoadData(string filename, string xmlNodeName, - Func selectFunction) + private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) { if (File.Exists(filename)) { - return - XDocument.Load(filename)?.Root?.Elements(xmlNodeName)?.Select(selectFunction)?.ToList(); + return XDocument.Load(filename)?.Root?.Elements(xmlNodeName)?.Select(selectFunction)?.ToList(); } return new List(); } - private static void SaveData(List data, string filename, string - xmlNodeName, Func selectFunction) + private static void SaveData(List data, string filename, string xmlNodeName, Func selectFunction) { if (data != null) { - new XDocument(new XElement(xmlNodeName, - data.Select(selectFunction).ToArray())).Save(filename); + new XDocument(new XElement(xmlNodeName, data.Select(selectFunction).ToArray())).Save(filename); } } } diff --git a/FoodOrders/FoodOrdersFileImplement/Implements/ComponentStorage.cs b/FoodOrders/FoodOrdersFileImplement/Implements/ComponentStorage.cs index 3fceecd..c7b5a12 100644 --- a/FoodOrders/FoodOrdersFileImplement/Implements/ComponentStorage.cs +++ b/FoodOrders/FoodOrdersFileImplement/Implements/ComponentStorage.cs @@ -18,8 +18,7 @@ namespace FoodOrdersFileImplement.Implements { return _source.Components.Select(x => x.GetViewModel).ToList(); } - public List GetFilteredList(ComponentSearchModel - model) + public List GetFilteredList(ComponentSearchModel model) { if (string.IsNullOrEmpty(model.ComponentName)) { @@ -27,6 +26,8 @@ namespace FoodOrdersFileImplement.Implements } return _source.Components.Where(x => x.ComponentName.Contains(model.ComponentName)).Select(x => x.GetViewModel).ToList(); } + + //FirstOrDefault выбирается первый или ничего, то есть вернёт первое совпадение или null public ComponentViewModel? GetElement(ComponentSearchModel model) { if (string.IsNullOrEmpty(model.ComponentName) && !model.Id.HasValue) @@ -37,8 +38,7 @@ namespace FoodOrdersFileImplement.Implements } public ComponentViewModel? Insert(ComponentBindingModel model) { - model.Id = _source.Components.Count > 0 ? _source.Components.Max(x => - x.Id) + 1 : 1; + model.Id = _source.Components.Count > 0 ? _source.Components.Max(x => x.Id) + 1 : 1; var newComponent = Component.Create(model); if (newComponent == null) { @@ -50,8 +50,7 @@ namespace FoodOrdersFileImplement.Implements } public ComponentViewModel? Update(ComponentBindingModel model) { - var component = _source.Components.FirstOrDefault(x => x.Id == - model.Id); + var component = _source.Components.FirstOrDefault(x => x.Id == model.Id); if (component == null) { return null; @@ -62,8 +61,7 @@ namespace FoodOrdersFileImplement.Implements } public ComponentViewModel? Delete(ComponentBindingModel model) { - var element = _source.Components.FirstOrDefault(x => x.Id == - model.Id); + var element = _source.Components.FirstOrDefault(x => x.Id == model.Id); if (element != null) { _source.Components.Remove(element); diff --git a/FoodOrders/FoodOrdersFileImplement/Implements/DishStorage.cs b/FoodOrders/FoodOrdersFileImplement/Implements/DishStorage.cs index 4688721..6dd0909 100644 --- a/FoodOrders/FoodOrdersFileImplement/Implements/DishStorage.cs +++ b/FoodOrders/FoodOrdersFileImplement/Implements/DishStorage.cs @@ -32,8 +32,7 @@ namespace FoodOrdersFileImplement.Implements { return null; } - return _source.Dishes - .FirstOrDefault(x => (!string.IsNullOrEmpty(model.DishName) && x.DishName == model.DishName) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; + return _source.Dishes.FirstOrDefault(x => (!string.IsNullOrEmpty(model.DishName) && x.DishName == model.DishName) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; } public DishViewModel? Insert(DishBindingModel model) { diff --git a/FoodOrders/FoodOrdersFileImplement/Implements/OrderStorage.cs b/FoodOrders/FoodOrdersFileImplement/Implements/OrderStorage.cs index 7452a64..2b2d218 100644 --- a/FoodOrders/FoodOrdersFileImplement/Implements/OrderStorage.cs +++ b/FoodOrders/FoodOrdersFileImplement/Implements/OrderStorage.cs @@ -3,6 +3,8 @@ using FoodOrdersContracts.SearchModels; using FoodOrdersContracts.StoragesContracts; using FoodOrdersContracts.ViewModels; using FoodOrdersFileImplement.Models; +using System.Reflection; +using System.Security.Cryptography.X509Certificates; namespace FoodOrdersFileImplement.Implements { @@ -34,21 +36,13 @@ namespace FoodOrdersFileImplement.Implements { return null; } - return _source.Orders - .FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; + return _source.Orders.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; } private OrderViewModel GetViewModel(Order order) { var viewModel = order.GetViewModel; - foreach (var dish in _source.Dishes) - { - if (dish.Id == order.DishId) - { - viewModel.DishName = dish.DishName; - break; - } - } + viewModel.DishName = _source.Dishes.FirstOrDefault(x => (x.Id == order.DishId))?.DishName; return viewModel; } diff --git a/FoodOrders/FoodOrdersFileImplement/Models/Component.cs b/FoodOrders/FoodOrdersFileImplement/Models/Component.cs index 8719134..951dad9 100644 --- a/FoodOrders/FoodOrdersFileImplement/Models/Component.cs +++ b/FoodOrders/FoodOrdersFileImplement/Models/Component.cs @@ -50,9 +50,11 @@ namespace FoodOrdersFileImplement.Models ComponentName = ComponentName, Cost = Cost }; - public XElement GetXElement => new("Component", - new XAttribute("Id", Id), - new XElement("ComponentName", ComponentName), - new XElement("Cost", Cost.ToString())); + public XElement GetXElement => new( + "Component", + new XAttribute("Id", Id), + new XElement("ComponentName", ComponentName), + new XElement("Cost", Cost.ToString()) + ); } } \ No newline at end of file diff --git a/FoodOrders/FoodOrdersFileImplement/Models/Dish.cs b/FoodOrders/FoodOrdersFileImplement/Models/Dish.cs index fb355f3..46cded5 100644 --- a/FoodOrders/FoodOrdersFileImplement/Models/Dish.cs +++ b/FoodOrders/FoodOrdersFileImplement/Models/Dish.cs @@ -8,11 +8,16 @@ namespace FoodOrdersFileImplement.Models public class Dish : IDishModel { public int Id { get; private set; } + public string DishName { get; private set; } = string.Empty; + public double Price { get; private set; } + + //словарь для файла, так как нам в файле нужно хранить просто id компонента и его количество public Dictionary Components { get; private set; } = new(); - private Dictionary? _dishComponents = - null; + + private Dictionary? _dishComponents = null; + public Dictionary DishComponents { get @@ -20,9 +25,7 @@ namespace FoodOrdersFileImplement.Models if (_dishComponents == null) { var _source = DataFileSingleton.GetInstance(); - _dishComponents = Components.ToDictionary(x => x.Key, y => - ((_source.Components.FirstOrDefault(z => z.Id == y.Key) as IComponentModel)!, - y.Value)); + _dishComponents = Components.ToDictionary(x => x.Key, y => ((_source.Components.FirstOrDefault(z => z.Id == y.Key) as IComponentModel)!, y.Value)); } return _dishComponents; } @@ -38,8 +41,7 @@ namespace FoodOrdersFileImplement.Models Id = model.Id, DishName = model.DishName, Price = model.Price, - Components = model.DishComponents.ToDictionary(x => x.Key, x - => x.Value.Item2) + Components = model.DishComponents.ToDictionary(x => x.Key, x => x.Value.Item2) }; } public static Dish? Create(XElement element) @@ -53,11 +55,7 @@ namespace FoodOrdersFileImplement.Models Id = Convert.ToInt32(element.Attribute("Id")!.Value), DishName = element.Element("DishName")!.Value, Price = Convert.ToDouble(element.Element("Price")!.Value), - Components = - element.Element("DishComponents")!.Elements("DishComponent") - .ToDictionary(x => - Convert.ToInt32(x.Element("Key")?.Value), x => - Convert.ToInt32(x.Element("Value")?.Value)) + Components = element.Element("DishComponents")!.Elements("DishComponent").ToDictionary(x => Convert.ToInt32(x.Element("Key")?.Value), x => Convert.ToInt32(x.Element("Value")?.Value)) }; } public void Update(DishBindingModel model) @@ -68,8 +66,9 @@ namespace FoodOrdersFileImplement.Models } DishName = model.DishName; Price = model.Price; - Components = model.DishComponents.ToDictionary(x => x.Key, x => - x.Value.Item2); + Components = model.DishComponents.ToDictionary(x => x.Key, x => x.Value.Item2); + //обнуляем словарь, чтобы в случае обновления, у нас был в дальнейшем сформирован актуальный словарь + // с помощью get метода _dishComponents = null; } public DishViewModel GetViewModel => new() @@ -79,17 +78,17 @@ namespace FoodOrdersFileImplement.Models Price = Price, DishComponents = DishComponents }; - public XElement GetXElement => new("Dish", - new XAttribute("Id", Id), - new XElement("DishName", DishName), - new XElement("Price", Price.ToString()), - new XElement("DishComponents", Components.Select(x => - new XElement("DishComponent", - new XElement("Key", x.Key), - - new XElement("Value", x.Value))) - - .ToArray())); + public XElement GetXElement => new( + "Dish", + new XAttribute("Id", Id), + new XElement("DishName", DishName), + new XElement("Price", Price.ToString()), + new XElement("DishComponents", Components.Select(x => + new XElement("DishComponent", + new XElement("Key", x.Key), + new XElement("Value", x.Value))).ToArray() + ) + ); } } diff --git a/FoodOrders/FoodOrdersListImplement/DataListSingleton.cs b/FoodOrders/FoodOrdersListImplement/DataListSingleton.cs index d8e4c35..87ce9fe 100644 --- a/FoodOrders/FoodOrdersListImplement/DataListSingleton.cs +++ b/FoodOrders/FoodOrdersListImplement/DataListSingleton.cs @@ -7,12 +7,12 @@ namespace FoodOrdersListImplement private static DataListSingleton? _instance; public List Components { get; set; } public List Orders { get; set; } - public List Dish { get; set; } + public List Dishes { get; set; } private DataListSingleton() { Components = new List(); Orders = new List(); - Dish = new List(); + Dishes = new List(); } public static DataListSingleton GetInstance() { diff --git a/FoodOrders/FoodOrdersListImplement/Implements/ComponentStorage.cs b/FoodOrders/FoodOrdersListImplement/Implements/ComponentStorage.cs index d8ba6cb..6986ceb 100644 --- a/FoodOrders/FoodOrdersListImplement/Implements/ComponentStorage.cs +++ b/FoodOrders/FoodOrdersListImplement/Implements/ComponentStorage.cs @@ -88,6 +88,8 @@ namespace FoodOrdersListImplement.Implements } public ComponentViewModel? Delete(ComponentBindingModel model) { + // не юзаем foreach так как при изменении данных (добавление и удаление записей) коллекции foreach ломается + // если бы просто меняли значение записи всё было бы в порядке for (int i = 0; i < _source.Components.Count; ++i) { if (_source.Components[i].Id == model.Id) diff --git a/FoodOrders/FoodOrdersListImplement/Implements/DishStorage.cs b/FoodOrders/FoodOrdersListImplement/Implements/DishStorage.cs index c751142..1956a9d 100644 --- a/FoodOrders/FoodOrdersListImplement/Implements/DishStorage.cs +++ b/FoodOrders/FoodOrdersListImplement/Implements/DishStorage.cs @@ -16,21 +16,20 @@ namespace FoodOrdersListImplement.Implements public List GetFullList() { var result = new List(); - foreach (var dish in _source.Dish) + foreach (var dish in _source.Dishes) { result.Add(dish.GetViewModel); } return result; } - public List GetFilteredList(DishSearchModel - model) + public List GetFilteredList(DishSearchModel model) { var result = new List(); if (string.IsNullOrEmpty(model.DishName)) { return result; } - foreach (var dish in _source.Dish) + foreach (var dish in _source.Dishes) { if (dish.DishName.Contains(model.DishName)) { @@ -45,11 +44,9 @@ namespace FoodOrdersListImplement.Implements { return null; } - foreach (var dish in _source.Dish) + foreach (var dish in _source.Dishes) { - if ((!string.IsNullOrEmpty(model.DishName) && - dish.DishName == model.DishName) || - (model.Id.HasValue && dish.Id == model.Id)) + if ((!string.IsNullOrEmpty(model.DishName) && dish.DishName == model.DishName) || (model.Id.HasValue && dish.Id == model.Id)) { return dish.GetViewModel; } @@ -59,7 +56,7 @@ namespace FoodOrdersListImplement.Implements public DishViewModel? Insert(DishBindingModel model) { model.Id = 1; - foreach (var dish in _source.Dish) + foreach (var dish in _source.Dishes) { if (model.Id <= dish.Id) { @@ -71,12 +68,12 @@ namespace FoodOrdersListImplement.Implements { return null; } - _source.Dish.Add(newDish); + _source.Dishes.Add(newDish); return newDish.GetViewModel; } public DishViewModel? Update(DishBindingModel model) { - foreach (var dish in _source.Dish) + foreach (var dish in _source.Dishes) { if (dish.Id == model.Id) { @@ -88,12 +85,12 @@ namespace FoodOrdersListImplement.Implements } public DishViewModel? Delete(DishBindingModel model) { - for (int i = 0; i < _source.Dish.Count; ++i) + for (int i = 0; i < _source.Dishes.Count; ++i) { - if (_source.Dish[i].Id == model.Id) + if (_source.Dishes[i].Id == model.Id) { - var element = _source.Dish[i]; - _source.Dish.RemoveAt(i); + var element = _source.Dishes[i]; + _source.Dishes.RemoveAt(i); return element.GetViewModel; } } diff --git a/FoodOrders/FoodOrdersListImplement/Implements/OrderStorage.cs b/FoodOrders/FoodOrdersListImplement/Implements/OrderStorage.cs index 1a77a87..4566b8b 100644 --- a/FoodOrders/FoodOrdersListImplement/Implements/OrderStorage.cs +++ b/FoodOrders/FoodOrdersListImplement/Implements/OrderStorage.cs @@ -65,7 +65,7 @@ namespace FoodOrdersListImplement.Implements private OrderViewModel GetViewModel(Order order) { var viewModel = order.GetViewModel; - foreach (var dish in _source.Dish) + foreach (var dish in _source.Dishes) { if (dish.Id == order.DishId) { diff --git a/FoodOrders/FoodOrdersListImplement/Models/Component.cs b/FoodOrders/FoodOrdersListImplement/Models/Component.cs index 2510fb9..9ae5b6a 100644 --- a/FoodOrders/FoodOrdersListImplement/Models/Component.cs +++ b/FoodOrders/FoodOrdersListImplement/Models/Component.cs @@ -4,11 +4,14 @@ using FoodOrdersDataModels.Models; namespace FoodOrdersListImplement.Models { + //класс отвечает не только за хранение данных но также и за их изменение public class Component : IComponentModel { public int Id { get; private set; } public string ComponentName { get; private set; } = string.Empty; public double Cost { get; set; } + + //создаём из ComponentBindingModel Component public static Component? Create(ComponentBindingModel? model) { if (model == null) @@ -22,6 +25,8 @@ namespace FoodOrdersListImplement.Models Cost = model.Cost }; } + + //изменённые данные из бизнес-логики передаём в поля Component public void Update(ComponentBindingModel? model) { if (model == null) @@ -31,6 +36,8 @@ namespace FoodOrdersListImplement.Models ComponentName = model.ComponentName; Cost = model.Cost; } + + //получение ComponentViewModel из Component public ComponentViewModel GetViewModel => new() { Id = Id,