From aa2a70b80c57ba77d7f8726a47745f28235a5631 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=BE=D1=84=D1=8C=D1=8F=20=D0=AF=D0=BA=D0=BE=D0=B1?= =?UTF-8?q?=D1=87=D1=83=D0=BA?= Date: Sat, 25 May 2024 22:14:50 +0400 Subject: [PATCH] =?UTF-8?q?=D0=B3=D0=BE=D1=82=D0=BE=D0=B2=D0=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractMailWorker.cs | 85 +++++ .../MotorPlantBusinessLogic/ClientLogic.cs | 11 +- .../MotorPlantBusinessLogic/MailKitWorker.cs | 84 +++++ .../MessageInfoLogic.cs | 48 +++ .../MotorPlantBusinessLogic.csproj | 2 + .../MotorPlantBusinessLogic/OrderLogic.cs | 34 +- .../Controllers/HomeController.cs | 11 + .../Views/Home/Mails.cshtml | 54 ++++ .../Views/Shared/_Layout.cshtml | 3 + .../BindingModels/MailConfigBindingModel.cs | 18 ++ .../BindingModels/MailSendInfoBindingModel.cs | 15 + .../BindingModels/MessageInfoBindingModel.cs | 19 ++ .../IMessageInfoLogic.cs | 17 + .../SearchModels/MessageInfoSearchModel.cs | 14 + .../StoragesContracts/IMessageInfoStorage.cs | 19 ++ .../ViewModels/MessageInfoViewModel.cs | 24 ++ .../MotorPlantDataModels/IMessageInfoModel.cs | 19 ++ .../MessageInfo.cs | 50 +++ .../MessageInfoStorage.cs | 54 ++++ .../20240525181417_InitialCreate4.Designer.cs | 296 ++++++++++++++++++ .../20240525181417_InitialCreate4.cs | 48 +++ .../MotorPlantDataBaseModelSnapshot.cs | 39 +++ .../MotorPlantDataBase.cs | 1 + .../DataFileSingleton.cs | 4 + .../MotorPlantFileImplement/MessageInfo.cs | 71 +++++ .../MessageInfoStorage.cs | 54 ++++ .../DataListSingleton.cs | 2 + .../MotorPlantListImplement/MessageInfo.cs | 46 +++ .../MessageInfoStorage.cs | 64 ++++ .../Controllers/ClientController.cs | 20 +- MotorPlant/MotorPlantRestApi/Program.cs | 25 ++ MotorPlant/MotorPlantRestApi/appsettings.json | 9 +- MotorPlant/MotorPlantView/App.config | 11 + .../MotorPlantView/FormMain.Designer.cs | 11 +- MotorPlant/MotorPlantView/FormMain.cs | 10 + .../MotorPlantView/FormViewMail.Designer.cs | 62 ++++ MotorPlant/MotorPlantView/FormViewMail.cs | 47 +++ MotorPlant/MotorPlantView/FormViewMail.resx | 120 +++++++ MotorPlant/MotorPlantView/Program.cs | 44 ++- 39 files changed, 1555 insertions(+), 10 deletions(-) create mode 100644 MotorPlant/MotorPlantBusinessLogic/AbstractMailWorker.cs create mode 100644 MotorPlant/MotorPlantBusinessLogic/MailKitWorker.cs create mode 100644 MotorPlant/MotorPlantBusinessLogic/MessageInfoLogic.cs create mode 100644 MotorPlant/MotorPlantClientApp/Views/Home/Mails.cshtml create mode 100644 MotorPlant/MotorPlantContracts/BindingModels/MailConfigBindingModel.cs create mode 100644 MotorPlant/MotorPlantContracts/BindingModels/MailSendInfoBindingModel.cs create mode 100644 MotorPlant/MotorPlantContracts/BindingModels/MessageInfoBindingModel.cs create mode 100644 MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IMessageInfoLogic.cs create mode 100644 MotorPlant/MotorPlantContracts/SearchModels/MessageInfoSearchModel.cs create mode 100644 MotorPlant/MotorPlantContracts/StoragesContracts/IMessageInfoStorage.cs create mode 100644 MotorPlant/MotorPlantContracts/ViewModels/MessageInfoViewModel.cs create mode 100644 MotorPlant/MotorPlantDataModels/IMessageInfoModel.cs create mode 100644 MotorPlant/MotorPlantDatabaseImplement/MessageInfo.cs create mode 100644 MotorPlant/MotorPlantDatabaseImplement/MessageInfoStorage.cs create mode 100644 MotorPlant/MotorPlantDatabaseImplement/Migrations/20240525181417_InitialCreate4.Designer.cs create mode 100644 MotorPlant/MotorPlantDatabaseImplement/Migrations/20240525181417_InitialCreate4.cs create mode 100644 MotorPlant/MotorPlantFileImplement/MessageInfo.cs create mode 100644 MotorPlant/MotorPlantFileImplement/MessageInfoStorage.cs create mode 100644 MotorPlant/MotorPlantListImplement/MessageInfo.cs create mode 100644 MotorPlant/MotorPlantListImplement/MessageInfoStorage.cs create mode 100644 MotorPlant/MotorPlantView/App.config create mode 100644 MotorPlant/MotorPlantView/FormViewMail.Designer.cs create mode 100644 MotorPlant/MotorPlantView/FormViewMail.cs create mode 100644 MotorPlant/MotorPlantView/FormViewMail.resx diff --git a/MotorPlant/MotorPlantBusinessLogic/AbstractMailWorker.cs b/MotorPlant/MotorPlantBusinessLogic/AbstractMailWorker.cs new file mode 100644 index 0000000..f6cf0f0 --- /dev/null +++ b/MotorPlant/MotorPlantBusinessLogic/AbstractMailWorker.cs @@ -0,0 +1,85 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantBusinessLogic.MailWorker +{ + public abstract class AbstractMailWorker + { + protected string _mailLogin = string.Empty; + protected string _mailPassword = string.Empty; + protected string _smtpClientHost = string.Empty; + protected int _smtpClientPort; + protected string _popHost = string.Empty; + protected int _popPort; + private readonly IMessageInfoLogic _messageInfoLogic; + private readonly ILogger _logger; + public AbstractMailWorker(ILogger logger, + IMessageInfoLogic messageInfoLogic) + { + _logger = logger; + _messageInfoLogic = messageInfoLogic; + } + public void MailConfig(MailConfigBindingModel config) + { + _mailLogin = config.MailLogin; + _mailPassword = config.MailPassword; + _smtpClientHost = config.SmtpClientHost; + _smtpClientPort = config.SmtpClientPort; + _popHost = config.PopHost; + _popPort = config.PopPort; + _logger.LogDebug("Config: {login}, {password}, {clientHost}, { clientPort}, { popHost}, { popPort}", _mailLogin, _mailPassword, _smtpClientHost, + _smtpClientPort, _popHost, _popPort); + } + public async void MailSendAsync(MailSendInfoBindingModel info) + { + if (string.IsNullOrEmpty(_mailLogin) || + string.IsNullOrEmpty(_mailPassword)) + { + return; + } + if (string.IsNullOrEmpty(_smtpClientHost) || _smtpClientPort == 0) + { + return; + } + if (string.IsNullOrEmpty(info.MailAddress) || + string.IsNullOrEmpty(info.Subject) || string.IsNullOrEmpty(info.Text)) + { + return; + } + _logger.LogDebug("Send Mail: {To}, {Subject}", info.MailAddress, + info.Subject); + await SendMailAsync(info); + } + public async void MailCheck() + { + if (string.IsNullOrEmpty(_mailLogin) || + string.IsNullOrEmpty(_mailPassword)) + { + return; + } + if (string.IsNullOrEmpty(_popHost) || _popPort == 0) + { + return; + } + if (_messageInfoLogic == null) + { + return; + } + var list = await ReceiveMailAsync(); + _logger.LogDebug("Check Mail: {Count} new mails", list.Count); + foreach (var mail in list) + { + _messageInfoLogic.Create(mail); + } + } + protected abstract Task SendMailAsync(MailSendInfoBindingModel info); + protected abstract Task> + ReceiveMailAsync(); + } +} diff --git a/MotorPlant/MotorPlantBusinessLogic/ClientLogic.cs b/MotorPlant/MotorPlantBusinessLogic/ClientLogic.cs index 4736a12..ed11cd8 100644 --- a/MotorPlant/MotorPlantBusinessLogic/ClientLogic.cs +++ b/MotorPlant/MotorPlantBusinessLogic/ClientLogic.cs @@ -10,6 +10,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using System.Text.RegularExpressions; namespace MotorPlantBusinessLogic.BusinessLogic { @@ -102,13 +103,21 @@ namespace MotorPlantBusinessLogic.BusinessLogic if (string.IsNullOrEmpty(model.Email)) { throw new ArgumentNullException("Нет Email клиента", - nameof(model.ClientFIO)); + nameof(model.Email)); } if (string.IsNullOrEmpty(model.Password)) { throw new ArgumentNullException("Нет пароля клиента", nameof(model.ClientFIO)); } + if (!Regex.IsMatch(model.Email, @"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$")) + { + throw new ArgumentException("Некорретно введен email клиента", nameof(model.Email)); + } + if (!Regex.IsMatch(model.Password, @"^(?=.*\d)(?=.*\W)(?=.*[^\d\s]).+$")) + { + throw new ArgumentException("Некорректно введен пароль клиента", nameof(model.Password)); + } _logger.LogInformation("Client. ClientFIO:{ClientFIO}." + "Email:{ Email}. Password:{ Password}. Id: { Id} ", model.ClientFIO, model.Email, model.Password, model.Id); var element = _clientStorage.GetElement(new ClientSearchModel diff --git a/MotorPlant/MotorPlantBusinessLogic/MailKitWorker.cs b/MotorPlant/MotorPlantBusinessLogic/MailKitWorker.cs new file mode 100644 index 0000000..7e04f61 --- /dev/null +++ b/MotorPlant/MotorPlantBusinessLogic/MailKitWorker.cs @@ -0,0 +1,84 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.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 MailKit.Net.Pop3; +using MailKit.Security; +using System.Threading.Tasks; + +namespace MotorPlantBusinessLogic.MailWorker +{ + public class MailKitWorker : AbstractMailWorker + { + public MailKitWorker(ILogger logger, IMessageInfoLogic + messageInfoLogic) : base(logger, messageInfoLogic) { } + protected override async Task SendMailAsync(MailSendInfoBindingModel + info) + { + using var objMailMessage = new MailMessage(); + using var objSmtpClient = new SmtpClient(_smtpClientHost, + _smtpClientPort); + try + { + objMailMessage.From = new MailAddress(_mailLogin); + objMailMessage.To.Add(new MailAddress(info.MailAddress)); + objMailMessage.Subject = info.Subject; + objMailMessage.Body = info.Text; + objMailMessage.SubjectEncoding = Encoding.UTF8; + objMailMessage.BodyEncoding = Encoding.UTF8; + objSmtpClient.UseDefaultCredentials = false; + objSmtpClient.EnableSsl = true; + objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; + objSmtpClient.Credentials = new NetworkCredential(_mailLogin, + _mailPassword); + await Task.Run(() => objSmtpClient.Send(objMailMessage)); + } + catch (Exception) + { + throw; + } + } + protected override async Task> + ReceiveMailAsync() + { + var list = new List(); + using var client = new Pop3Client(); + await Task.Run(() => + { + try + { + client.Connect(_popHost, _popPort, + SecureSocketOptions.SslOnConnect); + client.Authenticate(_mailLogin, _mailPassword); + for (int i = 0; i < client.Count; i++) + { + var message = client.GetMessage(i); + foreach (var mail in message.From.Mailboxes) + { + list.Add(new MessageInfoBindingModel + { + DateDelivery = message.Date.DateTime, + MessageId = message.MessageId, + SenderName = mail.Address, + Subject = message.Subject, + Body = message.TextBody + }); + } + } + } + catch (MailKit.Security.AuthenticationException) + { } + finally + { + client.Disconnect(true); + } + }); + return list; + } + } +} diff --git a/MotorPlant/MotorPlantBusinessLogic/MessageInfoLogic.cs b/MotorPlant/MotorPlantBusinessLogic/MessageInfoLogic.cs new file mode 100644 index 0000000..591df52 --- /dev/null +++ b/MotorPlant/MotorPlantBusinessLogic/MessageInfoLogic.cs @@ -0,0 +1,48 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.BusinessLogicsContracts; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.StoragesContracts; +using MotorPlantContracts.ViewModels; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantBusinessLogic.BusinessLogic +{ + public class MessageInfoLogic : IMessageInfoLogic + { + private readonly ILogger _logger; + private readonly IMessageInfoStorage _messageInfoStorage; + public MessageInfoLogic(ILogger logger, IMessageInfoStorage MessageInfoStorage) + { + _logger = logger; + _messageInfoStorage = MessageInfoStorage; + } + + public bool Create(MessageInfoBindingModel model) + { + if (_messageInfoStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } + + public List? ReadList(MessageInfoSearchModel? model) + { + _logger.LogInformation("ReadList. MessageId:{MessageId}.ClientId:{ClientId} ", model?.MessageId, model?.ClientId); + var list = (model == null) ? _messageInfoStorage.GetFullList() : _messageInfoStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + _logger.LogInformation("ReadList. Count:{Count}", list.Count); + return list; + } + } +} diff --git a/MotorPlant/MotorPlantBusinessLogic/MotorPlantBusinessLogic.csproj b/MotorPlant/MotorPlantBusinessLogic/MotorPlantBusinessLogic.csproj index 83215cb..c48f692 100644 --- a/MotorPlant/MotorPlantBusinessLogic/MotorPlantBusinessLogic.csproj +++ b/MotorPlant/MotorPlantBusinessLogic/MotorPlantBusinessLogic.csproj @@ -8,6 +8,7 @@ + @@ -20,6 +21,7 @@ + diff --git a/MotorPlant/MotorPlantBusinessLogic/OrderLogic.cs b/MotorPlant/MotorPlantBusinessLogic/OrderLogic.cs index d9afaf6..51dd370 100644 --- a/MotorPlant/MotorPlantBusinessLogic/OrderLogic.cs +++ b/MotorPlant/MotorPlantBusinessLogic/OrderLogic.cs @@ -5,6 +5,7 @@ using MotorPlantContracts.StoragesContracts; using MotorPlantContracts.ViewModels; using Microsoft.Extensions.Logging; using MotorPlantDataModels.Enums; +using MotorPlantBusinessLogic.MailWorker; namespace MotorPlantBusinessLogic.BusinessLogics { @@ -12,11 +13,15 @@ namespace MotorPlantBusinessLogic.BusinessLogics { private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; + private readonly AbstractMailWorker _mailWorker; + private readonly IClientLogic _clientLogic; static readonly object locker = new object(); - public OrderLogic(ILogger logger, IOrderStorage orderStorage) + public OrderLogic(ILogger logger, IOrderStorage orderStorage, AbstractMailWorker mailWorker, IClientLogic clientLogic) { _logger = logger; _orderStorage = orderStorage; + _mailWorker = mailWorker; + _clientLogic = clientLogic; } public OrderViewModel? ReadElement(OrderSearchModel model) { @@ -55,12 +60,14 @@ namespace MotorPlantBusinessLogic.BusinessLogics if (model.Status != OrderStatus.Неизвестен) return false; model.Status = OrderStatus.Принят; + var res = _orderStorage.Insert(model); - if (_orderStorage.Insert(model) == null) + if (res == null) { _logger.LogWarning("Insert operation failed"); return false; } + SendOrderStatusMail(model.ClientId, $"Изменен статус заказа #{res.Id}", $"Заказ #{res.Id} изменен статус на {model.Status}"); return true; } @@ -100,7 +107,13 @@ namespace MotorPlantBusinessLogic.BusinessLogics if (model.Status == OrderStatus.Готов) model.DateImplement = DateTime.Now; if (element.ImplementerId.HasValue) model.ImplementerId = element.ImplementerId; - _orderStorage.Update(model); + var result = _orderStorage.Update(model); + if (result == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + SendOrderStatusMail(result.ClientId, $"Изменен статус заказа #{result.Id}", $"Заказ #{model.Id} изменен статус на {result.Status}"); return true; } @@ -124,5 +137,20 @@ namespace MotorPlantBusinessLogic.BusinessLogics } _logger.LogInformation("Engine. EngineId:{EngineId}.Count:{Count}.Sum:{Sum}Id:{Id}", model.EngineId, model.Count, model.Sum, model.Id); } + private bool SendOrderStatusMail(int clientId, string subject, string text) + { + var client = _clientLogic.ReadElement(new() { Id = clientId }); + if (client == null) + { + return false; + } + _mailWorker.MailSendAsync(new() + { + MailAddress = client.Email, + Subject = subject, + Text = text + }); + return true; + } } } diff --git a/MotorPlant/MotorPlantClientApp/Controllers/HomeController.cs b/MotorPlant/MotorPlantClientApp/Controllers/HomeController.cs index 5c44e2f..7dc98df 100644 --- a/MotorPlant/MotorPlantClientApp/Controllers/HomeController.cs +++ b/MotorPlant/MotorPlantClientApp/Controllers/HomeController.cs @@ -113,6 +113,7 @@ namespace MotorPlantClientApp.Controllers [HttpGet] public IActionResult Create() { + var res = APIClient.GetRequest>("api/main/getEnginelist"); ViewBag.Engines = APIClient.GetRequest>("api/main/getEnginelist"); return View(); @@ -146,5 +147,15 @@ namespace MotorPlantClientApp.Controllers ); return Math.Round(count * (_Engine?.Price ?? 1), 2); } + [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/MotorPlant/MotorPlantClientApp/Views/Home/Mails.cshtml b/MotorPlant/MotorPlantClientApp/Views/Home/Mails.cshtml new file mode 100644 index 0000000..fcce2c6 --- /dev/null +++ b/MotorPlant/MotorPlantClientApp/Views/Home/Mails.cshtml @@ -0,0 +1,54 @@ +@using MotorPlantContracts.ViewModels + +@model List + +@{ + ViewData["Title"] = "Mails"; +} + +
+

Заказы

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

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

+ return; + } + + + + + + + + + + + @foreach (var item in Model) + { + + + + + + } + +
+ Дата письма + + Заголовок + + Текст +
+ @Html.DisplayFor(modelItem => item.DateDelivery) + + @Html.DisplayFor(modelItem => item.Subject) + + @Html.DisplayFor(modelItem => item.Body) +
+ } +
\ No newline at end of file diff --git a/MotorPlant/MotorPlantClientApp/Views/Shared/_Layout.cshtml b/MotorPlant/MotorPlantClientApp/Views/Shared/_Layout.cshtml index c2c4a00..009c2f8 100644 --- a/MotorPlant/MotorPlantClientApp/Views/Shared/_Layout.cshtml +++ b/MotorPlant/MotorPlantClientApp/Views/Shared/_Layout.cshtml @@ -25,6 +25,9 @@ + diff --git a/MotorPlant/MotorPlantContracts/BindingModels/MailConfigBindingModel.cs b/MotorPlant/MotorPlantContracts/BindingModels/MailConfigBindingModel.cs new file mode 100644 index 0000000..984f565 --- /dev/null +++ b/MotorPlant/MotorPlantContracts/BindingModels/MailConfigBindingModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.BindingModels +{ + public class MailConfigBindingModel + { + public string MailLogin { get; set; } = string.Empty; + public string MailPassword { get; set; } = string.Empty; + public string SmtpClientHost { get; set; } = string.Empty; + public int SmtpClientPort { get; set; } + public string PopHost { get; set; } = string.Empty; + public int PopPort { get; set; } + } +} diff --git a/MotorPlant/MotorPlantContracts/BindingModels/MailSendInfoBindingModel.cs b/MotorPlant/MotorPlantContracts/BindingModels/MailSendInfoBindingModel.cs new file mode 100644 index 0000000..a7594a0 --- /dev/null +++ b/MotorPlant/MotorPlantContracts/BindingModels/MailSendInfoBindingModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.BindingModels +{ + public class MailSendInfoBindingModel + { + public string MailAddress { get; set; } = string.Empty; + public string Subject { get; set; } = string.Empty; + public string Text { get; set; } = string.Empty; + } +} diff --git a/MotorPlant/MotorPlantContracts/BindingModels/MessageInfoBindingModel.cs b/MotorPlant/MotorPlantContracts/BindingModels/MessageInfoBindingModel.cs new file mode 100644 index 0000000..a940c2a --- /dev/null +++ b/MotorPlant/MotorPlantContracts/BindingModels/MessageInfoBindingModel.cs @@ -0,0 +1,19 @@ +using MotorPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.BindingModels +{ + public class MessageInfoBindingModel : IMessageInfoModel + { + public string MessageId { get; set; } = string.Empty; + public int? ClientId { get; set; } + public string SenderName { get; set; } = string.Empty; + public string Subject { get; set; } = string.Empty; + public string Body { get; set; } = string.Empty; + public DateTime DateDelivery { get; set; } + } +} diff --git a/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IMessageInfoLogic.cs b/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IMessageInfoLogic.cs new file mode 100644 index 0000000..5e46abf --- /dev/null +++ b/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IMessageInfoLogic.cs @@ -0,0 +1,17 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.BusinessLogicsContracts +{ + public interface IMessageInfoLogic + { + List? ReadList(MessageInfoSearchModel? model); + bool Create(MessageInfoBindingModel model); + } +} diff --git a/MotorPlant/MotorPlantContracts/SearchModels/MessageInfoSearchModel.cs b/MotorPlant/MotorPlantContracts/SearchModels/MessageInfoSearchModel.cs new file mode 100644 index 0000000..0e97565 --- /dev/null +++ b/MotorPlant/MotorPlantContracts/SearchModels/MessageInfoSearchModel.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.SearchModels +{ + public class MessageInfoSearchModel + { + public int? ClientId { get; set; } + public string? MessageId { get; set; } + } +} diff --git a/MotorPlant/MotorPlantContracts/StoragesContracts/IMessageInfoStorage.cs b/MotorPlant/MotorPlantContracts/StoragesContracts/IMessageInfoStorage.cs new file mode 100644 index 0000000..8ecd007 --- /dev/null +++ b/MotorPlant/MotorPlantContracts/StoragesContracts/IMessageInfoStorage.cs @@ -0,0 +1,19 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.StoragesContracts +{ + public interface IMessageInfoStorage + { + List GetFullList(); + List GetFilteredList(MessageInfoSearchModel model); + MessageInfoViewModel? GetElement(MessageInfoSearchModel model); + MessageInfoViewModel? Insert(MessageInfoBindingModel model); + } +} diff --git a/MotorPlant/MotorPlantContracts/ViewModels/MessageInfoViewModel.cs b/MotorPlant/MotorPlantContracts/ViewModels/MessageInfoViewModel.cs new file mode 100644 index 0000000..8d81661 --- /dev/null +++ b/MotorPlant/MotorPlantContracts/ViewModels/MessageInfoViewModel.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using MotorPlantDataModels.Models; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.ViewModels +{ + public class MessageInfoViewModel : IMessageInfoModel + { + public string MessageId { get; set; } = string.Empty; + public int? ClientId { get; set; } + [DisplayName("Отправитель")] + public string SenderName { get; set; } = string.Empty; + [DisplayName("Дата письма")] + public DateTime DateDelivery { get; set; } + [DisplayName("Заголовок")] + public string Subject { get; set; } = string.Empty; + [DisplayName("Текст")] + public string Body { get; set; } = string.Empty; + } +} diff --git a/MotorPlant/MotorPlantDataModels/IMessageInfoModel.cs b/MotorPlant/MotorPlantDataModels/IMessageInfoModel.cs new file mode 100644 index 0000000..464672c --- /dev/null +++ b/MotorPlant/MotorPlantDataModels/IMessageInfoModel.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantDataModels.Models +{ + public interface IMessageInfoModel + { + string MessageId { get; } + int? ClientId { get; } + string SenderName { get; } + DateTime DateDelivery { get; } + string Subject { get; } + string Body { get; } + + } +} diff --git a/MotorPlant/MotorPlantDatabaseImplement/MessageInfo.cs b/MotorPlant/MotorPlantDatabaseImplement/MessageInfo.cs new file mode 100644 index 0000000..0a9bc4b --- /dev/null +++ b/MotorPlant/MotorPlantDatabaseImplement/MessageInfo.cs @@ -0,0 +1,50 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.ViewModels; +using MotorPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantDatabaseImplement.Models +{ + public class MessageInfo : IMessageInfoModel + { + [Key] + public string MessageId { get; private set; } = string.Empty; + public int? ClientId { get; private set; } + public string SenderName { get; private set; } = string.Empty; + public DateTime DateDelivery { get; private set; } = DateTime.Now; + public string Subject { get; private set; } = string.Empty; + public string Body { get; private set; } = string.Empty; + public Client? Client { get; private set; } + public static MessageInfo? Create(MotorPlantDataBase context, MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Subject = model.Subject, + ClientId = context.Clients.FirstOrDefault(x => x.Email == model.SenderName).Id, + Client = context.Clients.FirstOrDefault(x => x.Email == model.SenderName), + MessageId = model.MessageId, + SenderName = model.SenderName, + DateDelivery = model.DateDelivery, + }; + } + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Subject = Subject, + ClientId = ClientId, + MessageId = MessageId, + SenderName = SenderName, + DateDelivery = DateDelivery, + }; + } +} diff --git a/MotorPlant/MotorPlantDatabaseImplement/MessageInfoStorage.cs b/MotorPlant/MotorPlantDatabaseImplement/MessageInfoStorage.cs new file mode 100644 index 0000000..388825c --- /dev/null +++ b/MotorPlant/MotorPlantDatabaseImplement/MessageInfoStorage.cs @@ -0,0 +1,54 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.StoragesContracts; +using MotorPlantContracts.ViewModels; +using MotorPlantDatabaseImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantDatabaseImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + using var context = new MotorPlantDataBase(); + if (model.MessageId != null) + { + return context.Messages.FirstOrDefault(x => x.MessageId == model.MessageId)?.GetViewModel; + } + return null; + } + public List GetFilteredList(MessageInfoSearchModel model) + { + using var context = new MotorPlantDataBase(); + return context.Messages + .Where(x => x.ClientId == model.ClientId) + .Select(x => x.GetViewModel) + .ToList(); + } + public List GetFullList() + { + using var context = new MotorPlantDataBase(); + return context.Messages + .Select(x => x.GetViewModel) + .ToList(); + } + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + using var context = new MotorPlantDataBase(); + var newMessage = MessageInfo.Create(context, model); + if (newMessage == null || context.Messages.Any(x => x.MessageId.Equals(model.MessageId))) + { + return null; + } + context.Messages.Add(newMessage); + context.SaveChanges(); + return newMessage.GetViewModel; + } + } +} diff --git a/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240525181417_InitialCreate4.Designer.cs b/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240525181417_InitialCreate4.Designer.cs new file mode 100644 index 0000000..3bc1fd0 --- /dev/null +++ b/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240525181417_InitialCreate4.Designer.cs @@ -0,0 +1,296 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using MotorPlantDatabaseImplement; + +#nullable disable + +namespace MotorPlantDatabaseImplement.Migrations +{ + [DbContext(typeof(MotorPlantDataBase))] + [Migration("20240525181417_InitialCreate4")] + partial class InitialCreate4 + { + /// + 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("MotorPlantDatabaseImplement.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("MotorPlantDatabaseImplement.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("MotorPlantDatabaseImplement.Models.Engine", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("EngineName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Price") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.ToTable("Engines"); + }); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.EngineComponent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ComponentId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("EngineId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ComponentId"); + + b.HasIndex("EngineId"); + + b.ToTable("EngineComponents"); + }); + + modelBuilder.Entity("MotorPlantDatabaseImplement.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("MotorPlantDatabaseImplement.Models.MessageInfo", 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("MotorPlantDatabaseImplement.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("EngineId") + .HasColumnType("int"); + + b.Property("ImplementerId") + .HasColumnType("int"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("Sum") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.HasIndex("EngineId"); + + b.HasIndex("ImplementerId"); + + b.ToTable("Orders"); + }); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.EngineComponent", b => + { + b.HasOne("MotorPlantDatabaseImplement.Models.Component", "Component") + .WithMany("EngineComponents") + .HasForeignKey("ComponentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("MotorPlantDatabaseImplement.Models.Engine", "Engine") + .WithMany("Components") + .HasForeignKey("EngineId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Component"); + + b.Navigation("Engine"); + }); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.MessageInfo", b => + { + b.HasOne("MotorPlantDatabaseImplement.Models.Client", "Client") + .WithMany() + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Order", b => + { + b.HasOne("MotorPlantDatabaseImplement.Models.Client", "Client") + .WithMany("Orders") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("MotorPlantDatabaseImplement.Models.Engine", "Engine") + .WithMany("Orders") + .HasForeignKey("EngineId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("MotorPlantDatabaseImplement.Models.Implementer", "Implementer") + .WithMany("Orders") + .HasForeignKey("ImplementerId"); + + b.Navigation("Client"); + + b.Navigation("Engine"); + + b.Navigation("Implementer"); + }); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Client", b => + { + b.Navigation("Orders"); + }); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Component", b => + { + b.Navigation("EngineComponents"); + }); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Engine", b => + { + b.Navigation("Components"); + + b.Navigation("Orders"); + }); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Implementer", b => + { + b.Navigation("Orders"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240525181417_InitialCreate4.cs b/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240525181417_InitialCreate4.cs new file mode 100644 index 0000000..5e25f73 --- /dev/null +++ b/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240525181417_InitialCreate4.cs @@ -0,0 +1,48 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace MotorPlantDatabaseImplement.Migrations +{ + /// + public partial class InitialCreate4 : 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/MotorPlant/MotorPlantDatabaseImplement/Migrations/MotorPlantDataBaseModelSnapshot.cs b/MotorPlant/MotorPlantDatabaseImplement/Migrations/MotorPlantDataBaseModelSnapshot.cs index 4fb27a6..bc532e5 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Migrations/MotorPlantDataBaseModelSnapshot.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Migrations/MotorPlantDataBaseModelSnapshot.cs @@ -140,6 +140,36 @@ namespace MotorPlantDatabaseImplement.Migrations b.ToTable("Implementers"); }); + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.MessageInfo", b => + { + b.Property("MessageId") + .HasColumnType("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("MotorPlantDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -202,6 +232,15 @@ namespace MotorPlantDatabaseImplement.Migrations b.Navigation("Engine"); }); + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.MessageInfo", b => + { + b.HasOne("MotorPlantDatabaseImplement.Models.Client", "Client") + .WithMany() + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Order", b => { b.HasOne("MotorPlantDatabaseImplement.Models.Client", "Client") diff --git a/MotorPlant/MotorPlantDatabaseImplement/MotorPlantDataBase.cs b/MotorPlant/MotorPlantDatabaseImplement/MotorPlantDataBase.cs index 768c309..cac86bb 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/MotorPlantDataBase.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/MotorPlantDataBase.cs @@ -26,5 +26,6 @@ optionsBuilder) 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/MotorPlant/MotorPlantFileImplement/DataFileSingleton.cs b/MotorPlant/MotorPlantFileImplement/DataFileSingleton.cs index 73045f0..c611b54 100644 --- a/MotorPlant/MotorPlantFileImplement/DataFileSingleton.cs +++ b/MotorPlant/MotorPlantFileImplement/DataFileSingleton.cs @@ -12,11 +12,13 @@ namespace MotorPlantFileImplement private readonly string EngineFileName = "Engine.xml"; private readonly string ClientFileName = "Client.xml"; private readonly string ImplementerFileName = "Implementer.xml"; + private readonly string MessageInfoFileName = "MessageInfo.xml"; public List Components { get; private set; } public List Orders { get; private set; } public List Engines { get; private set; } public List Clients { get; private set; } public List Implementers { get; private set; } + public List Messages { get; private set; } public static DataFileSingleton GetInstance() { if (instance == null) @@ -32,6 +34,7 @@ namespace MotorPlantFileImplement "Clients", x => x.GetXElement); public void SaveImplementers() => SaveData(Implementers, ImplementerFileName, "Implementers", x => x.GetXElement); + public void SaveMessages() => SaveData(Orders, ImplementerFileName, "Messages", x => x.GetXElement); private DataFileSingleton() { Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!; @@ -41,6 +44,7 @@ namespace MotorPlantFileImplement Client.Create(x)!)!; Implementers = LoadData(ImplementerFileName, "Implementer", x => Implementer.Create(x)!)!; + Messages = LoadData(MessageInfoFileName, "MessageInfo", x => MessageInfo.Create(x)!)!; } private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) { diff --git a/MotorPlant/MotorPlantFileImplement/MessageInfo.cs b/MotorPlant/MotorPlantFileImplement/MessageInfo.cs new file mode 100644 index 0000000..fcb68a9 --- /dev/null +++ b/MotorPlant/MotorPlantFileImplement/MessageInfo.cs @@ -0,0 +1,71 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.ViewModels; +using MotorPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace MotorPlantFileImplement.Models +{ + public class MessageInfo : IMessageInfoModel + { + public string MessageId { get; private set; } = string.Empty; + public int? ClientId { get; private set; } + public string SenderName { get; private set; } = string.Empty; + public DateTime DateDelivery { get; private set; } = DateTime.Now; + public string Subject { get; private set; } = string.Empty; + public string Body { get; private set; } = string.Empty; + public static MessageInfo? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Subject = model.Subject, + ClientId = model.ClientId, + MessageId = model.MessageId, + SenderName = model.SenderName, + DateDelivery = model.DateDelivery, + }; + } + public static MessageInfo? Create(XElement element) + { + if (element == null) + { + return null; + } + return new() + { + Body = element.Attribute("Body")!.Value, + Subject = element.Attribute("Subject")!.Value, + ClientId = Convert.ToInt32(element.Attribute("ClientId")!.Value), + MessageId = element.Attribute("MessageId")!.Value, + SenderName = element.Attribute("SenderName")!.Value, + DateDelivery = Convert.ToDateTime(element.Attribute("DateDelivery")!.Value), + }; + } + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Subject = Subject, + ClientId = ClientId, + MessageId = MessageId, + SenderName = SenderName, + DateDelivery = DateDelivery, + }; + public XElement GetXElement => new("MessageInfo", + new XAttribute("Body", Body), + new XAttribute("Subject", Subject), + new XAttribute("ClientId", ClientId), + new XAttribute("MessageId", MessageId), + new XAttribute("SenderName", SenderName), + new XAttribute("DateDelivery", DateDelivery) + ); + } +} diff --git a/MotorPlant/MotorPlantFileImplement/MessageInfoStorage.cs b/MotorPlant/MotorPlantFileImplement/MessageInfoStorage.cs new file mode 100644 index 0000000..d62e0b7 --- /dev/null +++ b/MotorPlant/MotorPlantFileImplement/MessageInfoStorage.cs @@ -0,0 +1,54 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.StoragesContracts; +using MotorPlantContracts.ViewModels; +using MotorPlantFileImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantFileImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + private readonly DataFileSingleton _source; + public MessageInfoStorage() + { + _source = DataFileSingleton.GetInstance(); + } + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (model.MessageId != null) + { + return _source.Messages.FirstOrDefault(x => x.MessageId == model.MessageId)?.GetViewModel; + } + return null; + } + public List GetFilteredList(MessageInfoSearchModel model) + { + return _source.Messages + .Where(x => x.ClientId == model.ClientId) + .Select(x => x.GetViewModel) + .ToList(); + } + public List GetFullList() + { + return _source.Messages + .Select(x => x.GetViewModel) + .ToList(); + } + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = MessageInfo.Create(model); + if (newMessage == null) + { + return null; + } + _source.Messages.Add(newMessage); + _source.SaveMessages(); + return newMessage.GetViewModel; + } + } +} diff --git a/MotorPlant/MotorPlantListImplement/DataListSingleton.cs b/MotorPlant/MotorPlantListImplement/DataListSingleton.cs index be17286..ef21443 100644 --- a/MotorPlant/MotorPlantListImplement/DataListSingleton.cs +++ b/MotorPlant/MotorPlantListImplement/DataListSingleton.cs @@ -11,6 +11,7 @@ namespace MotorPlantListImplement public List Engines { get; set; } public List Clients { get; set; } public List Implementers { get; set; } + public List Messages { get; set; } private DataListSingleton() { Components = new List(); @@ -18,6 +19,7 @@ namespace MotorPlantListImplement Engines = new List(); Clients = new List(); Implementers = new List(); + Messages = new List(); } public static DataListSingleton GetInstance() { diff --git a/MotorPlant/MotorPlantListImplement/MessageInfo.cs b/MotorPlant/MotorPlantListImplement/MessageInfo.cs new file mode 100644 index 0000000..6e96b58 --- /dev/null +++ b/MotorPlant/MotorPlantListImplement/MessageInfo.cs @@ -0,0 +1,46 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.ViewModels; +using MotorPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantListImplement.Models +{ + public class MessageInfo : IMessageInfoModel + { + public string MessageId { get; private set; } = string.Empty; + public int? ClientId { get; private set; } + public string SenderName { get; private set; } = string.Empty; + public DateTime DateDelivery { get; private set; } = DateTime.Now; + public string Subject { get; private set; } = string.Empty; + public string Body { get; private set; } = string.Empty; + public static MessageInfo? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Subject = model.Subject, + ClientId = model.ClientId, + MessageId = model.MessageId, + SenderName = model.SenderName, + DateDelivery = model.DateDelivery, + }; + } + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Subject = Subject, + ClientId = ClientId, + MessageId = MessageId, + SenderName = SenderName, + DateDelivery = DateDelivery, + }; + } +} diff --git a/MotorPlant/MotorPlantListImplement/MessageInfoStorage.cs b/MotorPlant/MotorPlantListImplement/MessageInfoStorage.cs new file mode 100644 index 0000000..5a4906f --- /dev/null +++ b/MotorPlant/MotorPlantListImplement/MessageInfoStorage.cs @@ -0,0 +1,64 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.StoragesContracts; +using MotorPlantContracts.ViewModels; +using MotorPlantListImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantListImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + private readonly DataListSingleton _source; + public MessageInfoStorage() + { + _source = DataListSingleton.GetInstance(); + } + public List GetFullList() + { + List result = new(); + foreach (var item in _source.Messages) + { + result.Add(item.GetViewModel); + } + return result; + } + public List GetFilteredList(MessageInfoSearchModel model) + { + List result = new(); + foreach (var item in _source.Messages) + { + if (item.ClientId.HasValue && item.ClientId == model.ClientId) + { + result.Add(item.GetViewModel); + } + } + return result; + } + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + foreach (var message in _source.Messages) + { + if (model.MessageId != null && model.MessageId.Equals(message.MessageId)) + { + return message.GetViewModel; + } + } + return null; + } + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = MessageInfo.Create(model); + if (newMessage == null) + { + return null; + } + _source.Messages.Add(newMessage); + return newMessage.GetViewModel; + } + } +} diff --git a/MotorPlant/MotorPlantRestApi/Controllers/ClientController.cs b/MotorPlant/MotorPlantRestApi/Controllers/ClientController.cs index a876f14..2a5888e 100644 --- a/MotorPlant/MotorPlantRestApi/Controllers/ClientController.cs +++ b/MotorPlant/MotorPlantRestApi/Controllers/ClientController.cs @@ -11,11 +11,13 @@ namespace MotorPlantRestApi.Controllers { private readonly ILogger _logger; private readonly IClientLogic _logic; - public ClientController(IClientLogic logic, ILogger + 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) @@ -34,6 +36,22 @@ namespace MotorPlantRestApi.Controllers throw; } } + [HttpGet] + public List? GetMessages(int clientId) + { + try + { + return _mailLogic.ReadList(new MessageInfoSearchModel + { + ClientId = clientId + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения писем клиента"); + throw; + } + } [HttpPost] public void Register(ClientBindingModel model) { diff --git a/MotorPlant/MotorPlantRestApi/Program.cs b/MotorPlant/MotorPlantRestApi/Program.cs index 2400180..44b45ea 100644 --- a/MotorPlant/MotorPlantRestApi/Program.cs +++ b/MotorPlant/MotorPlantRestApi/Program.cs @@ -4,6 +4,8 @@ using MotorPlantContracts.BusinessLogicsContracts; using MotorPlantContracts.StoragesContracts; using MotorPlantDatabaseImplement.Implements; using Microsoft.OpenApi.Models; +using MotorPlantBusinessLogic.MailWorker; +using MotorPlantContracts.BindingModels; var builder = WebApplication.CreateBuilder(args); builder.Logging.SetMinimumLevel(LogLevel.Trace); builder.Logging.AddLog4Net("log4net.config"); @@ -14,6 +16,11 @@ 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 @@ -28,6 +35,24 @@ builder.Services.AddSwaggerGen(c => }); }); var app = builder.Build(); +var mailSender = app.Services.GetService(); +mailSender?.MailConfig(new MailConfigBindingModel +{ + MailLogin = builder.Configuration?.GetSection("MailLogin")?.Value?.ToString() +?? string.Empty, + MailPassword = +builder.Configuration?.GetSection("MailPassword")?.Value?.ToString() ?? +string.Empty, + SmtpClientHost = +builder.Configuration?.GetSection("SmtpClientHost")?.Value?.ToString() ?? +string.Empty, + SmtpClientPort = +Convert.ToInt32(builder.Configuration?.GetSection("SmtpClientPort")?.Value?.ToString()), + PopHost = builder.Configuration?.GetSection("PopHost")?.Value?.ToString() ?? +string.Empty, + PopPort = +Convert.ToInt32(builder.Configuration?.GetSection("PopPort")?.Value?.ToString()) +}); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { diff --git a/MotorPlant/MotorPlantRestApi/appsettings.json b/MotorPlant/MotorPlantRestApi/appsettings.json index 10f68b8..fceecde 100644 --- a/MotorPlant/MotorPlantRestApi/appsettings.json +++ b/MotorPlant/MotorPlantRestApi/appsettings.json @@ -5,5 +5,12 @@ "Microsoft.AspNetCore": "Warning" } }, - "AllowedHosts": "*" + "AllowedHosts": "*", + "SmtpClientHost": "smtp.gmail.com", + "SmtpClientPort": "587", + "PopHost": "pop.gmail.com", + "PopPort": "995", + + "MailLogin": "lab7yakobchuk@gmail.com", + "MailPassword": "scht ahjt fxmx tdpc" } diff --git a/MotorPlant/MotorPlantView/App.config b/MotorPlant/MotorPlantView/App.config new file mode 100644 index 0000000..4bd2342 --- /dev/null +++ b/MotorPlant/MotorPlantView/App.config @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/MotorPlant/MotorPlantView/FormMain.Designer.cs b/MotorPlant/MotorPlantView/FormMain.Designer.cs index 8a11f86..2309e01 100644 --- a/MotorPlant/MotorPlantView/FormMain.Designer.cs +++ b/MotorPlant/MotorPlantView/FormMain.Designer.cs @@ -39,6 +39,7 @@ клиентыToolStripMenuItem = new ToolStripMenuItem(); запускРаботToolStripMenuItem = new ToolStripMenuItem(); исполнителиToolStripMenuItem = new ToolStripMenuItem(); + почтаToolStripMenuItem = new ToolStripMenuItem(); buttonCreateOrder = new Button(); buttonTakeOrderInWork = new Button(); buttonOrderReady = new Button(); @@ -52,7 +53,7 @@ // toolStrip1 // toolStrip1.ImageScalingSize = new Size(20, 20); - toolStrip1.Items.AddRange(new ToolStripItem[] { toolStripDropDownButton1, ReportsToolStripMenuItem, запускРаботToolStripMenuItem }); + toolStrip1.Items.AddRange(new ToolStripItem[] { toolStripDropDownButton1, ReportsToolStripMenuItem, запускРаботToolStripMenuItem, почтаToolStripMenuItem }); toolStrip1.Location = new Point(0, 0); toolStrip1.Name = "toolStrip1"; toolStrip1.Size = new Size(969, 25); @@ -192,6 +193,13 @@ исполнителиToolStripMenuItem.Size = new Size(180, 22); исполнителиToolStripMenuItem.Text = "Исполнители"; исполнителиToolStripMenuItem.Click += исполнителиToolStripMenuItem_Click; + // + // почтаToolStripMenuItem + // + почтаToolStripMenuItem.Name = "почтаToolStripMenuItem"; + почтаToolStripMenuItem.Size = new Size(53, 25); + почтаToolStripMenuItem.Text = "Почта"; + почтаToolStripMenuItem.Click += почтаToolStripMenuItem_Click; // // FormMain // @@ -234,5 +242,6 @@ private ToolStripMenuItem клиентыToolStripMenuItem; private ToolStripMenuItem запускРаботToolStripMenuItem; private ToolStripMenuItem исполнителиToolStripMenuItem; + private ToolStripMenuItem почтаToolStripMenuItem; } } \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormMain.cs b/MotorPlant/MotorPlantView/FormMain.cs index dc52f26..3eb4663 100644 --- a/MotorPlant/MotorPlantView/FormMain.cs +++ b/MotorPlant/MotorPlantView/FormMain.cs @@ -202,5 +202,15 @@ Program.ServiceProvider?.GetService(typeof(ImplementersForm)); form.ShowDialog(); } } + private void почтаToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = +Program.ServiceProvider?.GetService(typeof(FormViewMail)); + if (service is FormViewMail form) + { + form.ShowDialog(); + } + + } } } diff --git a/MotorPlant/MotorPlantView/FormViewMail.Designer.cs b/MotorPlant/MotorPlantView/FormViewMail.Designer.cs new file mode 100644 index 0000000..675c7cd --- /dev/null +++ b/MotorPlant/MotorPlantView/FormViewMail.Designer.cs @@ -0,0 +1,62 @@ +namespace MotorPlantView.Forms +{ + partial class FormViewMail + { + /// + /// 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.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(12, 12); + dataGridView.Name = "dataGridView"; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 29; + dataGridView.Size = new Size(776, 426); + dataGridView.TabIndex = 0; + // + // FormViewMail + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(800, 450); + Controls.Add(dataGridView); + Name = "FormViewMail"; + Text = "Письма"; + Load += ViewMailForm_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView; + } +} \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormViewMail.cs b/MotorPlant/MotorPlantView/FormViewMail.cs new file mode 100644 index 0000000..2140a57 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormViewMail.cs @@ -0,0 +1,47 @@ +using Microsoft.Extensions.Logging; +using MotorPlantContracts.BusinessLogicsContracts; +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 MotorPlantView.Forms +{ + public partial class FormViewMail : Form + { + private readonly ILogger _logger; + private readonly IMessageInfoLogic _logic; + public FormViewMail(ILogger logger, IMessageInfoLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + private void ViewMailForm_Load(object sender, EventArgs e) + { + try + { + var list = _logic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["MessageId"].Visible = false; + dataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + _logger.LogInformation("Загрузка списка писем"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки писем"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + } +} diff --git a/MotorPlant/MotorPlantView/FormViewMail.resx b/MotorPlant/MotorPlantView/FormViewMail.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormViewMail.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/Program.cs b/MotorPlant/MotorPlantView/Program.cs index a4d3282..048fb02 100644 --- a/MotorPlant/MotorPlantView/Program.cs +++ b/MotorPlant/MotorPlantView/Program.cs @@ -1,4 +1,4 @@ -using MotorPlantContracts.BusinessLogicsContracts; +using MotorPlantContracts.BusinessLogicsContracts; using MotorPlantContracts.StoragesContracts; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; @@ -9,6 +9,8 @@ using MotorPlantBusinessLogic.OfficePackage.Implements; using MotorPlantBusinessLogic.OfficePackage; using MotorPlantBusinessLogic; using MotorPlantBusinessLogic.BusinessLogic; +using MotorPlantBusinessLogic.MailWorker; +using MotorPlantContracts.BindingModels; namespace MotorPlantView.Forms { @@ -28,7 +30,37 @@ namespace MotorPlantView.Forms var services = new ServiceCollection(); ConfigureServices(services); _serviceProvider = services.BuildServiceProvider(); - + try + { + var mailSender = + _serviceProvider.GetService(); + mailSender?.MailConfig(new MailConfigBindingModel + { + MailLogin = + System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? + string.Empty, + MailPassword = + System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? + string.Empty, + SmtpClientHost = + System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? + string.Empty, + SmtpClientPort = + Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]), + PopHost = + System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty, + PopPort = + Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"]) + }); + // ñîçäàåì òàéìåð + var timer = new System.Threading.Timer(new + TimerCallback(MailCheck!), null, 0, 100000); + } + catch (Exception ex) + { + var logger = _serviceProvider.GetService(); + logger?.LogError(ex, "Îøèáêà ðàáîòû ñ ïî÷òîé"); + } Application.Run(_serviceProvider.GetRequiredService()); } private static void ConfigureServices(ServiceCollection services) @@ -51,6 +83,8 @@ namespace MotorPlantView.Forms services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -64,9 +98,13 @@ namespace MotorPlantView.Forms services.AddTransient(); services.AddTransient(); services.AddTransient(); - services.AddTransient(); + services.AddSingleton(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); } + private static void MailCheck(object obj) => +ServiceProvider?.GetService()?.MailCheck(); } } \ No newline at end of file