Coverage for dao/team_follow_dao.py: 40.80%

101 statements  

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

1"""Team Follow DAO. 

2 

3Tracks which teams, or squads, a user follows. Many-to-many. Cross-club by 

4design: a user can follow teams from any number of clubs (see 

5project_engagement_flywheel memory). 

6 

7A team row spans several age groups, so a follow carries `age_group_id` 

8(SB-1608): NULL follows every age group of the team (what every follow meant 

9before squads existed), a value follows that squad only. A follow is for 

10alerts; it never grants channel access. 

11 

12The list_subscriptions_for_team_ids method is the fan-out hot path — 

13called once per match event to find every push subscription that should 

14receive a notification. 

15""" 

16 

17from __future__ import annotations 

18 

19import structlog 

20 

21from dao.base_dao import BaseDAO 

22 

23logger = structlog.get_logger() 

24 

25TABLE = "user_team_follows" 

26 

27 

28def follows_match(follow_age_group_id: int | None, match_age_group_id: int | None) -> bool: 

29 """Whether a follow row should hear about a match of its team. 

30 

31 A whole-team follow (NULL) hears every match. A squad follow hears only 

32 matches in its age group, so a match with no age group reaches whole-team 

33 followers only: MT cannot say which squad played it. 

34 """ 

35 if follow_age_group_id is None: 

36 return True 

37 return match_age_group_id is not None and follow_age_group_id == match_age_group_id 

38 

39 

40class TeamFollowDAO(BaseDAO): 

41 """Data access for user→team follow relationships.""" 

42 

43 def follow(self, user_id: str, team_id: int) -> bool: 

44 """Follow every age group of a team. Idempotent — re-following returns True silently.""" 

45 try: 

46 # Check for existing first to keep idempotency clean. 

47 existing = ( 

48 self.client.table(TABLE) 

49 .select("user_id") 

50 .eq("user_id", user_id) 

51 .eq("team_id", team_id) 

52 .is_("age_group_id", "null") 

53 .limit(1) 

54 .execute() 

55 ) 

56 if existing.data: 

57 return True 

58 self.client.table(TABLE).insert( 

59 {"user_id": user_id, "team_id": team_id} 

60 ).execute() 

61 return True 

62 except Exception: 

63 logger.exception( 

64 "team_follow_failed", user_id=user_id, team_id=team_id 

65 ) 

66 return False 

67 

68 def team_plays_age_group(self, team_id: int, age_group_id: int) -> bool | None: 

69 """Whether the team is registered at this age group (team_mappings). None on error.""" 

70 try: 

71 rows = ( 

72 self.client.table("team_mappings") 

73 .select("team_id") 

74 .eq("team_id", team_id) 

75 .eq("age_group_id", age_group_id) 

76 .limit(1) 

77 .execute() 

78 ).data 

79 return bool(rows) 

80 except Exception: 

81 logger.exception("team_follow_age_check_failed", team_id=team_id, age_group_id=age_group_id) 

82 return None 

83 

84 def follow_squad(self, user_id: str, team_id: int, age_group_id: int) -> bool: 

85 """Follow one squad of any club (SB-1618). Idempotent. 

86 

87 A whole-team follow already covers every squad, so it is left as it is 

88 and nothing is added. 

89 """ 

90 try: 

91 rows = ( 

92 self.client.table(TABLE) 

93 .select("age_group_id") 

94 .eq("user_id", user_id) 

95 .eq("team_id", team_id) 

96 .execute() 

97 ).data or [] 

98 if any(r.get("age_group_id") in (None, age_group_id) for r in rows): 

99 return True 

100 self.client.table(TABLE).insert( 

101 {"user_id": user_id, "team_id": team_id, "age_group_id": age_group_id} 

102 ).execute() 

103 return True 

104 except Exception: 

105 logger.exception("team_follow_squad_failed", user_id=user_id, team_id=team_id, age_group_id=age_group_id) 

106 return False 

107 

108 def unfollow(self, user_id: str, team_id: int, age_group_id: int | None = None) -> bool: 

109 """Unfollow a team: every row for it, or with `age_group_id` just that squad. 

110 

111 Idempotent — returns True even if not following. 

112 """ 

113 try: 

114 query = self.client.table(TABLE).delete().eq("user_id", user_id).eq("team_id", team_id) 

115 if age_group_id is not None: 

116 query = query.eq("age_group_id", age_group_id) 

117 query.execute() 

118 return True 

119 except Exception: 

120 logger.exception( 

121 "team_unfollow_failed", user_id=user_id, team_id=team_id, age_group_id=age_group_id 

122 ) 

123 return False 

124 

125 def set_club_squads( 

126 self, user_id: str, club_team_ids: set[int], squads: set[tuple[int, int]] 

127 ) -> bool: 

128 """Make the user's follows of these teams exactly `squads` (team_id, age_group_id). 

129 

130 Follows of teams outside `club_team_ids` are left alone. A whole-team 

131 follow of a club team is replaced by the squads chosen for it. New 

132 squads are added before old rows go, so a failure part-way leaves extra 

133 alerts, never missing ones. 

134 """ 

135 if not club_team_ids: 

136 return True 

137 try: 

138 rows = ( 

139 self.client.table(TABLE) 

140 .select("team_id, age_group_id") 

141 .eq("user_id", user_id) 

142 .in_("team_id", sorted(club_team_ids)) 

143 .execute() 

144 ).data or [] 

145 existing = {(r["team_id"], r.get("age_group_id")) for r in rows} 

146 to_add = sorted(squads - existing) 

147 if to_add: 

148 self.client.table(TABLE).insert( 

149 [{"user_id": user_id, "team_id": t, "age_group_id": a} for t, a in to_add] 

150 ).execute() 

151 for team_id, age_group_id in sorted(existing - squads, key=lambda k: (k[0], k[1] or 0)): 

152 query = self.client.table(TABLE).delete().eq("user_id", user_id).eq("team_id", team_id) 

153 query = ( 

154 query.is_("age_group_id", "null") 

155 if age_group_id is None 

156 else query.eq("age_group_id", age_group_id) 

157 ) 

158 query.execute() 

159 return True 

160 except Exception: 

161 logger.exception("team_follow_set_squads_failed", user_id=user_id) 

162 return False 

163 

164 def list_for_user(self, user_id: str) -> list[dict]: 

165 """Return teams the user follows, joined with club + division + league 

166 for display. 

167 

168 SB-65: the original projection returned only `team.name` and 

169 `team.club.name`. For many MLS Next teams those two strings are 

170 identical (the team name IS the club name), making the "Teams you 

171 follow" list in the profile look like it's about clubs. Surfacing 

172 `team.division.name` and the division's league disambiguates each 

173 row (e.g. "IFA · Homegrown · Northeast"). 

174 """ 

175 try: 

176 response = ( 

177 self.client.table(TABLE) 

178 .select( 

179 "team_id, age_group_id, created_at, " 

180 "age_group:age_groups(id, name), " 

181 "team:teams!user_team_follows_team_id_fkey(" 

182 "id, name, age_group_id, " 

183 "club:clubs(id, name), " 

184 "division:divisions(" 

185 "id, name, " 

186 "leagues!divisions_league_id_fkey(id, name)" 

187 ")" 

188 ")" 

189 ) 

190 .eq("user_id", user_id) 

191 .order("created_at", desc=True) 

192 .execute() 

193 ) 

194 return response.data or [] 

195 except Exception: 

196 logger.exception("team_follow_list_failed", user_id=user_id) 

197 return [] 

198 

199 def _follower_user_ids(self, team_ids: list[int], age_group_id: int | None) -> list[str]: 

200 """Distinct users following any of these teams at this match's age group. 

201 Raises on DB error. 

202 

203 Shared by the Web Push, APNs and FCM fan-outs (SB-1236) so all resolve 

204 followers the same way; `follows_match` decides squad follows (SB-1608). 

205 """ 

206 follow_resp = ( 

207 self.client.table(TABLE) 

208 .select("user_id, age_group_id") 

209 .in_("team_id", team_ids) 

210 .execute() 

211 ) 

212 return list( 

213 { 

214 row["user_id"] 

215 for row in (follow_resp.data or []) 

216 if row.get("user_id") and follows_match(row.get("age_group_id"), age_group_id) 

217 } 

218 ) 

219 

220 def list_user_ids_for_team_ids( 

221 self, team_ids: list[int], age_group_id: int | None 

222 ) -> list[str]: 

223 """Distinct users following any of these teams (APNs/FCM fan-out, SB-1236). 

224 

225 Returns [] on error — same swallow-and-log contract as the 

226 subscriptions fan-out below. 

227 """ 

228 if not team_ids: 

229 return [] 

230 try: 

231 return self._follower_user_ids(team_ids, age_group_id) 

232 except Exception: 

233 logger.exception("team_follow_list_user_ids_failed", team_ids=team_ids) 

234 return [] 

235 

236 def list_subscriptions_for_team_ids( 

237 self, team_ids: list[int], age_group_id: int | None 

238 ) -> list[dict]: 

239 """Fan-out query: every push subscription whose owner follows any of these teams. 

240 

241 Returns deduplicated subscription rows (a user with multiple devices 

242 appears multiple times; that's intentional — each device gets its 

243 own push). Deduplication is by subscription.id, not user, so a user 

244 following both home and away teams still gets one push per device, 

245 not two. 

246 

247 Implemented as two plain `in_` queries rather than a PostgREST embed. 

248 `user_team_follows` and `push_subscriptions` have no direct foreign key 

249 between them (both only reference `user_profiles`), so PostgREST cannot 

250 embed one from the other — the embed form raises PGRST200, and since the 

251 DAO swallows exceptions, the dispatcher would silently deliver zero 

252 pushes. This is the fan-out that decides who actually gets notified 

253 (SB-77); see tests/integration/test_push_delivery_on_score.py. 

254 """ 

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

256 return [] 

257 try: 

258 # Step 1: distinct users following any of these teams. 

259 user_ids = self._follower_user_ids(team_ids, age_group_id) 

260 if not user_ids: 260 ↛ 261line 260 didn't jump to line 261 because the condition on line 260 was never true

261 return [] 

262 

263 # Step 2: every push subscription owned by those users. 

264 sub_resp = ( 

265 self.client.table("push_subscriptions") 

266 .select("id, endpoint, p256dh_key, auth_key, user_id") 

267 .in_("user_id", user_ids) 

268 .execute() 

269 ) 

270 

271 # Dedupe by subscription id (a user with 2 devices yields 2 rows — 

272 # intentional; each device gets its own push). 

273 seen_ids: set[str] = set() 

274 flat: list[dict] = [] 

275 for sub in sub_resp.data or []: 

276 if sub["id"] in seen_ids: 

277 continue 

278 seen_ids.add(sub["id"]) 

279 flat.append(sub) 

280 return flat 

281 except Exception: 

282 logger.exception( 

283 "team_follow_list_subscriptions_failed", team_ids=team_ids 

284 ) 

285 return []