FinalPresenceLexa/domain/UseCase/UserUseCase.cs
2025-04-28 11:51:01 +03:00

132 lines
4.1 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using data.RemoteData.RemoteDataBase.DAO;
using data.Repository;
namespace domain.UseCase
{
public class UserUseCase
{
private readonly IUserRepository _userRepository;
private readonly IGroupRepository _groupRepository;
private readonly IPresenceRepository _presenceRepository;
public UserUseCase(
IUserRepository userRepository,
IGroupRepository groupRepository,
IPresenceRepository presenceRepository)
{
_userRepository = userRepository;
_groupRepository = groupRepository;
_presenceRepository = presenceRepository;
}
private void ValidateFIO(string fio)
{
if (string.IsNullOrWhiteSpace(fio))
throw new ArgumentException("ФИО не может быть пустым");
}
private async Task ValidateGroupExists(int groupId)
{
var group = _groupRepository.GetGroupById(groupId);
if (group == null)
throw new ArgumentException("Группа не найдена");
}
public async Task<List<UserDAO>> GetAllUsersAsync()
{
var users = await _userRepository.GetAllUsersAsync();
var groups = _groupRepository.GetAllGroups();
return users.Select(user => new UserDAO
{
UserId = user.UserId,
FIO = user.FIO,
GroupId = user.GroupId,
Group = groups.FirstOrDefault(g => g.Id == user.GroupId)
}).ToList();
}
public bool RemoveUser(int userId)
{
try
{
var user = _userRepository.GetUserById(userId);
if (user == null)
return false;
// Проверяем связанные записи посещаемости
var userPresence = _presenceRepository.GetPresenceByUserId(userId);
if (userPresence.Any())
{
_presenceRepository.DeletePresenceByUser(userId);
}
_userRepository.RemoveUserByIdAsync(userId);
return true;
}
catch (Exception ex)
{
throw new ArgumentException("Ошибка при удалении пользователя", ex);
}
}
public async Task<UserDAO> AddUserAsync(string fio, int groupId)
{
ValidateFIO(fio);
await ValidateGroupExists(groupId);
var newUser = new UserDAO
{
FIO = fio,
GroupId = groupId
};
try
{
var createdUser = await _userRepository.AddUserAsync(newUser);
return createdUser;
}
catch (Exception ex)
{
throw new ArgumentException("Ошибка при создании пользователя", ex);
}
}
public UserDAO UpdateUser(int userId, string fio, int groupId)
{
ValidateFIO(fio);
ValidateGroupExists(groupId);
var existingUser = _userRepository.GetUserById(userId);
if (existingUser == null)
throw new ArgumentException("Пользователь не найден");
existingUser.FIO = fio;
existingUser.GroupId = groupId;
try
{
var updatedUser = _userRepository.UpdateUser(existingUser);
return updatedUser;
}
catch (Exception ex)
{
throw new ArgumentException("Ошибка при обновлении пользователя", ex);
}
}
public UserDAO? FindUserById(int userId)
{
return _userRepository.GetUserById(userId);
}
public List<UserDAO> GetAllUsers()
{
return _userRepository.GetAllUsers();
}
}
}