Coverage for dao/notification_channels_dao.py: 24.68%
65 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"""
2Notification Channels Data Access Object (SB-1602).
4Where match updates are posted: a squad, a club, or every match.
6``destination`` is sensitive, and a Postgres unique-violation message quotes it,
7so database errors here are logged by type only and never re-raised verbatim.
8"""
10import uuid
12import structlog
14from dao.base_dao import BaseDAO
16logger = structlog.get_logger()
18TABLE = "notification_channels"
19_UNIQUE_VIOLATION = "23505"
22class DuplicateChannelError(Exception):
23 """This target already posts to that destination."""
26class ChannelWriteError(Exception):
27 """A channel could not be saved. Safe to log: carries no destination."""
30def actor_id(user: dict) -> str | None:
31 """The caller's profile id for `created_by`; None for a non-user (service) caller."""
32 value = user.get("user_id") or user.get("id")
33 try:
34 return str(uuid.UUID(str(value)))
35 except ValueError:
36 return None
39class NotificationChannelsDAO(BaseDAO):
40 """Data access for scoped notification channels."""
42 def _select(self, description: str, build) -> list[dict]:
43 """Run a read; a failure is logged and returns no rows.
45 Delivery is best-effort, so one failed lookup must not cost the others.
46 """
47 try:
48 return build(self.client.table(TABLE).select("*")).execute().data or []
49 except Exception as exc:
50 logger.error("dao_notification_channels_read_failed", query=description, error_type=type(exc).__name__)
51 return []
53 def list_for_match(
54 self,
55 club_ids: list[int],
56 team_ids: list[int],
57 age_group_id: int | None,
58 ) -> list[dict]:
59 """Every channel that could receive this match, clubs before squads before global."""
60 rows: list[dict] = []
61 if club_ids:
62 rows += self._select(
63 "club",
64 lambda q: q.eq("scope_type", "club").in_("club_id", club_ids).order("id"),
65 )
66 if team_ids and age_group_id is not None:
67 rows += self._select(
68 "team",
69 lambda q: q.eq("scope_type", "team")
70 .in_("team_id", team_ids)
71 .eq("age_group_id", age_group_id)
72 .order("id"),
73 )
74 rows += self._select("global", lambda q: q.eq("scope_type", "global").order("id"))
75 return rows
77 def list_for_scope(
78 self,
79 scope_type: str,
80 club_id: int | None = None,
81 team_id: int | None = None,
82 age_group_id: int | None = None,
83 ) -> list[dict]:
84 """Channels for one scope. An empty list is the normal state."""
86 def build(query):
87 query = query.eq("scope_type", scope_type)
88 if club_id is not None:
89 query = query.eq("club_id", club_id)
90 if team_id is not None:
91 query = query.eq("team_id", team_id)
92 if age_group_id is not None:
93 query = query.eq("age_group_id", age_group_id)
94 return query.order("id")
96 return self._select("scope", build)
98 def get_by_id(self, channel_id: int) -> dict | None:
99 rows = self._select("by_id", lambda q: q.eq("id", channel_id).limit(1))
100 return rows[0] if rows else None
102 def create(self, fields: dict) -> dict:
103 """Insert a channel. Raises DuplicateChannelError or ChannelWriteError."""
104 try:
105 return self.client.table(TABLE).insert(fields).execute().data[0]
106 except Exception as exc:
107 raise self._write_error("create", exc) from None
109 def update(self, channel_id: int, fields: dict) -> dict | None:
110 """Update a channel; None if it no longer exists."""
111 try:
112 rows = self.client.table(TABLE).update(fields).eq("id", channel_id).execute().data
113 except Exception as exc:
114 raise self._write_error("update", exc) from None
115 return rows[0] if rows else None
117 def delete_by_id(self, channel_id: int) -> bool:
118 """Remove a channel. Returns True if a row was deleted."""
119 try:
120 return bool(self.client.table(TABLE).delete().eq("id", channel_id).execute().data)
121 except Exception as exc:
122 raise self._write_error("delete", exc) from None
124 @staticmethod
125 def _write_error(operation: str, exc: Exception) -> Exception:
126 if _UNIQUE_VIOLATION in str(exc):
127 return DuplicateChannelError()
128 logger.error("dao_notification_channels_write_failed", operation=operation, error_type=type(exc).__name__)
129 return ChannelWriteError(f"Could not {operation} notification channel")