using System.Diagnostics; using Microsoft.AspNetCore.Mvc; using VeterinaryClinicBusinessLogics.MailWorker; using VeterinaryClinicContracts.BindingModels; using VeterinaryClinicContracts.BusinessLogicsContracts; using VeterinaryClinicContracts.SearchModels; using VeterinaryClinicDataModels.Enums; using VeterinaryClinicWebApp.Models; namespace VeterinaryClinicWebApp.Controllers; public class HomeController : Controller { private readonly ILogger _logger; private readonly IUserLogic _userLogic; private readonly IAnimalLogic _animalLogic; private readonly IReportLogic _reportLogic; private readonly AbstractMailWorker _mailLogic; public HomeController(ILogger logger, IUserLogic userLogic, IAnimalLogic animalLogic, IReportLogic reportLogic, AbstractMailWorker mailLogic) { _logger = logger; _userLogic = userLogic; _animalLogic = animalLogic; _reportLogic = reportLogic; _mailLogic = mailLogic; } /// /// Домашняя страница /// [HttpGet] public IActionResult Index() { if (APIClient.User == null) { return Redirect("~/Home/Enter"); } return View(APIClient.User); } /// /// Личные данные пользователя /// [HttpGet] public IActionResult Privacy() { if (APIClient.User == null) { return Redirect("~/Home/Enter"); } return View(APIClient.User); } [HttpPost] public void Privacy(string fullname, UserRole role, string phone, string email, string password) { if (APIClient.User == null) { throw new Exception("Необходимо авторизоваться!"); } if (string.IsNullOrEmpty(fullname) || string.IsNullOrEmpty(phone) || string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password)) { throw new Exception("Введены не все данные!"); } _userLogic.Update(new UserBindingModel { Id = APIClient.User.Id, FullName = fullname, Role = role, Phone = phone, Email = email, Password = password }); APIClient.User.FullName = fullname; APIClient.User.Role = role; APIClient.User.Phone = phone; APIClient.User.Email = email; APIClient.User.Password = password; Response.Redirect("Privacy"); } /// /// Аутентификация /// [HttpGet] public IActionResult Enter() { if (APIClient.User != null) { throw new Exception("Вы уже авторизовались!"); } return View(); } [HttpPost] public void Enter(string email, string password) { if (string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password)) { throw new Exception("Введены не все данные!"); } APIClient.User = _userLogic.ReadElement(new UserSearchModel { Email = email, Password = password }); if (APIClient.User == null) { throw new Exception("Неверный логин/пароль"); } Response.Redirect("Index"); } /// /// Регистрация /// [HttpGet] public IActionResult Register() { if (APIClient.User != null) { throw new Exception("Вы уже зарегистрировались!"); } return View(); } [HttpPost] public void Register(string fullname, UserRole role, string phone, string email, string password) { if (string.IsNullOrEmpty(fullname) || string.IsNullOrEmpty(phone) || string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password)) { throw new Exception("Введены не все данные!"); } _userLogic.Create(new UserBindingModel { FullName = fullname, Role = role, Phone = phone, Email = email, Password = password }); Response.Redirect("Enter"); } /// /// Выйти из аккаунта /// [HttpGet] public void Logout() { if (APIClient.User == null) { throw new Exception("Необходимо авторизоваться!"); } APIClient.User = null; Response.Redirect("Enter"); } /// /// Получить отчет /// [HttpGet] public IActionResult Reports() { if (APIClient.User == null) { return Redirect("~/Home/Enter"); } return View(); } /// /// Вывести на форму отчёт /// [HttpPost] public IActionResult Reports(DateTime dateFrom, DateTime dateTo) { if (APIClient.User == null) { throw new Exception("Необходимо авторизоваться!"); } if (dateFrom == DateTime.MinValue || dateTo == DateTime.MinValue) { throw new Exception("Введены не все данные!"); } var data = _reportLogic.GetVisitsInfo(new ReportBindingModel { DateFrom = dateFrom, DateTo = dateTo, UserId = APIClient.User.Id }); return View(data); } /// /// Создать отчёт в формате Word /// [HttpPost] public void CreateReportWord() { if (APIClient.User == null) { throw new Exception("Необходимо авторизоваться!"); } _reportLogic.SaveAnimalServicesToWordFile(new ReportBindingModel { FileName = $@"D:\ {DateTime.Now.ToString("dd-MM-yyyy HH-mm-ss")}.docx", UserId = APIClient.User.Id }); Response.Redirect("/Home/Reports"); } /// /// Создать отчёт в формате Excel /// [HttpPost] public void CreateReportExcel() { if (APIClient.User == null) { throw new Exception("Необходимо авторизоваться!"); } _reportLogic.SaveAnimalServicesToExcelFile(new ReportBindingModel { FileName = $@"D:\ {DateTime.Now.ToString("dd-MM-yyyy HH-mm-ss")}.xlsx", UserId = APIClient.User.Id }); Response.Redirect("/Home/Reports"); } /// /// Создать отчёт в формате Pdf /// [HttpPost] public void CreateReportPdf(DateTime dateFrom, DateTime dateTo) { if (APIClient.User == null) { throw new Exception("Необходимо авторизоваться!"); } if (dateFrom == DateTime.MinValue || dateTo == DateTime.MinValue) { throw new Exception("Введены не все данные!"); } _reportLogic.SaveVisitsInfoToPdfFile(new ReportBindingModel { FileName = $@"D:\ {DateTime.Now.ToString("dd-MM-yyyy HH-mm-ss")}.pdf", UserId = APIClient.User.Id, DateFrom = dateFrom, DateTo = dateTo }); Response.Redirect("/Home/Reports"); } /// /// Отправить по почте отчёт /// [HttpPost] public void SendReport(IFormFile fileUpload) { if (APIClient.User == null) { throw new Exception("Необходимо авторизоваться!"); } if (fileUpload == null || fileUpload.Length <= 0) { throw new Exception("Файл не выбран или пуст!"); } // Путь до файла var uploadPath = @"D:\"; var fileName = Path.GetFileName(fileUpload.FileName); var fullPath = Path.Combine(uploadPath, fileName); _mailLogic.MailSendAsync(new MailSendInfoBindingModel { MailAddress = APIClient.User.Email, Subject = $"{fileName.Split('.')[0]}", Text = $"Отчёт отправлен {DateTime.Now}", Path = fullPath }); Response.Redirect("/Home/Reports"); } /// /// Ошибка /// [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } }