nomadro/apps/api/services/notify_svc/store.py
Eric ffa456afdf Ship social join profile + SeaweedFS avatars, notify/coffee, and .com audience stack.
Pay-then-profile join desk with live card, S3 upload fallback, hydration-safe drafts; document on test9 README.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-04 02:25:05 +08:00

1313 lines
46 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
SQLite store — domain shaped after Novu
(Organization/Environment · Subscriber · Topic · Workflow · Event · Notification · Message).
Secondary-dev reimplementation for Nomadro (not upstream runtime / Docker Novu).
"""
from __future__ import annotations
import json
import sqlite3
import time
import uuid
from pathlib import Path
from typing import Any
from .config import DATA_DIR, DB_PATH
try:
from ebook_svc.core.sqlite_util import connect as _connect
except Exception: # pragma: no cover
def _connect(path: str | Path, *, timeout: float = 30.0) -> sqlite3.Connection:
p = Path(path)
p.parent.mkdir(parents=True, exist_ok=True)
c = sqlite3.connect(str(p), timeout=timeout)
c.row_factory = sqlite3.Row
c.execute("PRAGMA journal_mode=WAL")
return c
CHANNEL_STEPS = {"in_app", "email", "sms", "push", "chat"}
ACTION_STEPS = {"delay", "digest", "throttle"}
ALL_STEPS = CHANNEL_STEPS | ACTION_STEPS
CATEGORIES = ("social", "buddy", "project", "system")
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",
}
def _ensure_column(c: sqlite3.Connection, table: str, column: str, decl: str) -> None:
cols = {r[1] for r in c.execute(f"PRAGMA table_info({table})").fetchall()}
if column not in cols:
c.execute(f"ALTER TABLE {table} ADD COLUMN {column} {decl}")
def _now() -> str:
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
def _id(prefix: str) -> str:
return f"{prefix}_{uuid.uuid4().hex[:10]}"
def _conn() -> sqlite3.Connection:
DATA_DIR.mkdir(parents=True, exist_ok=True)
return _connect(DB_PATH)
def _row(r: sqlite3.Row | None) -> dict[str, Any] | None:
if r is None:
return None
return dict(r)
def _json(v: Any) -> str:
return json.dumps(v, ensure_ascii=False)
def _parse(s: str | None, default: Any = None) -> Any:
if not s:
return default if default is not None else {}
try:
return json.loads(s)
except Exception:
return default if default is not None else {}
def init_db() -> None:
with _conn() as c:
c.executescript(
"""
CREATE TABLE IF NOT EXISTS environments (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
slug TEXT NOT NULL UNIQUE,
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS subscribers (
id TEXT PRIMARY KEY,
env_id TEXT NOT NULL,
subscriber_id TEXT NOT NULL,
email TEXT,
phone TEXT,
first_name TEXT,
last_name TEXT,
avatar TEXT,
locale TEXT DEFAULT 'zh',
data_json TEXT NOT NULL DEFAULT '{}',
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
UNIQUE(env_id, subscriber_id),
FOREIGN KEY(env_id) REFERENCES environments(id)
);
CREATE TABLE IF NOT EXISTS topics (
id TEXT PRIMARY KEY,
env_id TEXT NOT NULL,
key TEXT NOT NULL,
name TEXT NOT NULL,
created_at TEXT NOT NULL,
UNIQUE(env_id, key),
FOREIGN KEY(env_id) REFERENCES environments(id)
);
CREATE TABLE IF NOT EXISTS topic_subscribers (
topic_id TEXT NOT NULL,
subscriber_pk TEXT NOT NULL,
PRIMARY KEY(topic_id, subscriber_pk),
FOREIGN KEY(topic_id) REFERENCES topics(id),
FOREIGN KEY(subscriber_pk) REFERENCES subscribers(id)
);
CREATE TABLE IF NOT EXISTS workflows (
id TEXT PRIMARY KEY,
env_id TEXT NOT NULL,
workflow_id TEXT NOT NULL,
name TEXT NOT NULL,
description TEXT NOT NULL DEFAULT '',
active INTEGER NOT NULL DEFAULT 1,
tags_json TEXT NOT NULL DEFAULT '[]',
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
UNIQUE(env_id, workflow_id),
FOREIGN KEY(env_id) REFERENCES environments(id)
);
CREATE TABLE IF NOT EXISTS workflow_steps (
id TEXT PRIMARY KEY,
workflow_pk TEXT NOT NULL,
type TEXT NOT NULL,
name TEXT NOT NULL DEFAULT '',
position REAL NOT NULL DEFAULT 0,
active INTEGER NOT NULL DEFAULT 1,
template_json TEXT NOT NULL DEFAULT '{}',
filters_json TEXT NOT NULL DEFAULT '[]',
FOREIGN KEY(workflow_pk) REFERENCES workflows(id)
);
CREATE TABLE IF NOT EXISTS integrations (
id TEXT PRIMARY KEY,
env_id TEXT NOT NULL,
channel TEXT NOT NULL,
provider TEXT NOT NULL,
active INTEGER NOT NULL DEFAULT 0,
credentials_json TEXT NOT NULL DEFAULT '{}',
created_at TEXT NOT NULL,
FOREIGN KEY(env_id) REFERENCES environments(id)
);
CREATE TABLE IF NOT EXISTS events (
id TEXT PRIMARY KEY,
env_id TEXT NOT NULL,
transaction_id TEXT NOT NULL,
workflow_pk TEXT NOT NULL,
payload_json TEXT NOT NULL DEFAULT '{}',
created_at TEXT NOT NULL,
FOREIGN KEY(env_id) REFERENCES environments(id),
FOREIGN KEY(workflow_pk) REFERENCES workflows(id)
);
CREATE TABLE IF NOT EXISTS notifications (
id TEXT PRIMARY KEY,
event_id TEXT NOT NULL,
subscriber_pk TEXT NOT NULL,
workflow_pk TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'completed',
created_at TEXT NOT NULL,
FOREIGN KEY(event_id) REFERENCES events(id),
FOREIGN KEY(subscriber_pk) REFERENCES subscribers(id),
FOREIGN KEY(workflow_pk) REFERENCES workflows(id)
);
CREATE TABLE IF NOT EXISTS jobs (
id TEXT PRIMARY KEY,
notification_id TEXT NOT NULL,
step_id TEXT NOT NULL,
channel TEXT NOT NULL,
status TEXT NOT NULL,
detail_json TEXT NOT NULL DEFAULT '{}',
created_at TEXT NOT NULL,
FOREIGN KEY(notification_id) REFERENCES notifications(id)
);
CREATE TABLE IF NOT EXISTS messages (
id TEXT PRIMARY KEY,
notification_id TEXT,
subscriber_pk TEXT NOT NULL,
channel TEXT NOT NULL DEFAULT 'in_app',
subject TEXT NOT NULL DEFAULT '',
body TEXT NOT NULL DEFAULT '',
cta_label TEXT,
cta_url TEXT,
payload_json TEXT NOT NULL DEFAULT '{}',
read INTEGER NOT NULL DEFAULT 0,
archived INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL,
FOREIGN KEY(subscriber_pk) REFERENCES subscribers(id)
);
CREATE TABLE IF NOT EXISTS preferences (
subscriber_pk TEXT PRIMARY KEY,
channels_json TEXT NOT NULL DEFAULT '{}',
updated_at TEXT NOT NULL,
FOREIGN KEY(subscriber_pk) REFERENCES subscribers(id)
);
"""
)
_ensure_column(c, "messages", "category", "TEXT NOT NULL DEFAULT 'system'")
_ensure_column(c, "messages", "deleted", "INTEGER NOT NULL DEFAULT 0")
_seed(c)
_ensure_demo_feed(c)
def _seed(c: sqlite3.Connection) -> None:
if c.execute("SELECT 1 FROM environments LIMIT 1").fetchone():
return
now = _now()
env = "env_prod"
c.execute(
"INSERT INTO environments(id,name,slug,created_at) VALUES(?,?,?,?)",
(env, "Production", "production", now),
)
subs = [
("sub_guest", "guest", "guest@nomadro.com", None, "Guest", "Nomad", "zh"),
("sub_alice", "alice", "alice@nomadro.com", "+8613800000001", "Alice", "Chen", "zh"),
("sub_bob", "bob", "bob@nomadro.com", None, "Bob", "Rivera", "en"),
]
for pk, sid, email, phone, fn, ln, loc in subs:
c.execute(
"""INSERT INTO subscribers(
id,env_id,subscriber_id,email,phone,first_name,last_name,avatar,locale,data_json,created_at,updated_at
) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)""",
(pk, env, sid, email, phone, fn, ln, None, loc, _json({"plan": "free"}), now, now),
)
c.execute(
"INSERT INTO preferences(subscriber_pk,channels_json,updated_at) VALUES(?,?,?)",
(pk, _json(_default_prefs()), now),
)
topic = "topic_nomads"
c.execute(
"INSERT INTO topics(id,env_id,key,name,created_at) VALUES(?,?,?,?,?)",
(topic, env, "nomads", "Nomadro Nomads", now),
)
for pk in ("sub_guest", "sub_alice", "sub_bob"):
c.execute(
"INSERT INTO topic_subscribers(topic_id,subscriber_pk) VALUES(?,?)",
(topic, pk),
)
wf_welcome = "wf_welcome"
c.execute(
"""INSERT INTO workflows(id,env_id,workflow_id,name,description,active,tags_json,created_at,updated_at)
VALUES(?,?,?,?,?,?,?,?,?)""",
(
wf_welcome,
env,
"welcome-onboarding",
"Welcome onboarding",
"In-app welcome + email stub when a nomad joins",
1,
_json(["onboarding", "product"]),
now,
now,
),
)
steps_welcome = [
(
_id("step"),
"in_app",
"In-app welcome",
0,
{
"subject": "欢迎加入 Nomadro",
"body": "嗨 {{firstName}}——打开收件箱,开始远程一起做事。",
"ctaLabel": "打开工作台",
"ctaUrl": "/social/work",
},
),
(
_id("step"),
"email",
"Welcome email",
1,
{
"subject": "Welcome to Nomadro, {{firstName}}",
"body": "Your remote stack is ready: work · social · notify.",
},
),
]
for sid, typ, name, pos, tpl in steps_welcome:
c.execute(
"""INSERT INTO workflow_steps(id,workflow_pk,type,name,position,active,template_json,filters_json)
VALUES(?,?,?,?,?,?,?,?)""",
(sid, wf_welcome, typ, name, pos, 1, _json(tpl), "[]"),
)
wf_meetup = "wf_meetup"
c.execute(
"""INSERT INTO workflows(id,env_id,workflow_id,name,description,active,tags_json,created_at,updated_at)
VALUES(?,?,?,?,?,?,?,?,?)""",
(
wf_meetup,
env,
"meetup-reminder",
"Meetup reminder",
"Delay stub then in-app reminder for city meetups",
1,
_json(["meetup", "social"]),
now,
now,
),
)
steps_meetup = [
(
_id("step"),
"delay",
"Wait window",
0,
{"amount": 15, "unit": "minutes"},
),
(
_id("step"),
"in_app",
"Meetup ping",
1,
{
"subject": "活动提醒 · {{city}}",
"body": "{{title}} 快开始了,别迟到。",
"ctaLabel": "查看活动",
"ctaUrl": "/social/meetup",
},
),
(
_id("step"),
"push",
"Push stub",
2,
{"title": "{{title}}", "body": "Starts soon in {{city}}"},
),
]
for sid, typ, name, pos, tpl in steps_meetup:
c.execute(
"""INSERT INTO workflow_steps(id,workflow_pk,type,name,position,active,template_json,filters_json)
VALUES(?,?,?,?,?,?,?,?)""",
(sid, wf_meetup, typ, name, pos, 1, _json(tpl), "[]"),
)
for channel, provider, active in (
("in_app", "nomadro-inbox", 1),
("email", "smtp-stub", 0),
("sms", "twilio-stub", 0),
("push", "web-push-stub", 0),
("chat", "slack-stub", 0),
):
c.execute(
"""INSERT INTO integrations(id,env_id,channel,provider,active,credentials_json,created_at)
VALUES(?,?,?,?,?,?,?)""",
(_id("int"), env, channel, provider, active, "{}", now),
)
# seed one inbox message for guest
nid = _id("ntf")
eid = _id("evt")
c.execute(
"""INSERT INTO events(id,env_id,transaction_id,workflow_pk,payload_json,created_at)
VALUES(?,?,?,?,?,?)""",
(eid, env, _id("tx"), wf_welcome, _json({"source": "seed"}), now),
)
c.execute(
"""INSERT INTO notifications(id,event_id,subscriber_pk,workflow_pk,status,created_at)
VALUES(?,?,?,?,?,?)""",
(nid, eid, "sub_guest", wf_welcome, "completed", now),
)
c.execute(
"""INSERT INTO messages(
id,notification_id,subscriber_pk,channel,subject,body,cta_label,cta_url,payload_json,read,archived,category,deleted,created_at
) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
(
_id("msg"),
nid,
"sub_guest",
"in_app",
"欢迎加入 Nomadro",
"嗨 Guest——打开收件箱,开始远程一起做事。",
"打开工作台",
"/social/work",
_json({"seed": True}),
0,
0,
"system",
0,
now,
),
)
def _ensure_demo_feed(c: sqlite3.Connection) -> None:
"""Fill guest inbox with categorized samples (idempotent by subject tag)."""
guest = c.execute(
"SELECT id FROM subscribers WHERE subscriber_id='guest'"
).fetchone()
if not guest:
return
pk = guest["id"]
now = _now()
samples = [
(
"social",
"Alice 想认识你",
"在成都 · 看看对方介绍,决定要不要聊聊。",
"查看资料",
"/social/people",
),
(
"buddy",
"有人找搭子:出海小工具",
"兼职 / 一起做点事 · 匹配你的技能标签。",
"去看看",
"/social/team",
),
(
"project",
"看板有新动态",
"Sprint board · 卡片「部署 Notify」已更新。",
"打开看板",
"/social/work/boards",
),
(
"system",
"安全提醒:确认登录设备",
"若非本人操作,请立刻修改密码并联系支持。",
"账号设置",
"/social/roster",
),
]
for cat, subject, body, cta, url in samples:
exists = c.execute(
"SELECT 1 FROM messages WHERE subscriber_pk=? AND subject=? LIMIT 1",
(pk, subject),
).fetchone()
if exists:
continue
c.execute(
"""INSERT INTO messages(
id,notification_id,subscriber_pk,channel,subject,body,cta_label,cta_url,
payload_json,read,archived,category,deleted,created_at
) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
(
_id("msg"),
None,
pk,
"in_app",
subject,
body,
cta,
url,
_json({"demo": True, "category": cat}),
0,
0,
cat,
0,
now,
),
)
def default_env_id(c: sqlite3.Connection | None = None) -> str:
own = c is None
if own:
c = _conn()
assert c is not None
row = c.execute("SELECT id FROM environments ORDER BY created_at LIMIT 1").fetchone()
if own:
c.close()
if not row:
raise RuntimeError("no_environment")
return str(row["id"])
# —— subscribers ——
def list_subscribers() -> list[dict[str, Any]]:
with _conn() as c:
rows = c.execute(
"SELECT * FROM subscribers ORDER BY created_at DESC"
).fetchall()
return [_subscriber_out(dict(r)) for r in rows]
def get_subscriber(subscriber_id: str) -> dict[str, Any] | None:
with _conn() as c:
r = c.execute(
"SELECT * FROM subscribers WHERE subscriber_id=? OR id=?",
(subscriber_id, subscriber_id),
).fetchone()
return _subscriber_out(dict(r)) if r else None
def upsert_subscriber(data: dict[str, Any]) -> dict[str, Any]:
sid = (data.get("subscriber_id") or "").strip()
if not sid:
raise ValueError("subscriber_id_required")
now = _now()
with _conn() as c:
env = default_env_id(c)
existing = c.execute(
"SELECT id FROM subscribers WHERE env_id=? AND subscriber_id=?",
(env, sid),
).fetchone()
payload = {
"email": data.get("email"),
"phone": data.get("phone"),
"first_name": data.get("first_name") or data.get("firstName"),
"last_name": data.get("last_name") or data.get("lastName"),
"avatar": data.get("avatar"),
"locale": data.get("locale") or "zh",
"data_json": _json(data.get("data") or {}),
}
if existing:
pk = existing["id"]
c.execute(
"""UPDATE subscribers SET email=?,phone=?,first_name=?,last_name=?,avatar=?,locale=?,data_json=?,updated_at=?
WHERE id=?""",
(
payload["email"],
payload["phone"],
payload["first_name"],
payload["last_name"],
payload["avatar"],
payload["locale"],
payload["data_json"],
now,
pk,
),
)
else:
pk = _id("sub")
c.execute(
"""INSERT INTO subscribers(
id,env_id,subscriber_id,email,phone,first_name,last_name,avatar,locale,data_json,created_at,updated_at
) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)""",
(
pk,
env,
sid,
payload["email"],
payload["phone"],
payload["first_name"],
payload["last_name"],
payload["avatar"],
payload["locale"],
payload["data_json"],
now,
now,
),
)
c.execute(
"INSERT INTO preferences(subscriber_pk,channels_json,updated_at) VALUES(?,?,?)",
(pk, _json(_default_prefs()), now),
)
row = c.execute("SELECT * FROM subscribers WHERE id=?", (pk,)).fetchone()
return _subscriber_out(dict(row))
def delete_subscriber(subscriber_id: str) -> bool:
with _conn() as c:
r = c.execute(
"SELECT id FROM subscribers WHERE subscriber_id=? OR id=?",
(subscriber_id, subscriber_id),
).fetchone()
if not r:
return False
pk = r["id"]
c.execute("DELETE FROM topic_subscribers WHERE subscriber_pk=?", (pk,))
c.execute("DELETE FROM preferences WHERE subscriber_pk=?", (pk,))
c.execute("DELETE FROM messages WHERE subscriber_pk=?", (pk,))
c.execute("DELETE FROM subscribers WHERE id=?", (pk,))
return True
def _subscriber_out(r: dict[str, Any]) -> dict[str, Any]:
return {
"id": r["id"],
"subscriber_id": r["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": _parse(r.get("data_json"), {}),
"created_at": r.get("created_at"),
"updated_at": r.get("updated_at"),
}
# —— topics ——
def list_topics() -> list[dict[str, Any]]:
with _conn() as c:
rows = c.execute("SELECT * FROM topics ORDER BY created_at DESC").fetchall()
out = []
for r in rows:
d = dict(r)
count = c.execute(
"SELECT COUNT(*) AS n FROM topic_subscribers WHERE topic_id=?",
(d["id"],),
).fetchone()["n"]
members = c.execute(
"""SELECT s.subscriber_id FROM topic_subscribers ts
JOIN subscribers s ON s.id=ts.subscriber_pk
WHERE ts.topic_id=? ORDER BY s.subscriber_id""",
(d["id"],),
).fetchall()
out.append(
{
"id": d["id"],
"key": d["key"],
"name": d["name"],
"subscriber_count": count,
"subscribers": [m["subscriber_id"] for m in members],
"created_at": d["created_at"],
}
)
return out
def create_topic(key: str, name: str) -> dict[str, Any]:
key = key.strip()
name = name.strip() or key
if not key:
raise ValueError("key_required")
now = _now()
with _conn() as c:
env = default_env_id(c)
pk = _id("topic")
try:
c.execute(
"INSERT INTO topics(id,env_id,key,name,created_at) VALUES(?,?,?,?,?)",
(pk, env, key, name, now),
)
except sqlite3.IntegrityError as e:
raise ValueError("topic_exists") from e
return {
"id": pk,
"key": key,
"name": name,
"subscriber_count": 0,
"subscribers": [],
"created_at": now,
}
def add_topic_subscriber(topic_key: str, subscriber_id: str) -> dict[str, Any]:
with _conn() as c:
t = c.execute(
"SELECT * FROM topics WHERE key=? OR id=?",
(topic_key, topic_key),
).fetchone()
s = c.execute(
"SELECT * FROM subscribers WHERE subscriber_id=? OR id=?",
(subscriber_id, subscriber_id),
).fetchone()
if not t or not s:
raise ValueError("not_found")
c.execute(
"INSERT OR IGNORE INTO topic_subscribers(topic_id,subscriber_pk) VALUES(?,?)",
(t["id"], s["id"]),
)
topics = [x for x in list_topics() if x["id"] == t["id"] or x["key"] == t["key"]]
return topics[0]
def remove_topic_subscriber(topic_key: str, subscriber_id: str) -> bool:
with _conn() as c:
t = c.execute(
"SELECT id FROM topics WHERE key=? OR id=?",
(topic_key, topic_key),
).fetchone()
s = c.execute(
"SELECT id FROM subscribers WHERE subscriber_id=? OR id=?",
(subscriber_id, subscriber_id),
).fetchone()
if not t or not s:
return False
c.execute(
"DELETE FROM topic_subscribers WHERE topic_id=? AND subscriber_pk=?",
(t["id"], s["id"]),
)
return True
# —— workflows ——
def _workflow_out(c: sqlite3.Connection, r: sqlite3.Row) -> dict[str, Any]:
d = dict(r)
steps = c.execute(
"""SELECT * FROM workflow_steps WHERE workflow_pk=? ORDER BY position ASC""",
(d["id"],),
).fetchall()
return {
"id": d["id"],
"workflow_id": d["workflow_id"],
"name": d["name"],
"description": d.get("description") or "",
"active": bool(d.get("active")),
"tags": _parse(d.get("tags_json"), []),
"created_at": d["created_at"],
"updated_at": d["updated_at"],
"steps": [
{
"id": s["id"],
"type": s["type"],
"name": s["name"],
"position": s["position"],
"active": bool(s["active"]),
"template": _parse(s["template_json"], {}),
"filters": _parse(s["filters_json"], []),
}
for s in steps
],
}
def list_workflows() -> list[dict[str, Any]]:
with _conn() as c:
rows = c.execute("SELECT * FROM workflows ORDER BY updated_at DESC").fetchall()
return [_workflow_out(c, r) for r in rows]
def get_workflow(workflow_id: str) -> dict[str, Any] | None:
with _conn() as c:
r = c.execute(
"SELECT * FROM workflows WHERE workflow_id=? OR id=?",
(workflow_id, workflow_id),
).fetchone()
return _workflow_out(c, r) if r else None
def create_workflow(
workflow_id: str,
name: str,
description: str = "",
steps: list[dict[str, Any]] | None = None,
tags: list[str] | None = None,
) -> dict[str, Any]:
workflow_id = workflow_id.strip()
name = name.strip()
if not workflow_id or not name:
raise ValueError("workflow_id_and_name_required")
now = _now()
with _conn() as c:
env = default_env_id(c)
pk = _id("wf")
try:
c.execute(
"""INSERT INTO workflows(id,env_id,workflow_id,name,description,active,tags_json,created_at,updated_at)
VALUES(?,?,?,?,?,?,?,?,?)""",
(pk, env, workflow_id, name, description, 1, _json(tags or []), now, now),
)
except sqlite3.IntegrityError as e:
raise ValueError("workflow_exists") from e
for i, step in enumerate(steps or [{"type": "in_app", "name": "In-app", "template": {}}]):
typ = step.get("type") or "in_app"
if typ not in ALL_STEPS:
typ = "in_app"
c.execute(
"""INSERT INTO workflow_steps(id,workflow_pk,type,name,position,active,template_json,filters_json)
VALUES(?,?,?,?,?,?,?,?)""",
(
_id("step"),
pk,
typ,
step.get("name") or typ,
float(step.get("position", i)),
1 if step.get("active", True) else 0,
_json(step.get("template") or {}),
_json(step.get("filters") or []),
),
)
r = c.execute("SELECT * FROM workflows WHERE id=?", (pk,)).fetchone()
return _workflow_out(c, r)
def update_workflow(workflow_id: str, patch: dict[str, Any]) -> dict[str, Any] | None:
with _conn() as c:
r = c.execute(
"SELECT * FROM workflows WHERE workflow_id=? OR id=?",
(workflow_id, workflow_id),
).fetchone()
if not r:
return None
pk = r["id"]
now = _now()
name = patch.get("name", r["name"])
description = patch.get("description", r["description"])
active = r["active"] if patch.get("active") is None else (1 if patch["active"] else 0)
tags = patch.get("tags")
tags_json = _json(tags) if tags is not None else r["tags_json"]
c.execute(
"""UPDATE workflows SET name=?,description=?,active=?,tags_json=?,updated_at=? WHERE id=?""",
(name, description, active, tags_json, now, pk),
)
if "steps" in patch and isinstance(patch["steps"], list):
c.execute("DELETE FROM workflow_steps WHERE workflow_pk=?", (pk,))
for i, step in enumerate(patch["steps"]):
typ = step.get("type") or "in_app"
if typ not in ALL_STEPS:
typ = "in_app"
c.execute(
"""INSERT INTO workflow_steps(id,workflow_pk,type,name,position,active,template_json,filters_json)
VALUES(?,?,?,?,?,?,?,?)""",
(
step.get("id") or _id("step"),
pk,
typ,
step.get("name") or typ,
float(step.get("position", i)),
1 if step.get("active", True) else 0,
_json(step.get("template") or {}),
_json(step.get("filters") or []),
),
)
row = c.execute("SELECT * FROM workflows WHERE id=?", (pk,)).fetchone()
return _workflow_out(c, row)
def delete_workflow(workflow_id: str) -> bool:
with _conn() as c:
r = c.execute(
"SELECT id FROM workflows WHERE workflow_id=? OR id=?",
(workflow_id, workflow_id),
).fetchone()
if not r:
return False
c.execute("DELETE FROM workflow_steps WHERE workflow_pk=?", (r["id"],))
c.execute("DELETE FROM workflows WHERE id=?", (r["id"],))
return True
# —— preferences / integrations / inbox ——
def _merge_prefs(raw: dict[str, Any] | None) -> dict[str, Any]:
out = _default_prefs()
if raw:
out.update(raw)
return out
def get_preferences(subscriber_id: str) -> dict[str, Any] | None:
with _conn() as c:
s = c.execute(
"SELECT id,subscriber_id FROM subscribers WHERE subscriber_id=? OR id=?",
(subscriber_id, subscriber_id),
).fetchone()
if not s:
return None
p = c.execute(
"SELECT * FROM preferences WHERE subscriber_pk=?", (s["id"],)
).fetchone()
prefs = _merge_prefs(_parse(p["channels_json"], {}) if p else {})
return {
"subscriber_id": s["subscriber_id"],
"channels": prefs,
"dnd": bool(prefs.get("dnd")),
"email_subscribe": bool(prefs.get("email_subscribe")),
"browser_push": bool(prefs.get("browser_push")),
"push_permission": prefs.get("push_permission") or "default",
"updated_at": p["updated_at"] if p else None,
}
def set_preferences(subscriber_id: str, channels: dict[str, Any]) -> dict[str, Any]:
with _conn() as c:
s = c.execute(
"SELECT id,subscriber_id FROM subscribers WHERE subscriber_id=? OR id=?",
(subscriber_id, subscriber_id),
).fetchone()
if not s:
raise ValueError("subscriber_not_found")
now = _now()
existing = c.execute(
"SELECT channels_json FROM preferences WHERE subscriber_pk=?",
(s["id"],),
).fetchone()
merged = _merge_prefs(_parse(existing["channels_json"], {}) if existing else {})
merged.update(channels or {})
c.execute(
"""INSERT INTO preferences(subscriber_pk,channels_json,updated_at) VALUES(?,?,?)
ON CONFLICT(subscriber_pk) DO UPDATE SET channels_json=excluded.channels_json,updated_at=excluded.updated_at""",
(s["id"], _json(merged), now),
)
return get_preferences(subscriber_id) # type: ignore[return-value]
def list_integrations() -> list[dict[str, Any]]:
with _conn() as c:
rows = c.execute(
"SELECT id,channel,provider,active,created_at FROM integrations ORDER BY channel"
).fetchall()
return [
{
"id": r["id"],
"channel": r["channel"],
"provider": r["provider"],
"active": bool(r["active"]),
"created_at": r["created_at"],
}
for r in rows
]
def list_inbox(
subscriber_id: str,
*,
include_archived: bool = False,
category: str | None = None,
include_deleted: bool = False,
) -> list[dict[str, Any]]:
with _conn() as c:
s = c.execute(
"SELECT id FROM subscribers WHERE subscriber_id=? OR id=?",
(subscriber_id, subscriber_id),
).fetchone()
if not s:
return []
q = "SELECT * FROM messages WHERE subscriber_pk=? AND channel='in_app'"
args: list[Any] = [s["id"]]
if not include_deleted:
q += " AND COALESCE(deleted,0)=0"
if not include_archived:
q += " AND archived=0"
if category and category in CATEGORIES:
q += " AND category=?"
args.append(category)
q += " ORDER BY created_at DESC"
rows = c.execute(q, args).fetchall()
return [_message_out(dict(r)) for r in rows]
def patch_message(message_id: str, patch: dict[str, Any]) -> dict[str, Any] | None:
with _conn() as c:
r = c.execute("SELECT * FROM messages WHERE id=?", (message_id,)).fetchone()
if not r:
return None
read = r["read"] if patch.get("read") is None else (1 if patch["read"] else 0)
archived = (
r["archived"] if patch.get("archived") is None else (1 if patch["archived"] else 0)
)
deleted = r["deleted"] if patch.get("deleted") is None else (1 if patch["deleted"] else 0)
c.execute(
"UPDATE messages SET read=?, archived=?, deleted=? WHERE id=?",
(read, archived, deleted, message_id),
)
row = c.execute("SELECT * FROM messages WHERE id=?", (message_id,)).fetchone()
return _message_out(dict(row))
def delete_message(message_id: str) -> bool:
m = patch_message(message_id, {"deleted": True})
return m is not None
def mark_all_read(subscriber_id: str, category: str | None = None) -> int:
with _conn() as c:
s = c.execute(
"SELECT id FROM subscribers WHERE subscriber_id=? OR id=?",
(subscriber_id, subscriber_id),
).fetchone()
if not s:
return 0
q = (
"UPDATE messages SET read=1 WHERE subscriber_pk=? AND channel='in_app' "
"AND COALESCE(deleted,0)=0 AND read=0"
)
args: list[Any] = [s["id"]]
if category and category in CATEGORIES:
q += " AND category=?"
args.append(category)
cur = c.execute(q, args)
return int(cur.rowcount or 0)
def unread_count(subscriber_id: str, category: str | None = None) -> int:
with _conn() as c:
s = c.execute(
"SELECT id FROM subscribers WHERE subscriber_id=? OR id=?",
(subscriber_id, subscriber_id),
).fetchone()
if not s:
return 0
q = (
"SELECT COUNT(*) AS n FROM messages WHERE subscriber_pk=? AND channel='in_app' "
"AND read=0 AND archived=0 AND COALESCE(deleted,0)=0"
)
args: list[Any] = [s["id"]]
if category and category in CATEGORIES:
q += " AND category=?"
args.append(category)
return int(c.execute(q, args).fetchone()["n"])
def unread_by_category(subscriber_id: str) -> dict[str, int]:
return {cat: unread_count(subscriber_id, cat) for cat in CATEGORIES}
def _message_out(r: dict[str, Any]) -> dict[str, Any]:
cat = r.get("category") or "system"
if cat not in CATEGORIES:
cat = "system"
href = r.get("cta_url") or ""
return {
"id": r["id"],
"notification_id": r.get("notification_id"),
"channel": r.get("channel") or "in_app",
"category": cat,
"subject": r.get("subject") or "",
"body": r.get("body") or "",
"cta_label": r.get("cta_label"),
"cta_url": href,
"href": href,
"payload": _parse(r.get("payload_json"), {}),
"read": bool(r.get("read")),
"archived": bool(r.get("archived")),
"deleted": bool(r.get("deleted")),
"created_at": r.get("created_at"),
}
def list_activity(limit: int = 50) -> list[dict[str, Any]]:
with _conn() as c:
rows = c.execute(
"""SELECT n.id,n.status,n.created_at,n.event_id,
s.subscriber_id,w.workflow_id,w.name AS workflow_name,
e.transaction_id,e.payload_json
FROM notifications n
JOIN subscribers s ON s.id=n.subscriber_pk
JOIN workflows w ON w.id=n.workflow_pk
JOIN events e ON e.id=n.event_id
ORDER BY n.created_at DESC LIMIT ?""",
(limit,),
).fetchall()
out = []
for r in rows:
jobs = c.execute(
"SELECT channel,status,detail_json,created_at FROM jobs WHERE notification_id=? ORDER BY created_at",
(r["id"],),
).fetchall()
out.append(
{
"id": r["id"],
"status": r["status"],
"created_at": r["created_at"],
"subscriber_id": r["subscriber_id"],
"workflow_id": r["workflow_id"],
"workflow_name": r["workflow_name"],
"transaction_id": r["transaction_id"],
"payload": _parse(r["payload_json"], {}),
"jobs": [
{
"channel": j["channel"],
"status": j["status"],
"detail": _parse(j["detail_json"], {}),
"created_at": j["created_at"],
}
for j in jobs
],
}
)
return out
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]:
payload = payload or {}
with _conn() as c:
env = default_env_id(c)
wf = c.execute(
"SELECT * FROM workflows WHERE workflow_id=? OR id=?",
(workflow_id, workflow_id),
).fetchone()
if not wf:
raise ValueError("workflow_not_found")
if not wf["active"]:
raise ValueError("workflow_inactive")
targets: list[sqlite3.Row] = []
if topic_key:
t = c.execute(
"SELECT id FROM topics WHERE key=? OR id=?",
(topic_key, topic_key),
).fetchone()
if not t:
raise ValueError("topic_not_found")
targets = list(
c.execute(
"""SELECT s.* FROM topic_subscribers ts
JOIN subscribers s ON s.id=ts.subscriber_pk
WHERE ts.topic_id=?""",
(t["id"],),
).fetchall()
)
elif subscriber_id:
s = c.execute(
"SELECT * FROM subscribers WHERE subscriber_id=? OR id=?",
(subscriber_id, subscriber_id),
).fetchone()
if not s:
raise ValueError("subscriber_not_found")
targets = [s]
else:
raise ValueError("subscriber_or_topic_required")
steps = c.execute(
"SELECT * FROM workflow_steps WHERE workflow_pk=? AND active=1 ORDER BY position",
(wf["id"],),
).fetchall()
now = _now()
tx = _id("tx")
eid = _id("evt")
c.execute(
"""INSERT INTO events(id,env_id,transaction_id,workflow_pk,payload_json,created_at)
VALUES(?,?,?,?,?,?)""",
(eid, env, tx, wf["id"], _json(payload), now),
)
notifications: list[dict[str, Any]] = []
for sub in targets:
prefs_row = c.execute(
"SELECT channels_json FROM preferences WHERE subscriber_pk=?",
(sub["id"],),
).fetchone()
prefs = _parse(prefs_row["channels_json"], {}) if prefs_row else {}
ctx = {
"firstName": sub["first_name"] or sub["subscriber_id"],
"lastName": sub["last_name"] or "",
"email": sub["email"] or "",
"subscriberId": sub["subscriber_id"],
**{k: v for k, v in payload.items() if isinstance(v, (str, int, float))},
}
nid = _id("ntf")
c.execute(
"""INSERT INTO notifications(id,event_id,subscriber_pk,workflow_pk,status,created_at)
VALUES(?,?,?,?,?,?)""",
(nid, eid, sub["id"], wf["id"], "completed", now),
)
job_outs = []
for step in steps:
typ = step["type"]
tpl = _parse(step["template_json"], {})
if typ in ACTION_STEPS:
status = "skipped_recorded"
detail = {"reason": f"{typ}_stub", "template": tpl}
c.execute(
"""INSERT INTO jobs(id,notification_id,step_id,channel,status,detail_json,created_at)
VALUES(?,?,?,?,?,?,?)""",
(_id("job"), nid, step["id"], typ, status, _json(detail), now),
)
job_outs.append({"channel": typ, "status": status})
continue
# channel preference gate
if prefs.get(typ) is False:
status = "skipped_preference"
c.execute(
"""INSERT INTO jobs(id,notification_id,step_id,channel,status,detail_json,created_at)
VALUES(?,?,?,?,?,?,?)""",
(
_id("job"),
nid,
step["id"],
typ,
status,
_json({"reason": "preference_off"}),
now,
),
)
job_outs.append({"channel": typ, "status": status})
continue
# DND: mute external channels; inbox still receives in_app
if prefs.get("dnd") and typ != "in_app":
status = "skipped_dnd"
c.execute(
"""INSERT INTO jobs(id,notification_id,step_id,channel,status,detail_json,created_at)
VALUES(?,?,?,?,?,?,?)""",
(
_id("job"),
nid,
step["id"],
typ,
status,
_json({"reason": "dnd"}),
now,
),
)
job_outs.append({"channel": typ, "status": status})
continue
if typ == "email" and prefs.get("email_subscribe") is False:
status = "skipped_preference"
c.execute(
"""INSERT INTO jobs(id,notification_id,step_id,channel,status,detail_json,created_at)
VALUES(?,?,?,?,?,?,?)""",
(
_id("job"),
nid,
step["id"],
typ,
status,
_json({"reason": "email_subscribe_off"}),
now,
),
)
job_outs.append({"channel": typ, "status": status})
continue
if typ == "in_app":
subject = _render(tpl.get("subject") or tpl.get("title") or "", ctx)
body = _render(tpl.get("body") or tpl.get("content") or "", ctx)
cat = (
tpl.get("category")
or payload.get("category")
or "system"
)
if cat not in CATEGORIES:
cat = "system"
mid = _id("msg")
c.execute(
"""INSERT INTO messages(
id,notification_id,subscriber_pk,channel,subject,body,cta_label,cta_url,
payload_json,read,archived,category,deleted,created_at
) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
(
mid,
nid,
sub["id"],
"in_app",
subject,
body,
tpl.get("ctaLabel") or tpl.get("cta_label"),
tpl.get("ctaUrl") or tpl.get("cta_url"),
_json(payload),
0,
0,
cat,
0,
now,
),
)
status = "delivered"
detail = {"message_id": mid, "category": cat}
else:
# external channels: record intent only (stub providers)
status = "queued_stub"
detail = {
"provider": f"{typ}-stub",
"rendered": {
"subject": _render(tpl.get("subject") or tpl.get("title") or "", ctx),
"body": _render(tpl.get("body") or "", ctx),
},
}
c.execute(
"""INSERT INTO jobs(id,notification_id,step_id,channel,status,detail_json,created_at)
VALUES(?,?,?,?,?,?,?)""",
(_id("job"), nid, step["id"], typ, status, _json(detail), now),
)
job_outs.append({"channel": typ, "status": status})
notifications.append(
{
"id": nid,
"subscriber_id": sub["subscriber_id"],
"jobs": job_outs,
}
)
return {
"transaction_id": tx,
"event_id": eid,
"workflow_id": wf["workflow_id"],
"notifications": notifications,
}