diff --git a/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/BusinessLogics/ClientLogic.cs b/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/BusinessLogics/ClientLogic.cs index fb39bba..68576a3 100644 --- a/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/BusinessLogics/ClientLogic.cs +++ b/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/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 PrecastConcretePlantBusinessLogic.BusinessLogics @@ -94,13 +95,14 @@ namespace PrecastConcretePlantBusinessLogic.BusinessLogics { throw new ArgumentNullException("Не указаны ФИО", nameof(model.ClientFIO)); } - if (string.IsNullOrEmpty(model.Email)) + //todo INFO Да, подобное выражение проверяет только общий паттерн, и не гарантирует валидность адреса, но в данном случае можно и так. + if (string.IsNullOrEmpty(model.Email) || !Regex.IsMatch(model.Email, @"^[a-z0-9._%+-]+\@([a-z0-9-]+\.)+[a-z]{2,4}$")) { - throw new ArgumentNullException("Не указан логин(электронная почта)", nameof(model.Email)); + throw new ArgumentNullException("Не указан верный логин(электронная почта)", nameof(model.Email)); } - if (string.IsNullOrEmpty(model.Password)) + if (string.IsNullOrEmpty(model.Password) || !Regex.IsMatch(model.Password, @"^(?=.*[A-Za-z])(?=.*\d)(?=.*[^A-Za-z0-9\n]).{10,50}$")) { - throw new ArgumentNullException("Не указан пароль", nameof(model.Password)); + throw new ArgumentNullException("Не указан верный пароль", nameof(model.Password)); } //Из сообращений безопасности пароль в логгер не выводится. Только его длина _logger.LogInformation("Client. ClientFIO:{ClientFIO}.Email:{Email}.Password:{Password}.Id:{Id}", model.ClientFIO, model.Email, model.Password.Length, model.Id); diff --git a/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/BusinessLogics/MessageInfoLogic.cs b/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/BusinessLogics/MessageInfoLogic.cs new file mode 100644 index 0000000..a4af40f --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/BusinessLogics/MessageInfoLogic.cs @@ -0,0 +1,90 @@ +using Microsoft.Extensions.Logging; +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.BusinessLogicsContracts; +using PrecastConcretePlantContracts.SearchModels; +using PrecastConcretePlantContracts.StoragesContracts; +using PrecastConcretePlantContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantBusinessLogic.BusinessLogics +{ + public class MessageInfoLogic : IMessageInfoLogic + { + private readonly ILogger _logger; + private readonly IMessageInfoStorage _messageInfoStorage; + private readonly IClientStorage _clientStorage; + public MessageInfoLogic(ILogger logger, IMessageInfoStorage messageInfoStorage, IClientStorage clientStorage) + { + _logger = logger; + _messageInfoStorage = messageInfoStorage; + _clientStorage = clientStorage; + } + public List? ReadList(MessageInfoSearchModel? model) + { + _logger.LogInformation("ReadList. MessageId:{MessageId}.ClientId:{ClientId}", model?.MessageId, model?.ClientId); + var list = model == null ? _messageInfoStorage.GetFullList() : _messageInfoStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + _logger.LogInformation("ReadList. Count:{Count}", list.Count); + return list; + } + public bool Create(MessageInfoBindingModel model) + { + CheckModel(model); + if (_messageInfoStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } + private void CheckModel(MessageInfoBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (!withParams) + { + return; + } + if (string.IsNullOrEmpty(model.MessageId)) + { + throw new ArgumentNullException("Не указан id сообщения", nameof(model.MessageId)); + } + if (string.IsNullOrEmpty(model.SenderName)) + { + throw new ArgumentNullException("Не указао имя отправителя(электронная почта)", nameof(model.SenderName)); + } + if (string.IsNullOrEmpty(model.Subject)) + { + throw new ArgumentNullException("Не указана темма", nameof(model.Subject)); + } + if (string.IsNullOrEmpty(model.Body)) + { + throw new ArgumentNullException("Не указан текст сообщения", nameof(model.Subject)); + } + //Из сообращений безопасности пароль в логгер не выводится. Только его длина + _logger.LogInformation("MessageInfo. MessageId:{MessageId}.SenderName:{SenderName}.Subject:{Subject}.Body:{Body}", model.MessageId, model.SenderName, model.Subject, model.Body); + var element = _clientStorage.GetElement(new ClientSearchModel + { + Email = model.SenderName + }); + if (element == null) + { + _logger.LogWarning("Не удалоссь найти клиента, отправившего письмо с адреса Email:{Email}", model.SenderName); + } + else + { + model.ClientId = element.Id; + } + } + } +} \ No newline at end of file diff --git a/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/BusinessLogics/OrderLogic.cs b/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/BusinessLogics/OrderLogic.cs index dfa92ee..8524a99 100644 --- a/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/BusinessLogics/OrderLogic.cs @@ -4,12 +4,15 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Extensions.Logging; +using MigraDoc.Rendering; +using PrecastConcretePlantBusinessLogic.MailWorker; using PrecastConcretePlantContracts.BindingModels; using PrecastConcretePlantContracts.BusinessLogicsContracts; using PrecastConcretePlantContracts.SearchModels; using PrecastConcretePlantContracts.StoragesContracts; using PrecastConcretePlantContracts.ViewModels; using PrecastConcretePlantDataModels.Enums; +using System.Xml.Linq; namespace PrecastConcretePlantBusinessLogic.BusinessLogics { @@ -17,13 +20,15 @@ namespace PrecastConcretePlantBusinessLogic.BusinessLogics { private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; + private readonly AbstractMailWorker _mailWorker; static readonly object _locker = new object(); - public OrderLogic(ILogger logger, IOrderStorage orderStorage) - { - _logger = logger; + public OrderLogic(ILogger logger, IOrderStorage orderStorage, AbstractMailWorker mailWorker) + { + _logger = logger; _orderStorage = orderStorage; - } - public List? ReadList(OrderSearchModel? model) + _mailWorker = mailWorker; + } + public List? ReadList(OrderSearchModel? model) { _logger.LogInformation("ReadList. ClientId:{ClientId}.Status:{Status}.ImplementerId:{ImplementerId}.DateFrom:{DateFrom}.DateTo:{DateTo}OrderId:{Id}", model?.ClientId, model?.Status, model?.ImplementerId, model?.DateFrom, model?.DateTo, model?.Id); var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model); @@ -58,12 +63,19 @@ namespace PrecastConcretePlantBusinessLogic.BusinessLogics if (model.Status != OrderStatus.Неизвестен) return false; model.Status = OrderStatus.Принят; - if (_orderStorage.Insert(model) == null) - { + var element = _orderStorage.Insert(model); + if (element == null) + { _logger.LogWarning("Insert operation failed"); return false; } - return true; + Task.Run(() => _mailWorker.MailSendAsync(new MailSendInfoBindingModel + { + MailAddress = element.ClientEmail, + Subject = $"Изменение статуса заказа номер {element.Id}", + Text = $"Ваш заказ номер {element.Id} на изделие {element.ReinforcedName} от {element.DateCreate} на сумму {element.Sum} принят." + })); + return true; } public bool TakeOrderInWork(OrderBindingModel model) { @@ -135,7 +147,14 @@ namespace PrecastConcretePlantBusinessLogic.BusinessLogics _logger.LogWarning("Update operation failed"); return false; } - return true; + string DateInfo = model.DateImplement.HasValue ? $"Дата выполнения {model.DateImplement}" : ""; + Task.Run(() => _mailWorker.MailSendAsync(new MailSendInfoBindingModel + { + MailAddress = element.ClientEmail, + Subject = $"Изменение статуса заказа номер {element.Id}", + Text = $"Ваш заказ номер {element.Id} на изделие {element.ReinforcedName} от {element.DateCreate} на сумму {element.Sum} {model.Status}. {DateInfo}" + })); + return true; } _logger.LogWarning("Changing status operation faled: Current-{Status}:required-{requiredStatus}.", model.Status, requiredStatus); throw new InvalidOperationException($"Невозможно приствоить статус {requiredStatus} заказу с текущим статусом {model.Status}"); diff --git a/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/MailWorker/AbstractMailWorker.cs b/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/MailWorker/AbstractMailWorker.cs new file mode 100644 index 0000000..39d7bd5 --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/MailWorker/AbstractMailWorker.cs @@ -0,0 +1,89 @@ +using Microsoft.Extensions.Logging; +using PrecastConcretePlantBusinessLogic.BusinessLogics; +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.BusinessLogicsContracts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantBusinessLogic.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.Length, _smtpClientHost, _smtpClientPort, _popHost, _popPort); + } + public async void MailSendAsync(MailSendInfoBindingModel info) + { + if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword)) + { + return; + } + + if (string.IsNullOrEmpty(_smtpClientHost) || _smtpClientPort == 0) + { + return; + } + + if (string.IsNullOrEmpty(info.MailAddress) || string.IsNullOrEmpty(info.Subject) || string.IsNullOrEmpty(info.Text)) + { + return; + } + + _logger.LogDebug("Send Mail: {To}, {Subject}", info.MailAddress, info.Subject); + await SendMailAsync(info); + } + public async void MailCheck() + { + if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword)) + { + return; + } + + if (string.IsNullOrEmpty(_popHost) || _popPort == 0) + { + return; + } + + if (_messageInfoLogic == null) + { + return; + } + + var list = await ReceiveMailAsync(); + _logger.LogDebug("Check Mail: {Count} new mails", list.Count); + foreach (var mail in list) + { + 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/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/MailWorker/MailKitWorker.cs b/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/MailWorker/MailKitWorker.cs new file mode 100644 index 0000000..45543fc --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/MailWorker/MailKitWorker.cs @@ -0,0 +1,83 @@ +using Microsoft.Extensions.Logging; +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.BusinessLogicsContracts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Mail; +using System.Net; +using System.Security.Authentication; +using System.Text; +using System.Threading.Tasks; +using MailKit.Net.Pop3; +using MailKit.Security; + +namespace PrecastConcretePlantBusinessLogic.MailWorker +{ + public class MailKitWorker : AbstractMailWorker + { + public MailKitWorker(ILogger logger, IMessageInfoLogic messageInfoLogic, IClientLogic clientLogic) : base(logger, messageInfoLogic, clientLogic) { } + + protected override async Task SendMailAsync(MailSendInfoBindingModel info) + { + using var objMailMessage = new MailMessage(); + using var objSmtpClient = new SmtpClient(_smtpClientHost, _smtpClientPort); + try + { + objMailMessage.From = new MailAddress(_mailLogin); + objMailMessage.To.Add(new MailAddress(info.MailAddress)); + objMailMessage.Subject = info.Subject; + objMailMessage.Body = info.Text; + objMailMessage.SubjectEncoding = Encoding.UTF8; + objMailMessage.BodyEncoding = Encoding.UTF8; + + objSmtpClient.UseDefaultCredentials = false; + objSmtpClient.EnableSsl = true; + objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; + objSmtpClient.Credentials = new NetworkCredential(_mailLogin, _mailPassword); + + await Task.Run(() => objSmtpClient.Send(objMailMessage)); + } + catch (Exception) + { + throw; + } + } + + protected override async Task> ReceiveMailAsync() + { + var list = new List(); + using var client = new Pop3Client(); + await Task.Run(() => + { + try + { + client.Connect(_popHost, _popPort, SecureSocketOptions.SslOnConnect); + client.Authenticate(_mailLogin, _mailPassword); + for (int i = 0; i < client.Count; i++) + { + var message = client.GetMessage(i); + foreach (var mail in message.From.Mailboxes) + { + list.Add(new MessageInfoBindingModel + { + DateDelivery = message.Date.DateTime, + MessageId = message.MessageId, + SenderName = mail.Address, + Subject = message.Subject, + Body = message.TextBody + }); + } + } + } + catch (MailKit.Security.AuthenticationException) + { } + finally + { + client.Disconnect(true); + } + }); + return list; + } + } +} diff --git a/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/PrecastConcretePlantBusinessLogic.csproj b/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/PrecastConcretePlantBusinessLogic.csproj index 716ce41..2c31df2 100644 --- a/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/PrecastConcretePlantBusinessLogic.csproj +++ b/PrecastConcretePlant/PrecastConcretePlantBusinessLogic/PrecastConcretePlantBusinessLogic.csproj @@ -8,6 +8,7 @@ + diff --git a/PrecastConcretePlant/PrecastConcretePlantClientApp/Controllers/HomeController.cs b/PrecastConcretePlant/PrecastConcretePlantClientApp/Controllers/HomeController.cs index faf29d2..08ffce8 100644 --- a/PrecastConcretePlant/PrecastConcretePlantClientApp/Controllers/HomeController.cs +++ b/PrecastConcretePlant/PrecastConcretePlantClientApp/Controllers/HomeController.cs @@ -1,4 +1,5 @@ using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging; using PrecastConcretePlantClientApp.Models; using PrecastConcretePlantContracts.BindingModels; using PrecastConcretePlantContracts.ViewModels; @@ -143,5 +144,15 @@ namespace PrecastConcretePlantClientApp.Controllers var prod = APIClient.GetRequest($"api/main/getreinforced?reinforcedId={reinforced}"); 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/PrecastConcretePlant/PrecastConcretePlantClientApp/Properties/launchSettings.json b/PrecastConcretePlant/PrecastConcretePlantClientApp/Properties/launchSettings.json index d621e2e..1c12853 100644 --- a/PrecastConcretePlant/PrecastConcretePlantClientApp/Properties/launchSettings.json +++ b/PrecastConcretePlant/PrecastConcretePlantClientApp/Properties/launchSettings.json @@ -1,21 +1,13 @@ { - "iisSettings": { - "windowsAuthentication": false, - "anonymousAuthentication": true, - "iisExpress": { - "applicationUrl": "http://localhost:22958", - "sslPort": 44305 - } - }, "profiles": { "PrecastConcretePlantClientApp": { "commandName": "Project", - "dotnetRunMessages": true, "launchBrowser": true, - "applicationUrl": "https://localhost:7175;http://localhost:5257", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" - } + }, + "dotnetRunMessages": true, + "applicationUrl": "https://localhost:7251;http://localhost:5173" }, "IIS Express": { "commandName": "IISExpress", @@ -24,5 +16,13 @@ "ASPNETCORE_ENVIRONMENT": "Development" } } + }, + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:22958", + "sslPort": 0 + } } -} +} \ No newline at end of file diff --git a/PrecastConcretePlant/PrecastConcretePlantClientApp/Views/Home/Mails.cshtml b/PrecastConcretePlant/PrecastConcretePlantClientApp/Views/Home/Mails.cshtml new file mode 100644 index 0000000..019ff2d --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantClientApp/Views/Home/Mails.cshtml @@ -0,0 +1,55 @@ +@using PrecastConcretePlantContracts.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/PrecastConcretePlant/PrecastConcretePlantClientApp/Views/Shared/_Layout.cshtml b/PrecastConcretePlant/PrecastConcretePlantClientApp/Views/Shared/_Layout.cshtml index ca8cdbc..84af02c 100644 --- a/PrecastConcretePlant/PrecastConcretePlantClientApp/Views/Shared/_Layout.cshtml +++ b/PrecastConcretePlant/PrecastConcretePlantClientApp/Views/Shared/_Layout.cshtml @@ -28,6 +28,9 @@ + diff --git a/PrecastConcretePlant/PrecastConcretePlantClientApp/appsettings.json b/PrecastConcretePlant/PrecastConcretePlantClientApp/appsettings.json index e96ebdb..665817a 100644 --- a/PrecastConcretePlant/PrecastConcretePlantClientApp/appsettings.json +++ b/PrecastConcretePlant/PrecastConcretePlantClientApp/appsettings.json @@ -7,5 +7,5 @@ }, "AllowedHosts": "*", - "IPAddress": "http://localhost:5028" + "IPAddress": "http://localhost:7103" } diff --git a/PrecastConcretePlant/PrecastConcretePlantContracts/BindingModels/MailConfigBindingModel.cs b/PrecastConcretePlant/PrecastConcretePlantContracts/BindingModels/MailConfigBindingModel.cs new file mode 100644 index 0000000..bff865c --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantContracts/BindingModels/MailConfigBindingModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantContracts.BindingModels +{ + public class MailConfigBindingModel + { + public string MailLogin { get; set; } = string.Empty; + public string MailPassword { get; set; } = string.Empty; + public string SmtpClientHost { get; set; } = string.Empty; + public int SmtpClientPort { get; set; } + public string PopHost { get; set; } = string.Empty; + public int PopPort { get; set; } + } +} \ No newline at end of file diff --git a/PrecastConcretePlant/PrecastConcretePlantContracts/BindingModels/MailSendInfoBindingModel.cs b/PrecastConcretePlant/PrecastConcretePlantContracts/BindingModels/MailSendInfoBindingModel.cs new file mode 100644 index 0000000..48329f8 --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantContracts/BindingModels/MailSendInfoBindingModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantContracts.BindingModels +{ + public class MailSendInfoBindingModel + { + public string MailAddress { get; set; } = string.Empty; + public string Subject { get; set; } = string.Empty; + public string Text { get; set; } = string.Empty; + } +} \ No newline at end of file diff --git a/PrecastConcretePlant/PrecastConcretePlantContracts/BindingModels/MessageInfoBindingModel.cs b/PrecastConcretePlant/PrecastConcretePlantContracts/BindingModels/MessageInfoBindingModel.cs new file mode 100644 index 0000000..2f78b18 --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantContracts/BindingModels/MessageInfoBindingModel.cs @@ -0,0 +1,19 @@ +using PrecastConcretePlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantContracts.BindingModels +{ + public class MessageInfoBindingModel : IMessageInfoModel + { + public string MessageId { get; set; } = string.Empty; + public int? ClientId { get; set; } + public string SenderName { get; set; } = string.Empty; + public string Subject { get; set; } = string.Empty; + public string Body { get; set; } = string.Empty; + public DateTime DateDelivery { get; set; } + } +} \ No newline at end of file diff --git a/PrecastConcretePlant/PrecastConcretePlantContracts/BusinessLogicsContracts/IMessageInfoLogic.cs b/PrecastConcretePlant/PrecastConcretePlantContracts/BusinessLogicsContracts/IMessageInfoLogic.cs new file mode 100644 index 0000000..d83a78d --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantContracts/BusinessLogicsContracts/IMessageInfoLogic.cs @@ -0,0 +1,17 @@ +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.SearchModels; +using PrecastConcretePlantContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantContracts.BusinessLogicsContracts +{ + public interface IMessageInfoLogic + { + List? ReadList(MessageInfoSearchModel? model); + bool Create(MessageInfoBindingModel model); + } +} \ No newline at end of file diff --git a/PrecastConcretePlant/PrecastConcretePlantContracts/SearchModels/MessageInfoSearchModel.cs b/PrecastConcretePlant/PrecastConcretePlantContracts/SearchModels/MessageInfoSearchModel.cs new file mode 100644 index 0000000..beb779f --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantContracts/SearchModels/MessageInfoSearchModel.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantContracts.SearchModels +{ + public class MessageInfoSearchModel + { + public int? ClientId { get; set; } + public string? MessageId { get; set; } + } +} \ No newline at end of file diff --git a/PrecastConcretePlant/PrecastConcretePlantContracts/StoragesContracts/IMessageInfoStorage.cs b/PrecastConcretePlant/PrecastConcretePlantContracts/StoragesContracts/IMessageInfoStorage.cs new file mode 100644 index 0000000..e21c3e4 --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantContracts/StoragesContracts/IMessageInfoStorage.cs @@ -0,0 +1,19 @@ +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.SearchModels; +using PrecastConcretePlantContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantContracts.StoragesContracts +{ + public interface IMessageInfoStorage + { + List GetFullList(); + List GetFilteredList(MessageInfoSearchModel model); + MessageInfoViewModel? GetElement(MessageInfoSearchModel model); + MessageInfoViewModel? Insert(MessageInfoBindingModel model); + } +} \ No newline at end of file diff --git a/PrecastConcretePlant/PrecastConcretePlantContracts/ViewModels/MessageInfoViewModel.cs b/PrecastConcretePlant/PrecastConcretePlantContracts/ViewModels/MessageInfoViewModel.cs new file mode 100644 index 0000000..54fc705 --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantContracts/ViewModels/MessageInfoViewModel.cs @@ -0,0 +1,29 @@ +using PrecastConcretePlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantContracts.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/PrecastConcretePlant/PrecastConcretePlantContracts/ViewModels/OrderViewModel.cs b/PrecastConcretePlant/PrecastConcretePlantContracts/ViewModels/OrderViewModel.cs index 552c18c..3ebc49a 100644 --- a/PrecastConcretePlant/PrecastConcretePlantContracts/ViewModels/OrderViewModel.cs +++ b/PrecastConcretePlant/PrecastConcretePlantContracts/ViewModels/OrderViewModel.cs @@ -19,6 +19,7 @@ namespace PrecastConcretePlantContracts.ViewModels public int ClientId { get; set; } [DisplayName("Клиент")] public string ClientFIO { get; set; } = string.Empty; + public string ClientEmail { get; set; } = string.Empty; public int? ImplementerId { get; set; } [DisplayName("Исполнитель")] public string? ImplementerFIO { get; set; } = null; diff --git a/PrecastConcretePlant/PrecastConcretePlantDataModels/Models/IMessageInfoModel.cs b/PrecastConcretePlant/PrecastConcretePlantDataModels/Models/IMessageInfoModel.cs new file mode 100644 index 0000000..747b2d6 --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantDataModels/Models/IMessageInfoModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantDataModels.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/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Implements/ClientStorage.cs b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Implements/ClientStorage.cs index e42427d..ac34f82 100644 --- a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Implements/ClientStorage.cs +++ b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Implements/ClientStorage.cs @@ -39,7 +39,7 @@ namespace PrecastConcretePlantDatabaseImplement.Implements using var context = new PrecastConcretePlantDatabase(); return context.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; + (!string.IsNullOrEmpty(model.Email) && x.Email == model.Email && (string.IsNullOrEmpty(model.Password) || x.Password == model.Password)))?.GetViewModel; } public ClientViewModel? Insert(ClientBindingModel model) diff --git a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Implements/MessageInfoStorage.cs b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..7d25959 --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,52 @@ +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.SearchModels; +using PrecastConcretePlantContracts.StoragesContracts; +using PrecastConcretePlantContracts.ViewModels; +using PrecastConcretePlantDatabaseImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantDatabaseImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + public List GetFullList() + { + using var context = new PrecastConcretePlantDatabase(); + return context.MessageInfos.Select(x => x.GetViewModel).ToList(); + } + public List GetFilteredList(MessageInfoSearchModel model) + { + if (!model.ClientId.HasValue) + { + return new(); + } + using var context = new PrecastConcretePlantDatabase(); + 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 PrecastConcretePlantDatabase(); + 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 PrecastConcretePlantDatabase(); + context.MessageInfos.Add(newMessage); + context.SaveChanges(); + return newMessage.GetViewModel; + } + } +} \ No newline at end of file diff --git a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Migrations/20240513211930_MessageAddingMigration.Designer.cs b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Migrations/20240513211930_MessageAddingMigration.Designer.cs new file mode 100644 index 0000000..b04af9e --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Migrations/20240513211930_MessageAddingMigration.Designer.cs @@ -0,0 +1,298 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using PrecastConcretePlantDatabaseImplement; + +#nullable disable + +namespace PrecastConcretePlantDatabaseImplement.Migrations +{ + [DbContext(typeof(PrecastConcretePlantDatabase))] + [Migration("20240513211930_MessageAddingMigration")] + partial class MessageAddingMigration + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.3") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.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("PrecastConcretePlantDatabaseImplement.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("PrecastConcretePlantDatabaseImplement.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("PrecastConcretePlantDatabaseImplement.Models.MessageInfo", 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("MessageInfos"); + }); + + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.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("ImplementerId") + .HasColumnType("int"); + + b.Property("ReinforcedId") + .HasColumnType("int"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("Sum") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.HasIndex("ImplementerId"); + + b.HasIndex("ReinforcedId"); + + b.ToTable("Orders"); + }); + + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Reinforced", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Price") + .HasColumnType("float"); + + b.Property("ReinforcedName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Reinforceds"); + }); + + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.ReinforcedComponent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ComponentId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("ReinforcedId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ComponentId"); + + b.HasIndex("ReinforcedId"); + + b.ToTable("ReinforcedComponents"); + }); + + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.MessageInfo", b => + { + b.HasOne("PrecastConcretePlantDatabaseImplement.Models.Client", "Client") + .WithMany("ClientMessages") + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Order", b => + { + b.HasOne("PrecastConcretePlantDatabaseImplement.Models.Client", "Client") + .WithMany("ClientOrders") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("PrecastConcretePlantDatabaseImplement.Models.Implementer", "Implementer") + .WithMany("Order") + .HasForeignKey("ImplementerId"); + + b.HasOne("PrecastConcretePlantDatabaseImplement.Models.Reinforced", "Reinforced") + .WithMany("Orders") + .HasForeignKey("ReinforcedId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Client"); + + b.Navigation("Implementer"); + + b.Navigation("Reinforced"); + }); + + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.ReinforcedComponent", b => + { + b.HasOne("PrecastConcretePlantDatabaseImplement.Models.Component", "Component") + .WithMany("ReinforcedComponents") + .HasForeignKey("ComponentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("PrecastConcretePlantDatabaseImplement.Models.Reinforced", "Reinforced") + .WithMany("Components") + .HasForeignKey("ReinforcedId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Component"); + + b.Navigation("Reinforced"); + }); + + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Client", b => + { + b.Navigation("ClientMessages"); + + b.Navigation("ClientOrders"); + }); + + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Component", b => + { + b.Navigation("ReinforcedComponents"); + }); + + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Implementer", b => + { + b.Navigation("Order"); + }); + + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Reinforced", b => + { + b.Navigation("Components"); + + b.Navigation("Orders"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Migrations/20240513211930_MessageAddingMigration.cs b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Migrations/20240513211930_MessageAddingMigration.cs new file mode 100644 index 0000000..2f92b3a --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Migrations/20240513211930_MessageAddingMigration.cs @@ -0,0 +1,48 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace PrecastConcretePlantDatabaseImplement.Migrations +{ + /// + public partial class MessageAddingMigration : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "MessageInfos", + 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_MessageInfos", x => x.MessageId); + table.ForeignKey( + name: "FK_MessageInfos_Clients_ClientId", + column: x => x.ClientId, + principalTable: "Clients", + principalColumn: "Id"); + }); + + migrationBuilder.CreateIndex( + name: "IX_MessageInfos_ClientId", + table: "MessageInfos", + column: "ClientId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "MessageInfos"); + } + } +} diff --git a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Migrations/PrecastConcretePlantDatabaseModelSnapshot.cs b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Migrations/PrecastConcretePlantDatabaseModelSnapshot.cs index fc54fd5..e0d9e96 100644 --- a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Migrations/PrecastConcretePlantDatabaseModelSnapshot.cs +++ b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Migrations/PrecastConcretePlantDatabaseModelSnapshot.cs @@ -94,6 +94,36 @@ namespace PrecastConcretePlantDatabaseImplement.Migrations b.ToTable("Implementers"); }); + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.MessageInfo", 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("MessageInfos"); + }); + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -183,6 +213,15 @@ namespace PrecastConcretePlantDatabaseImplement.Migrations b.ToTable("ReinforcedComponents"); }); + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.MessageInfo", b => + { + b.HasOne("PrecastConcretePlantDatabaseImplement.Models.Client", "Client") + .WithMany("ClientMessages") + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Order", b => { b.HasOne("PrecastConcretePlantDatabaseImplement.Models.Client", "Client") @@ -229,6 +268,8 @@ namespace PrecastConcretePlantDatabaseImplement.Migrations modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Client", b => { + b.Navigation("ClientMessages"); + b.Navigation("ClientOrders"); }); diff --git a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Models/Client.cs b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Models/Client.cs index 2d39b3c..b94fa02 100644 --- a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Models/Client.cs +++ b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Models/Client.cs @@ -27,6 +27,8 @@ namespace PrecastConcretePlantDatabaseImplement.Models [ForeignKey("ClientId")] public virtual List ClientOrders { get; set; } = new(); + [ForeignKey("ClientId")] + public virtual List ClientMessages { get; set; } = new(); public static Client? Create(ClientBindingModel model) { diff --git a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Models/MessageInfo.cs b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..e1a1ecf --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Models/MessageInfo.cs @@ -0,0 +1,65 @@ +using Microsoft.EntityFrameworkCore; +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations.Schema; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using PrecastConcretePlantContracts.ViewModels; + +namespace PrecastConcretePlantDatabaseImplement.Models +{ + public class MessageInfo : IMessageInfoModel + { + [Key] + [DatabaseGenerated(DatabaseGeneratedOption.None)] + public string MessageId { get; set; } = string.Empty; + + public int? ClientId { get; set; } + + public virtual Client? Client { get; set; } + + [Required] + public string SenderName { get; set; } = string.Empty; + + [Required] + public DateTime DateDelivery { get; set; } + + [Required] + public string Subject { get; set; } = string.Empty; + + [Required] + public string Body { get; set; } = string.Empty; + + public static MessageInfo? Create(MessageInfoBindingModel? model) + { + if (model == null) + { + return null; + } + return new() + { + MessageId = model.MessageId, + ClientId = model.ClientId, + SenderName = model.SenderName, + DateDelivery = model.DateDelivery, + Subject = model.Subject, + Body = model.Body, + + }; + } + + public MessageInfoViewModel GetViewModel => new() + { + MessageId = MessageId, + ClientId = ClientId, + SenderName = SenderName, + DateDelivery = DateDelivery, + Subject = Subject, + Body = Body + }; + } +} \ No newline at end of file diff --git a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Models/Order.cs b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Models/Order.cs index b1d403c..e80de7d 100644 --- a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Models/Order.cs +++ b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Models/Order.cs @@ -84,6 +84,7 @@ namespace PrecastConcretePlantDatabaseImplement.Models ReinforcedName = Reinforced.ReinforcedName, ClientId = ClientId, ClientFIO = Client.ClientFIO, + ClientEmail = Client.Email, ImplementerId = ImplementerId, ImplementerFIO = Implementer != null ? Implementer.ImplementerFIO : null, Count = Count, diff --git a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/PrecastConcretePlantDatabase.cs b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/PrecastConcretePlantDatabase.cs index 81d61d6..7df30c6 100644 --- a/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/PrecastConcretePlantDatabase.cs +++ b/PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/PrecastConcretePlantDatabase.cs @@ -28,7 +28,9 @@ namespace PrecastConcretePlantDatabaseImplement 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/PrecastConcretePlant/PrecastConcretePlantFileImplement/DataFileSingleton.cs b/PrecastConcretePlant/PrecastConcretePlantFileImplement/DataFileSingleton.cs index e9daf05..34d764e 100644 --- a/PrecastConcretePlant/PrecastConcretePlantFileImplement/DataFileSingleton.cs +++ b/PrecastConcretePlant/PrecastConcretePlantFileImplement/DataFileSingleton.cs @@ -16,11 +16,13 @@ namespace PrecastConcretePlantFileImplement private readonly string ReinforcedFileName = "Reinforced.xml"; private readonly string ClientFileName = "Client.xml"; private readonly string ImplementerFileName = "Implementer.xml"; + private readonly string MessageInfoFileName = "MessageInfos.xml"; public List Components { get; private set; } public List Orders { get; private set; } public List Reinforceds { get; private set; } public List Clients { get; private set; } public List Implementers { get; private set; } + public List MessageInfos { get; private set; } public static DataFileSingleton GetInstance() { if (instance == null) @@ -34,6 +36,7 @@ namespace PrecastConcretePlantFileImplement public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement); public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", x => x.GetXElement); public void SaveImplementers() => SaveData(Implementers, ImplementerFileName, "Implementers", x => x.GetXElement); + public void SaveMessageInfos() => SaveData(MessageInfos, MessageInfoFileName, "MessageInfos", x => x.GetXElement); private DataFileSingleton() { Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!; @@ -41,7 +44,9 @@ namespace PrecastConcretePlantFileImplement Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!; Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!; Implementers = LoadData(ImplementerFileName, "Client", x => Implementer.Create(x)!)!; + MessageInfos = LoadData(MessageInfoFileName, "MessageInfo", x => MessageInfo.Create(x)!)!; } + private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) { if (File.Exists(filename)) diff --git a/PrecastConcretePlant/PrecastConcretePlantFileImplement/Implements/ClientStorage.cs b/PrecastConcretePlant/PrecastConcretePlantFileImplement/Implements/ClientStorage.cs index b0c92af..c6b9ef0 100644 --- a/PrecastConcretePlant/PrecastConcretePlantFileImplement/Implements/ClientStorage.cs +++ b/PrecastConcretePlant/PrecastConcretePlantFileImplement/Implements/ClientStorage.cs @@ -39,7 +39,7 @@ namespace PrecastConcretePlantFileImplement.Implements } 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)) + (!string.IsNullOrEmpty(model.Email) && x.Email == model.Email && (string.IsNullOrEmpty(model.Password) || x.Password == model.Password))) ?.GetViewModel; } public ClientViewModel? Insert(ClientBindingModel model) diff --git a/PrecastConcretePlant/PrecastConcretePlantFileImplement/Implements/MessageInfoStorage.cs b/PrecastConcretePlant/PrecastConcretePlantFileImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..0669b74 --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantFileImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,53 @@ +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.SearchModels; +using PrecastConcretePlantContracts.StoragesContracts; +using PrecastConcretePlantContracts.ViewModels; +using PrecastConcretePlantFileImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantFileImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + private readonly DataFileSingleton source; + public MessageInfoStorage() + { + source = DataFileSingleton.GetInstance(); + } + public List GetFullList() + { + return source.MessageInfos.Select(x => x.GetViewModel).ToList(); + } + public List GetFilteredList(MessageInfoSearchModel model) + { + if (!model.ClientId.HasValue) + { + return new(); + } + return source.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(); + } + return source.MessageInfos.FirstOrDefault(x => x.MessageId == model.MessageId)?.GetViewModel; + } + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = MessageInfo.Create(model); + if (newMessage == null) + { + return null; + } + source.MessageInfos.Add(newMessage); + source.SaveMessageInfos(); + return newMessage.GetViewModel; + } + } +} \ No newline at end of file diff --git a/PrecastConcretePlant/PrecastConcretePlantFileImplement/Implements/OrderStorage.cs b/PrecastConcretePlant/PrecastConcretePlantFileImplement/Implements/OrderStorage.cs index 5987b3b..90acc5f 100644 --- a/PrecastConcretePlant/PrecastConcretePlantFileImplement/Implements/OrderStorage.cs +++ b/PrecastConcretePlant/PrecastConcretePlantFileImplement/Implements/OrderStorage.cs @@ -93,6 +93,7 @@ namespace PrecastConcretePlantFileImplement.Implements if (client != null) { model.ClientFIO = client.ClientFIO; + model.ClientEmail = client.Email; } if (model.ImplementerId.HasValue) { diff --git a/PrecastConcretePlant/PrecastConcretePlantFileImplement/Models/MessageInfo.cs b/PrecastConcretePlant/PrecastConcretePlantFileImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..1a1e3b7 --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantFileImplement/Models/MessageInfo.cs @@ -0,0 +1,73 @@ +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.ViewModels; +using PrecastConcretePlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace PrecastConcretePlantFileImplement.Models +{ + public class MessageInfo : 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 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 static MessageInfo? Create(XElement element) + { + if (element == null) + { + return null; + } + string clientId = element.Element("ClientId")!.Value; + return new() + { + MessageId = element.Attribute("MessageId")!.Value, + ClientId = string.IsNullOrEmpty(clientId) ? null : Convert.ToInt32(clientId), + SenderName = element.Element("SenderName")!.Value, + DateDelivery = Convert.ToDateTime(element.Element("DateDelivery")!.Value), + Subject = element.Element("Subject")!.Value, + Body = element.Element("Body")!.Value + }; + } + public MessageInfoViewModel GetViewModel => new() + { + MessageId = MessageId, + ClientId = ClientId, + SenderName = SenderName, + DateDelivery = DateDelivery, + Subject = Subject, + Body = Body + }; + public XElement GetXElement => new("MessageInfo", + new XAttribute("MessageId", MessageId), + new XElement("ClientId", ClientId.ToString()), + new XElement("SenderName", SenderName), + new XElement("DateDelivery", DateDelivery.ToString()), + new XElement("Subject", Subject), + new XElement("Body", Body)); + } +} \ No newline at end of file diff --git a/PrecastConcretePlant/PrecastConcretePlantListImplement/DataListSingleton.cs b/PrecastConcretePlant/PrecastConcretePlantListImplement/DataListSingleton.cs index f98d893..d4374f6 100644 --- a/PrecastConcretePlant/PrecastConcretePlantListImplement/DataListSingleton.cs +++ b/PrecastConcretePlant/PrecastConcretePlantListImplement/DataListSingleton.cs @@ -15,6 +15,7 @@ namespace PrecastConcretePlantListImplement public List Reinforceds { get; set; } public List Clients { get; set; } public List Implementers { get; set; } + public List MessageInfos { get; set; } private DataListSingleton() { Components = new List(); @@ -22,6 +23,7 @@ namespace PrecastConcretePlantListImplement Reinforceds = new List(); Clients = new List(); Implementers = new List(); + MessageInfos = new List(); } public static DataListSingleton GetInstance() { diff --git a/PrecastConcretePlant/PrecastConcretePlantListImplement/Implements/ClientStorage.cs b/PrecastConcretePlant/PrecastConcretePlantListImplement/Implements/ClientStorage.cs index 9ba440e..4a384c9 100644 --- a/PrecastConcretePlant/PrecastConcretePlantListImplement/Implements/ClientStorage.cs +++ b/PrecastConcretePlant/PrecastConcretePlantListImplement/Implements/ClientStorage.cs @@ -55,7 +55,7 @@ namespace PrecastConcretePlantListImplement.Implements { if ((model.Id.HasValue && client.Id == model.Id) || (!string.IsNullOrEmpty(model.ClientFIO) && client.ClientFIO == model.ClientFIO) || - (!string.IsNullOrEmpty(model.Email) && !string.IsNullOrEmpty(model.Password) && client.Email == model.Email && client.Password == model.Password)) + (!string.IsNullOrEmpty(model.Email) && model.Email == client.Email && (string.IsNullOrEmpty(model.Password) || (client.Password == model.Password)))) { return client.GetViewModel; } diff --git a/PrecastConcretePlant/PrecastConcretePlantListImplement/Implements/MessageInfoStorage.cs b/PrecastConcretePlant/PrecastConcretePlantListImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..c6c3615 --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantListImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,73 @@ +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.SearchModels; +using PrecastConcretePlantContracts.StoragesContracts; +using PrecastConcretePlantContracts.ViewModels; +using PrecastConcretePlantListImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantListImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + private readonly DataListSingleton _source; + public MessageInfoStorage() + { + _source = DataListSingleton.GetInstance(); + } + public List GetFullList() + { + var resout = new List(); + foreach (var message in _source.MessageInfos) + { + resout.Add(message.GetViewModel); + } + return resout; + } + public List GetFilteredList(MessageInfoSearchModel model) + { + var resout = new List(); + if (string.IsNullOrEmpty(model.MessageId) && !model.ClientId.HasValue) + { + return resout; + } + foreach (var message in _source.MessageInfos) + { + if ((!string.IsNullOrEmpty(model.MessageId) && message.MessageId == model.MessageId) || + (model.ClientId.HasValue && message.ClientId == model.ClientId)) + { + resout.Add(message.GetViewModel); + } + } + return resout; + } + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (string.IsNullOrEmpty(model.MessageId)) + { + return null; + } + foreach (var message in _source.MessageInfos) + { + if (message.MessageId == model.MessageId) + { + return message.GetViewModel; + } + } + return null; + } + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = MessageInfo.Create(model); + if (newMessage == null) + { + return null; + } + _source.MessageInfos.Add(newMessage); + return newMessage.GetViewModel; + } + } +} \ No newline at end of file diff --git a/PrecastConcretePlant/PrecastConcretePlantListImplement/Implements/OrderStorage.cs b/PrecastConcretePlant/PrecastConcretePlantListImplement/Implements/OrderStorage.cs index 94d8a74..fbaf04d 100644 --- a/PrecastConcretePlant/PrecastConcretePlantListImplement/Implements/OrderStorage.cs +++ b/PrecastConcretePlant/PrecastConcretePlantListImplement/Implements/OrderStorage.cs @@ -116,6 +116,7 @@ namespace PrecastConcretePlantListImplement.Implements if (client.Id == model.ClientId) { model.ClientFIO = client.ClientFIO; + model.ClientEmail = client.Email; break; } } diff --git a/PrecastConcretePlant/PrecastConcretePlantListImplement/Models/MessageInfo.cs b/PrecastConcretePlant/PrecastConcretePlantListImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..aa84a6f --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantListImplement/Models/MessageInfo.cs @@ -0,0 +1,47 @@ +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.ViewModels; +using PrecastConcretePlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantListImplement.Models +{ + public class MessageInfo : 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 MessageInfo? Create(MessageInfoBindingModel? model) + { + if (model == null) + { + return null; + } + return new() + { + MessageId = model.MessageId, + ClientId = model.ClientId, + SenderName = model.SenderName, + DateDelivery = model.DateDelivery, + Subject = model.Subject, + Body = model.Body, + + }; + } + public MessageInfoViewModel GetViewModel => new() + { + MessageId = MessageId, + ClientId = ClientId, + SenderName = SenderName, + DateDelivery = DateDelivery, + Subject = Subject, + Body = Body + }; + } +} \ No newline at end of file diff --git a/PrecastConcretePlant/PrecastConcretePlantRestApi/Controllers/ClientController.cs b/PrecastConcretePlant/PrecastConcretePlantRestApi/Controllers/ClientController.cs index 7a738e5..ca2d4f8 100644 --- a/PrecastConcretePlant/PrecastConcretePlantRestApi/Controllers/ClientController.cs +++ b/PrecastConcretePlant/PrecastConcretePlantRestApi/Controllers/ClientController.cs @@ -3,6 +3,7 @@ using PrecastConcretePlantContracts.BindingModels; using PrecastConcretePlantContracts.BusinessLogicsContracts; using PrecastConcretePlantContracts.SearchModels; using PrecastConcretePlantContracts.ViewModels; +using System.Net; namespace PrecastConcretePlantRestApi.Controllers { @@ -14,10 +15,12 @@ namespace PrecastConcretePlantRestApi.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] @@ -48,7 +51,7 @@ namespace PrecastConcretePlantRestApi.Controllers catch (Exception ex) { _logger.LogError(ex, "Ошибка регистрации"); - throw; + Response.StatusCode = (int)HttpStatusCode.NotAcceptable; } } @@ -65,5 +68,21 @@ namespace PrecastConcretePlantRestApi.Controllers throw; } } + [HttpGet] + public List? GetMessages(int clientId) + { + try + { + return _mailLogic.ReadList(new MessageInfoSearchModel + { + ClientId = clientId + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения писем клиента"); + throw; + } + } } } \ No newline at end of file diff --git a/PrecastConcretePlant/PrecastConcretePlantRestApi/Program.cs b/PrecastConcretePlant/PrecastConcretePlantRestApi/Program.cs index 5ace417..316bd54 100644 --- a/PrecastConcretePlant/PrecastConcretePlantRestApi/Program.cs +++ b/PrecastConcretePlant/PrecastConcretePlantRestApi/Program.cs @@ -1,5 +1,7 @@ using Microsoft.OpenApi.Models; using PrecastConcretePlantBusinessLogic.BusinessLogics; +using PrecastConcretePlantBusinessLogic.MailWorker; +using PrecastConcretePlantContracts.BindingModels; using PrecastConcretePlantContracts.BusinessLogicsContracts; using PrecastConcretePlantContracts.StoragesContracts; using PrecastConcretePlantDatabaseImplement.Implements; @@ -14,11 +16,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 @@ -30,6 +36,18 @@ 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/PrecastConcretePlant/PrecastConcretePlantRestApi/Properties/launchSettings.json b/PrecastConcretePlant/PrecastConcretePlantRestApi/Properties/launchSettings.json index 5515e23..3d89f91 100644 --- a/PrecastConcretePlant/PrecastConcretePlantRestApi/Properties/launchSettings.json +++ b/PrecastConcretePlant/PrecastConcretePlantRestApi/Properties/launchSettings.json @@ -1,23 +1,14 @@ { - "$schema": "https://json.schemastore.org/launchsettings.json", - "iisSettings": { - "windowsAuthentication": false, - "anonymousAuthentication": true, - "iisExpress": { - "applicationUrl": "http://localhost:33063", - "sslPort": 44303 - } - }, "profiles": { "PrecastConcretePlantRestApi": { "commandName": "Project", - "dotnetRunMessages": true, "launchBrowser": true, "launchUrl": "swagger", - "applicationUrl": "https://localhost:7170;http://localhost:5028", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" - } + }, + "dotnetRunMessages": true, + "applicationUrl": "http://localhost:7103;http://localhost:5131" }, "IIS Express": { "commandName": "IISExpress", @@ -27,5 +18,14 @@ "ASPNETCORE_ENVIRONMENT": "Development" } } + }, + "$schema": "https://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:33063", + "sslPort": 0 + } } -} +} \ No newline at end of file diff --git a/PrecastConcretePlant/PrecastConcretePlantRestApi/appsettings.json b/PrecastConcretePlant/PrecastConcretePlantRestApi/appsettings.json index 10f68b8..3fe6ffe 100644 --- a/PrecastConcretePlant/PrecastConcretePlantRestApi/appsettings.json +++ b/PrecastConcretePlant/PrecastConcretePlantRestApi/appsettings.json @@ -5,5 +5,12 @@ "Microsoft.AspNetCore": "Warning" } }, - "AllowedHosts": "*" + "AllowedHosts": "*", + + "SmtpClientHost": "smtp.gmail.com", + "SmtpClientPort": "587", + "PopHost": "pop.gmail.com", + "PopPort": "995", + "MailLogin": "sofi.v.ivanova@gmail.com", + "MailPassword": "yipk wuhw fagk sghi" } diff --git a/PrecastConcretePlant/PrecastConcretePlantView/App.config b/PrecastConcretePlant/PrecastConcretePlantView/App.config new file mode 100644 index 0000000..c9370b3 --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantView/App.config @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/PrecastConcretePlant/PrecastConcretePlantView/FormMail.Designer.cs b/PrecastConcretePlant/PrecastConcretePlantView/FormMail.Designer.cs new file mode 100644 index 0000000..f1efe26 --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantView/FormMail.Designer.cs @@ -0,0 +1,67 @@ +namespace PrecastConcretePlantView +{ + 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.AllowUserToAddRows = false; + dataGridView.AllowUserToDeleteRows = false; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Dock = DockStyle.Fill; + dataGridView.Location = new Point(0, 0); + dataGridView.Margin = new Padding(3, 2, 3, 2); + dataGridView.Name = "dataGridView"; + dataGridView.ReadOnly = true; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 29; + dataGridView.Size = new Size(688, 202); + dataGridView.TabIndex = 1; + // + // FormMail + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(688, 202); + 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/PrecastConcretePlant/PrecastConcretePlantView/FormMail.cs b/PrecastConcretePlant/PrecastConcretePlantView/FormMail.cs new file mode 100644 index 0000000..9eba8e7 --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantView/FormMail.cs @@ -0,0 +1,55 @@ +using Microsoft.Extensions.Logging; +using PrecastConcretePlantBusinessLogic.BusinessLogics; +using PrecastConcretePlantContracts.BusinessLogicsContracts; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace PrecastConcretePlantView +{ + public partial class FormMail : Form + { + private readonly ILogger _logger; + private readonly IMessageInfoLogic _logic; + + public FormMail(ILogger logger, IMessageInfoLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + private void LoadData() + { + try + { + var list = _logic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["MessageId"].Visible = false; + dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["Body"].AutoSizeMode = + DataGridViewAutoSizeColumnMode.Fill; + } + _logger.LogInformation("Загрузка почтовых собщений"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки почтовых сообщений"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void FormMail_Load(object sender, EventArgs e) + { + LoadData(); + } + } +} \ No newline at end of file diff --git a/PrecastConcretePlant/PrecastConcretePlantView/FormMail.resx b/PrecastConcretePlant/PrecastConcretePlantView/FormMail.resx new file mode 100644 index 0000000..f298a7b --- /dev/null +++ b/PrecastConcretePlant/PrecastConcretePlantView/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/PrecastConcretePlant/PrecastConcretePlantView/FormMain.Designer.cs b/PrecastConcretePlant/PrecastConcretePlantView/FormMain.Designer.cs index 5e2a851..190c527 100644 --- a/PrecastConcretePlant/PrecastConcretePlantView/FormMain.Designer.cs +++ b/PrecastConcretePlant/PrecastConcretePlantView/FormMain.Designer.cs @@ -33,23 +33,24 @@ компонентыToolStripMenuItem = new ToolStripMenuItem(); жБИзделияToolStripMenuItem = new ToolStripMenuItem(); клиентыToolStripMenuItem = new ToolStripMenuItem(); + исполнителиToolStripMenuItem = new ToolStripMenuItem(); отчётыToolStripMenuItem = new ToolStripMenuItem(); ComponentsToolStripMenuItem = new ToolStripMenuItem(); ComponentReinforcedToolStripMenuItem = new ToolStripMenuItem(); OrdersToolStripMenuItem = new ToolStripMenuItem(); + запускРаботToolStripMenuItem = new ToolStripMenuItem(); dataGridView = new DataGridView(); buttonCreateOrder = new Button(); buttonIssuedOrder = new Button(); buttonRef = new Button(); - запускРаботToolStripMenuItem = new ToolStripMenuItem(); - исполнителиToolStripMenuItem = new ToolStripMenuItem(); + письмаToolStripMenuItem = new ToolStripMenuItem(); menuStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); SuspendLayout(); // // menuStrip1 // - menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчётыToolStripMenuItem, запускРаботToolStripMenuItem }); + menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчётыToolStripMenuItem, запускРаботToolStripMenuItem, письмаToolStripMenuItem }); menuStrip1.Location = new Point(0, 0); menuStrip1.Name = "menuStrip1"; menuStrip1.Size = new Size(1134, 24); @@ -66,24 +67,31 @@ // компонентыToolStripMenuItem // компонентыToolStripMenuItem.Name = "компонентыToolStripMenuItem"; - компонентыToolStripMenuItem.Size = new Size(180, 22); + компонентыToolStripMenuItem.Size = new Size(149, 22); компонентыToolStripMenuItem.Text = "Компоненты"; компонентыToolStripMenuItem.Click += компонентыToolStripMenuItem_Click; // // жБИзделияToolStripMenuItem // жБИзделияToolStripMenuItem.Name = "жБИзделияToolStripMenuItem"; - жБИзделияToolStripMenuItem.Size = new Size(180, 22); + жБИзделияToolStripMenuItem.Size = new Size(149, 22); жБИзделияToolStripMenuItem.Text = "ЖБ изделия"; жБИзделияToolStripMenuItem.Click += жБИзделияToolStripMenuItem_Click; // // клиентыToolStripMenuItem // клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; - клиентыToolStripMenuItem.Size = new Size(180, 22); + клиентыToolStripMenuItem.Size = new Size(149, 22); клиентыToolStripMenuItem.Text = "Клиенты"; клиентыToolStripMenuItem.Click += клиентыToolStripMenuItem_Click; // + // исполнителиToolStripMenuItem + // + исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; + исполнителиToolStripMenuItem.Size = new Size(149, 22); + исполнителиToolStripMenuItem.Text = "Исполнители"; + исполнителиToolStripMenuItem.Click += исполнителиToolStripMenuItem_Click; + // // отчётыToolStripMenuItem // отчётыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { ComponentsToolStripMenuItem, ComponentReinforcedToolStripMenuItem, OrdersToolStripMenuItem }); @@ -112,6 +120,13 @@ OrdersToolStripMenuItem.Text = "Заказы"; OrdersToolStripMenuItem.Click += OrdersToolStripMenuItem_Click; // + // запускРаботToolStripMenuItem + // + запускРаботToolStripMenuItem.Name = "запускРаботToolStripMenuItem"; + запускРаботToolStripMenuItem.Size = new Size(92, 20); + запускРаботToolStripMenuItem.Text = "Запуск работ"; + запускРаботToolStripMenuItem.Click += запускРаботToolStripMenuItem_Click; + // // dataGridView // dataGridView.BackgroundColor = SystemColors.ControlLightLight; @@ -153,19 +168,12 @@ buttonRef.UseVisualStyleBackColor = true; buttonRef.Click += buttonRef_Click; // - // запускРаботToolStripMenuItem + // письмаToolStripMenuItem // - запускРаботToolStripMenuItem.Name = "запускРаботToolStripMenuItem"; - запускРаботToolStripMenuItem.Size = new Size(92, 20); - запускРаботToolStripMenuItem.Text = "Запуск работ"; - запускРаботToolStripMenuItem.Click += запускРаботToolStripMenuItem_Click; - // - // исполнителиToolStripMenuItem - // - исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; - исполнителиToolStripMenuItem.Size = new Size(180, 22); - исполнителиToolStripMenuItem.Text = "Исполнители"; - исполнителиToolStripMenuItem.Click += исполнителиToolStripMenuItem_Click; + письмаToolStripMenuItem.Name = "письмаToolStripMenuItem"; + письмаToolStripMenuItem.Size = new Size(62, 20); + письмаToolStripMenuItem.Text = "Письма"; + письмаToolStripMenuItem.Click += письмаToolStripMenuItem_Click; // // FormMain // @@ -205,5 +213,6 @@ private ToolStripMenuItem клиентыToolStripMenuItem; private ToolStripMenuItem запускРаботToolStripMenuItem; private ToolStripMenuItem исполнителиToolStripMenuItem; + private ToolStripMenuItem письмаToolStripMenuItem; } } \ No newline at end of file diff --git a/PrecastConcretePlant/PrecastConcretePlantView/FormMain.cs b/PrecastConcretePlant/PrecastConcretePlantView/FormMain.cs index 54f8b20..d901b6c 100644 --- a/PrecastConcretePlant/PrecastConcretePlantView/FormMain.cs +++ b/PrecastConcretePlant/PrecastConcretePlantView/FormMain.cs @@ -43,6 +43,7 @@ namespace PrecastConcretePlantView dataGridView.DataSource = list; dataGridView.Columns["ReinforcedId"].Visible = false; dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["ClientEmail"].Visible = false; dataGridView.Columns["ImplementerId"].Visible = false; dataGridView.Columns["ReinforcedName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; @@ -220,5 +221,14 @@ namespace PrecastConcretePlantView _workProcess.DoWork((Program.ServiceProvider?.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(FormMail)); + if (service is FormMail form) + { + form.ShowDialog(); + } + } } } diff --git a/PrecastConcretePlant/PrecastConcretePlantView/Program.cs b/PrecastConcretePlant/PrecastConcretePlantView/Program.cs index 482686f..1651007 100644 --- a/PrecastConcretePlant/PrecastConcretePlantView/Program.cs +++ b/PrecastConcretePlant/PrecastConcretePlantView/Program.cs @@ -3,7 +3,9 @@ using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; using PrecastConcretePlantBusinessLogic.BusinessLogics; using PrecastConcretePlantBusinessLogic.Implements; +using PrecastConcretePlantBusinessLogic.MailWorker; using PrecastConcretePlantBusinessLogic.OfficePackage; +using PrecastConcretePlantContracts.BindingModels; using PrecastConcretePlantContracts.BusinessLogicsContracts; using PrecastConcretePlantContracts.StoragesContracts; using PrecastConcretePlantDatabaseImplement.Implements; @@ -29,8 +31,30 @@ namespace PrecastConcretePlant 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) { services.AddLogging(option => @@ -44,6 +68,8 @@ namespace PrecastConcretePlant services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); services.AddTransient(); @@ -51,10 +77,12 @@ namespace PrecastConcretePlant services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddSingleton(); services.AddTransient(); @@ -70,6 +98,8 @@ namespace PrecastConcretePlant services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); } + private static void MailCheck(object obj) => ServiceProvider?.GetService()?.MailCheck(); } } \ No newline at end of file