diff --git a/FishFactory/FishFactoryBusinessLogic/BusinessLogics/ClientLogic.cs b/FishFactory/FishFactoryBusinessLogic/BusinessLogics/ClientLogic.cs index 5803b21..53647a5 100644 --- a/FishFactory/FishFactoryBusinessLogic/BusinessLogics/ClientLogic.cs +++ b/FishFactory/FishFactoryBusinessLogic/BusinessLogics/ClientLogic.cs @@ -4,6 +4,7 @@ using FishFactoryContracts.SearchModels; using FishFactoryContracts.StoragesContracts; using FishFactoryContracts.ViewModels; using Microsoft.Extensions.Logging; +using System.Text.RegularExpressions; namespace FishFactoryBusinessLogic.BusinessLogics @@ -97,9 +98,9 @@ namespace FishFactoryBusinessLogic.BusinessLogics { throw new ArgumentNullException("Нет ФИО пользователя", nameof(model.ClientFIO)); } - if (string.IsNullOrEmpty(model.Email)) - { - throw new ArgumentNullException("Нет почты пользователя", nameof(model.Email)); + if (string.IsNullOrEmpty(model.Email) || !Regex.IsMatch(model.Email, @"^[a-z0-9._%+-]+\@([a-z0-9-]+\.)+[a-z]{2,4}$")) + { + throw new ArgumentNullException("Почта указана неверно", nameof(model.Email)); } if (string.IsNullOrEmpty(model.Password)) { diff --git a/FishFactory/FishFactoryBusinessLogic/BusinessLogics/MailWorker/AbstractMailWorker.cs b/FishFactory/FishFactoryBusinessLogic/BusinessLogics/MailWorker/AbstractMailWorker.cs new file mode 100644 index 0000000..3ff13c6 --- /dev/null +++ b/FishFactory/FishFactoryBusinessLogic/BusinessLogics/MailWorker/AbstractMailWorker.cs @@ -0,0 +1,85 @@ +using FishFactoryContracts.BindingModels; +using FishFactoryContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FishFactoryBusinessLogic.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.Length, _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(); + } +} \ No newline at end of file diff --git a/FishFactory/FishFactoryBusinessLogic/BusinessLogics/MailWorker/MailKitWorker.cs b/FishFactory/FishFactoryBusinessLogic/BusinessLogics/MailWorker/MailKitWorker.cs new file mode 100644 index 0000000..600c8ac --- /dev/null +++ b/FishFactory/FishFactoryBusinessLogic/BusinessLogics/MailWorker/MailKitWorker.cs @@ -0,0 +1,83 @@ +using MailKit.Net.Pop3; +using MailKit.Security; +using Microsoft.Extensions.Logging; +using FishFactoryContracts.BindingModels; +using FishFactoryContracts.BusinessLogicsContracts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Mail; +using System.Net; +using System.Text; +using System.Threading.Tasks; +using FishFactoryBusinessLogic.MailWorker; + +namespace FishFactoryBusinessLogic.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; + } + } +} \ No newline at end of file diff --git a/FishFactory/FishFactoryBusinessLogic/BusinessLogics/MessageInfoLogic.cs b/FishFactory/FishFactoryBusinessLogic/BusinessLogics/MessageInfoLogic.cs new file mode 100644 index 0000000..4eb7b26 --- /dev/null +++ b/FishFactory/FishFactoryBusinessLogic/BusinessLogics/MessageInfoLogic.cs @@ -0,0 +1,85 @@ +using FishFactoryContracts.SearchModels; +using FishFactoryContracts.StoragesContracts; +using Microsoft.Extensions.Logging; +using FishFactoryContracts.BindingModels; +using FishFactoryContracts.BusinessLogicsContracts; +using FishFactoryContracts.ViewModels; + +namespace FishFactoryBusinessLogic.BusinessLogics +{ + public class MessageInfoLogic : IMessageInfoLogic + { + private readonly ILogger _logger; + private readonly IMessageInfoStorage _messageInfoStorage; + private readonly IClientStorage _clientStorage; + public MessageInfoLogic(ILogger logger, IMessageInfoStorage messageInfoStorage, IClientStorage clientStorage) + { + _logger = logger; + _messageInfoStorage = messageInfoStorage; + _clientStorage = clientStorage; + } + 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; + } + public bool Create(MessageInfoBindingModel model) + { + CheckModel(model); + if (_messageInfoStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } + 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/FishFactory/FishFactoryBusinessLogic/BusinessLogics/OrderLogic.cs b/FishFactory/FishFactoryBusinessLogic/BusinessLogics/OrderLogic.cs index 3d60203..92f3b48 100644 --- a/FishFactory/FishFactoryBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/FishFactory/FishFactoryBusinessLogic/BusinessLogics/OrderLogic.cs @@ -5,6 +5,8 @@ using FishFactoryContracts.SearchModels; using FishFactoryContracts.StoragesContracts; using FishFactoryContracts.ViewModels; using FishFactoryDataModels.Enums; +using MigraDoc.Rendering; +using FishFactoryBusinessLogic.MailWorker; using System; using System.Collections.Generic; using System.Linq; @@ -17,11 +19,13 @@ namespace FishFactoryBusinessLogic.BusinessLogics { private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; + private readonly AbstractMailWorker _mailWorker; static readonly object _locker = new object(); - public OrderLogic(ILogger logger, IOrderStorage orderStorage) + public OrderLogic(ILogger logger, IOrderStorage orderStorage, AbstractMailWorker mailWorker) { _logger = logger; _orderStorage = orderStorage; + _mailWorker = mailWorker; } public OrderViewModel? ReadElement(OrderSearchModel model) { @@ -59,11 +63,18 @@ namespace FishFactoryBusinessLogic.BusinessLogics if (model.Status != OrderStatus.Неизвестен) return false; model.Status = OrderStatus.Принят; - if (_orderStorage.Insert(model) == null) + var element = _orderStorage.Insert(model); + if (element == null) { _logger.LogWarning("Insert operation failed"); return false; } + Task.Run(() => _mailWorker.MailSendAsync(new MailSendInfoBindingModel + { + MailAddress = element.ClientEmail, + Subject = $"Изменение статуса заказа номер {element.Id}", + Text = $"Ваш заказ номер {element.Id} на консервы {element.CannedName} от {element.DateCreate} на сумму {element.Sum} принят." + })); return true; } public bool TakeOrderInWork(OrderBindingModel model) @@ -116,6 +127,13 @@ namespace FishFactoryBusinessLogic.BusinessLogics _logger.LogWarning("Update operation failed"); return false; } + string DateInfo = model.DateImplement.HasValue ? $"Дата выполнения {model.DateImplement}" : ""; + Task.Run(() => _mailWorker.MailSendAsync(new MailSendInfoBindingModel + { + MailAddress = element.ClientEmail, + Subject = $"Изменение статуса заказа номер {element.Id}", + Text = $"Ваш заказ номер {element.Id} на консервы {element.CannedName} от {element.DateCreate} на сумму {element.Sum} {model.Status}. {DateInfo}" + })); return true; } _logger.LogWarning("Changing status operation faled: Current-{Status}:required-{requiredStatus}.", model.Status, requiredStatus); diff --git a/FishFactory/FishFactoryBusinessLogic/FishFactoryBusinessLogic.csproj b/FishFactory/FishFactoryBusinessLogic/FishFactoryBusinessLogic.csproj index 36bb788..c3064bb 100644 --- a/FishFactory/FishFactoryBusinessLogic/FishFactoryBusinessLogic.csproj +++ b/FishFactory/FishFactoryBusinessLogic/FishFactoryBusinessLogic.csproj @@ -8,6 +8,7 @@ + diff --git a/FishFactory/FishFactoryClientApp/Controllers/HomeController.cs b/FishFactory/FishFactoryClientApp/Controllers/HomeController.cs index dcbb42d..4347048 100644 --- a/FishFactory/FishFactoryClientApp/Controllers/HomeController.cs +++ b/FishFactory/FishFactoryClientApp/Controllers/HomeController.cs @@ -146,5 +146,15 @@ namespace FishFactoryClientApp.Controllers ); return count * (prod?.Price ?? 1); } + + [HttpGet] + public IActionResult Mails() + { + if (APIClient.Client == null) + { + return Redirect("~/Home/Enter"); + } + return View(APIClient.GetRequest>($"api/client/getmessages?clientId={APIClient.Client.Id}")); + } } } diff --git a/FishFactory/FishFactoryClientApp/Views/Home/Mails.cshtml b/FishFactory/FishFactoryClientApp/Views/Home/Mails.cshtml new file mode 100644 index 0000000..da23fc5 --- /dev/null +++ b/FishFactory/FishFactoryClientApp/Views/Home/Mails.cshtml @@ -0,0 +1,54 @@ +@using FishFactoryContracts.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/FishFactory/FishFactoryClientApp/Views/Shared/_Layout.cshtml b/FishFactory/FishFactoryClientApp/Views/Shared/_Layout.cshtml index 1616d6f..34191a7 100644 --- a/FishFactory/FishFactoryClientApp/Views/Shared/_Layout.cshtml +++ b/FishFactory/FishFactoryClientApp/Views/Shared/_Layout.cshtml @@ -26,6 +26,9 @@ + diff --git a/FishFactory/FishFactoryContracts/BindingModels/MailConfigBindingModel.cs b/FishFactory/FishFactoryContracts/BindingModels/MailConfigBindingModel.cs new file mode 100644 index 0000000..50494ef --- /dev/null +++ b/FishFactory/FishFactoryContracts/BindingModels/MailConfigBindingModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FishFactoryContracts.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; } + } +} \ No newline at end of file diff --git a/FishFactory/FishFactoryContracts/BindingModels/MailSendInfoBindingModel.cs b/FishFactory/FishFactoryContracts/BindingModels/MailSendInfoBindingModel.cs new file mode 100644 index 0000000..c0ecadf --- /dev/null +++ b/FishFactory/FishFactoryContracts/BindingModels/MailSendInfoBindingModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FishFactoryContracts.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; + } +} \ No newline at end of file diff --git a/FishFactory/FishFactoryContracts/BindingModels/MessageInfoBindingModel.cs b/FishFactory/FishFactoryContracts/BindingModels/MessageInfoBindingModel.cs new file mode 100644 index 0000000..8056b9c --- /dev/null +++ b/FishFactory/FishFactoryContracts/BindingModels/MessageInfoBindingModel.cs @@ -0,0 +1,19 @@ +using FishFactoryDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FishFactoryContracts.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; } + } +} \ No newline at end of file diff --git a/FishFactory/FishFactoryContracts/BusinessLogicsContracts/IMessageInfoLogic.cs b/FishFactory/FishFactoryContracts/BusinessLogicsContracts/IMessageInfoLogic.cs new file mode 100644 index 0000000..f830f10 --- /dev/null +++ b/FishFactory/FishFactoryContracts/BusinessLogicsContracts/IMessageInfoLogic.cs @@ -0,0 +1,17 @@ +using FishFactoryContracts.BindingModels; +using FishFactoryContracts.SearchModels; +using FishFactoryContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FishFactoryContracts.BusinessLogicsContracts +{ + public interface IMessageInfoLogic + { + List? ReadList(MessageInfoSearchModel? model); + bool Create(MessageInfoBindingModel model); + } +} \ No newline at end of file diff --git a/FishFactory/FishFactoryContracts/SearchModels/MessageInfoSearchModel.cs b/FishFactory/FishFactoryContracts/SearchModels/MessageInfoSearchModel.cs new file mode 100644 index 0000000..aa7ae2d --- /dev/null +++ b/FishFactory/FishFactoryContracts/SearchModels/MessageInfoSearchModel.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FishFactoryContracts.SearchModels +{ + public class MessageInfoSearchModel + { + public int? ClientId { get; set; } + public string? MessageId { get; set; } + } +} \ No newline at end of file diff --git a/FishFactory/FishFactoryContracts/StoragesContracts/IMessageInfoStorage.cs b/FishFactory/FishFactoryContracts/StoragesContracts/IMessageInfoStorage.cs new file mode 100644 index 0000000..6816e23 --- /dev/null +++ b/FishFactory/FishFactoryContracts/StoragesContracts/IMessageInfoStorage.cs @@ -0,0 +1,19 @@ +using FishFactoryContracts.BindingModels; +using FishFactoryContracts.SearchModels; +using FishFactoryContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FishFactoryContracts.StoragesContracts +{ + public interface IMessageInfoStorage + { + List GetFullList(); + List GetFilteredList(MessageInfoSearchModel model); + MessageInfoViewModel? GetElement(MessageInfoSearchModel model); + MessageInfoViewModel? Insert(MessageInfoBindingModel model); + } +} \ No newline at end of file diff --git a/FishFactory/FishFactoryContracts/ViewModels/MessageInfoViewModel.cs b/FishFactory/FishFactoryContracts/ViewModels/MessageInfoViewModel.cs new file mode 100644 index 0000000..074c950 --- /dev/null +++ b/FishFactory/FishFactoryContracts/ViewModels/MessageInfoViewModel.cs @@ -0,0 +1,29 @@ +using FishFactoryDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FishFactoryContracts.ViewModels +{ + public class MessageInfoViewModel : IMessageInfoModel + { + public string MessageId { get; set; } = string.Empty; + + public int? ClientId { get; set; } + + [DisplayName("Отправитель")] + public string SenderName { get; set; } = string.Empty; + + [DisplayName("Дата письма")] + public DateTime DateDelivery { get; set; } + + [DisplayName("Заголовок")] + public string Subject { get; set; } = string.Empty; + + [DisplayName("Текст")] + public string Body { get; set; } = string.Empty; + } +} \ No newline at end of file diff --git a/FishFactory/FishFactoryContracts/ViewModels/OrderViewModel.cs b/FishFactory/FishFactoryContracts/ViewModels/OrderViewModel.cs index 9675536..0c2423c 100644 --- a/FishFactory/FishFactoryContracts/ViewModels/OrderViewModel.cs +++ b/FishFactory/FishFactoryContracts/ViewModels/OrderViewModel.cs @@ -1,6 +1,7 @@ using FishFactoryDataModels.Enums; using FishFactoryDataModels.Models; using System.ComponentModel; + namespace FishFactoryContracts.ViewModels { public class OrderViewModel : IOrderModel @@ -11,6 +12,7 @@ namespace FishFactoryContracts.ViewModels [DisplayName("ФИО клиента")] public string ClientFIO { get; set; } = string.Empty; + public string ClientEmail { get; set; } = string.Empty; public int? ImplementerId { get; set; } [DisplayName("Исполнитель")] public string? ImplementerFIO { get; set; } = null; diff --git a/FishFactory/FishFactoryDataModels/Models/IMessageInfoModel.cs b/FishFactory/FishFactoryDataModels/Models/IMessageInfoModel.cs new file mode 100644 index 0000000..cf3b1cc --- /dev/null +++ b/FishFactory/FishFactoryDataModels/Models/IMessageInfoModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FishFactoryDataModels.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/FishFactory/FishFactoryDatabaseImplement/FishFactoryDatabase.cs b/FishFactory/FishFactoryDatabaseImplement/FishFactoryDatabase.cs index d7efdbd..80f8fbc 100644 --- a/FishFactory/FishFactoryDatabaseImplement/FishFactoryDatabase.cs +++ b/FishFactory/FishFactoryDatabaseImplement/FishFactoryDatabase.cs @@ -21,5 +21,6 @@ namespace FishFactoryDatabaseImplement public virtual DbSet Orders { set; get; } public virtual DbSet Clients { set; get; } public virtual DbSet Implementers { set; get; } + public virtual DbSet MessageInfos { set; get; } } } \ No newline at end of file diff --git a/FishFactory/FishFactoryDatabaseImplement/Implements/ClientStorage.cs b/FishFactory/FishFactoryDatabaseImplement/Implements/ClientStorage.cs index 74b53ab..3e1ea3e 100644 --- a/FishFactory/FishFactoryDatabaseImplement/Implements/ClientStorage.cs +++ b/FishFactory/FishFactoryDatabaseImplement/Implements/ClientStorage.cs @@ -32,11 +32,10 @@ namespace FishFactoryDatabaseImplement.Implements return null; } using var context = new FishFactoryDatabase(); - return context.Clients.FirstOrDefault(x => - (!string.IsNullOrEmpty(model.Email) && x.Email == model.Email && !string.IsNullOrEmpty(model.Password) && x.Password == model.Password) || - (model.Id.HasValue && x.Id == model.Id)) - ?.GetViewModel; - } + return context.Clients.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id) || + (!string.IsNullOrEmpty(model.ClientFIO) && x.ClientFIO == model.ClientFIO) || + (!string.IsNullOrEmpty(model.Email) && x.Email == model.Email && (string.IsNullOrEmpty(model.Password) || x.Password == model.Password)))?.GetViewModel; + } public ClientViewModel? Insert(ClientBindingModel model) { diff --git a/FishFactory/FishFactoryDatabaseImplement/Implements/MessageInfoStorage.cs b/FishFactory/FishFactoryDatabaseImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..e9c583d --- /dev/null +++ b/FishFactory/FishFactoryDatabaseImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,52 @@ +using FishFactoryContracts.BindingModels; +using FishFactoryContracts.SearchModels; +using FishFactoryContracts.StoragesContracts; +using FishFactoryContracts.ViewModels; +using FishFactoryDatabaseImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FishFactoryDatabaseImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + public List GetFullList() + { + using var context = new FishFactoryDatabase(); + return context.MessageInfos.Select(x => x.GetViewModel).ToList(); + } + public List GetFilteredList(MessageInfoSearchModel model) + { + if (!model.ClientId.HasValue) + { + return new(); + } + using var context = new FishFactoryDatabase(); + return context.MessageInfos.Where(x => x.ClientId.HasValue && x.ClientId == model.ClientId).Select(x => x.GetViewModel).ToList(); + } + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (string.IsNullOrEmpty(model.MessageId)) + { + return new(); + } + using var context = new FishFactoryDatabase(); + return context.MessageInfos.FirstOrDefault(x => x.MessageId == model.MessageId)?.GetViewModel; + } + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = MessageInfo.Create(model); + if (newMessage == null) + { + return null; + } + using var context = new FishFactoryDatabase(); + context.MessageInfos.Add(newMessage); + context.SaveChanges(); + return newMessage.GetViewModel; + } + } +} \ No newline at end of file diff --git a/FishFactory/FishFactoryDatabaseImplement/Models/Client.cs b/FishFactory/FishFactoryDatabaseImplement/Models/Client.cs index 423f640..3e02694 100644 --- a/FishFactory/FishFactoryDatabaseImplement/Models/Client.cs +++ b/FishFactory/FishFactoryDatabaseImplement/Models/Client.cs @@ -24,9 +24,11 @@ namespace FishFactoryDatabaseImplement.Models public string Password { get; set; } = string.Empty; [ForeignKey("ClientId")] - public virtual List Orders { get; set; } = new(); + public virtual List ClientOrders { get; set; } = new(); - public static Client? Create(ClientBindingModel model) + [ForeignKey("ClientId")] + public virtual List ClientMessages { get; set; } = new(); + public static Client? Create(ClientBindingModel model) { if (model == null) { diff --git a/FishFactory/FishFactoryDatabaseImplement/Models/MessageInfo.cs b/FishFactory/FishFactoryDatabaseImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..1f74155 --- /dev/null +++ b/FishFactory/FishFactoryDatabaseImplement/Models/MessageInfo.cs @@ -0,0 +1,64 @@ +using FishFactoryContracts.BindingModels; +using FishFactoryContracts.ViewModels; +using FishFactoryDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations.Schema; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FishFactoryDatabaseImplement.Models +{ + public class MessageInfo : IMessageInfoModel + { + [Key] + [DatabaseGenerated(DatabaseGeneratedOption.None)] + public string MessageId { get; set; } = string.Empty; + + public int? ClientId { get; set; } + + public virtual Client? Client { get; set; } + + [Required] + public string SenderName { get; set; } = string.Empty; + + [Required] + public DateTime DateDelivery { get; set; } + + [Required] + public string Subject { get; set; } = string.Empty; + + [Required] + public string Body { get; set; } = string.Empty; + + public static MessageInfo? Create(MessageInfoBindingModel? model) + { + if (model == null) + { + return null; + } + return new() + { + MessageId = model.MessageId, + ClientId = model.ClientId, + SenderName = model.SenderName, + DateDelivery = model.DateDelivery, + Subject = model.Subject, + Body = model.Body, + + }; + } + + public MessageInfoViewModel GetViewModel => new() + { + MessageId = MessageId, + ClientId = ClientId, + SenderName = SenderName, + DateDelivery = DateDelivery, + Subject = Subject, + Body = Body + }; + } +} \ No newline at end of file diff --git a/FishFactory/FishFactoryDatabaseImplement/Models/Order.cs b/FishFactory/FishFactoryDatabaseImplement/Models/Order.cs index 370a40f..343c8a3 100644 --- a/FishFactory/FishFactoryDatabaseImplement/Models/Order.cs +++ b/FishFactory/FishFactoryDatabaseImplement/Models/Order.cs @@ -73,7 +73,8 @@ namespace FishFactoryDatabaseImplement.Models Id = Id, ClientId = ClientId, ClientFIO = Client.ClientFIO, - CannedId = CannedId, + ClientEmail = Client.Email, + CannedId = CannedId, CannedName = Canned.CannedName, ImplementerId = ImplementerId, ImplementerFIO = Implementer != null ? Implementer.ImplementerFIO : null, diff --git a/FishFactory/FishFactoryRestApi/Controllers/ClientController.cs b/FishFactory/FishFactoryRestApi/Controllers/ClientController.cs index aad5897..dd1a06a 100644 --- a/FishFactory/FishFactoryRestApi/Controllers/ClientController.cs +++ b/FishFactory/FishFactoryRestApi/Controllers/ClientController.cs @@ -2,6 +2,7 @@ using FishFactoryContracts.BusinessLogicsContracts; using FishFactoryContracts.SearchModels; using FishFactoryContracts.ViewModels; +using System.Net; using Microsoft.AspNetCore.Mvc; namespace FishFactoryRestApi.Controllers { @@ -11,12 +12,14 @@ namespace FishFactoryRestApi.Controllers { private readonly ILogger _logger; private readonly IClientLogic _logic; - public ClientController(IClientLogic logic, ILogger - logger) - { + private readonly IMessageInfoLogic _mailLogic; + + public ClientController(IClientLogic logic, ILogger logger, IMessageInfoLogic mailLogic) + { _logger = logger; _logic = logic; - } + _mailLogic = mailLogic; + } [HttpGet] public ClientViewModel? Login(string login, string password) { @@ -44,8 +47,8 @@ namespace FishFactoryRestApi.Controllers catch (Exception ex) { _logger.LogError(ex, "Ошибка регистрации"); - throw; - } + Response.StatusCode = (int)HttpStatusCode.NotAcceptable; + } } [HttpPost] public void UpdateData(ClientBindingModel model) @@ -60,5 +63,22 @@ namespace FishFactoryRestApi.Controllers throw; } } - } + + [HttpGet] + public List? GetMessages(int clientId) + { + try + { + return _mailLogic.ReadList(new MessageInfoSearchModel + { + ClientId = clientId + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения писем клиента"); + throw; + } + } + } } \ No newline at end of file diff --git a/FishFactory/FishFactoryRestApi/Program.cs b/FishFactory/FishFactoryRestApi/Program.cs index dcb0631..67d8436 100644 --- a/FishFactory/FishFactoryRestApi/Program.cs +++ b/FishFactory/FishFactoryRestApi/Program.cs @@ -2,7 +2,11 @@ using FishFactoryBusinessLogic.BusinessLogics; using FishFactoryContracts.BusinessLogicsContracts; using FishFactoryContracts.StoragesContracts; using FishFactoryDatabaseImplement.Implements; +using FishFactoryBusinessLogic.MailWorker; +using FishFactoryContracts.BindingModels; using Microsoft.OpenApi.Models; +using PizzeriaBusinessLogic.MailWorker; + var builder = WebApplication.CreateBuilder(args); builder.Logging.SetMinimumLevel(LogLevel.Trace); builder.Logging.AddLog4Net("log4net.config"); @@ -14,7 +18,11 @@ 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 @@ -24,6 +32,17 @@ builder.Services.AddSwaggerGen(c => c.SwaggerDoc("v1", new OpenApiInfo { Title = "FishFactoryRestApi", Version = "v1" }); }); 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/FishFactory/FishFactoryRestApi/appsettings.json b/FishFactory/FishFactoryRestApi/appsettings.json index 10f68b8..83d0f9f 100644 --- a/FishFactory/FishFactoryRestApi/appsettings.json +++ b/FishFactory/FishFactoryRestApi/appsettings.json @@ -5,5 +5,12 @@ "Microsoft.AspNetCore": "Warning" } }, - "AllowedHosts": "*" + "AllowedHosts": "*", + + "SmtpClientHost": "smtp.gmail.com", + "SmtpClientPort": "587", + "PopHost": "pop.gmail.com", + "PopPort": "995", + "MailLogin": "labworkdanilkashtanov123@gmail.com", + "MailPassword": "passlab15" } diff --git a/FishFactory/FishFactoryView/App.config b/FishFactory/FishFactoryView/App.config new file mode 100644 index 0000000..3df9407 --- /dev/null +++ b/FishFactory/FishFactoryView/App.config @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/FishFactory/FishFactoryView/FormMail.Designer.cs b/FishFactory/FishFactoryView/FormMail.Designer.cs new file mode 100644 index 0000000..62ec628 --- /dev/null +++ b/FishFactory/FishFactoryView/FormMail.Designer.cs @@ -0,0 +1,67 @@ +namespace FishFactoryView +{ + partial class FormMail + { + /// + /// 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() + { + this.dataGridView = new System.Windows.Forms.DataGridView(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); + this.SuspendLayout(); + // + // dataGridView + // + this.dataGridView.AllowUserToAddRows = false; + this.dataGridView.AllowUserToDeleteRows = false; + this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView.Dock = System.Windows.Forms.DockStyle.Fill; + this.dataGridView.Location = new System.Drawing.Point(0, 0); + this.dataGridView.Name = "dataGridView"; + this.dataGridView.ReadOnly = true; + this.dataGridView.RowHeadersWidth = 51; + this.dataGridView.RowTemplate.Height = 29; + this.dataGridView.Size = new System.Drawing.Size(786, 270); + this.dataGridView.TabIndex = 0; + // + // FormMail + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(786, 270); + this.Controls.Add(this.dataGridView); + this.Name = "FormMail"; + this.Text = "Письма"; + this.Load += new System.EventHandler(this.FormMail_Load); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit(); + this.ResumeLayout(false); + + } + + #endregion + + private DataGridView dataGridView; + } +} \ No newline at end of file diff --git a/FishFactory/FishFactoryView/FormMail.cs b/FishFactory/FishFactoryView/FormMail.cs new file mode 100644 index 0000000..b3f973b --- /dev/null +++ b/FishFactory/FishFactoryView/FormMail.cs @@ -0,0 +1,54 @@ +using Microsoft.Extensions.Logging; +using FishFactoryContracts.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 FishFactoryView +{ + public partial class FormMail : Form + { + private readonly ILogger _logger; + private readonly IMessageInfoLogic _logic; + + public FormMail(ILogger logger, IMessageInfoLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + private void LoadData() + { + try + { + var list = _logic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["MessageId"].Visible = false; + dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["Body"].AutoSizeMode = + DataGridViewAutoSizeColumnMode.Fill; + } + _logger.LogInformation("Загрузка почтовых собщений"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки почтовых сообщений"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void FormMail_Load(object sender, EventArgs e) + { + LoadData(); + } + } +} diff --git a/FishFactory/FishFactoryView/FormMail.resx b/FishFactory/FishFactoryView/FormMail.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/FishFactory/FishFactoryView/FormMail.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/FishFactory/FishFactoryView/FormMain.Designer.cs b/FishFactory/FishFactoryView/FormMain.Designer.cs index 5d5cbef..4423a2a 100644 --- a/FishFactory/FishFactoryView/FormMain.Designer.cs +++ b/FishFactory/FishFactoryView/FormMain.Designer.cs @@ -45,6 +45,7 @@ buttonOrderReady = new Button(); buttonIssuedOrder = new Button(); buttonRef = new Button(); + MailsToolStripMenuItem = new ToolStripMenuItem(); menuStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); SuspendLayout(); @@ -52,7 +53,7 @@ // menuStrip1 // menuStrip1.ImageScalingSize = new Size(20, 20); - menuStrip1.Items.AddRange(new ToolStripItem[] { ToolStripMenuItem, reportsToolStripMenuItem, startWorkToolStripMenuItem }); + menuStrip1.Items.AddRange(new ToolStripItem[] { ToolStripMenuItem, reportsToolStripMenuItem, startWorkToolStripMenuItem, MailsToolStripMenuItem }); menuStrip1.Location = new Point(0, 0); menuStrip1.Name = "menuStrip1"; menuStrip1.Padding = new Padding(5, 2, 0, 2); @@ -200,6 +201,13 @@ buttonRef.UseVisualStyleBackColor = true; buttonRef.Click += ButtonRef_Click; // + // MailsToolStripMenuItem + // + MailsToolStripMenuItem.Name = "MailsToolStripMenuItem"; + MailsToolStripMenuItem.Size = new Size(53, 20); + MailsToolStripMenuItem.Text = "Почта"; + MailsToolStripMenuItem.Click += MailsToolStripMenuItem_Click; + // // FormMain // AutoScaleDimensions = new SizeF(7F, 15F); @@ -243,5 +251,6 @@ private ToolStripMenuItem ClientToolStripMenuItem; private ToolStripMenuItem startWorkToolStripMenuItem; private ToolStripMenuItem employersToolStripMenuItem; + private ToolStripMenuItem MailsToolStripMenuItem; } } \ No newline at end of file diff --git a/FishFactory/FishFactoryView/FormMain.cs b/FishFactory/FishFactoryView/FormMain.cs index 2a398a1..dcce12a 100644 --- a/FishFactory/FishFactoryView/FormMain.cs +++ b/FishFactory/FishFactoryView/FormMain.cs @@ -41,8 +41,11 @@ namespace FishFactoryView { dataGridView.DataSource = list; dataGridView.Columns["CannedId"].Visible = false; + dataGridView.Columns["ClientId"].Visible = false; dataGridView.Columns["CannedName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + dataGridView.Columns["ClientEmail"].Visible = false; + dataGridView.Columns["ImplementerId"].Visible = false; } _logger.LogInformation("Загрузка заказов"); } @@ -209,5 +212,14 @@ namespace FishFactoryView form.ShowDialog(); } } + + private void MailsToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormMail)); + if (service is FormMail form) + { + form.ShowDialog(); + } + } } } diff --git a/FishFactory/FishFactoryView/Program.cs b/FishFactory/FishFactoryView/Program.cs index d936622..9fb6981 100644 --- a/FishFactory/FishFactoryView/Program.cs +++ b/FishFactory/FishFactoryView/Program.cs @@ -2,6 +2,8 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; using FishFactoryBusinessLogic.BusinessLogics; +using FishFactoryBusinessLogic.MailWorker; +using FishFactoryContracts.BindingModels; using FishFactoryBusinessLogic.OfficePackage.Implements; using FishFactoryBusinessLogic.OfficePackage; using FishFactoryContracts.BusinessLogicsContracts; @@ -28,7 +30,27 @@ namespace FishFactoryView var services = new ServiceCollection(); ConfigureServices(services); _serviceProvider = services.BuildServiceProvider(); - Application.Run(_serviceProvider.GetRequiredService()); + 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, "Mails Problem"); + } + Application.Run(_serviceProvider.GetRequiredService()); } private static void ConfigureServices(ServiceCollection services) { @@ -48,7 +70,10 @@ namespace FishFactoryView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddSingleton(); services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -68,5 +93,6 @@ namespace FishFactoryView services.AddTransient(); services.AddTransient(); } - } + private static void MailCheck(object obj) => ServiceProvider?.GetService()?.MailCheck(); + } } \ No newline at end of file