Наконец-то я больше не буду делать такие бредовые слияния

This commit is contained in:
Николай 2023-03-24 01:03:00 +04:00
commit 31494e7dd6
32 changed files with 192 additions and 209 deletions

View File

@ -8,6 +8,16 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<None Remove="nlog.config" />
</ItemGroup>
<ItemGroup>
<Content Include="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.3">
<PrivateAssets>all</PrivateAssets>

View File

@ -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("Ошибка при сохранении. Дополнительная информация в логах.");

View File

@ -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<FormComponents> 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("Ошибка при удалении. Дополнительная информация в логах.");
}

View File

@ -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 = "Набор блюд:";
//

View File

@ -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<FormCreateOrder> 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("Расчет суммы заказа");

View File

@ -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;
//

View File

@ -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<int, (IComponentModel, int)> _dishComponents;
public int Id { set { _id = value; } }
@ -17,7 +17,7 @@ namespace FoodOrdersView
{
InitializeComponent();
_logger = logger;
_logic = logic;
_logicD = logic;
_dishComponents = new Dictionary<int, (IComponentModel, int)>();
}
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<int, (IComponentModel, int)>();
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("Ошибка при сохранении. Дополнительная информация в логах.");

View File

@ -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<FormDishes> 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
}))

View File

@ -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<FormMain> 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),

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)
{
_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("Компонент с таким названием уже есть");

View File

@ -24,10 +24,8 @@ namespace FoodOrdersBusinessLogic.BusinessLogics
public List<DishViewModel>? 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("Продукт с таким названием уже есть");
}
}
}

View File

@ -20,7 +20,7 @@ namespace FoodOrdersBusinessLogic.BusinessLogics
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);
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");

View File

@ -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<int, (IComponentModel, int)> DishComponents
{
get;
set;
} = new();
public Dictionary<int, (IComponentModel, int)> DishComponents { get; set; } = new();
}
}

View File

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

View File

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

View File

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

View File

@ -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;
}

View File

@ -9,30 +9,13 @@ namespace FoodOrdersDatabaseImplement.Implements
{
public class OrderStorage : IOrderStorage
{
public OrderViewModel? Delete(OrderBindingModel model)
public List<OrderViewModel> 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<OrderViewModel> 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<OrderViewModel> 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;
}
}
}

View File

@ -18,6 +18,7 @@ namespace FoodOrdersDatabaseImplement.Models
private Dictionary<int, (IComponentModel, int)>? _dishComponents = null;
//??
[NotMapped]
public Dictionary<int, (IComponentModel, int)> 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();
}

View File

@ -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)

View File

@ -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<T>? LoadData<T>(string filename, string xmlNodeName,
Func<XElement, T> selectFunction)
private static List<T>? LoadData<T>(string filename, string xmlNodeName, Func<XElement, T> 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<T>();
}
private static void SaveData<T>(List<T> data, string filename, string
xmlNodeName, Func<T, XElement> selectFunction)
private static void SaveData<T>(List<T> data, string filename, string xmlNodeName, Func<T, XElement> 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);
}
}
}

View File

@ -18,8 +18,7 @@ namespace FoodOrdersFileImplement.Implements
{
return _source.Components.Select(x => x.GetViewModel).ToList();
}
public List<ComponentViewModel> GetFilteredList(ComponentSearchModel
model)
public List<ComponentViewModel> 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);

View File

@ -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)
{

View File

@ -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;
}

View File

@ -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())
);
}
}

View File

@ -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<int, int> Components { get; private set; } = new();
private Dictionary<int, (IComponentModel, int)>? _dishComponents =
null;
private Dictionary<int, (IComponentModel, int)>? _dishComponents = null;
public Dictionary<int, (IComponentModel, int)> 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()
)
);
}
}

View File

@ -7,12 +7,12 @@ namespace FoodOrdersListImplement
private static DataListSingleton? _instance;
public List<Component> Components { get; set; }
public List<Order> Orders { get; set; }
public List<Dish> Dish { get; set; }
public List<Dish> Dishes { get; set; }
private DataListSingleton()
{
Components = new List<Component>();
Orders = new List<Order>();
Dish = new List<Dish>();
Dishes = new List<Dish>();
}
public static DataListSingleton GetInstance()
{

View File

@ -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)

View File

@ -16,21 +16,20 @@ namespace FoodOrdersListImplement.Implements
public List<DishViewModel> GetFullList()
{
var result = new List<DishViewModel>();
foreach (var dish in _source.Dish)
foreach (var dish in _source.Dishes)
{
result.Add(dish.GetViewModel);
}
return result;
}
public List<DishViewModel> GetFilteredList(DishSearchModel
model)
public List<DishViewModel> GetFilteredList(DishSearchModel model)
{
var result = new List<DishViewModel>();
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;
}
}

View File

@ -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)
{

View File

@ -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,