Coverage for notifications/channel_resolver.py: 88.00%

57 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2026-11-30 15:10 +0000

1"""Resolve the set of (platform, destination) channels for a given match. 

2 

3Club, squad and global channels are unioned and deduplicated. Home club's 

4timezone is always used for message timestamps, regardless of which club 

5owns a given destination. 

6""" 

7 

8from __future__ import annotations 

9 

10from typing import NamedTuple 

11 

12import structlog 

13 

14from dao.club_notifications_dao import ClubNotificationsDAO # noqa: TC001 — used at runtime for type check 

15from notifications.audience import players_allowed_at 

16from notifications.preferences import is_player_only 

17 

18logger = structlog.get_logger(__name__) 

19 

20 

21class ResolvedChannel(NamedTuple): 

22 """Where one post goes. `channel_id` is the row the delivery is recorded against.""" 

23 

24 platform: str 

25 destination: str 

26 channel_id: int 

27 # Post each match as its own thread (SB-1606). 

28 post_as_threads: bool = False 

29 

30 

31def select_destinations( 

32 rows: list[dict], event_type: str, age_group_name: str | None, team_id: int | None = None 

33) -> list[ResolvedChannel]: 

34 """Filter candidate channels to one per (platform, destination). 

35 

36 Pure, so the routing rules are testable without a database. `event_types` 

37 of None means every event; an empty list means none. 

38 

39 A player-only event (SB-1610) reaches only the player channel of the squad 

40 it is about (`team_id`): never a fan channel, a club channel, the other 

41 team's squad, or a global channel, whatever their `event_types` say. 

42 """ 

43 players_allowed = players_allowed_at(age_group_name) 

44 if is_player_only(event_type): 

45 rows = [ 

46 r 

47 for r in rows 

48 if r.get("audience") == "players" 

49 and r.get("scope_type") == "team" 

50 and team_id is not None 

51 and r.get("team_id") == team_id 

52 ] 

53 seen: set[tuple[str, str]] = set() 

54 ordered: list[ResolvedChannel] = [] 

55 for row in rows: 

56 if not row.get("enabled"): 

57 continue 

58 if row.get("audience") == "players" and not players_allowed: 

59 continue 

60 event_types = row.get("event_types") 

61 if event_types is not None and event_type not in event_types: 

62 continue 

63 key = (row["platform"], row["destination"]) 

64 if key not in seen: 

65 seen.add(key) 

66 ordered.append( 

67 ResolvedChannel(row["platform"], row["destination"], row["id"], bool(row.get("post_as_threads"))) 

68 ) 

69 return ordered 

70 

71 

72def resolve_destinations( 

73 match: dict, 

74 event_type: str, 

75 dao: ClubNotificationsDAO, 

76 team_id: int | None = None, 

77) -> list[ResolvedChannel]: 

78 """The channels that should hear about this match event. 

79 

80 Both clubs' channels, both squads' channels (the team row plus the match's 

81 age group), and global channels. 

82 """ 

83 home_club = match.get("home_team_club") or {} 

84 away_club = match.get("away_team_club") or {} 

85 club_ids = [c for c in (home_club.get("id"), away_club.get("id")) if c is not None] 

86 team_ids = [t for t in (match.get("home_team_id"), match.get("away_team_id")) if t is not None] 

87 rows = dao.list_for_match(club_ids, team_ids, match.get("age_group_id")) 

88 return select_destinations(rows, event_type, match.get("age_group_name"), team_id) 

89 

90 

91def resolve_user_push_subscriptions( 

92 home_team_id: int | None, 

93 away_team_id: int | None, 

94 team_follow_dao, 

95 age_group_id: int | None, 

96) -> list[dict]: 

97 """Find push subscriptions for users following either team at this age group. 

98 

99 Whole-team follows always match; squad follows only at their age group (SB-1608). 

100 

101 Returns subscription rows (id, endpoint, p256dh_key, auth_key, user_id), 

102 deduplicated by subscription id. A user with two devices appears twice 

103 (one per device). A user following both home and away teams still gets 

104 one push per device, not two. 

105 """ 

106 team_ids = [t for t in (home_team_id, away_team_id) if t is not None] 

107 if not team_ids: 107 ↛ 108line 107 didn't jump to line 108 because the condition on line 107 was never true

108 return [] 

109 try: 

110 return team_follow_dao.list_subscriptions_for_team_ids(team_ids, age_group_id) 

111 except Exception as exc: 

112 logger.warning( 

113 "resolve_push_subscriptions_failed", 

114 home_team_id=home_team_id, 

115 away_team_id=away_team_id, 

116 error=str(exc), 

117 ) 

118 return [] 

119 

120 

121def fetch_club_timezone(club_id: int | None, supabase_client) -> str: 

122 """Look up the IANA timezone for a club; fall back to America/New_York.""" 

123 if club_id is None: 

124 return "America/New_York" 

125 try: 

126 resp = ( 

127 supabase_client.table("clubs") 

128 .select("timezone") 

129 .eq("id", club_id) 

130 .limit(1) 

131 .execute() 

132 ) 

133 if resp.data: 133 ↛ 141line 133 didn't jump to line 141 because the condition on line 133 was always true

134 return resp.data[0].get("timezone") or "America/New_York" 

135 except Exception as exc: 

136 logger.warning( 

137 "fetch_club_timezone_failed", 

138 club_id=club_id, 

139 error=str(exc), 

140 ) 

141 return "America/New_York"