From 0fd7b8dc8505512d1e1055b47bffd1ff40b92bc7 Mon Sep 17 00:00:00 2001 From: Factorino73 Date: Mon, 22 Apr 2024 10:29:51 +0400 Subject: [PATCH 1/5] Add lock --- AircraftPlant/AircraftPlant.log.2024-04-21 | 41 +++++++++++++++++++ .../BusinessLogics/WorkModeling.cs | 29 +++++++------ 2 files changed, 58 insertions(+), 12 deletions(-) create mode 100644 AircraftPlant/AircraftPlant.log.2024-04-21 diff --git a/AircraftPlant/AircraftPlant.log.2024-04-21 b/AircraftPlant/AircraftPlant.log.2024-04-21 new file mode 100644 index 0000000..ed787cd --- /dev/null +++ b/AircraftPlant/AircraftPlant.log.2024-04-21 @@ -0,0 +1,41 @@ +2024-04-21 02:01:49,249 INFO Microsoft.Hosting.Lifetime.? [?] - MESSAGE: Now listening on: https://localhost:7122 + 2024-04-21 02:01:49,313 INFO Microsoft.Hosting.Lifetime.? [?] - MESSAGE: Now listening on: http://localhost:5092 + 2024-04-21 02:01:49,318 INFO Microsoft.Hosting.Lifetime.OnApplicationStarted [0] - MESSAGE: Application started. Press Ctrl+C to shut down. + 2024-04-21 02:01:49,321 INFO Microsoft.Hosting.Lifetime.OnApplicationStarted [0] - MESSAGE: Hosting environment: Development + 2024-04-21 02:01:49,322 INFO Microsoft.Hosting.Lifetime.OnApplicationStarted [0] - MESSAGE: Content root path: D:\ULSTU\Семестр 4\РПП\AircraftPlant\AircraftPlantRestApi\ + 2024-04-21 02:20:52,936 INFO Microsoft.Hosting.Lifetime.? [?] - MESSAGE: Now listening on: https://localhost:7122 + 2024-04-21 02:20:52,958 INFO Microsoft.Hosting.Lifetime.? [?] - MESSAGE: Now listening on: http://localhost:5092 + 2024-04-21 02:20:52,964 INFO Microsoft.Hosting.Lifetime.OnApplicationStarted [0] - MESSAGE: Application started. Press Ctrl+C to shut down. + 2024-04-21 02:20:52,966 INFO Microsoft.Hosting.Lifetime.OnApplicationStarted [0] - MESSAGE: Hosting environment: Development + 2024-04-21 02:20:52,967 INFO Microsoft.Hosting.Lifetime.OnApplicationStarted [0] - MESSAGE: Content root path: D:\ULSTU\Семестр 4\РПП\AircraftPlant\AircraftPlantRestApi\ + 2024-04-21 02:21:14,577 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadList [49] - MESSAGE: ReadList. ShopName:(null).Id:(null) + 2024-04-21 02:21:16,912 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadList [58] - MESSAGE: ReadList. Count:2 + 2024-04-21 02:21:40,373 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadList [49] - MESSAGE: ReadList. ShopName:(null).Id:(null) + 2024-04-21 02:21:40,397 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadList [58] - MESSAGE: ReadList. Count:2 + 2024-04-21 02:21:40,453 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadElement [75] - MESSAGE: ReadElement. ShopName:(null).Id:4 + 2024-04-21 02:21:40,562 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadElement [84] - MESSAGE: ReadElement find. Id:4 + 2024-04-21 02:21:45,409 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadElement [75] - MESSAGE: ReadElement. ShopName:(null).Id:5 + 2024-04-21 02:21:45,412 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadElement [84] - MESSAGE: ReadElement find. Id:5 + 2024-04-21 02:21:47,533 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadElement [75] - MESSAGE: ReadElement. ShopName:(null).Id:4 + 2024-04-21 02:21:47,535 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadElement [84] - MESSAGE: ReadElement find. Id:4 + 2024-04-21 02:23:50,172 INFO Microsoft.Hosting.Lifetime.? [?] - MESSAGE: Now listening on: https://localhost:7122 + 2024-04-21 02:23:50,194 INFO Microsoft.Hosting.Lifetime.? [?] - MESSAGE: Now listening on: http://localhost:5092 + 2024-04-21 02:23:50,198 INFO Microsoft.Hosting.Lifetime.OnApplicationStarted [0] - MESSAGE: Application started. Press Ctrl+C to shut down. + 2024-04-21 02:23:50,201 INFO Microsoft.Hosting.Lifetime.OnApplicationStarted [0] - MESSAGE: Hosting environment: Development + 2024-04-21 02:23:50,201 INFO Microsoft.Hosting.Lifetime.OnApplicationStarted [0] - MESSAGE: Content root path: D:\ULSTU\Семестр 4\РПП\AircraftPlant\AircraftPlantRestApi\ + 2024-04-21 02:24:06,733 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadList [49] - MESSAGE: ReadList. ShopName:(null).Id:(null) + 2024-04-21 02:24:08,724 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadList [58] - MESSAGE: ReadList. Count:2 + 2024-04-21 02:24:10,746 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadList [49] - MESSAGE: ReadList. ShopName:(null).Id:(null) + 2024-04-21 02:24:10,764 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadList [58] - MESSAGE: ReadList. Count:2 + 2024-04-21 02:26:31,564 INFO Microsoft.Hosting.Lifetime.? [?] - MESSAGE: Now listening on: https://localhost:7122 + 2024-04-21 02:26:31,586 INFO Microsoft.Hosting.Lifetime.? [?] - MESSAGE: Now listening on: http://localhost:5092 + 2024-04-21 02:26:31,592 INFO Microsoft.Hosting.Lifetime.OnApplicationStarted [0] - MESSAGE: Application started. Press Ctrl+C to shut down. + 2024-04-21 02:26:31,594 INFO Microsoft.Hosting.Lifetime.OnApplicationStarted [0] - MESSAGE: Hosting environment: Development + 2024-04-21 02:26:31,595 INFO Microsoft.Hosting.Lifetime.OnApplicationStarted [0] - MESSAGE: Content root path: D:\ULSTU\Семестр 4\РПП\AircraftPlant\AircraftPlantRestApi\ + 2024-04-21 02:26:50,068 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadList [49] - MESSAGE: ReadList. ShopName:(null).Id:(null) + 2024-04-21 02:26:52,105 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadList [58] - MESSAGE: ReadList. Count:2 + 2024-04-21 02:26:53,568 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadList [49] - MESSAGE: ReadList. ShopName:(null).Id:(null) + 2024-04-21 02:26:53,583 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadList [58] - MESSAGE: ReadList. Count:2 + 2024-04-21 02:26:53,599 INFO AircraftPlantBusinessLogic.BusinessLogics.PlaneLogic.ReadList [48] - MESSAGE: ReadList. PlaneName:(null).Id:(null) + 2024-04-21 02:26:53,668 INFO AircraftPlantBusinessLogic.BusinessLogics.PlaneLogic.ReadList [57] - MESSAGE: ReadList. Count:2 + \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/WorkModeling.cs b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/WorkModeling.cs index 493d99c..fabbb3f 100644 --- a/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/WorkModeling.cs +++ b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/WorkModeling.cs @@ -27,10 +27,12 @@ namespace AircraftPlantBusinessLogic.BusinessLogics /// private readonly Random _rnd; - /// - /// Бизнес-логика для заказов - /// - private IOrderLogic? _orderLogic; + private readonly object orderLock = new object(); + + /// + /// Бизнес-логика для заказов + /// + private IOrderLogic? _orderLogic; /// /// Конструктор @@ -91,15 +93,18 @@ namespace AircraftPlantBusinessLogic.BusinessLogics try { _logger.LogDebug("DoWork. Worker {Id} try get order {Order}", implementer.Id, order.Id); - // пытаемся назначить заказ на исполнителя - _orderLogic.TakeOrderInWork(new OrderBindingModel - { - Id = order.Id, - ImplementerId = implementer.Id - }); + // пытаемся назначить заказ на исполнителя + lock (orderLock) + { + _orderLogic.TakeOrderInWork(new OrderBindingModel + { + Id = order.Id, + ImplementerId = implementer.Id + }); + } - // делаем работу - Thread.Sleep(implementer.WorkExperience * _rnd.Next(100, 1000) * order.Count); + // делаем работу + Thread.Sleep(implementer.WorkExperience * _rnd.Next(100, 1000) * order.Count); _logger.LogDebug("DoWork. Worker {Id} finish order {Order}", implementer.Id, order.Id); _orderLogic.FinishOrder(new OrderBindingModel { -- 2.25.1 From a1de87096f6bfcc0df4ccb063d2c0eb907f4b2d1 Mon Sep 17 00:00:00 2001 From: Factorino73 Date: Mon, 22 Apr 2024 16:36:41 +0400 Subject: [PATCH 2/5] Fixes --- .../BusinessLogics/OrderLogic.cs | 3 +- .../BusinessLogics/WorkModeling.cs | 6 +- .../FormImplementer.Designer.cs | 260 +++++++++--------- 3 files changed, 135 insertions(+), 134 deletions(-) diff --git a/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/OrderLogic.cs b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/OrderLogic.cs index c7b560e..274c92a 100644 --- a/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/OrderLogic.cs @@ -193,7 +193,7 @@ orderStorage) model.Status = newStatus; - if (model.Status == OrderStatus.Выдан) + if (model.Status == OrderStatus.Готов) { model.DateImplement = DateTime.Now; } @@ -201,6 +201,7 @@ orderStorage) { model.DateImplement = element.DateImplement; } + CheckModel(model, false); if (_orderStorage.Update(model) == null) { diff --git a/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/WorkModeling.cs b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/WorkModeling.cs index fabbb3f..7a3e68b 100644 --- a/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/WorkModeling.cs +++ b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/WorkModeling.cs @@ -95,7 +95,7 @@ namespace AircraftPlantBusinessLogic.BusinessLogics _logger.LogDebug("DoWork. Worker {Id} try get order {Order}", implementer.Id, order.Id); // пытаемся назначить заказ на исполнителя lock (orderLock) - { + { _orderLogic.TakeOrderInWork(new OrderBindingModel { Id = order.Id, @@ -106,7 +106,7 @@ namespace AircraftPlantBusinessLogic.BusinessLogics // делаем работу Thread.Sleep(implementer.WorkExperience * _rnd.Next(100, 1000) * order.Count); _logger.LogDebug("DoWork. Worker {Id} finish order {Order}", implementer.Id, order.Id); - _orderLogic.FinishOrder(new OrderBindingModel + _orderLogic.DeliveryOrder(new OrderBindingModel { Id = order.Id }); @@ -156,7 +156,7 @@ namespace AircraftPlantBusinessLogic.BusinessLogics // доделываем работу Thread.Sleep(implementer.WorkExperience * _rnd.Next(100, 300) * runOrder.Count); _logger.LogDebug("DoWork. Worker {Id} finish order {Order}", implementer.Id, runOrder.Id); - _orderLogic.FinishOrder(new OrderBindingModel + _orderLogic.DeliveryOrder(new OrderBindingModel { Id = runOrder.Id }); diff --git a/AircraftPlant/AircraftPlantView/FormImplementer.Designer.cs b/AircraftPlant/AircraftPlantView/FormImplementer.Designer.cs index b2fe207..eb92254 100644 --- a/AircraftPlant/AircraftPlantView/FormImplementer.Designer.cs +++ b/AircraftPlant/AircraftPlantView/FormImplementer.Designer.cs @@ -20,139 +20,139 @@ 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() - { - textBoxImplementerFIO = new TextBox(); - textBoxPassword = new TextBox(); - numericUpDownWorkExperience = new NumericUpDown(); - numericUpDownQualification = new NumericUpDown(); - buttonCancel = new Button(); - labelImplementerFIO = new Label(); - labelPassword = new Label(); - labelWorkExperience = new Label(); - labelQualification = new Label(); - buttonSave = new Button(); - ((System.ComponentModel.ISupportInitialize)numericUpDownWorkExperience).BeginInit(); - ((System.ComponentModel.ISupportInitialize)numericUpDownQualification).BeginInit(); - SuspendLayout(); - // - // textBoxImplementerFIO - // - textBoxImplementerFIO.Location = new Point(108, 12); - textBoxImplementerFIO.Name = "textBoxImplementerFIO"; - textBoxImplementerFIO.Size = new Size(264, 23); - textBoxImplementerFIO.TabIndex = 0; - // - // textBoxPassword - // - textBoxPassword.Location = new Point(108, 41); - textBoxPassword.Name = "textBoxPassword"; - textBoxPassword.Size = new Size(264, 23); - textBoxPassword.TabIndex = 1; - // - // numericUpDownWorkExperience - // - numericUpDownWorkExperience.Location = new Point(108, 70); - numericUpDownWorkExperience.Name = "numericUpDownWorkExperience"; - numericUpDownWorkExperience.Size = new Size(264, 23); - numericUpDownWorkExperience.TabIndex = 2; - // - // numericUpDownQualification - // - numericUpDownQualification.Location = new Point(108, 99); - numericUpDownQualification.Name = "numericUpDownQualification"; - numericUpDownQualification.Size = new Size(264, 23); - numericUpDownQualification.TabIndex = 3; - // - // buttonCancel - // - buttonCancel.Location = new Point(297, 134); - buttonCancel.Name = "buttonCancel"; - buttonCancel.Size = new Size(75, 23); - buttonCancel.TabIndex = 4; - buttonCancel.Text = "Отмена"; - buttonCancel.UseVisualStyleBackColor = true; - buttonCancel.Click += buttonCancel_Click; - // - // labelImplementerFIO - // - labelImplementerFIO.AutoSize = true; - labelImplementerFIO.Location = new Point(12, 15); - labelImplementerFIO.Name = "labelImplementerFIO"; - labelImplementerFIO.Size = new Size(37, 15); - labelImplementerFIO.TabIndex = 5; - labelImplementerFIO.Text = "ФИО:"; - // - // labelPassword - // - labelPassword.AutoSize = true; - labelPassword.Location = new Point(11, 44); - labelPassword.Name = "labelPassword"; - labelPassword.Size = new Size(52, 15); - labelPassword.TabIndex = 6; - labelPassword.Text = "Пароль:"; - // - // labelWorkExperience - // - labelWorkExperience.AutoSize = true; - labelWorkExperience.Location = new Point(12, 72); - labelWorkExperience.Name = "labelWorkExperience"; - labelWorkExperience.Size = new Size(38, 15); - labelWorkExperience.TabIndex = 7; - labelWorkExperience.Text = "label1"; - // - // labelQualification - // - labelQualification.AutoSize = true; - labelQualification.Location = new Point(11, 101); - labelQualification.Name = "labelQualification"; - labelQualification.Size = new Size(91, 15); - labelQualification.TabIndex = 8; - labelQualification.Text = "Квалификация:"; - // - // buttonSave - // - buttonSave.Location = new Point(216, 134); - buttonSave.Name = "buttonSave"; - buttonSave.Size = new Size(75, 23); - buttonSave.TabIndex = 9; - buttonSave.Text = "Сохранить"; - buttonSave.UseVisualStyleBackColor = true; - buttonSave.Click += buttonSave_Click; - // - // FormImplementer - // - AutoScaleDimensions = new SizeF(7F, 15F); - AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(384, 169); - Controls.Add(buttonSave); - Controls.Add(labelQualification); - Controls.Add(labelWorkExperience); - Controls.Add(labelPassword); - Controls.Add(labelImplementerFIO); - Controls.Add(buttonCancel); - Controls.Add(numericUpDownQualification); - Controls.Add(numericUpDownWorkExperience); - Controls.Add(textBoxPassword); - Controls.Add(textBoxImplementerFIO); - Name = "FormImplementer"; - Text = "Исполнитель"; - Load += FormImplementer_Load; - ((System.ComponentModel.ISupportInitialize)numericUpDownWorkExperience).EndInit(); - ((System.ComponentModel.ISupportInitialize)numericUpDownQualification).EndInit(); - ResumeLayout(false); - PerformLayout(); - } + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + textBoxImplementerFIO = new TextBox(); + textBoxPassword = new TextBox(); + numericUpDownWorkExperience = new NumericUpDown(); + numericUpDownQualification = new NumericUpDown(); + buttonCancel = new Button(); + labelImplementerFIO = new Label(); + labelPassword = new Label(); + labelWorkExperience = new Label(); + labelQualification = new Label(); + buttonSave = new Button(); + ((System.ComponentModel.ISupportInitialize)numericUpDownWorkExperience).BeginInit(); + ((System.ComponentModel.ISupportInitialize)numericUpDownQualification).BeginInit(); + SuspendLayout(); + // + // textBoxImplementerFIO + // + textBoxImplementerFIO.Location = new Point(108, 12); + textBoxImplementerFIO.Name = "textBoxImplementerFIO"; + textBoxImplementerFIO.Size = new Size(264, 23); + textBoxImplementerFIO.TabIndex = 0; + // + // textBoxPassword + // + textBoxPassword.Location = new Point(108, 41); + textBoxPassword.Name = "textBoxPassword"; + textBoxPassword.Size = new Size(264, 23); + textBoxPassword.TabIndex = 1; + // + // numericUpDownWorkExperience + // + numericUpDownWorkExperience.Location = new Point(108, 70); + numericUpDownWorkExperience.Name = "numericUpDownWorkExperience"; + numericUpDownWorkExperience.Size = new Size(264, 23); + numericUpDownWorkExperience.TabIndex = 2; + // + // numericUpDownQualification + // + numericUpDownQualification.Location = new Point(108, 99); + numericUpDownQualification.Name = "numericUpDownQualification"; + numericUpDownQualification.Size = new Size(264, 23); + numericUpDownQualification.TabIndex = 3; + // + // buttonCancel + // + buttonCancel.Location = new Point(297, 134); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(75, 23); + buttonCancel.TabIndex = 4; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += buttonCancel_Click; + // + // labelImplementerFIO + // + labelImplementerFIO.AutoSize = true; + labelImplementerFIO.Location = new Point(12, 15); + labelImplementerFIO.Name = "labelImplementerFIO"; + labelImplementerFIO.Size = new Size(37, 15); + labelImplementerFIO.TabIndex = 5; + labelImplementerFIO.Text = "ФИО:"; + // + // labelPassword + // + labelPassword.AutoSize = true; + labelPassword.Location = new Point(11, 44); + labelPassword.Name = "labelPassword"; + labelPassword.Size = new Size(52, 15); + labelPassword.TabIndex = 6; + labelPassword.Text = "Пароль:"; + // + // labelWorkExperience + // + labelWorkExperience.AutoSize = true; + labelWorkExperience.Location = new Point(12, 72); + labelWorkExperience.Name = "labelWorkExperience"; + labelWorkExperience.Size = new Size(84, 15); + labelWorkExperience.TabIndex = 7; + labelWorkExperience.Text = "Опыт работы:"; + // + // labelQualification + // + labelQualification.AutoSize = true; + labelQualification.Location = new Point(11, 101); + labelQualification.Name = "labelQualification"; + labelQualification.Size = new Size(91, 15); + labelQualification.TabIndex = 8; + labelQualification.Text = "Квалификация:"; + // + // buttonSave + // + buttonSave.Location = new Point(216, 134); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(75, 23); + buttonSave.TabIndex = 9; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += buttonSave_Click; + // + // FormImplementer + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(384, 169); + Controls.Add(buttonSave); + Controls.Add(labelQualification); + Controls.Add(labelWorkExperience); + Controls.Add(labelPassword); + Controls.Add(labelImplementerFIO); + Controls.Add(buttonCancel); + Controls.Add(numericUpDownQualification); + Controls.Add(numericUpDownWorkExperience); + Controls.Add(textBoxPassword); + Controls.Add(textBoxImplementerFIO); + Name = "FormImplementer"; + Text = "Исполнитель"; + Load += FormImplementer_Load; + ((System.ComponentModel.ISupportInitialize)numericUpDownWorkExperience).EndInit(); + ((System.ComponentModel.ISupportInitialize)numericUpDownQualification).EndInit(); + ResumeLayout(false); + PerformLayout(); + } - #endregion + #endregion - private TextBox textBoxImplementerFIO; + private TextBox textBoxImplementerFIO; private TextBox textBoxPassword; private NumericUpDown numericUpDownWorkExperience; private NumericUpDown numericUpDownQualification; -- 2.25.1 From 6354412e33409721a95d908ca329e3ce02616ba9 Mon Sep 17 00:00:00 2001 From: Factorino73 Date: Sat, 4 May 2024 22:30:27 +0400 Subject: [PATCH 3/5] LabWork07_Basic --- AircraftPlant/AircraftPlant.log.2024-04-22 | 65 +++ .../AircraftPlantBusinessLogic.csproj | 1 + .../BusinessLogics/ClientLogic.cs | 9 +- .../BusinessLogics/MessageInfoLogic.cs | 81 +++ .../BusinessLogics/OrderLogic.cs | 77 ++- .../MailWorker/AbstractMailWorker.cs | 150 ++++++ .../MailWorker/MailKitWorker.cs | 103 ++++ .../Controllers/HomeController.cs | 17 +- .../Views/Home/Mails.cshtml | 54 ++ .../Views/Shared/_Layout.cshtml | 3 + .../BindingModels/MailConfigBindingModel.cs | 44 ++ .../BindingModels/MailSendInfoBindingModel.cs | 29 ++ .../BindingModels/MessageInfoBindingModel.cs | 46 ++ .../IMessageInfoLogic.cs | 31 ++ .../SearchModels/MessageInfoSearchModel.cs | 25 + .../StoragesContracts/IMessageInfoStorage.cs | 44 ++ .../ViewModels/MessageInfoViewModel.cs | 51 ++ .../Models/IMessageInfoModel.cs | 44 ++ .../AircraftPlantDatabase.cs | 7 +- .../Implements/MessageInfoStorage.cs | 87 ++++ ...240504174710_MessageInfoCreate.Designer.cs | 298 ++++++++++++ .../20240504174710_MessageInfoCreate.cs | 48 ++ .../AircraftPlantDatabaseModelSnapshot.cs | 41 ++ .../Models/Client.cs | 18 +- .../Models/Message.cs | 94 ++++ .../DataFileSingleton.cs | 50 +- .../Implements/MessageInfoStorage.cs | 95 ++++ .../Models/Message.cs | 118 +++++ .../DataListSingleton.cs | 14 +- .../Implements/MessageInfoStorage.cs | 107 ++++ .../Models/Message.cs | 83 ++++ .../Controllers/ClientController.cs | 43 +- AircraftPlant/AircraftPlantRestApi/Program.cs | 18 + .../AircraftPlantRestApi/appsettings.json | 9 +- .../AircraftPlantView.csproj | 6 + AircraftPlant/AircraftPlantView/App.config | 11 + .../AircraftPlantView/FormMail.Designer.cs | 70 +++ AircraftPlant/AircraftPlantView/FormMail.cs | 77 +++ AircraftPlant/AircraftPlantView/FormMail.resx | 120 +++++ .../AircraftPlantView/FormMain.Designer.cs | 361 +++++++------- AircraftPlant/AircraftPlantView/FormMain.cs | 460 +++++++++--------- AircraftPlant/AircraftPlantView/Program.cs | 38 +- 42 files changed, 2698 insertions(+), 449 deletions(-) create mode 100644 AircraftPlant/AircraftPlant.log.2024-04-22 create mode 100644 AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/MessageInfoLogic.cs create mode 100644 AircraftPlant/AircraftPlantBusinessLogic/MailWorker/AbstractMailWorker.cs create mode 100644 AircraftPlant/AircraftPlantBusinessLogic/MailWorker/MailKitWorker.cs create mode 100644 AircraftPlant/AircraftPlantClientApp/Views/Home/Mails.cshtml create mode 100644 AircraftPlant/AircraftPlantContracts/BindingModels/MailConfigBindingModel.cs create mode 100644 AircraftPlant/AircraftPlantContracts/BindingModels/MailSendInfoBindingModel.cs create mode 100644 AircraftPlant/AircraftPlantContracts/BindingModels/MessageInfoBindingModel.cs create mode 100644 AircraftPlant/AircraftPlantContracts/BusinessLogicsContracts/IMessageInfoLogic.cs create mode 100644 AircraftPlant/AircraftPlantContracts/SearchModels/MessageInfoSearchModel.cs create mode 100644 AircraftPlant/AircraftPlantContracts/StoragesContracts/IMessageInfoStorage.cs create mode 100644 AircraftPlant/AircraftPlantContracts/ViewModels/MessageInfoViewModel.cs create mode 100644 AircraftPlant/AircraftPlantDataModels/Models/IMessageInfoModel.cs create mode 100644 AircraftPlant/AircraftPlantDatabaseImplement/Implements/MessageInfoStorage.cs create mode 100644 AircraftPlant/AircraftPlantDatabaseImplement/Migrations/20240504174710_MessageInfoCreate.Designer.cs create mode 100644 AircraftPlant/AircraftPlantDatabaseImplement/Migrations/20240504174710_MessageInfoCreate.cs create mode 100644 AircraftPlant/AircraftPlantDatabaseImplement/Models/Message.cs create mode 100644 AircraftPlant/AircraftPlantFileImplement/Implements/MessageInfoStorage.cs create mode 100644 AircraftPlant/AircraftPlantFileImplement/Models/Message.cs create mode 100644 AircraftPlant/AircraftPlantListImplement/Implements/MessageInfoStorage.cs create mode 100644 AircraftPlant/AircraftPlantListImplement/Models/Message.cs create mode 100644 AircraftPlant/AircraftPlantView/App.config create mode 100644 AircraftPlant/AircraftPlantView/FormMail.Designer.cs create mode 100644 AircraftPlant/AircraftPlantView/FormMail.cs create mode 100644 AircraftPlant/AircraftPlantView/FormMail.resx diff --git a/AircraftPlant/AircraftPlant.log.2024-04-22 b/AircraftPlant/AircraftPlant.log.2024-04-22 new file mode 100644 index 0000000..74e80ca --- /dev/null +++ b/AircraftPlant/AircraftPlant.log.2024-04-22 @@ -0,0 +1,65 @@ +2024-04-22 01:54:32,867 INFO Microsoft.Hosting.Lifetime.? [?] - MESSAGE: Now listening on: https://localhost:7122 + 2024-04-22 01:54:32,897 INFO Microsoft.Hosting.Lifetime.? [?] - MESSAGE: Now listening on: http://localhost:5092 + 2024-04-22 01:54:32,904 INFO Microsoft.Hosting.Lifetime.OnApplicationStarted [0] - MESSAGE: Application started. Press Ctrl+C to shut down. + 2024-04-22 01:54:32,906 INFO Microsoft.Hosting.Lifetime.OnApplicationStarted [0] - MESSAGE: Hosting environment: Development + 2024-04-22 01:54:32,907 INFO Microsoft.Hosting.Lifetime.OnApplicationStarted [0] - MESSAGE: Content root path: D:\ULSTU\Семестр 4\РПП\AircraftPlant\AircraftPlantRestApi\ + 2024-04-22 01:54:46,181 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadList [49] - MESSAGE: ReadList. ShopName:(null).Id:(null) + 2024-04-22 01:54:48,412 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadList [58] - MESSAGE: ReadList. Count:2 + 2024-04-22 01:55:30,608 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadList [49] - MESSAGE: ReadList. ShopName:(null).Id:(null) + 2024-04-22 01:55:30,634 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadList [58] - MESSAGE: ReadList. Count:2 + 2024-04-22 01:56:13,348 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.CheckModel [247] - MESSAGE: Shop. ShopName:Магазин 3.Address:Улица 3. Id:0 + 2024-04-22 01:56:13,576 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadList [49] - MESSAGE: ReadList. ShopName:(null).Id:(null) + 2024-04-22 01:56:13,581 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadList [58] - MESSAGE: ReadList. Count:3 + 2024-04-22 01:56:21,121 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadList [49] - MESSAGE: ReadList. ShopName:(null).Id:(null) + 2024-04-22 01:56:21,124 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadList [58] - MESSAGE: ReadList. Count:3 + 2024-04-22 01:56:21,142 INFO AircraftPlantBusinessLogic.BusinessLogics.PlaneLogic.ReadList [48] - MESSAGE: ReadList. PlaneName:(null).Id:(null) + 2024-04-22 01:56:21,160 INFO AircraftPlantBusinessLogic.BusinessLogics.PlaneLogic.ReadList [57] - MESSAGE: ReadList. Count:2 + 2024-04-22 01:56:34,923 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.AddPlaneInShop [159] - MESSAGE: AddPlaneInShop. ShopName:(null).Id:6 + 2024-04-22 01:56:34,931 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.AddPlaneInShop [166] - MESSAGE: AddPlaneInShop find. Id:6 + 2024-04-22 01:56:34,935 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.AddPlaneInShop [183] - MESSAGE: AddPlaneInShop. Added 5 new plane to 'Магазин 3' shop + 2024-04-22 01:56:34,989 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadList [49] - MESSAGE: ReadList. ShopName:(null).Id:(null) + 2024-04-22 01:56:34,991 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadList [58] - MESSAGE: ReadList. Count:3 + 2024-04-22 01:56:45,267 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadList [49] - MESSAGE: ReadList. ShopName:(null).Id:(null) + 2024-04-22 01:56:45,269 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadList [58] - MESSAGE: ReadList. Count:3 + 2024-04-22 01:56:45,301 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadElement [75] - MESSAGE: ReadElement. ShopName:(null).Id:4 + 2024-04-22 01:56:45,303 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadElement [84] - MESSAGE: ReadElement find. Id:4 + 2024-04-22 01:56:49,512 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadElement [75] - MESSAGE: ReadElement. ShopName:(null).Id:6 + 2024-04-22 01:56:49,515 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadElement [84] - MESSAGE: ReadElement find. Id:6 + 2024-04-22 10:34:20,669 INFO Microsoft.Hosting.Lifetime.? [?] - MESSAGE: Now listening on: https://localhost:7122 + 2024-04-22 10:34:20,716 INFO Microsoft.Hosting.Lifetime.? [?] - MESSAGE: Now listening on: http://localhost:5092 + 2024-04-22 10:34:20,721 INFO Microsoft.Hosting.Lifetime.OnApplicationStarted [0] - MESSAGE: Application started. Press Ctrl+C to shut down. + 2024-04-22 10:34:20,724 INFO Microsoft.Hosting.Lifetime.OnApplicationStarted [0] - MESSAGE: Hosting environment: Development + 2024-04-22 10:34:20,725 INFO Microsoft.Hosting.Lifetime.OnApplicationStarted [0] - MESSAGE: Content root path: D:\ULSTU\Семестр 4\РПП\AircraftPlant\AircraftPlantRestApi\ + 2024-04-22 10:42:07,542 INFO Microsoft.Hosting.Lifetime.? [?] - MESSAGE: Now listening on: https://localhost:7122 + 2024-04-22 10:42:07,564 INFO Microsoft.Hosting.Lifetime.? [?] - MESSAGE: Now listening on: http://localhost:5092 + 2024-04-22 10:42:07,570 INFO Microsoft.Hosting.Lifetime.OnApplicationStarted [0] - MESSAGE: Application started. Press Ctrl+C to shut down. + 2024-04-22 10:42:07,572 INFO Microsoft.Hosting.Lifetime.OnApplicationStarted [0] - MESSAGE: Hosting environment: Development + 2024-04-22 10:42:07,573 INFO Microsoft.Hosting.Lifetime.OnApplicationStarted [0] - MESSAGE: Content root path: D:\ULSTU\Семестр 4\РПП\AircraftPlant\AircraftPlantRestApi\ + 2024-04-22 10:42:26,255 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadList [49] - MESSAGE: ReadList. ShopName:(null).Id:(null) + 2024-04-22 10:42:28,411 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadList [58] - MESSAGE: ReadList. Count:3 + 2024-04-22 10:43:50,297 INFO Microsoft.Hosting.Lifetime.? [?] - MESSAGE: Now listening on: https://localhost:7122 + 2024-04-22 10:43:50,324 INFO Microsoft.Hosting.Lifetime.? [?] - MESSAGE: Now listening on: http://localhost:5092 + 2024-04-22 10:43:50,329 INFO Microsoft.Hosting.Lifetime.OnApplicationStarted [0] - MESSAGE: Application started. Press Ctrl+C to shut down. + 2024-04-22 10:43:50,331 INFO Microsoft.Hosting.Lifetime.OnApplicationStarted [0] - MESSAGE: Hosting environment: Development + 2024-04-22 10:43:50,333 INFO Microsoft.Hosting.Lifetime.OnApplicationStarted [0] - MESSAGE: Content root path: D:\ULSTU\Семестр 4\РПП\AircraftPlant\AircraftPlantRestApi\ + 2024-04-22 10:48:54,048 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadList [49] - MESSAGE: ReadList. ShopName:(null).Id:(null) + 2024-04-22 10:48:56,110 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadList [58] - MESSAGE: ReadList. Count:3 + 2024-04-22 10:49:15,718 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.CheckModel [247] - MESSAGE: Shop. ShopName:shop.Address:street. Id:0 + 2024-04-22 10:49:16,089 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadList [49] - MESSAGE: ReadList. ShopName:(null).Id:(null) + 2024-04-22 10:49:16,094 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadList [58] - MESSAGE: ReadList. Count:4 + 2024-04-22 10:49:20,397 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadList [49] - MESSAGE: ReadList. ShopName:(null).Id:(null) + 2024-04-22 10:49:20,400 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadList [58] - MESSAGE: ReadList. Count:4 + 2024-04-22 10:49:20,417 INFO AircraftPlantBusinessLogic.BusinessLogics.PlaneLogic.ReadList [48] - MESSAGE: ReadList. PlaneName:(null).Id:(null) + 2024-04-22 10:49:20,446 INFO AircraftPlantBusinessLogic.BusinessLogics.PlaneLogic.ReadList [57] - MESSAGE: ReadList. Count:2 + 2024-04-22 10:49:26,177 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.AddPlaneInShop [159] - MESSAGE: AddPlaneInShop. ShopName:(null).Id:7 + 2024-04-22 10:49:26,189 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.AddPlaneInShop [166] - MESSAGE: AddPlaneInShop find. Id:7 + 2024-04-22 10:49:26,204 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.AddPlaneInShop [183] - MESSAGE: AddPlaneInShop. Added 3 new plane to 'shop' shop + 2024-04-22 10:49:26,300 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadList [49] - MESSAGE: ReadList. ShopName:(null).Id:(null) + 2024-04-22 10:49:26,303 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadList [58] - MESSAGE: ReadList. Count:4 + 2024-04-22 10:49:29,404 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadList [49] - MESSAGE: ReadList. ShopName:(null).Id:(null) + 2024-04-22 10:49:29,407 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadList [58] - MESSAGE: ReadList. Count:4 + 2024-04-22 10:49:29,437 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadElement [75] - MESSAGE: ReadElement. ShopName:(null).Id:4 + 2024-04-22 10:49:29,440 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadElement [84] - MESSAGE: ReadElement find. Id:4 + 2024-04-22 10:49:31,043 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadElement [75] - MESSAGE: ReadElement. ShopName:(null).Id:7 + 2024-04-22 10:49:31,046 INFO AircraftPlantBusinessLogic.BusinessLogics.ShopLogic.ReadElement [84] - MESSAGE: ReadElement find. Id:7 + \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantBusinessLogic/AircraftPlantBusinessLogic.csproj b/AircraftPlant/AircraftPlantBusinessLogic/AircraftPlantBusinessLogic.csproj index bcaa5f0..c8e9ae3 100644 --- a/AircraftPlant/AircraftPlantBusinessLogic/AircraftPlantBusinessLogic.csproj +++ b/AircraftPlant/AircraftPlantBusinessLogic/AircraftPlantBusinessLogic.csproj @@ -8,6 +8,7 @@ + diff --git a/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/ClientLogic.cs b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/ClientLogic.cs index 477238e..a24205b 100644 --- a/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/ClientLogic.cs +++ b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/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 AircraftPlantBusinessLogic.BusinessLogics @@ -155,13 +156,13 @@ namespace AircraftPlantBusinessLogic.BusinessLogics { throw new ArgumentNullException("Нет ФИО клиента", nameof(model.ClientFIO)); } - if (string.IsNullOrEmpty(model.Email)) + if (string.IsNullOrEmpty(model.Email) || !Regex.IsMatch(model.Email, @"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$", RegexOptions.IgnoreCase)) { - throw new ArgumentNullException("Нет почты клиента", nameof(model.Email)); + throw new ArgumentNullException("Невалидная электронная почта клиента", nameof(model.Email)); } - if (string.IsNullOrEmpty(model.Password)) + if (string.IsNullOrEmpty(model.Password) || !Regex.IsMatch(model.Password, @"^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$")) { - throw new ArgumentNullException("Нет пароля клиента", nameof(model.Password)); + throw new ArgumentNullException("Слабый пароль", nameof(model.Password)); } _logger.LogInformation("Client. ClientFIO: {ClientFIO}. Email: {Email}. Id: {Id}", model.ClientFIO, model.Email, model.Id); diff --git a/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/MessageInfoLogic.cs b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/MessageInfoLogic.cs new file mode 100644 index 0000000..62272c0 --- /dev/null +++ b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/MessageInfoLogic.cs @@ -0,0 +1,81 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.BusinessLogicsContracts; +using AircraftPlantContracts.SearchModels; +using AircraftPlantContracts.StoragesContracts; +using AircraftPlantContracts.ViewModels; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantBusinessLogic.BusinessLogics +{ + /// + /// Реализация интерфейса бизнес-логики для писем + /// + public class MessageInfoLogic : IMessageInfoLogic + { + /// + /// Логгер + /// + private readonly ILogger _logger; + + /// + /// Взаимодействие с хранилищем писем + /// + private readonly IMessageInfoStorage _messageStorage; + + /// + /// Конструктор + /// + /// + /// + public MessageInfoLogic(ILogger logger, IMessageInfoStorage messageStorage) + { + _logger = logger; + _messageStorage = messageStorage; + } + + /// + /// Получение списка + /// + /// + /// + public List? ReadList(MessageInfoSearchModel? model) + { + _logger.LogInformation("ReadList. MessageId: {MessageId}. ClientId: {ClientId}", model?.MessageId, model?.ClientId); + + var list = model == null ? _messageStorage.GetFullList() : _messageStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + + _logger.LogInformation("ReadList. Count: {Count}", list.Count); + return list; + } + + /// + /// Создание записи + /// + /// + /// + public bool Create(MessageInfoBindingModel model) + { + if (model == null) + { + return false; + } + + if (_messageStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } + } +} diff --git a/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/OrderLogic.cs b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/OrderLogic.cs index 274c92a..81a717e 100644 --- a/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/OrderLogic.cs @@ -1,9 +1,11 @@ -using AircraftPlantContracts.BindingModels; +using AircraftPlantBusinessLogic.MailWorker; +using AircraftPlantContracts.BindingModels; using AircraftPlantContracts.BusinessLogicsContracts; using AircraftPlantContracts.SearchModels; using AircraftPlantContracts.StoragesContracts; using AircraftPlantContracts.ViewModels; using AircraftPlantDataModels.Enums; +using AircraftPlantDataModels.Models; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; @@ -28,16 +30,29 @@ namespace AircraftPlantBusinessLogic.BusinessLogics /// private readonly IOrderStorage _orderStorage; + /// + /// Взаимодействие с хранилищем клиентов + /// + private readonly IClientStorage _clientStorage; + /// - /// Конструктор + /// Бизнес-логика для отправки писем /// - /// - /// - public OrderLogic(ILogger logger, IOrderStorage -orderStorage) + private readonly AbstractMailWorker _mailLogic; + + /// + /// Конструктор + /// + /// + /// + /// + /// + public OrderLogic(ILogger logger, IOrderStorage orderStorage, IClientStorage clientStorage, AbstractMailWorker mailLogic) { _logger = logger; _orderStorage = orderStorage; + _clientStorage = clientStorage; + _mailLogic = mailLogic; } /// @@ -101,11 +116,14 @@ orderStorage) model.Status = OrderStatus.Принят; - if (_orderStorage.Insert(model) == null) + var order = _orderStorage.Insert(model); + if (order == null) { _logger.LogWarning("Insert operation failed"); return false; } + + SendEmail(order); return true; } @@ -203,12 +221,55 @@ orderStorage) } CheckModel(model, false); - if (_orderStorage.Update(model) == null) + var order = _orderStorage.Update(model); + if (order == null) { _logger.LogWarning("Change status operation failed"); return false; } + + SendEmail(order); return true; } + + /// + /// Отправить письмо + /// + /// + public void SendEmail(OrderViewModel order) + { + if (order == null) + { + return; + } + + var client = _clientStorage.GetElement(new ClientSearchModel { Id = order.ClientId }); + if (client == null) + { + return; + } + + MailSendInfoBindingModel mailModel; + if (order.Status == OrderStatus.Принят) + { + mailModel = new MailSendInfoBindingModel + { + MailAddress = client.Email, + Subject = $"Order №{order.Id}", + Text = $"Your order №{order.Id} by {order.DateCreate} on {order.Sum} was accepted!" + }; + } + else + { + mailModel = new MailSendInfoBindingModel + { + MailAddress = client.Email, + Subject = $"Order №{order.Id}", + Text = $"Order №{order.Id} status was changed to {order.Status}" + }; + } + + _mailLogic.MailSendAsync(mailModel); + } } } diff --git a/AircraftPlant/AircraftPlantBusinessLogic/MailWorker/AbstractMailWorker.cs b/AircraftPlant/AircraftPlantBusinessLogic/MailWorker/AbstractMailWorker.cs new file mode 100644 index 0000000..089b497 --- /dev/null +++ b/AircraftPlant/AircraftPlantBusinessLogic/MailWorker/AbstractMailWorker.cs @@ -0,0 +1,150 @@ +using AircraftPlantBusinessLogic.BusinessLogics; +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantBusinessLogic.MailWorker +{ + /// + /// Абстрактный класс для работы с письмами + /// + public abstract class AbstractMailWorker + { + private readonly ILogger _logger; + + /// + /// Логин для доступа к почтовому сервису + /// + protected string _mailLogin = string.Empty; + + /// + /// Пароль для доступа к почтовому сервису + /// + protected string _mailPassword = string.Empty; + + /// + /// Хост SMTP-клиента + /// + protected string _smtpClientHost = string.Empty; + + /// + /// Порт SMTP-клиента + /// + protected int _smtpClientPort; + + /// + /// Хост протокола POP3 + /// + protected string _popHost = string.Empty; + + /// + /// Порт протокола POP3 + /// + protected int _popPort; + private object _clientLogic; + + /// + /// Бизнес-логика для писем + /// + private readonly IMessageInfoLogic _messageInfoLogic; + + /// + /// Конструктор + /// + /// + /// + 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/AircraftPlant/AircraftPlantBusinessLogic/MailWorker/MailKitWorker.cs b/AircraftPlant/AircraftPlantBusinessLogic/MailWorker/MailKitWorker.cs new file mode 100644 index 0000000..3193bf3 --- /dev/null +++ b/AircraftPlant/AircraftPlantBusinessLogic/MailWorker/MailKitWorker.cs @@ -0,0 +1,103 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Mail; +using System.Net; +using System.Text; +using System.Threading.Tasks; +using MailKit.Net.Pop3; +using MailKit.Security; + +namespace AircraftPlantBusinessLogic.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/AircraftPlant/AircraftPlantClientApp/Controllers/HomeController.cs b/AircraftPlant/AircraftPlantClientApp/Controllers/HomeController.cs index 8e36ae6..4e1586f 100644 --- a/AircraftPlant/AircraftPlantClientApp/Controllers/HomeController.cs +++ b/AircraftPlant/AircraftPlantClientApp/Controllers/HomeController.cs @@ -209,5 +209,20 @@ namespace AircraftPlantClientApp.Controllers var prod = APIClient.GetRequest($"api/main/getplane?planeId={plane}"); 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}")); + } + } } diff --git a/AircraftPlant/AircraftPlantClientApp/Views/Home/Mails.cshtml b/AircraftPlant/AircraftPlantClientApp/Views/Home/Mails.cshtml new file mode 100644 index 0000000..0b1fa57 --- /dev/null +++ b/AircraftPlant/AircraftPlantClientApp/Views/Home/Mails.cshtml @@ -0,0 +1,54 @@ +@using AircraftPlantContracts.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/AircraftPlant/AircraftPlantClientApp/Views/Shared/_Layout.cshtml b/AircraftPlant/AircraftPlantClientApp/Views/Shared/_Layout.cshtml index 03e35ec..d872b22 100644 --- a/AircraftPlant/AircraftPlantClientApp/Views/Shared/_Layout.cshtml +++ b/AircraftPlant/AircraftPlantClientApp/Views/Shared/_Layout.cshtml @@ -27,6 +27,9 @@ + diff --git a/AircraftPlant/AircraftPlantContracts/BindingModels/MailConfigBindingModel.cs b/AircraftPlant/AircraftPlantContracts/BindingModels/MailConfigBindingModel.cs new file mode 100644 index 0000000..7fe9c93 --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/BindingModels/MailConfigBindingModel.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.BindingModels +{ + /// + /// Модель привязки для настройки почтового сервиса + /// + public class MailConfigBindingModel + { + /// + /// Логин для доступа к почтовому сервису + /// + public string MailLogin { get; set; } = string.Empty; + + /// + /// Пароль для доступа к почтовому сервису + /// + public string MailPassword { get; set; } = string.Empty; + + /// + /// Хост SMTP-клиента + /// + public string SmtpClientHost { get; set; } = string.Empty; + + /// + /// Порт SMTP-клиента + /// + public int SmtpClientPort { get; set; } + + /// + /// Хост протокола POP3 + /// + public string PopHost { get; set; } = string.Empty; + + /// + /// Порт протокола POP3 + /// + public int PopPort { get; set; } + } +} diff --git a/AircraftPlant/AircraftPlantContracts/BindingModels/MailSendInfoBindingModel.cs b/AircraftPlant/AircraftPlantContracts/BindingModels/MailSendInfoBindingModel.cs new file mode 100644 index 0000000..c7c5fd6 --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/BindingModels/MailSendInfoBindingModel.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.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/AircraftPlant/AircraftPlantContracts/BindingModels/MessageInfoBindingModel.cs b/AircraftPlant/AircraftPlantContracts/BindingModels/MessageInfoBindingModel.cs new file mode 100644 index 0000000..5521fef --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/BindingModels/MessageInfoBindingModel.cs @@ -0,0 +1,46 @@ +using AircraftPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.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/AircraftPlant/AircraftPlantContracts/BusinessLogicsContracts/IMessageInfoLogic.cs b/AircraftPlant/AircraftPlantContracts/BusinessLogicsContracts/IMessageInfoLogic.cs new file mode 100644 index 0000000..ae4ed0b --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/BusinessLogicsContracts/IMessageInfoLogic.cs @@ -0,0 +1,31 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.SearchModels; +using AircraftPlantContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.BusinessLogicsContracts +{ + /// + /// Интерфейс для описания работы бизнес-логики для писем + /// + public interface IMessageInfoLogic + { + /// + /// Получение списка + /// + /// + /// + List? ReadList(MessageInfoSearchModel? model); + + /// + /// Создание записи + /// + /// + /// + bool Create(MessageInfoBindingModel model); + } +} diff --git a/AircraftPlant/AircraftPlantContracts/SearchModels/MessageInfoSearchModel.cs b/AircraftPlant/AircraftPlantContracts/SearchModels/MessageInfoSearchModel.cs new file mode 100644 index 0000000..5802e2b --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/SearchModels/MessageInfoSearchModel.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.SearchModels +{ + /// + /// Модель для передачи данных пользователя + /// в методы для поиска данных для писем + /// + public class MessageInfoSearchModel + { + /// + /// Идентификатор + /// + public string? MessageId { get; set; } + + /// + /// Идентификатор клиента + /// + public int? ClientId { get; set; } + } +} diff --git a/AircraftPlant/AircraftPlantContracts/StoragesContracts/IMessageInfoStorage.cs b/AircraftPlant/AircraftPlantContracts/StoragesContracts/IMessageInfoStorage.cs new file mode 100644 index 0000000..036407d --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/StoragesContracts/IMessageInfoStorage.cs @@ -0,0 +1,44 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.SearchModels; +using AircraftPlantContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.StoragesContracts +{ + /// + /// Интерфейс для описания работы с хранилищем для писем + /// + public interface IMessageInfoStorage + { + /// + /// Получение полного списка + /// + /// + List GetFullList(); + + /// + /// Получение фильтрованного списка + /// + /// + /// + List GetFilteredList(MessageInfoSearchModel model); + + /// + /// Получение элемента + /// + /// + /// + MessageInfoViewModel? GetElement(MessageInfoSearchModel model); + + /// + /// Добавление элемента + /// + /// + /// + MessageInfoViewModel? Insert(MessageInfoBindingModel model); + } +} diff --git a/AircraftPlant/AircraftPlantContracts/ViewModels/MessageInfoViewModel.cs b/AircraftPlant/AircraftPlantContracts/ViewModels/MessageInfoViewModel.cs new file mode 100644 index 0000000..ab64fd8 --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/ViewModels/MessageInfoViewModel.cs @@ -0,0 +1,51 @@ +using AircraftPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.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/AircraftPlant/AircraftPlantDataModels/Models/IMessageInfoModel.cs b/AircraftPlant/AircraftPlantDataModels/Models/IMessageInfoModel.cs new file mode 100644 index 0000000..05ffd3e --- /dev/null +++ b/AircraftPlant/AircraftPlantDataModels/Models/IMessageInfoModel.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantDataModels.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/AircraftPlant/AircraftPlantDatabaseImplement/AircraftPlantDatabase.cs b/AircraftPlant/AircraftPlantDatabaseImplement/AircraftPlantDatabase.cs index abe70dd..7ad2a33 100644 --- a/AircraftPlant/AircraftPlantDatabaseImplement/AircraftPlantDatabase.cs +++ b/AircraftPlant/AircraftPlantDatabaseImplement/AircraftPlantDatabase.cs @@ -55,5 +55,10 @@ namespace AircraftPlantDatabaseImplement /// Таблица исполнителей ///
public virtual DbSet Implementers { set; get; } - } + + /// + /// Таблица писем + /// + public virtual DbSet Messages { set; get; } + } } diff --git a/AircraftPlant/AircraftPlantDatabaseImplement/Implements/MessageInfoStorage.cs b/AircraftPlant/AircraftPlantDatabaseImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..9907ffa --- /dev/null +++ b/AircraftPlant/AircraftPlantDatabaseImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,87 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.SearchModels; +using AircraftPlantContracts.StoragesContracts; +using AircraftPlantContracts.ViewModels; +using AircraftPlantDatabaseImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantDatabaseImplement.Implements +{ + /// + /// Реализация интерфейса хранилища для писем + /// + public class MessageInfoStorage : IMessageInfoStorage + { + /// + /// Получение полного списка + /// + /// + public List GetFullList() + { + using var context = new AircraftPlantDatabase(); + return context.Messages + .Select(x => x.GetViewModel) + .ToList(); + } + + /// + /// Получение фильтрованного списка + /// + /// + /// + public List GetFilteredList(MessageInfoSearchModel model) + { + if (!model.ClientId.HasValue) + { + return new(); + } + + using var context = new AircraftPlantDatabase(); + return context.Messages + .Where(x => 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 AircraftPlantDatabase(); + return context.Messages + .FirstOrDefault(x => x.MessageId == model.MessageId) + ?.GetViewModel; + } + + /// + /// Добавление элемента + /// + /// + /// + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = Message.Create(model); + if (newMessage == null) + { + return null; + } + + using var context = new AircraftPlantDatabase(); + context.Messages.Add(newMessage); + context.SaveChanges(); + return newMessage.GetViewModel; + } + } +} diff --git a/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/20240504174710_MessageInfoCreate.Designer.cs b/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/20240504174710_MessageInfoCreate.Designer.cs new file mode 100644 index 0000000..d631285 --- /dev/null +++ b/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/20240504174710_MessageInfoCreate.Designer.cs @@ -0,0 +1,298 @@ +// +using System; +using AircraftPlantDatabaseImplement; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace AircraftPlantDatabaseImplement.Migrations +{ + [DbContext(typeof(AircraftPlantDatabase))] + [Migration("20240504174710_MessageInfoCreate")] + partial class MessageInfoCreate + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.3") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Client", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientFIO") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Email") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Password") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Clients"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Component", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ComponentName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Cost") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.ToTable("Components"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Implementer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ImplementerFIO") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Password") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Qualification") + .HasColumnType("int"); + + b.Property("WorkExperience") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.ToTable("Implementers"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Message", b => + { + b.Property("MessageId") + .HasColumnType("nvarchar(450)"); + + b.Property("Body") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("int"); + + b.Property("DateDelivery") + .HasColumnType("datetime2"); + + b.Property("SenderName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Subject") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("MessageId"); + + b.HasIndex("ClientId"); + + b.ToTable("Messages"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Order", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateImplement") + .HasColumnType("datetime2"); + + b.Property("ImplementerId") + .HasColumnType("int"); + + b.Property("PlaneId") + .HasColumnType("int"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("Sum") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.HasIndex("ImplementerId"); + + b.HasIndex("PlaneId"); + + b.ToTable("Orders"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Plane", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("PlaneName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Price") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.ToTable("Planes"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.PlaneComponent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ComponentId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("PlaneId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ComponentId"); + + b.HasIndex("PlaneId"); + + b.ToTable("PlaneComponents"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Message", b => + { + b.HasOne("AircraftPlantDatabaseImplement.Models.Client", "Client") + .WithMany("Messages") + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Order", b => + { + b.HasOne("AircraftPlantDatabaseImplement.Models.Client", "Client") + .WithMany("Orders") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("AircraftPlantDatabaseImplement.Models.Implementer", "Implementer") + .WithMany("Orders") + .HasForeignKey("ImplementerId"); + + b.HasOne("AircraftPlantDatabaseImplement.Models.Plane", "Plane") + .WithMany("Orders") + .HasForeignKey("PlaneId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Client"); + + b.Navigation("Implementer"); + + b.Navigation("Plane"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.PlaneComponent", b => + { + b.HasOne("AircraftPlantDatabaseImplement.Models.Component", "Component") + .WithMany("PlaneComponents") + .HasForeignKey("ComponentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("AircraftPlantDatabaseImplement.Models.Plane", "Plane") + .WithMany("Components") + .HasForeignKey("PlaneId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Component"); + + b.Navigation("Plane"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Client", b => + { + b.Navigation("Messages"); + + b.Navigation("Orders"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Component", b => + { + b.Navigation("PlaneComponents"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Implementer", b => + { + b.Navigation("Orders"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Plane", b => + { + b.Navigation("Components"); + + b.Navigation("Orders"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/20240504174710_MessageInfoCreate.cs b/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/20240504174710_MessageInfoCreate.cs new file mode 100644 index 0000000..c372add --- /dev/null +++ b/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/20240504174710_MessageInfoCreate.cs @@ -0,0 +1,48 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace AircraftPlantDatabaseImplement.Migrations +{ + /// + public partial class MessageInfoCreate : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Messages", + columns: table => new + { + MessageId = table.Column(type: "nvarchar(450)", nullable: false), + ClientId = table.Column(type: "int", nullable: true), + SenderName = table.Column(type: "nvarchar(max)", nullable: false), + DateDelivery = table.Column(type: "datetime2", nullable: false), + Subject = table.Column(type: "nvarchar(max)", nullable: false), + Body = table.Column(type: "nvarchar(max)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Messages", x => x.MessageId); + table.ForeignKey( + name: "FK_Messages_Clients_ClientId", + column: x => x.ClientId, + principalTable: "Clients", + principalColumn: "Id"); + }); + + migrationBuilder.CreateIndex( + name: "IX_Messages_ClientId", + table: "Messages", + column: "ClientId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Messages"); + } + } +} diff --git a/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/AircraftPlantDatabaseModelSnapshot.cs b/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/AircraftPlantDatabaseModelSnapshot.cs index 4925181..808e53a 100644 --- a/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/AircraftPlantDatabaseModelSnapshot.cs +++ b/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/AircraftPlantDatabaseModelSnapshot.cs @@ -94,6 +94,36 @@ namespace AircraftPlantDatabaseImplement.Migrations b.ToTable("Implementers"); }); + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Message", b => + { + b.Property("MessageId") + .HasColumnType("nvarchar(450)"); + + b.Property("Body") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("int"); + + b.Property("DateDelivery") + .HasColumnType("datetime2"); + + b.Property("SenderName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Subject") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("MessageId"); + + b.HasIndex("ClientId"); + + b.ToTable("Messages"); + }); + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -183,6 +213,15 @@ namespace AircraftPlantDatabaseImplement.Migrations b.ToTable("PlaneComponents"); }); + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Message", b => + { + b.HasOne("AircraftPlantDatabaseImplement.Models.Client", "Client") + .WithMany("Messages") + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Order", b => { b.HasOne("AircraftPlantDatabaseImplement.Models.Client", "Client") @@ -229,6 +268,8 @@ namespace AircraftPlantDatabaseImplement.Migrations modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Client", b => { + b.Navigation("Messages"); + b.Navigation("Orders"); }); diff --git a/AircraftPlant/AircraftPlantDatabaseImplement/Models/Client.cs b/AircraftPlant/AircraftPlantDatabaseImplement/Models/Client.cs index a44be09..6f59b44 100644 --- a/AircraftPlant/AircraftPlantDatabaseImplement/Models/Client.cs +++ b/AircraftPlant/AircraftPlantDatabaseImplement/Models/Client.cs @@ -45,12 +45,18 @@ namespace AircraftPlantDatabaseImplement.Models [ForeignKey("ClientId")] public virtual List Orders { get; set; } = new(); - /// - /// Создание модели клиента - /// - /// - /// - public static Client? Create(ClientBindingModel model) + /// + /// Связь с письмами + /// + [ForeignKey("ClientId")] + public virtual List Messages { get; set; } = new(); + + /// + /// Создание модели клиента + /// + /// + /// + public static Client? Create(ClientBindingModel model) { if (model == null) { diff --git a/AircraftPlant/AircraftPlantDatabaseImplement/Models/Message.cs b/AircraftPlant/AircraftPlantDatabaseImplement/Models/Message.cs new file mode 100644 index 0000000..50aae1e --- /dev/null +++ b/AircraftPlant/AircraftPlantDatabaseImplement/Models/Message.cs @@ -0,0 +1,94 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.ViewModels; +using AircraftPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantDatabaseImplement.Models +{ + /// + /// Сущность "Письмо" + /// + public class Message : IMessageInfoModel + { + /// + /// Идентификатор + /// + [Key] + public string MessageId { get; set; } = string.Empty; + + /// + /// Идентификатор клиента + /// + public int? ClientId { get; set; } + + /// + /// Сущность "Клиент" + /// + public virtual Client? Client { get; set; } + + /// + /// Адрес электронной почты отправителя + /// + [Required] + public string SenderName { get; set; } = string.Empty; + + /// + /// Дата получения письма + /// + [Required] + public DateTime DateDelivery { get; set; } + + /// + /// Заголовок письма + /// + [Required] + public string Subject { get; set; } = string.Empty; + + /// + /// Тело письма + /// + [Required] + public string Body { get; set; } = string.Empty; + + /// + /// Создание модели письма + /// + /// + /// + public static Message? 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/AircraftPlant/AircraftPlantFileImplement/DataFileSingleton.cs b/AircraftPlant/AircraftPlantFileImplement/DataFileSingleton.cs index a95f35c..30dd8fe 100644 --- a/AircraftPlant/AircraftPlantFileImplement/DataFileSingleton.cs +++ b/AircraftPlant/AircraftPlantFileImplement/DataFileSingleton.cs @@ -43,10 +43,15 @@ namespace AircraftPlantFileImplement /// private readonly string ImplementerFileName = "Implementer.xml"; - /// - /// Список классов-моделей компонентов - /// - public List Components { get; set; } + /// + /// Название файла для хранения информации о письмах + /// + private readonly string MessageFileName = "Message.xml"; + + /// + /// Список классов-моделей компонентов + /// + public List Components { get; set; } /// /// Список классов-моделей заказов @@ -68,16 +73,22 @@ namespace AircraftPlantFileImplement /// public List Implementers { get; set; } - /// - /// Конструктор - /// - private DataFileSingleton() + /// + /// Список классов-моделей писем + /// + public List Messages { get; set; } + + /// + /// Конструктор + /// + private DataFileSingleton() { Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!; Planes = LoadData(PlaneFileName, "Plane", x => Plane.Create(x)!)!; Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!; Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!; Implementers = LoadData(ImplementerFileName, "Implementer", x => Implementer.Create(x)!)!; + Messages = LoadData(MessageFileName, "Message", x => Message.Create(x)!)!; } /// @@ -118,15 +129,20 @@ namespace AircraftPlantFileImplement /// public void SaveImplementers() => SaveData(Implementers, ImplementerFileName, "Implementers", x => x.GetXElement); - /// - /// Метод для загрузки данных из xml-файла - /// - /// - /// - /// - /// - /// - private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) + /// + /// Сохранение писем + /// + public void SaveMessages() => SaveData(Messages, MessageFileName, "Messages", x => x.GetXElement); + + /// + /// Метод для загрузки данных из xml-файла + /// + /// + /// + /// + /// + /// + private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) { if (File.Exists(filename)) { diff --git a/AircraftPlant/AircraftPlantFileImplement/Implements/MessageInfoStorage.cs b/AircraftPlant/AircraftPlantFileImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..a6a2470 --- /dev/null +++ b/AircraftPlant/AircraftPlantFileImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,95 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.SearchModels; +using AircraftPlantContracts.ViewModels; +using AircraftPlantFileImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantFileImplement.Implements +{ + /// + /// Реализация интерфейса хранилища для писем + /// + public class MessageInfoStorage + { + /// + /// Хранилище + /// + private readonly DataFileSingleton _source; + + /// + /// Конструктор + /// + public MessageInfoStorage() + { + _source = DataFileSingleton.GetInstance(); + } + + /// + /// Получение полного списка + /// + /// + public List GetFullList() + { + return _source.Messages + .Select(x => x.GetViewModel) + .ToList(); + } + + /// + /// Получение фильтрованного списка + /// + /// + /// + public List GetFilteredList(MessageInfoSearchModel model) + { + if (!model.ClientId.HasValue) + { + return new(); + } + + return _source.Messages + .Where(x => x.ClientId == model.ClientId) + .Select(x => x.GetViewModel) + .ToList(); + } + + /// + /// Получение элемента + /// + /// + /// + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (string.IsNullOrEmpty(model.MessageId)) + { + return null; + } + + return _source.Messages + .FirstOrDefault(x => x.MessageId == model.MessageId) + ?.GetViewModel; + } + + /// + /// Добавление элемента + /// + /// + /// + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = Message.Create(model); + if (newMessage == null) + { + return null; + } + + _source.Messages.Add(newMessage); + _source.SaveMessages(); + return newMessage.GetViewModel; + } + } +} diff --git a/AircraftPlant/AircraftPlantFileImplement/Models/Message.cs b/AircraftPlant/AircraftPlantFileImplement/Models/Message.cs new file mode 100644 index 0000000..0cc1bc4 --- /dev/null +++ b/AircraftPlant/AircraftPlantFileImplement/Models/Message.cs @@ -0,0 +1,118 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.ViewModels; +using AircraftPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace AircraftPlantFileImplement.Models +{ + /// + /// Сущность "Письмо" + /// + public class Message : 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 Message? 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 static Message? 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 MessageInfoViewModel GetViewModel => new() + { + MessageId = MessageId, + ClientId = ClientId, + SenderName = SenderName, + DateDelivery = DateDelivery, + Subject = Subject, + Body = Body + }; + + /// + /// Запись данных о модели письма в файл + /// + 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/AircraftPlant/AircraftPlantListImplement/DataListSingleton.cs b/AircraftPlant/AircraftPlantListImplement/DataListSingleton.cs index 87edfd4..a07fc3e 100644 --- a/AircraftPlant/AircraftPlantListImplement/DataListSingleton.cs +++ b/AircraftPlant/AircraftPlantListImplement/DataListSingleton.cs @@ -42,16 +42,22 @@ namespace AircraftPlantListImplement /// public List Implementers { get; set; } - /// - /// Конструктор - /// - private DataListSingleton() + /// + /// Список классов-моделей писем + /// + public List Messages { get; set; } + + /// + /// Конструктор + /// + private DataListSingleton() { Components = new List(); Orders = new List(); Planes = new List(); Clients = new List(); Implementers = new List(); + Messages = new List(); } /// diff --git a/AircraftPlant/AircraftPlantListImplement/Implements/MessageInfoStorage.cs b/AircraftPlant/AircraftPlantListImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..97d381d --- /dev/null +++ b/AircraftPlant/AircraftPlantListImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,107 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.SearchModels; +using AircraftPlantContracts.StoragesContracts; +using AircraftPlantContracts.ViewModels; +using AircraftPlantListImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantListImplement.Implements +{ + /// + /// Реализация интерфейса хранилища для писем + /// + public class MessageInfoStorage : IMessageInfoStorage + { + /// + /// Хранилище + /// + private readonly DataListSingleton _source; + + /// + /// Конструктор + /// + public MessageInfoStorage() + { + _source = DataListSingleton.GetInstance(); + } + + /// + /// Получение полного списка + /// + /// + public List GetFullList() + { + var result = new List(); + foreach (var message in _source.Messages) + { + result.Add(message.GetViewModel); + } + return result; + } + + /// + /// Получение фильтрованного списка + /// + /// + /// + public List GetFilteredList(MessageInfoSearchModel model) + { + var result = new List(); + + if (!model.ClientId.HasValue) + { + return new(); + } + + foreach (var message in _source.Messages) + { + if (message.ClientId == model.ClientId) + { + result.Add(message.GetViewModel); + } + } + return result; + } + + /// + /// Получение элемента + /// + /// + /// + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (string.IsNullOrEmpty(model.MessageId)) + { + return null; + } + + foreach (var message in _source.Messages) + { + if (model.MessageId.Equals(message.MessageId)) + return message.GetViewModel; + } + return null; + } + + /// + /// Добавление элемента + /// + /// + /// + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = Message.Create(model); + if (newMessage == null) + { + return null; + } + + _source.Messages.Add(newMessage); + return newMessage.GetViewModel; + } + } +} diff --git a/AircraftPlant/AircraftPlantListImplement/Models/Message.cs b/AircraftPlant/AircraftPlantListImplement/Models/Message.cs new file mode 100644 index 0000000..6e0441a --- /dev/null +++ b/AircraftPlant/AircraftPlantListImplement/Models/Message.cs @@ -0,0 +1,83 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.ViewModels; +using AircraftPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantListImplement.Models +{ + /// + /// Сущность "Письмо" + /// + public class Message : 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 Message? 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/AircraftPlant/AircraftPlantRestApi/Controllers/ClientController.cs b/AircraftPlant/AircraftPlantRestApi/Controllers/ClientController.cs index 2bb3a49..d01bd9c 100644 --- a/AircraftPlant/AircraftPlantRestApi/Controllers/ClientController.cs +++ b/AircraftPlant/AircraftPlantRestApi/Controllers/ClientController.cs @@ -23,15 +23,22 @@ namespace AircraftPlantRestApi.Controllers /// private readonly IClientLogic _logic; - /// - /// Конструктор - /// - /// - /// - public ClientController(IClientLogic logic, ILogger logger) + /// + /// Бизнес-логика для писем + /// + private readonly IMessageInfoLogic _mailLogic; + + /// + /// Конструктор + /// + /// + /// + /// + public ClientController(IClientLogic logic, ILogger logger, IMessageInfoLogic mailLogic) { _logger = logger; _logic = logic; + _mailLogic = mailLogic; } /// @@ -93,5 +100,27 @@ namespace AircraftPlantRestApi.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/AircraftPlant/AircraftPlantRestApi/Program.cs b/AircraftPlant/AircraftPlantRestApi/Program.cs index 5ae7f92..efcbbab 100644 --- a/AircraftPlant/AircraftPlantRestApi/Program.cs +++ b/AircraftPlant/AircraftPlantRestApi/Program.cs @@ -1,4 +1,6 @@ using AircraftPlantBusinessLogic.BusinessLogics; +using AircraftPlantBusinessLogic.MailWorker; +using AircraftPlantContracts.BindingModels; using AircraftPlantContracts.BusinessLogicsContracts; using AircraftPlantContracts.StoragesContracts; using AircraftPlantDatabaseImplement.Implements; @@ -14,11 +16,15 @@ builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddTransient(); + +builder.Services.AddSingleton(); builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle @@ -30,6 +36,18 @@ 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/AircraftPlant/AircraftPlantRestApi/appsettings.json b/AircraftPlant/AircraftPlantRestApi/appsettings.json index 10f68b8..a875686 100644 --- a/AircraftPlant/AircraftPlantRestApi/appsettings.json +++ b/AircraftPlant/AircraftPlantRestApi/appsettings.json @@ -5,5 +5,12 @@ "Microsoft.AspNetCore": "Warning" } }, - "AllowedHosts": "*" + "AllowedHosts": "*", + + "SmtpClientHost": "smtp.gmail.com", + "SmtpClientPort": "587", + "PopHost": "pop.gmail.com", + "PopPort": "995", + "MailLogin": "aircraftplant73@gmail.com", + "MailPassword": "vcus klnn auqe axlq" } diff --git a/AircraftPlant/AircraftPlantView/AircraftPlantView.csproj b/AircraftPlant/AircraftPlantView/AircraftPlantView.csproj index 354cd26..ae6dade 100644 --- a/AircraftPlant/AircraftPlantView/AircraftPlantView.csproj +++ b/AircraftPlant/AircraftPlantView/AircraftPlantView.csproj @@ -37,4 +37,10 @@ + + + Always + + + \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantView/App.config b/AircraftPlant/AircraftPlantView/App.config new file mode 100644 index 0000000..d2a7c0c --- /dev/null +++ b/AircraftPlant/AircraftPlantView/App.config @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantView/FormMail.Designer.cs b/AircraftPlant/AircraftPlantView/FormMail.Designer.cs new file mode 100644 index 0000000..7d6019b --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormMail.Designer.cs @@ -0,0 +1,70 @@ +namespace AircraftPlantView +{ + 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.BackgroundColor = Color.White; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Dock = DockStyle.Fill; + dataGridView.GridColor = Color.Black; + dataGridView.Location = new Point(0, 0); + dataGridView.MultiSelect = false; + dataGridView.Name = "dataGridView"; + dataGridView.ReadOnly = true; + dataGridView.RowHeadersVisible = false; + dataGridView.RowTemplate.Height = 25; + dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; + dataGridView.Size = new Size(584, 361); + dataGridView.TabIndex = 2; + // + // FormMail + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(584, 361); + Controls.Add(dataGridView); + 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/AircraftPlant/AircraftPlantView/FormMail.cs b/AircraftPlant/AircraftPlantView/FormMail.cs new file mode 100644 index 0000000..6b03878 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormMail.cs @@ -0,0 +1,77 @@ +using AircraftPlantContracts.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 AircraftPlantView +{ + /// + /// Форма для вывода писем + /// + 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 FormMail_Load(object sender, EventArgs e) + { + LoadData(); + } + + /// + /// Метод загрузки писем + /// + private void LoadData() + { + try + { + var list = _logic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["MessageId"].Visible = false; + dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + _logger.LogInformation("Загрузка писем"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки писем"); + MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } +} diff --git a/AircraftPlant/AircraftPlantView/FormMail.resx b/AircraftPlant/AircraftPlantView/FormMail.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/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/AircraftPlant/AircraftPlantView/FormMain.Designer.cs b/AircraftPlant/AircraftPlantView/FormMain.Designer.cs index 75fd11e..e4f9e4c 100644 --- a/AircraftPlant/AircraftPlantView/FormMain.Designer.cs +++ b/AircraftPlant/AircraftPlantView/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() - { - dataGridView = new DataGridView(); - buttonCreateOrder = new Button(); - buttonIssuedOrder = new Button(); - buttonRefresh = new Button(); - menuStrip = new MenuStrip(); - справочникиToolStripMenuItem = new ToolStripMenuItem(); - компонентыToolStripMenuItem = new ToolStripMenuItem(); - изделияToolStripMenuItem = new ToolStripMenuItem(); - клиентыToolStripMenuItem = new ToolStripMenuItem(); - отчетыToolStripMenuItem = new ToolStripMenuItem(); - изделияToolStripMenuItem1 = new ToolStripMenuItem(); - изделияСКомпонентамиToolStripMenuItem = new ToolStripMenuItem(); - списокЗаказовToolStripMenuItem = new ToolStripMenuItem(); - запускРаботToolStripMenuItem = new ToolStripMenuItem(); - исполнителиToolStripMenuItem = new ToolStripMenuItem(); - ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); - menuStrip.SuspendLayout(); - SuspendLayout(); - // - // dataGridView - // - dataGridView.AllowUserToAddRows = false; - dataGridView.AllowUserToDeleteRows = false; - dataGridView.BackgroundColor = Color.White; - dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; - dataGridView.Dock = DockStyle.Left; - dataGridView.GridColor = Color.White; - dataGridView.Location = new Point(0, 24); - dataGridView.MultiSelect = false; - dataGridView.Name = "dataGridView"; - dataGridView.ReadOnly = true; - dataGridView.RowHeadersVisible = false; - dataGridView.RowTemplate.Height = 25; - dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; - dataGridView.Size = new Size(800, 337); - dataGridView.TabIndex = 0; - // - // buttonCreateOrder - // - buttonCreateOrder.Location = new Point(822, 36); - buttonCreateOrder.Name = "buttonCreateOrder"; - buttonCreateOrder.Size = new Size(150, 23); - buttonCreateOrder.TabIndex = 1; - buttonCreateOrder.Text = "Создать заказ"; - buttonCreateOrder.UseVisualStyleBackColor = true; - buttonCreateOrder.Click += buttonCreateOrder_Click; - // - // buttonIssuedOrder - // - buttonIssuedOrder.Location = new Point(822, 65); - buttonIssuedOrder.Name = "buttonIssuedOrder"; - buttonIssuedOrder.Size = new Size(150, 23); - buttonIssuedOrder.TabIndex = 4; - buttonIssuedOrder.Text = "Заказ выдан"; - buttonIssuedOrder.UseVisualStyleBackColor = true; - buttonIssuedOrder.Click += buttonIssuedOrder_Click; - // - // buttonRefresh - // - buttonRefresh.Location = new Point(822, 94); - buttonRefresh.Name = "buttonRefresh"; - buttonRefresh.Size = new Size(150, 23); - buttonRefresh.TabIndex = 5; - buttonRefresh.Text = "Обновить список"; - buttonRefresh.UseVisualStyleBackColor = true; - buttonRefresh.Click += buttonRefresh_Click; - // - // menuStrip - // - menuStrip.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчетыToolStripMenuItem, запускРаботToolStripMenuItem }); - menuStrip.Location = new Point(0, 0); - menuStrip.Name = "menuStrip"; - menuStrip.Size = new Size(984, 24); - menuStrip.TabIndex = 6; - menuStrip.Text = "menuStrip1"; - // - // справочникиToolStripMenuItem - // - справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, изделияToolStripMenuItem, клиентыToolStripMenuItem, исполнителиToolStripMenuItem }); - справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; - справочникиToolStripMenuItem.Size = new Size(94, 20); - справочникиToolStripMenuItem.Text = "Справочники"; - // - // компонентыToolStripMenuItem - // - компонентыToolStripMenuItem.Name = "компонентыToolStripMenuItem"; - компонентыToolStripMenuItem.Size = new Size(180, 22); - компонентыToolStripMenuItem.Text = "Компоненты"; - компонентыToolStripMenuItem.Click += компонентыToolStripMenuItem_Click; - // - // изделияToolStripMenuItem - // - изделияToolStripMenuItem.Name = "изделияToolStripMenuItem"; - изделияToolStripMenuItem.Size = new Size(180, 22); - изделияToolStripMenuItem.Text = "Изделия"; - изделияToolStripMenuItem.Click += изделияToolStripMenuItem_Click; - // - // клиентыToolStripMenuItem - // - клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; - клиентыToolStripMenuItem.Size = new Size(180, 22); - клиентыToolStripMenuItem.Text = "Клиенты"; - клиентыToolStripMenuItem.Click += клиентыToolStripMenuItem_Click; - // - // отчетыToolStripMenuItem - // - отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { изделияToolStripMenuItem1, изделияСКомпонентамиToolStripMenuItem, списокЗаказовToolStripMenuItem }); - отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem"; - отчетыToolStripMenuItem.Size = new Size(60, 20); - отчетыToolStripMenuItem.Text = "Отчеты"; - // - // изделияToolStripMenuItem1 - // - изделияToolStripMenuItem1.Name = "изделияToolStripMenuItem1"; - изделияToolStripMenuItem1.Size = new Size(215, 22); - изделияToolStripMenuItem1.Text = "Изделия"; - изделияToolStripMenuItem1.Click += изделияToolStripMenuItem1_Click; - // - // изделияСКомпонентамиToolStripMenuItem - // - изделияСКомпонентамиToolStripMenuItem.Name = "изделияСКомпонентамиToolStripMenuItem"; - изделияСКомпонентамиToolStripMenuItem.Size = new Size(215, 22); - изделияСКомпонентамиToolStripMenuItem.Text = "Изделия с компонентами"; - изделияСКомпонентамиToolStripMenuItem.Click += изделияСКомпонентамиToolStripMenuItem_Click; - // - // списокЗаказовToolStripMenuItem - // - списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem"; - списокЗаказовToolStripMenuItem.Size = new Size(215, 22); - списокЗаказовToolStripMenuItem.Text = "Список заказов"; - списокЗаказовToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click; - // - // запускРаботToolStripMenuItem - // - запускРаботToolStripMenuItem.Name = "запускРаботToolStripMenuItem"; - запускРаботToolStripMenuItem.Size = new Size(92, 20); - запускРаботToolStripMenuItem.Text = "Запуск работ"; - запускРаботToolStripMenuItem.Click += запускРаботToolStripMenuItem_Click; - // - // исполнителиToolStripMenuItem - // - исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; - исполнителиToolStripMenuItem.Size = new Size(180, 22); - исполнителиToolStripMenuItem.Text = "Исполнители"; - исполнителиToolStripMenuItem.Click += исполнителиToolStripMenuItem_Click; - // - // FormMain - // - AutoScaleDimensions = new SizeF(7F, 15F); - AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(984, 361); - Controls.Add(buttonRefresh); - Controls.Add(buttonIssuedOrder); - Controls.Add(buttonCreateOrder); - Controls.Add(dataGridView); - Controls.Add(menuStrip); - MainMenuStrip = menuStrip; - Name = "FormMain"; - Text = "Авиационный завод"; - Load += FormMain_Load; - ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); - menuStrip.ResumeLayout(false); - menuStrip.PerformLayout(); - ResumeLayout(false); - PerformLayout(); - } + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + dataGridView = new DataGridView(); + buttonCreateOrder = new Button(); + buttonIssuedOrder = new Button(); + buttonRefresh = new Button(); + menuStrip = new MenuStrip(); + справочникиToolStripMenuItem = new ToolStripMenuItem(); + компонентыToolStripMenuItem = new ToolStripMenuItem(); + изделияToolStripMenuItem = new ToolStripMenuItem(); + клиентыToolStripMenuItem = new ToolStripMenuItem(); + исполнителиToolStripMenuItem = new ToolStripMenuItem(); + отчетыToolStripMenuItem = new ToolStripMenuItem(); + изделияToolStripMenuItem1 = new ToolStripMenuItem(); + изделияСКомпонентамиToolStripMenuItem = new ToolStripMenuItem(); + списокЗаказовToolStripMenuItem = new ToolStripMenuItem(); + запускРаботToolStripMenuItem = new ToolStripMenuItem(); + почтаToolStripMenuItem = new ToolStripMenuItem(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + menuStrip.SuspendLayout(); + SuspendLayout(); + // + // dataGridView + // + dataGridView.AllowUserToAddRows = false; + dataGridView.AllowUserToDeleteRows = false; + dataGridView.BackgroundColor = Color.White; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Dock = DockStyle.Left; + dataGridView.GridColor = Color.White; + dataGridView.Location = new Point(0, 24); + dataGridView.MultiSelect = false; + dataGridView.Name = "dataGridView"; + dataGridView.ReadOnly = true; + dataGridView.RowHeadersVisible = false; + dataGridView.RowTemplate.Height = 25; + dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; + dataGridView.Size = new Size(800, 337); + dataGridView.TabIndex = 0; + // + // buttonCreateOrder + // + buttonCreateOrder.Location = new Point(822, 36); + buttonCreateOrder.Name = "buttonCreateOrder"; + buttonCreateOrder.Size = new Size(150, 23); + buttonCreateOrder.TabIndex = 1; + buttonCreateOrder.Text = "Создать заказ"; + buttonCreateOrder.UseVisualStyleBackColor = true; + buttonCreateOrder.Click += buttonCreateOrder_Click; + // + // buttonIssuedOrder + // + buttonIssuedOrder.Location = new Point(822, 65); + buttonIssuedOrder.Name = "buttonIssuedOrder"; + buttonIssuedOrder.Size = new Size(150, 23); + buttonIssuedOrder.TabIndex = 4; + buttonIssuedOrder.Text = "Заказ выдан"; + buttonIssuedOrder.UseVisualStyleBackColor = true; + buttonIssuedOrder.Click += buttonIssuedOrder_Click; + // + // buttonRefresh + // + buttonRefresh.Location = new Point(822, 94); + buttonRefresh.Name = "buttonRefresh"; + buttonRefresh.Size = new Size(150, 23); + buttonRefresh.TabIndex = 5; + buttonRefresh.Text = "Обновить список"; + buttonRefresh.UseVisualStyleBackColor = true; + buttonRefresh.Click += buttonRefresh_Click; + // + // menuStrip + // + menuStrip.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчетыToolStripMenuItem, запускРаботToolStripMenuItem, почтаToolStripMenuItem }); + menuStrip.Location = new Point(0, 0); + menuStrip.Name = "menuStrip"; + menuStrip.Size = new Size(984, 24); + menuStrip.TabIndex = 6; + menuStrip.Text = "menuStrip1"; + // + // справочникиToolStripMenuItem + // + справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, изделияToolStripMenuItem, клиентыToolStripMenuItem, исполнителиToolStripMenuItem }); + справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; + справочникиToolStripMenuItem.Size = new Size(94, 20); + справочникиToolStripMenuItem.Text = "Справочники"; + // + // компонентыToolStripMenuItem + // + компонентыToolStripMenuItem.Name = "компонентыToolStripMenuItem"; + компонентыToolStripMenuItem.Size = new Size(149, 22); + компонентыToolStripMenuItem.Text = "Компоненты"; + компонентыToolStripMenuItem.Click += компонентыToolStripMenuItem_Click; + // + // изделияToolStripMenuItem + // + изделияToolStripMenuItem.Name = "изделияToolStripMenuItem"; + изделияToolStripMenuItem.Size = new Size(149, 22); + изделияToolStripMenuItem.Text = "Изделия"; + изделияToolStripMenuItem.Click += изделияToolStripMenuItem_Click; + // + // клиентыToolStripMenuItem + // + клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; + клиентыToolStripMenuItem.Size = new Size(149, 22); + клиентыToolStripMenuItem.Text = "Клиенты"; + клиентыToolStripMenuItem.Click += клиентыToolStripMenuItem_Click; + // + // исполнителиToolStripMenuItem + // + исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; + исполнителиToolStripMenuItem.Size = new Size(149, 22); + исполнителиToolStripMenuItem.Text = "Исполнители"; + исполнителиToolStripMenuItem.Click += исполнителиToolStripMenuItem_Click; + // + // отчетыToolStripMenuItem + // + отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { изделияToolStripMenuItem1, изделияСКомпонентамиToolStripMenuItem, списокЗаказовToolStripMenuItem }); + отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem"; + отчетыToolStripMenuItem.Size = new Size(60, 20); + отчетыToolStripMenuItem.Text = "Отчеты"; + // + // изделияToolStripMenuItem1 + // + изделияToolStripMenuItem1.Name = "изделияToolStripMenuItem1"; + изделияToolStripMenuItem1.Size = new Size(215, 22); + изделияToolStripMenuItem1.Text = "Изделия"; + изделияToolStripMenuItem1.Click += изделияToolStripMenuItem1_Click; + // + // изделияСКомпонентамиToolStripMenuItem + // + изделияСКомпонентамиToolStripMenuItem.Name = "изделияСКомпонентамиToolStripMenuItem"; + изделияСКомпонентамиToolStripMenuItem.Size = new Size(215, 22); + изделияСКомпонентамиToolStripMenuItem.Text = "Изделия с компонентами"; + изделияСКомпонентамиToolStripMenuItem.Click += изделияСКомпонентамиToolStripMenuItem_Click; + // + // списокЗаказовToolStripMenuItem + // + списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem"; + списокЗаказовToolStripMenuItem.Size = new Size(215, 22); + списокЗаказовToolStripMenuItem.Text = "Список заказов"; + списокЗаказовToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click; + // + // запускРаботToolStripMenuItem + // + запускРаботToolStripMenuItem.Name = "запускРаботToolStripMenuItem"; + запускРаботToolStripMenuItem.Size = new Size(92, 20); + запускРаботToolStripMenuItem.Text = "Запуск работ"; + запускРаботToolStripMenuItem.Click += запускРаботToolStripMenuItem_Click; + // + // почтаToolStripMenuItem + // + почтаToolStripMenuItem.Name = "почтаToolStripMenuItem"; + почтаToolStripMenuItem.Size = new Size(53, 20); + почтаToolStripMenuItem.Text = "Почта"; + почтаToolStripMenuItem.Click += почтаToolStripMenuItem_Click; + // + // FormMain + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(984, 361); + Controls.Add(buttonRefresh); + Controls.Add(buttonIssuedOrder); + Controls.Add(buttonCreateOrder); + Controls.Add(dataGridView); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; + Name = "FormMain"; + Text = "Авиационный завод"; + Load += FormMain_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); + ResumeLayout(false); + PerformLayout(); + } - #endregion + #endregion - private DataGridView dataGridView; + private DataGridView dataGridView; private Button buttonCreateOrder; private Button buttonIssuedOrder; private Button buttonRefresh; @@ -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/AircraftPlant/AircraftPlantView/FormMain.cs b/AircraftPlant/AircraftPlantView/FormMain.cs index 34bd929..66302e5 100644 --- a/AircraftPlant/AircraftPlantView/FormMain.cs +++ b/AircraftPlant/AircraftPlantView/FormMain.cs @@ -14,244 +14,258 @@ using System.Windows.Forms; namespace AircraftPlantView { - /// - /// Главная форма - /// - public partial class FormMain : Form - { - /// - /// Логгер - /// - private readonly ILogger _logger; + /// + /// Главная форма + /// + public partial class FormMain : Form + { + /// + /// Логгер + /// + private readonly ILogger _logger; - /// - /// Бизнес-логика для заказов - /// - private readonly IOrderLogic _orderLogic; + /// + /// Бизнес-логика для заказов + /// + private readonly IOrderLogic _orderLogic; - /// - /// Взаимодействие с отчетами - /// - private readonly IReportLogic _reportLogic; + /// + /// Взаимодействие с отчетами + /// + private readonly IReportLogic _reportLogic; - /// - /// Имитация деятельности исполнителей - /// - private readonly IWorkProcess _workProcess; + /// + /// Имитация деятельности исполнителей + /// + private readonly IWorkProcess _workProcess; - /// - /// Конструктор - /// - /// - /// - public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess) - { - InitializeComponent(); - _logger = logger; - _orderLogic = orderLogic; - _reportLogic = reportLogic; - _workProcess = workProcess; - } + /// + /// Конструктор + /// + /// + /// + public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess) + { + InitializeComponent(); + _logger = logger; + _orderLogic = orderLogic; + _reportLogic = reportLogic; + _workProcess = workProcess; + } - /// - /// Загрузка списка заказов - /// - /// - /// - private void FormMain_Load(object sender, EventArgs e) - { - LoadData(); - } + /// + /// Загрузка списка заказов + /// + /// + /// + private void FormMain_Load(object sender, EventArgs e) + { + LoadData(); + } - /// - /// Показать список всех компонентов - /// - /// - /// - private void компонентыToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormComponents)); - if (service is FormComponents form) - { - form.ShowDialog(); - } - } + /// + /// Показать список всех компонентов + /// + /// + /// + private void компонентыToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormComponents)); + if (service is FormComponents form) + { + form.ShowDialog(); + } + } - /// - /// Показать список всех изделий - /// - /// - /// - private void изделияToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormPlanes)); - if (service is FormPlanes form) - { - form.ShowDialog(); - } - } + /// + /// Показать список всех изделий + /// + /// + /// + private void изделияToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormPlanes)); + if (service is FormPlanes form) + { + form.ShowDialog(); + } + } - /// - /// Вывести список всех клиентов - /// - /// - /// - private void клиентыToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormClients)); - if (service is FormClients form) - { - form.ShowDialog(); - } - } + /// + /// Вывести список всех клиентов + /// + /// + /// + private void клиентыToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormClients)); + if (service is FormClients form) + { + form.ShowDialog(); + } + } - /// - /// Вывести список всех исполнителей - /// - /// - /// - private void исполнителиToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormImplementers)); - if (service is FormImplementers form) - { - form.ShowDialog(); - } - } + /// + /// Вывести список всех исполнителей + /// + /// + /// + private void исполнителиToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormImplementers)); + if (service is FormImplementers form) + { + form.ShowDialog(); + } + } - /// - /// Вывести отчет по изделиям - /// - /// - /// - private void изделияToolStripMenuItem1_Click(object sender, EventArgs e) - { - using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; - if (dialog.ShowDialog() == DialogResult.OK) - { - _reportLogic.SavePlanesToWordFile(new ReportBindingModel { FileName = dialog.FileName }); - MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); - } - } + /// + /// Вывести отчет по изделиям + /// + /// + /// + private void изделияToolStripMenuItem1_Click(object sender, EventArgs e) + { + using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; + if (dialog.ShowDialog() == DialogResult.OK) + { + _reportLogic.SavePlanesToWordFile(new ReportBindingModel { FileName = dialog.FileName }); + MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } - /// - /// Получить отчет по изделиям с расшифровкой по компонентам - /// - /// - /// - private void изделияСКомпонентамиToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormReportPlaneComponents)); - if (service is FormReportPlaneComponents form) - { - form.ShowDialog(); - } - } + /// + /// Получить отчет по изделиям с расшифровкой по компонентам + /// + /// + /// + private void изделияСКомпонентамиToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReportPlaneComponents)); + if (service is FormReportPlaneComponents form) + { + form.ShowDialog(); + } + } - /// - /// Получить отчет по заказам - /// - /// - /// - private void списокЗаказовToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders)); - if (service is FormReportOrders form) - { - form.ShowDialog(); - } - } + /// + /// Получить отчет по заказам + /// + /// + /// + private void списокЗаказовToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders)); + if (service is FormReportOrders form) + { + form.ShowDialog(); + } + } - /// - /// Запуск имитации работы исполнителей - /// - /// - /// - private void запускРаботToolStripMenuItem_Click(object sender, EventArgs e) - { - _workProcess.DoWork(( - Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, - _orderLogic); - MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); - } + /// + /// Запуск имитации работы исполнителей + /// + /// + /// + private void запускРаботToolStripMenuItem_Click(object sender, EventArgs e) + { + _workProcess.DoWork(( + Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, + _orderLogic); + MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + } - /// - /// Кнопка "Создать заказ" - /// - /// - /// - private void buttonCreateOrder_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); - if (service is FormCreateOrder form) - { - form.ShowDialog(); - LoadData(); - } - } + /// + /// Посмотреть письма + /// + /// + /// + private void почтаToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormMail)); + if (service is FormMail form) + { + form.ShowDialog(); + } + } - /// - /// Кнопка "Заказ выдан" - /// - /// - /// - private void buttonIssuedOrder_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id); - try - { - var operationResult = _orderLogic.FinishOrder(new OrderBindingModel { Id = id }); - if (!operationResult) - { - throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); - } - _logger.LogInformation("Заказ №{id} выдан", id); - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка отметки о выдаче заказа"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } + /// + /// Кнопка "Создать заказ" + /// + /// + /// + private void buttonCreateOrder_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); + if (service is FormCreateOrder form) + { + form.ShowDialog(); + LoadData(); + } + } - /// - /// Кнопка "Обновить список" - /// - /// - /// - private void buttonRefresh_Click(object sender, EventArgs e) - { - LoadData(); - } + /// + /// Кнопка "Заказ выдан" + /// + /// + /// + private void buttonIssuedOrder_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id); + try + { + var operationResult = _orderLogic.FinishOrder(new OrderBindingModel { Id = id }); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + _logger.LogInformation("Заказ №{id} выдан", id); + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка отметки о выдаче заказа"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } - /// - /// Метод загрузки списка заказов - /// - private void LoadData() - { - _logger.LogInformation("Загрузка заказов"); - try - { - var list = _orderLogic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["PlaneId"].Visible = false; - dataGridView.Columns["ClientId"].Visible = false; - dataGridView.Columns["ImplementerId"].Visible = false; - } - _logger.LogInformation("Загрузка заказов"); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки заказов"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } + /// + /// Кнопка "Обновить список" + /// + /// + /// + private void buttonRefresh_Click(object sender, EventArgs e) + { + LoadData(); + } + + /// + /// Метод загрузки списка заказов + /// + private void LoadData() + { + _logger.LogInformation("Загрузка заказов"); + try + { + var list = _orderLogic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["PlaneId"].Visible = false; + dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["ImplementerId"].Visible = false; + } + _logger.LogInformation("Загрузка заказов"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки заказов"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } } diff --git a/AircraftPlant/AircraftPlantView/Program.cs b/AircraftPlant/AircraftPlantView/Program.cs index 80c4e13..bc6969b 100644 --- a/AircraftPlant/AircraftPlantView/Program.cs +++ b/AircraftPlant/AircraftPlantView/Program.cs @@ -8,6 +8,8 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; using System; +using AircraftPlantBusinessLogic.MailWorker; +using AircraftPlantContracts.BindingModels; namespace AircraftPlantView { @@ -33,7 +35,30 @@ namespace AircraftPlantView ConfigureServices(services); _serviceProvider = services.BuildServiceProvider(); - Application.Run(_serviceProvider.GetRequiredService()); + // + try + { + var mailSender = _serviceProvider.GetService(); + mailSender?.MailConfig(new MailConfigBindingModel + { + MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty, + MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty, + SmtpClientHost = System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty, + SmtpClientPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]), + PopHost = System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty, + PopPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"]) + }); + + // + var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 60000); + } + catch (Exception ex) + { + var logger = _serviceProvider.GetService(); + logger?.LogError(ex, " "); + } + + Application.Run(_serviceProvider.GetRequiredService()); } /// @@ -53,6 +78,7 @@ namespace AircraftPlantView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -60,7 +86,10 @@ namespace AircraftPlantView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddSingleton(); services.AddTransient(); services.AddTransient(); @@ -78,6 +107,13 @@ namespace AircraftPlantView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); } + + /// + /// + /// + /// + private static void MailCheck(object obj) => ServiceProvider?.GetService()?.MailCheck(); } } \ No newline at end of file -- 2.25.1 From 066eae705e0c552194164a9097e146ff250d7756 Mon Sep 17 00:00:00 2001 From: Factorino73 Date: Mon, 6 May 2024 04:26:07 +0400 Subject: [PATCH 4/5] Fix --- AircraftPlant/AircraftPlantClientApp/Views/Home/Mails.cshtml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AircraftPlant/AircraftPlantClientApp/Views/Home/Mails.cshtml b/AircraftPlant/AircraftPlantClientApp/Views/Home/Mails.cshtml index 659c270..408a9de 100644 --- a/AircraftPlant/AircraftPlantClientApp/Views/Home/Mails.cshtml +++ b/AircraftPlant/AircraftPlantClientApp/Views/Home/Mails.cshtml @@ -55,7 +55,7 @@ Назад

Страница @ViewBag.Page

- + Вперед } -- 2.25.1 From 30faefcee2c60d8ee8aba9ce10b20259875331f3 Mon Sep 17 00:00:00 2001 From: Factorino73 Date: Mon, 6 May 2024 11:01:40 +0400 Subject: [PATCH 5/5] Fix --- AircraftPlant/AircraftPlantClientApp/Views/Home/Mails.cshtml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/AircraftPlant/AircraftPlantClientApp/Views/Home/Mails.cshtml b/AircraftPlant/AircraftPlantClientApp/Views/Home/Mails.cshtml index 408a9de..7604a69 100644 --- a/AircraftPlant/AircraftPlantClientApp/Views/Home/Mails.cshtml +++ b/AircraftPlant/AircraftPlantClientApp/Views/Home/Mails.cshtml @@ -51,11 +51,11 @@ - 1 ? ViewBag.Page - 1 : 1 }) class="btn btn-primary"> + = 1 ? ViewBag.Page - 1 : 1 })" class="btn btn-primary"> Назад

Страница @ViewBag.Page

- + Вперед } -- 2.25.1