From 4fffd63a3447fa7e5f00aff6d75b25fa1280de42 Mon Sep 17 00:00:00 2001 From: ArtemEmelyanov Date: Tue, 25 Apr 2023 09:21:39 +0400 Subject: [PATCH 1/2] =?UTF-8?q?=D0=A1=D0=B4=D0=B5=D0=BB=D0=B0=D0=BD=D0=BD?= =?UTF-8?q?=D0=B0=D1=8F=20=D0=BB=D0=B0=D0=B1=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- FishFactory/FishFactory/App.config | 11 + .../FishFactory/FishFactoryView.csproj | 6 + FishFactory/FishFactory/FormMail.Designer.cs | 64 +++++ FishFactory/FishFactory/FormMail.cs | 49 ++++ FishFactory/FishFactory/FormMail.resx | 60 ++++ FishFactory/FishFactory/FormMain.Designer.cs | 61 +++-- FishFactory/FishFactory/FormMain.cs | 9 + FishFactory/FishFactory/Program.cs | 37 ++- .../BusinessLogic/ClientLogic.cs | 5 + .../BusinessLogic/MessageInfoLogic.cs | 48 ++++ .../BusinessLogic/OrderLogic.cs | 33 ++- .../FishFactoryBusinessLogic.csproj | 1 + .../MailWorker/AbstractMailWorker.cs | 82 ++++++ .../MailWorker/MailKitWorker.cs | 74 +++++ .../Controllers/HomeController.cs | 10 + .../Views/Home/Mails.cshtml | 54 ++++ .../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 | 28 ++ .../IMessageInfoModel.cs | 18 ++ .../FishFactoryDatabase.cs | 3 +- .../Implements/ClientStorage.cs | 23 +- .../Implements/MessageInfoStorage.cs | 57 ++++ .../20230422093015_Init2.Designer.cs | 257 ------------------ .../Migrations/20230422093015_Init2.cs | 59 ---- ...ner.cs => 20230424175659_Init.Designer.cs} | 48 +++- ...1050354_Init.cs => 20230424175659_Init.cs} | 34 ++- .../FishFactoryDatabaseModelSnapshot.cs | 41 +++ .../Models/Client.cs | 3 + .../Models/MessageInfo.cs | 57 ++++ .../DataFileSingleton.cs | 7 + .../Implements/MessageInfoStorage.cs | 58 ++++ .../Models/MessageInfo.cs | 80 ++++++ .../DataListSingleton.cs | 2 + .../Implements/MessageInfoStorage.cs | 66 +++++ .../Models/MessageInfo.cs | 46 ++++ .../Controllers/ClientController.cs | 21 +- .../FishFactoryRestApi.csproj | 6 + FishFactory/FishFactoryRestApi/Program.cs | 22 +- .../FishFactoryRestApi/appsettings.json | 9 +- 45 files changed, 1280 insertions(+), 374 deletions(-) create mode 100644 FishFactory/FishFactory/App.config create mode 100644 FishFactory/FishFactory/FormMail.Designer.cs create mode 100644 FishFactory/FishFactory/FormMail.cs create mode 100644 FishFactory/FishFactory/FormMail.resx create mode 100644 FishFactory/FishFactoryBusinessLogic/BusinessLogic/MessageInfoLogic.cs create mode 100644 FishFactory/FishFactoryBusinessLogic/MailWorker/AbstractMailWorker.cs create mode 100644 FishFactory/FishFactoryBusinessLogic/MailWorker/MailKitWorker.cs create mode 100644 FishFactory/FishFactoryClientApp/Views/Home/Mails.cshtml create mode 100644 FishFactory/FishFactoryContracts/BindingModels/MailConfigBindingModel.cs create mode 100644 FishFactory/FishFactoryContracts/BindingModels/MailSendInfoBindingModel.cs create mode 100644 FishFactory/FishFactoryContracts/BindingModels/MessageInfoBindingModel.cs create mode 100644 FishFactory/FishFactoryContracts/BusinessLogicsContracts/IMessageInfoLogic.cs create mode 100644 FishFactory/FishFactoryContracts/SearchModels/MessageInfoSearchModel.cs create mode 100644 FishFactory/FishFactoryContracts/StoragesContracts/IMessageInfoStorage.cs create mode 100644 FishFactory/FishFactoryContracts/ViewModels/MessageInfoViewModel.cs create mode 100644 FishFactory/FishFactoryDataModels/IMessageInfoModel.cs create mode 100644 FishFactory/FishFactoryDatabaseImplement/Implements/MessageInfoStorage.cs delete mode 100644 FishFactory/FishFactoryDatabaseImplement/Migrations/20230422093015_Init2.Designer.cs delete mode 100644 FishFactory/FishFactoryDatabaseImplement/Migrations/20230422093015_Init2.cs rename FishFactory/FishFactoryDatabaseImplement/Migrations/{20230411050354_Init.Designer.cs => 20230424175659_Init.Designer.cs} (85%) rename FishFactory/FishFactoryDatabaseImplement/Migrations/{20230411050354_Init.cs => 20230424175659_Init.cs} (85%) create mode 100644 FishFactory/FishFactoryDatabaseImplement/Models/MessageInfo.cs create mode 100644 FishFactory/FishFactoryFileImplement/Implements/MessageInfoStorage.cs create mode 100644 FishFactory/FishFactoryFileImplement/Models/MessageInfo.cs create mode 100644 FishFactory/FishFactoryListImplement/Implements/MessageInfoStorage.cs create mode 100644 FishFactory/FishFactoryListImplement/Models/MessageInfo.cs diff --git a/FishFactory/FishFactory/App.config b/FishFactory/FishFactory/App.config new file mode 100644 index 0000000..4a90f54 --- /dev/null +++ b/FishFactory/FishFactory/App.config @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/FishFactory/FishFactory/FishFactoryView.csproj b/FishFactory/FishFactory/FishFactoryView.csproj index d785759..f0c6121 100644 --- a/FishFactory/FishFactory/FishFactoryView.csproj +++ b/FishFactory/FishFactory/FishFactoryView.csproj @@ -26,4 +26,10 @@ + + + Always + + + \ No newline at end of file diff --git a/FishFactory/FishFactory/FormMail.Designer.cs b/FishFactory/FishFactory/FormMail.Designer.cs new file mode 100644 index 0000000..d35e20c --- /dev/null +++ b/FishFactory/FishFactory/FormMail.Designer.cs @@ -0,0 +1,64 @@ +using System.Windows.Forms; + +namespace FishFactoryView +{ + partial class FormMail + { + /// + /// 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.Dock = System.Windows.Forms.DockStyle.Fill; + this.dataGridView.Location = new System.Drawing.Point(0, 0); + this.dataGridView.Name = "dataGridView"; + this.dataGridView.RowTemplate.Height = 25; + this.dataGridView.Size = new System.Drawing.Size(800, 450); + this.dataGridView.TabIndex = 0; + // + // FormMail + // + 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 = "FormMail"; + this.Text = "Письма"; + this.Load += new System.EventHandler(this.FormViewMail_Load); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit(); + this.ResumeLayout(false); + + } + + #endregion + private DataGridView dataGridView; + } +} \ No newline at end of file diff --git a/FishFactory/FishFactory/FormMail.cs b/FishFactory/FishFactory/FormMail.cs new file mode 100644 index 0000000..4afb4f4 --- /dev/null +++ b/FishFactory/FishFactory/FormMail.cs @@ -0,0 +1,49 @@ +using FishFactoryContracts.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 FishFactoryView +{ + public partial class FormMail : Form + { + private readonly ILogger _logger; + private readonly IMessageInfoLogic _logic; + + public FormMail(ILogger logger, IMessageInfoLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + private void FormViewMail_Load(object sender, EventArgs e) + { + try + { + var list = _logic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["MessageId"].Visible = false; + dataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + _logger.LogInformation("Загрузка списка писем"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки писем"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + } +} diff --git a/FishFactory/FishFactory/FormMail.resx b/FishFactory/FishFactory/FormMail.resx new file mode 100644 index 0000000..f298a7b --- /dev/null +++ b/FishFactory/FishFactory/FormMail.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/FishFactory/FishFactory/FormMain.Designer.cs b/FishFactory/FishFactory/FormMain.Designer.cs index 210a313..07f6d7f 100644 --- a/FishFactory/FishFactory/FormMain.Designer.cs +++ b/FishFactory/FishFactory/FormMain.Designer.cs @@ -43,6 +43,7 @@ this.клиентыToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.исполнителиToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.запускРаботToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.письмаToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); this.menuStrip1.SuspendLayout(); this.SuspendLayout(); @@ -50,20 +51,18 @@ // dataGridView // this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; - this.dataGridView.Location = new System.Drawing.Point(14, 43); - this.dataGridView.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); + this.dataGridView.Location = new System.Drawing.Point(12, 32); this.dataGridView.Name = "dataGridView"; this.dataGridView.RowHeadersWidth = 51; this.dataGridView.RowTemplate.Height = 25; - this.dataGridView.Size = new System.Drawing.Size(988, 536); + this.dataGridView.Size = new System.Drawing.Size(864, 402); this.dataGridView.TabIndex = 0; // // ButtonCreateOrder // - this.ButtonCreateOrder.Location = new System.Drawing.Point(1008, 43); - this.ButtonCreateOrder.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); + this.ButtonCreateOrder.Location = new System.Drawing.Point(882, 32); this.ButtonCreateOrder.Name = "ButtonCreateOrder"; - this.ButtonCreateOrder.Size = new System.Drawing.Size(213, 31); + this.ButtonCreateOrder.Size = new System.Drawing.Size(186, 23); this.ButtonCreateOrder.TabIndex = 1; this.ButtonCreateOrder.Text = "Создать заказ"; this.ButtonCreateOrder.UseVisualStyleBackColor = true; @@ -71,10 +70,9 @@ // // ButtonIssuedOrder // - this.ButtonIssuedOrder.Location = new System.Drawing.Point(1008, 117); - this.ButtonIssuedOrder.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); + this.ButtonIssuedOrder.Location = new System.Drawing.Point(882, 88); this.ButtonIssuedOrder.Name = "ButtonIssuedOrder"; - this.ButtonIssuedOrder.Size = new System.Drawing.Size(213, 31); + this.ButtonIssuedOrder.Size = new System.Drawing.Size(186, 23); this.ButtonIssuedOrder.TabIndex = 4; this.ButtonIssuedOrder.Text = "Заказ выдан"; this.ButtonIssuedOrder.UseVisualStyleBackColor = true; @@ -82,10 +80,9 @@ // // ButtonRef // - this.ButtonRef.Location = new System.Drawing.Point(1008, 192); - this.ButtonRef.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); + this.ButtonRef.Location = new System.Drawing.Point(882, 144); this.ButtonRef.Name = "ButtonRef"; - this.ButtonRef.Size = new System.Drawing.Size(213, 31); + this.ButtonRef.Size = new System.Drawing.Size(186, 23); this.ButtonRef.TabIndex = 5; this.ButtonRef.Text = "Обновить список"; this.ButtonRef.UseVisualStyleBackColor = true; @@ -97,20 +94,20 @@ this.компонентыToolStripMenuItem1, this.консервыToolStripMenuItem}); this.изделияToolStripMenuItem.Name = "изделияToolStripMenuItem"; - this.изделияToolStripMenuItem.Size = new System.Drawing.Size(117, 24); + this.изделияToolStripMenuItem.Size = new System.Drawing.Size(94, 20); this.изделияToolStripMenuItem.Text = "Справочники"; // // компонентыToolStripMenuItem1 // this.компонентыToolStripMenuItem1.Name = "компонентыToolStripMenuItem1"; - this.компонентыToolStripMenuItem1.Size = new System.Drawing.Size(182, 26); + this.компонентыToolStripMenuItem1.Size = new System.Drawing.Size(145, 22); this.компонентыToolStripMenuItem1.Text = "Компоненты"; this.компонентыToolStripMenuItem1.Click += new System.EventHandler(this.КомпонентыToolStripMenuItem_Click); // // консервыToolStripMenuItem // this.консервыToolStripMenuItem.Name = "консервыToolStripMenuItem"; - this.консервыToolStripMenuItem.Size = new System.Drawing.Size(182, 26); + this.консервыToolStripMenuItem.Size = new System.Drawing.Size(145, 22); this.консервыToolStripMenuItem.Text = "Консервы"; this.консервыToolStripMenuItem.Click += new System.EventHandler(this.КонсервыToolStripMenuItem_Click); // @@ -122,11 +119,12 @@ this.отчетыToolStripMenuItem, this.клиентыToolStripMenuItem, this.исполнителиToolStripMenuItem, - this.запускРаботToolStripMenuItem}); + this.запускРаботToolStripMenuItem, + this.письмаToolStripMenuItem}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; - this.menuStrip1.Padding = new System.Windows.Forms.Padding(6, 3, 0, 3); - this.menuStrip1.Size = new System.Drawing.Size(1233, 30); + this.menuStrip1.Padding = new System.Windows.Forms.Padding(5, 2, 0, 2); + this.menuStrip1.Size = new System.Drawing.Size(1079, 24); this.menuStrip1.TabIndex = 6; this.menuStrip1.Text = "menuStrip1"; // @@ -137,63 +135,69 @@ this.компонентыПоИзделиямToolStripMenuItem, this.списокЗаказовToolStripMenuItem}); this.отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem"; - this.отчетыToolStripMenuItem.Size = new System.Drawing.Size(73, 24); + this.отчетыToolStripMenuItem.Size = new System.Drawing.Size(60, 20); this.отчетыToolStripMenuItem.Text = "Отчеты"; // // списокКомпонентовToolStripMenuItem // this.списокКомпонентовToolStripMenuItem.Name = "списокКомпонентовToolStripMenuItem"; - this.списокКомпонентовToolStripMenuItem.Size = new System.Drawing.Size(276, 26); + this.списокКомпонентовToolStripMenuItem.Size = new System.Drawing.Size(218, 22); this.списокКомпонентовToolStripMenuItem.Text = "Список компонентов"; this.списокКомпонентовToolStripMenuItem.Click += new System.EventHandler(this.списокКомпонентовToolStripMenuItem_Click_1); // // компонентыПоИзделиямToolStripMenuItem // this.компонентыПоИзделиямToolStripMenuItem.Name = "компонентыПоИзделиямToolStripMenuItem"; - this.компонентыПоИзделиямToolStripMenuItem.Size = new System.Drawing.Size(276, 26); + this.компонентыПоИзделиямToolStripMenuItem.Size = new System.Drawing.Size(218, 22); this.компонентыПоИзделиямToolStripMenuItem.Text = "Компоненты по изделиям"; this.компонентыПоИзделиямToolStripMenuItem.Click += new System.EventHandler(this.компонентыПоИзделиямToolStripMenuItem_Click_1); // // списокЗаказовToolStripMenuItem // this.списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem"; - this.списокЗаказовToolStripMenuItem.Size = new System.Drawing.Size(276, 26); + this.списокЗаказовToolStripMenuItem.Size = new System.Drawing.Size(218, 22); this.списокЗаказовToolStripMenuItem.Text = "Список заказов"; this.списокЗаказовToolStripMenuItem.Click += new System.EventHandler(this.списокЗаказовToolStripMenuItem_Click_1); // // клиентыToolStripMenuItem // this.клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; - this.клиентыToolStripMenuItem.Size = new System.Drawing.Size(83, 24); + this.клиентыToolStripMenuItem.Size = new System.Drawing.Size(67, 20); this.клиентыToolStripMenuItem.Text = "Клиенты"; this.клиентыToolStripMenuItem.Click += new System.EventHandler(this.клиентыToolStripMenuItem_Click); // // исполнителиToolStripMenuItem // this.исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; - this.исполнителиToolStripMenuItem.Size = new System.Drawing.Size(116, 24); + this.исполнителиToolStripMenuItem.Size = new System.Drawing.Size(94, 20); this.исполнителиToolStripMenuItem.Text = "Исполнители"; this.исполнителиToolStripMenuItem.Click += new System.EventHandler(this.исполнителиToolStripMenuItem_Click); // // запускРаботToolStripMenuItem // this.запускРаботToolStripMenuItem.Name = "запускРаботToolStripMenuItem"; - this.запускРаботToolStripMenuItem.Size = new System.Drawing.Size(114, 24); + this.запускРаботToolStripMenuItem.Size = new System.Drawing.Size(92, 20); this.запускРаботToolStripMenuItem.Text = "Запуск работ"; this.запускРаботToolStripMenuItem.Click += new System.EventHandler(this.запускРаботToolStripMenuItem_Click); // + // письмаToolStripMenuItem + // + this.письмаToolStripMenuItem.Name = "письмаToolStripMenuItem"; + this.письмаToolStripMenuItem.Size = new System.Drawing.Size(62, 20); + this.письмаToolStripMenuItem.Text = "Письма"; + this.письмаToolStripMenuItem.Click += new System.EventHandler(this.письмаToolStripMenuItem_Click); + // // FormMain // - this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); + this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(1233, 595); + this.ClientSize = new System.Drawing.Size(1079, 446); this.Controls.Add(this.ButtonRef); this.Controls.Add(this.ButtonIssuedOrder); this.Controls.Add(this.ButtonCreateOrder); this.Controls.Add(this.dataGridView); this.Controls.Add(this.menuStrip1); this.MainMenuStrip = this.menuStrip1; - this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); this.Name = "FormMain"; this.Text = "Рыбный завод"; this.Load += new System.EventHandler(this.FormMain_Load); @@ -221,5 +225,6 @@ private ToolStripMenuItem клиентыToolStripMenuItem; private ToolStripMenuItem исполнителиToolStripMenuItem; private ToolStripMenuItem запускРаботToolStripMenuItem; + private ToolStripMenuItem письмаToolStripMenuItem; } } \ No newline at end of file diff --git a/FishFactory/FishFactory/FormMain.cs b/FishFactory/FishFactory/FormMain.cs index beee5cb..cdc2e16 100644 --- a/FishFactory/FishFactory/FormMain.cs +++ b/FishFactory/FishFactory/FormMain.cs @@ -178,5 +178,14 @@ namespace FishFactoryView _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(FormMail)); + if (service is FormMail form) + { + form.ShowDialog(); + } + } } } diff --git a/FishFactory/FishFactory/Program.cs b/FishFactory/FishFactory/Program.cs index aefabff..27af78b 100644 --- a/FishFactory/FishFactory/Program.cs +++ b/FishFactory/FishFactory/Program.cs @@ -9,6 +9,9 @@ using NLog.Extensions.Logging; using FishFactoryBusinessLogic.BusinessLogic; using FishFactoryBusinessLogic.OfficePackage; using FishFactoryBusinessLogic.OfficePackage.Implements; +using DocumentFormat.OpenXml.Wordprocessing; +using FishFactoryBusinessLogic.MailWorker; +using FishFactoryContracts.BindingModels; namespace ProjectFishFactory { @@ -28,6 +31,27 @@ namespace ProjectFishFactory 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) @@ -42,19 +66,23 @@ namespace ProjectFishFactory services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); - services.AddTransient(); services.AddTransient(); services.AddTransient(); - services.AddTransient(); + services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddSingleton(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -67,6 +95,9 @@ namespace ProjectFishFactory 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/FishFactory/FishFactoryBusinessLogic/BusinessLogic/ClientLogic.cs b/FishFactory/FishFactoryBusinessLogic/BusinessLogic/ClientLogic.cs index 670cf2e..dbf8424 100644 --- a/FishFactory/FishFactoryBusinessLogic/BusinessLogic/ClientLogic.cs +++ b/FishFactory/FishFactoryBusinessLogic/BusinessLogic/ClientLogic.cs @@ -8,6 +8,7 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; +using System.Text.RegularExpressions; using System.Threading.Tasks; namespace FishFactoryBusinessLogic.BusinessLogic @@ -110,6 +111,10 @@ namespace FishFactoryBusinessLogic.BusinessLogic { Email = model.Email, }); + if (!Regex.IsMatch(model.Password, @"^(?=.*\d)(?=.*\W)(?=.*[^\d\s]).+$")) + { + throw new ArgumentException("Некорректно введенный пароль. Пароль должен содержать хотя бы одну букву, цифру и не буквенный символ", nameof(model.Password)); + } if (element != null && element.Id != model.Id) { throw new InvalidOperationException("Клиент с таким логином уже есть"); diff --git a/FishFactory/FishFactoryBusinessLogic/BusinessLogic/MessageInfoLogic.cs b/FishFactory/FishFactoryBusinessLogic/BusinessLogic/MessageInfoLogic.cs new file mode 100644 index 0000000..dd9016d --- /dev/null +++ b/FishFactory/FishFactoryBusinessLogic/BusinessLogic/MessageInfoLogic.cs @@ -0,0 +1,48 @@ +using FishFactoryContracts.BindingModels; +using FishFactoryContracts.BusinessLogicsContracts; +using FishFactoryContracts.SearchModels; +using FishFactoryContracts.StoragesContracts; +using FishFactoryContracts.ViewModels; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FishFactoryBusinessLogic.BusinessLogic +{ + public class MessageInfoLogic : IMessageInfoLogic + { + private readonly ILogger _logger; + private readonly IMessageInfoStorage _messageInfoStorage; + public MessageInfoLogic(ILogger logger, IMessageInfoStorage MessageInfoStorage) + { + _logger = logger; + _messageInfoStorage = MessageInfoStorage; + } + + public bool Create(MessageInfoBindingModel model) + { + if (_messageInfoStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } + + public List? ReadList(MessageInfoSearchModel? model) + { + _logger.LogInformation("ReadList. MessageId:{MessageId}.ClientId:{ClientId} ", model?.MessageId, model?.ClientId); + var list = (model == null) ? _messageInfoStorage.GetFullList() : _messageInfoStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + _logger.LogInformation("ReadList. Count:{Count}", list.Count); + return list; + } + } +} diff --git a/FishFactory/FishFactoryBusinessLogic/BusinessLogic/OrderLogic.cs b/FishFactory/FishFactoryBusinessLogic/BusinessLogic/OrderLogic.cs index fe058e9..3edf020 100644 --- a/FishFactory/FishFactoryBusinessLogic/BusinessLogic/OrderLogic.cs +++ b/FishFactory/FishFactoryBusinessLogic/BusinessLogic/OrderLogic.cs @@ -1,4 +1,5 @@ -using FishFactoryContracts.BindingModels; +using FishFactoryBusinessLogic.MailWorker; +using FishFactoryContracts.BindingModels; using FishFactoryContracts.BusinessLogicsContracts; using FishFactoryContracts.SearchModels; using FishFactoryContracts.StoragesContracts; @@ -17,10 +18,14 @@ namespace FishFactoryBusinessLogic.BusinessLogic { private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; - public OrderLogic(ILogger logger, IOrderStorage orderStorage) + private readonly AbstractMailWorker _mailWorker; + private readonly IClientLogic _clientLogic; + public OrderLogic(ILogger logger, IOrderStorage orderStorage, AbstractMailWorker mailWorker, IClientLogic clientLogic) { _logger = logger; _orderStorage = orderStorage; + _mailWorker = mailWorker; + _clientLogic = clientLogic; } public bool CreateOrder(OrderBindingModel model) { @@ -31,12 +36,14 @@ namespace FishFactoryBusinessLogic.BusinessLogic return false; } model.Status = OrderStatus.Принят; - if (_orderStorage.Insert(model) == null) + var result = _orderStorage.Insert(model); + if (result == null) { model.Status = OrderStatus.Неизвестен; _logger.LogWarning("Insert operation failed"); return false; } + SendOrderMessage(result.ClientId, $"Заказ №{result.Id}", $"Заказ №{result.Id} от {result.DateCreate} на сумму {result.Sum:0.00} принят"); return true; } public bool StatusUpdate(OrderBindingModel model, OrderStatus newStatus) @@ -67,12 +74,14 @@ namespace FishFactoryBusinessLogic.BusinessLogic model.DateImplement = viewModel.DateImplement; } CheckModel(model); - if (_orderStorage.Update(model) == null) + var result = _orderStorage.Update(model); + if (result == null) { model.Status--; _logger.LogWarning("Update operation failed"); return false; } + SendOrderMessage(result.ClientId, $"Заказ №{result.Id}", $"Заказ №{model.Id} изменен статус на {result.Status}"); return true; } public bool DeliveryOrder(OrderBindingModel model) @@ -143,5 +152,21 @@ namespace FishFactoryBusinessLogic.BusinessLogic _logger.LogInformation("ReadElement find. Id:{Id}", element.Id); return element; } + + 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; + } } } diff --git a/FishFactory/FishFactoryBusinessLogic/FishFactoryBusinessLogic.csproj b/FishFactory/FishFactoryBusinessLogic/FishFactoryBusinessLogic.csproj index bdeb2f2..5b3630c 100644 --- a/FishFactory/FishFactoryBusinessLogic/FishFactoryBusinessLogic.csproj +++ b/FishFactory/FishFactoryBusinessLogic/FishFactoryBusinessLogic.csproj @@ -8,6 +8,7 @@ + diff --git a/FishFactory/FishFactoryBusinessLogic/MailWorker/AbstractMailWorker.cs b/FishFactory/FishFactoryBusinessLogic/MailWorker/AbstractMailWorker.cs new file mode 100644 index 0000000..e4263f2 --- /dev/null +++ b/FishFactory/FishFactoryBusinessLogic/MailWorker/AbstractMailWorker.cs @@ -0,0 +1,82 @@ +using FishFactoryContracts.BindingModels; +using FishFactoryContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FishFactoryBusinessLogic.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; + private readonly IClientLogic _clientLogic; + public AbstractMailWorker(ILogger logger, IMessageInfoLogic messageInfoLogic, IClientLogic client) + { + _clientLogic = client; + _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) + { + 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/FishFactory/FishFactoryBusinessLogic/MailWorker/MailKitWorker.cs b/FishFactory/FishFactoryBusinessLogic/MailWorker/MailKitWorker.cs new file mode 100644 index 0000000..57b3f36 --- /dev/null +++ b/FishFactory/FishFactoryBusinessLogic/MailWorker/MailKitWorker.cs @@ -0,0 +1,74 @@ +using FishFactoryContracts.BindingModels; +using FishFactoryContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using System.Net.Mail; +using System.Net; +using System.Text; +using MailKit.Net.Pop3; +using MailKit.Security; + +namespace FishFactoryBusinessLogic.MailWorker +{ + public class MailKitWorker : AbstractMailWorker + { + public MailKitWorker(ILogger logger, IMessageInfoLogic messageInfoLogic, IClientLogic client) : base(logger, messageInfoLogic, client) { } + 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/FishFactory/FishFactoryClientApp/Controllers/HomeController.cs b/FishFactory/FishFactoryClientApp/Controllers/HomeController.cs index 8d0be5d..43388e2 100644 --- a/FishFactory/FishFactoryClientApp/Controllers/HomeController.cs +++ b/FishFactory/FishFactoryClientApp/Controllers/HomeController.cs @@ -135,6 +135,16 @@ namespace FishFactoryClientApp.Controllers var prod = APIClient.GetRequest($"api/main/getcanned?cannedId={canned}"); 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/FishFactory/FishFactoryClientApp/Views/Home/Mails.cshtml b/FishFactory/FishFactoryClientApp/Views/Home/Mails.cshtml new file mode 100644 index 0000000..b3be8e9 --- /dev/null +++ b/FishFactory/FishFactoryClientApp/Views/Home/Mails.cshtml @@ -0,0 +1,54 @@ +@using FishFactoryContracts.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) +
+ } +
diff --git a/FishFactory/FishFactoryClientApp/Views/Shared/_Layout.cshtml b/FishFactory/FishFactoryClientApp/Views/Shared/_Layout.cshtml index f83c2a0..c144437 100644 --- a/FishFactory/FishFactoryClientApp/Views/Shared/_Layout.cshtml +++ b/FishFactory/FishFactoryClientApp/Views/Shared/_Layout.cshtml @@ -24,6 +24,9 @@ + diff --git a/FishFactory/FishFactoryContracts/BindingModels/MailConfigBindingModel.cs b/FishFactory/FishFactoryContracts/BindingModels/MailConfigBindingModel.cs new file mode 100644 index 0000000..1b2f2dc --- /dev/null +++ b/FishFactory/FishFactoryContracts/BindingModels/MailConfigBindingModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FishFactoryContracts.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/FishFactory/FishFactoryContracts/BindingModels/MailSendInfoBindingModel.cs b/FishFactory/FishFactoryContracts/BindingModels/MailSendInfoBindingModel.cs new file mode 100644 index 0000000..f6855b4 --- /dev/null +++ b/FishFactory/FishFactoryContracts/BindingModels/MailSendInfoBindingModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FishFactoryContracts.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/FishFactory/FishFactoryContracts/BindingModels/MessageInfoBindingModel.cs b/FishFactory/FishFactoryContracts/BindingModels/MessageInfoBindingModel.cs new file mode 100644 index 0000000..f723f5f --- /dev/null +++ b/FishFactory/FishFactoryContracts/BindingModels/MessageInfoBindingModel.cs @@ -0,0 +1,19 @@ +using FishFactoryDataModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FishFactoryContracts.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/FishFactory/FishFactoryContracts/BusinessLogicsContracts/IMessageInfoLogic.cs b/FishFactory/FishFactoryContracts/BusinessLogicsContracts/IMessageInfoLogic.cs new file mode 100644 index 0000000..89f528a --- /dev/null +++ b/FishFactory/FishFactoryContracts/BusinessLogicsContracts/IMessageInfoLogic.cs @@ -0,0 +1,17 @@ +using FishFactoryContracts.BindingModels; +using FishFactoryContracts.SearchModels; +using FishFactoryContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FishFactoryContracts.BusinessLogicsContracts +{ + public interface IMessageInfoLogic + { + List? ReadList(MessageInfoSearchModel? model); + bool Create(MessageInfoBindingModel model); + } +} diff --git a/FishFactory/FishFactoryContracts/SearchModels/MessageInfoSearchModel.cs b/FishFactory/FishFactoryContracts/SearchModels/MessageInfoSearchModel.cs new file mode 100644 index 0000000..b9227ca --- /dev/null +++ b/FishFactory/FishFactoryContracts/SearchModels/MessageInfoSearchModel.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FishFactoryContracts.SearchModels +{ + public class MessageInfoSearchModel + { + public int? ClientId { get; set; } + public string? MessageId { get; set; } + } +} diff --git a/FishFactory/FishFactoryContracts/StoragesContracts/IMessageInfoStorage.cs b/FishFactory/FishFactoryContracts/StoragesContracts/IMessageInfoStorage.cs new file mode 100644 index 0000000..51124ee --- /dev/null +++ b/FishFactory/FishFactoryContracts/StoragesContracts/IMessageInfoStorage.cs @@ -0,0 +1,19 @@ +using FishFactoryContracts.BindingModels; +using FishFactoryContracts.SearchModels; +using FishFactoryContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FishFactoryContracts.StoragesContracts +{ + public interface IMessageInfoStorage + { + List GetFullList(); + List GetFilteredList(MessageInfoSearchModel model); + MessageInfoViewModel? GetElement(MessageInfoSearchModel model); + MessageInfoViewModel? Insert(MessageInfoBindingModel model); + } +} diff --git a/FishFactory/FishFactoryContracts/ViewModels/MessageInfoViewModel.cs b/FishFactory/FishFactoryContracts/ViewModels/MessageInfoViewModel.cs new file mode 100644 index 0000000..2fdc164 --- /dev/null +++ b/FishFactory/FishFactoryContracts/ViewModels/MessageInfoViewModel.cs @@ -0,0 +1,28 @@ +using FishFactoryDataModels; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FishFactoryContracts.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/FishFactory/FishFactoryDataModels/IMessageInfoModel.cs b/FishFactory/FishFactoryDataModels/IMessageInfoModel.cs new file mode 100644 index 0000000..da2a3a8 --- /dev/null +++ b/FishFactory/FishFactoryDataModels/IMessageInfoModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FishFactoryDataModels +{ + public interface IMessageInfoModel + { + string MessageId { get; } + int? ClientId { get; } + string SenderName { get; } + DateTime DateDelivery { get; } + string Subject { get; } + string Body { get; } + } +} diff --git a/FishFactory/FishFactoryDatabaseImplement/FishFactoryDatabase.cs b/FishFactory/FishFactoryDatabaseImplement/FishFactoryDatabase.cs index 907f7b0..f6b70d8 100644 --- a/FishFactory/FishFactoryDatabaseImplement/FishFactoryDatabase.cs +++ b/FishFactory/FishFactoryDatabaseImplement/FishFactoryDatabase.cs @@ -15,7 +15,7 @@ namespace FishFactoryDatabaseImplement { if (optionsBuilder.IsConfigured == false) { - optionsBuilder.UseNpgsql("Host=localhost;Port=5432;Database=FishFactoryLab6;Username=postgres;Password=postgres"); + optionsBuilder.UseNpgsql("Host=localhost;Port=5432;Database=FishFactoryLab7;Username=postgres;Password=postgres"); } base.OnConfiguring(optionsBuilder); } @@ -25,5 +25,6 @@ namespace FishFactoryDatabaseImplement 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/FishFactory/FishFactoryDatabaseImplement/Implements/ClientStorage.cs b/FishFactory/FishFactoryDatabaseImplement/Implements/ClientStorage.cs index ca274ac..e714b50 100644 --- a/FishFactory/FishFactoryDatabaseImplement/Implements/ClientStorage.cs +++ b/FishFactory/FishFactoryDatabaseImplement/Implements/ClientStorage.cs @@ -27,17 +27,20 @@ namespace FishFactoryDatabaseImplement.Implements public ClientViewModel? GetElement(ClientSearchModel model) { + if (string.IsNullOrEmpty(model.ClientFIO) && + string.IsNullOrEmpty(model.Email) && + string.IsNullOrEmpty(model.Password) && + !model.Id.HasValue) + { + return null; + } using var context = new FishFactoryDatabase(); - if (model.Id.HasValue) - return context.Clients.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; - if (model.Email != null && model.Password != null) - return context.Clients - .FirstOrDefault(x => x.Email.Equals(model.Email) - && x.Password.Equals(model.Password)) - ?.GetViewModel; - if (model.Email != null) - return context.Clients.FirstOrDefault(x => x.Email.Equals(model.Email))?.GetViewModel; - return null; + return context.Clients + .FirstOrDefault(x => (string.IsNullOrEmpty(model.ClientFIO) || x.ClientFIO == model.ClientFIO) && + (string.IsNullOrEmpty(model.Email) || x.Email == model.Email) && + (string.IsNullOrEmpty(model.Password) || x.Password == model.Password) && + (!model.Id.HasValue || x.Id == model.Id)) + ?.GetViewModel; } public List GetFilteredList(ClientSearchModel model) diff --git a/FishFactory/FishFactoryDatabaseImplement/Implements/MessageInfoStorage.cs b/FishFactory/FishFactoryDatabaseImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..f25f5d3 --- /dev/null +++ b/FishFactory/FishFactoryDatabaseImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,57 @@ +using FishFactoryContracts.BindingModels; +using FishFactoryContracts.SearchModels; +using FishFactoryContracts.StoragesContracts; +using FishFactoryContracts.ViewModels; +using FishFactoryDatabaseImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FishFactoryDatabaseImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + using var context = new FishFactoryDatabase(); + if (model.MessageId != null) + { + return context.Messages.FirstOrDefault(x => x.MessageId == model.MessageId)?.GetViewModel; + } + return null; + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + using var context = new FishFactoryDatabase(); + return context.Messages + .Where(x => x.ClientId == model.ClientId) + .Select(x => x.GetViewModel) + .ToList(); + } + + public List GetFullList() + { + using var context = new FishFactoryDatabase(); + return context.Messages + .Select(x => x.GetViewModel) + .ToList(); + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + using var context = new FishFactoryDatabase(); + var newMessage = MessageInfo.Create(model); + if (newMessage == null || context.Messages.Any(x => x.MessageId.Equals(model.MessageId))) + { + return null; + } + context.Messages.Add(newMessage); + context.SaveChanges(); + return newMessage.GetViewModel; + } + } +} diff --git a/FishFactory/FishFactoryDatabaseImplement/Migrations/20230422093015_Init2.Designer.cs b/FishFactory/FishFactoryDatabaseImplement/Migrations/20230422093015_Init2.Designer.cs deleted file mode 100644 index 97763ec..0000000 --- a/FishFactory/FishFactoryDatabaseImplement/Migrations/20230422093015_Init2.Designer.cs +++ /dev/null @@ -1,257 +0,0 @@ -// -using System; -using FishFactoryDatabaseImplement; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Migrations; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; -using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; - -#nullable disable - -namespace FishFactoryDatabaseImplement.Migrations -{ - [DbContext(typeof(FishFactoryDatabase))] - [Migration("20230422093015_Init2")] - partial class Init2 - { - /// - protected override void BuildTargetModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder - .HasAnnotation("ProductVersion", "7.0.4") - .HasAnnotation("Relational:MaxIdentifierLength", 63); - - NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); - - modelBuilder.Entity("FishFactoryDatabaseImplement.Models.Canned", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("integer"); - - NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); - - b.Property("CannedName") - .IsRequired() - .HasColumnType("text"); - - b.Property("Price") - .HasColumnType("double precision"); - - b.HasKey("Id"); - - b.ToTable("Canneds"); - }); - - modelBuilder.Entity("FishFactoryDatabaseImplement.Models.CannedComponent", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("integer"); - - NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); - - b.Property("CannedId") - .HasColumnType("integer"); - - b.Property("ComponentId") - .HasColumnType("integer"); - - b.Property("Count") - .HasColumnType("integer"); - - b.HasKey("Id"); - - b.HasIndex("CannedId"); - - b.HasIndex("ComponentId"); - - b.ToTable("CannedComponents"); - }); - - modelBuilder.Entity("FishFactoryDatabaseImplement.Models.Client", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("integer"); - - NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); - - b.Property("ClientFIO") - .IsRequired() - .HasColumnType("text"); - - b.Property("Email") - .IsRequired() - .HasColumnType("text"); - - b.Property("Password") - .IsRequired() - .HasColumnType("text"); - - b.HasKey("Id"); - - b.ToTable("Clients"); - }); - - modelBuilder.Entity("FishFactoryDatabaseImplement.Models.Component", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("integer"); - - NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); - - b.Property("ComponentName") - .IsRequired() - .HasColumnType("text"); - - b.Property("Cost") - .HasColumnType("double precision"); - - b.HasKey("Id"); - - b.ToTable("Components"); - }); - - modelBuilder.Entity("FishFactoryDatabaseImplement.Models.Implementer", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("integer"); - - NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); - - b.Property("ImplementerFIO") - .IsRequired() - .HasColumnType("text"); - - b.Property("Password") - .IsRequired() - .HasColumnType("text"); - - b.Property("Qualification") - .HasColumnType("integer"); - - b.Property("WorkExperience") - .HasColumnType("integer"); - - b.HasKey("Id"); - - b.ToTable("Implementers"); - }); - - modelBuilder.Entity("FishFactoryDatabaseImplement.Models.Order", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("integer"); - - NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); - - b.Property("CannedId") - .HasColumnType("integer"); - - b.Property("ClientId") - .HasColumnType("integer"); - - b.Property("Count") - .HasColumnType("integer"); - - b.Property("DateCreate") - .HasColumnType("timestamp with time zone"); - - b.Property("DateImplement") - .HasColumnType("timestamp with time zone"); - - b.Property("ImplementerId") - .HasColumnType("integer"); - - b.Property("Status") - .HasColumnType("integer"); - - b.Property("Sum") - .HasColumnType("double precision"); - - b.HasKey("Id"); - - b.HasIndex("CannedId"); - - b.HasIndex("ClientId"); - - b.HasIndex("ImplementerId"); - - b.ToTable("Orders"); - }); - - modelBuilder.Entity("FishFactoryDatabaseImplement.Models.CannedComponent", b => - { - b.HasOne("FishFactoryDatabaseImplement.Models.Canned", "Canned") - .WithMany("Components") - .HasForeignKey("CannedId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("FishFactoryDatabaseImplement.Models.Component", "Component") - .WithMany("CannedComponents") - .HasForeignKey("ComponentId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Canned"); - - b.Navigation("Component"); - }); - - modelBuilder.Entity("FishFactoryDatabaseImplement.Models.Order", b => - { - b.HasOne("FishFactoryDatabaseImplement.Models.Canned", "Canned") - .WithMany("Orders") - .HasForeignKey("CannedId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("FishFactoryDatabaseImplement.Models.Client", "Client") - .WithMany("Orders") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("FishFactoryDatabaseImplement.Models.Implementer", "Implementer") - .WithMany("Orders") - .HasForeignKey("ImplementerId"); - - b.Navigation("Canned"); - - b.Navigation("Client"); - - b.Navigation("Implementer"); - }); - - modelBuilder.Entity("FishFactoryDatabaseImplement.Models.Canned", b => - { - b.Navigation("Components"); - - b.Navigation("Orders"); - }); - - modelBuilder.Entity("FishFactoryDatabaseImplement.Models.Client", b => - { - b.Navigation("Orders"); - }); - - modelBuilder.Entity("FishFactoryDatabaseImplement.Models.Component", b => - { - b.Navigation("CannedComponents"); - }); - - modelBuilder.Entity("FishFactoryDatabaseImplement.Models.Implementer", b => - { - b.Navigation("Orders"); - }); -#pragma warning restore 612, 618 - } - } -} diff --git a/FishFactory/FishFactoryDatabaseImplement/Migrations/20230422093015_Init2.cs b/FishFactory/FishFactoryDatabaseImplement/Migrations/20230422093015_Init2.cs deleted file mode 100644 index 15632e6..0000000 --- a/FishFactory/FishFactoryDatabaseImplement/Migrations/20230422093015_Init2.cs +++ /dev/null @@ -1,59 +0,0 @@ -using Microsoft.EntityFrameworkCore.Migrations; - -#nullable disable - -namespace FishFactoryDatabaseImplement.Migrations -{ - /// - public partial class Init2 : Migration - { - /// - protected override void Up(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropForeignKey( - name: "FK_Orders_Implementers_ImplementerId", - table: "Orders"); - - migrationBuilder.AlterColumn( - name: "ImplementerId", - table: "Orders", - type: "integer", - nullable: true, - oldClrType: typeof(int), - oldType: "integer"); - - migrationBuilder.AddForeignKey( - name: "FK_Orders_Implementers_ImplementerId", - table: "Orders", - column: "ImplementerId", - principalTable: "Implementers", - principalColumn: "Id"); - } - - /// - protected override void Down(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropForeignKey( - name: "FK_Orders_Implementers_ImplementerId", - table: "Orders"); - - migrationBuilder.AlterColumn( - name: "ImplementerId", - table: "Orders", - type: "integer", - nullable: false, - defaultValue: 0, - oldClrType: typeof(int), - oldType: "integer", - oldNullable: true); - - migrationBuilder.AddForeignKey( - name: "FK_Orders_Implementers_ImplementerId", - table: "Orders", - column: "ImplementerId", - principalTable: "Implementers", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - } - } -} diff --git a/FishFactory/FishFactoryDatabaseImplement/Migrations/20230411050354_Init.Designer.cs b/FishFactory/FishFactoryDatabaseImplement/Migrations/20230424175659_Init.Designer.cs similarity index 85% rename from FishFactory/FishFactoryDatabaseImplement/Migrations/20230411050354_Init.Designer.cs rename to FishFactory/FishFactoryDatabaseImplement/Migrations/20230424175659_Init.Designer.cs index fbc3d34..0c97a82 100644 --- a/FishFactory/FishFactoryDatabaseImplement/Migrations/20230411050354_Init.Designer.cs +++ b/FishFactory/FishFactoryDatabaseImplement/Migrations/20230424175659_Init.Designer.cs @@ -12,7 +12,7 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; namespace FishFactoryDatabaseImplement.Migrations { [DbContext(typeof(FishFactoryDatabase))] - [Migration("20230411050354_Init")] + [Migration("20230424175659_Init")] partial class Init { /// @@ -143,6 +143,36 @@ namespace FishFactoryDatabaseImplement.Migrations b.ToTable("Implementers"); }); + modelBuilder.Entity("FishFactoryDatabaseImplement.Models.MessageInfo", b => + { + b.Property("MessageId") + .HasColumnType("text"); + + b.Property("Body") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientId") + .HasColumnType("integer"); + + b.Property("DateDelivery") + .HasColumnType("timestamp with time zone"); + + b.Property("SenderName") + .IsRequired() + .HasColumnType("text"); + + b.Property("Subject") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("MessageId"); + + b.HasIndex("ClientId"); + + b.ToTable("Messages"); + }); + modelBuilder.Entity("FishFactoryDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -167,7 +197,6 @@ namespace FishFactoryDatabaseImplement.Migrations .HasColumnType("timestamp with time zone"); b.Property("ImplementerId") - .IsRequired() .HasColumnType("integer"); b.Property("Status") @@ -206,6 +235,15 @@ namespace FishFactoryDatabaseImplement.Migrations b.Navigation("Component"); }); + modelBuilder.Entity("FishFactoryDatabaseImplement.Models.MessageInfo", b => + { + b.HasOne("FishFactoryDatabaseImplement.Models.Client", "Client") + .WithMany("Messages") + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + modelBuilder.Entity("FishFactoryDatabaseImplement.Models.Order", b => { b.HasOne("FishFactoryDatabaseImplement.Models.Canned", "Canned") @@ -222,9 +260,7 @@ namespace FishFactoryDatabaseImplement.Migrations b.HasOne("FishFactoryDatabaseImplement.Models.Implementer", "Implementer") .WithMany("Orders") - .HasForeignKey("ImplementerId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); + .HasForeignKey("ImplementerId"); b.Navigation("Canned"); @@ -242,6 +278,8 @@ namespace FishFactoryDatabaseImplement.Migrations modelBuilder.Entity("FishFactoryDatabaseImplement.Models.Client", b => { + b.Navigation("Messages"); + b.Navigation("Orders"); }); diff --git a/FishFactory/FishFactoryDatabaseImplement/Migrations/20230411050354_Init.cs b/FishFactory/FishFactoryDatabaseImplement/Migrations/20230424175659_Init.cs similarity index 85% rename from FishFactory/FishFactoryDatabaseImplement/Migrations/20230411050354_Init.cs rename to FishFactory/FishFactoryDatabaseImplement/Migrations/20230424175659_Init.cs index f03d01b..cac210d 100644 --- a/FishFactory/FishFactoryDatabaseImplement/Migrations/20230411050354_Init.cs +++ b/FishFactory/FishFactoryDatabaseImplement/Migrations/20230424175659_Init.cs @@ -71,6 +71,27 @@ namespace FishFactoryDatabaseImplement.Migrations table.PrimaryKey("PK_Implementers", x => x.Id); }); + migrationBuilder.CreateTable( + name: "Messages", + columns: table => new + { + MessageId = table.Column(type: "text", nullable: false), + ClientId = table.Column(type: "integer", nullable: true), + SenderName = table.Column(type: "text", nullable: false), + DateDelivery = table.Column(type: "timestamp with time zone", nullable: false), + Subject = table.Column(type: "text", nullable: false), + Body = table.Column(type: "text", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Messages", x => x.MessageId); + table.ForeignKey( + name: "FK_Messages_Clients_ClientId", + column: x => x.ClientId, + principalTable: "Clients", + principalColumn: "Id"); + }); + migrationBuilder.CreateTable( name: "CannedComponents", columns: table => new @@ -106,7 +127,7 @@ namespace FishFactoryDatabaseImplement.Migrations .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), CannedId = table.Column(type: "integer", nullable: false), ClientId = table.Column(type: "integer", nullable: false), - ImplementerId = table.Column(type: "integer", nullable: false), + ImplementerId = table.Column(type: "integer", nullable: true), Count = table.Column(type: "integer", nullable: false), Sum = table.Column(type: "double precision", nullable: false), Status = table.Column(type: "integer", nullable: false), @@ -132,8 +153,7 @@ namespace FishFactoryDatabaseImplement.Migrations name: "FK_Orders_Implementers_ImplementerId", column: x => x.ImplementerId, principalTable: "Implementers", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); + principalColumn: "Id"); }); migrationBuilder.CreateIndex( @@ -146,6 +166,11 @@ namespace FishFactoryDatabaseImplement.Migrations table: "CannedComponents", column: "ComponentId"); + migrationBuilder.CreateIndex( + name: "IX_Messages_ClientId", + table: "Messages", + column: "ClientId"); + migrationBuilder.CreateIndex( name: "IX_Orders_CannedId", table: "Orders", @@ -168,6 +193,9 @@ namespace FishFactoryDatabaseImplement.Migrations migrationBuilder.DropTable( name: "CannedComponents"); + migrationBuilder.DropTable( + name: "Messages"); + migrationBuilder.DropTable( name: "Orders"); diff --git a/FishFactory/FishFactoryDatabaseImplement/Migrations/FishFactoryDatabaseModelSnapshot.cs b/FishFactory/FishFactoryDatabaseImplement/Migrations/FishFactoryDatabaseModelSnapshot.cs index 1e95606..2d8a75b 100644 --- a/FishFactory/FishFactoryDatabaseImplement/Migrations/FishFactoryDatabaseModelSnapshot.cs +++ b/FishFactory/FishFactoryDatabaseImplement/Migrations/FishFactoryDatabaseModelSnapshot.cs @@ -140,6 +140,36 @@ namespace FishFactoryDatabaseImplement.Migrations b.ToTable("Implementers"); }); + modelBuilder.Entity("FishFactoryDatabaseImplement.Models.MessageInfo", b => + { + b.Property("MessageId") + .HasColumnType("text"); + + b.Property("Body") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientId") + .HasColumnType("integer"); + + b.Property("DateDelivery") + .HasColumnType("timestamp with time zone"); + + b.Property("SenderName") + .IsRequired() + .HasColumnType("text"); + + b.Property("Subject") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("MessageId"); + + b.HasIndex("ClientId"); + + b.ToTable("Messages"); + }); + modelBuilder.Entity("FishFactoryDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -202,6 +232,15 @@ namespace FishFactoryDatabaseImplement.Migrations b.Navigation("Component"); }); + modelBuilder.Entity("FishFactoryDatabaseImplement.Models.MessageInfo", b => + { + b.HasOne("FishFactoryDatabaseImplement.Models.Client", "Client") + .WithMany("Messages") + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + modelBuilder.Entity("FishFactoryDatabaseImplement.Models.Order", b => { b.HasOne("FishFactoryDatabaseImplement.Models.Canned", "Canned") @@ -236,6 +275,8 @@ namespace FishFactoryDatabaseImplement.Migrations modelBuilder.Entity("FishFactoryDatabaseImplement.Models.Client", b => { + b.Navigation("Messages"); + b.Navigation("Orders"); }); diff --git a/FishFactory/FishFactoryDatabaseImplement/Models/Client.cs b/FishFactory/FishFactoryDatabaseImplement/Models/Client.cs index 3be0390..d1ce11b 100644 --- a/FishFactory/FishFactoryDatabaseImplement/Models/Client.cs +++ b/FishFactory/FishFactoryDatabaseImplement/Models/Client.cs @@ -26,6 +26,9 @@ namespace FishFactoryDatabaseImplement.Models [ForeignKey("ClientId")] public virtual List Orders { get; set; } = new(); + [ForeignKey("ClientId")] + public virtual List Messages { get; set; } = new(); + public static Client? Create(ClientBindingModel model) { if (model == null) diff --git a/FishFactory/FishFactoryDatabaseImplement/Models/MessageInfo.cs b/FishFactory/FishFactoryDatabaseImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..037a616 --- /dev/null +++ b/FishFactory/FishFactoryDatabaseImplement/Models/MessageInfo.cs @@ -0,0 +1,57 @@ +using FishFactoryContracts.BindingModels; +using FishFactoryContracts.ViewModels; +using FishFactoryDataModels; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FishFactoryDatabaseImplement.Models +{ + public class MessageInfo : IMessageInfoModel + { + [Key] + public string MessageId { get; private set; } = string.Empty; + + public int? ClientId { get; private set; } + + public string SenderName { get; private set; } = string.Empty; + + public DateTime DateDelivery { get; private set; } = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc); + + public string Subject { get; private set; } = string.Empty; + + public string Body { get; private set; } = string.Empty; + + public Client? Client { get; private set; } + + public static MessageInfo? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Subject = model.Subject, + ClientId = model.ClientId, + MessageId = model.MessageId, + SenderName = model.SenderName, + DateDelivery = DateTime.SpecifyKind(model.DateDelivery, DateTimeKind.Utc), + }; + } + + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Subject = Subject, + ClientId = ClientId, + MessageId = MessageId, + SenderName = SenderName, + DateDelivery = DateDelivery, + }; + } +} diff --git a/FishFactory/FishFactoryFileImplement/DataFileSingleton.cs b/FishFactory/FishFactoryFileImplement/DataFileSingleton.cs index afbc6aa..74af490 100644 --- a/FishFactory/FishFactoryFileImplement/DataFileSingleton.cs +++ b/FishFactory/FishFactoryFileImplement/DataFileSingleton.cs @@ -15,10 +15,14 @@ namespace FishFactoryFileImplement private readonly string OrderFileName = "Order.xml"; private readonly string CannedFileName = "Canned.xml"; private readonly string ClientFileName = "Client.xml"; + private readonly string MessageInfoFileName = "MessageInfo.xml"; + private readonly string ImplementerFileName = "Implementer.xml"; public List Components { get; private set; } public List Orders { get; private set; } public List Canneds { get; private set; } public List Clients { get; private set; } + public List Messages { get; private set; } + public static DataFileSingleton GetInstance() { if (instance == null) @@ -31,12 +35,15 @@ namespace FishFactoryFileImplement public void SaveCanneds() => SaveData(Canneds, CannedFileName, "Canneds", x => x.GetXElement); public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement); public void SaveClients() => SaveData(Clients, OrderFileName, "Clients", x => x.GetXElement); + public void SaveImplementers() => SaveData(Orders, ImplementerFileName, "Implementers", x => x.GetXElement); + public void SaveMessages() => SaveData(Orders, MessageInfoFileName, "Messages", x => x.GetXElement); private DataFileSingleton() { Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!; Canneds = LoadData(CannedFileName, "Canned", x => Canned.Create(x)!)!; Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!; Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!; + Messages = LoadData(MessageInfoFileName, "MessageInfo", x => MessageInfo.Create(x)!)!; } private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) { diff --git a/FishFactory/FishFactoryFileImplement/Implements/MessageInfoStorage.cs b/FishFactory/FishFactoryFileImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..669979b --- /dev/null +++ b/FishFactory/FishFactoryFileImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,58 @@ +using FishFactoryContracts.BindingModels; +using FishFactoryContracts.SearchModels; +using FishFactoryContracts.StoragesContracts; +using FishFactoryContracts.ViewModels; +using FishFactoryFileImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FishFactoryFileImplement.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/FishFactory/FishFactoryFileImplement/Models/MessageInfo.cs b/FishFactory/FishFactoryFileImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..e71afbb --- /dev/null +++ b/FishFactory/FishFactoryFileImplement/Models/MessageInfo.cs @@ -0,0 +1,80 @@ +using FishFactoryContracts.BindingModels; +using FishFactoryContracts.ViewModels; +using FishFactoryDataModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace FishFactoryFileImplement.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/FishFactory/FishFactoryListImplement/DataListSingleton.cs b/FishFactory/FishFactoryListImplement/DataListSingleton.cs index 08c9428..7b1296e 100644 --- a/FishFactory/FishFactoryListImplement/DataListSingleton.cs +++ b/FishFactory/FishFactoryListImplement/DataListSingleton.cs @@ -15,6 +15,7 @@ namespace FishFactoryListImplement public List Canneds { get; set; } public List Clients { get; set; } public List Implementers { get; set; } + public List Messages { get; set; } private DataListSingleton() { @@ -23,6 +24,7 @@ namespace FishFactoryListImplement Canneds = new List(); Clients = new List(); Implementers = new List(); + Messages = new List(); } public static DataListSingleton GetInstance() { diff --git a/FishFactory/FishFactoryListImplement/Implements/MessageInfoStorage.cs b/FishFactory/FishFactoryListImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..a50c898 --- /dev/null +++ b/FishFactory/FishFactoryListImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,66 @@ +using FishFactoryContracts.BindingModels; +using FishFactoryContracts.SearchModels; +using FishFactoryContracts.StoragesContracts; +using FishFactoryContracts.ViewModels; +using FishFactoryListImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FishFactoryListImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + private readonly DataListSingleton _source; + public MessageInfoStorage() + { + _source = DataListSingleton.GetInstance(); + } + + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + foreach (var message in _source.Messages) + { + if (model.MessageId != null && model.MessageId.Equals(message.MessageId)) + return message.GetViewModel; + } + return null; + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + List result = new(); + foreach (var item in _source.Messages) + { + if (item.ClientId.HasValue && item.ClientId == model.ClientId) + { + result.Add(item.GetViewModel); + } + } + return result; + } + + public List GetFullList() + { + List result = new(); + foreach (var item in _source.Messages) + { + result.Add(item.GetViewModel); + } + return result; + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = MessageInfo.Create(model); + if (newMessage == null) + { + return null; + } + _source.Messages.Add(newMessage); + return newMessage.GetViewModel; + } + } +} diff --git a/FishFactory/FishFactoryListImplement/Models/MessageInfo.cs b/FishFactory/FishFactoryListImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..6319fc6 --- /dev/null +++ b/FishFactory/FishFactoryListImplement/Models/MessageInfo.cs @@ -0,0 +1,46 @@ +using FishFactoryContracts.BindingModels; +using FishFactoryContracts.ViewModels; +using FishFactoryDataModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FishFactoryListImplement.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/FishFactory/FishFactoryRestApi/Controllers/ClientController.cs b/FishFactory/FishFactoryRestApi/Controllers/ClientController.cs index 2035bed..f3e6795 100644 --- a/FishFactory/FishFactoryRestApi/Controllers/ClientController.cs +++ b/FishFactory/FishFactoryRestApi/Controllers/ClientController.cs @@ -12,10 +12,12 @@ namespace FishFactoryRestApi.Controllers { 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) @@ -60,6 +62,23 @@ namespace FishFactoryRestApi.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/FishFactory/FishFactoryRestApi/FishFactoryRestApi.csproj b/FishFactory/FishFactoryRestApi/FishFactoryRestApi.csproj index 45f1d45..d2e5ed0 100644 --- a/FishFactory/FishFactoryRestApi/FishFactoryRestApi.csproj +++ b/FishFactory/FishFactoryRestApi/FishFactoryRestApi.csproj @@ -17,4 +17,10 @@
+ + + Always + + + diff --git a/FishFactory/FishFactoryRestApi/Program.cs b/FishFactory/FishFactoryRestApi/Program.cs index 038480a..a8f0504 100644 --- a/FishFactory/FishFactoryRestApi/Program.cs +++ b/FishFactory/FishFactoryRestApi/Program.cs @@ -1,4 +1,6 @@ using FishFactoryBusinessLogic.BusinessLogic; +using FishFactoryBusinessLogic.MailWorker; +using FishFactoryContracts.BindingModels; using FishFactoryContracts.BusinessLogicsContracts; using FishFactoryContracts.StoragesContracts; using FishFactoryDatabaseImplement.Implements; @@ -12,13 +14,18 @@ builder.Logging.AddLog4Net("log4net.config"); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddTransient(); + builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddSingleton(); builder.Services.AddControllers(); -// Learn more about configuring Swagger/OpenAPI at -https://aka.ms/aspnetcore/swashbuckle +// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(c => { @@ -29,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/FishFactory/FishFactoryRestApi/appsettings.json b/FishFactory/FishFactoryRestApi/appsettings.json index 10f68b8..a8cbae9 100644 --- a/FishFactory/FishFactoryRestApi/appsettings.json +++ b/FishFactory/FishFactoryRestApi/appsettings.json @@ -5,5 +5,12 @@ "Microsoft.AspNetCore": "Warning" } }, - "AllowedHosts": "*" + "AllowedHosts": "*", + + "SmtpClientHost": "smtp.gmail.com", + "SmtpClientPort": "587", + "PopHost": "pop.gmail.com", + "PopPort": "995", + "MailLogin": "rpplabs098@gmail.com", + "MailPassword": "sxwf ohjr cgba wext" } -- 2.25.1 From f465106840e9748fa3a479457a4ae1a41db0fc2d Mon Sep 17 00:00:00 2001 From: ArtemEmelyanov Date: Wed, 26 Apr 2023 11:58:55 +0400 Subject: [PATCH 2/2] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BA=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../FishFactoryBusinessLogic/BusinessLogic/ClientLogic.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/FishFactory/FishFactoryBusinessLogic/BusinessLogic/ClientLogic.cs b/FishFactory/FishFactoryBusinessLogic/BusinessLogic/ClientLogic.cs index dbf8424..2facaa4 100644 --- a/FishFactory/FishFactoryBusinessLogic/BusinessLogic/ClientLogic.cs +++ b/FishFactory/FishFactoryBusinessLogic/BusinessLogic/ClientLogic.cs @@ -111,6 +111,10 @@ namespace FishFactoryBusinessLogic.BusinessLogic { Email = model.Email, }); + if (!Regex.IsMatch(model.Email, @"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$")) + { + throw new ArgumentException("Некорретно введенный email", nameof(model.Email)); + } if (!Regex.IsMatch(model.Password, @"^(?=.*\d)(?=.*\W)(?=.*[^\d\s]).+$")) { throw new ArgumentException("Некорректно введенный пароль. Пароль должен содержать хотя бы одну букву, цифру и не буквенный символ", nameof(model.Password)); -- 2.25.1