diff --git a/ConfectionaryBusinessLogic/ClientLogic.cs b/ConfectionaryBusinessLogic/ClientLogic.cs index 1a9b6c8..576fb6d 100644 --- a/ConfectionaryBusinessLogic/ClientLogic.cs +++ b/ConfectionaryBusinessLogic/ClientLogic.cs @@ -1,4 +1,5 @@ -using ConfectioneryBusinessLogic.BusinessLogics; +using System.Text.RegularExpressions; +using ConfectioneryBusinessLogic.BusinessLogics; using ConfectioneryContracts.BindingModels; using ConfectioneryContracts.BusinessLogicsContracts; using ConfectioneryContracts.SearchModels; @@ -102,6 +103,16 @@ namespace ConfectioneryBusinessLogic { throw new ArgumentNullException("Нет логина клиента", nameof(model.Email)); } + if (!Regex.IsMatch(model.Email, @"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$")) + { + throw new ArgumentException("Некорретно введенный email", nameof(model.Email)); + } + // Запасной (вероятно более правильный): ^((\w+\d+\W+)|(\w+\W+\d+)|(\d+\w+\W+)|(\d+\W+\w+)|(\W+\w+\d+)|(\W+\d+\w+))+$ + // Просматриваем наперед последовательность (де-факто оператор &&) цифр, небуквенных символов и букв (не цифр и не пробельных символов) + if (!Regex.IsMatch(model.Password, @"^(?=.*\d)(?=.*\W)(?=.*[^\d\s]).+$")) + { + throw new ArgumentException("Некорректно введенный пароль. Пароль должен содержать хотя бы одну букву, цифру и не буквенный символ", nameof(model.Password)); + } _logger.LogInformation("Client. Id: {Id}, FIO: {fio}, email: {email}", model.Id, model.ClientFIO, model.Email ); var element = _clientStorage.GetElement(new ClientSearchModel { diff --git a/ConfectionaryBusinessLogic/ConfectioneryBusinessLogic.csproj b/ConfectionaryBusinessLogic/ConfectioneryBusinessLogic.csproj index 8454587..4b0949c 100644 --- a/ConfectionaryBusinessLogic/ConfectioneryBusinessLogic.csproj +++ b/ConfectionaryBusinessLogic/ConfectioneryBusinessLogic.csproj @@ -8,6 +8,7 @@ + diff --git a/ConfectionaryBusinessLogic/MailWorker/AbstractMailWorker.cs b/ConfectionaryBusinessLogic/MailWorker/AbstractMailWorker.cs new file mode 100644 index 0000000..55e56d2 --- /dev/null +++ b/ConfectionaryBusinessLogic/MailWorker/AbstractMailWorker.cs @@ -0,0 +1,100 @@ +using ConfectioneryContracts.BindingModels; +using ConfectioneryContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ConfectioneryBusinessLogic.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/ConfectionaryBusinessLogic/MailWorker/MailKitWorker.cs b/ConfectionaryBusinessLogic/MailWorker/MailKitWorker.cs new file mode 100644 index 0000000..52fbcf2 --- /dev/null +++ b/ConfectionaryBusinessLogic/MailWorker/MailKitWorker.cs @@ -0,0 +1,82 @@ +using ConfectioneryContracts.BindingModels; +using ConfectioneryContracts.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 ConfectioneryBusinessLogic.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/ConfectionaryBusinessLogic/MessageInfoLogic.cs b/ConfectionaryBusinessLogic/MessageInfoLogic.cs new file mode 100644 index 0000000..ab6fa16 --- /dev/null +++ b/ConfectionaryBusinessLogic/MessageInfoLogic.cs @@ -0,0 +1,70 @@ +using ConfectioneryContracts.BindingModels; +using ConfectioneryContracts.BusinessLogicsContracts; +using ConfectioneryContracts.SearchModels; +using ConfectioneryContracts.StoragesContract; +using ConfectioneryContracts.ViewModels; +using DocumentFormat.OpenXml.EMMA; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ConfectioneryBusinessLogic +{ + public class MessageInfoLogic : IMessageInfoLogic + { + private readonly ILogger _logger; + private readonly IMessageInfoStorage _messageInfoStorage; + public MessageInfoLogic(ILogger logger, IMessageInfoStorage messageInfoStorage) + { + _logger = logger; + _messageInfoStorage = messageInfoStorage; + } + + public bool Create(MessageInfoBindingModel model) + { + if (_messageInfoStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } + + public MessageInfoViewModel? ReadElement(MessageInfoSearchModel model) + { + var res = _messageInfoStorage.GetElement(model); + if (res == null) + { + _logger.LogWarning("Read element operation failed"); + return null; + } + return res; + } + + public bool Update(MessageInfoBindingModel model) + { + if (_messageInfoStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + return true; + } + + public List? ReadList(MessageInfoSearchModel? model) + { + _logger.LogInformation("ReadList. MessageId:{MessageId}.ClientId:{ClientId} ", model?.MessageId, model?.ClientId); + var list = (model == null) ? _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; + } + } +} diff --git a/ConfectionaryBusinessLogic/OrderLogic.cs b/ConfectionaryBusinessLogic/OrderLogic.cs index 2548654..2a8f463 100644 --- a/ConfectionaryBusinessLogic/OrderLogic.cs +++ b/ConfectionaryBusinessLogic/OrderLogic.cs @@ -1,4 +1,5 @@ -using ConfectioneryContracts.BindingModels; +using ConfectioneryBusinessLogic.MailWorker; +using ConfectioneryContracts.BindingModels; using ConfectioneryContracts.BusinessLogicsContracts; using ConfectioneryContracts.SearchModels; using ConfectioneryContracts.StoragesContract; @@ -14,13 +15,17 @@ namespace ConfectioneryBusinessLogic.BusinessLogics private readonly IOrderStorage _orderStorage; private readonly IPastryStorage _pastryStorage; private readonly IShopLogic _shopLogic; + private readonly AbstractMailWorker _mailWorker; + private readonly IClientLogic _clientLogic; - public OrderLogic(ILogger logger, IOrderStorage orderStorage, IPastryStorage pastryStorage, IShopLogic shopLogic) + public OrderLogic(ILogger logger, IOrderStorage orderStorage, IPastryStorage pastryStorage, IShopLogic shopLogic, IClientLogic clientLogic, AbstractMailWorker mailWorker) { _logger = logger; _shopLogic = shopLogic; _pastryStorage = pastryStorage; _orderStorage = orderStorage; + _mailWorker = mailWorker; + _clientLogic = clientLogic; } public bool CreateOrder(OrderBindingModel model) @@ -33,11 +38,13 @@ namespace ConfectioneryBusinessLogic.BusinessLogics } model.Status = OrderStatus.Принят; model.DateCreate = DateTime.Now; - if (_orderStorage.Insert(model) == null) + var result = _orderStorage.Insert(model); + if (result == null) { _logger.LogWarning("Insert operation failed"); return false; } + SendOrderStatusMail(result.ClientId, $"Новый заказ создан. Номер заказа #{result.Id}", $"Заказ #{result.Id} от {result.DateCreate} на сумму {result.Sum:0.00} принят"); return true; } @@ -122,11 +129,13 @@ namespace ConfectioneryBusinessLogic.BusinessLogics model.PastryId = vmodel.PastryId; model.Sum = vmodel.Sum; model.Count= vmodel.Count; - if (_orderStorage.Update(model) == null) + var result = _orderStorage.Update(model); + if (result == null) { _logger.LogWarning("Update operation failed"); return false; } + SendOrderStatusMail(result.ClientId, $"Изменен статус заказа #{result.Id}", $"Заказ #{model.Id} изменен статус на {result.Status}"); return true; } @@ -146,5 +155,21 @@ namespace ConfectioneryBusinessLogic.BusinessLogics _logger.LogInformation("ReadElement find. Id:{Id}", element.Id); return element; } + + 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/ConfectionaryFileImplement/DataFileSingleton.cs b/ConfectionaryFileImplement/DataFileSingleton.cs index 91a4ee0..60529d7 100644 --- a/ConfectionaryFileImplement/DataFileSingleton.cs +++ b/ConfectionaryFileImplement/DataFileSingleton.cs @@ -12,12 +12,14 @@ namespace ConfectioneryFileImplement private readonly string ShopFileName = "Shop.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 Pastries { get; private set; } public List Clients { get; private set; } public List Shops { get; private set; } public List Implementers { get; private set; } + public List Messages { get; private set; } public static DataFileSingleton GetInstance() { @@ -33,6 +35,7 @@ namespace ConfectioneryFileImplement public void SaveClients() => SaveData(Clients, OrderFileName, "Clients", x => x.GetXElement); public void SaveShops() => SaveData(Shops, ShopFileName, "Shops", x => x.GetXElement); public void SaveImplementers() => SaveData(Orders, ImplementerFileName, "Implementers", x => x.GetXElement); + public void SaveMessages() => SaveData(Orders, ImplementerFileName, "Messages", x => x.GetXElement); private DataFileSingleton() { @@ -42,6 +45,7 @@ namespace ConfectioneryFileImplement Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!; Shops = LoadData(ShopFileName, "Shop", x => Shop.Create(x)!)!; Implementers = LoadData(ImplementerFileName, "Implementer", x => Implementer.Create(x)!)!; + Messages = LoadData(MessageInfoFileName, "MessageInfo", x => MessageInfo.Create(x)!)!; } private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) { diff --git a/ConfectionaryFileImplement/MessageInfo.cs b/ConfectionaryFileImplement/MessageInfo.cs new file mode 100644 index 0000000..ba0dc59 --- /dev/null +++ b/ConfectionaryFileImplement/MessageInfo.cs @@ -0,0 +1,102 @@ +using ConfectioneryContracts.BindingModels; +using ConfectioneryContracts.ViewModels; +using ConfectioneryDataModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace ConfectioneryFileImplement.Models +{ + // Update в этой сущности не нужен, поскольку в логике мы не изменяем никакие поля после создания письма + public class MessageInfo : IMessageInfoModel + { + public string MessageId { get; private set; } = string.Empty; + + public int? ClientId { get; private set; } + + public string SenderName { get; private set; } = string.Empty; + + public DateTime DateDelivery { get; private set; } = DateTime.Now; + + public string Subject { get; private set; } = string.Empty; + + public string Body { get; private set; } = string.Empty; + public bool HasRead { get; private set; } + public string? Reply { get; private set; } + + public static MessageInfo? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Reply = model.Reply, + HasRead = model.HasRead, + Subject = model.Subject, + ClientId = model.ClientId, + MessageId = model.MessageId, + SenderName = model.SenderName, + DateDelivery = model.DateDelivery, + }; + } + + public static MessageInfo? Create(XElement element) + { + if (element == null) + { + return null; + } + return new() + { + Body = element.Attribute("Body")!.Value, + Reply = element.Attribute("Reply")!.Value, + HasRead = Convert.ToBoolean(element.Attribute("HasRead")!.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 void Update(MessageInfoBindingModel model) + { + if (model == null) + { + return; + } + Reply = model.Reply; + HasRead = model.HasRead; + } + + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Reply = Reply, + HasRead = HasRead, + Subject = Subject, + ClientId = ClientId, + MessageId = MessageId, + SenderName = SenderName, + DateDelivery = DateDelivery, + }; + + public XElement GetXElement => new("MessageInfo", + new XAttribute("Body", Body), + new XAttribute("Reply", Reply), + new XAttribute("HasRead", HasRead), + new XAttribute("Subject", Subject), + new XAttribute("ClientId", ClientId), + new XAttribute("MessageId", MessageId), + new XAttribute("SenderName", SenderName), + new XAttribute("DateDelivery", DateDelivery) + ); + } + +} diff --git a/ConfectionaryFileImplement/MessageInfoStorage.cs b/ConfectionaryFileImplement/MessageInfoStorage.cs new file mode 100644 index 0000000..e8ab119 --- /dev/null +++ b/ConfectionaryFileImplement/MessageInfoStorage.cs @@ -0,0 +1,70 @@ +using ConfectioneryContracts.BindingModels; +using ConfectioneryContracts.SearchModels; +using ConfectioneryContracts.StoragesContract; +using ConfectioneryContracts.ViewModels; +using ConfectioneryFileImplement.Models; +using System.Reflection; + +namespace ConfectioneryFileImplement +{ + 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) + { + var res = _source.Messages + .Where(x => !model.ClientId.HasValue || x.ClientId == model.ClientId) + .Select(x => x.GetViewModel); + if (!(model.Page.HasValue && model.PageSize.HasValue)) + { + return res.ToList(); + } + return res.Skip((model.Page.Value - 1) * model.PageSize.Value).Take(model.PageSize.Value).ToList(); + + } + + public List GetFullList() + { + return _source.Messages + .Select(x => x.GetViewModel) + .ToList(); + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = MessageInfo.Create(model); + if (newMessage == null) + { + return null; + } + _source.Messages.Add(newMessage); + _source.SaveMessages(); + return newMessage.GetViewModel; + } + + public MessageInfoViewModel? Update(MessageInfoBindingModel model) + { + var res = _source.Messages.FirstOrDefault(x => x.MessageId.Equals(model.MessageId)); + if (res != null) + { + res.Update(model); + _source.SaveMessages(); + } + return res?.GetViewModel; + } + } +} diff --git a/ConfectionaryListImplement/DataListSingleton.cs b/ConfectionaryListImplement/DataListSingleton.cs index 4dffcdc..c3b26a8 100644 --- a/ConfectionaryListImplement/DataListSingleton.cs +++ b/ConfectionaryListImplement/DataListSingleton.cs @@ -10,6 +10,7 @@ namespace ConfectioneryListImplement public List Pastry { get; set; } public List Clients { get; set; } public List Implementers { get; set; } + public List Messages { get; set; } public List Shops { get; set; } private DataListSingleton() @@ -19,6 +20,7 @@ namespace ConfectioneryListImplement Pastry = new List(); Clients = new List(); Implementers = new List(); + Messages = new List(); Shops = new List(); } public static DataListSingleton GetInstance() diff --git a/ConfectionaryListImplement/MessageInfo.cs b/ConfectionaryListImplement/MessageInfo.cs new file mode 100644 index 0000000..588b890 --- /dev/null +++ b/ConfectionaryListImplement/MessageInfo.cs @@ -0,0 +1,72 @@ +using ConfectioneryContracts.BindingModels; +using ConfectioneryContracts.ViewModels; +using ConfectioneryDataModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ConfectioneryListImplement.Models +{ + // Update в этой сущности не нужен, поскольку в логике мы не изменяем никакие поля после создания письма + public class MessageInfo : IMessageInfoModel + { + public string MessageId { get; private set; } = string.Empty; + + public int? ClientId { get; private set; } + + public string SenderName { get; private set; } = string.Empty; + + public DateTime DateDelivery { get; private set; } = DateTime.Now; + + public string Subject { get; private set; } = string.Empty; + + public string Body { get; private set; } = string.Empty; + public bool HasRead { get; private set; } + public string? Reply { get; private set; } + + public static MessageInfo? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Reply = model.Reply, + HasRead = model.HasRead, + Subject = model.Subject, + ClientId = model.ClientId, + MessageId = model.MessageId, + SenderName = model.SenderName, + DateDelivery = model.DateDelivery, + }; + } + + public void Update(MessageInfoBindingModel model) + { + if (model == null) + { + return; + } + Reply = model.Reply; + HasRead = model.HasRead; + } + + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Reply = Reply, + HasRead = HasRead, + Subject = Subject, + ClientId = ClientId, + MessageId = MessageId, + SenderName = SenderName, + DateDelivery = DateDelivery, + }; + + } + +} diff --git a/ConfectionaryListImplement/MessageInfoStorage.cs b/ConfectionaryListImplement/MessageInfoStorage.cs new file mode 100644 index 0000000..ea04f1a --- /dev/null +++ b/ConfectionaryListImplement/MessageInfoStorage.cs @@ -0,0 +1,89 @@ +using ConfectioneryContracts.BindingModels; +using ConfectioneryContracts.SearchModels; +using ConfectioneryContracts.StoragesContract; +using ConfectioneryContracts.ViewModels; +using ConfectioneryListImplement.Models; +using System.Collections.Generic; + +namespace ConfectioneryListImplement +{ + 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); + } + } + + if (!(model.Page.HasValue && model.PageSize.HasValue)) + { + return result; + } + if (model.Page * model.PageSize >= result.Count) + { + return null; + } + List filteredResult = new(); + for (var i = (model.Page.Value - 1) * model.PageSize.Value; i < model.Page.Value * model.PageSize.Value; i++) + { + filteredResult.Add(result[i]); + } + return filteredResult; + } + + 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 = MessageInfo.Create(model); + if (newMessage == null) + { + return null; + } + _source.Messages.Add(newMessage); + return newMessage.GetViewModel; + } + + public MessageInfoViewModel? Update(MessageInfoBindingModel model) + { + foreach (var message in _source.Messages) + { + if (message.MessageId.Equals(model.MessageId)) + { + message.Update(model); + return message.GetViewModel; + } + } + return null; + } + } +} diff --git a/Confectionery/App.config b/Confectionery/App.config new file mode 100644 index 0000000..400d322 --- /dev/null +++ b/Confectionery/App.config @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/Confectionery/ConfectioneryView.csproj b/Confectionery/ConfectioneryView.csproj index 100e09c..ccf95a5 100644 --- a/Confectionery/ConfectioneryView.csproj +++ b/Confectionery/ConfectioneryView.csproj @@ -36,6 +36,9 @@ + + Always + PreserveNewest diff --git a/Confectionery/FormMain.Designer.cs b/Confectionery/FormMain.Designer.cs index d7648ba..d3b98cb 100644 --- a/Confectionery/FormMain.Designer.cs +++ b/Confectionery/FormMain.Designer.cs @@ -38,16 +38,17 @@ reportsToolStripMenuItem = new ToolStripMenuItem(); reportShopsToolStripMenuItem = new ToolStripMenuItem(); ShopPastriesToolStripMenuItem = new ToolStripMenuItem(); - groupOrdersToolStripMenuItem = new ToolStripMenuItem(); - pastriesToolStripMenuItem = new ToolStripMenuItem(); - pastryComponentsToolStripMenuItem = new ToolStripMenuItem(); - ordersToolStripMenuItem = new ToolStripMenuItem(); - DoWorkToolStripMenuItem = new ToolStripMenuItem(); - dataGridView = new DataGridView(); + groupOrdersToolStripMenuItem = new ToolStripMenuItem(); + pastriesToolStripMenuItem = new ToolStripMenuItem(); + pastryComponentsToolStripMenuItem = new ToolStripMenuItem(); + ordersToolStripMenuItem = new ToolStripMenuItem(); + mailToolStripMenuItem = new ToolStripMenuItem(); + dataGridView = new DataGridView(); buttonCreateOrder = new Button(); button3 = new Button(); button4 = new Button(); buttonAddPastryInShop = new Button(); + DoWorkToolStripMenuItem = new ToolStripMenuItem(); buttonSellPastry = new Button(); menuStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); @@ -55,7 +56,7 @@ // // menuStrip1 // - menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, reportsToolStripMenuItem, DoWorkToolStripMenuItem }); + menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, reportsToolStripMenuItem, DoWorkToolStripMenuItem, mailToolStripMenuItem }); menuStrip1.Location = new Point(0, 0); menuStrip1.Name = "menuStrip1"; menuStrip1.Size = new Size(783, 24); @@ -181,6 +182,13 @@ buttonCreateOrder.UseVisualStyleBackColor = true; buttonCreateOrder.Click += ButtonCreateOrder_Click; // + // mailToolStripMenuItem + // + mailToolStripMenuItem.Name = "mailToolStripMenuItem"; + mailToolStripMenuItem.Size = new Size(62, 20); + mailToolStripMenuItem.Text = "Письма"; + mailToolStripMenuItem.Click += MailToolStripMenuItem_Click; + // // button3 // button3.Anchor = AnchorStyles.Top | AnchorStyles.Right; @@ -269,7 +277,8 @@ private ToolStripMenuItem clientsToolStripMenuItem; private Button buttonAddPastryInShop; private Button buttonSellPastry; - private ToolStripMenuItem ImplementersToolStripMenuItem; - private ToolStripMenuItem DoWorkToolStripMenuItem; - } + private ToolStripMenuItem ImplementersToolStripMenuItem; + private ToolStripMenuItem DoWorkToolStripMenuItem; + private ToolStripMenuItem mailToolStripMenuItem; + } } \ No newline at end of file diff --git a/Confectionery/FormMain.cs b/Confectionery/FormMain.cs index 4533cb0..ff448d9 100644 --- a/Confectionery/FormMain.cs +++ b/Confectionery/FormMain.cs @@ -212,13 +212,22 @@ namespace ConfectioneryView } } - private void DoWorkToolStripMenuItem_Click(object sender, EventArgs e) - { - _workProcess.DoWork(( - Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, - _orderLogic); - MessageBox.Show(" ", "", - MessageBoxButtons.OK, MessageBoxIcon.Information); - } - } + private void DoWorkToolStripMenuItem_Click(object sender, EventArgs e) + { + _workProcess.DoWork(( + Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, + _orderLogic); + MessageBox.Show(" ", "", + MessageBoxButtons.OK, MessageBoxIcon.Information); + } + + private void MailToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormViewMail)); + if (service is FormViewMail form) + { + form.ShowDialog(); + } + } + } } \ No newline at end of file diff --git a/Confectionery/FormReplyMail.Designer.cs b/Confectionery/FormReplyMail.Designer.cs new file mode 100644 index 0000000..21e2af9 --- /dev/null +++ b/Confectionery/FormReplyMail.Designer.cs @@ -0,0 +1,149 @@ +namespace ConfectioneryView +{ + partial class FormReplyMail + { + /// + /// 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() + { + buttonSave = new Button(); + buttonCancel = new Button(); + label1 = new Label(); + label2 = new Label(); + label3 = new Label(); + textBoxHead = new TextBox(); + textBoxMail = new TextBox(); + textBoxReply = new TextBox(); + SuspendLayout(); + // + // buttonSave + // + buttonSave.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + buttonSave.Location = new Point(460, 291); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(117, 30); + buttonSave.TabIndex = 0; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += ButtonSave_Click; + // + // buttonCancel + // + buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + buttonCancel.Location = new Point(337, 291); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(117, 30); + buttonCancel.TabIndex = 1; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += ButtonCancel_Click; + // + // label1 + // + label1.Location = new Point(12, 9); + label1.Name = "label1"; + label1.Size = new Size(117, 23); + label1.TabIndex = 2; + label1.Text = "Заголовок письма:"; + label1.TextAlign = ContentAlignment.TopRight; + // + // label2 + // + label2.Location = new Point(12, 38); + label2.Name = "label2"; + label2.Size = new Size(117, 23); + label2.TabIndex = 3; + label2.Text = "Текст письма:"; + label2.TextAlign = ContentAlignment.TopRight; + // + // label3 + // + label3.Location = new Point(12, 117); + label3.Name = "label3"; + label3.Size = new Size(117, 31); + label3.TabIndex = 4; + label3.Text = "Ответ на письмо:"; + label3.TextAlign = ContentAlignment.TopRight; + // + // textBoxHead + // + textBoxHead.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + textBoxHead.Location = new Point(135, 5); + textBoxHead.Name = "textBoxHead"; + textBoxHead.ReadOnly = true; + textBoxHead.Size = new Size(442, 23); + textBoxHead.TabIndex = 5; + // + // textBoxMail + // + textBoxMail.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + textBoxMail.Location = new Point(135, 35); + textBoxMail.Multiline = true; + textBoxMail.Name = "textBoxMail"; + textBoxMail.ReadOnly = true; + textBoxMail.Size = new Size(442, 76); + textBoxMail.TabIndex = 6; + // + // textBoxReply + // + textBoxReply.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + textBoxReply.Location = new Point(135, 117); + textBoxReply.Multiline = true; + textBoxReply.Name = "textBoxReply"; + textBoxReply.Size = new Size(442, 168); + textBoxReply.TabIndex = 7; + // + // FormReplyMail + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(589, 333); + Controls.Add(textBoxReply); + Controls.Add(textBoxMail); + Controls.Add(textBoxHead); + Controls.Add(label3); + Controls.Add(label2); + Controls.Add(label1); + Controls.Add(buttonCancel); + Controls.Add(buttonSave); + Name = "FormReplyMail"; + Text = "Ответ на письмо"; + Load += FormReplyMail_Load; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Button buttonSave; + private Button buttonCancel; + private Label label1; + private Label label2; + private Label label3; + private TextBox textBoxHead; + private TextBox textBoxMail; + private TextBox textBoxReply; + } +} \ No newline at end of file diff --git a/Confectionery/FormReplyMail.cs b/Confectionery/FormReplyMail.cs new file mode 100644 index 0000000..7c6ba2d --- /dev/null +++ b/Confectionery/FormReplyMail.cs @@ -0,0 +1,83 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using ConfectioneryBusinessLogic.MailWorker; +using ConfectioneryContracts.BusinessLogicsContracts; +using ConfectioneryContracts.ViewModels; +using Microsoft.Extensions.Logging; +using MimeKit; + +namespace ConfectioneryView +{ + public partial class FormReplyMail : Form + { + private readonly ILogger _logger; + private readonly AbstractMailWorker _mailWorker; + private readonly IMessageInfoLogic _logic; + private MessageInfoViewModel _message; + + public string MessageId { get; set; } = string.Empty; + + public FormReplyMail(ILogger logger, AbstractMailWorker mailWorker, IMessageInfoLogic logic) + { + InitializeComponent(); + _logger = logger; + _mailWorker = mailWorker; + _logic = logic; + } + + private void ButtonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + + private void ButtonSave_Click(object sender, EventArgs e) + { + _mailWorker.MailSendAsync(new() + { + MailAddress = _message.SenderName, + Subject = _message.Subject, + Text = textBoxReply.Text, + }); + _logic.Update(new() + { + MessageId = MessageId, + Reply = textBoxReply.Text, + HasRead = true, + }); + MessageBox.Show("Успешно отправлено письмо", "Отправка письма", MessageBoxButtons.OK); + DialogResult = DialogResult.OK; + Close(); + } + + private void FormReplyMail_Load(object sender, EventArgs e) + { + try + { + _message = _logic.ReadElement(new() { MessageId = MessageId }); + if (_message == null) + throw new ArgumentNullException("Письма с таким id не существует"); + Text += $"для {_message.SenderName}"; + textBoxHead.Text = _message.Subject; + textBoxMail.Text = _message.Body; + if (_message.HasRead is false) + { + _logic.Update(new() { MessageId = MessageId, HasRead = true, Reply = _message.Reply }); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения собщения"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + } +} diff --git a/Confectionery/FormReplyMail.resx b/Confectionery/FormReplyMail.resx new file mode 100644 index 0000000..f298a7b --- /dev/null +++ b/Confectionery/FormReplyMail.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/Confectionery/FormViewMail.Designer.cs b/Confectionery/FormViewMail.Designer.cs new file mode 100644 index 0000000..6a47acf --- /dev/null +++ b/Confectionery/FormViewMail.Designer.cs @@ -0,0 +1,104 @@ +namespace ConfectioneryView +{ + partial class FormViewMail + { + /// + /// 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(); + buttonPrevPage = new Button(); + buttonNextPage = new Button(); + labelInfoPages = new Label(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // dataGridView + // + dataGridView.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(0, 0); + dataGridView.Name = "dataGridView"; + dataGridView.RowTemplate.Height = 25; + dataGridView.Size = new Size(730, 454); + dataGridView.TabIndex = 0; + dataGridView.RowHeaderMouseClick += dataGridView_RowHeaderMouseClick; + // + // buttonPrevPage + // + buttonPrevPage.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; + buttonPrevPage.Location = new Point(12, 460); + buttonPrevPage.Name = "buttonPrevPage"; + buttonPrevPage.Size = new Size(75, 23); + buttonPrevPage.TabIndex = 1; + buttonPrevPage.Text = "<<<"; + buttonPrevPage.UseVisualStyleBackColor = true; + buttonPrevPage.Click += ButtonPrevPage_Click; + // + // buttonNextPage + // + buttonNextPage.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; + buttonNextPage.Location = new Point(203, 460); + buttonNextPage.Name = "buttonNextPage"; + buttonNextPage.Size = new Size(75, 23); + buttonNextPage.TabIndex = 2; + buttonNextPage.Text = ">>>"; + buttonNextPage.UseVisualStyleBackColor = true; + buttonNextPage.Click += ButtonNextPage_Click; + // + // labelInfoPages + // + labelInfoPages.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; + labelInfoPages.Location = new Point(93, 464); + labelInfoPages.Name = "labelInfoPages"; + labelInfoPages.Size = new Size(104, 19); + labelInfoPages.TabIndex = 3; + labelInfoPages.Text = "{0} страница"; + labelInfoPages.TextAlign = ContentAlignment.MiddleCenter; + // + // FormViewMail + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(727, 498); + Controls.Add(labelInfoPages); + Controls.Add(buttonNextPage); + Controls.Add(buttonPrevPage); + Controls.Add(dataGridView); + Name = "FormViewMail"; + Text = "Письма"; + Load += FormViewMail_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView; + private Button buttonPrevPage; + private Button buttonNextPage; + private Label labelInfoPages; + } +} \ No newline at end of file diff --git a/Confectionery/FormViewMail.cs b/Confectionery/FormViewMail.cs new file mode 100644 index 0000000..9c7655c --- /dev/null +++ b/Confectionery/FormViewMail.cs @@ -0,0 +1,111 @@ +using ConfectioneryBusinessLogic.MailWorker; +using ConfectioneryContracts.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; +using ConfectioneryContracts.ViewModels; + +namespace ConfectioneryView +{ + public partial class FormViewMail : Form + { + private readonly ILogger _logger; + private readonly IMessageInfoLogic _logic; + private int currentPage = 1; + public int pageSize = 5; + + public FormViewMail(ILogger logger, IMessageInfoLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + buttonPrevPage.Enabled = false; + } + + private void FormViewMail_Load(object sender, EventArgs e) + { + MailLoad(); + } + + private bool MailLoad() + { + try + { + var list = _logic.ReadList(new() + { + Page = currentPage, + PageSize = pageSize, + }); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["MessageId"].Visible = false; + dataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + _logger.LogInformation("Загрузка списка писем"); + labelInfoPages.Text = $"{currentPage} страница"; + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки писем"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + return false; + } + } + + private void ButtonPrevPage_Click(object sender, EventArgs e) + { + if (currentPage == 1) + { + _logger.LogWarning("Неккоректный номер страницы {page}", currentPage - 1); + return; + } + currentPage--; + if (MailLoad()) + { + buttonNextPage.Enabled = true; + if (currentPage == 1) + { + buttonPrevPage.Enabled = false; + } + } + } + + private void ButtonNextPage_Click(object sender, EventArgs e) + { + currentPage++; + if (!MailLoad() || ((List)dataGridView.DataSource).Count == 0) + { + _logger.LogWarning("Out of range messages"); + currentPage--; + MailLoad(); + buttonNextPage.Enabled = false; + } + else + { + buttonPrevPage.Enabled = true; + } + } + + private void dataGridView_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReplyMail)); + if (service is FormReplyMail form) + { + form.MessageId = (string)dataGridView.Rows[e.RowIndex].Cells["MessageId"].Value; + form.ShowDialog(); + MailLoad(); + } + } + } +} diff --git a/Confectionery/FormViewMail.resx b/Confectionery/FormViewMail.resx new file mode 100644 index 0000000..f298a7b --- /dev/null +++ b/Confectionery/FormViewMail.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/Confectionery/Program.cs b/Confectionery/Program.cs index 2c8e30f..5406826 100644 --- a/Confectionery/Program.cs +++ b/Confectionery/Program.cs @@ -9,6 +9,8 @@ using NLog.Extensions.Logging; using ConfectioneryBusinessLogic; using ConfectioneryBusinessLogic.OfficePackage.Implements; using ConfectioneryBusinessLogic.OfficePackage; +using ConfectioneryBusinessLogic.MailWorker; +using ConfectioneryContracts.BindingModels; namespace ConfectioneryView { @@ -28,7 +30,30 @@ namespace ConfectioneryView var services = new ServiceCollection(); ConfigureServices(services); _serviceProvider = services.BuildServiceProvider(); - Application.Run(_serviceProvider.GetRequiredService()); + + try + { + var mailSender = _serviceProvider.GetService(); + mailSender?.MailConfig(new MailConfigBindingModel + { + MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty, + MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty, + SmtpClientHost = System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty, + SmtpClientPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]), + PopHost = System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty, + PopPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"]) + }); + + // + var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000); + } + catch (Exception ex) + { + var logger = _serviceProvider.GetService(); + logger?.LogError(ex, " "); + } + + Application.Run(_serviceProvider.GetRequiredService()); } private static void ConfigureServices(ServiceCollection services) { @@ -43,17 +68,21 @@ namespace ConfectioneryView 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.AddTransient(); - services.AddTransient(); + services.AddSingleton(); + + services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -75,6 +104,10 @@ namespace ConfectioneryView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); } - } + + private static void MailCheck(object obj) => ServiceProvider?.GetService()?.MailCheck(); + } } \ No newline at end of file diff --git a/ConfectioneryClientApp/APIClient.cs b/ConfectioneryClientApp/APIClient.cs index e4620e6..ed25668 100644 --- a/ConfectioneryClientApp/APIClient.cs +++ b/ConfectioneryClientApp/APIClient.cs @@ -10,6 +10,7 @@ namespace ConfectioneryClientApp private static readonly HttpClient _client = new(); public static ClientViewModel? Client { get; set; } = null; + public static int CurrentPage { get; set; } = 0; public static void Connect(IConfiguration configuration) { diff --git a/ConfectioneryClientApp/Controllers/HomeController.cs b/ConfectioneryClientApp/Controllers/HomeController.cs index 83f23d6..f47d812 100644 --- a/ConfectioneryClientApp/Controllers/HomeController.cs +++ b/ConfectioneryClientApp/Controllers/HomeController.cs @@ -4,6 +4,9 @@ using ConfectioneryContracts.BindingModels; using ConfectioneryContracts.ViewModels; using Microsoft.AspNetCore.Mvc; using System.Diagnostics; +using System.Text; +using ConfectioneryContracts.SearchModels; +using Microsoft.AspNetCore.Mvc.Rendering; namespace ConfectioneryClientApp.Controllers { @@ -144,5 +147,56 @@ namespace ConfectioneryClientApp.Controllers var prod = APIClient.GetRequest($"api/main/getpastry?pastryId={pastry}"); return count * (prod?.Price ?? 1); } + + [HttpGet] + public IActionResult Mails() + { + if (APIClient.Client == null) + { + return Redirect("~/Home/Enter"); + } + return View(); + } + + /// + /// Switches the page. + /// + /// Возвращает кортеж с таблицой в html, текущей страницей писем, выключать ли кнопку пред. страницы, выключать ли кнопку след. страницы + [HttpGet] + public Tuple? SwitchPage(bool isNext) + { + if (isNext) + { + APIClient.CurrentPage++; + } + else + { + if (APIClient.CurrentPage == 1) + { + return null; + } + APIClient.CurrentPage--; + } + + var res = APIClient.GetRequest>($"api/client/getmessages?clientId={APIClient.Client!.Id}&page={APIClient.CurrentPage}"); + if (isNext && (res == null || res.Count == 0)) + { + APIClient.CurrentPage--; + return Tuple.Create(null, null, APIClient.CurrentPage != 1, false); + } + + StringBuilder htmlTable = new(); + foreach (var mail in res) + { + htmlTable.Append("" + + $"{mail.DateDelivery}" + + $"{mail.Subject}" + + $"{mail.Body}" + + "" + (mail.HasRead ? "Прочитано" : "Непрочитано") + "" + + $"{mail.Reply}" + + ""); + } + return Tuple.Create(htmlTable.ToString(), APIClient.CurrentPage.ToString(), APIClient.CurrentPage != 1, true); + } } } \ No newline at end of file diff --git a/ConfectioneryClientApp/Views/Home/Mails.cshtml b/ConfectioneryClientApp/Views/Home/Mails.cshtml new file mode 100644 index 0000000..29b1cbe --- /dev/null +++ b/ConfectioneryClientApp/Views/Home/Mails.cshtml @@ -0,0 +1,80 @@ +@{ + ViewData["Title"] = "Mails"; +} +
+

Письма

+
+ +
+ + + + + + + + + + + + +
+ Дата письма + + Заголовок + + Текст + + Статус + + Ответ +
+ +
+ + \ No newline at end of file diff --git a/ConfectioneryClientApp/Views/Shared/_Layout.cshtml b/ConfectioneryClientApp/Views/Shared/_Layout.cshtml index 8801497..b329d8b 100644 --- a/ConfectioneryClientApp/Views/Shared/_Layout.cshtml +++ b/ConfectioneryClientApp/Views/Shared/_Layout.cshtml @@ -28,6 +28,9 @@ + diff --git a/ConfectioneryContracts/BindingModels/MailConfigBindingModel.cs b/ConfectioneryContracts/BindingModels/MailConfigBindingModel.cs new file mode 100644 index 0000000..0d2aa83 --- /dev/null +++ b/ConfectioneryContracts/BindingModels/MailConfigBindingModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ConfectioneryContracts.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/ConfectioneryContracts/BindingModels/MailSendInfoBindingModel.cs b/ConfectioneryContracts/BindingModels/MailSendInfoBindingModel.cs new file mode 100644 index 0000000..8fd8e76 --- /dev/null +++ b/ConfectioneryContracts/BindingModels/MailSendInfoBindingModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ConfectioneryContracts.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/ConfectioneryContracts/BindingModels/MessageInfoBindingModel.cs b/ConfectioneryContracts/BindingModels/MessageInfoBindingModel.cs new file mode 100644 index 0000000..47b1fce --- /dev/null +++ b/ConfectioneryContracts/BindingModels/MessageInfoBindingModel.cs @@ -0,0 +1,27 @@ +using ConfectioneryDataModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ConfectioneryContracts.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; } + + public bool HasRead { get; set; } + public string? Reply { get; set; } + } +} diff --git a/ConfectioneryContracts/BusinessLogicsContracts/IMessageInfoLogic.cs b/ConfectioneryContracts/BusinessLogicsContracts/IMessageInfoLogic.cs new file mode 100644 index 0000000..f954f4e --- /dev/null +++ b/ConfectioneryContracts/BusinessLogicsContracts/IMessageInfoLogic.cs @@ -0,0 +1,22 @@ +using ConfectioneryContracts.BindingModels; +using ConfectioneryContracts.SearchModels; +using ConfectioneryContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ConfectioneryContracts.BusinessLogicsContracts +{ + public interface IMessageInfoLogic + { + List? ReadList(MessageInfoSearchModel? model); + + bool Create(MessageInfoBindingModel model); + + bool Update(MessageInfoBindingModel model); + + MessageInfoViewModel? ReadElement(MessageInfoSearchModel model); + } +} diff --git a/ConfectioneryContracts/SearchModels/MessageInfoSearchModel.cs b/ConfectioneryContracts/SearchModels/MessageInfoSearchModel.cs new file mode 100644 index 0000000..ca96e1d --- /dev/null +++ b/ConfectioneryContracts/SearchModels/MessageInfoSearchModel.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ConfectioneryContracts.SearchModels +{ + public class MessageInfoSearchModel + { + public int? ClientId { get; set; } + + public string? MessageId { get; set; } + + public int? Page { get; set; } + + public int? PageSize { get; set; } + } +} diff --git a/ConfectioneryContracts/StoragesContract/IMessageInfoStorage.cs b/ConfectioneryContracts/StoragesContract/IMessageInfoStorage.cs new file mode 100644 index 0000000..b62df06 --- /dev/null +++ b/ConfectioneryContracts/StoragesContract/IMessageInfoStorage.cs @@ -0,0 +1,23 @@ +using ConfectioneryContracts.BindingModels; +using ConfectioneryContracts.SearchModels; +using ConfectioneryContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ConfectioneryContracts.StoragesContract +{ + public interface IMessageInfoStorage + { + List GetFullList(); + + List GetFilteredList(MessageInfoSearchModel model); + + MessageInfoViewModel? GetElement(MessageInfoSearchModel model); + + MessageInfoViewModel? Insert(MessageInfoBindingModel model); + MessageInfoViewModel? Update(MessageInfoBindingModel model); + } +} diff --git a/ConfectioneryContracts/ViewModels/MessageInfoViewModel.cs b/ConfectioneryContracts/ViewModels/MessageInfoViewModel.cs new file mode 100644 index 0000000..2955d75 --- /dev/null +++ b/ConfectioneryContracts/ViewModels/MessageInfoViewModel.cs @@ -0,0 +1,35 @@ +using ConfectioneryDataModels; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ConfectioneryContracts.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; + + [DisplayName("Прочитано")] + public bool HasRead { get; set; } + + [DisplayName("Ответ")] + public string? Reply { get; set; } + } +} diff --git a/ConfectioneryDataModels/IMessageInfoModel.cs b/ConfectioneryDataModels/IMessageInfoModel.cs new file mode 100644 index 0000000..8db6579 --- /dev/null +++ b/ConfectioneryDataModels/IMessageInfoModel.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ConfectioneryDataModels +{ + public interface IMessageInfoModel + { + string MessageId { get; } + + int? ClientId { get; } + + string SenderName { get; } + + DateTime DateDelivery { get; } + + string Subject { get; } + + string Body { get; } + + public bool HasRead { get; } + + public string? Reply { get; } + } +} diff --git a/ConfectioneryDatabaseImplement/Client.cs b/ConfectioneryDatabaseImplement/Client.cs index 83a5d3a..ce4bdfe 100644 --- a/ConfectioneryDatabaseImplement/Client.cs +++ b/ConfectioneryDatabaseImplement/Client.cs @@ -27,6 +27,9 @@ namespace ConfectioneryDatabaseImplement.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) { if (model == null) diff --git a/ConfectioneryDatabaseImplement/ConfectioneryDatabase.cs b/ConfectioneryDatabaseImplement/ConfectioneryDatabase.cs index c85feb8..74e3aae 100644 --- a/ConfectioneryDatabaseImplement/ConfectioneryDatabase.cs +++ b/ConfectioneryDatabaseImplement/ConfectioneryDatabase.cs @@ -29,5 +29,6 @@ namespace ConfectioneryDatabaseImplement public virtual DbSet Clients { set; get; } public virtual DbSet Implementers { set; get; } + public virtual DbSet Messages { set; get; } } } diff --git a/ConfectioneryDatabaseImplement/MessageInfo.cs b/ConfectioneryDatabaseImplement/MessageInfo.cs new file mode 100644 index 0000000..4225660 --- /dev/null +++ b/ConfectioneryDatabaseImplement/MessageInfo.cs @@ -0,0 +1,72 @@ +using ConfectioneryContracts.BindingModels; +using ConfectioneryContracts.ViewModels; +using ConfectioneryDataModels; +using System.ComponentModel.DataAnnotations; + +namespace ConfectioneryDatabaseImplement.Models +{ + // Update в этой сущности не нужен, поскольку в логике мы не изменяем никакие поля после создания письма + public class MessageInfo : IMessageInfoModel + { + [Key] + public string MessageId { get; private set; } = string.Empty; + + public int? ClientId { get; private set; } + + public string SenderName { get; private set; } = string.Empty; + + public DateTime DateDelivery { get; private set; } = DateTime.Now; + + public string Subject { get; private set; } = string.Empty; + + public string Body { get; private set; } = string.Empty; + + public Client? Client { get; private set; } + + public bool HasRead { get; private set; } + public string? Reply { get; private set; } + + public static MessageInfo? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Reply = model.Reply, + HasRead = model.HasRead, + Subject = model.Subject, + ClientId = model.ClientId, + MessageId = model.MessageId, + SenderName = model.SenderName, + DateDelivery = model.DateDelivery, + }; + } + + public void Update(MessageInfoBindingModel model) + { + if (model == null) + { + return; + } + Reply = model.Reply; + HasRead = model.HasRead; + } + + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Reply = Reply, + HasRead = HasRead, + Subject = Subject, + ClientId = ClientId, + MessageId = MessageId, + SenderName = SenderName, + DateDelivery = DateDelivery, + }; + + } + +} diff --git a/ConfectioneryDatabaseImplement/MessageInfoStorage.cs b/ConfectioneryDatabaseImplement/MessageInfoStorage.cs new file mode 100644 index 0000000..19b93c1 --- /dev/null +++ b/ConfectioneryDatabaseImplement/MessageInfoStorage.cs @@ -0,0 +1,68 @@ +using ConfectioneryContracts.BindingModels; +using ConfectioneryContracts.SearchModels; +using ConfectioneryContracts.StoragesContract; +using ConfectioneryContracts.ViewModels; +using ConfectioneryDatabaseImplement.Models; + +namespace ConfectioneryDatabaseImplement +{ + public class MessageInfoStorage : IMessageInfoStorage + { + + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + using var context = new ConfectioneryDatabase(); + if (model.MessageId != null) + { + return context.Messages.FirstOrDefault(x => x.MessageId == model.MessageId)?.GetViewModel; + } + return null; + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + using var context = new ConfectioneryDatabase(); + var res = context.Messages + .Where(x => !model.ClientId.HasValue || x.ClientId == model.ClientId) + .Select(x => x.GetViewModel); + if (!(model.Page.HasValue && model.PageSize.HasValue)) + { + return res.ToList(); + } + return res.Skip((model.Page.Value - 1) * model.PageSize.Value).Take(model.PageSize.Value).ToList(); + } + + public List GetFullList() + { + using var context = new ConfectioneryDatabase(); + return context.Messages + .Select(x => x.GetViewModel) + .ToList(); + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + using var context = new ConfectioneryDatabase(); + var newMessage = MessageInfo.Create(model); + if (newMessage == null || context.Messages.Any(x => x.MessageId.Equals(model.MessageId))) + { + return null; + } + context.Messages.Add(newMessage); + context.SaveChanges(); + return newMessage.GetViewModel; + } + + public MessageInfoViewModel? Update(MessageInfoBindingModel model) + { + using var context = new ConfectioneryDatabase(); + var res = context.Messages.FirstOrDefault(x => x.MessageId.Equals(model.MessageId)); + if (res != null) + { + res.Update(model); + context.SaveChanges(); + } + return res?.GetViewModel; + } + } +} diff --git a/ConfectioneryDatabaseImplement/Migrations/20230313155013_create_message.Designer.cs b/ConfectioneryDatabaseImplement/Migrations/20230313155013_create_message.Designer.cs new file mode 100644 index 0000000..877a422 --- /dev/null +++ b/ConfectioneryDatabaseImplement/Migrations/20230313155013_create_message.Designer.cs @@ -0,0 +1,298 @@ +// +using System; +using ConfectioneryDatabaseImplement; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace ConfectioneryDatabaseImplement.Migrations +{ + [DbContext(typeof(ConfectioneryDatabase))] + [Migration("20230313155013_create_message")] + partial class create_message + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.3") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("ConfectioneryDatabaseImplement.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("ConfectioneryDatabaseImplement.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("ConfectioneryDatabaseImplement.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("ConfectioneryDatabaseImplement.Models.MessageInfo", b => + { + b.Property("MessageId") + .HasColumnType("nvarchar(450)"); + + b.Property("Body") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("int"); + + b.Property("DateDelivery") + .HasColumnType("datetime2"); + + b.Property("SenderName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Subject") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("MessageId"); + + b.HasIndex("ClientId"); + + b.ToTable("Messages"); + }); + + modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Order", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateImplement") + .HasColumnType("datetime2"); + + b.Property("ImplementerId") + .HasColumnType("int"); + + b.Property("PastryId") + .HasColumnType("int"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("Sum") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.HasIndex("ImplementerId"); + + b.HasIndex("PastryId"); + + b.ToTable("Orders"); + }); + + modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Pastry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("PastryName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Price") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.ToTable("Pastries"); + }); + + modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.PastryComponent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ComponentId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("PastryId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ComponentId"); + + b.HasIndex("PastryId"); + + b.ToTable("PastryComponents"); + }); + + modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.MessageInfo", b => + { + b.HasOne("ConfectioneryDatabaseImplement.Models.Client", "Client") + .WithMany("Messages") + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + + modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Order", b => + { + b.HasOne("ConfectioneryDatabaseImplement.Models.Client", "Client") + .WithMany("Orders") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("ConfectioneryDatabaseImplement.Models.Implementer", "Implementer") + .WithMany("Orders") + .HasForeignKey("ImplementerId"); + + b.HasOne("ConfectioneryDatabaseImplement.Models.Pastry", "Pastry") + .WithMany("Orders") + .HasForeignKey("PastryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Client"); + + b.Navigation("Implementer"); + + b.Navigation("Pastry"); + }); + + modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.PastryComponent", b => + { + b.HasOne("ConfectioneryDatabaseImplement.Models.Component", "Component") + .WithMany("PastryComponents") + .HasForeignKey("ComponentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("ConfectioneryDatabaseImplement.Models.Pastry", "Pastry") + .WithMany("Components") + .HasForeignKey("PastryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Component"); + + b.Navigation("Pastry"); + }); + + modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Client", b => + { + b.Navigation("Messages"); + + b.Navigation("Orders"); + }); + + modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Component", b => + { + b.Navigation("PastryComponents"); + }); + + modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Implementer", b => + { + b.Navigation("Orders"); + }); + + modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Pastry", b => + { + b.Navigation("Components"); + + b.Navigation("Orders"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/ConfectioneryDatabaseImplement/Migrations/20230313155013_create_message.cs b/ConfectioneryDatabaseImplement/Migrations/20230313155013_create_message.cs new file mode 100644 index 0000000..9e35314 --- /dev/null +++ b/ConfectioneryDatabaseImplement/Migrations/20230313155013_create_message.cs @@ -0,0 +1,48 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace ConfectioneryDatabaseImplement.Migrations +{ + /// + public partial class create_message : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Messages", + columns: table => new + { + MessageId = table.Column(type: "nvarchar(450)", nullable: false), + ClientId = table.Column(type: "int", nullable: true), + SenderName = table.Column(type: "nvarchar(max)", nullable: false), + DateDelivery = table.Column(type: "datetime2", nullable: false), + Subject = table.Column(type: "nvarchar(max)", nullable: false), + Body = table.Column(type: "nvarchar(max)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Messages", x => x.MessageId); + table.ForeignKey( + name: "FK_Messages_Clients_ClientId", + column: x => x.ClientId, + principalTable: "Clients", + principalColumn: "Id"); + }); + + migrationBuilder.CreateIndex( + name: "IX_Messages_ClientId", + table: "Messages", + column: "ClientId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Messages"); + } + } +} diff --git a/ConfectioneryDatabaseImplement/Migrations/20230317234305_upgrade-message.Designer.cs b/ConfectioneryDatabaseImplement/Migrations/20230317234305_upgrade-message.Designer.cs new file mode 100644 index 0000000..6ba4437 --- /dev/null +++ b/ConfectioneryDatabaseImplement/Migrations/20230317234305_upgrade-message.Designer.cs @@ -0,0 +1,395 @@ +// +using System; +using ConfectioneryDatabaseImplement; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace ConfectioneryDatabaseImplement.Migrations +{ + [DbContext(typeof(ConfectioneryDatabase))] + [Migration("20230317234305_upgrade-message")] + partial class upgrademessage + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.3") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("ConfectioneryDatabaseImplement.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("ConfectioneryDatabaseImplement.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("ConfectioneryDatabaseImplement.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("ConfectioneryDatabaseImplement.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("HasRead") + .HasColumnType("bit"); + + b.Property("Reply") + .HasColumnType("nvarchar(max)"); + + b.Property("SenderName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Subject") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("MessageId"); + + b.HasIndex("ClientId"); + + b.ToTable("Messages"); + }); + + modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Order", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateImplement") + .HasColumnType("datetime2"); + + b.Property("ImplementerId") + .HasColumnType("int"); + + b.Property("PastryId") + .HasColumnType("int"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("Sum") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.HasIndex("ImplementerId"); + + b.HasIndex("PastryId"); + + b.ToTable("Orders"); + }); + + modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Pastry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("PastryName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Price") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.ToTable("Pastries"); + }); + + modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.PastryComponent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ComponentId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("PastryId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ComponentId"); + + b.HasIndex("PastryId"); + + b.ToTable("PastryComponents"); + }); + + modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Shop", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Address") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("DateOpening") + .HasColumnType("datetime2"); + + b.Property("MaxCountPastries") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("PastryId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("PastryId"); + + b.ToTable("Shops"); + }); + + modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.ShopPastry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("PastryId") + .HasColumnType("int"); + + b.Property("ShopId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("PastryId"); + + b.HasIndex("ShopId"); + + b.ToTable("ShopPastries"); + }); + + modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.MessageInfo", b => + { + b.HasOne("ConfectioneryDatabaseImplement.Models.Client", "Client") + .WithMany("Messages") + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + + modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Order", b => + { + b.HasOne("ConfectioneryDatabaseImplement.Models.Client", "Client") + .WithMany("Orders") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("ConfectioneryDatabaseImplement.Models.Implementer", "Implementer") + .WithMany("Orders") + .HasForeignKey("ImplementerId"); + + b.HasOne("ConfectioneryDatabaseImplement.Models.Pastry", "Pastry") + .WithMany("Orders") + .HasForeignKey("PastryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Client"); + + b.Navigation("Implementer"); + + b.Navigation("Pastry"); + }); + + modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.PastryComponent", b => + { + b.HasOne("ConfectioneryDatabaseImplement.Models.Component", "Component") + .WithMany("PastryComponents") + .HasForeignKey("ComponentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("ConfectioneryDatabaseImplement.Models.Pastry", "Pastry") + .WithMany("Components") + .HasForeignKey("PastryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Component"); + + b.Navigation("Pastry"); + }); + + modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Shop", b => + { + b.HasOne("ConfectioneryDatabaseImplement.Models.Pastry", null) + .WithMany("Shops") + .HasForeignKey("PastryId"); + }); + + modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.ShopPastry", b => + { + b.HasOne("ConfectioneryDatabaseImplement.Models.Pastry", "Pastry") + .WithMany() + .HasForeignKey("PastryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("ConfectioneryDatabaseImplement.Models.Shop", "Shop") + .WithMany("ShopPastries") + .HasForeignKey("ShopId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Pastry"); + + b.Navigation("Shop"); + }); + + modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Client", b => + { + b.Navigation("Messages"); + + b.Navigation("Orders"); + }); + + modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Component", b => + { + b.Navigation("PastryComponents"); + }); + + modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Implementer", b => + { + b.Navigation("Orders"); + }); + + modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Pastry", b => + { + b.Navigation("Components"); + + b.Navigation("Orders"); + + b.Navigation("Shops"); + }); + + modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Shop", b => + { + b.Navigation("ShopPastries"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/ConfectioneryDatabaseImplement/Migrations/20230317234305_upgrade-message.cs b/ConfectioneryDatabaseImplement/Migrations/20230317234305_upgrade-message.cs new file mode 100644 index 0000000..ac45468 --- /dev/null +++ b/ConfectioneryDatabaseImplement/Migrations/20230317234305_upgrade-message.cs @@ -0,0 +1,39 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace ConfectioneryDatabaseImplement.Migrations +{ + /// + public partial class upgrademessage : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "HasRead", + table: "Messages", + type: "bit", + nullable: false, + defaultValue: false); + + migrationBuilder.AddColumn( + name: "Reply", + table: "Messages", + type: "nvarchar(max)", + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "HasRead", + table: "Messages"); + + migrationBuilder.DropColumn( + name: "Reply", + table: "Messages"); + } + } +} diff --git a/ConfectioneryDatabaseImplement/Migrations/ConfectioneryDatabaseModelSnapshot.cs b/ConfectioneryDatabaseImplement/Migrations/ConfectioneryDatabaseModelSnapshot.cs index cc60273..be68b52 100644 --- a/ConfectioneryDatabaseImplement/Migrations/ConfectioneryDatabaseModelSnapshot.cs +++ b/ConfectioneryDatabaseImplement/Migrations/ConfectioneryDatabaseModelSnapshot.cs @@ -94,6 +94,42 @@ namespace ConfectioneryDatabaseImplement.Migrations b.ToTable("Implementers"); }); + modelBuilder.Entity("ConfectioneryDatabaseImplement.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("HasRead") + .HasColumnType("bit"); + + b.Property("Reply") + .HasColumnType("nvarchar(max)"); + + b.Property("SenderName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Subject") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("MessageId"); + + b.HasIndex("ClientId"); + + b.ToTable("Messages"); + }); + modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -241,6 +277,15 @@ namespace ConfectioneryDatabaseImplement.Migrations b.ToTable("ShopPastries"); }); + modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.MessageInfo", b => + { + b.HasOne("ConfectioneryDatabaseImplement.Models.Client", "Client") + .WithMany("Messages") + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Order", b => { b.HasOne("ConfectioneryDatabaseImplement.Models.Client", "Client") @@ -313,6 +358,8 @@ namespace ConfectioneryDatabaseImplement.Migrations modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Client", b => { + b.Navigation("Messages"); + b.Navigation("Orders"); }); diff --git a/ConfectioneryRestApi/Controllers/ClientController.cs b/ConfectioneryRestApi/Controllers/ClientController.cs index 6e165ca..1d49bdb 100644 --- a/ConfectioneryRestApi/Controllers/ClientController.cs +++ b/ConfectioneryRestApi/Controllers/ClientController.cs @@ -13,11 +13,14 @@ namespace ConfectioneryRestApi.Controllers private readonly ILogger _logger; private readonly IClientLogic _logic; + private readonly IMessageInfoLogic _mailLogic; + public int pageSize = 3; - public ClientController(IClientLogic logic, ILogger logger) + public ClientController(IClientLogic logic, IMessageInfoLogic mailLogic, ILogger logger) { _logger = logger; _logic = logic; + _mailLogic = mailLogic; } [HttpGet] @@ -66,5 +69,24 @@ namespace ConfectioneryRestApi.Controllers throw; } } - } + + [HttpGet] + public List? GetMessages(int clientId, int page) + { + try + { + return _mailLogic.ReadList(new() + { + ClientId = clientId, + Page = page, + PageSize = pageSize + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения писем клиента"); + throw; + } + } + } } diff --git a/ConfectioneryRestApi/Program.cs b/ConfectioneryRestApi/Program.cs index d2c513c..2ac77fd 100644 --- a/ConfectioneryRestApi/Program.cs +++ b/ConfectioneryRestApi/Program.cs @@ -1,5 +1,7 @@ using ConfectioneryBusinessLogic; using ConfectioneryBusinessLogic.BusinessLogics; +using ConfectioneryBusinessLogic.MailWorker; +using ConfectioneryContracts.BindingModels; using ConfectioneryContracts.BusinessLogicsContracts; using ConfectioneryContracts.StoragesContract; using ConfectioneryDatabaseImplement; @@ -17,6 +19,10 @@ builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddTransient(); + +builder.Services.AddSingleton(); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); @@ -34,6 +40,19 @@ 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/ConfectioneryRestApi/appsettings.json b/ConfectioneryRestApi/appsettings.json index 10f68b8..697acfb 100644 --- a/ConfectioneryRestApi/appsettings.json +++ b/ConfectioneryRestApi/appsettings.json @@ -5,5 +5,12 @@ "Microsoft.AspNetCore": "Warning" } }, - "AllowedHosts": "*" + "AllowedHosts": "*", + + "SmtpClientHost": "smtp.mail.ru", + "SmtpClientPort": "587", + "PopHost": "pop.mail.ru", + "PopPort": "995", + "MailLogin": "ordersender228@mail.ru", + "MailPassword": "v8czsQ8zztJc5wEHxKPN" }