pdf + почта

This commit is contained in:
ujijrujijr 2024-05-28 19:40:32 +04:00
parent 527af10bbc
commit a460ea0308
14 changed files with 376 additions and 48 deletions

View File

@ -85,7 +85,7 @@ namespace ComputerShopBusinessLogic.BusinessLogics
_saveToPdf.CreateDoc(new PdfInfoImplementer _saveToPdf.CreateDoc(new PdfInfoImplementer
{ {
FileName = model.FileName, FileName = model.FileName,
Title = "Список участников", Title = "Отчёт по заказам за период",
DateFrom = model.DateFrom!.Value, DateFrom = model.DateFrom!.Value,
DateTo = model.DateTo!.Value, DateTo = model.DateTo!.Value,
Orders = GetReportOrdersByDates(model) Orders = GetReportOrdersByDates(model)

View File

@ -0,0 +1,64 @@
using ComputerShopContracts.BindingModels;
using ComputerShopContracts.BusinessLogicContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputerShopBusinessLogic.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 IOrganiserLogic _organiserLogic;
private readonly ILogger _logger;
public AbstractMailWorker(ILogger<AbstractMailWorker> logger/*, IOrganiserLogic organiserLogic*/)
{
_logger = logger;
//_organiserLogic = organiserLogic;
}
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);
}
protected abstract Task SendMailAsync(MailSendInfoBindingModel info);
}
}

View File

@ -0,0 +1,51 @@
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Net;
using System.Security.Authentication;
using System.Text;
using System.Threading.Tasks;
using ComputerShopContracts.BusinessLogicContracts;
using System.Net.Mime;
using ComputerShopContracts.BindingModels;
namespace ComputerShopBusinessLogic.MailWorker
{
public class MailKitWorker : AbstractMailWorker
{
public MailKitWorker(ILogger<MailKitWorker> logger/*, IOrganiserLogic organiserLogic*/) : base(logger/*, organiserLogic*/) { }
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;
Attachment attachment = new Attachment("C:\\!Курсовая\\Отчёт за период.pdf", new ContentType(MediaTypeNames.Application.Pdf));
objMailMessage.Attachments.Add(attachment);
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;
}
}
}
}

View File

@ -16,29 +16,42 @@ namespace GarmentFactoryBusinessLogic.OfficePackage
CreateParagraph(new PdfParagraph { Text = info.Title, Style = "NormalTitle", ParagraphAlignment = PdfParagraphAlignmentType.Center }); CreateParagraph(new PdfParagraph { Text = info.Title, Style = "NormalTitle", ParagraphAlignment = PdfParagraphAlignmentType.Center });
CreateParagraph(new PdfParagraph { Text = $"с {info.DateFrom.ToShortDateString()} по {info.DateTo.ToShortDateString()}", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Center }); CreateParagraph(new PdfParagraph { Text = $"с {info.DateFrom.ToShortDateString()} по {info.DateTo.ToShortDateString()}", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Center });
//!!!МБ ТУТ НЕЛЬЗЯ ДРОБНЫЕ ЧИСЛА ИЛИ МОЖНО С ТОЧКОЙ //!!!МБ ТУТ НЕЛЬЗЯ ДРОБНЫЕ ЧИСЛА ИЛИ МОЖНО С ТОЧКОЙ
CreateTable(new List<string> { "1,5cm", "3cm", "3cm", "2,5cm", "1,5cm", "4cm", "3cm", "3cm", "3cm", "3cm" }); CreateTable(new List<string> { "2cm", "2.5cm", "2cm", "2cm", "2cm", "4cm", "2.5cm", "3.5cm", "3.5cm", "2.5cm" });
CreateRow(new PdfRowParameters CreateRow(new PdfRowParameters
{ {
Texts = new List<string> { "ID заказа", "Дата заказа", "Стоимость заказа", "Статус заказа", "ID заявки", "ФИО клиента", "Дата заявки", "Название сборки", "Каетегория сборки", "Цена сборки" }, Texts = new List<string> { "ID заказа", "Дата заказа", "Сумма заказа", "Статус заказа", "ID заявки", "ФИО клиента", "Дата заявки", "Название сборки", "Категория сборки", "Цена сборки" },
Style = "NormalTitle", Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center ParagraphAlignment = PdfParagraphAlignmentType.Center
}); });
foreach (var order in info.Orders) foreach (var order in info.Orders)
{ {
//!!!СЮДА
if (order.RequestsAssemblies.Count < 1)
{
CreateRow(new PdfRowParameters
{
Texts = new List<string> {
order.OrderId.ToString(), order.DateCreateOrder.ToShortDateString(), order.OrderSum.ToString(), order.OrderStatus.ToString(),
"Заказ без заявок", "Неизвестно", "Неизвестно",
"Неизвестно", "Неизвестно", "0"
}
});
}
foreach (var request in order.RequestsAssemblies) foreach (var request in order.RequestsAssemblies)
{ {
CreateRow(new PdfRowParameters CreateRow(new PdfRowParameters
{ {
Texts = new List<string> { order.OrderId.ToString(), order.DateCreateOrder.ToShortDateString(), order.OrderSum.ToString(), order.OrderStatus.ToString(), Texts = new List<string> { order.OrderId.ToString(), order.DateCreateOrder.ToShortDateString(), order.OrderSum.ToString(), order.OrderStatus.ToString(),
request.RequestId.ToString(), request.ClientFIO, request.DateRequest.ToShortDateString(), request.RequestId.ToString(), request.ClientFIO, request.DateRequest.ToShortDateString(),
string.IsNullOrEmpty(request.AssemblyName) ? "Сборка не привязана" : request.AssemblyName, string.IsNullOrEmpty(request.AssemblyName) ? "Сборка не привязана" : request.AssemblyName,
string.IsNullOrEmpty(request.AssemblyCategory) ? "Неизвестная категория" : request.AssemblyCategory, string.IsNullOrEmpty(request.AssemblyCategory) ? "Неизвестно" : request.AssemblyCategory,
request.AssemblyPrice.ToString() request.AssemblyPrice.ToString()
}, }
Style = "Normal", //},
ParagraphAlignment = PdfParagraphAlignmentType.Left //Style = "Normal",
//ParagraphAlignment = PdfParagraphAlignmentType.Left
}); });
} }

View File

@ -41,9 +41,10 @@ namespace GarmentFactoryBusinessLogic.OfficePackage.Implements
protected override void CreatePdf(PdfInfoImplementer info) protected override void CreatePdf(PdfInfoImplementer info)
{ {
_document = new Document(); _document = new Document();
DefineStyles(_document);
_section = _document.AddSection(); DefineStyles(_document);
_document.DefaultPageSetup.Orientation = Orientation.Landscape;
_section = _document.AddSection();
} }
protected override void CreateParagraph(PdfParagraph pdfParagraph) protected override void CreateParagraph(PdfParagraph pdfParagraph)
@ -100,13 +101,15 @@ namespace GarmentFactoryBusinessLogic.OfficePackage.Implements
} }
} }
//!!!ТУТ ИСКЛЮЧЕНИЕ
protected override void SavePdf(PdfInfoImplementer info) protected override void SavePdf(PdfInfoImplementer info)
{ {
var renderer = new PdfDocumentRenderer(true) var renderer = new PdfDocumentRenderer(true)
{ {
Document = _document Document = _document
}; };
renderer.RenderDocument(); System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
renderer.RenderDocument();
renderer.PdfDocument.Save(info.FileName); renderer.PdfDocument.Save(info.FileName);
} }
} }

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputerShopContracts.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 ComputerShopContracts.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

@ -83,10 +83,11 @@ namespace ComputerShopDatabaseImplement.Implements
public List<ReportOrdersViewModel> GetOrdersInfoByDates(ReportBindingModel report) public List<ReportOrdersViewModel> GetOrdersInfoByDates(ReportBindingModel report)
{ {
using var context = new ComputerShopDatabase(); using var context = new ComputerShopDatabase();
return context.Orders.Include(x => x.Requests) return context.Orders
.Where(x => x.UserId == report.UserId && DateTime.Compare(x.DateCreate, report.DateFrom.Value) >= 0 && DateTime.Compare(x.DateCreate, report.DateTo.Value) <= 0)
.Include(x => x.Requests)
.ThenInclude(x => x.Request) .ThenInclude(x => x.Request)
.ThenInclude(x => x.Assembly) .ThenInclude(x => x.Assembly)
.Where(x => x.UserId == report.UserId && x.DateCreate >= report.DateFrom && x.DateCreate <= report.DateTo)
.ToList() .ToList()
.Select(x => new ReportOrdersViewModel .Select(x => new ReportOrdersViewModel
{ {
@ -95,9 +96,9 @@ namespace ComputerShopDatabaseImplement.Implements
OrderSum = x.Sum, OrderSum = x.Sum,
OrderStatus = x.Status, OrderStatus = x.Status,
RequestsAssemblies = x.Requests.Select(r => (r.Request.Id, r.Request.ClientFIO, r.Request.DateRequest, RequestsAssemblies = x.Requests.Select(r => (r.Request.Id, r.Request.ClientFIO, r.Request.DateRequest,
(r.Request.Assembly != null) ? r.Request.Assembly.AssemblyName : "Без сборки", (r.Request.Assembly != null) ? r.Request.Assembly.AssemblyName : "",
(r.Request.Assembly != null) ? r.Request.Assembly.Category : "Без сборки", (r.Request.Assembly != null) ? r.Request.Assembly.Category : "",
(r.Request.Assembly != null) ? r.Request.Assembly.Price : 0)).ToList() (r.Request.Assembly != null) ? r.Request.Assembly.Price : 0)).ToList(),
}) })
.ToList(); .ToList();
} }

View File

@ -7,6 +7,7 @@ using ComputerShopDataModels.Enums;
using ComputerShopDataModels.Models; using ComputerShopDataModels.Models;
using ComputerShopContracts.SearchModels; using ComputerShopContracts.SearchModels;
using ComputerShopContracts.BusinessLogicContracts; using ComputerShopContracts.BusinessLogicContracts;
using DocumentFormat.OpenXml.Bibliography;
namespace ComputerShopImplementerApp.Controllers namespace ComputerShopImplementerApp.Controllers
{ {
@ -594,10 +595,116 @@ namespace ComputerShopImplementerApp.Controllers
throw; throw;
} }
string table = ""; string table = "";
//МБ НЕ НДО ПРИСВАИВАТЬ КЛАСС u-table-entity
table += $"<table class=\"u-table-entity\">";
table += "<colgroup>";
//ID заказа
table += "<col width=\"5%\" />";
//Дата заказа
table += "<col width=\"10%\" />";
//Стоимость заказа
table += "<col width=\"10%\" />";
//Статус заказа
table += "<col width=\"10%\" />";
//ID заявки
table += "<col width=\"5%\" />";
//ФИО клиента
table += "<col width=\"15%\" />";
//Дата заявки
table += "<col width=\"10%\" />";
//Название сборки
table += "<col width=\"15%\" />";
//Категория сборки
table += "<col width=\"10%\" />";
//Цена сборки
table += "<col width=\"10%\" />";
table += "</colgroup>";
//МБ НЕ НДО ПРИСВАИВАТЬ КЛАСС
table += "<thead class=\"u-custom-color-1 u-table-header u-table-header-1\">";
//МБ ИЗМЕНИТЬ ВЫСОТУ
table += "<tr style=\"height: 31px\">";
//МБ ИЗМЕНИТЬ КЛАСС
table += $"<th class=\"u-border-1 u-border-grey-50 u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">ID заказа</th>";
table += $"<th class=\"u-border-1 u-border-grey-50 u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">Дата заказа</th>";
table += $"<th class=\"u-border-1 u-border-grey-50 u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">Стоимость заказа</th>";
table += $"<th class=\"u-border-1 u-border-grey-50 u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">Статус заказа</th>";
table += $"<th class=\"u-border-1 u-border-grey-50 u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">ID заявки</th>";
table += $"<th class=\"u-border-1 u-border-grey-50 u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">ФИО клиента</th>";
table += $"<th class=\"u-border-1 u-border-grey-50 u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">Дата заявки</th>";
table += $"<th class=\"u-border-1 u-border-grey-50 u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">Название сборки</th>";
table += $"<th class=\"u-border-1 u-border-grey-50 u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">Категория сборки</th>";
table += $"<th class=\"u-border-1 u-border-grey-50 u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">Цена сборки</th>";
table += "</tr>";
table += "</thead>";
//МБ НЕ ПРИСВАИВАТЬ КЛАСС ИЛИ СДЕЛАТЬ ПЕРЕД ВНУТРЕННИМ ЦИКЛОМ
table += "<tbody class=\"u-table-body\">";
foreach (var order in result)
{
if (order.RequestsAssemblies.Count < 1)
{
//МБ ПОМЕНЯТЬ ВЫСОТУ
table += "<tr style=\"height: 75px\">";
table += $"<td class=\"u-border-1 u-border-grey-40 u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{order.OrderId.ToString()}</td>";
table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{order.DateCreateOrder.ToShortDateString()}</td>";
table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{order.OrderSum.ToString()}</td>";
table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{order.OrderStatus.ToString()}</td>";
table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{"Заказ без заявок"}</td>";
table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{"Неизвестно"}</td>";
table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{"Неизвестно"}</td>";
table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{"Неизвестно"}</td>";
table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{"Неизвестно"}</td>";
table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{"Неизвестно"}</td>";
table += "</tr>";
}
foreach (var request in order.RequestsAssemblies)
{
//МБ ПОМЕНЯТЬ ВЫСОТУ
table += "<tr style=\"height: 75px\">";
table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{order.OrderId.ToString()}</td>";
table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{order.DateCreateOrder.ToShortDateString()}</td>";
table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{order.OrderSum.ToString()}</td>";
table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{order.OrderStatus.ToString()}</td>";
table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{request.RequestId.ToString()}</td>";
table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{request.ClientFIO.ToString()}</td>";
table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{request.DateRequest.ToShortDateString()}</td>";
table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{(string.IsNullOrEmpty(request.AssemblyName) ? "Сборка не привязана" : request.AssemblyName)}</td>";
table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{(string.IsNullOrEmpty(request.AssemblyCategory) ? "Неизвестная категория" : request.AssemblyCategory)}</td>";
//МБ тут не будет 0 у непривязанных сборок
table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{request.AssemblyPrice.ToString()}</td>";
table += "</tr>";
}
}
table += "</table>";
return table; return table;
} }
[HttpPost]
public void ReportOrdersByDates(DateTime dateFrom, DateTime dateTo)
{
if (APIUser.User == null)
{
throw new Exception("Вход только авторизованным");
}
//if (string.IsNullOrEmpty(organiserEmail))
//{
// throw new Exception("Email пуст");
//}
APIUser.PostRequest("api/order/CreateReportToPDFFile", new ReportBindingModel
{
FileName = "C:\\!КУРСОВАЯ\\Отчёт за период.pdf",
DateFrom = dateFrom,
DateTo = dateTo,
UserId = APIUser.User.Id
});
APIUser.PostRequest("api/order/SendPDFToMail", new MailSendInfoBindingModel
{
//!!!МБ СЮДА ПЕРЕДАВАТЬ ПОЧТУ, КОТОРУЮ ВВОДЯТ НА СТРАНИЦЕ
MailAddress = APIUser.User.Email,
Subject = "Отчет за период",
Text = "Отчет по заказам с " + dateFrom.ToShortDateString() + " по " + dateTo.ToShortDateString()
});
Response.Redirect("Index");
}
// ОСТАЛЬНОЕ ОСТАЛЬНОЕ ОСТАЛЬНОЕ ОСТАЛЬНОЕ ОСТАЛЬНОЕ ОСТАЛЬНОЕ ОСТАЛЬНОЕ // ОСТАЛЬНОЕ ОСТАЛЬНОЕ ОСТАЛЬНОЕ ОСТАЛЬНОЕ ОСТАЛЬНОЕ ОСТАЛЬНОЕ ОСТАЛЬНОЕ
@ -652,16 +759,23 @@ namespace ComputerShopImplementerApp.Controllers
[HttpPost] [HttpPost]
public void Enter(string login, string password) public void Enter(string login, string password)
{ {
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password)) try
{ {
throw new Exception("Введите логин и пароль"); if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password))
{
throw new Exception("Введите логин и пароль");
}
APIUser.User = APIUser.GetRequest<UserViewModel>($"api/user/loginimplementer?login={login}&password={password}");
if (APIUser.User == null)
{
throw new Exception("Неверный логин/пароль");
}
Response.Redirect("Index");
} }
APIUser.User = APIUser.GetRequest<UserViewModel>($"api/user/loginimplementer?login={login}&password={password}"); catch (Exception)
if (APIUser.User == null)
{ {
throw new Exception("Неверный логин/пароль"); Response.Redirect("Enter");
} }
Response.Redirect("Index");
} }
[HttpGet] [HttpGet]

View File

@ -5,6 +5,8 @@ using ComputerShopDatabaseImplement.Implements;
using ComputerShopDatabaseImplement.Models; using ComputerShopDatabaseImplement.Models;
using ComputerShopDataModels.Models; using ComputerShopDataModels.Models;
using ComputerShopImplementerApp; using ComputerShopImplementerApp;
using GarmentFactoryBusinessLogic.OfficePackage;
using GarmentFactoryBusinessLogic.OfficePackage.Implements;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
@ -13,19 +15,25 @@ var builder = WebApplication.CreateBuilder(args);
//builder.Services.AddTransient<IShipmentModel, Shipment>(); //builder.Services.AddTransient<IShipmentModel, Shipment>();
//builder.Services.AddTransient<IRequestModel, Request>(); //builder.Services.AddTransient<IRequestModel, Request>();
builder.Services.AddTransient<IUserStorage, UserStorage>(); builder.Services.AddTransient<IUserStorage, UserStorage>();
builder.Services.AddTransient<IShipmentStorage, ShipmentStorage>(); builder.Services.AddTransient<IShipmentStorage, ShipmentStorage>();
builder.Services.AddTransient<IRequestStorage, RequestStorage>(); builder.Services.AddTransient<IRequestStorage, RequestStorage>();
builder.Services.AddTransient<IOrderStorage, OrderStorage>(); builder.Services.AddTransient<IOrderStorage, OrderStorage>();
builder.Services.AddTransient<IUserLogic, UserLogic>(); builder.Services.AddTransient<IUserLogic, UserLogic>();
builder.Services.AddTransient<IShipmentLogic, ShipmentLogic>(); builder.Services.AddTransient<IShipmentLogic, ShipmentLogic>();
builder.Services.AddTransient<IRequestLogic, RequestLogic>(); builder.Services.AddTransient<IRequestLogic, RequestLogic>();
builder.Services.AddTransient<IOrderLogic, OrderLogic>(); builder.Services.AddTransient<IOrderLogic, OrderLogic>();
builder.Services.AddTransient<IAssemblyStorage, AssemblyStorage>();
builder.Services.AddTransient<IReportImplementerLogic, ReportImplementerLogic>();
builder.Services.AddTransient<AbstractSaveToWordImplementer, SaveToWordImplementer>();
builder.Services.AddTransient<AbstractSaveToExcelImplementer, SaveToExcelImplementer>();
builder.Services.AddTransient<AbstractSaveToPdfImplementer, SaveToPdfImplementer>();
//builder.Services.AddTransient<IReportImplementerLogic, ReportImplementerLogic>();
// Add services to the container. // Add services to the container.
builder.Services.AddControllersWithViews(); builder.Services.AddControllersWithViews();

View File

@ -8,25 +8,22 @@
<h2 class="display-4">Отчёт за период по заказам</h2> <h2 class="display-4">Отчёт за период по заказам</h2>
</div> </div>
<div class="form-group"> <div class="form-group">
<label class="mb-3" for="dateFrom">Начало периода</label> <label class="mb-3" for="dateFrom">Начало периода:</label>
<input type="datetime-local" placeholder="Выберите дату начала периода" id="dateFrom" name="dateFrom" /> <input type="datetime-local" placeholder="Выберите дату начала периода" id="dateFrom" name="dateFrom" />
</div> </div>
<div class="form-group"> <div class="form-group">
<label class="mb-3" for="dateTo">Окончание периода</label> <label class="mb-3" for="dateTo">Окончание периода:</label>
<input type="datetime-local" placeholder="Выберите дату окончания периода" id="dateTo" name="dateTo"/> <input type="datetime-local" placeholder="Выберите дату окончания периода" id="dateTo" name="dateTo"/>
</div> </div>
<div class="form-group">
<label class="mb-3">Текущий статус заказа:</label>
@* <input class="mb-3" type="text" id="currentStatus" name="currentStatus" readonly /> *@
<span id="currentStatus" style="font-weight: bold;"></span>
</div>
<div class="row"> <div class="row">
<button type="button" id="show">Вывести здесь</button>
<div class="col-4"><input type="submit" value="Отправить на почту" class="btn btn-primary" /></div> <div class="col-4"><input type="submit" value="Отправить на почту" class="btn btn-primary" /></div>
</div> </div>
<div class="mt-3" id="report">
</div>
</form> </form>
<div class="row">
<button class="mt-5" type="button" id="show">Вывести здесь</button>
</div>
<div class="mt-3" id="report">
</div>
<script> <script>

View File

@ -2,6 +2,7 @@
using ComputerShopContracts.BusinessLogicContracts; using ComputerShopContracts.BusinessLogicContracts;
using ComputerShopContracts.SearchModels; using ComputerShopContracts.SearchModels;
using ComputerShopContracts.ViewModels; using ComputerShopContracts.ViewModels;
using ComputerShopBusinessLogic.MailWorker;
using ComputerShopDatabaseImplement.Models; using ComputerShopDatabaseImplement.Models;
using ComputerShopDataModels.Enums; using ComputerShopDataModels.Enums;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
@ -18,11 +19,14 @@ namespace ComputerShopRestApi.Controllers
private readonly IReportImplementerLogic _reportLogic; private readonly IReportImplementerLogic _reportLogic;
public OrderController(IOrderLogic logic, ILogger<OrderController> logger, IReportImplementerLogic reportLogic) private readonly AbstractMailWorker _mailWorker;
public OrderController(IOrderLogic logic, ILogger<OrderController> logger, IReportImplementerLogic reportLogic, AbstractMailWorker mailWorker)
{ {
_logger = logger; _logger = logger;
_logic = logic; _logic = logic;
_reportLogic = reportLogic; _reportLogic = reportLogic;
_mailWorker = mailWorker;
} }
[HttpGet] [HttpGet]
@ -103,18 +107,34 @@ namespace ComputerShopRestApi.Controllers
throw; throw;
} }
} }
//МБ ИЗМЕНИТЬ IEnumerable на List
//!!!ПОТОМ УДАЛИТЬ
//[HttpGet]
//public IEnumerable<string> GetOrderStatuses()
//{
// // Получаем все значения из перечисления и возвращаем как список строк
// var allStatuses = Enum.GetValues(typeof(OrderStatus)).Cast<OrderStatus>().Select(status => status.ToString());
// return allStatuses;
//}
[HttpPost] [HttpPost]
public void SendPDFToMail(MailSendInfoBindingModel model)
{
try
{
_mailWorker.MailSendAsync(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отправки письма");
throw;
}
}
//МБ ИЗМЕНИТЬ IEnumerable на List
//!!!ПОТОМ УДАЛИТЬ
//[HttpGet]
//public IEnumerable<string> GetOrderStatuses()
//{
// // Получаем все значения из перечисления и возвращаем как список строк
// var allStatuses = Enum.GetValues(typeof(OrderStatus)).Cast<OrderStatus>().Select(status => status.ToString());
// return allStatuses;
//}
[HttpPost]
public void CreateOrder(OrderBindingModel model) public void CreateOrder(OrderBindingModel model)
{ {
try try

View File

@ -2,11 +2,13 @@ using ComputerShopBusinessLogic.BusinessLogics;
using ComputerShopContracts.BusinessLogicContracts; using ComputerShopContracts.BusinessLogicContracts;
using ComputerShopContracts.StorageContracts; using ComputerShopContracts.StorageContracts;
using ComputerShopDatabaseImplement.Implements; using ComputerShopDatabaseImplement.Implements;
using ComputerShopBusinessLogic.MailWorker;
using ComputerShopDatabaseImplement.Models; using ComputerShopDatabaseImplement.Models;
using ComputerShopDataModels.Models; using ComputerShopDataModels.Models;
using GarmentFactoryBusinessLogic.OfficePackage; using GarmentFactoryBusinessLogic.OfficePackage;
using GarmentFactoryBusinessLogic.OfficePackage.Implements; using GarmentFactoryBusinessLogic.OfficePackage.Implements;
using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models;
using ComputerShopContracts.BindingModels;
var Builder = WebApplication.CreateBuilder(args); var Builder = WebApplication.CreateBuilder(args);
Builder.Logging.SetMinimumLevel(LogLevel.Trace); Builder.Logging.SetMinimumLevel(LogLevel.Trace);
@ -40,6 +42,8 @@ Builder.Services.AddTransient<AbstractSaveToExcelImplementer, SaveToExcelImpleme
Builder.Services.AddTransient<AbstractSaveToWordImplementer, SaveToWordImplementer>(); Builder.Services.AddTransient<AbstractSaveToWordImplementer, SaveToWordImplementer>();
Builder.Services.AddTransient<AbstractSaveToPdfImplementer, SaveToPdfImplementer>(); Builder.Services.AddTransient<AbstractSaveToPdfImplementer, SaveToPdfImplementer>();
Builder.Services.AddSingleton<AbstractMailWorker, MailKitWorker>();
Builder.Services.AddControllers(); Builder.Services.AddControllers();
Builder.Services.AddEndpointsApiExplorer(); Builder.Services.AddEndpointsApiExplorer();
Builder.Services.AddSwaggerGen(c => Builder.Services.AddSwaggerGen(c =>
@ -53,6 +57,19 @@ 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())
});
if (App.Environment.IsDevelopment()) if (App.Environment.IsDevelopment())
{ {
App.UseSwagger(); App.UseSwagger();

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": "rpplab7chernyshev@gmail.com",
"MailPassword": "cojg axan axbk qtqb"
} }