diff --git a/AircraftPlant/AircraftPlant.log.2024-04-08 b/AircraftPlant/AircraftPlant.log.2024-04-08 deleted file mode 100644 index 7f21d29..0000000 --- a/AircraftPlant/AircraftPlant.log.2024-04-08 +++ /dev/null @@ -1,23 +0,0 @@ -2024-04-08 10:12:55,009 INFO Microsoft.Hosting.Lifetime.? [?] - MESSAGE: Now listening on: https://localhost:7122 - 2024-04-08 10:12:55,090 INFO Microsoft.Hosting.Lifetime.? [?] - MESSAGE: Now listening on: http://localhost:5092 - 2024-04-08 10:12:55,097 INFO Microsoft.Hosting.Lifetime.OnApplicationStarted [0] - MESSAGE: Application started. Press Ctrl+C to shut down. - 2024-04-08 10:12:55,100 INFO Microsoft.Hosting.Lifetime.OnApplicationStarted [0] - MESSAGE: Hosting environment: Development - 2024-04-08 10:12:55,102 INFO Microsoft.Hosting.Lifetime.OnApplicationStarted [0] - MESSAGE: Content root path: D:\ULSTU\Семестр 4\РПП\AircraftPlant\AircraftPlantRestApi\ - 2024-04-08 10:13:00,428 INFO AircraftPlantBusinessLogic.BusinessLogics.PlaneLogic.ReadList [49] - MESSAGE: ReadList. PlaneName:(null).Id:(null) - 2024-04-08 10:13:03,695 INFO AircraftPlantBusinessLogic.BusinessLogics.PlaneLogic.ReadList [58] - MESSAGE: ReadList. Count:2 - 2024-04-08 10:13:37,635 INFO AircraftPlantBusinessLogic.BusinessLogics.ClientLogic.ReadElement [74] - MESSAGE: ReadElement. ClientEmail:client1.Id:(null) - 2024-04-08 10:13:37,766 INFO AircraftPlantBusinessLogic.BusinessLogics.ClientLogic.ReadElement [83] - MESSAGE: ReadElement find. Id:1 - 2024-04-08 10:13:37,802 INFO AircraftPlantBusinessLogic.BusinessLogics.ClientLogic.ReadElement [74] - MESSAGE: ReadElement. ClientEmail:client1.Id:(null) - 2024-04-08 10:13:37,849 INFO AircraftPlantBusinessLogic.BusinessLogics.ClientLogic.ReadElement [83] - MESSAGE: ReadElement find. Id:1 - 2024-04-08 10:13:37,914 INFO AircraftPlantBusinessLogic.BusinessLogics.OrderLogic.ReadList [50] - MESSAGE: ReadList. Order.Id:(null) - 2024-04-08 10:13:37,956 INFO AircraftPlantBusinessLogic.BusinessLogics.OrderLogic.ReadList [59] - MESSAGE: ReadList. Count:2 - 2024-04-08 10:13:45,625 INFO AircraftPlantBusinessLogic.BusinessLogics.PlaneLogic.ReadList [49] - MESSAGE: ReadList. PlaneName:(null).Id:(null) - 2024-04-08 10:13:45,628 INFO AircraftPlantBusinessLogic.BusinessLogics.PlaneLogic.ReadList [58] - MESSAGE: ReadList. Count:2 - 2024-04-08 10:13:48,493 INFO AircraftPlantBusinessLogic.BusinessLogics.PlaneLogic.ReadElement [75] - MESSAGE: ReadElement. PlaneName:(null).Id:1 - 2024-04-08 10:13:48,514 INFO AircraftPlantBusinessLogic.BusinessLogics.PlaneLogic.ReadElement [84] - MESSAGE: ReadElement find. Id:1 - 2024-04-08 10:13:50,536 INFO AircraftPlantBusinessLogic.BusinessLogics.PlaneLogic.ReadElement [75] - MESSAGE: ReadElement. PlaneName:(null).Id:1 - 2024-04-08 10:13:50,540 INFO AircraftPlantBusinessLogic.BusinessLogics.PlaneLogic.ReadElement [84] - MESSAGE: ReadElement find. Id:1 - 2024-04-08 10:13:50,584 INFO AircraftPlantBusinessLogic.BusinessLogics.OrderLogic.CheckModel [144] - MESSAGE: Order. OrderID:0.Sum:1650. PlaneId: 1 - 2024-04-08 10:13:50,780 INFO AircraftPlantBusinessLogic.BusinessLogics.OrderLogic.ReadList [50] - MESSAGE: ReadList. Order.Id:(null) - 2024-04-08 10:13:50,783 INFO AircraftPlantBusinessLogic.BusinessLogics.OrderLogic.ReadList [59] - MESSAGE: ReadList. Count:3 - \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantBusinessLogic/AircraftPlantBusinessLogic.csproj b/AircraftPlant/AircraftPlantBusinessLogic/AircraftPlantBusinessLogic.csproj index bcaa5f0..c8e9ae3 100644 --- a/AircraftPlant/AircraftPlantBusinessLogic/AircraftPlantBusinessLogic.csproj +++ b/AircraftPlant/AircraftPlantBusinessLogic/AircraftPlantBusinessLogic.csproj @@ -8,6 +8,7 @@ + diff --git a/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/ClientLogic.cs b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/ClientLogic.cs index 477238e..a24205b 100644 --- a/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/ClientLogic.cs +++ b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/ClientLogic.cs @@ -8,6 +8,7 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; +using System.Text.RegularExpressions; using System.Threading.Tasks; namespace AircraftPlantBusinessLogic.BusinessLogics @@ -155,13 +156,13 @@ namespace AircraftPlantBusinessLogic.BusinessLogics { throw new ArgumentNullException("Нет ФИО клиента", nameof(model.ClientFIO)); } - if (string.IsNullOrEmpty(model.Email)) + if (string.IsNullOrEmpty(model.Email) || !Regex.IsMatch(model.Email, @"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$", RegexOptions.IgnoreCase)) { - throw new ArgumentNullException("Нет почты клиента", nameof(model.Email)); + throw new ArgumentNullException("Невалидная электронная почта клиента", nameof(model.Email)); } - if (string.IsNullOrEmpty(model.Password)) + if (string.IsNullOrEmpty(model.Password) || !Regex.IsMatch(model.Password, @"^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$")) { - throw new ArgumentNullException("Нет пароля клиента", nameof(model.Password)); + throw new ArgumentNullException("Слабый пароль", nameof(model.Password)); } _logger.LogInformation("Client. ClientFIO: {ClientFIO}. Email: {Email}. Id: {Id}", model.ClientFIO, model.Email, model.Id); diff --git a/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/MessageInfoLogic.cs b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/MessageInfoLogic.cs new file mode 100644 index 0000000..a1fbf53 --- /dev/null +++ b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/MessageInfoLogic.cs @@ -0,0 +1,127 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.BusinessLogicsContracts; +using AircraftPlantContracts.SearchModels; +using AircraftPlantContracts.StoragesContracts; +using AircraftPlantContracts.ViewModels; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantBusinessLogic.BusinessLogics +{ + /// + /// Реализация интерфейса бизнес-логики для писем + /// + public class MessageInfoLogic : IMessageInfoLogic + { + /// + /// Логгер + /// + private readonly ILogger _logger; + + /// + /// Взаимодействие с хранилищем писем + /// + private readonly IMessageInfoStorage _messageStorage; + + /// + /// Конструктор + /// + /// + /// + public MessageInfoLogic(ILogger logger, IMessageInfoStorage messageStorage) + { + _logger = logger; + _messageStorage = messageStorage; + } + + /// + /// Получение списка + /// + /// + /// + public List? ReadList(MessageInfoSearchModel? model) + { + _logger.LogInformation("ReadList. MessageId: {MessageId}. ClientId: {ClientId}", model?.MessageId, model?.ClientId); + + var list = model == null ? _messageStorage.GetFullList() : _messageStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + + _logger.LogInformation("ReadList. Count: {Count}", list.Count); + return list; + } + + /// + /// Получение отдельной записи + /// + /// + /// + /// + public MessageInfoViewModel? ReadElement(MessageInfoSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + + _logger.LogInformation("ReadElement. MessageId:{Id}", model.MessageId); + + var element = _messageStorage.GetElement(model); + if (element == null) + { + _logger.LogWarning("ReadElement element not found"); + return null; + } + + _logger.LogInformation("ReadElement find. MessageId:{Id}", element.MessageId); + return element; + } + + /// + /// Создание записи + /// + /// + /// + public bool Create(MessageInfoBindingModel model) + { + if (model == null) + { + return false; + } + + if (_messageStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } + + /// + /// Изменение записи + /// + /// + /// + public bool Update(MessageInfoBindingModel model) + { + if (model == null) + { + return false; + } + + if (_messageStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + return true; + } + } +} diff --git a/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/OrderLogic.cs b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/OrderLogic.cs index 88da590..d25e228 100644 --- a/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/OrderLogic.cs @@ -1,4 +1,5 @@ -using AircraftPlantContracts.BindingModels; +using AircraftPlantBusinessLogic.MailWorker; +using AircraftPlantContracts.BindingModels; using AircraftPlantContracts.BusinessLogicsContracts; using AircraftPlantContracts.SearchModels; using AircraftPlantContracts.StoragesContracts; @@ -44,18 +45,35 @@ namespace AircraftPlantBusinessLogic.BusinessLogics /// private IPlaneStorage _planeStorage; + /// + /// Взаимодействие с хранилищем клиентов + /// + private readonly IClientStorage _clientStorage; + + /// + /// Бизнес-логика для отправки писем + /// + private readonly AbstractMailWorker _mailLogic; + /// /// Конструктор /// /// /// - public OrderLogic(ILogger logger, IOrderStorage orderStorage, IShopStorage shopStorage, IShopLogic shopLogic, IPlaneStorage planeStorage) + /// + /// + /// + /// + /// + public OrderLogic(ILogger logger, IOrderStorage orderStorage, IShopStorage shopStorage, IShopLogic shopLogic, IPlaneStorage planeStorage, IClientStorage clientStorage, AbstractMailWorker mailLogic) { _logger = logger; _orderStorage = orderStorage; _shopStorage = shopStorage; _shopLogic = shopLogic; _planeStorage = planeStorage; + _clientStorage = clientStorage; + _mailLogic = mailLogic; } /// @@ -119,11 +137,14 @@ namespace AircraftPlantBusinessLogic.BusinessLogics model.Status = OrderStatus.Принят; - if (_orderStorage.Insert(model) == null) + var order = _orderStorage.Insert(model); + if (order == null) { _logger.LogWarning("Insert operation failed"); return false; } + + SendEmail(order); return true; } @@ -236,11 +257,14 @@ namespace AircraftPlantBusinessLogic.BusinessLogics } CheckModel(model, false); - if (_orderStorage.Update(model) == null) + var order = _orderStorage.Update(model); + if (order == null) { _logger.LogWarning("Change status operation failed"); return false; } + + SendEmail(order); return true; } @@ -317,5 +341,45 @@ namespace AircraftPlantBusinessLogic.BusinessLogics } return false; } + + /// + /// Отправить письмо + /// + /// + public void SendEmail(OrderViewModel order) + { + if (order == null) + { + return; + } + + var client = _clientStorage.GetElement(new ClientSearchModel { Id = order.ClientId }); + if (client == null) + { + return; + } + + MailSendInfoBindingModel mailModel; + if (order.Status == OrderStatus.Принят) + { + mailModel = new MailSendInfoBindingModel + { + MailAddress = client.Email, + Subject = $"Order №{order.Id}", + Text = $"Your order №{order.Id} by {order.DateCreate} on {order.Sum} was accepted!" + }; + } + else + { + mailModel = new MailSendInfoBindingModel + { + MailAddress = client.Email, + Subject = $"Order №{order.Id}", + Text = $"Order №{order.Id} status was changed to {order.Status}" + }; + } + + _mailLogic.MailSendAsync(mailModel); + } } } diff --git a/AircraftPlant/AircraftPlantBusinessLogic/MailWorker/AbstractMailWorker.cs b/AircraftPlant/AircraftPlantBusinessLogic/MailWorker/AbstractMailWorker.cs new file mode 100644 index 0000000..41e96ba --- /dev/null +++ b/AircraftPlant/AircraftPlantBusinessLogic/MailWorker/AbstractMailWorker.cs @@ -0,0 +1,160 @@ +using AircraftPlantBusinessLogic.BusinessLogics; +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.BusinessLogicsContracts; +using AircraftPlantContracts.SearchModels; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantBusinessLogic.MailWorker +{ + /// + /// Абстрактный класс для работы с письмами + /// + public abstract class AbstractMailWorker + { + private readonly ILogger _logger; + + /// + /// Логин для доступа к почтовому сервису + /// + protected string _mailLogin = string.Empty; + + /// + /// Пароль для доступа к почтовому сервису + /// + protected string _mailPassword = string.Empty; + + /// + /// Хост SMTP-клиента + /// + protected string _smtpClientHost = string.Empty; + + /// + /// Порт SMTP-клиента + /// + protected int _smtpClientPort; + + /// + /// Хост протокола POP3 + /// + protected string _popHost = string.Empty; + + /// + /// Порт протокола POP3 + /// + protected int _popPort; + + /// + /// Бизнес-логика для писем + /// + private readonly IMessageInfoLogic _messageInfoLogic; + + /// + /// Бизнес-логика для клиентов + /// + private readonly IClientLogic _clientLogic; + + /// + /// Конструктор + /// + /// + /// + public AbstractMailWorker(ILogger logger, IMessageInfoLogic messageInfoLogic, IClientLogic clientLogic) + { + _logger = logger; + _messageInfoLogic = messageInfoLogic; + _clientLogic = clientLogic; + } + + /// + /// Настроить почтовый сервис + /// + /// + 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, _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) + { + mail.ClientId = _clientLogic.ReadElement(new ClientSearchModel + { + Email = mail.SenderName + })?.Id; + _messageInfoLogic.Create(mail); + } + } + + /// + /// Отправить письмо + /// + /// + /// + protected abstract Task SendMailAsync(MailSendInfoBindingModel info); + + /// + /// Получить все письма + /// + /// + protected abstract Task> ReceiveMailAsync(); + } +} diff --git a/AircraftPlant/AircraftPlantBusinessLogic/MailWorker/MailKitWorker.cs b/AircraftPlant/AircraftPlantBusinessLogic/MailWorker/MailKitWorker.cs new file mode 100644 index 0000000..17328b5 --- /dev/null +++ b/AircraftPlant/AircraftPlantBusinessLogic/MailWorker/MailKitWorker.cs @@ -0,0 +1,103 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Mail; +using System.Net; +using System.Text; +using System.Threading.Tasks; +using MailKit.Net.Pop3; +using MailKit.Security; + +namespace AircraftPlantBusinessLogic.MailWorker +{ + /// + /// Реализация абстрактного класса для работы с письмами + /// + public class MailKitWorker : AbstractMailWorker + { + /// + /// Конструктор + /// + /// + /// + public MailKitWorker(ILogger logger, IMessageInfoLogic messageInfoLogic, IClientLogic clientLogic) : base(logger, messageInfoLogic, clientLogic) { } + + /// + /// Отправить письмо + /// + /// + /// + 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 (AuthenticationException) + { } + finally + { + client.Disconnect(true); + } + }); + + return list; + } + } +} diff --git a/AircraftPlant/AircraftPlantClientApp/Controllers/HomeController.cs b/AircraftPlant/AircraftPlantClientApp/Controllers/HomeController.cs index 8e36ae6..7997868 100644 --- a/AircraftPlant/AircraftPlantClientApp/Controllers/HomeController.cs +++ b/AircraftPlant/AircraftPlantClientApp/Controllers/HomeController.cs @@ -209,5 +209,29 @@ namespace AircraftPlantClientApp.Controllers var prod = APIClient.GetRequest($"api/main/getplane?planeId={plane}"); return count * (prod?.Price ?? 1); } - } + + /// + /// Получение списка писем клиента + /// + /// + [HttpGet] + public IActionResult Mails(int page = 1) + { + if (APIClient.Client == null) + { + return Redirect("~/Home/Enter"); + } + + ViewBag.Page = page; + List? list = APIClient.GetRequest>($"api/client/getmessages?clientId={APIClient.Client.Id}¤tPage={page}"); + if (list != null && list.Count == 0 && page != 1) + { + page--; + ViewBag.Page = page; + list = APIClient.GetRequest>($"api/client/getmessages?clientId={APIClient.Client.Id}¤tPage={page}"); + } + + return View(list); + } + } } diff --git a/AircraftPlant/AircraftPlantClientApp/Views/Home/Mails.cshtml b/AircraftPlant/AircraftPlantClientApp/Views/Home/Mails.cshtml new file mode 100644 index 0000000..7604a69 --- /dev/null +++ b/AircraftPlant/AircraftPlantClientApp/Views/Home/Mails.cshtml @@ -0,0 +1,62 @@ +@using AircraftPlantContracts.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) +
+ + = 1 ? ViewBag.Page - 1 : 1 })" class="btn btn-primary"> + Назад + +

Страница @ViewBag.Page

+ + Вперед + + } +
\ No newline at end of file diff --git a/AircraftPlant/AircraftPlantClientApp/Views/Shared/_Layout.cshtml b/AircraftPlant/AircraftPlantClientApp/Views/Shared/_Layout.cshtml index 03e35ec..d872b22 100644 --- a/AircraftPlant/AircraftPlantClientApp/Views/Shared/_Layout.cshtml +++ b/AircraftPlant/AircraftPlantClientApp/Views/Shared/_Layout.cshtml @@ -27,6 +27,9 @@ + diff --git a/AircraftPlant/AircraftPlantContracts/BindingModels/MailConfigBindingModel.cs b/AircraftPlant/AircraftPlantContracts/BindingModels/MailConfigBindingModel.cs new file mode 100644 index 0000000..7fe9c93 --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/BindingModels/MailConfigBindingModel.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.BindingModels +{ + /// + /// Модель привязки для настройки почтового сервиса + /// + public class MailConfigBindingModel + { + /// + /// Логин для доступа к почтовому сервису + /// + public string MailLogin { get; set; } = string.Empty; + + /// + /// Пароль для доступа к почтовому сервису + /// + public string MailPassword { get; set; } = string.Empty; + + /// + /// Хост SMTP-клиента + /// + public string SmtpClientHost { get; set; } = string.Empty; + + /// + /// Порт SMTP-клиента + /// + public int SmtpClientPort { get; set; } + + /// + /// Хост протокола POP3 + /// + public string PopHost { get; set; } = string.Empty; + + /// + /// Порт протокола POP3 + /// + public int PopPort { get; set; } + } +} diff --git a/AircraftPlant/AircraftPlantContracts/BindingModels/MailSendInfoBindingModel.cs b/AircraftPlant/AircraftPlantContracts/BindingModels/MailSendInfoBindingModel.cs new file mode 100644 index 0000000..c7c5fd6 --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/BindingModels/MailSendInfoBindingModel.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.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/AircraftPlant/AircraftPlantContracts/BindingModels/MessageInfoBindingModel.cs b/AircraftPlant/AircraftPlantContracts/BindingModels/MessageInfoBindingModel.cs new file mode 100644 index 0000000..9f76560 --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/BindingModels/MessageInfoBindingModel.cs @@ -0,0 +1,56 @@ +using AircraftPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.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 DateTime DateDelivery { get; set; } + + /// + /// Заголовок письма + /// + public string Subject { get; set; } = string.Empty; + + /// + /// Тело письма + /// + public string Body { get; set; } = string.Empty; + + /// + /// Письмо прочитано + /// + public bool IsChecked { get; set; } + + /// + /// Ответ на писмо + /// + public string? Reply { get; set; } + } +} diff --git a/AircraftPlant/AircraftPlantContracts/BusinessLogicsContracts/IMessageInfoLogic.cs b/AircraftPlant/AircraftPlantContracts/BusinessLogicsContracts/IMessageInfoLogic.cs new file mode 100644 index 0000000..7e5c3b1 --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/BusinessLogicsContracts/IMessageInfoLogic.cs @@ -0,0 +1,45 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.SearchModels; +using AircraftPlantContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.BusinessLogicsContracts +{ + /// + /// Интерфейс для описания работы бизнес-логики для писем + /// + public interface IMessageInfoLogic + { + /// + /// Получение списка + /// + /// + /// + List? ReadList(MessageInfoSearchModel? model); + + /// + /// Получение отдельной записи + /// + /// + /// + MessageInfoViewModel? ReadElement(MessageInfoSearchModel model); + + /// + /// Создание записи + /// + /// + /// + bool Create(MessageInfoBindingModel model); + + /// + /// Изменение записи + /// + /// + /// + bool Update(MessageInfoBindingModel? model); + } +} diff --git a/AircraftPlant/AircraftPlantContracts/SearchModels/MessageInfoSearchModel.cs b/AircraftPlant/AircraftPlantContracts/SearchModels/MessageInfoSearchModel.cs new file mode 100644 index 0000000..012c0f3 --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/SearchModels/MessageInfoSearchModel.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.SearchModels +{ + /// + /// Модель для передачи данных пользователя + /// в методы для поиска данных для писем + /// + public class MessageInfoSearchModel + { + /// + /// Идентификатор + /// + public string? MessageId { get; set; } + + /// + /// Идентификатор клиента + /// + public int? ClientId { get; set; } + + /// + /// Размер страницы пагинации + /// + public int? PageSize { get; set; } + + /// + /// Текущая страница пагинации + /// + public int? CurrentPage { get; set; } + } +} diff --git a/AircraftPlant/AircraftPlantContracts/StoragesContracts/IMessageInfoStorage.cs b/AircraftPlant/AircraftPlantContracts/StoragesContracts/IMessageInfoStorage.cs new file mode 100644 index 0000000..4269d11 --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/StoragesContracts/IMessageInfoStorage.cs @@ -0,0 +1,51 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.SearchModels; +using AircraftPlantContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.StoragesContracts +{ + /// + /// Интерфейс для описания работы с хранилищем для писем + /// + public interface IMessageInfoStorage + { + /// + /// Получение полного списка + /// + /// + List GetFullList(); + + /// + /// Получение фильтрованного списка + /// + /// + /// + List GetFilteredList(MessageInfoSearchModel model); + + /// + /// Получение элемента + /// + /// + /// + MessageInfoViewModel? GetElement(MessageInfoSearchModel model); + + /// + /// Добавление элемента + /// + /// + /// + MessageInfoViewModel? Insert(MessageInfoBindingModel model); + + /// + /// Редактирование элемента + /// + /// + /// + MessageInfoViewModel? Update(MessageInfoBindingModel model); + } +} diff --git a/AircraftPlant/AircraftPlantContracts/ViewModels/MessageInfoViewModel.cs b/AircraftPlant/AircraftPlantContracts/ViewModels/MessageInfoViewModel.cs new file mode 100644 index 0000000..6d659cf --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/ViewModels/MessageInfoViewModel.cs @@ -0,0 +1,63 @@ +using AircraftPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.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; + + /// + /// Письмо прочитано + /// + [DisplayName("Прочитано")] + public bool IsChecked { get; set; } + + /// + /// Ответ на письмо + /// + [DisplayName("Ответ")] + public string? Reply { get; set; } + } +} diff --git a/AircraftPlant/AircraftPlantDataModels/Models/IMessageInfoModel.cs b/AircraftPlant/AircraftPlantDataModels/Models/IMessageInfoModel.cs new file mode 100644 index 0000000..2cb6732 --- /dev/null +++ b/AircraftPlant/AircraftPlantDataModels/Models/IMessageInfoModel.cs @@ -0,0 +1,54 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantDataModels.Models +{ + /// + /// Интерфейс для модели письма + /// + public interface IMessageInfoModel + { + /// + /// Идентификатор + /// + string MessageId { get; } + + /// + /// Идентификатор клиента + /// + int? ClientId { get; } + + /// + /// Адрес электронной почты отправителя + /// + string SenderName { get; } + + /// + /// Дата получения письма + /// + DateTime DateDelivery { get; } + + /// + /// Заголовок письма + /// + string Subject { get; } + + /// + /// Тело письма + /// + string Body { get; } + + /// + /// Письмо прочитано + /// + bool IsChecked { get; } + + /// + /// Ответ на письмо + /// + string? Reply { get; } + } +} diff --git a/AircraftPlant/AircraftPlantDatabaseImplement/AircraftPlantDatabase.cs b/AircraftPlant/AircraftPlantDatabaseImplement/AircraftPlantDatabase.cs index 86d720f..a907f86 100644 --- a/AircraftPlant/AircraftPlantDatabaseImplement/AircraftPlantDatabase.cs +++ b/AircraftPlant/AircraftPlantDatabaseImplement/AircraftPlantDatabase.cs @@ -65,5 +65,10 @@ namespace AircraftPlantDatabaseImplement /// Таблица исполнителей ///
public virtual DbSet Implementers { set; get; } - } + + /// + /// Таблица писем + /// + public virtual DbSet Messages { set; get; } + } } diff --git a/AircraftPlant/AircraftPlantDatabaseImplement/Implements/MessageInfoStorage.cs b/AircraftPlant/AircraftPlantDatabaseImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..e4ce0ee --- /dev/null +++ b/AircraftPlant/AircraftPlantDatabaseImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,127 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.SearchModels; +using AircraftPlantContracts.StoragesContracts; +using AircraftPlantContracts.ViewModels; +using AircraftPlantDatabaseImplement.Models; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantDatabaseImplement.Implements +{ + /// + /// Реализация интерфейса хранилища для писем + /// + public class MessageInfoStorage : IMessageInfoStorage + { + /// + /// Получение полного списка + /// + /// + public List GetFullList() + { + using var context = new AircraftPlantDatabase(); + return context.Messages + .Select(x => x.GetViewModel) + .ToList(); + } + + /// + /// Получение фильтрованного списка + /// + /// + /// + public List GetFilteredList(MessageInfoSearchModel model) + { + if (!model.ClientId.HasValue && (!model.PageSize.HasValue || !model.CurrentPage.HasValue)) + { + return new(); + } + + using var context = new AircraftPlantDatabase(); + + if (model.CurrentPage.HasValue && model.PageSize.HasValue && model.ClientId.HasValue) + { + return context.Messages + .Where(x => x.ClientId == model.ClientId) + .Skip((model.CurrentPage.Value - 1) * model.PageSize.Value) + .Take(model.PageSize.Value) + .Select(x => x.GetViewModel) + .ToList(); + } + + if (model.CurrentPage.HasValue && model.PageSize.HasValue) + { + return context.Messages + .Skip((model.CurrentPage.Value - 1) * model.PageSize.Value) + .Take(model.PageSize.Value) + .Select(x => x.GetViewModel) + .ToList(); + } + + return context.Messages + .Where(x => x.ClientId == model.ClientId) + .Select(x => x.GetViewModel) + .ToList(); + } + + /// + /// Получение элемента + /// + /// + /// + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (string.IsNullOrEmpty(model.MessageId)) + { + return null; + } + + using var context = new AircraftPlantDatabase(); + return context.Messages + .FirstOrDefault(x => x.MessageId == model.MessageId) + ?.GetViewModel; + } + + /// + /// Добавление элемента + /// + /// + /// + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = Message.Create(model); + if (newMessage == null) + { + return null; + } + + using var context = new AircraftPlantDatabase(); + context.Messages.Add(newMessage); + context.SaveChanges(); + return newMessage.GetViewModel; + } + + /// + /// Редактирование элемента + /// + /// + /// + public MessageInfoViewModel? Update(MessageInfoBindingModel model) + { + using var context = new AircraftPlantDatabase(); + var message = context.Messages.FirstOrDefault(x => x.MessageId == model.MessageId); + if (message == null) + { + return null; + } + + message.Update(model); + context.SaveChanges(); + return message.GetViewModel; + } + } +} diff --git a/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/20240504174710_MessageInfoCreate.Designer.cs b/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/20240504174710_MessageInfoCreate.Designer.cs new file mode 100644 index 0000000..d631285 --- /dev/null +++ b/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/20240504174710_MessageInfoCreate.Designer.cs @@ -0,0 +1,298 @@ +// +using System; +using AircraftPlantDatabaseImplement; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace AircraftPlantDatabaseImplement.Migrations +{ + [DbContext(typeof(AircraftPlantDatabase))] + [Migration("20240504174710_MessageInfoCreate")] + partial class MessageInfoCreate + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.3") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Client", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientFIO") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Email") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Password") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Clients"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Component", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ComponentName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Cost") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.ToTable("Components"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Implementer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ImplementerFIO") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Password") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Qualification") + .HasColumnType("int"); + + b.Property("WorkExperience") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.ToTable("Implementers"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Message", b => + { + b.Property("MessageId") + .HasColumnType("nvarchar(450)"); + + b.Property("Body") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("int"); + + b.Property("DateDelivery") + .HasColumnType("datetime2"); + + b.Property("SenderName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Subject") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("MessageId"); + + b.HasIndex("ClientId"); + + b.ToTable("Messages"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Order", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateImplement") + .HasColumnType("datetime2"); + + b.Property("ImplementerId") + .HasColumnType("int"); + + b.Property("PlaneId") + .HasColumnType("int"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("Sum") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.HasIndex("ImplementerId"); + + b.HasIndex("PlaneId"); + + b.ToTable("Orders"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Plane", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("PlaneName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Price") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.ToTable("Planes"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.PlaneComponent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ComponentId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("PlaneId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ComponentId"); + + b.HasIndex("PlaneId"); + + b.ToTable("PlaneComponents"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Message", b => + { + b.HasOne("AircraftPlantDatabaseImplement.Models.Client", "Client") + .WithMany("Messages") + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Order", b => + { + b.HasOne("AircraftPlantDatabaseImplement.Models.Client", "Client") + .WithMany("Orders") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("AircraftPlantDatabaseImplement.Models.Implementer", "Implementer") + .WithMany("Orders") + .HasForeignKey("ImplementerId"); + + b.HasOne("AircraftPlantDatabaseImplement.Models.Plane", "Plane") + .WithMany("Orders") + .HasForeignKey("PlaneId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Client"); + + b.Navigation("Implementer"); + + b.Navigation("Plane"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.PlaneComponent", b => + { + b.HasOne("AircraftPlantDatabaseImplement.Models.Component", "Component") + .WithMany("PlaneComponents") + .HasForeignKey("ComponentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("AircraftPlantDatabaseImplement.Models.Plane", "Plane") + .WithMany("Components") + .HasForeignKey("PlaneId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Component"); + + b.Navigation("Plane"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Client", b => + { + b.Navigation("Messages"); + + b.Navigation("Orders"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Component", b => + { + b.Navigation("PlaneComponents"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Implementer", b => + { + b.Navigation("Orders"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Plane", b => + { + b.Navigation("Components"); + + b.Navigation("Orders"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/20240504174710_MessageInfoCreate.cs b/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/20240504174710_MessageInfoCreate.cs new file mode 100644 index 0000000..c372add --- /dev/null +++ b/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/20240504174710_MessageInfoCreate.cs @@ -0,0 +1,48 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace AircraftPlantDatabaseImplement.Migrations +{ + /// + public partial class MessageInfoCreate : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Messages", + columns: table => new + { + MessageId = table.Column(type: "nvarchar(450)", nullable: false), + ClientId = table.Column(type: "int", nullable: true), + SenderName = table.Column(type: "nvarchar(max)", nullable: false), + DateDelivery = table.Column(type: "datetime2", nullable: false), + Subject = table.Column(type: "nvarchar(max)", nullable: false), + Body = table.Column(type: "nvarchar(max)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Messages", x => x.MessageId); + table.ForeignKey( + name: "FK_Messages_Clients_ClientId", + column: x => x.ClientId, + principalTable: "Clients", + principalColumn: "Id"); + }); + + migrationBuilder.CreateIndex( + name: "IX_Messages_ClientId", + table: "Messages", + column: "ClientId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Messages"); + } + } +} diff --git a/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/20240505220907_MessageInfoUpdate.Designer.cs b/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/20240505220907_MessageInfoUpdate.Designer.cs new file mode 100644 index 0000000..dc1b186 --- /dev/null +++ b/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/20240505220907_MessageInfoUpdate.Designer.cs @@ -0,0 +1,381 @@ +// +using System; +using AircraftPlantDatabaseImplement; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace AircraftPlantDatabaseImplement.Migrations +{ + [DbContext(typeof(AircraftPlantDatabase))] + [Migration("20240505220907_MessageInfoUpdate")] + partial class MessageInfoUpdate + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.3") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Client", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientFIO") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Email") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Password") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Clients"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Component", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ComponentName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Cost") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.ToTable("Components"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Implementer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ImplementerFIO") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Password") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Qualification") + .HasColumnType("int"); + + b.Property("WorkExperience") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.ToTable("Implementers"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Message", b => + { + b.Property("MessageId") + .HasColumnType("nvarchar(450)"); + + b.Property("Body") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("int"); + + b.Property("DateDelivery") + .HasColumnType("datetime2"); + + b.Property("IsChecked") + .HasColumnType("bit"); + + b.Property("Reply") + .HasColumnType("nvarchar(max)"); + + b.Property("SenderName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Subject") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("MessageId"); + + b.HasIndex("ClientId"); + + b.ToTable("Messages"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Order", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateImplement") + .HasColumnType("datetime2"); + + b.Property("ImplementerId") + .HasColumnType("int"); + + b.Property("PlaneId") + .HasColumnType("int"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("Sum") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.HasIndex("ImplementerId"); + + b.HasIndex("PlaneId"); + + b.ToTable("Orders"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Plane", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("PlaneName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Price") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.ToTable("Planes"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.PlaneComponent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ComponentId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("PlaneId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ComponentId"); + + b.HasIndex("PlaneId"); + + b.ToTable("PlaneComponents"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Shop", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Address") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("DateOpening") + .HasColumnType("datetime2"); + + b.Property("MaxPlanes") + .HasColumnType("int"); + + b.Property("ShopName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Shops"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.ShopPlane", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("PlaneId") + .HasColumnType("int"); + + b.Property("ShopId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("PlaneId"); + + b.HasIndex("ShopId"); + + b.ToTable("ShopPlanes"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Message", b => + { + b.HasOne("AircraftPlantDatabaseImplement.Models.Client", "Client") + .WithMany("Messages") + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Order", b => + { + b.HasOne("AircraftPlantDatabaseImplement.Models.Client", "Client") + .WithMany("Orders") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("AircraftPlantDatabaseImplement.Models.Implementer", "Implementer") + .WithMany("Orders") + .HasForeignKey("ImplementerId"); + + b.HasOne("AircraftPlantDatabaseImplement.Models.Plane", "Plane") + .WithMany("Orders") + .HasForeignKey("PlaneId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Client"); + + b.Navigation("Implementer"); + + b.Navigation("Plane"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.PlaneComponent", b => + { + b.HasOne("AircraftPlantDatabaseImplement.Models.Component", "Component") + .WithMany("PlaneComponents") + .HasForeignKey("ComponentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("AircraftPlantDatabaseImplement.Models.Plane", "Plane") + .WithMany("Components") + .HasForeignKey("PlaneId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Component"); + + b.Navigation("Plane"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.ShopPlane", b => + { + b.HasOne("AircraftPlantDatabaseImplement.Models.Plane", "Plane") + .WithMany() + .HasForeignKey("PlaneId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("AircraftPlantDatabaseImplement.Models.Shop", "Shop") + .WithMany("Planes") + .HasForeignKey("ShopId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Plane"); + + b.Navigation("Shop"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Client", b => + { + b.Navigation("Messages"); + + b.Navigation("Orders"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Component", b => + { + b.Navigation("PlaneComponents"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Implementer", b => + { + b.Navigation("Orders"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Plane", b => + { + b.Navigation("Components"); + + b.Navigation("Orders"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Shop", b => + { + b.Navigation("Planes"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/20240505220907_MessageInfoUpdate.cs b/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/20240505220907_MessageInfoUpdate.cs new file mode 100644 index 0000000..b651d89 --- /dev/null +++ b/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/20240505220907_MessageInfoUpdate.cs @@ -0,0 +1,39 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace AircraftPlantDatabaseImplement.Migrations +{ + /// + public partial class MessageInfoUpdate : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "IsChecked", + table: "Messages", + type: "bit", + nullable: false, + defaultValue: false); + + migrationBuilder.AddColumn( + name: "Reply", + table: "Messages", + type: "nvarchar(max)", + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "IsChecked", + table: "Messages"); + + migrationBuilder.DropColumn( + name: "Reply", + table: "Messages"); + } + } +} diff --git a/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/AircraftPlantDatabaseModelSnapshot.cs b/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/AircraftPlantDatabaseModelSnapshot.cs index 7bfbe92..eec4ac7 100644 --- a/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/AircraftPlantDatabaseModelSnapshot.cs +++ b/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/AircraftPlantDatabaseModelSnapshot.cs @@ -94,6 +94,42 @@ namespace AircraftPlantDatabaseImplement.Migrations b.ToTable("Implementers"); }); + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Message", b => + { + b.Property("MessageId") + .HasColumnType("nvarchar(450)"); + + b.Property("Body") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("int"); + + b.Property("DateDelivery") + .HasColumnType("datetime2"); + + b.Property("IsChecked") + .HasColumnType("bit"); + + b.Property("Reply") + .HasColumnType("nvarchar(max)"); + + b.Property("SenderName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Subject") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("MessageId"); + + b.HasIndex("ClientId"); + + b.ToTable("Messages"); + }); + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -236,6 +272,15 @@ namespace AircraftPlantDatabaseImplement.Migrations b.ToTable("ShopPlanes"); }); + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Message", b => + { + b.HasOne("AircraftPlantDatabaseImplement.Models.Client", "Client") + .WithMany("Messages") + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Order", b => { b.HasOne("AircraftPlantDatabaseImplement.Models.Client", "Client") @@ -301,6 +346,8 @@ namespace AircraftPlantDatabaseImplement.Migrations modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Client", b => { + b.Navigation("Messages"); + b.Navigation("Orders"); }); diff --git a/AircraftPlant/AircraftPlantDatabaseImplement/Models/Client.cs b/AircraftPlant/AircraftPlantDatabaseImplement/Models/Client.cs index a44be09..6f59b44 100644 --- a/AircraftPlant/AircraftPlantDatabaseImplement/Models/Client.cs +++ b/AircraftPlant/AircraftPlantDatabaseImplement/Models/Client.cs @@ -45,12 +45,18 @@ namespace AircraftPlantDatabaseImplement.Models [ForeignKey("ClientId")] public virtual List Orders { get; set; } = new(); - /// - /// Создание модели клиента - /// - /// - /// - public static Client? Create(ClientBindingModel model) + /// + /// Связь с письмами + /// + [ForeignKey("ClientId")] + public virtual List Messages { get; set; } = new(); + + /// + /// Создание модели клиента + /// + /// + /// + public static Client? Create(ClientBindingModel model) { if (model == null) { diff --git a/AircraftPlant/AircraftPlantDatabaseImplement/Models/Message.cs b/AircraftPlant/AircraftPlantDatabaseImplement/Models/Message.cs new file mode 100644 index 0000000..ea69a23 --- /dev/null +++ b/AircraftPlant/AircraftPlantDatabaseImplement/Models/Message.cs @@ -0,0 +1,124 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.ViewModels; +using AircraftPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantDatabaseImplement.Models +{ + /// + /// Сущность "Письмо" + /// + public class Message : IMessageInfoModel + { + /// + /// Идентификатор + /// + [Key] + 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; + + /// + /// Письмо прочитано + /// + [Required] + public bool IsChecked { get; set; } + + /// + /// Ответ на писмо + /// + public string? Reply { get; set; } + + /// + /// Создание модели письма + /// + /// + /// + public static Message? 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, + IsChecked = model.IsChecked, + Reply = model.Reply + }; + } + + /// + /// Изменение модели письма + /// + /// + public void Update(MessageInfoBindingModel model) + { + if (model == null) + { + return; + } + + IsChecked = model.IsChecked; + Reply = model.Reply; + } + + /// + /// Получение модели письма + /// + public MessageInfoViewModel GetViewModel => new() + { + MessageId = MessageId, + ClientId = ClientId, + SenderName = SenderName, + DateDelivery = DateDelivery, + Subject = Subject, + Body = Body, + IsChecked = IsChecked, + Reply = Reply + }; + } +} diff --git a/AircraftPlant/AircraftPlantFileImplement/DataFileSingleton.cs b/AircraftPlant/AircraftPlantFileImplement/DataFileSingleton.cs index f9920ec..981088e 100644 --- a/AircraftPlant/AircraftPlantFileImplement/DataFileSingleton.cs +++ b/AircraftPlant/AircraftPlantFileImplement/DataFileSingleton.cs @@ -48,10 +48,15 @@ namespace AircraftPlantFileImplement /// private readonly string ImplementerFileName = "Implementer.xml"; - /// - /// Список классов-моделей компонентов - /// - public List Components { get; set; } + /// + /// Название файла для хранения информации о письмах + /// + private readonly string MessageFileName = "Message.xml"; + + /// + /// Список классов-моделей компонентов + /// + public List Components { get; set; } /// /// Список классов-моделей заказов @@ -78,10 +83,15 @@ namespace AircraftPlantFileImplement /// public List Implementers { get; set; } - /// - /// Конструктор - /// - private DataFileSingleton() + /// + /// Список классов-моделей писем + /// + public List Messages { get; set; } + + /// + /// Конструктор + /// + private DataFileSingleton() { Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!; Planes = LoadData(PlaneFileName, "Plane", x => Plane.Create(x)!)!; @@ -89,6 +99,7 @@ namespace AircraftPlantFileImplement Shops = LoadData(ShopFileName, "Shop", x => Shop.Create(x)!)!; Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!; Implementers = LoadData(ImplementerFileName, "Implementer", x => Implementer.Create(x)!)!; + Messages = LoadData(MessageFileName, "Message", x => Message.Create(x)!)!; } /// @@ -134,15 +145,20 @@ namespace AircraftPlantFileImplement /// public void SaveImplementers() => SaveData(Implementers, ImplementerFileName, "Implementers", x => x.GetXElement); - /// - /// Метод для загрузки данных из xml-файла - /// - /// - /// - /// - /// - /// - private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) + /// + /// Сохранение писем + /// + public void SaveMessages() => SaveData(Messages, MessageFileName, "Messages", x => x.GetXElement); + + /// + /// Метод для загрузки данных из xml-файла + /// + /// + /// + /// + /// + /// + private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) { if (File.Exists(filename)) { diff --git a/AircraftPlant/AircraftPlantFileImplement/Implements/MessageInfoStorage.cs b/AircraftPlant/AircraftPlantFileImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..77b89c7 --- /dev/null +++ b/AircraftPlant/AircraftPlantFileImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,133 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.SearchModels; +using AircraftPlantContracts.StoragesContracts; +using AircraftPlantContracts.ViewModels; +using AircraftPlantFileImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantFileImplement.Implements +{ + /// + /// Реализация интерфейса хранилища для писем + /// + public class MessageInfoStorage : IMessageInfoStorage + { + /// + /// Хранилище + /// + private readonly DataFileSingleton _source; + + /// + /// Конструктор + /// + public MessageInfoStorage() + { + _source = DataFileSingleton.GetInstance(); + } + + /// + /// Получение полного списка + /// + /// + public List GetFullList() + { + return _source.Messages + .Select(x => x.GetViewModel) + .ToList(); + } + + /// + /// Получение фильтрованного списка + /// + /// + /// + public List GetFilteredList(MessageInfoSearchModel model) + { + if (!model.ClientId.HasValue && (!model.PageSize.HasValue || !model.CurrentPage.HasValue)) + { + return new(); + } + + if (model.CurrentPage.HasValue && model.PageSize.HasValue && model.ClientId.HasValue) + { + return _source.Messages + .Where(x => x.ClientId == model.ClientId) + .Skip((model.CurrentPage.Value - 1) * model.PageSize.Value) + .Take(model.PageSize.Value) + .Select(x => x.GetViewModel) + .ToList(); + } + + if (model.CurrentPage.HasValue && model.PageSize.HasValue) + { + return _source.Messages + .Skip((model.CurrentPage.Value - 1) * model.PageSize.Value) + .Take(model.PageSize.Value) + .Select(x => x.GetViewModel) + .ToList(); + } + + return _source.Messages + .Where(x => x.ClientId == model.ClientId) + .Select(x => x.GetViewModel) + .ToList(); + } + + /// + /// Получение элемента + /// + /// + /// + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (string.IsNullOrEmpty(model.MessageId)) + { + return null; + } + + return _source.Messages + .FirstOrDefault(x => x.MessageId == model.MessageId) + ?.GetViewModel; + } + + /// + /// Добавление элемента + /// + /// + /// + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = Message.Create(model); + if (newMessage == null) + { + return null; + } + + _source.Messages.Add(newMessage); + _source.SaveMessages(); + return newMessage.GetViewModel; + } + + /// + /// Редактирование элемента + /// + /// + /// + public MessageInfoViewModel? Update(MessageInfoBindingModel model) + { + var message = _source.Messages.FirstOrDefault(x => x.MessageId == model.MessageId); + if (message == null) + { + return null; + } + + message.Update(model); + _source.SaveMessages(); + return message.GetViewModel; + } + } +} diff --git a/AircraftPlant/AircraftPlantFileImplement/Models/Message.cs b/AircraftPlant/AircraftPlantFileImplement/Models/Message.cs new file mode 100644 index 0000000..fdf7189 --- /dev/null +++ b/AircraftPlant/AircraftPlantFileImplement/Models/Message.cs @@ -0,0 +1,151 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.ViewModels; +using AircraftPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace AircraftPlantFileImplement.Models +{ + /// + /// Сущность "Письмо" + /// + public class Message : IMessageInfoModel + { + /// + /// Идентификатор + /// + public string MessageId { get; set; } = string.Empty; + + /// + /// Идентификатор клиента + /// + public int? ClientId { get; set; } + + /// + /// Адрес электронной почты отправителя + /// + public string SenderName { get; set; } = string.Empty; + + /// + /// Дата получения письма + /// + public DateTime DateDelivery { get; set; } + + /// + /// Заголовок письма + /// + public string Subject { get; set; } = string.Empty; + + /// + /// Тело письма + /// + public string Body { get; set; } = string.Empty; + + /// + /// Письмо прочитано + /// + public bool IsChecked { get; set; } + + /// + /// Ответ на писмо + /// + public string? Reply { get; set; } + + /// + /// Создание модели письма + /// + /// + /// + public static Message? 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, + IsChecked = model.IsChecked, + Reply = model.Reply + }; + } + + /// + /// Создание модели письма из данных файла + /// + /// + /// + public static Message? Create(XElement element) + { + if (element == null) + { + return null; + } + + return new() + { + MessageId = element.Attribute("MessageId")!.Value, + ClientId = Convert.ToInt32(element.Attribute("ClientId")!.Value), + SenderName = element.Attribute("SenderName")!.Value, + DateDelivery = Convert.ToDateTime(element.Attribute("DateDelivery")!.Value), + Subject = element.Attribute("Subject")!.Value, + Body = element.Attribute("Body")!.Value, + IsChecked = Convert.ToBoolean(element.Attribute("IsChecked")!.Value), + Reply = element.Attribute("Reply")!.Value + }; + } + + /// + /// Изменение модели письма + /// + /// + public void Update(MessageInfoBindingModel model) + { + if (model == null) + { + return; + } + + IsChecked = model.IsChecked; + Reply = model.Reply; + } + + /// + /// Получение модели письма + /// + public MessageInfoViewModel GetViewModel => new() + { + MessageId = MessageId, + ClientId = ClientId, + SenderName = SenderName, + DateDelivery = DateDelivery, + Subject = Subject, + Body = Body, + IsChecked = IsChecked, + Reply = Reply + }; + + /// + /// Запись данных о модели письма в файл + /// + public XElement GetXElement => new("MessageInfo", + new XAttribute("MessageId", MessageId), + new XAttribute("ClientId", ClientId), + new XAttribute("SenderName", SenderName), + new XAttribute("DateDelivery", DateDelivery), + new XAttribute("Subject", Subject), + new XAttribute("Body", Body), + new XAttribute("IsChecked", IsChecked), + new XAttribute("Reply", Reply)); + } +} diff --git a/AircraftPlant/AircraftPlantListImplement/DataListSingleton.cs b/AircraftPlant/AircraftPlantListImplement/DataListSingleton.cs index 9671eca..dce0bda 100644 --- a/AircraftPlant/AircraftPlantListImplement/DataListSingleton.cs +++ b/AircraftPlant/AircraftPlantListImplement/DataListSingleton.cs @@ -47,10 +47,15 @@ namespace AircraftPlantListImplement /// public List Implementers { get; set; } - /// - /// Конструктор - /// - private DataListSingleton() + /// + /// Список классов-моделей писем + /// + public List Messages { get; set; } + + /// + /// Конструктор + /// + private DataListSingleton() { Components = new List(); Orders = new List(); @@ -58,6 +63,7 @@ namespace AircraftPlantListImplement Shops = new List(); Clients = new List(); Implementers = new List(); + Messages = new List(); } /// diff --git a/AircraftPlant/AircraftPlantListImplement/Implements/MessageInfoStorage.cs b/AircraftPlant/AircraftPlantListImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..24dbf60 --- /dev/null +++ b/AircraftPlant/AircraftPlantListImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,145 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.SearchModels; +using AircraftPlantContracts.StoragesContracts; +using AircraftPlantContracts.ViewModels; +using AircraftPlantListImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantListImplement.Implements +{ + /// + /// Реализация интерфейса хранилища для писем + /// + public class MessageInfoStorage : IMessageInfoStorage + { + /// + /// Хранилище + /// + private readonly DataListSingleton _source; + + /// + /// Конструктор + /// + public MessageInfoStorage() + { + _source = DataListSingleton.GetInstance(); + } + + /// + /// Получение полного списка + /// + /// + public List GetFullList() + { + var result = new List(); + foreach (var message in _source.Messages) + { + result.Add(message.GetViewModel); + } + return result; + } + + /// + /// Получение фильтрованного списка + /// + /// + /// + public List GetFilteredList(MessageInfoSearchModel model) + { + var result = new List(); + + if (model.ClientId.HasValue) + { + foreach (var message in _source.Messages) + { + if (message.ClientId == model.ClientId) + { + result.Add(message.GetViewModel); + } + } + return result; + } + + if (!model.CurrentPage.HasValue || !model.PageSize.HasValue) + { + return result; + } + + var resultPages = new List(); + if (model.ClientId.HasValue) + { + for (int i = (model.CurrentPage.Value - 1) * model.PageSize.Value; i < model.PageSize.Value * model.CurrentPage.Value; i++) + { + resultPages.Add(result[i]); + } + } + else + { + for (int i = (model.CurrentPage.Value - 1) * model.PageSize.Value; i < model.PageSize.Value * model.CurrentPage.Value; i++) + { + resultPages.Add(_source.Messages[i].GetViewModel); + } + } + return result; + } + + /// + /// Получение элемента + /// + /// + /// + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (string.IsNullOrEmpty(model.MessageId)) + { + return null; + } + + foreach (var message in _source.Messages) + { + if (model.MessageId.Equals(message.MessageId)) + return message.GetViewModel; + } + return null; + } + + /// + /// Добавление элемента + /// + /// + /// + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = Message.Create(model); + if (newMessage == null) + { + return null; + } + + _source.Messages.Add(newMessage); + return newMessage.GetViewModel; + } + + /// + /// Редактирование элемента + /// + /// + /// + public MessageInfoViewModel? Update(MessageInfoBindingModel model) + { + foreach (var message in _source.Messages) + { + if (message.MessageId == model.MessageId) + { + message.Update(model); + return message.GetViewModel; + } + } + return null; + } + } +} diff --git a/AircraftPlant/AircraftPlantListImplement/Models/Message.cs b/AircraftPlant/AircraftPlantListImplement/Models/Message.cs new file mode 100644 index 0000000..413e70e --- /dev/null +++ b/AircraftPlant/AircraftPlantListImplement/Models/Message.cs @@ -0,0 +1,112 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.ViewModels; +using AircraftPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantListImplement.Models +{ + /// + /// Сущность "Письмо" + /// + public class Message : IMessageInfoModel + { + /// + /// Идентификатор + /// + public string MessageId { get; set; } = string.Empty; + + /// + /// Идентификатор клиента + /// + public int? ClientId { get; set; } + + /// + /// Адрес электронной почты отправителя + /// + public string SenderName { get; set; } = string.Empty; + + /// + /// Дата получения письма + /// + public DateTime DateDelivery { get; set; } + + /// + /// Заголовок письма + /// + public string Subject { get; set; } = string.Empty; + + /// + /// Тело письма + /// + public string Body { get; set; } = string.Empty; + + /// + /// Письмо прочитано + /// + public bool IsChecked { get; set; } + + /// + /// Ответ на писмо + /// + public string? Reply { get; set; } + + /// + /// Создание модели письма + /// + /// + /// + public static Message? 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, + IsChecked = model.IsChecked, + Reply = model.Reply + }; + } + + /// + /// Изменение модели письма + /// + /// + public void Update(MessageInfoBindingModel model) + { + if (model == null) + { + return; + } + + IsChecked = model.IsChecked; + Reply = model.Reply; + } + + /// + /// Получение модели письма + /// + public MessageInfoViewModel GetViewModel => new() + { + MessageId = MessageId, + ClientId = ClientId, + SenderName = SenderName, + DateDelivery = DateDelivery, + Subject = Subject, + Body = Body, + IsChecked = IsChecked, + Reply = Reply + }; + } +} diff --git a/AircraftPlant/AircraftPlantRestApi/Controllers/ClientController.cs b/AircraftPlant/AircraftPlantRestApi/Controllers/ClientController.cs index 2bb3a49..54a605d 100644 --- a/AircraftPlant/AircraftPlantRestApi/Controllers/ClientController.cs +++ b/AircraftPlant/AircraftPlantRestApi/Controllers/ClientController.cs @@ -23,15 +23,22 @@ namespace AircraftPlantRestApi.Controllers /// 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; } /// @@ -93,5 +100,37 @@ namespace AircraftPlantRestApi.Controllers throw; } } - } + + /// + /// Получение списка писем клиента + /// + /// + /// + [HttpGet] + public List? GetMessages(int clientId, int? currentPage) + { + try + { + if (currentPage == null) + { + return _mailLogic.ReadList(new MessageInfoSearchModel + { + ClientId = clientId + }); + } + + return _mailLogic.ReadList(new MessageInfoSearchModel + { + ClientId = clientId, + CurrentPage = currentPage, + PageSize = 3 + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения писем клиента"); + throw; + } + } + } } diff --git a/AircraftPlant/AircraftPlantRestApi/Program.cs b/AircraftPlant/AircraftPlantRestApi/Program.cs index 065db15..ed9e0a8 100644 --- a/AircraftPlant/AircraftPlantRestApi/Program.cs +++ b/AircraftPlant/AircraftPlantRestApi/Program.cs @@ -1,4 +1,6 @@ using AircraftPlantBusinessLogic.BusinessLogics; +using AircraftPlantBusinessLogic.MailWorker; +using AircraftPlantContracts.BindingModels; using AircraftPlantContracts.BusinessLogicsContracts; using AircraftPlantContracts.StoragesContracts; using AircraftPlantDatabaseImplement.Implements; @@ -15,12 +17,16 @@ 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.AddTransient(); + +builder.Services.AddSingleton(); builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle @@ -32,6 +38,18 @@ 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/AircraftPlant/AircraftPlantRestApi/appsettings.json b/AircraftPlant/AircraftPlantRestApi/appsettings.json index 10f68b8..a875686 100644 --- a/AircraftPlant/AircraftPlantRestApi/appsettings.json +++ b/AircraftPlant/AircraftPlantRestApi/appsettings.json @@ -5,5 +5,12 @@ "Microsoft.AspNetCore": "Warning" } }, - "AllowedHosts": "*" + "AllowedHosts": "*", + + "SmtpClientHost": "smtp.gmail.com", + "SmtpClientPort": "587", + "PopHost": "pop.gmail.com", + "PopPort": "995", + "MailLogin": "aircraftplant73@gmail.com", + "MailPassword": "vcus klnn auqe axlq" } diff --git a/AircraftPlant/AircraftPlantView/AircraftPlantView.csproj b/AircraftPlant/AircraftPlantView/AircraftPlantView.csproj index 354cd26..ae6dade 100644 --- a/AircraftPlant/AircraftPlantView/AircraftPlantView.csproj +++ b/AircraftPlant/AircraftPlantView/AircraftPlantView.csproj @@ -37,4 +37,10 @@ + + + Always + + + \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantView/App.config b/AircraftPlant/AircraftPlantView/App.config new file mode 100644 index 0000000..d2a7c0c --- /dev/null +++ b/AircraftPlant/AircraftPlantView/App.config @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantView/FormImplementer.Designer.cs b/AircraftPlant/AircraftPlantView/FormImplementer.Designer.cs index b2fe207..eb92254 100644 --- a/AircraftPlant/AircraftPlantView/FormImplementer.Designer.cs +++ b/AircraftPlant/AircraftPlantView/FormImplementer.Designer.cs @@ -20,139 +20,139 @@ 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() - { - textBoxImplementerFIO = new TextBox(); - textBoxPassword = new TextBox(); - numericUpDownWorkExperience = new NumericUpDown(); - numericUpDownQualification = new NumericUpDown(); - buttonCancel = new Button(); - labelImplementerFIO = new Label(); - labelPassword = new Label(); - labelWorkExperience = new Label(); - labelQualification = new Label(); - buttonSave = new Button(); - ((System.ComponentModel.ISupportInitialize)numericUpDownWorkExperience).BeginInit(); - ((System.ComponentModel.ISupportInitialize)numericUpDownQualification).BeginInit(); - SuspendLayout(); - // - // textBoxImplementerFIO - // - textBoxImplementerFIO.Location = new Point(108, 12); - textBoxImplementerFIO.Name = "textBoxImplementerFIO"; - textBoxImplementerFIO.Size = new Size(264, 23); - textBoxImplementerFIO.TabIndex = 0; - // - // textBoxPassword - // - textBoxPassword.Location = new Point(108, 41); - textBoxPassword.Name = "textBoxPassword"; - textBoxPassword.Size = new Size(264, 23); - textBoxPassword.TabIndex = 1; - // - // numericUpDownWorkExperience - // - numericUpDownWorkExperience.Location = new Point(108, 70); - numericUpDownWorkExperience.Name = "numericUpDownWorkExperience"; - numericUpDownWorkExperience.Size = new Size(264, 23); - numericUpDownWorkExperience.TabIndex = 2; - // - // numericUpDownQualification - // - numericUpDownQualification.Location = new Point(108, 99); - numericUpDownQualification.Name = "numericUpDownQualification"; - numericUpDownQualification.Size = new Size(264, 23); - numericUpDownQualification.TabIndex = 3; - // - // buttonCancel - // - buttonCancel.Location = new Point(297, 134); - buttonCancel.Name = "buttonCancel"; - buttonCancel.Size = new Size(75, 23); - buttonCancel.TabIndex = 4; - buttonCancel.Text = "Отмена"; - buttonCancel.UseVisualStyleBackColor = true; - buttonCancel.Click += buttonCancel_Click; - // - // labelImplementerFIO - // - labelImplementerFIO.AutoSize = true; - labelImplementerFIO.Location = new Point(12, 15); - labelImplementerFIO.Name = "labelImplementerFIO"; - labelImplementerFIO.Size = new Size(37, 15); - labelImplementerFIO.TabIndex = 5; - labelImplementerFIO.Text = "ФИО:"; - // - // labelPassword - // - labelPassword.AutoSize = true; - labelPassword.Location = new Point(11, 44); - labelPassword.Name = "labelPassword"; - labelPassword.Size = new Size(52, 15); - labelPassword.TabIndex = 6; - labelPassword.Text = "Пароль:"; - // - // labelWorkExperience - // - labelWorkExperience.AutoSize = true; - labelWorkExperience.Location = new Point(12, 72); - labelWorkExperience.Name = "labelWorkExperience"; - labelWorkExperience.Size = new Size(38, 15); - labelWorkExperience.TabIndex = 7; - labelWorkExperience.Text = "label1"; - // - // labelQualification - // - labelQualification.AutoSize = true; - labelQualification.Location = new Point(11, 101); - labelQualification.Name = "labelQualification"; - labelQualification.Size = new Size(91, 15); - labelQualification.TabIndex = 8; - labelQualification.Text = "Квалификация:"; - // - // buttonSave - // - buttonSave.Location = new Point(216, 134); - buttonSave.Name = "buttonSave"; - buttonSave.Size = new Size(75, 23); - buttonSave.TabIndex = 9; - buttonSave.Text = "Сохранить"; - buttonSave.UseVisualStyleBackColor = true; - buttonSave.Click += buttonSave_Click; - // - // FormImplementer - // - AutoScaleDimensions = new SizeF(7F, 15F); - AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(384, 169); - Controls.Add(buttonSave); - Controls.Add(labelQualification); - Controls.Add(labelWorkExperience); - Controls.Add(labelPassword); - Controls.Add(labelImplementerFIO); - Controls.Add(buttonCancel); - Controls.Add(numericUpDownQualification); - Controls.Add(numericUpDownWorkExperience); - Controls.Add(textBoxPassword); - Controls.Add(textBoxImplementerFIO); - Name = "FormImplementer"; - Text = "Исполнитель"; - Load += FormImplementer_Load; - ((System.ComponentModel.ISupportInitialize)numericUpDownWorkExperience).EndInit(); - ((System.ComponentModel.ISupportInitialize)numericUpDownQualification).EndInit(); - ResumeLayout(false); - PerformLayout(); - } + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + textBoxImplementerFIO = new TextBox(); + textBoxPassword = new TextBox(); + numericUpDownWorkExperience = new NumericUpDown(); + numericUpDownQualification = new NumericUpDown(); + buttonCancel = new Button(); + labelImplementerFIO = new Label(); + labelPassword = new Label(); + labelWorkExperience = new Label(); + labelQualification = new Label(); + buttonSave = new Button(); + ((System.ComponentModel.ISupportInitialize)numericUpDownWorkExperience).BeginInit(); + ((System.ComponentModel.ISupportInitialize)numericUpDownQualification).BeginInit(); + SuspendLayout(); + // + // textBoxImplementerFIO + // + textBoxImplementerFIO.Location = new Point(108, 12); + textBoxImplementerFIO.Name = "textBoxImplementerFIO"; + textBoxImplementerFIO.Size = new Size(264, 23); + textBoxImplementerFIO.TabIndex = 0; + // + // textBoxPassword + // + textBoxPassword.Location = new Point(108, 41); + textBoxPassword.Name = "textBoxPassword"; + textBoxPassword.Size = new Size(264, 23); + textBoxPassword.TabIndex = 1; + // + // numericUpDownWorkExperience + // + numericUpDownWorkExperience.Location = new Point(108, 70); + numericUpDownWorkExperience.Name = "numericUpDownWorkExperience"; + numericUpDownWorkExperience.Size = new Size(264, 23); + numericUpDownWorkExperience.TabIndex = 2; + // + // numericUpDownQualification + // + numericUpDownQualification.Location = new Point(108, 99); + numericUpDownQualification.Name = "numericUpDownQualification"; + numericUpDownQualification.Size = new Size(264, 23); + numericUpDownQualification.TabIndex = 3; + // + // buttonCancel + // + buttonCancel.Location = new Point(297, 134); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(75, 23); + buttonCancel.TabIndex = 4; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += buttonCancel_Click; + // + // labelImplementerFIO + // + labelImplementerFIO.AutoSize = true; + labelImplementerFIO.Location = new Point(12, 15); + labelImplementerFIO.Name = "labelImplementerFIO"; + labelImplementerFIO.Size = new Size(37, 15); + labelImplementerFIO.TabIndex = 5; + labelImplementerFIO.Text = "ФИО:"; + // + // labelPassword + // + labelPassword.AutoSize = true; + labelPassword.Location = new Point(11, 44); + labelPassword.Name = "labelPassword"; + labelPassword.Size = new Size(52, 15); + labelPassword.TabIndex = 6; + labelPassword.Text = "Пароль:"; + // + // labelWorkExperience + // + labelWorkExperience.AutoSize = true; + labelWorkExperience.Location = new Point(12, 72); + labelWorkExperience.Name = "labelWorkExperience"; + labelWorkExperience.Size = new Size(84, 15); + labelWorkExperience.TabIndex = 7; + labelWorkExperience.Text = "Опыт работы:"; + // + // labelQualification + // + labelQualification.AutoSize = true; + labelQualification.Location = new Point(11, 101); + labelQualification.Name = "labelQualification"; + labelQualification.Size = new Size(91, 15); + labelQualification.TabIndex = 8; + labelQualification.Text = "Квалификация:"; + // + // buttonSave + // + buttonSave.Location = new Point(216, 134); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(75, 23); + buttonSave.TabIndex = 9; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += buttonSave_Click; + // + // FormImplementer + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(384, 169); + Controls.Add(buttonSave); + Controls.Add(labelQualification); + Controls.Add(labelWorkExperience); + Controls.Add(labelPassword); + Controls.Add(labelImplementerFIO); + Controls.Add(buttonCancel); + Controls.Add(numericUpDownQualification); + Controls.Add(numericUpDownWorkExperience); + Controls.Add(textBoxPassword); + Controls.Add(textBoxImplementerFIO); + Name = "FormImplementer"; + Text = "Исполнитель"; + Load += FormImplementer_Load; + ((System.ComponentModel.ISupportInitialize)numericUpDownWorkExperience).EndInit(); + ((System.ComponentModel.ISupportInitialize)numericUpDownQualification).EndInit(); + ResumeLayout(false); + PerformLayout(); + } - #endregion + #endregion - private TextBox textBoxImplementerFIO; + private TextBox textBoxImplementerFIO; private TextBox textBoxPassword; private NumericUpDown numericUpDownWorkExperience; private NumericUpDown numericUpDownQualification; diff --git a/AircraftPlant/AircraftPlantView/FormMail.Designer.cs b/AircraftPlant/AircraftPlantView/FormMail.Designer.cs new file mode 100644 index 0000000..1c9d972 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormMail.Designer.cs @@ -0,0 +1,122 @@ +namespace AircraftPlantView +{ + 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() + { + dataGridView = new DataGridView(); + buttonPrev = new Button(); + labelPage = new Label(); + buttonNext = new Button(); + buttonReply = new Button(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // dataGridView + // + dataGridView.AllowUserToAddRows = false; + dataGridView.AllowUserToDeleteRows = false; + dataGridView.BackgroundColor = Color.White; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Dock = DockStyle.Top; + dataGridView.GridColor = Color.Black; + dataGridView.Location = new Point(0, 0); + dataGridView.MultiSelect = false; + dataGridView.Name = "dataGridView"; + dataGridView.ReadOnly = true; + dataGridView.RowHeadersVisible = false; + dataGridView.RowTemplate.Height = 25; + dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; + dataGridView.Size = new Size(584, 320); + dataGridView.TabIndex = 2; + // + // buttonPrev + // + buttonPrev.Location = new Point(12, 326); + buttonPrev.Name = "buttonPrev"; + buttonPrev.Size = new Size(75, 23); + buttonPrev.TabIndex = 3; + buttonPrev.Text = "<<<"; + buttonPrev.UseVisualStyleBackColor = true; + buttonPrev.Click += buttonPrev_Click; + // + // labelPage + // + labelPage.AutoSize = true; + labelPage.Location = new Point(93, 330); + labelPage.Name = "labelPage"; + labelPage.Size = new Size(69, 15); + labelPage.TabIndex = 4; + labelPage.Text = "Страница 1"; + // + // buttonNext + // + buttonNext.Location = new Point(168, 326); + buttonNext.Name = "buttonNext"; + buttonNext.Size = new Size(75, 23); + buttonNext.TabIndex = 5; + buttonNext.Text = ">>>"; + buttonNext.UseVisualStyleBackColor = true; + buttonNext.Click += buttonNext_Click; + // + // buttonReply + // + buttonReply.Location = new Point(497, 330); + buttonReply.Name = "buttonReply"; + buttonReply.Size = new Size(75, 23); + buttonReply.TabIndex = 6; + buttonReply.Text = "Ответить"; + buttonReply.UseVisualStyleBackColor = true; + buttonReply.Click += buttonReply_Click; + // + // FormMail + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(584, 361); + Controls.Add(buttonReply); + Controls.Add(buttonNext); + Controls.Add(labelPage); + Controls.Add(buttonPrev); + Controls.Add(dataGridView); + Name = "FormMail"; + Text = "Письма"; + Load += FormMail_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private DataGridView dataGridView; + private Button buttonPrev; + private Label labelPage; + private Button buttonNext; + private Button buttonReply; + } +} \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantView/FormMail.cs b/AircraftPlant/AircraftPlantView/FormMail.cs new file mode 100644 index 0000000..a2b7a6c --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormMail.cs @@ -0,0 +1,152 @@ +using AircraftPlantContracts.BusinessLogicsContracts; +using AircraftPlantContracts.SearchModels; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace AircraftPlantView +{ + /// + /// Форма для вывода писем + /// + public partial class FormMail : Form + { + /// + /// Логгер + /// + private readonly ILogger _logger; + + /// + /// Бизнес-логика для писем + /// + private readonly IMessageInfoLogic _logic; + + /// + /// Размер страницы пагинации + /// + private int PageSize = 3; + + /// + /// Текущая страница пагинации + /// + private int CurrentPage = 1; + + /// + /// Конструктор + /// + /// + /// + public FormMail(ILogger logger, IMessageInfoLogic logic) + { + InitializeComponent(); + + _logger = logger; + _logic = logic; + } + + /// + /// Загрузка писем + /// + /// + /// + private void FormMail_Load(object sender, EventArgs e) + { + LoadData(); + } + + /// + /// Кнопка переключения на предыдущую страницу + /// + /// + /// + private void buttonPrev_Click(object sender, EventArgs e) + { + if (CurrentPage - 1 <= 0) + { + return; + } + + CurrentPage--; + LoadData(); + } + + /// + /// Кнопка переключения на следующую страницу + /// + /// + /// + private void buttonNext_Click(object sender, EventArgs e) + { + CurrentPage++; + LoadData(); + } + + /// + /// Кнопка "Отправить" + /// + /// + /// + private void buttonReply_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + var service = Program.ServiceProvider?.GetService(typeof(FormMessage)); + if (service is FormMessage form) + { + form.MessageId = Convert.ToString(dataGridView.SelectedRows[0].Cells["MessageId"].Value); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + } + + /// + /// Метод загрузки писем + /// + private void LoadData() + { + try + { + var list = _logic.ReadList(new MessageInfoSearchModel + { + PageSize = PageSize, + CurrentPage = CurrentPage + }); + + if (list != null && list.Count == 0 && CurrentPage != 1) + { + CurrentPage--; + list = _logic.ReadList(new MessageInfoSearchModel + { + PageSize = PageSize, + CurrentPage = CurrentPage + }); + } + + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["MessageId"].Visible = false; + dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + labelPage.Text = $"Страница {CurrentPage}"; + _logger.LogInformation("Загрузка писем"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки писем"); + MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } +} diff --git a/AircraftPlant/AircraftPlantView/FormMail.resx b/AircraftPlant/AircraftPlantView/FormMail.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/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/AircraftPlant/AircraftPlantView/FormMain.Designer.cs b/AircraftPlant/AircraftPlantView/FormMain.Designer.cs index b9f2be7..ab3ab72 100644 --- a/AircraftPlant/AircraftPlantView/FormMain.Designer.cs +++ b/AircraftPlant/AircraftPlantView/FormMain.Designer.cs @@ -34,22 +34,22 @@ buttonRefresh = new Button(); menuStrip = new MenuStrip(); справочникиToolStripMenuItem = new ToolStripMenuItem(); + магазиныToolStripMenuItem = new ToolStripMenuItem(); компонентыToolStripMenuItem = new ToolStripMenuItem(); изделияToolStripMenuItem = new ToolStripMenuItem(); - магазиныToolStripMenuItem = new ToolStripMenuItem(); клиентыToolStripMenuItem = new ToolStripMenuItem(); + исполнителиToolStripMenuItem = new ToolStripMenuItem(); отчетыToolStripMenuItem = new ToolStripMenuItem(); изделияToolStripMenuItem1 = new ToolStripMenuItem(); изделияСКомпонентамиToolStripMenuItem = new ToolStripMenuItem(); списокЗаказовToolStripMenuItem = new ToolStripMenuItem(); - buttonAddPlaneInShop = new Button(); - buttonSellPlanes = new Button(); заказыСГруппировкойToolStripMenuItem = new ToolStripMenuItem(); списокМагазиновToolStripMenuItem = new ToolStripMenuItem(); ассортиментМагазиновToolStripMenuItem = new ToolStripMenuItem(); - клиентыToolStripMenuItem = new ToolStripMenuItem(); запускРаботToolStripMenuItem = new ToolStripMenuItem(); - исполнителиToolStripMenuItem = new ToolStripMenuItem(); + buttonAddPlaneInShop = new Button(); + buttonSellPlanes = new Button(); + почтаToolStripMenuItem = new ToolStripMenuItem(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); menuStrip.SuspendLayout(); SuspendLayout(); @@ -104,7 +104,7 @@ // // menuStrip // - menuStrip.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчетыToolStripMenuItem, запускРаботToolStripMenuItem }); + menuStrip.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчетыToolStripMenuItem, запускРаботToolStripMenuItem, почтаToolStripMenuItem }); menuStrip.Location = new Point(0, 0); menuStrip.Name = "menuStrip"; menuStrip.Size = new Size(984, 24); @@ -113,41 +113,46 @@ // // справочникиToolStripMenuItem // - справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, изделияToolStripMenuItem, магазиныToolStripMenuItem }); - справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, изделияToolStripMenuItem, клиентыToolStripMenuItem }); - справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, изделияToolStripMenuItem, клиентыToolStripMenuItem, исполнителиToolStripMenuItem }); + справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { магазиныToolStripMenuItem, компонентыToolStripMenuItem, изделияToolStripMenuItem, клиентыToolStripMenuItem, исполнителиToolStripMenuItem }); справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; справочникиToolStripMenuItem.Size = new Size(94, 20); справочникиToolStripMenuItem.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(180, 22); + компонентыToolStripMenuItem.Size = new Size(149, 22); компонентыToolStripMenuItem.Text = "Компоненты"; компонентыToolStripMenuItem.Click += компонентыToolStripMenuItem_Click; // // изделияToolStripMenuItem // изделияToolStripMenuItem.Name = "изделияToolStripMenuItem"; - изделияToolStripMenuItem.Size = new Size(180, 22); + изделияToolStripMenuItem.Size = new Size(149, 22); изделияToolStripMenuItem.Text = "Изделия"; изделияToolStripMenuItem.Click += изделияToolStripMenuItem_Click; // - // магазиныToolStripMenuItem - // - магазиныToolStripMenuItem.Name = "магазиныToolStripMenuItem"; - магазиныToolStripMenuItem.Size = new Size(145, 22); - магазиныToolStripMenuItem.Text = "Магазины"; - магазиныToolStripMenuItem.Click += магазиныToolStripMenuItem_Click; - // // клиентыToolStripMenuItem // клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; - клиентыToolStripMenuItem.Size = new Size(180, 22); + клиенты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[] { изделияToolStripMenuItem1, изделияСКомпонентамиToolStripMenuItem, списокЗаказовToolStripMenuItem, заказыСГруппировкойToolStripMenuItem, списокМагазиновToolStripMenuItem, ассортиментМагазиновToolStripMenuItem }); @@ -158,44 +163,24 @@ // изделияToolStripMenuItem1 // изделияToolStripMenuItem1.Name = "изделияToolStripMenuItem1"; - изделияToolStripMenuItem1.Size = new Size(215, 22); + изделияToolStripMenuItem1.Size = new Size(250, 22); изделияToolStripMenuItem1.Text = "Изделия"; изделияToolStripMenuItem1.Click += изделияToolStripMenuItem1_Click; // // изделияСКомпонентамиToolStripMenuItem // изделияСКомпонентамиToolStripMenuItem.Name = "изделияСКомпонентамиToolStripMenuItem"; - изделияСКомпонентамиToolStripMenuItem.Size = new Size(215, 22); + изделияСКомпонентамиToolStripMenuItem.Size = new Size(250, 22); изделияСКомпонентамиToolStripMenuItem.Text = "Изделия с компонентами"; изделияСКомпонентамиToolStripMenuItem.Click += изделияСКомпонентамиToolStripMenuItem_Click; // // списокЗаказовToolStripMenuItem // списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem"; - списокЗаказовToolStripMenuItem.Size = new Size(215, 22); + списокЗаказовToolStripMenuItem.Size = new Size(250, 22); списокЗаказовToolStripMenuItem.Text = "Список заказов"; списокЗаказовToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click; // - // buttonAddPlaneInShop - // - buttonAddPlaneInShop.Location = new Point(822, 210); - buttonAddPlaneInShop.Name = "buttonAddPlaneInShop"; - buttonAddPlaneInShop.Size = new Size(150, 50); - buttonAddPlaneInShop.TabIndex = 7; - buttonAddPlaneInShop.Text = "Добавить изделие\r\nв магазин"; - buttonAddPlaneInShop.UseVisualStyleBackColor = true; - buttonAddPlaneInShop.Click += buttonAddPlaneInShop_Click; - // - // buttonSellPlanes - // - buttonSellPlanes.Location = new Point(822, 266); - buttonSellPlanes.Name = "buttonSellPlanes"; - buttonSellPlanes.Size = new Size(150, 23); - buttonSellPlanes.TabIndex = 8; - buttonSellPlanes.Text = "Продать изделия"; - buttonSellPlanes.UseVisualStyleBackColor = true; - buttonSellPlanes.Click += buttonSellPlanes_Click; - // // заказыСГруппировкойToolStripMenuItem // заказыСГруппировкойToolStripMenuItem.Name = "заказыСГруппировкойToolStripMenuItem"; @@ -217,7 +202,6 @@ ассортиментМагазиновToolStripMenuItem.Text = "Ассортимент магазинов"; ассортиментМагазиновToolStripMenuItem.Click += ассортиментМагазиновToolStripMenuItem_Click; // - // клиентыToolStripMenuItem // запускРаботToolStripMenuItem // запускРаботToolStripMenuItem.Name = "запускРаботToolStripMenuItem"; @@ -225,12 +209,32 @@ запускРаботToolStripMenuItem.Text = "Запуск работ"; запускРаботToolStripMenuItem.Click += запускРаботToolStripMenuItem_Click; // - // исполнителиToolStripMenuItem + // buttonAddPlaneInShop // - исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; - исполнителиToolStripMenuItem.Size = new Size(180, 22); - исполнителиToolStripMenuItem.Text = "Исполнители"; - исполнителиToolStripMenuItem.Click += исполнителиToolStripMenuItem_Click; + buttonAddPlaneInShop.Location = new Point(822, 210); + buttonAddPlaneInShop.Name = "buttonAddPlaneInShop"; + buttonAddPlaneInShop.Size = new Size(150, 50); + buttonAddPlaneInShop.TabIndex = 7; + buttonAddPlaneInShop.Text = "Добавить изделие\r\nв магазин"; + buttonAddPlaneInShop.UseVisualStyleBackColor = true; + buttonAddPlaneInShop.Click += buttonAddPlaneInShop_Click; + // + // buttonSellPlanes + // + buttonSellPlanes.Location = new Point(822, 266); + buttonSellPlanes.Name = "buttonSellPlanes"; + buttonSellPlanes.Size = new Size(150, 23); + buttonSellPlanes.TabIndex = 8; + buttonSellPlanes.Text = "Продать изделия"; + buttonSellPlanes.UseVisualStyleBackColor = true; + buttonSellPlanes.Click += buttonSellPlanes_Click; + // + // почтаToolStripMenuItem + // + почтаToolStripMenuItem.Name = "почтаToolStripMenuItem"; + почтаToolStripMenuItem.Size = new Size(53, 20); + почтаToolStripMenuItem.Text = "Почта"; + почтаToolStripMenuItem.Click += почтаToolStripMenuItem_Click; // // FormMain // @@ -278,5 +282,6 @@ private ToolStripMenuItem клиентыToolStripMenuItem; private ToolStripMenuItem запускРаботToolStripMenuItem; private ToolStripMenuItem исполнителиToolStripMenuItem; + private ToolStripMenuItem почтаToolStripMenuItem; } } \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantView/FormMain.cs b/AircraftPlant/AircraftPlantView/FormMain.cs index 7d074e9..0c57ca9 100644 --- a/AircraftPlant/AircraftPlantView/FormMain.cs +++ b/AircraftPlant/AircraftPlantView/FormMain.cs @@ -232,6 +232,20 @@ namespace AircraftPlantView 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/AircraftPlant/AircraftPlantView/FormMessage.Designer.cs b/AircraftPlant/AircraftPlantView/FormMessage.Designer.cs new file mode 100644 index 0000000..019fedc --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormMessage.Designer.cs @@ -0,0 +1,118 @@ +namespace AircraftPlantView +{ + partial class FormMessage + { + /// + /// 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() + { + labelSubject = new Label(); + textBoxSubject = new TextBox(); + textBoxBody = new TextBox(); + labelBody = new Label(); + buttonSend = new Button(); + buttonCancel = new Button(); + SuspendLayout(); + // + // labelSubject + // + labelSubject.AutoSize = true; + labelSubject.Location = new Point(12, 15); + labelSubject.Name = "labelSubject"; + labelSubject.Size = new Size(68, 15); + labelSubject.TabIndex = 0; + labelSubject.Text = "Заголовок:"; + // + // textBoxSubject + // + textBoxSubject.Location = new Point(90, 12); + textBoxSubject.Name = "textBoxSubject"; + textBoxSubject.Size = new Size(282, 23); + textBoxSubject.TabIndex = 1; + // + // textBoxBody + // + textBoxBody.Location = new Point(90, 41); + textBoxBody.Name = "textBoxBody"; + textBoxBody.Size = new Size(282, 23); + textBoxBody.TabIndex = 2; + // + // labelBody + // + labelBody.AutoSize = true; + labelBody.Location = new Point(12, 44); + labelBody.Name = "labelBody"; + labelBody.Size = new Size(39, 15); + labelBody.TabIndex = 3; + labelBody.Text = "Текст:"; + // + // buttonSend + // + buttonSend.Location = new Point(216, 76); + buttonSend.Name = "buttonSend"; + buttonSend.Size = new Size(75, 23); + buttonSend.TabIndex = 7; + buttonSend.Text = "Отправить"; + buttonSend.UseVisualStyleBackColor = true; + buttonSend.Click += buttonSend_Click; + // + // buttonCancel + // + buttonCancel.Location = new Point(297, 76); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(75, 23); + buttonCancel.TabIndex = 6; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += buttonCancel_Click; + // + // FormMessage + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(384, 111); + Controls.Add(buttonSend); + Controls.Add(buttonCancel); + Controls.Add(labelBody); + Controls.Add(textBoxBody); + Controls.Add(textBoxSubject); + Controls.Add(labelSubject); + Name = "FormMessage"; + Text = "Письмо"; + Load += FormMessage_Load; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Label labelSubject; + private TextBox textBoxSubject; + private TextBox textBoxBody; + private Label labelBody; + private Button buttonSend; + private Button buttonCancel; + } +} \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantView/FormMessage.cs b/AircraftPlant/AircraftPlantView/FormMessage.cs new file mode 100644 index 0000000..076fbe5 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormMessage.cs @@ -0,0 +1,142 @@ +using AircraftPlantBusinessLogic.MailWorker; +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.BusinessLogicsContracts; +using AircraftPlantContracts.SearchModels; +using AircraftPlantContracts.ViewModels; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace AircraftPlantView +{ + /// + /// Форма для отправки письма + /// + public partial class FormMessage : Form + { + /// + /// Логгер + /// + private readonly ILogger _logger; + + /// + /// Бизнес-логика для писем + /// + private readonly IMessageInfoLogic _messageLogic; + + /// + /// Бизнес-логика для отправки писем + /// + private readonly AbstractMailWorker _mailWorker; + + /// + /// Письмо + /// + private MessageInfoViewModel? _message; + + /// + /// Идентификатор сообщения + /// + public string MessageId { get; set; } = string.Empty; + + /// + /// Конструктор + /// + /// + /// + /// + public FormMessage(ILogger logger, IMessageInfoLogic messageLogic, AbstractMailWorker mailWorker) + { + InitializeComponent(); + + _logger = logger; + _messageLogic = messageLogic; + _mailWorker = mailWorker; + } + + /// + /// Загрузка данных + /// + /// + /// + private void FormMessage_Load(object sender, EventArgs e) + { + try + { + _message = _messageLogic.ReadElement(new MessageInfoSearchModel + { + MessageId = MessageId + }); + if (_message != null) + { + textBoxSubject.Text = _message.Subject; + textBoxBody.Text = _message.Reply; + if (!_message.IsChecked) + { + _messageLogic.Update(new MessageInfoBindingModel + { + MessageId = MessageId, + IsChecked = true, + Reply = _message.Reply + }); + } + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения собщения"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + /// + /// Кнопка "Отправить" + /// + /// + /// + private void buttonSend_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxBody.Text)) + { + MessageBox.Show("Заполните ответ", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + + _mailWorker.MailSendAsync(new() + { + MailAddress = _message!.SenderName, + Subject = _message.Subject, + Text = textBoxBody.Text, + }); + + _messageLogic.Update(new MessageInfoBindingModel + { + MessageId = MessageId, + IsChecked = true, + Reply = textBoxBody.Text + }); + + MessageBox.Show("Отправка прошла успешно", "Сообщение", MessageBoxButtons.OK); + DialogResult = DialogResult.OK; + Close(); + } + + /// + /// Кнопка "Отмена" + /// + /// + /// + private void buttonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } +} diff --git a/AircraftPlant/AircraftPlantView/FormMessage.resx b/AircraftPlant/AircraftPlantView/FormMessage.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormMessage.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/AircraftPlant/AircraftPlantView/Program.cs b/AircraftPlant/AircraftPlantView/Program.cs index 24d66fe..70d22c4 100644 --- a/AircraftPlant/AircraftPlantView/Program.cs +++ b/AircraftPlant/AircraftPlantView/Program.cs @@ -8,6 +8,8 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; using System; +using AircraftPlantBusinessLogic.MailWorker; +using AircraftPlantContracts.BindingModels; namespace AircraftPlantView { @@ -33,7 +35,30 @@ namespace AircraftPlantView ConfigureServices(services); _serviceProvider = services.BuildServiceProvider(); - Application.Run(_serviceProvider.GetRequiredService()); + // + 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, 60000); + } + catch (Exception ex) + { + var logger = _serviceProvider.GetService(); + logger?.LogError(ex, " "); + } + + Application.Run(_serviceProvider.GetRequiredService()); } /// @@ -54,6 +79,7 @@ namespace AircraftPlantView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -62,7 +88,10 @@ namespace AircraftPlantView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddSingleton(); services.AddTransient(); services.AddTransient(); @@ -86,6 +115,14 @@ namespace AircraftPlantView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); } + + /// + /// + /// + /// + private static void MailCheck(object obj) => ServiceProvider?.GetService()?.MailCheck(); } } \ No newline at end of file