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

32 statements  

« prev     ^ index     » next       coverage.py v7.10.2, created at 2026-09-10 21:56 +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 splitSearch = query.strip().split() 

11 if not splitSearch: 

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

13 searchWhere = None 

14 for namePart in splitSearch: 

15 nameSearch = namePart + "%" 

16 # This individual search term can match the user's first name, last name, or username. 

17 namePartWhere = (User.firstName.contains(namePart) | User.lastName.contains(namePart) | User.username.contains(namePart)) 

18 # For the first search term, initialize the WHERE condition. 

19 if searchWhere is None: 

20 searchWhere = namePartWhere 

21 else: 

22 searchWhere &= namePartWhere # Require every search term to match at least one of the first name, last name, or username fields. 

23 

24 if category == "instructor": 

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

26 elif category == "admin": 

27 userWhere = (User.isCeltsAdmin) 

28 elif category == "studentstaff": 

29 userWhere = (User.isCeltsStudentStaff) 

30 elif category == "operationsTeam": 

31 userWhere = (User.isCeltsOperationsTeam) 

32 elif category == "celtsLinkAdmin": 

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

34 elif category == "currentStudents": 

35 userWhere = (User.rawClassLevel.in_(["Freshman", "Sophomore", "Junior", "Senior"])) 

36 elif category == "all": 

37 userWhere = (True) 

38 else: 

39 userWhere = (User.isStudent) 

40 

41 fullSearchText = " ".join(splitSearch) 

42 # Combine into query 

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

44 fn.CONCAT(User.firstName, " ", User.lastName).contains(fullSearchText).desc(), 

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

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

47 User.lastName, 

48 User.firstName 

49 ) 

50 

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