filter users by role

This commit is contained in:
2026-03-14 21:38:42 -06:00
parent 4b4f4b087e
commit 5b3a91ada0
3 changed files with 18 additions and 3 deletions

View File

@@ -3,6 +3,7 @@ package com.petshop.backend.controller;
import com.petshop.backend.dto.common.BulkDeleteRequest;
import com.petshop.backend.dto.user.UserRequest;
import com.petshop.backend.dto.user.UserResponse;
import com.petshop.backend.entity.User;
import com.petshop.backend.service.UserService;
import jakarta.validation.Valid;
import org.springframework.data.domain.Page;
@@ -26,8 +27,9 @@ public class UserController {
@GetMapping
public ResponseEntity<Page<UserResponse>> getAllUsers(
@RequestParam(required = false) String q,
@RequestParam(required = false) User.Role role,
Pageable pageable) {
return ResponseEntity.ok(userService.getAllUsers(q, pageable));
return ResponseEntity.ok(userService.getAllUsers(q, role, pageable));
}
@GetMapping("/{id}")

View File

@@ -16,6 +16,7 @@ public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByEmail(String email);
Optional<User> findByPhone(String phone);
boolean existsByUsername(String username);
Page<User> findByRole(User.Role role, Pageable pageable);
@Query("SELECT u FROM User u WHERE " +
"LOWER(u.username) LIKE LOWER(CONCAT('%', :q, '%')) OR " +
@@ -23,4 +24,11 @@ public interface UserRepository extends JpaRepository<User, Long> {
"LOWER(COALESCE(u.email, '')) LIKE LOWER(CONCAT('%', :q, '%')) OR " +
"LOWER(COALESCE(u.phone, '')) LIKE LOWER(CONCAT('%', :q, '%'))")
Page<User> searchUsers(@Param("q") String query, Pageable pageable);
@Query("SELECT u FROM User u WHERE u.role = :role AND (" +
"LOWER(u.username) LIKE LOWER(CONCAT('%', :q, '%')) OR " +
"LOWER(COALESCE(u.fullName, '')) LIKE LOWER(CONCAT('%', :q, '%')) OR " +
"LOWER(COALESCE(u.email, '')) LIKE LOWER(CONCAT('%', :q, '%')) OR " +
"LOWER(COALESCE(u.phone, '')) LIKE LOWER(CONCAT('%', :q, '%')))")
Page<User> searchUsersByRole(@Param("q") String query, @Param("role") User.Role role, Pageable pageable);
}

View File

@@ -28,10 +28,15 @@ public class UserService {
this.userBusinessLinkageService = userBusinessLinkageService;
}
public Page<UserResponse> getAllUsers(String query, Pageable pageable) {
public Page<UserResponse> getAllUsers(String query, User.Role role, Pageable pageable) {
Page<User> users;
if (query != null && !query.trim().isEmpty()) {
boolean hasQuery = query != null && !query.trim().isEmpty();
if (hasQuery && role != null) {
users = userRepository.searchUsersByRole(query, role, pageable);
} else if (hasQuery) {
users = userRepository.searchUsers(query, pageable);
} else if (role != null) {
users = userRepository.findByRole(role, pageable);
} else {
users = userRepository.findAll(pageable);
}