From db92699469dcc3ea284d308f2baaa162aae26125 Mon Sep 17 00:00:00 2001 From: Arkadiy Radaev Date: Thu, 16 May 2024 10:17:58 +0400 Subject: [PATCH] res7 --- .../BusinessLogics/ClientLogic.cs | 222 ++++++----- .../BusinessLogics/MessageInfoLogic.cs | 94 +++++ .../BusinessLogics/OrderLogic.cs | 149 +++++--- .../GiftShopBusinessLogic.csproj | 1 + .../MailWorker/AbstractMailWorker.cs | 100 +++++ .../MailWorker/MailKitWorker.cs | 77 ++++ .../Controllers/HomeController.cs | 14 +- .../GiftShopClientApp.csproj | 1 + .../Properties/launchSettings.json | 6 +- .../GiftShopClientApp/Views/Home/Mails.cshtml | 53 +++ .../Views/Shared/_Layout.cshtml | 3 + GiftShop/GiftShopClientApp/appsettings.json | 2 +- .../BindingModels/MailConfigBindingModel.cs | 17 + .../BindingModels/MailSendInfoBindingModel.cs | 11 + .../BindingModels/MessageInfoBindingModel.cs | 19 + .../IMessageInfoLogic.cs | 13 + .../GiftShopContracts.csproj | 4 + .../SearchModels/MessageInfoSearchModel.cs | 9 + .../StoragesContracts/IMessageInfoStorage.cs | 17 + .../ViewModels/MessageInfoViewModel.cs | 24 ++ .../GiftShopDataModels.csproj | 4 + .../Models/IMessageInfoModel.cs | 17 + .../GiftShopDatabase.cs | 2 + .../GiftShopDatabaseImplement.csproj | 1 + .../Implements/MessageInfoStorage.cs | 52 +++ .../Implements/OrderStorage.cs | 92 ++--- .../20240516061313_lab7.Designer.cs | 300 +++++++++++++++ .../Migrations/20240516061313_lab7.cs | 48 +++ .../GiftShopDatabaseModelSnapshot.cs | 39 ++ .../Models/Client.cs | 2 + .../Models/Message.cs | 54 +++ .../GiftShopDatabaseImplement/Models/Order.cs | 92 ++--- .../DataFileSingleton.cs | 10 +- .../GiftShopFileImplement.csproj | 4 + .../Implements/MessageInfoStorage.cs | 52 +++ .../Implements/OrderStorage.cs | 108 +++--- .../GiftShopFileImplement/Models/Message.cs | 74 ++++ .../DataListSingleton.cs | 2 + .../GiftShopListImplement.csproj | 4 + .../Implements/MessageInfoStorage.cs | 60 +++ .../Implements/OrderStorage.cs | 64 ++-- .../GiftShopListImplement/Models/Message.cs | 48 +++ .../Controllers/ClientController.cs | 30 +- .../GiftShopRestApi/GiftShopRestApi.csproj | 1 + GiftShop/GiftShopRestApi/Program.cs | 17 + .../Properties/launchSettings.json | 6 +- GiftShop/GiftShopRestApi/appsettings.json | 8 +- GiftShop/GiftShopView/App.config | 11 + .../GiftShopView/FormCreateOrder.Designer.cs | 298 ++++++++------- GiftShop/GiftShopView/FormCreateOrder.cs | 240 ++++++------ GiftShop/GiftShopView/FormMails.Designer.cs | 64 ++++ GiftShop/GiftShopView/FormMails.cs | 46 +++ GiftShop/GiftShopView/FormMails.resx | 60 +++ GiftShop/GiftShopView/FormMain.Designer.cs | 353 +++++++++--------- GiftShop/GiftShopView/FormMain.cs | 9 + GiftShop/GiftShopView/FormMain.resx | 64 +--- GiftShop/GiftShopView/GiftShopView.csproj | 4 + GiftShop/GiftShopView/Program.cs | 52 ++- 58 files changed, 2368 insertions(+), 860 deletions(-) create mode 100644 GiftShop/GiftShopBusinessLogic/BusinessLogics/MessageInfoLogic.cs create mode 100644 GiftShop/GiftShopBusinessLogic/MailWorker/AbstractMailWorker.cs create mode 100644 GiftShop/GiftShopBusinessLogic/MailWorker/MailKitWorker.cs create mode 100644 GiftShop/GiftShopClientApp/Views/Home/Mails.cshtml create mode 100644 GiftShop/GiftShopContracts/BindingModels/MailConfigBindingModel.cs create mode 100644 GiftShop/GiftShopContracts/BindingModels/MailSendInfoBindingModel.cs create mode 100644 GiftShop/GiftShopContracts/BindingModels/MessageInfoBindingModel.cs create mode 100644 GiftShop/GiftShopContracts/BusinessLogicsContracts/IMessageInfoLogic.cs create mode 100644 GiftShop/GiftShopContracts/SearchModels/MessageInfoSearchModel.cs create mode 100644 GiftShop/GiftShopContracts/StoragesContracts/IMessageInfoStorage.cs create mode 100644 GiftShop/GiftShopContracts/ViewModels/MessageInfoViewModel.cs create mode 100644 GiftShop/GiftShopDataModels/Models/IMessageInfoModel.cs create mode 100644 GiftShop/GiftShopDatabaseImplement/Implements/MessageInfoStorage.cs create mode 100644 GiftShop/GiftShopDatabaseImplement/Migrations/20240516061313_lab7.Designer.cs create mode 100644 GiftShop/GiftShopDatabaseImplement/Migrations/20240516061313_lab7.cs create mode 100644 GiftShop/GiftShopDatabaseImplement/Models/Message.cs create mode 100644 GiftShop/GiftShopFileImplement/Implements/MessageInfoStorage.cs create mode 100644 GiftShop/GiftShopFileImplement/Models/Message.cs create mode 100644 GiftShop/GiftShopListImplement/Implements/MessageInfoStorage.cs create mode 100644 GiftShop/GiftShopListImplement/Models/Message.cs create mode 100644 GiftShop/GiftShopView/App.config create mode 100644 GiftShop/GiftShopView/FormMails.Designer.cs create mode 100644 GiftShop/GiftShopView/FormMails.cs create mode 100644 GiftShop/GiftShopView/FormMails.resx diff --git a/GiftShop/GiftShopBusinessLogic/BusinessLogics/ClientLogic.cs b/GiftShop/GiftShopBusinessLogic/BusinessLogics/ClientLogic.cs index 6cea0b7..ce33113 100644 --- a/GiftShop/GiftShopBusinessLogic/BusinessLogics/ClientLogic.cs +++ b/GiftShop/GiftShopBusinessLogic/BusinessLogics/ClientLogic.cs @@ -4,124 +4,122 @@ using GiftShopContracts.SearchModels; using GiftShopContracts.StoragesContracts; using GiftShopContracts.ViewModels; using Microsoft.Extensions.Logging; +using System.Text.RegularExpressions; namespace GiftShopBusinessLogic.BusinessLogics { - public class ClientLogic : IClientLogic - { - private readonly ILogger _logger; + public class ClientLogic : IClientLogic + { + private readonly ILogger _logger; + private readonly IClientStorage _clientStorage; + public ClientLogic(ILogger logger, IClientStorage clientStorage) + { + _logger = logger; + _clientStorage = clientStorage; + } + public bool Create(ClientBindingModel model) + { + CheckModel(model); + if (_clientStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } - private readonly IClientStorage _clientStorage; + public bool Delete(ClientBindingModel model) + { + CheckModel(model, false); + _logger.LogInformation("Delete. Id:{Id}", model.Id); + if (_clientStorage.Delete(model) == null) + { + _logger.LogWarning("Delete operation failed"); + return false; + } + return true; + } - public ClientLogic(ILogger logger, IClientStorage clientStorage) - { - _logger = logger; - _clientStorage = clientStorage; - } + public ClientViewModel? ReadElement(ClientSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + _logger.LogInformation("ReadElement. ClientFIO:{ClientFIO}. Email: {Email}. Id:{ Id}", model.ClientFIO, model.Email, model.Id); + var element = _clientStorage.GetElement(model); + if (element == null) + { + _logger.LogWarning("ReadElement element not found"); + return null; + } + _logger.LogInformation("ReadElement find. Id:{Id}", element.Id); + return element; + } - public bool Create(ClientBindingModel model) - { - CheckModel(model); - if (_clientStorage.Insert(model) == null) - { - _logger.LogWarning("Insert operation failed"); - return false; - } - return true; - } + public List? ReadList(ClientSearchModel? model) + { + _logger.LogInformation("ReadList. ClientFIO: {ClientName}. Email: {Email}. Id: {Id}.", model?.ClientFIO, model?.Email, model?.Id); + var list = model == null ? _clientStorage.GetFullList() : _clientStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + _logger.LogInformation("ReadList. Count:{Count}", list.Count); + return list; + } - public bool Delete(ClientBindingModel model) - { - CheckModel(model, false); - _logger.LogInformation("Delete. Id: {Id}", model.Id); - if (_clientStorage.Delete(model) == null) - { - _logger.LogWarning("Delete operation failed"); - return false; - } - return true; - } + public bool Update(ClientBindingModel model) + { + CheckModel(model); + if (_clientStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + return true; + } + private void CheckModel(ClientBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (!withParams) + { + return; + } + if (string.IsNullOrEmpty(model.ClientFIO)) + { + throw new ArgumentNullException("Нет ФИО клиента", nameof(model.ClientFIO)); + } + if (string.IsNullOrEmpty(model.Email)) + { + throw new ArgumentNullException("У клиента отсутствует почта", nameof(model.Email)); + } + if (string.IsNullOrEmpty(model.Password)) + { + throw new ArgumentNullException("У клиента отсутствует пароль", nameof(model.Password)); + } + if (!Regex.IsMatch(model.Email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$", RegexOptions.IgnoreCase)) + { + throw new ArgumentException("Неправильно введенный email", nameof(model.Email)); + } + if (!Regex.IsMatch(model.Password, @"^((\w+\d+\W+)|(\w+\W+\d+)|(\d+\w+\W+)|(\d+\W+\w+)|(\W+\w+\d+)|(\W+\d+\w+))[\w\d\W]*$") || model.Password.Length < 10 || model.Password.Length > 50) + { + throw new ArgumentException("Неправильно введенный пароль", nameof(model.Password)); + } + _logger.LogInformation("Client. ClientID:{Id}. ClientFIO: {ClientFIO}. Email:{ Email}. Password: { Password}", model.Id, model.ClientFIO, model.Email, model.Password); + var element = _clientStorage.GetElement(new ClientSearchModel + { + Email = model.Email + }); + if (element != null && element.Id != model.Id) + { + throw new InvalidOperationException("Такой клиент уже существует"); + } - public ClientViewModel? ReadElement(ClientSearchModel model) - { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - _logger.LogInformation("ReadElement. ClientFIO: {ClientFIO}. Email: {Email}. Id: {Id}.", model.ClientFIO, model.Email, model.Id); - - var element = _clientStorage.GetElement(model); - if (element == null) - { - _logger.LogWarning("ReadElement element not found"); - return null; - } - _logger.LogInformation("ReadElement find. Id: {Id}", element.Id); - return element; - } - - public List? ReadList(ClientSearchModel? model) - { - _logger.LogInformation("ReadList. ClientFIO: {ClientName}. Email: {Email}. Id: {Id}.", model?.ClientFIO, model?.Email, model?.Id); - - var list = model == null ? _clientStorage.GetFullList() : _clientStorage.GetFilteredList(model); - if (list == null) - { - _logger.LogWarning("ReadList return null list"); - return null; - } - _logger.LogInformation("ReadList. Count: {Count}", list.Count); - return list; - } - - public bool Update(ClientBindingModel model) - { - CheckModel(model); - if (_clientStorage.Update(model) == null) - { - _logger.LogWarning("Update operation failed"); - return false; - } - return true; - } - - private void CheckModel(ClientBindingModel model, bool withParams = true) - { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - - if (!withParams) - { - return; - } - - if (string.IsNullOrEmpty(model.ClientFIO)) - { - throw new ArgumentNullException("Нет ФИО клиента", nameof(model.ClientFIO)); - } - - if (string.IsNullOrEmpty(model.Email)) - { - throw new ArgumentNullException("Нет почты клиента", nameof(model.Email)); - } - - if (string.IsNullOrEmpty(model.Password)) - { - throw new ArgumentNullException("Нет пароля клиента", nameof(model.Password)); - } - _logger.LogInformation("Client. ClientFIO: {ClientFIO}. Email: {Email}. Id: {Id}", model.ClientFIO, 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/GiftShop/GiftShopBusinessLogic/BusinessLogics/MessageInfoLogic.cs b/GiftShop/GiftShopBusinessLogic/BusinessLogics/MessageInfoLogic.cs new file mode 100644 index 0000000..31db58f --- /dev/null +++ b/GiftShop/GiftShopBusinessLogic/BusinessLogics/MessageInfoLogic.cs @@ -0,0 +1,94 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.BusinessLogicsContracts; +using GiftShopContracts.SearchModels; +using GiftShopContracts.StoragesContracts; +using GiftShopContracts.ViewModels; +using Microsoft.Extensions.Logging; + +namespace GiftShopBusinessLogic.BusinessLogics +{ + public class MessageInfoLogic : IMessageInfoLogic + { + private readonly ILogger _logger; + private readonly IClientStorage _clientStorage; + private readonly IMessageInfoStorage _messageStorage; + + public MessageInfoLogic(ILogger logger, IMessageInfoStorage messageStorage, IClientStorage clientStorage) + { + _logger = logger; + _messageStorage = messageStorage; + _clientStorage = clientStorage; + } + + public bool Create(MessageInfoBindingModel model) + { + CheckModel(model); + if (_messageStorage.Insert(model) == null) + { + _logger.LogWarning("Insert 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 ? _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; + } + private void CheckModel(MessageInfoBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (!withParams) + { + return; + } + if (string.IsNullOrEmpty(model.MessageId)) + { + throw new ArgumentNullException("Не указан id сообщения", nameof(model.MessageId)); + } + if (string.IsNullOrEmpty(model.SenderName)) + { + throw new ArgumentNullException("Не указао почта", nameof(model.SenderName)); + } + if (string.IsNullOrEmpty(model.Subject)) + { + throw new ArgumentNullException("Не указана тема", nameof(model.Subject)); + } + if (string.IsNullOrEmpty(model.Body)) + { + throw new ArgumentNullException("Не указан текст сообщения", nameof(model.Subject)); + } + + _logger.LogInformation("MessageInfo. MessageId:{MessageId}.SenderName:{SenderName}.Subject:{Subject}.Body:{Body}", model.MessageId, model.SenderName, model.Subject, model.Body); + var element = _clientStorage.GetElement(new ClientSearchModel + { + Email = model.SenderName + }); + if (element == null) + { + _logger.LogWarning("Не удалоссь найти клиента, отправившего письмо с адреса Email:{Email}", model.SenderName); + } + else + { + model.ClientId = element.Id; + } + } + } +} diff --git a/GiftShop/GiftShopBusinessLogic/BusinessLogics/OrderLogic.cs b/GiftShop/GiftShopBusinessLogic/BusinessLogics/OrderLogic.cs index cd66ea2..f6e2776 100644 --- a/GiftShop/GiftShopBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/GiftShop/GiftShopBusinessLogic/BusinessLogics/OrderLogic.cs @@ -1,10 +1,12 @@ -using GiftShopContracts.BindingModels; +using GiftShopBusinessLogic.MailWorker; +using GiftShopContracts.BindingModels; using GiftShopContracts.BusinessLogicsContracts; using GiftShopContracts.SearchModels; using GiftShopContracts.StoragesContracts; using GiftShopContracts.ViewModels; using GiftShopDataModels.Enums; using Microsoft.Extensions.Logging; +using MigraDoc.Rendering; namespace GiftShopBusinessLogic.BusinessLogics { @@ -14,15 +16,20 @@ namespace GiftShopBusinessLogic.BusinessLogics private readonly IOrderStorage _orderStorage; - public OrderLogic(ILogger logger, IOrderStorage orderStorage) + private readonly AbstractMailWorker _mailWorker; + + private readonly IClientLogic _clientLogic; + + static readonly object locker = new object(); + + public OrderLogic(ILogger logger, IOrderStorage orderStorage, AbstractMailWorker mailWorker, IClientLogic clientLogic) { _logger = logger; _orderStorage = orderStorage; - } - public bool TakeOrderInWork(OrderBindingModel model) - { - return StatusUpdate(model, OrderStatus.Выполняется); - } + _mailWorker = mailWorker; + _clientLogic = clientLogic; + } + public bool CreateOrder(OrderBindingModel model) { CheckModel(model); @@ -34,63 +41,73 @@ namespace GiftShopBusinessLogic.BusinessLogics } model.Status = OrderStatus.Принят; - - if (_orderStorage.Insert(model) == null) + var result = _orderStorage.Insert(model); + if (result == null) { model.Status = OrderStatus.Неизвестен; _logger.LogWarning("Insert operation failed"); return false; } - - return true; + SendOrderMessage(result.ClientId, $"Магазин подарков, Заказ №{result.Id}", $"Заказ №{result.Id} от {result.DateCreate} на сумму {result.Sum:0.00} принят"); + return true; } public bool StatusUpdate(OrderBindingModel model, OrderStatus newStatus) { - var vmodel = _orderStorage.GetElement(new() { Id = model.Id }); + CheckModel(model,false); + var element = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id }); - if (vmodel==null) + if (element == null) { - throw new ArgumentNullException(nameof(model)); - } + _logger.LogWarning("Read operation failed"); + throw new ArgumentNullException(nameof(model)); + } - if ((int)vmodel.Status + 1 != (int)newStatus) - { - throw new InvalidOperationException($"Попытка перевести заказ не в следующий статус: " + - $"Текущий статус: {vmodel.Status} \n" + - $"Планируемый статус: {newStatus} \n" + - $"Доступный статус: {(OrderStatus)((int)vmodel.Status + 1)}"); - } + if (element.Status != newStatus - 1) + { + throw new InvalidOperationException($"Попытка перевести заказ не в следующий статус: " + + $"Текущий статус: {element.Status} \n" + + $"Планируемый статус: {newStatus} \n" + + $"Доступный статус: {(OrderStatus)((int)element.Status + 1)}"); + } - model.Status = newStatus; + model.Status = newStatus; + if (model.Status == OrderStatus.Выдан) model.DateImplement = DateTime.Now; + model.DateCreate = element.DateCreate; - model.DateCreate = vmodel.DateCreate; + if (model.DateImplement == null) + model.DateImplement = element.DateImplement; - if (model.DateImplement == null) - model.DateImplement = vmodel.DateImplement; + if (element.ImplementerId.HasValue) + model.ImplementerId = element.ImplementerId; - if (vmodel.ImplementerId.HasValue) - model.ImplementerId = vmodel.ImplementerId; + model.GiftId = element.GiftId; + model.Sum = element.Sum; + model.Count = element.Count; - model.GiftId = vmodel.GiftId; - 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; } + SendOrderMessage(result.ClientId, $"Магазин подарков, Заказ №{result.Id}", $"Заказ №{model.Id} изменен статус на {result.Status}"); return true; } - + + public bool TakeOrderInWork(OrderBindingModel model) + { + lock (locker) + { + return StatusUpdate(model, OrderStatus.Выполняется); + } + } public bool DeliveryOrder(OrderBindingModel model) - { - model.DateImplement = DateTime.Now; - return StatusUpdate(model, OrderStatus.Готов); + { + model.DateImplement = DateTime.Now; + return StatusUpdate(model, OrderStatus.Готов); } public bool FinishOrder(OrderBindingModel model) @@ -120,52 +137,62 @@ namespace GiftShopBusinessLogic.BusinessLogics { throw new ArgumentNullException(nameof(model)); } - if (!withParams) { return; } - if (model.GiftId < 0) { throw new ArgumentNullException("Некорректный идентификатор изделия", nameof(model.GiftId)); } - if (model.Count <= 0) { throw new ArgumentNullException("Количество изделий в заказе должно быть больше 0", nameof(model.Count)); } - if (model.Sum <= 0) { throw new ArgumentNullException("Сумма заказа должна быть больше 0", nameof(model.Sum)); } - _logger.LogInformation("Order. OrderId:{Id}.Sum:{ Sum}. EngineId: { EngineId}", model.Id, model.Sum, model.GiftId); } - public OrderViewModel? ReadElement(OrderSearchModel model) - { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } + public OrderViewModel? ReadElement(OrderSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } - _logger.LogInformation("ReadElement. Id:{ Id}", model.Id); + _logger.LogInformation("ReadElement. Id:{ Id}", model.Id); - var element = _orderStorage.GetElement(model); + var element = _orderStorage.GetElement(model); - if (element == null) - { - _logger.LogWarning("ReadElement element not found"); + if (element == null) + { + _logger.LogWarning("ReadElement element not found"); - return null; - } + return null; + } - _logger.LogInformation("ReadElement find. Id:{Id}", element.Id); + _logger.LogInformation("ReadElement find. Id:{Id}", element.Id); - return element; - } - } + return element; + } + + private bool SendOrderMessage(int clientId, string subject, string text) + { + var client = _clientLogic.ReadElement(new() { Id = clientId }); + if (client == null) + { + return false; + } + _mailWorker.MailSendAsync(new() + { + MailAddress = client.Email, + Subject = subject, + Text = text + }); + return true; + } + } } - diff --git a/GiftShop/GiftShopBusinessLogic/GiftShopBusinessLogic.csproj b/GiftShop/GiftShopBusinessLogic/GiftShopBusinessLogic.csproj index 0f2995b..9dc7388 100644 --- a/GiftShop/GiftShopBusinessLogic/GiftShopBusinessLogic.csproj +++ b/GiftShop/GiftShopBusinessLogic/GiftShopBusinessLogic.csproj @@ -8,6 +8,7 @@ + diff --git a/GiftShop/GiftShopBusinessLogic/MailWorker/AbstractMailWorker.cs b/GiftShop/GiftShopBusinessLogic/MailWorker/AbstractMailWorker.cs new file mode 100644 index 0000000..c432c93 --- /dev/null +++ b/GiftShop/GiftShopBusinessLogic/MailWorker/AbstractMailWorker.cs @@ -0,0 +1,100 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; + +namespace GiftShopBusinessLogic.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/GiftShop/GiftShopBusinessLogic/MailWorker/MailKitWorker.cs b/GiftShop/GiftShopBusinessLogic/MailWorker/MailKitWorker.cs new file mode 100644 index 0000000..4669cc2 --- /dev/null +++ b/GiftShop/GiftShopBusinessLogic/MailWorker/MailKitWorker.cs @@ -0,0 +1,77 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using System.Net.Mail; +using System.Net; +using System.Text; +using MailKit.Net.Pop3; +using MailKit.Security; + +namespace GiftShopBusinessLogic.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.HtmlBody + }) ; + } + } + } + catch (AuthenticationException) + { } + finally + { + client.Disconnect(true); + } + }); + return list; + } + } +} diff --git a/GiftShop/GiftShopClientApp/Controllers/HomeController.cs b/GiftShop/GiftShopClientApp/Controllers/HomeController.cs index 35afa87..d48a916 100644 --- a/GiftShop/GiftShopClientApp/Controllers/HomeController.cs +++ b/GiftShop/GiftShopClientApp/Controllers/HomeController.cs @@ -101,9 +101,9 @@ namespace GiftShopClientApp.Controllers } APIClient.PostRequest("api/client/register", new ClientBindingModel { - ClientFIO = fio, Email = login, - Password = password + Password = password, + ClientFIO = fio }); Response.Redirect("Enter"); return; @@ -143,5 +143,15 @@ namespace GiftShopClientApp.Controllers var gif = APIClient.GetRequest($"api/main/getgift?giftId={gift}"); return count * (gif?.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/GiftShop/GiftShopClientApp/GiftShopClientApp.csproj b/GiftShop/GiftShopClientApp/GiftShopClientApp.csproj index 9679658..73356a8 100644 --- a/GiftShop/GiftShopClientApp/GiftShopClientApp.csproj +++ b/GiftShop/GiftShopClientApp/GiftShopClientApp.csproj @@ -7,6 +7,7 @@ + diff --git a/GiftShop/GiftShopClientApp/Properties/launchSettings.json b/GiftShop/GiftShopClientApp/Properties/launchSettings.json index b152340..0d12152 100644 --- a/GiftShop/GiftShopClientApp/Properties/launchSettings.json +++ b/GiftShop/GiftShopClientApp/Properties/launchSettings.json @@ -7,7 +7,7 @@ "ASPNETCORE_ENVIRONMENT": "Development" }, "dotnetRunMessages": true, - "applicationUrl": "http://localhost:7105;http://localhost:5092" + "applicationUrl": "https://localhost:7098;http://localhost:8080" }, "IIS Express": { "commandName": "IISExpress", @@ -21,8 +21,8 @@ "windowsAuthentication": false, "anonymousAuthentication": false, "iisExpress": { - "applicationUrl": "http://localhost:34342", - "sslPort": 0 + "applicationUrl": "http://localhost:36192", + "sslPort": 44375 } } } \ No newline at end of file diff --git a/GiftShop/GiftShopClientApp/Views/Home/Mails.cshtml b/GiftShop/GiftShopClientApp/Views/Home/Mails.cshtml new file mode 100644 index 0000000..a89927c --- /dev/null +++ b/GiftShop/GiftShopClientApp/Views/Home/Mails.cshtml @@ -0,0 +1,53 @@ +@using GiftShopContracts.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) +
+ } +
\ No newline at end of file diff --git a/GiftShop/GiftShopClientApp/Views/Shared/_Layout.cshtml b/GiftShop/GiftShopClientApp/Views/Shared/_Layout.cshtml index dc7a821..5e868ee 100644 --- a/GiftShop/GiftShopClientApp/Views/Shared/_Layout.cshtml +++ b/GiftShop/GiftShopClientApp/Views/Shared/_Layout.cshtml @@ -25,6 +25,9 @@ + diff --git a/GiftShop/GiftShopClientApp/appsettings.json b/GiftShop/GiftShopClientApp/appsettings.json index e896a1a..a238eff 100644 --- a/GiftShop/GiftShopClientApp/appsettings.json +++ b/GiftShop/GiftShopClientApp/appsettings.json @@ -7,5 +7,5 @@ }, "AllowedHosts": "*", - "IPAddress": "http://localhost:5062/" + "IPAddress": "http://localhost:5175/" } diff --git a/GiftShop/GiftShopContracts/BindingModels/MailConfigBindingModel.cs b/GiftShop/GiftShopContracts/BindingModels/MailConfigBindingModel.cs new file mode 100644 index 0000000..07373ea --- /dev/null +++ b/GiftShop/GiftShopContracts/BindingModels/MailConfigBindingModel.cs @@ -0,0 +1,17 @@ +namespace GiftShopContracts.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/GiftShop/GiftShopContracts/BindingModels/MailSendInfoBindingModel.cs b/GiftShop/GiftShopContracts/BindingModels/MailSendInfoBindingModel.cs new file mode 100644 index 0000000..0f0bc59 --- /dev/null +++ b/GiftShop/GiftShopContracts/BindingModels/MailSendInfoBindingModel.cs @@ -0,0 +1,11 @@ +namespace GiftShopContracts.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/GiftShop/GiftShopContracts/BindingModels/MessageInfoBindingModel.cs b/GiftShop/GiftShopContracts/BindingModels/MessageInfoBindingModel.cs new file mode 100644 index 0000000..3b00ebd --- /dev/null +++ b/GiftShop/GiftShopContracts/BindingModels/MessageInfoBindingModel.cs @@ -0,0 +1,19 @@ +using GiftShopDataModels.Models; + +namespace GiftShopContracts.BindingModels +{ + public class MessageInfoBindingModel : IMessageInfoModel + { + public string MessageId { get; set; } = string.Empty; + + public int? ClientId { get; set; } + + public string SenderName { get; set; } = string.Empty; + + public string Subject { get; set; } = string.Empty; + + public string Body { get; set; } = string.Empty; + + public DateTime DateDelivery { get; set; } + } +} diff --git a/GiftShop/GiftShopContracts/BusinessLogicsContracts/IMessageInfoLogic.cs b/GiftShop/GiftShopContracts/BusinessLogicsContracts/IMessageInfoLogic.cs new file mode 100644 index 0000000..bbc6cf0 --- /dev/null +++ b/GiftShop/GiftShopContracts/BusinessLogicsContracts/IMessageInfoLogic.cs @@ -0,0 +1,13 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.SearchModels; +using GiftShopContracts.ViewModels; + +namespace GiftShopContracts.BusinessLogicsContracts +{ + public interface IMessageInfoLogic + { + List? ReadList(MessageInfoSearchModel? model); + + bool Create(MessageInfoBindingModel model); + } +} diff --git a/GiftShop/GiftShopContracts/GiftShopContracts.csproj b/GiftShop/GiftShopContracts/GiftShopContracts.csproj index 66d285f..1d12326 100644 --- a/GiftShop/GiftShopContracts/GiftShopContracts.csproj +++ b/GiftShop/GiftShopContracts/GiftShopContracts.csproj @@ -6,6 +6,10 @@ enable + + + + diff --git a/GiftShop/GiftShopContracts/SearchModels/MessageInfoSearchModel.cs b/GiftShop/GiftShopContracts/SearchModels/MessageInfoSearchModel.cs new file mode 100644 index 0000000..b194373 --- /dev/null +++ b/GiftShop/GiftShopContracts/SearchModels/MessageInfoSearchModel.cs @@ -0,0 +1,9 @@ +namespace GiftShopContracts.SearchModels +{ + public class MessageInfoSearchModel + { + public int? ClientId { get; set; } + + public string? MessageId { get; set; } + } +} diff --git a/GiftShop/GiftShopContracts/StoragesContracts/IMessageInfoStorage.cs b/GiftShop/GiftShopContracts/StoragesContracts/IMessageInfoStorage.cs new file mode 100644 index 0000000..04e4645 --- /dev/null +++ b/GiftShop/GiftShopContracts/StoragesContracts/IMessageInfoStorage.cs @@ -0,0 +1,17 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.SearchModels; +using GiftShopContracts.ViewModels; + +namespace GiftShopContracts.StoragesContracts +{ + public interface IMessageInfoStorage + { + List GetFullList(); + + List GetFilteredList(MessageInfoSearchModel model); + + MessageInfoViewModel? GetElement(MessageInfoSearchModel model); + + MessageInfoViewModel? Insert(MessageInfoBindingModel model); + } +} diff --git a/GiftShop/GiftShopContracts/ViewModels/MessageInfoViewModel.cs b/GiftShop/GiftShopContracts/ViewModels/MessageInfoViewModel.cs new file mode 100644 index 0000000..56547bc --- /dev/null +++ b/GiftShop/GiftShopContracts/ViewModels/MessageInfoViewModel.cs @@ -0,0 +1,24 @@ +using GiftShopDataModels.Models; +using System.ComponentModel; + +namespace GiftShopContracts.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/GiftShop/GiftShopDataModels/GiftShopDataModels.csproj b/GiftShop/GiftShopDataModels/GiftShopDataModels.csproj index 132c02c..a2561fe 100644 --- a/GiftShop/GiftShopDataModels/GiftShopDataModels.csproj +++ b/GiftShop/GiftShopDataModels/GiftShopDataModels.csproj @@ -6,4 +6,8 @@ enable + + + + diff --git a/GiftShop/GiftShopDataModels/Models/IMessageInfoModel.cs b/GiftShop/GiftShopDataModels/Models/IMessageInfoModel.cs new file mode 100644 index 0000000..06e4789 --- /dev/null +++ b/GiftShop/GiftShopDataModels/Models/IMessageInfoModel.cs @@ -0,0 +1,17 @@ +namespace GiftShopDataModels.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/GiftShop/GiftShopDatabaseImplement/GiftShopDatabase.cs b/GiftShop/GiftShopDatabaseImplement/GiftShopDatabase.cs index 1b6aba0..c9c35d5 100644 --- a/GiftShop/GiftShopDatabaseImplement/GiftShopDatabase.cs +++ b/GiftShop/GiftShopDatabaseImplement/GiftShopDatabase.cs @@ -25,5 +25,7 @@ namespace GiftShopDatabaseImplement public virtual DbSet Clients { set; get; } public virtual DbSet Implementers { set; get; } + + public virtual DbSet Messages { set; get; } } } diff --git a/GiftShop/GiftShopDatabaseImplement/GiftShopDatabaseImplement.csproj b/GiftShop/GiftShopDatabaseImplement/GiftShopDatabaseImplement.csproj index 81ac990..3ad2062 100644 --- a/GiftShop/GiftShopDatabaseImplement/GiftShopDatabaseImplement.csproj +++ b/GiftShop/GiftShopDatabaseImplement/GiftShopDatabaseImplement.csproj @@ -7,6 +7,7 @@ + diff --git a/GiftShop/GiftShopDatabaseImplement/Implements/MessageInfoStorage.cs b/GiftShop/GiftShopDatabaseImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..27f5e98 --- /dev/null +++ b/GiftShop/GiftShopDatabaseImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,52 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.SearchModels; +using GiftShopContracts.StoragesContracts; +using GiftShopContracts.ViewModels; +using GiftShopDatabaseImplement.Models; + +namespace GiftShopDatabaseImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + using var context = new GiftShopDatabase(); + if (string.IsNullOrEmpty(model.MessageId)) + { + return null; + } + return context.Messages.FirstOrDefault(x => x.MessageId == model.MessageId)?.GetViewModel; + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + //if (!model.ClientId.HasValue) return new(); + using var context = new GiftShopDatabase(); + return context.Messages + .Where(x => x.ClientId == model.ClientId) + .Select(x => x.GetViewModel) + .ToList(); + } + + public List GetFullList() + { + using var context = new GiftShopDatabase(); + return context.Messages + .Select(x => x.GetViewModel) + .ToList(); + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + using var context = new GiftShopDatabase(); + var newMessage = Message.Create(context, model); + if (newMessage == null || context.Messages.Any(x => x.MessageId.Equals(model.MessageId))) + { + return null; + } + context.Messages.Add(newMessage); + context.SaveChanges(); + return newMessage.GetViewModel; + } + } +} diff --git a/GiftShop/GiftShopDatabaseImplement/Implements/OrderStorage.cs b/GiftShop/GiftShopDatabaseImplement/Implements/OrderStorage.cs index ef43ea9..30dbd0c 100644 --- a/GiftShop/GiftShopDatabaseImplement/Implements/OrderStorage.cs +++ b/GiftShop/GiftShopDatabaseImplement/Implements/OrderStorage.cs @@ -7,23 +7,23 @@ using Microsoft.EntityFrameworkCore; namespace GiftShopDatabaseImplement.Implements { - public class OrderStorage : IOrderStorage - { - public OrderViewModel? Delete(OrderBindingModel model) - { - using var context = new GiftShopDatabase(); - var element = context.Orders.FirstOrDefault(rec => rec.Id == model.Id); - if (element != null) - { - context.Orders.Remove(element); - context.SaveChanges(); - return element.GetViewModel; - } - return null; - } + public class OrderStorage : IOrderStorage + { + public OrderViewModel? Delete(OrderBindingModel model) + { + using var context = new GiftShopDatabase(); + var element = context.Orders.FirstOrDefault(rec => rec.Id == model.Id); + if (element != null) + { + context.Orders.Remove(element); + context.SaveChanges(); + return element.GetViewModel; + } + return null; + } - public OrderViewModel? GetElement(OrderSearchModel model) - { + public OrderViewModel? GetElement(OrderSearchModel model) + { using var context = new GiftShopDatabase(); return context.Orders.Include(x => x.Gift).Include(x => x.Client).Include(x => x.Implementer).FirstOrDefault( x => ((model.Id.HasValue && x.Id == model.Id) || @@ -52,43 +52,43 @@ namespace GiftShopDatabaseImplement.Implements } public List GetFullList() - { - using var context = new GiftShopDatabase(); + { + using var context = new GiftShopDatabase(); return context.Orders.Include(x => x.Gift) - .Include(x => x.Client).Include(x => x.Implementer).Select(x => x.GetViewModel).ToList(); - } + .Include(x => x.Client).Include(x => x.Implementer).Select(x => x.GetViewModel).ToList(); + } - public OrderViewModel? Insert(OrderBindingModel model) - { - using var context = new GiftShopDatabase(); - var newOrder = Order.Create(model, context); - if (newOrder == null) - { - return null; - } - context.Orders.Add(newOrder); - context.SaveChanges(); + public OrderViewModel? Insert(OrderBindingModel model) + { + using var context = new GiftShopDatabase(); + var newOrder = Order.Create(model, context); + if (newOrder == null) + { + return null; + } + context.Orders.Add(newOrder); + context.SaveChanges(); return context.Orders .Include(x => x.Gift) .Include(x => x.Client) - .Include(x => x.Implementer) - .FirstOrDefault(x => x.Id == newOrder.Id) + .Include(x => x.Implementer) + .FirstOrDefault(x => x.Id == newOrder.Id) ?.GetViewModel; } - public OrderViewModel? Update(OrderBindingModel model) - { - using var context = new GiftShopDatabase(); + public OrderViewModel? Update(OrderBindingModel model) + { + using var context = new GiftShopDatabase(); var order = context.Orders.Include(x => x.Gift) - .Include(x => x.Client).Include(x => x.Implementer).FirstOrDefault(x => x.Id == model.Id); - if (order == null) - { - return null; - } - order.Update(model); - context.SaveChanges(); - return order.GetViewModel; - } - } -} + .Include(x => x.Client).Include(x => x.Implementer).FirstOrDefault(x => x.Id == model.Id); + if (order == null) + { + return null; + } + order.Update(model); + context.SaveChanges(); + return order.GetViewModel; + } + } +} \ No newline at end of file diff --git a/GiftShop/GiftShopDatabaseImplement/Migrations/20240516061313_lab7.Designer.cs b/GiftShop/GiftShopDatabaseImplement/Migrations/20240516061313_lab7.Designer.cs new file mode 100644 index 0000000..61881c1 --- /dev/null +++ b/GiftShop/GiftShopDatabaseImplement/Migrations/20240516061313_lab7.Designer.cs @@ -0,0 +1,300 @@ +// +using System; +using GiftShopDatabaseImplement; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace GiftShopDatabaseImplement.Migrations +{ + [DbContext(typeof(GiftShopDatabase))] + [Migration("20240516061313_lab7")] + partial class lab7 + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.4") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("GiftShopDatabaseImplement.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("GiftShopDatabaseImplement.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("GiftShopDatabaseImplement.Models.Gift", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("GiftName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Price") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.ToTable("Gifts"); + }); + + modelBuilder.Entity("GiftShopDatabaseImplement.Models.GiftComponent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ComponentId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("GiftId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ComponentId"); + + b.HasIndex("GiftId"); + + b.ToTable("GiftComponents"); + }); + + modelBuilder.Entity("GiftShopDatabaseImplement.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("GiftShopDatabaseImplement.Models.Message", 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("GiftShopDatabaseImplement.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("GiftId") + .HasColumnType("int"); + + b.Property("GiftName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ImplementerId") + .HasColumnType("int"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("Sum") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.HasIndex("GiftId"); + + b.HasIndex("ImplementerId"); + + b.ToTable("Orders"); + }); + + modelBuilder.Entity("GiftShopDatabaseImplement.Models.GiftComponent", b => + { + b.HasOne("GiftShopDatabaseImplement.Models.Component", "Component") + .WithMany("GiftComponents") + .HasForeignKey("ComponentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("GiftShopDatabaseImplement.Models.Gift", "Gift") + .WithMany("Components") + .HasForeignKey("GiftId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Component"); + + b.Navigation("Gift"); + }); + + modelBuilder.Entity("GiftShopDatabaseImplement.Models.Message", b => + { + b.HasOne("GiftShopDatabaseImplement.Models.Client", "Client") + .WithMany() + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + + modelBuilder.Entity("GiftShopDatabaseImplement.Models.Order", b => + { + b.HasOne("GiftShopDatabaseImplement.Models.Client", "Client") + .WithMany("Orders") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("GiftShopDatabaseImplement.Models.Gift", "Gift") + .WithMany("Orders") + .HasForeignKey("GiftId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("GiftShopDatabaseImplement.Models.Implementer", "Implementer") + .WithMany("Orders") + .HasForeignKey("ImplementerId"); + + b.Navigation("Client"); + + b.Navigation("Gift"); + + b.Navigation("Implementer"); + }); + + modelBuilder.Entity("GiftShopDatabaseImplement.Models.Client", b => + { + b.Navigation("Orders"); + }); + + modelBuilder.Entity("GiftShopDatabaseImplement.Models.Component", b => + { + b.Navigation("GiftComponents"); + }); + + modelBuilder.Entity("GiftShopDatabaseImplement.Models.Gift", b => + { + b.Navigation("Components"); + + b.Navigation("Orders"); + }); + + modelBuilder.Entity("GiftShopDatabaseImplement.Models.Implementer", b => + { + b.Navigation("Orders"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/GiftShop/GiftShopDatabaseImplement/Migrations/20240516061313_lab7.cs b/GiftShop/GiftShopDatabaseImplement/Migrations/20240516061313_lab7.cs new file mode 100644 index 0000000..c241915 --- /dev/null +++ b/GiftShop/GiftShopDatabaseImplement/Migrations/20240516061313_lab7.cs @@ -0,0 +1,48 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace GiftShopDatabaseImplement.Migrations +{ + /// + public partial class lab7 : 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/GiftShop/GiftShopDatabaseImplement/Migrations/GiftShopDatabaseModelSnapshot.cs b/GiftShop/GiftShopDatabaseImplement/Migrations/GiftShopDatabaseModelSnapshot.cs index 4ee65ea..80ccb45 100644 --- a/GiftShop/GiftShopDatabaseImplement/Migrations/GiftShopDatabaseModelSnapshot.cs +++ b/GiftShop/GiftShopDatabaseImplement/Migrations/GiftShopDatabaseModelSnapshot.cs @@ -140,6 +140,36 @@ namespace GiftShopDatabaseImplement.Migrations b.ToTable("Implementers"); }); + modelBuilder.Entity("GiftShopDatabaseImplement.Models.Message", 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("GiftShopDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -206,6 +236,15 @@ namespace GiftShopDatabaseImplement.Migrations b.Navigation("Gift"); }); + modelBuilder.Entity("GiftShopDatabaseImplement.Models.Message", b => + { + b.HasOne("GiftShopDatabaseImplement.Models.Client", "Client") + .WithMany("ClientMessages") + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + modelBuilder.Entity("GiftShopDatabaseImplement.Models.Order", b => { b.HasOne("GiftShopDatabaseImplement.Models.Client", "Client") diff --git a/GiftShop/GiftShopDatabaseImplement/Models/Client.cs b/GiftShop/GiftShopDatabaseImplement/Models/Client.cs index 41f4d04..ff1dd36 100644 --- a/GiftShop/GiftShopDatabaseImplement/Models/Client.cs +++ b/GiftShop/GiftShopDatabaseImplement/Models/Client.cs @@ -18,6 +18,8 @@ namespace GiftShopDatabaseImplement.Models [ForeignKey("ClientId")] public virtual List Orders { get; set; } = new(); + [ForeignKey("ClientId")] + public virtual List ClientMessages { get; set; } = new(); public static Client? Create(ClientBindingModel model) { if (model == null) diff --git a/GiftShop/GiftShopDatabaseImplement/Models/Message.cs b/GiftShop/GiftShopDatabaseImplement/Models/Message.cs new file mode 100644 index 0000000..6e6a0eb --- /dev/null +++ b/GiftShop/GiftShopDatabaseImplement/Models/Message.cs @@ -0,0 +1,54 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.ViewModels; +using GiftShopDataModels.Models; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace GiftShopDatabaseImplement.Models +{ + public class Message : IMessageInfoModel + { + [Key] + [DatabaseGenerated(DatabaseGeneratedOption.None)] + 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 static Message? Create(GiftShopDatabase context, MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Subject = model.Subject, + ClientId = context.Clients.FirstOrDefault(x => x.Email == model.SenderName).Id, + Client = context.Clients.FirstOrDefault(x => x.Email == model.SenderName), + MessageId = model.MessageId, + SenderName = model.SenderName, + DateDelivery = model.DateDelivery, + }; + } + + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Subject = Subject, + ClientId = ClientId, + MessageId = MessageId, + SenderName = SenderName, + DateDelivery = DateDelivery, + }; + } +} diff --git a/GiftShop/GiftShopDatabaseImplement/Models/Order.cs b/GiftShop/GiftShopDatabaseImplement/Models/Order.cs index f49004e..eb7145a 100644 --- a/GiftShop/GiftShopDatabaseImplement/Models/Order.cs +++ b/GiftShop/GiftShopDatabaseImplement/Models/Order.cs @@ -6,55 +6,55 @@ using System.ComponentModel.DataAnnotations; namespace GiftShopDatabaseImplement.Models { - public class Order : IOrderModel - { - public int Id { get; private set; } + public class Order : IOrderModel + { + public int Id { get; private set; } - public int GiftId { get; private set; } + public int GiftId { get; private set; } [Required] public int ClientId { get; set; } - public int? ImplementerId { get; private set; } + public int? ImplementerId { get; private set; } - public string GiftName { get; private set; } = string.Empty; + public string GiftName { get; private set; } = string.Empty; - [Required] - public int Count { get; private set; } + [Required] + public int Count { get; private set; } - [Required] - public double Sum { get; private set; } + [Required] + public double Sum { get; private set; } - [Required] - public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен; + [Required] + public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен; - [Required] - public DateTime DateCreate { get; private set; } = DateTime.Now; + [Required] + public DateTime DateCreate { get; private set; } = DateTime.Now; - public DateTime? DateImplement { get; private set; } + public DateTime? DateImplement { get; private set; } - public virtual Gift Gift { get; set; } + public virtual Gift Gift { get; set; } public Client Client { get; set; } - public Implementer? Implementer { get; set; } + public Implementer? Implementer { get; set; } - public static Order? Create(OrderBindingModel? model, GiftShopDatabase context) - { - if (model == null) - { - return null; - } + public static Order? Create(OrderBindingModel? model, GiftShopDatabase context) + { + if (model == null) + { + return null; + } - return new Order() - { - Id = model.Id, - GiftId = model.GiftId, + return new Order() + { + Id = model.Id, + GiftId = model.GiftId, GiftName = model.GiftName, - Count = model.Count, - Sum = model.Sum, - Status = model.Status, - DateCreate = model.DateCreate, - DateImplement = model.DateImplement, + Count = model.Count, + Sum = model.Sum, + Status = model.Status, + DateCreate = model.DateCreate, + DateImplement = model.DateImplement, Gift = context.Gifts.FirstOrDefault(x => x.Id == model.GiftId), ClientId = model.ClientId, Client = context.Clients.FirstOrDefault(x => x.Id == model.ClientId), @@ -62,19 +62,19 @@ namespace GiftShopDatabaseImplement.Models Implementer = (model.ImplementerId.HasValue ? context.Implementers.FirstOrDefault(x => x.Id == model.ImplementerId) : null), }; - } + } - public void Update(OrderBindingModel? model) - { - if (model == null) - { - return; - } + public void Update(OrderBindingModel? model) + { + if (model == null) + { + return; + } - Status = model.Status; - DateImplement = model.DateImplement; - ImplementerId = model.ImplementerId; - } + Status = model.Status; + DateImplement = model.DateImplement; + ImplementerId = model.ImplementerId; + } public OrderViewModel GetViewModel { @@ -86,8 +86,8 @@ namespace GiftShopDatabaseImplement.Models Id = Id, GiftId = GiftId, ClientId = ClientId, - ImplementerId = ImplementerId, - ClientFIO = Client.ClientFIO, + ImplementerId = ImplementerId, + ClientFIO = Client.ClientFIO, GiftName = Gift.GiftName, Count = Count, Sum = Sum, @@ -99,4 +99,4 @@ namespace GiftShopDatabaseImplement.Models } } } -} +} \ No newline at end of file diff --git a/GiftShop/GiftShopFileImplement/DataFileSingleton.cs b/GiftShop/GiftShopFileImplement/DataFileSingleton.cs index f8331fb..834ee03 100644 --- a/GiftShop/GiftShopFileImplement/DataFileSingleton.cs +++ b/GiftShop/GiftShopFileImplement/DataFileSingleton.cs @@ -17,7 +17,9 @@ namespace GiftShopFileImplement private readonly string ClientFileName = "Client.xml"; - public List Components { get; private set; } + private readonly string MessageFileName = "Message.xml"; + + public List Components { get; private set; } public List Orders { get; private set; } @@ -27,6 +29,8 @@ namespace GiftShopFileImplement public List Implementers { get; private set; } + public List Messages { get; private set; } + public static DataFileSingleton GetInstance() { if (instance == null) @@ -45,12 +49,16 @@ namespace GiftShopFileImplement public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", x => x.GetXElement); public void SaveImplementers() => SaveData(Implementers, OrderFileName, "Implementers", x => x.GetXElement); + + public void SaveMessages() => SaveData(Messages, MessageFileName, "Messages", x => x.GetXElement); private DataFileSingleton() { Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!; Gifts = LoadData(GiftFileName, "Gift", x => Gift.Create(x)!)!; Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!; + Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!; Implementers = LoadData(ImplementerFileName, "Implementer", x => Implementer.Create(x)!)!; + Messages = LoadData(MessageFileName, "Message", x => Message.Create(x)!)!; } private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) diff --git a/GiftShop/GiftShopFileImplement/GiftShopFileImplement.csproj b/GiftShop/GiftShopFileImplement/GiftShopFileImplement.csproj index ec87bae..ec26524 100644 --- a/GiftShop/GiftShopFileImplement/GiftShopFileImplement.csproj +++ b/GiftShop/GiftShopFileImplement/GiftShopFileImplement.csproj @@ -6,6 +6,10 @@ enable + + + + diff --git a/GiftShop/GiftShopFileImplement/Implements/MessageInfoStorage.cs b/GiftShop/GiftShopFileImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..3b1c8ce --- /dev/null +++ b/GiftShop/GiftShopFileImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,52 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.SearchModels; +using GiftShopContracts.StoragesContracts; +using GiftShopContracts.ViewModels; +using GiftShopFileImplement.Models; + +namespace GiftShopFileImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + private readonly DataFileSingleton source; + public MessageInfoStorage() + { + source = DataFileSingleton.GetInstance(); + } + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (string.IsNullOrEmpty(model.MessageId)) + { + return null; + } + return source.Messages.FirstOrDefault(x => x.MessageId == model.MessageId)?.GetViewModel; + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + if (string.IsNullOrEmpty(model.MessageId)) + { + return new(); + } + return source.Messages.Where(x => + x.ClientId == model.ClientId).Select(x => x.GetViewModel).ToList(); + } + + public List GetFullList() + { + return source.Messages.Select(x => x.GetViewModel).ToList(); + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = Message.Create(model); + if (newMessage == null) + { + return null; + } + source.Messages.Add(newMessage); + source.SaveMessages(); + return newMessage.GetViewModel; + } + } +} diff --git a/GiftShop/GiftShopFileImplement/Implements/OrderStorage.cs b/GiftShop/GiftShopFileImplement/Implements/OrderStorage.cs index 801eb93..89f027c 100644 --- a/GiftShop/GiftShopFileImplement/Implements/OrderStorage.cs +++ b/GiftShop/GiftShopFileImplement/Implements/OrderStorage.cs @@ -6,36 +6,36 @@ using GiftShopFileImplement.Models; namespace GiftShopFileImplement.Implements { - public class OrderStorage : IOrderStorage - { - private readonly DataFileSingleton source; + public class OrderStorage : IOrderStorage + { + private readonly DataFileSingleton source; - public OrderStorage() - { - source = DataFileSingleton.GetInstance(); - } + public OrderStorage() + { + source = DataFileSingleton.GetInstance(); + } - public OrderViewModel? Delete(OrderBindingModel model) - { - var element = source.Orders.FirstOrDefault(x => x.Id == model.Id); + public OrderViewModel? Delete(OrderBindingModel model) + { + var element = source.Orders.FirstOrDefault(x => x.Id == model.Id); - if (element != null) - { - source.Orders.Remove(element); - source.SaveOrders(); + if (element != null) + { + source.Orders.Remove(element); + source.SaveOrders(); - return AccessStorage(element.GetViewModel); - } + return AccessStorage(element.GetViewModel); + } - return null; - } + return null; + } - public OrderViewModel? GetElement(OrderSearchModel model) - { - if (!model.Id.HasValue) - { - return null; - } + public OrderViewModel? GetElement(OrderSearchModel model) + { + if (!model.Id.HasValue) + { + return null; + } return AccessStorage(source.Orders .FirstOrDefault(x => ((model.Id.HasValue && x.Id == model.Id) || @@ -43,8 +43,8 @@ namespace GiftShopFileImplement.Implements x.ImplementerId == model.ImplementerId && x.Status == model.Status)))?.GetViewModel); } - public List GetFilteredList(OrderSearchModel model) - { + public List GetFilteredList(OrderSearchModel model) + { return source.Orders .Where(x => ( (!model.Id.HasValue || x.Id == model.Id) && @@ -58,41 +58,41 @@ namespace GiftShopFileImplement.Implements .ToList(); } - public List GetFullList() - { - return source.Orders.Select(x => AccessStorage(x.GetViewModel)).ToList(); - } + public List GetFullList() + { + return source.Orders.Select(x => AccessStorage(x.GetViewModel)).ToList(); + } - public OrderViewModel? Insert(OrderBindingModel model) - { - model.Id = source.Orders.Count > 0 ? source.Orders.Max(x => x.Id) + 1 : 1; - var newOrder = Order.Create(model); + public OrderViewModel? Insert(OrderBindingModel model) + { + model.Id = source.Orders.Count > 0 ? source.Orders.Max(x => x.Id) + 1 : 1; + var newOrder = Order.Create(model); - if (newOrder == null) - { - return null; - } + if (newOrder == null) + { + return null; + } - source.Orders.Add(newOrder); - source.SaveOrders(); + source.Orders.Add(newOrder); + source.SaveOrders(); - return AccessStorage(newOrder.GetViewModel); - } + return AccessStorage(newOrder.GetViewModel); + } - public OrderViewModel? Update(OrderBindingModel model) - { - var order = source.Orders.FirstOrDefault(x => x.Id == model.Id); + public OrderViewModel? Update(OrderBindingModel model) + { + var order = source.Orders.FirstOrDefault(x => x.Id == model.Id); - if (order == null) - { - return null; - } + if (order == null) + { + return null; + } - order.Update(model); - source.SaveOrders(); + order.Update(model); + source.SaveOrders(); - return AccessStorage(order.GetViewModel); - } + return AccessStorage(order.GetViewModel); + } public OrderViewModel AccessStorage(OrderViewModel model) { if (model == null) @@ -109,4 +109,4 @@ namespace GiftShopFileImplement.Implements return model; } } -} +} \ No newline at end of file diff --git a/GiftShop/GiftShopFileImplement/Models/Message.cs b/GiftShop/GiftShopFileImplement/Models/Message.cs new file mode 100644 index 0000000..f45793b --- /dev/null +++ b/GiftShop/GiftShopFileImplement/Models/Message.cs @@ -0,0 +1,74 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.ViewModels; +using GiftShopDataModels.Models; +using System.Xml.Linq; + +namespace GiftShopFileImplement.Models +{ + public class Message : IMessageInfoModel + { + public string MessageId { get; private set; } = string.Empty; + + public int? ClientId { get; private set; } + + public string SenderName { get; private set; } = string.Empty; + + public DateTime DateDelivery { get; private set; } = DateTime.Now; + + public string Subject { get; private set; } = string.Empty; + + public string Body { get; private set; } = string.Empty; + public static Message? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Subject = model.Subject, + DateDelivery = model.DateDelivery, + SenderName = model.SenderName, + ClientId = model.ClientId, + MessageId = model.MessageId + }; + } + + public static Message? Create(XElement element) + { + if (element == null) + { + return null; + } + return new() + { + Body = element.Attribute("Body")!.Value, + Subject = element.Attribute("Subject")!.Value, + DateDelivery = Convert.ToDateTime(element.Attribute("DateDelivery")!.Value), + SenderName = element.Attribute("SenderName")!.Value, + ClientId = Convert.ToInt32(element.Attribute("ClientId")!.Value), + MessageId = element.Attribute("MessageId")!.Value, + }; + } + + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Subject = Subject, + DateDelivery = DateDelivery, + SenderName = SenderName, + ClientId = ClientId, + MessageId = MessageId + }; + + public XElement GetXElement => new("MessageInfo", + new XAttribute("Subject", Subject), + new XAttribute("Body", Body), + new XAttribute("ClientId", ClientId), + new XAttribute("MessageId", MessageId), + new XAttribute("SenderName", SenderName), + new XAttribute("DateDelivery", DateDelivery) + ); + } +} diff --git a/GiftShop/GiftShopListImplement/DataListSingleton.cs b/GiftShop/GiftShopListImplement/DataListSingleton.cs index 3becc52..96c94c2 100644 --- a/GiftShop/GiftShopListImplement/DataListSingleton.cs +++ b/GiftShop/GiftShopListImplement/DataListSingleton.cs @@ -10,6 +10,7 @@ namespace GiftShopListImplement public List Gifts { get; set; } public List Clients { get; set; } public List Implementers { get; set; } + public List Messages { get; set; } private DataListSingleton() { Components = new List(); @@ -17,6 +18,7 @@ namespace GiftShopListImplement Gifts = new List(); Clients = new List(); Implementers = new List(); + Messages = new List(); } public static DataListSingleton GetInstance() { diff --git a/GiftShop/GiftShopListImplement/GiftShopListImplement.csproj b/GiftShop/GiftShopListImplement/GiftShopListImplement.csproj index ec87bae..ec26524 100644 --- a/GiftShop/GiftShopListImplement/GiftShopListImplement.csproj +++ b/GiftShop/GiftShopListImplement/GiftShopListImplement.csproj @@ -6,6 +6,10 @@ enable + + + + diff --git a/GiftShop/GiftShopListImplement/Implements/MessageInfoStorage.cs b/GiftShop/GiftShopListImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..90bfe70 --- /dev/null +++ b/GiftShop/GiftShopListImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,60 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.SearchModels; +using GiftShopContracts.StoragesContracts; +using GiftShopContracts.ViewModels; +using GiftShopListImplement.Models; + +namespace GiftShopListImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + private readonly DataListSingleton _source; + public MessageInfoStorage() + { + _source = DataListSingleton.GetInstance(); + } + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + foreach (var message in _source.Messages) + { + if (model.MessageId != null && model.MessageId.Equals(message.MessageId)) + return message.GetViewModel; + } + return null; + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + var result = new List(); + foreach (var message in _source.Messages) + { + if (message.ClientId.HasValue && message.ClientId == model.ClientId) + { + result.Add(message.GetViewModel); + } + } + return result; + } + + public List GetFullList() + { + var result = new List(); + foreach (var message in _source.Messages) + { + result.Add(message.GetViewModel); + } + return result; + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = Message.Create(model); + if (newMessage == null) + { + return null; + } + _source.Messages.Add(newMessage); + return newMessage.GetViewModel; + } + } +} diff --git a/GiftShop/GiftShopListImplement/Implements/OrderStorage.cs b/GiftShop/GiftShopListImplement/Implements/OrderStorage.cs index 679c4a0..1234394 100644 --- a/GiftShop/GiftShopListImplement/Implements/OrderStorage.cs +++ b/GiftShop/GiftShopListImplement/Implements/OrderStorage.cs @@ -6,30 +6,30 @@ using GiftShopListImplement.Models; namespace GiftShopListImplement.Implements { - public class OrderStorage : IOrderStorage - { - private readonly DataListSingleton _source; - public OrderStorage() - { - _source = DataListSingleton.GetInstance(); - } - public OrderViewModel? Delete(OrderBindingModel model) - { - for (int i = 0; i < _source.Orders.Count; ++i) - { - if (_source.Orders[i].Id == model.Id) - { - var element = _source.Orders[i]; - _source.Orders.RemoveAt(i); - return element.GetViewModel; - } - } + public class OrderStorage : IOrderStorage + { + private readonly DataListSingleton _source; + public OrderStorage() + { + _source = DataListSingleton.GetInstance(); + } + public OrderViewModel? Delete(OrderBindingModel model) + { + for (int i = 0; i < _source.Orders.Count; ++i) + { + if (_source.Orders[i].Id == model.Id) + { + var element = _source.Orders[i]; + _source.Orders.RemoveAt(i); + return element.GetViewModel; + } + } - return null; - } + return null; + } - public OrderViewModel? GetElement(OrderSearchModel model) - { + public OrderViewModel? GetElement(OrderSearchModel model) + { if (!model.Id.HasValue) { return null; @@ -46,8 +46,8 @@ namespace GiftShopListImplement.Implements return null; } - public List GetFilteredList(OrderSearchModel model) - { + public List GetFilteredList(OrderSearchModel model) + { var result = new List(); foreach (var order in _source.Orders) { @@ -63,8 +63,8 @@ namespace GiftShopListImplement.Implements return result; } - public List GetFullList() - { + public List GetFullList() + { List list = new(); foreach (Order order in _source.Orders) { @@ -73,8 +73,8 @@ namespace GiftShopListImplement.Implements return list; } - public OrderViewModel? Insert(OrderBindingModel model) - { + public OrderViewModel? Insert(OrderBindingModel model) + { model.Id = 1; foreach (Order order in _source.Orders) { @@ -92,8 +92,8 @@ namespace GiftShopListImplement.Implements return newOrder.GetViewModel; } - public OrderViewModel? Update(OrderBindingModel model) - { + public OrderViewModel? Update(OrderBindingModel model) + { foreach (Order order in _source.Orders) { if (order.Id == model.Id) @@ -103,7 +103,7 @@ namespace GiftShopListImplement.Implements } } return null; - } + } public OrderViewModel AccessStorage(OrderViewModel model) { if (model == null) @@ -120,4 +120,4 @@ namespace GiftShopListImplement.Implements return model; } } -} +} \ No newline at end of file diff --git a/GiftShop/GiftShopListImplement/Models/Message.cs b/GiftShop/GiftShopListImplement/Models/Message.cs new file mode 100644 index 0000000..a5e90d1 --- /dev/null +++ b/GiftShop/GiftShopListImplement/Models/Message.cs @@ -0,0 +1,48 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.ViewModels; +using GiftShopDataModels.Models; + +namespace GiftShopListImplement.Models +{ + public class Message : IMessageInfoModel + { + public string MessageId { get; private set; } = string.Empty; + + public int? ClientId { get; private set; } + + public string SenderName { get; private set; } = string.Empty; + + public DateTime DateDelivery { get; private set; } = DateTime.Now; + + public string Subject { get; private set; } = string.Empty; + + public string Body { get; private set; } = string.Empty; + + public static Message? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Subject = model.Subject, + DateDelivery = model.DateDelivery, + SenderName = model.SenderName, + ClientId = model.ClientId, + MessageId = model.MessageId + }; + } + + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Subject = Subject, + DateDelivery = DateDelivery, + SenderName = SenderName, + ClientId = ClientId, + MessageId = MessageId + }; + } +} diff --git a/GiftShop/GiftShopRestApi/Controllers/ClientController.cs b/GiftShop/GiftShopRestApi/Controllers/ClientController.cs index 0433cf8..16eace1 100644 --- a/GiftShop/GiftShopRestApi/Controllers/ClientController.cs +++ b/GiftShop/GiftShopRestApi/Controllers/ClientController.cs @@ -3,6 +3,7 @@ using GiftShopContracts.BusinessLogicsContracts; using GiftShopContracts.SearchModels; using GiftShopContracts.ViewModels; using Microsoft.AspNetCore.Mvc; +using System.Net; namespace GiftShopRestApi.Controllers { @@ -14,11 +15,14 @@ namespace GiftShopRestApi.Controllers private readonly IClientLogic _logic; - public ClientController(IClientLogic logic, ILogger logger) + private readonly IMessageInfoLogic _mailLogic; + + public ClientController(IClientLogic logic, ILogger logger, IMessageInfoLogic mailLogic) { _logger = logger; _logic = logic; - } + _mailLogic = mailLogic; + } [HttpGet] public ClientViewModel? Login(string login, string password) @@ -48,8 +52,9 @@ namespace GiftShopRestApi.Controllers catch (Exception ex) { _logger.LogError(ex, "Ошибка регистрации"); + Response.StatusCode = (int)HttpStatusCode.NotAcceptable; throw; - } + } } [HttpPost] @@ -65,5 +70,22 @@ namespace GiftShopRestApi.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/GiftShop/GiftShopRestApi/GiftShopRestApi.csproj b/GiftShop/GiftShopRestApi/GiftShopRestApi.csproj index 7d8cf8f..8e21be8 100644 --- a/GiftShop/GiftShopRestApi/GiftShopRestApi.csproj +++ b/GiftShop/GiftShopRestApi/GiftShopRestApi.csproj @@ -7,6 +7,7 @@ + diff --git a/GiftShop/GiftShopRestApi/Program.cs b/GiftShop/GiftShopRestApi/Program.cs index 3bc676c..1b1f54d 100644 --- a/GiftShop/GiftShopRestApi/Program.cs +++ b/GiftShop/GiftShopRestApi/Program.cs @@ -1,4 +1,6 @@ using GiftShopBusinessLogic.BusinessLogics; +using GiftShopBusinessLogic.MailWorker; +using GiftShopContracts.BindingModels; using GiftShopContracts.BusinessLogicsContracts; using GiftShopContracts.StoragesContracts; using GiftShopDatabaseImplement.Implements; @@ -15,11 +17,15 @@ 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.AddSingleton(); builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle @@ -31,6 +37,17 @@ builder.Services.AddSwaggerGen(c => var app = builder.Build(); +var mailSender = app.Services.GetService(); +mailSender?.MailConfig(new MailConfigBindingModel +{ + MailLogin = builder.Configuration?.GetSection("MailLogin")?.Value?.ToString() ?? string.Empty, + MailPassword = builder.Configuration?.GetSection("MailPassword")?.Value?.ToString() ?? string.Empty, + SmtpClientHost = builder.Configuration?.GetSection("SmtpClientHost")?.Value?.ToString() ?? string.Empty, + SmtpClientPort = Convert.ToInt32(builder.Configuration?.GetSection("SmtpClientPort")?.Value?.ToString()), + PopHost = builder.Configuration?.GetSection("PopHost")?.Value?.ToString() ?? string.Empty, + PopPort = Convert.ToInt32(builder.Configuration?.GetSection("PopPort")?.Value?.ToString()) +}); + // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { diff --git a/GiftShop/GiftShopRestApi/Properties/launchSettings.json b/GiftShop/GiftShopRestApi/Properties/launchSettings.json index 4b9b3a2..5d05b54 100644 --- a/GiftShop/GiftShopRestApi/Properties/launchSettings.json +++ b/GiftShop/GiftShopRestApi/Properties/launchSettings.json @@ -8,7 +8,7 @@ "ASPNETCORE_ENVIRONMENT": "Development" }, "dotnetRunMessages": true, - "applicationUrl": "http://localhost:7100;http://localhost:5062" + "applicationUrl": "https://localhost:7175;http://localhost:5175" }, "IIS Express": { "commandName": "IISExpress", @@ -24,8 +24,8 @@ "windowsAuthentication": false, "anonymousAuthentication": false, "iisExpress": { - "applicationUrl": "http://localhost:39704", - "sslPort": 0 + "applicationUrl": "http://localhost:38846", + "sslPort": 44369 } } } \ No newline at end of file diff --git a/GiftShop/GiftShopRestApi/appsettings.json b/GiftShop/GiftShopRestApi/appsettings.json index 10f68b8..7cf3f8f 100644 --- a/GiftShop/GiftShopRestApi/appsettings.json +++ b/GiftShop/GiftShopRestApi/appsettings.json @@ -5,5 +5,11 @@ "Microsoft.AspNetCore": "Warning" } }, - "AllowedHosts": "*" + "AllowedHosts": "*", + "SmtpClientHost": "smtp.gmail.com", + "SmtpClientPort": "587", + "PopHost": "pop.gmail.com", + "PopPort": "995", + "MailLogin": "tempfortrip22@gmail.com", + "MailPassword": "gbyb vdkr qeux xrol" } diff --git a/GiftShop/GiftShopView/App.config b/GiftShop/GiftShopView/App.config new file mode 100644 index 0000000..8e35ec5 --- /dev/null +++ b/GiftShop/GiftShopView/App.config @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/GiftShop/GiftShopView/FormCreateOrder.Designer.cs b/GiftShop/GiftShopView/FormCreateOrder.Designer.cs index cc20d94..43ad6fc 100644 --- a/GiftShop/GiftShopView/FormCreateOrder.Designer.cs +++ b/GiftShop/GiftShopView/FormCreateOrder.Designer.cs @@ -1,145 +1,169 @@ namespace GiftShopView { - partial class FormCreateOrder - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; + partial class FormCreateOrder + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } - #region Windows Form Designer generated code + #region Windows Form Designer generated code - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - labelGift = new Label(); - labelCount = new Label(); - labelSum = new Label(); - comboBoxGift = new ComboBox(); - textBoxCount = new TextBox(); - textBoxSum = new TextBox(); - buttonSave = new Button(); - buttonCancel = new Button(); - SuspendLayout(); - // - // labelGift - // - labelGift.AutoSize = true; - labelGift.Location = new Point(34, 44); - labelGift.Name = "labelGift"; - labelGift.Size = new Size(71, 20); - labelGift.TabIndex = 0; - labelGift.Text = "Изделие:"; - // - // labelCount - // - labelCount.AutoSize = true; - labelCount.Location = new Point(34, 112); - labelCount.Name = "labelCount"; - labelCount.Size = new Size(93, 20); - labelCount.TabIndex = 1; - labelCount.Text = "Количество:"; - // - // labelSum - // - labelSum.AutoSize = true; - labelSum.Location = new Point(34, 171); - labelSum.Name = "labelSum"; - labelSum.Size = new Size(58, 20); - labelSum.TabIndex = 2; - labelSum.Text = "Сумма:"; - // - // comboBoxGift - // - comboBoxGift.DropDownStyle = ComboBoxStyle.DropDownList; - comboBoxGift.FormattingEnabled = true; - comboBoxGift.Location = new Point(141, 41); - comboBoxGift.Name = "comboBoxGift"; - comboBoxGift.Size = new Size(369, 28); - comboBoxGift.TabIndex = 3; - comboBoxGift.SelectedIndexChanged += ComboBoxGift_SelectedIndexChanged; - // - // textBoxCount - // - textBoxCount.Location = new Point(141, 109); - textBoxCount.Name = "textBoxCount"; - textBoxCount.Size = new Size(369, 27); - textBoxCount.TabIndex = 4; - textBoxCount.TextChanged += TextBoxCount_TextChanged; - // - // textBoxSum - // - textBoxSum.Location = new Point(141, 171); - textBoxSum.Name = "textBoxSum"; - textBoxSum.ReadOnly = true; - textBoxSum.Size = new Size(369, 27); - textBoxSum.TabIndex = 5; - // - // buttonSave - // - buttonSave.Location = new Point(197, 245); - buttonSave.Name = "buttonSave"; - buttonSave.Size = new Size(144, 45); - buttonSave.TabIndex = 6; - buttonSave.Text = "Сохранить"; - buttonSave.UseVisualStyleBackColor = true; - buttonSave.Click += ButtonSave_Click; - // - // buttonCancel - // - buttonCancel.Location = new Point(384, 245); - buttonCancel.Name = "buttonCancel"; - buttonCancel.Size = new Size(126, 45); - buttonCancel.TabIndex = 7; - buttonCancel.Text = "Отмена"; - buttonCancel.UseVisualStyleBackColor = true; - buttonCancel.Click += ButtonCancel_Click; - // - // FormCreateOrder - // - AutoScaleDimensions = new SizeF(8F, 20F); - AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(539, 308); - Controls.Add(buttonCancel); - Controls.Add(buttonSave); - Controls.Add(textBoxSum); - Controls.Add(textBoxCount); - Controls.Add(comboBoxGift); - Controls.Add(labelSum); - Controls.Add(labelCount); - Controls.Add(labelGift); - Name = "FormCreateOrder"; - Text = "Заказ"; - Load += FormCreateOrder_Load; - ResumeLayout(false); - PerformLayout(); - } + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + labelGift = new Label(); + labelCount = new Label(); + labelSum = new Label(); + comboBoxGift = new ComboBox(); + textBoxCount = new TextBox(); + textBoxSum = new TextBox(); + buttonSave = new Button(); + buttonCancel = new Button(); + labelClient = new Label(); + comboBoxClient = new ComboBox(); + SuspendLayout(); + // + // labelGift + // + labelGift.AutoSize = true; + labelGift.Location = new Point(34, 44); + labelGift.Name = "labelGift"; + labelGift.Size = new Size(71, 20); + labelGift.TabIndex = 0; + labelGift.Text = "Изделие:"; + // + // labelCount + // + labelCount.AutoSize = true; + labelCount.Location = new Point(34, 138); + labelCount.Name = "labelCount"; + labelCount.Size = new Size(93, 20); + labelCount.TabIndex = 1; + labelCount.Text = "Количество:"; + // + // labelSum + // + labelSum.AutoSize = true; + labelSum.Location = new Point(34, 187); + labelSum.Name = "labelSum"; + labelSum.Size = new Size(58, 20); + labelSum.TabIndex = 2; + labelSum.Text = "Сумма:"; + // + // comboBoxGift + // + comboBoxGift.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxGift.FormattingEnabled = true; + comboBoxGift.Location = new Point(141, 41); + comboBoxGift.Name = "comboBoxGift"; + comboBoxGift.Size = new Size(369, 28); + comboBoxGift.TabIndex = 3; + comboBoxGift.SelectedIndexChanged += ComboBoxGift_SelectedIndexChanged; + // + // textBoxCount + // + textBoxCount.Location = new Point(141, 135); + textBoxCount.Name = "textBoxCount"; + textBoxCount.Size = new Size(369, 27); + textBoxCount.TabIndex = 4; + textBoxCount.TextChanged += TextBoxCount_TextChanged; + // + // textBoxSum + // + textBoxSum.Location = new Point(141, 187); + textBoxSum.Name = "textBoxSum"; + textBoxSum.ReadOnly = true; + textBoxSum.Size = new Size(369, 27); + textBoxSum.TabIndex = 5; + // + // buttonSave + // + buttonSave.Location = new Point(197, 245); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(144, 45); + buttonSave.TabIndex = 6; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += ButtonSave_Click; + // + // buttonCancel + // + buttonCancel.Location = new Point(384, 245); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(126, 45); + buttonCancel.TabIndex = 7; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += ButtonCancel_Click; + // + // labelClient + // + labelClient.AutoSize = true; + labelClient.Location = new Point(34, 92); + labelClient.Name = "labelClient"; + labelClient.Size = new Size(61, 20); + labelClient.TabIndex = 8; + labelClient.Text = "Клиент:"; + // + // comboBoxClient + // + comboBoxClient.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxClient.FormattingEnabled = true; + comboBoxClient.Location = new Point(141, 89); + comboBoxClient.Name = "comboBoxClient"; + comboBoxClient.Size = new Size(369, 28); + comboBoxClient.TabIndex = 9; + // + // FormCreateOrder + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(539, 308); + Controls.Add(comboBoxClient); + Controls.Add(labelClient); + Controls.Add(buttonCancel); + Controls.Add(buttonSave); + Controls.Add(textBoxSum); + Controls.Add(textBoxCount); + Controls.Add(comboBoxGift); + Controls.Add(labelSum); + Controls.Add(labelCount); + Controls.Add(labelGift); + Name = "FormCreateOrder"; + Text = "Заказ"; + Load += FormCreateOrder_Load; + ResumeLayout(false); + PerformLayout(); + } - #endregion + #endregion - private Label labelGift; - private Label labelCount; - private Label labelSum; - private ComboBox comboBoxGift; - private TextBox textBoxCount; - private TextBox textBoxSum; - private Button buttonSave; - private Button buttonCancel; - } + private Label labelGift; + private Label labelCount; + private Label labelSum; + private ComboBox comboBoxGift; + private TextBox textBoxCount; + private TextBox textBoxSum; + private Button buttonSave; + private Button buttonCancel; + private Label labelClient; + private ComboBox comboBoxClient; + } } \ No newline at end of file diff --git a/GiftShop/GiftShopView/FormCreateOrder.cs b/GiftShop/GiftShopView/FormCreateOrder.cs index 6a7e005..da070f5 100644 --- a/GiftShop/GiftShopView/FormCreateOrder.cs +++ b/GiftShop/GiftShopView/FormCreateOrder.cs @@ -5,123 +5,145 @@ using Microsoft.Extensions.Logging; namespace GiftShopView { - public partial class FormCreateOrder : Form - { - private readonly ILogger _logger; + public partial class FormCreateOrder : Form + { + private readonly ILogger _logger; - private readonly IGiftLogic _logicP; + private readonly IGiftLogic _logicP; - private readonly IOrderLogic _logicO; + private readonly IOrderLogic _logicO; - public FormCreateOrder(ILogger logger, IGiftLogic logicP, IOrderLogic logicO) - { - InitializeComponent(); - _logger = logger; - _logicP = logicP; - _logicO = logicO; - } + private readonly IClientLogic _logicC; - private void FormCreateOrder_Load(object sender, EventArgs e) - { - _logger.LogInformation("Загрузка изделий для заказа"); - LoadData(); - } + public FormCreateOrder(ILogger logger, IGiftLogic logicP, IOrderLogic logicO, IClientLogic logicC) + { + InitializeComponent(); + _logger = logger; + _logicP = logicP; + _logicO = logicO; + _logicC = logicC; + } - private void LoadData() - { - _logger.LogInformation("Загрузка изделий для заказа"); - try - { - var list = _logicP.ReadList(null); - if (list != null) - { - comboBoxGift.DisplayMember = "GiftName"; - comboBoxGift.ValueMember = "ID"; - comboBoxGift.DataSource = list; - comboBoxGift.SelectedItem = null; - } - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки списка изделий"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } + private void FormCreateOrder_Load(object sender, EventArgs e) + { + _logger.LogInformation("Загрузка изделий для заказа"); + LoadData(); + } - private void CalcSum() - { - if (comboBoxGift.SelectedValue != null && !string.IsNullOrEmpty(textBoxCount.Text)) - { - try - { - int id = Convert.ToInt32(comboBoxGift.SelectedValue); - var product = _logicP.ReadElement(new GiftSearchModel - { - Id = id - }); - int count = Convert.ToInt32(textBoxCount.Text); - textBoxSum.Text = Math.Round(count * (product?.Price ?? 0), 2).ToString(); - _logger.LogInformation("Расчет суммы заказа"); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка расчета суммы заказа"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } + private void LoadData() + { + _logger.LogInformation("Загрузка изделий для заказа"); + try + { + var list = _logicP.ReadList(null); + if (list != null) + { + comboBoxGift.DisplayMember = "GiftName"; + comboBoxGift.ValueMember = "ID"; + comboBoxGift.DataSource = list; + comboBoxGift.SelectedItem = null; + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки списка изделий"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + _logger.LogInformation("Загрузка клиентов для заказа"); + try + { + var list = _logicC.ReadList(null); + if (list != null) + { + comboBoxClient.DisplayMember = "Клиент"; + comboBoxClient.ValueMember = "Id"; + comboBoxClient.DataSource = list.Select(c => c.ClientFIO).ToList(); + comboBoxClient.SelectedItem = null; + } - private void TextBoxCount_TextChanged(object sender, EventArgs e) - { - CalcSum(); - } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки списка клиентов"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } - private void ComboBoxGift_SelectedIndexChanged(object sender, EventArgs e) - { - CalcSum(); - } + private void CalcSum() + { + if (comboBoxGift.SelectedValue != null && !string.IsNullOrEmpty(textBoxCount.Text)) + { + try + { + int id = Convert.ToInt32(comboBoxGift.SelectedValue); + var product = _logicP.ReadElement(new GiftSearchModel + { + Id = id + }); + int count = Convert.ToInt32(textBoxCount.Text); + textBoxSum.Text = Math.Round(count * (product?.Price ?? 0), 2).ToString(); + _logger.LogInformation("Расчет суммы заказа"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка расчета суммы заказа"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } - private void ButtonSave_Click(object sender, EventArgs e) - { - if (string.IsNullOrEmpty(textBoxCount.Text)) - { - MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } - if (comboBoxGift.SelectedValue == null) - { - MessageBox.Show("Выберите изделие", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } - _logger.LogInformation("Создание заказа"); - try - { - var operationResult = _logicO.CreateOrder(new OrderBindingModel - { - GiftId = Convert.ToInt32(comboBoxGift.SelectedValue), - GiftName = comboBoxGift.Text, - Count = Convert.ToInt32(textBoxCount.Text), - Sum = Convert.ToDouble(textBoxSum.Text) - }); - if (!operationResult) - { - throw new Exception("Ошибка при создании заказа. Дополнительная информация в логах."); - } - MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); - DialogResult = DialogResult.OK; - Close(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка создания заказа"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } + private void TextBoxCount_TextChanged(object sender, EventArgs e) + { + CalcSum(); + } - private void ButtonCancel_Click(object sender, EventArgs e) - { - DialogResult = DialogResult.Cancel; - Close(); - } - } + private void ComboBoxGift_SelectedIndexChanged(object sender, EventArgs e) + { + CalcSum(); + } + + private void ButtonSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxCount.Text)) + { + MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (comboBoxGift.SelectedValue == null) + { + MessageBox.Show("Выберите изделие", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Создание заказа"); + try + { + var operationResult = _logicO.CreateOrder(new OrderBindingModel + { + GiftId = Convert.ToInt32(comboBoxGift.SelectedValue), + GiftName = comboBoxGift.Text, + ClientId = Convert.ToInt32(comboBoxClient.SelectedIndex), + Count = Convert.ToInt32(textBoxCount.Text), + Sum = Convert.ToDouble(textBoxSum.Text) + }); + if (!operationResult) + { + throw new Exception("Ошибка при создании заказа. Дополнительная информация в логах."); + } + MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + Close(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка создания заказа"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ButtonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } } diff --git a/GiftShop/GiftShopView/FormMails.Designer.cs b/GiftShop/GiftShopView/FormMails.Designer.cs new file mode 100644 index 0000000..cf09ad3 --- /dev/null +++ b/GiftShop/GiftShopView/FormMails.Designer.cs @@ -0,0 +1,64 @@ +namespace GiftShopView +{ + partial class FormMails + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + dataGridView = new DataGridView(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // dataGridView + // + dataGridView.BackgroundColor = SystemColors.ControlLightLight; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Dock = DockStyle.Fill; + dataGridView.Location = new Point(0, 0); + dataGridView.Name = "dataGridView"; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 29; + dataGridView.Size = new Size(800, 450); + dataGridView.TabIndex = 0; + // + // FormMails + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(800, 450); + Controls.Add(dataGridView); + Name = "FormMails"; + Text = "Письма"; + Load += FormMails_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView; + } +} \ No newline at end of file diff --git a/GiftShop/GiftShopView/FormMails.cs b/GiftShop/GiftShopView/FormMails.cs new file mode 100644 index 0000000..9c7a2e8 --- /dev/null +++ b/GiftShop/GiftShopView/FormMails.cs @@ -0,0 +1,46 @@ +using Microsoft.Extensions.Logging; +using GiftShopContracts.BusinessLogicsContracts; + +namespace GiftShopView +{ + 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 LoadData() + { + try + { + var list = _logic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["MessageId"].Visible = false; + dataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + _logger.LogInformation("Загрузка писем"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки писем"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + + private void FormMails_Load(object sender, EventArgs e) + { + LoadData(); + } + } +} + diff --git a/GiftShop/GiftShopView/FormMails.resx b/GiftShop/GiftShopView/FormMails.resx new file mode 100644 index 0000000..f298a7b --- /dev/null +++ b/GiftShop/GiftShopView/FormMails.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/GiftShop/GiftShopView/FormMain.Designer.cs b/GiftShop/GiftShopView/FormMain.Designer.cs index 273bc6d..a874af5 100644 --- a/GiftShop/GiftShopView/FormMain.Designer.cs +++ b/GiftShop/GiftShopView/FormMain.Designer.cs @@ -20,184 +20,186 @@ base.Dispose(disposing); } - #region Windows Form Designer generated code + #region Windows Form Designer generated code - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - menuStrip = new MenuStrip(); - справочникиToolStripMenuItem = new ToolStripMenuItem(); - компонентыToolStripMenuItem = new ToolStripMenuItem(); - изделияToolStripMenuItem = new ToolStripMenuItem(); - клиентыToolStripMenuItem = new ToolStripMenuItem(); - исполнителиToolStripMenuItem = new ToolStripMenuItem(); - отчётыToolStripMenuItem = new ToolStripMenuItem(); - списокКомпонентовToolStripMenuItem = new ToolStripMenuItem(); - компонентыПоИзделиямToolStripMenuItem = new ToolStripMenuItem(); - списокЗаказовToolStripMenuItem = new ToolStripMenuItem(); - запускРаботToolStripMenuItem = new ToolStripMenuItem(); - dataGridView = new DataGridView(); - buttonCreateOrder = new Button(); - buttonIssuedOrder = new Button(); - buttonRef = new Button(); - menuStrip.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); - SuspendLayout(); - // - // menuStrip - // - menuStrip.ImageScalingSize = new Size(20, 20); - menuStrip.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчётыToolStripMenuItem, запускРаботToolStripMenuItem }); - menuStrip.Location = new Point(0, 0); - menuStrip.Name = "menuStrip"; - menuStrip.Padding = new Padding(8, 2, 0, 2); - menuStrip.Size = new Size(1709, 33); - menuStrip.TabIndex = 0; - menuStrip.Text = "menuStrip1"; - // - // справочникиToolStripMenuItem - // - справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, изделияToolStripMenuItem, клиентыToolStripMenuItem, исполнителиToolStripMenuItem }); - справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; - справочникиToolStripMenuItem.Size = new Size(139, 29); - справочникиToolStripMenuItem.Text = "Справочники"; - // - // компонентыToolStripMenuItem - // - компонентыToolStripMenuItem.Name = "компонентыToolStripMenuItem"; - компонентыToolStripMenuItem.Size = new Size(220, 34); - компонентыToolStripMenuItem.Text = "Компоненты"; - компонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click; - // - // изделияToolStripMenuItem - // - изделияToolStripMenuItem.Name = "изделияToolStripMenuItem"; - изделияToolStripMenuItem.Size = new Size(220, 34); - изделияToolStripMenuItem.Text = "Изделия"; - изделияToolStripMenuItem.Click += ИзделияToolStripMenuItem_Click; - // - // клиентыToolStripMenuItem - // - клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; - клиентыToolStripMenuItem.Size = new Size(220, 34); - клиентыToolStripMenuItem.Text = "Клиенты"; - клиентыToolStripMenuItem.Click += ClientsToolStripMenuItem_Click; - // - // исполнителиToolStripMenuItem - // - исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; - исполнителиToolStripMenuItem.Size = new Size(220, 34); - исполнителиToolStripMenuItem.Text = "Исполнители"; - исполнителиToolStripMenuItem.Click += исполнителиToolStripMenuItem_Click; - // - // отчётыToolStripMenuItem - // - отчётыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокКомпонентовToolStripMenuItem, компонентыПоИзделиямToolStripMenuItem, списокЗаказовToolStripMenuItem }); - отчётыToolStripMenuItem.Name = "отчётыToolStripMenuItem"; - отчётыToolStripMenuItem.Size = new Size(88, 29); - отчётыToolStripMenuItem.Text = "Отчёты"; - // - // списокКомпонентовToolStripMenuItem - // - списокКомпонентовToolStripMenuItem.Name = "списокКомпонентовToolStripMenuItem"; - списокКомпонентовToolStripMenuItem.Size = new Size(327, 34); - списокКомпонентовToolStripMenuItem.Text = "Список компонентов"; - списокКомпонентовToolStripMenuItem.Click += ComponentsToolStripMenuItem_Click; - // - // компонентыПоИзделиямToolStripMenuItem - // - компонентыПоИзделиямToolStripMenuItem.Name = "компонентыПоИзделиямToolStripMenuItem"; - компонентыПоИзделиямToolStripMenuItem.Size = new Size(327, 34); - компонентыПоИзделиямToolStripMenuItem.Text = "Компоненты по изделиям"; - компонентыПоИзделиямToolStripMenuItem.Click += ComponentGiftsToolStripMenuItem_Click; - // - // списокЗаказовToolStripMenuItem - // - списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem"; - списокЗаказовToolStripMenuItem.Size = new Size(327, 34); - списокЗаказовToolStripMenuItem.Text = "Список заказов"; - списокЗаказовToolStripMenuItem.Click += OrdersToolStripMenuItem_Click; - // - // запускРаботToolStripMenuItem - // - запускРаботToolStripMenuItem.Name = "запускРаботToolStripMenuItem"; - запускРаботToolStripMenuItem.Size = new Size(136, 29); - запускРаботToolStripMenuItem.Text = "Запуск работ"; - запускРаботToolStripMenuItem.Click += запускРаботToolStripMenuItem_Click; - // - // dataGridView - // - dataGridView.BackgroundColor = SystemColors.ControlLightLight; - dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; - dataGridView.Location = new Point(15, 51); - dataGridView.Margin = new Padding(4, 4, 4, 4); - dataGridView.Name = "dataGridView"; - dataGridView.RowHeadersWidth = 51; - dataGridView.RowTemplate.Height = 29; - dataGridView.Size = new Size(1404, 529); - dataGridView.TabIndex = 1; - // - // buttonCreateOrder - // - buttonCreateOrder.Location = new Point(1444, 112); - buttonCreateOrder.Margin = new Padding(4, 4, 4, 4); - buttonCreateOrder.Name = "buttonCreateOrder"; - buttonCreateOrder.Size = new Size(236, 71); - buttonCreateOrder.TabIndex = 2; - buttonCreateOrder.Text = "Создать заказ"; - buttonCreateOrder.UseVisualStyleBackColor = true; - buttonCreateOrder.Click += ButtonCreateOrder_Click; - // - // buttonIssuedOrder - // - buttonIssuedOrder.Location = new Point(1444, 285); - buttonIssuedOrder.Margin = new Padding(4, 4, 4, 4); - buttonIssuedOrder.Name = "buttonIssuedOrder"; - buttonIssuedOrder.Size = new Size(236, 71); - buttonIssuedOrder.TabIndex = 5; - buttonIssuedOrder.Text = "Заказ выдан"; - buttonIssuedOrder.UseVisualStyleBackColor = true; - buttonIssuedOrder.Click += ButtonIssuedOrder_Click; - // - // buttonRef - // - buttonRef.Location = new Point(1444, 445); - buttonRef.Margin = new Padding(4, 4, 4, 4); - buttonRef.Name = "buttonRef"; - buttonRef.Size = new Size(236, 71); - buttonRef.TabIndex = 6; - buttonRef.Text = "Обновить список"; - buttonRef.UseVisualStyleBackColor = true; - buttonRef.Click += ButtonRef_Click; - // - // FormMain - // - AutoScaleDimensions = new SizeF(10F, 25F); - AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1709, 589); - Controls.Add(buttonRef); - Controls.Add(buttonIssuedOrder); - Controls.Add(buttonCreateOrder); - Controls.Add(dataGridView); - Controls.Add(menuStrip); - MainMenuStrip = menuStrip; - Margin = new Padding(4, 4, 4, 4); - Name = "FormMain"; - Text = "Магазин подарков"; - Load += FormMain_Load; - menuStrip.ResumeLayout(false); - menuStrip.PerformLayout(); - ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); - ResumeLayout(false); - PerformLayout(); - } + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + menuStrip = new MenuStrip(); + справочникиToolStripMenuItem = new ToolStripMenuItem(); + компонентыToolStripMenuItem = new ToolStripMenuItem(); + изделияToolStripMenuItem = new ToolStripMenuItem(); + клиентыToolStripMenuItem = new ToolStripMenuItem(); + исполнителиToolStripMenuItem = new ToolStripMenuItem(); + отчётыToolStripMenuItem = new ToolStripMenuItem(); + списокКомпонентовToolStripMenuItem = new ToolStripMenuItem(); + компонентыПоИзделиямToolStripMenuItem = new ToolStripMenuItem(); + списокЗаказовToolStripMenuItem = new ToolStripMenuItem(); + запускРаботToolStripMenuItem = new ToolStripMenuItem(); + dataGridView = new DataGridView(); + buttonCreateOrder = new Button(); + buttonIssuedOrder = new Button(); + buttonRef = new Button(); + письмаToolStripMenuItem = new ToolStripMenuItem(); + menuStrip.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // menuStrip + // + menuStrip.ImageScalingSize = new Size(20, 20); + menuStrip.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчётыToolStripMenuItem, запускРаботToolStripMenuItem, письмаToolStripMenuItem }); + menuStrip.Location = new Point(0, 0); + menuStrip.Name = "menuStrip"; + menuStrip.Size = new Size(1367, 28); + menuStrip.TabIndex = 0; + menuStrip.Text = "menuStrip1"; + // + // справочникиToolStripMenuItem + // + справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, изделияToolStripMenuItem, клиентыToolStripMenuItem, исполнителиToolStripMenuItem }); + справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; + справочникиToolStripMenuItem.Size = new Size(117, 24); + справочникиToolStripMenuItem.Text = "Справочники"; + // + // компонентыToolStripMenuItem + // + компонентыToolStripMenuItem.Name = "компонентыToolStripMenuItem"; + компонентыToolStripMenuItem.Size = new Size(185, 26); + компонентыToolStripMenuItem.Text = "Компоненты"; + компонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click; + // + // изделияToolStripMenuItem + // + изделияToolStripMenuItem.Name = "изделияToolStripMenuItem"; + изделияToolStripMenuItem.Size = new Size(185, 26); + изделияToolStripMenuItem.Text = "Изделия"; + изделияToolStripMenuItem.Click += ИзделияToolStripMenuItem_Click; + // + // клиентыToolStripMenuItem + // + клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; + клиентыToolStripMenuItem.Size = new Size(185, 26); + клиентыToolStripMenuItem.Text = "Клиенты"; + клиентыToolStripMenuItem.Click += ClientsToolStripMenuItem_Click; + // + // исполнителиToolStripMenuItem + // + исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; + исполнителиToolStripMenuItem.Size = new Size(185, 26); + исполнителиToolStripMenuItem.Text = "Исполнители"; + исполнителиToolStripMenuItem.Click += исполнителиToolStripMenuItem_Click; + // + // отчётыToolStripMenuItem + // + отчётыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокКомпонентовToolStripMenuItem, компонентыПоИзделиямToolStripMenuItem, списокЗаказовToolStripMenuItem }); + отчётыToolStripMenuItem.Name = "отчётыToolStripMenuItem"; + отчётыToolStripMenuItem.Size = new Size(73, 24); + отчётыToolStripMenuItem.Text = "Отчёты"; + // + // списокКомпонентовToolStripMenuItem + // + списокКомпонентовToolStripMenuItem.Name = "списокКомпонентовToolStripMenuItem"; + списокКомпонентовToolStripMenuItem.Size = new Size(276, 26); + списокКомпонентовToolStripMenuItem.Text = "Список компонентов"; + списокКомпонентовToolStripMenuItem.Click += ComponentsToolStripMenuItem_Click; + // + // компонентыПоИзделиямToolStripMenuItem + // + компонентыПоИзделиямToolStripMenuItem.Name = "компонентыПоИзделиямToolStripMenuItem"; + компонентыПоИзделиямToolStripMenuItem.Size = new Size(276, 26); + компонентыПоИзделиямToolStripMenuItem.Text = "Компоненты по изделиям"; + компонентыПоИзделиямToolStripMenuItem.Click += ComponentGiftsToolStripMenuItem_Click; + // + // списокЗаказовToolStripMenuItem + // + списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem"; + списокЗаказовToolStripMenuItem.Size = new Size(276, 26); + списокЗаказовToolStripMenuItem.Text = "Список заказов"; + списокЗаказовToolStripMenuItem.Click += OrdersToolStripMenuItem_Click; + // + // запускРаботToolStripMenuItem + // + запускРаботToolStripMenuItem.Name = "запускРаботToolStripMenuItem"; + запускРаботToolStripMenuItem.Size = new Size(114, 24); + запускРаботToolStripMenuItem.Text = "Запуск работ"; + запускРаботToolStripMenuItem.Click += запускРаботToolStripMenuItem_Click; + // + // dataGridView + // + dataGridView.BackgroundColor = SystemColors.ControlLightLight; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(12, 41); + dataGridView.Name = "dataGridView"; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 29; + dataGridView.Size = new Size(1123, 423); + dataGridView.TabIndex = 1; + // + // buttonCreateOrder + // + buttonCreateOrder.Location = new Point(1155, 90); + buttonCreateOrder.Name = "buttonCreateOrder"; + buttonCreateOrder.Size = new Size(189, 57); + buttonCreateOrder.TabIndex = 2; + buttonCreateOrder.Text = "Создать заказ"; + buttonCreateOrder.UseVisualStyleBackColor = true; + buttonCreateOrder.Click += ButtonCreateOrder_Click; + // + // buttonIssuedOrder + // + buttonIssuedOrder.Location = new Point(1155, 228); + buttonIssuedOrder.Name = "buttonIssuedOrder"; + buttonIssuedOrder.Size = new Size(189, 57); + buttonIssuedOrder.TabIndex = 5; + buttonIssuedOrder.Text = "Заказ выдан"; + buttonIssuedOrder.UseVisualStyleBackColor = true; + buttonIssuedOrder.Click += ButtonIssuedOrder_Click; + // + // buttonRef + // + buttonRef.Location = new Point(1155, 356); + buttonRef.Name = "buttonRef"; + buttonRef.Size = new Size(189, 57); + buttonRef.TabIndex = 6; + buttonRef.Text = "Обновить список"; + buttonRef.UseVisualStyleBackColor = true; + buttonRef.Click += ButtonRef_Click; + // + // письмаToolStripMenuItem + // + письмаToolStripMenuItem.Name = "письмаToolStripMenuItem"; + письмаToolStripMenuItem.Size = new Size(77, 24); + письмаToolStripMenuItem.Text = "Письма"; + письмаToolStripMenuItem.Click += письмаToolStripMenuItem_Click; + // + // FormMain + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(1367, 471); + Controls.Add(buttonRef); + Controls.Add(buttonIssuedOrder); + Controls.Add(buttonCreateOrder); + Controls.Add(dataGridView); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; + Name = "FormMain"; + Text = "Магазин подарков"; + Load += FormMain_Load; + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + PerformLayout(); + } - #endregion + #endregion - private MenuStrip menuStrip; + private MenuStrip menuStrip; private ToolStripMenuItem справочникиToolStripMenuItem; private ToolStripMenuItem компонентыToolStripMenuItem; private ToolStripMenuItem изделияToolStripMenuItem; @@ -212,5 +214,6 @@ private ToolStripMenuItem клиентыToolStripMenuItem; private ToolStripMenuItem исполнителиToolStripMenuItem; private ToolStripMenuItem запускРаботToolStripMenuItem; + private ToolStripMenuItem письмаToolStripMenuItem; } } \ No newline at end of file diff --git a/GiftShop/GiftShopView/FormMain.cs b/GiftShop/GiftShopView/FormMain.cs index afe2dd6..102e778 100644 --- a/GiftShop/GiftShopView/FormMain.cs +++ b/GiftShop/GiftShopView/FormMain.cs @@ -177,5 +177,14 @@ namespace GiftShopView .GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic); MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); } + + private void письмаToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormMails)); + if (service is FormMails form) + { + form.ShowDialog(); + } + } } } diff --git a/GiftShop/GiftShopView/FormMain.resx b/GiftShop/GiftShopView/FormMain.resx index 3ef7151..1263609 100644 --- a/GiftShop/GiftShopView/FormMain.resx +++ b/GiftShop/GiftShopView/FormMain.resx @@ -1,64 +1,4 @@ - - - + @@ -121,6 +61,6 @@ 17, 17 - 137 + 26 \ No newline at end of file diff --git a/GiftShop/GiftShopView/GiftShopView.csproj b/GiftShop/GiftShopView/GiftShopView.csproj index e75c4c7..7cb39ed 100644 --- a/GiftShop/GiftShopView/GiftShopView.csproj +++ b/GiftShop/GiftShopView/GiftShopView.csproj @@ -19,6 +19,7 @@ + all runtime; build; native; contentfiles; analyzers; buildtransitive @@ -39,6 +40,9 @@ + + Always + Always diff --git a/GiftShop/GiftShopView/Program.cs b/GiftShop/GiftShopView/Program.cs index e0e9df3..504be58 100644 --- a/GiftShop/GiftShopView/Program.cs +++ b/GiftShop/GiftShopView/Program.cs @@ -7,6 +7,8 @@ using GiftShopDatabaseImplement.Implements; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; +using GiftShopBusinessLogic.MailWorker; +using GiftShopContracts.BindingModels; namespace GiftShopView { @@ -21,7 +23,27 @@ namespace GiftShopView 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) @@ -35,19 +57,24 @@ namespace GiftShopView 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.AddTransient(); + services.AddTransient(); + services.AddTransient(); + + services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddSingleton(); - services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -57,8 +84,11 @@ namespace GiftShopView services.AddTransient(); services.AddTransient(); services.AddTransient(); - 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 -- 2.25.1