начало доавления отчетов, представления для доктора, контроллер общий с функциями доктора, байндинг и вью модели для отчетов

This commit is contained in:
ValAnn 2024-05-25 22:42:57 +04:00
parent 9159f52f40
commit 4881a7c7ca
12 changed files with 493 additions and 63 deletions

View File

@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>

View File

@ -0,0 +1,63 @@
using HospitalContracts.BusinessLogicContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HospitalBusinessLogic.MailWorker
{
public abstract class AbstractMailWorker
{
protected string _mailLogin = string.Empty;
protected string _mailPassword = string.Empty;
protected string _smtpClientHost = string.Empty;
protected int _smtpClientPort;
protected string _popHost = string.Empty;
protected int _popPort;
private readonly IPharmacistLogic _pharmacistLogic;
private readonly ILogger _logger;
public AbstractMailWorker(ILogger<AbstractMailWorker> logger, IPharmacistLogic pharmacistLogic)
{
_logger = logger;
_pharmacistLogic = pharmacistLogic;
}
public void MailConfig(MailConfigBindingModel config)
{
_mailLogin = config.MailLogin;
_mailPassword = config.MailPassword;
_smtpClientHost = config.SmtpClientHost;
_smtpClientPort = config.SmtpClientPort;
_popHost = config.PopHost;
_popPort = config.PopPort;
_logger.LogDebug("Config: {login}, {password}, {clientHost}, {clientPOrt}, {popHost}, {popPort}", _mailLogin, _mailPassword, _smtpClientHost, _smtpClientPort, _popHost, _popPort);
}
public async void MailSendAsync(MailSendInfoBindingModel info)
{
if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword))
{
return;
}
if (string.IsNullOrEmpty(_smtpClientHost) || _smtpClientPort == 0)
{
return;
}
if (string.IsNullOrEmpty(info.MailAddress) || string.IsNullOrEmpty(info.Subject) || string.IsNullOrEmpty(info.Text))
{
return;
}
_logger.LogDebug("Send Mail: {To}, {Subject}", info.MailAddress, info.Subject);
await SendMailAsync(info);
}
protected abstract Task SendMailAsync(MailSendInfoBindingModel info);
}
}

View File

@ -0,0 +1,50 @@
using HospitalContracts.BusinessLogicContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Net.Mime;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using HospitalContracts.BindingModels;
namespace HospitalBusinessLogic.MailWorker
{
public class MailKitWorker : AbstractMailWorker
{
public MailKitWorker(ILogger<MailKitWorker> logger, IPharmacistLogic pharmacistLogic) : base(logger, pharmacistLogic) { }
protected override async Task SendMailAsync(MailSendInfoBindingModel info)
{
using var objMailMessage = new MailMessage();
using var objSmtpClient = new SmtpClient(_smtpClientHost, _smtpClientPort);
try
{
objMailMessage.From = new MailAddress(_mailLogin);
objMailMessage.To.Add(new MailAddress(info.MailAddress));
objMailMessage.Subject = info.Subject;
objMailMessage.Body = info.Text;
objMailMessage.SubjectEncoding = Encoding.UTF8;
objMailMessage.BodyEncoding = Encoding.UTF8;
Attachment attachment = new Attachment("C:\\ReportsCourseWork\\pdffile.pdf", new ContentType(MediaTypeNames.Application.Pdf));
objMailMessage.Attachments.Add(attachment);
objSmtpClient.UseDefaultCredentials = false;
objSmtpClient.EnableSsl = true;
objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
objSmtpClient.Credentials = new NetworkCredential(_mailLogin, _mailPassword);
await Task.Run(() => objSmtpClient.Send(objMailMessage));
}
catch (Exception)
{
throw;
}
}
}
}

View File

@ -10,5 +10,6 @@ namespace HospitalContracts.BindingModels
{
public string FileName { get; set; } = string.Empty;
public List<int> Recipes { get; set; } = new();
}
}

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HospitalContracts.BindingModels
{
public class MailConfigBindingModel
{
public string MailLogin { get; set; } = string.Empty;
public string MailPassword { get; set; } = string.Empty;
public string SmtpClientHost { get; set; } = string.Empty;
public int SmtpClientPort { get; set; }
public string PopHost { get; set; } = string.Empty;
public int PopPort { get; set; }
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HospitalContracts.BindingModels
{
public class MailSendInfoBindingModel
{
public string MailAddress { get; set; } = string.Empty;
public string Subject { get; set; } = string.Empty;
public string Text { get; set; } = string.Empty;
}
}

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HospitalContracts.BindingModels
{
public class MedicinesDiseasesBindingModel
{
public string FileName { get; set; } = string.Empty;
public DateTime DateFrom { get; set; } = DateTime.Now;
public DateTime DateTo { get; set; } = DateTime.Now;
public int? DoctorId { get; set; }
public string? Email { get; set; }
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HospitalContracts.ViewModels
{
public class MedicinesDiseasesViewModel
{
public string PatientFIO { get; set; } = string.Empty;
public List<MedicineViewModel> Medicines { get; set; } = new();
public List<DiseaseViewModel> Diseases { get; set; } = new();
}
}

View File

@ -5,6 +5,7 @@ using HospitalDataModels.Models;
using HospitalDoctorApp.Models;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using System.Globalization;
using System.IO.Pipelines;
namespace HospitalDoctorApp.Controllers
@ -515,17 +516,7 @@ namespace HospitalDoctorApp.Controllers
return result;
}
[HttpGet]
public IActionResult ServiceListReport()
{
ViewBag.Animals = APIClient.GetRequest<List<RecipeViewModel>>($"api/animal/getanimallist?adminid={APIClient.Doctor.Id}");
return View();
}
[HttpGet]
public IActionResult Report()
{
return View();
}
[HttpGet]
public Tuple<RecipeViewModel, List<string>>? GetRecipe(int recipeId)
{
@ -556,6 +547,161 @@ namespace HospitalDoctorApp.Controllers
return result;
}
#region Reports
[HttpGet]
public IActionResult ProcedureListReport()
{
ViewBag.Services = APIClient.GetRequest<List<RecipeViewModel>>($"api/recipe/getrecipes?doctorid={APIClient.Doctor.Id}");
return View();
}
[HttpPost]
public void ProcedureListReport(List<int> recipes, string type)
{
if (APIClient.Doctor == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
if (recipes.Count <= 0)
{
throw new Exception("Количество должно быть больше 0");
}
if (string.IsNullOrEmpty(type))
{
throw new Exception("Неверный тип отчета");
}
if (type == "docx")
{
APIClient.PostRequest("api/report/createprocedurelistwordfile", new ListProceduresBindingModel
{
Recipes = recipes,
FileName = "C:\\ReportsCourseWork\\wordfile.docx"
});
Response.Redirect("GetWordFile");
}
else
{
APIClient.PostRequest("api/report/createprocedurelistexcelfile", new ListProceduresBindingModel
{
Recipes = recipes,
FileName = "C:\\ReportsCourseWork\\excelfile.xlsx"
});
Response.Redirect("GetExcelFile");
}
}
[HttpGet]
public IActionResult GetWordFile()
{
return new PhysicalFileResult("C:\\ReportsCourseWork\\wordfile.docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
}
public IActionResult GetExcelFile()
{
return new PhysicalFileResult("C:\\ReportsCourseWork\\excelfile.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}
[HttpGet]
public IActionResult Report()
{
ViewBag.Report = new List<MedicinesDiseasesBindingModel>();
return View();
}
[HttpGet]
public string GetPacientsReport(DateTime dateFrom, DateTime dateTo)
{
if (APIClient.Doctor == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
List<MedicinesDiseasesViewModel> result;
try
{
string dateFromS = dateFrom.ToString("s", CultureInfo.InvariantCulture);
string dateToS = dateTo.ToString("s", CultureInfo.InvariantCulture);
result = APIClient.GetRequest<List<MedicinesDiseasesViewModel>>
($"api/report/getmedicinesdiseasesreport?datefrom={dateFromS}&dateto={dateToS}&doctorid={APIClient.Doctor.Id}")!;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка создания отчета");
throw;
}
string table = "";
table += "<h2 class=\"text-custom-color-1\">Предварительный отчет</h2>";
table += "<div class=\"table-responsive\">";
table += "<table class=\"table table-striped table-bordered table-hover\">";
table += "<thead class=\"table-dark\">";
table += "<tr>";
table += "<th scope=\"col\">Дата</th>";
table += "<th scope=\"col\">ФИО пациента</th>";
table += "<th scope=\"col\">Болезнь</th>";
table += "<th scope=\"col\">Лекарство</th>";
table += "</tr>";
table += "</thead>";
foreach (var patient in result)
{
table += "<tbody>";
table += "<tr>";
table += $"<td></td>";
table += $"<td>{patient.PatientFIO}</td>";
table += $"<td></td>";
table += $"<td></td>";
table += "</tr>";
foreach (var disease in patient.Diseases)
{
table += "<tr>";
table += $"<td>{disease.Description}</td>";
table += $"<td></td>";
table += $"<td>{disease.Name}</td>";
table += $"<td></td>";
table += "</tr>";
}
foreach (var medicine in patient.Medicines)
{
table += "<tr>";
table += $"<td>{medicine.Name}</td>";
table += $"<td></td>";
table += $"<td></td>";
table += $"<td>{medicine.CountryOrigin}</td>";
table += "</tr>";
}
table += "</tbody>";
}
table += "</table>";
table += "</div>";
return table;
}
[HttpPost]
public void Report(DateTime dateFrom, DateTime dateTo)
{
if (APIClient.Doctor == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
APIClient.PostRequest("api/report/sendmedicinesdiseasesreporttoemail", new MedicinesDiseasesBindingModel
{
FileName = "C:\\ReportsCourseWork\\pdffile.pdf",
DoctorId = APIClient.Doctor.Id,
DateFrom = dateFrom,
DateTo = dateTo,
Email = APIClient.Doctor.MailAddress
});
Response.Redirect("Report");
}
#endregion
}
}

View File

@ -1,55 +1,65 @@
@{
ViewData["Title"] = "Report";
}
<div class="text-center">
<h1 class="display-4">Список пациентов с расшифровкой по лекарствам и болезням</h1>
<div class="container">
<div class="text-center mb-4">
<h2 class="text-custom-color-1">Список пациентов с расшифровкой по лекарствам и болезням за период</h2>
</div>
<form method="post">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="dateFrom" class="form-label text-custom-color-1">Начало периода:</label>
<input type="datetime-local" id="dateFrom" name="dateFrom" class="form-control" placeholder="Выберите дату начала периода">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="dateTo" class="form-label text-custom-color-1">Окончание периода:</label>
<input type="datetime-local" id="dateTo" name="dateTo" class="form-control" placeholder="Выберите дату окончания периода">
</div>
</div>
</div>
<div class="row mb-4">
<div class="col-md-8"></div>
<div class="col-md-4">
<button type="submit" class="btn btn-outline-dark w-100 text-center d-flex justify-content-md-center">Отправить на почту</button>
</div>
</div>
<div class="row mb-4">
<div class="col-md-8"></div>
<div class="col-md-4">
<button type="button" id="demonstrate" class="btn btn-outline-dark w-100 text-center d-flex justify-content-md-center">Продемонстрировать</button>
</div>
</div>
<div id="report"></div>
</form>
</div>
<div class="text-center">
@{
<div class="row mb-5">
<div class="col-4">Начальная дата:</div>
<div class="col-8">
<input type="date" id="startDate" name="startDate" class="form-control">
</div>
</div>
<div class="row mb-5">
<div class="col-4">Конечная дата:</div>
<div class="col-8">
<input type="date" id="endDate" name="endDate" class="form-control">
</div>
</div>
<table class="table">
<thead>
<tr>
<th>
Номер
</th>
<th>
Дата
</th>
<th>
Пациент
</th>
<th>
Лекарство
</th>
<th>
Болезнь
</th>
</tr>
</thead>
<tbody>
будет заполняться вьюшками отчета
</tbody>
</table>
<div class="row">
<div class="col-8"></div>
<div class="col-4"><input type="submit" value="Создать отчет" class="btn btn-primary" /></div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4"><input type="submit" value="Отправить на почту" class="btn btn-primary" /></div>
</div>
}
</div>
@section Scripts {
<script>
function check() {
var dateFrom = $('#dateFrom').val();
var dateTo = $('#dateTo').val();
if (dateFrom && dateTo) {
$.ajax({
method: "GET",
url: "/Home/GetAnimalsReport",
data: { dateFrom: dateFrom, dateTo: dateTo },
success: function (result) {
if (result != null) {
$('#report').html(result);
}
}
});
};
}
check();
$('#demonstrate').on('click', (e) => check());
</script>
}

View File

@ -37,6 +37,13 @@
<li class="nav-item">
<a class="nav-link text-dark" asparea="" asp-controller="Home" asp-action="Register">Регистрация</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asparea="" asp-controller="Home" asp-action="ProcedureListReport">Выгрузка списка</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asparea="" asp-controller="Home" asp-action="Report">Отчет</a>
</li>
</ul>
</div>
</div>

View File

@ -0,0 +1,88 @@
using HospitalBusinessLogic.BusinessLogics;
using HospitalContracts.BindingModels;
using HospitalContracts.BusinessLogicsContracts;
using HospitalContracts.ViewModels;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace HospitalRestApi.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class ReportController : Controller
{
private readonly IReportLogicDoctor _reportDoctor;
private readonly AbstractMailWorker _mailWorker;
public ReportController(ILogger<ReportController> logger, IReportLogicPharmacist reportPharmacist, AbstractMailWorker mailWorker)
{
_reportDoctor = reportPharmacist;
_mailWorker = mailWorker;
}
[Microsoft.AspNetCore.Mvc.HttpGet]
public IActionResult Index(ReportLogicPharmacist reportPharmacist)
{
return View();
}
[HttpPost]
public void CreateProcedureListWordFile(ListProceduresBindingModel model)
{
try
{
_reportDoctor.SaveProceduresToWordFile(model);
}
catch (Exception ex)
{
throw;
}
}
[HttpPost]
public void CreateProceddureListExcelFile(ListProceduresBindingModel model)
{
try
{
_reportDoctor.SaveProceduresToExcelFile(model);
}
catch (Exception ex)
{
throw;
}
}
[HttpGet]
public List<MedicinesDiseasesViewModel> GetMedicinesDiseasesReport(string dateFrom, string dateTo, int doctorId)
{
try
{
DateTime DateFrom = DateTime.Parse(dateFrom);
DateTime DateTo = DateTime.Parse(dateTo);
MedicinesDiseasesBindingModel model = new();
model.DateFrom = DateFrom;
model.DateTo = DateTo;
model.DoctorId = doctorId;
return _reportDoctor.GetMedicinesDiseases(model);
}
catch (Exception ex)
{
throw;
}
}
[HttpPost]
public void SendMedicinesDiseasesReportToEmail(MedicinesDiseasesBindingModel model)
{
try
{
_reportDoctor.SavePatientsToPdfFile(model);
_mailWorker.MailSendAsync(new MailSendInfoBindingModel
{
MailAddress = model.Email!,
Subject = "Отчет по patients",
Text = "TextPatients"
});
}
catch (Exception ex)
{
throw;
}
}
}
}