From d1eee31e9a4e3016dee84e3561a1d28701471fcb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=80=D1=82=D0=B5=D0=BC=20=D0=A5=D0=B0=D1=80=D0=BB?= =?UTF-8?q?=D0=B0=D0=BC=D0=BE=D0=B2?= Date: Tue, 30 May 2023 14:01:59 +0400 Subject: [PATCH 1/4] =?UTF-8?q?=D0=9B=D0=B0=D0=B17=20-=20=D0=92=D0=BD?= =?UTF-8?q?=D0=B5=D0=B4=D1=80=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=BD=D0=BE=D0=B2?= =?UTF-8?q?=D0=BE=D0=B9=20=D1=81=D1=83=D1=89=D0=BD=D0=BE=D1=81=D1=82=D0=B8?= =?UTF-8?q?=20MessageInfo.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../BusinessLogics/ClientLogic.cs | 16 +++- .../BusinessLogics/MessageInfoLogic.cs | 82 +++++++++++++++++++ .../BindingModels/MessageInfoBindingModel.cs | 19 +++++ .../IMessageInfoLogic.cs | 18 ++++ .../SearchModels/MessageInfoSearchModel.cs | 14 ++++ .../StoragesContracts/IMessageInfoStorage.cs | 19 +++++ .../ViewModels/MessageInfoViewModel.cs | 24 ++++++ .../ViewModels/OrderViewModel.cs | 3 +- .../Models/IMessageInfoModel.cs | 18 ++++ .../AbstractFoodOrdersDatabase.cs | 1 + .../Implements/MessageInfoStorage.cs | 59 +++++++++++++ .../Models/MessageInfo.cs | 56 +++++++++++++ .../Models/Order.cs | 1 + .../DataListSingleton.cs | 2 + .../DataFileSingleton.cs | 4 + .../Implements/MessageInfoStorage.cs | 61 ++++++++++++++ .../Models/MessageInfo.cs | 74 +++++++++++++++++ FoodOrders/FoodOrders/FormMails.Designer.cs | 67 +++++++++++++++ FoodOrders/FoodOrders/FormMails.cs | 47 +++++++++++ FoodOrders/FoodOrders/FormMails.resx | 60 ++++++++++++++ 20 files changed, 642 insertions(+), 3 deletions(-) create mode 100644 FoodOrders/AbstractFoodOrdersBusinessLogic/BusinessLogics/MessageInfoLogic.cs create mode 100644 FoodOrders/AbstractFoodOrdersContracts/BindingModels/MessageInfoBindingModel.cs create mode 100644 FoodOrders/AbstractFoodOrdersContracts/BusinessLogicsContracts/IMessageInfoLogic.cs create mode 100644 FoodOrders/AbstractFoodOrdersContracts/SearchModels/MessageInfoSearchModel.cs create mode 100644 FoodOrders/AbstractFoodOrdersContracts/StoragesContracts/IMessageInfoStorage.cs create mode 100644 FoodOrders/AbstractFoodOrdersContracts/ViewModels/MessageInfoViewModel.cs create mode 100644 FoodOrders/AbstractFoodOrdersDataModels/Models/IMessageInfoModel.cs create mode 100644 FoodOrders/AbstractFoodOrdersDatabaseImplement/Implements/MessageInfoStorage.cs create mode 100644 FoodOrders/AbstractFoodOrdersDatabaseImplement/Models/MessageInfo.cs create mode 100644 FoodOrders/AbstractShopFileImplement/Implements/MessageInfoStorage.cs create mode 100644 FoodOrders/AbstractShopFileImplement/Models/MessageInfo.cs create mode 100644 FoodOrders/FoodOrders/FormMails.Designer.cs create mode 100644 FoodOrders/FoodOrders/FormMails.cs create mode 100644 FoodOrders/FoodOrders/FormMails.resx diff --git a/FoodOrders/AbstractFoodOrdersBusinessLogic/BusinessLogics/ClientLogic.cs b/FoodOrders/AbstractFoodOrdersBusinessLogic/BusinessLogics/ClientLogic.cs index ddd7420..b437a61 100644 --- a/FoodOrders/AbstractFoodOrdersBusinessLogic/BusinessLogics/ClientLogic.cs +++ b/FoodOrders/AbstractFoodOrdersBusinessLogic/BusinessLogics/ClientLogic.cs @@ -8,6 +8,7 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; +using System.Text.RegularExpressions; using System.Threading.Tasks; namespace AbstractFoodOrdersBusinessLogic.BusinessLogics @@ -16,8 +17,10 @@ namespace AbstractFoodOrdersBusinessLogic.BusinessLogics { private readonly ILogger _logger; private readonly IClientStorage _clientStorage; + private Regex validateEmailRegex = new Regex("^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$"); + private Regex validatePasswordRegex = new Regex("^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).(?=.*?[#?!@$%^&*-]).{10,50}$"); - public ClientLogic(ILogger logger, IClientStorage clientStorage) + public ClientLogic(ILogger logger, IClientStorage clientStorage) { _logger = logger; _clientStorage = clientStorage; @@ -108,11 +111,20 @@ namespace AbstractFoodOrdersBusinessLogic.BusinessLogics { throw new ArgumentNullException("Нет электронной почты клиента", nameof(model.Email)); } - _logger.LogInformation("Client. ClientFIO:{ClientFIO}. Password:{Password}. Email:{Email}. Id:{Id}", model.ClientFIO, model.Password, model.Email, model.Id); + if (!validateEmailRegex.IsMatch(model.Email)) + { + throw new InvalidOperationException("Почта введена некорректно!"); + } + if (!validatePasswordRegex.IsMatch(model.Password)) + { + throw new InvalidOperationException("Пароль не удовлетворяет требованиям"); + } + _logger.LogInformation("Client. ClientFIO:{ClientFIO}. Password:{Password}. Email:{Email}. Id:{Id}", model.ClientFIO, model.Password, model.Email, model.Id); var element = _clientStorage.GetElement(new ClientSearchModel { Email = model.Email }); + if (element != null && element.Id != model.Id) { throw new InvalidOperationException("Клиент с таким логином уже зарегистрирован"); diff --git a/FoodOrders/AbstractFoodOrdersBusinessLogic/BusinessLogics/MessageInfoLogic.cs b/FoodOrders/AbstractFoodOrdersBusinessLogic/BusinessLogics/MessageInfoLogic.cs new file mode 100644 index 0000000..b7116b5 --- /dev/null +++ b/FoodOrders/AbstractFoodOrdersBusinessLogic/BusinessLogics/MessageInfoLogic.cs @@ -0,0 +1,82 @@ +using AbstractFoodOrdersContracts.BindingModels; +using AbstractFoodOrdersContracts.BusinessLogicsContracts; +using AbstractFoodOrdersContracts.SearchModels; +using AbstractFoodOrdersContracts.StoragesContracts; +using AbstractFoodOrdersContracts.ViewModels; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AbstractFoodOrdersBusinessLogic.BusinessLogics +{ + public class MessageInfoLogic: IMessageInfoLogic + { + private readonly ILogger _logger; + private readonly IMessageInfoStorage _messageStorage; + private readonly IClientLogic _clientLogic; + + public MessageInfoLogic(ILogger logger, IMessageInfoStorage logic, IClientLogic clientLogic) + { + _logger = logger; + _messageStorage = logic; + _clientLogic = clientLogic; + } + + public List? ReadList(MessageInfoSearchModel? model) + { + _logger.LogInformation("ReadList. MessageId:{MessageId}. ClientId:{ClientId}.", model?.MessageId, model?.ClientId); + var list = model == null ? _messageStorage.GetFullList() : _messageStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + _logger.LogInformation("ReadList. Count:{Count}", list.Count); + return list; + } + + public bool Create(MessageInfoBindingModel model) + { + CheckModel(model); + model.ClientId = _clientLogic.ReadElement(new ClientSearchModel() { Email = model.SenderName })?.Id; + if (_messageStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } + + 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); + } + } +} diff --git a/FoodOrders/AbstractFoodOrdersContracts/BindingModels/MessageInfoBindingModel.cs b/FoodOrders/AbstractFoodOrdersContracts/BindingModels/MessageInfoBindingModel.cs new file mode 100644 index 0000000..5ec9cd6 --- /dev/null +++ b/FoodOrders/AbstractFoodOrdersContracts/BindingModels/MessageInfoBindingModel.cs @@ -0,0 +1,19 @@ +using AbstractFoodOrdersDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AbstractFoodOrdersContracts.BindingModels +{ + public class MessageInfoBindingModel:IMessageInfoModel + { + public string MessageId { get; set; } = string.Empty; + public int? ClientId { get; set; } + public string SenderName { get; set; } = string.Empty; + public DateTime DateDelivery { get; set; } + public string Subject { get; set; } = string.Empty; + public string Body { get; set; } = string.Empty; + } +} diff --git a/FoodOrders/AbstractFoodOrdersContracts/BusinessLogicsContracts/IMessageInfoLogic.cs b/FoodOrders/AbstractFoodOrdersContracts/BusinessLogicsContracts/IMessageInfoLogic.cs new file mode 100644 index 0000000..a16c752 --- /dev/null +++ b/FoodOrders/AbstractFoodOrdersContracts/BusinessLogicsContracts/IMessageInfoLogic.cs @@ -0,0 +1,18 @@ +using AbstractFoodOrdersContracts.BindingModels; +using AbstractFoodOrdersContracts.SearchModels; +using AbstractFoodOrdersContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AbstractFoodOrdersContracts.BusinessLogicsContracts +{ + public interface IMessageInfoLogic + { + List? ReadList(MessageInfoSearchModel? model); + bool Create(MessageInfoBindingModel model); + + } +} diff --git a/FoodOrders/AbstractFoodOrdersContracts/SearchModels/MessageInfoSearchModel.cs b/FoodOrders/AbstractFoodOrdersContracts/SearchModels/MessageInfoSearchModel.cs new file mode 100644 index 0000000..4ca4aa9 --- /dev/null +++ b/FoodOrders/AbstractFoodOrdersContracts/SearchModels/MessageInfoSearchModel.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AbstractFoodOrdersContracts.SearchModels +{ + public class MessageInfoSearchModel + { + public string? MessageId { get; set; } + public int? ClientId { get; set; } + } +} diff --git a/FoodOrders/AbstractFoodOrdersContracts/StoragesContracts/IMessageInfoStorage.cs b/FoodOrders/AbstractFoodOrdersContracts/StoragesContracts/IMessageInfoStorage.cs new file mode 100644 index 0000000..849e923 --- /dev/null +++ b/FoodOrders/AbstractFoodOrdersContracts/StoragesContracts/IMessageInfoStorage.cs @@ -0,0 +1,19 @@ +using AbstractFoodOrdersContracts.BindingModels; +using AbstractFoodOrdersContracts.SearchModels; +using AbstractFoodOrdersContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AbstractFoodOrdersContracts.StoragesContracts +{ + public interface IMessageInfoStorage + { + List GetFullList(); + List GetFilteredList(MessageInfoSearchModel model); + MessageInfoViewModel? GetElement(MessageInfoSearchModel model); + MessageInfoViewModel? Insert(MessageInfoBindingModel model); + } +} diff --git a/FoodOrders/AbstractFoodOrdersContracts/ViewModels/MessageInfoViewModel.cs b/FoodOrders/AbstractFoodOrdersContracts/ViewModels/MessageInfoViewModel.cs new file mode 100644 index 0000000..37be3df --- /dev/null +++ b/FoodOrders/AbstractFoodOrdersContracts/ViewModels/MessageInfoViewModel.cs @@ -0,0 +1,24 @@ +using AbstractFoodOrdersDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AbstractFoodOrdersContracts.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/FoodOrders/AbstractFoodOrdersContracts/ViewModels/OrderViewModel.cs b/FoodOrders/AbstractFoodOrdersContracts/ViewModels/OrderViewModel.cs index fd0e73a..994623e 100644 --- a/FoodOrders/AbstractFoodOrdersContracts/ViewModels/OrderViewModel.cs +++ b/FoodOrders/AbstractFoodOrdersContracts/ViewModels/OrderViewModel.cs @@ -22,7 +22,8 @@ namespace AbstractFoodOrdersContracts.ViewModels public int ClientId { get; set; } [DisplayName("ФИО клиента")] public string ClientFIO { get; set; } = string.Empty; - [DisplayName("Количество")] + public string ClientEmail { get; set; } = string.Empty; + [DisplayName("Количество")] public int Count { get; set; } [DisplayName("Сумма")] public double Sum { get; set; } diff --git a/FoodOrders/AbstractFoodOrdersDataModels/Models/IMessageInfoModel.cs b/FoodOrders/AbstractFoodOrdersDataModels/Models/IMessageInfoModel.cs new file mode 100644 index 0000000..668b834 --- /dev/null +++ b/FoodOrders/AbstractFoodOrdersDataModels/Models/IMessageInfoModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AbstractFoodOrdersDataModels.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/FoodOrders/AbstractFoodOrdersDatabaseImplement/AbstractFoodOrdersDatabase.cs b/FoodOrders/AbstractFoodOrdersDatabaseImplement/AbstractFoodOrdersDatabase.cs index 4c3a7f0..bda2253 100644 --- a/FoodOrders/AbstractFoodOrdersDatabaseImplement/AbstractFoodOrdersDatabase.cs +++ b/FoodOrders/AbstractFoodOrdersDatabaseImplement/AbstractFoodOrdersDatabase.cs @@ -27,5 +27,6 @@ namespace AbstractFoodOrdersDatabaseImplement public virtual DbSet Orders { set; get; } public virtual DbSet Clients { set; get; } public virtual DbSet Implementers { set; get; } + public virtual DbSet MessageInfos { set; get; } } } diff --git a/FoodOrders/AbstractFoodOrdersDatabaseImplement/Implements/MessageInfoStorage.cs b/FoodOrders/AbstractFoodOrdersDatabaseImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..e5dd61c --- /dev/null +++ b/FoodOrders/AbstractFoodOrdersDatabaseImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,59 @@ +using AbstractFoodOrdersContracts.BindingModels; +using AbstractFoodOrdersContracts.SearchModels; +using AbstractFoodOrdersContracts.StoragesContracts; +using AbstractFoodOrdersContracts.ViewModels; +using AbstractFoodOrdersDatabaseImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AbstractFoodOrdersDatabaseImplement.Implements +{ + public class MessageInfoStorage:IMessageInfoStorage + { + public List GetFullList() + { + using var context = new AbstractFoodOrdersDatabase(); + return context.MessageInfos + .Select(x => x.GetViewModel) + .ToList(); + } + public List GetFilteredList(MessageInfoSearchModel model) + { + if (string.IsNullOrEmpty(model.MessageId) && !model.ClientId.HasValue) + { + return new(); + } + using var context = new AbstractFoodOrdersDatabase(); + return context.MessageInfos + .Where(x => x.ClientId == model.ClientId) + .Select(x => x.GetViewModel) + .ToList(); + } + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (string.IsNullOrEmpty(model.MessageId) && !model.ClientId.HasValue) + { + return new(); + } + using var context = new AbstractFoodOrdersDatabase(); + return context.MessageInfos + .FirstOrDefault(x => x.MessageId.Equals(model.MessageId) && x.ClientId == model.ClientId) + ?.GetViewModel; + } + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessageInfo = MessageInfo.Create(model); + if (newMessageInfo == null) + { + return null; + } + using var context = new AbstractFoodOrdersDatabase(); + context.MessageInfos.Add(newMessageInfo); + context.SaveChanges(); + return newMessageInfo.GetViewModel; + } + } +} diff --git a/FoodOrders/AbstractFoodOrdersDatabaseImplement/Models/MessageInfo.cs b/FoodOrders/AbstractFoodOrdersDatabaseImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..a677df4 --- /dev/null +++ b/FoodOrders/AbstractFoodOrdersDatabaseImplement/Models/MessageInfo.cs @@ -0,0 +1,56 @@ +using AbstractFoodOrdersContracts.BindingModels; +using AbstractFoodOrdersContracts.ViewModels; +using AbstractFoodOrdersDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations.Schema; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AbstractFoodOrdersDatabaseImplement.Models +{ + public class MessageInfo:IMessageInfoModel + { + [Key] + [DatabaseGenerated(DatabaseGeneratedOption.None)] + public string MessageId { get; set; } = string.Empty; + public int? ClientId { get; set; } + [Required] + public string SenderName { get; set; } = string.Empty; + [Required] + public DateTime DateDelivery { get; set; } + [Required] + public string Subject { get; set; } = string.Empty; + [Required] + public string Body { get; set; } = string.Empty; + + public static MessageInfo? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new MessageInfo() + { + MessageId = model.MessageId, + ClientId = model.ClientId, + SenderName = model.SenderName, + Body = model.Body, + Subject = model.Subject, + DateDelivery = model.DateDelivery + }; + } + + public MessageInfoViewModel GetViewModel => new() + { + MessageId = MessageId, + ClientId = ClientId, + SenderName = SenderName, + Body = Body, + Subject = Subject, + DateDelivery = DateDelivery + }; + } +} diff --git a/FoodOrders/AbstractFoodOrdersDatabaseImplement/Models/Order.cs b/FoodOrders/AbstractFoodOrdersDatabaseImplement/Models/Order.cs index 59b50bf..d6b4958 100644 --- a/FoodOrders/AbstractFoodOrdersDatabaseImplement/Models/Order.cs +++ b/FoodOrders/AbstractFoodOrdersDatabaseImplement/Models/Order.cs @@ -70,6 +70,7 @@ namespace AbstractFoodOrdersDatabaseImplement.Models DishId = DishId, ClientId = ClientId, ClientFIO = Client.ClientFIO, + ClientEmail = Client.Email, Count = Count, Sum = Sum, Status = Status, diff --git a/FoodOrders/AbstractFoodOrdersListImplement/DataListSingleton.cs b/FoodOrders/AbstractFoodOrdersListImplement/DataListSingleton.cs index 18a42b5..2b583e9 100644 --- a/FoodOrders/AbstractFoodOrdersListImplement/DataListSingleton.cs +++ b/FoodOrders/AbstractFoodOrdersListImplement/DataListSingleton.cs @@ -15,6 +15,7 @@ namespace AbstractFoodOrdersListImplement public List Dishes { get; set; } public List Clients { get; set; } public List Implementers { get; set; } + public List MessageInfos { get; set; } private DataListSingleton() { Components = new List(); @@ -22,6 +23,7 @@ namespace AbstractFoodOrdersListImplement Dishes = new List(); Clients = new List(); Implementers = new List(); + MessageInfos = new List(); } public static DataListSingleton GetInstance() { diff --git a/FoodOrders/AbstractShopFileImplement/DataFileSingleton.cs b/FoodOrders/AbstractShopFileImplement/DataFileSingleton.cs index e0e100c..06c2bfb 100644 --- a/FoodOrders/AbstractShopFileImplement/DataFileSingleton.cs +++ b/FoodOrders/AbstractShopFileImplement/DataFileSingleton.cs @@ -16,11 +16,13 @@ namespace AbstractFoodOrdersFileImplement private readonly string DishFileName = "Dish.xml"; private readonly string ClientFileName = "Client.xml"; private readonly string ImplementerFileName = "Implementer.xml"; + private readonly string MessageInfoFileName = "MessageInfo.xml"; public List Components { get; private set; } public List Orders { get; private set; } public List Dishes { get; private set; } public List Clients { get; private set; } public List Implementers { get; private set; } + public List MessageInfos { get; private set; } public static DataFileSingleton GetInstance() { if (instance == null) @@ -34,6 +36,7 @@ namespace AbstractFoodOrdersFileImplement public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement); public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", x => x.GetXElement); public void SaveImplementers() => SaveData(Implementers, ImplementerFileName, "Implementers", x => x.GetXElement); + public void SaveMessageInfos() => SaveData(MessageInfos, MessageInfoFileName, "MessageInfos", x => x.GetXElement); private DataFileSingleton() { Components = LoadData(ComponentFileName, "Component", x => @@ -45,6 +48,7 @@ namespace AbstractFoodOrdersFileImplement Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!; Implementers = LoadData(ImplementerFileName, "Implementer", x => Implementer.Create(x)!)!; + MessageInfos = LoadData(MessageInfoFileName, "MessageInfo", x => MessageInfo.Create(x)!)!; } private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) diff --git a/FoodOrders/AbstractShopFileImplement/Implements/MessageInfoStorage.cs b/FoodOrders/AbstractShopFileImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..a829928 --- /dev/null +++ b/FoodOrders/AbstractShopFileImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,61 @@ +using AbstractFoodOrdersContracts.BindingModels; +using AbstractFoodOrdersContracts.SearchModels; +using AbstractFoodOrdersContracts.StoragesContracts; +using AbstractFoodOrdersContracts.ViewModels; +using AbstractFoodOrdersFileImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AbstractFoodOrdersFileImplement.Implements +{ + public class MessageInfoStorage:IMessageInfoStorage + { + private readonly DataFileSingleton source; + public MessageInfoStorage() + { + source = DataFileSingleton.GetInstance(); + } + public List GetFullList() + { + return source.MessageInfos + .Select(x => x.GetViewModel) + .ToList(); + } + public List GetFilteredList(MessageInfoSearchModel model) + { + if (string.IsNullOrEmpty(model.MessageId) && !model.ClientId.HasValue) + { + return new(); + } + return source.MessageInfos + .Where(x => x.ClientId == model.ClientId) + .Select(x => x.GetViewModel) + .ToList(); + } + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (string.IsNullOrEmpty(model.MessageId) && !model.ClientId.HasValue) + { + return new(); + } + return source.MessageInfos + .FirstOrDefault(x => x.MessageId.Equals(model.MessageId) && x.ClientId == model.ClientId) + ?.GetViewModel; + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessageInfo = MessageInfo.Create(model); + if (newMessageInfo == null) + { + return null; + } + source.MessageInfos.Add(newMessageInfo); + source.SaveMessageInfos(); + return newMessageInfo.GetViewModel; + } + } +} diff --git a/FoodOrders/AbstractShopFileImplement/Models/MessageInfo.cs b/FoodOrders/AbstractShopFileImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..1cf1c5e --- /dev/null +++ b/FoodOrders/AbstractShopFileImplement/Models/MessageInfo.cs @@ -0,0 +1,74 @@ +using AbstractFoodOrdersContracts.BindingModels; +using AbstractFoodOrdersContracts.ViewModels; +using AbstractFoodOrdersDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace AbstractFoodOrdersFileImplement.Models +{ + public class MessageInfo:IMessageInfoModel + { + public string MessageId { get; set; } = string.Empty; + public int? ClientId { get; set; } + public string SenderName { get; set; } = string.Empty; + public DateTime DateDelivery { get; set; } + public string Subject { get; set; } = string.Empty; + public string Body { get; set; } = string.Empty; + + public static MessageInfo? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new MessageInfo() + { + MessageId = model.MessageId, + ClientId = model.ClientId, + SenderName = model.SenderName, + Body = model.Body, + Subject = model.Subject, + DateDelivery = model.DateDelivery + }; + } + + public static MessageInfo? Create(XElement element) + { + if (element == null) + { + return null; + } + return new MessageInfo() + { + MessageId = element.Attribute("MessageId")!.Value, + ClientId = Convert.ToInt32(element.Element("ClientId")!.Value), + SenderName = element.Element("SenderName")!.Value, + Body = element.Element("Body")!.Value, + Subject = element.Element("Subject")!.Value, + DateDelivery = Convert.ToDateTime(element.Element("DateDelivery")!.Value) + }; + } + + public MessageInfoViewModel GetViewModel => new() + { + MessageId = MessageId, + ClientId = ClientId, + SenderName = SenderName, + Body = Body, + Subject = Subject, + DateDelivery = DateDelivery + }; + + public XElement GetXElement => new("MessageInfo", + new XAttribute("MessageId", MessageId), + new XElement("ClientId", ClientId.ToString()), + new XElement("SenderName", SenderName), + new XElement("Subject", Subject), + new XElement("Body", Body), + new XElement("DateDelivery", DateDelivery.ToString())); + } +} diff --git a/FoodOrders/FoodOrders/FormMails.Designer.cs b/FoodOrders/FoodOrders/FormMails.Designer.cs new file mode 100644 index 0000000..8de5b4a --- /dev/null +++ b/FoodOrders/FoodOrders/FormMails.Designer.cs @@ -0,0 +1,67 @@ +namespace FoodOrders +{ + partial class FormMails + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.dataGridView = new System.Windows.Forms.DataGridView(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); + this.SuspendLayout(); + // + // dataGridView + // + this.dataGridView.BackgroundColor = System.Drawing.Color.White; + this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView.Location = new System.Drawing.Point(2, 1); + this.dataGridView.MultiSelect = false; + this.dataGridView.Name = "dataGridView"; + this.dataGridView.RowHeadersVisible = false; + this.dataGridView.RowHeadersWidth = 51; + this.dataGridView.RowTemplate.Height = 29; + this.dataGridView.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; + this.dataGridView.Size = new System.Drawing.Size(809, 292); + this.dataGridView.TabIndex = 6; + // + // FormMails + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(812, 298); + this.Controls.Add(this.dataGridView); + this.Name = "FormMails"; + this.Text = "Письма"; + this.Load += new System.EventHandler(this.FormMails_Load); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit(); + this.ResumeLayout(false); + + } + + #endregion + + private DataGridView dataGridView; + } +} \ No newline at end of file diff --git a/FoodOrders/FoodOrders/FormMails.cs b/FoodOrders/FoodOrders/FormMails.cs new file mode 100644 index 0000000..d1ed859 --- /dev/null +++ b/FoodOrders/FoodOrders/FormMails.cs @@ -0,0 +1,47 @@ +using AbstractFoodOrdersContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace FoodOrders +{ + 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["MessageId"].Visible = false; + dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + _logger.LogInformation("Загрузка писем"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки писем"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } +} diff --git a/FoodOrders/FoodOrders/FormMails.resx b/FoodOrders/FoodOrders/FormMails.resx new file mode 100644 index 0000000..f298a7b --- /dev/null +++ b/FoodOrders/FoodOrders/FormMails.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file -- 2.25.1 From 91423f07f609b5330891d79a7fcf690cf8297a09 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=80=D1=82=D0=B5=D0=BC=20=D0=A5=D0=B0=D1=80=D0=BB?= =?UTF-8?q?=D0=B0=D0=BC=D0=BE=D0=B2?= Date: Tue, 30 May 2023 22:13:03 +0400 Subject: [PATCH 2/4] =?UTF-8?q?=D0=9B=D0=B0=D0=B17-=D0=9F=D0=BE=D0=BB?= =?UTF-8?q?=D1=83=D1=87=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=B8=20=D0=BE=D1=82?= =?UTF-8?q?=D0=BF=D1=80=D0=B0=D0=B2=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=BF?= =?UTF-8?q?=D0=B8=D1=81=D0=B5=D0=BC=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82=D0=B0?= =?UTF-8?q?=D0=B5=D1=82.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractFoodOrdersBusinessLogic.csproj | 1 + .../BusinessLogics/ClientLogic.cs | 11 +- .../BusinessLogics/OrderLogic.cs | 120 +++++--- .../MailWorker/AbstractMailWorker.cs | 85 ++++++ .../MailWorker/MailKitWorker.cs | 79 +++++ .../Controllers/HomeController.cs | 12 + .../Views/Home/Mails.cshtml | 51 ++++ .../Views/Shared/_Layout.cshtml | 3 + .../BindingModels/MailConfigBindingModel.cs | 18 ++ .../BindingModels/MailSendInfoBindingModel.cs | 15 + .../20230530143643_MailInfo.Designer.cs | 285 ++++++++++++++++++ .../Migrations/20230530143643_MailInfo.cs | 38 +++ ...AbstractFoodOrdersDatabaseModelSnapshot.cs | 28 ++ .../Controllers/ClientController.cs | 23 +- .../AbstractFoodOrdersRestApi/Program.cs | 21 ++ .../appsettings.json | 9 +- FoodOrders/FoodOrders/App.config | 11 + FoodOrders/FoodOrders/FormMain.Designer.cs | 23 +- FoodOrders/FoodOrders/FormMain.cs | 10 +- FoodOrders/FoodOrders/Program.cs | 46 ++- 20 files changed, 819 insertions(+), 70 deletions(-) create mode 100644 FoodOrders/AbstractFoodOrdersBusinessLogic/MailWorker/AbstractMailWorker.cs create mode 100644 FoodOrders/AbstractFoodOrdersBusinessLogic/MailWorker/MailKitWorker.cs create mode 100644 FoodOrders/AbstractFoodOrdersClientApp/Views/Home/Mails.cshtml create mode 100644 FoodOrders/AbstractFoodOrdersContracts/BindingModels/MailConfigBindingModel.cs create mode 100644 FoodOrders/AbstractFoodOrdersContracts/BindingModels/MailSendInfoBindingModel.cs create mode 100644 FoodOrders/AbstractFoodOrdersDatabaseImplement/Migrations/20230530143643_MailInfo.Designer.cs create mode 100644 FoodOrders/AbstractFoodOrdersDatabaseImplement/Migrations/20230530143643_MailInfo.cs create mode 100644 FoodOrders/FoodOrders/App.config diff --git a/FoodOrders/AbstractFoodOrdersBusinessLogic/AbstractFoodOrdersBusinessLogic.csproj b/FoodOrders/AbstractFoodOrdersBusinessLogic/AbstractFoodOrdersBusinessLogic.csproj index 3d6c104..2eac1d6 100644 --- a/FoodOrders/AbstractFoodOrdersBusinessLogic/AbstractFoodOrdersBusinessLogic.csproj +++ b/FoodOrders/AbstractFoodOrdersBusinessLogic/AbstractFoodOrdersBusinessLogic.csproj @@ -8,6 +8,7 @@ + diff --git a/FoodOrders/AbstractFoodOrdersBusinessLogic/BusinessLogics/ClientLogic.cs b/FoodOrders/AbstractFoodOrdersBusinessLogic/BusinessLogics/ClientLogic.cs index b437a61..c2229b6 100644 --- a/FoodOrders/AbstractFoodOrdersBusinessLogic/BusinessLogics/ClientLogic.cs +++ b/FoodOrders/AbstractFoodOrdersBusinessLogic/BusinessLogics/ClientLogic.cs @@ -17,8 +17,6 @@ namespace AbstractFoodOrdersBusinessLogic.BusinessLogics { private readonly ILogger _logger; private readonly IClientStorage _clientStorage; - private Regex validateEmailRegex = new Regex("^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$"); - private Regex validatePasswordRegex = new Regex("^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).(?=.*?[#?!@$%^&*-]).{10,50}$"); public ClientLogic(ILogger logger, IClientStorage clientStorage) { @@ -111,13 +109,14 @@ namespace AbstractFoodOrdersBusinessLogic.BusinessLogics { throw new ArgumentNullException("Нет электронной почты клиента", nameof(model.Email)); } - if (!validateEmailRegex.IsMatch(model.Email)) + if (!Regex.IsMatch(model.Email, @"^[-\w.]+@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,4}$")) { - throw new InvalidOperationException("Почта введена некорректно!"); + throw new ArgumentNullException("Введенное не является адресом электронной почты", nameof(model.Email)); } - if (!validatePasswordRegex.IsMatch(model.Password)) + if (/*model.Password.Length < 10 ||*/ model.Password.Length > 50 /*|| + !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]*$")*/) { - throw new InvalidOperationException("Пароль не удовлетворяет требованиям"); + throw new ArgumentNullException("Пароль не соответсвует требованиям безопасности", nameof(model.Password)); } _logger.LogInformation("Client. ClientFIO:{ClientFIO}. Password:{Password}. Email:{Email}. Id:{Id}", model.ClientFIO, model.Password, model.Email, model.Id); var element = _clientStorage.GetElement(new ClientSearchModel diff --git a/FoodOrders/AbstractFoodOrdersBusinessLogic/BusinessLogics/OrderLogic.cs b/FoodOrders/AbstractFoodOrdersBusinessLogic/BusinessLogics/OrderLogic.cs index 46e97a6..0a4898b 100644 --- a/FoodOrders/AbstractFoodOrdersBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/FoodOrders/AbstractFoodOrdersBusinessLogic/BusinessLogics/OrderLogic.cs @@ -1,4 +1,5 @@ -using AbstractFoodOrdersContracts.BindingModels; +using AbstractFoodOrdersBusinessLogic.MailWorker; +using AbstractFoodOrdersContracts.BindingModels; using AbstractFoodOrdersContracts.BusinessLogicsContracts; using AbstractFoodOrdersContracts.SearchModels; using AbstractFoodOrdersContracts.StoragesContracts; @@ -17,70 +18,92 @@ namespace AbstractFoodOrdersBusinessLogic.BusinessLogics { private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; + private readonly AbstractMailWorker _mailWorker; static readonly object _locker = new object(); - public OrderLogic(ILogger logger, IOrderStorage orderStorage) + + public OrderLogic(ILogger logger, IOrderStorage orderStorage, AbstractMailWorker mailWorker) { _logger = logger; _orderStorage = orderStorage; + _mailWorker = mailWorker; } + public List? ReadList(OrderSearchModel? model) { - _logger.LogInformation("ReadList. ClientId:{ClientId}.Status:{Status}.ImplementerId:{ImplementerId}.DateFrom:{DateFrom}.DateTo:{DateTo}OrderId:{Id}", - model?.ClientId, model?.OrderStatus, model?.ImplementerId, model?.DateFrom, model?.DateTo, model?.Id); + _logger.LogInformation("ReadList. Id:{Id}", model?.Id); var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model); if (list == null) { _logger.LogWarning("ReadList return null list"); return null; } - _logger.LogInformation("ReadList. Count:{Count}", list.Count); + _logger.LogInformation("ReadList. Count: {Count}", list.Count); return list; } + public OrderViewModel? ReadElement(OrderSearchModel model) { if (model == null) { throw new ArgumentNullException(nameof(model)); } - _logger.LogInformation("ReadElement. ClientId:{ClientId}.Status:{Status}.ImplementerId:{ImplementerId}.DateFrom:{DateFrom}.DateTo:{DateTo}OrderId:{Id}", - model.ClientId, model.OrderStatus, model.ImplementerId, model.DateFrom, model.DateTo, model.Id); + _logger.LogInformation("ReadElement. ClientId: {ClientId}. ImplementerId: {ImplementerId}. Status: {Status}. DateFrom: {DateFrom}. DateTo: {DateTo}. Id: {Id}", + model.ClientId, model.ImplementerId, model.OrderStatus, model.DateFrom, model.DateTo, model.Id); var element = _orderStorage.GetElement(model); if (element == null) { _logger.LogWarning("ReadElement element not found"); return null; } - _logger.LogInformation("ReadElement find. Id:{Id}", element.Id); + _logger.LogInformation("ReadElement find. Id: {Id}", element.Id); return element; } + public bool CreateOrder(OrderBindingModel model) { CheckModel(model); if (model.Status != OrderStatus.Неизвестен) - return false; - model.Status = OrderStatus.Принят; - if (_orderStorage.Insert(model) == null) { - _logger.LogWarning("Insert operation failed"); + _logger.LogWarning("Order status change failed"); return false; } + model.Status = OrderStatus.Принят; + + var orderView = _orderStorage.Insert(model); + if (orderView == null) + { + _logger.LogWarning("Order creation failed"); + return false; + } + + Task.Run(() => _mailWorker.MailSendAsync(new MailSendInfoBindingModel + { + MailAddress = orderView.ClientEmail, + Subject = $"Новый заказ создан. Заказ №{orderView.Id}", + Text = $"Заказ №{orderView.Id} от {orderView.DateCreate} на сумму {orderView.Sum} принят." + })); + return true; } + public bool TakeOrderInWork(OrderBindingModel model) { lock (_locker) { - return ChangeStatus(model, OrderStatus.Выполняется); + return ChangeOrderStatus(model, OrderStatus.Выполняется); } } + public bool FinishOrder(OrderBindingModel model) { - return ChangeStatus(model, OrderStatus.Готов); + return ChangeOrderStatus(model, OrderStatus.Готов); } + public bool DeliveryOrder(OrderBindingModel model) { - return ChangeStatus(model, OrderStatus.Выдан); + return ChangeOrderStatus(model, OrderStatus.Выдан); } + private void CheckModel(OrderBindingModel model, bool withParams = true) { if (model == null) @@ -93,53 +116,50 @@ namespace AbstractFoodOrdersBusinessLogic.BusinessLogics } if (model.Count <= 0) { - throw new ArgumentException("Колличество изделий в заказе не может быть меньше 1", nameof(model.Count)); + throw new ArgumentNullException("Кол-во изделий в заказе должно быть больше 0", nameof(model.Count)); } if (model.Sum <= 0) { - throw new ArgumentException("Стоимость заказа на может быть меньше 1", nameof(model.Sum)); + throw new ArgumentNullException("Сумма заказа должна быть больше 0", nameof(model.Sum)); } - if (model.DateImplement.HasValue && model.DateImplement < model.DateCreate) - { - throw new ArithmeticException($"Дата выдачи заказа {model.DateImplement} не может быть раньше даты его создания {model.DateCreate}"); - } - _logger.LogInformation("Reinforced. ReinforcedId:{ReinforcedId}.Count:{Count}.Sum:{Sum}Id:{Id}", - model.DishId, model.Count, model.Sum, model.Id); + _logger.LogInformation("Order. Count: {Count}. Sum: {Sum} Id: {Id}", model.Count, model.Sum, model.Id); } - private bool ChangeStatus(OrderBindingModel model, OrderStatus requiredStatus) + + private bool ChangeOrderStatus(OrderBindingModel model, OrderStatus newStatus) { CheckModel(model, false); - var element = _orderStorage.GetElement(new OrderSearchModel() + var orderView = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id }); + + if (orderView == null || newStatus - orderView.Status != 1) { - Id = model.Id - }); - if (element == null) - { - throw new InvalidOperationException(nameof(element)); + _logger.LogWarning("Order status change failed"); + return false; } - model.DateCreate = element.DateCreate; - model.DishId = element.DishId; - model.DateImplement = element.DateImplement; - model.ClientId = element.ClientId; + + model.Status = newStatus; if (!model.ImplementerId.HasValue) - model.ImplementerId = element.ImplementerId; - model.Status = element.Status; - model.Count = element.Count; - model.Sum = element.Sum; - if (requiredStatus - model.Status == 1) + model.ImplementerId = orderView.ImplementerId; + model.DateImplement = orderView.DateImplement; + + if (newStatus == OrderStatus.Готов) { - model.Status = requiredStatus; - if (model.Status == OrderStatus.Готов) - model.DateImplement = DateTime.Now; - if (_orderStorage.Update(model) == null) - { - _logger.LogWarning("Update operation failed"); - return false; - } - return true; + model.DateImplement = DateTime.Now; } - _logger.LogWarning("Changing status operation faled: Current-{Status}:required-{requiredStatus}.", model.Status, requiredStatus); - throw new InvalidOperationException($"Невозможно приствоить статус {requiredStatus} заказу с текущим статусом {model.Status}"); + + if (_orderStorage.Update(model) == null) + { + _logger.LogWarning("Order status change failed"); + return false; + } + + Task.Run(() => _mailWorker.MailSendAsync(new MailSendInfoBindingModel + { + MailAddress = orderView.ClientEmail, + Subject = $"Заказ №{orderView.Id}", + Text = $"Заказ №{orderView.Id} изменен статус на {newStatus}." + })); + + return true; } } } diff --git a/FoodOrders/AbstractFoodOrdersBusinessLogic/MailWorker/AbstractMailWorker.cs b/FoodOrders/AbstractFoodOrdersBusinessLogic/MailWorker/AbstractMailWorker.cs new file mode 100644 index 0000000..cc5db36 --- /dev/null +++ b/FoodOrders/AbstractFoodOrdersBusinessLogic/MailWorker/AbstractMailWorker.cs @@ -0,0 +1,85 @@ +using AbstractFoodOrdersContracts.BindingModels; +using AbstractFoodOrdersContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AbstractFoodOrdersBusinessLogic.MailWorker +{ + public abstract class AbstractMailWorker + { + protected string _mailLogin = string.Empty; + protected string _mailPassword = string.Empty; + protected string _smtpClientHost = string.Empty; + protected int _smtpClientPort; + protected string _popHost = string.Empty; + protected int _popPort; + private readonly IMessageInfoLogic _messageInfoLogic; + private readonly ILogger _logger; + public AbstractMailWorker(ILogger logger, + IMessageInfoLogic messageInfoLogic) + { + _logger = logger; + _messageInfoLogic = messageInfoLogic; + } + public void MailConfig(MailConfigBindingModel config) + { + _mailLogin = config.MailLogin; + _mailPassword = config.MailPassword; + _smtpClientHost = config.SmtpClientHost; + _smtpClientPort = config.SmtpClientPort; + _popHost = config.PopHost; + _popPort = config.PopPort; + _logger.LogDebug("Config: {login}, {password}, {clientHost},{ clientPOrt}, { popHost}, { popPort}", _mailLogin, _mailPassword, _smtpClientHost, + _smtpClientPort, _popHost, _popPort); + } + public async void MailSendAsync(MailSendInfoBindingModel info) + { + if (string.IsNullOrEmpty(_mailLogin) || + string.IsNullOrEmpty(_mailPassword)) + { + return; + } + if (string.IsNullOrEmpty(_smtpClientHost) || _smtpClientPort == 0) + { + return; + } + if (string.IsNullOrEmpty(info.MailAddress) || + string.IsNullOrEmpty(info.Subject) || string.IsNullOrEmpty(info.Text)) + { + return; + } + _logger.LogDebug("Send Mail: {To}, {Subject}", info.MailAddress, + info.Subject); + await SendMailAsync(info); + } + public async void MailCheck() + { + if (string.IsNullOrEmpty(_mailLogin) || + string.IsNullOrEmpty(_mailPassword)) + { + return; + } + if (string.IsNullOrEmpty(_popHost) || _popPort == 0) + { + return; + } + if (_messageInfoLogic == null) + { + return; + } + var list = await ReceiveMailAsync(); + _logger.LogDebug("Check Mail: {Count} new mails", list.Count); + foreach (var mail in list) + { + _messageInfoLogic.Create(mail); + } + } + protected abstract Task SendMailAsync(MailSendInfoBindingModel info); + protected abstract Task>ReceiveMailAsync(); + + } +} diff --git a/FoodOrders/AbstractFoodOrdersBusinessLogic/MailWorker/MailKitWorker.cs b/FoodOrders/AbstractFoodOrdersBusinessLogic/MailWorker/MailKitWorker.cs new file mode 100644 index 0000000..a5704ba --- /dev/null +++ b/FoodOrders/AbstractFoodOrdersBusinessLogic/MailWorker/MailKitWorker.cs @@ -0,0 +1,79 @@ +using AbstractFoodOrdersContracts.BindingModels; +using AbstractFoodOrdersContracts.BusinessLogicsContracts; +using MailKit.Net.Pop3; +using MailKit.Security; +using Microsoft.Extensions.Logging; +using System.Net; +using System.Net.Mail; +using System.Text; + +namespace AbstractFoodOrdersBusinessLogic.MailWorker +{ + public class MailKitWorker:AbstractMailWorker + { + public MailKitWorker(ILogger logger, IMessageInfoLogic +messageInfoLogic) : base(logger, messageInfoLogic) { } + protected override async Task SendMailAsync(MailSendInfoBindingModel + info) + { + using var objMailMessage = new MailMessage(); + using var objSmtpClient = new SmtpClient(_smtpClientHost, + _smtpClientPort); + try + { + objMailMessage.From = new MailAddress(_mailLogin); + objMailMessage.To.Add(new MailAddress(info.MailAddress)); + objMailMessage.Subject = info.Subject; + objMailMessage.Body = info.Text; + objMailMessage.SubjectEncoding = Encoding.UTF8; + objMailMessage.BodyEncoding = Encoding.UTF8; + objSmtpClient.UseDefaultCredentials = false; + objSmtpClient.EnableSsl = true; + objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; + objSmtpClient.Credentials = new NetworkCredential(_mailLogin, + _mailPassword); + await Task.Run(() => objSmtpClient.Send(objMailMessage)); + } + catch (Exception) + { + throw; + } + } + protected override async Task> + ReceiveMailAsync() + { + var list = new List(); + using var client = new Pop3Client(); + await Task.Run(() => + { + try + { + client.Connect(_popHost, _popPort, SecureSocketOptions.SslOnConnect); + client.Authenticate(_mailLogin, _mailPassword); + for (int i = 0; i < client.Count; i++) + { + var message = client.GetMessage(i); + foreach (var mail in message.From.Mailboxes) + { + list.Add(new MessageInfoBindingModel + { + DateDelivery = message.Date.DateTime, + MessageId = message.MessageId, + SenderName = mail.Address, + Subject = message.Subject, + Body = message.TextBody + }); + } + } + } + catch (AuthenticationException) + { } + finally + { + client.Disconnect(true); + } + }); + return list; + } + } +} diff --git a/FoodOrders/AbstractFoodOrdersClientApp/Controllers/HomeController.cs b/FoodOrders/AbstractFoodOrdersClientApp/Controllers/HomeController.cs index e84f406..50cbd78 100644 --- a/FoodOrders/AbstractFoodOrdersClientApp/Controllers/HomeController.cs +++ b/FoodOrders/AbstractFoodOrdersClientApp/Controllers/HomeController.cs @@ -2,6 +2,7 @@ using AbstractFoodOrdersContracts.BindingModels; using AbstractFoodOrdersContracts.ViewModels; using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging; using System.Diagnostics; namespace AbstractFoodOrdersClientApp.Controllers @@ -142,5 +143,16 @@ namespace AbstractFoodOrdersClientApp.Controllers ); 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}")); +} + } } \ No newline at end of file diff --git a/FoodOrders/AbstractFoodOrdersClientApp/Views/Home/Mails.cshtml b/FoodOrders/AbstractFoodOrdersClientApp/Views/Home/Mails.cshtml new file mode 100644 index 0000000..b2f8692 --- /dev/null +++ b/FoodOrders/AbstractFoodOrdersClientApp/Views/Home/Mails.cshtml @@ -0,0 +1,51 @@ +@using AbstractFoodOrdersContracts.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/FoodOrders/AbstractFoodOrdersClientApp/Views/Shared/_Layout.cshtml b/FoodOrders/AbstractFoodOrdersClientApp/Views/Shared/_Layout.cshtml index 60ba003..e2d34bf 100644 --- a/FoodOrders/AbstractFoodOrdersClientApp/Views/Shared/_Layout.cshtml +++ b/FoodOrders/AbstractFoodOrdersClientApp/Views/Shared/_Layout.cshtml @@ -26,6 +26,9 @@ + diff --git a/FoodOrders/AbstractFoodOrdersContracts/BindingModels/MailConfigBindingModel.cs b/FoodOrders/AbstractFoodOrdersContracts/BindingModels/MailConfigBindingModel.cs new file mode 100644 index 0000000..e8b7472 --- /dev/null +++ b/FoodOrders/AbstractFoodOrdersContracts/BindingModels/MailConfigBindingModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AbstractFoodOrdersContracts.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/FoodOrders/AbstractFoodOrdersContracts/BindingModels/MailSendInfoBindingModel.cs b/FoodOrders/AbstractFoodOrdersContracts/BindingModels/MailSendInfoBindingModel.cs new file mode 100644 index 0000000..026597e --- /dev/null +++ b/FoodOrders/AbstractFoodOrdersContracts/BindingModels/MailSendInfoBindingModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AbstractFoodOrdersContracts.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/FoodOrders/AbstractFoodOrdersDatabaseImplement/Migrations/20230530143643_MailInfo.Designer.cs b/FoodOrders/AbstractFoodOrdersDatabaseImplement/Migrations/20230530143643_MailInfo.Designer.cs new file mode 100644 index 0000000..382b22e --- /dev/null +++ b/FoodOrders/AbstractFoodOrdersDatabaseImplement/Migrations/20230530143643_MailInfo.Designer.cs @@ -0,0 +1,285 @@ +// +using System; +using AbstractFoodOrdersDatabaseImplement; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace AbstractFoodOrdersDatabaseImplement.Migrations +{ + [DbContext(typeof(AbstractFoodOrdersDatabase))] + [Migration("20230530143643_MailInfo")] + partial class MailInfo + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.5") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("AbstractFoodOrdersDatabaseImplement.Models.Client", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientFIO") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Email") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Password") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Clients"); + }); + + modelBuilder.Entity("AbstractFoodOrdersDatabaseImplement.Models.Component", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ComponentName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Cost") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.ToTable("Components"); + }); + + modelBuilder.Entity("AbstractFoodOrdersDatabaseImplement.Models.Dish", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("DishName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Price") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.ToTable("Dishes"); + }); + + modelBuilder.Entity("AbstractFoodOrdersDatabaseImplement.Models.DishComponent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ComponentId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("DishId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ComponentId"); + + b.HasIndex("DishId"); + + b.ToTable("DishComponents"); + }); + + modelBuilder.Entity("AbstractFoodOrdersDatabaseImplement.Models.Implementer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ImplementerFIO") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Password") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Qualification") + .HasColumnType("int"); + + b.Property("WorkExperience") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.ToTable("Implementers"); + }); + + modelBuilder.Entity("AbstractFoodOrdersDatabaseImplement.Models.MessageInfo", b => + { + b.Property("MessageId") + .HasColumnType("nvarchar(450)"); + + b.Property("Body") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("int"); + + b.Property("DateDelivery") + .HasColumnType("datetime2"); + + b.Property("SenderName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Subject") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("MessageId"); + + b.ToTable("MessageInfos"); + }); + + modelBuilder.Entity("AbstractFoodOrdersDatabaseImplement.Models.Order", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateImplement") + .HasColumnType("datetime2"); + + b.Property("DishId") + .HasColumnType("int"); + + b.Property("ImplementerId") + .HasColumnType("int"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("Sum") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.HasIndex("DishId"); + + b.HasIndex("ImplementerId"); + + b.ToTable("Orders"); + }); + + modelBuilder.Entity("AbstractFoodOrdersDatabaseImplement.Models.DishComponent", b => + { + b.HasOne("AbstractFoodOrdersDatabaseImplement.Models.Component", "Component") + .WithMany("DishComponents") + .HasForeignKey("ComponentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("AbstractFoodOrdersDatabaseImplement.Models.Dish", "Dish") + .WithMany("Components") + .HasForeignKey("DishId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Component"); + + b.Navigation("Dish"); + }); + + modelBuilder.Entity("AbstractFoodOrdersDatabaseImplement.Models.Order", b => + { + b.HasOne("AbstractFoodOrdersDatabaseImplement.Models.Client", "Client") + .WithMany("ClientOrders") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("AbstractFoodOrdersDatabaseImplement.Models.Dish", "Dish") + .WithMany("Orders") + .HasForeignKey("DishId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("AbstractFoodOrdersDatabaseImplement.Models.Implementer", "Implementer") + .WithMany("Orders") + .HasForeignKey("ImplementerId"); + + b.Navigation("Client"); + + b.Navigation("Dish"); + + b.Navigation("Implementer"); + }); + + modelBuilder.Entity("AbstractFoodOrdersDatabaseImplement.Models.Client", b => + { + b.Navigation("ClientOrders"); + }); + + modelBuilder.Entity("AbstractFoodOrdersDatabaseImplement.Models.Component", b => + { + b.Navigation("DishComponents"); + }); + + modelBuilder.Entity("AbstractFoodOrdersDatabaseImplement.Models.Dish", b => + { + b.Navigation("Components"); + + b.Navigation("Orders"); + }); + + modelBuilder.Entity("AbstractFoodOrdersDatabaseImplement.Models.Implementer", b => + { + b.Navigation("Orders"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/FoodOrders/AbstractFoodOrdersDatabaseImplement/Migrations/20230530143643_MailInfo.cs b/FoodOrders/AbstractFoodOrdersDatabaseImplement/Migrations/20230530143643_MailInfo.cs new file mode 100644 index 0000000..99c8ccc --- /dev/null +++ b/FoodOrders/AbstractFoodOrdersDatabaseImplement/Migrations/20230530143643_MailInfo.cs @@ -0,0 +1,38 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace AbstractFoodOrdersDatabaseImplement.Migrations +{ + /// + public partial class MailInfo : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "MessageInfos", + columns: table => new + { + MessageId = table.Column(type: "nvarchar(450)", nullable: false), + ClientId = table.Column(type: "int", nullable: true), + SenderName = table.Column(type: "nvarchar(max)", nullable: false), + DateDelivery = table.Column(type: "datetime2", nullable: false), + Subject = table.Column(type: "nvarchar(max)", nullable: false), + Body = table.Column(type: "nvarchar(max)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_MessageInfos", x => x.MessageId); + }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "MessageInfos"); + } + } +} diff --git a/FoodOrders/AbstractFoodOrdersDatabaseImplement/Migrations/AbstractFoodOrdersDatabaseModelSnapshot.cs b/FoodOrders/AbstractFoodOrdersDatabaseImplement/Migrations/AbstractFoodOrdersDatabaseModelSnapshot.cs index ae0e3c2..3945381 100644 --- a/FoodOrders/AbstractFoodOrdersDatabaseImplement/Migrations/AbstractFoodOrdersDatabaseModelSnapshot.cs +++ b/FoodOrders/AbstractFoodOrdersDatabaseImplement/Migrations/AbstractFoodOrdersDatabaseModelSnapshot.cs @@ -140,6 +140,34 @@ namespace AbstractFoodOrdersDatabaseImplement.Migrations b.ToTable("Implementers"); }); + modelBuilder.Entity("AbstractFoodOrdersDatabaseImplement.Models.MessageInfo", b => + { + b.Property("MessageId") + .HasColumnType("nvarchar(450)"); + + b.Property("Body") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("int"); + + b.Property("DateDelivery") + .HasColumnType("datetime2"); + + b.Property("SenderName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Subject") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("MessageId"); + + b.ToTable("MessageInfos"); + }); + modelBuilder.Entity("AbstractFoodOrdersDatabaseImplement.Models.Order", b => { b.Property("Id") diff --git a/FoodOrders/AbstractFoodOrdersRestApi/Controllers/ClientController.cs b/FoodOrders/AbstractFoodOrdersRestApi/Controllers/ClientController.cs index d02a814..59b648f 100644 --- a/FoodOrders/AbstractFoodOrdersRestApi/Controllers/ClientController.cs +++ b/FoodOrders/AbstractFoodOrdersRestApi/Controllers/ClientController.cs @@ -12,11 +12,13 @@ namespace AbstractFoodOrdersRestApi.Controllers { private readonly ILogger _logger; private readonly IClientLogic _logic; - public ClientController(IClientLogic logic, ILogger + private readonly IMessageInfoLogic _mailLogic; + public ClientController(IClientLogic logic, IMessageInfoLogic mailLogic, ILogger logger) { _logger = logger; _logic = logic; + _mailLogic = mailLogic; } [HttpGet] public ClientViewModel? Login(string login, string password) @@ -61,5 +63,22 @@ namespace AbstractFoodOrdersRestApi.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/FoodOrders/AbstractFoodOrdersRestApi/Program.cs b/FoodOrders/AbstractFoodOrdersRestApi/Program.cs index a7e3f6b..eee883a 100644 --- a/FoodOrders/AbstractFoodOrdersRestApi/Program.cs +++ b/FoodOrders/AbstractFoodOrdersRestApi/Program.cs @@ -1,4 +1,6 @@ using AbstractFoodOrdersBusinessLogic.BusinessLogics; +using AbstractFoodOrdersBusinessLogic.MailWorker; +using AbstractFoodOrdersContracts.BindingModels; using AbstractFoodOrdersContracts.BusinessLogicsContracts; using AbstractFoodOrdersContracts.StoragesContracts; using AbstractFoodOrdersDatabaseImplement.Implements; @@ -13,9 +15,16 @@ builder.Logging.AddLog4Net("log4net.config"); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddTransient(); + builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddTransient(); + +builder.Services.AddTransient(); builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle @@ -27,6 +36,18 @@ builder.Services.AddSwaggerGen(c => var app = builder.Build(); +var mailSender = app.Services.GetService(); +mailSender?.MailConfig(new MailConfigBindingModel +{ + MailLogin = builder.Configuration?.GetSection("MailLogin")?.Value?.ToString() ?? string.Empty, + MailPassword = builder.Configuration?.GetSection("MailPassword")?.Value?.ToString() ?? string.Empty, + SmtpClientHost = builder.Configuration?.GetSection("SmtpClientHost")?.Value?.ToString() ?? string.Empty, + SmtpClientPort = Convert.ToInt32(builder.Configuration?.GetSection("SmtpClientPort")?.Value?.ToString()), + PopHost = builder.Configuration?.GetSection("PopHost")?.Value?.ToString() ?? string.Empty, + PopPort = Convert.ToInt32(builder.Configuration?.GetSection("PopPort")?.Value?.ToString()) +}); + + // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { diff --git a/FoodOrders/AbstractFoodOrdersRestApi/appsettings.json b/FoodOrders/AbstractFoodOrdersRestApi/appsettings.json index 10f68b8..8f1a9a0 100644 --- a/FoodOrders/AbstractFoodOrdersRestApi/appsettings.json +++ b/FoodOrders/AbstractFoodOrdersRestApi/appsettings.json @@ -5,5 +5,12 @@ "Microsoft.AspNetCore": "Warning" } }, - "AllowedHosts": "*" + "AllowedHosts": "*", + + "SmtpClientHost": "smtp.gmail.com", + "SmtpClientPort": "587", + "PopHost": "pop.gmail.com", + "PopPort": "995", + "MailLogin": "labwork07mail@gmail.com", + "MailPassword": "ugqf vpli kqcu fjui" } diff --git a/FoodOrders/FoodOrders/App.config b/FoodOrders/FoodOrders/App.config new file mode 100644 index 0000000..a0920ca --- /dev/null +++ b/FoodOrders/FoodOrders/App.config @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/FoodOrders/FoodOrders/FormMain.Designer.cs b/FoodOrders/FoodOrders/FormMain.Designer.cs index c7e3372..8a2c169 100644 --- a/FoodOrders/FoodOrders/FormMain.Designer.cs +++ b/FoodOrders/FoodOrders/FormMain.Designer.cs @@ -33,6 +33,7 @@ КомпонентыToolStripMenuItem = new ToolStripMenuItem(); БлюдаToolStripMenuItem = new ToolStripMenuItem(); ClientToolStripMenuItem = new ToolStripMenuItem(); + исполнителиToolStripMenuItem = new ToolStripMenuItem(); отчётыToolStripMenuItem = new ToolStripMenuItem(); ComponentToolStripMenuItem = new ToolStripMenuItem(); ComponentProductsToolStripMenuItem = new ToolStripMenuItem(); @@ -42,7 +43,7 @@ ButtonCreateOrder = new Button(); ButtonIssuedOrder = new Button(); ButtonRef = new Button(); - исполнителиToolStripMenuItem = new ToolStripMenuItem(); + письмаToolStripMenuItem = new ToolStripMenuItem(); menuStrip.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); SuspendLayout(); @@ -59,7 +60,7 @@ // // справочникиToolStripMenuItem // - справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { КомпонентыToolStripMenuItem, БлюдаToolStripMenuItem, ClientToolStripMenuItem, исполнителиToolStripMenuItem }); + справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { КомпонентыToolStripMenuItem, БлюдаToolStripMenuItem, ClientToolStripMenuItem, исполнителиToolStripMenuItem, письмаToolStripMenuItem }); справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; справочникиToolStripMenuItem.Size = new Size(117, 24); справочникиToolStripMenuItem.Text = "Справочники"; @@ -85,6 +86,13 @@ ClientToolStripMenuItem.Text = "Клиенты"; ClientToolStripMenuItem.Click += ClientToolStripMenuItem_Click; // + // исполнителиToolStripMenuItem + // + исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; + исполнителиToolStripMenuItem.Size = new Size(224, 26); + исполнителиToolStripMenuItem.Text = "Исполнители"; + исполнителиToolStripMenuItem.Click += ИсполнителиToolStripMenuItem_Click; + // // отчётыToolStripMenuItem // отчётыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { ComponentToolStripMenuItem, ComponentProductsToolStripMenuItem, OrdersToolStripMenuItem }); @@ -161,12 +169,12 @@ ButtonRef.UseVisualStyleBackColor = true; ButtonRef.Click += ButtonRef_Click; // - // исполнителиToolStripMenuItem + // письмаToolStripMenuItem // - исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; - исполнителиToolStripMenuItem.Size = new Size(224, 26); - исполнителиToolStripMenuItem.Text = "Исполнители"; - исполнителиToolStripMenuItem.Click += ИсполнителиToolStripMenuItem_Click; + письмаToolStripMenuItem.Name = "письмаToolStripMenuItem"; + письмаToolStripMenuItem.Size = new Size(224, 26); + письмаToolStripMenuItem.Text = "Письма"; + письмаToolStripMenuItem.Click += письмаToolStripMenuItem_Click; // // FormMain // @@ -206,5 +214,6 @@ private ToolStripMenuItem ClientToolStripMenuItem; private ToolStripMenuItem запускРаботыToolStripMenuItem; private ToolStripMenuItem исполнителиToolStripMenuItem; + private ToolStripMenuItem письмаToolStripMenuItem; } } \ No newline at end of file diff --git a/FoodOrders/FoodOrders/FormMain.cs b/FoodOrders/FoodOrders/FormMain.cs index 1fc604c..a224318 100644 --- a/FoodOrders/FoodOrders/FormMain.cs +++ b/FoodOrders/FoodOrders/FormMain.cs @@ -43,6 +43,7 @@ namespace FoodOrders dataGridView.Columns["ClientId"].Visible = false; dataGridView.Columns["DishId"].Visible = false; dataGridView.Columns["ImplementerId"].Visible = false; + dataGridView.Columns["ClientEmail"].Visible = false; } _logger.LogInformation("Загрузка заказов"); } @@ -213,6 +214,13 @@ namespace FoodOrders MessageBoxButtons.OK, MessageBoxIcon.Information); } - + private void письмаToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormMails)); + if (service is FormMails form) + { + form.ShowDialog(); + } + } } } diff --git a/FoodOrders/FoodOrders/Program.cs b/FoodOrders/FoodOrders/Program.cs index 7bee7ba..eafe1f5 100644 --- a/FoodOrders/FoodOrders/Program.cs +++ b/FoodOrders/FoodOrders/Program.cs @@ -8,6 +8,8 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; using System.Drawing; +using AbstractFoodOrdersBusinessLogic.MailWorker; +using AbstractFoodOrdersContracts.BindingModels; namespace FoodOrders { @@ -27,7 +29,36 @@ namespace FoodOrders var services = new ServiceCollection(); ConfigureServices(services); _serviceProvider = services.BuildServiceProvider(); - Application.Run(_serviceProvider.GetRequiredService()); + try + { + var mailSender = + _serviceProvider.GetService(); + mailSender?.MailConfig(new MailConfigBindingModel + { + MailLogin = + System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty, + MailPassword = + System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty, + SmtpClientHost = + System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty, + SmtpClientPort = + Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]), + PopHost = + System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty, + PopPort = + Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"]) + }); + // + var timer = new System.Threading.Timer(new + TimerCallback(MailCheck!), null, 0, 10000); + } + catch (Exception ex) + { + var logger = _serviceProvider.GetService(); + logger?.LogError(ex, " "); + } + + Application.Run(_serviceProvider.GetRequiredService()); } private static void ConfigureServices(ServiceCollection services) { @@ -41,16 +72,23 @@ namespace FoodOrders 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(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -63,6 +101,8 @@ namespace FoodOrders services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); } - } + private static void MailCheck(object obj) => ServiceProvider?.GetService()?.MailCheck(); + } } \ No newline at end of file -- 2.25.1 From 3315dd4f0d88fe474d4c0f5b00c69286f9478c38 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=80=D1=82=D0=B5=D0=BC=20=D0=A5=D0=B0=D1=80=D0=BB?= =?UTF-8?q?=D0=B0=D0=BC=D0=BE=D0=B2?= Date: Tue, 30 May 2023 22:24:41 +0400 Subject: [PATCH 3/4] =?UTF-8?q?=D0=9B=D0=B0=D0=B17-=D1=84=D0=B8=D0=BA?= =?UTF-8?q?=D1=81=20=D0=B2=D0=B0=D0=BB=D0=B8=D0=B4=D0=B0=D1=86=D0=B8=D0=B8?= =?UTF-8?q?=20=D0=BF=D0=B0=D1=80=D0=BE=D0=BB=D1=8F.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../BusinessLogics/ClientLogic.cs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/FoodOrders/AbstractFoodOrdersBusinessLogic/BusinessLogics/ClientLogic.cs b/FoodOrders/AbstractFoodOrdersBusinessLogic/BusinessLogics/ClientLogic.cs index c2229b6..1f453d4 100644 --- a/FoodOrders/AbstractFoodOrdersBusinessLogic/BusinessLogics/ClientLogic.cs +++ b/FoodOrders/AbstractFoodOrdersBusinessLogic/BusinessLogics/ClientLogic.cs @@ -113,10 +113,9 @@ namespace AbstractFoodOrdersBusinessLogic.BusinessLogics { throw new ArgumentNullException("Введенное не является адресом электронной почты", nameof(model.Email)); } - if (/*model.Password.Length < 10 ||*/ model.Password.Length > 50 /*|| - !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]*$")*/) + if (!Regex.IsMatch(model.Password, @"^(?=.*\d)(?=.*\W)(?=.*[^\d\s]).+$")) { - throw new ArgumentNullException("Пароль не соответсвует требованиям безопасности", nameof(model.Password)); + throw new ArgumentException("Некорректно введен пароль клиента", nameof(model.Password)); } _logger.LogInformation("Client. ClientFIO:{ClientFIO}. Password:{Password}. Email:{Email}. Id:{Id}", model.ClientFIO, model.Password, model.Email, model.Id); var element = _clientStorage.GetElement(new ClientSearchModel -- 2.25.1 From 6a7474bb87650f85d84e6481d09015eb3508217e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=80=D1=82=D0=B5=D0=BC=20=D0=A5=D0=B0=D1=80=D0=BB?= =?UTF-8?q?=D0=B0=D0=BC=D0=BE=D0=B2?= Date: Thu, 1 Jun 2023 16:24:40 +0400 Subject: [PATCH 4/4] =?UTF-8?q?=D0=9B=D0=B0=D0=B17=20-=20=D1=84=D0=B8?= =?UTF-8?q?=D0=BA=D1=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Implements/MessageInfoStorage.cs | 77 +++++++++++++++++++ .../Models/MessageInfo.cs | 48 ++++++++++++ 2 files changed, 125 insertions(+) create mode 100644 FoodOrders/AbstractFoodOrdersListImplement/Implements/MessageInfoStorage.cs create mode 100644 FoodOrders/AbstractFoodOrdersListImplement/Models/MessageInfo.cs diff --git a/FoodOrders/AbstractFoodOrdersListImplement/Implements/MessageInfoStorage.cs b/FoodOrders/AbstractFoodOrdersListImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..eb84506 --- /dev/null +++ b/FoodOrders/AbstractFoodOrdersListImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,77 @@ +using AbstractFoodOrdersContracts.BindingModels; +using AbstractFoodOrdersContracts.SearchModels; +using AbstractFoodOrdersContracts.StoragesContracts; +using AbstractFoodOrdersContracts.ViewModels; +using AbstractFoodOrdersListImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AbstractFoodOrdersListImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + private readonly DataListSingleton _source; + + public MessageInfoStorage(DataListSingleton source) + { + _source = source; + } + + public List GetFullList() + { + var result = new List(); + foreach (var messageInfo in _source.MessageInfos) + { + result.Add(messageInfo.GetViewModel); + } + return result; + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + var result = new List(); + if (string.IsNullOrEmpty(model.MessageId) && !model.ClientId.HasValue) + { + return result; + } + foreach (var messageInfo in _source.MessageInfos) + { + if (messageInfo.ClientId == model.ClientId) + { + result.Add(messageInfo.GetViewModel); + } + } + return result; + } + + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (string.IsNullOrEmpty(model.MessageId) && !model.ClientId.HasValue) + { + return null; + } + foreach (var messageInfo in _source.MessageInfos) + { + if (!string.IsNullOrEmpty(model.MessageId) && model.ClientId.HasValue && messageInfo.MessageId == model.MessageId && messageInfo.ClientId == model.ClientId) + { + return messageInfo.GetViewModel; + } + } + return null; + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessageInfo = MessageInfo.Create(model); + if (newMessageInfo == null) + { + return null; + } + _source.MessageInfos.Add(newMessageInfo); + return newMessageInfo.GetViewModel; + } + } +} diff --git a/FoodOrders/AbstractFoodOrdersListImplement/Models/MessageInfo.cs b/FoodOrders/AbstractFoodOrdersListImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..40b922b --- /dev/null +++ b/FoodOrders/AbstractFoodOrdersListImplement/Models/MessageInfo.cs @@ -0,0 +1,48 @@ +using AbstractFoodOrdersContracts.BindingModels; +using AbstractFoodOrdersContracts.ViewModels; +using AbstractFoodOrdersDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AbstractFoodOrdersListImplement.Models +{ + public class MessageInfo : IMessageInfoModel + { + public string MessageId { get; set; } = string.Empty; + public int? ClientId { get; set; } + public string SenderName { get; set; } = string.Empty; + public DateTime DateDelivery { get; set; } + public string Subject { get; set; } = string.Empty; + public string Body { get; set; } = string.Empty; + + public static MessageInfo? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new MessageInfo() + { + MessageId = model.MessageId, + ClientId = model.ClientId, + SenderName = model.SenderName, + Body = model.Body, + Subject = model.Subject, + DateDelivery = model.DateDelivery + }; + } + + public MessageInfoViewModel GetViewModel => new() + { + MessageId = MessageId, + ClientId = ClientId, + SenderName = SenderName, + Body = Body, + Subject = Subject, + DateDelivery = DateDelivery + }; + } +} -- 2.25.1