diff --git a/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/OrderLogic.cs b/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/OrderLogic.cs index 7b27063..c3322c1 100644 --- a/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/OrderLogic.cs +++ b/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/OrderLogic.cs @@ -5,128 +5,179 @@ using MotorPlantContracts.StoragesContracts; using MotorPlantContracts.ViewModels; using Microsoft.Extensions.Logging; using MotorPlantDataModels.Enums; +using MotorPlantDataModels.Models; namespace MotorPlantBusinessLogic.BusinessLogics { public class OrderLogic : IOrderLogic { - private readonly ILogger _logger; - private readonly IOrderStorage _orderStorage; + private readonly ILogger _logger; + private readonly IOrderStorage _orderStorage; + private readonly IShopStorage _shopStorage; + private readonly IShopLogic _shopLogic; + private readonly IEngineStorage _engineStorage; + public OrderLogic(ILogger logger, IOrderStorage orderStorage, IShopStorage shopStorage, IShopLogic shopLogic, IEngineStorage engineStorage) + { + _logger = logger; + _orderStorage = orderStorage; + _shopStorage = shopStorage; + _shopLogic = shopLogic; + _engineStorage = engineStorage; + } - public OrderLogic(ILogger logger, IOrderStorage orderStorage) - { - _logger = logger; - _orderStorage = orderStorage; - } + public List? ReadList(OrderSearchModel? model) + { + _logger.LogInformation("ReadList. OrderId:{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; + } - public List? ReadList(OrderSearchModel? model) - { - _logger.LogInformation("ReadList. OrderId:{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; - } + private void CheckModel(OrderBindingModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (model.Count <= 0) + { + throw new ArgumentNullException("Количество заказов должно быть больше нуля"); + } + if (model.Sum <= 0) + { + throw new ArgumentNullException("Цена заказа должна быть больше нуля"); + } + _logger.LogInformation("Order. OrderId:{Id}. Sum:{Sum}", model.Id, model.Sum); + } - public bool CreateOrder(OrderBindingModel model) - { - CheckModel(model); + public bool CreateOrder(OrderBindingModel model) + { + CheckModel(model); + if (model.Status != OrderStatus.Неизвестен) + { + return false; + } + model.Status = OrderStatus.Принят; + if (_orderStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; - if (model.Status != OrderStatus.Неизвестен) - return false; - model.Status = OrderStatus.Принят; + } - if (_orderStorage.Insert(model) == null) - { - model.Status = OrderStatus.Неизвестен; - _logger.LogWarning("Insert operation failed"); - return false; - } - return true; - } + private bool ChangeStatus(OrderBindingModel model, OrderStatus status) + { + var element = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id }); + if (element == null) + { + _logger.LogWarning("Find order failed"); + return false; + } + if (element.Status != status - 1) + { + _logger.LogWarning("Status change failed"); + throw new InvalidOperationException("Невозможно перевести состояние заказа"); + } + if (status == OrderStatus.Готов) + { + var engine = _engineStorage.GetElement(new EngineSearchModel() { Id = model.EngineId }); + if (engine == null) + { + _logger.LogWarning("Status change error. Engine not found"); + return false; + } + if (!CheckSupply(engine, model.Count)) + { + _logger.LogWarning("Status change error. Shop doesnt have engines"); + return false; + } + } + model.Status = status; + if (model.Status == OrderStatus.Выдан) model.DateImplement = DateTime.Now; + _orderStorage.Update(model); + return true; + } - public bool TakeOrderInWork(OrderBindingModel model) - { - return ToNextStatus(model, OrderStatus.Выполняется); - } + public bool TakeOrderInWork(OrderBindingModel model) + { + return ChangeStatus(model, OrderStatus.Выполняется); + } - public bool FinishOrder(OrderBindingModel model) - { - return ToNextStatus(model, OrderStatus.Готов); - } + public bool FinishOrder(OrderBindingModel model) + { + return ChangeStatus(model, OrderStatus.Готов); + } - public bool DeliveryOrder(OrderBindingModel model) - { - return ToNextStatus(model, OrderStatus.Выдан); - } + public bool DeliveryOrder(OrderBindingModel model) + { + return ChangeStatus(model, OrderStatus.Выдан); + } - public bool ToNextStatus(OrderBindingModel model, OrderStatus orderStatus) - { - CheckModel(model, false); - var element = _orderStorage.GetElement(new OrderSearchModel() - { - Id = model.Id - }); - if (element == null) - { - throw new ArgumentNullException(nameof(element)); - } + public bool CheckSupply(IEngineModel engine, int count) + { + if (count <= 0) + { + _logger.LogWarning("Check supply operation error. Engine count < 0"); + return false; + } + int sumCapacity = _shopStorage.GetFullList().Select(x => x.MaxCount).Sum(); + int sumCount = _shopStorage.GetFullList().Select(x => x.ShopEngines.Select(y => y.Value.Item2).Sum()).Sum(); + int free = sumCapacity - sumCount; - model.EngineId = element.EngineId; - model.DateCreate = element.DateCreate; - model.DateImplement = element.DateImplement; - model.Status = element.Status; - model.Count = element.Count; - model.Sum = element.Sum; - - if (model.Status != orderStatus - 1) - { - _logger.LogWarning("Status update to " + orderStatus + " operation failed"); - return false; - } - model.Status = orderStatus; - - if (model.Status == OrderStatus.Выдан) - { - model.DateImplement = DateTime.Now; - } - - if (_orderStorage.Update(model) == null) - { - model.Status--; - _logger.LogWarning("Changing status operation faled"); - return false; - } - return true; - } - - private void CheckModel(OrderBindingModel model, bool withParams = true) - { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - if (!withParams) - { - return; - } - if (model.Count <= 0) - { - throw new ArgumentNullException("Количество изделий должно быть больше 0", nameof(model.Count)); - } - if (model.Sum <= 0) - { - throw new ArgumentNullException("Цена заказа должна быть больше 0", nameof(model.Sum)); - } - if (model.DateImplement.HasValue && model.DateImplement < model.DateCreate) - { - throw new ArithmeticException($"Дата выдачи заказа {model.DateImplement} должна быть позже даты его создания {model.DateCreate}"); - } - _logger.LogInformation("Engine. EngineId:{EngineId}.Count:{Count}.Sum:{Sum}Id:{Id}", model.EngineId, model.Count, model.Sum, model.Id); - } - } + if (free < count) + { + _logger.LogWarning("Check supply error. No place for new Engines"); + return false; + } + foreach (var shop in _shopStorage.GetFullList()) + { + free = shop.MaxCount; + foreach (var doc in shop.ShopEngines) + { + free -= doc.Value.Item2; + } + if (free == 0) + { + continue; + } + if (free >= count) + { + if (_shopLogic.MakeSupply(new() + { + Id = shop.Id + }, engine, count)) + { + count = 0; + } + else + { + _logger.LogWarning("Supply error"); + return false; + } + } + else + { + if (_shopLogic.MakeSupply(new() { Id = shop.Id }, engine, free)) + count -= free; + else + { + _logger.LogWarning("Supply error"); + return false; + } + } + if (count <= 0) + { + return true; + } + } + return false; + } + } } diff --git a/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ShopLogic.cs b/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ShopLogic.cs new file mode 100644 index 0000000..35e65a1 --- /dev/null +++ b/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ShopLogic.cs @@ -0,0 +1,174 @@ +using Microsoft.Extensions.Logging; +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.BusinessLogicsContracts; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.StoragesContracts; +using MotorPlantContracts.ViewModels; +using MotorPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantBusinessLogic.BusinessLogic +{ + public class ShopLogic : IShopLogic + { + private readonly ILogger _logger; + private readonly IShopStorage _shopStorage; + + public ShopLogic(ILogger logger, IShopStorage shopStorage) + { + _logger = logger; + _shopStorage = shopStorage; + } + + public List ReadList(ShopSearchModel model) + { + _logger.LogInformation("ReadList. ShopName:{Name}. Id:{ Id}", model?.Name, model?.Id); + var list = model == null ? _shopStorage.GetFullList() : _shopStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + _logger.LogInformation("ReadList. Count:{Count}", list.Count); + return list; + } + + public ShopViewModel ReadElement(ShopSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + _logger.LogInformation("ReadElement. ShopName:{ShopName}.Id:{ Id}", model.Name, model.Id); + var element = _shopStorage.GetElement(model); + if (element == null) + { + _logger.LogWarning("ReadElement element not found"); + return null; + } + _logger.LogInformation("ReadElement find. Id:{Id}", element.Id); + return element; + } + + public bool Create(ShopBindingModel model) + { + CheckModel(model); + if (_shopStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } + + public bool Update(ShopBindingModel model) + { + CheckModel(model); + if (_shopStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + return true; + } + public bool Delete(ShopBindingModel model) + { + CheckModel(model, false); + _logger.LogInformation("Delete. Id:{Id}", model.Id); + if (_shopStorage.Delete(model) == null) + { + _logger.LogWarning("Delete operation failed"); + return false; + } + return true; + } + + private void CheckModel(ShopBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (!withParams) + { + return; + } + if (string.IsNullOrEmpty(model.ShopName)) + { + throw new ArgumentNullException("Нет названия магазина", + nameof(model.ShopName)); + } + if (string.IsNullOrEmpty(model.Adress)) + { + throw new ArgumentNullException("Нет адресса магазина", + nameof(model.ShopName)); + } + if (model.DateOpen == null) + { + throw new ArgumentNullException("Нет даты открытия магазина", + nameof(model.ShopName)); + } + _logger.LogInformation("Shop. ShopName:{ShopName}.Address:{Address}. DateOpen:{DateOpen}. Id: { Id}", model.ShopName, model.Adress, model.DateOpen, model.Id); + var element = _shopStorage.GetElement(new ShopSearchModel + { + Name = model.ShopName + }); + if (element != null && element.Id != model.Id) + { + throw new InvalidOperationException("Магазин с таким названием уже есть"); + } + } + + public bool MakeSell(IEngineModel model, int count) + { + return _shopStorage.SellEngines(model, count); + } + + public bool MakeSupply(ShopSearchModel model, IEngineModel engine, int count) + { + if (model == null) + throw new ArgumentNullException(nameof(model)); + if (engine == null) + throw new ArgumentNullException(nameof(engine)); + if (count <= 0) + throw new ArgumentNullException("Количество должно быть положительным числом"); + + ShopViewModel? curModel = _shopStorage.GetElement(model); + _logger.LogInformation("Make Supply. Id: {Id}. ShopName: {Name}", model.Id, model.Name); + if (curModel == null) + throw new ArgumentNullException(nameof(curModel)); + + var countItems = curModel.ShopEngines.Select(x => x.Value.Item2).Sum(); + if (curModel.MaxCount - countItems < count) + { + _logger.LogWarning("Shop is overflowed"); + return false; + } + + if (curModel.ShopEngines.TryGetValue(engine.Id, out var pair)) + { + curModel.ShopEngines[engine.Id] = (pair.Item1, pair.Item2 + count); + _logger.LogInformation("Make Supply. Add Dress. ShopName: {ShopName}. DressName: {Name}. Count: {Count}", curModel.ShopName, pair.Item1, count + pair.Item2); + } + else + { + curModel.ShopEngines.Add(engine.Id, (engine, count)); + _logger.LogInformation("Make Supply. Add new Dress. ShopName: {ShopName}. DressName: {Name}. Count: {Count}", curModel.ShopName, pair.Item1, count); + } + + return Update(new() + { + Id = curModel.Id, + ShopName = curModel.ShopName, + DateOpen = curModel.DateOpen, + MaxCount = curModel.MaxCount, + Adress = curModel.Adress, + ShopEngines = curModel.ShopEngines, + }); + } + } +} diff --git a/MotorPlant/MotorPlantContracts/BindingModels/ShopBindingModel.cs b/MotorPlant/MotorPlantContracts/BindingModels/ShopBindingModel.cs new file mode 100644 index 0000000..75dbc6f --- /dev/null +++ b/MotorPlant/MotorPlantContracts/BindingModels/ShopBindingModel.cs @@ -0,0 +1,19 @@ +using MotorPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.BindingModels +{ + public class ShopBindingModel : IShopModel + { + public int Id { get; set; } + public string ShopName { get; set; } + public string Adress { get; set; } + public DateTime DateOpen { get; set; } + public int MaxCount { get; set; } + public Dictionary ShopEngines { get; set; } = new(); + } +} diff --git a/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IShopLogic.cs b/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IShopLogic.cs new file mode 100644 index 0000000..ce4f7b0 --- /dev/null +++ b/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IShopLogic.cs @@ -0,0 +1,23 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.ViewModels; +using MotorPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.BusinessLogicsContracts +{ + public interface IShopLogic + { + List? ReadList(ShopSearchModel? model); + ShopViewModel? ReadElement(ShopSearchModel? model); + bool Create(ShopBindingModel? model); + bool Update(ShopBindingModel? model); + bool Delete(ShopBindingModel? model); + bool MakeSupply(ShopSearchModel model, IEngineModel engine, int count); + bool MakeSell(IEngineModel model, int count); + } +} diff --git a/MotorPlant/MotorPlantContracts/SearchModels/ShopSearchModel.cs b/MotorPlant/MotorPlantContracts/SearchModels/ShopSearchModel.cs new file mode 100644 index 0000000..470bafb --- /dev/null +++ b/MotorPlant/MotorPlantContracts/SearchModels/ShopSearchModel.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.SearchModels +{ + public class ShopSearchModel + { + public int? Id { get; set; } + public string? Name { get; set; } + } +} diff --git a/MotorPlant/MotorPlantContracts/StoragesContracts/IShopStorage.cs b/MotorPlant/MotorPlantContracts/StoragesContracts/IShopStorage.cs new file mode 100644 index 0000000..0fb2755 --- /dev/null +++ b/MotorPlant/MotorPlantContracts/StoragesContracts/IShopStorage.cs @@ -0,0 +1,23 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.ViewModels; +using MotorPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.StoragesContracts +{ + public interface IShopStorage + { + List GetFullList(); + List GetFilteredList(ShopSearchModel model); + ShopViewModel? GetElement(ShopSearchModel model); + ShopViewModel? Insert(ShopBindingModel model); + ShopViewModel? Update(ShopBindingModel model); + ShopViewModel? Delete(ShopBindingModel model); + bool SellEngines(IEngineModel model, int count); + } +} diff --git a/MotorPlant/MotorPlantContracts/ViewModels/ShopViewModel.cs b/MotorPlant/MotorPlantContracts/ViewModels/ShopViewModel.cs new file mode 100644 index 0000000..7e595f5 --- /dev/null +++ b/MotorPlant/MotorPlantContracts/ViewModels/ShopViewModel.cs @@ -0,0 +1,33 @@ +using MotorPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.ViewModels +{ + public class ShopViewModel : IShopModel + { + public int Id { get; set; } + + [DisplayName("Название магазина")] + + public string ShopName { get; set; } = string.Empty; + + [DisplayName("Адрес")] + + public string Adress { get; set; } = string.Empty; + + [DisplayName("Дата открытия")] + + public DateTime DateOpen { get; set; } + + [DisplayName("Вмещаемость")] + + public int MaxCount { get; set; } + + public Dictionary ShopEngines { get; set; } = new(); + } +} diff --git a/MotorPlant/MotorPlantDataModels/Models/IShopModel.cs b/MotorPlant/MotorPlantDataModels/Models/IShopModel.cs new file mode 100644 index 0000000..fef931e --- /dev/null +++ b/MotorPlant/MotorPlantDataModels/Models/IShopModel.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantDataModels.Models +{ + public interface IShopModel : IId + { + string ShopName { get; } + string Adress { get; } + DateTime DateOpen { get; } + int MaxCount { get; } + } +} diff --git a/MotorPlant/MotorPlantDatabaseImplement/Implements/OrderStorage.cs b/MotorPlant/MotorPlantDatabaseImplement/Implements/OrderStorage.cs index 3f17cc1..f198b99 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Implements/OrderStorage.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Implements/OrderStorage.cs @@ -13,8 +13,10 @@ namespace MotorPlantDatabaseImplement.Implements public List GetFullList() { using var context = new MotorPlantDatabase(); - return context.Orders.Include(x => x.Engine).Select(x => x.GetViewModel).ToList(); - } + return context.Orders + .Select(x => AccessEngineStorage(x.GetViewModel)) + .ToList(); + } public List GetFilteredList(OrderSearchModel model) { if (!model.Id.HasValue && !model.DateFrom.HasValue) @@ -22,6 +24,8 @@ namespace MotorPlantDatabaseImplement.Implements return new(); } using var context = new MotorPlantDatabase(); + return context.Orders.Where(x => x.Id == model.Id).Select(x => AccessEngineStorage(x.GetViewModel)).ToList(); + } if (model.DateFrom.HasValue) { return context.Orders @@ -38,59 +42,66 @@ namespace MotorPlantDatabaseImplement.Implements } public OrderViewModel? GetElement(OrderSearchModel model) { - if (!model.Id.HasValue) - { - return null; - } - using var context = new MotorPlantDatabase(); - return context.Orders.Include(x => x.Engine) - .FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; - } + if (!model.Id.HasValue) + { + return null; + } + using var context = new MotorPlantDatabase(); + return AccessEngineStorage(context.Orders.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel); + } public OrderViewModel? Insert(OrderBindingModel model) { - var newOrder = Order.Create(model); - if (newOrder == null) - { - return null; - } - using var context = new MotorPlantDatabase(); - context.Orders.Add(newOrder); - context.SaveChanges(); - return context.Orders - .Include(x => x.Engine) - .FirstOrDefault(x => x.Id == newOrder.Id) - ?.GetViewModel; - } + var newOrder = Order.Create(model); + if (newOrder == null) + { + return null; + } + using var context = new MotorPlantDatabase(); + context.Orders.Add(newOrder); + context.SaveChanges(); + return AccessEngineStorage(newOrder.GetViewModel); + } public OrderViewModel? Update(OrderBindingModel model) { - using var context = new MotorPlantDatabase(); - var order = context.Orders.FirstOrDefault(x => x.Id == model.Id); - if (order == null) - { - return null; - } - order.Update(model); - context.SaveChanges(); - return context.Orders - .Include(x => x.Engine) - .FirstOrDefault(x => x.Id == model.Id) - ?.GetViewModel; - } - public OrderViewModel? Delete(OrderBindingModel model) - { - using var context = new MotorPlantDatabase(); - var element = context.Orders.FirstOrDefault(rec => rec.Id == model.Id); - if (element != null) - { - var deletedElement = context.Orders - .Include(x => x.Engine) - .FirstOrDefault(x => x.Id == model.Id) - ?.GetViewModel; - context.Orders.Remove(element); - context.SaveChanges(); - return deletedElement; - } - return null; - } - } + using var context = new MotorPlantDatabase(); + var order = context.Orders.FirstOrDefault(x => x.Id == + model.Id); + if (order == null) + { + return null; + } + order.Update(model); + context.SaveChanges(); + return AccessEngineStorage(order.GetViewModel); + } + + public OrderViewModel? Delete(OrderBindingModel model) + { + using var context = new MotorPlantDatabase(); + var element = context.Orders.FirstOrDefault(rec => rec.Id == model.Id); + if (element != null) + { + context.Orders.Remove(element); + context.SaveChanges(); + return AccessEngineStorage(element.GetViewModel); + } + return null; + } + + public static OrderViewModel AccessEngineStorage(OrderViewModel model) + { + if (model == null) + return null; + using var context = new MotorPlantDatabase(); + foreach (var Engine in context.Engines) + { + if (Engine.Id == model.EngineId) + { + model.EngineName = Engine.EngineName; + break; + } + } + return model; + } + } } diff --git a/MotorPlant/MotorPlantDatabaseImplement/Implements/ShopStorage.cs b/MotorPlant/MotorPlantDatabaseImplement/Implements/ShopStorage.cs new file mode 100644 index 0000000..5772557 --- /dev/null +++ b/MotorPlant/MotorPlantDatabaseImplement/Implements/ShopStorage.cs @@ -0,0 +1,144 @@ +using Microsoft.EntityFrameworkCore; +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.StoragesContracts; +using MotorPlantContracts.ViewModels; +using MotorPlantDatabaseImplement.Models; +using MotorPlantDataModels.Models; + +namespace MotorPlantDatabaseImplement.Implements +{ + public class ShopStorage : IShopStorage + { + public ShopViewModel? Delete(ShopBindingModel model) + { + using var context = new MotorPlantDatabase(); + var element = context.Shops.FirstOrDefault(x => x.Id == model.Id); + if (element != null) + { + context.Shops.Remove(element); + context.SaveChanges(); + return element.GetViewModel; + } + return null; + } + + public ShopViewModel? GetElement(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.Name) && !model.Id.HasValue) + { + return null; + } + using var context = new MotorPlantDatabase(); + return context.Shops.Include(x => x.Engines).ThenInclude(x => x.Engine).FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)?.GetViewModel; + } + + public List GetFilteredList(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.Name)) + { + return new(); + } + using var context = new MotorPlantDatabase(); + return context.Shops + .Include(x => x.Engines) + .ThenInclude(x => x.Engine) + .Select(x => x.GetViewModel) + .Where(x => x.ShopName.Contains(model.Name ?? string.Empty)) + .ToList(); + } + + public List GetFullList() + { + using var context = new MotorPlantDatabase(); + return context.Shops + .Include(x => x.Engines) + .ThenInclude(x => x.Engine) + .Select(x => x.GetViewModel) + .ToList(); + } + + public ShopViewModel? Insert(ShopBindingModel model) + { + using var context = new MotorPlantDatabase(); + try + { + var newShop = Shop.Create(context, model); + if (newShop == null) + { + return null; + } + if (context.Shops.Any(x => x.ShopName == newShop.ShopName)) + { + throw new Exception("Не должно быть два магазина с одним названием"); + } + context.Shops.Add(newShop); + context.SaveChanges(); + return newShop.GetViewModel; + } + catch + { + throw; + } + } + + public ShopViewModel? Update(ShopBindingModel model) + { + using var context = new MotorPlantDatabase(); + var shop = context.Shops.FirstOrDefault(x => x.Id == model.Id); + if (shop == null) + { + return null; + } + try + { + if (context.Shops.Any(x => (x.ShopName == model.ShopName && x.Id != model.Id))) + { + throw new Exception("Не должно быть два магазина с одним названием"); + } + shop.Update(model); + shop.UpdateDresses(context, model); + context.SaveChanges(); + return shop.GetViewModel; + } + catch + { + throw; + } + } + public bool SellEngines(IEngineModel model, int count) + { + if (model == null) + return false; + using var context = new MotorPlantDatabase(); + using var transaction = context.Database.BeginTransaction(); + List lst = new List(); + foreach (var el in context.ShopEngines.Where(x => x.EngineId == model.Id)) + { + int dif = count; + if (el.Count < dif) + dif = el.Count; + el.Count -= dif; + count -= dif; + if (el.Count == 0) + { + lst.Add(el); + } + if (count == 0) + break; + } + if (count > 0) + { + transaction.Rollback(); + return false; + } + foreach (var el in lst) + { + context.ShopEngines.Remove(el); + } + context.SaveChanges(); + transaction.Commit(); + return true; + } + } +} diff --git a/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240404091307_NewMig.Designer.cs b/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240404091307_NewMig.Designer.cs deleted file mode 100644 index c0cfe9f..0000000 --- a/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240404091307_NewMig.Designer.cs +++ /dev/null @@ -1,171 +0,0 @@ -// -using System; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Migrations; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; -using MotorPlantDatabaseImplement; -using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; - -#nullable disable - -namespace MotorPlantDatabaseImplement.Migrations -{ - [DbContext(typeof(MotorPlantDatabase))] - [Migration("20240404091307_NewMig")] - partial class NewMig - { - /// - protected override void BuildTargetModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder - .HasAnnotation("ProductVersion", "7.0.16") - .HasAnnotation("Relational:MaxIdentifierLength", 63); - - NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); - - modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Component", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("integer"); - - NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); - - b.Property("ComponentName") - .IsRequired() - .HasColumnType("text"); - - b.Property("Cost") - .HasColumnType("double precision"); - - b.HasKey("Id"); - - b.ToTable("Components"); - }); - - modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Engine", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("integer"); - - NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); - - b.Property("EngineName") - .IsRequired() - .HasColumnType("text"); - - b.Property("Price") - .HasColumnType("double precision"); - - b.HasKey("Id"); - - b.ToTable("Engines"); - }); - - modelBuilder.Entity("MotorPlantDatabaseImplement.Models.EngineComponent", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("integer"); - - NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); - - b.Property("ComponentId") - .HasColumnType("integer"); - - b.Property("Count") - .HasColumnType("integer"); - - b.Property("EngineId") - .HasColumnType("integer"); - - b.HasKey("Id"); - - b.HasIndex("ComponentId"); - - b.HasIndex("EngineId"); - - b.ToTable("EngineComponents"); - }); - - modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Order", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("integer"); - - NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); - - b.Property("Count") - .HasColumnType("integer"); - - b.Property("DateCreate") - .HasColumnType("timestamp without time zone"); - - b.Property("DateImplement") - .HasColumnType("timestamp without time zone"); - - b.Property("EngineId") - .HasColumnType("integer"); - - b.Property("Status") - .HasColumnType("integer"); - - b.Property("Sum") - .HasColumnType("double precision"); - - b.HasKey("Id"); - - b.HasIndex("EngineId"); - - b.ToTable("Orders"); - }); - - modelBuilder.Entity("MotorPlantDatabaseImplement.Models.EngineComponent", b => - { - b.HasOne("MotorPlantDatabaseImplement.Models.Component", "Component") - .WithMany("EngineComponents") - .HasForeignKey("ComponentId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("MotorPlantDatabaseImplement.Models.Engine", "Engine") - .WithMany("Components") - .HasForeignKey("EngineId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Component"); - - b.Navigation("Engine"); - }); - - modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Order", b => - { - b.HasOne("MotorPlantDatabaseImplement.Models.Engine", "Engine") - .WithMany("Orders") - .HasForeignKey("EngineId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Engine"); - }); - - modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Component", b => - { - b.Navigation("EngineComponents"); - }); - - modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Engine", b => - { - b.Navigation("Components"); - - b.Navigation("Orders"); - }); -#pragma warning restore 612, 618 - } - } -} diff --git a/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240404091307_NewMig.cs b/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240411140319_NewMig.cs similarity index 66% rename from MotorPlant/MotorPlantDatabaseImplement/Migrations/20240404091307_NewMig.cs rename to MotorPlant/MotorPlantDatabaseImplement/Migrations/20240411140319_NewMig.cs index 074eca0..5a17410 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240404091307_NewMig.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240411140319_NewMig.cs @@ -40,6 +40,22 @@ namespace MotorPlantDatabaseImplement.Migrations table.PrimaryKey("PK_Engines", x => x.Id); }); + migrationBuilder.CreateTable( + name: "Shops", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + ShopName = table.Column(type: "text", nullable: false), + Adress = table.Column(type: "text", nullable: false), + DateOpen = table.Column(type: "timestamp without time zone", nullable: false), + MaxCount = table.Column(type: "integer", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Shops", x => x.Id); + }); + migrationBuilder.CreateTable( name: "EngineComponents", columns: table => new @@ -91,6 +107,33 @@ namespace MotorPlantDatabaseImplement.Migrations onDelete: ReferentialAction.Cascade); }); + migrationBuilder.CreateTable( + name: "ShopEngines", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + EngineId = table.Column(type: "integer", nullable: false), + ShopId = table.Column(type: "integer", nullable: false), + Count = table.Column(type: "integer", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ShopEngines", x => x.Id); + table.ForeignKey( + name: "FK_ShopEngines_Engines_EngineId", + column: x => x.EngineId, + principalTable: "Engines", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_ShopEngines_Shops_ShopId", + column: x => x.ShopId, + principalTable: "Shops", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + migrationBuilder.CreateIndex( name: "IX_EngineComponents_ComponentId", table: "EngineComponents", @@ -105,6 +148,16 @@ namespace MotorPlantDatabaseImplement.Migrations name: "IX_Orders_EngineId", table: "Orders", column: "EngineId"); + + migrationBuilder.CreateIndex( + name: "IX_ShopEngines_EngineId", + table: "ShopEngines", + column: "EngineId"); + + migrationBuilder.CreateIndex( + name: "IX_ShopEngines_ShopId", + table: "ShopEngines", + column: "ShopId"); } /// @@ -116,11 +169,17 @@ namespace MotorPlantDatabaseImplement.Migrations migrationBuilder.DropTable( name: "Orders"); + migrationBuilder.DropTable( + name: "ShopEngines"); + migrationBuilder.DropTable( name: "Components"); migrationBuilder.DropTable( name: "Engines"); + + migrationBuilder.DropTable( + name: "Shops"); } } } diff --git a/MotorPlant/MotorPlantDatabaseImplement/Migrations/MotorPlantDatabaseModelSnapshot.cs b/MotorPlant/MotorPlantDatabaseImplement/Migrations/MotorPlantDatabaseModelSnapshot.cs index 8e0807e..e59cde0 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Migrations/MotorPlantDatabaseModelSnapshot.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Migrations/MotorPlantDatabaseModelSnapshot.cs @@ -121,6 +121,59 @@ namespace MotorPlantDatabaseImplement.Migrations b.ToTable("Orders"); }); + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Shop", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Adress") + .IsRequired() + .HasColumnType("text"); + + b.Property("DateOpen") + .HasColumnType("timestamp without time zone"); + + b.Property("MaxCount") + .HasColumnType("integer"); + + b.Property("ShopName") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("Shops"); + }); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.ShopEngine", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Count") + .HasColumnType("integer"); + + b.Property("EngineId") + .HasColumnType("integer"); + + b.Property("ShopId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("EngineId"); + + b.HasIndex("ShopId"); + + b.ToTable("ShopEngines"); + }); + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.EngineComponent", b => { b.HasOne("MotorPlantDatabaseImplement.Models.Component", "Component") @@ -142,13 +195,30 @@ namespace MotorPlantDatabaseImplement.Migrations modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Order", b => { - b.HasOne("MotorPlantDatabaseImplement.Models.Engine", "Engine") + b.HasOne("MotorPlantDatabaseImplement.Models.Engine", null) .WithMany("Orders") .HasForeignKey("EngineId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); + }); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.ShopEngine", b => + { + b.HasOne("MotorPlantDatabaseImplement.Models.Engine", "Engine") + .WithMany() + .HasForeignKey("EngineId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("MotorPlantDatabaseImplement.Models.Shop", "Shop") + .WithMany("Engines") + .HasForeignKey("ShopId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); b.Navigation("Engine"); + + b.Navigation("Shop"); }); modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Component", b => @@ -162,6 +232,11 @@ namespace MotorPlantDatabaseImplement.Migrations b.Navigation("Orders"); }); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Shop", b => + { + b.Navigation("Engines"); + }); #pragma warning restore 612, 618 } } diff --git a/MotorPlant/MotorPlantDatabaseImplement/Models/Order.cs b/MotorPlant/MotorPlantDatabaseImplement/Models/Order.cs index 00cb15b..7355218 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Models/Order.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Models/Order.cs @@ -27,8 +27,6 @@ namespace MotorPlantDatabaseImplement.Models public DateTime? DateImplement { get; private set; } - public virtual Engine Engine { get; set; } - public static Order? Create(OrderBindingModel? model) { if (model == null) @@ -43,7 +41,6 @@ namespace MotorPlantDatabaseImplement.Models Sum = model.Sum, Status = model.Status, DateCreate = model.DateCreate, - DateImplement = model.DateImplement }; } @@ -66,7 +63,6 @@ namespace MotorPlantDatabaseImplement.Models Status = Status, DateCreate = DateCreate, DateImplement = DateImplement, - EngineName = Engine.EngineName }; } } \ No newline at end of file diff --git a/MotorPlant/MotorPlantDatabaseImplement/Models/Shop.cs b/MotorPlant/MotorPlantDatabaseImplement/Models/Shop.cs new file mode 100644 index 0000000..1aa014d --- /dev/null +++ b/MotorPlant/MotorPlantDatabaseImplement/Models/Shop.cs @@ -0,0 +1,105 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.ViewModels; +using MotorPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations.Schema; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantDatabaseImplement.Models +{ + public class Shop : IShopModel + { + public int Id { get; private set; } + [Required] + public string ShopName { get; private set; } + [Required] + public string Adress { get; private set; } + [Required] + public DateTime DateOpen { get; private set; } + [Required] + public int MaxCount { get; private set; } + private Dictionary? _shopEngines = null; + [NotMapped] + public Dictionary? ShopEngines + { + get + { + if (_shopEngines == null) + { + _shopEngines = Engines.ToDictionary(x => x.EngineId, x => (x.Engine as IEngineModel, x.Count)); + } + return _shopEngines; + } + } + [ForeignKey("ShopId")] + public virtual List Engines { get; set; } = new(); + public static Shop? Create(MotorPlantDatabase context, ShopBindingModel model) + { + if (model == null) + return null; + return new Shop() + { + Id = model.Id, + ShopName = model.ShopName, + Adress = model.Adress, + DateOpen = model.DateOpen, + MaxCount = model.MaxCount, + Engines = model.ShopEngines.Select(x => new ShopEngine + { + Engine = context.Engines.First(y => y.Id == x.Key), + Count = x.Value.Item2 + }).ToList() + }; + } + public void Update(ShopBindingModel? model) + { + if (model == null) + return; + ShopName = model.ShopName; + Adress = model.Adress; + DateOpen = model.DateOpen; + MaxCount = model.MaxCount; + } + public ShopViewModel GetViewModel => new() + { + Id = Id, + ShopName = ShopName, + Adress = Adress, + DateOpen = DateOpen, + MaxCount = MaxCount, + ShopEngines = ShopEngines + }; + + public void UpdateDresses(MotorPlantDatabase context, ShopBindingModel model) + { + var shopEngines = context.ShopEngines.Where(rec => rec.ShopId == model.Id).ToList(); + if (shopEngines != null && shopEngines.Count > 0) + { + context.ShopEngines.RemoveRange(shopEngines.Where(rec => !model.ShopEngines.ContainsKey(rec.EngineId))); + context.SaveChanges(); + foreach (var uEngine in shopEngines) + { + uEngine.Count = model.ShopEngines[uEngine.EngineId].Item2; + model.ShopEngines.Remove(uEngine.EngineId); + } + context.SaveChanges(); + } + var shop = context.Shops.First(x => x.Id == Id); + foreach (var pc in model.ShopEngines) + { + context.ShopEngines.Add(new ShopEngine + { + Shop = shop, + Engine = context.Engines.First(x => x.Id == pc.Key), + Count = pc.Value.Item2 + }); + context.SaveChanges(); + } + _shopEngines = null; + } + } +} diff --git a/MotorPlant/MotorPlantDatabaseImplement/Models/ShopEngine.cs b/MotorPlant/MotorPlantDatabaseImplement/Models/ShopEngine.cs new file mode 100644 index 0000000..c6ed0c0 --- /dev/null +++ b/MotorPlant/MotorPlantDatabaseImplement/Models/ShopEngine.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantDatabaseImplement.Models +{ + public class ShopEngine + { + public int Id { get; set; } + [Required] + public int EngineId { get; set; } + [Required] + public int ShopId { get; set; } + [Required] + public int Count { get; set; } + public virtual Shop Shop { get; set; } = new(); + public virtual Engine Engine { get; set; } = new(); + } +} diff --git a/MotorPlant/MotorPlantDatabaseImplement/MotorPlantDatabase.cs b/MotorPlant/MotorPlantDatabaseImplement/MotorPlantDatabase.cs index 26ecf49..73a1df5 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/MotorPlantDatabase.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/MotorPlantDatabase.cs @@ -9,7 +9,7 @@ namespace MotorPlantDatabaseImplement { if (optionsBuilder.IsConfigured == false) { - optionsBuilder.UseNpgsql(@"Host=localhost;Port=5432;Database=MotorPlant_db;Username=postgres;Password=admin"); + optionsBuilder.UseNpgsql(@"Host=localhost;Port=5432;Database=MotorPlantHard_db;Username=postgres;Password=admin"); } base.OnConfiguring(optionsBuilder); AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true); @@ -19,5 +19,7 @@ namespace MotorPlantDatabaseImplement public virtual DbSet Engines { get; set; } public virtual DbSet EngineComponents { get; set; } public virtual DbSet Orders { get; set; } - } + public virtual DbSet Shops { get; set; } + public virtual DbSet ShopEngines { get; set; } + } } \ No newline at end of file diff --git a/MotorPlant/MotorPlantDatabaseImplement/MotorPlantDatabaseImplement.csproj b/MotorPlant/MotorPlantDatabaseImplement/MotorPlantDatabaseImplement.csproj index 6fa33d6..fa3b43b 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/MotorPlantDatabaseImplement.csproj +++ b/MotorPlant/MotorPlantDatabaseImplement/MotorPlantDatabaseImplement.csproj @@ -21,8 +21,4 @@ - - - - diff --git a/MotorPlant/MotorPlantFileImplement/DataFileSingleton.cs b/MotorPlant/MotorPlantFileImplement/DataFileSingleton.cs index 8d52eb1..2d2bd6b 100644 --- a/MotorPlant/MotorPlantFileImplement/DataFileSingleton.cs +++ b/MotorPlant/MotorPlantFileImplement/DataFileSingleton.cs @@ -13,13 +13,17 @@ namespace MotorPlantFileImplement private readonly string EngineFileName = "Engine.xml"; - public List Components { get; private set; } + private readonly string ShopFileName = "Shop.xml"; + + public List Components { get; private set; } public List Orders { get; private set; } public List Engines { get; private set; } - public static DataFileSingleton GetInstance() + public List Shops { get; private set; } + + public static DataFileSingleton GetInstance() { if (instance == null) { @@ -33,14 +37,17 @@ namespace MotorPlantFileImplement public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement); - private DataFileSingleton() + public void SaveShops() => SaveData(Shops, ShopFileName, "Shops", x => x.GetXElement); + + private DataFileSingleton() { Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!; Engines = LoadData(EngineFileName, "Engine", x => Engine.Create(x)!)!; Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!; - } + Shops = LoadData(ShopFileName, "Shop", x => Shop.Create(x)!)!; + } - private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) + private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) { if (File.Exists(filename)) { diff --git a/MotorPlant/MotorPlantFileImplement/Implements/ShopStorage .cs b/MotorPlant/MotorPlantFileImplement/Implements/ShopStorage .cs new file mode 100644 index 0000000..29ae922 --- /dev/null +++ b/MotorPlant/MotorPlantFileImplement/Implements/ShopStorage .cs @@ -0,0 +1,118 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.StoragesContracts; +using MotorPlantContracts.ViewModels; +using MotorPlantDataModels.Models; +using MotorPlantFileImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantFileImplement.Implements +{ + public class ShopStorage : IShopStorage + { + private readonly DataFileSingleton _source; + public ShopStorage() + { + _source = DataFileSingleton.GetInstance(); + } + public List GetFullList() + { + return _source.Shops.Select(x => x.GetViewModel).ToList(); + } + public List GetFilteredList(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.Name)) + { + return new(); + } + return _source.Shops.Where(x => x.ShopName.Contains(model.Name)).Select(x => x.GetViewModel).ToList(); + + } + public ShopViewModel? GetElement(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.Name) && !model.Id.HasValue) + { + return null; + } + return _source.Shops.FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name) && x.ShopName == model.Name) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; + } + 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; + } + public ShopViewModel? Update(ShopBindingModel model) + { + var component = _source.Shops.FirstOrDefault(x => x.Id == model.Id); + if (component == null) + { + return null; + } + component.Update(model); + _source.SaveShops(); + return component.GetViewModel; + } + 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; + } + + public bool SellEngines(IEngineModel model, int count) + { + var eng = _source.Engines.FirstOrDefault(x => x.Id == model.Id); + int store = _source.Shops.SelectMany(x => x.ShopEngines).Sum(y => y.Key == model.Id ? y.Value.Item2 : 0); + + if (eng == null || store < count) + { + return false; + } + + for (int i = 0; i < _source.Shops.Count; i++) + { + var shop = _source.Shops[i]; + var engines = shop.ShopEngines; + foreach (var engine in engines.Where(x => x.Value.Item1.Id == eng.Id)) + { + var selling = Math.Min(engine.Value.Item2, count); + engines[engine.Value.Item1.Id] = (engine.Value.Item1, engine.Value.Item2 - selling); + + count -= selling; + + if (count <= 0) + { + break; + } + } + shop.Update(new ShopBindingModel + { + Id = model.Id, + ShopName = shop.ShopName, + Adress = shop.Adress, + MaxCount = shop.MaxCount, + DateOpen = shop.DateOpen, + ShopEngines = engines + }); + } + _source.SaveShops(); + return true; + } + } +} diff --git a/MotorPlant/MotorPlantFileImplement/Models/Engine.cs b/MotorPlant/MotorPlantFileImplement/Models/Engine.cs index 47f3f3c..e00f328 100644 --- a/MotorPlant/MotorPlantFileImplement/Models/Engine.cs +++ b/MotorPlant/MotorPlantFileImplement/Models/Engine.cs @@ -7,7 +7,7 @@ namespace MotorPlantFileImplement.Models { public class Engine : IEngineModel { - public int Id { get; private set; } + public int Id { get; private set; } public string EngineName { get; private set; } = string.Empty; public double Price { get; private set; } public Dictionary Components { get; private set; } = new(); diff --git a/MotorPlant/MotorPlantFileImplement/Models/Shop.cs b/MotorPlant/MotorPlantFileImplement/Models/Shop.cs new file mode 100644 index 0000000..98d151d --- /dev/null +++ b/MotorPlant/MotorPlantFileImplement/Models/Shop.cs @@ -0,0 +1,102 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.ViewModels; +using MotorPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace MotorPlantFileImplement.Models +{ + public class Shop : IShopModel + { + public int Id { get; private set; } + public string ShopName { get; private set; } + public string Adress { get; private set; } + public DateTime DateOpen { get; private set; } + public int MaxCount { get; private set; } + public Dictionary Engines { get; private set; } = new(); + private Dictionary? _shopEngines = null; + + public Dictionary ShopEngines + { + get + { + if (_shopEngines == null) + { + var source = DataFileSingleton.GetInstance(); + _shopEngines = Engines.ToDictionary(x => x.Key, y => ((source.Engines.FirstOrDefault(z => z.Id == y.Key) as IEngineModel)!, y.Value)); + } + return _shopEngines; + } + } + public static Shop? Create(ShopBindingModel model) + { + if (model == null) + { + return null; + } + return new Shop() + { + Id = model.Id, + ShopName = model.ShopName, + Adress = model.Adress, + DateOpen = model.DateOpen, + MaxCount = model.MaxCount, + Engines = model.ShopEngines.ToDictionary(x => x.Key, x => x.Value.Item2) + }; + } + public static Shop? Create(XElement element) + { + if (element == null) + { + return null; + } + return new Shop() + { + Id = Convert.ToInt32(element.Attribute("Id")!.Value), + ShopName = element.Element("ShopName")!.Value, + Adress = element.Element("Adress")!.Value, + MaxCount = Convert.ToInt32(element.Element("MaxCount")!.Value), + DateOpen = Convert.ToDateTime(element.Element("DateOpen")!.Value), + Engines = element.Element("ShopEngines")!.Elements("ShopEngine").ToDictionary(x => Convert.ToInt32(x.Element("Key")?.Value), x => Convert.ToInt32(x.Element("Value")?.Value)) + }; + + } + public void Update(ShopBindingModel? model) + { + if (model == null) + { + return; + } + ShopName = model.ShopName; + Adress = model.Adress; + DateOpen = model.DateOpen; + MaxCount = model.MaxCount; + if (model.ShopEngines.Count > 0) + { + Engines = model.ShopEngines.ToDictionary(x => x.Key, x => x.Value.Item2); + _shopEngines = null; + } + } + public ShopViewModel GetViewModel => new() + { + Id = Id, + ShopName = ShopName, + Adress = Adress, + DateOpen = DateOpen, + MaxCount = MaxCount, + ShopEngines = ShopEngines + }; + + public XElement GetXElement => new XElement("Shop", + new XAttribute("Id", Id), + new XElement("ShopName", ShopName), + new XElement("Adress", Adress), + new XElement("DateOpen", DateOpen), + new XElement("MaxCount", MaxCount), + new XElement("ShopEngines", Engines.Select(x => new XElement("ShopEngine", new XElement("Key", x.Key), new XElement("Value", x.Value))).ToArray())); + } +} diff --git a/MotorPlant/MotorPlantListImplement/DataListSingleton.cs b/MotorPlant/MotorPlantListImplement/DataListSingleton.cs index 4bd61f6..763c235 100644 --- a/MotorPlant/MotorPlantListImplement/DataListSingleton.cs +++ b/MotorPlant/MotorPlantListImplement/DataListSingleton.cs @@ -12,11 +12,14 @@ namespace MotorPlantListImplement public List Engines { get; set; } + public List Shops { get; set; } + private DataListSingleton() { Components = new List(); Orders = new List(); Engines = new List(); + Shops = new List(); } public static DataListSingleton GetInstance() diff --git a/MotorPlant/MotorPlantListImplement/Implements/ShopStorage.cs b/MotorPlant/MotorPlantListImplement/Implements/ShopStorage.cs new file mode 100644 index 0000000..2d61dae --- /dev/null +++ b/MotorPlant/MotorPlantListImplement/Implements/ShopStorage.cs @@ -0,0 +1,116 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.StoragesContracts; +using MotorPlantContracts.ViewModels; +using MotorPlantDataModels.Models; +using MotorPlantListImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantListImplement.Implements +{ + public class ShopStorage : IShopStorage + { + private readonly DataListSingleton _source; + public ShopStorage() + { + _source = DataListSingleton.GetInstance(); + } + public List GetFullList() + { + var result = new List(); + foreach (var shop in _source.Shops) + { + result.Add(shop.GetViewModel); + } + return result; + } + public List GetFilteredList(ShopSearchModel model) + { + var result = new List(); + if (string.IsNullOrEmpty(model.Name)) + { + return result; + } + foreach (var shop in _source.Shops) + { + if (shop.ShopName.Contains(model.Name)) + { + result.Add(shop.GetViewModel); + } + } + return result; + } + public ShopViewModel? GetElement(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.Name) && !model.Id.HasValue) + { + return null; + } + foreach (var shop in _source.Shops) + { + if ((!string.IsNullOrEmpty(model.Name) && + shop.ShopName == model.Name) || + (model.Id.HasValue && shop.Id == model.Id)) + { + return shop.GetViewModel; + } + } + return null; + } + public ShopViewModel? Insert(ShopBindingModel model) + { + model.Id = 1; + foreach (var shop in _source.Shops) + { + if (model.Id <= shop.Id) + { + model.Id = shop.Id + 1; + } + } + var newShop = Shop.Create(model); + if (newShop == null) + { + return null; + } + _source.Shops.Add(newShop); + return newShop.GetViewModel; + } + public ShopViewModel? Update(ShopBindingModel model) + { + foreach (var shop in _source.Shops) + { + if (shop.Id == model.Id) + { + shop.Update(model); + return shop.GetViewModel; + } + } + return null; + } + public ShopViewModel? Delete(ShopBindingModel model) + { + for (int i = 0; i < _source.Shops.Count; ++i) + { + if (_source.Shops[i].Id == model.Id) + { + var element = _source.Shops[i]; + _source.Shops.RemoveAt(i); + return element.GetViewModel; + } + } + return null; + } + public bool CheckAvailability(int engineId, int count) + { + return true; + } + public bool SellEngines(IEngineModel model, int count) + { + return true; + } + } +} diff --git a/MotorPlant/MotorPlantListImplement/Models/Shop.cs b/MotorPlant/MotorPlantListImplement/Models/Shop.cs new file mode 100644 index 0000000..05ac9bd --- /dev/null +++ b/MotorPlant/MotorPlantListImplement/Models/Shop.cs @@ -0,0 +1,58 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.ViewModels; +using MotorPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantListImplement.Models +{ + public class Shop : IShopModel + { + public int Id { get; private set; } + public string ShopName { get; private set; } + public string Adress { get; private set; } + public DateTime DateOpen { get; private set; } + public int MaxCount { get; private set; } + public Dictionary ShopEngines { get; private set; } = new(); + public static Shop? Create(ShopBindingModel model) + { + if (model == null) + { + return null; + } + return new Shop() + { + Id = model.Id, + ShopName = model.ShopName, + Adress = model.Adress, + DateOpen = model.DateOpen, + MaxCount = model.MaxCount, + ShopEngines = new() + }; + } + public void Update(ShopBindingModel? model) + { + if (model == null) + { + return; + } + ShopName = model.ShopName; + Adress = model.Adress; + DateOpen = model.DateOpen; + MaxCount = model.MaxCount; + ShopEngines = model.ShopEngines; + } + public ShopViewModel GetViewModel => new() + { + Id = Id, + ShopName = ShopName, + Adress = Adress, + DateOpen = DateOpen, + MaxCount = MaxCount, + ShopEngines = ShopEngines + }; + } +} diff --git a/MotorPlant/MotorPlantView/FormCreateOrder.cs b/MotorPlant/MotorPlantView/FormCreateOrder.cs index d4fd6e3..63df012 100644 --- a/MotorPlant/MotorPlantView/FormCreateOrder.cs +++ b/MotorPlant/MotorPlantView/FormCreateOrder.cs @@ -84,7 +84,7 @@ namespace MotorPlantView.Forms var operationResult = _logicO.CreateOrder(new OrderBindingModel { EngineId = Convert.ToInt32(comboBoxEngine.SelectedValue), - Count = Convert.ToInt32(textBoxCount.Text), + Count = Convert.ToInt32(textBoxCount.Text), Sum = Convert.ToDouble(textBoxSum.Text) }); if (!operationResult) @@ -97,7 +97,8 @@ namespace MotorPlantView.Forms } catch (Exception ex) { - _logger.LogError(ex, "Ошибка создания заказа"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError(ex, "Ошибка создания заказа"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } diff --git a/MotorPlant/MotorPlantView/FormEngines.cs b/MotorPlant/MotorPlantView/FormEngines.cs index 7e129dc..0c6692a 100644 --- a/MotorPlant/MotorPlantView/FormEngines.cs +++ b/MotorPlant/MotorPlantView/FormEngines.cs @@ -15,11 +15,6 @@ namespace MotorPlantView.Forms _logic = logic; } - private void FormEngines_Load(object sender, EventArgs e) - { - LoadData(); - } - private void LoadData() { try @@ -37,7 +32,13 @@ namespace MotorPlantView.Forms catch (Exception ex) { _logger.LogError(ex, "Ошибка загрузки компонентов"); - } + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void FormEngines_Load(object sender, EventArgs e) + { + LoadData(); } private void buttonAdd_Click(object sender, EventArgs e) diff --git a/MotorPlant/MotorPlantView/FormMain.Designer.cs b/MotorPlant/MotorPlantView/FormMain.Designer.cs index 77a042d..b4652b7 100644 --- a/MotorPlant/MotorPlantView/FormMain.Designer.cs +++ b/MotorPlant/MotorPlantView/FormMain.Designer.cs @@ -1,26 +1,26 @@ namespace MotorPlantView.Forms { - partial class FormMain - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; + partial class FormMain + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } - #region Windows Form Designer generated code + #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify @@ -203,7 +203,7 @@ PerformLayout(); } - #endregion + #endregion private ToolStrip toolStrip1; private Button buttonCreateOrder; diff --git a/MotorPlant/MotorPlantView/FormMain.cs b/MotorPlant/MotorPlantView/FormMain.cs index b4b6368..a036221 100644 --- a/MotorPlant/MotorPlantView/FormMain.cs +++ b/MotorPlant/MotorPlantView/FormMain.cs @@ -1,6 +1,7 @@ using Microsoft.Extensions.Logging; using MotorPlantContracts.BindingModels; using MotorPlantContracts.BusinessLogicsContracts; +using MotorPlantView; namespace MotorPlantView.Forms { @@ -28,32 +29,32 @@ namespace MotorPlantView.Forms { var list = _orderLogic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["EngineId"].Visible = false; - dataGridView.Columns["EngineName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["EngineId"].Visible = false; + dataGridView.Columns["EngineName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; + } - _logger.LogInformation("Загрузка заказов"); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки заказов"); - } - } - private void КомпонентыToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormComponents)); + _logger.LogInformation("Загрузка заказов"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки заказов"); + } + } + private void КомпонентыToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormComponents)); - if (service is FormComponents form) - { - form.ShowDialog(); - } - } - private void ИзделияToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormEngines)); + if (service is FormComponents form) + { + form.ShowDialog(); + } + } + private void ИзделияToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormEngines)); if (service is FormEngines form) { diff --git a/MotorPlant/MotorPlantView/FormSell.Designer.cs b/MotorPlant/MotorPlantView/FormSell.Designer.cs new file mode 100644 index 0000000..3696490 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormSell.Designer.cs @@ -0,0 +1,122 @@ +namespace MotorPlantView +{ + partial class FormSell + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + comboBoxEngine = new ComboBox(); + textBoxCount = new TextBox(); + buttonSave = new Button(); + buttonCancel = new Button(); + label1 = new Label(); + label2 = new Label(); + // + // comboBoxEngine + // + comboBoxEngine.FormattingEnabled = true; + comboBoxEngine.Location = new Point(110, 22); + comboBoxEngine.Margin = new Padding(3, 2, 3, 2); + comboBoxEngine.Name = "comboBoxEngine"; + comboBoxEngine.Size = new Size(133, 23); + comboBoxEngine.TabIndex = 0; + // + // textBoxCount + // + textBoxCount.Location = new Point(110, 71); + textBoxCount.Margin = new Padding(3, 2, 3, 2); + textBoxCount.Name = "textBoxCount"; + textBoxCount.Size = new Size(133, 23); + textBoxCount.TabIndex = 1; + // + // buttonSave + // + buttonSave.Location = new Point(39, 129); + buttonSave.Margin = new Padding(3, 2, 3, 2); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(82, 22); + buttonSave.TabIndex = 2; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += buttonSave_Click; + // + // buttonCancel + // + buttonCancel.Location = new Point(160, 129); + buttonCancel.Margin = new Padding(3, 2, 3, 2); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(82, 22); + buttonCancel.TabIndex = 3; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += buttonCancel_Click; + // + // label1 + // + label1.AutoSize = true; + label1.Location = new Point(24, 25); + label1.Name = "label1"; + label1.Size = new Size(50, 15); + label1.TabIndex = 4; + label1.Text = "Движки"; + // + // label2 + // + label2.AutoSize = true; + label2.Location = new Point(24, 74); + label2.Name = "label2"; + label2.Size = new Size(72, 15); + label2.TabIndex = 5; + label2.Text = "Количество"; + // + // FormSell + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(268, 176); + Controls.Add(label2); + Controls.Add(label1); + Controls.Add(buttonCancel); + Controls.Add(buttonSave); + Controls.Add(textBoxCount); + Controls.Add(comboBoxEngine); + Margin = new Padding(3, 2, 3, 2); + Name = "FormSell"; + Text = "Продажа"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private ComboBox comboBoxEngine; + private TextBox textBoxCount; + private Button buttonSave; + private Button buttonCancel; + private Label label1; + private Label label2; + } +} \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormSell.cs b/MotorPlant/MotorPlantView/FormSell.cs new file mode 100644 index 0000000..09d47ad --- /dev/null +++ b/MotorPlant/MotorPlantView/FormSell.cs @@ -0,0 +1,120 @@ +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; +using MotorPlantDataModels.Models; +using MotorPlantContracts.BusinessLogicsContracts; +using MotorPlantContracts.ViewModels; + +namespace MotorPlantView +{ + public partial class FormSell : Form + { + private readonly List? _engineList; + IShopLogic _shopLogic; + IEngineLogic _engineLogic; + public FormSell(IEngineLogic engineLogic, IShopLogic shopLogic) + { + InitializeComponent(); + _shopLogic = shopLogic; + _engineLogic = engineLogic; + _engineList = engineLogic.ReadList(null); + if (_engineList != null) + { + comboBoxEngine.DisplayMember = "EngineName"; + comboBoxEngine.ValueMember = "Id"; + comboBoxEngine.DataSource = _engineList; + comboBoxEngine.SelectedItem = null; + } + } + public int EngineId + { + get + { + return Convert.ToInt32(comboBoxEngine.SelectedValue); + } + set + { + comboBoxEngine.SelectedValue = value; + } + } + + public IEngineModel? EngineModel + { + get + { + if (_engineList == null) + { + return null; + } + foreach (var elem in _engineList) + { + if (elem.Id == EngineId) + { + return elem; + } + } + return null; + } + } + + + public int Count + { + get { return Convert.ToInt32(textBoxCount.Text); } + set + { textBoxCount.Text = value.ToString(); } + } + + private void buttonSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxCount.Text)) + { + MessageBox.Show("Заполните поле Количество", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (comboBoxEngine.SelectedValue == null) + { + MessageBox.Show("Выберите двигатель", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + + try + { + int count = Convert.ToInt32(textBoxCount.Text); + + bool res = _shopLogic.MakeSell( + _engineLogic.ReadElement(new() { Id = Convert.ToInt32(comboBoxEngine.SelectedValue) }), + count + ); + + if (!res) + { + throw new Exception("Ошибка при продаже."); + } + + MessageBox.Show("Продажа прошла успешно"); + DialogResult = DialogResult.OK; + Close(); + + } + catch (Exception err) + { + MessageBox.Show("Ошибка продажи"); + return; + } + } + + private void buttonCancel_Click(object sender, EventArgs e) + { + Close(); + } + } +} diff --git a/MotorPlant/MotorPlantView/FormSell.resx b/MotorPlant/MotorPlantView/FormSell.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormSell.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormShop.Designer.cs b/MotorPlant/MotorPlantView/FormShop.Designer.cs new file mode 100644 index 0000000..a529389 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormShop.Designer.cs @@ -0,0 +1,226 @@ +namespace MotorPlantView +{ + partial class FormShop + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + dateTimePicker = new DateTimePicker(); + textBoxName = new TextBox(); + textBoxAdress = new TextBox(); + dataGridView = new DataGridView(); + IdColumn = new DataGridViewTextBoxColumn(); + Title = new DataGridViewTextBoxColumn(); + Cost = new DataGridViewTextBoxColumn(); + Count = new DataGridViewTextBoxColumn(); + buttonSave = new Button(); + buttonCancel = new Button(); + label1 = new Label(); + label2 = new Label(); + label3 = new Label(); + label4 = new Label(); + numeric = new NumericUpDown(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + ((System.ComponentModel.ISupportInitialize)numeric).BeginInit(); + SuspendLayout(); + // + // dateTimePicker + // + dateTimePicker.Location = new Point(625, 26); + dateTimePicker.Margin = new Padding(3, 2, 3, 2); + dateTimePicker.Name = "dateTimePicker"; + dateTimePicker.Size = new Size(219, 23); + dateTimePicker.TabIndex = 0; + // + // textBoxName + // + textBoxName.Location = new Point(625, 64); + textBoxName.Margin = new Padding(3, 2, 3, 2); + textBoxName.Name = "textBoxName"; + textBoxName.Size = new Size(219, 23); + textBoxName.TabIndex = 1; + // + // textBoxAdress + // + textBoxAdress.Location = new Point(625, 104); + textBoxAdress.Margin = new Padding(3, 2, 3, 2); + textBoxAdress.Name = "textBoxAdress"; + textBoxAdress.Size = new Size(219, 23); + textBoxAdress.TabIndex = 2; + // + // dataGridView + // + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Columns.AddRange(new DataGridViewColumn[] { IdColumn, Title, Cost, Count }); + dataGridView.Location = new Point(9, 24); + dataGridView.Margin = new Padding(3, 2, 3, 2); + dataGridView.Name = "dataGridView"; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 29; + dataGridView.Size = new Size(485, 285); + dataGridView.TabIndex = 3; + // + // IdColumn + // + IdColumn.HeaderText = "Номер платья"; + IdColumn.MinimumWidth = 6; + IdColumn.Name = "IdColumn"; + IdColumn.Visible = false; + IdColumn.Width = 125; + // + // Title + // + Title.HeaderText = "Название"; + Title.MinimumWidth = 6; + Title.Name = "Title"; + Title.Width = 125; + // + // Cost + // + Cost.HeaderText = "Цена"; + Cost.MinimumWidth = 6; + Cost.Name = "Cost"; + Cost.Width = 125; + // + // Count + // + Count.HeaderText = "Количество"; + Count.MinimumWidth = 6; + Count.Name = "Count"; + Count.Width = 125; + // + // buttonSave + // + buttonSave.Location = new Point(625, 179); + buttonSave.Margin = new Padding(3, 2, 3, 2); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(82, 22); + buttonSave.TabIndex = 4; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += buttonSave_Click; + // + // buttonCancel + // + buttonCancel.Location = new Point(761, 179); + buttonCancel.Margin = new Padding(3, 2, 3, 2); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(82, 22); + buttonCancel.TabIndex = 5; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += buttonCancel_Click; + // + // label1 + // + label1.AutoSize = true; + label1.Location = new Point(518, 29); + label1.Name = "label1"; + label1.Size = new Size(85, 15); + label1.TabIndex = 6; + label1.Text = "Дата создания"; + // + // label2 + // + label2.AutoSize = true; + label2.Location = new Point(518, 66); + label2.Name = "label2"; + label2.Size = new Size(59, 15); + label2.TabIndex = 7; + label2.Text = "Название"; + // + // label3 + // + label3.AutoSize = true; + label3.Location = new Point(518, 106); + label3.Name = "label3"; + label3.Size = new Size(40, 15); + label3.TabIndex = 8; + label3.Text = "Адрес"; + // + // label4 + // + label4.AutoSize = true; + label4.Location = new Point(518, 144); + label4.Name = "label4"; + label4.Size = new Size(80, 15); + label4.TabIndex = 9; + label4.Text = "Вместимость"; + label4.TextAlign = ContentAlignment.TopCenter; + // + // numeric + // + numeric.Location = new Point(625, 142); + numeric.Margin = new Padding(3, 2, 3, 2); + numeric.Name = "numeric"; + numeric.Size = new Size(131, 23); + numeric.TabIndex = 10; + // + // FormShop + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(854, 338); + Controls.Add(numeric); + Controls.Add(label4); + Controls.Add(label3); + Controls.Add(label2); + Controls.Add(label1); + Controls.Add(buttonCancel); + Controls.Add(buttonSave); + Controls.Add(dataGridView); + Controls.Add(textBoxAdress); + Controls.Add(textBoxName); + Controls.Add(dateTimePicker); + Margin = new Padding(3, 2, 3, 2); + Name = "FormShop"; + Text = "Форма магазина"; + Load += ShopForm_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ((System.ComponentModel.ISupportInitialize)numeric).EndInit(); + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private DateTimePicker dateTimePicker; + private TextBox textBoxName; + private TextBox textBoxAdress; + private DataGridView dataGridView; + private Button buttonSave; + private Button buttonCancel; + private Label label1; + private Label label2; + private Label label3; + private DataGridViewTextBoxColumn IdColumn; + private DataGridViewTextBoxColumn Title; + private DataGridViewTextBoxColumn Cost; + private DataGridViewTextBoxColumn Count; + private Label label4; + private NumericUpDown numeric; + } +} \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormShop.cs b/MotorPlant/MotorPlantView/FormShop.cs new file mode 100644 index 0000000..497ffe8 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormShop.cs @@ -0,0 +1,123 @@ +using Microsoft.Extensions.Logging; +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.BusinessLogicsContracts; +using MotorPlantContracts.SearchModels; +using MotorPlantDataModels.Models; +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 MotorPlantView +{ + public partial class FormShop : Form + { + private readonly ILogger _logger; + private readonly IShopLogic _logic; + public int? _id; + private Dictionary _engines; + public FormShop(ILogger logger, IShopLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + private void ShopForm_Load(object sender, EventArgs e) + { + if (_id.HasValue) + { + _logger.LogInformation("Shop load"); + try + { + var shop = _logic.ReadElement(new ShopSearchModel { Id = _id }); + if (shop != null) + { + textBoxName.Text = shop.ShopName; + textBoxAdress.Text = shop.Adress; + dateTimePicker.Text = shop.DateOpen.ToString(); + numeric.Value = shop.MaxCount; + _engines = shop.ShopEngines ?? new Dictionary(); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Load shop error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + } + + private void LoadData() + { + _logger.LogInformation("Load engines"); + try + { + if (_engines != null) + { + foreach (var engine in _engines) + { + dataGridView.Rows.Add(new object[] { engine.Key, engine.Value.Item1.EngineName, engine.Value.Item1.Price, engine.Value.Item2 }); + } + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Load engines into shop error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + private void buttonSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxName.Text)) + { + MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (string.IsNullOrEmpty(textBoxAdress.Text)) + { + MessageBox.Show("Заполните адрес", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Save shop"); + try + { + var model = new ShopBindingModel + { + Id = _id ?? 0, + ShopName = textBoxName.Text, + Adress = textBoxAdress.Text, + DateOpen = dateTimePicker.Value.Date, + MaxCount = Convert.ToInt32(numeric.Value) + }; + var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + Close(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Save shop error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void buttonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } +} diff --git a/MotorPlant/MotorPlantView/FormShop.resx b/MotorPlant/MotorPlantView/FormShop.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormShop.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormShops.Designer.cs b/MotorPlant/MotorPlantView/FormShops.Designer.cs new file mode 100644 index 0000000..b4d34e3 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormShops.Designer.cs @@ -0,0 +1,114 @@ +namespace MotorPlantView +{ + partial class FormShops + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + dataGridView = new DataGridView(); + buttonAdd = new Button(); + buttonUpdate = new Button(); + buttonReset = new Button(); + buttonDelete = new Button(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // dataGridView + // + dataGridView.BackgroundColor = SystemColors.ButtonHighlight; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(12, 12); + dataGridView.Name = "dataGridView"; + dataGridView.RowTemplate.Height = 25; + dataGridView.Size = new Size(617, 426); + dataGridView.TabIndex = 0; + // + // buttonAdd + // + buttonAdd.Location = new Point(665, 114); + buttonAdd.Name = "buttonAdd"; + buttonAdd.Size = new Size(123, 45); + buttonAdd.TabIndex = 1; + buttonAdd.Text = "Добавить"; + buttonAdd.UseVisualStyleBackColor = true; + buttonAdd.Click += buttonAdd_Click; + // + // buttonUpdate + // + buttonUpdate.Location = new Point(665, 165); + buttonUpdate.Name = "buttonUpdate"; + buttonUpdate.Size = new Size(123, 44); + buttonUpdate.TabIndex = 2; + buttonUpdate.Text = "Изменить"; + buttonUpdate.UseVisualStyleBackColor = true; + buttonUpdate.Click += buttonUpdate_Click; + // + // buttonReset + // + buttonReset.Location = new Point(665, 215); + buttonReset.Name = "buttonReset"; + buttonReset.Size = new Size(123, 48); + buttonReset.TabIndex = 3; + buttonReset.Text = "Обновить"; + buttonReset.UseVisualStyleBackColor = true; + buttonReset.Click += buttonReset_Click; + // + // buttonDelete + // + buttonDelete.Location = new Point(665, 269); + buttonDelete.Name = "buttonDelete"; + buttonDelete.Size = new Size(123, 48); + buttonDelete.TabIndex = 4; + buttonDelete.Text = "Удалить"; + buttonDelete.UseVisualStyleBackColor = true; + buttonDelete.Click += buttonDelete_Click; + // + // FormShops + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(800, 450); + Controls.Add(buttonDelete); + Controls.Add(buttonReset); + Controls.Add(buttonUpdate); + Controls.Add(buttonAdd); + Controls.Add(dataGridView); + Name = "FormShops"; + Text = "FormShops"; + Load += FormShops_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView; + private Button buttonAdd; + private Button buttonUpdate; + private Button buttonReset; + private Button buttonDelete; + } +} \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormShops.cs b/MotorPlant/MotorPlantView/FormShops.cs new file mode 100644 index 0000000..8a4cbcb --- /dev/null +++ b/MotorPlant/MotorPlantView/FormShops.cs @@ -0,0 +1,108 @@ +using Microsoft.Extensions.Logging; +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.BusinessLogicsContracts; +using MotorPlantView.Forms; + +namespace MotorPlantView +{ + public partial class FormShops : Form + { + private readonly ILogger _logger; + private readonly IShopLogic _logic; + public FormShops(ILogger logger, IShopLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + private void LoadData() + { + try + { + var list = _logic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["Id"].Visible = false; + dataGridView.Columns["ShopName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + dataGridView.Columns["Adress"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + dataGridView.Columns["DateOpen"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + dataGridView.Columns["ShopEngines"].Visible = false; + } + _logger.LogInformation("Load shops"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Load shop error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + private void FormShops_Load(object sender, EventArgs e) + { + LoadData(); + } + + private void buttonAdd_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormShop)); + if (service is FormShop form) + { + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + + private void buttonUpdate_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + var service = Program.ServiceProvider?.GetService(typeof(FormShop)); + if (service is FormShop form) + { + var tmp = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + form._id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + } + + private void buttonReset_Click(object sender, EventArgs e) + { + LoadData(); + } + + private void buttonDelete_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Удаление магазина"); + try + { + if (!_logic.Delete(new ShopBindingModel + { + Id = id + })) + { + throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка удаления магазина"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } + } +} diff --git a/MotorPlant/MotorPlantView/FormShops.resx b/MotorPlant/MotorPlantView/FormShops.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormShops.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormSupply.Designer.cs b/MotorPlant/MotorPlantView/FormSupply.Designer.cs new file mode 100644 index 0000000..1b5719f --- /dev/null +++ b/MotorPlant/MotorPlantView/FormSupply.Designer.cs @@ -0,0 +1,147 @@ +namespace MotorPlantView +{ + partial class FormSupply + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + ShopComboBox = new ComboBox(); + EngineComboBox = new ComboBox(); + CountTextBox = new TextBox(); + SaveButton = new Button(); + Cancel = new Button(); + label1 = new Label(); + label2 = new Label(); + label3 = new Label(); + SuspendLayout(); + // + // ShopComboBox + // + ShopComboBox.FormattingEnabled = true; + ShopComboBox.Location = new Point(136, 26); + ShopComboBox.Margin = new Padding(3, 2, 3, 2); + ShopComboBox.Name = "ShopComboBox"; + ShopComboBox.Size = new Size(279, 23); + ShopComboBox.TabIndex = 0; + // + // EngineComboBox + // + EngineComboBox.FormattingEnabled = true; + EngineComboBox.Location = new Point(136, 59); + EngineComboBox.Margin = new Padding(3, 2, 3, 2); + EngineComboBox.Name = "EngineComboBox"; + EngineComboBox.Size = new Size(279, 23); + EngineComboBox.TabIndex = 1; + // + // CountTextBox + // + CountTextBox.Location = new Point(136, 96); + CountTextBox.Margin = new Padding(3, 2, 3, 2); + CountTextBox.Name = "CountTextBox"; + CountTextBox.Size = new Size(279, 23); + CountTextBox.TabIndex = 2; + // + // SaveButton + // + SaveButton.Location = new Point(220, 150); + SaveButton.Margin = new Padding(3, 2, 3, 2); + SaveButton.Name = "SaveButton"; + SaveButton.Size = new Size(94, 27); + SaveButton.TabIndex = 3; + SaveButton.Text = "Сохранить"; + SaveButton.UseVisualStyleBackColor = true; + SaveButton.Click += SaveButton_Click; + // + // Cancel + // + Cancel.Location = new Point(319, 150); + Cancel.Margin = new Padding(3, 2, 3, 2); + Cancel.Name = "Cancel"; + Cancel.Size = new Size(94, 27); + Cancel.TabIndex = 4; + Cancel.Text = "Отмена"; + Cancel.UseVisualStyleBackColor = true; + Cancel.Click += CancelButton_Click; + // + // label1 + // + label1.AutoSize = true; + label1.Location = new Point(35, 28); + label1.Name = "label1"; + label1.Size = new Size(54, 15); + label1.TabIndex = 5; + label1.Text = "Магазин"; + // + // label2 + // + label2.AutoSize = true; + label2.Location = new Point(35, 62); + label2.Name = "label2"; + label2.Size = new Size(64, 15); + label2.TabIndex = 6; + label2.Text = "Двигатели"; + // + // label3 + // + label3.AutoSize = true; + label3.Location = new Point(35, 98); + label3.Name = "label3"; + label3.Size = new Size(72, 15); + label3.TabIndex = 7; + label3.Text = "Количество"; + // + // FormSupply + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(443, 195); + Controls.Add(label3); + Controls.Add(label2); + Controls.Add(label1); + Controls.Add(Cancel); + Controls.Add(SaveButton); + Controls.Add(CountTextBox); + Controls.Add(EngineComboBox); + Controls.Add(ShopComboBox); + Margin = new Padding(3, 2, 3, 2); + Name = "FormSupply"; + Text = "Форма поставки"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private ComboBox ShopComboBox; + private ComboBox EngineComboBox; + private TextBox CountTextBox; + private Button SaveButton; + private Button Cancel; + private Label label1; + private Label label2; + private Label label3; + } +} \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormSupply.cs b/MotorPlant/MotorPlantView/FormSupply.cs new file mode 100644 index 0000000..fa59e52 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormSupply.cs @@ -0,0 +1,140 @@ +using MotorPlantContracts.BusinessLogicsContracts; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.ViewModels; +using MotorPlantDataModels.Models; + +namespace MotorPlantView +{ + public partial class FormSupply : Form + { + private readonly List? _engineList; + private readonly List? _shopsList; + IShopLogic _shopLogic; + IEngineLogic _engineLogic; + public int ShopId + { + get + { + return Convert.ToInt32(ShopComboBox.SelectedValue); + } + set + { + ShopComboBox.SelectedValue = value; + } + } + public int EngineId + { + get + { + return Convert.ToInt32(EngineComboBox.SelectedValue); + } + set + { + EngineComboBox.SelectedValue = value; + } + } + + public IEngineModel? EngineModel + { + get + { + if (_engineList == null) + { + return null; + } + foreach (var elem in _engineList) + { + if (elem.Id == EngineId) + { + return elem; + } + } + return null; + } + } + + + public int Count + { + get { return Convert.ToInt32(CountTextBox.Text); } + set + { CountTextBox.Text = value.ToString(); } + } + public FormSupply(IEngineLogic engineLogic, IShopLogic shopLogic) + { + InitializeComponent(); + _shopLogic = shopLogic; + _engineLogic = engineLogic; + _engineList = engineLogic.ReadList(null); + _shopsList = shopLogic.ReadList(null); + if (_engineList != null) + { + EngineComboBox.DisplayMember = "EngineName"; + EngineComboBox.ValueMember = "Id"; + EngineComboBox.DataSource = _engineList; + EngineComboBox.SelectedItem = null; + } + if (_shopsList != null) + { + ShopComboBox.DisplayMember = "ShopName"; + ShopComboBox.ValueMember = "Id"; + ShopComboBox.DataSource = _shopsList; + ShopComboBox.SelectedItem = null; + } + } + + private void SaveButton_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(CountTextBox.Text)) + { + MessageBox.Show("Заполните поле Количество", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (EngineComboBox.SelectedValue == null) + { + MessageBox.Show("Выберите двигатель", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (ShopComboBox.SelectedValue == null) + { + MessageBox.Show("Выберите магазин", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + + try + { + int count = Convert.ToInt32(CountTextBox.Text); + + bool res = _shopLogic.MakeSupply( + new ShopSearchModel() { Id = Convert.ToInt32(ShopComboBox.SelectedValue) }, + _engineLogic.ReadElement(new() { Id = Convert.ToInt32(EngineComboBox.SelectedValue) }), + count + ); + + if (!res) + { + throw new Exception("Ошибка при пополнении. Дополнительная информация в логах"); + } + + MessageBox.Show("Пополнение прошло успешно"); + DialogResult = DialogResult.OK; + Close(); + + } + catch (Exception er) + { + MessageBox.Show("Ошибка пополнения"); + return; + } + } + + private void CancelButton_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } +} diff --git a/MotorPlant/MotorPlantView/FormSupply.resx b/MotorPlant/MotorPlantView/FormSupply.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormSupply.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/MotorPlant/ShopsForm/Form1.Designer.cs b/MotorPlant/ShopsForm/Form1.Designer.cs new file mode 100644 index 0000000..a8b8dd9 --- /dev/null +++ b/MotorPlant/ShopsForm/Form1.Designer.cs @@ -0,0 +1,39 @@ +namespace ShopsForm +{ + partial class Form1 + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.components = new System.ComponentModel.Container(); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 450); + this.Text = "Form1"; + } + + #endregion + } +} \ No newline at end of file diff --git a/MotorPlant/ShopsForm/Form1.cs b/MotorPlant/ShopsForm/Form1.cs new file mode 100644 index 0000000..6be30b4 --- /dev/null +++ b/MotorPlant/ShopsForm/Form1.cs @@ -0,0 +1,10 @@ +namespace ShopsForm +{ + public partial class Form1 : Form + { + public Form1() + { + InitializeComponent(); + } + } +} \ No newline at end of file diff --git a/MotorPlant/ShopsForm/Form1.resx b/MotorPlant/ShopsForm/Form1.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/MotorPlant/ShopsForm/Form1.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/MotorPlant/ShopsForm/Program.cs b/MotorPlant/ShopsForm/Program.cs new file mode 100644 index 0000000..4b3f120 --- /dev/null +++ b/MotorPlant/ShopsForm/Program.cs @@ -0,0 +1,17 @@ +namespace ShopsForm +{ + internal static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + // To customize application configuration such as set high DPI settings or default font, + // see https://aka.ms/applicationconfiguration. + ApplicationConfiguration.Initialize(); + Application.Run(new Form1()); + } + } +} \ No newline at end of file diff --git a/MotorPlant/ShopsForm/ShopsForm.csproj b/MotorPlant/ShopsForm/ShopsForm.csproj new file mode 100644 index 0000000..b57c89e --- /dev/null +++ b/MotorPlant/ShopsForm/ShopsForm.csproj @@ -0,0 +1,11 @@ + + + + WinExe + net6.0-windows + enable + true + enable + + + \ No newline at end of file