Готово

This commit is contained in:
Yunusov_Niyaz 2024-05-25 23:22:13 +04:00
commit 2bffcdd9e7
24 changed files with 704 additions and 70 deletions

View File

@ -9,6 +9,7 @@ using VeterinaryContracts.SearchModels;
using VeterinaryContracts.StorageContracts;
using VeterinaryContracts.ViewModels;
using Microsoft.Extensions.Logging;
using System.Text.RegularExpressions;
namespace VeterinaryBusinessLogic.BusinessLogic
{
@ -101,6 +102,10 @@ namespace VeterinaryBusinessLogic.BusinessLogic
throw new ArgumentNullException("Нет Login доктора",
nameof(model.Login));
}
if (!Regex.IsMatch(model.Login, @"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$"))
{
throw new ArgumentException("Некорретно введен email клиента", nameof(model.Login));
}
if (string.IsNullOrEmpty(model.Password))
{
throw new ArgumentNullException("Нет пароля доктора",

View File

@ -72,7 +72,7 @@ namespace VeterinaryBusinessLogic.BusinessLogic
{
throw new ArgumentNullException("Цена заказа должна быть больше 0", nameof(model.Sum));
}
//if (model.DateCreate <= DateTime.Now)
//if (model.DateCreate < DateTime.Now)
//{
// throw new ArgumentNullException("Дата покупки не должна быть в прошлом", nameof(model.DateCreate));
//}

View File

@ -19,12 +19,15 @@ namespace VeterinaryBusinessLogic.BusinessLogic
private readonly IMedicationStorage _medicationStorage;
private readonly AbstractSaveToExcelDoctor _saveToExcel;
private readonly AbstractSaveToWordDoctor _saveToWord;
private readonly AbstractSaveToPdfDoctor _saveToPdf;
public ReportLogicDoctor( IMedicationStorage medicationStorage,
AbstractSaveToExcelDoctor saveToExcel, AbstractSaveToWordDoctor saveToWord)
AbstractSaveToExcelDoctor saveToExcel, AbstractSaveToWordDoctor saveToWord, AbstractSaveToPdfDoctor saveToPdf)
{
_medicationStorage = medicationStorage;
_saveToExcel = saveToExcel;
_saveToWord = saveToWord;
_saveToPdf = saveToPdf;
}
public void SavePurchasesToExcelFile(ReportPurchaseMedicationBindingModel model)
{
@ -54,5 +57,18 @@ namespace VeterinaryBusinessLogic.BusinessLogic
{
return _medicationStorage.GetReportDrugsVisits(new() { DateFrom = model.DateFrom, DateTo = model.DateTo });
}
public void SaveMedicationsToPdfFile(ReportDrugsVisitsBindingModel model)
{
_saveToPdf.CreateDoc(new PdfInfo
{
FileName = model.FileName,
Title = "Список медикаментов",
DateFrom = model.DateFrom!,
DateTo = model.DateTo!,
ReportDrugsVisits = GetVisitsDrugs(model)
});
}
}
}

View File

@ -0,0 +1,64 @@
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VeterinaryContracts.BindingModels;
using VeterinaryContracts.BusinessLogicContracts;
namespace VeterinaryBusinessLogic.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 IDoctorLogic _doctorLogic;
private readonly ILogger _logger;
public AbstractMailWorker(ILogger<AbstractMailWorker> logger, IDoctorLogic doctorLogic)
{
_logger = logger;
_doctorLogic = doctorLogic;
}
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 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 VeterinaryContracts.BindingModels;
using VeterinaryContracts.BusinessLogicContracts;
namespace VeterinaryBusinessLogic.MailWorker
{
public class MailKitWorker : AbstractMailWorker
{
public MailKitWorker(ILogger<MailKitWorker> logger, IDoctorLogic doctorLogic) : base(logger, doctorLogic) { }
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

@ -0,0 +1,72 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VeterinaryBusinessLogic.OfficePackage.HelperEnums;
using VeterinaryBusinessLogic.OfficePackage.HelperModels;
using VeterinaryDatabaseImplement.Implements;
namespace VeterinaryBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToPdfDoctor
{
public void CreateDoc(PdfInfo info)
{
CreatePdf(info);
CreateParagraph(new PdfParagraph
{
Text = info.Title,
Style =
"NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
CreateParagraph(new PdfParagraph
{
Text = $"с { info.DateFrom.ToShortDateString() } по { info.DateTo.ToShortDateString() }", Style
= "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
CreateTable(new List<string> { "4cm", "4cm", "4cm", "4cm" });
CreateRow(new PdfRowParameters
{
Texts = new List<string> { "Дата", "Название медикамента", "Услуга рекомендации","Название визита" },
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
foreach (var medication in info.ReportDrugsVisits)
{
CreateRow(new PdfRowParameters
{
Texts = new List<string> { "", medication.MedicationName, "", "" },
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
foreach(var visit in medication.Visits)
{
CreateRow(new PdfRowParameters
{
Texts = new List<string> { visit.DateVisit.ToString(), "", "", visit.VisitName },
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
}
foreach (var guidance in medication.Drugs)
{
CreateRow(new PdfRowParameters
{
Texts = new List<string> { guidance.DateCreate.ToString(), "", guidance.DrugName, "" },
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
}
}
SavePdf(info);
}
protected abstract void CreatePdf(PdfInfo info);
protected abstract void CreateParagraph(PdfParagraph paragraph);
protected abstract void CreateTable(List<string> columns);
protected abstract void CreateRow(PdfRowParameters rowParameters);
protected abstract void SavePdf(PdfInfo info);
}
}

View File

@ -10,6 +10,6 @@ namespace VeterinaryBusinessLogic.OfficePackage.HelperModels
public DateTime DateFrom { get; set; }
public DateTime DateTo { get; set; }
public List<ReportDrugsVisitsViewModel> ReportDrugsVisits { get; set; } = new();
public List<ReportVisitsDrugsViewModel> ReportVisitsDrugs{ get; set; } = new();
public List<ReportVisitsDrugsViewModel> ReportVisitsDrugs{ get; set; } = new();// возможно надо убрать
}
}

View File

@ -0,0 +1,108 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VeterinaryBusinessLogic.OfficePackage.HelperEnums;
using VeterinaryBusinessLogic.OfficePackage.HelperModels;
using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Tables;
using MigraDoc.Rendering;
using VeterinaryBusinessLogic.OfficePackage;
namespace VeterinaryBusinessLogic.OfficePackage.Implements
{
public class SaveToPdfDoctor : AbstractSaveToPdfDoctor
{
private Document? _document;
private Section? _section;
private Table? _table;
private static ParagraphAlignment
GetParagraphAlignment(PdfParagraphAlignmentType type)
{
return type switch
{
PdfParagraphAlignmentType.Center => ParagraphAlignment.Center,
PdfParagraphAlignmentType.Left => ParagraphAlignment.Left,
PdfParagraphAlignmentType.Right => ParagraphAlignment.Right,
_ => ParagraphAlignment.Justify,
};
}
/// <summary>
/// Создание стилей для документа
/// </summary>
/// <param name="document"></param>
private static void DefineStyles(Document document)
{
var style = document.Styles["Normal"];
style.Font.Name = "Times New Roman";
style.Font.Size = 14;
style = document.Styles.AddStyle("NormalTitle", "Normal");
style.Font.Bold = true;
}
protected override void CreatePdf(PdfInfo info)
{
_document = new Document();
DefineStyles(_document);
_section = _document.AddSection();
}
protected override void CreateParagraph(PdfParagraph pdfParagraph)
{
if (_section == null)
{
return;
}
var paragraph = _section.AddParagraph(pdfParagraph.Text);
paragraph.Format.SpaceAfter = "1cm";
paragraph.Format.Alignment =
GetParagraphAlignment(pdfParagraph.ParagraphAlignment);
paragraph.Style = pdfParagraph.Style;
}
protected override void CreateTable(List<string> columns)
{
if (_document == null)
{
return;
}
_table = _document.LastSection.AddTable();
foreach (var elem in columns)
{
_table.AddColumn(elem);
}
}
protected override void CreateRow(PdfRowParameters rowParameters)
{
if (_table == null)
{
return;
}
var row = _table.AddRow();
for (int i = 0; i < rowParameters.Texts.Count; ++i)
{
row.Cells[i].AddParagraph(rowParameters.Texts[i]);
if (!string.IsNullOrEmpty(rowParameters.Style))
{
row.Cells[i].Style = rowParameters.Style;
}
Unit borderWidth = 0.5;
row.Cells[i].Borders.Left.Width = borderWidth;
row.Cells[i].Borders.Right.Width = borderWidth;
row.Cells[i].Borders.Top.Width = borderWidth;
row.Cells[i].Borders.Bottom.Width = borderWidth;
row.Cells[i].Format.Alignment =
GetParagraphAlignment(rowParameters.ParagraphAlignment);
row.Cells[i].VerticalAlignment = VerticalAlignment.Center;
}
}
protected override void SavePdf(PdfInfo info)
{
var renderer = new PdfDocumentRenderer(true)
{
Document = _document
};
renderer.RenderDocument();
renderer.PdfDocument.Save(info.FileName);
}
}
}

View File

@ -14,6 +14,7 @@
<ItemGroup>
<ProjectReference Include="..\VeterinaryContracts\VeterinaryContracts.csproj" />
<ProjectReference Include="..\VeterinaryDatabaseImplement\VeterinaryDatabaseImplement.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VeterinaryContracts.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 VeterinaryContracts.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

@ -9,8 +9,12 @@ namespace VeterinaryContracts.BindingModels
public class ReportDrugsVisitsBindingModel
{
public string FileName { get; set; } = string.Empty;
public List<int> Medications { get; set; } = new();
public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }
//public List<int> Medications { get; set; } = new();
public DateTime DateFrom { get; set; }
public DateTime DateTo { get; set; }
public int? DoctorId { get; set; }
public string? Email { get; set; }
}
}

View File

@ -15,5 +15,6 @@ namespace VeterinaryContracts.BusinessLogicContracts
List<ReportPurchaseMedicationViewModel> GetPurchaseMedications(ReportPurchaseMedicationBindingModel model);
void SavePurchasesToWordFile(ReportPurchaseMedicationBindingModel model);
void SavePurchasesToExcelFile(ReportPurchaseMedicationBindingModel model);
void SaveMedicationsToPdfFile(ReportDrugsVisitsBindingModel model);
}
}

View File

@ -110,7 +110,8 @@ namespace VeterinaryDatabaseImplement.Implements
{
MedicationName = pet.MedicationName,
Drugs = context.Drugs
.Where(drug => drug.Medications
.Where(drug => drug.DateCreate <= model.DateTo &&
drug.DateCreate >= model.DateFrom && drug.Medications
.Select(x => x.MedicationId)
.ToList()
.Contains(pet.Id))

View File

@ -12,7 +12,7 @@ using VeterinaryDatabaseImplement;
namespace VeterinaryDatabaseImplement.Migrations
{
[DbContext(typeof(VeterinaryDatabase))]
[Migration("20240525104527_InitialCreate")]
[Migration("20240525190933_InitialCreate")]
partial class InitialCreate
{
/// <inheritdoc />

View File

@ -26,9 +26,7 @@ namespace VeterinaryRestApi.Controllers
var elem = _drug.ReadElement(new DrugSearchModel { Id = drugId });
if (elem == null)
return null;
var huinya = Tuple.Create(elem, elem.DrugMedications.Select(x => x.Value.MedicationName).ToList());
return huinya;
//return Tuple.Create(elem, elem.DrugMedications.Select(x => x.Value.MedicationName).ToList());
return Tuple.Create(elem, elem.DrugMedications.Select(x => x.Value.MedicationName).ToList());
}
catch (Exception ex)
{

View File

@ -0,0 +1,89 @@
using Microsoft.AspNetCore.Mvc;
using VeterinaryBusinessLogic.BusinessLogic;
using VeterinaryBusinessLogic.MailWorker;
using VeterinaryContracts.BindingModels;
using VeterinaryContracts.BusinessLogicContracts;
using VeterinaryContracts.ViewModels;
using VeterinaryDatabaseImplement.Implements;
namespace VeterinaryRestApi.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class ReportController : Controller
{
private readonly IReportLogicDoctor _reportDoctor;
private readonly AbstractMailWorker _mailWorker;
public ReportController(ILogger<ReportController> logger, IReportLogicDoctor reportDoctor, AbstractMailWorker mailWorker)
{
_reportDoctor = reportDoctor;
_mailWorker = mailWorker;
}
[Microsoft.AspNetCore.Mvc.HttpGet]
public IActionResult Index(ReportLogicDoctor reportDoctor)
{
return View();
}
[HttpPost]
public void CreatePurchaseListWordFile(ReportPurchaseMedicationBindingModel model)
{
try
{
_reportDoctor.SavePurchasesToWordFile(model);
}
catch (Exception ex)
{
throw;
}
}
[HttpPost]
public void CreatePurchaseListExcelFile(ReportPurchaseMedicationBindingModel model)
{
try
{
_reportDoctor.SavePurchasesToExcelFile(model);
}
catch (Exception ex)
{
throw;
}
}
[HttpGet]
public List<ReportDrugsVisitsViewModel> GetVisitsGuidesReport(string dateFrom, string dateTo, int doctorId)// переименовать
{
try
{
DateTime DateFrom = DateTime.Parse(dateFrom);
DateTime DateTo = DateTime.Parse(dateTo);
ReportDrugsVisitsBindingModel model = new();
model.DateFrom = DateFrom;
model.DateTo = DateTo;
model.DoctorId = doctorId;
return _reportDoctor.GetVisitsDrugs(model);
}
catch (Exception ex)
{
throw;
}
}
[HttpPost]
public void SendVisitsGuidesReportToEmail(ReportDrugsVisitsBindingModel model)// переименовать
{
try
{
_reportDoctor.SaveMedicationsToPdfFile(model);
_mailWorker.MailSendAsync(new MailSendInfoBindingModel
{
MailAddress = model.Email!,
Subject = "Отчет по медикаментам",
Text = "Лови"
});
}
catch (Exception ex)
{
throw;
}
}
}
}

View File

@ -1,8 +1,10 @@
using VeterinaryBusinessLogic.BusinessLogic;
using VeterinaryContracts.BindingModels;
using VeterinaryContracts.BusinessLogicContracts;
using VeterinaryContracts.StorageContracts;
using VeterinaryDatabaseImplement.Implements;
using Microsoft.OpenApi.Models;
using VeterinaryBusinessLogic.MailWorker;
var builder = WebApplication.CreateBuilder(args);
@ -29,9 +31,29 @@ builder.Services.AddTransient<IPurchaseLogic, PurchaseLogic>();
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "VeterinaryViewRestApi", Version = "v1" });
});
var app = builder.Build();
var mailSender = app.Services.GetService<AbstractMailWorker>();
mailSender?.MailConfig(new MailConfigBindingModel
{
MailLogin = builder.Configuration?.GetSection("MailLogin")?.Value?.ToString()
?? string.Empty,
MailPassword =
builder.Configuration?.GetSection("MailPassword")?.Value?.ToString() ??
string.Empty,
SmtpClientHost =
builder.Configuration?.GetSection("SmtpClientHost")?.Value?.ToString() ??
string.Empty,
SmtpClientPort =
Convert.ToInt32(builder.Configuration?.GetSection("SmtpClientPort")?.Value?.ToString()),
PopHost = builder.Configuration?.GetSection("PopHost")?.Value?.ToString() ??
string.Empty,
PopPort = Convert.ToInt32(builder.Configuration?.GetSection("PopPort")?.Value?.ToString())
});
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())

View File

@ -5,5 +5,11 @@
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
"AllowedHosts": "*",
"SmtpClientHost": "smtp.gmail.com",
"SmtpClientPort": "587",
"PopHost": "pop.gmail.com",
"PopPort": "995",
"MailLogin": "anasirov48@gmail.com",
"MailPassword": "xoac ehyi tnar fiho"
}

View File

@ -7,6 +7,7 @@ using System.Text;
using VeterinaryDataModels.Models;
using VeterinaryContracts.SearchModels;
using VeterinaryContracts.StorageContracts;
using System.Globalization;
namespace VeterinaryShowDoctorApp.Controllers
{
@ -474,14 +475,147 @@ namespace VeterinaryShowDoctorApp.Controllers
ViewBag.Medications = APIDoctor.GetRequest<List<MedicationViewModel>>($"api/medication/getmedications?doctorid={APIDoctor.Doctor.Id}");
return View();
}
[HttpGet]
public IActionResult Report()
[HttpPost]
public void PurchaseMedicationReport(List<int> medications, string type)
{
if (APIDoctor.Doctor == null)
{
return Redirect("~/Home/Enter");
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
if (medications.Count <= 0)
{
throw new Exception("Количество должно быть больше 0");
}
if (string.IsNullOrEmpty(type))
{
throw new Exception("Неверный тип отчета");
}
if (type == "docx")
{
APIDoctor.PostRequest("api/report/createpurchaselistwordfile", new ReportPurchaseMedicationBindingModel
{
Medications = medications,
FileName = "C:\\ReportsCourseWork\\wordfile.docx"
});
Response.Redirect("GetWordFile");
}
else
{
APIDoctor.PostRequest("api/report/createpurchaselistexcelfile", new ReportPurchaseMedicationBindingModel
{
Medications = medications,
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<ReportDrugsVisitsBindingModel>();
return View();
}
[HttpGet]
public string GetMedicationsReport(DateTime dateFrom, DateTime dateTo)
{
if (APIDoctor.Doctor == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
List<ReportDrugsVisitsViewModel> result;
try
{
string dateFromS = dateFrom.ToString("s", CultureInfo.InvariantCulture);
string dateToS = dateTo.ToString("s", CultureInfo.InvariantCulture);
result = APIDoctor.GetRequest<List<ReportDrugsVisitsViewModel>>
($"api/report/getvisitsguidesreport?datefrom={dateFromS}&dateto={dateToS}&doctorid={APIDoctor.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 medication in result)
{
table += "<tbody>";
table += "<tr>";
table += $"<td></td>";
table += $"<td>{medication.MedicationName}</td>";
table += $"<td></td>";
table += $"<td></td>";
table += "</tr>";
foreach (var drug in medication.Drugs)
{
table += "<tr>";
table += $"<td>{drug.DateCreate}</td>";
table += $"<td></td>";
table += $"<td>{drug.DrugName}</td>";
table += $"<td></td>";
table += "</tr>";
}
foreach (var visit in medication.Visits)
{
table += "<tr>";
table += $"<td>{visit.DateVisit}</td>";
table += $"<td></td>";
table += $"<td></td>";
table += $"<td>{visit.VisitName}</td>";
table += "</tr>";
}
table += "</tbody>";
}
table += "</table>";
table += "</div>";
return table;
}
[HttpPost]
public void Report(DateTime dateFrom, DateTime dateTo)
{
if (APIDoctor.Doctor == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
APIDoctor.PostRequest("api/report/sendvisitsguidesreporttoemail", new ReportDrugsVisitsBindingModel // поменять
{
FileName = "C:\\ReportsCourseWork\\pdffile.pdf",
DoctorId = APIDoctor.Doctor.Id,
DateFrom = dateFrom,
DateTo = dateTo,
Email = APIDoctor.Doctor.Login
});
Response.Redirect("Report");
}
}
}

View File

@ -33,6 +33,9 @@
<th>
Цена
</th>
<th>
Дата создания
</th>
</tr>
</thead>
<tbody>
@ -51,6 +54,9 @@
<td>
@Html.DisplayFor(modelItem =>item.Price)
</td>
<td>
@Html.DisplayFor(modelItem =>item.DateCreate)
</td>
</tr>
}
</tbody>

View File

@ -19,9 +19,18 @@
</select>
</div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-2"><input type="submit" value="Word" class="btn btn-primary" /></div>
<div class="col-1"><input type="submit" value="Excel" class="btn btn-primary" /></div>
<div class="file-format">
<label class="form-label">Выберите формат файла:</label>
<div class="form-check">
<input class="form-check-input" type="radio" name="type" value="docx" id="docx">
<label class="form-check-label" for="docx">Word-файл</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="type" value="xlsx" id="xlsx" checked>
<label class="form-check-label" for="xlsx">Excel-файл</label>
</div>
</div>
<div class="d-flex justify-content-center">
<button type="submit" class="btn btn-block btn-outline-dark w-100">Создать</button>
</div>
</form>

View File

@ -1,51 +1,66 @@
@{
ViewData["Title"] = "Report";

@{
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-2"><input type="submit" value="Создать отчет" class="btn btn-primary" /></div>
<div class="col-1"><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/GetMedicationsReport",
data: { dateFrom: dateFrom, dateTo: dateTo },
success: function (result) {
if (result != null) {
$('#report').html(result);
}
}
});
};
}
check();
$('#demonstrate').on('click', (e) => check());
</script>
}