From d080e573ce231fe48e193778611e4c0cac4c55c6 Mon Sep 17 00:00:00 2001 From: Yourdax Date: Sun, 28 Apr 2024 09:02:29 +0400 Subject: [PATCH] =?UTF-8?q?Autification=20failed=20=D0=BD=D0=B0=D0=B4?= =?UTF-8?q?=D0=BE=20=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2=D0=BB=D1=8F=D1=82?= =?UTF-8?q?=D1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../BusinessLogics/ClientLogic.cs | 26 ++-- .../BusinessLogics/MessageInfoLogic.cs | 65 ++++++++++ .../BusinessLogics/OrderLogic.cs | 64 +++++++--- .../CarpentryWorkshopBusinessLogic.csproj | 1 + .../MailWorker/AbstractMailWorker.cs | 68 ++++++++++ .../MailWorker/MailKitWorker.cs | 80 ++++++++++++ .../Controllers/HomeController.cs | 9 ++ .../Views/Home/Mails.cshtml | 54 ++++++++ .../Views/Shared/_Layout.cshtml | 3 + .../BindingModels/MailConfigBindingModel.cs | 18 +++ .../BindingModels/MailSendInfoBindingModel.cs | 15 +++ .../BindingModels/MessageInfoBindingModel.cs | 19 +++ .../IMessageInfoLogic.cs | 13 ++ .../SearchModels/MessageInfoSearchModel.cs | 9 ++ .../StoragesContracts/IMessageInfoStorage.cs | 18 +++ .../ViewModels/MessageInfoViewModel.cs | 24 ++++ .../Models/IMessageInfoModel.cs | 12 ++ .../CarpentryWorkshopDatabase.cs | 1 + .../Implements/ClientStorage.cs | 68 +++++----- .../Implements/MessageInfoStorage.cs | 64 ++++++++++ ... 20240428043913_InitialCreate.Designer.cs} | 47 ++++++- ...ate.cs => 20240428043913_InitialCreate.cs} | 29 +++++ .../CarpentryWorkshopDatabaseModelSnapshot.cs | 45 ++++++- .../Models/Client.cs | 56 ++++----- .../Models/MessageInfo.cs | 67 ++++++++++ .../DataFileSingleton.cs | 4 + .../Implements/ClientStorage.cs | 117 +++++++++--------- .../Implements/MessageInfoStorage.cs | 66 ++++++++++ .../Models/Client.cs | 25 ++-- .../Models/Message.cs | 87 +++++++++++++ .../DataListSingleton.cs | 2 + .../Implements/ClientStorage.cs | 107 +++++++--------- .../Implements/MessageInfoStorage.cs | 81 ++++++++++++ .../Models/Client.cs | 11 +- .../Models/Message.cs | 58 +++++++++ .../Controllers/ClientController.cs | 23 +++- .../CarpentryWorkshopRestApi/Program.cs | 30 +++-- .../CarpentryWorkshopRestApi/appsettings.json | 12 +- .../CarpentryWorkshopView/App.config | 11 ++ .../FormMail.Designer.cs | 60 +++++++++ .../CarpentryWorkshopView/FormMail.cs | 56 +++++++++ .../CarpentryWorkshopView/FormMail.resx | 60 +++++++++ .../FormMain.Designer.cs | 11 +- .../CarpentryWorkshopView/FormMain.cs | 8 ++ .../CarpentryWorkshopView/Program.cs | 27 ++++ 45 files changed, 1475 insertions(+), 256 deletions(-) create mode 100644 CarpentryWorkshop/CarpentryWorkshopBusinessLogic/BusinessLogics/MessageInfoLogic.cs create mode 100644 CarpentryWorkshop/CarpentryWorkshopBusinessLogic/MailWorker/AbstractMailWorker.cs create mode 100644 CarpentryWorkshop/CarpentryWorkshopBusinessLogic/MailWorker/MailKitWorker.cs create mode 100644 CarpentryWorkshop/CarpentryWorkshopClientApp/Views/Home/Mails.cshtml create mode 100644 CarpentryWorkshop/CarpentryWorkshopContracts/BindingModels/MailConfigBindingModel.cs create mode 100644 CarpentryWorkshop/CarpentryWorkshopContracts/BindingModels/MailSendInfoBindingModel.cs create mode 100644 CarpentryWorkshop/CarpentryWorkshopContracts/BindingModels/MessageInfoBindingModel.cs create mode 100644 CarpentryWorkshop/CarpentryWorkshopContracts/BusinessLogicsContracts/IMessageInfoLogic.cs create mode 100644 CarpentryWorkshop/CarpentryWorkshopContracts/SearchModels/MessageInfoSearchModel.cs create mode 100644 CarpentryWorkshop/CarpentryWorkshopContracts/StoragesContracts/IMessageInfoStorage.cs create mode 100644 CarpentryWorkshop/CarpentryWorkshopContracts/ViewModels/MessageInfoViewModel.cs create mode 100644 CarpentryWorkshop/CarpentryWorkshopDataModels/Models/IMessageInfoModel.cs create mode 100644 CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Implements/MessageInfoStorage.cs rename CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Migrations/{20240427190111_InitialCreate.Designer.cs => 20240428043913_InitialCreate.Designer.cs} (84%) rename CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Migrations/{20240427190111_InitialCreate.cs => 20240428043913_InitialCreate.cs} (86%) create mode 100644 CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Models/MessageInfo.cs create mode 100644 CarpentryWorkshop/CarpentryWorkshopFileImplement/Implements/MessageInfoStorage.cs create mode 100644 CarpentryWorkshop/CarpentryWorkshopFileImplement/Models/Message.cs create mode 100644 CarpentryWorkshop/CarpentryWorkshopListImplement/Implements/MessageInfoStorage.cs create mode 100644 CarpentryWorkshop/CarpentryWorkshopListImplement/Models/Message.cs create mode 100644 CarpentryWorkshop/CarpentryWorkshopView/App.config create mode 100644 CarpentryWorkshop/CarpentryWorkshopView/FormMail.Designer.cs create mode 100644 CarpentryWorkshop/CarpentryWorkshopView/FormMail.cs create mode 100644 CarpentryWorkshop/CarpentryWorkshopView/FormMail.resx diff --git a/CarpentryWorkshop/CarpentryWorkshopBusinessLogic/BusinessLogics/ClientLogic.cs b/CarpentryWorkshop/CarpentryWorkshopBusinessLogic/BusinessLogics/ClientLogic.cs index 704733e..674d93c 100644 --- a/CarpentryWorkshop/CarpentryWorkshopBusinessLogic/BusinessLogics/ClientLogic.cs +++ b/CarpentryWorkshop/CarpentryWorkshopBusinessLogic/BusinessLogics/ClientLogic.cs @@ -8,6 +8,7 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; +using System.Text.RegularExpressions; using System.Threading.Tasks; namespace CarpentryWorkshopBusinessLogic.BusinessLogics @@ -16,11 +17,13 @@ namespace CarpentryWorkshopBusinessLogic.BusinessLogics { 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); @@ -50,7 +53,7 @@ namespace CarpentryWorkshopBusinessLogic.BusinessLogics { throw new ArgumentNullException(nameof(model)); } - _logger.LogInformation("ReadElement. ClientFIO:{ClientFIO}. Id:{ Id}", model.ClientFIO, model.Id); + _logger.LogInformation("ReadElement. ClientFIO:{ClientFIO}. Email: {Email}. Id:{ Id}", model.ClientFIO, model.Email, model.Id); var element = _clientStorage.GetElement(model); if (element == null) { @@ -63,7 +66,7 @@ namespace CarpentryWorkshopBusinessLogic.BusinessLogics public List? ReadList(ClientSearchModel? model) { - _logger.LogInformation("ReadList. ClientFIO:{ClientFIO}. Id:{Id}", model?.ClientFIO, model?.Id); + _logger.LogInformation("ReadList. ClientId:{Id}", model?.Id); var list = model == null ? _clientStorage.GetFullList() : _clientStorage.GetFilteredList(model); if (list == null) { @@ -84,6 +87,7 @@ namespace CarpentryWorkshopBusinessLogic.BusinessLogics } return true; } + private void CheckModel(ClientBindingModel model, bool withParams = true) { if (model == null) @@ -96,24 +100,32 @@ namespace CarpentryWorkshopBusinessLogic.BusinessLogics } if (string.IsNullOrEmpty(model.ClientFIO)) { - throw new ArgumentNullException("Нет ФИО клиента", nameof(model.ClientFIO)); + throw new ArgumentNullException("Нет ФИО пользователя", nameof(model.ClientFIO)); } if (string.IsNullOrEmpty(model.Email)) { - throw new ArgumentNullException("У клиента отсутствует почта", nameof(model.Email)); + throw new ArgumentNullException("Нет почты клиента", nameof(model.Email)); } if (string.IsNullOrEmpty(model.Password)) { - throw new ArgumentNullException("У клиента отсутствует пароль", nameof(model.Email)); + throw new ArgumentNullException("Нет пароля клиента", nameof(model.Password)); } - _logger.LogInformation("Client. ClientID:{Id}. ClientFIO: {ClientFIO}. Email:{ Email}. Password: { Password}", model.Id, model.ClientFIO, model.Email, model.Password); + if (!Regex.IsMatch(model.Email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$", RegexOptions.IgnoreCase)) + { + throw new ArgumentException("Неправильно введенный email", nameof(model.Email)); + } + if (!Regex.IsMatch(model.Password, @"^^((\w+\d+\W+)|(\w+\W+\d+)|(\d+\w+\W+)|(\d+\W+\w+)|(\W+\w+\d+)|(\W+\d+\w+))[\w\d\W]*$", RegexOptions.IgnoreCase) || model.Password.Length < 10 || model.Password.Length > 50) + { + throw new ArgumentException("Неправильно введенный пароль", 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("Такой клиент уже существует"); + throw new InvalidOperationException("Клиент с таким именем уже есть"); } } } diff --git a/CarpentryWorkshop/CarpentryWorkshopBusinessLogic/BusinessLogics/MessageInfoLogic.cs b/CarpentryWorkshop/CarpentryWorkshopBusinessLogic/BusinessLogics/MessageInfoLogic.cs new file mode 100644 index 0000000..fe4c81b --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopBusinessLogic/BusinessLogics/MessageInfoLogic.cs @@ -0,0 +1,65 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.BusinessLogicsContracts; +using CarpentryWorkshopContracts.SearchModels; +using CarpentryWorkshopContracts.StoragesContracts; +using CarpentryWorkshopContracts.ViewModels; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CarpentryWorkshopBusinessLogic.BusinessLogics +{ + public class MessageInfoLogic : IMessageInfoLogic + { + private readonly ILogger _logger; + private readonly IMessageInfoStorage _messageInfoStorage; + public MessageInfoLogic(ILogger logger, IMessageInfoStorage messageInfoStorage) + { + _logger = logger; + _messageInfoStorage = messageInfoStorage; + } + + public bool Create(MessageInfoBindingModel model) + { + + var element = _messageInfoStorage.GetElement(new MessageInfoSearchModel + { + MessageId = model.MessageId + }); + if (element != null) + { + if (_messageInfoStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + return true; + } + else + { + if (_messageInfoStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } + } + + public List? ReadList(MessageInfoSearchModel? model) + { + _logger.LogInformation("ReadList. ClientId:{ClientId}", model?.ClientId); + var list = model == null ? _messageInfoStorage.GetFullList() : _messageInfoStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + _logger.LogInformation("ReadList. Count:{Count}", list.Count); + return list; + } + } +} diff --git a/CarpentryWorkshop/CarpentryWorkshopBusinessLogic/BusinessLogics/OrderLogic.cs b/CarpentryWorkshop/CarpentryWorkshopBusinessLogic/BusinessLogics/OrderLogic.cs index f0f1b72..1d7deb7 100644 --- a/CarpentryWorkshop/CarpentryWorkshopBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/CarpentryWorkshop/CarpentryWorkshopBusinessLogic/BusinessLogics/OrderLogic.cs @@ -1,4 +1,5 @@ -using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopBusinessLogic.MailWorker; +using CarpentryWorkshopContracts.BindingModels; using CarpentryWorkshopContracts.BusinessLogicsContracts; using CarpentryWorkshopContracts.SearchModels; using CarpentryWorkshopContracts.StoragesContracts; @@ -7,9 +8,11 @@ using CarpentryWorkshopDataModels.Enums; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; +using System.Xml.Linq; namespace CarpentryWorkshopBusinessLogic.BusinessLogics { @@ -17,11 +20,15 @@ namespace CarpentryWorkshopBusinessLogic.BusinessLogics { private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; + private readonly AbstractMailWorker _mailWorker; + private readonly IClientLogic _clientLogic; - public OrderLogic(ILogger logger, IOrderStorage orderStorage) + public OrderLogic(ILogger logger, IOrderStorage orderStorage, AbstractMailWorker mailWorker, IClientLogic clientLogic) { _logger = logger; _orderStorage = orderStorage; + _mailWorker = mailWorker; + _clientLogic = clientLogic; } public bool CreateOrder(OrderBindingModel model) @@ -35,14 +42,17 @@ namespace CarpentryWorkshopBusinessLogic.BusinessLogics } model.Status = OrderStatus.Принят; + var result = _orderStorage.Insert(model); - if (_orderStorage.Insert(model) == null) + if (result == null) { model.Status = OrderStatus.Неизвестен; _logger.LogWarning("Insert operation failed"); return false; } + SendOrderMessage(result.ClientId, $"Установка ПО, Заказ №{result.Id}", $"Заказ №{result.Id} от {result.DateCreate} на сумму {result.Sum:0.00} принят"); + return true; } @@ -76,13 +86,36 @@ namespace CarpentryWorkshopBusinessLogic.BusinessLogics model.Sum = vmodel.Sum; model.Count = vmodel.Count; - if (_orderStorage.Update(model) == null) + var result = _orderStorage.Update(model); + + if (result == null) { _logger.LogWarning("Update operation failed"); return false; } + + SendOrderMessage(result.ClientId, $"Установка ПО, Заказ №{result.Id}", $"Заказ №{model.Id} изменен статус на {result.Status}"); + return true; + } + + 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; } @@ -93,7 +126,7 @@ namespace CarpentryWorkshopBusinessLogic.BusinessLogics public bool DeliveryOrder(OrderBindingModel model) { - model.DateImplement = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc); + model.DateImplement = DateTime.Now; return StatusUpdate(model, OrderStatus.Готов); } @@ -118,26 +151,29 @@ namespace CarpentryWorkshopBusinessLogic.BusinessLogics return list; } - private bool CheckModel(OrderBindingModel model) + private void CheckModel(OrderBindingModel model, bool withParams = true) { if (model == null) { throw new ArgumentNullException(nameof(model)); } + if (!withParams) + { + return; + } + if (model.WoodId < 0) + { + throw new ArgumentNullException("Некорректный идентификатор у изделия", nameof(model.WoodId)); + } if (model.Count <= 0) { - throw new ArgumentException("Количество изделий в заказе должно быть больше 0", nameof(model.Count)); + throw new ArgumentNullException("Количество изделий в заказе должно быть больше 0", nameof(model.Count)); } if (model.Sum <= 0) { - throw new ArgumentException("Суммарная стоимость заказа должна быть больше 0", nameof(model.Sum)); + throw new ArgumentNullException("Сумма заказа должна быть больше 0", nameof(model.Sum)); } - if (model.DateCreate > model.DateImplement) - { - throw new ArgumentException("Время создания заказа не может быть больше времени его выполнения", nameof(model.DateImplement)); - } - - return true; + _logger.LogInformation("Order. OrderID:{Id}. Sum:{ Sum}. WoodId: { WoodId}", model.Id, model.Sum, model.WoodId); } public OrderViewModel? ReadElement(OrderSearchModel model) diff --git a/CarpentryWorkshop/CarpentryWorkshopBusinessLogic/CarpentryWorkshopBusinessLogic.csproj b/CarpentryWorkshop/CarpentryWorkshopBusinessLogic/CarpentryWorkshopBusinessLogic.csproj index 6cf787f..e5b252f 100644 --- a/CarpentryWorkshop/CarpentryWorkshopBusinessLogic/CarpentryWorkshopBusinessLogic.csproj +++ b/CarpentryWorkshop/CarpentryWorkshopBusinessLogic/CarpentryWorkshopBusinessLogic.csproj @@ -8,6 +8,7 @@ + diff --git a/CarpentryWorkshop/CarpentryWorkshopBusinessLogic/MailWorker/AbstractMailWorker.cs b/CarpentryWorkshop/CarpentryWorkshopBusinessLogic/MailWorker/AbstractMailWorker.cs new file mode 100644 index 0000000..1466d44 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopBusinessLogic/MailWorker/AbstractMailWorker.cs @@ -0,0 +1,68 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; + +namespace CarpentryWorkshopBusinessLogic.MailWorker +{ + public abstract class AbstractMailWorker + { + protected string _mailLogin; + protected string _mailPassword; + protected string _smtpClientHost; + protected int _smtpClientPort; + protected string _popHost; + protected int _popPort; + private IMessageInfoLogic _messageInfoLogic; + public AbstractMailWorker(IMessageInfoLogic messageInfoLogic) + { + _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; + } + 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; + } + 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(); + 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/CarpentryWorkshop/CarpentryWorkshopBusinessLogic/MailWorker/MailKitWorker.cs b/CarpentryWorkshop/CarpentryWorkshopBusinessLogic/MailWorker/MailKitWorker.cs new file mode 100644 index 0000000..0d6a95b --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopBusinessLogic/MailWorker/MailKitWorker.cs @@ -0,0 +1,80 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.BusinessLogicsContracts; +using CarpentryWorkshopContracts.SearchModels; +using CarpentryWorkshopContracts.StoragesContracts; +using MailKit.Net.Pop3; +using MailKit.Security; +using Microsoft.Extensions.Logging; +using System.Net; +using System.Net.Mail; +using System.Text; + +namespace CarpentryWorkshopBusinessLogic.MailWorker +{ + public class MailKitWorker : AbstractMailWorker + { + private IClientStorage _clientStorage; + public MailKitWorker(IMessageInfoLogic messageInfoLogic, IClientStorage clientStorage) : base(messageInfoLogic) + { + _clientStorage = clientStorage; + } + 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 + { + ClientId = _clientStorage.GetElement(new ClientSearchModel { Email = mail.Address })?.Id, + DateDelivery = message.Date.DateTime, + MessageId = message.MessageId, + SenderName = mail.Address, + Subject = message.Subject, + Body = message.TextBody + }); + } + } + } + finally + { + client.Disconnect(true); + } + }); + return list; + } + } +} \ No newline at end of file diff --git a/CarpentryWorkshop/CarpentryWorkshopClientApp/Controllers/HomeController.cs b/CarpentryWorkshop/CarpentryWorkshopClientApp/Controllers/HomeController.cs index 518a9f8..225cbad 100644 --- a/CarpentryWorkshop/CarpentryWorkshopClientApp/Controllers/HomeController.cs +++ b/CarpentryWorkshop/CarpentryWorkshopClientApp/Controllers/HomeController.cs @@ -149,5 +149,14 @@ namespace CarpentryWorkshopClientApp.Controllers var prod = APIClient.GetRequest($"api/main/getwood?woodId={wood}"); 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}")); + } } } \ No newline at end of file diff --git a/CarpentryWorkshop/CarpentryWorkshopClientApp/Views/Home/Mails.cshtml b/CarpentryWorkshop/CarpentryWorkshopClientApp/Views/Home/Mails.cshtml new file mode 100644 index 0000000..3a177ef --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopClientApp/Views/Home/Mails.cshtml @@ -0,0 +1,54 @@ +@using CarpentryWorkshopContracts.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) +
+ } +
diff --git a/CarpentryWorkshop/CarpentryWorkshopClientApp/Views/Shared/_Layout.cshtml b/CarpentryWorkshop/CarpentryWorkshopClientApp/Views/Shared/_Layout.cshtml index 0390638..b7f8dbc 100644 --- a/CarpentryWorkshop/CarpentryWorkshopClientApp/Views/Shared/_Layout.cshtml +++ b/CarpentryWorkshop/CarpentryWorkshopClientApp/Views/Shared/_Layout.cshtml @@ -28,6 +28,9 @@ + diff --git a/CarpentryWorkshop/CarpentryWorkshopContracts/BindingModels/MailConfigBindingModel.cs b/CarpentryWorkshop/CarpentryWorkshopContracts/BindingModels/MailConfigBindingModel.cs new file mode 100644 index 0000000..a50fe43 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopContracts/BindingModels/MailConfigBindingModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CarpentryWorkshopContracts.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/CarpentryWorkshop/CarpentryWorkshopContracts/BindingModels/MailSendInfoBindingModel.cs b/CarpentryWorkshop/CarpentryWorkshopContracts/BindingModels/MailSendInfoBindingModel.cs new file mode 100644 index 0000000..20e09aa --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopContracts/BindingModels/MailSendInfoBindingModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CarpentryWorkshopContracts.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/CarpentryWorkshop/CarpentryWorkshopContracts/BindingModels/MessageInfoBindingModel.cs b/CarpentryWorkshop/CarpentryWorkshopContracts/BindingModels/MessageInfoBindingModel.cs new file mode 100644 index 0000000..4d31cfc --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopContracts/BindingModels/MessageInfoBindingModel.cs @@ -0,0 +1,19 @@ +using CarpentryWorkshopDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CarpentryWorkshopContracts.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/CarpentryWorkshop/CarpentryWorkshopContracts/BusinessLogicsContracts/IMessageInfoLogic.cs b/CarpentryWorkshop/CarpentryWorkshopContracts/BusinessLogicsContracts/IMessageInfoLogic.cs new file mode 100644 index 0000000..8cd8d66 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopContracts/BusinessLogicsContracts/IMessageInfoLogic.cs @@ -0,0 +1,13 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.SearchModels; +using CarpentryWorkshopContracts.ViewModels; + +namespace CarpentryWorkshopContracts.BusinessLogicsContracts +{ + public interface IMessageInfoLogic + { + List? ReadList(MessageInfoSearchModel? model); + + bool Create(MessageInfoBindingModel model); + } +} \ No newline at end of file diff --git a/CarpentryWorkshop/CarpentryWorkshopContracts/SearchModels/MessageInfoSearchModel.cs b/CarpentryWorkshop/CarpentryWorkshopContracts/SearchModels/MessageInfoSearchModel.cs new file mode 100644 index 0000000..9427672 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopContracts/SearchModels/MessageInfoSearchModel.cs @@ -0,0 +1,9 @@ +namespace CarpentryWorkshopContracts.SearchModels +{ + public class MessageInfoSearchModel + { + public int? ClientId { get; set; } + + public string? MessageId { get; set; } + } +} \ No newline at end of file diff --git a/CarpentryWorkshop/CarpentryWorkshopContracts/StoragesContracts/IMessageInfoStorage.cs b/CarpentryWorkshop/CarpentryWorkshopContracts/StoragesContracts/IMessageInfoStorage.cs new file mode 100644 index 0000000..a7a959e --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopContracts/StoragesContracts/IMessageInfoStorage.cs @@ -0,0 +1,18 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.SearchModels; +using CarpentryWorkshopContracts.ViewModels; + +namespace CarpentryWorkshopContracts.StoragesContracts +{ + public interface IMessageInfoStorage + { + List GetFullList(); + + List GetFilteredList(MessageInfoSearchModel model); + + MessageInfoViewModel? GetElement(MessageInfoSearchModel model); + + MessageInfoViewModel? Insert(MessageInfoBindingModel model); + MessageInfoViewModel? Update(MessageInfoBindingModel model); + } +} \ No newline at end of file diff --git a/CarpentryWorkshop/CarpentryWorkshopContracts/ViewModels/MessageInfoViewModel.cs b/CarpentryWorkshop/CarpentryWorkshopContracts/ViewModels/MessageInfoViewModel.cs new file mode 100644 index 0000000..597eed5 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopContracts/ViewModels/MessageInfoViewModel.cs @@ -0,0 +1,24 @@ +using CarpentryWorkshopDataModels.Models; +using System.ComponentModel; + +namespace CarpentryWorkshopContracts.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/CarpentryWorkshop/CarpentryWorkshopDataModels/Models/IMessageInfoModel.cs b/CarpentryWorkshop/CarpentryWorkshopDataModels/Models/IMessageInfoModel.cs new file mode 100644 index 0000000..fec8b6a --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopDataModels/Models/IMessageInfoModel.cs @@ -0,0 +1,12 @@ +namespace CarpentryWorkshopDataModels.Models +{ + public interface IMessageInfoModel + { + string MessageId { get; } + int? ClientId { get; } + string SenderName { get; } + DateTime DateDelivery { get; } + string Subject { get; } + string Body { get; } + } +} \ No newline at end of file diff --git a/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/CarpentryWorkshopDatabase.cs b/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/CarpentryWorkshopDatabase.cs index 0537949..072db41 100644 --- a/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/CarpentryWorkshopDatabase.cs +++ b/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/CarpentryWorkshopDatabase.cs @@ -24,5 +24,6 @@ namespace CarpentryWorkshopDatabaseImplement 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/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Implements/ClientStorage.cs b/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Implements/ClientStorage.cs index abf6c78..0abec1d 100644 --- a/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Implements/ClientStorage.cs +++ b/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Implements/ClientStorage.cs @@ -16,50 +16,37 @@ namespace CarpentryWorkshopDatabaseImplement.Implements public ClientViewModel? Delete(ClientBindingModel model) { using var context = new CarpentryWorkshopDatabase(); - var res = context.Clients.FirstOrDefault(x => x.Id == model.Id); - if (res != null) + var element = context.Clients.FirstOrDefault(rec => rec.Id == model.Id); + if (element != null) { - context.Clients.Remove(res); + context.Clients.Remove(element); context.SaveChanges(); + return element.GetViewModel; } - return res?.GetViewModel; + return null; } public ClientViewModel? GetElement(ClientSearchModel model) { + if (string.IsNullOrEmpty(model.Email) && string.IsNullOrEmpty(model.Password) && !model.Id.HasValue) + { + return null; + } using var context = new CarpentryWorkshopDatabase(); - if (model.Id.HasValue) - return context.Clients.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; - if (model.Email != null && model.Password != null) - return context.Clients - .FirstOrDefault(x => x.Email.Equals(model.Email) - && x.Password.Equals(model.Password)) - ?.GetViewModel; - if (model.Email != null) - return context.Clients.FirstOrDefault(x => x.Email.Equals(model.Email))?.GetViewModel; - return null; + 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 List GetFilteredList(ClientSearchModel model) { - if (model == null) + if (string.IsNullOrEmpty(model.ClientFIO)) { return new(); } - if (model.Id.HasValue) - { - var res = GetElement(model); - return res != null ? new() { res } : new(); - } - if (model.Email != null) - { - using var context = new CarpentryWorkshopDatabase(); - return context.Clients - .Where(x => x.Email.Contains(model.Email)) - .Select(x => x.GetViewModel) - .ToList(); - } - return new(); + using var context = new CarpentryWorkshopDatabase(); + return context.Clients.Where(x => x.ClientFIO.Contains(model.ClientFIO)).Select(x => x.GetViewModel).ToList(); } public List GetFullList() @@ -70,23 +57,28 @@ namespace CarpentryWorkshopDatabaseImplement.Implements public ClientViewModel? Insert(ClientBindingModel model) { - using var context = new CarpentryWorkshopDatabase(); - var res = Client.Create(model); - if (res != null) + var newComponent = Client.Create(model); + if (newComponent == null) { - context.Clients.Add(res); - context.SaveChanges(); + return null; } - return res?.GetViewModel; + using var context = new CarpentryWorkshopDatabase(); + context.Clients.Add(newComponent); + context.SaveChanges(); + return newComponent.GetViewModel; } public ClientViewModel? Update(ClientBindingModel model) { using var context = new CarpentryWorkshopDatabase(); - var res = context.Clients.FirstOrDefault(x => x.Id == model.Id); - res?.Update(model); + var component = context.Clients.FirstOrDefault(x => x.Id == model.Id); + if (component == null) + { + return null; + } + component.Update(model); context.SaveChanges(); - return res?.GetViewModel; + return component.GetViewModel; } } } diff --git a/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Implements/MessageInfoStorage.cs b/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..c943e0e --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,64 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.SearchModels; +using CarpentryWorkshopContracts.StoragesContracts; +using CarpentryWorkshopContracts.ViewModels; +using CarpentryWorkshopDatabaseImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CarpentryWorkshopDatabaseImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + public List GetFullList() + { + using var context = new CarpentryWorkshopDatabase(); + return context.MessageInfos.Select(x => x.GetViewModel).ToList(); + } + public List GetFilteredList(MessageInfoSearchModel model) + { + if (!model.ClientId.HasValue) + { + return new(); + } + using var context = new CarpentryWorkshopDatabase(); + 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 CarpentryWorkshopDatabase(); + 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 CarpentryWorkshopDatabase(); + context.MessageInfos.Add(newMessage); + context.SaveChanges(); + return newMessage.GetViewModel; + } + public MessageInfoViewModel? Update(MessageInfoBindingModel model) + { + using var context = new CarpentryWorkshopDatabase(); + var component = context.MessageInfos.FirstOrDefault(x => x.MessageId == model.MessageId); + if (component == null) + { + return null; + } + component.Update(model); + context.SaveChanges(); + return component.GetViewModel; + } + } +} diff --git a/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Migrations/20240427190111_InitialCreate.Designer.cs b/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Migrations/20240428043913_InitialCreate.Designer.cs similarity index 84% rename from CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Migrations/20240427190111_InitialCreate.Designer.cs rename to CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Migrations/20240428043913_InitialCreate.Designer.cs index 1024bdf..43dab7f 100644 --- a/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Migrations/20240427190111_InitialCreate.Designer.cs +++ b/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Migrations/20240428043913_InitialCreate.Designer.cs @@ -12,7 +12,7 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; namespace CarpentryWorkshopDatabaseImplement.Migrations { [DbContext(typeof(CarpentryWorkshopDatabase))] - [Migration("20240427190111_InitialCreate")] + [Migration("20240428043913_InitialCreate")] partial class InitialCreate { /// @@ -97,6 +97,36 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations b.ToTable("Implementers"); }); + modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.MessageInfo", b => + { + b.Property("MessageId") + .HasColumnType("text"); + + b.Property("Body") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientId") + .HasColumnType("integer"); + + b.Property("DateDelivery") + .HasColumnType("timestamp with time zone"); + + b.Property("SenderName") + .IsRequired() + .HasColumnType("text"); + + b.Property("Subject") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("MessageId"); + + b.HasIndex("ClientId"); + + b.ToTable("MessageInfos"); + }); + modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -186,10 +216,19 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations b.ToTable("WoodComponents"); }); + modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.MessageInfo", b => + { + b.HasOne("CarpentryWorkshopDatabaseImplement.Models.Client", "Client") + .WithMany("ClientMessages") + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Order", b => { b.HasOne("CarpentryWorkshopDatabaseImplement.Models.Client", "Client") - .WithMany("Orders") + .WithMany("ClientOrders") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); @@ -232,7 +271,9 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Client", b => { - b.Navigation("Orders"); + b.Navigation("ClientMessages"); + + b.Navigation("ClientOrders"); }); modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Component", b => diff --git a/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Migrations/20240427190111_InitialCreate.cs b/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Migrations/20240428043913_InitialCreate.cs similarity index 86% rename from CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Migrations/20240427190111_InitialCreate.cs rename to CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Migrations/20240428043913_InitialCreate.cs index 9c8122e..9af448a 100644 --- a/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Migrations/20240427190111_InitialCreate.cs +++ b/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Migrations/20240428043913_InitialCreate.cs @@ -71,6 +71,27 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations table.PrimaryKey("PK_Woods", x => x.Id); }); + migrationBuilder.CreateTable( + name: "MessageInfos", + columns: table => new + { + MessageId = table.Column(type: "text", nullable: false), + ClientId = table.Column(type: "integer", nullable: true), + SenderName = table.Column(type: "text", nullable: false), + DateDelivery = table.Column(type: "timestamp with time zone", nullable: false), + Subject = table.Column(type: "text", nullable: false), + Body = table.Column(type: "text", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_MessageInfos", x => x.MessageId); + table.ForeignKey( + name: "FK_MessageInfos_Clients_ClientId", + column: x => x.ClientId, + principalTable: "Clients", + principalColumn: "Id"); + }); + migrationBuilder.CreateTable( name: "Orders", columns: table => new @@ -135,6 +156,11 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations onDelete: ReferentialAction.Cascade); }); + migrationBuilder.CreateIndex( + name: "IX_MessageInfos_ClientId", + table: "MessageInfos", + column: "ClientId"); + migrationBuilder.CreateIndex( name: "IX_Orders_ClientId", table: "Orders", @@ -164,6 +190,9 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations /// protected override void Down(MigrationBuilder migrationBuilder) { + migrationBuilder.DropTable( + name: "MessageInfos"); + migrationBuilder.DropTable( name: "Orders"); diff --git a/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Migrations/CarpentryWorkshopDatabaseModelSnapshot.cs b/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Migrations/CarpentryWorkshopDatabaseModelSnapshot.cs index 6300d49..4ae69cd 100644 --- a/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Migrations/CarpentryWorkshopDatabaseModelSnapshot.cs +++ b/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Migrations/CarpentryWorkshopDatabaseModelSnapshot.cs @@ -94,6 +94,36 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations b.ToTable("Implementers"); }); + modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.MessageInfo", b => + { + b.Property("MessageId") + .HasColumnType("text"); + + b.Property("Body") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientId") + .HasColumnType("integer"); + + b.Property("DateDelivery") + .HasColumnType("timestamp with time zone"); + + b.Property("SenderName") + .IsRequired() + .HasColumnType("text"); + + b.Property("Subject") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("MessageId"); + + b.HasIndex("ClientId"); + + b.ToTable("MessageInfos"); + }); + modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -183,10 +213,19 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations b.ToTable("WoodComponents"); }); + modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.MessageInfo", b => + { + b.HasOne("CarpentryWorkshopDatabaseImplement.Models.Client", "Client") + .WithMany("ClientMessages") + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Order", b => { b.HasOne("CarpentryWorkshopDatabaseImplement.Models.Client", "Client") - .WithMany("Orders") + .WithMany("ClientOrders") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); @@ -229,7 +268,9 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Client", b => { - b.Navigation("Orders"); + b.Navigation("ClientMessages"); + + b.Navigation("ClientOrders"); }); modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Component", b => diff --git a/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Models/Client.cs b/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Models/Client.cs index ae2e289..3eaef60 100644 --- a/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Models/Client.cs +++ b/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Models/Client.cs @@ -8,14 +8,13 @@ using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; -using CarpentryWorkshopDatabaseImplement.Models; - - namespace CarpentryWorkshopDatabaseImplement.Models { public class Client : IClientModel { + public int Id { get; set; } + [Required] public string ClientFIO { get; set; } = string.Empty; @@ -25,43 +24,36 @@ namespace CarpentryWorkshopDatabaseImplement.Models [Required] public string Password { get; set; } = string.Empty; - public int Id { get; set; } + [ForeignKey("ClientId")] + public virtual List ClientOrders { get; set; } = new(); [ForeignKey("ClientId")] - public virtual List Orders { get; set; } = new(); - - public static Client? Create(ClientBindingModel model) - { - if (model == null) - { - return null; - } - return new() - { - Id = model.Id, - ClientFIO = model.ClientFIO, - Email = model.Email, - Password = model.Password - }; - } - - public void Update(ClientBindingModel model) - { - if (model == null) - { - return; - } - ClientFIO = model.ClientFIO; - Email = model.Email; - Password = model.Password; - } + public virtual List ClientMessages { get; set; } = new(); public ClientViewModel GetViewModel => new() { Id = Id, ClientFIO = ClientFIO, Email = Email, - Password = Password, + Password = Password }; + + public static Client Create(ClientBindingModel model) + { + return new Client() + { + Id = model.Id, + ClientFIO = model.ClientFIO, + Email = model.Email, + Password = model.Password, + }; + } + + public void Update(ClientBindingModel model) + { + ClientFIO = model.ClientFIO; + Email = model.Email; + Password = model.Password; + } } } diff --git a/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Models/MessageInfo.cs b/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..bdfa859 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopDatabaseImplement/Models/MessageInfo.cs @@ -0,0 +1,67 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.ViewModels; +using CarpentryWorkshopDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CarpentryWorkshopDatabaseImplement.Models +{ + public class MessageInfo : IMessageInfoModel + { + [Key] + public string MessageId { get; set; } = string.Empty; + + public int? ClientId { get; set; } + + public virtual Client? Client { get; set; } + + public string SenderName { get; set; } = string.Empty; + + public DateTime DateDelivery { get; set; } + + public string Subject { get; set; } = string.Empty; + + 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 void Update(MessageInfoBindingModel model) + { + 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 + }; + } +} diff --git a/CarpentryWorkshop/CarpentryWorkshopFileImplement/DataFileSingleton.cs b/CarpentryWorkshop/CarpentryWorkshopFileImplement/DataFileSingleton.cs index 26101b1..c1382a8 100644 --- a/CarpentryWorkshop/CarpentryWorkshopFileImplement/DataFileSingleton.cs +++ b/CarpentryWorkshop/CarpentryWorkshopFileImplement/DataFileSingleton.cs @@ -11,6 +11,8 @@ namespace CarpentryWorkshopFileImplement private readonly string WoodFileName = "Wood.xml"; private readonly string ClientFileName = "Client.xml"; private readonly string ImplementerFileName = "Implementer.xml"; + private readonly string MessageFileName = "Message.xml"; + public List Messages { get; private set; } public List Components { get; private set; } public List Orders { get; private set; } public List Woods { get; private set; } @@ -28,6 +30,7 @@ namespace CarpentryWorkshopFileImplement public void SaveWoods() => SaveData(Woods, WoodFileName, "Woods", x => x.GetXElement); public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement); public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", x => x.GetXElement); + public void SaveMessages() => SaveData(Messages, MessageFileName, "Messages", x => x.GetXElement); public void SaveImplementers() => SaveData(Implementers, ImplementerFileName, "Implementers", x => x.GetXElement); private DataFileSingleton() @@ -37,6 +40,7 @@ namespace CarpentryWorkshopFileImplement 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/CarpentryWorkshop/CarpentryWorkshopFileImplement/Implements/ClientStorage.cs b/CarpentryWorkshop/CarpentryWorkshopFileImplement/Implements/ClientStorage.cs index c918fb9..ba12f6c 100644 --- a/CarpentryWorkshop/CarpentryWorkshopFileImplement/Implements/ClientStorage.cs +++ b/CarpentryWorkshop/CarpentryWorkshopFileImplement/Implements/ClientStorage.cs @@ -13,84 +13,81 @@ namespace CarpentryWorkshopFileImplement.Implements { public class ClientStorage : IClientStorage { - private readonly DataFileSingleton _source; + private readonly DataFileSingleton source; + public ClientStorage() { - _source = DataFileSingleton.GetInstance(); - } - - public ClientViewModel? Delete(ClientBindingModel model) - { - var res = _source.Clients.FirstOrDefault(x => x.Id == model.Id); - if (res != null) - { - _source.Clients.Remove(res); - _source.SaveClients(); - } - return res?.GetViewModel; - } - - public ClientViewModel? GetElement(ClientSearchModel model) - { - if (model.Id.HasValue) - return _source.Clients.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; - if (model.Email != null && model.Password != null) - return _source.Clients - .FirstOrDefault(x => x.Email.Equals(model.Email) - && x.Password.Equals(model.Password)) - ?.GetViewModel; - if (model.Email != null) - return _source.Clients.FirstOrDefault(x => x.Email.Equals(model.Email))?.GetViewModel; - return null; - } - - public List GetFilteredList(ClientSearchModel model) - { - if (model == null) - { - return new(); - } - if (model.Id.HasValue) - { - var res = GetElement(model); - return res != null ? new() { res } : new(); - } - if (model.Email != null) - { - return _source.Clients - .Where(x => x.Email.Contains(model.Email)) - .Select(x => x.GetViewModel) - .ToList(); - } - return new(); + source = DataFileSingleton.GetInstance(); } public List GetFullList() { - return _source.Clients.Select(x => x.GetViewModel).ToList(); + return source.Clients + .Select(x => x.GetViewModel) + .ToList(); + } + + public List GetFilteredList(ClientSearchModel model) + { + if (string.IsNullOrEmpty(model.ClientFIO) && string.IsNullOrEmpty(model.Email)) + { + return new(); + } + return source.Clients + .Where(x => (!string.IsNullOrEmpty(model.ClientFIO) && x.ClientFIO.Contains(model.ClientFIO)) || + (!string.IsNullOrEmpty(model.Email) && x.ClientFIO.Contains(model.Email))) + .Select(x => x.GetViewModel) + .ToList(); + } + + public ClientViewModel? GetElement(ClientSearchModel model) + { + if (!model.Id.HasValue && string.IsNullOrEmpty(model.ClientFIO) && string.IsNullOrEmpty(model.Email) && string.IsNullOrEmpty(model.Password)) + { + return null; + } + return source.Clients + .FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id) || + (!string.IsNullOrEmpty(model.ClientFIO) && x.ClientFIO == model.ClientFIO) || + (!string.IsNullOrEmpty(model.Email) && !string.IsNullOrEmpty(model.Password) && x.Email == model.Email && x.Password == model.Password)) + ?.GetViewModel; } public ClientViewModel? Insert(ClientBindingModel model) { - model.Id = _source.Clients.Count > 0 ? _source.Clients.Max(x => x.Id) + 1 : 1; - var res = Client.Create(model); - if (res != null) + model.Id = source.Components.Count > 0 ? source.Components.Max(x => x.Id) + 1 : 1; + var newClient = Client.Create(model); + if (newClient == null) { - _source.Clients.Add(res); - _source.SaveClients(); + return null; } - return res?.GetViewModel; + source.Clients.Add(newClient); + source.SaveClients(); + return newClient.GetViewModel; } public ClientViewModel? Update(ClientBindingModel model) { - var res = _source.Clients.FirstOrDefault(x => x.Id == model.Id); - if (res != null) + var client = source.Clients.FirstOrDefault(x => x.Id == model.Id); + if (client == null) { - res.Update(model); - _source.SaveClients(); + return null; } - return res?.GetViewModel; + client.Update(model); + source.SaveClients(); + return client.GetViewModel; + } + + public ClientViewModel? Delete(ClientBindingModel model) + { + var element = source.Clients.FirstOrDefault(x => x.Id == model.Id); + if (element != null) + { + source.Clients.Remove(element); + source.SaveClients(); + return element.GetViewModel; + } + return null; } } } diff --git a/CarpentryWorkshop/CarpentryWorkshopFileImplement/Implements/MessageInfoStorage.cs b/CarpentryWorkshop/CarpentryWorkshopFileImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..21d4518 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopFileImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,66 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.SearchModels; +using CarpentryWorkshopContracts.StoragesContracts; +using CarpentryWorkshopContracts.ViewModels; +using CarpentryWorkshopFileImplement.Models; + +namespace CarpentryWorkshopFileImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + private readonly DataFileSingleton source; + public MessageInfoStorage() + { + source = DataFileSingleton.GetInstance(); + } + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (model.MessageId == null) + return null; + return source.Messages.FirstOrDefault(x => + x.MessageId == model.MessageId)?.GetViewModel; + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + if (!model.ClientId.HasValue) + { + 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; + } + public MessageInfoViewModel? Update(MessageInfoBindingModel model) + { + var component = source.Messages.FirstOrDefault(x => x.MessageId == model.MessageId); + if (component == null) + { + return null; + } + component.Update(model); + source.SaveMessages(); + return component.GetViewModel; + } + } +} diff --git a/CarpentryWorkshop/CarpentryWorkshopFileImplement/Models/Client.cs b/CarpentryWorkshop/CarpentryWorkshopFileImplement/Models/Client.cs index c2f6d47..27f976b 100644 --- a/CarpentryWorkshop/CarpentryWorkshopFileImplement/Models/Client.cs +++ b/CarpentryWorkshop/CarpentryWorkshopFileImplement/Models/Client.cs @@ -8,18 +8,14 @@ using System.Text; using System.Threading.Tasks; using System.Xml.Linq; - namespace CarpentryWorkshopFileImplement.Models { public class Client : IClientModel { - public string ClientFIO { get; private set; } = string.Empty; - - public string Email { get; private set; } = string.Empty; - - public string Password { get; private set; } = string.Empty; - public int Id { get; private set; } + public string ClientFIO { get; private set; } = string.Empty; + public string Email { get; private set; } = string.Empty; + public string Password { get; private set; } = string.Empty; public static Client? Create(ClientBindingModel model) { @@ -27,7 +23,7 @@ namespace CarpentryWorkshopFileImplement.Models { return null; } - return new() + return new Client() { Id = model.Id, ClientFIO = model.ClientFIO, @@ -41,12 +37,12 @@ namespace CarpentryWorkshopFileImplement.Models { return null; } - return new() + return new Client() { Id = Convert.ToInt32(element.Attribute("Id")!.Value), - ClientFIO = element.Element("FIO")!.Value, + ClientFIO = element.Element("ClientFIO")!.Value, Email = element.Element("Email")!.Value, - Password = element.Element("Password")!.Value, + Password = element.Element("Password")!.Value }; } @@ -66,14 +62,13 @@ namespace CarpentryWorkshopFileImplement.Models Id = Id, ClientFIO = ClientFIO, Email = Email, - Password = Password, + Password = Password }; public XElement GetXElement => new("Client", new XAttribute("Id", Id), - new XElement("FIO", ClientFIO), + new XElement("ClientFIO", ClientFIO), new XElement("Email", Email), - new XElement("Password", Password) - ); + new XElement("Password", Password)); } } diff --git a/CarpentryWorkshop/CarpentryWorkshopFileImplement/Models/Message.cs b/CarpentryWorkshop/CarpentryWorkshopFileImplement/Models/Message.cs new file mode 100644 index 0000000..7c5271b --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopFileImplement/Models/Message.cs @@ -0,0 +1,87 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.ViewModels; +using CarpentryWorkshopDataModels.Models; +using System.Xml.Linq; + +namespace CarpentryWorkshopFileImplement.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; } + + 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, + }; + } + + internal void Update(MessageInfoBindingModel model) + { + if (model == null) + { + return; + } + SenderName = model.SenderName; + DateDelivery = model.DateDelivery; + Subject = model.Subject; + Body = model.Body; + } + + 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/CarpentryWorkshop/CarpentryWorkshopListImplement/DataListSingleton.cs b/CarpentryWorkshop/CarpentryWorkshopListImplement/DataListSingleton.cs index 0958ead..cb23055 100644 --- a/CarpentryWorkshop/CarpentryWorkshopListImplement/DataListSingleton.cs +++ b/CarpentryWorkshop/CarpentryWorkshopListImplement/DataListSingleton.cs @@ -10,6 +10,7 @@ namespace CarpentryWorkshopListImplement public List Woods { get; set; } public List Clients { get; set; } public List Implementers { get; set; } + public List Messages { get; set; } private DataListSingleton() { Components = new List(); @@ -17,6 +18,7 @@ namespace CarpentryWorkshopListImplement Woods = new List(); Clients = new List(); Implementers = new List(); + Messages = new List(); } public static DataListSingleton GetInstance() { diff --git a/CarpentryWorkshop/CarpentryWorkshopListImplement/Implements/ClientStorage.cs b/CarpentryWorkshop/CarpentryWorkshopListImplement/Implements/ClientStorage.cs index 178547d..6a7cf6c 100644 --- a/CarpentryWorkshop/CarpentryWorkshopListImplement/Implements/ClientStorage.cs +++ b/CarpentryWorkshop/CarpentryWorkshopListImplement/Implements/ClientStorage.cs @@ -3,11 +3,6 @@ using CarpentryWorkshopContracts.SearchModels; using CarpentryWorkshopContracts.StoragesContracts; using CarpentryWorkshopContracts.ViewModels; using CarpentryWorkshopListImplement.Models; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace CarpentryWorkshopListImplement.Implements { @@ -18,63 +13,6 @@ namespace CarpentryWorkshopListImplement.Implements { _source = DataListSingleton.GetInstance(); } - public ClientViewModel? Delete(ClientBindingModel model) - { - for (int i = 0; i < _source.Clients.Count; ++i) - { - if (_source.Clients[i].Id == model.Id) - { - var element = _source.Clients[i]; - _source.Clients.RemoveAt(i); - return element.GetViewModel; - } - } - return null; - } - - public ClientViewModel? GetElement(ClientSearchModel model) - { - if (model.Id.HasValue) - { - foreach (var client in _source.Clients) - { - if (client.Id == model.Id) - { - return client.GetViewModel; - } - } - } - else if (!string.IsNullOrEmpty(model.Email) && !string.IsNullOrEmpty(model.Password)) - { - foreach (var client in _source.Clients) - { - if (client.Email == model.Email && client.Password == model.Password) - { - return client.GetViewModel; - } - } - } - - return null; - } - - public List GetFilteredList(ClientSearchModel model) - { - var result = new List(); - if (string.IsNullOrEmpty(model.Email)) - { - return result; - } - foreach (var client in _source.Clients) - { - if (client.Email.Contains(model.Email)) - { - result.Add(client.GetViewModel); - } - } - return result; - } - public List GetFullList() { var result = new List(); @@ -84,7 +22,36 @@ namespace CarpentryWorkshopListImplement.Implements } return result; } - + public List GetFilteredList(ClientSearchModel model) + { + var result = new List(); + if (string.IsNullOrEmpty(model.ClientFIO)) + { + return result; + } + foreach (var client in _source.Clients) + { + if (client.ClientFIO.Contains(model.ClientFIO)) + { + result.Add(client.GetViewModel); + } + } + return result; + } + public ClientViewModel? GetElement(ClientSearchModel model) + { + foreach (var client in _source.Clients) + { + if (model.Id.HasValue && model.Id == client.Id) + return client.GetViewModel; + if (!string.IsNullOrEmpty(model.Email) && !string.IsNullOrEmpty(model.Password) && + client.Email.Equals(model.Email) && client.Password.Equals(model.Password)) + return client.GetViewModel; + if (!string.IsNullOrEmpty(model.Email) && client.Email.Equals(model.Email)) + return client.GetViewModel; + } + return null; + } public ClientViewModel? Insert(ClientBindingModel model) { model.Id = 1; @@ -103,7 +70,6 @@ namespace CarpentryWorkshopListImplement.Implements _source.Clients.Add(newClient); return newClient.GetViewModel; } - public ClientViewModel? Update(ClientBindingModel model) { foreach (var client in _source.Clients) @@ -116,5 +82,18 @@ namespace CarpentryWorkshopListImplement.Implements } return null; } + public ClientViewModel? Delete(ClientBindingModel model) + { + for (int i = 0; i < _source.Clients.Count; ++i) + { + if (_source.Clients[i].Id == model.Id) + { + var element = _source.Clients[i]; + _source.Clients.RemoveAt(i); + return element.GetViewModel; + } + } + return null; + } } } diff --git a/CarpentryWorkshop/CarpentryWorkshopListImplement/Implements/MessageInfoStorage.cs b/CarpentryWorkshop/CarpentryWorkshopListImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..8371fee --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopListImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,81 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.SearchModels; +using CarpentryWorkshopContracts.StoragesContracts; +using CarpentryWorkshopContracts.ViewModels; +using CarpentryWorkshopListImplement.Models; + +namespace CarpentryWorkshopListImplement.Implements +{ + internal class MessageInfoStorage : IMessageInfoStorage + { + private readonly DataListSingleton _source; + public MessageInfoStorage() + { + _source = DataListSingleton.GetInstance(); + } + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (model.MessageId == null) + { + return null; + } + foreach (var message in _source.Messages) + { + if (model.MessageId.Equals(message.MessageId)) + return message.GetViewModel; + } + return null; + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + if (!model.ClientId.HasValue) + { + return new(); + } + var result = new List(); + foreach (var item in _source.Messages) + { + if (item.ClientId == model.ClientId) + { + result.Add(item.GetViewModel); + } + } + return result; + } + + public List GetFullList() + { + var result = new List(); + foreach (var item in _source.Messages) + { + result.Add(item.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; + } + public MessageInfoViewModel? Update(MessageInfoBindingModel model) + { + foreach (var massage in _source.Messages) + { + if (massage.MessageId == model.MessageId) + { + massage.Update(model); + + return massage.GetViewModel; + } + } + return null; + } + } +} diff --git a/CarpentryWorkshop/CarpentryWorkshopListImplement/Models/Client.cs b/CarpentryWorkshop/CarpentryWorkshopListImplement/Models/Client.cs index 4d7ab11..64bb757 100644 --- a/CarpentryWorkshop/CarpentryWorkshopListImplement/Models/Client.cs +++ b/CarpentryWorkshop/CarpentryWorkshopListImplement/Models/Client.cs @@ -1,18 +1,13 @@ using CarpentryWorkshopContracts.BindingModels; using CarpentryWorkshopContracts.ViewModels; using CarpentryWorkshopDataModels.Models; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace CarpentryWorkshopListImplement.Models { public class Client : IClientModel { - public int Id { get; set; } - public string ClientFIO { get; set; } = string.Empty; + public int Id { get; private set; } + public string ClientFIO { get; private set; } = string.Empty; public string Email { get; set; } = string.Empty; public string Password { get; set; } = string.Empty; public static Client? Create(ClientBindingModel? model) @@ -44,7 +39,7 @@ namespace CarpentryWorkshopListImplement.Models Id = Id, ClientFIO = ClientFIO, Email = Email, - Password = Password + Password = Password, }; } } diff --git a/CarpentryWorkshop/CarpentryWorkshopListImplement/Models/Message.cs b/CarpentryWorkshop/CarpentryWorkshopListImplement/Models/Message.cs new file mode 100644 index 0000000..a785872 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopListImplement/Models/Message.cs @@ -0,0 +1,58 @@ +using CarpentryWorkshopContracts.BindingModels; +using CarpentryWorkshopContracts.ViewModels; +using CarpentryWorkshopDataModels.Models; + +namespace CarpentryWorkshopListImplement.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 void Update(MessageInfoBindingModel model) + { + if (model == null) + { + return; + } + SenderName = model.SenderName; + DateDelivery = model.DateDelivery; + Subject = model.Subject; + Body = model.Body; + } + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Subject = Subject, + DateDelivery = DateDelivery, + SenderName = SenderName, + ClientId = ClientId, + MessageId = MessageId + }; + } +} diff --git a/CarpentryWorkshop/CarpentryWorkshopRestApi/Controllers/ClientController.cs b/CarpentryWorkshop/CarpentryWorkshopRestApi/Controllers/ClientController.cs index 1bba867..ad089ac 100644 --- a/CarpentryWorkshop/CarpentryWorkshopRestApi/Controllers/ClientController.cs +++ b/CarpentryWorkshop/CarpentryWorkshopRestApi/Controllers/ClientController.cs @@ -11,13 +11,14 @@ namespace CarpentryWorkshopRestApi.Controllers public class ClientController : Controller { private readonly ILogger _logger; - private readonly IClientLogic _logic; + private readonly IMessageInfoLogic _mailLogic; - public ClientController(IClientLogic logic, ILogger logger) + public ClientController(IClientLogic logic, ILogger logger, IMessageInfoLogic mailLogic) { _logger = logger; _logic = logic; + _mailLogic = mailLogic; } [HttpGet] @@ -30,7 +31,6 @@ namespace CarpentryWorkshopRestApi.Controllers Email = login, Password = password }); - } catch (Exception ex) { @@ -66,5 +66,22 @@ namespace CarpentryWorkshopRestApi.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/CarpentryWorkshop/CarpentryWorkshopRestApi/Program.cs b/CarpentryWorkshop/CarpentryWorkshopRestApi/Program.cs index be549c9..3b9d713 100644 --- a/CarpentryWorkshop/CarpentryWorkshopRestApi/Program.cs +++ b/CarpentryWorkshop/CarpentryWorkshopRestApi/Program.cs @@ -1,4 +1,6 @@ using CarpentryWorkshopBusinessLogic.BusinessLogics; +using CarpentryWorkshopBusinessLogic.MailWorker; +using CarpentryWorkshopContracts.BindingModels; using CarpentryWorkshopContracts.BusinessLogicsContracts; using CarpentryWorkshopContracts.StoragesContracts; using CarpentryWorkshopDatabaseImplement.Implements; @@ -6,35 +8,49 @@ using Microsoft.OpenApi.Models; var builder = WebApplication.CreateBuilder(args); +builder.Logging.SetMinimumLevel(LogLevel.Trace); // Add services to the container. 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.AddTransient(); + +builder.Services.AddSingleton(); builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(c => { - c.SwaggerDoc("v1", new OpenApiInfo - { - Title = "ComputersShopRestApi", - Version = "v1" - }); + c.SwaggerDoc("v1", new OpenApiInfo { Title = "CarpentryWorkshopRestApi", 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()) { app.UseSwagger(); - app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "ComputersShopRestApi v1")); + app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "CarpentryWorkshopRestApi v1")); } app.UseHttpsRedirection(); diff --git a/CarpentryWorkshop/CarpentryWorkshopRestApi/appsettings.json b/CarpentryWorkshop/CarpentryWorkshopRestApi/appsettings.json index 10f68b8..708cc93 100644 --- a/CarpentryWorkshop/CarpentryWorkshopRestApi/appsettings.json +++ b/CarpentryWorkshop/CarpentryWorkshopRestApi/appsettings.json @@ -2,8 +2,16 @@ "Logging": { "LogLevel": { "Default": "Information", - "Microsoft.AspNetCore": "Warning" + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" } }, - "AllowedHosts": "*" + "AllowedHosts": "*", + + "SmtpClientHost": "smtp.gmail.com", + "SmtpClientPort": "587", + "PopHost": "pop.gmail.com", + "PopPort": "995", + "MailLogin": "mailworker2024@gmail.com", + "MailPassword": "qwerty!@#" } diff --git a/CarpentryWorkshop/CarpentryWorkshopView/App.config b/CarpentryWorkshop/CarpentryWorkshopView/App.config new file mode 100644 index 0000000..6c928f4 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopView/App.config @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/CarpentryWorkshop/CarpentryWorkshopView/FormMail.Designer.cs b/CarpentryWorkshop/CarpentryWorkshopView/FormMail.Designer.cs new file mode 100644 index 0000000..3ad9cd5 --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopView/FormMail.Designer.cs @@ -0,0 +1,60 @@ +namespace CarpentryWorkshopView +{ + 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() + { + dataGridView = new DataGridView(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // dataGridView + // + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(3, 3); + dataGridView.Name = "dataGridView"; + dataGridView.RowTemplate.Height = 25; + dataGridView.Size = new Size(794, 445); + dataGridView.TabIndex = 0; + // + // FormMail + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(800, 450); + Controls.Add(dataGridView); + Name = "FormMail"; + Text = "Эл. письма"; + Load += FormMail_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + private DataGridView dataGridView; + } +} \ No newline at end of file diff --git a/CarpentryWorkshop/CarpentryWorkshopView/FormMail.cs b/CarpentryWorkshop/CarpentryWorkshopView/FormMail.cs new file mode 100644 index 0000000..29ed5dd --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopView/FormMail.cs @@ -0,0 +1,56 @@ +using CarpentryWorkshopContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +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 CarpentryWorkshopView +{ + public partial class FormMail : Form + { + private readonly ILogger _logger; + private readonly IMessageInfoLogic _logic; + + public FormMail(ILogger logger, IMessageInfoLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + LoadData(); + } + + private void LoadData() + { + 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); + } + } + + private void FormMail_Load(object sender, EventArgs e) + { + LoadData(); + } + + } +} diff --git a/CarpentryWorkshop/CarpentryWorkshopView/FormMail.resx b/CarpentryWorkshop/CarpentryWorkshopView/FormMail.resx new file mode 100644 index 0000000..f298a7b --- /dev/null +++ b/CarpentryWorkshop/CarpentryWorkshopView/FormMail.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/CarpentryWorkshop/CarpentryWorkshopView/FormMain.Designer.cs b/CarpentryWorkshop/CarpentryWorkshopView/FormMain.Designer.cs index 4005e1e..8befce7 100644 --- a/CarpentryWorkshop/CarpentryWorkshopView/FormMain.Designer.cs +++ b/CarpentryWorkshop/CarpentryWorkshopView/FormMain.Designer.cs @@ -45,13 +45,14 @@ ButtonOrderReady = new Button(); ButtonIssuedOrder = new Button(); ButtonRef = new Button(); + письмаToolStripMenuItem = new ToolStripMenuItem(); menuStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); SuspendLayout(); // // menuStrip1 // - menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчетыToolStripMenuItem, запускРаботToolStripMenuItem, исполнителиToolStripMenuItem }); + menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчетыToolStripMenuItem, запускРаботToolStripMenuItem, исполнителиToolStripMenuItem, письмаToolStripMenuItem }); menuStrip1.Location = new Point(0, 0); menuStrip1.Name = "menuStrip1"; menuStrip1.Size = new Size(1174, 24); @@ -189,6 +190,13 @@ ButtonRef.UseVisualStyleBackColor = true; ButtonRef.Click += ButtonRef_Click; // + // письмаToolStripMenuItem + // + письмаToolStripMenuItem.Name = "письмаToolStripMenuItem"; + письмаToolStripMenuItem.Size = new Size(62, 20); + письмаToolStripMenuItem.Text = "Письма"; + письмаToolStripMenuItem.Click += письмаToolStripMenuItem_Click; + // // FormMain // AutoScaleDimensions = new SizeF(7F, 15F); @@ -230,5 +238,6 @@ private ToolStripMenuItem ClientsToolStripMenuItem; private ToolStripMenuItem запускРаботToolStripMenuItem; private ToolStripMenuItem исполнителиToolStripMenuItem; + private ToolStripMenuItem письмаToolStripMenuItem; } } \ No newline at end of file diff --git a/CarpentryWorkshop/CarpentryWorkshopView/FormMain.cs b/CarpentryWorkshop/CarpentryWorkshopView/FormMain.cs index 7cde27c..66db160 100644 --- a/CarpentryWorkshop/CarpentryWorkshopView/FormMain.cs +++ b/CarpentryWorkshop/CarpentryWorkshopView/FormMain.cs @@ -197,5 +197,13 @@ namespace CarpentryWorkshopView form.ShowDialog(); } } + private void письмаToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormMail)); + if (service is FormMail form) + { + form.ShowDialog(); + } + } } } diff --git a/CarpentryWorkshop/CarpentryWorkshopView/Program.cs b/CarpentryWorkshop/CarpentryWorkshopView/Program.cs index 058d34d..486b301 100644 --- a/CarpentryWorkshop/CarpentryWorkshopView/Program.cs +++ b/CarpentryWorkshop/CarpentryWorkshopView/Program.cs @@ -7,6 +7,8 @@ using CarpentryWorkshopDatabaseImplement.Implements; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; +using CarpentryWorkshopBusinessLogic.MailWorker; +using CarpentryWorkshopContracts.BindingModels; namespace CarpentryWorkshopView @@ -27,6 +29,26 @@ namespace CarpentryWorkshopView var services = new ServiceCollection(); ConfigureServices(services); _serviceProvider = services.BuildServiceProvider(); + 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, "Error"); + } Application.Run(_serviceProvider.GetRequiredService()); } private static void ConfigureServices(ServiceCollection services) @@ -41,6 +63,7 @@ namespace CarpentryWorkshopView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -48,7 +71,9 @@ namespace CarpentryWorkshopView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); + services.AddSingleton(); services.AddTransient(); services.AddTransient(); @@ -66,6 +91,8 @@ namespace CarpentryWorkshopView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); } + private static void MailCheck(object obj) => ServiceProvider?.GetService()?.MailCheck(); } } \ No newline at end of file