diff --git a/VeterinaryClinic/VeterinaryClinicBusinessLogics/BusinessLogics/ReportLogic.cs b/VeterinaryClinic/VeterinaryClinicBusinessLogics/BusinessLogics/ReportLogic.cs new file mode 100644 index 0000000..410524d --- /dev/null +++ b/VeterinaryClinic/VeterinaryClinicBusinessLogics/BusinessLogics/ReportLogic.cs @@ -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; + } + + /// + /// Получить список животных с расшифровкой по услугам + /// + /// + /// + public List GetAnimalServices(ReportBindingModel model) + { + var result = new List(); + + // Получаем список животных по идентификатору пользователя + 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() + }; + + // Проходим по списку всех визитов + 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; + } + + /// + /// Получить список визитов с расшифровкой по медикаментам и прививкам + /// + /// + /// + public List GetVisitsInfo(ReportBindingModel model) + { + var result = new List(); + + // Получаем список визитов отсортированных по дате и пользователю + 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(), + Vaccinations = new HashSet() + }; + + // Проходим по списку животных + 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) + }); + } + } +} diff --git a/VeterinaryClinic/VeterinaryClinicBusinessLogics/MailWorker/AbstractMailWorker.cs b/VeterinaryClinic/VeterinaryClinicBusinessLogics/MailWorker/AbstractMailWorker.cs new file mode 100644 index 0000000..fae95a3 --- /dev/null +++ b/VeterinaryClinic/VeterinaryClinicBusinessLogics/MailWorker/AbstractMailWorker.cs @@ -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 + { + /// + /// Логгер + /// + private readonly ILogger _logger; + + /// + /// Логин для доступа к почтовому сервису + /// + protected string _mailLogin = string.Empty; + + /// + /// Пароль для доступа к почтовому сервису + /// + protected string _mailPassword = string.Empty; + + /// + /// Хост SMTP-клиента + /// + protected string _smtpClientHost = string.Empty; + + /// + /// Порт SMTP-клиента + /// + protected int _smtpClientPort; + + /// + /// Хост протокола POP3 + /// + protected string _popHost = string.Empty; + + /// + /// Порт протокола POP3 + /// + protected int _popPort; + + /// + /// Конструктор + /// + /// + public AbstractMailWorker(ILogger logger) + { + _logger = logger; + } + + /// + /// Настроить почтовый сервис + /// + /// + 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.Path)) + { + return; + } + + _logger.LogDebug("Send Mail: {To}, {Subject}", info.MailAddress, info.Subject); + await SendMailAsync(info); + } + + /// + /// Отправить письмо + /// + /// + /// + protected abstract Task SendMailAsync(MailSendInfoBindingModel info); + } +} diff --git a/VeterinaryClinic/VeterinaryClinicBusinessLogics/MailWorker/MailKitWorker.cs b/VeterinaryClinic/VeterinaryClinicBusinessLogics/MailWorker/MailKitWorker.cs new file mode 100644 index 0000000..568146d --- /dev/null +++ b/VeterinaryClinic/VeterinaryClinicBusinessLogics/MailWorker/MailKitWorker.cs @@ -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 + { + /// + /// Конструктор + /// + /// + public MailKitWorker(ILogger logger) : base(logger) { } + + /// + /// Отправить письмо + /// + /// + /// + 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; + } + } + } +} diff --git a/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/AbstractSaveToExcel.cs b/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/AbstractSaveToExcel.cs new file mode 100644 index 0000000..1c7e51c --- /dev/null +++ b/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/AbstractSaveToExcel.cs @@ -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 +{ + /// + /// Абстрактный класс для создания отчета Excel + /// + public abstract class AbstractSaveToExcel + { + /// + /// Создать отчет Excel + /// + /// + 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); + } + + /// + /// Создать файл Excel + /// + /// + protected abstract void CreateExcel(ExcelInfo info); + + /// + /// Добавить новую ячейку в лист + /// + /// + protected abstract void InsertCellInWorksheet(ExcelCellParameters excelParams); + + /// + /// Объединить ячейки + /// + /// + protected abstract void MergeCells(ExcelMergeParameters excelParams); + + /// + /// Сохранить файл Excel + /// + /// + protected abstract void SaveExcel(ExcelInfo info); + } +} diff --git a/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/AbstractSaveToPdf.cs b/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/AbstractSaveToPdf.cs new file mode 100644 index 0000000..97bfad1 --- /dev/null +++ b/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/AbstractSaveToPdf.cs @@ -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 +{ + /// + /// Абстрактный класс для создания отчета Pdf + /// + public abstract class AbstractSaveToPdf + { + /// + /// Создать отчет Pdf + /// + /// + 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 { "7cm", "4cm", "4cm" }); + + // Создаем заголовок таблицы + // "Визит" | "Медикаменты" | "Вакцинации" + CreateRow(new PdfRowParameters + { + Texts = new List { "Визит", "Медикаменты", "Вакцинации" }, + Style = "NormalTitle", + ParagraphAlignment = PdfParagraphAlignmentType.Center + }); + + // Записываем основную информацию + foreach (var view in info.VisitsInfo) + { + // Записываем номер визита - дата + CreateRow(new PdfRowParameters + { + Texts = new List { view.Visit.Id.ToString(), " - ", view.Visit.Date.ToString() }, + Style = "Normal", + ParagraphAlignment = PdfParagraphAlignmentType.Left + }); + + // Конвертируем из HashSet в List, чтобы можно было обращаться по индексу + List medications = new List(view.Medications); + List vaccinations = new List(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 { "", medication, vaccination }, + Style = "Normal", + ParagraphAlignment = PdfParagraphAlignmentType.Left + }); + } + } + + // Сохраняем файл + SavePdf(info); + } + + /// + /// Создать файл Pdf + /// + /// + protected abstract void CreatePdf(PdfInfo info); + + /// + /// Создать абзац с текстом + /// + /// + protected abstract void CreateParagraph(PdfParagraph paragraph); + + /// + /// Создать таблицу + /// + /// + protected abstract void CreateTable(List columns); + + /// + /// Создать и заполнить строку + /// + /// + protected abstract void CreateRow(PdfRowParameters rowParameters); + + /// + /// Сохранить файл Pdf + /// + /// + protected abstract void SavePdf(PdfInfo info); + } +} diff --git a/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/AbstractSaveToWord.cs b/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/AbstractSaveToWord.cs new file mode 100644 index 0000000..0571ae9 --- /dev/null +++ b/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/AbstractSaveToWord.cs @@ -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 +{ + /// + /// Абстрактный класс для создания отчета Word + /// + public abstract class AbstractSaveToWord + { + /// + /// Создать отчет Word + /// + /// + 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); + } + + /// + /// Создать файл Word + /// + /// + protected abstract void CreateWord(WordInfo info); + + /// + /// Создать абзац с текстом + /// + /// + protected abstract void CreateParagraph(WordParagraph paragraph); + + /// + /// Сохранить файл Word + /// + /// + protected abstract void SaveWord(WordInfo info); + } +} diff --git a/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/HelperEnums/ExcelStyleInfoType.cs b/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/HelperEnums/ExcelStyleInfoType.cs new file mode 100644 index 0000000..5777b5d --- /dev/null +++ b/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/HelperEnums/ExcelStyleInfoType.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace VeterinaryClinicBusinessLogics.OfficePackage.HelperEnums +{ + /// + /// Тип стиля текста Excel + /// + public enum ExcelStyleInfoType + { + /// + /// Заголовок + /// + Title, + + /// + /// Подзаголовок + /// + Subtitle, + + /// + /// Обычный текст + /// + Text, + + /// + /// Обычный текст с границами + /// + TextWithBorder, + + /// + /// Подзаголовок с границами + /// + SubtitleWithBorder + } +} diff --git a/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/HelperEnums/PdfParagraphAlignmentType.cs b/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/HelperEnums/PdfParagraphAlignmentType.cs new file mode 100644 index 0000000..f52ef60 --- /dev/null +++ b/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/HelperEnums/PdfParagraphAlignmentType.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace VeterinaryClinicBusinessLogics.OfficePackage.HelperEnums +{ + /// + /// Тип выравнивания текста Pdf + /// + public enum PdfParagraphAlignmentType + { + /// + /// По центру + /// + Center, + + /// + /// По левому краю + /// + Left, + + /// + /// По правому краю + /// + Right + } +} diff --git a/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/HelperEnums/WordJustificationType.cs b/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/HelperEnums/WordJustificationType.cs new file mode 100644 index 0000000..bc1d92f --- /dev/null +++ b/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/HelperEnums/WordJustificationType.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace VeterinaryClinicBusinessLogics.OfficePackage.HelperEnums +{ + /// + /// Тип выравнивания текста Word + /// + public enum WordJustificationType + { + /// + /// По центру + /// + Center, + + /// + /// По ширине + /// + Both + } +} diff --git a/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/HelperModels/ExcelCellParameters.cs b/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/HelperModels/ExcelCellParameters.cs new file mode 100644 index 0000000..5b8b62e --- /dev/null +++ b/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/HelperModels/ExcelCellParameters.cs @@ -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 +{ + /// + /// Модель для описания свойств ячейки Excel + /// + public class ExcelCellParameters + { + /// + /// Название колонки + /// + public string ColumnName { get; set; } = string.Empty; + + /// + /// Номер строки + /// + public uint RowIndex { get; set; } + + /// + /// Текст ячейки + /// + public string Text { get; set; } = string.Empty; + + /// + /// Получение ячейки + /// + public string CellReference => $"{ColumnName}{RowIndex}"; + + /// + /// Стиль ячейки + /// + public ExcelStyleInfoType StyleInfo { get; set; } + } +} diff --git a/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/HelperModels/ExcelInfo.cs b/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/HelperModels/ExcelInfo.cs new file mode 100644 index 0000000..c3d0d3f --- /dev/null +++ b/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/HelperModels/ExcelInfo.cs @@ -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 +{ + /// + /// Модель для создания отчета Excel + /// + public class ExcelInfo + { + /// + /// Название файла + /// + public string FileName { get; set; } = string.Empty; + + /// + /// Заголовок + /// + public string Title { get; set; } = string.Empty; + + /// + /// Информация + /// + public List AnimalServices { get; set; } = new(); + } +} diff --git a/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/HelperModels/ExcelMergeParameters.cs b/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/HelperModels/ExcelMergeParameters.cs new file mode 100644 index 0000000..7d6ade8 --- /dev/null +++ b/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/HelperModels/ExcelMergeParameters.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace VeterinaryClinicBusinessLogics.OfficePackage.HelperModels +{ + /// + /// Модель для описания объединенных ячеек Excel + /// + public class ExcelMergeParameters + { + /// + /// Начальная ячейка + /// + public string CellFromName { get; set; } = string.Empty; + + /// + /// Конечная ячейка + /// + public string CellToName { get; set; } = string.Empty; + + /// + /// Получить диапазон объединения ячеек + /// + public string Merge => $"{CellFromName}:{CellToName}"; + } +} diff --git a/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/HelperModels/PdfInfo.cs b/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/HelperModels/PdfInfo.cs new file mode 100644 index 0000000..2a6446b --- /dev/null +++ b/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/HelperModels/PdfInfo.cs @@ -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 +{ + /// + /// Модель для создания отчета Pdf + /// + public class PdfInfo + { + /// + /// Название файла + /// + public string FileName { get; set; } = string.Empty; + + /// + /// Заголовок + /// + public string Title { get; set; } = string.Empty; + + /// + /// Начало периода выборки данных + /// + public DateTime DateFrom { get; set; } + + /// + /// Конец периода выборки данных + /// + public DateTime DateTo { get; set; } + + /// + /// Информация + /// + public List VisitsInfo { get; set; } = new(); + } +} diff --git a/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/HelperModels/PdfParagraph.cs b/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/HelperModels/PdfParagraph.cs new file mode 100644 index 0000000..807493d --- /dev/null +++ b/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/HelperModels/PdfParagraph.cs @@ -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 +{ + /// + /// Модель для создания абзаца Pdf + /// + public class PdfParagraph + { + /// + /// Текст абзаца + /// + public string Text { get; set; } = string.Empty; + + /// + /// Стиль текста + /// + public string Style { get; set; } = string.Empty; + + /// + /// Тип выравнивания текста + /// + public PdfParagraphAlignmentType ParagraphAlignment { get; set; } + } +} diff --git a/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/HelperModels/PdfRowParameters.cs b/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/HelperModels/PdfRowParameters.cs new file mode 100644 index 0000000..089ab6c --- /dev/null +++ b/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/HelperModels/PdfRowParameters.cs @@ -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 +{ + /// + /// Модель для создания строки Pdf + /// + public class PdfRowParameters + { + /// + /// Список текстов + /// + public List Texts { get; set; } = new(); + + /// + /// Стиль текста + /// + public string Style { get; set; } = string.Empty; + + /// + /// Тип выравнивания текста + /// + public PdfParagraphAlignmentType ParagraphAlignment { get; set; } + } +} diff --git a/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/HelperModels/WordInfo.cs b/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/HelperModels/WordInfo.cs new file mode 100644 index 0000000..3d11dba --- /dev/null +++ b/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/HelperModels/WordInfo.cs @@ -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 +{ + /// + /// Модель для создания отчета Word + /// + public class WordInfo + { + /// + /// Название файла + /// + public string FileName { get; set; } = string.Empty; + + /// + /// Заголовок + /// + public string Title { get; set; } = string.Empty; + + /// + /// Информация + /// + public List AnimalServices { get; set; } = new(); + } +} diff --git a/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/HelperModels/WordParagraph.cs b/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/HelperModels/WordParagraph.cs new file mode 100644 index 0000000..451ca33 --- /dev/null +++ b/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/HelperModels/WordParagraph.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace VeterinaryClinicBusinessLogics.OfficePackage.HelperModels +{ + /// + /// Модель для создания абзаца Word + /// + public class WordParagraph + { + /// + /// Список текстов в абзаце + /// + public List<(string, WordTextProperties)> Texts { get; set; } = new(); + + /// + /// Свойства абзаца + /// + public WordTextProperties? TextProperties { get; set; } + } +} diff --git a/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/HelperModels/WordTextProperties.cs b/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/HelperModels/WordTextProperties.cs new file mode 100644 index 0000000..b2952b7 --- /dev/null +++ b/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/HelperModels/WordTextProperties.cs @@ -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 +{ + /// + /// Модель для описания свойств абзаца Word + /// + public class WordTextProperties + { + /// + /// Размер шрифта + /// + public string Size { get; set; } = string.Empty; + + /// + /// Толщина шрифта + /// + public bool Bold { get; set; } + + /// + /// Тип выравнивания текста + /// + public WordJustificationType JustificationType { get; set; } + } +} diff --git a/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/Implements/SaveToExcel.cs b/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/Implements/SaveToExcel.cs new file mode 100644 index 0000000..f513e4a --- /dev/null +++ b/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/Implements/SaveToExcel.cs @@ -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 +{ + /// + /// Реализация абстрактного класса для создания отчета Excel + /// + public class SaveToExcel : AbstractSaveToExcel + { + /// + /// Документ + /// + private SpreadsheetDocument? _spreadsheetDocument; + + /// + /// Таблица общих строк + /// + private SharedStringTablePart? _shareStringPart; + + /// + /// Рабочий лист + /// + private Worksheet? _worksheet; + + /// + /// Настроить стили для файла + /// + /// + private static void CreateStyles(WorkbookPart workbookPart) + { + var sp = workbookPart.AddNewPart(); + 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); + } + + /// + /// Получить номер стиля по типу + /// + /// + /// + 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, + }; + } + + /// + /// Создать файл Excel + /// + /// + 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().Any() + ? _spreadsheetDocument.WorkbookPart.GetPartsOfType().First() + : _spreadsheetDocument.WorkbookPart.AddNewPart(); + + // Создаем SharedStringTable, если его нет + if (_shareStringPart.SharedStringTable == null) + { + _shareStringPart.SharedStringTable = new SharedStringTable(); + } + + // Создаем лист в книгу + var worksheetPart = workbookpart.AddNewPart(); + 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; + } + + /// + /// Добавить новую ячейку в лист + /// + /// + protected override void InsertCellInWorksheet(ExcelCellParameters excelParams) + { + if (_worksheet == null || _shareStringPart == null) + { + return; + } + + var sheetData = _worksheet.GetFirstChild(); + if (sheetData == null) + { + return; + } + + // Ищем строку, либо добавляем ее + Row row; + if (sheetData.Elements().Where(r => r.RowIndex! == excelParams.RowIndex).Any()) + { + row = sheetData.Elements().Where(r => r.RowIndex! == excelParams.RowIndex).First(); + } + else + { + row = new Row() { RowIndex = excelParams.RowIndex }; + sheetData.Append(row); + } + + // Ищем нужную ячейку + Cell cell; + if (row.Elements().Where(c => c.CellReference!.Value == excelParams.CellReference).Any()) + { + cell = row.Elements().Where(c => c.CellReference!.Value == excelParams.CellReference).First(); + } + else + { + // Все ячейки должны быть последовательно расположены друг за другом + // нужно определить, после какой вставлять + Cell? refCell = null; + foreach (Cell rowCell in row.Elements()) + { + 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().Count() - 1).ToString()); + cell.DataType = new EnumValue(CellValues.SharedString); + cell.StyleIndex = GetStyleValue(excelParams.StyleInfo); + } + + /// + /// Объединить ячейки + /// + /// + protected override void MergeCells(ExcelMergeParameters excelParams) + { + if (_worksheet == null) + { + return; + } + + MergeCells mergeCells; + if (_worksheet.Elements().Any()) + { + mergeCells = _worksheet.Elements().First(); + } + else + { + mergeCells = new MergeCells(); + + if (_worksheet.Elements().Any()) + { + _worksheet.InsertAfter(mergeCells, _worksheet.Elements().First()); + } + else + { + _worksheet.InsertAfter(mergeCells, _worksheet.Elements().First()); + } + } + + var mergeCell = new MergeCell() + { + Reference = new StringValue(excelParams.Merge) + }; + mergeCells.Append(mergeCell); + } + + /// + /// Сохранить файл Excel + /// + /// + protected override void SaveExcel(ExcelInfo info) + { + if (_spreadsheetDocument == null) + { + return; + } + + _spreadsheetDocument.WorkbookPart!.Workbook.Save(); + _spreadsheetDocument.Dispose(); + } + } +} diff --git a/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/Implements/SaveToPdf.cs b/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/Implements/SaveToPdf.cs new file mode 100644 index 0000000..b2f46ac --- /dev/null +++ b/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/Implements/SaveToPdf.cs @@ -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 +{ + /// + /// Реализация абстрактного класса для создания отчета Word + /// + public class SaveToPdf : AbstractSaveToPdf + { + /// + /// Документ + /// + 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, + }; + } + + /// + /// Настройки стилей + /// + /// + 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; + } + + /// + /// Создать файл Pdf + /// + /// + 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 columns) + { + if (_document == null) + { + return; + } + + _table = _document.LastSection.AddTable(); + foreach (var column in columns) + { + _table.AddColumn(column); + } + } + + /// + /// Создать и заполнить строку + /// + /// + 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; + } + } + + /// + /// Сохранить файл Pdf + /// + /// + protected override void SavePdf(PdfInfo info) + { + var renderer = new PdfDocumentRenderer(true) + { + Document = _document + }; + renderer.RenderDocument(); + renderer.PdfDocument.Save(info.FileName); + } + } +} diff --git a/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/Implements/SaveToWord.cs b/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/Implements/SaveToWord.cs new file mode 100644 index 0000000..35454ca --- /dev/null +++ b/VeterinaryClinic/VeterinaryClinicBusinessLogics/OfficePackage/Implements/SaveToWord.cs @@ -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 +{ + /// + /// Реализация абстрактного класса для создания отчета Word + /// + public class SaveToWord : AbstractSaveToWord + { + /// + /// Документ + /// + private WordprocessingDocument? _wordDocument; + + /// + /// Тело документа + /// + private Body? _docBody; + + /// + /// Получить тип выравнивания текста + /// + /// + /// + private static JustificationValues GetJustificationValues(WordJustificationType type) + { + return type switch + { + WordJustificationType.Both => JustificationValues.Both, + WordJustificationType.Center => JustificationValues.Center, + _ => JustificationValues.Left, + }; + } + + /// + /// Настройки станицы + /// + /// + private static SectionProperties CreateSectionProperties() + { + var properties = new SectionProperties(); + + var pageSize = new PageSize + { + Orient = PageOrientationValues.Portrait + }; + + properties.AppendChild(pageSize); + return properties; + } + + /// + /// Задать форматирование для абзаца + /// + /// + /// + 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; + } + + /// + /// Создать файл Word + /// + /// + 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()); + } + + /// + /// Создать абзац с текстом + /// + /// + 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); + } + + /// + /// Сохранить файл Word + /// + /// + protected override void SaveWord(WordInfo info) + { + if (_docBody == null || _wordDocument == null) + { + return; + } + + _docBody.AppendChild(CreateSectionProperties()); + _wordDocument.MainDocumentPart!.Document.Save(); + _wordDocument.Dispose(); + } + } +} diff --git a/VeterinaryClinic/VeterinaryClinicBusinessLogics/VeterinaryClinicBusinessLogics.csproj b/VeterinaryClinic/VeterinaryClinicBusinessLogics/VeterinaryClinicBusinessLogics.csproj index a3334f9..c5c7d75 100644 --- a/VeterinaryClinic/VeterinaryClinicBusinessLogics/VeterinaryClinicBusinessLogics.csproj +++ b/VeterinaryClinic/VeterinaryClinicBusinessLogics/VeterinaryClinicBusinessLogics.csproj @@ -7,7 +7,9 @@ + + diff --git a/VeterinaryClinic/VeterinaryClinicContracts/BindingModels/MailConfigBindingModel.cs b/VeterinaryClinic/VeterinaryClinicContracts/BindingModels/MailConfigBindingModel.cs new file mode 100644 index 0000000..495c74e --- /dev/null +++ b/VeterinaryClinic/VeterinaryClinicContracts/BindingModels/MailConfigBindingModel.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace VeterinaryClinicContracts.BindingModels +{ + /// + /// Модель привязки для настройки почтового сервиса + /// + public class MailConfigBindingModel + { + /// + /// Логин для доступа к почтовому сервису + /// + public string MailLogin { get; set; } = string.Empty; + + /// + /// Пароль для доступа к почтовому сервису + /// + public string MailPassword { get; set; } = string.Empty; + + /// + /// Хост SMTP-клиента + /// + public string SmtpClientHost { get; set; } = string.Empty; + + /// + /// Порт SMTP-клиента + /// + public int SmtpClientPort { get; set; } + + /// + /// Хост протокола POP3 + /// + public string PopHost { get; set; } = string.Empty; + + /// + /// Порт протокола POP3 + /// + public int PopPort { get; set; } + } +} diff --git a/VeterinaryClinic/VeterinaryClinicContracts/BindingModels/MailSendInfoBindingModel.cs b/VeterinaryClinic/VeterinaryClinicContracts/BindingModels/MailSendInfoBindingModel.cs new file mode 100644 index 0000000..4a4f2d2 --- /dev/null +++ b/VeterinaryClinic/VeterinaryClinicContracts/BindingModels/MailSendInfoBindingModel.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace VeterinaryClinicContracts.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; + + /// + /// Путь до файла + /// + public string Path { get; set; } = string.Empty; + } +} diff --git a/VeterinaryClinic/VeterinaryClinicContracts/BindingModels/ReportBindingModel.cs b/VeterinaryClinic/VeterinaryClinicContracts/BindingModels/ReportBindingModel.cs new file mode 100644 index 0000000..84e4c40 --- /dev/null +++ b/VeterinaryClinic/VeterinaryClinicContracts/BindingModels/ReportBindingModel.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace VeterinaryClinicContracts.BindingModels +{ + /// + /// Модель привязки для создания отчета + /// + public class ReportBindingModel + { + /// + /// Название файла + /// + public string FileName { get; set; } = string.Empty; + + /// + /// Начало периода выборки данных + /// + public DateTime? DateFrom { get; set; } + + /// + /// Конец периода выборки данных + /// + public DateTime? DateTo { get; set; } + + /// + /// Идентификатор пользователя + /// + public int UserId { get; set; } + } +} diff --git a/VeterinaryClinic/VeterinaryClinicContracts/BusinessLogicsContracts/IReportLogic.cs b/VeterinaryClinic/VeterinaryClinicContracts/BusinessLogicsContracts/IReportLogic.cs new file mode 100644 index 0000000..a5b42f3 --- /dev/null +++ b/VeterinaryClinic/VeterinaryClinicContracts/BusinessLogicsContracts/IReportLogic.cs @@ -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 +{ + /// + /// Интерфейс для описания работы бизнес-логики для отчетов + /// + public interface IReportLogic + { + /// + /// Получить список животных с расшифровкой по услугам + /// + /// + /// + List GetAnimalServices(ReportBindingModel model); + + /// + /// Получить список визитов с расшифровкой по медикаментам и прививкам + /// + /// + /// + List GetVisitsInfo(ReportBindingModel model); + + /// + /// Сохранить список животных с расшифровкой по услугам в файл Word + /// + /// + void SaveAnimalServicesToWordFile(ReportBindingModel model); + + /// + /// Сохранить список животных с расшифровкой по услугам в файл Excel + /// + /// + void SaveAnimalServicesToExcelFile(ReportBindingModel model); + + /// + /// Сохранить список визитов с расшифровкой по медикаментам и прививкам в Pdf файл + /// + /// + void SaveVisitsInfoToPdfFile(ReportBindingModel model); + } +} diff --git a/VeterinaryClinic/VeterinaryClinicContracts/ViewModels/ReportAnimalServicesViewModel.cs b/VeterinaryClinic/VeterinaryClinicContracts/ViewModels/ReportAnimalServicesViewModel.cs new file mode 100644 index 0000000..7fe4089 --- /dev/null +++ b/VeterinaryClinic/VeterinaryClinicContracts/ViewModels/ReportAnimalServicesViewModel.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace VeterinaryClinicContracts.ViewModels +{ + /// + /// Модель представления для отчета + /// списки услуг по животному + /// + public class ReportAnimalServicesViewModel + { + /// + /// Животное + /// + public AnimalViewModel Animal { get; set; } = new(); + + /// + /// Список услуг + /// + public HashSet Services { get; set; } = new(); + } +} diff --git a/VeterinaryClinic/VeterinaryClinicContracts/ViewModels/ReportVisitsViewModel.cs b/VeterinaryClinic/VeterinaryClinicContracts/ViewModels/ReportVisitsViewModel.cs new file mode 100644 index 0000000..82a91b5 --- /dev/null +++ b/VeterinaryClinic/VeterinaryClinicContracts/ViewModels/ReportVisitsViewModel.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace VeterinaryClinicContracts.ViewModels +{ + /// + /// Модель представления для отчета + /// по визитам с расшифровкой по медикаментам и прививкам + /// + public class ReportVisitsViewModel + { + /// + /// Визит + /// + public VisitViewModel Visit { get; set; } = new(); + + /// + /// Список медикаментов + /// + public HashSet Medications { get; set; } = new(); + + /// + /// Список прививок + /// + public HashSet Vaccinations { get; set; } = new(); + } +} diff --git a/VeterinaryClinic/VeterinaryClinicDatabaseImplement/Implements/VisitStorage.cs b/VeterinaryClinic/VeterinaryClinicDatabaseImplement/Implements/VisitStorage.cs index 976d744..22326ce 100644 --- a/VeterinaryClinic/VeterinaryClinicDatabaseImplement/Implements/VisitStorage.cs +++ b/VeterinaryClinic/VeterinaryClinicDatabaseImplement/Implements/VisitStorage.cs @@ -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(); } diff --git a/VeterinaryClinic/VeterinaryClinicRestApi/Program.cs b/VeterinaryClinic/VeterinaryClinicRestApi/Program.cs index 8371d89..45d0aaf 100644 --- a/VeterinaryClinic/VeterinaryClinicRestApi/Program.cs +++ b/VeterinaryClinic/VeterinaryClinicRestApi/Program.cs @@ -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(); builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddSingleton(); builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle diff --git a/VeterinaryClinic/VeterinaryClinicRestApi/appsettings.json b/VeterinaryClinic/VeterinaryClinicRestApi/appsettings.json index 10f68b8..beed6b4 100644 --- a/VeterinaryClinic/VeterinaryClinicRestApi/appsettings.json +++ b/VeterinaryClinic/VeterinaryClinicRestApi/appsettings.json @@ -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": "*" } diff --git a/VeterinaryClinic/VeterinaryClinicWebApp/Controllers/HomeController.cs b/VeterinaryClinic/VeterinaryClinicWebApp/Controllers/HomeController.cs index a62b34e..990ecb7 100644 --- a/VeterinaryClinic/VeterinaryClinicWebApp/Controllers/HomeController.cs +++ b/VeterinaryClinic/VeterinaryClinicWebApp/Controllers/HomeController.cs @@ -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 logger, IUserLogic userLogic) + private readonly IAnimalLogic _animalLogic; + + private readonly IReportLogic _reportLogic; + + private readonly AbstractMailWorker _mailLogic; + + public HomeController(ILogger logger, + IUserLogic userLogic, + IAnimalLogic animalLogic, + IReportLogic reportLogic, + AbstractMailWorker mailLogic) { _logger = logger; _userLogic = userLogic; + _animalLogic = animalLogic; + _reportLogic = reportLogic; + _mailLogic = mailLogic; } /// @@ -166,22 +180,141 @@ public class HomeController : Controller /// /// /// + [HttpGet] + public IActionResult Reports() + { + if (APIClient.User == null) + { + return Redirect("~/Home/Enter"); + } + + return View(); + } + + /// + /// + /// + [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); + } /// /// Word /// + [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"); + } /// /// Excel /// + [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"); + } /// /// Pdf /// + [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"); + } /// /// /// + [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"); + } /// /// diff --git a/VeterinaryClinic/VeterinaryClinicWebApp/Controllers/VisitController.cs b/VeterinaryClinic/VeterinaryClinicWebApp/Controllers/VisitController.cs index 52ee9e7..f0ead43 100644 --- a/VeterinaryClinic/VeterinaryClinicWebApp/Controllers/VisitController.cs +++ b/VeterinaryClinic/VeterinaryClinicWebApp/Controllers/VisitController.cs @@ -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 animal, List service) + public void CreateVisit(DateTime dateVisit, List 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 visitAnimals = new Dictionary(); - foreach (var animalId in animal) - { - visitAnimals.Add(animalId, _animalLogic.ReadElement(new AnimalSearchModel { Id = animalId })!); - } - Dictionary visitServices = new Dictionary(); 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 animal, List service) + public void UpdateVisit(int id, DateTime dateVisit, List 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 visitAnimals = new Dictionary(); - foreach (var animalId in animal) - { - visitAnimals.Add(animalId, _animalLogic.ReadElement(new AnimalSearchModel { Id = animalId })!); - } - Dictionary visitServices = new Dictionary(); 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"); } - } + + /// + /// Выписать рецепт пациенту + /// + /// + /// + [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(); + } + + /// + /// Выписать рецепт пациенту + /// + /// + [HttpPost] + public void CreateVisitAnimal(int visitId, List animals) + { + if (APIClient.User == null) + { + throw new Exception("Необходимо авторизоваться!"); + } + + if (visitId <= 0 || animals == null) + { + throw new Exception("Введены не все данные!"); + } + + Dictionary visitAnimals = new Dictionary(); + 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"); + } + } } diff --git a/VeterinaryClinic/VeterinaryClinicWebApp/Program.cs b/VeterinaryClinic/VeterinaryClinicWebApp/Program.cs index 1cd6d7b..816bbfa 100644 --- a/VeterinaryClinic/VeterinaryClinicWebApp/Program.cs +++ b/VeterinaryClinic/VeterinaryClinicWebApp/Program.cs @@ -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(); builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddSingleton(); + builder.Services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(30); diff --git a/VeterinaryClinic/VeterinaryClinicWebApp/Views/Home/Reports.cshtml b/VeterinaryClinic/VeterinaryClinicWebApp/Views/Home/Reports.cshtml new file mode 100644 index 0000000..f949d62 --- /dev/null +++ b/VeterinaryClinic/VeterinaryClinicWebApp/Views/Home/Reports.cshtml @@ -0,0 +1,98 @@ +@using VeterinaryClinicContracts.ViewModels + +@model List + +@{ + ViewBag.Title = "Отчеты"; +} + +
+

Отчеты

+
+ +
+ +
+
+ +
+
+ +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+ +
+ +
+ + +
+ + + +
+ + +
+ +
+
+
+ + + + + + + + + + + + @if (Model == null || Model.Count <= 0) + { + + } + else + { + foreach (var record in Model) + { + // номер визита - дата + + + + + // Конвертируем из HashSet в List, чтобы можно было обращаться по индексу + var medications = new List(record.Medications); + var vaccinations = new List(record.Vaccinations); + + // Записываем названия медикаментов во 2 колонку + // и названия вакцинаций в 3 колонку + int maxLength = Math.Max(medications.Count, vaccinations.Count); + for (int i = 0; i < maxLength; i++) + { + + + + + + } + } + } + +
ВизитМедикаментыВакцинации
Нет доступных данных@record.Visit.Id - @record.Visit.Date
@(i < medications.Count ? medications[i].Name : "")@(i < vaccinations.Count ? vaccinations[i].Name + " - " + vaccinations[i].DateInjection.ToShortTimeString() : "")
diff --git a/VeterinaryClinic/VeterinaryClinicWebApp/Views/Shared/_Layout.cshtml b/VeterinaryClinic/VeterinaryClinicWebApp/Views/Shared/_Layout.cshtml index 8090cb2..f3d6a1f 100644 --- a/VeterinaryClinic/VeterinaryClinicWebApp/Views/Shared/_Layout.cshtml +++ b/VeterinaryClinic/VeterinaryClinicWebApp/Views/Shared/_Layout.cshtml @@ -39,9 +39,13 @@ Визиты - @* *@ + + +