комментарии

This commit is contained in:
Bulat 2024-12-20 10:23:08 +04:00
parent 63a67391e9
commit dde7460c2e
12 changed files with 47 additions and 138 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

@ -7,7 +7,7 @@ using System.Threading.Tasks;
namespace RegistrationPatientsPolyclinic.Entities; namespace RegistrationPatientsPolyclinic.Entities;
public class MedicalHistory // сущность пополнения, наподобие FeedReplenushment public class MedicalHistory
{ {
public int Id { get; private set; } public int Id { get; private set; }

View File

@ -10,14 +10,13 @@ public class Patient
{ {
public int Id { get; private set; } 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 Last_Name { get; private set; } = string.Empty;
public string ContactNumber { get; private set; } 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

@ -38,19 +38,7 @@ internal class ChartReport
return false; 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) private List<(string Caption, double Value)> GetData(DateTime dateTime)
{ {
var medicalHistories = _medicalHistoryRepository.ReadMedicalHistory(null, null, null, null); var medicalHistories = _medicalHistoryRepository.ReadMedicalHistory(null, null, null, null);

View File

@ -29,35 +29,35 @@ internal class PdfBuilder
DefineStyles(); // настройка стиля DefineStyles(); // настройка стиля
} }
public PdfBuilder AddHeader(string header) // Заголовок, header - это текст заголовка public PdfBuilder AddHeader(string header)
{ {
_document.AddSection().AddParagraph(header, "NormalBold"); // документу добавляется секция добавляется параграф _document.AddSection().AddParagraph(header, "NormalBold");
return this; 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) if (data == null || data.Count == 0)
{ {
return this; return this;
} }
var chart = new Chart(ChartType.Pie2D); var chart = new Chart(ChartType.Pie2D);
var series = chart.SeriesCollection.AddSeries(); // добавляем серию var series = chart.SeriesCollection.AddSeries();
series.Add(data.Select(x => x.Value).ToArray()); 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()); xseries.Add(data.Select(x => x.Caption).ToArray());
chart.DataLabel.Type = DataLabelType.Percent; // вывод ввиде прицентов chart.DataLabel.Type = DataLabelType.Percent;
chart.DataLabel.Position = DataLabelPosition.OutsideEnd; chart.DataLabel.Position = DataLabelPosition.OutsideEnd;
chart.Width = Unit.FromCentimeter(16); // ширина и высота chart.Width = Unit.FromCentimeter(16);
chart.Height = Unit.FromCentimeter(12); chart.Height = Unit.FromCentimeter(12);
chart.TopArea.AddParagraph(title); // заголовок добавляется chart.TopArea.AddParagraph(title);
chart.XAxis.MajorTickMark = TickMarkType.Outside; // настраиваем где у нас будут подписи chart.XAxis.MajorTickMark = TickMarkType.Outside;
chart.YAxis.MajorTickMark = TickMarkType.Outside; // настраиваем где у нас будут подписи chart.YAxis.MajorTickMark = TickMarkType.Outside;
chart.YAxis.HasMajorGridlines = true; chart.YAxis.HasMajorGridlines = true;
chart.PlotArea.LineFormat.Width = 1; chart.PlotArea.LineFormat.Width = 1;
chart.PlotArea.LineFormat.Visible = true; chart.PlotArea.LineFormat.Visible = true;
chart.TopArea.AddLegend(); // где у нас будет легенда chart.TopArea.AddLegend();
_document.LastSection.Add(chart); // в документ добавляем нашу таблицу _document.LastSection.Add(chart);
return this; return this;
} }

View File

@ -60,7 +60,6 @@ internal class TableReport
} }
} }
/// ВНИЗУ БЫЛ ПРАВИЛЬНЫЙ
private List<string[]> GetData(int drugId, DateTime startDate, DateTime endDate) private List<string[]> GetData(int drugId, DateTime startDate, DateTime endDate)

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,13 +33,13 @@ internal class WordBuilder
public WordBuilder AddHeader(string header) public WordBuilder AddHeader(string header)
{ {
// код ставки заголовка в документ Word
var paragraph = _body.AppendChild(new Paragraph()); // в body добавляем новый элемент дочерний это будет параграф 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;
@ -52,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());
@ -61,12 +56,8 @@ internal class WordBuilder
} }
public WordBuilder AddTable(int[] widths, List<string[]> data) public WordBuilder AddTable(int[] widths, List<string[]> data)
{ // int[] width - будет передаваться массив intов {
// Табличка в Word состоит из 3-ех блоков
// 1-ый блок: свойство . Здесь будем задавать границы
// 2-ой блок: колонки или Grid там передадим информацию по колонкам, какие колонки и какая у каждого ширина
// 3-ий блок: строчки, заполняем строчки с данными
// widths - ширина колонок
if (widths == null || widths.Length == 0) if (widths == null || widths.Length == 0)
{ {
throw new ArgumentNullException(nameof(widths)); throw new ArgumentNullException(nameof(widths));
@ -75,14 +66,13 @@ internal class WordBuilder
{ {
throw new ArgumentNullException(nameof(data)); 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"); throw new InvalidOperationException("widths.Length != data.Length");
} }
// создаем таблицу
// 1-ый блок свойства
var table = new Table(); var table = new Table();
table.AppendChild(new TableProperties( // мы здесь задаем границы table.AppendChild(new TableProperties(
new TableBorders( new TableBorders(
new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 }, new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 }, new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
@ -93,27 +83,23 @@ 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)
{ {
tr.Append(new TableCell( // первая строчка, TableCell - это ячейка tr.Append(new TableCell(
new TableCellProperties(new TableCellWidth() // в первой строчке в свойствах проставлем ширину Width = widths[j].ToString() new TableCellProperties(new TableCellWidth()
{ {
Width = Width =
widths[j].ToString() // заполняем ширину ячейки widths[j].ToString()
}), }),
new Paragraph(new Run(new RunProperties(new Bold()), new // заголовок делаем что у нас он жирный Bold(), это шапка каждой таблицы new Paragraph(new Run(new RunProperties(new Bold()), new
Text(data.First()[j]))))); // Через LinQ метод вытаскиваем First, некий Text data.First() - берем элемент из первой строки Text(data.First()[j])))));
} }
table.Append(tr); // заполнили первую строчку добавили в табличку table.Append(tr);
// Данные table.Append(data.Skip(1).Select(x =>
// теперь просто заполняем данные new TableRow(x.Select(y => new TableCell(new Paragraph(new
table.Append(data.Skip(1).Select(x => // LinQ метод data.Skip(1) - пропускаем первую запись, которая у нас шапка таблицы Run(new Text(y))))))));
new TableRow(x.Select(y => new TableCell(new Paragraph(new // а для всех остальных мы берем элемент data(список)
Run(new Text(y)))))))); // и основе каждого списка создаем объект TableRow, которого через x.Select заполняет ячейки
_body.Append(table); _body.Append(table);
return this; return this;
} }
@ -121,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

@ -10,9 +10,9 @@ namespace RegistrationPatientsPolyclinic.Repositories;
public interface IDrugMedicalHistory public interface IDrugMedicalHistory
{ {
IEnumerable<DrugMedicalHistory> ReadDragMedicalHistory(int? drugId, string description); // чтение всего IEnumerable<DrugMedicalHistory> ReadDragMedicalHistory(int? drugId, string description);
void CreateDrugMedicalHistory(DrugMedicalHistory drugHistory); // создание объекта void CreateDrugMedicalHistory(DrugMedicalHistory drugHistory);
void DeleteDrugMedicalHistory(int Id); void DeleteDrugMedicalHistory(int Id);
} }

View File

@ -11,15 +11,10 @@ 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

@ -7,18 +7,15 @@ using System.Threading.Tasks;
namespace RegistrationPatientsPolyclinic.Repositories; namespace RegistrationPatientsPolyclinic.Repositories;
/// <summary>
/// Операцию read (чтение) разобьем на 2 метода: получение коллекции и получений одной записи по идентификатору.
/// </summary>
public interface IPatientRepository public interface IPatientRepository
{ {
IEnumerable<Patient> ReadPatient(); // метод получения всего списка (в данном случае пациентов) IEnumerable<Patient> 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); void DeletePatient(int id);
} }

View File

@ -112,53 +112,8 @@ 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;
}
}*/
}