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

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;
[Flags] // Flag - атрибут, его значения будут комбинироваться, например, если мы создадим объект от соотрудника,
// то его поле DoctorPost, то мы в него занесем только один из возможных вариантов(None, Junior, Senior, Head)
// а по атрибуту Flags позволяет хранить несколько записей
// ВАЖНО!!! Чтобы в перечеслении значения были степени двойки
// битовое объединение
[Flags]
public enum Diagnosis
{
None = 0,

View File

@ -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)
{

View File

@ -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()));

View File

@ -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;

View File

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

View File

@ -26,7 +26,7 @@ internal class TableReport
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)
{
@ -74,7 +74,6 @@ internal class TableReport
}
}
/// ВНИЗУ БЫЛ ПРАВИЛЬНЫЙ
/*
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))
.Select(x => new
{
Date = x.VisitDate,
Date = x.DoctorId,
CountIn = x.DrugMedicalHistory.FirstOrDefault(y => y.DrugId == drugId)?.Description,
CountOut = (int?)null
})
@ -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<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();
}
*/

View File

@ -10,13 +10,8 @@ using DocumentFormat.OpenXml.Packaging;
namespace RegistrationPatientsPolyclinic.Reports;
/// <summary>
/// Построитель Ворда
/// </summary>
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 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());
@ -60,6 +57,7 @@ internal class WordBuilder
public WordBuilder AddTable(int[] widths, List<string[]> data)
{
if (widths == null || widths.Length == 0)
{
throw new ArgumentNullException(nameof(widths));
@ -85,7 +83,6 @@ internal class WordBuilder
)
));
// Заголовок
var tr = new TableRow();
for (var j = 0; j < widths.Length; ++j)
{
@ -100,7 +97,6 @@ internal class WordBuilder
}
table.Append(tr);
// Данные
table.Append(data.Skip(1).Select(x =>
new TableRow(x.Select(y => new TableCell(new Paragraph(new
Run(new Text(y))))))));
@ -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;

View File

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

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

@ -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<int, List<DrugMedicalHistory>>();
INNER JOIN DrugMedicalHistory dmh ON dmh.MedicalHistoryId = mh.Id";
var medicalHistory =
connection.Query<MedicalHistory, DrugMedicalHistory, MedicalHistory>(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 });
connection.Query<TempDrugMedicalHistory>(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<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;
}
}*/
}