From 9fc3ff82e222f75e51446c2bc984b0043ac12e5f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=B0=D0=BA=D1=81=D0=B8=D0=BC=20=D0=A1=D0=B5=D1=80?= =?UTF-8?q?=D0=B3=D1=83=D0=BD=D0=BE=D0=B2?= Date: Mon, 15 May 2023 08:33:19 +0400 Subject: [PATCH 1/4] some fix --- .../BusinessLogics/ClientLogic.cs | 222 +++++++------ .../BusinessLogics/MessageInfoLogic.cs | 50 +++ .../BusinessLogics/OrderLogic.cs | 29 +- .../GiftShopBusinessLogic.csproj | 1 + .../MailWorker/AbstractMailWorker.cs | 95 ++++++ .../MailWorker/MailKitWorker.cs | 78 +++++ .../Controllers/HomeController.cs | 10 + .../GiftShopClientApp.csproj | 16 + .../GiftShopClientApp/Views/Home/Mails.cshtml | 53 ++++ .../Views/Shared/_Layout.cshtml | 3 + .../BindingModels/MailConfigBindingModel.cs | 17 + .../BindingModels/MailSendInfoBindingModel.cs | 11 + .../BindingModels/MessageInfoBindingModel.cs | 19 ++ .../IMessageInfoLogic.cs | 13 + .../SearchModels/MessageInfoSearchModel.cs | 9 + .../StoragesContracts/IMessageInfoStorage.cs | 17 + .../ViewModels/MessageInfoViewModel.cs | 24 ++ .../Models/IMessageInfoModel.cs | 17 + .../GiftShopDatabase.cs | 2 + .../Implements/MessageInfoStorage.cs | 55 ++++ .../20230514155217_ThirdMigration.Designer.cs | 300 ++++++++++++++++++ .../20230514155217_ThirdMigration.cs | 48 +++ .../GiftShopDatabaseModelSnapshot.cs | 39 +++ .../Models/Message.cs | 51 +++ .../DataFileSingleton.cs | 8 + .../Implements/MessageInfoStorage.cs | 53 ++++ .../GiftShopFileImplement/Models/Message.cs | 74 +++++ .../DataListSingleton.cs | 2 + .../Implements/MessageInfoStorage.cs | 70 ++++ .../GiftShopListImplement/Models/Message.cs | 48 +++ .../Controllers/ClientController.cs | 26 +- GiftShop/GiftShopRestApi/Program.cs | 17 + GiftShop/GiftShopRestApi/appsettings.json | 8 +- GiftShop/GiftShopView/App.config | 11 + GiftShop/GiftShopView/FormMails.Designer.cs | 64 ++++ GiftShop/GiftShopView/FormMails.cs | 41 +++ GiftShop/GiftShopView/FormMails.resx | 60 ++++ GiftShop/GiftShopView/FormMain.Designer.cs | 23 +- GiftShop/GiftShopView/FormMain.cs | 9 + GiftShop/GiftShopView/GiftShopView.csproj | 3 + GiftShop/GiftShopView/Program.cs | 34 +- 41 files changed, 1601 insertions(+), 129 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/20230514155217_ThirdMigration.Designer.cs create mode 100644 GiftShop/GiftShopDatabaseImplement/Migrations/20230514155217_ThirdMigration.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..ad39386 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}. Id:{ Id}", model.ClientFIO, 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:{ClientFIO}. Id:{Id}", model?.ClientFIO, 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.Email)); + } + if (!Regex.IsMatch(model.Email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$")) + { + 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..4d3e540 --- /dev/null +++ b/GiftShop/GiftShopBusinessLogic/BusinessLogics/MessageInfoLogic.cs @@ -0,0 +1,50 @@ +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 IMessageInfoStorage _messageStorage; + + public MessageInfoLogic(ILogger logger, IMessageInfoStorage messageStorage) + { + _logger = logger; + _messageStorage = messageStorage; + } + + public bool Create(MessageInfoBindingModel 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; + } + } +} diff --git a/GiftShop/GiftShopBusinessLogic/BusinessLogics/OrderLogic.cs b/GiftShop/GiftShopBusinessLogic/BusinessLogics/OrderLogic.cs index 997f9d2..77d972f 100644 --- a/GiftShop/GiftShopBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/GiftShop/GiftShopBusinessLogic/BusinessLogics/OrderLogic.cs @@ -1,4 +1,5 @@ -using GiftShopContracts.BindingModels; +using GiftShopBusinessLogic.MailWorker; +using GiftShopContracts.BindingModels; using GiftShopContracts.BusinessLogicsContracts; using GiftShopContracts.SearchModels; using GiftShopContracts.StoragesContracts; @@ -14,11 +15,17 @@ namespace GiftShopBusinessLogic.BusinessLogics private readonly IOrderStorage _orderStorage; - public OrderLogic(ILogger logger, IOrderStorage orderStorage) + private readonly AbstractMailWorker _mailWorker; + + private readonly IClientLogic _clientLogic; + + public OrderLogic(ILogger logger, IOrderStorage orderStorage, AbstractMailWorker mailWorker, IClientLogic clientLogic) { _logger = logger; _orderStorage = orderStorage; - } + _mailWorker = mailWorker; + _clientLogic = clientLogic; + } public bool CreateOrder(OrderBindingModel model) { @@ -166,5 +173,21 @@ namespace GiftShopBusinessLogic.BusinessLogics 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..4caa566 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..9686a26 --- /dev/null +++ b/GiftShop/GiftShopBusinessLogic/MailWorker/AbstractMailWorker.cs @@ -0,0 +1,95 @@ +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..38a96f6 --- /dev/null +++ b/GiftShop/GiftShopBusinessLogic/MailWorker/MailKitWorker.cs @@ -0,0 +1,78 @@ +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.TextBody + }); + } + } + } + catch (AuthenticationException) + { } + finally + { + client.Disconnect(true); + } + }); + return list; + } + } +} diff --git a/GiftShop/GiftShopClientApp/Controllers/HomeController.cs b/GiftShop/GiftShopClientApp/Controllers/HomeController.cs index 35afa87..8cdf0a8 100644 --- a/GiftShop/GiftShopClientApp/Controllers/HomeController.cs +++ b/GiftShop/GiftShopClientApp/Controllers/HomeController.cs @@ -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..56b2979 100644 --- a/GiftShop/GiftShopClientApp/GiftShopClientApp.csproj +++ b/GiftShop/GiftShopClientApp/GiftShopClientApp.csproj @@ -6,6 +6,10 @@ enable + + + + @@ -14,4 +18,16 @@ + + + + + + <_ContentIncludedByDefault Remove="Views\Home\Mails.cshtml" /> + + + + + + 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/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/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/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 dc7b314..254e70f 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/Implements/MessageInfoStorage.cs b/GiftShop/GiftShopDatabaseImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..af45ac2 --- /dev/null +++ b/GiftShop/GiftShopDatabaseImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,55 @@ +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) + { + if (string.IsNullOrEmpty(model.MessageId)) + { + return null; + } + using var context = new GiftShopDatabase(); + 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(model); + if (newMessage == null) + { + return null; + } + context.Messages.Add(newMessage); + context.SaveChanges(); + return newMessage.GetViewModel; + } + } +} diff --git a/GiftShop/GiftShopDatabaseImplement/Migrations/20230514155217_ThirdMigration.Designer.cs b/GiftShop/GiftShopDatabaseImplement/Migrations/20230514155217_ThirdMigration.Designer.cs new file mode 100644 index 0000000..9339929 --- /dev/null +++ b/GiftShop/GiftShopDatabaseImplement/Migrations/20230514155217_ThirdMigration.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("20230514155217_ThirdMigration")] + partial class ThirdMigration + { + /// + 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/20230514155217_ThirdMigration.cs b/GiftShop/GiftShopDatabaseImplement/Migrations/20230514155217_ThirdMigration.cs new file mode 100644 index 0000000..9ff5662 --- /dev/null +++ b/GiftShop/GiftShopDatabaseImplement/Migrations/20230514155217_ThirdMigration.cs @@ -0,0 +1,48 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace GiftShopDatabaseImplement.Migrations +{ + /// + public partial class ThirdMigration : 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..7c57d86 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() + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + modelBuilder.Entity("GiftShopDatabaseImplement.Models.Order", b => { b.HasOne("GiftShopDatabaseImplement.Models.Client", "Client") diff --git a/GiftShop/GiftShopDatabaseImplement/Models/Message.cs b/GiftShop/GiftShopDatabaseImplement/Models/Message.cs new file mode 100644 index 0000000..c02da99 --- /dev/null +++ b/GiftShop/GiftShopDatabaseImplement/Models/Message.cs @@ -0,0 +1,51 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.ViewModels; +using GiftShopDataModels.Models; +using System.ComponentModel.DataAnnotations; + +namespace GiftShopDatabaseImplement.Models +{ + public class Message : IMessageInfoModel + { + [Key] + public string MessageId { get; private set; } = string.Empty; + + public int? ClientId { get; private set; } + + public string SenderName { get; private set; } = string.Empty; + + public DateTime DateDelivery { get; private set; } = DateTime.Now; + + public string Subject { get; private set; } = string.Empty; + + public string Body { get; private set; } = string.Empty; + + public Client? Client { get; private set; } + public static Message? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Subject = model.Subject, + ClientId = model.ClientId, + MessageId = model.MessageId, + SenderName = model.SenderName, + DateDelivery = model.DateDelivery, + }; + } + + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Subject = Subject, + ClientId = ClientId, + MessageId = MessageId, + SenderName = SenderName, + DateDelivery = DateDelivery, + }; + } +} diff --git a/GiftShop/GiftShopFileImplement/DataFileSingleton.cs b/GiftShop/GiftShopFileImplement/DataFileSingleton.cs index 32b41a0..015e790 100644 --- a/GiftShop/GiftShopFileImplement/DataFileSingleton.cs +++ b/GiftShop/GiftShopFileImplement/DataFileSingleton.cs @@ -17,6 +17,8 @@ namespace GiftShopFileImplement private readonly string ImplementerFileName = "Implementer.xml"; + 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) @@ -46,12 +50,16 @@ namespace GiftShopFileImplement 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/Implements/MessageInfoStorage.cs b/GiftShop/GiftShopFileImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..e53268c --- /dev/null +++ b/GiftShop/GiftShopFileImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,53 @@ +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/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 ec01b43..3ce72ad 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() { @@ -18,6 +19,7 @@ namespace GiftShopListImplement Gifts = new List(); Clients = new List(); Implementers = new List(); + Messages = new List(); } public static DataListSingleton GetInstance() { diff --git a/GiftShop/GiftShopListImplement/Implements/MessageInfoStorage.cs b/GiftShop/GiftShopListImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..0755eda --- /dev/null +++ b/GiftShop/GiftShopListImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,70 @@ +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) + { + if (string.IsNullOrEmpty(model.MessageId)) + { + return null; + } + foreach (var message in _source.Messages) + { + if (message.MessageId == model.MessageId) + { + return message.GetViewModel; + } + } + return null; + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + var result = new List(); + if (string.IsNullOrEmpty(model.MessageId)) + { + return result; + } + foreach (var message in _source.Messages) + { + if (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/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..5a0cf6d 100644 --- a/GiftShop/GiftShopRestApi/Controllers/ClientController.cs +++ b/GiftShop/GiftShopRestApi/Controllers/ClientController.cs @@ -14,11 +14,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) @@ -65,5 +68,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/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/appsettings.json b/GiftShop/GiftShopRestApi/appsettings.json index 10f68b8..8c22c4a 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": "sergunovlab@gmail.com", + "MailPassword": "hzqn cbqi ppqy ycjo" } diff --git a/GiftShop/GiftShopView/App.config b/GiftShop/GiftShopView/App.config new file mode 100644 index 0000000..e1d8c74 --- /dev/null +++ b/GiftShop/GiftShopView/App.config @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file 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..36590ec --- /dev/null +++ b/GiftShop/GiftShopView/FormMails.cs @@ -0,0 +1,41 @@ +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 FormMails_Load(object sender, EventArgs e) + { + try + { + var list = _logic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["MessageId"].Visible = false; + dataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + _logger.LogInformation("Загрузка писем"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки писем"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + } +} + diff --git a/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 ee34174..a874af5 100644 --- a/GiftShop/GiftShopView/FormMain.Designer.cs +++ b/GiftShop/GiftShopView/FormMain.Designer.cs @@ -38,11 +38,12 @@ списокКомпонентов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(); + письмаToolStripMenuItem = new ToolStripMenuItem(); menuStrip.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); SuspendLayout(); @@ -50,7 +51,7 @@ // menuStrip // menuStrip.ImageScalingSize = new Size(20, 20); - menuStrip.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчётыToolStripMenuItem, запускРаботToolStripMenuItem }); + menuStrip.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчётыToolStripMenuItem, запускРаботToolStripMenuItem, письмаToolStripMenuItem }); menuStrip.Location = new Point(0, 0); menuStrip.Name = "menuStrip"; menuStrip.Size = new Size(1367, 28); @@ -120,6 +121,13 @@ списокЗаказов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; @@ -161,12 +169,12 @@ buttonRef.UseVisualStyleBackColor = true; buttonRef.Click += ButtonRef_Click; // - // запускРаботToolStripMenuItem + // письмаToolStripMenuItem // - запускРаботToolStripMenuItem.Name = "запускРаботToolStripMenuItem"; - запускРаботToolStripMenuItem.Size = new Size(114, 24); - запускРаботToolStripMenuItem.Text = "Запуск работ"; - запускРаботToolStripMenuItem.Click += запускРаботToolStripMenuItem_Click; + письмаToolStripMenuItem.Name = "письмаToolStripMenuItem"; + письмаToolStripMenuItem.Size = new Size(77, 24); + письмаToolStripMenuItem.Text = "Письма"; + письмаToolStripMenuItem.Click += письмаToolStripMenuItem_Click; // // FormMain // @@ -206,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/GiftShopView.csproj b/GiftShop/GiftShopView/GiftShopView.csproj index e75c4c7..56e6506 100644 --- a/GiftShop/GiftShopView/GiftShopView.csproj +++ b/GiftShop/GiftShopView/GiftShopView.csproj @@ -39,6 +39,9 @@ + + Always + Always diff --git a/GiftShop/GiftShopView/Program.cs b/GiftShop/GiftShopView/Program.cs index 361ffb7..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) @@ -36,6 +58,7 @@ namespace GiftShopView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -43,13 +66,15 @@ namespace GiftShopView 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(); @@ -61,6 +86,9 @@ namespace GiftShopView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); } - } + + private static void MailCheck(object obj) => ServiceProvider?.GetService()?.MailCheck(); + } } \ No newline at end of file -- 2.25.1 From 6e3d43e26526f2c0ec83e2fcc2caaa9ca57ff9cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=B0=D0=BA=D1=81=D0=B8=D0=BC=20=D0=A1=D0=B5=D1=80?= =?UTF-8?q?=D0=B3=D1=83=D0=BD=D0=BE=D0=B2?= Date: Sat, 20 May 2023 07:50:19 +0400 Subject: [PATCH 2/4] some fix --- .../20230514095932_SecMigration.Designer.cs | 261 ------------------ .../20230514155217_ThirdMigration.cs | 48 ---- ...> 20230515064632_SecMigration.Designer.cs} | 4 +- ...tion.cs => 20230515064632_SecMigration.cs} | 29 ++ 4 files changed, 31 insertions(+), 311 deletions(-) delete mode 100644 GiftShop/GiftShopDatabaseImplement/Migrations/20230514095932_SecMigration.Designer.cs delete mode 100644 GiftShop/GiftShopDatabaseImplement/Migrations/20230514155217_ThirdMigration.cs rename GiftShop/GiftShopDatabaseImplement/Migrations/{20230514155217_ThirdMigration.Designer.cs => 20230515064632_SecMigration.Designer.cs} (99%) rename GiftShop/GiftShopDatabaseImplement/Migrations/{20230514095932_SecMigration.cs => 20230515064632_SecMigration.cs} (85%) diff --git a/GiftShop/GiftShopDatabaseImplement/Migrations/20230514095932_SecMigration.Designer.cs b/GiftShop/GiftShopDatabaseImplement/Migrations/20230514095932_SecMigration.Designer.cs deleted file mode 100644 index 48e6665..0000000 --- a/GiftShop/GiftShopDatabaseImplement/Migrations/20230514095932_SecMigration.Designer.cs +++ /dev/null @@ -1,261 +0,0 @@ -// -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("20230514095932_SecMigration")] - partial class SecMigration - { - /// - 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.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.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/20230514155217_ThirdMigration.cs b/GiftShop/GiftShopDatabaseImplement/Migrations/20230514155217_ThirdMigration.cs deleted file mode 100644 index 9ff5662..0000000 --- a/GiftShop/GiftShopDatabaseImplement/Migrations/20230514155217_ThirdMigration.cs +++ /dev/null @@ -1,48 +0,0 @@ -using System; -using Microsoft.EntityFrameworkCore.Migrations; - -#nullable disable - -namespace GiftShopDatabaseImplement.Migrations -{ - /// - public partial class ThirdMigration : 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/20230514155217_ThirdMigration.Designer.cs b/GiftShop/GiftShopDatabaseImplement/Migrations/20230515064632_SecMigration.Designer.cs similarity index 99% rename from GiftShop/GiftShopDatabaseImplement/Migrations/20230514155217_ThirdMigration.Designer.cs rename to GiftShop/GiftShopDatabaseImplement/Migrations/20230515064632_SecMigration.Designer.cs index 9339929..77e6053 100644 --- a/GiftShop/GiftShopDatabaseImplement/Migrations/20230514155217_ThirdMigration.Designer.cs +++ b/GiftShop/GiftShopDatabaseImplement/Migrations/20230515064632_SecMigration.Designer.cs @@ -12,8 +12,8 @@ using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace GiftShopDatabaseImplement.Migrations { [DbContext(typeof(GiftShopDatabase))] - [Migration("20230514155217_ThirdMigration")] - partial class ThirdMigration + [Migration("20230515064632_SecMigration")] + partial class SecMigration { /// protected override void BuildTargetModel(ModelBuilder modelBuilder) diff --git a/GiftShop/GiftShopDatabaseImplement/Migrations/20230514095932_SecMigration.cs b/GiftShop/GiftShopDatabaseImplement/Migrations/20230515064632_SecMigration.cs similarity index 85% rename from GiftShop/GiftShopDatabaseImplement/Migrations/20230514095932_SecMigration.cs rename to GiftShop/GiftShopDatabaseImplement/Migrations/20230515064632_SecMigration.cs index 4aeb64e..b860920 100644 --- a/GiftShop/GiftShopDatabaseImplement/Migrations/20230514095932_SecMigration.cs +++ b/GiftShop/GiftShopDatabaseImplement/Migrations/20230515064632_SecMigration.cs @@ -70,6 +70,27 @@ namespace GiftShopDatabaseImplement.Migrations table.PrimaryKey("PK_Implementers", x => x.Id); }); + 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.CreateTable( name: "GiftComponents", columns: table => new @@ -145,6 +166,11 @@ namespace GiftShopDatabaseImplement.Migrations table: "GiftComponents", column: "GiftId"); + migrationBuilder.CreateIndex( + name: "IX_Messages_ClientId", + table: "Messages", + column: "ClientId"); + migrationBuilder.CreateIndex( name: "IX_Orders_ClientId", table: "Orders", @@ -167,6 +193,9 @@ namespace GiftShopDatabaseImplement.Migrations migrationBuilder.DropTable( name: "GiftComponents"); + migrationBuilder.DropTable( + name: "Messages"); + migrationBuilder.DropTable( name: "Orders"); -- 2.25.1 From f0f89c2720b846e27a440e82f0b3acdb0e33279c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=B0=D0=BA=D1=81=D0=B8=D0=BC=20=D0=A1=D0=B5=D1=80?= =?UTF-8?q?=D0=B3=D1=83=D0=BD=D0=BE=D0=B2?= Date: Thu, 1 Jun 2023 23:00:14 +0400 Subject: [PATCH 3/4] fix --- .../BusinessLogics/ClientLogic.cs | 10 +- .../BusinessLogics/OrderLogic.cs | 13 +- .../GiftShopView/FormCreateOrder.Designer.cs | 298 ++++++++++-------- GiftShop/GiftShopView/FormCreateOrder.cs | 240 +++++++------- GiftShop/GiftShopView/FormMails.cs | 61 ++-- 5 files changed, 338 insertions(+), 284 deletions(-) diff --git a/GiftShop/GiftShopBusinessLogic/BusinessLogics/ClientLogic.cs b/GiftShop/GiftShopBusinessLogic/BusinessLogics/ClientLogic.cs index ad39386..d50860c 100644 --- a/GiftShop/GiftShopBusinessLogic/BusinessLogics/ClientLogic.cs +++ b/GiftShop/GiftShopBusinessLogic/BusinessLogics/ClientLogic.cs @@ -46,7 +46,7 @@ namespace GiftShopBusinessLogic.BusinessLogics { throw new ArgumentNullException(nameof(model)); } - _logger.LogInformation("ReadElement. ClientFIO:{ClientFIO}. Id:{ Id}", model.ClientFIO, model.Id); + _logger.LogInformation("ReadElement. ClientFIO:{ClientFIO}. Email: {Email}. Id:{ Id}", model.ClientFIO, model.Email, model.Id); var element = _clientStorage.GetElement(model); if (element == null) { @@ -59,7 +59,7 @@ namespace GiftShopBusinessLogic.BusinessLogics public List? ReadList(ClientSearchModel? model) { - _logger.LogInformation("ReadList. ClientFIO:{ClientFIO}. Id:{Id}", model?.ClientFIO, model?.Id); + _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) { @@ -100,13 +100,13 @@ namespace GiftShopBusinessLogic.BusinessLogics } if (string.IsNullOrEmpty(model.Password)) { - throw new ArgumentNullException("У клиента отсутствует пароль", nameof(model.Email)); + throw new ArgumentNullException("У клиента отсутствует пароль", nameof(model.Password)); } - if (!Regex.IsMatch(model.Email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$")) + 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) + if (model.Password.Length < 10 || model.Password.Length > 50) { throw new ArgumentException("Неправильно введенный пароль", nameof(model.Password)); } diff --git a/GiftShop/GiftShopBusinessLogic/BusinessLogics/OrderLogic.cs b/GiftShop/GiftShopBusinessLogic/BusinessLogics/OrderLogic.cs index 77d972f..c9fb26f 100644 --- a/GiftShop/GiftShopBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/GiftShop/GiftShopBusinessLogic/BusinessLogics/OrderLogic.cs @@ -38,15 +38,15 @@ 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) @@ -79,12 +79,15 @@ namespace GiftShopBusinessLogic.BusinessLogics 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; } 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.cs b/GiftShop/GiftShopView/FormMails.cs index 36590ec..9c7a2e8 100644 --- a/GiftShop/GiftShopView/FormMails.cs +++ b/GiftShop/GiftShopView/FormMails.cs @@ -6,36 +6,41 @@ namespace GiftShopView public partial class FormMails : Form { private readonly ILogger _logger; - private readonly IMessageInfoLogic _logic; + private readonly IMessageInfoLogic _logic; - public FormMails(ILogger logger, IMessageInfoLogic logic) - { - InitializeComponent(); - _logger = logger; - _logic = logic; - } + public FormMails(ILogger logger, IMessageInfoLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } - private void FormMails_Load(object sender, EventArgs e) - { - try - { - var list = _logic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["ClientId"].Visible = false; - dataGridView.Columns["MessageId"].Visible = false; - dataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } - _logger.LogInformation("Загрузка писем"); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки писем"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, - MessageBoxIcon.Error); - } - } + 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(); + } } } -- 2.25.1 From 2c43bea1b1c99e29df7d9cae8db368832527de93 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=B0=D0=BA=D1=81=D0=B8=D0=BC=20=D0=A1=D0=B5=D1=80?= =?UTF-8?q?=D0=B3=D1=83=D0=BD=D0=BE=D0=B2?= Date: Sat, 3 Jun 2023 22:58:25 +0400 Subject: [PATCH 4/4] smth has changed --- GiftShop/GiftShopBusinessLogic/BusinessLogics/ClientLogic.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GiftShop/GiftShopBusinessLogic/BusinessLogics/ClientLogic.cs b/GiftShop/GiftShopBusinessLogic/BusinessLogics/ClientLogic.cs index d50860c..ce33113 100644 --- a/GiftShop/GiftShopBusinessLogic/BusinessLogics/ClientLogic.cs +++ b/GiftShop/GiftShopBusinessLogic/BusinessLogics/ClientLogic.cs @@ -106,7 +106,7 @@ namespace GiftShopBusinessLogic.BusinessLogics { throw new ArgumentException("Неправильно введенный email", nameof(model.Email)); } - if (model.Password.Length < 10 || model.Password.Length > 50) + 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)); } -- 2.25.1