From 7efae297429cfd4f546617f75da2359c48691455 Mon Sep 17 00:00:00 2001 From: Salikh Date: Fri, 3 May 2024 04:32:02 +0400 Subject: [PATCH] =?UTF-8?q?=D0=92=D1=80=D0=BE=D0=B4=D0=B5=20=D0=B1=D1=8B?= =?UTF-8?q?=20=D1=80=D0=B0=D0=B1=D0=BE=D1=87=D0=B8=D0=B9=20=D0=B1=D0=B8?= =?UTF-8?q?=D0=BB=D0=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../BusinessLogic/ClientLogic.cs | 15 +- .../BusinessLogic/MessageInfoLogic.cs | 94 ++++ .../BusinessLogic/OrderLogic.cs | 28 +- .../MailWorker/AbstractMailWorker.cs | 85 +++ .../MailWorker/MailKitWorker.cs | 78 +++ .../MotorPlantBusinessLogic.csproj | 1 + .../Controllers/HomeController.cs | 12 +- .../Views/Home/Mails.cshtml | 55 ++ .../Views/Shared/_Layout.cshtml | 3 + .../BindingModels/MailConfigBindingModel.cs | 18 + .../BindingModels/MailSendInfoBindingModel.cs | 15 + .../BindingModels/MessageInfoBindingModel.cs | 19 + .../IMessageInfoLogic.cs | 17 + .../SearchModels/ClientSearchModel.cs | 1 + .../SearchModels/MessageInfoSearchModel.cs | 14 + .../StoragesContracts/IMessageInfoStorage.cs | 19 + .../ViewModels/MessageInfoViewModel.cs | 29 ++ .../ViewModels/OrderViewModel.cs | 4 +- .../Models/IMessageInfoModel.cs | 23 + .../Implements/ClientStorage.cs | 7 +- .../Implements/MessageInfoStorage.cs | 52 ++ ... 20240502232313_lab7Migration.Designer.cs} | 52 +- ...Lab.cs => 20240502232313_lab7Migration.cs} | 31 +- .../MotorPlantDatabaseModelSnapshot.cs | 48 +- .../Models/Client.cs | 8 + .../Models/MessageInfo.cs | 59 +++ .../Models/Order.cs | 3 +- .../MotorPlantDatabase.cs | 5 +- .../DataFileSingleton.cs | 19 +- .../Implements/MessageInfoStorage.cs | 53 ++ .../Models/MessageInfo.cs | 75 +++ .../DataListSingleton.cs | 9 +- .../Implements/MessageInfoStorage.cs | 63 +++ .../Models/MessageInfo.cs | 48 ++ .../Controllers/ClientController.cs | 24 +- .../MotorPlantRestApi.csproj | 4 + MotorPlant/MotorPlantRestApi/Program.cs | 19 +- MotorPlant/MotorPlantRestApi/appsettings.json | 8 +- MotorPlant/MotorPlantView/App.config | 11 + .../MotorPlantView/FormMail.Designer.cs | 67 +++ MotorPlant/MotorPlantView/FormMail.cs | 45 ++ MotorPlant/MotorPlantView/FormMail.resx | 120 +++++ .../MotorPlantView/FormMain.Designer.cs | 493 +++++++++--------- MotorPlant/MotorPlantView/FormMain.cs | 388 +++++++------- MotorPlant/MotorPlantView/Program.cs | 34 +- 45 files changed, 1802 insertions(+), 473 deletions(-) create mode 100644 MotorPlant/MotorPlantBusinessLogic/BusinessLogic/MessageInfoLogic.cs create mode 100644 MotorPlant/MotorPlantBusinessLogic/MailWorker/AbstractMailWorker.cs create mode 100644 MotorPlant/MotorPlantBusinessLogic/MailWorker/MailKitWorker.cs create mode 100644 MotorPlant/MotorPlantClientApp/Views/Home/Mails.cshtml create mode 100644 MotorPlant/MotorPlantContracts/BindingModels/MailConfigBindingModel.cs create mode 100644 MotorPlant/MotorPlantContracts/BindingModels/MailSendInfoBindingModel.cs create mode 100644 MotorPlant/MotorPlantContracts/BindingModels/MessageInfoBindingModel.cs create mode 100644 MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IMessageInfoLogic.cs create mode 100644 MotorPlant/MotorPlantContracts/SearchModels/MessageInfoSearchModel.cs create mode 100644 MotorPlant/MotorPlantContracts/StoragesContracts/IMessageInfoStorage.cs create mode 100644 MotorPlant/MotorPlantContracts/ViewModels/MessageInfoViewModel.cs create mode 100644 MotorPlant/MotorPlantDataModels/Models/IMessageInfoModel.cs create mode 100644 MotorPlant/MotorPlantDatabaseImplement/Implements/MessageInfoStorage.cs rename MotorPlant/MotorPlantDatabaseImplement/Migrations/{20240418124911_InitMigrationFor6Lab.Designer.cs => 20240502232313_lab7Migration.Designer.cs} (83%) rename MotorPlant/MotorPlantDatabaseImplement/Migrations/{20240418124911_InitMigrationFor6Lab.cs => 20240502232313_lab7Migration.cs} (85%) create mode 100644 MotorPlant/MotorPlantDatabaseImplement/Models/MessageInfo.cs create mode 100644 MotorPlant/MotorPlantFileImplement/Implements/MessageInfoStorage.cs create mode 100644 MotorPlant/MotorPlantFileImplement/Models/MessageInfo.cs create mode 100644 MotorPlant/MotorPlantListImplement/Implements/MessageInfoStorage.cs create mode 100644 MotorPlant/MotorPlantListImplement/Models/MessageInfo.cs create mode 100644 MotorPlant/MotorPlantView/App.config create mode 100644 MotorPlant/MotorPlantView/FormMail.Designer.cs create mode 100644 MotorPlant/MotorPlantView/FormMail.cs create mode 100644 MotorPlant/MotorPlantView/FormMail.resx diff --git a/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ClientLogic.cs b/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ClientLogic.cs index 464ab08..6f7f230 100644 --- a/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ClientLogic.cs +++ b/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ClientLogic.cs @@ -4,6 +4,7 @@ using MotorPlantContracts.SearchModels; using MotorPlantContracts.StoragesContracts; using MotorPlantContracts.ViewModels; using Microsoft.Extensions.Logging; +using System.Text.RegularExpressions; namespace MotorPlantBusinessLogic.BusinessLogics { @@ -92,20 +93,20 @@ namespace MotorPlantBusinessLogic.BusinessLogics throw new ArgumentNullException("Нет ФИО пользователя", nameof(model.ClientFIO)); } - if (string.IsNullOrEmpty(model.Email)) + if (string.IsNullOrEmpty(model.Email) || !Regex.IsMatch(model.Email, @"^[a-z0-9._%+-]+\@([a-z0-9-]+\.)+[a-z]{2,4}$")) { - throw new ArgumentNullException("Нет логина (почты) пользователя", - nameof(model.Email)); + throw new ArgumentNullException("Не указана валидная почта", nameof(model.Email)); } if (string.IsNullOrEmpty(model.Password)) { - throw new ArgumentNullException("Нет пароля пользователя", nameof(model.Password)); + throw new ArgumentNullException("Не указан правильный пароль", nameof(model.Password)); } - _logger.LogInformation("Client. ClientFIO:{ClientFIO}. Password:{ Password}. Email:{ Email}. Id: { Id}", model.ClientFIO, model.Password, model.Email, model.Id); + _logger.LogInformation("Client. ClientFIO:{ClientFIO}.Email:{Email}.Id:{Id}", + model.ClientFIO, model.Email, model.Id); var element = _clientStorage.GetElement(new ClientSearchModel { - Email = model.Email - });; + ClientFIO = model.ClientFIO + }); if (element != null && element.Id != model.Id) { throw new InvalidOperationException("Пользователь с таким же логином (почтой) уже есть"); diff --git a/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/MessageInfoLogic.cs b/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/MessageInfoLogic.cs new file mode 100644 index 0000000..b385bb1 --- /dev/null +++ b/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/MessageInfoLogic.cs @@ -0,0 +1,94 @@ +using Microsoft.Extensions.Logging; +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.BusinessLogicsContracts; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.StoragesContracts; +using MotorPlantContracts.ViewModels; + +namespace MotorPlantBusinessLogic.BusinessLogic +{ + public class MessageInfoLogic : IMessageInfoLogic + { + private readonly ILogger _logger; + private readonly IMessageInfoStorage _messageInfoStorage; + private readonly IClientStorage _clientStorage; + + public MessageInfoLogic(ILogger logger, IMessageInfoStorage messageInfoStorage, IClientStorage clientStorage) + { + _logger = logger; + _messageInfoStorage = messageInfoStorage; + _clientStorage = clientStorage; + } + + public List ReadList(MessageInfoSearchModel? model) + { + _logger.LogInformation("ReadList. MessageId:{MessageId}.ClientId:{ClientId}", model?.MessageId, model?.ClientId); + + var list = model == null ? _messageInfoStorage.GetFullList() : _messageInfoStorage.GetFilteredList(model); + + if (list == null) + { + _logger.LogInformation("ReadList return null list"); + return null; + } + + _logger.LogInformation("ReadList. Count:{Count}", list.Count); + return list; + } + + public bool Create(MessageInfoBindingModel model) + { + CheckModel(model); + + if (_messageInfoStorage.Insert(model) == null) + { + _logger.LogWarning("Insert error"); + return false; + } + + return true; + } + + private void CheckModel(MessageInfoBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (!withParams) + { + return; + } + if (string.IsNullOrEmpty(model.MessageId)) + { + throw new ArgumentNullException("Не указан id сообщения", nameof(model.MessageId)); + } + if (string.IsNullOrEmpty(model.SenderName)) + { + throw new ArgumentNullException("Не указана почта", nameof(model.SenderName)); + } + if (string.IsNullOrEmpty(model.Subject)) + { + throw new ArgumentNullException("Не указана тема", nameof(model.Subject)); + } + if (string.IsNullOrEmpty(model.Body)) + { + throw new ArgumentNullException("Не указан текст сообщения", nameof(model.Subject)); + } + + _logger.LogInformation("MessageInfo. MessageId:{MessageId}.SenderName:{SenderName}.Subject:{Subject}.Body:{Body}", model.MessageId, model.SenderName, model.Subject, model.Body); + var element = _clientStorage.GetElement(new ClientSearchModel + { + Email = model.SenderName + }); + if (element == null) + { + _logger.LogWarning("Не удалось найти клиента, отправившего письмо с адреса Email:{Email}", model.SenderName); + } + else + { + model.ClientId = element.Id; + } + } + } +} diff --git a/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/OrderLogic.cs b/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/OrderLogic.cs index 3679cfd..98cb9c6 100644 --- a/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/OrderLogic.cs +++ b/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/OrderLogic.cs @@ -5,6 +5,7 @@ using MotorPlantContracts.StoragesContracts; using MotorPlantContracts.ViewModels; using Microsoft.Extensions.Logging; using MotorPlantDataModels.Enums; +using MotorPlantBusinessLogic.MailWorker; namespace MotorPlantBusinessLogic.BusinessLogics { @@ -12,15 +13,17 @@ namespace MotorPlantBusinessLogic.BusinessLogics { private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; - static readonly object _locker = new object(); + private readonly AbstractMailWorker _mailWorker; + static readonly object _locker = new object(); - public OrderLogic(ILogger logger, IOrderStorage orderStorage) + public OrderLogic(ILogger logger, IOrderStorage orderStorage, AbstractMailWorker mailWorker) { _logger = logger; _orderStorage = orderStorage; + _mailWorker = mailWorker; } - public OrderViewModel? ReadElement(OrderSearchModel model) + public OrderViewModel? ReadElement(OrderSearchModel model) { if (model == null) { @@ -60,12 +63,18 @@ namespace MotorPlantBusinessLogic.BusinessLogics return false; model.Status = OrderStatus.Принят; - if (_orderStorage.Insert(model) == null) + var element = _orderStorage.Insert(model); + if (element == null) { - model.Status = OrderStatus.Неизвестен; _logger.LogWarning("Insert operation failed"); return false; } + Task.Run(() => _mailWorker.MailSendAsync(new MailSendInfoBindingModel + { + MailAddress = element.ClientEmail, + Subject = $"Изменение статуса заказа номер {element.Id}", + Text = $"Ваш заказ номер {element.Id} на пиццу {element.EngineName} от {element.DateCreate} на сумму {element.Sum} принят." + })); return true; } @@ -123,7 +132,14 @@ namespace MotorPlantBusinessLogic.BusinessLogics _logger.LogWarning("Update operation failed"); return false; } - return true; + string DateInfo = model.DateImplement.HasValue ? $"Дата выполнения {model.DateImplement}" : ""; + Task.Run(() => _mailWorker.MailSendAsync(new MailSendInfoBindingModel + { + MailAddress = element.ClientEmail, + Subject = $"Изменение статуса заказа номер {element.Id}", + Text = $"Ваш заказ номер {element.Id} на пиццу {element.EngineName} от {element.DateCreate} на сумму {element.Sum} {model.Status}. {DateInfo}" + })); + return true; } _logger.LogWarning("Changing status operation faled: Current-{Status}:required-{requiredStatus}.", model.Status, orderStatus); throw new InvalidOperationException($"Невозможно приствоить статус {orderStatus} заказу с текущим статусом {model.Status}"); diff --git a/MotorPlant/MotorPlantBusinessLogic/MailWorker/AbstractMailWorker.cs b/MotorPlant/MotorPlantBusinessLogic/MailWorker/AbstractMailWorker.cs new file mode 100644 index 0000000..d3096dd --- /dev/null +++ b/MotorPlant/MotorPlantBusinessLogic/MailWorker/AbstractMailWorker.cs @@ -0,0 +1,85 @@ +using Microsoft.Extensions.Logging; +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.BusinessLogicsContracts; + +namespace MotorPlantBusinessLogic.MailWorker +{ + public abstract class AbstractMailWorker + { + protected string _mailLogin = string.Empty; + protected string _mailPassword = string.Empty; + protected string _smtpClientHost = string.Empty; + protected int _smtpClientPort; + protected string _popHost = string.Empty; + protected int _popPort; + private readonly IMessageInfoLogic _messageInfoLogic; + private readonly ILogger _logger; + + public AbstractMailWorker(ILogger logger, IMessageInfoLogic messageInfoLogic) + { + _logger = logger; + _messageInfoLogic = messageInfoLogic; + } + + public void MailConfig(MailConfigBindingModel config) + { + _mailLogin = config.MailLogin; + _mailPassword = config.MailPassword; + _smtpClientHost = config.SmtpClientHost; + _smtpClientPort = config.SmtpClientPort; + _popHost = config.PopHost; + _popPort = config.PopPort; + _logger.LogDebug("Config: {login}, {password}, {clientHost}, {clientPOrt}, {popHost}, {popPort}", _mailLogin, _mailPassword.Length, _smtpClientHost, _smtpClientPort, _popHost, _popPort); + } + + public async void MailSendAsync(MailSendInfoBindingModel info) + { + if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword)) + { + return; + } + + if (string.IsNullOrEmpty(_smtpClientHost) || _smtpClientPort == 0) + { + return; + } + + if (string.IsNullOrEmpty(info.MailAddress) || string.IsNullOrEmpty(info.Subject) || string.IsNullOrEmpty(info.Text)) + { + return; + } + + _logger.LogDebug("Send Mail: {To}, {Subject}", info.MailAddress, info.Subject); + await SendMailAsync(info); + } + + public async void MailCheck() + { + if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword)) + { + return; + } + + if (string.IsNullOrEmpty(_popHost) || _popPort == 0) + { + return; + } + + if (_messageInfoLogic == null) + { + return; + } + + var list = await ReceiveMailAsync(); + _logger.LogDebug("Check Mail: {Count} new mails", list.Count); + foreach (var mail in list) + { + _messageInfoLogic.Create(mail); + } + } + + protected abstract Task SendMailAsync(MailSendInfoBindingModel info); + + protected abstract Task> ReceiveMailAsync(); + } +} diff --git a/MotorPlant/MotorPlantBusinessLogic/MailWorker/MailKitWorker.cs b/MotorPlant/MotorPlantBusinessLogic/MailWorker/MailKitWorker.cs new file mode 100644 index 0000000..1198a60 --- /dev/null +++ b/MotorPlant/MotorPlantBusinessLogic/MailWorker/MailKitWorker.cs @@ -0,0 +1,78 @@ +using MailKit.Net.Pop3; +using MailKit.Security; +using Microsoft.Extensions.Logging; +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.BusinessLogicsContracts; +using System.Net; +using System.Net.Mail; +using System.Text; + +namespace MotorPlantBusinessLogic.MailWorker +{ + public class MailKitWorker : AbstractMailWorker + { + public MailKitWorker(ILogger logger, IMessageInfoLogic messageInfoLogic) : base(logger, messageInfoLogic) { } + + protected override async Task SendMailAsync(MailSendInfoBindingModel info) + { + using var objMailMessage = new MailMessage(); + using var objSmtpClient = new SmtpClient(_smtpClientHost, _smtpClientPort); + try + { + objMailMessage.From = new MailAddress(_mailLogin); + objMailMessage.To.Add(new MailAddress(info.MailAddress)); + objMailMessage.Subject = info.Subject; + objMailMessage.Body = info.Text; + objMailMessage.SubjectEncoding = Encoding.UTF8; + objMailMessage.BodyEncoding = Encoding.UTF8; + + objSmtpClient.UseDefaultCredentials = false; + objSmtpClient.EnableSsl = true; + objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; + objSmtpClient.Credentials = new NetworkCredential(_mailLogin, _mailPassword); + + await Task.Run(() => objSmtpClient.Send(objMailMessage)); + } + catch (Exception) + { + throw; + } + } + + protected override async Task> ReceiveMailAsync() + { + var list = new List(); + using var client = new Pop3Client(); + await Task.Run(() => + { + try + { + client.Connect(_popHost, _popPort, SecureSocketOptions.SslOnConnect); + client.Authenticate(_mailLogin, _mailPassword); + for (int i = 0; i < client.Count; i++) + { + var message = client.GetMessage(i); + foreach (var mail in message.From.Mailboxes) + { + list.Add(new MessageInfoBindingModel + { + DateDelivery = message.Date.DateTime, + MessageId = message.MessageId, + SenderName = mail.Address, + Subject = message.Subject, + Body = message.TextBody + }); + } + } + } + catch (MailKit.Security.AuthenticationException) + { } + finally + { + client.Disconnect(true); + } + }); + return list; + } + } +} diff --git a/MotorPlant/MotorPlantBusinessLogic/MotorPlantBusinessLogic.csproj b/MotorPlant/MotorPlantBusinessLogic/MotorPlantBusinessLogic.csproj index 5d4f1a4..b189a5b 100644 --- a/MotorPlant/MotorPlantBusinessLogic/MotorPlantBusinessLogic.csproj +++ b/MotorPlant/MotorPlantBusinessLogic/MotorPlantBusinessLogic.csproj @@ -8,6 +8,7 @@ + diff --git a/MotorPlant/MotorPlantClientApp/Controllers/HomeController.cs b/MotorPlant/MotorPlantClientApp/Controllers/HomeController.cs index 2eef108..6e41664 100644 --- a/MotorPlant/MotorPlantClientApp/Controllers/HomeController.cs +++ b/MotorPlant/MotorPlantClientApp/Controllers/HomeController.cs @@ -140,5 +140,15 @@ namespace MotorPlantClientApp.Controllers APIClient.GetRequest($"api/Main/GetEngine?engineId={engine}"); return count * (eng?.Price ?? 1); } - } + + [HttpGet] + public IActionResult Mails() + { + if (APIClient.Client == null) + { + return Redirect("~/Home/Enter"); + } + return View(APIClient.GetRequest>($"api/client/getmessages?clientId={APIClient.Client.Id}")); + } + } } \ No newline at end of file diff --git a/MotorPlant/MotorPlantClientApp/Views/Home/Mails.cshtml b/MotorPlant/MotorPlantClientApp/Views/Home/Mails.cshtml new file mode 100644 index 0000000..85fa003 --- /dev/null +++ b/MotorPlant/MotorPlantClientApp/Views/Home/Mails.cshtml @@ -0,0 +1,55 @@ +@using MotorPlantContracts.ViewModels + +@model List + +@{ + ViewData["Title"] = "Mails"; +} + + +
+

Заказы

+
+ + +
+ @{ + if (Model == null) + { +

Авторизируйтесь

+ return; + } + + + + + + + + + + + @foreach (var item in Model) + { + + + + + + } + +
+ Дата письма + + Заголовок + + Текст +
+ @Html.DisplayFor(modelItem => item.DateDelivery) + + @Html.DisplayFor(modelItem => item.Subject) + + @Html.DisplayFor(modelItem => item.Body) +
+ } +
\ No newline at end of file diff --git a/MotorPlant/MotorPlantClientApp/Views/Shared/_Layout.cshtml b/MotorPlant/MotorPlantClientApp/Views/Shared/_Layout.cshtml index e5934b1..25e0442 100644 --- a/MotorPlant/MotorPlantClientApp/Views/Shared/_Layout.cshtml +++ b/MotorPlant/MotorPlantClientApp/Views/Shared/_Layout.cshtml @@ -26,6 +26,9 @@ + diff --git a/MotorPlant/MotorPlantContracts/BindingModels/MailConfigBindingModel.cs b/MotorPlant/MotorPlantContracts/BindingModels/MailConfigBindingModel.cs new file mode 100644 index 0000000..984f565 --- /dev/null +++ b/MotorPlant/MotorPlantContracts/BindingModels/MailConfigBindingModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.BindingModels +{ + public class MailConfigBindingModel + { + public string MailLogin { get; set; } = string.Empty; + public string MailPassword { get; set; } = string.Empty; + public string SmtpClientHost { get; set; } = string.Empty; + public int SmtpClientPort { get; set; } + public string PopHost { get; set; } = string.Empty; + public int PopPort { get; set; } + } +} diff --git a/MotorPlant/MotorPlantContracts/BindingModels/MailSendInfoBindingModel.cs b/MotorPlant/MotorPlantContracts/BindingModels/MailSendInfoBindingModel.cs new file mode 100644 index 0000000..a7594a0 --- /dev/null +++ b/MotorPlant/MotorPlantContracts/BindingModels/MailSendInfoBindingModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.BindingModels +{ + public class MailSendInfoBindingModel + { + public string MailAddress { get; set; } = string.Empty; + public string Subject { get; set; } = string.Empty; + public string Text { get; set; } = string.Empty; + } +} diff --git a/MotorPlant/MotorPlantContracts/BindingModels/MessageInfoBindingModel.cs b/MotorPlant/MotorPlantContracts/BindingModels/MessageInfoBindingModel.cs new file mode 100644 index 0000000..a940c2a --- /dev/null +++ b/MotorPlant/MotorPlantContracts/BindingModels/MessageInfoBindingModel.cs @@ -0,0 +1,19 @@ +using MotorPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.BindingModels +{ + public class MessageInfoBindingModel : IMessageInfoModel + { + public string MessageId { get; set; } = string.Empty; + public int? ClientId { get; set; } + public string SenderName { get; set; } = string.Empty; + public string Subject { get; set; } = string.Empty; + public string Body { get; set; } = string.Empty; + public DateTime DateDelivery { get; set; } + } +} diff --git a/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IMessageInfoLogic.cs b/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IMessageInfoLogic.cs new file mode 100644 index 0000000..3ea3187 --- /dev/null +++ b/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IMessageInfoLogic.cs @@ -0,0 +1,17 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.BusinessLogicsContracts +{ + public interface IMessageInfoLogic + { + List ReadList(MessageInfoSearchModel? model); + bool Create(MessageInfoBindingModel model); + } +} diff --git a/MotorPlant/MotorPlantContracts/SearchModels/ClientSearchModel.cs b/MotorPlant/MotorPlantContracts/SearchModels/ClientSearchModel.cs index 1949867..833cedd 100644 --- a/MotorPlant/MotorPlantContracts/SearchModels/ClientSearchModel.cs +++ b/MotorPlant/MotorPlantContracts/SearchModels/ClientSearchModel.cs @@ -3,6 +3,7 @@ public class ClientSearchModel { public int? Id { get; set; } + public string? ClientFIO { get; set; } public string? Email { get; set; } public string? Password { get; set; } } diff --git a/MotorPlant/MotorPlantContracts/SearchModels/MessageInfoSearchModel.cs b/MotorPlant/MotorPlantContracts/SearchModels/MessageInfoSearchModel.cs new file mode 100644 index 0000000..a0de553 --- /dev/null +++ b/MotorPlant/MotorPlantContracts/SearchModels/MessageInfoSearchModel.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.SearchModels +{ + public class MessageInfoSearchModel + { + public int? ClientId { get; set; } + public string? MessageId { get; set;} + } +} diff --git a/MotorPlant/MotorPlantContracts/StoragesContracts/IMessageInfoStorage.cs b/MotorPlant/MotorPlantContracts/StoragesContracts/IMessageInfoStorage.cs new file mode 100644 index 0000000..8ecd007 --- /dev/null +++ b/MotorPlant/MotorPlantContracts/StoragesContracts/IMessageInfoStorage.cs @@ -0,0 +1,19 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.StoragesContracts +{ + public interface IMessageInfoStorage + { + List GetFullList(); + List GetFilteredList(MessageInfoSearchModel model); + MessageInfoViewModel? GetElement(MessageInfoSearchModel model); + MessageInfoViewModel? Insert(MessageInfoBindingModel model); + } +} diff --git a/MotorPlant/MotorPlantContracts/ViewModels/MessageInfoViewModel.cs b/MotorPlant/MotorPlantContracts/ViewModels/MessageInfoViewModel.cs new file mode 100644 index 0000000..c5db751 --- /dev/null +++ b/MotorPlant/MotorPlantContracts/ViewModels/MessageInfoViewModel.cs @@ -0,0 +1,29 @@ +using MotorPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.ViewModels +{ + public class MessageInfoViewModel : IMessageInfoModel + { + public string MessageId { get; set; } = string.Empty; + + public int? ClientId { get; set; } + + [DisplayName("Отправитель")] + public string SenderName { get; set; } = string.Empty; + + [DisplayName("Дата письма")] + public DateTime DateDelivery { get; set; } + + [DisplayName("Заголовок")] + public string Subject { get; set; } = string.Empty; + + [DisplayName("Текст")] + public string Body { get; set; } = string.Empty; + } +} diff --git a/MotorPlant/MotorPlantContracts/ViewModels/OrderViewModel.cs b/MotorPlant/MotorPlantContracts/ViewModels/OrderViewModel.cs index 7a73d3e..7889603 100644 --- a/MotorPlant/MotorPlantContracts/ViewModels/OrderViewModel.cs +++ b/MotorPlant/MotorPlantContracts/ViewModels/OrderViewModel.cs @@ -26,7 +26,9 @@ namespace MotorPlantContracts.ViewModels [DisplayName("ФИО клиента")] public string ClientFIO { get; set; } = string.Empty; - public int? ImplementerId { get; set; } + public string ClientEmail { get; set; } = string.Empty; + + public int? ImplementerId { get; set; } [DisplayName("Исполнитель")] public string? ImplementerFIO { get; set; } = null; diff --git a/MotorPlant/MotorPlantDataModels/Models/IMessageInfoModel.cs b/MotorPlant/MotorPlantDataModels/Models/IMessageInfoModel.cs new file mode 100644 index 0000000..6bda5d1 --- /dev/null +++ b/MotorPlant/MotorPlantDataModels/Models/IMessageInfoModel.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantDataModels.Models +{ + public interface IMessageInfoModel + { + string MessageId { get; } + + int? ClientId { get; } + + string SenderName { get; } + + DateTime DateDelivery { get; } + + string Subject { get; } + + string Body { get; } + } +} diff --git a/MotorPlant/MotorPlantDatabaseImplement/Implements/ClientStorage.cs b/MotorPlant/MotorPlantDatabaseImplement/Implements/ClientStorage.cs index 31fa716..71d9342 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Implements/ClientStorage.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Implements/ClientStorage.cs @@ -35,10 +35,9 @@ namespace MotorPlantDatabaseImplement.Implements return null; } using var context = new MotorPlantDatabase(); - return context.Clients - .FirstOrDefault(x => - (!string.IsNullOrEmpty(model.Email) && x.Email == model.Email) || - (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; + return context.Clients.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id) || + (!string.IsNullOrEmpty(model.ClientFIO) && x.ClientFIO == model.ClientFIO) || + (!string.IsNullOrEmpty(model.Email) && x.Email == model.Email && (string.IsNullOrEmpty(model.Password) || x.Password == model.Password)))?.GetViewModel; } public ClientViewModel? Insert(ClientBindingModel model) { diff --git a/MotorPlant/MotorPlantDatabaseImplement/Implements/MessageInfoStorage.cs b/MotorPlant/MotorPlantDatabaseImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..1028e47 --- /dev/null +++ b/MotorPlant/MotorPlantDatabaseImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,52 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.StoragesContracts; +using MotorPlantContracts.ViewModels; +using MotorPlantDatabaseImplement.Models; + + +namespace MotorPlantDatabaseImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (string.IsNullOrEmpty(model.MessageId)) + { + return null; + } + + using var context = new MotorPlantDatabase(); + + return context.MessageInfo.FirstOrDefault(x => x.MessageId == model.MessageId)?.GetViewModel; + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + if(!model.ClientId.HasValue) + { + return new(); + } + + using var context = new MotorPlantDatabase(); + + return context.MessageInfo.Where(x => x.ClientId.HasValue && x.ClientId == model.ClientId).Select(x => x.GetViewModel).ToList(); + } + + public List GetFullList() + { + using var context = new MotorPlantDatabase(); + return context.MessageInfo.Select(x => x.GetViewModel).ToList(); + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = MessageInfo.Create(model); + if (newMessage == null) return null; + using var context = new MotorPlantDatabase(); + context.MessageInfo.Add(newMessage); + context.SaveChanges(); + return newMessage.GetViewModel; + } + } +} diff --git a/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240418124911_InitMigrationFor6Lab.Designer.cs b/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240502232313_lab7Migration.Designer.cs similarity index 83% rename from MotorPlant/MotorPlantDatabaseImplement/Migrations/20240418124911_InitMigrationFor6Lab.Designer.cs rename to MotorPlant/MotorPlantDatabaseImplement/Migrations/20240502232313_lab7Migration.Designer.cs index d5a35a1..dfd22fa 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240418124911_InitMigrationFor6Lab.Designer.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240502232313_lab7Migration.Designer.cs @@ -12,8 +12,8 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; namespace MotorPlantDatabaseImplement.Migrations { [DbContext(typeof(MotorPlantDatabase))] - [Migration("20240418124911_InitMigrationFor6Lab")] - partial class InitMigrationFor6Lab + [Migration("20240502232313_lab7Migration")] + partial class lab7Migration { /// protected override void BuildTargetModel(ModelBuilder modelBuilder) @@ -143,6 +143,36 @@ namespace MotorPlantDatabaseImplement.Migrations b.ToTable("Implementers"); }); + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.MessageInfo", b => + { + b.Property("MessageId") + .HasColumnType("text"); + + b.Property("Body") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientId") + .HasColumnType("integer"); + + b.Property("DateDelivery") + .HasColumnType("timestamp without time zone"); + + b.Property("SenderName") + .IsRequired() + .HasColumnType("text"); + + b.Property("Subject") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("MessageId"); + + b.HasIndex("ClientId"); + + b.ToTable("MessageInfo"); + }); + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -205,10 +235,19 @@ namespace MotorPlantDatabaseImplement.Migrations b.Navigation("Engine"); }); + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.MessageInfo", b => + { + b.HasOne("MotorPlantDatabaseImplement.Models.Client", "Client") + .WithMany("ClientMessages") + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Order", b => { b.HasOne("MotorPlantDatabaseImplement.Models.Client", "Client") - .WithMany() + .WithMany("ClientOrders") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); @@ -230,6 +269,13 @@ namespace MotorPlantDatabaseImplement.Migrations b.Navigation("Implementer"); }); + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Client", b => + { + b.Navigation("ClientMessages"); + + b.Navigation("ClientOrders"); + }); + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Component", b => { b.Navigation("EngineComponents"); diff --git a/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240418124911_InitMigrationFor6Lab.cs b/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240502232313_lab7Migration.cs similarity index 85% rename from MotorPlant/MotorPlantDatabaseImplement/Migrations/20240418124911_InitMigrationFor6Lab.cs rename to MotorPlant/MotorPlantDatabaseImplement/Migrations/20240502232313_lab7Migration.cs index 7da9be1..6e80804 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240418124911_InitMigrationFor6Lab.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240502232313_lab7Migration.cs @@ -7,7 +7,7 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; namespace MotorPlantDatabaseImplement.Migrations { /// - public partial class InitMigrationFor6Lab : Migration + public partial class lab7Migration : Migration { /// protected override void Up(MigrationBuilder migrationBuilder) @@ -71,6 +71,27 @@ namespace MotorPlantDatabaseImplement.Migrations table.PrimaryKey("PK_Implementers", x => x.Id); }); + migrationBuilder.CreateTable( + name: "MessageInfo", + columns: table => new + { + MessageId = table.Column(type: "text", nullable: false), + ClientId = table.Column(type: "integer", nullable: true), + SenderName = table.Column(type: "text", nullable: false), + DateDelivery = table.Column(type: "timestamp without time zone", nullable: false), + Subject = table.Column(type: "text", nullable: false), + Body = table.Column(type: "text", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_MessageInfo", x => x.MessageId); + table.ForeignKey( + name: "FK_MessageInfo_Clients_ClientId", + column: x => x.ClientId, + principalTable: "Clients", + principalColumn: "Id"); + }); + migrationBuilder.CreateTable( name: "EngineComponents", columns: table => new @@ -145,6 +166,11 @@ namespace MotorPlantDatabaseImplement.Migrations table: "EngineComponents", column: "EngineId"); + migrationBuilder.CreateIndex( + name: "IX_MessageInfo_ClientId", + table: "MessageInfo", + column: "ClientId"); + migrationBuilder.CreateIndex( name: "IX_Orders_ClientId", table: "Orders", @@ -167,6 +193,9 @@ namespace MotorPlantDatabaseImplement.Migrations migrationBuilder.DropTable( name: "EngineComponents"); + migrationBuilder.DropTable( + name: "MessageInfo"); + migrationBuilder.DropTable( name: "Orders"); diff --git a/MotorPlant/MotorPlantDatabaseImplement/Migrations/MotorPlantDatabaseModelSnapshot.cs b/MotorPlant/MotorPlantDatabaseImplement/Migrations/MotorPlantDatabaseModelSnapshot.cs index 54df4a7..20ec5f0 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Migrations/MotorPlantDatabaseModelSnapshot.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Migrations/MotorPlantDatabaseModelSnapshot.cs @@ -140,6 +140,36 @@ namespace MotorPlantDatabaseImplement.Migrations b.ToTable("Implementers"); }); + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.MessageInfo", b => + { + b.Property("MessageId") + .HasColumnType("text"); + + b.Property("Body") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientId") + .HasColumnType("integer"); + + b.Property("DateDelivery") + .HasColumnType("timestamp without time zone"); + + b.Property("SenderName") + .IsRequired() + .HasColumnType("text"); + + b.Property("Subject") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("MessageId"); + + b.HasIndex("ClientId"); + + b.ToTable("MessageInfo"); + }); + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -202,10 +232,19 @@ namespace MotorPlantDatabaseImplement.Migrations b.Navigation("Engine"); }); + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.MessageInfo", b => + { + b.HasOne("MotorPlantDatabaseImplement.Models.Client", "Client") + .WithMany("ClientMessages") + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Order", b => { b.HasOne("MotorPlantDatabaseImplement.Models.Client", "Client") - .WithMany() + .WithMany("ClientOrders") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); @@ -227,6 +266,13 @@ namespace MotorPlantDatabaseImplement.Migrations b.Navigation("Implementer"); }); + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Client", b => + { + b.Navigation("ClientMessages"); + + b.Navigation("ClientOrders"); + }); + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Component", b => { b.Navigation("EngineComponents"); diff --git a/MotorPlant/MotorPlantDatabaseImplement/Models/Client.cs b/MotorPlant/MotorPlantDatabaseImplement/Models/Client.cs index e9e6a60..6702cfd 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Models/Client.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Models/Client.cs @@ -2,6 +2,7 @@ using MotorPlantContracts.ViewModels; using MotorPlantDataModels.Models; using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; namespace MotorPlantDatabaseImplement.Models { @@ -14,6 +15,13 @@ namespace MotorPlantDatabaseImplement.Models public string Email { get; private set; } = string.Empty; [Required] public string Password { get; private set; } = string.Empty; + + [ForeignKey("ClientId")] + public virtual List ClientOrders { get; set; } = new(); + + [ForeignKey("ClientId")] + public virtual List ClientMessages { get; set; } = new(); + public static Client? Create(ClientBindingModel model) { if (model == null) diff --git a/MotorPlant/MotorPlantDatabaseImplement/Models/MessageInfo.cs b/MotorPlant/MotorPlantDatabaseImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..5a6ecd4 --- /dev/null +++ b/MotorPlant/MotorPlantDatabaseImplement/Models/MessageInfo.cs @@ -0,0 +1,59 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.ViewModels; +using MotorPlantDataModels.Models; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace MotorPlantDatabaseImplement.Models +{ + public class MessageInfo : IMessageInfoModel + { + [Key] + [DatabaseGenerated(DatabaseGeneratedOption.None)] + public string MessageId { get; set; } = string.Empty; + + public int? ClientId { get; set; } + + public virtual Client? Client { get; set; } + + [Required] + public string SenderName { get; set; } = string.Empty; + + [Required] + public DateTime DateDelivery { get; set; } + + [Required] + public string Subject { get; set; } = string.Empty; + + [Required] + public string Body { get; set; } = string.Empty; + + public static MessageInfo? Create(MessageInfoBindingModel? model) + { + if (model == null) + { + return null; + } + return new() + { + MessageId = model.MessageId, + ClientId = model.ClientId, + SenderName = model.SenderName, + DateDelivery = model.DateDelivery, + Subject = model.Subject, + Body = model.Body, + + }; + } + + public MessageInfoViewModel GetViewModel => new() + { + MessageId = MessageId, + ClientId = ClientId, + SenderName = SenderName, + DateDelivery = DateDelivery, + Subject = Subject, + Body = Body + }; + } +} diff --git a/MotorPlant/MotorPlantDatabaseImplement/Models/Order.cs b/MotorPlant/MotorPlantDatabaseImplement/Models/Order.cs index b999356..91c89ff 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Models/Order.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Models/Order.cs @@ -76,7 +76,8 @@ namespace MotorPlantDatabaseImplement.Models EngineName = Engine.EngineName, ClientId = ClientId, ClientFIO = Client.ClientFIO, - ImplementerId = ImplementerId, + ClientEmail = Client.Email, + ImplementerId = ImplementerId, ImplementerFIO = Implementer != null ? Implementer.ImplementerFIO : null, Count = Count, Sum = Sum, diff --git a/MotorPlant/MotorPlantDatabaseImplement/MotorPlantDatabase.cs b/MotorPlant/MotorPlantDatabaseImplement/MotorPlantDatabase.cs index 6726d1d..47139cf 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/MotorPlantDatabase.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/MotorPlantDatabase.cs @@ -9,7 +9,7 @@ namespace MotorPlantDatabaseImplement { if (optionsBuilder.IsConfigured == false) { - optionsBuilder.UseNpgsql(@"Host=localhost;Port=5432;Database=MotorPlant_lab6_db;Username=postgres;Password=admin"); + optionsBuilder.UseNpgsql(@"Host=localhost;Port=5432;Database=MotorPlant_lab7_db;Username=postgres;Password=admin"); } base.OnConfiguring(optionsBuilder); AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true); @@ -21,5 +21,6 @@ namespace MotorPlantDatabaseImplement public virtual DbSet Orders { get; set; } public virtual DbSet Clients { set; get; } public virtual DbSet Implementers { set; get; } - } + public virtual DbSet MessageInfo { set; get; } + } } \ No newline at end of file diff --git a/MotorPlant/MotorPlantFileImplement/DataFileSingleton.cs b/MotorPlant/MotorPlantFileImplement/DataFileSingleton.cs index 792d531..6323bd0 100644 --- a/MotorPlant/MotorPlantFileImplement/DataFileSingleton.cs +++ b/MotorPlant/MotorPlantFileImplement/DataFileSingleton.cs @@ -17,7 +17,9 @@ namespace MotorPlantFileImplement private readonly string ImplementerFileName = "Implementer.xml"; - public List Components { get; private set; } + private readonly string MessageInfoFileName = "MessageInfo.xml"; + + public List Components { get; private set; } public List Orders { get; private set; } @@ -27,8 +29,11 @@ namespace MotorPlantFileImplement public List Implementers { get; private set; } + public List Messages { get; private set; } - public static DataFileSingleton GetInstance() + + + public static DataFileSingleton GetInstance() { if (instance == null) { @@ -46,16 +51,20 @@ namespace MotorPlantFileImplement public void SaveImplementers() => SaveData(Implementers, ImplementerFileName, "Implementers", x => x.GetXElement); - private DataFileSingleton() + public void SaveMessages() => SaveData(Orders, ImplementerFileName, "Messages", x => x.GetXElement); + + + private DataFileSingleton() { Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!; Engines = LoadData(EngineFileName, "Engine", x => Engine.Create(x)!)!; Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!; Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!; Implementers = LoadData(ImplementerFileName, "Implementer", x => Implementer.Create(x)!)!; - } + Messages = LoadData(MessageInfoFileName, "MessageInfo", x => MessageInfo.Create(x)!)!; + } - private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) + private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) { if (File.Exists(filename)) { diff --git a/MotorPlant/MotorPlantFileImplement/Implements/MessageInfoStorage.cs b/MotorPlant/MotorPlantFileImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..ce98e77 --- /dev/null +++ b/MotorPlant/MotorPlantFileImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,53 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.StoragesContracts; +using MotorPlantContracts.ViewModels; +using MotorPlantFileImplement.Models; + +namespace MotorPlantFileImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + private readonly DataFileSingleton _source; + public MessageInfoStorage() + { + _source = DataFileSingleton.GetInstance(); + } + + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (model.MessageId != null) + { + return _source.Messages.FirstOrDefault(x => x.MessageId == model.MessageId)?.GetViewModel; + } + return null; + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + return _source.Messages + .Where(x => x.ClientId == model.ClientId) + .Select(x => x.GetViewModel) + .ToList(); + } + + public List GetFullList() + { + return _source.Messages + .Select(x => x.GetViewModel) + .ToList(); + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = MessageInfo.Create(model); + if (newMessage == null) + { + return null; + } + _source.Messages.Add(newMessage); + _source.SaveMessages(); + return newMessage.GetViewModel; + } + } +} diff --git a/MotorPlant/MotorPlantFileImplement/Models/MessageInfo.cs b/MotorPlant/MotorPlantFileImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..b8c9785 --- /dev/null +++ b/MotorPlant/MotorPlantFileImplement/Models/MessageInfo.cs @@ -0,0 +1,75 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.ViewModels; +using MotorPlantDataModels.Models; +using System.Xml.Linq; + +namespace MotorPlantFileImplement.Models +{ + public class MessageInfo : IMessageInfoModel + { + public string MessageId { get; private set; } = string.Empty; + + public int? ClientId { get; private set; } + + public string SenderName { get; private set; } = string.Empty; + + public DateTime DateDelivery { get; private set; } = DateTime.Now; + + public string Subject { get; private set; } = string.Empty; + + public string Body { get; private set; } = string.Empty; + + public static MessageInfo? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Subject = model.Subject, + ClientId = model.ClientId, + MessageId = model.MessageId, + SenderName = model.SenderName, + DateDelivery = model.DateDelivery, + }; + } + + public static MessageInfo? Create(XElement element) + { + if (element == null) + { + return null; + } + return new() + { + Body = element.Attribute("Body")!.Value, + Subject = element.Attribute("Subject")!.Value, + ClientId = Convert.ToInt32(element.Attribute("ClientId")!.Value), + MessageId = element.Attribute("MessageId")!.Value, + SenderName = element.Attribute("SenderName")!.Value, + DateDelivery = Convert.ToDateTime(element.Attribute("DateDelivery")!.Value), + }; + } + + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Subject = Subject, + ClientId = ClientId, + MessageId = MessageId, + SenderName = SenderName, + DateDelivery = DateDelivery, + }; + + public XElement GetXElement => new("MessageInfo", + new XAttribute("Body", Body), + new XAttribute("Subject", Subject), + new XAttribute("ClientId", ClientId), + new XAttribute("MessageId", MessageId), + new XAttribute("SenderName", SenderName), + new XAttribute("DateDelivery", DateDelivery) + ); + } +} diff --git a/MotorPlant/MotorPlantListImplement/DataListSingleton.cs b/MotorPlant/MotorPlantListImplement/DataListSingleton.cs index 8a24804..7e47704 100644 --- a/MotorPlant/MotorPlantListImplement/DataListSingleton.cs +++ b/MotorPlant/MotorPlantListImplement/DataListSingleton.cs @@ -16,16 +16,19 @@ namespace MotorPlantListImplement public List Implementers { get; set; } - private DataListSingleton() + public List Messages { get; set; } + + private DataListSingleton() { Components = new List(); Orders = new List(); Engines = new List(); Clients = new List(); Implementers = new List(); - } + Messages = new List(); + } - public static DataListSingleton GetInstance() + public static DataListSingleton GetInstance() { if (_instance == null) { diff --git a/MotorPlant/MotorPlantListImplement/Implements/MessageInfoStorage.cs b/MotorPlant/MotorPlantListImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..a9437ab --- /dev/null +++ b/MotorPlant/MotorPlantListImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,63 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.StoragesContracts; +using MotorPlantContracts.ViewModels; +using MotorPlantListImplement.Models; + +namespace MotorPlantListImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + private readonly DataListSingleton _source; + public MessageInfoStorage() + { + _source = DataListSingleton.GetInstance(); + } + + public List GetFullList() + { + List result = new(); + foreach (var item in _source.Messages) + { + result.Add(item.GetViewModel); + } + return result; + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + List result = new(); + foreach (var item in _source.Messages) + { + if (item.ClientId.HasValue && item.ClientId == model.ClientId) + { + result.Add(item.GetViewModel); + } + } + return result; + } + + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + foreach (var message in _source.Messages) + { + if (model.MessageId != null && model.MessageId.Equals(message.MessageId)) + { + return message.GetViewModel; + } + } + return null; + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = MessageInfo.Create(model); + if (newMessage == null) + { + return null; + } + _source.Messages.Add(newMessage); + return newMessage.GetViewModel; + } + } +} diff --git a/MotorPlant/MotorPlantListImplement/Models/MessageInfo.cs b/MotorPlant/MotorPlantListImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..7c90ac7 --- /dev/null +++ b/MotorPlant/MotorPlantListImplement/Models/MessageInfo.cs @@ -0,0 +1,48 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.ViewModels; +using MotorPlantDataModels.Models; + +namespace MotorPlantListImplement.Models +{ + public class MessageInfo : IMessageInfoModel + { + public string MessageId { get; private set; } = string.Empty; + + public int? ClientId { get; private set; } + + public string SenderName { get; private set; } = string.Empty; + + public DateTime DateDelivery { get; private set; } = DateTime.Now; + + public string Subject { get; private set; } = string.Empty; + + public string Body { get; private set; } = string.Empty; + + public static MessageInfo? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Subject = model.Subject, + ClientId = model.ClientId, + MessageId = model.MessageId, + SenderName = model.SenderName, + DateDelivery = model.DateDelivery, + }; + } + + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Subject = Subject, + ClientId = ClientId, + MessageId = MessageId, + SenderName = SenderName, + DateDelivery = DateDelivery, + }; + } +} diff --git a/MotorPlant/MotorPlantRestApi/Controllers/ClientController.cs b/MotorPlant/MotorPlantRestApi/Controllers/ClientController.cs index 3c0ba19..b95ca6d 100644 --- a/MotorPlant/MotorPlantRestApi/Controllers/ClientController.cs +++ b/MotorPlant/MotorPlantRestApi/Controllers/ClientController.cs @@ -3,6 +3,7 @@ using MotorPlantContracts.BusinessLogicsContracts; using MotorPlantContracts.SearchModels; using MotorPlantContracts.ViewModels; using Microsoft.AspNetCore.Mvc; +using System.Net; namespace MotorPlantRestApi.Controllers { @@ -12,10 +13,13 @@ namespace MotorPlantRestApi.Controllers { private readonly ILogger _logger; private readonly IClientLogic _logic; - public ClientController(IClientLogic logic, ILogger logger) + private readonly IMessageInfoLogic _mailLogic; + + public ClientController(IClientLogic logic, ILogger logger, IMessageInfoLogic mailLogic) { _logger = logger; _logic = logic; + _mailLogic = mailLogic; } [HttpGet] public ClientViewModel? Login(string login, string password) @@ -60,6 +64,22 @@ namespace MotorPlantRestApi.Controllers throw; } } - } + [HttpGet] + public List? GetMessages(int clientId) + { + try + { + return _mailLogic.ReadList(new MessageInfoSearchModel + { + ClientId = clientId + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения писем клиента"); + throw; + } + } + } } diff --git a/MotorPlant/MotorPlantRestApi/MotorPlantRestApi.csproj b/MotorPlant/MotorPlantRestApi/MotorPlantRestApi.csproj index 263252f..3dcc529 100644 --- a/MotorPlant/MotorPlantRestApi/MotorPlantRestApi.csproj +++ b/MotorPlant/MotorPlantRestApi/MotorPlantRestApi.csproj @@ -7,6 +7,10 @@ + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/MotorPlant/MotorPlantRestApi/Program.cs b/MotorPlant/MotorPlantRestApi/Program.cs index 57c56d7..d88f032 100644 --- a/MotorPlant/MotorPlantRestApi/Program.cs +++ b/MotorPlant/MotorPlantRestApi/Program.cs @@ -1,5 +1,8 @@ using Microsoft.OpenApi.Models; +using MotorPlantBusinessLogic.BusinessLogic; using MotorPlantBusinessLogic.BusinessLogics; +using MotorPlantBusinessLogic.MailWorker; +using MotorPlantContracts.BindingModels; using MotorPlantContracts.BusinessLogicsContracts; using MotorPlantContracts.StoragesContracts; using MotorPlantDatabaseImplement.Implements; @@ -9,16 +12,19 @@ var builder = WebApplication.CreateBuilder(args); builder.Logging.SetMinimumLevel(LogLevel.Trace); builder.Logging.AddLog4Net("log4net.config"); - builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddTransient(); + +builder.Services.AddSingleton(); builder.Services.AddControllers(); @@ -34,6 +40,17 @@ builder.Services.AddSwaggerGen(c => var app = builder.Build(); +var mailSender = app.Services.GetService(); +mailSender?.MailConfig(new MailConfigBindingModel +{ + MailLogin = builder.Configuration?.GetSection("MailLogin")?.Value?.ToString() ?? string.Empty, + MailPassword = builder.Configuration?.GetSection("MailPassword")?.Value?.ToString() ?? string.Empty, + SmtpClientHost = builder.Configuration?.GetSection("SmtpClientHost")?.Value?.ToString() ?? string.Empty, + SmtpClientPort = Convert.ToInt32(builder.Configuration?.GetSection("SmtpClientPort")?.Value?.ToString()), + PopHost = builder.Configuration?.GetSection("PopHost")?.Value?.ToString() ?? string.Empty, + PopPort = Convert.ToInt32(builder.Configuration?.GetSection("PopPort")?.Value?.ToString()) +}); + // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { diff --git a/MotorPlant/MotorPlantRestApi/appsettings.json b/MotorPlant/MotorPlantRestApi/appsettings.json index 10f68b8..5f44b26 100644 --- a/MotorPlant/MotorPlantRestApi/appsettings.json +++ b/MotorPlant/MotorPlantRestApi/appsettings.json @@ -5,5 +5,11 @@ "Microsoft.AspNetCore": "Warning" } }, - "AllowedHosts": "*" + "AllowedHosts": "*", + "SmtpClientHost": "smtp.gmail.com", + "SmtpClientPort": "587", + "PopHost": "pop.gmail.com", + "PopPort": "995", + "MailLogin": "laba6workbyrpp@gmail.com", + "MailPassword": "ybrx wmzm iocn yaux" } diff --git a/MotorPlant/MotorPlantView/App.config b/MotorPlant/MotorPlantView/App.config new file mode 100644 index 0000000..1567ccd --- /dev/null +++ b/MotorPlant/MotorPlantView/App.config @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormMail.Designer.cs b/MotorPlant/MotorPlantView/FormMail.Designer.cs new file mode 100644 index 0000000..4b1b03f --- /dev/null +++ b/MotorPlant/MotorPlantView/FormMail.Designer.cs @@ -0,0 +1,67 @@ +namespace MotorPlantView +{ + partial class FormMail + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.dataGridView = new System.Windows.Forms.DataGridView(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); + this.SuspendLayout(); + // + // dataGridView + // + this.dataGridView.AllowUserToAddRows = false; + this.dataGridView.AllowUserToDeleteRows = false; + this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView.Dock = System.Windows.Forms.DockStyle.Fill; + this.dataGridView.Location = new System.Drawing.Point(0, 0); + this.dataGridView.Name = "dataGridView"; + this.dataGridView.ReadOnly = true; + this.dataGridView.RowHeadersWidth = 51; + this.dataGridView.RowTemplate.Height = 29; + this.dataGridView.Size = new System.Drawing.Size(786, 270); + this.dataGridView.TabIndex = 0; + // + // FormMail + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(786, 270); + this.Controls.Add(this.dataGridView); + this.Name = "FormMail"; + this.Text = "Письма"; + this.Load += new System.EventHandler(this.FormMail_Load); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit(); + this.ResumeLayout(false); + + } + + #endregion + + private DataGridView dataGridView; + } +} \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormMail.cs b/MotorPlant/MotorPlantView/FormMail.cs new file mode 100644 index 0000000..542ce87 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormMail.cs @@ -0,0 +1,45 @@ +using Microsoft.Extensions.Logging; +using MotorPlantContracts.BusinessLogicsContracts; + +namespace MotorPlantView +{ + public partial class FormMail : Form + { + private readonly ILogger _logger; + private readonly IMessageInfoLogic _logic; + + public FormMail(ILogger logger, IMessageInfoLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + private void LoadData() + { + try + { + var list = _logic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["MessageId"].Visible = false; + dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["Body"].AutoSizeMode = + DataGridViewAutoSizeColumnMode.Fill; + } + _logger.LogInformation("Загрузка писем"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки писем"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void FormMail_Load(object sender, EventArgs e) + { + LoadData(); + } + } +} diff --git a/MotorPlant/MotorPlantView/FormMail.resx b/MotorPlant/MotorPlantView/FormMail.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormMail.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormMain.Designer.cs b/MotorPlant/MotorPlantView/FormMain.Designer.cs index e768934..cce31d8 100644 --- a/MotorPlant/MotorPlantView/FormMain.Designer.cs +++ b/MotorPlant/MotorPlantView/FormMain.Designer.cs @@ -1,250 +1,259 @@ namespace MotorPlantView.Forms { - partial class FormMain - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; + partial class FormMain + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } - #region Windows Form Designer generated code + #region Windows Form Designer generated code - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - toolStrip1 = new ToolStrip(); - toolStripDropDownButton1 = new ToolStripDropDownButton(); - КомпонентыToolStripMenuItem = new ToolStripMenuItem(); - ДвигателиToolStripMenuItem = new ToolStripMenuItem(); - клиентыToolStripMenuItem = new ToolStripMenuItem(); - исполнителиToolStripMenuItem = new ToolStripMenuItem(); - отчетыToolStripMenuItem = new ToolStripMenuItem(); - списокДвигателейToolStripMenuItem = new ToolStripMenuItem(); - компонентыПоДвигателямToolStripMenuItem = new ToolStripMenuItem(); - списокЗаказовToolStripMenuItem = new ToolStripMenuItem(); - запускРаботToolStripMenuItem = new ToolStripMenuItem(); - buttonCreateOrder = new Button(); - buttonTakeOrderInWork = new Button(); - buttonOrderReady = new Button(); - buttonIssuedOrder = new Button(); - buttonRef = new Button(); - dataGridView = new DataGridView(); - toolStrip1.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); - SuspendLayout(); - // - // toolStrip1 - // - toolStrip1.ImageScalingSize = new Size(20, 20); - toolStrip1.Items.AddRange(new ToolStripItem[] { toolStripDropDownButton1, отчетыToolStripMenuItem, запускРаботToolStripMenuItem }); - toolStrip1.Location = new Point(0, 0); - toolStrip1.Name = "toolStrip1"; - toolStrip1.Size = new Size(985, 25); - toolStrip1.TabIndex = 0; - toolStrip1.Text = "toolStrip1"; - // - // toolStripDropDownButton1 - // - toolStripDropDownButton1.DisplayStyle = ToolStripItemDisplayStyle.Text; - toolStripDropDownButton1.DropDownItems.AddRange(new ToolStripItem[] { КомпонентыToolStripMenuItem, ДвигателиToolStripMenuItem, клиентыToolStripMenuItem, исполнителиToolStripMenuItem }); - toolStripDropDownButton1.ImageTransparentColor = Color.Magenta; - toolStripDropDownButton1.Name = "toolStripDropDownButton1"; - toolStripDropDownButton1.Size = new Size(88, 22); - toolStripDropDownButton1.Text = "Справочник"; - // - // КомпонентыToolStripMenuItem - // - КомпонентыToolStripMenuItem.Name = "КомпонентыToolStripMenuItem"; - КомпонентыToolStripMenuItem.Size = new Size(149, 22); - КомпонентыToolStripMenuItem.Text = "Компоненты"; - КомпонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click; - // - // ДвигателиToolStripMenuItem - // - ДвигателиToolStripMenuItem.Name = "ДвигателиToolStripMenuItem"; - ДвигателиToolStripMenuItem.Size = new Size(149, 22); - ДвигателиToolStripMenuItem.Text = "Двигатели"; - ДвигателиToolStripMenuItem.Click += ИзделияToolStripMenuItem_Click; - // - // клиентыToolStripMenuItem - // - клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; - клиентыToolStripMenuItem.Size = new Size(149, 22); - клиентыToolStripMenuItem.Text = "Клиенты"; - клиентыToolStripMenuItem.Click += клиентыToolStripMenuItem_Click; - // - // исполнителиToolStripMenuItem - // - исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; - исполнителиToolStripMenuItem.Size = new Size(149, 22); - исполнителиToolStripMenuItem.Text = "Исполнители"; - исполнителиToolStripMenuItem.Click += исполнителиToolStripMenuItem_Click; - // - // отчетыToolStripMenuItem - // - отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокДвигателейToolStripMenuItem, компонентыПоДвигателямToolStripMenuItem, списокЗаказовToolStripMenuItem }); - отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem"; - отчетыToolStripMenuItem.Size = new Size(60, 25); - отчетыToolStripMenuItem.Text = "Отчеты"; - // - // списокДвигателейToolStripMenuItem - // - списокДвигателейToolStripMenuItem.Name = "списокДвигателейToolStripMenuItem"; - списокДвигателейToolStripMenuItem.Size = new Size(228, 22); - списокДвигателейToolStripMenuItem.Text = "Список двигателей"; - списокДвигателейToolStripMenuItem.Click += списокДвигателейToolStripMenuItem_Click; - // - // компонентыПоДвигателямToolStripMenuItem - // - компонентыПоДвигателямToolStripMenuItem.Name = "компонентыПоДвигателямToolStripMenuItem"; - компонентыПоДвигателямToolStripMenuItem.Size = new Size(228, 22); - компонентыПоДвигателямToolStripMenuItem.Text = "Компоненты по двигателям"; - компонентыПоДвигателямToolStripMenuItem.Click += компонентыПоДвигателямToolStripMenuItem_Click; - // - // списокЗаказовToolStripMenuItem - // - списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem"; - списокЗаказовToolStripMenuItem.Size = new Size(228, 22); - списокЗаказовToolStripMenuItem.Text = "Список заказов"; - списокЗаказовToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click; - // - // запускРаботToolStripMenuItem - // - запускРаботToolStripMenuItem.Name = "запускРаботToolStripMenuItem"; - запускРаботToolStripMenuItem.Size = new Size(92, 25); - запускРаботToolStripMenuItem.Text = "Запуск работ"; - запускРаботToolStripMenuItem.Click += запускРаботToolStripMenuItem_Click; - // - // buttonCreateOrder - // - buttonCreateOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; - buttonCreateOrder.BackColor = SystemColors.ControlLight; - buttonCreateOrder.Location = new Point(797, 146); - buttonCreateOrder.Name = "buttonCreateOrder"; - buttonCreateOrder.Size = new Size(178, 30); - buttonCreateOrder.TabIndex = 1; - buttonCreateOrder.Text = "Создать заказ"; - buttonCreateOrder.UseVisualStyleBackColor = false; - buttonCreateOrder.Click += buttonCreateOrder_Click; - // - // buttonTakeOrderInWork - // - buttonTakeOrderInWork.Anchor = AnchorStyles.Top | AnchorStyles.Right; - buttonTakeOrderInWork.BackColor = SystemColors.ControlLight; - buttonTakeOrderInWork.Location = new Point(797, 194); - buttonTakeOrderInWork.Name = "buttonTakeOrderInWork"; - buttonTakeOrderInWork.Size = new Size(178, 30); - buttonTakeOrderInWork.TabIndex = 2; - buttonTakeOrderInWork.Text = "Отдать на выполнение"; - buttonTakeOrderInWork.UseVisualStyleBackColor = false; - buttonTakeOrderInWork.Click += buttonTakeOrderInWork_Click; - // - // buttonOrderReady - // - buttonOrderReady.Anchor = AnchorStyles.Top | AnchorStyles.Right; - buttonOrderReady.BackColor = SystemColors.ControlLight; - buttonOrderReady.Location = new Point(797, 242); - buttonOrderReady.Name = "buttonOrderReady"; - buttonOrderReady.Size = new Size(178, 30); - buttonOrderReady.TabIndex = 3; - buttonOrderReady.Text = "Заказ готов"; - buttonOrderReady.UseVisualStyleBackColor = false; - buttonOrderReady.Click += buttonOrderReady_Click; - // - // buttonIssuedOrder - // - buttonIssuedOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; - buttonIssuedOrder.BackColor = SystemColors.ControlLight; - buttonIssuedOrder.Location = new Point(797, 287); - buttonIssuedOrder.Name = "buttonIssuedOrder"; - buttonIssuedOrder.Size = new Size(178, 30); - buttonIssuedOrder.TabIndex = 4; - buttonIssuedOrder.Text = "Заказ выдан"; - buttonIssuedOrder.UseVisualStyleBackColor = false; - buttonIssuedOrder.Click += buttonIssuedOrder_Click; - // - // buttonRef - // - buttonRef.Anchor = AnchorStyles.Top | AnchorStyles.Right; - buttonRef.BackColor = SystemColors.ControlLight; - buttonRef.Location = new Point(797, 100); - buttonRef.Name = "buttonRef"; - buttonRef.Size = new Size(178, 30); - buttonRef.TabIndex = 5; - buttonRef.Text = "Обновить список"; - buttonRef.UseVisualStyleBackColor = false; - buttonRef.Click += buttonRef_Click; - // - // dataGridView - // - dataGridView.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - dataGridView.BackgroundColor = SystemColors.ButtonHighlight; - dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; - dataGridView.Location = new Point(0, 26); - dataGridView.Name = "dataGridView"; - dataGridView.ReadOnly = true; - dataGridView.RowHeadersWidth = 51; - dataGridView.RowTemplate.Height = 24; - dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; - dataGridView.Size = new Size(780, 441); - dataGridView.TabIndex = 6; - // - // FormMain - // - AutoScaleDimensions = new SizeF(7F, 15F); - AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(985, 467); - Controls.Add(dataGridView); - Controls.Add(buttonRef); - Controls.Add(buttonIssuedOrder); - Controls.Add(buttonOrderReady); - Controls.Add(buttonTakeOrderInWork); - Controls.Add(buttonCreateOrder); - Controls.Add(toolStrip1); - Name = "FormMain"; - Text = "Моторный завод"; - Load += FormMain_Load; - toolStrip1.ResumeLayout(false); - toolStrip1.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() + { + toolStrip1 = new ToolStrip(); + toolStripDropDownButton1 = new ToolStripDropDownButton(); + КомпонентыToolStripMenuItem = new ToolStripMenuItem(); + ДвигателиToolStripMenuItem = new ToolStripMenuItem(); + клиентыToolStripMenuItem = new ToolStripMenuItem(); + исполнителиToolStripMenuItem = new ToolStripMenuItem(); + отчетыToolStripMenuItem = new ToolStripMenuItem(); + списокДвигателейToolStripMenuItem = new ToolStripMenuItem(); + компонентыПоДвигателямToolStripMenuItem = new ToolStripMenuItem(); + списокЗаказовToolStripMenuItem = new ToolStripMenuItem(); + запускРаботToolStripMenuItem = new ToolStripMenuItem(); + почтаToolStripMenuItem = new ToolStripMenuItem(); + buttonCreateOrder = new Button(); + buttonTakeOrderInWork = new Button(); + buttonOrderReady = new Button(); + buttonIssuedOrder = new Button(); + buttonRef = new Button(); + dataGridView = new DataGridView(); + toolStrip1.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // toolStrip1 + // + toolStrip1.ImageScalingSize = new Size(20, 20); + toolStrip1.Items.AddRange(new ToolStripItem[] { toolStripDropDownButton1, отчетыToolStripMenuItem, запускРаботToolStripMenuItem, почтаToolStripMenuItem }); + toolStrip1.Location = new Point(0, 0); + toolStrip1.Name = "toolStrip1"; + toolStrip1.Size = new Size(1231, 25); + toolStrip1.TabIndex = 0; + toolStrip1.Text = "toolStrip1"; + // + // toolStripDropDownButton1 + // + toolStripDropDownButton1.DisplayStyle = ToolStripItemDisplayStyle.Text; + toolStripDropDownButton1.DropDownItems.AddRange(new ToolStripItem[] { КомпонентыToolStripMenuItem, ДвигателиToolStripMenuItem, клиентыToolStripMenuItem, исполнителиToolStripMenuItem }); + toolStripDropDownButton1.ImageTransparentColor = Color.Magenta; + toolStripDropDownButton1.Name = "toolStripDropDownButton1"; + toolStripDropDownButton1.Size = new Size(88, 22); + toolStripDropDownButton1.Text = "Справочник"; + // + // КомпонентыToolStripMenuItem + // + КомпонентыToolStripMenuItem.Name = "КомпонентыToolStripMenuItem"; + КомпонентыToolStripMenuItem.Size = new Size(149, 22); + КомпонентыToolStripMenuItem.Text = "Компоненты"; + КомпонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click; + // + // ДвигателиToolStripMenuItem + // + ДвигателиToolStripMenuItem.Name = "ДвигателиToolStripMenuItem"; + ДвигателиToolStripMenuItem.Size = new Size(149, 22); + ДвигателиToolStripMenuItem.Text = "Двигатели"; + ДвигателиToolStripMenuItem.Click += ИзделияToolStripMenuItem_Click; + // + // клиентыToolStripMenuItem + // + клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; + клиентыToolStripMenuItem.Size = new Size(149, 22); + клиентыToolStripMenuItem.Text = "Клиенты"; + клиентыToolStripMenuItem.Click += клиентыToolStripMenuItem_Click; + // + // исполнителиToolStripMenuItem + // + исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; + исполнителиToolStripMenuItem.Size = new Size(149, 22); + исполнителиToolStripMenuItem.Text = "Исполнители"; + исполнителиToolStripMenuItem.Click += исполнителиToolStripMenuItem_Click; + // + // отчетыToolStripMenuItem + // + отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокДвигателейToolStripMenuItem, компонентыПоДвигателямToolStripMenuItem, списокЗаказовToolStripMenuItem }); + отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem"; + отчетыToolStripMenuItem.Size = new Size(60, 25); + отчетыToolStripMenuItem.Text = "Отчеты"; + // + // списокДвигателейToolStripMenuItem + // + списокДвигателейToolStripMenuItem.Name = "списокДвигателейToolStripMenuItem"; + списокДвигателейToolStripMenuItem.Size = new Size(228, 22); + списокДвигателейToolStripMenuItem.Text = "Список двигателей"; + списокДвигателейToolStripMenuItem.Click += списокДвигателейToolStripMenuItem_Click; + // + // компонентыПоДвигателямToolStripMenuItem + // + компонентыПоДвигателямToolStripMenuItem.Name = "компонентыПоДвигателямToolStripMenuItem"; + компонентыПоДвигателямToolStripMenuItem.Size = new Size(228, 22); + компонентыПоДвигателямToolStripMenuItem.Text = "Компоненты по двигателям"; + компонентыПоДвигателямToolStripMenuItem.Click += компонентыПоДвигателямToolStripMenuItem_Click; + // + // списокЗаказовToolStripMenuItem + // + списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem"; + списокЗаказовToolStripMenuItem.Size = new Size(228, 22); + списокЗаказовToolStripMenuItem.Text = "Список заказов"; + списокЗаказовToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click; + // + // запускРаботToolStripMenuItem + // + запускРаботToolStripMenuItem.Name = "запускРаботToolStripMenuItem"; + запускРаботToolStripMenuItem.Size = new Size(92, 25); + запускРаботToolStripMenuItem.Text = "Запуск работ"; + запускРаботToolStripMenuItem.Click += запускРаботToolStripMenuItem_Click; + // + // почтаToolStripMenuItem + // + почтаToolStripMenuItem.Name = "почтаToolStripMenuItem"; + почтаToolStripMenuItem.Size = new Size(53, 25); + почтаToolStripMenuItem.Text = "Почта"; + почтаToolStripMenuItem.Click += почтаToolStripMenuItem_Click; + // + // buttonCreateOrder + // + buttonCreateOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; + buttonCreateOrder.BackColor = SystemColors.ControlLight; + buttonCreateOrder.Location = new Point(1043, 146); + buttonCreateOrder.Name = "buttonCreateOrder"; + buttonCreateOrder.Size = new Size(178, 30); + buttonCreateOrder.TabIndex = 1; + buttonCreateOrder.Text = "Создать заказ"; + buttonCreateOrder.UseVisualStyleBackColor = false; + buttonCreateOrder.Click += buttonCreateOrder_Click; + // + // buttonTakeOrderInWork + // + buttonTakeOrderInWork.Anchor = AnchorStyles.Top | AnchorStyles.Right; + buttonTakeOrderInWork.BackColor = SystemColors.ControlLight; + buttonTakeOrderInWork.Location = new Point(1043, 194); + buttonTakeOrderInWork.Name = "buttonTakeOrderInWork"; + buttonTakeOrderInWork.Size = new Size(178, 30); + buttonTakeOrderInWork.TabIndex = 2; + buttonTakeOrderInWork.Text = "Отдать на выполнение"; + buttonTakeOrderInWork.UseVisualStyleBackColor = false; + buttonTakeOrderInWork.Click += buttonTakeOrderInWork_Click; + // + // buttonOrderReady + // + buttonOrderReady.Anchor = AnchorStyles.Top | AnchorStyles.Right; + buttonOrderReady.BackColor = SystemColors.ControlLight; + buttonOrderReady.Location = new Point(1043, 242); + buttonOrderReady.Name = "buttonOrderReady"; + buttonOrderReady.Size = new Size(178, 30); + buttonOrderReady.TabIndex = 3; + buttonOrderReady.Text = "Заказ готов"; + buttonOrderReady.UseVisualStyleBackColor = false; + buttonOrderReady.Click += buttonOrderReady_Click; + // + // buttonIssuedOrder + // + buttonIssuedOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; + buttonIssuedOrder.BackColor = SystemColors.ControlLight; + buttonIssuedOrder.Location = new Point(1043, 287); + buttonIssuedOrder.Name = "buttonIssuedOrder"; + buttonIssuedOrder.Size = new Size(178, 30); + buttonIssuedOrder.TabIndex = 4; + buttonIssuedOrder.Text = "Заказ выдан"; + buttonIssuedOrder.UseVisualStyleBackColor = false; + buttonIssuedOrder.Click += buttonIssuedOrder_Click; + // + // buttonRef + // + buttonRef.Anchor = AnchorStyles.Top | AnchorStyles.Right; + buttonRef.BackColor = SystemColors.ControlLight; + buttonRef.Location = new Point(1043, 100); + buttonRef.Name = "buttonRef"; + buttonRef.Size = new Size(178, 30); + buttonRef.TabIndex = 5; + buttonRef.Text = "Обновить список"; + buttonRef.UseVisualStyleBackColor = false; + buttonRef.Click += buttonRef_Click; + // + // dataGridView + // + dataGridView.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + dataGridView.BackgroundColor = SystemColors.ButtonHighlight; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(0, 26); + dataGridView.Name = "dataGridView"; + dataGridView.ReadOnly = true; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 24; + dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; + dataGridView.Size = new Size(1026, 441); + dataGridView.TabIndex = 6; + // + // FormMain + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(1231, 467); + Controls.Add(dataGridView); + Controls.Add(buttonRef); + Controls.Add(buttonIssuedOrder); + Controls.Add(buttonOrderReady); + Controls.Add(buttonTakeOrderInWork); + Controls.Add(buttonCreateOrder); + Controls.Add(toolStrip1); + Name = "FormMain"; + Text = "Моторный завод"; + Load += FormMain_Load; + toolStrip1.ResumeLayout(false); + toolStrip1.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + PerformLayout(); + } - #endregion + #endregion - private ToolStrip toolStrip1; - private Button buttonCreateOrder; - private Button buttonTakeOrderInWork; - private Button buttonOrderReady; - private Button buttonIssuedOrder; - private Button buttonRef; - private DataGridView dataGridView; - private ToolStripDropDownButton toolStripDropDownButton1; - private ToolStripMenuItem КомпонентыToolStripMenuItem; - private ToolStripMenuItem ДвигателиToolStripMenuItem; - private ToolStripMenuItem отчетыToolStripMenuItem; - private ToolStripMenuItem списокДвигателейToolStripMenuItem; - private ToolStripMenuItem компонентыПоДвигателямToolStripMenuItem; - private ToolStripMenuItem списокЗаказовToolStripMenuItem; - private ToolStripMenuItem клиентыToolStripMenuItem; - private ToolStripMenuItem исполнителиToolStripMenuItem; - private ToolStripMenuItem запускРаботToolStripMenuItem; - } + private ToolStrip toolStrip1; + private Button buttonCreateOrder; + private Button buttonTakeOrderInWork; + private Button buttonOrderReady; + private Button buttonIssuedOrder; + private Button buttonRef; + private DataGridView dataGridView; + private ToolStripDropDownButton toolStripDropDownButton1; + private ToolStripMenuItem КомпонентыToolStripMenuItem; + private ToolStripMenuItem ДвигателиToolStripMenuItem; + private ToolStripMenuItem отчетыToolStripMenuItem; + private ToolStripMenuItem списокДвигателейToolStripMenuItem; + private ToolStripMenuItem компонентыПоДвигателямToolStripMenuItem; + private ToolStripMenuItem списокЗаказовToolStripMenuItem; + private ToolStripMenuItem клиентыToolStripMenuItem; + private ToolStripMenuItem исполнителиToolStripMenuItem; + private ToolStripMenuItem запускРаботToolStripMenuItem; + private ToolStripMenuItem почтаToolStripMenuItem; + } } \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormMain.cs b/MotorPlant/MotorPlantView/FormMain.cs index 7c1be90..0e880b1 100644 --- a/MotorPlant/MotorPlantView/FormMain.cs +++ b/MotorPlant/MotorPlantView/FormMain.cs @@ -4,203 +4,213 @@ using MotorPlantContracts.BusinessLogicsContracts; namespace MotorPlantView.Forms { - public partial class FormMain : Form - { - private readonly ILogger _logger; - private readonly IOrderLogic _orderLogic; - private readonly IReportLogic _reportLogic; - private readonly IWorkProcess _workProcess; + 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, IWorkProcess workProcess) - { - InitializeComponent(); - _logger = logger; - _orderLogic = orderLogic; - _reportLogic = reportLogic; - _workProcess = workProcess; - } - private void FormMain_Load(object sender, EventArgs e) - { - LoadData(); - } - private void LoadData() - { - _logger.LogInformation("Загрузка заказов"); - try - { - var list = _orderLogic.ReadList(null); + 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() + { + _logger.LogInformation("Загрузка заказов"); + try + { + var list = _orderLogic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["EngineId"].Visible = false; - dataGridView.Columns["ClientId"].Visible = false; - dataGridView.Columns["ImplementerId"].Visible = false; - dataGridView.Columns["EngineName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки заказов"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - private void КомпонентыToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormComponents)); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["EngineId"].Visible = false; + dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["ClientEmail"].Visible = false; + dataGridView.Columns["ImplementerId"].Visible = false; + dataGridView.Columns["EngineName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки заказов"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + private void КомпонентыToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormComponents)); - if (service is FormComponents form) - { - form.ShowDialog(); - } - } - private void ИзделияToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormEngines)); + if (service is FormComponents form) + { + form.ShowDialog(); + } + } + private void ИзделияToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormEngines)); - if (service is FormEngines form) - { - 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 buttonTakeOrderInWork_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id); - try - { - var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel - { - Id = id, - }); - 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); - _logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'", id); - try - { - var operationResult = _orderLogic.FinishOrder(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 buttonIssuedOrder_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id); - try - { - var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel - { - Id = id - }); - if (!operationResult) - { - throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); - } - _logger.LogInformation("Заказ №{id} выдан", id); - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка отметки о выдачи заказа"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } - private void buttonRef_Click(object sender, EventArgs e) - { - LoadData(); - } + if (service is FormEngines 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 buttonTakeOrderInWork_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id); + try + { + var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel + { + Id = id, + }); + 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); + _logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'", id); + try + { + var operationResult = _orderLogic.FinishOrder(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 buttonIssuedOrder_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id); + try + { + var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel + { + Id = id + }); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + _logger.LogInformation("Заказ №{id} выдан", id); + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка отметки о выдачи заказа"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + private void buttonRef_Click(object sender, EventArgs e) + { + LoadData(); + } - private void списокДвигателейToolStripMenuItem_Click(object sender, EventArgs e) - { - using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; - if (dialog.ShowDialog() == DialogResult.OK) - { - _reportLogic.SaveEngineToWordFile(new ReportBindingModel { FileName = dialog.FileName }); - MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); - } - } + private void списокДвигателейToolStripMenuItem_Click(object sender, EventArgs e) + { + using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; + if (dialog.ShowDialog() == DialogResult.OK) + { + _reportLogic.SaveEngineToWordFile(new ReportBindingModel { FileName = dialog.FileName }); + MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } - private void компонентыПоДвигателямToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormReportEngineComponents)); - if (service is FormReportEngineComponents form) - { - form.ShowDialog(); - } - } + private void компонентыПоДвигателямToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReportEngineComponents)); + if (service is FormReportEngineComponents form) + { + form.ShowDialog(); + } + } - private void списокЗаказовToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders)); - if (service is FormReportOrders form) - { - form.ShowDialog(); - } - } + private void списокЗаказовToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders)); + if (service is FormReportOrders form) + { + form.ShowDialog(); + } + } - private void клиентыToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormClients)); - if (service is FormClients form) - { - form.ShowDialog(); - } - } + private void клиентыToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormClients)); + if (service is FormClients form) + { + form.ShowDialog(); + } + } - private void исполнителиToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormImplementers)); - if (service is FormImplementers form) - { - form.ShowDialog(); - } - } + private void исполнителиToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormImplementers)); + if (service is FormImplementers form) + { + form.ShowDialog(); + } + } - private void запускРаботToolStripMenuItem_Click(object sender, EventArgs e) - { - _workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic); - MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); - } - } + private void запускРаботToolStripMenuItem_Click(object sender, EventArgs e) + { + _workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic); + MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + + private void почтаToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormMail)); + if (service is FormMail form) + { + form.ShowDialog(); + } + } + } } diff --git a/MotorPlant/MotorPlantView/Program.cs b/MotorPlant/MotorPlantView/Program.cs index d3c783d..76f012a 100644 --- a/MotorPlant/MotorPlantView/Program.cs +++ b/MotorPlant/MotorPlantView/Program.cs @@ -10,6 +10,8 @@ using MotorPlantBusinessLogic.BusinessLogic; using MotorPlantBusinessLogic.OfficePackage.Implements; using MotorPlantBusinessLogic.OfficePackage; using System.Text; +using MotorPlantBusinessLogic.MailWorker; +using MotorPlantContracts.BindingModels; namespace MotorPlantView { @@ -30,7 +32,26 @@ namespace MotorPlantView var services = new ServiceCollection(); ConfigureServices(services); _serviceProvider = services.BuildServiceProvider(); + try + { + var mailSender = _serviceProvider.GetService(); + mailSender?.MailConfig(new MailConfigBindingModel + { + MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty, + MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty, + SmtpClientHost = System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty, + SmtpClientPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]), + PopHost = System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty, + PopPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"]) + }); + var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000); + } + catch (Exception ex) + { + var logger = _serviceProvider.GetService(); + logger?.LogError(ex, "Mails Problem"); + } Application.Run(_serviceProvider.GetRequiredService()); } private static void ConfigureServices(ServiceCollection services) @@ -45,8 +66,9 @@ namespace MotorPlantView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); - services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -54,10 +76,13 @@ namespace MotorPlantView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); - services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddSingleton(); services.AddTransient(); services.AddTransient(); @@ -71,6 +96,9 @@ namespace MotorPlantView services.AddTransient(); services.AddTransient(); services.AddTransient(); - } + services.AddTransient(); + } + + private static void MailCheck(object obj) => ServiceProvider?.GetService()?.MailCheck(); } } \ No newline at end of file