From c8f16f65fee6c2be1f66869a6410a22e09dde36e Mon Sep 17 00:00:00 2001 From: dex_moth Date: Mon, 13 May 2024 23:46:59 +0400 Subject: [PATCH] =?UTF-8?q?=D1=83=D1=82=D1=80=D0=BE=20=D0=B2=D0=B5=D1=87?= =?UTF-8?q?=D0=B5=D1=80=D0=B0=20=D0=BC=D1=83=D0=B4=D1=80=D0=B5=D0=BD=D0=B5?= =?UTF-8?q?=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- FishFactory/App.config | 11 ++ FishFactory/Forms/FormMails.Designer.cs | 64 ++++++++++ FishFactory/Forms/FormMails.cs | 58 +++++++++ FishFactory/Forms/FormMails.resx | 120 ++++++++++++++++++ FishFactory/Forms/FormMain.Designer.cs | 11 +- FishFactory/Forms/FormMain.cs | 11 +- FishFactory/Program.cs | 29 +++++ .../BusinessLogic/MessageInfoLogic.cs | 85 +++++++++++++ .../BusinessLogic/OrderLogic.cs | 46 +++++-- .../FishFactoryBusinessLogic.csproj | 1 + .../MailWorker/AbstractMailWorker.cs | 80 ++++++++++++ .../MailWorker/MailKitWorker.cs | 77 +++++++++++ .../Controllers/ClientController.cs | 82 ++++++++++++ .../Controllers/HomeController.cs | 10 ++ FishFactoryClientApp/Views/Home/Mails.cshtml | 48 +++++++ .../Views/Shared/_Layout.cshtml | 3 + .../BindingModels/MailConfigBindingModel.cs | 12 ++ .../BindingModels/MailSendInfoBindingModel.cs | 9 ++ .../BindingModels/MessageInfoBindingModel.cs | 14 ++ .../IMessageInfoLogic.cs | 12 ++ .../SearchModels/MessageInfoSearchModel.cs | 8 ++ .../StoragesContracts/IMessageInfoStorage.cs | 14 ++ .../ViewModels/MessageInfoViewModel.cs | 24 ++++ .../ViewModels/OrderViewModel.cs | 9 +- .../Models/IMessageInfoModel.cs | 12 ++ .../FishFactoryDatabase.cs | 1 + .../Implements/MessageInfoStorage.cs | 50 ++++++++ .../Models/MessageInfo.cs | 57 +++++++++ FishFactoryFileImplement/DataFileSingleton.cs | 4 + .../Implements/MessageInfoStorage.cs | 63 +++++++++ .../Models/MessageInfo.cs | 48 +++++++ FishFactoryListImplement/DataListSingleton.cs | 2 + .../Implements/MessageInfoStorage.cs | 63 +++++++++ .../Models/MessageInfo.cs | 48 +++++++ .../Controllers/ClientController.cs | 22 +++- FishFactoryRestApi/Program.cs | 20 +++ 36 files changed, 1206 insertions(+), 22 deletions(-) create mode 100644 FishFactory/App.config create mode 100644 FishFactory/Forms/FormMails.Designer.cs create mode 100644 FishFactory/Forms/FormMails.cs create mode 100644 FishFactory/Forms/FormMails.resx create mode 100644 FishFactoryBusinessLogic/BusinessLogic/MessageInfoLogic.cs create mode 100644 FishFactoryBusinessLogic/MailWorker/AbstractMailWorker.cs create mode 100644 FishFactoryBusinessLogic/MailWorker/MailKitWorker.cs create mode 100644 FishFactoryClientApp/Controllers/ClientController.cs create mode 100644 FishFactoryClientApp/Views/Home/Mails.cshtml create mode 100644 FishFactoryContracts/BindingModels/MailConfigBindingModel.cs create mode 100644 FishFactoryContracts/BindingModels/MailSendInfoBindingModel.cs create mode 100644 FishFactoryContracts/BindingModels/MessageInfoBindingModel.cs create mode 100644 FishFactoryContracts/BusinessLogicsContracts/IMessageInfoLogic.cs create mode 100644 FishFactoryContracts/SearchModels/MessageInfoSearchModel.cs create mode 100644 FishFactoryContracts/StoragesContracts/IMessageInfoStorage.cs create mode 100644 FishFactoryContracts/ViewModels/MessageInfoViewModel.cs create mode 100644 FishFactoryDataModels/Models/IMessageInfoModel.cs create mode 100644 FishFactoryDatabaseImplement/Implements/MessageInfoStorage.cs create mode 100644 FishFactoryDatabaseImplement/Models/MessageInfo.cs create mode 100644 FishFactoryFileImplement/Implements/MessageInfoStorage.cs create mode 100644 FishFactoryFileImplement/Models/MessageInfo.cs create mode 100644 FishFactoryListImplement/Implements/MessageInfoStorage.cs create mode 100644 FishFactoryListImplement/Models/MessageInfo.cs diff --git a/FishFactory/App.config b/FishFactory/App.config new file mode 100644 index 0000000..c3487e6 --- /dev/null +++ b/FishFactory/App.config @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/FishFactory/Forms/FormMails.Designer.cs b/FishFactory/Forms/FormMails.Designer.cs new file mode 100644 index 0000000..a49142f --- /dev/null +++ b/FishFactory/Forms/FormMails.Designer.cs @@ -0,0 +1,64 @@ +namespace FishFactory.Forms +{ + 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.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(-2, -1); + dataGridView.Margin = new Padding(3, 4, 3, 4); + dataGridView.Name = "dataGridView"; + dataGridView.ReadOnly = true; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 24; + dataGridView.Size = new Size(931, 517); + dataGridView.TabIndex = 10; + // + // FormMails + // + AutoScaleDimensions = new SizeF(8F, 19F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(929, 515); + Controls.Add(dataGridView); + Name = "FormMails"; + Text = "FormMails"; + Load += FormMail_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + private DataGridView dataGridView; + } +} \ No newline at end of file diff --git a/FishFactory/Forms/FormMails.cs b/FishFactory/Forms/FormMails.cs new file mode 100644 index 0000000..518c899 --- /dev/null +++ b/FishFactory/Forms/FormMails.cs @@ -0,0 +1,58 @@ +using FishFactoryContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace FishFactory.Forms +{ + 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 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(); + } + + private void buttonRef_Click(object sender, EventArgs e) + { + LoadData(); + } + } +} diff --git a/FishFactory/Forms/FormMails.resx b/FishFactory/Forms/FormMails.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/FishFactory/Forms/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/Forms/FormMain.Designer.cs b/FishFactory/Forms/FormMain.Designer.cs index 602d6f6..7cce468 100644 --- a/FishFactory/Forms/FormMain.Designer.cs +++ b/FishFactory/Forms/FormMain.Designer.cs @@ -44,6 +44,7 @@ buttonIssuedOrder = new Button(); buttonRef = new Button(); dataGridView = new DataGridView(); + ПисьмаtoolStripLabel = new ToolStripLabel(); toolStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); SuspendLayout(); @@ -51,7 +52,7 @@ // toolStrip1 // toolStrip1.ImageScalingSize = new Size(20, 20); - toolStrip1.Items.AddRange(new ToolStripItem[] { toolStripDropDownButton1, toolStripDropDownButton2, ЗапускРаботToolStripLabel }); + toolStrip1.Items.AddRange(new ToolStripItem[] { toolStripDropDownButton1, toolStripDropDownButton2, ЗапускРаботToolStripLabel, ПисьмаtoolStripLabel }); toolStrip1.Location = new Point(0, 0); toolStrip1.Name = "toolStrip1"; toolStrip1.Size = new Size(1265, 26); @@ -184,6 +185,13 @@ dataGridView.Size = new Size(1054, 559); dataGridView.TabIndex = 6; // + // ПисьмаtoolStripLabel + // + ПисьмаtoolStripLabel.Name = "ПисьмаtoolStripLabel"; + ПисьмаtoolStripLabel.Size = new Size(128, 23); + ПисьмаtoolStripLabel.Text = "Письма (призрака)"; + ПисьмаtoolStripLabel.Click += ПисьмаtoolStripLabel_Click; + // // FormMain // AutoScaleDimensions = new SizeF(8F, 19F); @@ -222,5 +230,6 @@ private ToolStripMenuItem клиентыToolStripMenuItem; private ToolStripLabel ЗапускРаботToolStripLabel; private ToolStripMenuItem исполнителиToolStripMenuItem; + private ToolStripLabel ПисьмаtoolStripLabel; } } \ No newline at end of file diff --git a/FishFactory/Forms/FormMain.cs b/FishFactory/Forms/FormMain.cs index a41d81f..1ae5e7b 100644 --- a/FishFactory/Forms/FormMain.cs +++ b/FishFactory/Forms/FormMain.cs @@ -73,7 +73,7 @@ namespace FishFactory.Forms form.ShowDialog(); } } - + private void исполнителиToolStripMenuItem_Click(object sender, EventArgs e) { var service = Program.ServiceProvider?.GetService(typeof(FormImplementers)); @@ -162,5 +162,14 @@ namespace FishFactory.Forms _workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic); MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); } + + private void ПисьмаtoolStripLabel_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormMails)); + if (service is FormMails form) + { + form.ShowDialog(); + } + } } } diff --git a/FishFactory/Program.cs b/FishFactory/Program.cs index 96100d9..a32994b 100644 --- a/FishFactory/Program.cs +++ b/FishFactory/Program.cs @@ -8,6 +8,8 @@ using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; using FishFactoryBusinessLogic.OfficePackage; using FishFactoryBusinessLogic.OfficePackage.Implements; +using FishFactoryBusinessLogic.MailWorker; +using FishFactoryContracts.BindingModels; namespace FishFactory { @@ -28,6 +30,27 @@ namespace FishFactory ConfigureServices(services); _serviceProvider = services.BuildServiceProvider(); + try + { + var mailSender = _serviceProvider.GetService(); + mailSender?.MailConfig(new MailConfigBindingModel + { + MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty, + MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty, + SmtpClientHost = System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty, + SmtpClientPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]), + PopHost = System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty, + PopPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"]) + }); + // + var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000); + } + catch (Exception ex) + { + var logger = _serviceProvider.GetService(); + logger?.LogError(ex, " "); + } + Application.Run(_serviceProvider.GetRequiredService()); } private static void ConfigureServices(ServiceCollection services) @@ -42,14 +65,18 @@ namespace FishFactory 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(); @@ -60,6 +87,7 @@ namespace FishFactory services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -70,5 +98,6 @@ namespace FishFactory services.AddTransient(); services.AddTransient(); } + private static void MailCheck(object obj) => ServiceProvider?.GetService()?.MailCheck(); } } \ No newline at end of file diff --git a/FishFactoryBusinessLogic/BusinessLogic/MessageInfoLogic.cs b/FishFactoryBusinessLogic/BusinessLogic/MessageInfoLogic.cs new file mode 100644 index 0000000..b4fed63 --- /dev/null +++ b/FishFactoryBusinessLogic/BusinessLogic/MessageInfoLogic.cs @@ -0,0 +1,85 @@ +using FishFactoryContracts.BindingModels; +using FishFactoryContracts.BusinessLogicsContracts; +using FishFactoryContracts.SearchModels; +using FishFactoryContracts.StoragesContracts; +using FishFactoryContracts.ViewModels; +using Microsoft.Extensions.Logging; + +namespace FishFactoryBusinessLogic.BusinessLogic +{ + 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}", model.SenderName); + } + else + { + model.ClientId = element.Id; + } + } + } +} diff --git a/FishFactoryBusinessLogic/BusinessLogic/OrderLogic.cs b/FishFactoryBusinessLogic/BusinessLogic/OrderLogic.cs index 11a0cae..f269963 100644 --- a/FishFactoryBusinessLogic/BusinessLogic/OrderLogic.cs +++ b/FishFactoryBusinessLogic/BusinessLogic/OrderLogic.cs @@ -1,4 +1,5 @@ -using FishFactoryContracts.BindingModels; +using FishFactoryBusinessLogic.MailWorker; +using FishFactoryContracts.BindingModels; using FishFactoryContracts.BusinessLogicsContracts; using FishFactoryContracts.SearchModels; using FishFactoryContracts.StoragesContracts; @@ -12,11 +13,14 @@ namespace FishFactoryBusinessLogic.BusinessLogic { private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; + private readonly AbstractMailWorker _mailWorker; + static readonly object _locker = new object(); - public OrderLogic(ILogger logger, IOrderStorage orderStorage) + public OrderLogic(ILogger logger, IOrderStorage orderStorage, AbstractMailWorker mailWorker) { _logger = logger; _orderStorage = orderStorage; + _mailWorker = mailWorker; } public List? ReadList(OrderSearchModel? model) @@ -56,20 +60,32 @@ namespace FishFactoryBusinessLogic.BusinessLogic if (model.Status != OrderStatus.Неизвестен) return false; + model.Status = OrderStatus.Принят; - if (_orderStorage.Insert(model) == null) - { - model.Status = OrderStatus.Неизвестен; - _logger.LogWarning("Insert operation failed"); - return false; - } - return true; + var order = _orderStorage.Insert(model); + if (order == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + + Task.Run(() => _mailWorker.MailSendAsync(new MailSendInfoBindingModel + { + MailAddress = order.ClientEmail, + Subject = $"Новый заказ создан. Номер заказа - {order.Id}", + Text = $"Ваш заказ номер {order.Id} на текстиль {order.CannedName} от {order.DateCreate} на сумму {order.Sum} принят." + })); + + return true; } public bool TakeOrderInWork(OrderBindingModel model) { - return ToNextStatus(model, OrderStatus.Выполняется); + lock (_locker) + { + return ToNextStatus(model, OrderStatus.Выполняется); + } } public bool FinishOrder(OrderBindingModel model) @@ -124,7 +140,15 @@ namespace FishFactoryBusinessLogic.BusinessLogic _logger.LogWarning("Changing status operation faled"); return false; } - return true; + + Task.Run(() => _mailWorker.MailSendAsync(new MailSendInfoBindingModel + { + MailAddress = element.ClientEmail, + Subject = $"Изменение статуса заказа номер {element.Id}", + Text = $"У заказа номер {element.Id} изменен статус на {orderStatus}" + })); + + return true; } private void CheckModel(OrderBindingModel model, bool withParams = true) diff --git a/FishFactoryBusinessLogic/FishFactoryBusinessLogic.csproj b/FishFactoryBusinessLogic/FishFactoryBusinessLogic.csproj index aebc4b8..e4064a8 100644 --- a/FishFactoryBusinessLogic/FishFactoryBusinessLogic.csproj +++ b/FishFactoryBusinessLogic/FishFactoryBusinessLogic.csproj @@ -9,6 +9,7 @@ + diff --git a/FishFactoryBusinessLogic/MailWorker/AbstractMailWorker.cs b/FishFactoryBusinessLogic/MailWorker/AbstractMailWorker.cs new file mode 100644 index 0000000..c364679 --- /dev/null +++ b/FishFactoryBusinessLogic/MailWorker/AbstractMailWorker.cs @@ -0,0 +1,80 @@ +using FishFactoryContracts.BindingModels; +using FishFactoryContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; + +namespace FishFactoryBusinessLogic.MailWorker +{ + public abstract class AbstractMailWorker + { + protected string _mailLogin = string.Empty; + protected string _mailPassword = string.Empty; + protected string _smtpClientHost = string.Empty; + protected int _smtpClientPort; + protected string _popHost = string.Empty; + protected int _popPort; + private readonly IMessageInfoLogic _messageInfoLogic; + private readonly ILogger _logger; + public AbstractMailWorker(ILogger logger, IMessageInfoLogic messageInfoLogic) + { + _logger = logger; + _messageInfoLogic = messageInfoLogic; + } + public void MailConfig(MailConfigBindingModel config) + { + _mailLogin = config.MailLogin; + _mailPassword = config.MailPassword; + _smtpClientHost = config.SmtpClientHost; + _smtpClientPort = config.SmtpClientPort; + _popHost = config.PopHost; + _popPort = config.PopPort; + _logger.LogDebug("Config: {login}, {password}, {clientHost}, { clientPOrt}, { popHost}, { popPort}", _mailLogin, _mailPassword, _smtpClientHost, _smtpClientPort, _popHost, _popPort); + } + + public async void MailSendAsync(MailSendInfoBindingModel info) + { + if (string.IsNullOrEmpty(_mailLogin) || + string.IsNullOrEmpty(_mailPassword)) + { + return; + } + if (string.IsNullOrEmpty(_smtpClientHost) || _smtpClientPort == 0) + { + return; + } + if (string.IsNullOrEmpty(info.MailAddress) || + string.IsNullOrEmpty(info.Subject) || string.IsNullOrEmpty(info.Text)) + { + return; + } + _logger.LogDebug("Send Mail: {To}, {Subject}", info.MailAddress, + info.Subject); + await SendMailAsync(info); + } + + public async void MailCheck() + { + if (string.IsNullOrEmpty(_mailLogin) || + string.IsNullOrEmpty(_mailPassword)) + { + return; + } + if (string.IsNullOrEmpty(_popHost) || _popPort == 0) + { + return; + } + if (_messageInfoLogic == null) + { + return; + } + var list = await ReceiveMailAsync(); + _logger.LogDebug("Check Mail: {Count} new mails", list.Count); + foreach (var mail in list) + { + _messageInfoLogic.Create(mail); + } + } + + protected abstract Task SendMailAsync(MailSendInfoBindingModel info); + protected abstract Task> ReceiveMailAsync(); + } +} diff --git a/FishFactoryBusinessLogic/MailWorker/MailKitWorker.cs b/FishFactoryBusinessLogic/MailWorker/MailKitWorker.cs new file mode 100644 index 0000000..b45ea5a --- /dev/null +++ b/FishFactoryBusinessLogic/MailWorker/MailKitWorker.cs @@ -0,0 +1,77 @@ +using FishFactoryContracts.BindingModels; +using FishFactoryContracts.BusinessLogicsContracts; +using System.Net.Mail; +using System.Net; +using System.Text; +using MailKit.Net.Pop3; +using MailKit.Security; +using Microsoft.Extensions.Logging; + +namespace FishFactoryBusinessLogic.MailWorker +{ + public class MailKitWorker : AbstractMailWorker + { + public MailKitWorker(ILogger logger, IMessageInfoLogic messageInfoLogic) : base(logger, messageInfoLogic) { } + + //отправка письма + protected override async Task SendMailAsync(MailSendInfoBindingModel info) + { + using var objMailMessage = new MailMessage(); + using var objSmtpClient = new SmtpClient(_smtpClientHost, _smtpClientPort); + try + { + objMailMessage.From = new MailAddress(_mailLogin); + objMailMessage.To.Add(new MailAddress(info.MailAddress)); + objMailMessage.Subject = info.Subject; + objMailMessage.Body = info.Text; + objMailMessage.SubjectEncoding = Encoding.UTF8; + objMailMessage.BodyEncoding = Encoding.UTF8; + objSmtpClient.UseDefaultCredentials = false; + objSmtpClient.EnableSsl = true; + objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; + objSmtpClient.Credentials = new NetworkCredential(_mailLogin, _mailPassword); + await Task.Run(() => objSmtpClient.Send(objMailMessage)); + } + catch (Exception) + { + throw; + } + } + + //получение письма + protected override async Task> ReceiveMailAsync() + { + var list = new List(); + using var client = new Pop3Client(); + await Task.Run(() => + { + try + { + client.Connect(_popHost, _popPort, SecureSocketOptions.SslOnConnect); + client.Authenticate(_mailLogin, _mailPassword); + for (int i = 0; i < client.Count; i++) + { + var message = client.GetMessage(i); + foreach (var mail in message.From.Mailboxes) + { + list.Add(new MessageInfoBindingModel + { + DateDelivery = message.Date.DateTime, + MessageId = message.MessageId, + SenderName = mail.Address, + Subject = message.Subject, + Body = message.TextBody + }); + } + } + } + catch (MailKit.Security.AuthenticationException) { } + finally + { + client.Disconnect(true); + } + }); + return list; + } + } +} diff --git a/FishFactoryClientApp/Controllers/ClientController.cs b/FishFactoryClientApp/Controllers/ClientController.cs new file mode 100644 index 0000000..310e024 --- /dev/null +++ b/FishFactoryClientApp/Controllers/ClientController.cs @@ -0,0 +1,82 @@ +using FishFactoryContracts.BindingModels; +using FishFactoryContracts.BusinessLogicsContracts; +using FishFactoryContracts.SearchModels; +using FishFactoryContracts.ViewModels; +using Microsoft.AspNetCore.Mvc; + +namespace FishFactoryClientApp.Controllers +{ + [Route("api/[controller]/[action]")] + [ApiController] + public class ClientController : Controller + { + private readonly ILogger _logger; + private readonly IClientLogic _logic; + private readonly IMessageInfoLogic _mailLogic; + public ClientController(IClientLogic logic, IMessageInfoLogic mailLogic, ILogger logger) + { + _logger = logger; + _logic = logic; + _mailLogic = mailLogic; + } + [HttpGet] + public ClientViewModel? Login(string login, string password) + { + try + { + return _logic.ReadElement(new ClientSearchModel + { + Email = login, + Password = password + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка входа в систему"); + throw; + } + } + [HttpPost] + public void Register(ClientBindingModel model) + { + try + { + _logic.Create(model); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка регистрации"); + throw; + } + } + [HttpPost] + public void UpdateData(ClientBindingModel model) + { + try + { + _logic.Update(model); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка обновления данных"); + throw; + } + } + [HttpGet] + public List? GetMessages(int clientId) + { + try + { + return _mailLogic.ReadList(new MessageInfoSearchModel + { + ClientId = clientId + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения писем клиента"); + throw; + } + } + } +} diff --git a/FishFactoryClientApp/Controllers/HomeController.cs b/FishFactoryClientApp/Controllers/HomeController.cs index 38a9b5d..9f118bd 100644 --- a/FishFactoryClientApp/Controllers/HomeController.cs +++ b/FishFactoryClientApp/Controllers/HomeController.cs @@ -130,5 +130,15 @@ namespace AbstractShowClientApp.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/FishFactoryClientApp/Views/Home/Mails.cshtml b/FishFactoryClientApp/Views/Home/Mails.cshtml new file mode 100644 index 0000000..35f7053 --- /dev/null +++ b/FishFactoryClientApp/Views/Home/Mails.cshtml @@ -0,0 +1,48 @@ +@using AbstractShopContracts.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/FishFactoryClientApp/Views/Shared/_Layout.cshtml b/FishFactoryClientApp/Views/Shared/_Layout.cshtml index ea4f793..8c830d4 100644 --- a/FishFactoryClientApp/Views/Shared/_Layout.cshtml +++ b/FishFactoryClientApp/Views/Shared/_Layout.cshtml @@ -26,6 +26,9 @@ + diff --git a/FishFactoryContracts/BindingModels/MailConfigBindingModel.cs b/FishFactoryContracts/BindingModels/MailConfigBindingModel.cs new file mode 100644 index 0000000..6c60816 --- /dev/null +++ b/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; } + } +} diff --git a/FishFactoryContracts/BindingModels/MailSendInfoBindingModel.cs b/FishFactoryContracts/BindingModels/MailSendInfoBindingModel.cs new file mode 100644 index 0000000..41a8221 --- /dev/null +++ b/FishFactoryContracts/BindingModels/MailSendInfoBindingModel.cs @@ -0,0 +1,9 @@ +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; + } +} diff --git a/FishFactoryContracts/BindingModels/MessageInfoBindingModel.cs b/FishFactoryContracts/BindingModels/MessageInfoBindingModel.cs new file mode 100644 index 0000000..32fe9b9 --- /dev/null +++ b/FishFactoryContracts/BindingModels/MessageInfoBindingModel.cs @@ -0,0 +1,14 @@ +using FishFactoryDataModel.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; } + } +} diff --git a/FishFactoryContracts/BusinessLogicsContracts/IMessageInfoLogic.cs b/FishFactoryContracts/BusinessLogicsContracts/IMessageInfoLogic.cs new file mode 100644 index 0000000..c9624cc --- /dev/null +++ b/FishFactoryContracts/BusinessLogicsContracts/IMessageInfoLogic.cs @@ -0,0 +1,12 @@ +using FishFactoryContracts.BindingModels; +using FishFactoryContracts.SearchModels; +using FishFactoryContracts.ViewModels; + +namespace FishFactoryContracts.BusinessLogicsContracts +{ + public interface IMessageInfoLogic + { + List? ReadList(MessageInfoSearchModel? model); + bool Create(MessageInfoBindingModel model); + } +} diff --git a/FishFactoryContracts/SearchModels/MessageInfoSearchModel.cs b/FishFactoryContracts/SearchModels/MessageInfoSearchModel.cs new file mode 100644 index 0000000..a1c9bb4 --- /dev/null +++ b/FishFactoryContracts/SearchModels/MessageInfoSearchModel.cs @@ -0,0 +1,8 @@ +namespace FishFactoryContracts.SearchModels +{ + public class MessageInfoSearchModel + { + public int? ClientId { get; set; } + public string? MessageId { get; set; } + } +} diff --git a/FishFactoryContracts/StoragesContracts/IMessageInfoStorage.cs b/FishFactoryContracts/StoragesContracts/IMessageInfoStorage.cs new file mode 100644 index 0000000..a128a49 --- /dev/null +++ b/FishFactoryContracts/StoragesContracts/IMessageInfoStorage.cs @@ -0,0 +1,14 @@ +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); + } +} diff --git a/FishFactoryContracts/ViewModels/MessageInfoViewModel.cs b/FishFactoryContracts/ViewModels/MessageInfoViewModel.cs new file mode 100644 index 0000000..ae69112 --- /dev/null +++ b/FishFactoryContracts/ViewModels/MessageInfoViewModel.cs @@ -0,0 +1,24 @@ +using FishFactoryDataModel.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; + } +} diff --git a/FishFactoryContracts/ViewModels/OrderViewModel.cs b/FishFactoryContracts/ViewModels/OrderViewModel.cs index cfe31f5..3839a69 100644 --- a/FishFactoryContracts/ViewModels/OrderViewModel.cs +++ b/FishFactoryContracts/ViewModels/OrderViewModel.cs @@ -1,10 +1,5 @@ using FishFactoryDataModel.Enums; -using System; -using System.Collections.Generic; using System.ComponentModel; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace FishFactoryContracts.ViewModels { @@ -15,7 +10,9 @@ namespace FishFactoryContracts.ViewModels public int ClientId { get; set; } [DisplayName("Клиент")] public string ClientFIO { get; set; } = string.Empty; - public int? ImplementerId { get; set; } + [DisplayName("Почта клиента")] + public string ClientEmail { get; set; } = string.Empty; + public int? ImplementerId { get; set; } [DisplayName("Исполнитель")] public string? ImplementerFIO { get; set; } = string.Empty; public int CannedId { get; set; } diff --git a/FishFactoryDataModels/Models/IMessageInfoModel.cs b/FishFactoryDataModels/Models/IMessageInfoModel.cs new file mode 100644 index 0000000..1273459 --- /dev/null +++ b/FishFactoryDataModels/Models/IMessageInfoModel.cs @@ -0,0 +1,12 @@ +namespace FishFactoryDataModel.Models +{ + public interface IMessageInfoModel + { + string MessageId { get; } + int? ClientId { get; } + string SenderName { get; } + DateTime DateDelivery { get; } + string Subject { get; } + string Body { get; } + } +} diff --git a/FishFactoryDatabaseImplement/FishFactoryDatabase.cs b/FishFactoryDatabaseImplement/FishFactoryDatabase.cs index 48b39f5..e49a3a9 100644 --- a/FishFactoryDatabaseImplement/FishFactoryDatabase.cs +++ b/FishFactoryDatabaseImplement/FishFactoryDatabase.cs @@ -21,5 +21,6 @@ namespace FishFactoryDatabaseImplement public virtual DbSet Clients { set; get; } public virtual DbSet Orders { set; get; } public virtual DbSet Implementers { set; get; } + public virtual DbSet MessageInfos { set; get; } } } diff --git a/FishFactoryDatabaseImplement/Implements/MessageInfoStorage.cs b/FishFactoryDatabaseImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..e3de9de --- /dev/null +++ b/FishFactoryDatabaseImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,50 @@ +using FishFactoryContracts.BindingModels; +using FishFactoryContracts.SearchModels; +using FishFactoryContracts.StoragesContracts; +using FishFactoryContracts.ViewModels; +using FishFactoryDatabaseImplement.Models; + +namespace FishFactoryDatabaseImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + public List GetFullList() + { + using var context = new FishFactoryDatabase(); + return context.MessageInfos.Select(x => x.GetViewModel).ToList(); + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + if (!model.ClientId.HasValue) + { + return new(); + } + using var context = new FishFactoryDatabase(); + return context.MessageInfos.Where(x => x.ClientId.HasValue && x.ClientId == model.ClientId).Select(x => x.GetViewModel).ToList(); + } + + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (string.IsNullOrEmpty(model.MessageId)) + { + return new(); + } + using var context = new FishFactoryDatabase(); + return context.MessageInfos.FirstOrDefault(x => x.MessageId == model.MessageId)?.GetViewModel; + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = MessageInfo.Create(model); + if (newMessage == null) + { + return null; + } + using var context = new FishFactoryDatabase(); + context.MessageInfos.Add(newMessage); + context.SaveChanges(); + return newMessage.GetViewModel; + } + } +} diff --git a/FishFactoryDatabaseImplement/Models/MessageInfo.cs b/FishFactoryDatabaseImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..c3f4e42 --- /dev/null +++ b/FishFactoryDatabaseImplement/Models/MessageInfo.cs @@ -0,0 +1,57 @@ +using FishFactoryContracts.BindingModels; +using FishFactoryContracts.ViewModels; +using FishFactoryDataModel.Models; +using System.ComponentModel.DataAnnotations; + +namespace FishFactoryDatabaseImplement.Models +{ + public class MessageInfo : IMessageInfoModel + { + [Key] + 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 + }; + } +} diff --git a/FishFactoryFileImplement/DataFileSingleton.cs b/FishFactoryFileImplement/DataFileSingleton.cs index 0afb482..88e8e54 100644 --- a/FishFactoryFileImplement/DataFileSingleton.cs +++ b/FishFactoryFileImplement/DataFileSingleton.cs @@ -12,11 +12,13 @@ namespace FishFactoryFileImplement private readonly string CannedFileName = "Canned.xml"; private readonly string ClientFileName = "Client.xml"; private readonly string ImplementerFileName = "Implementer.xml"; + private readonly string MessageInfoFileName = "MessageInfo.xml"; public List Components { get; private set; } public List Orders { get; private set; } public List Canneds { get; private set; } public List Clients { get; private set; } public List Implementers { get; private set; } + public List Messages { get; private set; } public static DataFileSingleton GetInstance() { if (instance == null) @@ -30,6 +32,7 @@ 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, "Implementer", x => x.GetXElement); + public void SaveMessages() => SaveData(Orders, ImplementerFileName, "Messages", x => x.GetXElement); private DataFileSingleton() { Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!; @@ -37,6 +40,7 @@ namespace FishFactoryFileImplement 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(MessageInfoFileName, "MessageInfo", x => MessageInfo.Create(x)!)!; } private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) { diff --git a/FishFactoryFileImplement/Implements/MessageInfoStorage.cs b/FishFactoryFileImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..9c65aae --- /dev/null +++ b/FishFactoryFileImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,63 @@ +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 List GetFullList() + { + List result = new(); + foreach (var item in _source.Messages) + { + result.Add(item.GetViewModel); + } + return result; + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + List result = new(); + foreach (var item in _source.Messages) + { + if (item.ClientId.HasValue && item.ClientId == model.ClientId) + { + result.Add(item.GetViewModel); + } + } + return result; + } + + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + foreach (var message in _source.Messages) + { + if (model.MessageId != null && model.MessageId.Equals(message.MessageId)) + { + return message.GetViewModel; + } + } + return null; + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = MessageInfo.Create(model); + if (newMessage == null) + { + return null; + } + _source.Messages.Add(newMessage); + return newMessage.GetViewModel; + } + } +} diff --git a/FishFactoryFileImplement/Models/MessageInfo.cs b/FishFactoryFileImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..05b67c1 --- /dev/null +++ b/FishFactoryFileImplement/Models/MessageInfo.cs @@ -0,0 +1,48 @@ +using FishFactoryContracts.BindingModels; +using FishFactoryContracts.ViewModels; +using FishFactoryDataModel.Models; + +namespace FishFactoryFileImplement.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; } = DateTime.Now; + + 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() + { + Body = model.Body, + Subject = model.Subject, + ClientId = model.ClientId, + MessageId = model.MessageId, + SenderName = model.SenderName, + DateDelivery = model.DateDelivery, + }; + } + + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Subject = Subject, + ClientId = ClientId, + MessageId = MessageId, + SenderName = SenderName, + DateDelivery = DateDelivery, + }; + } +} diff --git a/FishFactoryListImplement/DataListSingleton.cs b/FishFactoryListImplement/DataListSingleton.cs index 1f883f4..f8c9e4d 100644 --- a/FishFactoryListImplement/DataListSingleton.cs +++ b/FishFactoryListImplement/DataListSingleton.cs @@ -10,6 +10,7 @@ namespace FishFactoryListImplement public List Canneds { get; set; } public List Clients { get; set; } public List Implementers { get; set; } + public List Messages { get; set; } private DataListSingleton() { Components = new List(); @@ -17,6 +18,7 @@ namespace FishFactoryListImplement Canneds = new List(); Clients = new List(); Implementers = new List(); + Messages = new List(); } public static DataListSingleton GetInstance() { diff --git a/FishFactoryListImplement/Implements/MessageInfoStorage.cs b/FishFactoryListImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..eb5f47f --- /dev/null +++ b/FishFactoryListImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,63 @@ +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 List GetFullList() + { + List result = new(); + foreach (var item in _source.Messages) + { + result.Add(item.GetViewModel); + } + return result; + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + List result = new(); + foreach (var item in _source.Messages) + { + if (item.ClientId.HasValue && item.ClientId == model.ClientId) + { + result.Add(item.GetViewModel); + } + } + return result; + } + + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + foreach (var message in _source.Messages) + { + if (model.MessageId != null && model.MessageId.Equals(message.MessageId)) + { + return message.GetViewModel; + } + } + return null; + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = MessageInfo.Create(model); + if (newMessage == null) + { + return null; + } + _source.Messages.Add(newMessage); + return newMessage.GetViewModel; + } + } +} diff --git a/FishFactoryListImplement/Models/MessageInfo.cs b/FishFactoryListImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..6e1a05a --- /dev/null +++ b/FishFactoryListImplement/Models/MessageInfo.cs @@ -0,0 +1,48 @@ +using FishFactoryContracts.BindingModels; +using FishFactoryContracts.ViewModels; +using FishFactoryDataModel.Models; + +namespace FishFactoryListImplement.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; } = DateTime.Now; + + 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() + { + Body = model.Body, + Subject = model.Subject, + ClientId = model.ClientId, + MessageId = model.MessageId, + SenderName = model.SenderName, + DateDelivery = model.DateDelivery, + }; + } + + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Subject = Subject, + ClientId = ClientId, + MessageId = MessageId, + SenderName = SenderName, + DateDelivery = DateDelivery, + }; + } +} diff --git a/FishFactoryRestApi/Controllers/ClientController.cs b/FishFactoryRestApi/Controllers/ClientController.cs index 930a30a..662b2d1 100644 --- a/FishFactoryRestApi/Controllers/ClientController.cs +++ b/FishFactoryRestApi/Controllers/ClientController.cs @@ -2,7 +2,6 @@ using FishFactoryContracts.BusinessLogicsContracts; using FishFactoryContracts.SearchModels; using FishFactoryContracts.ViewModels; -using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace FishFactoryRestApi.Controllers @@ -13,11 +12,12 @@ namespace FishFactoryRestApi.Controllers { private readonly ILogger _logger; private readonly IClientLogic _logic; - public ClientController(IClientLogic logic, ILogger - logger) + private readonly IMessageInfoLogic _mailLogic; + public ClientController(IClientLogic logic, ILogger logger, IMessageInfoLogic mailLogic) { _logger = logger; _logic = logic; + _mailLogic = mailLogic; } [HttpGet] public ClientViewModel? Login(string login, string password) @@ -62,5 +62,21 @@ 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; + } + } } } diff --git a/FishFactoryRestApi/Program.cs b/FishFactoryRestApi/Program.cs index 935ad4d..21b9073 100644 --- a/FishFactoryRestApi/Program.cs +++ b/FishFactoryRestApi/Program.cs @@ -1,4 +1,6 @@ using FishFactoryBusinessLogic.BusinessLogic; +using FishFactoryBusinessLogic.MailWorker; +using FishFactoryContracts.BindingModels; using FishFactoryContracts.BusinessLogicsContracts; using FishFactoryContracts.StoragesContracts; using FishFactoryDatabaseImplement.Implements; @@ -13,9 +15,17 @@ builder.Logging.AddLog4Net("log4net.config"); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddTransient(); + builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddTransient(); + +builder.Services.AddTransient(); + builder.Services.AddControllers(); builder.Services.AddEndpointsApiExplorer(); @@ -28,6 +38,16 @@ 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()) {