diff --git a/ProjectPolyclinic/ProjectPolyclinic/FormPolyclinic.Designer.cs b/ProjectPolyclinic/ProjectPolyclinic/FormPolyclinic.Designer.cs index 7f4a266..566fab5 100644 --- a/ProjectPolyclinic/ProjectPolyclinic/FormPolyclinic.Designer.cs +++ b/ProjectPolyclinic/ProjectPolyclinic/FormPolyclinic.Designer.cs @@ -37,6 +37,8 @@ VisitingsToolStripMenuItem = new ToolStripMenuItem(); ProfessionalDevelopmentsToolStripMenuItem = new ToolStripMenuItem(); отчетыToolStripMenuItem = new ToolStripMenuItem(); + directoryReportToolStripMenuItem = new ToolStripMenuItem(); + visitingReportToolStripMenuItem = new ToolStripMenuItem(); menuStrip1.SuspendLayout(); SuspendLayout(); // @@ -59,21 +61,21 @@ // пациентыToolStripMenuItem // пациентыToolStripMenuItem.Name = "пациентыToolStripMenuItem"; - пациентыToolStripMenuItem.Size = new Size(180, 22); + пациентыToolStripMenuItem.Size = new Size(152, 22); пациентыToolStripMenuItem.Text = "Пациенты"; пациентыToolStripMenuItem.Click += PatientsToolStripMenuItem_Click; // // DoctorsToolStripMenuItem // DoctorsToolStripMenuItem.Name = "DoctorsToolStripMenuItem"; - DoctorsToolStripMenuItem.Size = new Size(180, 22); + DoctorsToolStripMenuItem.Size = new Size(152, 22); DoctorsToolStripMenuItem.Text = "Врачи"; DoctorsToolStripMenuItem.Click += DoctorsToolStripMenuItem_Click; // // MedicinesToolStripMenuItem // MedicinesToolStripMenuItem.Name = "MedicinesToolStripMenuItem"; - MedicinesToolStripMenuItem.Size = new Size(180, 22); + MedicinesToolStripMenuItem.Size = new Size(152, 22); MedicinesToolStripMenuItem.Text = "Медикаменты"; MedicinesToolStripMenuItem.Click += MedicinesToolStripMenuItem_Click; // @@ -100,10 +102,27 @@ // // отчетыToolStripMenuItem // + отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { directoryReportToolStripMenuItem, visitingReportToolStripMenuItem }); отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem"; отчетыToolStripMenuItem.Size = new Size(60, 20); отчетыToolStripMenuItem.Text = "Отчеты"; // + // directoryReportToolStripMenuItem + // + directoryReportToolStripMenuItem.Name = "directoryReportToolStripMenuItem"; + directoryReportToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.W; + directoryReportToolStripMenuItem.Size = new Size(280, 22); + directoryReportToolStripMenuItem.Text = "Документ со справочниками"; + directoryReportToolStripMenuItem.Click += DirectoryReportToolStripMenuItem_Click; + // + // visitingReportToolStripMenuItem + // + visitingReportToolStripMenuItem.Name = "visitingReportToolStripMenuItem"; + visitingReportToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.E; + visitingReportToolStripMenuItem.Size = new Size(280, 22); + visitingReportToolStripMenuItem.Text = "Движение визитов"; + visitingReportToolStripMenuItem.Click += VisitingReportToolStripMenuItem_Click; + // // FormPolyclinic // AutoScaleDimensions = new SizeF(7F, 15F); @@ -133,5 +152,7 @@ private ToolStripMenuItem VisitingsToolStripMenuItem; private ToolStripMenuItem ProfessionalDevelopmentsToolStripMenuItem; private ToolStripMenuItem отчетыToolStripMenuItem; + private ToolStripMenuItem directoryReportToolStripMenuItem; + private ToolStripMenuItem visitingReportToolStripMenuItem; } } diff --git a/ProjectPolyclinic/ProjectPolyclinic/FormPolyclinic.cs b/ProjectPolyclinic/ProjectPolyclinic/FormPolyclinic.cs index 176025a..701ae4c 100644 --- a/ProjectPolyclinic/ProjectPolyclinic/FormPolyclinic.cs +++ b/ProjectPolyclinic/ProjectPolyclinic/FormPolyclinic.cs @@ -79,5 +79,31 @@ namespace ProjectPolyclinic MessageBoxButtons.OK, MessageBoxIcon.Error); } } + + private void DirectoryReportToolStripMenuItem_Click(object sender, EventArgs e) + { + try + { + _container.Resolve().ShowDialog(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, " ", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void VisitingReportToolStripMenuItem_Click(object sender, EventArgs e) + { + try + { + _container.Resolve().ShowDialog(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, " ", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } } } diff --git a/ProjectPolyclinic/ProjectPolyclinic/Forms/FormDirectoryReport.Designer.cs b/ProjectPolyclinic/ProjectPolyclinic/Forms/FormDirectoryReport.Designer.cs new file mode 100644 index 0000000..428b7d4 --- /dev/null +++ b/ProjectPolyclinic/ProjectPolyclinic/Forms/FormDirectoryReport.Designer.cs @@ -0,0 +1,101 @@ +namespace ProjectPolyclinic.Forms +{ + partial class FormDirectoryReport + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + checkBoxDoctors = new CheckBox(); + checkBoxPatients = new CheckBox(); + checkBoxMedicines = new CheckBox(); + buttonBuild = new Button(); + SuspendLayout(); + // + // checkBoxDoctors + // + checkBoxDoctors.AutoSize = true; + checkBoxDoctors.Location = new Point(51, 47); + checkBoxDoctors.Name = "checkBoxDoctors"; + checkBoxDoctors.Size = new Size(60, 19); + checkBoxDoctors.TabIndex = 0; + checkBoxDoctors.Text = "Врачи"; + checkBoxDoctors.UseVisualStyleBackColor = true; + // + // checkBoxPatients + // + checkBoxPatients.AutoSize = true; + checkBoxPatients.Location = new Point(51, 85); + checkBoxPatients.Name = "checkBoxPatients"; + checkBoxPatients.Size = new Size(82, 19); + checkBoxPatients.TabIndex = 1; + checkBoxPatients.Text = "Пациенты"; + checkBoxPatients.UseVisualStyleBackColor = true; + // + // checkBoxMedicines + // + checkBoxMedicines.AutoSize = true; + checkBoxMedicines.Location = new Point(51, 119); + checkBoxMedicines.Name = "checkBoxMedicines"; + checkBoxMedicines.Size = new Size(104, 19); + checkBoxMedicines.TabIndex = 2; + checkBoxMedicines.Text = "Медикаменты"; + checkBoxMedicines.UseVisualStyleBackColor = true; + // + // buttonBuild + // + buttonBuild.BackColor = SystemColors.Control; + buttonBuild.Location = new Point(238, 83); + buttonBuild.Name = "buttonBuild"; + buttonBuild.Size = new Size(101, 23); + buttonBuild.TabIndex = 3; + buttonBuild.Text = "Сформировать"; + buttonBuild.UseVisualStyleBackColor = false; + buttonBuild.Click += ButtonBuild_Click; + // + // FormDirectoryReport + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(385, 170); + Controls.Add(buttonBuild); + Controls.Add(checkBoxMedicines); + Controls.Add(checkBoxPatients); + Controls.Add(checkBoxDoctors); + Name = "FormDirectoryReport"; + StartPosition = FormStartPosition.CenterParent; + Text = "Выгрузка справочников"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private CheckBox checkBoxDoctors; + private CheckBox checkBoxPatients; + private CheckBox checkBoxMedicines; + private Button buttonBuild; + } +} \ No newline at end of file diff --git a/ProjectPolyclinic/ProjectPolyclinic/Forms/FormDirectoryReport.cs b/ProjectPolyclinic/ProjectPolyclinic/Forms/FormDirectoryReport.cs new file mode 100644 index 0000000..d9190f6 --- /dev/null +++ b/ProjectPolyclinic/ProjectPolyclinic/Forms/FormDirectoryReport.cs @@ -0,0 +1,64 @@ +using ProjectPolyclinic.Reports; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using Unity; + +namespace ProjectPolyclinic.Forms +{ + public partial class FormDirectoryReport : Form + { + private readonly IUnityContainer _container; + public FormDirectoryReport(IUnityContainer container) + { + InitializeComponent(); + _container = container ?? throw new ArgumentNullException(nameof(container)); + } + + private void ButtonBuild_Click(object sender, EventArgs e) + { + try + { + if (!checkBoxDoctors.Checked && + !checkBoxPatients.Checked && !checkBoxMedicines.Checked) + { + throw new Exception("Не выбран ни один справочник для выгрузки"); + } + var sfd = new SaveFileDialog() + { + Filter = "Docx Files | *.docx" + }; + if (sfd.ShowDialog() != DialogResult.OK) + { + throw new Exception("Не выбран файла для отчета"); + } + if + (_container.Resolve().CreateDoc(sfd.FileName, checkBoxDoctors.Checked, + checkBoxPatients.Checked, + checkBoxMedicines.Checked)) + { + MessageBox.Show("Документ сформирован", + "Формирование документа", + MessageBoxButtons.OK, + MessageBoxIcon.Information); + } + else + { + MessageBox.Show("Возникли ошибки при формировании документа.Подробности в логах", + "Формирование документа", + MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + catch ( Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка при создании отчета", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } +} diff --git a/ProjectPolyclinic/ProjectPolyclinic/Forms/FormDirectoryReport.resx b/ProjectPolyclinic/ProjectPolyclinic/Forms/FormDirectoryReport.resx new file mode 100644 index 0000000..8b2ff64 --- /dev/null +++ b/ProjectPolyclinic/ProjectPolyclinic/Forms/FormDirectoryReport.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/ProjectPolyclinic/ProjectPolyclinic/Forms/FormMedicines.cs b/ProjectPolyclinic/ProjectPolyclinic/Forms/FormMedicines.cs index 9d93267..4984654 100644 --- a/ProjectPolyclinic/ProjectPolyclinic/Forms/FormMedicines.cs +++ b/ProjectPolyclinic/ProjectPolyclinic/Forms/FormMedicines.cs @@ -95,7 +95,7 @@ namespace ProjectPolyclinic.Forms MessageBoxButtons.OK, MessageBoxIcon.Error); } } - private void LoadList() => dataGridViewData.DataSource = _medicationRepository.ReadMedication(); + private void LoadList() => dataGridViewData.DataSource = _medicationRepository.ReadMedicines(); private bool TryGetIdentifierFromSelectedRow(out int id) { id = 0; diff --git a/ProjectPolyclinic/ProjectPolyclinic/Forms/FormVisiting.cs b/ProjectPolyclinic/ProjectPolyclinic/Forms/FormVisiting.cs index 9290f50..7f7b1d7 100644 --- a/ProjectPolyclinic/ProjectPolyclinic/Forms/FormVisiting.cs +++ b/ProjectPolyclinic/ProjectPolyclinic/Forms/FormVisiting.cs @@ -31,7 +31,7 @@ namespace ProjectPolyclinic.Forms { checkedListBoxDiagnosisName.Items.Add(elem); } - ColumnMedicines.DataSource = medicationRepository.ReadMedication(); + ColumnMedicines.DataSource = medicationRepository.ReadMedicines(); ColumnMedicines.DisplayMember = "MedicinesType"; ColumnMedicines.ValueMember = "Id"; } diff --git a/ProjectPolyclinic/ProjectPolyclinic/Forms/FormVisitingReport.Designer.cs b/ProjectPolyclinic/ProjectPolyclinic/Forms/FormVisitingReport.Designer.cs new file mode 100644 index 0000000..7f43134 --- /dev/null +++ b/ProjectPolyclinic/ProjectPolyclinic/Forms/FormVisitingReport.Designer.cs @@ -0,0 +1,164 @@ +namespace ProjectPolyclinic.Forms +{ + partial class FormVisitingReport + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + dateTimePickerDateBegin = new DateTimePicker(); + dateTimePickerDateEnd = new DateTimePicker(); + label1 = new Label(); + label2 = new Label(); + label3 = new Label(); + label4 = new Label(); + comboBoxDoctor = new ComboBox(); + textBoxFilePath = new TextBox(); + buttonSelectFilePath = new Button(); + buttonMakeReport = new Button(); + SuspendLayout(); + // + // dateTimePickerDateBegin + // + dateTimePickerDateBegin.Location = new Point(126, 101); + dateTimePickerDateBegin.Name = "dateTimePickerDateBegin"; + dateTimePickerDateBegin.Size = new Size(200, 23); + dateTimePickerDateBegin.TabIndex = 0; + // + // dateTimePickerDateEnd + // + dateTimePickerDateEnd.Location = new Point(126, 134); + dateTimePickerDateEnd.Name = "dateTimePickerDateEnd"; + dateTimePickerDateEnd.Size = new Size(200, 23); + dateTimePickerDateEnd.TabIndex = 1; + // + // label1 + // + label1.AutoSize = true; + label1.Location = new Point(35, 32); + label1.Name = "label1"; + label1.Size = new Size(87, 15); + label1.TabIndex = 2; + label1.Text = "Путь до файла"; + // + // label2 + // + label2.AutoSize = true; + label2.Location = new Point(35, 68); + label2.Name = "label2"; + label2.Size = new Size(47, 15); + label2.TabIndex = 3; + label2.Text = "Доктор"; + // + // label3 + // + label3.AutoSize = true; + label3.Location = new Point(35, 101); + label3.Name = "label3"; + label3.Size = new Size(74, 15); + label3.TabIndex = 4; + label3.Text = "Дата начала"; + // + // label4 + // + label4.AutoSize = true; + label4.Location = new Point(35, 134); + label4.Name = "label4"; + label4.Size = new Size(68, 15); + label4.TabIndex = 5; + label4.Text = "Дата конца"; + // + // comboBoxDoctor + // + comboBoxDoctor.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxDoctor.FormattingEnabled = true; + comboBoxDoctor.Location = new Point(126, 68); + comboBoxDoctor.Name = "comboBoxDoctor"; + comboBoxDoctor.Size = new Size(200, 23); + comboBoxDoctor.TabIndex = 6; + // + // textBoxFilePath + // + textBoxFilePath.Location = new Point(126, 32); + textBoxFilePath.Name = "textBoxFilePath"; + textBoxFilePath.ReadOnly = true; + textBoxFilePath.Size = new Size(165, 23); + textBoxFilePath.TabIndex = 7; + // + // buttonSelectFilePath + // + buttonSelectFilePath.Location = new Point(297, 32); + buttonSelectFilePath.Name = "buttonSelectFilePath"; + buttonSelectFilePath.Size = new Size(29, 23); + buttonSelectFilePath.TabIndex = 8; + buttonSelectFilePath.Text = ".."; + buttonSelectFilePath.UseVisualStyleBackColor = true; + buttonSelectFilePath.Click += ButtonSelectFilePath_Click; + // + // buttonMakeReport + // + buttonMakeReport.Location = new Point(138, 180); + buttonMakeReport.Name = "buttonMakeReport"; + buttonMakeReport.Size = new Size(114, 23); + buttonMakeReport.TabIndex = 9; + buttonMakeReport.Text = "Сформировать"; + buttonMakeReport.UseVisualStyleBackColor = true; + buttonMakeReport.Click += ButtonMakeReport_Click; + // + // FormVisitingReport + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(447, 236); + Controls.Add(buttonMakeReport); + Controls.Add(buttonSelectFilePath); + Controls.Add(textBoxFilePath); + Controls.Add(comboBoxDoctor); + Controls.Add(label4); + Controls.Add(label3); + Controls.Add(label2); + Controls.Add(label1); + Controls.Add(dateTimePickerDateEnd); + Controls.Add(dateTimePickerDateBegin); + Name = "FormVisitingReport"; + Text = "FormVisitingReport"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private DateTimePicker dateTimePickerDateBegin; + private DateTimePicker dateTimePickerDateEnd; + private Label label1; + private Label label2; + private Label label3; + private Label label4; + private ComboBox comboBoxDoctor; + private TextBox textBoxFilePath; + private Button buttonSelectFilePath; + private Button buttonMakeReport; + } +} \ No newline at end of file diff --git a/ProjectPolyclinic/ProjectPolyclinic/Forms/FormVisitingReport.cs b/ProjectPolyclinic/ProjectPolyclinic/Forms/FormVisitingReport.cs new file mode 100644 index 0000000..b052e1f --- /dev/null +++ b/ProjectPolyclinic/ProjectPolyclinic/Forms/FormVisitingReport.cs @@ -0,0 +1,85 @@ +using ProjectPolyclinic.Reports; +using ProjectPolyclinic.Repositories; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using Unity; + +namespace ProjectPolyclinic.Forms +{ + public partial class FormVisitingReport : Form + { + private readonly IUnityContainer _container; + + public FormVisitingReport(IUnityContainer container, IDoctorRepository doctorRepository) + { + InitializeComponent(); + _container = container ?? throw new ArgumentNullException(nameof(container)); + comboBoxDoctor.DataSource = doctorRepository.ReadDoctors(); + comboBoxDoctor.DisplayMember = "FirstName"; + comboBoxDoctor.ValueMember = "Id"; + + } + + private void ButtonSelectFilePath_Click(object sender, EventArgs e) + { + var sfd = new SaveFileDialog() + { + Filter = "Excel Files | *.xlsx" + }; + if (sfd.ShowDialog() != DialogResult.OK) + { + return; + } + textBoxFilePath.Text = sfd.FileName; + } + + private void ButtonMakeReport_Click(object sender, EventArgs e) + { + try + { + if (string.IsNullOrWhiteSpace(textBoxFilePath.Text)) + { + throw new Exception("Отсутствует имя файла для отчета"); + } + if (comboBoxDoctor.SelectedIndex < 0) + { + throw new Exception("Не выбран доктор"); + } + if (dateTimePickerDateEnd.Value <= + dateTimePickerDateBegin.Value) + { + throw new Exception("Дата начала должна быть раньше даты окончания"); + } + if + (_container.Resolve().CreateTable(textBoxFilePath.Text, + (int)comboBoxDoctor.SelectedValue!, + dateTimePickerDateBegin.Value, dateTimePickerDateEnd.Value)) + { + MessageBox.Show("Документ сформирован", + "Формирование документа", + MessageBoxButtons.OK, + MessageBoxIcon.Information); + } + else + { + MessageBox.Show("Возникли ошибки при формировании документа.Подробности в логах", + "Формирование документа", + MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка при создании отчета", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + + } + } +} diff --git a/ProjectPolyclinic/ProjectPolyclinic/Forms/FormVisitingReport.resx b/ProjectPolyclinic/ProjectPolyclinic/Forms/FormVisitingReport.resx new file mode 100644 index 0000000..8b2ff64 --- /dev/null +++ b/ProjectPolyclinic/ProjectPolyclinic/Forms/FormVisitingReport.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/ProjectPolyclinic/ProjectPolyclinic/Reports/DocReport.cs b/ProjectPolyclinic/ProjectPolyclinic/Reports/DocReport.cs new file mode 100644 index 0000000..c86c800 --- /dev/null +++ b/ProjectPolyclinic/ProjectPolyclinic/Reports/DocReport.cs @@ -0,0 +1,84 @@ +using Microsoft.Extensions.Logging; +using ProjectPolyclinic.Repositories; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectPolyclinic.Reports; + +internal class DocReport +{ + private readonly IDoctorRepository _doctorRepository; + private readonly IPatientRepository _patientRepository; + private readonly IMedicationRepository _medicationRepository; + private readonly ILogger _logger; + + public DocReport(IDoctorRepository doctorRepository,IPatientRepository patientRepository,IMedicationRepository medicationRepository, ILogger logger) + { + _doctorRepository = doctorRepository ?? throw new ArgumentNullException(nameof(doctorRepository)); + _patientRepository = patientRepository ?? throw new ArgumentNullException(nameof(patientRepository)); + _medicationRepository = medicationRepository ?? throw new ArgumentNullException(nameof(medicationRepository)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + + } + public bool CreateDoc(string filePath, bool includeDoctors, bool includePatients, bool includeMedicines) + { + try + { + var builder = new WordBuilder(filePath) + .AddHeader("Документ со справочниками"); + if (includeDoctors) + { + builder.AddParagraph("Врачи") + .AddTable([2400, 2400, 2400], + GetDoctors()); + } + if (includePatients) + { + builder.AddParagraph("Пациенты") + .AddTable([2400, 2400, 2400], GetPatients()); + } + if (includeMedicines) + { + builder.AddParagraph("Медикаменты") + .AddTable([2400, 2400, 2400], GetMedicines()); + } + builder.Build(); + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при формировании документа"); + return false; + } + } + private List GetDoctors() + { + return [ + ["Имя доктора", "Фамилия доктора", "Специализация"], + .. _doctorRepository + .ReadDoctors() + .Select(x => new string[] { x.First_Name, x.Last_Name, x.Specialization.ToString()}), + ]; + } + private List GetPatients() + { + return [ + ["Имя пациента ", "Фамилия пациента", "Контактный номер"], + .. _patientRepository + .ReadPatients() + .Select(x => new string[] { x.First_Name, x.Last_Name, x.ContactNumber.ToString()}), + ]; + } + private List GetMedicines() + { + return [ + ["Тип таблетки ", "Доза", "Описание"], + .. _medicationRepository + .ReadMedicines() + .Select(x => new string[] { x.MedicinesType.ToString(), x.Dosing, x.Description}), + ]; + } +} diff --git a/ProjectPolyclinic/ProjectPolyclinic/Reports/ExcelBuilder.cs b/ProjectPolyclinic/ProjectPolyclinic/Reports/ExcelBuilder.cs new file mode 100644 index 0000000..83f41b2 --- /dev/null +++ b/ProjectPolyclinic/ProjectPolyclinic/Reports/ExcelBuilder.cs @@ -0,0 +1,323 @@ +using DocumentFormat.OpenXml; +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Spreadsheet; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectPolyclinic.Reports; + +internal class ExcelBuilder +{ + private readonly string _filePath; + private readonly SheetData _sheetData; + private readonly MergeCells _mergeCells; + private readonly Columns _columns; + private uint _rowIndex = 0; + public ExcelBuilder(string filePath) + { + if (string.IsNullOrWhiteSpace(filePath)) + { + throw new ArgumentNullException(nameof(filePath)); + } + if (File.Exists(filePath)) + { + File.Delete(filePath); + } + _filePath = filePath; + _sheetData = new SheetData(); + _mergeCells = new MergeCells(); + _columns = new Columns(); + _rowIndex = 1; + } + public ExcelBuilder AddHeader(string header, int startIndex, int count) + { + CreateCell(startIndex, _rowIndex, header,StyleIndex.SimpleTextWithoutBorder); + for (int i = startIndex + 1; i < startIndex + count; ++i) + { + CreateCell(i, _rowIndex, "", + StyleIndex.SimpleTextWithoutBorder); + } + _mergeCells.Append(new MergeCell() + { + Reference = + new + StringValue($"{GetExcelColumnName(startIndex)}{_rowIndex}:{GetExcelColumnName(startIndex + count - 1)}{_rowIndex}") + }); + _rowIndex++; + return this; + } + public ExcelBuilder AddParagraph(string text, int columnIndex) + { + CreateCell(columnIndex, _rowIndex++, text,StyleIndex.SimpleTextWithoutBorder); + return this; + } + public ExcelBuilder AddTable(int[] columnsWidths, List data) + { + if (columnsWidths == null || columnsWidths.Length == 0) + { + throw new ArgumentNullException(nameof(columnsWidths)); + } + if (data == null || data.Count == 0) + { + throw new ArgumentNullException(nameof(data)); + } + if (data.Any(x => x.Length != columnsWidths.Length)) + { + throw new InvalidOperationException("widths.Length !=data.Length"); + } + uint counter = 1; + int coef = 2; + _columns.Append(columnsWidths.Select(x => new Column + { + Min = counter, + Max = counter++, + Width = x * coef, + CustomWidth = true + })); + for (var j = 0; j < data.First().Length; ++j) + { + CreateCell(j, _rowIndex, data.First()[j], + StyleIndex.SimpleTextWithoutBorder); + } + _rowIndex++; + for (var i = 1; i < data.Count - 1; ++i) + { + for (var j = 0; j < data[i].Length; ++j) + { + CreateCell(j, _rowIndex, data[i][j], + StyleIndex.SimpleTextWithoutBorder); + } + _rowIndex++; + } + for (var j = 0; j < data.Last().Length; ++j) + { + CreateCell(j, _rowIndex, data.Last()[j], + StyleIndex.SimpleTextWithoutBorder); + } + _rowIndex++; + return this; + } + public void Build() + { + using var spreadsheetDocument = SpreadsheetDocument.Create(_filePath, + SpreadsheetDocumentType.Workbook); + var workbookpart = spreadsheetDocument.AddWorkbookPart(); + GenerateStyle(workbookpart); + workbookpart.Workbook = new Workbook(); + var worksheetPart = workbookpart.AddNewPart(); + worksheetPart.Worksheet = new Worksheet(); + if (_columns.HasChildren) + { + worksheetPart.Worksheet.Append(_columns); + } + worksheetPart.Worksheet.Append(_sheetData); + var sheets = + spreadsheetDocument.WorkbookPart!.Workbook.AppendChild(new Sheets()); + var sheet = new Sheet() + { + Id = + spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), + SheetId = 1, + Name = "Лист 1" + }; + sheets.Append(sheet); + if (_mergeCells.HasChildren) + { + worksheetPart.Worksheet.InsertAfter(_mergeCells, + worksheetPart.Worksheet.Elements().First()); + } + } + private static void GenerateStyle(WorkbookPart workbookPart) + { + var workbookStylesPart = +workbookPart.AddNewPart(); + workbookStylesPart.Stylesheet = new Stylesheet(); + var fonts = new Fonts() + { + Count = 2, + KnownFonts = + BooleanValue.FromBoolean(true) + }; + fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font + { + FontSize = new FontSize() { Val = 11 }, + FontName = new FontName() { Val = "Calibri" }, + FontFamilyNumbering = new FontFamilyNumbering() { Val = 2 }, + FontScheme = new FontScheme() + { + Val = new + EnumValue(FontSchemeValues.Minor) + } + }); + // TODO добавить шрифт с жирным + fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font + { + FontSize = new FontSize() { Val = 11 }, + FontName = new FontName() { Val = "Calibri" }, + Bold = new Bold(), + FontFamilyNumbering = new FontFamilyNumbering() { Val = 2 }, + FontScheme = new FontScheme() + { + Val = new EnumValue(FontSchemeValues.Minor) + } + }); + workbookStylesPart.Stylesheet.Append(fonts); + // Default Fill + var fills = new Fills() { Count = 1 }; + fills.Append(new Fill + { + PatternFill = new PatternFill() + { + PatternType = new + EnumValue(PatternValues.None) + } + }); + workbookStylesPart.Stylesheet.Append(fills); + // Default Border + var borders = new Borders() { Count = 2 }; + borders.Append(new Border + { + LeftBorder = new LeftBorder(), + RightBorder = new RightBorder(), + TopBorder = new TopBorder(), + BottomBorder = new BottomBorder(), + DiagonalBorder = new DiagonalBorder() + }); + // TODO добавить настройку с границами + borders.Append(new Border + { + LeftBorder = new LeftBorder() { Style = BorderStyleValues.Medium }, + RightBorder = new RightBorder() { Style = BorderStyleValues.Medium }, + TopBorder = new TopBorder() { Style = BorderStyleValues.Medium }, + BottomBorder = new BottomBorder() { Style = BorderStyleValues.Medium }, + DiagonalBorder = new DiagonalBorder() { Style = BorderStyleValues.Medium }, + }); + workbookStylesPart.Stylesheet.Append(borders); + // Default cell format and a date cell format + var cellFormats = new CellFormats() { Count = 4 }; + cellFormats.Append(new CellFormat + { + NumberFormatId = 0, + FormatId = 0, + FontId = 0, + BorderId = 0, + FillId = 0, + Alignment = new Alignment() + { + Horizontal = HorizontalAlignmentValues.Left, + Vertical = VerticalAlignmentValues.Center, + WrapText = true + } + }); + // TODO дополнить форматы + cellFormats.Append(new CellFormat + { + NumberFormatId = 1, + FormatId = 0, + FontId = 1, + BorderId = 0, + FillId = 0, + Alignment = new Alignment() + { + Horizontal = HorizontalAlignmentValues.Left, + Vertical = VerticalAlignmentValues.Center, + WrapText = true + } + }); + cellFormats.Append(new CellFormat + { + NumberFormatId = 2, + FormatId = 0, + FontId = 0, + BorderId = 1, + FillId = 0, + Alignment = new Alignment() + { + Horizontal = HorizontalAlignmentValues.Left, + Vertical = VerticalAlignmentValues.Center, + WrapText = true + } + }); + cellFormats.Append(new CellFormat + { + NumberFormatId = 3, + FormatId = 0, + FontId = 1, + BorderId = 1, + FillId = 0, + Alignment = new Alignment() + { + Horizontal = HorizontalAlignmentValues.Left, + Vertical = VerticalAlignmentValues.Center, + WrapText = true + } + }); + workbookStylesPart.Stylesheet.Append(cellFormats); + + } + private enum StyleIndex + { + SimpleTextWithoutBorder = 0, + SimpleTextWithBorder = 1, + BoldTextWithoutBorder = 2, + BoldTextWithBorder = 3, + } + private void CreateCell(int columnIndex, uint rowIndex, string text, +StyleIndex styleIndex) + { + var columnName = GetExcelColumnName(columnIndex); + var cellReference = columnName + rowIndex; + var row = _sheetData.Elements().FirstOrDefault(r => r.RowIndex! + == rowIndex); + if (row == null) + { + row = new Row() { RowIndex = rowIndex }; + _sheetData.Append(row); + } + var newCell = row.Elements() + .FirstOrDefault(c => c.CellReference != null && + c.CellReference.Value == columnName + rowIndex); + if (newCell == null) + { + Cell? refCell = null; + foreach (Cell cell in row.Elements()) + { + if (cell.CellReference?.Value != null && + cell.CellReference.Value.Length == cellReference.Length) + { + if (string.Compare(cell.CellReference.Value, + cellReference, true) > 0) + { + refCell = cell; + break; + } + } + } + newCell = new Cell() { CellReference = cellReference }; + row.InsertBefore(newCell, refCell); + } + newCell.CellValue = new CellValue(text); + newCell.DataType = CellValues.String; + newCell.StyleIndex = (uint)styleIndex; + } + private static string GetExcelColumnName(int columnNumber) + { + columnNumber += 1; + int dividend = columnNumber; + string columnName = string.Empty; + int modulo; + while (dividend > 0) + { + modulo = (dividend - 1) % 26; + columnName = Convert.ToChar(65 + modulo).ToString() + + columnName; + dividend = (dividend - modulo) / 26; + } + return columnName; + } + +} + diff --git a/ProjectPolyclinic/ProjectPolyclinic/Reports/TableReport.cs b/ProjectPolyclinic/ProjectPolyclinic/Reports/TableReport.cs new file mode 100644 index 0000000..676358d --- /dev/null +++ b/ProjectPolyclinic/ProjectPolyclinic/Reports/TableReport.cs @@ -0,0 +1,69 @@ +using Microsoft.Extensions.Logging; +using ProjectPolyclinic.Repositories; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Policy; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectPolyclinic.Reports; + +internal class TableReport +{ + private readonly IDoctorRepository _doctorRepository; + private readonly IVisitingRepository _visitingRepository; + private readonly ILogger _logger; + internal static readonly string[] item = ["Доктор", "Дата", "Количество визитов"]; + public TableReport(IDoctorRepository doctorRepository, IVisitingRepository visitingRepository, ILogger logger) + { + _doctorRepository = doctorRepository ?? throw new ArgumentNullException(nameof(doctorRepository)); + _visitingRepository = visitingRepository ?? throw new ArgumentNullException(nameof(visitingRepository)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + public bool CreateTable(string filePath, int doctorId, DateTime startDate, DateTime endDate) + { + try + { + var data = GetData(doctorId, startDate, endDate); + new ExcelBuilder(filePath) + .AddHeader("Сводка по движению визитов", 0, 2) + .AddParagraph("за период", 0) + .AddTable([10, 15, 15], data) + .Build(); + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при формировании документа"); + return false; + } + } + private List GetData(int doctorId, DateTime startDate, DateTime endDate) + { + var visits = _visitingRepository.ReadVisiting() + .Where(x => x.VisitingTime >= startDate && x.VisitingTime <= endDate && x.DoctorId == doctorId) + .Select(x => new + { + DoctorName = $"{_doctorRepository.ReadDoctorById(x.DoctorId)?.First_Name} {_doctorRepository.ReadDoctorById(x.DoctorId)?.Last_Name}", + Date = x.VisitingTime + }) + .OrderBy(x => x.Date) + .ToList(); + + + var result = new List { item } + .Union(visits.Select(x => new string[] + { + x.DoctorName, + x.Date.ToString("g"), + "1" + })) + .Union([["Всего", " ", visits.Count().ToString()]]) + .ToList(); + + + return result; + } +} \ No newline at end of file diff --git a/ProjectPolyclinic/ProjectPolyclinic/Reports/WordBuilder.cs b/ProjectPolyclinic/ProjectPolyclinic/Reports/WordBuilder.cs index 3f451a0..ed34e20 100644 --- a/ProjectPolyclinic/ProjectPolyclinic/Reports/WordBuilder.cs +++ b/ProjectPolyclinic/ProjectPolyclinic/Reports/WordBuilder.cs @@ -1,59 +1,103 @@ -using DocumentFormat.OpenXml.Wordprocessing; +using DocumentFormat.OpenXml; +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Wordprocessing; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; -namespace ProjectPolyclinic.Reports +namespace ProjectPolyclinic.Reports; + +internal class WordBuilder { - internal class WordBuilder + private readonly string _filePath; + private readonly Document _document; + private readonly Body _body; + public WordBuilder(string filePath) { - private readonly string _filePath; - private readonly Document _document; - private readonly Body _body; - public WordBuilder(string filePath) + if (string.IsNullOrWhiteSpace(filePath)) { - if (string.IsNullOrWhiteSpace(filePath)) + throw new ArgumentNullException(nameof(filePath)); + } + if (File.Exists(filePath)) + { + File.Delete(filePath); + } + _filePath = filePath; + _document = new Document(); + _body = _document.AppendChild(new Body()); + } + public WordBuilder AddHeader(string header) + { + var paragraph = _body.AppendChild(new Paragraph()); + var run = paragraph.AppendChild(new Run()); + run.AppendChild(new RunProperties(new Bold())); + run.AppendChild(new Text(header)); + return this; + + } + public WordBuilder AddParagraph(string text) + { + + var paragraph = _body.AppendChild(new Paragraph()); + var run = paragraph.AppendChild(new Run()); + run.AppendChild(new Text(text)); + + return this; + + } + public WordBuilder AddTable(int[] widths, List data) + { + if (widths == null || widths.Length == 0) + { + throw new ArgumentNullException(nameof(widths)); + } + if (data == null || data.Count == 0) + { + throw new ArgumentNullException(nameof(data)); + } + 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( + new TopBorder() { Val = new EnumValue(BorderValues.Single), Size = 12 }, + new BottomBorder() { Val = new EnumValue(BorderValues.Single), Size = 12 }, + new LeftBorder() { Val = new EnumValue(BorderValues.Single), Size = 12 }, + new RightBorder() { Val = new EnumValue(BorderValues.Single), Size = 12 }, + new InsideHorizontalBorder() { Val = new EnumValue(BorderValues.Single), Size = 12 }, + new InsideVerticalBorder() { Val = new EnumValue(BorderValues.Single), Size = 12 }))); + + // Заголовок + var tr = new TableRow(); + for (var j = 0; j < widths.Length; ++j) + { + tr.Append(new TableCell( + new TableCellProperties(new TableCellWidth() { - throw new ArgumentNullException(nameof(filePath)); - } - if (File.Exists(filePath)) - { - File.Delete(filePath); - } - _filePath = filePath; - _document = new Document(); - _body = _document.AppendChild(new Body()); + Width = + widths[j].ToString() + }), + new Paragraph(new Run(new RunProperties(new Bold()), new + Text(data.First()[j]))))); } - public WordBuilder AddHeader(string header) - { - var paragraph = _body.AppendChild(new Paragraph()); - var run = paragraph.AppendChild(new Run()); - run.AppendChild(new RunProperties(new Bold())); - run.AppendChild(new Text(header)); - return this; + 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; - } - public WordBuilder AddParagraph(string text) - { + } - var paragraph = _body.AppendChild(new Paragraph()); - var run = paragraph.AppendChild(new Run()); - run.AppendChild(new Text(text)); - - return this; - - } - public WordBuilder AddTable(string text) - { - return this; - - } - - public void Build() - { - - } + public void Build() + { + using var wordDocument = WordprocessingDocument.Create(_filePath,WordprocessingDocumentType.Document); + var mainPart = wordDocument.AddMainDocumentPart(); + mainPart.Document = _document; } } diff --git a/ProjectPolyclinic/ProjectPolyclinic/Repositories/IMedicationRepository.cs b/ProjectPolyclinic/ProjectPolyclinic/Repositories/IMedicationRepository.cs index 31d2f13..a97f4a7 100644 --- a/ProjectPolyclinic/ProjectPolyclinic/Repositories/IMedicationRepository.cs +++ b/ProjectPolyclinic/ProjectPolyclinic/Repositories/IMedicationRepository.cs @@ -9,7 +9,7 @@ namespace ProjectPolyclinic.Repositories { public interface IMedicationRepository { - IEnumerable ReadMedication(); + IEnumerable ReadMedicines(); Medication ReadMedicationById(int id); void CreateMedication(Medication medication); void UpdateMedication(Medication medication); diff --git a/ProjectPolyclinic/ProjectPolyclinic/Repositories/Implementations/MedicationRepository.cs b/ProjectPolyclinic/ProjectPolyclinic/Repositories/Implementations/MedicationRepository.cs index f5687ac..c22a9bc 100644 --- a/ProjectPolyclinic/ProjectPolyclinic/Repositories/Implementations/MedicationRepository.cs +++ b/ProjectPolyclinic/ProjectPolyclinic/Repositories/Implementations/MedicationRepository.cs @@ -97,7 +97,7 @@ namespace ProjectPolyclinic.Repositories.Implementations throw; } } - public IEnumerable ReadMedication() + public IEnumerable ReadMedicines() { _logger.LogInformation("Получение всех объектов"); try