From 67def9bb1ed5617c3d8450ba443bc7ab5256acdb Mon Sep 17 00:00:00 2001 From: Stranni15k Date: Sat, 20 May 2023 22:04:30 +0300 Subject: [PATCH] =?UTF-8?q?=D0=BB=D1=807?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../DataFileSingleton.cs | 45 +- .../Implements/ImplementerStorage.cs | 7 +- .../Implements/MessageInfoStorage.cs | 57 +++ .../Models/Implementer.cs | 6 +- .../Models/Message.cs | 80 +++ PrecastConcretePlant/App.config | 11 + PrecastConcretePlant/FormMails.Designer.cs | 62 +++ PrecastConcretePlant/FormMails.cs | 47 ++ PrecastConcretePlant/FormMails.resx | 60 +++ PrecastConcretePlant/FormMain.Designer.cs | 459 +++++++++--------- PrecastConcretePlant/FormMain.cs | 409 ++++++++-------- PrecastConcretePlant/Program.cs | 28 ++ .../BusinessLogic/ClientLogic.cs | 9 + .../BusinessLogic/MessageInfoLogic.cs | 55 +++ .../BusinessLogic/OrderLogic.cs | 38 +- .../BusinessLogic/WorkModeling.cs | 2 +- .../MailWorker/AbstractMailWorker.cs | 94 ++++ .../MailWorker/MailKitWorker.cs | 78 +++ .../PrecastConcretePlantBusinessLogic.csproj | 1 + .../Controllers/HomeController.cs | 10 + .../Views/Home/Mail.cshtml | 54 +++ .../Views/Shared/_Layout.cshtml | 3 + .../BindingModels/MailConfigBindingModel.cs | 18 + .../BindingModels/MailSendInfoBindingModel.cs | 15 + .../BindingModels/MessageInfoBindingModel.cs | 19 + .../IMessageInfoLogic.cs | 18 + .../SearchModels/MessageInfoSearchModel.cs | 14 + .../StoragesContracts/IMessageInfoStorage.cs | 22 + .../ViewModels/MessageInfoViewModel.cs | 29 ++ .../Implements/ImplementerStorage.cs | 2 +- .../Implements/MessageInfoStorage.cs | 56 +++ .../20230520190255_addmessage.Designer.cs | 301 ++++++++++++ .../Migrations/20230520190255_addmessage.cs | 49 ++ ...ecastConcretePlantDatabaseModelSnapshot.cs | 44 ++ .../Models/Client.cs | 4 +- .../Models/Message.cs | 56 +++ .../PrecastConcretePlantDatabase.cs | 3 +- .../Models/IMessageInfoModel.cs | 18 + .../DataListSingleton.cs | 6 +- .../Implements/ImplementerStorage.cs | 1 + .../Implements/MessageInfoStorage.cs | 73 +++ .../Implements/OrderStorage.cs | 27 +- .../Models/Message.cs | 54 +++ .../Controllers/ClientController.cs | 30 +- .../Controllers/ImplementerController.cs | 2 +- PrecastConcretePlantRestApi/Program.cs | 18 + PrecastConcretePlantRestApi/appsettings.json | 8 +- 47 files changed, 2036 insertions(+), 466 deletions(-) create mode 100644 PrecastConcreteFileImplement/Implements/MessageInfoStorage.cs create mode 100644 PrecastConcreteFileImplement/Models/Message.cs create mode 100644 PrecastConcretePlant/App.config create mode 100644 PrecastConcretePlant/FormMails.Designer.cs create mode 100644 PrecastConcretePlant/FormMails.cs create mode 100644 PrecastConcretePlant/FormMails.resx create mode 100644 PrecastConcretePlantBusinessLogic/BusinessLogic/MessageInfoLogic.cs create mode 100644 PrecastConcretePlantBusinessLogic/MailWorker/AbstractMailWorker.cs create mode 100644 PrecastConcretePlantBusinessLogic/MailWorker/MailKitWorker.cs create mode 100644 PrecastConcretePlantClientApp/Views/Home/Mail.cshtml create mode 100644 PrecastConcretePlantContracts/BindingModels/MailConfigBindingModel.cs create mode 100644 PrecastConcretePlantContracts/BindingModels/MailSendInfoBindingModel.cs create mode 100644 PrecastConcretePlantContracts/BindingModels/MessageInfoBindingModel.cs create mode 100644 PrecastConcretePlantContracts/BusinessLogicsContracts/IMessageInfoLogic.cs create mode 100644 PrecastConcretePlantContracts/SearchModels/MessageInfoSearchModel.cs create mode 100644 PrecastConcretePlantContracts/StoragesContracts/IMessageInfoStorage.cs create mode 100644 PrecastConcretePlantContracts/ViewModels/MessageInfoViewModel.cs create mode 100644 PrecastConcretePlantDataBaseImplemet/Implements/MessageInfoStorage.cs create mode 100644 PrecastConcretePlantDataBaseImplemet/Migrations/20230520190255_addmessage.Designer.cs create mode 100644 PrecastConcretePlantDataBaseImplemet/Migrations/20230520190255_addmessage.cs create mode 100644 PrecastConcretePlantDataBaseImplemet/Models/Message.cs create mode 100644 PrecastConcretePlantDataModels/Models/IMessageInfoModel.cs create mode 100644 PrecastConcretePlantListImplement/Implements/MessageInfoStorage.cs create mode 100644 PrecastConcretePlantListImplement/Models/Message.cs diff --git a/PrecastConcreteFileImplement/DataFileSingleton.cs b/PrecastConcreteFileImplement/DataFileSingleton.cs index 0a20983..7b11160 100644 --- a/PrecastConcreteFileImplement/DataFileSingleton.cs +++ b/PrecastConcreteFileImplement/DataFileSingleton.cs @@ -1,9 +1,7 @@ -using PrecastConcretePlantFileImplement.Models; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using PrecastConcretePlantContracts.SearchModels; +using PrecastConcretePlantContracts.StoragesContracts; +using PrecastConcretePlantContracts.ViewModels; +using PrecastConcretePlantFileImplement.Models; using System.Xml.Linq; namespace PrecastConcretePlantFileImplement @@ -16,12 +14,15 @@ namespace PrecastConcretePlantFileImplement private readonly string ReinforcedFileName = "Reinforced.xml"; private readonly string ClientFileName = "Client.xml"; private readonly string ImplementerFileName = "Implementer.xml"; - public List Components { get; private set; } + private readonly string MessageFileName = "Message.xml"; + public List Components { get; private set; } public List Orders { get; private set; } public List Reinforceds { get; private set; } public List Clients { get; private set; } public List Implementers { get; private set; } - public static DataFileSingleton GetInstance() + public List Messages { get; private set; } + + public static DataFileSingleton GetInstance() { if (instance == null) { @@ -33,29 +34,25 @@ namespace PrecastConcretePlantFileImplement "Components", x => x.GetXElement); public void SaveReinforceds() => SaveData(Reinforceds, ReinforcedFileName, "Reiforceds", x => x.GetXElement); - public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x - => x.GetXElement); - public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", x - => x.GetXElement); - public void SaveImplementers() => SaveData(Implementers, OrderFileName, "Implementers", x - => x.GetXElement); - private DataFileSingleton() + public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement); + public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", x => x.GetXElement); + public void SaveImplementers() => SaveData(Implementers, ImplementerFileName, "Implementers", x => x.GetXElement); + public void SaveMessages() => SaveData(Messages, MessageFileName, "Messages", x => x.GetXElement); + + private DataFileSingleton() { - Components = LoadData(ComponentFileName, "Component", x => - Component.Create(x)!)!; - Reinforceds = LoadData(ReinforcedFileName, "Reinforced", x => - Reinforced.Create(x)!)!; + Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!; + Reinforceds = LoadData(ReinforcedFileName, "Reinforced", x => Reinforced.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)!)!; - } - private static List? LoadData(string filename, string xmlNodeName, - Func selectFunction) + Messages = LoadData(MessageFileName, "Message", x => Message.Create(x)!)!; + } + private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) { if (File.Exists(filename)) { - return - XDocument.Load(filename)?.Root?.Elements(xmlNodeName)?.Select(selectFunction)?.ToList(); + return XDocument.Load(filename)?.Root?.Elements(xmlNodeName)?.Select(selectFunction)?.ToList(); } return new List(); } diff --git a/PrecastConcreteFileImplement/Implements/ImplementerStorage.cs b/PrecastConcreteFileImplement/Implements/ImplementerStorage.cs index e16961c..cdbd921 100644 --- a/PrecastConcreteFileImplement/Implements/ImplementerStorage.cs +++ b/PrecastConcreteFileImplement/Implements/ImplementerStorage.cs @@ -1,4 +1,9 @@ -using System; +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.SearchModels; +using PrecastConcretePlantContracts.StoragesContracts; +using PrecastConcretePlantContracts.ViewModels; +using PrecastConcretePlantFileImplement.Models; +using System; using System.Collections.Generic; using System.Linq; using System.Text; diff --git a/PrecastConcreteFileImplement/Implements/MessageInfoStorage.cs b/PrecastConcreteFileImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..b9dd573 --- /dev/null +++ b/PrecastConcreteFileImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,57 @@ +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.SearchModels; +using PrecastConcretePlantContracts.StoragesContracts; +using PrecastConcretePlantContracts.ViewModels; +using PrecastConcretePlantFileImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantFileImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + private readonly DataFileSingleton source; + public MessageInfoStorage() + { + source = DataFileSingleton.GetInstance(); + } + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (model.MessageId == null) + return null; + return source.Messages.FirstOrDefault(x => x.MessageId == model.MessageId)?.GetViewModel; + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + if (!model.ClientId.HasValue) + return new(); + return source.Messages + .Where(x => x.ClientId == model.ClientId) + .Select(x => x.GetViewModel) + .ToList(); + } + + public List GetFullList() + { + return source.Messages + .Select(x => x.GetViewModel) + .ToList(); + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = Message.Create(model); + if (newMessage == null) + { + return null; + } + source.Messages.Add(newMessage); + source.SaveMessages(); + return newMessage.GetViewModel; + } + } +} diff --git a/PrecastConcreteFileImplement/Models/Implementer.cs b/PrecastConcreteFileImplement/Models/Implementer.cs index cb887cb..3cf5a75 100644 --- a/PrecastConcreteFileImplement/Models/Implementer.cs +++ b/PrecastConcreteFileImplement/Models/Implementer.cs @@ -1,8 +1,12 @@ -using System; +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.ViewModels; +using PrecastConcretePlantDataModels.Models; +using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using System.Xml.Linq; namespace PrecastConcretePlantFileImplement.Models { diff --git a/PrecastConcreteFileImplement/Models/Message.cs b/PrecastConcreteFileImplement/Models/Message.cs new file mode 100644 index 0000000..dbb7edd --- /dev/null +++ b/PrecastConcreteFileImplement/Models/Message.cs @@ -0,0 +1,80 @@ +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.ViewModels; +using PrecastConcretePlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace PrecastConcretePlantFileImplement.Models +{ + public class Message : IMessageInfoModel + { + public string MessageId { get; private set; } = string.Empty; + + public int? ClientId { get; private set; } + + public string SenderName { get; private set; } = string.Empty; + + public DateTime DateDelivery { get; private set; } = DateTime.Now; + + public string Subject { get; private set; } = string.Empty; + + public string Body { get; private set; } = string.Empty; + + public static Message? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Subject = model.Subject, + DateDelivery = model.DateDelivery, + SenderName = model.SenderName, + ClientId = model.ClientId, + MessageId = model.MessageId + }; + } + + public static Message? Create(XElement element) + { + if (element == null) + { + return null; + } + return new() + { + Body = element.Attribute("Body")!.Value, + Subject = element.Attribute("Subject")!.Value, + DateDelivery = Convert.ToDateTime(element.Attribute("DateDelivery")!.Value), + SenderName = element.Attribute("SenderName")!.Value, + ClientId = Convert.ToInt32(element.Attribute("ClientId")!.Value), + MessageId = element.Attribute("MessageId")!.Value, + }; + } + + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Subject = Subject, + DateDelivery = DateDelivery, + SenderName = SenderName, + ClientId = ClientId, + MessageId = MessageId + }; + + public XElement GetXElement => new("MessageInfo", + new XAttribute("Subject", Subject), + new XAttribute("Body", Body), + new XAttribute("ClientId", ClientId), + new XAttribute("MessageId", MessageId), + new XAttribute("SenderName", SenderName), + new XAttribute("DateDelivery", DateDelivery) + ); + } +} diff --git a/PrecastConcretePlant/App.config b/PrecastConcretePlant/App.config new file mode 100644 index 0000000..674b97d --- /dev/null +++ b/PrecastConcretePlant/App.config @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/PrecastConcretePlant/FormMails.Designer.cs b/PrecastConcretePlant/FormMails.Designer.cs new file mode 100644 index 0000000..5ff025d --- /dev/null +++ b/PrecastConcretePlant/FormMails.Designer.cs @@ -0,0 +1,62 @@ +namespace PrecastConcretePlantView +{ + partial class FormMails + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.DataGridView = new System.Windows.Forms.DataGridView(); + ((System.ComponentModel.ISupportInitialize)(this.DataGridView)).BeginInit(); + this.SuspendLayout(); + // + // DataGridView + // + this.DataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.DataGridView.Location = new System.Drawing.Point(3, 3); + this.DataGridView.Name = "DataGridView"; + this.DataGridView.RowTemplate.Height = 25; + this.DataGridView.Size = new System.Drawing.Size(794, 445); + this.DataGridView.TabIndex = 0; + // + // FormMails + // + this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 450); + this.Controls.Add(this.DataGridView); + this.Name = "FormMails"; + this.Text = "Эл. письма"; + this.Load += new System.EventHandler(this.FormMails_Load); + ((System.ComponentModel.ISupportInitialize)(this.DataGridView)).EndInit(); + this.ResumeLayout(false); + + } + + #endregion + + private DataGridView DataGridView; + } +} \ No newline at end of file diff --git a/PrecastConcretePlant/FormMails.cs b/PrecastConcretePlant/FormMails.cs new file mode 100644 index 0000000..7bf0c74 --- /dev/null +++ b/PrecastConcretePlant/FormMails.cs @@ -0,0 +1,47 @@ +using PrecastConcretePlantContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using System.Windows.Forms; + +namespace PrecastConcretePlantView +{ + public partial class FormMails : Form + { + private readonly ILogger _logger; + private readonly IMessageInfoLogic _logic; + + public FormMails(ILogger logger, IMessageInfoLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + LoadData(); + } + + private void LoadData() + { + try + { + var list = _logic.ReadList(null); + if (list != null) + { + DataGridView.DataSource = list; + DataGridView.Columns["ClientId"].Visible = false; + DataGridView.Columns["MessageId"].Visible = false; + DataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + _logger.LogInformation("Загрузка писем"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки писем"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + + private void FormMails_Load(object sender, EventArgs e) + { + LoadData(); + } + } +} diff --git a/PrecastConcretePlant/FormMails.resx b/PrecastConcretePlant/FormMails.resx new file mode 100644 index 0000000..f298a7b --- /dev/null +++ b/PrecastConcretePlant/FormMails.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/PrecastConcretePlant/FormMain.Designer.cs b/PrecastConcretePlant/FormMain.Designer.cs index c86141e..840ba22 100644 --- a/PrecastConcretePlant/FormMain.Designer.cs +++ b/PrecastConcretePlant/FormMain.Designer.cs @@ -1,233 +1,242 @@ namespace PrecastConcretePlantView { - partial class FormMain - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; + partial class FormMain + { + /// + /// 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); - } + /// + /// 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 + #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() - { - MenuStrip = new MenuStrip(); - СправочникиToolStripMenuItem = new ToolStripMenuItem(); - ИзделияToolStripMenuItem = new ToolStripMenuItem(); - КомпонентыToolStripMenuItem = new ToolStripMenuItem(); - клиентыToolStripMenuItem = new ToolStripMenuItem(); - исполнителиToolStripMenuItem = new ToolStripMenuItem(); - отчетыToolStripMenuItem = new ToolStripMenuItem(); - списокЖБИToolStripMenuItem = new ToolStripMenuItem(); - компонентыПоИзделиямToolStripMenuItem = new ToolStripMenuItem(); - списокЗаказовToolStripMenuItem = new ToolStripMenuItem(); - запускРаботToolStripMenuItem = new ToolStripMenuItem(); - DataGridView = new DataGridView(); - CreateOrderButton = new Button(); - TakeOrderInWorkButton = new Button(); - OrderReadyButton = new Button(); - IssuedOrderButton = new Button(); - UpdateListButton = new Button(); - MenuStrip.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)DataGridView).BeginInit(); - SuspendLayout(); - // - // MenuStrip - // - MenuStrip.Items.AddRange(new ToolStripItem[] { СправочникиToolStripMenuItem, отчетыToolStripMenuItem, запускРаботToolStripMenuItem }); - MenuStrip.Location = new Point(0, 0); - MenuStrip.Name = "MenuStrip"; - MenuStrip.Size = new Size(953, 24); - MenuStrip.TabIndex = 0; - MenuStrip.Text = "menuStrip1"; - // - // СправочникиToolStripMenuItem - // - СправочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { ИзделияToolStripMenuItem, КомпонентыToolStripMenuItem, клиентыToolStripMenuItem, исполнителиToolStripMenuItem }); - СправочникиToolStripMenuItem.Name = "СправочникиToolStripMenuItem"; - СправочникиToolStripMenuItem.Size = new Size(94, 20); - СправочникиToolStripMenuItem.Text = "Cправочники"; - // - // Изделия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.Name = "исполнителиToolStripMenuItem"; - исполнителиToolStripMenuItem.Size = new Size(180, 22); - исполнителиToolStripMenuItem.Text = "Исполнители"; - исполнителиToolStripMenuItem.Click += исполнителиToolStripMenuItem_Click; - // - // отчетыToolStripMenuItem - // - отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокЖБИToolStripMenuItem, компонентыПоИзделиямToolStripMenuItem, списокЗаказовToolStripMenuItem }); - отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem"; - отчетыToolStripMenuItem.Size = new Size(60, 20); - отчетыToolStripMenuItem.Text = "Отчеты"; - // - // списокЖБИToolStripMenuItem - // - списокЖБИToolStripMenuItem.Name = "списокЖБИToolStripMenuItem"; - списокЖБИToolStripMenuItem.Size = new Size(197, 22); - списокЖБИToolStripMenuItem.Text = "Список ЖБИ"; - списокЖБИToolStripMenuItem.Click += списокИзделийToolStripMenuItem_Click; - // - // компонентыПоИзделиямToolStripMenuItem - // - компонентыПоИзделиямToolStripMenuItem.Name = "компонентыПоИзделиямToolStripMenuItem"; - компонентыПоИзделиямToolStripMenuItem.Size = new Size(197, 22); - компонентыПоИзделиямToolStripMenuItem.Text = "ЖБИ по компонентам"; - компонентыПоИзделиямToolStripMenuItem.Click += компонентыПоИзделиямToolStripMenuItem_Click; - // - // списокЗаказовToolStripMenuItem - // - списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem"; - списокЗаказовToolStripMenuItem.Size = new Size(197, 22); - списокЗаказовToolStripMenuItem.Text = "Список заказов"; - списокЗаказовToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click; - // - // запускРаботToolStripMenuItem - // - запускРаботToolStripMenuItem.Name = "запускРаботToolStripMenuItem"; - запускРаботToolStripMenuItem.Size = new Size(92, 20); - запускРаботToolStripMenuItem.Text = "Запуск работ"; - запускРаботToolStripMenuItem.Click += запускРаботToolStripMenuItem_Click; - // - // DataGridView - // - DataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; - DataGridView.Location = new Point(0, 27); - DataGridView.Name = "DataGridView"; - DataGridView.RowTemplate.Height = 25; - DataGridView.Size = new Size(805, 421); - DataGridView.TabIndex = 1; - // - // CreateOrderButton - // - CreateOrderButton.Location = new Point(825, 27); - CreateOrderButton.Name = "CreateOrderButton"; - CreateOrderButton.Size = new Size(104, 33); - CreateOrderButton.TabIndex = 2; - CreateOrderButton.Text = "Создать заказ"; - CreateOrderButton.UseVisualStyleBackColor = true; - CreateOrderButton.Click += CreateOrderButton_Click; - // - // TakeOrderInWorkButton - // - TakeOrderInWorkButton.Location = new Point(825, 66); - TakeOrderInWorkButton.Name = "TakeOrderInWorkButton"; - TakeOrderInWorkButton.Size = new Size(104, 39); - TakeOrderInWorkButton.TabIndex = 3; - TakeOrderInWorkButton.Text = "Отдать на выполнение"; - TakeOrderInWorkButton.UseVisualStyleBackColor = true; - TakeOrderInWorkButton.Click += TakeOrderInWorkButton_Click; - // - // OrderReadyButton - // - OrderReadyButton.Location = new Point(825, 111); - OrderReadyButton.Name = "OrderReadyButton"; - OrderReadyButton.Size = new Size(104, 33); - OrderReadyButton.TabIndex = 4; - OrderReadyButton.Text = "Заказ готов"; - OrderReadyButton.UseVisualStyleBackColor = true; - OrderReadyButton.Click += OrderReadyButton_Click; - // - // IssuedOrderButton - // - IssuedOrderButton.Location = new Point(825, 150); - IssuedOrderButton.Name = "IssuedOrderButton"; - IssuedOrderButton.Size = new Size(104, 33); - IssuedOrderButton.TabIndex = 5; - IssuedOrderButton.Text = "Заказ выдан"; - IssuedOrderButton.UseVisualStyleBackColor = true; - IssuedOrderButton.Click += IssuedOrderButton_Click; - // - // UpdateListButton - // - UpdateListButton.Location = new Point(825, 189); - UpdateListButton.Name = "UpdateListButton"; - UpdateListButton.Size = new Size(104, 33); - UpdateListButton.TabIndex = 6; - UpdateListButton.Text = "Обновить список"; - UpdateListButton.UseVisualStyleBackColor = true; - UpdateListButton.Click += UpdateListButton_Click; - // - // FormMain - // - AutoScaleDimensions = new SizeF(7F, 15F); - AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(953, 450); - Controls.Add(UpdateListButton); - Controls.Add(IssuedOrderButton); - Controls.Add(OrderReadyButton); - Controls.Add(TakeOrderInWorkButton); - Controls.Add(CreateOrderButton); - Controls.Add(DataGridView); - Controls.Add(MenuStrip); - MainMenuStrip = MenuStrip; - Name = "FormMain"; - Text = "Завод ЖБИ"; - Load += FormMain_Load; - MenuStrip.ResumeLayout(false); - MenuStrip.PerformLayout(); - ((System.ComponentModel.ISupportInitialize)DataGridView).EndInit(); - ResumeLayout(false); - PerformLayout(); - } + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + MenuStrip = new MenuStrip(); + СправочникиToolStripMenuItem = new ToolStripMenuItem(); + ИзделияToolStripMenuItem = new ToolStripMenuItem(); + КомпонентыToolStripMenuItem = new ToolStripMenuItem(); + клиентыToolStripMenuItem = new ToolStripMenuItem(); + исполнителиToolStripMenuItem = new ToolStripMenuItem(); + отчетыToolStripMenuItem = new ToolStripMenuItem(); + списокЖБИToolStripMenuItem = new ToolStripMenuItem(); + компонентыПоИзделиямToolStripMenuItem = new ToolStripMenuItem(); + списокЗаказовToolStripMenuItem = new ToolStripMenuItem(); + запускРаботToolStripMenuItem = new ToolStripMenuItem(); + элписьмаToolStripMenuItem = new ToolStripMenuItem(); + DataGridView = new DataGridView(); + CreateOrderButton = new Button(); + TakeOrderInWorkButton = new Button(); + OrderReadyButton = new Button(); + IssuedOrderButton = new Button(); + UpdateListButton = new Button(); + MenuStrip.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)DataGridView).BeginInit(); + SuspendLayout(); + // + // MenuStrip + // + MenuStrip.Items.AddRange(new ToolStripItem[] { СправочникиToolStripMenuItem, отчетыToolStripMenuItem, запускРаботToolStripMenuItem, элписьмаToolStripMenuItem }); + MenuStrip.Location = new Point(0, 0); + MenuStrip.Name = "MenuStrip"; + MenuStrip.Size = new Size(953, 24); + MenuStrip.TabIndex = 0; + MenuStrip.Text = "menuStrip1"; + // + // СправочникиToolStripMenuItem + // + СправочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { ИзделияToolStripMenuItem, КомпонентыToolStripMenuItem, клиентыToolStripMenuItem, исполнителиToolStripMenuItem }); + СправочникиToolStripMenuItem.Name = "СправочникиToolStripMenuItem"; + СправочникиToolStripMenuItem.Size = new Size(94, 20); + СправочникиToolStripMenuItem.Text = "Cправочники"; + // + // Изделия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[] { списокЖБИToolStripMenuItem, компонентыПоИзделиямToolStripMenuItem, списокЗаказовToolStripMenuItem }); + отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem"; + отчетыToolStripMenuItem.Size = new Size(60, 20); + отчетыToolStripMenuItem.Text = "Отчеты"; + // + // списокЖБИToolStripMenuItem + // + списокЖБИToolStripMenuItem.Name = "списокЖБИToolStripMenuItem"; + списокЖБИToolStripMenuItem.Size = new Size(197, 22); + списокЖБИToolStripMenuItem.Text = "Список ЖБИ"; + списокЖБИToolStripMenuItem.Click += списокИзделийToolStripMenuItem_Click; + // + // компонентыПоИзделиямToolStripMenuItem + // + компонентыПоИзделиямToolStripMenuItem.Name = "компонентыПоИзделиямToolStripMenuItem"; + компонентыПоИзделиямToolStripMenuItem.Size = new Size(197, 22); + компонентыПоИзделиямToolStripMenuItem.Text = "ЖБИ по компонентам"; + компонентыПоИзделиямToolStripMenuItem.Click += компонентыПоИзделиямToolStripMenuItem_Click; + // + // списокЗаказовToolStripMenuItem + // + списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem"; + списокЗаказовToolStripMenuItem.Size = new Size(197, 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(62, 20); + элписьмаToolStripMenuItem.Text = "Письма"; + элписьмаToolStripMenuItem.Click += элписьмаToolStripMenuItem_Click_1; + // + // DataGridView + // + DataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + DataGridView.Location = new Point(0, 27); + DataGridView.Name = "DataGridView"; + DataGridView.RowTemplate.Height = 25; + DataGridView.Size = new Size(805, 421); + DataGridView.TabIndex = 1; + // + // CreateOrderButton + // + CreateOrderButton.Location = new Point(825, 27); + CreateOrderButton.Name = "CreateOrderButton"; + CreateOrderButton.Size = new Size(104, 33); + CreateOrderButton.TabIndex = 2; + CreateOrderButton.Text = "Создать заказ"; + CreateOrderButton.UseVisualStyleBackColor = true; + CreateOrderButton.Click += CreateOrderButton_Click; + // + // TakeOrderInWorkButton + // + TakeOrderInWorkButton.Location = new Point(825, 66); + TakeOrderInWorkButton.Name = "TakeOrderInWorkButton"; + TakeOrderInWorkButton.Size = new Size(104, 39); + TakeOrderInWorkButton.TabIndex = 3; + TakeOrderInWorkButton.Text = "Отдать на выполнение"; + TakeOrderInWorkButton.UseVisualStyleBackColor = true; + TakeOrderInWorkButton.Click += TakeOrderInWorkButton_Click; + // + // OrderReadyButton + // + OrderReadyButton.Location = new Point(825, 111); + OrderReadyButton.Name = "OrderReadyButton"; + OrderReadyButton.Size = new Size(104, 33); + OrderReadyButton.TabIndex = 4; + OrderReadyButton.Text = "Заказ готов"; + OrderReadyButton.UseVisualStyleBackColor = true; + OrderReadyButton.Click += OrderReadyButton_Click; + // + // IssuedOrderButton + // + IssuedOrderButton.Location = new Point(825, 150); + IssuedOrderButton.Name = "IssuedOrderButton"; + IssuedOrderButton.Size = new Size(104, 33); + IssuedOrderButton.TabIndex = 5; + IssuedOrderButton.Text = "Заказ выдан"; + IssuedOrderButton.UseVisualStyleBackColor = true; + IssuedOrderButton.Click += IssuedOrderButton_Click; + // + // UpdateListButton + // + UpdateListButton.Location = new Point(825, 189); + UpdateListButton.Name = "UpdateListButton"; + UpdateListButton.Size = new Size(104, 33); + UpdateListButton.TabIndex = 6; + UpdateListButton.Text = "Обновить список"; + UpdateListButton.UseVisualStyleBackColor = true; + UpdateListButton.Click += UpdateListButton_Click; + // + // FormMain + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(953, 450); + Controls.Add(UpdateListButton); + Controls.Add(IssuedOrderButton); + Controls.Add(OrderReadyButton); + Controls.Add(TakeOrderInWorkButton); + Controls.Add(CreateOrderButton); + Controls.Add(DataGridView); + Controls.Add(MenuStrip); + MainMenuStrip = MenuStrip; + Name = "FormMain"; + Text = "Завод ЖБИ"; + Load += FormMain_Load; + MenuStrip.ResumeLayout(false); + MenuStrip.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)DataGridView).EndInit(); + ResumeLayout(false); + PerformLayout(); + } - #endregion + #endregion - private MenuStrip MenuStrip; - private ToolStripMenuItem СправочникиToolStripMenuItem; - private ToolStripMenuItem ИзделияToolStripMenuItem; - private ToolStripMenuItem КомпонентыToolStripMenuItem; - private DataGridView DataGridView; - private Button CreateOrderButton; - private Button TakeOrderInWorkButton; - private Button OrderReadyButton; - private Button IssuedOrderButton; - private Button UpdateListButton; - private ToolStripMenuItem отчетыToolStripMenuItem; - private ToolStripMenuItem списокЖБИToolStripMenuItem; - private ToolStripMenuItem компонентыПоИзделиямToolStripMenuItem; - private ToolStripMenuItem списокЗаказовToolStripMenuItem; - private ToolStripMenuItem клиентыToolStripMenuItem; - private ToolStripMenuItem исполнителиToolStripMenuItem; - private ToolStripMenuItem запускРаботToolStripMenuItem; - } + private MenuStrip MenuStrip; + private ToolStripMenuItem СправочникиToolStripMenuItem; + private ToolStripMenuItem ИзделияToolStripMenuItem; + private ToolStripMenuItem КомпонентыToolStripMenuItem; + private DataGridView DataGridView; + private Button CreateOrderButton; + private Button TakeOrderInWorkButton; + private Button OrderReadyButton; + private Button IssuedOrderButton; + private Button UpdateListButton; + private ToolStripMenuItem отчетыToolStripMenuItem; + private ToolStripMenuItem списокЖБИToolStripMenuItem; + private ToolStripMenuItem компонентыПоИзделиямToolStripMenuItem; + private ToolStripMenuItem списокЗаказовToolStripMenuItem; + private ToolStripMenuItem клиентыToolStripMenuItem; + private ToolStripMenuItem исполнителиToolStripMenuItem; + private ToolStripMenuItem запускРаботToolStripMenuItem; + private ToolStripMenuItem элписьмаToolStripMenuItem; + } } \ No newline at end of file diff --git a/PrecastConcretePlant/FormMain.cs b/PrecastConcretePlant/FormMain.cs index 4210dbb..b8d1dc3 100644 --- a/PrecastConcretePlant/FormMain.cs +++ b/PrecastConcretePlant/FormMain.cs @@ -4,6 +4,7 @@ using PrecastConcretePlantBusinessLogic.BusinessLogic; using PrecastConcretePlantContracts.BindingModels; using PrecastConcretePlantContracts.BusinessLogicsContracts; using PrecastConcretePlantDataModels.Enums; +using PrecastConcretePlantView; using System; using System.Collections.Generic; using System.ComponentModel; @@ -16,230 +17,248 @@ using System.Windows.Forms; namespace PrecastConcretePlantView { - public partial class FormMain : Form - { + public partial class FormMain : Form + { - private readonly ILogger _logger; - private readonly IOrderLogic _orderLogic; - private readonly IReportLogic _reportLogic; - private readonly IWorkProcess _workProcess; + private readonly ILogger _logger; + private readonly IOrderLogic _orderLogic; + private readonly IReportLogic _reportLogic; + 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 LoadData() - { - _logger.LogInformation("Загрузка заказов"); + private void LoadData() + { + _logger.LogInformation("Загрузка заказов"); - try - { - var list = _orderLogic.ReadList(null); + try + { + var list = _orderLogic.ReadList(null); - if (list != null) - { - DataGridView.DataSource = list; - DataGridView.Columns["ReinforcedId"].Visible = false; - DataGridView.Columns["ClientId"].Visible = false; - DataGridView.Columns["ImplementerId"].Visible = false; - DataGridView.Columns["DateImplement"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } + if (list != null) + { + DataGridView.DataSource = list; + DataGridView.Columns["ReinforcedId"].Visible = false; + DataGridView.Columns["ClientId"].Visible = false; + DataGridView.Columns["ImplementerId"].Visible = false; + DataGridView.Columns["DateImplement"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } - _logger.LogInformation("Загрузка заказов"); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки заказов"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } + _logger.LogInformation("Загрузка заказов"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки заказов"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } - private void КомпонентыToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormComponents)); + private void КомпонентыToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormComponents)); - if (service is FormComponents form) - { - form.ShowDialog(); - } - } + if (service is FormComponents form) + { + form.ShowDialog(); + } + } - private void ИзделияToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormReinforceds)); + private void ИзделияToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReinforceds)); - if (service is FormReinforceds form) - { - form.ShowDialog(); - } - } + if (service is FormReinforceds form) + { + form.ShowDialog(); + } + } - private void CreateOrderButton_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); + private void CreateOrderButton_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); - if (service is FormCreateOrder form) - { - form.ShowDialog(); - LoadData(); - } - } + if (service is FormCreateOrder form) + { + form.ShowDialog(); + LoadData(); + } + } - private void TakeOrderInWorkButton_Click(object sender, EventArgs e) - { - if (DataGridView.SelectedRows.Count == 1) - { - int id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id); + private void TakeOrderInWorkButton_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.TakeOrderInWork(new OrderBindingModel - { - Id = id - }); + try + { + var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel + { + Id = id + }); - if (!operationResult) - { - throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); - } + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка передачи заказа в работу"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка передачи заказа в работу"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } - private void IssuedOrderButton_Click(object sender, EventArgs e) - { - if (DataGridView.SelectedRows.Count == 1) - { - int id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id); + private void IssuedOrderButton_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 - }); + 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); - } - } - } + 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 OrderReadyButton_Click(object sender, EventArgs e) - { - if (DataGridView.SelectedRows.Count == 1) - { - int id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'", id); + private void OrderReadyButton_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.DeliveryOrder(new OrderBindingModel - { - Id = id - }); + try + { + var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel + { + Id = id + }); - if (!operationResult) - { - throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); - } + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } - _logger.LogInformation("Заказ №{id} готов", id); - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка отметки о готовности заказа"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } + _logger.LogInformation("Заказ №{id} готов", id); + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка отметки о готовности заказа"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } - private void UpdateListButton_Click(object sender, EventArgs e) - { - LoadData(); - } + private void UpdateListButton_Click(object sender, EventArgs e) + { + LoadData(); + } - private void списокИзделийToolStripMenuItem_Click(object sender, EventArgs e) - { - using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; - if (dialog.ShowDialog() == DialogResult.OK) - { - _reportLogic.SaveReinforcedsToWordFile(new ReportBindingModel { FileName = dialog.FileName }); - MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); - } - } + private void списокИзделийToolStripMenuItem_Click(object sender, EventArgs e) + { + using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; + if (dialog.ShowDialog() == DialogResult.OK) + { + _reportLogic.SaveReinforcedsToWordFile(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(FormReportReinforcedComponents)); - if (service is FormReportReinforcedComponents form) - { - form.ShowDialog(); - } - } + private void компонентыПоИзделиямToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReportReinforcedComponents)); + if (service is FormReportReinforcedComponents 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) - { - 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) - { - _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 исполнители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 элПисьмаToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormMails)); + if (service is FormMails form) + { + form.ShowDialog(); + } + } + + private void элписьмаToolStripMenuItem_Click_1(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormMails)); + if (service is FormMails form) + { + form.ShowDialog(); + } + } + } } diff --git a/PrecastConcretePlant/Program.cs b/PrecastConcretePlant/Program.cs index 8f6683e..5e9cab1 100644 --- a/PrecastConcretePlant/Program.cs +++ b/PrecastConcretePlant/Program.cs @@ -10,6 +10,8 @@ using NLog.Extensions.Logging; using System; using PrecastConcretePlantBusinessLogic.BusinessLogics; using PrecastConcretePlantView; +using PrecastConcretePlantBusinessLogic.MailWorker; +using PrecastConcretePlantContracts.BindingModels; namespace PrecastConcretePlant { @@ -25,6 +27,26 @@ namespace PrecastConcretePlant var services = new ServiceCollection(); ConfigureServices(services); _serviceProvider = services.BuildServiceProvider(); + try + { + var mailSender = _serviceProvider.GetService(); + mailSender?.MailConfig(new MailConfigBindingModel + { + MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty, + MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty, + SmtpClientHost = System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty, + SmtpClientPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]), + PopHost = System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty, + PopPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"]) + }); + + var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000); + } + catch (Exception ex) + { + var logger = _serviceProvider.GetService(); + logger?.LogError(ex, "Error"); + } Application.Run(_serviceProvider.GetRequiredService()); } @@ -43,6 +65,8 @@ namespace PrecastConcretePlant services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -50,7 +74,9 @@ namespace PrecastConcretePlant services.AddTransient(); services.AddTransient(); + services.AddSingleton(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -65,5 +91,7 @@ namespace PrecastConcretePlant services.AddTransient(); services.AddTransient(); } + + private static void MailCheck(object obj) => ServiceProvider?.GetService()?.MailCheck(); } } \ No newline at end of file diff --git a/PrecastConcretePlantBusinessLogic/BusinessLogic/ClientLogic.cs b/PrecastConcretePlantBusinessLogic/BusinessLogic/ClientLogic.cs index 0f678f5..e119bba 100644 --- a/PrecastConcretePlantBusinessLogic/BusinessLogic/ClientLogic.cs +++ b/PrecastConcretePlantBusinessLogic/BusinessLogic/ClientLogic.cs @@ -8,6 +8,7 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; +using System.Text.RegularExpressions; using System.Threading.Tasks; namespace PrecastConcretePlantBusinessLogic.BusinessLogic @@ -109,6 +110,14 @@ namespace PrecastConcretePlantBusinessLogic.BusinessLogic { throw new ArgumentNullException("Нет пароля учетной записи клиента", nameof(model.ClientFIO)); } + if (!Regex.IsMatch(model.Email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$", RegexOptions.IgnoreCase)) + { + throw new ArgumentException("Неправильно введенный email", nameof(model.Email)); + } + if (!Regex.IsMatch(model.Password, @"^^((\w+\d+\W+)|(\w+\W+\d+)|(\d+\w+\W+)|(\d+\W+\w+)|(\W+\w+\d+)|(\W+\d+\w+))[\w\d\W]*$", RegexOptions.IgnoreCase)) + { + throw new ArgumentException("Неправильно введенный пароль", nameof(model.Password)); + } _logger.LogInformation("Client. ClientFIO:{ClientFIO}. Email:{Email}. Password:{Password}. Id:{Id}", model.ClientFIO, model.Email, model.Password, model.Id); var element = _clientStorage.GetElement(new ClientSearchModel { diff --git a/PrecastConcretePlantBusinessLogic/BusinessLogic/MessageInfoLogic.cs b/PrecastConcretePlantBusinessLogic/BusinessLogic/MessageInfoLogic.cs new file mode 100644 index 0000000..4fb8d59 --- /dev/null +++ b/PrecastConcretePlantBusinessLogic/BusinessLogic/MessageInfoLogic.cs @@ -0,0 +1,55 @@ +using Microsoft.Extensions.Logging; +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.BusinessLogicsContracts; +using PrecastConcretePlantContracts.SearchModels; +using PrecastConcretePlantContracts.StoragesContracts; +using PrecastConcretePlantContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantBusinessLogic.BusinessLogic +{ + public class MessageInfoLogic : IMessageInfoLogic + { + private readonly ILogger _logger; + private readonly IMessageInfoStorage _messageStorage; + + public MessageInfoLogic(ILogger logger, IMessageInfoStorage messageStorage) + { + _logger = logger; + _messageStorage = messageStorage; + } + + public bool Create(MessageInfoBindingModel model) + { + if (_messageStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + + return false; + } + + return true; + } + + public List? ReadList(MessageInfoSearchModel? model) + { + _logger.LogInformation("ReadList. MessageId:{MessageId}.ClientId:{ClientId} ", model?.MessageId, model?.ClientId); + var list = model == null ? _messageStorage.GetFullList() : _messageStorage.GetFilteredList(model); + + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + + return null; + } + + _logger.LogInformation("ReadList. Count: {Count}", list.Count); + + return list; + } + } +} diff --git a/PrecastConcretePlantBusinessLogic/BusinessLogic/OrderLogic.cs b/PrecastConcretePlantBusinessLogic/BusinessLogic/OrderLogic.cs index d415da2..56e39df 100644 --- a/PrecastConcretePlantBusinessLogic/BusinessLogic/OrderLogic.cs +++ b/PrecastConcretePlantBusinessLogic/BusinessLogic/OrderLogic.cs @@ -1,4 +1,5 @@ using Microsoft.Extensions.Logging; +using PrecastConcretePlantBusinessLogic.MailWorker; using PrecastConcretePlantContracts.BindingModels; using PrecastConcretePlantContracts.BusinessLogicsContracts; using PrecastConcretePlantContracts.SearchModels; @@ -17,11 +18,15 @@ namespace PrecastConcretePlantBusinessLogic.BusinessLogic { private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; + private readonly AbstractMailWorker _mailWorker; + private readonly IClientLogic _clientLogic; - public OrderLogic(ILogger logger, IOrderStorage orderStorage) + public OrderLogic(ILogger logger, IOrderStorage orderStorage, AbstractMailWorker mailWorker, IClientLogic clientLogic) { _logger = logger; _orderStorage = orderStorage; + _mailWorker = mailWorker; + _clientLogic = clientLogic; } public bool CreateOrder(OrderBindingModel model) @@ -35,14 +40,17 @@ namespace PrecastConcretePlantBusinessLogic.BusinessLogic } model.Status = OrderStatus.Принят; + var result = _orderStorage.Insert(model); - if (_orderStorage.Insert(model) == null) + if (result == null) { model.Status = OrderStatus.Неизвестен; _logger.LogWarning("Insert operation failed"); return false; } + SendOrderMessage(result.ClientId, $"Производство ЖБИ, Заказ №{result.Id}", $"Заказ №{result.Id} от {result.DateCreate} на сумму {result.Sum:0.00} принят"); + return true; } @@ -63,6 +71,25 @@ namespace PrecastConcretePlantBusinessLogic.BusinessLogic return element; } + private bool SendOrderMessage(int clientId, string subject, string text) + { + var client = _clientLogic.ReadElement(new() { Id = clientId }); + + if (client == null) + { + return false; + } + + _mailWorker.MailSendAsync(new() + { + MailAddress = client.Email, + Subject = subject, + Text = text + }); + + return true; + } + private bool StatusUpdate(OrderBindingModel model, OrderStatus newStatus) { var viewModel = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id }); @@ -89,11 +116,15 @@ namespace PrecastConcretePlantBusinessLogic.BusinessLogic model.ImplementerId = viewModel.ImplementerId.Value; } CheckModel(model, false); - if (_orderStorage.Update(model) == null) + var result = _orderStorage.Update(model); + + if (result == null) { _logger.LogWarning("Change status operation failed"); return false; } + + SendOrderMessage(result.ClientId, $"Производство ЖБИ, Заказ №{result.Id}", $"Заказ №{model.Id} изменен статус на {result.Status}"); return true; } @@ -111,6 +142,7 @@ namespace PrecastConcretePlantBusinessLogic.BusinessLogic model.DateImplement=DateTime.Now; return StatusUpdate(model, OrderStatus.Выдан); } + public List? ReadList(OrderSearchModel? model) { _logger.LogInformation("Order. OrderId:{Id}", model?.Id); diff --git a/PrecastConcretePlantBusinessLogic/BusinessLogic/WorkModeling.cs b/PrecastConcretePlantBusinessLogic/BusinessLogic/WorkModeling.cs index ed20a97..a6cc406 100644 --- a/PrecastConcretePlantBusinessLogic/BusinessLogic/WorkModeling.cs +++ b/PrecastConcretePlantBusinessLogic/BusinessLogic/WorkModeling.cs @@ -36,7 +36,7 @@ namespace PrecastConcretePlantBusinessLogic.BusinessLogic return; } - var orders = _orderLogic.ReadList(new OrderSearchModel { Status = new() { OrderStatus.Принят, OrderStatus.Выполняется } }); + var orders = _orderLogic.ReadList(new OrderSearchModel { Statuses = new() { OrderStatus.Принят, OrderStatus.Выполняется } }); if (orders == null || orders.Count == 0) { _logger.LogWarning("DoWork. Orders is null or empty"); diff --git a/PrecastConcretePlantBusinessLogic/MailWorker/AbstractMailWorker.cs b/PrecastConcretePlantBusinessLogic/MailWorker/AbstractMailWorker.cs new file mode 100644 index 0000000..9157d22 --- /dev/null +++ b/PrecastConcretePlantBusinessLogic/MailWorker/AbstractMailWorker.cs @@ -0,0 +1,94 @@ +using Microsoft.Extensions.Logging; +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.BusinessLogicsContracts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantBusinessLogic.MailWorker +{ + public abstract class AbstractMailWorker + { + protected string _mailLogin = string.Empty; + protected string _mailPassword = string.Empty; + protected string _smtpClientHost = string.Empty; + protected int _smtpClientPort; + protected string _popHost = string.Empty; + protected int _popPort; + private readonly IMessageInfoLogic _messageInfoLogic; + private readonly IClientLogic _clientLogic; + private readonly ILogger _logger; + + public AbstractMailWorker(ILogger logger, IMessageInfoLogic messageInfoLogic, IClientLogic clientLogic) + { + _logger = logger; + _messageInfoLogic = messageInfoLogic; + _clientLogic = clientLogic; + } + + public void MailConfig(MailConfigBindingModel config) + { + _mailLogin = config.MailLogin; + _mailPassword = config.MailPassword; + _smtpClientHost = config.SmtpClientHost; + _smtpClientPort = config.SmtpClientPort; + _popHost = config.PopHost; + _popPort = config.PopPort; + _logger.LogDebug("Config: {login}, {password}, {clientHost}, {clientPOrt}, {popHost}, {popPort}", _mailLogin, _mailPassword, _smtpClientHost, _smtpClientPort, _popHost, _popPort); + } + + public async void MailSendAsync(MailSendInfoBindingModel info) + { + if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword)) + { + return; + } + + if (string.IsNullOrEmpty(_smtpClientHost) || _smtpClientPort == 0) + { + return; + } + + if (string.IsNullOrEmpty(info.MailAddress) || string.IsNullOrEmpty(info.Subject) || string.IsNullOrEmpty(info.Text)) + { + return; + } + + _logger.LogDebug("Send Mail: {To}, {Subject}", info.MailAddress, info.Subject); + + await SendMailAsync(info); + } + + public async void MailCheck() + { + if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword)) + { + return; + } + + if (string.IsNullOrEmpty(_popHost) || _popPort == 0) + { + return; + } + + if (_messageInfoLogic == null) + { + return; + } + + var list = await ReceiveMailAsync(); + _logger.LogDebug("Check Mail: {Count} new mails", list.Count); + + foreach (var mail in list) + { + mail.ClientId = _clientLogic.ReadElement(new() { Email = mail.SenderName })?.Id; + _messageInfoLogic.Create(mail); + } + } + + protected abstract Task SendMailAsync(MailSendInfoBindingModel info); + protected abstract Task> ReceiveMailAsync(); + } +} diff --git a/PrecastConcretePlantBusinessLogic/MailWorker/MailKitWorker.cs b/PrecastConcretePlantBusinessLogic/MailWorker/MailKitWorker.cs new file mode 100644 index 0000000..7c4f198 --- /dev/null +++ b/PrecastConcretePlantBusinessLogic/MailWorker/MailKitWorker.cs @@ -0,0 +1,78 @@ +using Microsoft.Extensions.Logging; +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.BusinessLogicsContracts; +using System.Net.Mail; +using System.Net; +using System.Text; +using MailKit.Net.Pop3; +using MailKit.Security; + +namespace PrecastConcretePlantBusinessLogic.MailWorker +{ + public class MailKitWorker : AbstractMailWorker + { + public MailKitWorker(ILogger logger, IMessageInfoLogic messageInfoLogic, IClientLogic clientLogic) : base(logger, messageInfoLogic, clientLogic) { } + + protected override async Task SendMailAsync(MailSendInfoBindingModel info) + { + using var objMailMessage = new MailMessage(); + using var objSmtpClient = new SmtpClient(_smtpClientHost, _smtpClientPort); + + try + { + objMailMessage.From = new MailAddress(_mailLogin); + objMailMessage.To.Add(new MailAddress(info.MailAddress)); + objMailMessage.Subject = info.Subject; + objMailMessage.Body = info.Text; + objMailMessage.SubjectEncoding = Encoding.UTF8; + objMailMessage.BodyEncoding = Encoding.UTF8; + objSmtpClient.UseDefaultCredentials = false; + objSmtpClient.EnableSsl = true; + objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; + objSmtpClient.Credentials = new NetworkCredential(_mailLogin, _mailPassword); + + await Task.Run(() => objSmtpClient.Send(objMailMessage)); + } + catch (Exception) + { + throw; + } + } + + protected override async Task> ReceiveMailAsync() + { + var list = new List(); + using var client = new Pop3Client(); + await Task.Run(() => + { + try + { + client.Connect(_popHost, _popPort, SecureSocketOptions.SslOnConnect); + client.Authenticate(_mailLogin, _mailPassword); + for (int i = 0; i < client.Count; i++) + { + var message = client.GetMessage(i); + foreach (var mail in message.From.Mailboxes) + { + list.Add(new MessageInfoBindingModel + { + DateDelivery = message.Date.DateTime, + MessageId = message.MessageId, + SenderName = mail.Address, + Subject = message.Subject, + Body = message.TextBody != null ? message.TextBody : message.HtmlBody + }); + } + } + } + catch (AuthenticationException) + { } + finally + { + client.Disconnect(true); + } + }); + return list; + } + } +} diff --git a/PrecastConcretePlantBusinessLogic/PrecastConcretePlantBusinessLogic.csproj b/PrecastConcretePlantBusinessLogic/PrecastConcretePlantBusinessLogic.csproj index 2d3f0cc..f640431 100644 --- a/PrecastConcretePlantBusinessLogic/PrecastConcretePlantBusinessLogic.csproj +++ b/PrecastConcretePlantBusinessLogic/PrecastConcretePlantBusinessLogic.csproj @@ -8,6 +8,7 @@ + diff --git a/PrecastConcretePlantClientApp/Controllers/HomeController.cs b/PrecastConcretePlantClientApp/Controllers/HomeController.cs index 646cd8a..31e3703 100644 --- a/PrecastConcretePlantClientApp/Controllers/HomeController.cs +++ b/PrecastConcretePlantClientApp/Controllers/HomeController.cs @@ -143,5 +143,15 @@ namespace PrecastConcretePlantClientApp.Controllers var trav = APIClient.GetRequest($"api/main/getReinforced?ReinforcedId={Reinforced}"); return count * (trav?.Price ?? 1); } + + [HttpGet] + public IActionResult Mails() + { + if (APIClient.Client == null) + { + return Redirect("~/Home/Enter"); + } + return View(APIClient.GetRequest>($"api/client/getmessages?clientId={APIClient.Client.Id}")); + } } } \ No newline at end of file diff --git a/PrecastConcretePlantClientApp/Views/Home/Mail.cshtml b/PrecastConcretePlantClientApp/Views/Home/Mail.cshtml new file mode 100644 index 0000000..20b9b6d --- /dev/null +++ b/PrecastConcretePlantClientApp/Views/Home/Mail.cshtml @@ -0,0 +1,54 @@ +@using PrecastConcretePlantContracts.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/PrecastConcretePlantClientApp/Views/Shared/_Layout.cshtml b/PrecastConcretePlantClientApp/Views/Shared/_Layout.cshtml index 08a5d37..f473f48 100644 --- a/PrecastConcretePlantClientApp/Views/Shared/_Layout.cshtml +++ b/PrecastConcretePlantClientApp/Views/Shared/_Layout.cshtml @@ -31,6 +31,9 @@ + diff --git a/PrecastConcretePlantContracts/BindingModels/MailConfigBindingModel.cs b/PrecastConcretePlantContracts/BindingModels/MailConfigBindingModel.cs new file mode 100644 index 0000000..b5635eb --- /dev/null +++ b/PrecastConcretePlantContracts/BindingModels/MailConfigBindingModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantContracts.BindingModels +{ + public class MailConfigBindingModel + { + public string MailLogin { get; set; } = string.Empty; + public string MailPassword { get; set; } = string.Empty; + public string SmtpClientHost { get; set; } = string.Empty; + public int SmtpClientPort { get; set; } + public string PopHost { get; set; } = string.Empty; + public int PopPort { get; set; } + } +} diff --git a/PrecastConcretePlantContracts/BindingModels/MailSendInfoBindingModel.cs b/PrecastConcretePlantContracts/BindingModels/MailSendInfoBindingModel.cs new file mode 100644 index 0000000..a9b7b40 --- /dev/null +++ b/PrecastConcretePlantContracts/BindingModels/MailSendInfoBindingModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantContracts.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/PrecastConcretePlantContracts/BindingModels/MessageInfoBindingModel.cs b/PrecastConcretePlantContracts/BindingModels/MessageInfoBindingModel.cs new file mode 100644 index 0000000..626a3e7 --- /dev/null +++ b/PrecastConcretePlantContracts/BindingModels/MessageInfoBindingModel.cs @@ -0,0 +1,19 @@ +using PrecastConcretePlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantContracts.BindingModels +{ + public class MessageInfoBindingModel : IMessageInfoModel + { + public string MessageId { get; set; } = string.Empty; + public int? ClientId { get; set; } + public string SenderName { get; set; } = string.Empty; + public string Subject { get; set; } = string.Empty; + public string Body { get; set; } = string.Empty; + public DateTime DateDelivery { get; set; } + } +} diff --git a/PrecastConcretePlantContracts/BusinessLogicsContracts/IMessageInfoLogic.cs b/PrecastConcretePlantContracts/BusinessLogicsContracts/IMessageInfoLogic.cs new file mode 100644 index 0000000..cede0b7 --- /dev/null +++ b/PrecastConcretePlantContracts/BusinessLogicsContracts/IMessageInfoLogic.cs @@ -0,0 +1,18 @@ +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.SearchModels; +using PrecastConcretePlantContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantContracts.BusinessLogicsContracts +{ + public interface IMessageInfoLogic + { + List? ReadList(MessageInfoSearchModel? model); + + bool Create(MessageInfoBindingModel model); + } +} diff --git a/PrecastConcretePlantContracts/SearchModels/MessageInfoSearchModel.cs b/PrecastConcretePlantContracts/SearchModels/MessageInfoSearchModel.cs new file mode 100644 index 0000000..243785d --- /dev/null +++ b/PrecastConcretePlantContracts/SearchModels/MessageInfoSearchModel.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantContracts.SearchModels +{ + public class MessageInfoSearchModel + { + public int? ClientId { get; set; } + public string? MessageId { get; set; } + } +} diff --git a/PrecastConcretePlantContracts/StoragesContracts/IMessageInfoStorage.cs b/PrecastConcretePlantContracts/StoragesContracts/IMessageInfoStorage.cs new file mode 100644 index 0000000..2055547 --- /dev/null +++ b/PrecastConcretePlantContracts/StoragesContracts/IMessageInfoStorage.cs @@ -0,0 +1,22 @@ +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.SearchModels; +using PrecastConcretePlantContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantContracts.StoragesContracts +{ + public interface IMessageInfoStorage + { + List GetFullList(); + + List GetFilteredList(MessageInfoSearchModel model); + + MessageInfoViewModel? GetElement(MessageInfoSearchModel model); + + MessageInfoViewModel? Insert(MessageInfoBindingModel model); + } +} diff --git a/PrecastConcretePlantContracts/ViewModels/MessageInfoViewModel.cs b/PrecastConcretePlantContracts/ViewModels/MessageInfoViewModel.cs new file mode 100644 index 0000000..6ad403b --- /dev/null +++ b/PrecastConcretePlantContracts/ViewModels/MessageInfoViewModel.cs @@ -0,0 +1,29 @@ +using PrecastConcretePlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantContracts.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/PrecastConcretePlantDataBaseImplemet/Implements/ImplementerStorage.cs b/PrecastConcretePlantDataBaseImplemet/Implements/ImplementerStorage.cs index 7027c5d..13cf08b 100644 --- a/PrecastConcretePlantDataBaseImplemet/Implements/ImplementerStorage.cs +++ b/PrecastConcretePlantDataBaseImplemet/Implements/ImplementerStorage.cs @@ -38,7 +38,7 @@ namespace PrecastConcretePlantDatabaseImplement.Implements if (model.ImplementerFIO != null) { - using var context = new SoftwareInstallationDataBase(); + using var context = new PrecastConcretePlantDatabase(); return context.Implementers .Where(x => x.ImplementerFIO.Equals(model.ImplementerFIO)) diff --git a/PrecastConcretePlantDataBaseImplemet/Implements/MessageInfoStorage.cs b/PrecastConcretePlantDataBaseImplemet/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..93ef687 --- /dev/null +++ b/PrecastConcretePlantDataBaseImplemet/Implements/MessageInfoStorage.cs @@ -0,0 +1,56 @@ +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.SearchModels; +using PrecastConcretePlantContracts.StoragesContracts; +using PrecastConcretePlantContracts.ViewModels; +using PrecastConcretePlantDatabaseImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantDatabaseImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (model.MessageId == null) + return null; + using var context = new PrecastConcretePlantDatabase(); + return context.Messages.FirstOrDefault(x => x.MessageId == model.MessageId)?.GetViewModel; + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + if (!model.ClientId.HasValue) + return new(); + using var context = new PrecastConcretePlantDatabase(); + return context.Messages + .Where(x => x.ClientId == model.ClientId) + .Select(x => x.GetViewModel) + .ToList(); + } + + public List GetFullList() + { + using var context = new PrecastConcretePlantDatabase(); + return context.Messages + .Select(x => x.GetViewModel) + .ToList(); + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = Message.Create(model); + if (newMessage == null) + { + return null; + } + using var context = new PrecastConcretePlantDatabase(); + context.Messages.Add(newMessage); + context.SaveChanges(); + return newMessage.GetViewModel; + } + } +} diff --git a/PrecastConcretePlantDataBaseImplemet/Migrations/20230520190255_addmessage.Designer.cs b/PrecastConcretePlantDataBaseImplemet/Migrations/20230520190255_addmessage.Designer.cs new file mode 100644 index 0000000..ffc1f36 --- /dev/null +++ b/PrecastConcretePlantDataBaseImplemet/Migrations/20230520190255_addmessage.Designer.cs @@ -0,0 +1,301 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using PrecastConcretePlantDatabaseImplement; + +#nullable disable + +namespace PrecastConcretePlantDatabaseImplement.Migrations +{ + [DbContext(typeof(PrecastConcretePlantDatabase))] + [Migration("20230520190255_addmessage")] + partial class addmessage + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.4") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.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("PrecastConcretePlantDatabaseImplement.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("PrecastConcretePlantDatabaseImplement.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("PrecastConcretePlantDatabaseImplement.Models.Message", b => + { + b.Property("MessageId") + .HasColumnType("nvarchar(450)"); + + b.Property("Body") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("int"); + + b.Property("DateDelivery") + .HasColumnType("datetime2"); + + b.Property("SenderName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Subject") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("MessageId"); + + b.HasIndex("ClientId"); + + b.ToTable("Messages"); + }); + + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.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("ReinforcedId") + .HasColumnType("int"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("Sum") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.HasIndex("ImplementerId"); + + b.HasIndex("ReinforcedId"); + + b.ToTable("Orders"); + }); + + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Reinforced", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Price") + .HasColumnType("float"); + + b.Property("ReinforcedName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Reinforceds"); + }); + + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.ReinforcedComponent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ComponentId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("ReinforcedId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ComponentId"); + + b.HasIndex("ReinforcedId"); + + b.ToTable("ReinforcedComponents"); + }); + + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Message", b => + { + b.HasOne("PrecastConcretePlantDatabaseImplement.Models.Client", "Client") + .WithMany("Messages") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Client"); + }); + + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Order", b => + { + b.HasOne("PrecastConcretePlantDatabaseImplement.Models.Client", "Client") + .WithMany("Orders") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("PrecastConcretePlantDatabaseImplement.Models.Implementer", "Implementer") + .WithMany("Orders") + .HasForeignKey("ImplementerId"); + + b.HasOne("PrecastConcretePlantDatabaseImplement.Models.Reinforced", "Reinforced") + .WithMany("Orders") + .HasForeignKey("ReinforcedId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Client"); + + b.Navigation("Implementer"); + + b.Navigation("Reinforced"); + }); + + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.ReinforcedComponent", b => + { + b.HasOne("PrecastConcretePlantDatabaseImplement.Models.Component", "Component") + .WithMany("ReinforcedComponents") + .HasForeignKey("ComponentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("PrecastConcretePlantDatabaseImplement.Models.Reinforced", "Reinforced") + .WithMany("Components") + .HasForeignKey("ReinforcedId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Component"); + + b.Navigation("Reinforced"); + }); + + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Client", b => + { + b.Navigation("Messages"); + + b.Navigation("Orders"); + }); + + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Component", b => + { + b.Navigation("ReinforcedComponents"); + }); + + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Implementer", b => + { + b.Navigation("Orders"); + }); + + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Reinforced", b => + { + b.Navigation("Components"); + + b.Navigation("Orders"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/PrecastConcretePlantDataBaseImplemet/Migrations/20230520190255_addmessage.cs b/PrecastConcretePlantDataBaseImplemet/Migrations/20230520190255_addmessage.cs new file mode 100644 index 0000000..f0d7a72 --- /dev/null +++ b/PrecastConcretePlantDataBaseImplemet/Migrations/20230520190255_addmessage.cs @@ -0,0 +1,49 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace PrecastConcretePlantDatabaseImplement.Migrations +{ + /// + public partial class addmessage : 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: false), + SenderName = table.Column(type: "nvarchar(max)", nullable: false), + DateDelivery = table.Column(type: "datetime2", nullable: false), + Subject = table.Column(type: "nvarchar(max)", nullable: false), + Body = table.Column(type: "nvarchar(max)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Messages", x => x.MessageId); + table.ForeignKey( + name: "FK_Messages_Clients_ClientId", + column: x => x.ClientId, + principalTable: "Clients", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_Messages_ClientId", + table: "Messages", + column: "ClientId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Messages"); + } + } +} diff --git a/PrecastConcretePlantDataBaseImplemet/Migrations/PrecastConcretePlantDatabaseModelSnapshot.cs b/PrecastConcretePlantDataBaseImplemet/Migrations/PrecastConcretePlantDatabaseModelSnapshot.cs index d08d6bf..6d2bbcc 100644 --- a/PrecastConcretePlantDataBaseImplemet/Migrations/PrecastConcretePlantDatabaseModelSnapshot.cs +++ b/PrecastConcretePlantDataBaseImplemet/Migrations/PrecastConcretePlantDatabaseModelSnapshot.cs @@ -94,6 +94,37 @@ namespace PrecastConcretePlantDatabaseImplement.Migrations b.ToTable("Implementers"); }); + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Message", b => + { + b.Property("MessageId") + .HasColumnType("nvarchar(450)"); + + b.Property("Body") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("int"); + + b.Property("DateDelivery") + .HasColumnType("datetime2"); + + b.Property("SenderName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Subject") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("MessageId"); + + b.HasIndex("ClientId"); + + b.ToTable("Messages"); + }); + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -183,6 +214,17 @@ namespace PrecastConcretePlantDatabaseImplement.Migrations b.ToTable("ReinforcedComponents"); }); + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Message", b => + { + b.HasOne("PrecastConcretePlantDatabaseImplement.Models.Client", "Client") + .WithMany("Messages") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Client"); + }); + modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Order", b => { b.HasOne("PrecastConcretePlantDatabaseImplement.Models.Client", "Client") @@ -229,6 +271,8 @@ namespace PrecastConcretePlantDatabaseImplement.Migrations modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Client", b => { + b.Navigation("Messages"); + b.Navigation("Orders"); }); diff --git a/PrecastConcretePlantDataBaseImplemet/Models/Client.cs b/PrecastConcretePlantDataBaseImplemet/Models/Client.cs index e8c7a06..a1e55c4 100644 --- a/PrecastConcretePlantDataBaseImplemet/Models/Client.cs +++ b/PrecastConcretePlantDataBaseImplemet/Models/Client.cs @@ -27,7 +27,9 @@ namespace PrecastConcretePlantDatabaseImplement.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/PrecastConcretePlantDataBaseImplemet/Models/Message.cs b/PrecastConcretePlantDataBaseImplemet/Models/Message.cs new file mode 100644 index 0000000..44460cc --- /dev/null +++ b/PrecastConcretePlantDataBaseImplemet/Models/Message.cs @@ -0,0 +1,56 @@ +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.ViewModels; +using PrecastConcretePlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantDatabaseImplement.Models +{ + public class Message : IMessageInfoModel + { + [Key] + public string MessageId { get; private set; } = string.Empty; + public int? ClientId { get; private set; } + [Required] + public string SenderName { get; private set; } = string.Empty; + [Required] + public DateTime DateDelivery { get; private set; } = DateTime.Now; + [Required] + public string Subject { get; private set; } = string.Empty; + [Required] + public string Body { get; private set; } = string.Empty; + + public virtual Client Client { get; set; } + + public static Message? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Subject = model.Subject, + ClientId = model.ClientId, + MessageId = model.MessageId, + SenderName = model.SenderName, + DateDelivery = model.DateDelivery, + }; + } + + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Subject = Subject, + ClientId = ClientId, + MessageId = MessageId, + SenderName = SenderName, + DateDelivery = DateDelivery, + }; + } +} diff --git a/PrecastConcretePlantDataBaseImplemet/PrecastConcretePlantDatabase.cs b/PrecastConcretePlantDataBaseImplemet/PrecastConcretePlantDatabase.cs index 60b3cda..d23cae4 100644 --- a/PrecastConcretePlantDataBaseImplemet/PrecastConcretePlantDatabase.cs +++ b/PrecastConcretePlantDataBaseImplemet/PrecastConcretePlantDatabase.cs @@ -25,5 +25,6 @@ namespace PrecastConcretePlantDatabaseImplement public virtual DbSet Orders { set; get; } public virtual DbSet Clients { set; get; } public virtual DbSet Implementers { set; get; } - } + public virtual DbSet Messages { set; get; } + } } diff --git a/PrecastConcretePlantDataModels/Models/IMessageInfoModel.cs b/PrecastConcretePlantDataModels/Models/IMessageInfoModel.cs new file mode 100644 index 0000000..19ff002 --- /dev/null +++ b/PrecastConcretePlantDataModels/Models/IMessageInfoModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantDataModels.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/PrecastConcretePlantListImplement/DataListSingleton.cs b/PrecastConcretePlantListImplement/DataListSingleton.cs index cd739ac..36e9f14 100644 --- a/PrecastConcretePlantListImplement/DataListSingleton.cs +++ b/PrecastConcretePlantListImplement/DataListSingleton.cs @@ -15,14 +15,16 @@ namespace PrecastConcretePlantListImplement public List Reinforceds { get; set; } public List Clients { get; set; } public List Implementers { get; set; } - private DataListSingleton() + public List Messages { get; set; } + private DataListSingleton() { Components = new List(); Orders = new List(); Reinforceds = new List(); Clients = new List(); Implementers = new List(); - } + Messages = new List(); + } public static DataListSingleton GetInstance() { if (_instance == null) diff --git a/PrecastConcretePlantListImplement/Implements/ImplementerStorage.cs b/PrecastConcretePlantListImplement/Implements/ImplementerStorage.cs index fdb06d6..2ff5412 100644 --- a/PrecastConcretePlantListImplement/Implements/ImplementerStorage.cs +++ b/PrecastConcretePlantListImplement/Implements/ImplementerStorage.cs @@ -2,6 +2,7 @@ using PrecastConcretePlantContracts.SearchModels; using PrecastConcretePlantContracts.StoragesContracts; using PrecastConcretePlantContracts.ViewModels; +using PrecastConcretePlantListImplement.Models; using System; using System.Collections.Generic; using System.Linq; diff --git a/PrecastConcretePlantListImplement/Implements/MessageInfoStorage.cs b/PrecastConcretePlantListImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..923ea94 --- /dev/null +++ b/PrecastConcretePlantListImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,73 @@ +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.SearchModels; +using PrecastConcretePlantContracts.StoragesContracts; +using PrecastConcretePlantContracts.ViewModels; +using PrecastConcretePlantListImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrecastConcretePlantListImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + private readonly DataListSingleton _source; + public MessageInfoStorage() + { + _source = DataListSingleton.GetInstance(); + } + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (model.MessageId == null) + { + return null; + } + foreach (var message in _source.Messages) + { + if (model.MessageId.Equals(message.MessageId)) + return message.GetViewModel; + } + return null; + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + if (!model.ClientId.HasValue) + { + return new(); + } + var result = new List(); + foreach (var item in _source.Messages) + { + if (item.ClientId == model.ClientId) + { + result.Add(item.GetViewModel); + } + } + return result; + } + + public List GetFullList() + { + var result = new List(); + foreach (var item in _source.Messages) + { + result.Add(item.GetViewModel); + } + return result; + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = Message.Create(model); + if (newMessage == null) + { + return null; + } + _source.Messages.Add(newMessage); + return newMessage.GetViewModel; + } + } +} diff --git a/PrecastConcretePlantListImplement/Implements/OrderStorage.cs b/PrecastConcretePlantListImplement/Implements/OrderStorage.cs index 3ededc3..35b7859 100644 --- a/PrecastConcretePlantListImplement/Implements/OrderStorage.cs +++ b/PrecastConcretePlantListImplement/Implements/OrderStorage.cs @@ -1,5 +1,4 @@ - -using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.BindingModels; using PrecastConcretePlantContracts.SearchModels; using PrecastConcretePlantContracts.StoragesContracts; using PrecastConcretePlantContracts.ViewModels; @@ -86,7 +85,7 @@ namespace PrecastConcretePlantListImplement.Implements result.Add(order.GetViewModel); } - else if (model.Status != null && model.Status.Contains(order.Status)) + else if (model.Statuses != null && model.Statuses.Contains(order.Status)) { result.Add(order.GetViewModel); } @@ -116,6 +115,28 @@ namespace PrecastConcretePlantListImplement.Implements return result; } + private OrderViewModel GetViewModel(Order order) + { + var viewModel = order.GetViewModel; + foreach (var reinforced in _source.Reinforceds) + { + if (reinforced.Id == order.ReinforcedId) + { + viewModel.ReinforcedName = reinforced.ReinforcedName; + break; + } + } + foreach (var client in _source.Clients) + { + if (client.Id == order.ClientId) + { + viewModel.ClientFIO = client.ClientFIO; + break; + } + } + return viewModel; + } + public List GetFullList() { var result = new List(); diff --git a/PrecastConcretePlantListImplement/Models/Message.cs b/PrecastConcretePlantListImplement/Models/Message.cs new file mode 100644 index 0000000..9dcbacc --- /dev/null +++ b/PrecastConcretePlantListImplement/Models/Message.cs @@ -0,0 +1,54 @@ +using PrecastConcretePlantContracts.BindingModels; +using PrecastConcretePlantContracts.ViewModels; +using PrecastConcretePlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace PrecastConcretePlantListImplement.Models +{ + public class Message : IMessageInfoModel + { + public string MessageId { get; private set; } = string.Empty; + + public int? ClientId { get; private set; } + + public string SenderName { get; private set; } = string.Empty; + + public DateTime DateDelivery { get; private set; } = DateTime.Now; + + public string Subject { get; private set; } = string.Empty; + + public string Body { get; private set; } = string.Empty; + + public static Message? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Subject = model.Subject, + DateDelivery = model.DateDelivery, + SenderName = model.SenderName, + ClientId = model.ClientId, + MessageId = model.MessageId + }; + } + + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Subject = Subject, + DateDelivery = DateDelivery, + SenderName = SenderName, + ClientId = ClientId, + MessageId = MessageId + }; + } +} diff --git a/PrecastConcretePlantRestApi/Controllers/ClientController.cs b/PrecastConcretePlantRestApi/Controllers/ClientController.cs index 13797b9..efc278b 100644 --- a/PrecastConcretePlantRestApi/Controllers/ClientController.cs +++ b/PrecastConcretePlantRestApi/Controllers/ClientController.cs @@ -11,14 +11,15 @@ namespace PrecastConcretePlantRestApi.Controllers public class ClientController : Controller { private readonly ILogger _logger; + private readonly IMessageInfoLogic _mailLogic; + private readonly IClientLogic _logic; - private readonly IClientLogic _logic; - - public ClientController(IClientLogic logic, ILogger logger) - { + public ClientController(IClientLogic logic, ILogger logger, IMessageInfoLogic mailLogic) + { _logger = logger; _logic = logic; - } + _mailLogic = mailLogic; + } [HttpGet] public ClientViewModel? Login(string login, string password) @@ -65,5 +66,22 @@ namespace PrecastConcretePlantRestApi.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/PrecastConcretePlantRestApi/Controllers/ImplementerController.cs b/PrecastConcretePlantRestApi/Controllers/ImplementerController.cs index c2a7709..5f76e29 100644 --- a/PrecastConcretePlantRestApi/Controllers/ImplementerController.cs +++ b/PrecastConcretePlantRestApi/Controllers/ImplementerController.cs @@ -46,7 +46,7 @@ namespace PrecastConcretePlantRestApi.Controllers { return _order.ReadList(new OrderSearchModel { - Status = new() { OrderStatus.Принят } + Statuses = new() { OrderStatus.Принят } }); } catch (Exception ex) diff --git a/PrecastConcretePlantRestApi/Program.cs b/PrecastConcretePlantRestApi/Program.cs index 9c88860..70e8364 100644 --- a/PrecastConcretePlantRestApi/Program.cs +++ b/PrecastConcretePlantRestApi/Program.cs @@ -1,5 +1,7 @@ using Microsoft.OpenApi.Models; using PrecastConcretePlantBusinessLogic.BusinessLogic; +using PrecastConcretePlantBusinessLogic.MailWorker; +using PrecastConcretePlantContracts.BindingModels; using PrecastConcretePlantContracts.BusinessLogicsContracts; using PrecastConcretePlantContracts.StoragesContracts; using PrecastConcretePlantDatabaseImplement.Implements; @@ -13,10 +15,14 @@ builder.Logging.AddLog4Net("log4net.config"); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddTransient(); + +builder.Services.AddSingleton(); builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle @@ -28,6 +34,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/PrecastConcretePlantRestApi/appsettings.json b/PrecastConcretePlantRestApi/appsettings.json index 10f68b8..6442551 100644 --- a/PrecastConcretePlantRestApi/appsettings.json +++ b/PrecastConcretePlantRestApi/appsettings.json @@ -5,5 +5,11 @@ "Microsoft.AspNetCore": "Warning" } }, - "AllowedHosts": "*" + "AllowedHosts": "*", + "SmtpClientHost": "smtp.gmail.com", + "SmtpClientPort": "587", + "PopHost": "pop.gmail.com", + "PopPort": "995", + "MailLogin": "rppprecastconcreteplant@gmail.com", + "MailPassword": "ywcf hsuz rnig pezh" }