diff --git a/StudentProgressRecord/Entity/Marks.cs b/StudentProgressRecord/Entity/Marks.cs index 641d923..5eaca43 100644 --- a/StudentProgressRecord/Entity/Marks.cs +++ b/StudentProgressRecord/Entity/Marks.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -8,19 +9,26 @@ namespace StudentProgressRecord.Entity { public class Marks { + + public long StatementId { get; set; } + [Browsable(false)] public long StudentId { get; set; } public int Mark { get; set; } - public static Marks CreateElement(long statementId, long studentId, int mark) + public string StudentName { get; set; } = string.Empty; + + + public static Marks CreateElement(long statementId, long studentId, int mark, string studentName="") { return new Marks { StatementId = statementId, StudentId = studentId, - Mark = mark + Mark = mark, + StudentName = studentName }; } diff --git a/StudentProgressRecord/Entity/Statement.cs b/StudentProgressRecord/Entity/Statement.cs index 6c7c009..bedf569 100644 --- a/StudentProgressRecord/Entity/Statement.cs +++ b/StudentProgressRecord/Entity/Statement.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.ComponentModel; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; @@ -11,14 +12,27 @@ namespace StudentProgressRecord.Entity { public long Id { get; set; } + [Browsable(false)] public long SubjectId { get; set; } + [Browsable(false)] public long TeacherId { get; set; } + [DisplayName("Дата")] public DateTime Date { get; set; } + [DisplayName("Название предмета")] + public string SubjectName { get; set; } = string.Empty; + + [DisplayName("Преподователь")] + public string TeacherName { get; set; } = string.Empty; + + [Browsable(false)] public IEnumerable Marks { get; set; } = []; + [DisplayName("Оценки")] + public string Mark => Marks != null ? string.Join(", ", Marks.Select(x => $"{x.StudentName} {x.Mark}")) : string.Empty; + public static Statement CreateOperation(long id, long subjectId, long teacherId, DateTime timeStamp, IEnumerable marks) { @@ -32,5 +46,19 @@ namespace StudentProgressRecord.Entity }; } + public static Statement CreateOperation(TempStatement statement, IEnumerable marks) + { + return new Statement + { + Id = statement.Id, + SubjectId = statement.SubjectId, + TeacherId = statement.TeacherId, + SubjectName = statement.SubjectName, + TeacherName = statement.TeacherName, + Date = statement.Date, + Marks = marks + }; + } + } } diff --git a/StudentProgressRecord/Entity/Student.cs b/StudentProgressRecord/Entity/Student.cs index ba2ed2c..9f00cf0 100644 --- a/StudentProgressRecord/Entity/Student.cs +++ b/StudentProgressRecord/Entity/Student.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -11,10 +12,14 @@ namespace StudentProgressRecord.Entity public long Id { get; set; } + [DisplayName("Имя")] public string Name { get; set; } + [DisplayName("Семейное положение")] public bool FamilyPos { get; set; } + + [DisplayName("Общажитие")] public bool Domitory { get; set; } diff --git a/StudentProgressRecord/Entity/StudentTransition.cs b/StudentProgressRecord/Entity/StudentTransition.cs index 5e69af6..6dc3da7 100644 --- a/StudentProgressRecord/Entity/StudentTransition.cs +++ b/StudentProgressRecord/Entity/StudentTransition.cs @@ -1,6 +1,7 @@ using StudentProgressRecord.Entity.Enums; using System; using System.Collections.Generic; +using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -12,10 +13,18 @@ namespace StudentProgressRecord.Entity public long Id { get; set; } + [Browsable(false)] public long StudentId { get; set; } + [DisplayName("Студент")] + public string StudentName { get; set; } = string.Empty; + + [DisplayName("Тип операции")] public Operations Operation { get; set; } + + + [DisplayName("Дата")] public DateTime Date { get; set; } public static StudentTransition CreateOperation(long id, long studentId, Operations operation, DateTime time) diff --git a/StudentProgressRecord/Entity/Subject.cs b/StudentProgressRecord/Entity/Subject.cs index 16598d6..d0c509c 100644 --- a/StudentProgressRecord/Entity/Subject.cs +++ b/StudentProgressRecord/Entity/Subject.cs @@ -1,6 +1,7 @@ using StudentProgressRecord.Entity.Enums; using System; using System.Collections.Generic; +using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -11,8 +12,12 @@ namespace StudentProgressRecord.Entity { public long Id { get; set; } + + [DisplayName("Название")] public string Name { get; set; } + + [DisplayName("Направление")] public Direction direction { get; set; } public static Subject CreateEntity(long id, string name, Direction direction) diff --git a/StudentProgressRecord/Entity/Teacher.cs b/StudentProgressRecord/Entity/Teacher.cs index 410b19f..1049fdc 100644 --- a/StudentProgressRecord/Entity/Teacher.cs +++ b/StudentProgressRecord/Entity/Teacher.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -10,6 +11,8 @@ namespace StudentProgressRecord.Entity { public long Id { get; set; } + + [DisplayName("Имя")] public string Name { get; set; } public static Teacher CreateEntity(long id, string name) diff --git a/StudentProgressRecord/Entity/TempStatement.cs b/StudentProgressRecord/Entity/TempStatement.cs new file mode 100644 index 0000000..673c473 --- /dev/null +++ b/StudentProgressRecord/Entity/TempStatement.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace StudentProgressRecord.Entity +{ + public class TempStatement + { + public int Id { get; set; } + + public long SubjectId { get; set; } + + public string SubjectName { get; set; } + + public long TeacherId { get; set; } + + public string TeacherName { get; set; } + + public DateTime Date { get; set; } + + public long StudentId { get; set; } + + public int Mark { get; set; } + + public string StudentName { get; set; } + } +} diff --git a/StudentProgressRecord/Forms/FormDirectoryReport.Designer.cs b/StudentProgressRecord/Forms/FormDirectoryReport.Designer.cs new file mode 100644 index 0000000..756cfc1 --- /dev/null +++ b/StudentProgressRecord/Forms/FormDirectoryReport.Designer.cs @@ -0,0 +1,100 @@ +namespace StudentProgressRecord.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() + { + checkBoxStudent = new CheckBox(); + checkBoxSubject = new CheckBox(); + checkBoxTeacher = new CheckBox(); + buttonApply = new Button(); + SuspendLayout(); + // + // checkBoxStudent + // + checkBoxStudent.AutoSize = true; + checkBoxStudent.Location = new Point(12, 12); + checkBoxStudent.Name = "checkBoxStudent"; + checkBoxStudent.Size = new Size(84, 24); + checkBoxStudent.TabIndex = 0; + checkBoxStudent.Text = "Студент"; + checkBoxStudent.UseVisualStyleBackColor = true; + // + // checkBoxSubject + // + checkBoxSubject.AutoSize = true; + checkBoxSubject.Location = new Point(12, 42); + checkBoxSubject.Name = "checkBoxSubject"; + checkBoxSubject.Size = new Size(92, 24); + checkBoxSubject.TabIndex = 1; + checkBoxSubject.Text = "Предмет"; + checkBoxSubject.UseVisualStyleBackColor = true; + // + // checkBoxTeacher + // + checkBoxTeacher.AutoSize = true; + checkBoxTeacher.Location = new Point(12, 72); + checkBoxTeacher.Name = "checkBoxTeacher"; + checkBoxTeacher.Size = new Size(88, 24); + checkBoxTeacher.TabIndex = 2; + checkBoxTeacher.Text = "Препод."; + checkBoxTeacher.UseVisualStyleBackColor = true; + // + // buttonApply + // + buttonApply.Location = new Point(119, 39); + buttonApply.Name = "buttonApply"; + buttonApply.Size = new Size(129, 29); + buttonApply.TabIndex = 3; + buttonApply.Text = "Сформировать"; + buttonApply.UseVisualStyleBackColor = true; + buttonApply.Click += this.ButtonBuild_Click; + // + // FormDirectoryReport + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(266, 119); + Controls.Add(buttonApply); + Controls.Add(checkBoxTeacher); + Controls.Add(checkBoxSubject); + Controls.Add(checkBoxStudent); + Name = "FormDirectoryReport"; + StartPosition = FormStartPosition.CenterParent; + Text = "ОтчетСправочник"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private CheckBox checkBoxStudent; + private CheckBox checkBoxSubject; + private CheckBox checkBoxTeacher; + private Button buttonApply; + } +} \ No newline at end of file diff --git a/StudentProgressRecord/Forms/FormDirectoryReport.cs b/StudentProgressRecord/Forms/FormDirectoryReport.cs new file mode 100644 index 0000000..1ee2b59 --- /dev/null +++ b/StudentProgressRecord/Forms/FormDirectoryReport.cs @@ -0,0 +1,65 @@ +using StudentProgressRecord.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 StudentProgressRecord.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 (!checkBoxStudent.Checked && + !checkBoxSubject.Checked && !checkBoxTeacher.Checked) + { + throw new Exception("Не выбран ни один справочник для выгрузки"); + } + var sfd = new SaveFileDialog() + { + Filter = "Docx Files | *.docx" + }; + if (sfd.ShowDialog() != DialogResult.OK) + { + throw new Exception("Не выбран файла для отчета"); + } + if + (_container.Resolve().CreateDock(sfd.FileName, checkBoxSubject.Checked, + checkBoxStudent.Checked, + checkBoxTeacher.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/StudentProgressRecord/Forms/FormDirectoryReport.resx b/StudentProgressRecord/Forms/FormDirectoryReport.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/StudentProgressRecord/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/StudentProgressRecord/Forms/FormOperationsReport.Designer.cs b/StudentProgressRecord/Forms/FormOperationsReport.Designer.cs new file mode 100644 index 0000000..ac0799a --- /dev/null +++ b/StudentProgressRecord/Forms/FormOperationsReport.Designer.cs @@ -0,0 +1,162 @@ +namespace StudentProgressRecord.Forms +{ + partial class FormOperationsReport + { + /// + /// 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() + { + labelFilePath = new Label(); + textBoxFilePath = new TextBox(); + buttonFilePath = new Button(); + labelStudent = new Label(); + comboBoxStudent = new ComboBox(); + dateTimePickerStart = new DateTimePicker(); + dateTimePickerEnd = new DateTimePicker(); + labelDateFrom = new Label(); + labelDateTo = new Label(); + buttonApply = new Button(); + SuspendLayout(); + // + // labelFilePath + // + labelFilePath.AutoSize = true; + labelFilePath.Location = new Point(12, 24); + labelFilePath.Name = "labelFilePath"; + labelFilePath.Size = new Size(109, 20); + labelFilePath.TabIndex = 0; + labelFilePath.Text = "Путь до файла"; + // + // textBoxFilePath + // + textBoxFilePath.Location = new Point(127, 24); + textBoxFilePath.Name = "textBoxFilePath"; + textBoxFilePath.Size = new Size(168, 27); + textBoxFilePath.TabIndex = 1; + // + // buttonFilePath + // + buttonFilePath.Location = new Point(301, 23); + buttonFilePath.Name = "buttonFilePath"; + buttonFilePath.Size = new Size(26, 29); + buttonFilePath.TabIndex = 2; + buttonFilePath.Text = "..."; + buttonFilePath.UseVisualStyleBackColor = true; + buttonFilePath.Click += ButtonSelectFilePath_Click; + // + // labelStudent + // + labelStudent.AutoSize = true; + labelStudent.Location = new Point(12, 75); + labelStudent.Name = "labelStudent"; + labelStudent.Size = new Size(62, 20); + labelStudent.TabIndex = 3; + labelStudent.Text = "Студент"; + // + // comboBoxStudent + // + comboBoxStudent.FormattingEnabled = true; + comboBoxStudent.Location = new Point(127, 72); + comboBoxStudent.Name = "comboBoxStudent"; + comboBoxStudent.Size = new Size(168, 28); + comboBoxStudent.TabIndex = 4; + // + // dateTimePickerStart + // + dateTimePickerStart.Location = new Point(127, 144); + dateTimePickerStart.Name = "dateTimePickerStart"; + dateTimePickerStart.Size = new Size(200, 27); + dateTimePickerStart.TabIndex = 5; + // + // dateTimePickerEnd + // + dateTimePickerEnd.Location = new Point(127, 194); + dateTimePickerEnd.Name = "dateTimePickerEnd"; + dateTimePickerEnd.Size = new Size(200, 27); + dateTimePickerEnd.TabIndex = 6; + // + // labelDateFrom + // + labelDateFrom.AutoSize = true; + labelDateFrom.Location = new Point(12, 151); + labelDateFrom.Name = "labelDateFrom"; + labelDateFrom.Size = new Size(60, 20); + labelDateFrom.TabIndex = 7; + labelDateFrom.Text = "Дата от"; + // + // labelDateTo + // + labelDateTo.AutoSize = true; + labelDateTo.Location = new Point(12, 199); + labelDateTo.Name = "labelDateTo"; + labelDateTo.Size = new Size(62, 20); + labelDateTo.TabIndex = 8; + labelDateTo.Text = "Дата до"; + // + // buttonApply + // + buttonApply.Location = new Point(102, 282); + buttonApply.Name = "buttonApply"; + buttonApply.Size = new Size(132, 29); + buttonApply.TabIndex = 9; + buttonApply.Text = "Сформировать"; + buttonApply.UseVisualStyleBackColor = true; + buttonApply.Click += buttonApply_Click; + // + // FormOperationsReport + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(337, 323); + Controls.Add(buttonApply); + Controls.Add(labelDateTo); + Controls.Add(labelDateFrom); + Controls.Add(dateTimePickerEnd); + Controls.Add(dateTimePickerStart); + Controls.Add(comboBoxStudent); + Controls.Add(labelStudent); + Controls.Add(buttonFilePath); + Controls.Add(textBoxFilePath); + Controls.Add(labelFilePath); + Name = "FormOperationsReport"; + Text = "FormOperationsReport"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Label labelFilePath; + private TextBox textBoxFilePath; + private Button buttonFilePath; + private Label labelStudent; + private ComboBox comboBoxStudent; + private DateTimePicker dateTimePickerStart; + private DateTimePicker dateTimePickerEnd; + private Label labelDateFrom; + private Label labelDateTo; + private Button buttonApply; + } +} \ No newline at end of file diff --git a/StudentProgressRecord/Forms/FormOperationsReport.cs b/StudentProgressRecord/Forms/FormOperationsReport.cs new file mode 100644 index 0000000..5a67850 --- /dev/null +++ b/StudentProgressRecord/Forms/FormOperationsReport.cs @@ -0,0 +1,82 @@ +using StudentProgressRecord.Reports; +using StudentProgressRecord.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 StudentProgressRecord.Forms +{ + public partial class FormOperationsReport : Form + { + private readonly IUnityContainer _container; + public FormOperationsReport(IUnityContainer container, IStudentRepository + studentRepository) + { + InitializeComponent(); + _container = container ?? + throw new ArgumentNullException(nameof(container)); + comboBoxStudent.DataSource = studentRepository.ReadStudents(); + comboBoxStudent.DisplayMember = "Name"; + comboBoxStudent.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 buttonApply_Click(object sender, EventArgs e) + { + try + { + if (string.IsNullOrWhiteSpace(textBoxFilePath.Text)) + { + throw new Exception("Отсутствует имя файла для отчета"); + } + if (comboBoxStudent.SelectedIndex < 0) + { + throw new Exception("Не выбран корм"); + } + if (dateTimePickerEnd.Value <= + dateTimePickerStart.Value) + { + throw new Exception("Дата начала должна быть раньше даты окончания"); + } + if (_container.Resolve().CreateTable(textBoxFilePath.Text, + (long)comboBoxStudent.SelectedValue!, + dateTimePickerStart.Value, dateTimePickerEnd.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/StudentProgressRecord/Forms/FormOperationsReport.resx b/StudentProgressRecord/Forms/FormOperationsReport.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/StudentProgressRecord/Forms/FormOperationsReport.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/StudentProgressRecord/Forms/FormStatementDistributionReport.Designer.cs b/StudentProgressRecord/Forms/FormStatementDistributionReport.Designer.cs new file mode 100644 index 0000000..a43573f --- /dev/null +++ b/StudentProgressRecord/Forms/FormStatementDistributionReport.Designer.cs @@ -0,0 +1,130 @@ +namespace StudentProgressRecord.Forms +{ + partial class FormStatementDistributionReport + { + /// + /// 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(); + labelFile = new Label(); + dateTimePickerStart = new DateTimePicker(); + labelDateFrom = new Label(); + buttonApply = new Button(); + labelDateTo = new Label(); + dateTimePickerEnd = new DateTimePicker(); + SuspendLayout(); + // + // buttonFile + // + buttonFile.Location = new Point(133, 12); + buttonFile.Name = "buttonFile"; + buttonFile.Size = new Size(94, 29); + buttonFile.TabIndex = 0; + buttonFile.Text = "Выбрать"; + buttonFile.UseVisualStyleBackColor = true; + buttonFile.Click += buttonFile_Click; + // + // labelFile + // + labelFile.AutoSize = true; + labelFile.Location = new Point(12, 18); + labelFile.Name = "labelFile"; + labelFile.Size = new Size(45, 20); + labelFile.TabIndex = 1; + labelFile.Text = "Файл"; + // + // dateTimePickerStart + // + dateTimePickerStart.Location = new Point(78, 57); + dateTimePickerStart.Name = "dateTimePickerStart"; + dateTimePickerStart.Size = new Size(161, 27); + dateTimePickerStart.TabIndex = 2; + // + // labelDateFrom + // + labelDateFrom.AutoSize = true; + labelDateFrom.Location = new Point(12, 62); + labelDateFrom.Name = "labelDateFrom"; + labelDateFrom.Size = new Size(60, 20); + labelDateFrom.TabIndex = 3; + labelDateFrom.Text = "Дата от"; + // + // buttonApply + // + buttonApply.Location = new Point(12, 165); + buttonApply.Name = "buttonApply"; + buttonApply.Size = new Size(215, 29); + buttonApply.TabIndex = 4; + buttonApply.Text = "Сформировать"; + buttonApply.UseVisualStyleBackColor = true; + buttonApply.Click += buttonApply_Click; + // + // labelDateTo + // + labelDateTo.AutoSize = true; + labelDateTo.Location = new Point(12, 95); + labelDateTo.Name = "labelDateTo"; + labelDateTo.Size = new Size(62, 20); + labelDateTo.TabIndex = 6; + labelDateTo.Text = "Дата до"; + // + // dateTimePickerEnd + // + dateTimePickerEnd.Location = new Point(78, 90); + dateTimePickerEnd.Name = "dateTimePickerEnd"; + dateTimePickerEnd.Size = new Size(161, 27); + dateTimePickerEnd.TabIndex = 5; + // + // FormStatementDistributionReport + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(294, 206); + Controls.Add(labelDateTo); + Controls.Add(dateTimePickerEnd); + Controls.Add(buttonApply); + Controls.Add(labelDateFrom); + Controls.Add(dateTimePickerStart); + Controls.Add(labelFile); + Controls.Add(buttonFile); + Name = "FormStatementDistributionReport"; + StartPosition = FormStartPosition.CenterParent; + Text = "FormStatementDistributionReport"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Button buttonFile; + private Label labelFile; + private DateTimePicker dateTimePickerStart; + private Label labelDateFrom; + private Button buttonApply; + private Label labelDateTo; + private DateTimePicker dateTimePickerEnd; + } +} \ No newline at end of file diff --git a/StudentProgressRecord/Forms/FormStatementDistributionReport.cs b/StudentProgressRecord/Forms/FormStatementDistributionReport.cs new file mode 100644 index 0000000..1bb663a --- /dev/null +++ b/StudentProgressRecord/Forms/FormStatementDistributionReport.cs @@ -0,0 +1,74 @@ +using StudentProgressRecord.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 StudentProgressRecord.Forms +{ + public partial class FormStatementDistributionReport : Form + { + private string _fileName = string.Empty; + private readonly IUnityContainer _container; + public FormStatementDistributionReport(IUnityContainer container) + { + InitializeComponent(); + _container = container ?? + throw new ArgumentNullException(nameof(container)); + } + + private void buttonFile_Click(object sender, EventArgs e) + { + var sfd = new SaveFileDialog() + { + Filter = "Pdf Files | *.pdf" + }; + if (sfd.ShowDialog() == DialogResult.OK) + { + _fileName = sfd.FileName; + labelFile.Text = Path.GetFileName(_fileName); + } + } + + private void buttonApply_Click(object sender, EventArgs e) + { + try + { + if (string.IsNullOrWhiteSpace(_fileName)) + { + throw new Exception("Отсутствует имя файла для отчета"); + } + if (dateTimePickerEnd.Value <= + dateTimePickerStart.Value) + { + throw new Exception("Дата начала должна быть раньше даты окончания"); + } + if + (_container.Resolve().CreateChart(_fileName, dateTimePickerStart.Value, dateTimePickerEnd.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/StudentProgressRecord/Forms/FormStatementDistributionReport.resx b/StudentProgressRecord/Forms/FormStatementDistributionReport.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/StudentProgressRecord/Forms/FormStatementDistributionReport.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/StudentProgressRecord/Forms/FormViewEntities/FormViewStatement.cs b/StudentProgressRecord/Forms/FormViewEntities/FormViewStatement.cs index ec13869..89d8897 100644 --- a/StudentProgressRecord/Forms/FormViewEntities/FormViewStatement.cs +++ b/StudentProgressRecord/Forms/FormViewEntities/FormViewStatement.cs @@ -78,6 +78,7 @@ namespace StudentProgressRecord.Forms.FormViewEntities private void LoadList() { dataGridView.DataSource = _statementRepository.ReadStatements(); + dataGridView.Columns["Id"].Visible = false; } private bool TryGetIdFromSelectesRow(out int id) diff --git a/StudentProgressRecord/Forms/FormViewEntities/FormViewStudentTransition.cs b/StudentProgressRecord/Forms/FormViewEntities/FormViewStudentTransition.cs index 9f80bf7..7a8e250 100644 --- a/StudentProgressRecord/Forms/FormViewEntities/FormViewStudentTransition.cs +++ b/StudentProgressRecord/Forms/FormViewEntities/FormViewStudentTransition.cs @@ -57,18 +57,7 @@ namespace StudentProgressRecord.Forms.FormViewEntities private void LoadList() { dataGridView.DataSource = _studentTransitionRepository.ReadStudentTransitions(); - } - - private bool TryGetIdFromSelectesRow(out int id) - { - id = 0; - if (dataGridView.SelectedRows.Count < 1) - { - MessageBox.Show("Нет выбранной записи", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - return false; - } - id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - return true; + dataGridView.Columns["Id"].Visible = false; } } } diff --git a/StudentProgressRecord/Forms/FormViewEntities/FormViewStudents.cs b/StudentProgressRecord/Forms/FormViewEntities/FormViewStudents.cs index 9761ff6..3c10b25 100644 --- a/StudentProgressRecord/Forms/FormViewEntities/FormViewStudents.cs +++ b/StudentProgressRecord/Forms/FormViewEntities/FormViewStudents.cs @@ -98,6 +98,7 @@ namespace StudentProgressRecord.Forms.FormViewEntities private void LoadList() { dataGridView.DataSource = _studentRepository.ReadStudents(); + dataGridView.Columns["Id"].Visible = false; } private bool TryGetIdFromSelectesRow(out int id) diff --git a/StudentProgressRecord/Forms/FormViewEntities/FormViewSubjects.cs b/StudentProgressRecord/Forms/FormViewEntities/FormViewSubjects.cs index 914c8af..cb1657b 100644 --- a/StudentProgressRecord/Forms/FormViewEntities/FormViewSubjects.cs +++ b/StudentProgressRecord/Forms/FormViewEntities/FormViewSubjects.cs @@ -96,6 +96,7 @@ namespace StudentProgressRecord.Forms.FormViewEntities private void LoadList() { dataGridView.DataSource = _subjectRepository.ReadSubjects(); + dataGridView.Columns["Id"].Visible = false; } private bool TryGetIdFromSelectesRow(out int id) diff --git a/StudentProgressRecord/Forms/FormViewEntities/FormViewTeachers.cs b/StudentProgressRecord/Forms/FormViewEntities/FormViewTeachers.cs index a4c34d4..8c07e47 100644 --- a/StudentProgressRecord/Forms/FormViewEntities/FormViewTeachers.cs +++ b/StudentProgressRecord/Forms/FormViewEntities/FormViewTeachers.cs @@ -98,6 +98,7 @@ namespace StudentProgressRecord.Forms.FormViewEntities private void LoadList() { dataGridView.DataSource = _teacherRepository.ReadTeachers(); + dataGridView.Columns["Id"].Visible = false; } private bool TryGetIdFromSelectesRow(out int id) diff --git a/StudentProgressRecord/Forms/FormsEntity/FormStatement.cs b/StudentProgressRecord/Forms/FormsEntity/FormStatement.cs index 9ed164a..1154cff 100644 --- a/StudentProgressRecord/Forms/FormsEntity/FormStatement.cs +++ b/StudentProgressRecord/Forms/FormsEntity/FormStatement.cs @@ -83,7 +83,7 @@ namespace StudentProgressRecord.Forms marks.Add(Marks.CreateElement(0, Convert.ToInt32(row.Cells["columnStudent"].Value), Convert.ToInt32(row.Cells["columnMark"].Value))); } - return marks; + return marks.GroupBy(x => x.StudentId, x => x.Mark, (id, mark) => Marks.CreateElement(0, id, mark.Sum())).ToList(); } } } diff --git a/StudentProgressRecord/Forms/FormsEntity/FormUniversity.Designer.cs b/StudentProgressRecord/Forms/FormsEntity/FormUniversity.Designer.cs index c1115b9..49aa6ad 100644 --- a/StudentProgressRecord/Forms/FormsEntity/FormUniversity.Designer.cs +++ b/StudentProgressRecord/Forms/FormsEntity/FormUniversity.Designer.cs @@ -38,6 +38,9 @@ TransientToolStripMenuItem = new ToolStripMenuItem(); StatementToolStripMenuItem = new ToolStripMenuItem(); ReportToolStripMenuItem = new ToolStripMenuItem(); + ToolStripMenuItemDirectory = new ToolStripMenuItem(); + операцииToolStripMenuItem = new ToolStripMenuItem(); + анализToolStripMenuItem = new ToolStripMenuItem(); menuStrip1.SuspendLayout(); SuspendLayout(); // @@ -89,23 +92,48 @@ // TransientToolStripMenuItem // TransientToolStripMenuItem.Name = "TransientToolStripMenuItem"; - TransientToolStripMenuItem.Size = new Size(224, 26); + TransientToolStripMenuItem.Size = new Size(193, 26); TransientToolStripMenuItem.Text = "Перемещения"; TransientToolStripMenuItem.Click += TransientToolStripMenuItem_Click_1; // // StatementToolStripMenuItem // StatementToolStripMenuItem.Name = "StatementToolStripMenuItem"; - StatementToolStripMenuItem.Size = new Size(224, 26); + StatementToolStripMenuItem.Size = new Size(193, 26); StatementToolStripMenuItem.Text = "Ведомость"; StatementToolStripMenuItem.Click += StatementToolStripMenuItem_Click; // // ReportToolStripMenuItem // + ReportToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { ToolStripMenuItemDirectory, операцииToolStripMenuItem, анализToolStripMenuItem }); ReportToolStripMenuItem.Name = "ReportToolStripMenuItem"; ReportToolStripMenuItem.Size = new Size(73, 24); ReportToolStripMenuItem.Text = "Отчеты"; // + // ToolStripMenuItemDirectory + // + ToolStripMenuItemDirectory.Name = "ToolStripMenuItemDirectory"; + ToolStripMenuItemDirectory.ShortcutKeys = Keys.Control | Keys.W; + ToolStripMenuItemDirectory.Size = new Size(233, 26); + ToolStripMenuItemDirectory.Text = "Справочник"; + ToolStripMenuItemDirectory.Click += ToolStripMenuItemDirectory_Click; + // + // операцииToolStripMenuItem + // + операцииToolStripMenuItem.Name = "операцииToolStripMenuItem"; + операцииToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.E; + операцииToolStripMenuItem.Size = new Size(233, 26); + операцииToolStripMenuItem.Text = "Операции"; + операцииToolStripMenuItem.Click += операцииToolStripMenuItem_Click; + // + // анализToolStripMenuItem + // + анализToolStripMenuItem.Name = "анализToolStripMenuItem"; + анализToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.P; + анализToolStripMenuItem.Size = new Size(233, 26); + анализToolStripMenuItem.Text = "Анализ"; + анализToolStripMenuItem.Click += анализToolStripMenuItem_Click; + // // FormUniversity // AutoScaleDimensions = new SizeF(8F, 20F); @@ -133,5 +161,8 @@ private ToolStripMenuItem SubjectToolStripMenuItem; private ToolStripMenuItem TransientToolStripMenuItem; private ToolStripMenuItem StatementToolStripMenuItem; + private ToolStripMenuItem ToolStripMenuItemDirectory; + private ToolStripMenuItem операцииToolStripMenuItem; + private ToolStripMenuItem анализToolStripMenuItem; } } \ No newline at end of file diff --git a/StudentProgressRecord/Forms/FormsEntity/FormUniversity.cs b/StudentProgressRecord/Forms/FormsEntity/FormUniversity.cs index 5260e83..2285e00 100644 --- a/StudentProgressRecord/Forms/FormsEntity/FormUniversity.cs +++ b/StudentProgressRecord/Forms/FormsEntity/FormUniversity.cs @@ -1,4 +1,5 @@ -using StudentProgressRecord.Forms.FormViewEntities; +using StudentProgressRecord.Forms; +using StudentProgressRecord.Forms.FormViewEntities; using System; using System.Collections.Generic; using System.ComponentModel; @@ -87,6 +88,43 @@ namespace StudentProgressRecord } } - + private void ToolStripMenuItemDirectory_Click(object sender, EventArgs e) + { + try + { + _container.Resolve().ShowDialog(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка при загрузке", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void операцииToolStripMenuItem_Click(object sender, EventArgs e) + { + try + { + _container.Resolve().ShowDialog(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка при загрузке", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void анализToolStripMenuItem_Click(object sender, EventArgs e) + { + try + { + _container.Resolve().ShowDialog(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка при загрузке", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } } } diff --git a/StudentProgressRecord/Reports/ChartReport.cs b/StudentProgressRecord/Reports/ChartReport.cs new file mode 100644 index 0000000..1ea7cca --- /dev/null +++ b/StudentProgressRecord/Reports/ChartReport.cs @@ -0,0 +1,54 @@ +using Microsoft.Extensions.Logging; +using StudentProgressRecord.Repositories; +using StudentProgressRecord.RepositoryImp; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace StudentProgressRecord.Reports +{ + internal class ChartReport + { + private readonly IStatementRepository _statementRepository; + private readonly ILogger _logger; + public ChartReport(IStatementRepository statementRepository, + ILogger logger) + { + _statementRepository = statementRepository ?? throw new ArgumentNullException(nameof(statementRepository)); + _logger = logger ?? + throw new ArgumentNullException(nameof(logger)); + } + public bool CreateChart(string filePath, DateTime dateTimeStart, DateTime dateTimeEnd) + { + try + { + new PdfBuilder(filePath) + .AddHeader("Оценки студентов") + .AddPieChart("Оценки", GetData(dateTimeStart, dateTimeEnd)) + .Build(); + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при формировании документа"); + return false; + } + } + private List<(string Caption, double Value)> GetData(DateTime dateTimeStart, DateTime dateTimeEnd) + { + + return _statementRepository + .ReadStatements() + .Where(x => x.Date >= dateTimeStart && x.Date <= dateTimeEnd) + .SelectMany(x => x.Marks) + .GroupBy(x => x.Mark, (key, group) => new { + Id = key, + Count = group.Count() + }) + .Select(x => (x.Id.ToString(), (double)x.Count)) + .ToList(); + } + } +} diff --git a/StudentProgressRecord/Reports/DockReport.cs b/StudentProgressRecord/Reports/DockReport.cs new file mode 100644 index 0000000..d06ea47 --- /dev/null +++ b/StudentProgressRecord/Reports/DockReport.cs @@ -0,0 +1,90 @@ +using Microsoft.Extensions.Logging; +using StudentProgressRecord.Repositories; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace StudentProgressRecord.Reports +{ + public class DockReport + { + private readonly ISubjectRepository _subjectRepository; + + private readonly IStudentRepository _studentRepository; + + private readonly ITeacherRepository _teacherRepository; + + private readonly ILogger _logger; + + public DockReport(ISubjectRepository subjectRepository, IStudentRepository studentRepository, ITeacherRepository teacherRepository, ILogger logger) + { + _subjectRepository = subjectRepository ?? throw new ArgumentNullException(nameof(subjectRepository)); + _studentRepository = studentRepository ?? throw new ArgumentNullException(nameof(studentRepository)); + _teacherRepository = teacherRepository ?? throw new ArgumentNullException(nameof(teacherRepository)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + public bool CreateDock(string filepath, bool includeSubject, bool includeStudent, bool includeTeacher) + { + try + { + var builder = new WordBuilder(filepath) + .AddHeader("Документ со справочниками"); + + if (includeStudent) + { + builder.AddParagraph("Студенты") + .AddTable([2400, 1200, 1200], GetStudents()); + } + if (includeTeacher) + { + builder.AddParagraph("Учителя") + .AddTable([4800], GetTeachers()); + } + if (includeSubject) + { + builder.AddParagraph("Предметы") + .AddTable([2400, 1200], GetSubjects()); + } + builder.Build(); + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при формировании документа"); + return false; + } + } + + + private List GetStudents() + { + return [ + ["Имя судента", "Семейное положение", "Общажитие"], + .. _studentRepository.ReadStudents() + .Select(x => new string[] {x.Name, x.FamilyPos.ToString(), x.Domitory.ToString() }), + ]; + } + private List GetTeachers() + { + return [ + ["Имя преподавателя"], + .. _teacherRepository.ReadTeachers() + .Select(x => new string[] {x.Name}), + ]; + } + + private List GetSubjects() + { + return [ + ["Название предмета", "Направления"], + .. _subjectRepository.ReadSubjects() + .Select(x => new string[] {x.Name, x.direction.ToString()}), + ]; + } + + + } +} diff --git a/StudentProgressRecord/Reports/ExcelBuilder.cs b/StudentProgressRecord/Reports/ExcelBuilder.cs new file mode 100644 index 0000000..bdca0ca --- /dev/null +++ b/StudentProgressRecord/Reports/ExcelBuilder.cs @@ -0,0 +1,314 @@ +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Spreadsheet; +using DocumentFormat.OpenXml; + +namespace StudentProgressRecord.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.BoiledTextWithoutBorder); + for (int i = startIndex + 1; i < startIndex + count; ++i) + { + CreateCell(i, _rowIndex, "", + StyleIndex.BoiledTextWithoutBorder); + } + _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.BoiledTextWithoutBorder); + 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.BoiledTextWithBorder); + } + _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.BoiledTextWithBorder); + } + _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 }, + Bold = new Bold(), + 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() + }); + 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 = 1, + BorderId = 1, + 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.Left, + Vertical = VerticalAlignmentValues.Center, + WrapText = true + } + }); + cellFormats.Append(new CellFormat + { + NumberFormatId = 0, + FormatId = 0, + FontId = 1, + BorderId = 0, + FillId = 0, + Alignment = new Alignment() + { + Horizontal = HorizontalAlignmentValues.Left, + Vertical = VerticalAlignmentValues.Center, + WrapText = true + } + }); + workbookStylesPart.Stylesheet.Append(cellFormats); + } + private enum StyleIndex + { + SimpleTextWithoutBorder = 0, + BoiledTextWithBorder = 1, + SimpleTextWithBorder = 2, + BoiledTextWithoutBorder = 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/StudentProgressRecord/Reports/PdfBuilder.cs b/StudentProgressRecord/Reports/PdfBuilder.cs new file mode 100644 index 0000000..18ddad4 --- /dev/null +++ b/StudentProgressRecord/Reports/PdfBuilder.cs @@ -0,0 +1,78 @@ +using MigraDoc.DocumentObjectModel; +using MigraDoc.DocumentObjectModel.Shapes.Charts; +using MigraDoc.Rendering; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace StudentProgressRecord.Reports +{ + public 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() + { + var renderer = new PdfDocumentRenderer() + { + Document = _document + }; + renderer.RenderDocument(); + renderer.PdfDocument.Save(_filePath); + } + private void DefineStyles() + { + var style = _document.Styles.AddStyle("NormalBold", "Normal"); + style.Font.Bold = true; + style.Font.Size = 16; + style.ParagraphFormat.Alignment = ParagraphAlignment.Center; + } + } +} diff --git a/StudentProgressRecord/Reports/TableReport.cs b/StudentProgressRecord/Reports/TableReport.cs new file mode 100644 index 0000000..895bbc3 --- /dev/null +++ b/StudentProgressRecord/Reports/TableReport.cs @@ -0,0 +1,76 @@ +using Microsoft.Extensions.Logging; +using StudentProgressRecord.Entity.Enums; +using StudentProgressRecord.IRepositories; +using StudentProgressRecord.Repositories; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace StudentProgressRecord.Reports +{ + internal class TableReport + { + private readonly IStudentTransitionRepository _studentTransitionRepository; + private readonly IStatementRepository _statementRepository; + private readonly ILogger _logger; + internal static readonly string[] item = ["Дата", "Оценка", "Операция"]; + public TableReport(IStudentTransitionRepository studentTransitionRepository, IStatementRepository statementRepository, ILogger logger) + { + _statementRepository = statementRepository?? throw new ArgumentNullException(nameof(statementRepository)); + _studentTransitionRepository = studentTransitionRepository ?? throw new ArgumentNullException(nameof(studentTransitionRepository)); + _logger = logger ?? + throw new ArgumentNullException(nameof(logger)); + } + public bool CreateTable(string filePath, long studentId, DateTime startDate, DateTime endDate) + { + try + { + new ExcelBuilder(filePath) + .AddHeader("Сводка по стунденту", 0, 3) + .AddParagraph("за период", 0) + .AddTable([15, 15, 15], GetData(studentId, startDate, + endDate)) + .Build(); + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при формировании документа"); + return false; + } + } + private List GetData(long studentId, DateTime startDate, DateTime + endDate) + { + var data = _statementRepository + .ReadStatements() + .Where(x => x.Date >= startDate && x.Date <= endDate && + x.Marks.Any(y => y.StudentId == studentId)) + .Select(x => new { + Date = x.Date, + Mark = x.Marks.FirstOrDefault(y => y.StudentId == studentId)?.Mark, + Operation = (Operations?)null + }) + .Union( + _studentTransitionRepository + .ReadStudentTransitions() + .Where(x => x.Date >= startDate && x.Date <= endDate && x.StudentId == studentId) + .Select(x => new { + Date = x.Date, + Mark = (int?)null, + Operation = (Operations?)x.Operation + })) + .OrderBy(x => x.Date).ToList(); + return + new List() { item } + .Union( + data + .Select(x => new string[] { + x.Date.ToString(), x.Mark?.ToString() ?? string.Empty, x.Operation.ToString() ?? string.Empty})) + .Union( + [["Всего",data.Where((x) => x.Mark.HasValue).Average(x => x.Mark).ToString(), data.Count(x => x.Operation.HasValue).ToString()]]).ToList(); + } + } +} diff --git a/StudentProgressRecord/Reports/WordBuilder.cs b/StudentProgressRecord/Reports/WordBuilder.cs new file mode 100644 index 0000000..7a58692 --- /dev/null +++ b/StudentProgressRecord/Reports/WordBuilder.cs @@ -0,0 +1,130 @@ +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Wordprocessing; +using DocumentFormat.OpenXml; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace StudentProgressRecord.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()); + // TODO прописать настройки под жирный текст + 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/StudentProgressRecord/RepositoryImp/QueryBuilder.cs b/StudentProgressRecord/RepositoryImp/QueryBuilder.cs new file mode 100644 index 0000000..3b55103 --- /dev/null +++ b/StudentProgressRecord/RepositoryImp/QueryBuilder.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace StudentProgressRecord.RepositoryImp +{ + public class QueryBuilder + { + private readonly StringBuilder _builder; + public QueryBuilder() + { + _builder = new(); + } + public QueryBuilder AddCondition(string condition) + { + if (_builder.Length > 0) + { + _builder.Append(" AND "); + } + _builder.Append(condition); + return this; + } + public string Build() + { + if (_builder.Length == 0) + { + return string.Empty; + } + return $"WHERE {_builder}"; + } + } +} diff --git a/StudentProgressRecord/RepositoryImp/StatementRepository.cs b/StudentProgressRecord/RepositoryImp/StatementRepository.cs index 422c1f6..146b6af 100644 --- a/StudentProgressRecord/RepositoryImp/StatementRepository.cs +++ b/StudentProgressRecord/RepositoryImp/StatementRepository.cs @@ -88,13 +88,22 @@ namespace StudentProgressRecord.RepositoryImp _logger.LogInformation("Получение всех объектов"); try { - using var connection = new NpgsqlConnection(_connectionString.GetConnectionString()); - var querySelect = "SELECT * FROM Statement"; - var objs = connection.Query(querySelect); + var querySelect = + @"SELECT + st.*, s.Name as SubjectName, t.Name as TeacherName, m.Mark, Student.Name as StudentName FROM Statement st + JOIN Subject s ON s.id = st.SubjectId + JOIN Teacher t ON t.id = st.TeacherId + JOIN Marks m ON m.statementId = st.id + LEFT JOIN Student on Student.id = m.studentId + "; + var objs = connection.Query(querySelect); _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(objs)); - return objs; + + return objs.GroupBy(x => x.Id, y => y, + (key, value) => + Statement.CreateOperation(value.First(), value.Select(z => Marks.CreateElement(0, z.StudentId, z.Mark, z.StudentName)))).ToList(); } catch (Exception ex) { diff --git a/StudentProgressRecord/RepositoryImp/StudentTransitionRepository.cs b/StudentProgressRecord/RepositoryImp/StudentTransitionRepository.cs index d54c6f6..4447514 100644 --- a/StudentProgressRecord/RepositoryImp/StudentTransitionRepository.cs +++ b/StudentProgressRecord/RepositoryImp/StudentTransitionRepository.cs @@ -85,7 +85,8 @@ namespace StudentProgressRecord.RepositoryImp try { using var connection = new NpgsqlConnection(_connectionString.GetConnectionString()); - var querySelect = "SELECT * FROM StudentTransition"; + var querySelect = @"SELECT st.*, s.Name as StudentName FROM StudentTransition st + JOIN Student s ON s.id = st.StudentId"; var objs = connection.Query(querySelect); _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(objs)); diff --git a/StudentProgressRecord/StudentProgressRecord.csproj b/StudentProgressRecord/StudentProgressRecord.csproj index 126a7d2..3fec795 100644 --- a/StudentProgressRecord/StudentProgressRecord.csproj +++ b/StudentProgressRecord/StudentProgressRecord.csproj @@ -20,10 +20,12 @@ + + @@ -49,6 +51,10 @@ + + + + diff --git a/StudentProgressRecord/V1__dll.sql b/StudentProgressRecord/V1__dll.sql new file mode 100644 index 0000000..999c303 --- /dev/null +++ b/StudentProgressRecord/V1__dll.sql @@ -0,0 +1,38 @@ +CREATE TABLE subject( + id BIGSERIAL PRIMARY KEY, + name VARCHAR(255) NOT NULL, + direction VARCHAR(255) NOT NULL +); + +CREATE TABLE teacher( + id BIGSERIAL PRIMARY KEY, + name VARCHAR(255) NOT NULL +); + + +CREATE TABLE student( + id BIGSERIAL PRIMARY KEY, + name VARCHAR(255) NOT NULL, + familyPos bool NOT NULL, + domitory bool NOT NULL +); + +CREATE TABLE studentTransition( + id BIGSERIAL PRIMARY KEY, + studentid BIGINT REFERENCES student (id) NOT NULL, + operation VARCHAR(255) NOT NULL, + date timestamp +); + +CREATE TABLE statement( + id BIGSERIAL PRIMARY KEY, + subjectid BIGINT REFERENCES subject (id) NOT NULL, + teacherid BIGINT REFERENCES teacher (id) NOT NULL, + date timestamp +); + +CREATE TABLE marks( + statementid BIGINT REFERENCES statement (id) NOT NULL, + studentid BIGINT REFERENCES student (id) NOT NULL, + mark integer NOT NULL +); diff --git a/StudentProgressRecord/appsetting.json b/StudentProgressRecord/appsetting.json index a13deda..640f7a0 100644 --- a/StudentProgressRecord/appsetting.json +++ b/StudentProgressRecord/appsetting.json @@ -6,7 +6,7 @@ { "Name": "File", "Args": { - "path": "Logs/university_log.txt", + "path": "Logs\\university_log.txt", "rollingInterval": "Day" } }