Лаб_2сложн

This commit is contained in:
yuliya.mavrina@internet.ru 2024-05-19 23:49:58 +03:00
parent 80550c60fd
commit 136591c7a7
5 changed files with 497 additions and 516 deletions

View File

@ -10,6 +10,7 @@ using System.Windows.Forms;
using RenovationWorkContracts.BindingModels; using RenovationWorkContracts.BindingModels;
using RenovationWorkContracts.BusinessLogicsContracts; using RenovationWorkContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using RenovationWorkDataModels.Enums;
namespace RenovationWorkView namespace RenovationWorkView
{ {
@ -76,54 +77,67 @@ namespace RenovationWorkView
} }
} }
private void buttonTakeOrderInWork_Click(object sender, EventArgs e) private OrderBindingModel CreateBindingModel(int id, bool isDone = false)
{ {
if (dataGridView.SelectedRows.Count == 1) return new OrderBindingModel
{ {
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); Id = id,
_logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id); RepairId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["RepairId"].Value),
try Status = Enum.Parse<OrderStatus>(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()),
{ Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value),
var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel { Id = id }); Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()),
if (!operationResult) DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()),
{ };
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); }
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка передачи заказа в работу");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void buttonOrderReady_Click(object sender, EventArgs e) private void buttonTakeOrderInWork_Click(object sender, EventArgs e)
{ {
if (dataGridView.SelectedRows.Count == 1) if (dataGridView.SelectedRows.Count == 1)
{ {
int id = int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); _logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'", id); try
try {
{ var operationResult = _orderLogic.TakeOrderInWork(CreateBindingModel(id));
var operationResult = _orderLogic.FinishOrder(new OrderBindingModel { Id = id }); if (!operationResult)
if (!operationResult) {
{ throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); }
} LoadData();
LoadData(); }
} catch (Exception ex)
catch (Exception ex) {
{ _logger.LogError(ex, "Ошибка передачи заказа в работу");
_logger.LogError(ex, "Ошибка отметки о готовности заказа"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); }
} }
} }
}
private void buttonIssuedOrder_Click(object sender, EventArgs e) private void buttonOrderReady_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'", id);
try
{
var operationResult = _orderLogic.FinishOrder(CreateBindingModel(id));
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о готовности заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void buttonIssuedOrder_Click(object sender, EventArgs e)
{ {
if (dataGridView.SelectedRows.Count == 1) if (dataGridView.SelectedRows.Count == 1)
{ {
@ -131,7 +145,7 @@ namespace RenovationWorkView
_logger.LogInformation("Заказ No{id}. Меняется статус на 'Выдан'", id); _logger.LogInformation("Заказ No{id}. Меняется статус на 'Выдан'", id);
try try
{ {
var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel {Id = id}); var operationResult = _orderLogic.DeliveryOrder(CreateBindingModel(id));
if (!operationResult) if (!operationResult)
{ {
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
@ -147,7 +161,7 @@ namespace RenovationWorkView
} }
} }
private void buttonRef_Click(object sender, EventArgs e) private void buttonRef_Click(object sender, EventArgs e)
{ {
LoadData(); LoadData();
} }

View File

@ -14,123 +14,99 @@ using Microsoft.Extensions.Logging;
namespace RenovationWorkBusinessLogic.BusinessLogics namespace RenovationWorkBusinessLogic.BusinessLogics
{ {
public class OrderLogic : IOrderLogic public class OrderLogic : IOrderLogic
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage; private readonly IOrderStorage _orderStorage;
private readonly IShopLogic _shopLogic; private readonly IShopLogic _shopLogic;
private readonly IRepairStorage _repairStorage; private readonly IRepairStorage _repairStorage;
private readonly IShopStorage _shopStorage; private readonly IShopStorage _shopStorage;
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage, public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage,
IRepairStorage repairStorage, IShopLogic shopLogic, IShopStorage shopStorage) IRepairStorage repairStorage, IShopLogic shopLogic, IShopStorage shopStorage)
{ {
_logger = logger; _logger = logger;
_orderStorage = orderStorage; _orderStorage = orderStorage;
_repairStorage = repairStorage; _repairStorage = repairStorage;
_shopLogic = shopLogic; _shopLogic = shopLogic;
_shopStorage = shopStorage; _shopStorage = shopStorage;
} }
public bool CreateOrder(OrderBindingModel model) public bool CreateOrder(OrderBindingModel model)
{ {
CheckModel(model); CheckModel(model);
if (model.Status != OrderStatus.Неизвестен) if (model.Status != OrderStatus.Неизвестен)
{ {
_logger.LogWarning("Insert operation failed. Order status incorrect."); _logger.LogWarning("Insert operation failed. Order status incorrect.");
return false; return false;
} }
model.Status = OrderStatus.Принят; model.Status = OrderStatus.Принят;
if (_orderStorage.Insert(model) == null) if (_orderStorage.Insert(model) == null)
{ {
model.Status = OrderStatus.Неизвестен; model.Status = OrderStatus.Неизвестен;
_logger.LogWarning("Insert operation failed"); _logger.LogWarning("Insert operation failed");
return false; return false;
} }
return true; return true;
} }
private bool StatusUpdate(OrderBindingModel model, OrderStatus status) private bool StatusUpdate(OrderBindingModel model, OrderStatus status)
{ {
var element = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id }); CheckModel(model);
if (element == null) var element = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id });
{ if (element == null)
_logger.LogWarning("Read operation failed"); {
return false; _logger.LogWarning("Read operation failed");
} return false;
CheckModel(element); }
if (element.Status != status - 1) if (element.Status != status - 1)
{ {
_logger.LogWarning("Status change operation failed"); _logger.LogWarning("Status change operation failed");
throw new InvalidOperationException("Текущий статус заказа не может быть переведен в выбранный"); throw new InvalidOperationException("Текущий статус заказа не может быть переведен в выбранный");
} }
if (element.Status == OrderStatus.Готов) if (element.Status == OrderStatus.Готов)
{ {
var repair = _repairStorage.GetElement(new RepairSearchModel() { Id = model.RepairId }); var repair = _repairStorage.GetElement(new RepairSearchModel() { Id = model.RepairId });
if (repair == null) if (repair == null)
{ {
_logger.LogWarning("Status update to " + status.ToString() + " operation failed. Document not found."); _logger.LogWarning("Status update to " + status.ToString() + " operation failed. Document not found.");
return false; return false;
} }
if (CheckSupply(repair, model.Count) == false) if (CheckSupply(repair, model.Count) == false)
{ {
_logger.LogWarning("Status update to " + status.ToString() + " operation failed. Shop supply error."); _logger.LogWarning("Status update to " + status.ToString() + " operation failed. Shop supply error.");
return false; return false;
} }
} }
model.Status = status; model.Status = status;
if (model.Status == OrderStatus.Выдан) if (model.Status == OrderStatus.Выдан)
model.DateImplement = DateTime.Now; model.DateImplement = DateTime.Now;
_orderStorage.Update(model); _orderStorage.Update(model);
return true; return true;
} }
public bool DeliveryOrder(OrderBindingModel model) public bool DeliveryOrder(OrderBindingModel model)
{ {
return StatusUpdate(model, OrderStatus.Выдан); return StatusUpdate(model, OrderStatus.Выдан);
} }
public bool FinishOrder(OrderBindingModel model) public bool FinishOrder(OrderBindingModel model)
{ {
return StatusUpdate(model, OrderStatus.Готов); return StatusUpdate(model, OrderStatus.Готов);
} }
public bool TakeOrderInWork(OrderBindingModel model) public bool TakeOrderInWork(OrderBindingModel model)
{ {
return StatusUpdate(model, OrderStatus.Выполняется); return StatusUpdate(model, OrderStatus.Выполняется);
} }
public List<OrderViewModel>? ReadList(OrderSearchModel? model) public List<OrderViewModel>? ReadList(OrderSearchModel? model)
{ {
_logger.LogInformation("ReadList. OrderId:{Id}", model?.Id); _logger.LogInformation("ReadList. OrderId:{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)
{ {
_logger.LogWarning("ReadList return null list"); _logger.LogWarning("ReadList return null list");
return null; return null;
} }
_logger.LogInformation("ReadList. Count:{Count}", list.Count); _logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list; return list;
} }
private void CheckModel(OrderBindingModel model, bool withParams = true) private void CheckModel(OrderBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (model.RepairId < 0)
{
throw new ArgumentNullException("Некорректный идентификатор документа", nameof(model.RepairId));
}
if (model.Count <= 0)
{
throw new ArgumentNullException("Количество работ в заказе должно быть больше 0", nameof(model.Count));
}
if (model.Sum <= 0)
{
throw new ArgumentNullException("Сумма заказа должна быть больше 0", nameof(model.Sum));
}
_logger.LogInformation("Order. Count: {Count}. Sum: {Sum}. Id: {Id}", model.Count, model.Sum, model.Id);
}
private void CheckModel(OrderViewModel model, bool withParams = true)
{ {
if (model == null) if (model == null)
{ {
@ -140,10 +116,6 @@ namespace RenovationWorkBusinessLogic.BusinessLogics
{ {
return; return;
} }
if (model.RepairId < 0)
{
throw new ArgumentNullException("Некорректный идентификатор документа", nameof(model.RepairId));
}
if (model.Count <= 0) if (model.Count <= 0)
{ {
throw new ArgumentNullException("Количество работ в заказе должно быть больше 0", nameof(model.Count)); throw new ArgumentNullException("Количество работ в заказе должно быть больше 0", nameof(model.Count));
@ -155,59 +127,59 @@ namespace RenovationWorkBusinessLogic.BusinessLogics
_logger.LogInformation("Order. Count: {Count}. Sum: {Sum}. Id: {Id}", model.Count, model.Sum, model.Id); _logger.LogInformation("Order. Count: {Count}. Sum: {Sum}. Id: {Id}", model.Count, model.Sum, model.Id);
} }
private bool CheckSupply(IRepairModel repair, int count) private bool CheckSupply(IRepairModel repair, int count)
{ {
if (count <= 0) if (count <= 0)
{ {
_logger.LogWarning("Check then supply operation error. Repair count < 0."); _logger.LogWarning("Check then supply operation error. Repair count < 0.");
return false; return false;
} }
int sumCapacity = 0; int sumCapacity = 0;
int sumCount = 0; int sumCount = 0;
sumCapacity = _shopStorage.GetFullList().Select(x => x.MaxCapacity).Sum(); sumCapacity = _shopStorage.GetFullList().Select(x => x.MaxCapacity).Sum();
sumCount = _shopStorage.GetFullList().Select(x => x.ShopRepairs.Select(y => y.Value.Item2).Sum()).Sum(); sumCount = _shopStorage.GetFullList().Select(x => x.ShopRepairs.Select(y => y.Value.Item2).Sum()).Sum();
int freeSpace = sumCapacity - sumCount; int freeSpace = sumCapacity - sumCount;
if (freeSpace - count < 0) if (freeSpace - count < 0)
{ {
_logger.LogWarning("Check then supply operation error. There's no place for new Repair in shops."); _logger.LogWarning("Check then supply operation error. There's no place for new Repair in shops.");
return false; return false;
} }
foreach (var shop in _shopStorage.GetFullList()) foreach (var shop in _shopStorage.GetFullList())
{ {
freeSpace = shop.MaxCapacity; freeSpace = shop.MaxCapacity;
foreach (var doc in shop.ShopRepairs) foreach (var doc in shop.ShopRepairs)
{ {
freeSpace -= doc.Value.Item2; freeSpace -= doc.Value.Item2;
} }
if (freeSpace == 0) if (freeSpace == 0)
{ {
continue; continue;
} }
if (freeSpace - count >= 0) if (freeSpace - count >= 0)
{ {
if (_shopLogic.ReplenishRepairs(new() { Id = shop.Id }, repair, count)) if (_shopLogic.ReplenishRepairs(new() { Id = shop.Id }, repair, count))
count = 0; count = 0;
else else
{ {
_logger.LogWarning("Supply error"); _logger.LogWarning("Supply error");
return false; return false;
} }
} }
if (freeSpace - count < 0) if (freeSpace - count < 0)
{ {
if (_shopLogic.ReplenishRepairs(new() { Id = shop.Id }, repair, freeSpace)) if (_shopLogic.ReplenishRepairs(new() { Id = shop.Id }, repair, freeSpace))
count -= freeSpace; count -= freeSpace;
else else
{ {
_logger.LogWarning("Supply error"); _logger.LogWarning("Supply error");
return false; return false;
} }
} }
if (count <= 0) if (count <= 0)
{ {
return true; return true;
} }
} }
return false; return false;
} }
} }
} }

View File

@ -13,164 +13,163 @@ using Microsoft.Extensions.Logging;
namespace RenovationWorkBusinessLogic.BusinessLogics namespace RenovationWorkBusinessLogic.BusinessLogics
{ {
public class ShopLogic : IShopLogic public class ShopLogic : IShopLogic
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IShopStorage _shopStorage; private readonly IShopStorage _shopStorage;
public ShopLogic(ILogger<ShopLogic> logger, IShopStorage ShopStorage) public ShopLogic(ILogger<ShopLogic> logger, IShopStorage ShopStorage)
{ {
_logger = logger; _logger = logger;
_shopStorage = ShopStorage; _shopStorage = ShopStorage;
} }
public List<ShopViewModel>? ReadList(ShopSearchModel? model) public List<ShopViewModel>? ReadList(ShopSearchModel? model)
{ {
_logger.LogInformation("ReadList. ShopName:{ShopName}. Id:{ Id}", model?.ShopName, model?.Id); _logger.LogInformation("ReadList. ShopName:{ShopName}. Id:{ Id}", model?.ShopName, model?.Id);
var list = model == null ? _shopStorage.GetFullList() : var list = model == null ? _shopStorage.GetFullList() :
_shopStorage.GetFilteredList(model); _shopStorage.GetFilteredList(model);
if (list == null) if (list == null)
{ {
_logger.LogWarning("ReadList return null list"); _logger.LogWarning("ReadList return null list");
return null; return null;
} }
_logger.LogInformation("ReadList. Count:{Count}", list.Count); _logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list; return list;
} }
public ShopViewModel? ReadElement(ShopSearchModel model) public ShopViewModel? ReadElement(ShopSearchModel model)
{ {
if (model == null) if (model == null)
{ {
throw new ArgumentNullException(nameof(model)); throw new ArgumentNullException(nameof(model));
} }
_logger.LogInformation("ReadElement. ShopName:{ShopName}.Id:{ Id}", model.ShopName, model.Id); _logger.LogInformation("ReadElement. ShopName:{ShopName}.Id:{ Id}", model.ShopName, model.Id);
var element = _shopStorage.GetElement(model); var element = _shopStorage.GetElement(model);
if (element == null) if (element == null)
{ {
_logger.LogWarning("ReadElement element not found"); _logger.LogWarning("ReadElement element not found");
return null; return null;
} }
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id); _logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element; return element;
} }
public bool Create(ShopBindingModel model) public bool Create(ShopBindingModel model)
{ {
CheckModel(model); CheckModel(model);
if (_shopStorage.Insert(model) == null) if (_shopStorage.Insert(model) == null)
{ {
_logger.LogWarning("Insert operation failed"); _logger.LogWarning("Insert operation failed");
return false; return false;
} }
return true; return true;
} }
public bool Update(ShopBindingModel model) public bool Update(ShopBindingModel model)
{ {
CheckModel(model); CheckModel(model);
if (_shopStorage.Update(model) == null) if (_shopStorage.Update(model) == null)
{ {
_logger.LogWarning("Update operation failed"); _logger.LogWarning("Update operation failed");
return false; return false;
} }
return true; return true;
} }
public bool Delete(ShopBindingModel model) public bool Delete(ShopBindingModel model)
{ {
CheckModel(model, false); CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id); _logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_shopStorage.Delete(model) == null) if (_shopStorage.Delete(model) == null)
{ {
_logger.LogWarning("Delete operation failed"); _logger.LogWarning("Delete operation failed");
return false; return false;
} }
return true; return true;
} }
public bool ReplenishRepairs(ShopSearchModel model, IRepairModel repair, int count) public bool ReplenishRepairs(ShopSearchModel model, IRepairModel repair, int count)
{ {
{ {
_logger.LogInformation("Try to replenish repairs. ShopName:{ShopName}. Id:{Id}", model.ShopName, model.Id); _logger.LogInformation("Try to replenish repairs. ShopName:{ShopName}. Id:{Id}", model.ShopName, model.Id);
if (model == null) if (model == null)
{ {
_logger.LogWarning("Read operation failed"); _logger.LogWarning("Read operation failed");
throw new ArgumentNullException(nameof(model)); throw new ArgumentNullException(nameof(model));
} }
ShopViewModel? curModel = ReadElement(model); ShopViewModel? curModel = ReadElement(model);
if (curModel == null) if (curModel == null)
{ {
_logger.LogWarning("Read operation failed"); _logger.LogWarning("Read operation failed");
throw new ArgumentNullException(nameof(curModel)); throw new ArgumentNullException(nameof(curModel));
} }
if (repair == null) if (repair == null)
{ {
_logger.LogWarning("Read operation failed"); _logger.LogWarning("Read operation failed");
throw new ArgumentNullException(nameof(repair)); throw new ArgumentNullException(nameof(repair));
} }
if (count <= 0) if (count <= 0)
{ {
_logger.LogWarning("Read operation failed"); _logger.LogWarning("Read operation failed");
throw new ArgumentException("Количество должно быть положительным"); throw new ArgumentException("Количество должно быть положительным");
} }
int countItems = curModel.ShopRepairs.Select(x => x.Value.Item2).Sum(); int countItems = curModel.ShopRepairs.Select(x => x.Value.Item2).Sum();
if (curModel.MaxCapacity - countItems >= count) if (curModel.MaxCapacity - countItems >= count)
{ {
if (curModel.ShopRepairs.TryGetValue(repair.Id, out var sameDocument)) if (curModel.ShopRepairs.TryGetValue(repair.Id, out var sameDocument))
{ {
curModel.ShopRepairs[repair.Id] = (repair, sameDocument.Item2 + count); curModel.ShopRepairs[repair.Id] = (repair, sameDocument.Item2 + count);
_logger.LogInformation("Same repair found by supply. Added {0} of {1} in {2} shop", count, repair.RepairName, curModel.ShopName); _logger.LogInformation("Same repair found by supply. Added {0} of {1} in {2} shop", count, repair.RepairName, curModel.ShopName);
} }
else else
{ {
curModel.ShopRepairs[repair.Id] = (repair, count); curModel.ShopRepairs[repair.Id] = (repair, count);
_logger.LogInformation("New repair added by supply. Added {0} of {1} in {2} shop", count, repair.RepairName, curModel.ShopName); _logger.LogInformation("New repair added by supply. Added {0} of {1} in {2} shop", count, repair.RepairName, curModel.ShopName);
} }
_shopStorage.Update(new() _shopStorage.Update(new()
{ {
Id = curModel.Id, Id = curModel.Id,
ShopName = curModel.ShopName, ShopName = curModel.ShopName,
Address = curModel.Address, Address = curModel.Address,
OpeningDate = curModel.OpeningDate, OpeningDate = curModel.OpeningDate,
ShopRepairs = curModel.ShopRepairs, ShopRepairs = curModel.ShopRepairs,
MaxCapacity = curModel.MaxCapacity MaxCapacity = curModel.MaxCapacity
}); });
} }
else else
{ {
_logger.LogWarning("Required shop is overflowed"); _logger.LogWarning("Required shop is overflowed");
return false; return false;
} }
return true; return true;
} }
} }
private void CheckModel(ShopBindingModel model, bool withParams = true) private void CheckModel(ShopBindingModel model, bool withParams = true)
{ {
if (model == null) if (model == null)
{ {
throw new ArgumentNullException(nameof(model)); throw new ArgumentNullException(nameof(model));
} }
if (!withParams) if (!withParams)
{ {
return; return;
} }
if (string.IsNullOrEmpty(model.ShopName)) if (string.IsNullOrEmpty(model.ShopName))
{ {
throw new ArgumentNullException("Нет названия магазина", nameof(model.ShopName)); throw new ArgumentNullException("Нет названия магазина", nameof(model.ShopName));
} }
if (string.IsNullOrEmpty(model.Address)) if (string.IsNullOrEmpty(model.Address))
{ {
throw new ArgumentNullException("Нет адреса магазина", nameof(model.Address)); throw new ArgumentNullException("Нет адреса магазина", nameof(model.Address));
} }
_logger.LogInformation("Shop. ShopName:{ShopName}.Address:{Address}. DateOpen:{DateOpen}. Id: { Id}", _logger.LogInformation("Shop. ShopName:{ShopName}.Address:{Address}. DateOpen:{DateOpen}. Id: { Id}",
model.ShopName, model.Address, model.OpeningDate, model.Id); model.ShopName, model.Address, model.OpeningDate, model.Id);
var element = _shopStorage.GetElement(new ShopSearchModel var element = _shopStorage.GetElement(new ShopSearchModel
{ {
ShopName = model.ShopName ShopName = model.ShopName
}); });
if (element != null && element.Id != model.Id) if (element != null && element.Id != model.Id)
{ {
throw new InvalidOperationException("Магазин с таким названием уже есть"); throw new InvalidOperationException("Магазин с таким названием уже есть");
} }
} }
public bool SellRepairs(IRepairModel repair, int count) public bool SellRepairs(IRepairModel repair, int count)
{ {
return _shopStorage.SellRepairs(repair, count); return _shopStorage.SellRepairs(repair, count);
} }
} }
} }

View File

@ -9,59 +9,59 @@ using RenovationWorkFileImplement.Models;
namespace RenovationWorkFileImplement namespace RenovationWorkFileImplement
{ {
internal class DataFileSingleton internal class DataFileSingleton
{ {
private static DataFileSingleton? instance; private static DataFileSingleton? instance;
private readonly string ComponentFileName = "Component.xml"; private readonly string ComponentFileName = "Component.xml";
private readonly string OrderFileName = "Order.xml"; private readonly string OrderFileName = "Order.xml";
private readonly string RepairFileName = "Repair.xml"; private readonly string RepairFileName = "Repair.xml";
private readonly string ShopFileName = "Shops.xml"; private readonly string ShopFileName = "Shops.xml";
public List<Shop> Shops { get; private set; } public List<Shop> Shops { get; private set; }
public List<Component> Components { get; private set; } public List<Component> Components { get; private set; }
public List<Order> Orders { get; private set; } public List<Order> Orders { get; private set; }
public List<Repair> Repairs { get; private set; } public List<Repair> Repairs { get; private set; }
public static DataFileSingleton GetInstance() public static DataFileSingleton GetInstance()
{ {
if (instance == null) if (instance == null)
{ {
instance = new DataFileSingleton(); instance = new DataFileSingleton();
} }
return instance; return instance;
} }
public void SaveComponents() => SaveData(Components, ComponentFileName, "Components", x => x.GetXElement); public void SaveComponents() => SaveData(Components, ComponentFileName, "Components", x => x.GetXElement);
public void SaveRepairs() => SaveData(Repairs, RepairFileName, "Repairs", x => x.GetXElement); public void SaveRepairs() => SaveData(Repairs, RepairFileName, "Repairs", x => x.GetXElement);
public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement); public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement);
public void SaveShops() => SaveData(Shops, ShopFileName,"Shops", x => x.GetXElement); public void SaveShops() => SaveData(Shops, ShopFileName, "Shops", x => x.GetXElement);
private DataFileSingleton() private DataFileSingleton()
{ {
Components = LoadData(ComponentFileName, "Component", x => Components = LoadData(ComponentFileName, "Component", x =>
Component.Create(x)!)!; Component.Create(x)!)!;
Repairs = LoadData(RepairFileName, "Repair", x => Repairs = LoadData(RepairFileName, "Repair", x =>
Repair.Create(x)!)!; Repair.Create(x)!)!;
Orders = LoadData(OrderFileName, "Order", x => Orders = LoadData(OrderFileName, "Order", x =>
Order.Create(x)!)!; Order.Create(x)!)!;
Shops = LoadData(ShopFileName, "Shop", x => Shops = LoadData(ShopFileName, "Shop", x =>
Shop.Create(x)!)!; Shop.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)) if (File.Exists(filename))
{ {
return return
XDocument.Load(filename)?.Root?.Elements(xmlNodeName)?.Select(selectFunction)?.ToList(); XDocument.Load(filename)?.Root?.Elements(xmlNodeName)?.Select(selectFunction)?.ToList();
} }
return new List<T>(); 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) if (data != null)
{ {
new XDocument(new XElement(xmlNodeName, new XDocument(new XElement(xmlNodeName,
data.Select(selectFunction).ToArray())).Save(filename); data.Select(selectFunction).ToArray())).Save(filename);
} }
} }
} }
} }

View File

@ -11,86 +11,82 @@ using RenovationWorkFileImplement.Models;
namespace RenovationWorkFileImplement.Implements namespace RenovationWorkFileImplement.Implements
{ {
public class OrderStorage : IOrderStorage public class OrderStorage : IOrderStorage
{ {
private readonly DataFileSingleton source; private readonly DataFileSingleton source;
public OrderStorage() public OrderStorage()
{ {
source = DataFileSingleton.GetInstance(); source = DataFileSingleton.GetInstance();
} }
public List<OrderViewModel> GetFullList() public List<OrderViewModel> GetFullList()
{ {
return source.Orders.Select(x => AccessRepairStorage(x.GetViewModel)).ToList(); return source.Orders.Select(x => AccessRepairStorage(x.GetViewModel)).ToList();
} }
public List<OrderViewModel> GetFilteredList(OrderSearchModel model) public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{ {
if (!model.Id.HasValue) if (!model.Id.HasValue)
{ {
return new(); return new();
} }
return source.Orders.Where(x => x.Id == model.Id) return source.Orders.Where(x => x.Id == model.Id)
.Select(x => AccessRepairStorage(x.GetViewModel)) .Select(x => AccessRepairStorage(x.GetViewModel))
.ToList(); .ToList();
} }
public OrderViewModel? GetElement(OrderSearchModel model) public OrderViewModel? GetElement(OrderSearchModel model)
{ {
if (!model.Id.HasValue) if (!model.Id.HasValue)
{ {
return null; return null;
} }
return AccessRepairStorage(source.Orders.FirstOrDefault( return AccessRepairStorage(source.Orders.FirstOrDefault(
x => (model.Id.HasValue && x.Id == model.Id))?.GetViewModel x => (model.Id.HasValue && x.Id == model.Id))?.GetViewModel
); );
} }
public OrderViewModel? Insert(OrderBindingModel model) public OrderViewModel? Insert(OrderBindingModel model)
{ {
model.Id = source.Orders.Count > 0 ? source.Orders.Max(x => x.Id) + 1 : 1; model.Id = source.Orders.Count > 0 ? source.Orders.Max(x => x.Id) + 1 : 1;
var newOrder = Order.Create(model); var newOrder = Order.Create(model);
if (newOrder == null) if (newOrder == null)
{ {
return null; return null;
} }
source.Orders.Add(newOrder); source.Orders.Add(newOrder);
source.SaveOrders(); source.SaveOrders();
return AccessRepairStorage(newOrder.GetViewModel); return AccessRepairStorage(newOrder.GetViewModel);
} }
public OrderViewModel? Update(OrderBindingModel model) public OrderViewModel? Update(OrderBindingModel model)
{ {
var order = source.Orders.FirstOrDefault(x => x.Id == model.Id); var order = source.Orders.FirstOrDefault(x => x.Id == model.Id);
if (order == null) if (order == null)
{ {
return null; return null;
} }
order.Update(model); order.Update(model);
source.SaveOrders(); source.SaveOrders();
return AccessRepairStorage(order.GetViewModel); return AccessRepairStorage(order.GetViewModel);
} }
public OrderViewModel? Delete(OrderBindingModel model) public OrderViewModel? Delete(OrderBindingModel model)
{ {
var element = source.Orders.FirstOrDefault(x => x.Id == var element = source.Orders.FirstOrDefault(x => x.Id ==
model.Id); model.Id);
if (element != null) if (element != null)
{ {
source.Orders.Remove(element); source.Orders.Remove(element);
source.SaveOrders(); source.SaveOrders();
return AccessRepairStorage(element.GetViewModel); return AccessRepairStorage(element.GetViewModel);
} }
return null; return null;
} }
public OrderViewModel? AccessRepairStorage(OrderViewModel model) public OrderViewModel? AccessRepairStorage(OrderViewModel model)
{ {
if (model == null) if (model == null)
return null; return null;
foreach (var Repair in source.Repairs) var repair = source.Repairs.FirstOrDefault(x => (x.Id == model.RepairId));
{ if (repair == null)
if (Repair.Id == model.RepairId) return model;
{ model.RepairName = repair.RepairName;
model.RepairName = Repair.RepairName; return model;
break; }
} }
}
return model;
}
}
} }