From 4fb8c4ad661eb19f4201bd2c7e45a21d1e428a4f Mon Sep 17 00:00:00 2001 From: ujijrujijr Date: Sun, 5 May 2024 18:46:39 +0400 Subject: [PATCH 1/2] =?UTF-8?q?=D0=97=D0=B0=D0=BB=D0=B8=D0=BB=20=D0=BB?= =?UTF-8?q?=D0=B0=D0=B1=207?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- GarmentFactory/App.config | 11 + GarmentFactory/FormMails.Designer.cs | 67 ++++ GarmentFactory/FormMails.cs | 53 ++++ GarmentFactory/FormMails.resx | 120 +++++++ GarmentFactory/FormMain.Designer.cs | 11 +- GarmentFactory/FormMain.cs | 9 + GarmentFactory/GarmentFactory.sln | 4 +- GarmentFactory/GarmentFactoryView.csproj | 3 + GarmentFactory/Program.cs | 36 ++- .../BusinessLogics/ClientLogic.cs | 10 +- .../BusinessLogics/MessageInfoLogic.cs | 90 ++++++ .../BusinessLogics/OrderLogic.cs | 29 +- .../GarmentFactoryBusinessLogic.csproj | 1 + .../MailWorker/AbstractMailWorker.cs | 86 +++++ .../MailWorker/MailKitWorker.cs | 82 +++++ .../Controllers/HomeController.cs | 13 +- .../Views/Home/Mails.cshtml | 55 ++++ .../Views/Shared/_Layout.cshtml | 3 + .../BindingModels/MailConfigBindingModel.cs | 18 ++ .../BindingModels/MailSendInfoBindingModel.cs | 15 + .../BindingModels/MessageInfoBindingModel.cs | 19 ++ .../IMessageInfoLogic.cs | 17 + .../SearchModels/MessageInfoSearchModel.cs | 14 + .../StoragesContracts/IMessageInfoStorage.cs | 19 ++ .../ViewModels/MessageInfoViewModel.cs | 29 ++ .../ViewModels/OrderViewModel.cs | 4 +- .../Models/IMessageInfoModel.cs | 18 ++ .../GarmentFactoryDatabase.cs | 2 + .../Implements/ClientStorage.cs | 6 +- .../Implements/MessageInfoStorage.cs | 55 ++++ .../20240505113527_AddedMails.Designer.cs | 298 ++++++++++++++++++ .../Migrations/20240505113527_AddedMails.cs | 48 +++ .../20240505123925_AddedMails_1.Designer.cs | 298 ++++++++++++++++++ .../Migrations/20240505123925_AddedMails_1.cs | 22 ++ .../GarmentFactoryDatabaseModelSnapshot.cs | 41 +++ .../Models/Client.cs | 5 +- .../Models/MessageInfo.cs | 63 ++++ .../Models/Order.cs | 1 + .../DataFileSingleton.cs | 7 + .../Implements/MessageInfoStorage.cs | 58 ++++ .../Models/MessageInfo.cs | 80 +++++ .../DataListSingleton.cs | 4 +- .../Implements/MessageInfoStorage.cs | 68 ++++ .../Models/MessageInfo.cs | 53 ++++ .../Controllers/ClientController.cs | 23 +- GarmentFactoryRestApi/Program.cs | 18 ++ GarmentFactoryRestApi/appsettings.json | 9 +- 47 files changed, 1969 insertions(+), 26 deletions(-) create mode 100644 GarmentFactory/App.config create mode 100644 GarmentFactory/FormMails.Designer.cs create mode 100644 GarmentFactory/FormMails.cs create mode 100644 GarmentFactory/FormMails.resx create mode 100644 GarmentFactoryBusinessLogic/BusinessLogics/MessageInfoLogic.cs create mode 100644 GarmentFactoryBusinessLogic/MailWorker/AbstractMailWorker.cs create mode 100644 GarmentFactoryBusinessLogic/MailWorker/MailKitWorker.cs create mode 100644 GarmentFactoryClientApp/Views/Home/Mails.cshtml create mode 100644 GarmentFactoryContracts/BindingModels/MailConfigBindingModel.cs create mode 100644 GarmentFactoryContracts/BindingModels/MailSendInfoBindingModel.cs create mode 100644 GarmentFactoryContracts/BindingModels/MessageInfoBindingModel.cs create mode 100644 GarmentFactoryContracts/BusinessLogicsContracts/IMessageInfoLogic.cs create mode 100644 GarmentFactoryContracts/SearchModels/MessageInfoSearchModel.cs create mode 100644 GarmentFactoryContracts/StoragesContracts/IMessageInfoStorage.cs create mode 100644 GarmentFactoryContracts/ViewModels/MessageInfoViewModel.cs create mode 100644 GarmentFactoryDataModels/Models/IMessageInfoModel.cs create mode 100644 GarmentFactoryDatabaseImplement/Implements/MessageInfoStorage.cs create mode 100644 GarmentFactoryDatabaseImplement/Migrations/20240505113527_AddedMails.Designer.cs create mode 100644 GarmentFactoryDatabaseImplement/Migrations/20240505113527_AddedMails.cs create mode 100644 GarmentFactoryDatabaseImplement/Migrations/20240505123925_AddedMails_1.Designer.cs create mode 100644 GarmentFactoryDatabaseImplement/Migrations/20240505123925_AddedMails_1.cs create mode 100644 GarmentFactoryDatabaseImplement/Models/MessageInfo.cs create mode 100644 GarmentFactoryFileImplement/Implements/MessageInfoStorage.cs create mode 100644 GarmentFactoryFileImplement/Models/MessageInfo.cs create mode 100644 GarmentFactoryListImplement/Implements/MessageInfoStorage.cs create mode 100644 GarmentFactoryListImplement/Models/MessageInfo.cs diff --git a/GarmentFactory/App.config b/GarmentFactory/App.config new file mode 100644 index 0000000..cdd7638 --- /dev/null +++ b/GarmentFactory/App.config @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/GarmentFactory/FormMails.Designer.cs b/GarmentFactory/FormMails.Designer.cs new file mode 100644 index 0000000..24b207e --- /dev/null +++ b/GarmentFactory/FormMails.Designer.cs @@ -0,0 +1,67 @@ +namespace GarmentFactoryView +{ + 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.AllowUserToAddRows = false; + this.dataGridView.AllowUserToDeleteRows = false; + this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView.Dock = System.Windows.Forms.DockStyle.Fill; + this.dataGridView.Location = new System.Drawing.Point(0, 0); + this.dataGridView.Name = "dataGridView"; + this.dataGridView.ReadOnly = true; + this.dataGridView.RowHeadersWidth = 51; + this.dataGridView.RowTemplate.Height = 29; + this.dataGridView.Size = new System.Drawing.Size(786, 270); + this.dataGridView.TabIndex = 0; + // + // FormMail + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(786, 270); + this.Controls.Add(this.dataGridView); + this.Name = "FormMails"; + this.Text = "Письма"; + this.Load += new System.EventHandler(this.FormMail_Load); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit(); + this.ResumeLayout(false); + + } + + #endregion + + private DataGridView dataGridView; + } +} \ No newline at end of file diff --git a/GarmentFactory/FormMails.cs b/GarmentFactory/FormMails.cs new file mode 100644 index 0000000..73886f1 --- /dev/null +++ b/GarmentFactory/FormMails.cs @@ -0,0 +1,53 @@ +using GarmentFactoryContracts.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 GarmentFactoryView +{ + public partial class FormMails : Form + { + private readonly ILogger _logger; + private readonly IMessageInfoLogic _logic; + + public FormMails(ILogger logger, IMessageInfoLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + private void LoadData() + { + try + { + var list = _logic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["MessageId"].Visible = false; + dataGridView.Columns["ClientId"].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 FormMail_Load(object sender, EventArgs e) + { + LoadData(); + } + } +} \ No newline at end of file diff --git a/GarmentFactory/FormMails.resx b/GarmentFactory/FormMails.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/GarmentFactory/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/GarmentFactory/FormMain.Designer.cs b/GarmentFactory/FormMain.Designer.cs index 7e121da..731a885 100644 --- a/GarmentFactory/FormMain.Designer.cs +++ b/GarmentFactory/FormMain.Designer.cs @@ -45,6 +45,7 @@ textileComponentsToolStripMenuItem = new ToolStripMenuItem(); ordersToolStripMenuItem = new ToolStripMenuItem(); запускРаботToolStripMenuItem = new ToolStripMenuItem(); + почтаToolStripMenuItem = new ToolStripMenuItem(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); menuStrip1.SuspendLayout(); SuspendLayout(); @@ -123,7 +124,7 @@ // menuStrip1 // menuStrip1.ImageScalingSize = new Size(20, 20); - menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчётыToolStripMenuItem, запускРаботToolStripMenuItem }); + menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчётыToolStripMenuItem, запускРаботToolStripMenuItem, почтаToolStripMenuItem }); menuStrip1.Location = new Point(0, 0); menuStrip1.Name = "menuStrip1"; menuStrip1.Size = new Size(1547, 28); @@ -200,6 +201,13 @@ запускРаботToolStripMenuItem.Text = "Запуск работ"; запускРаботToolStripMenuItem.Click += запускРаботToolStripMenuItem_Click; // + // почтаToolStripMenuItem + // + почтаToolStripMenuItem.Name = "почтаToolStripMenuItem"; + почтаToolStripMenuItem.Size = new Size(65, 24); + почтаToolStripMenuItem.Text = "Почта"; + почтаToolStripMenuItem.Click += почтаToolStripMenuItem_Click; + // // FormMain // AutoScaleDimensions = new SizeF(8F, 20F); @@ -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/GarmentFactory/FormMain.cs b/GarmentFactory/FormMain.cs index d84801d..bbc26eb 100644 --- a/GarmentFactory/FormMain.cs +++ b/GarmentFactory/FormMain.cs @@ -211,5 +211,14 @@ namespace GarmentFactoryView _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(FormMails)); + if (service is FormMails form) + { + form.ShowDialog(); + } + } } } diff --git a/GarmentFactory/GarmentFactory.sln b/GarmentFactory/GarmentFactory.sln index d02f338..93a61ed 100644 --- a/GarmentFactory/GarmentFactory.sln +++ b/GarmentFactory/GarmentFactory.sln @@ -25,9 +25,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GarmentFactoryDatabaseImple {DB84150A-FB0D-4FCB-90DD-2CAC6845E1AF} = {DB84150A-FB0D-4FCB-90DD-2CAC6845E1AF} EndProjectSection EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GarmentFactoryRestApi", "..\GarmentFactoryRestApi\GarmentFactoryRestApi.csproj", "{5D50174D-BD95-4CE9-AC7E-E81FE1B6D99C}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GarmentFactoryRestApi", "..\GarmentFactoryRestApi\GarmentFactoryRestApi.csproj", "{5D50174D-BD95-4CE9-AC7E-E81FE1B6D99C}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GarmentFactoryClientApp", "..\GarmentFactoryClientApp\GarmentFactoryClientApp.csproj", "{5842FFC0-16D2-4268-841C-CF17396D54BC}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GarmentFactoryClientApp", "..\GarmentFactoryClientApp\GarmentFactoryClientApp.csproj", "{5842FFC0-16D2-4268-841C-CF17396D54BC}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution diff --git a/GarmentFactory/GarmentFactoryView.csproj b/GarmentFactory/GarmentFactoryView.csproj index 6b48d02..f188e4f 100644 --- a/GarmentFactory/GarmentFactoryView.csproj +++ b/GarmentFactory/GarmentFactoryView.csproj @@ -44,6 +44,9 @@ + + Always + Always diff --git a/GarmentFactory/Program.cs b/GarmentFactory/Program.cs index 72f878e..e7cecea 100644 --- a/GarmentFactory/Program.cs +++ b/GarmentFactory/Program.cs @@ -8,7 +8,8 @@ using GarmentFactoryView; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; - +using GarmentFactoryBusinessLogic.MailWorker; +using GarmentFactoryContracts.BindingModels; namespace GarmentFactory { @@ -28,7 +29,28 @@ namespace GarmentFactory var services = new ServiceCollection(); ConfigureServices(services); _serviceProvider = services.BuildServiceProvider(); - Application.Run(_serviceProvider.GetRequiredService()); + 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) { @@ -42,6 +64,7 @@ namespace GarmentFactory services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -49,13 +72,16 @@ namespace GarmentFactory services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddSingleton(); - services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -67,6 +93,8 @@ namespace GarmentFactory 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/GarmentFactoryBusinessLogic/BusinessLogics/ClientLogic.cs b/GarmentFactoryBusinessLogic/BusinessLogics/ClientLogic.cs index ff667e6..658a54d 100644 --- a/GarmentFactoryBusinessLogic/BusinessLogics/ClientLogic.cs +++ b/GarmentFactoryBusinessLogic/BusinessLogics/ClientLogic.cs @@ -4,11 +4,13 @@ using GarmentFactoryContracts.SearchModels; using GarmentFactoryContracts.StoragesContracts; using GarmentFactoryContracts.ViewModels; using Microsoft.Extensions.Logging; +using System.Text.RegularExpressions; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using DocumentFormat.OpenXml.EMMA; namespace GarmentFactoryBusinessLogic.BusinessLogics { @@ -101,13 +103,13 @@ namespace GarmentFactoryBusinessLogic.BusinessLogics { throw new ArgumentNullException("Нет ФИО пользователя", nameof(model.ClientFIO)); } - if (string.IsNullOrEmpty(model.Email)) + if (string.IsNullOrEmpty(model.Email) || !Regex.IsMatch(model.Email, @"^[a-z0-9._%+-]+\@([a-z0-9-]+\.)+[a-z]{2,4}$")) { - throw new ArgumentNullException("Нет почты пользователя", nameof(model.Email)); + throw new ArgumentException("Почта не соответствует требованиям", nameof(model.Email)); } - if (string.IsNullOrEmpty(model.Password)) + if (string.IsNullOrEmpty(model.Password) || !Regex.IsMatch(model.Password, @"^(?=.*[A-Za-z])(?=.*\d)(?=.*[^A-Za-z0-9\n]).{10,50}$")) { - throw new ArgumentNullException("Нет пароля пользователя", nameof(model.Password)); + throw new ArgumentNullException("Пароль не соответствует требованиям", nameof(model.Password)); } _logger.LogInformation("Client. ClientFIO:{ClientFIO}.Email:{Email}.Password:{Password}.Id:{Id}", model.ClientFIO, model.Email, model.Password, model.Id); diff --git a/GarmentFactoryBusinessLogic/BusinessLogics/MessageInfoLogic.cs b/GarmentFactoryBusinessLogic/BusinessLogics/MessageInfoLogic.cs new file mode 100644 index 0000000..256fa73 --- /dev/null +++ b/GarmentFactoryBusinessLogic/BusinessLogics/MessageInfoLogic.cs @@ -0,0 +1,90 @@ +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.BusinessLogicsContracts; +using GarmentFactoryContracts.SearchModels; +using GarmentFactoryContracts.StoragesContracts; +using GarmentFactoryContracts.ViewModels; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryBusinessLogic.BusinessLogics +{ + 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.Subject)) + { + throw new ArgumentNullException("Не указана тема", nameof(model.Subject)); + } + if (string.IsNullOrEmpty(model.Body)) + { + throw new ArgumentNullException("Не указан текст сообщения", nameof(model.Subject)); + } + + _logger.LogInformation("MessageInfo. MessageId:{MessageId}.SenderName:{SenderName}.Subject:{Subject}.Body:{Body}", model.MessageId, model.SenderName, model.Subject, model.Body); + var element = _clientStorage.GetElement(new ClientSearchModel + { + Email = model.SenderName + }); + if (element == null) + { + _logger.LogWarning("Не удалоссь найти клиента, отправившего письмо с адреса Email:{Email}", model.SenderName); + } + else + { + model.ClientId = element.Id; + } + } + } +} diff --git a/GarmentFactoryBusinessLogic/BusinessLogics/OrderLogic.cs b/GarmentFactoryBusinessLogic/BusinessLogics/OrderLogic.cs index 797b110..617cc82 100644 --- a/GarmentFactoryBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/GarmentFactoryBusinessLogic/BusinessLogics/OrderLogic.cs @@ -1,4 +1,5 @@ -using GarmentFactoryContracts.BindingModels; +using GarmentFactoryBusinessLogic.MailWorker; +using GarmentFactoryContracts.BindingModels; using GarmentFactoryContracts.BusinessLogicsContracts; using GarmentFactoryContracts.SearchModels; using GarmentFactoryContracts.StoragesContracts; @@ -19,11 +20,13 @@ namespace GarmentFactoryBusinessLogic.BusinessLogics private readonly ILogger _logger; //Хранение всех заказов private readonly IOrderStorage _orderStorage; + private readonly AbstractMailWorker _mailWorker; static readonly object _locker = new object(); - public OrderLogic(ILogger logger, IOrderStorage orderStorage) + public OrderLogic(ILogger logger, IOrderStorage orderStorage, AbstractMailWorker mailWorker) { _logger = logger; _orderStorage = orderStorage; + _mailWorker = mailWorker; } public OrderViewModel? ReadElement(OrderSearchModel model) @@ -93,12 +96,20 @@ namespace GarmentFactoryBusinessLogic.BusinessLogics return false; } model.Status = OrderStatus.Принят; - if (_orderStorage.Insert(model) == null) + + var order = _orderStorage.Insert(model); + if (order == null) { _logger.LogWarning("Insert operation failed"); return false; } - return true; + Task.Run(() => _mailWorker.MailSendAsync(new MailSendInfoBindingModel + { + MailAddress = order.ClientEmail, + Subject = $"Новый заказ создан. Номер заказа - {order.Id}", + Text = $"Ваш заказ номер {order.Id} на текстиль {order.TextileName} от {order.DateCreate} на сумму {order.Sum} принят." + })); + return true; } //Общий метод изменения статуса заказа @@ -133,7 +144,15 @@ namespace GarmentFactoryBusinessLogic.BusinessLogics _logger.LogWarning("Update operation failed"); return false; } - return true; + + //Отправка письма на почту + Task.Run(() => _mailWorker.MailSendAsync(new MailSendInfoBindingModel + { + MailAddress = order.ClientEmail, + Subject = $"Изменение статуса заказа номер {order.Id}", + Text = $"У заказа номер {order.Id} изменен статус на {newStatus}" + })); + return true; } if (order.Status + 1 != newStatus) { diff --git a/GarmentFactoryBusinessLogic/GarmentFactoryBusinessLogic.csproj b/GarmentFactoryBusinessLogic/GarmentFactoryBusinessLogic.csproj index 3cc214a..db0b6db 100644 --- a/GarmentFactoryBusinessLogic/GarmentFactoryBusinessLogic.csproj +++ b/GarmentFactoryBusinessLogic/GarmentFactoryBusinessLogic.csproj @@ -8,6 +8,7 @@ + diff --git a/GarmentFactoryBusinessLogic/MailWorker/AbstractMailWorker.cs b/GarmentFactoryBusinessLogic/MailWorker/AbstractMailWorker.cs new file mode 100644 index 0000000..f25025f --- /dev/null +++ b/GarmentFactoryBusinessLogic/MailWorker/AbstractMailWorker.cs @@ -0,0 +1,86 @@ +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryBusinessLogic.MailWorker +{ + public abstract class AbstractMailWorker + { + protected string _mailLogin = string.Empty; + protected string _mailPassword = string.Empty; + protected string _smtpClientHost = string.Empty; + protected int _smtpClientPort; + protected string _popHost = string.Empty; + protected int _popPort; + private readonly IMessageInfoLogic _messageInfoLogic; + private readonly ILogger _logger; + public AbstractMailWorker(ILogger logger, IMessageInfoLogic messageInfoLogic) + { + _logger = logger; + _messageInfoLogic = messageInfoLogic; + } + public void MailConfig(MailConfigBindingModel config) + { + _mailLogin = config.MailLogin; + _mailPassword = config.MailPassword; + _smtpClientHost = config.SmtpClientHost; + _smtpClientPort = config.SmtpClientPort; + _popHost = config.PopHost; + _popPort = config.PopPort; + _logger.LogDebug("Config: {login}, {password}, {clientHost}, { clientPOrt}, { popHost}, { popPort}", _mailLogin, _mailPassword, _smtpClientHost, _smtpClientPort, _popHost, _popPort); + } + + public async void MailSendAsync(MailSendInfoBindingModel info) + { + if (string.IsNullOrEmpty(_mailLogin) || + string.IsNullOrEmpty(_mailPassword)) + { + return; + } + if (string.IsNullOrEmpty(_smtpClientHost) || _smtpClientPort == 0) + { + return; + } + if (string.IsNullOrEmpty(info.MailAddress) || + string.IsNullOrEmpty(info.Subject) || string.IsNullOrEmpty(info.Text)) + { + return; + } + _logger.LogDebug("Send Mail: {To}, {Subject}", info.MailAddress, + info.Subject); + await SendMailAsync(info); + } + + public async void MailCheck() + { + if (string.IsNullOrEmpty(_mailLogin) || + string.IsNullOrEmpty(_mailPassword)) + { + return; + } + if (string.IsNullOrEmpty(_popHost) || _popPort == 0) + { + return; + } + if (_messageInfoLogic == null) + { + return; + } + var list = await ReceiveMailAsync(); + _logger.LogDebug("Check Mail: {Count} new mails", list.Count); + foreach (var mail in list) + { + _messageInfoLogic.Create(mail); + } + } + + protected abstract Task SendMailAsync(MailSendInfoBindingModel info); + protected abstract Task> ReceiveMailAsync(); + } + +} diff --git a/GarmentFactoryBusinessLogic/MailWorker/MailKitWorker.cs b/GarmentFactoryBusinessLogic/MailWorker/MailKitWorker.cs new file mode 100644 index 0000000..2b23776 --- /dev/null +++ b/GarmentFactoryBusinessLogic/MailWorker/MailKitWorker.cs @@ -0,0 +1,82 @@ +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Mail; +using System.Net; +using System.Security.Authentication; +using System.Text; +using System.Threading.Tasks; +using MailKit.Net.Pop3; +using MailKit.Security; + +namespace GarmentFactoryBusinessLogic.MailWorker +{ + public class MailKitWorker : AbstractMailWorker + { + public MailKitWorker(ILogger logger, IMessageInfoLogic messageInfoLogic) : base(logger, messageInfoLogic) { } + + //отправка письма + protected override async Task SendMailAsync(MailSendInfoBindingModel info) + { + using var objMailMessage = new MailMessage(); + using var objSmtpClient = new SmtpClient(_smtpClientHost, _smtpClientPort); + try + { + objMailMessage.From = new MailAddress(_mailLogin); + objMailMessage.To.Add(new MailAddress(info.MailAddress)); + objMailMessage.Subject = info.Subject; + objMailMessage.Body = info.Text; + objMailMessage.SubjectEncoding = Encoding.UTF8; + objMailMessage.BodyEncoding = Encoding.UTF8; + objSmtpClient.UseDefaultCredentials = false; + objSmtpClient.EnableSsl = true; + objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; + objSmtpClient.Credentials = new NetworkCredential(_mailLogin, _mailPassword); + await Task.Run(() => objSmtpClient.Send(objMailMessage)); + } + catch (Exception) + { + throw; + } + } + + //получение письма + protected override async Task> ReceiveMailAsync() + { + var list = new List(); + using var client = new Pop3Client(); + await Task.Run(() => + { + try + { + client.Connect(_popHost, _popPort, SecureSocketOptions.SslOnConnect); + client.Authenticate(_mailLogin, _mailPassword); + for (int i = 0; i < client.Count; i++) + { + var message = client.GetMessage(i); + foreach (var mail in message.From.Mailboxes) + { + list.Add(new MessageInfoBindingModel + { + DateDelivery = message.Date.DateTime, + MessageId = message.MessageId, + SenderName = mail.Address, + Subject = message.Subject, + Body = message.TextBody + }); + } + } + } + catch (MailKit.Security.AuthenticationException) { } + finally + { + client.Disconnect(true); + } + }); + return list; + } + } +} diff --git a/GarmentFactoryClientApp/Controllers/HomeController.cs b/GarmentFactoryClientApp/Controllers/HomeController.cs index c22f524..731efb7 100644 --- a/GarmentFactoryClientApp/Controllers/HomeController.cs +++ b/GarmentFactoryClientApp/Controllers/HomeController.cs @@ -143,5 +143,16 @@ namespace GarmentFactoryClientApp.Controllers var _textile = APIClient.GetRequest($"api/main/gettextile?textileId={textile}"); return count * (_textile?.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/GarmentFactoryClientApp/Views/Home/Mails.cshtml b/GarmentFactoryClientApp/Views/Home/Mails.cshtml new file mode 100644 index 0000000..a0bf363 --- /dev/null +++ b/GarmentFactoryClientApp/Views/Home/Mails.cshtml @@ -0,0 +1,55 @@ +@using GarmentFactoryContracts.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/GarmentFactoryClientApp/Views/Shared/_Layout.cshtml b/GarmentFactoryClientApp/Views/Shared/_Layout.cshtml index da03a6d..7721d7d 100644 --- a/GarmentFactoryClientApp/Views/Shared/_Layout.cshtml +++ b/GarmentFactoryClientApp/Views/Shared/_Layout.cshtml @@ -25,6 +25,9 @@ + diff --git a/GarmentFactoryContracts/BindingModels/MailConfigBindingModel.cs b/GarmentFactoryContracts/BindingModels/MailConfigBindingModel.cs new file mode 100644 index 0000000..1cebfc4 --- /dev/null +++ b/GarmentFactoryContracts/BindingModels/MailConfigBindingModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryContracts.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/GarmentFactoryContracts/BindingModels/MailSendInfoBindingModel.cs b/GarmentFactoryContracts/BindingModels/MailSendInfoBindingModel.cs new file mode 100644 index 0000000..ffb3031 --- /dev/null +++ b/GarmentFactoryContracts/BindingModels/MailSendInfoBindingModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryContracts.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/GarmentFactoryContracts/BindingModels/MessageInfoBindingModel.cs b/GarmentFactoryContracts/BindingModels/MessageInfoBindingModel.cs new file mode 100644 index 0000000..3d502f4 --- /dev/null +++ b/GarmentFactoryContracts/BindingModels/MessageInfoBindingModel.cs @@ -0,0 +1,19 @@ +using GarmentFactoryDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryContracts.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/GarmentFactoryContracts/BusinessLogicsContracts/IMessageInfoLogic.cs b/GarmentFactoryContracts/BusinessLogicsContracts/IMessageInfoLogic.cs new file mode 100644 index 0000000..349aca0 --- /dev/null +++ b/GarmentFactoryContracts/BusinessLogicsContracts/IMessageInfoLogic.cs @@ -0,0 +1,17 @@ +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.SearchModels; +using GarmentFactoryContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryContracts.BusinessLogicsContracts +{ + public interface IMessageInfoLogic + { + List? ReadList(MessageInfoSearchModel? model); + bool Create(MessageInfoBindingModel model); + } +} diff --git a/GarmentFactoryContracts/SearchModels/MessageInfoSearchModel.cs b/GarmentFactoryContracts/SearchModels/MessageInfoSearchModel.cs new file mode 100644 index 0000000..e08e106 --- /dev/null +++ b/GarmentFactoryContracts/SearchModels/MessageInfoSearchModel.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryContracts.SearchModels +{ + public class MessageInfoSearchModel + { + public int? ClientId { get; set; } + public string? MessageId { get; set; } + } +} diff --git a/GarmentFactoryContracts/StoragesContracts/IMessageInfoStorage.cs b/GarmentFactoryContracts/StoragesContracts/IMessageInfoStorage.cs new file mode 100644 index 0000000..772420b --- /dev/null +++ b/GarmentFactoryContracts/StoragesContracts/IMessageInfoStorage.cs @@ -0,0 +1,19 @@ +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.SearchModels; +using GarmentFactoryContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryContracts.StoragesContracts +{ + public interface IMessageInfoStorage + { + List GetFullList(); + List GetFilteredList(MessageInfoSearchModel model); + MessageInfoViewModel? GetElement(MessageInfoSearchModel model); + MessageInfoViewModel? Insert(MessageInfoBindingModel model); + } +} diff --git a/GarmentFactoryContracts/ViewModels/MessageInfoViewModel.cs b/GarmentFactoryContracts/ViewModels/MessageInfoViewModel.cs new file mode 100644 index 0000000..8389e77 --- /dev/null +++ b/GarmentFactoryContracts/ViewModels/MessageInfoViewModel.cs @@ -0,0 +1,29 @@ +using GarmentFactoryDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryContracts.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/GarmentFactoryContracts/ViewModels/OrderViewModel.cs b/GarmentFactoryContracts/ViewModels/OrderViewModel.cs index 51706a3..d307ea9 100644 --- a/GarmentFactoryContracts/ViewModels/OrderViewModel.cs +++ b/GarmentFactoryContracts/ViewModels/OrderViewModel.cs @@ -42,5 +42,7 @@ namespace GarmentFactoryContracts.ViewModels [DisplayName("Дата выполнения")] public DateTime? DateComplete { get; set; } - } + + public string ClientEmail { get; set; } = string.Empty; + } } diff --git a/GarmentFactoryDataModels/Models/IMessageInfoModel.cs b/GarmentFactoryDataModels/Models/IMessageInfoModel.cs new file mode 100644 index 0000000..708013f --- /dev/null +++ b/GarmentFactoryDataModels/Models/IMessageInfoModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryDataModels.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/GarmentFactoryDatabaseImplement/GarmentFactoryDatabase.cs b/GarmentFactoryDatabaseImplement/GarmentFactoryDatabase.cs index 79b772c..ead98ab 100644 --- a/GarmentFactoryDatabaseImplement/GarmentFactoryDatabase.cs +++ b/GarmentFactoryDatabaseImplement/GarmentFactoryDatabase.cs @@ -31,5 +31,7 @@ namespace GarmentFactoryDatabaseImplement public virtual DbSet Clients { set; get; } public virtual DbSet Implementers { set; get; } + + public virtual DbSet MessageInfos { set; get; } } } diff --git a/GarmentFactoryDatabaseImplement/Implements/ClientStorage.cs b/GarmentFactoryDatabaseImplement/Implements/ClientStorage.cs index 7c88a8d..712204a 100644 --- a/GarmentFactoryDatabaseImplement/Implements/ClientStorage.cs +++ b/GarmentFactoryDatabaseImplement/Implements/ClientStorage.cs @@ -21,17 +21,17 @@ namespace GarmentFactoryDatabaseImplement.Implements public List GetFilteredList(ClientSearchModel model) { - if (string.IsNullOrEmpty(model.ClientFIO)) + if (string.IsNullOrEmpty(model.Email) && string.IsNullOrEmpty(model.ClientFIO)) { return new(); } using var context = new GarmentFactoryDatabase(); - return context.Clients.Where(x => x.ClientFIO.Contains(model.ClientFIO)).Select(x => x.GetViewModel).ToList(); + return context.Clients.Where(x => (!string.IsNullOrEmpty(model.ClientFIO) && x.ClientFIO.Contains(model.ClientFIO)) || (!string.IsNullOrEmpty(model.Email) && x.Email.Contains(model.Email))).Select(x => x.GetViewModel).ToList(); } public ClientViewModel? GetElement(ClientSearchModel model) { - if (string.IsNullOrEmpty(model.Email) && string.IsNullOrEmpty(model.Password) && !model.Id.HasValue) + if (string.IsNullOrEmpty(model.Email) && string.IsNullOrEmpty(model.ClientFIO) && string.IsNullOrEmpty(model.Password) && !model.Id.HasValue) { return null; } diff --git a/GarmentFactoryDatabaseImplement/Implements/MessageInfoStorage.cs b/GarmentFactoryDatabaseImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..183ec99 --- /dev/null +++ b/GarmentFactoryDatabaseImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,55 @@ +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.SearchModels; +using GarmentFactoryContracts.StoragesContracts; +using GarmentFactoryContracts.ViewModels; +using GarmentFactoryDatabaseImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryDatabaseImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + public List GetFullList() + { + using var context = new GarmentFactoryDatabase(); + return context.MessageInfos.Select(x => x.GetViewModel).ToList(); + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + if (!model.ClientId.HasValue) + { + return new(); + } + using var context = new GarmentFactoryDatabase(); + return context.MessageInfos.Where(x => x.ClientId.HasValue && x.ClientId == model.ClientId).Select(x => x.GetViewModel).ToList(); + } + + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (string.IsNullOrEmpty(model.MessageId)) + { + return new(); + } + using var context = new GarmentFactoryDatabase(); + return context.MessageInfos.FirstOrDefault(x => x.MessageId == model.MessageId)?.GetViewModel; + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = MessageInfo.Create(model); + if (newMessage == null) + { + return null; + } + using var context = new GarmentFactoryDatabase(); + context.MessageInfos.Add(newMessage); + context.SaveChanges(); + return newMessage.GetViewModel; + } + } +} diff --git a/GarmentFactoryDatabaseImplement/Migrations/20240505113527_AddedMails.Designer.cs b/GarmentFactoryDatabaseImplement/Migrations/20240505113527_AddedMails.Designer.cs new file mode 100644 index 0000000..ceb8d03 --- /dev/null +++ b/GarmentFactoryDatabaseImplement/Migrations/20240505113527_AddedMails.Designer.cs @@ -0,0 +1,298 @@ +// +using System; +using GarmentFactoryDatabaseImplement; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace GarmentFactoryDatabaseImplement.Migrations +{ + [DbContext(typeof(GarmentFactoryDatabase))] + [Migration("20240505113527_AddedMails")] + partial class AddedMails + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.17") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.Client", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientFIO") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Email") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Password") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Clients"); + }); + + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.Component", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ComponentName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Cost") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.ToTable("Components"); + }); + + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.Implementer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ImplementerFIO") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Password") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Qualification") + .HasColumnType("int"); + + b.Property("WorkExperience") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.ToTable("Implementers"); + }); + + modelBuilder.Entity("GarmentFactoryDatabaseImplement.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("MessageInfos"); + }); + + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.Order", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("DateComplete") + .HasColumnType("datetime2"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("ImplementerId") + .HasColumnType("int"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("Sum") + .HasColumnType("float"); + + b.Property("TextileId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.HasIndex("ImplementerId"); + + b.HasIndex("TextileId"); + + b.ToTable("Orders"); + }); + + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.Textile", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Price") + .HasColumnType("float"); + + b.Property("TextileName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Textiles"); + }); + + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.TextileComponent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ComponentId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("TextileId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ComponentId"); + + b.HasIndex("TextileId"); + + b.ToTable("TextileComponents"); + }); + + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.MessageInfo", b => + { + b.HasOne("GarmentFactoryDatabaseImplement.Models.Client", "Client") + .WithMany("ClientMessages") + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.Order", b => + { + b.HasOne("GarmentFactoryDatabaseImplement.Models.Client", "Client") + .WithMany("Orders") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("GarmentFactoryDatabaseImplement.Models.Implementer", "Implementer") + .WithMany("Order") + .HasForeignKey("ImplementerId"); + + b.HasOne("GarmentFactoryDatabaseImplement.Models.Textile", "Textile") + .WithMany("Orders") + .HasForeignKey("TextileId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Client"); + + b.Navigation("Implementer"); + + b.Navigation("Textile"); + }); + + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.TextileComponent", b => + { + b.HasOne("GarmentFactoryDatabaseImplement.Models.Component", "Component") + .WithMany("TextileComponents") + .HasForeignKey("ComponentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("GarmentFactoryDatabaseImplement.Models.Textile", "Textile") + .WithMany("Components") + .HasForeignKey("TextileId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Component"); + + b.Navigation("Textile"); + }); + + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.Client", b => + { + b.Navigation("ClientMessages"); + + b.Navigation("Orders"); + }); + + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.Component", b => + { + b.Navigation("TextileComponents"); + }); + + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.Implementer", b => + { + b.Navigation("Order"); + }); + + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.Textile", b => + { + b.Navigation("Components"); + + b.Navigation("Orders"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/GarmentFactoryDatabaseImplement/Migrations/20240505113527_AddedMails.cs b/GarmentFactoryDatabaseImplement/Migrations/20240505113527_AddedMails.cs new file mode 100644 index 0000000..8d8b55a --- /dev/null +++ b/GarmentFactoryDatabaseImplement/Migrations/20240505113527_AddedMails.cs @@ -0,0 +1,48 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace GarmentFactoryDatabaseImplement.Migrations +{ + /// + public partial class AddedMails : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "MessageInfos", + 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_MessageInfos", x => x.MessageId); + table.ForeignKey( + name: "FK_MessageInfos_Clients_ClientId", + column: x => x.ClientId, + principalTable: "Clients", + principalColumn: "Id"); + }); + + migrationBuilder.CreateIndex( + name: "IX_MessageInfos_ClientId", + table: "MessageInfos", + column: "ClientId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "MessageInfos"); + } + } +} diff --git a/GarmentFactoryDatabaseImplement/Migrations/20240505123925_AddedMails_1.Designer.cs b/GarmentFactoryDatabaseImplement/Migrations/20240505123925_AddedMails_1.Designer.cs new file mode 100644 index 0000000..785e984 --- /dev/null +++ b/GarmentFactoryDatabaseImplement/Migrations/20240505123925_AddedMails_1.Designer.cs @@ -0,0 +1,298 @@ +// +using System; +using GarmentFactoryDatabaseImplement; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace GarmentFactoryDatabaseImplement.Migrations +{ + [DbContext(typeof(GarmentFactoryDatabase))] + [Migration("20240505123925_AddedMails_1")] + partial class AddedMails_1 + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.17") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.Client", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientFIO") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Email") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Password") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Clients"); + }); + + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.Component", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ComponentName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Cost") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.ToTable("Components"); + }); + + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.Implementer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ImplementerFIO") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Password") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Qualification") + .HasColumnType("int"); + + b.Property("WorkExperience") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.ToTable("Implementers"); + }); + + modelBuilder.Entity("GarmentFactoryDatabaseImplement.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("MessageInfos"); + }); + + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.Order", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("DateComplete") + .HasColumnType("datetime2"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("ImplementerId") + .HasColumnType("int"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("Sum") + .HasColumnType("float"); + + b.Property("TextileId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.HasIndex("ImplementerId"); + + b.HasIndex("TextileId"); + + b.ToTable("Orders"); + }); + + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.Textile", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Price") + .HasColumnType("float"); + + b.Property("TextileName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Textiles"); + }); + + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.TextileComponent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ComponentId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("TextileId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ComponentId"); + + b.HasIndex("TextileId"); + + b.ToTable("TextileComponents"); + }); + + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.MessageInfo", b => + { + b.HasOne("GarmentFactoryDatabaseImplement.Models.Client", "Client") + .WithMany("ClientMessages") + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.Order", b => + { + b.HasOne("GarmentFactoryDatabaseImplement.Models.Client", "Client") + .WithMany("Orders") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("GarmentFactoryDatabaseImplement.Models.Implementer", "Implementer") + .WithMany("Order") + .HasForeignKey("ImplementerId"); + + b.HasOne("GarmentFactoryDatabaseImplement.Models.Textile", "Textile") + .WithMany("Orders") + .HasForeignKey("TextileId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Client"); + + b.Navigation("Implementer"); + + b.Navigation("Textile"); + }); + + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.TextileComponent", b => + { + b.HasOne("GarmentFactoryDatabaseImplement.Models.Component", "Component") + .WithMany("TextileComponents") + .HasForeignKey("ComponentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("GarmentFactoryDatabaseImplement.Models.Textile", "Textile") + .WithMany("Components") + .HasForeignKey("TextileId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Component"); + + b.Navigation("Textile"); + }); + + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.Client", b => + { + b.Navigation("ClientMessages"); + + b.Navigation("Orders"); + }); + + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.Component", b => + { + b.Navigation("TextileComponents"); + }); + + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.Implementer", b => + { + b.Navigation("Order"); + }); + + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.Textile", b => + { + b.Navigation("Components"); + + b.Navigation("Orders"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/GarmentFactoryDatabaseImplement/Migrations/20240505123925_AddedMails_1.cs b/GarmentFactoryDatabaseImplement/Migrations/20240505123925_AddedMails_1.cs new file mode 100644 index 0000000..d1b9a38 --- /dev/null +++ b/GarmentFactoryDatabaseImplement/Migrations/20240505123925_AddedMails_1.cs @@ -0,0 +1,22 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace GarmentFactoryDatabaseImplement.Migrations +{ + /// + public partial class AddedMails_1 : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + + } + } +} diff --git a/GarmentFactoryDatabaseImplement/Migrations/GarmentFactoryDatabaseModelSnapshot.cs b/GarmentFactoryDatabaseImplement/Migrations/GarmentFactoryDatabaseModelSnapshot.cs index 3946c85..7ec865f 100644 --- a/GarmentFactoryDatabaseImplement/Migrations/GarmentFactoryDatabaseModelSnapshot.cs +++ b/GarmentFactoryDatabaseImplement/Migrations/GarmentFactoryDatabaseModelSnapshot.cs @@ -94,6 +94,36 @@ namespace GarmentFactoryDatabaseImplement.Migrations b.ToTable("Implementers"); }); + modelBuilder.Entity("GarmentFactoryDatabaseImplement.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("MessageInfos"); + }); + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -183,6 +213,15 @@ namespace GarmentFactoryDatabaseImplement.Migrations b.ToTable("TextileComponents"); }); + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.MessageInfo", b => + { + b.HasOne("GarmentFactoryDatabaseImplement.Models.Client", "Client") + .WithMany("ClientMessages") + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.Order", b => { b.HasOne("GarmentFactoryDatabaseImplement.Models.Client", "Client") @@ -229,6 +268,8 @@ namespace GarmentFactoryDatabaseImplement.Migrations modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.Client", b => { + b.Navigation("ClientMessages"); + b.Navigation("Orders"); }); diff --git a/GarmentFactoryDatabaseImplement/Models/Client.cs b/GarmentFactoryDatabaseImplement/Models/Client.cs index a6052ec..8f231b7 100644 --- a/GarmentFactoryDatabaseImplement/Models/Client.cs +++ b/GarmentFactoryDatabaseImplement/Models/Client.cs @@ -25,7 +25,10 @@ namespace GarmentFactoryDatabaseImplement.Models [ForeignKey("ClientId")] public virtual List Orders { get; set; } = new(); - public static Client? Create(ClientBindingModel model) + [ForeignKey("ClientId")] + public virtual List ClientMessages { get; set; } = new(); + + public static Client? Create(ClientBindingModel model) { if (model == null) { diff --git a/GarmentFactoryDatabaseImplement/Models/MessageInfo.cs b/GarmentFactoryDatabaseImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..56bce11 --- /dev/null +++ b/GarmentFactoryDatabaseImplement/Models/MessageInfo.cs @@ -0,0 +1,63 @@ +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.ViewModels; +using GarmentFactoryDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryDatabaseImplement.Models +{ + public class MessageInfo : IMessageInfoModel + { + [Key] + public string MessageId { get; set; } = string.Empty; + + public int? ClientId { get; set; } + + public virtual Client? Client { get; set; } + + [Required] + public string SenderName { get; set; } = string.Empty; + + [Required] + public DateTime DateDelivery { get; set; } + + [Required] + public string Subject { get; set; } = string.Empty; + + [Required] + public string Body { get; set; } = string.Empty; + + public static MessageInfo? Create(MessageInfoBindingModel? model) + { + if (model == null) + { + return null; + } + return new() + { + MessageId = model.MessageId, + ClientId = model.ClientId, + SenderName = model.SenderName, + DateDelivery = model.DateDelivery, + Subject = model.Subject, + Body = model.Body, + + }; + } + + public MessageInfoViewModel GetViewModel => new() + { + MessageId = MessageId, + ClientId = ClientId, + SenderName = SenderName, + DateDelivery = DateDelivery, + Subject = Subject, + Body = Body + }; + } +} diff --git a/GarmentFactoryDatabaseImplement/Models/Order.cs b/GarmentFactoryDatabaseImplement/Models/Order.cs index 2282b83..01be1b0 100644 --- a/GarmentFactoryDatabaseImplement/Models/Order.cs +++ b/GarmentFactoryDatabaseImplement/Models/Order.cs @@ -94,6 +94,7 @@ namespace GarmentFactoryDatabaseImplement.Models DateComplete = DateComplete, TextileName = Textile.TextileName, ClientFIO = Client.ClientFIO, + ClientEmail = Client.Email, ImplementerFIO = Implementer?.ImplementerFIO, }; } diff --git a/GarmentFactoryFileImplement/DataFileSingleton.cs b/GarmentFactoryFileImplement/DataFileSingleton.cs index eb98241..af96121 100644 --- a/GarmentFactoryFileImplement/DataFileSingleton.cs +++ b/GarmentFactoryFileImplement/DataFileSingleton.cs @@ -16,11 +16,15 @@ namespace GarmentFactoryFileImplement private readonly string TextileFileName = "Textile.xml"; private readonly string ClientFileName = "Client.xml"; private readonly string ImplementerFileName = "Implementer.xml"; + private readonly string MessageInfoFileName = "MessageInfo.xml"; + public List Components { get; private set; } public List Orders { get; private set; } public List Textiles { 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() { if (instance == null) @@ -29,11 +33,13 @@ namespace GarmentFactoryFileImplement } return instance; } + public void SaveComponents() => SaveData(Components, ComponentFileName, "Components", x => x.GetXElement); public void SaveTextiles() => SaveData(Textiles, TextileFileName, "Textiles", x => x.GetXElement); 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() { @@ -42,6 +48,7 @@ namespace GarmentFactoryFileImplement 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/GarmentFactoryFileImplement/Implements/MessageInfoStorage.cs b/GarmentFactoryFileImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..30828fe --- /dev/null +++ b/GarmentFactoryFileImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,58 @@ +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.StoragesContracts; +using GarmentFactoryContracts.ViewModels; +using GarmentFactoryContracts.SearchModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using GarmentFactoryFileImplement.Models; + +namespace GarmentFactoryFileImplement.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/GarmentFactoryFileImplement/Models/MessageInfo.cs b/GarmentFactoryFileImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..cbaf45d --- /dev/null +++ b/GarmentFactoryFileImplement/Models/MessageInfo.cs @@ -0,0 +1,80 @@ +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.ViewModels; +using GarmentFactoryDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace GarmentFactoryFileImplement.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 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/GarmentFactoryListImplement/DataListSingleton.cs b/GarmentFactoryListImplement/DataListSingleton.cs index 13869f0..d188116 100644 --- a/GarmentFactoryListImplement/DataListSingleton.cs +++ b/GarmentFactoryListImplement/DataListSingleton.cs @@ -10,13 +10,15 @@ namespace GarmentFactoryListImplement public List Textiles { get; set; } public List Clients { get; set; } public List Implementers { get; set; } - private DataListSingleton() + public List Messages { get; set; } + private DataListSingleton() { Components = new List(); Orders = new List(); Textiles = new List(); Clients = new List(); Implementers = new List(); + Messages = new List(); } public static DataListSingleton GetInstance() { diff --git a/GarmentFactoryListImplement/Implements/MessageInfoStorage.cs b/GarmentFactoryListImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..fec7cd6 --- /dev/null +++ b/GarmentFactoryListImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,68 @@ +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.SearchModels; +using GarmentFactoryContracts.StoragesContracts; +using GarmentFactoryContracts.ViewModels; +using GarmentFactoryListImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryListImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + private readonly DataListSingleton _source; + public MessageInfoStorage() + { + _source = DataListSingleton.GetInstance(); + } + + public List GetFullList() + { + List result = new(); + foreach (var item in _source.Messages) + { + result.Add(item.GetViewModel); + } + return result; + } + + 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 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 MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = MessageInfo.Create(model); + if (newMessage == null) + { + return null; + } + _source.Messages.Add(newMessage); + return newMessage.GetViewModel; + } + } +} diff --git a/GarmentFactoryListImplement/Models/MessageInfo.cs b/GarmentFactoryListImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..0b2329d --- /dev/null +++ b/GarmentFactoryListImplement/Models/MessageInfo.cs @@ -0,0 +1,53 @@ +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.ViewModels; +using GarmentFactoryDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryListImplement.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/GarmentFactoryRestApi/Controllers/ClientController.cs b/GarmentFactoryRestApi/Controllers/ClientController.cs index 5ca1878..ba0eafd 100644 --- a/GarmentFactoryRestApi/Controllers/ClientController.cs +++ b/GarmentFactoryRestApi/Controllers/ClientController.cs @@ -13,11 +13,13 @@ namespace GarmentFactoryRestApi.Controllers private readonly ILogger _logger; private readonly IClientLogic _logic; + private readonly IMessageInfoLogic _mailLogic; - public ClientController(IClientLogic logic, ILogger logger) + public ClientController(IClientLogic logic, ILogger logger, IMessageInfoLogic mailLogic) { _logger = logger; _logic = logic; + _mailLogic = mailLogic; } [HttpGet] @@ -65,5 +67,22 @@ namespace GarmentFactoryRestApi.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/GarmentFactoryRestApi/Program.cs b/GarmentFactoryRestApi/Program.cs index 845dea3..955511f 100644 --- a/GarmentFactoryRestApi/Program.cs +++ b/GarmentFactoryRestApi/Program.cs @@ -1,4 +1,6 @@ using GarmentFactoryBusinessLogic.BusinessLogics; +using GarmentFactoryBusinessLogic.MailWorker; +using GarmentFactoryContracts.BindingModels; using GarmentFactoryContracts.BusinessLogicsContracts; using GarmentFactoryContracts.StoragesContracts; using GarmentFactoryDatabaseImplement.Implements; @@ -14,11 +16,16 @@ builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddTransient(); + builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddTransient(); + +builder.Services.AddSingleton(); builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle @@ -30,6 +37,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/GarmentFactoryRestApi/appsettings.json b/GarmentFactoryRestApi/appsettings.json index 10f68b8..cecbb9b 100644 --- a/GarmentFactoryRestApi/appsettings.json +++ b/GarmentFactoryRestApi/appsettings.json @@ -5,5 +5,12 @@ "Microsoft.AspNetCore": "Warning" } }, - "AllowedHosts": "*" + "AllowedHosts": "*", + + "SmtpClientHost": "smtp.gmail.com", + "SmtpClientPort": "587", + "PopHost": "pop.gmail.com", + "PopPort": "995", + "MailLogin": "ujijrujijr@gmail.com", + "MailPassword": "twkn exbj fkua jrlw" } -- 2.25.1 From 6c97579ac0efd8d8082514c22245a10599c212e2 Mon Sep 17 00:00:00 2001 From: ujijrujijr Date: Mon, 13 May 2024 23:41:25 +0400 Subject: [PATCH 2/2] =?UTF-8?q?=D0=9F=D1=80=D0=B0=D0=B2=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- GarmentFactory/App.config | 4 ++-- GarmentFactory/FormMain.cs | 1 + .../BusinessLogics/MessageInfoLogic.cs | 2 +- .../MailWorker/AbstractMailWorker.cs | 12 ++++-------- GarmentFactoryClientApp/Views/Home/Mails.cshtml | 2 +- GarmentFactoryClientApp/Views/Shared/_Layout.cshtml | 2 +- GarmentFactoryContracts/ViewModels/OrderViewModel.cs | 1 + .../Implements/ClientStorage.cs | 1 + .../Models/MessageInfo.cs | 1 - GarmentFactoryRestApi/appsettings.json | 4 ++-- 10 files changed, 14 insertions(+), 16 deletions(-) diff --git a/GarmentFactory/App.config b/GarmentFactory/App.config index cdd7638..055eb06 100644 --- a/GarmentFactory/App.config +++ b/GarmentFactory/App.config @@ -5,7 +5,7 @@ - - + + \ No newline at end of file diff --git a/GarmentFactory/FormMain.cs b/GarmentFactory/FormMain.cs index bbc26eb..ea15fda 100644 --- a/GarmentFactory/FormMain.cs +++ b/GarmentFactory/FormMain.cs @@ -40,6 +40,7 @@ namespace GarmentFactoryView dataGridView.DataSource = list; dataGridView.Columns["TextileId"].Visible = false; dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["ClientEmail"].Visible = false; dataGridView.Columns["ImplementerId"].Visible = false; dataGridView.Columns["TextileName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dataGridView.Columns["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; diff --git a/GarmentFactoryBusinessLogic/BusinessLogics/MessageInfoLogic.cs b/GarmentFactoryBusinessLogic/BusinessLogics/MessageInfoLogic.cs index 256fa73..6539fa0 100644 --- a/GarmentFactoryBusinessLogic/BusinessLogics/MessageInfoLogic.cs +++ b/GarmentFactoryBusinessLogic/BusinessLogics/MessageInfoLogic.cs @@ -61,7 +61,7 @@ namespace GarmentFactoryBusinessLogic.BusinessLogics } if (string.IsNullOrEmpty(model.SenderName)) { - throw new ArgumentNullException("Не указао почта", nameof(model.SenderName)); + throw new ArgumentNullException("Не указана почта", nameof(model.SenderName)); } if (string.IsNullOrEmpty(model.Subject)) { diff --git a/GarmentFactoryBusinessLogic/MailWorker/AbstractMailWorker.cs b/GarmentFactoryBusinessLogic/MailWorker/AbstractMailWorker.cs index f25025f..117cf6b 100644 --- a/GarmentFactoryBusinessLogic/MailWorker/AbstractMailWorker.cs +++ b/GarmentFactoryBusinessLogic/MailWorker/AbstractMailWorker.cs @@ -37,8 +37,7 @@ namespace GarmentFactoryBusinessLogic.MailWorker public async void MailSendAsync(MailSendInfoBindingModel info) { - if (string.IsNullOrEmpty(_mailLogin) || - string.IsNullOrEmpty(_mailPassword)) + if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword)) { return; } @@ -46,20 +45,17 @@ namespace GarmentFactoryBusinessLogic.MailWorker { return; } - if (string.IsNullOrEmpty(info.MailAddress) || - string.IsNullOrEmpty(info.Subject) || string.IsNullOrEmpty(info.Text)) + if (string.IsNullOrEmpty(info.MailAddress) || string.IsNullOrEmpty(info.Subject) || string.IsNullOrEmpty(info.Text)) { return; } - _logger.LogDebug("Send Mail: {To}, {Subject}", info.MailAddress, - info.Subject); + _logger.LogDebug("Send Mail: {To}, {Subject}", info.MailAddress, info.Subject); await SendMailAsync(info); } public async void MailCheck() { - if (string.IsNullOrEmpty(_mailLogin) || - string.IsNullOrEmpty(_mailPassword)) + if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword)) { return; } diff --git a/GarmentFactoryClientApp/Views/Home/Mails.cshtml b/GarmentFactoryClientApp/Views/Home/Mails.cshtml index a0bf363..677575d 100644 --- a/GarmentFactoryClientApp/Views/Home/Mails.cshtml +++ b/GarmentFactoryClientApp/Views/Home/Mails.cshtml @@ -8,7 +8,7 @@
-

Заказы

+

Письма

diff --git a/GarmentFactoryClientApp/Views/Shared/_Layout.cshtml b/GarmentFactoryClientApp/Views/Shared/_Layout.cshtml index 7721d7d..5593066 100644 --- a/GarmentFactoryClientApp/Views/Shared/_Layout.cshtml +++ b/GarmentFactoryClientApp/Views/Shared/_Layout.cshtml @@ -26,7 +26,7 @@ Личные данные