using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Newtonsoft.Json; using SchoolAgainStudyBusinessLogic.MailWorker; using SchoolAgainStudyContracts.BindingModel; using SchoolAgainStudyContracts.BusinessLogicContracts; using SchoolAgainStudyContracts.SearchModel; using SchoolAgainStudyDataBaseImplements.Models; using SchoolAgainStudyDataModels.Models; using System.Diagnostics; using TeacherWebClient.Models; namespace TeacherWebClient.Controllers { public class HomeController : Controller { private readonly ILogger _logger; private readonly IProductLogic _product; private readonly ILessonLogic _lesson; private readonly ITaskLogic _task; private readonly IMaterialLogic _material; private readonly ITeacherLogic _teacher; private readonly IReportLogic _report; private readonly AbstractMailWorker mailSender; private readonly IChartLogic _chart; public HomeController(ILogger logger, IProductLogic product, ILessonLogic lesson, ITaskLogic task, IMaterialLogic material, ITeacherLogic teacher, IReportLogic report, AbstractMailWorker abstractMailWorker, IChartLogic chart) { _logger = logger; _product = product; _lesson = lesson; _task = task; _material = material; _teacher = teacher; _report = report; _chart = chart; try { mailSender = abstractMailWorker; mailSender?.MailConfig(new MailConfigBindingModel { MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty, MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty, SmtpClientHost = System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty, SmtpClientPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]), PopHost = System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty, PopPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"]) }); } catch (Exception ex) { logger?.LogError(ex, "Ошибка работы с почтой"); } } [HttpGet] public IActionResult Index() { if (APIClient.Teacher == null) { return Redirect("~/Home/Enter"); } return View(); } public IActionResult Privacy() { if (APIClient.Teacher == null) { return Redirect("~/Home/Enter"); } return View(APIClient.Teacher); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } [HttpPost] public void Privacy(string name, string post, string email, string login, string password) { if (APIClient.Teacher == null) { throw new Exception("Вы как суда попали? Суда вход только авторизованным"); } if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(name) || string.IsNullOrEmpty(email) || string.IsNullOrEmpty(post)) { throw new Exception("Введите данные"); } _teacher.Update(new TeacherBindingModel { Id = APIClient.Teacher.Id, Name = name, Email = email, Password = password, Login = login, Post = post }); APIClient.Teacher.Name = name; APIClient.Teacher.Email = email; APIClient.Teacher.Password = password; APIClient.Teacher.Login = login; APIClient.Teacher.Post = post; Response.Redirect("Index"); } [HttpGet] public IActionResult Enter() { return View(); } [HttpPost] public void Enter(string login, string password) { if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password)) { throw new Exception("Введите логин и пароль"); } APIClient.Teacher = _teacher.ReadElement(new TeacherSearchModel { Login = login, Password = password }); if (APIClient.Teacher == null) { throw new Exception("Неверный логин/пароль"); } Response.Redirect("Index"); } [HttpGet] public IActionResult Register() { return View(); } [HttpPost] public void Register(string name, string post, string email, string login, string password) { if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(name) || string.IsNullOrEmpty(email) || string.IsNullOrEmpty(post)) { throw new Exception("Введите ФИО, должность, почту, логин, пароль"); } _teacher.Create(new TeacherBindingModel { Name = name, Email = email, Password = password, Login = login, Post = post }); Response.Redirect("Enter"); return; } [HttpGet] public IActionResult Materials() { if (APIClient.Teacher == null) { return Redirect("~/Home/Enter"); } return View(_material.ReadList(new MaterialSearchModel { TeacherId = APIClient.Teacher.Id })); } [HttpGet] public IActionResult CreateMaterial() { return View(); } [HttpPost] public void CreateMaterial(string title, string sphereUse) { if (APIClient.Teacher == null) { throw new Exception("Вы как суда попали? Суда вход только авторизованным"); } if (string.IsNullOrEmpty(title) && string.IsNullOrEmpty(sphereUse)) { throw new Exception("Введите название и сферу использования"); } _material.Create(new MaterialBindingModel { TeacherId = APIClient.Teacher.Id, Title = title, SphereUse = sphereUse }); Response.Redirect("Materials"); } [HttpGet] public IActionResult MaterialSetting(int id) { return View(_material.ReadElement(new MaterialSearchModel { Id = id })); } [HttpPost] public void UpdateMaterial(int id, string name, string sph) { if (string.IsNullOrEmpty(name)) { throw new Exception("Нет названия"); } if (string.IsNullOrEmpty(sph)) { throw new Exception("Нет сферы применения"); } _material.Update(new MaterialBindingModel { Id = id, Title = name, SphereUse = sph, TeacherId = APIClient.Teacher.Id, }); Response.Redirect("/Home/Materials"); } public void DeleteMaterial(int id) { _material.Delete(new MaterialBindingModel { Id = id, }); Response.Redirect("/Home/Materials"); } [HttpGet] public IActionResult Lessons() { if (APIClient.Teacher == null) { return Redirect("~/Home/Enter"); } return View(_lesson.ReadList(new LessonSearchModel { TeacherId = APIClient.Teacher.Id })); } [HttpGet] public IActionResult CreateLesson() { ViewBag.Products = _product.ReadList(null); var list = _material.ReadList(new MaterialSearchModel { TeacherId = APIClient.Teacher.Id }); var simpMaterial = list.Select(x => new { MaterialId = x.Id, MaterialName = x.Title }); ViewBag.Materials = new MultiSelectList(simpMaterial, "MaterialId", "MaterialName"); return View(); } [HttpPost] public void CreateLesson(string title, string dateEvent, int product, int[] materials) { if (APIClient.Teacher == null) { throw new Exception("Вы как суда попали? Суда вход только авторизованным"); } if (string.IsNullOrEmpty(title) || string.IsNullOrEmpty(dateEvent) || product <= 0) { throw new Exception("Введите название и дату"); } Dictionary lessonMaterials = new Dictionary(); foreach (int id in materials) { lessonMaterials.Add(id, _material.ReadElement(new MaterialSearchModel { Id = id })); } _lesson.Create(new LessonBindingModel { TeacherId = APIClient.Teacher.Id, TeacherName = APIClient.Teacher.Name, Title = title, DateEvent = DateTime.SpecifyKind(DateTime.Parse(dateEvent), DateTimeKind.Utc), ProductId = product, ProductName = _product.ReadElement(new ProductSearchModel { Id = product }).Title, LessonMaterials = lessonMaterials }); Response.Redirect("Lessons"); } [HttpGet] public IActionResult LessonSetting(int id) { var lesson = _lesson.ReadElement(new LessonSearchModel { Id = id }); var materials = _material.ReadList(new MaterialSearchModel { TeacherId = APIClient.Teacher.Id }).Select(x => new { MaterialId = x.Id, MaterialName = x.Title }).ToList(); var selectedMaterials = lesson.LessonMaterials.Select(x => x.Key).ToArray(); ViewBag.Materials = new MultiSelectList(materials, "MaterialId", "MaterialName", selectedMaterials); ViewBag.Products = _product.ReadList(null); return View(lesson); } [HttpPost] public void UpdateLesson(int idLesson, string title, string dateEvent, int product, int[] materials) { if (string.IsNullOrEmpty(title)) { throw new Exception("Нет названия"); } if (string.IsNullOrEmpty(dateEvent)) { throw new Exception("Нет даты"); } if (product <= 0) { throw new Exception("Нет изделия"); } Dictionary lessonMaterials = new Dictionary(); foreach (int id in materials) { lessonMaterials.Add(id, _material.ReadElement(new MaterialSearchModel { Id = id })); } _lesson.Update(new LessonBindingModel { Id = idLesson, TeacherId = APIClient.Teacher.Id, TeacherName = APIClient.Teacher.Name, Title = title, DateEvent = DateTime.SpecifyKind(DateTime.Parse(dateEvent), DateTimeKind.Utc), ProductId = product, ProductName = _product.ReadElement(new ProductSearchModel { Id = product }).Title, LessonMaterials = lessonMaterials }); Response.Redirect("/Home/Lessons"); } public void DeleteLesson(int id) { _lesson.Delete(new LessonBindingModel { Id = id, }); Response.Redirect("/Home/Lessons"); } [HttpGet] public IActionResult Tasks() { if (APIClient.Teacher == null) { return Redirect("~/Home/Enter"); } return View(_task.ReadList(new TaskSearchModel { TeacherId = APIClient.Teacher.Id })); } [HttpGet] public IActionResult CreateTask() { var list = _material.ReadList(new MaterialSearchModel { TeacherId = APIClient.Teacher.Id }); var simpMaterial = list.Select(x => new { MaterialId = x.Id, MaterialName = x.Title }); ViewBag.Materials = new MultiSelectList(simpMaterial, "MaterialId", "MaterialName"); return View(); } [HttpPost] public void CreateTask(string title, string dateIssue, string dateDelivery, int[] materials) { if (APIClient.Teacher == null) { throw new Exception("Вы как суда попали? Суда вход только авторизованным"); } if (string.IsNullOrEmpty(title) && string.IsNullOrEmpty(dateIssue) || string.IsNullOrEmpty(dateDelivery)) { throw new Exception("Введите название и даты"); } if(DateTime.SpecifyKind(DateTime.Parse(dateIssue), DateTimeKind.Utc) >= DateTime.SpecifyKind(DateTime.Parse(dateDelivery), DateTimeKind.Utc)) { throw new Exception("Дата выдачи должна быть раньше срока сдачи"); } Dictionary taskMaterials = new Dictionary(); foreach (int id in materials) { taskMaterials.Add(id, _material.ReadElement(new MaterialSearchModel { Id = id })); } _task.Create(new TaskBindingModel { TeacherId = APIClient.Teacher.Id, TeacherName = APIClient.Teacher.Name, Title = title, DateIssue = DateTime.SpecifyKind(DateTime.Parse(dateIssue), DateTimeKind.Utc), DateDelivery = DateTime.SpecifyKind(DateTime.Parse(dateDelivery), DateTimeKind.Utc), TaskMaterials = taskMaterials }); Response.Redirect("Tasks"); } [HttpGet] public IActionResult TaskSetting(int id) { var task = _task.ReadElement(new TaskSearchModel { Id = id }); var materials = _material.ReadList(new MaterialSearchModel { TeacherId = APIClient.Teacher.Id }).Select(x => new { MaterialId = x.Id, MaterialName = x.Title }).ToList(); var selectedMaterials = task.TaskMaterials.Select(x => x.Key).ToArray(); ViewBag.Materials = new MultiSelectList(materials, "MaterialId", "MaterialName", selectedMaterials); return View(task); } [HttpPost] public void UpdateTask(int idTask, string title, string dateIssue, string dateDelivery, int[] materials) { if (string.IsNullOrEmpty(title)) { throw new Exception("Нет названия"); } if (string.IsNullOrEmpty(dateIssue)) { throw new Exception("Нет даты выдачи"); } if (string.IsNullOrEmpty(dateDelivery)) { throw new Exception("Нет срока сдачи"); } if (DateTime.SpecifyKind(DateTime.Parse(dateIssue), DateTimeKind.Utc) >= DateTime.SpecifyKind(DateTime.Parse(dateDelivery), DateTimeKind.Utc)) { throw new Exception("Дата выдачи должна быть раньше срока сдачи"); } Dictionary taskMaterials = new Dictionary(); foreach (int id in materials) { taskMaterials.Add(id, _material.ReadElement(new MaterialSearchModel { Id = id })); } _task.Update(new TaskBindingModel { Id = idTask, TeacherId = APIClient.Teacher.Id, TeacherName = APIClient.Teacher.Name, Title = title, DateIssue = DateTime.SpecifyKind(DateTime.Parse(dateIssue), DateTimeKind.Utc), DateDelivery = DateTime.SpecifyKind(DateTime.Parse(dateDelivery), DateTimeKind.Utc), TaskMaterials = taskMaterials }); Response.Redirect("/Home/Tasks"); } public void DeleteTask(int id) { _task.Delete(new TaskBindingModel { Id = id, }); Response.Redirect("/Home/Tasks"); } public IActionResult Reports() { var list = _material.ReadList(new MaterialSearchModel { TeacherId = APIClient.Teacher.Id }); var simpMaterial = list.Select(x => new { MaterialId = x.Id, MaterialName = x.Title }); ViewBag.Materials = new MultiSelectList(simpMaterial, "MaterialId", "MaterialName"); return View(); } public IActionResult GetPartial(int[] materials, string mode) { var list = materials.Select(x => _material.ReadElement(new MaterialSearchModel { Id = x })).ToList(); if (mode.Equals("Excel")) { _report.SaveDiyMaterialToExcelFile (new ReportBindingModel { FileName = $"C:\\Университет\\2 курс\\4 семестр\\РПП\\Курсач РПП\\Reports\\{APIClient.Teacher.Name}-{DateTime.Now.ToString("dd/MM/yyyy")}.xlsx", Materials = list, TeacherId = APIClient.Teacher.Id }); } else { _report.SaveDiyMaterialToWordFile (new ReportBindingModel { FileName = $"C:\\Университет\\2 курс\\4 семестр\\РПП\\Курсач РПП\\Reports\\{APIClient.Teacher.Name}-{DateTime.Now.ToString("dd/MM/yyyy")}.docx", Materials = list, TeacherId = APIClient.Teacher.Id }); } var items = _report.GetDiyMaterial(new ReportBindingModel { Materials = list, TeacherId = APIClient.Teacher.Id }); return PartialView("_DiyListPartial", items); } public IActionResult SendingEmail() { return View(); } public IActionResult GetPartialForPDF(string dateFrom, string dateTo) { var _dateFrom = DateTime.SpecifyKind(DateTime.Parse(dateFrom), DateTimeKind.Utc); var _dateTo = DateTime.SpecifyKind(DateTime.Parse(dateTo), DateTimeKind.Utc); if (_dateFrom > _dateTo) { throw new Exception("Неверные даты"); } string path = $"C:\\Университет\\2 курс\\4 семестр\\РПП\\Курсач РПП\\Reports\\{APIClient.Teacher.Name} от {_dateFrom.ToString("dd/MM/yyyy")}.pdf"; _report.SaveLessonTaskToPdfFile (new ReportBindingModel { FileName = path, DateFrom = _dateFrom, DateTo = _dateTo, TeacherId = APIClient.Teacher.Id }); var items = _report.GetLessonTask(new ReportBindingModel { DateFrom = _dateFrom, DateTo = _dateTo, TeacherId = APIClient.Teacher.Id }); mailSender.MailSendAsync(new MailSendInfoBindingModel { MailAddress = APIClient.Teacher.Email, Subject = "Отчет", Path = path }); return PartialView("_LessonTaskListPartial", items); } [HttpGet] public IActionResult TopMaterials() { if (APIClient.Teacher == null) { return Redirect("~/Home/Enter"); } ViewBag.DataPoints = JsonConvert.SerializeObject(_chart.GetTopMaterials(APIClient.Teacher.Id), new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore }); return View(); } [HttpGet] public IActionResult TopStudents() { if (APIClient.Teacher == null) { return Redirect("~/Home/Enter"); } ViewBag.DataPoints = JsonConvert.SerializeObject(_chart.GetTopStudents(APIClient.Teacher.Id), new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore }); return View(); } } }