Compare commits

...

73 Commits
test ... main

Author SHA1 Message Date
GokaPek
55f53dfa66 Финал курсовой 3 2024-05-30 05:16:33 +04:00
GokaPek
aec627bbcd Круд дисциплин готово Егор 2024-05-30 05:03:29 +04:00
GokaPek
d75f7d7ae5 фикс 2024-05-30 04:17:00 +04:00
GokaPek
e85ff82d03 Merge branch 'main' of https://git.is.ulstu.ru/StroevVladimir/CourseWork 2024-05-30 04:16:45 +04:00
GokaPek
d3acce8dd5 Ведомости круд вроде готово 2024-05-30 04:16:38 +04:00
DyCTaTOR
a73d638b0e Готовая курсовая(почти) 2024-05-30 03:38:21 +04:00
GokaPek
ad24e2c38c Круды препода финал 2024-05-30 03:23:27 +04:00
GokaPek
acbac6aadb Егор финал оформления1 2024-05-30 02:30:33 +04:00
GokaPek
495bafb4e3 Егор финал репортов ВСЕХ 2024-05-30 02:14:15 +04:00
GokaPek
5e53d3c1d5 Пофиксил баг с дисциплинами 2024-05-30 01:50:55 +04:00
DyCTaTOR
520441bd07 Готовые репорты пдф у кладовщика 2024-05-30 01:19:26 +04:00
GokaPek
84d8c3dc4a слил 2024-05-30 00:32:45 +04:00
GokaPek
3226311dd2 Отправка на почту пдф 2024-05-30 00:31:58 +04:00
DyCTaTOR
42982bcdab Готовая курсовая worker 2024-05-30 00:22:33 +04:00
GokaPek
2c4de39d60 Merge branch 'main' of https://git.is.ulstu.ru/StroevVladimir/CourseWork 2024-05-30 00:09:14 +04:00
GokaPek
70560b602e Фильтрация по времени 2024-05-30 00:09:06 +04:00
GokaPek
3da62fe249 На грани нервного срыва 2024-05-29 23:23:53 +04:00
DyCTaTOR
d6e5e9dced Готовые Аттестации 2024-05-29 22:48:30 +04:00
DyCTaTOR
85159ea8af Промежуточное 2024-05-29 21:59:17 +04:00
DyCTaTOR
478fbf8b8a готовые пдф отчёты 2024-05-29 21:06:39 +04:00
DyCTaTOR
7927b8e1ba Не работает созданеи пдф 2024-05-29 20:33:49 +04:00
DyCTaTOR
d7ef2be740 норм слили 2024-05-29 19:29:42 +04:00
DyCTaTOR
62ab8d442b Неработающая почта, но работающее представление 2024-05-29 19:27:40 +04:00
GokaPek
c04d59cbda Отчёты эксель Егор готово 2024-05-29 18:51:07 +04:00
GokaPek
ec9b192a82 Егор репорт в ворд 2024-05-29 17:55:47 +04:00
DyCTaTOR
84f56090f2 Начало отправки репортов по почте 2024-05-29 17:43:10 +04:00
GokaPek
411f8d61fb хотфикс 2024-05-29 12:06:41 +04:00
GokaPek
d93f31f42c Репорт ворд Егор готово, но отображение на сайте не работает 2024-05-29 11:30:39 +04:00
DyCTaTOR
27d38f78fc Готовый отчёты word + excel + решенные ошибки с обновлением связи многие ко многим + исправление страницы Students. Но ошибка с Attestation.StudentName 2024-05-29 02:49:07 +04:00
GokaPek
d7422d9547 Готово получение отчёта ворд Егор в сваггере (свэг) 2024-05-28 23:13:49 +04:00
GokaPek
1295f4c633 Merge branch 'main' of https://git.is.ulstu.ru/StroevVladimir/CourseWork 2024-05-28 22:09:53 +04:00
GokaPek
0d6cafab67 Частично готово Егор Ворд 2024-05-28 22:09:51 +04:00
DyCTaTOR
097918078f Готовый первый репорт у воркера 2024-05-28 22:09:26 +04:00
DyCTaTOR
4fc502b41f Метадон тут 2024-05-28 21:49:47 +04:00
GokaPek
81de79c675 Метадон где? 2024-05-28 21:47:51 +04:00
GokaPek
6f0ef7d77c Слияние чреслами 2024-05-28 21:43:50 +04:00
GokaPek
deb726ff1b Середина разработки Егор отчёт ворд 2024-05-28 21:41:10 +04:00
DyCTaTOR
4e4d3ff5e1 Промежуточное 2024-05-28 21:40:18 +04:00
DyCTaTOR
9736b196cf Начало отчётов 2024-05-28 20:27:58 +04:00
DyCTaTOR
1e31de4842 констр 2024-05-28 20:09:03 +04:00
GokaPek
8efcfdd805 Егор начало репортов 2024-05-28 20:07:10 +04:00
DyCTaTOR
ca302e66ff Реализованные отношение многие ко многим 2024-05-28 19:50:51 +04:00
DyCTaTOR
68b0a0ac82 Промежуточное сохранение 2024-05-28 19:50:51 +04:00
GokaPek
84c7c71263 Скролл 2024-05-28 19:50:37 +04:00
GokaPek
9da8a0fd79 Многие ко многим егор 2024-05-28 19:17:05 +04:00
GokaPek
74537d905a Многие-ко-многим начало 2024-05-28 17:05:02 +04:00
DyCTaTOR
96a5f2c708 Готовые аттестации 2024-05-28 00:44:31 +04:00
GokaPek
0d7809310a Дисциплины 2024-05-27 23:53:45 +04:00
GokaPek
669f02e5aa Хотфикс2 2024-05-27 23:22:44 +04:00
GokaPek
a5fa00adea хотфикс 2024-05-27 23:18:20 +04:00
DyCTaTOR
c6ebaf2b68 исправленные учителя 2024-05-27 23:08:44 +04:00
DyCTaTOR
b4e85ced88 Готовые студенты 2024-05-27 22:35:43 +04:00
DyCTaTOR
0c5cb4e121 ы 2024-05-27 22:35:42 +04:00
GokaPek
58063233d7 О 2024-05-27 22:35:15 +04:00
GokaPek
702c845c1f Merge branch 'main' of https://git.is.ulstu.ru/StroevVladimir/CourseWork 2024-05-27 20:11:03 +04:00
GokaPek
8dbce23517 Всё сломалось, ничего не понятно. Создаются преподаватели при создании ведмости 2024-05-27 20:10:56 +04:00
DyCTaTOR
974d8946ee Начало отображение студентов 2024-05-27 17:32:21 +04:00
GokaPek
75ead823e8 Частичная готовность формы ведомостей 2024-05-27 10:21:44 +04:00
DyCTaTOR
9453fd225a Проблема с выводом планов обучения 2024-05-27 01:11:57 +04:00
DyCTaTOR
9d7db7a41b Сделана регистрация + вход + отображение личных данных для воркера 2024-05-27 00:51:07 +04:00
GokaPek
d7753b4c27 Cделал учителей 2024-05-26 23:51:13 +04:00
GokaPek
a939803e8c О 2024-05-26 22:28:34 +04:00
GokaPek
df552c39e1 Частично выполнен вход. Изменения в UserStorage 2024-05-26 16:22:04 +04:00
DyCTaTOR
16cb48a2b1 Ура, эта ху...фигня работает 2024-05-22 12:05:01 +04:00
GokaPek
d8d6cc5dd8 а 2024-05-19 21:23:30 +04:00
DyCTaTOR
2a5e8e3372 Попытка исправить другую ошибку 2024-05-18 20:48:42 +04:00
DyCTaTOR
f897516f3e Решенная проблема 2024-05-18 19:24:39 +04:00
GokaPek
e037e11a64 пошаманил с дисциплиной (немного) 2024-05-02 19:15:37 +04:00
DyCTaTOR
3535087e69 Репорты готовые 2024-05-02 17:22:43 +04:00
DyCTaTOR
f37916070e Merge branch 'test' of https://git.is.ulstu.ru/StroevVladimir/CourseWork into test 2024-05-02 15:38:09 +04:00
DyCTaTOR
17e4d7a19b Очистка решения main 2024-05-02 15:31:04 +04:00
DyCTaTOR
376402df20 очистка main 2024-05-02 15:28:53 +04:00
DyCTaTOR
cb2987f4d8 oops 2024-05-02 15:15:35 +04:00
126 changed files with 6804 additions and 1139 deletions

View File

@ -15,7 +15,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UniversityRestApi", "Univer
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UniversityClientAppStorekeeper", "UniversityClientApp\UniversityClientAppStorekeeper.csproj", "{65698622-8424-4D8E-BFC9-721BB5252F22}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UniversityClientAppStorekeeper", "UniversityClientApp\UniversityClientAppStorekeeper.csproj", "{65698622-8424-4D8E-BFC9-721BB5252F22}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UniversityClientAppWorker", "UniversityClientAppWorker\UniversityClientAppWorker.csproj", "{11E2609A-BD4A-4D03-8B71-4EC0DF1CDC88}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UniversityClientAppWorker", "UniversityClientAppWorker\UniversityClientAppWorker.csproj", "{11E2609A-BD4A-4D03-8B71-4EC0DF1CDC88}"
ProjectSection(ProjectDependencies) = postProject
{4F0BB8C6-2BA8-4212-BC86-4E66C1C03816} = {4F0BB8C6-2BA8-4212-BC86-4E66C1C03816}
EndProjectSection
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution

View File

@ -58,8 +58,6 @@ namespace UniversityBusinessLogic.BusinessLogics
{ {
CheckModel(model); CheckModel(model);
model.Score = AttestationScore.Неявка;
if (_attestationStorage.Insert(model) == null) if (_attestationStorage.Insert(model) == null)
{ {
_logger.LogWarning("Insert operation failed"); _logger.LogWarning("Insert operation failed");
@ -89,51 +87,6 @@ namespace UniversityBusinessLogic.BusinessLogics
} }
return true; return true;
} }
public bool ScoreUpdate(AttestationBindingModel model, AttestationScore newScore)
{
CheckModel(model);
if (!Enum.IsDefined(typeof(AttestationScore), newScore))
{
_logger.LogWarning("Score update to " + newScore.ToString() + " operation failed. Attestation status incorrect.");
return false;
}
if (_attestationStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
model.Score = newScore;
return true;
}
public bool SetPass(AttestationBindingModel model)
{
return ScoreUpdate(model, AttestationScore.Зачёт);
}
public bool SetNotPass(AttestationBindingModel model)
{
return ScoreUpdate(model, AttestationScore.Незачёт);
}
public bool SetTwo(AttestationBindingModel model)
{
return ScoreUpdate(model, AttestationScore.Неудовлетворительно);
}
public bool SetThree(AttestationBindingModel model)
{
return ScoreUpdate(model, AttestationScore.Удовлетворительно);
}
public bool SetFour(AttestationBindingModel model)
{
return ScoreUpdate(model, AttestationScore.Хорошо);
}
public bool SetFive(AttestationBindingModel model)
{
return ScoreUpdate(model, AttestationScore.Отлично);
}
private void CheckModel(AttestationBindingModel model, bool withParams = true) private void CheckModel(AttestationBindingModel model, bool withParams = true)
{ {

View File

@ -1,32 +1,60 @@
using AbstractLawFirmContracts.ViewModels; using UniversityBusinessLogic.OfficePackage;
using System.Reflection;
using UniversityBusinessLogics.OfficePackage;
using UniversityContracts.BindingModels; using UniversityContracts.BindingModels;
using UniversityContracts.BusinessLogicContracts; using UniversityContracts.BusinessLogicContracts;
using UniversityContracts.SearchModels; using UniversityContracts.SearchModels;
using UniversityContracts.StorageContracts; using UniversityContracts.StorageContracts;
using UniversityContracts.ViewModels;
using DocumentFormat.OpenXml.EMMA;
using UniversityBusinessLogic.OfficePackage.HelperModels;
namespace UniversityBusinessLogics.BusinessLogics; namespace UniversityBusinessLogics.BusinessLogics;
public class ReportLogic : IReportLogic public class ReportLogic : IReportLogic
{ {
public List<ReportDisciplineViewModel> GetDisciplines(ReportBindingModel model)
{
throw new NotImplementedException();
}
/*private readonly AbstractSaveToWord _saveToWord; /*private readonly AbstractSaveToWord _saveToWord;
private readonly AbstractSaveToExcel _saveToExcel; private readonly AbstractSaveToExcel _saveToExcel;
private readonly AbstractSaveToPdf _saveToPdf;*/ private readonly AbstractSaveToPdf _saveToPdf;*/
private readonly ITeacherStorage _teacherStorage; private readonly ITeacherStorage _teacherStorage;
private readonly IDisciplineStorage _disciplineStorage; private readonly IDisciplineStorage _disciplineStorage;
private readonly IStudentStorage _studentStorage; private readonly IStudentStorage _studentStorage;
private readonly IStatementStorage _statementStorage; private readonly IStatementStorage _statementStorage;
private readonly IPlanOfStudyStorage _planOfStudyStorage; private readonly IPlanOfStudyStorage _planOfStudyStorage;
public List<ReportTeacherViewModel> GetTeachers()
private readonly AbstractSaveToExcelWorker _saveToExcelWorker;
private readonly AbstractSaveToWordWorker _saveToWordWorker;
private readonly AbstractSaveToPdfWorker _saveToPdfWorker;
private readonly AbstractSaveToExcelStorekeeper _saveToExcelStorekeeper;
private readonly AbstractSaveToPdfStorekeeper _saveToPdfStorekeeper;
private readonly AbstractSaveToWordStorekeeper _saveToWordStorekeeper;
public ReportLogic (ITeacherStorage teacherStorage, IDisciplineStorage
disciplineStorage, IStudentStorage studentStorage, IStatementStorage statementStorage,
IPlanOfStudyStorage planOfStudyStorage, AbstractSaveToExcelWorker saveToExcelWorker, AbstractSaveToWordWorker saveToWordWorker
,AbstractSaveToPdfWorker saveToPdfWorker, AbstractSaveToWordStorekeeper saveToWordStorekeeper,
AbstractSaveToExcelStorekeeper saveToExcelStorekeeper, AbstractSaveToPdfStorekeeper saveToPdfStorekeeper)
{ {
var teachers = _teacherStorage.GetFullList(); _teacherStorage = teacherStorage;
_disciplineStorage = disciplineStorage;
_studentStorage = studentStorage;
_statementStorage = statementStorage;
_planOfStudyStorage = planOfStudyStorage;
_saveToExcelWorker = saveToExcelWorker;
_saveToWordWorker = saveToWordWorker;
_saveToPdfWorker = saveToPdfWorker;
_saveToWordStorekeeper = saveToWordStorekeeper;
_saveToExcelStorekeeper = saveToExcelStorekeeper;
_saveToPdfStorekeeper = saveToPdfStorekeeper;
}
public List<ReportTeacherViewModel> GetTeachers(int userId)
{
var teachers = _teacherStorage.GetFilteredList(new TeacherSearchModel
{
UserId = userId
});
// Создаем список для результатов // Создаем список для результатов
var result = new List<ReportTeacherViewModel>(); var result = new List<ReportTeacherViewModel>();
@ -40,7 +68,7 @@ private readonly AbstractSaveToPdf _saveToPdf;*/
}); });
// Получаем список студентов, связанных с дисциплинами // Получаем список студентов, связанных с дисциплинами
var students = new List<(string Student, string PhoneNumber)>(); var students = new List<string>();
foreach (var discipline in disciplines) foreach (var discipline in disciplines)
{ {
var studentDisciplines = _disciplineStorage.GetStudentsForDiscipline(new DisciplineSearchModel var studentDisciplines = _disciplineStorage.GetStudentsForDiscipline(new DisciplineSearchModel
@ -55,7 +83,7 @@ private readonly AbstractSaveToPdf _saveToPdf;*/
Id = studentDiscipline.Id, Id = studentDiscipline.Id,
}); });
foreach(var st in studentList){ foreach(var st in studentList){
students.Add((st.Name, st.PhoneNumber)); students.Add(st.Name + " " + st.PhoneNumber);
} }
} }
} }
@ -63,6 +91,7 @@ private readonly AbstractSaveToPdf _saveToPdf;*/
// Добавляем учителя и его студентов в результат // Добавляем учителя и его студентов в результат
result.Add(new ReportTeacherViewModel result.Add(new ReportTeacherViewModel
{ {
TeacherId = teacher.Id,
TeacherName = teacher.Name, TeacherName = teacher.Name,
Students = students.Distinct().ToList() // Убираем дубликаты, если они есть Students = students.Distinct().ToList() // Убираем дубликаты, если они есть
}); });
@ -73,7 +102,7 @@ private readonly AbstractSaveToPdf _saveToPdf;*/
public List<ReportDisciplineViewModel> GetDisciplines(ReportDateRangeBindingModel model) public List<ReportDisciplineViewModel> GetDisciplines(ReportDateRangeBindingModel model)
{ {
var disciplines = _disciplineStorage.GetFullList(); var disciplines = _disciplineStorage.GetFilteredList(new DisciplineSearchModel { DateFrom = model.DateFrom, DateTo = model.DateTo});
var reportDisciplineViewModels = new List<ReportDisciplineViewModel>(); var reportDisciplineViewModels = new List<ReportDisciplineViewModel>();
@ -125,18 +154,121 @@ private readonly AbstractSaveToPdf _saveToPdf;*/
return reportDisciplineViewModels; return reportDisciplineViewModels;
} }
public List<ReportPlanOfStudyViewModel> GetPlanOfStudyAndDisciplines(int userId)
{
var planOfStudies = _planOfStudyStorage.GetFullList();
var reportPlanOfStudyViewModels = new List<ReportPlanOfStudyViewModel>();
foreach (var planOfStudy in planOfStudies)
{
// Получаем список дисциплин для текущего плана обучения
var disciplines = _planOfStudyStorage.GetDisciplineFromStudentsFromPlanOfStudys(new PlanOfStudySearchModel { Id = planOfStudy.Id, UserId = userId });
// Создаем ReportPlanOfStudyViewModel и добавляем его в список
reportPlanOfStudyViewModels.Add(new ReportPlanOfStudyViewModel
{
Id = planOfStudy.Id,
PlanOfStudyName = planOfStudy.Profile,
FormOfStudy = planOfStudy.FormOfStudy,
Disciplines = disciplines.Select(d => d.Name).ToList() // Получаем только имена дисциплин
});
}
return reportPlanOfStudyViewModels;
}
public List<ReportPlanOfStudyAndStudentViewModel> GetPlanOfStudyAndStudents()
{
var planOfStudies = _planOfStudyStorage.GetFullList();
var reportPlanOfStudyAndStudentViewModels = new List<ReportPlanOfStudyAndStudentViewModel>();
foreach (var planOfStudy in planOfStudies)
{
// Получаем список студентов для текущего плана обучения
var students = _studentStorage.GetFilteredList(new StudentSearchModel { Id = planOfStudy.Id });
// Создаем списки имен студентов и дисциплин
var studentNames = students.Select(student => student.Name).ToList();
var disciplineNames = new List<string>();
foreach (var student in students)
{
// Получаем список дисциплин для текущего студента
var disciplines = _disciplineStorage.GetFilteredList(new DisciplineSearchModel { Id = student.Id });
// Добавляем имена дисциплин в общий список
disciplineNames.AddRange(disciplines.Select(discipline => discipline.Name));
}
// Создаем ReportPlanOfStudyAndStudentViewModel и добавляем его в список
reportPlanOfStudyAndStudentViewModels.Add(new ReportPlanOfStudyAndStudentViewModel
{
Id = planOfStudy.Id, // Добавляем идентификатор плана обучения
PlanOfStudyName = planOfStudy.Profile,
StudentName = studentNames,
DisciplineName = disciplineNames
});
}
return reportPlanOfStudyAndStudentViewModels;
}
public void SaveTeachersToExcel(ReportBindingModel option) public void SaveTeachersToExcel(ReportBindingModel option)
{ {
throw new NotImplementedException(); _saveToExcelStorekeeper.CreateReport(new ExcelInfoStorekeeper
{
FileName = option.FileName,
Title = "Список преподователей и студентов",
Teachers = GetTeachers(0)
});
}
public void SavePlanOfStudyToExcel(ReportBindingModel option)
{
_saveToExcelWorker.CreateReport(new ExcelInfoWorker
{
FileName = option.FileName,
Title = "Список дисциплин и планов обучения",
PlanOfStudys = GetPlanOfStudyAndDisciplines(0)
});
}
public void SavePlanOfStudyToWord(ReportBindingModel option)
{
_saveToWordWorker.CreateDoc(new WordInfoWorker
{
FileName = option.FileName,
Title = "Список дисциплин и планов обучения",
PlanOfStudys = GetPlanOfStudyAndDisciplines(0)
});
} }
public void SaveTeachersToWord(ReportBindingModel option) public void SaveTeachersToWord(ReportBindingModel option)
{ {
throw new NotImplementedException(); _saveToWordStorekeeper.CreateDoc(new WordInfoStorekeeper
{
FileName = option.FileName,
Title = "Список преподавателей и студентов",
TeacherInfo = GetTeachers(0)
});
} }
public void SendDisciplinesToEmail(ReportDateRangeBindingModel option, string email) public void SendDisciplinesToEmail(ReportDateRangeBindingModel option)
{ {
throw new NotImplementedException(); _saveToPdfStorekeeper.CreateDoc(new PdfInfoStorekeeper
{
FileName = option.FileName,
Title = "Отчёт по дисциплинам",
Disciplines = GetDisciplines(option)
});
}
public void SendPlanOfStudyToEmail(ReportBindingModel option)
{
_saveToPdfWorker.CreateDoc(new PdfInfoWorker
{
FileName = option.FileName,
Title = "Отчёт по заказам за период",
PlanOfStudyAndStudent = GetPlanOfStudyAndStudents()
});
} }
} }

View File

@ -0,0 +1,62 @@
using Microsoft.Extensions.Logging;
using UniversityContracts.BindingModels;
using UniversityContracts.BusinessLogicsContracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UniversityBusinessLogic.MailWorker
{
public abstract class AbstractMailWorker
{
protected string _mailLogin = string.Empty;
protected string _mailPassword = string.Empty;
protected string _smtpClientHost = string.Empty;
protected int _smtpClientPort;
protected string _popHost = string.Empty;
protected int _popPort;
private readonly ILogger _logger;
public AbstractMailWorker(ILogger<AbstractMailWorker> logger)
{
_logger = logger;
}
public void MailConfig(MailConfigBindingModel config)
{
_mailLogin = config.MailLogin;
_mailPassword = config.MailPassword;
_smtpClientHost = config.SmtpClientHost;
_smtpClientPort = config.SmtpClientPort;
_popHost = config.PopHost;
_popPort = config.PopPort;
_logger.LogDebug("Config: {login}, {password}, {clientHost}, {clientPOrt}, {popHost}, {popPort}", _mailLogin, _mailPassword, _smtpClientHost, _smtpClientPort, _popHost, _popPort);
}
public async void MailSendAsync(MailSendInfoBindingModel info)
{
if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword))
{
return;
}
if (string.IsNullOrEmpty(_smtpClientHost) || _smtpClientPort == 0)
{
return;
}
if (string.IsNullOrEmpty(info.MailAddress) || string.IsNullOrEmpty(info.Subject) || string.IsNullOrEmpty(info.Text))
{
return;
}
_logger.LogDebug("Send Mail: {To}, {Subject}", info.MailAddress, info.Subject);
await SendMailAsync(info);
}
protected abstract Task SendMailAsync(MailSendInfoBindingModel info);
}
}

View File

@ -0,0 +1,52 @@
using Microsoft.Extensions.Logging;
using UniversityContracts.BindingModels;
using UniversityContracts.BusinessLogicsContracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Net;
using System.Security.Authentication;
using System.Text;
using System.Threading.Tasks;
using MailKit.Net.Pop3;
using MailKit.Security;
using System.Net.Mime;
namespace UniversityBusinessLogic.MailWorker
{
public class MailKitWorker : AbstractMailWorker
{
public MailKitWorker(ILogger<MailKitWorker> logger) : base(logger) { }
protected override async Task SendMailAsync(MailSendInfoBindingModel info)
{
using var objMailMessage = new MailMessage();
using var objSmtpClient = new SmtpClient(_smtpClientHost, _smtpClientPort);
try
{
objMailMessage.From = new MailAddress(_mailLogin);
objMailMessage.To.Add(new MailAddress(info.MailAddress));
objMailMessage.Subject = info.Subject;
objMailMessage.Body = info.Text;
objMailMessage.SubjectEncoding = Encoding.UTF8;
objMailMessage.BodyEncoding = Encoding.UTF8;
Attachment attachment = new Attachment("C:\\ВременныеОтчёты\\Сведения по планам обучения.pdf", new ContentType(MediaTypeNames.Application.Pdf));
objMailMessage.Attachments.Add(attachment);
objSmtpClient.UseDefaultCredentials = false;
objSmtpClient.EnableSsl = true;
objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
objSmtpClient.Credentials = new NetworkCredential(_mailLogin, _mailPassword);
await Task.Run(() => objSmtpClient.Send(objMailMessage));
}
catch (Exception)
{
throw;
}
}
}
}

View File

@ -0,0 +1,60 @@
using UniversityBusinessLogic.OfficePackage.HelperEnums;
using UniversityBusinessLogic.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UniversityBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToExcelStorekeeper
{
public void CreateReport(ExcelInfoStorekeeper info)
{
CreateExcel(info);
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = 1,
Text = info.Title,
StyleInfo = ExcelStyleInfoType.Title
});
MergeCells(new ExcelMergeParameters
{
CellFromName = "A1",
CellToName = "C1"
});
uint rowIndex = 2;
foreach (var t in info.Teachers)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = rowIndex,
Text = t.TeacherName,
StyleInfo = ExcelStyleInfoType.Text
}); ;
rowIndex++;
foreach (var st in t.Students)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "B",
RowIndex = rowIndex,
Text = st,
StyleInfo =
ExcelStyleInfoType.TextWithBroder
});
rowIndex++;
}
rowIndex++;
}
SaveExcel(info);
}
protected abstract void CreateExcel(ExcelInfoStorekeeper info);
protected abstract void InsertCellInWorksheet(ExcelCellParameters excelParams);
protected abstract void MergeCells(ExcelMergeParameters excelParams);
protected abstract void SaveExcel(ExcelInfoStorekeeper info);
}
}

View File

@ -0,0 +1,68 @@
using UniversityBusinessLogic.OfficePackage.HelperEnums;
using UniversityBusinessLogic.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UniversityBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToExcelWorker
{
public void CreateReport(ExcelInfoWorker info)
{
CreateExcel(info);
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = 1,
Text = info.Title,
StyleInfo = ExcelStyleInfoType.Title
});
MergeCells(new ExcelMergeParameters
{
CellFromName = "A1",
CellToName = "C1"
});
uint rowIndex = 2;
foreach (var ps in info.PlanOfStudys)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = rowIndex,
Text = ps.PlanOfStudyName,
StyleInfo = ExcelStyleInfoType.Text
}); ;
rowIndex++;
foreach (var discipline in ps.Disciplines)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "B",
RowIndex = rowIndex,
Text = ps.FormOfStudy,
StyleInfo =
ExcelStyleInfoType.TextWithBroder
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "C",
RowIndex = rowIndex,
Text = discipline,
StyleInfo =
ExcelStyleInfoType.TextWithBroder
});
rowIndex++;
}
rowIndex++;
}
SaveExcel(info);
}
protected abstract void CreateExcel(ExcelInfoWorker info);
protected abstract void InsertCellInWorksheet(ExcelCellParameters excelParams);
protected abstract void MergeCells(ExcelMergeParameters excelParams);
protected abstract void SaveExcel(ExcelInfoWorker info);
}
}

View File

@ -0,0 +1,71 @@
using UniversityBusinessLogic.OfficePackage.HelperEnums;
using UniversityBusinessLogic.OfficePackage.HelperModels;
namespace UniversityBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToPdfStorekeeper
{
public void CreateDoc(PdfInfoStorekeeper info)
{
CreatePdf(info);
CreateParagraph(new PdfParagraph { Text = info.Title, Style = "NormalTitle", ParagraphAlignment = PdfParagraphAlignmentType.Center });
CreateTable(new List<string> { "6cm", "6cm", "6cm", "3cm", "4 cm" });
CreateRow(new PdfRowParameters
{
Texts = new List<string> { "Дисциплина", "План обучения", "Ведомость" },
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
foreach (var item in info.Disciplines)
{
foreach (var plOfSt in item.PlanOfStudys) {
foreach (var statement in item.Statements)
{
CreateRow(new PdfRowParameters
{
Texts = new List<string> { item.DisciplineName, plOfSt, statement},
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
}
}
}
SavePdf(info);
}
/// <summary>
/// Создание doc-файла
/// </summary>
/// <param name="info"></param>
protected abstract void CreatePdf(PdfInfoStorekeeper info);
/// <summary>
/// Создание параграфа с текстом
/// </summary>
/// <param name="title"></param>
/// <param name="style"></param>
protected abstract void CreateParagraph(PdfParagraph paragraph);
/// <summary>
/// Создание таблицы
/// </summary>
/// <param name="title"></param>
/// <param name="style"></param>
protected abstract void CreateTable(List<string> columns);
/// <summary>
/// Создание и заполнение строки
/// </summary>
/// <param name="rowParameters"></param>
protected abstract void CreateRow(PdfRowParameters rowParameters);
/// <summary>
/// Сохранение файла
/// </summary>
/// <param name="info"></param>
protected abstract void SavePdf(PdfInfoStorekeeper info);
}
}

View File

@ -0,0 +1,89 @@
using UniversityBusinessLogic.OfficePackage.HelperEnums;
using UniversityBusinessLogic.OfficePackage.HelperModels;
namespace UniversityBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToPdfWorker
{
public void CreateDoc(PdfInfoWorker info)
{
CreatePdf(info);
CreateParagraph(new PdfParagraph { Text = info.Title, Style = "NormalTitle", ParagraphAlignment = PdfParagraphAlignmentType.Center });
CreateTable(new List<string> { "4cm", "5cm", "6cm", "5cm", "5 cm" });
CreateRow(new PdfRowParameters
{
Texts = new List<string> { "Номер", "План обучения", "Студент", "Дисциплина" },
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
foreach (var item in info.PlanOfStudyAndStudent)
{
foreach (var studentName in item.StudentName)
{
var rowTexts = new List<string> { item.Id.ToString(), item.PlanOfStudyName, studentName };
if (item.DisciplineName.Any())
{
foreach (var disciplineName in item.DisciplineName)
{
rowTexts.Add(disciplineName);
CreateRow(new PdfRowParameters
{
Texts = rowTexts,
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
rowTexts.RemoveAt(rowTexts.Count - 1);
}
}
else
{
// Если нет дисциплин, добавляем пустую строку
rowTexts.Add("");
CreateRow(new PdfRowParameters
{
Texts = rowTexts,
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
}
}
}
SavePdf(info);
}
/// <summary>
/// Создание doc-файла
/// </summary>
/// <param name="info"></param>
protected abstract void CreatePdf(PdfInfoWorker info);
/// <summary>
/// Создание параграфа с текстом
/// </summary>
/// <param name="title"></param>
/// <param name="style"></param>
protected abstract void CreateParagraph(PdfParagraph paragraph);
/// <summary>
/// Создание таблицы
/// </summary>
/// <param name="title"></param>
/// <param name="style"></param>
protected abstract void CreateTable(List<string> columns);
/// <summary>
/// Создание и заполнение строки
/// </summary>
/// <param name="rowParameters"></param>
protected abstract void CreateRow(PdfRowParameters rowParameters);
/// <summary>
/// Сохранение файла
/// </summary>
/// <param name="info"></param>
protected abstract void SavePdf(PdfInfoWorker info);
}
}

View File

@ -0,0 +1,82 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UniversityBusinessLogic.OfficePackage.HelperModels;
using UniversityBusinessLogic.OfficePackage.HelperEnums;
namespace UniversityBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToWordStorekeeper
{
public void CreateDoc(WordInfoStorekeeper info)
{
CreateWord(info);
CreateParagraph(new WordParagraph
{
Texts = new List<(string, WordTextProperties)> { (info.Title, new WordTextProperties { Bold = true, Size = "24", }) },
TextProperties = new WordTextProperties
{
Size = "24",
JustificationType = WordJustificationType.Center
}
});
foreach (var discipline in info.TeacherInfo)
{
CreateParagraph(new WordParagraph
{
Texts = new List<(string, WordTextProperties)>
{
("Teacher №" + discipline.TeacherId.ToString() + " - " + discipline.TeacherName, new WordTextProperties {Size = "24", Bold=true})
},
TextProperties = new WordTextProperties
{
Size = "24",
JustificationType = WordJustificationType.Both
}
});
foreach (var student in discipline.Students)
{
if (!string.IsNullOrEmpty(student))
{
CreateParagraph(new WordParagraph
{
Texts = new List<(string, WordTextProperties)> {
(student, new WordTextProperties { Size = "24" })
},
TextProperties = new WordTextProperties
{
Size = "24",
JustificationType = WordJustificationType.Both
}
});
}
}
}
SaveWord(info);
}
/// <summary>
/// Создание doc-файла
/// </summary>
/// <param name="info"></param>
protected abstract void CreateWord(WordInfoStorekeeper info);
/// <summary>
/// Создание абзаца с текстом
/// </summary>
/// <param name="paragraph"></param>
/// <returns></returns>
protected abstract void CreateParagraph(WordParagraph paragraph);
/// <summary>
/// Сохранение файла
/// </summary>
/// <param name="info"></param>
protected abstract void SaveWord(WordInfoStorekeeper info);
}
}

View File

@ -0,0 +1,63 @@
using UniversityBusinessLogic.OfficePackage.HelperEnums;
using UniversityBusinessLogic.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DocumentFormat.OpenXml.Wordprocessing;
namespace UniversityBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToWordWorker
{
public void CreateDoc(WordInfoWorker info)
{
CreateWord(info);
CreateParagraph(new WordParagraph
{
Texts = new List<(string, WordTextProperties)> { (info.Title, new WordTextProperties
{ Bold = true, Size = "24", }) },
TextProperties = new WordTextProperties
{
Size = "24",
JustificationType = WordJustificationType.Center
}
});
foreach (var planOfStudys in info.PlanOfStudys)
{
CreateParagraph(new WordParagraph
{
Texts = new List<(string, WordTextProperties)> {
(planOfStudys.PlanOfStudyName + " :", new WordTextProperties { Size = "24", Bold = true, }),
},
TextProperties = new WordTextProperties
{
Size = "24",
JustificationType = WordJustificationType.Both
}
});
foreach(var discipline in planOfStudys.Disciplines)
{
CreateParagraph(new WordParagraph
{
Texts = new List<(string, WordTextProperties)> {
(planOfStudys.FormOfStudy + " : ", new WordTextProperties { Size = "24", }),
(discipline, new WordTextProperties { Size = "24", }),
},
TextProperties = new WordTextProperties
{
Size = "24",
JustificationType = WordJustificationType.Both
}
});
}
}
SaveWord(info);
}
protected abstract void CreateWord(WordInfoWorker info);
protected abstract void CreateParagraph(WordParagraph paragraph);
protected abstract void SaveWord(WordInfoWorker info);
}
}

View File

@ -1,4 +1,4 @@
namespace UniversityBusinessLogics.OfficePackage.HelperEnums namespace UniversityBusinessLogic.OfficePackage.HelperEnums
{ {
public enum ExcelStyleInfoType public enum ExcelStyleInfoType
{ {

View File

@ -1,9 +1,11 @@
namespace UniversityBusinessLogics.OfficePackage.HelperEnums namespace UniversityBusinessLogic.OfficePackage.HelperEnums
{ {
public enum PdfParagraphAlignmentType public enum PdfParagraphAlignmentType
{ {
Center, Center,
Left, Left,
Rigth
Right
} }
} }

View File

@ -1,4 +1,4 @@
namespace UniversityBusinessLogics.OfficePackage.HelperEnums namespace UniversityBusinessLogic.OfficePackage.HelperEnums
{ {
public enum WordJustificationType public enum WordJustificationType
{ {

View File

@ -1,6 +1,6 @@
using UniversityBusinessLogics.OfficePackage.HelperEnums; using UniversityBusinessLogic.OfficePackage.HelperEnums;
namespace UniversityBusinessLogics.OfficePackage.HelperModels namespace UniversityBusinessLogic.OfficePackage.HelperModels
{ {
public class ExcelCellParameters public class ExcelCellParameters
{ {

View File

@ -1,6 +1,8 @@
namespace UniversityBusinessLogics.OfficePackage.HelperModels using UniversityContracts.ViewModels;
namespace UniversityBusinessLogic.OfficePackage.HelperModels
{ {
public class ExcelInfo public class ExcelInfoStorekeeper
{ {
public string? FileName { get; set; } public string? FileName { get; set; }
@ -12,7 +14,7 @@
get; get;
set; set;
} = new(); } = new();
public List<ReportTeacherViewModel> Teachers { get; set; } = new();
public List<string> Headers { get; set; } = new(); public List<string> Headers { get; set; } = new();
} }
} }

View File

@ -0,0 +1,20 @@
using UniversityContracts.ViewModels;
namespace UniversityBusinessLogic.OfficePackage.HelperModels
{
public class ExcelInfoWorker
{
public string? FileName { get; set; }
public Stream? Stream { get; set; }
public string Title { get; set; } = string.Empty;
public List<object> ReportObjects
{
get;
set;
} = new();
public List<ReportPlanOfStudyViewModel> PlanOfStudys { get; set; } = new();
public List<string> Headers { get; set; } = new();
}
}

View File

@ -1,4 +1,4 @@
namespace UniversityBusinessLogics.OfficePackage.HelperModels namespace UniversityBusinessLogic.OfficePackage.HelperModels
{ {
public class ExcelMergeParameters public class ExcelMergeParameters
{ {

View File

@ -1,6 +1,8 @@
namespace UniversityBusinessLogics.OfficePackage.HelperModels using UniversityContracts.ViewModels;
namespace UniversityBusinessLogic.OfficePackage.HelperModels
{ {
public class PdfInfo public class PdfInfoStorekeeper
{ {
public string? FileName { get; set; } public string? FileName { get; set; }
public Stream? Stream { get; set; } public Stream? Stream { get; set; }
@ -9,5 +11,6 @@
public DateOnly DateFrom { get; set; } public DateOnly DateFrom { get; set; }
public DateOnly DateTo { get; set; } public DateOnly DateTo { get; set; }
public List<object> ReportObjects { get; set; } = new(); public List<object> ReportObjects { get; set; } = new();
public List<ReportDisciplineViewModel> Disciplines { get; set; } = new();
} }
} }

View File

@ -0,0 +1,11 @@
using UniversityContracts.ViewModels;
namespace UniversityBusinessLogic.OfficePackage.HelperModels
{
public class PdfInfoWorker
{
public string? FileName { get; set; }
public string Title { get; set; } = string.Empty;
public List<ReportPlanOfStudyAndStudentViewModel> PlanOfStudyAndStudent { get; set; } = new();
}
}

View File

@ -1,6 +1,6 @@
using UniversityBusinessLogics.OfficePackage.HelperEnums; using UniversityBusinessLogic.OfficePackage.HelperEnums;
namespace UniversityBusinessLogics.OfficePackage.HelperModels namespace UniversityBusinessLogic.OfficePackage.HelperModels
{ {
public class PdfParagraph public class PdfParagraph
{ {

View File

@ -1,6 +1,6 @@
using UniversityBusinessLogics.OfficePackage.HelperEnums; using UniversityBusinessLogic.OfficePackage.HelperEnums;
namespace UniversityBusinessLogics.OfficePackage.HelperModels namespace UniversityBusinessLogic.OfficePackage.HelperModels
{ {
public class PdfRowParameters public class PdfRowParameters
{ {

View File

@ -0,0 +1,13 @@
using UniversityContracts.ViewModels;
namespace UniversityBusinessLogic.OfficePackage.HelperModels
{
public class WordInfoStorekeeper
{
public string? FileName { get; set; }
public Stream? Stream { get; set; }
public string Title { get; set; } = string.Empty;
public List<object> ReportObjects { get; set; } = new();
public List<ReportTeacherViewModel> TeacherInfo{ get; set; } = new();
}
}

View File

@ -1,13 +1,15 @@
 
namespace UniversityBusinessLogics.OfficePackage.HelperModels using UniversityContracts.ViewModels;
namespace UniversityBusinessLogic.OfficePackage.HelperModels
{ {
public class WordInfo public class WordInfoWorker
{ {
public string? FileName { get; set; } public string? FileName { get; set; }
public Stream? Stream { get; set; } public Stream? Stream { get; set; }
public string Title { get; set; } = string.Empty; public string Title { get; set; } = string.Empty;
public List<object> ReportObjects { get; set; } = new(); public List<object> ReportObjects { get; set; } = new();
public List<ReportPlanOfStudyViewModel> PlanOfStudys { get; set; } = new();
} }
} }

View File

@ -1,4 +1,4 @@
namespace UniversityBusinessLogics.OfficePackage.HelperModels namespace UniversityBusinessLogic.OfficePackage.HelperModels
{ {
public class WordParagraph public class WordParagraph
{ {

View File

@ -1,6 +1,6 @@
using UniversityBusinessLogics.OfficePackage.HelperEnums; using UniversityBusinessLogic.OfficePackage.HelperEnums;
namespace UniversityBusinessLogics.OfficePackage.HelperModels namespace UniversityBusinessLogic.OfficePackage.HelperModels
{ {
public class WordTextProperties public class WordTextProperties
{ {

View File

@ -0,0 +1,356 @@
using DocumentFormat.OpenXml.Office2010.Excel;
using DocumentFormat.OpenXml.Office2013.Excel;
using DocumentFormat.OpenXml.Office2016.Excel;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml;
using UniversityBusinessLogic.OfficePackage.HelperEnums;
using UniversityBusinessLogic.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UniversityBusinessLogic.OfficePackage.Implements
{
public class SaveToExcelStorekeeper : AbstractSaveToExcelStorekeeper
{
private SpreadsheetDocument? _spreadsheetDocument;
private SharedStringTablePart? _shareStringPart;
private Worksheet? _worksheet;
/// <summary>
/// Настройка стилей для файла
/// </summary>
/// <param name="workbookpart"></param>
private static 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 });
fontUsual.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color()
{ Theme = 1U });
fontUsual.Append(new FontName() { Val = "Times New Roman" });
fontUsual.Append(new FontFamilyNumbering() { Val = 2 });
fontUsual.Append(new FontScheme() { Val = FontSchemeValues.Minor });
var fontTitle = new Font();
fontTitle.Append(new Bold());
fontTitle.Append(new FontSize() { Val = 14D });
fontTitle.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color()
{ Theme = 1U });
fontTitle.Append(new FontName() { Val = "Times New Roman" });
fontTitle.Append(new FontFamilyNumbering() { Val = 2 });
fontTitle.Append(new FontScheme() { Val = FontSchemeValues.Minor });
fonts.Append(fontUsual);
fonts.Append(fontTitle);
var fills = new Fills() { Count = 2U };
var fill1 = new Fill();
fill1.Append(new PatternFill() { PatternType = PatternValues.None });
var fill2 = new Fill();
fill2.Append(new PatternFill()
{
PatternType = PatternValues.Gray125
});
fills.Append(fill1);
fills.Append(fill2);
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);
var cellStyleFormats = new CellStyleFormats() { Count = 1U };
var cellFormatStyle = new CellFormat()
{
NumberFormatId = 0U,
FontId
= 0U,
FillId = 0U,
BorderId = 0U
};
cellStyleFormats.Append(cellFormatStyle);
var cellFormats = new CellFormats() { Count = 3U };
var cellFormatFont = new CellFormat()
{
NumberFormatId = 0U,
FontId =
0U,
FillId = 0U,
BorderId = 0U,
FormatId = 0U,
ApplyFont = true
};
var cellFormatFontAndBorder = new CellFormat()
{
NumberFormatId = 0U,
FontId = 0U,
FillId = 0U,
BorderId = 1U,
FormatId = 0U,
ApplyFont = true,
ApplyBorder = true
};
var cellFormatTitle = new CellFormat()
{
NumberFormatId = 0U,
FontId
= 1U,
FillId = 0U,
BorderId = 0U,
FormatId = 0U,
Alignment = new Alignment()
{
Vertical = VerticalAlignmentValues.Center,
WrapText = true,
Horizontal =
HorizontalAlignmentValues.Center
},
ApplyFont = true
};
cellFormats.Append(cellFormatFont);
cellFormats.Append(cellFormatFontAndBorder);
cellFormats.Append(cellFormatTitle);
var cellStyles = new CellStyles() { Count = 1U };
cellStyles.Append(new CellStyle()
{
Name = "Normal",
FormatId = 0U,
BuiltinId = 0U
});
var differentialFormats = new
DocumentFormat.OpenXml.Office2013.Excel.DifferentialFormats()
{ Count = 0U };
var tableStyles = new TableStyles()
{
Count = 0U,
DefaultTableStyle =
"TableStyleMedium2",
DefaultPivotStyle = "PivotStyleLight16"
};
var stylesheetExtensionList = new StylesheetExtensionList();
var stylesheetExtension1 = new StylesheetExtension()
{
Uri =
"{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}"
};
stylesheetExtension1.AddNamespaceDeclaration("x14",
"http://schemas.microsoft.com/office/spreadsheetml/2009/9/main");
stylesheetExtension1.Append(new SlicerStyles()
{
DefaultSlicerStyle =
"SlicerStyleLight1"
});
var stylesheetExtension2 = new StylesheetExtension()
{
Uri =
"{9260A510-F301-46a8-8635-F512D64BE5F5}"
};
stylesheetExtension2.AddNamespaceDeclaration("x15",
"http://schemas.microsoft.com/office/spreadsheetml/2010/11/main");
stylesheetExtension2.Append(new TimelineStyles()
{
DefaultTimelineStyle = "TimeSlicerStyleLight1"
});
stylesheetExtensionList.Append(stylesheetExtension1);
stylesheetExtensionList.Append(stylesheetExtension2);
sp.Stylesheet.Append(fonts);
sp.Stylesheet.Append(fills);
sp.Stylesheet.Append(borders);
sp.Stylesheet.Append(cellStyleFormats);
sp.Stylesheet.Append(cellFormats);
sp.Stylesheet.Append(cellStyles);
sp.Stylesheet.Append(differentialFormats);
sp.Stylesheet.Append(tableStyles);
sp.Stylesheet.Append(stylesheetExtensionList);
}
/// <summary>
/// Получение номера стиля из типа
/// </summary>
/// <param name="styleInfo"></param>
/// <returns></returns>
private static uint GetStyleValue(ExcelStyleInfoType styleInfo)
{
return styleInfo switch
{
ExcelStyleInfoType.Title => 2U,
ExcelStyleInfoType.TextWithBroder => 1U,
ExcelStyleInfoType.Text => 0U,
_ => 0U,
};
}
protected override void CreateExcel(ExcelInfoStorekeeper info)
{
_spreadsheetDocument = SpreadsheetDocument.Create(info.FileName,
SpreadsheetDocumentType.Workbook);
// Создаем книгу (в ней хранятся листы)
var workbookpart = _spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
CreateStyles(workbookpart);
// Получаем/создаем хранилище текстов для книги
_shareStringPart =
_spreadsheetDocument.WorkbookPart!.GetPartsOfType<SharedStringTablePart>().Any()
?
_spreadsheetDocument.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First()
:
_spreadsheetDocument.WorkbookPart.AddNewPart<SharedStringTablePart>();
// Создаем SharedStringTable, если его нет
if (_shareStringPart.SharedStringTable == null)
{
_shareStringPart.SharedStringTable = new SharedStringTable();
}
// Создаем лист в книгу
var worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
// Добавляем лист в книгу
var sheets =
_spreadsheetDocument.WorkbookPart.Workbook.AppendChild(new Sheets());
var sheet = new Sheet()
{
Id =
_spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Лист"
};
sheets.Append(sheet);
_worksheet = worksheetPart.Worksheet;
}
protected override void InsertCellInWorksheet(ExcelCellParameters
excelParams)
{
if (_worksheet == null || _shareStringPart == null)
{
return;
}
var sheetData = _worksheet.GetFirstChild<SheetData>();
if (sheetData == null)
{
return;
}
// Ищем строку, либо добавляем ее
Row row;
if (sheetData.Elements<Row>().Where(r => r.RowIndex! ==
excelParams.RowIndex).Any())
{
row = sheetData.Elements<Row>().Where(r => r.RowIndex! ==
excelParams.RowIndex).First();
}
else
{
row = new Row() { RowIndex = excelParams.RowIndex };
sheetData.Append(row);
}
// Ищем нужную ячейку
Cell cell;
if (row.Elements<Cell>().Where(c => c.CellReference!.Value ==
excelParams.CellReference).Any())
{
cell = row.Elements<Cell>().Where(c => c.CellReference!.Value ==
excelParams.CellReference).First();
}
else
{
// Все ячейки должны быть последовательно друг за другом расположены
//нужно определить, после какой вставлять
Cell? refCell = null;
foreach (Cell rowCell in row.Elements<Cell>())
{
if (string.Compare(rowCell.CellReference!.Value,
excelParams.CellReference, true) > 0)
{
refCell = rowCell;
break;
}
}
var newCell = new Cell()
{
CellReference =
excelParams.CellReference
};
row.InsertBefore(newCell, refCell);
cell = newCell;
}
// вставляем новый текст
_shareStringPart.SharedStringTable.AppendChild(new
SharedStringItem(new Text(excelParams.Text)));
_shareStringPart.SharedStringTable.Save();
cell.CellValue = new
CellValue((_shareStringPart.SharedStringTable.Elements<SharedStringItem>().Count(
) - 1).ToString());
cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
cell.StyleIndex = GetStyleValue(excelParams.StyleInfo);
}
protected override 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);
}
protected override void SaveExcel(ExcelInfoStorekeeper info)
{
if (_spreadsheetDocument == null)
{
return;
}
_spreadsheetDocument.WorkbookPart!.Workbook.Save();
_spreadsheetDocument.Dispose();
}
}
}

View File

@ -0,0 +1,356 @@
using DocumentFormat.OpenXml.Office2010.Excel;
using DocumentFormat.OpenXml.Office2013.Excel;
using DocumentFormat.OpenXml.Office2016.Excel;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml;
using UniversityBusinessLogic.OfficePackage.HelperEnums;
using UniversityBusinessLogic.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UniversityBusinessLogic.OfficePackage.Implements
{
public class SaveToExcelWorker : AbstractSaveToExcelWorker
{
private SpreadsheetDocument? _spreadsheetDocument;
private SharedStringTablePart? _shareStringPart;
private Worksheet? _worksheet;
/// <summary>
/// Настройка стилей для файла
/// </summary>
/// <param name="workbookpart"></param>
private static 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 });
fontUsual.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color()
{ Theme = 1U });
fontUsual.Append(new FontName() { Val = "Times New Roman" });
fontUsual.Append(new FontFamilyNumbering() { Val = 2 });
fontUsual.Append(new FontScheme() { Val = FontSchemeValues.Minor });
var fontTitle = new Font();
fontTitle.Append(new Bold());
fontTitle.Append(new FontSize() { Val = 14D });
fontTitle.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color()
{ Theme = 1U });
fontTitle.Append(new FontName() { Val = "Times New Roman" });
fontTitle.Append(new FontFamilyNumbering() { Val = 2 });
fontTitle.Append(new FontScheme() { Val = FontSchemeValues.Minor });
fonts.Append(fontUsual);
fonts.Append(fontTitle);
var fills = new Fills() { Count = 2U };
var fill1 = new Fill();
fill1.Append(new PatternFill() { PatternType = PatternValues.None });
var fill2 = new Fill();
fill2.Append(new PatternFill()
{
PatternType = PatternValues.Gray125
});
fills.Append(fill1);
fills.Append(fill2);
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);
var cellStyleFormats = new CellStyleFormats() { Count = 1U };
var cellFormatStyle = new CellFormat()
{
NumberFormatId = 0U,
FontId
= 0U,
FillId = 0U,
BorderId = 0U
};
cellStyleFormats.Append(cellFormatStyle);
var cellFormats = new CellFormats() { Count = 3U };
var cellFormatFont = new CellFormat()
{
NumberFormatId = 0U,
FontId =
0U,
FillId = 0U,
BorderId = 0U,
FormatId = 0U,
ApplyFont = true
};
var cellFormatFontAndBorder = new CellFormat()
{
NumberFormatId = 0U,
FontId = 0U,
FillId = 0U,
BorderId = 1U,
FormatId = 0U,
ApplyFont = true,
ApplyBorder = true
};
var cellFormatTitle = new CellFormat()
{
NumberFormatId = 0U,
FontId
= 1U,
FillId = 0U,
BorderId = 0U,
FormatId = 0U,
Alignment = new Alignment()
{
Vertical = VerticalAlignmentValues.Center,
WrapText = true,
Horizontal =
HorizontalAlignmentValues.Center
},
ApplyFont = true
};
cellFormats.Append(cellFormatFont);
cellFormats.Append(cellFormatFontAndBorder);
cellFormats.Append(cellFormatTitle);
var cellStyles = new CellStyles() { Count = 1U };
cellStyles.Append(new CellStyle()
{
Name = "Normal",
FormatId = 0U,
BuiltinId = 0U
});
var differentialFormats = new
DocumentFormat.OpenXml.Office2013.Excel.DifferentialFormats()
{ Count = 0U };
var tableStyles = new TableStyles()
{
Count = 0U,
DefaultTableStyle =
"TableStyleMedium2",
DefaultPivotStyle = "PivotStyleLight16"
};
var stylesheetExtensionList = new StylesheetExtensionList();
var stylesheetExtension1 = new StylesheetExtension()
{
Uri =
"{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}"
};
stylesheetExtension1.AddNamespaceDeclaration("x14",
"http://schemas.microsoft.com/office/spreadsheetml/2009/9/main");
stylesheetExtension1.Append(new SlicerStyles()
{
DefaultSlicerStyle =
"SlicerStyleLight1"
});
var stylesheetExtension2 = new StylesheetExtension()
{
Uri =
"{9260A510-F301-46a8-8635-F512D64BE5F5}"
};
stylesheetExtension2.AddNamespaceDeclaration("x15",
"http://schemas.microsoft.com/office/spreadsheetml/2010/11/main");
stylesheetExtension2.Append(new TimelineStyles()
{
DefaultTimelineStyle = "TimeSlicerStyleLight1"
});
stylesheetExtensionList.Append(stylesheetExtension1);
stylesheetExtensionList.Append(stylesheetExtension2);
sp.Stylesheet.Append(fonts);
sp.Stylesheet.Append(fills);
sp.Stylesheet.Append(borders);
sp.Stylesheet.Append(cellStyleFormats);
sp.Stylesheet.Append(cellFormats);
sp.Stylesheet.Append(cellStyles);
sp.Stylesheet.Append(differentialFormats);
sp.Stylesheet.Append(tableStyles);
sp.Stylesheet.Append(stylesheetExtensionList);
}
/// <summary>
/// Получение номера стиля из типа
/// </summary>
/// <param name="styleInfo"></param>
/// <returns></returns>
private static uint GetStyleValue(ExcelStyleInfoType styleInfo)
{
return styleInfo switch
{
ExcelStyleInfoType.Title => 2U,
ExcelStyleInfoType.TextWithBroder => 1U,
ExcelStyleInfoType.Text => 0U,
_ => 0U,
};
}
protected override void CreateExcel(ExcelInfoWorker info)
{
_spreadsheetDocument = SpreadsheetDocument.Create(info.FileName,
SpreadsheetDocumentType.Workbook);
// Создаем книгу (в ней хранятся листы)
var workbookpart = _spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
CreateStyles(workbookpart);
// Получаем/создаем хранилище текстов для книги
_shareStringPart =
_spreadsheetDocument.WorkbookPart!.GetPartsOfType<SharedStringTablePart>().Any()
?
_spreadsheetDocument.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First()
:
_spreadsheetDocument.WorkbookPart.AddNewPart<SharedStringTablePart>();
// Создаем SharedStringTable, если его нет
if (_shareStringPart.SharedStringTable == null)
{
_shareStringPart.SharedStringTable = new SharedStringTable();
}
// Создаем лист в книгу
var worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
// Добавляем лист в книгу
var sheets =
_spreadsheetDocument.WorkbookPart.Workbook.AppendChild(new Sheets());
var sheet = new Sheet()
{
Id =
_spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Лист"
};
sheets.Append(sheet);
_worksheet = worksheetPart.Worksheet;
}
protected override void InsertCellInWorksheet(ExcelCellParameters
excelParams)
{
if (_worksheet == null || _shareStringPart == null)
{
return;
}
var sheetData = _worksheet.GetFirstChild<SheetData>();
if (sheetData == null)
{
return;
}
// Ищем строку, либо добавляем ее
Row row;
if (sheetData.Elements<Row>().Where(r => r.RowIndex! ==
excelParams.RowIndex).Any())
{
row = sheetData.Elements<Row>().Where(r => r.RowIndex! ==
excelParams.RowIndex).First();
}
else
{
row = new Row() { RowIndex = excelParams.RowIndex };
sheetData.Append(row);
}
// Ищем нужную ячейку
Cell cell;
if (row.Elements<Cell>().Where(c => c.CellReference!.Value ==
excelParams.CellReference).Any())
{
cell = row.Elements<Cell>().Where(c => c.CellReference!.Value ==
excelParams.CellReference).First();
}
else
{
// Все ячейки должны быть последовательно друг за другом расположены
//нужно определить, после какой вставлять
Cell? refCell = null;
foreach (Cell rowCell in row.Elements<Cell>())
{
if (string.Compare(rowCell.CellReference!.Value,
excelParams.CellReference, true) > 0)
{
refCell = rowCell;
break;
}
}
var newCell = new Cell()
{
CellReference =
excelParams.CellReference
};
row.InsertBefore(newCell, refCell);
cell = newCell;
}
// вставляем новый текст
_shareStringPart.SharedStringTable.AppendChild(new
SharedStringItem(new Text(excelParams.Text)));
_shareStringPart.SharedStringTable.Save();
cell.CellValue = new
CellValue((_shareStringPart.SharedStringTable.Elements<SharedStringItem>().Count(
) - 1).ToString());
cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
cell.StyleIndex = GetStyleValue(excelParams.StyleInfo);
}
protected override 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);
}
protected override void SaveExcel(ExcelInfoWorker info)
{
if (_spreadsheetDocument == null)
{
return;
}
_spreadsheetDocument.WorkbookPart!.Workbook.Save();
_spreadsheetDocument.Dispose();
}
}
}

View File

@ -0,0 +1,115 @@
using UniversityBusinessLogic.OfficePackage.HelperEnums;
using UniversityBusinessLogic.OfficePackage.HelperModels;
using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Tables;
using MigraDoc.Rendering;
namespace UniversityBusinessLogic.OfficePackage.Implements
{
public class SaveToPdfStorekeeper : AbstractSaveToPdfStorekeeper
{
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,
PdfParagraphAlignmentType.Right => ParagraphAlignment.Right,
_ => ParagraphAlignment.Justify,
};
}
/// <summary>
/// Создание стилей для документа
/// </summary>
/// <param name="document"></param>
private static 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;
}
protected override void CreatePdf(PdfInfoStorekeeper info)
{
_document = new Document();
DefineStyles(_document);
_document.DefaultPageSetup.Orientation = Orientation.Landscape;
_section = _document.AddSection();
}
protected override 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;
}
protected override void CreateTable(List<string> columns)
{
if (_document == null)
{
return;
}
_table = _document.LastSection.AddTable();
foreach (var elem in columns)
{
_table.AddColumn(elem);
}
}
protected override 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;
}
}
protected override void SavePdf(PdfInfoStorekeeper info)
{
var renderer = new PdfDocumentRenderer(true)
{
Document = _document
};
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
renderer.RenderDocument();
renderer.PdfDocument.Save(info.FileName);
}
}
}

View File

@ -0,0 +1,125 @@
using UniversityBusinessLogic.OfficePackage.HelperEnums;
using UniversityBusinessLogic.OfficePackage.HelperModels;
using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Tables;
using MigraDoc.Rendering;
namespace UniversityBusinessLogic.OfficePackage.Implements
{
public class SaveToPdfWorker : AbstractSaveToPdfWorker
{
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,
PdfParagraphAlignmentType.Right => ParagraphAlignment.Right,
_ => ParagraphAlignment.Justify,
};
}
/// <summary>
/// Создание стилей для документа
/// </summary>
/// <param name="document"></param>
private static 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;
}
protected override void CreatePdf(PdfInfoWorker info)
{
_document = new Document();
DefineStyles(_document);
_document.DefaultPageSetup.Orientation = Orientation.Landscape;
_section = _document.AddSection();
}
protected override 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;
}
protected override void CreateTable(List<string> columns)
{
if (_document == null)
{
return;
}
_table = _document.LastSection.AddTable();
foreach (var elem in columns)
{
_table.AddColumn(elem);
}
}
protected override 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;
}
}
protected override void SavePdf(PdfInfoWorker info)
{
if (_document == null)
{
throw new InvalidOperationException("Document is not initialized.");
}
var renderer = new PdfDocumentRenderer(true)
{
Document = _document
};
try
{
renderer.RenderDocument();
renderer.PdfDocument.Save(info.FileName);
}
catch (NullReferenceException ex)
{
throw new Exception(ex.Message);
}
}
}
}

View File

@ -0,0 +1,136 @@
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using UniversityBusinessLogic.OfficePackage.HelperModels;
using UniversityBusinessLogic.OfficePackage;
using UniversityBusinessLogic.OfficePackage.HelperEnums;
namespace UniversityBusinessLogic.OfficePackage.Implements
{
public class SaveToWordStorekeeper : AbstractSaveToWordStorekeeper
{
private WordprocessingDocument? _wordDocument;
private Body? _docBody;
/// <summary>
/// Получение типа выравнивания
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
private static JustificationValues GetJustificationValues(WordJustificationType type)
{
return type switch
{
WordJustificationType.Both => JustificationValues.Both,
WordJustificationType.Center => JustificationValues.Center,
_ => JustificationValues.Left,
};
}
/// <summary>
/// Настройки страницы
/// </summary>
/// <returns></returns>
private static SectionProperties CreateSectionProperties()
{
var properties = new SectionProperties();
var pageSize = new PageSize
{
Orient = PageOrientationValues.Portrait
};
properties.AppendChild(pageSize);
return properties;
}
/// <summary>
/// Задание форматирования для абзаца
/// </summary>
/// <param name="paragraphProperties"></param>
/// <returns></returns>
private static ParagraphProperties? CreateParagraphProperties(WordTextProperties? paragraphProperties)
{
if (paragraphProperties == null)
{
return null;
}
var properties = new ParagraphProperties();
properties.AppendChild(new Justification()
{
Val = GetJustificationValues(paragraphProperties.JustificationType)
});
properties.AppendChild(new SpacingBetweenLines
{
LineRule = LineSpacingRuleValues.Auto
});
properties.AppendChild(new Indentation());
var paragraphMarkRunProperties = new ParagraphMarkRunProperties();
if (!string.IsNullOrEmpty(paragraphProperties.Size))
{
paragraphMarkRunProperties.AppendChild(new FontSize { Val = paragraphProperties.Size });
}
properties.AppendChild(paragraphMarkRunProperties);
return properties;
}
protected override void CreateWord(WordInfoStorekeeper info)
{
_wordDocument = WordprocessingDocument.Create(info.FileName, WordprocessingDocumentType.Document);
MainDocumentPart mainPart = _wordDocument.AddMainDocumentPart();
mainPart.Document = new Document();
_docBody = mainPart.Document.AppendChild(new Body());
}
protected override void CreateParagraph(WordParagraph paragraph)
{
if (_docBody == null || paragraph == null)
{
return;
}
var docParagraph = new Paragraph();
docParagraph.AppendChild(CreateParagraphProperties(paragraph.TextProperties));
foreach (var run in paragraph.Texts)
{
var docRun = new Run();
var properties = new RunProperties();
properties.AppendChild(new FontSize { Val = run.Item2.Size });
if (run.Item2.Bold)
{
properties.AppendChild(new Bold());
}
docRun.AppendChild(properties);
docRun.AppendChild(new Text { Text = run.Item1, Space = SpaceProcessingModeValues.Preserve });
docParagraph.AppendChild(docRun);
}
_docBody.AppendChild(docParagraph);
}
protected override void SaveWord(WordInfoStorekeeper info)
{
if (_docBody == null || _wordDocument == null)
{
return;
}
_docBody.AppendChild(CreateSectionProperties());
_wordDocument.MainDocumentPart!.Document.Save();
_wordDocument.Dispose();
}
}
}

View File

@ -0,0 +1,136 @@
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using UniversityBusinessLogic.OfficePackage.HelperEnums;
using UniversityBusinessLogic.OfficePackage.HelperModels;
using UniversityBusinessLogic.OfficePackage;
namespace UniversityBusinessLogic.OfficePackage.Implements
{
public class SaveToWordWorker : AbstractSaveToWordWorker
{
private WordprocessingDocument? _wordDocument;
private Body? _docBody;
/// <summary>
/// Получение типа выравнивания
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
private static JustificationValues GetJustificationValues(WordJustificationType type)
{
return type switch
{
WordJustificationType.Both => JustificationValues.Both,
WordJustificationType.Center => JustificationValues.Center,
_ => JustificationValues.Left,
};
}
/// <summary>
/// Настройки страницы
/// </summary>
/// <returns></returns>
private static SectionProperties CreateSectionProperties()
{
var properties = new SectionProperties();
var pageSize = new PageSize
{
Orient = PageOrientationValues.Portrait
};
properties.AppendChild(pageSize);
return properties;
}
/// <summary>
/// Задание форматирования для абзаца
/// </summary>
/// <param name="paragraphProperties"></param>
/// <returns></returns>
private static ParagraphProperties? CreateParagraphProperties(WordTextProperties? paragraphProperties)
{
if (paragraphProperties == null)
{
return null;
}
var properties = new ParagraphProperties();
properties.AppendChild(new Justification()
{
Val = GetJustificationValues(paragraphProperties.JustificationType)
});
properties.AppendChild(new SpacingBetweenLines
{
LineRule = LineSpacingRuleValues.Auto
});
properties.AppendChild(new Indentation());
var paragraphMarkRunProperties = new ParagraphMarkRunProperties();
if (!string.IsNullOrEmpty(paragraphProperties.Size))
{
paragraphMarkRunProperties.AppendChild(new FontSize { Val = paragraphProperties.Size });
}
properties.AppendChild(paragraphMarkRunProperties);
return properties;
}
protected override void CreateWord(WordInfoWorker info)
{
_wordDocument = WordprocessingDocument.Create(info.FileName, WordprocessingDocumentType.Document);
MainDocumentPart mainPart = _wordDocument.AddMainDocumentPart();
mainPart.Document = new Document();
_docBody = mainPart.Document.AppendChild(new Body());
}
protected override void CreateParagraph(WordParagraph paragraph)
{
if (_docBody == null || paragraph == null)
{
return;
}
var docParagraph = new Paragraph();
docParagraph.AppendChild(CreateParagraphProperties(paragraph.TextProperties));
foreach (var run in paragraph.Texts)
{
var docRun = new Run();
var properties = new RunProperties();
properties.AppendChild(new FontSize { Val = run.Item2.Size });
if (run.Item2.Bold)
{
properties.AppendChild(new Bold());
}
docRun.AppendChild(properties);
docRun.AppendChild(new Text { Text = run.Item1, Space = SpaceProcessingModeValues.Preserve });
docParagraph.AppendChild(docRun);
}
_docBody.AppendChild(docParagraph);
}
protected override void SaveWord(WordInfoWorker info)
{
if (_docBody == null || _wordDocument == null)
{
return;
}
_docBody.AppendChild(CreateSectionProperties());
_wordDocument.MainDocumentPart!.Document.Save();
_wordDocument.Dispose();
}
}
}

View File

@ -7,7 +7,10 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="DocumentFormat.OpenXml" Version="3.0.2" />
<PackageReference Include="MailKit" Version="4.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" /> <PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="PdfSharp.MigraDoc.Standard" Version="1.51.15" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@ -0,0 +1,124 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using System.Text;
using UniversityContracts.ViewModels;
using Azure.Core;
using UniversityDataModels.Models;
using UniversityDatabaseImplement.Models;
namespace UniversityClientAppStorekeeper
{
[Route("api/[controller]")]
[ApiController]
public class APIStorekeeper : ControllerBase
{
private static readonly HttpClient _client = new();
public static UserViewModel? Client { get; set; } = null;
public static void Connect(IConfiguration configuration)
{
_client.BaseAddress = new Uri(configuration["IPAddress"]);
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue("application/json"));
}
public static T? GetRequest<T>(string requestUrl)
{
var response = _client.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 = _client.PostAsync(requestUrl, data);
var result = response.Result.Content.ReadAsStringAsync().Result;
if (!response.Result.IsSuccessStatusCode)
{
throw new Exception(result);
}
}
public static async Task<T?> GetRequestDisciplineAsync<T>(string requestUrl)
{
var response = await _client.GetAsync(requestUrl);
var result = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
var settings = new JsonSerializerSettings
{
Converters = new List<JsonConverter> { new StudentConverter()}
};
return JsonConvert.DeserializeObject<T>(result, settings);
}
else
{
throw new Exception(result);
}
}
}
public class StudentConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(IStudentModel);
//return true;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
if (existingValue is Student student)
return student;
var student1 = new Student();
serializer.Populate(reader, student1);
return student1;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value == null)
{
writer.WriteNull();
return;
}
var student = (Student)value;
serializer.Serialize(writer, student);
}
}
public class DisciplineConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(IDisciplineModel);
//return true;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return serializer.Deserialize<Discipline>(reader);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, value);
}
}
}

View File

@ -1,6 +1,14 @@
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using System.Diagnostics; using System.Diagnostics;
using System.Reflection.Metadata;
using UniversityClientApp.Models; using UniversityClientApp.Models;
using UniversityClientAppStorekeeper;
using UniversityContracts.BindingModels;
using UniversityContracts.ViewModels;
using UniversityDatabaseImplement.Models;
using UniversityDatabaseImplement;
using UniversityDataModels.Enums;
using UniversityDataModels.Models;
namespace UniversityClientApp.Controllers namespace UniversityClientApp.Controllers
{ {
@ -15,6 +23,10 @@ namespace UniversityClientApp.Controllers
public IActionResult Index() public IActionResult Index()
{ {
if (APIStorekeeper.Client == null)
{
return Redirect("~/Home/Enter");
}
return View(); return View();
} }
@ -23,34 +35,400 @@ namespace UniversityClientApp.Controllers
return View(); return View();
} }
[HttpGet]
public IActionResult Enter() public IActionResult Enter()
{ {
return View(); return View();
} }
[HttpPost]
public IActionResult Disciplines() public void Enter(string login, string password)
{ {
return View(); if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password))
}
public IActionResult Statements()
{ {
return View(); throw new Exception("Ââåäèòå ëîãèí è ïàðîëü");
} }
APIStorekeeper.Client = APIStorekeeper.GetRequest<UserViewModel>($"api/user/loginstorekeeper?login={login}&password={password}");
public IActionResult Teachers() if (APIStorekeeper.Client == null)
{ {
return View(); throw new Exception("Íåâåðíûé ëîãèí/ïàðîëü");
} }
Response.Redirect("Index");
public IActionResult Report() {
return View();
} }
[HttpGet]
public IActionResult Register() public IActionResult Register()
{ {
return View(); return View();
} }
[HttpPost]
public void Register(string login, string password, string email)
{
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(email))
{
throw new Exception("Ââåäèòå ëîãèí, ïàðîëü è ÔÈÎ");
}
APIStorekeeper.PostRequest("api/user/registerstorekeeper", new UserBindingModel
{
Login = login,
Email = email,
Password = password,
Role = UserRole.Êëàäîâùèê
});
Response.Redirect("Enter");
return;
}
[HttpGet]
public async Task<IActionResult> Disciplines()
{
if (APIStorekeeper.Client == null)
{
return Redirect("~/Home/Enter");
}
ViewBag.Teachers = APIStorekeeper.GetRequest<List<TeacherViewModel>>($"api/teacher/getteachers?userId={APIStorekeeper.Client.Id}");
ViewBag.Students = APIStorekeeper.GetRequest<List<StudentViewModel>>($"api/student/getstudents?userId={APIStorekeeper.Client.Id}");
// Îæèäàåì çàâåðøåíèÿ àñèíõðîííîé îïåðàöèè
var disciplines = await APIStorekeeper.GetRequestDisciplineAsync<List<DisciplineViewModel>>($"api/discipline/getdisciplines");
// Òåïåðü ìû ìîæåì ïåðåäàòü ðåçóëüòàò â ïðåäñòàâëåíèå
return View(disciplines);
}
[HttpPost]
public void Disciplines(string name, string description, DateOnly date, int teacher, List<int> studentIds)
{
if (APIStorekeeper.Client == null)
{
Redirect("~/Home/Enter");
}
var disciplineModel = new DisciplineBindingModel
{
UserId = APIStorekeeper.Client.Id,
Name = name,
Description = description,
Date = date,
TeacherId = teacher,
StudentDisciplines = studentIds.ToDictionary(id => id, id => (IStudentModel)null)
};
APIStorekeeper.PostRequest("api/discipline/creatediscipline", disciplineModel);
Response.Redirect("Disciplines");
}
[HttpGet]
public IActionResult Statements()
{
if (APIStorekeeper.Client == null)
{
return Redirect("~/Home/Enter");
}
ViewBag.Teachers = APIStorekeeper.GetRequest<List<TeacherViewModel>>($"api/teacher/getteachers?userId={APIStorekeeper.Client.Id}");
return View(APIStorekeeper.GetRequest<List<StatementViewModel>>($"api/statement/getstatements?teacherId={0}"));
}
[HttpPost]
public void Statements(string name, DateTime date, int teacher)
{
if (APIStorekeeper.Client == null)
{
Redirect("~/Home/Enter");
}
APIStorekeeper.PostRequest("api/statement/createstatement", new StatementBindingModel
{
UserId = APIStorekeeper.Client.Id,
Name = name,
Date = date,
TeacherId = teacher,
});
Response.Redirect("Statements");
}
[HttpGet]
public IActionResult Teachers()
{
if (APIStorekeeper.Client == null)
{
return Redirect("~/Home/Enter");
}
return View(APIStorekeeper.GetRequest<List<TeacherViewModel>>($"api/teacher/getteachers?userId={APIStorekeeper.Client.Id}"));
}
[HttpPost]
public void Teachers(string name, string position, string academicDegree)
{
if (APIStorekeeper.Client == null)
{
Redirect("~/Home/Enter");
}
APIStorekeeper.PostRequest("api/teacher/createteacher", new TeacherBindingModel
{
UserId = APIStorekeeper.Client.Id,
Name = name,
Position = position,
AcademicDegree = academicDegree
});
Response.Redirect("Teachers");
}
[HttpGet]
public IActionResult Report() {
if (APIStorekeeper.Client == null)
{
return Redirect("~/Home/Enter");
}
return View("Report", APIStorekeeper.GetRequest<List<ReportTeacherViewModel>>($"api/teacher/getteachersreport?userId={APIStorekeeper.Client.Id}"));
}
[HttpPost]
public IActionResult Report(string type)
{
if (APIStorekeeper.Client == null)
{
Redirect("~/Home/Enter");
}
if (string.IsNullOrEmpty(type))
{
throw new Exception("Error, wrong type");
}
if (type == "docx")
{
APIStorekeeper.PostRequest("api/teacher/loadreporttoword", new ReportBindingModel
{
FileName = $"C:\\ÂðåìåííûåÎò÷¸òû\\TeachersAndStudents.docx"
});
return GetWordFile();
}
if (type == "xlsx")
{
APIStorekeeper.PostRequest("api/teacher/loadreporttoexcel", new ReportBindingModel
{
FileName = $"C:\\ÂðåìåííûåÎò÷¸òû\\TeachersAndStudents.xlsx"
});
return GetExcelFile();
}
return Redirect("Report");
}
[HttpPost]
public void ReportDisciplines(string type, DateOnly dateFrom, DateOnly dateTo)
{
if (APIStorekeeper.Client == null)
{
Redirect("~/Home/Enter");
throw new Exception("Âõîä òîëüêî àâòîðèçîâàííûì");
}
if (dateFrom == DateOnly.MinValue || dateTo == DateOnly.MaxValue)
{
throw new Exception();
}
if (type == "pdf")
{
APIStorekeeper.PostRequest($"api/discipline/createreporttopdffile?dateFrom={dateFrom:yyyy-MM-dd}&dateTo={dateTo:yyyy-MM-dd}", new ReportDateRangeBindingModel
{
FileName = "C:\\ÂðåìåííûåÎò÷¸òû\\Ñâåäåíèÿ ïî ïëàíàì îáó÷åíèÿ.pdf"
});
APIStorekeeper.PostRequest("api/discipline/sendpdftomail", new MailSendInfoBindingModel
{
MailAddress = APIStorekeeper.Client.Email,
Subject = "Îò÷åò",
Text = "Ñâåäåíèÿ ïî äèñöèïëèíàì"
});
}
Response.Redirect("Index");
return;
}
[HttpGet]
public IActionResult ReportDisciplines(DateOnly dateFrom, DateOnly dateTo)
{
if (APIStorekeeper.Client == null)
{
return Redirect("~/Home/Enter");
}
// Ïåðåäàåì äàííûå â ÷àñòè÷íîå ïðåäñòàâëåíèå
if (dateFrom == DateOnly.MinValue || dateTo == DateOnly.MaxValue)
{
return View("ReportDisciplines", null);
}
var reportData = APIStorekeeper.GetRequest<List<ReportDisciplineViewModel>>($"api/discipline/getreportdisciplines?datefrom={dateFrom:yyyy-MM-dd}&dateto={dateTo:yyyy-MM-dd}");
return View("ReportDisciplines", reportData);
}
public IActionResult GetWordFile()
{
return PhysicalFile($"C:\\ÂðåìåííûåÎò÷¸òû\\TeachersAndStudents.xlsx",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"TeachersAndStudents.docx");
}
public IActionResult GetExcelFile()
{
return PhysicalFile($"C:\\ÂðåìåííûåÎò÷¸òû\\TeachersAndStudents.xlsx",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"TeachersAndStudents.xlsx");
}
// UDS
// Ïðåïîäàâàòåëü
[HttpPost]
public void DeleteTeacher(int id)
{
if (id == 0)
{
throw new Exception("id íå ìîæåò áûòü ðàâåí 0");
}
APIStorekeeper.PostRequest("api/teacher/deleteteacher", new TeacherBindingModel
{
Id = id
});
Response.Redirect("Teachers");
}
[HttpGet]
public IActionResult InfoTeacher(int id)
{
if (APIStorekeeper.Client == null)
{
return Redirect("~/Home/Enter");
}
var obj = APIStorekeeper.GetRequest<TeacherViewModel>($"api/teacher/getteacher?userId={APIStorekeeper.Client.Id}&id={id}");
return View(obj);
}
[HttpPost]
public void UpdateTeacher(int id, string name, string academicdegree, string position)
{
if (APIStorekeeper.Client == null)
{
throw new Exception("Âõîä òîëüêî àâòîðèçîâàííûì");
}
if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(academicdegree) || string.IsNullOrEmpty(position))
{
throw new Exception("Ââåäèòå");
}
APIStorekeeper.PostRequest("api/teacher/updateteacher", new TeacherBindingModel
{
Id = id,
Name = name,
AcademicDegree = academicdegree,
Position = position
});
Response.Redirect("Teachers");
}
// Âåäîìîñòü
[HttpPost]
public void DeleteStatement(int id)
{
if (id == 0)
{
throw new Exception("id íå ìîæåò áûòü ðàâåí 0");
}
APIStorekeeper.PostRequest("api/statement/deletestatement", new StatementBindingModel
{
Id = id
});
Response.Redirect("Statements");
}
[HttpGet]
public IActionResult InfoStatement(int id)
{
if (APIStorekeeper.Client == null)
{
return Redirect("~/Home/Enter");
}
ViewBag.Teachers = APIStorekeeper.GetRequest<List<TeacherViewModel>>($"api/teacher/getteachers?userId={APIStorekeeper.Client.Id}");
var obj = APIStorekeeper.GetRequest<StatementViewModel>($"api/statement/getstatement?userId={APIStorekeeper.Client.Id}&id={id}");
return View(obj);
}
[HttpPost]
public void UpdateStatement(int id, string name, DateTime date, int teacher)
{
if (APIStorekeeper.Client == null)
{
throw new Exception("Âõîä òîëüêî àâòîðèçîâàííûì");
}
if (string.IsNullOrEmpty(name) || teacher == 0)
{
throw new Exception("Ââåäèòå");
}
APIStorekeeper.PostRequest("api/statement/updatestatement", new StatementBindingModel
{
Id = id,
Name = name,
Date = date,
TeacherId = teacher
});
Response.Redirect("Statements");
}
// Äèñöèïëèíà
[HttpGet]
public async Task<IActionResult> InfoDiscipline(int id)
{
if (APIStorekeeper.Client == null)
{
return Redirect("~/Home/Enter");
}
var obj1 = APIStorekeeper.GetRequest<List<StudentViewModel>>($"api/student/getallstudents");
ViewBag.Students = obj1;
var obj2 = APIStorekeeper.GetRequest<List<TeacherViewModel>>($"api/teacher/getteachers?userId={APIStorekeeper.Client.Id}");
ViewBag.Teachers = obj2;
var obj = await APIStorekeeper.GetRequestDisciplineAsync<DisciplineViewModel>($"api/discipline/getdiscipline?id={id}&userId={APIStorekeeper.Client.Id}");
return View(obj);
}
[HttpPost]
public void DeleteDiscipline(int id)
{
if (id == 0)
{
throw new Exception("id íå ìîæåò áûòü ðàâåí 0");
}
APIStorekeeper.PostRequest("api/discipline/deletediscipline", new DisciplineBindingModel
{
Id = id
});
Response.Redirect("Disciplines");
}
[HttpPost]
public void UpdateDiscipline(int id, string name, string description, int teacher, List<int> studentIds, DateOnly date)
{
if (id == 0)
{
throw new Exception("id íå ìîæåò áûòü ðàâåí 0");
}
var disciplineStudents = studentIds.ToDictionary(id => id, id => (IStudentModel)null);
APIStorekeeper.PostRequest("api/discipline/updatediscipline", new DisciplineBindingModel
{
Id = id,
Name = name,
Description = description,
TeacherId = teacher,
StudentDisciplines = disciplineStudents,
Date = date
});
Response.Redirect("Disciplines");
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error() public IActionResult Error()

View File

@ -1,9 +1,12 @@
using UniversityClientAppStorekeeper;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
// Add services to the container. // Add services to the container.
builder.Services.AddControllersWithViews(); builder.Services.AddControllersWithViews().AddRazorRuntimeCompilation();
var app = builder.Build(); var app = builder.Build();
APIStorekeeper.Connect(builder.Configuration);
// Configure the HTTP request pipeline. // Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment()) if (!app.Environment.IsDevelopment())

View File

@ -13,6 +13,11 @@
</PackageReference> </PackageReference>
</ItemGroup> </ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="6.0.26" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\UniversityDatabaseImplement\UniversityDatabaseImplement.csproj" /> <ProjectReference Include="..\UniversityDatabaseImplement\UniversityDatabaseImplement.csproj" />
</ItemGroup> </ItemGroup>

View File

@ -1,5 +1,10 @@
@{ @using UniversityContracts.ViewModels
ViewData["Title"] = "Manage Disciplines"; @model List<DisciplineViewModel>
@{
List<StudentViewModel> students = ViewBag.Students;
}
@{
ViewData["Title"] = "Управление дисциплинами";
} }
<div class="text-center"> <div class="text-center">
@ -9,27 +14,54 @@
<form method="post"> <form method="post">
<div class="row"> <div class="row">
<div class="col-4">Name:</div> <div class="col-4">Название:</div>
<div class="col-8"> <div class="col-8">
<input type="text" name="name" id="name" class="form-control" /> <input type="text" name="name" id="name" class="form-control" />
</div> </div>
</div> </div>
<div class="row"> <div class="row">
<div class="col-4">Description:</div> <div class="col-4">Описание:</div>
<div class="col-8"> <div class="col-8">
<textarea name="description" id="description" class="form-control"></textarea> <textarea name="description" id="description" class="form-control"></textarea>
</div> </div>
</div> </div>
<div class="row"> <div class="row">
<div class="col-4">Students:</div> <div class="col-4">Дата:</div>
<div class="col-8"> <div class="col-8">
<select id="students" name="students" class="form-control" multiple asp-items="ViewBag.Students"></select> <input type="date" name="date" id="date" class="form-control" />
</div> </div>
</div> </div>
<div class="row">
<div class="col-4">Преподаватель:</div>
<div class="col-8">
<select id="teacher" name="teacher" class="form-control" asp-items="@(new SelectList(@ViewBag.Teachers,"Id", "Name"))"></select>
</div>
</div>
<div class="row">
<div class="col-4">Студенты:</div>
<div class="col-8">
<div class="scrollable-list">
@foreach (var student in students)
{
<div class="form-check">
<input class="form-check-input" type="checkbox" name="studentIds" value="@student.Id" id="student-@student.Id">
<label class="form-check-label" for="student-@student.Id">
@student.Name
</label>
</div>
}
</div>
</div>
</div>
<div class="row"> <div class="row">
<div class="col-8"></div> <div class="col-8"></div>
<div class="col-4"> <div class="col-4">
<input type="submit" value="Create Discipline" class="btn btn-primary" /> <input type="submit" value="Создать дисциплину" class="btn btn-primary" />
</div> </div>
</div> </div>
</form> </form>
@ -37,32 +69,40 @@
<table class="table"> <table class="table">
<thead> <thead>
<tr> <tr>
<th>Name</th> <th>Имя</th>
<th>Description</th> <th>Описание</th>
<th>Students</th> <th>Дата</th>
<th>Actions</th> <th>Имя учителя</th>
<th></th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@* @foreach (var discipline in Model) @foreach (var item in Model)
{ {
<tr> <tr>
<td>@discipline.Name</td>
<td>@discipline.Description</td>
<td> <td>
@foreach (var student in discipline.Students) @Html.DisplayFor(modelItem => item.Id)
{
<span>@student.Name</span>
}
</td> </td>
<td> <td>
<a asp-action="Edit" asp-route-id="@discipline.Id" class="btn btn-warning">Edit</a> @Html.DisplayFor(modelItem => item.Name)
<a asp-action="Details" asp-route-id="@discipline.Id" class="btn btn-info">Details</a> </td>
<a asp-action="Delete" asp-route-id="@discipline.Id" class="btn btn-danger">Delete</a> <td>
@Html.DisplayFor(modelItem => item.Date)
</td>
<td>
@Html.DisplayFor(modelItem => item.TeacherName)
<td>
<div class="btn-group">
<a asp-controller="Home" asp-action="InfoDiscipline" asp-route-id="@item.Id" class="btn btn-warning">Изменить</a>
<form asp-controller="Home" asp-action="DeleteDiscipline" method="post">
<input type="hidden" name="id" value="@item.Id" />
<button type="submit" class="btn btn-danger">Удалить</button>
</form>
</div>
</td>
</td> </td>
</tr> </tr>
} *@ }
</tbody> </tbody>
</table> </table>

View File

@ -2,7 +2,7 @@
ViewData["Title"] = "Enter"; ViewData["Title"] = "Enter";
} }
<div class="text-center"> <div class="text-center">
<h2 class="display-4">Вход в приложение</h2> <h2 class="display-4">Вход</h2>
</div> </div>
<form method="post"> <form method="post">
<div class="row"> <div class="row">
@ -15,6 +15,8 @@
</div> </div>
<div class="row"> <div class="row">
<div class="col-8"></div> <div class="col-8"></div>
<div class="col-4"><input type="submit" value="Вход" class="btn btnprimary" /></div> <div class="col-4"><input type="submit" value="Submit" class="btn btnprimary" /></div>
</div> </div>
</form> </form>
<a href="/Home/Register">Register</a>

View File

@ -3,12 +3,12 @@
} }
<div class="text-center"> <div class="text-center">
<div class="menu"> <div class="menu">
<a href="/Home/Disciplines">Disciplines</a> <a href="/Home/Disciplines">Дисциплины</a>
<a href="/Home/Teachers">Teachers</a> <a href="/Home/Teachers">Преподаватели</a>
<a href="/Home/Statements">Statements</a> <a href="/Home/Statements">Ведомости</a>
<a href="/Home/Report">Report</a> <a href="/Home/Report">Отчёты по преподавателям</a>
<a href="/Home/ReportDisciplines">Отчёты по дисциплинам</a>
</div> </div>
<div class="header"> <div class="header">
<img src="" alt="Logo" class="logo"> <img src="" alt="Logo" class="logo">

View File

@ -0,0 +1,64 @@
@using UniversityContracts.ViewModels
@model DisciplineViewModel
@{
ViewData["Title"] = "Дисциплина";
}
<div class="text-center">
<h2 class="display-4">@ViewData["Title"] - @Model.Id</h2>
</div>
<form asp-action="UpdateDiscipline" method="post">
<div class="row">
<div class="col-4">Название:</div>
<div class="col-8">
<input type="text" name="name" id="name" class="form-control" value="@Model.Name"/>
</div>
</div>
<div class="row">
<div class="col-4">Описание:</div>
<div class="col-8">
<input name="description" id="description" class="form-control" value="@Model.Description"></input>
</div>
</div>
<div class="row">
<div class="col-4">Дата:</div>
<div class="col-8">
<input type="date" name="date" id="date" class="form-control" value="@Model.Date" />
</div>
</div>
<div class="row">
<div class="col-4">Преподаватель:</div>
<div class="col-8">
<select id="teacher" name="teacher" class="form-control" asp-items="@(new SelectList(@ViewBag.Teachers,"Id", "Name"))" value="@Model.TeacherId"></select>
</div>
</div>
<div class="row">
<div class="col-4">Студенты:</div>
<div class="col-8">
<div class="scrollable-list">
@foreach (var student in ViewBag.Students)
{
<div class="form-check">
<input class="form-check-input" type="checkbox" name="studentIds" value="@student.Id" id="student-@student.Id" /
checked="@(Model.StudentDisciplines.ContainsKey(student.Id))">
<label class="form-check-label" for="student-@student.Id">
@student.Name
</label>
</div>
}
</div>
</div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4">
<form asp-action="Disciplines">
<input type="submit" value="Отмена" class="btn btn-primary" />
</form>
<input type="hidden" name="id" value="@Model.Id" />
<input type="submit" value="Сохранить" class="btn btn-danger" />
</div>
</div>
</form>

View File

@ -0,0 +1,41 @@
@using UniversityContracts.ViewModels
@model StatementViewModel
@{
ViewData["Title"] = "Ведомость";
}
<div class="text-center">
<h2 class="display-4">@ViewData["Title"] - @Model.Id</h2>
</div>
<form asp-action="UpdateStatement" method="post">
<div class="row">
<div class="col-4">Название:</div>
<div class="col-8">
<input type="text" name="name" id="name" class="form-control" value="@Model.Name"/>
</div>
</div>
<div class="row">
<div class="col-4">Дата:</div>
<div class="col-8">
<input type="datetime-local" name="date" id="date" class="form-control" value="@Model.Date"/>
</div>
</div>
<div class="row">
<div class="col-4">Преподаватель:</div>
<div class="col-8">
<select id="teacher" name="teacher" class="form-control" asp-items="@(new SelectList(@ViewBag.Teachers,"Id", "Name"))" value="@Model.TeacherId"></select>
</div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4 mt-2">
<form asp-action="Statements">
<input type="submit" value="Отмена" class="btn btn-primary" />
</form>
<input type="hidden" name="id" value="@Model.Id" />
<input type="submit" value="Сохранить" class="btn btn-danger" />
</div>
</div>
</form>

View File

@ -0,0 +1,38 @@
@using UniversityContracts.ViewModels
@model TeacherViewModel
@{
ViewData["Title"] = "Преподаватель";
}
<div class="text-center">
<h2 class="display-4">@ViewData["Title"] - @Model.Id</h2>
</div>
<form asp-action="UpdateTeacher" method="post">
<div class="row">
<div class="col-4">Имя:</div>
<div class="col-8">
<input type="text" name="name" id="name" class="form-control" value="@Model.Name" />
</div>
</div>
<div class="row">
<div class="col-4">Учёная степень:</div>
<div class="col-8">
<input type="text" name="academicDegree" id="academicDegree" class="form-control" value="@Model.AcademicDegree" />
</div>
</div>
<div class="row">
<div class="col-4">Должность:</div>
<div class="col-8">
<input type="text" name="position" id="position" class="form-control" value="@Model.Position" />
</div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4 mt-2">
<form asp-action="Teachers">
<input type="submit" value="Отмена" class="btn btn-primary" />
</form>
<input type="hidden" name="id" value="@Model.Id" />
<input type="submit" value="Сохранить" class="btn btn-danger" />
</div>
</div>
</form>

View File

@ -1,6 +1,6 @@
@{ @{
ViewData["Title"] = "Privacy Policy"; ViewData["Title"] = "Прайваси";
} }
<h1>@ViewData["Title"]</h1> <h1>@ViewData["Title"]</h1>
<p>Use this page to detail your site's privacy policy.</p> <p>Прайваси</p>

View File

@ -7,31 +7,19 @@
<form method="post"> <form method="post">
<div class="row"> <div class="row">
<div class="col-4">Логин:</div> <div class="col-4">Логин:</div>
<div class="col-8"><input type="text" name="email" /></div> <div class="col-8"><input type="text" name="login" /></div>
</div> </div>
<div class="row"> <div class="row">
<div class="col-4">Пароль:</div> <div class="col-4">Пароль:</div>
<div class="col-8"><input type="password" name="password" /></div> <div class="col-8"><input type="password" name="password" /></div>
</div> </div>
<div class="row"> <div class="row">
<div class="col-4">Фамилия:</div> <div class="col-4">Email:</div>
<div class="col-8"><input type="text" name="lastName" /></div> <div class="col-8"><input type="text" name="email" /></div>
</div> </div>
<div class="row">
<div class="col-4">Имя:</div>
<div class="col-8"><input type="text" name="firstName" /></div>
</div>
<div class="row">
<div class="col-4">Отчество:</div>
<div class="col-8"><input type="text" name="midleName" /></div>
</div>
<div class="row">
<div class="col-4">Телефон:</div>
<div class="col-8"><input type="text" name="phoneNumber" /></div>
</div>
<div class="row"> <div class="row">
<div class="col-8"></div> <div class="col-8"></div>
<div class="col-4"><input type="submit" value="Регистрация" <div class="col-4"><input type="submit" value="Submit"
class="btn btn-primary" /></div> class="btn btn-primary" /></div>
</div> </div>
</form> </form>

View File

@ -1,5 +1,7 @@
@{ @using UniversityContracts.ViewModels
ViewData["Title"] = "Student List by Teacher"; @model List<ReportTeacherViewModel>
@{
ViewData["Title"] = "Отчёты по преподавателям со студентами";
} }
<div class="text-center"> <div class="text-center">
@ -8,33 +10,47 @@
<form method="post"> <form method="post">
<div class="row"> <div class="row">
<div class="col-4">Teachers:</div> <div class="col-8 btn-group"></div>
<div class="col-8"> <div class="col-4 mt-2">
<select id="teachers" name="teachers" class="form-control" multiple asp-items="ViewBag.Teachers"></select> <form method="post">
</div> <input type="hidden" name="type" value="docx" />
</div> <input type="submit" value="Save in Word" class="btn btn-primary" />
<div class="row"> </form>
<div class="col-4">File Format:</div>
<div class="col-8"> <form method="post">
<select id="fileFormat" name="fileFormat" class="form-control" asp-items="ViewBag.FileFormats"></select> <input type="hidden" name="type" value="xlsx" />
</div> <input type="submit" value="Save in Excel" class="btn btn-success" />
</div> </form>
<div class="row"> </div>
<div class="col-4">File Name:</div> <div class="col-4 mt-2">
<div class="col-8">
<input type="text" name="fileName" id="fileName" class="form-control" />
</div>
</div>
<div class="row">
<div class="col-4">File Location:</div>
<div class="col-8">
<input type="text" name="fileLocation" id="fileLocation" class="form-control" />
</div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4">
<input type="submit" value="Get Student List" class="btn btn-primary" />
</div> </div>
</div> </div>
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>Имя преподавателя</th>
<th>Студент</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@item.TeacherId
</td>
<td>
@item.TeacherName
</td>
<td>
@foreach (var st in item.Students)
{
<div>@st</div>
}
</td>
</tr>
}
</tbody>
</table>
</form> </form>

View File

@ -0,0 +1,57 @@
@using UniversityContracts.ViewModels
@model List<ReportDisciplineViewModel>
<form method="get" action="/Home/ReportDisciplines">
<div class="text-center">
<h2 class="display-4">Отчёт за период по дисциплинам</h2>
</div>
<div class="form-group">
<label class="mb-3" for="dateFrom">Начало периода:</label>
<input type="date" placeholder="Выберите дату начала периода" id="dateFrom" name="dateFrom" />
</div>
<div class="form-group">
<label class="mb-3" for="dateTo">Окончание периода:</label>
<input type="date" placeholder="Выберите дату окончания периода" id="dateTo" name="dateTo" />
</div>
<div class="row">
<div class="col-4"><input type="submit" value="Вывести здесь" class="btn btn-primary" /></div>
</div>
</form>
<form method="post" action="/Home/ReportDisciplines">
<div class="form-group">
<label class="mb-3" for="dateFrom">Начало периода:</label>
<input type="date" placeholder="Выберите дату начала периода" id="dateFrom" name="dateFrom" />
</div>
<div class="form-group">
<label class="mb-3" for="dateTo">Окончание периода:</label>
<input type="date" placeholder="Выберите дату окончания периода" id="dateTo" name="dateTo" />
</div>
<input type="hidden" name="type" value="pdf" />
<input type="submit" value="Отправить в формате Pdf на почту" class="btn btn-primary" />
</form>
@if (Model != null && Model.Any())
{
<table class="table" id="reportTable">
<thead>
<tr>
<th>Название дисциплины</th>
<th>Планы обучения</th>
<th>Заявления</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>@item.DisciplineName</td>
<td>@string.Join(", ", item.PlanOfStudys)</td>
<td>@string.Join(", ", item.Statements)</td>
</tr>
}
</tbody>
</table>
}

View File

@ -1,5 +1,7 @@
@{ @using UniversityContracts.ViewModels
ViewData["Title"] = "Manage Statement Records"; @model List<StatementViewModel>
@{
ViewData["Title"] = "Управление ведомостями";
} }
<div class="text-center"> <div class="text-center">
@ -10,27 +12,27 @@
<form method="post"> <form method="post">
<div class="row"> <div class="row">
<div class="col-4">Title:</div> <div class="col-4">Название:</div>
<div class="col-8"> <div class="col-8">
<input type="text" name="title" id="title" class="form-control" /> <input type="text" name="name" id="name" class="form-control" />
</div> </div>
</div> </div>
<div class="row"> <div class="row">
<div class="col-4">Date:</div> <div class="col-4">Дата:</div>
<div class="col-8"> <div class="col-8">
<input type="date" name="date" id="date" class="form-control" /> <input type="datetime-local" name="date" id="date" class="form-control" />
</div> </div>
</div> </div>
<div class="row"> <div class="row">
<div class="col-4">Teacher:</div> <div class="col-4">Преподаватель:</div>
<div class="col-8"> <div class="col-8">
<select id="teacherId" name="teacherId" class="form-control" asp-items="ViewBag.Teachers"></select> <select id="teacher" name="teacher" class="form-control" asp-items="@(new SelectList(@ViewBag.Teachers,"Id", "Name"))"></select>
</div> </div>
</div> </div>
<div class="row"> <div class="row">
<div class="col-8"></div> <div class="col-8"></div>
<div class="col-4"> <div class="col-4">
<input type="submit" value="Create Statement Record" class="btn btn-primary" /> <input type="submit" value="Создать ведомость" class="btn btn-primary" />
</div> </div>
</div> </div>
</form> </form>
@ -38,26 +40,39 @@
<table class="table"> <table class="table">
<thead> <thead>
<tr> <tr>
<th>Title</th> <th>Id</th>
<th>Date</th> <th>Название</th>
<th>Teacher</th> <th>Дата</th>
<th>Actions</th> <th>Преподаватель</th>
<th>Действие</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>@foreach (var item in Model)
@* @foreach (var record in Model)
{ {
<tr> <tr>
<td>@record.Title</td>
<td>@record.Date.ToString("d")</td>
<td>@record.Teacher.Name</td>
<td> <td>
<a asp-action="Edit" asp-route-id="@record.Id" class="btn btn-warning">Edit</a> @Html.DisplayFor(modelItem => item.Id)
<a asp-action="Details" asp-route-id="@record.Id" class="btn btn-info">Details</a> </td>
<a asp-action="Delete" asp-route-id="@record.Id" class="btn btn-danger">Delete</a> <td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Date)
</td>
<td>
@Html.DisplayFor(modelItem => item.TeacherName)
</td>
<td>
<div class="btn-group">
<a asp-controller="Home" asp-action="InfoStatement" asp-route-id="@item.Id" class="btn btn-warning">Изменить</a>
<form asp-controller="Home" asp-action="DeleteStatement" method="post">
<input type="hidden" name="id" value="@item.Id" />
<button type="submit" class="btn btn-danger">Удалить</button>
</form>
</div>
</td> </td>
</tr> </tr>
} *@ }
</tbody> </tbody>
</table> </table>

View File

@ -1,5 +1,7 @@
@{ @using UniversityContracts.ViewModels
ViewData["Title"] = "Manage Teachers"; @model List<TeacherViewModel>
@{
ViewData["Title"] = "Преподаватели";
} }
<div class="text-center"> <div class="text-center">
@ -9,33 +11,27 @@
<form method="post"> <form method="post">
<div class="row"> <div class="row">
<div class="col-4">Name:</div> <div class="col-4">Имя:</div>
<div class="col-8"> <div class="col-8">
<input type="text" name="name" id="name" class="form-control" /> <input type="text" name="name" id="name" class="form-control" />
</div> </div>
</div> </div>
<div class="row"> <div class="row">
<div class="col-4">Academic Degree:</div> <div class="col-4">Учёная степень:</div>
<div class="col-8"> <div class="col-8">
<input type="text" name="academicDegree" id="academicDegree" class="form-control" /> <input type="text" name="academicDegree" id="academicDegree" class="form-control" />
</div> </div>
</div> </div>
<div class="row"> <div class="row">
<div class="col-4">Position:</div> <div class="col-4">Должность:</div>
<div class="col-8"> <div class="col-8">
<input type="text" name="position" id="position" class="form-control" /> <input type="text" name="position" id="position" class="form-control" />
</div> </div>
</div> </div>
<div class="row">
<div class="col-4">Disciplines:</div>
<div class="col-8">
<select id="disciplines" name="disciplines" class="form-control" multiple asp-items="ViewBag.Disciplines"></select>
</div>
</div>
<div class="row"> <div class="row">
<div class="col-8"></div> <div class="col-8"></div>
<div class="col-4"> <div class="col-4">
<input type="submit" value="Create Teacher" class="btn btn-primary" /> <input type="submit" value="Создать преподавателя" class="btn btn-primary" />
</div> </div>
</div> </div>
</form> </form>
@ -43,35 +39,40 @@
<table class="table"> <table class="table">
<thead> <thead>
<tr> <tr>
<th>Name</th> <th>Id</th>
<th>Academic Degree</th> <th>Имя</th>
<th>Position</th> <th>Учёная степень</th>
<th>Disciplines</th> <th>Должность</th>
<th>Actions</th> <th>Действия</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@foreach (var item in Model)
@* @foreach (var teacher in Model)
{ {
<tr> <tr>
<td>@teacher.Name</td>
<td>@teacher.AcademicDegree</td>
<td>@teacher.Position</td>
<td> <td>
@foreach (var discipline in teacher.Disciplines) @Html.DisplayFor(modelItem => item.Id)
{
<span>@discipline.Name</span>
}
</td> </td>
<td> <td>
<a asp-action="Edit" asp-route-id="@teacher.Id" class="btn btn-warning">Edit</a> @Html.DisplayFor(modelItem => item.Name)
<a asp-action="Details" asp-route-id="@teacher.Id" class="btn btn-info">Details</a> </td>
<a asp-action="Delete" asp-route-id="@teacher.Id" class="btn btn-danger">Delete</a> <td>
@Html.DisplayFor(modelItem => item.AcademicDegree)
</td>
<td>
@Html.DisplayFor(modelItem => item.Position)
</td>
<td>
<div class="btn-group">
<a asp-controller="Home" asp-action="InfoTeacher" asp-route-id="@item.Id" class="btn btn-warning">Изменить</a>
<form asp-controller="Home" asp-action="DeleteTeacher" method="post">
<input type="hidden" name="id" value="@item.Id" />
<button type="submit" class="btn btn-danger">Удалить</button>
</form>
</div>
</td> </td>
</tr> </tr>
} *@ }
</tbody> </tbody>
</table> </table>

View File

@ -20,10 +20,25 @@
<div class="navbar-collapse collapse d-sm-inline-flex justify-content-between"> <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
<ul class="navbar-nav flex-grow-1"> <ul class="navbar-nav flex-grow-1">
<li class="nav-item"> <li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a> <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Главная</a>
</li> </li>
<li class="nav-item"> <li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a> <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Прайваси</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="Teachers">Преподаватели</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Statements">Ведомости</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Report">Отчёты по преподавателям и студентам</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="ReportDisciplines">Отчёт по дисциплинам</a>
</li> </li>
</ul> </ul>
</div> </div>

View File

@ -5,5 +5,6 @@
"Microsoft.AspNetCore": "Warning" "Microsoft.AspNetCore": "Warning"
} }
}, },
"AllowedHosts": "*" "AllowedHosts": "*",
"IPAddress": "http://localhost:5032/"
} }

View File

@ -20,3 +20,8 @@ html {
body { body {
margin-bottom: 60px; margin-bottom: 60px;
} }
.scrollable-list {
max-height: 200px; /* Âûñîòà ñêðîëëáàðà */
overflow-y: auto; /* Äîáàâëÿåì ñêðîëëáàð */
}

View File

@ -0,0 +1,131 @@
using Newtonsoft.Json;
using UniversityContracts.ViewModels;
using System.Net.Http.Headers;
using System.Text;
using Azure.Core;
using UniversityDataModels.Models;
using UniversityDatabaseImplement.Models;
namespace PlumbingRepairClientApp
{
public class APIClient
{
private static readonly HttpClient _client = new();
public static UserViewModel? User { get; set; } = null;
public static void Connect(IConfiguration configuration)
{
_client.BaseAddress = new Uri(configuration["IPAddress"]);
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public static T? GetRequest<T>(string requestUrl)
{
var response = _client.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 async Task<T?> GetRequestPlanOfStudyAsync<T>(string requestUrl)
{
var response = await _client.GetAsync(requestUrl);
var result = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
var settings = new JsonSerializerSettings
{
Converters = new List<JsonConverter> { new TeacherConverter() }
};
return JsonConvert.DeserializeObject<T>(result, settings);
}
else
{
throw new Exception(result);
}
}
public static async Task<T?> GetRequestStudentsAsync<T>(string requestUrl)
{
var response = await _client.GetAsync(requestUrl);
var result = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
var settings = new JsonSerializerSettings
{
Converters = new List<JsonConverter> { new TeacherConverter() }
};
return JsonConvert.DeserializeObject<T>(result, settings);
}
else
{
throw new Exception(result);
}
}
public static async Task<T?> GetRequestAsync<T>(string requestUrl)
{
var response = await _client.GetAsync(requestUrl);
var result = await response.Content.ReadAsStringAsync();
if (response.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 = _client.PostAsync(requestUrl, data);
var result = response.Result.Content.ReadAsStringAsync().Result;
if (!response.Result.IsSuccessStatusCode)
{
throw new Exception(result);
}
}
}
public class TeacherConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(ITeacherModel);
//return true;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
// Пропускаем десериализацию, если уже есть экземпляр Teacher
if (existingValue is Teacher teacher)
return teacher;
var teach = new Teacher();
serializer.Populate(reader, teach);
return teach;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value == null)
{
writer.WriteNull();
return;
}
var teacher = (Teacher)value;
serializer.Serialize(writer, teacher);
}
}
}

View File

@ -1,7 +1,15 @@
using DocumentFormat.OpenXml.Office2010.Excel;
using DocumentFormat.OpenXml.Wordprocessing;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using PlumbingRepairClientApp;
using System.Diagnostics; using System.Diagnostics;
using UniversityClientAppWorker.Models; using UniversityClientAppWorker.Models;
using UniversityContracts.BindingModels;
using UniversityContracts.ViewModels;
using UniversityDatabaseImplement.Models;
using UniversityDataModels.Enums; using UniversityDataModels.Enums;
using UniversityDataModels.Models;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace UniversityClientAppWorker.Controllers namespace UniversityClientAppWorker.Controllers
{ {
@ -13,29 +21,315 @@ namespace UniversityClientAppWorker.Controllers
{ {
_logger = logger; _logger = logger;
} }
[HttpGet]
public IActionResult Index() public async Task<IActionResult> Index()
{ {
return View(); if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
} }
ViewBag.Teachers = APIClient.GetRequest<List<TeacherViewModel>>($"api/teacher/getallteachers");
var planOfStudys = await APIClient.GetRequestPlanOfStudyAsync<List<PlanOfStudyViewModel>>($"api/planofstudys/getplanofstudys?userId={APIClient.User.Id}");
return View(planOfStudys);
}
[HttpGet]
public async Task<IActionResult> InfoPlanOfStudy(int id)
{
if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
}
var obj1 = APIClient.GetRequest<List<TeacherViewModel>>($"api/teacher/getallteachers");
ViewBag.Teachers = obj1;
var obj = await APIClient.GetRequestPlanOfStudyAsync<PlanOfStudyViewModel>($"api/planofstudys/getplanofstudy?id={id}&userId={APIClient.User.Id}");
return View(obj);
}
[HttpPost]
public void CreatePlanOfStudy(string profile, string formOfStudy, List<int> teacherIds)
{
if (APIClient.User == null)
{
throw new Exception("Âõîä òîëüêî àâòîðèçîâàííûì ïîëüçîâàòåëÿì");
}
if (string.IsNullOrEmpty(formOfStudy) || string.IsNullOrEmpty(profile))
{
throw new Exception("Ââåäèòå äàííûå ïðîôèëÿ è ôîðìû îáó÷åíèÿ");
}
APIClient.PostRequest("api/planofstudys/createplanofstudy", new PlanOfStudyBindingModel
{
Profile = profile,
FormOfStudy = formOfStudy,
UserId = APIClient.User.Id,
PlanOfStudyTeachers = teacherIds.ToDictionary(id => id, id => (ITeacherModel)null)
});
Response.Redirect("Index");
}
[HttpPost]
public void DeletePlanOfStudy(int id)
{
if (id == 0)
{
throw new Exception("id íå ìîæåò áûòü ðàâåí 0");
}
APIClient.PostRequest("api/planofstudys/deleteplanofstudy", new PlanOfStudyBindingModel
{
Id = id
});
Response.Redirect("Index");
}
[HttpPost]
public void UpdatePlanOfStudy(int id, string profile, string formOfStudy, List<int> teacherIds)
{
if (id == 0)
{
throw new Exception("id íå ìîæåò áûòü ðàâåí 0");
}
var planOfStudyTeachers = teacherIds.ToDictionary(id => id, id => (ITeacherModel)null);
APIClient.PostRequest("api/planofstudys/updateplanofstudy", new PlanOfStudyBindingModel
{
Id = id,
Profile = profile,
FormOfStudy = formOfStudy,
PlanOfStudyTeachers = planOfStudyTeachers
});
Response.Redirect("Index");
}
[HttpGet]
public IActionResult Privacy() public IActionResult Privacy()
{ {
return View(); if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
} }
return View(APIClient.User);
}
[HttpPost]
public void Privacy(string login, string password, string email)
{
if (APIClient.User == null)
{
throw new Exception("Âõîä òîëüêî àâòîðèçîâàííûì ïîëüçîâàòåëÿì");
}
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(email))
{
throw new Exception("Ââåäèòå ëîãèí, ïàðîëü è ïî÷òó");
}
APIClient.PostRequest("api/user/updatedata", new UserViewModel
{
Id = APIClient.User.Id,
Email = email,
Login = login,
Password = password
});
APIClient.User.Login = login;
APIClient.User.Email = email;
APIClient.User.Password = password;
Response.Redirect("Index");
}
[HttpGet]
public IActionResult Attestations() public IActionResult Attestations()
{ {
ViewBag.AttestationScore = Enum.GetValues(typeof(AttestationScore)).Cast<AttestationScore>(); if (APIClient.User == null)
return View(); {
return Redirect("~/Home/Enter");
} }
ViewBag.Students = APIClient.GetRequest<List<StudentViewModel>>($"api/student/getstudents?userId={APIClient.User.Id}");
ViewBag.AttestationScore = Enum.GetValues(typeof(AttestationScore)).Cast<AttestationScore>();
var obj = APIClient.GetRequest<List<AttestationViewModel>>($"api/attestation/getattestations?userId={APIClient.User.Id}");
return View(obj);
}
[HttpPost]
public void CreateAttestation(string formOfEvaluation, int student, AttestationScore score)
{
if (APIClient.User == null)
{
throw new Exception("Âõîä òîëüêî àâòîðèçîâàííûì");
}
if (string.IsNullOrEmpty(formOfEvaluation) || student == 0)
{
throw new Exception("Ââåäèòå ôîðìó îöåíèâàíèÿ è âûáåðèòå ñòóäåíòà");
}
var Student = APIClient.GetRequest<StudentViewModel>($"api/student/getstudent?userId={APIClient.User.Id}&studentId={student}");
public IActionResult Students() if(Student == null)
{
throw new Exception("Ñòóäåíò íå íàéäåí");
}
APIClient.PostRequest("api/attestation/createattestation", new AttestationBindingModel
{
UserId = APIClient.User.Id,
FormOfEvaluation = formOfEvaluation,
StudentId = student,
StudentName = Student.Name,
Score = score
});
Response.Redirect("Attestations");
}
[HttpGet]
public IActionResult InfoAttestation(int id)
{
if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
}
ViewBag.Students = APIClient.GetRequest<List<StudentViewModel>>($"api/student/getstudents?userId={APIClient.User.Id}");
ViewBag.AttestationScore = Enum.GetValues(typeof(AttestationScore)).Cast<AttestationScore>();
var obj = APIClient.GetRequest<AttestationViewModel>($"api/attestation/getattestation?userId={APIClient.User.Id}&id={id}");
return View(obj);
}
[HttpPost]
public void UpdateAttestation(int id, string formOfEvaluation, int student, AttestationScore score)
{
if (APIClient.User == null)
{
throw new Exception("Âõîä òîëüêî àâòîðèçîâàííûì");
}
if (string.IsNullOrEmpty(formOfEvaluation) || student == 0)
{
throw new Exception("Ââåäèòå ôîðìó îöåíèâàíèÿ è âûáåðèòå ñòóäåíòà");
}
var Student = APIClient.GetRequest<StudentViewModel>($"api/student/getstudent?userId={APIClient.User.Id}&studentId={student}");
if (Student == null)
{
throw new Exception("Ñòóäåíò íå íàéäåí");
}
APIClient.PostRequest("api/attestation/updateattestation", new AttestationBindingModel
{
Id = id,
FormOfEvaluation = formOfEvaluation,
StudentId = student,
StudentName = Student.Name,
Score = score
});
Response.Redirect("Attestations");
}
[HttpPost]
public void DeleteAttestation(int id)
{
if (id == 0)
{
throw new Exception("id íå ìîæåò áûòü ðàâåí 0");
}
APIClient.PostRequest("api/attestation/deleteattestation", new PlanOfStudyBindingModel
{
Id = id
});
Response.Redirect("Attestations");
}
[HttpGet]
public async Task<IActionResult> Students()
{
if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
}
var planOfStudys = await APIClient.GetRequestPlanOfStudyAsync<List<PlanOfStudyViewModel>>
($"api/planofstudys/getplanofstudys?userId={APIClient.User.Id}");
ViewBag.PlanOfStudys = planOfStudys;
return View(APIClient.GetRequest<List<StudentViewModel>>($"api/student/getstudents?userId={APIClient.User.Id}"));
}
[HttpPost]
public async Task<IActionResult> CreateStudent(string name, int planOfStudy, string phoneNumber)
{
if (APIClient.User == null)
{
throw new Exception("Âõîä òîëüêî àâòîðèçîâàííûì");
}
if (string.IsNullOrEmpty(name) || planOfStudy == 0 || string.IsNullOrEmpty(phoneNumber))
{
throw new Exception("Ââåäèòå ÔÈÎ, ïëàí îáó÷åíèÿ è òåëåôîí");
}
var PlanOfStudy = await APIClient.GetRequestPlanOfStudyAsync<PlanOfStudyViewModel>($"api/planofstudys/getplanofstudy?id={planOfStudy}");
if(PlanOfStudy == null)
{
throw new Exception("Ïëàí îáó÷åíèÿ íå íàéäåí");
}
APIClient.PostRequest("api/student/createstudent", new StudentBindingModel
{
UserId = APIClient.User.Id,
Name = name,
PlanOfStudyId = planOfStudy,
PlanOfStudyProfile = PlanOfStudy.Profile,
PhoneNumber = phoneNumber,
});
return Redirect("/Home/Students");
}
[HttpGet]
public async Task<IActionResult> InfoStudent(int id)
{
if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
}
if(id == 0)
{
throw new Exception("id íå ìîæåò áûòü 0");
}
var planOfStudys = await APIClient.GetRequestPlanOfStudyAsync<List<PlanOfStudyViewModel>>
($"api/planofstudys/getplanofstudys?userId={APIClient.User.Id}");
ViewBag.PlanOfStudys = planOfStudys;
var obj = APIClient.GetRequest<StudentViewModel>($"api/student/getstudent?userId={APIClient.User.Id}&studentId={id}");
return View(obj);
}
[HttpPost]
public async Task<IActionResult> UpdateStudent(int id, string name, int planOfStudy, string phoneNumber)
{
if (APIClient.User == null)
{
throw new Exception("Âõîä òîëüêî àâòîðèçîâàííûì");
}
if(id == 0)
{
throw new Exception("id íå ìîæåò áûòü 0");
}
if (string.IsNullOrEmpty(name) || planOfStudy == 0 || string.IsNullOrEmpty(phoneNumber))
{
throw new Exception("Ââåäèòå ÔÈÎ, ïëàí îáó÷åíèÿ è òåëåôîí");
}
var PlanOfStudy = await APIClient.GetRequestPlanOfStudyAsync<PlanOfStudyViewModel>($"api/planofstudys/getplanofstudy?id={planOfStudy}");
if (PlanOfStudy == null)
{
throw new Exception("Ïëàí îáó÷åíèÿ íå íàéäåí");
}
APIClient.PostRequest("api/student/updatestudent", new StudentBindingModel
{
Id = id,
Name = name,
PlanOfStudyId = planOfStudy,
PlanOfStudyProfile = PlanOfStudy.Profile,
PhoneNumber = phoneNumber,
});
return Redirect("/Home/Students");
}
[HttpPost]
public void DeleteStudent(int id)
{
if (APIClient.User == null)
{
throw new Exception("Âõîä òîëüêî àâòîðèçîâàííûì");
}
if (id == 0)
{
throw new Exception("id íå ìîæåò áûòü 0");
}
APIClient.PostRequest("api/student/deletestudent", new StudentBindingModel
{
Id = id
});
Response.Redirect("Students");
}
[HttpGet]
public IActionResult Enter()
{ {
return View(); return View();
} }
[HttpGet]
public IActionResult PlanOfStudys() public IActionResult Register()
{ {
return View(); return View();
} }
@ -44,6 +338,124 @@ namespace UniversityClientAppWorker.Controllers
public IActionResult Error() public IActionResult Error()
{ {
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
[HttpPost]
public void Enter(string login, string password)
{
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password))
{
throw new Exception("Ââåäèòå ëîãèí è ïàðîëü");
}
APIClient.User = APIClient.GetRequest<UserViewModel>($"api/user/loginworker?login={login}&password={password}");
if (APIClient.User == null)
{
throw new Exception("Íåâåðíûé ëîãèí/ïàðîëü");
}
Response.Redirect("Index");
}
[HttpPost]
public void Register(string login, string password, string email)
{
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(email))
{
throw new Exception("Ââåäèòå ëîãèí, ïàðîëü è ïî÷òó");
}
APIClient.PostRequest("api/user/registerworker", new UserBindingModel
{
Email = email,
Login = login,
Password = password
});
Response.Redirect("Enter");
return;
}
[HttpGet]
public IActionResult GetWordFile()
{
return PhysicalFile($"C:\\ÂðåìåííûåÎò÷¸òû\\Ïëàíû îáó÷åíèé ïî äèñöèïëèíàì.docx",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"Ïëàíû îáó÷åíèé ïî äèñöèïëèíàì.docx");
}
public IActionResult GetExcelFile()
{
return PhysicalFile($"C:\\ÂðåìåííûåÎò÷¸òû\\Ïëàíû îáó÷åíèé ïî äèñöèïëèíàì.xlsx",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"Ïëàíû îáó÷åíèé ïî äèñöèïëèíàì.xlsx");
}
[HttpGet]
public IActionResult ReportPlanOfStudys()
{
if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
}
return View("ReportPlanOfStudys", APIClient.GetRequest<List<ReportPlanOfStudyViewModel>>($"api/planofstudys/getplanofstudyanddisciplines?userId={APIClient.User.Id}"));
}
[HttpPost]
public IActionResult ReportPlanOfStudys(string type)
{
if (APIClient.User == null)
{
Redirect("~/Home/Enter");
throw new Exception("Âõîä òîëüêî àâòîðèçîâàííûì");
}
if (string.IsNullOrEmpty(type))
{
throw new Exception("Íåâåðíûé òèï îò÷åòà");
}
if (type == "docx")
{
APIClient.PostRequest("api/planofstudys/loadreporttoword", new ReportBindingModel
{
FileName = "C:\\ÂðåìåííûåÎò÷¸òû\\Ïëàíû îáó÷åíèé ïî äèñöèïëèíàì.docx"
});
return GetWordFile();
}
if (type == "xlsx")
{
APIClient.PostRequest("api/planofstudys/loadreporttoexcel", new ReportBindingModel
{
FileName = "C:\\ÂðåìåííûåÎò÷¸òû\\Ïëàíû îáó÷åíèé ïî äèñöèïëèíàì.xlsx"
});
return GetExcelFile();
}
return Redirect("Index");
}
[HttpGet]
public IActionResult ReportPlanOfStudyAndStudents()
{
if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
}
return View("ReportPlanOfStudyAndStudents", APIClient.GetRequest<List<ReportPlanOfStudyAndStudentViewModel>>($"api/planofstudys/getplanofstudyandstudents"));
}
[HttpPost]
public void ReportPlanOfStudyAndStudents(string type)
{
if (APIClient.User == null)
{
Redirect("~/Home/Enter");
throw new Exception("Âõîä òîëüêî àâòîðèçîâàííûì");
}
if (type == "pdf")
{
APIClient.PostRequest("api/planofstudys/createreporttopdffile", new ReportBindingModel
{
FileName = "C:\\ÂðåìåííûåÎò÷¸òû\\Ñâåäåíèÿ ïî ïëàíàì îáó÷åíèÿ.pdf"
});
APIClient.PostRequest("api/planofstudys/sendpdftomail", new MailSendInfoBindingModel
{
MailAddress = APIClient.User.Email,
Subject = "Îò÷åò",
Text = "Ñâåäåíèÿ ïî ïëàíàì îáó÷åíèÿ"
});
}
Response.Redirect("Index");
return;
} }
} }
} }

View File

@ -1,10 +1,19 @@
using PlumbingRepairClientApp;
using UniversityBusinessLogic.OfficePackage;
using UniversityBusinessLogic.OfficePackage.Implements;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
// Add services to the container. // Add services to the container.
builder.Services.AddControllersWithViews(); builder.Services.AddControllersWithViews();
builder.Services.AddTransient<AbstractSaveToExcelWorker, SaveToExcelWorker>();
builder.Services.AddTransient<AbstractSaveToWordWorker, SaveToWordWorker>();
builder.Services.AddTransient<AbstractSaveToPdfWorker, SaveToPdfWorker>();
var app = builder.Build(); var app = builder.Build();
APIClient.Connect(builder.Configuration);
// Configure the HTTP request pipeline. // Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment()) if (!app.Environment.IsDevelopment())
{ {

View File

@ -11,9 +11,11 @@
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\UniversityBusinessLogic\UniversityBusinessLogic.csproj" />
<ProjectReference Include="..\UniversityDatabaseImplement\UniversityDatabaseImplement.csproj" /> <ProjectReference Include="..\UniversityDatabaseImplement\UniversityDatabaseImplement.csproj" />
<ProjectReference Include="..\UniversityDataModels\UniversityDataModels.csproj" /> <ProjectReference Include="..\UniversityDataModels\UniversityDataModels.csproj" />
</ItemGroup> </ItemGroup>

View File

@ -1,34 +1,40 @@
@{ @using UniversityContracts.ViewModels
ViewData["Title"] = "Manage Attestations"; @model List<AttestationViewModel>
@{
ViewData["Title"] = "Управление аттестациями";
} }
<div class="text-center"> <div class="text-center">
<h2 class="display-4">@ViewData["Title"]</h2> <h2 class="display-4">@ViewData["Title"]</h2>
</div> </div>
<form method="post"> <form asp-action="CreateAttestation" method="post">
<div class="row"> <div class="row">
<div class="col-4">Form Of Evaluation:</div> <div class="col-4">Форма оценивания:</div>
<div class="col-8"> <div class="col-8">
<input type="text" name="formOfEvaluation" id="formOfEvaluation" class="form-control" /> <select name="formOfEvaluation" id="formOfEvaluation" class="form-control">
<option value="Зачёт">Зачёт</option>
<option value="Экзамен">Экзамен</option>
<option value="Дифферинцируемый зачёт">Дифферинцируемый зачёт</option>
</select>
</div> </div>
</div> </div>
<div class="row"> <div class="row">
<div class="col-4">Student:</div> <div class="col-4">Студент:</div>
<div class="col-8"> <div class="col-8">
<select name="student" id="student" class="form-control" multiple asp-items="ViewBag.Students"></select> <select name="student" id="student" class="form-control" asp-items="@(new SelectList(ViewBag.Students, "Id", "Name"))"></select>
</div> </div>
</div> </div>
<div class="row"> <div class="row">
<div class="col-4">Score:</div> <div class="col-4">Оценка:</div>
<div class="col-8"> <div class="col-8">
<select id="score" name="score" class="form-control" asp-items="@(new SelectList(ViewBag.AttestationScore, "Score"))"></select> <select id="score" name="score" class="form-control" asp-items="@(new SelectList(ViewBag.AttestationScore, "Score"))"></select>
</div> </div>
</div> </div>
<div class="row"> <div class="row">
<div class="col-8"></div> <div class="col-8"></div>
<div class="col-4"> <div class="col-4 mt-2">
<input type="submit" value="Create Attestation" class="btn btn-primary" /> <input type="submit" value="Добавить аттестацию" class="btn btn-primary" />
</div> </div>
</div> </div>
</form> </form>
@ -36,32 +42,39 @@
<table class="table"> <table class="table">
<thead> <thead>
<tr> <tr>
<th>Form Of Evaluation</th> <th>Id</th>
<th>Student</th> <th>Форма оценивания</th>
<th>Score</th> <th>Студент</th>
<th>Actions</th> <th>Оценка</th>
<th>Действия</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@* @foreach (var discipline in Model) @foreach (var attestation in Model)
{ {
<tr> <tr>
<td>@discipline.Name</td>
<td>@discipline.Description</td>
<td> <td>
@foreach (var student in discipline.Students) @Html.DisplayFor(modelItem => attestation.Id)
{
<span>@student.Name</span>
}
</td> </td>
<td> <td>
<a asp-action="Edit" asp-route-id="@discipline.Id" class="btn btn-warning">Edit</a> @Html.DisplayFor(modelItem => attestation.FormOfEvaluation)
<a asp-action="Details" asp-route-id="@discipline.Id" class="btn btn-info">Details</a> </td>
<a asp-action="Delete" asp-route-id="@discipline.Id" class="btn btn-danger">Delete</a> <td>
@Html.DisplayFor(modelItem => attestation.StudentName)
</td>
<td>
@Html.DisplayFor(modelItem => attestation.Score)
</td>
<td>
<div class="btn-group">
<a asp-controller="Home" asp-action="InfoAttestation" asp-route-id="@attestation.Id" class="btn btn-warning">Изменить</a>
<form asp-controller="Home" asp-action="DeleteAttestation" method="post">
<input type="hidden" name="id" value="@attestation.Id" />
<button type="submit" class="btn btn-danger">Удалить</button>
</form>
</div>
</td> </td>
</tr> </tr>
} *@ }
</tbody> </tbody>
</table> </table>

View File

@ -5,16 +5,16 @@
<h2 class="display-4">Вход в приложение</h2> <h2 class="display-4">Вход в приложение</h2>
</div> </div>
<form method="post"> <form method="post">
<div class="row"> <div class="row">
<div class="col-4">Логин:</div> <div class="col-4">Логин:</div>
<div class="col-8"><input type="text" name="login" /></div> <div class="col-8"><input type="text" name="login" /></div>
</div> </div>
<div class="row"> <div class="row">
<div class="col-4">Пароль:</div> <div class="col-4">Пароль:</div>
<div class="col-8"><input type="password" name="password" /></div> <div class="col-8"><input type="password" name="password" /></div>
</div> </div>
<div class="row"> <div class="row">
<div class="col-8"></div> <div class="col-8"></div>
<div class="col-4"><input type="submit" value="Вход" class="btn btnprimary" /></div> <div class="col-4"><input type="submit" value="Вход" class="btn btn-primary" /></div>
</div> </div>
</form> </form>

View File

@ -1,15 +1,89 @@
@{ @using UniversityContracts.ViewModels
ViewData["Title"] = "Home Page"; @model List<PlanOfStudyViewModel>
@{
ViewData["Title"] = "Управление планами обучений";
} }
<div class="text-center"> <div class="text-center">
<h2 class="display-4">@ViewData["Title"]</h2>
<div class="menu">
<a href="/Home/Students">Студенты</a>
<a href="/Home/PlanOfStudys">Планы обучения</a>
<a href="/Home/Attestations">Аттестации</a>
</div>
<div class="header">
<img src="" alt="Logo" class="logo">
</div>
</div> </div>
<div class="btn-group">
<form asp-action="ReportPlanOfStudys" method="get">
<input type="submit" value="Отчёт по планам обучения" class="btn btn-info" />
</form>
<form asp-action="ReportPlanOfStudyAndStudents" method="get">
<input type="submit" value="Сведения по планам обучения" class="btn btn-secondary" />
</form>
</div>
<form asp-action="CreatePlanOfStudy" method="post">
<div class="row mt-2">
<div class="col-4">Профиль:</div>
<div class="col-8">
<input type="text" name="profile" id="profile" class="form-control" />
</div>
</div>
<div class="row">
<div class="col-4">Форма обучения:</div>
<div class="col-8">
<input name="formOfStudy" id="formOfStudy" class="form-control" multiple asp-items="ViewBag.PlanOfStudys"></input>
</div>
</div>
<div class="row">
<div class="col-4">Преподаватели:</div>
<div class="col-8">
<div class="scrollable-list">
@foreach (var teacher in ViewBag.Teachers)
{
<div class="form-check">
<input class="form-check-input" type="checkbox" name="teacherIds" value="@teacher.Id" id="student-@teacher.Id">
<label class="form-check-label" for="teacher-@teacher.Id">
@teacher.Name
</label>
</div>
}
</div>
</div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4 mt-2">
<input type="submit" value="Создать план обучения" class="btn btn-primary" />
</div>
</div>
</form>
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>Профиль</th>
<th>Форма обучения</th>
<th>Действия</th>
</tr>
</thead>
<tbody>
@foreach (var planOfStudy in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => planOfStudy.Id)
</td>
<td>
@Html.DisplayFor(modelItem => planOfStudy.Profile)
</td>
<td>
@Html.DisplayFor(modelItem => planOfStudy.FormOfStudy)
</td>
<td>
<div class="btn-group">
<a asp-controller="Home" asp-action="InfoPlanOfStudy" asp-route-id="@planOfStudy.Id" class="btn btn-warning">Изменить</a>
<form asp-controller="Home" asp-action="DeletePlanOfStudy" method="post">
<input type="hidden" name="id" value="@planOfStudy.Id" />
<button type="submit" class="btn btn-danger">Удалить</button>
</form>
</div>
</td>
</tr>
}
</tbody>
</table>

View File

@ -0,0 +1,42 @@
@using UniversityContracts.ViewModels
@model AttestationViewModel
@{
ViewData["Title"] = "Аттестация";
}
<div class="text-center">
<h2 class="display-4">@ViewData["Title"] - @Model.Id</h2>
</div>
<form asp-action="UpdateAttestation" method="post">
<div class="row">
<div class="col-4">Форма оценивания:</div>
<div class="col-8">
<select name="formOfEvaluation" id="formOfEvaluation" class="form-control" value="@Model.FormOfEvaluation">
<option value="Зачёт">Зачёт</option>
<option value="Экзамен">Экзамен</option>
<option value="Дифферинцируемый зачёт">Дифферинцируемый зачёт</option>
</select>
</div>
</div>
<div class="row">
<div class="col-4">Студент:</div>
<div class="col-8">
<select name="student" id="student" class="form-control" asp-items="@(new SelectList(ViewBag.Students, "Id", "Name", Model.StudentId))"></select>
</div>
</div>
<div class="row">
<div class="col-4">Оценка:</div>
<div class="col-8">
<select id="score" name="score" class="form-control" asp-items="@(new SelectList(ViewBag.AttestationScore, "Score"))"></select>
</div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4 mt-2">
<form asp-action="Attestations">
<input type="submit" value="Отмена" class="btn btn-primary" />
</form>
<input type="hidden" name="id" value="@Model.Id" />
<input type="submit" value="Сохранить" class="btn btn-danger" />
</div>
</div>
</form>

View File

@ -0,0 +1,43 @@
@using UniversityContracts.ViewModels
@model PlanOfStudyViewModel
@{
ViewData["Title"] = "План обучения";
}
<div class="text-center">
<h2 class="display-4">@ViewData["Title"] - @Model.Id</h2>
</div>
<form asp-action="UpdatePlanOfStudy" method="post">
<div class="row">
<div class="col-4">Профиль:</div>
<div class="col-8"><input type="text" name="profile" value="@Model.Profile" /></div>
</div>
<div class="row">
<div class="col-4">Форма обучения:</div>
<div class="col-8"><input type="text" name="formOfStudy" value="@Model.FormOfStudy" /></div>
</div>
<div class="row">
<div class="col-4">Преподаватели:</div>
<div class="col-8">
@foreach (var teacher in ViewBag.Teachers)
{
<div class="form-check">
<input class="form-check-input" type="checkbox" name="teacherIds" value="@teacher.Id" id="teacher-@teacher.Id"
checked="@(Model.PlanOfStudyTeachers.ContainsKey(teacher.Id))">
<label class="form-check-label" for="teacher-@teacher.Id">
@teacher.Name
</label>
</div>
}
</div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4">
<form asp-action="Index">
<input type="submit" value="Отмена" class="btn btn-primary" />
</form>
<input type="hidden" name="id" value="@Model.Id" />
<input type="submit" value="Сохранить" class="btn btn-danger" />
</div>
</div>
</form>

View File

@ -0,0 +1,39 @@
@using UniversityContracts.ViewModels
@model StudentViewModel
@{
ViewData["Title"] = "Студент";
}
<div class="text-center">
<h2 class="display-4">@ViewData["Title"] - @Model.Id</h2>
</div>
<form asp-action="UpdateStudent" method="post">
<div class="row">
<div class="col-4">ФИО:</div>
<div class="col-8">
<input type="text" name="name" id="name" class="form-control" value="@Model.Name" />
</div>
</div>
<div class="row">
<div class="col-4">План обучения:</div>
<div class="col-8">
<select name="planOfStudy" id="planOfStudy" class="form-control" asp-items="@(new SelectList(ViewBag.PlanOfStudys, "Id", "Profile", Model.PlanOfStudyId))"></select>
</div>
</div>
<div class="row">
<div class="col-4">Номер телефона:</div>
<div class="col-8">
<input id="phoneNumber" name="phoneNumber" class="form-control" value="@Model.PhoneNumber"></input>
</div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4 mt-2">
<form asp-action="Students">
<input type="submit" value="Отмена" class="btn btn-primary" />
</form>
<input type="hidden" name="id" value="@Model.Id" />
<input type="submit" value="Сохранить" class="btn btn-danger" />
</div>
</div>
</form>

View File

@ -1,60 +0,0 @@
@{
ViewData["Title"] = "Manage PlansOfStudys";
}
<div class="text-center">
<h2 class="display-4">@ViewData["Title"]</h2>
</div>
<form method="post">
<div class="row">
<div class="col-4">Profile:</div>
<div class="col-8">
<input type="text" name="profile" id="profile" class="form-control" />
</div>
</div>
<div class="row">
<div class="col-4">FormOfStudy:</div>
<div class="col-8">
<input name="formOfStudy" id="formOfStudy" class="form-control" multiple asp-items="ViewBag.PlanOfStudys"></input>
</div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4">
<input type="submit" value="Create Student" class="btn btn-primary" />
</div>
</div>
</form>
<table class="table">
<thead>
<tr>
<th>Profile</th>
<th>FormOfStudy</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
@* @foreach (var discipline in Model)
{
<tr>
<td>@discipline.Name</td>
<td>@discipline.Description</td>
<td>
@foreach (var student in discipline.Students)
{
<span>@student.Name</span>
}
</td>
<td>
<a asp-action="Edit" asp-route-id="@discipline.Id" class="btn btn-warning">Edit</a>
<a asp-action="Details" asp-route-id="@discipline.Id" class="btn btn-info">Details</a>
<a asp-action="Delete" asp-route-id="@discipline.Id" class="btn btn-danger">Delete</a>
</td>
</tr>
} *@
</tbody>
</table>

View File

@ -1,6 +1,26 @@
@{ @using UniversityContracts.ViewModels
@model UserViewModel
@{
ViewData["Title"] = "Privacy Policy"; ViewData["Title"] = "Privacy Policy";
} }
<h1>@ViewData["Title"]</h1> <div class="text-center">
<h2 class="display-4">Личные данные</h2>
<p>Use this page to detail your site's privacy policy.</p> </div>
<form method="post">
<div class="row">
<div class="col-4">Логин:</div>
<div class="col-8"><input type="text" name="login" value="@Model.Login" /></div>
</div>
<div class="row">
<div class="col-4">Пароль:</div>
<div class="col-8"><input type="password" name="password" value="@Model.Password" /></div>
</div>
<div class="row">
<div class="col-4">E-mail:</div>
<div class="col-8"><input type="text" name="email" value="@Model.Email" /></div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4"><input type="submit" value="Сохранить" class="btn btn-primary" /></div>
</div>
</form>

View File

@ -5,33 +5,21 @@
<h2 class="display-4">Регистрация</h2> <h2 class="display-4">Регистрация</h2>
</div> </div>
<form method="post"> <form method="post">
<div class="row">
<div class="col-4">Логин:</div>
<div class="col-8"><input type="text" name="email" /></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-4">Фамилия:</div>
<div class="col-8"><input type="text" name="lastName" /></div>
</div>
<div class="row"> <div class="row">
<div class="col-4">Имя:</div> <div class="col-4">Логин:</div>
<div class="col-8"><input type="text" name="firstName" /></div> <div class="col-8"><input type="text" name="login" /></div>
</div> </div>
<div class="row"> <div class="row">
<div class="col-4">Отчество:</div> <div class="col-4">Почта:</div>
<div class="col-8"><input type="text" name="midleName" /></div> <div class="col-8"><input type="text" name="email" /></div>
</div> </div>
<div class="row"> <div class="row">
<div class="col-4">Телефон:</div> <div class="col-4">Пароль:</div>
<div class="col-8"><input type="text" name="phoneNumber" /></div> <div class="col-8"><input type="password" name="password" /></div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4"><input type="submit" value="Регистрация"
class="btn btn-primary" /></div>
</div> </div>
<div class="row">
<div class="col-8"></div>
<div class="col-4"><input type="submit" value="Регистрация"
class="btn btn-primary" /></div>
</div>
</form> </form>

View File

@ -0,0 +1,62 @@
@using UniversityContracts.ViewModels
@model List<ReportPlanOfStudyAndStudentViewModel>
@{
ViewData["Title"] = "Сведения по планам обучения";
}
<div class="text-center">
<h2 class="display-4">@ViewData["Title"]</h2>
</div>
<form method="post">
<div class="row">
<div class="col-8"></div>
<div class="col-4 mt-2">
<form method="post">
<input type="hidden" name="type" value="pdf" />
<input type="submit" value="Отправить в формате Pdf на почту" class="btn btn-secondary" />
</form>
</div>
<div class="col-4 mt-2">
</div>
</div>
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>План обучения</th>
<th>Студенты</th>
<th>Дисциплины</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Id)
</td>
<td>
@Html.DisplayFor(modelItem => item.PlanOfStudyName)
</td>
<td>
@foreach (var student in item.StudentName)
{
<div>
@Html.DisplayFor(modelItem => student)
</div>
}
</td>
<td>
@foreach (var discipline in item.DisciplineName)
{
<div>
@Html.DisplayFor(modelItem => discipline)
</div>
}
</td>
</tr>
}
</tbody>
</table>
</form>

View File

@ -0,0 +1,62 @@
@using UniversityContracts.ViewModels
@model List<ReportPlanOfStudyViewModel>
@{
ViewData["Title"] = "Отчёт по планам обучения";
}
<div class="text-center">
<h2 class="display-4">@ViewData["Title"]</h2>
</div>
<form method="post">
<div class="row">
<div class="col-8 btn-group"></div>
<div class="col-4 mt-2">
<form method="post">
<input type="hidden" name="type" value="docx" />
<input type="submit" value="Сохранить в формате Word" class="btn btn-primary" />
</form>
<form method="post">
<input type="hidden" name="type" value="xlsx" />
<input type="submit" value="Сохранить в формате Excel" class="btn btn-success" />
</form>
</div>
<div class="col-4 mt-2">
</div>
</div>
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>План обучения</th>
<th>Форма обучения</th>
<th>Дисциплины</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Id)
</td>
<td>
@Html.DisplayFor(modelItem => item.PlanOfStudyName)
</td>
<td>
@Html.DisplayFor(modelItem => item.FormOfStudy)
</td>
<td>
@foreach (var discipline in item.Disciplines)
{
<div>
@Html.DisplayFor(modelItem => discipline)
</div>
}
</td>
</tr>
}
</tbody>
</table>
</form>

View File

@ -1,34 +1,36 @@
@{ @using UniversityContracts.ViewModels
ViewData["Title"] = "Manage Students"; @model List<StudentViewModel>
@{
ViewData["Title"] = "Управление студентами";
} }
<div class="text-center"> <div class="text-center">
<h2 class="display-4">@ViewData["Title"]</h2> <h2 class="display-4">@ViewData["Title"]</h2>
</div> </div>
<form method="post"> <form asp-action="CreateStudent" method="post">
<div class="row"> <div class="row">
<div class="col-4">Name:</div> <div class="col-4">ФИО:</div>
<div class="col-8"> <div class="col-8">
<input type="text" name="name" id="name" class="form-control" /> <input type="text" name="name" id="name" class="form-control" />
</div> </div>
</div> </div>
<div class="row"> <div class="row">
<div class="col-4">Plan Of Study:</div> <div class="col-4">План обучения:</div>
<div class="col-8"> <div class="col-8">
<select name="planOfStudy" id="planOfStudy" class="form-control" multiple asp-items="ViewBag.PlanOfStudys"></select> <select name="planOfStudy" id="planOfStudy" class="form-control" asp-items="@(new SelectList(ViewBag.PlanOfStudys, "Id", "Profile"))"></select>
</div> </div>
</div> </div>
<div class="row"> <div class="row">
<div class="col-4">Phone number:</div> <div class="col-4">Номер телефона:</div>
<div class="col-8"> <div class="col-8">
<textarea id="phoneNumber" name="phoneNumber" class="form-control"></textarea> <input id="phoneNumber" name="phoneNumber" class="form-control"></input>
</div> </div>
</div> </div>
<div class="row"> <div class="row">
<div class="col-8"></div> <div class="col-8"></div>
<div class="col-4"> <div class="col-4 mt-2">
<input type="submit" value="Create Student" class="btn btn-primary" /> <input type="submit" value="Добавить студента" class="btn btn-primary" />
</div> </div>
</div> </div>
</form> </form>
@ -36,31 +38,40 @@
<table class="table"> <table class="table">
<thead> <thead>
<tr> <tr>
<th>Name</th> <th>Id</th>
<th>Plan of study</th> <th>ФИО</th>
<th>Phone number</th> <th>План обучения</th>
<th>Actions</th> <th>Номер телефона</th>
<th>Действия</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@* @foreach (var discipline in Model) @foreach (var student in Model)
{ {
<tr> <tr>
<td>@discipline.Name</td>
<td>@discipline.Description</td>
<td> <td>
@foreach (var student in discipline.Students) @Html.DisplayFor(modelItem => student.Id)
{
<span>@student.Name</span>
}
</td> </td>
<td> <td>
<a asp-action="Edit" asp-route-id="@discipline.Id" class="btn btn-warning">Edit</a> @Html.DisplayFor(modelItem => student.Name)
<a asp-action="Details" asp-route-id="@discipline.Id" class="btn btn-info">Details</a> </td>
<a asp-action="Delete" asp-route-id="@discipline.Id" class="btn btn-danger">Delete</a> <td>
@Html.DisplayFor(modelItem => student.PlanOfStudyProfile)
</td>
<td>
@Html.DisplayFor(modelItem => student.PhoneNumber)
</td>
<td>
<div class="btn-group">
<a asp-controller="Home" asp-action="InfoStudent" asp-route-id="@student.Id" class="btn btn-warning">Изменить</a>
<form asp-controller="Home" asp-action="DeleteStudent" method="post">
<input type="hidden" name="id" value="@student.Id" />
<button type="submit" class="btn btn-danger">Удалить</button>
</form>
</div>
</td> </td>
</tr> </tr>
} *@ }
</tbody> </tbody>
</table> </table>

View File

@ -20,10 +20,22 @@
<div class="navbar-collapse collapse d-sm-inline-flex justify-content-between"> <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
<ul class="navbar-nav flex-grow-1"> <ul class="navbar-nav flex-grow-1">
<li class="nav-item"> <li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a> <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Планы обучения</a>
</li> </li>
<li class="nav-item"> <li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a> <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Личные данные</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Students">Студенты</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Attestations">Аттестация</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Enter">Вход</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Register">Регистрация</a>
</li> </li>
</ul> </ul>
</div> </div>

View File

@ -5,5 +5,7 @@
"Microsoft.AspNetCore": "Warning" "Microsoft.AspNetCore": "Warning"
} }
}, },
"AllowedHosts": "*" "AllowedHosts": "*",
"IPAddress": "http://localhost:5032/"
} }

View File

@ -15,5 +15,6 @@ namespace UniversityContracts.BindingModels
public string FormOfEvaluation { get; set; } = string.Empty; public string FormOfEvaluation { get; set; } = string.Empty;
public AttestationScore Score { get; set; } = AttestationScore.Неявка; public AttestationScore Score { get; set; } = AttestationScore.Неявка;
public int StudentId { get; set; } public int StudentId { get; set; }
public string StudentName { get; set; } = string.Empty;
} }
} }

View File

@ -15,6 +15,7 @@ namespace UniversityContracts.BindingModels
public int TeacherId { get; set; } public int TeacherId { get; set; }
public string Name { get; set; } = string.Empty; public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty; public string Description { get; set; } = string.Empty;
public DateOnly Date { get; set; } = DateOnly.FromDateTime(DateTime.Now);
public Dictionary<int, IStudentModel> StudentDisciplines { get; set; } = new(); public Dictionary<int, IStudentModel> StudentDisciplines { get; set; } = new();
} }
} }

View File

@ -0,0 +1,18 @@
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; }
public string PopHost { get; set; } = string.Empty;
public int PopPort { get; set; }
}
}

View File

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

View File

@ -10,7 +10,6 @@ namespace UniversityContracts.BindingModels
{ {
public string? FileName { get; set; } public string? FileName { get; set; }
public Stream? Stream { get; set; } public Stream? Stream { get; set; }
public DateOnly DateFrom { get; set; } public DateOnly DateFrom { get; set; }
public DateOnly DateTo { get; set; } public DateOnly DateTo { get; set; }
} }

View File

@ -14,6 +14,6 @@ namespace UniversityContracts.BindingModels
public int UserId { get; set; } public int UserId { get; set; }
public int TeacherId { get; set; } public int TeacherId { get; set; }
public string Name { get; set; } = string.Empty; public string Name { get; set; } = string.Empty;
public DateTime Date { get; } public DateTime Date { get; set; }
} }
} }

View File

@ -7,6 +7,7 @@ namespace UniversityContracts.BindingModels
public int Id { get; set; } public int Id { get; set; }
public int UserId { get; set; } public int UserId { get; set; }
public int PlanOfStudyId { get; set; } public int PlanOfStudyId { get; set; }
public string PlanOfStudyProfile { get; set; } = string.Empty;
public string Name { get; set; } = string.Empty; public string Name { get; set; } = string.Empty;
public string PhoneNumber { get; set; } = string.Empty; public string PhoneNumber { get; set; } = string.Empty;
} }

View File

@ -12,7 +12,6 @@ namespace UniversityContracts.BindingModels
{ {
public int Id { get; set; } public int Id { get; set; }
public int UserId { get; set; } public int UserId { get; set; }
public int StorekeeperId { get; set; }
public string Name { get; set; } = string.Empty; public string Name { get; set; } = string.Empty;
public string AcademicDegree { get; set; } = string.Empty; public string AcademicDegree { get; set; } = string.Empty;
public string Position { get; set; } = string.Empty; public string Position { get; set; } = string.Empty;

View File

@ -12,15 +12,10 @@ namespace UniversityContracts.BusinessLogicsContracts
public interface IAttestationLogic public interface IAttestationLogic
{ {
List<AttestationViewModel>? ReadList(AttestationSearchModel? model); List<AttestationViewModel>? ReadList(AttestationSearchModel? model);
AttestationViewModel? ReadElement(AttestationSearchModel model);
bool CreateAttestation(AttestationBindingModel model); bool CreateAttestation(AttestationBindingModel model);
bool DeleteAttestation(AttestationBindingModel model); bool DeleteAttestation(AttestationBindingModel model);
bool UpdateAttestation(AttestationBindingModel model); bool UpdateAttestation(AttestationBindingModel model);
bool SetPass(AttestationBindingModel model);
bool SetNotPass(AttestationBindingModel model);
bool SetTwo(AttestationBindingModel model);
bool SetThree(AttestationBindingModel model);
bool SetFour(AttestationBindingModel model);
bool SetFive(AttestationBindingModel model);
} }
} }

View File

@ -1,10 +1,10 @@
using AbstractLawFirmContracts.ViewModels; using System;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using UniversityContracts.BindingModels; using UniversityContracts.BindingModels;
using UniversityContracts.ViewModels;
namespace UniversityContracts.BusinessLogicContracts namespace UniversityContracts.BusinessLogicContracts
{ {
@ -15,12 +15,16 @@ namespace UniversityContracts.BusinessLogicContracts
/// </summary> /// </summary>
/// <param name="model"></param> /// <param name="model"></param>
/// <returns></returns> /// <returns></returns>
List<ReportTeacherViewModel> GetTeachers(); List<ReportTeacherViewModel> GetTeachers(int userId);
List<ReportDisciplineViewModel> GetDisciplines(ReportBindingModel model); List<ReportDisciplineViewModel> GetDisciplines(ReportDateRangeBindingModel model);
List<ReportPlanOfStudyViewModel> GetPlanOfStudyAndDisciplines(int userId);
List<ReportPlanOfStudyAndStudentViewModel> GetPlanOfStudyAndStudents();
void SaveTeachersToWord(ReportBindingModel option); void SaveTeachersToWord(ReportBindingModel option);
void SavePlanOfStudyToWord(ReportBindingModel option);
void SaveTeachersToExcel(ReportBindingModel option); void SaveTeachersToExcel(ReportBindingModel option);
void SavePlanOfStudyToExcel(ReportBindingModel option);
void SendDisciplinesToEmail(ReportDateRangeBindingModel option, string email); void SendDisciplinesToEmail(ReportDateRangeBindingModel option);
public void SendPlanOfStudyToEmail(ReportBindingModel option);
} }
} }

View File

@ -9,7 +9,7 @@ namespace UniversityContracts.SearchModels
public class AttestationSearchModel public class AttestationSearchModel
{ {
public int? Id { get; set; } public int? Id { get; set; }
public int UserId { get; set; } public int? UserId { get; set; }
public int? StudentId { get; set; } public int StudentId { get; set; }
} }
} }

View File

@ -17,5 +17,6 @@ namespace UniversityContracts.StorageContracts
PlanOfStudyViewModel? Insert(PlanOfStudyBindingModel model); PlanOfStudyViewModel? Insert(PlanOfStudyBindingModel model);
PlanOfStudyViewModel? Update(PlanOfStudyBindingModel model); PlanOfStudyViewModel? Update(PlanOfStudyBindingModel model);
PlanOfStudyViewModel? Delete(PlanOfStudyBindingModel model); PlanOfStudyViewModel? Delete(PlanOfStudyBindingModel model);
List<DisciplineViewModel> GetDisciplineFromStudentsFromPlanOfStudys(PlanOfStudySearchModel model);
} }
} }

View File

@ -14,6 +14,8 @@ namespace UniversityContracts.ViewModels
public int Id { get; set; } public int Id { get; set; }
public int UserId { get; set; } public int UserId { get; set; }
public int StudentId { get; set; } public int StudentId { get; set; }
[DisplayName("ФИО студента")]
public string StudentName { get; set; } = string.Empty;
[DisplayName("Форма оценивания")] [DisplayName("Форма оценивания")]
public string FormOfEvaluation { get; set; } = string.Empty; public string FormOfEvaluation { get; set; } = string.Empty;
[DisplayName("Оценка")] [DisplayName("Оценка")]

View File

@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks; using System.Threading.Tasks;
using UniversityDataModels.Models; using UniversityDataModels.Models;
@ -13,14 +14,24 @@ namespace UniversityContracts.ViewModels
public int Id { get; set; } public int Id { get; set; }
public int UserId { get; set; } public int UserId { get; set; }
public int TeacherId { get; set; } public int TeacherId { get; set; }
public string TeacherName { get; set; } = string.Empty;
[DisplayName("Название дисциплины")] [DisplayName("Название дисциплины")]
public string Name { get; set; } = string.Empty; public string Name { get; set; } = string.Empty;
[DisplayName("Описание дисциплины")] [DisplayName("Описание дисциплины")]
public string Description { get; set; } = string.Empty; public string Description { get; set; } = string.Empty;
[DisplayName("Дата cоздания")]
public DateOnly Date { get; set; } = DateOnly.FromDateTime(DateTime.Now);
public Dictionary<int, IStudentModel> StudentDisciplines public Dictionary<int, IStudentModel> StudentDisciplines
{ {
get; get;
set; set;
} = new(); } = new();
public DisciplineViewModel() { }
[JsonConstructor]
public DisciplineViewModel(Dictionary<int, StudentViewModel> disciplineStudents) {
this.StudentDisciplines = disciplineStudents.ToDictionary(x => x.Key, x => x.Value as IStudentModel);
}
} }
} }

View File

@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks; using System.Threading.Tasks;
using UniversityDataModels.Models; using UniversityDataModels.Models;
@ -12,7 +13,6 @@ namespace UniversityContracts.ViewModels
{ {
public int Id { get; set; } public int Id { get; set; }
public int UserId { get; set; } public int UserId { get; set; }
public int WorkerId { get; set; }
[DisplayName("Профиль")] [DisplayName("Профиль")]
public string Profile { get; set; } = string.Empty; public string Profile { get; set; } = string.Empty;
[DisplayName("Форма обучения")] [DisplayName("Форма обучения")]
@ -22,5 +22,13 @@ namespace UniversityContracts.ViewModels
get; get;
set; set;
} = new(); } = new();
public PlanOfStudyViewModel() { }
[JsonConstructor]
public PlanOfStudyViewModel(Dictionary<int, TeacherViewModel> planOfStudyTeachers)
{
this.PlanOfStudyTeachers = planOfStudyTeachers.ToDictionary(x => x.Key, x => x.Value as ITeacherModel);
}
} }
} }

View File

@ -4,7 +4,7 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace AbstractLawFirmContracts.ViewModels namespace UniversityContracts.ViewModels
{ {
public class ReportDisciplineViewModel public class ReportDisciplineViewModel
{ {

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UniversityContracts.ViewModels
{
public class ReportPlanOfStudyAndStudentViewModel
{
public int Id { get; set; }
public string PlanOfStudyName { get; set; } = string.Empty;
public List<string> StudentName { get; set; } = new();
public List<string> DisciplineName { 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.ViewModels
{
public class ReportPlanOfStudyViewModel
{
public int Id { get; set; }
public string PlanOfStudyName { get; set; } = string.Empty;
public string FormOfStudy { get; set; } = string.Empty;
public List<string> Disciplines { get; set; } = new();
}
}

View File

@ -4,11 +4,12 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace AbstractLawFirmContracts.ViewModels namespace UniversityContracts.ViewModels
{ {
public class ReportTeacherViewModel public class ReportTeacherViewModel
{ {
public int TeacherId { get; set; }
public string TeacherName { get; set; } = string.Empty; public string TeacherName { get; set; } = string.Empty;
public List<(string Student, string PhoneNumber)> Students { get; set; } = new(); public List<string> Students { get; set; } = new();
} }
} }

View File

@ -13,6 +13,7 @@ namespace UniversityContracts.ViewModels
public int Id { get; set; } public int Id { get; set; }
public int UserId { get; set; } public int UserId { get; set; }
public int TeacherId { get; set; } public int TeacherId { get; set; }
public string TeacherName { get; set; } = string.Empty;
[DisplayName("Название ведомости")] [DisplayName("Название ведомости")]
public string Name { get; set; } = string.Empty; public string Name { get; set; } = string.Empty;
[DisplayName("Дата оформления ведомости")] [DisplayName("Дата оформления ведомости")]

View File

@ -8,6 +8,8 @@ namespace UniversityContracts.ViewModels
public int Id { get; set; } public int Id { get; set; }
public int UserId { get; set; } public int UserId { get; set; }
public int PlanOfStudyId { get; set; } public int PlanOfStudyId { get; set; }
[DisplayName("Профиль")]
public string PlanOfStudyProfile { get; set; } = string.Empty;
[DisplayName("ФИО")] [DisplayName("ФИО")]
public string Name { get; set; } = string.Empty; public string Name { get; set; } = string.Empty;
[DisplayName("Номер Телефона")] [DisplayName("Номер Телефона")]

View File

@ -23,25 +23,25 @@ namespace UniversityDatabaseImplement.Implements
public List<AttestationViewModel> GetFilteredList(AttestationSearchModel model) public List<AttestationViewModel> GetFilteredList(AttestationSearchModel model)
{ {
using var context = new UniversityDatabase(); if (model == null)
if (model.Id.HasValue)
{ {
return context.Attestations return new();
.Include(x => x.Student)
.Where(x => x.Id == model.Id)
.Select(x => x.GetViewModel)
.ToList();
}
else if (model.StudentId.HasValue)
{
return context.Attestations
.Include(x => x.Student)
.Where(x => x.StudentId == model.StudentId)
.Select(x => x.GetViewModel)
.ToList();
} }
return new(); using var context = new UniversityDatabase();
var query = context.Attestations
.Include(x => x.Student)
.ThenInclude(s => s.User)
.Include(x => x.User)
.AsQueryable();
if (model.UserId.HasValue)
{
query = query.Where(x => x.UserId == model.UserId.Value);
}
return query.Select(x => x.GetViewModel).ToList();
} }
public AttestationViewModel? GetElement(AttestationSearchModel model) public AttestationViewModel? GetElement(AttestationSearchModel model)

View File

@ -94,11 +94,24 @@ namespace UniversityDatabaseImplement.Implements
query = query.Where(x => x.TeacherId == model.TeacherId.Value); query = query.Where(x => x.TeacherId == model.TeacherId.Value);
} }
if (model.DateFrom.HasValue && model.DateTo.HasValue) if (model.DateFrom.HasValue && model.DateTo.HasValue)
{ {
query = query.Where(x => model.DateFrom.Value <= x.Date && x.Date <= model.DateTo.Value); //query = query.Where(x => model.DateFrom.Value <= x.Date && x.Date <= model.DateTo.Value);
}
var x = query.Select(x => x.GetViewModel).ToList();
var res = new List<DisciplineViewModel>();
foreach (var item in x) {
if (item.Date > model.DateFrom && item.Date < model.DateTo)
{
res.Add(item);
}
}
return res;
}
return query.Select(x => x.GetViewModel).ToList(); return query.Select(x => x.GetViewModel).ToList();
} }
@ -109,6 +122,7 @@ namespace UniversityDatabaseImplement.Implements
return context.Disciplines return context.Disciplines
.Include(x => x.Students) .Include(x => x.Students)
.ThenInclude(x => x.Student) .ThenInclude(x => x.Student)
.Include(x => x.Teacher)
.ToList() .ToList()
.Select(x => x.GetViewModel) .Select(x => x.GetViewModel)
.ToList(); .ToList();

View File

@ -18,21 +18,63 @@ namespace UniversityDatabaseImplement.Implements
{ {
using var context = new UniversityDatabase(); using var context = new UniversityDatabase();
return context.PlanOfStudys.Select(x => x.GetViewModel).ToList(); return context.PlanOfStudys
.Include(x => x.Teachers)
.ThenInclude(t => t.Teacher)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public List<DisciplineViewModel> GetDisciplineFromStudentsFromPlanOfStudys(PlanOfStudySearchModel model)
{
using var context = new UniversityDatabase();
var students = context.Students
.Where(s => s.PlanOfStudyId == model.Id)
.Include(s => s.StudentDiscipline)
.ThenInclude(sd => sd.Discipline)
.ToList();
if(students == null)
{
return new List<DisciplineViewModel>();
}
// Получаем список дисциплин, которые соответствуют условиям поиска в модели PlanOfStudySearchModel
var disciplines = students
.SelectMany(s => s.StudentDiscipline)
.Distinct()
.ToList();
if (disciplines == null)
{
return new List<DisciplineViewModel>();
}
// Преобразуем список дисциплин в список DisciplineViewModel и возвращаем его
return disciplines
.Select(d => d.Discipline.GetViewModel).ToList();
} }
public List<PlanOfStudyViewModel> GetFilteredList(PlanOfStudySearchModel model) public List<PlanOfStudyViewModel> GetFilteredList(PlanOfStudySearchModel model)
{ {
if(model == null)
{
return new();
}
using var context = new UniversityDatabase(); using var context = new UniversityDatabase();
var query = context.PlanOfStudys
.Include(x => x.Teachers)
.ThenInclude(x => x.Teacher)
.Include(x => x.Students)
.Include(x => x.User)
.AsQueryable();
if (model.Id.HasValue) if (model.Id.HasValue)
{ {
return context.PlanOfStudys query = query.Where(x => x.Id == model.Id.Value);
.Include(x => x.Students)
.Where(x => x.Id == model.Id)
.Select(x => x.GetViewModel)
.ToList();
} }
return new(); return query.Select(x => x.GetViewModel).ToList();
} }
public PlanOfStudyViewModel? GetElement(PlanOfStudySearchModel model) public PlanOfStudyViewModel? GetElement(PlanOfStudySearchModel model)
@ -42,7 +84,12 @@ namespace UniversityDatabaseImplement.Implements
return null; return null;
} }
using var context = new UniversityDatabase(); using var context = new UniversityDatabase();
return context.PlanOfStudys.Include(x => x.Profile).FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; return context.PlanOfStudys
.Include(x => x.User)
.Include(x => x.Teachers)
.ThenInclude(x => x.Teacher)
.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))?
.GetViewModel;
} }
public PlanOfStudyViewModel? Insert(PlanOfStudyBindingModel model) public PlanOfStudyViewModel? Insert(PlanOfStudyBindingModel model)
@ -64,14 +111,20 @@ namespace UniversityDatabaseImplement.Implements
public PlanOfStudyViewModel? Update(PlanOfStudyBindingModel model) public PlanOfStudyViewModel? Update(PlanOfStudyBindingModel model)
{ {
using var context = new UniversityDatabase(); using var context = new UniversityDatabase();
var order = context.PlanOfStudys.FirstOrDefault(x => x.Id == model.Id); var planOfStudy = context.PlanOfStudys.FirstOrDefault(x => x.Id == model.Id);
if (order == null) if (planOfStudy == null)
{ {
return null; return null;
} }
order.Update(model); planOfStudy.Update(model);
planOfStudy.UpdateTeachers(context, model);
context.SaveChanges(); context.SaveChanges();
return context.PlanOfStudys.Include(x => x.Profile).FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; return context.PlanOfStudys
.Include(x => x.User)
.Include(x => x.Teachers)
.ThenInclude(x => x.Teacher)
.FirstOrDefault(x => x.Id == model.Id)?
.GetViewModel;
} }
public PlanOfStudyViewModel? Delete(PlanOfStudyBindingModel model) public PlanOfStudyViewModel? Delete(PlanOfStudyBindingModel model)
{ {

View File

@ -26,16 +26,23 @@ namespace UniversityDatabaseImplement.Implements
public List<StatementViewModel> GetFilteredList(StatementSearchModel model) public List<StatementViewModel> GetFilteredList(StatementSearchModel model)
{ {
if (!model.Id.HasValue && !model.Date.HasValue)
{
return new();
}
using var context = new UniversityDatabase(); using var context = new UniversityDatabase();
return context.Statements
.Where(x => x.Id == model.Id || model.Date <= x.Date) // Фильтр по Id
.Include(x => x.Teacher) IQueryable<Statement> query = context.Statements;
.Select(x => x.GetViewModel) if (model.Id.HasValue)
.ToList(); {
query = query.Where(x => x.Id == model.Id.Value);
}
// Фильтр по Date
if (model.Date.HasValue)
{
query = query.Where(x => x.Date <= model.Date.Value);
}
// Загрузка связанных данных
return query.Include(x => x.Teacher).Select(x => x.GetViewModel).ToList();
} }
public List<StatementViewModel> GetFullList() public List<StatementViewModel> GetFullList()
@ -46,12 +53,12 @@ namespace UniversityDatabaseImplement.Implements
public StatementViewModel? Insert(StatementBindingModel model) public StatementViewModel? Insert(StatementBindingModel model)
{ {
var newStatement = Statement.Create(model); using var context = new UniversityDatabase();
var newStatement = Statement.Create(context, model);
if (newStatement == null) if (newStatement == null)
{ {
return null; return null;
} }
using var context = new UniversityDatabase();
context.Statements.Add(newStatement); context.Statements.Add(newStatement);
context.SaveChanges(); context.SaveChanges();
return context.Statements.Include(x => x.Teacher).FirstOrDefault(x => x.Id == newStatement.Id)?.GetViewModel; return context.Statements.Include(x => x.Teacher).FirstOrDefault(x => x.Id == newStatement.Id)?.GetViewModel;

View File

@ -1,4 +1,5 @@
using System; using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Linq; using System.Linq;
@ -24,14 +25,31 @@ namespace UniversityDatabaseImplement.Implements
public List<StudentViewModel> GetFilteredList(StudentSearchModel model) public List<StudentViewModel> GetFilteredList(StudentSearchModel model)
{ {
if (string.IsNullOrEmpty(model.Name)) if (model == null)
{ {
return new(); return new List<StudentViewModel>();
} }
using var context = new UniversityDatabase(); using var context = new UniversityDatabase();
return context.Students.Where(x => x.Name.Contains(model.Name)).Select(x => x.GetViewModel).ToList(); // Начальный запрос без фильтрации
var query = context.Students
.Include(x => x.User)
.Include(x => x.PlanOfStudy)
.AsQueryable();
// Если в модели поиска указан Id, добавляем условие фильтрации
if (model.Id.HasValue)
{
query = query.Where(x => x.Id == model.Id.Value);
}
// Выполняем запрос и получаем результаты
var results = query
.Select(x => x.GetViewModel)
.ToList();
return results;
} }
public StudentViewModel? GetElement(StudentSearchModel model) public StudentViewModel? GetElement(StudentSearchModel model)

View File

@ -23,11 +23,9 @@ namespace UniversityDatabaseImplement.Implements
} }
public List<TeacherViewModel> GetFilteredList(TeacherSearchModel model) public List<TeacherViewModel> GetFilteredList(TeacherSearchModel model)
{ {
if (string.IsNullOrEmpty(model.Name) || string.IsNullOrEmpty(model.AcademicDegree) || string.IsNullOrEmpty(model.Position))
{
return new();
}
using var context = new UniversityDatabase(); using var context = new UniversityDatabase();
if (!string.IsNullOrEmpty(model.Name) || !string.IsNullOrEmpty(model.AcademicDegree) || !string.IsNullOrEmpty(model.Position))
{
return context.Teachers return context.Teachers
.Where(x => x.Name.Contains(model.Name)) .Where(x => x.Name.Contains(model.Name))
.Where(x => x.Position.Contains(model.Position)) .Where(x => x.Position.Contains(model.Position))
@ -35,6 +33,13 @@ namespace UniversityDatabaseImplement.Implements
.Include(x => x.User) .Include(x => x.User)
.Select(x => x.GetViewModel) .Select(x => x.GetViewModel)
.ToList(); .ToList();
}
else { return context.Teachers.Include(x => x.User).Select(x => x.GetViewModel)
.ToList();
}
return new();
} }
public TeacherViewModel? GetElement(TeacherSearchModel model) public TeacherViewModel? GetElement(TeacherSearchModel model)
{ {
@ -49,12 +54,14 @@ namespace UniversityDatabaseImplement.Implements
} }
public TeacherViewModel? Insert(TeacherBindingModel model) public TeacherViewModel? Insert(TeacherBindingModel model)
{ {
var newTeacher = Teacher.Create(model); using var context = new UniversityDatabase();
var newTeacher = Teacher.Create(context, model);
if (newTeacher == null) if (newTeacher == null)
{ {
return null; return null;
} }
using var context = new UniversityDatabase();
context.Teachers.Add(newTeacher); context.Teachers.Add(newTeacher);
context.SaveChanges(); context.SaveChanges();
return newTeacher.GetViewModel; return newTeacher.GetViewModel;

View File

@ -30,16 +30,18 @@ namespace UniversityDatabaseImplement.Implements
} }
public UserViewModel? GetElement(UserSearchModel model) public UserViewModel? GetElement(UserSearchModel model)
{ {
if (string.IsNullOrEmpty(model.Login) && string.IsNullOrEmpty(model.Email) && !model.Id.HasValue) if (string.IsNullOrEmpty(model.Login) && string.IsNullOrEmpty(model.Password))
{ {
return null; return null;
} }
using var context = new UniversityDatabase(); using var context = new UniversityDatabase();
//Поиск пользователя при входе в систему по логину, паролю и его роли (чтобы не могли войти в аккаунты другой роли) //Поиск пользователя при входе в систему по логину, паролю и его роли (чтобы не могли войти в аккаунты другой роли)
// UPD По роли не ищется
if (!string.IsNullOrEmpty(model.Login) && !string.IsNullOrEmpty(model.Password) && model.Role.HasValue) if (!string.IsNullOrEmpty(model.Login) && !string.IsNullOrEmpty(model.Password) && model.Role.HasValue)
{ {
return context.Users.FirstOrDefault(x => x.Login == model.Login && x.Password == model.Password && x.Role == model.Role)?.GetViewModel;
return context.Users.FirstOrDefault(x => x.Login == model.Login && x.Password == model.Password)?.GetViewModel;
} }
//Получение по логину (пользователей с таким логином будет 1 или 0) //Получение по логину (пользователей с таким логином будет 1 или 0)
if (!string.IsNullOrEmpty(model.Login)) if (!string.IsNullOrEmpty(model.Login))

View File

@ -0,0 +1,467 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using UniversityDatabaseImplement;
#nullable disable
namespace UniversityDatabaseImplement.Migrations
{
[DbContext(typeof(UniversityDatabase))]
[Migration("20240518164251_newMigration")]
partial class newMigration
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.4")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("UniversityDatabaseImplement.Models.Attestation", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("FormOfEvaluation")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("Score")
.HasColumnType("int");
b.Property<int>("StudentId")
.HasColumnType("int");
b.Property<int>("UserId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("StudentId");
b.HasIndex("UserId");
b.ToTable("Attestations");
});
modelBuilder.Entity("UniversityDatabaseImplement.Models.Discipline", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<DateOnly>("Date")
.HasColumnType("date");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("TeacherId")
.HasColumnType("int");
b.Property<int>("UserId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("TeacherId");
b.HasIndex("UserId");
b.ToTable("Disciplines");
});
modelBuilder.Entity("UniversityDatabaseImplement.Models.PlanOfStudy", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<DateOnly>("Date")
.HasColumnType("date");
b.Property<string>("FormOfStudy")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Profile")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("UserId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("PlanOfStudys");
});
modelBuilder.Entity("UniversityDatabaseImplement.Models.PlanOfStudyTeacher", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("PlanOfStudyId")
.HasColumnType("int");
b.Property<int>("TeacherId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("PlanOfStudyId");
b.HasIndex("TeacherId");
b.ToTable("PlanOfStudyTeachers");
});
modelBuilder.Entity("UniversityDatabaseImplement.Models.Statement", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<DateTime>("Date")
.HasColumnType("datetime2");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("TeacherId")
.HasColumnType("int");
b.Property<int>("UserId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("TeacherId");
b.HasIndex("UserId");
b.ToTable("Statements");
});
modelBuilder.Entity("UniversityDatabaseImplement.Models.Student", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("PhoneNumber")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("PlanOfStudyId")
.HasColumnType("int");
b.Property<int>("UserId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("PlanOfStudyId");
b.HasIndex("UserId");
b.ToTable("Students");
});
modelBuilder.Entity("UniversityDatabaseImplement.Models.StudentDiscipline", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("DisciplineId")
.HasColumnType("int");
b.Property<int>("StudentId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("DisciplineId");
b.HasIndex("StudentId");
b.ToTable("StudentDisciplines");
});
modelBuilder.Entity("UniversityDatabaseImplement.Models.Teacher", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("AcademicDegree")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Position")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("UserId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("Teachers");
});
modelBuilder.Entity("UniversityDatabaseImplement.Models.User", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("Email")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Login")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("Role")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Users");
});
modelBuilder.Entity("UniversityDatabaseImplement.Models.Attestation", b =>
{
b.HasOne("UniversityDatabaseImplement.Models.Student", "Student")
.WithMany("Attestations")
.HasForeignKey("StudentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("UniversityDatabaseImplement.Models.User", "User")
.WithMany("Attestations")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Student");
b.Navigation("User");
});
modelBuilder.Entity("UniversityDatabaseImplement.Models.Discipline", b =>
{
b.HasOne("UniversityDatabaseImplement.Models.Teacher", "Teacher")
.WithMany("Disciplines")
.HasForeignKey("TeacherId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("UniversityDatabaseImplement.Models.User", "User")
.WithMany("Disciplines")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Teacher");
b.Navigation("User");
});
modelBuilder.Entity("UniversityDatabaseImplement.Models.PlanOfStudy", b =>
{
b.HasOne("UniversityDatabaseImplement.Models.User", "User")
.WithMany("PlanOfStudys")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("UniversityDatabaseImplement.Models.PlanOfStudyTeacher", b =>
{
b.HasOne("UniversityDatabaseImplement.Models.PlanOfStudy", "PlanOfStudy")
.WithMany("Teachers")
.HasForeignKey("PlanOfStudyId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("UniversityDatabaseImplement.Models.Teacher", "Teacher")
.WithMany("PlanOfStudyTeachers")
.HasForeignKey("TeacherId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("PlanOfStudy");
b.Navigation("Teacher");
});
modelBuilder.Entity("UniversityDatabaseImplement.Models.Statement", b =>
{
b.HasOne("UniversityDatabaseImplement.Models.Teacher", "Teacher")
.WithMany("Statements")
.HasForeignKey("TeacherId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("UniversityDatabaseImplement.Models.User", "User")
.WithMany("Statements")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Teacher");
b.Navigation("User");
});
modelBuilder.Entity("UniversityDatabaseImplement.Models.Student", b =>
{
b.HasOne("UniversityDatabaseImplement.Models.PlanOfStudy", "PlanOfStudy")
.WithMany("Students")
.HasForeignKey("PlanOfStudyId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("UniversityDatabaseImplement.Models.User", "User")
.WithMany("Students")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("PlanOfStudy");
b.Navigation("User");
});
modelBuilder.Entity("UniversityDatabaseImplement.Models.StudentDiscipline", b =>
{
b.HasOne("UniversityDatabaseImplement.Models.Discipline", "Discipline")
.WithMany("Students")
.HasForeignKey("DisciplineId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("UniversityDatabaseImplement.Models.Student", "Student")
.WithMany("StudentDiscipline")
.HasForeignKey("StudentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Discipline");
b.Navigation("Student");
});
modelBuilder.Entity("UniversityDatabaseImplement.Models.Teacher", b =>
{
b.HasOne("UniversityDatabaseImplement.Models.User", "User")
.WithMany("Teachers")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("UniversityDatabaseImplement.Models.Discipline", b =>
{
b.Navigation("Students");
});
modelBuilder.Entity("UniversityDatabaseImplement.Models.PlanOfStudy", b =>
{
b.Navigation("Students");
b.Navigation("Teachers");
});
modelBuilder.Entity("UniversityDatabaseImplement.Models.Student", b =>
{
b.Navigation("Attestations");
b.Navigation("StudentDiscipline");
});
modelBuilder.Entity("UniversityDatabaseImplement.Models.Teacher", b =>
{
b.Navigation("Disciplines");
b.Navigation("PlanOfStudyTeachers");
b.Navigation("Statements");
});
modelBuilder.Entity("UniversityDatabaseImplement.Models.User", b =>
{
b.Navigation("Attestations");
b.Navigation("Disciplines");
b.Navigation("PlanOfStudys");
b.Navigation("Statements");
b.Navigation("Students");
b.Navigation("Teachers");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,41 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace UniversityDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class newMigration : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<DateOnly>(
name: "Date",
table: "PlanOfStudys",
type: "date",
nullable: false,
defaultValue: new DateOnly(1, 1, 1));
migrationBuilder.AddColumn<DateOnly>(
name: "Date",
table: "Disciplines",
type: "date",
nullable: false,
defaultValue: new DateOnly(1, 1, 1));
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Date",
table: "PlanOfStudys");
migrationBuilder.DropColumn(
name: "Date",
table: "Disciplines");
}
}
}

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