diff --git a/ConfectionaryBusinessLogic/ImplementerLogic.cs b/ConfectionaryBusinessLogic/ImplementerLogic.cs new file mode 100644 index 0000000..529c4ff --- /dev/null +++ b/ConfectionaryBusinessLogic/ImplementerLogic.cs @@ -0,0 +1,123 @@ +using ConfectioneryContracts.BindingModels; +using ConfectioneryContracts.BusinessLogicsContracts; +using ConfectioneryContracts.SearchModels; +using ConfectioneryContracts.StoragesContract; +using ConfectioneryContracts.ViewModels; +using Microsoft.Extensions.Logging; + +namespace ConfectioneryBusinessLogic +{ + public class ImplementerLogic : IImplementerLogic + { + private readonly ILogger _logger; + private readonly IImplementerStorage _implementerStorage; + public ImplementerLogic(ILogger logger, IImplementerStorage implementerStorage) + { + _logger = logger; + _implementerStorage = implementerStorage; + } + + public bool Create(ImplementerBindingModel model) + { + CheckModel(model); + if (_implementerStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } + + public bool Delete(ImplementerBindingModel model) + { + CheckModel(model, false); + _logger.LogInformation("Delete. Id:{Id}", model.Id); + if (_implementerStorage.Delete(model) == null) + { + _logger.LogWarning("Delete operation failed"); + return false; + } + return true; + } + + public ImplementerViewModel? ReadElement(ImplementerSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + _logger.LogInformation("ReadElement. FIO:{FIO}.Id:{ Id}", + model.ImplementerFIO, model.Id); + var element = _implementerStorage.GetElement(model); + if (element == null) + { + _logger.LogWarning("ReadElement element not found"); + return null; + } + _logger.LogInformation("ReadElement find. Id:{Id}", element.Id); + return element; + } + + public List? ReadList(ImplementerSearchModel? model) + { + _logger.LogInformation("ReadList. FIO:{FIO}.Id:{ Id} ", model?.ImplementerFIO, model?.Id); + var list = (model == null) ? _implementerStorage.GetFullList() : + _implementerStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + _logger.LogInformation("ReadList. Count:{Count}", list.Count); + return list; + } + + public bool Update(ImplementerBindingModel model) + { + CheckModel(model); + if (_implementerStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + return true; + } + + private void CheckModel(ImplementerBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (!withParams) + { + return; + } + if (model.WorkExperience < 0) + { + throw new ArgumentException("Опыт работы не должен быть отрицательным", nameof(model.WorkExperience)); + } + if (model.Qualification < 0) + { + throw new ArgumentException("Квалификация не должна быть отрицательной", nameof(model.Qualification)); + } + if (string.IsNullOrEmpty(model.Password)) + { + throw new ArgumentNullException("Нет пароля исполнителя", nameof(model.ImplementerFIO)); + } + if (string.IsNullOrEmpty(model.ImplementerFIO)) + { + throw new ArgumentNullException("Нет фио исполнителя", nameof(model.ImplementerFIO)); + } + _logger.LogInformation("Implementer. Id: {Id}, FIO: {FIO}", model.Id, model.ImplementerFIO); + var element = _implementerStorage.GetElement(new ImplementerSearchModel + { + ImplementerFIO = model.ImplementerFIO, + }); + if (element != null && element.Id != model.Id) + { + throw new InvalidOperationException("Исполнитель с таким фио уже есть"); + } + } + } +} diff --git a/ConfectionaryBusinessLogic/OrderLogic.cs b/ConfectionaryBusinessLogic/OrderLogic.cs index 3a57520..91d1e44 100644 --- a/ConfectionaryBusinessLogic/OrderLogic.cs +++ b/ConfectionaryBusinessLogic/OrderLogic.cs @@ -94,11 +94,10 @@ namespace ConfectioneryBusinessLogic.BusinessLogics } if ((int)vmodel.Status + 1 != (int)orderStatus) { - throw new ArgumentException($"Попытка перевести заказ не в следующий статус: " + + throw new InvalidOperationException($"Попытка перевести заказ не в следующий статус: " + $"Текущий статус: {vmodel.Status} \n" + $"Планируемый статус: {orderStatus} \n" + - $"Доступный статус: {(OrderStatus)((int)vmodel.Status + 1)}", - nameof(vmodel)); + $"Доступный статус: {(OrderStatus)((int)vmodel.Status + 1)}"); } if (orderStatus == OrderStatus.Готов) { @@ -113,6 +112,8 @@ namespace ConfectioneryBusinessLogic.BusinessLogics model.DateCreate = vmodel.DateCreate; if (model.DateImplement == null) model.DateImplement = vmodel.DateImplement; + if (vmodel.ImplementerId.HasValue) + model.ImplementerId = vmodel.ImplementerId; model.PastryId = vmodel.PastryId; model.Sum = vmodel.Sum; model.Count= vmodel.Count; @@ -123,5 +124,22 @@ namespace ConfectioneryBusinessLogic.BusinessLogics } return true; } - } + + public OrderViewModel? ReadElement(OrderSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + _logger.LogInformation("ReadElement. Id:{ Id}", model.Id); + var element = _orderStorage.GetElement(model); + if (element == null) + { + _logger.LogWarning("ReadElement element not found"); + return null; + } + _logger.LogInformation("ReadElement find. Id:{Id}", element.Id); + return element; + } + } } diff --git a/ConfectionaryBusinessLogic/WorkModeling.cs b/ConfectionaryBusinessLogic/WorkModeling.cs new file mode 100644 index 0000000..5aee2dc --- /dev/null +++ b/ConfectionaryBusinessLogic/WorkModeling.cs @@ -0,0 +1,160 @@ +using ConfectioneryContracts.BindingModels; +using ConfectioneryContracts.BusinessLogicsContracts; +using ConfectioneryContracts.SearchModels; +using ConfectioneryContracts.ViewModels; +using ConfectioneryDataModels.Enums; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ConfectioneryBusinessLogic +{ + 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) + { + // Поскольку у нас могут быть заказы в работе мы не дожны заканчивать работы, если нет Принятых заказов + // Поэтому находим заказы в работе и продолжаем работу, если они есть + var workingOrders = _orderLogic.ReadList(new() { Status = OrderStatus.Выполняется }); + if (workingOrders == null || workingOrders.Count == 0) + { + _logger.LogWarning("DoWork. Orders is null or empty"); + return; + } + else + { + _logger.LogWarning("DoWork. Еще есть заказы в работе. для {Count} заказов", workingOrders.Count); + } + } + else + _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; + } + } + } +} diff --git a/ConfectionaryFileImplement/DataFileSingleton.cs b/ConfectionaryFileImplement/DataFileSingleton.cs index 251fd12..91a4ee0 100644 --- a/ConfectionaryFileImplement/DataFileSingleton.cs +++ b/ConfectionaryFileImplement/DataFileSingleton.cs @@ -11,11 +11,13 @@ namespace ConfectioneryFileImplement private readonly string PastryFileName = "Pastry.xml"; private readonly string ShopFileName = "Shop.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 Pastries { get; private set; } public List Clients { get; private set; } public List Shops { get; private set; } + public List Implementers { get; private set; } public static DataFileSingleton GetInstance() { @@ -30,6 +32,7 @@ namespace ConfectioneryFileImplement public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement); public void SaveClients() => SaveData(Clients, OrderFileName, "Clients", x => x.GetXElement); public void SaveShops() => SaveData(Shops, ShopFileName, "Shops", x => x.GetXElement); + public void SaveImplementers() => SaveData(Orders, ImplementerFileName, "Implementers", x => x.GetXElement); private DataFileSingleton() { @@ -38,6 +41,7 @@ namespace ConfectioneryFileImplement Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!; Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!; Shops = LoadData(ShopFileName, "Shop", x => Shop.Create(x)!)!; + Implementers = LoadData(ImplementerFileName, "Implementer", x => Implementer.Create(x)!)!; } private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) { diff --git a/ConfectionaryFileImplement/Implementer.cs b/ConfectionaryFileImplement/Implementer.cs new file mode 100644 index 0000000..156c3ad --- /dev/null +++ b/ConfectionaryFileImplement/Implementer.cs @@ -0,0 +1,88 @@ +using ConfectioneryContracts.BindingModels; +using ConfectioneryContracts.ViewModels; +using ConfectioneryDataModels; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace ConfectioneryFileImplement +{ + 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/ConfectionaryFileImplement/ImplementerStorage.cs b/ConfectionaryFileImplement/ImplementerStorage.cs new file mode 100644 index 0000000..f64f551 --- /dev/null +++ b/ConfectionaryFileImplement/ImplementerStorage.cs @@ -0,0 +1,90 @@ +using ConfectioneryContracts.BindingModels; +using ConfectioneryContracts.SearchModels; +using ConfectioneryContracts.StoragesContract; +using ConfectioneryContracts.ViewModels; + +namespace ConfectioneryFileImplement +{ + public class ImplementerStorage : IImplementerStorage + { + private readonly DataFileSingleton _source; + public ImplementerStorage() + { + _source = DataFileSingleton.GetInstance(); + } + + public ImplementerViewModel? Delete(ImplementerBindingModel model) + { + var res = _source.Implementers.FirstOrDefault(x => x.Id == model.Id); + if (res != null) + { + _source.Implementers.Remove(res); + _source.SaveImplementers(); + } + return res?.GetViewModel; + } + + public ImplementerViewModel? GetElement(ImplementerSearchModel model) + { + if (model.Id.HasValue) + return _source.Implementers.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; + if (model.ImplementerFIO != null && model.Password != null) + return _source.Implementers + .FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO) + && x.Password.Equals(model.Password)) + ?.GetViewModel; + if (model.ImplementerFIO != null) + return _source.Implementers.FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO))?.GetViewModel; + return null; + } + + public List GetFilteredList(ImplementerSearchModel model) + { + if (model == null) + { + return new(); + } + if (model.Id.HasValue) + { + var res = GetElement(model); + return res != null ? new() { res } : new(); + } + if (model.ImplementerFIO != null) // На случай если фио не будет уникальным (по заданию оно уникально) + { + return _source.Implementers + .Where(x => x.ImplementerFIO.Equals(model.ImplementerFIO)) + .Select(x => x.GetViewModel) + .ToList(); + } + return new(); + } + + public List GetFullList() + { + return _source.Implementers.Select(x => x.GetViewModel).ToList(); + } + + public ImplementerViewModel? Insert(ImplementerBindingModel model) + { + model.Id = _source.Implementers.Count > 0 ? _source.Implementers.Max(x => x.Id) + 1 : 1; + var res = Implementer.Create(model); + if (res != null) + { + _source.Implementers.Add(res); + _source.SaveImplementers(); + } + return res?.GetViewModel; + } + + public ImplementerViewModel? Update(ImplementerBindingModel model) + { + var res = _source.Implementers.FirstOrDefault(x => x.Id == model.Id); + if (res != null) + { + res.Update(model); + _source.SaveImplementers(); + } + return res?.GetViewModel; + } + } +} diff --git a/ConfectionaryFileImplement/Order.cs b/ConfectionaryFileImplement/Order.cs index 177a901..2953eac 100644 --- a/ConfectionaryFileImplement/Order.cs +++ b/ConfectionaryFileImplement/Order.cs @@ -14,6 +14,7 @@ namespace ConfectioneryFileImplement.Models public int ClientId { get; set; } + public int? ImplementerId { get; set; } public int Count { get; private set; } @@ -40,7 +41,8 @@ namespace ConfectioneryFileImplement.Models Status = model.Status, DateCreate = model.DateCreate, DateImplement = model.DateImplement, - Id = model.Id, + ImplementerId = model.ImplementerId, + Id = model.Id, }; } public static Order? Create(XElement element) @@ -59,6 +61,7 @@ namespace ConfectioneryFileImplement.Models PastryId = Convert.ToInt32(element.Element("PastryId")!.Value), ClientId = Convert.ToInt32(element.Element("ClientId")!.Value), DateCreate = Convert.ToDateTime(element.Element("DateCreate")!.Value), + ImplementerId = Convert.ToInt32(element.Element("ImplementerId")!.Value), DateImplement = string.IsNullOrEmpty(dateImplement) ? null : Convert.ToDateTime(dateImplement), }; } @@ -74,20 +77,23 @@ namespace ConfectioneryFileImplement.Models Sum = model.Sum; Status = model.Status; DateCreate = model.DateCreate; + ImplementerId = model.ImplementerId; DateImplement = model.DateImplement; - Id = model.Id; + Id = model.Id; } public OrderViewModel GetViewModel => new() { + ImplementerFIO = DataFileSingleton.GetInstance().Implementers.FirstOrDefault(x => x.Id == ImplementerId)?.ImplementerFIO ?? string.Empty, PastryName = DataFileSingleton.GetInstance().Pastries.FirstOrDefault(x => x.Id == PastryId)?.PastryName ?? string.Empty, ClientFIO = DataFileSingleton.GetInstance().Clients.FirstOrDefault(x => x.Id == ClientId)?.ClientFIO ?? string.Empty, - PastryId = PastryId, + PastryId = PastryId, ClientId = ClientId, Count = Count, Sum = Sum, Status = Status, DateCreate = DateCreate, DateImplement = DateImplement, + ImplementerId = ImplementerId, Id = Id, }; public XElement GetXElement => new("Order", @@ -98,7 +104,8 @@ namespace ConfectioneryFileImplement.Models new XElement("Sum", Sum.ToString()), new XElement("Status", (int)Status), new XElement("DateCreate", DateCreate), - new XElement("DateImplement", DateImplement) + new XElement("DateImplement", DateImplement), + new XElement("ImplementerId", ImplementerId) ); } } diff --git a/ConfectionaryFileImplement/OrderStorage.cs b/ConfectionaryFileImplement/OrderStorage.cs index 266422d..ecd3a9b 100644 --- a/ConfectionaryFileImplement/OrderStorage.cs +++ b/ConfectionaryFileImplement/OrderStorage.cs @@ -28,11 +28,15 @@ namespace ConfectioneryFileImplement public OrderViewModel? GetElement(OrderSearchModel model) { - if (!model.Id.HasValue) - { - return null; - } - return _source.Orders.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)?.GetViewModel; + if (model.ImplementerId.HasValue) + { + return _source.Orders.FirstOrDefault(x => x.ImplementerId == model.ImplementerId)?.GetViewModel; + } + if (!model.Id.HasValue) + { + return null; + } + return _source.Orders.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)?.GetViewModel; } public List GetFilteredList(OrderSearchModel model) @@ -51,7 +55,14 @@ namespace ConfectioneryFileImplement .Select(x => x.GetViewModel) .ToList(); } - var result = GetElement(model); + if (!model.Id.HasValue && model.Status.HasValue) + { + return _source.Orders + .Where(x => x.Status == model.Status) + .Select(x => x.GetViewModel) + .ToList(); + } + var result = GetElement(model); return result != null ? new() { result } : new(); } diff --git a/ConfectionaryListImplement/DataListSingleton.cs b/ConfectionaryListImplement/DataListSingleton.cs index 9e4f485..4dffcdc 100644 --- a/ConfectionaryListImplement/DataListSingleton.cs +++ b/ConfectionaryListImplement/DataListSingleton.cs @@ -9,6 +9,7 @@ namespace ConfectioneryListImplement public List Orders { get; set; } public List Pastry { get; set; } public List Clients { get; set; } + public List Implementers { get; set; } public List Shops { get; set; } private DataListSingleton() @@ -17,6 +18,7 @@ namespace ConfectioneryListImplement Orders = new List(); Pastry = new List(); Clients = new List(); + Implementers = new List(); Shops = new List(); } public static DataListSingleton GetInstance() diff --git a/ConfectionaryListImplement/Implementer.cs b/ConfectionaryListImplement/Implementer.cs new file mode 100644 index 0000000..07b674b --- /dev/null +++ b/ConfectionaryListImplement/Implementer.cs @@ -0,0 +1,55 @@ +using ConfectioneryContracts.BindingModels; +using ConfectioneryContracts.ViewModels; +using ConfectioneryDataModels; + +namespace ConfectioneryListImplement +{ + 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, + }; + } +} diff --git a/ConfectionaryListImplement/ImplementerStorage.cs b/ConfectionaryListImplement/ImplementerStorage.cs new file mode 100644 index 0000000..99ae586 --- /dev/null +++ b/ConfectionaryListImplement/ImplementerStorage.cs @@ -0,0 +1,84 @@ +using ConfectioneryContracts.BindingModels; +using ConfectioneryContracts.SearchModels; +using ConfectioneryContracts.StoragesContract; +using ConfectioneryContracts.ViewModels; + +namespace ConfectioneryListImplement +{ + public class ImplementerStorage : IImplementerStorage + { + private readonly DataListSingleton _source; + public ImplementerStorage() + { + _source = DataListSingleton.GetInstance(); + } + + public ImplementerViewModel? Delete(ImplementerBindingModel model) + { + var res = _source.Implementers.FirstOrDefault(x => x.Id == model.Id); + if (res != null) + { + _source.Implementers.Remove(res); + } + return res?.GetViewModel; + } + + public ImplementerViewModel? GetElement(ImplementerSearchModel model) + { + if (model.Id.HasValue) + return _source.Implementers.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; + if (model.ImplementerFIO != null && model.Password != null) + return _source.Implementers + .FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO) + && x.Password.Equals(model.Password)) + ?.GetViewModel; + if (model.ImplementerFIO != null) + return _source.Implementers.FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO))?.GetViewModel; + return null; + } + + public List GetFilteredList(ImplementerSearchModel model) + { + if (model == null) + { + return new(); + } + if (model.Id.HasValue) + { + var res = GetElement(model); + return res != null ? new() { res } : new(); + } + if (model.ImplementerFIO != null) // На случай если фио не будет уникальным (по заданию оно уникально) + { + return _source.Implementers + .Where(x => x.ImplementerFIO.Equals(model.ImplementerFIO)) + .Select(x => x.GetViewModel) + .ToList(); + } + return new(); + } + + public List GetFullList() + { + return _source.Implementers.Select(x => x.GetViewModel).ToList(); + } + + public ImplementerViewModel? Insert(ImplementerBindingModel model) + { + model.Id = _source.Implementers.Count > 0 ? _source.Implementers.Max(x => x.Id) + 1 : 1; + var res = Implementer.Create(model); + if (res != null) + { + _source.Implementers.Add(res); + } + return res?.GetViewModel; + } + + public ImplementerViewModel? Update(ImplementerBindingModel model) + { + var res = _source.Implementers.FirstOrDefault(x => x.Id == model.Id); + res?.Update(model); + return res?.GetViewModel; + } + } +} diff --git a/ConfectionaryListImplement/Order.cs b/ConfectionaryListImplement/Order.cs index 9954ae8..539716f 100644 --- a/ConfectionaryListImplement/Order.cs +++ b/ConfectionaryListImplement/Order.cs @@ -13,6 +13,8 @@ namespace ConfectioneryListImplement.Models public int ClientId { get; private set; } + public int? ImplementerId { get; private set; } + public int Count { get; private set; } public double Sum { get; private set; } @@ -38,6 +40,7 @@ namespace ConfectioneryListImplement.Models Status = model.Status, DateCreate = model.DateCreate, DateImplement = model.DateImplement, + ImplementerId = model.ImplementerId, Id = model.Id, }; } @@ -53,6 +56,7 @@ namespace ConfectioneryListImplement.Models Status = model.Status; DateCreate = model.DateCreate; DateImplement = model.DateImplement; + ImplementerId = model.ImplementerId; Id = model.Id; } public OrderViewModel GetViewModel => new() @@ -60,7 +64,9 @@ namespace ConfectioneryListImplement.Models PastryId = PastryId, ClientFIO = DataListSingleton.GetInstance().Clients.FirstOrDefault(x => x.Id == ClientId)?.ClientFIO ?? string.Empty, ClientId = ClientId, - Count = Count, + ImplementerId = ImplementerId, + ImplementerFIO = DataListSingleton.GetInstance().Implementers.FirstOrDefault(x => x.Id == ImplementerId)?.ImplementerFIO ?? string.Empty, + Count = Count, Sum = Sum, Status = Status, DateCreate = DateCreate, diff --git a/ConfectionaryListImplement/OrderStorage.cs b/ConfectionaryListImplement/OrderStorage.cs index 8b0558a..7159bf2 100644 --- a/ConfectionaryListImplement/OrderStorage.cs +++ b/ConfectionaryListImplement/OrderStorage.cs @@ -30,6 +30,10 @@ namespace ConfectioneryListImplement public OrderViewModel? GetElement(OrderSearchModel model) { + if (model.ImplementerId.HasValue) + { + return _source.Orders.FirstOrDefault(x => x.ImplementerId == model.ImplementerId)?.GetViewModel; + } if (!model.Id.HasValue) { return null; @@ -61,6 +65,18 @@ namespace ConfectioneryListImplement .Select(x => x.GetViewModel) .ToList(); } + if (!model.Id.HasValue && model.Status.HasValue) + { + return _source.Orders + .Where(x => x.Status == model.Status) + .Select(x => x.GetViewModel) + .ToList(); + } + if (model.ImplementerId.HasValue) + { + var res = _source.Orders.FirstOrDefault(x => x.ImplementerId == model.ImplementerId); + return res != null ? new() { res.GetViewModel } : new(); + } foreach (var order in _source.Orders) { if (order.Id == model.Id) diff --git a/Confectionery/ConfectioneryView.csproj b/Confectionery/ConfectioneryView.csproj index f77aa13..5027ef1 100644 --- a/Confectionery/ConfectioneryView.csproj +++ b/Confectionery/ConfectioneryView.csproj @@ -30,6 +30,9 @@ Form + + Form + diff --git a/Confectionery/FormComponent.cs b/Confectionery/FormComponent.cs index 66747be..c87ec7b 100644 --- a/Confectionery/FormComponent.cs +++ b/Confectionery/FormComponent.cs @@ -27,8 +27,7 @@ namespace ConfectioneryView _logger.LogInformation("Получение компонента"); var view = _logic.ReadElement(new ComponentSearchModel { - Id = - _id.Value + Id = _id.Value }); if (view != null) { diff --git a/Confectionery/FormImplementer.Designer.cs b/Confectionery/FormImplementer.Designer.cs new file mode 100644 index 0000000..736dfc1 --- /dev/null +++ b/Confectionery/FormImplementer.Designer.cs @@ -0,0 +1,173 @@ +namespace ConfectioneryView +{ + 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() + { + label1 = new Label(); + label2 = new Label(); + label3 = new Label(); + label4 = new Label(); + textBoxFio = new TextBox(); + textBoxPassword = new TextBox(); + numericUpDownWorkExperience = new NumericUpDown(); + numericUpDownQualification = new NumericUpDown(); + buttonCancel = new Button(); + buttonSave = new Button(); + ((System.ComponentModel.ISupportInitialize)numericUpDownWorkExperience).BeginInit(); + ((System.ComponentModel.ISupportInitialize)numericUpDownQualification).BeginInit(); + SuspendLayout(); + // + // label1 + // + label1.AutoSize = true; + label1.Location = new Point(79, 12); + label1.Name = "label1"; + label1.Size = new Size(37, 15); + label1.TabIndex = 0; + label1.Text = "ФИО:"; + // + // label2 + // + label2.AutoSize = true; + label2.Location = new Point(69, 41); + label2.Name = "label2"; + label2.Size = new Size(52, 15); + label2.TabIndex = 1; + label2.Text = "Пароль:"; + // + // label3 + // + label3.AutoSize = true; + label3.Location = new Point(78, 68); + label3.Name = "label3"; + label3.Size = new Size(38, 15); + label3.TabIndex = 2; + label3.Text = "Стаж:"; + // + // label4 + // + label4.AutoSize = true; + label4.Location = new Point(25, 97); + label4.Name = "label4"; + label4.Size = new Size(91, 15); + label4.TabIndex = 3; + label4.Text = "Квалификация:"; + // + // textBoxFio + // + textBoxFio.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + textBoxFio.Location = new Point(127, 9); + textBoxFio.Name = "textBoxFio"; + textBoxFio.Size = new Size(271, 23); + textBoxFio.TabIndex = 4; + // + // textBoxPassword + // + textBoxPassword.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + textBoxPassword.Location = new Point(127, 38); + textBoxPassword.Name = "textBoxPassword"; + textBoxPassword.PasswordChar = '*'; + textBoxPassword.Size = new Size(271, 23); + textBoxPassword.TabIndex = 5; + // + // numericUpDownWorkExperience + // + numericUpDownWorkExperience.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + numericUpDownWorkExperience.Location = new Point(127, 66); + numericUpDownWorkExperience.Name = "numericUpDownWorkExperience"; + numericUpDownWorkExperience.Size = new Size(271, 23); + numericUpDownWorkExperience.TabIndex = 6; + // + // numericUpDownQualification + // + numericUpDownQualification.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + numericUpDownQualification.Location = new Point(127, 95); + numericUpDownQualification.Name = "numericUpDownQualification"; + numericUpDownQualification.Size = new Size(271, 23); + numericUpDownQualification.TabIndex = 7; + // + // buttonCancel + // + buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + buttonCancel.Location = new Point(309, 138); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(89, 33); + buttonCancel.TabIndex = 8; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += ButtonCancel_Click; + // + // buttonSave + // + buttonSave.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + buttonSave.Location = new Point(214, 138); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(89, 33); + buttonSave.TabIndex = 9; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += ButtonSave_Click; + // + // FormImplementer + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(410, 183); + Controls.Add(buttonSave); + Controls.Add(buttonCancel); + Controls.Add(numericUpDownQualification); + Controls.Add(numericUpDownWorkExperience); + Controls.Add(textBoxPassword); + Controls.Add(textBoxFio); + Controls.Add(label4); + Controls.Add(label3); + Controls.Add(label2); + Controls.Add(label1); + Name = "FormImplementer"; + Text = "Добавление / Редактирование исполнителя"; + Load += FormImplementer_Load; + ((System.ComponentModel.ISupportInitialize)numericUpDownWorkExperience).EndInit(); + ((System.ComponentModel.ISupportInitialize)numericUpDownQualification).EndInit(); + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Label label1; + private Label label2; + private Label label3; + private Label label4; + private TextBox textBoxFio; + private TextBox textBoxPassword; + private NumericUpDown numericUpDownWorkExperience; + private NumericUpDown numericUpDownQualification; + private Button buttonCancel; + private Button buttonSave; + } +} \ No newline at end of file diff --git a/Confectionery/FormImplementer.cs b/Confectionery/FormImplementer.cs new file mode 100644 index 0000000..9658c89 --- /dev/null +++ b/Confectionery/FormImplementer.cs @@ -0,0 +1,101 @@ +using ConfectioneryContracts.BindingModels; +using ConfectioneryContracts.BusinessLogicsContracts; +using ConfectioneryContracts.SearchModels; +using Microsoft.Extensions.Logging; +using System.Windows.Forms; + +namespace ConfectioneryView +{ + 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; + numericUpDownQualification.Value = view.Qualification; + numericUpDownWorkExperience.Value = view.WorkExperience; + } + } + 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(textBoxPassword.Text)) + { + MessageBox.Show("Заполните пароль", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (string.IsNullOrEmpty(textBoxFio.Text)) + { + MessageBox.Show("Заполните фио", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Сохранение исполнителя"); + try + { + var model = new ImplementerBindingModel + { + Id = _id ?? 0, + ImplementerFIO = textBoxFio.Text, + Password = textBoxPassword.Text, + Qualification = (int)numericUpDownQualification.Value, + WorkExperience = (int)numericUpDownWorkExperience.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/Confectionery/FormImplementer.resx b/Confectionery/FormImplementer.resx new file mode 100644 index 0000000..f298a7b --- /dev/null +++ b/Confectionery/FormImplementer.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/Confectionery/FormMain.Designer.cs b/Confectionery/FormMain.Designer.cs index b0d3579..45078c3 100644 --- a/Confectionery/FormMain.Designer.cs +++ b/Confectionery/FormMain.Designer.cs @@ -1,259 +1,250 @@ namespace ConfectioneryView { - partial class FormMain - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; + partial class FormMain + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } - #region Windows Form Designer generated code + #region Windows Form Designer generated code - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - menuStrip1 = new MenuStrip(); - справочникиToolStripMenuItem = new ToolStripMenuItem(); - pastryToolStripMenuItem = new ToolStripMenuItem(); - componentToolStripMenuItem = new ToolStripMenuItem(); - ShopsToolStripMenuItem = new ToolStripMenuItem(); - reportsToolStripMenuItem = new ToolStripMenuItem(); - reportShopsToolStripMenuItem = new ToolStripMenuItem(); - ShopPastriesToolStripMenuItem = new ToolStripMenuItem(); - ordersToolStripMenuItem = new ToolStripMenuItem(); - dataGridView = new DataGridView(); - buttonCreateOrder = new Button(); - buttonTakeOrderInWork = new Button(); - button2 = new Button(); - button3 = new Button(); - button4 = new Button(); - buttonAddPastryInShop = new Button(); - buttonSellPastry = new Button(); - clientsToolStripMenuItem = new ToolStripMenuItem(); - menuStrip1.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); - SuspendLayout(); - // - // menuStrip1 - // - menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, reportsToolStripMenuItem }); - menuStrip1.Location = new Point(0, 0); - menuStrip1.Name = "menuStrip1"; - menuStrip1.Size = new Size(783, 24); - menuStrip1.TabIndex = 0; - menuStrip1.Text = "menuStrip1"; - // - // справочникиToolStripMenuItem - // - справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { pastryToolStripMenuItem, componentToolStripMenuItem, ShopsToolStripMenuItem }); - справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { pastryToolStripMenuItem, componentToolStripMenuItem, clientsToolStripMenuItem }); - справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; - справочникиToolStripMenuItem.Size = new Size(94, 20); - справочникиToolStripMenuItem.Text = "Справочники"; - // - // pastryToolStripMenuItem - // - pastryToolStripMenuItem.Name = "pastryToolStripMenuItem"; - pastryToolStripMenuItem.Size = new Size(180, 22); - pastryToolStripMenuItem.Text = "Изделия"; - pastryToolStripMenuItem.Click += PastryToolStripMenuItem_Click; - // - // componentToolStripMenuItem - // - componentToolStripMenuItem.Name = "componentToolStripMenuItem"; - componentToolStripMenuItem.Size = new Size(180, 22); - componentToolStripMenuItem.Text = "Компоненты"; - componentToolStripMenuItem.Click += ComponentsToolStripMenuItem_Click; - // - // ShopsToolStripMenuItem - // - ShopsToolStripMenuItem.Name = "ShopsToolStripMenuItem"; - ShopsToolStripMenuItem.Size = new Size(145, 22); - ShopsToolStripMenuItem.Text = "Магазины"; - ShopsToolStripMenuItem.Click += ShopsToolStripMenuItem_Click; - // - // reportsToolStripMenuItem - // - reportsToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { reportShopsToolStripMenuItem, ShopPastriesToolStripMenuItem, ordersToolStripMenuItem }); - reportsToolStripMenuItem.Name = "reportsToolStripMenuItem"; - reportsToolStripMenuItem.Size = new Size(60, 20); - reportsToolStripMenuItem.Text = "Отчеты"; - // - // reportShopsToolStripMenuItem - // - reportShopsToolStripMenuItem.Name = "reportShopsToolStripMenuItem"; - reportShopsToolStripMenuItem.Size = new Size(202, 22); - reportShopsToolStripMenuItem.Text = "Список магазинов"; - reportShopsToolStripMenuItem.Click += ReportShopsToolStripMenuItem_Click; - // - // ShopPastriesToolStripMenuItem - // - ShopPastriesToolStripMenuItem.Name = "ShopPastriesToolStripMenuItem"; - ShopPastriesToolStripMenuItem.Size = new Size(202, 22); - ShopPastriesToolStripMenuItem.Text = "Магазины с изделиями"; - ShopPastriesToolStripMenuItem.Click += ShopPastriesToolStripMenuItem_Click; - // - // ordersToolStripMenuItem - // - ordersToolStripMenuItem.Name = "ordersToolStripMenuItem"; - ordersToolStripMenuItem.Size = new Size(202, 22); - ordersToolStripMenuItem.Text = "Список заказов"; - ordersToolStripMenuItem.Click += OrdersToolStripMenuItem_Click; - // - // dataGridView - // - dataGridView.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; - dataGridView.Location = new Point(12, 27); - dataGridView.Name = "dataGridView"; - dataGridView.RowTemplate.Height = 25; - dataGridView.Size = new Size(606, 399); - dataGridView.TabIndex = 1; - // - // buttonCreateOrder - // - buttonCreateOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; - buttonCreateOrder.Location = new Point(624, 39); - buttonCreateOrder.Name = "buttonCreateOrder"; - buttonCreateOrder.Size = new Size(147, 32); - buttonCreateOrder.TabIndex = 2; - buttonCreateOrder.Text = "Создать заказ"; - buttonCreateOrder.UseVisualStyleBackColor = true; - buttonCreateOrder.Click += ButtonCreateOrder_Click; - // - // buttonTakeOrderInWork - // - buttonTakeOrderInWork.Anchor = AnchorStyles.Top | AnchorStyles.Right; - buttonTakeOrderInWork.Location = new Point(624, 98); - buttonTakeOrderInWork.Name = "buttonTakeOrderInWork"; - buttonTakeOrderInWork.Size = new Size(147, 32); - buttonTakeOrderInWork.TabIndex = 3; - buttonTakeOrderInWork.Text = "Отдать на выполнение"; - buttonTakeOrderInWork.UseVisualStyleBackColor = true; - buttonTakeOrderInWork.Click += ButtonTakeOrderInWork_Click; - // - // button2 - // - button2.Anchor = AnchorStyles.Top | AnchorStyles.Right; - button2.Location = new Point(624, 157); - button2.Name = "button2"; - button2.Size = new Size(147, 32); - button2.TabIndex = 4; - button2.Text = "Заказ готов"; - button2.UseVisualStyleBackColor = true; - button2.Click += ButtonOrderReady_Click; - // - // button3 - // - button3.Anchor = AnchorStyles.Top | AnchorStyles.Right; - button3.Location = new Point(624, 215); - button3.Name = "button3"; - button3.Size = new Size(147, 32); - button3.TabIndex = 5; - button3.Text = "Заказ выдан"; - button3.UseVisualStyleBackColor = true; - button3.Click += ButtonIssuedOrder_Click; - // - // button4 - // - button4.Anchor = AnchorStyles.Top | AnchorStyles.Right; - button4.Location = new Point(624, 274); - button4.Name = "button4"; - button4.Size = new Size(147, 32); - button4.TabIndex = 6; - button4.Text = "Обновить список"; - button4.UseVisualStyleBackColor = true; - button4.Click += ButtonRef_Click; - // - // buttonAddPastryInShop - // - buttonAddPastryInShop.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; - buttonAddPastryInShop.Location = new Point(624, 384); - buttonAddPastryInShop.Name = "buttonAddPastryInShop"; - buttonAddPastryInShop.Size = new Size(147, 31); - buttonAddPastryInShop.TabIndex = 7; - buttonAddPastryInShop.Text = "Пополнение магазина"; - buttonAddPastryInShop.UseVisualStyleBackColor = true; - buttonAddPastryInShop.Click += ButtonAddPastryInShop_Click; - // - // buttonSellPastry - // - buttonSellPastry.Anchor = AnchorStyles.Top | AnchorStyles.Right; - buttonSellPastry.Location = new Point(624, 331); - buttonSellPastry.Name = "buttonSellPastry"; - buttonSellPastry.Size = new Size(147, 31); - buttonSellPastry.TabIndex = 8; - buttonSellPastry.Text = "Продать изделие"; - buttonSellPastry.UseVisualStyleBackColor = true; - buttonSellPastry.Click += ButtonSellPastry_Click; - // - // clientsToolStripMenuItem - // - clientsToolStripMenuItem.Name = "clientsToolStripMenuItem"; - clientsToolStripMenuItem.Size = new Size(180, 22); - clientsToolStripMenuItem.Text = "Клиенты"; - clientsToolStripMenuItem.Click += ClientsToolStripMenuItem_Click; - // - // FormMain - // - AutoScaleDimensions = new SizeF(7F, 15F); - AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(783, 438); - Controls.Add(buttonSellPastry); - Controls.Add(buttonAddPastryInShop); - Controls.Add(button4); - Controls.Add(button3); - Controls.Add(button2); - Controls.Add(buttonTakeOrderInWork); - Controls.Add(buttonCreateOrder); - Controls.Add(dataGridView); - Controls.Add(menuStrip1); - MainMenuStrip = menuStrip1; - Name = "FormMain"; - Text = "Кондитерская"; - Load += FormMain_Load; - menuStrip1.ResumeLayout(false); - menuStrip1.PerformLayout(); - ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); - ResumeLayout(false); - PerformLayout(); - } + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + menuStrip1 = new MenuStrip(); + справочникиToolStripMenuItem = new ToolStripMenuItem(); + pastryToolStripMenuItem = new ToolStripMenuItem(); + componentToolStripMenuItem = new ToolStripMenuItem(); + ShopsToolStripMenuItem = new ToolStripMenuItem(); + clientsToolStripMenuItem = new ToolStripMenuItem(); + reportsToolStripMenuItem = new ToolStripMenuItem(); + reportShopsToolStripMenuItem = new ToolStripMenuItem(); + ShopPastriesToolStripMenuItem = new ToolStripMenuItem(); + ordersToolStripMenuItem = new ToolStripMenuItem(); + dataGridView = new DataGridView(); + buttonCreateOrder = new Button(); + button3 = new Button(); + button4 = new Button(); + buttonAddPastryInShop = new Button(); + ImplementersToolStripMenuItem = new ToolStripMenuItem(); + DoWorkToolStripMenuItem = new ToolStripMenuItem(); + buttonSellPastry = new Button(); + menuStrip1.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // menuStrip1 + // + menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, reportsToolStripMenuItem, DoWorkToolStripMenuItem }); + menuStrip1.Location = new Point(0, 0); + menuStrip1.Name = "menuStrip1"; + menuStrip1.Size = new Size(783, 24); + menuStrip1.TabIndex = 0; + menuStrip1.Text = "menuStrip1"; + // + // справочникиToolStripMenuItem + // + справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { ShopsToolStripMenuItem, pastryToolStripMenuItem, componentToolStripMenuItem, clientsToolStripMenuItem }); + справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; + справочникиToolStripMenuItem.Size = new Size(94, 20); + справочникиToolStripMenuItem.Text = "Справочники"; + // + // pastryToolStripMenuItem + // + pastryToolStripMenuItem.Name = "pastryToolStripMenuItem"; + pastryToolStripMenuItem.Size = new Size(145, 22); + pastryToolStripMenuItem.Text = "Изделия"; + pastryToolStripMenuItem.Click += PastryToolStripMenuItem_Click; + // + // componentToolStripMenuItem + // + componentToolStripMenuItem.Name = "componentToolStripMenuItem"; + componentToolStripMenuItem.Size = new Size(145, 22); + componentToolStripMenuItem.Text = "Компоненты"; + componentToolStripMenuItem.Click += ComponentsToolStripMenuItem_Click; + // + // ShopsToolStripMenuItem + // + ShopsToolStripMenuItem.Name = "ShopsToolStripMenuItem"; + ShopsToolStripMenuItem.Size = new Size(145, 22); + ShopsToolStripMenuItem.Text = "Магазины"; + ShopsToolStripMenuItem.Click += ShopsToolStripMenuItem_Click; + // + // clientsToolStripMenuItem + // + clientsToolStripMenuItem.Name = "clientsToolStripMenuItem"; + clientsToolStripMenuItem.Size = new Size(145, 22); + clientsToolStripMenuItem.Text = "Клиенты"; + clientsToolStripMenuItem.Click += ClientsToolStripMenuItem_Click; + // + // reportsToolStripMenuItem + // + reportsToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { reportShopsToolStripMenuItem, ShopPastriesToolStripMenuItem, ordersToolStripMenuItem }); + reportsToolStripMenuItem.Name = "reportsToolStripMenuItem"; + reportsToolStripMenuItem.Size = new Size(60, 20); + reportsToolStripMenuItem.Text = "Отчеты"; + // + // reportShopsToolStripMenuItem + // + reportShopsToolStripMenuItem.Name = "reportShopsToolStripMenuItem"; + reportShopsToolStripMenuItem.Size = new Size(202, 22); + reportShopsToolStripMenuItem.Text = "Список магазинов"; + reportShopsToolStripMenuItem.Click += ReportShopsToolStripMenuItem_Click; + // + // ShopPastriesToolStripMenuItem + // + ShopPastriesToolStripMenuItem.Name = "ShopPastriesToolStripMenuItem"; + ShopPastriesToolStripMenuItem.Size = new Size(202, 22); + ShopPastriesToolStripMenuItem.Text = "Магазины с изделиями"; + ShopPastriesToolStripMenuItem.Click += ShopPastriesToolStripMenuItem_Click; + // + // ordersToolStripMenuItem + // + ordersToolStripMenuItem.Name = "ordersToolStripMenuItem"; + ordersToolStripMenuItem.Size = new Size(202, 22); + ordersToolStripMenuItem.Text = "Список заказов"; + ordersToolStripMenuItem.Click += OrdersToolStripMenuItem_Click; + // + // dataGridView + // + dataGridView.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(12, 27); + dataGridView.Name = "dataGridView"; + dataGridView.RowTemplate.Height = 25; + dataGridView.Size = new Size(606, 399); + dataGridView.TabIndex = 1; + // + // buttonCreateOrder + // + buttonCreateOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; + buttonCreateOrder.Location = new Point(624, 39); + buttonCreateOrder.Name = "buttonCreateOrder"; + buttonCreateOrder.Size = new Size(147, 32); + buttonCreateOrder.TabIndex = 2; + buttonCreateOrder.Text = "Создать заказ"; + buttonCreateOrder.UseVisualStyleBackColor = true; + buttonCreateOrder.Click += ButtonCreateOrder_Click; + // + // button3 + // + button3.Anchor = AnchorStyles.Top | AnchorStyles.Right; + button3.Location = new Point(624, 91); + button3.Name = "button3"; + button3.Size = new Size(147, 32); + button3.TabIndex = 5; + button3.Text = "Заказ выдан"; + button3.UseVisualStyleBackColor = true; + button3.Click += ButtonIssuedOrder_Click; + // + // button4 + // + button4.Anchor = AnchorStyles.Top | AnchorStyles.Right; + button4.Location = new Point(624, 150); + button4.Name = "button4"; + button4.Size = new Size(147, 32); + button4.TabIndex = 6; + button4.Text = "Обновить список"; + button4.UseVisualStyleBackColor = true; + button4.Click += ButtonRef_Click; + // + // buttonAddPastryInShop + // + buttonAddPastryInShop.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + buttonAddPastryInShop.Location = new Point(624, 260); + buttonAddPastryInShop.Name = "buttonAddPastryInShop"; + buttonAddPastryInShop.Size = new Size(147, 31); + buttonAddPastryInShop.TabIndex = 7; + buttonAddPastryInShop.Text = "Пополнение магазина"; + buttonAddPastryInShop.UseVisualStyleBackColor = true; + buttonAddPastryInShop.Click += ButtonAddPastryInShop_Click; + // + // ImplementersToolStripMenuItem + // + ImplementersToolStripMenuItem.Name = "ImplementersToolStripMenuItem"; + ImplementersToolStripMenuItem.Size = new Size(180, 22); + ImplementersToolStripMenuItem.Text = "Исполнители"; + ImplementersToolStripMenuItem.Click += ImplementersToolStripMenuItem_Click; + // + // DoWorkToolStripMenuItem + // + DoWorkToolStripMenuItem.Name = "DoWorkToolStripMenuItem"; + DoWorkToolStripMenuItem.Size = new Size(92, 20); + DoWorkToolStripMenuItem.Text = "Запуск работ"; + DoWorkToolStripMenuItem.Click += DoWorkToolStripMenuItem_Click; + // + // buttonSellPastry + // + buttonSellPastry.Anchor = AnchorStyles.Top | AnchorStyles.Right; + buttonSellPastry.Location = new Point(624, 207); + buttonSellPastry.Name = "buttonSellPastry"; + buttonSellPastry.Size = new Size(147, 31); + buttonSellPastry.TabIndex = 8; + buttonSellPastry.Text = "Продать изделие"; + buttonSellPastry.UseVisualStyleBackColor = true; + buttonSellPastry.Click += ButtonSellPastry_Click; + // + // FormMain + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(783, 438); + Controls.Add(buttonSellPastry); + Controls.Add(buttonAddPastryInShop); + Controls.Add(button4); + Controls.Add(button3); + Controls.Add(buttonCreateOrder); + Controls.Add(dataGridView); + Controls.Add(menuStrip1); + MainMenuStrip = menuStrip1; + Name = "FormMain"; + Text = "Кондитерская"; + Load += FormMain_Load; + menuStrip1.ResumeLayout(false); + menuStrip1.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + PerformLayout(); + } - #endregion + #endregion - private MenuStrip menuStrip1; - private ToolStripMenuItem справочникиToolStripMenuItem; - private DataGridView dataGridView; - private Button buttonCreateOrder; - private Button buttonTakeOrderInWork; - private Button button2; - private Button button3; - private Button button4; - private ToolStripMenuItem pastryToolStripMenuItem; - private ToolStripMenuItem componentToolStripMenuItem; - private ToolStripMenuItem reportsToolStripMenuItem; - private ToolStripMenuItem reportShopsToolStripMenuItem; - private ToolStripMenuItem ShopPastriesToolStripMenuItem; - private ToolStripMenuItem ordersToolStripMenuItem; - private ToolStripMenuItem ShopsToolStripMenuItem; - private Button buttonAddPastryInShop; - private Button buttonSellPastry; - private ToolStripMenuItem clientsToolStripMenuItem; - } + private MenuStrip menuStrip1; + private ToolStripMenuItem справочникиToolStripMenuItem; + private DataGridView dataGridView; + private Button buttonCreateOrder; + private Button buttonTakeOrderInWork; + private Button button2; + private Button button3; + private Button button4; + private ToolStripMenuItem pastryToolStripMenuItem; + private ToolStripMenuItem componentToolStripMenuItem; + private ToolStripMenuItem reportsToolStripMenuItem; + private ToolStripMenuItem reportShopsToolStripMenuItem; + private ToolStripMenuItem ShopPastriesToolStripMenuItem; + private ToolStripMenuItem ordersToolStripMenuItem; + private ToolStripMenuItem ShopsToolStripMenuItem; + private Button buttonAddPastryInShop; + private Button buttonSellPastry; + private ToolStripMenuItem clientsToolStripMenuItem; + private ToolStripMenuItem ImplementersToolStripMenuItem; + private ToolStripMenuItem DoWorkToolStripMenuItem; + } } \ No newline at end of file diff --git a/Confectionery/FormMain.cs b/Confectionery/FormMain.cs index 540f6d7..86d8a51 100644 --- a/Confectionery/FormMain.cs +++ b/Confectionery/FormMain.cs @@ -7,217 +7,238 @@ using System.Windows.Forms; namespace ConfectioneryView { - public partial class FormMain : Form - { - private readonly ILogger _logger; - private readonly IOrderLogic _orderLogic; - private readonly IReportLogic _reportLogic; + public partial class FormMain : Form + { + private readonly ILogger _logger; + private readonly IOrderLogic _orderLogic; + private readonly IReportLogic _reportLogic; + private readonly IWorkProcess _workProcess; - public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic) - { - InitializeComponent(); - _logger = logger; - _orderLogic = orderLogic; - _reportLogic = reportLogic; - } - private void FormMain_Load(object sender, EventArgs e) - { - LoadData(); - } - private void LoadData() - { - try - { - var list = _orderLogic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["Id"].HeaderText = " "; - dataGridView.Columns["PastryId"].Visible = false; - dataGridView.Columns["ClientId"].Visible = false; - dataGridView.Columns["PastryName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } - _logger.LogInformation(" "); - } - catch (Exception ex) - { - _logger.LogError(ex, " "); - MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, - MessageBoxIcon.Error); - } - } - private void ComponentsToolStripMenuItem_Click(object sender, EventArgs - e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormComponents)); - if (service is FormComponents form) - { - form.ShowDialog(); - } - } - private void PastryToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormViewPastry)); - if (service is FormViewPastry form) - { - form.ShowDialog(); - } - } + 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) + { + LoadData(); + } + private void LoadData() + { + try + { + var list = _orderLogic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["Id"].HeaderText = " "; + dataGridView.Columns["PastryId"].Visible = false; + dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["ImplementerId"].Visible = false; + dataGridView.Columns["PastryName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + _logger.LogInformation(" "); + } + catch (Exception ex) + { + _logger.LogError(ex, " "); + MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + private void ComponentsToolStripMenuItem_Click(object sender, EventArgs + e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormComponents)); + if (service is FormComponents form) + { + form.ShowDialog(); + } + } + private void PastryToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormViewPastry)); + if (service is FormViewPastry form) + { + form.ShowDialog(); + } + } - private void ButtonCreateOrder_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); - if (service is FormCreateOrder form) - { - form.ShowDialog(); - LoadData(); - } - } + private void ButtonCreateOrder_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); + if (service is FormCreateOrder form) + { + form.ShowDialog(); + LoadData(); + } + } - private void ButtonTakeOrderInWork_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation(" No{id}. ' '", id); - try - { - var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel { Id = id }); - if (!operationResult) - { - throw new Exception(" . ."); - } - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, " "); - MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, - MessageBoxIcon.Error); - } - } - } - private void ButtonOrderReady_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - OrderStatus orderStatus = (OrderStatus)dataGridView.SelectedRows[0].Cells["Status"].Value; - _logger.LogInformation(" No{id}. ''", id); - try - { - var operationResult = _orderLogic.FinishOrder(new OrderBindingModel - { - Id = id, - Status = orderStatus - }); - if (!operationResult) - { - throw new Exception(" . ."); - } - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, " "); - MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } - private void ButtonIssuedOrder_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - int id = - Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation(" No{id}. ''", id); - try - { - var operationResult = _orderLogic.DeliveryOrder(new - OrderBindingModel - { Id = id }); - if (!operationResult) - { - throw new Exception(" . ."); - } - _logger.LogInformation(" No{id} ", id); - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, " "); - MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, - MessageBoxIcon.Error); - } - } - } - private void ButtonRef_Click(object sender, EventArgs e) - { - LoadData(); - } + private void ButtonTakeOrderInWork_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation(" No{id}. ' '", id); + try + { + var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel { Id = id }); + if (!operationResult) + { + throw new Exception(" . ."); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, " "); + MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + } + private void ButtonOrderReady_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + OrderStatus orderStatus = (OrderStatus)dataGridView.SelectedRows[0].Cells["Status"].Value; + _logger.LogInformation(" No{id}. ''", id); + try + { + var operationResult = _orderLogic.FinishOrder(new OrderBindingModel + { + Id = id, + Status = orderStatus + }); + if (!operationResult) + { + throw new Exception(" . ."); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, " "); + MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + private void ButtonIssuedOrder_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + int id = + Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation(" No{id}. ''", id); + try + { + var operationResult = _orderLogic.DeliveryOrder(new + OrderBindingModel + { Id = id }); + if (!operationResult) + { + throw new Exception(" . ."); + } + _logger.LogInformation(" No{id} ", id); + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, " "); + MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + } + private void ButtonRef_Click(object sender, EventArgs e) + { + LoadData(); + } - private void ReportShopsToolStripMenuItem_Click(object sender, EventArgs e) - { - using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; - if (dialog.ShowDialog() == DialogResult.OK) - { - _reportLogic.SaveShopsToWordFile(new ReportBindingModel { FileName = dialog.FileName }); - MessageBox.Show("", "", MessageBoxButtons.OK, MessageBoxIcon.Information); - } - } + private void ReportShopsToolStripMenuItem_Click(object sender, EventArgs e) + { + using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; + if (dialog.ShowDialog() == DialogResult.OK) + { + _reportLogic.SaveShopsToWordFile(new ReportBindingModel { FileName = dialog.FileName }); + MessageBox.Show("", "", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } - private void ShopPastriesToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormReportShopPastries)); - if (service is FormReportShopPastries form) - { - form.ShowDialog(); - } - } + private void ShopPastriesToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReportShopPastries)); + if (service is FormReportShopPastries form) + { + form.ShowDialog(); + } + } - private void OrdersToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders)); - if (service is FormReportOrders form) - { - form.ShowDialog(); - } - } - private void ShopsToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormViewShops)); - if (service is FormViewShops form) - { - form.ShowDialog(); - } - } + private void OrdersToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders)); + if (service is FormReportOrders form) + { + form.ShowDialog(); + } + } + private void ShopsToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormViewShops)); + if (service is FormViewShops form) + { + form.ShowDialog(); + } + } - private void ButtonAddPastryInShop_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormAddPastryInShop)); - if (service is FormAddPastryInShop form) - { - form.ShowDialog(); - } - } + private void ButtonAddPastryInShop_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormAddPastryInShop)); + if (service is FormAddPastryInShop form) + { + form.ShowDialog(); + } + } - private void ButtonSellPastry_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormSellPastry)); - if (service is FormSellPastry form) - { - form.ShowDialog(); - } - } + private void ButtonSellPastry_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormSellPastry)); + if (service is FormSellPastry form) + { + form.ShowDialog(); + } + } - private void ClientsToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormViewClients)); - if (service is FormViewClients form) - { - form.ShowDialog(); - } - } - } + private void ClientsToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormViewClients)); + if (service is FormViewClients form) + { + form.ShowDialog(); + } + } + + private void ImplementersToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormViewImplementers)); + if (service is FormViewImplementers form) + { + form.ShowDialog(); + } + } + + private void DoWorkToolStripMenuItem_Click(object sender, EventArgs e) + { + _workProcess.DoWork(( + Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, + _orderLogic); + MessageBox.Show(" ", "", + MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } } \ No newline at end of file diff --git a/Confectionery/FormViewImplementers.Designer.cs b/Confectionery/FormViewImplementers.Designer.cs new file mode 100644 index 0000000..a0ebda4 --- /dev/null +++ b/Confectionery/FormViewImplementers.Designer.cs @@ -0,0 +1,118 @@ +namespace ConfectioneryView +{ + partial class FormViewImplementers + { + /// + /// 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() + { + buttonRef = new Button(); + buttonDel = new Button(); + buttonUpd = new Button(); + buttonAdd = new Button(); + dataGridView = new DataGridView(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // buttonRef + // + buttonRef.Anchor = AnchorStyles.Top | AnchorStyles.Right; + buttonRef.Location = new Point(626, 202); + buttonRef.Name = "buttonRef"; + buttonRef.Size = new Size(90, 37); + buttonRef.TabIndex = 9; + buttonRef.Text = "Обновить"; + buttonRef.UseVisualStyleBackColor = true; + buttonRef.Click += ButtonRef_Click; + // + // buttonDel + // + buttonDel.Anchor = AnchorStyles.Top | AnchorStyles.Right; + buttonDel.Location = new Point(626, 151); + buttonDel.Name = "buttonDel"; + buttonDel.Size = new Size(90, 33); + buttonDel.TabIndex = 8; + buttonDel.Text = "Удалить"; + buttonDel.UseVisualStyleBackColor = true; + buttonDel.Click += ButtonDel_Click; + // + // buttonUpd + // + buttonUpd.Anchor = AnchorStyles.Top | AnchorStyles.Right; + buttonUpd.Location = new Point(626, 102); + buttonUpd.Name = "buttonUpd"; + buttonUpd.Size = new Size(90, 34); + buttonUpd.TabIndex = 7; + buttonUpd.Text = "Изменить"; + buttonUpd.UseVisualStyleBackColor = true; + buttonUpd.Click += ButtonUpd_Click; + // + // buttonAdd + // + buttonAdd.Anchor = AnchorStyles.Top | AnchorStyles.Right; + buttonAdd.Location = new Point(626, 57); + buttonAdd.Name = "buttonAdd"; + buttonAdd.Size = new Size(90, 30); + buttonAdd.TabIndex = 6; + buttonAdd.Text = "Добавить"; + buttonAdd.UseVisualStyleBackColor = true; + buttonAdd.Click += ButtonAdd_Click; + // + // dataGridView + // + dataGridView.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(12, 12); + dataGridView.Name = "dataGridView"; + dataGridView.RowTemplate.Height = 25; + dataGridView.Size = new Size(553, 302); + dataGridView.TabIndex = 5; + // + // FormViewImplementers + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(722, 319); + Controls.Add(buttonRef); + Controls.Add(buttonDel); + Controls.Add(buttonUpd); + Controls.Add(buttonAdd); + Controls.Add(dataGridView); + Name = "FormViewImplementers"; + Text = "Просмотр списка исполнителей"; + Load += FormViewImplementers_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private Button buttonRef; + private Button buttonDel; + private Button buttonUpd; + private Button buttonAdd; + private DataGridView dataGridView; + } +} \ No newline at end of file diff --git a/Confectionery/FormViewImplementers.cs b/Confectionery/FormViewImplementers.cs new file mode 100644 index 0000000..b6f4906 --- /dev/null +++ b/Confectionery/FormViewImplementers.cs @@ -0,0 +1,111 @@ +using ConfectioneryContracts.BindingModels; +using ConfectioneryContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace ConfectioneryView +{ + public partial class FormViewImplementers : Form + { + private readonly ILogger _logger; + private readonly IImplementerLogic _logic; + public FormViewImplementers(ILogger logger, IImplementerLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + private void FormViewImplementers_Load(object sender, EventArgs e) + { + LoadData(); + } + private void LoadData() + { + try + { + var list = _logic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["Id"].Visible = false; + dataGridView.Columns["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + _logger.LogInformation("Загрузка исполнителей"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки исполнителей"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + 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/Confectionery/FormViewImplementers.resx b/Confectionery/FormViewImplementers.resx new file mode 100644 index 0000000..f298a7b --- /dev/null +++ b/Confectionery/FormViewImplementers.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/Confectionery/Program.cs b/Confectionery/Program.cs index b4fca00..ba75f3f 100644 --- a/Confectionery/Program.cs +++ b/Confectionery/Program.cs @@ -41,13 +41,17 @@ namespace ConfectioneryView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -67,6 +71,8 @@ namespace ConfectioneryView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); } } } \ No newline at end of file diff --git a/ConfectioneryContracts/BindingModels/ImplementerBindingModel.cs b/ConfectioneryContracts/BindingModels/ImplementerBindingModel.cs new file mode 100644 index 0000000..bcf2fde --- /dev/null +++ b/ConfectioneryContracts/BindingModels/ImplementerBindingModel.cs @@ -0,0 +1,25 @@ +using ConfectioneryDataModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ConfectioneryContracts.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/ConfectioneryContracts/BindingModels/OrderBindingModel.cs b/ConfectioneryContracts/BindingModels/OrderBindingModel.cs index 62eec79..1961d7d 100644 --- a/ConfectioneryContracts/BindingModels/OrderBindingModel.cs +++ b/ConfectioneryContracts/BindingModels/OrderBindingModel.cs @@ -8,6 +8,7 @@ namespace ConfectioneryContracts.BindingModels public int Id { get; set; } public int PastryId { 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/ConfectioneryContracts/BusinessLogicsContracts/IImplementerLogic.cs b/ConfectioneryContracts/BusinessLogicsContracts/IImplementerLogic.cs new file mode 100644 index 0000000..0b19763 --- /dev/null +++ b/ConfectioneryContracts/BusinessLogicsContracts/IImplementerLogic.cs @@ -0,0 +1,20 @@ +using ConfectioneryContracts.BindingModels; +using ConfectioneryContracts.SearchModels; +using ConfectioneryContracts.ViewModels; + +namespace ConfectioneryContracts.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/ConfectioneryContracts/BusinessLogicsContracts/IOrderLogic.cs b/ConfectioneryContracts/BusinessLogicsContracts/IOrderLogic.cs index 221258a..dfd1797 100644 --- a/ConfectioneryContracts/BusinessLogicsContracts/IOrderLogic.cs +++ b/ConfectioneryContracts/BusinessLogicsContracts/IOrderLogic.cs @@ -7,7 +7,8 @@ namespace ConfectioneryContracts.BusinessLogicsContracts public interface IOrderLogic { List? ReadList(OrderSearchModel? model); - bool CreateOrder(OrderBindingModel model); + OrderViewModel? ReadElement(OrderSearchModel model); + bool CreateOrder(OrderBindingModel model); bool TakeOrderInWork(OrderBindingModel model); bool FinishOrder(OrderBindingModel model); bool DeliveryOrder(OrderBindingModel model); diff --git a/ConfectioneryContracts/BusinessLogicsContracts/IWorkProcess.cs b/ConfectioneryContracts/BusinessLogicsContracts/IWorkProcess.cs new file mode 100644 index 0000000..5a1de4c --- /dev/null +++ b/ConfectioneryContracts/BusinessLogicsContracts/IWorkProcess.cs @@ -0,0 +1,10 @@ +namespace ConfectioneryContracts.BusinessLogicsContracts +{ + public interface IWorkProcess + { + /// + /// Запуск работ + /// + void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic); + } +} diff --git a/ConfectioneryContracts/SearchModels/ImplementerSearchModel.cs b/ConfectioneryContracts/SearchModels/ImplementerSearchModel.cs new file mode 100644 index 0000000..0554d59 --- /dev/null +++ b/ConfectioneryContracts/SearchModels/ImplementerSearchModel.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ConfectioneryContracts.SearchModels +{ + public class ImplementerSearchModel + { + public int? Id { get; set; } + + public string? ImplementerFIO { get; set; } + + public string? Password { get; set; } + } +} diff --git a/ConfectioneryContracts/SearchModels/OrderSearchModel.cs b/ConfectioneryContracts/SearchModels/OrderSearchModel.cs index 2aaa9a2..606260e 100644 --- a/ConfectioneryContracts/SearchModels/OrderSearchModel.cs +++ b/ConfectioneryContracts/SearchModels/OrderSearchModel.cs @@ -1,4 +1,6 @@ -namespace ConfectioneryContracts.SearchModels +using ConfectioneryDataModels.Enums; + +namespace ConfectioneryContracts.SearchModels { public class OrderSearchModel { @@ -9,5 +11,9 @@ public DateTime? DateTo { get; set; } public int? ClientId { get; set; } + + public int? ImplementerId { get; set; } + + public OrderStatus? Status { get; set; } } } diff --git a/ConfectioneryContracts/StoragesContract/IImplementerStorage.cs b/ConfectioneryContracts/StoragesContract/IImplementerStorage.cs new file mode 100644 index 0000000..3c59d27 --- /dev/null +++ b/ConfectioneryContracts/StoragesContract/IImplementerStorage.cs @@ -0,0 +1,26 @@ +using ConfectioneryContracts.BindingModels; +using ConfectioneryContracts.SearchModels; +using ConfectioneryContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ConfectioneryContracts.StoragesContract +{ + 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/ConfectioneryContracts/ViewModels/ImplementerViewModel.cs b/ConfectioneryContracts/ViewModels/ImplementerViewModel.cs new file mode 100644 index 0000000..d712215 --- /dev/null +++ b/ConfectioneryContracts/ViewModels/ImplementerViewModel.cs @@ -0,0 +1,30 @@ +using ConfectioneryDataModels; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ConfectioneryContracts.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/ConfectioneryContracts/ViewModels/OrderViewModel.cs b/ConfectioneryContracts/ViewModels/OrderViewModel.cs index 32a6d71..49e9198 100644 --- a/ConfectioneryContracts/ViewModels/OrderViewModel.cs +++ b/ConfectioneryContracts/ViewModels/OrderViewModel.cs @@ -17,10 +17,15 @@ namespace ConfectioneryContracts.ViewModels public int ClientId { get; set; } - [DisplayName("Фамилия клиента")] + public int? ImplementerId { get; set; } + + [DisplayName("Фамилия клиента")] public string ClientFIO { get; set; } = string.Empty; - [DisplayName("Изделие")] + [DisplayName("Фамилия исполнителя")] + public string ImplementerFIO { get; set; } = string.Empty; + + [DisplayName("Изделие")] public string PastryName { get; set; } = string.Empty; [DisplayName("Количество")] diff --git a/ConfectioneryDataModels/IImplementerModel.cs b/ConfectioneryDataModels/IImplementerModel.cs new file mode 100644 index 0000000..0f1df0e --- /dev/null +++ b/ConfectioneryDataModels/IImplementerModel.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ConfectioneryDataModels +{ + public interface IImplementerModel : IId + { + string ImplementerFIO { get; } + string Password { get; } + int WorkExperience { get; } + int Qualification { get; } + } +} diff --git a/ConfectioneryDataModels/IOrderModel.cs b/ConfectioneryDataModels/IOrderModel.cs index c168d51..ddfc3e7 100644 --- a/ConfectioneryDataModels/IOrderModel.cs +++ b/ConfectioneryDataModels/IOrderModel.cs @@ -6,6 +6,7 @@ namespace ConfectioneryDataModels.Models { int PastryId { get; } int ClientId { get; } + int? ImplementerId { get; } int Count { get; } double Sum { get; } OrderStatus Status { get; } diff --git a/ConfectioneryDatabaseImplement/ConfectioneryDatabase.cs b/ConfectioneryDatabaseImplement/ConfectioneryDatabase.cs index b66843b..c85feb8 100644 --- a/ConfectioneryDatabaseImplement/ConfectioneryDatabase.cs +++ b/ConfectioneryDatabaseImplement/ConfectioneryDatabase.cs @@ -28,5 +28,6 @@ namespace ConfectioneryDatabaseImplement public virtual DbSet ShopPastries { set; get; } public virtual DbSet Clients { set; get; } + public virtual DbSet Implementers { set; get; } } } diff --git a/ConfectioneryDatabaseImplement/Implementer.cs b/ConfectioneryDatabaseImplement/Implementer.cs new file mode 100644 index 0000000..649bca3 --- /dev/null +++ b/ConfectioneryDatabaseImplement/Implementer.cs @@ -0,0 +1,60 @@ +using ConfectioneryContracts.BindingModels; +using ConfectioneryContracts.ViewModels; +using ConfectioneryDataModels; +using System.ComponentModel.DataAnnotations.Schema; + +namespace ConfectioneryDatabaseImplement.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; } + + [ForeignKey("ImplementerId")] + public virtual List Orders { get; private set; } = new(); + + public static Implementer? Create(ImplementerBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Id = model.Id, + Password = model.Password, + Qualification = model.Qualification, + ImplementerFIO = model.ImplementerFIO, + WorkExperience = model.WorkExperience, + }; + } + + public void Update(ImplementerBindingModel model) + { + if (model == null) + { + return; + } + Password = model.Password; + Qualification = model.Qualification; + ImplementerFIO = model.ImplementerFIO; + WorkExperience = model.WorkExperience; + } + + public ImplementerViewModel GetViewModel => new() + { + Id = Id, + Password = Password, + Qualification = Qualification, + ImplementerFIO = ImplementerFIO, + WorkExperience = WorkExperience, + }; + } +} diff --git a/ConfectioneryDatabaseImplement/ImplementerStorage.cs b/ConfectioneryDatabaseImplement/ImplementerStorage.cs new file mode 100644 index 0000000..2550b58 --- /dev/null +++ b/ConfectioneryDatabaseImplement/ImplementerStorage.cs @@ -0,0 +1,90 @@ +using ConfectioneryContracts.BindingModels; +using ConfectioneryContracts.SearchModels; +using ConfectioneryContracts.StoragesContract; +using ConfectioneryContracts.ViewModels; +using ConfectioneryDatabaseImplement.Models; + +namespace ConfectioneryDatabaseImplement.Implements +{ + public class ImplementerStorage : IImplementerStorage + { + public ImplementerViewModel? Delete(ImplementerBindingModel model) + { + using var context = new ConfectioneryDatabase(); + var res = context.Implementers.FirstOrDefault(x => x.Id == model.Id); + if (res != null) + { + context.Implementers.Remove(res); + context.SaveChanges(); + } + return res?.GetViewModel; + } + + public ImplementerViewModel? GetElement(ImplementerSearchModel model) + { + using var context = new ConfectioneryDatabase(); + if (model.Id.HasValue) + return context.Implementers.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; + if (model.ImplementerFIO != null && model.Password != null) + return context.Implementers + .FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO) + && x.Password.Equals(model.Password)) + ?.GetViewModel; + if (model.ImplementerFIO != null) + return context.Implementers.FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO))?.GetViewModel; + return null; + } + + public List GetFilteredList(ImplementerSearchModel model) + { + if (model == null) + { + return new(); + } + if (model.Id.HasValue) + { + var res = GetElement(model); + return res != null ? new() { res } : new(); + } + if (model.ImplementerFIO != null) // На случай если фио не будет уникальным (по заданию оно уникально) + { + using var context = new ConfectioneryDatabase(); + return context.Implementers + .Where(x => x.ImplementerFIO.Equals(model.ImplementerFIO)) + .Select(x => x.GetViewModel) + .ToList(); + } + return new(); + } + + public List GetFullList() + { + using var context = new ConfectioneryDatabase(); + return context.Implementers.Select(x => x.GetViewModel).ToList(); + } + + public ImplementerViewModel? Insert(ImplementerBindingModel model) + { + using var context = new ConfectioneryDatabase(); + var res = Implementer.Create(model); + if (res != null) + { + context.Implementers.Add(res); + context.SaveChanges(); + } + return res?.GetViewModel; + } + + public ImplementerViewModel? Update(ImplementerBindingModel model) + { + using var context = new ConfectioneryDatabase(); + var res = context.Implementers.FirstOrDefault(x => x.Id == model.Id); + if (res != null) + { + res.Update(model); + context.SaveChanges(); + } + return res?.GetViewModel; + } + } +} diff --git a/ConfectioneryDatabaseImplement/Migrations/20230306113501_implementer.Designer.cs b/ConfectioneryDatabaseImplement/Migrations/20230306113501_implementer.Designer.cs new file mode 100644 index 0000000..03e5e93 --- /dev/null +++ b/ConfectioneryDatabaseImplement/Migrations/20230306113501_implementer.Designer.cs @@ -0,0 +1,257 @@ +// +using System; +using ConfectioneryDatabaseImplement; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace ConfectioneryDatabaseImplement.Migrations +{ + [DbContext(typeof(ConfectioneryDatabase))] + [Migration("20230306113501_implementer")] + partial class implementer + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.3") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("ConfectioneryDatabaseImplement.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("ConfectioneryDatabaseImplement.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("ConfectioneryDatabaseImplement.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("ConfectioneryDatabaseImplement.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("PastryId") + .HasColumnType("int"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("Sum") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.HasIndex("ImplementerId"); + + b.HasIndex("PastryId"); + + b.ToTable("Orders"); + }); + + modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Pastry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("PastryName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Price") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.ToTable("Pastries"); + }); + + modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.PastryComponent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ComponentId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("PastryId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ComponentId"); + + b.HasIndex("PastryId"); + + b.ToTable("PastryComponents"); + }); + + modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Order", b => + { + b.HasOne("ConfectioneryDatabaseImplement.Models.Client", "Client") + .WithMany("Orders") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("ConfectioneryDatabaseImplement.Models.Implementer", "Implementer") + .WithMany("Orders") + .HasForeignKey("ImplementerId"); + + b.HasOne("ConfectioneryDatabaseImplement.Models.Pastry", "Pastry") + .WithMany("Orders") + .HasForeignKey("PastryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Client"); + + b.Navigation("Implementer"); + + b.Navigation("Pastry"); + }); + + modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.PastryComponent", b => + { + b.HasOne("ConfectioneryDatabaseImplement.Models.Component", "Component") + .WithMany("PastryComponents") + .HasForeignKey("ComponentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("ConfectioneryDatabaseImplement.Models.Pastry", "Pastry") + .WithMany("Components") + .HasForeignKey("PastryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Component"); + + b.Navigation("Pastry"); + }); + + modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Client", b => + { + b.Navigation("Orders"); + }); + + modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Component", b => + { + b.Navigation("PastryComponents"); + }); + + modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Implementer", b => + { + b.Navigation("Orders"); + }); + + modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Pastry", b => + { + b.Navigation("Components"); + + b.Navigation("Orders"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/ConfectioneryDatabaseImplement/Migrations/20230306113501_implementer.cs b/ConfectioneryDatabaseImplement/Migrations/20230306113501_implementer.cs new file mode 100644 index 0000000..f1ee0e6 --- /dev/null +++ b/ConfectioneryDatabaseImplement/Migrations/20230306113501_implementer.cs @@ -0,0 +1,67 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace ConfectioneryDatabaseImplement.Migrations +{ + /// + public partial class implementer : 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/ConfectioneryDatabaseImplement/Migrations/ConfectioneryDatabaseModelSnapshot.cs b/ConfectioneryDatabaseImplement/Migrations/ConfectioneryDatabaseModelSnapshot.cs index f4abd73..cc60273 100644 --- a/ConfectioneryDatabaseImplement/Migrations/ConfectioneryDatabaseModelSnapshot.cs +++ b/ConfectioneryDatabaseImplement/Migrations/ConfectioneryDatabaseModelSnapshot.cs @@ -10,17 +10,17 @@ using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace ConfectioneryDatabaseImplement.Migrations { - [DbContext(typeof(ConfectioneryDatabase))] - partial class ConfectioneryDatabaseModelSnapshot : ModelSnapshot - { - protected override void BuildModel(ModelBuilder modelBuilder) - { + [DbContext(typeof(ConfectioneryDatabase))] + partial class ConfectioneryDatabaseModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { #pragma warning disable 612, 618 - modelBuilder - .HasAnnotation("ProductVersion", "7.0.3") - .HasAnnotation("Relational:MaxIdentifierLength", 128); + modelBuilder + .HasAnnotation("ProductVersion", "7.0.3") + .HasAnnotation("Relational:MaxIdentifierLength", 128); - SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Client", b => { @@ -28,7 +28,7 @@ namespace ConfectioneryDatabaseImplement.Migrations .ValueGeneratedOnAdd() .HasColumnType("int"); - SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); b.Property("ClientFIO") .IsRequired() @@ -59,21 +59,48 @@ namespace ConfectioneryDatabaseImplement.Migrations .IsRequired() .HasColumnType("nvarchar(max)"); - b.Property("Cost") - .HasColumnType("float"); + b.Property("Cost") + .HasColumnType("float"); - b.HasKey("Id"); + b.HasKey("Id"); - b.ToTable("Components"); - }); + b.ToTable("Components"); + }); - modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Order", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("int"); + modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Implementer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); - SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + 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("ConfectioneryDatabaseImplement.Models.Order", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); b.Property("ClientId") .HasColumnType("int"); @@ -81,75 +108,80 @@ namespace ConfectioneryDatabaseImplement.Migrations b.Property("Count") .HasColumnType("int"); - b.Property("DateCreate") - .HasColumnType("datetime2"); + b.Property("DateCreate") + .HasColumnType("datetime2"); - b.Property("DateImplement") - .HasColumnType("datetime2"); + b.Property("DateImplement") + .HasColumnType("datetime2"); - b.Property("PastryId") - .HasColumnType("int"); + b.Property("ImplementerId") + .HasColumnType("int"); - b.Property("Status") - .HasColumnType("int"); + b.Property("PastryId") + .HasColumnType("int"); - b.Property("Sum") - .HasColumnType("float"); + b.Property("Status") + .HasColumnType("int"); - b.HasKey("Id"); + b.Property("Sum") + .HasColumnType("float"); + + b.HasKey("Id"); b.HasIndex("ClientId"); + b.HasIndex("ImplementerId"); + b.HasIndex("PastryId"); - b.ToTable("Orders"); - }); + b.ToTable("Orders"); + }); - modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Pastry", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("int"); + modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Pastry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); - SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); - b.Property("PastryName") - .IsRequired() - .HasColumnType("nvarchar(max)"); + b.Property("PastryName") + .IsRequired() + .HasColumnType("nvarchar(max)"); - b.Property("Price") - .HasColumnType("float"); + b.Property("Price") + .HasColumnType("float"); - b.HasKey("Id"); + b.HasKey("Id"); b.ToTable("Pastries"); }); - modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.PastryComponent", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("int"); + modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.PastryComponent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); - SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); - b.Property("ComponentId") - .HasColumnType("int"); + b.Property("ComponentId") + .HasColumnType("int"); - b.Property("Count") - .HasColumnType("int"); + b.Property("Count") + .HasColumnType("int"); - b.Property("PastryId") - .HasColumnType("int"); + b.Property("PastryId") + .HasColumnType("int"); - b.HasKey("Id"); + b.HasKey("Id"); - b.HasIndex("ComponentId"); + b.HasIndex("ComponentId"); - b.HasIndex("PastryId"); + b.HasIndex("PastryId"); - b.ToTable("PastryComponents"); - }); + b.ToTable("PastryComponents"); + }); modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Shop", b => { @@ -217,6 +249,10 @@ namespace ConfectioneryDatabaseImplement.Migrations .OnDelete(DeleteBehavior.Cascade) .IsRequired(); + b.HasOne("ConfectioneryDatabaseImplement.Models.Implementer", "Implementer") + .WithMany("Orders") + .HasForeignKey("ImplementerId"); + b.HasOne("ConfectioneryDatabaseImplement.Models.Pastry", "Pastry") .WithMany("Orders") .HasForeignKey("PastryId") @@ -225,6 +261,8 @@ namespace ConfectioneryDatabaseImplement.Migrations b.Navigation("Client"); + b.Navigation("Implementer"); + b.Navigation("Pastry"); }); @@ -236,11 +274,11 @@ namespace ConfectioneryDatabaseImplement.Migrations .OnDelete(DeleteBehavior.Cascade) .IsRequired(); - b.HasOne("ConfectioneryDatabaseImplement.Models.Pastry", "Pastry") - .WithMany("Components") - .HasForeignKey("PastryId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); + b.HasOne("ConfectioneryDatabaseImplement.Models.Pastry", "Pastry") + .WithMany("Components") + .HasForeignKey("PastryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); b.Navigation("Component"); @@ -283,9 +321,14 @@ namespace ConfectioneryDatabaseImplement.Migrations b.Navigation("PastryComponents"); }); - modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Pastry", b => - { - b.Navigation("Components"); + modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Implementer", b => + { + b.Navigation("Orders"); + }); + + modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Pastry", b => + { + b.Navigation("Components"); b.Navigation("Orders"); @@ -297,6 +340,6 @@ namespace ConfectioneryDatabaseImplement.Migrations b.Navigation("ShopPastries"); }); #pragma warning restore 612, 618 - } - } + } + } } diff --git a/ConfectioneryDatabaseImplement/Order.cs b/ConfectioneryDatabaseImplement/Order.cs index 9859bee..e565c25 100644 --- a/ConfectioneryDatabaseImplement/Order.cs +++ b/ConfectioneryDatabaseImplement/Order.cs @@ -24,7 +24,9 @@ namespace ConfectioneryDatabaseImplement.Models [Required] public int ClientId { get; private set; } - [Required] + public int? ImplementerId { get; private set; } + + [Required] public int Count { get; private set; } [Required] @@ -40,9 +42,10 @@ namespace ConfectioneryDatabaseImplement.Models public Pastry Pastry { get; private set; } - public Client Client { get; private set; } + public Implementer? Implementer { get; private set; } + public static Order? Create(OrderBindingModel? model) { if (model == null) @@ -57,6 +60,7 @@ namespace ConfectioneryDatabaseImplement.Models Sum = model.Sum, Status = model.Status, DateCreate = model.DateCreate, + ImplementerId = model.ImplementerId, DateImplement = model.DateImplement, Id = model.Id, }; @@ -74,6 +78,7 @@ namespace ConfectioneryDatabaseImplement.Models Status = model.Status; DateCreate = model.DateCreate; DateImplement = model.DateImplement; + ImplementerId = model.ImplementerId; Id = model.Id; } public OrderViewModel GetViewModel @@ -86,12 +91,15 @@ namespace ConfectioneryDatabaseImplement.Models PastryName = context.Pastries.FirstOrDefault(x => x.Id == PastryId)?.PastryName ?? string.Empty, // ?????? ClientFIO = Client?.ClientFIO ?? context.Clients.FirstOrDefault(x => x.Id == ClientId)?.ClientFIO ?? string.Empty, + ImplementerFIO = Implementer?.ImplementerFIO ?? + context.Implementers.FirstOrDefault(x => x.Id == ImplementerId)?.ImplementerFIO ?? string.Empty, PastryId = PastryId, Count = Count, Sum = Sum, Status = Status, DateCreate = DateCreate, DateImplement = DateImplement, + ImplementerId = ImplementerId, Id = Id, }; } diff --git a/ConfectioneryDatabaseImplement/OrderStorage.cs b/ConfectioneryDatabaseImplement/OrderStorage.cs index e962a50..14ef8b7 100644 --- a/ConfectioneryDatabaseImplement/OrderStorage.cs +++ b/ConfectioneryDatabaseImplement/OrderStorage.cs @@ -4,7 +4,6 @@ using ConfectioneryContracts.StoragesContract; using ConfectioneryContracts.ViewModels; using ConfectioneryDatabaseImplement.Models; using Microsoft.EntityFrameworkCore; -using System.Security.Cryptography.X509Certificates; namespace ConfectioneryDatabaseImplement.Implements { @@ -13,7 +12,10 @@ namespace ConfectioneryDatabaseImplement.Implements public OrderViewModel? Delete(OrderBindingModel model) { using var context = new ConfectioneryDatabase(); - var element = context.Orders.Include(x => x.Client).FirstOrDefault(x => x.Id == model.Id); + var element = context.Orders + .Include(x => x.Client) + .Include(x => x.Implementer) + .FirstOrDefault(x => x.Id == model.Id); if (element != null) { context.Orders.Remove(element); @@ -26,41 +28,52 @@ namespace ConfectioneryDatabaseImplement.Implements public OrderViewModel? GetElement(OrderSearchModel model) { using var context = new ConfectioneryDatabase(); - if (!model.Id.HasValue) - { - return null; - } - return context.Orders - .Include(x => x.Client) - .FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id) - ?.GetViewModel; + // Находим первого либо по айди заказа, либо по айди исполнителя, либо по айди исполнителя и статусу заказа, исходя из того что есть в модели + return context.Orders + .Include(x => x.Client) + .Include(x => x.Implementer) + .FirstOrDefault(x => + (!model.Status.HasValue || model.Status.HasValue && x.Status == model.Status) && + model.ImplementerId.HasValue && x.ImplementerId == model.ImplementerId || + model.Id.HasValue && x.Id == model.Id + ) + ?.GetViewModel; } public List GetFilteredList(OrderSearchModel model) { - if (model.Id.HasValue) - { - var result = GetElement(model); - return result != null ? new() { result } : new(); - } - using var context = new ConfectioneryDatabase(); - if (model.DateFrom.HasValue && model.DateTo.HasValue) // если не ищем по айдишнику, значит ищем по диапазону дат - { - return context.Orders - .Where(x => model.DateFrom <= x.DateCreate.Date && x.DateCreate <= model.DateTo) - .Include(x => x.Client) + if (model.Id.HasValue) + { + var result = GetElement(model); + return result != null ? new() { result } : new(); + } + + using var context = new ConfectioneryDatabase(); + IQueryable? queryWhere = null; + + if (model.DateFrom.HasValue && model.DateTo.HasValue) // если не ищем по айдишнику, значит ищем по диапазону дат + { + queryWhere = context.Orders + .Where(x => model.DateFrom <= x.DateCreate.Date && + x.DateCreate.Date <= model.DateTo); + } + else if (model.Status.HasValue) + { + queryWhere = context.Orders.Where(x => x.Status == model.Status); + } + else if (model.ClientId.HasValue) + { + queryWhere = context.Orders.Where(x => x.ClientId == model.ClientId); + } + else + { + return new(); + } + return queryWhere + .Include(x => x.Client) + .Include(x => x.Implementer) .Select(x => x.GetViewModel) - .ToList(); - } - if (model.ClientId.HasValue) - { - return context.Orders - .Where(x => x.Client.Id == model.ClientId) - .Include(x => x.Client) - .Select(x => x.GetViewModel) - .ToList(); - } - return new(); + .ToList(); } public List GetFullList() @@ -68,7 +81,8 @@ namespace ConfectioneryDatabaseImplement.Implements using var context = new ConfectioneryDatabase(); return context.Orders .Include(x => x.Client) - .Select(x => x.GetViewModel) + .Include(x => x.Implementer) + .Select(x => x.GetViewModel) .ToList(); } @@ -90,7 +104,8 @@ namespace ConfectioneryDatabaseImplement.Implements using var context = new ConfectioneryDatabase(); var order = context.Orders .Include(x => x.Client) - .FirstOrDefault(x => x.Id == model.Id); + .Include(x => x.Implementer) + .FirstOrDefault(x => x.Id == model.Id); if (order == null) { return null; diff --git a/ConfectioneryRestApi/Controllers/ImplementerController.cs b/ConfectioneryRestApi/Controllers/ImplementerController.cs new file mode 100644 index 0000000..9664734 --- /dev/null +++ b/ConfectioneryRestApi/Controllers/ImplementerController.cs @@ -0,0 +1,107 @@ +using ConfectioneryContracts.BindingModels; +using ConfectioneryContracts.BusinessLogicsContracts; +using ConfectioneryContracts.SearchModels; +using ConfectioneryContracts.ViewModels; +using ConfectioneryDataModels.Enums; +using Microsoft.AspNetCore.Mvc; + +namespace ConfectioneryRestApi.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; + } + } + } +}