using LCU.API.Internal.Operations.IncentiveApi.Exceptions; using LCU.API.Internal.Operations.IncentiveApi.Models.DataTransfer; using LCU.API.Internal.Operations.IncentiveApiLib.Services; using LCU.API.Internal.Operations.IncentiveApiLib.Repositories; using LCU.Library.Internal.IncentiveApiModels.Entities; using LCU.Library.Internal.IncentiveApiModels.Enums; namespace LCU.API.Internal.Operations.IncentiveApi.Services; public class UserAssignmentService : IUserAssignmentService { private readonly IUserAssignmentRepository _userAssignmentRepository; private readonly IUserService _userService; private readonly IUnitOfWork _unitOfWork; public UserAssignmentService(IUserAssignmentRepository userAssignmentRepository, IUserService userService, IUnitOfWork unitOfWork) { _userAssignmentRepository = userAssignmentRepository; _userService = userService; _unitOfWork = unitOfWork; } public async Task> GetAllUserAssignmentsAsync() { return await _userAssignmentRepository.GetAllUserAssignmentsAsync(); } public async Task GetUserAssignment(AssignmentType assignmentType, string key) { return await _userAssignmentRepository.FindExistingAssignmentAsync(assignmentType, key); } public async Task SetRegionalManager(UserAssignmentRequest assignmentRequest) { var employee = await _userService.GetUserByEmployeeIdAsync(assignmentRequest.EmployeeId); if (employee == null) { throw new NotFoundException("Employee Not Found"); } if( !employee.HasRoleAnywhere(Role.RegionalManager)) { throw new BadUserAssignmentException("Employee must have the Regional Manager role"); } var assignment = await GetUserAssignment(assignmentRequest.Type.Value, assignmentRequest.Key); if (assignment != null) { assignment.AppUser = employee; } else { assignment = new UserAssignment { Id = 0, Type = assignmentRequest.Type.Value, Key = assignmentRequest.Key, AppUser = employee }; employee.Assignments.Add(assignment); } await _unitOfWork.CompleteAsync(); return assignment; } }