This commit is contained in:
Николай 2023-03-11 19:13:24 +04:00
parent b0fbd900d3
commit da162462b5
15 changed files with 60 additions and 36 deletions

View File

@ -8,6 +8,16 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<None Remove="nlog.config" />
</ItemGroup>
<ItemGroup>
<Content Include="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" /> <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" /> <PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />

View File

@ -74,10 +74,7 @@ namespace FoodOrdersView
_logger.LogInformation("Удаление блюда"); _logger.LogInformation("Удаление блюда");
try try
{ {
if (!_logic.Delete(new ComponentBindingModel if (!_logic.Delete(new ComponentBindingModel { Id = id }))
{
Id = id
}))
{ {
throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
} }

View File

@ -45,10 +45,7 @@ namespace FoodOrdersView
try try
{ {
int id = Convert.ToInt32(comboBoxDish.SelectedValue); int id = Convert.ToInt32(comboBoxDish.SelectedValue);
var product = _logicS.ReadElement(new DishSearchModel var product = _logicS.ReadElement(new DishSearchModel { Id = id });
{
Id = id
});
int count = Convert.ToInt32(textBoxCount.Text); int count = Convert.ToInt32(textBoxCount.Text);
textBoxSum.Text = Math.Round(count * (product?.Price ?? 0), 2).ToString(); textBoxSum.Text = Math.Round(count * (product?.Price ?? 0), 2).ToString();
_logger.LogInformation("Расчет суммы заказа"); _logger.LogInformation("Расчет суммы заказа");

View File

@ -52,6 +52,7 @@
this.textBoxPrice.Location = new System.Drawing.Point(90, 36); this.textBoxPrice.Location = new System.Drawing.Point(90, 36);
this.textBoxPrice.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); this.textBoxPrice.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.textBoxPrice.Name = "textBoxPrice"; this.textBoxPrice.Name = "textBoxPrice";
this.textBoxPrice.ReadOnly = true;
this.textBoxPrice.Size = new System.Drawing.Size(138, 23); this.textBoxPrice.Size = new System.Drawing.Size(138, 23);
this.textBoxPrice.TabIndex = 7; this.textBoxPrice.TabIndex = 7;
// //

View File

@ -35,6 +35,7 @@ namespace FoodOrdersView
{ {
textBoxName.Text = view.DishName; textBoxName.Text = view.DishName;
textBoxPrice.Text = view.Price.ToString(); textBoxPrice.Text = view.Price.ToString();
//если не null то слева, если null то справа
_dishComponents = view.DishComponents ?? new Dictionary<int, (IComponentModel, int)>(); _dishComponents = view.DishComponents ?? new Dictionary<int, (IComponentModel, int)>();
LoadData(); LoadData();
} }
@ -82,13 +83,11 @@ namespace FoodOrdersView
_logger.LogInformation("Добавление нового блюда: { ComponentName} - { Count}", form.ComponentModel.ComponentName, form.Count); _logger.LogInformation("Добавление нового блюда: { ComponentName} - { Count}", form.ComponentModel.ComponentName, form.Count);
if (_dishComponents.ContainsKey(form.Id)) if (_dishComponents.ContainsKey(form.Id))
{ {
_dishComponents[form.Id] = (form.ComponentModel, _dishComponents[form.Id] = (form.ComponentModel, form.Count);
form.Count);
} }
else else
{ {
_dishComponents.Add(form.Id, (form.ComponentModel, _dishComponents.Add(form.Id, (form.ComponentModel, form.Count));
form.Count));
} }
LoadData(); LoadData();
} }
@ -101,8 +100,7 @@ namespace FoodOrdersView
var service = Program.ServiceProvider?.GetService(typeof(FormDishComponents)); var service = Program.ServiceProvider?.GetService(typeof(FormDishComponents));
if (service is FormDishComponents form) if (service is FormDishComponents form)
{ {
int id = int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value);
Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value);
form.Id = id; form.Id = id;
form.Count = _dishComponents[id].Item2; form.Count = _dishComponents[id].Item2;
if (form.ShowDialog() == DialogResult.OK) if (form.ShowDialog() == DialogResult.OK)
@ -127,8 +125,8 @@ namespace FoodOrdersView
{ {
try try
{ {
_logger.LogInformation("Удаление блюда: { ComponentName} - { Count} ", _logger.LogInformation("Удаление блюда: { ComponentName} - { Count} ", dataGridView.SelectedRows[0].Cells[1].Value, dataGridView.SelectedRows[0].Cells[2].Value);
dataGridView.SelectedRows[0].Cells[1].Value); _dishComponents?.Remove(Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value)); _dishComponents?.Remove(Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value));
} }
catch (Exception ex) catch (Exception ex)
{ {

View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true" internalLogLevel="Info">
<targets>
<target xsi:type="File" name="tofile" fileName="log-${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile" />
</rules>
</nlog>
</configuration>

View File

@ -19,10 +19,8 @@ namespace FoodOrdersBusinessLogic.BusinessLogics
} }
public List<ComponentViewModel>? ReadList(ComponentSearchModel? model) public List<ComponentViewModel>? ReadList(ComponentSearchModel? model)
{ {
_logger.LogInformation("ReadList. ComponentName:{ComponentName}. Id:{Id}", _logger.LogInformation("ReadList. ComponentName:{ComponentName}. Id:{Id}", model?.ComponentName, model?.Id);
model?.ComponentName, model?.Id); var list = model == null ? _componentStorage.GetFullList() : _componentStorage.GetFilteredList(model);
var list = model == null ? _componentStorage.GetFullList() :
_componentStorage.GetFilteredList(model);
if (list == null) if (list == null)
{ {
_logger.LogWarning("ReadList return null list"); _logger.LogWarning("ReadList return null list");
@ -38,7 +36,7 @@ namespace FoodOrdersBusinessLogic.BusinessLogics
throw new ArgumentNullException(nameof(model)); throw new ArgumentNullException(nameof(model));
} }
_logger.LogInformation("ReadElement. ComponentName:{ComponentName}. Id:{Id}", model.ComponentName, model.Id); _logger.LogInformation("ReadElement. ComponentName:{ComponentName}. Id:{Id}", model.ComponentName, model.Id);
var element = _componentStorage.GetElement(model); var element = _componentStorage.GetElement(model);
if (element == null) if (element == null)
{ {
_logger.LogWarning("ReadElement element not found"); _logger.LogWarning("ReadElement element not found");
@ -78,8 +76,7 @@ namespace FoodOrdersBusinessLogic.BusinessLogics
} }
return true; return true;
} }
private void CheckModel(ComponentBindingModel model, bool withParams = private void CheckModel(ComponentBindingModel model, bool withParams = true)
true)
{ {
if (model == null) if (model == null)
{ {
@ -99,10 +96,10 @@ namespace FoodOrdersBusinessLogic.BusinessLogics
throw new ArgumentNullException("Цена компонента должна быть больше 0", nameof(model.Cost)); throw new ArgumentNullException("Цена компонента должна быть больше 0", nameof(model.Cost));
} }
_logger.LogInformation("Component. ComponentName:{ComponentName}. Cost:{ Cost}. Id:{Id}", model.ComponentName, model.Cost, model.Id); _logger.LogInformation("Component. ComponentName:{ComponentName}. Cost:{ Cost}. Id:{Id}", model.ComponentName, model.Cost, model.Id);
var element = _componentStorage.GetElement(new ComponentSearchModel var element = _componentStorage.GetElement(new ComponentSearchModel
{ {
ComponentName = model.ComponentName ComponentName = model.ComponentName
}); });
if (element != null && element.Id != model.Id) if (element != null && element.Id != model.Id)
{ {
throw new InvalidOperationException("Компонент с таким названием уже есть"); throw new InvalidOperationException("Компонент с таким названием уже есть");

View File

@ -111,7 +111,7 @@ namespace FoodOrdersBusinessLogic.BusinessLogics
}); });
if (element != null && element.Id != model.Id) if (element != null && element.Id != model.Id)
{ {
throw new InvalidOperationException("Прдукт с таким названием уже есть"); throw new InvalidOperationException("Продукт с таким названием уже есть");
} }
} }
} }

View File

@ -20,7 +20,7 @@ namespace FoodOrdersBusinessLogic.BusinessLogics
public List<OrderViewModel>? ReadList(OrderSearchModel? model) public List<OrderViewModel>? 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); var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model);
if (list == null) 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); _logger.LogInformation("Order. OrderID:{Id}. Sum:{ Sum}. DishId: { DishId}", model.Id, model.Sum, model.Id);
} }
//???
public bool StatusUpdate(OrderBindingModel model, OrderStatus newStatus) public bool StatusUpdate(OrderBindingModel model, OrderStatus newStatus)
{ {
var viewModel = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id }); var viewModel = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id });
@ -111,7 +110,7 @@ namespace FoodOrdersBusinessLogic.BusinessLogics
{ {
model.DateImplement = viewModel.DateImplement; model.DateImplement = viewModel.DateImplement;
} }
CheckModel(model); CheckModel(model, false);
if (_orderStorage.Update(model) == null) if (_orderStorage.Update(model) == null)
{ {
_logger.LogWarning("Change status operation failed"); _logger.LogWarning("Change status operation failed");

View File

@ -7,10 +7,6 @@ namespace FoodOrdersContracts.BindingModels
public int Id { get; set; } public int Id { get; set; }
public string DishName { get; set; } = string.Empty; public string DishName { get; set; } = string.Empty;
public double Price { get; set; } public double Price { get; set; }
public Dictionary<int, (IComponentModel, int)> DishComponents public Dictionary<int, (IComponentModel, int)> DishComponents { get; set; } = new();
{
get;
set;
} = new();
} }
} }

View File

@ -6,6 +6,8 @@ namespace FoodOrdersContracts.BusinessLogicsContracts
{ {
public interface IComponentLogic public interface IComponentLogic
{ {
//чтение листа, если модель есть то с фильтром, если модели нет то весь
// знак вопроса так как модет вернуть null, а в качестве параметра, так как модель может не передаваться
List<ComponentViewModel>? ReadList(ComponentSearchModel? model); List<ComponentViewModel>? ReadList(ComponentSearchModel? model);
ComponentViewModel? ReadElement(ComponentSearchModel model); ComponentViewModel? ReadElement(ComponentSearchModel model);
bool Create(ComponentBindingModel model); bool Create(ComponentBindingModel model);

View File

@ -3,6 +3,8 @@ namespace FoodOrdersDataModels.Models
{ {
public interface IDishModel : IId public interface IDishModel : IId
{ {
//в словаре первый int это id, то есть по id компонента найдём сам компонент
//дальше идёт кортеж в котором находиться уже копмонент и то сколько таких компонентов в данном блюде
string DishName { get; } string DishName { get; }
double Price { get; } double Price { get; }
Dictionary<int, (IComponentModel, int)> DishComponents { get; } Dictionary<int, (IComponentModel, int)> DishComponents { get; }

View File

@ -9,6 +9,7 @@ namespace FoodOrdersDataModels.Models
double Sum { get; } double Sum { get; }
OrderStatus Status { get; } OrderStatus Status { get; }
DateTime DateCreate { get; } DateTime DateCreate { get; }
//через "?" обозначается что поле может быть null
DateTime? DateImplement { get; } DateTime? DateImplement { get; }
} }
} }

View File

@ -88,6 +88,8 @@ namespace FoodOrdersListImplement.Implements
} }
public ComponentViewModel? Delete(ComponentBindingModel model) public ComponentViewModel? Delete(ComponentBindingModel model)
{ {
// не юзаем foreach так как при изменении данных (добавление и удаление записей) коллекции foreach ломается
// если бы просто меняли значение записи всё было бы в порядке
for (int i = 0; i < _source.Components.Count; ++i) for (int i = 0; i < _source.Components.Count; ++i)
{ {
if (_source.Components[i].Id == model.Id) if (_source.Components[i].Id == model.Id)

View File

@ -4,11 +4,14 @@ using FoodOrdersDataModels.Models;
namespace FoodOrdersListImplement.Models namespace FoodOrdersListImplement.Models
{ {
//класс отвечает не только за хранение данных но также и за их изменение
public class Component : IComponentModel public class Component : IComponentModel
{ {
public int Id { get; private set; } public int Id { get; private set; }
public string ComponentName { get; private set; } = string.Empty; public string ComponentName { get; private set; } = string.Empty;
public double Cost { get; set; } public double Cost { get; set; }
//создаём из ComponentBindingModel Component
public static Component? Create(ComponentBindingModel? model) public static Component? Create(ComponentBindingModel? model)
{ {
if (model == null) if (model == null)
@ -22,6 +25,8 @@ namespace FoodOrdersListImplement.Models
Cost = model.Cost Cost = model.Cost
}; };
} }
//изменённые данные из бизнес-логики передаём в поля Component
public void Update(ComponentBindingModel? model) public void Update(ComponentBindingModel? model)
{ {
if (model == null) if (model == null)
@ -31,6 +36,8 @@ namespace FoodOrdersListImplement.Models
ComponentName = model.ComponentName; ComponentName = model.ComponentName;
Cost = model.Cost; Cost = model.Cost;
} }
//получение ComponentViewModel из Component
public ComponentViewModel GetViewModel => new() public ComponentViewModel GetViewModel => new()
{ {
Id = Id, Id = Id,