CourseWork_SchoolStudyAgain/SchoolAgainStudy/StudentWebClient/Controllers/HomeController.cs

537 lines
21 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml.Wordprocessing;
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 SchoolAgainStudyDataModels.Models;
using StudentWebClient.Models;
using System.Collections;
using System.Diagnostics;
using System.Linq.Expressions;
namespace StudentWebClient.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly ITaskLogic _task;
private readonly IDiyLogic _diy;
private readonly IProductLogic _product;
private readonly IInterestLogic _interest;
private readonly IStudentLogic _student;
private readonly IReportLogic _report;
private readonly IChartLogic _chart;
private readonly AbstractMailWorker mailSender;
public HomeController(ILogger<HomeController> logger, IDiyLogic diy,
IProductLogic product , ITaskLogic task , IInterestLogic interest,
IStudentLogic student, IReportLogic report, AbstractMailWorker abstractMailWorker, IChartLogic chartLogic)
{
_logger = logger;
_diy = diy;
_product = product;
_task = task;
_interest = interest;
_student = student;
_report = report;
_chart = chartLogic;
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, "Ошибка работы с почтой");
}
}
public IActionResult Index()
{
if (APIClient.Student == null)
{
return Redirect("~/Home/Enter");
}
return View();
}
[HttpGet]
public IActionResult Privacy()
{
if (APIClient.Student == null)
{
return Redirect("~/Home/Enter");
}
return View(APIClient.Student);
}
[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 email,string login, string password, int scClass)
{
if (APIClient.Student == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(name) || string.IsNullOrEmpty(email) || scClass<=0 || scClass > 11)
{
throw new Exception("Введите данные");
}
_student.Update( new StudentBindingModel
{
Id = APIClient.Student.Id,
Name = name,
Email = email,
Password = password,
Login = login,
Class = scClass
});
APIClient.Student.Name = name;
APIClient.Student.Email = email;
APIClient.Student.Password = password;
APIClient.Student.Login = login;
APIClient.Student.Class = scClass;
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.Student = _student.ReadElement(new StudentSearchModel { Login = login, Password = password });
if (APIClient.Student == null)
{
throw new Exception("Неверный логин/пароль");
}
Response.Redirect("Index");
}
[HttpGet]
public IActionResult Register()
{
return View();
}
[HttpPost]
public void Register(string name, string email, string login, string password, int scClass)
{
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(name) || string.IsNullOrEmpty(email) || scClass <= 0 || scClass > 11)
{
throw new Exception("Введите логин, пароль и ФИО, класс, почту");
}
_student.Create( new StudentBindingModel
{
Name = name,
Email = email,
Password = password,
Login = login,
Class = scClass
});
Response.Redirect("Enter");
return;
}
[HttpGet]
public IActionResult Interests()
{
if (APIClient.Student == null)
{
return Redirect("~/Home/Enter");
}
return View(_interest.ReadList(new InterestSearchModel { StudentId = APIClient.Student.Id}));
}
[HttpGet]
public IActionResult CreateInterest()
{
return View();
}
[HttpPost]
public void CreateInterest(string title,string description)
{
if (APIClient.Student == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
if (string.IsNullOrEmpty(title) && string.IsNullOrEmpty(description))
{
throw new Exception("Введите название и описане");
}
_interest.Create( new InterestBindingModel
{
StudentId = APIClient.Student.Id,
Title = title,
Description = description
});
Response.Redirect("Interests");
}
[HttpGet]
public IActionResult InterestSetting(int id)
{
return View(_interest.ReadElement(new InterestSearchModel { Id = id}));
}
[HttpPost]
public void UpdateInterest(int id,string name, string desc)
{
if (string.IsNullOrEmpty(name))
{
throw new Exception("Нет названия");
}
if (string.IsNullOrEmpty(desc))
{
throw new Exception("Нет описания");
}
_interest.Update( new InterestBindingModel
{
Id = id,
Title = name,
Description = desc,
StudentId = APIClient.Student.Id,
});
Response.Redirect("/Home/Interests");
}
public void DeleteInterest(int id)
{
_interest.Delete(new InterestBindingModel
{
Id = id,
});
Response.Redirect("/Home/Interests");
}
[HttpGet]
public IActionResult Diyes()
{
if (APIClient.Student == null)
{
return Redirect("~/Home/Enter");
}
return View(_diy.ReadList(new DiySearchModel { StudentId = APIClient.Student.Id}));
}
[HttpGet]
public IActionResult CreateDiy()
{
ViewBag.Tasks = _task.ReadList(null);
var list = _interest.ReadList(new InterestSearchModel { StudentId = APIClient.Student.Id});
var simpInterest = list.Select(x => new { InterestId = x.Id, InterestName = x.Title });
ViewBag.Interests = new MultiSelectList(simpInterest, "InterestId", "InterestName");
return View();
}
[HttpPost]
public void CreateDiy(string title, string description, string dateCreate, int task, int[] interests )
{
if (APIClient.Student == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
if (string.IsNullOrEmpty(title) && string.IsNullOrEmpty(description) || string.IsNullOrEmpty(dateCreate) || task <=0 )
{
throw new Exception("Введите название и описане");
}
Dictionary<int, IInterest> diyInterests = new Dictionary<int, IInterest>();
foreach(int id in interests)
{
diyInterests.Add(id,_interest.ReadElement(new InterestSearchModel { Id = id}));
}
_diy.Create(new DiyBindingModel
{
StudentId = APIClient.Student.Id,
StudentName = APIClient.Student.Name,
Title = title,
Description = description,
DateCreate = DateTime.SpecifyKind(DateTime.Parse(dateCreate), DateTimeKind.Utc),
TaskId = task,
TaskName = _task.ReadElement(new TaskSearchModel { Id = task }).Title,
DiyInterests = diyInterests
}) ;
Response.Redirect("Diyes");
}
[HttpGet]
public IActionResult DiySetting(int id)
{
var diy = _diy.ReadElement(new DiySearchModel { Id = id });
var interests = _interest.ReadList(new InterestSearchModel { StudentId = APIClient.Student.Id}).Select(x => new {InterestId = x.Id, InterestName = x.Title}).ToList();
var selectedInterests = diy.DiyInterests.Select(x => x.Key).ToArray();
ViewBag.Interests = new MultiSelectList(interests, "InterestId", "InterestName", selectedInterests);
ViewBag.Tasks = _task.ReadList(null);
return View(diy);
}
[HttpPost]
public void UpdateDiy(int idDiy,string title, string description, string dateCreate, int task, int[] interests)
{
if (string.IsNullOrEmpty(title))
{
throw new Exception("Нет названия");
}
if (string.IsNullOrEmpty(description))
{
throw new Exception("Нет описания");
}
if (string.IsNullOrEmpty(dateCreate))
{
throw new Exception("Нет даты");
}
if (task <= 0)
{
throw new Exception("Нет задания");
}
Dictionary<int, IInterest> diyInterests = new Dictionary<int, IInterest>();
foreach (int id in interests)
{
diyInterests.Add(id, _interest.ReadElement(new InterestSearchModel { Id = id }));
}
_diy.Update(new DiyBindingModel
{
Id = idDiy,
StudentId = APIClient.Student.Id,
StudentName = APIClient.Student.Name,
Title = title,
Description = description,
DateCreate = DateTime.SpecifyKind(DateTime.Parse(dateCreate), DateTimeKind.Utc),
TaskId = task,
TaskName = _task.ReadElement(new TaskSearchModel { Id = task }).Title,
DiyInterests = diyInterests
});
Response.Redirect("/Home/Diyes");
}
public void DeleteDiy(int id)
{
_diy.Delete( new DiyBindingModel
{
Id = id,
});
Response.Redirect("/Home/Diyes");
}
[HttpGet]
public IActionResult Products()
{
if (APIClient.Student == null)
{
return Redirect("~/Home/Enter");
}
return View(_product.ReadList(new ProductSearchModel { StudentId = APIClient.Student.Id }));
}
[HttpGet]
public IActionResult CreateProduct()
{
var list = _interest.ReadList(new InterestSearchModel { StudentId = APIClient.Student.Id });
var simpInterest = list.Select(x => new { InterestId = x.Id, InterestName = x.Title });
ViewBag.Interests = new MultiSelectList(simpInterest, "InterestId", "InterestName");
return View();
}
[HttpPost]
public void CreateProduct(string title, string description, string dateCreate, int[] interests)
{
if (APIClient.Student == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
if (string.IsNullOrEmpty(title) && string.IsNullOrEmpty(description) || string.IsNullOrEmpty(dateCreate))
{
throw new Exception("Введите название и описане");
}
Dictionary<int, IInterest> productInterests = new Dictionary<int, IInterest>();
foreach (int id in interests)
{
productInterests.Add(id, _interest.ReadElement(new InterestSearchModel { Id = id }));
}
_product.Create(new ProductBindingModel
{
StudentId = APIClient.Student.Id,
StudentName = APIClient.Student.Name,
Title = title,
Description = description,
DateCreate = DateTime.SpecifyKind(DateTime.Parse(dateCreate), DateTimeKind.Utc),
ProductInterests = productInterests
});
Response.Redirect("Products");
}
[HttpGet]
public IActionResult ProductSetting(int id)
{
var product = _product.ReadElement(new ProductSearchModel { Id = id });
var interests = _interest.ReadList(new InterestSearchModel { StudentId = APIClient.Student.Id }).Select(x => new { InterestId = x.Id, InterestName = x.Title }).ToList();
var selectedInterests = product.ProductInterests.Select(x => x.Key).ToArray();
ViewBag.Interests = new MultiSelectList(interests, "InterestId", "InterestName", selectedInterests);
return View(product);
}
[HttpPost]
public void UpdateProduct(int idDiy, string title, string description, string dateCreate, int[] interests)
{
if (string.IsNullOrEmpty(title))
{
throw new Exception("Нет названия");
}
if (string.IsNullOrEmpty(description))
{
throw new Exception("Нет описания");
}
if (string.IsNullOrEmpty(dateCreate))
{
throw new Exception("Нет даты");
}
Dictionary<int, IInterest> productInterests = new Dictionary<int, IInterest>();
foreach (int id in interests)
{
productInterests.Add(id, _interest.ReadElement(new InterestSearchModel { Id = id }));
}
_product.Update(new ProductBindingModel
{
Id = idDiy,
StudentId = APIClient.Student.Id,
StudentName = APIClient.Student.Name,
Title = title,
Description = description,
DateCreate = DateTime.SpecifyKind(DateTime.Parse(dateCreate), DateTimeKind.Utc),
ProductInterests = productInterests
});
Response.Redirect("/Home/Products");
}
public void DeleteProduct(int id)
{
_product.Delete(new ProductBindingModel
{
Id = id,
});
Response.Redirect("/Home/Products");
}
public IActionResult Reports()
{
var list = _interest.ReadList(new InterestSearchModel { StudentId = APIClient.Student.Id });
var simpInterest = list.Select(x => new { InterestId = x.Id, InterestName = x.Title });
ViewBag.Interests = new MultiSelectList(simpInterest, "InterestId", "InterestName");
return View();
}
public IActionResult GetPartial(int[] interests, string mode)
{
var list = interests.Select(x => _interest.ReadElement(new InterestSearchModel { Id = x })).ToList();
if (mode.Equals("Excel"))
{
_report.SaveInterestLessonToExcelFile
(new ReportBindingModel { FileName = $"C:\\Users\\Вова\\Documents\\Учеба\\Reports\\{APIClient.Student.Name}-{DateTime.Now.ToString("dd/MM/yyyy")}.xlsx", Interests = list, StudentId = APIClient.Student.Id });
}
else
{
_report.SaveInterestLessonToWordFile
(new ReportBindingModel { FileName = $"C:\\Users\\Вова\\Documents\\Учеба\\Reports\\{APIClient.Student.Name}-{DateTime.Now.ToString("dd/MM/yyyy")}.docx", Interests = list, StudentId = APIClient.Student.Id });
}
var items = _report.GetInterestLesson(new ReportBindingModel { Interests = list, StudentId = APIClient.Student.Id});
return PartialView("_LessonListPartial", 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:\\Users\\Вова\\Documents\\Учеба\\Reports\\{APIClient.Student.Name} от {_dateFrom.ToString("dd/MM/yyyy")}.pdf";
_report.SaveInterestsToPdfFile
(new ReportBindingModel { FileName = path,
DateFrom = _dateFrom, DateTo = _dateTo, StudentId = APIClient.Student.Id});
var items = _report.GetInterests(new ReportBindingModel { DateFrom = _dateFrom, DateTo = _dateTo, StudentId = APIClient.Student.Id });
mailSender.MailSendAsync(new MailSendInfoBindingModel
{
MailAddress = APIClient.Student.Email,
Subject = $"Отчет от {dateFrom} по {dateTo}",
Path = path
});
return PartialView("_InterestListPartial", items);
}
[HttpGet]
public IActionResult WorksCharts()
{
if (APIClient.Student == null)
{
return Redirect("~/Home/Enter");
}
return View(_chart.GetDifferenceInCount(APIClient.Student.Id));
}
[HttpGet]
public IActionResult ActivityCharts()
{
if (APIClient.Student == null)
{
return Redirect("~/Home/Enter");
}
ViewBag.DataPoints = JsonConvert.SerializeObject(_chart.GetActivitys(APIClient.Student.Id),
new JsonSerializerSettings() {
NullValueHandling = NullValueHandling.Ignore});
return View();
}
[HttpGet]
public IActionResult TopInterests()
{
if (APIClient.Student == null)
{
return Redirect("~/Home/Enter");
}
ViewBag.DataPoints = JsonConvert.SerializeObject(_chart.GetTopInterests(APIClient.Student.Id),
new JsonSerializerSettings()
{
NullValueHandling = NullValueHandling.Ignore
});
return View();
}
}
}