diff --git a/GiftShop/GiftShopBusinessLogic/BusinessLogics/ClientLogic.cs b/GiftShop/GiftShopBusinessLogic/BusinessLogics/ClientLogic.cs index 6cea0b7..ad39386 100644 --- a/GiftShop/GiftShopBusinessLogic/BusinessLogics/ClientLogic.cs +++ b/GiftShop/GiftShopBusinessLogic/BusinessLogics/ClientLogic.cs @@ -4,124 +4,122 @@ using GiftShopContracts.SearchModels; using GiftShopContracts.StoragesContracts; using GiftShopContracts.ViewModels; using Microsoft.Extensions.Logging; +using System.Text.RegularExpressions; namespace GiftShopBusinessLogic.BusinessLogics { - public class ClientLogic : IClientLogic - { - private readonly ILogger _logger; + public class ClientLogic : IClientLogic + { + private readonly ILogger _logger; + private readonly IClientStorage _clientStorage; + public ClientLogic(ILogger logger, IClientStorage clientStorage) + { + _logger = logger; + _clientStorage = clientStorage; + } + public bool Create(ClientBindingModel model) + { + CheckModel(model); + if (_clientStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } - private readonly IClientStorage _clientStorage; + public bool Delete(ClientBindingModel model) + { + CheckModel(model, false); + _logger.LogInformation("Delete. Id:{Id}", model.Id); + if (_clientStorage.Delete(model) == null) + { + _logger.LogWarning("Delete operation failed"); + return false; + } + return true; + } - public ClientLogic(ILogger logger, IClientStorage clientStorage) - { - _logger = logger; - _clientStorage = clientStorage; - } + public ClientViewModel? ReadElement(ClientSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + _logger.LogInformation("ReadElement. ClientFIO:{ClientFIO}. Id:{ Id}", model.ClientFIO, model.Id); + var element = _clientStorage.GetElement(model); + if (element == null) + { + _logger.LogWarning("ReadElement element not found"); + return null; + } + _logger.LogInformation("ReadElement find. Id:{Id}", element.Id); + return element; + } - public bool Create(ClientBindingModel model) - { - CheckModel(model); - if (_clientStorage.Insert(model) == null) - { - _logger.LogWarning("Insert operation failed"); - return false; - } - return true; - } + public List? ReadList(ClientSearchModel? model) + { + _logger.LogInformation("ReadList. ClientFIO:{ClientFIO}. Id:{Id}", model?.ClientFIO, model?.Id); + var list = model == null ? _clientStorage.GetFullList() : _clientStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + _logger.LogInformation("ReadList. Count:{Count}", list.Count); + return list; + } - public bool Delete(ClientBindingModel model) - { - CheckModel(model, false); - _logger.LogInformation("Delete. Id: {Id}", model.Id); - if (_clientStorage.Delete(model) == null) - { - _logger.LogWarning("Delete operation failed"); - return false; - } - return true; - } + public bool Update(ClientBindingModel model) + { + CheckModel(model); + if (_clientStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + return true; + } + private void CheckModel(ClientBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (!withParams) + { + return; + } + if (string.IsNullOrEmpty(model.ClientFIO)) + { + throw new ArgumentNullException("Нет ФИО клиента", nameof(model.ClientFIO)); + } + if (string.IsNullOrEmpty(model.Email)) + { + throw new ArgumentNullException("У клиента отсутствует почта", nameof(model.Email)); + } + if (string.IsNullOrEmpty(model.Password)) + { + throw new ArgumentNullException("У клиента отсутствует пароль", nameof(model.Email)); + } + if (!Regex.IsMatch(model.Email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$")) + { + 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]*$") || model.Password.Length < 10 || model.Password.Length > 50) + { + throw new ArgumentException("Неправильно введенный пароль", nameof(model.Password)); + } + _logger.LogInformation("Client. ClientID:{Id}. ClientFIO: {ClientFIO}. Email:{ Email}. Password: { Password}", model.Id, model.ClientFIO, model.Email, model.Password); + var element = _clientStorage.GetElement(new ClientSearchModel + { + Email = model.Email + }); + if (element != null && element.Id != model.Id) + { + throw new InvalidOperationException("Такой клиент уже существует"); + } - public ClientViewModel? ReadElement(ClientSearchModel model) - { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - _logger.LogInformation("ReadElement. ClientFIO: {ClientFIO}. Email: {Email}. Id: {Id}.", model.ClientFIO, model.Email, model.Id); - - var element = _clientStorage.GetElement(model); - if (element == null) - { - _logger.LogWarning("ReadElement element not found"); - return null; - } - _logger.LogInformation("ReadElement find. Id: {Id}", element.Id); - return element; - } - - public List? ReadList(ClientSearchModel? model) - { - _logger.LogInformation("ReadList. ClientFIO: {ClientName}. Email: {Email}. Id: {Id}.", model?.ClientFIO, model?.Email, model?.Id); - - var list = model == null ? _clientStorage.GetFullList() : _clientStorage.GetFilteredList(model); - if (list == null) - { - _logger.LogWarning("ReadList return null list"); - return null; - } - _logger.LogInformation("ReadList. Count: {Count}", list.Count); - return list; - } - - public bool Update(ClientBindingModel model) - { - CheckModel(model); - if (_clientStorage.Update(model) == null) - { - _logger.LogWarning("Update operation failed"); - return false; - } - return true; - } - - private void CheckModel(ClientBindingModel model, bool withParams = true) - { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - - if (!withParams) - { - return; - } - - if (string.IsNullOrEmpty(model.ClientFIO)) - { - throw new ArgumentNullException("Нет ФИО клиента", nameof(model.ClientFIO)); - } - - if (string.IsNullOrEmpty(model.Email)) - { - throw new ArgumentNullException("Нет почты клиента", nameof(model.Email)); - } - - if (string.IsNullOrEmpty(model.Password)) - { - throw new ArgumentNullException("Нет пароля клиента", nameof(model.Password)); - } - _logger.LogInformation("Client. ClientFIO: {ClientFIO}. Email: {Email}. Id: {Id}", model.ClientFIO, model.Email, model.Id); - - var element = _clientStorage.GetElement(new ClientSearchModel - { - Email = model.Email - }); - - if (element != null && element.Id != model.Id) - { - throw new InvalidOperationException("Клиент с такой почтой уже есть"); - } - } - } + } + } } diff --git a/GiftShop/GiftShopBusinessLogic/BusinessLogics/MessageInfoLogic.cs b/GiftShop/GiftShopBusinessLogic/BusinessLogics/MessageInfoLogic.cs new file mode 100644 index 0000000..4d3e540 --- /dev/null +++ b/GiftShop/GiftShopBusinessLogic/BusinessLogics/MessageInfoLogic.cs @@ -0,0 +1,50 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.BusinessLogicsContracts; +using GiftShopContracts.SearchModels; +using GiftShopContracts.StoragesContracts; +using GiftShopContracts.ViewModels; +using Microsoft.Extensions.Logging; + +namespace GiftShopBusinessLogic.BusinessLogics +{ + public class MessageInfoLogic : IMessageInfoLogic + { + private readonly ILogger _logger; + private readonly IMessageInfoStorage _messageStorage; + + public MessageInfoLogic(ILogger logger, IMessageInfoStorage messageStorage) + { + _logger = logger; + _messageStorage = messageStorage; + } + + public bool Create(MessageInfoBindingModel 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; + } + } +} diff --git a/GiftShop/GiftShopBusinessLogic/BusinessLogics/OrderLogic.cs b/GiftShop/GiftShopBusinessLogic/BusinessLogics/OrderLogic.cs index 997f9d2..77d972f 100644 --- a/GiftShop/GiftShopBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/GiftShop/GiftShopBusinessLogic/BusinessLogics/OrderLogic.cs @@ -1,4 +1,5 @@ -using GiftShopContracts.BindingModels; +using GiftShopBusinessLogic.MailWorker; +using GiftShopContracts.BindingModels; using GiftShopContracts.BusinessLogicsContracts; using GiftShopContracts.SearchModels; using GiftShopContracts.StoragesContracts; @@ -14,11 +15,17 @@ namespace GiftShopBusinessLogic.BusinessLogics private readonly IOrderStorage _orderStorage; - public OrderLogic(ILogger logger, IOrderStorage orderStorage) + private readonly AbstractMailWorker _mailWorker; + + private readonly IClientLogic _clientLogic; + + public OrderLogic(ILogger logger, IOrderStorage orderStorage, AbstractMailWorker mailWorker, IClientLogic clientLogic) { _logger = logger; _orderStorage = orderStorage; - } + _mailWorker = mailWorker; + _clientLogic = clientLogic; + } public bool CreateOrder(OrderBindingModel model) { @@ -166,5 +173,21 @@ namespace GiftShopBusinessLogic.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/GiftShop/GiftShopBusinessLogic/GiftShopBusinessLogic.csproj b/GiftShop/GiftShopBusinessLogic/GiftShopBusinessLogic.csproj index 0f2995b..4caa566 100644 --- a/GiftShop/GiftShopBusinessLogic/GiftShopBusinessLogic.csproj +++ b/GiftShop/GiftShopBusinessLogic/GiftShopBusinessLogic.csproj @@ -8,6 +8,7 @@ + diff --git a/GiftShop/GiftShopBusinessLogic/MailWorker/AbstractMailWorker.cs b/GiftShop/GiftShopBusinessLogic/MailWorker/AbstractMailWorker.cs new file mode 100644 index 0000000..9686a26 --- /dev/null +++ b/GiftShop/GiftShopBusinessLogic/MailWorker/AbstractMailWorker.cs @@ -0,0 +1,95 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; + +namespace GiftShopBusinessLogic.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/GiftShop/GiftShopBusinessLogic/MailWorker/MailKitWorker.cs b/GiftShop/GiftShopBusinessLogic/MailWorker/MailKitWorker.cs new file mode 100644 index 0000000..38a96f6 --- /dev/null +++ b/GiftShop/GiftShopBusinessLogic/MailWorker/MailKitWorker.cs @@ -0,0 +1,78 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using System.Net.Mail; +using System.Net; +using System.Text; +using MailKit.Net.Pop3; +using MailKit.Security; + +namespace GiftShopBusinessLogic.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 (AuthenticationException) + { } + finally + { + client.Disconnect(true); + } + }); + return list; + } + } +} diff --git a/GiftShop/GiftShopClientApp/Controllers/HomeController.cs b/GiftShop/GiftShopClientApp/Controllers/HomeController.cs index 35afa87..8cdf0a8 100644 --- a/GiftShop/GiftShopClientApp/Controllers/HomeController.cs +++ b/GiftShop/GiftShopClientApp/Controllers/HomeController.cs @@ -143,5 +143,15 @@ namespace GiftShopClientApp.Controllers var gif = APIClient.GetRequest($"api/main/getgift?giftId={gift}"); return count * (gif?.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/GiftShop/GiftShopClientApp/GiftShopClientApp.csproj b/GiftShop/GiftShopClientApp/GiftShopClientApp.csproj index 9679658..56b2979 100644 --- a/GiftShop/GiftShopClientApp/GiftShopClientApp.csproj +++ b/GiftShop/GiftShopClientApp/GiftShopClientApp.csproj @@ -6,6 +6,10 @@ enable + + + + @@ -14,4 +18,16 @@ + + + + + + <_ContentIncludedByDefault Remove="Views\Home\Mails.cshtml" /> + + + + + + diff --git a/GiftShop/GiftShopClientApp/Views/Home/Mails.cshtml b/GiftShop/GiftShopClientApp/Views/Home/Mails.cshtml new file mode 100644 index 0000000..a89927c --- /dev/null +++ b/GiftShop/GiftShopClientApp/Views/Home/Mails.cshtml @@ -0,0 +1,53 @@ +@using GiftShopContracts.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/GiftShop/GiftShopClientApp/Views/Shared/_Layout.cshtml b/GiftShop/GiftShopClientApp/Views/Shared/_Layout.cshtml index dc7a821..5e868ee 100644 --- a/GiftShop/GiftShopClientApp/Views/Shared/_Layout.cshtml +++ b/GiftShop/GiftShopClientApp/Views/Shared/_Layout.cshtml @@ -25,6 +25,9 @@ + diff --git a/GiftShop/GiftShopContracts/BindingModels/MailConfigBindingModel.cs b/GiftShop/GiftShopContracts/BindingModels/MailConfigBindingModel.cs new file mode 100644 index 0000000..07373ea --- /dev/null +++ b/GiftShop/GiftShopContracts/BindingModels/MailConfigBindingModel.cs @@ -0,0 +1,17 @@ +namespace GiftShopContracts.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/GiftShop/GiftShopContracts/BindingModels/MailSendInfoBindingModel.cs b/GiftShop/GiftShopContracts/BindingModels/MailSendInfoBindingModel.cs new file mode 100644 index 0000000..0f0bc59 --- /dev/null +++ b/GiftShop/GiftShopContracts/BindingModels/MailSendInfoBindingModel.cs @@ -0,0 +1,11 @@ +namespace GiftShopContracts.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/GiftShop/GiftShopContracts/BindingModels/MessageInfoBindingModel.cs b/GiftShop/GiftShopContracts/BindingModels/MessageInfoBindingModel.cs new file mode 100644 index 0000000..3b00ebd --- /dev/null +++ b/GiftShop/GiftShopContracts/BindingModels/MessageInfoBindingModel.cs @@ -0,0 +1,19 @@ +using GiftShopDataModels.Models; + +namespace GiftShopContracts.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/GiftShop/GiftShopContracts/BusinessLogicsContracts/IMessageInfoLogic.cs b/GiftShop/GiftShopContracts/BusinessLogicsContracts/IMessageInfoLogic.cs new file mode 100644 index 0000000..bbc6cf0 --- /dev/null +++ b/GiftShop/GiftShopContracts/BusinessLogicsContracts/IMessageInfoLogic.cs @@ -0,0 +1,13 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.SearchModels; +using GiftShopContracts.ViewModels; + +namespace GiftShopContracts.BusinessLogicsContracts +{ + public interface IMessageInfoLogic + { + List? ReadList(MessageInfoSearchModel? model); + + bool Create(MessageInfoBindingModel model); + } +} diff --git a/GiftShop/GiftShopContracts/SearchModels/MessageInfoSearchModel.cs b/GiftShop/GiftShopContracts/SearchModels/MessageInfoSearchModel.cs new file mode 100644 index 0000000..b194373 --- /dev/null +++ b/GiftShop/GiftShopContracts/SearchModels/MessageInfoSearchModel.cs @@ -0,0 +1,9 @@ +namespace GiftShopContracts.SearchModels +{ + public class MessageInfoSearchModel + { + public int? ClientId { get; set; } + + public string? MessageId { get; set; } + } +} diff --git a/GiftShop/GiftShopContracts/StoragesContracts/IMessageInfoStorage.cs b/GiftShop/GiftShopContracts/StoragesContracts/IMessageInfoStorage.cs new file mode 100644 index 0000000..04e4645 --- /dev/null +++ b/GiftShop/GiftShopContracts/StoragesContracts/IMessageInfoStorage.cs @@ -0,0 +1,17 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.SearchModels; +using GiftShopContracts.ViewModels; + +namespace GiftShopContracts.StoragesContracts +{ + public interface IMessageInfoStorage + { + List GetFullList(); + + List GetFilteredList(MessageInfoSearchModel model); + + MessageInfoViewModel? GetElement(MessageInfoSearchModel model); + + MessageInfoViewModel? Insert(MessageInfoBindingModel model); + } +} diff --git a/GiftShop/GiftShopContracts/ViewModels/MessageInfoViewModel.cs b/GiftShop/GiftShopContracts/ViewModels/MessageInfoViewModel.cs new file mode 100644 index 0000000..56547bc --- /dev/null +++ b/GiftShop/GiftShopContracts/ViewModels/MessageInfoViewModel.cs @@ -0,0 +1,24 @@ +using GiftShopDataModels.Models; +using System.ComponentModel; + +namespace GiftShopContracts.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/GiftShop/GiftShopDataModels/Models/IMessageInfoModel.cs b/GiftShop/GiftShopDataModels/Models/IMessageInfoModel.cs new file mode 100644 index 0000000..06e4789 --- /dev/null +++ b/GiftShop/GiftShopDataModels/Models/IMessageInfoModel.cs @@ -0,0 +1,17 @@ +namespace GiftShopDataModels.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/GiftShop/GiftShopDatabaseImplement/GiftShopDatabase.cs b/GiftShop/GiftShopDatabaseImplement/GiftShopDatabase.cs index dc7b314..254e70f 100644 --- a/GiftShop/GiftShopDatabaseImplement/GiftShopDatabase.cs +++ b/GiftShop/GiftShopDatabaseImplement/GiftShopDatabase.cs @@ -25,5 +25,7 @@ namespace GiftShopDatabaseImplement public virtual DbSet Clients { set; get; } public virtual DbSet Implementers { set; get; } + + public virtual DbSet Messages { set; get; } } } diff --git a/GiftShop/GiftShopDatabaseImplement/Implements/MessageInfoStorage.cs b/GiftShop/GiftShopDatabaseImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..af45ac2 --- /dev/null +++ b/GiftShop/GiftShopDatabaseImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,55 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.SearchModels; +using GiftShopContracts.StoragesContracts; +using GiftShopContracts.ViewModels; +using GiftShopDatabaseImplement.Models; + +namespace GiftShopDatabaseImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (string.IsNullOrEmpty(model.MessageId)) + { + return null; + } + using var context = new GiftShopDatabase(); + return context.Messages + .FirstOrDefault(x => x.MessageId == model.MessageId)? + .GetViewModel; + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + if (!model.ClientId.HasValue) + return new(); + using var context = new GiftShopDatabase(); + return context.Messages + .Where(x => x.ClientId == model.ClientId) + .Select(x => x.GetViewModel) + .ToList(); + } + + public List GetFullList() + { + using var context = new GiftShopDatabase(); + return context.Messages + .Select(x => x.GetViewModel) + .ToList(); + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + using var context = new GiftShopDatabase(); + var newMessage = Message.Create(model); + if (newMessage == null) + { + return null; + } + context.Messages.Add(newMessage); + context.SaveChanges(); + return newMessage.GetViewModel; + } + } +} diff --git a/GiftShop/GiftShopDatabaseImplement/Migrations/20230514155217_ThirdMigration.Designer.cs b/GiftShop/GiftShopDatabaseImplement/Migrations/20230514155217_ThirdMigration.Designer.cs new file mode 100644 index 0000000..9339929 --- /dev/null +++ b/GiftShop/GiftShopDatabaseImplement/Migrations/20230514155217_ThirdMigration.Designer.cs @@ -0,0 +1,300 @@ +// +using System; +using GiftShopDatabaseImplement; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace GiftShopDatabaseImplement.Migrations +{ + [DbContext(typeof(GiftShopDatabase))] + [Migration("20230514155217_ThirdMigration")] + partial class ThirdMigration + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.4") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("GiftShopDatabaseImplement.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("GiftShopDatabaseImplement.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("GiftShopDatabaseImplement.Models.Gift", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("GiftName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Price") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.ToTable("Gifts"); + }); + + modelBuilder.Entity("GiftShopDatabaseImplement.Models.GiftComponent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ComponentId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("GiftId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ComponentId"); + + b.HasIndex("GiftId"); + + b.ToTable("GiftComponents"); + }); + + modelBuilder.Entity("GiftShopDatabaseImplement.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("GiftShopDatabaseImplement.Models.Message", 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("GiftShopDatabaseImplement.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("GiftId") + .HasColumnType("int"); + + b.Property("GiftName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ImplementerId") + .HasColumnType("int"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("Sum") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.HasIndex("GiftId"); + + b.HasIndex("ImplementerId"); + + b.ToTable("Orders"); + }); + + modelBuilder.Entity("GiftShopDatabaseImplement.Models.GiftComponent", b => + { + b.HasOne("GiftShopDatabaseImplement.Models.Component", "Component") + .WithMany("GiftComponents") + .HasForeignKey("ComponentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("GiftShopDatabaseImplement.Models.Gift", "Gift") + .WithMany("Components") + .HasForeignKey("GiftId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Component"); + + b.Navigation("Gift"); + }); + + modelBuilder.Entity("GiftShopDatabaseImplement.Models.Message", b => + { + b.HasOne("GiftShopDatabaseImplement.Models.Client", "Client") + .WithMany() + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + + modelBuilder.Entity("GiftShopDatabaseImplement.Models.Order", b => + { + b.HasOne("GiftShopDatabaseImplement.Models.Client", "Client") + .WithMany("Orders") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("GiftShopDatabaseImplement.Models.Gift", "Gift") + .WithMany("Orders") + .HasForeignKey("GiftId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("GiftShopDatabaseImplement.Models.Implementer", "Implementer") + .WithMany("Orders") + .HasForeignKey("ImplementerId"); + + b.Navigation("Client"); + + b.Navigation("Gift"); + + b.Navigation("Implementer"); + }); + + modelBuilder.Entity("GiftShopDatabaseImplement.Models.Client", b => + { + b.Navigation("Orders"); + }); + + modelBuilder.Entity("GiftShopDatabaseImplement.Models.Component", b => + { + b.Navigation("GiftComponents"); + }); + + modelBuilder.Entity("GiftShopDatabaseImplement.Models.Gift", b => + { + b.Navigation("Components"); + + b.Navigation("Orders"); + }); + + modelBuilder.Entity("GiftShopDatabaseImplement.Models.Implementer", b => + { + b.Navigation("Orders"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/GiftShop/GiftShopDatabaseImplement/Migrations/20230514155217_ThirdMigration.cs b/GiftShop/GiftShopDatabaseImplement/Migrations/20230514155217_ThirdMigration.cs new file mode 100644 index 0000000..9ff5662 --- /dev/null +++ b/GiftShop/GiftShopDatabaseImplement/Migrations/20230514155217_ThirdMigration.cs @@ -0,0 +1,48 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace GiftShopDatabaseImplement.Migrations +{ + /// + public partial class ThirdMigration : 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/GiftShop/GiftShopDatabaseImplement/Migrations/GiftShopDatabaseModelSnapshot.cs b/GiftShop/GiftShopDatabaseImplement/Migrations/GiftShopDatabaseModelSnapshot.cs index 4ee65ea..7c57d86 100644 --- a/GiftShop/GiftShopDatabaseImplement/Migrations/GiftShopDatabaseModelSnapshot.cs +++ b/GiftShop/GiftShopDatabaseImplement/Migrations/GiftShopDatabaseModelSnapshot.cs @@ -140,6 +140,36 @@ namespace GiftShopDatabaseImplement.Migrations b.ToTable("Implementers"); }); + modelBuilder.Entity("GiftShopDatabaseImplement.Models.Message", 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("GiftShopDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -206,6 +236,15 @@ namespace GiftShopDatabaseImplement.Migrations b.Navigation("Gift"); }); + modelBuilder.Entity("GiftShopDatabaseImplement.Models.Message", b => + { + b.HasOne("GiftShopDatabaseImplement.Models.Client", "Client") + .WithMany() + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + modelBuilder.Entity("GiftShopDatabaseImplement.Models.Order", b => { b.HasOne("GiftShopDatabaseImplement.Models.Client", "Client") diff --git a/GiftShop/GiftShopDatabaseImplement/Models/Message.cs b/GiftShop/GiftShopDatabaseImplement/Models/Message.cs new file mode 100644 index 0000000..c02da99 --- /dev/null +++ b/GiftShop/GiftShopDatabaseImplement/Models/Message.cs @@ -0,0 +1,51 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.ViewModels; +using GiftShopDataModels.Models; +using System.ComponentModel.DataAnnotations; + +namespace GiftShopDatabaseImplement.Models +{ + public class Message : 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 Message? 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/GiftShop/GiftShopFileImplement/DataFileSingleton.cs b/GiftShop/GiftShopFileImplement/DataFileSingleton.cs index 32b41a0..015e790 100644 --- a/GiftShop/GiftShopFileImplement/DataFileSingleton.cs +++ b/GiftShop/GiftShopFileImplement/DataFileSingleton.cs @@ -17,6 +17,8 @@ namespace GiftShopFileImplement private readonly string ImplementerFileName = "Implementer.xml"; + private readonly string MessageFileName = "Message.xml"; + public List Components { get; private set; } public List Orders { get; private set; } @@ -27,6 +29,8 @@ namespace GiftShopFileImplement public List Implementers { get; private set; } + public List Messages { get; private set; } + public static DataFileSingleton GetInstance() { if (instance == null) @@ -46,12 +50,16 @@ namespace GiftShopFileImplement public void SaveImplementers() => SaveData(Implementers, OrderFileName, "Implementers", x => x.GetXElement); + public void SaveMessages() => SaveData(Messages, MessageFileName, "Messages", x => x.GetXElement); + private DataFileSingleton() { Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!; Gifts = LoadData(GiftFileName, "Gift", x => Gift.Create(x)!)!; Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!; + Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!; Implementers = LoadData(ImplementerFileName, "Implementer", x => Implementer.Create(x)!)!; + Messages = LoadData(MessageFileName, "Message", x => Message.Create(x)!)!; } private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) diff --git a/GiftShop/GiftShopFileImplement/Implements/MessageInfoStorage.cs b/GiftShop/GiftShopFileImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..e53268c --- /dev/null +++ b/GiftShop/GiftShopFileImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,53 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.SearchModels; +using GiftShopContracts.StoragesContracts; +using GiftShopContracts.ViewModels; +using GiftShopFileImplement.Models; + +namespace GiftShopFileImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + private readonly DataFileSingleton source; + public MessageInfoStorage() + { + source = DataFileSingleton.GetInstance(); + } + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (string.IsNullOrEmpty(model.MessageId)) + { + return null; + } + return source.Messages.FirstOrDefault(x => + x.MessageId == model.MessageId)?.GetViewModel; + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + if (string.IsNullOrEmpty(model.MessageId)) + { + return new(); + } + 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 = Message.Create(model); + if (newMessage == null) + { + return null; + } + source.Messages.Add(newMessage); + source.SaveMessages(); + return newMessage.GetViewModel; + } + } +} diff --git a/GiftShop/GiftShopFileImplement/Models/Message.cs b/GiftShop/GiftShopFileImplement/Models/Message.cs new file mode 100644 index 0000000..f45793b --- /dev/null +++ b/GiftShop/GiftShopFileImplement/Models/Message.cs @@ -0,0 +1,74 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.ViewModels; +using GiftShopDataModels.Models; +using System.Xml.Linq; + +namespace GiftShopFileImplement.Models +{ + public class Message : 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 Message? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Subject = model.Subject, + DateDelivery = model.DateDelivery, + SenderName = model.SenderName, + ClientId = model.ClientId, + MessageId = model.MessageId + }; + } + + public static Message? Create(XElement element) + { + if (element == null) + { + return null; + } + return new() + { + Body = element.Attribute("Body")!.Value, + Subject = element.Attribute("Subject")!.Value, + DateDelivery = Convert.ToDateTime(element.Attribute("DateDelivery")!.Value), + SenderName = element.Attribute("SenderName")!.Value, + ClientId = Convert.ToInt32(element.Attribute("ClientId")!.Value), + MessageId = element.Attribute("MessageId")!.Value, + }; + } + + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Subject = Subject, + DateDelivery = DateDelivery, + SenderName = SenderName, + ClientId = ClientId, + MessageId = MessageId + }; + + public XElement GetXElement => new("MessageInfo", + new XAttribute("Subject", Subject), + new XAttribute("Body", Body), + new XAttribute("ClientId", ClientId), + new XAttribute("MessageId", MessageId), + new XAttribute("SenderName", SenderName), + new XAttribute("DateDelivery", DateDelivery) + ); + } +} diff --git a/GiftShop/GiftShopListImplement/DataListSingleton.cs b/GiftShop/GiftShopListImplement/DataListSingleton.cs index ec01b43..3ce72ad 100644 --- a/GiftShop/GiftShopListImplement/DataListSingleton.cs +++ b/GiftShop/GiftShopListImplement/DataListSingleton.cs @@ -10,6 +10,7 @@ namespace GiftShopListImplement public List Gifts { get; set; } public List Clients { get; set; } public List Implementers { get; set; } + public List Messages { get; set; } private DataListSingleton() { @@ -18,6 +19,7 @@ namespace GiftShopListImplement Gifts = new List(); Clients = new List(); Implementers = new List(); + Messages = new List(); } public static DataListSingleton GetInstance() { diff --git a/GiftShop/GiftShopListImplement/Implements/MessageInfoStorage.cs b/GiftShop/GiftShopListImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..0755eda --- /dev/null +++ b/GiftShop/GiftShopListImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,70 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.SearchModels; +using GiftShopContracts.StoragesContracts; +using GiftShopContracts.ViewModels; +using GiftShopListImplement.Models; + +namespace GiftShopListImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + private readonly DataListSingleton _source; + public MessageInfoStorage() + { + _source = DataListSingleton.GetInstance(); + } + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (string.IsNullOrEmpty(model.MessageId)) + { + return null; + } + foreach (var message in _source.Messages) + { + if (message.MessageId == model.MessageId) + { + return message.GetViewModel; + } + } + return null; + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + var result = new List(); + if (string.IsNullOrEmpty(model.MessageId)) + { + return result; + } + foreach (var message in _source.Messages) + { + if (message.ClientId == model.ClientId) + { + result.Add(message.GetViewModel); + } + } + return result; + } + + public List GetFullList() + { + var result = new List(); + foreach (var message in _source.Messages) + { + result.Add(message.GetViewModel); + } + return result; + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = Message.Create(model); + if (newMessage == null) + { + return null; + } + _source.Messages.Add(newMessage); + return newMessage.GetViewModel; + } + } +} diff --git a/GiftShop/GiftShopListImplement/Models/Message.cs b/GiftShop/GiftShopListImplement/Models/Message.cs new file mode 100644 index 0000000..a5e90d1 --- /dev/null +++ b/GiftShop/GiftShopListImplement/Models/Message.cs @@ -0,0 +1,48 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.ViewModels; +using GiftShopDataModels.Models; + +namespace GiftShopListImplement.Models +{ + public class Message : 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 Message? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Subject = model.Subject, + DateDelivery = model.DateDelivery, + SenderName = model.SenderName, + ClientId = model.ClientId, + MessageId = model.MessageId + }; + } + + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Subject = Subject, + DateDelivery = DateDelivery, + SenderName = SenderName, + ClientId = ClientId, + MessageId = MessageId + }; + } +} diff --git a/GiftShop/GiftShopRestApi/Controllers/ClientController.cs b/GiftShop/GiftShopRestApi/Controllers/ClientController.cs index 0433cf8..5a0cf6d 100644 --- a/GiftShop/GiftShopRestApi/Controllers/ClientController.cs +++ b/GiftShop/GiftShopRestApi/Controllers/ClientController.cs @@ -14,11 +14,14 @@ namespace GiftShopRestApi.Controllers 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) @@ -65,5 +68,22 @@ namespace GiftShopRestApi.Controllers throw; } } - } + + [HttpGet] + public List? GetMessages(int clientId) + { + try + { + return _mailLogic.ReadList(new MessageInfoSearchModel + { + ClientId = clientId + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения писем клиента"); + throw; + } + } + } } diff --git a/GiftShop/GiftShopRestApi/Program.cs b/GiftShop/GiftShopRestApi/Program.cs index 3bc676c..1b1f54d 100644 --- a/GiftShop/GiftShopRestApi/Program.cs +++ b/GiftShop/GiftShopRestApi/Program.cs @@ -1,4 +1,6 @@ using GiftShopBusinessLogic.BusinessLogics; +using GiftShopBusinessLogic.MailWorker; +using GiftShopContracts.BindingModels; using GiftShopContracts.BusinessLogicsContracts; using GiftShopContracts.StoragesContracts; using GiftShopDatabaseImplement.Implements; @@ -15,11 +17,15 @@ 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.AddTransient(); +builder.Services.AddTransient(); + +builder.Services.AddSingleton(); builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle @@ -31,6 +37,17 @@ 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/GiftShop/GiftShopRestApi/appsettings.json b/GiftShop/GiftShopRestApi/appsettings.json index 10f68b8..8c22c4a 100644 --- a/GiftShop/GiftShopRestApi/appsettings.json +++ b/GiftShop/GiftShopRestApi/appsettings.json @@ -5,5 +5,11 @@ "Microsoft.AspNetCore": "Warning" } }, - "AllowedHosts": "*" + "AllowedHosts": "*", + "SmtpClientHost": "smtp.gmail.com", + "SmtpClientPort": "587", + "PopHost": "pop.gmail.com", + "PopPort": "995", + "MailLogin": "sergunovlab@gmail.com", + "MailPassword": "hzqn cbqi ppqy ycjo" } diff --git a/GiftShop/GiftShopView/App.config b/GiftShop/GiftShopView/App.config new file mode 100644 index 0000000..e1d8c74 --- /dev/null +++ b/GiftShop/GiftShopView/App.config @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/GiftShop/GiftShopView/FormMails.Designer.cs b/GiftShop/GiftShopView/FormMails.Designer.cs new file mode 100644 index 0000000..cf09ad3 --- /dev/null +++ b/GiftShop/GiftShopView/FormMails.Designer.cs @@ -0,0 +1,64 @@ +namespace GiftShopView +{ + partial class FormMails + { + /// + /// 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.BackgroundColor = SystemColors.ControlLightLight; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Dock = DockStyle.Fill; + dataGridView.Location = new Point(0, 0); + dataGridView.Name = "dataGridView"; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 29; + dataGridView.Size = new Size(800, 450); + dataGridView.TabIndex = 0; + // + // FormMails + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(800, 450); + Controls.Add(dataGridView); + Name = "FormMails"; + Text = "Письма"; + Load += FormMails_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView; + } +} \ No newline at end of file diff --git a/GiftShop/GiftShopView/FormMails.cs b/GiftShop/GiftShopView/FormMails.cs new file mode 100644 index 0000000..36590ec --- /dev/null +++ b/GiftShop/GiftShopView/FormMails.cs @@ -0,0 +1,41 @@ +using Microsoft.Extensions.Logging; +using GiftShopContracts.BusinessLogicsContracts; + +namespace GiftShopView +{ + public partial class FormMails : Form + { + private readonly ILogger _logger; + private readonly IMessageInfoLogic _logic; + + public FormMails(ILogger logger, IMessageInfoLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + private void FormMails_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/GiftShop/GiftShopView/FormMails.resx b/GiftShop/GiftShopView/FormMails.resx new file mode 100644 index 0000000..f298a7b --- /dev/null +++ b/GiftShop/GiftShopView/FormMails.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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/GiftShop/GiftShopView/FormMain.Designer.cs b/GiftShop/GiftShopView/FormMain.Designer.cs index ee34174..a874af5 100644 --- a/GiftShop/GiftShopView/FormMain.Designer.cs +++ b/GiftShop/GiftShopView/FormMain.Designer.cs @@ -38,11 +38,12 @@ списокКомпонентовToolStripMenuItem = new ToolStripMenuItem(); компонентыПоИзделиямToolStripMenuItem = new ToolStripMenuItem(); списокЗаказовToolStripMenuItem = new ToolStripMenuItem(); + запускРаботToolStripMenuItem = new ToolStripMenuItem(); dataGridView = new DataGridView(); buttonCreateOrder = new Button(); buttonIssuedOrder = new Button(); buttonRef = new Button(); - запускРаботToolStripMenuItem = new ToolStripMenuItem(); + письмаToolStripMenuItem = new ToolStripMenuItem(); menuStrip.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); SuspendLayout(); @@ -50,7 +51,7 @@ // menuStrip // menuStrip.ImageScalingSize = new Size(20, 20); - menuStrip.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчётыToolStripMenuItem, запускРаботToolStripMenuItem }); + menuStrip.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчётыToolStripMenuItem, запускРаботToolStripMenuItem, письмаToolStripMenuItem }); menuStrip.Location = new Point(0, 0); menuStrip.Name = "menuStrip"; menuStrip.Size = new Size(1367, 28); @@ -120,6 +121,13 @@ списокЗаказовToolStripMenuItem.Text = "Список заказов"; списокЗаказовToolStripMenuItem.Click += OrdersToolStripMenuItem_Click; // + // запускРаботToolStripMenuItem + // + запускРаботToolStripMenuItem.Name = "запускРаботToolStripMenuItem"; + запускРаботToolStripMenuItem.Size = new Size(114, 24); + запускРаботToolStripMenuItem.Text = "Запуск работ"; + запускРаботToolStripMenuItem.Click += запускРаботToolStripMenuItem_Click; + // // dataGridView // dataGridView.BackgroundColor = SystemColors.ControlLightLight; @@ -161,12 +169,12 @@ buttonRef.UseVisualStyleBackColor = true; buttonRef.Click += ButtonRef_Click; // - // запускРаботToolStripMenuItem + // письмаToolStripMenuItem // - запускРаботToolStripMenuItem.Name = "запускРаботToolStripMenuItem"; - запускРаботToolStripMenuItem.Size = new Size(114, 24); - запускРаботToolStripMenuItem.Text = "Запуск работ"; - запускРаботToolStripMenuItem.Click += запускРаботToolStripMenuItem_Click; + письмаToolStripMenuItem.Name = "письмаToolStripMenuItem"; + письмаToolStripMenuItem.Size = new Size(77, 24); + письмаToolStripMenuItem.Text = "Письма"; + письмаToolStripMenuItem.Click += письмаToolStripMenuItem_Click; // // FormMain // @@ -206,5 +214,6 @@ private ToolStripMenuItem клиентыToolStripMenuItem; private ToolStripMenuItem исполнителиToolStripMenuItem; private ToolStripMenuItem запускРаботToolStripMenuItem; + private ToolStripMenuItem письмаToolStripMenuItem; } } \ No newline at end of file diff --git a/GiftShop/GiftShopView/FormMain.cs b/GiftShop/GiftShopView/FormMain.cs index afe2dd6..102e778 100644 --- a/GiftShop/GiftShopView/FormMain.cs +++ b/GiftShop/GiftShopView/FormMain.cs @@ -177,5 +177,14 @@ namespace GiftShopView .GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic); MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); } + + private void письмаToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormMails)); + if (service is FormMails form) + { + form.ShowDialog(); + } + } } } diff --git a/GiftShop/GiftShopView/GiftShopView.csproj b/GiftShop/GiftShopView/GiftShopView.csproj index e75c4c7..56e6506 100644 --- a/GiftShop/GiftShopView/GiftShopView.csproj +++ b/GiftShop/GiftShopView/GiftShopView.csproj @@ -39,6 +39,9 @@ + + Always + Always diff --git a/GiftShop/GiftShopView/Program.cs b/GiftShop/GiftShopView/Program.cs index 361ffb7..504be58 100644 --- a/GiftShop/GiftShopView/Program.cs +++ b/GiftShop/GiftShopView/Program.cs @@ -7,6 +7,8 @@ using GiftShopDatabaseImplement.Implements; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; +using GiftShopBusinessLogic.MailWorker; +using GiftShopContracts.BindingModels; namespace GiftShopView { @@ -21,7 +23,27 @@ namespace GiftShopView 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, " "); + } + Application.Run(_serviceProvider.GetRequiredService()); } private static void ConfigureServices(ServiceCollection services) @@ -36,6 +58,7 @@ namespace GiftShopView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -43,13 +66,15 @@ namespace GiftShopView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddSingleton(); - services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -61,6 +86,9 @@ namespace GiftShopView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); } - } + + private static void MailCheck(object obj) => ServiceProvider?.GetService()?.MailCheck(); + } } \ No newline at end of file