From d3d9083201dbe89d9b8c7c4f3e86a33f83429f8b Mon Sep 17 00:00:00 2001 From: frog24 Date: Fri, 3 May 2024 01:12:33 +0400 Subject: [PATCH] =?UTF-8?q?=D0=9E=D0=9D=D0=9E=20=D0=A0=D0=90=D0=91=D0=9E?= =?UTF-8?q?=D0=A2=D0=90=D0=95=D0=A2=20=20(o=5FO)=20!?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../DataFileSingleton.cs | 5 + .../Implements/MessageInfoStorage.cs | 53 +++ .../Models/MessageInfo.cs | 80 ++++ ComputersShop/ComputersShop/App.config | 11 + .../ComputersShop/ComputersShop.csproj | 3 + .../ComputersShop/FormMails.Designer.cs | 96 ++++ ComputersShop/ComputersShop/FormMails.cs | 47 ++ ComputersShop/ComputersShop/FormMails.resx | 60 +++ .../ComputersShop/FormMain.Designer.cs | 421 +++++++++--------- ComputersShop/ComputersShop/FormMain.cs | 381 ++++++++-------- ComputersShop/ComputersShop/Program.cs | 38 +- .../BusinessLogics/ClientLogic.cs | 13 + .../BusinessLogics/MessageInfoLogic.cs | 46 ++ .../BusinessLogics/OrderLogic.cs | 35 +- .../ComputersShopBusinessLogic.csproj | 1 + .../MailWorker/AbstractMailWorker.cs | 83 ++++ .../MailWorker/MailKitWorker.cs | 81 ++++ .../Controllers/HomeController.cs | 11 + .../Views/Home/Mails.cshtml | 55 +++ .../Views/Shared/_Layout.cshtml | 3 + .../BindingModels/MailConfigBindingModel.cs | 18 + .../BindingModels/MailSendInfoBindingModel.cs | 15 + .../BindingModels/MessageInfoBindingModel.cs | 19 + .../IMessageInfoLogic.cs | 17 + .../SearchModels/MessageInfoSearchModel.cs | 14 + .../StoragesContracts/IMessageInfoStorage.cs | 19 + .../ViewModels/MessageInfoViewModel.cs | 23 + .../Models/IMessageInfoModel.cs | 18 + .../ComputersShopDatabase.cs | 1 + .../Implements/MessageInfoStorage.cs | 49 ++ ...s => 20240502193720_FirstTime.Designer.cs} | 43 +- ...804_one.cs => 20240502193720_FirstTime.cs} | 31 +- .../ComputersShopDatabaseModelSnapshot.cs | 39 ++ .../Models/MessageInfo.cs | 49 ++ .../DataListSingleton.cs | 4 +- .../Implements/MessageInfoStorage.cs | 65 +++ .../Models/MessageInfo.cs | 46 ++ .../Controllers/ClientController.cs | 23 +- ComputersShop/ComputersShopRestApi/Program.cs | 19 + .../ComputersShopRestApi/appsettings.json | 10 +- 40 files changed, 1638 insertions(+), 407 deletions(-) create mode 100644 ComputersShop/ComputerShopFileImplements/Implements/MessageInfoStorage.cs create mode 100644 ComputersShop/ComputerShopFileImplements/Models/MessageInfo.cs create mode 100644 ComputersShop/ComputersShop/App.config create mode 100644 ComputersShop/ComputersShop/FormMails.Designer.cs create mode 100644 ComputersShop/ComputersShop/FormMails.cs create mode 100644 ComputersShop/ComputersShop/FormMails.resx create mode 100644 ComputersShop/ComputersShopBusinessLogic/BusinessLogics/MessageInfoLogic.cs create mode 100644 ComputersShop/ComputersShopBusinessLogic/MailWorker/AbstractMailWorker.cs create mode 100644 ComputersShop/ComputersShopBusinessLogic/MailWorker/MailKitWorker.cs create mode 100644 ComputersShop/ComputersShopClientApp/Views/Home/Mails.cshtml create mode 100644 ComputersShop/ComputersShopContracts/BindingModels/MailConfigBindingModel.cs create mode 100644 ComputersShop/ComputersShopContracts/BindingModels/MailSendInfoBindingModel.cs create mode 100644 ComputersShop/ComputersShopContracts/BindingModels/MessageInfoBindingModel.cs create mode 100644 ComputersShop/ComputersShopContracts/BusinessLogicsContracts/IMessageInfoLogic.cs create mode 100644 ComputersShop/ComputersShopContracts/SearchModels/MessageInfoSearchModel.cs create mode 100644 ComputersShop/ComputersShopContracts/StoragesContracts/IMessageInfoStorage.cs create mode 100644 ComputersShop/ComputersShopContracts/ViewModels/MessageInfoViewModel.cs create mode 100644 ComputersShop/ComputersShopDataModels/Models/IMessageInfoModel.cs create mode 100644 ComputersShop/ComputersShopDatabaseImplements/Implements/MessageInfoStorage.cs rename ComputersShop/ComputersShopDatabaseImplements/Migrations/{20240420140804_one.Designer.cs => 20240502193720_FirstTime.Designer.cs} (86%) rename ComputersShop/ComputersShopDatabaseImplements/Migrations/{20240420140804_one.cs => 20240502193720_FirstTime.cs} (85%) create mode 100644 ComputersShop/ComputersShopDatabaseImplements/Models/MessageInfo.cs create mode 100644 ComputersShop/ComputersShopListImplement/Implements/MessageInfoStorage.cs create mode 100644 ComputersShop/ComputersShopListImplement/Models/MessageInfo.cs diff --git a/ComputersShop/ComputerShopFileImplements/DataFileSingleton.cs b/ComputersShop/ComputerShopFileImplements/DataFileSingleton.cs index 11a0b04..48434df 100644 --- a/ComputersShop/ComputerShopFileImplements/DataFileSingleton.cs +++ b/ComputersShop/ComputerShopFileImplements/DataFileSingleton.cs @@ -16,11 +16,13 @@ namespace ComputersShopFileImplements public readonly string ComputerFileName = "Computer.xml"; public readonly string ClientFileName = "Client.xml"; public readonly string ImplementerFileName = "Implementer.xml"; + public readonly string MessageInfoFileName = "MessageInfo.xml"; public List Components { get; private set; } public List Orders { get; private set; } public List Computers { get; private set; } public List Clients { get; private set; } public List Implementers { get; private set; } + public List Messages { get; private set; } public static DataFileSingleton GetInstance() { if (instance == null) @@ -39,6 +41,8 @@ namespace ComputersShopFileImplements "Clients", x => x.GetXElement); public void SaveImplementers() => SaveData(Implementers, ImplementerFileName, "Implementers", x => x.GetXElement); + public void SaveMessages() => SaveData(Messages, MessageInfoFileName, + "Messages", x => x.GetXElement); private DataFileSingleton() { Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!; @@ -46,6 +50,7 @@ namespace ComputersShopFileImplements Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!; Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!; Implementers = LoadData(ImplementerFileName, "Implementers", x => Implementer.Create(x)!)!; + Messages = LoadData(MessageInfoFileName, "Messages", x => MessageInfo.Create(x)!)!; } private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) diff --git a/ComputersShop/ComputerShopFileImplements/Implements/MessageInfoStorage.cs b/ComputersShop/ComputerShopFileImplements/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..2163d5b --- /dev/null +++ b/ComputersShop/ComputerShopFileImplements/Implements/MessageInfoStorage.cs @@ -0,0 +1,53 @@ +using ComputersShopContracts.BindingModels; +using ComputersShopContracts.SearchModels; +using ComputersShopContracts.StoragesContracts; +using ComputersShopContracts.ViewModels; +using ComputersShopFileImplements.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopFileImplements.Implements +{ + public class MessageInfoStorage: IMessageInfoStorage + { + + private readonly DataFileSingleton _source; + public MessageInfoStorage() + { + _source = DataFileSingleton.GetInstance(); + } + + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (model.MessageId != null) + { + return _source.Messages.FirstOrDefault(x => x.MessageId == model.MessageId)?.GetViewModel; + } + return null; + } + + public List GetFiltredList(MessageInfoSearchModel model) + { + return _source.Messages.Where(x => x.ClientId == model.ClientId).Select(x => x.GetViewModel).ToList(); + } + + public List GetFullList() + { + return _source.Messages.Select(x => x.GetViewModel).ToList(); + } + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = MessageInfo.Create(model); + if (newMessage == null) + { + return null; + } + _source.Messages.Add(newMessage); + _source.SaveMessages(); + return newMessage.GetViewModel; + } + } +} diff --git a/ComputersShop/ComputerShopFileImplements/Models/MessageInfo.cs b/ComputersShop/ComputerShopFileImplements/Models/MessageInfo.cs new file mode 100644 index 0000000..3ed6dfe --- /dev/null +++ b/ComputersShop/ComputerShopFileImplements/Models/MessageInfo.cs @@ -0,0 +1,80 @@ +using ComputersShopContracts.BindingModels; +using ComputersShopContracts.ViewModels; +using ComputersShopDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace ComputersShopFileImplements.Models +{ + public class MessageInfo: IMessageInfoModel + { + public string MessageId { get; private set; } = string.Empty; + + public int? ClientId { get; private set; } + + public string SenderName { get; private set; } = string.Empty; + + public DateTime DateDelivery { get; private set; } = DateTime.Now; + + public string Subject { get; private set; } = string.Empty; + + public string Body { get; private set; } = string.Empty; + + public static MessageInfo? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Subject = model.Subject, + ClientId = model.ClientId, + MessageId = model.MessageId, + SenderName = model.SenderName, + DateDelivery = model.DateDelivery, + }; + } + + public static MessageInfo? Create(XElement element) + { + if (element == null) + { + return null; + } + return new() + { + Body = element.Attribute("Body")!.Value, + Subject = element.Attribute("Subject")!.Value, + ClientId = Convert.ToInt32(element.Attribute("ClientId")!.Value), + MessageId = element.Attribute("MessageId")!.Value, + SenderName = element.Attribute("SenderName")!.Value, + DateDelivery = Convert.ToDateTime(element.Attribute("DateDelivery")!.Value), + }; + } + + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Subject = Subject, + ClientId = ClientId, + MessageId = MessageId, + SenderName = SenderName, + DateDelivery = DateDelivery, + }; + + public XElement GetXElement => new("MessageInfo", + new XAttribute("Body", Body), + new XAttribute("Subject", Subject), + new XAttribute("ClientId", ClientId), + new XAttribute("MessageId", MessageId), + new XAttribute("SenderName", SenderName), + new XAttribute("DateDelivery", DateDelivery) + ); + } +} diff --git a/ComputersShop/ComputersShop/App.config b/ComputersShop/ComputersShop/App.config new file mode 100644 index 0000000..9d9414c --- /dev/null +++ b/ComputersShop/ComputersShop/App.config @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/ComputersShop/ComputersShop/ComputersShop.csproj b/ComputersShop/ComputersShop/ComputersShop.csproj index b903a24..dff2007 100644 --- a/ComputersShop/ComputersShop/ComputersShop.csproj +++ b/ComputersShop/ComputersShop/ComputersShop.csproj @@ -28,6 +28,9 @@ + + Always + Always diff --git a/ComputersShop/ComputersShop/FormMails.Designer.cs b/ComputersShop/ComputersShop/FormMails.Designer.cs new file mode 100644 index 0000000..8c59227 --- /dev/null +++ b/ComputersShop/ComputersShop/FormMails.Designer.cs @@ -0,0 +1,96 @@ +namespace ComputersShop +{ + 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() + { + DataGridViewCellStyle dataGridViewCellStyle1 = new DataGridViewCellStyle(); + DataGridViewCellStyle dataGridViewCellStyle2 = new DataGridViewCellStyle(); + DataGridViewCellStyle dataGridViewCellStyle3 = new DataGridViewCellStyle(); + dataGridView = new DataGridView(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // dataGridView + // + dataGridView.AllowUserToAddRows = false; + dataGridView.AllowUserToDeleteRows = false; + dataGridView.BackgroundColor = SystemColors.ButtonHighlight; + dataGridViewCellStyle1.Alignment = DataGridViewContentAlignment.MiddleLeft; + dataGridViewCellStyle1.BackColor = SystemColors.Control; + dataGridViewCellStyle1.Font = new Font("Segoe UI", 9F, FontStyle.Regular, GraphicsUnit.Point); + dataGridViewCellStyle1.ForeColor = SystemColors.WindowText; + dataGridViewCellStyle1.SelectionBackColor = SystemColors.Highlight; + dataGridViewCellStyle1.SelectionForeColor = SystemColors.HighlightText; + dataGridViewCellStyle1.WrapMode = DataGridViewTriState.True; + dataGridView.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle1; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridViewCellStyle2.Alignment = DataGridViewContentAlignment.MiddleLeft; + dataGridViewCellStyle2.BackColor = SystemColors.Window; + dataGridViewCellStyle2.Font = new Font("Segoe UI", 9F, FontStyle.Regular, GraphicsUnit.Point); + dataGridViewCellStyle2.ForeColor = SystemColors.ControlText; + dataGridViewCellStyle2.SelectionBackColor = SystemColors.Highlight; + dataGridViewCellStyle2.SelectionForeColor = SystemColors.HighlightText; + dataGridViewCellStyle2.WrapMode = DataGridViewTriState.False; + dataGridView.DefaultCellStyle = dataGridViewCellStyle2; + dataGridView.Dock = DockStyle.Left; + dataGridView.Location = new Point(0, 0); + dataGridView.MultiSelect = false; + dataGridView.Name = "dataGridView"; + dataGridView.ReadOnly = true; + dataGridViewCellStyle3.Alignment = DataGridViewContentAlignment.MiddleLeft; + dataGridViewCellStyle3.BackColor = SystemColors.Control; + dataGridViewCellStyle3.Font = new Font("Segoe UI", 9F, FontStyle.Regular, GraphicsUnit.Point); + dataGridViewCellStyle3.ForeColor = SystemColors.WindowText; + dataGridViewCellStyle3.SelectionBackColor = SystemColors.Highlight; + dataGridViewCellStyle3.SelectionForeColor = SystemColors.HighlightText; + dataGridViewCellStyle3.WrapMode = DataGridViewTriState.True; + dataGridView.RowHeadersDefaultCellStyle = dataGridViewCellStyle3; + dataGridView.RowHeadersVisible = false; + dataGridView.RowTemplate.Height = 25; + dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; + dataGridView.Size = new Size(785, 361); + dataGridView.TabIndex = 1; + // + // FormMails + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(784, 361); + Controls.Add(dataGridView); + Name = "FormMails"; + Text = "Письма"; + Load += FormMails_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView; + } +} \ No newline at end of file diff --git a/ComputersShop/ComputersShop/FormMails.cs b/ComputersShop/ComputersShop/FormMails.cs new file mode 100644 index 0000000..a30ea9a --- /dev/null +++ b/ComputersShop/ComputersShop/FormMails.cs @@ -0,0 +1,47 @@ +using ComputersShopContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace ComputersShop +{ + public partial class FormMails : Form + { + private readonly ILogger _logger; + private readonly IMessageInfoLogic _logic; + public FormMails(ILogger logger, IMessageInfoLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + private void FormMails_Load(object sender, EventArgs e) + { + try + { + var list = _logic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["MessageId"].Visible = false; + dataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + _logger.LogInformation("Load mails"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Load mails error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } +} diff --git a/ComputersShop/ComputersShop/FormMails.resx b/ComputersShop/ComputersShop/FormMails.resx new file mode 100644 index 0000000..f298a7b --- /dev/null +++ b/ComputersShop/ComputersShop/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/ComputersShop/ComputersShop/FormMain.Designer.cs b/ComputersShop/ComputersShop/FormMain.Designer.cs index 632a0d3..dc2c230 100644 --- a/ComputersShop/ComputersShop/FormMain.Designer.cs +++ b/ComputersShop/ComputersShop/FormMain.Designer.cs @@ -1,214 +1,223 @@ namespace ComputersShop { - 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(); - buttonCreateOrder = new Button(); - buttonIssuedOrder = new Button(); - buttonUpdate = 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(1184, 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 = "Справочники"; - // - // компоненты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(232, 22); - списокКомпьютеровToolStripMenuItem.Text = "Список компонентов"; - списокКомпьютеровToolStripMenuItem.Click += ComponentsToolStripMenuItem_Click; - // - // компьютерыСКомпонентамиToolStripMenuItem - // - компьютерыСКомпонентамиToolStripMenuItem.Name = "компьютерыСКомпонентамиToolStripMenuItem"; - компьютерыСКомпонентамиToolStripMenuItem.Size = new Size(232, 22); - компьютерыСКомпонентамиToolStripMenuItem.Text = "Компьтеры с компонентами"; - компьютерыСКомпонентамиToolStripMenuItem.Click += ComponentComputersToolStripMenuItem_Click; - // - // списокЗаказовToolStripMenuItem - // - списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem"; - списокЗаказовToolStripMenuItem.Size = new Size(232, 22); - списокЗаказовToolStripMenuItem.Text = "Список заказов"; - списокЗаказовToolStripMenuItem.Click += OrdersToolStripMenuItem_Click; - // - // запускРаботToolStripMenuItem - // - запускРаботToolStripMenuItem.Name = "запускРаботToolStripMenuItem"; - запускРаботToolStripMenuItem.Size = new Size(92, 20); - запускРаботToolStripMenuItem.Text = "Запуск работ"; - запускРаботToolStripMenuItem.Click += ЗапускРаботToolStripMenuItem_Click; - // - // dataGridView - // - dataGridView.AllowUserToAddRows = false; - dataGridView.AllowUserToDeleteRows = false; - dataGridView.BackgroundColor = SystemColors.ButtonHighlight; - dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; - dataGridView.Location = new Point(0, 27); - dataGridView.MultiSelect = false; - dataGridView.Name = "dataGridView"; - dataGridView.ReadOnly = true; - dataGridView.RowHeadersVisible = false; - dataGridView.RowTemplate.Height = 25; - dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; - dataGridView.Size = new Size(980, 425); - dataGridView.TabIndex = 1; - // - // buttonCreateOrder - // - buttonCreateOrder.Location = new Point(992, 27); - buttonCreateOrder.Name = "buttonCreateOrder"; - buttonCreateOrder.Size = new Size(180, 35); - buttonCreateOrder.TabIndex = 2; - buttonCreateOrder.Text = "Создать заказ"; - buttonCreateOrder.UseVisualStyleBackColor = true; - buttonCreateOrder.Click += ButtonCreateOrder_Click; - // - // buttonIssuedOrder - // - buttonIssuedOrder.Location = new Point(992, 147); - buttonIssuedOrder.Name = "buttonIssuedOrder"; - buttonIssuedOrder.Size = new Size(180, 35); - buttonIssuedOrder.TabIndex = 5; - buttonIssuedOrder.Text = "Заказ выдан"; - buttonIssuedOrder.UseVisualStyleBackColor = true; - buttonIssuedOrder.Click += ButtonIssuedOrder_Click; - // - // buttonUpdate - // - buttonUpdate.Location = new Point(992, 87); - buttonUpdate.Name = "buttonUpdate"; - buttonUpdate.Size = new Size(180, 35); - buttonUpdate.TabIndex = 6; - buttonUpdate.Text = "Обновить список"; - buttonUpdate.UseVisualStyleBackColor = true; - buttonUpdate.Click += ButtonUpd_Click; - // - // FormMain - // - AutoScaleDimensions = new SizeF(7F, 15F); - AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1184, 450); - Controls.Add(buttonUpdate); - Controls.Add(buttonIssuedOrder); - Controls.Add(buttonCreateOrder); - 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(); + buttonCreateOrder = new Button(); + buttonIssuedOrder = new Button(); + buttonUpdate = 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(1184, 24); + menuStrip.TabIndex = 0; + menuStrip.Text = "menuStrip1"; + // + // справочникиToolStripMenuItem + // + справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, комьютерыToolStripMenuItem, клиентыToolStripMenuItem, исполнителиToolStripMenuItem, письмаToolStripMenuItem }); + справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; + справочникиToolStripMenuItem.Size = new Size(94, 20); + справочникиToolStripMenuItem.Text = "Справочники"; + // + // компонентыToolStripMenuItem + // + компонентыToolStripMenuItem.Name = "компонентыToolStripMenuItem"; + компонентыToolStripMenuItem.Size = new Size(180, 22); + компонентыToolStripMenuItem.Text = "Компоненты"; + компонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click; + // + // комьютерыToolStripMenuItem + // + комьютерыToolStripMenuItem.Name = "комьютерыToolStripMenuItem"; + комьютерыToolStripMenuItem.Size = new Size(180, 22); + комьютерыToolStripMenuItem.Text = "Комьютеры"; + комьютерыToolStripMenuItem.Click += КомпьютерыToolStripMenuItem_Click; + // + // клиентыToolStripMenuItem + // + клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; + клиентыToolStripMenuItem.Size = new Size(180, 22); + клиентыToolStripMenuItem.Text = "Клиенты"; + клиентыToolStripMenuItem.Click += клиентыToolStripMenuItem_Click; + // + // исполнителиToolStripMenuItem + // + исполнителиToolStripMenuItem.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(232, 22); + списокКомпьютеровToolStripMenuItem.Text = "Список компонентов"; + списокКомпьютеровToolStripMenuItem.Click += ComponentsToolStripMenuItem_Click; + // + // компьютерыСКомпонентамиToolStripMenuItem + // + компьютерыСКомпонентамиToolStripMenuItem.Name = "компьютерыСКомпонентамиToolStripMenuItem"; + компьютерыСКомпонентамиToolStripMenuItem.Size = new Size(232, 22); + компьютерыСКомпонентамиToolStripMenuItem.Text = "Компьтеры с компонентами"; + компьютерыСКомпонентамиToolStripMenuItem.Click += ComponentComputersToolStripMenuItem_Click; + // + // списокЗаказовToolStripMenuItem + // + списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem"; + списокЗаказовToolStripMenuItem.Size = new Size(232, 22); + списокЗаказовToolStripMenuItem.Text = "Список заказов"; + списокЗаказовToolStripMenuItem.Click += OrdersToolStripMenuItem_Click; + // + // запускРаботToolStripMenuItem + // + запускРаботToolStripMenuItem.Name = "запускРаботToolStripMenuItem"; + запускРаботToolStripMenuItem.Size = new Size(92, 20); + запускРаботToolStripMenuItem.Text = "Запуск работ"; + запускРаботToolStripMenuItem.Click += ЗапускРаботToolStripMenuItem_Click; + // + // dataGridView + // + dataGridView.AllowUserToAddRows = false; + dataGridView.AllowUserToDeleteRows = false; + dataGridView.BackgroundColor = SystemColors.ButtonHighlight; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(0, 27); + dataGridView.MultiSelect = false; + dataGridView.Name = "dataGridView"; + dataGridView.ReadOnly = true; + dataGridView.RowHeadersVisible = false; + dataGridView.RowTemplate.Height = 25; + dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; + dataGridView.Size = new Size(980, 425); + dataGridView.TabIndex = 1; + // + // buttonCreateOrder + // + buttonCreateOrder.Location = new Point(992, 27); + buttonCreateOrder.Name = "buttonCreateOrder"; + buttonCreateOrder.Size = new Size(180, 35); + buttonCreateOrder.TabIndex = 2; + buttonCreateOrder.Text = "Создать заказ"; + buttonCreateOrder.UseVisualStyleBackColor = true; + buttonCreateOrder.Click += ButtonCreateOrder_Click; + // + // buttonIssuedOrder + // + buttonIssuedOrder.Location = new Point(992, 147); + buttonIssuedOrder.Name = "buttonIssuedOrder"; + buttonIssuedOrder.Size = new Size(180, 35); + buttonIssuedOrder.TabIndex = 5; + buttonIssuedOrder.Text = "Заказ выдан"; + buttonIssuedOrder.UseVisualStyleBackColor = true; + buttonIssuedOrder.Click += ButtonIssuedOrder_Click; + // + // buttonUpdate + // + buttonUpdate.Location = new Point(992, 87); + buttonUpdate.Name = "buttonUpdate"; + buttonUpdate.Size = new Size(180, 35); + buttonUpdate.TabIndex = 6; + buttonUpdate.Text = "Обновить список"; + buttonUpdate.UseVisualStyleBackColor = true; + buttonUpdate.Click += ButtonUpd_Click; + // + // FormMain + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(1184, 450); + Controls.Add(buttonUpdate); + Controls.Add(buttonIssuedOrder); + Controls.Add(buttonCreateOrder); + 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 buttonCreateOrder; - private Button buttonIssuedOrder; - private Button buttonUpdate; - 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 buttonCreateOrder; + private Button buttonIssuedOrder; + private Button buttonUpdate; + 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/ComputersShop/ComputersShop/FormMain.cs b/ComputersShop/ComputersShop/FormMain.cs index 053276f..fa748f5 100644 --- a/ComputersShop/ComputersShop/FormMain.cs +++ b/ComputersShop/ComputersShop/FormMain.cs @@ -15,203 +15,212 @@ using System.Windows.Forms; namespace ComputersShop { - public partial class FormMain : Form - { - private readonly ILogger _logger; + public partial class FormMain : Form + { + private readonly ILogger _logger; - private readonly IOrderLogic _orderLogic; - private readonly IReportLogic _reportLogic; - private readonly IWorkProcess _workProcess; + 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() - { - try - { - var list = _orderLogic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["ComputerId"].Visible = false; - dataGridView.Columns["ComputerName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - dataGridView.Columns["ClientId"].Visible = false; - dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - dataGridView.Columns["ImplementerId"].Visible = false; - } - _logger.LogInformation("Orders loading"); - } - catch (Exception ex) - { - _logger.LogError(ex, "Orders loading error"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } + private void LoadData() + { + try + { + var list = _orderLogic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["ComputerId"].Visible = false; + dataGridView.Columns["ComputerName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + dataGridView.Columns["ImplementerId"].Visible = false; + } + _logger.LogInformation("Orders loading"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Orders loading error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } - private void КомпонентыToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormComponents)); - if (service is FormComponents form) - { - form.ShowDialog(); - } - } + private void КомпонентыToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormComponents)); + if (service is FormComponents form) + { + form.ShowDialog(); + } + } - private void КомпьютерыToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormComputers)); - if (service is FormComputers form) - { - form.ShowDialog(); - } - } + private void КомпьютерыToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormComputers)); + if (service is FormComputers form) + { + form.ShowDialog(); + } + } - private void ButtonCreateOrder_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); - if (service is FormCreateOrder form) - { - form.ShowDialog(); - LoadData(); - } - } + private void ButtonCreateOrder_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); + if (service is FormCreateOrder form) + { + form.ShowDialog(); + LoadData(); + } + } - private void ButtonTakeOrderInWork_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Order №{id}. Status changes to 'В работе'", id); - try - { - var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel { Id = id }); - if (!operationResult) - { - throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); - } - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Error taking an order to work"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } + private void ButtonTakeOrderInWork_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Order №{id}. Status changes to 'В работе'", id); + try + { + var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel { Id = id }); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error taking an order to work"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } - private void ButtonOrderReady_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Order №{id}. Status changes to 'Готов'", id); - try - { - var operationResult = _orderLogic.FinishOrder(new OrderBindingModel { Id = id }); - if (!operationResult) - { - throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); - } - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Order readiness marking error"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } + private void ButtonOrderReady_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Order №{id}. Status changes to 'Готов'", id); + try + { + var operationResult = _orderLogic.FinishOrder(new OrderBindingModel { Id = id }); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Order readiness marking error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } - private void ButtonIssuedOrder_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Order №{id}. Status changes to 'Выдан'", id); - try - { - var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel { Id = id }); - if (!operationResult) - { - throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); - } - _logger.LogInformation("Order №{id} issued", id); - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Order issue marking error"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } + private void ButtonIssuedOrder_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Order №{id}. Status changes to 'Выдан'", id); + try + { + var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel { Id = id }); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + _logger.LogInformation("Order №{id} issued", id); + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Order issue marking error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } - private void ButtonUpd_Click(object sender, EventArgs e) - { - LoadData(); - } + private void ButtonUpd_Click(object sender, EventArgs e) + { + LoadData(); + } - private void ComponentsToolStripMenuItem_Click(object sender, EventArgs e) - { - using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; - if (dialog.ShowDialog() == DialogResult.OK) - { - _reportLogic.SaveComputersToWordFile(new ReportBindingModel - { - FileName = dialog.FileName - }); - MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); - } - } - private void ComponentComputersToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormReportComputerComponents)); - if (service is FormReportComputerComponents form) - { - form.ShowDialog(); - } - } - private void OrdersToolStripMenuItem_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(FormImplementers)); - if (service is FormImplementers form) - { - form.ShowDialog(); - } - } + private void ComponentsToolStripMenuItem_Click(object sender, EventArgs e) + { + using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; + if (dialog.ShowDialog() == DialogResult.OK) + { + _reportLogic.SaveComputersToWordFile(new ReportBindingModel + { + FileName = dialog.FileName + }); + MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + private void ComponentComputersToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReportComputerComponents)); + if (service is FormReportComputerComponents form) + { + form.ShowDialog(); + } + } + private void OrdersToolStripMenuItem_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(FormImplementers)); + if (service is FormImplementers 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) + { + var service = Program.ServiceProvider?.GetService(typeof(FormMails)); + if (service is FormMails 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); + } + } } diff --git a/ComputersShop/ComputersShop/Program.cs b/ComputersShop/ComputersShop/Program.cs index 2ab53d7..2321f82 100644 --- a/ComputersShop/ComputersShop/Program.cs +++ b/ComputersShop/ComputersShop/Program.cs @@ -9,6 +9,8 @@ using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; using System; using ComputersShopContracts.BusinessLogicsContracts; +using ComputersShopBusinessLogic.MailWorker; +using ComputersShopContracts.BindingModels; namespace ComputersShop { @@ -28,7 +30,31 @@ namespace ComputersShop var services = new ServiceCollection(); ConfigureServices(services); _serviceProvider = services.BuildServiceProvider(); - Application.Run(_serviceProvider.GetRequiredService()); + + try + { + var mailSender = _serviceProvider.GetService(); + mailSender?.MailConfig(new MailConfigBindingModel + { + MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty, + MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty, + SmtpClientHost = System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty, + SmtpClientPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]), + PopHost = System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty, + PopPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"]) + }); + // + var timer = new System.Threading.Timer(new + TimerCallback(MailCheck!), null, 0, 100000); + } + catch (Exception ex) + { + var logger = _serviceProvider.GetService(); + logger?.LogError(ex, " "); + } + + + Application.Run(_serviceProvider.GetRequiredService()); } private static void ConfigureServices(ServiceCollection services) { @@ -42,6 +68,7 @@ namespace ComputersShop services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -49,10 +76,12 @@ namespace ComputersShop services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); - services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddSingleton(); services.AddTransient(); @@ -68,6 +97,9 @@ namespace ComputersShop services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); } - } + + private static void MailCheck(object obj) => ServiceProvider?.GetService()?.MailCheck(); + } } \ No newline at end of file diff --git a/ComputersShop/ComputersShopBusinessLogic/BusinessLogics/ClientLogic.cs b/ComputersShop/ComputersShopBusinessLogic/BusinessLogics/ClientLogic.cs index e761756..cf37cd9 100644 --- a/ComputersShop/ComputersShopBusinessLogic/BusinessLogics/ClientLogic.cs +++ b/ComputersShop/ComputersShopBusinessLogic/BusinessLogics/ClientLogic.cs @@ -8,6 +8,7 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; +using System.Text.RegularExpressions; using System.Threading.Tasks; namespace ComputersShopBusinessLogic.BusinessLogics @@ -98,6 +99,18 @@ namespace ComputersShopBusinessLogic.BusinessLogics { throw new ArgumentNullException("Нет эл. почты", nameof(model.Email)); } + if (string.IsNullOrEmpty(model.Password)) + { + throw new ArgumentNullException("Нет пароля", nameof(model.Password)); + } + 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. Id:{Id}. FIO:{ClientFIO}. Email:{Email}.", model.Id, model.ClientFIO, model.Email); diff --git a/ComputersShop/ComputersShopBusinessLogic/BusinessLogics/MessageInfoLogic.cs b/ComputersShop/ComputersShopBusinessLogic/BusinessLogics/MessageInfoLogic.cs new file mode 100644 index 0000000..ac725e7 --- /dev/null +++ b/ComputersShop/ComputersShopBusinessLogic/BusinessLogics/MessageInfoLogic.cs @@ -0,0 +1,46 @@ +using ComputersShopContracts.BindingModels; +using ComputersShopContracts.BusinessLogicsContracts; +using ComputersShopContracts.SearchModels; +using ComputersShopContracts.StoragesContracts; +using ComputersShopContracts.ViewModels; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopBusinessLogic.BusinessLogics +{ + public class MessageInfoLogic: IMessageInfoLogic + { + private readonly ILogger _logger; + private readonly IMessageInfoStorage _messageInfoStorage; + public MessageInfoLogic(ILogger logger, IMessageInfoStorage messageInfoStorage) + { + _logger = logger; + _messageInfoStorage = messageInfoStorage; + } + public bool Create(MessageInfoBindingModel model) + { + if (_messageInfoStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } + public List? ReadList(MessageInfoSearchModel? model) + { + _logger.LogInformation("ReadList. MessageInfoName:{MessageInfoName}. Id:{Id}", model?.MessageId, model?.ClientId); + var list = model == null ? _messageInfoStorage.GetFullList() : _messageInfoStorage.GetFiltredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + _logger.LogInformation("ReadList. Count:{Count}", list.Count); + return list; + } + } +} diff --git a/ComputersShop/ComputersShopBusinessLogic/BusinessLogics/OrderLogic.cs b/ComputersShop/ComputersShopBusinessLogic/BusinessLogics/OrderLogic.cs index 2da4896..ef4b419 100644 --- a/ComputersShop/ComputersShopBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/ComputersShop/ComputersShopBusinessLogic/BusinessLogics/OrderLogic.cs @@ -1,5 +1,7 @@ -using ComputersShopContracts.BindingModels; +using ComputersShopBusinessLogic.MailWorker; +using ComputersShopContracts.BindingModels; using ComputersShopContracts.BuisnessLogicsContracts; +using ComputersShopContracts.BusinessLogicsContracts; using ComputersShopContracts.SearchModels; using ComputersShopContracts.StoragesContracts; using ComputersShopContracts.ViewModels; @@ -18,10 +20,14 @@ namespace ComputersShopBusinessLogic.BusinessLogics private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; static readonly object locker = new object(); - public OrderLogic(ILogger logger, IOrderStorage orderStorage) + private readonly AbstractMailWorker _mailWorker; + private readonly IClientLogic _clientLogic; + public OrderLogic(ILogger logger, IOrderStorage orderStorage, AbstractMailWorker mailWorker, IClientLogic clientLogic) { _logger = logger; _orderStorage = orderStorage; + _mailWorker = mailWorker; + _clientLogic = clientLogic; } public List? ReadList(OrderSearchModel? model) { @@ -65,12 +71,14 @@ namespace ComputersShopBusinessLogic.BusinessLogics return false; } model.Status = OrderStatus.Принят; - if (_orderStorage.Insert(model) == null) + var order = _orderStorage.Insert(model); + if (order == null) { _logger.LogWarning("Insert operation failed"); return false; } - return true; + SendOrderMessage(order.ClientId, $"DNS, Заказ №{order.Id}", $"Заказ №{order.Id} от {order.DateCreate} на сумму {order.Sum:0.00} принят"); + return true; } public bool ChangeStatus(OrderBindingModel model, OrderStatus newStatus) { @@ -96,12 +104,14 @@ namespace ComputersShopBusinessLogic.BusinessLogics { model.DateImplement = DateTime.Now; } - if (_orderStorage.Update(model) == null) + var order = _orderStorage.Update(model); + if (order == null) { model.Status = oldStatus; _logger.LogWarning("Update operation failed"); return false; } + SendOrderMessage(order.ClientId, $"DNS, Заказ №{order.Id}", $"Заказ №{order.Id} от {order.DateCreate} на сумму {order.Sum:0.00} принят"); return true; } public bool TakeOrderInWork(OrderBindingModel model) @@ -143,5 +153,20 @@ namespace ComputersShopBusinessLogic.BusinessLogics } _logger.LogInformation("Order. Id:{Id}. Sum:{Sum}. ComputerId:{ComputerId}", model.Id, model.Sum, model.ComputerId); } + private bool SendOrderMessage(int clientId, string subject, string text) + { + var client = _clientLogic.ReadElement(new() { Id = clientId }); + if (client == null) + { + return false; + } + _mailWorker.MailSendAsync(new() + { + MailAddress = client.Email, + Subject = subject, + Text = text + }); + return true; + } } } diff --git a/ComputersShop/ComputersShopBusinessLogic/ComputersShopBusinessLogic.csproj b/ComputersShop/ComputersShopBusinessLogic/ComputersShopBusinessLogic.csproj index a8c80e3..9f21440 100644 --- a/ComputersShop/ComputersShopBusinessLogic/ComputersShopBusinessLogic.csproj +++ b/ComputersShop/ComputersShopBusinessLogic/ComputersShopBusinessLogic.csproj @@ -8,6 +8,7 @@ + diff --git a/ComputersShop/ComputersShopBusinessLogic/MailWorker/AbstractMailWorker.cs b/ComputersShop/ComputersShopBusinessLogic/MailWorker/AbstractMailWorker.cs new file mode 100644 index 0000000..3ec9f87 --- /dev/null +++ b/ComputersShop/ComputersShopBusinessLogic/MailWorker/AbstractMailWorker.cs @@ -0,0 +1,83 @@ +using ComputersShopContracts.BindingModels; +using ComputersShopContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopBusinessLogic.MailWorker +{ + public abstract class AbstractMailWorker + { + protected string _mailLogin = string.Empty; + protected string _mailPassword = string.Empty; + protected string _smtpClientHost = string.Empty; + protected int _smtpClientPort; + protected string _popHost = string.Empty; + protected int _popPort; + private readonly IMessageInfoLogic _messageInfoLogic; + private readonly ILogger _logger; + + public AbstractMailWorker(ILogger logger, IMessageInfoLogic messageInfoLogic) + { + _logger = logger; + _messageInfoLogic = messageInfoLogic; + } + + public void MailConfig(MailConfigBindingModel config) + { + _mailLogin = config.MailLogin; + _mailPassword = config.MailPassword; + _smtpClientHost = config.SmtpClientHost; + _smtpClientPort = config.SmtpClientPort; + _popHost = config.PopHost; + _popPort = config.PopPort; + _logger.LogDebug("Config: {login}, {password}, {clientHost}, {clientPort}, {popHost}, {popPort}", + _mailLogin, _mailPassword, _smtpClientHost, _smtpClientPort, _popHost, _popPort); + } + public async void MailSendAsync(MailSendInfoBindingModel info) + { + if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword)) + { + return; + } + if (string.IsNullOrEmpty(_smtpClientHost) || _smtpClientPort == 0) + { + return; + } + if (string.IsNullOrEmpty(info.MailAddress) || + string.IsNullOrEmpty(info.Subject) || + string.IsNullOrEmpty(info.Text)) + { + return; + } + _logger.LogDebug("Send mail to: {To}, {Subject}", info.MailAddress, info.Subject); + await SendMailAsync(info); + } + public async void MailCheck() + { + if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword)) + { + return; + } + if (string.IsNullOrEmpty(_popHost) || _popPort == 0) + { + return; + } + if (_messageInfoLogic == null) + { + return; + } + var list = await ReceiveMailAsync(); + _logger.LogDebug("Check mail: {Count} new mails", list.Count); + foreach(var mail in list) + { + _messageInfoLogic.Create(mail); + } + } + protected abstract Task SendMailAsync(MailSendInfoBindingModel info); + protected abstract Task> ReceiveMailAsync(); + } +} diff --git a/ComputersShop/ComputersShopBusinessLogic/MailWorker/MailKitWorker.cs b/ComputersShop/ComputersShopBusinessLogic/MailWorker/MailKitWorker.cs new file mode 100644 index 0000000..208afda --- /dev/null +++ b/ComputersShop/ComputersShopBusinessLogic/MailWorker/MailKitWorker.cs @@ -0,0 +1,81 @@ +using ComputersShopContracts.BindingModels; +using ComputersShopContracts.BusinessLogicsContracts; +using MailKit.Net.Pop3; +using MailKit.Security; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Mail; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopBusinessLogic.MailWorker +{ + public class MailKitWorker : AbstractMailWorker + { + public MailKitWorker(ILogger logger, IMessageInfoLogic messageInfoLogic) : + base(logger, messageInfoLogic) + { } + protected override async Task SendMailAsync(MailSendInfoBindingModel info) + { + using var objMailMessage = new MailMessage(); + using var objSmtpClient = new SmtpClient(_smtpClientHost, _smtpClientPort); + try + { + objMailMessage.From = new MailAddress(_mailLogin); + objMailMessage.To.Add(new MailAddress(info.MailAddress)); + objMailMessage.Subject = info.Subject; + objMailMessage.Body = info.Text; + objMailMessage.SubjectEncoding = Encoding.UTF8; + objMailMessage.BodyEncoding = Encoding.UTF8; + objSmtpClient.UseDefaultCredentials = false; + objSmtpClient.EnableSsl = true; + objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; + objSmtpClient.Credentials = new NetworkCredential(_mailLogin, _mailPassword); + await Task.Run(() => objSmtpClient.Send(objMailMessage)); + } + catch (Exception) + { + throw; + } + } + protected override async Task> ReceiveMailAsync() + { + var list = new List(); + using var client = new Pop3Client(); + await Task.Run(() => + { + try + { + client.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; + client.Connect(_popHost, _popPort, SecureSocketOptions.SslOnConnect); + client.Authenticate(_mailLogin, _mailPassword); + for (int i = 0; i < client.Count; i++) + { + var message = client.GetMessage(i); + foreach (var mail in message.From.Mailboxes) + { + list.Add(new MessageInfoBindingModel + { + DateDelivery = message.Date.DateTime, + MessageId = message.MessageId, + SenderName = mail.Address, + Subject = message.Subject, + Body = message.TextBody + }); + } + } + } + catch (AuthenticationException) + { } + finally + { + client.Disconnect(true); + } + }); + return list; + } + } +} diff --git a/ComputersShop/ComputersShopClientApp/Controllers/HomeController.cs b/ComputersShop/ComputersShopClientApp/Controllers/HomeController.cs index 434da13..a6d8374 100644 --- a/ComputersShop/ComputersShopClientApp/Controllers/HomeController.cs +++ b/ComputersShop/ComputersShopClientApp/Controllers/HomeController.cs @@ -139,5 +139,16 @@ namespace ComputersShopClientApp.Controllers var _computer = APIClient.GetRequest($"api/main/getcomputer?computerid={computer}"); return Math.Round(count * (_computer?.Price ?? 1), 2); } + + [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/ComputersShop/ComputersShopClientApp/Views/Home/Mails.cshtml b/ComputersShop/ComputersShopClientApp/Views/Home/Mails.cshtml new file mode 100644 index 0000000..82864e9 --- /dev/null +++ b/ComputersShop/ComputersShopClientApp/Views/Home/Mails.cshtml @@ -0,0 +1,55 @@ +@using ComputersShopContracts.ViewModels + +@model List + +@{ + ViewData["Title"] = "Mails"; +} + +
+

Заказы

+
+ +
+ @{ + if (Model == null) + { +

Авторизируйтесь

+ return; + } + + + + + + + + + + @foreach (var item in Model) + { + + + + + + } + +
+ Дата письма + + Заголовок + + Текст +
+ @Html.DisplayFor(modelItem => + item.DateDelivery) + + @Html.DisplayFor(modelItem => + item.Subject) + + @Html.DisplayFor(modelItem => + item.Body) +
+ } +
diff --git a/ComputersShop/ComputersShopClientApp/Views/Shared/_Layout.cshtml b/ComputersShop/ComputersShopClientApp/Views/Shared/_Layout.cshtml index 6db21dd..a10df88 100644 --- a/ComputersShop/ComputersShopClientApp/Views/Shared/_Layout.cshtml +++ b/ComputersShop/ComputersShopClientApp/Views/Shared/_Layout.cshtml @@ -25,6 +25,9 @@ + diff --git a/ComputersShop/ComputersShopContracts/BindingModels/MailConfigBindingModel.cs b/ComputersShop/ComputersShopContracts/BindingModels/MailConfigBindingModel.cs new file mode 100644 index 0000000..696b731 --- /dev/null +++ b/ComputersShop/ComputersShopContracts/BindingModels/MailConfigBindingModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopContracts.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/ComputersShop/ComputersShopContracts/BindingModels/MailSendInfoBindingModel.cs b/ComputersShop/ComputersShopContracts/BindingModels/MailSendInfoBindingModel.cs new file mode 100644 index 0000000..9b4acc3 --- /dev/null +++ b/ComputersShop/ComputersShopContracts/BindingModels/MailSendInfoBindingModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopContracts.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/ComputersShop/ComputersShopContracts/BindingModels/MessageInfoBindingModel.cs b/ComputersShop/ComputersShopContracts/BindingModels/MessageInfoBindingModel.cs new file mode 100644 index 0000000..6f3f35e --- /dev/null +++ b/ComputersShop/ComputersShopContracts/BindingModels/MessageInfoBindingModel.cs @@ -0,0 +1,19 @@ +using ComputersShopDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopContracts.BindingModels +{ + public class MessageInfoBindingModel: IMessageInfoModel + { + public string MessageId { get; set; } = string.Empty; + public int? ClientId { get; set; } + public string SenderName { get; set; } = string.Empty; + public DateTime DateDelivery { get; set; } + public string Subject { get; set; } = string.Empty; + public string Body { get; set; } = string.Empty; + } +} diff --git a/ComputersShop/ComputersShopContracts/BusinessLogicsContracts/IMessageInfoLogic.cs b/ComputersShop/ComputersShopContracts/BusinessLogicsContracts/IMessageInfoLogic.cs new file mode 100644 index 0000000..159368b --- /dev/null +++ b/ComputersShop/ComputersShopContracts/BusinessLogicsContracts/IMessageInfoLogic.cs @@ -0,0 +1,17 @@ +using ComputersShopContracts.BindingModels; +using ComputersShopContracts.SearchModels; +using ComputersShopContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopContracts.BusinessLogicsContracts +{ + public interface IMessageInfoLogic + { + List? ReadList(MessageInfoSearchModel? model); + bool Create(MessageInfoBindingModel model); + } +} diff --git a/ComputersShop/ComputersShopContracts/SearchModels/MessageInfoSearchModel.cs b/ComputersShop/ComputersShopContracts/SearchModels/MessageInfoSearchModel.cs new file mode 100644 index 0000000..69d6a42 --- /dev/null +++ b/ComputersShop/ComputersShopContracts/SearchModels/MessageInfoSearchModel.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopContracts.SearchModels +{ + public class MessageInfoSearchModel + { + public int? ClientId { get; set; } + public string? MessageId { get; set; } + } +} diff --git a/ComputersShop/ComputersShopContracts/StoragesContracts/IMessageInfoStorage.cs b/ComputersShop/ComputersShopContracts/StoragesContracts/IMessageInfoStorage.cs new file mode 100644 index 0000000..05eca9f --- /dev/null +++ b/ComputersShop/ComputersShopContracts/StoragesContracts/IMessageInfoStorage.cs @@ -0,0 +1,19 @@ +using ComputersShopContracts.BindingModels; +using ComputersShopContracts.SearchModels; +using ComputersShopContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopContracts.StoragesContracts +{ + public interface IMessageInfoStorage + { + List GetFullList(); + List GetFiltredList(MessageInfoSearchModel model); + MessageInfoViewModel? GetElement(MessageInfoSearchModel model); + MessageInfoViewModel? Insert(MessageInfoBindingModel model); + } +} diff --git a/ComputersShop/ComputersShopContracts/ViewModels/MessageInfoViewModel.cs b/ComputersShop/ComputersShopContracts/ViewModels/MessageInfoViewModel.cs new file mode 100644 index 0000000..196a14c --- /dev/null +++ b/ComputersShop/ComputersShopContracts/ViewModels/MessageInfoViewModel.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopContracts.ViewModels +{ + public class MessageInfoViewModel + { + 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/ComputersShop/ComputersShopDataModels/Models/IMessageInfoModel.cs b/ComputersShop/ComputersShopDataModels/Models/IMessageInfoModel.cs new file mode 100644 index 0000000..568d0f5 --- /dev/null +++ b/ComputersShop/ComputersShopDataModels/Models/IMessageInfoModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopDataModels.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/ComputersShop/ComputersShopDatabaseImplements/ComputersShopDatabase.cs b/ComputersShop/ComputersShopDatabaseImplements/ComputersShopDatabase.cs index 6b23961..f5abecc 100644 --- a/ComputersShop/ComputersShopDatabaseImplements/ComputersShopDatabase.cs +++ b/ComputersShop/ComputersShopDatabaseImplements/ComputersShopDatabase.cs @@ -25,5 +25,6 @@ namespace ComputersShopDatabaseImplements 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/ComputersShop/ComputersShopDatabaseImplements/Implements/MessageInfoStorage.cs b/ComputersShop/ComputersShopDatabaseImplements/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..7b5f583 --- /dev/null +++ b/ComputersShop/ComputersShopDatabaseImplements/Implements/MessageInfoStorage.cs @@ -0,0 +1,49 @@ +using ComputersShopContracts.BindingModels; +using ComputersShopContracts.SearchModels; +using ComputersShopContracts.StoragesContracts; +using ComputersShopContracts.ViewModels; +using ComputersShopDatabaseImplements.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopDatabaseImplements.Implements +{ + public class MessageInfoStorage: IMessageInfoStorage + { + public List GetFullList() + { + using var context = new ComputersShopDatabase(); + return context.Messages.Select(x => x.GetViewModel).ToList(); + } + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (model.MessageId == null) + { + return null; + } + using var context = new ComputersShopDatabase(); + return context.Messages.FirstOrDefault(x => x.MessageId == model.MessageId)?.GetViewModel; + } + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + using var context = new ComputersShopDatabase(); + model.ClientId = context.Clients.FirstOrDefault(x => x.Email.Equals(model.SenderName))?.Id; + var message = MessageInfo.Create(model); + if (message == null || context.Messages.Any(x => x.MessageId.Equals(model.MessageId))) + { + return null; + } + context.Messages.Add(message); + context.SaveChanges(); + return message.GetViewModel; + } + public List GetFiltredList(MessageInfoSearchModel model) + { + using var context = new ComputersShopDatabase(); + return context.Messages.Where(x => x.ClientId == model.ClientId).Select(x => x.GetViewModel).ToList(); + } + } +} diff --git a/ComputersShop/ComputersShopDatabaseImplements/Migrations/20240420140804_one.Designer.cs b/ComputersShop/ComputersShopDatabaseImplements/Migrations/20240502193720_FirstTime.Designer.cs similarity index 86% rename from ComputersShop/ComputersShopDatabaseImplements/Migrations/20240420140804_one.Designer.cs rename to ComputersShop/ComputersShopDatabaseImplements/Migrations/20240502193720_FirstTime.Designer.cs index cf133f6..d048c08 100644 --- a/ComputersShop/ComputersShopDatabaseImplements/Migrations/20240420140804_one.Designer.cs +++ b/ComputersShop/ComputersShopDatabaseImplements/Migrations/20240502193720_FirstTime.Designer.cs @@ -12,8 +12,8 @@ using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace ComputersShopDatabaseImplements.Migrations { [DbContext(typeof(ComputersShopDatabase))] - [Migration("20240420140804_one")] - partial class one + [Migration("20240502193720_FirstTime")] + partial class FirstTime { /// protected override void BuildTargetModel(ModelBuilder modelBuilder) @@ -143,6 +143,36 @@ namespace ComputersShopDatabaseImplements.Migrations b.ToTable("Implementers"); }); + modelBuilder.Entity("ComputersShopDatabaseImplements.Models.MessageInfo", b => + { + b.Property("MessageId") + .HasColumnType("nvarchar(450)"); + + b.Property("Body") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("int"); + + b.Property("DateDelivery") + .HasColumnType("datetime2"); + + b.Property("SenderName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Subject") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("MessageId"); + + b.HasIndex("ClientId"); + + b.ToTable("Messages"); + }); + modelBuilder.Entity("ComputersShopDatabaseImplements.Models.Order", b => { b.Property("Id") @@ -205,6 +235,15 @@ namespace ComputersShopDatabaseImplements.Migrations b.Navigation("Computer"); }); + modelBuilder.Entity("ComputersShopDatabaseImplements.Models.MessageInfo", b => + { + b.HasOne("ComputersShopDatabaseImplements.Models.Client", "Client") + .WithMany() + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + modelBuilder.Entity("ComputersShopDatabaseImplements.Models.Order", b => { b.HasOne("ComputersShopDatabaseImplements.Models.Client", "Client") diff --git a/ComputersShop/ComputersShopDatabaseImplements/Migrations/20240420140804_one.cs b/ComputersShop/ComputersShopDatabaseImplements/Migrations/20240502193720_FirstTime.cs similarity index 85% rename from ComputersShop/ComputersShopDatabaseImplements/Migrations/20240420140804_one.cs rename to ComputersShop/ComputersShopDatabaseImplements/Migrations/20240502193720_FirstTime.cs index 92c3719..1f3b337 100644 --- a/ComputersShop/ComputersShopDatabaseImplements/Migrations/20240420140804_one.cs +++ b/ComputersShop/ComputersShopDatabaseImplements/Migrations/20240502193720_FirstTime.cs @@ -6,7 +6,7 @@ using Microsoft.EntityFrameworkCore.Migrations; namespace ComputersShopDatabaseImplements.Migrations { /// - public partial class one : Migration + public partial class FirstTime : Migration { /// protected override void Up(MigrationBuilder migrationBuilder) @@ -70,6 +70,27 @@ namespace ComputersShopDatabaseImplements.Migrations table.PrimaryKey("PK_Implementers", x => x.Id); }); + migrationBuilder.CreateTable( + name: "Messages", + columns: table => new + { + MessageId = table.Column(type: "nvarchar(450)", nullable: false), + ClientId = table.Column(type: "int", nullable: true), + SenderName = table.Column(type: "nvarchar(max)", nullable: false), + DateDelivery = table.Column(type: "datetime2", nullable: false), + Subject = table.Column(type: "nvarchar(max)", nullable: false), + Body = table.Column(type: "nvarchar(max)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Messages", x => x.MessageId); + table.ForeignKey( + name: "FK_Messages_Clients_ClientId", + column: x => x.ClientId, + principalTable: "Clients", + principalColumn: "Id"); + }); + migrationBuilder.CreateTable( name: "ComputerComponents", columns: table => new @@ -144,6 +165,11 @@ namespace ComputersShopDatabaseImplements.Migrations table: "ComputerComponents", column: "ComputerId"); + migrationBuilder.CreateIndex( + name: "IX_Messages_ClientId", + table: "Messages", + column: "ClientId"); + migrationBuilder.CreateIndex( name: "IX_Orders_ClientId", table: "Orders", @@ -166,6 +192,9 @@ namespace ComputersShopDatabaseImplements.Migrations migrationBuilder.DropTable( name: "ComputerComponents"); + migrationBuilder.DropTable( + name: "Messages"); + migrationBuilder.DropTable( name: "Orders"); diff --git a/ComputersShop/ComputersShopDatabaseImplements/Migrations/ComputersShopDatabaseModelSnapshot.cs b/ComputersShop/ComputersShopDatabaseImplements/Migrations/ComputersShopDatabaseModelSnapshot.cs index bf958d7..ac6a706 100644 --- a/ComputersShop/ComputersShopDatabaseImplements/Migrations/ComputersShopDatabaseModelSnapshot.cs +++ b/ComputersShop/ComputersShopDatabaseImplements/Migrations/ComputersShopDatabaseModelSnapshot.cs @@ -140,6 +140,36 @@ namespace ComputersShopDatabaseImplements.Migrations b.ToTable("Implementers"); }); + modelBuilder.Entity("ComputersShopDatabaseImplements.Models.MessageInfo", b => + { + b.Property("MessageId") + .HasColumnType("nvarchar(450)"); + + b.Property("Body") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("int"); + + b.Property("DateDelivery") + .HasColumnType("datetime2"); + + b.Property("SenderName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Subject") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("MessageId"); + + b.HasIndex("ClientId"); + + b.ToTable("Messages"); + }); + modelBuilder.Entity("ComputersShopDatabaseImplements.Models.Order", b => { b.Property("Id") @@ -202,6 +232,15 @@ namespace ComputersShopDatabaseImplements.Migrations b.Navigation("Computer"); }); + modelBuilder.Entity("ComputersShopDatabaseImplements.Models.MessageInfo", b => + { + b.HasOne("ComputersShopDatabaseImplements.Models.Client", "Client") + .WithMany() + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + modelBuilder.Entity("ComputersShopDatabaseImplements.Models.Order", b => { b.HasOne("ComputersShopDatabaseImplements.Models.Client", "Client") diff --git a/ComputersShop/ComputersShopDatabaseImplements/Models/MessageInfo.cs b/ComputersShop/ComputersShopDatabaseImplements/Models/MessageInfo.cs new file mode 100644 index 0000000..2c8b115 --- /dev/null +++ b/ComputersShop/ComputersShopDatabaseImplements/Models/MessageInfo.cs @@ -0,0 +1,49 @@ +using ComputersShopContracts.BindingModels; +using ComputersShopContracts.ViewModels; +using ComputersShopDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopDatabaseImplements.Models +{ + public class MessageInfo: IMessageInfoModel + { + [Key] + public string MessageId { get; private set; } = string.Empty; + public int? ClientId { get; private set; } + public string SenderName { get; private set; } = string.Empty; + public DateTime DateDelivery { get; private set; } = DateTime.Now; + public string Subject { get; private set; } = string.Empty; + public string Body { get; private set; } = string.Empty; + public virtual Client? Client { get; private set; } + public static MessageInfo? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Subject = model.Subject, + ClientId = model.ClientId, + MessageId = model.MessageId, + SenderName = model.SenderName, + DateDelivery = model.DateDelivery, + }; + } + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Subject = Subject, + ClientId = ClientId, + MessageId = MessageId, + SenderName = SenderName, + DateDelivery = DateDelivery, + }; + } +} diff --git a/ComputersShop/ComputersShopListImplement/DataListSingleton.cs b/ComputersShop/ComputersShopListImplement/DataListSingleton.cs index 0af6562..9eb7079 100644 --- a/ComputersShop/ComputersShopListImplement/DataListSingleton.cs +++ b/ComputersShop/ComputersShopListImplement/DataListSingleton.cs @@ -1,4 +1,5 @@ using ComputersShopListImplement.Models; +using ComputersShopListImplements.Models; using System; using System.Collections.Generic; using System.Linq; @@ -15,6 +16,7 @@ namespace ComputersShopListImplement public List Computers { get; set; } public List Clients { get; set; } public List Implementers { get; set; } + public List Messages { get; set; } private DataListSingleton() { Components = new List(); @@ -22,7 +24,7 @@ namespace ComputersShopListImplement Computers = new List(); Clients = new List(); Implementers = new List(); - + Messages = new List(); } public static DataListSingleton GetInstance() { diff --git a/ComputersShop/ComputersShopListImplement/Implements/MessageInfoStorage.cs b/ComputersShop/ComputersShopListImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..0581f45 --- /dev/null +++ b/ComputersShop/ComputersShopListImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,65 @@ +using ComputersShopContracts.BindingModels; +using ComputersShopContracts.SearchModels; +using ComputersShopContracts.StoragesContracts; +using ComputersShopContracts.ViewModels; +using ComputersShopListImplement; +using ComputersShopListImplements.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopListImplements.Implements +{ + public class MessageInfoStorage: IMessageInfoStorage + { + private readonly DataListSingleton _source; + public MessageInfoStorage() + { + _source = DataListSingleton.GetInstance(); + } + public List GetFullList() + { + var result = new List(); + foreach (var message in _source.Messages) + { + result.Add(message.GetViewModel); + } + return result; + } + public List GetFiltredList(MessageInfoSearchModel model) + { + var result = new List(); + foreach (var message in _source.Messages) + { + if (message.ClientId.HasValue && message.ClientId == model.ClientId) + { + result.Add(message.GetViewModel); + } + } + return result; + } + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + foreach (var message in _source.Messages) + { + if (model.MessageId != null && model.MessageId.Equals(message.MessageId)) + { + return message.GetViewModel; + } + } + return null; + } + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = MessageInfo.Create(model); + if (newMessage == null) + { + return null; + } + _source.Messages.Add(newMessage); + return newMessage.GetViewModel; + } + } +} diff --git a/ComputersShop/ComputersShopListImplement/Models/MessageInfo.cs b/ComputersShop/ComputersShopListImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..09725a0 --- /dev/null +++ b/ComputersShop/ComputersShopListImplement/Models/MessageInfo.cs @@ -0,0 +1,46 @@ +using ComputersShopContracts.BindingModels; +using ComputersShopContracts.ViewModels; +using ComputersShopDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopListImplements.Models +{ + public class MessageInfo: IMessageInfoModel + { + public string MessageId { get; private set; } = string.Empty; + public int? ClientId { get; private set; } + public string SenderName { get; private set; } = string.Empty; + public DateTime DateDelivery { get; private set; } = DateTime.Now; + public string Subject { get; private set; } = string.Empty; + public string Body { get; private set; } = string.Empty; + public static MessageInfo? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Subject = model.Subject, + ClientId = model.ClientId, + MessageId = model.MessageId, + SenderName = model.SenderName, + DateDelivery = model.DateDelivery, + }; + } + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Subject = Subject, + ClientId = ClientId, + MessageId = MessageId, + SenderName = SenderName, + DateDelivery = DateDelivery, + }; + } +} diff --git a/ComputersShop/ComputersShopRestApi/Controllers/ClientController.cs b/ComputersShop/ComputersShopRestApi/Controllers/ClientController.cs index baa22eb..31d774f 100644 --- a/ComputersShop/ComputersShopRestApi/Controllers/ClientController.cs +++ b/ComputersShop/ComputersShopRestApi/Controllers/ClientController.cs @@ -13,12 +13,15 @@ namespace ComputersShopRestApi.Controllers { private readonly ILogger _logger; private readonly IClientLogic _logic; + private readonly IMessageInfoLogic _mailLogic; - public ClientController(IClientLogic logic, ILogger logger) + public ClientController(IClientLogic logic, ILogger logger, IMessageInfoLogic mailLogic) { _logger = logger; _logic = logic; - } + _mailLogic = mailLogic; + + } [HttpGet] public ClientViewModel? Login(string login, string password) @@ -62,5 +65,21 @@ namespace ComputersShopRestApi.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/ComputersShop/ComputersShopRestApi/Program.cs b/ComputersShop/ComputersShopRestApi/Program.cs index 040cb56..7723341 100644 --- a/ComputersShop/ComputersShopRestApi/Program.cs +++ b/ComputersShop/ComputersShopRestApi/Program.cs @@ -1,4 +1,6 @@ using ComputersShopBusinessLogic.BusinessLogics; +using ComputersShopBusinessLogic.MailWorker; +using ComputersShopContracts.BindingModels; using ComputersShopContracts.BuisnessLogicsContracts; using ComputersShopContracts.BusinessLogicsContracts; using ComputersShopContracts.StoragesContracts; @@ -13,10 +15,16 @@ builder.Logging.AddLog4Net("log4net.config"); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddTransient(); + +builder.Services.AddTransient(); builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle @@ -28,6 +36,17 @@ builder.Services.AddSwaggerGen(c => var app = builder.Build(); +var mailSender = app.Services.GetService(); +mailSender?.MailConfig(new MailConfigBindingModel +{ + MailLogin = builder.Configuration?.GetSection("MailLogin")?.Value?.ToString() ?? string.Empty, + MailPassword = builder.Configuration?.GetSection("MailPassword")?.Value?.ToString() ?? string.Empty, + SmtpClientHost = builder.Configuration?.GetSection("SmtpClientHost")?.Value?.ToString() ?? string.Empty, + SmtpClientPort = Convert.ToInt32(builder.Configuration?.GetSection("SmtpClientPort")?.Value?.ToString()), + PopHost = builder.Configuration?.GetSection("PopHost")?.Value?.ToString() ?? string.Empty, + PopPort = Convert.ToInt32(builder.Configuration?.GetSection("PopPort")?.Value?.ToString()) +}); + // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { diff --git a/ComputersShop/ComputersShopRestApi/appsettings.json b/ComputersShop/ComputersShopRestApi/appsettings.json index 10f68b8..9cc2c75 100644 --- a/ComputersShop/ComputersShopRestApi/appsettings.json +++ b/ComputersShop/ComputersShopRestApi/appsettings.json @@ -5,5 +5,13 @@ "Microsoft.AspNetCore": "Warning" } }, - "AllowedHosts": "*" + "AllowedHosts": "*", + + "SmtpClientHost": "smtp.mail.ru", + "SmtpClientPort": "587", + "PopHost": "pop.mail.ru", + "PopPort": "995", + "MailLogin": "pibd-21_barsukov@mail.ru", + "MailPassword": "Z62KAj7aEWnVhs9VHhKv" + }