From 58b5d6045204e1d492fb85207225e2d94917fe5b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=B0=D0=BA=D1=81=D0=B8=D0=BC=20=D0=9A=D1=83=D0=BA?= =?UTF-8?q?=D0=BB=D0=B5=D0=B2?= Date: Sun, 19 May 2024 10:10:11 +0400 Subject: [PATCH] =?UTF-8?q?=D0=B7=D0=B0=D0=B3=D1=80=D1=83=D0=B7=D0=B8?= =?UTF-8?q?=D0=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- SoftwareInstallation/App.config | 11 + SoftwareInstallation/FormComponents.cs | 1 + SoftwareInstallation/FormMain.Designer.cs | 23 +- SoftwareInstallation/FormMain.cs | 11 + SoftwareInstallation/FormPackage.cs | 1 + SoftwareInstallation/FormPackages.cs | 1 + SoftwareInstallation/FormViewMail.Designer.cs | 62 +++++ SoftwareInstallation/FormViewMail.cs | 48 ++++ SoftwareInstallation/FormViewMail.resx | 120 +++++++++ SoftwareInstallation/Program.cs | 82 +++++-- .../BusinessLogics/ClientLogic.cs | 13 +- .../BusinessLogics/MessageInfoLogic.cs | 43 ++++ .../BusinessLogics/OrderLogic.cs | 37 ++- .../MailWorker/AbstractMailWorker.cs | 86 +++++++ .../MailWorker/MailKitWorker.cs | 85 +++++++ .../Controllers/HomeController.cs | 15 +- .../SoftwareInstallationClientApp.csproj | 4 + .../Views/Home/Mails.cshtml | 54 +++++ .../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 ++++ ... 20240515171640_InitialCreate.Designer.cs} | 41 +++- ...ate.cs => 20240515171640_InitialCreate.cs} | 29 +++ ...ftwareInstallationDataBaseModelSnapshot.cs | 39 +++ .../Models/MessageInfo.cs | 53 ++++ .../SoftwareInstallationDataBase.cs | 5 +- .../DataListSingleton.cs | 8 +- .../Implements/ImplementerStorage.cs | 103 ++++++++ .../Implements/OrderStorage.cs | 229 +++++++++--------- .../Models/Implementer.cs | 54 +++++ .../Models/Order.cs | 10 +- SoftwareInstallationRestAP/Program.cs | 25 ++ SoftwareInstallationRestAP/appsettings.json | 9 +- 39 files changed, 1330 insertions(+), 164 deletions(-) create mode 100644 SoftwareInstallation/App.config create mode 100644 SoftwareInstallation/FormViewMail.Designer.cs create mode 100644 SoftwareInstallation/FormViewMail.cs create mode 100644 SoftwareInstallation/FormViewMail.resx create mode 100644 SoftwareInstallationBusinessLogic/BusinessLogics/MessageInfoLogic.cs create mode 100644 SoftwareInstallationBusinessLogic/MailWorker/AbstractMailWorker.cs create mode 100644 SoftwareInstallationBusinessLogic/MailWorker/MailKitWorker.cs create mode 100644 SoftwareInstallationClientApp/Views/Home/Mails.cshtml create mode 100644 SoftwareInstallationContracts/BindingModels/MailConfigBindingModel.cs create mode 100644 SoftwareInstallationContracts/BindingModels/MailSendInfoBingingModel.cs create mode 100644 SoftwareInstallationContracts/BindingModels/MessageInfoBindingModel.cs create mode 100644 SoftwareInstallationContracts/BusinessLogicsContracts/IMessageInfoLogic.cs create mode 100644 SoftwareInstallationContracts/SearchModels/MessageInfoSearchModel.cs create mode 100644 SoftwareInstallationContracts/StoragesContracts/IMessageInfoStorage.cs create mode 100644 SoftwareInstallationContracts/ViewModels/MessageInfoViewModel.cs create mode 100644 SoftwareInstallationDataModels/Models/IMessageInfoModel.cs create mode 100644 SoftwareInstallationDatabaseImplement/Implements/MessageInfoStorage.cs rename SoftwareInstallationDatabaseImplement/Migrations/{20240502175831_InitialCreate.Designer.cs => 20240515171640_InitialCreate.Designer.cs} (86%) rename SoftwareInstallationDatabaseImplement/Migrations/{20240502175831_InitialCreate.cs => 20240515171640_InitialCreate.cs} (85%) create mode 100644 SoftwareInstallationDatabaseImplement/Models/MessageInfo.cs create mode 100644 SoftwareInstallationListImplement/Implements/ImplementerStorage.cs create mode 100644 SoftwareInstallationListImplement/Models/Implementer.cs diff --git a/SoftwareInstallation/App.config b/SoftwareInstallation/App.config new file mode 100644 index 0000000..3cfa452 --- /dev/null +++ b/SoftwareInstallation/App.config @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/SoftwareInstallation/FormComponents.cs b/SoftwareInstallation/FormComponents.cs index c39d1e7..c5b0764 100644 --- a/SoftwareInstallation/FormComponents.cs +++ b/SoftwareInstallation/FormComponents.cs @@ -1,4 +1,5 @@ using Microsoft.Extensions.Logging; +using SoftwareInstallation.Forms; using SoftwareInstallationContracts.BindingModels; using SoftwareInstallationContracts.BusinessLogicsContracts; using System; diff --git a/SoftwareInstallation/FormMain.Designer.cs b/SoftwareInstallation/FormMain.Designer.cs index 0afadc6..825a64e 100644 --- a/SoftwareInstallation/FormMain.Designer.cs +++ b/SoftwareInstallation/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/SoftwareInstallation/FormMain.cs b/SoftwareInstallation/FormMain.cs index ab4935e..7a8cb12 100644 --- a/SoftwareInstallation/FormMain.cs +++ b/SoftwareInstallation/FormMain.cs @@ -221,5 +221,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/SoftwareInstallation/FormPackage.cs b/SoftwareInstallation/FormPackage.cs index 74db5c8..969bf1d 100644 --- a/SoftwareInstallation/FormPackage.cs +++ b/SoftwareInstallation/FormPackage.cs @@ -1,4 +1,5 @@ using Microsoft.Extensions.Logging; +using SoftwareInstallation.Forms; using SoftwareInstallationContracts.BindingModels; using SoftwareInstallationContracts.BusinessLogicsContracts; using SoftwareInstallationContracts.SearchModels; diff --git a/SoftwareInstallation/FormPackages.cs b/SoftwareInstallation/FormPackages.cs index 0bd8473..fc2dd7c 100644 --- a/SoftwareInstallation/FormPackages.cs +++ b/SoftwareInstallation/FormPackages.cs @@ -1,4 +1,5 @@ using Microsoft.Extensions.Logging; +using SoftwareInstallation.Forms; using SoftwareInstallationContracts.BindingModels; using SoftwareInstallationContracts.BusinessLogicsContracts; using System; diff --git a/SoftwareInstallation/FormViewMail.Designer.cs b/SoftwareInstallation/FormViewMail.Designer.cs new file mode 100644 index 0000000..8c8709b --- /dev/null +++ b/SoftwareInstallation/FormViewMail.Designer.cs @@ -0,0 +1,62 @@ +namespace SoftwareInstallation.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/SoftwareInstallation/FormViewMail.cs b/SoftwareInstallation/FormViewMail.cs new file mode 100644 index 0000000..84cc280 --- /dev/null +++ b/SoftwareInstallation/FormViewMail.cs @@ -0,0 +1,48 @@ +using SoftwareInstallationContracts.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 SoftwareInstallation.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/SoftwareInstallation/FormViewMail.resx b/SoftwareInstallation/FormViewMail.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/SoftwareInstallation/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/SoftwareInstallation/Program.cs b/SoftwareInstallation/Program.cs index 65599ed..49b9279 100644 --- a/SoftwareInstallation/Program.cs +++ b/SoftwareInstallation/Program.cs @@ -1,16 +1,17 @@ +using SoftwareInstallationContracts.BusinessLogicsContracts; +using SoftwareInstallationBusinessLogic.BusinessLogic; +using SoftwareInstallationContracts.StoragesContracts; +using SoftwareInstallationDatabaseImplement.Implements; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; -using SoftwareInstallationBusinessLogic.BusinessLogic; using SoftwareInstallationBusinessLogic.OfficePackage.Implements; using SoftwareInstallationBusinessLogic.OfficePackage; -using SoftwareInstallationContracts.BusinessLogicsContracts; -using SoftwareInstallationContracts.StoragesContracts; -using SoftwareInstallationDatabaseImplement.Implements; -using System; -using SoftwareInstallation.Forms; +using SoftwareInstallationBusinessLogic.MailWorker; +using SoftwareInstallationContracts.BindingModels; +using SoftwareInstallationView; -namespace SoftwareInstallationView +namespace SoftwareInstallation.Forms { internal static class Program { @@ -28,6 +29,38 @@ namespace SoftwareInstallationView 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()); } private static void ConfigureServices(ServiceCollection services) @@ -37,24 +70,21 @@ namespace SoftwareInstallationView option.SetMinimumLevel(LogLevel.Information); option.AddNLog("nlog.config"); }); - 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.AddTransient(); - - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -65,11 +95,17 @@ namespace SoftwareInstallationView services.AddTransient(); services.AddTransient(); services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); + 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/SoftwareInstallationBusinessLogic/BusinessLogics/ClientLogic.cs b/SoftwareInstallationBusinessLogic/BusinessLogics/ClientLogic.cs index c39edc8..c07ab1b 100644 --- a/SoftwareInstallationBusinessLogic/BusinessLogics/ClientLogic.cs +++ b/SoftwareInstallationBusinessLogic/BusinessLogics/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 SoftwareInstallationBusinessLogic.BusinessLogic { @@ -102,14 +103,22 @@ namespace SoftwareInstallationBusinessLogic.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)); } - _logger.LogInformation("Client. ClientFIO:{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/SoftwareInstallationBusinessLogic/BusinessLogics/MessageInfoLogic.cs b/SoftwareInstallationBusinessLogic/BusinessLogics/MessageInfoLogic.cs new file mode 100644 index 0000000..ffb8538 --- /dev/null +++ b/SoftwareInstallationBusinessLogic/BusinessLogics/MessageInfoLogic.cs @@ -0,0 +1,43 @@ +using SoftwareInstallationContracts.BindingModels; +using SoftwareInstallationContracts.BusinessLogicsContracts; +using SoftwareInstallationContracts.SearchModels; +using SoftwareInstallationContracts.StoragesContracts; +using SoftwareInstallationContracts.ViewModels; +using Microsoft.Extensions.Logging; + +namespace SoftwareInstallationBusinessLogic.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/SoftwareInstallationBusinessLogic/BusinessLogics/OrderLogic.cs b/SoftwareInstallationBusinessLogic/BusinessLogics/OrderLogic.cs index d82c6be..d46800f 100644 --- a/SoftwareInstallationBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/SoftwareInstallationBusinessLogic/BusinessLogics/OrderLogic.cs @@ -10,7 +10,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; - +using SoftwareInstallationBusinessLogic.MailWorker; namespace SoftwareInstallationBusinessLogic.BusinessLogic { @@ -18,12 +18,16 @@ namespace SoftwareInstallationBusinessLogic.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) @@ -63,12 +67,14 @@ namespace SoftwareInstallationBusinessLogic.BusinessLogic if (model.Status != OrderStatus.Неизвестен) return false; model.Status = OrderStatus.Принят; - - if (_orderStorage.Insert(model) == null) + + var res = _orderStorage.Insert(model); + if (res == null) { _logger.LogWarning("Insert operation failed"); return false; } + SendOrderStatusMail(model.ClientId, $"Изменен статус заказа #{res.Id}", $"Заказ #{res.Id} изменен статус на {model.Status}"); return true; } @@ -108,7 +114,13 @@ namespace SoftwareInstallationBusinessLogic.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; } @@ -132,5 +144,20 @@ namespace SoftwareInstallationBusinessLogic.BusinessLogic } _logger.LogInformation("Software. SoftwareId:{SoftwareId}.Count:{Count}.Sum:{Sum}Id:{Id}", model.SoftwareId, 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/SoftwareInstallationBusinessLogic/MailWorker/AbstractMailWorker.cs b/SoftwareInstallationBusinessLogic/MailWorker/AbstractMailWorker.cs new file mode 100644 index 0000000..31485fe --- /dev/null +++ b/SoftwareInstallationBusinessLogic/MailWorker/AbstractMailWorker.cs @@ -0,0 +1,86 @@ +using SoftwareInstallationContracts.BindingModels; +using SoftwareInstallationContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +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/SoftwareInstallationBusinessLogic/MailWorker/MailKitWorker.cs b/SoftwareInstallationBusinessLogic/MailWorker/MailKitWorker.cs new file mode 100644 index 0000000..8dbff7c --- /dev/null +++ b/SoftwareInstallationBusinessLogic/MailWorker/MailKitWorker.cs @@ -0,0 +1,85 @@ +using SoftwareInstallationContracts.BindingModels; +using SoftwareInstallationContracts.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 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) + { } + finally + { + client.Disconnect(true); + } + }); + return list; + } + } +} diff --git a/SoftwareInstallationClientApp/Controllers/HomeController.cs b/SoftwareInstallationClientApp/Controllers/HomeController.cs index 328bc95..1ba77e1 100644 --- a/SoftwareInstallationClientApp/Controllers/HomeController.cs +++ b/SoftwareInstallationClientApp/Controllers/HomeController.cs @@ -115,7 +115,8 @@ namespace SoftwareInstallationClientApp.Controllers [HttpGet] public IActionResult Create() { - ViewBag.Softwares = + var res = APIClient.GetRequest>("api/main/getSoftwarelist"); + ViewBag.Softwares = APIClient.GetRequest>("api/main/getSoftwarelist"); return View(); } @@ -148,5 +149,15 @@ namespace SoftwareInstallationClientApp.Controllers ); return Math.Round(count * (_Software?.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/SoftwareInstallationClientApp/SoftwareInstallationClientApp.csproj b/SoftwareInstallationClientApp/SoftwareInstallationClientApp.csproj index 39f3a5c..ebccd81 100644 --- a/SoftwareInstallationClientApp/SoftwareInstallationClientApp.csproj +++ b/SoftwareInstallationClientApp/SoftwareInstallationClientApp.csproj @@ -10,6 +10,10 @@ + + + + diff --git a/SoftwareInstallationClientApp/Views/Home/Mails.cshtml b/SoftwareInstallationClientApp/Views/Home/Mails.cshtml new file mode 100644 index 0000000..5a41e0c --- /dev/null +++ b/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/SoftwareInstallationContracts/BindingModels/MailConfigBindingModel.cs b/SoftwareInstallationContracts/BindingModels/MailConfigBindingModel.cs new file mode 100644 index 0000000..2a19212 --- /dev/null +++ b/SoftwareInstallationContracts/BindingModels/MailConfigBindingModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SoftwareInstallationContracts.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/SoftwareInstallationContracts/BindingModels/MailSendInfoBingingModel.cs b/SoftwareInstallationContracts/BindingModels/MailSendInfoBingingModel.cs new file mode 100644 index 0000000..8a05240 --- /dev/null +++ b/SoftwareInstallationContracts/BindingModels/MailSendInfoBingingModel.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SoftwareInstallationContracts.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/SoftwareInstallationContracts/BindingModels/MessageInfoBindingModel.cs b/SoftwareInstallationContracts/BindingModels/MessageInfoBindingModel.cs new file mode 100644 index 0000000..b9f6582 --- /dev/null +++ b/SoftwareInstallationContracts/BindingModels/MessageInfoBindingModel.cs @@ -0,0 +1,24 @@ +using SoftwareInstallationDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SoftwareInstallationContracts.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/SoftwareInstallationContracts/BusinessLogicsContracts/IMessageInfoLogic.cs b/SoftwareInstallationContracts/BusinessLogicsContracts/IMessageInfoLogic.cs new file mode 100644 index 0000000..bfa39ed --- /dev/null +++ b/SoftwareInstallationContracts/BusinessLogicsContracts/IMessageInfoLogic.cs @@ -0,0 +1,13 @@ +using SoftwareInstallationContracts.BindingModels; +using SoftwareInstallationContracts.SearchModels; +using SoftwareInstallationContracts.ViewModels; + +namespace SoftwareInstallationContracts.BusinessLogicsContracts +{ + public interface IMessageInfoLogic + { + List? ReadList(MessageInfoSearchModel? model); + + bool Create(MessageInfoBindingModel model); + } +} \ No newline at end of file diff --git a/SoftwareInstallationContracts/SearchModels/MessageInfoSearchModel.cs b/SoftwareInstallationContracts/SearchModels/MessageInfoSearchModel.cs new file mode 100644 index 0000000..a3605a6 --- /dev/null +++ b/SoftwareInstallationContracts/SearchModels/MessageInfoSearchModel.cs @@ -0,0 +1,9 @@ +namespace SoftwareInstallationContracts.SearchModels +{ + public class MessageInfoSearchModel + { + public int? ClientId { get; set; } + + public string? MessageId { get; set; } + } +} \ No newline at end of file diff --git a/SoftwareInstallationContracts/StoragesContracts/IMessageInfoStorage.cs b/SoftwareInstallationContracts/StoragesContracts/IMessageInfoStorage.cs new file mode 100644 index 0000000..e6b2c2c --- /dev/null +++ b/SoftwareInstallationContracts/StoragesContracts/IMessageInfoStorage.cs @@ -0,0 +1,17 @@ +using SoftwareInstallationContracts.BindingModels; +using SoftwareInstallationContracts.SearchModels; +using SoftwareInstallationContracts.ViewModels; + +namespace SoftwareInstallationContracts.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/SoftwareInstallationContracts/ViewModels/MessageInfoViewModel.cs b/SoftwareInstallationContracts/ViewModels/MessageInfoViewModel.cs new file mode 100644 index 0000000..9481530 --- /dev/null +++ b/SoftwareInstallationContracts/ViewModels/MessageInfoViewModel.cs @@ -0,0 +1,24 @@ +using SoftwareInstallationDataModels.Models; +using System.ComponentModel; + +namespace SoftwareInstallationContracts.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/SoftwareInstallationDataModels/Models/IMessageInfoModel.cs b/SoftwareInstallationDataModels/Models/IMessageInfoModel.cs new file mode 100644 index 0000000..53858e4 --- /dev/null +++ b/SoftwareInstallationDataModels/Models/IMessageInfoModel.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SoftwareInstallationDataModels.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/SoftwareInstallationDatabaseImplement/Implements/MessageInfoStorage.cs b/SoftwareInstallationDatabaseImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..56a0fb1 --- /dev/null +++ b/SoftwareInstallationDatabaseImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,52 @@ +using SoftwareInstallationContracts.BindingModels; +using SoftwareInstallationContracts.SearchModels; +using SoftwareInstallationContracts.StoragesContracts; +using SoftwareInstallationContracts.ViewModels; +using SoftwareInstallationDatabaseImplement.Models; + +namespace SoftwareInstallationDatabaseImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + using var context = new SoftwareInstallationDataBase(); + 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 SoftwareInstallationDataBase(); + return context.Messages + .Where(x => x.ClientId == model.ClientId) + .Select(x => x.GetViewModel) + .ToList(); + } + + public List GetFullList() + { + using var context = new SoftwareInstallationDataBase(); + return context.Messages + .Select(x => x.GetViewModel) + .ToList(); + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + using var context = new SoftwareInstallationDataBase(); + 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/SoftwareInstallationDatabaseImplement/Migrations/20240502175831_InitialCreate.Designer.cs b/SoftwareInstallationDatabaseImplement/Migrations/20240515171640_InitialCreate.Designer.cs similarity index 86% rename from SoftwareInstallationDatabaseImplement/Migrations/20240502175831_InitialCreate.Designer.cs rename to SoftwareInstallationDatabaseImplement/Migrations/20240515171640_InitialCreate.Designer.cs index e1eb745..97db298 100644 --- a/SoftwareInstallationDatabaseImplement/Migrations/20240502175831_InitialCreate.Designer.cs +++ b/SoftwareInstallationDatabaseImplement/Migrations/20240515171640_InitialCreate.Designer.cs @@ -12,7 +12,7 @@ using SoftwareInstallationDatabaseImplement; namespace SoftwareInstallationDatabaseImplement.Migrations { [DbContext(typeof(SoftwareInstallationDataBase))] - [Migration("20240502175831_InitialCreate")] + [Migration("20240515171640_InitialCreate")] partial class InitialCreate { /// @@ -97,6 +97,36 @@ namespace SoftwareInstallationDatabaseImplement.Migrations b.ToTable("Implementers"); }); + modelBuilder.Entity("SoftwareInstallationDatabaseImplement.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("SoftwareInstallationDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -186,6 +216,15 @@ namespace SoftwareInstallationDatabaseImplement.Migrations b.ToTable("Softwares"); }); + modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.MessageInfo", b => + { + b.HasOne("SoftwareInstallationDatabaseImplement.Models.Client", "Client") + .WithMany() + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.Order", b => { b.HasOne("SoftwareInstallationDatabaseImplement.Models.Client", "Client") diff --git a/SoftwareInstallationDatabaseImplement/Migrations/20240502175831_InitialCreate.cs b/SoftwareInstallationDatabaseImplement/Migrations/20240515171640_InitialCreate.cs similarity index 85% rename from SoftwareInstallationDatabaseImplement/Migrations/20240502175831_InitialCreate.cs rename to SoftwareInstallationDatabaseImplement/Migrations/20240515171640_InitialCreate.cs index e389401..1cf519f 100644 --- a/SoftwareInstallationDatabaseImplement/Migrations/20240502175831_InitialCreate.cs +++ b/SoftwareInstallationDatabaseImplement/Migrations/20240515171640_InitialCreate.cs @@ -70,6 +70,27 @@ namespace SoftwareInstallationDatabaseImplement.Migrations table.PrimaryKey("PK_Softwares", 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 SoftwareInstallationDatabaseImplement.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 SoftwareInstallationDatabaseImplement.Migrations /// protected override void Down(MigrationBuilder migrationBuilder) { + migrationBuilder.DropTable( + name: "Messages"); + migrationBuilder.DropTable( name: "Orders"); diff --git a/SoftwareInstallationDatabaseImplement/Migrations/SoftwareInstallationDataBaseModelSnapshot.cs b/SoftwareInstallationDatabaseImplement/Migrations/SoftwareInstallationDataBaseModelSnapshot.cs index d6b1ff3..76425d1 100644 --- a/SoftwareInstallationDatabaseImplement/Migrations/SoftwareInstallationDataBaseModelSnapshot.cs +++ b/SoftwareInstallationDatabaseImplement/Migrations/SoftwareInstallationDataBaseModelSnapshot.cs @@ -94,6 +94,36 @@ namespace SoftwareInstallationDatabaseImplement.Migrations b.ToTable("Implementers"); }); + modelBuilder.Entity("SoftwareInstallationDatabaseImplement.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("SoftwareInstallationDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -183,6 +213,15 @@ namespace SoftwareInstallationDatabaseImplement.Migrations b.ToTable("Softwares"); }); + modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.MessageInfo", b => + { + b.HasOne("SoftwareInstallationDatabaseImplement.Models.Client", "Client") + .WithMany() + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.Order", b => { b.HasOne("SoftwareInstallationDatabaseImplement.Models.Client", "Client") diff --git a/SoftwareInstallationDatabaseImplement/Models/MessageInfo.cs b/SoftwareInstallationDatabaseImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..8370339 --- /dev/null +++ b/SoftwareInstallationDatabaseImplement/Models/MessageInfo.cs @@ -0,0 +1,53 @@ +using SoftwareInstallationContracts.BindingModels; +using SoftwareInstallationContracts.ViewModels; +using SoftwareInstallationDataModels.Models; +using System.ComponentModel.DataAnnotations; + +namespace SoftwareInstallationDatabaseImplement.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(SoftwareInstallationDataBase 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/SoftwareInstallationDatabaseImplement/SoftwareInstallationDataBase.cs b/SoftwareInstallationDatabaseImplement/SoftwareInstallationDataBase.cs index c303428..51dff52 100644 --- a/SoftwareInstallationDatabaseImplement/SoftwareInstallationDataBase.cs +++ b/SoftwareInstallationDatabaseImplement/SoftwareInstallationDataBase.cs @@ -16,7 +16,7 @@ optionsBuilder) { if (optionsBuilder.IsConfigured == false) { - optionsBuilder.UseSqlServer(@"Data Source=LAPTOP-952S2NGN;Initial Catalog=SOFT;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True"); + optionsBuilder.UseSqlServer(@"Data Source=LAPTOP-952S2NGN;Initial Catalog=SS;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True"); } base.OnConfiguring(optionsBuilder); } @@ -26,5 +26,6 @@ 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/SoftwareInstallationListImplement/DataListSingleton.cs b/SoftwareInstallationListImplement/DataListSingleton.cs index 1fa200e..be60d14 100644 --- a/SoftwareInstallationListImplement/DataListSingleton.cs +++ b/SoftwareInstallationListImplement/DataListSingleton.cs @@ -14,14 +14,16 @@ namespace SoftwareInstallationListImplement public List Orders { get; set; } public List Softwares { get; set; } public List Clients { get; set; } - private DataListSingleton() + public List Implementers { get; set; } + private DataListSingleton() { Components = new List(); Orders = new List(); Softwares = new List(); Clients = new List(); - } - public static DataListSingleton GetInstance() + Implementers = new List(); + } + public static DataListSingleton GetInstance() { if (_instance == null) { diff --git a/SoftwareInstallationListImplement/Implements/ImplementerStorage.cs b/SoftwareInstallationListImplement/Implements/ImplementerStorage.cs new file mode 100644 index 0000000..8cde476 --- /dev/null +++ b/SoftwareInstallationListImplement/Implements/ImplementerStorage.cs @@ -0,0 +1,103 @@ +using SoftwareInstallationContracts.BindingModels; +using SoftwareInstallationContracts.SearchModels; +using SoftwareInstallationContracts.StoragesContracts; +using SoftwareInstallationContracts.ViewModels; +using SoftwareInstallationListImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SoftwareInstallationListImplement.Implements +{ + public class ImplementerStorage : IImplementerStorage + { + private readonly DataListSingleton _source; + public ImplementerStorage() + { + _source = DataListSingleton.GetInstance(); + } + public List GetFullList() + { + var result = new List(); + foreach (var implementer in _source.Implementers) + { + result.Add(implementer.GetViewModel); + } + return result; + } + public List GetFilteredList(ImplementerSearchModel + model) + { + var result = new List(); + if (string.IsNullOrEmpty(model.ImplementerFIO) && string.IsNullOrEmpty(model.Password)) + { + return result; + } + foreach (var implementer in _source.Implementers) + { + if (implementer.ImplementerFIO.Contains(model.ImplementerFIO)) + { + result.Add(implementer.GetViewModel); + } + } + return result; + } + public ImplementerViewModel? GetElement(ImplementerSearchModel model) + { + foreach (var implementer in _source.Implementers) + { + if ((string.IsNullOrEmpty(model.ImplementerFIO) || implementer.ImplementerFIO == model.ImplementerFIO) && + (!model.Id.HasValue || implementer.Id == model.Id) && (string.IsNullOrEmpty(model.Password) || implementer.Password == model.Password)) + { + return implementer.GetViewModel; + } + } + return null; + } + public ImplementerViewModel? Insert(ImplementerBindingModel model) + { + model.Id = 1; + foreach (var implementer in _source.Implementers) + { + if (model.Id <= implementer.Id) + { + model.Id = implementer.Id + 1; + } + } + var newImplementer = Implementer.Create(model); + if (newImplementer == null) + { + return null; + } + _source.Implementers.Add(newImplementer); + return newImplementer.GetViewModel; + } + public ImplementerViewModel? Update(ImplementerBindingModel model) + { + foreach (var implementer in _source.Implementers) + { + if (model.Id == implementer.Id) + { + implementer.Update(model); + return implementer.GetViewModel; + } + } + return null; + } + public ImplementerViewModel? Delete(ImplementerBindingModel model) + { + for (int i = 0; i < _source.Implementers.Count; ++i) + { + if (_source.Implementers[i].Id == model.Id) + { + var element = _source.Implementers[i]; + _source.Implementers.RemoveAt(i); + return element.GetViewModel; + } + } + return null; + } + } +} diff --git a/SoftwareInstallationListImplement/Implements/OrderStorage.cs b/SoftwareInstallationListImplement/Implements/OrderStorage.cs index 46b57ef..2807938 100644 --- a/SoftwareInstallationListImplement/Implements/OrderStorage.cs +++ b/SoftwareInstallationListImplement/Implements/OrderStorage.cs @@ -1,126 +1,125 @@ - -using SoftwareInstallationContracts.BindingModels; +using SoftwareInstallationContracts.BindingModels; using SoftwareInstallationContracts.SearchModels; using SoftwareInstallationContracts.StoragesContracts; using SoftwareInstallationContracts.ViewModels; using SoftwareInstallationListImplement.Models; -using SoftwareInstallationListImplement; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; namespace SoftwareInstallationListImplement.Implements { - public class OrderStorage : IOrderStorage - { - private readonly DataListSingleton _source; - public OrderStorage() - { - _source = DataListSingleton.GetInstance(); - } - public List GetFullList() - { - var result = new List(); - foreach (var order in _source.Orders) - { - result.Add(AccessSoftwareStorage(order.GetViewModel)); - } - return result; - } - public List GetFilteredList(OrderSearchModel - model) - { - var result = new List(); - foreach (var order in _source.Orders) - { - if ((!model.Id.HasValue || order.Id == model.Id) && - (!model.DateFrom.HasValue || order.DateCreate >= model.DateFrom) && - (!model.DateTo.HasValue || order.DateCreate <= model.DateTo) && - (!model.ClientId.HasValue || order.ClientId == model.ClientId)) ; - { - result.Add(AccessSoftwareStorage(order.GetViewModel)); - } - } - return result; - } - public OrderViewModel? GetElement(OrderSearchModel model) - { - if (!model.Id.HasValue) - { - return null; - } - foreach (var order in _source.Orders) - { - if (model.Id.HasValue && order.Id == model.Id) - { - return order.GetViewModel; - } - } - return null; - } - public OrderViewModel? Insert(OrderBindingModel model) - { - model.Id = 1; - foreach (var order in _source.Orders) - { - if (model.Id <= order.Id) - { - model.Id = order.Id + 1; - } - } - var newOrder = Order.Create(model); - if (newOrder == null) - { - return null; - } - _source.Orders.Add(newOrder); - return newOrder.GetViewModel; - } - public OrderViewModel? Update(OrderBindingModel model) - { - foreach (var order in _source.Orders) - { - if (order.Id == model.Id) - { - order.Update(model); - return order.GetViewModel; - } - } - return null; - } - public OrderViewModel? Delete(OrderBindingModel model) - { - for (int i = 0; i < _source.Orders.Count; ++i) - { - if (_source.Orders[i].Id == model.Id) - { - var element = _source.Orders[i]; - _source.Orders.RemoveAt(i); - return element.GetViewModel; - } - } - return null; - } + public class OrderStorage : IOrderStorage + { + private readonly DataListSingleton _source; + public OrderStorage() + { + _source = DataListSingleton.GetInstance(); + } + public List GetFullList() + { + var result = new List(); + foreach (var order in _source.Orders) + { + result.Add(AccessStorage(order.GetViewModel)); + } + return result; + } + public List GetFilteredList(OrderSearchModel + model) + { + var result = new List(); + foreach (var order in _source.Orders) + { + if ((!model.Id.HasValue || order.Id == model.Id) && + (!model.DateFrom.HasValue || order.DateCreate >= model.DateFrom) && + (!model.DateTo.HasValue || order.DateCreate <= model.DateTo) && + (!model.ClientId.HasValue || order.ClientId == model.ClientId)) ; + { + result.Add(AccessStorage(order.GetViewModel)); + } + } + return result; + } + public OrderViewModel? GetElement(OrderSearchModel model) + { + if (!model.Id.HasValue) + { + return null; + } + foreach (var order in _source.Orders) + { + if ((model.Id.HasValue && order.Id == model.Id) || + (model.ImplementerId.HasValue && model.Status.HasValue && + order.ImplementerId == model.ImplementerId && order.Status == model.Status)) + { + return AccessStorage(order.GetViewModel); + } + } + return null; + } + public OrderViewModel? Insert(OrderBindingModel model) + { + model.Id = 1; + foreach (var order in _source.Orders) + { + if (model.Id <= order.Id) + { + model.Id = order.Id + 1; + } + } + var newOrder = Order.Create(model); + if (newOrder == null) + { + return null; + } + _source.Orders.Add(newOrder); + return newOrder.GetViewModel; + } + public OrderViewModel? Update(OrderBindingModel model) + { + foreach (var order in _source.Orders) + { + if (order.Id == model.Id) + { + order.Update(model); + return order.GetViewModel; + } + } + return null; + } + public OrderViewModel? Delete(OrderBindingModel model) + { + for (int i = 0; i < _source.Orders.Count; ++i) + { + if (_source.Orders[i].Id == model.Id) + { + var element = _source.Orders[i]; + _source.Orders.RemoveAt(i); + return element.GetViewModel; + } + } + return null; + } - public OrderViewModel AccessSoftwareStorage(OrderViewModel model) - { - foreach (var Software in _source.Softwares) - { - if (Software.Id == model.SoftwareId) - { - model.SoftwareName = Software.SoftwareName; - break; - } - } - return model; - } + public OrderViewModel AccessStorage(OrderViewModel model) + { + if (model == null) + return null; + var travel = _source.Softwares.FirstOrDefault(x => x.Id == model.Id); + var client = _source.Clients.FirstOrDefault(x => x.Id == model.Id); + var implementer = _source.Implementers.FirstOrDefault(x => x.Id == model.ImplementerId); + if (travel != null) + model.SoftwareName = travel.SoftwareName; + if (client != null) + model.ClientFIO = client.ClientFIO; + if (implementer != null) + model.ImplementerFIO = implementer.ImplementerFIO; + return model; + } - public OrderViewModel AccessClientStorage(OrderViewModel model) - { - var client = _source.Clients.FirstOrDefault(x => x.Id == model.ClientId); - if (client != null) - model.ClientFIO = client.ClientFIO; - return model; - } - - - } + } } diff --git a/SoftwareInstallationListImplement/Models/Implementer.cs b/SoftwareInstallationListImplement/Models/Implementer.cs new file mode 100644 index 0000000..5698620 --- /dev/null +++ b/SoftwareInstallationListImplement/Models/Implementer.cs @@ -0,0 +1,54 @@ +using SoftwareInstallationContracts.BindingModels; +using SoftwareInstallationContracts.ViewModels; +using SoftwareInstallationDataModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SoftwareInstallationListImplement.Models +{ + public class Implementer : IImplementerModel + { + public int Id { get; private set; } + public string ImplementerFIO { get; private set; } = string.Empty; + public string Password { get; set; } = string.Empty; + public int WorkExperience { get; set; } = 0; + public int Qualification { get; set; } = 0; + public static Implementer? Create(ImplementerBindingModel model) + { + if (model == null) + { + return null; + } + return new Implementer() + { + Id = model.Id, + ImplementerFIO = model.ImplementerFIO, + Password = model.Password, + WorkExperience = model.WorkExperience, + Qualification = model.Qualification + }; + } + public void Update(ImplementerBindingModel model) + { + if (model == null) + { + return; + } + ImplementerFIO = model.ImplementerFIO; + Password = model.Password; + WorkExperience = model.WorkExperience; + Qualification = model.Qualification; + } + public ImplementerViewModel GetViewModel => new() + { + Id = Id, + ImplementerFIO = ImplementerFIO, + Password = Password, + WorkExperience = WorkExperience, + Qualification = Qualification + }; + } +} diff --git a/SoftwareInstallationListImplement/Models/Order.cs b/SoftwareInstallationListImplement/Models/Order.cs index 38b4bcc..1adf711 100644 --- a/SoftwareInstallationListImplement/Models/Order.cs +++ b/SoftwareInstallationListImplement/Models/Order.cs @@ -11,7 +11,8 @@ namespace SoftwareInstallationListImplement.Models public int Id { get; private set; } public int SoftwareId { get; private set; } public int ClientId { get; private set; } - public int Count { get; private set; } + public int? ImplementerId { get; private set; } + public int Count { get; private set; } public double Sum { get; private set; } public OrderStatus Status { get; private set; } public DateTime DateCreate { get; private set; } @@ -31,6 +32,7 @@ namespace SoftwareInstallationListImplement.Models Sum = model.Sum, Status = model.Status, DateCreate = model.DateCreate, + ImplementerId = model.ImplementerId, DateImplement = model.DateImplement, }; } @@ -46,13 +48,15 @@ namespace SoftwareInstallationListImplement.Models Sum = model.Sum; Status = model.Status; DateCreate = model.DateCreate; - DateImplement = model.DateImplement; + ImplementerId = model.ImplementerId; + DateImplement = model.DateImplement; } public OrderViewModel GetViewModel => new() { Id = Id, SoftwareId = SoftwareId, - ClientId = ClientId, + ImplementerId = ImplementerId, + ClientId = ClientId, Count = Count, Sum = Sum, Status = Status, diff --git a/SoftwareInstallationRestAP/Program.cs b/SoftwareInstallationRestAP/Program.cs index bee9be2..622f6c3 100644 --- a/SoftwareInstallationRestAP/Program.cs +++ b/SoftwareInstallationRestAP/Program.cs @@ -3,6 +3,8 @@ using SoftwareInstallationContracts.BusinessLogicsContracts; using SoftwareInstallationContracts.StoragesContracts; using SoftwareInstallationDatabaseImplement.Implements; using Microsoft.OpenApi.Models; +using SoftwareInstallationBusinessLogic.MailWorker; +using SoftwareInstallationContracts.BindingModels; var builder = WebApplication.CreateBuilder(args); builder.Logging.SetMinimumLevel(LogLevel.Trace); builder.Logging.AddLog4Net("log4net.config"); @@ -10,9 +12,14 @@ 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 +34,24 @@ 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/SoftwareInstallationRestAP/appsettings.json b/SoftwareInstallationRestAP/appsettings.json index 10f68b8..99acf03 100644 --- a/SoftwareInstallationRestAP/appsettings.json +++ b/SoftwareInstallationRestAP/appsettings.json @@ -5,5 +5,12 @@ "Microsoft.AspNetCore": "Warning" } }, - "AllowedHosts": "*" + "AllowedHosts": "*", + "SmtpClientHost": "smtp.gmail.com", + "SmtpClientPort": "587", + "PopHost": "pop.gmail.com", + "PopPort": "995", + + "MailLogin": "kukleva92@gmail.com", + "MailPassword": "skpf kwgh rxpx yajp" }