diff --git a/StudentProgress/StudentProgress/Entities/Grades.cs b/StudentProgress/StudentProgress/Entities/Grades.cs index c9c4e58..7b89070 100644 --- a/StudentProgress/StudentProgress/Entities/Grades.cs +++ b/StudentProgress/StudentProgress/Entities/Grades.cs @@ -18,4 +18,16 @@ public class Grades StudentGrade = studentGrades }; } + + public static Grades CreateEntity(TempStudentGrades tempStudentGrades, IEnumerable studentGrades) + { + return new Grades + { + Id = tempStudentGrades.Id, + SubjectsId = tempStudentGrades.SubjectsId, + ProfessorsId = tempStudentGrades.ProfessorsId, + Date = tempStudentGrades.Date, + StudentGrade = studentGrades + }; + } } diff --git a/StudentProgress/StudentProgress/Entities/TempStudentGrades.cs b/StudentProgress/StudentProgress/Entities/TempStudentGrades.cs new file mode 100644 index 0000000..c6d6b18 --- /dev/null +++ b/StudentProgress/StudentProgress/Entities/TempStudentGrades.cs @@ -0,0 +1,18 @@ +using StudentProgress.Entities.Enums; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace StudentProgress.Entities; + +public class TempStudentGrades +{ + public int Id { get; private set; } + public int SubjectsId { get; private set; } + public int ProfessorsId { get; private set; } + public DateTime Date { get; private set; } + public int StudentID { get; private set; } + public Grade Grade { get; private set; } +} diff --git a/StudentProgress/StudentProgress/Forms/FormDirectoryReport.Designer.cs b/StudentProgress/StudentProgress/Forms/FormDirectoryReport.Designer.cs new file mode 100644 index 0000000..c08bbec --- /dev/null +++ b/StudentProgress/StudentProgress/Forms/FormDirectoryReport.Designer.cs @@ -0,0 +1,112 @@ +namespace StudentProgress.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() + { + buttonBuild = new Button(); + checkBoxSubjects = new CheckBox(); + checkBoxStudents = new CheckBox(); + checkBoxProfessors = new CheckBox(); + checkBoxGroups = new CheckBox(); + SuspendLayout(); + // + // buttonBuild + // + buttonBuild.Location = new Point(12, 166); + buttonBuild.Name = "buttonBuild"; + buttonBuild.Size = new Size(136, 23); + buttonBuild.TabIndex = 0; + buttonBuild.Text = "Сформировать"; + buttonBuild.UseVisualStyleBackColor = true; + buttonBuild.Click += buttonBuild_Click; + // + // checkBoxSubjects + // + checkBoxSubjects.AutoSize = true; + checkBoxSubjects.Location = new Point(12, 129); + checkBoxSubjects.Name = "checkBoxSubjects"; + checkBoxSubjects.Size = new Size(83, 19); + checkBoxSubjects.TabIndex = 1; + checkBoxSubjects.Text = "Предметы"; + checkBoxSubjects.UseVisualStyleBackColor = true; + // + // checkBoxStudents + // + checkBoxStudents.AutoSize = true; + checkBoxStudents.Location = new Point(12, 91); + checkBoxStudents.Name = "checkBoxStudents"; + checkBoxStudents.Size = new Size(78, 19); + checkBoxStudents.TabIndex = 2; + checkBoxStudents.Text = "Студенты"; + checkBoxStudents.UseVisualStyleBackColor = true; + // + // checkBoxProfessors + // + checkBoxProfessors.AutoSize = true; + checkBoxProfessors.Location = new Point(12, 49); + checkBoxProfessors.Name = "checkBoxProfessors"; + checkBoxProfessors.Size = new Size(111, 19); + checkBoxProfessors.TabIndex = 3; + checkBoxProfessors.Text = "Преподаватели"; + checkBoxProfessors.UseVisualStyleBackColor = true; + // + // checkBoxGroups + // + checkBoxGroups.AutoSize = true; + checkBoxGroups.Location = new Point(12, 12); + checkBoxGroups.Name = "checkBoxGroups"; + checkBoxGroups.Size = new Size(68, 19); + checkBoxGroups.TabIndex = 4; + checkBoxGroups.Text = "Группы"; + checkBoxGroups.UseVisualStyleBackColor = true; + // + // FormDirectoryReport + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(160, 198); + Controls.Add(checkBoxGroups); + Controls.Add(checkBoxProfessors); + Controls.Add(checkBoxStudents); + Controls.Add(checkBoxSubjects); + Controls.Add(buttonBuild); + Name = "FormDirectoryReport"; + Text = "Отчет по справочникам"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Button buttonBuild; + private CheckBox checkBoxSubjects; + private CheckBox checkBoxStudents; + private CheckBox checkBoxProfessors; + private CheckBox checkBoxGroups; + } +} \ No newline at end of file diff --git a/StudentProgress/StudentProgress/Forms/FormDirectoryReport.cs b/StudentProgress/StudentProgress/Forms/FormDirectoryReport.cs new file mode 100644 index 0000000..7067fea --- /dev/null +++ b/StudentProgress/StudentProgress/Forms/FormDirectoryReport.cs @@ -0,0 +1,20 @@ +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; + +namespace StudentProgress.Forms +{ + public partial class FormDirectoryReport : Form + { + public FormDirectoryReport() + { + InitializeComponent(); + } + } +} diff --git a/StudentProgress/StudentProgress/Forms/FormDirectoryReport.resx b/StudentProgress/StudentProgress/Forms/FormDirectoryReport.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/StudentProgress/StudentProgress/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/StudentProgress/StudentProgress/Forms/FormGradeDistribution.Designer.cs b/StudentProgress/StudentProgress/Forms/FormGradeDistribution.Designer.cs new file mode 100644 index 0000000..b0bcbe8 --- /dev/null +++ b/StudentProgress/StudentProgress/Forms/FormGradeDistribution.Designer.cs @@ -0,0 +1,107 @@ +namespace StudentProgress.Forms +{ + partial class FormGradeDistribution + { + /// + /// 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() + { + buttonFile = new Button(); + buttonBuild = new Button(); + dateTimePicker = new DateTimePicker(); + label3 = new Label(); + labelFileName = new Label(); + SuspendLayout(); + // + // buttonFile + // + buttonFile.Location = new Point(12, 6); + buttonFile.Name = "buttonFile"; + buttonFile.Size = new Size(90, 23); + buttonFile.TabIndex = 17; + buttonFile.Text = "Выбрать"; + buttonFile.UseVisualStyleBackColor = true; + buttonFile.Click += buttonFile_Click; + // + // buttonBuild + // + buttonBuild.Location = new Point(12, 64); + buttonBuild.Name = "buttonBuild"; + buttonBuild.Size = new Size(217, 23); + buttonBuild.TabIndex = 16; + buttonBuild.Text = "Сформировать"; + buttonBuild.UseVisualStyleBackColor = true; + buttonBuild.Click += buttonBuild_Click; + // + // dateTimePicker + // + dateTimePicker.Location = new Point(53, 35); + dateTimePicker.Name = "dateTimePicker"; + dateTimePicker.Size = new Size(176, 23); + dateTimePicker.TabIndex = 13; + // + // label3 + // + label3.AutoSize = true; + label3.Location = new Point(12, 41); + label3.Name = "label3"; + label3.Size = new Size(35, 15); + label3.TabIndex = 11; + label3.Text = "Дата:"; + // + // labelFileName + // + labelFileName.AutoSize = true; + labelFileName.Location = new Point(108, 10); + labelFileName.Name = "labelFileName"; + labelFileName.Size = new Size(36, 15); + labelFileName.TabIndex = 10; + labelFileName.Text = "Файл"; + // + // FormGradeDistribution + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(242, 101); + Controls.Add(buttonFile); + Controls.Add(buttonBuild); + Controls.Add(dateTimePicker); + Controls.Add(label3); + Controls.Add(labelFileName); + Name = "FormGradeDistribution"; + Text = "Отчет распределения оценок"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Button buttonFile; + private Button buttonBuild; + private DateTimePicker dateTimePicker; + private Label label3; + private Label labelFileName; + } +} \ No newline at end of file diff --git a/StudentProgress/StudentProgress/Forms/FormGradeDistribution.cs b/StudentProgress/StudentProgress/Forms/FormGradeDistribution.cs new file mode 100644 index 0000000..4633372 --- /dev/null +++ b/StudentProgress/StudentProgress/Forms/FormGradeDistribution.cs @@ -0,0 +1,20 @@ +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; + +namespace StudentProgress.Forms +{ + public partial class FormGradeDistribution : Form + { + public FormGradeDistribution() + { + InitializeComponent(); + } + } +} diff --git a/StudentProgress/StudentProgress/Forms/FormGradeDistribution.resx b/StudentProgress/StudentProgress/Forms/FormGradeDistribution.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/StudentProgress/StudentProgress/Forms/FormGradeDistribution.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/StudentProgress/StudentProgress/Forms/FormStudentGradeReport.Designer.cs b/StudentProgress/StudentProgress/Forms/FormStudentGradeReport.Designer.cs new file mode 100644 index 0000000..e69d774 --- /dev/null +++ b/StudentProgress/StudentProgress/Forms/FormStudentGradeReport.Designer.cs @@ -0,0 +1,162 @@ +namespace StudentProgress.Forms +{ + partial class FormStudentGradeReport + { + /// + /// 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() + { + label1 = new Label(); + label2 = new Label(); + label3 = new Label(); + label4 = new Label(); + dateTimePickerStart = new DateTimePicker(); + dateTimePickerEnd = new DateTimePicker(); + textBoxFilePath = new TextBox(); + buttonBuild = new Button(); + comboBoxStudent = new ComboBox(); + buttonFile = new Button(); + SuspendLayout(); + // + // label1 + // + label1.AutoSize = true; + label1.Location = new Point(12, 15); + label1.Name = "label1"; + label1.Size = new Size(90, 15); + label1.TabIndex = 0; + label1.Text = "Путь до файла:"; + // + // label2 + // + label2.AutoSize = true; + label2.Location = new Point(12, 51); + label2.Name = "label2"; + label2.Size = new Size(50, 15); + label2.TabIndex = 1; + label2.Text = "Студент"; + // + // label3 + // + label3.AutoSize = true; + label3.Location = new Point(12, 86); + label3.Name = "label3"; + label3.Size = new Size(77, 15); + label3.TabIndex = 2; + label3.Text = "Дата начала:"; + // + // label4 + // + label4.AutoSize = true; + label4.Location = new Point(12, 123); + label4.Name = "label4"; + label4.Size = new Size(71, 15); + label4.TabIndex = 3; + label4.Text = "Дата конца:"; + // + // dateTimePickerStart + // + dateTimePickerStart.Location = new Point(108, 80); + dateTimePickerStart.Name = "dateTimePickerStart"; + dateTimePickerStart.Size = new Size(205, 23); + dateTimePickerStart.TabIndex = 4; + // + // dateTimePickerEnd + // + dateTimePickerEnd.Location = new Point(108, 117); + dateTimePickerEnd.Name = "dateTimePickerEnd"; + dateTimePickerEnd.Size = new Size(205, 23); + dateTimePickerEnd.TabIndex = 5; + // + // textBoxFilePath + // + textBoxFilePath.Location = new Point(108, 12); + textBoxFilePath.Name = "textBoxFilePath"; + textBoxFilePath.Size = new Size(161, 23); + textBoxFilePath.TabIndex = 6; + // + // buttonBuild + // + buttonBuild.Location = new Point(12, 155); + buttonBuild.Name = "buttonBuild"; + buttonBuild.Size = new Size(301, 23); + buttonBuild.TabIndex = 7; + buttonBuild.Text = "Сформировать"; + buttonBuild.UseVisualStyleBackColor = true; + buttonBuild.Click += buttonBuild_Click; + // + // comboBoxStudent + // + comboBoxStudent.FormattingEnabled = true; + comboBoxStudent.Location = new Point(109, 48); + comboBoxStudent.Name = "comboBoxStudent"; + comboBoxStudent.Size = new Size(204, 23); + comboBoxStudent.TabIndex = 8; + // + // buttonFile + // + buttonFile.Location = new Point(275, 12); + buttonFile.Name = "buttonFile"; + buttonFile.Size = new Size(38, 23); + buttonFile.TabIndex = 9; + buttonFile.Text = "..."; + buttonFile.UseVisualStyleBackColor = true; + buttonFile.Click += buttonFile_Click; + // + // FormStudentGradeReport + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(326, 189); + Controls.Add(buttonFile); + Controls.Add(comboBoxStudent); + Controls.Add(buttonBuild); + Controls.Add(textBoxFilePath); + Controls.Add(dateTimePickerEnd); + Controls.Add(dateTimePickerStart); + Controls.Add(label4); + Controls.Add(label3); + Controls.Add(label2); + Controls.Add(label1); + Name = "FormStudentGradeReport"; + Text = "Отчет по успеваемости студента"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Label label1; + private Label label2; + private Label label3; + private Label label4; + private DateTimePicker dateTimePickerStart; + private DateTimePicker dateTimePickerEnd; + private TextBox textBoxFilePath; + private Button buttonBuild; + private ComboBox comboBoxStudent; + private Button buttonFile; + } +} \ No newline at end of file diff --git a/StudentProgress/StudentProgress/Forms/FormStudentGradeReport.cs b/StudentProgress/StudentProgress/Forms/FormStudentGradeReport.cs new file mode 100644 index 0000000..5b8a76e --- /dev/null +++ b/StudentProgress/StudentProgress/Forms/FormStudentGradeReport.cs @@ -0,0 +1,20 @@ +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; + +namespace StudentProgress.Forms +{ + public partial class FormStudentGradeReport : Form + { + public FormStudentGradeReport() + { + InitializeComponent(); + } + } +} diff --git a/StudentProgress/StudentProgress/Forms/FormStudentGradeReport.resx b/StudentProgress/StudentProgress/Forms/FormStudentGradeReport.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/StudentProgress/StudentProgress/Forms/FormStudentGradeReport.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/StudentProgress/StudentProgress/Reports/ChartReport.cs b/StudentProgress/StudentProgress/Reports/ChartReport.cs new file mode 100644 index 0000000..f46ec72 --- /dev/null +++ b/StudentProgress/StudentProgress/Reports/ChartReport.cs @@ -0,0 +1,56 @@ +using Microsoft.Extensions.Logging; +using StudentProgress.Repositories; +using StudentProgress.Repositories.Implementations; +using System.Reflection.PortableExecutable; + +namespace StudentProgress.Reports; + +internal class ChartReport +{ + private readonly IGradesRepository _gradesRepository; + private readonly ISubjectsRepository _subjectsRepository; + private readonly ILogger _logger; + + public ChartReport(IGradesRepository gradesRepository, ISubjectsRepository subjectsRepository, ILogger logger) + { + _gradesRepository = gradesRepository ?? throw new ArgumentNullException(nameof(gradesRepository)); + _subjectsRepository = subjectsRepository ?? throw new ArgumentNullException(nameof(subjectsRepository)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + public bool CreateChart(string filePath, DateTime dateTime) + { + try + { + new PdfBuilder(filePath) + .AddHeader("Диаграмма по оценкам") + .AddPieChart("Распределение оценок по предметам", GetData(dateTime)) + .Build(); + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при формировании диаграммы"); + return false; + } + } + + private List<(string Caption, double Value)> GetData(DateTime dateTime) + { + // Получаем названия предметов + var subjectNames = _subjectsRepository + .ReadSubjects() + .ToDictionary(s => s.Id, s => s.NameSubject); + + // Группируем оценки по предметам за конкретный день + return _gradesRepository + .ReadGrades() + .Where(g => g.Date.Date == dateTime.Date) // Фильтруем по дате + .GroupBy(g => g.SubjectsId) // Группировка по ID предмета + .Select(g => ( + Caption: subjectNames.TryGetValue(g.Key, out var name) ? name : "Неизвестный предмет", + Value: (double)g.SelectMany(grade => grade.StudentGrade).Count() // Количество оценок + )) + .ToList(); + } +} diff --git a/StudentProgress/StudentProgress/Reports/DocReport.cs b/StudentProgress/StudentProgress/Reports/DocReport.cs new file mode 100644 index 0000000..9d8504d --- /dev/null +++ b/StudentProgress/StudentProgress/Reports/DocReport.cs @@ -0,0 +1,93 @@ +using Microsoft.Extensions.Logging; +using StudentProgress.Repositories; + +namespace StudentProgress.Reports; + +public class DocReport +{ + private readonly IGroupRepository _groupRepository; + private readonly IProfessorsRepository _professorsRepository; + private readonly IStudentRepository _studentRepository; + private readonly ISubjectsRepository _subjectsRepository; + private readonly ILogger _logger; + + public DocReport(IGroupRepository groupRepository, IProfessorsRepository professorsRepository, IStudentRepository studentRepository, ISubjectsRepository subjectsRepository, ILogger logger) + { + _groupRepository = groupRepository ?? throw new ArgumentNullException(nameof(groupRepository)); + _professorsRepository = professorsRepository ?? throw new ArgumentNullException(nameof(professorsRepository)); + _studentRepository = studentRepository ?? throw new ArgumentNullException(nameof(studentRepository)); + _subjectsRepository = subjectsRepository ?? throw new ArgumentNullException(nameof(subjectsRepository)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + public bool CreateDoc(string filePath, bool includeGroups, bool includeProfessors, bool includeStudents, bool includeSubjects) + { + try + { + var builder = new WordBuilder(filePath).AddHeader("Документ со справочниками"); + if (includeGroups) + { + builder.AddParagraph("Группы").AddTable([2400], GetGroups()); + } + if (includeProfessors) + { + builder.AddParagraph("Преподаватели").AddTable([2400, 2400], GetProfessors()); + } + if (includeStudents) + { + builder.AddParagraph("Студенты").AddTable([2400, 2400], GetStudents()); + } + if (includeSubjects) + { + builder.AddParagraph("Предметы").AddTable([2400, 2400], GetSubjects()); + } + builder.Build(); + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при формировании документа"); + return false; + } + } + + private List GetGroups() + { + return [ + ["Название группы"], + .. _groupRepository + .ReadGroup() + .Select(x => new string[] { x.NameGroup }), + ]; + } + + private List GetProfessors() + { + return [ + ["Имя", "Фамилия"], + .. _professorsRepository + .ReadProfessors() + .Select(x => new string[] { x.FirstName, x.Surname }), + ]; + } + + private List GetStudents() + { + return [ + ["Имя", "Фамилия"], + .. _studentRepository + .ReadStudents() + .Select(x => new string[] { x.Name, x.Surname }), + ]; + } + + private List GetSubjects() + { + return [ + ["Название предмета", "Курсы"], + .. _subjectsRepository + .ReadSubjects() + .Select(x => new string[] { x.NameSubject, x.Course.ToString() }), + ]; + } +} diff --git a/StudentProgress/StudentProgress/Reports/ExcelBuilder.cs b/StudentProgress/StudentProgress/Reports/ExcelBuilder.cs new file mode 100644 index 0000000..32cd210 --- /dev/null +++ b/StudentProgress/StudentProgress/Reports/ExcelBuilder.cs @@ -0,0 +1,314 @@ +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Spreadsheet; +using DocumentFormat.OpenXml; +using Microsoft.Extensions.Primitives; +using Serilog.Parsing; +using static Npgsql.Replication.PgOutput.Messages.RelationMessage; + +namespace StudentProgress.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.BoldTextWithoutBorder); + 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.BoldTextWithBorder); + } + _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.SimpleTextWithBorder); + } + _rowIndex++; + } + for (var j = 0; j < data.Last().Length; ++j) + { + CreateCell(j, _rowIndex, data.Last()[j], StyleIndex.BoldTextWithBorder); + } + _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) + } + }); + 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) + }, + Bold = new Bold() { Val = true } + }); + 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() + }); + borders.Append(new Border + { + LeftBorder = new LeftBorder() { Style = BorderStyleValues.Thin }, + RightBorder = new RightBorder() { Style = BorderStyleValues.Thin }, + TopBorder = new TopBorder() { Style = BorderStyleValues.Thin }, + BottomBorder = new BottomBorder() { Style = BorderStyleValues.Thin }, + DiagonalBorder = new DiagonalBorder() + }); + 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 + } + }); + cellFormats.Append(new CellFormat + { + NumberFormatId = 0, + FormatId = 0, + FontId = 0, + BorderId = 1, + FillId = 0, + Alignment = new Alignment() + { + Horizontal = HorizontalAlignmentValues.Right, + Vertical = VerticalAlignmentValues.Center, + WrapText = true + } + }); + cellFormats.Append(new CellFormat + { + NumberFormatId = 0, + FormatId = 0, + FontId = 1, + BorderId = 0, + FillId = 0, + Alignment = new Alignment() + { + Horizontal = HorizontalAlignmentValues.Center, + Vertical = VerticalAlignmentValues.Center, + WrapText = true + } + }); + cellFormats.Append(new CellFormat + { + NumberFormatId = 0, + FormatId = 0, + FontId = 1, + BorderId = 1, + FillId = 0, + Alignment = new Alignment() + { + Horizontal = HorizontalAlignmentValues.Center, + 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/StudentProgress/StudentProgress/Reports/PdfBuilder.cs b/StudentProgress/StudentProgress/Reports/PdfBuilder.cs new file mode 100644 index 0000000..48471eb --- /dev/null +++ b/StudentProgress/StudentProgress/Reports/PdfBuilder.cs @@ -0,0 +1,77 @@ +using MigraDoc.DocumentObjectModel; +using MigraDoc.DocumentObjectModel.Shapes.Charts; +using MigraDoc.Rendering; +using System.Reflection.Metadata; +using System.Text; + +namespace StudentProgress.Reports; + +internal class PdfBuilder +{ + private readonly string _filePath; + private readonly Document _document; + + public PdfBuilder(string filePath) + { + if (string.IsNullOrWhiteSpace(filePath)) + { + throw new ArgumentNullException(nameof(filePath)); + } + if (File.Exists(filePath)) + { + File.Delete(filePath); + } + _filePath = filePath; + _document = new Document(); + DefineStyles(); + } + + public PdfBuilder AddHeader(string header) + { + _document.AddSection().AddParagraph(header, "NormalBold"); + return this; + } + + public PdfBuilder AddPieChart(string title, List<(string Caption, double Value)> data) + { + if (data == null || data.Count == 0) + { + return this; + } + var chart = new Chart(ChartType.Pie2D); + var series = chart.SeriesCollection.AddSeries(); + series.Add(data.Select(x => x.Value).ToArray()); + var xseries = chart.XValues.AddXSeries(); + xseries.Add(data.Select(x => x.Caption).ToArray()); + chart.DataLabel.Type = DataLabelType.Percent; + chart.DataLabel.Position = DataLabelPosition.OutsideEnd; + chart.Width = Unit.FromCentimeter(16); + chart.Height = Unit.FromCentimeter(12); + chart.TopArea.AddParagraph(title); + chart.XAxis.MajorTickMark = TickMarkType.Outside; + chart.YAxis.MajorTickMark = TickMarkType.Outside; + chart.YAxis.HasMajorGridlines = true; + chart.PlotArea.LineFormat.Width = 1; + chart.PlotArea.LineFormat.Visible = true; + chart.TopArea.AddLegend(); + _document.LastSection.Add(chart); + return this; + } + + public void Build() + { + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + var renderer = new PdfDocumentRenderer(true) + { + Document = _document + }; + renderer.RenderDocument(); + renderer.PdfDocument.Save(_filePath); + } + private void DefineStyles() + { + var headerStyle = _document.Styles.AddStyle("NormalBold", "Normal"); + headerStyle.Font.Bold = true; + headerStyle.Font.Size = 14; + } +} diff --git a/StudentProgress/StudentProgress/Reports/TableReport.cs b/StudentProgress/StudentProgress/Reports/TableReport.cs new file mode 100644 index 0000000..056395c --- /dev/null +++ b/StudentProgress/StudentProgress/Reports/TableReport.cs @@ -0,0 +1,85 @@ +using Microsoft.Extensions.Logging; +using StudentProgress.Repositories; +using StudentProgress.Repositories.Implementations; + +namespace StudentProgress.Reports; + +internal class TableReport +{ + private readonly IGradesRepository _gradesRepository; + private readonly IProfessorsRepository _professorsRepository; + private readonly ISubjectsRepository _subjectsRepository; + private readonly ILogger _logger; + internal static readonly string[] item = ["Дата", "Предмет", "Оценка", "Преподаватель"]; + + public TableReport(IGradesRepository gradesRepository, IProfessorsRepository professorsRepository, ISubjectsRepository subjectsRepository, ILogger logger) + { + _gradesRepository = gradesRepository ?? throw new ArgumentNullException(nameof(gradesRepository)); + _professorsRepository = professorsRepository ?? throw new ArgumentNullException(nameof(professorsRepository)); + _subjectsRepository = subjectsRepository ?? throw new ArgumentNullException(nameof(subjectsRepository)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + public bool CreateTable(string filePath, int studentId, DateTime startDate, DateTime endDate) + { + try + { + new ExcelBuilder(filePath) + .AddHeader("Сводка по оценкам", 0, 4) + .AddParagraph("за период", 0) + .AddTable([10, 15, 15, 15], GetData(studentId, startDate, endDate)) + .Build(); + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при формировании документа"); + return false; + } + } + + private List GetData(int studentId, DateTime startDate, DateTime endDate) + { + var subjects = _subjectsRepository + .ReadSubjects() + .ToDictionary(s => s.Id, s => s.NameSubject); + + var professors = _professorsRepository + .ReadProfessors() + .ToDictionary(p => p.Id, p => $"{p.Surname} {p.FirstName}"); + + // Получаем оценки за диапазон дат для указанного студента + var gradesData = _gradesRepository + .ReadGrades() + .Where(g => g.Date >= startDate && g.Date <= endDate + && g.StudentGrade.Any(sg => sg.StudentID == studentId)) + .Select(g => new + { + Date = g.Date, + Subject = subjects.TryGetValue(g.SubjectsId, out var subject) ? subject : "Неизвестный предмет", + Grade = (int)g.StudentGrade.First(sg => sg.StudentID == studentId).Grade, + Professor = professors.TryGetValue(g.ProfessorsId, out var prof) ? prof : "Неизвестный преподаватель" + }) + .ToList(); + + var averageGrade = gradesData.Any() ? gradesData.Average(g => g.Grade) : 0; + + // Формируем заголовки и строки для таблицы + return new List { item } + .Union(gradesData.Select(g => new string[] + { + g.Date.ToString("dd.MM.yyyy"), + g.Subject, + g.Grade.ToString(), + g.Professor + })) + .Union(new[] + { + new string[] + { + "Средний балл", "", averageGrade.ToString("0.00"), "" + } + }) + .ToList(); + } +} diff --git a/StudentProgress/StudentProgress/Reports/WordBuilder.cs b/StudentProgress/StudentProgress/Reports/WordBuilder.cs new file mode 100644 index 0000000..56d97bc --- /dev/null +++ b/StudentProgress/StudentProgress/Reports/WordBuilder.cs @@ -0,0 +1,133 @@ +using DocumentFormat.OpenXml.Drawing.Charts; +using DocumentFormat.OpenXml; +using DocumentFormat.OpenXml.Wordprocessing; +using DocumentFormat.OpenXml.Packaging; +using static System.Net.Mime.MediaTypeNames; +using static System.Windows.Forms.VisualStyles.VisualStyleElement.Tab; +using System.Reflection.Metadata; + +namespace StudentProgress.Reports; + +public class WordBuilder +{ + private readonly string _filePath; + private readonly Document _document; + private readonly Body _body; + + public WordBuilder(string 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()); + var runProperties = run.AppendChild(new RunProperties()); + runProperties.AppendChild(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() + { + Width = + widths[j].ToString() + }), + new Paragraph(new Run(new RunProperties(new Bold()), new + Text(data.First()[j]))))); + } + 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 void Build() + { + using var wordDocument = WordprocessingDocument.Create(_filePath, +WordprocessingDocumentType.Document); + var mainPart = wordDocument.AddMainDocumentPart(); + mainPart.Document = _document; + } +} diff --git a/StudentProgress/StudentProgress/StudentProgress.csproj b/StudentProgress/StudentProgress/StudentProgress.csproj index df12085..83259bb 100644 --- a/StudentProgress/StudentProgress/StudentProgress.csproj +++ b/StudentProgress/StudentProgress/StudentProgress.csproj @@ -10,11 +10,13 @@ + +