From 72147f6d7f61e551db6d15e4505de5328f4aad3a Mon Sep 17 00:00:00 2001 From: goldfest Date: Thu, 2 May 2024 21:00:30 +0400 Subject: [PATCH] =?UTF-8?q?=D0=BF=D0=BE=D0=BB=D0=BD=D0=BE=D1=81=D1=82?= =?UTF-8?q?=D1=8C=D1=8E=20=D1=81=D0=B4=D0=B5=D0=BB=D0=B0=D0=BD=D0=BD=D0=B0?= =?UTF-8?q?=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TravelCompany/TravelCompany/App.config | 11 ++ .../TravelCompany/FormMain.Designer.cs | 23 +++- TravelCompany/TravelCompany/FormMain.cs | 11 ++ .../TravelCompany/FormViewMail.Designer.cs | 62 +++++++++ TravelCompany/TravelCompany/FormViewMail.cs | 48 +++++++ TravelCompany/TravelCompany/FormViewMail.resx | 120 ++++++++++++++++++ TravelCompany/TravelCompany/Program.cs | 40 ++++++ .../BusinessLogic/ClientLogic.cs | 11 +- .../BusinessLogic/MessageInfoLogic.cs | 43 +++++++ .../BusinessLogic/OrderLogic.cs | 35 ++++- .../MailWorker/AbstractMailWorker.cs | 86 +++++++++++++ .../MailWorker/MailKitWorker.cs | 85 +++++++++++++ .../TravelCompanyBusinessLogic.csproj | 3 +- .../Controllers/HomeController.cs | 12 ++ .../Views/Home/Mails.cshtml | 54 ++++++++ .../Views/Shared/_Layout.cshtml | 3 + .../BindingModels/MailConfigBindingModel.cs | 18 +++ .../BindingModels/MailSendInfoBingingModel.cs | 16 +++ .../BindingModels/MessageInfoBindingModel.cs | 24 ++++ .../IMessageInfoLogic.cs | 13 ++ .../SearchModels/MessageInfoSearchModel.cs | 9 ++ .../StoragesContracts/IMessageInfoStorage.cs | 17 +++ .../ViewModels/MessageInfoViewModel.cs | 24 ++++ .../Models/IMessageInfoModel.cs | 19 +++ .../Implements/MessageInfoStorage.cs | 52 ++++++++ ...20240502135336_Initial-Create.Designer.cs} | 41 +++++- ...te.cs => 20240502135336_Initial-Create.cs} | 29 +++++ .../TravelCompanyDataBaseModelSnapshot.cs | 39 ++++++ .../Models/MessageInfo.cs | 53 ++++++++ .../TravelCompanyDataBase.cs | 3 +- .../Controllers/ClientController.cs | 21 ++- TravelCompany/TravelCompanyRestApi/Program.cs | 31 +++++ .../TravelCompanyRestApi/appsettings.json | 9 +- 33 files changed, 1049 insertions(+), 16 deletions(-) create mode 100644 TravelCompany/TravelCompany/App.config create mode 100644 TravelCompany/TravelCompany/FormViewMail.Designer.cs create mode 100644 TravelCompany/TravelCompany/FormViewMail.cs create mode 100644 TravelCompany/TravelCompany/FormViewMail.resx create mode 100644 TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/MessageInfoLogic.cs create mode 100644 TravelCompany/TravelCompanyBusinessLogic/MailWorker/AbstractMailWorker.cs create mode 100644 TravelCompany/TravelCompanyBusinessLogic/MailWorker/MailKitWorker.cs create mode 100644 TravelCompany/TravelCompanyClientApp/Views/Home/Mails.cshtml create mode 100644 TravelCompany/TravelCompanyContracts/BindingModels/MailConfigBindingModel.cs create mode 100644 TravelCompany/TravelCompanyContracts/BindingModels/MailSendInfoBingingModel.cs create mode 100644 TravelCompany/TravelCompanyContracts/BindingModels/MessageInfoBindingModel.cs create mode 100644 TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IMessageInfoLogic.cs create mode 100644 TravelCompany/TravelCompanyContracts/SearchModels/MessageInfoSearchModel.cs create mode 100644 TravelCompany/TravelCompanyContracts/StoragesContracts/IMessageInfoStorage.cs create mode 100644 TravelCompany/TravelCompanyContracts/ViewModels/MessageInfoViewModel.cs create mode 100644 TravelCompany/TravelCompanyDataModels/Models/IMessageInfoModel.cs create mode 100644 TravelCompany/TravelCompanyDatabaseImplement/Implements/MessageInfoStorage.cs rename TravelCompany/TravelCompanyDatabaseImplement/Migrations/{20240502101530_Initial-Create.Designer.cs => 20240502135336_Initial-Create.Designer.cs} (86%) rename TravelCompany/TravelCompanyDatabaseImplement/Migrations/{20240502101530_Initial-Create.cs => 20240502135336_Initial-Create.cs} (85%) create mode 100644 TravelCompany/TravelCompanyDatabaseImplement/Models/MessageInfo.cs diff --git a/TravelCompany/TravelCompany/App.config b/TravelCompany/TravelCompany/App.config new file mode 100644 index 0000000..0a083bb --- /dev/null +++ b/TravelCompany/TravelCompany/App.config @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/TravelCompany/TravelCompany/FormMain.Designer.cs b/TravelCompany/TravelCompany/FormMain.Designer.cs index 3d1f849..2f74bf1 100644 --- a/TravelCompany/TravelCompany/FormMain.Designer.cs +++ b/TravelCompany/TravelCompany/FormMain.Designer.cs @@ -34,6 +34,7 @@ компонентыToolStripMenuItem = new ToolStripMenuItem(); ПутёвкиToolStripMenuItem = new ToolStripMenuItem(); клиентыToolStripMenuItem = new ToolStripMenuItem(); + исполнителиToolStripMenuItem = new ToolStripMenuItem(); отчетыToolStripMenuItem = new ToolStripMenuItem(); списокКомпонентовToolStripMenuItem = new ToolStripMenuItem(); компонентыПоПутёвкамToolStripMenuItem = new ToolStripMenuItem(); @@ -45,7 +46,7 @@ buttonIssuedOrder = new Button(); buttonRef = new Button(); dataGridView = new DataGridView(); - исполнителиToolStripMenuItem = new ToolStripMenuItem(); + почтаToolStripMenuItem = new ToolStripMenuItem(); toolStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); SuspendLayout(); @@ -53,7 +54,7 @@ // toolStrip1 // toolStrip1.ImageScalingSize = new Size(20, 20); - toolStrip1.Items.AddRange(new ToolStripItem[] { toolStripDropDownButton1, отчетыToolStripMenuItem, запускРаботToolStripMenuItem }); + toolStrip1.Items.AddRange(new ToolStripItem[] { toolStripDropDownButton1, отчетыToolStripMenuItem, запускРаботToolStripMenuItem, почтаToolStripMenuItem }); toolStrip1.Location = new Point(0, 0); toolStrip1.Name = "toolStrip1"; toolStrip1.Size = new Size(969, 25); @@ -91,6 +92,13 @@ клиентыToolStripMenuItem.Text = "Клиенты"; клиентыToolStripMenuItem.Click += клиентыToolStripMenuItem_Click; // + // исполнителиToolStripMenuItem + // + исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; + исполнителиToolStripMenuItem.Size = new Size(180, 22); + исполнителиToolStripMenuItem.Text = "Исполнители"; + исполнителиToolStripMenuItem.Click += исполнителиToolStripMenuItem_Click; + // // отчетыToolStripMenuItem // отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокКомпонентовToolStripMenuItem, компонентыПоПутёвкамToolStripMenuItem, списокЗаказовToolStripMenuItem }); @@ -188,12 +196,12 @@ dataGridView.Size = new Size(763, 435); dataGridView.TabIndex = 6; // - // исполнителиToolStripMenuItem + // почтаToolStripMenuItem // - исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; - исполнителиToolStripMenuItem.Size = new Size(180, 22); - исполнителиToolStripMenuItem.Text = "Исполнители"; - исполнителиToolStripMenuItem.Click += исполнителиToolStripMenuItem_Click; + почтаToolStripMenuItem.Name = "почтаToolStripMenuItem"; + почтаToolStripMenuItem.Size = new Size(53, 25); + почтаToolStripMenuItem.Text = "Почта"; + почтаToolStripMenuItem.Click += почтаToolStripMenuItem_Click; // // FormMain // @@ -236,5 +244,6 @@ private ToolStripMenuItem клиентыToolStripMenuItem; private ToolStripMenuItem запускРаботToolStripMenuItem; private ToolStripMenuItem исполнителиToolStripMenuItem; + private ToolStripMenuItem почтаToolStripMenuItem; } } \ No newline at end of file diff --git a/TravelCompany/TravelCompany/FormMain.cs b/TravelCompany/TravelCompany/FormMain.cs index 42be528..a2e0865 100644 --- a/TravelCompany/TravelCompany/FormMain.cs +++ b/TravelCompany/TravelCompany/FormMain.cs @@ -220,5 +220,16 @@ Program.ServiceProvider?.GetService(typeof(ImplementersForm)); form.ShowDialog(); } } + + private void почтаToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = +Program.ServiceProvider?.GetService(typeof(FormViewMail)); + if (service is FormViewMail form) + { + form.ShowDialog(); + } + + } } } diff --git a/TravelCompany/TravelCompany/FormViewMail.Designer.cs b/TravelCompany/TravelCompany/FormViewMail.Designer.cs new file mode 100644 index 0000000..f50f748 --- /dev/null +++ b/TravelCompany/TravelCompany/FormViewMail.Designer.cs @@ -0,0 +1,62 @@ +namespace TravelCompany.Forms +{ + partial class FormViewMail + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + dataGridView = new DataGridView(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // dataGridView + // + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(12, 12); + dataGridView.Name = "dataGridView"; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 29; + dataGridView.Size = new Size(776, 426); + dataGridView.TabIndex = 0; + // + // ViewMailForm + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(800, 450); + Controls.Add(dataGridView); + Name = "ViewMailForm"; + Text = "ViewMailForm"; + Load += ViewMailForm_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView; + } +} \ No newline at end of file diff --git a/TravelCompany/TravelCompany/FormViewMail.cs b/TravelCompany/TravelCompany/FormViewMail.cs new file mode 100644 index 0000000..278477b --- /dev/null +++ b/TravelCompany/TravelCompany/FormViewMail.cs @@ -0,0 +1,48 @@ +using TravelCompanyContracts.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 TravelCompany.Forms +{ + public partial class FormViewMail : Form + { + private readonly ILogger _logger; + private readonly IMessageInfoLogic _logic; + public FormViewMail(ILogger logger, IMessageInfoLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + private void ViewMailForm_Load(object sender, EventArgs e) + { + try + { + var list = _logic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["MessageId"].Visible = false; + dataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + _logger.LogInformation("Загрузка списка писем"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки писем"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + } +} diff --git a/TravelCompany/TravelCompany/FormViewMail.resx b/TravelCompany/TravelCompany/FormViewMail.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/TravelCompany/TravelCompany/FormViewMail.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/TravelCompany/TravelCompany/Program.cs b/TravelCompany/TravelCompany/Program.cs index 7c0b2fc..f9b7da7 100644 --- a/TravelCompany/TravelCompany/Program.cs +++ b/TravelCompany/TravelCompany/Program.cs @@ -7,6 +7,9 @@ using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; using TravelCompanyBusinessLogic.OfficePackage.Implements; using TravelCompanyBusinessLogic.OfficePackage; +using TravelCompanyBusinessLogic.MailWorker; +using TravelCompanyContracts.BindingModels; +using IceCreamBusinessLogic.BusinessLogic; namespace TravelCompany.Forms @@ -27,6 +30,37 @@ namespace TravelCompany.Forms var services = new ServiceCollection(); ConfigureServices(services); _serviceProvider = services.BuildServiceProvider(); + try + { + var mailSender = + _serviceProvider.GetService(); + mailSender?.MailConfig(new MailConfigBindingModel + { + MailLogin = + System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? + string.Empty, + MailPassword = + System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? + string.Empty, + SmtpClientHost = + System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? + string.Empty, + SmtpClientPort = + Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]), + PopHost = + System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty, + PopPort = + Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"]) + }); + // + var timer = new System.Threading.Timer(new + TimerCallback(MailCheck!), null, 0, 100000); + } + catch (Exception ex) + { + var logger = _serviceProvider.GetService(); + logger?.LogError(ex, " "); + } Application.Run(_serviceProvider.GetRequiredService()); } @@ -40,6 +74,7 @@ namespace TravelCompany.Forms services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -50,6 +85,7 @@ namespace TravelCompany.Forms services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -63,10 +99,14 @@ namespace TravelCompany.Forms services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddSingleton(); services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); } + private static void MailCheck(object obj) => +ServiceProvider?.GetService()?.MailCheck(); } } \ No newline at end of file diff --git a/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/ClientLogic.cs b/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/ClientLogic.cs index e6df35a..8471ae9 100644 --- a/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/ClientLogic.cs +++ b/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/ClientLogic.cs @@ -10,6 +10,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using System.Text.RegularExpressions; namespace TravelCompanyBusinessLogic.BusinessLogic { @@ -102,13 +103,21 @@ namespace TravelCompanyBusinessLogic.BusinessLogic if (string.IsNullOrEmpty(model.Email)) { throw new ArgumentNullException("Нет Email клиента", - nameof(model.ClientFIO)); + nameof(model.Email)); } if (string.IsNullOrEmpty(model.Password)) { throw new ArgumentNullException("Нет пароля клиента", nameof(model.ClientFIO)); } + if (!Regex.IsMatch(model.Email, @"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$")) + { + throw new ArgumentException("Некорретно введен email клиента", nameof(model.Email)); + } + if (!Regex.IsMatch(model.Password, @"^(?=.*\d)(?=.*\W)(?=.*[^\d\s]).+$")) + { + throw new ArgumentException("Некорректно введен пароль клиента", nameof(model.Password)); + } _logger.LogInformation("Client. ClientFIO:{ClientFIO}." + "Email:{ Email}. Password:{ Password}. Id: { Id} ", model.ClientFIO, model.Email, model.Password, model.Id); var element = _clientStorage.GetElement(new ClientSearchModel diff --git a/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/MessageInfoLogic.cs b/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/MessageInfoLogic.cs new file mode 100644 index 0000000..f807bb7 --- /dev/null +++ b/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/MessageInfoLogic.cs @@ -0,0 +1,43 @@ +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.BusinessLogicsContracts; +using TravelCompanyContracts.SearchModels; +using TravelCompanyContracts.StoragesContracts; +using TravelCompanyContracts.ViewModels; +using Microsoft.Extensions.Logging; + +namespace IceCreamBusinessLogic.BusinessLogic +{ + public class MessageInfoLogic : IMessageInfoLogic + { + private readonly ILogger _logger; + private readonly IMessageInfoStorage _messageInfoStorage; + public MessageInfoLogic(ILogger logger, IMessageInfoStorage MessageInfoStorage) + { + _logger = logger; + _messageInfoStorage = MessageInfoStorage; + } + + public bool Create(MessageInfoBindingModel model) + { + if (_messageInfoStorage.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) ? _messageInfoStorage.GetFullList() : _messageInfoStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + _logger.LogInformation("ReadList. Count:{Count}", list.Count); + return list; + } + } +} diff --git a/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/OrderLogic.cs b/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/OrderLogic.cs index 66fe06b..bb4de48 100644 --- a/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/OrderLogic.cs +++ b/TravelCompany/TravelCompanyBusinessLogic/BusinessLogic/OrderLogic.cs @@ -10,6 +10,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using TravelCompanyBusinessLogic.MailWorker; namespace TravelCompanyBusinessLogic.BusinessLogic { @@ -17,12 +18,16 @@ namespace TravelCompanyBusinessLogic.BusinessLogic { 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 OrderViewModel? ReadElement(OrderSearchModel model) @@ -62,12 +67,15 @@ namespace TravelCompanyBusinessLogic.BusinessLogic if (model.Status != OrderStatus.Неизвестен) return false; model.Status = OrderStatus.Принят; + var res = _orderStorage.Insert(model); - if (_orderStorage.Insert(model) == null) + if (res == null) { _logger.LogWarning("Insert operation failed"); return false; } + SendOrderStatusMail(model.ClientId, $"Изменен статус заказа #{res.Id}", $"Заказ #{res.Id} изменен статус на {model.Status}"); + return true; } @@ -107,7 +115,13 @@ namespace TravelCompanyBusinessLogic.BusinessLogic if (model.Status == OrderStatus.Готов) model.DateImplement = DateTime.Now; if (element.ImplementerId.HasValue) model.ImplementerId = element.ImplementerId; - _orderStorage.Update(model); + var result = _orderStorage.Update(model); + if (result == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + SendOrderStatusMail(result.ClientId, $"Изменен статус заказа #{result.Id}", $"Заказ #{model.Id} изменен статус на {result.Status}"); return true; } @@ -131,5 +145,20 @@ namespace TravelCompanyBusinessLogic.BusinessLogic } _logger.LogInformation("Travel. TravelId:{TravelId}.Count:{Count}.Sum:{Sum}Id:{Id}", model.TravelId, model.Count, model.Sum, model.Id); } + private bool SendOrderStatusMail(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/TravelCompany/TravelCompanyBusinessLogic/MailWorker/AbstractMailWorker.cs b/TravelCompany/TravelCompanyBusinessLogic/MailWorker/AbstractMailWorker.cs new file mode 100644 index 0000000..4063800 --- /dev/null +++ b/TravelCompany/TravelCompanyBusinessLogic/MailWorker/AbstractMailWorker.cs @@ -0,0 +1,86 @@ +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TravelCompanyBusinessLogic.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/TravelCompany/TravelCompanyBusinessLogic/MailWorker/MailKitWorker.cs b/TravelCompany/TravelCompanyBusinessLogic/MailWorker/MailKitWorker.cs new file mode 100644 index 0000000..d379cf8 --- /dev/null +++ b/TravelCompany/TravelCompanyBusinessLogic/MailWorker/MailKitWorker.cs @@ -0,0 +1,85 @@ +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Security.Authentication; +using System.Text; +using System.Threading.Tasks; +using MailKit.Net.Pop3; +using MailKit.Security; +using System.Net.Mail; + +namespace TravelCompanyBusinessLogic.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/TravelCompany/TravelCompanyBusinessLogic/TravelCompanyBusinessLogic.csproj b/TravelCompany/TravelCompanyBusinessLogic/TravelCompanyBusinessLogic.csproj index 6a3ac21..d0bd460 100644 --- a/TravelCompany/TravelCompanyBusinessLogic/TravelCompanyBusinessLogic.csproj +++ b/TravelCompany/TravelCompanyBusinessLogic/TravelCompanyBusinessLogic.csproj @@ -1,4 +1,4 @@ - + net6.0 @@ -8,6 +8,7 @@ + diff --git a/TravelCompany/TravelCompanyClientApp/Controllers/HomeController.cs b/TravelCompany/TravelCompanyClientApp/Controllers/HomeController.cs index 2432ef1..4d7e420 100644 --- a/TravelCompany/TravelCompanyClientApp/Controllers/HomeController.cs +++ b/TravelCompany/TravelCompanyClientApp/Controllers/HomeController.cs @@ -114,6 +114,7 @@ namespace TravelCompanyClientApp.Controllers [HttpGet] public IActionResult Create() { + var res = APIClient.GetRequest>("api/main/getTravellist"); ViewBag.Travels = APIClient.GetRequest>("api/main/getTravellist"); return View(); @@ -147,5 +148,16 @@ namespace TravelCompanyClientApp.Controllers ); return Math.Round(count * (_Travel?.Price ?? 1), 2); } + + [HttpGet] + public IActionResult Mails() + { + if (APIClient.Client == null) + { + return Redirect("~/Home/Enter"); + } + return + View(APIClient.GetRequest>($"api/client/getmessages?clientId={APIClient.Client.Id}")); + } } } diff --git a/TravelCompany/TravelCompanyClientApp/Views/Home/Mails.cshtml b/TravelCompany/TravelCompanyClientApp/Views/Home/Mails.cshtml new file mode 100644 index 0000000..1d2f80e --- /dev/null +++ b/TravelCompany/TravelCompanyClientApp/Views/Home/Mails.cshtml @@ -0,0 +1,54 @@ +@using TravelCompanyContracts.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/TravelCompany/TravelCompanyClientApp/Views/Shared/_Layout.cshtml b/TravelCompany/TravelCompanyClientApp/Views/Shared/_Layout.cshtml index cdfdc2f..e24616e 100644 --- a/TravelCompany/TravelCompanyClientApp/Views/Shared/_Layout.cshtml +++ b/TravelCompany/TravelCompanyClientApp/Views/Shared/_Layout.cshtml @@ -25,6 +25,9 @@ + diff --git a/TravelCompany/TravelCompanyContracts/BindingModels/MailConfigBindingModel.cs b/TravelCompany/TravelCompanyContracts/BindingModels/MailConfigBindingModel.cs new file mode 100644 index 0000000..88e531f --- /dev/null +++ b/TravelCompany/TravelCompanyContracts/BindingModels/MailConfigBindingModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TravelCompanyContracts.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/TravelCompany/TravelCompanyContracts/BindingModels/MailSendInfoBingingModel.cs b/TravelCompany/TravelCompanyContracts/BindingModels/MailSendInfoBingingModel.cs new file mode 100644 index 0000000..07c9060 --- /dev/null +++ b/TravelCompany/TravelCompanyContracts/BindingModels/MailSendInfoBingingModel.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TravelCompanyContracts.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/TravelCompany/TravelCompanyContracts/BindingModels/MessageInfoBindingModel.cs b/TravelCompany/TravelCompanyContracts/BindingModels/MessageInfoBindingModel.cs new file mode 100644 index 0000000..875253e --- /dev/null +++ b/TravelCompany/TravelCompanyContracts/BindingModels/MessageInfoBindingModel.cs @@ -0,0 +1,24 @@ +using TravelCompanyDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TravelCompanyContracts.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/TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IMessageInfoLogic.cs b/TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IMessageInfoLogic.cs new file mode 100644 index 0000000..7738d23 --- /dev/null +++ b/TravelCompany/TravelCompanyContracts/BusinessLogicsContracts/IMessageInfoLogic.cs @@ -0,0 +1,13 @@ +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.SearchModels; +using TravelCompanyContracts.ViewModels; + +namespace TravelCompanyContracts.BusinessLogicsContracts +{ + public interface IMessageInfoLogic + { + List? ReadList(MessageInfoSearchModel? model); + + bool Create(MessageInfoBindingModel model); + } +} \ No newline at end of file diff --git a/TravelCompany/TravelCompanyContracts/SearchModels/MessageInfoSearchModel.cs b/TravelCompany/TravelCompanyContracts/SearchModels/MessageInfoSearchModel.cs new file mode 100644 index 0000000..723b799 --- /dev/null +++ b/TravelCompany/TravelCompanyContracts/SearchModels/MessageInfoSearchModel.cs @@ -0,0 +1,9 @@ +namespace TravelCompanyContracts.SearchModels +{ + public class MessageInfoSearchModel + { + public int? ClientId { get; set; } + + public string? MessageId { get; set; } + } +} \ No newline at end of file diff --git a/TravelCompany/TravelCompanyContracts/StoragesContracts/IMessageInfoStorage.cs b/TravelCompany/TravelCompanyContracts/StoragesContracts/IMessageInfoStorage.cs new file mode 100644 index 0000000..85861ec --- /dev/null +++ b/TravelCompany/TravelCompanyContracts/StoragesContracts/IMessageInfoStorage.cs @@ -0,0 +1,17 @@ +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.SearchModels; +using TravelCompanyContracts.ViewModels; + +namespace TravelCompanyContracts.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/TravelCompany/TravelCompanyContracts/ViewModels/MessageInfoViewModel.cs b/TravelCompany/TravelCompanyContracts/ViewModels/MessageInfoViewModel.cs new file mode 100644 index 0000000..9f211c5 --- /dev/null +++ b/TravelCompany/TravelCompanyContracts/ViewModels/MessageInfoViewModel.cs @@ -0,0 +1,24 @@ +using TravelCompanyDataModels.Models; +using System.ComponentModel; + +namespace TravelCompanyContracts.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/TravelCompany/TravelCompanyDataModels/Models/IMessageInfoModel.cs b/TravelCompany/TravelCompanyDataModels/Models/IMessageInfoModel.cs new file mode 100644 index 0000000..329a26f --- /dev/null +++ b/TravelCompany/TravelCompanyDataModels/Models/IMessageInfoModel.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TravelCompanyDataModels.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/TravelCompany/TravelCompanyDatabaseImplement/Implements/MessageInfoStorage.cs b/TravelCompany/TravelCompanyDatabaseImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..afed799 --- /dev/null +++ b/TravelCompany/TravelCompanyDatabaseImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,52 @@ +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.SearchModels; +using TravelCompanyContracts.StoragesContracts; +using TravelCompanyContracts.ViewModels; +using TravelCompanyDatabaseImplement.Models; + +namespace TravelCompanyDatabaseImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + using var context = new TravelCompanyDataBase(); + if (model.MessageId != null) + { + return context.Messages.FirstOrDefault(x => x.MessageId == model.MessageId)?.GetViewModel; + } + return null; + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + using var context = new TravelCompanyDataBase(); + return context.Messages + .Where(x => x.ClientId == model.ClientId) + .Select(x => x.GetViewModel) + .ToList(); + } + + public List GetFullList() + { + using var context = new TravelCompanyDataBase(); + return context.Messages + .Select(x => x.GetViewModel) + .ToList(); + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + using var context = new TravelCompanyDataBase(); + var newMessage = MessageInfo.Create(context, model); + if (newMessage == null || context.Messages.Any(x => x.MessageId.Equals(model.MessageId))) + { + return null; + } + context.Messages.Add(newMessage); + context.SaveChanges(); + return newMessage.GetViewModel; + } + } +} diff --git a/TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240502101530_Initial-Create.Designer.cs b/TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240502135336_Initial-Create.Designer.cs similarity index 86% rename from TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240502101530_Initial-Create.Designer.cs rename to TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240502135336_Initial-Create.Designer.cs index a605010..698f872 100644 --- a/TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240502101530_Initial-Create.Designer.cs +++ b/TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240502135336_Initial-Create.Designer.cs @@ -12,7 +12,7 @@ using TravelCompanyDatabaseImplement; namespace TravelCompanyDatabaseImplement.Migrations { [DbContext(typeof(TravelCompanyDataBase))] - [Migration("20240502101530_Initial-Create")] + [Migration("20240502135336_Initial-Create")] partial class InitialCreate { /// @@ -97,6 +97,36 @@ namespace TravelCompanyDatabaseImplement.Migrations b.ToTable("Implementers"); }); + modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.MessageInfo", b => + { + b.Property("MessageId") + .HasColumnType("nvarchar(450)"); + + b.Property("Body") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("int"); + + b.Property("DateDelivery") + .HasColumnType("datetime2"); + + b.Property("SenderName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Subject") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("MessageId"); + + b.HasIndex("ClientId"); + + b.ToTable("Messages"); + }); + modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -186,6 +216,15 @@ namespace TravelCompanyDatabaseImplement.Migrations b.ToTable("TravelComponents"); }); + modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.MessageInfo", b => + { + b.HasOne("TravelCompanyDatabaseImplement.Models.Client", "Client") + .WithMany() + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.Order", b => { b.HasOne("TravelCompanyDatabaseImplement.Models.Client", "Client") diff --git a/TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240502101530_Initial-Create.cs b/TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240502135336_Initial-Create.cs similarity index 85% rename from TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240502101530_Initial-Create.cs rename to TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240502135336_Initial-Create.cs index 16190d0..36a3a68 100644 --- a/TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240502101530_Initial-Create.cs +++ b/TravelCompany/TravelCompanyDatabaseImplement/Migrations/20240502135336_Initial-Create.cs @@ -70,6 +70,27 @@ namespace TravelCompanyDatabaseImplement.Migrations table.PrimaryKey("PK_Travels", x => x.Id); }); + migrationBuilder.CreateTable( + name: "Messages", + columns: table => new + { + MessageId = table.Column(type: "nvarchar(450)", nullable: false), + ClientId = table.Column(type: "int", nullable: true), + SenderName = table.Column(type: "nvarchar(max)", nullable: false), + DateDelivery = table.Column(type: "datetime2", nullable: false), + Subject = table.Column(type: "nvarchar(max)", nullable: false), + Body = table.Column(type: "nvarchar(max)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Messages", x => x.MessageId); + table.ForeignKey( + name: "FK_Messages_Clients_ClientId", + column: x => x.ClientId, + principalTable: "Clients", + principalColumn: "Id"); + }); + migrationBuilder.CreateTable( name: "Orders", columns: table => new @@ -134,6 +155,11 @@ namespace TravelCompanyDatabaseImplement.Migrations onDelete: ReferentialAction.Cascade); }); + migrationBuilder.CreateIndex( + name: "IX_Messages_ClientId", + table: "Messages", + column: "ClientId"); + migrationBuilder.CreateIndex( name: "IX_Orders_ClientId", table: "Orders", @@ -163,6 +189,9 @@ namespace TravelCompanyDatabaseImplement.Migrations /// protected override void Down(MigrationBuilder migrationBuilder) { + migrationBuilder.DropTable( + name: "Messages"); + migrationBuilder.DropTable( name: "Orders"); diff --git a/TravelCompany/TravelCompanyDatabaseImplement/Migrations/TravelCompanyDataBaseModelSnapshot.cs b/TravelCompany/TravelCompanyDatabaseImplement/Migrations/TravelCompanyDataBaseModelSnapshot.cs index 47ece42..4ada4ab 100644 --- a/TravelCompany/TravelCompanyDatabaseImplement/Migrations/TravelCompanyDataBaseModelSnapshot.cs +++ b/TravelCompany/TravelCompanyDatabaseImplement/Migrations/TravelCompanyDataBaseModelSnapshot.cs @@ -94,6 +94,36 @@ namespace TravelCompanyDatabaseImplement.Migrations b.ToTable("Implementers"); }); + modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.MessageInfo", b => + { + b.Property("MessageId") + .HasColumnType("nvarchar(450)"); + + b.Property("Body") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("int"); + + b.Property("DateDelivery") + .HasColumnType("datetime2"); + + b.Property("SenderName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Subject") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("MessageId"); + + b.HasIndex("ClientId"); + + b.ToTable("Messages"); + }); + modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -183,6 +213,15 @@ namespace TravelCompanyDatabaseImplement.Migrations b.ToTable("TravelComponents"); }); + modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.MessageInfo", b => + { + b.HasOne("TravelCompanyDatabaseImplement.Models.Client", "Client") + .WithMany() + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + modelBuilder.Entity("TravelCompanyDatabaseImplement.Models.Order", b => { b.HasOne("TravelCompanyDatabaseImplement.Models.Client", "Client") diff --git a/TravelCompany/TravelCompanyDatabaseImplement/Models/MessageInfo.cs b/TravelCompany/TravelCompanyDatabaseImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..043b74b --- /dev/null +++ b/TravelCompany/TravelCompanyDatabaseImplement/Models/MessageInfo.cs @@ -0,0 +1,53 @@ +using TravelCompanyContracts.BindingModels; +using TravelCompanyContracts.ViewModels; +using TravelCompanyDataModels.Models; +using System.ComponentModel.DataAnnotations; + +namespace TravelCompanyDatabaseImplement.Models +{ + public class MessageInfo : IMessageInfoModel + { + [Key] + public string MessageId { get; private set; } = string.Empty; + + public int? ClientId { get; private set; } + + public string SenderName { get; private set; } = string.Empty; + + public DateTime DateDelivery { get; private set; } = DateTime.Now; + + public string Subject { get; private set; } = string.Empty; + + public string Body { get; private set; } = string.Empty; + + public Client? Client { get; private set; } + + public static MessageInfo? Create(TravelCompanyDataBase context, MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Subject = model.Subject, + ClientId = context.Clients.FirstOrDefault(x => x.Email == model.SenderName).Id, + Client = context.Clients.FirstOrDefault(x => x.Email == model.SenderName), + 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/TravelCompany/TravelCompanyDatabaseImplement/TravelCompanyDataBase.cs b/TravelCompany/TravelCompanyDatabaseImplement/TravelCompanyDataBase.cs index eca8a18..f9898f9 100644 --- a/TravelCompany/TravelCompanyDatabaseImplement/TravelCompanyDataBase.cs +++ b/TravelCompany/TravelCompanyDatabaseImplement/TravelCompanyDataBase.cs @@ -16,7 +16,7 @@ optionsBuilder) { if (optionsBuilder.IsConfigured == false) { - optionsBuilder.UseSqlServer(@"Data Source=DESKTOP-D5A5OOG\GOLDFEST;Initial Catalog=TravelCompanyDatabase1;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True"); + optionsBuilder.UseSqlServer(@"Data Source=DESKTOP-D5A5OOG\GOLDFEST;Initial Catalog=TravelCompanyDatabase2;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True"); } base.OnConfiguring(optionsBuilder); } @@ -26,6 +26,7 @@ optionsBuilder) public virtual DbSet Orders { set; get; } public virtual DbSet Clients { set; get; } public virtual DbSet Implementers { set; get; } + public virtual DbSet Messages { set; get; } } } diff --git a/TravelCompany/TravelCompanyRestApi/Controllers/ClientController.cs b/TravelCompany/TravelCompanyRestApi/Controllers/ClientController.cs index 568a9ed..6e63931 100644 --- a/TravelCompany/TravelCompanyRestApi/Controllers/ClientController.cs +++ b/TravelCompany/TravelCompanyRestApi/Controllers/ClientController.cs @@ -11,11 +11,13 @@ namespace TravelCompanyRestApi.Controllers { private readonly ILogger _logger; private readonly IClientLogic _logic; - public ClientController(IClientLogic logic, ILogger + 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) @@ -34,6 +36,23 @@ namespace TravelCompanyRestApi.Controllers throw; } } + + [HttpGet] + public List? GetMessages(int clientId) + { + try + { + return _mailLogic.ReadList(new MessageInfoSearchModel + { + ClientId = clientId + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения писем клиента"); + throw; + } + } [HttpPost] public void Register(ClientBindingModel model) { diff --git a/TravelCompany/TravelCompanyRestApi/Program.cs b/TravelCompany/TravelCompanyRestApi/Program.cs index 656951d..116ec75 100644 --- a/TravelCompany/TravelCompanyRestApi/Program.cs +++ b/TravelCompany/TravelCompanyRestApi/Program.cs @@ -3,6 +3,9 @@ using TravelCompanyContracts.BusinessLogicsContracts; using TravelCompanyContracts.StoragesContracts; using TravelCompanyDatabaseImplement.Implements; using Microsoft.OpenApi.Models; +using IceCreamBusinessLogic.BusinessLogic; +using TravelCompanyBusinessLogic.MailWorker; +using TravelCompanyContracts.BindingModels; var builder = WebApplication.CreateBuilder(args); builder.Logging.SetMinimumLevel(LogLevel.Trace); builder.Logging.AddLog4Net("log4net.config"); @@ -10,9 +13,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.AddSingleton(); + builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle @@ -27,6 +38,26 @@ 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/TravelCompany/TravelCompanyRestApi/appsettings.json b/TravelCompany/TravelCompanyRestApi/appsettings.json index 10f68b8..ee2c170 100644 --- a/TravelCompany/TravelCompanyRestApi/appsettings.json +++ b/TravelCompany/TravelCompanyRestApi/appsettings.json @@ -5,5 +5,12 @@ "Microsoft.AspNetCore": "Warning" } }, - "AllowedHosts": "*" + "AllowedHosts": "*", + "SmtpClientHost": "smtp.gmail.com", + "SmtpClientPort": "587", + "PopHost": "pop.gmail.com", + "PopPort": "995", + + "MailLogin": "vano001899@gmail.com", + "MailPassword": "yzui tptd qjsg gvdb" }