From 624e96e92fe554cfaa82105dd8a6097fe2871f26 Mon Sep 17 00:00:00 2001 From: the Date: Thu, 20 Apr 2023 23:04:13 +0400 Subject: [PATCH 1/6] Start --- .../Models/IMessageInfoModel.cs | 18 ++ .../BusinessLogics/ClientLogic.cs | 9 + .../BusinessLogics/MessageInfoLogic.cs | 48 +++ .../BusinessLogics/OrderLogic.cs | 31 +- .../ComputerShopBusinessLogic.csproj | 1 + .../MailWorker/AbstractMailWorker.cs | 82 +++++ .../MailWorker/MailKitWorker.cs | 79 +++++ .../Controllers/HomeController.cs | 9 + ComputerShopClientApp/Views/Home/Mails.cshtml | 54 ++++ .../Views/Shared/_Layout.cshtml | 3 + .../BindingModels/MailConfigBindingModel.cs | 18 ++ .../BindingModels/MailSendInfoBindingModel.cs | 15 + .../BindingModels/MessageInfoBindingModel.cs | 24 ++ .../IMessageInfoLogic.cs | 17 + .../SearchModels/MessageInfoSearchModel.cs | 14 + .../StoragesContracts/IMessageInfoStorage.cs | 19 ++ .../ViewModels/MessageInfoViewModel.cs | 25 ++ .../ComputerShopDatabase.cs | 2 +- .../Implements/MessageInfoStorage.cs | 56 ++++ .../20230420190320_messagesMig.Designer.cs | 302 ++++++++++++++++++ .../Migrations/20230420190320_messagesMig.cs | 48 +++ .../ComputerShopDatabaseModelSnapshot.cs | 41 +++ .../Models/Client.cs | 2 + .../Models/MessageInfo.cs | 57 ++++ .../Controllers/ClientController.cs | 21 +- ComputerShopRestApi/Program.cs | 18 ++ ComputerShopRestApi/appsettings.json | 9 +- ComputersShop/App.config | 11 + ComputersShop/Program.cs | 27 ++ 29 files changed, 1052 insertions(+), 8 deletions(-) create mode 100644 AbstractComputerDataModel/Models/IMessageInfoModel.cs create mode 100644 ComputerShopBusinessLogic/BusinessLogics/MessageInfoLogic.cs create mode 100644 ComputerShopBusinessLogic/MailWorker/AbstractMailWorker.cs create mode 100644 ComputerShopBusinessLogic/MailWorker/MailKitWorker.cs create mode 100644 ComputerShopClientApp/Views/Home/Mails.cshtml create mode 100644 ComputerShopContracts/BindingModels/MailConfigBindingModel.cs create mode 100644 ComputerShopContracts/BindingModels/MailSendInfoBindingModel.cs create mode 100644 ComputerShopContracts/BindingModels/MessageInfoBindingModel.cs create mode 100644 ComputerShopContracts/BusinessLogicsContracts/IMessageInfoLogic.cs create mode 100644 ComputerShopContracts/SearchModels/MessageInfoSearchModel.cs create mode 100644 ComputerShopContracts/StoragesContracts/IMessageInfoStorage.cs create mode 100644 ComputerShopContracts/ViewModels/MessageInfoViewModel.cs create mode 100644 ComputerShopDatabaseImplement/Implements/MessageInfoStorage.cs create mode 100644 ComputerShopDatabaseImplement/Migrations/20230420190320_messagesMig.Designer.cs create mode 100644 ComputerShopDatabaseImplement/Migrations/20230420190320_messagesMig.cs create mode 100644 ComputerShopDatabaseImplement/Models/MessageInfo.cs create mode 100644 ComputersShop/App.config diff --git a/AbstractComputerDataModel/Models/IMessageInfoModel.cs b/AbstractComputerDataModel/Models/IMessageInfoModel.cs new file mode 100644 index 0000000..cb7fa30 --- /dev/null +++ b/AbstractComputerDataModel/Models/IMessageInfoModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputerShopDataModels.Models +{ + public class IMessageInfoModel + { + string MessageId { get; } + int? ClientId { get; } + string SenderName { get; } + DateTime DateDelivery { get; } + string Subject { get; } + string Body { get; } + } +} diff --git a/ComputerShopBusinessLogic/BusinessLogics/ClientLogic.cs b/ComputerShopBusinessLogic/BusinessLogics/ClientLogic.cs index 3336015..8981792 100644 --- a/ComputerShopBusinessLogic/BusinessLogics/ClientLogic.cs +++ b/ComputerShopBusinessLogic/BusinessLogics/ClientLogic.cs @@ -8,6 +8,7 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; +using System.Text.RegularExpressions; using System.Threading.Tasks; namespace ComputerShopBusinessLogic.BusinessLogics @@ -103,6 +104,14 @@ namespace ComputerShopBusinessLogic.BusinessLogics { throw new ArgumentNullException("Нет логина(почты) клиента", nameof(model.Email)); } + 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. Id: {Id}, FIO: {fio}, email: {email}", model.Id, model.ClientFIO, model.Email); var element = _clientStorage.GetElement(new ClientSearchModel { diff --git a/ComputerShopBusinessLogic/BusinessLogics/MessageInfoLogic.cs b/ComputerShopBusinessLogic/BusinessLogics/MessageInfoLogic.cs new file mode 100644 index 0000000..97a31ce --- /dev/null +++ b/ComputerShopBusinessLogic/BusinessLogics/MessageInfoLogic.cs @@ -0,0 +1,48 @@ +using ComputerShopContracts.BindingModels; +using ComputerShopContracts.BusinessLogicsContracts; +using ComputerShopContracts.SearchModels; +using ComputerShopContracts.StoragesContracts; +using ComputerShopContracts.ViewModels; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputerShopBusinessLogic.BusinessLogics +{ + 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/ComputerShopBusinessLogic/BusinessLogics/OrderLogic.cs b/ComputerShopBusinessLogic/BusinessLogics/OrderLogic.cs index d8696a0..f7c54d2 100644 --- a/ComputerShopBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/ComputerShopBusinessLogic/BusinessLogics/OrderLogic.cs @@ -10,6 +10,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using ComputerShopBusinessLogic.MailWorker; namespace ComputerShopBusinessLogic.BusinessLogics { @@ -17,11 +18,15 @@ namespace ComputerShopBusinessLogic.BusinessLogics { private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; + private readonly AbstractMailWorker _mailWorker; + private readonly IClientLogic _clientLogic; - 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) @@ -33,10 +38,12 @@ namespace ComputerShopBusinessLogic.BusinessLogics return false; } model.Status = OrderStatus.Принят; - if (_orderStorage.Insert(model) == null) + var result = _orderStorage.Insert(model); + if (result == null) { model.Status = OrderStatus.Неизвестен; _logger.LogWarning("Insert operation failed"); + SendOrderStatusMail(result.ClientId, $"Новый заказ создан. Номер заказа #{result.Id}", $"Заказ #{result.Id} от {result.DateCreate} на сумму {result.Sum:0.00} принят"); return false; } return true; @@ -78,12 +85,14 @@ namespace ComputerShopBusinessLogic.BusinessLogics } model1.Status = newStatus; if (model1.Status == OrderStatus.Выдан) model1.DateImplement = DateTime.Now; - if (_orderStorage.Update(model1) == null) + var result = _orderStorage.Update(model); + if (result == null) { model1.Status--; _logger.LogWarning("Update operation failed"); return false; } + SendOrderStatusMail(result.ClientId, $"Изменен статус заказа #{result.Id}", $"Заказ #{result.Id} изменен статус на {result.Status}"); return true; } @@ -132,7 +141,21 @@ namespace ComputerShopBusinessLogic.BusinessLogics _logger.LogInformation("ReadElement find. Id:{Id}", element.Id); return element; } - + 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; + } private void CheckModel(OrderBindingModel model, bool withParams = true) { if (model == null) diff --git a/ComputerShopBusinessLogic/ComputerShopBusinessLogic.csproj b/ComputerShopBusinessLogic/ComputerShopBusinessLogic.csproj index 15f6898..0ef3d37 100644 --- a/ComputerShopBusinessLogic/ComputerShopBusinessLogic.csproj +++ b/ComputerShopBusinessLogic/ComputerShopBusinessLogic.csproj @@ -8,6 +8,7 @@ + diff --git a/ComputerShopBusinessLogic/MailWorker/AbstractMailWorker.cs b/ComputerShopBusinessLogic/MailWorker/AbstractMailWorker.cs new file mode 100644 index 0000000..09d20e8 --- /dev/null +++ b/ComputerShopBusinessLogic/MailWorker/AbstractMailWorker.cs @@ -0,0 +1,82 @@ +using ComputerShopContracts.BindingModels; +using ComputerShopContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputerShopBusinessLogic.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() { Email = mail.SenderName })?.Id; + _messageInfoLogic.Create(mail); + } + } + protected abstract Task SendMailAsync(MailSendInfoBindingModel info); + protected abstract Task> + ReceiveMailAsync(); + } +} diff --git a/ComputerShopBusinessLogic/MailWorker/MailKitWorker.cs b/ComputerShopBusinessLogic/MailWorker/MailKitWorker.cs new file mode 100644 index 0000000..ac48d57 --- /dev/null +++ b/ComputerShopBusinessLogic/MailWorker/MailKitWorker.cs @@ -0,0 +1,79 @@ +using ComputerShopContracts.BindingModels; +using ComputerShopContracts.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 ComputerShopBusinessLogic.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 (MailKit.Security.AuthenticationException) + { } + finally + { + client.Disconnect(true); + } + }); + return list; + } + } +} diff --git a/ComputerShopClientApp/Controllers/HomeController.cs b/ComputerShopClientApp/Controllers/HomeController.cs index 5d9e990..5489ab3 100644 --- a/ComputerShopClientApp/Controllers/HomeController.cs +++ b/ComputerShopClientApp/Controllers/HomeController.cs @@ -143,5 +143,14 @@ namespace ComputerShopClientApp.Controllers var comp = APIClient.GetRequest($"api/main/getproduct?productId={computer}"); return count * (comp?.Price ?? 1); } + [HttpGet] + public IActionResult Mails() + { + if (APIClient.Client == null) + { + return Redirect("~/Home/Enter"); + } + return View(APIClient.GetRequest>($"api/client/getmessages?clientId={APIClient.Client.Id}")); + } } } \ No newline at end of file diff --git a/ComputerShopClientApp/Views/Home/Mails.cshtml b/ComputerShopClientApp/Views/Home/Mails.cshtml new file mode 100644 index 0000000..68d0f1b --- /dev/null +++ b/ComputerShopClientApp/Views/Home/Mails.cshtml @@ -0,0 +1,54 @@ +@using ComputerShopContracts.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/ComputerShopClientApp/Views/Shared/_Layout.cshtml b/ComputerShopClientApp/Views/Shared/_Layout.cshtml index 63549ab..f57b13f 100644 --- a/ComputerShopClientApp/Views/Shared/_Layout.cshtml +++ b/ComputerShopClientApp/Views/Shared/_Layout.cshtml @@ -31,6 +31,9 @@ Личные данные +