diff --git a/FishFactory/FishFactoryBusinessLogic/BusinessLogics/ClientLogic.cs b/FishFactory/FishFactoryBusinessLogic/BusinessLogics/ClientLogic.cs index 9cd8cf6..2fa9f10 100644 --- a/FishFactory/FishFactoryBusinessLogic/BusinessLogics/ClientLogic.cs +++ b/FishFactory/FishFactoryBusinessLogic/BusinessLogics/ClientLogic.cs @@ -7,114 +7,114 @@ using FishFactoryContracts.ViewModels; namespace FishFactoryBusinessLogic.BusinessLogics { - public class ClientLogic : IClientLogic - { - private readonly ILogger _logger; - private readonly IClientStorage _clientStorage; - public ClientLogic(ILogger logger, IClientStorage clientStorage) - { - _logger = logger; - _clientStorage = clientStorage; - } - public bool Create(ClientBindingModel model) - { - CheckModel(model); - if (_clientStorage.Insert(model) == null) - { - _logger.LogWarning("Insert operation failed"); - return false; - } - return true; - } + public class ClientLogic : IClientLogic + { + private readonly ILogger _logger; + private readonly IClientStorage _clientStorage; + public ClientLogic(ILogger logger, IClientStorage clientStorage) + { + _logger = logger; + _clientStorage = clientStorage; + } + public bool Create(ClientBindingModel model) + { + CheckModel(model); + if (_clientStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } - public bool Delete(ClientBindingModel model) - { - CheckModel(model, false); - _logger.LogInformation("Delete. Id: {Id}", model.Id); - if (_clientStorage.Delete(model) == null) - { - _logger.LogWarning("Delete operation failed"); - return false; - } - return true; - } + public bool Delete(ClientBindingModel model) + { + CheckModel(model, false); + _logger.LogInformation("Delete. Id: {Id}", model.Id); + if (_clientStorage.Delete(model) == null) + { + _logger.LogWarning("Delete operation failed"); + return false; + } + return true; + } - public ClientViewModel? ReadElement(ClientSearchModel model) - { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - _logger.LogInformation("ReadElement. ClientFIO: {ClientFIO}. Email: {Email}. Id: {Id}.", - model.ClientFIO, model.Email, model.Id); - var element = _clientStorage.GetElement(model); - if (element == null) - { - _logger.LogWarning("ReadElement element not found"); - return null; - } - _logger.LogInformation("ReadElement find. Id: {Id}", element.Id); - return element; - } + public ClientViewModel? ReadElement(ClientSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + _logger.LogInformation("ReadElement. ClientFIO: {ClientFIO}. Email: {Email}. Id: {Id}.", + model.ClientFIO, model.Email, model.Id); + var element = _clientStorage.GetElement(model); + if (element == null) + { + _logger.LogWarning("ReadElement element not found"); + return null; + } + _logger.LogInformation("ReadElement find. Id: {Id}", element.Id); + return element; + } - public List? ReadList(ClientSearchModel? model) - { - _logger.LogInformation("ReadList. ClientFIO: {ClientFIO}. Email: {Email}. Id: {Id}.", - model?.ClientFIO, model?.Email, model?.Id); - var list = model == null ? _clientStorage.GetFullList() : - _clientStorage.GetFilteredList(model); - if (list == null) - { - _logger.LogWarning("ReadList return null list"); - return null; - } - _logger.LogInformation("ReadList. Count: {Count}", list.Count); - return list; - } + public List? ReadList(ClientSearchModel? model) + { + _logger.LogInformation("ReadList. ClientFIO: {ClientFIO}. Email: {Email}. Id: {Id}.", + model?.ClientFIO, model?.Email, model?.Id); + var list = model == null ? _clientStorage.GetFullList() : + _clientStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + _logger.LogInformation("ReadList. Count: {Count}", list.Count); + return list; + } - public bool Update(ClientBindingModel model) - { - CheckModel(model); - if (_clientStorage.Update(model) == null) - { - _logger.LogWarning("Update operation failed"); - return false; - } - return true; - } + public bool Update(ClientBindingModel model) + { + CheckModel(model); + if (_clientStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + return true; + } - private void CheckModel(ClientBindingModel model, bool withParams = true) - { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - if (!withParams) - { - return; - } - if (string.IsNullOrEmpty(model.ClientFIO)) - { - throw new ArgumentNullException("Нет ФИО клиента", nameof(model.ClientFIO)); - } - if (string.IsNullOrEmpty(model.Email)) - { - throw new ArgumentNullException("Нет почты клиента", nameof(model.Email)); - } - if (string.IsNullOrEmpty(model.Password)) - { - throw new ArgumentNullException("Нет пароля клиента", nameof(model.Password)); - } - _logger.LogInformation("Client. ClientFIO: {ClientFIO}. Email: {Email}. Id: {Id}", - model.ClientFIO, model.Email, model.Id); - var element = _clientStorage.GetElement(new ClientSearchModel - { - Email = model.Email - }); - if (element != null && element.Id != model.Id) - { - throw new InvalidOperationException("Клиент с такой почтой уже есть"); - } - } - } + private void CheckModel(ClientBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (!withParams) + { + return; + } + if (string.IsNullOrEmpty(model.ClientFIO)) + { + throw new ArgumentNullException("Нет ФИО клиента", nameof(model.ClientFIO)); + } + if (string.IsNullOrEmpty(model.Email)) + { + throw new ArgumentNullException("Нет почты клиента", nameof(model.Email)); + } + if (string.IsNullOrEmpty(model.Password)) + { + throw new ArgumentNullException("Нет пароля клиента", nameof(model.Password)); + } + _logger.LogInformation("Client. ClientFIO: {ClientFIO}. Email: {Email}. Id: {Id}", + model.ClientFIO, model.Email, model.Id); + var element = _clientStorage.GetElement(new ClientSearchModel + { + Email = model.Email + }); + if (element != null && element.Id != model.Id) + { + throw new InvalidOperationException("Клиент с такой почтой уже есть"); + } + } + } } \ No newline at end of file diff --git a/FishFactory/FishFactoryBusinessLogic/BusinessLogics/MessageInfoLogic.cs b/FishFactory/FishFactoryBusinessLogic/BusinessLogics/MessageInfoLogic.cs new file mode 100644 index 0000000..6ff0ac0 --- /dev/null +++ b/FishFactory/FishFactoryBusinessLogic/BusinessLogics/MessageInfoLogic.cs @@ -0,0 +1,43 @@ +using Microsoft.Extensions.Logging; +using FishFactoryContracts.BindingModels; +using FishFactoryContracts.BusinessLogicsContracts; +using FishFactoryContracts.SearchModels; +using FishFactoryContracts.StoragesContracts; +using FishFactoryContracts.ViewModels; + +namespace FishFactoryBusinessLogic.BusinessLogics +{ + public class MessageInfoLogic : IMessageInfoLogic + { + private readonly ILogger _logger; + private readonly IMessageInfoStorage _messageStorage; + public MessageInfoLogic(ILogger logger, IMessageInfoStorage messageStorage) + { + _logger = logger; + _messageStorage = messageStorage; + } + public bool Create(MessageInfoBindingModel model) + { + if (_messageStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } + public List? ReadList(MessageInfoSearchModel? model) + { + _logger.LogInformation("ReadList. MessageId:{MessageId}.ClientId:{ClientId} ", + model?.MessageId, model?.ClientId); + var list = model == null ? _messageStorage.GetFullList() : + _messageStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + _logger.LogInformation("ReadList. Count: {Count}", list.Count); + return list; + } + } +} \ No newline at end of file diff --git a/FishFactory/FishFactoryBusinessLogic/BusinessLogics/OrderLogic.cs b/FishFactory/FishFactoryBusinessLogic/BusinessLogics/OrderLogic.cs index f420a28..ef1e5d3 100644 --- a/FishFactory/FishFactoryBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/FishFactory/FishFactoryBusinessLogic/BusinessLogics/OrderLogic.cs @@ -1,4 +1,5 @@ using Microsoft.Extensions.Logging; +using FishFactoryBusinessLogic.MailWorker; using FishFactoryContracts.BindingModels; using FishFactoryContracts.BusinessLogicsContracts; using FishFactoryContracts.SearchModels; @@ -12,13 +13,17 @@ namespace FishFactoryBusinessLogic.BusinessLogics { private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; + private readonly AbstractMailWorker _mailWorker; + private readonly IClientLogic _clientLogic; static readonly object _locker = new object(); - 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) { @@ -29,13 +34,15 @@ namespace FishFactoryBusinessLogic.BusinessLogics return false; } model.Status = OrderStatus.Принят; - if (_orderStorage.Insert(model) == null) - { + var result = _orderStorage.Insert(model); + if (result == null) + { model.Status = OrderStatus.Неизвестен; _logger.LogWarning("Insert operation failed"); return false; } - return true; + SendOrderMessage(result.ClientId, $"Рыбный завод, Заказ №{result.Id}", $"Заказ №{result.Id} от {result.DateCreate} на сумму {result.Sum:0.00} принят"); + return true; } public bool StatusUpdate(OrderBindingModel model, OrderStatus newStatus) @@ -57,13 +64,15 @@ namespace FishFactoryBusinessLogic.BusinessLogics model.DateImplement = viewModel.DateImplement; } CheckModel(model, false); - if (_orderStorage.Update(model) == null) - { + var result = _orderStorage.Update(model); + if (result == null) + { model.Status--; _logger.LogWarning("Update operation failed"); return false; } - return true; + SendOrderMessage(result.ClientId, $"Рыбный завод, Заказ №{result.Id}", $"Заказ №{model.Id} изменен статус на {result.Status}"); + return true; } public bool TakeOrderInWork(OrderBindingModel model) @@ -139,5 +148,21 @@ namespace FishFactoryBusinessLogic.BusinessLogics } _logger.LogInformation("Order. OrderID:{Id}. Sum:{ Sum}. CannedId: { CannedId}", model.Id, model.Sum, model.CannedId); } - } + + private bool SendOrderMessage(int clientId, string subject, string text) + { + var client = _clientLogic.ReadElement(new() { Id = clientId }); + if (client == null) + { + return false; + } + _mailWorker.MailSendAsync(new() + { + MailAddress = client.Email, + Subject = subject, + Text = text + }); + return true; + } + } } diff --git a/FishFactory/FishFactoryBusinessLogic/FishFactoryBusinessLogic.csproj b/FishFactory/FishFactoryBusinessLogic/FishFactoryBusinessLogic.csproj index 76111d2..7322c42 100644 --- a/FishFactory/FishFactoryBusinessLogic/FishFactoryBusinessLogic.csproj +++ b/FishFactory/FishFactoryBusinessLogic/FishFactoryBusinessLogic.csproj @@ -8,12 +8,14 @@ + + diff --git a/FishFactory/FishFactoryBusinessLogic/MailWorker/AbstractMailWorker.cs b/FishFactory/FishFactoryBusinessLogic/MailWorker/AbstractMailWorker.cs new file mode 100644 index 0000000..2fb840e --- /dev/null +++ b/FishFactory/FishFactoryBusinessLogic/MailWorker/AbstractMailWorker.cs @@ -0,0 +1,97 @@ +using FishFactoryContracts.BindingModels; +using FishFactoryContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using FishFactoryBusinessLogic.BusinessLogics; + +namespace FishFactoryBusinessLogic.MailWorker +{ + public abstract class AbstractMailWorker + { + protected string _mailLogin = string.Empty; + + protected string _mailPassword = string.Empty; + + protected string _smtpClientHost = string.Empty; + + protected int _smtpClientPort; + + protected string _popHost = string.Empty; + + protected int _popPort; + + private readonly IMessageInfoLogic _messageInfoLogic; + + private readonly IClientLogic _clientLogic; + + private readonly ILogger _logger; + + public AbstractMailWorker(ILogger logger, IMessageInfoLogic messageInfoLogic, IClientLogic clientLogic) + { + _logger = logger; + _messageInfoLogic = messageInfoLogic; + _clientLogic = clientLogic; + } + + public void MailConfig(MailConfigBindingModel config) + { + _mailLogin = config.MailLogin; + _mailPassword = config.MailPassword; + _smtpClientHost = config.SmtpClientHost; + _smtpClientPort = config.SmtpClientPort; + _popHost = config.PopHost; + _popPort = config.PopPort; + _logger.LogDebug("Config: {login}, {password}, {clientHost}, {clientPOrt}, {popHost}, {popPort}", _mailLogin, _mailPassword, _smtpClientHost, _smtpClientPort, _popHost, _popPort); + } + + public async void MailSendAsync(MailSendInfoBindingModel info) + { + if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword)) + { + return; + } + + if (string.IsNullOrEmpty(_smtpClientHost) || _smtpClientPort == 0) + { + return; + } + + if (string.IsNullOrEmpty(info.MailAddress) || string.IsNullOrEmpty(info.Subject) || string.IsNullOrEmpty(info.Text)) + { + return; + } + + _logger.LogDebug("Send Mail: {To}, {Subject}", info.MailAddress, info.Subject); + await SendMailAsync(info); + } + + public async void MailCheck() + { + if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword)) + { + return; + } + + if (string.IsNullOrEmpty(_popHost) || _popPort == 0) + { + return; + } + + if (_messageInfoLogic == null) + { + return; + } + + var list = await ReceiveMailAsync(); + _logger.LogDebug("Check Mail: {Count} new mails", list.Count); + foreach (var mail in list) + { + mail.ClientId = _clientLogic.ReadElement(new() { Email = mail.SenderName })?.Id; + _messageInfoLogic.Create(mail); + } + } + + protected abstract Task SendMailAsync(MailSendInfoBindingModel info); + + protected abstract Task> ReceiveMailAsync(); + } +} \ No newline at end of file diff --git a/FishFactory/FishFactoryBusinessLogic/MailWorker/MailKitWorker.cs b/FishFactory/FishFactoryBusinessLogic/MailWorker/MailKitWorker.cs new file mode 100644 index 0000000..5a27a1e --- /dev/null +++ b/FishFactory/FishFactoryBusinessLogic/MailWorker/MailKitWorker.cs @@ -0,0 +1,79 @@ +using FishFactoryBusinessLogic.BusinessLogics; +using FishFactoryContracts.BindingModels; +using FishFactoryContracts.BusinessLogicsContracts; +using MailKit.Net.Pop3; +using MailKit.Security; +using Microsoft.Extensions.Logging; +using System.Net; +using System.Net.Mail; +using System.Text; + +namespace FishFactoryBusinessLogic.MailWorker +{ + public class MailKitWorker : AbstractMailWorker + { + public MailKitWorker(ILogger logger, IMessageInfoLogic messageInfoLogic, IClientLogic clientLogic) : base(logger, messageInfoLogic, clientLogic) { } + + protected override async Task SendMailAsync(MailSendInfoBindingModel info) + { + using var objMailMessage = new MailMessage(); + using var objSmtpClient = new SmtpClient(_smtpClientHost, _smtpClientPort); + try + { + objMailMessage.From = new MailAddress(_mailLogin); + objMailMessage.To.Add(new MailAddress(info.MailAddress)); + objMailMessage.Subject = info.Subject; + objMailMessage.Body = info.Text; + objMailMessage.SubjectEncoding = Encoding.UTF8; + objMailMessage.BodyEncoding = Encoding.UTF8; + + objSmtpClient.UseDefaultCredentials = false; + objSmtpClient.EnableSsl = true; + objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; + objSmtpClient.Credentials = new NetworkCredential(_mailLogin, _mailPassword); + + await Task.Run(() => objSmtpClient.Send(objMailMessage)); + } + catch (Exception) + { + throw; + } + } + + protected override async Task> ReceiveMailAsync() + { + var list = new List(); + using var client = new Pop3Client(); + await Task.Run(() => + { + try + { + client.Connect(_popHost, _popPort, SecureSocketOptions.SslOnConnect); + client.Authenticate(_mailLogin, _mailPassword); + for (int i = 0; i < client.Count; i++) + { + var message = client.GetMessage(i); + foreach (var mail in message.From.Mailboxes) + { + list.Add(new MessageInfoBindingModel + { + DateDelivery = message.Date.DateTime, + MessageId = message.MessageId, + SenderName = mail.Address, + Subject = message.Subject, + Body = message.TextBody + }); + } + } + } + catch (AuthenticationException) + { } + finally + { + client.Disconnect(true); + } + }); + return list; + } + } +} \ No newline at end of file diff --git a/FishFactory/FishFactoryClientApp/Controllers/HomeController.cs b/FishFactory/FishFactoryClientApp/Controllers/HomeController.cs index 3618851..58623ce 100644 --- a/FishFactory/FishFactoryClientApp/Controllers/HomeController.cs +++ b/FishFactory/FishFactoryClientApp/Controllers/HomeController.cs @@ -143,5 +143,15 @@ namespace FishFactoryClientApp.Controllers var prod = APIClient.GetRequest($"api/main/getCanned?cannedId={canned}"); 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/FishFactory/FishFactoryClientApp/Views/Home/Mails.cshtml b/FishFactory/FishFactoryClientApp/Views/Home/Mails.cshtml new file mode 100644 index 0000000..87e6be6 --- /dev/null +++ b/FishFactory/FishFactoryClientApp/Views/Home/Mails.cshtml @@ -0,0 +1,54 @@ +@using FishFactoryContracts.ViewModels + +@model List + +@{ + ViewData["Title"] = "Mails"; +} + +
+

Письма

+
+ + +
+ @{ + if (Model == null) + { +

Авторизируйтесь

+ return; + } + + + + + + + + + + + @foreach (var item in Model) + { + + + + + + } + +
+ Дата письма + + Заголовок + + Текст +
+ @Html.DisplayFor(modelItem => item.DateDelivery) + + @Html.DisplayFor(modelItem => item.Subject) + + @Html.DisplayFor(modelItem => item.Body) +
+ } +
\ No newline at end of file diff --git a/FishFactory/FishFactoryClientApp/Views/Shared/_Layout.cshtml b/FishFactory/FishFactoryClientApp/Views/Shared/_Layout.cshtml index 3259a63..769b6ee 100644 --- a/FishFactory/FishFactoryClientApp/Views/Shared/_Layout.cshtml +++ b/FishFactory/FishFactoryClientApp/Views/Shared/_Layout.cshtml @@ -25,6 +25,9 @@ + diff --git a/FishFactory/FishFactoryContracts/BindingModels/MailConfigBindingModel.cs b/FishFactory/FishFactoryContracts/BindingModels/MailConfigBindingModel.cs new file mode 100644 index 0000000..eb5b07b --- /dev/null +++ b/FishFactory/FishFactoryContracts/BindingModels/MailConfigBindingModel.cs @@ -0,0 +1,12 @@ +namespace FishFactoryContracts.BindingModels +{ + public class MailConfigBindingModel + { + public string MailLogin { get; set; } = string.Empty; + public string MailPassword { get; set; } = string.Empty; + public string SmtpClientHost { get; set; } = string.Empty; + public int SmtpClientPort { get; set; } + public string PopHost { get; set; } = string.Empty; + public int PopPort { get; set; } + } +} \ No newline at end of file diff --git a/FishFactory/FishFactoryContracts/BindingModels/MailSendInfoBindingModel.cs b/FishFactory/FishFactoryContracts/BindingModels/MailSendInfoBindingModel.cs new file mode 100644 index 0000000..ad20eb0 --- /dev/null +++ b/FishFactory/FishFactoryContracts/BindingModels/MailSendInfoBindingModel.cs @@ -0,0 +1,11 @@ +namespace FishFactoryContracts.BindingModels +{ + public class MailSendInfoBindingModel + { + public string MailAddress { get; set; } = string.Empty; + + public string Subject { get; set; } = string.Empty; + + public string Text { get; set; } = string.Empty; + } +} \ No newline at end of file diff --git a/FishFactory/FishFactoryContracts/BindingModels/MessageInfoBindingModel.cs b/FishFactory/FishFactoryContracts/BindingModels/MessageInfoBindingModel.cs new file mode 100644 index 0000000..617da32 --- /dev/null +++ b/FishFactory/FishFactoryContracts/BindingModels/MessageInfoBindingModel.cs @@ -0,0 +1,19 @@ +using FishFactoryDataModels.Models; + +namespace FishFactoryContracts.BindingModels +{ + public class MessageInfoBindingModel : IMessageInfoModel + { + public string MessageId { get; set; } = string.Empty; + + public int? ClientId { get; set; } + + public string SenderName { get; set; } = string.Empty; + + public string Subject { get; set; } = string.Empty; + + public string Body { get; set; } = string.Empty; + + public DateTime DateDelivery { get; set; } + } +} \ No newline at end of file diff --git a/FishFactory/FishFactoryContracts/BusinessLogicsContracts/IMessageInfoLogic.cs b/FishFactory/FishFactoryContracts/BusinessLogicsContracts/IMessageInfoLogic.cs new file mode 100644 index 0000000..ddb3ff1 --- /dev/null +++ b/FishFactory/FishFactoryContracts/BusinessLogicsContracts/IMessageInfoLogic.cs @@ -0,0 +1,13 @@ +using FishFactoryContracts.BindingModels; +using FishFactoryContracts.SearchModels; +using FishFactoryContracts.ViewModels; + +namespace FishFactoryContracts.BusinessLogicsContracts +{ + public interface IMessageInfoLogic + { + List? ReadList(MessageInfoSearchModel? model); + + bool Create(MessageInfoBindingModel model); + } +} \ No newline at end of file diff --git a/FishFactory/FishFactoryContracts/SearchModels/MessageInfoSearchModel.cs b/FishFactory/FishFactoryContracts/SearchModels/MessageInfoSearchModel.cs new file mode 100644 index 0000000..b2b3d31 --- /dev/null +++ b/FishFactory/FishFactoryContracts/SearchModels/MessageInfoSearchModel.cs @@ -0,0 +1,9 @@ +namespace FishFactoryContracts.SearchModels +{ + public class MessageInfoSearchModel + { + public int? ClientId { get; set; } + + public string? MessageId { get; set; } + } +} \ No newline at end of file diff --git a/FishFactory/FishFactoryContracts/StoragesContracts/IMessageInfoStorage.cs b/FishFactory/FishFactoryContracts/StoragesContracts/IMessageInfoStorage.cs new file mode 100644 index 0000000..ae8e02f --- /dev/null +++ b/FishFactory/FishFactoryContracts/StoragesContracts/IMessageInfoStorage.cs @@ -0,0 +1,17 @@ +using FishFactoryContracts.BindingModels; +using FishFactoryContracts.SearchModels; +using FishFactoryContracts.ViewModels; + +namespace FishFactoryContracts.StoragesContracts +{ + public interface IMessageInfoStorage + { + List GetFullList(); + + List GetFilteredList(MessageInfoSearchModel model); + + MessageInfoViewModel? GetElement(MessageInfoSearchModel model); + + MessageInfoViewModel? Insert(MessageInfoBindingModel model); + } +} \ No newline at end of file diff --git a/FishFactory/FishFactoryContracts/ViewModels/MessageInfoViewModel.cs b/FishFactory/FishFactoryContracts/ViewModels/MessageInfoViewModel.cs new file mode 100644 index 0000000..d56ce06 --- /dev/null +++ b/FishFactory/FishFactoryContracts/ViewModels/MessageInfoViewModel.cs @@ -0,0 +1,24 @@ +using FishFactoryDataModels.Models; +using System.ComponentModel; + +namespace FishFactoryContracts.ViewModels +{ + public class MessageInfoViewModel : IMessageInfoModel + { + public string MessageId { get; set; } = string.Empty; + + public int? ClientId { get; set; } + + [DisplayName("Отправитель")] + public string SenderName { get; set; } = string.Empty; + + [DisplayName("Дата письма")] + public DateTime DateDelivery { get; set; } + + [DisplayName("Заголовок")] + public string Subject { get; set; } = string.Empty; + + [DisplayName("Текст")] + public string Body { get; set; } = string.Empty; + } +} \ No newline at end of file diff --git a/FishFactory/FishFactoryDataModels/Models/IMessageInfoModel.cs b/FishFactory/FishFactoryDataModels/Models/IMessageInfoModel.cs new file mode 100644 index 0000000..accd4b9 --- /dev/null +++ b/FishFactory/FishFactoryDataModels/Models/IMessageInfoModel.cs @@ -0,0 +1,17 @@ +namespace FishFactoryDataModels.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/FishFactory/FishFactoryDatabaseImplement/FishFactoryDatabase.cs b/FishFactory/FishFactoryDatabaseImplement/FishFactoryDatabase.cs index 63d3d64..5ff4cde 100644 --- a/FishFactory/FishFactoryDatabaseImplement/FishFactoryDatabase.cs +++ b/FishFactory/FishFactoryDatabaseImplement/FishFactoryDatabase.cs @@ -24,5 +24,6 @@ namespace FishFactoryDatabaseImplement public virtual DbSet Clients { set; get; } public virtual DbSet Implementers { set; get; } + public virtual DbSet Messages { set; get; } } } diff --git a/FishFactory/FishFactoryDatabaseImplement/Implements/MessageInfoStorage.cs b/FishFactory/FishFactoryDatabaseImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..d5eff80 --- /dev/null +++ b/FishFactory/FishFactoryDatabaseImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,51 @@ +using FishFactoryContracts.BindingModels; +using FishFactoryContracts.SearchModels; +using FishFactoryContracts.StoragesContracts; +using FishFactoryContracts.ViewModels; +using FishFactoryDatabaseImplement.Models; + +namespace FishFactoryDatabaseImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (model.MessageId == null) + return null; + using var context = new FishFactoryDatabase(); + return context.Messages.FirstOrDefault(x => x.MessageId == model.MessageId)?.GetViewModel; + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + if (!model.ClientId.HasValue) + return new(); + using var context = new FishFactoryDatabase(); + return context.Messages + .Where(x => x.ClientId == model.ClientId) + .Select(x => x.GetViewModel) + .ToList(); + } + + public List GetFullList() + { + using var context = new FishFactoryDatabase(); + return context.Messages + .Select(x => x.GetViewModel) + .ToList(); + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = Message.Create(model); + if (newMessage == null) + { + return null; + } + using var context = new FishFactoryDatabase(); + context.Messages.Add(newMessage); + context.SaveChanges(); + return newMessage.GetViewModel; + } + } +} \ No newline at end of file diff --git a/FishFactory/FishFactoryDatabaseImplement/Migrations/20240512140313_InitMail.Designer.cs b/FishFactory/FishFactoryDatabaseImplement/Migrations/20240512140313_InitMail.Designer.cs new file mode 100644 index 0000000..5c4ccd8 --- /dev/null +++ b/FishFactory/FishFactoryDatabaseImplement/Migrations/20240512140313_InitMail.Designer.cs @@ -0,0 +1,285 @@ +// +using System; +using FishFactoryDatabaseImplement; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace FishFactoryDatabaseImplement.Migrations +{ + [DbContext(typeof(FishFactoryDatabase))] + [Migration("20240512140313_InitMail")] + partial class InitMail + { + /// + 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("FishFactoryDatabaseImplement.Models.Canned", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("CannedName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Price") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.ToTable("CannedList"); + }); + + modelBuilder.Entity("FishFactoryDatabaseImplement.Models.CannedComponent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("CannedId") + .HasColumnType("int"); + + b.Property("ComponentId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("CannedId"); + + b.HasIndex("ComponentId"); + + b.ToTable("CannedComponents"); + }); + + modelBuilder.Entity("FishFactoryDatabaseImplement.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("FishFactoryDatabaseImplement.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("FishFactoryDatabaseImplement.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("FishFactoryDatabaseImplement.Models.Message", b => + { + b.Property("MessageId") + .HasColumnType("nvarchar(450)"); + + b.Property("Body") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("int"); + + b.Property("DateDelivery") + .HasColumnType("datetime2"); + + b.Property("SenderName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Subject") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("MessageId"); + + b.ToTable("Messages"); + }); + + modelBuilder.Entity("FishFactoryDatabaseImplement.Models.Order", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("CannedId") + .HasColumnType("int"); + + 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("Status") + .HasColumnType("int"); + + b.Property("Sum") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.HasIndex("CannedId"); + + b.HasIndex("ClientId"); + + b.HasIndex("ImplementerId"); + + b.ToTable("Orders"); + }); + + modelBuilder.Entity("FishFactoryDatabaseImplement.Models.CannedComponent", b => + { + b.HasOne("FishFactoryDatabaseImplement.Models.Canned", "Canned") + .WithMany("Components") + .HasForeignKey("CannedId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("FishFactoryDatabaseImplement.Models.Component", "Component") + .WithMany("CannedComponents") + .HasForeignKey("ComponentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Canned"); + + b.Navigation("Component"); + }); + + modelBuilder.Entity("FishFactoryDatabaseImplement.Models.Order", b => + { + b.HasOne("FishFactoryDatabaseImplement.Models.Canned", "Canned") + .WithMany("Orders") + .HasForeignKey("CannedId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("FishFactoryDatabaseImplement.Models.Client", "Client") + .WithMany("Orders") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("FishFactoryDatabaseImplement.Models.Implementer", "Implementer") + .WithMany("Orders") + .HasForeignKey("ImplementerId"); + + b.Navigation("Canned"); + + b.Navigation("Client"); + + b.Navigation("Implementer"); + }); + + modelBuilder.Entity("FishFactoryDatabaseImplement.Models.Canned", b => + { + b.Navigation("Components"); + + b.Navigation("Orders"); + }); + + modelBuilder.Entity("FishFactoryDatabaseImplement.Models.Client", b => + { + b.Navigation("Orders"); + }); + + modelBuilder.Entity("FishFactoryDatabaseImplement.Models.Component", b => + { + b.Navigation("CannedComponents"); + }); + + modelBuilder.Entity("FishFactoryDatabaseImplement.Models.Implementer", b => + { + b.Navigation("Orders"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/FishFactory/FishFactoryDatabaseImplement/Migrations/20240512140313_InitMail.cs b/FishFactory/FishFactoryDatabaseImplement/Migrations/20240512140313_InitMail.cs new file mode 100644 index 0000000..3d94075 --- /dev/null +++ b/FishFactory/FishFactoryDatabaseImplement/Migrations/20240512140313_InitMail.cs @@ -0,0 +1,38 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace FishFactoryDatabaseImplement.Migrations +{ + /// + public partial class InitMail : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Messages", + columns: table => new + { + MessageId = table.Column(type: "nvarchar(450)", nullable: false), + ClientId = table.Column(type: "int", nullable: true), + SenderName = table.Column(type: "nvarchar(max)", nullable: false), + DateDelivery = table.Column(type: "datetime2", nullable: false), + Subject = table.Column(type: "nvarchar(max)", nullable: false), + Body = table.Column(type: "nvarchar(max)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Messages", x => x.MessageId); + }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Messages"); + } + } +} diff --git a/FishFactory/FishFactoryDatabaseImplement/Migrations/FishFactoryDatabaseModelSnapshot.cs b/FishFactory/FishFactoryDatabaseImplement/Migrations/FishFactoryDatabaseModelSnapshot.cs index fb857c0..a2873a2 100644 --- a/FishFactory/FishFactoryDatabaseImplement/Migrations/FishFactoryDatabaseModelSnapshot.cs +++ b/FishFactory/FishFactoryDatabaseImplement/Migrations/FishFactoryDatabaseModelSnapshot.cs @@ -140,6 +140,34 @@ namespace FishFactoryDatabaseImplement.Migrations b.ToTable("Implementers"); }); + modelBuilder.Entity("FishFactoryDatabaseImplement.Models.Message", b => + { + b.Property("MessageId") + .HasColumnType("nvarchar(450)"); + + b.Property("Body") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("int"); + + b.Property("DateDelivery") + .HasColumnType("datetime2"); + + b.Property("SenderName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Subject") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("MessageId"); + + b.ToTable("Messages"); + }); + modelBuilder.Entity("FishFactoryDatabaseImplement.Models.Order", b => { b.Property("Id") diff --git a/FishFactory/FishFactoryDatabaseImplement/Models/Message.cs b/FishFactory/FishFactoryDatabaseImplement/Models/Message.cs new file mode 100644 index 0000000..be4a554 --- /dev/null +++ b/FishFactory/FishFactoryDatabaseImplement/Models/Message.cs @@ -0,0 +1,49 @@ +using FishFactoryContracts.BindingModels; +using FishFactoryContracts.ViewModels; +using FishFactoryDataModels.Models; +using System.ComponentModel.DataAnnotations; + +namespace FishFactoryDatabaseImplement.Models +{ + public class Message : IMessageInfoModel + { + [Key] + public string MessageId { get; private set; } = string.Empty; + public int? ClientId { get; private set; } + [Required] + public string SenderName { get; private set; } = string.Empty; + [Required] + public DateTime DateDelivery { get; private set; } = DateTime.Now; + [Required] + public string Subject { get; private set; } = string.Empty; + [Required] + 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, + ClientId = model.ClientId, + MessageId = model.MessageId, + SenderName = model.SenderName, + DateDelivery = model.DateDelivery, + }; + } + + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Subject = Subject, + ClientId = ClientId, + MessageId = MessageId, + SenderName = SenderName, + DateDelivery = DateDelivery, + }; + } +} \ No newline at end of file diff --git a/FishFactory/FishFactoryFileImplement/DataFileSingleton.cs b/FishFactory/FishFactoryFileImplement/DataFileSingleton.cs index a491b6f..b8bc4e7 100644 --- a/FishFactory/FishFactoryFileImplement/DataFileSingleton.cs +++ b/FishFactory/FishFactoryFileImplement/DataFileSingleton.cs @@ -11,11 +11,13 @@ namespace FishFactoryFileImplement private readonly string CannedFileName = "Canned.xml"; private readonly string ClientFileName = "Client.xml"; private readonly string ImplementerFileName = "Implementer.xml"; + private readonly string MessageFileName = "Message.xml"; public List Components { get; private set; } public List Orders { get; private set; } public List Clients { get; private set; } public List ListCanned { get; private set; } public List Implementers { get; private set; } + public List Messages { get; private set; } public static DataFileSingleton GetInstance() { if (instance == null) @@ -33,13 +35,16 @@ namespace FishFactoryFileImplement 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 SaveMessages() => SaveData(Messages, MessageFileName, "Messages", x => x.GetXElement); + private DataFileSingleton() - { + { Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!; ListCanned = LoadData(CannedFileName, "Canned", x => Canned.Create(x)!)!; Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!; Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!; Implementers = LoadData(ImplementerFileName, "Implementer", x => Implementer.Create(x)!)!; + Messages = LoadData(MessageFileName, "Message", x => Message.Create(x)!)!; } private static List? LoadData(string filename, string xmlNodeName, diff --git a/FishFactory/FishFactoryFileImplement/Implements/MessageInfoStorage.cs b/FishFactory/FishFactoryFileImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..e26b99c --- /dev/null +++ b/FishFactory/FishFactoryFileImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,52 @@ +using FishFactoryContracts.BindingModels; +using FishFactoryContracts.SearchModels; +using FishFactoryContracts.StoragesContracts; +using FishFactoryContracts.ViewModels; +using FishFactoryFileImplement.Models; + +namespace FishFactoryFileImplement.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; + } + } +} \ No newline at end of file diff --git a/FishFactory/FishFactoryFileImplement/Models/Message.cs b/FishFactory/FishFactoryFileImplement/Models/Message.cs new file mode 100644 index 0000000..80b8f43 --- /dev/null +++ b/FishFactory/FishFactoryFileImplement/Models/Message.cs @@ -0,0 +1,76 @@ +using FishFactoryContracts.BindingModels; +using FishFactoryContracts.ViewModels; +using FishFactoryDataModels.Models; +using System.Reflection; +using System.Xml.Linq; + +namespace FishFactoryFileImplement.Models +{ + public class Message : IMessageInfoModel + { + public string MessageId { get; private set; } = string.Empty; + + public int? ClientId { get; private set; } + + public string SenderName { get; private set; } = string.Empty; + + public DateTime DateDelivery { get; private set; } = DateTime.Now; + + public string Subject { get; private set; } = string.Empty; + + public string Body { get; private set; } = string.Empty; + + public static Message? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Subject = model.Subject, + DateDelivery = model.DateDelivery, + SenderName = model.SenderName, + ClientId = model.ClientId, + MessageId = model.MessageId + }; + } + + public static Message? Create(XElement element) + { + if (element == null) + { + return null; + } + return new() + { + Body = element.Attribute("Body")!.Value, + Subject = element.Attribute("Subject")!.Value, + DateDelivery = Convert.ToDateTime(element.Attribute("DateDelivery")!.Value), + SenderName = element.Attribute("SenderName")!.Value, + ClientId = Convert.ToInt32(element.Attribute("ClientId")!.Value), + MessageId = element.Attribute("MessageId")!.Value, + }; + } + + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Subject = Subject, + DateDelivery = DateDelivery, + SenderName = SenderName, + ClientId = ClientId, + MessageId = MessageId + }; + + public XElement GetXElement => new("MessageInfo", + new XAttribute("Subject", Subject), + new XAttribute("Body", Body), + new XAttribute("ClientId", ClientId), + new XAttribute("MessageId", MessageId), + new XAttribute("SenderName", SenderName), + new XAttribute("DateDelivery", DateDelivery) + ); + } +} \ No newline at end of file diff --git a/FishFactory/FishFactoryListImplement/DataListSingleton.cs b/FishFactory/FishFactoryListImplement/DataListSingleton.cs index 2e73fbb..3a3ae88 100644 --- a/FishFactory/FishFactoryListImplement/DataListSingleton.cs +++ b/FishFactory/FishFactoryListImplement/DataListSingleton.cs @@ -10,6 +10,7 @@ namespace FishFactoryListImplement public List ListCanned { get; set; } public List Clients { get; set; } public List Implementers { get; set; } + public List Messages { get; set; } private DataListSingleton() { @@ -18,6 +19,7 @@ namespace FishFactoryListImplement ListCanned = new List(); Clients = new List(); Implementers = new List(); + Messages = new List(); } public static DataListSingleton GetInstance() diff --git a/FishFactory/FishFactoryListImplement/Implements/MessageInfoStorage.cs b/FishFactory/FishFactoryListImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..359adaa --- /dev/null +++ b/FishFactory/FishFactoryListImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,68 @@ +using FishFactoryContracts.BindingModels; +using FishFactoryContracts.SearchModels; +using FishFactoryContracts.StoragesContracts; +using FishFactoryContracts.ViewModels; +using FishFactoryListImplement.Models; + +namespace FishFactoryListImplement.Implements +{ + public 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; + } + } +} \ No newline at end of file diff --git a/FishFactory/FishFactoryListImplement/Models/Message.cs b/FishFactory/FishFactoryListImplement/Models/Message.cs new file mode 100644 index 0000000..2bf05ec --- /dev/null +++ b/FishFactory/FishFactoryListImplement/Models/Message.cs @@ -0,0 +1,48 @@ +using FishFactoryContracts.BindingModels; +using FishFactoryContracts.ViewModels; +using FishFactoryDataModels.Models; + +namespace FishFactoryListImplement.Models +{ + public class Message : IMessageInfoModel + { + public string MessageId { get; private set; } = string.Empty; + + public int? ClientId { get; private set; } + + public string SenderName { get; private set; } = string.Empty; + + public DateTime DateDelivery { get; private set; } = DateTime.Now; + + public string Subject { get; private set; } = string.Empty; + + public string Body { get; private set; } = string.Empty; + + public static Message? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Subject = model.Subject, + DateDelivery = model.DateDelivery, + SenderName = model.SenderName, + ClientId = model.ClientId, + MessageId = model.MessageId + }; + } + + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Subject = Subject, + DateDelivery = DateDelivery, + SenderName = SenderName, + ClientId = ClientId, + MessageId = MessageId + }; + } +} \ No newline at end of file diff --git a/FishFactory/FishFactoryRestApi/Controllers/ClientController.cs b/FishFactory/FishFactoryRestApi/Controllers/ClientController.cs index f67e427..469c4a0 100644 --- a/FishFactory/FishFactoryRestApi/Controllers/ClientController.cs +++ b/FishFactory/FishFactoryRestApi/Controllers/ClientController.cs @@ -3,6 +3,7 @@ using FishFactoryContracts.BusinessLogicsContracts; using FishFactoryContracts.SearchModels; using FishFactoryContracts.ViewModels; using Microsoft.AspNetCore.Mvc; +using System.Net; namespace FishFactoryRestApi.Controllers { @@ -14,11 +15,14 @@ namespace FishFactoryRestApi.Controllers private readonly IClientLogic _logic; - public ClientController(IClientLogic logic, ILogger logger) - { + private readonly IMessageInfoLogic _mailLogic; + + public ClientController(IClientLogic logic, ILogger logger, IMessageInfoLogic mailLogic) + { _logger = logger; _logic = logic; - } + _mailLogic = mailLogic; + } [HttpGet] public ClientViewModel? Login(string login, string password) @@ -48,8 +52,8 @@ namespace FishFactoryRestApi.Controllers catch (Exception ex) { _logger.LogError(ex, "Ошибка регистрации"); - throw; - } + Response.StatusCode = (int)HttpStatusCode.NotAcceptable; + } } [HttpPost] @@ -65,5 +69,22 @@ namespace FishFactoryRestApi.Controllers throw; } } - } + + [HttpGet] + public List? GetMessages(int clientId) + { + try + { + return _mailLogic.ReadList(new MessageInfoSearchModel + { + ClientId = clientId + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения писем клиента"); + throw; + } + } + } } \ No newline at end of file diff --git a/FishFactory/FishFactoryRestApi/FishFactoryRestApi.csproj b/FishFactory/FishFactoryRestApi/FishFactoryRestApi.csproj index 36d85ac..45f1d45 100644 --- a/FishFactory/FishFactoryRestApi/FishFactoryRestApi.csproj +++ b/FishFactory/FishFactoryRestApi/FishFactoryRestApi.csproj @@ -8,7 +8,7 @@ - + diff --git a/FishFactory/FishFactoryRestApi/Program.cs b/FishFactory/FishFactoryRestApi/Program.cs index 74ff857..56f3e19 100644 --- a/FishFactory/FishFactoryRestApi/Program.cs +++ b/FishFactory/FishFactoryRestApi/Program.cs @@ -3,6 +3,8 @@ using FishFactoryContracts.BusinessLogicsContracts; using FishFactoryContracts.StoragesContracts; using FishFactoryDatabaseImplement.Implements; using Microsoft.OpenApi.Models; +using FishFactoryBusinessLogic.MailWorker; +using FishFactoryContracts.BindingModels; var builder = WebApplication.CreateBuilder(args); @@ -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,17 @@ builder.Services.AddSwaggerGen(c => var app = builder.Build(); +var mailSender = app.Services.GetService(); +mailSender?.MailConfig(new MailConfigBindingModel +{ + MailLogin = builder.Configuration?.GetSection("MailLogin")?.Value?.ToString() ?? string.Empty, + MailPassword = builder.Configuration?.GetSection("MailPassword")?.Value?.ToString() ?? string.Empty, + SmtpClientHost = builder.Configuration?.GetSection("SmtpClientHost")?.Value?.ToString() ?? string.Empty, + SmtpClientPort = Convert.ToInt32(builder.Configuration?.GetSection("SmtpClientPort")?.Value?.ToString()), + PopHost = builder.Configuration?.GetSection("PopHost")?.Value?.ToString() ?? string.Empty, + PopPort = Convert.ToInt32(builder.Configuration?.GetSection("PopPort")?.Value?.ToString()) +}); + // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { diff --git a/FishFactory/FishFactoryRestApi/appsettings.json b/FishFactory/FishFactoryRestApi/appsettings.json index ec04bc1..5732212 100644 --- a/FishFactory/FishFactoryRestApi/appsettings.json +++ b/FishFactory/FishFactoryRestApi/appsettings.json @@ -5,5 +5,12 @@ "Microsoft.AspNetCore": "Warning" } }, - "AllowedHosts": "*" + "AllowedHosts": "*", + + "SmtpClientHost": "smtp.gmail.com", + "SmtpClientPort": "587", + "PopHost": "pop.gmail.com", + "PopPort": "995", + "MailLogin": "labarpp7@gmail.com", + "MailPassword": "hasy gdtx phra ddri" } \ No newline at end of file diff --git a/FishFactory/FishFactoryView/App.config b/FishFactory/FishFactoryView/App.config new file mode 100644 index 0000000..10062d6 --- /dev/null +++ b/FishFactory/FishFactoryView/App.config @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/FishFactory/FishFactoryView/FormCanned.Designer.cs b/FishFactory/FishFactoryView/FormCanned.Designer.cs index 0e1e17e..89f1187 100644 --- a/FishFactory/FishFactoryView/FormCanned.Designer.cs +++ b/FishFactory/FishFactoryView/FormCanned.Designer.cs @@ -217,7 +217,7 @@ Controls.Add(labelName); Name = "FormCanned"; Text = "Консервы"; - Load += FormSushi_Load; + Load += FormCanned_Load; groupBoxComponents.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); ResumeLayout(false); diff --git a/FishFactory/FishFactoryView/FormCanned.cs b/FishFactory/FishFactoryView/FormCanned.cs index c5b0fe1..96d0ee9 100644 --- a/FishFactory/FishFactoryView/FormCanned.cs +++ b/FishFactory/FishFactoryView/FormCanned.cs @@ -21,7 +21,7 @@ namespace FishFactoryView _logic = logic; _cannedComponents = new Dictionary(); } - private void FormSushi_Load(object sender, EventArgs e) + private void FormCanned_Load(object sender, EventArgs e) { if (_id.HasValue) { diff --git a/FishFactory/FishFactoryView/FormMails.Designer.cs b/FishFactory/FishFactoryView/FormMails.Designer.cs new file mode 100644 index 0000000..f9491aa --- /dev/null +++ b/FishFactory/FishFactoryView/FormMails.Designer.cs @@ -0,0 +1,64 @@ +using DocumentFormat.OpenXml.Wordprocessing; + +namespace FishFactoryView +{ + partial class FormMails + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + dataGridView = new DataGridView(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // dataGridView + // + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Dock = DockStyle.Fill; + dataGridView.Location = new Point(0, 0); + dataGridView.Name = "dataGridView"; + dataGridView.RowTemplate.Height = 25; + dataGridView.Size = new Size(803, 450); + dataGridView.TabIndex = 0; + // + // FormMails + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(800, 450); + Controls.Add(dataGridView); + Name = "FormMails"; + Text = "Письма"; + Load += FormMails_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView; + } +} \ No newline at end of file diff --git a/FishFactory/FishFactoryView/FormMails.cs b/FishFactory/FishFactoryView/FormMails.cs new file mode 100644 index 0000000..b6d8fad --- /dev/null +++ b/FishFactory/FishFactoryView/FormMails.cs @@ -0,0 +1,41 @@ +using Microsoft.Extensions.Logging; +using FishFactoryContracts.BusinessLogicsContracts; +using System.Windows.Forms; + +namespace FishFactoryView +{ + public partial class FormMails : Form + { + private readonly ILogger _logger; + private readonly IMessageInfoLogic _logic; + + public FormMails(ILogger logger, IMessageInfoLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + private void FormMails_Load(object sender, EventArgs e) + { + try + { + var list = _logic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["MessageId"].Visible = false; + dataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + _logger.LogInformation("Загрузка писем"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки писем"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + } +} \ No newline at end of file diff --git a/FishFactory/FishFactoryView/FormMails.resx b/FishFactory/FishFactoryView/FormMails.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/FishFactory/FishFactoryView/FormMails.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/FishFactory/FishFactoryView/FormMain.Designer.cs b/FishFactory/FishFactoryView/FormMain.Designer.cs index b1b89ca..adcd7a2 100644 --- a/FishFactory/FishFactoryView/FormMain.Designer.cs +++ b/FishFactory/FishFactoryView/FormMain.Designer.cs @@ -43,7 +43,8 @@ this.buttonSetToFinish = new System.Windows.Forms.Button(); this.buttonCreateOrder = new System.Windows.Forms.Button(); this.dataGridView = new System.Windows.Forms.DataGridView(); - this.menuStrip.SuspendLayout(); + this.lettersToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.menuStrip.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); this.SuspendLayout(); // @@ -52,7 +53,8 @@ this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.reference_booksToolStripMenuItem, this.reportsToolStripMenuItem, - this.startOfWorkToolStripMenuItem}); + this.startOfWorkToolStripMenuItem, + this.lettersToolStripMenuItem}); this.menuStrip.Location = new System.Drawing.Point(0, 0); this.menuStrip.Name = "menuStrip"; this.menuStrip.Size = new System.Drawing.Size(1086, 24); @@ -136,6 +138,13 @@ this.startOfWorkToolStripMenuItem.Text = "Запуск работ"; this.startOfWorkToolStripMenuItem.Click += new System.EventHandler(this.DoWorkToolStripMenuItem_Click); // + // lettersToolStripMenuItem + // + this.lettersToolStripMenuItem.Name = "lettersToolStripMenuItem"; + this.lettersToolStripMenuItem.Size = new System.Drawing.Size(62, 20); + this.lettersToolStripMenuItem.Text = "Письма"; + this.lettersToolStripMenuItem.Click += new System.EventHandler(this.MailsToolStripMenuItem_Click); + // // buttonUpdate // this.buttonUpdate.Location = new System.Drawing.Point(905, 253); @@ -220,5 +229,6 @@ private ToolStripMenuItem clientsToolStripMenuItem; private ToolStripMenuItem performersToolStripMenuItem; private ToolStripMenuItem startOfWorkToolStripMenuItem; + private ToolStripMenuItem lettersToolStripMenuItem; } } \ No newline at end of file diff --git a/FishFactory/FishFactoryView/FormMain.cs b/FishFactory/FishFactoryView/FormMain.cs index 0fb437c..9f7afbc 100644 --- a/FishFactory/FishFactoryView/FormMain.cs +++ b/FishFactory/FishFactoryView/FormMain.cs @@ -206,6 +206,15 @@ namespace FishFactoryView { form.ShowDialog(); } - } + } + + private void MailsToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormMails)); + if (service is FormMails form) + { + form.ShowDialog(); + } + } } } diff --git a/FishFactory/FishFactoryView/Program.cs b/FishFactory/FishFactoryView/Program.cs index 258ff74..cae1df8 100644 --- a/FishFactory/FishFactoryView/Program.cs +++ b/FishFactory/FishFactoryView/Program.cs @@ -7,7 +7,8 @@ using FishFactoryBusinessLogic.OfficePackage; using FishFactoryContracts.BusinessLogicsContracts; using FishFactoryContracts.StoragesContracts; using FishFactoryDatabaseImplement.Implements; -using FishFactoryView; +using FishFactoryBusinessLogic.MailWorker; +using FishFactoryContracts.BindingModels; namespace FishFactoryView { @@ -28,8 +29,28 @@ namespace FishFactoryView 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"]) + }); - Application.Run(_serviceProvider.GetRequiredService()); + // + 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) @@ -44,13 +65,16 @@ namespace FishFactoryView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); + services.AddSingleton(); services.AddTransient(); services.AddTransient(); @@ -68,6 +92,9 @@ namespace FishFactoryView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); } - } + + private static void MailCheck(object obj) => ServiceProvider?.GetService()?.MailCheck(); + } }