From a1b68b22792d36d91784ef332cd387863b94e8b2 Mon Sep 17 00:00:00 2001 From: dyakonovr Date: Thu, 2 May 2024 23:33:17 +0400 Subject: [PATCH 1/2] All done (I guess) --- .../SoftwareInstallation/App.config | 11 + .../FormMails.Designer.cs | 62 ++++ .../SoftwareInstallation/FormMails.cs | 55 ++++ .../SoftwareInstallation/FormMails.resx | 120 +++++++ .../SoftwareInstallation/FormMain.Designer.cs | 47 +-- .../SoftwareInstallation/FormMain.cs | 9 + .../SoftwareInstallation/Program.cs | 42 +++ .../BusinessLogics/ClientLogic.cs | 10 + .../BusinessLogics/MessageInfoLogic.cs | 101 ++++++ .../BusinessLogics/OrderLogic.cs | 37 ++- .../BusinessLogics/WorkModeling.cs | 2 + .../MailWorker/AbsractMailWorker.cs | 85 +++++ .../MailWorker/MailKitWorker.cs | 83 +++++ .../SoftwareInstallationBusinessLogic.csproj | 1 + .../Controllers/HomeController.cs | 23 +- .../Views/Home/Mails.cshtml | 54 ++++ .../Views/Shared/_Layout.cshtml | 9 +- .../BindingModels/MailConfigBindingModel.cs | 19 ++ .../BindingModels/MailInfoBindingModel.cs | 19 ++ .../BindingModels/MailSendBindingModel.cs | 15 + .../IMessageInfoLogic.cs | 18 ++ .../SearchModels/MessageInfoSearchModel.cs | 14 + .../StoragesContracts/IMessageInfoStorage.cs | 20 ++ .../ViewModels/MessageInfoViewModel.cs | 29 ++ .../Models/IMessageInfoModel.cs | 18 ++ .../Implements/MessageInfoStorage.cs | 56 ++++ ...40427172814_MailMessagesUpdate.Designer.cs | 301 ++++++++++++++++++ .../20240427172814_MailMessagesUpdate.cs | 49 +++ .../20240430080140_Test.Designer.cs | 298 +++++++++++++++++ .../Migrations/20240430080140_Test.cs | 59 ++++ ...ftwareInstallationDatabaseModelSnapshot.cs | 41 +++ .../Models/Client.cs | 5 +- .../Models/Message.cs | 55 ++++ .../SoftwareInstallationDatabase.cs | 1 + .../DataFileSingleton.cs | 26 +- .../Implements/ImplementerStorage.cs | 164 ++++++---- .../Implements/MessageInfoStorage.cs | 57 ++++ .../Models/Implementer.cs | 136 ++++---- .../Models/Message.cs | 80 +++++ .../DataListSingleton.cs | 10 +- .../Implements/ImplementerStorage.cs | 14 +- .../Implements/MessageInfoStorage.cs | 73 +++++ .../Models/Message.cs | 53 +++ .../Controllers/ClientController.cs | 21 +- .../SoftwareInstallationRestApi/Program.cs | 22 ++ .../appsettings.json | 8 +- 46 files changed, 2240 insertions(+), 192 deletions(-) create mode 100644 SoftwareInstallation/SoftwareInstallation/App.config create mode 100644 SoftwareInstallation/SoftwareInstallation/FormMails.Designer.cs create mode 100644 SoftwareInstallation/SoftwareInstallation/FormMails.cs create mode 100644 SoftwareInstallation/SoftwareInstallation/FormMails.resx create mode 100644 SoftwareInstallation/SoftwareInstallationBusinessLogic/BusinessLogics/MessageInfoLogic.cs create mode 100644 SoftwareInstallation/SoftwareInstallationBusinessLogic/MailWorker/AbsractMailWorker.cs create mode 100644 SoftwareInstallation/SoftwareInstallationBusinessLogic/MailWorker/MailKitWorker.cs create mode 100644 SoftwareInstallation/SoftwareInstallationClientApp/Views/Home/Mails.cshtml create mode 100644 SoftwareInstallation/SoftwareInstallationContracts/BindingModels/MailConfigBindingModel.cs create mode 100644 SoftwareInstallation/SoftwareInstallationContracts/BindingModels/MailInfoBindingModel.cs create mode 100644 SoftwareInstallation/SoftwareInstallationContracts/BindingModels/MailSendBindingModel.cs create mode 100644 SoftwareInstallation/SoftwareInstallationContracts/BusinessLogicContracts/IMessageInfoLogic.cs create mode 100644 SoftwareInstallation/SoftwareInstallationContracts/SearchModels/MessageInfoSearchModel.cs create mode 100644 SoftwareInstallation/SoftwareInstallationContracts/StoragesContracts/IMessageInfoStorage.cs create mode 100644 SoftwareInstallation/SoftwareInstallationContracts/ViewModels/MessageInfoViewModel.cs create mode 100644 SoftwareInstallation/SoftwareInstallationDataModels/Models/IMessageInfoModel.cs create mode 100644 SoftwareInstallation/SoftwareInstallationDatabaseImplement/Implements/MessageInfoStorage.cs create mode 100644 SoftwareInstallation/SoftwareInstallationDatabaseImplement/Migrations/20240427172814_MailMessagesUpdate.Designer.cs create mode 100644 SoftwareInstallation/SoftwareInstallationDatabaseImplement/Migrations/20240427172814_MailMessagesUpdate.cs create mode 100644 SoftwareInstallation/SoftwareInstallationDatabaseImplement/Migrations/20240430080140_Test.Designer.cs create mode 100644 SoftwareInstallation/SoftwareInstallationDatabaseImplement/Migrations/20240430080140_Test.cs create mode 100644 SoftwareInstallation/SoftwareInstallationDatabaseImplement/Models/Message.cs create mode 100644 SoftwareInstallation/SoftwareInstallationFileImplement/Implements/MessageInfoStorage.cs create mode 100644 SoftwareInstallation/SoftwareInstallationFileImplement/Models/Message.cs create mode 100644 SoftwareInstallation/SoftwareInstallationListImplement/Implements/MessageInfoStorage.cs create mode 100644 SoftwareInstallation/SoftwareInstallationListImplement/Models/Message.cs diff --git a/SoftwareInstallation/SoftwareInstallation/App.config b/SoftwareInstallation/SoftwareInstallation/App.config new file mode 100644 index 0000000..046eeb8 --- /dev/null +++ b/SoftwareInstallation/SoftwareInstallation/App.config @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/SoftwareInstallation/SoftwareInstallation/FormMails.Designer.cs b/SoftwareInstallation/SoftwareInstallation/FormMails.Designer.cs new file mode 100644 index 0000000..30f2ded --- /dev/null +++ b/SoftwareInstallation/SoftwareInstallation/FormMails.Designer.cs @@ -0,0 +1,62 @@ +namespace SoftwareInstallationView +{ + 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() + { + this.DataGridView = new System.Windows.Forms.DataGridView(); + ((System.ComponentModel.ISupportInitialize)(this.DataGridView)).BeginInit(); + this.SuspendLayout(); + // + // DataGridView + // + this.DataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.DataGridView.Location = new System.Drawing.Point(3, 3); + this.DataGridView.Name = "DataGridView"; + this.DataGridView.RowTemplate.Height = 25; + this.DataGridView.Size = new System.Drawing.Size(794, 445); + this.DataGridView.TabIndex = 0; + // + // FormMails + // + this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 450); + this.Controls.Add(this.DataGridView); + this.Name = "FormMails"; + this.Text = "Эл. письма"; + this.Load += new System.EventHandler(this.FormMails_Load); + ((System.ComponentModel.ISupportInitialize)(this.DataGridView)).EndInit(); + this.ResumeLayout(false); + + } + + #endregion + + private DataGridView DataGridView; + } +} \ No newline at end of file diff --git a/SoftwareInstallation/SoftwareInstallation/FormMails.cs b/SoftwareInstallation/SoftwareInstallation/FormMails.cs new file mode 100644 index 0000000..57706d1 --- /dev/null +++ b/SoftwareInstallation/SoftwareInstallation/FormMails.cs @@ -0,0 +1,55 @@ +using Microsoft.Extensions.Logging; +using SoftwareInstallationContracts.BusinessLogicContracts; +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 SoftwareInstallationView +{ + public partial class FormMails : Form + { + private readonly ILogger _logger; + private readonly IMessageInfoLogic _logic; + + public FormMails(ILogger logger, IMessageInfoLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + LoadData(); + } + + private void LoadData() + { + try + { + var list = _logic.ReadList(null); + if (list != null) + { + DataGridView.DataSource = list; + DataGridView.Columns["ClientId"].Visible = false; + DataGridView.Columns["MessageId"].Visible = false; + DataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + _logger.LogInformation("Загрузка писем"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки писем"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + + private void FormMails_Load(object sender, EventArgs e) + { + LoadData(); + } + } +} diff --git a/SoftwareInstallation/SoftwareInstallation/FormMails.resx b/SoftwareInstallation/SoftwareInstallation/FormMails.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/SoftwareInstallation/SoftwareInstallation/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/SoftwareInstallation/SoftwareInstallation/FormMain.Designer.cs b/SoftwareInstallation/SoftwareInstallation/FormMain.Designer.cs index c9c62c6..e55e9df 100644 --- a/SoftwareInstallation/SoftwareInstallation/FormMain.Designer.cs +++ b/SoftwareInstallation/SoftwareInstallation/FormMain.Designer.cs @@ -32,18 +32,19 @@ справочникиToolStripMenuItem = new ToolStripMenuItem(); компонентыToolStripMenuItem = new ToolStripMenuItem(); изделияToolStripMenuItem = new ToolStripMenuItem(); + исполнителиToolStripMenuItem = new ToolStripMenuItem(); отчётыToolStripMenuItem = new ToolStripMenuItem(); списокИзделийToolStripMenuItem = new ToolStripMenuItem(); компонентыПоИзделиямToolStripMenuItem = new ToolStripMenuItem(); списокЗаказовToolStripMenuItem = new ToolStripMenuItem(); + запускРаботToolStripMenuItem = new ToolStripMenuItem(); + элекПисьмаToolStripMenuItem = new ToolStripMenuItem(); dataGridView = new DataGridView(); buttonCreateOrder = new Button(); buttonTakeOrderInWork = new Button(); buttonOrderReady = new Button(); buttonIssuedOrder = new Button(); buttonRefresh = new Button(); - запускРаботToolStripMenuItem = new ToolStripMenuItem(); - исполнителиToolStripMenuItem = new ToolStripMenuItem(); menuStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); SuspendLayout(); @@ -51,7 +52,7 @@ // menuStrip1 // menuStrip1.ImageScalingSize = new Size(20, 20); - menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчётыToolStripMenuItem, запускРаботToolStripMenuItem }); + menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчётыToolStripMenuItem, запускРаботToolStripMenuItem, элекПисьмаToolStripMenuItem }); menuStrip1.Location = new Point(0, 0); menuStrip1.Name = "menuStrip1"; menuStrip1.Padding = new Padding(7, 3, 0, 3); @@ -69,17 +70,24 @@ // компонентыToolStripMenuItem // компонентыToolStripMenuItem.Name = "компонентыToolStripMenuItem"; - компонентыToolStripMenuItem.Size = new Size(224, 26); + компонентыToolStripMenuItem.Size = new Size(185, 26); компонентыToolStripMenuItem.Text = "Компоненты"; компонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click; // // изделияToolStripMenuItem // изделияToolStripMenuItem.Name = "изделияToolStripMenuItem"; - изделияToolStripMenuItem.Size = new Size(224, 26); + изделияToolStripMenuItem.Size = new Size(185, 26); изделияToolStripMenuItem.Text = "Изделия"; изделияToolStripMenuItem.Click += ИзделияToolStripMenuItem_Click; // + // исполнителиToolStripMenuItem + // + исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; + исполнителиToolStripMenuItem.Size = new Size(185, 26); + исполнителиToolStripMenuItem.Text = "Исполнители"; + исполнителиToolStripMenuItem.Click += исполнителиToolStripMenuItem_Click; + // // отчётыToolStripMenuItem // отчётыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокИзделийToolStripMenuItem, компонентыПоИзделиямToolStripMenuItem, списокЗаказовToolStripMenuItem }); @@ -108,6 +116,20 @@ списокЗаказовToolStripMenuItem.Text = "Список заказов"; списокЗаказовToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click; // + // запускРаботToolStripMenuItem + // + запускРаботToolStripMenuItem.Name = "запускРаботToolStripMenuItem"; + запускРаботToolStripMenuItem.Size = new Size(114, 24); + запускРаботToolStripMenuItem.Text = "Запуск работ"; + запускРаботToolStripMenuItem.Click += ЗапускРаботToolStripMenuItem_Click; + // + // элекПисьмаToolStripMenuItem + // + элекПисьмаToolStripMenuItem.Name = "элекПисьмаToolStripMenuItem"; + элекПисьмаToolStripMenuItem.Size = new Size(172, 24); + элекПисьмаToolStripMenuItem.Text = "Электронные письма"; + элекПисьмаToolStripMenuItem.Click += электронныеПисьмаToolStripMenuItem_Click; + // // dataGridView // dataGridView.AllowUserToAddRows = false; @@ -184,20 +206,6 @@ buttonRefresh.UseVisualStyleBackColor = true; buttonRefresh.Click += ButtonRef_Click; // - // запускРаботToolStripMenuItem - // - запускРаботToolStripMenuItem.Name = "запускРаботToolStripMenuItem"; - запускРаботToolStripMenuItem.Size = new Size(114, 24); - запускРаботToolStripMenuItem.Text = "Запуск работ"; - запускРаботToolStripMenuItem.Click += ЗапускРаботToolStripMenuItem_Click; - // - // исполнителиToolStripMenuItem - // - исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; - исполнителиToolStripMenuItem.Size = new Size(224, 26); - исполнителиToolStripMenuItem.Text = "Исполнители"; - исполнителиToolStripMenuItem.Click += исполнителиToolStripMenuItem_Click; - // // FormMain // AutoScaleDimensions = new SizeF(8F, 20F); @@ -240,5 +248,6 @@ private ToolStripMenuItem списокЗаказовToolStripMenuItem; private ToolStripMenuItem исполнителиToolStripMenuItem; private ToolStripMenuItem запускРаботToolStripMenuItem; + private ToolStripMenuItem элекПисьмаToolStripMenuItem; } } \ No newline at end of file diff --git a/SoftwareInstallation/SoftwareInstallation/FormMain.cs b/SoftwareInstallation/SoftwareInstallation/FormMain.cs index d5d4fa5..635e38b 100644 --- a/SoftwareInstallation/SoftwareInstallation/FormMain.cs +++ b/SoftwareInstallation/SoftwareInstallation/FormMain.cs @@ -222,5 +222,14 @@ e) { LoadData(); } + + private void электронныеПисьмаToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormMails)); + if (service is FormMails form) + { + form.ShowDialog(); + } + } } } diff --git a/SoftwareInstallation/SoftwareInstallation/Program.cs b/SoftwareInstallation/SoftwareInstallation/Program.cs index 0e6fbf8..3d3f812 100644 --- a/SoftwareInstallation/SoftwareInstallation/Program.cs +++ b/SoftwareInstallation/SoftwareInstallation/Program.cs @@ -3,8 +3,10 @@ using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; using SoftwareInstallationBusinessLogic.BusinessLogic; using SoftwareInstallationBusinessLogic.BusinessLogics; +using SoftwareInstallationBusinessLogic.MailWorker; using SoftwareInstallationBusinessLogic.OfficePackage; using SoftwareInstallationBusinessLogic.OfficePackage.Implements; +using SoftwareInstallationContracts.BindingModels; using SoftwareInstallationContracts.BusinessLogicContracts; using SoftwareInstallationContracts.StoragesContracts; using SoftwareInstallationDatabaseImplement.Implements; @@ -29,6 +31,39 @@ namespace SoftwareInstallation 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()); } @@ -66,6 +101,13 @@ namespace SoftwareInstallation services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + + services.AddTransient(); + services.AddTransient(); + services.AddSingleton(); } + + private static void MailCheck(object obj) => ServiceProvider?.GetService()?.MailCheck(); } } \ No newline at end of file diff --git a/SoftwareInstallation/SoftwareInstallationBusinessLogic/BusinessLogics/ClientLogic.cs b/SoftwareInstallation/SoftwareInstallationBusinessLogic/BusinessLogics/ClientLogic.cs index 488ac61..143b0c1 100644 --- a/SoftwareInstallation/SoftwareInstallationBusinessLogic/BusinessLogics/ClientLogic.cs +++ b/SoftwareInstallation/SoftwareInstallationBusinessLogic/BusinessLogics/ClientLogic.cs @@ -8,6 +8,7 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; +using System.Text.RegularExpressions; using System.Threading.Tasks; namespace SoftwareInstallationBusinessLogic.BusinessLogics @@ -108,6 +109,15 @@ namespace SoftwareInstallationBusinessLogic.BusinessLogics throw new ArgumentNullException("Нет пароля клиента", nameof(model.ClientFIO)); } + if (!Regex.IsMatch(model.Email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$", RegexOptions.IgnoreCase)) + { + throw new ArgumentException("Неправильно введенный email", nameof(model.Email)); + } + + if (!Regex.IsMatch(model.Password, @"^^((\w+\d+\W+)|(\w+\W+\d+)|(\d+\w+\W+)|(\d+\W+\w+)|(\W+\w+\d+)|(\W+\d+\w+))[\w\d\W]*$", RegexOptions.IgnoreCase)) + { + 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/SoftwareInstallation/SoftwareInstallationBusinessLogic/BusinessLogics/MessageInfoLogic.cs b/SoftwareInstallation/SoftwareInstallationBusinessLogic/BusinessLogics/MessageInfoLogic.cs new file mode 100644 index 0000000..e71c1c3 --- /dev/null +++ b/SoftwareInstallation/SoftwareInstallationBusinessLogic/BusinessLogics/MessageInfoLogic.cs @@ -0,0 +1,101 @@ +using Microsoft.Extensions.Logging; +using SoftwareInstallationContracts.BindingModels; +using SoftwareInstallationContracts.BusinessLogicContracts; +using SoftwareInstallationContracts.SearchModels; +using SoftwareInstallationContracts.StoragesContracts; +using SoftwareInstallationContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SoftwareInstallationBusinessLogic.BusinessLogics +{ + public class MessageInfoLogic : IMessageInfoLogic + { + private readonly ILogger _logger; + private readonly IMessageInfoStorage _messageStorage; + private readonly IClientStorage _clientStorage; + + public MessageInfoLogic(ILogger logger, IMessageInfoStorage messageStorage, IClientStorage clientStorage) + { + _logger = logger; + _messageStorage = messageStorage; + _clientStorage = clientStorage; + + } + + public bool Create(MessageInfoBindingModel model) + { + CheckModel(model); + if (_messageStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + + return false; + } + + return true; + } + + public List? ReadList(MessageInfoSearchModel? model) + { + _logger.LogInformation("ReadList. MessageId:{MessageId}.ClientId:{ClientId} ", model?.MessageId, model?.ClientId); + var list = model == null ? _messageStorage.GetFullList() : _messageStorage.GetFilteredList(model); + + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + + return null; + } + + _logger.LogInformation("ReadList. Count: {Count}", list.Count); + + return list; + } + private void CheckModel(MessageInfoBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (!withParams) + { + return; + } + if (string.IsNullOrEmpty(model.MessageId)) + { + throw new ArgumentNullException("Не указан id сообщения", nameof(model.MessageId)); + } + if (string.IsNullOrEmpty(model.SenderName)) + { + throw new ArgumentNullException("Не указао почта", nameof(model.SenderName)); + } + if (string.IsNullOrEmpty(model.Subject)) + { + throw new ArgumentNullException("Не указана тема", nameof(model.Subject)); + } + if (string.IsNullOrEmpty(model.Body)) + { + throw new ArgumentNullException("Не указан текст сообщения", nameof(model.Subject)); + } + + _logger.LogInformation("MessageInfo. MessageId:{MessageId}.SenderName:{SenderName}.Subject:{Subject}.Body:{Body}", model.MessageId, model.SenderName, model.Subject, model.Body); + var element = _clientStorage.GetElement(new ClientSearchModel + { + Email = model.SenderName + }); + if (element == null) + { + _logger.LogWarning("Не удалоссь найти клиента, отправившего письмо с адреса Email:{Email}", model.SenderName); + } + else + { + model.ClientId = element.Id; + } + } + + } +} diff --git a/SoftwareInstallation/SoftwareInstallationBusinessLogic/BusinessLogics/OrderLogic.cs b/SoftwareInstallation/SoftwareInstallationBusinessLogic/BusinessLogics/OrderLogic.cs index dde1f67..285622d 100644 --- a/SoftwareInstallation/SoftwareInstallationBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/SoftwareInstallation/SoftwareInstallationBusinessLogic/BusinessLogics/OrderLogic.cs @@ -1,5 +1,6 @@ using DocumentFormat.OpenXml.EMMA; using Microsoft.Extensions.Logging; +using SoftwareInstallationBusinessLogic.MailWorker; using SoftwareInstallationContracts.BindingModels; using SoftwareInstallationContracts.BusinessLogicContracts; using SoftwareInstallationContracts.SearchModels; @@ -18,12 +19,16 @@ namespace SoftwareInstallationBusinessLogic.BusinessLogics { private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; + private readonly AbstractMailWorker _mailWorker; + private readonly IClientLogic _clientLogic; static readonly object locker = new object(); - public OrderLogic(ILogger logger, IOrderStorage orderStorage) + public OrderLogic(ILogger logger, IOrderStorage orderStorage, AbstractMailWorker mailWorker, IClientLogic clientLogic) { _logger = logger; _orderStorage = orderStorage; + _mailWorker = mailWorker; + _clientLogic = clientLogic; } public bool CreateOrder(OrderBindingModel model) @@ -37,14 +42,17 @@ namespace SoftwareInstallationBusinessLogic.BusinessLogics } model.Status = OrderStatus.Принят; + var result = _orderStorage.Insert(model); - if (_orderStorage.Insert(model) == null) + if (result == null) { model.Status = OrderStatus.Неизвестен; _logger.LogWarning("Insert operation failed"); return false; } + SendOrderMessage(result.ClientId, $"Установка ПО, Заказ №{result.Id}", $"Заказ №{result.Id} от {result.DateCreate} на сумму {result.Sum:0.00} принят"); + return true; } @@ -74,14 +82,16 @@ namespace SoftwareInstallationBusinessLogic.BusinessLogics model.Count = viewModel.Count; model.PackageId = viewModel.PackageId; - - if (_orderStorage.Update(model) == null) + var result = _orderStorage.Update(model); + if (result == null) { model.Status--; _logger.LogWarning("Неудачная операция обновления статуса"); return false; } + SendOrderMessage(result.ClientId, $"Установка ПО, Заказ №{result.Id}", $"Заказ №{model.Id} изменен статус на {result.Status}"); + return true; } @@ -170,6 +180,25 @@ namespace SoftwareInstallationBusinessLogic.BusinessLogics return element; } + + private bool SendOrderMessage(int clientId, string subject, string text) + { + var client = _clientLogic.ReadElement(new() { Id = clientId }); + + if (client == null) + { + return false; + } + + _mailWorker.MailSendAsync(new() + { + MailAddress = client.Email, + Subject = subject, + Text = text + }); + + return true; + } } } diff --git a/SoftwareInstallation/SoftwareInstallationBusinessLogic/BusinessLogics/WorkModeling.cs b/SoftwareInstallation/SoftwareInstallationBusinessLogic/BusinessLogics/WorkModeling.cs index b5e99ee..42e19ac 100644 --- a/SoftwareInstallation/SoftwareInstallationBusinessLogic/BusinessLogics/WorkModeling.cs +++ b/SoftwareInstallation/SoftwareInstallationBusinessLogic/BusinessLogics/WorkModeling.cs @@ -91,6 +91,8 @@ namespace SoftwareInstallationBusinessLogic.BusinessLogic _logger.LogError(ex, "Error while do work"); throw; } + + // отдыхаем только если работаем } }); } diff --git a/SoftwareInstallation/SoftwareInstallationBusinessLogic/MailWorker/AbsractMailWorker.cs b/SoftwareInstallation/SoftwareInstallationBusinessLogic/MailWorker/AbsractMailWorker.cs new file mode 100644 index 0000000..8659e4c --- /dev/null +++ b/SoftwareInstallation/SoftwareInstallationBusinessLogic/MailWorker/AbsractMailWorker.cs @@ -0,0 +1,85 @@ +using Microsoft.Extensions.Logging; +using SoftwareInstallationContracts.BindingModels; +using SoftwareInstallationContracts.BusinessLogicContracts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SoftwareInstallationBusinessLogic.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/SoftwareInstallation/SoftwareInstallationBusinessLogic/MailWorker/MailKitWorker.cs b/SoftwareInstallation/SoftwareInstallationBusinessLogic/MailWorker/MailKitWorker.cs new file mode 100644 index 0000000..f5eac70 --- /dev/null +++ b/SoftwareInstallation/SoftwareInstallationBusinessLogic/MailWorker/MailKitWorker.cs @@ -0,0 +1,83 @@ +using Microsoft.Extensions.Logging; +using SoftwareInstallationContracts.BindingModels; +using SoftwareInstallationContracts.BusinessLogicContracts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Mail; +using System.Net; +using System.Security.Authentication; +using System.Text; +using System.Threading.Tasks; +using MailKit.Net.Pop3; +using MailKit.Security; + +namespace SoftwareInstallationBusinessLogic.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 error) + { } + finally + { + client.Disconnect(true); + } + }); + return list; + } + } +} diff --git a/SoftwareInstallation/SoftwareInstallationBusinessLogic/SoftwareInstallationBusinessLogic.csproj b/SoftwareInstallation/SoftwareInstallationBusinessLogic/SoftwareInstallationBusinessLogic.csproj index 7c14add..3ef689b 100644 --- a/SoftwareInstallation/SoftwareInstallationBusinessLogic/SoftwareInstallationBusinessLogic.csproj +++ b/SoftwareInstallation/SoftwareInstallationBusinessLogic/SoftwareInstallationBusinessLogic.csproj @@ -8,6 +8,7 @@ + diff --git a/SoftwareInstallation/SoftwareInstallationClientApp/Controllers/HomeController.cs b/SoftwareInstallation/SoftwareInstallationClientApp/Controllers/HomeController.cs index c748ea8..251e2b7 100644 --- a/SoftwareInstallation/SoftwareInstallationClientApp/Controllers/HomeController.cs +++ b/SoftwareInstallation/SoftwareInstallationClientApp/Controllers/HomeController.cs @@ -36,12 +36,12 @@ namespace SoftwareInstallationClientApp.Controllers { if (APIClient.Client == null) { - throw new Exception(" ? "); + throw new Exception("Вы как суда попали? Суда вход только авторизованным"); } if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(fio)) { - throw new Exception(" , "); + throw new Exception("Введите логин, пароль и ФИО"); } APIClient.PostRequest("api/client/updatedata", new ClientBindingModel { @@ -75,13 +75,13 @@ namespace SoftwareInstallationClientApp.Controllers if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password)) { - throw new Exception(" "); + throw new Exception("Введите логин и пароль"); } APIClient.Client = APIClient.GetRequest($"api/client/login?login={login}&password={password}"); if (APIClient.Client == null) { - throw new Exception(" /"); + throw new Exception("Неверный логин/пароль"); } Response.Redirect("Index"); } @@ -96,7 +96,7 @@ namespace SoftwareInstallationClientApp.Controllers if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(fio)) { - throw new Exception(" , "); + throw new Exception("Введите логин, пароль и ФИО"); } APIClient.PostRequest("api/client/register", new ClientBindingModel { @@ -118,11 +118,11 @@ namespace SoftwareInstallationClientApp.Controllers { if (APIClient.Client == null) { - throw new Exception(" ? "); + throw new Exception("Вы как суда попали? Суда вход только авторизованным"); } if (count <= 0) { - throw new Exception(" 0"); + throw new Exception("Количество и сумма должны быть больше 0"); } APIClient.PostRequest("api/main/createorder", new OrderBindingModel { @@ -139,5 +139,14 @@ namespace SoftwareInstallationClientApp.Controllers var pack = APIClient.GetRequest($"api/main/getpackage?packageId={package}"); return count * (pack?.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}")); + } } } diff --git a/SoftwareInstallation/SoftwareInstallationClientApp/Views/Home/Mails.cshtml b/SoftwareInstallation/SoftwareInstallationClientApp/Views/Home/Mails.cshtml new file mode 100644 index 0000000..dfff0c9 --- /dev/null +++ b/SoftwareInstallation/SoftwareInstallationClientApp/Views/Home/Mails.cshtml @@ -0,0 +1,54 @@ +@using SoftwareInstallationContracts.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/SoftwareInstallation/SoftwareInstallationClientApp/Views/Shared/_Layout.cshtml b/SoftwareInstallation/SoftwareInstallationClientApp/Views/Shared/_Layout.cshtml index 5db7b1b..2099ea6 100644 --- a/SoftwareInstallation/SoftwareInstallationClientApp/Views/Shared/_Layout.cshtml +++ b/SoftwareInstallation/SoftwareInstallationClientApp/Views/Shared/_Layout.cshtml @@ -23,14 +23,17 @@