From 9255ad46c8acf4b08af7136d714045cac87fc879 Mon Sep 17 00:00:00 2001 From: "kagbie3nn@mail.ru" Date: Sat, 15 Jun 2024 20:01:56 +0400 Subject: [PATCH 1/9] =?UTF-8?q?=D0=B1=D0=B0=D0=B7=D0=BE=D0=B2=D0=B0=D1=8F?= =?UTF-8?q?=20=D0=BB=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82=D0=BE=D1=80=D0=BD?= =?UTF-8?q?=D0=B0=D1=8F=207?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../BusinessLogic/MessageInfoLogic.cs | 94 ++++++++++++++ .../Views/Home/Mails.chtml | 52 ++++++++ .../BindingModels/MailConfigBindingModel.cs | 23 ++++ .../BindingModels/MailSendInfoBindingModel.cs | 17 +++ .../BindingModels/MessageInfoBindingModel.cs | 24 ++++ .../IMessageInfoLogic.cs | 18 +++ .../SearchModels/MessageInfoSearchModel.cs | 15 +++ .../StoragesContracts/IMessageInfoStorage.cs | 22 ++++ .../ViewModels/MessageInfoViewModel.cs | 29 +++++ .../Models/IMessageInfoModel.cs | 23 ++++ .../Implements/MessageInfoStorage.cs | 61 +++++++++ .../Implements/MessageInfoStorage.cs | 58 +++++++++ .../Models/Message.cs | 80 ++++++++++++ .../Implements/MessageInfoStorage.cs | 66 ++++++++++ .../Models/Message.cs | 53 ++++++++ ComputersShop/ComputersShopView/App.config | 11 ++ .../ComputersShopView/FormMails.Designer.cs | 65 ++++++++++ ComputersShop/ComputersShopView/FormMails.cs | 49 +++++++ .../ComputersShopView/FormMails.resx | 120 ++++++++++++++++++ 19 files changed, 880 insertions(+) create mode 100644 ComputersShop/ComputersShopBusinessLogic/BusinessLogic/MessageInfoLogic.cs create mode 100644 ComputersShop/ComputersShopClientApp/Views/Home/Mails.chtml 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/ComputersShopDatabaseImplement/Implements/MessageInfoStorage.cs create mode 100644 ComputersShop/ComputersShopFileImplement/Implements/MessageInfoStorage.cs create mode 100644 ComputersShop/ComputersShopFileImplement/Models/Message.cs create mode 100644 ComputersShop/ComputersShopListImplement/Implements/MessageInfoStorage.cs create mode 100644 ComputersShop/ComputersShopListImplement/Models/Message.cs create mode 100644 ComputersShop/ComputersShopView/App.config create mode 100644 ComputersShop/ComputersShopView/FormMails.Designer.cs create mode 100644 ComputersShop/ComputersShopView/FormMails.cs create mode 100644 ComputersShop/ComputersShopView/FormMails.resx diff --git a/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/MessageInfoLogic.cs b/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/MessageInfoLogic.cs new file mode 100644 index 0000000..ca8b538 --- /dev/null +++ b/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/MessageInfoLogic.cs @@ -0,0 +1,94 @@ +using ComputersShopBusinessLogic.BusinessLogic; +using ComputersShopContracts.BindingModels; +using ComputersShopContracts.BusinessLogicContracts; +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; + private readonly IClientStorage _clientStorage; + + public MessageInfoLogic(ILogger logger, IMessageInfoStorage messageInfoStorage, IClientStorage clientStorage) + { + _logger = logger; + _messageInfoStorage = messageInfoStorage; + _clientStorage = clientStorage; + } + + 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. ClientId:{ClientId}. MessageId:{MessageId}", model?.ClientId, model?.MessageId); + var list = model == null ? _messageInfoStorage.GetFullList() : _messageInfoStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + _logger.LogInformation("ReadList. Count:{Count}", list.Count); + return list; + } + + private void CheckModel(MessageInfoBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (!withParams) + { + return; + } + if (string.IsNullOrEmpty(model.MessageId)) + { + throw new ArgumentNullException("Не указан id сообщения", nameof(model.MessageId)); + } + if (string.IsNullOrEmpty(model.SenderName)) + { + throw new ArgumentNullException("Не указао почта", nameof(model.SenderName)); + } + if (string.IsNullOrEmpty(model.Subject)) + { + throw new ArgumentNullException("Не указана тема", nameof(model.Subject)); + } + if (string.IsNullOrEmpty(model.Body)) + { + throw new ArgumentNullException("Не указан текст сообщения", nameof(model.Subject)); + } + + _logger.LogInformation("MessageInfo. MessageId:{MessageId}.SenderName:{SenderName}.Subject:{Subject}.Body:{Body}", model.MessageId, model.SenderName, model.Subject, model.Body); + var element = _clientStorage.GetElement(new ClientSearchModel + { + Email = model.SenderName + }); + if (element == null) + { + _logger.LogWarning("Не удалось найти клиента, отправившего письмо с адреса Email:{Email}", model.SenderName); + } + else + { + model.ClientId = element.Id; + } + } + } +} \ No newline at end of file diff --git a/ComputersShop/ComputersShopClientApp/Views/Home/Mails.chtml b/ComputersShop/ComputersShopClientApp/Views/Home/Mails.chtml new file mode 100644 index 0000000..21cb744 --- /dev/null +++ b/ComputersShop/ComputersShopClientApp/Views/Home/Mails.chtml @@ -0,0 +1,52 @@ +@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/ComputersShopContracts/BindingModels/MailConfigBindingModel.cs b/ComputersShop/ComputersShopContracts/BindingModels/MailConfigBindingModel.cs new file mode 100644 index 0000000..adf3ecd --- /dev/null +++ b/ComputersShop/ComputersShopContracts/BindingModels/MailConfigBindingModel.cs @@ -0,0 +1,23 @@ +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..f9b4566 --- /dev/null +++ b/ComputersShop/ComputersShopContracts/BindingModels/MailSendInfoBindingModel.cs @@ -0,0 +1,17 @@ +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..2966e42 --- /dev/null +++ b/ComputersShop/ComputersShopContracts/BindingModels/MessageInfoBindingModel.cs @@ -0,0 +1,24 @@ +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 string Subject { get; set; } = string.Empty; + + public string Body { get; set; } = string.Empty; + + public DateTime DateDelivery { get; set; } + } +} diff --git a/ComputersShop/ComputersShopContracts/BusinessLogicsContracts/IMessageInfoLogic.cs b/ComputersShop/ComputersShopContracts/BusinessLogicsContracts/IMessageInfoLogic.cs new file mode 100644 index 0000000..a4dfcff --- /dev/null +++ b/ComputersShop/ComputersShopContracts/BusinessLogicsContracts/IMessageInfoLogic.cs @@ -0,0 +1,18 @@ +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.BusinessLogicContracts +{ + public interface IMessageInfoLogic + { + List? ReadList(MessageInfoSearchModel? model); + + bool Create(MessageInfoBindingModel model); + } +} \ No newline at end of file diff --git a/ComputersShop/ComputersShopContracts/SearchModels/MessageInfoSearchModel.cs b/ComputersShop/ComputersShopContracts/SearchModels/MessageInfoSearchModel.cs new file mode 100644 index 0000000..5154a94 --- /dev/null +++ b/ComputersShop/ComputersShopContracts/SearchModels/MessageInfoSearchModel.cs @@ -0,0 +1,15 @@ +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..64dfea8 --- /dev/null +++ b/ComputersShop/ComputersShopContracts/StoragesContracts/IMessageInfoStorage.cs @@ -0,0 +1,22 @@ +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 GetFilteredList(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..e9f7ce7 --- /dev/null +++ b/ComputersShop/ComputersShopContracts/ViewModels/MessageInfoViewModel.cs @@ -0,0 +1,29 @@ +using ComputersShopDataModels.Models; +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 : IMessageInfoModel + { + public string MessageId { get; set; } = string.Empty; + + public int? ClientId { get; set; } + + [DisplayName("Отправитель")] + public string SenderName { get; set; } = string.Empty; + + [DisplayName("Дата письма")] + public DateTime DateDelivery { get; set; } + + [DisplayName("Заголовок")] + public string Subject { get; set; } = string.Empty; + + [DisplayName("Текст")] + public string Body { get; set; } = string.Empty; + } +} diff --git a/ComputersShop/ComputersShopDataModels/Models/IMessageInfoModel.cs b/ComputersShop/ComputersShopDataModels/Models/IMessageInfoModel.cs new file mode 100644 index 0000000..5985ff7 --- /dev/null +++ b/ComputersShop/ComputersShopDataModels/Models/IMessageInfoModel.cs @@ -0,0 +1,23 @@ +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/ComputersShopDatabaseImplement/Implements/MessageInfoStorage.cs b/ComputersShop/ComputersShopDatabaseImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..eb8e70c --- /dev/null +++ b/ComputersShop/ComputersShopDatabaseImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,61 @@ +using ComputersShopContracts.BindingModels; +using ComputersShopContracts.SearchModels; +using ComputersShopContracts.StoragesContracts; +using ComputersShopContracts.ViewModels; +using ComputersShopDatabaseImplement; +using ComputersShopDataBaseImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopDataBaseImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (string.IsNullOrEmpty(model.MessageId)) + { + return null; + } + using var context = new ComputersShopDatabase(); + return context.Messages + .FirstOrDefault(x => x.MessageId == model.MessageId)? + .GetViewModel; + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + if (!model.ClientId.HasValue) + return new(); + using var context = new ComputersShopDatabase(); + return context.Messages + .Where(x => x.ClientId == model.ClientId) + .Select(x => x.GetViewModel) + .ToList(); + } + + public List GetFullList() + { + using var context = new ComputersShopDatabase(); + return context.Messages + .Select(x => x.GetViewModel) + .ToList(); + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + using var context = new ComputersShopDatabase(); + var newMessage = Message.Create(model); + if (newMessage == null) + { + return null; + } + context.Messages.Add(newMessage); + context.SaveChanges(); + return newMessage.GetViewModel; + } + } +} \ No newline at end of file diff --git a/ComputersShop/ComputersShopFileImplement/Implements/MessageInfoStorage.cs b/ComputersShop/ComputersShopFileImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..8e36716 --- /dev/null +++ b/ComputersShop/ComputersShopFileImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,58 @@ +using ComputersShopContracts.BindingModels; +using ComputersShopContracts.SearchModels; +using ComputersShopContracts.StoragesContracts; +using ComputersShopContracts.ViewModels; +using ComputersShopFileImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopFileImplement.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 GetFilteredList(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 = Message.Create(model); + if (newMessage == null) + { + return null; + } + _source.Messages.Add(newMessage); + _source.SaveMessages(); + return newMessage.GetViewModel; + } + } +} \ No newline at end of file diff --git a/ComputersShop/ComputersShopFileImplement/Models/Message.cs b/ComputersShop/ComputersShopFileImplement/Models/Message.cs new file mode 100644 index 0000000..45ae353 --- /dev/null +++ b/ComputersShop/ComputersShopFileImplement/Models/Message.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 ComputersShopFileImplement.Models +{ + public class Message : IMessageInfoModel + { + public string MessageId { get; private set; } = string.Empty; + + public int? ClientId { get; private set; } + + public string SenderName { get; private set; } = string.Empty; + + public DateTime DateDelivery { get; private set; } = DateTime.Now; + + public string Subject { get; private set; } = string.Empty; + + public string Body { get; private set; } = string.Empty; + + public static Message? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Subject = model.Subject, + ClientId = model.ClientId, + MessageId = model.MessageId, + SenderName = model.SenderName, + DateDelivery = model.DateDelivery, + }; + } + + public static Message? 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/ComputersShopListImplement/Implements/MessageInfoStorage.cs b/ComputersShop/ComputersShopListImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..d4b481d --- /dev/null +++ b/ComputersShop/ComputersShopListImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,66 @@ +using ComputersShopContracts.BindingModels; +using ComputersShopContracts.SearchModels; +using ComputersShopContracts.StoragesContracts; +using ComputersShopContracts.ViewModels; +using ComputersShopListImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopListImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + private readonly DataListSingleton _source; + public MessageInfoStorage() + { + _source = DataListSingleton.GetInstance(); + } + + 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 List GetFilteredList(MessageInfoSearchModel model) + { + List result = new(); + foreach (var item in _source.Messages) + { + if (item.ClientId.HasValue && item.ClientId == model.ClientId) + { + result.Add(item.GetViewModel); + } + } + return result; + } + + public List GetFullList() + { + List result = new(); + foreach (var item in _source.Messages) + { + result.Add(item.GetViewModel); + } + return result; + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = Message.Create(model); + if (newMessage == null) + { + return null; + } + _source.Messages.Add(newMessage); + return newMessage.GetViewModel; + } + } +} diff --git a/ComputersShop/ComputersShopListImplement/Models/Message.cs b/ComputersShop/ComputersShopListImplement/Models/Message.cs new file mode 100644 index 0000000..3b579ae --- /dev/null +++ b/ComputersShop/ComputersShopListImplement/Models/Message.cs @@ -0,0 +1,53 @@ +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 ComputersShopListImplement.Models +{ + public class Message : IMessageInfoModel + { + public string MessageId { get; private set; } = string.Empty; + + public int? ClientId { get; private set; } + + public string SenderName { get; private set; } = string.Empty; + + public DateTime DateDelivery { get; private set; } = DateTime.Now; + + public string Subject { get; private set; } = string.Empty; + + public string Body { get; private set; } = string.Empty; + + public static Message? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Subject = model.Subject, + 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/ComputersShopView/App.config b/ComputersShop/ComputersShopView/App.config new file mode 100644 index 0000000..d18d589 --- /dev/null +++ b/ComputersShop/ComputersShopView/App.config @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/ComputersShop/ComputersShopView/FormMails.Designer.cs b/ComputersShop/ComputersShopView/FormMails.Designer.cs new file mode 100644 index 0000000..43569ef --- /dev/null +++ b/ComputersShop/ComputersShopView/FormMails.Designer.cs @@ -0,0 +1,65 @@ +namespace ComputersShopView +{ + 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() + { + dataGridView = new DataGridView(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // dataGridView + // + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Dock = DockStyle.Fill; + dataGridView.Location = new Point(0, 0); + dataGridView.Margin = new Padding(3, 2, 3, 2); + dataGridView.Name = "dataGridView"; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 29; + dataGridView.Size = new Size(947, 576); + dataGridView.TabIndex = 0; + // + // FormMails + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(947, 576); + Controls.Add(dataGridView); + Margin = new Padding(3, 2, 3, 2); + 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/ComputersShopView/FormMails.cs b/ComputersShop/ComputersShopView/FormMails.cs new file mode 100644 index 0000000..927b4d1 --- /dev/null +++ b/ComputersShop/ComputersShopView/FormMails.cs @@ -0,0 +1,49 @@ +using ComputersShopContracts.BusinessLogicContracts; +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 ComputersShopView +{ + 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("Загрузка писем"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки писем"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + } +} diff --git a/ComputersShop/ComputersShopView/FormMails.resx b/ComputersShop/ComputersShopView/FormMails.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/ComputersShop/ComputersShopView/FormMails.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 -- 2.25.1 From 0d359ec90fcb76c948c28449c85592e43a8585f8 Mon Sep 17 00:00:00 2001 From: "kagbie3nn@mail.ru" Date: Sat, 15 Jun 2024 21:15:05 +0400 Subject: [PATCH 2/9] =?UTF-8?q?7=20=D0=BB=D0=B0=D0=B1=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../BusinessLogic/ClientLogic.cs | 7 +- .../BusinessLogic/ImplementerLogic.cs | 7 +- .../BusinessLogic/OrderLogic.cs | 37 +++++-- .../ComputersShopBusinessLogic.csproj | 1 + .../MailWorker/AbstractMailWorker.cs | 101 ++++++++++++++++++ .../MailWorker/MailKitWorker.cs | 82 ++++++++++++++ .../Controllers/HomeController.cs | 11 +- .../Views/Home/Mails.cshtml | 53 +++++++++ .../ComputersShopDatabase.cs | 1 + .../Implements/ClientStorage.cs | 36 ++++--- .../Models/Client.cs | 3 +- .../Models/MessageInfo.cs | 57 ++++++++++ .../Controllers/ClientController.cs | 21 +++- ComputersShop/ComputersShopRestApi/Program.cs | 19 +++- .../ComputersShopRestApi/appsettings.json | 8 +- ComputersShop/ComputersShopView/Program.cs | 28 ++++- 16 files changed, 441 insertions(+), 31 deletions(-) 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/ComputersShopDatabaseImplement/Models/MessageInfo.cs diff --git a/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/ClientLogic.cs b/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/ClientLogic.cs index b2ab694..4fc7499 100644 --- a/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/ClientLogic.cs +++ b/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/ClientLogic.cs @@ -9,6 +9,7 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; +using System.Text.RegularExpressions; using System.Threading.Tasks; namespace ComputersShopBusinessLogic.BusinessLogic @@ -107,7 +108,11 @@ namespace ComputersShopBusinessLogic.BusinessLogic { throw new ArgumentNullException("У клиента отсутствует пароль", nameof(model.Email)); } - _logger.LogInformation("Client. ClientID:{Id}. ClientFIO: {ClientFIO}. Email:{ Email}. Password: { Password}", model.Id, model.ClientFIO, model.Email, model.Password); + if (!Regex.IsMatch(model.Email, @"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$")) + { + throw new ArgumentException("Некорретно введенный email", nameof(model.Email)); + } + _logger.LogInformation("Client. ClientID:{Id}. ClientFIO: {ClientFIO}. Email:{ Email}. Password: { Password}", model.Id, model.ClientFIO, model.Email, model.Password); var element = _clientStorage.GetElement(new ClientSearchModel { Email = model.Email diff --git a/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/ImplementerLogic.cs b/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/ImplementerLogic.cs index 936c396..359a1c9 100644 --- a/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/ImplementerLogic.cs +++ b/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/ImplementerLogic.cs @@ -1,4 +1,9 @@ -using Microsoft.Extensions.Logging; +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; diff --git a/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/OrderLogic.cs b/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/OrderLogic.cs index c099a5d..2dc4063 100644 --- a/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/OrderLogic.cs +++ b/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/OrderLogic.cs @@ -10,6 +10,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using ComputersShopBusinessLogic.MailWorker; namespace ComputersShopBusinessLogic.BusinessLogic { @@ -18,11 +19,15 @@ namespace ComputersShopBusinessLogic.BusinessLogic private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; - 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) { _logger.LogInformation("ReadList. OrderId:{Id}", model?.Id); @@ -41,12 +46,15 @@ namespace ComputersShopBusinessLogic.BusinessLogic CheckModel(model); if (model.Status != OrderStatus.Неизвестен) return false; model.Status = OrderStatus.Принят; - if (_orderStorage.Insert(model) == null) - { + var result = _orderStorage.Insert(model); + if (result == null) + { _logger.LogWarning("Insert operation failed"); return false; } - return true; + + SendOrderStatusMail(result.ClientId, $"Новый заказ создан. Номер заказа #{result.Id}", $"Заказ #{result.Id} от {result.DateCreate} на сумму {result.Sum:0.00} принят"); + return true; } public bool ChangeStatus(OrderBindingModel model, OrderStatus status) { @@ -112,5 +120,20 @@ namespace ComputersShopBusinessLogic.BusinessLogic } _logger.LogInformation("Order. Sum:{ Cost}. Id: { Id}", model.Sum, model.Id); } - } + private bool SendOrderStatusMail(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 3029ee4..3fdb8ba 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..5acad10 --- /dev/null +++ b/ComputersShop/ComputersShopBusinessLogic/MailWorker/AbstractMailWorker.cs @@ -0,0 +1,101 @@ +using ComputersShopContracts.BindingModels; +using ComputersShopContracts.BusinessLogicContracts; +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 IClientLogic _clientLogic; + + private readonly ILogger _logger; + + public AbstractMailWorker(ILogger logger, IMessageInfoLogic messageInfoLogic, IClientLogic clientLogic) + { + _logger = logger; + _messageInfoLogic = messageInfoLogic; + _clientLogic = clientLogic; + } + + public void MailConfig(MailConfigBindingModel config) + { + _mailLogin = config.MailLogin; + _mailPassword = config.MailPassword; + _smtpClientHost = config.SmtpClientHost; + _smtpClientPort = config.SmtpClientPort; + _popHost = config.PopHost; + _popPort = config.PopPort; + _logger.LogDebug("Config: {login}, {password}, {clientHost}, {clientPOrt}, {popHost}, {popPort}", _mailLogin, _mailPassword, _smtpClientHost, _smtpClientPort, _popHost, _popPort); + } + + public async void MailSendAsync(MailSendInfoBindingModel info) + { + if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword)) + { + return; + } + + if (string.IsNullOrEmpty(_smtpClientHost) || _smtpClientPort == 0) + { + return; + } + + if (string.IsNullOrEmpty(info.MailAddress) || string.IsNullOrEmpty(info.Subject) || string.IsNullOrEmpty(info.Text)) + { + return; + } + + _logger.LogDebug("Send Mail: {To}, {Subject}", info.MailAddress, info.Subject); + await SendMailAsync(info); + } + + public async void MailCheck() + { + if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword)) + { + return; + } + + if (string.IsNullOrEmpty(_popHost) || _popPort == 0) + { + return; + } + + if (_messageInfoLogic == null) + { + return; + } + + var list = await ReceiveMailAsync(); + _logger.LogDebug("Check Mail: {Count} new mails", list.Count); + foreach (var mail in list) + { + mail.ClientId = _clientLogic.ReadElement(new() { Email = mail.SenderName })?.Id; + _messageInfoLogic.Create(mail); + } + } + + protected abstract Task SendMailAsync(MailSendInfoBindingModel info); + + protected abstract Task> ReceiveMailAsync(); + } +} diff --git a/ComputersShop/ComputersShopBusinessLogic/MailWorker/MailKitWorker.cs b/ComputersShop/ComputersShopBusinessLogic/MailWorker/MailKitWorker.cs new file mode 100644 index 0000000..cacf980 --- /dev/null +++ b/ComputersShop/ComputersShopBusinessLogic/MailWorker/MailKitWorker.cs @@ -0,0 +1,82 @@ +using ComputersShopContracts.BindingModels; +using ComputersShopContracts.BusinessLogicContracts; +using ComputersShopContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Mail; +using System.Net; +using System.Security.Authentication; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopBusinessLogic.MailWorker +{ + public class MailKitWorker : AbstractMailWorker + { + public MailKitWorker(ILogger logger, IMessageInfoLogic messageInfoLogic, IClientLogic clientLogic) : base(logger, messageInfoLogic, clientLogic) { } + + protected override async Task SendMailAsync(MailSendInfoBindingModel info) + { + using var objMailMessage = new MailMessage(); + using var objSmtpClient = new SmtpClient(_smtpClientHost, _smtpClientPort); + try + { + objMailMessage.From = new MailAddress(_mailLogin); + objMailMessage.To.Add(new MailAddress(info.MailAddress)); + objMailMessage.Subject = info.Subject; + objMailMessage.Body = info.Text; + objMailMessage.SubjectEncoding = Encoding.UTF8; + objMailMessage.BodyEncoding = Encoding.UTF8; + + objSmtpClient.UseDefaultCredentials = false; + objSmtpClient.EnableSsl = true; + objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; + objSmtpClient.Credentials = new NetworkCredential(_mailLogin, _mailPassword); + + await Task.Run(() => objSmtpClient.Send(objMailMessage)); + } + catch (Exception) + { + throw; + } + } + + protected override async Task> ReceiveMailAsync() + { + var list = new List(); + using var client = new Pop3Client(); + await Task.Run(() => + { + try + { + client.Connect(_popHost, _popPort, SecureSocketOptions.SslOnConnect); + client.Authenticate(_mailLogin, _mailPassword); + for (int i = 0; i < client.Count; i++) + { + var message = client.GetMessage(i); + foreach (var mail in message.From.Mailboxes) + { + list.Add(new MessageInfoBindingModel + { + DateDelivery = message.Date.DateTime, + MessageId = message.MessageId, + SenderName = mail.Address, + Subject = message.Subject, + Body = message.TextBody, + }); + } + } + } + catch (AuthenticationException) + { } + finally + { + client.Disconnect(true); + } + }); + return list; + } + } +} \ No newline at end of file diff --git a/ComputersShop/ComputersShopClientApp/Controllers/HomeController.cs b/ComputersShop/ComputersShopClientApp/Controllers/HomeController.cs index 8df9080..038241e 100644 --- a/ComputersShop/ComputersShopClientApp/Controllers/HomeController.cs +++ b/ComputersShop/ComputersShopClientApp/Controllers/HomeController.cs @@ -142,5 +142,14 @@ namespace ComputersShopClientApp.Controllers var prod = APIClient.GetRequest($"api/main/getcomputer?computerId={computer}"); return count * (prod?.Price ?? 1); } - } + [HttpGet] + public IActionResult Mails() + { + if (APIClient.Client == null) + { + return Redirect("~/Home/Enter"); + } + return View(APIClient.GetRequest>($"api/client/getmessages?clientId={APIClient.Client.Id}")); + } + } } diff --git a/ComputersShop/ComputersShopClientApp/Views/Home/Mails.cshtml b/ComputersShop/ComputersShopClientApp/Views/Home/Mails.cshtml new file mode 100644 index 0000000..e9eb20a --- /dev/null +++ b/ComputersShop/ComputersShopClientApp/Views/Home/Mails.cshtml @@ -0,0 +1,53 @@ +@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/ComputersShopDatabaseImplement/ComputersShopDatabase.cs b/ComputersShop/ComputersShopDatabaseImplement/ComputersShopDatabase.cs index 0b46b63..9cba463 100644 --- a/ComputersShop/ComputersShopDatabaseImplement/ComputersShopDatabase.cs +++ b/ComputersShop/ComputersShopDatabaseImplement/ComputersShopDatabase.cs @@ -25,5 +25,6 @@ namespace ComputersShopDatabaseImplement 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/ComputersShopDatabaseImplement/Implements/ClientStorage.cs b/ComputersShop/ComputersShopDatabaseImplement/Implements/ClientStorage.cs index 800e401..f928fbb 100644 --- a/ComputersShop/ComputersShopDatabaseImplement/Implements/ClientStorage.cs +++ b/ComputersShop/ComputersShopDatabaseImplement/Implements/ClientStorage.cs @@ -15,7 +15,7 @@ namespace ComputersShopDatabaseImplement.Implements { public ClientViewModel? Delete(ClientBindingModel model) { - using var context = new ComputersShopDatabase(); + using var context = new ComputersShopDataBase(); var res = context.Clients.FirstOrDefault(x => x.Id == model.Id); if (res != null) { @@ -27,17 +27,21 @@ namespace ComputersShopDatabaseImplement.Implements public ClientViewModel? GetElement(ClientSearchModel model) { - using var context = new ComputersShopDatabase(); - if (model.Id.HasValue) - return context.Clients.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; - if (model.Email != null && model.Password != null) - return context.Clients - .FirstOrDefault(x => x.Email.Equals(model.Email) - && x.Password.Equals(model.Password)) - ?.GetViewModel; - if (model.Email != null) - return context.Clients.FirstOrDefault(x => x.Email.Equals(model.Email))?.GetViewModel; - return null; + if (string.IsNullOrEmpty(model.ClientFIO) && + string.IsNullOrEmpty(model.Email) && + string.IsNullOrEmpty(model.Password) && + !model.Id.HasValue) + { + return null; + } + using var context = new ComputersShopDataBase(); + var temp = context.Clients + .FirstOrDefault(x => (string.IsNullOrEmpty(model.ClientFIO) || x.ClientFIO == model.ClientFIO) && + (string.IsNullOrEmpty(model.Email) || x.Email == model.Email) && + (string.IsNullOrEmpty(model.Password) || x.Password == model.Password) && + (!model.Id.HasValue || x.Id == model.Id)) + ?.GetViewModel; + return temp; } public List GetFilteredList(ClientSearchModel model) @@ -53,7 +57,7 @@ namespace ComputersShopDatabaseImplement.Implements } if (model.Email != null) { - using var context = new ComputersShopDatabase(); + using var context = new ComputersShopDataBase(); return context.Clients .Where(x => x.Email.Contains(model.Email)) .Select(x => x.GetViewModel) @@ -64,13 +68,13 @@ namespace ComputersShopDatabaseImplement.Implements public List GetFullList() { - using var context = new ComputersShopDatabase(); + using var context = new ComputersShopDataBase(); return context.Clients.Select(x => x.GetViewModel).ToList(); } public ClientViewModel? Insert(ClientBindingModel model) { - using var context = new ComputersShopDatabase(); + using var context = new ComputersShopDataBase(); var res = Client.Create(model); if (res != null) { @@ -82,7 +86,7 @@ namespace ComputersShopDatabaseImplement.Implements public ClientViewModel? Update(ClientBindingModel model) { - using var context = new ComputersShopDatabase(); + using var context = new ComputersShopDataBase(); var res = context.Clients.FirstOrDefault(x => x.Id == model.Id); res?.Update(model); context.SaveChanges(); diff --git a/ComputersShop/ComputersShopDatabaseImplement/Models/Client.cs b/ComputersShop/ComputersShopDatabaseImplement/Models/Client.cs index 2529f5f..3f47c2a 100644 --- a/ComputersShop/ComputersShopDatabaseImplement/Models/Client.cs +++ b/ComputersShop/ComputersShopDatabaseImplement/Models/Client.cs @@ -21,7 +21,8 @@ namespace ComputersShopDatabaseImplement.Models [Required] public string Password { get; set; } = string.Empty; - + [ForeignKey("ClientId")] + public virtual List Messages { get; set; } = new(); public int Id { get; set; } [ForeignKey("ClientId")] diff --git a/ComputersShop/ComputersShopDatabaseImplement/Models/MessageInfo.cs b/ComputersShop/ComputersShopDatabaseImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..58f4f86 --- /dev/null +++ b/ComputersShop/ComputersShopDatabaseImplement/Models/MessageInfo.cs @@ -0,0 +1,57 @@ +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 ComputersShopDatabaseImplement.Models +{ + public class MessageInfo : IMessageInfoModel + { + [Key] + public string MessageId { get; private set; } = string.Empty; + + public int? ClientId { get; private set; } + + public virtual Client? Client { get; set; } + + public string SenderName { get; private set; } = string.Empty; + + public DateTime DateDelivery { get; private set; } = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc); + + public string Subject { get; private set; } = string.Empty; + + public string Body { get; private set; } = string.Empty; + + public static Message? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Subject = model.Subject, + ClientId = model.ClientId, + MessageId = model.MessageId, + SenderName = model.SenderName, + DateDelivery = DateTime.SpecifyKind(model.DateDelivery, DateTimeKind.Utc) + }; + } + + 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 22a5fae..73052d0 100644 --- a/ComputersShop/ComputersShopRestApi/Controllers/ClientController.cs +++ b/ComputersShop/ComputersShopRestApi/Controllers/ClientController.cs @@ -1,4 +1,5 @@ using ComputersShopContracts.BindingModels; +using ComputersShopContracts.BusinessLogicContracts; using ComputersShopContracts.BusinessLogicsContracts; using ComputersShopContracts.SearchModels; using ComputersShopContracts.ViewModels; @@ -13,11 +14,13 @@ 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] @@ -66,5 +69,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 bf456bc..95c5de9 100644 --- a/ComputersShop/ComputersShopRestApi/Program.cs +++ b/ComputersShop/ComputersShopRestApi/Program.cs @@ -1,7 +1,12 @@ using ComputersShopBusinessLogic.BusinessLogic; +using ComputersShopBusinessLogic.BusinessLogics; +using ComputersShopBusinessLogic.MailWorker; +using ComputersShopContracts.BindingModels; +using ComputersShopContracts.BusinessLogicContracts; using ComputersShopContracts.BusinessLogicsContracts; using ComputersShopContracts.StoragesContracts; using ComputersShopDatabaseImplement.Implements; +using ComputersShopDataBaseImplement.Implements; using Microsoft.OpenApi.Models; var builder = WebApplication.CreateBuilder(args); @@ -14,11 +19,12 @@ 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 @@ -34,6 +40,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..8c89e0b 100644 --- a/ComputersShop/ComputersShopRestApi/appsettings.json +++ b/ComputersShop/ComputersShopRestApi/appsettings.json @@ -5,5 +5,11 @@ "Microsoft.AspNetCore": "Warning" } }, - "AllowedHosts": "*" + "AllowedHosts": "*", + "SmtpClientHost": "smtp.gmail.com", + "SmtpClientPort": "587", + "PopHost": "pop.gmail.com", + "PopPort": "995", + "MailLogin": "rpplabs900@gmail.com", + "MailPassword": "wmbu qrgy ocwl tadm" } diff --git a/ComputersShop/ComputersShopView/Program.cs b/ComputersShop/ComputersShopView/Program.cs index 2773da6..20bfa80 100644 --- a/ComputersShop/ComputersShopView/Program.cs +++ b/ComputersShop/ComputersShopView/Program.cs @@ -9,6 +9,9 @@ using ComputersShopView; using ComputersShopBusinessLogic.OfficePackage.Implements; using ComputersShopBusinessLogic.OfficePackage; using ComputersShopBusinessLogic; +using ComputersShopBusinessLogic.MailWorker; +using ComputersShopContracts.BindingModels; +using ComputersShopDataBaseImplement.Implements; namespace ComputersShop @@ -29,6 +32,26 @@ namespace ComputersShop var services = new ServiceCollection(); ConfigureServices(services); _serviceProvider = services.BuildServiceProvider(); + try + { + var mailSender = _serviceProvider.GetService(); + mailSender?.MailConfig(new MailConfigBindingModel + { + MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty, + MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty, + SmtpClientHost = System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty, + SmtpClientPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]), + PopHost = System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty, + PopPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"]) + }); + + var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000); + } + catch (Exception ex) + { + var logger = _serviceProvider.GetService(); + logger?.LogError(ex, "Error"); + } Application.Run(_serviceProvider.GetRequiredService()); } private static void ConfigureServices(ServiceCollection services) @@ -43,6 +66,7 @@ namespace ComputersShop services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -50,11 +74,12 @@ namespace ComputersShop services.AddTransient(); services.AddTransient(); services.AddTransient(); - services.AddTransient() + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddSingleton(); services.AddTransient(); services.AddTransient(); @@ -69,5 +94,6 @@ namespace ComputersShop services.AddTransient(); services.AddTransient(); } + private static void MailCheck(object obj) => ServiceProvider?.GetService()?.MailCheck(); } } \ No newline at end of file -- 2.25.1 From fdf53e3301fbabb66f45106fb252c11ea0dfd38a Mon Sep 17 00:00:00 2001 From: "kagbie3nn@mail.ru" Date: Sat, 15 Jun 2024 21:21:04 +0400 Subject: [PATCH 3/9] =?UTF-8?q?=D0=B4=D0=BE=D0=B4=D0=B5=D0=BB=D0=B0=D0=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../BusinessLogic/OrderLogic.cs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/OrderLogic.cs b/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/OrderLogic.cs index 2dc4063..b0b95ab 100644 --- a/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/OrderLogic.cs +++ b/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/OrderLogic.cs @@ -80,8 +80,15 @@ namespace ComputersShopBusinessLogic.BusinessLogic { model.ImplementerId = element.ImplementerId; } - if (model.Status == OrderStatus.Выдан) model.DateImplement = DateTime.Now; - _orderStorage.Update(model); + CheckModel(model); + var result = _orderStorage.Update(model); + if (result == null) + { + model.Status--; + _logger.LogWarning("Update operation failed"); + return false; + } + SendOrderStatusMail(result.ClientId, $"DNS, Заказ №{result.Id}", $"Заказ №{model.Id} изменен статус на {result.Status}"); return true; } -- 2.25.1 From ebd10259002c455e3879ac764046022db3c73377 Mon Sep 17 00:00:00 2001 From: "kagbie3nn@mail.ru" Date: Sat, 15 Jun 2024 21:21:04 +0400 Subject: [PATCH 4/9] =?UTF-8?q?=D0=B4=D0=BE=D0=B4=D0=B5=D0=BB=D0=B0=D0=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../BusinessLogic/ImplementerLogic.cs | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/ImplementerLogic.cs b/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/ImplementerLogic.cs index 359a1c9..9f01d7e 100644 --- a/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/ImplementerLogic.cs +++ b/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/ImplementerLogic.cs @@ -1,10 +1,4 @@ -using ComputersShopContracts.BindingModels; -using ComputersShopContracts.BusinessLogicsContracts; -using ComputersShopContracts.SearchModels; -using ComputersShopContracts.StoragesContracts; -using ComputersShopContracts.ViewModels; -using Microsoft.Extensions.Logging; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; -- 2.25.1 From 2419c6fc255e653dbd4e5783d4294cdb1f6cd37f Mon Sep 17 00:00:00 2001 From: "kagbie3nn@mail.ru" Date: Sat, 15 Jun 2024 21:26:39 +0400 Subject: [PATCH 5/9] =?UTF-8?q?Revert=20"=D0=B4=D0=BE=D0=B4=D0=B5=D0=BB?= =?UTF-8?q?=D0=B0=D0=BB"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit ebd10259002c455e3879ac764046022db3c73377. --- .../BusinessLogic/ImplementerLogic.cs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/ImplementerLogic.cs b/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/ImplementerLogic.cs index 9f01d7e..359a1c9 100644 --- a/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/ImplementerLogic.cs +++ b/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/ImplementerLogic.cs @@ -1,4 +1,10 @@ -using System; +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; -- 2.25.1 From baf4bfba6df7ea1436146a47dbabaaa2706db715 Mon Sep 17 00:00:00 2001 From: "kagbie3nn@mail.ru" Date: Sat, 15 Jun 2024 21:27:32 +0400 Subject: [PATCH 6/9] =?UTF-8?q?Revert=20"=D0=B4=D0=BE=D0=B4=D0=B5=D0=BB?= =?UTF-8?q?=D0=B0=D0=BB"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit fdf53e3301fbabb66f45106fb252c11ea0dfd38a. --- .../BusinessLogic/OrderLogic.cs | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/OrderLogic.cs b/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/OrderLogic.cs index b0b95ab..2dc4063 100644 --- a/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/OrderLogic.cs +++ b/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/OrderLogic.cs @@ -80,15 +80,8 @@ namespace ComputersShopBusinessLogic.BusinessLogic { model.ImplementerId = element.ImplementerId; } - CheckModel(model); - var result = _orderStorage.Update(model); - if (result == null) - { - model.Status--; - _logger.LogWarning("Update operation failed"); - return false; - } - SendOrderStatusMail(result.ClientId, $"DNS, Заказ №{result.Id}", $"Заказ №{model.Id} изменен статус на {result.Status}"); + if (model.Status == OrderStatus.Выдан) model.DateImplement = DateTime.Now; + _orderStorage.Update(model); return true; } -- 2.25.1 From de97e336458b75a97f519ca1440e9530a212e5a1 Mon Sep 17 00:00:00 2001 From: "kagbie3nn@mail.ru" Date: Sat, 15 Jun 2024 21:27:42 +0400 Subject: [PATCH 7/9] =?UTF-8?q?Revert=20"7=20=D0=BB=D0=B0=D0=B1=D0=B0"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit 0d359ec90fcb76c948c28449c85592e43a8585f8. --- .../BusinessLogic/ClientLogic.cs | 7 +- .../BusinessLogic/ImplementerLogic.cs | 7 +- .../BusinessLogic/OrderLogic.cs | 37 ++----- .../ComputersShopBusinessLogic.csproj | 1 - .../MailWorker/AbstractMailWorker.cs | 101 ------------------ .../MailWorker/MailKitWorker.cs | 82 -------------- .../Controllers/HomeController.cs | 11 +- .../Views/Home/Mails.cshtml | 53 --------- .../ComputersShopDatabase.cs | 1 - .../Implements/ClientStorage.cs | 36 +++---- .../Models/Client.cs | 3 +- .../Models/MessageInfo.cs | 57 ---------- .../Controllers/ClientController.cs | 21 +--- ComputersShop/ComputersShopRestApi/Program.cs | 19 +--- .../ComputersShopRestApi/appsettings.json | 8 +- ComputersShop/ComputersShopView/Program.cs | 28 +---- 16 files changed, 31 insertions(+), 441 deletions(-) delete mode 100644 ComputersShop/ComputersShopBusinessLogic/MailWorker/AbstractMailWorker.cs delete mode 100644 ComputersShop/ComputersShopBusinessLogic/MailWorker/MailKitWorker.cs delete mode 100644 ComputersShop/ComputersShopClientApp/Views/Home/Mails.cshtml delete mode 100644 ComputersShop/ComputersShopDatabaseImplement/Models/MessageInfo.cs diff --git a/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/ClientLogic.cs b/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/ClientLogic.cs index 4fc7499..b2ab694 100644 --- a/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/ClientLogic.cs +++ b/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/ClientLogic.cs @@ -9,7 +9,6 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; -using System.Text.RegularExpressions; using System.Threading.Tasks; namespace ComputersShopBusinessLogic.BusinessLogic @@ -108,11 +107,7 @@ namespace ComputersShopBusinessLogic.BusinessLogic { throw new ArgumentNullException("У клиента отсутствует пароль", nameof(model.Email)); } - if (!Regex.IsMatch(model.Email, @"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$")) - { - throw new ArgumentException("Некорретно введенный email", nameof(model.Email)); - } - _logger.LogInformation("Client. ClientID:{Id}. ClientFIO: {ClientFIO}. Email:{ Email}. Password: { Password}", model.Id, model.ClientFIO, model.Email, model.Password); + _logger.LogInformation("Client. ClientID:{Id}. ClientFIO: {ClientFIO}. Email:{ Email}. Password: { Password}", model.Id, model.ClientFIO, model.Email, model.Password); var element = _clientStorage.GetElement(new ClientSearchModel { Email = model.Email diff --git a/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/ImplementerLogic.cs b/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/ImplementerLogic.cs index 359a1c9..936c396 100644 --- a/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/ImplementerLogic.cs +++ b/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/ImplementerLogic.cs @@ -1,9 +1,4 @@ -using ComputersShopContracts.BindingModels; -using ComputersShopContracts.BusinessLogicsContracts; -using ComputersShopContracts.SearchModels; -using ComputersShopContracts.StoragesContracts; -using ComputersShopContracts.ViewModels; -using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; diff --git a/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/OrderLogic.cs b/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/OrderLogic.cs index 2dc4063..c099a5d 100644 --- a/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/OrderLogic.cs +++ b/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/OrderLogic.cs @@ -10,7 +10,6 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; -using ComputersShopBusinessLogic.MailWorker; namespace ComputersShopBusinessLogic.BusinessLogic { @@ -19,15 +18,11 @@ namespace ComputersShopBusinessLogic.BusinessLogic private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; - private readonly AbstractMailWorker _mailWorker; - private readonly IClientLogic _clientLogic; - public OrderLogic(ILogger logger, IOrderStorage orderStorage, AbstractMailWorker mailWorker, IClientLogic clientLogic) - { + public OrderLogic(ILogger logger, IOrderStorage orderStorage) + { _logger = logger; _orderStorage = orderStorage; - mailWorker = mailWorker; - _clientLogic = clientLogic; - } + } public List? ReadList(OrderSearchModel? model) { _logger.LogInformation("ReadList. OrderId:{Id}", model?.Id); @@ -46,15 +41,12 @@ namespace ComputersShopBusinessLogic.BusinessLogic CheckModel(model); if (model.Status != OrderStatus.Неизвестен) return false; model.Status = OrderStatus.Принят; - var result = _orderStorage.Insert(model); - if (result == null) - { + if (_orderStorage.Insert(model) == null) + { _logger.LogWarning("Insert operation failed"); return false; } - - SendOrderStatusMail(result.ClientId, $"Новый заказ создан. Номер заказа #{result.Id}", $"Заказ #{result.Id} от {result.DateCreate} на сумму {result.Sum:0.00} принят"); - return true; + return true; } public bool ChangeStatus(OrderBindingModel model, OrderStatus status) { @@ -120,20 +112,5 @@ namespace ComputersShopBusinessLogic.BusinessLogic } _logger.LogInformation("Order. Sum:{ Cost}. Id: { Id}", model.Sum, model.Id); } - private bool SendOrderStatusMail(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 3fdb8ba..3029ee4 100644 --- a/ComputersShop/ComputersShopBusinessLogic/ComputersShopBusinessLogic.csproj +++ b/ComputersShop/ComputersShopBusinessLogic/ComputersShopBusinessLogic.csproj @@ -8,7 +8,6 @@ - diff --git a/ComputersShop/ComputersShopBusinessLogic/MailWorker/AbstractMailWorker.cs b/ComputersShop/ComputersShopBusinessLogic/MailWorker/AbstractMailWorker.cs deleted file mode 100644 index 5acad10..0000000 --- a/ComputersShop/ComputersShopBusinessLogic/MailWorker/AbstractMailWorker.cs +++ /dev/null @@ -1,101 +0,0 @@ -using ComputersShopContracts.BindingModels; -using ComputersShopContracts.BusinessLogicContracts; -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 IClientLogic _clientLogic; - - private readonly ILogger _logger; - - public AbstractMailWorker(ILogger logger, IMessageInfoLogic messageInfoLogic, IClientLogic clientLogic) - { - _logger = logger; - _messageInfoLogic = messageInfoLogic; - _clientLogic = clientLogic; - } - - public void MailConfig(MailConfigBindingModel config) - { - _mailLogin = config.MailLogin; - _mailPassword = config.MailPassword; - _smtpClientHost = config.SmtpClientHost; - _smtpClientPort = config.SmtpClientPort; - _popHost = config.PopHost; - _popPort = config.PopPort; - _logger.LogDebug("Config: {login}, {password}, {clientHost}, {clientPOrt}, {popHost}, {popPort}", _mailLogin, _mailPassword, _smtpClientHost, _smtpClientPort, _popHost, _popPort); - } - - public async void MailSendAsync(MailSendInfoBindingModel info) - { - if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword)) - { - return; - } - - if (string.IsNullOrEmpty(_smtpClientHost) || _smtpClientPort == 0) - { - return; - } - - if (string.IsNullOrEmpty(info.MailAddress) || string.IsNullOrEmpty(info.Subject) || string.IsNullOrEmpty(info.Text)) - { - return; - } - - _logger.LogDebug("Send Mail: {To}, {Subject}", info.MailAddress, info.Subject); - await SendMailAsync(info); - } - - public async void MailCheck() - { - if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword)) - { - return; - } - - if (string.IsNullOrEmpty(_popHost) || _popPort == 0) - { - return; - } - - if (_messageInfoLogic == null) - { - return; - } - - var list = await ReceiveMailAsync(); - _logger.LogDebug("Check Mail: {Count} new mails", list.Count); - foreach (var mail in list) - { - mail.ClientId = _clientLogic.ReadElement(new() { Email = mail.SenderName })?.Id; - _messageInfoLogic.Create(mail); - } - } - - protected abstract Task SendMailAsync(MailSendInfoBindingModel info); - - protected abstract Task> ReceiveMailAsync(); - } -} diff --git a/ComputersShop/ComputersShopBusinessLogic/MailWorker/MailKitWorker.cs b/ComputersShop/ComputersShopBusinessLogic/MailWorker/MailKitWorker.cs deleted file mode 100644 index cacf980..0000000 --- a/ComputersShop/ComputersShopBusinessLogic/MailWorker/MailKitWorker.cs +++ /dev/null @@ -1,82 +0,0 @@ -using ComputersShopContracts.BindingModels; -using ComputersShopContracts.BusinessLogicContracts; -using ComputersShopContracts.BusinessLogicsContracts; -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net.Mail; -using System.Net; -using System.Security.Authentication; -using System.Text; -using System.Threading.Tasks; - -namespace ComputersShopBusinessLogic.MailWorker -{ - public class MailKitWorker : AbstractMailWorker - { - public MailKitWorker(ILogger logger, IMessageInfoLogic messageInfoLogic, IClientLogic clientLogic) : base(logger, messageInfoLogic, clientLogic) { } - - protected override async Task SendMailAsync(MailSendInfoBindingModel info) - { - using var objMailMessage = new MailMessage(); - using var objSmtpClient = new SmtpClient(_smtpClientHost, _smtpClientPort); - try - { - objMailMessage.From = new MailAddress(_mailLogin); - objMailMessage.To.Add(new MailAddress(info.MailAddress)); - objMailMessage.Subject = info.Subject; - objMailMessage.Body = info.Text; - objMailMessage.SubjectEncoding = Encoding.UTF8; - objMailMessage.BodyEncoding = Encoding.UTF8; - - objSmtpClient.UseDefaultCredentials = false; - objSmtpClient.EnableSsl = true; - objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; - objSmtpClient.Credentials = new NetworkCredential(_mailLogin, _mailPassword); - - await Task.Run(() => objSmtpClient.Send(objMailMessage)); - } - catch (Exception) - { - throw; - } - } - - protected override async Task> ReceiveMailAsync() - { - var list = new List(); - using var client = new Pop3Client(); - await Task.Run(() => - { - try - { - client.Connect(_popHost, _popPort, SecureSocketOptions.SslOnConnect); - client.Authenticate(_mailLogin, _mailPassword); - for (int i = 0; i < client.Count; i++) - { - var message = client.GetMessage(i); - foreach (var mail in message.From.Mailboxes) - { - list.Add(new MessageInfoBindingModel - { - DateDelivery = message.Date.DateTime, - MessageId = message.MessageId, - SenderName = mail.Address, - Subject = message.Subject, - Body = message.TextBody, - }); - } - } - } - catch (AuthenticationException) - { } - finally - { - client.Disconnect(true); - } - }); - return list; - } - } -} \ No newline at end of file diff --git a/ComputersShop/ComputersShopClientApp/Controllers/HomeController.cs b/ComputersShop/ComputersShopClientApp/Controllers/HomeController.cs index 038241e..8df9080 100644 --- a/ComputersShop/ComputersShopClientApp/Controllers/HomeController.cs +++ b/ComputersShop/ComputersShopClientApp/Controllers/HomeController.cs @@ -142,14 +142,5 @@ namespace ComputersShopClientApp.Controllers var prod = APIClient.GetRequest($"api/main/getcomputer?computerId={computer}"); return count * (prod?.Price ?? 1); } - [HttpGet] - public IActionResult Mails() - { - if (APIClient.Client == null) - { - return Redirect("~/Home/Enter"); - } - return View(APIClient.GetRequest>($"api/client/getmessages?clientId={APIClient.Client.Id}")); - } - } + } } diff --git a/ComputersShop/ComputersShopClientApp/Views/Home/Mails.cshtml b/ComputersShop/ComputersShopClientApp/Views/Home/Mails.cshtml deleted file mode 100644 index e9eb20a..0000000 --- a/ComputersShop/ComputersShopClientApp/Views/Home/Mails.cshtml +++ /dev/null @@ -1,53 +0,0 @@ -@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/ComputersShopDatabaseImplement/ComputersShopDatabase.cs b/ComputersShop/ComputersShopDatabaseImplement/ComputersShopDatabase.cs index 9cba463..0b46b63 100644 --- a/ComputersShop/ComputersShopDatabaseImplement/ComputersShopDatabase.cs +++ b/ComputersShop/ComputersShopDatabaseImplement/ComputersShopDatabase.cs @@ -25,6 +25,5 @@ namespace ComputersShopDatabaseImplement 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/ComputersShopDatabaseImplement/Implements/ClientStorage.cs b/ComputersShop/ComputersShopDatabaseImplement/Implements/ClientStorage.cs index f928fbb..800e401 100644 --- a/ComputersShop/ComputersShopDatabaseImplement/Implements/ClientStorage.cs +++ b/ComputersShop/ComputersShopDatabaseImplement/Implements/ClientStorage.cs @@ -15,7 +15,7 @@ namespace ComputersShopDatabaseImplement.Implements { public ClientViewModel? Delete(ClientBindingModel model) { - using var context = new ComputersShopDataBase(); + using var context = new ComputersShopDatabase(); var res = context.Clients.FirstOrDefault(x => x.Id == model.Id); if (res != null) { @@ -27,21 +27,17 @@ namespace ComputersShopDatabaseImplement.Implements public ClientViewModel? GetElement(ClientSearchModel model) { - if (string.IsNullOrEmpty(model.ClientFIO) && - string.IsNullOrEmpty(model.Email) && - string.IsNullOrEmpty(model.Password) && - !model.Id.HasValue) - { - return null; - } - using var context = new ComputersShopDataBase(); - var temp = context.Clients - .FirstOrDefault(x => (string.IsNullOrEmpty(model.ClientFIO) || x.ClientFIO == model.ClientFIO) && - (string.IsNullOrEmpty(model.Email) || x.Email == model.Email) && - (string.IsNullOrEmpty(model.Password) || x.Password == model.Password) && - (!model.Id.HasValue || x.Id == model.Id)) - ?.GetViewModel; - return temp; + using var context = new ComputersShopDatabase(); + if (model.Id.HasValue) + return context.Clients.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; + if (model.Email != null && model.Password != null) + return context.Clients + .FirstOrDefault(x => x.Email.Equals(model.Email) + && x.Password.Equals(model.Password)) + ?.GetViewModel; + if (model.Email != null) + return context.Clients.FirstOrDefault(x => x.Email.Equals(model.Email))?.GetViewModel; + return null; } public List GetFilteredList(ClientSearchModel model) @@ -57,7 +53,7 @@ namespace ComputersShopDatabaseImplement.Implements } if (model.Email != null) { - using var context = new ComputersShopDataBase(); + using var context = new ComputersShopDatabase(); return context.Clients .Where(x => x.Email.Contains(model.Email)) .Select(x => x.GetViewModel) @@ -68,13 +64,13 @@ namespace ComputersShopDatabaseImplement.Implements public List GetFullList() { - using var context = new ComputersShopDataBase(); + using var context = new ComputersShopDatabase(); return context.Clients.Select(x => x.GetViewModel).ToList(); } public ClientViewModel? Insert(ClientBindingModel model) { - using var context = new ComputersShopDataBase(); + using var context = new ComputersShopDatabase(); var res = Client.Create(model); if (res != null) { @@ -86,7 +82,7 @@ namespace ComputersShopDatabaseImplement.Implements public ClientViewModel? Update(ClientBindingModel model) { - using var context = new ComputersShopDataBase(); + using var context = new ComputersShopDatabase(); var res = context.Clients.FirstOrDefault(x => x.Id == model.Id); res?.Update(model); context.SaveChanges(); diff --git a/ComputersShop/ComputersShopDatabaseImplement/Models/Client.cs b/ComputersShop/ComputersShopDatabaseImplement/Models/Client.cs index 3f47c2a..2529f5f 100644 --- a/ComputersShop/ComputersShopDatabaseImplement/Models/Client.cs +++ b/ComputersShop/ComputersShopDatabaseImplement/Models/Client.cs @@ -21,8 +21,7 @@ namespace ComputersShopDatabaseImplement.Models [Required] public string Password { get; set; } = string.Empty; - [ForeignKey("ClientId")] - public virtual List Messages { get; set; } = new(); + public int Id { get; set; } [ForeignKey("ClientId")] diff --git a/ComputersShop/ComputersShopDatabaseImplement/Models/MessageInfo.cs b/ComputersShop/ComputersShopDatabaseImplement/Models/MessageInfo.cs deleted file mode 100644 index 58f4f86..0000000 --- a/ComputersShop/ComputersShopDatabaseImplement/Models/MessageInfo.cs +++ /dev/null @@ -1,57 +0,0 @@ -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 ComputersShopDatabaseImplement.Models -{ - public class MessageInfo : IMessageInfoModel - { - [Key] - public string MessageId { get; private set; } = string.Empty; - - public int? ClientId { get; private set; } - - public virtual Client? Client { get; set; } - - public string SenderName { get; private set; } = string.Empty; - - public DateTime DateDelivery { get; private set; } = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc); - - public string Subject { get; private set; } = string.Empty; - - public string Body { get; private set; } = string.Empty; - - public static Message? Create(MessageInfoBindingModel model) - { - if (model == null) - { - return null; - } - return new() - { - Body = model.Body, - Subject = model.Subject, - ClientId = model.ClientId, - MessageId = model.MessageId, - SenderName = model.SenderName, - DateDelivery = DateTime.SpecifyKind(model.DateDelivery, DateTimeKind.Utc) - }; - } - - 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 73052d0..22a5fae 100644 --- a/ComputersShop/ComputersShopRestApi/Controllers/ClientController.cs +++ b/ComputersShop/ComputersShopRestApi/Controllers/ClientController.cs @@ -1,5 +1,4 @@ using ComputersShopContracts.BindingModels; -using ComputersShopContracts.BusinessLogicContracts; using ComputersShopContracts.BusinessLogicsContracts; using ComputersShopContracts.SearchModels; using ComputersShopContracts.ViewModels; @@ -14,13 +13,11 @@ namespace ComputersShopRestApi.Controllers private readonly ILogger _logger; private readonly IClientLogic _logic; - private readonly IMessageInfoLogic _mailLogic; - public ClientController(IClientLogic logic, ILogger logger, IMessageInfoLogic mailLogic) + public ClientController(IClientLogic logic, ILogger logger) { _logger = logger; _logic = logic; - _mailLogic = mailLogic; } [HttpGet] @@ -69,21 +66,5 @@ 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 95c5de9..bf456bc 100644 --- a/ComputersShop/ComputersShopRestApi/Program.cs +++ b/ComputersShop/ComputersShopRestApi/Program.cs @@ -1,12 +1,7 @@ using ComputersShopBusinessLogic.BusinessLogic; -using ComputersShopBusinessLogic.BusinessLogics; -using ComputersShopBusinessLogic.MailWorker; -using ComputersShopContracts.BindingModels; -using ComputersShopContracts.BusinessLogicContracts; using ComputersShopContracts.BusinessLogicsContracts; using ComputersShopContracts.StoragesContracts; using ComputersShopDatabaseImplement.Implements; -using ComputersShopDataBaseImplement.Implements; using Microsoft.OpenApi.Models; var builder = WebApplication.CreateBuilder(args); @@ -19,12 +14,11 @@ 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 @@ -40,17 +34,6 @@ 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 8c89e0b..10f68b8 100644 --- a/ComputersShop/ComputersShopRestApi/appsettings.json +++ b/ComputersShop/ComputersShopRestApi/appsettings.json @@ -5,11 +5,5 @@ "Microsoft.AspNetCore": "Warning" } }, - "AllowedHosts": "*", - "SmtpClientHost": "smtp.gmail.com", - "SmtpClientPort": "587", - "PopHost": "pop.gmail.com", - "PopPort": "995", - "MailLogin": "rpplabs900@gmail.com", - "MailPassword": "wmbu qrgy ocwl tadm" + "AllowedHosts": "*" } diff --git a/ComputersShop/ComputersShopView/Program.cs b/ComputersShop/ComputersShopView/Program.cs index 20bfa80..2773da6 100644 --- a/ComputersShop/ComputersShopView/Program.cs +++ b/ComputersShop/ComputersShopView/Program.cs @@ -9,9 +9,6 @@ using ComputersShopView; using ComputersShopBusinessLogic.OfficePackage.Implements; using ComputersShopBusinessLogic.OfficePackage; using ComputersShopBusinessLogic; -using ComputersShopBusinessLogic.MailWorker; -using ComputersShopContracts.BindingModels; -using ComputersShopDataBaseImplement.Implements; namespace ComputersShop @@ -32,26 +29,6 @@ namespace ComputersShop var services = new ServiceCollection(); ConfigureServices(services); _serviceProvider = services.BuildServiceProvider(); - try - { - var mailSender = _serviceProvider.GetService(); - mailSender?.MailConfig(new MailConfigBindingModel - { - MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty, - MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty, - SmtpClientHost = System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty, - SmtpClientPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]), - PopHost = System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty, - PopPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"]) - }); - - var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000); - } - catch (Exception ex) - { - var logger = _serviceProvider.GetService(); - logger?.LogError(ex, "Error"); - } Application.Run(_serviceProvider.GetRequiredService()); } private static void ConfigureServices(ServiceCollection services) @@ -66,7 +43,6 @@ namespace ComputersShop services.AddTransient(); services.AddTransient(); services.AddTransient(); - services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -74,12 +50,11 @@ namespace ComputersShop services.AddTransient(); services.AddTransient(); services.AddTransient(); - services.AddTransient(); + services.AddTransient() services.AddTransient(); services.AddTransient(); services.AddTransient(); - services.AddSingleton(); services.AddTransient(); services.AddTransient(); @@ -94,6 +69,5 @@ namespace ComputersShop services.AddTransient(); services.AddTransient(); } - private static void MailCheck(object obj) => ServiceProvider?.GetService()?.MailCheck(); } } \ No newline at end of file -- 2.25.1 From d9dbe2171da87339c8e983f299dfff473937808e Mon Sep 17 00:00:00 2001 From: "kagbie3nn@mail.ru" Date: Sun, 16 Jun 2024 10:56:35 +0400 Subject: [PATCH 8/9] 7 --- .../BusinessLogic/ClientLogic.cs | 9 + .../BusinessLogic/OrderLogic.cs | 27 ++- .../ComputersShopBusinessLogic.csproj | 1 + .../MailWorker/AbstractMailWorker.cs | 101 +++++++++++ .../MailWorker/MailKitWorker.cs | 83 +++++++++ .../ComputersShopClientApp/APIClient.cs | 2 + .../Controllers/HomeController.cs | 10 ++ .../Views/Home/Mails.cshtml | 52 ++++++ .../Views/Shared/_Layout.cshtml | 3 + .../ViewModels/OrderViewModel.cs | 2 + .../ComputersShopDatabase.cs | 1 + .../Implements/ClientStorage.cs | 25 +-- .../Implements/OrderStorage.cs | 167 ++++++++++++------ .../Models/Client.cs | 2 + .../Models/Message.cs | 56 ++++++ .../Models/Order.cs | 3 +- .../DataFileSingleton.cs | 5 +- .../DataListSingleton.cs | 2 + .../Controllers/ClientController.cs | 24 ++- ComputersShop/ComputersShopRestApi/Program.cs | 20 +++ .../ComputersShopRestApi/appsettings.json | 8 +- ComputersShop/ComputersShopView/Program.cs | 28 +++ 22 files changed, 559 insertions(+), 72 deletions(-) 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/ComputersShopDatabaseImplement/Models/Message.cs diff --git a/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/ClientLogic.cs b/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/ClientLogic.cs index b2ab694..962df9b 100644 --- a/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/ClientLogic.cs +++ b/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/ClientLogic.cs @@ -9,6 +9,7 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; +using System.Text.RegularExpressions; using System.Threading.Tasks; namespace ComputersShopBusinessLogic.BusinessLogic @@ -107,6 +108,14 @@ namespace ComputersShopBusinessLogic.BusinessLogic { throw new ArgumentNullException("У клиента отсутствует пароль", nameof(model.Email)); } + 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. ClientID:{Id}. ClientFIO: {ClientFIO}. Email:{ Email}. Password: { Password}", model.Id, model.ClientFIO, model.Email, model.Password); var element = _clientStorage.GetElement(new ClientSearchModel { diff --git a/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/OrderLogic.cs b/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/OrderLogic.cs index 78ee495..b6c0f7b 100644 --- a/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/OrderLogic.cs +++ b/ComputersShop/ComputersShopBusinessLogic/BusinessLogic/OrderLogic.cs @@ -18,10 +18,14 @@ namespace ComputersShopBusinessLogic.BusinessLogic private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; - 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) { @@ -41,11 +45,13 @@ namespace ComputersShopBusinessLogic.BusinessLogic CheckModel(model); if (model.Status != OrderStatus.Неизвестен) return false; model.Status = OrderStatus.Принят; - if (_orderStorage.Insert(model) == null) + var result = _orderStorage.Insert(model); + if (result == null) { _logger.LogWarning("Insert operation failed"); return false; } + SendOrderMessage(result.ClientId, $"DNS, Заказ №{result.Id}", $"Заказ №{result.Id} от {result.DateCreate} на сумму {result.Sum:0.00} принят"); return true; } public bool ChangeStatus(OrderBindingModel model, OrderStatus status) @@ -57,6 +63,7 @@ namespace ComputersShopBusinessLogic.BusinessLogic _logger.LogWarning("Read operation failed"); return false; } + if (element.Status != status - 1) { _logger.LogWarning("Status change operation failed"); @@ -65,6 +72,7 @@ namespace ComputersShopBusinessLogic.BusinessLogic model.Status = status; if (model.Status == OrderStatus.Выдан) model.DateImplement = DateTime.Now; _orderStorage.Update(model); + SendOrderMessage(element.ClientId, $"DNS, Заказ №{element.Id}", $"Заказ №{model.Id} изменен статус на {element.Status}"); return true; } @@ -103,5 +111,20 @@ namespace ComputersShopBusinessLogic.BusinessLogic } _logger.LogInformation("Order. Sum:{ Cost}. Id: { Id}", model.Sum, model.Id); } + 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 3029ee4..b026805 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..0f07ce6 --- /dev/null +++ b/ComputersShop/ComputersShopBusinessLogic/MailWorker/AbstractMailWorker.cs @@ -0,0 +1,101 @@ +using ComputersShopContracts.BindingModels; +using ComputersShopContracts.BusinessLogicContracts; +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 IClientLogic _clientLogic; + + private readonly ILogger _logger; + + public AbstractMailWorker(ILogger logger, IMessageInfoLogic messageInfoLogic, IClientLogic clientLogic) + { + _logger = logger; + _messageInfoLogic = messageInfoLogic; + _clientLogic = clientLogic; + } + + public void MailConfig(MailConfigBindingModel config) + { + _mailLogin = config.MailLogin; + _mailPassword = config.MailPassword; + _smtpClientHost = config.SmtpClientHost; + _smtpClientPort = config.SmtpClientPort; + _popHost = config.PopHost; + _popPort = config.PopPort; + _logger.LogDebug("Config: {login}, {password}, {clientHost}, {clientPOrt}, {popHost}, {popPort}", _mailLogin, _mailPassword, _smtpClientHost, _smtpClientPort, _popHost, _popPort); + } + + public async void MailSendAsync(MailSendInfoBindingModel info) + { + if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword)) + { + return; + } + + if (string.IsNullOrEmpty(_smtpClientHost) || _smtpClientPort == 0) + { + return; + } + + if (string.IsNullOrEmpty(info.MailAddress) || string.IsNullOrEmpty(info.Subject) || string.IsNullOrEmpty(info.Text)) + { + return; + } + + _logger.LogDebug("Send Mail: {To}, {Subject}", info.MailAddress, info.Subject); + await SendMailAsync(info); + } + + public async void MailCheck() + { + if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword)) + { + return; + } + + if (string.IsNullOrEmpty(_popHost) || _popPort == 0) + { + return; + } + + if (_messageInfoLogic == null) + { + return; + } + + var list = await ReceiveMailAsync(); + _logger.LogDebug("Check Mail: {Count} new mails", list.Count); + foreach (var mail in list) + { + mail.ClientId = _clientLogic.ReadElement(new() { Email = mail.SenderName })?.Id; + _messageInfoLogic.Create(mail); + } + } + + protected abstract Task SendMailAsync(MailSendInfoBindingModel info); + + protected abstract Task> ReceiveMailAsync(); + } +} diff --git a/ComputersShop/ComputersShopBusinessLogic/MailWorker/MailKitWorker.cs b/ComputersShop/ComputersShopBusinessLogic/MailWorker/MailKitWorker.cs new file mode 100644 index 0000000..c7e1a82 --- /dev/null +++ b/ComputersShop/ComputersShopBusinessLogic/MailWorker/MailKitWorker.cs @@ -0,0 +1,83 @@ +using ComputersShopContracts.BindingModels; +using ComputersShopContracts.BusinessLogicContracts; +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.Mail; +using System.Net; +using System.Text; +using System.Threading.Tasks; + +namespace ComputersShopBusinessLogic.MailWorker +{ + public class MailKitWorker : AbstractMailWorker + { + public MailKitWorker(ILogger logger, IMessageInfoLogic messageInfoLogic, IClientLogic clientLogic) : base(logger, messageInfoLogic, clientLogic) { } + + protected override async Task SendMailAsync(MailSendInfoBindingModel info) + { + using var objMailMessage = new MailMessage(); + using var objSmtpClient = new SmtpClient(_smtpClientHost, _smtpClientPort); + try + { + objMailMessage.From = new MailAddress(_mailLogin); + objMailMessage.To.Add(new MailAddress(info.MailAddress)); + objMailMessage.Subject = info.Subject; + objMailMessage.Body = info.Text; + objMailMessage.SubjectEncoding = Encoding.UTF8; + objMailMessage.BodyEncoding = Encoding.UTF8; + + objSmtpClient.UseDefaultCredentials = false; + objSmtpClient.EnableSsl = true; + objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; + objSmtpClient.Credentials = new NetworkCredential(_mailLogin, _mailPassword); + + await Task.Run(() => objSmtpClient.Send(objMailMessage)); + } + catch (Exception) + { + throw; + } + } + + protected override async Task> ReceiveMailAsync() + { + var list = new List(); + using var client = new Pop3Client(); + await Task.Run(() => + { + try + { + client.Connect(_popHost, _popPort, SecureSocketOptions.SslOnConnect); + client.Authenticate(_mailLogin, _mailPassword); + for (int i = 0; i < client.Count; i++) + { + var message = client.GetMessage(i); + foreach (var mail in message.From.Mailboxes) + { + list.Add(new MessageInfoBindingModel + { + DateDelivery = message.Date.DateTime, + MessageId = message.MessageId, + SenderName = mail.Address, + Subject = message.Subject, + Body = message.TextBody, + }); + } + } + } + catch (AuthenticationException) + { } + finally + { + client.Disconnect(true); + } + }); + return list; + } + } +} diff --git a/ComputersShop/ComputersShopClientApp/APIClient.cs b/ComputersShop/ComputersShopClientApp/APIClient.cs index a15a863..d292edc 100644 --- a/ComputersShop/ComputersShopClientApp/APIClient.cs +++ b/ComputersShop/ComputersShopClientApp/APIClient.cs @@ -13,6 +13,8 @@ namespace ComputersShopClientApp { private static readonly HttpClient _client = new(); + public static int MailPage { get; set; } = 1; + public static ClientViewModel? Client { get; set; } = null; public static void Connect(IConfiguration configuration) diff --git a/ComputersShop/ComputersShopClientApp/Controllers/HomeController.cs b/ComputersShop/ComputersShopClientApp/Controllers/HomeController.cs index 8df9080..81c40e7 100644 --- a/ComputersShop/ComputersShopClientApp/Controllers/HomeController.cs +++ b/ComputersShop/ComputersShopClientApp/Controllers/HomeController.cs @@ -142,5 +142,15 @@ namespace ComputersShopClientApp.Controllers var prod = APIClient.GetRequest($"api/main/getcomputer?computerId={computer}"); return count * (prod?.Price ?? 1); } + + [HttpGet] + public IActionResult Mails() + { + if (APIClient.Client == null) + { + return Redirect("~/Home/Enter"); + } + return View(APIClient.GetRequest>($"api/client/getmessages?clientId={APIClient.Client.Id}")); + } } } diff --git a/ComputersShop/ComputersShopClientApp/Views/Home/Mails.cshtml b/ComputersShop/ComputersShopClientApp/Views/Home/Mails.cshtml new file mode 100644 index 0000000..678439b --- /dev/null +++ b/ComputersShop/ComputersShopClientApp/Views/Home/Mails.cshtml @@ -0,0 +1,52 @@ +@model List + +@{ + ViewData["Title"] = "Mails"; +} + +
+

Письма

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

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

+ return; + } + + + + + + + + + + + @foreach (var item in Model) + { + + + + + + } + +
+ Дата письма + + Заголовок + + Текст +
+ @Html.DisplayFor(modelItem => item.DateDelivery) + + @Html.DisplayFor(modelItem => item.Subject) + + @Html.DisplayFor(modelItem => item.Body) +
+ } +
\ No newline at end of file diff --git a/ComputersShop/ComputersShopClientApp/Views/Shared/_Layout.cshtml b/ComputersShop/ComputersShopClientApp/Views/Shared/_Layout.cshtml index 491b2d2..89ca8e1 100644 --- a/ComputersShop/ComputersShopClientApp/Views/Shared/_Layout.cshtml +++ b/ComputersShop/ComputersShopClientApp/Views/Shared/_Layout.cshtml @@ -31,6 +31,9 @@ + diff --git a/ComputersShop/ComputersShopContracts/ViewModels/OrderViewModel.cs b/ComputersShop/ComputersShopContracts/ViewModels/OrderViewModel.cs index 1433620..d5edd61 100644 --- a/ComputersShop/ComputersShopContracts/ViewModels/OrderViewModel.cs +++ b/ComputersShop/ComputersShopContracts/ViewModels/OrderViewModel.cs @@ -18,6 +18,8 @@ namespace ComputersShopContracts.ViewModels public int ClientId { get; set; } [DisplayName("Фамилия клиента")] public string ClientFIO { get; set; } = string.Empty; + + public string ClientEmail { get; set; } = string.Empty; public string ComputerName { get; set; } = string.Empty; [DisplayName("Количество")] public int Count { get; set; } diff --git a/ComputersShop/ComputersShopDatabaseImplement/ComputersShopDatabase.cs b/ComputersShop/ComputersShopDatabaseImplement/ComputersShopDatabase.cs index cd0a0a8..d13bd89 100644 --- a/ComputersShop/ComputersShopDatabaseImplement/ComputersShopDatabase.cs +++ b/ComputersShop/ComputersShopDatabaseImplement/ComputersShopDatabase.cs @@ -24,5 +24,6 @@ namespace ComputersShopDatabaseImplement public virtual DbSet ComputerComponents { set; get; } public virtual DbSet Orders { set; get; } public virtual DbSet Clients { set; get; } + public virtual DbSet Messages { set; get; } } } diff --git a/ComputersShop/ComputersShopDatabaseImplement/Implements/ClientStorage.cs b/ComputersShop/ComputersShopDatabaseImplement/Implements/ClientStorage.cs index 800e401..8742833 100644 --- a/ComputersShop/ComputersShopDatabaseImplement/Implements/ClientStorage.cs +++ b/ComputersShop/ComputersShopDatabaseImplement/Implements/ClientStorage.cs @@ -27,17 +27,20 @@ namespace ComputersShopDatabaseImplement.Implements public ClientViewModel? GetElement(ClientSearchModel model) { - using var context = new ComputersShopDatabase(); - if (model.Id.HasValue) - return context.Clients.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; - if (model.Email != null && model.Password != null) - return context.Clients - .FirstOrDefault(x => x.Email.Equals(model.Email) - && x.Password.Equals(model.Password)) - ?.GetViewModel; - if (model.Email != null) - return context.Clients.FirstOrDefault(x => x.Email.Equals(model.Email))?.GetViewModel; - return null; + if (string.IsNullOrEmpty(model.ClientFIO) && + string.IsNullOrEmpty(model.Email) && + string.IsNullOrEmpty(model.Password) && + !model.Id.HasValue) + { + return null; + } + var temp = context.Clients + .FirstOrDefault(x => (string.IsNullOrEmpty(model.ClientFIO) || x.ClientFIO == model.ClientFIO) && + (string.IsNullOrEmpty(model.Email) || x.Email == model.Email) && + (string.IsNullOrEmpty(model.Password) || x.Password == model.Password) && + (!model.Id.HasValue || x.Id == model.Id)) + ?.GetViewModel; + return temp; } public List GetFilteredList(ClientSearchModel model) diff --git a/ComputersShop/ComputersShopDatabaseImplement/Implements/OrderStorage.cs b/ComputersShop/ComputersShopDatabaseImplement/Implements/OrderStorage.cs index c00e178..72c033b 100644 --- a/ComputersShop/ComputersShopDatabaseImplement/Implements/OrderStorage.cs +++ b/ComputersShop/ComputersShopDatabaseImplement/Implements/OrderStorage.cs @@ -14,49 +14,122 @@ namespace ComputersShopDatabaseImplement.Implements { public class OrderStorage : IOrderStorage { - public List GetFullList() + public OrderViewModel? Delete(OrderBindingModel model) { - using var context = new ComputersShopDatabase(); - return context.Orders.Include(x => x.Computer).Select(x => x.GetViewModel).ToList(); - } - - public List GetFilteredList(OrderSearchModel model) - { - if (!model.Id.HasValue && (model.DateFrom == null || model.DateTo == null)) + using var context = new ComputersShopDataBase(); + var element = context.Orders + .FirstOrDefault(rec => rec.Id == model.Id); + if (element != null) { - return new(); - } - using var context = new ComputersShopDatabase(); - if (model.Id.HasValue) - { - return context.Orders - .Include(x => x.Computer) - .Where(x => x.Id == model.Id) - .Select(x => x.GetViewModel) - .ToList(); - } - else - { - return context.Orders - .Include(x => x.Computer) - .Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo) - .Select(x => x.GetViewModel) - .ToList(); + var deletedElement = context.Orders + .Include(x => x.Computer) + .Include(x => x.Client) + .Include(x => x.Implementer) + .FirstOrDefault(x => x.Id == model.Id) + ?.GetViewModel; + context.Orders.Remove(element); + context.SaveChanges(); + return deletedElement; } + return null; } public OrderViewModel? GetElement(OrderSearchModel model) { if (!model.Id.HasValue) { - return new(); + return null; } - using var context = new ComputersShopDatabase(); + + using var context = new ComputersShopDataBase(); + if (model.ImplementerId.HasValue && model.Status.HasValue) + { + return context.Orders + .Include(x => x.Computer) + .Include(x => x.Client) + .Include(x => x.Implementer) + .FirstOrDefault(x => x.ImplementerId == model.ImplementerId && x.Status == model.Status) + ?.GetViewModel; + } + if (model.ImplementerId.HasValue) + { + return context.Orders + .Include(x => x.Computer) + .Include(x => x.Client) + .Include(x => x.Implementer) + .FirstOrDefault(x => x.ImplementerId == model.ImplementerId) + ?.GetViewModel; + } + return context.Orders - .Include(x => x.Computer) - .Include(x => x.Client) - .FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id) - ?.GetViewModel; + .Include(x => x.Computer) + .Include(x => x.Client) + .Include(x => x.Implementer) + .FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id) + ?.GetViewModel; + } + + public List GetFilteredList(OrderSearchModel model) + { + using var context = new ComputersShopDataBase(); + if (model.Id.HasValue) + { + return context.Orders + .Include(x => x.Computer) + .Include(x => x.Client) + .Include(x => x.Implementer) + .Where(x => x.Id == model.Id) + .Select(x => x.GetViewModel) + .ToList(); + } + else if (model.DateFrom != null && model.DateTo != null) + { + return context.Orders + .Include(x => x.Computer) + .Include(x => x.Client) + .Include(x => x.Implementer) + .Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo) + .Select(x => x.GetViewModel) + .ToList(); + } + else if (model.ClientId.HasValue) + { + return context.Orders + .Include(x => x.Computer) + .Include(x => x.Client) + .Include(x => x.Implementer) + .Where(x => x.ClientId == model.ClientId) + .Select(x => x.GetViewModel) + .ToList(); + } + else if (model.ImplementerId.HasValue) + { + return context.Orders + .Include(x => x.Computer) + .Include(x => x.Client) + .Include(x => x.Implementer) + .Where(x => x.ImplementerId == model.ImplementerId) + .Select(x => x.GetViewModel) + .ToList(); + } + return context.Orders + .Include(x => x.Computer) + .Include(x => x.Client) + .Include(x => x.Implementer) + .Where(x => model.Status == x.Status) + .Select(x => x.GetViewModel) + .ToList(); + } + + public List GetFullList() + { + using var context = new ComputersShopDataBase(); + return context.Orders + .Include(x => x.Computer) + .Include(x => x.Client) + .Include(x => x.Implementer) + .Select(x => x.GetViewModel) + .ToList(); } public OrderViewModel? Insert(OrderBindingModel model) @@ -66,23 +139,25 @@ namespace ComputersShopDatabaseImplement.Implements { return null; } - using var context = new ComputersShopDatabase(); - if (model == null) - return null; - + + using var context = new ComputersShopDataBase(); + context.Orders.Add(newOrder); context.SaveChanges(); return context.Orders .Include(x => x.Computer) .Include(x => x.Client) + .Include(x => x.Implementer) .FirstOrDefault(x => x.Id == newOrder.Id) ?.GetViewModel; } public OrderViewModel? Update(OrderBindingModel model) { - using var context = new ComputersShopDatabase(); + using var context = new ComputersShopDataBase(); + var order = context.Orders.Include(x => x.Client).FirstOrDefault(x => x.Id == model.Id); + if (order == null) { return null; @@ -92,25 +167,9 @@ namespace ComputersShopDatabaseImplement.Implements return context.Orders .Include(x => x.Computer) .Include(x => x.Client) + .Include(x => x.Implementer) .FirstOrDefault(x => x.Id == model.Id) ?.GetViewModel; } - - public OrderViewModel? Delete(OrderBindingModel model) - { - using var context = new ComputersShopDatabase(); - var order = context.Orders.FirstOrDefault(rec => rec.Id == model.Id); - if (order != null) - { - var deletedElement = context.Orders - .Include(x => x.Computer) - .FirstOrDefault(x => x.Id == model.Id) - ?.GetViewModel; - context.Orders.Remove(order); - context.SaveChanges(); - return deletedElement; - } - return null; - } } } diff --git a/ComputersShop/ComputersShopDatabaseImplement/Models/Client.cs b/ComputersShop/ComputersShopDatabaseImplement/Models/Client.cs index 2529f5f..8de42c7 100644 --- a/ComputersShop/ComputersShopDatabaseImplement/Models/Client.cs +++ b/ComputersShop/ComputersShopDatabaseImplement/Models/Client.cs @@ -26,6 +26,8 @@ namespace ComputersShopDatabaseImplement.Models [ForeignKey("ClientId")] public virtual List Orders { get; set; } = new(); + [ForeignKey("ClientId")] + public virtual List Messages { get; set; } = new(); public static Client? Create(ClientBindingModel model) { diff --git a/ComputersShop/ComputersShopDatabaseImplement/Models/Message.cs b/ComputersShop/ComputersShopDatabaseImplement/Models/Message.cs new file mode 100644 index 0000000..42faf5e --- /dev/null +++ b/ComputersShop/ComputersShopDatabaseImplement/Models/Message.cs @@ -0,0 +1,56 @@ +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 ComputersShopDataBaseImplement.Models +{ + public class Message : IMessageInfoModel + { + [Key] + public string MessageId { get; private set; } = string.Empty; + + public int? ClientId { get; private set; } + + public virtual Client? Client { get; set; } + + public string SenderName { get; private set; } = string.Empty; + + public DateTime DateDelivery { get; private set; } = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc); + + public string Subject { get; private set; } = string.Empty; + + public string Body { get; private set; } = string.Empty; + + public static Message? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Subject = model.Subject, + ClientId = model.ClientId, + MessageId = model.MessageId, + SenderName = model.SenderName, + DateDelivery = DateTime.SpecifyKind(model.DateDelivery, DateTimeKind.Utc) + }; + } + + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Subject = Subject, + ClientId = ClientId, + MessageId = MessageId, + SenderName = SenderName, + DateDelivery = DateDelivery, + }; + } +} \ No newline at end of file diff --git a/ComputersShop/ComputersShopDatabaseImplement/Models/Order.cs b/ComputersShop/ComputersShopDatabaseImplement/Models/Order.cs index 564238b..5775e5e 100644 --- a/ComputersShop/ComputersShopDatabaseImplement/Models/Order.cs +++ b/ComputersShop/ComputersShopDatabaseImplement/Models/Order.cs @@ -19,7 +19,7 @@ namespace ComputersShopDatabaseImplement.Models [Required] public int ComputerId { get; private set; } - + public virtual Computer Computer { get; set; } = new(); @@ -82,6 +82,7 @@ namespace ComputersShopDatabaseImplement.Models Status = Status, DateCreate = DateCreate, DateImplement = DateImplement, + ClientEmail = Client.Email, }; } } diff --git a/ComputersShop/ComputersShopFileImplement/DataFileSingleton.cs b/ComputersShop/ComputersShopFileImplement/DataFileSingleton.cs index 633a59a..1a3f85d 100644 --- a/ComputersShop/ComputersShopFileImplement/DataFileSingleton.cs +++ b/ComputersShop/ComputersShopFileImplement/DataFileSingleton.cs @@ -10,10 +10,12 @@ namespace ComputersShopFileImplement private readonly string OrderFileName = "Order.xml"; private readonly string ComputerFileName = "Computer.xml"; private readonly string ClientFileName = "Client.xml"; + private readonly string MessageFileName = "Message.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 Messages { get; private set; } public static DataFileSingleton GetInstance() { @@ -28,13 +30,14 @@ namespace ComputersShopFileImplement public void SaveComputers() => SaveData(Computers, ComputerFileName, "Computers", x => x.GetXElement); public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement); public void SaveClients() => SaveData(Clients, OrderFileName, "Clients", x => x.GetXElement); - + public void SaveMessages() => SaveData(Messages, MessageFileName, "Messages", x => x.GetXElement); private DataFileSingleton() { Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!; Computers = LoadData(ComputerFileName, "Computer", x => Computer.Create(x)!)!; Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!; Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!; + Messages = LoadData(MessageFileName, "MessageInfo", x => Message.Create(x)!)!; } private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) diff --git a/ComputersShop/ComputersShopListImplement/DataListSingleton.cs b/ComputersShop/ComputersShopListImplement/DataListSingleton.cs index 5450b07..313b967 100644 --- a/ComputersShop/ComputersShopListImplement/DataListSingleton.cs +++ b/ComputersShop/ComputersShopListImplement/DataListSingleton.cs @@ -9,12 +9,14 @@ namespace ComputersShopListImplement public List Orders { get; set; } public List Computers { get; set; } public List Clients { get; set; } + public List Messages { get; set; } private DataListSingleton() { Components = new List(); Orders = new List(); Computers = new List(); Clients = new List(); + Messages = new List(); } public static DataListSingleton GetInstance() { diff --git a/ComputersShop/ComputersShopRestApi/Controllers/ClientController.cs b/ComputersShop/ComputersShopRestApi/Controllers/ClientController.cs index 22a5fae..7165ca8 100644 --- a/ComputersShop/ComputersShopRestApi/Controllers/ClientController.cs +++ b/ComputersShop/ComputersShopRestApi/Controllers/ClientController.cs @@ -1,4 +1,5 @@ using ComputersShopContracts.BindingModels; +using ComputersShopContracts.BusinessLogicContracts; using ComputersShopContracts.BusinessLogicsContracts; using ComputersShopContracts.SearchModels; using ComputersShopContracts.ViewModels; @@ -13,11 +14,12 @@ namespace ComputersShopRestApi.Controllers private readonly ILogger _logger; private readonly IClientLogic _logic; - - public ClientController(IClientLogic logic, ILogger logger) + private readonly IMessageInfoLogic _mailLogic; + public ClientController(IClientLogic logic, ILogger logger, IMessageInfoLogic mailLogic) { _logger = logger; _logic = logic; + _mailLogic = mailLogic; } [HttpGet] @@ -66,5 +68,23 @@ 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 2c94cc2..fb34fe8 100644 --- a/ComputersShop/ComputersShopRestApi/Program.cs +++ b/ComputersShop/ComputersShopRestApi/Program.cs @@ -1,7 +1,12 @@ using ComputersShopBusinessLogic.BusinessLogic; +using ComputersShopBusinessLogic.BusinessLogics; +using ComputersShopBusinessLogic.MailWorker; +using ComputersShopContracts.BindingModels; +using ComputersShopContracts.BusinessLogicContracts; using ComputersShopContracts.BusinessLogicsContracts; using ComputersShopContracts.StoragesContracts; using ComputersShopDatabaseImplement.Implements; +using ComputersShopDataBaseImplement.Implements; using Microsoft.OpenApi.Models; var builder = WebApplication.CreateBuilder(args); @@ -13,10 +18,14 @@ builder.Logging.AddLog4Net("log4net.config"); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddTransient(); + +builder.Services.AddSingleton(); builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle @@ -32,6 +41,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..8c89e0b 100644 --- a/ComputersShop/ComputersShopRestApi/appsettings.json +++ b/ComputersShop/ComputersShopRestApi/appsettings.json @@ -5,5 +5,11 @@ "Microsoft.AspNetCore": "Warning" } }, - "AllowedHosts": "*" + "AllowedHosts": "*", + "SmtpClientHost": "smtp.gmail.com", + "SmtpClientPort": "587", + "PopHost": "pop.gmail.com", + "PopPort": "995", + "MailLogin": "rpplabs900@gmail.com", + "MailPassword": "wmbu qrgy ocwl tadm" } diff --git a/ComputersShop/ComputersShopView/Program.cs b/ComputersShop/ComputersShopView/Program.cs index d6bf5de..67276f9 100644 --- a/ComputersShop/ComputersShopView/Program.cs +++ b/ComputersShop/ComputersShopView/Program.cs @@ -9,6 +9,11 @@ using ComputersShopView; using ComputersShopBusinessLogic.OfficePackage.Implements; using ComputersShopBusinessLogic.OfficePackage; using ComputersShopBusinessLogic; +using ComputersShopBusinessLogic.MailWorker; +using ComputersShopContracts.BindingModels; +using ComputersShopBusinessLogic.BusinessLogics; +using ComputersShopContracts.BusinessLogicContracts; +using ComputersShopDataBaseImplement.Implements; namespace ComputersShop @@ -29,6 +34,26 @@ namespace ComputersShop var services = new ServiceCollection(); ConfigureServices(services); _serviceProvider = services.BuildServiceProvider(); + try + { + var mailSender = _serviceProvider.GetService(); + mailSender?.MailConfig(new MailConfigBindingModel + { + MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty, + MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty, + SmtpClientHost = System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty, + SmtpClientPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]), + PopHost = System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty, + PopPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"]) + }); + + var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000); + } + catch (Exception ex) + { + var logger = _serviceProvider.GetService(); + logger?.LogError(ex, "<22><> <20><> <20> <20><>"); + } Application.Run(_serviceProvider.GetRequiredService()); } private static void ConfigureServices(ServiceCollection services) @@ -42,16 +67,19 @@ namespace ComputersShop services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddSingleton(); services.AddTransient(); services.AddTransient(); -- 2.25.1 From 945fa5c83d39679840c39fddd26ef5330b089cd5 Mon Sep 17 00:00:00 2001 From: "kagbie3nn@mail.ru" Date: Sun, 16 Jun 2024 11:31:13 +0400 Subject: [PATCH 9/9] 7 --- .../BindingModels/MailSendInfoBindingModel.cs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/ComputersShop/ComputersShopContracts/BindingModels/MailSendInfoBindingModel.cs b/ComputersShop/ComputersShopContracts/BindingModels/MailSendInfoBindingModel.cs index f9b4566..270d231 100644 --- a/ComputersShop/ComputersShopContracts/BindingModels/MailSendInfoBindingModel.cs +++ b/ComputersShop/ComputersShopContracts/BindingModels/MailSendInfoBindingModel.cs @@ -8,10 +8,16 @@ namespace ComputersShopContracts.BindingModels { public class MailSendInfoBindingModel { - public string MailAddress { get; set; } = string.Empty; + public string MessageId { get; set; } = string.Empty; + + public int? ClientId { get; set; } + + public string SenderName { get; set; } = string.Empty; public string Subject { get; set; } = string.Empty; - public string Text { get; set; } = string.Empty; + public string Body { get; set; } = string.Empty; + + public DateTime DateDelivery { get; set; } } } -- 2.25.1