pdf сделан, осталось добавить графики для доп задания и дезигн

This commit is contained in:
Danil Markov 2023-05-19 02:00:18 +04:00
parent 96a6d6bbf7
commit 5f5f175a0d
15 changed files with 298 additions and 47 deletions

View File

@ -0,0 +1,58 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using UniversityContracts.BindingModels;
namespace UniversityBusinessLogic.BusinessLogics
{
public class MailSender
{
private string mailLogin = string.Empty;
private string mailPassword = string.Empty;
private string smtpClientHost = string.Empty;
private int smtpClientPort;
public MailSender(){}
public void MailConfig(MailConfigBindingModel config)
{
mailLogin = config.MailLogin;
mailPassword = config.MailPassword;
smtpClientHost = config.SmtpClientHost;
smtpClientPort = config.SmtpClientPort;
}
public async void 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;
MemoryStream ms = new(info.File);
objMailMessage.Attachments.Add(new Attachment(ms, "report.pdf", "application/pdf"));
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

@ -3,11 +3,11 @@ using UniversityContracts.BusinessLogicContracts;
using UniversityContracts.ViewModels;
using UniversityContracts.SearchModels;
using UniversityContracts.StoragesContracts;
using CarDealershipBusinessLogic.BusinessLogic.OfficePackage;
using UniversityBusinessLogic.OfficePackage;
using System.Reflection.PortableExecutable;
using DocumentFormat.OpenXml.InkML;
using DocumentFormat.OpenXml.Wordprocessing;
using UniversityBusinessLogic.BusinessLogic.OfficePackage;
namespace UniversityBusinessLogic.BusinessLogics
{
@ -19,9 +19,10 @@ namespace UniversityBusinessLogic.BusinessLogics
private readonly IEducationGroupStorage _educationGroupStorage;
private readonly IDisciplineStorage _disciplineStorage;
private readonly IStreamStorage _streamStorage;
private readonly WordBuilderProvider wordBuilder;
private readonly ExcelBuilderProvider excelBuilder;
private readonly PdfBuilderProvider pdfBuilder;
private readonly WordBuilderProvider _wordBuilder;
private readonly ExcelBuilderProvider _excelBuilder;
private readonly PdfBuilderProvider _pdfBuilder;
private readonly MailSender _mailSender;
public ReportProviderLogic(IDocumentStorage documentStorage,
IStudentStorage studentStorage,
@ -31,7 +32,8 @@ namespace UniversityBusinessLogic.BusinessLogics
IStreamStorage streamStorage,
WordBuilderProvider wordBuilder,
ExcelBuilderProvider excelBuilder,
PdfBuilderProvider pdfBuilder)
PdfBuilderProvider pdfBuilder,
MailSender mailSender)
{
_documentStorage = documentStorage;
_studentStorage = studentStorage;
@ -39,9 +41,10 @@ namespace UniversityBusinessLogic.BusinessLogics
_educationGroupStorage = educationGroupStorage;
_disciplineStorage = disciplineStorage;
_streamStorage = streamStorage;
this.wordBuilder = wordBuilder;
this.excelBuilder = excelBuilder;
this.pdfBuilder = pdfBuilder;
_wordBuilder = wordBuilder;
_excelBuilder = excelBuilder;
_pdfBuilder = pdfBuilder;
_mailSender = mailSender;
}
public List<ReportStudentsDisciplineViewModel> GetStudentsDiscipline(List<StudentViewModel> students)
@ -55,7 +58,7 @@ namespace UniversityBusinessLogic.BusinessLogics
.ToList();
ReportStudentsDisciplineViewModel reportRecord = new()
{
Student = student.Name + " " + student.Surname + " " + student.StudentCard,
Student = student.Name + " " + student.Surname + ", " + student.StudentCard,
Disciplines = disciplines
};
reportRecords.Add(reportRecord);
@ -80,6 +83,7 @@ namespace UniversityBusinessLogic.BusinessLogics
.Select(s => new StudentStatusViewModel()
{
StudentName = s.Name + " " + s.Surname,
DateOfAddmission = s.DateOfAddmission,
EducationStatus = s.EducationStatusName
})
.ToList();
@ -95,40 +99,43 @@ namespace UniversityBusinessLogic.BusinessLogics
public byte[] SaveListFile(StudentDisciplineListBindingModel model)
{
byte[] file = Array.Empty<byte>();
string title = "Список дисциплин по выбранным студентам";
if (model.FileType == "docx")
{
wordBuilder.CreateDocument();
wordBuilder.CreateTitle("Список комплектаций по выбранным покупкам");
wordBuilder.CreateStudentsDisciplineTable(GetStudentsDiscipline(model.Students));
file = wordBuilder.GetFile();
_wordBuilder.CreateDocument();
_wordBuilder.CreateTitle(title);
_wordBuilder.CreateStudentsDisciplineTable(GetStudentsDiscipline(model.Students));
file = _wordBuilder.GetFile();
}
else if (model.FileType == "xlsx")
{
excelBuilder.CreateDocument();
excelBuilder.CreateTitle("Список комплектаций по выбранным покупкам");
excelBuilder.CreateStudentsDisciplineTable(GetStudentsDiscipline(model.Students));
file = excelBuilder.GetFile();
_excelBuilder.CreateDocument();
_excelBuilder.CreateTitle(title);
_excelBuilder.CreateStudentsDisciplineTable(GetStudentsDiscipline(model.Students));
file = _excelBuilder.GetFile();
}
return file;
}
public void SendByMailEducationStatusReport(ReportBindingModel reportModel)
public void SendByMailStatusReport(ReportBindingModel reportModel)
{
byte[] file = pdfBuilder.GetEquipmentReportFile(new()
byte[] file = _pdfBuilder.GetEducationStatusReportFile(new()
{
Title = "Отчет по комплектациям",
Title = "Отчет по статусам обучения",
DateFrom = reportModel.DateFrom,
DateTo = reportModel.DateTo,
Records = GetStreamStudentEdStatPeriod(reportModel)
});
/* mailSender.SendMailAsync(new ()
_mailSender.SendMailAsync(new ()
{
MailAddress = reportModel.UserEmail,
Subject = "Отчет по комплектациям",
Text = $"За период с {reportModel.DateFrom.ToShortDateString()} " +
$"по {reportModel.DateTo.ToShortDateString()}.",
File = file
}); */
});
}
}
}

View File

@ -5,8 +5,9 @@ using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Tables;
using MigraDoc.Rendering;
using PdfSharp.Pdf;
using System.Text;
namespace CarDealershipBusinessLogic.BusinessLogic.OfficePackage
namespace UniversityBusinessLogic.BusinessLogic.OfficePackage
{
public class PdfBuilderProvider
{
@ -93,6 +94,10 @@ namespace CarDealershipBusinessLogic.BusinessLogic.OfficePackage
private void Save()
{
// Регистрация провайдера кодировки для кодировки 1252, без этого ошибОчка была
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var renderer = new PdfDocumentRenderer(true)
{
Document = document
@ -109,7 +114,7 @@ namespace CarDealershipBusinessLogic.BusinessLogic.OfficePackage
return file;
}
public byte[] GetEquipmentReportFile(PdfData<ReportStreamStudentEdStatPeriodViewModel> data)
public byte[] GetEducationStatusReportFile(PdfData<ReportStreamStudentEdStatPeriodViewModel> data)
{
CreateDocument();
@ -128,11 +133,11 @@ namespace CarDealershipBusinessLogic.BusinessLogic.OfficePackage
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
CreateTable(new List<string> { "5cm", "5cm", "5cm" });
CreateTable(new List<string> { "4cm","5cm", "3cm", "3cm" });
CreateRow(new PdfRowParameters
{
Texts = new List<string> { "Статус обучения", "Поток", "Количество студентов" },
Texts = new List<string> { "Поток", "Студент", "Дата зачисления", "Статус обучения" },
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
@ -143,7 +148,7 @@ namespace CarDealershipBusinessLogic.BusinessLogic.OfficePackage
int recordHeight = studentsAndStatus.Count + 1;
for (int i = 0; i < recordHeight; i++)
{
List<string> cellsData = new() { "", "", "" };
List<string> cellsData = new() { "", "", "", "" };
if (i == 0)
{
cellsData[0] = record.StreamName;
@ -159,7 +164,8 @@ namespace CarDealershipBusinessLogic.BusinessLogic.OfficePackage
if (k < studentsAndStatus.Count)
{
cellsData[1] = studentsAndStatus[k].StudentName;
cellsData[2] = studentsAndStatus[k].EducationStatus;
cellsData[2] = studentsAndStatus[k].DateOfAddmission.ToString("yyyy-MM-dd");
cellsData[3] = studentsAndStatus[k].EducationStatus;
}
CreateRow(new PdfRowParameters
{

View File

@ -4,7 +4,7 @@ using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
namespace CarDealershipBusinessLogic.BusinessLogic.OfficePackage
namespace UniversityBusinessLogic.BusinessLogic.OfficePackage
{
public class WordBuilderProvider
{
@ -146,13 +146,13 @@ namespace CarDealershipBusinessLogic.BusinessLogic.OfficePackage
List<List<string>> rows = new();
foreach (ReportStudentsDisciplineViewModel student in data)
{
List<string> disciplineCells = new() { student.Student, "" };
rows.Add(disciplineCells);
List<string> workCells;
List<string> studentCells = new() { student.Student, "" };
rows.Add(studentCells);
List<string> disciplineCells;
foreach (string discipline in student.Disciplines)
{
workCells = new() { "", discipline };
rows.Add(workCells);
disciplineCells = new() { "", discipline };
rows.Add(disciplineCells);
}
}
WordTableData wordTable = new()

View File

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

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UniversityContracts.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;
public byte[] File { get; set; } = Array.Empty<byte>();
}
}

View File

@ -16,6 +16,6 @@ namespace UniversityContracts.BusinessLogicContracts
byte[] SaveListFile(StudentDisciplineListBindingModel model);
void SendByMailEducationStatusReport(ReportBindingModel reportModel);
void SendByMailStatusReport(ReportBindingModel reportModel);
}
}

View File

@ -9,6 +9,7 @@ namespace UniversityContracts.ViewModels
public class StudentStatusViewModel
{
public string StudentName { get; set; } = string.Empty;
public DateTime DateOfAddmission { get; set; }
public string EducationStatus { get; set; } = string.Empty;
}
}

View File

@ -151,7 +151,19 @@ namespace UniversityProvider.Controllers
("api/reportprovider/getreportdata", reportModel);
return list;
}
[HttpPost]
public void SendByMailStatusReport([FromBody] ReportBindingModel reportModel)
{
if (APIClient.User == null)
{
return;
}
reportModel.UserId = APIClient.User.Id;
reportModel.UserEmail = APIClient.User.Login;
APIClient.PostRequest("api/reportprovider/sendbymailstatusreport", reportModel);
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{

View File

@ -27,4 +27,27 @@
</button>
</div>
<p class="mb-0">
<span>За период с&nbsp;</span>
<span id="date-from-span" class="fw-bold">...</span>
<span>&nbsp;по&nbsp;</span>
<span id="date-to-span" class="fw-bold">...</span>
</p>
<div class="table-shell mb-2 border">
<table class="table mb-0">
<thead class="table-head">
<tr>
<th>Поток</th>
<th>Студент</th>
<th>Дата зачисления</th>
<th>Статус обучения</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
</div>
<div id="table"></div>
<script src="~/js/report/reportpdf.js" asp-append-version="true"></script>

View File

@ -2,6 +2,9 @@
const dateToInput = document.getElementById("date-to-input");
const generateButton = document.getElementById("generate-button");
const sendByMailButton = document.getElementById("send-by-mail-button");
const dateToSpan = document.getElementById("date-to-span");
const dateFromSpan = document.getElementById("date-from-span");
const tbody = document.getElementById("tbody");
generateButton.addEventListener("click", () => {
const dateFrom = new Date(dateFromInput.value);
@ -15,13 +18,53 @@ generateButton.addEventListener("click", () => {
type: "POST",
contentType: "application/json",
data: JSON.stringify(reportModel)
}).done((reportData) => {
/*dateFromSpan.innerHTML = reportModel["DateFrom"].toLocaleDateString();
dateToSpan.innerHTML = reportModel["DateTo"].toLocaleDateString();*/
renderTable(reportData);
}).done((data) => {
dateFromSpan.innerHTML = reportModel["DateFrom"].toLocaleDateString();
dateToSpan.innerHTML = reportModel["DateTo"].toLocaleDateString();
/*renderTable(reportData);*/
// Добавление данных
for (var i = 0; i < data.length; i++) {
var streamData = data[i];
var streamName = streamData.streamName;
// Добавление строки для каждого студента в потоке
for (var j = 0; j < streamData.studentStatus.length; j++) {
var student = streamData.studentStatus[j];
if (j === 0) {
var row = tbody.insertRow();
var streamNameCell = row.insertCell()
streamNameCell.textContent = streamName;
var studentNameCell = row.insertCell();
var dateOfAdmissionCell = row.insertCell();
var studentStatusCell = row.insertCell();
tbody.appendChild(row)
}
var row = tbody.insertRow();
var streamNameCell = row.insertCell()
var studentNameCell = row.insertCell();
studentNameCell.textContent = student.studentName;
var dateOfAdmissionCell = row.insertCell();
dateOfAdmissionCell.textContent = formatDate(student.dateOfAddmission);
var studentStatusCell = row.insertCell();
studentStatusCell.textContent = student.educationStatus;
tbody.appendChild(row);
}
}
});
});
const formatDate = (dateString) => {
const date = new Date(dateString);
const year = date.getFullYear();
const month = ('0' + (date.getMonth() + 1)).slice(-2);
const day = ('0' + date.getDate()).slice(-2);
return `${year}-${month}-${day}`;
};
sendByMailButton.addEventListener("click", () => {
const dateFrom = new Date(dateFromInput.value);
const dateTo = new Date(dateToInput.value);
@ -30,7 +73,7 @@ sendByMailButton.addEventListener("click", () => {
"DateTo": dateTo
};
$.ajax({
url: "/home/sendbymailequipmentreport",
url: "/home/sendbymailstatusreport",
type: "POST",
contentType: "application/json",
data: JSON.stringify(reportModel)
@ -39,6 +82,56 @@ sendByMailButton.addEventListener("click", () => {
});
});
const renderTable = function (reportData) {
tbody.innerHTML = "";
/*reportData.forEach((record) => {
const cars = record.cars;
const works = record.works;
const recordHeight = Math.max(cars.length + 1, works.length + 1);
for (let i = 0; i < recordHeight; i++) {
let cellsData = ["", "", "", ""];
if (i === 0) {
cellsData[0] = record.equipmentName;
cellsData[1] = getDate(record.equipmentDateCreate);
createTableRow(cellsData);
continue;
}
let k = i - 1;
if (k < cars.length) {
cellsData[2] = cars[k];
}
if (k < works.length) {
cellsData[3] = works[k];
}
createTableRow(cellsData);
}
});*/
const renderTable = (reportData) => {
console.log(reportData)
reportData.forEach((item) => {
var streamName = item.streamName;
var students = []
item.studentStatus.forEach((stud) => {
students.push({ studentName: stud.studentName, educationStatus: stud.educationName });
})
createTableSection(streamName, students);
})
}
const createTableSection = (streamName, students) => {
const tr = document.createElement('tr');
const trWrapper = [];
tr.classList.add("table-row");
tr.appendChild(createTableCell(streamName));
students.forEach((item) => {
const newTr = document.createElement('tr');
newTr.appendChild(createTableCell(item))
});
}
const createTableCell = (item) => {
const td = document.createElement('td');
td.innerHTML = cellText;
return td;
}

View File

@ -28,6 +28,7 @@ createBtn.addEventListener("click", () => {
"Name": nameInput.value,
"Surname": surnameInput.value,
"DateOfBirth": new Date(dateInput.value),
"DateOfAddmission": new Date(),
"StudentCard": parseInt(studCardInput.value),
};
console.log(student)

View File

@ -30,11 +30,10 @@ namespace UniversityRestAPI.Controllers
return list;
}
[HttpPost]
public void SendByMailEquipmentReport(ReportBindingModel reportModel)
public void SendByMailStatusReport(ReportBindingModel reportModel)
{
//reportLogic.SendByMailEquipmentReport(reportModel);
reportLogic.SendByMailStatusReport(reportModel);
}
}
}

View File

@ -1,4 +1,4 @@
using CarDealershipBusinessLogic.BusinessLogic.OfficePackage;
using UniversityBusinessLogic.BusinessLogic.OfficePackage;
using Microsoft.OpenApi.Models;
using System.Reflection.PortableExecutable;
using UniversityBusinessLogic.BusinessLogics;
@ -6,6 +6,7 @@ using UniversityBusinessLogic.OfficePackage;
using UniversityContracts.BusinessLogicContracts;
using UniversityContracts.StoragesContracts;
using UniversityDataBaseImplemet.Implements;
using UniversityContracts.BindingModels;
var builder = WebApplication.CreateBuilder(args);
@ -31,6 +32,8 @@ builder.Services.AddTransient<WordBuilderProvider>();
builder.Services.AddTransient<ExcelBuilderProvider>();
builder.Services.AddTransient<PdfBuilderProvider>();
builder.Services.AddSingleton<MailSender>();
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
@ -42,6 +45,15 @@ builder.Services.AddSwaggerGen(c =>
var app = builder.Build();
var mailSender = app.Services.GetService<MailSender>();
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()),
});
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{

View File

@ -5,5 +5,12 @@
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
"AllowedHosts": "*",
"SmtpClientHost": "smtp.gmail.com",
"SmtpClientPort": "587",
"PopHost": "pop.gmail.com",
"PopPort": "995",
"MailLogin": "rpplabs098@gmail.com",
"MailPassword": "sxwf ohjr cgba wext"
}