"""Create an in-app notification and push it. Used by every module that produces a notification. The inbox row is written in the caller's transaction (deduplicated by recipient + event_key, so a retried request never creates a second one). The push is best effort and honours the recipient's preference flag. Push data carries notification_id, kind and target_json; review/session pushes keep the legacy type=review.received + session_id keys so older app builds still route them. """ import json import logging from uuid import UUID from sqlalchemy import delete, select from sqlalchemy.dialects.postgresql import insert from sqlalchemy.ext.asyncio import AsyncSession from app.integrations.push import PushClient from app.modules.devices.models import Device from app.modules.notifications.models import Notification from app.modules.settings.models import UserSettings log = logging.getLogger(__name__) # kind -> the user_settings flag that turns its push off PREFERENCE = {"review": "notify_coach", "drill": "notify_drills", "armcare": "notify_coach", "result": "notify_results", "report": "notify_weekly"} async def notify(db: AsyncSession, push: PushClient | None, recipient_id: UUID, *, kind: str, title: str, body: str = "", target: dict | None = None, event_key: str) -> UUID | None: """Returns the notification id, or None when this event was already delivered to this recipient.""" target = {k: str(v) for k, v in (target or {}).items()} notification_id = await db.scalar( insert(Notification).values(recipient_id=recipient_id, kind=kind, title=title[:120], body=body[:300], target=target, event_key=event_key[:160]) .on_conflict_do_nothing(index_elements=["recipient_id", "event_key"]).returning(Notification.id)) if notification_id is None or push is None: return notification_id flag = PREFERENCE.get(kind) if flag and await db.scalar(select(getattr(UserSettings, flag)).where(UserSettings.account_id == recipient_id)) \ is False: return notification_id tokens = list((await db.scalars(select(Device.push_token).where(Device.account_id == recipient_id))).all()) if not tokens: return notification_id data = {"notification_id": str(notification_id), "kind": kind, "target_json": json.dumps(target)} if kind == "review" and "session_id" in target: data.update(type="review.received", session_id=target["session_id"]) try: dead = await push.send(tokens, data, notification={"title": title, "body": body}) except Exception: # a push failure must never fail the request log.exception("push: %s failed", kind) return notification_id if dead: await db.execute(delete(Device).where(Device.push_token.in_(dead))) return notification_id