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..ade2bfa 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,12 +38,14 @@ 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"); return false; } + SendOrderStatusMail(result.ClientId, $"Новый заказ создан. Номер заказа #{result.Id}", $"Заказ #{result.Id} от {result.DateCreate} на сумму {result.Sum:0.00} принят"); return true; } @@ -65,9 +72,9 @@ namespace ComputerShopBusinessLogic.BusinessLogics Count = viewModel.Count, Sum = viewModel.Sum }; - if (model.ImplementerId.HasValue) + if (viewModel.ImplementerId.HasValue) { - model1.ImplementerId = model.ImplementerId; + model1.ImplementerId = viewModel.ImplementerId; } CheckModel(model1, false); @@ -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(model1); + 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..3cfae46 --- /dev/null +++ b/ComputerShopBusinessLogic/MailWorker/AbstractMailWorker.cs @@ -0,0 +1,81 @@ +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..35bde32 --- /dev/null +++ b/ComputerShopBusinessLogic/MailWorker/MailKitWorker.cs @@ -0,0 +1,78 @@ +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 @@ Личные данные +