admin.nomadro.com gets sidebar L1/L2 social ops (paginated lists + entity detail); API adds soft-delete archives/stats and shared nomadro_pb for social/coffee/notify/work. Co-authored-by: Cursor <cursoragent@cursor.com>
1588 lines
55 KiB
Python
1588 lines
55 KiB
Python
"""
|
||
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",
|
||
# Timezone-aware quiet hours (HH:MM local)
|
||
"timezone": "Asia/Shanghai",
|
||
"quiet_start": "22:00",
|
||
"quiet_end": "08:00",
|
||
"digest_daily": True,
|
||
"digest_weekly": True,
|
||
}
|
||
|
||
|
||
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_onboarding_workflows(c)
|
||
_ensure_demo_feed(c)
|
||
|
||
|
||
def _ensure_onboarding_workflows(c: sqlite3.Connection) -> None:
|
||
"""Idempotent: city-recs workflow + welcome CTA → chat (existing DBs)."""
|
||
env_row = c.execute("SELECT id FROM environments LIMIT 1").fetchone()
|
||
if not env_row:
|
||
return
|
||
env = env_row["id"]
|
||
now = _now()
|
||
exists = c.execute(
|
||
"SELECT id FROM workflows WHERE workflow_id=?",
|
||
("city-recs-onboarding",),
|
||
).fetchone()
|
||
if not exists:
|
||
wf_city = _id("wf")
|
||
c.execute(
|
||
"""INSERT INTO workflows(id,env_id,workflow_id,name,description,active,tags_json,created_at,updated_at)
|
||
VALUES(?,?,?,?,?,?,?,?,?)""",
|
||
(
|
||
wf_city,
|
||
env,
|
||
"city-recs-onboarding",
|
||
"Same-city recommendations",
|
||
"Push 3 same-city people after join profile",
|
||
1,
|
||
_json(["onboarding", "social", "city"]),
|
||
now,
|
||
now,
|
||
),
|
||
)
|
||
c.execute(
|
||
"""INSERT INTO workflow_steps(id,workflow_pk,type,name,position,active,template_json,filters_json)
|
||
VALUES(?,?,?,?,?,?,?,?)""",
|
||
(
|
||
_id("step"),
|
||
wf_city,
|
||
"in_app",
|
||
"City recs",
|
||
0,
|
||
1,
|
||
_json(
|
||
{
|
||
"subject": "{{city}} · 同城推荐",
|
||
"body": "为你挑了几位同城游民:\n{{recsText}}",
|
||
"ctaLabel": "去认识他们",
|
||
"ctaUrl": "/social/people",
|
||
"category": "social",
|
||
}
|
||
),
|
||
"[]",
|
||
),
|
||
)
|
||
# Soft-update welcome in-app CTA toward chat if still pointing at /social/work
|
||
for row in c.execute(
|
||
"""SELECT ws.id, ws.template_json FROM workflow_steps ws
|
||
JOIN workflows w ON w.id=ws.workflow_pk
|
||
WHERE w.workflow_id='welcome-onboarding' AND ws.type='in_app'"""
|
||
).fetchall():
|
||
tpl = _parse(row["template_json"], {})
|
||
if tpl.get("ctaUrl") == "/social/work":
|
||
tpl["ctaUrl"] = "/social/chat"
|
||
tpl["ctaLabel"] = "进入群聊"
|
||
tpl["body"] = "嗨 {{firstName}}——先去群聊打个招呼,再看看同城推荐。"
|
||
tpl["category"] = "social"
|
||
c.execute(
|
||
"UPDATE workflow_steps SET template_json=? WHERE id=?",
|
||
(_json(tpl), row["id"]),
|
||
)
|
||
_ensure_social_engagement_workflows(c, env, now)
|
||
|
||
|
||
def _ensure_social_engagement_workflows(
|
||
c: sqlite3.Connection, env: str, now: str
|
||
) -> None:
|
||
"""Likes / coffee / board / city / room / report / digests — idempotent seeds."""
|
||
specs: list[tuple[str, str, str, dict[str, Any]]] = [
|
||
(
|
||
"social-like",
|
||
"Someone liked you",
|
||
"In-app when a nomad likes your profile",
|
||
{
|
||
"subject": "{{actor}} 喜欢了你",
|
||
"body": "去看看对方资料,决定要不要打招呼。",
|
||
"ctaLabel": "想见的人",
|
||
"ctaUrl": "/social/people",
|
||
"category": "social",
|
||
},
|
||
),
|
||
(
|
||
"coffee-invite",
|
||
"Coffeechat invite",
|
||
"Booking / invite for coffeechat",
|
||
{
|
||
"subject": "咖啡聊邀请 · {{title}}",
|
||
"body": "{{firstName}} 约你聊聊。",
|
||
"ctaLabel": "查看预约",
|
||
"ctaUrl": "/social/coffeechat",
|
||
"category": "social",
|
||
},
|
||
),
|
||
(
|
||
"board-join",
|
||
"Joined your board",
|
||
"Someone joined a work board you own",
|
||
{
|
||
"subject": "{{firstName}} 进了你的看板",
|
||
"body": "看板「{{title}}」有新成员。",
|
||
"ctaLabel": "打开看板",
|
||
"ctaUrl": "/social/work/boards",
|
||
"category": "project",
|
||
},
|
||
),
|
||
(
|
||
"city-online",
|
||
"Same-city online",
|
||
"A same-city nomad came online",
|
||
{
|
||
"subject": "{{city}} 有同城上线",
|
||
"body": "{{firstName}} 现在在线,想认识的话打个招呼。",
|
||
"ctaLabel": "去看看",
|
||
"ctaUrl": "/social/people",
|
||
"category": "social",
|
||
},
|
||
),
|
||
(
|
||
"room-live",
|
||
"Video room live",
|
||
"A meetup / video room started",
|
||
{
|
||
"subject": "视频厅开场 · {{title}}",
|
||
"body": "有厅正在开,一键加入。",
|
||
"ctaLabel": "进入视频厅",
|
||
"ctaUrl": "/social/meetup",
|
||
"category": "social",
|
||
},
|
||
),
|
||
(
|
||
"report-result",
|
||
"Report resolved",
|
||
"Moderation result for a user report",
|
||
{
|
||
"subject": "举报处理结果",
|
||
"body": "{{resultNote}}(状态:{{status}})",
|
||
"ctaLabel": "打开通知",
|
||
"ctaUrl": "/social/notifications",
|
||
"category": "system",
|
||
},
|
||
),
|
||
(
|
||
"city-digest-daily",
|
||
"Daily city digest",
|
||
"Same-city activity summary (daily)",
|
||
{
|
||
"subject": "{{city}} · 今日同城摘要",
|
||
"body": "{{digestText}}",
|
||
"ctaLabel": "去同城看看",
|
||
"ctaUrl": "/social/people",
|
||
"category": "social",
|
||
},
|
||
),
|
||
(
|
||
"city-digest-weekly",
|
||
"Weekly city digest",
|
||
"Same-city activity summary (weekly)",
|
||
{
|
||
"subject": "{{city}} · 本周同城摘要",
|
||
"body": "{{digestText}}",
|
||
"ctaLabel": "去同城看看",
|
||
"ctaUrl": "/social/people",
|
||
"category": "social",
|
||
},
|
||
),
|
||
]
|
||
for wid, name, desc, tpl in specs:
|
||
exists = c.execute(
|
||
"SELECT id FROM workflows WHERE workflow_id=?", (wid,)
|
||
).fetchone()
|
||
if exists:
|
||
continue
|
||
pk = _id("wf")
|
||
c.execute(
|
||
"""INSERT INTO workflows(id,env_id,workflow_id,name,description,active,tags_json,created_at,updated_at)
|
||
VALUES(?,?,?,?,?,?,?,?,?)""",
|
||
(
|
||
pk,
|
||
env,
|
||
wid,
|
||
name,
|
||
desc,
|
||
1,
|
||
_json(["social", "engagement"]),
|
||
now,
|
||
now,
|
||
),
|
||
)
|
||
c.execute(
|
||
"""INSERT INTO workflow_steps(id,workflow_pk,type,name,position,active,template_json,filters_json)
|
||
VALUES(?,?,?,?,?,?,?,?)""",
|
||
(_id("step"), pk, "in_app", "In-app", 0, 1, _json(tpl), "[]"),
|
||
)
|
||
|
||
|
||
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/chat",
|
||
"category": "social",
|
||
},
|
||
),
|
||
(
|
||
_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_city = "wf_city_recs"
|
||
c.execute(
|
||
"""INSERT INTO workflows(id,env_id,workflow_id,name,description,active,tags_json,created_at,updated_at)
|
||
VALUES(?,?,?,?,?,?,?,?,?)""",
|
||
(
|
||
wf_city,
|
||
env,
|
||
"city-recs-onboarding",
|
||
"Same-city recommendations",
|
||
"Push 3 same-city people after join profile",
|
||
1,
|
||
_json(["onboarding", "social", "city"]),
|
||
now,
|
||
now,
|
||
),
|
||
)
|
||
c.execute(
|
||
"""INSERT INTO workflow_steps(id,workflow_pk,type,name,position,active,template_json,filters_json)
|
||
VALUES(?,?,?,?,?,?,?,?)""",
|
||
(
|
||
_id("step"),
|
||
wf_city,
|
||
"in_app",
|
||
"City recs",
|
||
0,
|
||
1,
|
||
_json(
|
||
{
|
||
"subject": "{{city}} · 同城推荐",
|
||
"body": "为你挑了几位同城游民:\n{{recsText}}",
|
||
"ctaLabel": "去认识他们",
|
||
"ctaUrl": "/social/people",
|
||
"category": "social",
|
||
}
|
||
),
|
||
"[]",
|
||
),
|
||
)
|
||
|
||
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 or timezone quiet hours: mute external; inbox still receives in_app
|
||
quiet = False
|
||
try:
|
||
from datetime import datetime
|
||
from zoneinfo import ZoneInfo
|
||
|
||
qs = str(prefs.get("quiet_start") or "").strip()
|
||
qe = str(prefs.get("quiet_end") or "").strip()
|
||
if qs and qe:
|
||
tz = ZoneInfo(
|
||
str(prefs.get("timezone") or "Asia/Shanghai")
|
||
)
|
||
local = datetime.now(tz)
|
||
sh, sm = [int(x) for x in qs.split(":")[:2]]
|
||
eh, em = [int(x) for x in qe.split(":")[:2]]
|
||
cur = local.hour * 60 + local.minute
|
||
a, b = sh * 60 + sm, eh * 60 + em
|
||
quiet = (
|
||
(a < b and a <= cur < b)
|
||
or (a > b and (cur >= a or cur < b))
|
||
)
|
||
except Exception:
|
||
quiet = False
|
||
if (prefs.get("dnd") or quiet) and typ != "in_app":
|
||
status = "skipped_dnd" if prefs.get("dnd") else "skipped_quiet_hours"
|
||
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"
|
||
if prefs.get("dnd")
|
||
else "quiet_hours"
|
||
}
|
||
),
|
||
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,
|
||
}
|