package com.labelsys.backend.service; import com.labelsys.backend.context.LoginUser; import com.labelsys.backend.enums.UserRole; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; import org.springframework.stereotype.Service; @Service public class DataPermissionService { public boolean canAccessCreator(LoginUser currentUser, Long creatorId, UserRole creatorRole) { return switch (currentUser.role()) { case EMPLOYEE -> currentUser.userId().equals(creatorId); case MANAGER -> creatorRole == UserRole.EMPLOYEE || creatorRole == UserRole.MANAGER; case ENGINEER -> true; }; } /** * Generic in-memory role-based data filter for records already loaded in memory. */ public List filterByRole( LoginUser currentUser, List allRecords, Function roleExtractor, Function ownerIdExtractor) { if (allRecords == null || allRecords.isEmpty()) { return List.of(); } UserRole currentRole = currentUser.role(); Long currentUserId = currentUser.userId(); return allRecords.stream() .filter(record -> { UserRole recordRole = roleExtractor.apply(record); Long recordOwnerId = ownerIdExtractor.apply(record); return switch (currentRole) { case EMPLOYEE -> currentUserId.equals(recordOwnerId); case MANAGER -> recordRole == UserRole.EMPLOYEE || recordRole == UserRole.MANAGER; case ENGINEER -> true; }; }) .collect(Collectors.toList()); } /** * Returns the creator roles visible to the current user for SQL-side filtering. */ public List getAllowedRoles(LoginUser currentUser) { return switch (currentUser.role()) { case EMPLOYEE -> List.of(); case MANAGER -> List.of("EMPLOYEE", "MANAGER"); case ENGINEER -> List.of("EMPLOYEE", "MANAGER", "ENGINEER"); }; } /** * Whether SQL queries should additionally restrict by creator/user id. */ public boolean shouldFilterByUserId(LoginUser currentUser) { return currentUser.role() == UserRole.EMPLOYEE; } }