ворд/эксель + вывод в таблице

This commit is contained in:
Владимир Данилов 2024-05-29 23:12:32 +04:00
parent 787f1685c7
commit 94d89e7e27
40 changed files with 2461 additions and 65 deletions

View File

@ -0,0 +1,219 @@
using VeterinaryClinicBusinessLogics.OfficePackage;
using VeterinaryClinicBusinessLogics.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VeterinaryClinicContracts.BindingModels;
using VeterinaryClinicContracts.BusinessLogicsContracts;
using VeterinaryClinicContracts.SearchModels;
using VeterinaryClinicContracts.StoragesContracts;
using VeterinaryClinicContracts.ViewModels;
namespace VeterinaryClinicBusinessLogics.BusinessLogics
{
public class ReportLogic : IReportLogic
{
private readonly IAnimalStorage _animalStorage;
private readonly IMedicationStorage _medicationStorage;
private readonly IServiceStorage _serviceStorage;
private readonly IVaccinationStorage _vaccinationStorage;
private readonly IVisitStorage _visitStorage;
private readonly AbstractSaveToWord _saveToWord;
private readonly AbstractSaveToExcel _saveToExcel;
private readonly AbstractSaveToPdf _saveToPdf;
public ReportLogic(IAnimalStorage animalStorage,
IMedicationStorage medicationStorage,
IServiceStorage serviceStorage,
IVaccinationStorage vaccinationStorage,
IVisitStorage visitStorage,
AbstractSaveToWord saveToWord,
AbstractSaveToExcel saveToExcel,
AbstractSaveToPdf saveToPdf)
{
_animalStorage = animalStorage;
_medicationStorage = medicationStorage;
_serviceStorage = serviceStorage;
_vaccinationStorage = vaccinationStorage;
_visitStorage = visitStorage;
_saveToWord = saveToWord;
_saveToExcel = saveToExcel;
_saveToPdf = saveToPdf;
}
/// <summary>
/// Получить список животных с расшифровкой по услугам
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public List<ReportAnimalServicesViewModel> GetAnimalServices(ReportBindingModel model)
{
var result = new List<ReportAnimalServicesViewModel>();
// Получаем список животных по идентификатору пользователя
var animals = _animalStorage.GetFilteredList(new AnimalSearchModel
{
UserId = model.UserId
});
// Получаем список всех визитов,
// так как животные и услуги связаны через сущность "Визит"
var visits = _visitStorage.GetFullList();
// Проходим по списку полученных животных
foreach (var animal in animals)
{
// Создаём запись
var record = new ReportAnimalServicesViewModel
{
Animal = animal,
// HashSet используется для того, чтобы не повторялись процедуры
Services = new HashSet<ServiceViewModel>()
};
// Проходим по списку всех визитов
foreach (var visit in visits)
{
// Проверяем есть ли у визита текущее животное
if (visit.VisitAnimals.ContainsKey(animal.Id))
{
// Если есть, то проходим по списку всех услуг визита
foreach (var serviceId in visit.VisitServices.Keys)
{
// Находим услугу и добавляем в список услуг
var service = _serviceStorage.GetElement(new ServiceSearchModel
{
Id = serviceId
});
record.Services.Add(service!);
}
}
}
// Добавляем запись
result.Add(record);
}
return result;
}
/// <summary>
/// Получить список визитов с расшифровкой по медикаментам и прививкам
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public List<ReportVisitsViewModel> GetVisitsInfo(ReportBindingModel model)
{
var result = new List<ReportVisitsViewModel>();
// Получаем список визитов отсортированных по дате и пользователю
var visits = _visitStorage.GetFilteredList(new VisitSearchModel
{
UserId = model.UserId,
DateFrom = model.DateFrom,
DateTo = model.DateTo
});
// Получаем список животных по идентификатору пользователя
var animals = _animalStorage.GetFilteredList(new AnimalSearchModel
{
UserId = model.UserId,
});
// Получаем список вакцинаций по идентификатору пользователя
var vaccinations = _vaccinationStorage.GetFilteredList(new VaccinationSearchModel
{
UserId = model.UserId,
});
// Проходим по списку всех визитов
foreach (var visit in visits)
{
// Создаем запись
var record = new ReportVisitsViewModel
{
Visit = visit,
// HashSet используется для того, чтобы не повторялись медикаменты/вакцинация
Medications = new HashSet<MedicationViewModel>(),
Vaccinations = new HashSet<VaccinationViewModel>()
};
// Проходим по списку животных
foreach (var animal in animals)
{
// Проверяем есть ли у визита текущее животное
if (visit.VisitAnimals.ContainsKey(animal.Id))
{
// Проходим по списку медикаментов, связанных с животным
foreach (var medicationId in animal.AnimalMedications.Keys)
{
// Находим медикамент и добавляем в список медикаментов
var medication = _medicationStorage.GetElement(new MedicationSearchModel
{
Id = medicationId,
});
record.Medications.Add(medication!);
}
// Проходим по списку вакцинаций
foreach (var vaccination in vaccinations)
{
// Если вакцинация относится к текущему животному
if (vaccination.AnimalId.Equals(animal.Id))
{
// Добавляем в список вакцинаций
record.Vaccinations.Add(vaccination);
}
}
}
}
result.Add(record);
}
return result;
}
public void SaveAnimalServicesToExcelFile(ReportBindingModel model)
{
_saveToExcel.CreateReport(new ExcelInfo
{
FileName = model.FileName,
Title = "Список услуг.",
AnimalServices = GetAnimalServices(model)
});
}
public void SaveAnimalServicesToWordFile(ReportBindingModel model)
{
_saveToWord.CreateReport(new WordInfo
{
FileName = model.FileName,
Title = "Список услуг.",
AnimalServices = GetAnimalServices(model)
});
}
public void SaveVisitsInfoToPdfFile(ReportBindingModel model)
{
_saveToPdf.CreateReport(new PdfInfo
{
FileName = model.FileName,
Title = "Сведения о визитах.",
DateFrom = model.DateFrom!.Value,
DateTo = model.DateTo!.Value,
VisitsInfo = GetVisitsInfo(model)
});
}
}
}

View File

@ -0,0 +1,105 @@
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VeterinaryClinicContracts.BindingModels;
namespace VeterinaryClinicBusinessLogics.MailWorker
{
public abstract class AbstractMailWorker
{
/// <summary>
/// Логгер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Логин для доступа к почтовому сервису
/// </summary>
protected string _mailLogin = string.Empty;
/// <summary>
/// Пароль для доступа к почтовому сервису
/// </summary>
protected string _mailPassword = string.Empty;
/// <summary>
/// Хост SMTP-клиента
/// </summary>
protected string _smtpClientHost = string.Empty;
/// <summary>
/// Порт SMTP-клиента
/// </summary>
protected int _smtpClientPort;
/// <summary>
/// Хост протокола POP3
/// </summary>
protected string _popHost = string.Empty;
/// <summary>
/// Порт протокола POP3
/// </summary>
protected int _popPort;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="logger"></param>
public AbstractMailWorker(ILogger<AbstractMailWorker> logger)
{
_logger = logger;
}
/// <summary>
/// Настроить почтовый сервис
/// </summary>
/// <param name="config"></param>
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);
}
/// <summary>
/// Проверить и отправить письмо
/// </summary>
/// <param name="info"></param>
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.Path))
{
return;
}
_logger.LogDebug("Send Mail: {To}, {Subject}", info.MailAddress, info.Subject);
await SendMailAsync(info);
}
/// <summary>
/// Отправить письмо
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
protected abstract Task SendMailAsync(MailSendInfoBindingModel info);
}
}

View File

@ -0,0 +1,54 @@
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using VeterinaryClinicContracts.BindingModels;
namespace VeterinaryClinicBusinessLogics.MailWorker
{
public class MailKitWorker : AbstractMailWorker
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="logger"></param>
public MailKitWorker(ILogger<MailKitWorker> logger) : base(logger) { }
/// <summary>
/// Отправить письмо
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
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.Attachments.Add(new Attachment(info.Path));
// Указываем параметры
objMailMessage.SubjectEncoding = Encoding.UTF8;
objMailMessage.BodyEncoding = Encoding.UTF8;
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,193 @@
using DocumentFormat.OpenXml.Presentation;
using VeterinaryClinicBusinessLogics.OfficePackage.HelperEnums;
using VeterinaryClinicBusinessLogics.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VeterinaryClinicBusinessLogics.OfficePackage
{
/// <summary>
/// Абстрактный класс для создания отчета Excel
/// </summary>
public abstract class AbstractSaveToExcel
{
/// <summary>
/// Создать отчет Excel
/// </summary>
/// <param name="info"></param>
public void CreateReport(ExcelInfo info)
{
// Создаем файл
CreateExcel(info);
// Создаем заголовок таблицы
// "Список животных."
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = 1,
Text = info.Title,
StyleInfo = ExcelStyleInfoType.Title
});
// Объединяем ячейки A1:H1 для заголовка таблицы
MergeCells(new ExcelMergeParameters
{
CellFromName = "A1",
CellToName = "H1"
});
// Записываем основную информацию
uint rowIndex = 2;
foreach (var view in info.AnimalServices)
{
// "Животное:"
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = rowIndex,
Text = "Животное:",
StyleInfo = ExcelStyleInfoType.SubtitleWithBorder
});
// Номер животного "№X"
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "B",
RowIndex = rowIndex,
Text = $"№{view.Animal.Id}",
StyleInfo = ExcelStyleInfoType.TextWithBorder
});
// "Вид:"
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "C",
RowIndex = rowIndex,
Text = "Вид:",
StyleInfo = ExcelStyleInfoType.SubtitleWithBorder
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "D",
RowIndex = rowIndex,
Text = $"{view.Animal.Type}",
StyleInfo = ExcelStyleInfoType.TextWithBorder
});
// "Порода:"
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "E",
RowIndex = rowIndex,
Text = "Порода:",
StyleInfo = ExcelStyleInfoType.SubtitleWithBorder
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "F",
RowIndex = rowIndex,
Text = $"{view.Animal.Breed}",
StyleInfo = ExcelStyleInfoType.TextWithBorder
});
// "Возраст:"
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "G",
RowIndex = rowIndex,
Text = "Возраст:",
StyleInfo = ExcelStyleInfoType.SubtitleWithBorder
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "H",
RowIndex = rowIndex,
Text = $"{view.Animal.Age}",
StyleInfo = ExcelStyleInfoType.TextWithBorder
});
rowIndex++;
// "Услуги:"
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = rowIndex,
Text = "Услуги:",
StyleInfo = ExcelStyleInfoType.Subtitle
});
MergeCells(new ExcelMergeParameters
{
CellFromName = "A" + rowIndex,
CellToName = "B" + rowIndex
});
// Список услуг
foreach (var service in view.Services)
{
// "Название услуги"
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "C",
RowIndex = rowIndex,
Text = $"{service.Name}",
StyleInfo = ExcelStyleInfoType.Text
});
MergeCells(new ExcelMergeParameters
{
CellFromName = "C" + rowIndex,
CellToName = "E" + rowIndex
});
// "Стоимость услуги"
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "F",
RowIndex = rowIndex,
Text = $"{service.Cost}",
StyleInfo = ExcelStyleInfoType.Text
});
MergeCells(new ExcelMergeParameters
{
CellFromName = "F" + rowIndex,
CellToName = "H" + rowIndex
});
rowIndex++;
}
}
SaveExcel(info);
}
/// <summary>
/// Создать файл Excel
/// </summary>
/// <param name="info"></param>
protected abstract void CreateExcel(ExcelInfo info);
/// <summary>
/// Добавить новую ячейку в лист
/// </summary>
/// <param name="excelParams"></param>
protected abstract void InsertCellInWorksheet(ExcelCellParameters excelParams);
/// <summary>
/// Объединить ячейки
/// </summary>
/// <param name="excelParams"></param>
protected abstract void MergeCells(ExcelMergeParameters excelParams);
/// <summary>
/// Сохранить файл Excel
/// </summary>
/// <param name="info"></param>
protected abstract void SaveExcel(ExcelInfo info);
}
}

View File

@ -0,0 +1,119 @@
using VeterinaryClinicBusinessLogics.OfficePackage.HelperEnums;
using VeterinaryClinicBusinessLogics.OfficePackage.HelperModels;
using VeterinaryClinicContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VeterinaryClinicBusinessLogics.OfficePackage
{
/// <summary>
/// Абстрактный класс для создания отчета Pdf
/// </summary>
public abstract class AbstractSaveToPdf
{
/// <summary>
/// Создать отчет Pdf
/// </summary>
/// <param name="info"></param>
public void CreateReport(PdfInfo info)
{
// Создаем файл
CreatePdf(info);
// Создаем заголовок
// "Сведения по визитам."
CreateParagraph(new PdfParagraph
{
Text = info.Title,
Style = "NormalTitle"
});
// Период выборки данных
// "с XX.XX.XXXX по XX.XX.XXXX"
CreateParagraph(new PdfParagraph
{
Text = $"С {info.DateFrom.ToShortDateString()} по {info.DateTo.ToShortDateString()}",
Style = "Normal"
});
// Создаем таблицу с тремя колонками
CreateTable(new List<string> { "7cm", "4cm", "4cm" });
// Создаем заголовок таблицы
// "Визит" | "Медикаменты" | "Вакцинации"
CreateRow(new PdfRowParameters
{
Texts = new List<string> { "Визит", "Медикаменты", "Вакцинации" },
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
// Записываем основную информацию
foreach (var view in info.VisitsInfo)
{
// Записываем номер визита - дата
CreateRow(new PdfRowParameters
{
Texts = new List<string> { view.Visit.Id.ToString(), " - ", view.Visit.Date.ToString() },
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
// Конвертируем из HashSet в List, чтобы можно было обращаться по индексу
List<MedicationViewModel> medications = new List<MedicationViewModel>(view.Medications);
List<VaccinationViewModel> vaccinations = new List<VaccinationViewModel>(view.Vaccinations);
// Записываем названия медикамента во 2 колонку
// и названия вакцинации в 3 колонку
int maxLength = Math.Max(medications.Count, vaccinations.Count);
for (int i = 0; i < maxLength; i++)
{
string medication = (i < medications.Count) ? medications[i].Name : "";
string vaccination = (i < vaccinations.Count) ? vaccinations[i].Name : "";
CreateRow(new PdfRowParameters
{
Texts = new List<string> { "", medication, vaccination },
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
}
}
// Сохраняем файл
SavePdf(info);
}
/// <summary>
/// Создать файл Pdf
/// </summary>
/// <param name="info"></param>
protected abstract void CreatePdf(PdfInfo info);
/// <summary>
/// Создать абзац с текстом
/// </summary>
/// <param name="paragraph"></param>
protected abstract void CreateParagraph(PdfParagraph paragraph);
/// <summary>
/// Создать таблицу
/// </summary>
/// <param name="columns"></param>
protected abstract void CreateTable(List<string> columns);
/// <summary>
/// Создать и заполнить строку
/// </summary>
/// <param name="rowParameters"></param>
protected abstract void CreateRow(PdfRowParameters rowParameters);
/// <summary>
/// Сохранить файл Pdf
/// </summary>
/// <param name="info"></param>
protected abstract void SavePdf(PdfInfo info);
}
}

View File

@ -0,0 +1,118 @@
using VeterinaryClinicBusinessLogics.OfficePackage.HelperEnums;
using VeterinaryClinicBusinessLogics.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VeterinaryClinicBusinessLogics.OfficePackage
{
/// <summary>
/// Абстрактный класс для создания отчета Word
/// </summary>
public abstract class AbstractSaveToWord
{
/// <summary>
/// Создать отчет Word
/// </summary>
/// <param name="info"></param>
public void CreateReport(WordInfo info)
{
// Создаем файл
CreateWord(info);
// Создаем заголовок
// "Список животных."
CreateParagraph(new WordParagraph
{
Texts = new List<(string, WordTextProperties)>
{
(info.Title, new WordTextProperties { Bold = true, Size = "24" })
},
TextProperties = new WordTextProperties
{
Size = "24",
JustificationType = WordJustificationType.Center
}
});
// Записываем основную информацию
foreach (var view in info.AnimalServices)
{
CreateParagraph(new WordParagraph
{
Texts = new List<(string, WordTextProperties)>
{
($"Животное №{view.Animal.Id}. ", new WordTextProperties { Bold = true, Size = "24" }),
($"Вид: ", new WordTextProperties { Bold = true, Size = "24" }),
(view.Animal.Type, new WordTextProperties { Bold = false, Size = "24" }),
($". Порода: ", new WordTextProperties { Bold = true, Size = "24" }),
(view.Animal.Breed, new WordTextProperties { Bold = false, Size = "24" }),
($". Возраст: ", new WordTextProperties { Bold = true, Size = "24" }),
(view.Animal.Age.ToString(), new WordTextProperties { Bold = false, Size = "24" })
},
TextProperties = new WordTextProperties
{
Size = "24",
JustificationType = WordJustificationType.Both
}
});
// "Услуги:"
CreateParagraph(new WordParagraph
{
Texts = new List<(string, WordTextProperties)>
{
("Услуги:", new WordTextProperties { Bold = true, Size = "24" })
},
TextProperties = new WordTextProperties
{
Size = "24",
JustificationType = WordJustificationType.Both
}
});
// Список Услуг
foreach (var service in view.Services)
{
// "Название услуги"
CreateParagraph(new WordParagraph
{
Texts = new List<(string, WordTextProperties)>
{
(service.Name.ToString(), new WordTextProperties { Bold = false, Size = "24" }),
($" - {service.Cost}", new WordTextProperties { Bold = false, Size = "24" })
},
TextProperties = new WordTextProperties
{
Size = "24",
JustificationType = WordJustificationType.Both
}
});
}
}
// Сохраняем файл
SaveWord(info);
}
/// <summary>
/// Создать файл Word
/// </summary>
/// <param name="info"></param>
protected abstract void CreateWord(WordInfo info);
/// <summary>
/// Создать абзац с текстом
/// </summary>
/// <param name="paragraph"></param>
protected abstract void CreateParagraph(WordParagraph paragraph);
/// <summary>
/// Сохранить файл Word
/// </summary>
/// <param name="info"></param>
protected abstract void SaveWord(WordInfo info);
}
}

View File

@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VeterinaryClinicBusinessLogics.OfficePackage.HelperEnums
{
/// <summary>
/// Тип стиля текста Excel
/// </summary>
public enum ExcelStyleInfoType
{
/// <summary>
/// Заголовок
/// </summary>
Title,
/// <summary>
/// Подзаголовок
/// </summary>
Subtitle,
/// <summary>
/// Обычный текст
/// </summary>
Text,
/// <summary>
/// Обычный текст с границами
/// </summary>
TextWithBorder,
/// <summary>
/// Подзаголовок с границами
/// </summary>
SubtitleWithBorder
}
}

View File

@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VeterinaryClinicBusinessLogics.OfficePackage.HelperEnums
{
/// <summary>
/// Тип выравнивания текста Pdf
/// </summary>
public enum PdfParagraphAlignmentType
{
/// <summary>
/// По центру
/// </summary>
Center,
/// <summary>
/// По левому краю
/// </summary>
Left,
/// <summary>
/// По правому краю
/// </summary>
Right
}
}

View File

@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VeterinaryClinicBusinessLogics.OfficePackage.HelperEnums
{
/// <summary>
/// Тип выравнивания текста Word
/// </summary>
public enum WordJustificationType
{
/// <summary>
/// По центру
/// </summary>
Center,
/// <summary>
/// По ширине
/// </summary>
Both
}
}

View File

@ -0,0 +1,40 @@
using VeterinaryClinicBusinessLogics.OfficePackage.HelperEnums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VeterinaryClinicBusinessLogics.OfficePackage.HelperModels
{
/// <summary>
/// Модель для описания свойств ячейки Excel
/// </summary>
public class ExcelCellParameters
{
/// <summary>
/// Название колонки
/// </summary>
public string ColumnName { get; set; } = string.Empty;
/// <summary>
/// Номер строки
/// </summary>
public uint RowIndex { get; set; }
/// <summary>
/// Текст ячейки
/// </summary>
public string Text { get; set; } = string.Empty;
/// <summary>
/// Получение ячейки
/// </summary>
public string CellReference => $"{ColumnName}{RowIndex}";
/// <summary>
/// Стиль ячейки
/// </summary>
public ExcelStyleInfoType StyleInfo { get; set; }
}
}

View File

@ -0,0 +1,30 @@
using VeterinaryClinicContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VeterinaryClinicBusinessLogics.OfficePackage.HelperModels
{
/// <summary>
/// Модель для создания отчета Excel
/// </summary>
public class ExcelInfo
{
/// <summary>
/// Название файла
/// </summary>
public string FileName { get; set; } = string.Empty;
/// <summary>
/// Заголовок
/// </summary>
public string Title { get; set; } = string.Empty;
/// <summary>
/// Информация
/// </summary>
public List<ReportAnimalServicesViewModel> AnimalServices { get; set; } = new();
}
}

View File

@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VeterinaryClinicBusinessLogics.OfficePackage.HelperModels
{
/// <summary>
/// Модель для описания объединенных ячеек Excel
/// </summary>
public class ExcelMergeParameters
{
/// <summary>
/// Начальная ячейка
/// </summary>
public string CellFromName { get; set; } = string.Empty;
/// <summary>
/// Конечная ячейка
/// </summary>
public string CellToName { get; set; } = string.Empty;
/// <summary>
/// Получить диапазон объединения ячеек
/// </summary>
public string Merge => $"{CellFromName}:{CellToName}";
}
}

View File

@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VeterinaryClinicContracts.ViewModels;
namespace VeterinaryClinicBusinessLogics.OfficePackage.HelperModels
{
/// <summary>
/// Модель для создания отчета Pdf
/// </summary>
public class PdfInfo
{
/// <summary>
/// Название файла
/// </summary>
public string FileName { get; set; } = string.Empty;
/// <summary>
/// Заголовок
/// </summary>
public string Title { get; set; } = string.Empty;
/// <summary>
/// Начало периода выборки данных
/// </summary>
public DateTime DateFrom { get; set; }
/// <summary>
/// Конец периода выборки данных
/// </summary>
public DateTime DateTo { get; set; }
/// <summary>
/// Информация
/// </summary>
public List<ReportVisitsViewModel> VisitsInfo { get; set; } = new();
}
}

View File

@ -0,0 +1,30 @@
using VeterinaryClinicBusinessLogics.OfficePackage.HelperEnums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VeterinaryClinicBusinessLogics.OfficePackage.HelperModels
{
/// <summary>
/// Модель для создания абзаца Pdf
/// </summary>
public class PdfParagraph
{
/// <summary>
/// Текст абзаца
/// </summary>
public string Text { get; set; } = string.Empty;
/// <summary>
/// Стиль текста
/// </summary>
public string Style { get; set; } = string.Empty;
/// <summary>
/// Тип выравнивания текста
/// </summary>
public PdfParagraphAlignmentType ParagraphAlignment { get; set; }
}
}

View File

@ -0,0 +1,30 @@
using VeterinaryClinicBusinessLogics.OfficePackage.HelperEnums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VeterinaryClinicBusinessLogics.OfficePackage.HelperModels
{
/// <summary>
/// Модель для создания строки Pdf
/// </summary>
public class PdfRowParameters
{
/// <summary>
/// Список текстов
/// </summary>
public List<string> Texts { get; set; } = new();
/// <summary>
/// Стиль текста
/// </summary>
public string Style { get; set; } = string.Empty;
/// <summary>
/// Тип выравнивания текста
/// </summary>
public PdfParagraphAlignmentType ParagraphAlignment { get; set; }
}
}

View File

@ -0,0 +1,30 @@
using VeterinaryClinicContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VeterinaryClinicBusinessLogics.OfficePackage.HelperModels
{
/// <summary>
/// Модель для создания отчета Word
/// </summary>
public class WordInfo
{
/// <summary>
/// Название файла
/// </summary>
public string FileName { get; set; } = string.Empty;
/// <summary>
/// Заголовок
/// </summary>
public string Title { get; set; } = string.Empty;
/// <summary>
/// Информация
/// </summary>
public List<ReportAnimalServicesViewModel> AnimalServices { get; set; } = new();
}
}

View File

@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VeterinaryClinicBusinessLogics.OfficePackage.HelperModels
{
/// <summary>
/// Модель для создания абзаца Word
/// </summary>
public class WordParagraph
{
/// <summary>
/// Список текстов в абзаце
/// </summary>
public List<(string, WordTextProperties)> Texts { get; set; } = new();
/// <summary>
/// Свойства абзаца
/// </summary>
public WordTextProperties? TextProperties { get; set; }
}
}

View File

@ -0,0 +1,30 @@
using VeterinaryClinicBusinessLogics.OfficePackage.HelperEnums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VeterinaryClinicBusinessLogics.OfficePackage.HelperModels
{
/// <summary>
/// Модель для описания свойств абзаца Word
/// </summary>
public class WordTextProperties
{
/// <summary>
/// Размер шрифта
/// </summary>
public string Size { get; set; } = string.Empty;
/// <summary>
/// Толщина шрифта
/// </summary>
public bool Bold { get; set; }
/// <summary>
/// Тип выравнивания текста
/// </summary>
public WordJustificationType JustificationType { get; set; }
}
}

View File

@ -0,0 +1,355 @@
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Office2010.Excel;
using DocumentFormat.OpenXml.Office2013.Excel;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using VeterinaryClinicBusinessLogics.OfficePackage.HelperEnums;
using VeterinaryClinicBusinessLogics.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VeterinaryClinicBusinessLogics.OfficePackage.Implements
{
/// <summary>
/// Реализация абстрактного класса для создания отчета Excel
/// </summary>
public class SaveToExcel : AbstractSaveToExcel
{
/// <summary>
/// Документ
/// </summary>
private SpreadsheetDocument? _spreadsheetDocument;
/// <summary>
/// Таблица общих строк
/// </summary>
private SharedStringTablePart? _shareStringPart;
/// <summary>
/// Рабочий лист
/// </summary>
private Worksheet? _worksheet;
/// <summary>
/// Настроить стили для файла
/// </summary>
/// <param name="workbookPart"></param>
private static void CreateStyles(WorkbookPart workbookPart)
{
var sp = workbookPart.AddNewPart<WorkbookStylesPart>();
sp.Stylesheet = new Stylesheet();
// Создание шрифтов
var fonts = new Fonts() { Count = 2U, KnownFonts = true };
// Шрифт обычного текста
var fontUsual = new Font();
fontUsual.Append(new FontSize() { Val = 12D });
fontUsual.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Theme = 1U });
fontUsual.Append(new FontName() { Val = "Times New Roman" });
fontUsual.Append(new FontFamilyNumbering() { Val = 2 });
fontUsual.Append(new FontScheme() { Val = FontSchemeValues.Minor });
// Шрифт заголовка
var fontTitle = new Font();
fontTitle.Append(new Bold());
fontTitle.Append(new FontSize() { Val = 14D });
fontTitle.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Theme = 1U });
fontTitle.Append(new FontName() { Val = "Times New Roman" });
fontTitle.Append(new FontFamilyNumbering() { Val = 2 });
fontTitle.Append(new FontScheme() { Val = FontSchemeValues.Minor });
fonts.Append(fontUsual);
fonts.Append(fontTitle);
// Создание заливок
var fills = new Fills() { Count = 1U };
// Пустая заливка
var fillNone = new Fill();
fillNone.Append(new PatternFill() { PatternType = PatternValues.None });
fills.Append(fillNone);
// Создание границ
var borders = new Borders() { Count = 3U };
// Пустая граница
var borderNoBorder = new Border();
borderNoBorder.Append(new LeftBorder());
borderNoBorder.Append(new RightBorder());
borderNoBorder.Append(new TopBorder());
borderNoBorder.Append(new BottomBorder());
borderNoBorder.Append(new DiagonalBorder());
// Толстая граница
var borderThick = new Border();
var leftBorderThick = new LeftBorder() { Style = BorderStyleValues.Thick };
leftBorderThick.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
var rightBorderThick = new RightBorder() { Style = BorderStyleValues.Thick };
rightBorderThick.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
var topBorderThick = new TopBorder() { Style = BorderStyleValues.Thick };
topBorderThick.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
var bottomBorderThick = new BottomBorder() { Style = BorderStyleValues.Thick };
bottomBorderThick.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
borderThick.Append(leftBorderThick);
borderThick.Append(rightBorderThick);
borderThick.Append(topBorderThick);
borderThick.Append(bottomBorderThick);
borderThick.Append(new DiagonalBorder());
// Верхняя толстая граница и нижняя тонкая граница
var borderCombo = new Border();
var topBorderCombo = new TopBorder() { Style = BorderStyleValues.Thick };
topBorderCombo.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
var bottomBorderCombo = new BottomBorder() { Style = BorderStyleValues.Thin };
bottomBorderCombo.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
borderCombo.Append(new LeftBorder());
borderCombo.Append(new RightBorder());
borderCombo.Append(topBorderCombo);
borderCombo.Append(bottomBorderCombo);
borderCombo.Append(new DiagonalBorder());
borders.Append(borderNoBorder);
borders.Append(borderThick);
borders.Append(borderCombo);
// Создаем форматы стилей ячеек
var cellStyleFormats = new CellStyleFormats() { Count = 1U };
var cellFormatStyle = new CellFormat() { NumberFormatId = 0U, FontId = 0U, FillId = 0U, BorderId = 0U };
cellStyleFormats.Append(cellFormatStyle);
// Создаем форматы ячеек
var cellFormats = new CellFormats() { Count = 5U };
var cellFormatFont = new CellFormat() { NumberFormatId = 0U, FontId = 0U, FillId = 0U, BorderId = 0U, FormatId = 0U, ApplyFont = true };
var cellFormatFontAndBorder = new CellFormat() { NumberFormatId = 0U, FontId = 0U, FillId = 0U, BorderId = 2U, FormatId = 0U, ApplyFont = true, ApplyBorder = true };
var cellFormatSubtitleAndBorder = new CellFormat() { NumberFormatId = 0U, FontId = 1U, FillId = 0U, BorderId = 2U, FormatId = 0U, ApplyFont = true, ApplyBorder = true };
var cellFormatSubtitle = new CellFormat() { NumberFormatId = 0U, FontId = 1U, FillId = 0U, BorderId = 0U, FormatId = 0U, ApplyFont = true };
var cellFormatTitle = new CellFormat() { NumberFormatId = 0U, FontId = 1U, FillId = 0U, BorderId = 1U, FormatId = 0U, Alignment = new Alignment() { Vertical = VerticalAlignmentValues.Center, WrapText = true, Horizontal = HorizontalAlignmentValues.Center }, ApplyFont = true, ApplyBorder = true };
cellFormats.Append(cellFormatFont);
cellFormats.Append(cellFormatFontAndBorder);
cellFormats.Append(cellFormatSubtitleAndBorder);
cellFormats.Append(cellFormatSubtitle);
cellFormats.Append(cellFormatTitle);
// Создаем стили ячеек
var cellStyles = new CellStyles() { Count = 1U };
cellStyles.Append(new CellStyle() { Name = "Normal", FormatId = 0U, BuiltinId = 0U });
var differentialFormats = new DocumentFormat.OpenXml.Office2013.Excel.DifferentialFormats() { Count = 0U };
var tableStyles = new TableStyles() { Count = 0U, DefaultTableStyle = "TableStyleMedium2", DefaultPivotStyle = "PivotStyleLight16" };
// Список расширений стилей
var stylesheetExtensionList = new StylesheetExtensionList();
var stylesheetExtension1 = new StylesheetExtension() { Uri = "{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}" };
stylesheetExtension1.AddNamespaceDeclaration("x14", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main");
stylesheetExtension1.Append(new SlicerStyles() { DefaultSlicerStyle = "SlicerStyleLight1" });
var stylesheetExtension2 = new StylesheetExtension() { Uri = "{9260A510-F301-46a8-8635-F512D64BE5F5}" };
stylesheetExtension2.AddNamespaceDeclaration("x15", "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main");
stylesheetExtension2.Append(new TimelineStyles() { DefaultTimelineStyle = "TimeSlicerStyleLight1" });
stylesheetExtensionList.Append(stylesheetExtension1);
stylesheetExtensionList.Append(stylesheetExtension2);
// Добавляем все стили
sp.Stylesheet.Append(fonts);
sp.Stylesheet.Append(fills);
sp.Stylesheet.Append(borders);
sp.Stylesheet.Append(cellStyleFormats);
sp.Stylesheet.Append(cellFormats);
sp.Stylesheet.Append(cellStyles);
sp.Stylesheet.Append(differentialFormats);
sp.Stylesheet.Append(tableStyles);
sp.Stylesheet.Append(stylesheetExtensionList);
}
/// <summary>
/// Получить номер стиля по типу
/// </summary>
/// <param name="styleInfo"></param>
/// <returns></returns>
private static uint GetStyleValue(ExcelStyleInfoType styleInfo)
{
return styleInfo switch
{
ExcelStyleInfoType.Title => 4U,
ExcelStyleInfoType.Subtitle => 3U,
ExcelStyleInfoType.SubtitleWithBorder => 2U,
ExcelStyleInfoType.TextWithBorder => 1U,
ExcelStyleInfoType.Text => 0U,
_ => 0U,
};
}
/// <summary>
/// Создать файл Excel
/// </summary>
/// <param name="info"></param>
protected override void CreateExcel(ExcelInfo info)
{
_spreadsheetDocument = SpreadsheetDocument.Create(info.FileName, SpreadsheetDocumentType.Workbook);
// Создаем книгу (в ней хранятся листы)
var workbookpart = _spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
// Настраиваем стили
CreateStyles(workbookpart);
// Получаем/создаем хранилище текстов для книги
_shareStringPart = _spreadsheetDocument.WorkbookPart!.GetPartsOfType<SharedStringTablePart>().Any()
? _spreadsheetDocument.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First()
: _spreadsheetDocument.WorkbookPart.AddNewPart<SharedStringTablePart>();
// Создаем SharedStringTable, если его нет
if (_shareStringPart.SharedStringTable == null)
{
_shareStringPart.SharedStringTable = new SharedStringTable();
}
// Создаем лист в книгу
var worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
// Добавляем лист в книгу
var sheets = _spreadsheetDocument.WorkbookPart.Workbook.AppendChild(new Sheets());
var sheet = new Sheet()
{
Id = _spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Лист"
};
sheets.Append(sheet);
_worksheet = worksheetPart.Worksheet;
}
/// <summary>
/// Добавить новую ячейку в лист
/// </summary>
/// <param name="excelParams"></param>
protected override void InsertCellInWorksheet(ExcelCellParameters excelParams)
{
if (_worksheet == null || _shareStringPart == null)
{
return;
}
var sheetData = _worksheet.GetFirstChild<SheetData>();
if (sheetData == null)
{
return;
}
// Ищем строку, либо добавляем ее
Row row;
if (sheetData.Elements<Row>().Where(r => r.RowIndex! == excelParams.RowIndex).Any())
{
row = sheetData.Elements<Row>().Where(r => r.RowIndex! == excelParams.RowIndex).First();
}
else
{
row = new Row() { RowIndex = excelParams.RowIndex };
sheetData.Append(row);
}
// Ищем нужную ячейку
Cell cell;
if (row.Elements<Cell>().Where(c => c.CellReference!.Value == excelParams.CellReference).Any())
{
cell = row.Elements<Cell>().Where(c => c.CellReference!.Value == excelParams.CellReference).First();
}
else
{
// Все ячейки должны быть последовательно расположены друг за другом
// нужно определить, после какой вставлять
Cell? refCell = null;
foreach (Cell rowCell in row.Elements<Cell>())
{
if (string.Compare(rowCell.CellReference!.Value, excelParams.CellReference, true) > 0)
{
refCell = rowCell;
break;
}
}
var newCell = new Cell() { CellReference = excelParams.CellReference };
row.InsertBefore(newCell, refCell);
cell = newCell;
}
// Вставляем новый текст
_shareStringPart.SharedStringTable.AppendChild(new SharedStringItem(new Text(excelParams.Text)));
_shareStringPart.SharedStringTable.Save();
cell.CellValue = new CellValue((_shareStringPart.SharedStringTable.Elements<SharedStringItem>().Count() - 1).ToString());
cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
cell.StyleIndex = GetStyleValue(excelParams.StyleInfo);
}
/// <summary>
/// Объединить ячейки
/// </summary>
/// <param name="excelParams"></param>
protected override void MergeCells(ExcelMergeParameters excelParams)
{
if (_worksheet == null)
{
return;
}
MergeCells mergeCells;
if (_worksheet.Elements<MergeCells>().Any())
{
mergeCells = _worksheet.Elements<MergeCells>().First();
}
else
{
mergeCells = new MergeCells();
if (_worksheet.Elements<CustomSheetView>().Any())
{
_worksheet.InsertAfter(mergeCells, _worksheet.Elements<CustomSheetView>().First());
}
else
{
_worksheet.InsertAfter(mergeCells, _worksheet.Elements<SheetData>().First());
}
}
var mergeCell = new MergeCell()
{
Reference = new StringValue(excelParams.Merge)
};
mergeCells.Append(mergeCell);
}
/// <summary>
/// Сохранить файл Excel
/// </summary>
/// <param name="info"></param>
protected override void SaveExcel(ExcelInfo info)
{
if (_spreadsheetDocument == null)
{
return;
}
_spreadsheetDocument.WorkbookPart!.Workbook.Save();
_spreadsheetDocument.Dispose();
}
}
}

View File

@ -0,0 +1,157 @@
using VeterinaryClinicBusinessLogics.OfficePackage.HelperEnums;
using VeterinaryClinicBusinessLogics.OfficePackage.HelperModels;
using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Tables;
using MigraDoc.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VeterinaryClinicBusinessLogics.OfficePackage.Implements
{
/// <summary>
/// Реализация абстрактного класса для создания отчета Word
/// </summary>
public class SaveToPdf : AbstractSaveToPdf
{
/// <summary>
/// Документ
/// </summary>
private Document? _document;
/// <summary>
/// Секция
/// </summary>
private Section? _section;
/// <summary>
/// Таблица
/// </summary>
private Table? _table;
/// <summary>
/// Получить тип выравнивания текста
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
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;
}
/// <summary>
/// Создать файл Pdf
/// </summary>
/// <param name="info"></param>
protected override void CreatePdf(PdfInfo info)
{
_document = new Document();
DefineStyles(_document);
_section = _document.AddSection();
}
/// <summary>
/// Создать абзац с текстом
/// </summary>
/// <param name="pdfParagraph"></param>
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;
}
/// <summary>
/// Создать таблицу
/// </summary>
/// <param name="columns"></param>
protected override void CreateTable(List<string> columns)
{
if (_document == null)
{
return;
}
_table = _document.LastSection.AddTable();
foreach (var column in columns)
{
_table.AddColumn(column);
}
}
/// <summary>
/// Создать и заполнить строку
/// </summary>
/// <param name="rowParameters"></param>
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;
}
}
/// <summary>
/// Сохранить файл Pdf
/// </summary>
/// <param name="info"></param>
protected override void SavePdf(PdfInfo info)
{
var renderer = new PdfDocumentRenderer(true)
{
Document = _document
};
renderer.RenderDocument();
renderer.PdfDocument.Save(info.FileName);
}
}
}

View File

@ -0,0 +1,163 @@
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using VeterinaryClinicBusinessLogics.OfficePackage.HelperEnums;
using VeterinaryClinicBusinessLogics.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VeterinaryClinicBusinessLogics.OfficePackage.Implements
{
/// <summary>
/// Реализация абстрактного класса для создания отчета Word
/// </summary>
public class SaveToWord : AbstractSaveToWord
{
/// <summary>
/// Документ
/// </summary>
private WordprocessingDocument? _wordDocument;
/// <summary>
/// Тело документа
/// </summary>
private Body? _docBody;
/// <summary>
/// Получить тип выравнивания текста
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
private static JustificationValues GetJustificationValues(WordJustificationType type)
{
return type switch
{
WordJustificationType.Both => JustificationValues.Both,
WordJustificationType.Center => JustificationValues.Center,
_ => JustificationValues.Left,
};
}
/// <summary>
/// Настройки станицы
/// </summary>
/// <returns></returns>
private static SectionProperties CreateSectionProperties()
{
var properties = new SectionProperties();
var pageSize = new PageSize
{
Orient = PageOrientationValues.Portrait
};
properties.AppendChild(pageSize);
return properties;
}
/// <summary>
/// Задать форматирование для абзаца
/// </summary>
/// <param name="paragraphProperties"></param>
/// <returns></returns>
private static ParagraphProperties? CreateParagraphProperties(WordTextProperties? paragraphProperties)
{
if (paragraphProperties == null)
{
return null;
}
var properties = new ParagraphProperties();
properties.AppendChild(new Justification()
{
Val = GetJustificationValues(paragraphProperties.JustificationType)
});
properties.AppendChild(new SpacingBetweenLines
{
LineRule = LineSpacingRuleValues.Auto
});
properties.AppendChild(new Indentation());
var paragraphMarkRunProperties = new ParagraphMarkRunProperties();
if (!string.IsNullOrEmpty(paragraphProperties.Size))
{
paragraphMarkRunProperties.AppendChild(new FontSize { Val = paragraphProperties.Size });
}
properties.AppendChild(paragraphMarkRunProperties);
return properties;
}
/// <summary>
/// Создать файл Word
/// </summary>
/// <param name="info"></param>
protected override void CreateWord(WordInfo info)
{
_wordDocument = WordprocessingDocument.Create(info.FileName, WordprocessingDocumentType.Document);
MainDocumentPart mainPart = _wordDocument.AddMainDocumentPart();
mainPart.Document = new Document();
_docBody = mainPart.Document.AppendChild(new Body());
}
/// <summary>
/// Создать абзац с текстом
/// </summary>
/// <param name="paragraph"></param>
protected override void CreateParagraph(WordParagraph paragraph)
{
if (_docBody == null || paragraph == null)
{
return;
}
var docParagraph = new Paragraph();
docParagraph.AppendChild(CreateParagraphProperties(paragraph.TextProperties));
foreach (var run in paragraph.Texts)
{
var docRun = new Run();
var properties = new RunProperties();
properties.AppendChild(new FontSize { Val = run.Item2.Size });
if (run.Item2.Bold)
{
properties.AppendChild(new Bold());
}
docRun.AppendChild(properties);
docRun.AppendChild(new Text
{
Text = run.Item1,
Space = SpaceProcessingModeValues.Preserve
});
docParagraph.AppendChild(docRun);
}
_docBody.AppendChild(docParagraph);
}
/// <summary>
/// Сохранить файл Word
/// </summary>
/// <param name="info"></param>
protected override void SaveWord(WordInfo info)
{
if (_docBody == null || _wordDocument == null)
{
return;
}
_docBody.AppendChild(CreateSectionProperties());
_wordDocument.MainDocumentPart!.Document.Save();
_wordDocument.Dispose();
}
}
}

View File

@ -7,7 +7,9 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="DocumentFormat.OpenXml" Version="3.0.2" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="PdfSharp.MigraDoc.Standard" Version="1.51.15" />
</ItemGroup>
<ItemGroup>

View File

@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VeterinaryClinicContracts.BindingModels
{
/// <summary>
/// Модель привязки для настройки почтового сервиса
/// </summary>
public class MailConfigBindingModel
{
/// <summary>
/// Логин для доступа к почтовому сервису
/// </summary>
public string MailLogin { get; set; } = string.Empty;
/// <summary>
/// Пароль для доступа к почтовому сервису
/// </summary>
public string MailPassword { get; set; } = string.Empty;
/// <summary>
/// Хост SMTP-клиента
/// </summary>
public string SmtpClientHost { get; set; } = string.Empty;
/// <summary>
/// Порт SMTP-клиента
/// </summary>
public int SmtpClientPort { get; set; }
/// <summary>
/// Хост протокола POP3
/// </summary>
public string PopHost { get; set; } = string.Empty;
/// <summary>
/// Порт протокола POP3
/// </summary>
public int PopPort { get; set; }
}
}

View File

@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VeterinaryClinicContracts.BindingModels
{
/// <summary>
/// Модель привязки для отправки письма
/// </summary>
public class MailSendInfoBindingModel
{
/// <summary>
/// Адрес электронной почты
/// </summary>
public string MailAddress { get; set; } = string.Empty;
/// <summary>
/// Заголовок письма
/// </summary>
public string Subject { get; set; } = string.Empty;
/// <summary>
/// Текст письма
/// </summary>
public string Text { get; set; } = string.Empty;
/// <summary>
/// Путь до файла
/// </summary>
public string Path { get; set; } = string.Empty;
}
}

View File

@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VeterinaryClinicContracts.BindingModels
{
/// <summary>
/// Модель привязки для создания отчета
/// </summary>
public class ReportBindingModel
{
/// <summary>
/// Название файла
/// </summary>
public string FileName { get; set; } = string.Empty;
/// <summary>
/// Начало периода выборки данных
/// </summary>
public DateTime? DateFrom { get; set; }
/// <summary>
/// Конец периода выборки данных
/// </summary>
public DateTime? DateTo { get; set; }
/// <summary>
/// Идентификатор пользователя
/// </summary>
public int UserId { get; set; }
}
}

View File

@ -0,0 +1,48 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VeterinaryClinicContracts.BindingModels;
using VeterinaryClinicContracts.ViewModels;
namespace VeterinaryClinicContracts.BusinessLogicsContracts
{
/// <summary>
/// Интерфейс для описания работы бизнес-логики для отчетов
/// </summary>
public interface IReportLogic
{
/// <summary>
/// Получить список животных с расшифровкой по услугам
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
List<ReportAnimalServicesViewModel> GetAnimalServices(ReportBindingModel model);
/// <summary>
/// Получить список визитов с расшифровкой по медикаментам и прививкам
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
List<ReportVisitsViewModel> GetVisitsInfo(ReportBindingModel model);
/// <summary>
/// Сохранить список животных с расшифровкой по услугам в файл Word
/// </summary>
/// <param name="model"></param>
void SaveAnimalServicesToWordFile(ReportBindingModel model);
/// <summary>
/// Сохранить список животных с расшифровкой по услугам в файл Excel
/// </summary>
/// <param name="model"></param>
void SaveAnimalServicesToExcelFile(ReportBindingModel model);
/// <summary>
/// Сохранить список визитов с расшифровкой по медикаментам и прививкам в Pdf файл
/// </summary>
/// <param name="model"></param>
void SaveVisitsInfoToPdfFile(ReportBindingModel model);
}
}

View File

@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VeterinaryClinicContracts.ViewModels
{
/// <summary>
/// Модель представления для отчета
/// списки услуг по животному
/// </summary>
public class ReportAnimalServicesViewModel
{
/// <summary>
/// Животное
/// </summary>
public AnimalViewModel Animal { get; set; } = new();
/// <summary>
/// Список услуг
/// </summary>
public HashSet<ServiceViewModel> Services { get; set; } = new();
}
}

View File

@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VeterinaryClinicContracts.ViewModels
{
/// <summary>
/// Модель представления для отчета
/// по визитам с расшифровкой по медикаментам и прививкам
/// </summary>
public class ReportVisitsViewModel
{
/// <summary>
/// Визит
/// </summary>
public VisitViewModel Visit { get; set; } = new();
/// <summary>
/// Список медикаментов
/// </summary>
public HashSet<MedicationViewModel> Medications { get; set; } = new();
/// <summary>
/// Список прививок
/// </summary>
public HashSet<VaccinationViewModel> Vaccinations { get; set; } = new();
}
}

View File

@ -46,6 +46,13 @@ namespace VeterinaryClinicDatabaseImplement.Implements
.ToList();
}
if (model.DateFrom.HasValue && model.DateTo.HasValue)
{
filtered = filtered
.Where(x => x.Date >= model.DateFrom && x.Date <= model.DateTo)
.ToList();
}
return filtered ?? new();
}

View File

@ -3,6 +3,9 @@ using VeterinaryClinicContracts.BusinessLogicsContracts;
using VeterinaryClinicContracts.StoragesContracts;
using VeterinaryClinicDatabaseImplement.Implements;
using Microsoft.OpenApi.Models;
using VeterinaryClinicBusinessLogics.OfficePackage.Implements;
using VeterinaryClinicBusinessLogics.OfficePackage;
using VeterinaryClinicBusinessLogics.MailWorker;
var builder = WebApplication.CreateBuilder(args);
@ -25,6 +28,11 @@ builder.Services.AddTransient<IUserLogic, UserLogic>();
builder.Services.AddTransient<IVaccinationLogic, VaccinationLogic>();
builder.Services.AddTransient<IVisitLogic, VisitLogic>();
builder.Services.AddTransient<IReportLogic, ReportLogic>();
builder.Services.AddTransient<AbstractSaveToWord, SaveToWord>();
builder.Services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
builder.Services.AddTransient<AbstractSaveToPdf, SaveToPdf>();
builder.Services.AddSingleton<AbstractMailWorker, MailKitWorker>();
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle

View File

@ -5,5 +5,11 @@
"Microsoft.AspNetCore": "Warning"
}
},
"SmtpClientHost": "smtp.gmail.com",
"SmtpClientPort": "587",
"PopHost": "pop.gmail.com",
"PopPort": "995",
"MailLogin": "hugolyter@gmail.com",
"MailPassword": "erpt vlrs aogd xoun",
"AllowedHosts": "*"
}

View File

@ -1,5 +1,6 @@
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using VeterinaryClinicBusinessLogics.MailWorker;
using VeterinaryClinicContracts.BindingModels;
using VeterinaryClinicContracts.BusinessLogicsContracts;
using VeterinaryClinicContracts.SearchModels;
@ -14,10 +15,23 @@ public class HomeController : Controller
private readonly IUserLogic _userLogic;
public HomeController(ILogger<HomeController> logger, IUserLogic userLogic)
private readonly IAnimalLogic _animalLogic;
private readonly IReportLogic _reportLogic;
private readonly AbstractMailWorker _mailLogic;
public HomeController(ILogger<HomeController> logger,
IUserLogic userLogic,
IAnimalLogic animalLogic,
IReportLogic reportLogic,
AbstractMailWorker mailLogic)
{
_logger = logger;
_userLogic = userLogic;
_animalLogic = animalLogic;
_reportLogic = reportLogic;
_mailLogic = mailLogic;
}
/// <summary>
@ -166,22 +180,141 @@ public class HomeController : Controller
/// <summary>
/// Ïîëó÷èòü îò÷åò
/// </summary>
[HttpGet]
public IActionResult Reports()
{
if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
}
return View();
}
/// <summary>
/// Âûâåñòè íà ôîðìó îò÷¸ò
/// </summary>
[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);
}
/// <summary>
/// Ñîçäàòü îò÷¸ò â ôîðìàòå Word
/// </summary>
[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");
}
/// <summary>
/// Ñîçäàòü îò÷¸ò â ôîðìàòå Excel
/// </summary>
[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");
}
/// <summary>
/// Ñîçäàòü îò÷¸ò â ôîðìàòå Pdf
/// </summary>
[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");
}
/// <summary>
/// Îòïðàâèòü ïî ïî÷òå îò÷¸ò
/// </summary>
[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");
}
/// <summary>
/// Îøèáêà

View File

@ -1,10 +1,12 @@
using Microsoft.AspNetCore.Http;
using DocumentFormat.OpenXml.Office2010.Excel;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using VeterinaryClinicBusinessLogics.BusinessLogics;
using VeterinaryClinicContracts.BindingModels;
using VeterinaryClinicContracts.BusinessLogicsContracts;
using VeterinaryClinicContracts.SearchModels;
using VeterinaryClinicDatabaseImplement.Models;
using VeterinaryClinicDataModels.Models;
using VeterinaryClinicWebApp.Models;
@ -54,35 +56,24 @@ namespace VeterinaryClinicWebApp.Controllers
return Redirect("~/Home/Enter");
}
ViewBag.Animals = _animalLogic.ReadList(new AnimalSearchModel
{
UserId = APIClient.User.Id,
});
ViewBag.Services = _serviceLogic.ReadList(null);
return View();
}
[HttpPost]
public void CreateVisit(DateTime dateVisit, List<int> animal, List<int> service)
public void CreateVisit(DateTime dateVisit, List<int> service)
{
if (APIClient.User == null)
{
throw new Exception("Необходимо авторизоваться!");
}
if (dateVisit == DateTime.MinValue || animal == null || service == null)
if (dateVisit == DateTime.MinValue || service == null)
{
throw new Exception("Введены не все данные!");
}
Dictionary<int, IAnimalModel> visitAnimals = new Dictionary<int, IAnimalModel>();
foreach (var animalId in animal)
{
visitAnimals.Add(animalId, _animalLogic.ReadElement(new AnimalSearchModel { Id = animalId })!);
}
Dictionary<int, IServiceModel> visitServices = new Dictionary<int, IServiceModel>();
foreach (var serviceId in service)
{
@ -92,7 +83,6 @@ namespace VeterinaryClinicWebApp.Controllers
_visitLogic.Create(new VisitBindingModel
{
Date = dateVisit,
VisitAnimals = visitAnimals,
VisitServices = visitServices,
UserId = APIClient.User.Id
});
@ -111,11 +101,6 @@ namespace VeterinaryClinicWebApp.Controllers
return Redirect("~/Home/Enter");
}
ViewBag.Animals = _animalLogic.ReadList(new AnimalSearchModel
{
UserId = APIClient.User.Id,
});
ViewBag.Services = _serviceLogic.ReadList(null);
return View(_visitLogic.ReadElement(new VisitSearchModel
@ -125,37 +110,32 @@ namespace VeterinaryClinicWebApp.Controllers
}
[HttpPost]
public void UpdateVisit(int id, DateTime dateVisit, List<int> animal, List<int> service)
public void UpdateVisit(int id, DateTime dateVisit, List<int> service)
{
if (APIClient.User == null)
{
throw new Exception("Необходимо авторизоваться!");
}
if (dateVisit == DateTime.MinValue || animal == null || service == null)
if (dateVisit == DateTime.MinValue || service == null)
{
throw new Exception("Введены не все данные!");
}
Dictionary<int, IAnimalModel> visitAnimals = new Dictionary<int, IAnimalModel>();
foreach (var animalId in animal)
{
visitAnimals.Add(animalId, _animalLogic.ReadElement(new AnimalSearchModel { Id = animalId })!);
}
Dictionary<int, IServiceModel> visitServices = new Dictionary<int, IServiceModel>();
foreach (var serviceId in service)
{
visitServices.Add(serviceId, _serviceLogic.ReadElement(new ServiceSearchModel { Id = serviceId })!);
}
_visitLogic.Update(new VisitBindingModel
var visit = _visitLogic.ReadElement(new VisitSearchModel { Id = id });
_visitLogic.Update(new VisitBindingModel
{
Id = id,
Date = dateVisit,
VisitAnimals = visitAnimals,
VisitServices = visitServices,
UserId = APIClient.User.Id
VisitAnimals = visit!.VisitAnimals,
UserId = APIClient.User.Id
});
Response.Redirect("/Visit/Visits");
@ -179,5 +159,67 @@ namespace VeterinaryClinicWebApp.Controllers
Response.Redirect("/Visit/Visits");
}
}
/// <summary>
/// Выписать рецепт пациенту
/// </summary>
/// <returns></returns>
/// <exception cref="Exception"></exception>
[HttpGet]
public IActionResult CreateVisitAnimal()
{
if (APIClient.User == null)
{
throw new Exception("Необходимо авторизоваться!");
}
ViewBag.Visits = _visitLogic.ReadList(new VisitSearchModel
{
UserId = APIClient.User.Id
});
ViewBag.Animals = _animalLogic.ReadList(new AnimalSearchModel
{
UserId = APIClient.User.Id
});
return View();
}
/// <summary>
/// Выписать рецепт пациенту
/// </summary>
/// <exception cref="Exception"></exception>
[HttpPost]
public void CreateVisitAnimal(int visitId, List<int> animals)
{
if (APIClient.User == null)
{
throw new Exception("Необходимо авторизоваться!");
}
if (visitId <= 0 || animals == null)
{
throw new Exception("Введены не все данные!");
}
Dictionary<int, IAnimalModel> visitAnimals = new Dictionary<int, IAnimalModel>();
foreach (var animalId in animals)
{
visitAnimals.Add(animalId, _animalLogic.ReadElement(new AnimalSearchModel { Id = animalId })!);
}
var visit = _visitLogic.ReadElement(new VisitSearchModel { Id = visitId });
_visitLogic.Update(new VisitBindingModel
{
Id = visit!.Id,
Date = visit!.Date,
VisitServices = visit!.VisitServices,
VisitAnimals = visitAnimals,
UserId = APIClient.User.Id
});
Response.Redirect("/Visit/Visits");
}
}
}

View File

@ -1,8 +1,11 @@
using VeterinaryClinicBusinessLogics.BusinessLogics;
using VeterinaryClinicBusinessLogics.OfficePackage.Implements;
using VeterinaryClinicBusinessLogics.OfficePackage;
using VeterinaryClinicContracts.BusinessLogicsContracts;
using VeterinaryClinicContracts.StoragesContracts;
using VeterinaryClinicDatabaseImplement.Implements;
using VeterinaryClinicWebApp;
using VeterinaryClinicBusinessLogics.MailWorker;
var builder = WebApplication.CreateBuilder(args);
@ -25,6 +28,12 @@ builder.Services.AddTransient<IUserLogic, UserLogic>();
builder.Services.AddTransient<IVaccinationLogic, VaccinationLogic>();
builder.Services.AddTransient<IVisitLogic, VisitLogic>();
builder.Services.AddTransient<IReportLogic, ReportLogic>();
builder.Services.AddTransient<AbstractSaveToWord, SaveToWord>();
builder.Services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
builder.Services.AddTransient<AbstractSaveToPdf, SaveToPdf>();
builder.Services.AddSingleton<AbstractMailWorker, MailKitWorker>();
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(30);

View File

@ -0,0 +1,98 @@
@using VeterinaryClinicContracts.ViewModels
@model List<ReportVisitsViewModel>
@{
ViewBag.Title = "Отчеты";
}
<div class="text-center">
<h2 class="display-4">Отчеты</h2>
</div>
<form method="post" enctype="multipart/form-data" style="margin-top: 50px">
<!-- Сохранить отчеты в формате Word и Excel -->
<div class="d-flex justify-content-center" style="gap: 30px">
<div class="text-center">
<button type="submit" class="btn btn-primary" formaction="@Url.Action("CreateReportWord", "Home")">Список услуг Word</button>
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary" formaction="@Url.Action("CreateReportExcel", "Home")">Список услуг Excel</button>
</div>
</div>
<!-- Временной период выборки данных -->
<div class="d-flex justify-content-center" style="margin: 30px 0px">
<div class="text-center">
<label for="dateFrom">С</label>
<input type="date" id="dateFrom" name="dateFrom" class="form-control d-inline-block w-auto">
</div>
<div class="text-center">
<label for="dateTo">по</label>
<input type="date" id="dateTo" name="dateTo" class="form-control d-inline-block w-auto">
</div>
</div>
<!-- Действия для отчета в формате Pdf -->
<div class="d-flex justify-content-between">
<!-- Сохранить отчет в формате Pdf -->
<div class="text-center">
<button type="submit" class="btn btn-primary" formaction="@Url.Action("CreateReportPdf", "Home")">Сведения о визитах Pdf</button>
</div>
<!-- Отправить отчет на почту -->
<div class="d-flex">
<label for="fileUpload" class="d-block"></label>
<input type="file" id="fileUpload" name="fileUpload" class="form-control-file d-inline-block w-auto">
<button type="submit" class="btn btn-primary" formaction="@Url.Action("SendReport", "Home")">Отправить отчет на почту</button>
</div>
<!-- Вывести отчет на форму -->
<div class="text-center">
<button type="submit" class="btn btn-primary" formaction="@Url.Action("Reports", "Home")">Вывести отчет на форму</button>
</div>
</div>
</form>
<!-- Таблица для вывода отчета на форму -->
<table class="table">
<thead>
<tr>
<th>Визит</th>
<th>Медикаменты</th>
<th>Вакцинации</th>
</tr>
</thead>
<tbody>
@if (Model == null || Model.Count <= 0)
{
<td class="text-center" colspan="3">Нет доступных данных</td>
}
else
{
foreach (var record in Model)
{
// номер визита - дата
<td>@record.Visit.Id - @record.Visit.Date</td>
<td></td>
<td></td>
// Конвертируем из HashSet в List, чтобы можно было обращаться по индексу
var medications = new List<MedicationViewModel>(record.Medications);
var vaccinations = new List<VaccinationViewModel>(record.Vaccinations);
// Записываем названия медикаментов во 2 колонку
// и названия вакцинаций в 3 колонку
int maxLength = Math.Max(medications.Count, vaccinations.Count);
for (int i = 0; i < maxLength; i++)
{
<tr>
<td></td>
<td>@(i < medications.Count ? medications[i].Name : "")</td>
<td>@(i < vaccinations.Count ? vaccinations[i].Name + " - " + vaccinations[i].DateInjection.ToShortTimeString() : "")</td>
</tr>
}
}
}
</tbody>
</table>

View File

@ -39,9 +39,13 @@
<a class="nav-link text-dark" asp-area="" asp-controller="Visit" asp-action="Visits">Визиты</a>
</li>
<!-- Выписка визитов (привязка животных к визитам) -->
@* <li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Visit" asp-action="CreateVisitAnimals">Выписать визит</a>
</li> *@
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Visit" asp-action="CreateVisitAnimal">Добавить животного на визит</a>
</li>
<!-- Отчеты -->
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Reports">Отчеты</a>
</li>
</ul>
<ul class="navbar-nav ms-auto">
<!-- Личные данные -->

View File

@ -13,19 +13,6 @@
<div class="col-8"><input type="datetime-local" class="form-control" name="dateVisit" id="dateVisit" /></div>
</div>
<!-- Животные -->
<div class="row">
<div class="col-4">Животные:</div>
<div class="col-8">
<select name="animal" id="animal" class="form-control" size="4" multiple>
@foreach (var animal in ViewBag.Animals)
{
<option value="@animal.Id">@animal.Breed</option>
}
</select>
</div>
</div>
<!-- Услуги -->
<div class="row">
<div class="col-4">Услуги:</div>

View File

@ -0,0 +1,41 @@
@{
ViewData["Title"] = "Добавить животного на визит";
}
<div class="text-center">
<h2 class="display-4">Добавить животного на визит</h2>
</div>
<form method="post" style="margin-top: 50px">
<!-- Визиты -->
<div class="row">
<div class="col-4">Визиты:</div>
<div class="col-8">
<select name="visitId" id="visitId" class="form-control">
@foreach (var visit in ViewBag.Visits)
{
<option value="@visit.Id">@visit.Id - @visit.Date.ToShortDateString()</option>
}
</select>
</div>
</div>
<!-- Животные -->
<div class="row">
<div class="col-4">Животные:</div>
<div class="col-8">
<select name="animals" id="animals" class="form-control" size="4" multiple>
@foreach (var animal in ViewBag.Animals)
{
<option value="@animal.Id">@animal.Breed - @animal.Age</option>
}
</select>
</div>
</div>
<!-- Кнопка "Добавить" -->
<div class="row">
<div class="col-8"></div>
<div class="col-4"><input type="submit" value="Добавить" class="btn btn-primary" /></div>
</div>
</form>

View File

@ -18,20 +18,6 @@
<div class="col-8"><input type="datetime-local" class="form-control" name="dateVisit" value="@Model.Date.ToString("yyyy-MM-ddTHH:mm")" /></div>
</div>
<!-- Животные -->
<div class="row">
<div class="col-4">Животные:</div>
<div class="col-8">
<select name="animal" id="animal" class="form-control" size="4" multiple>
@foreach (var animal in ViewBag.Animals)
{
var isSelected = Model.VisitAnimals.Any(x => x.Key.Equals(animal.Id));
<option value="@animal.Id" selected="@isSelected">@animal.Breed</option>
}
</select>
</div>
</div>
<!-- Услуги -->
<div class="row">
<div class="col-4">Услуги:</div>

View File

@ -53,7 +53,7 @@
}
else
{
<p>Нет назначенных лекарств</p>
<p>Нет назначенных животных</p>
}
</td>
<td>
@ -68,7 +68,7 @@
}
else
{
<p>Нет назначенных лекарств</p>
<p>Нет назначенных услуг</p>
}
</td>
<td>