Compare commits

..

22 Commits

Author SHA1 Message Date
d71a022960 done 2023-06-22 00:20:17 +04:00
71de67e722 ref 2023-06-21 21:38:05 +04:00
9a6f9e100b Merge branch 'provider' of http://student.git.athene.tech/ker73rus/PIbd-21_Pyatakov_KM_Markov_DP_University into provider 2023-05-20 09:55:49 +04:00
755c3027c4 ддд 2023-05-20 09:55:46 +04:00
32e10131de fix 2023-05-20 07:18:17 +04:00
d05d582122 fix 2023-05-20 07:15:14 +04:00
89b1399fb8 fix 2023-05-20 06:19:34 +04:00
1813adc543 Merge branch 'cccc' into provider 2023-05-20 05:51:08 +04:00
d707ffd472 ccc 2023-05-20 05:46:02 +04:00
f202ad7898 на этом хватит 2023-05-20 01:34:25 +04:00
f155fd0684 customer for provider 2023-05-19 21:25:56 +04:00
6ba2b66dfc Сделан график по "Статус обучения - кол-во студентов", думаю над вторым графиком 2023-05-19 14:46:02 +04:00
7bc6efdc0c fix 2023-05-19 13:11:40 +04:00
5f5f175a0d pdf сделан, осталось добавить графики для доп задания и дезигн 2023-05-19 02:00:18 +04:00
96a6d6bbf7 Список word и excel сделан.
Почти сделан pdf (добавил вспомогательный viewmodel так как C# не умеет в кортежи).
Нужно доделать pdf с отправкой на почту и навести красоту (стили, валидацию)
2023-05-18 21:57:00 +04:00
bc6d955ad4 все crud сделаны. Привязка из нескольких записей групп для приказа сделана. Привязка из одной записи студента для статуса обучения сделана.
Остались отчеты, возможно графики и дезигн
2023-05-18 14:36:57 +04:00
7e3706b2f6 Documents - нужно сделать update и пофиксить delete.
многие ко многим работает (нужен фикс update и delete)
2023-05-18 04:35:12 +04:00
c87f2caaac EducationStatus crud с выбором из списка «Студенты» записи к ней 2023-05-17 22:54:39 +04:00
91212b9254 student crud 2023-05-17 16:47:38 +04:00
295dc0ad1d Регистрция + Вход 2023-05-16 23:35:28 +04:00
752868c67f role теперь enum + по мелочи 2023-05-16 22:01:03 +04:00
8388b39941 RestAPI + migration + начало интерфейса для поставщика 2023-05-15 20:29:07 +04:00
268 changed files with 83489 additions and 849 deletions

View File

@ -1 +1,2 @@
Курсовая работа по дисциплине "Разработка профессиональных приложений". Группа: ПИбд-21. Студенты: Пятаков К.М. и Марков Д.П.
# PIbd-21_Pyatakov_Km_Markov_DP_University

View File

@ -3,8 +3,6 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.4.33213.308
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UniversityCustomer", "UniversityCustomer\UniversityCustomer.csproj", "{1360F158-7807-49AD-94A2-4E2ACB2A941E}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UniversityModels", "UniversityModels\UniversityModels.csproj", "{597412F7-884C-49CB-AC41-36308551D330}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UniversityDataBaseImplemet", "UniversityDataBaseImplemet\UniversityDataBaseImplemet.csproj", "{F8532F5E-942B-428E-8A10-280E905B8185}"
@ -13,7 +11,11 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UniversityContracts", "Univ
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UniversityBusinessLogic", "UniversityBusinessLogic\UniversityBusinessLogic.csproj", "{1F4D08DA-C856-42E5-8E1A-634B6EDB4C9D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UniversityProvider", "UniversityProvider\UniversityProvider.csproj", "{3EC7CE2C-9D59-4570-B66B-746076D00A03}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UniversityProvider", "UniversityProvider\UniversityProvider.csproj", "{3EC7CE2C-9D59-4570-B66B-746076D00A03}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UniversityRestAPI", "UniversityRestAPI\UniversityRestAPI.csproj", "{24344F5E-3066-4B9B-82FC-F58608D0751D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UniversityCustomer", "UniversityCustomer\UniversityCustomer.csproj", "{E6E3DB3C-5E3F-446E-8724-3476D8A8C5B8}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -21,10 +23,6 @@ Global
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{1360F158-7807-49AD-94A2-4E2ACB2A941E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1360F158-7807-49AD-94A2-4E2ACB2A941E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1360F158-7807-49AD-94A2-4E2ACB2A941E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1360F158-7807-49AD-94A2-4E2ACB2A941E}.Release|Any CPU.Build.0 = Release|Any CPU
{597412F7-884C-49CB-AC41-36308551D330}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{597412F7-884C-49CB-AC41-36308551D330}.Debug|Any CPU.Build.0 = Debug|Any CPU
{597412F7-884C-49CB-AC41-36308551D330}.Release|Any CPU.ActiveCfg = Release|Any CPU
@ -45,6 +43,14 @@ Global
{3EC7CE2C-9D59-4570-B66B-746076D00A03}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3EC7CE2C-9D59-4570-B66B-746076D00A03}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3EC7CE2C-9D59-4570-B66B-746076D00A03}.Release|Any CPU.Build.0 = Release|Any CPU
{24344F5E-3066-4B9B-82FC-F58608D0751D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{24344F5E-3066-4B9B-82FC-F58608D0751D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{24344F5E-3066-4B9B-82FC-F58608D0751D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{24344F5E-3066-4B9B-82FC-F58608D0751D}.Release|Any CPU.Build.0 = Release|Any CPU
{E6E3DB3C-5E3F-446E-8724-3476D8A8C5B8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E6E3DB3C-5E3F-446E-8724-3476D8A8C5B8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E6E3DB3C-5E3F-446E-8724-3476D8A8C5B8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E6E3DB3C-5E3F-446E-8724-3476D8A8C5B8}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@ -72,6 +72,12 @@ namespace UniversityBusinessLogic.BusinessLogics
}
return true;
}
public int GetNumberOfPages(int userId, int pageSize = 10)
{
return _disciplineStorage.GetNumberOfPages(userId, pageSize);
}
private void CheckModel(DisciplineBindingModel model, bool withParams = true)
{
if (model == null)

View File

@ -69,6 +69,11 @@ namespace UniversityBusinessLogic.BusinessLogics
return list;
}
public int GetNumberOfPages(int userId, int pageSize = 10)
{
return _documentStorage.GetNumberOfPages(userId, pageSize);
}
private void CheckModel(DocumentBindingModel model, bool withParams = true)
{
if (model == null)

View File

@ -4,13 +4,14 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UniversityContracts.BindingModels;
using UniversityContracts.BusinessLogicContracts;
using UniversityContracts.SearchModels;
using UniversityContracts.StoragesContracts;
using UniversityContracts.ViewModels;
namespace UniversityBusinessLogic.BusinessLogics
{
public class EducationGroupLogic
public class EducationGroupLogic : IEducationGroupLogic
{
private readonly IEducationGroupStorage _egStorage;
@ -70,6 +71,11 @@ namespace UniversityBusinessLogic.BusinessLogics
return list;
}
public int GetNumberOfPages(int userId, int pageSize = 10)
{
return _egStorage.GetNumberOfPages(userId, pageSize);
}
private void CheckModel(EducationGroupBindingModel model, bool withParams = true)
{
if (model == null)

View File

@ -71,6 +71,16 @@ namespace UniversityBusinessLogic.BusinessLogics
return list;
}
public List<EducationStatusStudentsCountViewModel> GetEducationStatusStudents()
{
return _esStorage.GetEducationStatusStudents() ?? new List<EducationStatusStudentsCountViewModel>();
}
public int GetNumberOfPages(int userId, int pageSize = 10)
{
return _esStorage.GetNumberOfPages(userId, pageSize);
}
private void CheckModel(EducationStatusBindingModel model, bool withParams = true)
{
if (model == null)

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

@ -1,17 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UniversityContracts.BindingModels;
using UniversityContracts.BindingModels;
using UniversityContracts.BusinessLogicContracts;
using UniversityContracts.ViewModels;
using UniversityContracts.SearchModels;
using UniversityContracts.StoragesContracts;
using UniversityBusinessLogic.OfficePackage;
using System.Reflection;
using System.Net;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using DocumentFormat.OpenXml.InkML;
using DocumentFormat.OpenXml.Wordprocessing;
using UniversityBusinessLogic.BusinessLogic.OfficePackage;
namespace UniversityBusinessLogic.BusinessLogics
{
@ -23,9 +19,10 @@ namespace UniversityBusinessLogic.BusinessLogics
private readonly IEducationGroupStorage _educationGroupStorage;
private readonly IDisciplineStorage _disciplineStorage;
private readonly IStreamStorage _streamStorage;
private readonly AbstractSaveToExcelProvider _saveToExcel;
private readonly AbstractSaveToWordProvider _saveToWord;
private readonly AbstractSaveToPdfProvider _saveToPdf;
private readonly WordBuilderCustomer _wordBuilder;
private readonly ExcelBuilderCustomer _excelBuilder;
private readonly PdfBuilderProvider _pdfBuilder;
private readonly MailSender _mailSender;
public ReportCustomerLogic(IDocumentStorage documentStorage,
IStudentStorage studentStorage,
@ -33,9 +30,10 @@ namespace UniversityBusinessLogic.BusinessLogics
IEducationGroupStorage educationGroupStorage,
IDisciplineStorage disciplineStorage,
IStreamStorage streamStorage,
AbstractSaveToExcelProvider saveToExcel,
AbstractSaveToWordProvider saveToWord,
AbstractSaveToPdfProvider saveToPdf)
WordBuilderCustomer wordBuilder,
ExcelBuilderCustomer excelBuilder,
PdfBuilderProvider pdfBuilder,
MailSender mailSender)
{
_documentStorage = documentStorage;
_studentStorage = studentStorage;
@ -43,66 +41,86 @@ namespace UniversityBusinessLogic.BusinessLogics
_educationGroupStorage = educationGroupStorage;
_disciplineStorage = disciplineStorage;
_streamStorage = streamStorage;
_saveToExcel = saveToExcel;
_saveToWord = saveToWord;
_saveToPdf = saveToPdf;
_wordBuilder = wordBuilder;
_excelBuilder = excelBuilder;
_pdfBuilder = pdfBuilder;
_mailSender = mailSender;
}
public List<ReportDisciplineViewModel> GetDiscipline(ReportBindingModel model)
public List<ReportStudentsDisciplineViewModel> GetStudentsDiscipline(List<StudentViewModel> students)
{
var result = _streamStorage.GetFilteredList(new StreamSearchModel { Id = _disciplineStorage.GetElement(new DisciplineSearchModel { Name = model.DisciplineName })?.StreamId })
.Select(stream => new ReportDisciplineViewModel
var reportRecords = new List<ReportStudentsDisciplineViewModel>();
foreach (var student in students)
{
var disciplines = _studentStorage.GetStudentStreams(new() { Id = student.Id })
.SelectMany(stream => _streamStorage.GetStreamDisciplines(new() { Id = stream.Id }))
.Select(discipline => discipline.Name)
.ToList();
ReportStudentsDisciplineViewModel reportRecord = new()
{
DisciplineName = model.DisciplineName,
StudentEdStatus = stream.StudentStream
.Where(student => _documentStorage.GetFilteredList(new DocumentSearchModel
{
UserId = model.UserId,
DateFrom = model.DateFrom,
DateTo = model.DateTo,
})
.Any(document => document.StudentDocument.ContainsKey(student.Value.Id)))//Выбираем студентов, которые есть в приказах за выбранный промежуток времени
.Join(_documentStorage.GetFullList(),
t1 => t1.Value.Id,
t2 => t2.UserId,
(t1, t2) => new { student = t1, document = t2 })
.Select(res => (
StudentFIO: $"{res.student.Value.Name} {res.student.Value.Surname}",
Document: $"{res.document.Date}",
EdStatus: _educationStatusStorage.GetElement(new EducationStatusSearchModel { Id = res.student.Value.EducationStatusId })?.Name ?? "не удалось получить"))
.ToList()
})
.ToList();
return result;
Student = student.Name + " " + student.Surname + ", " + student.StudentCard,
Disciplines = disciplines
};
reportRecords.Add(reportRecord);
}
return reportRecords;
}
public List<ReportStreamEducationStatusViewModel> StreamEducationStatus(List<StreamViewModel> streams)
public byte[] SaveListFile(StreamStudentBindingModel model)
{
var result = streams
.Select(stream => new ReportStreamEducationStatusViewModel
{
StreamName = stream.Name,
StudentEdStatus = stream.StudentStream
.Select(student => (
StudentFIO: $"{student.Value.Name} {student.Value.Surname}",
EdStatus: _educationStatusStorage.GetElement(new EducationStatusSearchModel { Id = student.Value.EducationStatusId })?.Name ?? "не удалось получить"))
.ToList()
})
.ToList();
return result;
byte[] file = Array.Empty<byte>();
string title = "Список студентов по потоку " + model.StreamName;
if (model.FileType == "docx")
{
_wordBuilder.CreateDocument();
_wordBuilder.CreateTitle(title);
_wordBuilder.CreateStudentsStatusTable(model.Students);
file = _wordBuilder.GetFile();
}
else if (model.FileType == "xlsx")
{
_excelBuilder.CreateDocument();
_excelBuilder.CreateTitle(title);
_excelBuilder.CreateStudentsDisciplineTable(model.Students);
file = _excelBuilder.GetFile();
}
return file;
}
public void SendByMailStatusReport(ReportBindingModel reportModel)
{
/*byte[] file = _pdfBuilder.GetEducationStatusReportFile(new()
{
Title = "Отчет по статусам обучения",
DateFrom = reportModel.DateFrom,
DateTo = reportModel.DateTo,
Records = GetStreamStudentEdStatPeriod(reportModel)
});
_mailSender.SendMailAsync(new()
{
MailAddress = reportModel.UserEmail,
Subject = "Отчет по статусам обучения",
Text = $"За период с {reportModel.DateFrom.ToShortDateString()} " +
$"по {reportModel.DateTo.ToShortDateString()}.",
File = file
});*/
}
public void SaveBlanksToWordFile(ReportBindingModel model)
List<ReportDisciplineViewModel> IReportCustomerLogic.GetDiscipline(ReportBindingModel model)
{
throw new NotImplementedException();
}
public void SaveDocumentBlankToExcelFile(ReportBindingModel model)
List<ReportStreamEducationStatusViewModel> IReportCustomerLogic.StreamEducationStatus(List<StreamViewModel> streams)
{
throw new NotImplementedException();
}
public void SaveOrdersToPdfFile(ReportBindingModel model)
void IReportCustomerLogic.SendByMailStatusReport(ReportBindingModel reportModel)
{
throw new NotImplementedException();
}

View File

@ -1,14 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UniversityContracts.BindingModels;
using UniversityContracts.BindingModels;
using UniversityContracts.BusinessLogicContracts;
using UniversityContracts.ViewModels;
using UniversityContracts.SearchModels;
using UniversityContracts.StoragesContracts;
using UniversityBusinessLogic.OfficePackage;
using System.Reflection.PortableExecutable;
using DocumentFormat.OpenXml.InkML;
using DocumentFormat.OpenXml.Wordprocessing;
using UniversityBusinessLogic.BusinessLogic.OfficePackage;
namespace UniversityBusinessLogic.BusinessLogics
{
@ -20,19 +19,21 @@ namespace UniversityBusinessLogic.BusinessLogics
private readonly IEducationGroupStorage _educationGroupStorage;
private readonly IDisciplineStorage _disciplineStorage;
private readonly IStreamStorage _streamStorage;
private readonly AbstractSaveToExcelProvider _saveToExcel;
private readonly AbstractSaveToWordProvider _saveToWord;
private readonly AbstractSaveToPdfProvider _saveToPdf;
private readonly WordBuilderProvider _wordBuilder;
private readonly ExcelBuilderProvider _excelBuilder;
private readonly PdfBuilderProvider _pdfBuilder;
private readonly MailSender _mailSender;
public ReportProviderLogic(IDocumentStorage documentStorage,
IStudentStorage studentStorage,
IEducationStatusStorage educationStatusStorage,
IEducationGroupStorage educationGroupStorage,
IDisciplineStorage disciplineStorage,
IStreamStorage streamStorage,
AbstractSaveToExcelProvider saveToExcel,
AbstractSaveToWordProvider saveToWord,
AbstractSaveToPdfProvider saveToPdf)
IStreamStorage streamStorage,
WordBuilderProvider wordBuilder,
ExcelBuilderProvider excelBuilder,
PdfBuilderProvider pdfBuilder,
MailSender mailSender)
{
_documentStorage = documentStorage;
_studentStorage = studentStorage;
@ -40,69 +41,98 @@ namespace UniversityBusinessLogic.BusinessLogics
_educationGroupStorage = educationGroupStorage;
_disciplineStorage = disciplineStorage;
_streamStorage = streamStorage;
_saveToExcel = saveToExcel;
_saveToWord = saveToWord;
_saveToPdf = saveToPdf;
_wordBuilder = wordBuilder;
_excelBuilder = excelBuilder;
_pdfBuilder = pdfBuilder;
_mailSender = mailSender;
}
public List<ReportStudentsDisciplineViewModel> GetStudentsDiscipline(List<StudentViewModel> students)
{
var result = students
.Select(student => new ReportStudentsDisciplineViewModel
var reportRecords = new List<ReportStudentsDisciplineViewModel>();
foreach (var student in students)
{
var disciplines = _studentStorage.GetStudentStreams(new() { Id = student.Id })
.SelectMany(stream => _streamStorage.GetStreamDisciplines(new() { Id = stream.Id }))
.Select(discipline => discipline.Name)
.ToList();
ReportStudentsDisciplineViewModel reportRecord = new()
{
StudentFIO = $"{student.Name} {student.Surname}",
Disciplines = _streamStorage.GetFullList()
.Where(stream => stream.StudentStream.ContainsKey(student.Id))
.Join(_disciplineStorage.GetFullList(),
stream => stream.Id,
discipline => discipline.StreamId,
(stream, discipline) => discipline.Name)
.ToList()
})
.ToList();
return result;
Student = student.Name + " " + student.Surname + ", " + student.StudentCard,
Disciplines = disciplines
};
reportRecords.Add(reportRecord);
}
return reportRecords;
}
public List<ReportStreamStudentEdStatPeriodViewModel> StreamStudentEdStatPeriod(ReportBindingModel model)
public List<ReportStreamStudentEdStatPeriodViewModel> GetStreamStudentEdStatPeriod(ReportBindingModel model)
{
var result = _streamStorage
.GetFilteredList(new StreamSearchModel { UserId = model.UserId })
.Select(stream => new ReportStreamStudentEdStatPeriodViewModel
{
StreamName = stream.Name,
StudentEdStatus = stream.StudentStream
.Where(student => _documentStorage.GetFilteredList(new DocumentSearchModel
{
UserId = model.UserId,
DateFrom = model.DateFrom,
DateTo = model.DateTo,
})
.Any(document => document.StudentDocument.ContainsKey(student.Value.Id)))//Выбираем студентов, которые есть в приказах за выбранный промежуток времени
.Select(student => (
StudentFIO: $"{student.Value.Name} {student.Value.Surname}",
EdStatus: _educationStatusStorage.GetElement(new EducationStatusSearchModel { Id = student.Value.EducationStatusId })?.Name ?? "не удалось получить"))
.ToList()
})
.ToList();
return result;
List<ReportStreamStudentEdStatPeriodViewModel> reportRecords = new List<ReportStreamStudentEdStatPeriodViewModel>();
var streams = _streamStorage.GetFullList();
foreach (var stream in streams)
{
ReportStreamStudentEdStatPeriodViewModel reportData = new ReportStreamStudentEdStatPeriodViewModel();
reportData.StreamName = stream.Name;
var students = _streamStorage.GetStreamStudents(new() { Id = stream.Id, DateFrom = model.DateFrom, DateTo = model.DateTo })
.Select(s => new StudentStatusViewModel()
{
StudentName = s.Name + " " + s.Surname,
DateOfAddmission = s.DateOfAddmission,
EducationStatus = s.EducationStatusName
})
.ToList();
reportData.StudentStatus = students;
reportRecords.Add(reportData);
}
return reportRecords;
}
public void SaveBlanksToWordFile(ReportBindingModel model)
public byte[] SaveListFile(StudentDisciplineListBindingModel model)
{
throw new NotImplementedException();
//TODO
byte[] file = Array.Empty<byte>();
string title = "Список дисциплин по выбранным студентам";
if (model.FileType == "docx")
{
_wordBuilder.CreateDocument();
_wordBuilder.CreateTitle(title);
_wordBuilder.CreateStudentsDisciplineTable(GetStudentsDiscipline(model.Students));
file = _wordBuilder.GetFile();
}
else if (model.FileType == "xlsx")
{
_excelBuilder.CreateDocument();
_excelBuilder.CreateTitle(title);
_excelBuilder.CreateStudentsDisciplineTable(GetStudentsDiscipline(model.Students));
file = _excelBuilder.GetFile();
}
return file;
}
public void SaveDocumentBlankToExcelFile(ReportBindingModel model)
public void SendByMailStatusReport(ReportBindingModel reportModel)
{
throw new NotImplementedException();
//TODO
}
public void SaveOrdersToPdfFile(ReportBindingModel model)
{
throw new NotImplementedException();
//TODO
byte[] file = _pdfBuilder.GetEducationStatusReportFile(new()
{
Title = "Отчет по статусам обучения",
DateFrom = reportModel.DateFrom,
DateTo = reportModel.DateTo,
Records = GetStreamStudentEdStatPeriod(reportModel)
});
_mailSender.SendMailAsync(new ()
{
MailAddress = reportModel.UserEmail,
Subject = "Отчет по статусам обучения",
Text = $"За период с {reportModel.DateFrom.ToShortDateString()} " +
$"по {reportModel.DateTo.ToShortDateString()}.",
File = file
});
}
}
}

View File

@ -1,100 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UniversityContracts.BindingModels;
using UniversityContracts.BusinessLogicContracts;
using UniversityContracts.SearchModels;
using UniversityContracts.StoragesContracts;
using UniversityContracts.ViewModels;
namespace UniversityBusinessLogic.BusinessLogics
{
public class RoleLogic : IRoleLogic
{
private readonly IRoleStorage _roleStorage;
public RoleLogic(IRoleStorage roleStorage)
{
_roleStorage = roleStorage;
}
public bool Create(RoleBindingModel model)
{
CheckModel(model);
if (_roleStorage.Insert(model) == null)
{
return false;
}
return true;
}
public bool Delete(RoleBindingModel model)
{
CheckModel(model, false);
if (_roleStorage.Delete(model) == null)
{
return false;
}
return true;
}
public RoleViewModel? ReadElement(RoleSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
var element = _roleStorage.GetElement(model);
if (element == null)
{
return null;
}
return element;
}
public List<RoleViewModel>? ReadList(RoleSearchModel? model)
{
var list = model == null ? _roleStorage.GetFullList() : _roleStorage.GetFilteredList(model);
if (list == null)
{
return null;
}
return list;
}
public bool Update(RoleBindingModel model)
{
CheckModel(model);
if (_roleStorage.Update(model) == null)
{
return false;
}
return true;
}
private void CheckModel(RoleBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.Name))
{
throw new ArgumentNullException("Нет названия роли", nameof(model.Name));
}
var element = _roleStorage.GetElement(new RoleSearchModel
{
Name = model.Name
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Роль с таким названием уже есть");
}
}
}
}

View File

@ -71,6 +71,11 @@ namespace UniversityBusinessLogic.BusinessLogics
return list;
}
public int GetNumberOfPages(int userId, int pageSize = 10)
{
return _streamStorage.GetNumberOfPages(userId, pageSize);
}
private void CheckModel(StreamBindingModel model, bool withParams = true)
{
if (model == null)

View File

@ -71,7 +71,12 @@ namespace UniversityBusinessLogic.BusinessLogics
return list;
}
private void CheckModel(StudentBindingModel model, bool withParams = true)
public int GetNumberOfPages(int userId, int pageSize = 10)
{
return _studentStorage.GetNumberOfPages(userId, pageSize);
}
private void CheckModel(StudentBindingModel model, bool withParams = true)
{
if (model == null)
{
@ -83,9 +88,17 @@ namespace UniversityBusinessLogic.BusinessLogics
}
if (string.IsNullOrEmpty(model.Name))
{
throw new ArgumentNullException("Нет названия документа", nameof(model.Name));
throw new ArgumentNullException("Нет имени студента", nameof(model.Name));
}
if (model.StudentCard <= 0)
if (string.IsNullOrEmpty(model.Name))
{
throw new ArgumentNullException("Нет фамилии студента", nameof(model.Name));
}
if (model.DateOfBirth > DateTime.UtcNow)
{
throw new ArgumentNullException("Неверно указана дата рождения студента", nameof(model.Name));
}
if (model.StudentCard <= 0)
{
throw new ArgumentNullException("Неверно указан номер студенческого билета", nameof(model.Name));
}
@ -96,8 +109,13 @@ namespace UniversityBusinessLogic.BusinessLogics
});
if (student != null && student.Id != model.Id)
{
throw new InvalidOperationException("Приказ с таким названием уже есть");
throw new InvalidOperationException("Студент с таким номером студенческого билета уже есть");
}
}
public List<StudentViewModel> GetStudentsFromStream(int streamId)
{
return _studentStorage.GetStudentsFromStream(streamId);
}
}
}

View File

@ -63,14 +63,15 @@ namespace UniversityBusinessLogic.BusinessLogics
return list;
}
public bool Update(UserBindingModel model)
public UserViewModel Update(UserBindingModel model)
{
CheckModel(model, false);
if (_userStorage.Update(model) == null)
var user = _userStorage.Update(model);
if (user == null)
{
return false;
return new();
}
return true;
return user;
}
private void CheckModel(UserBindingModel model, bool withParams = true)
{

View File

@ -1,12 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UniversityBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToExcelProvider
{
}
}

View File

@ -1,12 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UniversityBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToWordProvider
{
}
}

View File

@ -0,0 +1,8 @@
namespace UniversityBusinessLogic.OfficePackage.Enums
{
public enum PdfParagraphAlignmentType
{
Center,
Left
}
}

View File

@ -0,0 +1,344 @@
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UniversityBusinessLogic.OfficePackage.Models;
using UniversityContracts.ViewModels;
namespace UniversityBusinessLogic.OfficePackage
{
public class ExcelBuilderCustomer
{
private readonly string tempFileName = "temp.xlsx";
private SpreadsheetDocument? spreadsheetDocument;
private SharedStringTablePart? shareStringPart;
private Worksheet? worksheet;
private void CreateStyles(WorkbookPart workbookpart)
{
var sp = workbookpart.AddNewPart<WorkbookStylesPart>();
sp.Stylesheet = new Stylesheet();
var fonts = new Fonts() { Count = 2U, KnownFonts = true };
var fontUsual = new Font();
fontUsual.Append(new FontSize() { Val = 12D });
fonts.Append(fontUsual);
var fontTitle = new Font();
fontTitle.Append(new Bold());
fontTitle.Append(new FontSize() { Val = 12D });
fonts.Append(fontTitle);
var fills = new Fills() { Count = 3U };
var fill1 = new Fill();
fill1.Append(new PatternFill()
{
PatternType = PatternValues.None
});
var fill2 = new Fill();
fill2.Append(new PatternFill()
{
PatternType = PatternValues.Gray125
});
var fill3 = new Fill();
fill3.Append(new PatternFill()
{
PatternType = PatternValues.Solid,
ForegroundColor = new()
{
Rgb = "e0e8ff"
}
});
var fill4 = new Fill();
fill1.Append(new PatternFill()
{
PatternType = PatternValues.None
});
fills.Append(fill1);
fills.Append(fill2);
fills.Append(fill3);
fills.Append(fill4);
var borders = new Borders() { Count = 2U };
var borderNoBorder = new Border();
borderNoBorder.Append(new LeftBorder());
borderNoBorder.Append(new RightBorder());
borderNoBorder.Append(new TopBorder());
borderNoBorder.Append(new BottomBorder());
borderNoBorder.Append(new DiagonalBorder());
var borderThin = new Border();
var leftBorder = new LeftBorder() { Style = BorderStyleValues.Thin };
leftBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
var rightBorder = new RightBorder() { Style = BorderStyleValues.Thin };
rightBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
var topBorder = new TopBorder() { Style = BorderStyleValues.Thin };
topBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
var bottomBorder = new BottomBorder() { Style = BorderStyleValues.Thin };
bottomBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
borderThin.Append(leftBorder);
borderThin.Append(rightBorder);
borderThin.Append(topBorder);
borderThin.Append(bottomBorder);
borderThin.Append(new DiagonalBorder());
borders.Append(borderNoBorder);
borders.Append(borderThin);
CellFormats cellFormats = new() { Count = 4U };
CellFormat cellFormatEmpty = new()
{
FontId = 0U,
FillId = 0U,
BorderId = 1U,
ApplyFont = true
};
CellFormat cellFormatDefault = new()
{
FontId = 0U,
FillId = 3U,
BorderId = 1U,
ApplyFont = true
};
CellFormat cellFormatTitle = new()
{
FontId = 1U,
FillId = 2U,
BorderId = 1U,
ApplyFont = true,
ApplyBorder = true,
Alignment = new Alignment()
{
Vertical = VerticalAlignmentValues.Center,
Horizontal = HorizontalAlignmentValues.Center,
WrapText = true
}
};
cellFormats.Append(cellFormatEmpty);
cellFormats.Append(cellFormatDefault);
cellFormats.Append(cellFormatTitle);
sp.Stylesheet.Append(fonts);
sp.Stylesheet.Append(fills);
sp.Stylesheet.Append(borders);
sp.Stylesheet.Append(cellFormats);
}
public void CreateDocument()
{
spreadsheetDocument = SpreadsheetDocument.Create(tempFileName,
SpreadsheetDocumentType.Workbook);
WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
CreateStyles(workbookpart);
shareStringPart = spreadsheetDocument.WorkbookPart!
.GetPartsOfType<SharedStringTablePart>()
.Any()
? spreadsheetDocument.WorkbookPart
.GetPartsOfType<SharedStringTablePart>()
.First()
: spreadsheetDocument.WorkbookPart
.AddNewPart<SharedStringTablePart>();
if (shareStringPart.SharedStringTable == null)
{
shareStringPart.SharedStringTable = new SharedStringTable();
}
WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild(new Sheets());
Sheet sheet = new()
{
Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Лист"
};
sheets.Append(sheet);
worksheet = worksheetPart.Worksheet;
}
public void InsertCellInWorksheet(ExcelCellData cellData)
{
if (worksheet == null || shareStringPart == null)
{
return;
}
var sheetData = worksheet.GetFirstChild<SheetData>();
if (sheetData == null)
{
return;
}
Row? row = sheetData.Elements<Row>()
.Where(r => r.RowIndex! == cellData.RowIndex)
.FirstOrDefault();
if (row == null)
{
row = new Row() { RowIndex = cellData.RowIndex };
sheetData.Append(row);
}
Cell? cell = row.Elements<Cell>()
.Where(c => c.CellReference!.Value == cellData.CellReference)
.FirstOrDefault();
if (cell == null)
{
Cell? refCell = null;
foreach (Cell rowCell in row.Elements<Cell>())
{
if (string.Compare(rowCell.CellReference!.Value, cellData.CellReference, true) > 0)
{
refCell = rowCell;
break;
}
}
var newCell = new Cell()
{
CellReference = cellData.CellReference
};
row.InsertBefore(newCell, refCell);
cell = newCell;
}
shareStringPart.SharedStringTable.AppendChild(new SharedStringItem(new Text(cellData.Text)));
shareStringPart.SharedStringTable.Save();
cell.CellValue = new CellValue((shareStringPart.SharedStringTable.Elements<SharedStringItem>().Count() - 1).ToString());
cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
cell.StyleIndex = cellData.StyleIndex;
}
private void MergeCells(ExcelMergeParameters excelParams)
{
if (worksheet == null)
{
return;
}
MergeCells mergeCells;
if (worksheet.Elements<MergeCells>().Any())
{
mergeCells = worksheet.Elements<MergeCells>().First();
}
else
{
mergeCells = new MergeCells();
if (worksheet.Elements<CustomSheetView>().Any())
{
worksheet.InsertAfter(mergeCells, worksheet.Elements<CustomSheetView>().First());
}
else
{
worksheet.InsertAfter(mergeCells, worksheet.Elements<SheetData>().First());
}
}
var mergeCell = new MergeCell()
{
Reference = new StringValue(excelParams.Merge)
};
mergeCells.Append(mergeCell);
}
private void Save()
{
if (spreadsheetDocument == null)
{
return;
}
spreadsheetDocument.WorkbookPart!.Workbook.Save();
spreadsheetDocument.Dispose();
}
public byte[] GetFile()
{
Save();
byte[] file = File.ReadAllBytes(tempFileName);
File.Delete(tempFileName);
return file;
}
public void CreateTitle(string text)
{
MergeCells(new ExcelMergeParameters
{
CellFromName = "A1",
CellToName = "B1"
});
InsertCellInWorksheet(new ExcelCellData
{
ColumnName = "A",
RowIndex = 1,
Text = text,
StyleIndex = 0
});
}
public void CreateStudentsDisciplineTable(List<StudentViewModel> students)
{
if (worksheet == null || shareStringPart == null)
{
return;
}
Columns columns = new();
Column columnA = new() { Min = 1, Max = 1, Width = 30, CustomWidth = true };
columns.Append(columnA);
Column columnB = new() { Min = 2, Max = 2, Width = 30, CustomWidth = true };
columns.Append(columnB);
worksheet.InsertAt(columns, 0);
InsertCellInWorksheet(new ExcelCellData
{
ColumnName = "A",
RowIndex = 2,
Text = "Студент",
StyleIndex = 2
});
InsertCellInWorksheet(new ExcelCellData
{
ColumnName = "B",
RowIndex = 2,
Text = "Дисциплина",
StyleIndex = 2
});
uint currentRow = 3;
foreach (StudentViewModel student in students)
{
InsertCellInWorksheet(new ExcelCellData
{
ColumnName = "A",
RowIndex = currentRow,
Text = student.Name + " " + student.Surname,
StyleIndex = 1
});
InsertCellInWorksheet(new ExcelCellData
{
ColumnName = "B",
RowIndex = currentRow,
Text = student.EducationStatusName,
StyleIndex = 1
});
currentRow++;
}
}
}
}

View File

@ -0,0 +1,356 @@
using UniversityBusinessLogic.OfficePackage.Models;
using UniversityContracts.ViewModels;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
namespace UniversityBusinessLogic.OfficePackage
{
public class ExcelBuilderProvider
{
private readonly string tempFileName = "temp.xlsx";
private SpreadsheetDocument? spreadsheetDocument;
private SharedStringTablePart? shareStringPart;
private Worksheet? worksheet;
private void CreateStyles(WorkbookPart workbookpart)
{
var sp = workbookpart.AddNewPart<WorkbookStylesPart>();
sp.Stylesheet = new Stylesheet();
var fonts = new Fonts() { Count = 2U, KnownFonts = true };
var fontUsual = new Font();
fontUsual.Append(new FontSize() { Val = 12D });
fonts.Append(fontUsual);
var fontTitle = new Font();
fontTitle.Append(new Bold());
fontTitle.Append(new FontSize() { Val = 12D });
fonts.Append(fontTitle);
var fills = new Fills() { Count = 3U };
var fill1 = new Fill();
fill1.Append(new PatternFill()
{
PatternType = PatternValues.None
});
var fill2 = new Fill();
fill2.Append(new PatternFill()
{
PatternType = PatternValues.Gray125
});
var fill3 = new Fill();
fill3.Append(new PatternFill()
{
PatternType = PatternValues.Solid,
ForegroundColor = new()
{
Rgb = "e0e8ff"
}
});
var fill4 = new Fill();
fill1.Append(new PatternFill()
{
PatternType = PatternValues.None
});
fills.Append(fill1);
fills.Append(fill2);
fills.Append(fill3);
fills.Append(fill4);
var borders = new Borders() { Count = 2U };
var borderNoBorder = new Border();
borderNoBorder.Append(new LeftBorder());
borderNoBorder.Append(new RightBorder());
borderNoBorder.Append(new TopBorder());
borderNoBorder.Append(new BottomBorder());
borderNoBorder.Append(new DiagonalBorder());
var borderThin = new Border();
var leftBorder = new LeftBorder() { Style = BorderStyleValues.Thin };
leftBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
var rightBorder = new RightBorder() { Style = BorderStyleValues.Thin };
rightBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
var topBorder = new TopBorder() { Style = BorderStyleValues.Thin };
topBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
var bottomBorder = new BottomBorder() { Style = BorderStyleValues.Thin };
bottomBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
borderThin.Append(leftBorder);
borderThin.Append(rightBorder);
borderThin.Append(topBorder);
borderThin.Append(bottomBorder);
borderThin.Append(new DiagonalBorder());
borders.Append(borderNoBorder);
borders.Append(borderThin);
CellFormats cellFormats = new() { Count = 4U };
CellFormat cellFormatEmpty = new()
{
FontId = 0U,
FillId = 0U,
BorderId = 1U,
ApplyFont = true
};
CellFormat cellFormatDefault = new()
{
FontId = 0U,
FillId = 3U,
BorderId = 1U,
ApplyFont = true
};
CellFormat cellFormatTitle = new()
{
FontId = 1U,
FillId = 2U,
BorderId = 1U,
ApplyFont = true,
ApplyBorder = true,
Alignment = new Alignment()
{
Vertical = VerticalAlignmentValues.Center,
Horizontal = HorizontalAlignmentValues.Center,
WrapText = true
}
};
cellFormats.Append(cellFormatEmpty);
cellFormats.Append(cellFormatDefault);
cellFormats.Append(cellFormatTitle);
sp.Stylesheet.Append(fonts);
sp.Stylesheet.Append(fills);
sp.Stylesheet.Append(borders);
sp.Stylesheet.Append(cellFormats);
}
public void CreateDocument()
{
spreadsheetDocument = SpreadsheetDocument.Create(tempFileName,
SpreadsheetDocumentType.Workbook);
WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
CreateStyles(workbookpart);
shareStringPart = spreadsheetDocument.WorkbookPart!
.GetPartsOfType<SharedStringTablePart>()
.Any()
? spreadsheetDocument.WorkbookPart
.GetPartsOfType<SharedStringTablePart>()
.First()
: spreadsheetDocument.WorkbookPart
.AddNewPart<SharedStringTablePart>();
if (shareStringPart.SharedStringTable == null)
{
shareStringPart.SharedStringTable = new SharedStringTable();
}
WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild(new Sheets());
Sheet sheet = new()
{
Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Лист"
};
sheets.Append(sheet);
worksheet = worksheetPart.Worksheet;
}
public void InsertCellInWorksheet(ExcelCellData cellData)
{
if (worksheet == null || shareStringPart == null)
{
return;
}
var sheetData = worksheet.GetFirstChild<SheetData>();
if (sheetData == null)
{
return;
}
Row? row = sheetData.Elements<Row>()
.Where(r => r.RowIndex! == cellData.RowIndex)
.FirstOrDefault();
if (row == null)
{
row = new Row() { RowIndex = cellData.RowIndex };
sheetData.Append(row);
}
Cell? cell = row.Elements<Cell>()
.Where(c => c.CellReference!.Value == cellData.CellReference)
.FirstOrDefault();
if (cell == null)
{
Cell? refCell = null;
foreach (Cell rowCell in row.Elements<Cell>())
{
if (string.Compare(rowCell.CellReference!.Value, cellData.CellReference, true) > 0)
{
refCell = rowCell;
break;
}
}
var newCell = new Cell()
{
CellReference = cellData.CellReference
};
row.InsertBefore(newCell, refCell);
cell = newCell;
}
shareStringPart.SharedStringTable.AppendChild(new SharedStringItem(new Text(cellData.Text)));
shareStringPart.SharedStringTable.Save();
cell.CellValue = new CellValue((shareStringPart.SharedStringTable.Elements<SharedStringItem>().Count() - 1).ToString());
cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
cell.StyleIndex = cellData.StyleIndex;
}
private void MergeCells(ExcelMergeParameters excelParams)
{
if (worksheet == null)
{
return;
}
MergeCells mergeCells;
if (worksheet.Elements<MergeCells>().Any())
{
mergeCells = worksheet.Elements<MergeCells>().First();
}
else
{
mergeCells = new MergeCells();
if (worksheet.Elements<CustomSheetView>().Any())
{
worksheet.InsertAfter(mergeCells, worksheet.Elements<CustomSheetView>().First());
}
else
{
worksheet.InsertAfter(mergeCells, worksheet.Elements<SheetData>().First());
}
}
var mergeCell = new MergeCell()
{
Reference = new StringValue(excelParams.Merge)
};
mergeCells.Append(mergeCell);
}
private void Save()
{
if (spreadsheetDocument == null)
{
return;
}
spreadsheetDocument.WorkbookPart!.Workbook.Save();
spreadsheetDocument.Dispose();
}
public byte[] GetFile()
{
Save();
byte[] file = File.ReadAllBytes(tempFileName);
File.Delete(tempFileName);
return file;
}
public void CreateTitle(string text)
{
MergeCells(new ExcelMergeParameters
{
CellFromName = "A1",
CellToName = "B1"
});
InsertCellInWorksheet(new ExcelCellData
{
ColumnName = "A",
RowIndex = 1,
Text = text,
StyleIndex = 0
});
}
public void CreateStudentsDisciplineTable(List<ReportStudentsDisciplineViewModel> data)
{
if (worksheet == null || shareStringPart == null)
{
return;
}
Columns columns = new();
Column columnA = new() { Min = 1, Max = 1, Width = 30, CustomWidth = true };
columns.Append(columnA);
Column columnB = new() { Min = 2, Max = 2, Width = 30, CustomWidth = true };
columns.Append(columnB);
worksheet.InsertAt(columns, 0);
InsertCellInWorksheet(new ExcelCellData
{
ColumnName = "A",
RowIndex = 2,
Text = "Студент",
StyleIndex = 2
});
InsertCellInWorksheet(new ExcelCellData
{
ColumnName = "B",
RowIndex = 2,
Text = "Дисциплина",
StyleIndex = 2
});
uint currentRow = 3;
foreach (ReportStudentsDisciplineViewModel student in data)
{
InsertCellInWorksheet(new ExcelCellData
{
ColumnName = "A",
RowIndex = currentRow,
Text = student.Student,
StyleIndex = 1
});
InsertCellInWorksheet(new ExcelCellData
{
ColumnName = "B",
RowIndex = currentRow,
Text = "",
StyleIndex = 1
});
currentRow++;
foreach (string discipline in student.Disciplines)
{
InsertCellInWorksheet(new ExcelCellData
{
ColumnName = "A",
RowIndex = currentRow,
Text = "",
StyleIndex = 1
});
InsertCellInWorksheet(new ExcelCellData
{
ColumnName = "B",
RowIndex = currentRow,
Text = discipline,
StyleIndex = 1
});
currentRow++;
}
}
}
}
}

View File

@ -0,0 +1,15 @@
namespace UniversityBusinessLogic.OfficePackage.Models
{
public class ExcelCellData
{
public string ColumnName { get; set; } = string.Empty;
public uint RowIndex { get; set; }
public string Text { get; set; } = string.Empty;
public string CellReference => $"{ColumnName}{RowIndex}";
public uint StyleIndex { get; set; } = 0;
}
}

View File

@ -0,0 +1,11 @@
namespace UniversityBusinessLogic.OfficePackage.Models
{
public class ExcelMergeParameters
{
public string CellFromName { get; set; } = string.Empty;
public string CellToName { get; set; } = string.Empty;
public string Merge => $"{CellFromName}:{CellToName}";
}
}

View File

@ -0,0 +1,13 @@
namespace UniversityBusinessLogic.OfficePackage.Models
{
public class PdfData<T>
{
public string Title { get; set; } = string.Empty;
public DateTime DateFrom { get; set; }
public DateTime DateTo { get; set; }
public List<T> Records { get; set; } = new();
}
}

View File

@ -0,0 +1,11 @@
using UniversityBusinessLogic.OfficePackage.Enums;
namespace UniversityBusinessLogic.OfficePackage.Models
{
public class PdfParagraph
{
public string Text { get; set; } = string.Empty;
public string Style { get; set; } = string.Empty;
public PdfParagraphAlignmentType ParagraphAlignment { get; set; }
}
}

View File

@ -0,0 +1,11 @@
using UniversityBusinessLogic.OfficePackage.Enums;
namespace UniversityBusinessLogic.OfficePackage.Models
{
public class PdfRowParameters
{
public List<string> Texts { get; set; } = new();
public string Style { get; set; } = string.Empty;
public PdfParagraphAlignmentType ParagraphAlignment { get; set; }
}
}

View File

@ -0,0 +1,8 @@
namespace UniversityBusinessLogic.OfficePackage.Models
{
public class WordTableData
{
public List<(string, int)> Columns { get; set; } = new();
public List<List<string>> Rows { get; set; } = new();
}
}

View File

@ -0,0 +1,182 @@
using UniversityBusinessLogic.OfficePackage.Enums;
using UniversityBusinessLogic.OfficePackage.Models;
using UniversityContracts.ViewModels;
using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Tables;
using MigraDoc.Rendering;
using PdfSharp.Pdf;
using System.Text;
namespace UniversityBusinessLogic.BusinessLogic.OfficePackage
{
public class PdfBuilderProvider
{
private readonly string tempFileName = "temp.pdf";
private Document? document;
private Section? section;
private Table? table;
private static ParagraphAlignment GetParagraphAlignment(PdfParagraphAlignmentType type)
{
return type switch
{
PdfParagraphAlignmentType.Center => ParagraphAlignment.Center,
PdfParagraphAlignmentType.Left => ParagraphAlignment.Left,
_ => ParagraphAlignment.Justify,
};
}
private void DefineStyles(Document document)
{
var style = document.Styles["Normal"];
style.Font.Name = "Times New Roman";
style.Font.Size = 14;
style = document.Styles.AddStyle("NormalTitle", "Normal");
style.Font.Bold = true;
}
public void CreateDocument()
{
document = new Document();
DefineStyles(document);
section = document.AddSection();
}
public void CreateParagraph(PdfParagraph pdfParagraph)
{
if (section == null)
{
return;
}
var paragraph = section.AddParagraph(pdfParagraph.Text);
paragraph.Format.SpaceAfter = "1cm";
paragraph.Format.Alignment = GetParagraphAlignment(pdfParagraph.ParagraphAlignment);
paragraph.Style = pdfParagraph.Style;
}
public void CreateTable(List<string> columns)
{
if (document == null)
{
return;
}
table = document.LastSection.AddTable();
foreach (var elem in columns)
{
table.AddColumn(elem);
}
}
public void CreateRow(PdfRowParameters rowParameters)
{
if (table == null)
{
return;
}
var row = table.AddRow();
for (int i = 0; i < rowParameters.Texts.Count; ++i)
{
row.Cells[i].AddParagraph(rowParameters.Texts[i]);
if (!string.IsNullOrEmpty(rowParameters.Style))
{
row.Cells[i].Style = rowParameters.Style;
}
Unit borderWidth = 0.5;
row.Cells[i].Borders.Left.Width = borderWidth;
row.Cells[i].Borders.Right.Width = borderWidth;
row.Cells[i].Borders.Top.Width = borderWidth;
row.Cells[i].Borders.Bottom.Width = borderWidth;
row.Cells[i].Format.Alignment = GetParagraphAlignment(rowParameters.ParagraphAlignment);
row.Cells[i].VerticalAlignment = VerticalAlignment.Center;
}
}
private void Save()
{
// Регистрация провайдера кодировки для кодировки 1252, без этого ошибОчка была
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var renderer = new PdfDocumentRenderer(true)
{
Document = document
};
renderer.RenderDocument();
renderer.PdfDocument.Save(tempFileName);
}
public byte[] GetFile()
{
Save();
byte[] file = File.ReadAllBytes(tempFileName);
File.Delete(tempFileName);
return file;
}
public byte[] GetEducationStatusReportFile(PdfData<ReportStreamStudentEdStatPeriodViewModel> data)
{
CreateDocument();
CreateParagraph(new PdfParagraph
{
Text = data.Title,
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
CreateParagraph(new PdfParagraph
{
Text = $"за период с {data.DateFrom.ToShortDateString()} " +
$"по {data.DateTo.ToShortDateString()}",
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
CreateTable(new List<string> { "4cm","5cm", "3cm", "3cm" });
CreateRow(new PdfRowParameters
{
Texts = new List<string> { "Поток", "Студент", "Дата зачисления", "Статус обучения" },
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
foreach (var record in data.Records)
{
List<StudentStatusViewModel> studentsAndStatus = record.StudentStatus;
int recordHeight = studentsAndStatus.Count + 1;
for (int i = 0; i < recordHeight; i++)
{
List<string> cellsData = new() { "", "", "", "" };
if (i == 0)
{
cellsData[0] = record.StreamName;
CreateRow(new PdfRowParameters
{
Texts = cellsData,
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
continue;
}
int k = i - 1;
if (k < studentsAndStatus.Count)
{
cellsData[1] = studentsAndStatus[k].StudentName;
//cellsData[2] = studentsAndStatus[k].DateOfAddmission.ToString("yyyy-MM-dd");
cellsData[3] = studentsAndStatus[k].EducationStatus;
}
CreateRow(new PdfRowParameters
{
Texts = cellsData,
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
}
}
return GetFile();
}
}
}

View File

@ -0,0 +1,171 @@
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UniversityBusinessLogic.OfficePackage.Models;
using UniversityContracts.ViewModels;
namespace UniversityBusinessLogic.OfficePackage
{
public class WordBuilderCustomer
{
private readonly string tempFileName = "temp.docx";
private WordprocessingDocument? wordDocument;
private Body? documentBody;
public void CreateDocument()
{
wordDocument = WordprocessingDocument.Create(tempFileName,
WordprocessingDocumentType.Document);
MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
mainPart.Document = new Document();
documentBody = mainPart.Document.AppendChild(new Body());
}
public void CreateParagraph(string text)
{
if (documentBody == null)
{
return;
}
Paragraph paragraph = new();
Run run = new();
run.AppendChild(new Text
{
Text = text
});
paragraph.AppendChild(run);
documentBody.AppendChild(paragraph);
}
public void CreateTitle(string text)
{
if (documentBody == null)
{
return;
}
Paragraph paragraph = new();
Run run = new();
RunProperties properties = new();
properties.AppendChild(new Bold());
run.AppendChild(properties);
run.AppendChild(new Text
{
Text = text
});
paragraph.AppendChild(run);
documentBody.AppendChild(paragraph);
}
private TableCell CreateTableCell(string text, bool inHead = false, int? cellWidth = null)
{
Run run = new();
TableCell tableCell = new();
TableCellProperties cellProperties = new()
{
TableCellWidth = new()
{
Width = cellWidth.ToString()
},
TableCellMargin = new()
{
LeftMargin = new()
{
Width = "100"
}
}
};
if (inHead)
{
Shading shading = new()
{
Color = "auto",
Fill = "e0e8ff",
Val = ShadingPatternValues.Clear
};
cellProperties.Append(shading);
RunProperties properties = new();
properties.AppendChild(new Bold());
run.AppendChild(properties);
}
run.AppendChild(new Text
{
Text = text
});
Paragraph paragraph = new(run);
tableCell.AppendChild(paragraph);
tableCell.Append(cellProperties);
return tableCell;
}
protected void CreateTable(WordTableData tableData)
{
if (documentBody == null || tableData == null)
{
return;
}
var table = new Table();
TableProperties tableProperties = new(
new TableBorders(
new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 3 },
new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 3 },
new LeftBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 3 },
new RightBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 3 },
new InsideHorizontalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 3 },
new InsideVerticalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 3 }
)
);
table.AppendChild(tableProperties);
table.Append(new TableRow(tableData.Columns.Select(x => CreateTableCell(x.Item1, true, x.Item2))));
table.Append(tableData.Rows.Select(x => new TableRow(x.Select(y => CreateTableCell(y)))));
documentBody.AppendChild(table);
}
private void Save()
{
if (documentBody == null || wordDocument == null)
{
return;
}
wordDocument.MainDocumentPart!.Document.Save();
wordDocument.Dispose();
}
public byte[] GetFile()
{
Save();
byte[] file = File.ReadAllBytes(tempFileName);
File.Delete(tempFileName);
return file;
}
public void CreateStudentsStatusTable(List<StudentViewModel> students)
{
List<List<string>> rows = new();
foreach(StudentViewModel student in students) {
List<string> studentCells = new() { student.Name + " " + student.Surname, student.EducationStatusName };
rows.Add(studentCells);
}
WordTableData wordTable = new()
{
Columns = new List<(string, int)>()
{
("Студент", 3000),
("Cтатус", 3000)
},
Rows = rows
};
CreateTable(wordTable);
}
}
}

View File

@ -0,0 +1,170 @@
using UniversityBusinessLogic.OfficePackage.Models;
using UniversityContracts.ViewModels;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
namespace UniversityBusinessLogic.BusinessLogic.OfficePackage
{
public class WordBuilderProvider
{
private readonly string tempFileName = "temp.docx";
private WordprocessingDocument? wordDocument;
private Body? documentBody;
public void CreateDocument()
{
wordDocument = WordprocessingDocument.Create(tempFileName,
WordprocessingDocumentType.Document);
MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
mainPart.Document = new Document();
documentBody = mainPart.Document.AppendChild(new Body());
}
public void CreateParagraph(string text)
{
if (documentBody == null)
{
return;
}
Paragraph paragraph = new();
Run run = new();
run.AppendChild(new Text
{
Text = text
});
paragraph.AppendChild(run);
documentBody.AppendChild(paragraph);
}
public void CreateTitle(string text)
{
if (documentBody == null)
{
return;
}
Paragraph paragraph = new();
Run run = new();
RunProperties properties = new();
properties.AppendChild(new Bold());
run.AppendChild(properties);
run.AppendChild(new Text
{
Text = text
});
paragraph.AppendChild(run);
documentBody.AppendChild(paragraph);
}
private TableCell CreateTableCell(string text, bool inHead = false, int? cellWidth = null)
{
Run run = new();
TableCell tableCell = new();
TableCellProperties cellProperties = new()
{
TableCellWidth = new()
{
Width = cellWidth.ToString()
},
TableCellMargin = new()
{
LeftMargin = new()
{
Width = "100"
}
}
};
if (inHead)
{
Shading shading = new()
{
Color = "auto",
Fill = "e0e8ff",
Val = ShadingPatternValues.Clear
};
cellProperties.Append(shading);
RunProperties properties = new();
properties.AppendChild(new Bold());
run.AppendChild(properties);
}
run.AppendChild(new Text
{
Text = text
});
Paragraph paragraph = new(run);
tableCell.AppendChild(paragraph);
tableCell.Append(cellProperties);
return tableCell;
}
protected void CreateTable(WordTableData tableData)
{
if (documentBody == null || tableData == null)
{
return;
}
var table = new Table();
TableProperties tableProperties = new(
new TableBorders(
new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 3 },
new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 3 },
new LeftBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 3 },
new RightBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 3 },
new InsideHorizontalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 3 },
new InsideVerticalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 3 }
)
);
table.AppendChild(tableProperties);
table.Append(new TableRow(tableData.Columns.Select(x => CreateTableCell(x.Item1, true, x.Item2))));
table.Append(tableData.Rows.Select(x => new TableRow(x.Select(y => CreateTableCell(y)))));
documentBody.AppendChild(table);
}
private void Save()
{
if (documentBody == null || wordDocument == null)
{
return;
}
wordDocument.MainDocumentPart!.Document.Save();
wordDocument.Dispose();
}
public byte[] GetFile()
{
Save();
byte[] file = File.ReadAllBytes(tempFileName);
File.Delete(tempFileName);
return file;
}
public void CreateStudentsDisciplineTable(List<ReportStudentsDisciplineViewModel> data)
{
List<List<string>> rows = new();
foreach (ReportStudentsDisciplineViewModel student in data)
{
List<string> studentCells = new() { student.Student, "" };
rows.Add(studentCells);
List<string> disciplineCells;
foreach (string discipline in student.Disciplines)
{
disciplineCells = new() { "", discipline };
rows.Add(disciplineCells);
}
}
WordTableData wordTable = new()
{
Columns = new List<(string, int)>()
{
("Студент", 3000),
("Дисциплина", 3000)
},
Rows = rows
};
CreateTable(wordTable);
}
}
}

View File

@ -11,9 +11,12 @@
</ItemGroup>
<ItemGroup>
<Folder Include="OfficePackage\HelperEnums\" />
<Folder Include="OfficePackage\HelperModels\" />
<Folder Include="OfficePackage\Implements\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="DocumentFormat.OpenXml" Version="2.20.0" />
<PackageReference Include="PdfSharp.MigraDoc.Standard" Version="1.51.15" />
</ItemGroup>
</Project>

View File

@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UniversityContracts.ViewModels;
using UniversityModels.Models;
namespace UniversityContracts.BindingModels
@ -13,6 +14,7 @@ namespace UniversityContracts.BindingModels
public string Name { get; set; } = string.Empty;
public DateTime Date { get; set; } = DateTime.Now;
public int UserId { get; set; }
public Dictionary<int, IStudentModel> StudentDocument { get; set; } = new();
public List<StudentViewModel> DocumentStudents { get; set; } = new();
public List<EducationGroupViewModel> DocumentGroups { get; set; } = 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

@ -8,10 +8,9 @@ namespace UniversityContracts.BindingModels
{
public class ReportBindingModel
{
public string FileName { get; set; } = string.Empty;
public string DisciplineName { get; set; } = string.Empty;
public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }
public int? UserId { get; set; }
public string UserEmail { get; set; } = string.Empty;
public DateTime DateFrom { get; set; }
public DateTime DateTo { get; set; }
public int UserId { get; set; }
}
}

View File

@ -1,15 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UniversityModels.Models;
namespace UniversityContracts.BindingModels
{
public class RoleBindingModel : IRoleModel
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
}
}

View File

@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UniversityContracts.ViewModels;
using UniversityModels.Models;
namespace UniversityContracts.BindingModels
@ -16,7 +17,7 @@ namespace UniversityContracts.BindingModels
public int UserId { get; set; }
public int Id { get; set; }
public Dictionary<int, IStudentModel> StudentStream { get; set; } = new();
public List<StudentViewModel> StudentStream { get; set; } = new();
public List<EducationGroupViewModel> GroupStream { get; set; } = new();
}
}

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UniversityContracts.ViewModels;
namespace UniversityContracts.BindingModels
{
public class StreamStudentBindingModel
{
public string FileType { get; set; } = string.Empty;
public string StreamName { get; set; }
public List<StudentViewModel> Students { get; set; } = new();
}
}

View File

@ -13,8 +13,9 @@ namespace UniversityContracts.BindingModels
public string Name { get; set; } = string.Empty;
public string Surname { get; set; } = string.Empty;
public DateTime DateOfBirth { get; set; }
public DateTime DateOfAddmission { get; set; }
public int StudentCard { get; set; }
public int EducationStatusId { get; set; }
public int? EducationStatusId { get; set; }
public int UserId { get; set; }
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UniversityContracts.ViewModels;
namespace UniversityContracts.BindingModels
{
public class StudentDisciplineListBindingModel
{
public string FileType { get; set; } = string.Empty;
public List<StudentViewModel> Students { get; set; } = new();
}
}

View File

@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UniversityModels.Enums;
using UniversityModels.Models;
namespace UniversityContracts.BindingModels
@ -11,7 +12,7 @@ namespace UniversityContracts.BindingModels
{
public int Id { get; set; }
public string Login { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty;
public int RoleId { get; set; }
}
public string Password { get; set; } = string.Empty;
public Role Role { get; set; }
}
}

View File

@ -16,5 +16,6 @@ namespace UniversityContracts.BusinessLogicContracts
bool Delete(DisciplineBindingModel model);
List<DisciplineViewModel>? ReadList(DisciplineSearchModel? model);
DisciplineViewModel? ReadElement(DisciplineSearchModel model);
int GetNumberOfPages(int userId, int pageSize = 10);
}
}

View File

@ -5,6 +5,7 @@ using System.Text;
using System.Threading.Tasks;
using UniversityContracts.BindingModels;
using UniversityContracts.SearchModels;
using UniversityContracts.StoragesContracts;
using UniversityContracts.ViewModels;
namespace UniversityContracts.BusinessLogicContracts
@ -16,5 +17,6 @@ namespace UniversityContracts.BusinessLogicContracts
bool Delete(DocumentBindingModel model);
List<DocumentViewModel>? ReadList(DocumentSearchModel? model);
DocumentViewModel? ReadElement(DocumentSearchModel model);
int GetNumberOfPages(int userId, int pageSize = 10);
}
}

View File

@ -16,5 +16,6 @@ namespace UniversityContracts.BusinessLogicContracts
bool Delete(EducationGroupBindingModel model);
List<EducationGroupViewModel>? ReadList(EducationGroupSearchModel? model);
EducationGroupViewModel? ReadElement(EducationGroupSearchModel model);
int GetNumberOfPages(int userId, int pageSize = 10);
}
}

View File

@ -16,5 +16,7 @@ namespace UniversityContracts.BusinessLogicContracts
bool Delete(EducationStatusBindingModel model);
List<EducationStatusViewModel>? ReadList(EducationStatusSearchModel? model);
EducationStatusViewModel? ReadElement(EducationStatusSearchModel model);
List<EducationStatusStudentsCountViewModel> GetEducationStatusStudents();
int GetNumberOfPages(int userId, int pageSize = 10);
}
}

View File

@ -13,10 +13,7 @@ namespace UniversityContracts.BusinessLogicContracts
List<ReportDisciplineViewModel> GetDiscipline(ReportBindingModel model);
List<ReportStreamEducationStatusViewModel> StreamEducationStatus(List<StreamViewModel> streams);
void SaveBlanksToWordFile(ReportBindingModel model);
void SaveDocumentBlankToExcelFile(ReportBindingModel model);
void SaveOrdersToPdfFile(ReportBindingModel model);
byte[] SaveListFile(StreamStudentBindingModel model);
void SendByMailStatusReport(ReportBindingModel reportModel);
}
}

View File

@ -12,12 +12,10 @@ namespace UniversityContracts.BusinessLogicContracts
{
List<ReportStudentsDisciplineViewModel> GetStudentsDiscipline(List<StudentViewModel> students);
List<ReportStreamStudentEdStatPeriodViewModel> StreamStudentEdStatPeriod(ReportBindingModel model);
List<ReportStreamStudentEdStatPeriodViewModel> GetStreamStudentEdStatPeriod(ReportBindingModel model);
void SaveBlanksToWordFile(ReportBindingModel model);
byte[] SaveListFile(StudentDisciplineListBindingModel model);
void SaveDocumentBlankToExcelFile(ReportBindingModel model);
void SaveOrdersToPdfFile(ReportBindingModel model);
void SendByMailStatusReport(ReportBindingModel reportModel);
}
}

View File

@ -1,20 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UniversityContracts.BindingModels;
using UniversityContracts.SearchModels;
using UniversityContracts.ViewModels;
namespace UniversityContracts.BusinessLogicContracts
{
public interface IRoleLogic
{
List<RoleViewModel>? ReadList(RoleSearchModel? model);
RoleViewModel? ReadElement(RoleSearchModel model);
bool Create(RoleBindingModel model);
bool Update(RoleBindingModel model);
bool Delete(RoleBindingModel model);
}
}

View File

@ -16,5 +16,6 @@ namespace UniversityContracts.BusinessLogicContracts
bool Delete(StreamBindingModel model);
List<StreamViewModel>? ReadList(StreamSearchModel? model);
StreamViewModel? ReadElement(StreamSearchModel model);
int GetNumberOfPages(int userId, int pageSize = 10);
}
}

View File

@ -16,5 +16,7 @@ namespace UniversityContracts.BusinessLogicContracts
bool Delete(StudentBindingModel model);
List<StudentViewModel>? ReadList(StudentSearchModel? model);
StudentViewModel? ReadElement(StudentSearchModel model);
int GetNumberOfPages(int userId, int pageSize = 10);
List<StudentViewModel> GetStudentsFromStream(int streamId);
}
}

View File

@ -12,7 +12,7 @@ namespace UniversityContracts.BusinessLogicContracts
public interface IUserLogic
{
bool Create(UserBindingModel model);
bool Update(UserBindingModel model);
UserViewModel Update(UserBindingModel model);
bool Delete(UserBindingModel model);
List<UserViewModel>? ReadList(UserSearchModel? model);
UserViewModel? ReadElement(UserSearchModel model);

View File

@ -1,12 +0,0 @@
{
"profiles": {
"UniversityContracts": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "https://localhost:49347;http://localhost:49350"
}
}
}

View File

@ -12,5 +12,7 @@ namespace UniversityContracts.SearchModels
public string Name { get; set; } = string.Empty;
public int? StreamId { get; set; }
public int? UserId { get; set; }
public int? PageNumber { get; set; }
public int? PageSize { get; set; }
}
}

View File

@ -13,5 +13,7 @@ namespace UniversityContracts.SearchModels
public int? UserId { get; set; }
public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }
public int? PageNumber { get; set; }
public int? PageSize { get; set; }
}
}

View File

@ -12,5 +12,7 @@ namespace UniversityContracts.SearchModels
public string? Name { get; set; }
public int? UserId { get; set; }
public int? NumberOfStudents { get; set; }
public int? PageNumber { get; set; }
public int? PageSize { get; set; }
}
}

View File

@ -11,5 +11,7 @@ namespace UniversityContracts.SearchModels
public int? Id { get; set; }
public string? Name { get; set; }
public int? UserId { get; set; }
public int? PageNumber { get; set; }
public int? PageSize { get; set; }
}
}

View File

@ -1,14 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UniversityContracts.SearchModels
{
public class RoleSearchModel
{
public string? Name { get; set; }
public int? Id { get; set; }
}
}

View File

@ -12,5 +12,9 @@ namespace UniversityContracts.SearchModels
public int? UserId { get; set; }
public string? Name { get; set; }
public int? Course { get; set; }
public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }
public int? PageNumber { get; set; }
public int? PageSize { get; set; }
}
}

View File

@ -11,8 +11,11 @@ namespace UniversityContracts.SearchModels
public int? Id { get; set; }
public int? StudentCard { get; set; }
public int? UserId { get; set; }
public int? EducationStatusId { get; set; }
public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }
public bool? Disciplines { get; set; }
}
public int? PageNumber { get; set; }
public int? PageSize { get; set; }
}
}

View File

@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UniversityModels.Enums;
namespace UniversityContracts.SearchModels
{
@ -10,7 +6,7 @@ namespace UniversityContracts.SearchModels
{
public int? Id { get; set; }
public string? Login { get; set; }
public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }
public string? Password { get; set; }
public Role? Role { get; set; }
}
}

View File

@ -17,5 +17,6 @@ namespace UniversityContracts.StoragesContracts
DisciplineViewModel? Insert(DisciplineBindingModel model);
DisciplineViewModel? Update(DisciplineBindingModel model);
DisciplineViewModel? Delete(DisciplineBindingModel model);
int GetNumberOfPages(int userId, int pageSize);
}
}

View File

@ -17,5 +17,6 @@ namespace UniversityContracts.StoragesContracts
DocumentViewModel? Insert(DocumentBindingModel model);
DocumentViewModel? Update(DocumentBindingModel model);
DocumentViewModel? Delete(DocumentBindingModel model);
int GetNumberOfPages(int userId, int pageSize);
}
}

View File

@ -17,5 +17,6 @@ namespace UniversityContracts.StoragesContracts
EducationGroupViewModel? Insert(EducationGroupBindingModel model);
EducationGroupViewModel? Update(EducationGroupBindingModel model);
EducationGroupViewModel? Delete(EducationGroupBindingModel model);
int GetNumberOfPages(int userId, int pageSize);
}
}

View File

@ -17,5 +17,7 @@ namespace UniversityContracts.StoragesContracts
EducationStatusViewModel? Insert(EducationStatusBindingModel model);
EducationStatusViewModel? Update(EducationStatusBindingModel model);
EducationStatusViewModel? Delete(EducationStatusBindingModel model);
List<EducationStatusStudentsCountViewModel>? GetEducationStatusStudents();
int GetNumberOfPages(int userId, int pageSize = 10);
}
}

View File

@ -1,21 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UniversityContracts.BindingModels;
using UniversityContracts.SearchModels;
using UniversityContracts.ViewModels;
namespace UniversityContracts.StoragesContracts
{
public interface IRoleStorage
{
List<RoleViewModel> GetFullList();
List<RoleViewModel> GetFilteredList(RoleSearchModel model);
RoleViewModel? GetElement(RoleSearchModel model);
RoleViewModel? Insert(RoleBindingModel model);
RoleViewModel? Update(RoleBindingModel model);
RoleViewModel? Delete(RoleBindingModel model);
}
}

View File

@ -17,5 +17,8 @@ namespace UniversityContracts.StoragesContracts
StreamViewModel? Insert(StreamBindingModel model);
StreamViewModel? Update(StreamBindingModel model);
StreamViewModel? Delete(StreamBindingModel model);
List<DisciplineViewModel> GetStreamDisciplines(StreamSearchModel model);
List<StudentViewModel> GetStreamStudents(StreamSearchModel model);
int GetNumberOfPages(int userId, int pageSize);
}
}

View File

@ -17,5 +17,8 @@ namespace UniversityContracts.StoragesContracts
StudentViewModel? Insert(StudentBindingModel model);
StudentViewModel? Update(StudentBindingModel model);
StudentViewModel? Delete(StudentBindingModel model);
}
List<StreamViewModel> GetStudentStreams(StudentSearchModel model);
List<StudentViewModel> GetStudentsFromStream(int streamId);
int GetNumberOfPages(int userId, int pageSize);
}
}

View File

@ -17,6 +17,7 @@ namespace UniversityContracts.ViewModels
public string Name { get; set; } = string.Empty;
[DisplayName("Дата создания документа")]
public DateTime Date { get; set; } = DateTime.Now;
public Dictionary<int, IStudentModel> StudentDocument { get; set; } = new();
public List<StudentViewModel> DocumentStudents { get; set; } = new();
public List<EducationGroupViewModel> DocumentEdGroups { get; set; } = new();
}
}

View File

@ -4,16 +4,27 @@ using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UniversityModels.Models;
namespace UniversityContracts.ViewModels
{
public class EducationGroupViewModel
public class EducationGroupViewModel : IEducationGroupModel
{
public int Id { get; set; }
[DisplayName("Название группы")]
public string Name { get; set; } = string.Empty;
[DisplayName("Количество студентов в группе")]
public int NumberOfStudents { get; set; }
public int NumberOfStudent { get; set; }
public int UserId { get; set; }
public EducationGroupViewModel() { }
public EducationGroupViewModel(IEducationGroupModel model)
{
Id = model.Id;
UserId = model.UserId;
Name = model.Name;
NumberOfStudent = model.NumberOfStudent;
}
}
}

View File

@ -4,15 +4,12 @@ using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UniversityModels.Models;
namespace UniversityContracts.ViewModels
{
public class RoleViewModel : IRoleModel
public class EducationStatusStudentsCountViewModel
{
[DisplayName("Название")]
public int Count { get; set; }
public string Name { get; set; } = string.Empty;
public int Id { get; set; }
}
}

View File

@ -10,6 +10,6 @@ namespace UniversityContracts.ViewModels
{
public int Id { get; set; }
public string StreamName { get; set; } = string.Empty;
public List<(string StudentFIO, string EdStatus)> StudentEdStatus { get; set; } = new();
public List<StudentStatusViewModel> StudentStatus { get; set; } = new();
}
}

View File

@ -8,7 +8,7 @@ namespace UniversityContracts.ViewModels
{
public class ReportStudentsDisciplineViewModel
{
public string StudentFIO { get; set; } = string.Empty;
public string Student { get; set; } = string.Empty;
public List<string> Disciplines { get; set; } = new();
}
}

View File

@ -8,7 +8,7 @@ using UniversityModels.Models;
namespace UniversityContracts.ViewModels
{
public class StreamViewModel
public class StreamViewModel : IStreamModel
{
public int Id { get; set; }
public int UserId { get; set; }
@ -16,6 +16,7 @@ namespace UniversityContracts.ViewModels
public string Name { get; set; } = string.Empty;
[DisplayName("Номер курса")]
public int Course { get; set; }
public Dictionary<int, IStudentModel> StudentStream { get; set; } = new();
public List<StudentViewModel> StudentStream { get; set; } = new();
public List<EducationGroupViewModel> StreamEdGroups { get; set; } = new();
}
}

View File

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

@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@ -18,9 +19,24 @@ namespace UniversityContracts.ViewModels
public string Surname { get; set; } = string.Empty;
[DisplayName("Дата рождения студента")]
public DateTime DateOfBirth { get; set; } = DateTime.Now;
[DisplayName("Дата поступления")]
public DateTime DateOfAddmission { get; set; } = DateTime.Now;
[DisplayName("Статус обучения")]
public string EducationStatusName { get; set; } = string.Empty;
public int StudentCard { get; set; }
public int EducationStatusId { get; set; }
public int? EducationStatusId { get; set; }
public StudentViewModel() { }
public StudentViewModel(IStudentModel model)
{
Id = model.Id;
UserId = model.UserId;
Name = model.Name;
Surname = model.Surname;
DateOfBirth = model.DateOfBirth;
StudentCard = model.StudentCard;
EducationStatusId = model.EducationStatusId;
}
}
}

View File

@ -4,13 +4,15 @@ using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UniversityModels.Enums;
namespace UniversityContracts.ViewModels
{
public class UserViewModel
{
public int Id { get; set; }
public int RoleId { get; set; }
[DisplayName("Роль")]
public Role Role { get; set; }
[DisplayName("Логин")]
public string Login { get; set; } = string.Empty;
[DisplayName("Пароль")]

View File

@ -0,0 +1,67 @@
using Newtonsoft.Json;
using System.Net.Http.Headers;
using System.Text;
using UniversityContracts.ViewModels;
namespace UniversityCustomer
{
public static class APIClient
{
private static readonly HttpClient _user = new();
public static UserViewModel? User { get; set; } = null;
public static void Connect(IConfiguration configuration)
{
_user.BaseAddress = new Uri(configuration["IPAddress"]);
_user.DefaultRequestHeaders.Accept.Clear();
_user.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public static T? GetRequest<T>(string requestUrl)
{
var response = _user.GetAsync(requestUrl);
var result = response.Result.Content.ReadAsStringAsync().Result;
if (response.Result.IsSuccessStatusCode)
{
return JsonConvert.DeserializeObject<T>(result);
}
else
{
throw new Exception(result);
}
}
public static void PostRequest<T>(string requestUrl, T model)
{
var json = JsonConvert.SerializeObject(model);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var response = _user.PostAsync(requestUrl, data);
var result = response.Result.Content.ReadAsStringAsync().Result;
if (!response.Result.IsSuccessStatusCode)
{
throw new Exception(result);
}
}
public static O? PostRequestWithResult<I, O>(string requestUrl, I model)
{
var json = JsonConvert.SerializeObject(model);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var response = _user.PostAsync(requestUrl, data);
var result = response.Result.Content.ReadAsStringAsync().Result;
if (response.Result.IsSuccessStatusCode)
{
var temp = JsonConvert.DeserializeObject<O>(result);
return temp;
}
else
{
return default;
}
}
}
}

View File

@ -0,0 +1,73 @@
using Microsoft.AspNetCore.Mvc;
using UniversityContracts.BindingModels;
using UniversityContracts.ViewModels;
namespace UniversityCustomer.Controllers
{
public class DisciplineController : Controller
{
public IActionResult Create()
{
if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
}
return View();
}
[HttpPost]
public void Create([FromBody] DisciplineBindingModel disciplineModel)
{
if (APIClient.User == null)
{
throw new Exception("403");
}
disciplineModel.UserId = APIClient.User.Id;
APIClient.PostRequest("api/discipline/create", disciplineModel);
Response.Redirect("/Home/Disciplines");
}
public IActionResult Update(int id)
{
if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
}
ViewBag.Discipline = APIClient.GetRequest<DisciplineViewModel>($"api/discipline/get?id={id}");
return View();
}
[HttpPost]
public void Update([FromBody] DisciplineBindingModel disciplineModel)
{
if (APIClient.User == null)
{
throw new Exception("403");
}
disciplineModel.UserId = APIClient.User.Id;
APIClient.PostRequest("api/discipline/update", disciplineModel);
Response.Redirect("/Home/Disciplines");
}
[HttpPost]
public void Delete(int id)
{
if (APIClient.User == null)
{
throw new Exception("403");
}
APIClient.PostRequest($"api/discipline/delete", new DisciplineBindingModel() { Id = id });
Response.Redirect("/Home/Disciplines");
}
public DisciplineViewModel? Get(int id)
{
if (APIClient.User == null)
{
return new();
}
DisciplineViewModel? document = APIClient.GetRequest<DisciplineViewModel>($"api/discipline/get?id={id}");
return document;
}
}
}

View File

@ -0,0 +1,84 @@
using Microsoft.AspNetCore.Mvc;
using UniversityContracts.BindingModels;
using UniversityContracts.ViewModels;
using UniversityModels.Models;
namespace UniversityCustomer.Controllers
{
public class EducationGroupController : Controller
{
public IActionResult Create()
{
if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
}
return View();
}
[HttpPost]
public void Create([FromBody] EducationGroupBindingModel educationGroupModel)
{
if (APIClient.User == null)
{
throw new Exception("403");
}
educationGroupModel.UserId = APIClient.User.Id;
APIClient.PostRequest("api/educationgroup/create", educationGroupModel);
Response.Redirect("/Home/EducationGroups");
}
public IActionResult Update(int id)
{
if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
}
ViewBag.EducationGroup = APIClient.GetRequest<EducationGroupViewModel>($"api/educationgroup/get?id={id}");
return View();
}
[HttpPost]
public void Update([FromBody] EducationGroupBindingModel egsModel)
{
if (APIClient.User == null)
{
throw new Exception("403");
}
egsModel.UserId = APIClient.User.Id;
APIClient.PostRequest("api/educationgroup/update", egsModel);
Response.Redirect("/Home/EducationGroups");
}
[HttpPost]
public void Delete(int id)
{
if (APIClient.User == null)
{
throw new Exception("403");
}
APIClient.PostRequest($"api/educationgroup/delete", new EducationGroupBindingModel() { Id = id });
Response.Redirect("/Home/EducationGroups");
}
public List<EducationGroupViewModel> GetAllByUser()
{
if (APIClient.User == null)
{
return new();
}
List<EducationGroupViewModel>? egs = APIClient.GetRequest<List<EducationGroupViewModel>>($"api/educationgroup/getallbyuser?userId={APIClient.User.Id}");
return egs ?? new();
}
public EducationGroupViewModel? Get(int id)
{
if (APIClient.User == null)
{
return new();
}
EducationGroupViewModel? eg = APIClient.GetRequest<EducationGroupViewModel>($"api/educationgroup/get?id={id}");
return eg;
}
}
}

View File

@ -0,0 +1,179 @@
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using UniversityContracts.BindingModels;
using UniversityContracts.ViewModels;
using UniversityCustomer;
using UniversityModels.Enums;
using UniversityCustomer.Models;
namespace UniversityProvider.Controllers
{
public class HomeController : Controller
{
public HomeController() { }
public IActionResult Index()
{
if (APIClient.User == null)
{
return Redirect("~/Home/Login");
}
return View();
}
public IActionResult Login()
{
return View();
}
[HttpPost]
public void Login(string login, string password)
{
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password))
{
throw new Exception("Введите логин и пароль");
}
APIClient.User = APIClient.GetRequest<UserViewModel>($"api/user/login?login={login}&password={password}&role={Role.Customer}");
if (APIClient.User == null)
{
throw new Exception("Неверный логин/пароль");
}
Response.Redirect("Index");
}
public IActionResult Registration()
{
return View();
}
[HttpPost]
public void Registration(string login, string password)
{
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password))
{
throw new Exception("Введите логин и пароль");
}
APIClient.PostRequest("api/user/register", new UserBindingModel
{
Login = login,
Password = password,
Role = Role.Customer
});
Response.Redirect("Login");
return;
}
public IActionResult Streams(int page)
{
if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
}
if (page == 0)
{
page = 1;
}
ViewBag.Streams = APIClient.GetRequest<List<StreamViewModel>>
($"api/stream/getmany?userId={APIClient.User.Id}&page={page}");
ViewBag.Page = page;
ViewBag.NumberOfPages = APIClient.GetRequest<int>
($"api/stream/getnumberofpages?userId={APIClient.User.Id}");
return View();
}
public List<EducationStatusViewModel> Status()
{
return APIClient.GetRequest<List<EducationStatusViewModel>>
($"api/educationstatus/getall");
}
public IActionResult EducationGroups(int page)
{
if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
}
if (page == 0)
{
page = 1;
}
ViewBag.EducationGroups = APIClient.GetRequest<List<EducationGroupViewModel>>
($"api/educationgroup/getmany?userId={APIClient.User.Id}&page={page}");
ViewBag.Page = page;
ViewBag.NumberOfPages = APIClient.GetRequest<int>
($"api/educationgroup/getnumberofpages?userId={APIClient.User.Id}");
return View();
}
public IActionResult Disciplines(int page)
{
if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
}
if (page == 0)
{
page = 1;
}
ViewBag.Disciplines = APIClient.GetRequest<List<DisciplineViewModel>>
($"api/discipline/getmany?userId={APIClient.User.Id}&page={page}");
ViewBag.Page = page;
ViewBag.NumberOfPages = APIClient.GetRequest<int>
($"api/discipline/getnumberofpages?userId={APIClient.User.Id}");
return View();
}
public IActionResult StreamStudentList()
{
return View();
}
[HttpPost]
public int[]? StreamStudentList([FromBody] StreamStudentBindingModel listModel)
{
if (APIClient.User == null)
{
return Array.Empty<int>();
}
byte[]? file = APIClient.PostRequestWithResult<StreamStudentBindingModel, byte[]>
("api/reportcustomer/streamstudentlist", listModel);
return file!.Select(b => (int)b).ToArray();
}
public IActionResult GetReport()
{
return View();
}
[HttpPost]
public List<ReportStreamStudentEdStatPeriodViewModel>? GetReport([FromBody] ReportBindingModel reportModel)
{
if (APIClient.User == null)
{
return new();
}
reportModel.UserId = APIClient.User.Id;
reportModel.UserEmail = APIClient.User.Login;
List<ReportStreamStudentEdStatPeriodViewModel>? list = APIClient.PostRequestWithResult<ReportBindingModel, List<ReportStreamStudentEdStatPeriodViewModel>>
("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()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}

View File

@ -0,0 +1,40 @@
using Microsoft.AspNetCore.Mvc;
using UniversityContracts.BindingModels;
using UniversityContracts.BusinessLogicContracts;
using UniversityContracts.ViewModels;
namespace UniversityRestAPI.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class ReportCustomerController : Controller
{
private readonly IReportCustomerLogic reportLogic;
public ReportCustomerController(IReportCustomerLogic reportLogic)
{
this.reportLogic = reportLogic;
}
[HttpPost]
public byte[] StreamStudentList(StreamStudentBindingModel listModel)
{
byte[] file = reportLogic.SaveListFile(listModel);
return file;
}
[HttpPost]
public List<ReportDisciplineViewModel> GetReportData(ReportBindingModel reportModel)
{
var list = reportLogic.GetDiscipline(reportModel);
return list;
}
[HttpPost]
public void SendByMailStatusReport(ReportBindingModel reportModel)
{
reportLogic.SendByMailStatusReport(reportModel);
}
}
}

View File

@ -0,0 +1,123 @@
using Microsoft.AspNetCore.Mvc;
using UniversityContracts.BindingModels;
using UniversityContracts.ViewModels;
namespace UniversityCustomer.Controllers
{
public class StreamController : Controller
{
public IActionResult Create()
{
if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
}
return View();
}
[HttpPost]
public void Create([FromBody] StreamBindingModel streamModel)
{
if (APIClient.User == null)
{
throw new Exception("403");
}
streamModel.UserId = APIClient.User.Id;
APIClient.PostRequest("api/stream/create", streamModel);
Response.Redirect("/Home/Streams");
}
public IActionResult Update(int id)
{
if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
}
ViewBag.Stream = APIClient.GetRequest<StreamViewModel>($"api/stream/get?id={id}");
return View();
}
[HttpPost]
public void Update([FromBody] StreamBindingModel streamModel)
{
if (APIClient.User == null)
{
throw new Exception("403");
}
streamModel.UserId = APIClient.User.Id;
APIClient.PostRequest("api/stream/update", streamModel);
Response.Redirect("/Home/Streams");
}
public IActionResult Bind(int id)
{
if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
}
ViewBag.Stream = APIClient.GetRequest<StreamViewModel>($"api/stream/get?id={id}");
return View();
}
[HttpPost]
public void Bind([FromBody] StreamBindingModel streamModel)
{
if (APIClient.User == null)
{
throw new Exception("403");
}
APIClient.PostRequest("api/stream/update", streamModel);
}
[HttpPost]
public void Delete(int id)
{
if (APIClient.User == null)
{
throw new Exception("403");
}
APIClient.PostRequest($"api/stream/delete", new StreamBindingModel() { Id = id });
Response.Redirect("/Home/Streams");
}
public List<StudentViewModel> GetAllStudents()
{
if (APIClient.User == null)
{
return new();
}
List<StudentViewModel>? students = APIClient.GetRequest<List<StudentViewModel>>($"api/student/getall");
return students ?? new();
}
public List<EducationGroupViewModel> GetGroupsByUser()
{
if (APIClient.User == null)
{
return new();
}
List<EducationGroupViewModel>? group = APIClient.GetRequest<List<EducationGroupViewModel>>($"api/educationgroup/getallbyuser?userId={APIClient.User.Id}");
return group ?? new();
}
public StreamViewModel? Get(int id)
{
if (APIClient.User == null)
{
return new();
}
StreamViewModel? document = APIClient.GetRequest<StreamViewModel>($"api/stream/get?id={id}");
return document;
}
public List<StreamViewModel>? GetAllByUser()
{
if (APIClient.User == null)
{
return new();
}
List<StreamViewModel>? streams = APIClient.GetRequest<List<StreamViewModel>>($"api/stream/getallbyuser?userId={APIClient.User.Id}");
return streams;
}
}
}

View File

@ -0,0 +1,8 @@
namespace UniversityCustomer.Models;
public class ErrorViewModel
{
public string? RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}

View File

@ -1,6 +1,32 @@
using System.IO.Pipes;
using UniversityCustomer;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
APIClient.Connect(builder.Configuration);
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();

View File

@ -3,8 +3,8 @@
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:36856",
"sslPort": 44301
"applicationUrl": "http://localhost:23549",
"sslPort": 44311
}
},
"profiles": {
@ -12,7 +12,7 @@
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7160;http://localhost:5024",
"applicationUrl": "https://localhost:7272;http://localhost:5129",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}

View File

@ -6,4 +6,19 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\UniversityContracts\UniversityContracts.csproj" />
</ItemGroup>
<ItemGroup>
<Content Update="Views\EducationGroup\Update.cshtml">
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
</ItemGroup>
</Project>

View File

@ -0,0 +1,29 @@
@{
ViewData["Title"] = "Дисциплина";
}
<h4 class="fw-bold">Добавление дисциплины</h4>
<div id="error-div-shell" class="error-div-shell mb-2">
<div>
<p id="error-p" class="error-p"></p>
</div>
</div>
<p class="mb-0">Название:</p>
<input type="text" id="name-input" name="name" class="form-control mb-3" />
<div class="row">
<div class="col-md-6">
<label for="studentsSelect">Потоки:</label>
<select id="studentsSelect">
</select>
</div>
</div>
<button id="create-button" type="button" class="button-primary text-button">
Создать
</button>
<script src="~/js/discipline/discipline-create.js" asp-append-version="true"></script>

View File

@ -0,0 +1,49 @@
@using UniversityContracts.ViewModels
@{
ViewData["Title"] = "Дисциплина";
}
@{
<h4 id="discipline-data" class="fw-bold" data-id="@ViewBag.Discipline.Id">Обновление приказа</h4>
if (ViewBag.Discipline == null)
{
<h3 class="display-4">Войдите в аккаунт</h3>
return;
}
<div id="error-div-shell" class="error-div-shell mb-2">
<div>
<p id="error-p" class="error-p"></p>
</div>
</div>
<p class="mb-0">Имя:</p>
<input value="@ViewBag.Discipline.Name" type="text" id="name-input" name="name" class="form-control mb-3" />
<p class="mb-0">Часы:</p>
<input value="@ViewBag.Discipline.Hours" type="text" id="hours-input" name="hours" class="form-control mb-3" />
<div class="row">
<div class="col-md-6">
<label for="markTypeSelect">Тип отметки:</label>
<select id="markTypeSelect">
<option value="false">Зачёт</option>
<option value="true">Экзамен</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-6">
<label for="streamsSelect">Потоки:</label>
<select id="streamsSelect">
</select>
</div>
</div>
<button id="update-button" type="button" class="button-primary text-button">
Сохранить изменения
</button>
}
<script src="~/js/discipline/disciplines-update.js" asp-append-version="true"></script>

View File

@ -0,0 +1,20 @@
@{
ViewData["Title"] = "Группа";
}
<h4 class="fw-bold">Добавление группы</h4>
<div id="error-div-shell" class="error-div-shell mb-2">
<div>
<p id="error-p" class="error-p"></p>
</div>
</div>
<p class="mb-0">Название:</p>
<input type="text" id="name-input" name="name" class="form-control mb-3" />
<button id="create-button" type="button" class="button-primary text-button">
Создать
</button>
<script src="~/js/educationgroup/educationgroup-create.js" asp-append-version="true"></script>

View File

@ -0,0 +1,41 @@
@{
ViewData["Title"] = "Группа обучения";
}
@{
<div class="text-center" id="document-data" data-id="@ViewBag.Document.Id">
<h1 class="display-4">Обновление приказа</h1>
</div>
<div id="error-div-shell" class="error-div-shell mb-2">
<div>
<p id="error-p" class="error-p text-danger"></p>
</div>
</div>
<p class="mb-0">Название:</p>
<input type="text" value="@ViewBag.Document.Name" id="name-input" name="name" class="form-control mb-3" />
<button id="create-button" type="button" class="btn btn-primary text-button">
Сохранить изменения
</button>
<div class="mt-4">
<div class="scrollable-table">
<table class="table table-bordered">
<thead class="thead-light">
<tr>
<th>Имя</th>
<th>Фамилия</th>
<th>Дата рождения</th>
<th>Номер студ. билета</th>
<th>Статус обучения</th>
</tr>
</thead>
<tbody id="scrollable-table__tbody">
</tbody>
</table>
</div>
</div>
}
<script src="~/js/document/document-update.js" asp-append-version="true"></script>

View File

@ -0,0 +1,65 @@
@using UniversityContracts.ViewModels
@{
ViewData["Title"] = "Дисциплины";
}
<div class="text-center">
<h1 class="display-4">Дисциплины</h1>
</div>
<div class="text-center">
@{
if (ViewBag.Disciplines == null)
{
<h3 class="display-4">Войдите в аккаунт</h3>
return;
}
<div>
<a class="btn btn-secondary" asp-controller="Discipline" asp-action="Create">Добавить дисциплину</a>
</div>
<div class="d-flex mb-2 gap-1">
<div class="input-group" style="width: auto;">
<input id="page-input" type="number" min="1" value="@ViewBag.Page" max="@ViewBag.NumberOfPages" class="form-control" style="max-width: 5em">
<span class="input-group-text">/ @ViewBag.NumberOfPages</span>
</div>
<a href="/Home/Disciplines?page=@ViewBag.Page" id="go-button" class="button-primary text-button">
Перейти
</a>
</div>
<table class="table">
<thead>
<tr>
<th>
Название
</th>
<th>
Изменить запись
</th>
<th>
Удалить запись
</th>
</tr>
</thead>
<tbody>
@foreach (var item in ViewBag.Disciplines)
{
<tr class="d-table-row">
<td>
@item.Name
</td>
<td>
<a id="update-button-@item.Id" class="btn btn-secondary" asp-controller="Discipline" asp-action="Update" asp-route-id="@item.Id">Изменить</a>
</td>
<td>
<a id="remove-button-@item.Id" class="btn btn-secondary remove-btn" data-id="@item.Id">Удалить</a>
</td>
</tr>
}
</tbody>
</table>
}
</div>
<script src="~/js/discipline/disciplines.js" asp-append-version="true"></script>

View File

@ -0,0 +1,65 @@
@using UniversityContracts.ViewModels
@{
ViewData["Title"] = "Группы обучения";
}
<div class="text-center">
<h1 class="display-4">Группы обучения</h1>
</div>
<div class="text-center">
@{
if (ViewBag.EducationGroups == null)
{
<h3 class="display-4">Войдите в аккаунт</h3>
return;
}
<div>
<a class="btn btn-secondary" asp-controller="EducationGroup" asp-action="Create">Добавить группу</a>
</div>
<div class="d-flex mb-2 gap-1">
<div class="input-group" style="width: auto;">
<input id="page-input" type="number" min="1" value="@ViewBag.Page" max="@ViewBag.NumberOfPages" class="form-control" style="max-width: 5em">
<span class="input-group-text">/ @ViewBag.NumberOfPages</span>
</div>
<a href="/Home/EducationGroups?page=@ViewBag.Page" id="go-button" class="button-primary text-button">
Перейти
</a>
</div>
<table class="table">
<thead>
<tr>
<th>
Название
</th>
<th>
Количество студентов
</th>
</tr>
</thead>
<tbody>
@foreach (var item in ViewBag.EducationGroups)
{
<tr class="d-table-row">
<td>
@item.Name
</td>
<td>
@item.NumberOfStudent
</td>
<td>
<a id="update-button-@item.Id" class="btn btn-secondary" asp-controller="EducationGroup" asp-action="Update" asp-route-id="@item.Id">Изменить</a>
</td>
<td>
<a id="remove-button-@item.Id" class="btn btn-secondary remove-btn" data-id="@item.Id">Удалить</a>
</td>
</tr>
}
</tbody>
</table>
}
</div>
<script src="~/js/educationgroup/educationgroups.js" asp-append-version="true"></script>

View File

@ -0,0 +1,7 @@
@{
ViewData["Title"] = "Главная страница";
}
<div class="text-center">
<h1>Добро пожаловать в курсовой проект University</h1>
</div>

View File

@ -0,0 +1,27 @@
@{
ViewData["Title"] = "Вход";
}
<div class="text-center">
<h2 class="display-4">Вход в приложение</h2>
</div>
<form method="post">
<div class="row">
<div class="col-4">Логин:</div>
<div class="col-8"><input type="text" name="login" /></div>
</div>
<div class="row">
<div class="col-4">Пароль:</div>
<div class="col-8"><input type="password" name="password" /></div>
</div>
<div class="row">
<div class="col-8">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Registration">
Нет аккаунта?
</a>
</div>
<div class="col-4">
<input type="submit" value="Войти" class="btn btn-primary" />
</div>
</div>
</form>

View File

@ -0,0 +1,27 @@
@{
ViewData["Title"] = "Регистрация";
}
<div class="text-center">
<h2 class="display-4">Регистрация</h2>
</div>
<form method="post">
<div class="row">
<div class="col-4">Логин (эл.почта):</div>
<div class="col-8"><input type="email" name="login" /></div>
</div>
<div class="row">
<div class="col-4">Пароль:</div>
<div class="col-8"><input type="password" name="password" /></div>
</div>
<div class="row">
<div class="col-8">
<a class="nav-link text-primary" asp-area="" asp-controller="Home" asp-action="Login">
Есть аккаунт?
</a>
</div>
<div class="col-4">
<input type="submit" value="Регистрация" class="btn btn-primary" />
</div>
</div>
</form>

View File

@ -0,0 +1,34 @@
@{
ViewData["Title"] = "Список студентов по потокам";
}
<div class="text-center">
<h1 class="display-4">Список студентов по потокам</h1>
</div>
<div id="error-div-shell" class="error-div-shell mb-2">
<div>
<p id="error-p" class="error-p"></p>
</div>
</div>
<div class="row justify-content-between">
<select class="form-select" id="file-type">
<option>docx</option>
<option>xlsx</option>
</select>
<div class="row">
<div class="col-md-6">
<label for="streamsSelect">Потоки:</label>
<select id="streamsSelect">
</select>
</div>
</div>
<button id="create-button" type="button" class="btn btn-primary mt-4">
Получить список по выбранным записям
</button>
</div>
<script src="~/js/report/reportlist.js" asp-append-version="true"></script>

View File

@ -0,0 +1,74 @@
@using UniversityContracts.ViewModels
@{
ViewData["Title"] = "Потоки";
}
<div class="text-center">
<h1 class="display-4">Потоки</h1>
</div>
<div class="text-center">
@{
if (ViewBag.Streams == null)
{
<h3 class="display-4">Войдите в аккаунт</h3>
return;
}
<div>
<a class="btn btn-secondary" asp-controller="Stream" asp-action="Create">Добавить поток</a>
</div>
<div class="d-flex mb-2 gap-1">
<div class="input-group" style="width: auto;">
<input id="page-input" type="number" min="1" value="@ViewBag.Page" max="@ViewBag.NumberOfPages" class="form-control" style="max-width: 5em">
<span class="input-group-text">/ @ViewBag.NumberOfPages</span>
</div>
<a href="/Home/Streams?page=@ViewBag.Page" id="go-button" class="button-primary text-button">
Перейти
</a>
</div>
<table class="table">
<thead>
<tr>
<th>
Название
</th>
<th>
Курс
</th>
<th>
Изменить запись
</th>
<th>
Удалить запись
</th>
</tr>
</thead>
<tbody>
@foreach (var item in ViewBag.Streams)
{
<tr class="d-table-row">
<td>
@item.Name
</td>
<td>
@item.Course.ToString()
</td>
<td>
<a id="update-button-@item.Id" class="btn btn-secondary" asp-controller="Stream" asp-action="Bind" asp-route-id="@item.Id">Добавить студентов</a>
</td>
<td>
<a id="update-button-@item.Id" class="btn btn-secondary" asp-controller="Stream" asp-action="Update" asp-route-id="@item.Id">Изменить</a>
</td>
<td>
<a id="remove-button-@item.Id" class="btn btn-secondary remove-btn" data-id="@item.Id">Удалить</a>
</td>
</tr>
}
</tbody>
</table>
}
</div>
<script src="~/js/stream/streams.js" asp-append-version="true"></script>

View File

@ -0,0 +1,25 @@
@model ErrorViewModel
@{
ViewData["Title"] = "Error";
}
<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>
@if (Model.ShowRequestId)
{
<p>
<strong>Request ID:</strong> <code>@Model.RequestId</code>
</p>
}
<h3>Development Mode</h3>
<p>
Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred.
</p>
<p>
<strong>The Development environment shouldn't be enabled for deployed applications.</strong>
It can result in displaying sensitive information from exceptions to end users.
For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
and restarting the app.
</p>

View File

@ -0,0 +1,52 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - UniversityCustomer</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
<link rel="stylesheet" href="~/UniversityCustomer.styles.css" asp-append-version="true" />
</head>
<body>
<header>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
<div class="container-fluid">
<a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">UniversityCustomer</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Streams">Потоки</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="EducationGroups">Группы обучения</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Disciplines">Дисциплины</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="StreamStudentList">Получить список</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="GetReport">Получить отчёт</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="container">
<main role="main" class="pb-3">
@RenderBody()
</main>
</div>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
@await RenderSectionAsync("Scripts", required: false)
</body>
</html>

View File

@ -0,0 +1,48 @@
/* Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification
for details on configuring this project to bundle and minify static web assets. */
a.navbar-brand {
white-space: normal;
text-align: center;
word-break: break-all;
}
a {
color: #0077cc;
}
.btn-primary {
color: #fff;
background-color: #1b6ec2;
border-color: #1861ac;
}
.nav-pills .nav-link.active, .nav-pills .show > .nav-link {
color: #fff;
background-color: #1b6ec2;
border-color: #1861ac;
}
.border-top {
border-top: 1px solid #e5e5e5;
}
.border-bottom {
border-bottom: 1px solid #e5e5e5;
}
.box-shadow {
box-shadow: 0 .25rem .75rem rgba(0, 0, 0, .05);
}
button.accept-policy {
font-size: 1rem;
line-height: inherit;
}
.footer {
position: absolute;
bottom: 0;
width: 100%;
white-space: nowrap;
line-height: 60px;
}

View File

@ -0,0 +1,2 @@
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>

View File

@ -0,0 +1,38 @@
@{
ViewData["Title"] = "Поток";
}
<h4 id="stream-data" class="fw-bold" data-id="@ViewBag.Stream.Id">Привязка студента к потоку</h4>
<div id="error-div-shell" class="error-div-shell">
<div>
<p id="error-p" class="error-p mb-2"></p>
</div>
</div>
<p class="mb-0">Название:</p>
<input type="text" id="name-input" value="@ViewBag.Stream.Name" readonly class="form-control mb-2" />
<p class="mb-0">Курс:</p>
<input type="number" min="1" value="@ViewBag.Stream.Course" id="number-input" readonly class="form-control mb-2" />
<button id="create-button" class="button-primary text-button">
Сохранить привязку
</button>
<p class="mb-0">Студенты:</p>
<div class="scrollable-table">
<table class="table table-bordered">
<thead class="thead-light">
<tr>
<th>Имя</th>
<th>Фамилия</th>
<th>Номер студенческого билета</th>
</tr>
</thead>
<tbody id="scrollable-table__tbody">
</tbody>
</table>
</div>
<script src="~/js/stream/stream-bind.js" asp-append-version="true"></script>

View File

@ -0,0 +1,34 @@
@{
ViewData["Title"] = "Поток";
}
<h4 class="fw-bold">Создание потока</h4>
<div id="error-div-shell" class="error-div-shell">
<div>
<p id="error-p" class="error-p mb-2"></p>
</div>
</div>
<p class="mb-0">Название:</p>
<input type="text" id="name-input" class="form-control mb-2" />
<p class="mb-0">Курс:</p>
<input type="number" min="1" id="number-input" class="form-control mb-2"/>
<button id="create-button" class="button-primary text-button">
Создать
</button>
<p class="mb-0">Группы:</p>
<div class="scrollable-table">
<table class="table table-bordered">
<thead class="thead-light">
<tr>
<th>Название</th>
</tr>
</thead>
<tbody id="scrollable-table__tbody">
</tbody>
</table>
</div>
<script src="~/js/stream/stream-create.js" asp-append-version="true"></script>

Some files were not shown because too many files have changed in this diff Show More