diff --git a/SoftwareInstallation/SoftwareInstallationBusinessLogic/BusinessLogics/ClientLogic.cs b/SoftwareInstallation/SoftwareInstallationBusinessLogic/BusinessLogics/ClientLogic.cs index 51bea21..da477a8 100644 --- a/SoftwareInstallation/SoftwareInstallationBusinessLogic/BusinessLogics/ClientLogic.cs +++ b/SoftwareInstallation/SoftwareInstallationBusinessLogic/BusinessLogics/ClientLogic.cs @@ -1,5 +1,6 @@ using Microsoft.Extensions.Logging; using SoftwareInstallationContracts.BindingModels; +using SoftwareInstallationContracts.BusinessLogicContracts; using SoftwareInstallationContracts.BusinessLogicsContracts; using SoftwareInstallationContracts.SearchModels; using SoftwareInstallationContracts.StoragesContracts; @@ -8,6 +9,7 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; +using System.Text.RegularExpressions; using System.Threading.Tasks; namespace SoftwareInstallationBusinessLogic.BusinessLogics @@ -108,6 +110,15 @@ namespace SoftwareInstallationBusinessLogic.BusinessLogics throw new ArgumentNullException("Нет пароля клиента", nameof(model.ClientFIO)); } + if (!Regex.IsMatch(model.Email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$", RegexOptions.IgnoreCase)) + { + throw new ArgumentException("Неправильно введенный email", nameof(model.Email)); + } + + if (!Regex.IsMatch(model.Password, @"^^((\w+\d+\W+)|(\w+\W+\d+)|(\d+\w+\W+)|(\d+\W+\w+)|(\W+\w+\d+)|(\W+\d+\w+))[\w\d\W]*$", RegexOptions.IgnoreCase)) + { + 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/SoftwareInstallation/SoftwareInstallationBusinessLogic/BusinessLogics/MessageInfoLogic.cs b/SoftwareInstallation/SoftwareInstallationBusinessLogic/BusinessLogics/MessageInfoLogic.cs new file mode 100644 index 0000000..e71c1c3 --- /dev/null +++ b/SoftwareInstallation/SoftwareInstallationBusinessLogic/BusinessLogics/MessageInfoLogic.cs @@ -0,0 +1,101 @@ +using Microsoft.Extensions.Logging; +using SoftwareInstallationContracts.BindingModels; +using SoftwareInstallationContracts.BusinessLogicContracts; +using SoftwareInstallationContracts.SearchModels; +using SoftwareInstallationContracts.StoragesContracts; +using SoftwareInstallationContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SoftwareInstallationBusinessLogic.BusinessLogics +{ + public class MessageInfoLogic : IMessageInfoLogic + { + private readonly ILogger _logger; + private readonly IMessageInfoStorage _messageStorage; + private readonly IClientStorage _clientStorage; + + public MessageInfoLogic(ILogger logger, IMessageInfoStorage messageStorage, IClientStorage clientStorage) + { + _logger = logger; + _messageStorage = messageStorage; + _clientStorage = clientStorage; + + } + + public bool Create(MessageInfoBindingModel model) + { + CheckModel(model); + if (_messageStorage.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 ? _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; + } + private void CheckModel(MessageInfoBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (!withParams) + { + return; + } + if (string.IsNullOrEmpty(model.MessageId)) + { + throw new ArgumentNullException("Не указан id сообщения", nameof(model.MessageId)); + } + if (string.IsNullOrEmpty(model.SenderName)) + { + throw new ArgumentNullException("Не указао почта", nameof(model.SenderName)); + } + if (string.IsNullOrEmpty(model.Subject)) + { + throw new ArgumentNullException("Не указана тема", nameof(model.Subject)); + } + if (string.IsNullOrEmpty(model.Body)) + { + throw new ArgumentNullException("Не указан текст сообщения", nameof(model.Subject)); + } + + _logger.LogInformation("MessageInfo. MessageId:{MessageId}.SenderName:{SenderName}.Subject:{Subject}.Body:{Body}", model.MessageId, model.SenderName, model.Subject, model.Body); + var element = _clientStorage.GetElement(new ClientSearchModel + { + Email = model.SenderName + }); + if (element == null) + { + _logger.LogWarning("Не удалоссь найти клиента, отправившего письмо с адреса Email:{Email}", model.SenderName); + } + else + { + model.ClientId = element.Id; + } + } + + } +} diff --git a/SoftwareInstallation/SoftwareInstallationBusinessLogic/BusinessLogics/OrderLogic.cs b/SoftwareInstallation/SoftwareInstallationBusinessLogic/BusinessLogics/OrderLogic.cs index 922c166..8c6e781 100644 --- a/SoftwareInstallation/SoftwareInstallationBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/SoftwareInstallation/SoftwareInstallationBusinessLogic/BusinessLogics/OrderLogic.cs @@ -1,5 +1,8 @@ -using Microsoft.Extensions.Logging; +using DocumentFormat.OpenXml.EMMA; +using Microsoft.Extensions.Logging; +using SoftwareInstallationBusinessLogic.MailWorker; using SoftwareInstallationContracts.BindingModels; +using SoftwareInstallationContracts.BusinessLogicContracts; using SoftwareInstallationContracts.BusinessLogicsContracts; using SoftwareInstallationContracts.SearchModels; using SoftwareInstallationContracts.StoragesContracts; @@ -17,12 +20,16 @@ namespace SoftwareInstallationBusinessLogic.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 bool CreateOrder(OrderBindingModel model) @@ -36,14 +43,17 @@ namespace SoftwareInstallationBusinessLogic.BusinessLogics } model.Status = OrderStatus.Принят; + var result = _orderStorage.Insert(model); - if (_orderStorage.Insert(model) == null) + if (result == null) { model.Status = OrderStatus.Неизвестен; _logger.LogWarning("Insert operation failed"); return false; } + SendOrderMessage(result.ClientId, $"Установка ПО, Заказ №{result.Id}", $"Заказ №{result.Id} от {result.DateCreate} на сумму {result.Sum:0.00} принят"); + return true; } @@ -63,7 +73,7 @@ namespace SoftwareInstallationBusinessLogic.BusinessLogics model.Status = newStatus; - if (model.Status == OrderStatus.Готов) + if (model.Status == OrderStatus.Выдан) model.DateImplement = DateTime.Now; if (viewModel.ImplementerId.HasValue) @@ -73,14 +83,16 @@ namespace SoftwareInstallationBusinessLogic.BusinessLogics model.Count = viewModel.Count; model.PackageId = viewModel.PackageId; - - if (_orderStorage.Update(model) == null) + var result = _orderStorage.Update(model); + if (result == null) { model.Status--; _logger.LogWarning("Неудачная операция обновления статуса"); return false; } + SendOrderMessage(result.ClientId, $"Установка ПО, Заказ №{result.Id}", $"Заказ №{model.Id} изменен статус на {result.Status}"); + return true; } @@ -147,6 +159,7 @@ namespace SoftwareInstallationBusinessLogic.BusinessLogics _logger.LogInformation("Order. OrderId:{Id}.Sum:{Sum}. PackageId: {PackageId}", model.Id, model.Sum, model.PackageId); } + public OrderViewModel? ReadElement(OrderSearchModel model) { if (model == null) @@ -168,6 +181,25 @@ namespace SoftwareInstallationBusinessLogic.BusinessLogics return element; } + + private bool SendOrderMessage(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/SoftwareInstallation/SoftwareInstallationBusinessLogic/MailWorker/AbsractMailWorker.cs b/SoftwareInstallation/SoftwareInstallationBusinessLogic/MailWorker/AbsractMailWorker.cs new file mode 100644 index 0000000..8659e4c --- /dev/null +++ b/SoftwareInstallation/SoftwareInstallationBusinessLogic/MailWorker/AbsractMailWorker.cs @@ -0,0 +1,85 @@ +using Microsoft.Extensions.Logging; +using SoftwareInstallationContracts.BindingModels; +using SoftwareInstallationContracts.BusinessLogicContracts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SoftwareInstallationBusinessLogic.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/SoftwareInstallation/SoftwareInstallationBusinessLogic/MailWorker/MailKitWorker.cs b/SoftwareInstallation/SoftwareInstallationBusinessLogic/MailWorker/MailKitWorker.cs new file mode 100644 index 0000000..f5eac70 --- /dev/null +++ b/SoftwareInstallation/SoftwareInstallationBusinessLogic/MailWorker/MailKitWorker.cs @@ -0,0 +1,83 @@ +using Microsoft.Extensions.Logging; +using SoftwareInstallationContracts.BindingModels; +using SoftwareInstallationContracts.BusinessLogicContracts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Mail; +using System.Net; +using System.Security.Authentication; +using System.Text; +using System.Threading.Tasks; +using MailKit.Net.Pop3; +using MailKit.Security; + +namespace SoftwareInstallationBusinessLogic.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 error) + { } + finally + { + client.Disconnect(true); + } + }); + return list; + } + } +} diff --git a/SoftwareInstallation/SoftwareInstallationBusinessLogic/SoftwareInstallationBusinessLogic.csproj b/SoftwareInstallation/SoftwareInstallationBusinessLogic/SoftwareInstallationBusinessLogic.csproj index 4d616ed..9bbe797 100644 --- a/SoftwareInstallation/SoftwareInstallationBusinessLogic/SoftwareInstallationBusinessLogic.csproj +++ b/SoftwareInstallation/SoftwareInstallationBusinessLogic/SoftwareInstallationBusinessLogic.csproj @@ -9,6 +9,7 @@ + diff --git a/SoftwareInstallation/SoftwareInstallationClientApp/Controllers/HomeController.cs b/SoftwareInstallation/SoftwareInstallationClientApp/Controllers/HomeController.cs index c748ea8..edf7c1a 100644 --- a/SoftwareInstallation/SoftwareInstallationClientApp/Controllers/HomeController.cs +++ b/SoftwareInstallation/SoftwareInstallationClientApp/Controllers/HomeController.cs @@ -139,5 +139,14 @@ namespace SoftwareInstallationClientApp.Controllers var pack = APIClient.GetRequest($"api/main/getpackage?packageId={package}"); return count * (pack?.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/SoftwareInstallation/SoftwareInstallationClientApp/Views/Home/Mails.cshtml b/SoftwareInstallation/SoftwareInstallationClientApp/Views/Home/Mails.cshtml new file mode 100644 index 0000000..dfff0c9 --- /dev/null +++ b/SoftwareInstallation/SoftwareInstallationClientApp/Views/Home/Mails.cshtml @@ -0,0 +1,54 @@ +@using SoftwareInstallationContracts.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/SoftwareInstallation/SoftwareInstallationClientApp/Views/Shared/_Layout.cshtml b/SoftwareInstallation/SoftwareInstallationClientApp/Views/Shared/_Layout.cshtml index 4d124b2..89b3c98 100644 --- a/SoftwareInstallation/SoftwareInstallationClientApp/Views/Shared/_Layout.cshtml +++ b/SoftwareInstallation/SoftwareInstallationClientApp/Views/Shared/_Layout.cshtml @@ -23,19 +23,22 @@