From 3b0aeddf2f47ffc1901e06ad493e7d53727b3f41 Mon Sep 17 00:00:00 2001 From: Bulat Date: Thu, 19 Dec 2024 16:31:11 +0400 Subject: [PATCH 1/3] good --- .../RegistrationPatientsPolyclinic/Reports/TableReport.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/TableReport.cs b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/TableReport.cs index 779aea8..8abee14 100644 --- a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/TableReport.cs +++ b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/TableReport.cs @@ -22,7 +22,7 @@ internal class TableReport private readonly ILogger _logger; - internal static readonly string[] item = ["Дата", "Описание", "Количество лекарства"]; + internal static readonly string[] item = ["Дата", "Описание", "Количество пациентов"]; public TableReport(IMedicalHistoryRepository medicalHistoryRepository, IDoctorPaymentsRepository doctorPaymentsRepository, ILogger logger) { From 63a67391e92d142c756ad183a60f9937aafc15e6 Mon Sep 17 00:00:00 2001 From: Bulat Date: Fri, 20 Dec 2024 09:29:01 +0400 Subject: [PATCH 2/3] =?UTF-8?q?=D0=B4=D0=BE=D0=BF=D0=B8=D0=BB=D0=B8=D0=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Reports/ChartReport.cs | 32 +++++++++++++- .../Reports/PdfBuilder.cs | 28 ++++++------ .../Reports/TableReport.cs | 10 ++--- .../Reports/WordBuilder.cs | 44 ++++++++++++------- 4 files changed, 76 insertions(+), 38 deletions(-) diff --git a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/ChartReport.cs b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/ChartReport.cs index 2584078..cadbe00 100644 --- a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/ChartReport.cs +++ b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/ChartReport.cs @@ -27,8 +27,8 @@ internal class ChartReport try { new PdfBuilder(filePath) - .AddHeader("Пополенение лекарства") - .AddPieChart("Виды лекарства", GetData(dateTime)) + .AddHeader("Количество посещений пациентов") + .AddPieChart("Пациенты", GetData(dateTime)) .Build(); return true; } @@ -38,6 +38,7 @@ internal class ChartReport return false; } } + /* private List<(string Caption, double Value)> GetData(DateTime dateTime) { // Получаем все медицинские истории за указанную дату @@ -49,4 +50,31 @@ internal class ChartReport .Select(g => (Caption: $"Patient {g.Key}", Value: (double)g.Count())) .ToList(); } + */ + private List<(string Caption, double Value)> GetData(DateTime dateTime) + { + var medicalHistories = _medicalHistoryRepository.ReadMedicalHistory(null, null, null, null); + + var filteredHistories = medicalHistories + .Where(mh => mh.VisitDate.Date == dateTime.Date) + .Where(mh => mh.DrugMedicalHistory != null && mh.DrugMedicalHistory.Any()) + .ToList(); + var groupedData = filteredHistories + .GroupBy( + mh => mh.DoctorId, + (key, group) => new + { + DoctorId = key, + TotalDrugs = group + .SelectMany(mh => mh.DrugMedicalHistory) + .Count() + } + ) + .ToList(); + var result = groupedData + .Select(x => (x.DoctorId.ToString(), (double)x.TotalDrugs)) + .ToList(); + + return result; + } } diff --git a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/PdfBuilder.cs b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/PdfBuilder.cs index e626ae0..0939123 100644 --- a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/PdfBuilder.cs +++ b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/PdfBuilder.cs @@ -26,38 +26,38 @@ internal class PdfBuilder } _filePath = filePath; _document = new Document(); - DefineStyles(); + DefineStyles(); // настройка стиля } - public PdfBuilder AddHeader(string header) + public PdfBuilder AddHeader(string header) // Заголовок, header - это текст заголовка { - _document.AddSection().AddParagraph(header, "NormalBold"); + _document.AddSection().AddParagraph(header, "NormalBold"); // документу добавляется секция добавляется параграф return this; } - public PdfBuilder AddPieChart(string title, List<(string Caption, double Value)> data) + public PdfBuilder AddPieChart(string title, List<(string Caption, double Value)> data) // метод добавления диаграммы круговой { if (data == null || data.Count == 0) { return this; } - var chart = new Chart(ChartType.Pie2D); - var series = chart.SeriesCollection.AddSeries(); + var chart = new Chart(ChartType.Pie2D); + var series = chart.SeriesCollection.AddSeries(); // добавляем серию series.Add(data.Select(x => x.Value).ToArray()); - var xseries = chart.XValues.AddXSeries(); + var xseries = chart.XValues.AddXSeries(); // добавляем подписи xseries.Add(data.Select(x => x.Caption).ToArray()); - chart.DataLabel.Type = DataLabelType.Percent; + chart.DataLabel.Type = DataLabelType.Percent; // вывод ввиде прицентов chart.DataLabel.Position = DataLabelPosition.OutsideEnd; - chart.Width = Unit.FromCentimeter(16); + chart.Width = Unit.FromCentimeter(16); // ширина и высота chart.Height = Unit.FromCentimeter(12); - chart.TopArea.AddParagraph(title); - chart.XAxis.MajorTickMark = TickMarkType.Outside; - chart.YAxis.MajorTickMark = TickMarkType.Outside; + chart.TopArea.AddParagraph(title); // заголовок добавляется + chart.XAxis.MajorTickMark = TickMarkType.Outside; // настраиваем где у нас будут подписи + chart.YAxis.MajorTickMark = TickMarkType.Outside; // настраиваем где у нас будут подписи chart.YAxis.HasMajorGridlines = true; chart.PlotArea.LineFormat.Width = 1; chart.PlotArea.LineFormat.Visible = true; - chart.TopArea.AddLegend(); - _document.LastSection.Add(chart); + chart.TopArea.AddLegend(); // где у нас будет легенда + _document.LastSection.Add(chart); // в документ добавляем нашу таблицу return this; } diff --git a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/TableReport.cs b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/TableReport.cs index 8abee14..393ea3e 100644 --- a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/TableReport.cs +++ b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/TableReport.cs @@ -22,7 +22,7 @@ internal class TableReport private readonly ILogger _logger; - internal static readonly string[] item = ["Дата", "Описание", "Количество пациентов"]; + internal static readonly string[] item = ["Id доктора", "Описание", "Количество пациентов"]; public TableReport(IMedicalHistoryRepository medicalHistoryRepository, IDoctorPaymentsRepository doctorPaymentsRepository, ILogger logger) { @@ -70,15 +70,15 @@ internal class TableReport .Where(x => x.VisitDate >= startDate && x.VisitDate <= endDate && x.DrugMedicalHistory.Any(y => y.DrugId == drugId) ) .Select(x => new { - Date = x.VisitDate, + Date = x.DoctorId, CountIn = x.DrugMedicalHistory.FirstOrDefault(y => y.DrugId == drugId)?.Description, CountOut = (int?)null }) .Union( _doctorPaymentsRepository .ReadDoctorPayments() - .Where(x => x.DoctorPaymentData >= startDate && x.DoctorPaymentData <= endDate) - .Select(x => new {Date = x.DoctorPaymentData, CountIn = (string?)null, CountOut = (int?)x.Count_Patient })) + .Where(x => x.IdDoctor!=0) + .Select(x => new {Date = x.IdDoctor, CountIn = (string?)null, CountOut = (int?)x.Count_Patient })) .OrderBy(x => x.Date); @@ -87,7 +87,7 @@ internal class TableReport data .Select(x => new string[] {x.Date.ToString(), x.CountIn ?? string.Empty, x.CountOut?.ToString() ?? string.Empty })) .Union( - new List() { new string[] { "Всего", data.Sum(x => x.CountOut ?? 0).ToString(), string.Empty } }) + new List() { new string[] { "Всего", string.Empty, data.Sum(x => x.CountOut ?? 0).ToString() } }) .ToList(); } diff --git a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/WordBuilder.cs b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/WordBuilder.cs index ca72689..5f04319 100644 --- a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/WordBuilder.cs +++ b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/WordBuilder.cs @@ -38,11 +38,13 @@ internal class WordBuilder public WordBuilder AddHeader(string header) { - // код ставки заголовка - var paragraph = _body.AppendChild(new Paragraph()); - var run = paragraph.AppendChild(new Run()); + // код ставки заголовка в документ Word + var paragraph = _body.AppendChild(new Paragraph()); // в body добавляем новый элемент дочерний это будет параграф + var run = paragraph.AppendChild(new Run()); // добавление блока + // жирный шрифт var runProperties = run.AppendChild(new RunProperties()); runProperties.AppendChild(new Bold()); + // добавляем текст run.AppendChild(new Text(header)); return this; @@ -50,7 +52,7 @@ internal class WordBuilder public WordBuilder AddParagraph(string text) { - // код ставки заголовка + // код ставки параграфа var paragraph = _body.AppendChild(new Paragraph()); var run = paragraph.AppendChild(new Run()); @@ -59,7 +61,12 @@ internal class WordBuilder } public WordBuilder AddTable(int[] widths, List data) - { + { // int[] width - будет передаваться массив intов + // Табличка в Word состоит из 3-ех блоков + // 1-ый блок: свойство . Здесь будем задавать границы + // 2-ой блок: колонки или Grid там передадим информацию по колонкам, какие колонки и какая у каждого ширина + // 3-ий блок: строчки, заполняем строчки с данными + // widths - ширина колонок if (widths == null || widths.Length == 0) { throw new ArgumentNullException(nameof(widths)); @@ -68,13 +75,14 @@ internal class WordBuilder { throw new ArgumentNullException(nameof(data)); } - if (data.Any(x => x.Length != widths.Length)) + if (data.Any(x => x.Length != widths.Length)) // использьем LinQ метод Any { throw new InvalidOperationException("widths.Length != data.Length"); } - + // создаем таблицу + // 1-ый блок свойства var table = new Table(); - table.AppendChild(new TableProperties( + table.AppendChild(new TableProperties( // мы здесь задаем границы new TableBorders( new TopBorder() { Val = new EnumValue(BorderValues.Single), Size = 12 }, new BottomBorder() { Val = new EnumValue(BorderValues.Single), Size = 12 }, @@ -86,24 +94,26 @@ internal class WordBuilder )); // Заголовок + // идем заполнять строчки, var tr = new TableRow(); for (var j = 0; j < widths.Length; ++j) { - tr.Append(new TableCell( - new TableCellProperties(new TableCellWidth() + tr.Append(new TableCell( // первая строчка, TableCell - это ячейка + new TableCellProperties(new TableCellWidth() // в первой строчке в свойствах проставлем ширину Width = widths[j].ToString() { Width = - widths[j].ToString() + widths[j].ToString() // заполняем ширину ячейки }), - new Paragraph(new Run(new RunProperties(new Bold()), new - Text(data.First()[j]))))); + new Paragraph(new Run(new RunProperties(new Bold()), new // заголовок делаем что у нас он жирный Bold(), это шапка каждой таблицы + Text(data.First()[j]))))); // Через LinQ метод вытаскиваем First, некий Text data.First() - берем элемент из первой строки } - table.Append(tr); + table.Append(tr); // заполнили первую строчку добавили в табличку // Данные - table.Append(data.Skip(1).Select(x => - new TableRow(x.Select(y => new TableCell(new Paragraph(new - Run(new Text(y)))))))); + // теперь просто заполняем данные + table.Append(data.Skip(1).Select(x => // LinQ метод data.Skip(1) - пропускаем первую запись, которая у нас шапка таблицы + new TableRow(x.Select(y => new TableCell(new Paragraph(new // а для всех остальных мы берем элемент data(список) + Run(new Text(y)))))))); // и основе каждого списка создаем объект TableRow, которого через x.Select заполняет ячейки _body.Append(table); return this; } From dde7460c2e6dbdc1465ad6109fae8d53baa73ccd Mon Sep 17 00:00:00 2001 From: Bulat Date: Fri, 20 Dec 2024 10:23:08 +0400 Subject: [PATCH 3/3] =?UTF-8?q?=D0=BA=D0=BE=D0=BC=D0=BC=D0=B5=D0=BD=D1=82?= =?UTF-8?q?=D0=B0=D1=80=D0=B8=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Entities/Enums/Diagnosis.cs | 6 +- .../Entities/MedicalHistory.cs | 2 +- .../Entities/Patient.cs | 3 +- .../Forms/FormMedicalHistory.cs | 6 -- .../Reports/ChartReport.cs | 14 +---- .../Reports/PdfBuilder.cs | 24 ++++---- .../Reports/TableReport.cs | 1 - .../Reports/WordBuilder.cs | 58 +++++++------------ .../Repositories/IDrugMedicalHistory.cs | 4 +- .../Repositories/IMedicalHistoryRepository.cs | 9 +-- .../Repositories/IPatientRepository.cs | 11 ++-- .../MedicalHistoryRepository.cs | 47 +-------------- 12 files changed, 47 insertions(+), 138 deletions(-) diff --git a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Entities/Enums/Diagnosis.cs b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Entities/Enums/Diagnosis.cs index d9f3ee4..809214f 100644 --- a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Entities/Enums/Diagnosis.cs +++ b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Entities/Enums/Diagnosis.cs @@ -6,11 +6,7 @@ using System.Threading.Tasks; namespace RegistrationPatientsPolyclinic.Entities.Enums; -[Flags] // Flag - атрибут, его значения будут комбинироваться, например, если мы создадим объект от соотрудника, -// то его поле DoctorPost, то мы в него занесем только один из возможных вариантов(None, Junior, Senior, Head) -// а по атрибуту Flags позволяет хранить несколько записей -// ВАЖНО!!! Чтобы в перечеслении значения были степени двойки -// битовое объединение +[Flags] public enum Diagnosis { None = 0, diff --git a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Entities/MedicalHistory.cs b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Entities/MedicalHistory.cs index 5408a96..f8171f5 100644 --- a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Entities/MedicalHistory.cs +++ b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Entities/MedicalHistory.cs @@ -7,7 +7,7 @@ using System.Threading.Tasks; namespace RegistrationPatientsPolyclinic.Entities; -public class MedicalHistory // сущность пополнения, наподобие FeedReplenushment +public class MedicalHistory { public int Id { get; private set; } diff --git a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Entities/Patient.cs b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Entities/Patient.cs index 70cb6e3..a3a7751 100644 --- a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Entities/Patient.cs +++ b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Entities/Patient.cs @@ -10,14 +10,13 @@ public class Patient { public int Id { get; private set; } - public string First_Name { get; private set; } = string .Empty; // string.Empty - означает, что по умолчанию это свойство будет содержать пустую строку, а не null(то же самое "") + public string First_Name { get; private set; } = string .Empty; public string Last_Name { get; private set; } = string.Empty; public string ContactNumber { get; private set; } - // ТУТ СДЕЛАЕМ СТАТИСТИЧЕСКИЙ МЕТОД, который будет отвечать за создание объекта public static Patient CreateEntity(int id, string first_Name, string last_Name, string contactNumber) { diff --git a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Forms/FormMedicalHistory.cs b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Forms/FormMedicalHistory.cs index 7404038..c347eea 100644 --- a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Forms/FormMedicalHistory.cs +++ b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Forms/FormMedicalHistory.cs @@ -57,12 +57,6 @@ namespace RegistrationPatientsPolyclinic.Forms throw new Exception("Имеются незаполненные поля"); } - /* - CreateEntity(0, - Convert.ToInt32(comboBoxPacient.Text), - Convert.ToInt32(row.Cells["ColumnDoctor"].Value), (Diagnosis)row.Cells["ColumnDiagnosis"].Value, - (Status)row.Cells["ColumnStatus"].Value, ColumnDrug); - */ _medicalHistoryRepository.CreateMedicalHistory(MedicalHistory.CreateEntity(0, (int)comboBoxPacient.SelectedValue!, (int)comboBoxDoctor.SelectedValue!, CreateListMedicalHistoryFromDataGrid())); diff --git a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/ChartReport.cs b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/ChartReport.cs index cadbe00..bde0a8c 100644 --- a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/ChartReport.cs +++ b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/ChartReport.cs @@ -38,19 +38,7 @@ internal class ChartReport return false; } } - /* - private List<(string Caption, double Value)> GetData(DateTime dateTime) - { - // Получаем все медицинские истории за указанную дату - var medicalHistories = _medicalHistoryRepository.ReadMedicalHistory(dateTime, dateTime); - - // Группируем по идентификатору пациента и считаем количество посещений - return medicalHistories - .GroupBy(mh => mh.PatientId) - .Select(g => (Caption: $"Patient {g.Key}", Value: (double)g.Count())) - .ToList(); - } - */ + private List<(string Caption, double Value)> GetData(DateTime dateTime) { var medicalHistories = _medicalHistoryRepository.ReadMedicalHistory(null, null, null, null); diff --git a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/PdfBuilder.cs b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/PdfBuilder.cs index 0939123..46d1f19 100644 --- a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/PdfBuilder.cs +++ b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/PdfBuilder.cs @@ -29,35 +29,35 @@ internal class PdfBuilder DefineStyles(); // настройка стиля } - public PdfBuilder AddHeader(string header) // Заголовок, header - это текст заголовка + public PdfBuilder AddHeader(string header) { - _document.AddSection().AddParagraph(header, "NormalBold"); // документу добавляется секция добавляется параграф + _document.AddSection().AddParagraph(header, "NormalBold"); return this; } - public PdfBuilder AddPieChart(string title, List<(string Caption, double Value)> data) // метод добавления диаграммы круговой + public PdfBuilder AddPieChart(string title, List<(string Caption, double Value)> data) { if (data == null || data.Count == 0) { return this; } var chart = new Chart(ChartType.Pie2D); - var series = chart.SeriesCollection.AddSeries(); // добавляем серию + var series = chart.SeriesCollection.AddSeries(); series.Add(data.Select(x => x.Value).ToArray()); - var xseries = chart.XValues.AddXSeries(); // добавляем подписи + var xseries = chart.XValues.AddXSeries(); xseries.Add(data.Select(x => x.Caption).ToArray()); - chart.DataLabel.Type = DataLabelType.Percent; // вывод ввиде прицентов + chart.DataLabel.Type = DataLabelType.Percent; chart.DataLabel.Position = DataLabelPosition.OutsideEnd; - chart.Width = Unit.FromCentimeter(16); // ширина и высота + chart.Width = Unit.FromCentimeter(16); chart.Height = Unit.FromCentimeter(12); - chart.TopArea.AddParagraph(title); // заголовок добавляется - chart.XAxis.MajorTickMark = TickMarkType.Outside; // настраиваем где у нас будут подписи - chart.YAxis.MajorTickMark = TickMarkType.Outside; // настраиваем где у нас будут подписи + chart.TopArea.AddParagraph(title); + chart.XAxis.MajorTickMark = TickMarkType.Outside; + chart.YAxis.MajorTickMark = TickMarkType.Outside; chart.YAxis.HasMajorGridlines = true; chart.PlotArea.LineFormat.Width = 1; chart.PlotArea.LineFormat.Visible = true; - chart.TopArea.AddLegend(); // где у нас будет легенда - _document.LastSection.Add(chart); // в документ добавляем нашу таблицу + chart.TopArea.AddLegend(); + _document.LastSection.Add(chart); return this; } diff --git a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/TableReport.cs b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/TableReport.cs index 393ea3e..e0aa030 100644 --- a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/TableReport.cs +++ b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/TableReport.cs @@ -60,7 +60,6 @@ internal class TableReport } } - /// ВНИЗУ БЫЛ ПРАВИЛЬНЫЙ private List GetData(int drugId, DateTime startDate, DateTime endDate) diff --git a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/WordBuilder.cs b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/WordBuilder.cs index 5f04319..58867cc 100644 --- a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/WordBuilder.cs +++ b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/WordBuilder.cs @@ -10,13 +10,8 @@ using DocumentFormat.OpenXml.Packaging; namespace RegistrationPatientsPolyclinic.Reports; -/// -/// Построитель Ворда -/// internal class WordBuilder { - // Создание заголовка, вставить некий параграф с текстом - // Потребуется сделать табличку private readonly string _filePath; private readonly Document _document; private readonly Body _body; @@ -38,13 +33,13 @@ internal class WordBuilder public WordBuilder AddHeader(string header) { - // код ставки заголовка в документ Word - var paragraph = _body.AppendChild(new Paragraph()); // в body добавляем новый элемент дочерний это будет параграф - var run = paragraph.AppendChild(new Run()); // добавление блока - // жирный шрифт + + var paragraph = _body.AppendChild(new Paragraph()); + var run = paragraph.AppendChild(new Run()); + var runProperties = run.AppendChild(new RunProperties()); runProperties.AppendChild(new Bold()); - // добавляем текст + run.AppendChild(new Text(header)); return this; @@ -52,7 +47,7 @@ internal class WordBuilder public WordBuilder AddParagraph(string text) { - // код ставки параграфа + var paragraph = _body.AppendChild(new Paragraph()); var run = paragraph.AppendChild(new Run()); @@ -61,12 +56,8 @@ internal class WordBuilder } public WordBuilder AddTable(int[] widths, List data) - { // int[] width - будет передаваться массив intов - // Табличка в Word состоит из 3-ех блоков - // 1-ый блок: свойство . Здесь будем задавать границы - // 2-ой блок: колонки или Grid там передадим информацию по колонкам, какие колонки и какая у каждого ширина - // 3-ий блок: строчки, заполняем строчки с данными - // widths - ширина колонок + { + if (widths == null || widths.Length == 0) { throw new ArgumentNullException(nameof(widths)); @@ -75,14 +66,13 @@ internal class WordBuilder { throw new ArgumentNullException(nameof(data)); } - if (data.Any(x => x.Length != widths.Length)) // использьем LinQ метод Any + if (data.Any(x => x.Length != widths.Length)) { throw new InvalidOperationException("widths.Length != data.Length"); } - // создаем таблицу - // 1-ый блок свойства + var table = new Table(); - table.AppendChild(new TableProperties( // мы здесь задаем границы + table.AppendChild(new TableProperties( new TableBorders( new TopBorder() { Val = new EnumValue(BorderValues.Single), Size = 12 }, new BottomBorder() { Val = new EnumValue(BorderValues.Single), Size = 12 }, @@ -93,27 +83,23 @@ internal class WordBuilder ) )); - // Заголовок - // идем заполнять строчки, var tr = new TableRow(); for (var j = 0; j < widths.Length; ++j) { - tr.Append(new TableCell( // первая строчка, TableCell - это ячейка - new TableCellProperties(new TableCellWidth() // в первой строчке в свойствах проставлем ширину Width = widths[j].ToString() + tr.Append(new TableCell( + new TableCellProperties(new TableCellWidth() { Width = - widths[j].ToString() // заполняем ширину ячейки + widths[j].ToString() }), - new Paragraph(new Run(new RunProperties(new Bold()), new // заголовок делаем что у нас он жирный Bold(), это шапка каждой таблицы - Text(data.First()[j]))))); // Через LinQ метод вытаскиваем First, некий Text data.First() - берем элемент из первой строки + new Paragraph(new Run(new RunProperties(new Bold()), new + Text(data.First()[j]))))); } - table.Append(tr); // заполнили первую строчку добавили в табличку - - // Данные - // теперь просто заполняем данные - table.Append(data.Skip(1).Select(x => // LinQ метод data.Skip(1) - пропускаем первую запись, которая у нас шапка таблицы - new TableRow(x.Select(y => new TableCell(new Paragraph(new // а для всех остальных мы берем элемент data(список) - Run(new Text(y)))))))); // и основе каждого списка создаем объект TableRow, которого через x.Select заполняет ячейки + table.Append(tr); + + table.Append(data.Skip(1).Select(x => + new TableRow(x.Select(y => new TableCell(new Paragraph(new + Run(new Text(y)))))))); _body.Append(table); return this; } @@ -121,7 +107,7 @@ internal class WordBuilder public void Build() { - // элемент какой будет все создавать + using var wordDocument = WordprocessingDocument.Create(_filePath, WordprocessingDocumentType.Document); var mainPart = wordDocument.AddMainDocumentPart(); mainPart.Document = _document; diff --git a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Repositories/IDrugMedicalHistory.cs b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Repositories/IDrugMedicalHistory.cs index 264724a..35c5321 100644 --- a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Repositories/IDrugMedicalHistory.cs +++ b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Repositories/IDrugMedicalHistory.cs @@ -10,9 +10,9 @@ namespace RegistrationPatientsPolyclinic.Repositories; public interface IDrugMedicalHistory { - IEnumerable ReadDragMedicalHistory(int? drugId, string description); // чтение всего + IEnumerable ReadDragMedicalHistory(int? drugId, string description); - void CreateDrugMedicalHistory(DrugMedicalHistory drugHistory); // создание объекта + void CreateDrugMedicalHistory(DrugMedicalHistory drugHistory); void DeleteDrugMedicalHistory(int Id); } diff --git a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Repositories/IMedicalHistoryRepository.cs b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Repositories/IMedicalHistoryRepository.cs index 7979ac9..2aad5e0 100644 --- a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Repositories/IMedicalHistoryRepository.cs +++ b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Repositories/IMedicalHistoryRepository.cs @@ -11,15 +11,10 @@ public interface IMedicalHistoryRepository { IEnumerable ReadMedicalHistory(DateTime? dateForm = null, DateTime? dateTo = null, int? PatientId = null, - int? DoctorId = null); // по этим параметрам можно не весь список читать, а только какую то часть + int? DoctorId = null); - /* - IEnumerable ReadMedicalHistory(DateTime? dateForm = null, DateTime? dateTo = null, int? PatientId = null, - int? DoctorId = null); // по этим параметрам можно не весь список читать, а только какую то часть - - */ - void CreateMedicalHistory(MedicalHistory medicalHistory); // объекь будет заносится в список + void CreateMedicalHistory(MedicalHistory medicalHistory); void DeletemedicalHistory(int id); diff --git a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Repositories/IPatientRepository.cs b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Repositories/IPatientRepository.cs index 3cc9133..0ecf6ef 100644 --- a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Repositories/IPatientRepository.cs +++ b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Repositories/IPatientRepository.cs @@ -7,18 +7,15 @@ using System.Threading.Tasks; namespace RegistrationPatientsPolyclinic.Repositories; -/// -/// Операцию read (чтение) разобьем на 2 метода: получение коллекции и получений одной записи по идентификатору. -/// public interface IPatientRepository { - IEnumerable ReadPatient(); // метод получения всего списка (в данном случае пациентов) + IEnumerable ReadPatient(); - Patient ReadPatientById(int id); // получение по id + Patient ReadPatientById(int id); - void CreatPatient(Patient patient); // метод для того чтобы добавить в существующую коллекцию пациента + void CreatPatient(Patient patient); - void UpdatePatient(Patient patient); // метод на изменение + void UpdatePatient(Patient patient); void DeletePatient(int id); } diff --git a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Repositories/Implementations/MedicalHistoryRepository.cs b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Repositories/Implementations/MedicalHistoryRepository.cs index b2f8a1c..b654612 100644 --- a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Repositories/Implementations/MedicalHistoryRepository.cs +++ b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Repositories/Implementations/MedicalHistoryRepository.cs @@ -112,52 +112,7 @@ WHERE Id=@id"; } } - /* - public IEnumerable ReadMedicalHistory(DateTime? dateForm = null, DateTime? dateTo = null, int? PatientId = null, int? DoctorId = null) - { - _logger.LogInformation("Получение всех объектов"); - try - { - using var connection = new - NpgsqlConnection(_connectionString.ConnectionString); - var querySelect = @"SELECT * FROM MedicalHistory"; - var medicalHistory = - connection.Query(querySelect); - _logger.LogDebug("Полученные объекты: {json}", - JsonConvert.SerializeObject(medicalHistory)); - return medicalHistory; - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка при чтении объектов"); - throw; - } - - } - */ - /* - public IEnumerable ReadMedicalHistory(DateTime? dateForm = null, DateTime? dateTo = null, int? PatientId = null, int? DoctorId = null) - { - _logger.LogInformation("Получение всех объектов"); - try - { - using var connection = new - NpgsqlConnection(_connectionString.ConnectionString); - var querySelect = @"SELECT mh.*, dmh.DrugId, dmh.Description - FROM MedicalHistory mh - INNER JOIN DrugMedicalHistory dmh ON dmh.MedicalHistoryId = mh.Id"; - var medicalHistory = - connection.Query(querySelect); - _logger.LogDebug("Полученные объекты: {json}", - JsonConvert.SerializeObject(medicalHistory)); - return medicalHistory; - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка при чтении объектов"); - throw; - } - }*/ + }