From 1e75647ce8211fd77d41c45865c49633fe18fe2f Mon Sep 17 00:00:00 2001 From: Zakharov_Rostislav Date: Tue, 21 May 2024 18:07:25 +0400 Subject: [PATCH] lab-7-hard --- .../Implements/MessageInfoStorage.cs | 31 +- .../Models/MessageInfo.cs | 38 +- .../BlacksmithWorkshop/FormLetter.Designer.cs | 189 +++++++++ .../BlacksmithWorkshop/FormLetter.cs | 141 +++++++ .../BlacksmithWorkshop/FormLetter.resx | 120 ++++++ .../ViewMailForm.Designer.cs | 85 +++- .../BlacksmithWorkshop/ViewMailForm.cs | 102 ++++- .../BusinessLogics/MessageInfoLogic.cs | 31 +- .../BusinessLogics/OrderLogic.cs | 5 +- .../MailWorker/AbstractMailWorker.cs | 155 +++---- .../MailWorker/MailKitWorker.cs | 147 ++++--- .../BlacksmithWorkshopClientApp/APIClient.cs | 3 +- .../Controllers/HomeController.cs | 6 +- .../Views/Home/Mails.cshtml | 18 + .../Views/Shared/_Layout.cshtml | 2 +- .../MailReplySendInfoBindingModel.cs | 13 + .../BindingModels/MessageInfoBindingModel .cs | 5 +- .../IMessageInfoLogic.cs | 6 +- .../SearchModels/MessageInfoSearchModel.cs | 4 +- .../StoragesContracts/IMessageInfoStorage.cs | 3 +- .../ViewModels/MessageInfoViewModel.cs | 7 +- .../Models/IMessageInfoModel.cs | 5 +- .../BlacksmithWorkshopDataBase.cs | 2 +- .../Implements/MessageInfoStorage.cs | 69 ++- .../20240521123604_InitialCreate.Designer.cs | 394 ++++++++++++++++++ ...ate.cs => 20240521123604_InitialCreate.cs} | 42 ++ ...BlacksmithWorkshopDataBaseModelSnapshot.cs | 17 + .../Models/MessageInfo.cs | 50 ++- .../Implements/MessageInfoStorage.cs | 55 ++- .../Models/MessageInfo.cs | 29 +- .../Controllers/ClientController.cs | 36 +- 31 files changed, 1545 insertions(+), 265 deletions(-) create mode 100644 BlacksmithWorkshop/BlacksmithWorkshop/FormLetter.Designer.cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshop/FormLetter.cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshop/FormLetter.resx create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopContracts/BindingModels/MailReplySendInfoBindingModel.cs create mode 100644 BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/20240521123604_InitialCreate.Designer.cs rename BlacksmithWorkshop/BlacksmithWorkshopDatabaseImplement/Migrations/{20240507165329_InitialCreate.cs => 20240521123604_InitialCreate.cs} (83%) diff --git a/BlacksmithWorkshop/BlackcmithWorkshopFileImplement/Implements/MessageInfoStorage.cs b/BlacksmithWorkshop/BlackcmithWorkshopFileImplement/Implements/MessageInfoStorage.cs index 9137086..9134528 100644 --- a/BlacksmithWorkshop/BlackcmithWorkshopFileImplement/Implements/MessageInfoStorage.cs +++ b/BlacksmithWorkshop/BlackcmithWorkshopFileImplement/Implements/MessageInfoStorage.cs @@ -28,12 +28,19 @@ namespace BlacksmithWorkshopFileImplement.Implements return null; } public List GetFilteredList(MessageInfoSearchModel model) - { - return _source.Messages - .Where(x => x.ClientId == model.ClientId) - .Select(x => x.GetViewModel) + { + var res = _source.Messages + .Where(x => !model.ClientId.HasValue || x.ClientId == model.ClientId) + .Select(x => x.GetViewModel); + if (!(model.PageIndex.HasValue && model.PageLength.HasValue)) + { + return res.ToList(); + } + return res + .Skip((model.PageIndex.Value - 1) * model.PageLength.Value) + .Take(model.PageLength.Value) .ToList(); - } + } public List GetFullList() { return _source.Messages @@ -50,6 +57,16 @@ namespace BlacksmithWorkshopFileImplement.Implements _source.Messages.Add(newMessage); _source.SaveMessages(); return newMessage.GetViewModel; - } - } + } + public MessageInfoViewModel? Update(MessageInfoBindingModel model) + { + var res = _source.Messages.FirstOrDefault(x => x.MessageId.Equals(model.MessageId)); + if (res != null) + { + res.Update(model); + _source.SaveMessages(); + } + return res?.GetViewModel; + } + } } diff --git a/BlacksmithWorkshop/BlackcmithWorkshopFileImplement/Models/MessageInfo.cs b/BlacksmithWorkshop/BlackcmithWorkshopFileImplement/Models/MessageInfo.cs index f487570..0eadf4d 100644 --- a/BlacksmithWorkshop/BlackcmithWorkshopFileImplement/Models/MessageInfo.cs +++ b/BlacksmithWorkshop/BlackcmithWorkshopFileImplement/Models/MessageInfo.cs @@ -18,7 +18,10 @@ namespace BlacksmithWorkshopFileImplement.Models 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) + public bool IsReaded { get; private set; } + public bool IsReply { get; private set; } + public string? ReplyMessageId { get; private set; } = string.Empty; + public static MessageInfo? Create(MessageInfoBindingModel model) { if (model == null) { @@ -32,7 +35,10 @@ namespace BlacksmithWorkshopFileImplement.Models MessageId = model.MessageId, SenderName = model.SenderName, DateDelivery = model.DateDelivery, - }; + IsReply = model.IsReply, + IsReaded = model.IsReaded, + ReplyMessageId = model.ReplyMessageId, + }; } public static MessageInfo? Create(XElement element) { @@ -48,9 +54,21 @@ namespace BlacksmithWorkshopFileImplement.Models MessageId = element.Attribute("MessageId")!.Value, SenderName = element.Attribute("SenderName")!.Value, DateDelivery = Convert.ToDateTime(element.Attribute("DateDelivery")!.Value), - }; + IsReply = Convert.ToBoolean(element.Attribute("IsReply")!.Value), + IsReaded = Convert.ToBoolean(element.Attribute("HasRead")!.Value), + ReplyMessageId = element.Attribute("ReplyMessageId")!.Value, + }; } - public MessageInfoViewModel GetViewModel => new() + public void Update(MessageInfoBindingModel model) + { + if (model == null) + { + return; + } + IsReply = model.IsReply; + IsReaded = model.IsReaded; + } + public MessageInfoViewModel GetViewModel => new() { Body = Body, Subject = Subject, @@ -58,14 +76,20 @@ namespace BlacksmithWorkshopFileImplement.Models MessageId = MessageId, SenderName = SenderName, DateDelivery = DateDelivery, - }; + IsReply = IsReply, + IsReaded = IsReaded, + ReplyMessageId = ReplyMessageId, + }; public XElement GetXElement => new("MessageInfo", new XAttribute("Body", Body), new XAttribute("Subject", Subject), new XAttribute("ClientId", ClientId ?? 0), new XAttribute("MessageId", MessageId), new XAttribute("SenderName", SenderName), - new XAttribute("DateDelivery", DateDelivery) - ); + new XAttribute("DateDelivery", DateDelivery), + new XAttribute("IsReply", IsReply), + new XAttribute("IsReaded", IsReaded), + new XAttribute("ReplyMessageId", ReplyMessageId ?? "") + ); } } diff --git a/BlacksmithWorkshop/BlacksmithWorkshop/FormLetter.Designer.cs b/BlacksmithWorkshop/BlacksmithWorkshop/FormLetter.Designer.cs new file mode 100644 index 0000000..4385684 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshop/FormLetter.Designer.cs @@ -0,0 +1,189 @@ +namespace BlacksmithWorkshop +{ + partial class FormLetter + { + /// + /// 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() + { + textBoxEmail = new TextBox(); + labelAdress = new Label(); + labelSubject = new Label(); + textBoxSubject = new TextBox(); + labelBody = new Label(); + textBoxBody = new TextBox(); + buttonClose = new Button(); + buttonReply = new Button(); + labelDate = new Label(); + textBoxDate = new TextBox(); + buttonSend = new Button(); + SuspendLayout(); + // + // textBoxEmail + // + textBoxEmail.Location = new Point(63, 4); + textBoxEmail.Margin = new Padding(3, 2, 3, 2); + textBoxEmail.Name = "textBoxEmail"; + textBoxEmail.ReadOnly = true; + textBoxEmail.Size = new Size(163, 23); + textBoxEmail.TabIndex = 0; + // + // labelAdress + // + labelAdress.AutoSize = true; + labelAdress.Location = new Point(10, 7); + labelAdress.Name = "labelAdress"; + labelAdress.Size = new Size(43, 15); + labelAdress.TabIndex = 1; + labelAdress.Text = "Адрес:"; + // + // labelSubject + // + labelSubject.AutoSize = true; + labelSubject.Location = new Point(10, 41); + labelSubject.Name = "labelSubject"; + labelSubject.Size = new Size(37, 15); + labelSubject.TabIndex = 2; + labelSubject.Text = "Тема:"; + // + // textBoxSubject + // + textBoxSubject.Location = new Point(63, 39); + textBoxSubject.Margin = new Padding(3, 2, 3, 2); + textBoxSubject.Name = "textBoxSubject"; + textBoxSubject.ReadOnly = true; + textBoxSubject.Size = new Size(484, 23); + textBoxSubject.TabIndex = 3; + // + // labelBody + // + labelBody.AutoSize = true; + labelBody.Location = new Point(10, 72); + labelBody.Name = "labelBody"; + labelBody.Size = new Size(83, 15); + labelBody.TabIndex = 4; + labelBody.Text = "Текст письма:"; + // + // textBoxBody + // + textBoxBody.Location = new Point(10, 89); + textBoxBody.Margin = new Padding(3, 2, 3, 2); + textBoxBody.Multiline = true; + textBoxBody.Name = "textBoxBody"; + textBoxBody.ReadOnly = true; + textBoxBody.Size = new Size(536, 140); + textBoxBody.TabIndex = 5; + // + // buttonClose + // + buttonClose.Location = new Point(430, 244); + buttonClose.Margin = new Padding(3, 2, 3, 2); + buttonClose.Name = "buttonClose"; + buttonClose.Size = new Size(97, 29); + buttonClose.TabIndex = 6; + buttonClose.Text = "Закрыть"; + buttonClose.UseVisualStyleBackColor = true; + buttonClose.Click += buttonClose_Click; + // + // buttonReply + // + buttonReply.Location = new Point(327, 244); + buttonReply.Margin = new Padding(3, 2, 3, 2); + buttonReply.Name = "buttonReply"; + buttonReply.Size = new Size(97, 29); + buttonReply.TabIndex = 7; + buttonReply.Text = "Ответить"; + buttonReply.UseVisualStyleBackColor = true; + buttonReply.Click += buttonReply_Click; + // + // labelDate + // + labelDate.AutoSize = true; + labelDate.Location = new Point(243, 7); + labelDate.Name = "labelDate"; + labelDate.Size = new Size(101, 15); + labelDate.TabIndex = 8; + labelDate.Text = "Дата получения: "; + // + // textBoxDate + // + textBoxDate.Location = new Point(360, 4); + textBoxDate.Margin = new Padding(3, 2, 3, 2); + textBoxDate.Name = "textBoxDate"; + textBoxDate.ReadOnly = true; + textBoxDate.Size = new Size(187, 23); + textBoxDate.TabIndex = 9; + // + // buttonSend + // + buttonSend.Location = new Point(224, 244); + buttonSend.Margin = new Padding(3, 2, 3, 2); + buttonSend.Name = "buttonSend"; + buttonSend.Size = new Size(97, 29); + buttonSend.TabIndex = 10; + buttonSend.Text = "Отправить"; + buttonSend.UseVisualStyleBackColor = true; + buttonSend.Visible = false; + buttonSend.Click += buttonSend_Click; + // + // FormLetter + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(556, 283); + Controls.Add(buttonSend); + Controls.Add(textBoxDate); + Controls.Add(labelDate); + Controls.Add(buttonReply); + Controls.Add(buttonClose); + Controls.Add(textBoxBody); + Controls.Add(labelBody); + Controls.Add(textBoxSubject); + Controls.Add(labelSubject); + Controls.Add(labelAdress); + Controls.Add(textBoxEmail); + Margin = new Padding(3, 2, 3, 2); + Name = "FormLetter"; + Text = "Письмо"; + Load += FormLetter_Load; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private TextBox textBoxEmail; + private Label labelAdress; + private Label labelSubject; + private TextBox textBoxSubject; + private Label labelBody; + private TextBox textBoxBody; + private Button buttonClose; + private Button buttonReply; + private Label labelDate; + private TextBox textBoxDate; + private Button buttonSend; + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshop/FormLetter.cs b/BlacksmithWorkshop/BlacksmithWorkshop/FormLetter.cs new file mode 100644 index 0000000..f5e8129 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshop/FormLetter.cs @@ -0,0 +1,141 @@ +using BlacksmithWorkshopBusinessLogic.MailWorker; +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.BusinessLogicsContracts; +using BlacksmithWorkshopContracts.SearchModels; +using BlacksmithWorkshopContracts.ViewModels; +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; +using System.Windows.Forms.VisualStyles; + +namespace BlacksmithWorkshop +{ + public partial class FormLetter : Form + { + private readonly ILogger _logger; + private readonly IMessageInfoLogic _logic; + private readonly AbstractMailWorker _worker; + public MessageInfoViewModel? model; + public string? messageId; + public FormLetter(ILogger logger, IMessageInfoLogic logic, AbstractMailWorker worker) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + _worker = worker; + } + private void FormLetter_Load(object sender, EventArgs e) + { + if (!string.IsNullOrEmpty(messageId)) + { + ReloadLetter(); + return; + } + else if (model != null) + { + ConfigurateToCreateAnsver(); + return; + } + _logger.LogError("Для формы не переданно сведений о письме, на которое отвечаем!"); + DialogResult = DialogResult.Abort; + Close(); + return; + } + private void ReloadLetter() + { + _logger.LogInformation("Загрузка существующего письма с id:{}", messageId); + model = _logic.ReadElement(new MessageInfoSearchModel + { + MessageId = messageId + }); + if (model != null) + { + _logger.LogInformation("Письмо найдено"); + textBoxEmail.Text = model.SenderName; + textBoxDate.Text = model.DateDelivery.ToString(); + textBoxSubject.Text = model.Subject; + textBoxBody.Text = model.Body; + if (model.IsReply) + { + _logger.LogInformation("Письмо само и есть ответ"); + buttonReply.Visible = false; + } + else + { + if (!string.IsNullOrEmpty(model.ReplyMessageId)) + { + _logger.LogInformation("У письма есть ответ."); + buttonReply.Text = "Прочитать ответ"; + } + } + return; + } + _logger.LogWarning("Письмо с таким id не удалось найти"); + DialogResult = DialogResult.Abort; + Close(); + return; + } + private void ConfigurateToCreateAnsver() + { + textBoxEmail.Text = model.SenderName; + labelDate.Visible = false; + textBoxDate.Visible = false; + textBoxSubject.Text = $"re: {model.Subject}"; + textBoxBody.ReadOnly = false; + buttonReply.Visible = false; + buttonSend.Visible = true; + _logger.LogInformation("Запущена форма создания нового письма - ответа"); + } + private void buttonClose_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + private void buttonReply_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormLetter)); + if (service is FormLetter form) + { + if (!string.IsNullOrEmpty(model.ReplyMessageId)) + { + form.messageId = model.ReplyMessageId; + } + else + { + form.model = model; + } + + if (form.ShowDialog() != DialogResult.Cancel) + { + buttonReply.Visible = false; + } + } + } + private void buttonSend_Click(object sender, EventArgs e) + { + if (model == null) + { + return; + } + string subject = textBoxSubject.Text; + string text = textBoxBody.Text; + + Task.Run(() => _worker.MailSendReplyAsync(new MailReplySendInfoBindingModel + { + MailAddress = model.SenderName, + Subject = subject, + Text = text, + ParentMessageId = model.MessageId, + })); + DialogResult = DialogResult.OK; + Close(); + } + } +} diff --git a/BlacksmithWorkshop/BlacksmithWorkshop/FormLetter.resx b/BlacksmithWorkshop/BlacksmithWorkshop/FormLetter.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshop/FormLetter.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshop/ViewMailForm.Designer.cs b/BlacksmithWorkshop/BlacksmithWorkshop/ViewMailForm.Designer.cs index d7351ac..1134e76 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshop/ViewMailForm.Designer.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshop/ViewMailForm.Designer.cs @@ -28,37 +28,108 @@ /// private void InitializeComponent() { + panel1 = new Panel(); dataGridView = new DataGridView(); + buttonOpen = new Button(); + numericUpDownPage = new NumericUpDown(); + buttonPreveous = new Button(); + buttonNext = new Button(); + panel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + ((System.ComponentModel.ISupportInitialize)numericUpDownPage).BeginInit(); SuspendLayout(); // + // panel1 + // + panel1.Controls.Add(dataGridView); + panel1.Location = new Point(3, 1); + panel1.Name = "panel1"; + panel1.Size = new Size(696, 323); + panel1.TabIndex = 0; + // // dataGridView // + dataGridView.AllowUserToAddRows = false; + dataGridView.AllowUserToDeleteRows = false; dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; - dataGridView.Location = new Point(10, 9); + dataGridView.Dock = DockStyle.Fill; + dataGridView.Location = new Point(0, 0); dataGridView.Margin = new Padding(3, 2, 3, 2); dataGridView.Name = "dataGridView"; + dataGridView.ReadOnly = true; dataGridView.RowHeadersWidth = 51; dataGridView.RowTemplate.Height = 29; - dataGridView.Size = new Size(679, 320); - dataGridView.TabIndex = 0; + dataGridView.Size = new Size(696, 323); + dataGridView.TabIndex = 2; + // + // buttonOpen + // + buttonOpen.Location = new Point(722, 187); + buttonOpen.Name = "buttonOpen"; + buttonOpen.Size = new Size(74, 23); + buttonOpen.TabIndex = 1; + buttonOpen.Text = "Прочитать"; + buttonOpen.UseVisualStyleBackColor = true; + buttonOpen.Click += buttonOpen_Click; + // + // numericUpDownPage + // + numericUpDownPage.Location = new Point(722, 215); + numericUpDownPage.Margin = new Padding(3, 2, 3, 2); + numericUpDownPage.Name = "numericUpDownPage"; + numericUpDownPage.Size = new Size(74, 23); + numericUpDownPage.TabIndex = 4; + numericUpDownPage.ValueChanged += numericUpDownPage_ValueChanged; + // + // buttonPreveous + // + buttonPreveous.Location = new Point(722, 242); + buttonPreveous.Margin = new Padding(3, 2, 3, 2); + buttonPreveous.Name = "buttonPreveous"; + buttonPreveous.Size = new Size(34, 22); + buttonPreveous.TabIndex = 5; + buttonPreveous.Text = "<-"; + buttonPreveous.UseVisualStyleBackColor = true; + buttonPreveous.Click += buttonPreveous_Click; + // + // buttonNext + // + buttonNext.Location = new Point(763, 242); + buttonNext.Margin = new Padding(3, 2, 3, 2); + buttonNext.Name = "buttonNext"; + buttonNext.Size = new Size(34, 22); + buttonNext.TabIndex = 6; + buttonNext.Text = "->"; + buttonNext.UseVisualStyleBackColor = true; + buttonNext.Click += buttonNext_Click; // // ViewMailForm // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(700, 338); - Controls.Add(dataGridView); + ClientSize = new Size(809, 321); + Controls.Add(buttonNext); + Controls.Add(buttonPreveous); + Controls.Add(numericUpDownPage); + Controls.Add(buttonOpen); + Controls.Add(panel1); Margin = new Padding(3, 2, 3, 2); Name = "ViewMailForm"; - Text = "Почта"; + Text = "Письма"; Load += ViewMailForm_Load; + panel1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ((System.ComponentModel.ISupportInitialize)numericUpDownPage).EndInit(); ResumeLayout(false); } #endregion + private Panel panel1; private DataGridView dataGridView; - } + private Button buttonOpen; + private NumericUpDown numericUpDownPage; + private Button buttonPreveous; + private Button buttonNext; + } } \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshop/ViewMailForm.cs b/BlacksmithWorkshop/BlacksmithWorkshop/ViewMailForm.cs index 04ab472..17727d7 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshop/ViewMailForm.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshop/ViewMailForm.cs @@ -1,4 +1,6 @@ -using BlacksmithWorkshopContracts.BusinessLogicsContracts; +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.BusinessLogicsContracts; +using BlacksmithWorkshopContracts.SearchModels; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; @@ -16,7 +18,9 @@ namespace BlacksmithWorkshop { private readonly ILogger _logger; private readonly IMessageInfoLogic _logic; - public ViewMailForm(ILogger logger, IMessageInfoLogic logic) + private int currentPage = 1; + private int pageLength = 2; + public ViewMailForm(ILogger logger, IMessageInfoLogic logic) { InitializeComponent(); _logger = logger; @@ -24,24 +28,80 @@ namespace BlacksmithWorkshop } private void ViewMailForm_Load(object sender, EventArgs e) { - try - { - var list = _logic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["ClientId"].Visible = false; - dataGridView.Columns["MessageId"].Visible = false; - dataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } - _logger.LogInformation("Загрузка списка писем"); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки писем"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, - MessageBoxIcon.Error); - } + LoadData(); + numericUpDownPage.Value = pageLength; } - } + private void LoadData() + { + try + { + var list = _logic.ReadList(new MessageInfoSearchModel() + { + PageLength = pageLength, + PageIndex = currentPage + }); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["MessageId"].Visible = false; + dataGridView.Columns["ReplyMessageId"].Visible = false; + dataGridView.Columns["Reply"].Visible = false; + dataGridView.Columns["IsReply"].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 buttonOpen_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count <= 0) + return; + + var service = Program.ServiceProvider?.GetService(typeof(FormLetter)); + if (service is FormLetter form) + { + string? messageId = dataGridView.SelectedRows[0].Cells["MessageId"].Value.ToString(); + if (messageId == null) return; + form.messageId = messageId; + + if (!Convert.ToBoolean(dataGridView.SelectedRows[0].Cells["IsReaded"].Value)) + { + _logic.Update(new MessageInfoBindingModel + { + MessageId = messageId, + IsReaded = true, + ReplyMessageId = dataGridView.SelectedRows[0].Cells["ReplyMessageId"].Value?.ToString() + }); + } + + form.ShowDialog(); + LoadData(); + } + } + + private void buttonPreveous_Click(object sender, EventArgs e) + { + currentPage = Math.Max(1, currentPage - 1); + LoadData(); + } + + private void buttonNext_Click(object sender, EventArgs e) + { + currentPage++; + LoadData(); + } + + private void numericUpDownPage_ValueChanged(object sender, EventArgs e) + { + pageLength = Math.Max(1, (int)numericUpDownPage.Value); + LoadData(); + } + } } diff --git a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/MessageInfoLogic.cs b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/MessageInfoLogic.cs index 8a5a6f4..c575e04 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/MessageInfoLogic.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/MessageInfoLogic.cs @@ -16,11 +16,11 @@ namespace BlacksmithWorkshopBusinessLogic.BusinessLogics { private readonly ILogger _logger; private readonly IMessageInfoStorage _messageInfoStorage; - public MessageInfoLogic(ILogger logger, IMessageInfoStorage MessageInfoStorage) + public MessageInfoLogic(ILogger logger, IMessageInfoStorage MessageInfoStorage) { _logger = logger; _messageInfoStorage = MessageInfoStorage; - } + } public bool Create(MessageInfoBindingModel model) { if (_messageInfoStorage.Insert(model) == null) @@ -41,6 +41,29 @@ namespace BlacksmithWorkshopBusinessLogic.BusinessLogics } _logger.LogInformation("ReadList. Count:{Count}", list.Count); return list; - } - } + } + public MessageInfoViewModel? ReadElement(MessageInfoSearchModel model) + { + _logger.LogInformation("ReadElement. MessageId:{MessageId}", model?.MessageId); + if (model == null) + throw new ArgumentNullException(nameof(model)); + var element = _messageInfoStorage.GetElement(model); + if (element == null) + { + _logger.LogWarning("ReadElement element not found"); + return null; + } + _logger.LogInformation("ReadElement find. Id:{Id}", element.MessageId); + return element; + } + public bool Update(MessageInfoBindingModel model) + { + if (_messageInfoStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + return true; + } + } } diff --git a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/OrderLogic.cs b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/OrderLogic.cs index b77d6c2..e6ab3c9 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/OrderLogic.cs @@ -26,9 +26,8 @@ namespace BlacksmithWorkshopBusinessLogic.BusinessLogics private readonly IClientLogic _clientLogic; static readonly object locker = new object(); public OrderLogic(ILogger logger, IOrderStorage orderStorage, - IManufactureStorage manufactureStorage, IShopLogic shopLogic, IShopStorage shopStorage) - public OrderLogic(ILogger logger, IOrderStorage orderStorage, - AbstractMailWorker mailWorker, IClientLogic clientLogic) + AbstractMailWorker mailWorker, IClientLogic clientLogic, IShopLogic shopLogic, + IManufactureStorage manufactureStorage, IShopStorage shopStorage) { _orderStorage = orderStorage; _logger = logger; diff --git a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/MailWorker/AbstractMailWorker.cs b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/MailWorker/AbstractMailWorker.cs index 03e517e..981528e 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/MailWorker/AbstractMailWorker.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/MailWorker/AbstractMailWorker.cs @@ -9,75 +9,88 @@ using System.Threading.Tasks; namespace BlacksmithWorkshopBusinessLogic.MailWorker { - public abstract class AbstractMailWorker - { - protected string _mailLogin = string.Empty; - protected string _mailPassword = string.Empty; - protected string _smtpClientHost = string.Empty; - protected int _smtpClientPort; - protected string _popHost = string.Empty; - protected int _popPort; - private readonly IMessageInfoLogic _messageInfoLogic; - private readonly ILogger _logger; - public AbstractMailWorker(ILogger logger, - IMessageInfoLogic messageInfoLogic) - { - _logger = logger; - _messageInfoLogic = messageInfoLogic; - } - public void MailConfig(MailConfigBindingModel config) - { - _mailLogin = config.MailLogin; - _mailPassword = config.MailPassword; - _smtpClientHost = config.SmtpClientHost; - _smtpClientPort = config.SmtpClientPort; - _popHost = config.PopHost; - _popPort = config.PopPort; - _logger.LogDebug( - "Config: {login}, {password}, {clientHost}, { clientPOrt}, { popHost}, { popPort}", - _mailLogin, _mailPassword, _smtpClientHost, _smtpClientPort, _popHost, _popPort); - } - public async void MailSendAsync(MailSendInfoBindingModel info) - { - if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword)) - { - return; - } - if (string.IsNullOrEmpty(_smtpClientHost) || _smtpClientPort == 0) - { - return; - } - if (string.IsNullOrEmpty(info.MailAddress) || string.IsNullOrEmpty(info.Subject) || - string.IsNullOrEmpty(info.Text)) - { - return; - } - _logger.LogDebug("Send Mail: {To}, {Subject}", info.MailAddress, info.Subject); - await SendMailAsync(info); - } - public async void MailCheck() - { - if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword)) - { - return; - } - if (string.IsNullOrEmpty(_popHost) || _popPort == 0) - { - return; - } - if (_messageInfoLogic == null) - { - return; - } - var list = await ReceiveMailAsync(); - _logger.LogDebug("Check Mail: {Count} new mails", list.Count); - foreach (var mail in list) - { - _messageInfoLogic.Create(mail); - } - } - protected abstract Task SendMailAsync(MailSendInfoBindingModel info); - protected abstract Task> - ReceiveMailAsync(); - } + 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.Length, _smtpClientHost, _smtpClientPort, _popHost, _popPort); + } + public async void MailSendAsync(MailSendInfoBindingModel info) + { + if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword)) + return; + if (string.IsNullOrEmpty(_smtpClientHost) || _smtpClientPort == 0) + return; + if (string.IsNullOrEmpty(info.MailAddress) || string.IsNullOrEmpty(info.Subject) || string.IsNullOrEmpty(info.Text)) + return; + _logger.LogDebug("Send Mail: {To}, {Subject}", info.MailAddress, info.Subject); + await SendMailAsync(info); + } + public async void MailCheck() + { + if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword)) + return; + if (string.IsNullOrEmpty(_popHost) || _popPort == 0) + return; + if (_messageInfoLogic == null) + return; + var list = await ReceiveMailAsync(); + _logger.LogDebug("Check Mail: {Count} new mails", list.Count); + foreach (var mail in list) + _messageInfoLogic.Create(mail); + } + public async void MailSendReplyAsync(MailReplySendInfoBindingModel 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) || string.IsNullOrEmpty(info.ParentMessageId)) + return; + _logger.LogDebug("Send Mail as reply: {To}, {Subject}, {parentId}", info.MailAddress, info.Subject, info.ParentMessageId); + string? messageId = await SendMailAsync(info); + if (string.IsNullOrEmpty(messageId)) + throw new InvalidOperationException("Непредвиденная ошибка при отправке сообщения в ответ"); + if (_messageInfoLogic.Create(new MessageInfoBindingModel + { + MessageId = messageId, + DateDelivery = DateTime.Now, + SenderName = _mailLogin, + IsReply = true, + Subject = info.Subject, + Body = info.Text, + })) + { + _messageInfoLogic.Update(new MessageInfoBindingModel() + { + MessageId = info.ParentMessageId, + ReplyMessageId = messageId, + IsReaded = true + }); + } + } + protected abstract Task SendMailAsync(MailSendInfoBindingModel info); + protected abstract Task> ReceiveMailAsync(); + } } diff --git a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/MailWorker/MailKitWorker.cs b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/MailWorker/MailKitWorker.cs index bfa6985..7921e70 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/MailWorker/MailKitWorker.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/MailWorker/MailKitWorker.cs @@ -13,69 +13,86 @@ using System.Threading.Tasks; namespace BlacksmithWorkshopBusinessLogic.MailWorker { - public class MailKitWorker : AbstractMailWorker - { - public MailKitWorker(ILogger logger, IMessageInfoLogic - messageInfoLogic) : base(logger, messageInfoLogic) { } - protected override async Task SendMailAsync(MailSendInfoBindingModel info) - { - using var objMailMessage = new MailMessage(); - using var objSmtpClient = new SmtpClient(_smtpClientHost, _smtpClientPort); - try - { - objMailMessage.From = new MailAddress(_mailLogin); - objMailMessage.To.Add(new MailAddress(info.MailAddress)); - objMailMessage.Subject = info.Subject; - objMailMessage.Body = info.Text; - objMailMessage.SubjectEncoding = Encoding.UTF8; - objMailMessage.BodyEncoding = Encoding.UTF8; - objSmtpClient.UseDefaultCredentials = false; - objSmtpClient.EnableSsl = true; - objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; - objSmtpClient.Credentials = new NetworkCredential(_mailLogin, _mailPassword); - await Task.Run(() => objSmtpClient.Send(objMailMessage)); - } - catch (Exception) - { - throw; - } - } - protected override async Task> - ReceiveMailAsync() - { - var list = new List(); - using var client = new Pop3Client(); - await Task.Run(() => - { - try - { - client.Connect(_popHost, _popPort, - SecureSocketOptions.SslOnConnect); - client.Authenticate(_mailLogin, _mailPassword); - for (int i = 0; i < client.Count; i++) - { - var message = client.GetMessage(i); - foreach (var mail in message.From.Mailboxes) - { - list.Add(new MessageInfoBindingModel - { - DateDelivery = message.Date.DateTime, - MessageId = message.MessageId, - SenderName = mail.Address, - Subject = message.Subject, - Body = message.TextBody - }); - } - } - } - catch (AuthenticationException) - { } - finally - { - client.Disconnect(true); - } - }); - return list; - } - } + public class MailKitWorker : AbstractMailWorker + { + public MailKitWorker(ILogger logger, IMessageInfoLogic messageInfoLogic) : base(logger, messageInfoLogic) { } + protected override async Task SendMailAsync(MailSendInfoBindingModel info) + { + string? resount = null; + using var objMailMessage = new MailMessage(); + using var objSmtpClient = new SmtpClient(_smtpClientHost, _smtpClientPort); + try + { + ConfigurateSmtpClient(objSmtpClient); + CreateMessage(objMailMessage, info); + + if (info is MailReplySendInfoBindingModel replyInfo) + { + objMailMessage.Headers.Add("In-Reply-To", replyInfo.ParentMessageId); + objMailMessage.Headers.Add("References", replyInfo.ParentMessageId); + + string messageGuid = Guid.NewGuid().ToString(); + objMailMessage.Headers.Add("Message-Id", messageGuid); + resount = messageGuid; + } + await Task.Run(() => objSmtpClient.Send(objMailMessage)); + } + catch (Exception) + { + throw; + } + return resount; + } + protected override async Task> ReceiveMailAsync() + { + var list = new List(); + using var client = new Pop3Client(); + await Task.Run(() => + { + try + { + client.Connect(_popHost, _popPort, SecureSocketOptions.SslOnConnect); + client.Authenticate(_mailLogin, _mailPassword); + for (int i = 0; i < client.Count; i++) + { + var message = client.GetMessage(i); + foreach (var mail in message.From.Mailboxes) + { + list.Add(new MessageInfoBindingModel + { + DateDelivery = message.Date.DateTime, + MessageId = message.MessageId, + SenderName = mail.Address, + Subject = message.Subject, + Body = message.TextBody + }); + } + } + } + catch (AuthenticationException) + { } + finally + { + client.Disconnect(true); + } + }); + return list; + } + private void CreateMessage(MailMessage objMailMessage, MailSendInfoBindingModel info) + { + 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; + } + private void ConfigurateSmtpClient(SmtpClient objSmtpClient) + { + objSmtpClient.UseDefaultCredentials = false; + objSmtpClient.EnableSsl = true; + objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; + objSmtpClient.Credentials = new NetworkCredential(_mailLogin, _mailPassword); + } + } } diff --git a/BlacksmithWorkshop/BlacksmithWorkshopClientApp/APIClient.cs b/BlacksmithWorkshop/BlacksmithWorkshopClientApp/APIClient.cs index 1824cf9..51304df 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopClientApp/APIClient.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopClientApp/APIClient.cs @@ -9,7 +9,8 @@ namespace BlacksmithWorkshopClientApp { private static readonly HttpClient _client = new(); public static ClientViewModel? Client { get; set; } = null; - public static void Connect(IConfiguration configuration) + public static int MailPage { get; set; } = 1; + public static void Connect(IConfiguration configuration) { _client.BaseAddress = new Uri(configuration["IPAddress"]); _client.DefaultRequestHeaders.Accept.Clear(); diff --git a/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Controllers/HomeController.cs b/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Controllers/HomeController.cs index 21a93fb..6df7466 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Controllers/HomeController.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Controllers/HomeController.cs @@ -144,14 +144,14 @@ namespace BlacksmithWorkshopClientApp.Controllers return Math.Round(count * (_manufacture?.Price ?? 1), 2); } [HttpGet] - public IActionResult Mails() + public IActionResult Mails(int page = 1) { if (APIClient.Client == null) { return Redirect("~/Home/Enter"); } - return - View(APIClient.GetRequest>($"api/client/getmessages?clientId={APIClient.Client.Id}")); + page = Math.Max(page, 1); + return View(APIClient.GetRequest>($"api/client/getmessages?clientId={APIClient.Client.Id}&page={page}")); } } } diff --git a/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Views/Home/Mails.cshtml b/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Views/Home/Mails.cshtml index 9741b90..707747a 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Views/Home/Mails.cshtml +++ b/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Views/Home/Mails.cshtml @@ -1,5 +1,6 @@ @using BlacksmithWorkshopContracts.ViewModels @model List +@Url.ActionContext.RouteData.Values["page"] @{ ViewData["Title"] = "Mails"; } @@ -45,5 +46,22 @@ } +
+ @{ + int page = int.Parse(Context.Request.Query["page"]); +
+ +
+ if (page > 1) + { + <- + } + else + { +

<-

+ } + -> + } +
} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Views/Shared/_Layout.cshtml b/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Views/Shared/_Layout.cshtml index f490f14..a1c6313 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Views/Shared/_Layout.cshtml +++ b/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Views/Shared/_Layout.cshtml @@ -27,7 +27,7 @@ Личные данные