From e9c62b734ff7476dc083f93995f9530d21f0f716 Mon Sep 17 00:00:00 2001 From: Arkadiy Radaev Date: Wed, 15 May 2024 15:07:11 +0400 Subject: [PATCH 1/2] res 6 --- .../BusinessLogics/ImplementerLogic.cs | 125 ++++++ .../BusinessLogics/OrderLogic.cs | 72 +++- .../BusinessLogics/WorkModeling.cs | 138 +++++++ .../BindingModels/ImplementerBindingModel.cs | 17 + .../BindingModels/OrderBindingModel.cs | 2 + .../IImplementerLogic.cs | 19 + .../BusinessLogicsContracts/IOrderLogic.cs | 2 + .../BusinessLogicsContracts/IWorkProcess.cs | 10 + .../SearchModels/ImplementerSearchModel.cs | 11 + .../SearchModels/OrderSearchModel.cs | 8 +- .../StoragesContracts/IImplementerStorage.cs | 21 ++ .../ViewModels/ImplementerViewModel.cs | 22 ++ .../ViewModels/OrderViewModel.cs | 10 +- .../Models/IImplementerModel.cs | 13 + .../GiftShopDatabase.cs | 2 + .../Implements/ImplementerStorage.cs | 117 ++++++ .../Implements/OrderStorage.cs | 72 ++-- .../20240412193555_AddImplementer.Designer.cs | 257 +++++++++++++ .../20240412193555_AddImplementer.cs | 67 ++++ .../20240416084528_Orders.Designer.cs | 261 +++++++++++++ .../Migrations/20240416084528_Orders.cs | 22 ++ .../GiftShopDatabaseModelSnapshot.cs | 43 +++ .../Models/Implementer.cs | 65 ++++ .../GiftShopDatabaseImplement/Models/Order.cs | 22 +- .../DataFileSingleton.cs | 10 +- .../Implements/ImplementerStorage.cs | 103 +++++ .../Models/Implementer.cs | 81 ++++ .../GiftShopFileImplement/Models/Order.cs | 22 +- .../DataListSingleton.cs | 6 +- .../Implements/ImplementerStorage.cs | 126 +++++++ .../Models/Implementer.cs | 56 +++ .../GiftShopListImplement/Models/Order.cs | 15 +- .../Controllers/ImplementerController.cs | 103 +++++ GiftShop/GiftShopRestApi/Program.cs | 2 + .../GiftShopView/FormImplementer.Designer.cs | 174 +++++++++ GiftShop/GiftShopView/FormImplementer.cs | 98 +++++ GiftShop/GiftShopView/FormImplementer.resx | 60 +++ .../GiftShopView/FormImplementers.Designer.cs | 121 ++++++ GiftShop/GiftShopView/FormImplementers.cs | 111 ++++++ GiftShop/GiftShopView/FormImplementers.resx | 60 +++ GiftShop/GiftShopView/FormMain.Designer.cs | 168 ++++----- GiftShop/GiftShopView/FormMain.cs | 355 ++++++++---------- GiftShop/GiftShopView/FormMain.resx | 64 +++- GiftShop/GiftShopView/Program.cs | 7 +- 44 files changed, 2779 insertions(+), 361 deletions(-) create mode 100644 GiftShop/GiftShopBusinessLogic/BusinessLogics/ImplementerLogic.cs create mode 100644 GiftShop/GiftShopBusinessLogic/BusinessLogics/WorkModeling.cs create mode 100644 GiftShop/GiftShopContracts/BindingModels/ImplementerBindingModel.cs create mode 100644 GiftShop/GiftShopContracts/BusinessLogicsContracts/IImplementerLogic.cs create mode 100644 GiftShop/GiftShopContracts/BusinessLogicsContracts/IWorkProcess.cs create mode 100644 GiftShop/GiftShopContracts/SearchModels/ImplementerSearchModel.cs create mode 100644 GiftShop/GiftShopContracts/StoragesContracts/IImplementerStorage.cs create mode 100644 GiftShop/GiftShopContracts/ViewModels/ImplementerViewModel.cs create mode 100644 GiftShop/GiftShopDataModels/Models/IImplementerModel.cs create mode 100644 GiftShop/GiftShopDatabaseImplement/Implements/ImplementerStorage.cs create mode 100644 GiftShop/GiftShopDatabaseImplement/Migrations/20240412193555_AddImplementer.Designer.cs create mode 100644 GiftShop/GiftShopDatabaseImplement/Migrations/20240412193555_AddImplementer.cs create mode 100644 GiftShop/GiftShopDatabaseImplement/Migrations/20240416084528_Orders.Designer.cs create mode 100644 GiftShop/GiftShopDatabaseImplement/Migrations/20240416084528_Orders.cs create mode 100644 GiftShop/GiftShopDatabaseImplement/Models/Implementer.cs create mode 100644 GiftShop/GiftShopFileImplement/Implements/ImplementerStorage.cs create mode 100644 GiftShop/GiftShopFileImplement/Models/Implementer.cs create mode 100644 GiftShop/GiftShopListImplement/Implements/ImplementerStorage.cs create mode 100644 GiftShop/GiftShopListImplement/Models/Implementer.cs create mode 100644 GiftShop/GiftShopRestApi/Controllers/ImplementerController.cs create mode 100644 GiftShop/GiftShopView/FormImplementer.Designer.cs create mode 100644 GiftShop/GiftShopView/FormImplementer.cs create mode 100644 GiftShop/GiftShopView/FormImplementer.resx create mode 100644 GiftShop/GiftShopView/FormImplementers.Designer.cs create mode 100644 GiftShop/GiftShopView/FormImplementers.cs create mode 100644 GiftShop/GiftShopView/FormImplementers.resx 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..cd66ea2 100644 --- a/GiftShop/GiftShopBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/GiftShop/GiftShopBusinessLogic/BusinessLogics/OrderLogic.cs @@ -19,7 +19,10 @@ namespace GiftShopBusinessLogic.BusinessLogics _logger = logger; _orderStorage = orderStorage; } - + public bool TakeOrderInWork(OrderBindingModel model) + { + return StatusUpdate(model, OrderStatus.Выполняется); + } public bool CreateOrder(OrderBindingModel model) { CheckModel(model); @@ -44,36 +47,49 @@ 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)); + } - model.Status = newStatus; + if ((int)vmodel.Status + 1 != (int)newStatus) + { + throw new InvalidOperationException($"Попытка перевести заказ не в следующий статус: " + + $"Текущий статус: {vmodel.Status} \n" + + $"Планируемый статус: {newStatus} \n" + + $"Доступный статус: {(OrderStatus)((int)vmodel.Status + 1)}"); + } - if (model.Status == OrderStatus.Выдан) - model.DateImplement = DateTime.Now; + model.Status = newStatus; - if (_orderStorage.Update(model) == null) + model.DateCreate = vmodel.DateCreate; + + 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; } return true; } - - public bool TakeOrderInWork(OrderBindingModel model) - { - return StatusUpdate(model, OrderStatus.Выполняется); - } + public bool DeliveryOrder(OrderBindingModel model) { + model.DateImplement = DateTime.Now; return StatusUpdate(model, OrderStatus.Готов); } @@ -127,5 +143,29 @@ 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..39ed8cf 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..53fd40a 100644 --- a/GiftShop/GiftShopContracts/BusinessLogicsContracts/IOrderLogic.cs +++ b/GiftShop/GiftShopContracts/BusinessLogicsContracts/IOrderLogic.cs @@ -8,6 +8,8 @@ namespace GiftShopContracts.BusinessLogicsContracts { List? ReadList(OrderSearchModel? 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..4bf9269 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..2296592 100644 --- a/GiftShop/GiftShopContracts/ViewModels/OrderViewModel.cs +++ b/GiftShop/GiftShopContracts/ViewModels/OrderViewModel.cs @@ -6,17 +6,23 @@ namespace GiftShopContracts.ViewModels { public class OrderViewModel : IOrderModel { + [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("Клиент")] + [DisplayName("ФИО исполнителя")] + public string ImplementerFIO { get; set; } = string.Empty; + + [DisplayName("Клиент")] public string ClientFIO { get; set; } = string.Empty; [DisplayName("Количество")] 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 f7d0bf5..1b6aba0 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..a1eb350 100644 --- a/GiftShop/GiftShopDatabaseImplement/Implements/OrderStorage.cs +++ b/GiftShop/GiftShopDatabaseImplement/Implements/OrderStorage.cs @@ -29,47 +29,60 @@ 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) + .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 - .Include(x => x.Gift) - .Include(x => x.Client) - .Where(x => x.ClientId == model.ClientId) - .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.ClientId == model.ClientId) + .ToList() + .Select(x => x.GetViewModel) + .ToList(); + + return context.Orders + .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,7 +98,8 @@ namespace GiftShopDatabaseImplement.Implements return context.Orders .Include(x => x.Gift) .Include(x => x.Client) - .FirstOrDefault(x => x.Id == newOrder.Id) + .Include(x => x.Implementer) + .FirstOrDefault(x => x.Id == newOrder.Id) ?.GetViewModel; } @@ -93,8 +107,8 @@ 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); - if (order == null) + .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/20240412193555_AddImplementer.Designer.cs b/GiftShop/GiftShopDatabaseImplement/Migrations/20240412193555_AddImplementer.Designer.cs new file mode 100644 index 0000000..21e7094 --- /dev/null +++ b/GiftShop/GiftShopDatabaseImplement/Migrations/20240412193555_AddImplementer.Designer.cs @@ -0,0 +1,257 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using GiftShopDatabaseImplement; + +#nullable disable + +namespace GiftShopDatabaseImplement.Migrations +{ + [DbContext(typeof(GiftShopDatabase))] + [Migration("20240412193555_AddImplementer")] + partial class AddImplementer + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.3") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.Client", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientFIO") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Email") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Password") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Clients"); + }); + + modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.Component", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ComponentName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Cost") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.ToTable("Components"); + }); + + modelBuilder.Entity("SoftwareInstallationDatabaseImplement.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("SoftwareInstallationDatabaseImplement.Models.Order", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateImplement") + .HasColumnType("datetime2"); + + b.Property("ImplementerId") + .HasColumnType("int"); + + b.Property("PackageId") + .HasColumnType("int"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("Sum") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.HasIndex("ImplementerId"); + + b.HasIndex("PackageId"); + + b.ToTable("Orders"); + }); + + modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.Package", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("PackageName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Price") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.PackageComponent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ComponentId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("PackageId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ComponentId"); + + b.HasIndex("PackageId"); + + b.ToTable("PackageComponents"); + }); + + modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.Order", b => + { + b.HasOne("SoftwareInstallationDatabaseImplement.Models.Client", "Client") + .WithMany("Orders") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("SoftwareInstallationDatabaseImplement.Models.Implementer", "Implementer") + .WithMany("Orders") + .HasForeignKey("ImplementerId"); + + b.HasOne("SoftwareInstallationDatabaseImplement.Models.Package", "Package") + .WithMany("Orders") + .HasForeignKey("PackageId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Client"); + + b.Navigation("Implementer"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.PackageComponent", b => + { + b.HasOne("SoftwareInstallationDatabaseImplement.Models.Component", "Component") + .WithMany("PackageComponents") + .HasForeignKey("ComponentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("SoftwareInstallationDatabaseImplement.Models.Package", "Package") + .WithMany("Components") + .HasForeignKey("PackageId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Component"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.Client", b => + { + b.Navigation("Orders"); + }); + + modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.Component", b => + { + b.Navigation("PackageComponents"); + }); + + modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.Implementer", b => + { + b.Navigation("Orders"); + }); + + modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.Package", b => + { + b.Navigation("Components"); + + b.Navigation("Orders"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/GiftShop/GiftShopDatabaseImplement/Migrations/20240412193555_AddImplementer.cs b/GiftShop/GiftShopDatabaseImplement/Migrations/20240412193555_AddImplementer.cs new file mode 100644 index 0000000..eba8c32 --- /dev/null +++ b/GiftShop/GiftShopDatabaseImplement/Migrations/20240412193555_AddImplementer.cs @@ -0,0 +1,67 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace GiftShopDatabaseImplement.Migrations +{ + /// + public partial class AddImplementer : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "ImplementerId", + table: "Orders", + type: "int", + nullable: true); + + 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.CreateIndex( + name: "IX_Orders_ImplementerId", + table: "Orders", + column: "ImplementerId"); + + migrationBuilder.AddForeignKey( + name: "FK_Orders_Implementers_ImplementerId", + table: "Orders", + column: "ImplementerId", + principalTable: "Implementers", + principalColumn: "Id"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropForeignKey( + name: "FK_Orders_Implementers_ImplementerId", + table: "Orders"); + + migrationBuilder.DropTable( + name: "Implementers"); + + migrationBuilder.DropIndex( + name: "IX_Orders_ImplementerId", + table: "Orders"); + + migrationBuilder.DropColumn( + name: "ImplementerId", + table: "Orders"); + } + } +} diff --git a/GiftShop/GiftShopDatabaseImplement/Migrations/20240416084528_Orders.Designer.cs b/GiftShop/GiftShopDatabaseImplement/Migrations/20240416084528_Orders.Designer.cs new file mode 100644 index 0000000..4fbd56c --- /dev/null +++ b/GiftShop/GiftShopDatabaseImplement/Migrations/20240416084528_Orders.Designer.cs @@ -0,0 +1,261 @@ +// +using System; +using GiftShopDatabaseImplement; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace GiftShopDatabaseImplement.Migrations +{ + [DbContext(typeof(GiftShopDatabase))] + [Migration("20240416084528_Orders")] + partial class Orders + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.4") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("GiftShopDatabaseImplement.Models.Client", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientFIO") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Email") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Password") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Clients"); + }); + + modelBuilder.Entity("GiftShopDatabaseImplement.Models.Component", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ComponentName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Cost") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.ToTable("Components"); + }); + + modelBuilder.Entity("GiftShopDatabaseImplement.Models.Gift", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("GiftName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Price") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.ToTable("Gifts"); + }); + + modelBuilder.Entity("GiftShopDatabaseImplement.Models.GiftComponent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ComponentId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("GiftId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ComponentId"); + + b.HasIndex("GiftId"); + + 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") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateImplement") + .HasColumnType("datetime2"); + + b.Property("GiftId") + .HasColumnType("int"); + + b.Property("GiftName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ImplementerId") + .HasColumnType("int"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("Sum") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.HasIndex("GiftId"); + + b.HasIndex("ImplementerId"); + + b.ToTable("Orders"); + }); + + modelBuilder.Entity("GiftShopDatabaseImplement.Models.GiftComponent", b => + { + b.HasOne("GiftShopDatabaseImplement.Models.Component", "Component") + .WithMany("GiftComponents") + .HasForeignKey("ComponentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("GiftShopDatabaseImplement.Models.Gift", "Gift") + .WithMany("Components") + .HasForeignKey("GiftId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Component"); + + b.Navigation("Gift"); + }); + + modelBuilder.Entity("GiftShopDatabaseImplement.Models.Order", b => + { + b.HasOne("GiftShopDatabaseImplement.Models.Client", "Client") + .WithMany("Orders") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("GiftShopDatabaseImplement.Models.Gift", "Gift") + .WithMany("Orders") + .HasForeignKey("GiftId") + .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 => + { + b.Navigation("Orders"); + }); + + modelBuilder.Entity("GiftShopDatabaseImplement.Models.Component", b => + { + b.Navigation("GiftComponents"); + }); + + modelBuilder.Entity("GiftShopDatabaseImplement.Models.Gift", b => + { + b.Navigation("Components"); + + b.Navigation("Orders"); + }); + + modelBuilder.Entity("GiftShopDatabaseImplement.Models.Implementer", b => + { + b.Navigation("Orders"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/GiftShop/GiftShopDatabaseImplement/Migrations/20240416084528_Orders.cs b/GiftShop/GiftShopDatabaseImplement/Migrations/20240416084528_Orders.cs new file mode 100644 index 0000000..d28faa9 --- /dev/null +++ b/GiftShop/GiftShopDatabaseImplement/Migrations/20240416084528_Orders.cs @@ -0,0 +1,22 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace GiftShopDatabaseImplement.Migrations +{ + /// + public partial class Orders : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + + } + } +} 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..6fa903f 100644 --- a/GiftShop/GiftShopDatabaseImplement/Models/Order.cs +++ b/GiftShop/GiftShopDatabaseImplement/Models/Order.cs @@ -15,7 +15,9 @@ namespace GiftShopDatabaseImplement.Models [Required] public int ClientId { get; set; } - public string GiftName { get; private set; } = string.Empty; + public int? ImplementerId { get; private set; } + + public string GiftName { get; private set; } = string.Empty; [Required] public int Count { get; private set; } @@ -34,8 +36,9 @@ namespace GiftShopDatabaseImplement.Models public virtual Gift Gift { get; set; } public Client Client { get; set; } + public Implementer? Implementer { get; set; } - public static Order? Create(OrderBindingModel? model) + public static Order? Create(OrderBindingModel? model) { if (model == null) { @@ -47,6 +50,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, @@ -63,13 +67,9 @@ namespace GiftShopDatabaseImplement.Models return; } - GiftId = model.GiftId; - GiftName = model.GiftName; - Count = model.Count; - Sum = model.Sum; Status = model.Status; - DateCreate = model.DateCreate; DateImplement = model.DateImplement; + ImplementerId = model.ImplementerId; } public OrderViewModel GetViewModel @@ -82,14 +82,16 @@ namespace GiftShopDatabaseImplement.Models Id = Id, GiftId = GiftId, ClientId = ClientId, - ClientFIO = context.Clients.FirstOrDefault(x => x.Id == ClientId)?.ClientFIO ?? string.Empty, + 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..f8331fb 100644 --- a/GiftShop/GiftShopFileImplement/DataFileSingleton.cs +++ b/GiftShop/GiftShopFileImplement/DataFileSingleton.cs @@ -9,6 +9,8 @@ namespace GiftShopFileImplement private readonly string ComponentFileName = "Component.xml"; + private readonly string ImplementerFileName = "Implementer.xml"; + private readonly string OrderFileName = "Order.xml"; private readonly string GiftFileName = "Gift.xml"; @@ -23,7 +25,9 @@ namespace GiftShopFileImplement public List Clients { get; private set; } - public static DataFileSingleton GetInstance() + public List Implementers { get; private set; } + + public static DataFileSingleton GetInstance() { if (instance == null) { @@ -40,11 +44,13 @@ namespace GiftShopFileImplement public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", x => x.GetXElement); - private DataFileSingleton() + 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..ccf3083 100644 --- a/GiftShop/GiftShopFileImplement/Models/Order.cs +++ b/GiftShop/GiftShopFileImplement/Models/Order.cs @@ -10,6 +10,12 @@ namespace GiftShopFileImplement.Models { public int GiftId { 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,7 +38,10 @@ namespace GiftShopFileImplement.Models { Id = model.Id, GiftId = model.GiftId, + GiftName = model.GiftName, Count = model.Count, + ClientId = model.ClientId, + ImplementerId = model.ImplementerId, Sum = model.Sum, Status = model.Status, DateCreate = model.DateCreate, @@ -50,8 +59,11 @@ namespace GiftShopFileImplement.Models { 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) }; @@ -68,11 +80,7 @@ namespace GiftShopFileImplement.Models { return; } - GiftId = model.GiftId; - Count = model.Count; - Sum = model.Sum; Status = model.Status; - DateCreate = model.DateCreate; DateImplement = model.DateImplement; } @@ -80,6 +88,9 @@ namespace GiftShopFileImplement.Models { Id = Id, GiftId = GiftId, + ClientId = ClientId, + ImplementerId = ImplementerId, + GiftName = GiftName, Count = Count, Sum = Sum, Status = Status, @@ -89,7 +100,10 @@ namespace GiftShopFileImplement.Models public XElement GetXElement => new("Order", 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()), diff --git a/GiftShop/GiftShopListImplement/DataListSingleton.cs b/GiftShop/GiftShopListImplement/DataListSingleton.cs index 4cd0e49..3becc52 100644 --- a/GiftShop/GiftShopListImplement/DataListSingleton.cs +++ b/GiftShop/GiftShopListImplement/DataListSingleton.cs @@ -9,12 +9,14 @@ namespace GiftShopListImplement public List Orders { get; set; } public List Gifts { get; set; } public List Clients { get; set; } - - private DataListSingleton() + 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() { 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..3873fc7 100644 --- a/GiftShop/GiftShopListImplement/Models/Order.cs +++ b/GiftShop/GiftShopListImplement/Models/Order.cs @@ -8,11 +8,15 @@ namespace GiftShopListImplement.Models internal class Order : IOrderModel { public int GiftId { get; private set; } - public string GiftName { get; private set; } + public int ClientId { get; private set; } + public int Count { get; private set; } + public int? ImplementerId { get; private set; } + + public double Sum { get; private set; } public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен; @@ -38,7 +42,9 @@ namespace GiftShopListImplement.Models Sum = model.Sum, Status = model.Status, DateCreate = model.DateCreate, - DateImplement = model.DateImplement + DateImplement = model.DateImplement, + ImplementerId = model.ImplementerId, + ClientId = model.ClientId, }; } @@ -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..273bc6d 100644 --- a/GiftShop/GiftShopView/FormMain.Designer.cs +++ b/GiftShop/GiftShopView/FormMain.Designer.cs @@ -1,24 +1,24 @@ 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 @@ -32,17 +32,17 @@ справочники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(); + запускРабот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(); @@ -50,108 +50,113 @@ // menuStrip // menuStrip.ImageScalingSize = new Size(20, 20); - menuStrip.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчётыToolStripMenuItem }); + menuStrip.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчётыToolStripMenuItem, запускРаботToolStripMenuItem }); menuStrip.Location = new Point(0, 0); menuStrip.Name = "menuStrip"; - menuStrip.Size = new Size(1367, 28); + menuStrip.Padding = new Padding(8, 2, 0, 2); + menuStrip.Size = new Size(1709, 33); menuStrip.TabIndex = 0; menuStrip.Text = "menuStrip1"; // // справочникиToolStripMenuItem // - справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, изделияToolStripMenuItem, клиентыToolStripMenuItem }); + справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, изделияToolStripMenuItem, клиентыToolStripMenuItem, исполнителиToolStripMenuItem }); справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; - справочникиToolStripMenuItem.Size = new Size(117, 24); + справочникиToolStripMenuItem.Size = new Size(139, 29); справочникиToolStripMenuItem.Text = "Справочники"; // // компонентыToolStripMenuItem // компонентыToolStripMenuItem.Name = "компонентыToolStripMenuItem"; - компонентыToolStripMenuItem.Size = new Size(224, 26); + компонентыToolStripMenuItem.Size = new Size(220, 34); компонентыToolStripMenuItem.Text = "Компоненты"; компонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click; // // изделияToolStripMenuItem // изделияToolStripMenuItem.Name = "изделияToolStripMenuItem"; - изделияToolStripMenuItem.Size = new Size(224, 26); + изделияToolStripMenuItem.Size = new Size(220, 34); изделияToolStripMenuItem.Text = "Изделия"; изделияToolStripMenuItem.Click += ИзделияToolStripMenuItem_Click; // + // клиентыToolStripMenuItem + // + клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; + клиентыToolStripMenuItem.Size = new Size(220, 34); + клиентыToolStripMenuItem.Text = "Клиенты"; + клиентыToolStripMenuItem.Click += ClientsToolStripMenuItem_Click; + // + // исполнителиToolStripMenuItem + // + исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; + исполнителиToolStripMenuItem.Size = new Size(220, 34); + исполнители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.Size = new Size(88, 29); отчётыToolStripMenuItem.Text = "Отчёты"; // // списокКомпонентовToolStripMenuItem // списокКомпонентовToolStripMenuItem.Name = "списокКомпонентовToolStripMenuItem"; - списокКомпонентовToolStripMenuItem.Size = new Size(276, 26); + списокКомпонентовToolStripMenuItem.Size = new Size(327, 34); списокКомпонентовToolStripMenuItem.Text = "Список компонентов"; списокКомпонентовToolStripMenuItem.Click += ComponentsToolStripMenuItem_Click; // // компонентыПоИзделиямToolStripMenuItem // компонентыПоИзделиямToolStripMenuItem.Name = "компонентыПоИзделиямToolStripMenuItem"; - компонентыПоИзделиямToolStripMenuItem.Size = new Size(276, 26); + компонентыПоИзделиямToolStripMenuItem.Size = new Size(327, 34); компонентыПоИзделиямToolStripMenuItem.Text = "Компоненты по изделиям"; компонентыПоИзделиямToolStripMenuItem.Click += ComponentGiftsToolStripMenuItem_Click; // // списокЗаказовToolStripMenuItem // списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem"; - списокЗаказовToolStripMenuItem.Size = new Size(276, 26); + списокЗаказовToolStripMenuItem.Size = new Size(327, 34); списокЗаказовToolStripMenuItem.Text = "Список заказов"; списокЗаказовToolStripMenuItem.Click += OrdersToolStripMenuItem_Click; // + // запускРаботToolStripMenuItem + // + запускРаботToolStripMenuItem.Name = "запускРаботToolStripMenuItem"; + запускРаботToolStripMenuItem.Size = new Size(136, 29); + запускРаботToolStripMenuItem.Text = "Запуск работ"; + запускРаботToolStripMenuItem.Click += запускРаботToolStripMenuItem_Click; + // // dataGridView // dataGridView.BackgroundColor = SystemColors.ControlLightLight; dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; - dataGridView.Location = new Point(12, 41); + dataGridView.Location = new Point(15, 51); + dataGridView.Margin = new Padding(4, 4, 4, 4); dataGridView.Name = "dataGridView"; dataGridView.RowHeadersWidth = 51; dataGridView.RowTemplate.Height = 29; - dataGridView.Size = new Size(1123, 423); + dataGridView.Size = new Size(1404, 529); dataGridView.TabIndex = 1; // // buttonCreateOrder // - buttonCreateOrder.Location = new Point(1155, 67); + buttonCreateOrder.Location = new Point(1444, 112); + buttonCreateOrder.Margin = new Padding(4, 4, 4, 4); buttonCreateOrder.Name = "buttonCreateOrder"; - buttonCreateOrder.Size = new Size(189, 41); + buttonCreateOrder.Size = new Size(236, 71); 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.Location = new Point(1444, 285); + buttonIssuedOrder.Margin = new Padding(4, 4, 4, 4); buttonIssuedOrder.Name = "buttonIssuedOrder"; - buttonIssuedOrder.Size = new Size(189, 41); + buttonIssuedOrder.Size = new Size(236, 71); buttonIssuedOrder.TabIndex = 5; buttonIssuedOrder.Text = "Заказ выдан"; buttonIssuedOrder.UseVisualStyleBackColor = true; @@ -159,34 +164,27 @@ // // buttonRef // - buttonRef.Location = new Point(1155, 356); + buttonRef.Location = new Point(1444, 445); + buttonRef.Margin = new Padding(4, 4, 4, 4); buttonRef.Name = "buttonRef"; - buttonRef.Size = new Size(189, 41); + buttonRef.Size = new Size(236, 71); 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); + AutoScaleDimensions = new SizeF(10F, 25F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1367, 471); + ClientSize = new Size(1709, 589); Controls.Add(buttonRef); Controls.Add(buttonIssuedOrder); - Controls.Add(buttonOrderReady); - Controls.Add(buttonTakeOrderInWork); Controls.Add(buttonCreateOrder); Controls.Add(dataGridView); Controls.Add(menuStrip); MainMenuStrip = menuStrip; + Margin = new Padding(4, 4, 4, 4); Name = "FormMain"; Text = "Магазин подарков"; Load += FormMain_Load; @@ -200,19 +198,19 @@ #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 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/FormMain.resx b/GiftShop/GiftShopView/FormMain.resx index 1263609..3ef7151 100644 --- a/GiftShop/GiftShopView/FormMain.resx +++ b/GiftShop/GiftShopView/FormMain.resx @@ -1,4 +1,64 @@ - + + + @@ -61,6 +121,6 @@ 17, 17 - 26 + 137 \ No newline at end of file diff --git a/GiftShop/GiftShopView/Program.cs b/GiftShop/GiftShopView/Program.cs index eef1a7f..e0e9df3 100644 --- a/GiftShop/GiftShopView/Program.cs +++ b/GiftShop/GiftShopView/Program.cs @@ -35,13 +35,14 @@ 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(); @@ -56,6 +57,8 @@ namespace GiftShopView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); } } } \ No newline at end of file -- 2.25.1 From 0e574729f3c5426db18132c7a6c82a3607ae45a1 Mon Sep 17 00:00:00 2001 From: Arkadiy Radaev Date: Wed, 15 May 2024 15:49:43 +0400 Subject: [PATCH 2/2] fix --- .../Implements/OrderStorage.cs | 66 +++++----------- .../GiftShopDatabaseImplement/Models/Order.cs | 22 +++--- .../Implements/OrderStorage.cs | 52 ++++++++----- .../Implements/OrderStorage.cs | 76 ++++++++++--------- 4 files changed, 109 insertions(+), 107 deletions(-) diff --git a/GiftShop/GiftShopDatabaseImplement/Implements/OrderStorage.cs b/GiftShop/GiftShopDatabaseImplement/Implements/OrderStorage.cs index a1eb350..ef43ea9 100644 --- a/GiftShop/GiftShopDatabaseImplement/Implements/OrderStorage.cs +++ b/GiftShop/GiftShopDatabaseImplement/Implements/OrderStorage.cs @@ -24,21 +24,11 @@ namespace GiftShopDatabaseImplement.Implements public OrderViewModel? GetElement(OrderSearchModel model) { - if (!model.Id.HasValue) - { - return null; - } - using var context = new GiftShopDatabase(); - 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; - } + using var context = new GiftShopDatabase(); + return context.Orders.Include(x => x.Gift).Include(x => x.Client).Include(x => x.Implementer).FirstOrDefault( + x => ((model.Id.HasValue && x.Id == model.Id) || + (x.ImplementerId == model.ImplementerId && x.Status == model.Status)))?.GetViewModel; + } public List GetFilteredList(OrderSearchModel model) { @@ -47,35 +37,19 @@ namespace GiftShopDatabaseImplement.Implements return new(); } using var context = new GiftShopDatabase(); - if (model.DateTo != null && model.DateFrom != null && model.ClientId.HasValue) - { - return context.Orders - .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 - .Where(x => x.Status == model.Status) - .ToList() - .Select(x => x.GetViewModel) - .ToList(); - } + return context.Orders + .Include(x => x.Gift) + .Include(x => x.Client).Include(x => x.Implementer).Where(x => ( + (!model.Id.HasValue || x.Id == model.Id) && + (!model.DateFrom.HasValue || x.DateCreate >= model.DateFrom) && + (!model.DateTo.HasValue || x.DateCreate <= model.DateTo) + && + (!model.ClientId.HasValue || x.ClientId == model.ClientId) + ) + ) + .Select(x => x.GetViewModel) + .ToList(); + } public List GetFullList() { @@ -86,12 +60,12 @@ namespace GiftShopDatabaseImplement.Implements public OrderViewModel? Insert(OrderBindingModel model) { - var newOrder = Order.Create(model); + using var context = new GiftShopDatabase(); + var newOrder = Order.Create(model, context); if (newOrder == null) { return null; } - using var context = new GiftShopDatabase(); context.Orders.Add(newOrder); context.SaveChanges(); diff --git a/GiftShop/GiftShopDatabaseImplement/Models/Order.cs b/GiftShop/GiftShopDatabaseImplement/Models/Order.cs index 6fa903f..f49004e 100644 --- a/GiftShop/GiftShopDatabaseImplement/Models/Order.cs +++ b/GiftShop/GiftShopDatabaseImplement/Models/Order.cs @@ -38,7 +38,7 @@ namespace GiftShopDatabaseImplement.Models public Client Client { get; set; } public Implementer? Implementer { get; set; } - public static Order? Create(OrderBindingModel? model) + public static Order? Create(OrderBindingModel? model, GiftShopDatabase context) { if (model == null) { @@ -49,15 +49,19 @@ namespace GiftShopDatabaseImplement.Models { Id = model.Id, GiftId = model.GiftId, - ClientId = model.ClientId, - ImplementerId = model.ImplementerId, GiftName = model.GiftName, Count = model.Count, Sum = model.Sum, Status = model.Status, DateCreate = model.DateCreate, - DateImplement = model.DateImplement - }; + DateImplement = model.DateImplement, + Gift = context.Gifts.FirstOrDefault(x => x.Id == model.GiftId), + ClientId = model.ClientId, + Client = context.Clients.FirstOrDefault(x => x.Id == model.ClientId), + ImplementerId = model.ImplementerId, + Implementer = (model.ImplementerId.HasValue ? context.Implementers.FirstOrDefault(x => x.Id == model.ImplementerId) + : null), + }; } public void Update(OrderBindingModel? model) @@ -83,15 +87,15 @@ namespace GiftShopDatabaseImplement.Models 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, + ClientFIO = Client.ClientFIO, + GiftName = Gift.GiftName, Count = Count, Sum = Sum, Status = Status, DateCreate = DateCreate, DateImplement = DateImplement, - ImplementerFIO = Implementer?.ImplementerFIO ?? string.Empty - }; + ImplementerFIO = (Implementer != null ? Implementer.ImplementerFIO : string.Empty) + }; } } } diff --git a/GiftShop/GiftShopFileImplement/Implements/OrderStorage.cs b/GiftShop/GiftShopFileImplement/Implements/OrderStorage.cs index c11cad2..801eb93 100644 --- a/GiftShop/GiftShopFileImplement/Implements/OrderStorage.cs +++ b/GiftShop/GiftShopFileImplement/Implements/OrderStorage.cs @@ -24,7 +24,7 @@ namespace GiftShopFileImplement.Implements source.Orders.Remove(element); source.SaveOrders(); - return element.GetViewModel; + return AccessStorage(element.GetViewModel); } return null; @@ -37,27 +37,30 @@ namespace GiftShopFileImplement.Implements return null; } - return source.Orders.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; - } + return AccessStorage(source.Orders + .FirstOrDefault(x => ((model.Id.HasValue && x.Id == model.Id) || + (model.ImplementerId.HasValue && + x.ImplementerId == model.ImplementerId && x.Status == model.Status)))?.GetViewModel); + } public List GetFilteredList(OrderSearchModel model) { - if (!model.Id.HasValue) - { - return source.Orders - .Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo) - .Select(x => x.GetViewModel) - .ToList(); - } return source.Orders - .Where(x => x.Id == model.Id) - .Select(x => x.GetViewModel) - .ToList(); + .Where(x => ( + (!model.Id.HasValue || x.Id == model.Id) && + (!model.DateFrom.HasValue || x.DateCreate >= model.DateFrom) && + (!model.DateTo.HasValue || x.DateCreate <= model.DateTo) + && + (!model.ClientId.HasValue || x.ClientId == model.ClientId) + ) + ) + .Select(x => AccessStorage(x.GetViewModel)) + .ToList(); } public List GetFullList() { - return source.Orders.Select(x => x.GetViewModel).ToList(); + return source.Orders.Select(x => AccessStorage(x.GetViewModel)).ToList(); } public OrderViewModel? Insert(OrderBindingModel model) @@ -73,7 +76,7 @@ namespace GiftShopFileImplement.Implements source.Orders.Add(newOrder); source.SaveOrders(); - return newOrder.GetViewModel; + return AccessStorage(newOrder.GetViewModel); } public OrderViewModel? Update(OrderBindingModel model) @@ -88,7 +91,22 @@ namespace GiftShopFileImplement.Implements order.Update(model); source.SaveOrders(); - return order.GetViewModel; + return AccessStorage(order.GetViewModel); } - } + public OrderViewModel AccessStorage(OrderViewModel model) + { + if (model == null) + return null; + var gift = source.Gifts.FirstOrDefault(x => x.Id == model.Id); + var client = source.Clients.FirstOrDefault(x => x.Id == model.Id); + var implementer = source.Implementers.FirstOrDefault(x => x.Id == model.ImplementerId); + if (gift != null) + model.GiftName = gift.GiftName; + if (client != null) + model.ClientFIO = client.ClientFIO; + if (implementer != null) + model.ImplementerFIO = implementer.ImplementerFIO; + return model; + } + } } diff --git a/GiftShop/GiftShopListImplement/Implements/OrderStorage.cs b/GiftShop/GiftShopListImplement/Implements/OrderStorage.cs index 5d2cb04..679c4a0 100644 --- a/GiftShop/GiftShopListImplement/Implements/OrderStorage.cs +++ b/GiftShop/GiftShopListImplement/Implements/OrderStorage.cs @@ -30,46 +30,37 @@ namespace GiftShopListImplement.Implements public OrderViewModel? GetElement(OrderSearchModel model) { - if (!model.Id.HasValue) - { - return null; - } - - foreach (var order in _source.Orders) - { - if (model.Id.HasValue && order.Id == model.Id) - { - return order.GetViewModel; - } - } - - return null; - } + if (!model.Id.HasValue) + { + return null; + } + foreach (var order in _source.Orders) + { + if ((model.Id.HasValue && order.Id == model.Id) || + (model.ImplementerId.HasValue && + order.ImplementerId == model.ImplementerId && order.Status == model.Status)) + { + return AccessStorage(order.GetViewModel); + } + } + return null; + } public List GetFilteredList(OrderSearchModel model) { - List list = new(); - if (!model.Id.HasValue || model.Id == 0) + var result = new List(); + foreach (var order in _source.Orders) { - foreach (Order order in _source.Orders) + if ((!model.Id.HasValue || order.Id == model.Id) && + (!model.DateFrom.HasValue || order.DateCreate >= model.DateFrom) && + (!model.DateTo.HasValue || order.DateCreate <= model.DateTo) + && + (!model.ClientId.HasValue || order.ClientId == model.ClientId)) { - if (order.DateCreate >= model.DateFrom && order.DateCreate <= model.DateTo) - { - list.Add(order.GetViewModel); - } + result.Add(AccessStorage(order.GetViewModel)); } } - else - { - foreach (Order order in _source.Orders) - { - if (order.Id == model.Id) - { - list.Add(order.GetViewModel); - } - } - } - return list; + return result; } public List GetFullList() @@ -77,7 +68,7 @@ namespace GiftShopListImplement.Implements List list = new(); foreach (Order order in _source.Orders) { - list.Add(order.GetViewModel); + list.Add(AccessStorage(order.GetViewModel)); } return list; } @@ -113,5 +104,20 @@ namespace GiftShopListImplement.Implements } return null; } - } + public OrderViewModel AccessStorage(OrderViewModel model) + { + if (model == null) + return null; + var gift = _source.Gifts.FirstOrDefault(x => x.Id == model.Id); + var client = _source.Clients.FirstOrDefault(x => x.Id == model.Id); + var implementer = _source.Implementers.FirstOrDefault(x => x.Id == model.ImplementerId); + if (gift != null) + model.GiftName = gift.GiftName; + if (client != null) + model.ClientFIO = client.ClientFIO; + if (implementer != null) + model.ImplementerFIO = implementer.ImplementerFIO; + return model; + } + } } -- 2.25.1