From df256cfa2b09bed4f39455641cf2e49ddbb990b4 Mon Sep 17 00:00:00 2001 From: Extrimal Date: Sat, 11 May 2024 18:37:39 +0400 Subject: [PATCH] =?UTF-8?q?7=20=D0=B2=D1=80=D0=BE=D0=B4=D0=B5=20=D0=B3?= =?UTF-8?q?=D0=BE=D1=82=D0=BE=D0=B2=D0=B0=D1=8F=20=D0=BB=D0=B0=D0=B1=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../BusinessLogics/ClientLogic.cs | 9 +- .../BusinessLogics/MessageInfoLogic.cs | 95 +++++ .../BusinessLogics/OrderLogic.cs | 21 +- .../GarmentFactoryBusinessLogic.csproj | 1 + .../MailWorker/AbstractMailWorker.cs | 97 +++++ .../MailWorker/MailKitWorker.cs | 82 ++++ .../Controllers/HomeController.cs | 12 +- .../Views/Home/Mails.cshtml | 54 +++ .../Views/Shared/_Layout.cshtml | 11 +- .../BindingModels/MailConfigBindingModel.cs | 23 ++ .../BindingModels/MailSendInfoBindingModel.cs | 17 + .../BindingModels/MessageInfoBindingModel.cs | 24 ++ .../IMessageInfoLogic.cs | 18 + .../SearchModels/MessageInfoSearchModel.cs | 14 + .../StoragesContracts/IMessageInfoStorage.cs | 22 ++ .../ViewModels/MessageInfoViewModel.cs | 29 ++ .../ViewModels/OrderViewModel.cs | 1 + .../Models/IMessageInfoModel.cs | 23 ++ .../GarmentFactoryDatabase.cs | 1 + .../Implements/ClientStorage.cs | 1 + .../Implements/MessageInfoStorage.cs | 62 +++ .../20240511115922_MailCreate.Designer.cs | 298 ++++++++++++++ .../Migrations/20240511115922_MailCreate.cs | 48 +++ .../GarmentFactoryDatabaseModelSnapshot.cs | 41 ++ .../Models/Client.cs | 3 +- .../Models/MessageInfo.cs | 63 +++ .../Models/Order.cs | 1 + .../DataFileSingleton.cs | 4 + .../Implements/ClientStorage.cs | 1 + .../Implements/MessageInfoStorage.cs | 63 +++ .../Models/MessageInfo.cs | 80 ++++ .../DataListSingleton.cs | 2 + .../Implements/ClientStorage.cs | 4 +- .../Implements/MessageInfoStorage.cs | 77 ++++ .../Models/MessageInfo.cs | 53 +++ .../Controllers/ClientController.cs | 20 +- .../GarmentFactoryRestApi/Program.cs | 16 + .../GarmentFactoryRestApi/appsettings.json | 8 +- GarmentFactory/GarmentFactoryView/App.config | 11 + .../GarmentFactoryView/FormMails.Designer.cs | 68 ++++ .../GarmentFactoryView/FormMails.cs | 45 +++ .../GarmentFactoryView/FormMails.resx | 120 ++++++ .../GarmentFactoryView/FormMain.Designer.cs | 363 +++++++++--------- GarmentFactory/GarmentFactoryView/FormMain.cs | 292 +++++++------- GarmentFactory/GarmentFactoryView/Program.cs | 39 +- 45 files changed, 1997 insertions(+), 340 deletions(-) create mode 100644 GarmentFactory/GarmentFactoryBusinessLogic/BusinessLogics/MessageInfoLogic.cs create mode 100644 GarmentFactory/GarmentFactoryBusinessLogic/MailWorker/AbstractMailWorker.cs create mode 100644 GarmentFactory/GarmentFactoryBusinessLogic/MailWorker/MailKitWorker.cs create mode 100644 GarmentFactory/GarmentFactoryClientApp/Views/Home/Mails.cshtml create mode 100644 GarmentFactory/GarmentFactoryContracts/BindingModels/MailConfigBindingModel.cs create mode 100644 GarmentFactory/GarmentFactoryContracts/BindingModels/MailSendInfoBindingModel.cs create mode 100644 GarmentFactory/GarmentFactoryContracts/BindingModels/MessageInfoBindingModel.cs create mode 100644 GarmentFactory/GarmentFactoryContracts/BusinessLogicsContracts/IMessageInfoLogic.cs create mode 100644 GarmentFactory/GarmentFactoryContracts/SearchModels/MessageInfoSearchModel.cs create mode 100644 GarmentFactory/GarmentFactoryContracts/StoragesContracts/IMessageInfoStorage.cs create mode 100644 GarmentFactory/GarmentFactoryContracts/ViewModels/MessageInfoViewModel.cs create mode 100644 GarmentFactory/GarmentFactoryDataModels/Models/IMessageInfoModel.cs create mode 100644 GarmentFactory/GarmentFactoryDatabaseImplement/Implements/MessageInfoStorage.cs create mode 100644 GarmentFactory/GarmentFactoryDatabaseImplement/Migrations/20240511115922_MailCreate.Designer.cs create mode 100644 GarmentFactory/GarmentFactoryDatabaseImplement/Migrations/20240511115922_MailCreate.cs create mode 100644 GarmentFactory/GarmentFactoryDatabaseImplement/Models/MessageInfo.cs create mode 100644 GarmentFactory/GarmentFactoryFileImplement/Implements/MessageInfoStorage.cs create mode 100644 GarmentFactory/GarmentFactoryFileImplement/Models/MessageInfo.cs create mode 100644 GarmentFactory/GarmentFactoryListImplement/Implements/MessageInfoStorage.cs create mode 100644 GarmentFactory/GarmentFactoryListImplement/Models/MessageInfo.cs create mode 100644 GarmentFactory/GarmentFactoryView/App.config create mode 100644 GarmentFactory/GarmentFactoryView/FormMails.Designer.cs create mode 100644 GarmentFactory/GarmentFactoryView/FormMails.cs create mode 100644 GarmentFactory/GarmentFactoryView/FormMails.resx diff --git a/GarmentFactory/GarmentFactoryBusinessLogic/BusinessLogics/ClientLogic.cs b/GarmentFactory/GarmentFactoryBusinessLogic/BusinessLogics/ClientLogic.cs index 6e5f66d..4824c7d 100644 --- a/GarmentFactory/GarmentFactoryBusinessLogic/BusinessLogics/ClientLogic.cs +++ b/GarmentFactory/GarmentFactoryBusinessLogic/BusinessLogics/ClientLogic.cs @@ -8,6 +8,7 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; +using System.Text.RegularExpressions; using System.Threading.Tasks; namespace GarmentFactoryBusinessLogic.BusinessLogics @@ -102,13 +103,13 @@ namespace GarmentFactoryBusinessLogic.BusinessLogics { throw new ArgumentNullException("Нет ФИО клиента", nameof(model.ClientFIO)); } - if (string.IsNullOrEmpty(model.Email)) + if (string.IsNullOrEmpty(model.Email) || !Regex.IsMatch(model.Email, @"^[a-z0-9._%+-]+\@([a-z0-9-]+\.)+[a-z]{2,4}$")) { - throw new ArgumentNullException("Нет логина(почты) клиента", nameof(model.Email)); + throw new ArgumentNullException("Неправильно введен логин(почта)", nameof(model.Email)); } - if (string.IsNullOrEmpty(model.Password)) + if (string.IsNullOrEmpty(model.Password) || !Regex.IsMatch(model.Password, @"^(?=.*[A-Za-z])(?=.*\d)(?=.*[^A-Za-z0-9\n]).{10,50}$")) { - throw new ArgumentNullException("Нет пароля клиента", nameof(model.Password)); + throw new ArgumentNullException("Неправильно введен пароль клиента", nameof(model.Password)); } _logger.LogInformation("Client. Id: {id}, FIO: {fio}, email: {email}, password: {password}", model.Id, model.ClientFIO, model.Email, model.Password); diff --git a/GarmentFactory/GarmentFactoryBusinessLogic/BusinessLogics/MessageInfoLogic.cs b/GarmentFactory/GarmentFactoryBusinessLogic/BusinessLogics/MessageInfoLogic.cs new file mode 100644 index 0000000..a15eae0 --- /dev/null +++ b/GarmentFactory/GarmentFactoryBusinessLogic/BusinessLogics/MessageInfoLogic.cs @@ -0,0 +1,95 @@ +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.BusinessLogicsContracts; +using GarmentFactoryContracts.SearchModels; +using GarmentFactoryContracts.StoragesContracts; +using GarmentFactoryContracts.ViewModels; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryBusinessLogic.BusinessLogics +{ + public class MessageInfoLogic : IMessageInfoLogic + { + private readonly ILogger _logger; + + private readonly IMessageInfoStorage _messageInfoStorage; + + private readonly IClientStorage _clientStorage; + + public MessageInfoLogic(ILogger logger, IMessageInfoStorage messageInfoStorage, IClientStorage clientStorage) + { + _logger = logger; + _messageInfoStorage = messageInfoStorage; + _clientStorage = clientStorage; + } + + public List? ReadList(MessageInfoSearchModel? model) + { + _logger.LogInformation("ReadList. MessageId: {MessageId}. ClientId: {ClientId}", model?.MessageId, model?.ClientId); + var list = model == null ? _messageInfoStorage.GetFullList() : _messageInfoStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + _logger.LogInformation("ReadList. Count: {Count}", list.Count); + return list; + } + + public bool Create(MessageInfoBindingModel model) + { + CheckModel(model); + if (_messageInfoStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } + + private void CheckModel(MessageInfoBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (!withParams) + { + return; + } + if (string.IsNullOrEmpty(model.MessageId)) + { + throw new ArgumentNullException("Не указан id", nameof(model.MessageId)); + } + if (string.IsNullOrEmpty(model.SenderName)) + { + throw new ArgumentNullException("Не указана почта отправителя", nameof(model.SenderName)); + } + if (string.IsNullOrEmpty(model.Subject)) + { + throw new ArgumentNullException("Не указан заголовок", nameof(model.Subject)); + } + if (string.IsNullOrEmpty(model.Body)) + { + throw new ArgumentNullException("Не указан текст", nameof(model.Subject)); + } + _logger.LogInformation("MessageInfo. MessageId: {MessageId}. SenderName: {SenderName}. DateDelivery: {DateDelivery} Subject: {Subject}. Body: {Body}", model.MessageId, model.SenderName, model.DateDelivery, model.Subject, model.Body); + var element = _clientStorage.GetElement(new ClientSearchModel + { + Email = model.SenderName + }); + if (element == null) + { + _logger.LogWarning("Не удалось найти клиента, отправившего письмо с адреса Email: {Email}", model.SenderName); + } + else + { + model.ClientId = element.Id; + } + } + } +} diff --git a/GarmentFactory/GarmentFactoryBusinessLogic/BusinessLogics/OrderLogic.cs b/GarmentFactory/GarmentFactoryBusinessLogic/BusinessLogics/OrderLogic.cs index e652c9f..2bebf54 100644 --- a/GarmentFactory/GarmentFactoryBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/GarmentFactory/GarmentFactoryBusinessLogic/BusinessLogics/OrderLogic.cs @@ -10,6 +10,7 @@ using GarmentFactoryContracts.StoragesContracts; using GarmentFactoryContracts.ViewModels; using GarmentFactoryDataModels.Enums; using Microsoft.Extensions.Logging; +using GarmentFactoryBusinessLogic.MailWorker; namespace GarmentFactoryBusinessLogic.BusinessLogics { @@ -19,11 +20,13 @@ namespace GarmentFactoryBusinessLogic.BusinessLogics private readonly IOrderStorage _orderStorage; static readonly object locker = new(); + private readonly AbstractMailWorker _mailWorker; - public OrderLogic(ILogger logger, IOrderStorage orderStorage) + public OrderLogic(ILogger logger, IOrderStorage orderStorage, AbstractMailWorker mailWorker) { _logger = logger; _orderStorage = orderStorage; + _mailWorker = mailWorker; } public bool CreateOrder(OrderBindingModel model) @@ -35,11 +38,18 @@ namespace GarmentFactoryBusinessLogic.BusinessLogics return false; } model.Status = OrderStatus.Принят; - if (_orderStorage.Insert(model) == null) + var element = _orderStorage.Insert(model); + if (element == null) { _logger.LogWarning("Insert operation failed"); return false; } + Task.Run(() => _mailWorker.MailSendAsync(new MailSendInfoBindingModel + { + MailAddress = element.ClientEmail, + Subject = $"Новый заказ создан. Номер заказа - {element.Id}", + Text = $"Заказ №{element.Id} от {element.DateCreate} на сумму {element.Sum} принят." + })); return true; } @@ -152,6 +162,13 @@ namespace GarmentFactoryBusinessLogic.BusinessLogics _logger.LogWarning("Change status operation failed"); return false; } + string DateInfo = model.DateImplement.HasValue ? $"Дата выполнения {model.DateImplement}" : ""; + Task.Run(() => _mailWorker.MailSendAsync(new MailSendInfoBindingModel + { + MailAddress = order.ClientEmail, + Subject = $"Заказ №{order.Id}", + Text = $"Заказ №{order.Id} изменен статус на {model.Status}. {DateInfo}" + })); return true; } } diff --git a/GarmentFactory/GarmentFactoryBusinessLogic/GarmentFactoryBusinessLogic.csproj b/GarmentFactory/GarmentFactoryBusinessLogic/GarmentFactoryBusinessLogic.csproj index 409d98a..35e5667 100644 --- a/GarmentFactory/GarmentFactoryBusinessLogic/GarmentFactoryBusinessLogic.csproj +++ b/GarmentFactory/GarmentFactoryBusinessLogic/GarmentFactoryBusinessLogic.csproj @@ -8,6 +8,7 @@ + diff --git a/GarmentFactory/GarmentFactoryBusinessLogic/MailWorker/AbstractMailWorker.cs b/GarmentFactory/GarmentFactoryBusinessLogic/MailWorker/AbstractMailWorker.cs new file mode 100644 index 0000000..2c595ea --- /dev/null +++ b/GarmentFactory/GarmentFactoryBusinessLogic/MailWorker/AbstractMailWorker.cs @@ -0,0 +1,97 @@ +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryBusinessLogic.MailWorker +{ + public abstract class AbstractMailWorker + { + protected string _mailLogin = string.Empty; + + protected string _mailPassword = string.Empty; + + protected string _smtpClientHost = string.Empty; + + protected int _smtpClientPort; + + protected string _popHost = string.Empty; + + protected int _popPort; + + private readonly IMessageInfoLogic _messageInfoLogic; + + private readonly ILogger _logger; + + public AbstractMailWorker(ILogger logger, IMessageInfoLogic messageInfoLogic) + { + _logger = logger; + _messageInfoLogic = messageInfoLogic; + } + + public void MailConfig(MailConfigBindingModel config) + { + _mailLogin = config.MailLogin; + _mailPassword = config.MailPassword; + _smtpClientHost = config.SmtpClientHost; + _smtpClientPort = config.SmtpClientPort; + _popHost = config.PopHost; + _popPort = config.PopPort; + _logger.LogDebug("Config: {login}, {password}, {clientHost}, {clientPOrt}, {popHost}, {popPort}", _mailLogin, _mailPassword, _smtpClientHost, _smtpClientPort, _popHost, _popPort); + } + + public async void MailSendAsync(MailSendInfoBindingModel info) + { + if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword)) + { + return; + } + + if (string.IsNullOrEmpty(_smtpClientHost) || _smtpClientPort == 0) + { + return; + } + + if (string.IsNullOrEmpty(info.MailAddress) || string.IsNullOrEmpty(info.Subject) || string.IsNullOrEmpty(info.Text)) + { + return; + } + + _logger.LogDebug("Send Mail: {To}, {Subject}", info.MailAddress, info.Subject); + await SendMailAsync(info); + } + + public async void MailCheck() + { + if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword)) + { + return; + } + + if (string.IsNullOrEmpty(_popHost) || _popPort == 0) + { + return; + } + + if (_messageInfoLogic == null) + { + return; + } + + var list = await ReceiveMailAsync(); + _logger.LogDebug("Check Mail: {Count} new mails", list.Count); + foreach (var mail in list) + { + _messageInfoLogic.Create(mail); + } + } + + protected abstract Task SendMailAsync(MailSendInfoBindingModel info); + + protected abstract Task> ReceiveMailAsync(); + } +} diff --git a/GarmentFactory/GarmentFactoryBusinessLogic/MailWorker/MailKitWorker.cs b/GarmentFactory/GarmentFactoryBusinessLogic/MailWorker/MailKitWorker.cs new file mode 100644 index 0000000..1e28401 --- /dev/null +++ b/GarmentFactory/GarmentFactoryBusinessLogic/MailWorker/MailKitWorker.cs @@ -0,0 +1,82 @@ +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.BusinessLogicsContracts; +using MailKit.Net.Pop3; +using MailKit.Security; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Mail; +using System.Net; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryBusinessLogic.MailWorker +{ + public class MailKitWorker : AbstractMailWorker + { + public MailKitWorker(ILogger logger, IMessageInfoLogic messageInfoLogic) : base(logger, messageInfoLogic) { } + + protected override async Task SendMailAsync(MailSendInfoBindingModel info) + { + using var objMailMessage = new MailMessage(); + using var objSmtpClient = new SmtpClient(_smtpClientHost, _smtpClientPort); + try + { + objMailMessage.From = new MailAddress(_mailLogin); + objMailMessage.To.Add(new MailAddress(info.MailAddress)); + objMailMessage.Subject = info.Subject; + objMailMessage.Body = info.Text; + objMailMessage.SubjectEncoding = Encoding.UTF8; + objMailMessage.BodyEncoding = Encoding.UTF8; + + objSmtpClient.UseDefaultCredentials = false; + objSmtpClient.EnableSsl = true; + objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; + objSmtpClient.Credentials = new NetworkCredential(_mailLogin, _mailPassword); + + await Task.Run(() => objSmtpClient.Send(objMailMessage)); + } + catch (Exception) + { + throw; + } + } + + protected override async Task> ReceiveMailAsync() + { + var list = new List(); + using var client = new Pop3Client(); + await Task.Run(() => + { + try + { + client.Connect(_popHost, _popPort, SecureSocketOptions.SslOnConnect); + client.Authenticate(_mailLogin, _mailPassword); + for (int i = 0; i < client.Count; i++) + { + var message = client.GetMessage(i); + foreach (var mail in message.From.Mailboxes) + { + list.Add(new MessageInfoBindingModel + { + DateDelivery = message.Date.DateTime, + MessageId = message.MessageId, + SenderName = mail.Address, + Subject = message.Subject, + Body = message.TextBody + }); + } + } + } + catch (AuthenticationException) + { } + finally + { + client.Disconnect(true); + } + }); + return list; + } + } +} diff --git a/GarmentFactory/GarmentFactoryClientApp/Controllers/HomeController.cs b/GarmentFactory/GarmentFactoryClientApp/Controllers/HomeController.cs index 1b992b7..10df20d 100644 --- a/GarmentFactory/GarmentFactoryClientApp/Controllers/HomeController.cs +++ b/GarmentFactory/GarmentFactoryClientApp/Controllers/HomeController.cs @@ -143,5 +143,15 @@ namespace GarmentFactoryClientApp.Controllers var t = APIClient.GetRequest($"api/main/gettextile?textileId={textile}"); return count * (t?.Price ?? 1); } - } + + [HttpGet] + public IActionResult Mails() + { + if (APIClient.Client == null) + { + return Redirect("~/Home/Enter"); + } + return View(APIClient.GetRequest>($"api/client/getmessages?clientId={APIClient.Client.Id}")); + } + } } diff --git a/GarmentFactory/GarmentFactoryClientApp/Views/Home/Mails.cshtml b/GarmentFactory/GarmentFactoryClientApp/Views/Home/Mails.cshtml new file mode 100644 index 0000000..7cfe29a --- /dev/null +++ b/GarmentFactory/GarmentFactoryClientApp/Views/Home/Mails.cshtml @@ -0,0 +1,54 @@ +@using GarmentFactoryContracts.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/GarmentFactory/GarmentFactoryClientApp/Views/Shared/_Layout.cshtml b/GarmentFactory/GarmentFactoryClientApp/Views/Shared/_Layout.cshtml index 5853cee..a18ab66 100644 --- a/GarmentFactory/GarmentFactoryClientApp/Views/Shared/_Layout.cshtml +++ b/GarmentFactory/GarmentFactoryClientApp/Views/Shared/_Layout.cshtml @@ -21,16 +21,19 @@ diff --git a/GarmentFactory/GarmentFactoryContracts/BindingModels/MailConfigBindingModel.cs b/GarmentFactory/GarmentFactoryContracts/BindingModels/MailConfigBindingModel.cs new file mode 100644 index 0000000..c5220ca --- /dev/null +++ b/GarmentFactory/GarmentFactoryContracts/BindingModels/MailConfigBindingModel.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryContracts.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/GarmentFactory/GarmentFactoryContracts/BindingModels/MailSendInfoBindingModel.cs b/GarmentFactory/GarmentFactoryContracts/BindingModels/MailSendInfoBindingModel.cs new file mode 100644 index 0000000..1960742 --- /dev/null +++ b/GarmentFactory/GarmentFactoryContracts/BindingModels/MailSendInfoBindingModel.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryContracts.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/GarmentFactory/GarmentFactoryContracts/BindingModels/MessageInfoBindingModel.cs b/GarmentFactory/GarmentFactoryContracts/BindingModels/MessageInfoBindingModel.cs new file mode 100644 index 0000000..4ddb85f --- /dev/null +++ b/GarmentFactory/GarmentFactoryContracts/BindingModels/MessageInfoBindingModel.cs @@ -0,0 +1,24 @@ +using GarmentFactoryDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryContracts.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/GarmentFactory/GarmentFactoryContracts/BusinessLogicsContracts/IMessageInfoLogic.cs b/GarmentFactory/GarmentFactoryContracts/BusinessLogicsContracts/IMessageInfoLogic.cs new file mode 100644 index 0000000..ced0e6c --- /dev/null +++ b/GarmentFactory/GarmentFactoryContracts/BusinessLogicsContracts/IMessageInfoLogic.cs @@ -0,0 +1,18 @@ +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.SearchModels; +using GarmentFactoryContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryContracts.BusinessLogicsContracts +{ + public interface IMessageInfoLogic + { + List? ReadList(MessageInfoSearchModel? model); + + bool Create(MessageInfoBindingModel model); + } +} diff --git a/GarmentFactory/GarmentFactoryContracts/SearchModels/MessageInfoSearchModel.cs b/GarmentFactory/GarmentFactoryContracts/SearchModels/MessageInfoSearchModel.cs new file mode 100644 index 0000000..0d69edb --- /dev/null +++ b/GarmentFactory/GarmentFactoryContracts/SearchModels/MessageInfoSearchModel.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryContracts.SearchModels +{ + public class MessageInfoSearchModel + { + public int? ClientId { get; set; } + public string? MessageId { get; set; } + } +} diff --git a/GarmentFactory/GarmentFactoryContracts/StoragesContracts/IMessageInfoStorage.cs b/GarmentFactory/GarmentFactoryContracts/StoragesContracts/IMessageInfoStorage.cs new file mode 100644 index 0000000..adeeeb0 --- /dev/null +++ b/GarmentFactory/GarmentFactoryContracts/StoragesContracts/IMessageInfoStorage.cs @@ -0,0 +1,22 @@ +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.SearchModels; +using GarmentFactoryContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryContracts.StoragesContracts +{ + public interface IMessageInfoStorage + { + List GetFullList(); + + List GetFilteredList(MessageInfoSearchModel model); + + MessageInfoViewModel? GetElement(MessageInfoSearchModel model); + + MessageInfoViewModel? Insert(MessageInfoBindingModel model); + } +} diff --git a/GarmentFactory/GarmentFactoryContracts/ViewModels/MessageInfoViewModel.cs b/GarmentFactory/GarmentFactoryContracts/ViewModels/MessageInfoViewModel.cs new file mode 100644 index 0000000..0530635 --- /dev/null +++ b/GarmentFactory/GarmentFactoryContracts/ViewModels/MessageInfoViewModel.cs @@ -0,0 +1,29 @@ +using GarmentFactoryDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryContracts.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/GarmentFactory/GarmentFactoryContracts/ViewModels/OrderViewModel.cs b/GarmentFactory/GarmentFactoryContracts/ViewModels/OrderViewModel.cs index f24c2f9..2129cac 100644 --- a/GarmentFactory/GarmentFactoryContracts/ViewModels/OrderViewModel.cs +++ b/GarmentFactory/GarmentFactoryContracts/ViewModels/OrderViewModel.cs @@ -34,5 +34,6 @@ namespace GarmentFactoryContracts.ViewModels public DateTime DateCreate { get; set; } = DateTime.Now; [DisplayName("Дата выполнения")] public DateTime? DateImplement { get; set; } + public string ClientEmail { get; set; } = string.Empty; } } diff --git a/GarmentFactory/GarmentFactoryDataModels/Models/IMessageInfoModel.cs b/GarmentFactory/GarmentFactoryDataModels/Models/IMessageInfoModel.cs new file mode 100644 index 0000000..93f8e76 --- /dev/null +++ b/GarmentFactory/GarmentFactoryDataModels/Models/IMessageInfoModel.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryDataModels.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/GarmentFactory/GarmentFactoryDatabaseImplement/GarmentFactoryDatabase.cs b/GarmentFactory/GarmentFactoryDatabaseImplement/GarmentFactoryDatabase.cs index 56dadb1..fbb2ef2 100644 --- a/GarmentFactory/GarmentFactoryDatabaseImplement/GarmentFactoryDatabase.cs +++ b/GarmentFactory/GarmentFactoryDatabaseImplement/GarmentFactoryDatabase.cs @@ -24,5 +24,6 @@ namespace GarmentFactoryDatabaseImplement public virtual DbSet Orders { set; get; } public virtual DbSet Clients { set; get; } public virtual DbSet Implementers { set; get; } + public virtual DbSet MessageInfos { set; get; } } } diff --git a/GarmentFactory/GarmentFactoryDatabaseImplement/Implements/ClientStorage.cs b/GarmentFactory/GarmentFactoryDatabaseImplement/Implements/ClientStorage.cs index 4e4dfdd..ab1788f 100644 --- a/GarmentFactory/GarmentFactoryDatabaseImplement/Implements/ClientStorage.cs +++ b/GarmentFactory/GarmentFactoryDatabaseImplement/Implements/ClientStorage.cs @@ -43,6 +43,7 @@ namespace GarmentFactoryDatabaseImplement.Implements using var context = new GarmentFactoryDatabase(); return context.Clients.FirstOrDefault(x => (!string.IsNullOrEmpty(model.Email) && x.Email == model.Email && !string.IsNullOrEmpty(model.Password) && x.Password == model.Password) + || (!string.IsNullOrEmpty(model.Email) && x.Email == model.Email && string.IsNullOrEmpty(model.Password)) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; } diff --git a/GarmentFactory/GarmentFactoryDatabaseImplement/Implements/MessageInfoStorage.cs b/GarmentFactory/GarmentFactoryDatabaseImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..fa982c2 --- /dev/null +++ b/GarmentFactory/GarmentFactoryDatabaseImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,62 @@ +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.SearchModels; +using GarmentFactoryContracts.StoragesContracts; +using GarmentFactoryContracts.ViewModels; +using GarmentFactoryDatabaseImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryDatabaseImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + public List GetFullList() + { + using var context = new GarmentFactoryDatabase(); + return context.MessageInfos + .Select(x => x.GetViewModel) + .ToList(); + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + if (!model.ClientId.HasValue) + { + return new(); + } + using var context = new GarmentFactoryDatabase(); + return context.MessageInfos + .Where(x => x.ClientId.HasValue && x.ClientId == model.ClientId) + .Select(x => x.GetViewModel) + .ToList(); + } + + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (string.IsNullOrEmpty(model.MessageId)) + { + return new(); + } + using var context = new GarmentFactoryDatabase(); + return context.MessageInfos + .FirstOrDefault(x => model.MessageId.Equals(x.MessageId)) + ?.GetViewModel; + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = MessageInfo.Create(model); + if (newMessage == null) + { + return null; + } + using var context = new GarmentFactoryDatabase(); + context.MessageInfos.Add(newMessage); + context.SaveChanges(); + return newMessage.GetViewModel; + } + } +} diff --git a/GarmentFactory/GarmentFactoryDatabaseImplement/Migrations/20240511115922_MailCreate.Designer.cs b/GarmentFactory/GarmentFactoryDatabaseImplement/Migrations/20240511115922_MailCreate.Designer.cs new file mode 100644 index 0000000..ab94dcc --- /dev/null +++ b/GarmentFactory/GarmentFactoryDatabaseImplement/Migrations/20240511115922_MailCreate.Designer.cs @@ -0,0 +1,298 @@ +// +using System; +using GarmentFactoryDatabaseImplement; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace GarmentFactoryDatabaseImplement.Migrations +{ + [DbContext(typeof(GarmentFactoryDatabase))] + [Migration("20240511115922_MailCreate")] + partial class MailCreate + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.16") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("GarmentFactoryDatabaseImplement.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("GarmentFactoryDatabaseImplement.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("GarmentFactoryDatabaseImplement.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("GarmentFactoryDatabaseImplement.Models.MessageInfo", b => + { + b.Property("MessageId") + .HasColumnType("nvarchar(450)"); + + b.Property("Body") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("int"); + + b.Property("DateDelivery") + .HasColumnType("datetime2"); + + b.Property("SenderName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Subject") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("MessageId"); + + b.HasIndex("ClientId"); + + b.ToTable("MessageInfos"); + }); + + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.Order", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateImplement") + .HasColumnType("datetime2"); + + b.Property("ImplementerId") + .HasColumnType("int"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("Sum") + .HasColumnType("float"); + + b.Property("TextileId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.HasIndex("ImplementerId"); + + b.HasIndex("TextileId"); + + b.ToTable("Orders"); + }); + + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.Textile", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Price") + .HasColumnType("float"); + + b.Property("TextileName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Textiles"); + }); + + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.TextileComponent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ComponentId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("TextileId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ComponentId"); + + b.HasIndex("TextileId"); + + b.ToTable("TextileComponents"); + }); + + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.MessageInfo", b => + { + b.HasOne("GarmentFactoryDatabaseImplement.Models.Client", "Client") + .WithMany("ClientMessages") + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.Order", b => + { + b.HasOne("GarmentFactoryDatabaseImplement.Models.Client", "Client") + .WithMany("Orders") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("GarmentFactoryDatabaseImplement.Models.Implementer", "Implementer") + .WithMany("Orders") + .HasForeignKey("ImplementerId"); + + b.HasOne("GarmentFactoryDatabaseImplement.Models.Textile", "Textile") + .WithMany("Orders") + .HasForeignKey("TextileId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Client"); + + b.Navigation("Implementer"); + + b.Navigation("Textile"); + }); + + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.TextileComponent", b => + { + b.HasOne("GarmentFactoryDatabaseImplement.Models.Component", "Component") + .WithMany("TextileComponents") + .HasForeignKey("ComponentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("GarmentFactoryDatabaseImplement.Models.Textile", "Textile") + .WithMany("Components") + .HasForeignKey("TextileId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Component"); + + b.Navigation("Textile"); + }); + + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.Client", b => + { + b.Navigation("ClientMessages"); + + b.Navigation("Orders"); + }); + + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.Component", b => + { + b.Navigation("TextileComponents"); + }); + + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.Implementer", b => + { + b.Navigation("Orders"); + }); + + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.Textile", b => + { + b.Navigation("Components"); + + b.Navigation("Orders"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/GarmentFactory/GarmentFactoryDatabaseImplement/Migrations/20240511115922_MailCreate.cs b/GarmentFactory/GarmentFactoryDatabaseImplement/Migrations/20240511115922_MailCreate.cs new file mode 100644 index 0000000..175c9a1 --- /dev/null +++ b/GarmentFactory/GarmentFactoryDatabaseImplement/Migrations/20240511115922_MailCreate.cs @@ -0,0 +1,48 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace GarmentFactoryDatabaseImplement.Migrations +{ + /// + public partial class MailCreate : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "MessageInfos", + columns: table => new + { + MessageId = table.Column(type: "nvarchar(450)", nullable: false), + ClientId = table.Column(type: "int", nullable: true), + SenderName = table.Column(type: "nvarchar(max)", nullable: false), + DateDelivery = table.Column(type: "datetime2", nullable: false), + Subject = table.Column(type: "nvarchar(max)", nullable: false), + Body = table.Column(type: "nvarchar(max)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_MessageInfos", x => x.MessageId); + table.ForeignKey( + name: "FK_MessageInfos_Clients_ClientId", + column: x => x.ClientId, + principalTable: "Clients", + principalColumn: "Id"); + }); + + migrationBuilder.CreateIndex( + name: "IX_MessageInfos_ClientId", + table: "MessageInfos", + column: "ClientId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "MessageInfos"); + } + } +} diff --git a/GarmentFactory/GarmentFactoryDatabaseImplement/Migrations/GarmentFactoryDatabaseModelSnapshot.cs b/GarmentFactory/GarmentFactoryDatabaseImplement/Migrations/GarmentFactoryDatabaseModelSnapshot.cs index fedfaf9..96bc8e3 100644 --- a/GarmentFactory/GarmentFactoryDatabaseImplement/Migrations/GarmentFactoryDatabaseModelSnapshot.cs +++ b/GarmentFactory/GarmentFactoryDatabaseImplement/Migrations/GarmentFactoryDatabaseModelSnapshot.cs @@ -94,6 +94,36 @@ namespace GarmentFactoryDatabaseImplement.Migrations b.ToTable("Implementers"); }); + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.MessageInfo", b => + { + b.Property("MessageId") + .HasColumnType("nvarchar(450)"); + + b.Property("Body") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("int"); + + b.Property("DateDelivery") + .HasColumnType("datetime2"); + + b.Property("SenderName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Subject") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("MessageId"); + + b.HasIndex("ClientId"); + + b.ToTable("MessageInfos"); + }); + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -183,6 +213,15 @@ namespace GarmentFactoryDatabaseImplement.Migrations b.ToTable("TextileComponents"); }); + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.MessageInfo", b => + { + b.HasOne("GarmentFactoryDatabaseImplement.Models.Client", "Client") + .WithMany("ClientMessages") + .HasForeignKey("ClientId"); + + b.Navigation("Client"); + }); + modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.Order", b => { b.HasOne("GarmentFactoryDatabaseImplement.Models.Client", "Client") @@ -229,6 +268,8 @@ namespace GarmentFactoryDatabaseImplement.Migrations modelBuilder.Entity("GarmentFactoryDatabaseImplement.Models.Client", b => { + b.Navigation("ClientMessages"); + b.Navigation("Orders"); }); diff --git a/GarmentFactory/GarmentFactoryDatabaseImplement/Models/Client.cs b/GarmentFactory/GarmentFactoryDatabaseImplement/Models/Client.cs index d8c9e09..d53e791 100644 --- a/GarmentFactory/GarmentFactoryDatabaseImplement/Models/Client.cs +++ b/GarmentFactory/GarmentFactoryDatabaseImplement/Models/Client.cs @@ -26,7 +26,8 @@ namespace GarmentFactoryDatabaseImplement.Models [ForeignKey("ClientId")] public virtual List Orders { get; set; } = new(); - + [ForeignKey("ClientId")] + public virtual List ClientMessages { get; set; } = new(); public static Client? Create(ClientBindingModel model) { if (model == null) diff --git a/GarmentFactory/GarmentFactoryDatabaseImplement/Models/MessageInfo.cs b/GarmentFactory/GarmentFactoryDatabaseImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..fbdc758 --- /dev/null +++ b/GarmentFactory/GarmentFactoryDatabaseImplement/Models/MessageInfo.cs @@ -0,0 +1,63 @@ +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.ViewModels; +using GarmentFactoryDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations.Schema; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryDatabaseImplement.Models +{ + public class MessageInfo : IMessageInfoModel + { + [Key] + [DatabaseGenerated(DatabaseGeneratedOption.None)] + public string MessageId { get; set; } = string.Empty; + + public int? ClientId { get; set; } + + [Required] + public string SenderName { get; set; } = string.Empty; + + [Required] + public DateTime DateDelivery { get; set; } + + [Required] + public string Subject { get; set; } = string.Empty; + + [Required] + public string Body { get; set; } = string.Empty; + + public virtual Client? Client { get; set; } + + public static MessageInfo? Create(MessageInfoBindingModel? model) + { + if (model == null) + { + return null; + } + return new() + { + MessageId = model.MessageId, + ClientId = model.ClientId, + SenderName = model.SenderName, + DateDelivery = model.DateDelivery, + Subject = model.Subject, + Body = model.Body + }; + } + + public MessageInfoViewModel GetViewModel => new() + { + MessageId = MessageId, + ClientId = ClientId, + SenderName = SenderName, + DateDelivery = DateDelivery, + Subject = Subject, + Body = Body + }; + } +} diff --git a/GarmentFactory/GarmentFactoryDatabaseImplement/Models/Order.cs b/GarmentFactory/GarmentFactoryDatabaseImplement/Models/Order.cs index 3a3f8a5..04b0c70 100644 --- a/GarmentFactory/GarmentFactoryDatabaseImplement/Models/Order.cs +++ b/GarmentFactory/GarmentFactoryDatabaseImplement/Models/Order.cs @@ -82,6 +82,7 @@ namespace GarmentFactoryDatabaseImplement.Models Status = Status, DateCreate = DateCreate, DateImplement = DateImplement, + ClientEmail = Client.Email ?? string.Empty, TextileName = Textile.TextileName ?? string.Empty, ClientFIO = Client.ClientFIO ?? string.Empty, ImplementerFIO = Implementer?.ImplementerFIO ?? string.Empty diff --git a/GarmentFactory/GarmentFactoryFileImplement/DataFileSingleton.cs b/GarmentFactory/GarmentFactoryFileImplement/DataFileSingleton.cs index 02ec3ba..33473f5 100644 --- a/GarmentFactory/GarmentFactoryFileImplement/DataFileSingleton.cs +++ b/GarmentFactory/GarmentFactoryFileImplement/DataFileSingleton.cs @@ -16,11 +16,13 @@ namespace GarmentFactoryFileImplement private readonly string TextileFileName = "Textile.xml"; private readonly string ClientFileName = "Client.xml"; private readonly string ImplementerFileName = "Implementer.xml"; + private readonly string MessageInfoFileName = "MessageInfo.xml"; public List Components { get; private set; } public List Orders { get; private set; } public List Textils { get; private set; } public List Clients { get; private set; } public List Implementers { get; private set; } + public List Messages { get; private set; } public static DataFileSingleton GetInstance() { if (instance == null) @@ -34,6 +36,7 @@ namespace GarmentFactoryFileImplement public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement); public void SaveImplementers() => SaveData(Implementers, ImplementerFileName, "Implementers", x => x.GetXElement); public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", x => x.GetXElement); + public void SaveMessages() => SaveData(Orders, ImplementerFileName, "Messages", x => x.GetXElement); private DataFileSingleton() { Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!; @@ -41,6 +44,7 @@ namespace GarmentFactoryFileImplement 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(MessageInfoFileName, "MessageInfo", x => MessageInfo.Create(x)!)!; } private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) diff --git a/GarmentFactory/GarmentFactoryFileImplement/Implements/ClientStorage.cs b/GarmentFactory/GarmentFactoryFileImplement/Implements/ClientStorage.cs index a1457b7..7e067bf 100644 --- a/GarmentFactory/GarmentFactoryFileImplement/Implements/ClientStorage.cs +++ b/GarmentFactory/GarmentFactoryFileImplement/Implements/ClientStorage.cs @@ -48,6 +48,7 @@ namespace GarmentFactoryFileImplement.Implements return source.Clients .FirstOrDefault(x => (!string.IsNullOrEmpty(model.Email) && x.Email == model.Email && !string.IsNullOrEmpty(model.Password) && x.Password == model.Password) + || (!string.IsNullOrEmpty(model.Email) && x.Email == model.Email && string.IsNullOrEmpty(model.Password)) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; } diff --git a/GarmentFactory/GarmentFactoryFileImplement/Implements/MessageInfoStorage.cs b/GarmentFactory/GarmentFactoryFileImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..e4c3698 --- /dev/null +++ b/GarmentFactory/GarmentFactoryFileImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,63 @@ +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.SearchModels; +using GarmentFactoryContracts.StoragesContracts; +using GarmentFactoryContracts.ViewModels; +using GarmentFactoryFileImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryFileImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + private readonly DataFileSingleton _source; + + public MessageInfoStorage() + { + _source = DataFileSingleton.GetInstance(); + } + + public List GetFullList() + { + return _source.Messages + .Select(x => x.GetViewModel) + .ToList(); + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + if (!model.ClientId.HasValue) + { + return new(); + } + return _source.Messages + .Where(x => x.ClientId.HasValue && x.ClientId == model.ClientId) + .Select(x => x.GetViewModel) + .ToList(); + } + + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (string.IsNullOrEmpty(model.MessageId)) + { + return null; + } + return _source.Messages.FirstOrDefault(x => model.MessageId.Equals(x.MessageId))?.GetViewModel; + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = MessageInfo.Create(model); + if (newMessage == null) + { + return null; + } + _source.Messages.Add(newMessage); + _source.SaveMessages(); + return newMessage.GetViewModel; + } + } +} diff --git a/GarmentFactory/GarmentFactoryFileImplement/Models/MessageInfo.cs b/GarmentFactory/GarmentFactoryFileImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..2738bfd --- /dev/null +++ b/GarmentFactory/GarmentFactoryFileImplement/Models/MessageInfo.cs @@ -0,0 +1,80 @@ +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.ViewModels; +using GarmentFactoryDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace GarmentFactoryFileImplement.Models +{ + public class MessageInfo : IMessageInfoModel + { + public string MessageId { get; private set; } = string.Empty; + + public int? ClientId { get; private set; } + + public string SenderName { get; private set; } = string.Empty; + + public DateTime DateDelivery { get; private set; } = DateTime.Now; + + public string Subject { get; private set; } = string.Empty; + + public string Body { get; private set; } = string.Empty; + + public static MessageInfo? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + MessageId = model.MessageId, + ClientId = model.ClientId, + SenderName = model.SenderName, + DateDelivery = model.DateDelivery, + Subject = model.Subject, + Body = model.Body + }; + } + + public static MessageInfo? Create(XElement element) + { + if (element == null) + { + return null; + } + return new() + { + MessageId = element.Attribute("MessageId")!.Value, + ClientId = Convert.ToInt32(element.Element("ClientId")!.Value), + SenderName = element.Element("SenderName")!.Value, + DateDelivery = Convert.ToDateTime(element.Element("DateDelivery")!.Value), + Subject = element.Element("Subject")!.Value, + Body = element.Element("Body")!.Value + }; + } + + public MessageInfoViewModel GetViewModel => new() + { + MessageId = MessageId, + ClientId = ClientId, + SenderName = SenderName, + DateDelivery = DateDelivery, + Subject = Subject, + Body = Body + }; + + public XElement GetXElement => new("MessageInfo", + new XAttribute("MessageId", MessageId), + new XElement("ClientId", ClientId), + new XElement("SenderName", SenderName), + new XElement("DateDelivery", DateDelivery), + new XElement("Subject", Subject), + new XElement("Body", Body) + ); + } +} diff --git a/GarmentFactory/GarmentFactoryListImplement/DataListSingleton.cs b/GarmentFactory/GarmentFactoryListImplement/DataListSingleton.cs index 9a8163f..1611fb4 100644 --- a/GarmentFactory/GarmentFactoryListImplement/DataListSingleton.cs +++ b/GarmentFactory/GarmentFactoryListImplement/DataListSingleton.cs @@ -15,6 +15,7 @@ namespace GarmentFactoryListImplement public List Textiles { get; set; } public List Clients { get; set; } public List Implementers { get; set; } + public List Messages { get; set; } private DataListSingleton() { Components = new List(); @@ -22,6 +23,7 @@ namespace GarmentFactoryListImplement Textiles = new List(); Clients = new List(); Implementers = new List(); + Messages = new List(); } public static DataListSingleton GetInstance() { diff --git a/GarmentFactory/GarmentFactoryListImplement/Implements/ClientStorage.cs b/GarmentFactory/GarmentFactoryListImplement/Implements/ClientStorage.cs index ae4f019..d53e613 100644 --- a/GarmentFactory/GarmentFactoryListImplement/Implements/ClientStorage.cs +++ b/GarmentFactory/GarmentFactoryListImplement/Implements/ClientStorage.cs @@ -55,8 +55,8 @@ namespace GarmentFactoryListImplement.Implements } foreach (var client in _source.Clients) { - if ((!string.IsNullOrEmpty(model.Email) && client.Email == model.Email - && !string.IsNullOrEmpty(model.Password) && client.Password == model.Password) + if ((!string.IsNullOrEmpty(model.Email) && client.Email == model.Email && !string.IsNullOrEmpty(model.Password) && client.Password == model.Password) + || (!string.IsNullOrEmpty(model.Email) && client.Email == model.Email && string.IsNullOrEmpty(model.Password)) || (model.Id.HasValue && client.Id == model.Id)) { return client.GetViewModel; diff --git a/GarmentFactory/GarmentFactoryListImplement/Implements/MessageInfoStorage.cs b/GarmentFactory/GarmentFactoryListImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..e5f715b --- /dev/null +++ b/GarmentFactory/GarmentFactoryListImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,77 @@ +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.SearchModels; +using GarmentFactoryContracts.StoragesContracts; +using GarmentFactoryContracts.ViewModels; +using GarmentFactoryListImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryListImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + private readonly DataListSingleton _source; + + public MessageInfoStorage() + { + _source = DataListSingleton.GetInstance(); + } + + public List GetFullList() + { + var result = new List(); + foreach (var message in _source.Messages) + { + result.Add(message.GetViewModel); + } + return result; + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + var result = new List(); + if (!model.ClientId.HasValue) + { + return result; + } + foreach (var message in _source.Messages) + { + if (message.ClientId.HasValue && message.ClientId == model.ClientId) + { + result.Add(message.GetViewModel); + } + } + return result; + } + + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (string.IsNullOrEmpty(model.MessageId)) + { + return null; + } + foreach (var message in _source.Messages) + { + if (model.MessageId.Equals(message.MessageId)) + { + return message.GetViewModel; + } + } + return null; + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = MessageInfo.Create(model); + if (newMessage == null) + { + return null; + } + _source.Messages.Add(newMessage); + return newMessage.GetViewModel; + } + } +} diff --git a/GarmentFactory/GarmentFactoryListImplement/Models/MessageInfo.cs b/GarmentFactory/GarmentFactoryListImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..c6ab6bf --- /dev/null +++ b/GarmentFactory/GarmentFactoryListImplement/Models/MessageInfo.cs @@ -0,0 +1,53 @@ +using GarmentFactoryContracts.BindingModels; +using GarmentFactoryContracts.ViewModels; +using GarmentFactoryDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GarmentFactoryListImplement.Models +{ + public class MessageInfo : IMessageInfoModel + { + public string MessageId { get; private set; } = string.Empty; + + public int? ClientId { get; private set; } + + public string SenderName { get; private set; } = string.Empty; + + public DateTime DateDelivery { get; private set; } = DateTime.Now; + + public string Subject { get; private set; } = string.Empty; + + public string Body { get; private set; } = string.Empty; + + public static MessageInfo? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + MessageId = model.MessageId, + ClientId = model.ClientId, + SenderName = model.SenderName, + DateDelivery = model.DateDelivery, + Subject = model.Subject, + Body = model.Body + }; + } + + public MessageInfoViewModel GetViewModel => new() + { + MessageId = MessageId, + ClientId = ClientId, + SenderName = SenderName, + DateDelivery = DateDelivery, + Subject = Subject, + Body = Body + }; + } +} diff --git a/GarmentFactory/GarmentFactoryRestApi/Controllers/ClientController.cs b/GarmentFactory/GarmentFactoryRestApi/Controllers/ClientController.cs index 7313748..5ef946b 100644 --- a/GarmentFactory/GarmentFactoryRestApi/Controllers/ClientController.cs +++ b/GarmentFactory/GarmentFactoryRestApi/Controllers/ClientController.cs @@ -13,11 +13,13 @@ namespace GarmentFactoryRestApi.Controllers private readonly ILogger _logger; private readonly IClientLogic _logic; + private readonly IMessageInfoLogic _mailLogic; - public ClientController(IClientLogic logic, ILogger logger) + public ClientController(IClientLogic logic, ILogger logger, IMessageInfoLogic mailLogic) { _logger = logger; _logic = logic; + _mailLogic = mailLogic; } [HttpGet] @@ -65,5 +67,21 @@ namespace GarmentFactoryRestApi.Controllers throw; } } + [HttpGet] + public List? GetMessages(int clientId) + { + try + { + return _mailLogic.ReadList(new MessageInfoSearchModel + { + ClientId = clientId + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error receiving client's emails"); + throw; + } + } } } diff --git a/GarmentFactory/GarmentFactoryRestApi/Program.cs b/GarmentFactory/GarmentFactoryRestApi/Program.cs index c42e937..0f4e319 100644 --- a/GarmentFactory/GarmentFactoryRestApi/Program.cs +++ b/GarmentFactory/GarmentFactoryRestApi/Program.cs @@ -2,6 +2,8 @@ using GarmentFactoryBusinessLogic.BusinessLogics; using GarmentFactoryContracts.BusinessLogicsContracts; using GarmentFactoryContracts.StoragesContracts; using GarmentFactoryDatabaseImplement.Implements; +using GarmentFactoryBusinessLogic.MailWorker; +using GarmentFactoryContracts.BindingModels; using Microsoft.OpenApi.Models; var builder = WebApplication.CreateBuilder(args); builder.Logging.SetMinimumLevel(LogLevel.Trace); @@ -10,9 +12,13 @@ builder.Logging.AddLog4Net("log4net.config"); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddTransient(); + +builder.Services.AddSingleton(); builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle @@ -27,6 +33,16 @@ 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/GarmentFactory/GarmentFactoryRestApi/appsettings.json b/GarmentFactory/GarmentFactoryRestApi/appsettings.json index 10f68b8..6554cf8 100644 --- a/GarmentFactory/GarmentFactoryRestApi/appsettings.json +++ b/GarmentFactory/GarmentFactoryRestApi/appsettings.json @@ -5,5 +5,11 @@ "Microsoft.AspNetCore": "Warning" } }, - "AllowedHosts": "*" + "AllowedHosts": "*", + "SmtpClientHost": "smtp.gmail.com", + "SmtpClientPort": "587", + "PopHost": "pop.gmail.com", + "PopPort": "995", + "MailLogin": "shanyginalexandr228@gmail.com", + "MailPassword": "h h q w s l p h d q o h h j t g" } diff --git a/GarmentFactory/GarmentFactoryView/App.config b/GarmentFactory/GarmentFactoryView/App.config new file mode 100644 index 0000000..da7e4a8 --- /dev/null +++ b/GarmentFactory/GarmentFactoryView/App.config @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/GarmentFactory/GarmentFactoryView/FormMails.Designer.cs b/GarmentFactory/GarmentFactoryView/FormMails.Designer.cs new file mode 100644 index 0000000..15d471b --- /dev/null +++ b/GarmentFactory/GarmentFactoryView/FormMails.Designer.cs @@ -0,0 +1,68 @@ +namespace GarmentFactoryView +{ + 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.AllowUserToAddRows = false; + dataGridView.AllowUserToDeleteRows = false; + dataGridView.BackgroundColor = SystemColors.ControlLightLight; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Dock = DockStyle.Fill; + dataGridView.Location = new Point(0, 0); + dataGridView.Name = "dataGridView"; + dataGridView.ReadOnly = true; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 29; + dataGridView.Size = new Size(838, 285); + dataGridView.TabIndex = 0; + // + // FormMails + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(838, 285); + Controls.Add(dataGridView); + Name = "FormMails"; + StartPosition = FormStartPosition.CenterScreen; + Text = "Письма"; + Load += FormMails_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView; + } +} \ No newline at end of file diff --git a/GarmentFactory/GarmentFactoryView/FormMails.cs b/GarmentFactory/GarmentFactoryView/FormMails.cs new file mode 100644 index 0000000..df4c265 --- /dev/null +++ b/GarmentFactory/GarmentFactoryView/FormMails.cs @@ -0,0 +1,45 @@ +using Microsoft.Extensions.Logging; +using GarmentFactoryContracts.BusinessLogicsContracts; + +namespace GarmentFactoryView +{ + 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) + { + LoadData(); + } + + private void LoadData() + { + try + { + var list = _logic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["MessageId"].Visible = false; + dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + _logger.LogInformation("Messages loading"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Messages loading error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } +} diff --git a/GarmentFactory/GarmentFactoryView/FormMails.resx b/GarmentFactory/GarmentFactoryView/FormMails.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/GarmentFactory/GarmentFactoryView/FormMails.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/GarmentFactory/GarmentFactoryView/FormMain.Designer.cs b/GarmentFactory/GarmentFactoryView/FormMain.Designer.cs index aa35f44..1f2856a 100644 --- a/GarmentFactory/GarmentFactoryView/FormMain.Designer.cs +++ b/GarmentFactory/GarmentFactoryView/FormMain.Designer.cs @@ -20,185 +20,193 @@ base.Dispose(disposing); } - #region Windows Form Designer generated code + #region Windows Form Designer generated code - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - menuStrip = new MenuStrip(); - справочникиToolStripMenuItem = new ToolStripMenuItem(); - компонентыToolStripMenuItem = new ToolStripMenuItem(); - изделиеToolStripMenuItem = new ToolStripMenuItem(); - клиентыToolStripMenuItem = new ToolStripMenuItem(); - исполнителиToolStripMenuItem = new ToolStripMenuItem(); - отчетыToolStripMenuItem = new ToolStripMenuItem(); - списокПродуктаToolStripMenuItem = new ToolStripMenuItem(); - компонентыПоИзделиямToolStripMenuItem = new ToolStripMenuItem(); - списокЗаказовToolStripMenuItem = new ToolStripMenuItem(); - запускРаботToolStripMenuItem = new ToolStripMenuItem(); - dataGridView = new DataGridView(); - buttonCreateOrder = new Button(); - buttonIssuedOrder = new Button(); - buttonUpd = new Button(); - menuStrip.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); - SuspendLayout(); - // - // menuStrip - // - menuStrip.ImageScalingSize = new Size(20, 20); - menuStrip.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчетыToolStripMenuItem, запускРаботToolStripMenuItem }); - menuStrip.Location = new Point(0, 0); - menuStrip.Name = "menuStrip"; - menuStrip.Size = new Size(1447, 28); - menuStrip.TabIndex = 0; - menuStrip.Text = "menuStrip1"; - // - // справочникиToolStripMenuItem - // - справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, изделиеToolStripMenuItem, клиентыToolStripMenuItem, исполнителиToolStripMenuItem }); - справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; - справочникиToolStripMenuItem.Size = new Size(117, 24); - справочникиToolStripMenuItem.Text = "Справочники"; - // - // компонентыToolStripMenuItem - // - компонентыToolStripMenuItem.Name = "компонентыToolStripMenuItem"; - компонентыToolStripMenuItem.Size = new Size(185, 26); - компонентыToolStripMenuItem.Text = "Компоненты"; - компонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click; - // - // изделиеToolStripMenuItem - // - изделиеToolStripMenuItem.Name = "изделиеToolStripMenuItem"; - изделиеToolStripMenuItem.Size = new Size(185, 26); - изделиеToolStripMenuItem.Text = "Изделие"; - изделиеToolStripMenuItem.Click += ИзделиеToolStripMenuItem_Click; - // - // клиентыToolStripMenuItem - // - клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; - клиентыToolStripMenuItem.Size = new Size(185, 26); - клиентыToolStripMenuItem.Text = "Клиенты"; - клиентыToolStripMenuItem.Click += КлиентыToolStripMenuItem_Click; - // - // исполнителиToolStripMenuItem - // - исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; - исполнителиToolStripMenuItem.Size = new Size(185, 26); - исполнителиToolStripMenuItem.Text = "Исполнители"; - исполнителиToolStripMenuItem.Click += ИсполнителиToolStripMenuItem_Click; - // - // отчетыToolStripMenuItem - // - отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокПродуктаToolStripMenuItem, компонентыПоИзделиямToolStripMenuItem, списокЗаказовToolStripMenuItem }); - отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem"; - отчетыToolStripMenuItem.Size = new Size(73, 24); - отчетыToolStripMenuItem.Text = "Отчеты"; - // - // списокПродуктаToolStripMenuItem - // - списокПродуктаToolStripMenuItem.Name = "списокПродуктаToolStripMenuItem"; - списокПродуктаToolStripMenuItem.Size = new Size(276, 26); - списокПродуктаToolStripMenuItem.Text = "Список изделия"; - списокПродуктаToolStripMenuItem.Click += СписокИзделияToolStripMenuItem_Click; - // - // компонентыПоИзделиямToolStripMenuItem - // - компонентыПоИзделиямToolStripMenuItem.Name = "компонентыПоИзделиямToolStripMenuItem"; - компонентыПоИзделиямToolStripMenuItem.Size = new Size(276, 26); - компонентыПоИзделиямToolStripMenuItem.Text = "Компоненты по изделиям"; - компонентыПоИзделиямToolStripMenuItem.Click += КомпонентыПоИзделиямToolStripMenuItem_Click; - // - // списокЗаказовToolStripMenuItem - // - списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem"; - списокЗаказовToolStripMenuItem.Size = new Size(276, 26); - списокЗаказовToolStripMenuItem.Text = "Список заказов"; - списокЗаказовToolStripMenuItem.Click += СписокЗаказовToolStripMenuItem_Click; - // - // запускРаботToolStripMenuItem - // - запускРаботToolStripMenuItem.Name = "запускРаботToolStripMenuItem"; - запускРаботToolStripMenuItem.Size = new Size(114, 24); - запускРаботToolStripMenuItem.Text = "Запуск работ"; - запускРаботToolStripMenuItem.Click += ЗапускРаботToolStripMenuItem_Click; - // - // dataGridView - // - dataGridView.AllowUserToAddRows = false; - dataGridView.AllowUserToDeleteRows = false; - dataGridView.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - dataGridView.BackgroundColor = SystemColors.ControlLightLight; - dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; - dataGridView.Location = new Point(0, 37); - dataGridView.Name = "dataGridView"; - dataGridView.ReadOnly = true; - dataGridView.RowHeadersVisible = false; - dataGridView.RowHeadersWidth = 51; - dataGridView.RowTemplate.Height = 29; - dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; - dataGridView.Size = new Size(1213, 427); - dataGridView.TabIndex = 1; - // - // buttonCreateOrder - // - buttonCreateOrder.Location = new Point(1236, 127); - buttonCreateOrder.Name = "buttonCreateOrder"; - buttonCreateOrder.Size = new Size(199, 36); - buttonCreateOrder.TabIndex = 2; - buttonCreateOrder.Text = "Создать заказ"; - buttonCreateOrder.UseVisualStyleBackColor = true; - buttonCreateOrder.Click += ButtonCreateOrder_Click; - // - // buttonIssuedOrder - // - buttonIssuedOrder.Location = new Point(1236, 211); - buttonIssuedOrder.Name = "buttonIssuedOrder"; - buttonIssuedOrder.Size = new Size(199, 36); - buttonIssuedOrder.TabIndex = 5; - buttonIssuedOrder.Text = "Заказ выдан"; - buttonIssuedOrder.UseVisualStyleBackColor = true; - buttonIssuedOrder.Click += ButtonIssuedOrder_Click; - // - // buttonUpd - // - buttonUpd.Location = new Point(1236, 291); - buttonUpd.Name = "buttonUpd"; - buttonUpd.Size = new Size(197, 36); - buttonUpd.TabIndex = 6; - buttonUpd.Text = "Обновить список"; - buttonUpd.UseVisualStyleBackColor = true; - buttonUpd.Click += ButtonUpd_Click; - // - // FormMain - // - AutoScaleDimensions = new SizeF(8F, 20F); - AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1447, 463); - Controls.Add(buttonUpd); - Controls.Add(buttonIssuedOrder); - Controls.Add(buttonCreateOrder); - Controls.Add(dataGridView); - Controls.Add(menuStrip); - MainMenuStrip = menuStrip; - Name = "FormMain"; - StartPosition = FormStartPosition.CenterScreen; - Text = "Текстильная фабрика"; - Load += FormMain_Load; - menuStrip.ResumeLayout(false); - menuStrip.PerformLayout(); - ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); - ResumeLayout(false); - PerformLayout(); - } + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + menuStrip = new MenuStrip(); + справочникиToolStripMenuItem = new ToolStripMenuItem(); + компонентыToolStripMenuItem = new ToolStripMenuItem(); + изделиеToolStripMenuItem = new ToolStripMenuItem(); + клиентыToolStripMenuItem = new ToolStripMenuItem(); + исполнителиToolStripMenuItem = new ToolStripMenuItem(); + отчетыToolStripMenuItem = new ToolStripMenuItem(); + списокПродуктаToolStripMenuItem = new ToolStripMenuItem(); + компонентыПоИзделиямToolStripMenuItem = new ToolStripMenuItem(); + списокЗаказовToolStripMenuItem = new ToolStripMenuItem(); + запускРаботToolStripMenuItem = new ToolStripMenuItem(); + dataGridView = new DataGridView(); + buttonCreateOrder = new Button(); + buttonIssuedOrder = new Button(); + buttonUpd = new Button(); + почтаToolStripMenuItem = new ToolStripMenuItem(); + menuStrip.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // menuStrip + // + menuStrip.ImageScalingSize = new Size(20, 20); + menuStrip.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчетыToolStripMenuItem, запускРаботToolStripMenuItem, почтаToolStripMenuItem }); + menuStrip.Location = new Point(0, 0); + menuStrip.Name = "menuStrip"; + menuStrip.Size = new Size(1447, 28); + menuStrip.TabIndex = 0; + menuStrip.Text = "menuStrip1"; + // + // справочникиToolStripMenuItem + // + справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, изделиеToolStripMenuItem, клиентыToolStripMenuItem, исполнителиToolStripMenuItem }); + справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; + справочникиToolStripMenuItem.Size = new Size(117, 24); + справочникиToolStripMenuItem.Text = "Справочники"; + // + // компонентыToolStripMenuItem + // + компонентыToolStripMenuItem.Name = "компонентыToolStripMenuItem"; + компонентыToolStripMenuItem.Size = new Size(185, 26); + компонентыToolStripMenuItem.Text = "Компоненты"; + компонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click; + // + // изделиеToolStripMenuItem + // + изделиеToolStripMenuItem.Name = "изделиеToolStripMenuItem"; + изделиеToolStripMenuItem.Size = new Size(185, 26); + изделиеToolStripMenuItem.Text = "Изделие"; + изделиеToolStripMenuItem.Click += ИзделиеToolStripMenuItem_Click; + // + // клиентыToolStripMenuItem + // + клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; + клиентыToolStripMenuItem.Size = new Size(185, 26); + клиентыToolStripMenuItem.Text = "Клиенты"; + клиентыToolStripMenuItem.Click += КлиентыToolStripMenuItem_Click; + // + // исполнителиToolStripMenuItem + // + исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; + исполнителиToolStripMenuItem.Size = new Size(185, 26); + исполнителиToolStripMenuItem.Text = "Исполнители"; + исполнителиToolStripMenuItem.Click += ИсполнителиToolStripMenuItem_Click; + // + // отчетыToolStripMenuItem + // + отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокПродуктаToolStripMenuItem, компонентыПоИзделиямToolStripMenuItem, списокЗаказовToolStripMenuItem }); + отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem"; + отчетыToolStripMenuItem.Size = new Size(73, 24); + отчетыToolStripMenuItem.Text = "Отчеты"; + // + // списокПродуктаToolStripMenuItem + // + списокПродуктаToolStripMenuItem.Name = "списокПродуктаToolStripMenuItem"; + списокПродуктаToolStripMenuItem.Size = new Size(276, 26); + списокПродуктаToolStripMenuItem.Text = "Список изделия"; + списокПродуктаToolStripMenuItem.Click += СписокИзделияToolStripMenuItem_Click; + // + // компонентыПоИзделиямToolStripMenuItem + // + компонентыПоИзделиямToolStripMenuItem.Name = "компонентыПоИзделиямToolStripMenuItem"; + компонентыПоИзделиямToolStripMenuItem.Size = new Size(276, 26); + компонентыПоИзделиямToolStripMenuItem.Text = "Компоненты по изделиям"; + компонентыПоИзделиямToolStripMenuItem.Click += КомпонентыПоИзделиямToolStripMenuItem_Click; + // + // списокЗаказовToolStripMenuItem + // + списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem"; + списокЗаказовToolStripMenuItem.Size = new Size(276, 26); + списокЗаказовToolStripMenuItem.Text = "Список заказов"; + списокЗаказовToolStripMenuItem.Click += СписокЗаказовToolStripMenuItem_Click; + // + // запускРаботToolStripMenuItem + // + запускРаботToolStripMenuItem.Name = "запускРаботToolStripMenuItem"; + запускРаботToolStripMenuItem.Size = new Size(114, 24); + запускРаботToolStripMenuItem.Text = "Запуск работ"; + запускРаботToolStripMenuItem.Click += ЗапускРаботToolStripMenuItem_Click; + // + // dataGridView + // + dataGridView.AllowUserToAddRows = false; + dataGridView.AllowUserToDeleteRows = false; + dataGridView.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + dataGridView.BackgroundColor = SystemColors.ControlLightLight; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(0, 37); + dataGridView.Name = "dataGridView"; + dataGridView.ReadOnly = true; + dataGridView.RowHeadersVisible = false; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 29; + dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; + dataGridView.Size = new Size(1213, 427); + dataGridView.TabIndex = 1; + // + // buttonCreateOrder + // + buttonCreateOrder.Location = new Point(1236, 127); + buttonCreateOrder.Name = "buttonCreateOrder"; + buttonCreateOrder.Size = new Size(199, 36); + buttonCreateOrder.TabIndex = 2; + buttonCreateOrder.Text = "Создать заказ"; + buttonCreateOrder.UseVisualStyleBackColor = true; + buttonCreateOrder.Click += ButtonCreateOrder_Click; + // + // buttonIssuedOrder + // + buttonIssuedOrder.Location = new Point(1236, 211); + buttonIssuedOrder.Name = "buttonIssuedOrder"; + buttonIssuedOrder.Size = new Size(199, 36); + buttonIssuedOrder.TabIndex = 5; + buttonIssuedOrder.Text = "Заказ выдан"; + buttonIssuedOrder.UseVisualStyleBackColor = true; + buttonIssuedOrder.Click += ButtonIssuedOrder_Click; + // + // buttonUpd + // + buttonUpd.Location = new Point(1236, 291); + buttonUpd.Name = "buttonUpd"; + buttonUpd.Size = new Size(197, 36); + buttonUpd.TabIndex = 6; + buttonUpd.Text = "Обновить список"; + buttonUpd.UseVisualStyleBackColor = true; + buttonUpd.Click += ButtonUpd_Click; + // + // почтаToolStripMenuItem + // + почтаToolStripMenuItem.Name = "почтаToolStripMenuItem"; + почтаToolStripMenuItem.Size = new Size(65, 24); + почтаToolStripMenuItem.Text = "Почта"; + почтаToolStripMenuItem.Click += ПочтаToolStripMenuItem_Click; + // + // FormMain + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(1447, 463); + Controls.Add(buttonUpd); + Controls.Add(buttonIssuedOrder); + Controls.Add(buttonCreateOrder); + Controls.Add(dataGridView); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; + Name = "FormMain"; + StartPosition = FormStartPosition.CenterScreen; + Text = "Текстильная фабрика"; + Load += FormMain_Load; + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + PerformLayout(); + } - #endregion + #endregion - private MenuStrip menuStrip; + private MenuStrip menuStrip; private ToolStripMenuItem справочникиToolStripMenuItem; private ToolStripMenuItem компонентыToolStripMenuItem; private ToolStripMenuItem изделиеToolStripMenuItem; @@ -213,5 +221,6 @@ private ToolStripMenuItem клиентыToolStripMenuItem; private ToolStripMenuItem запускРаботToolStripMenuItem; private ToolStripMenuItem исполнителиToolStripMenuItem; - } + private ToolStripMenuItem почтаToolStripMenuItem; + } } \ No newline at end of file diff --git a/GarmentFactory/GarmentFactoryView/FormMain.cs b/GarmentFactory/GarmentFactoryView/FormMain.cs index 737600d..61d5ead 100644 --- a/GarmentFactory/GarmentFactoryView/FormMain.cs +++ b/GarmentFactory/GarmentFactoryView/FormMain.cs @@ -13,157 +13,167 @@ using Microsoft.Extensions.Logging; namespace GarmentFactoryView { - public partial class FormMain : Form - { - private readonly ILogger _logger; - private readonly IOrderLogic _orderLogic; - private readonly IReportLogic _reportLogic; - private readonly IWorkProcess _workProcess; - public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess) - { - InitializeComponent(); - _logger = logger; - _orderLogic = orderLogic; - _reportLogic = reportLogic; - _workProcess = workProcess; - } + public partial class FormMain : Form + { + private readonly ILogger _logger; + private readonly IOrderLogic _orderLogic; + private readonly IReportLogic _reportLogic; + private readonly IWorkProcess _workProcess; + public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess) + { + InitializeComponent(); + _logger = logger; + _orderLogic = orderLogic; + _reportLogic = reportLogic; + _workProcess = workProcess; + } - private void FormMain_Load(object sender, EventArgs e) - { - LoadData(); - } - private void LoadData() - { - try - { - var list = _orderLogic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["TextileId"].Visible = false; - dataGridView.Columns["TextileName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - dataGridView.Columns["ClientId"].Visible = false; - dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - dataGridView.Columns["ImplementerId"].Visible = false; - dataGridView.Columns["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } - _logger.LogInformation("Загрузка заказов"); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки заказов"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - private void КомпонентыToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormComponents)); - if (service is FormComponents form) - { - form.ShowDialog(); - } - } + private void FormMain_Load(object sender, EventArgs e) + { + LoadData(); + } + private void LoadData() + { + try + { + var list = _orderLogic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["TextileId"].Visible = false; + dataGridView.Columns["TextileName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + dataGridView.Columns["ImplementerId"].Visible = false; + dataGridView.Columns["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + dataGridView.Columns["ClientEmail"].Visible = false; + } + _logger.LogInformation("Загрузка заказов"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки заказов"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + private void КомпонентыToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormComponents)); + if (service is FormComponents form) + { + form.ShowDialog(); + } + } - private void ИзделиеToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormTextiles)); - if (service is FormTextiles form) - { - form.ShowDialog(); - } - } + private void ИзделиеToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormTextiles)); + if (service is FormTextiles form) + { + form.ShowDialog(); + } + } - private void ButtonCreateOrder_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); - if (service is FormCreateOrder form) - { - form.ShowDialog(); - LoadData(); - } + private void ButtonCreateOrder_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); + if (service is FormCreateOrder form) + { + form.ShowDialog(); + LoadData(); + } - } + } - private void ButtonIssuedOrder_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id); - try - { - var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel { Id = id }); - if (!operationResult) - { - throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); - } - _logger.LogInformation("Заказ №{id} выдан", id); - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка отметки о выдачи заказа"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, - MessageBoxIcon.Error); - } - } + private void ButtonIssuedOrder_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id); + try + { + var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel { Id = id }); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + _logger.LogInformation("Заказ №{id} выдан", id); + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка отметки о выдачи заказа"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } - } - private void ButtonUpd_Click(object sender, EventArgs e) - { - LoadData(); - } + } + private void ButtonUpd_Click(object sender, EventArgs e) + { + LoadData(); + } - private void СписокИзделияToolStripMenuItem_Click(object sender, EventArgs e) - { - using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; - if (dialog.ShowDialog() == DialogResult.OK) - { - _reportLogic.SaveTextilesToWordFile(new ReportBindingModel { FileName = dialog.FileName }); - MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); - } - } + private void СписокИзделияToolStripMenuItem_Click(object sender, EventArgs e) + { + using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; + if (dialog.ShowDialog() == DialogResult.OK) + { + _reportLogic.SaveTextilesToWordFile(new ReportBindingModel { FileName = dialog.FileName }); + MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } - private void КомпонентыПоИзделиямToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormReportTextileComponents)); - if (service is FormReportTextileComponents form) - { - form.ShowDialog(); - } - } + private void КомпонентыПоИзделиямToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReportTextileComponents)); + if (service is FormReportTextileComponents form) + { + form.ShowDialog(); + } + } - private void СписокЗаказовToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders)); - if (service is FormReportOrders form) - { - form.ShowDialog(); - } - } + private void СписокЗаказовToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders)); + if (service is FormReportOrders form) + { + form.ShowDialog(); + } + } - private void КлиентыToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormClients)); - if (service is FormClients form) - { - form.ShowDialog(); - } - } + private void КлиентыToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormClients)); + if (service is FormClients form) + { + form.ShowDialog(); + } + } - private void ЗапускРаботToolStripMenuItem_Click(object sender, EventArgs e) - { - _workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic); - MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); - } + private void ЗапускРаботToolStripMenuItem_Click(object sender, EventArgs e) + { + _workProcess.DoWork((Program.ServiceProvider?.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(FormImplementers)); - if (service is FormImplementers form) - { - form.ShowDialog(); - } - } - } + private void ИсполнителиToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormImplementers)); + if (service is FormImplementers form) + { + form.ShowDialog(); + } + } + + 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/GarmentFactory/GarmentFactoryView/Program.cs b/GarmentFactory/GarmentFactoryView/Program.cs index f073195..3398cfe 100644 --- a/GarmentFactory/GarmentFactoryView/Program.cs +++ b/GarmentFactory/GarmentFactoryView/Program.cs @@ -8,6 +8,8 @@ using GarmentFactoryDatabaseImplement.Implements; using GarmentFactoryBusinessLogic.OfficePackage.Implements; using GarmentFactoryBusinessLogic.OfficePackage; using System.Drawing; +using GarmentFactoryBusinessLogic.MailWorker; +using GarmentFactoryContracts.BindingModels; namespace GarmentFactoryView { @@ -22,7 +24,27 @@ namespace GarmentFactoryView 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, "Mails Problem"); + } + Application.Run(_serviceProvider.GetRequiredService()); } private static void ConfigureServices(ServiceCollection services) { @@ -36,16 +58,19 @@ namespace GarmentFactoryView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); - services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); - services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddSingleton(); - services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -60,7 +85,9 @@ namespace GarmentFactoryView services.AddTransient(); services.AddTransient(); services.AddTransient(); - } + services.AddTransient(); - } + } + private static void MailCheck(object obj) => ServiceProvider?.GetService()?.MailCheck(); + } }