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/Patient.cs b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Entities/Patient.cs index 0a01f1d..fcf008e 100644 --- a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Entities/Patient.cs +++ b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Entities/Patient.cs @@ -11,16 +11,15 @@ public class Patient { public int Id { get; private set; } - [DisplayName("Имя")] - public string First_Name { get; private set; } = string .Empty; + public string First_Name { get; private set; } = string .Empty; // string.Empty - означает, что по умолчанию это свойство будет содержать пустую строку, а не null(то же самое "") [DisplayName("Фамилия")] public string Last_Name { get; private set; } = string.Empty; public string FullName => $"{First_Name} {Last_Name}"; - [DisplayName("Контактный номер")] - 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 657d9c9..c96f7bc 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 13af507..62e0973 100644 --- a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/ChartReport.cs +++ b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/ChartReport.cs @@ -30,8 +30,8 @@ internal class ChartReport try { new PdfBuilder(filePath) - .AddHeader($"Выписанные лекарства на {dateTime:dd.MM.yyyy}") - .AddPieChart("Соотношение выписанных лекарств по врачам", GetData(dateTime)) + .AddHeader("Пополенение лекарства") + .AddPieChart("Виды лекарства", GetData(dateTime)) .Build(); return true; } @@ -41,30 +41,16 @@ internal class ChartReport return false; } } + private List<(string Caption, double Value)> GetData(DateTime dateTime) { - var medicalHistories = _medicalHistoryRepository.ReadMedicalHistory(null, null, null, null); + // Получаем все медицинские истории за указанную дату + var medicalHistories = _medicalHistoryRepository.ReadMedicalHistory(dateTime, dateTime); - 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.DoctorName, - (doctorName, group) => new - { - DoctorName = doctorName, - TotalDrugAssignments = group - .SelectMany(mh => mh.DrugMedicalHistory) - .Count() - } - ) - .ToList(); - - var result = groupedData - .Select(x => (Caption: x.DoctorName, Value: (double)x.TotalDrugAssignments)) + // Группируем по идентификатору пациента и считаем количество посещений + return medicalHistories + .GroupBy(mh => mh.PatientId) + .Select(g => (Caption: $"Patient {g.Key}", Value: (double)g.Count())) .ToList(); return result; diff --git a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/PdfBuilder.cs b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/PdfBuilder.cs index e626ae0..46d1f19 100644 --- a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/PdfBuilder.cs +++ b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/PdfBuilder.cs @@ -26,22 +26,22 @@ internal class PdfBuilder } _filePath = filePath; _document = new Document(); - DefineStyles(); + DefineStyles(); // настройка стиля } - public PdfBuilder AddHeader(string 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 chart = new Chart(ChartType.Pie2D); var series = chart.SeriesCollection.AddSeries(); series.Add(data.Select(x => x.Value).ToArray()); var xseries = chart.XValues.AddXSeries(); @@ -51,8 +51,8 @@ internal class PdfBuilder 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.XAxis.MajorTickMark = TickMarkType.Outside; + chart.YAxis.MajorTickMark = TickMarkType.Outside; chart.YAxis.HasMajorGridlines = true; chart.PlotArea.LineFormat.Width = 1; chart.PlotArea.LineFormat.Visible = true; diff --git a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/TableReport.cs b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/TableReport.cs index 3059bab..a104a88 100644 --- a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/TableReport.cs +++ b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Reports/TableReport.cs @@ -26,7 +26,7 @@ internal class TableReport private readonly ILogger _logger; - internal static readonly string[] item = ["Id врача", "Количество пациентов", "Выплаты"]; + internal static readonly string[] item = ["Дата", "Описание", "Количество лекарства"]; public TableReport(IMedicalHistoryRepository medicalHistoryRepository, IDoctorPaymentsRepository doctorPaymentsRepository, IDoctorRepository doctorRepository, IDrugRepository drugRepository, ILogger logger) { @@ -74,7 +74,6 @@ internal class TableReport } } - /// ВНИЗУ БЫЛ ПРАВИЛЬНЫЙ /* private List GetData(int drugId, DateTime startDate, DateTime endDate) @@ -113,7 +112,7 @@ 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 }) @@ -121,7 +120,7 @@ internal class TableReport _doctorPaymentsRepository .ReadDoctorPayments() .Where(x => x.DoctorPaymentData >= startDate && x.DoctorPaymentData <= endDate) - .Select(x => new { Date = x.DoctorPaymentData, CountIn = (string?)null, CountOut = (int?)x.Count_Patient })) + .Select(x => new {Date = x.DoctorPaymentData, CountIn = (string?)null, CountOut = (int?)x.Count_Patient })) .OrderBy(x => x.Date); @@ -130,7 +129,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..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,11 +33,13 @@ internal class WordBuilder public WordBuilder AddHeader(string header) { - // код ставки заголовка - var paragraph = _body.AppendChild(new Paragraph()); + + 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; @@ -50,7 +47,7 @@ internal class WordBuilder public WordBuilder AddParagraph(string text) { - // код ставки заголовка + var paragraph = _body.AppendChild(new Paragraph()); var run = paragraph.AppendChild(new Run()); @@ -59,7 +56,8 @@ internal class WordBuilder } public WordBuilder AddTable(int[] widths, List data) - { + { + if (widths == null || widths.Length == 0) { throw new ArgumentNullException(nameof(widths)); @@ -68,11 +66,11 @@ internal class WordBuilder { throw new ArgumentNullException(nameof(data)); } - if (data.Any(x => x.Length != widths.Length)) + if (data.Any(x => x.Length != widths.Length)) { throw new InvalidOperationException("widths.Length != data.Length"); } - + var table = new Table(); table.AppendChild(new TableProperties( new TableBorders( @@ -85,25 +83,23 @@ 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( + new TableCellProperties(new TableCellWidth() { 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 + Text(data.First()[j]))))); } - 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(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; } @@ -111,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/IMedicalHistoryRepository.cs b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Repositories/IMedicalHistoryRepository.cs index f320a62..dee6ee3 100644 --- a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Repositories/IMedicalHistoryRepository.cs +++ b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Repositories/IMedicalHistoryRepository.cs @@ -13,7 +13,13 @@ public interface IMedicalHistoryRepository IEnumerable ReadMedicalHistory(DateTime? dateForm = null, DateTime? dateTo = null, int? PatientId = null, int? DoctorId = null); - void CreateMedicalHistory(MedicalHistory medicalHistory); + + /* + IEnumerable ReadMedicalHistory(DateTime? dateForm = null, DateTime? dateTo = null, int? PatientId = null, + int? DoctorId = null); // по этим параметрам можно не весь список читать, а только какую то часть + + */ + void CreateMedicalHistory(MedicalHistory medicalHistory); // объекь будет заносится в список void DeletemedicalHistory(int id); diff --git a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Repositories/IPatientRepository.cs b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Repositories/IPatientRepository.cs index 0c50cf3..07f9079 100644 --- a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Repositories/IPatientRepository.cs +++ b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Repositories/IPatientRepository.cs @@ -9,13 +9,13 @@ namespace RegistrationPatientsPolyclinic.Repositories; public interface IPatientRepository { - IEnumerable ReadPatient(); + IEnumerable ReadPatient(); // метод получения всего списка (в данном случае пациентов) - Patient ReadPatientById(int id); + Patient ReadPatientById(int id); // получение по 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 2edebe7..2bef2c6 100644 --- a/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Repositories/Implementations/MedicalHistoryRepository.cs +++ b/RegistrationPatientsPolyclinic/RegistrationPatientsPolyclinic/Repositories/Implementations/MedicalHistoryRepository.cs @@ -93,67 +93,19 @@ WHERE Id=@id"; _logger.LogInformation("Получение всех объектов"); try { - var builder = new QueryBuilder(); - - if (dateForm.HasValue) - { - builder.AddCondition("mh.VisitDate >= @dateForm"); - } - if (dateTo.HasValue) - { - builder.AddCondition("mh.VisitDate <= @dateTo"); - } - if (DoctorId.HasValue) - { - builder.AddCondition("mh.DoctorId = @DoctorId"); - } - if (PatientId.HasValue) - { - builder.AddCondition("mh.PatientId = @PatientId"); - } - - - using var connection = new NpgsqlConnection(_connectionString.ConnectionString); - - var querySelect = $@"SELECT mh.*, - CONCAT(p.Last_Name, ' ', p.First_Name) as PatientName, - CONCAT(d.Last_Name, ' ', d.First_Name) as DoctorName, - dmh.Id AS Id, dmh.DrugId AS drugId,dmh.MedicalHistoryId AS MedicalHistoryId, dmh.Description + //var querySelect = @"SELECT * FROM MedicalHistory"; + var querySelect = @"SELECT mh.*, dmh.DrugId, dmh.Description FROM MedicalHistory mh - LEFT JOIN DrugMedicalHistory dmh ON dmh.MedicalHistoryId = mh.Id - LEFT JOIN Patient p ON p.Id = mh.PatientId - LEFT JOIN doctor d ON d.Id = mh.DoctorId - {builder.Build()}"; - _logger.LogDebug("SQL запрос: {query}", querySelect); - _logger.LogDebug("Параметры: dateForm = {dateForm}, dateTo = {dateTo}, doctorId = {doctorId}, patientId = {patientId}", - dateForm, dateTo, DoctorId, PatientId); - var historyDict = new Dictionary>(); + INNER JOIN DrugMedicalHistory dmh ON dmh.MedicalHistoryId = mh.Id"; var medicalHistory = - connection.Query(querySelect, - (history, drug) => - { - if (!historyDict.TryGetValue(history.Id, out var drugs)) - { - drugs = new List(); - historyDict.Add(history.Id, drugs); - } - if (drug != null && drug.Id > 0) - { - drugs.Add(DrugMedicalHistory.CreateEntity(drug.Id, drug.DrugId, drug.Description, drug.MedicalHistoryId)); - } - return history; - }, splitOn: "Id", param: new { dateForm, dateTo, DoctorId, PatientId }); - + connection.Query(querySelect); _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(medicalHistory)); - return historyDict.Select(x => - { - var mh = medicalHistory.First(y => y.Id == x.Key); - mh.SetDrugMedHistory(x.Value); - return mh; - }).ToArray(); + return medicalHistory.GroupBy(x => x.Id, y => y, + (key, value) => MedicalHistory.CreateOpeartion(value.First(), + value.Select(z => DrugMedicalHistory.CreateEntity(0, z.DrugId, z.Description)))).ToList(); } catch (Exception ex) { @@ -162,8 +114,54 @@ 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; + } + }*/ } +