From bb8974a2f6e6c151dfc19185e63952e1b9ff6167 Mon Sep 17 00:00:00 2001 From: revengel66 Date: Fri, 21 Jun 2024 14:39:07 +0400 Subject: [PATCH 01/16] lab 6 in process --- Pizzeria/Pizzeria/Program.cs | 4 +++ .../BusinessLogic/OrderLogic.cs | 32 +++++++++++++++++-- .../BindingModels/OrderBindingModel.cs | 1 + .../BusinessLogicsContracts/IOrderLogic.cs | 1 + .../SearchModels/OrderSearchModel.cs | 6 +++- .../ViewModels/OrderViewModel.cs | 4 +++ .../PizzeriaDataModels/Models/IOrderModel.cs | 1 + .../Implements/OrderStorage.cs | 7 +++- .../PizzeriaDatabaseImplement/Models/Order.cs | 11 ++++++- Pizzeria/PizzeriaRestApi/Program.cs | 2 ++ 10 files changed, 64 insertions(+), 5 deletions(-) diff --git a/Pizzeria/Pizzeria/Program.cs b/Pizzeria/Pizzeria/Program.cs index d447ad0..e788c1d 100644 --- a/Pizzeria/Pizzeria/Program.cs +++ b/Pizzeria/Pizzeria/Program.cs @@ -39,12 +39,14 @@ namespace Pizzeria services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -60,6 +62,8 @@ namespace Pizzeria services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); } } } \ No newline at end of file diff --git a/Pizzeria/PizzeriaBusinessLogic/BusinessLogic/OrderLogic.cs b/Pizzeria/PizzeriaBusinessLogic/BusinessLogic/OrderLogic.cs index c9fa888..f9408de 100644 --- a/Pizzeria/PizzeriaBusinessLogic/BusinessLogic/OrderLogic.cs +++ b/Pizzeria/PizzeriaBusinessLogic/BusinessLogic/OrderLogic.cs @@ -38,11 +38,31 @@ namespace PizzeriaBusinessLogic.BusinessLogic } return true; } - + + public OrderViewModel? ReadElement(OrderSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + _logger.LogInformation("ReadElement. ClientId:{ClientId}.Status:{Status}.ImplementerId:{ImplementerId}.DateFrom:{DateFrom}.DateTo:{DateTo}OrderId:{Id}", + model.ClientId, model.Status, model.ImplementerId, model.DateFrom, model.DateTo, 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; + } + + public List? ReadList(OrderSearchModel? model) { - _logger.LogInformation("ReadList. OrderId: {Id}.", model?.Id); + _logger.LogInformation("ReadList. ClientId:{ClientId}.Status:{Status}.ImplementerId:{ImplementerId}.DateFrom:{DateFrom}.DateTo:{DateTo}OrderId:{Id}", + model?.ClientId, model?.Status, model?.ImplementerId, model?.DateFrom, model?.DateTo, model?.Id); var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model); if (list == null) { @@ -92,6 +112,10 @@ namespace PizzeriaBusinessLogic.BusinessLogic } model.Status = status; + if (order.ImplementerId.HasValue) + { + model.ImplementerId = order.ImplementerId; + } if (model.Status == OrderStatus.Готов) { model.DateImplement = DateTime.Now; @@ -132,6 +156,10 @@ namespace PizzeriaBusinessLogic.BusinessLogic { throw new ArgumentNullException("Стоимость заказа должна быть больше 0", nameof(model.Sum)); } + if (model.DateImplement.HasValue && model.DateImplement < model.DateCreate) + { + throw new ArithmeticException($"Дата выдачи заказа {model.DateImplement} не может быть раньше даты его создания {model.DateCreate}"); + } _logger.LogInformation("Order. Id: {Id}. Sum: {Sum}. PizzaId: {PizzaId}. PizzaCount: {Count}", model.Id, model.Sum, model.PizzaId, model.Count); } } diff --git a/Pizzeria/PizzeriaContracts/BindingModels/OrderBindingModel.cs b/Pizzeria/PizzeriaContracts/BindingModels/OrderBindingModel.cs index 88d6a4a..0379065 100644 --- a/Pizzeria/PizzeriaContracts/BindingModels/OrderBindingModel.cs +++ b/Pizzeria/PizzeriaContracts/BindingModels/OrderBindingModel.cs @@ -9,6 +9,7 @@ namespace PizzeriaContracts.BindingModels public int Id { get; set; } public int PizzaId { get; set; } public int ClientId { get; set; } + public int? ImplementerId { get; set; } public int Count { get; set; } public double Sum { get; set; } public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; diff --git a/Pizzeria/PizzeriaContracts/BusinessLogicsContracts/IOrderLogic.cs b/Pizzeria/PizzeriaContracts/BusinessLogicsContracts/IOrderLogic.cs index a2507e3..ce429f4 100644 --- a/Pizzeria/PizzeriaContracts/BusinessLogicsContracts/IOrderLogic.cs +++ b/Pizzeria/PizzeriaContracts/BusinessLogicsContracts/IOrderLogic.cs @@ -12,5 +12,6 @@ namespace PizzeriaContracts.BusinessLogicsContracts bool TakeOrderInWork(OrderBindingModel model); bool FinishOrder(OrderBindingModel model); bool DeliveryOrder(OrderBindingModel model); + OrderViewModel? ReadElement(OrderSearchModel model); } } diff --git a/Pizzeria/PizzeriaContracts/SearchModels/OrderSearchModel.cs b/Pizzeria/PizzeriaContracts/SearchModels/OrderSearchModel.cs index f796587..5c10320 100644 --- a/Pizzeria/PizzeriaContracts/SearchModels/OrderSearchModel.cs +++ b/Pizzeria/PizzeriaContracts/SearchModels/OrderSearchModel.cs @@ -1,9 +1,13 @@ -namespace PizzeriaContracts.SearchModels +using PizzeriaDataModels.Enums; + +namespace PizzeriaContracts.SearchModels { public class OrderSearchModel { public int? Id { get; set; } public int? ClientId { get; set; } + public OrderStatus? Status { get; set; } + public int? ImplementerId { get; set; } public DateTime? DateFrom { get; set; } public DateTime? DateTo { get; set; } } diff --git a/Pizzeria/PizzeriaContracts/ViewModels/OrderViewModel.cs b/Pizzeria/PizzeriaContracts/ViewModels/OrderViewModel.cs index cb411df..ae25144 100644 --- a/Pizzeria/PizzeriaContracts/ViewModels/OrderViewModel.cs +++ b/Pizzeria/PizzeriaContracts/ViewModels/OrderViewModel.cs @@ -19,6 +19,10 @@ namespace PizzeriaContracts.ViewModels [DisplayName("ФИО клиента")] public string ClientFIO { get; set; } = string.Empty; + public int? ImplementerId { get; set; } + [DisplayName("Исполнитель")] + public string? ImplementerFIO { get; set; } = null; + [DisplayName("Количество")] public int Count { get; set; } diff --git a/Pizzeria/PizzeriaDataModels/Models/IOrderModel.cs b/Pizzeria/PizzeriaDataModels/Models/IOrderModel.cs index 83add86..6ed8326 100644 --- a/Pizzeria/PizzeriaDataModels/Models/IOrderModel.cs +++ b/Pizzeria/PizzeriaDataModels/Models/IOrderModel.cs @@ -7,6 +7,7 @@ namespace PizzeriaDataModels.Models { int PizzaId { get; } int ClientId { get; } + int? ImplementerId { get; } int Count { get; } double Sum { get; } OrderStatus Status { get; } diff --git a/Pizzeria/PizzeriaDatabaseImplement/Implements/OrderStorage.cs b/Pizzeria/PizzeriaDatabaseImplement/Implements/OrderStorage.cs index 0fd2a4f..527e0e7 100644 --- a/Pizzeria/PizzeriaDatabaseImplement/Implements/OrderStorage.cs +++ b/Pizzeria/PizzeriaDatabaseImplement/Implements/OrderStorage.cs @@ -14,7 +14,12 @@ namespace PizzeriaDatabaseImplement.Implements public List GetFullList() { using var context = new PizzeriaDatabase(); - return context.Orders.Include(x => x.Pizza).Include(x => x.Client).Select(x => x.GetViewModel).ToList(); + return context.Orders + .Include(x => x.Pizza) + .Include(x => x.Client) + .Include(x => x.Implementer) + .Select(x => x.GetViewModel) + .ToList(); } public List GetFilteredList(OrderSearchModel model) diff --git a/Pizzeria/PizzeriaDatabaseImplement/Models/Order.cs b/Pizzeria/PizzeriaDatabaseImplement/Models/Order.cs index b319b00..fa38216 100644 --- a/Pizzeria/PizzeriaDatabaseImplement/Models/Order.cs +++ b/Pizzeria/PizzeriaDatabaseImplement/Models/Order.cs @@ -22,6 +22,9 @@ namespace PizzeriaDatabaseImplement.Models public virtual Pizza Pizza { get; set; } = new(); + public int? ImplementerId { get; private set; } + public virtual Implementer? Implementer { get; set; } = new(); + [Required] public int Count { get; private set; } @@ -45,6 +48,8 @@ namespace PizzeriaDatabaseImplement.Models Client = context.Clients.First(x => x.Id == model.ClientId), PizzaId = model.PizzaId, Pizza = context.Pizzas.First(x => x.Id == model.PizzaId), + ImplementerId = model.ImplementerId, + Implementer = model.ImplementerId.HasValue ? context.Implementers.First(x => x.Id == model.ImplementerId) : null, Count = model.Count, Sum = model.Sum, Status = model.Status, @@ -53,7 +58,7 @@ namespace PizzeriaDatabaseImplement.Models }; } - public void Update(OrderBindingModel? model) + public void Update(PizzeriaDatabase context, OrderBindingModel? model) { if (model == null) { @@ -61,6 +66,8 @@ namespace PizzeriaDatabaseImplement.Models } Status = model.Status; DateImplement = model.DateImplement; + ImplementerId = model.ImplementerId; + Implementer = model.ImplementerId.HasValue ? context.Implementers.First(x => x.Id == model.ImplementerId) : null; } public OrderViewModel GetViewModel => new() @@ -70,6 +77,8 @@ namespace PizzeriaDatabaseImplement.Models ClientFIO = Client.ClientFIO, PizzaId = PizzaId, PizzaName = Pizza.PizzaName, + ImplementerId = ImplementerId, + ImplementerFIO = Implementer != null ? Implementer.ImplementerFIO : null, Count = Count, Sum = Sum, Status = Status, diff --git a/Pizzeria/PizzeriaRestApi/Program.cs b/Pizzeria/PizzeriaRestApi/Program.cs index 004702c..dadd31c 100644 --- a/Pizzeria/PizzeriaRestApi/Program.cs +++ b/Pizzeria/PizzeriaRestApi/Program.cs @@ -13,10 +13,12 @@ builder.Logging.AddLog4Net("log4net.config"); 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(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle -- 2.25.1 From e7963c8662ae389ebd3d8d14d583a858b1b30c52 Mon Sep 17 00:00:00 2001 From: revengel66 Date: Fri, 21 Jun 2024 14:39:37 +0400 Subject: [PATCH 02/16] in process 2 --- .../BusinessLogic/ImplementerLogic.cs | 123 ++++++++++++++++++ .../BindingModels/ImplementerBindingModel.cs | 13 ++ .../IImplementerLogic.cs | 15 +++ .../SearchModels/ImplementerSearchModel.cs | 10 ++ .../StorageContracts/IImplementerStorage.cs | 16 +++ .../ViewModels/ImplementerViewModel.cs | 22 ++++ .../Models/IImplementerModel.cs | 19 +++ .../Implements/ImplementerStorage.cs | 79 +++++++++++ .../Models/Implementer.cs | 65 +++++++++ .../Controllers/ImplementerController.cs | 107 +++++++++++++++ 10 files changed, 469 insertions(+) create mode 100644 Pizzeria/PizzeriaBusinessLogic/BusinessLogic/ImplementerLogic.cs create mode 100644 Pizzeria/PizzeriaContracts/BindingModels/ImplementerBindingModel.cs create mode 100644 Pizzeria/PizzeriaContracts/BusinessLogicsContracts/IImplementerLogic.cs create mode 100644 Pizzeria/PizzeriaContracts/SearchModels/ImplementerSearchModel.cs create mode 100644 Pizzeria/PizzeriaContracts/StorageContracts/IImplementerStorage.cs create mode 100644 Pizzeria/PizzeriaContracts/ViewModels/ImplementerViewModel.cs create mode 100644 Pizzeria/PizzeriaDataModels/Models/IImplementerModel.cs create mode 100644 Pizzeria/PizzeriaDatabaseImplement/Implements/ImplementerStorage.cs create mode 100644 Pizzeria/PizzeriaDatabaseImplement/Models/Implementer.cs create mode 100644 Pizzeria/PizzeriaRestApi/Controllers/ImplementerController.cs diff --git a/Pizzeria/PizzeriaBusinessLogic/BusinessLogic/ImplementerLogic.cs b/Pizzeria/PizzeriaBusinessLogic/BusinessLogic/ImplementerLogic.cs new file mode 100644 index 0000000..af5a000 --- /dev/null +++ b/Pizzeria/PizzeriaBusinessLogic/BusinessLogic/ImplementerLogic.cs @@ -0,0 +1,123 @@ +using Microsoft.Extensions.Logging; +using PizzeriaContracts.BindingModels; +using PizzeriaContracts.BusinessLogicsContracts; +using PizzeriaContracts.SearchModels; +using PizzeriaContracts.StorageContracts; +using PizzeriaContracts.ViewModels; + +namespace PizzeriaBusinessLogic.BusinessLogic +{ + public class ImplementerLogic : IImplementerLogic + { + private readonly ILogger _logger; + private readonly IImplementerStorage _implementerStorage; + + public ImplementerLogic(ILogger logger, IImplementerStorage implementerStorage) + { + _logger = logger; + _implementerStorage = implementerStorage; + } + + public List? ReadList(ImplementerSearchModel? model) + { + _logger.LogInformation("ReadList. ImplementerFIO:{ImplementerFIO}.Password:{Password}.Id:{ Id}", model?.ImplementerFIO, model?.Password?.Length, 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 ImplementerViewModel? ReadElement(ImplementerSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + _logger.LogInformation("ReadElement. ImplementerFIO:{ImplementerFIO}.Password:{Password}.Id:{ Id}", model?.ImplementerFIO, model?.Password?.Length, 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 bool Create(ImplementerBindingModel model) + { + CheckModel(model); + if (_implementerStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } + + public bool Update(ImplementerBindingModel model) + { + CheckModel(model); + if (_implementerStorage.Update(model) == null) + { + _logger.LogWarning("Update 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; + } + + private void CheckModel(ImplementerBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (!withParams) + { + return; + } + if (string.IsNullOrEmpty(model.ImplementerFIO)) + { + throw new ArgumentNullException("Нет ФИО исполнителя", nameof(model.ImplementerFIO)); + } + if (string.IsNullOrEmpty(model.Password)) + { + throw new ArgumentNullException("Нет пароля исполнителя", nameof(model.Password)); + } + if (model.WorkExperience < 0) + { + throw new ArgumentNullException("Стаж должен быть больше 0", nameof(model.WorkExperience)); + } + if (model.Qualification < 0) + { + throw new ArgumentNullException("Квалификация должна быть положительной", nameof(model.Qualification)); + } + _logger.LogInformation("Implementer. ImplementerFIO:{ImplementerFIO}.Password:{Password}.WorkExperience:{WorkExperience}.Qualification:{Qualification}.Id: { Id}", + model.ImplementerFIO, model.Password, model.WorkExperience, model.Qualification, model.Id); + var element = _implementerStorage.GetElement(new ImplementerSearchModel + { + ImplementerFIO = model.ImplementerFIO + }); + if (element != null && element.Id != model.Id) + { + throw new InvalidOperationException("Исполнитель с таким ФИО уже есть"); + } + } + } +} diff --git a/Pizzeria/PizzeriaContracts/BindingModels/ImplementerBindingModel.cs b/Pizzeria/PizzeriaContracts/BindingModels/ImplementerBindingModel.cs new file mode 100644 index 0000000..839aafb --- /dev/null +++ b/Pizzeria/PizzeriaContracts/BindingModels/ImplementerBindingModel.cs @@ -0,0 +1,13 @@ +using PizzeriaDataModels.Models; + +namespace PizzeriaContracts.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/Pizzeria/PizzeriaContracts/BusinessLogicsContracts/IImplementerLogic.cs b/Pizzeria/PizzeriaContracts/BusinessLogicsContracts/IImplementerLogic.cs new file mode 100644 index 0000000..e02b3c4 --- /dev/null +++ b/Pizzeria/PizzeriaContracts/BusinessLogicsContracts/IImplementerLogic.cs @@ -0,0 +1,15 @@ +using PizzeriaContracts.BindingModels; +using PizzeriaContracts.SearchModels; +using PizzeriaContracts.ViewModels; + +namespace PizzeriaContracts.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/Pizzeria/PizzeriaContracts/SearchModels/ImplementerSearchModel.cs b/Pizzeria/PizzeriaContracts/SearchModels/ImplementerSearchModel.cs new file mode 100644 index 0000000..5d024e4 --- /dev/null +++ b/Pizzeria/PizzeriaContracts/SearchModels/ImplementerSearchModel.cs @@ -0,0 +1,10 @@ + +namespace PizzeriaContracts.SearchModels +{ + public class ImplementerSearchModel + { + public int? Id { get; set; } + public string? ImplementerFIO { get; set; } + public string? Password { get; set; } + } +} diff --git a/Pizzeria/PizzeriaContracts/StorageContracts/IImplementerStorage.cs b/Pizzeria/PizzeriaContracts/StorageContracts/IImplementerStorage.cs new file mode 100644 index 0000000..30f013f --- /dev/null +++ b/Pizzeria/PizzeriaContracts/StorageContracts/IImplementerStorage.cs @@ -0,0 +1,16 @@ +using PizzeriaContracts.BindingModels; +using PizzeriaContracts.SearchModels; +using PizzeriaContracts.ViewModels; + +namespace PizzeriaContracts.StorageContracts +{ + 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/Pizzeria/PizzeriaContracts/ViewModels/ImplementerViewModel.cs b/Pizzeria/PizzeriaContracts/ViewModels/ImplementerViewModel.cs new file mode 100644 index 0000000..8782c47 --- /dev/null +++ b/Pizzeria/PizzeriaContracts/ViewModels/ImplementerViewModel.cs @@ -0,0 +1,22 @@ +using PizzeriaDataModels.Models; +using System.ComponentModel; + +namespace PizzeriaContracts.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/Pizzeria/PizzeriaDataModels/Models/IImplementerModel.cs b/Pizzeria/PizzeriaDataModels/Models/IImplementerModel.cs new file mode 100644 index 0000000..4d709e1 --- /dev/null +++ b/Pizzeria/PizzeriaDataModels/Models/IImplementerModel.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PizzeriaDataModels.Models +{ + public interface IImplementerModel : IId + { + string ImplementerFIO { get; } + + string Password { get; } + + int WorkExperience { get; } + + int Qualification { get; } + } +} diff --git a/Pizzeria/PizzeriaDatabaseImplement/Implements/ImplementerStorage.cs b/Pizzeria/PizzeriaDatabaseImplement/Implements/ImplementerStorage.cs new file mode 100644 index 0000000..22986c8 --- /dev/null +++ b/Pizzeria/PizzeriaDatabaseImplement/Implements/ImplementerStorage.cs @@ -0,0 +1,79 @@ +using PizzeriaContracts.BindingModels; +using PizzeriaContracts.SearchModels; +using PizzeriaContracts.StorageContracts; +using PizzeriaContracts.ViewModels; +using PizzeriaDatabaseImplement.Models; + +namespace PizzeriaDatabaseImplement.Implements +{ + public class ImplementerStorage : IImplementerStorage + { + public List GetFullList() + { + using var context = new PizzeriaDatabase(); + return context.Implementers.Select(x => x.GetViewModel).ToList(); + } + + public List GetFilteredList(ImplementerSearchModel model) + { + if (string.IsNullOrEmpty(model.ImplementerFIO)) + { + return new(); + } + using var context = new PizzeriaDatabase(); + return context.Implementers.Where(x => x.ImplementerFIO.Contains(model.ImplementerFIO)).Select(x => x.GetViewModel).ToList(); + } + + public ImplementerViewModel? GetElement(ImplementerSearchModel model) + { + if (string.IsNullOrEmpty(model.ImplementerFIO) && !model.Id.HasValue) + { + return null; + } + using var context = new PizzeriaDatabase(); + return context.Implementers.FirstOrDefault(x => + (!string.IsNullOrEmpty(model.ImplementerFIO) && x.ImplementerFIO == model.ImplementerFIO && (!string.IsNullOrEmpty(model.Password) ? x.Password == model.Password : true)) || + (model.Id.HasValue && x.Id == model.Id)) + ?.GetViewModel; + } + + public ImplementerViewModel? Insert(ImplementerBindingModel model) + { + var newImplementer = Implementer.Create(model); + if (newImplementer == null) + { + return null; + } + using var context = new PizzeriaDatabase(); + context.Implementers.Add(newImplementer); + context.SaveChanges(); + return newImplementer.GetViewModel; + } + + public ImplementerViewModel? Update(ImplementerBindingModel model) + { + using var context = new PizzeriaDatabase(); + var implementer = context.Implementers.FirstOrDefault(x => x.Id == model.Id); + if (implementer == null) + { + return null; + } + implementer.Update(model); + context.SaveChanges(); + return implementer.GetViewModel; + } + + public ImplementerViewModel? Delete(ImplementerBindingModel model) + { + using var context = new PizzeriaDatabase(); + var implementer = context.Implementers.FirstOrDefault(rec => rec.Id == model.Id); + if (implementer != null) + { + context.Implementers.Remove(implementer); + context.SaveChanges(); + return implementer.GetViewModel; + } + return null; + } + } +} diff --git a/Pizzeria/PizzeriaDatabaseImplement/Models/Implementer.cs b/Pizzeria/PizzeriaDatabaseImplement/Models/Implementer.cs new file mode 100644 index 0000000..e8c82a4 --- /dev/null +++ b/Pizzeria/PizzeriaDatabaseImplement/Models/Implementer.cs @@ -0,0 +1,65 @@ +using PizzeriaContracts.BindingModels; +using PizzeriaContracts.ViewModels; +using PizzeriaDataModels.Models; +using System.ComponentModel.DataAnnotations.Schema; +using System.ComponentModel.DataAnnotations; + +namespace PizzeriaDatabaseImplement.Models +{ + public class Implementer : IImplementerModel + { + public int Id { get; set; } + + [Required] + public string ImplementerFIO { get; set; } = string.Empty; + + [Required] + public string Password { get; set; } = string.Empty; + + [Required] + public int WorkExperience { get; set; } + + [Required] + public int Qualification { get; set; } + + [ForeignKey("ImplementerId")] + public virtual List Order { get; set; } = new(); + + public static Implementer? Create(ImplementerBindingModel? model) + { + if (model == null) + { + return null; + } + return new Implementer() + { + Id = model.Id, + ImplementerFIO = model.ImplementerFIO, + Password = model.Password, + WorkExperience = model.WorkExperience, + Qualification = model.Qualification + }; + } + + public void Update(ImplementerBindingModel model) + { + if (model == null) + { + return; + } + ImplementerFIO = model.ImplementerFIO; + Password = model.Password; + WorkExperience = model.WorkExperience; + Qualification = model.Qualification; + } + + public ImplementerViewModel GetViewModel => new() + { + Id = Id, + ImplementerFIO = ImplementerFIO, + Password = Password, + WorkExperience = WorkExperience, + Qualification = Qualification + }; + } +} diff --git a/Pizzeria/PizzeriaRestApi/Controllers/ImplementerController.cs b/Pizzeria/PizzeriaRestApi/Controllers/ImplementerController.cs new file mode 100644 index 0000000..c9768a6 --- /dev/null +++ b/Pizzeria/PizzeriaRestApi/Controllers/ImplementerController.cs @@ -0,0 +1,107 @@ +using Microsoft.AspNetCore.Mvc; +using PizzeriaContracts.BindingModels; +using PizzeriaContracts.BusinessLogicsContracts; +using PizzeriaContracts.SearchModels; +using PizzeriaContracts.ViewModels; +using PizzeriaDataModels.Enums; + +namespace PizzeriaRestApi.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; + } + } + } +} -- 2.25.1 From 875842b96af6faec549746102d734f19b1013fb5 Mon Sep 17 00:00:00 2001 From: revengel66 Date: Fri, 21 Jun 2024 15:06:54 +0400 Subject: [PATCH 03/16] add client --- Pizzeria/Pizzeria/FormCreateOrder.Designer.cs | 65 ++++++++++++------- 1 file changed, 41 insertions(+), 24 deletions(-) diff --git a/Pizzeria/Pizzeria/FormCreateOrder.Designer.cs b/Pizzeria/Pizzeria/FormCreateOrder.Designer.cs index f261442..5f4cf4f 100644 --- a/Pizzeria/Pizzeria/FormCreateOrder.Designer.cs +++ b/Pizzeria/Pizzeria/FormCreateOrder.Designer.cs @@ -36,42 +36,42 @@ labelSum = new Label(); textBoxSum = new TextBox(); comboBoxPizza = new ComboBox(); + comboBoxClient = new ComboBox(); + labelClient = new Label(); SuspendLayout(); // // textBoxCount // - textBoxCount.Location = new Point(113, 55); - textBoxCount.Margin = new Padding(3, 4, 3, 4); + textBoxCount.Location = new Point(99, 73); textBoxCount.Name = "textBoxCount"; - textBoxCount.Size = new Size(266, 27); + textBoxCount.Size = new Size(233, 23); textBoxCount.TabIndex = 13; textBoxCount.TextChanged += textBoxCount_TextChanged; // // labelCount // labelCount.AutoSize = true; - labelCount.Location = new Point(13, 59); + labelCount.Location = new Point(11, 76); labelCount.Name = "labelCount"; - labelCount.Size = new Size(93, 20); + labelCount.Size = new Size(75, 15); labelCount.TabIndex = 12; labelCount.Text = "Количество:"; // // labelPizza // labelPizza.AutoSize = true; - labelPizza.Location = new Point(13, 20); + labelPizza.Location = new Point(11, 15); labelPizza.Name = "labelPizza"; - labelPizza.Size = new Size(55, 20); + labelPizza.Size = new Size(43, 15); labelPizza.TabIndex = 11; labelPizza.Text = "Пицца"; // // buttonCancel // buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; - buttonCancel.Location = new Point(294, 145); - buttonCancel.Margin = new Padding(3, 4, 3, 4); + buttonCancel.Location = new Point(257, 170); buttonCancel.Name = "buttonCancel"; - buttonCancel.Size = new Size(86, 31); + buttonCancel.Size = new Size(75, 23); buttonCancel.TabIndex = 15; buttonCancel.Text = "Отмена"; buttonCancel.UseVisualStyleBackColor = true; @@ -80,10 +80,9 @@ // buttonSave // buttonSave.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; - buttonSave.Location = new Point(193, 145); - buttonSave.Margin = new Padding(3, 4, 3, 4); + buttonSave.Location = new Point(169, 170); buttonSave.Name = "buttonSave"; - buttonSave.Size = new Size(94, 31); + buttonSave.Size = new Size(82, 23); buttonSave.TabIndex = 16; buttonSave.Text = "Сохранить"; buttonSave.UseVisualStyleBackColor = true; @@ -92,36 +91,53 @@ // labelSum // labelSum.AutoSize = true; - labelSum.Location = new Point(13, 97); + labelSum.Location = new Point(11, 105); labelSum.Name = "labelSum"; - labelSum.Size = new Size(58, 20); + labelSum.Size = new Size(48, 15); labelSum.TabIndex = 12; labelSum.Text = "Сумма:"; // // textBoxSum // - textBoxSum.Location = new Point(113, 93); - textBoxSum.Margin = new Padding(3, 4, 3, 4); + textBoxSum.Location = new Point(99, 102); textBoxSum.Name = "textBoxSum"; textBoxSum.ReadOnly = true; - textBoxSum.Size = new Size(266, 27); + textBoxSum.Size = new Size(233, 23); textBoxSum.TabIndex = 13; // // comboBoxPizza // comboBoxPizza.DropDownStyle = ComboBoxStyle.DropDownList; comboBoxPizza.FormattingEnabled = true; - comboBoxPizza.Location = new Point(113, 16); - comboBoxPizza.Margin = new Padding(3, 4, 3, 4); + comboBoxPizza.Location = new Point(99, 12); comboBoxPizza.Name = "comboBoxPizza"; - comboBoxPizza.Size = new Size(266, 28); + comboBoxPizza.Size = new Size(233, 23); comboBoxPizza.TabIndex = 17; // + // comboBoxClient + // + comboBoxClient.FormattingEnabled = true; + comboBoxClient.Location = new Point(99, 43); + comboBoxClient.Name = "comboBoxClient"; + comboBoxClient.Size = new Size(233, 23); + comboBoxClient.TabIndex = 18; + // + // labelClient + // + labelClient.AutoSize = true; + labelClient.Location = new Point(12, 46); + labelClient.Name = "labelClient"; + labelClient.Size = new Size(46, 15); + labelClient.TabIndex = 19; + labelClient.Text = "Клиент"; + // // FormCreateOrder // - AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(401, 200); + ClientSize = new Size(351, 211); + Controls.Add(labelClient); + Controls.Add(comboBoxClient); Controls.Add(comboBoxPizza); Controls.Add(buttonCancel); Controls.Add(buttonSave); @@ -130,7 +146,6 @@ Controls.Add(textBoxCount); Controls.Add(labelCount); Controls.Add(labelPizza); - Margin = new Padding(3, 4, 3, 4); Name = "FormCreateOrder"; Text = "Заказ"; Load += FormCreateOrder_Load; @@ -147,5 +162,7 @@ private Label labelSum; private TextBox textBoxSum; private ComboBox comboBoxPizza; + private ComboBox comboBoxClient; + private Label labelClient; } } \ No newline at end of file -- 2.25.1 From 3d3d2ec217412a7b96db9a49a4cca87207f2fe7a Mon Sep 17 00:00:00 2001 From: revengel66 Date: Fri, 21 Jun 2024 15:07:22 +0400 Subject: [PATCH 04/16] edit formcreateorder --- Pizzeria/Pizzeria/FormCreateOrder.cs | 33 ++++++++++++++++++++++++---- 1 file changed, 29 insertions(+), 4 deletions(-) diff --git a/Pizzeria/Pizzeria/FormCreateOrder.cs b/Pizzeria/Pizzeria/FormCreateOrder.cs index eb53204..324d906 100644 --- a/Pizzeria/Pizzeria/FormCreateOrder.cs +++ b/Pizzeria/Pizzeria/FormCreateOrder.cs @@ -11,12 +11,14 @@ namespace Pizzeria private readonly ILogger _logger; private readonly IPizzaLogic _logicP; private readonly IOrderLogic _logicO; + private readonly IClientLogic _logicC; - public FormCreateOrder(ILogger logger, IPizzaLogic logicP, IOrderLogic logicO) + public FormCreateOrder(ILogger logger, IPizzaLogic logicP, IOrderLogic logicO, IClientLogic logicC) { InitializeComponent(); _logger = logger; _logicP = logicP; + _logicC = logicC; _logicO = logicO; } private void FormCreateOrder_Load(object sender, EventArgs e) @@ -32,12 +34,29 @@ namespace Pizzeria comboBoxPizza.DataSource = _list; comboBoxPizza.SelectedItem = null; } - } + } catch (Exception ex) { _logger.LogError(ex, "Ошибка при загрузке пиццы для заказа"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } + _logger.LogInformation("Loading clients for order"); + try + { + var clientList = _logicC.ReadList(null); + if (clientList != null) + { + comboBoxClient.DisplayMember = "ClientFIO"; + comboBoxClient.ValueMember = "Id"; + comboBoxClient.DataSource = clientList; + comboBoxClient.SelectedItem = null; + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Error during loading clients for order"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } } private void CalcSum() @@ -52,7 +71,7 @@ namespace Pizzeria Id = id }); int count = Convert.ToInt32(textBoxCount.Text); - textBoxSum.Text = Math.Round(count * (Pizza?.Price ?? 0),2).ToString(); + textBoxSum.Text = Math.Round(count * (Pizza?.Price ?? 0), 2).ToString(); _logger.LogInformation("Расчет суммы заказа"); } catch (Exception ex) @@ -89,7 +108,12 @@ namespace Pizzeria } if (comboBoxPizza.SelectedValue == null) { - MessageBox.Show("Выберите пицца", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("Выберите пиццу", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (comboBoxClient.SelectedValue == null) + { + MessageBox.Show("Выберите клиента", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } _logger.LogInformation("Создание заказа"); @@ -98,6 +122,7 @@ namespace Pizzeria var operationResult = _logicO.CreateOrder(new OrderBindingModel { PizzaId = Convert.ToInt32(comboBoxPizza.SelectedValue), + ClientId = Convert.ToInt32(comboBoxClient.SelectedValue), Count = Convert.ToInt32(textBoxCount.Text), Sum = Convert.ToDouble(textBoxSum.Text) }); -- 2.25.1 From 54a20dda00168eb4542e81b0fe4401b847f28b54 Mon Sep 17 00:00:00 2001 From: revengel66 Date: Fri, 21 Jun 2024 15:07:54 +0400 Subject: [PATCH 05/16] edit orderlogic --- .../BusinessLogic/OrderLogic.cs | 44 ++++--------------- 1 file changed, 8 insertions(+), 36 deletions(-) diff --git a/Pizzeria/PizzeriaBusinessLogic/BusinessLogic/OrderLogic.cs b/Pizzeria/PizzeriaBusinessLogic/BusinessLogic/OrderLogic.cs index f9408de..277115d 100644 --- a/Pizzeria/PizzeriaBusinessLogic/BusinessLogic/OrderLogic.cs +++ b/Pizzeria/PizzeriaBusinessLogic/BusinessLogic/OrderLogic.cs @@ -4,7 +4,7 @@ using PizzeriaContracts.BusinessLogicsContracts; using PizzeriaContracts.SearchModels; using PizzeriaContracts.StorageContracts; using PizzeriaContracts.ViewModels; -using PizzeriaDataModels.Enums; +using PizzeriaDataModels.Enums; namespace PizzeriaBusinessLogic.BusinessLogic { @@ -19,10 +19,10 @@ namespace PizzeriaBusinessLogic.BusinessLogic _logger = logger; _orderStorage = orderStorage; } - + public bool CreateOrder(OrderBindingModel model) { - + CheckModel(model); if (model.Status != OrderStatus.Неизвестен) @@ -39,30 +39,10 @@ namespace PizzeriaBusinessLogic.BusinessLogic return true; } - public OrderViewModel? ReadElement(OrderSearchModel model) - { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - _logger.LogInformation("ReadElement. ClientId:{ClientId}.Status:{Status}.ImplementerId:{ImplementerId}.DateFrom:{DateFrom}.DateTo:{DateTo}OrderId:{Id}", - model.ClientId, model.Status, model.ImplementerId, model.DateFrom, model.DateTo, 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; - } - - public List? ReadList(OrderSearchModel? model) { - _logger.LogInformation("ReadList. ClientId:{ClientId}.Status:{Status}.ImplementerId:{ImplementerId}.DateFrom:{DateFrom}.DateTo:{DateTo}OrderId:{Id}", - model?.ClientId, model?.Status, model?.ImplementerId, model?.DateFrom, model?.DateTo, model?.Id); + _logger.LogInformation("ReadList. OrderId: {Id}.", model?.Id); var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model); if (list == null) { @@ -90,10 +70,10 @@ namespace PizzeriaBusinessLogic.BusinessLogic public bool ChangeStatus(OrderBindingModel model, OrderStatus status) { CheckModel(model, false); - + var searchOrder = new OrderSearchModel { Id = model.Id }; var order = _orderStorage.GetElement(searchOrder); - + if (order == null) { throw new ArgumentNullException(nameof(order)); @@ -112,10 +92,6 @@ namespace PizzeriaBusinessLogic.BusinessLogic } model.Status = status; - if (order.ImplementerId.HasValue) - { - model.ImplementerId = order.ImplementerId; - } if (model.Status == OrderStatus.Готов) { model.DateImplement = DateTime.Now; @@ -127,11 +103,11 @@ namespace PizzeriaBusinessLogic.BusinessLogic return false; } return true; - + } private void CheckModel(OrderBindingModel model, bool withParams = true) { - + if (model == null) { throw new ArgumentNullException(nameof(model)); @@ -156,10 +132,6 @@ namespace PizzeriaBusinessLogic.BusinessLogic { throw new ArgumentNullException("Стоимость заказа должна быть больше 0", nameof(model.Sum)); } - if (model.DateImplement.HasValue && model.DateImplement < model.DateCreate) - { - throw new ArithmeticException($"Дата выдачи заказа {model.DateImplement} не может быть раньше даты его создания {model.DateCreate}"); - } _logger.LogInformation("Order. Id: {Id}. Sum: {Sum}. PizzaId: {PizzaId}. PizzaCount: {Count}", model.Id, model.Sum, model.PizzaId, model.Count); } } -- 2.25.1 From 1d8c53582b69306100f668d1154b131f8fa879d0 Mon Sep 17 00:00:00 2001 From: revengel66 Date: Fri, 21 Jun 2024 15:13:53 +0400 Subject: [PATCH 06/16] edit orderlogic --- .../BusinessLogic/OrderLogic.cs | 33 +++++++++++++++++-- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/Pizzeria/PizzeriaBusinessLogic/BusinessLogic/OrderLogic.cs b/Pizzeria/PizzeriaBusinessLogic/BusinessLogic/OrderLogic.cs index 277115d..c51b134 100644 --- a/Pizzeria/PizzeriaBusinessLogic/BusinessLogic/OrderLogic.cs +++ b/Pizzeria/PizzeriaBusinessLogic/BusinessLogic/OrderLogic.cs @@ -5,6 +5,7 @@ using PizzeriaContracts.SearchModels; using PizzeriaContracts.StorageContracts; using PizzeriaContracts.ViewModels; using PizzeriaDataModels.Enums; +using System.Xml.Linq; namespace PizzeriaBusinessLogic.BusinessLogic { @@ -13,13 +14,29 @@ namespace PizzeriaBusinessLogic.BusinessLogic private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; - + static readonly object _locker = new object(); public OrderLogic(ILogger logger, IOrderStorage orderStorage) { _logger = logger; _orderStorage = orderStorage; } - + public OrderViewModel? ReadElement(OrderSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + _logger.LogInformation("ReadElement. ClientId:{ClientId}.Status:{Status}.ImplementerId:{ImplementerId}.DateFrom:{DateFrom}.DateTo:{DateTo}OrderId:{Id}", + model.ClientId, model.Status, model.ImplementerId, model.DateFrom, model.DateTo, 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; + } public bool CreateOrder(OrderBindingModel model) { @@ -42,7 +59,8 @@ namespace PizzeriaBusinessLogic.BusinessLogic public List? ReadList(OrderSearchModel? model) { - _logger.LogInformation("ReadList. OrderId: {Id}.", model?.Id); + _logger.LogInformation("ReadList. ClientId:{ClientId}.Status:{Status}.ImplementerId:{ImplementerId}.DateFrom:{DateFrom}.DateTo:{DateTo}OrderId:{Id}", + model?.ClientId, model?.Status, model?.ImplementerId, model?.DateFrom, model?.DateTo, model?.Id); var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model); if (list == null) { @@ -92,6 +110,15 @@ namespace PizzeriaBusinessLogic.BusinessLogic } model.Status = status; + if (order.ImplementerId.HasValue) + { + model.ImplementerId = order.ImplementerId; + } + if (model.Status == OrderStatus.Выдан) + { + model.DateImplement = DateTime.Now; + } + if (model.Status == OrderStatus.Готов) { model.DateImplement = DateTime.Now; -- 2.25.1 From 6d669290c5afeb6b43d43fa81f0a16b129488296 Mon Sep 17 00:00:00 2001 From: revengel66 Date: Fri, 21 Jun 2024 15:37:13 +0400 Subject: [PATCH 07/16] 6 laba storages --- .../Implements/OrderStorage.cs | 70 ++++++++++++++++--- .../PizzeriaDatabase.cs | 1 + .../DataFileSingleton.cs | 4 ++ .../Implements/OrderStorage.cs | 17 +++-- .../PizzeriaFileImplement/Models/Order.cs | 6 +- .../DataListSingleton.cs | 3 + .../PizzeriaListImplement/Models/Order.cs | 3 + 7 files changed, 87 insertions(+), 17 deletions(-) diff --git a/Pizzeria/PizzeriaDatabaseImplement/Implements/OrderStorage.cs b/Pizzeria/PizzeriaDatabaseImplement/Implements/OrderStorage.cs index 527e0e7..f81c544 100644 --- a/Pizzeria/PizzeriaDatabaseImplement/Implements/OrderStorage.cs +++ b/Pizzeria/PizzeriaDatabaseImplement/Implements/OrderStorage.cs @@ -4,8 +4,6 @@ using PizzeriaContracts.ViewModels; using PizzeriaDatabaseImplement.Models; using Microsoft.EntityFrameworkCore; using PizzeriaContracts.StorageContracts; -using System.Collections.Generic; -using System.Linq; namespace PizzeriaDatabaseImplement.Implements { @@ -27,13 +25,41 @@ namespace PizzeriaDatabaseImplement.Implements using var context = new PizzeriaDatabase(); if (model.DateFrom.HasValue) { - return context.Orders.Include(x => x.Pizza).Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo).Select(x => x.GetViewModel).ToList(); + return context.Orders + .Include(x => x.Pizza) + .Include(x => x.Client) + .Include(x => x.Implementer) + .Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo) + .Select(x => x.GetViewModel) + .ToList(); } if (model.ClientId.HasValue) { - return context.Orders.Include(x => x.Pizza).Where(x => x.ClientId == model.ClientId).Select(x => x.GetViewModel).ToList(); + return context.Orders + .Include(x => x.Pizza) + .Include(x => x.Client) + .Include(x => x.Implementer) + .Where(x => x.ClientId == model.ClientId) + .Select(x => x.GetViewModel) + .ToList(); } - return context.Orders.Include(x => x.Pizza).Where(x => x.Id == model.Id).Select(x => x.GetViewModel).ToList(); + else if (model.ImplementerId.HasValue) + { + return context.Orders + .Include(x => x.Pizza) + .Include(x => x.Client) + .Include(x => x.Implementer) + .Where(x => x.ImplementerId == model.ImplementerId) + .Select(x => x.GetViewModel) + .ToList(); + } + return context.Orders + .Include(x => x.Pizza) + .Include(x => x.Client) + .Include(x => x.Implementer) + .Where(x => x.Id == model.Id) + .Select(x => x.GetViewModel) + .ToList(); } public OrderViewModel? GetElement(OrderSearchModel model) @@ -43,7 +69,15 @@ namespace PizzeriaDatabaseImplement.Implements return new(); } using var context = new PizzeriaDatabase(); - return context.Orders.Include(x => x.Pizza).FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; + return context.Orders + .Include(x => x.Pizza) + .Include(x => x.Client) + .Include(x => x.Implementer) + .FirstOrDefault(x => + model.ImplementerId.HasValue && x.ImplementerId == model.ImplementerId && model.Status != null && x.Status.Equals(model.Status) + || model.Status == null && model.ImplementerId.HasValue && x.ImplementerId == model.ImplementerId + || model.Id.HasValue && x.Id == model.Id) + ?.GetViewModel; } public OrderViewModel? Insert(OrderBindingModel model) @@ -58,7 +92,12 @@ namespace PizzeriaDatabaseImplement.Implements } context.Orders.Add(newOrder); context.SaveChanges(); - return newOrder.GetViewModel; + return context.Orders + .Include(x => x.Pizza) + .Include(x => x.Client) + .Include(x => x.Implementer) + .FirstOrDefault(x => x.Id == newOrder.Id) + ?.GetViewModel; } public OrderViewModel? Update(OrderBindingModel model) @@ -69,9 +108,14 @@ namespace PizzeriaDatabaseImplement.Implements { return null; } - order.Update(model); + order.Update(context,model); context.SaveChanges(); - return order.GetViewModel; + return context.Orders + .Include(x => x.Pizza) + .Include(x => x.Client) + .Include(x => x.Implementer) + .FirstOrDefault(x => x.Id == model.Id) + ?.GetViewModel; } public OrderViewModel? Delete(OrderBindingModel model) @@ -80,9 +124,15 @@ namespace PizzeriaDatabaseImplement.Implements var order = context.Orders.FirstOrDefault(rec => rec.Id == model.Id); if (order != null) { + var deletedElement = context.Orders + .Include(x => x.Pizza) + .Include(x => x.Client) + .Include(x => x.Implementer) + .FirstOrDefault(x => x.Id == model.Id) + ?.GetViewModel; context.Orders.Remove(order); context.SaveChanges(); - return order.GetViewModel; + return deletedElement; } return null; } diff --git a/Pizzeria/PizzeriaDatabaseImplement/PizzeriaDatabase.cs b/Pizzeria/PizzeriaDatabaseImplement/PizzeriaDatabase.cs index b6361d7..a76d949 100644 --- a/Pizzeria/PizzeriaDatabaseImplement/PizzeriaDatabase.cs +++ b/Pizzeria/PizzeriaDatabaseImplement/PizzeriaDatabase.cs @@ -18,6 +18,7 @@ namespace PizzeriaDatabaseImplement public virtual DbSet PizzaComponents { set; get; } public virtual DbSet Orders { set; get; } public virtual DbSet Clients { set; get; } + public virtual DbSet Implementers { set; get; } } } diff --git a/Pizzeria/PizzeriaFileImplement/DataFileSingleton.cs b/Pizzeria/PizzeriaFileImplement/DataFileSingleton.cs index 54025c2..ba9325b 100644 --- a/Pizzeria/PizzeriaFileImplement/DataFileSingleton.cs +++ b/Pizzeria/PizzeriaFileImplement/DataFileSingleton.cs @@ -10,16 +10,19 @@ namespace PizzeriaFileImplement private readonly string OrderFileName = "Order.xml"; private readonly string PizzaFileName = "Pizza.xml"; private readonly string ClientFileName = "Client.xml"; + private readonly string ImplementerFileName = "Implementer.xml"; public List Components { get; private set; } public List Orders { get; private set; } public List Pizzas { get; private set; } public List Clients { get; private set; } + public List Implementers { get; private set; } private DataFileSingleton() { Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!; Pizzas = LoadData(PizzaFileName, "Pizza", x => Pizza.Create(x)!)!; Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!; Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!; + Implementers = LoadData(ImplementerFileName, "Implementer", x => Implementer.Create(x)!)!; } public static DataFileSingleton GetInstance() { @@ -34,6 +37,7 @@ namespace PizzeriaFileImplement public void SavePizzas() => SaveData(Pizzas, PizzaFileName, "Pizzas", x => x.GetXElement); public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement); public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", x => x.GetXElement); + public void SaveImplementers() => SaveData(Implementers, ImplementerFileName, "Implementers", x => x.GetXElement); private static List? LoadData(string filename, string xmlNodeName,Func selectFunction) { diff --git a/Pizzeria/PizzeriaFileImplement/Implements/OrderStorage.cs b/Pizzeria/PizzeriaFileImplement/Implements/OrderStorage.cs index 40ea89a..d33c14c 100644 --- a/Pizzeria/PizzeriaFileImplement/Implements/OrderStorage.cs +++ b/Pizzeria/PizzeriaFileImplement/Implements/OrderStorage.cs @@ -31,12 +31,11 @@ namespace PizzeriaFileImplement.Implements { return null; } - var order = source.Orders.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id)); - if (order == null) - { - return null; - } - return AddData(order.GetViewModel); + var order = source.Orders.FirstOrDefault(x => + model.ImplementerId.HasValue && x.ImplementerId == model.ImplementerId && model.Status != null && x.Status.Equals(model.Status) + || model.Status == null && model.ImplementerId.HasValue && x.ImplementerId == model.ImplementerId + || model.Id.HasValue && x.Id == model.Id); + return order?.GetViewModel != null ? AddData(order.GetViewModel) : null; } public List GetFilteredList(OrderSearchModel model) @@ -53,6 +52,11 @@ namespace PizzeriaFileImplement.Implements { return source.Orders.Where(x => x.ClientId == model.ClientId).Select(x => AddData(x.GetViewModel)).ToList(); } + if (!model.ImplementerId.HasValue && !model.Id.HasValue) + { + return source.Orders.Where(x => x.ImplementerId == model.ImplementerId).Select(x => x.GetViewModel).ToList(); + + } return new(); } @@ -60,6 +64,7 @@ namespace PizzeriaFileImplement.Implements { return source.Orders.Select(x => AddData(x.GetViewModel)).ToList(); } + public OrderViewModel? Insert(OrderBindingModel model) { model.Id = source.Orders.Count > 0 ? source.Orders.Max(x => x.Id) + 1 : 1; diff --git a/Pizzeria/PizzeriaFileImplement/Models/Order.cs b/Pizzeria/PizzeriaFileImplement/Models/Order.cs index 88c5ed5..8475342 100644 --- a/Pizzeria/PizzeriaFileImplement/Models/Order.cs +++ b/Pizzeria/PizzeriaFileImplement/Models/Order.cs @@ -12,7 +12,7 @@ namespace PizzeriaFileImplement.Models public int PizzaId { get; private set; } public int ClientId { get; private set; } - + public int? ImplementerId { get; set; } public int Count { get; private set; } public double Sum { get; private set; } @@ -33,6 +33,7 @@ namespace PizzeriaFileImplement.Models { Id = model.Id, PizzaId = model.PizzaId, + ImplementerId = model.ImplementerId, ClientId = model.ClientId, Count = model.Count, Sum = model.Sum, @@ -51,6 +52,7 @@ namespace PizzeriaFileImplement.Models { Id = Convert.ToInt32(element.Attribute("Id")!.Value), PizzaId = Convert.ToInt32(element.Element("PizzaId")!.Value), + ImplementerId = Convert.ToInt32(element.Element("ImplementerId")!.Value), ClientId = Convert.ToInt32(element.Element("ClientId")!.Value), Count = Convert.ToInt32(element.Element("Count")!.Value), Sum = Convert.ToDouble(element.Element("Sum")!.Value), @@ -74,6 +76,7 @@ namespace PizzeriaFileImplement.Models Id = Id, PizzaId = PizzaId, ClientId = ClientId, + ImplementerId = ImplementerId, Count = Count, Sum = Sum, Status = Status, @@ -85,6 +88,7 @@ namespace PizzeriaFileImplement.Models new XAttribute("Id", Id), new XElement("PizzaId", PizzaId), new XElement("ClientId", ClientId), + new XElement("ImplementerId", ImplementerId), new XElement("Count", Count.ToString()), new XElement("Sum", Sum.ToString()), new XElement("Status", Status.ToString()), diff --git a/Pizzeria/PizzeriaListImplement/DataListSingleton.cs b/Pizzeria/PizzeriaListImplement/DataListSingleton.cs index 0325445..366111a 100644 --- a/Pizzeria/PizzeriaListImplement/DataListSingleton.cs +++ b/Pizzeria/PizzeriaListImplement/DataListSingleton.cs @@ -9,11 +9,14 @@ namespace PizzeriaListImplement public List Orders { get; set; } public List Pizzas { get; set; } public List Clients { get; set; } + public List Implementers { get; set; } private DataListSingleton() { Components = new List(); Orders = new List(); Pizzas = new List(); + Clients = new List(); + Implementers = new List(); } public static DataListSingleton GetInstance() { diff --git a/Pizzeria/PizzeriaListImplement/Models/Order.cs b/Pizzeria/PizzeriaListImplement/Models/Order.cs index 676e9dc..ec6ddd1 100644 --- a/Pizzeria/PizzeriaListImplement/Models/Order.cs +++ b/Pizzeria/PizzeriaListImplement/Models/Order.cs @@ -12,6 +12,7 @@ namespace PizzeriaListImplement.Models public int PizzaId { get; private set; } public int ClientId { get; private set; } + public int? ImplementerId { get; private set; } public int Count { get; private set; } public double Sum { get; private set; } @@ -33,6 +34,7 @@ namespace PizzeriaListImplement.Models Id = model.Id, PizzaId = model.PizzaId, ClientId = model.ClientId, + ImplementerId = model.ImplementerId, Count = model.Count, Sum = model.Sum, Status = model.Status, @@ -55,6 +57,7 @@ namespace PizzeriaListImplement.Models Id = Id, PizzaId = PizzaId, ClientId = ClientId, + ImplementerId = ImplementerId, Count = Count, Sum = Sum, Status = Status, -- 2.25.1 From 7d03ea1b317e7e0555c2e583286df99debd69a48 Mon Sep 17 00:00:00 2001 From: revengel66 Date: Fri, 21 Jun 2024 15:37:28 +0400 Subject: [PATCH 08/16] 6 laba storages --- .../Implements/ImplementerStorage.cs | 94 +++++++++++++++++++ .../Models/Implementer.cs | 82 ++++++++++++++++ .../Models/Implementer.cs | 55 +++++++++++ 3 files changed, 231 insertions(+) create mode 100644 Pizzeria/PizzeriaFileImplement/Implements/ImplementerStorage.cs create mode 100644 Pizzeria/PizzeriaFileImplement/Models/Implementer.cs create mode 100644 Pizzeria/PizzeriaListImplement/Models/Implementer.cs diff --git a/Pizzeria/PizzeriaFileImplement/Implements/ImplementerStorage.cs b/Pizzeria/PizzeriaFileImplement/Implements/ImplementerStorage.cs new file mode 100644 index 0000000..aa62ccb --- /dev/null +++ b/Pizzeria/PizzeriaFileImplement/Implements/ImplementerStorage.cs @@ -0,0 +1,94 @@ +using PizzeriaContracts.BindingModels; +using PizzeriaContracts.SearchModels; +using PizzeriaContracts.StorageContracts; +using PizzeriaContracts.ViewModels; +using PizzeriaFileImplement.Models; + +namespace PizzeriaFileImplement.Implements +{ + public class ImplementerStorage : IImplementerStorage + { + private readonly DataFileSingleton _source; + public ImplementerStorage() + { + _source = DataFileSingleton.GetInstance(); + } + + public List GetFullList() + { + return _source.Implementers.Select(x => x.GetViewModel).ToList(); + } + + 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 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 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; + } + + 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; + } + } +} diff --git a/Pizzeria/PizzeriaFileImplement/Models/Implementer.cs b/Pizzeria/PizzeriaFileImplement/Models/Implementer.cs new file mode 100644 index 0000000..58f26c5 --- /dev/null +++ b/Pizzeria/PizzeriaFileImplement/Models/Implementer.cs @@ -0,0 +1,82 @@ +using PizzeriaContracts.BindingModels; +using PizzeriaContracts.ViewModels; +using PizzeriaDataModels.Models; +using System.Xml.Linq; + +namespace PizzeriaFileImplement.Models +{ + public class Implementer : IImplementerModel + { + public int Id { get; private set; } + + 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 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, + }; + + 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/Pizzeria/PizzeriaListImplement/Models/Implementer.cs b/Pizzeria/PizzeriaListImplement/Models/Implementer.cs new file mode 100644 index 0000000..c781b8e --- /dev/null +++ b/Pizzeria/PizzeriaListImplement/Models/Implementer.cs @@ -0,0 +1,55 @@ +using PizzeriaContracts.BindingModels; +using PizzeriaContracts.ViewModels; +using PizzeriaDataModels.Models; + +namespace PizzeriaListImplement.Models +{ + public class Implementer : IImplementerModel + { + public int Id { get; private set; } + + 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 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, + }; + } +} -- 2.25.1 From 393779d3c3c789ba435a27ea9634b1c16813bc6f Mon Sep 17 00:00:00 2001 From: revengel66 Date: Fri, 21 Jun 2024 15:41:19 +0400 Subject: [PATCH 09/16] edit list storage 6 lab --- .../Implements/ImplementerStorage.cs | 118 ++++++++++++++++++ 1 file changed, 118 insertions(+) create mode 100644 Pizzeria/PizzeriaListImplement/Implements/ImplementerStorage.cs diff --git a/Pizzeria/PizzeriaListImplement/Implements/ImplementerStorage.cs b/Pizzeria/PizzeriaListImplement/Implements/ImplementerStorage.cs new file mode 100644 index 0000000..3c5f218 --- /dev/null +++ b/Pizzeria/PizzeriaListImplement/Implements/ImplementerStorage.cs @@ -0,0 +1,118 @@ +using PizzeriaContracts.BindingModels; +using PizzeriaContracts.SearchModels; +using PizzeriaContracts.StorageContracts; +using PizzeriaContracts.ViewModels; +using PizzeriaListImplement.Models; + +namespace PizzeriaListImplement.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; + } + } +} -- 2.25.1 From 8cba1d13b901e10bca2bc04f6da711b44a1c6e55 Mon Sep 17 00:00:00 2001 From: revengel66 Date: Fri, 21 Jun 2024 15:55:37 +0400 Subject: [PATCH 10/16] edit order storage list 6 lab --- .../Implements/OrderStorage.cs | 63 ++++++++++++++++--- 1 file changed, 53 insertions(+), 10 deletions(-) diff --git a/Pizzeria/PizzeriaListImplement/Implements/OrderStorage.cs b/Pizzeria/PizzeriaListImplement/Implements/OrderStorage.cs index 6dd2457..9df05be 100644 --- a/Pizzeria/PizzeriaListImplement/Implements/OrderStorage.cs +++ b/Pizzeria/PizzeriaListImplement/Implements/OrderStorage.cs @@ -35,10 +35,14 @@ namespace PizzeriaListImplement.Implements } foreach (var order in _source.Orders) { - if ((model.Id.HasValue && order.Id == model.Id)) + if (model.Id.HasValue && order.Id == model.Id) { return AddPizzaName(order.GetViewModel); } + else if (model.ImplementerId.HasValue && model.ImplementerId == order.ImplementerId) + { + return GetViewModel(order); + } } return null; } @@ -46,31 +50,70 @@ namespace PizzeriaListImplement.Implements public List GetFilteredList(OrderSearchModel model) { var result = new List(); - if (!model.Id.HasValue && !model.DateFrom.HasValue) - { - return result; - } if (model.DateFrom.HasValue) { foreach (var order in _source.Orders) { if (order.DateCreate >= model.DateFrom && order.DateCreate <= model.DateTo) { - result.Add(AddPizzaName(order.GetViewModel)); + result.Add(GetViewModel(order)); } } - return result; } - foreach (var order in _source.Orders) + else if (model.ClientId.HasValue && !model.Id.HasValue) { - if (order.Id == model.Id) + foreach (var order in _source.Orders) { - result.Add(AddPizzaName(order.GetViewModel)); + if (order.ClientId == model.ClientId) + { + result.Add(GetViewModel(order)); + } + } + } + else if (model.ImplementerId.HasValue && !model.Id.HasValue) + { + foreach (var order in _source.Orders) + { + if (order.ImplementerId == model.ImplementerId) + { + result.Add(GetViewModel(order)); + } + } + } + else if (model.Id.HasValue) + { + foreach (var order in _source.Orders) + { + if (order.Id == model.Id) + { + result.Add(GetViewModel(order)); + } } } return result; } + private OrderViewModel GetViewModel(Order order) + { + var viewModel = order.GetViewModel; + foreach (var package in _source.Pizzas) + { + if (package.Id == order.PizzaId) + { + viewModel.PizzaName = package.PizzaName; + break; + } + } + foreach (var client in _source.Clients) + { + if (client.Id == order.ClientId) + { + viewModel.ClientFIO = client.ClientFIO; + break; + } + } + return viewModel; + } public List GetFullList() { var result = new List(); -- 2.25.1 From de9cf6e8933e4e9d48ea9d6b623725cd43afda11 Mon Sep 17 00:00:00 2001 From: revengel66 Date: Fri, 21 Jun 2024 16:00:10 +0400 Subject: [PATCH 11/16] add IWorkProcess lab6 --- .../BusinessLogicsContracts/IWorkProcess.cs | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 Pizzeria/PizzeriaContracts/BusinessLogicsContracts/IWorkProcess.cs diff --git a/Pizzeria/PizzeriaContracts/BusinessLogicsContracts/IWorkProcess.cs b/Pizzeria/PizzeriaContracts/BusinessLogicsContracts/IWorkProcess.cs new file mode 100644 index 0000000..c53793b --- /dev/null +++ b/Pizzeria/PizzeriaContracts/BusinessLogicsContracts/IWorkProcess.cs @@ -0,0 +1,8 @@ + +namespace PizzeriaContracts.BusinessLogicsContracts +{ + public interface IWorkProcess + { + void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic); + } +} -- 2.25.1 From 6caf3fb37866269dfbb66e671192112427ab6542 Mon Sep 17 00:00:00 2001 From: revengel66 Date: Fri, 21 Jun 2024 16:05:20 +0400 Subject: [PATCH 12/16] add WorkModeling lab6 --- .../BusinessLogic/WorkModeling.cs | 134 ++++++++++++++++++ 1 file changed, 134 insertions(+) create mode 100644 Pizzeria/PizzeriaBusinessLogic/BusinessLogic/WorkModeling.cs diff --git a/Pizzeria/PizzeriaBusinessLogic/BusinessLogic/WorkModeling.cs b/Pizzeria/PizzeriaBusinessLogic/BusinessLogic/WorkModeling.cs new file mode 100644 index 0000000..bb5452a --- /dev/null +++ b/Pizzeria/PizzeriaBusinessLogic/BusinessLogic/WorkModeling.cs @@ -0,0 +1,134 @@ +using Microsoft.Extensions.Logging; +using PizzeriaContracts.BindingModels; +using PizzeriaContracts.BusinessLogicsContracts; +using PizzeriaContracts.SearchModels; +using PizzeriaContracts.ViewModels; +using PizzeriaDataModels.Enums; + +namespace PizzeriaBusinessLogic.BusinessLogic +{ + 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.FinishOrder(new OrderBindingModel + { + Id = order.Id + }); + } + // кто-то мог уже перехватить заказ, игнорируем ошибку + catch (InvalidOperationException ex) + { + _logger.LogWarning(ex, "Error try get work"); + } + // заканчиваем выполнение имитации в случае иной ошибки + catch (Exception ex) + { + _logger.LogError(ex, "Error while do work"); + throw; + } + // отдыхаем + Thread.Sleep(implementer.Qualification * _rnd.Next(10, 100)); + } + }); + } + + 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; + } + } + } +} -- 2.25.1 From 33bd12a1cfec62ff0d142568981767fe959b734a Mon Sep 17 00:00:00 2001 From: revengel66 Date: Fri, 21 Jun 2024 16:17:39 +0400 Subject: [PATCH 13/16] add Implementer forms lab 6 --- Pizzeria/Pizzeria/FormImplementer.Designer.cs | 166 ++++++++++++++++++ Pizzeria/Pizzeria/FormImplementer.cs | 94 ++++++++++ Pizzeria/Pizzeria/FormImplementer.resx | 120 +++++++++++++ .../Pizzeria/FormImplementers.Designer.cs | 129 ++++++++++++++ Pizzeria/Pizzeria/FormImplementers.cs | 108 ++++++++++++ Pizzeria/Pizzeria/FormImplementers.resx | 120 +++++++++++++ Pizzeria/Pizzeria/Program.cs | 1 + 7 files changed, 738 insertions(+) create mode 100644 Pizzeria/Pizzeria/FormImplementer.Designer.cs create mode 100644 Pizzeria/Pizzeria/FormImplementer.cs create mode 100644 Pizzeria/Pizzeria/FormImplementer.resx create mode 100644 Pizzeria/Pizzeria/FormImplementers.Designer.cs create mode 100644 Pizzeria/Pizzeria/FormImplementers.cs create mode 100644 Pizzeria/Pizzeria/FormImplementers.resx diff --git a/Pizzeria/Pizzeria/FormImplementer.Designer.cs b/Pizzeria/Pizzeria/FormImplementer.Designer.cs new file mode 100644 index 0000000..720a9af --- /dev/null +++ b/Pizzeria/Pizzeria/FormImplementer.Designer.cs @@ -0,0 +1,166 @@ +namespace Pizzeria +{ + 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() + { + this.textBoxFIO = new System.Windows.Forms.TextBox(); + this.labelFIO = new System.Windows.Forms.Label(); + this.textBoxPassword = new System.Windows.Forms.TextBox(); + this.labelPassword = new System.Windows.Forms.Label(); + this.labelWorkExperience = new System.Windows.Forms.Label(); + this.numericUpDownWorkExperience = new System.Windows.Forms.NumericUpDown(); + this.numericUpDownQualification = new System.Windows.Forms.NumericUpDown(); + this.labelQualification = new System.Windows.Forms.Label(); + this.buttonCancel = new System.Windows.Forms.Button(); + this.buttonSave = new System.Windows.Forms.Button(); + ((System.ComponentModel.ISupportInitialize)(this.numericUpDownWorkExperience)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.numericUpDownQualification)).BeginInit(); + this.SuspendLayout(); + // + // textBoxFIO + // + this.textBoxFIO.Location = new System.Drawing.Point(157, 12); + this.textBoxFIO.Name = "textBoxFIO"; + this.textBoxFIO.Size = new System.Drawing.Size(382, 27); + this.textBoxFIO.TabIndex = 3; + // + // labelFIO + // + this.labelFIO.AutoSize = true; + this.labelFIO.Location = new System.Drawing.Point(12, 15); + this.labelFIO.Name = "labelFIO"; + this.labelFIO.Size = new System.Drawing.Size(139, 20); + this.labelFIO.TabIndex = 2; + this.labelFIO.Text = "ФИО исполнителя:"; + // + // textBoxPassword + // + this.textBoxPassword.Location = new System.Drawing.Point(157, 50); + this.textBoxPassword.Name = "textBoxPassword"; + this.textBoxPassword.Size = new System.Drawing.Size(205, 27); + this.textBoxPassword.TabIndex = 5; + // + // labelPassword + // + this.labelPassword.AutoSize = true; + this.labelPassword.Location = new System.Drawing.Point(12, 53); + this.labelPassword.Name = "labelPassword"; + this.labelPassword.Size = new System.Drawing.Size(65, 20); + this.labelPassword.TabIndex = 4; + this.labelPassword.Text = "Пароль:"; + // + // labelWorkExperience + // + this.labelWorkExperience.AutoSize = true; + this.labelWorkExperience.Location = new System.Drawing.Point(12, 99); + this.labelWorkExperience.Name = "labelWorkExperience"; + this.labelWorkExperience.Size = new System.Drawing.Size(105, 20); + this.labelWorkExperience.TabIndex = 6; + this.labelWorkExperience.Text = "Опыт работы:"; + // + // numericUpDownWorkExperience + // + this.numericUpDownWorkExperience.Location = new System.Drawing.Point(157, 97); + this.numericUpDownWorkExperience.Name = "numericUpDownWorkExperience"; + this.numericUpDownWorkExperience.Size = new System.Drawing.Size(124, 27); + this.numericUpDownWorkExperience.TabIndex = 8; + // + // numericUpDownQualification + // + this.numericUpDownQualification.Location = new System.Drawing.Point(157, 142); + this.numericUpDownQualification.Name = "numericUpDownQualification"; + this.numericUpDownQualification.Size = new System.Drawing.Size(124, 27); + this.numericUpDownQualification.TabIndex = 10; + // + // labelQualification + // + this.labelQualification.AutoSize = true; + this.labelQualification.Location = new System.Drawing.Point(12, 144); + this.labelQualification.Name = "labelQualification"; + this.labelQualification.Size = new System.Drawing.Size(114, 20); + this.labelQualification.TabIndex = 9; + this.labelQualification.Text = "Квалификация:"; + // + // buttonCancel + // + this.buttonCancel.Location = new System.Drawing.Point(422, 203); + this.buttonCancel.Name = "buttonCancel"; + this.buttonCancel.Size = new System.Drawing.Size(136, 40); + this.buttonCancel.TabIndex = 12; + this.buttonCancel.Text = "Отмена"; + this.buttonCancel.UseVisualStyleBackColor = true; + this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click); + // + // buttonSave + // + this.buttonSave.Location = new System.Drawing.Point(265, 203); + this.buttonSave.Name = "buttonSave"; + this.buttonSave.Size = new System.Drawing.Size(130, 40); + this.buttonSave.TabIndex = 11; + this.buttonSave.Text = "Сохранить"; + this.buttonSave.UseVisualStyleBackColor = true; + this.buttonSave.Click += new System.EventHandler(this.buttonSave_Click); + // + // FormImplementer + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(570, 255); + this.Controls.Add(this.buttonCancel); + this.Controls.Add(this.buttonSave); + this.Controls.Add(this.numericUpDownQualification); + this.Controls.Add(this.labelQualification); + this.Controls.Add(this.numericUpDownWorkExperience); + this.Controls.Add(this.labelWorkExperience); + this.Controls.Add(this.textBoxPassword); + this.Controls.Add(this.labelPassword); + this.Controls.Add(this.textBoxFIO); + this.Controls.Add(this.labelFIO); + this.Name = "FormImplementer"; + this.Text = "Исполнитель"; + this.Load += new System.EventHandler(this.FormImplementer_Load); + ((System.ComponentModel.ISupportInitialize)(this.numericUpDownWorkExperience)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.numericUpDownQualification)).EndInit(); + this.ResumeLayout(false); + this.PerformLayout(); + } + + #endregion + + private TextBox textBoxFIO; + private Label labelFIO; + private TextBox textBoxPassword; + private Label labelPassword; + private Label labelWorkExperience; + private NumericUpDown numericUpDownWorkExperience; + private NumericUpDown numericUpDownQualification; + private Label labelQualification; + private Button buttonCancel; + private Button buttonSave; + } +} \ No newline at end of file diff --git a/Pizzeria/Pizzeria/FormImplementer.cs b/Pizzeria/Pizzeria/FormImplementer.cs new file mode 100644 index 0000000..1bd0615 --- /dev/null +++ b/Pizzeria/Pizzeria/FormImplementer.cs @@ -0,0 +1,94 @@ +using Microsoft.Extensions.Logging; +using PizzeriaContracts.BindingModels; +using PizzeriaContracts.BusinessLogicsContracts; +using PizzeriaContracts.SearchModels; + +namespace Pizzeria +{ + 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 FormImplementer_Load(object sender, EventArgs e) + { + if (_id.HasValue) + { + try + { + _logger.LogInformation("Получение исполнителя"); + var view = _logic.ReadElement(new ImplementerSearchModel + { + Id = _id.Value + }); + if (view != null) + { + textBoxFIO.Text = view.ImplementerFIO; + textBoxPassword.Text = view.Password; + numericUpDownWorkExperience.Value = view.WorkExperience; + numericUpDownQualification.Value = view.Qualification; + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения исполнителя"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + + private void buttonSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxFIO.Text)) + { + MessageBox.Show("Заполните ФИО", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (string.IsNullOrEmpty(textBoxPassword.Text)) + { + MessageBox.Show("Заполните пароль", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Сохранение исполнителя"); + try + { + var model = new ImplementerBindingModel + { + Id = _id ?? 0, + ImplementerFIO = textBoxFIO.Text, + Password = textBoxPassword.Text, + WorkExperience = (int)numericUpDownWorkExperience.Value, + Qualification = (int)numericUpDownQualification.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(); + } + } +} diff --git a/Pizzeria/Pizzeria/FormImplementer.resx b/Pizzeria/Pizzeria/FormImplementer.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/Pizzeria/Pizzeria/FormImplementer.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/Pizzeria/Pizzeria/FormImplementers.Designer.cs b/Pizzeria/Pizzeria/FormImplementers.Designer.cs new file mode 100644 index 0000000..724db3e --- /dev/null +++ b/Pizzeria/Pizzeria/FormImplementers.Designer.cs @@ -0,0 +1,129 @@ +namespace Pizzeria +{ + 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() + { + this.ToolsPanel = new System.Windows.Forms.Panel(); + this.buttonRef = new System.Windows.Forms.Button(); + this.buttonDel = new System.Windows.Forms.Button(); + this.buttonUpd = new System.Windows.Forms.Button(); + this.buttonAdd = new System.Windows.Forms.Button(); + this.dataGridView = new System.Windows.Forms.DataGridView(); + this.ToolsPanel.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); + this.SuspendLayout(); + // + // ToolsPanel + // + this.ToolsPanel.Controls.Add(this.buttonRef); + this.ToolsPanel.Controls.Add(this.buttonDel); + this.ToolsPanel.Controls.Add(this.buttonUpd); + this.ToolsPanel.Controls.Add(this.buttonAdd); + this.ToolsPanel.Location = new System.Drawing.Point(608, 12); + this.ToolsPanel.Name = "ToolsPanel"; + this.ToolsPanel.Size = new System.Drawing.Size(180, 426); + this.ToolsPanel.TabIndex = 3; + // + // buttonRef + // + this.buttonRef.Location = new System.Drawing.Point(31, 206); + this.buttonRef.Name = "buttonRef"; + this.buttonRef.Size = new System.Drawing.Size(126, 36); + this.buttonRef.TabIndex = 3; + this.buttonRef.Text = "Обновить"; + this.buttonRef.UseVisualStyleBackColor = true; + this.buttonRef.Click += new System.EventHandler(this.buttonRef_Click); + // + // buttonDel + // + this.buttonDel.Location = new System.Drawing.Point(31, 142); + this.buttonDel.Name = "buttonDel"; + this.buttonDel.Size = new System.Drawing.Size(126, 36); + this.buttonDel.TabIndex = 2; + this.buttonDel.Text = "Удалить"; + this.buttonDel.UseVisualStyleBackColor = true; + this.buttonDel.Click += new System.EventHandler(this.buttonDel_Click); + // + // buttonUpd + // + this.buttonUpd.Location = new System.Drawing.Point(31, 76); + this.buttonUpd.Name = "buttonUpd"; + this.buttonUpd.Size = new System.Drawing.Size(126, 36); + this.buttonUpd.TabIndex = 1; + this.buttonUpd.Text = "Изменить"; + this.buttonUpd.UseVisualStyleBackColor = true; + this.buttonUpd.Click += new System.EventHandler(this.buttonUpd_Click); + // + // buttonAdd + // + this.buttonAdd.Location = new System.Drawing.Point(31, 16); + this.buttonAdd.Name = "buttonAdd"; + this.buttonAdd.Size = new System.Drawing.Size(126, 36); + this.buttonAdd.TabIndex = 0; + this.buttonAdd.Text = "Добавить"; + this.buttonAdd.UseVisualStyleBackColor = true; + this.buttonAdd.Click += new System.EventHandler(this.buttonAdd_Click); + // + // dataGridView + // + this.dataGridView.AllowUserToAddRows = false; + this.dataGridView.AllowUserToDeleteRows = false; + this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView.Location = new System.Drawing.Point(12, 12); + this.dataGridView.Name = "dataGridView"; + this.dataGridView.ReadOnly = true; + this.dataGridView.RowHeadersWidth = 51; + this.dataGridView.RowTemplate.Height = 29; + this.dataGridView.Size = new System.Drawing.Size(590, 426); + this.dataGridView.TabIndex = 2; + // + // FormImplementers + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 450); + this.Controls.Add(this.ToolsPanel); + this.Controls.Add(this.dataGridView); + this.Name = "FormImplementers"; + this.Text = "Исполнители"; + this.Load += new System.EventHandler(this.FormImplementers_Load); + this.ToolsPanel.ResumeLayout(false); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit(); + this.ResumeLayout(false); + } + + #endregion + + private Panel ToolsPanel; + private Button buttonRef; + private Button buttonDel; + private Button buttonUpd; + private Button buttonAdd; + private DataGridView dataGridView; + } +} \ No newline at end of file diff --git a/Pizzeria/Pizzeria/FormImplementers.cs b/Pizzeria/Pizzeria/FormImplementers.cs new file mode 100644 index 0000000..f4d2031 --- /dev/null +++ b/Pizzeria/Pizzeria/FormImplementers.cs @@ -0,0 +1,108 @@ +using Microsoft.Extensions.Logging; +using PizzeriaContracts.BindingModels; +using PizzeriaContracts.BusinessLogicsContracts; + +namespace Pizzeria +{ + public partial class FormImplementers : Form + { + private readonly ILogger _logger; + private readonly IImplementerLogic _logic; + + public FormImplementers(ILogger logger, IImplementerLogic implementerLogic) + { + InitializeComponent(); + _logger = logger; + _logic = implementerLogic; + } + + 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); + } + } + + private void FormImplementers_Load(object sender, EventArgs e) + { + LoadData(); + } + + private void buttonAdd_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 buttonUpd_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 buttonDel_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 buttonRef_Click(object sender, EventArgs e) + { + LoadData(); + } + } +} diff --git a/Pizzeria/Pizzeria/FormImplementers.resx b/Pizzeria/Pizzeria/FormImplementers.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/Pizzeria/Pizzeria/FormImplementers.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/Pizzeria/Pizzeria/Program.cs b/Pizzeria/Pizzeria/Program.cs index e788c1d..10bd964 100644 --- a/Pizzeria/Pizzeria/Program.cs +++ b/Pizzeria/Pizzeria/Program.cs @@ -47,6 +47,7 @@ namespace Pizzeria services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); -- 2.25.1 From 8a56f8224674a1a069eced9b606c1f1b2b4d97c8 Mon Sep 17 00:00:00 2001 From: revengel66 Date: Fri, 21 Jun 2024 16:57:52 +0400 Subject: [PATCH 14/16] end 6 lab --- Pizzeria/Pizzeria/FormMain.Designer.cs | 76 ++++-- Pizzeria/Pizzeria/FormMain.cs | 20 +- .../BusinessLogic/OrderLogic.cs | 92 +++---- .../Implements/OrderStorage.cs | 92 ++++++- .../20240621122250_ImplementorAdd.Designer.cs | 257 ++++++++++++++++++ .../20240621122250_ImplementorAdd.cs | 67 +++++ .../PizzeriaDatabaseModelSnapshot.cs | 43 +++ 7 files changed, 565 insertions(+), 82 deletions(-) create mode 100644 Pizzeria/PizzeriaDatabaseImplement/Migrations/20240621122250_ImplementorAdd.Designer.cs create mode 100644 Pizzeria/PizzeriaDatabaseImplement/Migrations/20240621122250_ImplementorAdd.cs diff --git a/Pizzeria/Pizzeria/FormMain.Designer.cs b/Pizzeria/Pizzeria/FormMain.Designer.cs index 84d49ec..47f8872 100644 --- a/Pizzeria/Pizzeria/FormMain.Designer.cs +++ b/Pizzeria/Pizzeria/FormMain.Designer.cs @@ -33,10 +33,12 @@ компоненты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(); ButtonIssuedOrder = new Button(); ButtonOrderReady = new Button(); @@ -50,70 +52,83 @@ // 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.Padding = new Padding(7, 3, 0, 3); - menuStrip.Size = new Size(1372, 30); + menuStrip.Size = new Size(1200, 24); menuStrip.TabIndex = 0; menuStrip.Text = "Справочники:"; // // справочкини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(120, 24); + справочкиниToolStripMenuItem.Size = new Size(97, 20); справочкиниToolStripMenuItem.Text = "Справочники:"; // // компонентыToolStripMenuItem // компонентыToolStripMenuItem.Name = "компонентыToolStripMenuItem"; - компонентыToolStripMenuItem.Size = new Size(186, 26); + компонентыToolStripMenuItem.Size = new Size(180, 22); компонентыToolStripMenuItem.Text = "Ингредиенты"; компонентыToolStripMenuItem.Click += ИнгредиентыToolStripMenuItem_Click; // // изделияToolStripMenuItem // изделияToolStripMenuItem.Name = "изделияToolStripMenuItem"; - изделияToolStripMenuItem.Size = new Size(186, 26); + изделияToolStripMenuItem.Size = new Size(180, 22); изделияToolStripMenuItem.Text = "Пиццы"; изделияToolStripMenuItem.Click += ПиццыToolStripMenuItem_Click; // // клиентыToolStripMenuItem // клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; - клиентыToolStripMenuItem.Size = new Size(186, 26); + клиентыToolStripMenuItem.Size = new Size(180, 22); клиентыToolStripMenuItem.Text = "Клиенты"; клиентыToolStripMenuItem.Click += клиентыToolStripMenuItem_Click; // + // исполнителиToolStripMenuItem + // + исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; + исполнителиToolStripMenuItem.Size = new Size(180, 22); + исполнители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(60, 20); отчётыToolStripMenuItem.Text = "Отчёты"; // // списокИзделийToolStripMenuItem // списокИзделийToolStripMenuItem.Name = "списокИзделийToolStripMenuItem"; - списокИзделийToolStripMenuItem.Size = new Size(276, 26); + списокИзделийToolStripMenuItem.Size = new Size(218, 22); списокИзделийToolStripMenuItem.Text = "Список изделий"; списокИзделийToolStripMenuItem.Click += списокИзделийToolStripMenuItem_Click; // // компонентыПоИзделиямToolStripMenuItem // компонентыПоИзделиямToolStripMenuItem.Name = "компонентыПоИзделиямToolStripMenuItem"; - компонентыПоИзделиямToolStripMenuItem.Size = new Size(276, 26); + компонентыПоИзделиямToolStripMenuItem.Size = new Size(218, 22); компонентыПоИзделиямToolStripMenuItem.Text = "Компоненты по изделиям"; компонентыПоИзделиямToolStripMenuItem.Click += компонентыПоИзделиямToolStripMenuItem_Click; // // списокЗаказовToolStripMenuItem // списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem"; - списокЗаказовToolStripMenuItem.Size = new Size(276, 26); + списокЗаказовToolStripMenuItem.Size = new Size(218, 22); списокЗаказовToolStripMenuItem.Text = "Список заказов"; списокЗаказовToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click; // + // запускРаботToolStripMenuItem + // + запускРаботToolStripMenuItem.Name = "запускРаботToolStripMenuItem"; + запускРаботToolStripMenuItem.Size = new Size(92, 20); + запускРаботToolStripMenuItem.Text = "Запуск работ"; + запускРаботToolStripMenuItem.Click += запускРаботToolStripMenuItem_Click; + // // dataGridView // dataGridView.AllowUserToAddRows = false; @@ -121,8 +136,7 @@ dataGridView.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; dataGridView.BackgroundColor = SystemColors.ControlLightLight; dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; - dataGridView.Location = new Point(0, 36); - dataGridView.Margin = new Padding(3, 4, 3, 4); + dataGridView.Location = new Point(0, 27); dataGridView.MultiSelect = false; dataGridView.Name = "dataGridView"; dataGridView.ReadOnly = true; @@ -130,15 +144,16 @@ dataGridView.RowHeadersWidth = 51; dataGridView.RowTemplate.Height = 25; dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; - dataGridView.Size = new Size(1113, 483); + dataGridView.Size = new Size(974, 362); dataGridView.TabIndex = 0; // // ButtonIssuedOrder // ButtonIssuedOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; - ButtonIssuedOrder.Location = new Point(1143, 247); + ButtonIssuedOrder.Location = new Point(1000, 185); + ButtonIssuedOrder.Margin = new Padding(3, 2, 3, 2); ButtonIssuedOrder.Name = "ButtonIssuedOrder"; - ButtonIssuedOrder.Size = new Size(205, 43); + ButtonIssuedOrder.Size = new Size(179, 32); ButtonIssuedOrder.TabIndex = 8; ButtonIssuedOrder.Text = "Заказ выдан"; ButtonIssuedOrder.UseVisualStyleBackColor = true; @@ -147,9 +162,10 @@ // ButtonOrderReady // ButtonOrderReady.Anchor = AnchorStyles.Top | AnchorStyles.Right; - ButtonOrderReady.Location = new Point(1143, 185); + ButtonOrderReady.Location = new Point(1000, 139); + ButtonOrderReady.Margin = new Padding(3, 2, 3, 2); ButtonOrderReady.Name = "ButtonOrderReady"; - ButtonOrderReady.Size = new Size(205, 43); + ButtonOrderReady.Size = new Size(179, 32); ButtonOrderReady.TabIndex = 7; ButtonOrderReady.Text = "Заказ готов"; ButtonOrderReady.UseVisualStyleBackColor = true; @@ -158,9 +174,10 @@ // ButtonnTakeOrderInWork // ButtonnTakeOrderInWork.Anchor = AnchorStyles.Top | AnchorStyles.Right; - ButtonnTakeOrderInWork.Location = new Point(1143, 124); + ButtonnTakeOrderInWork.Location = new Point(1000, 93); + ButtonnTakeOrderInWork.Margin = new Padding(3, 2, 3, 2); ButtonnTakeOrderInWork.Name = "ButtonnTakeOrderInWork"; - ButtonnTakeOrderInWork.Size = new Size(205, 43); + ButtonnTakeOrderInWork.Size = new Size(179, 32); ButtonnTakeOrderInWork.TabIndex = 6; ButtonnTakeOrderInWork.Text = "Отдать на выполнение"; ButtonnTakeOrderInWork.UseVisualStyleBackColor = true; @@ -169,9 +186,10 @@ // ButtonCreateOrder // ButtonCreateOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; - ButtonCreateOrder.Location = new Point(1143, 63); + ButtonCreateOrder.Location = new Point(1000, 47); + ButtonCreateOrder.Margin = new Padding(3, 2, 3, 2); ButtonCreateOrder.Name = "ButtonCreateOrder"; - ButtonCreateOrder.Size = new Size(205, 43); + ButtonCreateOrder.Size = new Size(179, 32); ButtonCreateOrder.TabIndex = 5; ButtonCreateOrder.Text = "Создать заказ"; ButtonCreateOrder.UseVisualStyleBackColor = true; @@ -180,9 +198,10 @@ // buttonRef_Click // buttonRef_Click.Anchor = AnchorStyles.Top | AnchorStyles.Right; - buttonRef_Click.Location = new Point(1143, 308); + buttonRef_Click.Location = new Point(1000, 231); + buttonRef_Click.Margin = new Padding(3, 2, 3, 2); buttonRef_Click.Name = "buttonRef_Click"; - buttonRef_Click.Size = new Size(205, 43); + buttonRef_Click.Size = new Size(179, 32); buttonRef_Click.TabIndex = 8; buttonRef_Click.Text = "Обновить список"; buttonRef_Click.UseVisualStyleBackColor = true; @@ -190,9 +209,9 @@ // // FormMain // - AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1372, 520); + ClientSize = new Size(1200, 390); Controls.Add(buttonRef_Click); Controls.Add(ButtonIssuedOrder); Controls.Add(ButtonOrderReady); @@ -201,7 +220,6 @@ Controls.Add(dataGridView); Controls.Add(menuStrip); MainMenuStrip = menuStrip; - Margin = new Padding(3, 4, 3, 4); Name = "FormMain"; Text = "Пиццерия"; Load += FormMain_Load; @@ -229,5 +247,7 @@ private ToolStripMenuItem компонентыПоИзделиямToolStripMenuItem; private ToolStripMenuItem списокЗаказовToolStripMenuItem; private ToolStripMenuItem клиентыToolStripMenuItem; + private ToolStripMenuItem исполнителиToolStripMenuItem; + private ToolStripMenuItem запускРаботToolStripMenuItem; } } \ No newline at end of file diff --git a/Pizzeria/Pizzeria/FormMain.cs b/Pizzeria/Pizzeria/FormMain.cs index 0d702f5..e14b39c 100644 --- a/Pizzeria/Pizzeria/FormMain.cs +++ b/Pizzeria/Pizzeria/FormMain.cs @@ -8,12 +8,14 @@ namespace Pizzeria private readonly ILogger _logger; private readonly IOrderLogic _orderLogic; private readonly IReportLogic _reportLogic; - public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic) + private readonly IWorkProcess _workProcess; + public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess) { InitializeComponent(); _logger = logger; _orderLogic = orderLogic; _reportLogic = reportLogic; + _workProcess = workProcess; } private void FormMain_Load(object sender, EventArgs e) { @@ -29,6 +31,7 @@ namespace Pizzeria dataGridView.DataSource = list; dataGridView.Columns["PizzaId"].Visible = false; dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["ImplementerId"].Visible = false; dataGridView.Columns["PizzaName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; } _logger.LogInformation("Загрузка заказов"); @@ -173,6 +176,21 @@ namespace Pizzeria 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 запускРабот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/Pizzeria/PizzeriaBusinessLogic/BusinessLogic/OrderLogic.cs b/Pizzeria/PizzeriaBusinessLogic/BusinessLogic/OrderLogic.cs index c51b134..9920d77 100644 --- a/Pizzeria/PizzeriaBusinessLogic/BusinessLogic/OrderLogic.cs +++ b/Pizzeria/PizzeriaBusinessLogic/BusinessLogic/OrderLogic.cs @@ -5,7 +5,6 @@ using PizzeriaContracts.SearchModels; using PizzeriaContracts.StorageContracts; using PizzeriaContracts.ViewModels; using PizzeriaDataModels.Enums; -using System.Xml.Linq; namespace PizzeriaBusinessLogic.BusinessLogic { @@ -73,7 +72,10 @@ namespace PizzeriaBusinessLogic.BusinessLogic public bool TakeOrderInWork(OrderBindingModel model) { - return ChangeStatus(model, OrderStatus.Выполняется); + lock (_locker) + { + return ChangeStatus(model, OrderStatus.Выполняется); + } } public bool FinishOrder(OrderBindingModel model) @@ -85,56 +87,47 @@ namespace PizzeriaBusinessLogic.BusinessLogic { return ChangeStatus(model, OrderStatus.Выдан); } - public bool ChangeStatus(OrderBindingModel model, OrderStatus status) + private bool ChangeStatus(OrderBindingModel model, OrderStatus requiredStatus) { CheckModel(model, false); - - var searchOrder = new OrderSearchModel { Id = model.Id }; - var order = _orderStorage.GetElement(searchOrder); - - if (order == null) + var element = _orderStorage.GetElement(new OrderSearchModel() { - throw new ArgumentNullException(nameof(order)); - } - model.PizzaId = order.PizzaId; - model.Count = order.Count; - model.Sum = order.Count; - model.DateCreate = order.DateCreate; - model.DateImplement = order.DateImplement; - model.Status = order.Status; - - if (model.Status != status - 1) + Id = model.Id + }); + if (element == null) { - _logger.LogWarning("Status update to " + status + " operation failed"); - return false; + throw new InvalidOperationException(nameof(element)); } - model.Status = status; - - if (order.ImplementerId.HasValue) + model.DateCreate = element.DateCreate; + model.PizzaId = element.PizzaId; + model.DateImplement = element.DateImplement; + model.ClientId = element.ClientId; + if (!model.ImplementerId.HasValue) { - model.ImplementerId = order.ImplementerId; + model.ImplementerId = element.ImplementerId; } - if (model.Status == OrderStatus.Выдан) + model.Status = element.Status; + model.Count = element.Count; + model.Sum = element.Sum; + if (requiredStatus - model.Status == 1) { - model.DateImplement = DateTime.Now; + model.Status = requiredStatus; + if (model.Status == OrderStatus.Готов) + { + model.DateImplement = DateTime.Now; + } + if (_orderStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + return true; } - - if (model.Status == OrderStatus.Готов) - { - model.DateImplement = DateTime.Now; - } - if (_orderStorage.Update(model) == null) - { - model.Status--; - _logger.LogWarning("Changing status operation faled"); - return false; - } - return true; - + _logger.LogWarning("Changing status operation faled: Current-{Status}:required-{requiredStatus}.", model.Status, requiredStatus); + throw new InvalidOperationException($"Невозможно приствоить статус {requiredStatus} заказу с текущим статусом {model.Status}"); } private void CheckModel(OrderBindingModel model, bool withParams = true) { - if (model == null) { throw new ArgumentNullException(nameof(model)); @@ -143,23 +136,20 @@ namespace PizzeriaBusinessLogic.BusinessLogic { return; } - if (model.ClientId <= 0) - { - throw new ArgumentNullException("Некорректный идентификатор клиента", nameof(model.ClientId)); - } - if (model.PizzaId <= 0) - { - throw new ArgumentNullException("Некорректный идентификатор пиццы", nameof(model.PizzaId)); - } if (model.Count <= 0) { - throw new ArgumentNullException("В заказе должно быть хотя бы одно пицца", nameof(model.Count)); + throw new ArgumentException("Колличество пиццы в заказе не может быть меньше 1", nameof(model.Count)); } if (model.Sum <= 0) { - throw new ArgumentNullException("Стоимость заказа должна быть больше 0", nameof(model.Sum)); + throw new ArgumentException("Стоимость заказа на может быть меньше 1", nameof(model.Sum)); } - _logger.LogInformation("Order. Id: {Id}. Sum: {Sum}. PizzaId: {PizzaId}. PizzaCount: {Count}", model.Id, model.Sum, model.PizzaId, model.Count); + if (model.DateImplement.HasValue && model.DateImplement < model.DateCreate) + { + throw new ArithmeticException($"Дата выдачи заказа {model.DateImplement} не может быть раньше даты его создания {model.DateCreate}"); + } + _logger.LogInformation("Pizza. PizzaId:{PizzaId}.Count:{Count}.Sum:{Sum}Id:{Id}", + model.PizzaId, model.Count, model.Sum, model.Id); } } } diff --git a/Pizzeria/PizzeriaDatabaseImplement/Implements/OrderStorage.cs b/Pizzeria/PizzeriaDatabaseImplement/Implements/OrderStorage.cs index f81c544..4a4c365 100644 --- a/Pizzeria/PizzeriaDatabaseImplement/Implements/OrderStorage.cs +++ b/Pizzeria/PizzeriaDatabaseImplement/Implements/OrderStorage.cs @@ -1,4 +1,4 @@ -using PizzeriaContracts.BindingModels; +/*using PizzeriaContracts.BindingModels; using PizzeriaContracts.SearchModels; using PizzeriaContracts.ViewModels; using PizzeriaDatabaseImplement.Models; @@ -137,4 +137,92 @@ namespace PizzeriaDatabaseImplement.Implements return null; } } -} \ No newline at end of file +} +*/ + +using PizzeriaContracts.BindingModels; +using PizzeriaContracts.SearchModels; +using PizzeriaContracts.ViewModels; +using PizzeriaDatabaseImplement.Models; +using Microsoft.EntityFrameworkCore; +using PizzeriaContracts.StorageContracts; + +namespace PizzeriaDatabaseImplement.Implements +{ + public class OrderStorage : IOrderStorage + { + public List GetFullList() + { + using var context = new PizzeriaDatabase(); + return context.Orders.Include(x => x.Pizza).Include(x => x.Client).Include(y => y.Implementer).Select(x => x.GetViewModel).ToList(); + } + + public List GetFilteredList(OrderSearchModel model) + { + using var context = new PizzeriaDatabase(); + if ((!model.DateFrom.HasValue || !model.DateTo.HasValue) && !model.ClientId.HasValue && !model.Status.HasValue) + { + return new(); + } + return context.Orders.Include(x => x.Pizza).Include(x => x.Client).Include(x => x.Implementer).Where(x => + (model.DateFrom.HasValue && model.DateTo.HasValue && x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo) || + (model.ClientId.HasValue && x.ClientId == model.ClientId) || + (model.Status.HasValue && x.Status == model.Status)) + .Select(x => x.GetViewModel).ToList(); + } + + public OrderViewModel? GetElement(OrderSearchModel model) + { + if (!model.Id.HasValue && (!model.ImplementerId.HasValue || !model.Status.HasValue)) + { + return new(); + } + using var context = new PizzeriaDatabase(); + return context.Orders.Include(x => x.Pizza).Include(x => x.Client).Include(x => x.Implementer).FirstOrDefault(x => + (model.Id.HasValue && x.Id == model.Id) || + (model.ImplementerId.HasValue && x.ImplementerId == model.ImplementerId && x.Status == model.Status)) + ?.GetViewModel; + } + + public OrderViewModel? Insert(OrderBindingModel model) + { + using var context = new PizzeriaDatabase(); + if (model == null) + return null; + var newOrder = Order.Create(context, model); + if (newOrder == null) + { + return null; + } + context.Orders.Add(newOrder); + context.SaveChanges(); + return newOrder.GetViewModel; + } + + public OrderViewModel? Update(OrderBindingModel model) + { + using var context = new PizzeriaDatabase(); + var order = context.Orders.FirstOrDefault(x => x.Id == model.Id); + if (order == null) + { + return null; + } + order.Update(context, model); + context.SaveChanges(); + return order.GetViewModel; + } + + public OrderViewModel? Delete(OrderBindingModel model) + { + using var context = new PizzeriaDatabase(); + var order = context.Orders.FirstOrDefault(rec => rec.Id == model.Id); + if (order != null) + { + context.Orders.Remove(order); + context.SaveChanges(); + return order.GetViewModel; + } + return null; + } + } +} diff --git a/Pizzeria/PizzeriaDatabaseImplement/Migrations/20240621122250_ImplementorAdd.Designer.cs b/Pizzeria/PizzeriaDatabaseImplement/Migrations/20240621122250_ImplementorAdd.Designer.cs new file mode 100644 index 0000000..87e32cc --- /dev/null +++ b/Pizzeria/PizzeriaDatabaseImplement/Migrations/20240621122250_ImplementorAdd.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 PizzeriaDatabaseImplement; + +#nullable disable + +namespace PizzeriaDatabaseImplement.Migrations +{ + [DbContext(typeof(PizzeriaDatabase))] + [Migration("20240621122250_ImplementorAdd")] + partial class ImplementorAdd + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.17") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("PizzeriaDatabaseImplement.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("PizzeriaDatabaseImplement.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("PizzeriaDatabaseImplement.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("PizzeriaDatabaseImplement.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("PizzaId") + .HasColumnType("int"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("Sum") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.HasIndex("ImplementerId"); + + b.HasIndex("PizzaId"); + + b.ToTable("Orders"); + }); + + modelBuilder.Entity("PizzeriaDatabaseImplement.Models.Pizza", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("PizzaName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Price") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.ToTable("Pizzas"); + }); + + modelBuilder.Entity("PizzeriaDatabaseImplement.Models.PizzaComponent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ComponentId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("PizzaId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ComponentId"); + + b.HasIndex("PizzaId"); + + b.ToTable("PizzaComponents"); + }); + + modelBuilder.Entity("PizzeriaDatabaseImplement.Models.Order", b => + { + b.HasOne("PizzeriaDatabaseImplement.Models.Client", "Client") + .WithMany("Orders") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("PizzeriaDatabaseImplement.Models.Implementer", "Implementer") + .WithMany("Order") + .HasForeignKey("ImplementerId"); + + b.HasOne("PizzeriaDatabaseImplement.Models.Pizza", "Pizza") + .WithMany("Orders") + .HasForeignKey("PizzaId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Client"); + + b.Navigation("Implementer"); + + b.Navigation("Pizza"); + }); + + modelBuilder.Entity("PizzeriaDatabaseImplement.Models.PizzaComponent", b => + { + b.HasOne("PizzeriaDatabaseImplement.Models.Component", "Component") + .WithMany("PizzaComponents") + .HasForeignKey("ComponentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("PizzeriaDatabaseImplement.Models.Pizza", "Pizza") + .WithMany("Components") + .HasForeignKey("PizzaId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Component"); + + b.Navigation("Pizza"); + }); + + modelBuilder.Entity("PizzeriaDatabaseImplement.Models.Client", b => + { + b.Navigation("Orders"); + }); + + modelBuilder.Entity("PizzeriaDatabaseImplement.Models.Component", b => + { + b.Navigation("PizzaComponents"); + }); + + modelBuilder.Entity("PizzeriaDatabaseImplement.Models.Implementer", b => + { + b.Navigation("Order"); + }); + + modelBuilder.Entity("PizzeriaDatabaseImplement.Models.Pizza", b => + { + b.Navigation("Components"); + + b.Navigation("Orders"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Pizzeria/PizzeriaDatabaseImplement/Migrations/20240621122250_ImplementorAdd.cs b/Pizzeria/PizzeriaDatabaseImplement/Migrations/20240621122250_ImplementorAdd.cs new file mode 100644 index 0000000..0959b28 --- /dev/null +++ b/Pizzeria/PizzeriaDatabaseImplement/Migrations/20240621122250_ImplementorAdd.cs @@ -0,0 +1,67 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace PizzeriaDatabaseImplement.Migrations +{ + /// + public partial class ImplementorAdd : 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/Pizzeria/PizzeriaDatabaseImplement/Migrations/PizzeriaDatabaseModelSnapshot.cs b/Pizzeria/PizzeriaDatabaseImplement/Migrations/PizzeriaDatabaseModelSnapshot.cs index 8bcc5e6..c8caa3c 100644 --- a/Pizzeria/PizzeriaDatabaseImplement/Migrations/PizzeriaDatabaseModelSnapshot.cs +++ b/Pizzeria/PizzeriaDatabaseImplement/Migrations/PizzeriaDatabaseModelSnapshot.cs @@ -67,6 +67,33 @@ namespace PizzeriaDatabaseImplement.Migrations b.ToTable("Components"); }); + modelBuilder.Entity("PizzeriaDatabaseImplement.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("PizzeriaDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -87,6 +114,9 @@ namespace PizzeriaDatabaseImplement.Migrations b.Property("DateImplement") .HasColumnType("datetime2"); + b.Property("ImplementerId") + .HasColumnType("int"); + b.Property("PizzaId") .HasColumnType("int"); @@ -100,6 +130,8 @@ namespace PizzeriaDatabaseImplement.Migrations b.HasIndex("ClientId"); + b.HasIndex("ImplementerId"); + b.HasIndex("PizzaId"); b.ToTable("Orders"); @@ -159,6 +191,10 @@ namespace PizzeriaDatabaseImplement.Migrations .OnDelete(DeleteBehavior.Cascade) .IsRequired(); + b.HasOne("PizzeriaDatabaseImplement.Models.Implementer", "Implementer") + .WithMany("Order") + .HasForeignKey("ImplementerId"); + b.HasOne("PizzeriaDatabaseImplement.Models.Pizza", "Pizza") .WithMany("Orders") .HasForeignKey("PizzaId") @@ -167,6 +203,8 @@ namespace PizzeriaDatabaseImplement.Migrations b.Navigation("Client"); + b.Navigation("Implementer"); + b.Navigation("Pizza"); }); @@ -199,6 +237,11 @@ namespace PizzeriaDatabaseImplement.Migrations b.Navigation("PizzaComponents"); }); + modelBuilder.Entity("PizzeriaDatabaseImplement.Models.Implementer", b => + { + b.Navigation("Order"); + }); + modelBuilder.Entity("PizzeriaDatabaseImplement.Models.Pizza", b => { b.Navigation("Components"); -- 2.25.1 From 54d9bc4c6a0c6c694ca6c6a3e924d23f802451be Mon Sep 17 00:00:00 2001 From: revengel66 Date: Fri, 21 Jun 2024 17:11:56 +0400 Subject: [PATCH 15/16] edit lab6 --- .../Implements/OrderStorage.cs | 143 +----------------- 1 file changed, 1 insertion(+), 142 deletions(-) diff --git a/Pizzeria/PizzeriaDatabaseImplement/Implements/OrderStorage.cs b/Pizzeria/PizzeriaDatabaseImplement/Implements/OrderStorage.cs index 4a4c365..9328441 100644 --- a/Pizzeria/PizzeriaDatabaseImplement/Implements/OrderStorage.cs +++ b/Pizzeria/PizzeriaDatabaseImplement/Implements/OrderStorage.cs @@ -1,4 +1,4 @@ -/*using PizzeriaContracts.BindingModels; +using PizzeriaContracts.BindingModels; using PizzeriaContracts.SearchModels; using PizzeriaContracts.ViewModels; using PizzeriaDatabaseImplement.Models; @@ -9,148 +9,7 @@ namespace PizzeriaDatabaseImplement.Implements { public class OrderStorage : IOrderStorage { - public List GetFullList() - { - using var context = new PizzeriaDatabase(); - return context.Orders - .Include(x => x.Pizza) - .Include(x => x.Client) - .Include(x => x.Implementer) - .Select(x => x.GetViewModel) - .ToList(); - } - public List GetFilteredList(OrderSearchModel model) - { - using var context = new PizzeriaDatabase(); - if (model.DateFrom.HasValue) - { - return context.Orders - .Include(x => x.Pizza) - .Include(x => x.Client) - .Include(x => x.Implementer) - .Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo) - .Select(x => x.GetViewModel) - .ToList(); - } - if (model.ClientId.HasValue) - { - return context.Orders - .Include(x => x.Pizza) - .Include(x => x.Client) - .Include(x => x.Implementer) - .Where(x => x.ClientId == model.ClientId) - .Select(x => x.GetViewModel) - .ToList(); - } - else if (model.ImplementerId.HasValue) - { - return context.Orders - .Include(x => x.Pizza) - .Include(x => x.Client) - .Include(x => x.Implementer) - .Where(x => x.ImplementerId == model.ImplementerId) - .Select(x => x.GetViewModel) - .ToList(); - } - return context.Orders - .Include(x => x.Pizza) - .Include(x => x.Client) - .Include(x => x.Implementer) - .Where(x => x.Id == model.Id) - .Select(x => x.GetViewModel) - .ToList(); - } - - public OrderViewModel? GetElement(OrderSearchModel model) - { - if (!model.Id.HasValue) - { - return new(); - } - using var context = new PizzeriaDatabase(); - return context.Orders - .Include(x => x.Pizza) - .Include(x => x.Client) - .Include(x => x.Implementer) - .FirstOrDefault(x => - model.ImplementerId.HasValue && x.ImplementerId == model.ImplementerId && model.Status != null && x.Status.Equals(model.Status) - || model.Status == null && model.ImplementerId.HasValue && x.ImplementerId == model.ImplementerId - || model.Id.HasValue && x.Id == model.Id) - ?.GetViewModel; - } - - public OrderViewModel? Insert(OrderBindingModel model) - { - using var context = new PizzeriaDatabase(); - if (model == null) - return null; - var newOrder = Order.Create(context, model); - if (newOrder == null) - { - return null; - } - context.Orders.Add(newOrder); - context.SaveChanges(); - return context.Orders - .Include(x => x.Pizza) - .Include(x => x.Client) - .Include(x => x.Implementer) - .FirstOrDefault(x => x.Id == newOrder.Id) - ?.GetViewModel; - } - - public OrderViewModel? Update(OrderBindingModel model) - { - using var context = new PizzeriaDatabase(); - var order = context.Orders.FirstOrDefault(x => x.Id == model.Id); - if (order == null) - { - return null; - } - order.Update(context,model); - context.SaveChanges(); - return context.Orders - .Include(x => x.Pizza) - .Include(x => x.Client) - .Include(x => x.Implementer) - .FirstOrDefault(x => x.Id == model.Id) - ?.GetViewModel; - } - - public OrderViewModel? Delete(OrderBindingModel model) - { - using var context = new PizzeriaDatabase(); - var order = context.Orders.FirstOrDefault(rec => rec.Id == model.Id); - if (order != null) - { - var deletedElement = context.Orders - .Include(x => x.Pizza) - .Include(x => x.Client) - .Include(x => x.Implementer) - .FirstOrDefault(x => x.Id == model.Id) - ?.GetViewModel; - context.Orders.Remove(order); - context.SaveChanges(); - return deletedElement; - } - return null; - } - } -} -*/ - -using PizzeriaContracts.BindingModels; -using PizzeriaContracts.SearchModels; -using PizzeriaContracts.ViewModels; -using PizzeriaDatabaseImplement.Models; -using Microsoft.EntityFrameworkCore; -using PizzeriaContracts.StorageContracts; - -namespace PizzeriaDatabaseImplement.Implements -{ - public class OrderStorage : IOrderStorage - { public List GetFullList() { using var context = new PizzeriaDatabase(); -- 2.25.1 From 69b2c056c3b4e46cfd040979360aa3681a8af103 Mon Sep 17 00:00:00 2001 From: revengel66 Date: Fri, 21 Jun 2024 17:20:23 +0400 Subject: [PATCH 16/16] edit code --- Pizzeria/PizzeriaListImplement/DataListSingleton.cs | 2 +- Pizzeria/PizzeriaListImplement/Implements/OrderStorage.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Pizzeria/PizzeriaListImplement/DataListSingleton.cs b/Pizzeria/PizzeriaListImplement/DataListSingleton.cs index 230bdf0..366111a 100644 --- a/Pizzeria/PizzeriaListImplement/DataListSingleton.cs +++ b/Pizzeria/PizzeriaListImplement/DataListSingleton.cs @@ -16,7 +16,7 @@ namespace PizzeriaListImplement Orders = new List(); Pizzas = new List(); Clients = new List(); - Implementers = new List(); + Implementers = new List(); } public static DataListSingleton GetInstance() { diff --git a/Pizzeria/PizzeriaListImplement/Implements/OrderStorage.cs b/Pizzeria/PizzeriaListImplement/Implements/OrderStorage.cs index 26894cb..9df05be 100644 --- a/Pizzeria/PizzeriaListImplement/Implements/OrderStorage.cs +++ b/Pizzeria/PizzeriaListImplement/Implements/OrderStorage.cs @@ -63,7 +63,7 @@ namespace PizzeriaListImplement.Implements else if (model.ClientId.HasValue && !model.Id.HasValue) { foreach (var order in _source.Orders) -{ + { if (order.ClientId == model.ClientId) { result.Add(GetViewModel(order)); -- 2.25.1