diff --git a/FlowerShop/FlowerShop/App.config b/FlowerShop/FlowerShop/App.config new file mode 100644 index 0000000..0b63381 --- /dev/null +++ b/FlowerShop/FlowerShop/App.config @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/FlowerShop/FlowerShop/FormMail.Designer.cs b/FlowerShop/FlowerShop/FormMail.Designer.cs new file mode 100644 index 0000000..ef8474c --- /dev/null +++ b/FlowerShop/FlowerShop/FormMail.Designer.cs @@ -0,0 +1,68 @@ +namespace FlowerShopView +{ + 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() + { + dataGridView = new DataGridView(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // DataGridView + // + dataGridView.AllowUserToAddRows = false; + dataGridView.AllowUserToDeleteRows = false; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Dock = DockStyle.Fill; + dataGridView.Location = new Point(0, 0); + dataGridView.Margin = new Padding(3, 2, 3, 2); + dataGridView.Name = "DataGridView"; + dataGridView.ReadOnly = true; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 29; + dataGridView.Size = new Size(1084, 456); + dataGridView.TabIndex = 0; + // + // FormMail + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(1084, 456); + Controls.Add(dataGridView); + Margin = new Padding(3, 2, 3, 2); + Name = "FormMail"; + Text = "Письма"; + Load += FormMail_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView; + } +} \ No newline at end of file diff --git a/FlowerShop/FlowerShop/FormMail.cs b/FlowerShop/FlowerShop/FormMail.cs new file mode 100644 index 0000000..72f0ca0 --- /dev/null +++ b/FlowerShop/FlowerShop/FormMail.cs @@ -0,0 +1,47 @@ +using FlowerShopContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; + +namespace FlowerShopView +{ + public partial class FormMail : Form + { + private readonly ILogger _logger; + private readonly IMessageInfoLogic _messageLogic; + + public FormMail(ILogger Logger, IMessageInfoLogic MessageLogic) + { + InitializeComponent(); + + _logger = Logger; + _messageLogic = MessageLogic; + } + + private void LoadData() + { + try + { + var List = _messageLogic.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(); + } + } +} diff --git a/FlowerShop/FlowerShop/FormMail.resx b/FlowerShop/FlowerShop/FormMail.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/FlowerShop/FlowerShop/FormMail.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/FlowerShop/FlowerShop/FormMain.Designer.cs b/FlowerShop/FlowerShop/FormMain.Designer.cs index b8d27df..0ac44ad 100644 --- a/FlowerShop/FlowerShop/FormMain.Designer.cs +++ b/FlowerShop/FlowerShop/FormMain.Designer.cs @@ -20,184 +20,192 @@ base.Dispose(disposing); } - #region Windows Form Designer generated code + #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() - { - menuStrip1 = new MenuStrip(); - справочникиToolStripMenuItem = new ToolStripMenuItem(); - ЦветыToolStripMenuItem = new ToolStripMenuItem(); - КомпонентыToolStripMenuItem = new ToolStripMenuItem(); - клиентыToolStripMenuItem = new ToolStripMenuItem(); - исполнителиToolStripMenuItem = new ToolStripMenuItem(); - отчётыToolStripMenuItem = new ToolStripMenuItem(); - списокЦветковToolStripMenuItem = new ToolStripMenuItem(); - компонентыПоЦветамToolStripMenuItem = new ToolStripMenuItem(); - списокЗаказовToolStripMenuItem = new ToolStripMenuItem(); - запускToolStripMenuItem = new ToolStripMenuItem(); - dataGridView = new DataGridView(); - buttonCreateOrder = new Button(); - buttonIssuedOrder = new Button(); - buttonRef = new Button(); - menuStrip1.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); - SuspendLayout(); - // - // menuStrip1 - // - menuStrip1.ImageScalingSize = new Size(20, 20); - menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчётыToolStripMenuItem, запускToolStripMenuItem }); - menuStrip1.Location = new Point(0, 0); - menuStrip1.Name = "menuStrip1"; - menuStrip1.Padding = new Padding(7, 3, 0, 3); - menuStrip1.Size = new Size(1102, 30); - menuStrip1.TabIndex = 0; - menuStrip1.Text = "menuStrip1"; - // - // справочникиToolStripMenuItem - // - справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { ЦветыToolStripMenuItem, КомпонентыToolStripMenuItem, клиентыToolStripMenuItem, исполнителиToolStripMenuItem }); - справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; - справочникиToolStripMenuItem.Size = new Size(117, 24); - справочникиToolStripMenuItem.Text = "Справочники"; - // - // ЦветыToolStripMenuItem - // - ЦветыToolStripMenuItem.Name = "ЦветыToolStripMenuItem"; - ЦветыToolStripMenuItem.Size = new Size(185, 26); - ЦветыToolStripMenuItem.Text = "Цветы"; - ЦветыToolStripMenuItem.Click += ЦветыToolStripMenuItem_Click; - // - // КомпонентыToolStripMenuItem - // - КомпонентыToolStripMenuItem.Name = "КомпонентыToolStripMenuItem"; - КомпонентыToolStripMenuItem.Size = new Size(185, 26); - КомпонентыToolStripMenuItem.Text = "Компоненты"; - КомпонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click; - // - // клиентыToolStripMenuItem - // - клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; - клиентыToolStripMenuItem.Size = new Size(185, 26); - клиентыToolStripMenuItem.Text = "Клиенты"; - клиентыToolStripMenuItem.Click += клиентыToolStripMenuItem_Click; - // - // исполнителиToolStripMenuItem - // - исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; - исполнителиToolStripMenuItem.Size = new Size(185, 26); - исполнителиToolStripMenuItem.Text = "Исполнители"; - исполнителиToolStripMenuItem.Click += исполнителиToolStripMenuItem_Click; - // - // отчётыToolStripMenuItem - // - отчётыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокЦветковToolStripMenuItem, компонентыПоЦветамToolStripMenuItem, списокЗаказовToolStripMenuItem }); - отчётыToolStripMenuItem.Name = "отчётыToolStripMenuItem"; - отчётыToolStripMenuItem.Size = new Size(73, 24); - отчётыToolStripMenuItem.Text = "Отчёты"; - // - // списокЦветковToolStripMenuItem - // - списокЦветковToolStripMenuItem.Name = "списокЦветковToolStripMenuItem"; - списокЦветковToolStripMenuItem.Size = new Size(258, 26); - списокЦветковToolStripMenuItem.Text = "Список цветков"; - списокЦветковToolStripMenuItem.Click += списокЦветковToolStripMenuItem_Click; - // - // компонентыПоЦветамToolStripMenuItem - // - компонентыПоЦветамToolStripMenuItem.Name = "компонентыПоЦветамToolStripMenuItem"; - компонентыПоЦветамToolStripMenuItem.Size = new Size(258, 26); - компонентыПоЦветамToolStripMenuItem.Text = "Компоненты по цветам"; - компонентыПоЦветамToolStripMenuItem.Click += компонентыПоЦветамToolStripMenuItem_Click; - // - // списокЗаказовToolStripMenuItem - // - списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem"; - списокЗаказовToolStripMenuItem.Size = new Size(258, 26); - списокЗаказовToolStripMenuItem.Text = "Список заказов"; - списокЗаказовToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click; - // - // запускToolStripMenuItem - // - запускToolStripMenuItem.Name = "запускToolStripMenuItem"; - запускToolStripMenuItem.Size = new Size(114, 24); - запускToolStripMenuItem.Text = "Запуск работ"; - запускToolStripMenuItem.Click += запускToolStripMenuItem_Click; - // - // dataGridView - // - dataGridView.BackgroundColor = Color.White; - dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; - dataGridView.Location = new Point(14, 36); - dataGridView.Margin = new Padding(3, 4, 3, 4); - dataGridView.Name = "dataGridView"; - dataGridView.RowHeadersWidth = 51; - dataGridView.RowTemplate.Height = 25; - dataGridView.Size = new Size(845, 548); - dataGridView.TabIndex = 1; - // - // buttonCreateOrder - // - buttonCreateOrder.Location = new Point(886, 73); - buttonCreateOrder.Margin = new Padding(3, 4, 3, 4); - buttonCreateOrder.Name = "buttonCreateOrder"; - buttonCreateOrder.Size = new Size(181, 43); - buttonCreateOrder.TabIndex = 2; - buttonCreateOrder.Text = "Создать заказ"; - buttonCreateOrder.UseVisualStyleBackColor = true; - buttonCreateOrder.Click += ButtonCreateOrder_Click; - // - // buttonIssuedOrder - // - buttonIssuedOrder.Location = new Point(886, 147); - buttonIssuedOrder.Margin = new Padding(3, 4, 3, 4); - buttonIssuedOrder.Name = "buttonIssuedOrder"; - buttonIssuedOrder.Size = new Size(181, 43); - buttonIssuedOrder.TabIndex = 3; - buttonIssuedOrder.Text = "Заказ выдан"; - buttonIssuedOrder.UseVisualStyleBackColor = true; - buttonIssuedOrder.Click += ButtonIssuedOrder_Click; - // - // buttonRef - // - buttonRef.Location = new Point(886, 220); - buttonRef.Margin = new Padding(3, 4, 3, 4); - buttonRef.Name = "buttonRef"; - buttonRef.Size = new Size(181, 43); - buttonRef.TabIndex = 6; - buttonRef.Text = "Обновить список"; - buttonRef.UseVisualStyleBackColor = true; - buttonRef.Click += ButtonRef_Click; - // - // FormMain - // - AutoScaleDimensions = new SizeF(8F, 20F); - AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1102, 600); - Controls.Add(buttonRef); - Controls.Add(buttonIssuedOrder); - Controls.Add(buttonCreateOrder); - Controls.Add(dataGridView); - Controls.Add(menuStrip1); - MainMenuStrip = menuStrip1; - Margin = new Padding(3, 4, 3, 4); - Name = "FormMain"; - Text = "Цветочный магазин"; - Load += FormMain_Load; - menuStrip1.ResumeLayout(false); - menuStrip1.PerformLayout(); - ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); - ResumeLayout(false); - PerformLayout(); - } + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + menuStrip1 = new MenuStrip(); + справочникиToolStripMenuItem = new ToolStripMenuItem(); + ЦветыToolStripMenuItem = new ToolStripMenuItem(); + КомпонентыToolStripMenuItem = new ToolStripMenuItem(); + клиентыToolStripMenuItem = new ToolStripMenuItem(); + исполнителиToolStripMenuItem = new ToolStripMenuItem(); + отчётыToolStripMenuItem = new ToolStripMenuItem(); + списокЦветковToolStripMenuItem = new ToolStripMenuItem(); + компонентыПоЦветамToolStripMenuItem = new ToolStripMenuItem(); + списокЗаказовToolStripMenuItem = new ToolStripMenuItem(); + запускToolStripMenuItem = new ToolStripMenuItem(); + dataGridView = new DataGridView(); + buttonCreateOrder = new Button(); + buttonIssuedOrder = new Button(); + buttonRef = new Button(); + письмаToolStripMenuItem = new ToolStripMenuItem(); + menuStrip1.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // menuStrip1 + // + menuStrip1.ImageScalingSize = new Size(20, 20); + menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчётыToolStripMenuItem, запускToolStripMenuItem, письмаToolStripMenuItem }); + menuStrip1.Location = new Point(0, 0); + menuStrip1.Name = "menuStrip1"; + menuStrip1.Padding = new Padding(7, 3, 0, 3); + menuStrip1.Size = new Size(1102, 30); + menuStrip1.TabIndex = 0; + menuStrip1.Text = "menuStrip1"; + // + // справочникиToolStripMenuItem + // + справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { ЦветыToolStripMenuItem, КомпонентыToolStripMenuItem, клиентыToolStripMenuItem, исполнителиToolStripMenuItem }); + справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; + справочникиToolStripMenuItem.Size = new Size(117, 24); + справочникиToolStripMenuItem.Text = "Справочники"; + // + // ЦветыToolStripMenuItem + // + ЦветыToolStripMenuItem.Name = "ЦветыToolStripMenuItem"; + ЦветыToolStripMenuItem.Size = new Size(224, 26); + ЦветыToolStripMenuItem.Text = "Цветы"; + ЦветыToolStripMenuItem.Click += ЦветыToolStripMenuItem_Click; + // + // КомпонентыToolStripMenuItem + // + КомпонентыToolStripMenuItem.Name = "КомпонентыToolStripMenuItem"; + КомпонентыToolStripMenuItem.Size = new Size(224, 26); + КомпонентыToolStripMenuItem.Text = "Компоненты"; + КомпонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click; + // + // клиентыToolStripMenuItem + // + клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; + клиентыToolStripMenuItem.Size = new Size(224, 26); + клиентыToolStripMenuItem.Text = "Клиенты"; + клиентыToolStripMenuItem.Click += клиентыToolStripMenuItem_Click; + // + // исполнителиToolStripMenuItem + // + исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; + исполнителиToolStripMenuItem.Size = new Size(224, 26); + исполнителиToolStripMenuItem.Text = "Исполнители"; + исполнителиToolStripMenuItem.Click += исполнителиToolStripMenuItem_Click; + // + // отчётыToolStripMenuItem + // + отчётыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокЦветковToolStripMenuItem, компонентыПоЦветамToolStripMenuItem, списокЗаказовToolStripMenuItem }); + отчётыToolStripMenuItem.Name = "отчётыToolStripMenuItem"; + отчётыToolStripMenuItem.Size = new Size(73, 24); + отчётыToolStripMenuItem.Text = "Отчёты"; + // + // списокЦветковToolStripMenuItem + // + списокЦветковToolStripMenuItem.Name = "списокЦветковToolStripMenuItem"; + списокЦветковToolStripMenuItem.Size = new Size(258, 26); + списокЦветковToolStripMenuItem.Text = "Список цветков"; + списокЦветковToolStripMenuItem.Click += списокЦветковToolStripMenuItem_Click; + // + // компонентыПоЦветамToolStripMenuItem + // + компонентыПоЦветамToolStripMenuItem.Name = "компонентыПоЦветамToolStripMenuItem"; + компонентыПоЦветамToolStripMenuItem.Size = new Size(258, 26); + компонентыПоЦветамToolStripMenuItem.Text = "Компоненты по цветам"; + компонентыПоЦветамToolStripMenuItem.Click += компонентыПоЦветамToolStripMenuItem_Click; + // + // списокЗаказовToolStripMenuItem + // + списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem"; + списокЗаказовToolStripMenuItem.Size = new Size(258, 26); + списокЗаказовToolStripMenuItem.Text = "Список заказов"; + списокЗаказовToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click; + // + // запускToolStripMenuItem + // + запускToolStripMenuItem.Name = "запускToolStripMenuItem"; + запускToolStripMenuItem.Size = new Size(114, 24); + запускToolStripMenuItem.Text = "Запуск работ"; + запускToolStripMenuItem.Click += запускToolStripMenuItem_Click; + // + // dataGridView + // + dataGridView.BackgroundColor = Color.White; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(14, 36); + dataGridView.Margin = new Padding(3, 4, 3, 4); + dataGridView.Name = "dataGridView"; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 25; + dataGridView.Size = new Size(845, 548); + dataGridView.TabIndex = 1; + // + // buttonCreateOrder + // + buttonCreateOrder.Location = new Point(886, 73); + buttonCreateOrder.Margin = new Padding(3, 4, 3, 4); + buttonCreateOrder.Name = "buttonCreateOrder"; + buttonCreateOrder.Size = new Size(181, 43); + buttonCreateOrder.TabIndex = 2; + buttonCreateOrder.Text = "Создать заказ"; + buttonCreateOrder.UseVisualStyleBackColor = true; + buttonCreateOrder.Click += ButtonCreateOrder_Click; + // + // buttonIssuedOrder + // + buttonIssuedOrder.Location = new Point(886, 147); + buttonIssuedOrder.Margin = new Padding(3, 4, 3, 4); + buttonIssuedOrder.Name = "buttonIssuedOrder"; + buttonIssuedOrder.Size = new Size(181, 43); + buttonIssuedOrder.TabIndex = 3; + buttonIssuedOrder.Text = "Заказ выдан"; + buttonIssuedOrder.UseVisualStyleBackColor = true; + buttonIssuedOrder.Click += ButtonIssuedOrder_Click; + // + // buttonRef + // + buttonRef.Location = new Point(886, 220); + buttonRef.Margin = new Padding(3, 4, 3, 4); + buttonRef.Name = "buttonRef"; + buttonRef.Size = new Size(181, 43); + buttonRef.TabIndex = 6; + buttonRef.Text = "Обновить список"; + buttonRef.UseVisualStyleBackColor = true; + buttonRef.Click += ButtonRef_Click; + // + // письмаToolStripMenuItem + // + письмаToolStripMenuItem.Name = "письмаToolStripMenuItem"; + письмаToolStripMenuItem.Size = new Size(77, 24); + письмаToolStripMenuItem.Text = "Письма"; + письмаToolStripMenuItem.Click += письмаToolStripMenuItem_Click; + // + // FormMain + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(1102, 600); + Controls.Add(buttonRef); + Controls.Add(buttonIssuedOrder); + Controls.Add(buttonCreateOrder); + Controls.Add(dataGridView); + Controls.Add(menuStrip1); + MainMenuStrip = menuStrip1; + Margin = new Padding(3, 4, 3, 4); + Name = "FormMain"; + Text = "Цветочный магазин"; + Load += FormMain_Load; + menuStrip1.ResumeLayout(false); + menuStrip1.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + PerformLayout(); + } - #endregion + #endregion - private MenuStrip menuStrip1; + private MenuStrip menuStrip1; private ToolStripMenuItem справочникиToolStripMenuItem; private ToolStripMenuItem ЦветыToolStripMenuItem; private ToolStripMenuItem КомпонентыToolStripMenuItem; @@ -212,5 +220,6 @@ private ToolStripMenuItem клиентыToolStripMenuItem; private ToolStripMenuItem исполнителиToolStripMenuItem; private ToolStripMenuItem запускToolStripMenuItem; + private ToolStripMenuItem письмаToolStripMenuItem; } } \ No newline at end of file diff --git a/FlowerShop/FlowerShop/FormMain.cs b/FlowerShop/FlowerShop/FormMain.cs index e19e7bc..44ea087 100644 --- a/FlowerShop/FlowerShop/FormMain.cs +++ b/FlowerShop/FlowerShop/FormMain.cs @@ -34,6 +34,7 @@ namespace FlowerShopView dataGridView.DataSource = list; dataGridView.Columns["FlowerId"].Visible = false; dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["ClientEmail"].Visible = false; dataGridView.Columns["ImplementerId"].Visible = false; } } @@ -150,7 +151,17 @@ namespace FlowerShopView private void запускToolStripMenuItem_Click(object sender, EventArgs e) { _workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic); - MessageBox.Show("Процесс обработки запущен", "Сообщение",MessageBoxButtons.OK, MessageBoxIcon.Information); + 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/FlowerShop/FlowerShop/Program.cs b/FlowerShop/FlowerShop/Program.cs index d334694..131b0bd 100644 --- a/FlowerShop/FlowerShop/Program.cs +++ b/FlowerShop/FlowerShop/Program.cs @@ -1,4 +1,4 @@ -using FlowerShopBusinessLogic.BusinessLogics; +using FlowerShopBusinessLogic.BusinessLogics; using FlowerShopBusinessLogic.OfficePackage.Implements; using FlowerShopBusinessLogic.OfficePackage; using FlowerShopContracts.BusinessLogicsContracts; @@ -7,6 +7,8 @@ using FlowerShopDatabaseImplement.Implements; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; +using FlowerShopBusinessLogic.MailWorker; +using FlowerShopContracts.BindingModels; namespace FlowerShopView { @@ -26,6 +28,28 @@ namespace FlowerShopView 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) @@ -40,18 +64,21 @@ namespace FlowerShopView 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(); @@ -65,6 +92,8 @@ namespace FlowerShopView 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/FlowerShop/FlowerShopBusinessLogic/BusinessLogics/ClientLogic.cs b/FlowerShop/FlowerShopBusinessLogic/BusinessLogics/ClientLogic.cs index b5dff7f..d4a6f48 100644 --- a/FlowerShop/FlowerShopBusinessLogic/BusinessLogics/ClientLogic.cs +++ b/FlowerShop/FlowerShopBusinessLogic/BusinessLogics/ClientLogic.cs @@ -1,9 +1,11 @@ -using FlowerShopContracts.BindingModels; +using DocumentFormat.OpenXml.EMMA; +using FlowerShopContracts.BindingModels; using FlowerShopContracts.BusinessLogicsContracts; using FlowerShopContracts.SearchModels; using FlowerShopContracts.StoragesContracts; using FlowerShopContracts.ViewModels; using Microsoft.Extensions.Logging; +using System.Text.RegularExpressions; namespace FlowerShopBusinessLogic.BusinessLogics { @@ -92,14 +94,13 @@ namespace FlowerShopBusinessLogic.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}. Password:{ Password}. Email:{ Email}. Id: { Id}", model.ClientFIO, model.Password, model.Email, model.Id); var element = _clientStorage.GetElement(new ClientSearchModel diff --git a/FlowerShop/FlowerShopBusinessLogic/BusinessLogics/MessageInfoLogic.cs b/FlowerShop/FlowerShopBusinessLogic/BusinessLogics/MessageInfoLogic.cs new file mode 100644 index 0000000..ea49db3 --- /dev/null +++ b/FlowerShop/FlowerShopBusinessLogic/BusinessLogics/MessageInfoLogic.cs @@ -0,0 +1,85 @@ +using FlowerShopContracts.BindingModels; +using FlowerShopContracts.BusinessLogicsContracts; +using FlowerShopContracts.SearchModels; +using FlowerShopContracts.StoragesContracts; +using FlowerShopContracts.ViewModels; +using Microsoft.Extensions.Logging; + +namespace FlowerShopBusinessLogic.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.LogDebug("ReadList. MessageId: {MessageId}, ClientId: {ClientId}", model?.MessageId, model?.ClientId); + + var result = model == null ? _messageInfoStorage.GetFullList() : _messageInfoStorage.GetFilteredList(model); + + _logger.LogDebug("ReadList result. Count: {Count}", result.Count); + return result; + } + + 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}", model.SenderName); + } + else + { + model.ClientId = Element.Id; + } + } + } +} \ No newline at end of file diff --git a/FlowerShop/FlowerShopBusinessLogic/BusinessLogics/OrderLogic.cs b/FlowerShop/FlowerShopBusinessLogic/BusinessLogics/OrderLogic.cs index 0e7caba..fd6fceb 100644 --- a/FlowerShop/FlowerShopBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/FlowerShop/FlowerShopBusinessLogic/BusinessLogics/OrderLogic.cs @@ -1,4 +1,5 @@ -using FlowerShopContracts.BindingModels; +using FlowerShopBusinessLogic.MailWorker; +using FlowerShopContracts.BindingModels; using FlowerShopContracts.BusinessLogicsContracts; using FlowerShopContracts.SearchModels; using FlowerShopContracts.StoragesContracts; @@ -12,11 +13,13 @@ namespace FlowerShopBusinessLogic.BusinessLogics { private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; - static readonly object _locker = new object(); - public OrderLogic(ILogger logger, IOrderStorage orderStorage) + private readonly AbstractMailWorker _mailLogic; + static readonly object _locker = new object(); + public OrderLogic(ILogger logger, IOrderStorage orderStorage, AbstractMailWorker mailLogic) { _logger = logger; _orderStorage = orderStorage; + _mailLogic = mailLogic; } public List? ReadList(OrderSearchModel? model) { @@ -57,14 +60,22 @@ namespace FlowerShopBusinessLogic.BusinessLogics if (model.Status != OrderStatus.Неизвестен) return false; model.Status = OrderStatus.Принят; - if (_orderStorage.Insert(model) == null) + var createdOrder = _orderStorage.Insert(model); + if (createdOrder == null) { model.Status = OrderStatus.Неизвестен; _logger.LogWarning("Insert operation failed"); return false; } - return true; - } + Task.Run(() => _mailLogic.MailSendAsync(new MailSendInfoBindingModel + { + MailAddress = createdOrder.ClientEmail, + Subject = $"Изменение статуса заказа номер {createdOrder.Id}", + Text = $"Ваш заказ №{createdOrder.Id} на покупку цветов {createdOrder.FlowerName} от {createdOrder.DateCreate} на сумму {createdOrder.Sum} принят." + })); + + return true; + } public bool TakeOrderInWork(OrderBindingModel model) { lock (_locker) @@ -120,7 +131,14 @@ namespace FlowerShopBusinessLogic.BusinessLogics _logger.LogWarning("Changing status operation faled"); return false; } - return true; + string dateInfo = model.DateImplement.HasValue ? $"Дата выполнения: {model.DateImplement}" : ""; + Task.Run(() => _mailLogic.MailSendAsync(new MailSendInfoBindingModel + { + MailAddress = element.ClientEmail, + Subject = $"Изменение статуса заказа номер {element.Id}", + Text = $"Ваш заказ №{element.Id} на покупку цветов {element.FlowerName} от {element.DateCreate} на сумму {element.Sum}. Статус изменен на {orderStatus}. {dateInfo}" + })); + return true; } private void CheckModel(OrderBindingModel model, bool withParams = true) { diff --git a/FlowerShop/FlowerShopBusinessLogic/FlowerShopBusinessLogic.csproj b/FlowerShop/FlowerShopBusinessLogic/FlowerShopBusinessLogic.csproj index b89f2e6..c53a978 100644 --- a/FlowerShop/FlowerShopBusinessLogic/FlowerShopBusinessLogic.csproj +++ b/FlowerShop/FlowerShopBusinessLogic/FlowerShopBusinessLogic.csproj @@ -8,6 +8,7 @@ + diff --git a/FlowerShop/FlowerShopBusinessLogic/MailWorker/AbstractMailWorker.cs b/FlowerShop/FlowerShopBusinessLogic/MailWorker/AbstractMailWorker.cs new file mode 100644 index 0000000..04b8e5d --- /dev/null +++ b/FlowerShop/FlowerShopBusinessLogic/MailWorker/AbstractMailWorker.cs @@ -0,0 +1,76 @@ +using FlowerShopContracts.BindingModels; +using FlowerShopContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; + +namespace FlowerShopBusinessLogic.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/FlowerShop/FlowerShopBusinessLogic/MailWorker/MailKitWorker.cs b/FlowerShop/FlowerShopBusinessLogic/MailWorker/MailKitWorker.cs new file mode 100644 index 0000000..3d17f2e --- /dev/null +++ b/FlowerShop/FlowerShopBusinessLogic/MailWorker/MailKitWorker.cs @@ -0,0 +1,74 @@ +using FlowerShopContracts.BindingModels; +using FlowerShopContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using MailKit.Net.Pop3; +using MailKit.Security; +using System.Net; +using System.Net.Mail; +using System.Text; + +namespace FlowerShopBusinessLogic.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 (AuthenticationException) { } + finally + { + client.Disconnect(true); + } + }); + return list; + } + + } +} diff --git a/FlowerShop/FlowerShopClientApp/Controllers/HomeController.cs b/FlowerShop/FlowerShopClientApp/Controllers/HomeController.cs index f57ad6b..fd84327 100644 --- a/FlowerShop/FlowerShopClientApp/Controllers/HomeController.cs +++ b/FlowerShop/FlowerShopClientApp/Controllers/HomeController.cs @@ -2,6 +2,7 @@ using FlowerShopContracts.BindingModels; using FlowerShopContracts.ViewModels; using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging; using System.Diagnostics; namespace FlowerShopClientApp.Controllers @@ -77,8 +78,7 @@ namespace FlowerShopClientApp.Controllers { throw new Exception("Введите логин и пароль"); } - APIClient.Client = - APIClient.GetRequest($"api/Client/Login?login={login}&password={password}"); + APIClient.Client = APIClient.GetRequest($"api/Client/Login?login={login}&password={password}"); if (APIClient.Client == null) { throw new Exception("Неверный логин/пароль"); @@ -108,6 +108,16 @@ namespace FlowerShopClientApp.Controllers return; } [HttpGet] + public IActionResult Mails() + { + if (APIClient.Client == null) + { + return Redirect("~/Home/Enter"); + } + return + View(APIClient.GetRequest>($"api/client/getmessages?clientId={APIClient.Client.Id}")); + } + [HttpGet] public IActionResult Create() { ViewBag.Flowers = APIClient.GetRequest>("api/Main/GetFlowerList"); diff --git a/FlowerShop/FlowerShopClientApp/Views/Home/Mails.cshtml b/FlowerShop/FlowerShopClientApp/Views/Home/Mails.cshtml new file mode 100644 index 0000000..cf74100 --- /dev/null +++ b/FlowerShop/FlowerShopClientApp/Views/Home/Mails.cshtml @@ -0,0 +1,51 @@ +@using FlowerShopContracts.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/FlowerShop/FlowerShopClientApp/Views/Shared/_Layout.cshtml b/FlowerShop/FlowerShopClientApp/Views/Shared/_Layout.cshtml index 621b0a9..b338d91 100644 --- a/FlowerShop/FlowerShopClientApp/Views/Shared/_Layout.cshtml +++ b/FlowerShop/FlowerShopClientApp/Views/Shared/_Layout.cshtml @@ -26,6 +26,9 @@ +
  • + Письма +
  • diff --git a/FlowerShop/FlowerShopContracts/BindingModels/MailConfigBindingModel.cs b/FlowerShop/FlowerShopContracts/BindingModels/MailConfigBindingModel.cs new file mode 100644 index 0000000..371d771 --- /dev/null +++ b/FlowerShop/FlowerShopContracts/BindingModels/MailConfigBindingModel.cs @@ -0,0 +1,12 @@ +namespace FlowerShopContracts.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/FlowerShop/FlowerShopContracts/BindingModels/MailSendInfoBindingModel.cs b/FlowerShop/FlowerShopContracts/BindingModels/MailSendInfoBindingModel.cs new file mode 100644 index 0000000..1d00620 --- /dev/null +++ b/FlowerShop/FlowerShopContracts/BindingModels/MailSendInfoBindingModel.cs @@ -0,0 +1,9 @@ +namespace FlowerShopContracts.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/FlowerShop/FlowerShopContracts/BindingModels/MessageInfoBindingModel.cs b/FlowerShop/FlowerShopContracts/BindingModels/MessageInfoBindingModel.cs new file mode 100644 index 0000000..bf8193d --- /dev/null +++ b/FlowerShop/FlowerShopContracts/BindingModels/MessageInfoBindingModel.cs @@ -0,0 +1,14 @@ +using FlowerShopDataModels.Models; + +namespace FlowerShopContracts.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 DateTime DateDelivery { get; set; } + public string Subject { get; set; } = string.Empty; + public string Body { get; set; } = string.Empty; + } +} diff --git a/FlowerShop/FlowerShopContracts/BusinessLogicsContracts/IMessageInfoLogic.cs b/FlowerShop/FlowerShopContracts/BusinessLogicsContracts/IMessageInfoLogic.cs new file mode 100644 index 0000000..e620bfa --- /dev/null +++ b/FlowerShop/FlowerShopContracts/BusinessLogicsContracts/IMessageInfoLogic.cs @@ -0,0 +1,12 @@ +using FlowerShopContracts.BindingModels; +using FlowerShopContracts.SearchModels; +using FlowerShopContracts.ViewModels; + +namespace FlowerShopContracts.BusinessLogicsContracts +{ + public interface IMessageInfoLogic + { + List? ReadList(MessageInfoSearchModel? Model); + bool Create(MessageInfoBindingModel Model); + } +} diff --git a/FlowerShop/FlowerShopContracts/SearchModels/MessageInfoSearchModel.cs b/FlowerShop/FlowerShopContracts/SearchModels/MessageInfoSearchModel.cs new file mode 100644 index 0000000..f4de6f3 --- /dev/null +++ b/FlowerShop/FlowerShopContracts/SearchModels/MessageInfoSearchModel.cs @@ -0,0 +1,8 @@ +namespace FlowerShopContracts.SearchModels +{ + public class MessageInfoSearchModel + { + public string? MessageId { get; set; } + public int? ClientId { get; set; } + } +} diff --git a/FlowerShop/FlowerShopContracts/StoragesContracts/IMessageInfoStorage.cs b/FlowerShop/FlowerShopContracts/StoragesContracts/IMessageInfoStorage.cs new file mode 100644 index 0000000..8551d5c --- /dev/null +++ b/FlowerShop/FlowerShopContracts/StoragesContracts/IMessageInfoStorage.cs @@ -0,0 +1,14 @@ +using FlowerShopContracts.BindingModels; +using FlowerShopContracts.SearchModels; +using FlowerShopContracts.ViewModels; + +namespace FlowerShopContracts.StoragesContracts +{ + public interface IMessageInfoStorage + { + List GetFullList(); + List GetFilteredList(MessageInfoSearchModel Model); + MessageInfoViewModel? GetElement(MessageInfoSearchModel Model); + MessageInfoViewModel? Insert(MessageInfoBindingModel Model); + } +} diff --git a/FlowerShop/FlowerShopContracts/ViewModels/MessageInfoViewModel.cs b/FlowerShop/FlowerShopContracts/ViewModels/MessageInfoViewModel.cs new file mode 100644 index 0000000..0454d46 --- /dev/null +++ b/FlowerShop/FlowerShopContracts/ViewModels/MessageInfoViewModel.cs @@ -0,0 +1,19 @@ +using FlowerShopDataModels.Models; +using System.ComponentModel; + +namespace FlowerShopContracts.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/FlowerShop/FlowerShopContracts/ViewModels/OrderViewModel.cs b/FlowerShop/FlowerShopContracts/ViewModels/OrderViewModel.cs index 96038ac..27000b8 100644 --- a/FlowerShop/FlowerShopContracts/ViewModels/OrderViewModel.cs +++ b/FlowerShop/FlowerShopContracts/ViewModels/OrderViewModel.cs @@ -15,6 +15,8 @@ namespace FlowerShopContracts.ViewModels public string FlowerName { get; set; } = string.Empty; [DisplayName("ФИО клиента")] public string ClientFIO { get; set; } = string.Empty; + [DisplayName("Почта клиента")] + public string ClientEmail { get; set; } = string.Empty; [DisplayName("ФИО исполнителя")] public string ImplementerFIO { get; set; }=string.Empty; [DisplayName("Количество")] diff --git a/FlowerShop/FlowerShopDataModels/Models/IMessageInfoModel.cs b/FlowerShop/FlowerShopDataModels/Models/IMessageInfoModel.cs new file mode 100644 index 0000000..1c244fe --- /dev/null +++ b/FlowerShop/FlowerShopDataModels/Models/IMessageInfoModel.cs @@ -0,0 +1,12 @@ +namespace FlowerShopDataModels.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/FlowerShop/FlowerShopDatabaseImplement/FlowerShopDatabase.cs b/FlowerShop/FlowerShopDatabaseImplement/FlowerShopDatabase.cs index 733f6a0..2ea68f2 100644 --- a/FlowerShop/FlowerShopDatabaseImplement/FlowerShopDatabase.cs +++ b/FlowerShop/FlowerShopDatabaseImplement/FlowerShopDatabase.cs @@ -9,7 +9,7 @@ namespace FlowerShopDatabaseImplement { if (optionsBuilder.IsConfigured == false) { - optionsBuilder.UseNpgsql(@"Host=localhost;Database=FlowerShopDatabaseFull;Username=postgres;Password=postgres"); + optionsBuilder.UseNpgsql(@"Host=localhost;Database=FlowerShopDatabaseTestFull;Username=postgres;Password=postgres"); } base.OnConfiguring(optionsBuilder); AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true); @@ -21,5 +21,6 @@ namespace FlowerShopDatabaseImplement public virtual DbSet Orders { set; get; } public virtual DbSet Clients { set; get; } public virtual DbSet Implementers { set; get; } + public virtual DbSet MessageInfos { set; get; } } } diff --git a/FlowerShop/FlowerShopDatabaseImplement/Implements/MessageInfoStorage.cs b/FlowerShop/FlowerShopDatabaseImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..2075293 --- /dev/null +++ b/FlowerShop/FlowerShopDatabaseImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,56 @@ +using FlowerShopContracts.BindingModels; +using FlowerShopContracts.SearchModels; +using FlowerShopContracts.StoragesContracts; +using FlowerShopContracts.ViewModels; +using FlowerShopDatabaseImplement.Models; + +namespace FlowerShopDatabaseImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + public List GetFullList() + { + using var Context = new FlowerShopDatabase(); + + return Context.MessageInfos + .Select(x => x.GetViewModel) + .ToList(); + } + + public List GetFilteredList(MessageInfoSearchModel Model) + { + using var Context = new FlowerShopDatabase(); + + 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 null; + + using var Context = new FlowerShopDatabase(); + + return Context.MessageInfos + .FirstOrDefault(x => x.MessageId == Model.MessageId)? + .GetViewModel; + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel Model) + { + var NewMessageInfo = MessageInfo.Create(Model); + + if (NewMessageInfo == null) + return null; + + using var Context = new FlowerShopDatabase(); + Context.MessageInfos.Add(NewMessageInfo); + + Context.SaveChanges(); + return NewMessageInfo.GetViewModel; + } + } +} diff --git a/FlowerShop/FlowerShopDatabaseImplement/Migrations/20240502144838_test.Designer.cs b/FlowerShop/FlowerShopDatabaseImplement/Migrations/20240502144838_test.Designer.cs new file mode 100644 index 0000000..3b50714 --- /dev/null +++ b/FlowerShop/FlowerShopDatabaseImplement/Migrations/20240502144838_test.Designer.cs @@ -0,0 +1,279 @@ +// +using System; +using FlowerShopDatabaseImplement; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace FlowerShopDatabaseImplement.Migrations +{ + [DbContext(typeof(FlowerShopDatabase))] + [Migration("20240502144838_test")] + partial class test + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "6.0.27") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("FlowerShopDatabaseImplement.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("FlowerShopDatabaseImplement.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("FlowerShopDatabaseImplement.Models.Flower", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("FlowerName") + .IsRequired() + .HasColumnType("text"); + + b.Property("Price") + .HasColumnType("double precision"); + + b.HasKey("Id"); + + b.ToTable("Flowers"); + }); + + modelBuilder.Entity("FlowerShopDatabaseImplement.Models.FlowerComponent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ComponentId") + .HasColumnType("integer"); + + b.Property("Count") + .HasColumnType("integer"); + + b.Property("FlowerId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("ComponentId"); + + b.HasIndex("FlowerId"); + + b.ToTable("FlowerComponents"); + }); + + modelBuilder.Entity("FlowerShopDatabaseImplement.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("FlowerShopDatabaseImplement.Models.MessageInfo", b => + { + b.Property("MessageId") + .HasColumnType("text"); + + b.Property("Body") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientId") + .HasColumnType("integer"); + + b.Property("DateDelivery") + .HasColumnType("timestamp without time zone"); + + b.Property("SenderName") + .IsRequired() + .HasColumnType("text"); + + b.Property("Subject") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("MessageId"); + + b.ToTable("MessageInfos"); + }); + + modelBuilder.Entity("FlowerShopDatabaseImplement.Models.Order", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClientId") + .HasColumnType("integer"); + + b.Property("Count") + .HasColumnType("integer"); + + b.Property("DateCreate") + .HasColumnType("timestamp without time zone"); + + b.Property("DateImplement") + .HasColumnType("timestamp without time zone"); + + b.Property("FlowerId") + .HasColumnType("integer"); + + b.Property("ImplementerId") + .HasColumnType("integer"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("Sum") + .HasColumnType("double precision"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.HasIndex("FlowerId"); + + b.HasIndex("ImplementerId"); + + b.ToTable("Orders"); + }); + + modelBuilder.Entity("FlowerShopDatabaseImplement.Models.FlowerComponent", b => + { + b.HasOne("FlowerShopDatabaseImplement.Models.Component", "Component") + .WithMany("FlowerComponents") + .HasForeignKey("ComponentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("FlowerShopDatabaseImplement.Models.Flower", "Flower") + .WithMany("Components") + .HasForeignKey("FlowerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Component"); + + b.Navigation("Flower"); + }); + + modelBuilder.Entity("FlowerShopDatabaseImplement.Models.Order", b => + { + b.HasOne("FlowerShopDatabaseImplement.Models.Client", "Client") + .WithMany() + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("FlowerShopDatabaseImplement.Models.Flower", "Flower") + .WithMany("Orders") + .HasForeignKey("FlowerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("FlowerShopDatabaseImplement.Models.Implementer", "Implementer") + .WithMany("Order") + .HasForeignKey("ImplementerId"); + + b.Navigation("Client"); + + b.Navigation("Flower"); + + b.Navigation("Implementer"); + }); + + modelBuilder.Entity("FlowerShopDatabaseImplement.Models.Component", b => + { + b.Navigation("FlowerComponents"); + }); + + modelBuilder.Entity("FlowerShopDatabaseImplement.Models.Flower", b => + { + b.Navigation("Components"); + + b.Navigation("Orders"); + }); + + modelBuilder.Entity("FlowerShopDatabaseImplement.Models.Implementer", b => + { + b.Navigation("Order"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/FlowerShop/FlowerShopDatabaseImplement/Migrations/20240502144838_test.cs b/FlowerShop/FlowerShopDatabaseImplement/Migrations/20240502144838_test.cs new file mode 100644 index 0000000..5cbc8ed --- /dev/null +++ b/FlowerShop/FlowerShopDatabaseImplement/Migrations/20240502144838_test.cs @@ -0,0 +1,35 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace FlowerShopDatabaseImplement.Migrations +{ + public partial class test : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "MessageInfos", + 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 without time zone", nullable: false), + Subject = table.Column(type: "text", nullable: false), + Body = table.Column(type: "text", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_MessageInfos", x => x.MessageId); + }); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "MessageInfos"); + } + } +} diff --git a/FlowerShop/FlowerShopDatabaseImplement/Migrations/FlowerShopDatabaseModelSnapshot.cs b/FlowerShop/FlowerShopDatabaseImplement/Migrations/FlowerShopDatabaseModelSnapshot.cs index dc3a919..80707fe 100644 --- a/FlowerShop/FlowerShopDatabaseImplement/Migrations/FlowerShopDatabaseModelSnapshot.cs +++ b/FlowerShop/FlowerShopDatabaseImplement/Migrations/FlowerShopDatabaseModelSnapshot.cs @@ -140,6 +140,34 @@ namespace FlowerShopDatabaseImplement.Migrations b.ToTable("Implementers"); }); + modelBuilder.Entity("FlowerShopDatabaseImplement.Models.MessageInfo", b => + { + b.Property("MessageId") + .HasColumnType("text"); + + b.Property("Body") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientId") + .HasColumnType("integer"); + + b.Property("DateDelivery") + .HasColumnType("timestamp without time zone"); + + b.Property("SenderName") + .IsRequired() + .HasColumnType("text"); + + b.Property("Subject") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("MessageId"); + + b.ToTable("MessageInfos"); + }); + modelBuilder.Entity("FlowerShopDatabaseImplement.Models.Order", b => { b.Property("Id") diff --git a/FlowerShop/FlowerShopDatabaseImplement/Models/MessageInfo.cs b/FlowerShop/FlowerShopDatabaseImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..0721a80 --- /dev/null +++ b/FlowerShop/FlowerShopDatabaseImplement/Models/MessageInfo.cs @@ -0,0 +1,44 @@ +using FlowerShopContracts.BindingModels; +using FlowerShopContracts.ViewModels; +using FlowerShopDataModels.Models; +using System.ComponentModel.DataAnnotations; + +namespace FlowerShopDatabaseImplement.Models +{ + public class MessageInfo : IMessageInfoModel + { + [Key] + public string MessageId { get; set; } = string.Empty; + public int? ClientId { get; set; } + public string SenderName { get; set; } = string.Empty; + public DateTime DateDelivery { get; set; } + public string Subject { get; set; } = string.Empty; + 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/FlowerShop/FlowerShopDatabaseImplement/Models/Order.cs b/FlowerShop/FlowerShopDatabaseImplement/Models/Order.cs index 98ce151..424413a 100644 --- a/FlowerShop/FlowerShopDatabaseImplement/Models/Order.cs +++ b/FlowerShop/FlowerShopDatabaseImplement/Models/Order.cs @@ -61,6 +61,7 @@ namespace FlowerShopDatabaseImplement.Models ImplementerId = ImplementerId, FlowerName = Flower.FlowerName, ClientFIO = Client.ClientFIO, + ClientEmail = Client.Email, ImplementerFIO = Implementer?.ImplementerFIO, Count = Count, Sum = Sum, diff --git a/FlowerShop/FlowerShopFileImplement/DataFileSingleton.cs b/FlowerShop/FlowerShopFileImplement/DataFileSingleton.cs index b3c3b6f..64d4160 100644 --- a/FlowerShop/FlowerShopFileImplement/DataFileSingleton.cs +++ b/FlowerShop/FlowerShopFileImplement/DataFileSingleton.cs @@ -11,11 +11,13 @@ namespace FlowerShopFileImplement private readonly string FlowerFileName = "Flower.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 Flowers { get; private set; } public List Clients { get; private set; } public List Implementers { get; private set; } + public List MessageInfos { get; private set; } public static DataFileSingleton GetInstance() { if (instance == null) @@ -29,6 +31,7 @@ namespace FlowerShopFileImplement 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 SaveMessageInfos() => SaveData(MessageInfos, MessageInfoFileName, "MessageInfos", x => x.GetXElement); private DataFileSingleton() { Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!; @@ -36,6 +39,7 @@ namespace FlowerShopFileImplement Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!; Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!; Implementers = LoadData(ImplementerFileName, "Implementer", x => Implementer.Create(x)!)!; + MessageInfos = LoadData(MessageInfoFileName, "MessageInfo", x => MessageInfo.Create(x)!)!; } private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) { diff --git a/FlowerShop/FlowerShopFileImplement/Implements/MessageInfoStorage.cs b/FlowerShop/FlowerShopFileImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..37d80ea --- /dev/null +++ b/FlowerShop/FlowerShopFileImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,56 @@ +using FlowerShopContracts.BindingModels; +using FlowerShopContracts.SearchModels; +using FlowerShopContracts.StoragesContracts; +using FlowerShopContracts.ViewModels; +using FlowerShopFileImplement.Models; + +namespace FlowerShopFileImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + private readonly DataFileSingleton _source; + + public MessageInfoStorage() + { + _source = DataFileSingleton.GetInstance(); + } + + public List GetFullList() + { + return _source.MessageInfos + .Select(x => x.GetViewModel) + .ToList(); + } + + public List GetFilteredList(MessageInfoSearchModel Model) + { + return _source.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 null; + + return _source.MessageInfos + .FirstOrDefault(x => x.MessageId == Model.MessageId)? + .GetViewModel; + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel Model) + { + var NewMessageInfo = MessageInfo.Create(Model); + + if (NewMessageInfo == null) + return null; + + _source.MessageInfos.Add(NewMessageInfo); + _source.SaveMessageInfos(); + + return NewMessageInfo.GetViewModel; + } + } +} diff --git a/FlowerShop/FlowerShopFileImplement/Implements/OrderStorage.cs b/FlowerShop/FlowerShopFileImplement/Implements/OrderStorage.cs index 23ac5dc..70a4b0f 100644 --- a/FlowerShop/FlowerShopFileImplement/Implements/OrderStorage.cs +++ b/FlowerShop/FlowerShopFileImplement/Implements/OrderStorage.cs @@ -84,6 +84,7 @@ namespace FlowerShopFileImplement.Implements var client = source.Clients.FirstOrDefault(x => x.Id == order.ClientId); viewModel.FlowerName = flower?.FlowerName; viewModel.ClientFIO = client?.ClientFIO; + viewModel.ClientEmail = client?.Email; return viewModel; } } diff --git a/FlowerShop/FlowerShopFileImplement/Models/MessageInfo.cs b/FlowerShop/FlowerShopFileImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..225d467 --- /dev/null +++ b/FlowerShop/FlowerShopFileImplement/Models/MessageInfo.cs @@ -0,0 +1,74 @@ +using FlowerShopContracts.BindingModels; +using FlowerShopContracts.ViewModels; +using FlowerShopDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace FlowerShopFileImplement.Models +{ + public class MessageInfo : IMessageInfoModel + { + public string MessageId { get; set; } = string.Empty; + public int? ClientId { get; set; } + public string SenderName { get; set; } = string.Empty; + public DateTime DateDelivery { get; set; } + public string Subject { get; set; } = string.Empty; + 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 + }; + + public static MessageInfo? Create(XElement Element) + { + if (Element == null) + return null; + + return new() + { + MessageId = Element.Attribute("MessageId")!.Value, + ClientId = Convert.ToInt32(Element.Attribute("ClientId")!.Value), + SenderName = Element.Attribute("SenderName")!.Value, + DateDelivery = Convert.ToDateTime(Element.Attribute("DateDelivery")!.Value), + Subject = Element.Attribute("Subject")!.Value, + Body = Element.Attribute("Body")!.Value, + }; + } + + public XElement GetXElement => new( + "MessageInfo", + new XAttribute("MessageId", MessageId), + new XAttribute("ClientId", ClientId), + new XAttribute("SenderName", SenderName), + new XAttribute("DateDelivery", DateDelivery), + new XAttribute("Subject", Subject), + new XAttribute("Body", Body) + ); + } +} diff --git a/FlowerShop/FlowerShopListImplement/DataListSingleton.cs b/FlowerShop/FlowerShopListImplement/DataListSingleton.cs index a1a6cb6..719fd66 100644 --- a/FlowerShop/FlowerShopListImplement/DataListSingleton.cs +++ b/FlowerShop/FlowerShopListImplement/DataListSingleton.cs @@ -10,6 +10,8 @@ namespace FlowerShopListImplement public List Flowers { get; set; } public List Clients { get; set; } public List Implementers { get; set; } + + public List MessageInfos { get; set; } private DataListSingleton() { Components = new List(); @@ -17,6 +19,7 @@ namespace FlowerShopListImplement Flowers = new List(); Clients = new List(); Implementers = new List(); + MessageInfos = new List(); } public static DataListSingleton GetInstance() { diff --git a/FlowerShop/FlowerShopListImplement/Implements/MessageInfoStorage.cs b/FlowerShop/FlowerShopListImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..0eb7b51 --- /dev/null +++ b/FlowerShop/FlowerShopListImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,54 @@ +using FlowerShopContracts.BindingModels; +using FlowerShopContracts.SearchModels; +using FlowerShopContracts.StoragesContracts; +using FlowerShopContracts.ViewModels; +using FlowerShopListImplement.Models; + +namespace FlowerShopListImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + private readonly DataListSingleton _source; + + public MessageInfoStorage() + { + _source = DataListSingleton.GetInstance(); + } + + public List GetFullList() + { + return _source.MessageInfos + .Select(x => x.GetViewModel) + .ToList(); + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + return _source.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 null; + + return _source.MessageInfos + .FirstOrDefault(x => x.MessageId == model.MessageId)? + .GetViewModel; + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var NewMessageInfo = MessageInfo.Create(model); + + if (NewMessageInfo == null) + return null; + + _source.MessageInfos.Add(NewMessageInfo); + return NewMessageInfo.GetViewModel; + } + } +} diff --git a/FlowerShop/FlowerShopListImplement/Implements/OrderStorage.cs b/FlowerShop/FlowerShopListImplement/Implements/OrderStorage.cs index 7a0f2e9..bc84f8b 100644 --- a/FlowerShop/FlowerShopListImplement/Implements/OrderStorage.cs +++ b/FlowerShop/FlowerShopListImplement/Implements/OrderStorage.cs @@ -114,6 +114,7 @@ namespace FlowerShopListImplement.Implements if (client.Id == model.ClientId) { model.ClientFIO = client.ClientFIO; + model.ClientEmail = client.Email; return model; } } diff --git a/FlowerShop/FlowerShopListImplement/Models/MessageInfo.cs b/FlowerShop/FlowerShopListImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..1cb185c --- /dev/null +++ b/FlowerShop/FlowerShopListImplement/Models/MessageInfo.cs @@ -0,0 +1,42 @@ +using FlowerShopContracts.BindingModels; +using FlowerShopContracts.ViewModels; +using FlowerShopDataModels.Models; + +namespace FlowerShopListImplement.Models +{ + public class MessageInfo : IMessageInfoModel + { + public string MessageId { get; set; } = string.Empty; + public int? ClientId { get; set; } + public string SenderName { get; set; } = string.Empty; + public DateTime DateDelivery { get; set; } + public string Subject { get; set; } = string.Empty; + 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/FlowerShop/FlowerShopRestApi/Controllers/ClientController.cs b/FlowerShop/FlowerShopRestApi/Controllers/ClientController.cs index 6a7b463..016d678 100644 --- a/FlowerShop/FlowerShopRestApi/Controllers/ClientController.cs +++ b/FlowerShop/FlowerShopRestApi/Controllers/ClientController.cs @@ -11,18 +11,20 @@ namespace FlowerShopRestApi.Controllers public class ClientController : Controller { private readonly ILogger _logger; - private readonly IClientLogic _logic; - public ClientController(IClientLogic logic, ILogger logger) + private readonly IClientLogic _clientLogic; + private readonly IMessageInfoLogic _mailLogic; + public ClientController(IClientLogic clientLogic, IMessageInfoLogic mailLogic, ILogger logger) { _logger = logger; - _logic = logic; + _clientLogic = clientLogic; + _mailLogic = mailLogic; } [HttpGet] public ClientViewModel? Login(string login, string password) { try { - return _logic.ReadElement(new ClientSearchModel + return _clientLogic.ReadElement(new ClientSearchModel { Email = login, Password = password @@ -39,7 +41,7 @@ namespace FlowerShopRestApi.Controllers { try { - _logic.Create(model); + _clientLogic.Create(model); } catch (Exception ex) { @@ -52,7 +54,7 @@ namespace FlowerShopRestApi.Controllers { try { - _logic.Update(model); + _clientLogic.Update(model); } catch (Exception ex) { @@ -60,6 +62,23 @@ namespace FlowerShopRestApi.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/FlowerShop/FlowerShopRestApi/Program.cs b/FlowerShop/FlowerShopRestApi/Program.cs index 10ed2df..776b2c6 100644 --- a/FlowerShop/FlowerShopRestApi/Program.cs +++ b/FlowerShop/FlowerShopRestApi/Program.cs @@ -1,4 +1,6 @@ using FlowerShopBusinessLogic.BusinessLogics; +using FlowerShopBusinessLogic.MailWorker; +using FlowerShopContracts.BindingModels; using FlowerShopContracts.BusinessLogicsContracts; using FlowerShopContracts.StoragesContracts; using FlowerShopDatabaseImplement.Implements; @@ -13,10 +15,14 @@ builder.Logging.AddLog4Net("log4net.config"); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddTransient(); + +builder.Services.AddSingleton(); builder.Services.AddControllers(); @@ -32,6 +38,19 @@ 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/FlowerShop/FlowerShopRestApi/appsettings.json b/FlowerShop/FlowerShopRestApi/appsettings.json index 10f68b8..ae70384 100644 --- a/FlowerShop/FlowerShopRestApi/appsettings.json +++ b/FlowerShop/FlowerShopRestApi/appsettings.json @@ -5,5 +5,13 @@ "Microsoft.AspNetCore": "Warning" } }, - "AllowedHosts": "*" + "AllowedHosts": "*", + + "SmtpClientHost": "smtp.gmail.com", + "SmtpClientPort": "587", + "PopHost": "pop.gmail.com", + "PopPort": "995", + "MailLogin": "labworker83@gmail.com", + "MailPassword": "wpxc drvx lhqb uqpe" + }