Лаб7-Получение и отправление писем работает.

This commit is contained in:
Артем Харламов 2023-05-30 22:13:03 +04:00
parent d1eee31e9a
commit 91423f07f6
20 changed files with 819 additions and 70 deletions

View File

@ -8,6 +8,7 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="DocumentFormat.OpenXml" Version="2.20.0" /> <PackageReference Include="DocumentFormat.OpenXml" Version="2.20.0" />
<PackageReference Include="MailKit" Version="4.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" /> <PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.2.3" /> <PackageReference Include="NLog.Extensions.Logging" Version="5.2.3" />
<PackageReference Include="PDFsharp-MigraDoc" Version="1.50.5147" /> <PackageReference Include="PDFsharp-MigraDoc" Version="1.50.5147" />

View File

@ -17,8 +17,6 @@ namespace AbstractFoodOrdersBusinessLogic.BusinessLogics
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IClientStorage _clientStorage; private readonly IClientStorage _clientStorage;
private Regex validateEmailRegex = new Regex("^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$");
private Regex validatePasswordRegex = new Regex("^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).(?=.*?[#?!@$%^&*-]).{10,50}$");
public ClientLogic(ILogger<ClientLogic> logger, IClientStorage clientStorage) public ClientLogic(ILogger<ClientLogic> logger, IClientStorage clientStorage)
{ {
@ -111,13 +109,14 @@ namespace AbstractFoodOrdersBusinessLogic.BusinessLogics
{ {
throw new ArgumentNullException("Нет электронной почты клиента", nameof(model.Email)); throw new ArgumentNullException("Нет электронной почты клиента", nameof(model.Email));
} }
if (!validateEmailRegex.IsMatch(model.Email)) if (!Regex.IsMatch(model.Email, @"^[-\w.]+@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,4}$"))
{ {
throw new InvalidOperationException("Почта введена некорректно!"); throw new ArgumentNullException("Введенное не является адресом электронной почты", nameof(model.Email));
} }
if (!validatePasswordRegex.IsMatch(model.Password)) if (/*model.Password.Length < 10 ||*/ model.Password.Length > 50 /*||
!Regex.IsMatch(model.Password, @"^((\w+\d+\W+)|(\w+\W+\d+)|(\d+\w+\W+)|(\d+\W+\w+)|(\W+\w+\d+)|(\W+\d+\w+))[\w\d\W]*$")*/)
{ {
throw new InvalidOperationException("Пароль не удовлетворяет требованиям"); throw new ArgumentNullException("Пароль не соответсвует требованиям безопасности", nameof(model.Password));
} }
_logger.LogInformation("Client. ClientFIO:{ClientFIO}. Password:{Password}. Email:{Email}. Id:{Id}", model.ClientFIO, model.Password, model.Email, model.Id); _logger.LogInformation("Client. ClientFIO:{ClientFIO}. Password:{Password}. Email:{Email}. Id:{Id}", model.ClientFIO, model.Password, model.Email, model.Id);
var element = _clientStorage.GetElement(new ClientSearchModel var element = _clientStorage.GetElement(new ClientSearchModel

View File

@ -1,4 +1,5 @@
using AbstractFoodOrdersContracts.BindingModels; using AbstractFoodOrdersBusinessLogic.MailWorker;
using AbstractFoodOrdersContracts.BindingModels;
using AbstractFoodOrdersContracts.BusinessLogicsContracts; using AbstractFoodOrdersContracts.BusinessLogicsContracts;
using AbstractFoodOrdersContracts.SearchModels; using AbstractFoodOrdersContracts.SearchModels;
using AbstractFoodOrdersContracts.StoragesContracts; using AbstractFoodOrdersContracts.StoragesContracts;
@ -17,70 +18,92 @@ namespace AbstractFoodOrdersBusinessLogic.BusinessLogics
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage; private readonly IOrderStorage _orderStorage;
private readonly AbstractMailWorker _mailWorker;
static readonly object _locker = new object(); static readonly object _locker = new object();
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage)
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage, AbstractMailWorker mailWorker)
{ {
_logger = logger; _logger = logger;
_orderStorage = orderStorage; _orderStorage = orderStorage;
_mailWorker = mailWorker;
} }
public List<OrderViewModel>? ReadList(OrderSearchModel? model) public List<OrderViewModel>? ReadList(OrderSearchModel? model)
{ {
_logger.LogInformation("ReadList. ClientId:{ClientId}.Status:{Status}.ImplementerId:{ImplementerId}.DateFrom:{DateFrom}.DateTo:{DateTo}OrderId:{Id}", _logger.LogInformation("ReadList. Id:{Id}", model?.Id);
model?.ClientId, model?.OrderStatus, model?.ImplementerId, model?.DateFrom, model?.DateTo, model?.Id);
var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model); var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model);
if (list == null) if (list == null)
{ {
_logger.LogWarning("ReadList return null list"); _logger.LogWarning("ReadList return null list");
return null; return null;
} }
_logger.LogInformation("ReadList. Count:{Count}", list.Count); _logger.LogInformation("ReadList. Count: {Count}", list.Count);
return list; return list;
} }
public OrderViewModel? ReadElement(OrderSearchModel model) public OrderViewModel? ReadElement(OrderSearchModel model)
{ {
if (model == null) if (model == null)
{ {
throw new ArgumentNullException(nameof(model)); throw new ArgumentNullException(nameof(model));
} }
_logger.LogInformation("ReadElement. ClientId:{ClientId}.Status:{Status}.ImplementerId:{ImplementerId}.DateFrom:{DateFrom}.DateTo:{DateTo}OrderId:{Id}", _logger.LogInformation("ReadElement. ClientId: {ClientId}. ImplementerId: {ImplementerId}. Status: {Status}. DateFrom: {DateFrom}. DateTo: {DateTo}. Id: {Id}",
model.ClientId, model.OrderStatus, model.ImplementerId, model.DateFrom, model.DateTo, model.Id); model.ClientId, model.ImplementerId, model.OrderStatus, model.DateFrom, model.DateTo, model.Id);
var element = _orderStorage.GetElement(model); var element = _orderStorage.GetElement(model);
if (element == null) if (element == null)
{ {
_logger.LogWarning("ReadElement element not found"); _logger.LogWarning("ReadElement element not found");
return null; return null;
} }
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id); _logger.LogInformation("ReadElement find. Id: {Id}", element.Id);
return element; return element;
} }
public bool CreateOrder(OrderBindingModel model) public bool CreateOrder(OrderBindingModel model)
{ {
CheckModel(model); CheckModel(model);
if (model.Status != OrderStatus.Неизвестен) if (model.Status != OrderStatus.Неизвестен)
return false;
model.Status = OrderStatus.Принят;
if (_orderStorage.Insert(model) == null)
{ {
_logger.LogWarning("Insert operation failed"); _logger.LogWarning("Order status change failed");
return false; return false;
} }
model.Status = OrderStatus.Принят;
var orderView = _orderStorage.Insert(model);
if (orderView == null)
{
_logger.LogWarning("Order creation failed");
return false;
}
Task.Run(() => _mailWorker.MailSendAsync(new MailSendInfoBindingModel
{
MailAddress = orderView.ClientEmail,
Subject = $"Новый заказ создан. Заказ №{orderView.Id}",
Text = $"Заказ №{orderView.Id} от {orderView.DateCreate} на сумму {orderView.Sum} принят."
}));
return true; return true;
} }
public bool TakeOrderInWork(OrderBindingModel model) public bool TakeOrderInWork(OrderBindingModel model)
{ {
lock (_locker) lock (_locker)
{ {
return ChangeStatus(model, OrderStatus.Выполняется); return ChangeOrderStatus(model, OrderStatus.Выполняется);
} }
} }
public bool FinishOrder(OrderBindingModel model) public bool FinishOrder(OrderBindingModel model)
{ {
return ChangeStatus(model, OrderStatus.Готов); return ChangeOrderStatus(model, OrderStatus.Готов);
} }
public bool DeliveryOrder(OrderBindingModel model) public bool DeliveryOrder(OrderBindingModel model)
{ {
return ChangeStatus(model, OrderStatus.Выдан); return ChangeOrderStatus(model, OrderStatus.Выдан);
} }
private void CheckModel(OrderBindingModel model, bool withParams = true) private void CheckModel(OrderBindingModel model, bool withParams = true)
{ {
if (model == null) if (model == null)
@ -93,53 +116,50 @@ namespace AbstractFoodOrdersBusinessLogic.BusinessLogics
} }
if (model.Count <= 0) if (model.Count <= 0)
{ {
throw new ArgumentException("Колличество изделий в заказе не может быть меньше 1", nameof(model.Count)); throw new ArgumentNullException("Кол-во изделий в заказе должно быть больше 0", nameof(model.Count));
} }
if (model.Sum <= 0) if (model.Sum <= 0)
{ {
throw new ArgumentException("Стоимость заказа на может быть меньше 1", nameof(model.Sum)); throw new ArgumentNullException("Сумма заказа должна быть больше 0", nameof(model.Sum));
} }
if (model.DateImplement.HasValue && model.DateImplement < model.DateCreate) _logger.LogInformation("Order. Count: {Count}. Sum: {Sum} Id: {Id}", model.Count, model.Sum, model.Id);
{
throw new ArithmeticException($"Дата выдачи заказа {model.DateImplement} не может быть раньше даты его создания {model.DateCreate}");
}
_logger.LogInformation("Reinforced. ReinforcedId:{ReinforcedId}.Count:{Count}.Sum:{Sum}Id:{Id}",
model.DishId, model.Count, model.Sum, model.Id);
} }
private bool ChangeStatus(OrderBindingModel model, OrderStatus requiredStatus)
private bool ChangeOrderStatus(OrderBindingModel model, OrderStatus newStatus)
{ {
CheckModel(model, false); CheckModel(model, false);
var element = _orderStorage.GetElement(new OrderSearchModel() var orderView = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id });
if (orderView == null || newStatus - orderView.Status != 1)
{ {
Id = model.Id _logger.LogWarning("Order status change failed");
}); return false;
if (element == null)
{
throw new InvalidOperationException(nameof(element));
} }
model.DateCreate = element.DateCreate;
model.DishId = element.DishId; model.Status = newStatus;
model.DateImplement = element.DateImplement;
model.ClientId = element.ClientId;
if (!model.ImplementerId.HasValue) if (!model.ImplementerId.HasValue)
model.ImplementerId = element.ImplementerId; model.ImplementerId = orderView.ImplementerId;
model.Status = element.Status; model.DateImplement = orderView.DateImplement;
model.Count = element.Count;
model.Sum = element.Sum; if (newStatus == OrderStatus.Готов)
if (requiredStatus - model.Status == 1)
{ {
model.Status = requiredStatus; model.DateImplement = DateTime.Now;
if (model.Status == OrderStatus.Готов)
model.DateImplement = DateTime.Now;
if (_orderStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
} }
_logger.LogWarning("Changing status operation faled: Current-{Status}:required-{requiredStatus}.", model.Status, requiredStatus);
throw new InvalidOperationException($"Невозможно приствоить статус {requiredStatus} заказу с текущим статусом {model.Status}"); if (_orderStorage.Update(model) == null)
{
_logger.LogWarning("Order status change failed");
return false;
}
Task.Run(() => _mailWorker.MailSendAsync(new MailSendInfoBindingModel
{
MailAddress = orderView.ClientEmail,
Subject = $"Заказ №{orderView.Id}",
Text = $"Заказ №{orderView.Id} изменен статус на {newStatus}."
}));
return true;
} }
} }
} }

View File

@ -0,0 +1,85 @@
using AbstractFoodOrdersContracts.BindingModels;
using AbstractFoodOrdersContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractFoodOrdersBusinessLogic.MailWorker
{
public abstract class AbstractMailWorker
{
protected string _mailLogin = string.Empty;
protected string _mailPassword = string.Empty;
protected string _smtpClientHost = string.Empty;
protected int _smtpClientPort;
protected string _popHost = string.Empty;
protected int _popPort;
private readonly IMessageInfoLogic _messageInfoLogic;
private readonly ILogger _logger;
public AbstractMailWorker(ILogger<AbstractMailWorker> 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<List<MessageInfoBindingModel>>ReceiveMailAsync();
}
}

View File

@ -0,0 +1,79 @@
using AbstractFoodOrdersContracts.BindingModels;
using AbstractFoodOrdersContracts.BusinessLogicsContracts;
using MailKit.Net.Pop3;
using MailKit.Security;
using Microsoft.Extensions.Logging;
using System.Net;
using System.Net.Mail;
using System.Text;
namespace AbstractFoodOrdersBusinessLogic.MailWorker
{
public class MailKitWorker:AbstractMailWorker
{
public MailKitWorker(ILogger<MailKitWorker> 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<List<MessageInfoBindingModel>>
ReceiveMailAsync()
{
var list = new List<MessageInfoBindingModel>();
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;
}
}
}

View File

@ -2,6 +2,7 @@
using AbstractFoodOrdersContracts.BindingModels; using AbstractFoodOrdersContracts.BindingModels;
using AbstractFoodOrdersContracts.ViewModels; using AbstractFoodOrdersContracts.ViewModels;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Diagnostics; using System.Diagnostics;
namespace AbstractFoodOrdersClientApp.Controllers namespace AbstractFoodOrdersClientApp.Controllers
@ -142,5 +143,16 @@ namespace AbstractFoodOrdersClientApp.Controllers
); );
return count * (prod?.Price ?? 1); return count * (prod?.Price ?? 1);
} }
[HttpGet]
public IActionResult Mails()
{
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
return
View(APIClient.GetRequest<List<MessageInfoViewModel>>($"api/client/getmessages?clientId={ APIClient.Client.Id}"));
}
} }
} }

View File

@ -0,0 +1,51 @@
@using AbstractFoodOrdersContracts.ViewModels
@model List<MessageInfoViewModel>
@{
ViewData["Title"] = "Mails";
}
<div class="text-center">
<h1 class="display-4">Заказы</h1>
</div>
<div class="text-center">
@{
if (Model == null)
{
<h3 class="display-4">Авторизируйтесь</h3>
return;
}
<table class="table">
<thead>
<tr>
<th>
Дата письма
</th>
<th>
Заголовок
</th>
<th>
Текст
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem =>
item.DateDelivery)
</td>
<td>
@Html.DisplayFor(modelItem =>
item.Subject)
</td>
<td>
@Html.DisplayFor(modelItem =>
item.Body)
</td>
</tr>
}
</tbody>
</table>
}
</div>

View File

@ -26,6 +26,9 @@
<li class="nav-item"> <li class="nav-item">
<a class="nav-link text-dark" asparea="" asp-controller="Home" asp-action="Privacy">Личные данные</a> <a class="nav-link text-dark" asparea="" asp-controller="Home" asp-action="Privacy">Личные данные</a>
</li> </li>
<li class="nav-item">
<a class="nav-link text-dark" asparea="" asp-controller="Home" asp-action="Mails">Письма</a>
</li>
<li class="nav-item"> <li class="nav-item">
<a class="nav-link text-dark" asparea="" asp-controller="Home" asp-action="Enter">Вход</a> <a class="nav-link text-dark" asparea="" asp-controller="Home" asp-action="Enter">Вход</a>
</li> </li>

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractFoodOrdersContracts.BindingModels
{
public class MailConfigBindingModel
{
public string MailLogin { get; set; } = string.Empty;
public string MailPassword { get; set; } = string.Empty;
public string SmtpClientHost { get; set; } = string.Empty;
public int SmtpClientPort { get; set; }
public string PopHost { get; set; } = string.Empty;
public int PopPort { get; set; }
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractFoodOrdersContracts.BindingModels
{
public class MailSendInfoBindingModel
{
public string MailAddress { get; set; } = string.Empty;
public string Subject { get; set; } = string.Empty;
public string Text { get; set; } = string.Empty;
}
}

View File

@ -0,0 +1,285 @@
// <auto-generated />
using System;
using AbstractFoodOrdersDatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace AbstractFoodOrdersDatabaseImplement.Migrations
{
[DbContext(typeof(AbstractFoodOrdersDatabase))]
[Migration("20230530143643_MailInfo")]
partial class MailInfo
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.5")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("AbstractFoodOrdersDatabaseImplement.Models.Client", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ClientFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Clients");
});
modelBuilder.Entity("AbstractFoodOrdersDatabaseImplement.Models.Component", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ComponentName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Cost")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Components");
});
modelBuilder.Entity("AbstractFoodOrdersDatabaseImplement.Models.Dish", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("DishName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Price")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Dishes");
});
modelBuilder.Entity("AbstractFoodOrdersDatabaseImplement.Models.DishComponent", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("ComponentId")
.HasColumnType("int");
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("DishId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ComponentId");
b.HasIndex("DishId");
b.ToTable("DishComponents");
});
modelBuilder.Entity("AbstractFoodOrdersDatabaseImplement.Models.Implementer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ImplementerFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("Qualification")
.HasColumnType("int");
b.Property<int>("WorkExperience")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Implementers");
});
modelBuilder.Entity("AbstractFoodOrdersDatabaseImplement.Models.MessageInfo", b =>
{
b.Property<string>("MessageId")
.HasColumnType("nvarchar(450)");
b.Property<string>("Body")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int?>("ClientId")
.HasColumnType("int");
b.Property<DateTime>("DateDelivery")
.HasColumnType("datetime2");
b.Property<string>("SenderName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Subject")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("MessageId");
b.ToTable("MessageInfos");
});
modelBuilder.Entity("AbstractFoodOrdersDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("ClientId")
.HasColumnType("int");
b.Property<int>("Count")
.HasColumnType("int");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int>("DishId")
.HasColumnType("int");
b.Property<int?>("ImplementerId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("ClientId");
b.HasIndex("DishId");
b.HasIndex("ImplementerId");
b.ToTable("Orders");
});
modelBuilder.Entity("AbstractFoodOrdersDatabaseImplement.Models.DishComponent", b =>
{
b.HasOne("AbstractFoodOrdersDatabaseImplement.Models.Component", "Component")
.WithMany("DishComponents")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("AbstractFoodOrdersDatabaseImplement.Models.Dish", "Dish")
.WithMany("Components")
.HasForeignKey("DishId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Component");
b.Navigation("Dish");
});
modelBuilder.Entity("AbstractFoodOrdersDatabaseImplement.Models.Order", b =>
{
b.HasOne("AbstractFoodOrdersDatabaseImplement.Models.Client", "Client")
.WithMany("ClientOrders")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("AbstractFoodOrdersDatabaseImplement.Models.Dish", "Dish")
.WithMany("Orders")
.HasForeignKey("DishId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("AbstractFoodOrdersDatabaseImplement.Models.Implementer", "Implementer")
.WithMany("Orders")
.HasForeignKey("ImplementerId");
b.Navigation("Client");
b.Navigation("Dish");
b.Navigation("Implementer");
});
modelBuilder.Entity("AbstractFoodOrdersDatabaseImplement.Models.Client", b =>
{
b.Navigation("ClientOrders");
});
modelBuilder.Entity("AbstractFoodOrdersDatabaseImplement.Models.Component", b =>
{
b.Navigation("DishComponents");
});
modelBuilder.Entity("AbstractFoodOrdersDatabaseImplement.Models.Dish", b =>
{
b.Navigation("Components");
b.Navigation("Orders");
});
modelBuilder.Entity("AbstractFoodOrdersDatabaseImplement.Models.Implementer", b =>
{
b.Navigation("Orders");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,38 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace AbstractFoodOrdersDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class MailInfo : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "MessageInfos",
columns: table => new
{
MessageId = table.Column<string>(type: "nvarchar(450)", nullable: false),
ClientId = table.Column<int>(type: "int", nullable: true),
SenderName = table.Column<string>(type: "nvarchar(max)", nullable: false),
DateDelivery = table.Column<DateTime>(type: "datetime2", nullable: false),
Subject = table.Column<string>(type: "nvarchar(max)", nullable: false),
Body = table.Column<string>(type: "nvarchar(max)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_MessageInfos", x => x.MessageId);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "MessageInfos");
}
}
}

View File

@ -140,6 +140,34 @@ namespace AbstractFoodOrdersDatabaseImplement.Migrations
b.ToTable("Implementers"); b.ToTable("Implementers");
}); });
modelBuilder.Entity("AbstractFoodOrdersDatabaseImplement.Models.MessageInfo", b =>
{
b.Property<string>("MessageId")
.HasColumnType("nvarchar(450)");
b.Property<string>("Body")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int?>("ClientId")
.HasColumnType("int");
b.Property<DateTime>("DateDelivery")
.HasColumnType("datetime2");
b.Property<string>("SenderName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Subject")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("MessageId");
b.ToTable("MessageInfos");
});
modelBuilder.Entity("AbstractFoodOrdersDatabaseImplement.Models.Order", b => modelBuilder.Entity("AbstractFoodOrdersDatabaseImplement.Models.Order", b =>
{ {
b.Property<int>("Id") b.Property<int>("Id")

View File

@ -12,11 +12,13 @@ namespace AbstractFoodOrdersRestApi.Controllers
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IClientLogic _logic; private readonly IClientLogic _logic;
public ClientController(IClientLogic logic, ILogger<ClientController> private readonly IMessageInfoLogic _mailLogic;
public ClientController(IClientLogic logic, IMessageInfoLogic mailLogic, ILogger<ClientController>
logger) logger)
{ {
_logger = logger; _logger = logger;
_logic = logic; _logic = logic;
_mailLogic = mailLogic;
} }
[HttpGet] [HttpGet]
public ClientViewModel? Login(string login, string password) public ClientViewModel? Login(string login, string password)
@ -61,5 +63,22 @@ namespace AbstractFoodOrdersRestApi.Controllers
throw; throw;
} }
} }
} [HttpGet]
public List<MessageInfoViewModel>? GetMessages(int clientId)
{
try
{
return _mailLogic.ReadList(new MessageInfoSearchModel
{
ClientId = clientId
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения писем клиента");
throw;
}
}
}
} }

View File

@ -1,4 +1,6 @@
using AbstractFoodOrdersBusinessLogic.BusinessLogics; using AbstractFoodOrdersBusinessLogic.BusinessLogics;
using AbstractFoodOrdersBusinessLogic.MailWorker;
using AbstractFoodOrdersContracts.BindingModels;
using AbstractFoodOrdersContracts.BusinessLogicsContracts; using AbstractFoodOrdersContracts.BusinessLogicsContracts;
using AbstractFoodOrdersContracts.StoragesContracts; using AbstractFoodOrdersContracts.StoragesContracts;
using AbstractFoodOrdersDatabaseImplement.Implements; using AbstractFoodOrdersDatabaseImplement.Implements;
@ -13,9 +15,16 @@ builder.Logging.AddLog4Net("log4net.config");
builder.Services.AddTransient<IClientStorage, ClientStorage>(); builder.Services.AddTransient<IClientStorage, ClientStorage>();
builder.Services.AddTransient<IOrderStorage, OrderStorage>(); builder.Services.AddTransient<IOrderStorage, OrderStorage>();
builder.Services.AddTransient<IDishStorage, DishStorage>(); builder.Services.AddTransient<IDishStorage, DishStorage>();
builder.Services.AddTransient<IImplementerStorage, ImplementerStorage>();
builder.Services.AddTransient<IMessageInfoStorage, MessageInfoStorage>();
builder.Services.AddTransient<IOrderLogic, OrderLogic>(); builder.Services.AddTransient<IOrderLogic, OrderLogic>();
builder.Services.AddTransient<IClientLogic, ClientLogic>(); builder.Services.AddTransient<IClientLogic, ClientLogic>();
builder.Services.AddTransient<IDishLogic, DishLogic>(); builder.Services.AddTransient<IDishLogic, DishLogic>();
builder.Services.AddTransient<IImplementerLogic, ImplementerLogic>();
builder.Services.AddTransient<IMessageInfoLogic, MessageInfoLogic>();
builder.Services.AddTransient<AbstractMailWorker, MailKitWorker>();
builder.Services.AddControllers(); builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
@ -27,6 +36,18 @@ builder.Services.AddSwaggerGen(c =>
var app = builder.Build(); var app = builder.Build();
var mailSender = app.Services.GetService<AbstractMailWorker>();
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. // Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment()) if (app.Environment.IsDevelopment())
{ {

View File

@ -5,5 +5,12 @@
"Microsoft.AspNetCore": "Warning" "Microsoft.AspNetCore": "Warning"
} }
}, },
"AllowedHosts": "*" "AllowedHosts": "*",
"SmtpClientHost": "smtp.gmail.com",
"SmtpClientPort": "587",
"PopHost": "pop.gmail.com",
"PopPort": "995",
"MailLogin": "labwork07mail@gmail.com",
"MailPassword": "ugqf vpli kqcu fjui"
} }

View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="SmtpClientHost" value="smtp.gmail.com" />
<add key="SmtpClientPort" value="587" />
<add key="PopHost" value="pop.gmail.com" />
<add key="PopPort" value="995" />
<add key="MailLogin" value="labwork07mail@gmail.com" />
<add key="MailPassword" value="ugqf vpli kqcu fjui" />
</appSettings>
</configuration>

View File

@ -33,6 +33,7 @@
КомпонентыToolStripMenuItem = new ToolStripMenuItem(); КомпонентыToolStripMenuItem = new ToolStripMenuItem();
БлюдаToolStripMenuItem = new ToolStripMenuItem(); БлюдаToolStripMenuItem = new ToolStripMenuItem();
ClientToolStripMenuItem = new ToolStripMenuItem(); ClientToolStripMenuItem = new ToolStripMenuItem();
исполнителиToolStripMenuItem = new ToolStripMenuItem();
отчётыToolStripMenuItem = new ToolStripMenuItem(); отчётыToolStripMenuItem = new ToolStripMenuItem();
ComponentToolStripMenuItem = new ToolStripMenuItem(); ComponentToolStripMenuItem = new ToolStripMenuItem();
ComponentProductsToolStripMenuItem = new ToolStripMenuItem(); ComponentProductsToolStripMenuItem = new ToolStripMenuItem();
@ -42,7 +43,7 @@
ButtonCreateOrder = new Button(); ButtonCreateOrder = new Button();
ButtonIssuedOrder = new Button(); ButtonIssuedOrder = new Button();
ButtonRef = new Button(); ButtonRef = new Button();
исполнителиToolStripMenuItem = new ToolStripMenuItem(); письмаToolStripMenuItem = new ToolStripMenuItem();
menuStrip.SuspendLayout(); menuStrip.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout(); SuspendLayout();
@ -59,7 +60,7 @@
// //
// справочникиToolStripMenuItem // справочникиToolStripMenuItem
// //
справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { КомпонентыToolStripMenuItem, БлюдаToolStripMenuItem, ClientToolStripMenuItem, исполнителиToolStripMenuItem }); справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { КомпонентыToolStripMenuItem, БлюдаToolStripMenuItem, ClientToolStripMenuItem, исполнителиToolStripMenuItem, письмаToolStripMenuItem });
справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem";
справочникиToolStripMenuItem.Size = new Size(117, 24); справочникиToolStripMenuItem.Size = new Size(117, 24);
справочникиToolStripMenuItem.Text = "Справочники"; справочникиToolStripMenuItem.Text = "Справочники";
@ -85,6 +86,13 @@
ClientToolStripMenuItem.Text = "Клиенты"; ClientToolStripMenuItem.Text = "Клиенты";
ClientToolStripMenuItem.Click += ClientToolStripMenuItem_Click; ClientToolStripMenuItem.Click += ClientToolStripMenuItem_Click;
// //
// исполнителиToolStripMenuItem
//
исполнителиToolStripMenuItem.Name = сполнителиToolStripMenuItem";
исполнителиToolStripMenuItem.Size = new Size(224, 26);
исполнителиToolStripMenuItem.Text = "Исполнители";
исполнителиToolStripMenuItem.Click += ИсполнителиToolStripMenuItem_Click;
//
// отчётыToolStripMenuItem // отчётыToolStripMenuItem
// //
отчётыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { ComponentToolStripMenuItem, ComponentProductsToolStripMenuItem, OrdersToolStripMenuItem }); отчётыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { ComponentToolStripMenuItem, ComponentProductsToolStripMenuItem, OrdersToolStripMenuItem });
@ -161,12 +169,12 @@
ButtonRef.UseVisualStyleBackColor = true; ButtonRef.UseVisualStyleBackColor = true;
ButtonRef.Click += ButtonRef_Click; ButtonRef.Click += ButtonRef_Click;
// //
// исполнителиToolStripMenuItem // письмаToolStripMenuItem
// //
исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; письмаToolStripMenuItem.Name = "письмаToolStripMenuItem";
исполнителиToolStripMenuItem.Size = new Size(224, 26); письмаToolStripMenuItem.Size = new Size(224, 26);
исполнителиToolStripMenuItem.Text = "Исполнители"; письмаToolStripMenuItem.Text = "Письма";
исполнителиToolStripMenuItem.Click += ИсполнителиToolStripMenuItem_Click; письмаToolStripMenuItem.Click += письмаToolStripMenuItem_Click;
// //
// FormMain // FormMain
// //
@ -206,5 +214,6 @@
private ToolStripMenuItem ClientToolStripMenuItem; private ToolStripMenuItem ClientToolStripMenuItem;
private ToolStripMenuItem запускРаботыToolStripMenuItem; private ToolStripMenuItem запускРаботыToolStripMenuItem;
private ToolStripMenuItem исполнителиToolStripMenuItem; private ToolStripMenuItem исполнителиToolStripMenuItem;
private ToolStripMenuItem письмаToolStripMenuItem;
} }
} }

View File

@ -43,6 +43,7 @@ namespace FoodOrders
dataGridView.Columns["ClientId"].Visible = false; dataGridView.Columns["ClientId"].Visible = false;
dataGridView.Columns["DishId"].Visible = false; dataGridView.Columns["DishId"].Visible = false;
dataGridView.Columns["ImplementerId"].Visible = false; dataGridView.Columns["ImplementerId"].Visible = false;
dataGridView.Columns["ClientEmail"].Visible = false;
} }
_logger.LogInformation("Загрузка заказов"); _logger.LogInformation("Загрузка заказов");
} }
@ -213,6 +214,13 @@ namespace FoodOrders
MessageBoxButtons.OK, MessageBoxIcon.Information); 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();
}
}
} }
} }

View File

@ -8,6 +8,8 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging; using NLog.Extensions.Logging;
using System.Drawing; using System.Drawing;
using AbstractFoodOrdersBusinessLogic.MailWorker;
using AbstractFoodOrdersContracts.BindingModels;
namespace FoodOrders namespace FoodOrders
{ {
@ -27,7 +29,36 @@ namespace FoodOrders
var services = new ServiceCollection(); var services = new ServiceCollection();
ConfigureServices(services); ConfigureServices(services);
_serviceProvider = services.BuildServiceProvider(); _serviceProvider = services.BuildServiceProvider();
Application.Run(_serviceProvider.GetRequiredService<FormMain>()); try
{
var mailSender =
_serviceProvider.GetService<AbstractMailWorker>();
mailSender?.MailConfig(new MailConfigBindingModel
{
MailLogin =
System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty,
MailPassword =
System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty,
SmtpClientHost =
System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty,
SmtpClientPort =
Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]),
PopHost =
System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty,
PopPort =
Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"])
});
// ñîçäàåì òàéìåð
var timer = new System.Threading.Timer(new
TimerCallback(MailCheck!), null, 0, 10000);
}
catch (Exception ex)
{
var logger = _serviceProvider.GetService<ILogger>();
logger?.LogError(ex, "Îøèáêà ðàáîòû ñ ïî÷òîé");
}
Application.Run(_serviceProvider.GetRequiredService<FormMain>());
} }
private static void ConfigureServices(ServiceCollection services) private static void ConfigureServices(ServiceCollection services)
{ {
@ -41,16 +72,23 @@ namespace FoodOrders
services.AddTransient<IDishStorage, DishStorage>(); services.AddTransient<IDishStorage, DishStorage>();
services.AddTransient<IClientStorage, ClientStorage>(); services.AddTransient<IClientStorage, ClientStorage>();
services.AddTransient<IImplementerStorage, ImplementerStorage>(); services.AddTransient<IImplementerStorage, ImplementerStorage>();
services.AddTransient<IComponentLogic, ComponentLogic>(); services.AddTransient<IMessageInfoStorage,MessageInfoStorage>();
services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IOrderLogic, OrderLogic>(); services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<IDishLogic, DishLogic>(); services.AddTransient<IDishLogic, DishLogic>();
services.AddTransient<IReportLogic, ReportLogic>(); services.AddTransient<IReportLogic, ReportLogic>();
services.AddTransient<IClientLogic, ClientLogic>(); services.AddTransient<IClientLogic, ClientLogic>();
services.AddTransient<IImplementerLogic, ImplementerLogic>(); services.AddTransient<IImplementerLogic, ImplementerLogic>();
services.AddTransient<IMessageInfoLogic, MessageInfoLogic>();
services.AddTransient<IWorkProcess, WorkModeling>(); services.AddTransient<IWorkProcess, WorkModeling>();
services.AddSingleton<AbstractMailWorker, MailKitWorker>();
services.AddTransient<AbstractSaveToExcel, SaveToExcel>(); services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
services.AddTransient<AbstractSaveToWord, SaveToWord>(); services.AddTransient<AbstractSaveToWord, SaveToWord>();
services.AddTransient<AbstractSaveToPdf, SaveToPdf>(); services.AddTransient<AbstractSaveToPdf, SaveToPdf>();
services.AddTransient<FormMain>(); services.AddTransient<FormMain>();
services.AddTransient<FormComponent>(); services.AddTransient<FormComponent>();
services.AddTransient<FormComponents>(); services.AddTransient<FormComponents>();
@ -63,6 +101,8 @@ namespace FoodOrders
services.AddTransient<FormClients>(); services.AddTransient<FormClients>();
services.AddTransient<FormCreateImplementer>(); services.AddTransient<FormCreateImplementer>();
services.AddTransient<FormImplementers>(); services.AddTransient<FormImplementers>();
services.AddTransient<FormMails>();
} }
} private static void MailCheck(object obj) => ServiceProvider?.GetService<AbstractMailWorker>()?.MailCheck();
}
} }