Coverage for dao/channel_members_dao.py: 20.71%
114 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 15:03 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 15:03 +0000
1"""
2Channel Members Data Access Object (SB-1607).
4Grants to notification channels, and the facts the access rules need: a
5channel's club, its age group's name, and the squads a player is on now.
7Reads used to decide access fail closed: a failed lookup returns nothing, which
8the rules read as "no access". Channel reads never select `destination`.
9"""
11import structlog
13from dao.base_dao import BaseDAO
14from mt_tools.my_team import Squad
16logger = structlog.get_logger()
18TABLE = "channel_members"
19# Everything a member-facing read needs, and never `destination`.
20CHANNEL_COLUMNS = "id, scope_type, club_id, team_id, age_group_id, audience, platform, invite_url, enabled"
23class MemberWriteError(Exception):
24 """A grant could not be saved. Safe to log."""
27def _age_sort_key(name: str) -> tuple[int, str]:
28 """U9 before U13: by the number in the name, then the name."""
29 digits = "".join(ch for ch in name if ch.isdigit())
30 return (int(digits) if digits else 999, name)
33class ChannelMembersDAO(BaseDAO):
34 """Data access for channel grants."""
36 def _rows(self, description: str, build) -> list[dict]:
37 try:
38 return build().execute().data or []
39 except Exception as exc:
40 logger.error("dao_channel_members_read_failed", query=description, error_type=type(exc).__name__)
41 return []
43 # --- channels ---------------------------------------------------------------
45 def team_club_id(self, team_id: int | None) -> int | None:
46 if team_id is None:
47 return None
48 rows = self._rows("team_club", lambda: self.client.table("teams").select("club_id").eq("id", team_id).limit(1))
49 return rows[0].get("club_id") if rows else None
51 def club_name(self, club_id: int) -> str | None:
52 rows = self._rows("club_name", lambda: self.client.table("clubs").select("name").eq("id", club_id).limit(1))
53 return rows[0].get("name") if rows else None
55 def channel(self, channel_id: int) -> dict | None:
56 rows = self._rows(
57 "channel",
58 lambda: self.client.table("notification_channels").select(CHANNEL_COLUMNS).eq("id", channel_id).limit(1),
59 )
60 return rows[0] if rows else None
62 def channels_for_team(self, team_id: int, club_id: int | None) -> list[dict]:
63 """The team's squad channels and its club's channels, in id order."""
64 rows = self._rows(
65 "team_channels",
66 lambda: self.client.table("notification_channels")
67 .select(CHANNEL_COLUMNS)
68 .eq("scope_type", "team")
69 .eq("team_id", team_id)
70 .order("id"),
71 )
72 if club_id is not None:
73 rows += self._rows(
74 "club_channels",
75 lambda: self.client.table("notification_channels")
76 .select(CHANNEL_COLUMNS)
77 .eq("scope_type", "club")
78 .eq("club_id", club_id)
79 .order("id"),
80 )
81 return rows
83 def age_group_names(self, age_group_ids: set[int]) -> dict[int, str]:
84 if not age_group_ids:
85 return {}
86 rows = self._rows(
87 "age_groups",
88 lambda: self.client.table("age_groups").select("id, name").in_("id", sorted(age_group_ids)),
89 )
90 return {r["id"]: r["name"] for r in rows}
92 # --- players ----------------------------------------------------------------
94 def current_squads(self, user_id: str) -> list[Squad]:
95 """The squads this user plays for now, from their current squad history."""
96 rows = self._rows(
97 "current_squads",
98 lambda: self.client.table("player_team_history")
99 .select("team_id, age_group_id, teams(club_id), age_groups(name)")
100 .eq("player_id", user_id)
101 .eq("is_current", True),
102 )
103 return [
104 Squad(
105 team_id=r["team_id"],
106 age_group_id=r.get("age_group_id"),
107 club_id=(r.get("teams") or {}).get("club_id"),
108 age_group_name=(r.get("age_groups") or {}).get("name"),
109 )
110 for r in rows
111 ]
113 # --- grants -----------------------------------------------------------------
115 def statuses(self, user_id: str, channel_ids: list[int]) -> dict[int, str]:
116 if not channel_ids:
117 return {}
118 rows = self._rows(
119 "statuses",
120 lambda: self.client.table(TABLE)
121 .select("channel_id, status")
122 .eq("user_id", user_id)
123 .in_("channel_id", channel_ids),
124 )
125 return {r["channel_id"]: r["status"] for r in rows}
127 def get(self, channel_id: int, user_id: str) -> dict | None:
128 rows = self._rows(
129 "get",
130 lambda: self.client.table(TABLE).select("*").eq("channel_id", channel_id).eq("user_id", user_id).limit(1),
131 )
132 return rows[0] if rows else None
134 def save(self, channel_id: int, user_id: str, fields: dict) -> dict:
135 """Create or update the grant for (channel, user). Raises MemberWriteError."""
136 try:
137 row = {"channel_id": channel_id, "user_id": user_id, **fields}
138 return self.client.table(TABLE).upsert(row, on_conflict="channel_id,user_id").execute().data[0]
139 except Exception as exc:
140 logger.error("dao_channel_members_write_failed", error_type=type(exc).__name__)
141 raise MemberWriteError("Could not save channel access") from None
143 def delete(self, channel_id: int, user_id: str) -> None:
144 try:
145 self.client.table(TABLE).delete().eq("channel_id", channel_id).eq("user_id", user_id).execute()
146 except Exception as exc:
147 logger.error("dao_channel_members_write_failed", error_type=type(exc).__name__)
148 raise MemberWriteError("Could not withdraw request") from None
150 def requested(self, channel_ids: list[int]) -> list[dict]:
151 """Pending requests on these channels, oldest first, with who asked."""
152 return self.with_status(channel_ids, "requested")
154 def with_status(self, channel_ids: list[int], status: str) -> list[dict]:
155 """Grants in one status on these channels, oldest first, with who they are (SB-1671)."""
156 if not channel_ids:
157 return []
158 return self._rows(
159 f"with_status_{status}",
160 lambda: self.client.table(TABLE)
161 .select(
162 "channel_id, user_id, source, created_at, decided_at, "
163 "user_profiles!channel_members_user_id_fkey(display_name, username)"
164 )
165 .in_("channel_id", channel_ids)
166 .eq("status", status)
167 .order("created_at"),
168 )
170 def granted_user_ids(self, channel_id: int) -> set[str]:
171 """Everyone with an active or pending grant on this channel."""
172 rows = self._rows(
173 "granted_user_ids",
174 lambda: self.client.table(TABLE)
175 .select("user_id")
176 .eq("channel_id", channel_id)
177 .in_("status", ["active", "requested"]),
178 )
179 return {r["user_id"] for r in rows}
181 def club_people(self, club_id: int, roles: list[str], limit: int = 500) -> list[dict]:
182 """Profiles in these roles whose club is this one, directly or through their team (SB-1671).
184 Carries only what the access rules and a picker need.
185 """
186 team_ids = [
187 r["id"]
188 for r in self._rows(
189 "club_teams", lambda: self.client.table("teams").select("id").eq("club_id", club_id).limit(1000)
190 )
191 ]
192 club_filter = f"club_id.eq.{club_id}"
193 if team_ids:
194 club_filter += f",team_id.in.({','.join(str(t) for t in team_ids)})"
195 return self._rows(
196 "club_people",
197 lambda: self.client.table("user_profiles")
198 .select("id, role, club_id, team_id, display_name, username")
199 .in_("role", roles)
200 .or_(club_filter)
201 .order("display_name")
202 .limit(limit),
203 )
205 def channels_for_teams(self, team_ids: set[int], club_ids: set[int]) -> list[dict]:
206 """Squad channels of these teams and club channels of these clubs, in id order."""
207 rows: list[dict] = []
208 if team_ids:
209 rows += self._rows(
210 "my_team_channels",
211 lambda: self.client.table("notification_channels")
212 .select(CHANNEL_COLUMNS)
213 .eq("scope_type", "team")
214 .in_("team_id", sorted(team_ids))
215 .order("id"),
216 )
217 if club_ids:
218 rows += self._rows(
219 "my_club_channels",
220 lambda: self.client.table("notification_channels")
221 .select(CHANNEL_COLUMNS)
222 .eq("scope_type", "club")
223 .in_("club_id", sorted(club_ids))
224 .order("id"),
225 )
226 return rows
228 def team_age_groups(self, team_id: int) -> list[dict] | None:
229 """The age groups a team is registered in (team_mappings), youngest first.
231 Each is a squad that can have its own channels. None when the lookup
232 failed, so "could not check" never reads as "registered in none".
233 """
234 try:
235 rows = (
236 self.client.table("team_mappings")
237 .select("age_group_id, age_groups(name)")
238 .eq("team_id", team_id)
239 .execute()
240 .data
241 or []
242 )
243 except Exception as exc:
244 logger.error("dao_channel_members_read_failed", query="team_age_groups", error_type=type(exc).__name__)
245 return None
246 names = {r["age_group_id"]: (r.get("age_groups") or {}).get("name") or "" for r in rows}
247 return [{"id": i, "name": n} for i, n in sorted(names.items(), key=lambda kv: _age_sort_key(kv[1]))]
249 def team_clubs(self, team_ids: set[int]) -> dict[int, int | None]:
250 if not team_ids:
251 return {}
252 rows = self._rows(
253 "team_clubs", lambda: self.client.table("teams").select("id, club_id").in_("id", sorted(team_ids))
254 )
255 return {r["id"]: r.get("club_id") for r in rows}
257 def is_managed(self, team_ids: set[int], club_ids: set[int]) -> bool | None:
258 """Whether anyone on MT manages these teams or clubs: the claimed/unclaimed split.
260 None when the lookup failed, so "could not check" never reads as "unclaimed".
261 """
262 try:
263 if team_ids:
264 rows = (
265 self.client.table("user_profiles")
266 .select("id")
267 .in_("role", ["team-manager", "team_manager"])
268 .in_("team_id", sorted(team_ids))
269 .limit(1)
270 .execute()
271 .data
272 )
273 if rows:
274 return True
275 if club_ids:
276 rows = (
277 self.client.table("user_profiles")
278 .select("id")
279 .eq("role", "club_manager")
280 .in_("club_id", sorted(club_ids))
281 .limit(1)
282 .execute()
283 .data
284 )
285 if rows:
286 return True
287 except Exception as exc:
288 logger.error("dao_channel_members_read_failed", query="is_managed", error_type=type(exc).__name__)
289 return None
290 return False
292 def profile(self, user_id: str) -> dict | None:
293 """The fields channel access depends on, for someone other than the caller."""
294 rows = self._rows(
295 "profile",
296 lambda: self.client.table("user_profiles").select("id, role, club_id, team_id").eq("id", user_id).limit(1),
297 )
298 return rows[0] if rows else None