Coverage for app / services / notifications.py: 77%
119 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""
2The in-app inbox — what the platform tells a person without waiting to be
3looked at (cost-control plan A2).
5A notification is one row per recipient (``notifications``), written by the
6platform when something happens that a person should know about: a budget
7passing a threshold (``budgets/alerts.py``), the platform allowance likewise,
8a monthly statement ready to read (``statements/store.py``). Each **kind** is
9one registered class saying how it is titled and where it links; adding one
10is a class here and a call where it happens.
12What a notification may say: figures, a budget's name, a workspace's name —
13never a prompt, an answer, or what a named colleague spent. Who receives it
14is decided by the caller, usually :func:`governors` — those who govern the
15workspace it is about (its owner for a Personal one; an admin or a governance
16editor of an organisation or project), who are the people who can act on a
17budget.
19Each is written at most once per recipient and ``dedupe_key``
20(``uq_notification_once``): a budget's 80% in October is one notification,
21however often the alerts job looks. The inbox is a person's, across every
22workspace they belong to, like their invites — each notification names its
23workspace, and its link opens in it.
24"""
26from __future__ import annotations
28import logging
29from abc import ABC
30from dataclasses import dataclass
31from datetime import datetime, timedelta
32from typing import Any, ClassVar, Iterable
33from uuid import UUID
35from sqlalchemy import and_
36from sqlalchemy.exc import IntegrityError, SQLAlchemyError
37from sqlalchemy.orm import Session
39from app.db.postgres.models import Notification, Project
40from app.services import access as access_service
41from app.services import membership as membership_service
42from app.services.workspace import Workspace, WorkspaceKind
43from app.util.time import aware_utcnow
45logger = logging.getLogger(__name__)
47#: How long a read notification is kept; unread ones are kept until read.
48RETENTION_DAYS = 90
49#: Unread ones are deleted after this long all the same.
50UNREAD_RETENTION_DAYS = 365
53# ── Kinds ────────────────────────────────────────────────────────────────────
56class Kind(ABC):
57 """One kind of notification."""
59 key: ClassVar[str]
60 #: How a list labels the kind.
61 label: ClassVar[str]
64_KINDS: dict[str, Kind] = {}
67def register_kind(cls: type[Kind]) -> type[Kind]:
68 if cls.key in _KINDS:
69 raise RuntimeError(f"Notification kind '{cls.key}' is already registered.")
70 _KINDS[cls.key] = cls()
71 return cls
74def kind_keys() -> frozenset[str]:
75 return frozenset(_KINDS)
78@register_kind
79class BudgetThreshold(Kind):
80 """A budget passed one of its alert thresholds, or was used up."""
82 key = "budget_threshold"
83 label = "Budget"
86@register_kind
87class BudgetProjected(Kind):
88 """At its recent rate, a budget is used up before it starts again."""
90 key = "budget_projected"
91 label = "Budget forecast"
94@register_kind
95class AllowanceThreshold(Kind):
96 """The platform allowance passed a threshold, or was used up."""
98 key = "allowance_threshold"
99 label = "Platform allowance"
102@register_kind
103class StatementReady(Kind):
104 """A month closed, and its statement was written."""
106 key = "statement_ready"
107 label = "Statement"
110@register_kind
111class SwarmAttention(Kind):
112 """A swarm run waits on its person: a plan to approve, or a question."""
114 key = "swarm_attention"
115 label = "Swarm"
118@register_kind
119class SwarmFinished(Kind):
120 """A swarm run finished, with its whole answer or part of it, or not."""
122 key = "swarm_finished"
123 label = "Swarm"
126# ── Writing ──────────────────────────────────────────────────────────────────
129@dataclass(frozen=True)
130class Message:
131 """What one notification says, before it has a recipient."""
133 kind: str
134 title: str
135 dedupe_key: str
136 body: str | None = None
137 #: A page written against ``/user/…``; fe-core moves it into the
138 #: workspace.
139 link: str | None = None
140 workspace: Workspace | None = None
141 workspace_name: str | None = None
142 data: dict[str, Any] | None = None
145def notify(db: Session, recipients: Iterable[UUID], message: Message) -> int:
146 """Write ``message`` to each recipient who has not had it
147 (``dedupe_key``). Returns how many were written. Commits; never raises —
148 a notification is worth less than the work that caused it."""
149 if message.kind not in _KINDS:
150 raise ValueError(f"Unknown notification kind {message.kind!r}")
151 wanted = list(dict.fromkeys(r for r in recipients if r is not None))
152 if not wanted:
153 return 0
154 try:
155 had = {
156 row[0]
157 for row in db.query(Notification.recipient_user_id)
158 .filter(
159 Notification.recipient_user_id.in_(wanted),
160 Notification.dedupe_key == message.dedupe_key,
161 )
162 .all()
163 }
164 rows = [
165 Notification(
166 recipient_user_id=recipient,
167 kind=message.kind,
168 workspace_key=message.workspace.key if message.workspace else None,
169 workspace_name=(message.workspace_name or "")[:255] or None,
170 title=message.title[:200],
171 body=message.body,
172 link=message.link,
173 data=message.data,
174 dedupe_key=message.dedupe_key[:200],
175 )
176 for recipient in wanted
177 if recipient not in had
178 ]
179 if not rows:
180 return 0
181 db.add_all(rows)
182 db.commit()
183 return len(rows)
184 except IntegrityError:
185 # Another process wrote it first: the recipient has it.
186 db.rollback()
187 return 0
188 except SQLAlchemyError:
189 db.rollback()
190 logger.exception("Could not write notification %s", message.dedupe_key)
191 return 0
194# ── Recipients ───────────────────────────────────────────────────────────────
197def _governs(row: Any) -> bool:
198 if membership_service.role_of(row) is membership_service.MemberRole.admin:
199 return True
200 return (
201 access_service.effective(row).get(access_service.AccessArea.governance)
202 is access_service.AccessLevel.editor
203 )
206def governors(db: Session, ws: Workspace | None) -> list[UUID]:
207 """Everyone who governs ``ws`` — as ``budgets.status.governs`` decides
208 it for one person: the owner of a Personal workspace; an admin or a
209 governance editor of an organisation; for a project, its own admins and
210 governance editors and those who are its admins by position (its
211 organisation's admins, or a personal project's owner)."""
212 if ws is None:
213 return []
214 if ws.kind is WorkspaceKind.personal:
215 return [ws.id]
216 scope = (
217 membership_service.ORGANISATION
218 if ws.kind is WorkspaceKind.organisation
219 else membership_service.PROJECT
220 )
221 found = [
222 user.id
223 for row, user, _role in membership_service.members(db, scope, ws.id)
224 if _governs(row)
225 ]
226 if ws.kind is WorkspaceKind.project:
227 project = db.get(Project, ws.id)
228 if project is not None:
229 found += [
230 user.id
231 for user, _via in membership_service.implicit_admins(db, project)
232 ]
233 return list(dict.fromkeys(found))
236# ── Reading ──────────────────────────────────────────────────────────────────
239def for_user(
240 db: Session, user_id: UUID, *, unread_only: bool = False, limit: int = 50
241) -> list[Notification]:
242 query = db.query(Notification).filter(Notification.recipient_user_id == user_id)
243 if unread_only:
244 query = query.filter(Notification.read_at.is_(None))
245 return query.order_by(Notification.created_at.desc()).limit(limit).all()
248def unread_count(db: Session, user_id: UUID) -> int:
249 return (
250 db.query(Notification)
251 .filter(
252 Notification.recipient_user_id == user_id,
253 Notification.read_at.is_(None),
254 )
255 .count()
256 )
259def mark_read(db: Session, user_id: UUID, notification_id: UUID | None = None) -> int:
260 """Mark one of ``user_id``'s notifications read, or all of them.
261 Another person's is not theirs to mark: it reads as not found."""
262 query = db.query(Notification).filter(
263 Notification.recipient_user_id == user_id,
264 Notification.read_at.is_(None),
265 )
266 if notification_id is not None:
267 query = query.filter(Notification.id == notification_id)
268 changed = query.update(
269 {Notification.read_at: aware_utcnow().replace(tzinfo=None)},
270 synchronize_session=False,
271 )
272 db.commit()
273 return int(changed or 0)
276def prune(db: Session, now: datetime | None = None) -> int:
277 """Delete read notifications past ``RETENTION_DAYS``, and unread ones
278 past ``UNREAD_RETENTION_DAYS``. Commits."""
279 now = (now or aware_utcnow()).replace(tzinfo=None)
280 deleted = (
281 db.query(Notification)
282 .filter(
283 (
284 and_(
285 Notification.read_at.isnot(None),
286 Notification.created_at < now - timedelta(days=RETENTION_DAYS),
287 )
288 )
289 | (Notification.created_at < now - timedelta(days=UNREAD_RETENTION_DAYS))
290 )
291 .delete(synchronize_session=False)
292 )
293 db.commit()
294 return int(deleted or 0)