решал конфликты

This commit is contained in:
Bulat 2024-12-20 11:16:05 +04:00
commit 3788700f03
10 changed files with 108 additions and 134 deletions

View File

@ -6,11 +6,7 @@ using System.Threading.Tasks;
namespace RegistrationPatientsPolyclinic.Entities.Enums; namespace RegistrationPatientsPolyclinic.Entities.Enums;
[Flags] // Flag - атрибут, его значения будут комбинироваться, например, если мы создадим объект от соотрудника, [Flags]
// то его поле DoctorPost, то мы в него занесем только один из возможных вариантов(None, Junior, Senior, Head)
// а по атрибуту Flags позволяет хранить несколько записей
// ВАЖНО!!! Чтобы в перечеслении значения были степени двойки
// битовое объединение
public enum Diagnosis public enum Diagnosis
{ {
None = 0, None = 0,

View File

@ -11,16 +11,15 @@ public class Patient
{ {
public int Id { get; private set; } public int Id { get; private set; }
[DisplayName("Имя")] public string First_Name { get; private set; } = string .Empty; // string.Empty - означает, что по умолчанию это свойство будет содержать пустую строку, а не null(то же самое "")
public string First_Name { get; private set; } = string .Empty;
[DisplayName("Фамилия")] [DisplayName("Фамилия")]
public string Last_Name { get; private set; } = string.Empty; public string Last_Name { get; private set; } = string.Empty;
public string FullName => $"{First_Name} {Last_Name}"; 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) public static Patient CreateEntity(int id, string first_Name, string last_Name, string contactNumber)
{ {

View File

@ -57,12 +57,6 @@ namespace RegistrationPatientsPolyclinic.Forms
throw new Exception("Имеются незаполненные поля"); 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!, _medicalHistoryRepository.CreateMedicalHistory(MedicalHistory.CreateEntity(0, (int)comboBoxPacient.SelectedValue!,
(int)comboBoxDoctor.SelectedValue!, CreateListMedicalHistoryFromDataGrid())); (int)comboBoxDoctor.SelectedValue!, CreateListMedicalHistoryFromDataGrid()));

View File

@ -30,8 +30,8 @@ internal class ChartReport
try try
{ {
new PdfBuilder(filePath) new PdfBuilder(filePath)
.AddHeader($"Выписанные лекарства на {dateTime:dd.MM.yyyy}") .AddHeader("Пополенение лекарства")
.AddPieChart("Соотношение выписанных лекарств по врачам", GetData(dateTime)) .AddPieChart("Виды лекарства", GetData(dateTime))
.Build(); .Build();
return true; return true;
} }
@ -41,30 +41,16 @@ internal class ChartReport
return false; return false;
} }
} }
private List<(string Caption, double Value)> GetData(DateTime dateTime) 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) return medicalHistories
.Where(mh => mh.DrugMedicalHistory != null && mh.DrugMedicalHistory.Any()) .GroupBy(mh => mh.PatientId)
.ToList(); .Select(g => (Caption: $"Patient {g.Key}", Value: (double)g.Count()))
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))
.ToList(); .ToList();
return result; return result;

View File

@ -26,7 +26,7 @@ internal class PdfBuilder
} }
_filePath = filePath; _filePath = filePath;
_document = new Document(); _document = new Document();
DefineStyles(); DefineStyles(); // настройка стиля
} }
public PdfBuilder AddHeader(string header) public PdfBuilder AddHeader(string header)

View File

@ -26,7 +26,7 @@ internal class TableReport
private readonly ILogger<TableReport> _logger; private readonly ILogger<TableReport> _logger;
internal static readonly string[] item = ["Id врача", "Количество пациентов", "Выплаты"]; internal static readonly string[] item = ["Дата", "Описание", "Количество лекарства"];
public TableReport(IMedicalHistoryRepository medicalHistoryRepository, IDoctorPaymentsRepository doctorPaymentsRepository, IDoctorRepository doctorRepository, IDrugRepository drugRepository, ILogger<TableReport> logger) public TableReport(IMedicalHistoryRepository medicalHistoryRepository, IDoctorPaymentsRepository doctorPaymentsRepository, IDoctorRepository doctorRepository, IDrugRepository drugRepository, ILogger<TableReport> logger)
{ {
@ -74,7 +74,6 @@ internal class TableReport
} }
} }
/// ВНИЗУ БЫЛ ПРАВИЛЬНЫЙ
/* /*
private List<string[]> GetData(int drugId, DateTime startDate, DateTime endDate) private List<string[]> 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)) .Where(x => x.VisitDate >= startDate && x.VisitDate <= endDate && x.DrugMedicalHistory.Any(y => y.DrugId == drugId))
.Select(x => new .Select(x => new
{ {
Date = x.VisitDate, Date = x.DoctorId,
CountIn = x.DrugMedicalHistory.FirstOrDefault(y => y.DrugId == drugId)?.Description, CountIn = x.DrugMedicalHistory.FirstOrDefault(y => y.DrugId == drugId)?.Description,
CountOut = (int?)null CountOut = (int?)null
}) })
@ -121,7 +120,7 @@ internal class TableReport
_doctorPaymentsRepository _doctorPaymentsRepository
.ReadDoctorPayments() .ReadDoctorPayments()
.Where(x => x.DoctorPaymentData >= startDate && x.DoctorPaymentData <= endDate) .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); .OrderBy(x => x.Date);
@ -130,7 +129,7 @@ internal class TableReport
data 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( .Union(
new List<string[]>() { new string[] { "Всего", data.Sum(x => x.CountOut ?? 0).ToString(), string.Empty } }) new List<string[]>() { new string[] { "Всего", string.Empty, data.Sum(x => x.CountOut ?? 0).ToString() } })
.ToList(); .ToList();
} }
*/ */

View File

@ -10,13 +10,8 @@ using DocumentFormat.OpenXml.Packaging;
namespace RegistrationPatientsPolyclinic.Reports; namespace RegistrationPatientsPolyclinic.Reports;
/// <summary>
/// Построитель Ворда
/// </summary>
internal class WordBuilder internal class WordBuilder
{ {
// Создание заголовка, вставить некий параграф с текстом
// Потребуется сделать табличку
private readonly string _filePath; private readonly string _filePath;
private readonly Document _document; private readonly Document _document;
private readonly Body _body; private readonly Body _body;
@ -38,11 +33,13 @@ internal class WordBuilder
public WordBuilder AddHeader(string header) public WordBuilder AddHeader(string header)
{ {
// код ставки заголовка
var paragraph = _body.AppendChild(new Paragraph()); var paragraph = _body.AppendChild(new Paragraph());
var run = paragraph.AppendChild(new Run()); var run = paragraph.AppendChild(new Run());
var runProperties = run.AppendChild(new RunProperties()); var runProperties = run.AppendChild(new RunProperties());
runProperties.AppendChild(new Bold()); runProperties.AppendChild(new Bold());
run.AppendChild(new Text(header)); run.AppendChild(new Text(header));
return this; return this;
@ -50,7 +47,7 @@ internal class WordBuilder
public WordBuilder AddParagraph(string text) public WordBuilder AddParagraph(string text)
{ {
// код ставки заголовка
var paragraph = _body.AppendChild(new Paragraph()); var paragraph = _body.AppendChild(new Paragraph());
var run = paragraph.AppendChild(new Run()); var run = paragraph.AppendChild(new Run());
@ -60,6 +57,7 @@ internal class WordBuilder
public WordBuilder AddTable(int[] widths, List<string[]> data) public WordBuilder AddTable(int[] widths, List<string[]> data)
{ {
if (widths == null || widths.Length == 0) if (widths == null || widths.Length == 0)
{ {
throw new ArgumentNullException(nameof(widths)); throw new ArgumentNullException(nameof(widths));
@ -85,7 +83,6 @@ internal class WordBuilder
) )
)); ));
// Заголовок
var tr = new TableRow(); var tr = new TableRow();
for (var j = 0; j < widths.Length; ++j) for (var j = 0; j < widths.Length; ++j)
{ {
@ -100,7 +97,6 @@ internal class WordBuilder
} }
table.Append(tr); table.Append(tr);
// Данные
table.Append(data.Skip(1).Select(x => table.Append(data.Skip(1).Select(x =>
new TableRow(x.Select(y => new TableCell(new Paragraph(new new TableRow(x.Select(y => new TableCell(new Paragraph(new
Run(new Text(y)))))))); Run(new Text(y))))))));
@ -111,7 +107,7 @@ internal class WordBuilder
public void Build() public void Build()
{ {
// элемент какой будет все создавать
using var wordDocument = WordprocessingDocument.Create(_filePath, WordprocessingDocumentType.Document); using var wordDocument = WordprocessingDocument.Create(_filePath, WordprocessingDocumentType.Document);
var mainPart = wordDocument.AddMainDocumentPart(); var mainPart = wordDocument.AddMainDocumentPart();
mainPart.Document = _document; mainPart.Document = _document;

View File

@ -13,7 +13,13 @@ public interface IMedicalHistoryRepository
IEnumerable<MedicalHistory> ReadMedicalHistory(DateTime? dateForm = null, DateTime? dateTo = null, int? PatientId = null, IEnumerable<MedicalHistory> ReadMedicalHistory(DateTime? dateForm = null, DateTime? dateTo = null, int? PatientId = null,
int? DoctorId = null); 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); void DeletemedicalHistory(int id);

View File

@ -9,13 +9,13 @@ namespace RegistrationPatientsPolyclinic.Repositories;
public interface IPatientRepository 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); void DeletePatient(int id);
} }

View File

@ -93,67 +93,19 @@ WHERE Id=@id";
_logger.LogInformation("Получение всех объектов"); _logger.LogInformation("Получение всех объектов");
try 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 using var connection = new
NpgsqlConnection(_connectionString.ConnectionString); NpgsqlConnection(_connectionString.ConnectionString);
//var querySelect = @"SELECT * FROM MedicalHistory";
var querySelect = $@"SELECT mh.*, var querySelect = @"SELECT mh.*, dmh.DrugId, dmh.Description
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
FROM MedicalHistory mh FROM MedicalHistory mh
LEFT JOIN DrugMedicalHistory dmh ON dmh.MedicalHistoryId = mh.Id INNER 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<int, List<DrugMedicalHistory>>();
var medicalHistory = var medicalHistory =
connection.Query<MedicalHistory, DrugMedicalHistory, MedicalHistory>(querySelect, connection.Query<TempDrugMedicalHistory>(querySelect);
(history, drug) =>
{
if (!historyDict.TryGetValue(history.Id, out var drugs))
{
drugs = new List<DrugMedicalHistory>();
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 });
_logger.LogDebug("Полученные объекты: {json}", _logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(medicalHistory)); JsonConvert.SerializeObject(medicalHistory));
return historyDict.Select(x => return medicalHistory.GroupBy(x => x.Id, y => y,
{ (key, value) => MedicalHistory.CreateOpeartion(value.First(),
var mh = medicalHistory.First(y => y.Id == x.Key); value.Select(z => DrugMedicalHistory.CreateEntity(0, z.DrugId, z.Description)))).ToList();
mh.SetDrugMedHistory(x.Value);
return mh;
}).ToArray();
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -162,8 +114,54 @@ 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;
}
}*/
} }