diff --git a/SushiBar/SushiBar/App.config b/SushiBar/SushiBar/App.config new file mode 100644 index 0000000..a30a5cb --- /dev/null +++ b/SushiBar/SushiBar/App.config @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/SushiBar/SushiBar/FormMain.Designer.cs b/SushiBar/SushiBar/FormMain.Designer.cs index 292488a..773bf04 100644 --- a/SushiBar/SushiBar/FormMain.Designer.cs +++ b/SushiBar/SushiBar/FormMain.Designer.cs @@ -45,6 +45,7 @@ buttonSetToWork = new Button(); buttonCreateOrder = new Button(); dataGridView = new DataGridView(); + письмаToolStripMenuItem = new ToolStripMenuItem(); menuStrip.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); SuspendLayout(); @@ -68,41 +69,41 @@ // ингредиентыToolStripMenuItem // ингредиентыToolStripMenuItem.Name = "ингредиентыToolStripMenuItem"; - ингредиентыToolStripMenuItem.Size = new Size(180, 22); + ингредиентыToolStripMenuItem.Size = new Size(154, 22); ингредиентыToolStripMenuItem.Text = "Ингредиенты"; ингредиентыToolStripMenuItem.Click += IngredientsToolStripMenuItem_Click; // // сушиToolStripMenuItem // сушиToolStripMenuItem.Name = "сушиToolStripMenuItem"; - сушиToolStripMenuItem.Size = new Size(180, 22); + сушиToolStripMenuItem.Size = new Size(154, 22); сушиToolStripMenuItem.Text = "Суши"; сушиToolStripMenuItem.Click += SushiToolStripMenuItem_Click; // // клиентыToolStripMenuItem // клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; - клиентыToolStripMenuItem.Size = new Size(180, 22); + клиентыToolStripMenuItem.Size = new Size(154, 22); клиентыToolStripMenuItem.Text = "Клиенты"; клиентыToolStripMenuItem.Click += клиентыToolStripMenuItem_Click; // // исполнителиToolStripMenuItem // исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; - исполнителиToolStripMenuItem.Size = new Size(180, 22); + исполнителиToolStripMenuItem.Size = new Size(154, 22); исполнителиToolStripMenuItem.Text = "Исполнители"; исполнителиToolStripMenuItem.Click += employersToolStripMenuItem_Click; // // начатьРаботуToolStripMenuItem // начатьРаботуToolStripMenuItem.Name = "начатьРаботуToolStripMenuItem"; - начатьРаботуToolStripMenuItem.Size = new Size(180, 22); + начатьРаботуToolStripMenuItem.Size = new Size(154, 22); начатьРаботуToolStripMenuItem.Text = "Начать работу"; начатьРаботуToolStripMenuItem.Click += startWorkToolStripMenuItem_Click; // // отчетыToolStripMenuItem // - отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокСушиToolStripMenuItem, сушиСИнгредиентамиToolStripMenuItem, списокЗаказовToolStripMenuItem }); + отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокСушиToolStripMenuItem, сушиСИнгредиентамиToolStripMenuItem, списокЗаказовToolStripMenuItem, письмаToolStripMenuItem }); отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem"; отчетыToolStripMenuItem.Size = new Size(60, 20); отчетыToolStripMenuItem.Text = "Отчеты"; @@ -200,6 +201,13 @@ dataGridView.Size = new Size(919, 426); dataGridView.TabIndex = 7; // + // письмаToolStripMenuItem + // + письмаToolStripMenuItem.Name = "письмаToolStripMenuItem"; + письмаToolStripMenuItem.Size = new Size(203, 22); + письмаToolStripMenuItem.Text = "Письма"; + письмаToolStripMenuItem.Click += письмаToolStripMenuItem_Click; + // // FormMain // AutoScaleDimensions = new SizeF(7F, 15F); @@ -242,5 +250,6 @@ private ToolStripMenuItem клиентыToolStripMenuItem; private ToolStripMenuItem исполнителиToolStripMenuItem; private ToolStripMenuItem начатьРаботуToolStripMenuItem; + private ToolStripMenuItem письмаToolStripMenuItem; } } \ No newline at end of file diff --git a/SushiBar/SushiBar/FormMain.cs b/SushiBar/SushiBar/FormMain.cs index 7748147..e9057ef 100644 --- a/SushiBar/SushiBar/FormMain.cs +++ b/SushiBar/SushiBar/FormMain.cs @@ -34,7 +34,8 @@ namespace SushiBarView { dataGridView.DataSource = list; dataGridView.Columns["SushiId"].Visible = false; - dataGridView.Columns["Implementerid"].Visible=false; + dataGridView.Columns["Implementerid"].Visible = false; + dataGridView.Columns["ClientEmail"].Visible = false; } _logger.LogInformation("Загрузка заказов"); } @@ -199,5 +200,14 @@ namespace SushiBarView _workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic); MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); } + + private void письмаToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormViewMail)); + if (service is FormViewMail form) + { + form.ShowDialog(); + } + } } } \ No newline at end of file diff --git a/SushiBar/SushiBar/FormViewMail.Designer.cs b/SushiBar/SushiBar/FormViewMail.Designer.cs new file mode 100644 index 0000000..0f71814 --- /dev/null +++ b/SushiBar/SushiBar/FormViewMail.Designer.cs @@ -0,0 +1,61 @@ +namespace SushiBarView +{ + 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.Dock = DockStyle.Fill; + dataGridView.Location = new Point(0, 0); + dataGridView.Name = "dataGridView"; + dataGridView.Size = new Size(800, 450); + dataGridView.TabIndex = 0; + // + // FormViewMail + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(800, 450); + Controls.Add(dataGridView); + Name = "FormViewMail"; + Text = "FormViewMail"; + Load += FormViewMail_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView; + } +} \ No newline at end of file diff --git a/SushiBar/SushiBar/FormViewMail.cs b/SushiBar/SushiBar/FormViewMail.cs new file mode 100644 index 0000000..6bc7378 --- /dev/null +++ b/SushiBar/SushiBar/FormViewMail.cs @@ -0,0 +1,39 @@ +using Microsoft.Extensions.Logging; +using SushiBarContracts.BusinessLogicsContracts; + + +namespace SushiBarView +{ + 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 FormViewMail_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/SushiBar/SushiBar/FormViewMail.resx b/SushiBar/SushiBar/FormViewMail.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/SushiBar/SushiBar/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/SushiBar/SushiBar/Program.cs b/SushiBar/SushiBar/Program.cs index 82cb232..7982341 100644 --- a/SushiBar/SushiBar/Program.cs +++ b/SushiBar/SushiBar/Program.cs @@ -8,6 +8,8 @@ using SushiBarContracts.BusinessLogicsContracts; using SushiBarContracts.StoragesContracts; using SushiBarDatabaseImplement.Implements; using SushiBarBusinessLogic; +using SushiBarBusinessLogic.MailWorker; +using SushiBarContracts.BindingModels; namespace SushiBarView { @@ -24,13 +26,32 @@ namespace SushiBarView // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); + 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 services = new ServiceCollection(); - ConfigureServices(services); - _serviceProvider = services.BuildServiceProvider(); + 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()); - } + Application.Run(_serviceProvider.GetRequiredService()); + } private static void ConfigureServices(ServiceCollection services) { @@ -44,16 +65,18 @@ namespace SushiBarView 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,12 +88,14 @@ namespace SushiBarView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); - } - - } + services.AddSingleton(); + } + private static void MailCheck(object obj) => ServiceProvider?.GetService()?.MailCheck(); + } } diff --git a/SushiBar/SushiBar/SushiBarView.csproj b/SushiBar/SushiBar/SushiBarView.csproj index 8cfbc34..97e4567 100644 --- a/SushiBar/SushiBar/SushiBarView.csproj +++ b/SushiBar/SushiBar/SushiBarView.csproj @@ -29,4 +29,10 @@ + + + Always + + + \ No newline at end of file diff --git a/SushiBar/SushiBarBusinessLogic/BusinessLogics/ClientLogic.cs b/SushiBar/SushiBarBusinessLogic/BusinessLogics/ClientLogic.cs index 4e68d36..0c2aa8b 100644 --- a/SushiBar/SushiBarBusinessLogic/BusinessLogics/ClientLogic.cs +++ b/SushiBar/SushiBarBusinessLogic/BusinessLogics/ClientLogic.cs @@ -4,6 +4,7 @@ using SushiBarContracts.BusinessLogicsContracts; using SushiBarContracts.SearchModel; using SushiBarContracts.StoragesContracts; using SushiBarContracts.ViewModels; +using System.Text.RegularExpressions; namespace SushiBarBusinessLogic { @@ -90,26 +91,25 @@ namespace SushiBarBusinessLogic } if (string.IsNullOrEmpty(model.ClientFIO)) { - throw new ArgumentNullException("Invalid fullname of user", nameof(model.ClientFIO)); + throw new ArgumentNullException("Нет ФИО пользователя", nameof(model.ClientFIO)); } - if (string.IsNullOrEmpty(model.Email)) + if (string.IsNullOrEmpty(model.Email) || !Regex.IsMatch(model.Email, @"^[A-Za-z0-9._%+-]+\@([a-z0-9-]+\.)+[a-z]{2,4}$")) { - throw new ArgumentNullException("Invalid email of user", nameof(model.Email)); + throw new ArgumentNullException("Нет указана валидная почта", nameof(model.Email)); } - if (string.IsNullOrEmpty(model.Password)) - { - throw new ArgumentNullException("Invalid password of user", nameof(model.Password)); + if (!Regex.IsMatch(model.Email, @"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$")) + { + throw new ArgumentNullException("Не указан правильный пароль", nameof(model.Password)); } - _logger.LogInformation("Client. ClientFIO:{ClientFIO}. Email:{Email}. Id:{Id} ", model.ClientFIO, model.Email, model.Id); - + _logger.LogInformation("Client. ClientFIO:{ClientFIO}.Email:{Email}.Id:{Id}", + model.ClientFIO, model.Email, model.Id); var element = _clientStorage.GetElement(new ClientSearchModel { - Email = model.Email + ClientFIO = model.ClientFIO }); - if (element != null && element.Id != model.Id) { - throw new InvalidOperationException("User with such email already exists."); + throw new InvalidOperationException("Клиент с таким именем уже есть"); } } } diff --git a/SushiBar/SushiBarBusinessLogic/BusinessLogics/MessageInfoLogic.cs b/SushiBar/SushiBarBusinessLogic/BusinessLogics/MessageInfoLogic.cs new file mode 100644 index 0000000..1579165 --- /dev/null +++ b/SushiBar/SushiBarBusinessLogic/BusinessLogics/MessageInfoLogic.cs @@ -0,0 +1,81 @@ +using Microsoft.Extensions.Logging; +using SushiBarContracts.BindingModels; +using SushiBarContracts.BusinessLogicsContracts; +using SushiBarContracts.SearchModel; +using SushiBarContracts.SearchModels; +using SushiBarContracts.StoragesContracts; +using SushiBarContracts.ViewModels; + +namespace SushiBarBusinessLogic +{ + public class MessageInfoLogic : IMessageInfoLogic + { + private readonly ILogger _logger; + private readonly IMessageInfoStorage _messageInfoStorage; + private readonly IClientStorage _clientStorage; + public MessageInfoLogic(ILogger logger, IMessageInfoStorage messageInfoStorage, IClientStorage clientStorage) + { + _logger = logger; + _messageInfoStorage = messageInfoStorage; + _clientStorage = clientStorage; + } + public List? ReadList(MessageInfoSearchModel? model) + { + _logger.LogInformation("ReadList. MessageId:{MessageId}.ClientId:{ClientId}", model?.MessageId, model?.ClientId); + var list = model == null ? _messageInfoStorage.GetFullList() : _messageInfoStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + _logger.LogInformation("ReadList. Count:{Count}", list.Count); + return list; + } + public bool Create(MessageInfoBindingModel model) + { + CheckModel(model); + if (_messageInfoStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } + private void CheckModel(MessageInfoBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (!withParams) + { + return; + } + if (string.IsNullOrEmpty(model.MessageId)) + { + throw new ArgumentNullException("Не указан id сообщения", nameof(model.MessageId)); + } + if (string.IsNullOrEmpty(model.SenderName)) + { + throw new ArgumentNullException("Не указао почта", nameof(model.SenderName)); + } + if (string.IsNullOrEmpty(model.Body)) + { + throw new ArgumentNullException("Не указан текст сообщения", nameof(model.Subject)); + } + _logger.LogInformation("MessageInfo. MessageId:{MessageId}.SenderName:{SenderName}.Subject:{Subject}.Body:{Body}", model.MessageId, model.SenderName, model.Subject, model.Body); + var element = _clientStorage.GetElement(new ClientSearchModel + { + Email = model.SenderName + }); + if (element == null) + { + _logger.LogWarning("Не удалоссь найти клиента, отправившего письмо с адреса Email:{Email}", model.SenderName); + } + else + { + model.ClientId = element.Id; + } + } + } +} diff --git a/SushiBar/SushiBarBusinessLogic/BusinessLogics/OrderLogic.cs b/SushiBar/SushiBarBusinessLogic/BusinessLogics/OrderLogic.cs index dd229c0..f65d6cd 100644 --- a/SushiBar/SushiBarBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/SushiBar/SushiBarBusinessLogic/BusinessLogics/OrderLogic.cs @@ -1,4 +1,5 @@ using Microsoft.Extensions.Logging; +using SushiBarBusinessLogic.MailWorker; using SushiBarContracts.BindingModels; using SushiBarContracts.BusinessLogicsContracts; using SushiBarContracts.SearchModels; @@ -10,15 +11,18 @@ namespace SushiBarBusinessLogic.BusinessLogics { public class OrderLogic : IOrderLogic { - private readonly ILogger _logger; - private readonly IOrderStorage _orderStorage; - static readonly object _locker = new object(); - public OrderLogic(ILogger logger, IOrderStorage orderStorage) - { - _logger = logger; - _orderStorage = orderStorage; - } - public List? ReadList(OrderSearchModel? model) + private readonly ILogger _logger; + private readonly IOrderStorage _orderStorage; + private readonly AbstractMailWorker _mailWorker; + private readonly IClientLogic _clientLogic; + public OrderLogic(ILogger logger, IOrderStorage orderStorage, AbstractMailWorker mailWorker, IClientLogic clientLogic) + { + _logger = logger; + _orderStorage = orderStorage; + _mailWorker = mailWorker; + _clientLogic = clientLogic; + } + public List? ReadList(OrderSearchModel? model) { _logger.LogInformation("ReadList. ClientId:{ClientId}.Status:{Status}.ImplementerId:{ImplementerId}.DateFrom:{DateFrom}.DateTo:{DateTo}OrderId:{Id}", model?.ClientId, model?.Status, model?.ImplementerId, model?.DateFrom, model?.DateTo, model?.Id); @@ -37,30 +41,35 @@ namespace SushiBarBusinessLogic.BusinessLogics if (model.Status != OrderStatus.Неизвестен) return false; model.Status = OrderStatus.Принят; - if (_orderStorage.Insert(model) == null) + var element = _orderStorage.Insert(model); + if (element == null) { _logger.LogWarning("Insert operation failed"); return false; } - return true; + Task.Run(() => _mailWorker.MailSendAsync(new MailSendInfoBindingModel + { + MailAddress = element.ClientEmail, + Subject = $"Изменение статуса заказа номер {element.Id}", + Text = $"Ваш заказ номер {element.Id} на суши {element.SushiName} от {element.DateCreate} на сумму {element.Sum} принят." + })); + SendOrderStatusMail(element.ClientId, $"Новый заказ создан. Номер заказа #{element.Id}", $"Заказ #{element.Id} от {element.DateCreate} на сумму {element.Sum:0.00} принят"); + return true; } public bool TakeOrderInWork(OrderBindingModel model) { - lock (_locker) - { - return ChangeStatus(model, OrderStatus.Выполняется); - } - } + return StatusUpdate(model, OrderStatus.Выполняется); + } public bool FinishOrder(OrderBindingModel model) { - return ChangeStatus(model, OrderStatus.Готов); + return StatusUpdate(model, OrderStatus.Готов); } public bool DeliveryOrder(OrderBindingModel model) { - return ChangeStatus(model, OrderStatus.Выдан); + return StatusUpdate(model, OrderStatus.Выдан); } private void CheckModel(OrderBindingModel model, bool withParams = true) @@ -89,48 +98,43 @@ namespace SushiBarBusinessLogic.BusinessLogics model.SushiId, model.Count, model.Sum, model.Id); } - private bool ChangeStatus(OrderBindingModel model, OrderStatus requiredStatus) - { - CheckModel(model, false); - var element = _orderStorage.GetElement(new OrderSearchModel() - { - Id = model.Id - }); - if (element == null) - { - throw new InvalidOperationException(nameof(element)); - } - model.DateCreate = element.DateCreate; - model.SushiId = element.SushiId; - model.DateImplement = element.DateImplement; - model.ClientId = element.ClientId; - if (!model.ImplementerId.HasValue) - { - model.ImplementerId = element.ImplementerId; - } - model.Status = element.Status; - model.Count = element.Count; - model.Sum = element.Sum; - if (requiredStatus - model.Status == 1) - { - model.Status = requiredStatus; - if (model.Status == OrderStatus.Готов) - { - model.DateImplement = DateTime.Now; - } - if (_orderStorage.Update(model) == null) - { - _logger.LogWarning("Update operation failed"); - return false; - } - return true; - } - _logger.LogWarning("Changing status operation faled: Current-{Status}:required-{requiredStatus}.", model.Status, requiredStatus); - throw new InvalidOperationException($"Невозможно приствоить статус {requiredStatus} заказу с текущим статусом {model.Status}"); + private bool StatusUpdate(OrderBindingModel model, OrderStatus newStatus) + { + var viewModel = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id }); + if (viewModel == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (viewModel.Status + 1 != newStatus) + { + _logger.LogWarning("Change status operation failed"); + throw new InvalidOperationException(); + } + model.Status = newStatus; + if (model.Status == OrderStatus.Готов) + { + model.DateImplement = DateTime.Now; + } + else + { + model.DateImplement = viewModel.DateImplement; + } + if (viewModel.ImplementerId.HasValue) + { + model.ImplementerId = viewModel.ImplementerId.Value; + } + CheckModel(model, false); + 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; + } - } - - public OrderViewModel? ReadElement(OrderSearchModel model) + public OrderViewModel? ReadElement(OrderSearchModel model) { if (model == null) { @@ -147,5 +151,20 @@ namespace SushiBarBusinessLogic.BusinessLogics _logger.LogInformation("ReadElement find. Id:{Id}", element.Id); return element; } - } + 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/SushiBar/SushiBarBusinessLogic/MailWorker/AbstractMailWorker.cs b/SushiBar/SushiBarBusinessLogic/MailWorker/AbstractMailWorker.cs new file mode 100644 index 0000000..8ccf826 --- /dev/null +++ b/SushiBar/SushiBarBusinessLogic/MailWorker/AbstractMailWorker.cs @@ -0,0 +1,97 @@ +using Microsoft.Extensions.Logging; +using SushiBarContracts.BindingModels; +using SushiBarContracts.BusinessLogicsContracts; + + +namespace SushiBarBusinessLogic.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/SushiBar/SushiBarBusinessLogic/MailWorker/MailKitWorker.cs b/SushiBar/SushiBarBusinessLogic/MailWorker/MailKitWorker.cs new file mode 100644 index 0000000..268fa2a --- /dev/null +++ b/SushiBar/SushiBarBusinessLogic/MailWorker/MailKitWorker.cs @@ -0,0 +1,79 @@ +using Microsoft.Extensions.Logging; +using System.Net.Mail; +using System.Net; +using System.Text; +using SushiBarContracts.BusinessLogicsContracts; +using SushiBarContracts.BindingModels; +using MailKit.Net.Pop3; +using MailKit.Security; +using MailChimp.Net.Logic; + +namespace SushiBarBusinessLogic.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 (MailKit.Security.AuthenticationException) + { } + finally + { + client.Disconnect(true); + } + }); + return list; + } + } +} diff --git a/SushiBar/SushiBarBusinessLogic/SushiBarBusinessLogic.csproj b/SushiBar/SushiBarBusinessLogic/SushiBarBusinessLogic.csproj index cc0951c..81607fc 100644 --- a/SushiBar/SushiBarBusinessLogic/SushiBarBusinessLogic.csproj +++ b/SushiBar/SushiBarBusinessLogic/SushiBarBusinessLogic.csproj @@ -8,6 +8,8 @@ + + diff --git a/SushiBar/SushiBarClientApp/Controllers/HomeController.cs b/SushiBar/SushiBarClientApp/Controllers/HomeController.cs index 05903f2..7d45370 100644 --- a/SushiBar/SushiBarClientApp/Controllers/HomeController.cs +++ b/SushiBar/SushiBarClientApp/Controllers/HomeController.cs @@ -146,7 +146,13 @@ namespace SushiBarClientApp.Controllers ); return count * (prod?.Price ?? 1); } - } - - } - + public IActionResult Mails() + { + if (APIClient.Client == null) + { + return Redirect("~/Home/Enter"); + } + return View(APIClient.GetRequest>($"api/client/getmessages?clientId={APIClient.Client.Id}")); + } + } +} \ No newline at end of file diff --git a/SushiBar/SushiBarClientApp/Views/Home/Mails.cshtml b/SushiBar/SushiBarClientApp/Views/Home/Mails.cshtml new file mode 100644 index 0000000..f4ae88c --- /dev/null +++ b/SushiBar/SushiBarClientApp/Views/Home/Mails.cshtml @@ -0,0 +1,54 @@ +@using SushiBarContracts.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/SushiBar/SushiBarClientApp/Views/Shared/_Layout.cshtml b/SushiBar/SushiBarClientApp/Views/Shared/_Layout.cshtml index 386e637..41b9ff2 100644 --- a/SushiBar/SushiBarClientApp/Views/Shared/_Layout.cshtml +++ b/SushiBar/SushiBarClientApp/Views/Shared/_Layout.cshtml @@ -33,6 +33,9 @@ + diff --git a/SushiBar/SushiBarContracts/BindingModels/MailConfigBindingModel.cs b/SushiBar/SushiBarContracts/BindingModels/MailConfigBindingModel.cs new file mode 100644 index 0000000..4b4b776 --- /dev/null +++ b/SushiBar/SushiBarContracts/BindingModels/MailConfigBindingModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SushiBarContracts.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/SushiBar/SushiBarContracts/BindingModels/MailSendInfoBindingModel.cs b/SushiBar/SushiBarContracts/BindingModels/MailSendInfoBindingModel.cs new file mode 100644 index 0000000..6536457 --- /dev/null +++ b/SushiBar/SushiBarContracts/BindingModels/MailSendInfoBindingModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SushiBarContracts.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/SushiBar/SushiBarContracts/BindingModels/MessageInfoBindingModel.cs b/SushiBar/SushiBarContracts/BindingModels/MessageInfoBindingModel.cs new file mode 100644 index 0000000..7fcd282 --- /dev/null +++ b/SushiBar/SushiBarContracts/BindingModels/MessageInfoBindingModel.cs @@ -0,0 +1,20 @@ +using PrecastConcretePlantDataModels.Models; +using SushiBarDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SushiBarContracts.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/SushiBar/SushiBarContracts/BusinessLogicsContracts/IMessageInfoLogic.cs b/SushiBar/SushiBarContracts/BusinessLogicsContracts/IMessageInfoLogic.cs new file mode 100644 index 0000000..4b93100 --- /dev/null +++ b/SushiBar/SushiBarContracts/BusinessLogicsContracts/IMessageInfoLogic.cs @@ -0,0 +1,17 @@ +using SushiBarContracts.BindingModels; +using SushiBarContracts.SearchModels; +using SushiBarContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SushiBarContracts.BusinessLogicsContracts +{ + public interface IMessageInfoLogic + { + List? ReadList(MessageInfoSearchModel? model); + bool Create(MessageInfoBindingModel model); + } +} diff --git a/SushiBar/SushiBarContracts/SearchModels/MessageInfoSearchModel.cs b/SushiBar/SushiBarContracts/SearchModels/MessageInfoSearchModel.cs new file mode 100644 index 0000000..20981ec --- /dev/null +++ b/SushiBar/SushiBarContracts/SearchModels/MessageInfoSearchModel.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SushiBarContracts.SearchModels +{ + public class MessageInfoSearchModel + { + public int? ClientId { get; set; } + public string? MessageId { get; set; } + } +} diff --git a/SushiBar/SushiBarContracts/StoragesContracts/IMessageInfoStorage.cs b/SushiBar/SushiBarContracts/StoragesContracts/IMessageInfoStorage.cs new file mode 100644 index 0000000..b989a1a --- /dev/null +++ b/SushiBar/SushiBarContracts/StoragesContracts/IMessageInfoStorage.cs @@ -0,0 +1,19 @@ +using SushiBarContracts.BindingModels; +using SushiBarContracts.SearchModels; +using SushiBarContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SushiBarContracts.StoragesContracts +{ + public interface IMessageInfoStorage + { + List GetFullList(); + List GetFilteredList(MessageInfoSearchModel model); + MessageInfoViewModel? GetElement(MessageInfoSearchModel model); + MessageInfoViewModel? Insert(MessageInfoBindingModel model); + } +} diff --git a/SushiBar/SushiBarContracts/ViewModels/MessageInfoViewModel.cs b/SushiBar/SushiBarContracts/ViewModels/MessageInfoViewModel.cs new file mode 100644 index 0000000..f4c4557 --- /dev/null +++ b/SushiBar/SushiBarContracts/ViewModels/MessageInfoViewModel.cs @@ -0,0 +1,30 @@ +using PrecastConcretePlantDataModels.Models; +using SushiBarDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SushiBarContracts.ViewModels +{ + public class MessageInfoViewModel : IMessageInfoModel + { + public string MessageId { get; set; } = string.Empty; + + public int? ClientId { get; set; } + + [DisplayName("Отправитель")] + public string SenderName { get; set; } = string.Empty; + + [DisplayName("Дата письма")] + public DateTime DateDelivery { get; set; } + + [DisplayName("Заголовок")] + public string Subject { get; set; } = string.Empty; + + [DisplayName("Текст")] + public string Body { get; set; } = string.Empty; + } +} diff --git a/SushiBar/SushiBarContracts/ViewModels/OrderViewModel.cs b/SushiBar/SushiBarContracts/ViewModels/OrderViewModel.cs index 65c5ba7..22003be 100644 --- a/SushiBar/SushiBarContracts/ViewModels/OrderViewModel.cs +++ b/SushiBar/SushiBarContracts/ViewModels/OrderViewModel.cs @@ -13,6 +13,7 @@ namespace SushiBarContracts.ViewModels public string? ImplementerFIO { get; set; } = null; public int SushiId { get; set; } public int ClientId { get; set; } + public string ClientEmail { get; set; } = string.Empty; [DisplayName("ФИО клиента")] public string ClientFIO { get; set; } = string.Empty; diff --git a/SushiBar/SushiBarDataModels/Models/IMessageInfoModel.cs b/SushiBar/SushiBarDataModels/Models/IMessageInfoModel.cs new file mode 100644 index 0000000..5da4404 --- /dev/null +++ b/SushiBar/SushiBarDataModels/Models/IMessageInfoModel.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantDataModels.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/SushiBar/SushiBarDatabaseImplement/Implements/MessageInfoStorage.cs b/SushiBar/SushiBarDatabaseImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..529de05 --- /dev/null +++ b/SushiBar/SushiBarDatabaseImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,48 @@ +using SushiBarContracts.BindingModels; +using SushiBarContracts.SearchModels; +using SushiBarContracts.StoragesContracts; +using SushiBarContracts.ViewModels; +using SushiBarDatabaseImplement.Models; + +namespace SushiBarDatabaseImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + using var context = new SushiBarDatabase(); + 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 SushiBarDatabase(); + return context.Messages + .Where(x => x.ClientId == model.ClientId).Select(x => x.GetViewModel).ToList(); + } + + public List GetFullList() + { + using var context = new SushiBarDatabase(); + return context.Messages.Select(x => x.GetViewModel).ToList(); + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + using var context = new SushiBarDatabase(); + var newMessage = MessageInfo.Create(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/SushiBar/SushiBarDatabaseImplement/Migrations/20240512150027_6Lab.Designer.cs b/SushiBar/SushiBarDatabaseImplement/Migrations/20240516141726_tested17.Designer.cs similarity index 86% rename from SushiBar/SushiBarDatabaseImplement/Migrations/20240512150027_6Lab.Designer.cs rename to SushiBar/SushiBarDatabaseImplement/Migrations/20240516141726_tested17.Designer.cs index 949f5eb..886438c 100644 --- a/SushiBar/SushiBarDatabaseImplement/Migrations/20240512150027_6Lab.Designer.cs +++ b/SushiBar/SushiBarDatabaseImplement/Migrations/20240516141726_tested17.Designer.cs @@ -12,8 +12,8 @@ using SushiBarDatabaseImplement; namespace SushiBarDatabaseImplement.Migrations { [DbContext(typeof(SushiBarDatabase))] - [Migration("20240512150027_6Lab")] - partial class _6Lab + [Migration("20240516141726_tested17")] + partial class tested17 { /// protected override void BuildTargetModel(ModelBuilder modelBuilder) @@ -97,6 +97,36 @@ namespace SushiBarDatabaseImplement.Migrations b.ToTable("Ingredients"); }); + modelBuilder.Entity("SushiBarDatabaseImplement.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("SushiBarDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -186,6 +216,15 @@ namespace SushiBarDatabaseImplement.Migrations b.ToTable("SushiIngredients"); }); + modelBuilder.Entity("SushiBarDatabaseImplement.Models.MessageInfo", b => + { + b.HasOne("SushiBarDatabaseImplement.Models.Client", "Client") + .WithMany() + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + modelBuilder.Entity("SushiBarDatabaseImplement.Models.Order", b => { b.HasOne("SushiBarDatabaseImplement.Models.Client", "Client") diff --git a/SushiBar/SushiBarDatabaseImplement/Migrations/20240512150027_6Lab.cs b/SushiBar/SushiBarDatabaseImplement/Migrations/20240516141726_tested17.cs similarity index 84% rename from SushiBar/SushiBarDatabaseImplement/Migrations/20240512150027_6Lab.cs rename to SushiBar/SushiBarDatabaseImplement/Migrations/20240516141726_tested17.cs index df876ec..3c828d5 100644 --- a/SushiBar/SushiBarDatabaseImplement/Migrations/20240512150027_6Lab.cs +++ b/SushiBar/SushiBarDatabaseImplement/Migrations/20240516141726_tested17.cs @@ -6,7 +6,7 @@ using Microsoft.EntityFrameworkCore.Migrations; namespace SushiBarDatabaseImplement.Migrations { /// - public partial class _6Lab : Migration + public partial class tested17 : Migration { /// protected override void Up(MigrationBuilder migrationBuilder) @@ -70,6 +70,27 @@ namespace SushiBarDatabaseImplement.Migrations table.PrimaryKey("PK_ListSushi", 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 SushiBarDatabaseImplement.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 SushiBarDatabaseImplement.Migrations /// protected override void Down(MigrationBuilder migrationBuilder) { + migrationBuilder.DropTable( + name: "Messages"); + migrationBuilder.DropTable( name: "Orders"); diff --git a/SushiBar/SushiBarDatabaseImplement/Migrations/SushiBarDatabaseModelSnapshot.cs b/SushiBar/SushiBarDatabaseImplement/Migrations/SushiBarDatabaseModelSnapshot.cs index 29e4b06..d597d07 100644 --- a/SushiBar/SushiBarDatabaseImplement/Migrations/SushiBarDatabaseModelSnapshot.cs +++ b/SushiBar/SushiBarDatabaseImplement/Migrations/SushiBarDatabaseModelSnapshot.cs @@ -94,6 +94,36 @@ namespace SushiBarDatabaseImplement.Migrations b.ToTable("Ingredients"); }); + modelBuilder.Entity("SushiBarDatabaseImplement.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("SushiBarDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -183,6 +213,15 @@ namespace SushiBarDatabaseImplement.Migrations b.ToTable("SushiIngredients"); }); + modelBuilder.Entity("SushiBarDatabaseImplement.Models.MessageInfo", b => + { + b.HasOne("SushiBarDatabaseImplement.Models.Client", "Client") + .WithMany() + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + modelBuilder.Entity("SushiBarDatabaseImplement.Models.Order", b => { b.HasOne("SushiBarDatabaseImplement.Models.Client", "Client") diff --git a/SushiBar/SushiBarDatabaseImplement/Models/MessageInfo.cs b/SushiBar/SushiBarDatabaseImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..10b0699 --- /dev/null +++ b/SushiBar/SushiBarDatabaseImplement/Models/MessageInfo.cs @@ -0,0 +1,54 @@ +using PrecastConcretePlantDataModels.Models; +using SushiBarContracts.BindingModels; +using SushiBarContracts.ViewModels; +using System.ComponentModel.DataAnnotations; + + +namespace SushiBarDatabaseImplement.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(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Subject = model.Subject, + ClientId = model.ClientId, + MessageId = model.MessageId, + SenderName = model.SenderName, + DateDelivery = model.DateDelivery, + }; + } + + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Subject = Subject, + ClientId = ClientId, + MessageId = MessageId, + SenderName = SenderName, + DateDelivery = DateDelivery, + }; + + } +} diff --git a/SushiBar/SushiBarDatabaseImplement/SushiBarDatabase.cs b/SushiBar/SushiBarDatabaseImplement/SushiBarDatabase.cs index cd277e0..9ddabec 100644 --- a/SushiBar/SushiBarDatabaseImplement/SushiBarDatabase.cs +++ b/SushiBar/SushiBarDatabaseImplement/SushiBarDatabase.cs @@ -10,7 +10,7 @@ namespace SushiBarDatabaseImplement { if (optionsBuilder.IsConfigured == false) { - optionsBuilder.UseSqlServer(@"Data Source=DESKTOP-E2VPEN3\SQLEXPRESS;Initial Catalog=SushiBarDatabase;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True"); + optionsBuilder.UseSqlServer(@"Data Source=DESKTOP-E2VPEN3\SQLEXPRESS;Initial Catalog=SushiBarDatabaseTest;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True"); } base.OnConfiguring(optionsBuilder); } @@ -23,5 +23,6 @@ namespace SushiBarDatabaseImplement 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/SushiBar/SushiBarFileImplement/DataFileSingleton.cs b/SushiBar/SushiBarFileImplement/DataFileSingleton.cs index b0c1fcc..1cf7549 100644 --- a/SushiBar/SushiBarFileImplement/DataFileSingleton.cs +++ b/SushiBar/SushiBarFileImplement/DataFileSingleton.cs @@ -11,11 +11,13 @@ namespace SushiBarFileImplement private readonly string SushiFileName = "Sushi.xml"; private readonly string ClientFileName = "Client.xml"; private readonly string ImplementerFileName = "Implementer.xml"; + private readonly string MessageInfoFileName = "MessageInfo.xml"; public List Ingredients { get; private set; } public List Orders { get; private set; } public List ListSushi { get; private set; } public List Clients { get; private set; } public List Implementers { get; private set; } + public List Messages { get; private set; } public static DataFileSingleton GetInstance() { @@ -32,6 +34,7 @@ namespace SushiBarFileImplement public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement); public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", x => x.GetXElement); public void SaveImplementers() => SaveData(Implementers, ImplementerFileName, "Implementers", x => x.GetXElement); + public void SaveMessages() => SaveData(Orders, ImplementerFileName, "Messages", x => x.GetXElement); private DataFileSingleton() { @@ -40,6 +43,7 @@ namespace SushiBarFileImplement Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!; Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!; Implementers = LoadData(ImplementerFileName, "Implementer", x => Implementer.Create(x)!)!; + Messages = LoadData(MessageInfoFileName, "MessageInfo", x => MessageInfo.Create(x)!)!; } private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) diff --git a/SushiBar/SushiBarFileImplement/Implements/MessageInfoStorage.cs b/SushiBar/SushiBarFileImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..eed14a8 --- /dev/null +++ b/SushiBar/SushiBarFileImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,53 @@ +using SushiBarContracts.BindingModels; +using SushiBarContracts.SearchModels; +using SushiBarContracts.StoragesContracts; +using SushiBarContracts.ViewModels; +using SushiBarFileImplement.Models; + +namespace SushiBarFileImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + private readonly DataFileSingleton _source; + public MessageInfoStorage() + { + _source = DataFileSingleton.GetInstance(); + } + + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (model.MessageId != null) + { + return _source.Messages.FirstOrDefault(x => x.MessageId == model.MessageId)?.GetViewModel; + } + return null; + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + return _source.Messages + .Where(x => x.ClientId == model.ClientId) + .Select(x => x.GetViewModel) + .ToList(); + } + + public List GetFullList() + { + return _source.Messages + .Select(x => x.GetViewModel) + .ToList(); + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = MessageInfo.Create(model); + if (newMessage == null) + { + return null; + } + _source.Messages.Add(newMessage); + _source.SaveMessages(); + return newMessage.GetViewModel; + } + } +} diff --git a/SushiBar/SushiBarFileImplement/Models/MessageInfo.cs b/SushiBar/SushiBarFileImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..ea89b78 --- /dev/null +++ b/SushiBar/SushiBarFileImplement/Models/MessageInfo.cs @@ -0,0 +1,83 @@ +using PrecastConcretePlantDataModels.Models; +using SushiBarContracts.BindingModels; +using SushiBarContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace SushiBarFileImplement.Models +{ + [DataContract] + public class MessageInfo : IMessageInfoModel + { + [DataMember] + public string MessageId { get; private set; } = string.Empty; + [DataMember] + public int? ClientId { get; private set; } + [DataMember] + public string SenderName { get; private set; } = string.Empty; + [DataMember] + public DateTime DateDelivery { get; private set; } = DateTime.Now; + [DataMember] + public string Subject { get; private set; } = string.Empty; + [DataMember] + public string Body { get; private set; } = string.Empty; + + public static MessageInfo? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Subject = model.Subject, + ClientId = model.ClientId, + MessageId = model.MessageId, + SenderName = model.SenderName, + DateDelivery = model.DateDelivery, + }; + } + + public static MessageInfo? Create(XElement element) + { + if (element == null) + { + return null; + } + return new() + { + Body = element.Attribute("Body")!.Value, + Subject = element.Attribute("Subject")!.Value, + ClientId = Convert.ToInt32(element.Attribute("ClientId")!.Value), + MessageId = element.Attribute("MessageId")!.Value, + SenderName = element.Attribute("SenderName")!.Value, + DateDelivery = Convert.ToDateTime(element.Attribute("DateDelivery")!.Value), + }; + } + + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Subject = Subject, + ClientId = ClientId, + MessageId = MessageId, + SenderName = SenderName, + DateDelivery = DateDelivery, + }; + + public XElement GetXElement => new("MessageInfo", + new XAttribute("Body", Body), + new XAttribute("Subject", Subject), + new XAttribute("ClientId", ClientId), + new XAttribute("MessageId", MessageId), + new XAttribute("SenderName", SenderName), + new XAttribute("DateDelivery", DateDelivery) + ); + } +} diff --git a/SushiBar/SushiBarListImplement/DataListSingleton.cs b/SushiBar/SushiBarListImplement/DataListSingleton.cs index 5b6c0d2..9e0b832 100644 --- a/SushiBar/SushiBarListImplement/DataListSingleton.cs +++ b/SushiBar/SushiBarListImplement/DataListSingleton.cs @@ -11,6 +11,7 @@ namespace SushiBarListImplement public List ListSushi { get; set; } public List Clients { get; set; } public List Implementers { get; set; } + public List Messages { get; set; } private DataListSingleton() { Ingredients = new List(); @@ -18,6 +19,7 @@ namespace SushiBarListImplement ListSushi = new List(); Clients = new List(); Implementers = new List(); + Messages = new List(); } public static DataListSingleton GetInstance() { diff --git a/SushiBar/SushiBarListImplement/Implements/MessageInfoStorage.cs b/SushiBar/SushiBarListImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..820aa3a --- /dev/null +++ b/SushiBar/SushiBarListImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,61 @@ +using SushiBarContracts.BindingModels; +using SushiBarContracts.SearchModels; +using SushiBarContracts.StoragesContracts; +using SushiBarContracts.ViewModels; +using SushiBarListImplement.Models; + +namespace SushiBarListImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + private readonly DataListSingleton _source; + public MessageInfoStorage() + { + _source = DataListSingleton.GetInstance(); + } + + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + foreach (var message in _source.Messages) + { + if (model.MessageId != null && model.MessageId.Equals(message.MessageId)) + return message.GetViewModel; + } + return null; + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + List result = new(); + foreach (var item in _source.Messages) + { + if (item.ClientId.HasValue && item.ClientId == model.ClientId) + { + result.Add(item.GetViewModel); + } + } + return result; + } + + public List GetFullList() + { + List result = new(); + foreach (var item in _source.Messages) + { + result.Add(item.GetViewModel); + } + return result; + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = MessageInfo.Create(model); + if (newMessage == null) + { + return null; + } + _source.Messages.Add(newMessage); + return newMessage.GetViewModel; + } + } +} diff --git a/SushiBar/SushiBarListImplement/Models/MessageInfo.cs b/SushiBar/SushiBarListImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..2e967e1 --- /dev/null +++ b/SushiBar/SushiBarListImplement/Models/MessageInfo.cs @@ -0,0 +1,53 @@ +using PrecastConcretePlantDataModels.Models; +using SushiBarContracts.BindingModels; +using SushiBarContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SushiBarListImplement.Models +{ + public class MessageInfo : IMessageInfoModel + { + public string MessageId { get; private set; } = string.Empty; + + public int? ClientId { get; private set; } + + public string SenderName { get; private set; } = string.Empty; + + public DateTime DateDelivery { get; private set; } = DateTime.Now; + + public string Subject { get; private set; } = string.Empty; + + public string Body { get; private set; } = string.Empty; + + public static MessageInfo? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Subject = model.Subject, + ClientId = model.ClientId, + MessageId = model.MessageId, + SenderName = model.SenderName, + DateDelivery = model.DateDelivery, + }; + } + + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Subject = Subject, + ClientId = ClientId, + MessageId = MessageId, + SenderName = SenderName, + DateDelivery = DateDelivery, + }; + } +} diff --git a/SushiBar/SushiBarRestApi/Controllers/ClientController.cs b/SushiBar/SushiBarRestApi/Controllers/ClientController.cs index 539965b..6cf743a 100644 --- a/SushiBar/SushiBarRestApi/Controllers/ClientController.cs +++ b/SushiBar/SushiBarRestApi/Controllers/ClientController.cs @@ -2,6 +2,7 @@ using SushiBarContracts.BindingModel; using SushiBarContracts.BusinessLogicsContracts; using SushiBarContracts.SearchModel; +using SushiBarContracts.SearchModels; using SushiBarContracts.ViewModels; @@ -12,12 +13,13 @@ namespace SushiBarRestApi.Controllers public class ClientController : Controller { private readonly ILogger _logger; - private readonly IClientLogic _logic; - public ClientController(IClientLogic logic, ILogger - logger) + private readonly IClientLogic _logic; + private readonly IMessageInfoLogic _mailLogic; + public ClientController(IClientLogic logic, IMessageInfoLogic mailLogic, ILogger logger) { _logger = logger; _logic = logic; + _mailLogic = mailLogic; } [HttpGet] public ClientViewModel? Login(string login, string password) @@ -62,7 +64,22 @@ namespace SushiBarRestApi.Controllers throw; } } - + [HttpGet] + public List? GetMessages(int clientId) + { + try + { + return _mailLogic.ReadList(new MessageInfoSearchModel + { + ClientId = clientId + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения писем клиента"); + throw; + } } - } + } +} \ No newline at end of file diff --git a/SushiBar/SushiBarRestApi/Program.cs b/SushiBar/SushiBarRestApi/Program.cs index 00220f2..d45758c 100644 --- a/SushiBar/SushiBarRestApi/Program.cs +++ b/SushiBar/SushiBarRestApi/Program.cs @@ -1,6 +1,8 @@ using Microsoft.OpenApi.Models; using SushiBarBusinessLogic; using SushiBarBusinessLogic.BusinessLogics; +using SushiBarBusinessLogic.MailWorker; +using SushiBarContracts.BindingModels; using SushiBarContracts.BusinessLogicsContracts; using SushiBarContracts.StoragesContracts; using SushiBarDatabaseImplement.Implements; @@ -14,9 +16,13 @@ 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 @@ -31,6 +37,16 @@ builder.Services.AddSwaggerGen(c => }); }); var app = builder.Build(); +var mailSender = app.Services.GetService(); +mailSender?.MailConfig(new MailConfigBindingModel +{ + MailLogin = builder.Configuration?.GetSection("MailLogin")?.Value?.ToString() ?? string.Empty, + MailPassword = builder.Configuration?.GetSection("MailPassword")?.Value?.ToString() ?? string.Empty, + SmtpClientHost = builder.Configuration?.GetSection("SmtpClientHost")?.Value?.ToString() ?? string.Empty, + SmtpClientPort = Convert.ToInt32(builder.Configuration?.GetSection("SmtpClientPort")?.Value?.ToString()), + PopHost = builder.Configuration?.GetSection("PopHost")?.Value?.ToString() ?? string.Empty, + PopPort = Convert.ToInt32(builder.Configuration?.GetSection("PopPort")?.Value?.ToString()) +}); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { @@ -38,7 +54,7 @@ if (app.Environment.IsDevelopment()) app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "AbstractShopRestApi v1")); } -app.UseHttpsRedirection(); + app.UseAuthorization(); app.MapControllers(); app.Run(); diff --git a/SushiBar/SushiBarRestApi/appsettings.json b/SushiBar/SushiBarRestApi/appsettings.json index 10f68b8..93780df 100644 --- a/SushiBar/SushiBarRestApi/appsettings.json +++ b/SushiBar/SushiBarRestApi/appsettings.json @@ -5,5 +5,11 @@ "Microsoft.AspNetCore": "Warning" } }, - "AllowedHosts": "*" -} + "AllowedHosts": "*", + "SmtpClientHost": "smtp.gmail.com", + "SmtpClientPort": "587", + "PopHost": "pop.gmail.com", + "PopPort": "995", + "MailLogin": "allresourcesforlab@gmail.com", + "MailPassword": "eypt yuxk tylv dnpa" +} \ No newline at end of file