PIbd-21_MasenkinMS_Coursewo.../Hospital/HospitalWebApp/Controllers/HomeController.cs

407 lines
12 KiB
C#
Raw Permalink 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 HospitalBusinessLogics.MailWorker;
using HospitalContracts.BindingModels;
using HospitalContracts.BusinessLogicsContracts;
using HospitalContracts.SearchModels;
using HospitalContracts.ViewModels;
using HospitalDataModels.Enums;
using HospitalWebApp.Models;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
namespace HospitalWebApp.Controllers
{
/// <summary>
/// Главный контроллер
/// </summary>
public class HomeController : Controller
{
/// <summary>
/// Логгер
/// </summary>
private readonly ILogger<HomeController> _logger;
/// <summary>
/// Бизнес-логика для сущности "Доктор"
/// </summary>
private readonly IDoctorLogic _doctorLogic;
/// <summary>
/// Бизнес-логика для сущности "Рецепт"
/// </summary>
private readonly IRecipeLogic _recipeLogic;
/// <summary>
/// Бизнес-логика для отчетов
/// </summary>
private readonly IReportLogic _reportLogic;
/// <summary>
/// Бизнес-логика для отправки писем
/// </summary>
private readonly AbstractMailWorker _mailLogic;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="logger"></param>
/// <param name="doctorLogic"></param>
/// <param name="recipeLogic"></param>
/// <param name="reportLogic"></param>
/// <param name="mailLogic"></param>
public HomeController(ILogger<HomeController> logger, IDoctorLogic doctorLogic, IRecipeLogic recipeLogic, IReportLogic reportLogic, AbstractMailWorker mailLogic)
{
_logger = logger;
_doctorLogic = doctorLogic;
_recipeLogic = recipeLogic;
_reportLogic = reportLogic;
_mailLogic = mailLogic;
}
/// <summary>
/// Домашняя страница
/// </summary>
/// <returns></returns>
[HttpGet]
public IActionResult Index()
{
if (APIClient.Doctor == null)
{
return Redirect("~/Home/Enter");
}
return View(APIClient.Doctor);
}
/// <summary>
/// Личные данные доктора
/// </summary>
/// <returns></returns>
[HttpGet]
public IActionResult Privacy()
{
if (APIClient.Doctor == null)
{
return Redirect("~/Home/Enter");
}
return View(APIClient.Doctor);
}
/// <summary>
/// Личные данные доктора
/// </summary>
/// <param name="fullname"></param>
/// <param name="post"></param>
/// <param name="email"></param>
/// <param name="password"></param>
/// <exception cref="Exception"></exception>
[HttpPost]
public void Privacy(string fullname, DoctorPost post, string email, string password)
{
if (APIClient.Doctor == null)
{
throw new Exception("Необходимо авторизоваться!");
}
if (string.IsNullOrEmpty(fullname) || string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password))
{
throw new Exception("Введены не все данные!");
}
_doctorLogic.Update(new DoctorBindingModel
{
Id = APIClient.Doctor.Id,
FullName = fullname,
Post = post,
Email = email,
Password = password
});
APIClient.Doctor.FullName = fullname;
APIClient.Doctor.Post = post;
APIClient.Doctor.Email = email;
APIClient.Doctor.Password = password;
Response.Redirect("Privacy");
}
/// <summary>
/// Аутентификация
/// </summary>
/// <returns></returns>
[HttpGet]
public IActionResult Enter()
{
if (APIClient.Doctor != null)
{
throw new Exception("Вы уже авторизовались!");
}
return View();
}
/// <summary>
/// Аутентификация
/// </summary>
/// <param name="email"></param>
/// <param name="password"></param>
/// <exception cref="Exception"></exception>
[HttpPost]
public void Enter(string email, string password)
{
if (string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password))
{
throw new Exception("Введены не все данные!");
}
APIClient.Doctor = _doctorLogic.ReadElement(new DoctorSearchModel
{
Email = email,
Password = password
});
if (APIClient.Doctor == null)
{
throw new Exception("Неверный логин/пароль");
}
Response.Redirect("Index");
}
/// <summary>
/// Регистрация
/// </summary>
/// <returns></returns>
[HttpGet]
public IActionResult Register()
{
if (APIClient.Doctor != null)
{
throw new Exception("Вы уже зарегистрировались!");
}
return View();
}
/// <summary>
/// Регистрация
/// </summary>
/// <param name="fullname"></param>
/// <param name="post"></param>
/// <param name="email"></param>
/// <param name="password"></param>
/// <exception cref="Exception"></exception>
[HttpPost]
public void Register(string fullname, DoctorPost post, string email, string password)
{
if (string.IsNullOrEmpty(fullname) || string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password))
{
throw new Exception("Введены не все данные!");
}
_doctorLogic.Create(new DoctorBindingModel
{
FullName = fullname,
Post = post,
Email = email,
Password = password
});
Response.Redirect("Enter");
}
/// <summary>
/// Выйти из аккаунта
/// </summary>
/// <exception cref="Exception"></exception>
[HttpGet]
public void Logout()
{
if (APIClient.Doctor == null)
{
throw new Exception("Необходимо авторизоваться!");
}
APIClient.Doctor = null;
Response.Redirect("Enter");
}
/// <summary>
/// Получить отчет
/// </summary>
/// <returns></returns>
[HttpGet]
public IActionResult Reports()
{
if (APIClient.Doctor == null)
{
return Redirect("~/Home/Enter");
}
ViewBag.Recipes = _recipeLogic.ReadList(new RecipeSearchModel
{
DoctorId = APIClient.Doctor.Id
});
return View();
}
/// <summary>
/// Вывести на форму отчёт
/// </summary>
/// <exception cref="Exception"></exception>
[HttpPost]
public IActionResult Reports(DateTime dateFrom, DateTime dateTo)
{
if (APIClient.Doctor == null)
{
throw new Exception("Необходимо авторизоваться!");
}
if (dateFrom == DateTime.MinValue || dateTo == DateTime.MinValue)
{
throw new Exception("Введены не все данные!");
}
var data = _reportLogic.GetPatientsInfo(new ReportBindingModel
{
DateFrom = dateFrom,
DateTo = dateTo,
DoctorId = APIClient.Doctor.Id
});
ViewBag.Recipes = _recipeLogic.ReadList(new RecipeSearchModel
{
DoctorId = APIClient.Doctor.Id
});
return View(data);
}
/// <summary>
/// Создать отчёт в формате Word
/// </summary>
/// <exception cref="Exception"></exception>
[HttpPost]
public void CreateReportWord(List<int> recipes)
{
if (APIClient.Doctor == null)
{
throw new Exception("Необходимо авторизоваться!");
}
if (recipes == null || recipes.Count <= 0)
{
throw new Exception("Не выбраны рецепты!");
}
_reportLogic.SaveRecipeProceduresToWordFile(new ReportBindingModel
{
FileName = $@"{Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)}\Downloads\Список процедур {DateTime.Now.ToString("dd-MM-yyyy HH-mm-ss")}.docx",
DoctorId = APIClient.Doctor.Id,
Recipes = recipes
});
Response.Redirect("/Home/Reports");
}
/// <summary>
/// Создать отчёт в формате Excel
/// </summary>
/// <exception cref="Exception"></exception>
[HttpPost]
public void CreateReportExcel(List<int> recipes)
{
if (APIClient.Doctor == null)
{
throw new Exception("Необходимо авторизоваться!");
}
if (recipes == null || recipes.Count <= 0)
{
throw new Exception("Не выбраны рецепты!");
}
_reportLogic.SaveRecipeProceduresToExcelFile(new ReportBindingModel
{
FileName = $@"{Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)}\Downloads\Список процедур {DateTime.Now.ToString("dd-MM-yyyy HH-mm-ss")}.xlsx",
DoctorId = APIClient.Doctor.Id,
Recipes = recipes
});
Response.Redirect("/Home/Reports");
}
/// <summary>
/// Создать отчёт в формате Pdf
/// </summary>
/// <exception cref="Exception"></exception>
[HttpPost]
public void CreateReportPdf(DateTime dateFrom, DateTime dateTo)
{
if (APIClient.Doctor == null)
{
throw new Exception("Необходимо авторизоваться!");
}
if (dateFrom == DateTime.MinValue || dateTo == DateTime.MinValue)
{
throw new Exception("Введены не все данные!");
}
_reportLogic.SavePatientsInfoToPdfFile(new ReportBindingModel
{
FileName = $@"{Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)}\Downloads\Сведения о пациентах {DateTime.Now.ToString("dd-MM-yyyy HH-mm-ss")}.pdf",
DoctorId = APIClient.Doctor.Id,
DateFrom = dateFrom,
DateTo = dateTo
});
Response.Redirect("/Home/Reports");
}
/// <summary>
/// Отправить по почте отчёт
/// </summary>
/// <param name="fileUpload"></param>
/// <exception cref="Exception"></exception>
[HttpPost]
public void SendReport(IFormFile fileUpload)
{
if (APIClient.Doctor == null)
{
throw new Exception("Необходимо авторизоваться!");
}
if (fileUpload == null || fileUpload.Length <= 0)
{
throw new Exception("Файл не выбран или пуст!");
}
// Путь до файла
var uploadPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\Downloads\";
var fileName = Path.GetFileName(fileUpload.FileName);
var fullPath = Path.Combine(uploadPath, fileName);
_mailLogic.MailSendAsync(new MailSendInfoBindingModel
{
MailAddress = APIClient.Doctor.Email,
Subject = $"{fileName.Split('.')[0]}",
Text = $"Отчёт отправлен {DateTime.Now}",
Path = fullPath
});
Response.Redirect("/Home/Reports");
}
/// <summary>
/// Ошибка
/// </summary>
/// <returns></returns>
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}