Coverage for app/backend/src/couchers/helpers/newbie.py: 100%

18 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-19 06:12 +0000

1from typing import Any 

2 

3from sqlalchemy import Enum 

4from sqlalchemy.sql import and_, case, func, or_, select, type_coerce 

5from sqlalchemy.sql.elements import ColumnElement 

6 

7from couchers.helpers.completed_profile import has_completed_profile_expression 

8from couchers.helpers.references import where_references_counted 

9from couchers.materialized_views import UserResponseRate 

10from couchers.models import HostingStatus, HostPool, Reference, User 

11 

12HOST_POOL_NEWBIE_MAX_REFERENCES = 1 

13HOST_POOL_NEWBIE_MAX_REQUESTS = 5 

14HOST_POOL_NEWBIE_MIN_RESPONSE96H = 0.66 

15# once this many requests are counted, at least one of them must have been accepted 

16HOST_POOL_NEWBIE_REQUESTS_BEFORE_ACCEPTANCE = 3 

17 

18 

19def has_newbie_hosting_history_expression() -> ColumnElement[bool]: 

20 """ 

21 Whether the hosting history of the User in the enclosing query lets them into the newbie pool. 

22 """ 

23 # the count shown on the user's profile 

24 reference_count = where_references_counted( 

25 select(func.count(Reference.id)).where(Reference.to_user_id == User.id), None 

26 ).scalar_subquery() 

27 

28 # nulls (nothing counted yet) don't disqualify 

29 has_disqualifying_response_rate = ( 

30 select(UserResponseRate.user_id) 

31 .where(UserResponseRate.user_id == User.id) 

32 .where( 

33 or_( 

34 UserResponseRate.requests96h > HOST_POOL_NEWBIE_MAX_REQUESTS, 

35 UserResponseRate.response96h < HOST_POOL_NEWBIE_MIN_RESPONSE96H, 

36 and_( 

37 UserResponseRate.requests168h >= HOST_POOL_NEWBIE_REQUESTS_BEFORE_ACCEPTANCE, 

38 UserResponseRate.accept168h == 0, 

39 ), 

40 ) 

41 ) 

42 .exists() 

43 ) 

44 

45 return and_(reference_count <= HOST_POOL_NEWBIE_MAX_REFERENCES, ~has_disqualifying_response_rate) 

46 

47 

48def host_pool_expression() -> ColumnElement[Any]: 

49 """ 

50 The host pool of the User in the enclosing query. 

51 """ 

52 # nested so the history subqueries only run for the few users who meet the profile conditions 

53 return type_coerce( 

54 case( 

55 ( 

56 and_( 

57 User.hosting_status == HostingStatus.can_host, 

58 has_completed_profile_expression(), 

59 User.has_completed_my_home, 

60 ), 

61 case( 

62 (has_newbie_hosting_history_expression(), HostPool.newbie.name), 

63 else_=HostPool.normal.name, 

64 ), 

65 ), 

66 else_=HostPool.normal.name, 

67 ), 

68 Enum(HostPool, native_enum=False, create_constraint=False), 

69 )