"""Notify service on PocketBase (Novu-domain subset, online-first).""" from __future__ import annotations import time import uuid from typing import Any from nomadro_pb import ensure_once, get_pb, pb_quote C_SUB = "notify_subscribers" C_TOPICS = "notify_topics" C_WF = "notify_workflows" C_PREFS = "notify_preferences" C_MSG = "notify_messages" C_ACT = "notify_activity" C_INT = "notify_integrations" def _now() -> str: return time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime()) def _id(prefix: str) -> str: return f"{prefix}_{uuid.uuid4().hex[:12]}" def _default_prefs() -> dict[str, Any]: return { "in_app": True, "email": True, "sms": False, "push": True, "chat": False, "dnd": False, "email_subscribe": True, "browser_push": False, "push_permission": "default", "timezone": "Asia/Shanghai", "quiet_start": "22:00", "quiet_end": "08:00", "digest_daily": True, "digest_weekly": True, } def init_db() -> None: ensure_once() _seed_workflows() def _seed_workflows() -> None: specs = [ ("social-like", "Someone liked you", "{{actor}} 喜欢了你", "去看看对方资料。"), ("coffee-invite", "Coffeechat invite", "咖啡聊邀请 · {{title}}", "{{firstName}} 约你聊聊。"), ("board-join", "Joined your board", "{{firstName}} 进了你的看板", "看板「{{title}}」有新成员。"), ("city-online", "Same-city online", "{{city}} 有同城上线", "{{firstName}} 现在在线。"), ("room-live", "Video room live", "视频厅开场 · {{title}}", "有厅正在开。"), ("report-result", "Report resolved", "举报处理结果", "{{resultNote}}"), ("city-digest-daily", "Daily city digest", "{{city}} · 今日同城摘要", "{{digestText}}"), ("city-digest-weekly", "Weekly city digest", "{{city}} · 本周同城摘要", "{{digestText}}"), ("welcome", "Welcome", "欢迎加入 Nomadro", "去完善介绍,认识同城的人。"), ] pb = get_pb() now = _now() for wid, name, subject, body in specs: if pb.first(C_WF, filter=f"workflow_id={pb_quote(wid)}"): continue pb.create( C_WF, { "workflow_id": wid, "name": name, "description": name, "active": True, "tags": ["social"], "steps": [ { "id": _id("step"), "type": "in_app", "name": "In-app", "position": 0, "active": True, "template": { "subject": subject, "body": body, "ctaLabel": "打开", "ctaUrl": "/social/notifications", "category": "social", }, "filters": [], } ], "created_at": now, "updated_at": now, }, ) def upsert_subscriber(data: dict[str, Any]) -> dict[str, Any]: init_db() sid = str(data.get("subscriber_id") or "").strip() if not sid: raise ValueError("subscriber_id required") now = _now() body = { "subscriber_id": sid, "email": data.get("email"), "phone": data.get("phone"), "first_name": data.get("first_name") or data.get("firstName"), "last_name": data.get("last_name"), "avatar": data.get("avatar"), "locale": data.get("locale") or "zh", "data": data.get("data") or {}, "updated_at": now, } existing = get_pb().first(C_SUB, filter=f"subscriber_id={pb_quote(sid)}") if existing: get_pb().update(C_SUB, existing["id"], body) else: body["created_at"] = now get_pb().create(C_SUB, body) return get_subscriber(sid) # type: ignore[return-value] def get_subscriber(subscriber_id: str) -> dict[str, Any] | None: init_db() r = get_pb().first(C_SUB, filter=f"subscriber_id={pb_quote(subscriber_id)}") if not r: return None return { "id": r.get("id"), "subscriber_id": r.get("subscriber_id"), "email": r.get("email"), "phone": r.get("phone"), "first_name": r.get("first_name"), "last_name": r.get("last_name"), "avatar": r.get("avatar"), "locale": r.get("locale") or "zh", "data": r.get("data") or {}, "created_at": r.get("created_at"), "updated_at": r.get("updated_at"), } def list_subscribers() -> list[dict[str, Any]]: init_db() return [get_subscriber(r["subscriber_id"]) for r in get_pb().list_all(C_SUB)] # type: ignore def delete_subscriber(subscriber_id: str) -> bool: r = get_pb().first(C_SUB, filter=f"subscriber_id={pb_quote(subscriber_id)}") if not r: return False get_pb().delete(C_SUB, r["id"]) return True def get_preferences(subscriber_id: str) -> dict[str, Any] | None: init_db() upsert_subscriber({"subscriber_id": subscriber_id}) r = get_pb().first(C_PREFS, filter=f"subscriber_id={pb_quote(subscriber_id)}") channels = _default_prefs() if r and isinstance(r.get("channels"), dict): channels.update(r["channels"]) return { "subscriber_id": subscriber_id, "channels": channels, "dnd": bool(channels.get("dnd")), "email_subscribe": bool(channels.get("email_subscribe", True)), "browser_push": bool(channels.get("browser_push")), "push_permission": channels.get("push_permission") or "default", "updated_at": (r or {}).get("updated_at"), } def set_preferences(subscriber_id: str, channels: dict[str, Any]) -> dict[str, Any]: init_db() upsert_subscriber({"subscriber_id": subscriber_id}) cur = get_preferences(subscriber_id) or {} merged = {**(cur.get("channels") or {}), **(channels or {})} get_pb().upsert( C_PREFS, filter=f"subscriber_id={pb_quote(subscriber_id)}", payload={ "subscriber_id": subscriber_id, "channels": merged, "updated_at": _now(), }, ) return get_preferences(subscriber_id) # type: ignore[return-value] def list_workflows() -> list[dict[str, Any]]: init_db() rows = get_pb().list_all(C_WF, sort="name") return [ { "id": r.get("id"), "workflow_id": r.get("workflow_id"), "name": r.get("name"), "description": r.get("description") or "", "active": bool(r.get("active", True)), "tags": r.get("tags") or [], "created_at": r.get("created_at"), "updated_at": r.get("updated_at"), "steps": r.get("steps") or [], } for r in rows ] def get_workflow(workflow_id: str) -> dict[str, Any] | None: init_db() r = get_pb().first(C_WF, filter=f"workflow_id={pb_quote(workflow_id)}") if not r: return None return { "id": r.get("id"), "workflow_id": r.get("workflow_id"), "name": r.get("name"), "description": r.get("description") or "", "active": bool(r.get("active", True)), "tags": r.get("tags") or [], "created_at": r.get("created_at"), "updated_at": r.get("updated_at"), "steps": r.get("steps") or [], } def create_workflow(**kwargs: Any) -> dict[str, Any]: init_db() wid = str(kwargs.get("workflow_id") or _id("wf")) now = _now() get_pb().create( C_WF, { "workflow_id": wid, "name": kwargs.get("name") or wid, "description": kwargs.get("description") or "", "active": bool(kwargs.get("active", True)), "tags": kwargs.get("tags") or [], "steps": kwargs.get("steps") or [], "created_at": now, "updated_at": now, }, ) return get_workflow(wid) # type: ignore[return-value] def update_workflow(workflow_id: str, patch: dict[str, Any]) -> dict[str, Any] | None: r = get_pb().first(C_WF, filter=f"workflow_id={pb_quote(workflow_id)}") if not r: return None body = {**patch, "updated_at": _now()} get_pb().update(C_WF, r["id"], body) return get_workflow(workflow_id) def delete_workflow(workflow_id: str) -> bool: r = get_pb().first(C_WF, filter=f"workflow_id={pb_quote(workflow_id)}") if not r: return False get_pb().delete(C_WF, r["id"]) return True def list_topics() -> list[dict[str, Any]]: init_db() rows = get_pb().list_all(C_TOPICS) return [ { "id": r.get("id"), "key": r.get("key"), "name": r.get("name"), "subscriber_count": len(r.get("subscribers") or []), "subscribers": r.get("subscribers") or [], "created_at": r.get("created_at"), } for r in rows ] def create_topic(key: str, name: str) -> dict[str, Any]: init_db() get_pb().upsert( C_TOPICS, filter=f"key={pb_quote(key)}", payload={ "key": key, "name": name, "subscribers": [], "created_at": _now(), }, ) return next(t for t in list_topics() if t["key"] == key) def add_topic_subscriber(topic_key: str, subscriber_id: str) -> dict[str, Any]: r = get_pb().first(C_TOPICS, filter=f"key={pb_quote(topic_key)}") if not r: raise ValueError("topic_not_found") subs = list(r.get("subscribers") or []) if subscriber_id not in subs: subs.append(subscriber_id) get_pb().update(C_TOPICS, r["id"], {"subscribers": subs}) return next(t for t in list_topics() if t["key"] == topic_key) def remove_topic_subscriber(topic_key: str, subscriber_id: str) -> bool: r = get_pb().first(C_TOPICS, filter=f"key={pb_quote(topic_key)}") if not r: return False subs = [s for s in (r.get("subscribers") or []) if s != subscriber_id] get_pb().update(C_TOPICS, r["id"], {"subscribers": subs}) return True def list_integrations() -> list[dict[str, Any]]: init_db() rows = get_pb().list_all(C_INT) return [ { "id": r.get("id"), "channel": r.get("channel"), "provider": r.get("provider"), "active": bool(r.get("active", True)), "created_at": r.get("created_at"), } for r in rows ] def list_inbox( subscriber_id: str, *, category: str | None = None, limit: int = 50, ) -> list[dict[str, Any]]: init_db() rows = get_pb().list_all( C_MSG, filter=f"subscriber_id={pb_quote(subscriber_id)}", sort="-created_at", hard_limit=limit, ) out = [] for r in rows: if r.get("deleted"): continue if category and r.get("category") != category: continue out.append(_message_out(r)) return out def _message_out(r: dict[str, Any]) -> dict[str, Any]: return { "id": r.get("id"), "notification_id": r.get("notification_id"), "channel": r.get("channel") or "in_app", "category": r.get("category") or "social", "subject": r.get("subject") or "", "body": r.get("body") or "", "cta_label": r.get("cta_label"), "cta_url": r.get("cta_url"), "href": r.get("href") or r.get("cta_url"), "payload": r.get("payload") or {}, "read": bool(r.get("read")), "archived": bool(r.get("archived")), "deleted": bool(r.get("deleted")), "created_at": r.get("created_at"), } def patch_message(message_id: str, patch: dict[str, Any]) -> dict[str, Any] | None: try: get_pb().update(C_MSG, message_id, patch) except Exception: return None try: r = get_pb().request( "GET", f"/api/collections/{C_MSG}/records/{message_id}", admin=True ) except Exception: return None return _message_out(r) def delete_message(message_id: str) -> bool: try: get_pb().update(C_MSG, message_id, {"deleted": True}) return True except Exception: return False def mark_all_read(subscriber_id: str, category: str | None = None) -> int: n = 0 for m in list_inbox(subscriber_id, category=category, limit=200): if not m.get("read"): patch_message(m["id"], {"read": True}) n += 1 return n def unread_count(subscriber_id: str, category: str | None = None) -> int: return sum( 1 for m in list_inbox(subscriber_id, category=category, limit=200) if not m.get("read") ) def unread_by_category(subscriber_id: str) -> dict[str, int]: counts: dict[str, int] = {} for m in list_inbox(subscriber_id, limit=200): if m.get("read"): continue cat = m.get("category") or "social" counts[cat] = counts.get(cat, 0) + 1 return counts def list_activity(limit: int = 50) -> list[dict[str, Any]]: init_db() rows = get_pb().list_all(C_ACT, sort="-created_at", hard_limit=limit) return [ { "id": r.get("id"), "status": r.get("status"), "created_at": r.get("created_at"), "subscriber_id": r.get("subscriber_id"), "workflow_id": r.get("workflow_id"), "workflow_name": r.get("workflow_name"), "transaction_id": r.get("transaction_id"), "payload": r.get("payload") or {}, "jobs": r.get("jobs") or [], } for r in rows ] def _render(tpl: str, ctx: dict[str, Any]) -> str: out = tpl or "" for k, v in ctx.items(): out = out.replace("{{" + k + "}}", str(v if v is not None else "")) return out def trigger_event( *, workflow_id: str, subscriber_id: str | None = None, topic_key: str | None = None, payload: dict[str, Any] | None = None, ) -> dict[str, Any]: init_db() payload = dict(payload or {}) targets: list[str] = [] if subscriber_id: targets.append(subscriber_id) if topic_key: t = get_pb().first(C_TOPICS, filter=f"key={pb_quote(topic_key)}") if t: targets.extend(t.get("subscribers") or []) if not targets: raise ValueError("subscriber_id or topic_key required") wf = get_workflow(workflow_id) if not wf or not wf.get("active"): raise ValueError("workflow_not_found") outs = [] for sid in targets: upsert_subscriber({"subscriber_id": sid, "first_name": payload.get("firstName")}) prefs = get_preferences(sid) or {} channels = prefs.get("channels") or {} # quiet / dnd: still write in_app steps = wf.get("steps") or [] jobs = [] nid = _id("ntf") for step in steps: if not step.get("active", True): continue typ = step.get("type") or "in_app" tpl = (step.get("template") or {}) if isinstance(step.get("template"), dict) else {} subject = _render(str(tpl.get("subject") or ""), payload) body = _render(str(tpl.get("body") or ""), payload) status = "sent" if typ != "in_app" and (channels.get("dnd") or payload.get("quietHours")): status = "skipped_dnd" else: get_pb().create( C_MSG, { "subscriber_id": sid, "notification_id": nid, "channel": typ, "category": payload.get("category") or tpl.get("category") or "social", "subject": subject, "body": body, "cta_label": tpl.get("ctaLabel"), "cta_url": payload.get("ctaUrl") or tpl.get("ctaUrl"), "href": payload.get("ctaUrl") or tpl.get("ctaUrl"), "payload": payload, "read": False, "archived": False, "deleted": False, "created_at": _now(), }, ) jobs.append({"channel": typ, "status": status}) get_pb().create( C_ACT, { "status": "completed", "subscriber_id": sid, "workflow_id": workflow_id, "workflow_name": wf.get("name"), "transaction_id": nid, "payload": payload, "jobs": jobs, "created_at": _now(), }, ) outs.append({"subscriber_id": sid, "notification_id": nid, "jobs": jobs}) return {"ok": True, "results": outs} def default_env_id(*_a: Any, **_k: Any) -> str: return "default"