Files
flowdeck/app/routers/notifications.py
T
bruno d4adf89db5
FlowDeck CI / lint (push) Successful in 49s
FlowDeck CI / test (push) Successful in 5m26s
FlowDeck CI / docker (push) Successful in 43s
feat(calendar): v5.8.0 calendrier & rappels + v5.7.0 database avancee (pt.2)
v5.8.0 (release 5.11.7) — Calendrier & Rappels :
- moteur de recurrence RRULE subset (daily/weekly/monthly, interval,
  count, until, byweekday, timezone) — app/services/recurrence.py
- vues calendar Jour / Semaine / Mois avec expansion des occurrences
  cote serveur (GET /db/{id}/calendar/api) et popover evenement
  (Time / Timezone / Repeat / Remind)
- rappels avant echeance (scan 60 s, table reminder_log, in-app +
  email, cible = personnes assignees) — app/services/reminders.py
- fuseaux horaires : users.timezone + reglages in-app, timezone par
  evenement, liste de zones (GET /db/timezones/api)
- notifications d'assignation sur PUT /db/pages/{id}/api et
  preferences etendues (reminders, assignments)
- template Meeting notes enrichi (Agenda, Notes — migration 12)
- migrations 11-12 ; 20 tests dedies ; suite complete 523 verte

v5.7.0 (release 5.11.6, termine avant cette session, reste dans
l'arbre sans commit) — Database Avancée Pt.2 :
- proprietes person + auto-proprietes (created/last-edited time & by)
- groupes de proprietes, vues sauvegardees par utilisateur
- swimlanes, WIP limits, cartes configurables, calendar drag & drop,
  gallery couvertures ; 12 tests dedies
2026-09-13 22:49:14 -04:00

153 lines
5.4 KiB
Python

"""FlowDeck — Notifications API (v4.9.0 collaboration)."""
from __future__ import annotations
import logging
from fastapi import APIRouter, HTTPException, Request
from app.auth.session import SessionManager
from app.db import get_conn
logger = logging.getLogger(__name__)
router = APIRouter(tags=["notifications"], prefix="/api/notifications")
def _current_user(request: Request) -> dict:
user = SessionManager.decode_session(request.cookies.get("flowdeck_session", ""))
if not user or not user.get("id"):
raise HTTPException(status_code=401, detail="Authentication required")
return user
@router.get("")
async def list_notifications(request: Request, limit: int = 50):
"""List the current user's notifications, newest first."""
user = _current_user(request)
with get_conn() as conn:
rows = conn.execute(
"""SELECT n.*, a.login AS actor_login, a.full_name AS actor_name,
a.avatar_url AS actor_avatar, a.avatar_color AS actor_color
FROM notifications n
LEFT JOIN users a ON n.actor_id = a.id
WHERE n.user_id=?
ORDER BY n.created_at DESC, n.id DESC LIMIT ?""",
(user["id"], limit),
).fetchall()
unread = conn.execute(
"SELECT COUNT(*) AS c FROM notifications WHERE user_id=? AND is_read=0",
(user["id"],),
).fetchone()["c"]
return {
"notifications": [dict(r) for r in rows],
"unread": unread,
}
@router.get("/unread-count")
async def unread_count(request: Request):
"""Unread count for the topbar badge."""
user = _current_user(request)
with get_conn() as conn:
c = conn.execute(
"SELECT COUNT(*) AS c FROM notifications WHERE user_id=? AND is_read=0",
(user["id"],),
).fetchone()["c"]
return {"unread": c}
@router.post("/read")
async def mark_read(request: Request):
"""Mark one notification as read (id) or all (id omitted)."""
user = _current_user(request)
body = await request.json() if request.headers.get("content-type") else {}
nid = body.get("id")
with get_conn() as conn:
if nid:
conn.execute(
"UPDATE notifications SET is_read=1 WHERE id=? AND user_id=?",
(nid, user["id"]),
)
else:
conn.execute(
"UPDATE notifications SET is_read=1 WHERE user_id=?",
(user["id"],),
)
conn.commit()
return {"status": "ok"}
@router.post("/read-all")
async def mark_all_read(request: Request):
"""Mark all notifications as read."""
return await mark_read(request)
@router.get("/prefs")
async def get_prefs(request: Request):
"""Return the current user's notification email preferences."""
user = _current_user(request)
from app.services import notifications as notif
return {"prefs": notif.get_user_prefs(user["id"])}
@router.post("/prefs")
async def set_prefs(request: Request):
"""Update the current user's notification email preferences."""
user = _current_user(request)
from app.services import notifications as notif
body = await request.json() if request.headers.get("content-type") else {}
prefs = notif.get_user_prefs(user["id"])
for key in ("comments", "mentions", "reminders", "assignments"):
if key in body:
prefs[key] = bool(body[key])
notif.set_user_prefs(user["id"], prefs)
return {"status": "ok", "prefs": prefs}
@router.get("/timezone")
async def get_timezone(request: Request):
"""Return the current user's IANA timezone ('' = UTC)."""
user = _current_user(request)
with get_conn() as conn:
row = conn.execute("SELECT timezone FROM users WHERE id=?", (user["id"],)).fetchone()
tz = (row["timezone"] if row and "timezone" in row.keys() else "") or ""
from app.services.recurrence import common_timezones
return {"timezone": tz, "zones": common_timezones()}
@router.post("/timezone")
async def set_timezone(request: Request):
"""Update the current user's IANA timezone (empty string = UTC)."""
user = _current_user(request)
body = await request.json() if request.headers.get("content-type") else {}
tz = (body.get("timezone") or "").strip()
from app.services.recurrence import is_valid_timezone
if tz and not is_valid_timezone(tz):
raise HTTPException(status_code=400, detail=f"Unknown timezone '{tz}'")
with get_conn() as conn:
conn.execute("UPDATE users SET timezone=? WHERE id=?", (tz, user["id"]))
conn.commit()
return {"status": "ok", "timezone": tz}
@router.get("/users/search")
async def search_users(request: Request, q: str = ""):
"""User autocomplete for @mentions."""
_current_user(request)
q = (q or "").strip()
with get_conn() as conn:
if q:
like = f"%{q}%"
rows = conn.execute(
"""SELECT id, login, full_name, avatar_url, avatar_color
FROM users WHERE login LIKE ? OR full_name LIKE ?
ORDER BY (login=? OR full_name=?) DESC, login LIMIT 20""",
(like, like, q, q),
).fetchall()
else:
rows = conn.execute(
"""SELECT id, login, full_name, avatar_url, avatar_color
FROM users ORDER BY login LIMIT 20"""
).fetchall()
return {"users": [dict(r) for r in rows]}