using ClosedXML.Excel; using Demo.Data.RemoteData.RemoteDataBase.DAO; using Demo.Data.Repository; using Demo.domain.Models; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Demo.Domain.UseCase { public class UseCaseGeneratePresence { public readonly IUserRepository _userRepository; public readonly IPresenceRepository _presenceRepository; private readonly IGroupRepository _groupRepository; public UseCaseGeneratePresence(IUserRepository userRepository, IPresenceRepository presenceRepository, IGroupRepository groupRepository) { _userRepository = userRepository; _presenceRepository = presenceRepository; _groupRepository = groupRepository; } public Dictionary> GetAllAttendanceByGroups() { var attendanceByGroup = new Dictionary>(); var allGroups = _groupRepository.GetAllGroups(); foreach (var group in allGroups) { var groupAttendance = _presenceRepository.GetAttendanceByGroup(group.Id); var attendanceRecords = new List(); foreach (var record in groupAttendance) { var names = _userRepository.GetUserNames().Where(u => u.UserGuid == record.UserGuid); foreach (var name in names) { attendanceRecords.Add(new AttendanceRecord { UserName = name.FIO, UserGuid = name.UserGuid, Date = record.Date, IsAttedance = record.IsAttedance, LessonNumber = record.LessonNumber, GroupName = group.Name }); } } attendanceByGroup.Add(group.Name, attendanceRecords); } return attendanceByGroup; } public void ExportAttendanceToExcel() { var attendanceByGroup = GetAllAttendanceByGroups(); string projectDirectory = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.FullName; string reportsFolderPath = Path.Combine(projectDirectory, "Reports"); string filePath = Path.Combine(reportsFolderPath, "AttendanceReport.xlsx"); // Создаем папку, если она не существует if (!Directory.Exists(reportsFolderPath)) { Directory.CreateDirectory(reportsFolderPath); } using (var workbook = new XLWorkbook()) { foreach (var group in attendanceByGroup) { var worksheet = workbook.Worksheets.Add($"{group.Key}"); worksheet.Cell(1, 1).Value = "ФИО"; worksheet.Cell(1, 2).Value = "Группа"; worksheet.Cell(1, 3).Value = "Дата"; worksheet.Cell(1, 4).Value = "Занятие"; worksheet.Cell(1, 5).Value = "Статус"; int row = 2; int lesNum = 1; foreach (var record in group.Value.OrderBy(r => r.Date).ThenBy(r => r.LessonNumber).ThenBy(r => r.UserGuid)) { if (lesNum != record.LessonNumber) { row++; } worksheet.Cell(row, 1).Value = record.UserName; worksheet.Cell(row, 2).Value = record.GroupName; worksheet.Cell(row, 3).Value = record.Date.ToString("dd.MM.yyyy"); worksheet.Cell(row, 4).Value = record.LessonNumber; worksheet.Cell(row, 5).Value = record.IsAttedance ? "Присутствует" : "Отсутствует"; row++; lesNum = record.LessonNumber; } worksheet.Columns().AdjustToContents(); } workbook.SaveAs(filePath); } } public List GetPresenceByDateAndGroup(DateTime date, int groupId) { return _presenceRepository.GetPresenceByDateAndGroup(date, groupId); } public void GeneratePresenceDaily(int firstLesson, int lastLesson, int groupId) { try { var users = _userRepository.GetAllUsers().Where(u => u.GroupId == groupId).ToList(); // Находим последнюю дату посещаемости для данной группы DateOnly startDate = _presenceRepository.GetLastDateByGroupId(groupId)?.AddDays(1) ?? DateOnly.FromDateTime(DateTime.Today); List presences = new List(); for (int lessonNumber = firstLesson; lessonNumber <= lastLesson; lessonNumber++) { foreach (var user in users) { var presence = new PresenceDao { UserGuid = user.UserGuid, GroupId = user.GroupId, Date = startDate, LessonNumber = lessonNumber, IsAttedance = true }; try { _presenceRepository.SavePresence(new List { presence }); Console.WriteLine($"Посещаемость добавлена для UserId = {user.UserGuid}, LessonNumber = {lessonNumber} на дату {startDate}"); } catch (Exception ex) { Console.WriteLine($"Ошибка при добавлении посещаемости для UserId = {user.UserGuid}: {ex.Message}"); if (ex.InnerException != null) { Console.WriteLine($"Inner exception: {ex.InnerException.Message}"); } } } } } catch (Exception ex) { Console.WriteLine($"Ошибка при генерации посещаемости: {ex.Message}"); if (ex.InnerException != null) { Console.WriteLine($"Inner exception: {ex.InnerException.Message}"); } } } public void GenerateWeeklyPresence(int firstLesson, int lastLesson, int groupId, DateTime startTime) { for (int i = 0; i < 7; i++) { DateTime currentTime = startTime.AddDays(i); GeneratePresenceDaily(firstLesson, lastLesson, groupId); } } // Отметить пользователя как отсутствующего на диапазоне занятий public void MarkUserAbsentForLessons(Guid UserGuid, int groupId, int firstLesson, int lastLesson, DateTime date) { List presences = _presenceRepository.GetPresenceForAbsent(date, groupId); // Обновляем состояние присутствия для указанных занятий foreach (var presence in presences.Where(p => p.UserGuid == UserGuid && p.LessonNumber >= firstLesson && p.LessonNumber <= lastLesson)) { presence.IsAttedance = false; // Устанавливаем отсутствие Console.WriteLine($"PresenceId: {presence.PresenceId}, UserId: {presence.UserGuid}, Lesson Num: {presence.LessonNumber}, Att: {presence.IsAttedance}"); } // Сохраняем изменения в репозитории _presenceRepository.UpdateAtt(UserGuid, groupId, firstLesson, lastLesson, DateOnly.FromDateTime(date), false); } public List GetAllPresenceByGroup(int groupId) { return _presenceRepository.GetPresenceByGroup(groupId); } public void GetGeneralPresence(int groupId) { _presenceRepository.GetGeneralPresenceForGroup(groupId); } } }