Этап 2. Получение отчетов на форму или на скачивание

This commit is contained in:
prodigygirl 2023-05-18 18:23:17 +04:00
parent a0ce881f77
commit c529bcf1b9
9 changed files with 275 additions and 4 deletions

View File

@ -0,0 +1,87 @@
using HospitalContracts.BindingModels;
using HospitalContracts.BusinessLogicContracts;
using HospitalContracts.ViewModels;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.IO;
namespace HospitalRestApi.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
[ApiExplorerSettings(IgnoreApi = true)]
public class ReportController : ControllerBase
{
private readonly ILogger _logger;
private readonly IReportLogic _logic;
public ReportController(ILogger<ReportController> logger, IReportLogic logic)
{
_logger = logger;
_logic = logic;
}
[HttpPost]
public ActionResult GetReportPatientsToExcelFile(ReportBindingModel model)
{
try
{
var stream = _logic.SavePatientsToExcelFile(model);
return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", model.FileName);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения списка пациентов");
throw;
}
}
[HttpPost]
public ActionResult GetReportPatientsToWordFile(ReportBindingModel model)
{
try
{
var stream = _logic.SavePatientsToWordFile(model);
return File(stream, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", model.FileName);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения списка пациентов");
throw;
}
}
[HttpGet]
public List<ReportPrescriptionProcedureViewModel> GetReportPrescriptions(DateTime startDate, DateTime endDate)
{
try
{
return _logic.GetPrescriptionProcedures(new ReportBindingModel { DateFrom = startDate, DateTo = endDate});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения списка пациентов");
throw;
}
}
[HttpPost]
public ActionResult GetReportPrescriptionsPdf(DateTime startDate, DateTime endDate, ReportBindingModel model)
{
try
{
var stream = _logic.SavePrescriptionsToPdfFile(model);
return File(stream, "application/pdf", "pdf.pdf");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения списка пациентов");
throw;
}
}
}
}

View File

@ -1,4 +1,6 @@
using HospitalBusinessLogic;
using HospitalBusinessLogic.OfficePackage;
using HospitalBusinessLogic.OfficePackage.Implements;
using HospitalContracts.BusinessLogicContracts;
using HospitalContracts.StorageContracts;
using HospitalDatabaseImplement.Implements;
@ -26,8 +28,9 @@ builder.Services.AddTransient<ITreatmentLogic, TreatmentLogic>();
builder.Services.AddTransient<IReportLogic, ReportLogic>();
//builder.Services.AddTransient<AbstractSaveToWord, SaveToWord>();
//builder.Services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
builder.Services.AddTransient<AbstractSaveToWord, SaveToWord>();
builder.Services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
builder.Services.AddTransient<AbstractSaveToPdf, SaveToPdf>();
//builder.Services.AddSingleton<AbstractMailWorker, MailKitWorker>();
builder.Services.AddControllers().AddJsonOptions((option) =>

View File

@ -41,5 +41,24 @@ namespace HospitalWeb
throw new Exception(result);
}
}
public static (Stream stream, string? contentType)? GetFileRequest<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.ReadAsStreamAsync().Result;
response.Result.Content.Headers.TryGetValues("content-type", out var type);
if (response.Result.IsSuccessStatusCode)
{
return (stream: result, contentType: type?.First());
}
else
{
throw new Exception($"Failed to retrieve file from {requestUrl}. StatusCode: {response.Result.StatusCode}");
}
}
}
}

View File

@ -51,8 +51,6 @@ namespace HospitalWeb.Controllers
model.ApothecaryId = APIClient.Apothecary.Id;
if (model.Id != 0)
{
// тут надо вытащить ключи, потом по ним сделать массовый запрос сущностей лекарств, а потом вставить как значения в словарь
//model.RecipeMedicines =
APIClient.PostRequest("api/recipe/update", model);
}
else

View File

@ -0,0 +1,62 @@
using HospitalContracts.BindingModels;
using HospitalContracts.ViewModels;
using HospitalWeb.HelpModels;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Net;
namespace HospitalWeb.Controllers
{
public class ReportController : Controller
{
[HttpGet("/reports/patients")]
public IActionResult ReportPatients()
{
ViewBag.Medicines = APIClient.GetRequest<List<MedicineViewModel>>($"api/medicine/getmedicines");
return View();
}
[HttpGet("/reports/precriptions")]
public IActionResult ReportPrescriptions(List<ReportPrescriptionProcedureViewModel>? report)
{
return View(report);
}
[HttpGet("/report/getprescriptions")]
public IActionResult GetPrescriptions(DateTime startDate, DateTime endDate, string type)
{
/* // если type - получение отчета на форме
// Преобразуем даты к нужному формату
string startDateString = startDate.ToString("yyyy-MM-dd HH:mm:ss.fffffff");
string endDateString = endDate.ToString("yyyy-MM-dd HH:mm:ss.fffffff");
var report = APIClient.GetRequest<List<ReportPrescriptionProcedureViewModel>>($"api/report/getreportprescriptions?startDate={startDateString}&endDate={endDateString}");
return View("ReportPrescriptions", report);*/
// иначе отправка на почту
string startDateString = startDate.ToString("yyyy-MM-dd HH:mm:ss.fffffff");
string endDateString = endDate.ToString("yyyy-MM-dd HH:mm:ss.fffffff");
var fileData = APIClient.GetFileRequest($"api/report/getreportprescriptionspdf?", new ReportBindingModel { DateFrom = startDate, DateTo = endDate });
if (fileData != null)
return File(fileData.Value.stream, fileData.Value.contentType!, "prescriptions.pdf");
throw new Exception($"Failed to retrieve file from.");
}
[HttpGet("/reports/download")]
public IActionResult DownloadReport(ReportBindingModel model, string Format)
{
var format = Enum.Parse<FileFormat>(Format);
var (endpoint, extension) = format switch
{
FileFormat.Word => ("api/report/getreportpatientstowordfile/", ".docx"),
FileFormat.Excel => ("api/report/getreportpatientstoexcelfile/", ".xlsx"),
_ => throw new ArgumentException($"Invalid file format: {format}", nameof(Format))
};
model.FileName += extension;
var fileData = APIClient.GetFileRequest(endpoint, model);
if (fileData != null)
return File(fileData.Value.stream, fileData.Value.contentType!, model.FileName);
throw new Exception($"Failed to retrieve file from {endpoint}.");
}
}
}

View File

@ -0,0 +1,8 @@
namespace HospitalWeb.HelpModels
{
public enum FileFormat
{
Word = 0,
Excel = 1
}
}

View File

@ -0,0 +1,34 @@
@using HospitalContracts.ViewModels;
@using System.Globalization
@model MedicineViewModel
@{
ViewData["Title"] = "Отчет Пациенты";
}
<div class="text-center">
<h2 class="display-4">@ViewData["Title"]</h2>
</div>
<form id="reportForm" method="get" action="/reports/download">
<div class="row">
<div class="col-4">Выбор лекарств</div>
<div class="col-8">
<select id="medicines" name="Medicines" class="form-control" multiple asp-items="@(new SelectList(@ViewBag.Medicines,"Id", "Name"))"></select>
<small>Для выбора нескольких элементов удерживайте клавишу Ctrl.</small>
</div>
</div>
<div class="row">
<div class="col-4">Название файла (без формата):</div>
<div class="col-8"><input type="text" name="FileName" required /></div>
</div>
<div class="row">
<div class="col-4">Формат файла:</div>
<div class="col-8">
<select name="Format" required>
<option value="Word">Word</option>
<option value="Excel">Excel</option>
</select>
</div>
</div>
<button id="submitReport">Получить отчет</button>
</form>

View File

@ -0,0 +1,51 @@
@using HospitalContracts.ViewModels;
@model List<ReportPrescriptionProcedureViewModel>
@{
ViewData["Title"] = "Отчет Поступления";
}
<div class="text-center">
<h2 class="display-4">@ViewData["Title"]</h2>
</div>
<form method="get" class="form-inline" action="/report/getprescriptions">
<div class="form-group mx-sm-3 mb-2">
<label for="startDate" class="sr-only">Начальная дата:</label>
<input type="date" class="form-control" id="startDate" name="startDate" required />
</div>
<div class="form-group mx-sm-3 mb-2">
<label for="endDate" class="sr-only">Конечная дата:</label>
<input type="date" class="form-control" id="endDate" name="endDate" required />
</div>
<div class="form-group mx-sm-3 mb-2">
<button type="submit" class="btn btn-primary" name="type" value="getReport">Получить отчет</button>
</div>
<div class="form-group mx-sm-3 mb-2">
<button type="submit" class="btn btn-secondary" name="type" value="sendPdf">Отправить pdf на почту</button>
</div>
</form>
@if (Model != null && Model.Any())
{
<table class="table">
<thead>
<tr>
<th>Дата поступления</th>
<th>Лекарство</th>
<th>Количество</th>
<th>Название процедуры</th>
</tr>
</thead>
<tbody>
@foreach (var report in Model)
{
<tr>
<td>@report.DateCreate.ToShortDateString()</td>
<td>@report.MedicineName</td>
<td>@report.Number</td>
<td>@report.ProcedureName</td>
</tr>
}
</tbody>
</table>
}

View File

@ -28,6 +28,15 @@
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Recipe" asp-action="Recipes">Рецепты</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link text-dark dropdown-toggle" href="#" id="reportDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
Отчеты
</a>
<div class="dropdown-menu" aria-labelledby="reportDropdown">
<a class="dropdown-item" asp-area="" asp-controller="Report" asp-action="ReportPatients">Отчет Пациенты</a>
<a class="dropdown-item" asp-area="" asp-controller="Report" asp-action="ReportPrescriptions">Отчет Поступления</a>
</div>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Профиль</a>
</li>