From 237f82df317853215ba5beeeda785b0f89a45c91 Mon Sep 17 00:00:00 2001 From: Anastasia Date: Sat, 13 May 2023 13:15:43 +0400 Subject: [PATCH] =?UTF-8?q?=D0=A1=D0=B4=D0=B5=D0=BB=D0=B0=D0=BD=D0=BD?= =?UTF-8?q?=D0=B0=D1=8F=207=20=D0=BB=D0=B0=D0=B1.=20=D1=80=D0=B0=D0=B1?= =?UTF-8?q?=D0=BE=D1=82=D0=B0.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Models/IMessageInfoModel.cs | 18 ++ JewelryStore/JewelryStore/App.config | 11 + .../JewelryStore/FormMails.Designer.cs | 65 ++++ JewelryStore/JewelryStore/FormMails.cs | 55 ++++ JewelryStore/JewelryStore/FormMails.resx | 60 ++++ .../JewelryStore/FormMain.Designer.cs | 32 +- JewelryStore/JewelryStore/FormMain.cs | 8 + JewelryStore/JewelryStore/Program.cs | 28 ++ .../BusinessLogics/ClientLogic.cs | 10 + .../BusinessLogics/MessageInfoLogic.cs | 55 ++++ .../BusinessLogics/OrderLogic.cs | 56 +++- .../JewelryStoreBusinessLogic.csproj | 1 + .../MailWorker/AbstractMailWorker.cs | 94 ++++++ .../MailWorker/MailKitWorker.cs | 82 +++++ .../Controllers/HomeController.cs | 10 + .../Views/Home/Mails.cshtml | 54 ++++ .../Views/Shared/_Layout.cshtml | 15 +- .../BindingModels/MailConfigBindingModel.cs | 18 ++ .../BindingModels/MailSendInfoBindingModel.cs | 15 + .../BindingModels/MessageInfoBindingModel.cs | 19 ++ .../IMessageInfoLogic.cs | 17 + .../SearchModels/MessageInfoSearchModel.cs | 14 + .../StoragesModels/IMessageInfoStorage.cs | 19 ++ .../ViewModels/MessageInfoViewModel.cs | 29 ++ .../Implements/MessageInfoStorage.cs | 55 ++++ .../JewelryStoreDatabase.cs | 1 + .../20230513091120_AddMessage.Designer.cs | 301 ++++++++++++++++++ .../Migrations/20230513091120_AddMessage.cs | 49 +++ .../JewelryStoreDatabaseModelSnapshot.cs | 44 +++ .../Models/Client.cs | 3 + .../Models/Message.cs | 56 ++++ .../DataFileSingleton.cs | 10 +- .../Implements/MessageInfoStorage.cs | 57 ++++ .../Models/Message.cs | 80 +++++ .../DataListSingleton.cs | 2 + .../Implements/MessageInfoStorage.cs | 73 +++++ .../Models/Message.cs | 53 +++ .../Controllers/ClientController.cs | 21 +- JewelryStore/JewelryStoreRestApi/Program.cs | 18 ++ .../JewelryStoreRestApi/appsettings.json | 9 +- 40 files changed, 1584 insertions(+), 33 deletions(-) create mode 100644 JewelryStore/JewelryShopDataModels/Models/IMessageInfoModel.cs create mode 100644 JewelryStore/JewelryStore/App.config create mode 100644 JewelryStore/JewelryStore/FormMails.Designer.cs create mode 100644 JewelryStore/JewelryStore/FormMails.cs create mode 100644 JewelryStore/JewelryStore/FormMails.resx create mode 100644 JewelryStore/JewelryStoreBusinessLogic/BusinessLogics/MessageInfoLogic.cs create mode 100644 JewelryStore/JewelryStoreBusinessLogic/MailWorker/AbstractMailWorker.cs create mode 100644 JewelryStore/JewelryStoreBusinessLogic/MailWorker/MailKitWorker.cs create mode 100644 JewelryStore/JewelryStoreClientApp/Views/Home/Mails.cshtml create mode 100644 JewelryStore/JewelryStoreContracts/BindingModels/MailConfigBindingModel.cs create mode 100644 JewelryStore/JewelryStoreContracts/BindingModels/MailSendInfoBindingModel.cs create mode 100644 JewelryStore/JewelryStoreContracts/BindingModels/MessageInfoBindingModel.cs create mode 100644 JewelryStore/JewelryStoreContracts/BusinessLogicsContracts/IMessageInfoLogic.cs create mode 100644 JewelryStore/JewelryStoreContracts/SearchModels/MessageInfoSearchModel.cs create mode 100644 JewelryStore/JewelryStoreContracts/StoragesModels/IMessageInfoStorage.cs create mode 100644 JewelryStore/JewelryStoreContracts/ViewModels/MessageInfoViewModel.cs create mode 100644 JewelryStore/JewelryStoreDatabaseImplement/Implements/MessageInfoStorage.cs create mode 100644 JewelryStore/JewelryStoreDatabaseImplement/Migrations/20230513091120_AddMessage.Designer.cs create mode 100644 JewelryStore/JewelryStoreDatabaseImplement/Migrations/20230513091120_AddMessage.cs create mode 100644 JewelryStore/JewelryStoreDatabaseImplement/Models/Message.cs create mode 100644 JewelryStore/JewelryStoreFileImplement/Implements/MessageInfoStorage.cs create mode 100644 JewelryStore/JewelryStoreFileImplement/Models/Message.cs create mode 100644 JewelryStore/JewelryStoreListImplement/Implements/MessageInfoStorage.cs create mode 100644 JewelryStore/JewelryStoreListImplement/Models/Message.cs diff --git a/JewelryStore/JewelryShopDataModels/Models/IMessageInfoModel.cs b/JewelryStore/JewelryShopDataModels/Models/IMessageInfoModel.cs new file mode 100644 index 0000000..120de88 --- /dev/null +++ b/JewelryStore/JewelryShopDataModels/Models/IMessageInfoModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JewelryStoreDataModels.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/JewelryStore/JewelryStore/App.config b/JewelryStore/JewelryStore/App.config new file mode 100644 index 0000000..e3dc7a9 --- /dev/null +++ b/JewelryStore/JewelryStore/App.config @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/JewelryStore/JewelryStore/FormMails.Designer.cs b/JewelryStore/JewelryStore/FormMails.Designer.cs new file mode 100644 index 0000000..7c69012 --- /dev/null +++ b/JewelryStore/JewelryStore/FormMails.Designer.cs @@ -0,0 +1,65 @@ +namespace JewelryStore +{ + 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.BackgroundColor = System.Drawing.SystemColors.Window; + this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView.Dock = System.Windows.Forms.DockStyle.Fill; + this.dataGridView.Location = new System.Drawing.Point(0, 0); + this.dataGridView.Name = "dataGridView"; + this.dataGridView.RowHeadersWidth = 62; + this.dataGridView.RowTemplate.Height = 33; + this.dataGridView.Size = new System.Drawing.Size(1161, 461); + this.dataGridView.TabIndex = 0; + // + // FormMails + // + this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(1161, 461); + 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/JewelryStore/JewelryStore/FormMails.cs b/JewelryStore/JewelryStore/FormMails.cs new file mode 100644 index 0000000..5507ba1 --- /dev/null +++ b/JewelryStore/JewelryStore/FormMails.cs @@ -0,0 +1,55 @@ +using JewelryStoreContracts.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 JewelryStore +{ + 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/JewelryStore/JewelryStore/FormMails.resx b/JewelryStore/JewelryStore/FormMails.resx new file mode 100644 index 0000000..f298a7b --- /dev/null +++ b/JewelryStore/JewelryStore/FormMails.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/JewelryStore/JewelryStore/FormMain.Designer.cs b/JewelryStore/JewelryStore/FormMain.Designer.cs index 82e1799..e9caced 100644 --- a/JewelryStore/JewelryStore/FormMain.Designer.cs +++ b/JewelryStore/JewelryStore/FormMain.Designer.cs @@ -32,16 +32,17 @@ this.СправочникиToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.КомпонентыToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.ИзделияToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.исполнителиToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.отчетыToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.списокИзделийToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.компонентыПоИзделиямToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.списокЗаказовToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.запускРаботToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.письмаToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.dataGridView = new System.Windows.Forms.DataGridView(); this.buttonCreateOrder = new System.Windows.Forms.Button(); this.buttonIssuedOrder = new System.Windows.Forms.Button(); this.buttonRefresh = new System.Windows.Forms.Button(); - this.исполнителиToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.menuStrip.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); this.SuspendLayout(); @@ -52,7 +53,8 @@ this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.СправочникиToolStripMenuItem, this.отчетыToolStripMenuItem, - this.запускРаботToolStripMenuItem}); + this.запускРаботToolStripMenuItem, + this.письмаToolStripMenuItem}); this.menuStrip.Location = new System.Drawing.Point(0, 0); this.menuStrip.Name = "menuStrip"; this.menuStrip.Size = new System.Drawing.Size(1121, 33); @@ -72,17 +74,24 @@ // КомпонентыToolStripMenuItem // this.КомпонентыToolStripMenuItem.Name = "КомпонентыToolStripMenuItem"; - this.КомпонентыToolStripMenuItem.Size = new System.Drawing.Size(270, 34); + this.КомпонентыToolStripMenuItem.Size = new System.Drawing.Size(220, 34); this.КомпонентыToolStripMenuItem.Text = "Компоненты"; this.КомпонентыToolStripMenuItem.Click += new System.EventHandler(this.КомпонентыToolStripMenuItem_Click); // // ИзделияToolStripMenuItem // this.ИзделияToolStripMenuItem.Name = "ИзделияToolStripMenuItem"; - this.ИзделияToolStripMenuItem.Size = new System.Drawing.Size(270, 34); + this.ИзделияToolStripMenuItem.Size = new System.Drawing.Size(220, 34); this.ИзделияToolStripMenuItem.Text = "Изделия"; this.ИзделияToolStripMenuItem.Click += new System.EventHandler(this.ИзделияToolStripMenuItem_Click); // + // исполнителиToolStripMenuItem + // + this.исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; + this.исполнителиToolStripMenuItem.Size = new System.Drawing.Size(220, 34); + this.исполнителиToolStripMenuItem.Text = "Исполнители"; + this.исполнителиToolStripMenuItem.Click += new System.EventHandler(this.ИсполнителиToolStripMenuItem_Click); + // // отчетыToolStripMenuItem // this.отчетыToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { @@ -121,6 +130,13 @@ this.запускРаботToolStripMenuItem.Text = "Запуск работ"; this.запускРаботToolStripMenuItem.Click += new System.EventHandler(this.ЗапускРаботToolStripMenuItem_Click); // + // письмаToolStripMenuItem + // + this.письмаToolStripMenuItem.Name = "письмаToolStripMenuItem"; + this.письмаToolStripMenuItem.Size = new System.Drawing.Size(90, 29); + this.письмаToolStripMenuItem.Text = "Письма"; + this.письмаToolStripMenuItem.Click += new System.EventHandler(this.ПисьмаToolStripMenuItem_Click); + // // dataGridView // this.dataGridView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) @@ -166,13 +182,6 @@ this.buttonRefresh.UseVisualStyleBackColor = true; this.buttonRefresh.Click += new System.EventHandler(this.ButtonRefresh_Click); // - // исполнителиToolStripMenuItem - // - this.исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; - this.исполнителиToolStripMenuItem.Size = new System.Drawing.Size(270, 34); - this.исполнителиToolStripMenuItem.Text = "Исполнители"; - this.исполнителиToolStripMenuItem.Click += new System.EventHandler(this.ИсполнителиToolStripMenuItem_Click); - // // FormMain // this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F); @@ -211,5 +220,6 @@ private ToolStripMenuItem списокЗаказовToolStripMenuItem; private ToolStripMenuItem запускРаботToolStripMenuItem; private ToolStripMenuItem исполнителиToolStripMenuItem; + private ToolStripMenuItem письмаToolStripMenuItem; } } \ No newline at end of file diff --git a/JewelryStore/JewelryStore/FormMain.cs b/JewelryStore/JewelryStore/FormMain.cs index a16a802..d12209a 100644 --- a/JewelryStore/JewelryStore/FormMain.cs +++ b/JewelryStore/JewelryStore/FormMain.cs @@ -218,5 +218,13 @@ namespace JewelryStore } } + private void ПисьмаToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormMails)); + if (service is FormMails form) + { + form.ShowDialog(); + } + } } } \ No newline at end of file diff --git a/JewelryStore/JewelryStore/Program.cs b/JewelryStore/JewelryStore/Program.cs index db85ec7..50cfd47 100644 --- a/JewelryStore/JewelryStore/Program.cs +++ b/JewelryStore/JewelryStore/Program.cs @@ -8,6 +8,8 @@ using JewelryStoreBusinessLogic.BusinessLogics; using JewelryStoreBusinessLogic.OfficePackage.Implements; using JewelryStoreBusinessLogic.OfficePackage; using JewelryStoreContracts.StoragesModels; +using JewelryStoreContracts.BindingModels; +using JewelryStoreBusinessLogic.MailWorker; namespace JewelryStore { @@ -25,6 +27,26 @@ namespace JewelryStore 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, "Error"); + } Application.Run(_serviceProvider.GetRequiredService()); } @@ -40,13 +62,16 @@ namespace JewelryStore 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(); @@ -63,7 +88,10 @@ namespace JewelryStore 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/JewelryStore/JewelryStoreBusinessLogic/BusinessLogics/ClientLogic.cs b/JewelryStore/JewelryStoreBusinessLogic/BusinessLogics/ClientLogic.cs index 0dc1b59..8a6ba2d 100644 --- a/JewelryStore/JewelryStoreBusinessLogic/BusinessLogics/ClientLogic.cs +++ b/JewelryStore/JewelryStoreBusinessLogic/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 JewelryStoreBusinessLogic.BusinessLogics @@ -107,6 +108,15 @@ namespace JewelryStoreBusinessLogic.BusinessLogics { throw new ArgumentNullException("Нет пароля клиента", nameof(model.Password)); } + 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}. Id: {Id}", model.ClientFIO, model.Email, model.Id); var element = _clientStorage.GetElement(new ClientSearchModel { diff --git a/JewelryStore/JewelryStoreBusinessLogic/BusinessLogics/MessageInfoLogic.cs b/JewelryStore/JewelryStoreBusinessLogic/BusinessLogics/MessageInfoLogic.cs new file mode 100644 index 0000000..2faf953 --- /dev/null +++ b/JewelryStore/JewelryStoreBusinessLogic/BusinessLogics/MessageInfoLogic.cs @@ -0,0 +1,55 @@ +using JewelryStoreContracts.BindingModels; +using JewelryStoreContracts.BusinessLogicsContracts; +using JewelryStoreContracts.SearchModels; +using JewelryStoreContracts.StoragesModels; +using JewelryStoreContracts.ViewModels; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JewelryStoreBusinessLogic.BusinessLogics +{ + public class MessageInfoLogic : IMessageInfoLogic + { + private readonly ILogger _logger; + private readonly IMessageInfoStorage _messageStorage; + + public MessageInfoLogic(ILogger logger, IMessageInfoStorage messageStorage) + { + _logger = logger; + _messageStorage = messageStorage; + } + + public bool Create(MessageInfoBindingModel model) + { + if (_messageStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + + return false; + } + + return true; + } + + public List? ReadList(MessageInfoSearchModel? model) + { + _logger.LogInformation("ReadList. MessageId:{MessageId}.ClientId:{ClientId} ", model?.MessageId, model?.ClientId); + var list = model == null ? _messageStorage.GetFullList() : _messageStorage.GetFilteredList(model); + + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + + return null; + } + + _logger.LogInformation("ReadList. Count: {Count}", list.Count); + + return list; + } + } +} diff --git a/JewelryStore/JewelryStoreBusinessLogic/BusinessLogics/OrderLogic.cs b/JewelryStore/JewelryStoreBusinessLogic/BusinessLogics/OrderLogic.cs index e08b552..78bef5a 100644 --- a/JewelryStore/JewelryStoreBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/JewelryStore/JewelryStoreBusinessLogic/BusinessLogics/OrderLogic.cs @@ -1,4 +1,5 @@ -using JewelryStoreContracts.BindingModels; +using JewelryStoreBusinessLogic.MailWorker; +using JewelryStoreContracts.BindingModels; using JewelryStoreContracts.BusinessLogicsContracts; using JewelryStoreContracts.SearchModels; using JewelryStoreContracts.StoragesContracts; @@ -12,11 +13,15 @@ namespace JewelryStoreBusinessLogic.BusinessLogics { private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; + private readonly AbstractMailWorker _mailWorker; + private readonly IClientLogic _clientLogic; - 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) @@ -24,11 +29,13 @@ namespace JewelryStoreBusinessLogic.BusinessLogics CheckModel(model); if (model.Status != OrderStatus.Неизвестен) return false; model.Status = OrderStatus.Принят; - if (_orderStorage.Insert(model) == null) + var result = _orderStorage.Insert(model); + if (result == null) { _logger.LogWarning("Insert operation failed"); return false; } + SendOrderMessage(result.ClientId, $"Установка ПО, Заказ №{result.Id}", $"Заказ №{result.Id} от {result.DateCreate} на сумму {result.Sum:0.00} принят"); return true; } @@ -61,13 +68,34 @@ namespace JewelryStoreBusinessLogic.BusinessLogics model.JewelId = vmodel.JewelId; model.Sum = vmodel.Sum; model.Count = vmodel.Count; - if (_orderStorage.Update(model) == null) + var result = _orderStorage.Update(model); + if (result == null) { model.Status--; _logger.LogWarning("Update operation failed"); return false; } + SendOrderMessage(result.ClientId, $"Установка ПО, Заказ №{result.Id}", $"Заказ №{model.Id} изменен статус на {result.Status}"); + return true; + } + + 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; } @@ -100,25 +128,29 @@ namespace JewelryStoreBusinessLogic.BusinessLogics return StatusUpdate(model, OrderStatus.Выполняется); } - private bool CheckModel(OrderBindingModel model) + private void CheckModel(OrderBindingModel model, bool withParams = true) { if (model == null) { throw new ArgumentNullException(nameof(model)); } + if (!withParams) + { + return; + } + if (model.JewelId < 0) + { + throw new ArgumentNullException("Некорректный идентификатор у изделия", nameof(model.JewelId)); + } if (model.Count <= 0) { - throw new ArgumentException("Количество изделий в заказе должно быть больше 0", nameof(model.Count)); + throw new ArgumentNullException("Количество изделий в заказе должно быть больше 0", nameof(model.Count)); } if (model.Sum <= 0) { - throw new ArgumentException("Суммарная стоимость заказа должна быть больше 0", nameof(model.Sum)); + throw new ArgumentNullException("Сумма заказа должна быть больше 0", nameof(model.Sum)); } - if (model.DateCreate > model.DateImplement) - { - throw new ArgumentException("Время создания заказа не может быть больше времени его выполнения", nameof(model.DateImplement)); - } - return true; + _logger.LogInformation("Order. OrderID:{Id}. Sum:{ Sum}. JewelId: { JewelId}", model.Id, model.Sum, model.JewelId); } public OrderViewModel? ReadElement(OrderSearchModel model) diff --git a/JewelryStore/JewelryStoreBusinessLogic/JewelryStoreBusinessLogic.csproj b/JewelryStore/JewelryStoreBusinessLogic/JewelryStoreBusinessLogic.csproj index 696b768..b6bb711 100644 --- a/JewelryStore/JewelryStoreBusinessLogic/JewelryStoreBusinessLogic.csproj +++ b/JewelryStore/JewelryStoreBusinessLogic/JewelryStoreBusinessLogic.csproj @@ -8,6 +8,7 @@ + diff --git a/JewelryStore/JewelryStoreBusinessLogic/MailWorker/AbstractMailWorker.cs b/JewelryStore/JewelryStoreBusinessLogic/MailWorker/AbstractMailWorker.cs new file mode 100644 index 0000000..5dab7b1 --- /dev/null +++ b/JewelryStore/JewelryStoreBusinessLogic/MailWorker/AbstractMailWorker.cs @@ -0,0 +1,94 @@ +using JewelryStoreContracts.BindingModels; +using JewelryStoreContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JewelryStoreBusinessLogic.MailWorker +{ + public abstract class AbstractMailWorker + { + protected string _mailLogin = string.Empty; + protected string _mailPassword = string.Empty; + protected string _smtpClientHost = string.Empty; + protected int _smtpClientPort; + protected string _popHost = string.Empty; + protected int _popPort; + private readonly IMessageInfoLogic _messageInfoLogic; + private readonly IClientLogic _clientLogic; + private readonly ILogger _logger; + + public AbstractMailWorker(ILogger logger, IMessageInfoLogic messageInfoLogic, IClientLogic clientLogic) + { + _logger = logger; + _messageInfoLogic = messageInfoLogic; + _clientLogic = clientLogic; + } + + public void MailConfig(MailConfigBindingModel config) + { + _mailLogin = config.MailLogin; + _mailPassword = config.MailPassword; + _smtpClientHost = config.SmtpClientHost; + _smtpClientPort = config.SmtpClientPort; + _popHost = config.PopHost; + _popPort = config.PopPort; + _logger.LogDebug("Config: {login}, {password}, {clientHost}, {clientPOrt}, {popHost}, {popPort}", _mailLogin, _mailPassword, _smtpClientHost, _smtpClientPort, _popHost, _popPort); + } + + public async void MailSendAsync(MailSendInfoBindingModel info) + { + if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword)) + { + return; + } + + if (string.IsNullOrEmpty(_smtpClientHost) || _smtpClientPort == 0) + { + return; + } + + if (string.IsNullOrEmpty(info.MailAddress) || string.IsNullOrEmpty(info.Subject) || string.IsNullOrEmpty(info.Text)) + { + return; + } + + _logger.LogDebug("Send Mail: {To}, {Subject}", info.MailAddress, info.Subject); + + await SendMailAsync(info); + } + + public async void MailCheck() + { + if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword)) + { + return; + } + + if (string.IsNullOrEmpty(_popHost) || _popPort == 0) + { + return; + } + + if (_messageInfoLogic == null) + { + return; + } + + var list = await ReceiveMailAsync(); + _logger.LogDebug("Check Mail: {Count} new mails", list.Count); + + foreach (var mail in list) + { + mail.ClientId = _clientLogic.ReadElement(new() { Email = mail.SenderName })?.Id; + _messageInfoLogic.Create(mail); + } + } + + protected abstract Task SendMailAsync(MailSendInfoBindingModel info); + protected abstract Task> ReceiveMailAsync(); + } +} diff --git a/JewelryStore/JewelryStoreBusinessLogic/MailWorker/MailKitWorker.cs b/JewelryStore/JewelryStoreBusinessLogic/MailWorker/MailKitWorker.cs new file mode 100644 index 0000000..52d4479 --- /dev/null +++ b/JewelryStore/JewelryStoreBusinessLogic/MailWorker/MailKitWorker.cs @@ -0,0 +1,82 @@ +using JewelryStoreContracts.BindingModels; +using JewelryStoreContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Mail; +using System.Net; +using System.Text; +using System.Threading.Tasks; +using MailKit.Net.Pop3; +using MailKit.Security; + +namespace JewelryStoreBusinessLogic.MailWorker +{ + public class MailKitWorker : AbstractMailWorker + { + public MailKitWorker(ILogger logger, IMessageInfoLogic messageInfoLogic, IClientLogic clientLogic) : base(logger, messageInfoLogic, clientLogic) { } + + protected override async Task SendMailAsync(MailSendInfoBindingModel info) + { + using var objMailMessage = new MailMessage(); + using var objSmtpClient = new SmtpClient(_smtpClientHost, _smtpClientPort); + + try + { + objMailMessage.From = new MailAddress(_mailLogin); + objMailMessage.To.Add(new MailAddress(info.MailAddress)); + objMailMessage.Subject = info.Subject; + objMailMessage.Body = info.Text; + objMailMessage.SubjectEncoding = Encoding.UTF8; + objMailMessage.BodyEncoding = Encoding.UTF8; + objSmtpClient.UseDefaultCredentials = false; + objSmtpClient.EnableSsl = true; + objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; + objSmtpClient.Credentials = new NetworkCredential(_mailLogin, _mailPassword); + + await Task.Run(() => objSmtpClient.Send(objMailMessage)); + } + catch (Exception) + { + throw; + } + } + + protected override async Task> ReceiveMailAsync() + { + var list = new List(); + using var client = new Pop3Client(); + await Task.Run(() => + { + try + { + client.Connect(_popHost, _popPort, SecureSocketOptions.SslOnConnect); + client.Authenticate(_mailLogin, _mailPassword); + for (int i = 0; i < client.Count; i++) + { + var message = client.GetMessage(i); + foreach (var mail in message.From.Mailboxes) + { + list.Add(new MessageInfoBindingModel + { + DateDelivery = message.Date.DateTime, + MessageId = message.MessageId, + SenderName = mail.Address, + Subject = message.Subject, + Body = message.TextBody + }); + } + } + } + catch (AuthenticationException) + { } + finally + { + client.Disconnect(true); + } + }); + return list; + } + } +} diff --git a/JewelryStore/JewelryStoreClientApp/Controllers/HomeController.cs b/JewelryStore/JewelryStoreClientApp/Controllers/HomeController.cs index 998a6d0..0baf100 100644 --- a/JewelryStore/JewelryStoreClientApp/Controllers/HomeController.cs +++ b/JewelryStore/JewelryStoreClientApp/Controllers/HomeController.cs @@ -146,5 +146,15 @@ namespace JewelryStoreClientApp.Controllers ); 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}")); + } } } diff --git a/JewelryStore/JewelryStoreClientApp/Views/Home/Mails.cshtml b/JewelryStore/JewelryStoreClientApp/Views/Home/Mails.cshtml new file mode 100644 index 0000000..8f12a1d --- /dev/null +++ b/JewelryStore/JewelryStoreClientApp/Views/Home/Mails.cshtml @@ -0,0 +1,54 @@ +@using JewelryStoreContracts.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/JewelryStore/JewelryStoreClientApp/Views/Shared/_Layout.cshtml b/JewelryStore/JewelryStoreClientApp/Views/Shared/_Layout.cshtml index a675fee..a580739 100644 --- a/JewelryStore/JewelryStoreClientApp/Views/Shared/_Layout.cshtml +++ b/JewelryStore/JewelryStoreClientApp/Views/Shared/_Layout.cshtml @@ -12,23 +12,26 @@