presence_new/ui/PresenceConsole.cs
2024-11-16 15:02:17 +03:00

166 lines
7.7 KiB
C#
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using presence.domain.UseCase;
using ClosedXML.Excel;
using presence.data.Repository;
namespace presence.ui
{
public class PresenceConsoleUI
{
private readonly PresenceUseCase _presenceUseCase;
private readonly IPresenceRepository _presenceRepository;
public PresenceConsoleUI(PresenceUseCase presenceUseCase, IPresenceRepository presenceRepository)
{
_presenceUseCase = presenceUseCase;
_presenceRepository = presenceRepository;
}
public void GetPresenceByGroup(int groupId)
{
StringBuilder presenceOutput = new StringBuilder();
var presence = _presenceUseCase.GetPresenceByGroup(groupId);
foreach (var p in presence)
{
presenceOutput.AppendLine($"{p.User.Guid}\t{p.User.FIO}\t{p.ClassNumber}\t{p.Date}\t{p.IsAttendence}");
}
Console.WriteLine(presenceOutput);
}
public void GetPresenceByGroupAndDate(int groupId, DateOnly date)
{
StringBuilder presenceOutput = new StringBuilder();
var presence = _presenceUseCase.GetPresenceByGroupAndDate(groupId, date);
foreach (var p in presence)
{
presenceOutput.AppendLine($"{p.User.Guid}\t{p.User.FIO}\t{p.ClassNumber}\t{p.Date}\t{p.IsAttendence}");
}
Console.WriteLine(presenceOutput);
}
public void UncheckAttendence(int firstClass, int lastClass, DateOnly date, int userId)
{
string output = _presenceUseCase.UncheckAttendence(firstClass, lastClass, date, userId) ?
"Посещаемость обновлена" : "Посещаемость не обновлена";
Console.WriteLine(output);
}
public void AddPresence(int firstClass, int lastClass, int groupId, DateOnly date)
{
StringBuilder presenceOutput = new StringBuilder();
_presenceUseCase.AddPresence(firstClass, lastClass, groupId, date);
presenceOutput.AppendLine("Посещаемость добавлена");
Console.WriteLine(presenceOutput);
}
public void GetPresenceStatsByGroup(int groupId)
{
var stats = _presenceUseCase.GetPresenceStatsByGroup(groupId);
StringBuilder output = new StringBuilder();
output.AppendLine($"Информация о группе {groupId}:");
output.AppendLine($"Количество студентов: {stats["Количество студентов"]}");
output.AppendLine($"Количество занятий: {stats["Количество занятий"]}");
output.AppendLine($"Общий процент посещаемости: {stats["Процент посещаемости"]}%");
output.AppendLine("\nСтатистика по студентам:");
var presence = _presenceUseCase.GetPresenceByGroup(groupId);
var students = presence.GroupBy(p => p.User)
.Select(g => new {
Student = g.Key,
Total = stats["Количество занятий"],
Attended = g.Count(p => p.IsAttendence),
Missed = stats["Количество занятий"] - g.Count(p => p.IsAttendence),
Percentage = (g.Count(p => p.IsAttendence) * 100) / stats["Количество занятий"]
});
foreach(var student in students) {
output.AppendLine($"\nСтудент: {student.Student.FIO}");
output.AppendLine($"Посещено занятий: {student.Attended}");
output.AppendLine($"Пропущено занятий: {student.Missed}");
output.AppendLine($"Процент посещаемости: {student.Percentage}%");
}
Console.WriteLine(output.ToString());
}
public void GenerateWeeklyPresence(int firstClass, int lastClass, int groupId, DateOnly startDate)
{
_presenceUseCase.GenerateWeeklyPresence(firstClass, lastClass, groupId, startDate);
Console.WriteLine("Посещаемость на неделю сгенерирована");
}
public void ExportPresenceToExcel(int groupId, string filePath)
{
var presence = _presenceUseCase.GetPresenceByGroup(groupId);
var stats = _presenceUseCase.GetPresenceStatsByGroup(groupId);
using (var workbook = new XLWorkbook())
{
var worksheet = workbook.Worksheets.Add("Посещаемость");
// Заголовок листа
worksheet.Cell(1, 1).Value = $"Группа {groupId}";
worksheet.Range(1, 1, 1, 3).Merge();
worksheet.Cell(1, 1).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
// Заголовки столбцов
worksheet.Cell(3, 1).Value = "№";
worksheet.Cell(3, 2).Value = "ФИО";
// Получаем все уникальные даты
var dates = presence.Select(p => p.Date).Distinct().OrderBy(d => d).ToList();
int col = 3;
foreach (var date in dates)
{
worksheet.Cell(3, col).Value = date.ToString("dd.MM.yyyy");
col++;
}
// Группируем данные по студентам
var studentGroups = presence.GroupBy(p => p.User);
int row = 4;
int studentNumber = 1;
foreach (var studentGroup in studentGroups)
{
// Номер и ФИО студента
worksheet.Cell(row, 1).Value = studentNumber++;
worksheet.Cell(row, 2).Value = studentGroup.Key.FIO;
// Заполняем посещаемость по датам
col = 3;
foreach (var date in dates)
{
var presenceOnDate = studentGroup.FirstOrDefault(p => p.Date == date);
worksheet.Cell(row, col).Value = presenceOnDate?.IsAttendence == true ? "+" : "н";
worksheet.Cell(row, col).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
col++;
}
row++;
}
// Форматирование
var tableRange = worksheet.Range(3, 1, row - 1, dates.Count + 2);
tableRange.Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
tableRange.Style.Border.InsideBorder = XLBorderStyleValues.Thin;
worksheet.Columns().AdjustToContents();
try
{
workbook.SaveAs(filePath);
Console.WriteLine($"Данные успешно экспортированы в файл: {filePath}");
}
catch (Exception ex)
{
Console.WriteLine($"Ошибка при сохранении файла: {ex.Message}");
}
}
}
}
}