diff --git a/AircraftPlant/AbstractShopListImplement/DataListSingleton.cs b/AircraftPlant/AbstractShopListImplement/DataListSingleton.cs index 362137c..d12e213 100644 --- a/AircraftPlant/AbstractShopListImplement/DataListSingleton.cs +++ b/AircraftPlant/AbstractShopListImplement/DataListSingleton.cs @@ -42,6 +42,11 @@ namespace AircraftPlantListImplement /// public List Implementers { get; set; } + /// + /// Список классов-моделей писем + /// + public List Messages { get; set; } + /// /// Конструктор /// @@ -52,6 +57,7 @@ namespace AircraftPlantListImplement Planes = new List(); Clients = new List(); Implementers = new List(); + Messages = new List(); } /// /// Получить ссылку на класс diff --git a/AircraftPlant/AbstractShopListImplement/Message.cs b/AircraftPlant/AbstractShopListImplement/Message.cs new file mode 100644 index 0000000..0a6857f --- /dev/null +++ b/AircraftPlant/AbstractShopListImplement/Message.cs @@ -0,0 +1,47 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.ViewModels; +using AircraftPlantDataModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantListImplement +{ + 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 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, + }; + } + public MessageInfoViewModel GetViewModel => new() + { + MessageId = MessageId, + ClientId = ClientId, + SenderName = SenderName, + DateDelivery = DateDelivery, + Subject = Subject, + Body = Body + }; + } +} \ No newline at end of file diff --git a/AircraftPlant/AbstractShopListImplement/MessageInfoStorage.cs b/AircraftPlant/AbstractShopListImplement/MessageInfoStorage.cs new file mode 100644 index 0000000..0492cf7 --- /dev/null +++ b/AircraftPlant/AbstractShopListImplement/MessageInfoStorage.cs @@ -0,0 +1,73 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.SearchModels; +using AircraftPlantContracts.StoragesContracts; +using AircraftPlantContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantListImplement +{ + 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) + { + return new(); + } + + foreach (var message in _source.Messages) + { + if (message.ClientId == model.ClientId) + { + result.Add(message.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; + } + } +} \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantBusinessLogic/AircraftPlantBusinessLogic.csproj b/AircraftPlant/AircraftPlantBusinessLogic/AircraftPlantBusinessLogic.csproj index 4315cef..79561e5 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 85bc219..879e9a9 100644 --- a/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/ClientLogic.cs +++ b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/ClientLogic.cs @@ -4,6 +4,7 @@ using AircraftPlantContracts.SearchModels; using AircraftPlantContracts.StoragesContracts; using AircraftPlantContracts.ViewModels; using Microsoft.Extensions.Logging; +using System.Text.RegularExpressions; using System; using System.Collections.Generic; using System.Linq; @@ -102,13 +103,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..9410e46 --- /dev/null +++ b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/MessageInfoLogic.cs @@ -0,0 +1,72 @@ +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; + } + } +} diff --git a/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/OrderLogic.cs b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/OrderLogic.cs index 27e9bbd..ee0439a 100644 --- a/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/OrderLogic.cs @@ -1,9 +1,11 @@ -using AircraftPlantContracts.BindingModels; +using AircraftPlantBusinessLogic.MailWorker; +using AircraftPlantContracts.BindingModels; using AircraftPlantContracts.BusinessLogicsContracts; using AircraftPlantContracts.SearchModels; using AircraftPlantContracts.StoragesContracts; using AircraftPlantContracts.ViewModels; using AircraftPlantDataModels.Enums; +using AircraftPlantDataModels.Models; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; @@ -30,16 +32,31 @@ namespace AircraftPlantBusinessLogic.BusinessLogics static readonly object locker = new(); + /// + /// Взаимодействие с хранилищем клиентов + /// + private readonly IClientStorage _clientStorage; + + /// + /// Бизнес-логика для отправки писем + /// + private readonly AbstractMailWorker _mailLogic; + /// /// Конструктор /// /// /// - public OrderLogic(ILogger logger, IOrderStorage orderStorage) + /// + /// + public OrderLogic(ILogger logger, IOrderStorage orderStorage, IClientStorage clientStorage, AbstractMailWorker mailLogic) { _logger = logger; _orderStorage = orderStorage; + _clientStorage = clientStorage; + _mailLogic = mailLogic; } + /// /// Получение списка /// @@ -59,6 +76,7 @@ namespace AircraftPlantBusinessLogic.BusinessLogics _logger.LogInformation("ReadList. Count:{Count}", list.Count); return list; } + /// /// Получение отдельной записи /// @@ -83,6 +101,7 @@ namespace AircraftPlantBusinessLogic.BusinessLogics _logger.LogInformation("ReadElement find. Id:{Id}", element.Id); return element; } + /// /// Создание заказа /// @@ -99,13 +118,17 @@ 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; } + /// /// Смена статуса заказа (Выполняется) /// @@ -119,6 +142,7 @@ namespace AircraftPlantBusinessLogic.BusinessLogics return StatusUpdate(model, OrderStatus.Выполняется); } } + /// /// Смена статуса заказа (Выдан) /// @@ -128,6 +152,7 @@ namespace AircraftPlantBusinessLogic.BusinessLogics { return StatusUpdate(model, OrderStatus.Выдан); } + /// /// Смена статуса заказа (Готов) /// @@ -137,6 +162,7 @@ namespace AircraftPlantBusinessLogic.BusinessLogics { return StatusUpdate(model, OrderStatus.Готов); } + /// /// Проверка модели заказа /// @@ -166,6 +192,7 @@ namespace AircraftPlantBusinessLogic.BusinessLogics } _logger.LogInformation("Order. OrderID:{Id}.Sum:{ Sum}. PlaneId: { PlaneId}", model.Id, model.Sum, model.PlaneId); } + /// /// Смена статуса заказа /// @@ -202,13 +229,57 @@ namespace AircraftPlantBusinessLogic.BusinessLogics { model.DateImplement = element.DateImplement; } + 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; } + + /// + /// Отправить письмо + /// + /// + 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 = $"Ваш заказ №{order.Id} от {order.DateCreate} на сумму {order.Sum} был принят!" + }; + } + else + { + mailModel = new MailSendInfoBindingModel + { + MailAddress = client.Email, + Subject = $"Order №{order.Id}", + Text = $"Заказ №{order.Id} изменен статус на {order.Status}" + }; + } + + _mailLogic.MailSendAsync(mailModel); + } } -} \ No newline at end of file +} diff --git a/AircraftPlant/AircraftPlantBusinessLogic/MailWorker/AbstractMailWorker.cs b/AircraftPlant/AircraftPlantBusinessLogic/MailWorker/AbstractMailWorker.cs new file mode 100644 index 0000000..94ac497 --- /dev/null +++ b/AircraftPlant/AircraftPlantBusinessLogic/MailWorker/AbstractMailWorker.cs @@ -0,0 +1,88 @@ +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 + { + protected string _mailLogin = string.Empty; + protected string _mailPassword = string.Empty; + protected string _smtpClientHost = string.Empty; + protected int _smtpClientPort; + protected string _popHost = string.Empty; + protected int _popPort; + private readonly IMessageInfoLogic _messageInfoLogic; + private readonly IClientLogic _clientLogic; + private readonly ILogger _logger; + 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..81bdf06 --- /dev/null +++ b/AircraftPlant/AircraftPlantBusinessLogic/MailWorker/MailKitWorker.cs @@ -0,0 +1,83 @@ +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 87d447f..3dcf428 100644 --- a/AircraftPlant/AircraftPlantClientApp/Controllers/HomeController.cs +++ b/AircraftPlant/AircraftPlantClientApp/Controllers/HomeController.cs @@ -139,5 +139,16 @@ namespace AircraftPlantClientApp.Controllers var prod = APIClient.GetRequest($"api/main/getplane?planeId={plane}"); return count * (prod?.Price ?? 1); } + + [HttpGet] + public IActionResult Mails() + { + if (APIClient.Client == null) + { + return Redirect("~/Home/Enter"); + } + + return View(APIClient.GetRequest>($"api/client/getmessages?clientId={APIClient.Client.Id}")); + } } } diff --git a/AircraftPlant/AircraftPlantClientApp/Views/Home/Mails.cshtml b/AircraftPlant/AircraftPlantClientApp/Views/Home/Mails.cshtml new file mode 100644 index 0000000..0b1fa57 --- /dev/null +++ b/AircraftPlant/AircraftPlantClientApp/Views/Home/Mails.cshtml @@ -0,0 +1,54 @@ +@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) +
+ } +
\ No newline at end of file diff --git a/AircraftPlant/AircraftPlantClientApp/Views/Shared/_Layout.cshtml b/AircraftPlant/AircraftPlantClientApp/Views/Shared/_Layout.cshtml index 9810ee9..33331b1 100644 --- a/AircraftPlant/AircraftPlantClientApp/Views/Shared/_Layout.cshtml +++ b/AircraftPlant/AircraftPlantClientApp/Views/Shared/_Layout.cshtml @@ -26,6 +26,9 @@ + diff --git a/AircraftPlant/AircraftPlantContracts»/BindingModels/MailConfigBindingModel.cs b/AircraftPlant/AircraftPlantContracts»/BindingModels/MailConfigBindingModel.cs new file mode 100644 index 0000000..b46d6af --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts»/BindingModels/MailConfigBindingModel.cs @@ -0,0 +1,18 @@ +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; + public string SmtpClientHost { get; set; } = string.Empty; + public int SmtpClientPort { get; set; } + public string PopHost { get; set; } = string.Empty; + public int PopPort { get; set; } + } +} diff --git a/AircraftPlant/AircraftPlantContracts»/BindingModels/MailSendInfoBindingModel.cs b/AircraftPlant/AircraftPlantContracts»/BindingModels/MailSendInfoBindingModel.cs new file mode 100644 index 0000000..c3de044 --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts»/BindingModels/MailSendInfoBindingModel.cs @@ -0,0 +1,15 @@ +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..538624b --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts»/BindingModels/MessageInfoBindingModel.cs @@ -0,0 +1,19 @@ +using AircraftPlantDataModels; +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; + } +} diff --git a/AircraftPlant/AircraftPlantContracts»/BusinessLogicsContracts/IMessageInfoLogic.cs b/AircraftPlant/AircraftPlantContracts»/BusinessLogicsContracts/IMessageInfoLogic.cs new file mode 100644 index 0000000..429aedb --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts»/BusinessLogicsContracts/IMessageInfoLogic.cs @@ -0,0 +1,18 @@ +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); + } +} diff --git a/AircraftPlant/AircraftPlantContracts»/SearchModels/MessageInfoSearchModel.cs b/AircraftPlant/AircraftPlantContracts»/SearchModels/MessageInfoSearchModel.cs new file mode 100644 index 0000000..0855874 --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts»/SearchModels/MessageInfoSearchModel.cs @@ -0,0 +1,14 @@ +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; } + } +} diff --git a/AircraftPlant/AircraftPlantContracts»/StoragesContracts/IMessageInfoStorage.cs b/AircraftPlant/AircraftPlantContracts»/StoragesContracts/IMessageInfoStorage.cs new file mode 100644 index 0000000..505cd6e --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts»/StoragesContracts/IMessageInfoStorage.cs @@ -0,0 +1,20 @@ +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); + } + +} diff --git a/AircraftPlant/AircraftPlantContracts»/ViewModels/MessageInfoViewModel.cs b/AircraftPlant/AircraftPlantContracts»/ViewModels/MessageInfoViewModel.cs new file mode 100644 index 0000000..b5c4d0c --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts»/ViewModels/MessageInfoViewModel.cs @@ -0,0 +1,24 @@ +using AircraftPlantDataModels; +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; + } +} \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantDataModels/IMessageInfoModel.cs b/AircraftPlant/AircraftPlantDataModels/IMessageInfoModel.cs new file mode 100644 index 0000000..10c0535 --- /dev/null +++ b/AircraftPlant/AircraftPlantDataModels/IMessageInfoModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantDataModels +{ + public interface IMessageInfoModel + { + string MessageId { get; } + int? ClientId { get; } + string SenderName { get; } + DateTime DateDelivery { get; } + string Subject { get; } + string Body { get; } + } +} diff --git a/AircraftPlant/AircraftPlantDatabaseImplement/AircraftPlantDatabase.cs b/AircraftPlant/AircraftPlantDatabaseImplement/AircraftPlantDatabase.cs index 550c374..2bc17e2 100644 --- a/AircraftPlant/AircraftPlantDatabaseImplement/AircraftPlantDatabase.cs +++ b/AircraftPlant/AircraftPlantDatabaseImplement/AircraftPlantDatabase.cs @@ -25,5 +25,6 @@ namespace AircraftPlantDatabaseImplement public virtual DbSet Orders { set; get; } public virtual DbSet Clients { set; get; } 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..b7f0e84 --- /dev/null +++ b/AircraftPlant/AircraftPlantDatabaseImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,62 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.SearchModels; +using AircraftPlantContracts.StoragesContracts; +using AircraftPlantContracts.ViewModels; +using AircraftPlantDatabaseImplement.Models; +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) + { + return new(); + } + + using var context = new AircraftPlantDatabase(); + 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; + } + } +} \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/20240507180516_MessageInfoCreate.Designer.cs b/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/20240507180516_MessageInfoCreate.Designer.cs new file mode 100644 index 0000000..a45f7b3 --- /dev/null +++ b/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/20240507180516_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("20240507180516_MessageInfoCreate")] + partial class MessageInfoCreate + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.17") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("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/20240507180516_MessageInfoCreate.cs b/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/20240507180516_MessageInfoCreate.cs new file mode 100644 index 0000000..c372add --- /dev/null +++ b/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/20240507180516_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/AircraftPlantDatabaseModelSnapshot.cs b/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/AircraftPlantDatabaseModelSnapshot.cs index d770153..043d3c7 100644 --- a/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/AircraftPlantDatabaseModelSnapshot.cs +++ b/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/AircraftPlantDatabaseModelSnapshot.cs @@ -94,6 +94,36 @@ 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("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") @@ -183,6 +213,15 @@ namespace AircraftPlantDatabaseImplement.Migrations 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") @@ -229,6 +268,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 6650939..31ea51f 100644 --- a/AircraftPlant/AircraftPlantDatabaseImplement/Models/Client.cs +++ b/AircraftPlant/AircraftPlantDatabaseImplement/Models/Client.cs @@ -22,6 +22,8 @@ namespace AircraftPlantDatabaseImplement.Models public string Password { get; set; } = string.Empty; [ForeignKey("ClientId")] public virtual List Orders { get; set; } = new(); + [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..3ca7d5e --- /dev/null +++ b/AircraftPlant/AircraftPlantDatabaseImplement/Models/Message.cs @@ -0,0 +1,54 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.ViewModels; +using AircraftPlantDataModels; +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; + 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, + }; + } + public MessageInfoViewModel GetViewModel => new() + { + MessageId = MessageId, + ClientId = ClientId, + SenderName = SenderName, + DateDelivery = DateDelivery, + Subject = Subject, + Body = Body + }; + } +} \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantFileImplement/DataFileSingleton.cs b/AircraftPlant/AircraftPlantFileImplement/DataFileSingleton.cs index 9f98dcd..b1c30ed 100644 --- a/AircraftPlant/AircraftPlantFileImplement/DataFileSingleton.cs +++ b/AircraftPlant/AircraftPlantFileImplement/DataFileSingleton.cs @@ -16,11 +16,13 @@ namespace AircraftPlantFileImplement private readonly string PlaneFileName = "Plane.xml"; private readonly string ClientFileName = "Client.xml"; private readonly string ImplementerFileName = "Implementer.xml"; + private readonly string MessageFileName = "Message.xml"; public List Components { get; private set; } public List Orders { get; private set; } public List Planes { get; private set; } public List Clients { get; set; } public List Implementers { get; set; } + public List Messages { get; set; } public static DataFileSingleton GetInstance() { if (instance == null) @@ -34,6 +36,7 @@ namespace AircraftPlantFileImplement public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement); public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", x => x.GetXElement); public void SaveImplementers() => SaveData(Implementers, ImplementerFileName, "Implementers", x => x.GetXElement); + public void SaveMessages() => SaveData(Messages, MessageFileName, "Messages", x => x.GetXElement); private DataFileSingleton() { Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!; @@ -41,6 +44,7 @@ namespace AircraftPlantFileImplement Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!; Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!; Implementers = LoadData(ImplementerFileName, "Implementer", x => Implementer.Create(x)!)!; + Messages = LoadData(MessageFileName, "Message", x => Message.Create(x)!)!; } private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) { diff --git a/AircraftPlant/AircraftPlantFileImplement/Message.cs b/AircraftPlant/AircraftPlantFileImplement/Message.cs new file mode 100644 index 0000000..a1e933e --- /dev/null +++ b/AircraftPlant/AircraftPlantFileImplement/Message.cs @@ -0,0 +1,72 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.ViewModels; +using AircraftPlantDataModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace AircraftPlantFileImplement +{ + 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 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, + }; + } + 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 + }; + } + public MessageInfoViewModel GetViewModel => new() + { + MessageId = MessageId, + ClientId = ClientId, + SenderName = SenderName, + DateDelivery = DateDelivery, + Subject = Subject, + Body = Body + }; + 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)); + } +} \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantFileImplement/MessageInfoStorage.cs b/AircraftPlant/AircraftPlantFileImplement/MessageInfoStorage.cs new file mode 100644 index 0000000..aedf3de --- /dev/null +++ b/AircraftPlant/AircraftPlantFileImplement/MessageInfoStorage.cs @@ -0,0 +1,62 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.SearchModels; +using AircraftPlantContracts.StoragesContracts; +using AircraftPlantContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantFileImplement +{ + 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) + { + return new(); + } + + 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; + } + } +} diff --git a/AircraftPlant/AircraftPlantRestApi/Controllers/ClientController.cs b/AircraftPlant/AircraftPlantRestApi/Controllers/ClientController.cs index 0a57023..a3412dd 100644 --- a/AircraftPlant/AircraftPlantRestApi/Controllers/ClientController.cs +++ b/AircraftPlant/AircraftPlantRestApi/Controllers/ClientController.cs @@ -12,11 +12,12 @@ namespace AircraftPlantRestApi.Controllers { private readonly ILogger _logger; private readonly IClientLogic _logic; - public ClientController(IClientLogic logic, ILogger - logger) + private readonly IMessageInfoLogic _mailLogic; + public ClientController(IClientLogic logic, IMessageInfoLogic mailLogic, ILogger logger) { _logger = logger; _logic = logic; + _mailLogic = mailLogic; } [HttpGet] public ClientViewModel? Login(string login, string password) @@ -61,6 +62,22 @@ namespace AircraftPlantRestApi.Controllers throw; } } + [HttpGet] + public List? GetMessages(int clientId) + { + try + { + return _mailLogic.ReadList(new MessageInfoSearchModel + { + ClientId = clientId + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения писем клиента"); + throw; + } + } } } diff --git a/AircraftPlant/AircraftPlantRestApi/Program.cs b/AircraftPlant/AircraftPlantRestApi/Program.cs index 677f5b7..fb56e67 100644 --- a/AircraftPlant/AircraftPlantRestApi/Program.cs +++ b/AircraftPlant/AircraftPlantRestApi/Program.cs @@ -1,3 +1,5 @@ +using AircraftPlantBusinessLogic.MailWorker; +using AircraftPlantContracts.BindingModels; using AircraftPlantBusinessLogic.BusinessLogics; using AircraftPlantContracts.BusinessLogicsContracts; using AircraftPlantContracts.StoragesContracts; @@ -14,11 +16,15 @@ 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 @@ -30,6 +36,16 @@ 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..5323dbd 100644 --- a/AircraftPlant/AircraftPlantRestApi/appsettings.json +++ b/AircraftPlant/AircraftPlantRestApi/appsettings.json @@ -5,5 +5,11 @@ "Microsoft.AspNetCore": "Warning" } }, - "AllowedHosts": "*" -} + "AllowedHosts": "*", + "SmtpClientHost": "smtp.gmail.com", + "SmtpClientPort": "587", + "PopHost": "pop.gmail.com", + "PopPort": "995", + "MailLogin": "forstudy0934@gmail.com", + "MailPassword": "dtdx jawi xagv ynsz" +} \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantView/App.config b/AircraftPlant/AircraftPlantView/App.config new file mode 100644 index 0000000..b725c81 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/App.config @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantView/FormMails.Designer.cs b/AircraftPlant/AircraftPlantView/FormMails.Designer.cs new file mode 100644 index 0000000..c147703 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormMails.Designer.cs @@ -0,0 +1,73 @@ +namespace AircraftPlantView +{ + partial class FormMails + { + /// + /// 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(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // dataGridView + // + dataGridView.AllowUserToAddRows = false; + dataGridView.AllowUserToDeleteRows = false; + dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; + dataGridView.BackgroundColor = Color.White; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Dock = DockStyle.Left; + dataGridView.GridColor = Color.White; + dataGridView.Location = new Point(0, 0); + dataGridView.Margin = new Padding(3, 4, 3, 4); + dataGridView.MultiSelect = false; + dataGridView.Name = "dataGridView"; + dataGridView.ReadOnly = true; + dataGridView.RowHeadersVisible = false; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 25; + dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; + dataGridView.Size = new Size(671, 450); + dataGridView.TabIndex = 1; + // + // FormMails + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(671, 450); + Controls.Add(dataGridView); + Name = "FormMails"; + Text = "Письма"; + Load += this.FormMails_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView; + } +} \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantView/FormMails.cs b/AircraftPlant/AircraftPlantView/FormMails.cs new file mode 100644 index 0000000..3b44bd0 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormMails.cs @@ -0,0 +1,77 @@ +using AircraftPlantContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace AircraftPlantView +{ + /// + /// Форма для вывода писем + /// + public partial class FormMails : Form + { + /// + /// Логгер + /// + private readonly ILogger _logger; + + /// + /// Бизнес-логика для писем + /// + private readonly IMessageInfoLogic _logic; + + /// + /// Конструктор + /// + /// + /// + public FormMails(ILogger logger, IMessageInfoLogic logic) + { + InitializeComponent(); + + _logger = logger; + _logic = logic; + } + + /// + /// Загрузка писем + /// + /// + /// + private void FormMails_Load(object sender, EventArgs e) + { + LoadData(); + } + + /// + /// Метод загрузки писем + /// + private void LoadData() + { + try + { + var list = _logic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["MessageId"].Visible = false; + dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + _logger.LogInformation("Загрузка писем"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки писем"); + MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } +} diff --git a/AircraftPlant/AircraftPlantView/FormMails.resx b/AircraftPlant/AircraftPlantView/FormMails.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormMails.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 1293d22..6540ec9 100644 --- a/AircraftPlant/AircraftPlantView/FormMain.Designer.cs +++ b/AircraftPlant/AircraftPlantView/FormMain.Designer.cs @@ -43,6 +43,7 @@ компонентыПоИзделиямToolStripMenuItem = new ToolStripMenuItem(); списокЗаказовToolStripMenuItem = new ToolStripMenuItem(); запускРаботToolStripMenuItem = new ToolStripMenuItem(); + почтаToolStripMenuItem = new ToolStripMenuItem(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); menuStrip1.SuspendLayout(); SuspendLayout(); @@ -104,7 +105,7 @@ // menuStrip1 // menuStrip1.ImageScalingSize = new Size(20, 20); - menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчётыToolStripMenuItem, запускРаботToolStripMenuItem }); + menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчётыToolStripMenuItem, запускРаботToolStripMenuItem, почтаToolStripMenuItem }); menuStrip1.Location = new Point(0, 0); menuStrip1.Name = "menuStrip1"; menuStrip1.Padding = new Padding(7, 3, 0, 3); @@ -122,28 +123,28 @@ // компонентыToolStripMenuItem // компонентыToolStripMenuItem.Name = "компонентыToolStripMenuItem"; - компонентыToolStripMenuItem.Size = new Size(224, 26); + компонентыToolStripMenuItem.Size = new Size(185, 26); компонентыToolStripMenuItem.Text = "Компоненты"; компонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click; // // изделияToolStripMenuItem // изделияToolStripMenuItem.Name = "изделияToolStripMenuItem"; - изделияToolStripMenuItem.Size = new Size(224, 26); + изделияToolStripMenuItem.Size = new Size(185, 26); изделияToolStripMenuItem.Text = "Изделия"; изделияToolStripMenuItem.Click += ИзделияToolStripMenuItem_Click; // // клиентыToolStripMenuItem // клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; - клиентыToolStripMenuItem.Size = new Size(224, 26); + клиентыToolStripMenuItem.Size = new Size(185, 26); клиентыToolStripMenuItem.Text = "Клиенты"; клиентыToolStripMenuItem.Click += КлиентыToolStripMenuItem_Click; // // исполнителиToolStripMenuItem // исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; - исполнителиToolStripMenuItem.Size = new Size(224, 26); + исполнителиToolStripMenuItem.Size = new Size(185, 26); исполнителиToolStripMenuItem.Text = "Исполнители"; исполнителиToolStripMenuItem.Click += ИсполнителиToolStripMenuItem_Click; // @@ -182,6 +183,13 @@ запускРаботToolStripMenuItem.Text = "Запуск работ"; запускРаботToolStripMenuItem.Click += ЗапускРаботToolStripMenuItem_Click; // + // почтаToolStripMenuItem + // + почтаToolStripMenuItem.Name = "почтаToolStripMenuItem"; + почтаToolStripMenuItem.Size = new Size(65, 24); + почтаToolStripMenuItem.Text = "Почта"; + почтаToolStripMenuItem.Click += ПочтаToolStripMenuItem_Click; + // // FormMain // AutoScaleDimensions = new SizeF(8F, 20F); @@ -221,5 +229,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 607bf87..0c1dd7a 100644 --- a/AircraftPlant/AircraftPlantView/FormMain.cs +++ b/AircraftPlant/AircraftPlantView/FormMain.cs @@ -111,12 +111,31 @@ namespace AircraftPlantView } } + /// + /// Запуск имитации работы исполнителей + /// + /// + /// private void ЗапускРаботToolStripMenuItem_Click(object sender, EventArgs e) { _workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic )) as IImplementerLogic)!, _orderLogic); MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); } + /// + /// Посмотреть письма + /// + /// + /// + private void ПочтаToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormMails)); + if (service is FormMails form) + { + form.ShowDialog(); + } + } + /// /// Кнопка "Создать заказ" /// diff --git a/AircraftPlant/AircraftPlantView/Program.cs b/AircraftPlant/AircraftPlantView/Program.cs index 58df76e..ea40c46 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,6 +35,29 @@ namespace AircraftPlantView ConfigureServices(services); _serviceProvider = services.BuildServiceProvider(); + try + { + var mailSender = + _serviceProvider.GetService(); + mailSender?.MailConfig(new MailConfigBindingModel + { + MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty, + MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty, + SmtpClientHost = System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty, + SmtpClientPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]), + PopHost = System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty, + PopPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"]) + }); + // + var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000); + } + catch (Exception ex) + { + var logger = _serviceProvider.GetService(); + logger?.LogError(ex, " "); + } + + Application.Run(_serviceProvider.GetRequiredService()); } @@ -53,6 +78,8 @@ namespace AircraftPlantView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); services.AddTransient(); @@ -60,7 +87,10 @@ namespace AircraftPlantView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddSingleton(); services.AddTransient(); services.AddTransient(); @@ -78,6 +108,8 @@ namespace AircraftPlantView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); } + private static void MailCheck(object obj) => ServiceProvider?.GetService()?.MailCheck(); } } \ No newline at end of file