ничего не сохраняется :(

This commit is contained in:
bulatova_karina 2024-05-05 16:09:41 +04:00
parent 2fed22eb38
commit 5ac66dc71b
27 changed files with 1489 additions and 157 deletions

View File

@ -15,43 +15,78 @@ namespace ComputersShopBusinessLogic.BusinessLogics
public class ComputerLogic : IComputerLogic
{
private readonly ILogger _logger;
/// <summary>
/// Взаимодействие с хранилищем изделий
/// </summary>
private readonly IComputerStorage _computerStorage;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="logger"></param>
/// <param name="computerStorage"></param>
public ComputerLogic(ILogger<ComputerLogic> logger, IComputerStorage computerStorage)
{
_logger = logger;
_computerStorage = computerStorage;
}
/// <summary>
/// Получение списка
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public List<ComputerViewModel>? ReadList(ComputerSearchModel? model)
{
_logger.LogInformation("ReadList. ComputerName:{ComputerName}. Id:{Id}", model?.ComputerName, model?.Id);
_logger.LogInformation("ReadList. ComputerName:{ComputerName}.Id:{ Id}", model?.ComputerName, model?.Id);
var list = model == null ? _computerStorage.GetFullList() : _computerStorage.GetFiltredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
/// <summary>
/// Получение отдельной записи
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
public ComputerViewModel? ReadElement(ComputerSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. ComputerName:{ComputerName}. Id:{Id}", model.ComputerName, model.Id);
_logger.LogInformation("ReadElement. ComputerName:{ComputerName}.Id:{ Id}", model.ComputerName, model.Id);
var element = _computerStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
/// <summary>
/// Создание записи
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public bool Create(ComputerBindingModel model)
{
CheckModel(model);
if (_computerStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
@ -59,9 +94,16 @@ namespace ComputersShopBusinessLogic.BusinessLogics
}
return true;
}
/// <summary>
/// Изменение записи
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public bool Update(ComputerBindingModel model)
{
CheckModel(model);
if (_computerStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
@ -69,10 +111,17 @@ namespace ComputersShopBusinessLogic.BusinessLogics
}
return true;
}
/// <summary>
/// Удаление записи
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public bool Delete(ComputerBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_computerStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
@ -80,6 +129,12 @@ namespace ComputersShopBusinessLogic.BusinessLogics
}
return true;
}
/// <summary>
/// Проверка модели изделия
/// </summary>
/// <param name="model"></param>
/// <param name="withParams"></param>
private void CheckModel(ComputerBindingModel model, bool withParams = true)
{
if (model == null)
@ -92,20 +147,20 @@ namespace ComputersShopBusinessLogic.BusinessLogics
}
if (string.IsNullOrEmpty(model.ComputerName))
{
throw new ArgumentNullException("Нет названия компьютера", nameof(model.ComputerName));
throw new ArgumentNullException("Нет названия изделия", nameof(model.ComputerName));
}
if (model.Price <= 0)
{
throw new ArgumentNullException("Цена должна быть больше 0", nameof(model.Price));
throw new ArgumentNullException("Цена изделия должна быть больше 0", nameof(model.Price));
}
_logger.LogInformation("Computer. ComputerName:{ComputerName}. Cost:{Cost}. Id:{Id}", model.ComputerName, model.Price, model.Id);
_logger.LogInformation("Computer. ComputerName:{ComputerName}.Price:{ Price}. Id: { Id}", model.ComputerName, model.Price, model.Id);
var element = _computerStorage.GetElement(new ComputerSearchModel
{
ComputerName = model.ComputerName
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Компьютер с таким названием уже есть");
throw new InvalidOperationException("Изделие с таким названием уже есть");
}
}
}

View File

@ -9,6 +9,7 @@ using ComputersShopContracts.SearchModels;
using ComputersShopContracts.StoragesContracts;
using ComputersShopContracts.ViewModels;
using ComputersShopDataModels.Enums;
using ComputersShopDataModels.Models;
using Microsoft.Extensions.Logging;
namespace ComputersShopBusinessLogic.BusinessLogics
@ -16,33 +17,77 @@ namespace ComputersShopBusinessLogic.BusinessLogics
public class OrderLogic : IOrderLogic
{
private readonly ILogger _logger;
/// <summary>
/// Взаимодействие с хранилищем заказов
/// </summary>
private readonly IOrderStorage _orderStorage;
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage)
/// <summary>
/// Взаимодействие с хранилищем магазинов
/// </summary>
private IShopStorage _shopStorage;
/// <summary>
/// Бизнес-логика магазинов
/// </summary>
private IShopLogic _shopLogic;
/// <summary>
/// Взаимодействие с хранилищем изделий
/// </summary>
private IComputerStorage _computerStorage;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="logger"></param>
/// <param name="orderStorage"></param>
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage, IShopStorage shopStorage, IShopLogic shopLogic, IComputerStorage computerStorage)
{
_logger = logger;
_orderStorage = orderStorage;
_shopStorage = shopStorage;
_shopLogic = shopLogic;
_computerStorage = computerStorage;
}
/// <summary>
/// Получение списка
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public List<OrderViewModel>? ReadList(OrderSearchModel? model)
{
_logger.LogInformation("ReadList. Id:{Id}", model?.Id);
var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFiltredList(model);
_logger.LogInformation("ReadList. Order.Id:{ Id}", model?.Id);
var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
/// <summary>
/// Создание заказа
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public bool CreateOrder(OrderBindingModel model)
{
CheckModel(model);
if (model.Status != OrderStatus.Неизвестен)
{
_logger.LogWarning("Wrong order status. Insert operation failed");
_logger.LogWarning("Insert operation failed. Order status incorrect.");
return false;
}
model.Status = OrderStatus.Принят;
if (_orderStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
@ -50,52 +95,42 @@ namespace ComputersShopBusinessLogic.BusinessLogics
}
return true;
}
public bool ChangeStatus(OrderBindingModel model, OrderStatus newStatus)
{
var viewModel = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id });
if (viewModel == null)
{
throw new ArgumentNullException(nameof(viewModel));
}
if (viewModel.Status + 1 != newStatus)
{
_logger.LogWarning("Status change operation failed");
return false;
}
model.Status = newStatus;
model.ComputerId = viewModel.ComputerId;
model.Count = viewModel.Count;
model.Sum = viewModel.Sum;
model.DateCreate = viewModel.DateCreate;
if (model.Status == OrderStatus.Готов)
{
model.DateImplement = DateTime.Now;
}
else
{
model.DateImplement = viewModel.DateImplement;
}
CheckModel(model, false);
if (_orderStorage.Update(model) == null)
{
_logger.LogWarning("Status change operation failed");
return false;
}
return true;
}
/// <summary>
/// Смена статуса заказа (Выполняется)
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public bool TakeOrderInWork(OrderBindingModel model)
{
return ChangeStatus(model, OrderStatus.Выполняется);
return StatusUpdate(model, OrderStatus.Выполняется);
}
/// <summary>
/// Смена статуса заказа (Выдан)
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public bool FinishOrder(OrderBindingModel model)
{
return ChangeStatus(model, OrderStatus.Готов);
return StatusUpdate(model, OrderStatus.Выдан);
}
/// <summary>
/// Смена статуса заказа (Готов)
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public bool DeliveryOrder(OrderBindingModel model)
{
return ChangeStatus(model, OrderStatus.Выдан);
return StatusUpdate(model, OrderStatus.Готов);
}
/// <summary>
/// Проверка модели заказа
/// </summary>
/// <param name="model"></param>
/// <param name="withParams"></param>
private void CheckModel(OrderBindingModel model, bool withParams = true)
{
if (model == null)
@ -106,19 +141,149 @@ namespace ComputersShopBusinessLogic.BusinessLogics
{
return;
}
if (model.Sum <= 0)
if (model.ComputerId < 0)
{
throw new ArgumentNullException("Цена должна быть больше 0", nameof(model.Sum));
throw new ArgumentNullException("Некорректный идентификатор изделия", nameof(model.ComputerId));
}
if (model.Count <= 0)
{
throw new ArgumentNullException("Количество изделий должно быть больше 0", nameof(model.Count));
throw new ArgumentNullException("Количество изделий в заказе должно быть больше 0", nameof(model.Count));
}
if (model.DateImplement != null && model.DateImplement < model.DateCreate)
if (model.Sum <= 0)
{
throw new ArithmeticException("Дата завершения не может быть раньше даты начала");
throw new ArgumentNullException("Сумма заказа должна быть больше 0", nameof(model.Sum));
}
_logger.LogInformation("Order. Id:{Id}. Sum:{Sum}. ComputerId:{ComputerId}", model.Id, model.Sum, model.ComputerId);
_logger.LogInformation("Order. OrderID:{Id}.Sum:{ Sum}. ComputerId: { ComputerId}", model.Id, model.Sum, model.ComputerId);
}
/// <summary>
/// Смена статуса заказа
/// </summary>
/// <param name="model"></param>
/// <param name="newStatus"></param>
/// <returns></returns>
private bool StatusUpdate(OrderBindingModel model, OrderStatus newStatus)
{
var element = _orderStorage.GetElement(new OrderSearchModel
{
Id = model.Id
});
if (element == null)
{
throw new ArgumentNullException(nameof(model));
}
if (element.Status + 1 != newStatus)
{
_logger.LogWarning("Change status operation failed");
return false;
}
model.Status = newStatus;
if (newStatus == OrderStatus.Выдан)
{
var computer = _computerStorage.GetElement(new ComputerSearchModel { Id = element.ComputerId });
if (computer == null)
{
_logger.LogWarning("Status change error. Computer not found");
return false;
}
if (!CheckSupply(computer, element.Count))
{
_logger.LogWarning("Status change error. Shop is overflowed");
return false;
}
}
if (model.Status == OrderStatus.Выдан)
{
model.DateImplement = DateTime.Now;
}
else
{
model.DateImplement = element.DateImplement;
}
CheckModel(model, false);
if (_orderStorage.Update(model) == null)
{
_logger.LogWarning("Change status operation failed");
return false;
}
return true;
}
/// <summary>
/// Проверка заказа
/// </summary>
/// <param name="computer"></param>
/// <param name="count"></param>
/// <returns></returns>
public bool CheckSupply(IComputerModel model, int count)
{
if (count <= 0)
{
_logger.LogWarning("Check supply operation error. Computers count < 0");
return false;
}
int sumCapacity = _shopStorage.GetFullList().Select(x => x.MaxComputers).Sum();
int sumCount = _shopStorage.GetFullList().Select(x => x.ShopComputers.Select(y => y.Value.Item2).Sum()).Sum();
int free = sumCapacity - sumCount;
if (free < count)
{
_logger.LogWarning("Check supply error. No place for new computers");
return false;
}
foreach (var shop in _shopStorage.GetFullList())
{
free = shop.MaxComputers;
foreach (var computer in shop.ShopComputers)
{
free -= computer.Value.Item2;
}
if (free == 0)
{
continue;
}
if (free >= count)
{
if (_shopLogic.AddComputerInShop(new()
{
Id = shop.Id
}, model, count))
{
count = 0;
}
else
{
_logger.LogWarning("Supply error");
return false;
}
}
else
{
if (_shopLogic.AddComputerInShop(new()
{
Id = shop.Id
}, model, free))
{
count -= free;
}
else
{
_logger.LogWarning("Supply error");
return false;
}
}
if (count <= 0)
{
return true;
}
}
return false;
}
}
}

View File

@ -16,12 +16,28 @@ namespace ComputersShopBusinessLogic.BusinessLogics
public class ShopLogic : IShopLogic
{
private readonly ILogger _logger;
/// <summary>
/// Взаимодействие с хранилищем магазинов
/// </summary>
private readonly IShopStorage _shopStorage;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="logger"></param>
/// <param name="shopStorage"></param>
public ShopLogic(ILogger<ShopLogic> logger, IShopStorage shopStorage)
{
_logger = logger;
_shopStorage = shopStorage;
}
/// <summary>
/// Получение списка
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public List<ShopViewModel>? ReadList(ShopSearchModel? model)
{
_logger.LogInformation("ReadList. ShopName:{ShopName}.Id:{ Id}", model?.ShopName, model?.Id);
@ -36,6 +52,13 @@ namespace ComputersShopBusinessLogic.BusinessLogics
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
/// <summary>
/// Получение отдельной записи
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
public ShopViewModel? ReadElement(ShopSearchModel model)
{
if (model == null)
@ -55,6 +78,12 @@ namespace ComputersShopBusinessLogic.BusinessLogics
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
/// <summary>
/// Создание записи
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public bool Create(ShopBindingModel model)
{
CheckModel(model);
@ -66,6 +95,12 @@ namespace ComputersShopBusinessLogic.BusinessLogics
}
return true;
}
/// <summary>
/// Изменение записи
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public bool Update(ShopBindingModel model)
{
CheckModel(model);
@ -77,6 +112,12 @@ namespace ComputersShopBusinessLogic.BusinessLogics
}
return true;
}
/// <summary>
/// Удаление записи
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public bool Delete(ShopBindingModel model)
{
CheckModel(model, false);
@ -89,6 +130,16 @@ namespace ComputersShopBusinessLogic.BusinessLogics
}
return true;
}
/// <summary>
/// Добавление изделия в магазин
/// </summary>
/// <param name="model"></param>
/// <param name="computer"></param>
/// <param name="count"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="ArgumentException"></exception>
public bool AddComputerInShop(ShopSearchModel model, IComputerModel computer, int count)
{
if (model == null)
@ -97,7 +148,7 @@ namespace ComputersShopBusinessLogic.BusinessLogics
}
if (count <= 0)
{
throw new ArgumentException("Кол-во изделий должно быть больше 0", nameof(count));
throw new ArgumentException("Количество изделий должно быть больше 0", nameof(count));
}
_logger.LogInformation("AddComputerInShop. ShopName:{ShopName}.Id:{ Id}", model.ShopName, model.Id);
var element = _shopStorage.GetElement(model);
@ -108,6 +159,13 @@ namespace ComputersShopBusinessLogic.BusinessLogics
}
_logger.LogInformation("AddComputerInShop find. Id:{Id}", element.Id);
var countComputers = element.ShopComputers.Select(x => x.Value.Item2).Sum();
if (element.MaxComputers - countComputers < count)
{
_logger.LogWarning("Shop is overflowed");
return false;
}
if (element.ShopComputers.TryGetValue(computer.Id, out var pair))
{
element.ShopComputers[computer.Id] = (computer, count + pair.Item2);
@ -125,10 +183,47 @@ namespace ComputersShopBusinessLogic.BusinessLogics
Address = element.Address,
ShopName = element.ShopName,
DateOpening = element.DateOpening,
ShopComputers = element.ShopComputers
ShopComputers = element.ShopComputers,
MaxComputers = element.MaxComputers
});
return true;
}
/// <summary>
/// Продажа изделий
/// </summary>
/// <param name="computer"></param>
/// <param name="count"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="ArgumentException"></exception>
public bool SellComputers(IComputerModel computer, int count)
{
if (computer == null)
{
throw new ArgumentNullException(nameof(computer));
}
if (count <= 0)
{
throw new ArgumentException("Количество изделий должно быть больше 0", nameof(count));
}
if (_shopStorage.SellComputers(computer, count))
{
_logger.LogInformation("Selling sucsess");
return true;
}
_logger.LogInformation("Selling failed");
return false;
}
/// <summary>
/// Проверка модели магазина
/// </summary>
/// <param name="model"></param>
/// <param name="withParams"></param>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="InvalidOperationException"></exception>
private void CheckModel(ShopBindingModel model, bool withParams = true)
{
if (model == null)

View File

@ -19,5 +19,6 @@ namespace ComputersShopContracts.BindingModels
get;
set;
} = new();
public int MaxComputers { get; set; }
}
}

View File

@ -18,5 +18,6 @@ namespace ComputersShopContracts.BusinessLogicsContracts
bool Update(ShopBindingModel model);
bool Delete(ShopBindingModel model);
bool AddComputerInShop(ShopSearchModel model, IComputerModel computer, int count);
bool SellComputers(IComputerModel computer, int count);
}
}

View File

@ -12,10 +12,40 @@ namespace ComputersShopContracts.StoragesContracts
public interface IOrderStorage
{
List<OrderViewModel> GetFullList();
List<OrderViewModel> GetFiltredList(OrderSearchModel model);
/// <summary>
/// Получение фильтрованного списка
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
List<OrderViewModel> GetFilteredList(OrderSearchModel model);
/// <summary>
/// Получение элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
OrderViewModel? GetElement(OrderSearchModel model);
/// <summary>
/// Добавление элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
OrderViewModel? Insert(OrderBindingModel model);
/// <summary>
/// Редактирование элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
OrderViewModel? Update(OrderBindingModel model);
/// <summary>
/// Удаление элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
OrderViewModel? Delete(OrderBindingModel model);
}
}

View File

@ -7,6 +7,7 @@ using ComputersShopContracts.BindingModels;
using ComputersShopContracts.SearchModels;
using ComputersShopContracts.ViewModels;
using ComputersShopDataModels;
using ComputersShopDataModels.Models;
namespace ComputersShopContracts.StoragesContracts
{
@ -18,5 +19,7 @@ namespace ComputersShopContracts.StoragesContracts
ShopViewModel? Insert(ShopBindingModel model);
ShopViewModel? Update(ShopBindingModel model);
ShopViewModel? Delete(ShopBindingModel model);
bool SellComputers(IComputerModel model, int count);
bool CheckCount(IComputerModel model, int count);
}
}

View File

@ -23,5 +23,7 @@ namespace ComputersShopContracts.ViewModels
get;
set;
} = new();
[DisplayName("Максимальное количество изделий")]
public int MaxComputers { get; set; }
}
}

View File

@ -12,5 +12,6 @@ namespace ComputersShopDataModels.Models
string Address { get; }
DateTime DateOpening { get; }
Dictionary<int, (IComputerModel, int)> ShopComputers { get; }
int MaxComputers { get; }
}
}

View File

@ -11,35 +11,101 @@ namespace ComputersShopFileImplement
{
internal class DataFileSingleton
{
private static DataFileSingleton? instance;
public readonly string ComponentFileName = "Component.xml";
public readonly string OrderFileName = "Order.xml";
public readonly string ComputerFileName = "Computer.xml";
public List<Component> Components { get; private set; }
public List<Order> Orders { get; private set; }
public List<Computer> Computers { get; private set; }
public static DataFileSingleton GetInstance()
{
if (instance == null)
{
instance = new DataFileSingleton();
}
return instance;
}
public void SaveComponents() => SaveData(Components, ComponentFileName,
"Components", x => x.GetXElement);
public void SaveComputers() => SaveData(Computers, ComputerFileName,
"Computers", x => x.GetXElement);
public void SaveOrders() => SaveData(Orders, OrderFileName,
"Orders", x => x.GetXElement);
private static DataFileSingleton? _instance;
/// <summary>
/// Название файла для хранения информации о компонентах
/// </summary>
private readonly string ComponentFileName = "Component.xml";
/// <summary>
/// Название файла для хранения информации о заказах
/// </summary>
private readonly string OrderFileName = "Order.xml";
/// <summary>
/// Название файла для хранения информации о изделиях
/// </summary>
private readonly string ComputerFileName = "Computer.xml";
/// <summary>
/// Название файла для хранения информации о магазинах
/// </summary>
private readonly string ShopFileName = "Shop.xml";
/// <summary>
/// Список классов-моделей компонентов
/// </summary>
public List<Component> Components { get; set; }
/// <summary>
/// Список классов-моделей заказов
/// </summary>
public List<Order> Orders { get; set; }
/// <summary>
/// Список классов-моделей изделий
/// </summary>
public List<Computer> Computers { get; set; }
/// <summary>
/// Список классов-моделей магазина
/// </summary>
public List<Shop> Shops { get; set; }
/// <summary>
/// Конструктор
/// </summary>
private DataFileSingleton()
{
Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!;
Computers = LoadData(ComputerFileName, "Computer", x => Computer.Create(x)!)!;
Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!;
Shops = LoadData(ShopFileName, "Shop", x => Shop.Create(x)!)!;
}
private static List<T>? LoadData<T>(string filename, string xmlNodeName,
Func<XElement, T> selectFunction)
/// <summary>
/// Получить ссылку на класс
/// </summary>
/// <returns></returns>
public static DataFileSingleton GetInstance()
{
if (_instance == null)
{
_instance = new DataFileSingleton();
}
return _instance;
}
/// <summary>
/// Сохранение компонентов
/// </summary>
public void SaveComponents() => SaveData(Components, ComponentFileName, "Components", x => x.GetXElement);
/// <summary>
/// Сохранение изделий
/// </summary>
public void SaveComputers() => SaveData(Computers, ComputerFileName, "Computers", x => x.GetXElement);
/// <summary>
/// Сохранение заказов
/// </summary>
public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement);
/// <summary>
/// Сохранение магазинов
/// </summary>
public void SaveShops() => SaveData(Shops, ShopFileName, "Shops", x => x.GetXElement);
/// <summary>
/// Метод для загрузки данных из xml-файла
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="filename"></param>
/// <param name="xmlNodeName"></param>
/// <param name="selectFunction"></param>
/// <returns></returns>
private static List<T>? LoadData<T>(string filename, string xmlNodeName, Func<XElement, T> selectFunction)
{
if (File.Exists(filename))
{
@ -47,8 +113,16 @@ namespace ComputersShopFileImplement
}
return new List<T>();
}
private static void SaveData<T>(List<T> data, string filename,
string xmlNodeName, Func<T, XElement> selectFunction)
/// <summary>
/// Метод для сохранения данных в xml-файл
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data"></param>
/// <param name="filename"></param>
/// <param name="xmlNodeName"></param>
/// <param name="selectFunction"></param>
private static void SaveData<T>(List<T> data, string filename, string xmlNodeName, Func<T, XElement> selectFunction)
{
if (data != null)
{

View File

@ -13,70 +13,129 @@ namespace ComputersShopFileImplement.Implements
{
public class OrderStorage : IOrderStorage
{
private readonly DataFileSingleton source;
private readonly DataFileSingleton _source;
/// <summary>
/// Конструктор
/// </summary>
public OrderStorage()
{
source = DataFileSingleton.GetInstance();
_source = DataFileSingleton.GetInstance();
}
/// <summary>
/// Получение полного списка
/// </summary>
/// <returns></returns>
public List<OrderViewModel> GetFullList()
{
return source.Orders.Select(x => GetViewModel(x)).ToList();
return _source.Orders
.Select(x => GetViewModel(x))
.ToList();
}
public List<OrderViewModel> GetFiltredList(OrderSearchModel model)
/// <summary>
/// Получение фильтрованного списка
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return new();
}
return source.Orders.Where(x => x.Id == model.Id).Select(x => GetViewModel(x)).ToList();
return _source.Orders
.Where(x => x.Id.Equals(model.Id))
.Select(x => GetViewModel(x))
.ToList();
}
/// <summary>
/// Получение элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
return GetViewModel(source.Orders.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id));
}
public OrderViewModel? Update(OrderBindingModel model)
{
var order = source.Orders.FirstOrDefault(x => x.Id == model.Id);
if (order == null)
{
return null;
}
order.Update(model);
source.SaveOrders();
return GetViewModel(order);
return GetViewModel(_source.Orders
.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id)));
}
/// <summary>
/// Добавление элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
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);
if (newOrder == null)
{
return null;
}
source.Orders.Add(newOrder);
source.SaveOrders();
_source.Orders.Add(newOrder);
_source.SaveOrders();
return GetViewModel(newOrder);
}
public OrderViewModel? Delete(OrderBindingModel model)
/// <summary>
/// Редактирование элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
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)
{
return null;
}
source.Orders.Remove(order);
source.SaveOrders();
order.Update(model);
_source.SaveOrders();
return GetViewModel(order);
}
/// <summary>
/// Удаление элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public OrderViewModel? Delete(OrderBindingModel model)
{
var element = _source.Orders.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
_source.Orders.Remove(element);
_source.SaveOrders();
return GetViewModel(element);
}
return null;
}
/// <summary>
/// Получение модели заказа
/// </summary>
/// <param name="order"></param>
/// <returns></returns>
private OrderViewModel GetViewModel(Order order)
{
var viewModel = order.GetViewModel;
var computer = source.Computers.FirstOrDefault(x => x.Id == order.ComputerId);
viewModel.ComputerName = computer?.ComputerName;
var computer = _source.Computers.FirstOrDefault(x => x.Id == order.ComputerId);
if (computer != null)
{
viewModel.ComputerName = computer.ComputerName;
}
return viewModel;
}
}

View File

@ -0,0 +1,193 @@
using ComputersShopContracts.BindingModels;
using ComputersShopContracts.SearchModels;
using ComputersShopContracts.StoragesContracts;
using ComputersShopContracts.ViewModels;
using ComputersShopDataModels.Models;
using ComputersShopFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputersShopFileImplement.Implements
{
public class ShopStorage : IShopStorage
{
/// <summary>
/// Хранилище
/// </summary>
private readonly DataFileSingleton _source;
/// <summary>
/// Конструктор
/// </summary>
public ShopStorage()
{
_source = DataFileSingleton.GetInstance();
}
/// <summary>
/// Получение полного списка
/// </summary>
/// <returns></returns>
public List<ShopViewModel> GetFullList()
{
return _source.Shops
.Select(x => x.GetViewModel)
.ToList();
}
/// <summary>
/// Получение фильтрованного списка
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public List<ShopViewModel> GetFilteredList(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.ShopName))
{
return new();
}
return _source.Shops
.Where(x => x.ShopName.Contains(model.ShopName))
.Select(x => x.GetViewModel)
.ToList();
}
/// <summary>
/// Получение элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public ShopViewModel? GetElement(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.ShopName) && !model.Id.HasValue)
{
return null;
}
return _source.Shops
.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.ShopName) &&
x.ShopName == model.ShopName) ||
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
/// <summary>
/// Добавление элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public ShopViewModel? Insert(ShopBindingModel model)
{
model.Id = _source.Shops.Count > 0 ? _source.Shops.Max(x => x.Id) + 1 : 1;
var newShop = Shop.Create(model);
if (newShop == null)
{
return null;
}
_source.Shops.Add(newShop);
_source.SaveShops();
return newShop.GetViewModel;
}
/// <summary>
/// Редактирование элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public ShopViewModel? Update(ShopBindingModel model)
{
var shop = _source.Shops.FirstOrDefault(x => x.Id == model.Id);
if (shop == null)
{
return null;
}
shop.Update(model);
_source.SaveShops();
return shop.GetViewModel;
}
/// <summary>
/// Удаление элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public ShopViewModel? Delete(ShopBindingModel model)
{
var element = _source.Shops.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
_source.Shops.Remove(element);
_source.SaveShops();
return element.GetViewModel;
}
return null;
}
/// <summary>
/// Продажа изделий
/// </summary>
/// <param name="model"></param>
/// <param name="count"></param>
/// <returns></returns>
public bool SellComputers(IComputerModel model, int count)
{
var computer = _source.Computers.FirstOrDefault(x => x.Id == model.Id);
if (computer == null || !CheckCount(model, count))
{
return false;
}
foreach (var shop in _source.Shops)
{
var computers = shop.ShopComputers;
foreach (var elem in computers.Where(x => x.Value.Item1.Id == computer.Id))
{
var selling = Math.Min(elem.Value.Item2, count);
computers[elem.Value.Item1.Id] = (elem.Value.Item1, elem.Value.Item2 - selling);
count -= selling;
if (count <= 0)
{
break;
}
}
shop.Update(new ShopBindingModel
{
Id = model.Id,
ShopName = shop.ShopName,
Address = shop.Address,
DateOpening = shop.DateOpening,
ShopComputers = computers,
MaxComputers = shop.MaxComputers
});
}
_source.SaveShops();
return true;
}
/// <summary>
/// Проверка наличия в нужном количестве
/// </summary>
/// <param name="model"></param>
/// <param name="count"></param>
/// <returns></returns>
public bool CheckCount(IComputerModel model, int count)
{
int store = _source.Shops
.Select(x => x.ShopComputers
.Select(y => (y.Value.Item1.Id == model.Id ? y.Value.Item2 : 0))
.Sum()).Sum();
return store >= count;
}
}
}

View File

@ -0,0 +1,155 @@
using ComputersShopContracts.BindingModels;
using ComputersShopContracts.ViewModels;
using ComputersShopDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace ComputersShopFileImplement.Models
{
public class Shop : IShopModel
{
/// <summary>
/// Идентификатор
/// </summary>
public int Id { get; private set; }
/// <summary>
/// Название магазина
/// </summary>
public string ShopName { get; private set; } = string.Empty;
/// <summary>
/// Адрес магазина
/// </summary>
public string Address { get; private set; } = string.Empty;
/// <summary>
/// Дата открытия магазина
/// </summary>
public DateTime DateOpening { get; private set; }
/// <summary>
/// Коллекция изделий магазина в виде
/// «идентификатор изделия количество изделий»
/// </summary>
public Dictionary<int, int> Computers { get; private set; } = new();
/// <summary>
/// Коллекция изделий в магазине
/// </summary>
private Dictionary<int, (IComputerModel, int)>? _shopComputers = null;
public Dictionary<int, (IComputerModel, int)> ShopComputers
{
get
{
if (_shopComputers == null)
{
var source = DataFileSingleton.GetInstance();
_shopComputers = Computers.ToDictionary(x => x.Key, y => ((source.Computers.FirstOrDefault(z => z.Id == y.Key) as IComputerModel)!, y.Value));
}
return _shopComputers;
}
}
/// <summary>
/// Максимальное количество изделий
/// </summary>
public int MaxComputers { get; private set; }
/// <summary>
/// Создание модели магазина из данных файла
/// </summary>
/// <param name="element"></param>
/// <returns></returns>
public static Shop? Create(XElement element)
{
if (element == null)
{
return null;
}
return new()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
ShopName = element.Element("ShopName")!.Value,
Address = element.Element("Address")!.Value,
DateOpening = Convert.ToDateTime(element.Element("DateOpening")!.Value),
Computers = element.Element("ShopComputers")!.Elements("ShopComputers")!
.ToDictionary(x => Convert.ToInt32(x.Element("Key")?.Value), x => Convert.ToInt32(x.Element("Value")?.Value)),
MaxComputers = Convert.ToInt32(element.Element("MaxComputers")!.Value)
};
}
/// <summary>
/// Создание модели магазина
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public static Shop? Create(ShopBindingModel? model)
{
if (model == null)
{
return null;
}
return new Shop()
{
Id = model.Id,
ShopName = model.ShopName,
Address = model.Address,
DateOpening = model.DateOpening,
Computers = model.ShopComputers.ToDictionary(x => x.Key, x => x.Value.Item2),
MaxComputers = model.MaxComputers
};
}
/// <summary>
/// Изменение модели магазина
/// </summary>
/// <param name="model"></param>
public void Update(ShopBindingModel? model)
{
if (model == null)
{
return;
}
ShopName = model.ShopName;
Address = model.Address;
DateOpening = model.DateOpening;
Computers = model.ShopComputers.ToDictionary(x => x.Key, x => x.Value.Item2);
MaxComputers = model.MaxComputers;
_shopComputers = null;
}
/// <summary>
/// Получение модели магазина
/// </summary>
public ShopViewModel GetViewModel => new()
{
Id = Id,
ShopName = ShopName,
Address = Address,
DateOpening = DateOpening,
ShopComputers = ShopComputers,
MaxComputers = MaxComputers
};
/// <summary>
/// Запись данных о модели магазина в файл
/// </summary>
public XElement GetXElement => new("Shop",
new XAttribute("Id", Id),
new XElement("ShopName", ShopName),
new XElement("Address", Address),
new XElement("DateOpening", DateOpening.ToString()),
new XElement("ShopComputers", Computers.Select(x =>
new XElement("ShopComputers",
new XElement("Key", x.Key),
new XElement("Value", x.Value))).ToArray()),
new XElement("MaxComputers", MaxComputers.ToString()));
}
}

View File

@ -11,10 +11,30 @@ namespace AbstractShopListImplement
public class DataListSingleton
{
private static DataListSingleton? _instance;
/// <summary>
/// Список классов-моделей компонентов
/// </summary>
public List<Component> Components { get; set; }
/// <summary>
/// Список классов-моделей заказов
/// </summary>
public List<Order> Orders { get; set; }
/// <summary>
/// Список классов-моделей изделий
/// </summary>
public List<Computer> Computers { get; set; }
/// <summary>
/// Список классов-моделей магазинов
/// </summary>
public List<Shop> Shops { get; set; }
/// <summary>
/// Конструктор
/// </summary>
private DataListSingleton()
{
Components = new List<Component>();
@ -22,6 +42,11 @@ namespace AbstractShopListImplement
Computers = new List<Computer>();
Shops = new List<Shop>();
}
/// <summary>
/// Получить ссылку на класс
/// </summary>
/// <returns></returns>
public static DataListSingleton GetInstance()
{
if (_instance == null)

View File

@ -15,50 +15,79 @@ namespace ComputersShopListImplement.Implements
public class OrderStorage : IOrderStorage
{
private readonly DataListSingleton _source;
/// <summary>
/// Конструктор
/// </summary>
public OrderStorage()
{
_source = DataListSingleton.GetInstance();
}
/// <summary>
/// Получение полного списка
/// </summary>
/// <returns></returns>
public List<OrderViewModel> GetFullList()
{
var result = new List<OrderViewModel>();
foreach (var order in _source.Orders)
{
result.Add(AddComputerName(order.GetViewModel));
result.Add(order.GetViewModel);
}
return result;
}
public List<OrderViewModel> GetFiltredList(OrderSearchModel model)
/// <summary>
/// Получение фильтрованного списка
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
var result = new List<OrderViewModel>();
if (model == null || !model.Id.HasValue)
if (!model.Id.HasValue)
{
return result;
}
foreach (var order in _source.Orders)
{
if (order.Id == model.Id)
{
result.Add(AddComputerName(order.GetViewModel));
result.Add(order.GetViewModel);
}
}
return result;
}
/// <summary>
/// Получение элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
foreach (var order in _source.Orders)
{
if (model.Id.HasValue && order.Id == model.Id)
{
return AddComputerName(order.GetViewModel);
return order.GetViewModel;
}
}
return null;
}
/// <summary>
/// Добавление элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public OrderViewModel? Insert(OrderBindingModel model)
{
model.Id = 1;
@ -69,14 +98,22 @@ namespace ComputersShopListImplement.Implements
model.Id = order.Id + 1;
}
}
var newOrder = Order.Create(model);
if (newOrder == null)
{
return null;
}
_source.Orders.Add(newOrder);
return AddComputerName(newOrder.GetViewModel);
return newOrder.GetViewModel;
}
/// <summary>
/// Редактирование элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public OrderViewModel? Update(OrderBindingModel model)
{
foreach (var order in _source.Orders)
@ -84,11 +121,17 @@ namespace ComputersShopListImplement.Implements
if (order.Id == model.Id)
{
order.Update(model);
return AddComputerName(order.GetViewModel);
return order.GetViewModel;
}
}
return null;
}
/// <summary>
/// Удаление элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public OrderViewModel? Delete(OrderBindingModel model)
{
for (int i = 0; i < _source.Orders.Count; ++i)
@ -97,20 +140,11 @@ namespace ComputersShopListImplement.Implements
{
var element = _source.Orders[i];
_source.Orders.RemoveAt(i);
return AddComputerName(element.GetViewModel);
return element.GetViewModel;
}
}
return null;
}
private OrderViewModel AddComputerName(OrderViewModel model)
{
var selectedComputer = _source.Computers.Find(computer => computer.Id == model.ComputerId);
if (selectedComputer != null)
{
model.ComputerName = selectedComputer.ComputerName;
}
return model;
}
}
}

View File

@ -9,6 +9,7 @@ using ComputersShopContracts.SearchModels;
using ComputersShopContracts.StoragesContracts;
using ComputersShopContracts.ViewModels;
using ComputersShopDataModels;
using ComputersShopDataModels.Models;
using ComputersShopListImplement.Models;
namespace ComputersShopListImplement.Implements
@ -16,10 +17,19 @@ namespace ComputersShopListImplement.Implements
public class ShopStorage : IShopStorage
{
private readonly DataListSingleton _source;
/// <summary>
/// Конструктор
/// </summary>
public ShopStorage()
{
_source = DataListSingleton.GetInstance();
}
/// <summary>
/// Получение полного списка
/// </summary>
/// <returns></returns>
public List<ShopViewModel> GetFullList()
{
var result = new List<ShopViewModel>();
@ -29,6 +39,12 @@ namespace ComputersShopListImplement.Implements
}
return result;
}
/// <summary>
/// Получение фильтрованного списка
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public List<ShopViewModel> GetFilteredList(ShopSearchModel model)
{
var result = new List<ShopViewModel>();
@ -46,6 +62,12 @@ namespace ComputersShopListImplement.Implements
}
return result;
}
/// <summary>
/// Получение элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public ShopViewModel? GetElement(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.ShopName) && !model.Id.HasValue)
@ -62,6 +84,12 @@ namespace ComputersShopListImplement.Implements
}
return null;
}
/// <summary>
/// Добавление элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public ShopViewModel? Insert(ShopBindingModel model)
{
model.Id = 1;
@ -82,6 +110,12 @@ namespace ComputersShopListImplement.Implements
_source.Shops.Add(newShop);
return newShop.GetViewModel;
}
/// <summary>
/// Редактирование элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public ShopViewModel? Update(ShopBindingModel model)
{
foreach (var shop in _source.Shops)
@ -94,6 +128,12 @@ namespace ComputersShopListImplement.Implements
}
return null;
}
/// <summary>
/// Удаление элемента
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public ShopViewModel? Delete(ShopBindingModel model)
{
for (int i = 0; i < _source.Shops.Count; ++i)
@ -107,5 +147,29 @@ namespace ComputersShopListImplement.Implements
}
return null;
}
/// <summary>
/// Продажа изделий
/// </summary>
/// <param name="computer"></param>
/// <param name="count"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool SellComputers(IComputerModel model, int count)
{
throw new NotImplementedException();
}
/// <summary>
/// Проверка наличия в нужном количестве
/// </summary>
/// <param name="model"></param>
/// <param name="count"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool CheckCount(IComputerModel model, int count)
{
throw new NotImplementedException();
}
}
}

View File

@ -13,14 +13,41 @@ namespace ComputersShopListImplement.Models
public class Shop : IShopModel
{
public int Id { get; private set; }
/// <summary>
/// Название магазина
/// </summary>
public string ShopName { get; private set; } = string.Empty;
/// <summary>
/// Адрес магазина
/// </summary>
public string Address { get; private set; } = string.Empty;
/// <summary>
/// Дата открытия магазина
/// </summary>
public DateTime DateOpening { get; private set; }
/// <summary>
/// Коллекция изделий в магазине
/// </summary>
public Dictionary<int, (IComputerModel, int)> ShopComputers
{
get;
private set;
} = new Dictionary<int, (IComputerModel, int)>();
/// <summary>
/// Максимальное количество изделий
/// </summary>
public int MaxComputers { get; private set; }
/// <summary>
/// Создание модели магазина
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public static Shop? Create(ShopBindingModel? model)
{
if (model == null)
@ -34,9 +61,15 @@ namespace ComputersShopListImplement.Models
ShopName = model.ShopName,
Address = model.Address,
DateOpening = model.DateOpening,
ShopComputers = model.ShopComputers
ShopComputers = model.ShopComputers,
MaxComputers = model.MaxComputers
};
}
/// <summary>
/// Изменение модели магазина
/// </summary>
/// <param name="model"></param>
public void Update(ShopBindingModel? model)
{
if (model == null)
@ -48,14 +81,20 @@ namespace ComputersShopListImplement.Models
Address = model.Address;
DateOpening = model.DateOpening;
ShopComputers = model.ShopComputers;
MaxComputers = model.MaxComputers;
}
/// <summary>
/// Получение модели магазина
/// </summary>
public ShopViewModel GetViewModel => new()
{
Id = Id,
ShopName = ShopName,
Address = Address,
DateOpening = DateOpening,
ShopComputers = ShopComputers
ShopComputers = ShopComputers,
MaxComputers = MaxComputers
};
}
}

View File

@ -40,6 +40,7 @@
this.buttonOrderReady = new System.Windows.Forms.Button();
this.buttonIssuedOrder = new System.Windows.Forms.Button();
this.buttonRef = new System.Windows.Forms.Button();
this.продажаИзделийToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.menuStrip1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
@ -61,7 +62,8 @@
this.компонентыToolStripMenuItem,
this.изделияToolStripMenuItem,
this.магазиныToolStripMenuItem,
this.поставкиToolStripMenuItem});
this.поставкиToolStripMenuItem,
this.продажаИзделийToolStripMenuItem});
this.справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem";
this.справочникиToolStripMenuItem.Size = new System.Drawing.Size(117, 24);
this.справочникиToolStripMenuItem.Text = "Справочники";
@ -157,6 +159,12 @@
this.buttonRef.UseVisualStyleBackColor = true;
this.buttonRef.Click += new System.EventHandler(this.ButtonRef_Click);
//
// продажаИзделийToolStripMenuItem
//
this.продажаИзделийToolStripMenuItem.Name = "продажаИзделийToolStripMenuItem";
this.продажаИзделийToolStripMenuItem.Size = new System.Drawing.Size(224, 26);
this.продажаИзделийToolStripMenuItem.Text = "Продажа изделий";
//
// FormMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
@ -195,5 +203,6 @@
private ToolStripMenuItem изделияToolStripMenuItem;
private ToolStripMenuItem магазиныToolStripMenuItem;
private ToolStripMenuItem поставкиToolStripMenuItem;
private ToolStripMenuItem продажаИзделийToolStripMenuItem;
}
}

View File

@ -80,6 +80,15 @@ namespace ComputersShopView
form.ShowDialog();
}
}
private void ПродажаизделийToolStripMenuItem_Click(object sender, EventArgs
e)
{
var services = Program.ServiceProvider?.GetService(typeof(FormSell));
if (services is FormSell form)
{
form.ShowDialog();
}
}
private void ButtonCreateOrder_Click(object sender, EventArgs e)
{
var service =

View File

@ -0,0 +1,120 @@
namespace ComputersShopView
{
partial class FormSell
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.labelComputer = new System.Windows.Forms.Label();
this.labelCount = new System.Windows.Forms.Label();
this.comboBoxComputer = new System.Windows.Forms.ComboBox();
this.textBoxCount = new System.Windows.Forms.TextBox();
this.buttonSave = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// labelComputer
//
this.labelComputer.AutoSize = true;
this.labelComputer.Location = new System.Drawing.Point(12, 50);
this.labelComputer.Name = "labelComputer";
this.labelComputer.Size = new System.Drawing.Size(71, 20);
this.labelComputer.TabIndex = 0;
this.labelComputer.Text = "Изделие:";
//
// labelCount
//
this.labelCount.AutoSize = true;
this.labelCount.Location = new System.Drawing.Point(12, 106);
this.labelCount.Name = "labelCount";
this.labelCount.Size = new System.Drawing.Size(93, 20);
this.labelCount.TabIndex = 1;
this.labelCount.Text = "Количество:";
//
// comboBoxComputer
//
this.comboBoxComputer.FormattingEnabled = true;
this.comboBoxComputer.Location = new System.Drawing.Point(137, 42);
this.comboBoxComputer.Name = "comboBoxComputer";
this.comboBoxComputer.Size = new System.Drawing.Size(267, 28);
this.comboBoxComputer.TabIndex = 2;
//
// textBoxCount
//
this.textBoxCount.Location = new System.Drawing.Point(137, 99);
this.textBoxCount.Name = "textBoxCount";
this.textBoxCount.Size = new System.Drawing.Size(267, 27);
this.textBoxCount.TabIndex = 3;
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(244, 154);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(94, 29);
this.buttonSave.TabIndex = 4;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.buttonSave_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(368, 154);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(94, 29);
this.buttonCancel.TabIndex = 5;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// FormSell
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(474, 199);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.textBoxCount);
this.Controls.Add(this.comboBoxComputer);
this.Controls.Add(this.labelCount);
this.Controls.Add(this.labelComputer);
this.Name = "FormSell";
this.Text = "Продажа";
this.Load += new System.EventHandler(this.FormSell_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Label labelComputer;
private Label labelCount;
private ComboBox comboBoxComputer;
private TextBox textBoxCount;
private Button buttonSave;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,107 @@
using ComputersShopContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ComputersShopView
{
public partial class FormSell : Form
{
private readonly ILogger _logger;
/// <summary>
/// Бизнес-логика для изделий
/// </summary>
private readonly IComputerLogic _logicC;
/// <summary>
/// Бизнес-логика для магазинов
/// </summary>
private readonly IShopLogic _logicS;
public FormSell(ILogger<FormSell> logger, IComputerLogic planeLogic, IShopLogic shopLogic)
{
InitializeComponent();
_logger = logger;
_logicC = planeLogic;
_logicS = shopLogic;
}
private void FormSell_Load(object sender, EventArgs e)
{
_logger.LogInformation("Загрузка изделий для продажи");
try
{
var list = _logicC.ReadList(null);
if (list != null)
{
comboBoxComputer.DisplayMember = "ComputerName";
comboBoxComputer.ValueMember = "Id";
comboBoxComputer.DataSource = list;
comboBoxComputer.SelectedItem = null;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка изделий");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Кнопка "Сохранить"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCount.Text))
{
MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxComputer.SelectedValue == null)
{
MessageBox.Show("Выберите изделие", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Продажа изделий");
_logger.LogInformation("Создание заказа");
try
{
var operationResult = _logicS.SellComputers(
_logicC.ReadElement(new() { Id = Convert.ToInt32(comboBoxComputer.SelectedValue) }),
Convert.ToInt32(textBoxCount.Text)
);
if (!operationResult)
{
throw new Exception("Ошибка при продаже изделий. Дополнительная информация в логах.");
}
MessageBox.Show("Продажа прошла успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка продажи изделий");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Кнопка "Отмена"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -35,11 +35,13 @@
this.textBoxAddress = new System.Windows.Forms.TextBox();
this.textBoxName = new System.Windows.Forms.TextBox();
this.dataGridViewShop = new System.Windows.Forms.DataGridView();
this.buttonSave = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.id = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ComputerName = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Count = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.buttonSave = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.labelMaxComputers = new System.Windows.Forms.Label();
this.textBoxMaxComputers = new System.Windows.Forms.TextBox();
((System.ComponentModel.ISupportInitialize)(this.dataGridViewShop)).BeginInit();
this.SuspendLayout();
//
@ -72,24 +74,24 @@
//
// dateTimePicker
//
this.dateTimePicker.Location = new System.Drawing.Point(104, 97);
this.dateTimePicker.Location = new System.Drawing.Point(121, 97);
this.dateTimePicker.Name = "dateTimePicker";
this.dateTimePicker.Size = new System.Drawing.Size(403, 27);
this.dateTimePicker.Size = new System.Drawing.Size(386, 27);
this.dateTimePicker.TabIndex = 3;
//
// textBoxAddress
//
this.textBoxAddress.Location = new System.Drawing.Point(104, 61);
this.textBoxAddress.Location = new System.Drawing.Point(121, 61);
this.textBoxAddress.Name = "textBoxAddress";
this.textBoxAddress.Size = new System.Drawing.Size(403, 27);
this.textBoxAddress.Size = new System.Drawing.Size(386, 27);
this.textBoxAddress.TabIndex = 4;
this.textBoxAddress.TextChanged += new System.EventHandler(this.FormShop_Load);
//
// textBoxName
//
this.textBoxName.Location = new System.Drawing.Point(104, 22);
this.textBoxName.Location = new System.Drawing.Point(121, 22);
this.textBoxName.Name = "textBoxName";
this.textBoxName.Size = new System.Drawing.Size(403, 27);
this.textBoxName.Size = new System.Drawing.Size(386, 27);
this.textBoxName.TabIndex = 5;
//
// dataGridViewShop
@ -99,33 +101,13 @@
this.id,
this.ComputerName,
this.Count});
this.dataGridViewShop.Location = new System.Drawing.Point(23, 156);
this.dataGridViewShop.Location = new System.Drawing.Point(23, 197);
this.dataGridViewShop.Name = "dataGridViewShop";
this.dataGridViewShop.RowHeadersWidth = 51;
this.dataGridViewShop.RowTemplate.Height = 29;
this.dataGridViewShop.Size = new System.Drawing.Size(507, 173);
this.dataGridViewShop.TabIndex = 6;
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(319, 354);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(94, 29);
this.buttonSave.TabIndex = 7;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.ButtonSave_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(436, 354);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(94, 29);
this.buttonCancel.TabIndex = 8;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.ButtonCancel_Click);
//
// id
//
this.id.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
@ -148,11 +130,49 @@
this.Count.MinimumWidth = 6;
this.Count.Name = "Count";
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(319, 376);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(94, 29);
this.buttonSave.TabIndex = 7;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.ButtonSave_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(436, 376);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(94, 29);
this.buttonCancel.TabIndex = 8;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.ButtonCancel_Click);
//
// labelMaxComputers
//
this.labelMaxComputers.AutoSize = true;
this.labelMaxComputers.Location = new System.Drawing.Point(12, 150);
this.labelMaxComputers.Name = "labelMaxComputers";
this.labelMaxComputers.Size = new System.Drawing.Size(103, 20);
this.labelMaxComputers.TabIndex = 9;
this.labelMaxComputers.Text = "Вместимость:";
//
// textBoxMaxComputers
//
this.textBoxMaxComputers.Location = new System.Drawing.Point(121, 147);
this.textBoxMaxComputers.Name = "textBoxMaxComputers";
this.textBoxMaxComputers.Size = new System.Drawing.Size(386, 27);
this.textBoxMaxComputers.TabIndex = 10;
//
// FormShop
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(546, 395);
this.ClientSize = new System.Drawing.Size(546, 417);
this.Controls.Add(this.textBoxMaxComputers);
this.Controls.Add(this.labelMaxComputers);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.dataGridViewShop);
@ -185,5 +205,7 @@
private DataGridViewTextBoxColumn id;
private DataGridViewTextBoxColumn ComputerName;
private DataGridViewTextBoxColumn Count;
private Label labelMaxComputers;
private TextBox textBoxMaxComputers;
}
}

View File

@ -43,6 +43,7 @@ namespace ComputersShopView
textBoxName.Text = view.ShopName;
textBoxAddress.Text = view.Address;
dateTimePicker.Text = view.DateOpening.ToString();
textBoxMaxComputers.Text = view.MaxComputers.ToString();
_shopComputers = view.ShopComputers ?? new Dictionary<int, (IComputerModel, int)>();
LoadData();
}
@ -108,7 +109,8 @@ namespace ComputersShopView
ShopName = textBoxName.Text,
Address = textBoxAddress.Text,
DateOpening = dateTimePicker.Value.Date,
ShopComputers = _shopComputers
ShopComputers = _shopComputers,
MaxComputers = Convert.ToInt32(textBoxMaxComputers.Text)
};
var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model);
if (!operationResult)

View File

@ -105,6 +105,11 @@
// numericUpDownCount
//
this.numericUpDownCount.Location = new System.Drawing.Point(142, 139);
this.numericUpDownCount.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.numericUpDownCount.Name = "numericUpDownCount";
this.numericUpDownCount.Size = new System.Drawing.Size(348, 27);
this.numericUpDownCount.TabIndex = 8;

View File

@ -50,6 +50,7 @@ namespace ComputersShopView
_logger.LogError(ex, "Ошибка загрузки списка магазинов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
_logger.LogInformation("Загрузка изделий");
try
{

View File

@ -67,6 +67,7 @@ namespace ComputersShopView
services.AddTransient<FormShops>();
services.AddTransient<FormShop>();
services.AddTransient<FormSupply>();
services.AddTransient<FormSell>();
}
}
}