ISEbd-21 Hairullov B.A. Lab_Work_04 #6

Closed
selli7 wants to merge 8 commits from LabWork_4 into LabWork_3
25 changed files with 416 additions and 128 deletions

View File

@ -1,6 +1,7 @@
using RegistrationPatientsPolyclinic.Entities.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@ -10,12 +11,16 @@ namespace RegistrationPatientsPolyclinic.Entities;
public class Doctor
{
public int Id { get; private set; }
[DisplayName("Имя")]
public string First_Name { get; private set; } = string.Empty;
[DisplayName("Фамилия")]
public string Last_Name { get; private set; } = string.Empty;
public DoctorPost DoctorPost { get; private set; } // объявляется свойство DoctorPost, которое имеет тип DoctorPost
public string FullName => $"{Last_Name} {First_Name}";
[DisplayName("Должность")]
public DoctorPost DoctorPost { get; private set; }
public static Doctor CreateEntity(int id, string first_Name, string last_Name, DoctorPost doctorPost)
{

View File

@ -1,6 +1,7 @@
using RegistrationPatientsPolyclinic.Entities.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@ -10,14 +11,20 @@ namespace RegistrationPatientsPolyclinic.Entities;
public class DoctorPayments
{
public int Id { get; private set; }
[Browsable(false)]
public int IdDoctor { get; private set; }
[DisplayName("Доктор")]
public string DoctorName { get; private set; } = string.Empty;
[DisplayName("Месяц")]
public string Month { get; private set; } = string.Empty;
[DisplayName("Количество пациентов")]
public int Count_Patient { get; private set; }
public DateTime DoctorPaymentData { get; private set; }
[DisplayName("Оплата")]
public int Payment { get; private set; }
public static DoctorPayments CreateElement(int id, int idDoctor, string month, int count_patient, int payment)
@ -28,7 +35,6 @@ public class DoctorPayments
IdDoctor = idDoctor,
Month = month,
Count_Patient = count_patient,
DoctorPaymentData = DateTime.Now,
Payment = payment
};
}

View File

@ -1,20 +1,24 @@
using RegistrationPatientsPolyclinic.Entities.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RegistrationPatientsPolyclinic.Entities;
public class Drug // Наподобие Feed
public class Drug
{
public int Id { get; private set; }
[DisplayName("Название лекарства")]
public DrugName DrugName { get; private set; }
[DisplayName("Количество")]
public int Grams { get; private set; }
[DisplayName("Описание")]
public string Description { get; private set; } = string.Empty;
public static Drug CreateElement(int id, DrugName name, int grams, string description)

View File

@ -7,24 +7,26 @@ using System.Threading.Tasks;
namespace RegistrationPatientsPolyclinic.Entities;
public class DrugMedicalHistory // Тоже самое что FeedFeedRepleshments
public class DrugMedicalHistory
{
public int Id { get; private set; }
public int DrugId { get; private set; }
public string DrugName { get; private set; } = string.Empty;
public string Description { get; private set; } = string.Empty;
public int MedicalHistoryId { get; private set; }
public static DrugMedicalHistory CreateEntity(int id, int drugId, string description)
public static DrugMedicalHistory CreateEntity(int id, int drugId, string description, int medicalHistoryId)
{
return new DrugMedicalHistory
{
Id = id,
DrugId = drugId,
Description = description ?? string.Empty
Description = description ?? string.Empty,
MedicalHistoryId = medicalHistoryId
};
}
}

View File

@ -1,6 +1,7 @@
using RegistrationPatientsPolyclinic.Entities.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@ -11,15 +12,30 @@ public class MedicalHistory
{
public int Id { get; private set; }
[Browsable(false)]
public int PatientId { get; private set; }
[DisplayName("Имя пациента")]
public string PatientName { get; private set; } = string.Empty;
[Browsable(false)]
public int DoctorId { get; private set; }
[DisplayName("Имя доктора")]
public string DoctorName { get; private set; } = string.Empty;
[DisplayName("Дата приема")]
public DateTime VisitDate { get; private set; }
public IEnumerable<DrugMedicalHistory> DrugMedicalHistory { get; set; } = [];
[Browsable(false)]
public IEnumerable<DrugMedicalHistory> DrugMedicalHistory { get; set; } = [];
[DisplayName("Назначенные лекарства")]
public string DrugsSummary => string.Join(", ", DrugMedicalHistory
.Select(d => $" {d.DrugId}, {d.Description}"));
public static MedicalHistory CreateEntity(int id, int patientId, int doctorId,
IEnumerable<DrugMedicalHistory> drugMedicalHistory)
@ -33,16 +49,12 @@ public class MedicalHistory
DrugMedicalHistory = drugMedicalHistory
};
}
public static MedicalHistory CreateOpeartion(TempDrugMedicalHistory tempDrugMedicalHistory, IEnumerable<DrugMedicalHistory> drugMedicalHistories)
public void SetDrugMedHistory(IEnumerable<DrugMedicalHistory> drugMedicalHistory)
{
return new MedicalHistory
if (drugMedicalHistory != null && drugMedicalHistory.Any())
{
Id = tempDrugMedicalHistory.Id,
PatientId = tempDrugMedicalHistory.PatientId,
DoctorId = tempDrugMedicalHistory.DoctorId,
VisitDate = tempDrugMedicalHistory.VisitDate,
DrugMedicalHistory = drugMedicalHistories
};
DrugMedicalHistory = drugMedicalHistory;
}
}
}

View File

@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@ -10,13 +11,15 @@ public class Patient
{
public int Id { get; private set; }
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 ContactNumber { get; private set; }
public string FullName => $"{First_Name} {Last_Name}";
// ТУТ СДЕЛАЕМ СТАТИСТИЧЕСКИЙ МЕТОД, который будет отвечать за создание объекта
public static Patient CreateEntity(int id, string first_Name, string last_Name, string contactNumber)
{

View File

@ -16,8 +16,6 @@ namespace RegistrationPatientsPolyclinic.Forms
{
public partial class FormDoctor : Form
{
// Понадобиться интерфейс работника
// так же будет сеттер с id
private readonly IDoctorRepository _doctorRepository;
@ -53,7 +51,7 @@ namespace RegistrationPatientsPolyclinic.Forms
_doctorRepository = doctorRepository ??
throw new ArgumentNullException(nameof(doctorRepository));
comboBoxPost.DataSource = Enum.GetValues(typeof(DoctorPost)); // вытащи значение из этого перечисления, вернет массив строк, т.е. массив тпеих элементов(DoctorPost)
comboBoxPost.DataSource = Enum.GetValues(typeof(DoctorPost));
}
private void ButtonSave_Click(object sender, EventArgs e)

View File

@ -23,7 +23,7 @@ namespace RegistrationPatientsPolyclinic.Forms
throw new ArgumentNullException(nameof(doctorPaymentsRepository));
comboBoxDoctor.DataSource = doctorRepository.ReadDoctors();
comboBoxDoctor.DisplayMember = "Firts_Name";
comboBoxDoctor.DisplayMember = "FullName";
comboBoxDoctor.ValueMember = "Id";
}
@ -36,18 +36,15 @@ namespace RegistrationPatientsPolyclinic.Forms
throw new Exception("Имеются не заполненные поля");
}
// Получаем значение из первой строки колонки ColumnMonth
string month = dataGridViewPayment.Rows[0].Cells["ColumnMonth"].Value?.ToString();
int countPatient = int.Parse(dataGridViewPayment.Rows[0].Cells["ColumnCount"].Value?.ToString() ?? "0");
int payment = int.Parse(dataGridViewPayment.Rows[0].Cells["ColumnPayment"].Value?.ToString() ?? "0");
// Проверяем, что месяц не пустой
if (string.IsNullOrEmpty(month))
{
throw new Exception("Месяц не заполнен");
}
// Создаем элемент DoctorPayments
_doctorPaymentsRepository.CreateDoctorPayments(DoctorPayments.CreateElement(0, (int)comboBoxDoctor.SelectedValue!, month, countPatient, payment));
@ -71,7 +68,6 @@ namespace RegistrationPatientsPolyclinic.Forms
{
continue;
}
// ДОДЕЛАТЬ!!!
list.Add(DoctorPayments.CreateElement(0, 0, row.Cells["ColumnMonth"].Value.ToString(), Convert.ToInt32(row.Cells["ColumnCount"].Value),
Convert.ToInt32(row.Cells["ColumnPayment"].Value)));
}

View File

@ -52,7 +52,12 @@ namespace RegistrationPatientsPolyclinic.Forms
}
}
private void LoadList() => dataGridView.DataSource = _doctorPaymentsRepository.ReadDoctorPayments();
private void LoadList()
{
dataGridView.DataSource = _doctorPaymentsRepository.ReadDoctorPayments();
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["Month"].DefaultCellStyle.Format = "yyyy-dd";
}
}

View File

@ -15,8 +15,6 @@ namespace RegistrationPatientsPolyclinic.Forms
{
public partial class FormDoctors : Form
{
// Здесь понадобится экземпляр IUnity контейнер через который мы будем создавать объекты FormDoctor и вызывать его
// IPatientRepository через который мы будем получать список
private readonly IUnityContainer _container;
@ -25,7 +23,7 @@ namespace RegistrationPatientsPolyclinic.Forms
public FormDoctors(IUnityContainer container, IDoctorRepository doctorRepository)
{
InitializeComponent();
_container = container ?? // мы получаем через контейнер объект
_container = container ??
throw new ArgumentNullException(nameof(container));
_doctorRepository = doctorRepository ??
throw new ArgumentNullException(nameof(doctorRepository)); ;
@ -33,7 +31,6 @@ namespace RegistrationPatientsPolyclinic.Forms
private void FormDoctors_Load(object sender, EventArgs e)
{
// метод, при загрузки формы будет прогружаться все данные
try
{
LoadList();
@ -43,12 +40,16 @@ namespace RegistrationPatientsPolyclinic.Forms
MessageBox.Show(ex.Message, "Ошибка при загрузке", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
// отдельный метод который будет загружать в GridView
private void LoadList() => dataGridView.DataSource = _doctorRepository.ReadDoctors();
private void LoadList()
{
dataGridView.DataSource = _doctorRepository.ReadDoctors();
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["FullName"].Visible = false;
}
private bool TryGetIdentifierFromSelectedRow(out int id) // возвращает смог н извлечь или нет
private bool TryGetIdentifierFromSelectedRow(out int id)
{
id = 0;
if (dataGridView.SelectedRows.Count < 1)

View File

@ -32,7 +32,6 @@ namespace RegistrationPatientsPolyclinic.Forms
{
throw new InvalidDataException(nameof(drag));
}
// проходимся по всем значениям перечисления
foreach (DrugName elem in Enum.GetValues(typeof(DrugName)))
{
if ((elem & drag.DrugName) != 0)
@ -57,10 +56,10 @@ namespace RegistrationPatientsPolyclinic.Forms
InitializeComponent();
_drugRepository = drugRepository??
throw new ArgumentNullException(nameof(drugRepository));
// вытаскиваем все значения
foreach(var elem in Enum.GetValues(typeof(DrugName)))
{
checkedListBoxName.Items.Add(elem); // заполняем поэлементно значения
checkedListBoxName.Items.Add(elem);
}
}

View File

@ -31,7 +31,7 @@
dateTimePickerStart = new DateTimePicker();
textBoxFilePath = new TextBox();
buttonSelectFilePath = new Button();
comboBoxDrug = new ComboBox();
comboBoxDoctor = new ComboBox();
dateTimePickerEnd = new DateTimePicker();
labelFilePath = new Label();
labelDrug = new Label();
@ -65,13 +65,13 @@
buttonSelectFilePath.UseVisualStyleBackColor = true;
buttonSelectFilePath.Click += buttonSelectFilePath_Click;
//
// comboBoxDrug
// comboBoxDoctor
//
comboBoxDrug.FormattingEnabled = true;
comboBoxDrug.Location = new Point(140, 143);
comboBoxDrug.Name = "comboBoxDrug";
comboBoxDrug.Size = new Size(125, 28);
comboBoxDrug.TabIndex = 3;
comboBoxDoctor.FormattingEnabled = true;
comboBoxDoctor.Location = new Point(140, 143);
comboBoxDoctor.Name = "comboBoxDoctor";
comboBoxDoctor.Size = new Size(125, 28);
comboBoxDoctor.TabIndex = 3;
//
// dateTimePickerEnd
//
@ -137,7 +137,7 @@
Controls.Add(labelDrug);
Controls.Add(labelFilePath);
Controls.Add(dateTimePickerEnd);
Controls.Add(comboBoxDrug);
Controls.Add(comboBoxDoctor);
Controls.Add(buttonSelectFilePath);
Controls.Add(textBoxFilePath);
Controls.Add(dateTimePickerStart);
@ -152,7 +152,7 @@
private DateTimePicker dateTimePickerStart;
private TextBox textBoxFilePath;
private Button buttonSelectFilePath;
private ComboBox comboBoxDrug;
private ComboBox comboBoxDoctor;
private DateTimePicker dateTimePickerEnd;
private Label labelFilePath;
private Label labelDrug;

View File

@ -17,15 +17,15 @@ namespace RegistrationPatientsPolyclinic.Forms
{
private readonly IUnityContainer _container;
public FormDrugReport(IUnityContainer container, IDrugRepository drugRepository)
public FormDrugReport(IUnityContainer container, IDrugRepository drugRepository, IDoctorRepository doctorRepository)
{
InitializeComponent();
_container = container ??
throw new ArgumentNullException(nameof(container));
comboBoxDrug.DataSource = drugRepository.ReadDrug();
comboBoxDrug.DisplayMember = "Name";
comboBoxDrug.ValueMember = "Id";
comboBoxDoctor.DataSource = doctorRepository.ReadDoctors();
comboBoxDoctor.DisplayMember = "FullName";
comboBoxDoctor.ValueMember = "Id";
}
@ -50,16 +50,21 @@ namespace RegistrationPatientsPolyclinic.Forms
{
throw new Exception("Отсутствует имя файла для отчета");
}
if (comboBoxDrug.SelectedIndex < 0)
if (comboBoxDoctor.SelectedIndex < 0)
{
throw new Exception("Не выбран корм");
throw new Exception("Не выбран врач");
}
if (dateTimePickerEnd.Value <= dateTimePickerStart.Value)
{
throw new Exception("Дата начала должна быть раньше даты окончания");
}
if (_container.Resolve<TableReport>().CreateTable(textBoxFilePath.Text, (int)comboBoxDrug.SelectedValue!,
dateTimePickerStart.Value, dateTimePickerEnd.Value))
// Приведение дат к началу и концу месяца
var startDate = new DateTime(dateTimePickerStart.Value.Year, dateTimePickerStart.Value.Month, 1);
var endDate = new DateTime(dateTimePickerEnd.Value.Year, dateTimePickerEnd.Value.Month, 1).AddMonths(1).AddDays(-1);
if (_container.Resolve<TableReport>().CreateTable(textBoxFilePath.Text, (int)comboBoxDoctor.SelectedValue!,
startDate, endDate))
{
MessageBox.Show("Документ сформирован", "Формирование документа", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

View File

@ -29,7 +29,11 @@ namespace RegistrationPatientsPolyclinic.Forms
}
private void LoadList() => dataGridView.DataSource = _dragRepository.ReadDrug();
private void LoadList()
{
dataGridView.DataSource = _dragRepository.ReadDrug();
dataGridView.Columns["Id"].Visible = false;
}
private void buttonAdd_Click(object sender, EventArgs e)

View File

@ -52,7 +52,12 @@ namespace RegistrationPatientsPolyclinic.Forms
}
}
private void LoadList() => dataGridView.DataSource = _medicalHistoryRepository.ReadMedicalHistory();
private void LoadList()
{
dataGridView.DataSource = _medicalHistoryRepository.ReadMedicalHistory();
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["VisitDate"].DefaultCellStyle.Format = "dd.MM.yyyy";
}
private void buttonDel_Click(object sender, EventArgs e)
{

View File

@ -32,12 +32,12 @@ namespace RegistrationPatientsPolyclinic.Forms
throw new ArgumentNullException(nameof(medicalHistoryRepository));
comboBoxPacient.DataSource = patientRepository.ReadPatient(); // передает набор всех пациентов
comboBoxPacient.DisplayMember = "First_Name"; // отображение в combobox
comboBoxPacient.DisplayMember = "FullName"; // отображение в combobox
comboBoxPacient.ValueMember = "Id";
comboBoxDoctor.DataSource = doctorRepository.ReadDoctors();
comboBoxDoctor.DisplayMember = "First_Name";
comboBoxDoctor.DisplayMember = "FullName";
comboBoxDoctor.ValueMember = "Id";
ColumnDrug.DataSource = drugRepository.ReadDrug();
@ -85,10 +85,10 @@ _medicalHistoryRepository.ReadMedicalHistory();
{
continue;
}
list.Add(DrugMedicalHistory.CreateEntity(0, Convert.ToInt32(row.Cells["ColumnDrug"].Value), row.Cells["ColumnDescription"].Value?.ToString()));
list.Add(DrugMedicalHistory.CreateEntity(0, Convert.ToInt32(row.Cells["ColumnDrug"].Value), row.Cells["ColumnDescription"].Value?.ToString(), 0));
}
return list.GroupBy(x => x.DrugId, x => x.Description, (id, description) =>
DrugMedicalHistory.CreateEntity(0, id, string.Join(", ", description))).ToList();
DrugMedicalHistory.CreateEntity(0, id, string.Join(", ", description), 0)).ToList();
}
}

View File

@ -99,7 +99,12 @@ namespace RegistrationPatientsPolyclinic.Forms
// отдельный метод который будет загружать в GridView
private void LoadList() => dataGridView.DataSource = _pacientRepository.ReadPatient();
private void LoadList()
{
dataGridView.DataSource = _pacientRepository.ReadPatient();
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["FullName"].Visible = false;
}
private bool TryGetIdentifierFromSelectedRow(out int id) // возвращает смог н извлечь или нет

View File

@ -1,5 +1,6 @@
using Microsoft.Extensions.Logging;
using RegistrationPatientsPolyclinic.Repositories;
using RegistrationPatientsPolyclinic.Repositories.Implementations;
using System;
using System.Collections.Generic;
using System.Linq;
@ -14,10 +15,12 @@ internal class ChartReport
private readonly IMedicalHistoryRepository _medicalHistoryRepository;
private readonly ILogger<ChartReport> _logger;
public ChartReport(IMedicalHistoryRepository medicalHistoryRepository, ILogger<ChartReport> logger)
public ChartReport(IMedicalHistoryRepository medicalHistoryRepository, IDoctorPaymentsRepository doctorPaymentsRepository, ILogger<ChartReport> logger)
{
_medicalHistoryRepository = medicalHistoryRepository ??
throw new ArgumentNullException(nameof(medicalHistoryRepository));
_doctorPaymentsRepository = doctorPaymentsRepository ??
throw new ArgumentNullException(nameof(doctorPaymentsRepository));
_logger = logger ??
throw new ArgumentNullException(nameof(logger));
}
@ -27,8 +30,8 @@ internal class ChartReport
try
{
new PdfBuilder(filePath)
.AddHeader("Количество посещений пациентов")
.AddPieChart("Пациенты", GetData(dateTime))
.AddHeader("Пополенение лекарства")
.AddPieChart("Виды лекарства", GetData(dateTime))
.Build();
return true;
}
@ -41,26 +44,13 @@ internal class ChartReport
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.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))
// Группируем по идентификатору пациента и считаем количество посещений
return medicalHistories
.GroupBy(mh => mh.PatientId)
.Select(g => (Caption: $"Patient {g.Key}", Value: (double)g.Count()))
.ToList();
return result;

View File

@ -20,37 +20,51 @@ internal class TableReport
private readonly IDoctorPaymentsRepository _doctorPaymentsRepository;
private readonly IDrugRepository _drugRepository;
private readonly IDoctorRepository _doctorRepository;
private readonly ILogger<TableReport> _logger;
internal static readonly string[] item = ["Id доктора", "Описание", "Количество пациентов"];
internal static readonly string[] item = ["Дата", "Описание", "Количество лекарства"];
public TableReport(IMedicalHistoryRepository medicalHistoryRepository, IDoctorPaymentsRepository doctorPaymentsRepository, ILogger<TableReport> logger)
public TableReport(IMedicalHistoryRepository medicalHistoryRepository, IDoctorPaymentsRepository doctorPaymentsRepository, IDoctorRepository doctorRepository, IDrugRepository drugRepository, ILogger<TableReport> logger)
{
_medicalHistoryRepository = medicalHistoryRepository ??
throw new ArgumentNullException(nameof(medicalHistoryRepository)); ;
_doctorPaymentsRepository = doctorPaymentsRepository ??
throw new ArgumentNullException(nameof(doctorPaymentsRepository));
_drugRepository = drugRepository ??
throw new ArgumentNullException(nameof(drugRepository));
_doctorRepository = doctorRepository ??
throw new ArgumentNullException(nameof(IMedicalHistoryRepository));
_logger = logger ??
throw new ArgumentNullException(nameof(logger));
}
public bool CreateTable(string filePath, int drugId, DateTime startDate, DateTime endDate)
public bool CreateTable(string filePath, int doctorId, DateTime startDate, DateTime endDate)
{
try
{
var data = GetData(drugId, startDate, endDate);
var columnsWidths = new int[] {10, 15, 15 };
var startOfMonth = new DateTime(startDate.Year, startDate.Month, 1);
var endOfMonth = new DateTime(endDate.Year, endDate.Month, 1).AddMonths(1).AddDays(-1);
if (columnsWidths.Length != data.First().Length)
{
throw new InvalidOperationException("Количество ширин столбцов не соответствует количеству данных.");
}
// Получаем данные для таблицы и имя врача
var (tableData, doctorFullName) = GetData(doctorId, startOfMonth, endOfMonth);
new ExcelBuilder(filePath)
.AddHeader("Сводка по движению лекарство", 0, 3)
.AddParagraph("за период", 0)
.AddTable(columnsWidths, data)
.Build();
var excelBuilder = new ExcelBuilder(filePath)
.AddHeader("Сводка по оплате", 0, 3)
.AddParagraph($"За период с {startOfMonth:MMMM yyyy} по {endOfMonth:MMMM yyyy}", 0)
.AddParagraph($"Врач: {doctorFullName}", 0)
.AddTable(new[] { 25, 25, 25 }, tableData);
/*
excelBuilder.AddParagraph("", 0);
excelBuilder
.AddHeader("Назначенные лекарства", 0, 2)
.AddTable(new[] { 25, 25 }, GetDrugData(doctorId, startOfMonth, endOfMonth));
*/
excelBuilder.Build();
return true;
}
catch (Exception ex)
@ -61,12 +75,73 @@ internal class TableReport
}
/*
private List<string[]> GetData(int drugId, DateTime startDate, DateTime endDate)
{
var data = _medicalHistoryRepository
.ReadMedicalHistory(dateForm: startDate,dateTo : endDate, null, null)
.Select(x => new
{
Date = x.VisitDate,
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 }))
.OrderBy(x => x.Date);
return new List<string[]>() { item }
.Union(
data
.Select(x => new string[] {x.Date.ToString("dd.MM.yyyy"), x.CountIn ?? string.Empty, x.CountOut?.ToString() ?? string.Empty }))
.Union(
new List<string[]>() { new string[] { "Всего", data.Sum(x => x.CountOut ?? 0).ToString(), string.Empty } })
.ToList();
}
*/
/*
private List<string[]> GetData(int drugId, DateTime startDate, DateTime endDate)
{
var data = _medicalHistoryRepository
.ReadMedicalHistory()
.Where(x => x.VisitDate >= startDate && x.VisitDate <= endDate && x.DrugMedicalHistory.Any(y => y.DrugId == drugId) )
.Where(x => x.VisitDate >= startDate && x.VisitDate <= endDate && x.DrugMedicalHistory.Any(y => y.DrugId == drugId))
.Select(x => new
{
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 }))
.OrderBy(x => x.Date);
return new List<string[]>() { item }
.Union(
data
.Select(x => new string[] { x.Date.ToString(), x.CountIn ?? string.Empty, x.CountOut?.ToString() ?? string.Empty }))
.Union(
new List<string[]>() { new string[] { "Всего", string.Empty, data.Sum(x => x.CountOut ?? 0).ToString() } })
.ToList();
}
*/
// ВНИЗУ САМЫЙ ПОСЛЕДНИЙ!!!
/*
private List<string[]> GetData(int drugId, DateTime startDate, DateTime endDate)
{
var data = _medicalHistoryRepository
.ReadMedicalHistory()
.Where(x => x.VisitDate >= startDate && x.VisitDate <= endDate && x.DrugMedicalHistory.Any(y => y.DrugId == drugId))
.Select(x => new
{
Date = x.DoctorId,
@ -76,26 +151,95 @@ internal class TableReport
.Union(
_doctorPaymentsRepository
.ReadDoctorPayments()
.Where(x => x.IdDoctor!=0)
.Select(x => new {Date = x.IdDoctor, CountIn = (string?)null, CountOut = (int?)x.Count_Patient }))
.Where(x => x.Id != 0)
.Select(x => new { Date = x.IdDoctor, CountIn = (string?)null, CountOut = (int?)x.Count_Patient }))
.OrderBy(x => x.Date);
return new List<string[]>() { item }
.Union(
data
.Select(x => new string[] {x.Date.ToString(), x.CountIn ?? string.Empty, x.CountOut?.ToString() ?? string.Empty }))
.Select(x => new string[] { x.Date.ToString(), x.CountIn ?? string.Empty, x.CountOut?.ToString() ?? string.Empty }))
.Union(
new List<string[]>() { new string[] { "Всего", string.Empty, data.Sum(x => x.CountOut ?? 0).ToString() } })
new List<string[]>() { new string[] { "Всего", string.Empty, data.Sum(x => x.CountOut ?? 0).ToString() } })
.ToList();
}
*/
private (List<string[]>, string) GetData(int doctorId, DateTime startOfMonth, DateTime endOfMonth)
{
var data = _doctorPaymentsRepository
.ReadDoctorPayments()
.Where(x =>
{
var IdDoctorss = x.IdDoctor;
return IdDoctorss == doctorId;
})
.Select(x => new
{
DoctorName = x.DoctorName, // Предполагается, что есть поле DoctorName
CountOfPatients = x.Count_Patient,
Payments = x.Payment
})
.ToList();
var doctorName = data.FirstOrDefault()?.DoctorName ?? "Неизвестный врач";
var result = new List<string[]>()
{
new[] { "Имя Врача", "Количество пациентов", "Выплаты" }
}
.Union(
data.Select(x => new string[]
{
x.DoctorName,
x.CountOfPatients.ToString(),
x.Payments.ToString()
})
)
.Union(
new[]
{
new string[]
{
"Всего",
data.Sum(x => x.CountOfPatients).ToString(),
data.Sum(x => x.Payments).ToString()
}
}
)
.ToList();
return (result, doctorName);
}
private List<string[]> GetDrugData(int doctorId, DateTime startOfMonth, DateTime endOfMonth)
{
var medicalHistories = _medicalHistoryRepository
.ReadMedicalHistory(startOfMonth, endOfMonth, doctorId, null) // Исправлено
.Where(mh => mh.DrugMedicalHistory != null && mh.DrugMedicalHistory.Any())
.ToList();
_logger.LogDebug("Полученные медицинские истории с лекарствами: {data}", JsonConvert.SerializeObject(medicalHistories));
var drugData = medicalHistories
.SelectMany(mh => mh.DrugMedicalHistory.Select(drug => new
{
Date = mh.VisitDate,
Count = drug.Description
}))
.OrderBy(x => x.Date)
.ToList();
var result = new List<string[]> { new[] { "Дата", "Назначенные лекарства" } };
result.AddRange(drugData.Select(item => new string[]
{
item.Date.ToString("dd MMMM yyyy"),
item.Count.ToString()
}));
return result;
}
}

View File

@ -9,8 +9,7 @@ namespace RegistrationPatientsPolyclinic.Repositories;
public interface IDoctorPaymentsRepository
{
IEnumerable<DoctorPayments> ReadDoctorPayments();
IEnumerable<DoctorPayments> ReadDoctorPayments(int? doctorId = null, string month = null);
void CreateDoctorPayments(DoctorPayments doctorPayments);

View File

@ -14,7 +14,12 @@ public interface IMedicalHistoryRepository
int? DoctorId = null);
void CreateMedicalHistory(MedicalHistory medicalHistory);
/*
IEnumerable<TempDrugMedicalHistory> ReadMedicalHistory(DateTime? dateForm = null, DateTime? dateTo = null, int? PatientId = null,
int? DoctorId = null); // по этим параметрам можно не весь список читать, а только какую то часть
*/
void CreateMedicalHistory(MedicalHistory medicalHistory); // объекь будет заносится в список
void DeletemedicalHistory(int id);

View File

@ -9,13 +9,13 @@ namespace RegistrationPatientsPolyclinic.Repositories;
public interface IPatientRepository
{
IEnumerable<Patient> ReadPatient();
IEnumerable<Patient> 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);
}

View File

@ -1,4 +1,6 @@
using Dapper;
using DocumentFormat.OpenXml.Bibliography;
using DocumentFormat.OpenXml.Wordprocessing;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
@ -47,17 +49,34 @@ VALUES (@IdDoctor, @Month, @Count_Patient, @Payment)";
}
public IEnumerable<DoctorPayments> ReadDoctorPayments()
public IEnumerable<DoctorPayments> ReadDoctorPayments(int? doctorId = null, string month = null)
{
_logger.LogInformation("Получение всех объектов");
try
{
var builder = new QueryBuilder();
if (doctorId.HasValue)
{
builder.AddCondition("fa.IdDoctor = @doctorId");
}
if (!string.IsNullOrEmpty(month))
{
builder.AddCondition("fa.Month = @month");
}
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM DoctorPayments";
var querySelect = $@"SELECT fa.*,
CONCAT(e.Last_Name, ' ', e.First_Name) AS DoctorName
FROM DoctorPayments fa
LEFT JOIN Doctor e ON e.Id = fa.IdDoctor
{builder.Build()}";
var doctorPayments =
connection.Query<DoctorPayments>(querySelect);
connection.Query<DoctorPayments>(querySelect, new { doctorId , month });
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(doctorPayments));
return doctorPayments;
@ -70,6 +89,7 @@ VALUES (@IdDoctor, @Month, @Count_Patient, @Payment)";
}
}

View File

@ -1,4 +1,5 @@
using Dapper;
using DocumentFormat.OpenXml.Wordprocessing;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
@ -24,7 +25,7 @@ public class MedicalHistoryRepository : IMedicalHistoryRepository
_logger = logger;
}
public void CreateMedicalHistory(MedicalHistory medicalHistory)
{
_logger.LogInformation("Добавление объекта");
@ -63,7 +64,7 @@ VALUES (@DrugId,@MedicalHistoryId, @Description)";
}
}
public void DeletemedicalHistory(int id)
{
@ -86,6 +87,7 @@ WHERE Id=@id";
}
public IEnumerable<MedicalHistory> ReadMedicalHistory(DateTime? dateForm = null, DateTime? dateTo = null, int? PatientId = null, int? DoctorId = null)
{
_logger.LogInformation("Получение всех объектов");
@ -112,7 +114,52 @@ WHERE Id=@id";
}
}
/*
public IEnumerable<MedicalHistory> 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<MedicalHistory>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(medicalHistory));
return medicalHistory;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
*/
/*
public IEnumerable<TempDrugMedicalHistory> 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<TempDrugMedicalHistory>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(medicalHistory));
return medicalHistory;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}*/
}

View File

@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RegistrationPatientsPolyclinic.Repositories.Implementations;
internal class QueryBuilder
{
private readonly StringBuilder _builder;
public QueryBuilder()
{
_builder = new();
}
public QueryBuilder AddCondition(string condition)
{
if (_builder.Length > 0)
{
_builder.Append(" AND ");
}
_builder.Append(condition);
return this;
}
public string Build()
{
if (_builder.Length == 0)
{
return string.Empty;
}
return $"WHERE {_builder}";
}
}