diff --git a/src/main/java/com/klaroworks/runtime/service/RoleMatrixService.java b/src/main/java/com/klaroworks/runtime/service/RoleMatrixService.java new file mode 100644 index 0000000..e473322 --- /dev/null +++ b/src/main/java/com/klaroworks/runtime/service/RoleMatrixService.java @@ -0,0 +1,53 @@ +package com.klaroworks.runtime.service; + +import com.klaroworks.runtime.dto.RoleCreateRequest; +import com.klaroworks.runtime.dto.RoleResponse; +import com.klaroworks.runtime.entity.Role; +import com.klaroworks.runtime.exception.DuplicateResourceException; +import com.klaroworks.runtime.exception.RoleNotFoundException; +import com.klaroworks.runtime.repository.RoleRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import java.util.List; + +@Service +@RequiredArgsConstructor +@Transactional(readOnly = true) +public class RoleMatrixService { + + private final RoleRepository roleRepository; + + @Transactional + public RoleResponse createRole(RoleCreateRequest request) { + if (roleRepository.existsByName(request.getName())) { + throw new DuplicateResourceException("Role", request.getName()); + } + Role role = Role.create(request.getName(), request.getDescription()); + return RoleResponse.from(roleRepository.save(role)); + } + + public RoleResponse getRoleById(Long id) { + return roleRepository.findById(id) + .map(RoleResponse::from) + .orElseThrow(() -> new RoleNotFoundException(id)); + } + + public List getAllRoles() { + return roleRepository.findAll().stream().map(RoleResponse::from).toList(); + } + + @Transactional + public RoleResponse updateRole(Long id, RoleCreateRequest request) { + Role role = roleRepository.findById(id) + .orElseThrow(() -> new RoleNotFoundException(id)); + role.update(request.getName(), request.getDescription()); + return RoleResponse.from(role); + } + + @Transactional + public void deleteRole(Long id) { + if (!roleRepository.existsById(id)) throw new RoleNotFoundException(id); + roleRepository.deleteById(id); + } +}