Coverage for app/logic/searchUsers.py: 91%

32 statements  

« prev     ^ index     » next       coverage.py v7.10.2, created at 2026-08-24 19:35 +0000

1from peewee import fn 

2from playhouse.shortcuts import model_to_dict 

3from app.models.user import User 

4def searchUsers(query, category=None): 

5 ''' 

6 Search the User table based on the search query and category 

7 

8 MySQL LIKE is case insensitive 

9 ''' 

10 # add wildcards to each piece of the query 

11 splitSearch = query.strip().split() 

12 if not splitSearch: 

13 return User.select().where(False) 

14 fullSearch = " ".join(splitSearch) + "%" 

15 searchWhere = (User.firstName ** fullSearch | User.lastName ** fullSearch | User.username ** fullSearch) 

16 for splitIndex in range(1, len(splitSearch)): 

17 firstName = " ".join(splitSearch[:splitIndex]) + "%" 

18 lastName = " ".join(splitSearch[splitIndex:]) + "%" 

19 

20 searchWhere |= ( 

21 (User.firstName ** firstName) & 

22 (User.lastName ** lastName) 

23 ) 

24 

25 # Also allow individual pieces of the name to match 

26 for namePart in splitSearch: 

27 nameSearch = namePart + "%" 

28 

29 searchWhere |= ( 

30 (User.firstName ** nameSearch) | 

31 (User.lastName ** nameSearch) | 

32 (User.username ** nameSearch) 

33 ) 

34 

35 if category == "instructor": 

36 userWhere = (User.isFaculty | User.isStaff) 

37 elif category == "admin": 

38 userWhere = (User.isCeltsAdmin) 

39 elif category == "studentstaff": 

40 userWhere = (User.isCeltsStudentStaff) 

41 elif category == "operationsTeam": 

42 userWhere = (User.isCeltsOperationsTeam) 

43 elif category == "celtsLinkAdmin": 

44 userWhere = (User.isFaculty | User.isStaff | User.isCeltsStudentStaff | User.isCeltsOperationsTeam) 

45 elif category == "all": 

46 userWhere = (True) 

47 else: 

48 userWhere = (User.isStudent) 

49 

50 fullSearchText = " ".join(splitSearch) 

51 # Combine into query 

52 searchResults = User.select().where(searchWhere, userWhere).order_by( 

53 fn.CONCAT(User.firstName, " ", User.lastName) 

54 .contains(fullSearchText) 

55 .desc(), 

56 User.firstName.startswith(fullSearchText).desc(), 

57 User.lastName.startswith(fullSearchText).desc(), 

58 User.lastName, 

59 User.firstName 

60 ) 

61 

62 return { user.username : model_to_dict(user) for user in searchResults }