diff --git a/JewelryStore/App.config b/JewelryStore/App.config new file mode 100644 index 0000000..cffc8e8 --- /dev/null +++ b/JewelryStore/App.config @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/JewelryStore/FormCreateOrder.cs b/JewelryStore/FormCreateOrder.cs index 3746e0b..012e7cd 100644 --- a/JewelryStore/FormCreateOrder.cs +++ b/JewelryStore/FormCreateOrder.cs @@ -111,13 +111,18 @@ namespace JewelryStore MessageBoxButtons.OK, MessageBoxIcon.Error); return; } - _logger.LogInformation("Создание заказа"); + if (comboBoxClient.SelectedValue == null) + { + MessageBox.Show("Выберите клиента", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Создание заказа"); try { var operationResult = _logicO.CreateOrder(new OrderBindingModel { JewelId = Convert.ToInt32(comboBoxJewel.SelectedIndex) + 1, - JewelName = comboBoxJewel.SelectedValue.ToString(), + JewelName = comboBoxJewel.Text, ClientId = Convert.ToInt32(comboBoxClient.SelectedIndex) + 1, Count = Convert.ToInt32(textBoxCount.Text), Sum = Convert.ToDouble(textBoxSum.Text) diff --git a/JewelryStore/FormMails.Designer.cs b/JewelryStore/FormMails.Designer.cs new file mode 100644 index 0000000..3be02f2 --- /dev/null +++ b/JewelryStore/FormMails.Designer.cs @@ -0,0 +1,62 @@ +namespace JewelryStore +{ + partial class FormMails + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.DataGridView = new System.Windows.Forms.DataGridView(); + ((System.ComponentModel.ISupportInitialize)(this.DataGridView)).BeginInit(); + this.SuspendLayout(); + // + // DataGridView + // + this.DataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.DataGridView.Location = new System.Drawing.Point(3, 3); + this.DataGridView.Name = "DataGridView"; + this.DataGridView.RowTemplate.Height = 25; + this.DataGridView.Size = new System.Drawing.Size(794, 445); + this.DataGridView.TabIndex = 0; + // + // FormMails + // + this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 450); + this.Controls.Add(this.DataGridView); + this.Name = "FormMails"; + this.Text = "Эл. письма"; + this.Load += new System.EventHandler(this.FormMails_Load); + ((System.ComponentModel.ISupportInitialize)(this.DataGridView)).EndInit(); + this.ResumeLayout(false); + + } + + #endregion + + private DataGridView DataGridView; + } +} \ No newline at end of file diff --git a/JewelryStore/FormMails.cs b/JewelryStore/FormMails.cs new file mode 100644 index 0000000..5e37d56 --- /dev/null +++ b/JewelryStore/FormMails.cs @@ -0,0 +1,55 @@ +using JewelryStoreContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace JewelryStore +{ + public partial class FormMails : Form + { + private readonly ILogger _logger; + private readonly IMessageInfoLogic _logic; + + public FormMails(ILogger logger, IMessageInfoLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + LoadData(); + } + + private void LoadData() + { + try + { + var list = _logic.ReadList(null); + if (list != null) + { + DataGridView.DataSource = list; + DataGridView.Columns["ClientId"].Visible = false; + DataGridView.Columns["MessageId"].Visible = false; + DataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + _logger.LogInformation("Загрузка писем"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки писем"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + + private void FormMails_Load(object sender, EventArgs e) + { + LoadData(); + } + } +} diff --git a/JewelryStore/FormMails.resx b/JewelryStore/FormMails.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/JewelryStore/FormMails.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/JewelryStore/FormMain.Designer.cs b/JewelryStore/FormMain.Designer.cs index 251d535..5c00a81 100644 --- a/JewelryStore/FormMain.Designer.cs +++ b/JewelryStore/FormMain.Designer.cs @@ -45,7 +45,8 @@ this.компонентыПоИзделиямToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.списокЗаказзовToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.запускРаботToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); + this.элПисьмаToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); this.menuStrip.SuspendLayout(); this.SuspendLayout(); // @@ -115,7 +116,8 @@ this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.справочникиToolStripMenuItem, this.отчетыToolStripMenuItem, - this.запускРаботToolStripMenuItem}); + this.запускРаботToolStripMenuItem, + this.элПисьмаToolStripMenuItem}); this.menuStrip.Location = new System.Drawing.Point(0, 0); this.menuStrip.Name = "menuStrip"; this.menuStrip.Size = new System.Drawing.Size(1530, 33); @@ -198,10 +200,17 @@ this.запускРаботToolStripMenuItem.Size = new System.Drawing.Size(136, 29); this.запускРаботToolStripMenuItem.Text = "Запуск работ"; this.запускРаботToolStripMenuItem.Click += new System.EventHandler(this.запускРаботToolStripMenuItem_Click); - // - // FormMain - // - this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F); + // + // элПисьмаToolStripMenuItem + // + this.элПисьмаToolStripMenuItem.Name = "элПисьмаToolStripMenuItem"; + this.элПисьмаToolStripMenuItem.Size = new System.Drawing.Size(82, 20); + this.элПисьмаToolStripMenuItem.Text = "Эл. Письма"; + this.элПисьмаToolStripMenuItem.Click += new System.EventHandler(this.элПисьмаToolStripMenuItem_Click); + // + // FormMain + // + this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1530, 450); this.Controls.Add(this.buttonRefresh); @@ -242,5 +251,6 @@ private ToolStripMenuItem клиентыToolStripMenuItem; private ToolStripMenuItem запускРаботToolStripMenuItem; private ToolStripMenuItem исполнителиToolStripMenuItem; - } + private ToolStripMenuItem элПисьмаToolStripMenuItem; + } } \ No newline at end of file diff --git a/JewelryStore/FormMain.cs b/JewelryStore/FormMain.cs index 1917875..f34be91 100644 --- a/JewelryStore/FormMain.cs +++ b/JewelryStore/FormMain.cs @@ -30,7 +30,8 @@ namespace JewelryStore _orderLogic = orderLogic; _reportLogic = reportLogic; _workProcess = workProcess; - } + LoadData(); + } private void FormMain_Load(object sender, EventArgs e) { @@ -100,14 +101,6 @@ namespace JewelryStore var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel { Id = id, - //JewelId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["JewelId"].Value), - //ClientId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["ClientId"].Value), - //ImplementerId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["ImplementerId"].Value), - //JewelName = dataGridView.SelectedRows[0].Cells["JewelName"].Value.ToString(), - //Status = Enum.Parse(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()), - //Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value), - //Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()), - //DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()), }); if (!operationResult) { @@ -136,14 +129,6 @@ namespace JewelryStore var operationResult = _orderLogic.FinishOrder(new OrderBindingModel { Id = id, - //JewelId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["JewelId"].Value), - //ClientId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["ClientId"].Value), - //ImplementerId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["ImplementerId"].Value), - //JewelName = dataGridView.SelectedRows[0].Cells["JewelName"].Value.ToString(), - //Status = Enum.Parse(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()), - //Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value), - //Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()), - //DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()), }); if (!operationResult) { @@ -172,14 +157,6 @@ namespace JewelryStore OrderBindingModel { Id = id, - //JewelId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["JewelId"].Value), - //ClientId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["ClientId"].Value), - //ImplementerId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["ImplementerId"].Value), - //JewelName = dataGridView.SelectedRows[0].Cells["JewelName"].Value.ToString(), - //Status = Enum.Parse(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()), - //Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value), - //Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()), - //DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()), }); if (!operationResult) { @@ -262,5 +239,13 @@ namespace JewelryStore form.ShowDialog(); } } - } + private void элПисьмаToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormMails)); + if (service is FormMails form) + { + form.ShowDialog(); + } + } + } } diff --git a/JewelryStore/Program.cs b/JewelryStore/Program.cs index 50bf9fa..9d4c511 100644 --- a/JewelryStore/Program.cs +++ b/JewelryStore/Program.cs @@ -9,6 +9,8 @@ using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; using JewelryStoreBusinessLogic.OfficePackage; using JewelryStoreBusinessLogic.OfficePackage.Implements; +using JewelryStoreBusinessLogic.MailWorker; +using JewelryStoreContracts.BindingModels; namespace JewelryStore { @@ -29,6 +31,27 @@ namespace JewelryStore var services = new ServiceCollection(); ConfigureServices(services); _serviceProvider = services.BuildServiceProvider(); + try + { + var mailSender = _serviceProvider.GetService(); + mailSender?.MailConfig(new MailConfigBindingModel + { + MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty, + MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty, + SmtpClientHost = System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty, + SmtpClientPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]), + PopHost = System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty, + PopPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"]) + }); + + // + var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000); + } + catch (Exception ex) + { + var logger = _serviceProvider.GetService(); + logger?.LogError(ex, " "); + } Application.Run(_serviceProvider.GetRequiredService()); } private static void ConfigureServices(ServiceCollection services) @@ -43,9 +66,11 @@ namespace JewelryStore services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); + services.AddSingleton(); services.AddTransient(); services.AddTransient(); @@ -53,6 +78,7 @@ namespace JewelryStore services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -70,7 +96,8 @@ namespace JewelryStore services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); } - + private static void MailCheck(object obj) => ServiceProvider?.GetService()?.MailCheck(); } } \ No newline at end of file diff --git a/JewelryStore/nlog.config b/JewelryStore/nlog.config index 609afe6..bec9ca5 100644 --- a/JewelryStore/nlog.config +++ b/JewelryStore/nlog.config @@ -5,11 +5,12 @@ autoReload="true" internalLogLevel="Info"> - + - \ No newline at end of file + + diff --git a/JewelryStoreBusinessLogic/BusinessLogics/ClientLogic.cs b/JewelryStoreBusinessLogic/BusinessLogics/ClientLogic.cs index 7f53193..1e034ae 100644 --- a/JewelryStoreBusinessLogic/BusinessLogics/ClientLogic.cs +++ b/JewelryStoreBusinessLogic/BusinessLogics/ClientLogic.cs @@ -9,6 +9,7 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; +using System.Text.RegularExpressions; using System.Threading.Tasks; namespace JewelryStoreBusinessLogic.BusinessLogics @@ -108,7 +109,16 @@ namespace JewelryStoreBusinessLogic.BusinessLogics { throw new ArgumentNullException("Нет пароля клиента", nameof(model.Password)); } - _logger.LogInformation("Client. ClientFIO: {ClientFIO}. Email: {Email}. Id: {Id}", model.ClientFIO, model.Email, model.Id); + if (!Regex.IsMatch(model.Email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$", RegexOptions.IgnoreCase)) + { + throw new ArgumentException("Неправильно введенный email", nameof(model.Email)); + } + + if (!Regex.IsMatch(model.Password, @"^^((\w+\d+\W+)|(\w+\W+\d+)|(\d+\w+\W+)|(\d+\W+\w+)|(\W+\w+\d+)|(\W+\d+\w+))[\w\d\W]*$", RegexOptions.IgnoreCase)) + { + throw new ArgumentException("Неправильно введенный пароль", nameof(model.Password)); + } + _logger.LogInformation("Client. ClientFIO: {ClientFIO}. Email: {Email}. Id: {Id}", model.ClientFIO, model.Email, model.Id); var element = _clientStorage.GetElement(new ClientSearchModel { Email = model.Email diff --git a/JewelryStoreBusinessLogic/BusinessLogics/MessageInfoLogic.cs b/JewelryStoreBusinessLogic/BusinessLogics/MessageInfoLogic.cs new file mode 100644 index 0000000..6b9fc9e --- /dev/null +++ b/JewelryStoreBusinessLogic/BusinessLogics/MessageInfoLogic.cs @@ -0,0 +1,56 @@ +using JewelryStoreContracts.BindingModels; +using JewelryStoreContracts.BusinessLogicsContracts; +using JewelryStoreContracts.SearchModels; +using JewelryStoreContracts.StoragesContracts; +using JewelryStoreContracts.ViewModels; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JewelryStoreBusinessLogic.BusinessLogics +{ + public class MessageInfoLogic : IMessageInfoLogic + { + private readonly ILogger _logger; + private readonly IMessageInfoStorage _messageStorage; + + public MessageInfoLogic(ILogger logger, IMessageInfoStorage messageStorage) + { + _logger = logger; + _messageStorage = messageStorage; + } + + public bool Create(MessageInfoBindingModel model) + { + if (_messageStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + + return false; + } + + return true; + } + + public List? ReadList(MessageInfoSearchModel? model) + { + _logger.LogInformation("ReadList. MessageId:{MessageId}.ClientId:{ClientId} ", model?.MessageId, model?.ClientId); + var list = model == null ? _messageStorage.GetFullList() : _messageStorage.GetFilteredList(model); + + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + + return null; + } + + _logger.LogInformation("ReadList. Count: {Count} ", list.Count); + + return list; + } + } +} + diff --git a/JewelryStoreBusinessLogic/BusinessLogics/OrderLogic.cs b/JewelryStoreBusinessLogic/BusinessLogics/OrderLogic.cs index 7010a87..03d7d2a 100644 --- a/JewelryStoreBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/JewelryStoreBusinessLogic/BusinessLogics/OrderLogic.cs @@ -1,4 +1,5 @@ -using JewelryStoreContracts.BindingModels; +using JewelryStoreBusinessLogic.MailWorker; +using JewelryStoreContracts.BindingModels; using JewelryStoreContracts.BusinessLogicsContracts; using JewelryStoreContracts.SearchModels; using JewelryStoreContracts.StoragesContracts; @@ -17,12 +18,16 @@ namespace JewelryStoreBusinessLogic.BusinessLogics { private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; + private readonly AbstractMailWorker _mailWorker; + private readonly IClientLogic _clientLogic; - public OrderLogic(ILogger logger, IOrderStorage orderStorage) + public OrderLogic(ILogger logger, IOrderStorage orderStorage, AbstractMailWorker mailWorker, IClientLogic clientLogic) { _logger = logger; _orderStorage = orderStorage; - } + _mailWorker = mailWorker; + _clientLogic = clientLogic; + } public bool CreateOrder(OrderBindingModel model) { @@ -35,15 +40,16 @@ namespace JewelryStoreBusinessLogic.BusinessLogics } model.Status = OrderStatus.Принят; + var result = _orderStorage.Insert(model); - if (_orderStorage.Insert(model) == null) - { + if (result == null) + { model.Status = OrderStatus.Неизвестен; _logger.LogWarning("Insert operation failed"); return false; } - - return true; + SendOrderMessage(result.ClientId, $"Магазин драгоценностей, Заказ №{result.Id}", $"Заказ №{result.Id} от {result.DateCreate} на сумму {result.Sum:0.00} принят"); + return true; } public bool StatusUpdate(OrderBindingModel model, OrderStatus newStatus) @@ -75,18 +81,38 @@ namespace JewelryStoreBusinessLogic.BusinessLogics model.JewelId = vmodel.JewelId; model.Sum = vmodel.Sum; model.Count = vmodel.Count; + var result = _orderStorage.Update(model); - if (_orderStorage.Update(model) == null) + if (result == null) { _logger.LogWarning("Update operation failed"); return false; } - - return true; + SendOrderMessage(result.ClientId, $"Магазин драгоценностей, Заказ №{result.Id}", $"Заказ №{model.Id} изменен статус на {result.Status}"); + return true; } - public bool TakeOrderInWork(OrderBindingModel model) + private bool SendOrderMessage(int clientId, string subject, string text) + { + var client = _clientLogic.ReadElement(new() { Id = clientId }); + + if (client == null) + { + return false; + } + + _mailWorker.MailSendAsync(new() + { + MailAddress = client.Email, + Subject = subject, + Text = text + }); + + return true; + } + + public bool TakeOrderInWork(OrderBindingModel model) { return StatusUpdate(model, OrderStatus.Выполняется); } diff --git a/JewelryStoreBusinessLogic/JewelryStoreBusinessLogic.csproj b/JewelryStoreBusinessLogic/JewelryStoreBusinessLogic.csproj index c29c38b..6b32983 100644 --- a/JewelryStoreBusinessLogic/JewelryStoreBusinessLogic.csproj +++ b/JewelryStoreBusinessLogic/JewelryStoreBusinessLogic.csproj @@ -16,6 +16,7 @@ + diff --git a/JewelryStoreBusinessLogic/MailWorker/AbstractMailWorker.cs b/JewelryStoreBusinessLogic/MailWorker/AbstractMailWorker.cs new file mode 100644 index 0000000..c72d1a3 --- /dev/null +++ b/JewelryStoreBusinessLogic/MailWorker/AbstractMailWorker.cs @@ -0,0 +1,94 @@ +using JewelryStoreContracts.BindingModels; +using JewelryStoreContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JewelryStoreBusinessLogic.MailWorker +{ + public abstract class AbstractMailWorker + { + protected string _mailLogin = string.Empty; + protected string _mailPassword = string.Empty; + protected string _smtpClientHost = string.Empty; + protected int _smtpClientPort; + protected string _popHost = string.Empty; + protected int _popPort; + private readonly IMessageInfoLogic _messageInfoLogic; + private readonly IClientLogic _clientLogic; + private readonly ILogger _logger; + + public AbstractMailWorker(ILogger logger, IMessageInfoLogic messageInfoLogic, IClientLogic clientLogic) + { + _logger = logger; + _messageInfoLogic = messageInfoLogic; + _clientLogic = clientLogic; + } + + public void MailConfig(MailConfigBindingModel config) + { + _mailLogin = config.MailLogin; + _mailPassword = config.MailPassword; + _smtpClientHost = config.SmtpClientHost; + _smtpClientPort = config.SmtpClientPort; + _popHost = config.PopHost; + _popPort = config.PopPort; + _logger.LogDebug("Config: {login}, {password}, {clientHost}, {clientPOrt}, {popHost}, {popPort}", _mailLogin, _mailPassword, _smtpClientHost, _smtpClientPort, _popHost, _popPort); + } + + public async void MailSendAsync(MailSendInfoBindingModel info) + { + if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword)) + { + return; + } + + if (string.IsNullOrEmpty(_smtpClientHost) || _smtpClientPort == 0) + { + return; + } + + if (string.IsNullOrEmpty(info.MailAddress) || string.IsNullOrEmpty(info.Subject) || string.IsNullOrEmpty(info.Text)) + { + return; + } + + _logger.LogDebug("Send Mail: {To}, {Subject}", info.MailAddress, info.Subject); + + await SendMailAsync(info); + } + + public async void MailCheck() + { + if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword)) + { + return; + } + + if (string.IsNullOrEmpty(_popHost) || _popPort == 0) + { + return; + } + + if (_messageInfoLogic == null) + { + return; + } + + var list = await ReceiveMailAsync(); + _logger.LogDebug("Check Mail: {Count} new mails", list.Count); + + foreach (var mail in list) + { + mail.ClientId = _clientLogic.ReadElement(new() { Email = mail.SenderName })?.Id; + _messageInfoLogic.Create(mail); + } + } + + protected abstract Task SendMailAsync(MailSendInfoBindingModel info); + protected abstract Task> ReceiveMailAsync(); + } +} diff --git a/JewelryStoreBusinessLogic/MailWorker/MailKitWorker.cs b/JewelryStoreBusinessLogic/MailWorker/MailKitWorker.cs new file mode 100644 index 0000000..25a008e --- /dev/null +++ b/JewelryStoreBusinessLogic/MailWorker/MailKitWorker.cs @@ -0,0 +1,79 @@ +using JewelryStoreContracts.BindingModels; +using JewelryStoreContracts.BusinessLogicsContracts; +using MailKit.Net.Pop3; +using MailKit.Security; +using Microsoft.Extensions.Logging; +using System.Net; +using System.Net.Mail; +using System.Text; + +namespace JewelryStoreBusinessLogic.MailWorker +{ + public class MailKitWorker : AbstractMailWorker + { + public MailKitWorker(ILogger logger, IMessageInfoLogic messageInfoLogic, IClientLogic clientLogic) : base(logger, messageInfoLogic, clientLogic) { } + + protected override async Task SendMailAsync(MailSendInfoBindingModel info) + { + using var objMailMessage = new MailMessage(); + using var objSmtpClient = new SmtpClient(_smtpClientHost, _smtpClientPort); + + try + { + objMailMessage.From = new MailAddress(_mailLogin); + objMailMessage.To.Add(new MailAddress(info.MailAddress)); + objMailMessage.Subject = info.Subject; + objMailMessage.Body = info.Text; + objMailMessage.SubjectEncoding = Encoding.UTF8; + objMailMessage.BodyEncoding = Encoding.UTF8; + objSmtpClient.UseDefaultCredentials = false; + objSmtpClient.EnableSsl = true; + objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; + objSmtpClient.Credentials = new NetworkCredential(_mailLogin, _mailPassword); + + await Task.Run(() => objSmtpClient.Send(objMailMessage)); + } + catch (Exception) + { + throw; + } + } + + protected override async Task> ReceiveMailAsync() + { + var list = new List(); + using var client = new Pop3Client(); + await Task.Run(() => + { + try + { + client.Connect(_popHost, _popPort, SecureSocketOptions.SslOnConnect); + client.Authenticate(_mailLogin, _mailPassword); + for (int i = 0; i < client.Count; i++) + { + var message = client.GetMessage(i); + foreach (var mail in message.From.Mailboxes) + { + list.Add(new MessageInfoBindingModel + { + DateDelivery = message.Date.DateTime, + MessageId = message.MessageId, + SenderName = mail.Address, + Subject = message.Subject, + Body = message.TextBody + }); + } + } + } + catch (AuthenticationException) + { + } + finally + { + client.Disconnect(true); + } + }); + return list; + } + } +} diff --git a/JewelryStoreClientApp/APIClient.cs b/JewelryStoreClientApp/APIClient.cs index 95389a1..d747788 100644 --- a/JewelryStoreClientApp/APIClient.cs +++ b/JewelryStoreClientApp/APIClient.cs @@ -5,41 +5,47 @@ using System.Text; namespace JewelryStoreClientApp { - public class APIClient - { - private static readonly HttpClient _client = new(); - public static ClientViewModel? Client { get; set; } = null; - public static void Connect(IConfiguration configuration) - { - _client.BaseAddress = new Uri(configuration["IPAddress"]); - _client.DefaultRequestHeaders.Accept.Clear(); - _client.DefaultRequestHeaders.Accept.Add(new - MediaTypeWithQualityHeaderValue("application/json")); - } - public static T? GetRequest(string requestUrl) - { - var response = _client.GetAsync(requestUrl); - var result = response.Result.Content.ReadAsStringAsync().Result; - if (response.Result.IsSuccessStatusCode) - { - return JsonConvert.DeserializeObject(result); - } - else - { - throw new Exception(result); - } - } - public static void PostRequest(string requestUrl, T model) - { - var json = JsonConvert.SerializeObject(model); - var data = new StringContent(json, Encoding.UTF8, "application/json"); - var response = _client.PostAsync(requestUrl, data); - var result = response.Result.Content.ReadAsStringAsync().Result; - if (!response.Result.IsSuccessStatusCode) - { - throw new Exception(result); - } - } + public class APIClient + { + private static readonly HttpClient _client = new(); - } + public static ClientViewModel? Client { get; set; } = null; + + public static void Connect(IConfiguration configuration) + { + _client.BaseAddress = new Uri(configuration["IPAddress"]); + _client.DefaultRequestHeaders.Accept.Clear(); + _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + } + + public static T? GetRequest(string requestUrl) + { + var response = _client.GetAsync(requestUrl); + var result = response.Result.Content.ReadAsStringAsync().Result; + if (response.Result.IsSuccessStatusCode) + { + return JsonConvert.DeserializeObject(result); + } + else + { + throw new Exception(result); + } + } + + public static void PostRequest(string requestUrl, T model) + { + var json = JsonConvert.SerializeObject(model); + var data = new StringContent(json, Encoding.UTF8, "application/json"); + + var response = _client.PostAsync(requestUrl, data); + + var result = response.Result.Content.ReadAsStringAsync().Result; + if (!response.Result.IsSuccessStatusCode) + { + throw new Exception(result); + } + } + } } + + diff --git a/JewelryStoreClientApp/Controllers/HomeController.cs b/JewelryStoreClientApp/Controllers/HomeController.cs index 3b5d82c..1189237 100644 --- a/JewelryStoreClientApp/Controllers/HomeController.cs +++ b/JewelryStoreClientApp/Controllers/HomeController.cs @@ -149,5 +149,14 @@ namespace JewelryStoreClientApp.Controllers return count * (prod?.Price ?? 1); } + [HttpGet] + public IActionResult Mails() + { + if (APIClient.Client == null) + { + return Redirect("~/Home/Enter"); + } + return View(APIClient.GetRequest>($"api/client/getmessages?clientId={APIClient.Client.Id}")); + } } } \ No newline at end of file diff --git a/JewelryStoreClientApp/Views/Home/Mails.cshtml b/JewelryStoreClientApp/Views/Home/Mails.cshtml new file mode 100644 index 0000000..ba3e78c --- /dev/null +++ b/JewelryStoreClientApp/Views/Home/Mails.cshtml @@ -0,0 +1,54 @@ +@using JewelryStoreContracts.ViewModels + +@model List + +@{ + ViewData["Title"] = "Mails"; +} + +
+

Заказы

+
+ + +
+ @{ + if (Model == null) + { +

Авторизируйтесь

+ return; + } + + + + + + + + + + + @foreach (var item in Model) + { + + + + + + } + +
+ Дата письма + + Заголовок + + Текст +
+ @Html.DisplayFor(modelItem => item.DateDelivery) + + @Html.DisplayFor(modelItem => item.Subject) + + @Html.DisplayFor(modelItem => item.Body) +
+ } +
\ No newline at end of file diff --git a/JewelryStoreClientApp/Views/Shared/_Layout.cshtml b/JewelryStoreClientApp/Views/Shared/_Layout.cshtml index d2de4b5..d787fc2 100644 --- a/JewelryStoreClientApp/Views/Shared/_Layout.cshtml +++ b/JewelryStoreClientApp/Views/Shared/_Layout.cshtml @@ -26,6 +26,9 @@ + diff --git a/JewelryStoreContracts/BindingModels/MailConfigBindingModel.cs b/JewelryStoreContracts/BindingModels/MailConfigBindingModel.cs new file mode 100644 index 0000000..feecb5d --- /dev/null +++ b/JewelryStoreContracts/BindingModels/MailConfigBindingModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JewelryStoreContracts.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/JewelryStoreContracts/BindingModels/MailSendInfoBindingModel.cs b/JewelryStoreContracts/BindingModels/MailSendInfoBindingModel.cs new file mode 100644 index 0000000..aba0bf0 --- /dev/null +++ b/JewelryStoreContracts/BindingModels/MailSendInfoBindingModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JewelryStoreContracts.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/JewelryStoreContracts/BindingModels/MessageInfoBindingModel.cs b/JewelryStoreContracts/BindingModels/MessageInfoBindingModel.cs new file mode 100644 index 0000000..defcf64 --- /dev/null +++ b/JewelryStoreContracts/BindingModels/MessageInfoBindingModel.cs @@ -0,0 +1,19 @@ +using JewelryStoreDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JewelryStoreContracts.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/JewelryStoreContracts/BusinessLogicsContracts/IMessageInfoLogic.cs b/JewelryStoreContracts/BusinessLogicsContracts/IMessageInfoLogic.cs new file mode 100644 index 0000000..263f61d --- /dev/null +++ b/JewelryStoreContracts/BusinessLogicsContracts/IMessageInfoLogic.cs @@ -0,0 +1,17 @@ +using JewelryStoreContracts.BindingModels; +using JewelryStoreContracts.SearchModels; +using JewelryStoreContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JewelryStoreContracts.BusinessLogicsContracts +{ + public interface IMessageInfoLogic + { + List? ReadList(MessageInfoSearchModel? model); + bool Create(MessageInfoBindingModel model); + } +} diff --git a/JewelryStoreContracts/SearchModels/MessageInfoSearchModel.cs b/JewelryStoreContracts/SearchModels/MessageInfoSearchModel.cs new file mode 100644 index 0000000..1758850 --- /dev/null +++ b/JewelryStoreContracts/SearchModels/MessageInfoSearchModel.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JewelryStoreContracts.SearchModels +{ + public class MessageInfoSearchModel + { + public int? ClientId { get; set; } + public string? MessageId { get; set; } + } +} diff --git a/JewelryStoreContracts/StoragesContracts/IMessageInfoStorage.cs b/JewelryStoreContracts/StoragesContracts/IMessageInfoStorage.cs new file mode 100644 index 0000000..866c1fb --- /dev/null +++ b/JewelryStoreContracts/StoragesContracts/IMessageInfoStorage.cs @@ -0,0 +1,19 @@ +using JewelryStoreContracts.BindingModels; +using JewelryStoreContracts.SearchModels; +using JewelryStoreContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JewelryStoreContracts.StoragesContracts +{ + public interface IMessageInfoStorage + { + List GetFullList(); + List GetFilteredList(MessageInfoSearchModel model); + MessageInfoViewModel? GetElement(MessageInfoSearchModel model); + MessageInfoViewModel? Insert(MessageInfoBindingModel model); + } +} diff --git a/JewelryStoreContracts/ViewModels/MessageInfoViewModel.cs b/JewelryStoreContracts/ViewModels/MessageInfoViewModel.cs new file mode 100644 index 0000000..caadf29 --- /dev/null +++ b/JewelryStoreContracts/ViewModels/MessageInfoViewModel.cs @@ -0,0 +1,29 @@ +using JewelryStoreDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JewelryStoreContracts.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/JewelryStoreDataModels/Models/IMessageInfoModel.cs b/JewelryStoreDataModels/Models/IMessageInfoModel.cs new file mode 100644 index 0000000..120de88 --- /dev/null +++ b/JewelryStoreDataModels/Models/IMessageInfoModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JewelryStoreDataModels.Models +{ + public interface IMessageInfoModel + { + string MessageId { get; } + int? ClientId { get; } + string SenderName { get; } + DateTime DateDelivery { get; } + string Subject { get; } + string Body { get; } + } +} diff --git a/JewelryStoreDatabaseImplement/Implements/ClientStorage.cs b/JewelryStoreDatabaseImplement/Implements/ClientStorage.cs index ec6754e..56f8d8e 100644 --- a/JewelryStoreDatabaseImplement/Implements/ClientStorage.cs +++ b/JewelryStoreDatabaseImplement/Implements/ClientStorage.cs @@ -40,12 +40,12 @@ namespace JewelryStoreDatabaseImplement.Implements public List GetFilteredList(ClientSearchModel model) { - if (string.IsNullOrEmpty(model.ClientFIO)) + if (string.IsNullOrEmpty(model.Email)) { return new(); } using var context = new JewelryStoreDataBase(); - return context.Clients.Where(x => x.ClientFIO.Contains(model.ClientFIO)).Select(x => x.GetViewModel).ToList(); + return context.Clients.Where(x => x.Email.Contains(model.Email)).Select(x => x.GetViewModel).ToList(); } public List GetFullList() diff --git a/JewelryStoreDatabaseImplement/Implements/MessageInfoStorage.cs b/JewelryStoreDatabaseImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..11f87e3 --- /dev/null +++ b/JewelryStoreDatabaseImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,56 @@ +using JewelryStoreContracts.BindingModels; +using JewelryStoreContracts.SearchModels; +using JewelryStoreContracts.StoragesContracts; +using JewelryStoreContracts.ViewModels; +using JewelryStoreDatabaseImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JewelryStoreDatabaseImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (model.MessageId == null) + return null; + using var context = new JewelryStoreDataBase(); + return context.Messages.FirstOrDefault(x => x.MessageId == model.MessageId)?.GetViewModel; + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + if (!model.ClientId.HasValue) + return new(); + using var context = new JewelryStoreDataBase(); + return context.Messages + .Where(x => x.ClientId == model.ClientId) + .Select(x => x.GetViewModel) + .ToList(); + } + + public List GetFullList() + { + using var context = new JewelryStoreDataBase(); + return context.Messages + .Select(x => x.GetViewModel) + .ToList(); + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = Message.Create(model); + if (newMessage == null) + { + return null; + } + using var context = new JewelryStoreDataBase(); + context.Messages.Add(newMessage); + context.SaveChanges(); + return newMessage.GetViewModel; + } + } +} diff --git a/JewelryStoreDatabaseImplement/JewelryStoreDataBase.cs b/JewelryStoreDatabaseImplement/JewelryStoreDataBase.cs index 244174f..1695cc1 100644 --- a/JewelryStoreDatabaseImplement/JewelryStoreDataBase.cs +++ b/JewelryStoreDatabaseImplement/JewelryStoreDataBase.cs @@ -27,8 +27,8 @@ namespace JewelryStoreDatabaseImplement 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/JewelryStoreDatabaseImplement/Migrations/20230418091905_InitialCreate.Designer.cs b/JewelryStoreDatabaseImplement/Migrations/20230502054647_Init.Designer.cs similarity index 84% rename from JewelryStoreDatabaseImplement/Migrations/20230418091905_InitialCreate.Designer.cs rename to JewelryStoreDatabaseImplement/Migrations/20230502054647_Init.Designer.cs index 6fff767..09e8b2d 100644 --- a/JewelryStoreDatabaseImplement/Migrations/20230418091905_InitialCreate.Designer.cs +++ b/JewelryStoreDatabaseImplement/Migrations/20230502054647_Init.Designer.cs @@ -12,8 +12,8 @@ using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace JewelryStoreDatabaseImplement.Migrations { [DbContext(typeof(JewelryStoreDataBase))] - [Migration("20230418091905_InitialCreate")] - partial class InitialCreate + [Migration("20230502054647_Init")] + partial class Init { /// protected override void BuildTargetModel(ModelBuilder modelBuilder) @@ -143,6 +143,37 @@ namespace JewelryStoreDatabaseImplement.Migrations b.ToTable("JewelComponents"); }); + modelBuilder.Entity("JewelryStoreDatabaseImplement.Models.Message", b => + { + b.Property("MessageId") + .HasColumnType("nvarchar(450)"); + + b.Property("Body") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .IsRequired() + .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("JewelryStoreDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -209,6 +240,17 @@ namespace JewelryStoreDatabaseImplement.Migrations b.Navigation("Jewel"); }); + modelBuilder.Entity("JewelryStoreDatabaseImplement.Models.Message", b => + { + b.HasOne("JewelryStoreDatabaseImplement.Models.Client", "Client") + .WithMany("Messages") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Client"); + }); + modelBuilder.Entity("JewelryStoreDatabaseImplement.Models.Order", b => { b.HasOne("JewelryStoreDatabaseImplement.Models.Client", "Client") @@ -236,6 +278,8 @@ namespace JewelryStoreDatabaseImplement.Migrations modelBuilder.Entity("JewelryStoreDatabaseImplement.Models.Client", b => { + b.Navigation("Messages"); + b.Navigation("Orders"); }); diff --git a/JewelryStoreDatabaseImplement/Migrations/20230418091905_InitialCreate.cs b/JewelryStoreDatabaseImplement/Migrations/20230502054647_Init.cs similarity index 84% rename from JewelryStoreDatabaseImplement/Migrations/20230418091905_InitialCreate.cs rename to JewelryStoreDatabaseImplement/Migrations/20230502054647_Init.cs index 3435bf1..2937438 100644 --- a/JewelryStoreDatabaseImplement/Migrations/20230418091905_InitialCreate.cs +++ b/JewelryStoreDatabaseImplement/Migrations/20230502054647_Init.cs @@ -6,7 +6,7 @@ using Microsoft.EntityFrameworkCore.Migrations; namespace JewelryStoreDatabaseImplement.Migrations { /// - public partial class InitialCreate : Migration + public partial class Init : Migration { /// protected override void Up(MigrationBuilder migrationBuilder) @@ -70,6 +70,28 @@ namespace JewelryStoreDatabaseImplement.Migrations table.PrimaryKey("PK_Jewels", x => x.Id); }); + migrationBuilder.CreateTable( + name: "Messages", + columns: table => new + { + MessageId = table.Column(type: "nvarchar(450)", nullable: false), + ClientId = table.Column(type: "int", nullable: false), + 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", + onDelete: ReferentialAction.Cascade); + }); + migrationBuilder.CreateTable( name: "JewelComponents", columns: table => new @@ -145,6 +167,11 @@ namespace JewelryStoreDatabaseImplement.Migrations table: "JewelComponents", column: "JewelId"); + migrationBuilder.CreateIndex( + name: "IX_Messages_ClientId", + table: "Messages", + column: "ClientId"); + migrationBuilder.CreateIndex( name: "IX_Orders_ClientId", table: "Orders", @@ -167,6 +194,9 @@ namespace JewelryStoreDatabaseImplement.Migrations migrationBuilder.DropTable( name: "JewelComponents"); + migrationBuilder.DropTable( + name: "Messages"); + migrationBuilder.DropTable( name: "Orders"); diff --git a/JewelryStoreDatabaseImplement/Migrations/JewelryStoreDataBaseModelSnapshot.cs b/JewelryStoreDatabaseImplement/Migrations/JewelryStoreDataBaseModelSnapshot.cs index 599816d..a4f12d1 100644 --- a/JewelryStoreDatabaseImplement/Migrations/JewelryStoreDataBaseModelSnapshot.cs +++ b/JewelryStoreDatabaseImplement/Migrations/JewelryStoreDataBaseModelSnapshot.cs @@ -140,6 +140,37 @@ namespace JewelryStoreDatabaseImplement.Migrations b.ToTable("JewelComponents"); }); + modelBuilder.Entity("JewelryStoreDatabaseImplement.Models.Message", b => + { + b.Property("MessageId") + .HasColumnType("nvarchar(450)"); + + b.Property("Body") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .IsRequired() + .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("JewelryStoreDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -206,6 +237,17 @@ namespace JewelryStoreDatabaseImplement.Migrations b.Navigation("Jewel"); }); + modelBuilder.Entity("JewelryStoreDatabaseImplement.Models.Message", b => + { + b.HasOne("JewelryStoreDatabaseImplement.Models.Client", "Client") + .WithMany("Messages") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Client"); + }); + modelBuilder.Entity("JewelryStoreDatabaseImplement.Models.Order", b => { b.HasOne("JewelryStoreDatabaseImplement.Models.Client", "Client") @@ -233,6 +275,8 @@ namespace JewelryStoreDatabaseImplement.Migrations modelBuilder.Entity("JewelryStoreDatabaseImplement.Models.Client", b => { + b.Navigation("Messages"); + b.Navigation("Orders"); }); diff --git a/JewelryStoreDatabaseImplement/Models/Client.cs b/JewelryStoreDatabaseImplement/Models/Client.cs index dc30528..b3248da 100644 --- a/JewelryStoreDatabaseImplement/Models/Client.cs +++ b/JewelryStoreDatabaseImplement/Models/Client.cs @@ -23,7 +23,10 @@ namespace JewelryStoreDatabaseImplement.Models [ForeignKey("ClientId")] public virtual List Orders { get; set; } = new(); - public static Client? Create(ClientBindingModel model) + + [ForeignKey("ClientId")] + public virtual List Messages { get; set; } = new(); + public static Client? Create(ClientBindingModel model) { if (model == null) { diff --git a/JewelryStoreDatabaseImplement/Models/Message.cs b/JewelryStoreDatabaseImplement/Models/Message.cs new file mode 100644 index 0000000..6e9aaf3 --- /dev/null +++ b/JewelryStoreDatabaseImplement/Models/Message.cs @@ -0,0 +1,56 @@ +using JewelryStoreContracts.BindingModels; +using JewelryStoreContracts.ViewModels; +using JewelryStoreDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JewelryStoreDatabaseImplement.Models +{ + public class Message: IMessageInfoModel + { + [Key] + public string MessageId { get; private set; } = string.Empty; + public int? ClientId { get; private set; } + [Required] + public string SenderName { get; private set; } = string.Empty; + [Required] + public DateTime DateDelivery { get; private set; } = DateTime.Now; + [Required] + public string Subject { get; private set; } = string.Empty; + [Required] + public string Body { get; private set; } = string.Empty; + + public virtual Client Client { get; set; } + + public static Message? 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/JewelryStoreFileImplement/DataFileSingleton.cs b/JewelryStoreFileImplement/DataFileSingleton.cs index 40f68f9..1bdd6cc 100644 --- a/JewelryStoreFileImplement/DataFileSingleton.cs +++ b/JewelryStoreFileImplement/DataFileSingleton.cs @@ -16,15 +16,19 @@ namespace JewelryStoreFileImplement private readonly string JewelFileName = "Jewel.xml"; private readonly string ClientFileName = "Client.xml"; private readonly string ImplementerFileName = "Implementer.xml"; + private readonly string MessageFileName = "Message.xml"; - public List Components { get; private set; } + + public List Components { get; private set; } public List Orders { get; private set; } public List Jewels { 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() + + public static DataFileSingleton GetInstance() { if (instance == null) { @@ -37,19 +41,21 @@ namespace JewelryStoreFileImplement public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement); public void SaveClients() => SaveData(Clients, OrderFileName, "Clients", x => x.GetXElement); public void SaveImplementers() => SaveData(Implementers, OrderFileName, "Implementers", x => x.GetXElement); + public void SaveMessages() => SaveData(Messages, MessageFileName, "Messages", x => x.GetXElement); - private DataFileSingleton() + private DataFileSingleton() { Components = LoadData(ComponentFileName, "Component", x =>Component.Create(x)!)!; Jewels = LoadData(JewelFileName, "Jewel", x => Jewel.Create(x)!)!; 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(MessageFileName, "Message", x => Message.Create(x)!)!; - } - private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) + } + private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) { if (File.Exists(filename)) { diff --git a/JewelryStoreFileImplement/Implements/ClientStorage.cs b/JewelryStoreFileImplement/Implements/ClientStorage.cs index 5dd0ebc..032a79b 100644 --- a/JewelryStoreFileImplement/Implements/ClientStorage.cs +++ b/JewelryStoreFileImplement/Implements/ClientStorage.cs @@ -24,12 +24,12 @@ namespace JewelryStoreFileImplement.Implements } public List GetFilteredList(ClientSearchModel model) { - if (string.IsNullOrEmpty(model.ClientFIO)) + if (string.IsNullOrEmpty(model.Email)) { return new(); } return source.Clients - .Where(x => x.ClientFIO.Contains(model.ClientFIO)) + .Where(x => x.Email.Contains(model.Email)) .Select(x => x.GetViewModel) .ToList(); } diff --git a/JewelryStoreFileImplement/Implements/MessageInfoStorage.cs b/JewelryStoreFileImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..30238e6 --- /dev/null +++ b/JewelryStoreFileImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,57 @@ +using JewelryStoreContracts.BindingModels; +using JewelryStoreContracts.SearchModels; +using JewelryStoreContracts.StoragesContracts; +using JewelryStoreContracts.ViewModels; +using JewelryStoreFileImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JewelryStoreFileImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + private readonly DataFileSingleton source; + public MessageInfoStorage() + { + source = DataFileSingleton.GetInstance(); + } + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (model.MessageId == null) + return null; + return source.Messages.FirstOrDefault(x => x.MessageId == model.MessageId)?.GetViewModel; + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + if (!model.ClientId.HasValue) + return new(); + 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 = Message.Create(model); + if (newMessage == null) + { + return null; + } + source.Messages.Add(newMessage); + source.SaveMessages(); + return newMessage.GetViewModel; + } + } +} diff --git a/JewelryStoreFileImplement/Models/Message.cs b/JewelryStoreFileImplement/Models/Message.cs new file mode 100644 index 0000000..03ba95d --- /dev/null +++ b/JewelryStoreFileImplement/Models/Message.cs @@ -0,0 +1,80 @@ +using JewelryStoreContracts.BindingModels; +using JewelryStoreContracts.ViewModels; +using JewelryStoreDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace JewelryStoreFileImplement.Models +{ + public class Message : 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 Message? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Subject = model.Subject, + DateDelivery = model.DateDelivery, + SenderName = model.SenderName, + ClientId = model.ClientId, + MessageId = model.MessageId + }; + } + + public static Message? Create(XElement element) + { + if (element == null) + { + return null; + } + return new() + { + Body = element.Attribute("Body")!.Value, + Subject = element.Attribute("Subject")!.Value, + DateDelivery = Convert.ToDateTime(element.Attribute("DateDelivery")!.Value), + SenderName = element.Attribute("SenderName")!.Value, + ClientId = Convert.ToInt32(element.Attribute("ClientId")!.Value), + MessageId = element.Attribute("MessageId")!.Value, + }; + } + + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Subject = Subject, + DateDelivery = DateDelivery, + SenderName = SenderName, + ClientId = ClientId, + MessageId = MessageId + }; + + public XElement GetXElement => new("MessageInfo", + new XAttribute("Subject", Subject), + new XAttribute("Body", Body), + new XAttribute("ClientId", ClientId), + new XAttribute("MessageId", MessageId), + new XAttribute("SenderName", SenderName), + new XAttribute("DateDelivery", DateDelivery) + ); + } +} diff --git a/JewelryStoreListImplement/DataListSingleton.cs b/JewelryStoreListImplement/DataListSingleton.cs index a9b35b4..f308324 100644 --- a/JewelryStoreListImplement/DataListSingleton.cs +++ b/JewelryStoreListImplement/DataListSingleton.cs @@ -15,15 +15,18 @@ namespace JewelryStoreListImplement public List Jewels { get; set; } public List Clients { get; set; } public List Implementers { get; set; } + public List Messages { get; set; } - private DataListSingleton() + private DataListSingleton() { Components = new List(); Orders = new List(); Jewels = new List(); Implementers = new List(); - } - public static DataListSingleton GetInstance() + Messages = new List(); + + } + public static DataListSingleton GetInstance() { if (_instance == null) { diff --git a/JewelryStoreListImplement/Implements/ClientStorage.cs b/JewelryStoreListImplement/Implements/ClientStorage.cs index 5fdd08a..e385e3d 100644 --- a/JewelryStoreListImplement/Implements/ClientStorage.cs +++ b/JewelryStoreListImplement/Implements/ClientStorage.cs @@ -30,13 +30,13 @@ namespace JewelryStoreListImplement.Implements public List GetFilteredList(ClientSearchModel model) { var result = new List(); - if (string.IsNullOrEmpty(model.ClientFIO)) + if (string.IsNullOrEmpty(model.Email)) { return result; } foreach (var client in _source.Clients) { - if (client.ClientFIO.Contains(model.ClientFIO)) + if (client.Email.Contains(model.Email)) { result.Add(client.GetViewModel); } diff --git a/JewelryStoreListImplement/Implements/MessageInfoStorage.cs b/JewelryStoreListImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..f5c82d3 --- /dev/null +++ b/JewelryStoreListImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,73 @@ +using JewelryStoreContracts.BindingModels; +using JewelryStoreContracts.SearchModels; +using JewelryStoreContracts.StoragesContracts; +using JewelryStoreContracts.ViewModels; +using JewelryStoreListImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JewelryStoreListImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + private readonly DataListSingleton _source; + public MessageInfoStorage() + { + _source = DataListSingleton.GetInstance(); + } + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (model.MessageId == null) + { + return null; + } + foreach (var message in _source.Messages) + { + if (model.MessageId.Equals(message.MessageId)) + return message.GetViewModel; + } + return null; + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + if (!model.ClientId.HasValue) + { + return new(); + } + var result = new List(); + foreach (var item in _source.Messages) + { + if (item.ClientId == model.ClientId) + { + result.Add(item.GetViewModel); + } + } + return result; + } + + public List GetFullList() + { + var result = new List(); + foreach (var item in _source.Messages) + { + result.Add(item.GetViewModel); + } + return result; + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = Message.Create(model); + if (newMessage == null) + { + return null; + } + _source.Messages.Add(newMessage); + return newMessage.GetViewModel; + } + } +} diff --git a/JewelryStoreListImplement/Models/Message.cs b/JewelryStoreListImplement/Models/Message.cs new file mode 100644 index 0000000..48376a6 --- /dev/null +++ b/JewelryStoreListImplement/Models/Message.cs @@ -0,0 +1,53 @@ +using JewelryStoreContracts.BindingModels; +using JewelryStoreContracts.ViewModels; +using JewelryStoreDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JewelryStoreListImplement.Models +{ + public class Message : 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 Message? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Subject = model.Subject, + DateDelivery = model.DateDelivery, + SenderName = model.SenderName, + ClientId = model.ClientId, + MessageId = model.MessageId + }; + } + + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Subject = Subject, + DateDelivery = DateDelivery, + SenderName = SenderName, + ClientId = ClientId, + MessageId = MessageId + }; + } +} diff --git a/JewelryStoreRestApi/Controllers/ClientController.cs b/JewelryStoreRestApi/Controllers/ClientController.cs index a13f57d..83011d9 100644 --- a/JewelryStoreRestApi/Controllers/ClientController.cs +++ b/JewelryStoreRestApi/Controllers/ClientController.cs @@ -11,13 +11,18 @@ namespace JewelryStoreRestApi.Controllers public class ClientController : Controller { private readonly ILogger _logger; + private readonly IClientLogic _logic; - public ClientController(IClientLogic logic, ILogger - logger) + + 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) { @@ -35,6 +40,7 @@ namespace JewelryStoreRestApi.Controllers throw; } } + [HttpPost] public void Register(ClientBindingModel model) { @@ -48,6 +54,7 @@ namespace JewelryStoreRestApi.Controllers throw; } } + [HttpPost] public void UpdateData(ClientBindingModel model) { @@ -61,5 +68,22 @@ namespace JewelryStoreRestApi.Controllers throw; } } + + [HttpGet] + public List? GetMessages(int clientId) + { + try + { + return _mailLogic.ReadList(new MessageInfoSearchModel + { + ClientId = clientId + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения писем клиента"); + throw; + } + } } } diff --git a/JewelryStoreRestApi/Program.cs b/JewelryStoreRestApi/Program.cs index a84bf51..bda72b2 100644 --- a/JewelryStoreRestApi/Program.cs +++ b/JewelryStoreRestApi/Program.cs @@ -1,4 +1,6 @@ using JewelryStoreBusinessLogic.BusinessLogics; +using JewelryStoreBusinessLogic.MailWorker; +using JewelryStoreContracts.BindingModels; using JewelryStoreContracts.BusinessLogicsContracts; using JewelryStoreContracts.StoragesContracts; using JewelryStoreDatabaseImplement.Implements; @@ -16,6 +18,9 @@ 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 +36,17 @@ 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/JewelryStoreRestApi/appsettings.json b/JewelryStoreRestApi/appsettings.json index 10f68b8..533a1a4 100644 --- a/JewelryStoreRestApi/appsettings.json +++ b/JewelryStoreRestApi/appsettings.json @@ -5,5 +5,11 @@ "Microsoft.AspNetCore": "Warning" } }, - "AllowedHosts": "*" + "AllowedHosts": "*", + "SmtpClientHost": "smtp.gmail.com", + "SmtpClientPort": "587", + "PopHost": "pop.gmail.com", + "PopPort": "995", + "MailLogin": "labsrpp@gmail.com", + "MailPassword": "iuhd xvlg ntva eeqm" }