diff --git a/GiftShop/GiftShopBusinessLogic/BusinessLogics/ImplementerLogic.cs b/GiftShop/GiftShopBusinessLogic/BusinessLogics/ImplementerLogic.cs new file mode 100644 index 0000000..7499de0 --- /dev/null +++ b/GiftShop/GiftShopBusinessLogic/BusinessLogics/ImplementerLogic.cs @@ -0,0 +1,125 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.BusinessLogicsContracts; +using GiftShopContracts.SearchModels; +using GiftShopContracts.StoragesContracts; +using GiftShopContracts.ViewModels; +using Microsoft.Extensions.Logging; + +namespace GiftShopBusinessLogic.BusinessLogics +{ + public class ImplementerLogic : IImplementerLogic + { + private readonly ILogger _logger; + private readonly IImplementerStorage _implementerStorage; + + public ImplementerLogic(ILogger logger, IImplementerStorage implementerStorage) + { + _logger = logger; + _implementerStorage = implementerStorage; + } + + public bool Create(ImplementerBindingModel model) + { + CheckModel(model); + if (_implementerStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } + + public bool Delete(ImplementerBindingModel model) + { + CheckModel(model, false); + _logger.LogInformation("Delete. Id:{Id}", model.Id); + if (_implementerStorage.Delete(model) == null) + { + _logger.LogWarning("Delete operation failed"); + return false; + } + return true; + } + + public ImplementerViewModel? ReadElement(ImplementerSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + _logger.LogInformation("ReadElement. FIO:{FIO}.Id:{ Id}", + model.ImplementerFIO, model.Id); + var element = _implementerStorage.GetElement(model); + + if (element == null) + { + _logger.LogWarning("ReadElement element not found"); + return null; + } + _logger.LogInformation("ReadElement find. Id:{Id}", element.Id); + return element; + } + + public List? ReadList(ImplementerSearchModel? model) + { + _logger.LogInformation("ReadList. FIO:{FIO}.Id:{ Id} ", model?.ImplementerFIO, model?.Id); + var list = (model == null) ? _implementerStorage.GetFullList() : + _implementerStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + _logger.LogInformation("ReadList. Count:{Count}", list.Count); + return list; + } + + public bool Update(ImplementerBindingModel model) + { + CheckModel(model); + if (_implementerStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + return true; + } + + private void CheckModel(ImplementerBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (!withParams) + { + return; + } + if (model.WorkExperience < 0) + { + throw new ArgumentException("Опыт работы не должен быть отрицательным", nameof(model.WorkExperience)); + } + if (model.Qualification < 0) + { + throw new ArgumentException("Квалификация не должна быть отрицательной", nameof(model.Qualification)); + } + if (string.IsNullOrEmpty(model.Password)) + { + throw new ArgumentNullException("Нет пароля исполнителя", nameof(model.ImplementerFIO)); + } + if (string.IsNullOrEmpty(model.ImplementerFIO)) + { + throw new ArgumentNullException("Нет ФИО исполнителя", nameof(model.ImplementerFIO)); + } + _logger.LogInformation("Implementer. Id: {Id}, FIO: {FIO}", model.Id, model.ImplementerFIO); + var element = _implementerStorage.GetElement(new ImplementerSearchModel + { + ImplementerFIO = model.ImplementerFIO, + }); + if (element != null && element.Id != model.Id) + { + throw new InvalidOperationException("Исполнитель с таким ФИО уже есть"); + } + } + } +} diff --git a/GiftShop/GiftShopBusinessLogic/BusinessLogics/OrderLogic.cs b/GiftShop/GiftShopBusinessLogic/BusinessLogics/OrderLogic.cs index 050147d..997f9d2 100644 --- a/GiftShop/GiftShopBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/GiftShop/GiftShopBusinessLogic/BusinessLogics/OrderLogic.cs @@ -44,23 +44,38 @@ namespace GiftShopBusinessLogic.BusinessLogics public bool StatusUpdate(OrderBindingModel model, OrderStatus newStatus) { - CheckModel(model); + var vmodel = _orderStorage.GetElement(new() { Id = model.Id }); - if (model.Status + 1 != newStatus) + if (vmodel == null) { - _logger.LogWarning("Status update to " + newStatus.ToString() + " operation failed. Order status incorrect."); - return false; + throw new ArgumentNullException(nameof(model)); + } + + if ((int)vmodel.Status + 1 != (int)newStatus) + { + throw new InvalidOperationException($"Попытка перевести заказ не в следующий статус: " + + $"Текущий статус: {vmodel.Status} \n" + + $"Планируемый статус: {newStatus} \n" + + $"Доступный статус: {(OrderStatus)((int)vmodel.Status + 1)}"); } model.Status = newStatus; + model.DateCreate = vmodel.DateCreate; - if (model.Status == OrderStatus.Выдан) - model.DateImplement = DateTime.Now; + if (model.DateImplement == null) + model.DateImplement = vmodel.DateImplement; + + if (vmodel.ImplementerId.HasValue) + model.ImplementerId = vmodel.ImplementerId; + + model.GiftId = vmodel.GiftId; + model.Sum = vmodel.Sum; + model.Count = vmodel.Count; if (_orderStorage.Update(model) == null) { - model.Status--; _logger.LogWarning("Update operation failed"); + return false; } @@ -73,8 +88,9 @@ namespace GiftShopBusinessLogic.BusinessLogics } public bool DeliveryOrder(OrderBindingModel model) - { - return StatusUpdate(model, OrderStatus.Готов); + { + model.DateImplement = DateTime.Now; + return StatusUpdate(model, OrderStatus.Готов); } public bool FinishOrder(OrderBindingModel model) @@ -127,5 +143,28 @@ namespace GiftShopBusinessLogic.BusinessLogics _logger.LogInformation("Order. OrderId:{Id}.Sum:{ Sum}. EngineId: { EngineId}", model.Id, model.Sum, model.GiftId); } - } + + public OrderViewModel? ReadElement(OrderSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + + _logger.LogInformation("ReadElement. Id:{ Id}", model.Id); + + var element = _orderStorage.GetElement(model); + + if (element == null) + { + _logger.LogWarning("ReadElement element not found"); + + return null; + } + + _logger.LogInformation("ReadElement find. Id:{Id}", element.Id); + + return element; + } + } } diff --git a/GiftShop/GiftShopBusinessLogic/BusinessLogics/WorkModeling.cs b/GiftShop/GiftShopBusinessLogic/BusinessLogics/WorkModeling.cs new file mode 100644 index 0000000..76958b6 --- /dev/null +++ b/GiftShop/GiftShopBusinessLogic/BusinessLogics/WorkModeling.cs @@ -0,0 +1,138 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.BusinessLogicsContracts; +using GiftShopContracts.SearchModels; +using GiftShopContracts.ViewModels; +using GiftShopDataModels.Enums; +using Microsoft.Extensions.Logging; + +namespace GiftShopBusinessLogic.BusinessLogics +{ + public class WorkModeling : IWorkProcess + { + private readonly ILogger _logger; + + private readonly Random _rnd; + + private IOrderLogic? _orderLogic; + + public WorkModeling(ILogger logger) + { + _logger = logger; + _rnd = new Random(1000); + } + + public void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic) + { + _orderLogic = orderLogic; + var implementers = implementerLogic.ReadList(null); + if (implementers == null) + { + _logger.LogWarning("DoWork. Implementers is null"); + return; + } + + var orders = _orderLogic.ReadList(new OrderSearchModel { Status = OrderStatus.Принят }); + if (orders == null || orders.Count == 0) + { + _logger.LogWarning("DoWork. Orders is null or empty"); + return; + } + + _logger.LogDebug("DoWork for {Count} orders", orders.Count); + + foreach (var implementer in implementers) + { + Task.Run(() => WorkerWorkAsync(implementer, orders)); + } + } + + private async Task WorkerWorkAsync(ImplementerViewModel implementer, List orders) + { + if (_orderLogic == null || implementer == null) + { + return; + } + await RunOrderInWork(implementer); + + await Task.Run(() => + { + foreach (var order in orders) + { + try + { + _logger.LogDebug("DoWork. Worker {Id} try get order {Order}", implementer.Id, order.Id); + + _orderLogic.TakeOrderInWork(new OrderBindingModel + { + Id = order.Id, + ImplementerId = implementer.Id + }); + + Thread.Sleep(implementer.WorkExperience * _rnd.Next(100, 1000) * order.Count); + _logger.LogDebug("DoWork. Worker {Id} finish order {Order}", implementer.Id, order.Id); + + _orderLogic.DeliveryOrder(new OrderBindingModel + { + Id = order.Id + }); + + Thread.Sleep(implementer.Qualification * _rnd.Next(10, 100)); + } + + catch (InvalidOperationException ex) + { + _logger.LogWarning(ex, "Error try get work"); + } + + catch (Exception ex) + { + _logger.LogError(ex, "Error while do work"); + throw; + } + } + }); + } + //ищем заказ которые уже в работе + private async Task RunOrderInWork(ImplementerViewModel implementer) + { + if (_orderLogic == null || implementer == null) + { + return; + } + try + { + var runOrder = await Task.Run(() => _orderLogic.ReadElement(new OrderSearchModel + { + ImplementerId = implementer.Id, + Status = OrderStatus.Выполняется + })); + if (runOrder == null) + { + return; + } + + _logger.LogDebug("DoWork. Worker {Id} back to order {Order}", implementer.Id, runOrder.Id); + // доделываем работу + Thread.Sleep(implementer.WorkExperience * _rnd.Next(100, 300) * runOrder.Count); + _logger.LogDebug("DoWork. Worker {Id} finish order {Order}", implementer.Id, runOrder.Id); + _orderLogic.FinishOrder(new OrderBindingModel + { + Id = runOrder.Id + }); + // отдыхаем + Thread.Sleep(implementer.Qualification * _rnd.Next(10, 100)); + } + + catch (InvalidOperationException ex) + { + _logger.LogWarning(ex, "Error try get work"); + } + + catch (Exception ex) + { + _logger.LogError(ex, "Error while do work"); + throw; + } + } + } +} diff --git a/GiftShop/GiftShopContracts/BindingModels/ImplementerBindingModel.cs b/GiftShop/GiftShopContracts/BindingModels/ImplementerBindingModel.cs new file mode 100644 index 0000000..0b9007b --- /dev/null +++ b/GiftShop/GiftShopContracts/BindingModels/ImplementerBindingModel.cs @@ -0,0 +1,17 @@ +using GiftShopDataModels.Models; + +namespace GiftShopContracts.BindingModels +{ + public class ImplementerBindingModel : IImplementerModel + { + public int Id { get; set; } + + public string ImplementerFIO { get; set; } = string.Empty; + + public string Password { get; set; } = string.Empty; + + public int WorkExperience { get; set; } + + public int Qualification { get; set; } + } +} diff --git a/GiftShop/GiftShopContracts/BindingModels/OrderBindingModel.cs b/GiftShop/GiftShopContracts/BindingModels/OrderBindingModel.cs index d9cb0ab..3f70db2 100644 --- a/GiftShop/GiftShopContracts/BindingModels/OrderBindingModel.cs +++ b/GiftShop/GiftShopContracts/BindingModels/OrderBindingModel.cs @@ -22,5 +22,7 @@ namespace GiftShopContracts.BindingModels public DateTime DateCreate { get; set; } = DateTime.Now; public DateTime? DateImplement { get; set; } - } + + public int? ImplementerId { get; set; } + } } diff --git a/GiftShop/GiftShopContracts/BusinessLogicsContracts/IImplementerLogic.cs b/GiftShop/GiftShopContracts/BusinessLogicsContracts/IImplementerLogic.cs new file mode 100644 index 0000000..e9732ab --- /dev/null +++ b/GiftShop/GiftShopContracts/BusinessLogicsContracts/IImplementerLogic.cs @@ -0,0 +1,19 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.SearchModels; +using GiftShopContracts.ViewModels; + +namespace GiftShopContracts.BusinessLogicsContracts +{ + public interface IImplementerLogic + { + List? ReadList(ImplementerSearchModel? model); + + ImplementerViewModel? ReadElement(ImplementerSearchModel model); + + bool Create(ImplementerBindingModel model); + + bool Update(ImplementerBindingModel model); + + bool Delete(ImplementerBindingModel model); + } +} diff --git a/GiftShop/GiftShopContracts/BusinessLogicsContracts/IOrderLogic.cs b/GiftShop/GiftShopContracts/BusinessLogicsContracts/IOrderLogic.cs index 486d713..b299be8 100644 --- a/GiftShop/GiftShopContracts/BusinessLogicsContracts/IOrderLogic.cs +++ b/GiftShop/GiftShopContracts/BusinessLogicsContracts/IOrderLogic.cs @@ -8,7 +8,9 @@ namespace GiftShopContracts.BusinessLogicsContracts { List? ReadList(OrderSearchModel? model); - bool CreateOrder(OrderBindingModel model); + OrderViewModel? ReadElement(OrderSearchModel model); + + bool CreateOrder(OrderBindingModel model); bool TakeOrderInWork(OrderBindingModel model); diff --git a/GiftShop/GiftShopContracts/BusinessLogicsContracts/IWorkProcess.cs b/GiftShop/GiftShopContracts/BusinessLogicsContracts/IWorkProcess.cs new file mode 100644 index 0000000..f76ecc9 --- /dev/null +++ b/GiftShop/GiftShopContracts/BusinessLogicsContracts/IWorkProcess.cs @@ -0,0 +1,10 @@ +namespace GiftShopContracts.BusinessLogicsContracts +{ + public interface IWorkProcess + { + /// + /// Запуск работ + /// + void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic); + } +} diff --git a/GiftShop/GiftShopContracts/SearchModels/ImplementerSearchModel.cs b/GiftShop/GiftShopContracts/SearchModels/ImplementerSearchModel.cs new file mode 100644 index 0000000..ae36438 --- /dev/null +++ b/GiftShop/GiftShopContracts/SearchModels/ImplementerSearchModel.cs @@ -0,0 +1,11 @@ +namespace GiftShopContracts.SearchModels +{ + public class ImplementerSearchModel + { + public int? Id { get; set; } + + public string? ImplementerFIO { get; set; } + + public string? Password { get; set; } + } +} diff --git a/GiftShop/GiftShopContracts/SearchModels/OrderSearchModel.cs b/GiftShop/GiftShopContracts/SearchModels/OrderSearchModel.cs index 67ff007..ef5a8df 100644 --- a/GiftShop/GiftShopContracts/SearchModels/OrderSearchModel.cs +++ b/GiftShop/GiftShopContracts/SearchModels/OrderSearchModel.cs @@ -1,4 +1,6 @@ -namespace GiftShopContracts.SearchModels +using GiftShopDataModels.Enums; + +namespace GiftShopContracts.SearchModels { public class OrderSearchModel { @@ -9,5 +11,9 @@ public DateTime? DateFrom { get; set; } public DateTime? DateTo { get; set; } - } + + public int? ImplementerId { get; set; } + + public OrderStatus Status { get; set; } + } } diff --git a/GiftShop/GiftShopContracts/StoragesContracts/IImplementerStorage.cs b/GiftShop/GiftShopContracts/StoragesContracts/IImplementerStorage.cs new file mode 100644 index 0000000..98dc36d --- /dev/null +++ b/GiftShop/GiftShopContracts/StoragesContracts/IImplementerStorage.cs @@ -0,0 +1,21 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.SearchModels; +using GiftShopContracts.ViewModels; + +namespace GiftShopContracts.StoragesContracts +{ + public interface IImplementerStorage + { + List GetFullList(); + + List GetFilteredList(ImplementerSearchModel model); + + ImplementerViewModel? GetElement(ImplementerSearchModel model); + + ImplementerViewModel? Insert(ImplementerBindingModel model); + + ImplementerViewModel? Update(ImplementerBindingModel model); + + ImplementerViewModel? Delete(ImplementerBindingModel model); + } +} diff --git a/GiftShop/GiftShopContracts/ViewModels/ImplementerViewModel.cs b/GiftShop/GiftShopContracts/ViewModels/ImplementerViewModel.cs new file mode 100644 index 0000000..0b246a6 --- /dev/null +++ b/GiftShop/GiftShopContracts/ViewModels/ImplementerViewModel.cs @@ -0,0 +1,22 @@ +using GiftShopDataModels.Models; +using System.ComponentModel; + +namespace GiftShopContracts.ViewModels +{ + public class ImplementerViewModel : IImplementerModel + { + public int Id { get; set; } + + [DisplayName("ФИО исполнителя")] + public string ImplementerFIO { get; set; } = string.Empty; + + [DisplayName("Пароль")] + public string Password { get; set; } = string.Empty; + + [DisplayName("Стаж работы")] + public int WorkExperience { get; set; } + + [DisplayName("Квалификация")] + public int Qualification { get; set; } + } +} diff --git a/GiftShop/GiftShopContracts/ViewModels/OrderViewModel.cs b/GiftShop/GiftShopContracts/ViewModels/OrderViewModel.cs index 2182ed0..a0fee94 100644 --- a/GiftShop/GiftShopContracts/ViewModels/OrderViewModel.cs +++ b/GiftShop/GiftShopContracts/ViewModels/OrderViewModel.cs @@ -5,39 +5,38 @@ using System.ComponentModel; namespace GiftShopContracts.ViewModels { public class OrderViewModel : IOrderModel - { - public int Id { get; set; } + { + [DisplayName("Номер")] + public int Id { get; set; } public int GiftId { get; set; } public int ClientId { get; set; } - [DisplayName("Изделие")] + public int? ImplementerId { get; set; } + [DisplayName("Изделие")] public string GiftName { get; set; } = string.Empty; + [DisplayName("ФИО исполнителя")] + public string ImplementerFIO { get; set; } = string.Empty; + [DisplayName("Клиент")] public string ClientFIO { get; set; } = string.Empty; [DisplayName("Количество")] - public int Count { get; set; } [DisplayName("Сумма")] - public double Sum { get; set; } [DisplayName("Статус")] - public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; [DisplayName("Дата создания")] - public DateTime DateCreate { get; set; } = DateTime.Now; - [DisplayName("Дата выполнения")] - public DateTime? DateImplement { get; set; } } } diff --git a/GiftShop/GiftShopDataModels/Models/IImplementerModel.cs b/GiftShop/GiftShopDataModels/Models/IImplementerModel.cs new file mode 100644 index 0000000..696e194 --- /dev/null +++ b/GiftShop/GiftShopDataModels/Models/IImplementerModel.cs @@ -0,0 +1,13 @@ +namespace GiftShopDataModels.Models +{ + public interface IImplementerModel : IId + { + string ImplementerFIO { get; } + + string Password { get; } + + int WorkExperience { get; } + + int Qualification { get; } + } +} diff --git a/GiftShop/GiftShopDatabaseImplement/GiftShopDatabase.cs b/GiftShop/GiftShopDatabaseImplement/GiftShopDatabase.cs index a048bbf..dc7b314 100644 --- a/GiftShop/GiftShopDatabaseImplement/GiftShopDatabase.cs +++ b/GiftShop/GiftShopDatabaseImplement/GiftShopDatabase.cs @@ -23,5 +23,7 @@ namespace GiftShopDatabaseImplement public virtual DbSet Orders { set; get; } public virtual DbSet Clients { set; get; } - } + + public virtual DbSet Implementers { set; get; } + } } diff --git a/GiftShop/GiftShopDatabaseImplement/Implements/ImplementerStorage.cs b/GiftShop/GiftShopDatabaseImplement/Implements/ImplementerStorage.cs new file mode 100644 index 0000000..5050951 --- /dev/null +++ b/GiftShop/GiftShopDatabaseImplement/Implements/ImplementerStorage.cs @@ -0,0 +1,117 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.SearchModels; +using GiftShopContracts.StoragesContracts; +using GiftShopContracts.ViewModels; +using GiftShopDatabaseImplement.Models; + +namespace GiftShopDatabaseImplement.Implements +{ + public class ImplementerStorage : IImplementerStorage + { + public ImplementerViewModel? Delete(ImplementerBindingModel model) + { + using var context = new GiftShopDatabase(); + + var res = context.Implementers + .FirstOrDefault(x => x.Id == model.Id); + + if (res != null) + { + context.Implementers.Remove(res); + context.SaveChanges(); + } + + return res?.GetViewModel; + } + + public ImplementerViewModel? GetElement(ImplementerSearchModel model) + { + using var context = new GiftShopDatabase(); + + if (model.Id.HasValue) + return context.Implementers + .FirstOrDefault(x => x.Id == model.Id) + ?.GetViewModel; + + if (model.ImplementerFIO != null && model.Password != null) + return context.Implementers + .FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO) + && x.Password.Equals(model.Password)) + ?.GetViewModel; + + if (model.ImplementerFIO != null) + return context.Implementers + .FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO)) + ?.GetViewModel; + + return null; + } + + public List GetFilteredList(ImplementerSearchModel model) + { + if (model == null) + { + return new(); + } + + if (model.Id.HasValue) + { + var res = GetElement(model); + + return res != null ? new() { res } : new(); + } + + if (model.ImplementerFIO != null) + { + using var context = new GiftShopDatabase(); + + return context.Implementers + .Where(x => x.ImplementerFIO.Equals(model.ImplementerFIO)) + .Select(x => x.GetViewModel) + .ToList(); + } + + return new(); + } + + public List GetFullList() + { + using var context = new GiftShopDatabase(); + + return context.Implementers + .Select(x => x.GetViewModel) + .ToList(); + } + + public ImplementerViewModel? Insert(ImplementerBindingModel model) + { + using var context = new GiftShopDatabase(); + + var res = Implementer.Create(model); + + if (res != null) + { + context.Implementers.Add(res); + context.SaveChanges(); + } + + return res?.GetViewModel; + } + + public ImplementerViewModel? Update(ImplementerBindingModel model) + { + using var context = new GiftShopDatabase(); + + var res = context.Implementers + .FirstOrDefault(x => x.Id == model.Id); + + if (res != null) + { + res.Update(model); + context.SaveChanges(); + } + + return res?.GetViewModel; + } + } +} diff --git a/GiftShop/GiftShopDatabaseImplement/Implements/OrderStorage.cs b/GiftShop/GiftShopDatabaseImplement/Implements/OrderStorage.cs index 50be1d7..2a73c23 100644 --- a/GiftShop/GiftShopDatabaseImplement/Implements/OrderStorage.cs +++ b/GiftShop/GiftShopDatabaseImplement/Implements/OrderStorage.cs @@ -29,46 +29,61 @@ namespace GiftShopDatabaseImplement.Implements return null; } using var context = new GiftShopDatabase(); - return context.Orders.Include(x => x.Gift) - .Include(x => x.Client).FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; + if (model.ImplementerId.HasValue) + { + return context.Orders + .FirstOrDefault(x => x.ImplementerId == model.ImplementerId && x.Status.Equals(model.Status)) + ?.GetViewModel; + } + return context.Orders + .FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id) + ?.GetViewModel; } public List GetFilteredList(OrderSearchModel model) { - if (!model.DateFrom.HasValue && !model.DateTo.HasValue && !model.ClientId.HasValue) + if (model is null) { return new(); } using var context = new GiftShopDatabase(); - if (model.DateFrom.HasValue) + if (model.DateTo != null && model.DateFrom != null && model.ClientId.HasValue) { return context.Orders - .Include(x => x.Gift) - .Include(x => x.Client) - .Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo) - .Select(x => x.GetViewModel) - .ToList(); - } - else if (model.ClientId.HasValue) - return context.Orders - .Include(x => x.Gift) - .Include(x => x.Client) - .Where(x => x.ClientId == model.ClientId) + .Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo && x.ClientId == model.ClientId) + .ToList() .Select(x => x.GetViewModel) .ToList(); + } + + else if (model.DateTo != null && model.DateFrom != null) + { + return context.Orders + .Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo) + .ToList() + .Select(x => x.GetViewModel) + .ToList(); + } + else if (model.ClientId.HasValue) + { + return context.Orders + .Where(x => x.ClientId == model.ClientId) + .ToList() + .Select(x => x.GetViewModel) + .ToList(); + } return context.Orders - .Include(x => x.Gift) - .Include(x => x.Client) - .Where(x => x.Id == model.Id) - .Select(x => x.GetViewModel) - .ToList(); + .Where(x => x.Status == model.Status) + .ToList() + .Select(x => x.GetViewModel) + .ToList(); } public List GetFullList() { using var context = new GiftShopDatabase(); return context.Orders.Include(x => x.Gift) - .Include(x => x.Client).Select(x => x.GetViewModel).ToList(); + .Include(x => x.Client).Include(x => x.Implementer).Select(x => x.GetViewModel).ToList(); } public OrderViewModel? Insert(OrderBindingModel model) @@ -85,6 +100,7 @@ namespace GiftShopDatabaseImplement.Implements return context.Orders .Include(x => x.Gift) .Include(x => x.Client) + .Include(x => x.Implementer) .FirstOrDefault(x => x.Id == newOrder.Id) ?.GetViewModel; } @@ -93,7 +109,7 @@ namespace GiftShopDatabaseImplement.Implements { using var context = new GiftShopDatabase(); var order = context.Orders.Include(x => x.Gift) - .Include(x => x.Client).FirstOrDefault(x => x.Id == model.Id); + .Include(x => x.Client).Include(x => x.Implementer).FirstOrDefault(x => x.Id == model.Id); if (order == null) { return null; diff --git a/GiftShop/GiftShopDatabaseImplement/Migrations/20230428071341_SecMigration.Designer.cs b/GiftShop/GiftShopDatabaseImplement/Migrations/20230514095932_SecMigration.Designer.cs similarity index 82% rename from GiftShop/GiftShopDatabaseImplement/Migrations/20230428071341_SecMigration.Designer.cs rename to GiftShop/GiftShopDatabaseImplement/Migrations/20230514095932_SecMigration.Designer.cs index fdac7f5..48e6665 100644 --- a/GiftShop/GiftShopDatabaseImplement/Migrations/20230428071341_SecMigration.Designer.cs +++ b/GiftShop/GiftShopDatabaseImplement/Migrations/20230514095932_SecMigration.Designer.cs @@ -12,7 +12,7 @@ using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace GiftShopDatabaseImplement.Migrations { [DbContext(typeof(GiftShopDatabase))] - [Migration("20230428071341_SecMigration")] + [Migration("20230514095932_SecMigration")] partial class SecMigration { /// @@ -116,6 +116,33 @@ namespace GiftShopDatabaseImplement.Migrations b.ToTable("GiftComponents"); }); + modelBuilder.Entity("GiftShopDatabaseImplement.Models.Implementer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ImplementerFIO") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Password") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Qualification") + .HasColumnType("int"); + + b.Property("WorkExperience") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.ToTable("Implementers"); + }); + modelBuilder.Entity("GiftShopDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -143,6 +170,9 @@ namespace GiftShopDatabaseImplement.Migrations .IsRequired() .HasColumnType("nvarchar(max)"); + b.Property("ImplementerId") + .HasColumnType("int"); + b.Property("Status") .HasColumnType("int"); @@ -155,6 +185,8 @@ namespace GiftShopDatabaseImplement.Migrations b.HasIndex("GiftId"); + b.HasIndex("ImplementerId"); + b.ToTable("Orders"); }); @@ -191,9 +223,15 @@ namespace GiftShopDatabaseImplement.Migrations .OnDelete(DeleteBehavior.Cascade) .IsRequired(); + b.HasOne("GiftShopDatabaseImplement.Models.Implementer", "Implementer") + .WithMany("Orders") + .HasForeignKey("ImplementerId"); + b.Navigation("Client"); b.Navigation("Gift"); + + b.Navigation("Implementer"); }); modelBuilder.Entity("GiftShopDatabaseImplement.Models.Client", b => @@ -212,6 +250,11 @@ namespace GiftShopDatabaseImplement.Migrations b.Navigation("Orders"); }); + + modelBuilder.Entity("GiftShopDatabaseImplement.Models.Implementer", b => + { + b.Navigation("Orders"); + }); #pragma warning restore 612, 618 } } diff --git a/GiftShop/GiftShopDatabaseImplement/Migrations/20230428071341_SecMigration.cs b/GiftShop/GiftShopDatabaseImplement/Migrations/20230514095932_SecMigration.cs similarity index 82% rename from GiftShop/GiftShopDatabaseImplement/Migrations/20230428071341_SecMigration.cs rename to GiftShop/GiftShopDatabaseImplement/Migrations/20230514095932_SecMigration.cs index 8fbdbe1..4aeb64e 100644 --- a/GiftShop/GiftShopDatabaseImplement/Migrations/20230428071341_SecMigration.cs +++ b/GiftShop/GiftShopDatabaseImplement/Migrations/20230514095932_SecMigration.cs @@ -54,6 +54,22 @@ namespace GiftShopDatabaseImplement.Migrations table.PrimaryKey("PK_Gifts", x => x.Id); }); + migrationBuilder.CreateTable( + name: "Implementers", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + ImplementerFIO = table.Column(type: "nvarchar(max)", nullable: false), + Password = table.Column(type: "nvarchar(max)", nullable: false), + WorkExperience = table.Column(type: "int", nullable: false), + Qualification = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Implementers", x => x.Id); + }); + migrationBuilder.CreateTable( name: "GiftComponents", columns: table => new @@ -89,6 +105,7 @@ namespace GiftShopDatabaseImplement.Migrations .Annotation("SqlServer:Identity", "1, 1"), GiftId = table.Column(type: "int", nullable: false), ClientId = table.Column(type: "int", nullable: false), + ImplementerId = table.Column(type: "int", nullable: true), GiftName = table.Column(type: "nvarchar(max)", nullable: false), Count = table.Column(type: "int", nullable: false), Sum = table.Column(type: "float", nullable: false), @@ -111,6 +128,11 @@ namespace GiftShopDatabaseImplement.Migrations principalTable: "Gifts", principalColumn: "Id", onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_Orders_Implementers_ImplementerId", + column: x => x.ImplementerId, + principalTable: "Implementers", + principalColumn: "Id"); }); migrationBuilder.CreateIndex( @@ -132,6 +154,11 @@ namespace GiftShopDatabaseImplement.Migrations name: "IX_Orders_GiftId", table: "Orders", column: "GiftId"); + + migrationBuilder.CreateIndex( + name: "IX_Orders_ImplementerId", + table: "Orders", + column: "ImplementerId"); } /// @@ -151,6 +178,9 @@ namespace GiftShopDatabaseImplement.Migrations migrationBuilder.DropTable( name: "Gifts"); + + migrationBuilder.DropTable( + name: "Implementers"); } } } diff --git a/GiftShop/GiftShopDatabaseImplement/Migrations/GiftShopDatabaseModelSnapshot.cs b/GiftShop/GiftShopDatabaseImplement/Migrations/GiftShopDatabaseModelSnapshot.cs index c06af06..4ee65ea 100644 --- a/GiftShop/GiftShopDatabaseImplement/Migrations/GiftShopDatabaseModelSnapshot.cs +++ b/GiftShop/GiftShopDatabaseImplement/Migrations/GiftShopDatabaseModelSnapshot.cs @@ -113,6 +113,33 @@ namespace GiftShopDatabaseImplement.Migrations b.ToTable("GiftComponents"); }); + modelBuilder.Entity("GiftShopDatabaseImplement.Models.Implementer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ImplementerFIO") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Password") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Qualification") + .HasColumnType("int"); + + b.Property("WorkExperience") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.ToTable("Implementers"); + }); + modelBuilder.Entity("GiftShopDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -140,6 +167,9 @@ namespace GiftShopDatabaseImplement.Migrations .IsRequired() .HasColumnType("nvarchar(max)"); + b.Property("ImplementerId") + .HasColumnType("int"); + b.Property("Status") .HasColumnType("int"); @@ -152,6 +182,8 @@ namespace GiftShopDatabaseImplement.Migrations b.HasIndex("GiftId"); + b.HasIndex("ImplementerId"); + b.ToTable("Orders"); }); @@ -188,9 +220,15 @@ namespace GiftShopDatabaseImplement.Migrations .OnDelete(DeleteBehavior.Cascade) .IsRequired(); + b.HasOne("GiftShopDatabaseImplement.Models.Implementer", "Implementer") + .WithMany("Orders") + .HasForeignKey("ImplementerId"); + b.Navigation("Client"); b.Navigation("Gift"); + + b.Navigation("Implementer"); }); modelBuilder.Entity("GiftShopDatabaseImplement.Models.Client", b => @@ -209,6 +247,11 @@ namespace GiftShopDatabaseImplement.Migrations b.Navigation("Orders"); }); + + modelBuilder.Entity("GiftShopDatabaseImplement.Models.Implementer", b => + { + b.Navigation("Orders"); + }); #pragma warning restore 612, 618 } } diff --git a/GiftShop/GiftShopDatabaseImplement/Models/Implementer.cs b/GiftShop/GiftShopDatabaseImplement/Models/Implementer.cs new file mode 100644 index 0000000..f4ac6a2 --- /dev/null +++ b/GiftShop/GiftShopDatabaseImplement/Models/Implementer.cs @@ -0,0 +1,65 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.ViewModels; +using GiftShopDataModels.Models; +using System.ComponentModel.DataAnnotations.Schema; +using System.ComponentModel.DataAnnotations; + +namespace GiftShopDatabaseImplement.Models +{ + public class Implementer : IImplementerModel + { + [Required] + public string ImplementerFIO { get; private set; } = string.Empty; + + [Required] + public string Password { get; private set; } = string.Empty; + + [Required] + public int WorkExperience { get; private set; } + + [Required] + public int Qualification { get; private set; } + + public int Id { get; private set; } + + [ForeignKey("ImplementerId")] + public virtual List Orders { get; private set; } = new(); + + public static Implementer? Create(ImplementerBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Id = model.Id, + Password = model.Password, + Qualification = model.Qualification, + ImplementerFIO = model.ImplementerFIO, + WorkExperience = model.WorkExperience + }; + } + + public void Update(ImplementerBindingModel model) + { + if (model == null) + { + return; + } + Password = model.Password; + Qualification = model.Qualification; + ImplementerFIO = model.ImplementerFIO; + WorkExperience = model.WorkExperience; + } + + public ImplementerViewModel GetViewModel => new() + { + Id = Id, + Password = Password, + Qualification = Qualification, + ImplementerFIO = ImplementerFIO, + WorkExperience = WorkExperience + }; + } +} diff --git a/GiftShop/GiftShopDatabaseImplement/Models/Order.cs b/GiftShop/GiftShopDatabaseImplement/Models/Order.cs index 6927333..dfcec2c 100644 --- a/GiftShop/GiftShopDatabaseImplement/Models/Order.cs +++ b/GiftShop/GiftShopDatabaseImplement/Models/Order.cs @@ -15,6 +15,8 @@ namespace GiftShopDatabaseImplement.Models [Required] public int ClientId { get; set; } + public int? ImplementerId { get; private set; } + public string GiftName { get; private set; } = string.Empty; [Required] @@ -35,6 +37,8 @@ namespace GiftShopDatabaseImplement.Models public Client Client { get; set; } + public Implementer? Implementer { get; set; } + public static Order? Create(OrderBindingModel? model) { if (model == null) @@ -47,6 +51,7 @@ namespace GiftShopDatabaseImplement.Models Id = model.Id, GiftId = model.GiftId, ClientId = model.ClientId, + ImplementerId = model.ImplementerId, GiftName = model.GiftName, Count = model.Count, Sum = model.Sum, @@ -61,16 +66,11 @@ namespace GiftShopDatabaseImplement.Models if (model == null) { return; - } - - GiftId = model.GiftId; - GiftName = model.GiftName; - Count = model.Count; - Sum = model.Sum; - Status = model.Status; - DateCreate = model.DateCreate; - DateImplement = model.DateImplement; - } + } + Status = model.Status; + DateImplement = model.DateImplement; + ImplementerId = model.ImplementerId; + } public OrderViewModel GetViewModel { @@ -82,13 +82,15 @@ namespace GiftShopDatabaseImplement.Models Id = Id, GiftId = GiftId, ClientId = ClientId, + ImplementerId = ImplementerId, ClientFIO = context.Clients.FirstOrDefault(x => x.Id == ClientId)?.ClientFIO ?? string.Empty, GiftName = context.Gifts.FirstOrDefault(x => x.Id == GiftId)?.GiftName ?? string.Empty, Count = Count, Sum = Sum, Status = Status, DateCreate = DateCreate, - DateImplement = DateImplement + DateImplement = DateImplement, + ImplementerFIO = Implementer?.ImplementerFIO ?? string.Empty }; } } diff --git a/GiftShop/GiftShopFileImplement/DataFileSingleton.cs b/GiftShop/GiftShopFileImplement/DataFileSingleton.cs index 3cf0f4b..32b41a0 100644 --- a/GiftShop/GiftShopFileImplement/DataFileSingleton.cs +++ b/GiftShop/GiftShopFileImplement/DataFileSingleton.cs @@ -15,6 +15,8 @@ namespace GiftShopFileImplement private readonly string ClientFileName = "Client.xml"; + private readonly string ImplementerFileName = "Implementer.xml"; + public List Components { get; private set; } public List Orders { get; private set; } @@ -23,6 +25,8 @@ namespace GiftShopFileImplement public List Clients { get; private set; } + public List Implementers { get; private set; } + public static DataFileSingleton GetInstance() { if (instance == null) @@ -40,12 +44,15 @@ namespace GiftShopFileImplement public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", x => x.GetXElement); + public void SaveImplementers() => SaveData(Implementers, OrderFileName, "Implementers", x => x.GetXElement); + private DataFileSingleton() { Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!; Gifts = LoadData(GiftFileName, "Gift", x => Gift.Create(x)!)!; Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!; - } + Implementers = LoadData(ImplementerFileName, "Implementer", x => Implementer.Create(x)!)!; + } private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) { diff --git a/GiftShop/GiftShopFileImplement/Implements/ImplementerStorage.cs b/GiftShop/GiftShopFileImplement/Implements/ImplementerStorage.cs new file mode 100644 index 0000000..f648487 --- /dev/null +++ b/GiftShop/GiftShopFileImplement/Implements/ImplementerStorage.cs @@ -0,0 +1,103 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.SearchModels; +using GiftShopContracts.StoragesContracts; +using GiftShopContracts.ViewModels; +using GiftShopFileImplement.Models; + +namespace GiftShopFileImplement.Implements +{ + public class ImplementerStorage : IImplementerStorage + { + private readonly DataFileSingleton _source; + public ImplementerStorage() + { + _source = DataFileSingleton.GetInstance(); + } + public ImplementerViewModel? Delete(ImplementerBindingModel model) + { + var res = _source.Implementers.FirstOrDefault(x => x.Id == model.Id); + + if (res != null) + { + _source.Implementers.Remove(res); + _source.SaveImplementers(); + } + return res?.GetViewModel; + } + + public ImplementerViewModel? GetElement(ImplementerSearchModel model) + { + if (model.Id.HasValue) + return _source.Implementers.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; + + if (model.ImplementerFIO != null && model.Password != null) + return _source.Implementers + .FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO) + && x.Password.Equals(model.Password)) + ?.GetViewModel; + + if (model.ImplementerFIO != null) + return _source.Implementers.FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO))?.GetViewModel; + + return null; + } + + public List GetFilteredList(ImplementerSearchModel model) + { + if (model == null) + { + return new(); + } + + if (model.Id.HasValue) + { + var res = GetElement(model); + + return res != null ? new() { res } : new(); + } + + if (model.ImplementerFIO != null) + { + return _source.Implementers + .Where(x => x.ImplementerFIO.Equals(model.ImplementerFIO)) + .Select(x => x.GetViewModel) + .ToList(); + } + + return new(); + } + + public List GetFullList() + { + return _source.Implementers.Select(x => x.GetViewModel).ToList(); + } + + public ImplementerViewModel? Insert(ImplementerBindingModel model) + { + model.Id = _source.Implementers.Count > 0 ? _source.Implementers.Max(x => x.Id) + 1 : 1; + + var res = Implementer.Create(model); + + if (res != null) + { + _source.Implementers.Add(res); + _source.SaveImplementers(); + } + + return res?.GetViewModel; + } + + public ImplementerViewModel? Update(ImplementerBindingModel model) + { + var res = _source.Implementers.FirstOrDefault(x => x.Id == model.Id); + + if (res != null) + { + res.Update(model); + _source.SaveImplementers(); + } + + return res?.GetViewModel; + } + } +} diff --git a/GiftShop/GiftShopFileImplement/Models/Implementer.cs b/GiftShop/GiftShopFileImplement/Models/Implementer.cs new file mode 100644 index 0000000..64cdca2 --- /dev/null +++ b/GiftShop/GiftShopFileImplement/Models/Implementer.cs @@ -0,0 +1,81 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.ViewModels; +using GiftShopDataModels.Models; +using System.Xml.Linq; + +namespace GiftShopFileImplement.Models +{ + public class Implementer : IImplementerModel + { + public string ImplementerFIO { get; private set; } = string.Empty; + + public string Password { get; private set; } = string.Empty; + + public int WorkExperience { get; private set; } + + public int Qualification { get; private set; } + + public int Id { get; private set; } + + public static Implementer? Create(XElement element) + { + if (element == null) + { + return null; + } + return new() + { + ImplementerFIO = element.Element("FIO")!.Value, + Password = element.Element("Password")!.Value, + Id = Convert.ToInt32(element.Attribute("Id")!.Value), + Qualification = Convert.ToInt32(element.Element("Qualification")!.Value), + WorkExperience = Convert.ToInt32(element.Element("WorkExperience")!.Value), + }; + } + + public static Implementer? Create(ImplementerBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Id = model.Id, + Password = model.Password, + Qualification = model.Qualification, + ImplementerFIO = model.ImplementerFIO, + WorkExperience = model.WorkExperience, + }; + } + + public void Update(ImplementerBindingModel model) + { + if (model == null) + { + return; + } + Password = model.Password; + Qualification = model.Qualification; + ImplementerFIO = model.ImplementerFIO; + WorkExperience = model.WorkExperience; + } + + public ImplementerViewModel GetViewModel => new() + { + Id = Id, + Password = Password, + Qualification = Qualification, + ImplementerFIO = ImplementerFIO, + WorkExperience = WorkExperience + }; + + public XElement GetXElement => new("Client", + new XAttribute("Id", Id), + new XElement("Password", Password), + new XElement("FIO", ImplementerFIO), + new XElement("Qualification", Qualification), + new XElement("WorkExperience", WorkExperience) + ); + } +} diff --git a/GiftShop/GiftShopFileImplement/Models/Order.cs b/GiftShop/GiftShopFileImplement/Models/Order.cs index b44f984..e2c5acf 100644 --- a/GiftShop/GiftShopFileImplement/Models/Order.cs +++ b/GiftShop/GiftShopFileImplement/Models/Order.cs @@ -10,7 +10,13 @@ namespace GiftShopFileImplement.Models { public int GiftId { get; private set; } - public int Count { get; private set; } + public int? ImplementerId { get; set; } + + public int ClientId { get; private set; } + + public string GiftName { get; private set; } = string.Empty; + + public int Count { get; private set; } public double Sum { get; private set; } @@ -32,8 +38,11 @@ namespace GiftShopFileImplement.Models { Id = model.Id, GiftId = model.GiftId, - Count = model.Count, - Sum = model.Sum, + GiftName = model.GiftName, + Count = model.Count, + ClientId = model.ClientId, + ImplementerId = model.ImplementerId, + Sum = model.Sum, Status = model.Status, DateCreate = model.DateCreate, DateImplement = model.DateImplement @@ -47,14 +56,17 @@ namespace GiftShopFileImplement.Models return null; } var order = new Order() - { - Id = Convert.ToInt32(element.Attribute("Id")!.Value), - GiftId = Convert.ToInt32(element.Element("GiftId")!.Value), - Count = Convert.ToInt32(element.Element("Count")!.Value), - Sum = Convert.ToDouble(element.Element("Sum")!.Value), - Status = (OrderStatus)Enum.Parse(typeof(OrderStatus), element.Element("Status")!.Value), - DateCreate = DateTime.ParseExact(element.Element("DateCreate")!.Value, "G", null) - }; + { + Id = Convert.ToInt32(element.Attribute("Id")!.Value), + GiftId = Convert.ToInt32(element.Element("GiftId")!.Value), + GiftName = element.Element("GiftName")!.Value, + Count = Convert.ToInt32(element.Element("Count")!.Value), + Sum = Convert.ToDouble(element.Element("Sum")!.Value), + ImplementerId = Convert.ToInt32(element.Element("ImplementerId")!.Value), + ClientId = Convert.ToInt32(element.Element("ClientId")!.Value), + Status = (OrderStatus)Enum.Parse(typeof(OrderStatus), element.Element("Status")!.Value), + DateCreate = DateTime.ParseExact(element.Element("DateCreate")!.Value, "G", null) + }; DateTime.TryParse(element.Element("DateImplement")!.Value, out DateTime dateImpl); order.DateImplement = dateImpl; @@ -67,33 +79,35 @@ namespace GiftShopFileImplement.Models if (model == null) { return; - } - GiftId = model.GiftId; - Count = model.Count; - Sum = model.Sum; - Status = model.Status; - DateCreate = model.DateCreate; - DateImplement = model.DateImplement; - } + } + Status = model.Status; + DateImplement = model.DateImplement; + } public OrderViewModel GetViewModel => new() - { - Id = Id, - GiftId = GiftId, - Count = Count, - Sum = Sum, - Status = Status, - DateCreate = DateCreate, - DateImplement = DateImplement - }; + { + Id = Id, + GiftId = GiftId, + ClientId = ClientId, + ImplementerId = ImplementerId, + GiftName = GiftName, + Count = Count, + Sum = Sum, + Status = Status, + DateCreate = DateCreate, + DateImplement = DateImplement + }; public XElement GetXElement => new("Order", - new XAttribute("Id", Id), - new XElement("GiftId", GiftId.ToString()), - new XElement("Count", Count.ToString()), - new XElement("Sum", Sum.ToString()), - new XElement("Status", Status.ToString()), - new XElement("DateCreate", DateCreate.ToString()), - new XElement("DateImplement", DateImplement.ToString())); - } + new XAttribute("Id", Id), + new XElement("GiftName", GiftName), + new XElement("GiftId", GiftId.ToString()), + new XElement("ClientId", ClientId.ToString()), + new XElement("ImplementerId", ImplementerId.ToString()), + new XElement("Count", Count.ToString()), + new XElement("Sum", Sum.ToString()), + new XElement("Status", Status.ToString()), + new XElement("DateCreate", DateCreate.ToString()), + new XElement("DateImplement", DateImplement.ToString())); + } } diff --git a/GiftShop/GiftShopListImplement/DataListSingleton.cs b/GiftShop/GiftShopListImplement/DataListSingleton.cs index 4cd0e49..ec01b43 100644 --- a/GiftShop/GiftShopListImplement/DataListSingleton.cs +++ b/GiftShop/GiftShopListImplement/DataListSingleton.cs @@ -9,13 +9,16 @@ namespace GiftShopListImplement public List Orders { get; set; } public List Gifts { get; set; } public List Clients { get; set; } + public List Implementers { get; set; } private DataListSingleton() { Components = new List(); Orders = new List(); Gifts = new List(); - } + Clients = new List(); + Implementers = new List(); + } public static DataListSingleton GetInstance() { if (_instance == null) diff --git a/GiftShop/GiftShopListImplement/Implements/ImplementerStorage.cs b/GiftShop/GiftShopListImplement/Implements/ImplementerStorage.cs new file mode 100644 index 0000000..bce7e56 --- /dev/null +++ b/GiftShop/GiftShopListImplement/Implements/ImplementerStorage.cs @@ -0,0 +1,126 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.SearchModels; +using GiftShopContracts.StoragesContracts; +using GiftShopContracts.ViewModels; +using GiftShopListImplement.Models; + +namespace GiftShopListImplement.Implements +{ + public class ImplementerStorage : IImplementerStorage + { + private readonly DataListSingleton _source; + public ImplementerStorage() + { + _source = DataListSingleton.GetInstance(); + } + + public ImplementerViewModel? Delete(ImplementerBindingModel model) + { + for (int i = 0; i < _source.Implementers.Count; ++i) + { + if (_source.Implementers[i].Id == model.Id) + { + var element = _source.Implementers[i]; + _source.Implementers.RemoveAt(i); + + return element.GetViewModel; + } + } + return null; + } + + public ImplementerViewModel? GetElement(ImplementerSearchModel model) + { + foreach (var x in _source.Implementers) + { + if (model.Id.HasValue && x.Id == model.Id) + return x.GetViewModel; + + if (model.ImplementerFIO != null && model.Password != null && + x.ImplementerFIO.Equals(model.ImplementerFIO) && + x.Password.Equals(model.Password)) + return x.GetViewModel; + + if (model.ImplementerFIO != null && x.ImplementerFIO.Equals(model.ImplementerFIO)) + return x.GetViewModel; + } + return null; + } + + public List GetFilteredList(ImplementerSearchModel model) + { + if (model == null) + { + return new(); + } + + if (model.Id.HasValue) + { + var res = GetElement(model); + + return res != null ? new() { res } : new(); + } + + List result = new(); + + if (model.ImplementerFIO != null) + { + foreach (var implementer in _source.Implementers) + { + if (implementer.ImplementerFIO.Equals(model.ImplementerFIO)) + { + result.Add(implementer.GetViewModel); + } + } + } + return result; + } + + public List GetFullList() + { + var result = new List(); + + foreach (var implementer in _source.Implementers) + { + result.Add(implementer.GetViewModel); + } + + return result; + } + + public ImplementerViewModel? Insert(ImplementerBindingModel model) + { + model.Id = 1; + + foreach (var implementer in _source.Implementers) + { + if (model.Id <= implementer.Id) + { + model.Id = implementer.Id + 1; + } + } + + var res = Implementer.Create(model); + + if (res != null) + { + _source.Implementers.Add(res); + } + return res?.GetViewModel; + } + + public ImplementerViewModel? Update(ImplementerBindingModel model) + { + foreach (var implementer in _source.Implementers) + { + if (implementer.Id == model.Id) + { + implementer.Update(model); + + return implementer.GetViewModel; + } + } + return null; + } + } +} diff --git a/GiftShop/GiftShopListImplement/Models/Implementer.cs b/GiftShop/GiftShopListImplement/Models/Implementer.cs new file mode 100644 index 0000000..ceef145 --- /dev/null +++ b/GiftShop/GiftShopListImplement/Models/Implementer.cs @@ -0,0 +1,56 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.ViewModels; +using GiftShopDataModels.Models; + +namespace GiftShopListImplement.Models +{ + public class Implementer : IImplementerModel + { + public string ImplementerFIO { get; private set; } = string.Empty; + + public string Password { get; private set; } = string.Empty; + + public int WorkExperience { get; private set; } + + public int Qualification { get; private set; } + + public int Id { get; private set; } + + public static Implementer? Create(ImplementerBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Id = model.Id, + Password = model.Password, + Qualification = model.Qualification, + ImplementerFIO = model.ImplementerFIO, + WorkExperience = model.WorkExperience, + }; + } + + public void Update(ImplementerBindingModel model) + { + if (model == null) + { + return; + } + Password = model.Password; + Qualification = model.Qualification; + ImplementerFIO = model.ImplementerFIO; + WorkExperience = model.WorkExperience; + } + + public ImplementerViewModel GetViewModel => new() + { + Id = Id, + Password = Password, + Qualification = Qualification, + ImplementerFIO = ImplementerFIO, + WorkExperience = WorkExperience + }; + } +} diff --git a/GiftShop/GiftShopListImplement/Models/Order.cs b/GiftShop/GiftShopListImplement/Models/Order.cs index 90a9a36..5e4f4ce 100644 --- a/GiftShop/GiftShopListImplement/Models/Order.cs +++ b/GiftShop/GiftShopListImplement/Models/Order.cs @@ -9,9 +9,13 @@ namespace GiftShopListImplement.Models { public int GiftId { get; private set; } - public string GiftName { get; private set; } + public int? ImplementerId { get; private set; } - public int Count { get; private set; } + public string GiftName { get; private set; } + + public int ClientId { get; private set; } + + public int Count { get; private set; } public double Sum { get; private set; } @@ -38,8 +42,10 @@ namespace GiftShopListImplement.Models Sum = model.Sum, Status = model.Status, DateCreate = model.DateCreate, - DateImplement = model.DateImplement - }; + DateImplement = model.DateImplement, + ImplementerId = model.ImplementerId, + ClientId = model.ClientId, + }; } public void Update(OrderBindingModel? model) @@ -49,7 +55,6 @@ namespace GiftShopListImplement.Models return; } Status = model.Status; - DateImplement = model.DateImplement; } public OrderViewModel GetViewModel => new() @@ -61,7 +66,9 @@ namespace GiftShopListImplement.Models Sum = Sum, Status = Status, DateCreate = DateCreate, - DateImplement = DateImplement - }; + DateImplement = DateImplement, + ClientId = ClientId, + ImplementerId = ImplementerId + }; } } diff --git a/GiftShop/GiftShopRestApi/Controllers/ImplementerController.cs b/GiftShop/GiftShopRestApi/Controllers/ImplementerController.cs new file mode 100644 index 0000000..02f3254 --- /dev/null +++ b/GiftShop/GiftShopRestApi/Controllers/ImplementerController.cs @@ -0,0 +1,103 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.BusinessLogicsContracts; +using GiftShopContracts.SearchModels; +using GiftShopContracts.ViewModels; +using GiftShopDataModels.Enums; +using Microsoft.AspNetCore.Mvc; + +namespace GiftShopRestApi.Controllers +{ + [Route("api/[controller]/[action]")] + [ApiController] + public class ImplementerController : Controller + { + private readonly ILogger _logger; + private readonly IOrderLogic _order; + private readonly IImplementerLogic _logic; + public ImplementerController(IOrderLogic order, IImplementerLogic logic, ILogger logger) + { + _logger = logger; + _order = order; + _logic = logic; + } + + [HttpGet] + public ImplementerViewModel? Login(string login, string password) + { + try + { + return _logic.ReadElement(new ImplementerSearchModel + { + ImplementerFIO = login, + Password = password + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка авторизации сотрудника"); + throw; + } + } + + [HttpGet] + public List? GetNewOrders() + { + try + { + return _order.ReadList(new OrderSearchModel + { + Status = OrderStatus.Принят + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения новых заказов"); + throw; + } + } + [HttpGet] + public OrderViewModel? GetImplementerOrder(int implementerId) + { + try + { + return _order.ReadElement(new OrderSearchModel + { + ImplementerId = implementerId + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения текущего заказа исполнителя"); + + throw; + } + } + [HttpPost] + public void TakeOrderInWork(OrderBindingModel model) + { + try + { + _order.TakeOrderInWork(model); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка перевода заказа с №{Id} в работу", + model.Id); + throw; + } + } + [HttpPost] + public void FinishOrder(OrderBindingModel model) + { + try + { + _order.FinishOrder(model); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка отметки о готовности заказа с №{ Id}", model.Id); + throw; + } + } + } +} diff --git a/GiftShop/GiftShopRestApi/Program.cs b/GiftShop/GiftShopRestApi/Program.cs index 1eaf4d0..3bc676c 100644 --- a/GiftShop/GiftShopRestApi/Program.cs +++ b/GiftShop/GiftShopRestApi/Program.cs @@ -12,11 +12,13 @@ builder.Logging.AddLog4Net("log4net.config"); // Add services to the container. builder.Services.AddTransient(); +builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddControllers(); diff --git a/GiftShop/GiftShopView/FormImplementer.Designer.cs b/GiftShop/GiftShopView/FormImplementer.Designer.cs new file mode 100644 index 0000000..a5d7390 --- /dev/null +++ b/GiftShop/GiftShopView/FormImplementer.Designer.cs @@ -0,0 +1,174 @@ +namespace GiftShopView +{ + partial class FormImplementer + { + /// + /// 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() + { + FIOTextBox = new TextBox(); + PasswordTextBox = new TextBox(); + LabelFIO = new Label(); + LabelPassword = new Label(); + QualificationNumericUpDown = new NumericUpDown(); + WorkExpNumericUpDown = new NumericUpDown(); + LabelWorkExperience = new Label(); + LabelQualification = new Label(); + ButtonCancel = new Button(); + ButtonSave = new Button(); + ((System.ComponentModel.ISupportInitialize)QualificationNumericUpDown).BeginInit(); + ((System.ComponentModel.ISupportInitialize)WorkExpNumericUpDown).BeginInit(); + SuspendLayout(); + // + // FIOTextBox + // + FIOTextBox.Location = new Point(144, 13); + FIOTextBox.Margin = new Padding(3, 4, 3, 4); + FIOTextBox.Name = "FIOTextBox"; + FIOTextBox.Size = new Size(194, 27); + FIOTextBox.TabIndex = 0; + // + // PasswordTextBox + // + PasswordTextBox.Location = new Point(144, 66); + PasswordTextBox.Margin = new Padding(3, 4, 3, 4); + PasswordTextBox.Name = "PasswordTextBox"; + PasswordTextBox.Size = new Size(194, 27); + PasswordTextBox.TabIndex = 1; + // + // LabelFIO + // + LabelFIO.AutoSize = true; + LabelFIO.Location = new Point(14, 20); + LabelFIO.Name = "LabelFIO"; + LabelFIO.Size = new Size(49, 20); + LabelFIO.TabIndex = 2; + LabelFIO.Text = "ФИО: "; + // + // LabelPassword + // + LabelPassword.AutoSize = true; + LabelPassword.Location = new Point(14, 69); + LabelPassword.Name = "LabelPassword"; + LabelPassword.Size = new Size(69, 20); + LabelPassword.TabIndex = 3; + LabelPassword.Text = "Пароль: "; + // + // QualificationNumericUpDown + // + QualificationNumericUpDown.Location = new Point(144, 175); + QualificationNumericUpDown.Margin = new Padding(3, 4, 3, 4); + QualificationNumericUpDown.Name = "QualificationNumericUpDown"; + QualificationNumericUpDown.Size = new Size(194, 27); + QualificationNumericUpDown.TabIndex = 4; + // + // WorkExpNumericUpDown + // + WorkExpNumericUpDown.Location = new Point(144, 123); + WorkExpNumericUpDown.Margin = new Padding(3, 4, 3, 4); + WorkExpNumericUpDown.Name = "WorkExpNumericUpDown"; + WorkExpNumericUpDown.Size = new Size(194, 27); + WorkExpNumericUpDown.TabIndex = 5; + // + // LabelWorkExperience + // + LabelWorkExperience.AutoSize = true; + LabelWorkExperience.Location = new Point(14, 123); + LabelWorkExperience.Name = "LabelWorkExperience"; + LabelWorkExperience.Size = new Size(109, 20); + LabelWorkExperience.TabIndex = 6; + LabelWorkExperience.Text = "Опыт работы: "; + // + // LabelQualification + // + LabelQualification.AutoSize = true; + LabelQualification.Location = new Point(14, 177); + LabelQualification.Name = "LabelQualification"; + LabelQualification.Size = new Size(118, 20); + LabelQualification.TabIndex = 7; + LabelQualification.Text = "Квалификация: "; + // + // ButtonCancel + // + ButtonCancel.Location = new Point(211, 225); + ButtonCancel.Margin = new Padding(3, 4, 3, 4); + ButtonCancel.Name = "ButtonCancel"; + ButtonCancel.Size = new Size(111, 39); + ButtonCancel.TabIndex = 8; + ButtonCancel.Text = "Отмена"; + ButtonCancel.UseVisualStyleBackColor = true; + ButtonCancel.Click += ButtonCancel_Click; + // + // ButtonSave + // + ButtonSave.Location = new Point(94, 225); + ButtonSave.Margin = new Padding(3, 4, 3, 4); + ButtonSave.Name = "ButtonSave"; + ButtonSave.Size = new Size(111, 39); + ButtonSave.TabIndex = 9; + ButtonSave.Text = "Сохранить"; + ButtonSave.UseVisualStyleBackColor = true; + ButtonSave.Click += ButtonSave_Click; + // + // FormImplementer + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(350, 285); + Controls.Add(ButtonSave); + Controls.Add(ButtonCancel); + Controls.Add(LabelQualification); + Controls.Add(LabelWorkExperience); + Controls.Add(WorkExpNumericUpDown); + Controls.Add(QualificationNumericUpDown); + Controls.Add(LabelPassword); + Controls.Add(LabelFIO); + Controls.Add(PasswordTextBox); + Controls.Add(FIOTextBox); + Margin = new Padding(3, 4, 3, 4); + Name = "FormImplementer"; + Text = "Исполнитель"; + Load += FormImplementer_Load; + ((System.ComponentModel.ISupportInitialize)QualificationNumericUpDown).EndInit(); + ((System.ComponentModel.ISupportInitialize)WorkExpNumericUpDown).EndInit(); + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private TextBox FIOTextBox; + private TextBox PasswordTextBox; + private Label LabelFIO; + private Label LabelPassword; + private NumericUpDown QualificationNumericUpDown; + private NumericUpDown WorkExpNumericUpDown; + private Label LabelWorkExperience; + private Label LabelQualification; + private Button ButtonCancel; + private Button ButtonSave; + + } +} \ No newline at end of file diff --git a/GiftShop/GiftShopView/FormImplementer.cs b/GiftShop/GiftShopView/FormImplementer.cs new file mode 100644 index 0000000..691ee52 --- /dev/null +++ b/GiftShop/GiftShopView/FormImplementer.cs @@ -0,0 +1,98 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.BusinessLogicsContracts; +using GiftShopContracts.SearchModels; +using Microsoft.Extensions.Logging; + +namespace GiftShopView +{ + public partial class FormImplementer : Form + { + private readonly ILogger _logger; + private readonly IImplementerLogic _logic; + private int? _id; + public int Id { set { _id = value; } } + + public FormImplementer(ILogger logger, IImplementerLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + private void ButtonSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(PasswordTextBox.Text)) + { + MessageBox.Show("Заполните пароль", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (string.IsNullOrEmpty(FIOTextBox.Text)) + { + MessageBox.Show("Заполните фио", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Сохранение исполнителя"); + try + { + var model = new ImplementerBindingModel + { + Id = _id ?? 0, + ImplementerFIO = FIOTextBox.Text, + Password = PasswordTextBox.Text, + Qualification = (int)QualificationNumericUpDown.Value, + WorkExperience = (int)WorkExpNumericUpDown.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, "Ошибка сохранения исполнителя"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ButtonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + + private void FormImplementer_Load(object sender, EventArgs e) + { + if (_id.HasValue) + { + try + { + _logger.LogInformation("Получение исполнителя"); + var view = _logic.ReadElement(new ImplementerSearchModel + { + Id = _id.Value + }); + if (view != null) + { + FIOTextBox.Text = view.ImplementerFIO; + PasswordTextBox.Text = view.Password; + QualificationNumericUpDown.Value = view.Qualification; + WorkExpNumericUpDown.Value = view.WorkExperience; + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения исполнителя"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } +} + diff --git a/GiftShop/GiftShopView/FormImplementer.resx b/GiftShop/GiftShopView/FormImplementer.resx new file mode 100644 index 0000000..f298a7b --- /dev/null +++ b/GiftShop/GiftShopView/FormImplementer.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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/GiftShop/GiftShopView/FormImplementers.Designer.cs b/GiftShop/GiftShopView/FormImplementers.Designer.cs new file mode 100644 index 0000000..8e55677 --- /dev/null +++ b/GiftShop/GiftShopView/FormImplementers.Designer.cs @@ -0,0 +1,121 @@ +namespace GiftShopView +{ + partial class FormImplementers + { + /// + /// 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(); + AddButton = new Button(); + ChangeButton = new Button(); + DeleteButton = new Button(); + UpdateButton = new Button(); + ((System.ComponentModel.ISupportInitialize)DataGridView).BeginInit(); + SuspendLayout(); + // + // DataGridView + // + DataGridView.BackgroundColor = SystemColors.ControlLightLight; + DataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + DataGridView.Location = new Point(1, 1); + DataGridView.Margin = new Padding(3, 4, 3, 4); + DataGridView.Name = "DataGridView"; + DataGridView.RowHeadersWidth = 51; + DataGridView.RowTemplate.Height = 25; + DataGridView.Size = new Size(543, 434); + DataGridView.TabIndex = 0; + // + // AddButton + // + AddButton.Location = new Point(566, 41); + AddButton.Margin = new Padding(3, 4, 3, 4); + AddButton.Name = "AddButton"; + AddButton.Size = new Size(112, 37); + AddButton.TabIndex = 1; + AddButton.Text = "Добавить"; + AddButton.UseVisualStyleBackColor = true; + AddButton.Click += AddButton_Click; + // + // ChangeButton + // + ChangeButton.Location = new Point(566, 102); + ChangeButton.Margin = new Padding(3, 4, 3, 4); + ChangeButton.Name = "ChangeButton"; + ChangeButton.Size = new Size(112, 35); + ChangeButton.TabIndex = 2; + ChangeButton.Text = "Изменить"; + ChangeButton.UseVisualStyleBackColor = true; + ChangeButton.Click += ChangeButton_Click; + // + // DeleteButton + // + DeleteButton.Location = new Point(566, 172); + DeleteButton.Margin = new Padding(3, 4, 3, 4); + DeleteButton.Name = "DeleteButton"; + DeleteButton.Size = new Size(112, 32); + DeleteButton.TabIndex = 3; + DeleteButton.Text = "Удалить"; + DeleteButton.UseVisualStyleBackColor = true; + DeleteButton.Click += DeleteButton_Click; + // + // UpdateButton + // + UpdateButton.Location = new Point(566, 232); + UpdateButton.Margin = new Padding(3, 4, 3, 4); + UpdateButton.Name = "UpdateButton"; + UpdateButton.Size = new Size(112, 31); + UpdateButton.TabIndex = 4; + UpdateButton.Text = "Обновить"; + UpdateButton.UseVisualStyleBackColor = true; + UpdateButton.Click += UpdateButton_Click; + // + // FormImplementers + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(690, 445); + Controls.Add(UpdateButton); + Controls.Add(DeleteButton); + Controls.Add(ChangeButton); + Controls.Add(AddButton); + Controls.Add(DataGridView); + Margin = new Padding(3, 4, 3, 4); + Name = "FormImplementers"; + Text = "Исполнители"; + Load += FormImplementers_Load; + ((System.ComponentModel.ISupportInitialize)DataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView DataGridView; + private Button AddButton; + private Button ChangeButton; + private Button DeleteButton; + private Button UpdateButton; + } +} \ No newline at end of file diff --git a/GiftShop/GiftShopView/FormImplementers.cs b/GiftShop/GiftShopView/FormImplementers.cs new file mode 100644 index 0000000..fc88be4 --- /dev/null +++ b/GiftShop/GiftShopView/FormImplementers.cs @@ -0,0 +1,111 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; + +namespace GiftShopView +{ + public partial class FormImplementers : Form + { + private readonly ILogger _logger; + private readonly IImplementerLogic _logic; + public FormImplementers(ILogger logger, IImplementerLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + private void AddButton_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormImplementer)); + + if (service is FormImplementer form) + { + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + + private void ChangeButton_Click(object sender, EventArgs e) + { + if (DataGridView.SelectedRows.Count == 1) + { + var service = Program.ServiceProvider?.GetService(typeof(FormImplementer)); + if (service is FormImplementer form) + { + form.Id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + } + + private void DeleteButton_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 ImplementerBindingModel + { + Id = id + })) + { + throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); + } + + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка удаления исполнителя"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } + + private void UpdateButton_Click(object sender, EventArgs e) + { + LoadData(); + } + + private void FormImplementers_Load(object sender, EventArgs e) + { + LoadData(); + } + + private void LoadData() + { + try + { + var list = _logic.ReadList(null); + + if (list != null) + { + DataGridView.DataSource = list; + DataGridView.Columns["Id"].Visible = false; + DataGridView.Columns["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + + _logger.LogInformation("Загрузка исполнителей"); + } + + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки исполнителей"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } +} diff --git a/GiftShop/GiftShopView/FormImplementers.resx b/GiftShop/GiftShopView/FormImplementers.resx new file mode 100644 index 0000000..f298a7b --- /dev/null +++ b/GiftShop/GiftShopView/FormImplementers.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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/GiftShop/GiftShopView/FormMain.Designer.cs b/GiftShop/GiftShopView/FormMain.Designer.cs index 868109f..ee34174 100644 --- a/GiftShop/GiftShopView/FormMain.Designer.cs +++ b/GiftShop/GiftShopView/FormMain.Designer.cs @@ -1,218 +1,210 @@ namespace GiftShopView { - 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 - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - menuStrip = new MenuStrip(); - справочникиToolStripMenuItem = new ToolStripMenuItem(); - компонентыToolStripMenuItem = new ToolStripMenuItem(); - изделияToolStripMenuItem = new ToolStripMenuItem(); - отчётыToolStripMenuItem = new ToolStripMenuItem(); - списокКомпонентовToolStripMenuItem = new ToolStripMenuItem(); - компонентыПоИзделиямToolStripMenuItem = new ToolStripMenuItem(); - списокЗаказовToolStripMenuItem = new ToolStripMenuItem(); - dataGridView = new DataGridView(); - buttonCreateOrder = new Button(); - buttonTakeOrderInWork = new Button(); - buttonOrderReady = new Button(); - buttonIssuedOrder = new Button(); - buttonRef = new Button(); - клиентыToolStripMenuItem = new ToolStripMenuItem(); - menuStrip.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); - SuspendLayout(); - // - // menuStrip - // - menuStrip.ImageScalingSize = new Size(20, 20); - menuStrip.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчётыToolStripMenuItem }); - menuStrip.Location = new Point(0, 0); - menuStrip.Name = "menuStrip"; - menuStrip.Size = new Size(1367, 28); - menuStrip.TabIndex = 0; - menuStrip.Text = "menuStrip1"; - // - // справочникиToolStripMenuItem - // - справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, изделияToolStripMenuItem, клиентыToolStripMenuItem }); - справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; - справочникиToolStripMenuItem.Size = new Size(117, 24); - справочникиToolStripMenuItem.Text = "Справочники"; - // - // компонентыToolStripMenuItem - // - компонентыToolStripMenuItem.Name = "компонентыToolStripMenuItem"; - компонентыToolStripMenuItem.Size = new Size(224, 26); - компонентыToolStripMenuItem.Text = "Компоненты"; - компонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click; - // - // изделияToolStripMenuItem - // - изделияToolStripMenuItem.Name = "изделияToolStripMenuItem"; - изделияToolStripMenuItem.Size = new Size(224, 26); - изделияToolStripMenuItem.Text = "Изделия"; - изделияToolStripMenuItem.Click += ИзделияToolStripMenuItem_Click; - // - // отчётыToolStripMenuItem - // - отчётыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокКомпонентовToolStripMenuItem, компонентыПоИзделиямToolStripMenuItem, списокЗаказовToolStripMenuItem }); - отчётыToolStripMenuItem.Name = "отчётыToolStripMenuItem"; - отчётыToolStripMenuItem.Size = new Size(73, 24); - отчётыToolStripMenuItem.Text = "Отчёты"; - // - // списокКомпонентовToolStripMenuItem - // - списокКомпонентовToolStripMenuItem.Name = "списокКомпонентовToolStripMenuItem"; - списокКомпонентовToolStripMenuItem.Size = new Size(276, 26); - списокКомпонентовToolStripMenuItem.Text = "Список компонентов"; - списокКомпонентовToolStripMenuItem.Click += ComponentsToolStripMenuItem_Click; - // - // компонентыПоИзделиямToolStripMenuItem - // - компонентыПоИзделиямToolStripMenuItem.Name = "компонентыПоИзделиямToolStripMenuItem"; - компонентыПоИзделиямToolStripMenuItem.Size = new Size(276, 26); - компонентыПоИзделиямToolStripMenuItem.Text = "Компоненты по изделиям"; - компонентыПоИзделиямToolStripMenuItem.Click += ComponentGiftsToolStripMenuItem_Click; - // - // списокЗаказовToolStripMenuItem - // - списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem"; - списокЗаказовToolStripMenuItem.Size = new Size(276, 26); - списокЗаказовToolStripMenuItem.Text = "Список заказов"; - списокЗаказовToolStripMenuItem.Click += OrdersToolStripMenuItem_Click; - // - // dataGridView - // - dataGridView.BackgroundColor = SystemColors.ControlLightLight; - dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; - dataGridView.Location = new Point(12, 41); - dataGridView.Name = "dataGridView"; - dataGridView.RowHeadersWidth = 51; - dataGridView.RowTemplate.Height = 29; - dataGridView.Size = new Size(1123, 423); - dataGridView.TabIndex = 1; - // - // buttonCreateOrder - // - buttonCreateOrder.Location = new Point(1155, 67); - buttonCreateOrder.Name = "buttonCreateOrder"; - buttonCreateOrder.Size = new Size(189, 41); - buttonCreateOrder.TabIndex = 2; - buttonCreateOrder.Text = "Создать заказ"; - buttonCreateOrder.UseVisualStyleBackColor = true; - buttonCreateOrder.Click += ButtonCreateOrder_Click; - // - // buttonTakeOrderInWork - // - buttonTakeOrderInWork.Location = new Point(1155, 136); - buttonTakeOrderInWork.Name = "buttonTakeOrderInWork"; - buttonTakeOrderInWork.Size = new Size(189, 41); - buttonTakeOrderInWork.TabIndex = 3; - buttonTakeOrderInWork.Text = "Отдать на выполнение"; - buttonTakeOrderInWork.UseVisualStyleBackColor = true; - buttonTakeOrderInWork.Click += ButtonTakeOrderInWork_Click; - // - // buttonOrderReady - // - buttonOrderReady.Location = new Point(1155, 211); - buttonOrderReady.Name = "buttonOrderReady"; - buttonOrderReady.Size = new Size(189, 41); - buttonOrderReady.TabIndex = 4; - buttonOrderReady.Text = "Заказ готов"; - buttonOrderReady.UseVisualStyleBackColor = true; - buttonOrderReady.Click += ButtonOrderReady_Click; - // - // buttonIssuedOrder - // - buttonIssuedOrder.Location = new Point(1155, 290); - buttonIssuedOrder.Name = "buttonIssuedOrder"; - buttonIssuedOrder.Size = new Size(189, 41); - buttonIssuedOrder.TabIndex = 5; - buttonIssuedOrder.Text = "Заказ выдан"; - buttonIssuedOrder.UseVisualStyleBackColor = true; - buttonIssuedOrder.Click += ButtonIssuedOrder_Click; - // - // buttonRef - // - buttonRef.Location = new Point(1155, 356); - buttonRef.Name = "buttonRef"; - buttonRef.Size = new Size(189, 41); - buttonRef.TabIndex = 6; - buttonRef.Text = "Обновить список"; - buttonRef.UseVisualStyleBackColor = true; - buttonRef.Click += ButtonRef_Click; - // - // клиентыToolStripMenuItem - // - клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; - клиентыToolStripMenuItem.Size = new Size(224, 26); - клиентыToolStripMenuItem.Text = "Клиенты"; - клиентыToolStripMenuItem.Click += new System.EventHandler(this.ClientsToolStripMenuItem_Click); - // - // FormMain - // - AutoScaleDimensions = new SizeF(8F, 20F); - AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1367, 471); - Controls.Add(buttonRef); - Controls.Add(buttonIssuedOrder); - Controls.Add(buttonOrderReady); - Controls.Add(buttonTakeOrderInWork); - Controls.Add(buttonCreateOrder); - Controls.Add(dataGridView); - Controls.Add(menuStrip); - MainMenuStrip = menuStrip; - Name = "FormMain"; - Text = "Магазин подарков"; - Load += FormMain_Load; - menuStrip.ResumeLayout(false); - menuStrip.PerformLayout(); - ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); - ResumeLayout(false); - PerformLayout(); - } + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + menuStrip = new MenuStrip(); + справочникиToolStripMenuItem = new ToolStripMenuItem(); + компонентыToolStripMenuItem = new ToolStripMenuItem(); + изделияToolStripMenuItem = new ToolStripMenuItem(); + клиентыToolStripMenuItem = new ToolStripMenuItem(); + исполнителиToolStripMenuItem = new ToolStripMenuItem(); + отчётыToolStripMenuItem = new ToolStripMenuItem(); + списокКомпонентовToolStripMenuItem = new ToolStripMenuItem(); + компонентыПоИзделиямToolStripMenuItem = new ToolStripMenuItem(); + списокЗаказовToolStripMenuItem = new ToolStripMenuItem(); + dataGridView = new DataGridView(); + buttonCreateOrder = new Button(); + buttonIssuedOrder = new Button(); + buttonRef = new Button(); + запускРаботToolStripMenuItem = new ToolStripMenuItem(); + menuStrip.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // menuStrip + // + menuStrip.ImageScalingSize = new Size(20, 20); + menuStrip.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчётыToolStripMenuItem, запускРаботToolStripMenuItem }); + menuStrip.Location = new Point(0, 0); + menuStrip.Name = "menuStrip"; + menuStrip.Size = new Size(1367, 28); + menuStrip.TabIndex = 0; + menuStrip.Text = "menuStrip1"; + // + // справочникиToolStripMenuItem + // + справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, изделияToolStripMenuItem, клиентыToolStripMenuItem, исполнителиToolStripMenuItem }); + справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; + справочникиToolStripMenuItem.Size = new Size(117, 24); + справочникиToolStripMenuItem.Text = "Справочники"; + // + // компонентыToolStripMenuItem + // + компонентыToolStripMenuItem.Name = "компонентыToolStripMenuItem"; + компонентыToolStripMenuItem.Size = new Size(185, 26); + компонентыToolStripMenuItem.Text = "Компоненты"; + компонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click; + // + // изделияToolStripMenuItem + // + изделияToolStripMenuItem.Name = "изделияToolStripMenuItem"; + изделияToolStripMenuItem.Size = new Size(185, 26); + изделияToolStripMenuItem.Text = "Изделия"; + изделияToolStripMenuItem.Click += ИзделияToolStripMenuItem_Click; + // + // клиентыToolStripMenuItem + // + клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; + клиентыToolStripMenuItem.Size = new Size(185, 26); + клиентыToolStripMenuItem.Text = "Клиенты"; + клиентыToolStripMenuItem.Click += ClientsToolStripMenuItem_Click; + // + // исполнителиToolStripMenuItem + // + исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; + исполнителиToolStripMenuItem.Size = new Size(185, 26); + исполнителиToolStripMenuItem.Text = "Исполнители"; + исполнителиToolStripMenuItem.Click += исполнителиToolStripMenuItem_Click; + // + // отчётыToolStripMenuItem + // + отчётыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокКомпонентовToolStripMenuItem, компонентыПоИзделиямToolStripMenuItem, списокЗаказовToolStripMenuItem }); + отчётыToolStripMenuItem.Name = "отчётыToolStripMenuItem"; + отчётыToolStripMenuItem.Size = new Size(73, 24); + отчётыToolStripMenuItem.Text = "Отчёты"; + // + // списокКомпонентовToolStripMenuItem + // + списокКомпонентовToolStripMenuItem.Name = "списокКомпонентовToolStripMenuItem"; + списокКомпонентовToolStripMenuItem.Size = new Size(276, 26); + списокКомпонентовToolStripMenuItem.Text = "Список компонентов"; + списокКомпонентовToolStripMenuItem.Click += ComponentsToolStripMenuItem_Click; + // + // компонентыПоИзделиямToolStripMenuItem + // + компонентыПоИзделиямToolStripMenuItem.Name = "компонентыПоИзделиямToolStripMenuItem"; + компонентыПоИзделиямToolStripMenuItem.Size = new Size(276, 26); + компонентыПоИзделиямToolStripMenuItem.Text = "Компоненты по изделиям"; + компонентыПоИзделиямToolStripMenuItem.Click += ComponentGiftsToolStripMenuItem_Click; + // + // списокЗаказовToolStripMenuItem + // + списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem"; + списокЗаказовToolStripMenuItem.Size = new Size(276, 26); + списокЗаказовToolStripMenuItem.Text = "Список заказов"; + списокЗаказовToolStripMenuItem.Click += OrdersToolStripMenuItem_Click; + // + // dataGridView + // + dataGridView.BackgroundColor = SystemColors.ControlLightLight; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(12, 41); + dataGridView.Name = "dataGridView"; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 29; + dataGridView.Size = new Size(1123, 423); + dataGridView.TabIndex = 1; + // + // buttonCreateOrder + // + buttonCreateOrder.Location = new Point(1155, 90); + buttonCreateOrder.Name = "buttonCreateOrder"; + buttonCreateOrder.Size = new Size(189, 57); + buttonCreateOrder.TabIndex = 2; + buttonCreateOrder.Text = "Создать заказ"; + buttonCreateOrder.UseVisualStyleBackColor = true; + buttonCreateOrder.Click += ButtonCreateOrder_Click; + // + // buttonIssuedOrder + // + buttonIssuedOrder.Location = new Point(1155, 228); + buttonIssuedOrder.Name = "buttonIssuedOrder"; + buttonIssuedOrder.Size = new Size(189, 57); + buttonIssuedOrder.TabIndex = 5; + buttonIssuedOrder.Text = "Заказ выдан"; + buttonIssuedOrder.UseVisualStyleBackColor = true; + buttonIssuedOrder.Click += ButtonIssuedOrder_Click; + // + // buttonRef + // + buttonRef.Location = new Point(1155, 356); + buttonRef.Name = "buttonRef"; + buttonRef.Size = new Size(189, 57); + buttonRef.TabIndex = 6; + buttonRef.Text = "Обновить список"; + buttonRef.UseVisualStyleBackColor = true; + buttonRef.Click += ButtonRef_Click; + // + // запускРаботToolStripMenuItem + // + запускРаботToolStripMenuItem.Name = "запускРаботToolStripMenuItem"; + запускРаботToolStripMenuItem.Size = new Size(114, 24); + запускРаботToolStripMenuItem.Text = "Запуск работ"; + запускРаботToolStripMenuItem.Click += запускРаботToolStripMenuItem_Click; + // + // FormMain + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(1367, 471); + Controls.Add(buttonRef); + Controls.Add(buttonIssuedOrder); + Controls.Add(buttonCreateOrder); + Controls.Add(dataGridView); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; + Name = "FormMain"; + Text = "Магазин подарков"; + Load += FormMain_Load; + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + PerformLayout(); + } - #endregion + #endregion - private MenuStrip menuStrip; - private ToolStripMenuItem справочникиToolStripMenuItem; - private ToolStripMenuItem компонентыToolStripMenuItem; - private ToolStripMenuItem изделияToolStripMenuItem; - private DataGridView dataGridView; - private Button buttonCreateOrder; - private Button buttonTakeOrderInWork; - private Button buttonOrderReady; - private Button buttonIssuedOrder; - private Button buttonRef; - private ToolStripMenuItem отчётыToolStripMenuItem; - private ToolStripMenuItem списокКомпонентовToolStripMenuItem; - private ToolStripMenuItem компонентыПоИзделиямToolStripMenuItem; - private ToolStripMenuItem списокЗаказовToolStripMenuItem; - private ToolStripMenuItem клиентыToolStripMenuItem; - } + private MenuStrip menuStrip; + private ToolStripMenuItem справочникиToolStripMenuItem; + private ToolStripMenuItem компонентыToolStripMenuItem; + private ToolStripMenuItem изделияToolStripMenuItem; + private DataGridView dataGridView; + private Button buttonCreateOrder; + private Button buttonIssuedOrder; + private Button buttonRef; + private ToolStripMenuItem отчётыToolStripMenuItem; + private ToolStripMenuItem списокКомпонентовToolStripMenuItem; + private ToolStripMenuItem компонентыПоИзделиямToolStripMenuItem; + private ToolStripMenuItem списокЗаказовToolStripMenuItem; + private ToolStripMenuItem клиентыToolStripMenuItem; + private ToolStripMenuItem исполнителиToolStripMenuItem; + private ToolStripMenuItem запускРаботToolStripMenuItem; + } } \ No newline at end of file diff --git a/GiftShop/GiftShopView/FormMain.cs b/GiftShop/GiftShopView/FormMain.cs index d4eaa61..afe2dd6 100644 --- a/GiftShop/GiftShopView/FormMain.cs +++ b/GiftShop/GiftShopView/FormMain.cs @@ -5,226 +5,177 @@ using Microsoft.Extensions.Logging; namespace GiftShopView { - public partial class FormMain : Form - { - private readonly ILogger _logger; + public partial class FormMain : Form + { + private readonly ILogger _logger; - private readonly IOrderLogic _orderLogic; + private readonly IOrderLogic _orderLogic; - private readonly IReportLogic _reportLogic; + private readonly IReportLogic _reportLogic; - public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic) - { - InitializeComponent(); - _logger = logger; - _orderLogic = orderLogic; - _reportLogic = reportLogic; - } + private readonly IWorkProcess _workProcess; - private void FormMain_Load(object sender, EventArgs e) - { - LoadData(); - } + public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess) + { + InitializeComponent(); + _logger = logger; + _orderLogic = orderLogic; + _reportLogic = reportLogic; + _workProcess = workProcess; + } - private void LoadData() - { - _logger.LogInformation("Загрузка заказов"); - try - { - var list = _orderLogic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["GiftId"].Visible = false; - dataGridView.Columns["GiftName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - dataGridView.Columns["ClientId"].Visible = false; - } - _logger.LogInformation("Загрузка заказов"); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки заказов"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } + private void FormMain_Load(object sender, EventArgs e) + { + LoadData(); + } - private void КомпонентыToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = - Program.ServiceProvider?.GetService(typeof(FormComponents)); - if (service is FormComponents form) - { - form.ShowDialog(); - } - } + private void LoadData() + { + _logger.LogInformation("Загрузка заказов"); + try + { + var list = _orderLogic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["GiftId"].Visible = false; + dataGridView.Columns["GiftName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["ImplementerId"].Visible = false; + } + _logger.LogInformation("Загрузка заказов"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки заказов"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } - private void ИзделияToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormGifts)); + private void КомпонентыToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormComponents)); + if (service is FormComponents form) + { + form.ShowDialog(); + } + } - if (service is FormGifts form) - { - form.ShowDialog(); - } - } + private void ИзделияToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormGifts)); + if (service is FormGifts form) + { + form.ShowDialog(); + } + } - private void ButtonCreateOrder_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); - if (service is FormCreateOrder form) - { - form.ShowDialog(); - LoadData(); - } - } + private void ButtonCreateOrder_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); + if (service is FormCreateOrder form) + { + form.ShowDialog(); + LoadData(); + } + } - private void ButtonTakeOrderInWork_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id); - try - { - var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel - { - Id = id, - GiftId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["GiftId"].Value), - ClientId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["ClientId"].Value), - GiftName = dataGridView.SelectedRows[0].Cells["GiftName"].Value.ToString(), - Status = Enum.Parse(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()), - Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value), - Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()), - DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()), - }); - if (!operationResult) - { - throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); - } - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка передачи заказа в работу"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, - MessageBoxIcon.Error); - } - } - } + private void ButtonIssuedOrder_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id); + try + { + var operationResult = _orderLogic.FinishOrder(new OrderBindingModel + { + Id = id, + GiftId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["GiftId"].Value), + ClientId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["ClientId"].Value), + GiftName = dataGridView.SelectedRows[0].Cells["GiftName"].Value.ToString(), + Status = Enum.Parse(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()), + Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value), + Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()), + DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()), + }); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + _logger.LogInformation("Заказ №{id} выдан", id); + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка отметки о выдачи заказа"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } - private void ButtonOrderReady_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'", id); - try - { - var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel - { - Id = id, - GiftId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["GiftId"].Value), - ClientId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["ClientId"].Value), - GiftName = dataGridView.SelectedRows[0].Cells["GiftName"].Value.ToString(), - Status = Enum.Parse(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()), - Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value), - Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()), - DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()), - }); - if (!operationResult) - { - throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); - } - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка отметки о готовности заказа"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } + private void ButtonRef_Click(object sender, EventArgs e) + { + LoadData(); + } - private void ButtonIssuedOrder_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id); - try - { - var operationResult = _orderLogic.FinishOrder(new OrderBindingModel - { - Id = id, - GiftId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["GiftId"].Value), - ClientId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["ClientId"].Value), - GiftName = dataGridView.SelectedRows[0].Cells["GiftName"].Value.ToString(), - Status = Enum.Parse(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()), - Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value), - Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()), - DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()), - }); - if (!operationResult) - { - throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); - } - _logger.LogInformation("Заказ №{id} выдан", id); - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка отметки о выдачи заказа"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } + private void ComponentsToolStripMenuItem_Click(object sender, EventArgs e) + { + using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; - private void ButtonRef_Click(object sender, EventArgs e) - { - LoadData(); - } + if (dialog.ShowDialog() == DialogResult.OK) + { + _reportLogic.SaveGiftsToWordFile(new ReportBindingModel + { + FileName = dialog.FileName + }); + MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } - private void ComponentsToolStripMenuItem_Click(object sender, EventArgs e) - { - using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; + private void ComponentGiftsToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReportGiftComponents)); - if (dialog.ShowDialog() == DialogResult.OK) - { - _reportLogic.SaveGiftsToWordFile(new ReportBindingModel - { - FileName = dialog.FileName - }); - MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); - } - } + if (service is FormReportGiftComponents form) + { + form.ShowDialog(); + } + } - private void ComponentGiftsToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormReportGiftComponents)); + private void OrdersToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders)); - if (service is FormReportGiftComponents form) - { - form.ShowDialog(); - } - } + if (service is FormReportOrders form) + { + form.ShowDialog(); + } + } - private void OrdersToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders)); + private void ClientsToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormClients)); + if (service is FormClients form) + { + form.ShowDialog(); + } + } - if (service is FormReportOrders form) - { - form.ShowDialog(); - } - } + private void исполнителиToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormImplementers)); + if (service is FormImplementers form) + { + form.ShowDialog(); + } + } - private void ClientsToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormClients)); - if (service is FormClients form) - { - form.ShowDialog(); - } - } - } + private void запускРаботToolStripMenuItem_Click(object sender, EventArgs e) + { + _workProcess.DoWork((Program.ServiceProvider? + .GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic); + MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } } diff --git a/GiftShop/GiftShopView/Program.cs b/GiftShop/GiftShopView/Program.cs index eef1a7f..361ffb7 100644 --- a/GiftShop/GiftShopView/Program.cs +++ b/GiftShop/GiftShopView/Program.cs @@ -35,14 +35,17 @@ namespace GiftShopView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); - services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); - services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -56,6 +59,8 @@ namespace GiftShopView services.AddTransient(); services.AddTransient(); services.AddTransient(); - } + services.AddTransient(); + services.AddTransient(); + } } } \ No newline at end of file