diff --git a/apps/admin/deploy/_deploy_admin_com_us.py b/apps/admin/deploy/_deploy_admin_com_us.py new file mode 100644 index 0000000..89fde67 --- /dev/null +++ b/apps/admin/deploy/_deploy_admin_com_us.py @@ -0,0 +1,104 @@ +# -*- coding: utf-8 -*- +"""Build apps/com/admin and deploy static dist to admin.nomadro.com (US VPS).""" +from __future__ import annotations + +import io +import subprocess +import tarfile +import time +from pathlib import Path + +import paramiko + +US = ("108.174.50.68", "root", "Xiao4669805") +ROOT = Path(__file__).resolve().parents[3] +ADMIN_COM = ROOT / "apps" / "com" / "admin" +REMOTE_ROOT = "/www/wwwroot/admin.nomadro.com" + + +def build() -> Path: + subprocess.run( + ["pnpm", "--filter", "@nomadro/admin-com", "build"], + cwd=str(ROOT), + check=True, + shell=True, + ) + dist = ADMIN_COM / "dist" + if not dist.is_dir(): + raise SystemExit("dist missing") + return dist + + +def pack(dist: Path) -> bytes: + buf = io.BytesIO() + with tarfile.open(fileobj=buf, mode="w:gz") as tar: + for p in dist.rglob("*"): + if p.is_file(): + tar.add(p, arcname=p.relative_to(dist).as_posix()) + return buf.getvalue() + + +def main() -> int: + print("=== build ===", flush=True) + dist = build() + blob = pack(dist) + print("pack", len(blob), "bytes", flush=True) + + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + host, user, password = US + c.connect(host, 22, user, password, timeout=40, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/admin-com.tgz", "wb") as f: + f.write(blob) + sftp.close() + + remote = rf""" +set -euo pipefail +mkdir -p {REMOTE_ROOT} +ts=$(date +%Y%m%d%H%M%S) +if [ -d {REMOTE_ROOT} ] && [ "$(ls -A {REMOTE_ROOT} 2>/dev/null)" ]; then + mkdir -p /www/wwwroot/_bak_admin_com + tar -C {REMOTE_ROOT} -czf /www/wwwroot/_bak_admin_com/admin-$ts.tgz . || true +fi +rm -rf {REMOTE_ROOT}.new +mkdir -p {REMOTE_ROOT}.new +tar -xzf /tmp/admin-com.tgz -C {REMOTE_ROOT}.new +# atomic swap +rm -rf {REMOTE_ROOT}.old +mv {REMOTE_ROOT} {REMOTE_ROOT}.old 2>/dev/null || true +mv {REMOTE_ROOT}.new {REMOTE_ROOT} +rm -rf {REMOTE_ROOT}.old +# spa fallback already in nginx; smoke +curl -sk -o /dev/null -w "admin_home %{{http_code}}\n" https://admin.nomadro.com/ +curl -sk https://admin.nomadro.com/ | tr '\n' ' ' | grep -o 'Nomadro' | head -1 || true +# keep API up +systemctl is-active nomadmini-api +curl -sS -o /tmp/login.json -w "login %{{http_code}}\n" --max-time 10 -X POST https://api.nomadro.com/api/admin/login \ + -H 'content-type: application/json' \ + -d '{{"username":"hackrobot","password":"Xiao4669805@"}}' +head -c 120 /tmp/login.json; echo +echo DEPLOY_ADMIN_COM_OK +""" + chan = c.get_transport().open_session() + chan.settimeout(180) + chan.get_pty() + chan.exec_command(remote) + buf = [] + end = time.time() + 180 + while time.time() < end: + if chan.recv_ready(): + buf.append(chan.recv(65536).decode("utf-8", "replace")) + if chan.exit_status_ready(): + while chan.recv_ready(): + buf.append(chan.recv(65536).decode("utf-8", "replace")) + break + time.sleep(0.05) + print("".join(buf)[-5000:], flush=True) + code = chan.recv_exit_status() + c.close() + return code + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/apps/admin/deploy/_push_social_ugc_admin_us.py b/apps/admin/deploy/_push_social_ugc_admin_us.py new file mode 100644 index 0000000..26aa65e --- /dev/null +++ b/apps/admin/deploy/_push_social_ugc_admin_us.py @@ -0,0 +1,186 @@ +# -*- coding: utf-8 -*- +"""Push PocketBase social_ugc admin stack to US nomadmini-api + social_svc. + +admin.nomadro.com Social page needs: + GET /api/admin/social/ugc/{stats,archives,detail/...} +and soft-delete via social_svc.pb_data → PocketBase. +""" +from __future__ import annotations + +import io +import sys +import tarfile +import time +from pathlib import Path + +import paramiko + +sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True) + +ROOT = Path(__file__).resolve().parents[3] +US = ("108.174.50.68", "root", "Xiao4669805") +REMOTE_APP = "/opt/nomadmini/backend/app" +REMOTE_API = "/var/www/nomadro.cn/apps/api" +REMOTE_BACKEND = "/opt/nomadmini/backend" + +LOCAL_UGC = ROOT / "apps/api/services/ebook_svc/services/social_ugc.py" +LOCAL_ADMIN = ROOT / "apps/api/services/ebook_svc/routers/social_ugc_admin.py" +LOCAL_SVC = ROOT / "apps/api/services/social_svc" +LOCAL_PB = ROOT / "apps/api/services/nomadro_pb" + + +def to_app(text: str) -> str: + return text.replace("ebook_svc.", "app.") + + +def connect() -> paramiko.SSHClient: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + h, u, p = US + c.connect(h, 22, u, p, timeout=45, allow_agent=False, look_for_keys=False, banner_timeout=90) + t = c.get_transport() + if t: + t.set_keepalive(15) + return c + + +def sh(c: paramiko.SSHClient, cmd: str, timeout: int = 240) -> tuple[int, str]: + print(f"$ {cmd[:240].replace(chr(10), ' ')}", flush=True) + _, o, e = c.exec_command(cmd, timeout=timeout) + out = o.read().decode("utf-8", "replace") + err = e.read().decode("utf-8", "replace") + code = o.channel.recv_exit_status() + text = out + (("\n" + err) if err.strip() else "") + if text.strip(): + print(text[-8000:], flush=True) + print("exit", code, flush=True) + return code, text + + +def pack() -> bytes: + buf = io.BytesIO() + with tarfile.open(fileobj=buf, mode="w:gz") as tar: + for src, name in ( + (LOCAL_UGC, "api/services/social_ugc.py"), + (LOCAL_ADMIN, "api/routers/social_ugc_admin.py"), + ): + if not src.is_file(): + raise SystemExit(f"missing {src}") + text = to_app(src.read_text(encoding="utf-8")) + if "ebook_svc." in text: + raise SystemExit(f"rewrite failed: {src}") + data = text.encode("utf-8") + info = tarfile.TarInfo(name=name) + info.size = len(data) + tar.addfile(info, io.BytesIO(data)) + tar.add(LOCAL_SVC, arcname="services/social_svc") + tar.add(LOCAL_PB, arcname="services/nomadro_pb") + buf.seek(0) + return buf.read() + + +def main() -> int: + if not LOCAL_SVC.is_dir() or not LOCAL_PB.is_dir(): + raise SystemExit("missing social_svc or nomadro_pb") + blob = pack() + print(f"pack {len(blob)} bytes", flush=True) + + c = connect() + try: + sftp = c.open_sftp() + with sftp.file("/tmp/social_ugc_admin_us.tgz", "wb") as rf: + rf.write(blob) + sftp.close() + + code, _ = sh( + c, + f""" +set -euo pipefail +mkdir -p /tmp/social_ugc_extract +rm -rf /tmp/social_ugc_extract/* +tar -xzf /tmp/social_ugc_admin_us.tgz -C /tmp/social_ugc_extract +TS=$(date +%Y%m%d%H%M%S) + +# 1) social_svc + nomadro_pb → social API tree +mkdir -p {REMOTE_API}/services +[ -d {REMOTE_API}/services/social_svc ] && cp -a {REMOTE_API}/services/social_svc /tmp/social_svc.bak.$TS || true +rsync -a --delete /tmp/social_ugc_extract/services/social_svc/ {REMOTE_API}/services/social_svc/ +rsync -a --delete /tmp/social_ugc_extract/services/nomadro_pb/ {REMOTE_API}/services/nomadro_pb/ + +# 2) same packages on nomadmini PYTHONPATH (import social_svc / nomadro_pb) +rsync -a --delete /tmp/social_ugc_extract/services/social_svc/ {REMOTE_BACKEND}/social_svc/ +rsync -a --delete /tmp/social_ugc_extract/services/nomadro_pb/ {REMOTE_BACKEND}/nomadro_pb/ +# also under services/ for social_ugc parents[2] path probe +mkdir -p {REMOTE_BACKEND}/services +rsync -a --delete /tmp/social_ugc_extract/services/social_svc/ {REMOTE_BACKEND}/services/social_svc/ +rsync -a --delete /tmp/social_ugc_extract/services/nomadro_pb/ {REMOTE_BACKEND}/services/nomadro_pb/ + +# 3) hot-patch ugc modules (ebook_svc→app already rewritten) +cp -a {REMOTE_APP}/services/social_ugc.py {REMOTE_APP}/services/social_ugc.py.bak-$TS 2>/dev/null || true +cp -a {REMOTE_APP}/routers/social_ugc_admin.py {REMOTE_APP}/routers/social_ugc_admin.py.bak-$TS 2>/dev/null || true +cp /tmp/social_ugc_extract/api/services/social_ugc.py {REMOTE_APP}/services/social_ugc.py +cp /tmp/social_ugc_extract/api/routers/social_ugc_admin.py {REMOTE_APP}/routers/social_ugc_admin.py + +# 4) ensure PB URL in nomadmini env (do not clobber secrets) +ENVF={REMOTE_BACKEND}/.env +touch "$ENVF" +grep -q '^PB_URL=' "$ENVF" || echo 'PB_URL=http://127.0.0.1:8090' >> "$ENVF" +grep -q '^POCKETBASE_URL=' "$ENVF" || echo 'POCKETBASE_URL=http://127.0.0.1:8090' >> "$ENVF" + +# 5) import smoke +cd {REMOTE_BACKEND} +.venv/bin/python - <<'PY' +import sys +sys.path.insert(0, ".") +sys.path.insert(0, "services") +from app.routers import social_ugc_admin +from app.services import social_ugc +paths = sorted({{getattr(r, "path", "") for r in social_ugc_admin.router.routes}}) +need = [ + "/api/admin/social/ugc/stats", + "/api/admin/social/ugc/archives", + "/api/admin/social/ugc/detail/{{entity}}/{{entity_id}}", + "/api/admin/social/ugc/overview", +] +for p in need: + assert p in paths, (p, paths) +print("ugc_routes_ok", len(paths)) +print("backend", social_ugc.available()) +PY + +# 6) restart APIs +systemctl kill -s9 nomadro-social.service 2>/dev/null || true +fuser -k 8020/tcp 2>/dev/null || true +sleep 1 +systemctl reset-failed nomadro-social 2>/dev/null || true +systemctl start nomadro-social 2>/dev/null || true +systemctl restart nomadmini-api +sleep 3 +systemctl is-active nomadmini-api +systemctl is-active nomadro-social || true +curl -sS -o /dev/null -w 'social_health:%{{http_code}}\\n' --max-time 8 http://127.0.0.1:8020/api/social/v1/health || true +curl -sS -o /dev/null -w 'api_health:%{{http_code}}\\n' --max-time 8 http://127.0.0.1:8010/docs || true + +TOKEN=$(curl -sS --max-time 12 -X POST https://api.nomadro.com/api/admin/login \\ + -H 'content-type: application/json' \\ + -d '{{"username":"hackrobot","password":"Xiao4669805@"}}' | python3 -c 'import sys,json; print(json.load(sys.stdin).get("token",""))') +echo "token_len ${{#TOKEN}}" +for path in overview stats archives; do + code=$(curl -sS -o /tmp/ugc_$path.json -w '%{{http_code}}' --max-time 15 \\ + -H "Authorization: Bearer $TOKEN" \\ + "https://api.nomadro.com/api/admin/social/ugc/$path") + echo "ugc_$path $code" + head -c 220 /tmp/ugc_$path.json; echo +done +curl -sk -o /dev/null -w 'admin_com %{{http_code}}\\n' https://admin.nomadro.com/ +echo PUSH_SOCIAL_UGC_ADMIN_US_OK +""", + ) + return code + finally: + c.close() + print("done", time.strftime("%H:%M:%S"), flush=True) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/apps/admin/deploy/_push_ugc_sqlite_us.py b/apps/admin/deploy/_push_ugc_sqlite_us.py new file mode 100644 index 0000000..e924060 --- /dev/null +++ b/apps/admin/deploy/_push_ugc_sqlite_us.py @@ -0,0 +1,97 @@ +# -*- coding: utf-8 -*- +"""Hot-patch US nomadmini social_ugc to SQLite soft-delete + stats (no PocketBase).""" +from __future__ import annotations + +from pathlib import Path + +import paramiko + +US = ("108.174.50.68", "root", "Xiao4669805") +HERE = Path(__file__).resolve().parent +SRC = HERE / "_us_social_ugc_sqlite.py" +ADMIN_SRC = ( + Path(__file__).resolve().parents[3] + / "apps/api/services/ebook_svc/routers/social_ugc_admin.py" +) +REMOTE_APP = "/opt/nomadmini/backend/app" + + +def to_app(text: str) -> str: + return text.replace("ebook_svc.", "app.") + + +def main() -> int: + if not SRC.is_file(): + raise SystemExit(f"missing {SRC}") + body = SRC.read_text(encoding="utf-8").encode("utf-8") + admin_body = to_app(ADMIN_SRC.read_text(encoding="utf-8")).encode("utf-8") + if b"ebook_svc." in admin_body: + raise SystemExit("admin rewrite failed") + + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + h, u, p = US + c.connect(h, 22, u, p, timeout=45, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + with sftp.file("/tmp/social_ugc_sqlite_us.py", "wb") as f: + f.write(body) + with sftp.file("/tmp/social_ugc_admin_us.py", "wb") as f: + f.write(admin_body) + sftp.close() + print("uploaded", len(body), len(admin_body), flush=True) + + cmd = rf""" +set -euo pipefail +TS=$(date +%Y%m%d%H%M%S) +B={REMOTE_APP} +cp -a "$B/services/social_ugc.py" "$B/services/social_ugc.py.bak-pre-sqlite-$TS" || true +cp -a "$B/routers/social_ugc_admin.py" "$B/routers/social_ugc_admin.py.bak-pre-sqlite-$TS" || true +cp /tmp/social_ugc_sqlite_us.py "$B/services/social_ugc.py" +cp /tmp/social_ugc_admin_us.py "$B/routers/social_ugc_admin.py" +# ensure SOCIAL_DB_PATH on nomadmini +ENVF=/opt/nomadmini/backend/.env +grep -q '^SOCIAL_DB_PATH=' "$ENVF" || echo 'SOCIAL_DB_PATH=/var/www/nomadro-data/social/social.db' >> "$ENVF" +# prefer empty PB so nothing accidental +sed -i 's/^USE_POCKETBASE=.*/USE_POCKETBASE=false/' "$ENVF" || true +cd /opt/nomadmini/backend +.venv/bin/python - <<'PY' +from app.services import social_ugc as ugc +from app.routers import social_ugc_admin +print('available', ugc.available()) +print('overview', ugc.overview()) +print('stats', {{k: ugc.stats().get(k) for k in ('ok','counts','backend')}}) +paths = sorted({{getattr(r,'path','') for r in social_ugc_admin.router.routes}}) +for need in ['/api/admin/social/ugc/stats','/api/admin/social/ugc/archives','/api/admin/social/ugc/detail/{{entity}}/{{entity_id}}']: + assert need in paths, need +print('routes_ok', len(paths)) +PY +systemctl restart nomadmini-api +sleep 3 +systemctl is-active nomadmini-api +systemctl is-active nomadro-social +curl -sS --max-time 8 http://127.0.0.1:8020/api/social/v1/health; echo +TOKEN=$(curl -sS --max-time 12 -X POST https://api.nomadro.com/api/admin/login \ + -H 'content-type: application/json' \ + -d '{{"username":"hackrobot","password":"Xiao4669805@"}}' | python3 -c 'import sys,json; print(json.load(sys.stdin).get("token",""))') +echo "token_len ${{#TOKEN}}" +for path in overview stats archives roster; do + code=$(curl -sS -o /tmp/ugc_$path.json -w '%{{http_code}}' --max-time 15 \ + -H "Authorization: Bearer $TOKEN" \ + "https://api.nomadro.com/api/admin/social/ugc/$path") + echo "ugc_$path $code" + head -c 260 /tmp/ugc_$path.json; echo +done +curl -sk -o /dev/null -w 'admin_com %{{http_code}}\n' https://admin.nomadro.com/ +echo PUSH_UGC_SQLITE_US_OK +""" + _, o, e = c.exec_command(cmd, timeout=180) + print(o.read().decode("utf-8", "replace"), flush=True) + err = e.read().decode("utf-8", "replace") + if err.strip(): + print("STDERR", err[-3000:], flush=True) + c.close() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/apps/admin/deploy/_restore_social_sqlite_us.py b/apps/admin/deploy/_restore_social_sqlite_us.py new file mode 100644 index 0000000..3057403 --- /dev/null +++ b/apps/admin/deploy/_restore_social_sqlite_us.py @@ -0,0 +1,66 @@ +# -*- coding: utf-8 -*- +"""Restore US social_svc to pre-PB SQLite backup; fetch bak ugc for local enhance.""" +from __future__ import annotations + +from pathlib import Path + +import paramiko + +US = ("108.174.50.68", "root", "Xiao4669805") +OUT = Path(__file__).resolve().parent + + +def main() -> int: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + h, u, p = US + c.connect(h, 22, u, p, timeout=45, allow_agent=False, look_for_keys=False) + sftp = c.open_sftp() + sftp.get( + "/opt/nomadmini/backend/app/services/social_ugc.py.bak-20261104081910", + str(OUT / "_tmp_social_ugc_sqlite.py"), + ) + sftp.get( + "/opt/nomadmini/backend/app/routers/social_ugc_admin.py.bak-20261104081910", + str(OUT / "_tmp_social_ugc_admin_old.py"), + ) + sftp.close() + print("downloaded bak ugc", flush=True) + + cmd = r""" +set -euo pipefail +BAK=$(ls -dt /tmp/social_svc.bak.* | head -1) +echo restoring_from "$BAK" +rsync -a --delete "$BAK/" /var/www/nomadro.cn/apps/api/services/social_svc/ +rm -rf /opt/nomadmini/backend/social_svc /opt/nomadmini/backend/services/social_svc +systemctl kill -s9 nomadro-social 2>/dev/null || true +fuser -k 8020/tcp 2>/dev/null || true +sleep 1 +systemctl reset-failed nomadro-social 2>/dev/null || true +systemctl start nomadro-social +sleep 2 +systemctl is-active nomadro-social +curl -sS --max-time 8 http://127.0.0.1:8020/api/social/v1/health; echo +python3 - <<'PY' +import sqlite3 +db=sqlite3.connect('/var/www/nomadro-data/social/social.db') +print('tables', [r[0] for r in db.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY 1")]) +for t in ['roster','messages','cafe_reviews','gig_apps','feedback']: + try: + print(t, db.execute(f'SELECT COUNT(*) FROM {t}').fetchone()[0]) + except Exception as e: + print(t, e) +PY +echo RESTORE_SOCIAL_SQLITE_OK +""" + _, o, e = c.exec_command(cmd, timeout=120) + print(o.read().decode("utf-8", "replace"), flush=True) + err = e.read().decode("utf-8", "replace") + if err.strip(): + print("STDERR", err[-2000:], flush=True) + c.close() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/apps/admin/deploy/_smoke_admin_com_us.py b/apps/admin/deploy/_smoke_admin_com_us.py new file mode 100644 index 0000000..3c276a2 --- /dev/null +++ b/apps/admin/deploy/_smoke_admin_com_us.py @@ -0,0 +1,77 @@ +# -*- coding: utf-8 -*- +from __future__ import annotations + +import json +import time +import urllib.error +import urllib.request + +import paramiko + +US = ("108.174.50.68", "root", "Xiao4669805") + + +def http(url: str, **kw): + req = urllib.request.Request(url, **kw) + try: + with urllib.request.urlopen(req, timeout=20) as resp: + body = resp.read().decode("utf-8", "replace") + return resp.status, body + except urllib.error.HTTPError as e: + return e.code, e.read().decode("utf-8", "replace") + except Exception as e: + return 0, str(e) + + +def main() -> int: + time.sleep(2) + code, body = http("https://admin.nomadro.com/") + print("admin_com", code, "Nomadro" in body) + code, body = http( + "https://api.nomadro.com/api/admin/login", + data=json.dumps( + {"username": "hackrobot", "password": "Xiao4669805@"} + ).encode(), + headers={"content-type": "application/json"}, + method="POST", + ) + print("login", code, body[:160]) + token = "" + try: + token = json.loads(body).get("token") or "" + except Exception: + pass + if not token: + # remote curl fallback + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + h, u, p = US + c.connect(h, 22, u, p, timeout=40, allow_agent=False, look_for_keys=False) + _, o, e = c.exec_command( + r""" +systemctl is-active nomadmini-api +journalctl -u nomadmini-api -n 40 --no-pager +curl -sS -o /tmp/login.json -w 'login %{http_code}\n' --max-time 15 -X POST https://api.nomadro.com/api/admin/login \ + -H 'content-type: application/json' \ + -d '{"username":"hackrobot","password":"Xiao4669805@"}' +head -c 300 /tmp/login.json; echo +""", + timeout=60, + ) + print(o.read().decode("utf-8", "replace")) + print(e.read().decode("utf-8", "replace")[-1500:]) + c.close() + return 1 + headers = {"Authorization": f"Bearer {token}"} + for path in ("overview", "stats", "archives", "messages?limit=5", "roster?limit=5"): + c2, b2 = http( + f"https://api.nomadro.com/api/admin/social/ugc/{path}", + headers=headers, + ) + print(f"ugc/{path}", c2, b2[:220].replace("\n", " ")) + print("SMOKE_OK") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/apps/admin/deploy/_us_social_ugc_sqlite.py b/apps/admin/deploy/_us_social_ugc_sqlite.py new file mode 100644 index 0000000..d414cc2 --- /dev/null +++ b/apps/admin/deploy/_us_social_ugc_sqlite.py @@ -0,0 +1,674 @@ +"""游民社区 UGC 管理 — 直连 social.db(US 生产;软删除 + social_archives)。 + +默认路径可通过 SOCIAL_DB_PATH 覆盖;生产:/var/www/nomadro-data/social/social.db +""" +from __future__ import annotations + +import json +import os +import sqlite3 +import time +import uuid +from contextlib import contextmanager +from pathlib import Path +from typing import Any, Iterator + +from app.core.sqlite_util import connect as _connect + +_DEFAULT = Path("/var/www/nomadro-data/social/social.db") +SOCIAL_DB_PATH = Path(os.getenv("SOCIAL_DB_PATH", str(_DEFAULT))).resolve() + +ENTITY_TABLES = { + "roster": ("roster", "guest_id"), + "messages": ("messages", "id"), + "reviews": ("cafe_reviews", "id"), + "gigApps": ("gig_apps", "id"), + "feedback": ("feedback", "id"), +} + + +def _now() -> str: + return time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime()) + + +def _uid(prefix: str = "arc") -> str: + return f"{prefix}_{uuid.uuid4().hex[:12]}" + + +@contextmanager +def _db(*, readonly: bool = False) -> Iterator[sqlite3.Connection]: + SOCIAL_DB_PATH.parent.mkdir(parents=True, exist_ok=True) + if readonly and SOCIAL_DB_PATH.is_file(): + uri = f"file:{SOCIAL_DB_PATH.as_posix()}?mode=ro" + conn = sqlite3.connect(uri, uri=True, timeout=30.0) + conn.row_factory = sqlite3.Row + else: + conn = _connect(SOCIAL_DB_PATH) + try: + if not readonly: + _ensure_schema(conn) + yield conn + if not readonly: + conn.commit() + except Exception: + if not readonly: + conn.rollback() + raise + finally: + conn.close() + + +def _ensure_schema(conn: sqlite3.Connection) -> None: + conn.execute( + """ + CREATE TABLE IF NOT EXISTS social_archives ( + id TEXT PRIMARY KEY, + entity TEXT NOT NULL, + entity_id TEXT NOT NULL, + guest_id TEXT DEFAULT '', + action TEXT NOT NULL, + note TEXT DEFAULT '', + payload TEXT DEFAULT '{}', + created_at TEXT NOT NULL + ) + """ + ) + conn.execute( + "CREATE INDEX IF NOT EXISTS idx_social_archives_entity ON social_archives(entity, entity_id, created_at)" + ) + # soft-delete markers on live tables (idempotent) + for table, _pk in { + "roster": "guest_id", + "messages": "id", + "cafe_reviews": "id", + "gig_apps": "id", + "feedback": "id", + }.items(): + cols = {r[1] for r in conn.execute(f"PRAGMA table_info({table})").fetchall()} + if "deleted_at" not in cols: + try: + conn.execute(f"ALTER TABLE {table} ADD COLUMN deleted_at TEXT") + except sqlite3.OperationalError: + pass + if table == "roster" and "status" not in cols: + try: + conn.execute("ALTER TABLE roster ADD COLUMN status TEXT DEFAULT ''") + except sqlite3.OperationalError: + pass + + +def _row_dict(row: sqlite3.Row | None) -> dict[str, Any] | None: + if row is None: + return None + return {k: row[k] for k in row.keys()} + + +def _archive( + conn: sqlite3.Connection, + *, + entity: str, + entity_id: str, + action: str, + payload: dict[str, Any] | None, + guest_id: str = "", + note: str = "", +) -> str: + aid = _uid("arc") + conn.execute( + """ + INSERT INTO social_archives(id, entity, entity_id, guest_id, action, note, payload, created_at) + VALUES(?,?,?,?,?,?,?,?) + """, + ( + aid, + entity, + entity_id, + guest_id or "", + action, + note or "", + json.dumps(payload or {}, ensure_ascii=False), + _now(), + ), + ) + return aid + + +def _soft_delete( + conn: sqlite3.Connection, + *, + entity: str, + entity_id: str, + table: str, + pk: str, + guest_id: str = "", +) -> bool: + row = conn.execute(f"SELECT * FROM {table} WHERE {pk}=?", (entity_id,)).fetchone() + if not row: + return False + payload = _row_dict(row) or {} + if payload.get("deleted_at"): + return True + _archive( + conn, + entity=entity, + entity_id=entity_id, + action="soft_delete", + payload=payload, + guest_id=guest_id or str(payload.get("guest_id") or ""), + ) + if table == "roster": + conn.execute( + "UPDATE roster SET deleted_at=?, status='deleted', updated_at=? WHERE guest_id=?", + (_now(), _now(), entity_id), + ) + else: + conn.execute( + f"UPDATE {table} SET deleted_at=? WHERE {pk}=?", + (_now(), entity_id), + ) + return True + + +def _alive_clause(alias: str = "") -> str: + col = f"{alias}.deleted_at" if alias else "deleted_at" + return f"({col} IS NULL OR {col}='')" + + +def available() -> dict[str, Any]: + exists = SOCIAL_DB_PATH.is_file() + size = SOCIAL_DB_PATH.stat().st_size if exists else 0 + writable = False + if exists: + try: + writable = os.access(SOCIAL_DB_PATH, os.W_OK) + except Exception: + writable = False + return { + "ok": True, + "path": str(SOCIAL_DB_PATH), + "exists": exists, + "bytes": size, + "writable": writable, + "backend": "sqlite", + } + + +def overview() -> dict[str, Any]: + info = available() + counts = { + "messages": 0, + "roster": 0, + "reviews": 0, + "gigApps": 0, + "feedback": 0, + } + if not info["exists"]: + return {**info, "counts": counts} + try: + with _db() as c: + counts["messages"] = c.execute( + f"SELECT COUNT(*) AS n FROM messages WHERE {_alive_clause()}" + ).fetchone()["n"] + counts["roster"] = c.execute( + f"SELECT COUNT(*) AS n FROM roster WHERE {_alive_clause()} AND IFNULL(status,'')!='deleted'" + ).fetchone()["n"] + counts["reviews"] = c.execute( + f"SELECT COUNT(*) AS n FROM cafe_reviews WHERE {_alive_clause()}" + ).fetchone()["n"] + counts["gigApps"] = c.execute( + f"SELECT COUNT(*) AS n FROM gig_apps WHERE {_alive_clause()}" + ).fetchone()["n"] + counts["feedback"] = c.execute( + f"SELECT COUNT(*) AS n FROM feedback WHERE {_alive_clause()}" + ).fetchone()["n"] + except Exception as e: + return {**info, "counts": counts, "error": str(e)} + return {**info, "counts": counts} + + +def list_messages( + *, + channel_id: str = "", + q: str = "", + limit: int = 100, + offset: int = 0, +) -> dict[str, Any]: + limit = max(1, min(int(limit or 100), 500)) + offset = max(0, int(offset or 0)) + clauses: list[str] = [_alive_clause()] + params: list[Any] = [] + if channel_id.strip(): + clauses.append("channel_id=?") + params.append(channel_id.strip()) + if q.strip(): + clauses.append("(author LIKE ? OR text LIKE ? OR guest_id LIKE ?)") + like = f"%{q.strip()}%" + params.extend([like, like, like]) + where = f" WHERE {' AND '.join(clauses)}" + with _db() as c: + total = c.execute(f"SELECT COUNT(*) AS n FROM messages{where}", tuple(params)).fetchone()["n"] + rows = c.execute( + f""" + SELECT id, channel_id, author, text, guest_id, created_at, deleted_at + FROM messages{where} + ORDER BY created_at DESC, rowid DESC + LIMIT ? OFFSET ? + """, + (*params, limit, offset), + ).fetchall() + items = [ + { + "id": r["id"], + "channelId": r["channel_id"], + "author": r["author"], + "text": r["text"], + "guestId": r["guest_id"], + "at": r["created_at"], + } + for r in rows + ] + return {"ok": True, "total": total, "items": items} + + +def delete_message(message_id: str) -> bool: + with _db() as c: + return _soft_delete( + c, entity="messages", entity_id=message_id, table="messages", pk="id" + ) + + +def list_roster(*, q: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]: + limit = max(1, min(int(limit or 100), 500)) + offset = max(0, int(offset or 0)) + clauses: list[str] = [_alive_clause(), "IFNULL(status,'')!='deleted'"] + params: list[Any] = [] + if q.strip(): + clauses.append("(name LIKE ? OR city LIKE ? OR title LIKE ? OR guest_id LIKE ? OR bio LIKE ?)") + like = f"%{q.strip()}%" + params.extend([like, like, like, like, like]) + where = f" WHERE {' AND '.join(clauses)}" + with _db() as c: + total = c.execute(f"SELECT COUNT(*) AS n FROM roster{where}", tuple(params)).fetchone()["n"] + rows = c.execute( + f""" + SELECT guest_id, name, title, city, phone, linktree, skills, bio, updated_at, status, deleted_at + FROM roster{where} + ORDER BY updated_at DESC + LIMIT ? OFFSET ? + """, + (*params, limit, offset), + ).fetchall() + items = [ + { + "guestId": r["guest_id"], + "name": r["name"], + "title": r["title"] or "", + "city": r["city"] or "", + "phone": r["phone"] or "", + "linktree": r["linktree"] or "", + "skills": r["skills"] or "", + "bio": r["bio"] or "", + "updatedAt": r["updated_at"], + "status": r["status"] or "", + } + for r in rows + ] + return {"ok": True, "total": total, "items": items} + + +def update_roster(guest_id: str, patch: dict[str, Any]) -> dict[str, Any] | None: + with _db() as c: + row = c.execute("SELECT * FROM roster WHERE guest_id=?", (guest_id,)).fetchone() + if not row: + return None + restore = bool(patch.get("restore")) + fields = { + "name": str(patch.get("name", row["name"] or ""))[:64] or "游民", + "title": str(patch.get("title", row["title"] or ""))[:80], + "city": str(patch.get("city", row["city"] or ""))[:64], + "phone": str(patch.get("phone", row["phone"] or ""))[:32], + "linktree": str(patch.get("linktree", row["linktree"] or ""))[:240], + "skills": str(patch.get("skills", row["skills"] or ""))[:200], + "bio": str(patch.get("bio", row["bio"] or ""))[:2000], + } + status = str(patch.get("status", row["status"] if "status" in row.keys() else "") or "") + deleted_at = row["deleted_at"] if "deleted_at" in row.keys() else None + if restore: + status = "" + deleted_at = None + _archive( + c, + entity="roster", + entity_id=guest_id, + action="restore", + payload=_row_dict(row), + guest_id=guest_id, + ) + updated = _now() + c.execute( + """ + UPDATE roster SET name=?, title=?, city=?, phone=?, linktree=?, skills=?, bio=?, + status=?, deleted_at=?, updated_at=? + WHERE guest_id=? + """, + ( + fields["name"], + fields["title"], + fields["city"], + fields["phone"], + fields["linktree"], + fields["skills"], + fields["bio"], + status, + deleted_at, + updated, + guest_id, + ), + ) + _archive( + c, + entity="roster", + entity_id=guest_id, + action="update", + payload={**fields, "status": status}, + guest_id=guest_id, + ) + return { + **fields, + "guestId": guest_id, + "updatedAt": updated, + "status": status, + } + + +def delete_roster(guest_id: str) -> bool: + with _db() as c: + return _soft_delete( + c, + entity="roster", + entity_id=guest_id, + table="roster", + pk="guest_id", + guest_id=guest_id, + ) + + +def list_reviews(*, cafe_id: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]: + limit = max(1, min(int(limit or 100), 500)) + offset = max(0, int(offset or 0)) + clauses: list[str] = [_alive_clause()] + params: list[Any] = [] + if cafe_id.strip(): + clauses.append("cafe_id=?") + params.append(cafe_id.strip()) + where = f" WHERE {' AND '.join(clauses)}" + with _db() as c: + total = c.execute( + f"SELECT COUNT(*) AS n FROM cafe_reviews{where}", tuple(params) + ).fetchone()["n"] + rows = c.execute( + f""" + SELECT id, cafe_id, author, score, text, photo_note, guest_id, created_at + FROM cafe_reviews{where} + ORDER BY created_at DESC + LIMIT ? OFFSET ? + """, + (*params, limit, offset), + ).fetchall() + items = [ + { + "id": r["id"], + "cafeId": r["cafe_id"], + "author": r["author"], + "score": r["score"], + "text": r["text"], + "photoNote": r["photo_note"] or "", + "guestId": r["guest_id"], + "at": r["created_at"], + } + for r in rows + ] + return {"ok": True, "total": total, "items": items} + + +def delete_review(review_id: str) -> bool: + with _db() as c: + return _soft_delete( + c, entity="reviews", entity_id=review_id, table="cafe_reviews", pk="id" + ) + + +def list_gig_apps(*, gig_id: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]: + limit = max(1, min(int(limit or 100), 500)) + offset = max(0, int(offset or 0)) + clauses: list[str] = [_alive_clause()] + params: list[Any] = [] + if gig_id.strip(): + clauses.append("gig_id=?") + params.append(gig_id.strip()) + where = f" WHERE {' AND '.join(clauses)}" + with _db() as c: + total = c.execute( + f"SELECT COUNT(*) AS n FROM gig_apps{where}", tuple(params) + ).fetchone()["n"] + rows = c.execute( + f""" + SELECT id, gig_id, name, contact, note, guest_id, created_at + FROM gig_apps{where} + ORDER BY created_at DESC + LIMIT ? OFFSET ? + """, + (*params, limit, offset), + ).fetchall() + items = [ + { + "id": r["id"], + "gigId": r["gig_id"], + "name": r["name"], + "contact": r["contact"], + "note": r["note"] or "", + "guestId": r["guest_id"], + "at": r["created_at"], + } + for r in rows + ] + return {"ok": True, "total": total, "items": items} + + +def delete_gig_app(app_id: str) -> bool: + with _db() as c: + return _soft_delete( + c, entity="gigApps", entity_id=app_id, table="gig_apps", pk="id" + ) + + +def list_feedback(*, limit: int = 100, offset: int = 0) -> dict[str, Any]: + limit = max(1, min(int(limit or 100), 500)) + offset = max(0, int(offset or 0)) + where = f" WHERE {_alive_clause()}" + with _db() as c: + total = c.execute(f"SELECT COUNT(*) AS n FROM feedback{where}").fetchone()["n"] + rows = c.execute( + f""" + SELECT id, kind, text, contact, guest_id, created_at + FROM feedback{where} + ORDER BY created_at DESC + LIMIT ? OFFSET ? + """, + (limit, offset), + ).fetchall() + items = [ + { + "id": r["id"], + "kind": r["kind"], + "text": r["text"], + "contact": r["contact"] or "", + "guestId": r["guest_id"], + "at": r["created_at"], + } + for r in rows + ] + return {"ok": True, "total": total, "items": items} + + +def delete_feedback(fid: str) -> bool: + with _db() as c: + return _soft_delete( + c, entity="feedback", entity_id=fid, table="feedback", pk="id" + ) + + +def stats() -> dict[str, Any]: + with _db() as c: + def cnt(sql: str) -> int: + return int(c.execute(sql).fetchone()[0]) + + counts = { + "messages": cnt(f"SELECT COUNT(*) FROM messages WHERE {_alive_clause()}"), + "roster": cnt( + f"SELECT COUNT(*) FROM roster WHERE {_alive_clause()} AND IFNULL(status,'')!='deleted'" + ), + "reviews": cnt(f"SELECT COUNT(*) FROM cafe_reviews WHERE {_alive_clause()}"), + "gigApps": cnt(f"SELECT COUNT(*) FROM gig_apps WHERE {_alive_clause()}"), + "feedback": cnt(f"SELECT COUNT(*) FROM feedback WHERE {_alive_clause()}"), + "archives": cnt("SELECT COUNT(*) FROM social_archives"), + } + soft = { + "roster": cnt( + "SELECT COUNT(*) FROM roster WHERE (deleted_at IS NOT NULL AND deleted_at!='') OR status='deleted'" + ), + "messages": cnt( + "SELECT COUNT(*) FROM messages WHERE deleted_at IS NOT NULL AND deleted_at!=''" + ), + "reviews": cnt( + "SELECT COUNT(*) FROM cafe_reviews WHERE deleted_at IS NOT NULL AND deleted_at!=''" + ), + "gigApps": cnt( + "SELECT COUNT(*) FROM gig_apps WHERE deleted_at IS NOT NULL AND deleted_at!=''" + ), + "feedback": cnt( + "SELECT COUNT(*) FROM feedback WHERE deleted_at IS NOT NULL AND deleted_at!=''" + ), + } + rows = c.execute( + f""" + SELECT IFNULL(NULLIF(TRIM(city),''),'未填') AS city, COUNT(*) AS n + FROM roster + WHERE {_alive_clause()} AND IFNULL(status,'')!='deleted' + GROUP BY 1 + ORDER BY n DESC + LIMIT 12 + """ + ).fetchall() + by_city = [{"name": r["city"], "value": int(r["n"])} for r in rows] + day_rows = c.execute( + f""" + SELECT substr(updated_at,1,10) AS d, COUNT(*) AS n + FROM roster + WHERE {_alive_clause()} AND IFNULL(status,'')!='deleted' + AND updated_at IS NOT NULL AND updated_at!='' + GROUP BY 1 + ORDER BY 1 + """ + ).fetchall() + day_series = [{"date": r["d"], "value": int(r["n"])} for r in day_rows][-30:] + return { + "ok": True, + "counts": counts, + "softDeleted": soft, + "activeRoster": counts["roster"], + "byCity": by_city, + "rosterByDay": day_series, + "backend": "sqlite", + } + + +def get_detail(entity: str, entity_id: str) -> dict[str, Any] | None: + meta = ENTITY_TABLES.get(entity) + if not meta: + return None + table, pk = meta + with _db() as c: + row = c.execute(f"SELECT * FROM {table} WHERE {pk}=?", (entity_id,)).fetchone() + if not row: + return None + item = _row_dict(row) or {} + hist = c.execute( + """ + SELECT id, action, note, payload, created_at + FROM social_archives + WHERE entity=? AND entity_id=? + ORDER BY created_at DESC + LIMIT 50 + """, + (entity, entity_id), + ).fetchall() + soft = bool(item.get("deleted_at")) or item.get("status") == "deleted" + history = [] + for h in hist: + try: + payload = json.loads(h["payload"] or "{}") + except Exception: + payload = {} + history.append( + { + "id": h["id"], + "action": h["action"], + "at": h["created_at"], + "note": h["note"] or "", + "payload": payload, + } + ) + return { + "ok": True, + "entity": entity, + "id": entity_id, + "item": item, + "softDeleted": soft, + "history": history, + } + + +def list_archives( + *, entity: str = "", limit: int = 100, offset: int = 0 +) -> dict[str, Any]: + lim = max(1, min(int(limit or 100), 500)) + off = max(0, int(offset or 0)) + clauses: list[str] = [] + params: list[Any] = [] + if entity.strip(): + clauses.append("entity=?") + params.append(entity.strip()) + where = f" WHERE {' AND '.join(clauses)}" if clauses else "" + with _db() as c: + total = c.execute( + f"SELECT COUNT(*) AS n FROM social_archives{where}", tuple(params) + ).fetchone()["n"] + rows = c.execute( + f""" + SELECT id, entity, entity_id, guest_id, action, note, payload, created_at + FROM social_archives{where} + ORDER BY created_at DESC + LIMIT ? OFFSET ? + """, + (*params, lim, off), + ).fetchall() + items = [] + for r in rows: + try: + payload = json.loads(r["payload"] or "{}") + except Exception: + payload = {} + items.append( + { + "id": r["id"], + "entity": r["entity"], + "entityId": r["entity_id"], + "guestId": r["guest_id"] or "", + "action": r["action"], + "note": r["note"] or "", + "at": r["created_at"], + "payload": payload, + } + ) + return {"ok": True, "total": total, "items": items} diff --git a/apps/admin/src/pages/SocialData.tsx b/apps/admin/src/pages/SocialData.tsx index f3aef72..ad9361a 100644 --- a/apps/admin/src/pages/SocialData.tsx +++ b/apps/admin/src/pages/SocialData.tsx @@ -92,7 +92,7 @@ export default function SocialData() { }, [loadList]) async function remove(kind: Tab, id: string) { - if (!confirm('确认删除?不可恢复')) return + if (!confirm('软删除?内容会写入存档(social_archives),不会物理抹除。')) return setBusy(true) setMsg('') setErr('') @@ -105,7 +105,7 @@ export default function SocialData() { feedback: `/api/admin/social/ugc/feedback/${id}`, } await api(map[kind], { method: 'DELETE' }) - setMsg('已删除') + setMsg('已软删除并写入存档') await loadList() await loadOverview() } catch (e: any) { diff --git a/apps/api/services/coffee_svc/pb_store.py b/apps/api/services/coffee_svc/pb_store.py new file mode 100644 index 0000000..f5ea64c --- /dev/null +++ b/apps/api/services/coffee_svc/pb_store.py @@ -0,0 +1,405 @@ +"""Coffeechat booking store on PocketBase (no SQLite).""" +from __future__ import annotations + +import time +import uuid +from datetime import datetime, timedelta, timezone +from typing import Any +from zoneinfo import ZoneInfo + +from nomadro_pb import ensure_once, get_pb, pb_quote + +C_HOSTS = "coffee_hosts" +C_SCHEDULES = "coffee_schedules" +C_EVENTS = "coffee_event_types" +C_BOOKINGS = "coffee_bookings" + + +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 init_db() -> None: + ensure_once() + _seed() + + +def _seed() -> None: + pb = get_pb() + if pb.first(C_HOSTS, filter='username="alice"'): + return + hid = _id("host") + now = _now() + pb.create( + C_HOSTS, + { + "username": "alice", + "name": "Alice Chen", + "bio": "演示主持人 · 可约 30 分钟咖啡聊", + "avatar": "", + "city": "Chengdu", + "timezone": "Asia/Shanghai", + "created_at": now, + }, + ) + # re-fetch for id + host = pb.first(C_HOSTS, filter='username="alice"') + if not host: + return + hid = host["id"] + sid = _id("sch") + pb.create( + C_SCHEDULES, + { + "host_id": hid, + "name": "Default", + "timezone": "Asia/Shanghai", + "availability": [ + {"days": ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"], "startTime": 600, "endTime": 1080} + ], + "created_at": now, + }, + ) + sch = pb.first(C_SCHEDULES, filter=f"host_id={pb_quote(hid)}") + pb.create( + C_EVENTS, + { + "host_id": hid, + "schedule_id": (sch or {}).get("id") or sid, + "slug": "30min", + "title": "咖啡聊 30′", + "description": "线下咖啡馆或线上都行", + "length_minutes": 30, + "slot_interval": 30, + "buffer_before": 0, + "buffer_after": 0, + "locations": [{"type": "inPerson", "label": "咖啡馆(见面后定)"}], + "active": True, + "created_at": now, + }, + ) + + +def list_hosts() -> list[dict[str, Any]]: + init_db() + rows = get_pb().list_all(C_HOSTS, sort="username") + out = [] + for r in rows: + n = len( + get_pb().list_all( + C_EVENTS, + filter=f'host_id={pb_quote(r["id"])} && active=true', + hard_limit=50, + ) + ) + out.append(_host_out(r, event_count=n)) + return out + + +def get_host(username: str) -> dict[str, Any] | None: + init_db() + r = get_pb().first(C_HOSTS, filter=f"username={pb_quote(username)}") + if not r: + return None + events = get_pb().list_all( + C_EVENTS, filter=f'host_id={pb_quote(r["id"])} && active=true' + ) + h = _host_out(r, event_count=len(events)) + h["event_types"] = [_event_out(e) for e in events] + return h + + +def _host_out(r: dict[str, Any], *, event_count: int = 0) -> dict[str, Any]: + return { + "id": r.get("id"), + "username": r.get("username"), + "name": r.get("name"), + "bio": r.get("bio") or "", + "avatar": r.get("avatar"), + "timezone": r.get("timezone") or "Asia/Shanghai", + "city": r.get("city") or "", + "event_count": event_count, + "created_at": r.get("created_at"), + } + + +def get_event_type(username: str, slug: str) -> dict[str, Any] | None: + init_db() + host = get_pb().first(C_HOSTS, filter=f"username={pb_quote(username)}") + if not host: + return None + e = get_pb().first( + C_EVENTS, + filter=f'host_id={pb_quote(host["id"])} && slug={pb_quote(slug)}', + ) + if not e: + return None + out = _event_out(e) + out["host"] = _host_out(host) + return out + + +def _event_out(r: dict[str, Any]) -> dict[str, Any]: + return { + "id": r.get("id"), + "host_id": r.get("host_id"), + "schedule_id": r.get("schedule_id"), + "slug": r.get("slug"), + "title": r.get("title"), + "description": r.get("description") or "", + "length_minutes": int(r.get("length_minutes") or 30), + "slot_interval": int(r.get("slot_interval") or 15), + "buffer_before": int(r.get("buffer_before") or 0), + "buffer_after": int(r.get("buffer_after") or 0), + "locations": r.get("locations") or [], + "active": bool(r.get("active", True)), + "created_at": r.get("created_at"), + } + + +def get_schedule(host_username: str) -> dict[str, Any] | None: + init_db() + host = get_pb().first(C_HOSTS, filter=f"username={pb_quote(host_username)}") + if not host: + return None + s = get_pb().first(C_SCHEDULES, filter=f'host_id={pb_quote(host["id"])}') + if not s: + return None + return { + "id": s.get("id"), + "host_id": host["id"], + "name": s.get("name") or "Default", + "timezone": s.get("timezone") or host.get("timezone") or "Asia/Shanghai", + "availability": s.get("availability") or [], + "created_at": s.get("created_at"), + } + + +def update_schedule( + username: str, + *, + availability: list[dict[str, Any]] | None = None, + timezone_name: str | None = None, + name: str | None = None, +) -> dict[str, Any]: + s = get_schedule(username) + if not s: + raise ValueError("schedule_not_found") + patch: dict[str, Any] = {} + if availability is not None: + patch["availability"] = availability + if timezone_name: + patch["timezone"] = timezone_name + if name: + patch["name"] = name + if patch: + get_pb().update(C_SCHEDULES, s["id"], patch) + return get_schedule(username) # type: ignore[return-value] + + +def upsert_event_type(username: str, data: dict[str, Any]) -> dict[str, Any]: + init_db() + host = get_pb().first(C_HOSTS, filter=f"username={pb_quote(username)}") + if not host: + raise ValueError("host_not_found") + sch = get_pb().first(C_SCHEDULES, filter=f'host_id={pb_quote(host["id"])}') + slug = str(data.get("slug") or "").strip() + if not slug: + raise ValueError("slug_required") + existing = get_pb().first( + C_EVENTS, + filter=f'host_id={pb_quote(host["id"])} && slug={pb_quote(slug)}', + ) + body = { + "host_id": host["id"], + "schedule_id": (sch or {}).get("id") or "", + "slug": slug, + "title": str(data.get("title") or slug)[:200], + "description": str(data.get("description") or "")[:2000], + "length_minutes": int(data.get("length_minutes") or 30), + "slot_interval": int(data.get("slot_interval") or 15), + "buffer_before": int(data.get("buffer_before") or 0), + "buffer_after": int(data.get("buffer_after") or 0), + "locations": data.get("locations") or [], + "active": bool(data.get("active", True)), + "created_at": _now(), + } + if existing: + get_pb().update(C_EVENTS, existing["id"], body) + else: + get_pb().create(C_EVENTS, body) + return get_event_type(username, slug) # type: ignore[return-value] + + +def available_slots(username: str, slug: str, day: str) -> dict[str, Any]: + et = get_event_type(username, slug) + if not et: + raise ValueError("event_type_not_found") + sch = get_schedule(username) + if not sch: + raise ValueError("schedule_not_found") + tz = ZoneInfo(sch.get("timezone") or "Asia/Shanghai") + length = int(et["length_minutes"]) + interval = int(et["slot_interval"] or 15) + # naive window: 10:00-18:00 local every interval + slots = [] + base = datetime.fromisoformat(f"{day}T00:00:00").replace(tzinfo=tz) + for mins in range(10 * 60, 18 * 60, interval): + start = base + timedelta(minutes=mins) + end = start + timedelta(minutes=length) + if end.hour > 18 or (end.hour == 18 and end.minute > 0): + continue + slots.append( + { + "start": start.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), + "end": end.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), + "local": start.strftime("%H:%M"), + } + ) + return { + "ok": True, + "day": day, + "timezone": sch.get("timezone"), + "slots": slots, + "event_type": { + "slug": et["slug"], + "title": et["title"], + "length_minutes": length, + }, + } + + +def create_booking(data: dict[str, Any]) -> dict[str, Any]: + init_db() + username = str(data.get("username") or "").strip() + slug = str(data.get("event_slug") or "").strip() + start = str(data.get("start") or "").strip() + attendee_name = str(data.get("attendee_name") or "").strip() + if not username or not slug or not start or not attendee_name: + raise ValueError("username_slug_start_attendee_required") + et = get_event_type(username, slug) + if not et: + raise ValueError("event_type_not_found") + host = get_pb().first(C_HOSTS, filter=f"username={pb_quote(username)}") + length = int(et["length_minutes"]) + start_dt = datetime.fromisoformat(start.replace("Z", "+00:00")) + end_dt = start_dt + timedelta(minutes=length) + now = _now() + uid = _id("uid") + body = { + "uid": uid, + "event_type_id": et["id"], + "host_id": host["id"], + "title": et["title"], + "status": "accepted", + "start_utc": start_dt.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), + "end_utc": end_dt.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), + "location": str(data.get("location") or ""), + "notes": str(data.get("notes") or ""), + "attendee_name": attendee_name[:120], + "attendee_email": data.get("attendee_email"), + "attendee_device": data.get("attendee_device"), + "created_at": now, + "cancelled_at": "", + } + rec = get_pb().create(C_BOOKINGS, body) + return get_booking(rec["id"]) # type: ignore[return-value] + + +def get_booking(booking_id: str) -> dict[str, Any] | None: + init_db() + try: + r = get_pb().request( + "GET", f"/api/collections/{C_BOOKINGS}/records/{booking_id}", admin=True + ) + except Exception: + r = get_pb().first(C_BOOKINGS, filter=f"uid={pb_quote(booking_id)}") + if not r: + return None + host = None + if r.get("host_id"): + try: + host = get_pb().request( + "GET", + f"/api/collections/{C_HOSTS}/records/{r['host_id']}", + admin=True, + ) + except Exception: + host = None + return _booking_out(r, host=host) + + +def list_bookings( + *, + host_username: str | None = None, + status: str | None = None, +) -> list[dict[str, Any]]: + init_db() + rows = get_pb().list_all(C_BOOKINGS, sort="-start_utc", hard_limit=100) + out = [] + for r in rows: + if status and r.get("status") != status: + continue + host = None + if r.get("host_id"): + try: + host = get_pb().request( + "GET", + f"/api/collections/{C_HOSTS}/records/{r['host_id']}", + admin=True, + ) + except Exception: + host = None + if host_username and host and host.get("username") != host_username: + continue + out.append(_booking_out(r, host=host)) + return out + + +def cancel_booking(booking_id: str) -> dict[str, Any] | None: + b = get_booking(booking_id) + if not b: + return None + get_pb().update( + C_BOOKINGS, + b["id"], + {"status": "cancelled", "cancelled_at": _now()}, + ) + return get_booking(b["id"]) + + +def _booking_out( + r: dict[str, Any], host: dict[str, Any] | None = None +) -> dict[str, Any]: + return { + "id": r.get("id"), + "uid": r.get("uid"), + "event_type_id": r.get("event_type_id"), + "host_id": r.get("host_id"), + "host": ( + { + "username": host.get("username"), + "name": host.get("name"), + "city": host.get("city"), + } + if host + else None + ), + "title": r.get("title"), + "status": r.get("status"), + "start": r.get("start_utc"), + "end": r.get("end_utc"), + "location": r.get("location") or "", + "notes": r.get("notes") or "", + "attendee": { + "name": r.get("attendee_name"), + "email": r.get("attendee_email"), + "device": r.get("attendee_device"), + }, + "created_at": r.get("created_at"), + "cancelled_at": r.get("cancelled_at") or None, + } diff --git a/apps/api/services/coffee_svc/routers/api.py b/apps/api/services/coffee_svc/routers/api.py index 7bc8215..8451896 100644 --- a/apps/api/services/coffee_svc/routers/api.py +++ b/apps/api/services/coffee_svc/routers/api.py @@ -131,6 +131,20 @@ def book(body: BookingIn): except ValueError as e: code = 409 if str(e) == "slot_unavailable" else 400 raise HTTPException(code, str(e)) from e + # Notify host (subscriber = host_id) — best-effort + try: + from social_svc.notify_bridge import notify_coffee_invite + + host = b.get("host") or {} + to_id = str(b.get("host_id") or host.get("username") or "") + if to_id: + notify_coffee_invite( + to_id, + str(body.attendee_name or "游民"), + str(b.get("title") or "咖啡聊"), + ) + except Exception: + pass return {"ok": True, "booking": b} diff --git a/apps/api/services/coffee_svc/store.py b/apps/api/services/coffee_svc/store.py index e53128c..e6d6448 100644 --- a/apps/api/services/coffee_svc/store.py +++ b/apps/api/services/coffee_svc/store.py @@ -1,719 +1,17 @@ -""" -SQLite store — domain shaped after Cal.com -(User/Host · EventType · Schedule · Availability · Booking · Attendee · Slot). -Secondary-dev reimplementation for Nomadro coffeechat (not upstream Cal runtime). -""" +"""Coffeechat store — PocketBase (online-first).""" from __future__ import annotations -import json -import sqlite3 -import time -import uuid -from datetime import date, datetime, timedelta, timezone -from pathlib import Path -from typing import Any -from zoneinfo import ZoneInfo - -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 - - -WEEKDAYS = ("sun", "mon", "tue", "wed", "thu", "fri", "sat") -# Cal.com uses 0=Sunday … Python weekday() is 0=Monday — map carefully -PY_TO_CAL = {0: "mon", 1: "tue", 2: "wed", 3: "thu", 4: "fri", 5: "sat", 6: "sun"} - - -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 _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 hosts ( - id TEXT PRIMARY KEY, - username TEXT NOT NULL UNIQUE, - name TEXT NOT NULL, - bio TEXT NOT NULL DEFAULT '', - avatar TEXT, - timezone TEXT NOT NULL DEFAULT 'Asia/Shanghai', - city TEXT NOT NULL DEFAULT '', - created_at TEXT NOT NULL - ); - CREATE TABLE IF NOT EXISTS schedules ( - id TEXT PRIMARY KEY, - host_id TEXT NOT NULL, - name TEXT NOT NULL DEFAULT 'Working hours', - timezone TEXT NOT NULL DEFAULT 'Asia/Shanghai', - availability_json TEXT NOT NULL DEFAULT '[]', - created_at TEXT NOT NULL, - FOREIGN KEY(host_id) REFERENCES hosts(id) - ); - CREATE TABLE IF NOT EXISTS event_types ( - id TEXT PRIMARY KEY, - host_id TEXT NOT NULL, - schedule_id TEXT NOT NULL, - slug TEXT NOT NULL, - title TEXT NOT NULL, - description TEXT NOT NULL DEFAULT '', - length_minutes INTEGER NOT NULL DEFAULT 30, - slot_interval INTEGER NOT NULL DEFAULT 15, - buffer_before INTEGER NOT NULL DEFAULT 0, - buffer_after INTEGER NOT NULL DEFAULT 0, - locations_json TEXT NOT NULL DEFAULT '[]', - active INTEGER NOT NULL DEFAULT 1, - created_at TEXT NOT NULL, - UNIQUE(host_id, slug), - FOREIGN KEY(host_id) REFERENCES hosts(id), - FOREIGN KEY(schedule_id) REFERENCES schedules(id) - ); - CREATE TABLE IF NOT EXISTS bookings ( - id TEXT PRIMARY KEY, - uid TEXT NOT NULL UNIQUE, - event_type_id TEXT NOT NULL, - host_id TEXT NOT NULL, - title TEXT NOT NULL, - status TEXT NOT NULL DEFAULT 'accepted', - start_utc TEXT NOT NULL, - end_utc TEXT NOT NULL, - location TEXT NOT NULL DEFAULT '', - notes TEXT NOT NULL DEFAULT '', - attendee_name TEXT NOT NULL, - attendee_email TEXT, - attendee_device TEXT, - created_at TEXT NOT NULL, - cancelled_at TEXT, - FOREIGN KEY(event_type_id) REFERENCES event_types(id), - FOREIGN KEY(host_id) REFERENCES hosts(id) - ); - CREATE INDEX IF NOT EXISTS idx_bookings_host_start - ON bookings(host_id, start_utc); - """ - ) - _seed(c) - - -def _default_availability() -> list[dict[str, Any]]: - """Cal.com-style weekly windows (local schedule timezone).""" - windows = [{"days": ["mon", "tue", "wed", "thu", "fri"], "startTime": 600, "endTime": 720}] - # 10:00–12:00 and 14:00–18:00 as minutes from midnight - windows.append( - {"days": ["mon", "tue", "wed", "thu", "fri"], "startTime": 840, "endTime": 1080} - ) - windows.append({"days": ["sat"], "startTime": 660, "endTime": 900}) - return windows - - -def _seed(c: sqlite3.Connection) -> None: - if c.execute("SELECT 1 FROM hosts LIMIT 1").fetchone(): - return - now = _now() - hosts = [ - ("host_alice", "alice", "Alice Chen", "成都远程 · 爱咖啡闲聊产品与出海", "Chengdu", "Asia/Shanghai"), - ("host_bob", "bob", "Bob Rivera", "EN/ZH · coffee or video walkthrough", "Chiang Mai", "Asia/Bangkok"), - ("host_guest", "guest", "Guest Nomad", "演示主持人 · 可约 30 分钟咖啡聊", "Shenzhen", "Asia/Shanghai"), - ] - for hid, user, name, bio, city, tz in hosts: - c.execute( - """INSERT INTO hosts(id,username,name,bio,avatar,timezone,city,created_at) - VALUES(?,?,?,?,?,?,?,?)""", - (hid, user, name, bio, None, tz, city, now), - ) - sid = f"sch_{user}" - c.execute( - """INSERT INTO schedules(id,host_id,name,timezone,availability_json,created_at) - VALUES(?,?,?,?,?,?)""", - (sid, hid, "Working hours", tz, _json(_default_availability()), now), - ) - events = [ - ( - f"et_{user}_coffee", - "coffee-30", - "☕ 咖啡聊 30′", - "同城咖啡馆或语音闲聊,认识一下就好。", - 30, - [ - {"type": "inPerson", "label": "咖啡馆(见面后定)"}, - {"type": "link", "label": "语音/视频", "link": "/social/meetup"}, - ], - ), - ( - f"et_{user}_video", - "video-45", - "📹 视频深聊 45′", - "产品 / 副业 / 旅居经验,线上视频。", - 45, - [{"type": "link", "label": "Nomadro 视频厅", "link": "/social/meetup"}], - ), - ] - for eid, slug, title, desc, length, locs in events: - c.execute( - """INSERT INTO event_types( - id,host_id,schedule_id,slug,title,description,length_minutes, - slot_interval,buffer_before,buffer_after,locations_json,active,created_at - ) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)""", - ( - eid, - hid, - sid, - slug, - title, - desc, - length, - 15, - 0, - 0, - _json(locs), - 1, - now, - ), - ) - - # sample booking tomorrow 10:00 Asia/Shanghai for alice coffee - tz = ZoneInfo("Asia/Shanghai") - tomorrow = datetime.now(tz).date() + timedelta(days=1) - start_local = datetime(tomorrow.year, tomorrow.month, tomorrow.day, 10, 0, tzinfo=tz) - end_local = start_local + timedelta(minutes=30) - c.execute( - """INSERT INTO bookings( - id,uid,event_type_id,host_id,title,status,start_utc,end_utc,location,notes, - attendee_name,attendee_email,attendee_device,created_at,cancelled_at - ) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""", - ( - _id("bk"), - _id("uid"), - "et_alice_coffee", - "host_alice", - "☕ 咖啡聊 30′", - "accepted", - start_local.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), - end_local.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), - "咖啡馆(见面后定)", - "种子预约", - "Demo Attendee", - "demo@nomadro.com", - None, - now, - None, - ), - ) - - -# —— hosts / event types —— - - -def list_hosts() -> list[dict[str, Any]]: - with _conn() as c: - rows = c.execute("SELECT * FROM hosts ORDER BY username").fetchall() - out = [] - for r in rows: - n = c.execute( - "SELECT COUNT(*) AS n FROM event_types WHERE host_id=? AND active=1", - (r["id"],), - ).fetchone()["n"] - out.append(_host_out(dict(r), event_count=n)) - return out - - -def get_host(username: str) -> dict[str, Any] | None: - with _conn() as c: - r = c.execute( - "SELECT * FROM hosts WHERE username=? OR id=?", - (username, username), - ).fetchone() - if not r: - return None - events = [ - _event_out(dict(e)) - for e in c.execute( - "SELECT * FROM event_types WHERE host_id=? AND active=1 ORDER BY length_minutes", - (r["id"],), - ).fetchall() - ] - h = _host_out(dict(r), event_count=len(events)) - h["event_types"] = events - return h - - -def _host_out(r: dict[str, Any], *, event_count: int = 0) -> dict[str, Any]: - return { - "id": r["id"], - "username": r["username"], - "name": r["name"], - "bio": r.get("bio") or "", - "avatar": r.get("avatar"), - "timezone": r.get("timezone") or "Asia/Shanghai", - "city": r.get("city") or "", - "event_count": event_count, - "created_at": r.get("created_at"), - } - - -def get_event_type(username: str, slug: str) -> dict[str, Any] | None: - with _conn() as c: - h = c.execute( - "SELECT * FROM hosts WHERE username=? OR id=?", - (username, username), - ).fetchone() - if not h: - return None - e = c.execute( - "SELECT * FROM event_types WHERE host_id=? AND slug=?", - (h["id"], slug), - ).fetchone() - if not e: - return None - out = _event_out(dict(e)) - out["host"] = _host_out(dict(h)) - sch = c.execute( - "SELECT * FROM schedules WHERE id=?", (e["schedule_id"],) - ).fetchone() - if sch: - out["schedule"] = _schedule_out(dict(sch)) - return out - - -def _event_out(r: dict[str, Any]) -> dict[str, Any]: - return { - "id": r["id"], - "host_id": r["host_id"], - "schedule_id": r["schedule_id"], - "slug": r["slug"], - "title": r["title"], - "description": r.get("description") or "", - "length_minutes": int(r["length_minutes"]), - "slot_interval": int(r.get("slot_interval") or 15), - "buffer_before": int(r.get("buffer_before") or 0), - "buffer_after": int(r.get("buffer_after") or 0), - "locations": _parse(r.get("locations_json"), []), - "active": bool(r.get("active")), - "created_at": r.get("created_at"), - } - - -def _schedule_out(r: dict[str, Any]) -> dict[str, Any]: - return { - "id": r["id"], - "host_id": r["host_id"], - "name": r["name"], - "timezone": r["timezone"], - "availability": _parse(r.get("availability_json"), []), - "created_at": r["created_at"], - } - - -def get_schedule(host_username: str) -> dict[str, Any] | None: - with _conn() as c: - h = c.execute( - "SELECT * FROM hosts WHERE username=? OR id=?", - (host_username, host_username), - ).fetchone() - if not h: - return None - s = c.execute( - "SELECT * FROM schedules WHERE host_id=? ORDER BY created_at LIMIT 1", - (h["id"],), - ).fetchone() - return _schedule_out(dict(s)) if s else None - - -def update_schedule( - host_username: str, - *, - availability: list[dict[str, Any]] | None = None, - timezone_name: str | None = None, - name: str | None = None, -) -> dict[str, Any]: - with _conn() as c: - h = c.execute( - "SELECT * FROM hosts WHERE username=? OR id=?", - (host_username, host_username), - ).fetchone() - if not h: - raise ValueError("host_not_found") - s = c.execute( - "SELECT * FROM schedules WHERE host_id=? ORDER BY created_at LIMIT 1", - (h["id"],), - ).fetchone() - if not s: - raise ValueError("schedule_not_found") - avail = ( - _json(availability) - if availability is not None - else s["availability_json"] - ) - tz = timezone_name or s["timezone"] - nm = name or s["name"] - c.execute( - "UPDATE schedules SET availability_json=?, timezone=?, name=? WHERE id=?", - (avail, tz, nm, s["id"]), - ) - if timezone_name: - c.execute( - "UPDATE hosts SET timezone=? WHERE id=?", - (timezone_name, h["id"]), - ) - row = c.execute("SELECT * FROM schedules WHERE id=?", (s["id"],)).fetchone() - return _schedule_out(dict(row)) - - -def upsert_event_type( - host_username: str, - data: dict[str, Any], -) -> dict[str, Any]: - slug = (data.get("slug") or "").strip() - title = (data.get("title") or "").strip() - if not slug or not title: - raise ValueError("slug_and_title_required") - with _conn() as c: - h = c.execute( - "SELECT * FROM hosts WHERE username=? OR id=?", - (host_username, host_username), - ).fetchone() - if not h: - raise ValueError("host_not_found") - sch = c.execute( - "SELECT id FROM schedules WHERE host_id=? LIMIT 1", - (h["id"],), - ).fetchone() - if not sch: - raise ValueError("schedule_not_found") - existing = c.execute( - "SELECT * FROM event_types WHERE host_id=? AND slug=?", - (h["id"], slug), - ).fetchone() - length = int(data.get("length_minutes") or 30) - interval = int(data.get("slot_interval") or 15) - locs = data.get("locations") or [ - {"type": "inPerson", "label": "咖啡馆(见面后定)"} - ] - now = _now() - if existing: - c.execute( - """UPDATE event_types SET title=?,description=?,length_minutes=?, - slot_interval=?,locations_json=?,active=? WHERE id=?""", - ( - title, - data.get("description") or "", - length, - interval, - _json(locs), - 1 if data.get("active", True) else 0, - existing["id"], - ), - ) - eid = existing["id"] - else: - eid = _id("et") - c.execute( - """INSERT INTO event_types( - id,host_id,schedule_id,slug,title,description,length_minutes, - slot_interval,buffer_before,buffer_after,locations_json,active,created_at - ) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)""", - ( - eid, - h["id"], - sch["id"], - slug, - title, - data.get("description") or "", - length, - interval, - int(data.get("buffer_before") or 0), - int(data.get("buffer_after") or 0), - _json(locs), - 1, - now, - ), - ) - row = c.execute("SELECT * FROM event_types WHERE id=?", (eid,)).fetchone() - return _event_out(dict(row)) - - -# —— slots (Cal.com getSchedule / availableSlots parity) —— - - -def _parse_utc(s: str) -> datetime: - if s.endswith("Z"): - s = s[:-1] + "+00:00" - return datetime.fromisoformat(s).astimezone(timezone.utc) - - -def available_slots( - username: str, - event_slug: str, - day: str, -) -> dict[str, Any]: - """Return bookable UTC slots for a local calendar day (YYYY-MM-DD).""" - et = get_event_type(username, event_slug) - if not et or not et.get("active"): - raise ValueError("event_type_not_found") - host = et["host"] - sch = et.get("schedule") or {} - tz_name = sch.get("timezone") or host.get("timezone") or "Asia/Shanghai" - try: - tz = ZoneInfo(tz_name) - except Exception: - tz = ZoneInfo("Asia/Shanghai") - tz_name = "Asia/Shanghai" - - try: - day_d = date.fromisoformat(day) - except ValueError as e: - raise ValueError("invalid_day") from e - - length = int(et["length_minutes"]) - interval = int(et.get("slot_interval") or 15) - buf_before = int(et.get("buffer_before") or 0) - buf_after = int(et.get("buffer_after") or 0) - cal_day = PY_TO_CAL[day_d.weekday()] - windows = [ - w - for w in (sch.get("availability") or []) - if cal_day in (w.get("days") or []) - ] - if not windows: - return { - "ok": True, - "day": day, - "timezone": tz_name, - "slots": [], - "event_type": {"slug": et["slug"], "length_minutes": length}, - } - - # busy from accepted bookings that day (host local) - day_start = datetime(day_d.year, day_d.month, day_d.day, 0, 0, tzinfo=tz) - day_end = day_start + timedelta(days=1) - with _conn() as c: - busy_rows = c.execute( - """SELECT start_utc,end_utc FROM bookings - WHERE host_id=? AND status='accepted' - AND start_utc < ? AND end_utc > ?""", - ( - host["id"], - day_end.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), - day_start.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), - ), - ).fetchall() - busy = [(_parse_utc(b["start_utc"]), _parse_utc(b["end_utc"])) for b in busy_rows] - - now_utc = datetime.now(timezone.utc) - slots: list[dict[str, str]] = [] - for w in windows: - start_m = int(w.get("startTime") or 0) - end_m = int(w.get("endTime") or 0) - cursor = day_start + timedelta(minutes=start_m) - window_end = day_start + timedelta(minutes=end_m) - while cursor + timedelta(minutes=length) <= window_end: - slot_start = cursor - slot_end = cursor + timedelta(minutes=length) - slot_start_utc = slot_start.astimezone(timezone.utc) - slot_end_utc = slot_end.astimezone(timezone.utc) - # past - if slot_start_utc <= now_utc + timedelta(minutes=5): - cursor += timedelta(minutes=interval) - continue - # overlap busy with buffers - blocked = False - for b0, b1 in busy: - a0 = slot_start_utc - timedelta(minutes=buf_before) - a1 = slot_end_utc + timedelta(minutes=buf_after) - if a0 < b1 and a1 > b0: - blocked = True - break - if not blocked: - slots.append( - { - "start": slot_start_utc.strftime("%Y-%m-%dT%H:%M:%SZ"), - "end": slot_end_utc.strftime("%Y-%m-%dT%H:%M:%SZ"), - "local": slot_start.strftime("%H:%M"), - } - ) - cursor += timedelta(minutes=interval) - - return { - "ok": True, - "day": day, - "timezone": tz_name, - "slots": slots, - "event_type": { - "slug": et["slug"], - "title": et["title"], - "length_minutes": length, - }, - "host": {"username": host["username"], "name": host["name"]}, - } - - -# —— bookings —— - - -def create_booking(data: dict[str, Any]) -> dict[str, Any]: - username = (data.get("username") or "").strip() - slug = (data.get("event_slug") or data.get("slug") or "").strip() - start = (data.get("start") or "").strip() - attendee_name = (data.get("attendee_name") or "").strip() - if not username or not slug or not start or not attendee_name: - raise ValueError("username_slug_start_attendee_required") - - et = get_event_type(username, slug) - if not et or not et.get("active"): - raise ValueError("event_type_not_found") - - start_utc = _parse_utc(start if "T" in start else start + "Z") - end_utc = start_utc + timedelta(minutes=int(et["length_minutes"])) - day = start_utc.astimezone( - ZoneInfo(et["host"].get("timezone") or "Asia/Shanghai") - ).date().isoformat() - - # re-validate slot still free - avail = available_slots(username, slug, day) - ok_starts = {s["start"] for s in avail["slots"]} - start_key = start_utc.strftime("%Y-%m-%dT%H:%M:%SZ") - if start_key not in ok_starts: - raise ValueError("slot_unavailable") - - locs = et.get("locations") or [] - loc_label = data.get("location") or ( - locs[0].get("label") if locs else "Coffeechat" - ) - now = _now() - bid = _id("bk") - uid = _id("uid") - with _conn() as c: - c.execute( - """INSERT INTO bookings( - id,uid,event_type_id,host_id,title,status,start_utc,end_utc,location,notes, - attendee_name,attendee_email,attendee_device,created_at,cancelled_at - ) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""", - ( - bid, - uid, - et["id"], - et["host"]["id"], - et["title"], - "accepted", - start_key, - end_utc.strftime("%Y-%m-%dT%H:%M:%SZ"), - loc_label, - data.get("notes") or "", - attendee_name, - data.get("attendee_email"), - data.get("attendee_device"), - now, - None, - ), - ) - return get_booking(bid) # type: ignore[return-value] - - -def get_booking(booking_id: str) -> dict[str, Any] | None: - with _conn() as c: - r = c.execute( - "SELECT * FROM bookings WHERE id=? OR uid=?", - (booking_id, booking_id), - ).fetchone() - if not r: - return None - h = c.execute("SELECT username,name,city FROM hosts WHERE id=?", (r["host_id"],)).fetchone() - return _booking_out(dict(r), host=dict(h) if h else None) - - -def list_bookings( - *, - host_username: str | None = None, - status: str | None = None, -) -> list[dict[str, Any]]: - with _conn() as c: - q = "SELECT b.* FROM bookings b" - args: list[Any] = [] - if host_username: - q += " JOIN hosts h ON h.id=b.host_id WHERE (h.username=? OR h.id=?)" - args.extend([host_username, host_username]) - else: - q += " WHERE 1=1" - if status: - q += " AND b.status=?" - args.append(status) - q += " ORDER BY b.start_utc DESC LIMIT 100" - rows = c.execute(q, args).fetchall() - out = [] - for r in rows: - h = c.execute( - "SELECT username,name,city FROM hosts WHERE id=?", - (r["host_id"],), - ).fetchone() - out.append(_booking_out(dict(r), host=dict(h) if h else None)) - return out - - -def cancel_booking(booking_id: str) -> dict[str, Any] | None: - with _conn() as c: - r = c.execute( - "SELECT id FROM bookings WHERE id=? OR uid=?", - (booking_id, booking_id), - ).fetchone() - if not r: - return None - c.execute( - "UPDATE bookings SET status='cancelled', cancelled_at=? WHERE id=?", - (_now(), r["id"]), - ) - return get_booking(r["id"]) - - -def _booking_out(r: dict[str, Any], host: dict[str, Any] | None = None) -> dict[str, Any]: - return { - "id": r["id"], - "uid": r["uid"], - "event_type_id": r["event_type_id"], - "host_id": r["host_id"], - "host": host, - "title": r["title"], - "status": r["status"], - "start": r["start_utc"], - "end": r["end_utc"], - "location": r.get("location") or "", - "notes": r.get("notes") or "", - "attendee": { - "name": r["attendee_name"], - "email": r.get("attendee_email"), - "device": r.get("attendee_device"), - }, - "created_at": r["created_at"], - "cancelled_at": r.get("cancelled_at"), - } +from coffee_svc.pb_store import ( # noqa: F401 + available_slots, + cancel_booking, + create_booking, + get_booking, + get_event_type, + get_host, + get_schedule, + init_db, + list_bookings, + list_hosts, + update_schedule, + upsert_event_type, +) diff --git a/apps/api/services/coffee_svc/store_sqlite_legacy.py b/apps/api/services/coffee_svc/store_sqlite_legacy.py new file mode 100644 index 0000000..e53128c --- /dev/null +++ b/apps/api/services/coffee_svc/store_sqlite_legacy.py @@ -0,0 +1,719 @@ +""" +SQLite store — domain shaped after Cal.com +(User/Host · EventType · Schedule · Availability · Booking · Attendee · Slot). +Secondary-dev reimplementation for Nomadro coffeechat (not upstream Cal runtime). +""" +from __future__ import annotations + +import json +import sqlite3 +import time +import uuid +from datetime import date, datetime, timedelta, timezone +from pathlib import Path +from typing import Any +from zoneinfo import ZoneInfo + +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 + + +WEEKDAYS = ("sun", "mon", "tue", "wed", "thu", "fri", "sat") +# Cal.com uses 0=Sunday … Python weekday() is 0=Monday — map carefully +PY_TO_CAL = {0: "mon", 1: "tue", 2: "wed", 3: "thu", 4: "fri", 5: "sat", 6: "sun"} + + +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 _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 hosts ( + id TEXT PRIMARY KEY, + username TEXT NOT NULL UNIQUE, + name TEXT NOT NULL, + bio TEXT NOT NULL DEFAULT '', + avatar TEXT, + timezone TEXT NOT NULL DEFAULT 'Asia/Shanghai', + city TEXT NOT NULL DEFAULT '', + created_at TEXT NOT NULL + ); + CREATE TABLE IF NOT EXISTS schedules ( + id TEXT PRIMARY KEY, + host_id TEXT NOT NULL, + name TEXT NOT NULL DEFAULT 'Working hours', + timezone TEXT NOT NULL DEFAULT 'Asia/Shanghai', + availability_json TEXT NOT NULL DEFAULT '[]', + created_at TEXT NOT NULL, + FOREIGN KEY(host_id) REFERENCES hosts(id) + ); + CREATE TABLE IF NOT EXISTS event_types ( + id TEXT PRIMARY KEY, + host_id TEXT NOT NULL, + schedule_id TEXT NOT NULL, + slug TEXT NOT NULL, + title TEXT NOT NULL, + description TEXT NOT NULL DEFAULT '', + length_minutes INTEGER NOT NULL DEFAULT 30, + slot_interval INTEGER NOT NULL DEFAULT 15, + buffer_before INTEGER NOT NULL DEFAULT 0, + buffer_after INTEGER NOT NULL DEFAULT 0, + locations_json TEXT NOT NULL DEFAULT '[]', + active INTEGER NOT NULL DEFAULT 1, + created_at TEXT NOT NULL, + UNIQUE(host_id, slug), + FOREIGN KEY(host_id) REFERENCES hosts(id), + FOREIGN KEY(schedule_id) REFERENCES schedules(id) + ); + CREATE TABLE IF NOT EXISTS bookings ( + id TEXT PRIMARY KEY, + uid TEXT NOT NULL UNIQUE, + event_type_id TEXT NOT NULL, + host_id TEXT NOT NULL, + title TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'accepted', + start_utc TEXT NOT NULL, + end_utc TEXT NOT NULL, + location TEXT NOT NULL DEFAULT '', + notes TEXT NOT NULL DEFAULT '', + attendee_name TEXT NOT NULL, + attendee_email TEXT, + attendee_device TEXT, + created_at TEXT NOT NULL, + cancelled_at TEXT, + FOREIGN KEY(event_type_id) REFERENCES event_types(id), + FOREIGN KEY(host_id) REFERENCES hosts(id) + ); + CREATE INDEX IF NOT EXISTS idx_bookings_host_start + ON bookings(host_id, start_utc); + """ + ) + _seed(c) + + +def _default_availability() -> list[dict[str, Any]]: + """Cal.com-style weekly windows (local schedule timezone).""" + windows = [{"days": ["mon", "tue", "wed", "thu", "fri"], "startTime": 600, "endTime": 720}] + # 10:00–12:00 and 14:00–18:00 as minutes from midnight + windows.append( + {"days": ["mon", "tue", "wed", "thu", "fri"], "startTime": 840, "endTime": 1080} + ) + windows.append({"days": ["sat"], "startTime": 660, "endTime": 900}) + return windows + + +def _seed(c: sqlite3.Connection) -> None: + if c.execute("SELECT 1 FROM hosts LIMIT 1").fetchone(): + return + now = _now() + hosts = [ + ("host_alice", "alice", "Alice Chen", "成都远程 · 爱咖啡闲聊产品与出海", "Chengdu", "Asia/Shanghai"), + ("host_bob", "bob", "Bob Rivera", "EN/ZH · coffee or video walkthrough", "Chiang Mai", "Asia/Bangkok"), + ("host_guest", "guest", "Guest Nomad", "演示主持人 · 可约 30 分钟咖啡聊", "Shenzhen", "Asia/Shanghai"), + ] + for hid, user, name, bio, city, tz in hosts: + c.execute( + """INSERT INTO hosts(id,username,name,bio,avatar,timezone,city,created_at) + VALUES(?,?,?,?,?,?,?,?)""", + (hid, user, name, bio, None, tz, city, now), + ) + sid = f"sch_{user}" + c.execute( + """INSERT INTO schedules(id,host_id,name,timezone,availability_json,created_at) + VALUES(?,?,?,?,?,?)""", + (sid, hid, "Working hours", tz, _json(_default_availability()), now), + ) + events = [ + ( + f"et_{user}_coffee", + "coffee-30", + "☕ 咖啡聊 30′", + "同城咖啡馆或语音闲聊,认识一下就好。", + 30, + [ + {"type": "inPerson", "label": "咖啡馆(见面后定)"}, + {"type": "link", "label": "语音/视频", "link": "/social/meetup"}, + ], + ), + ( + f"et_{user}_video", + "video-45", + "📹 视频深聊 45′", + "产品 / 副业 / 旅居经验,线上视频。", + 45, + [{"type": "link", "label": "Nomadro 视频厅", "link": "/social/meetup"}], + ), + ] + for eid, slug, title, desc, length, locs in events: + c.execute( + """INSERT INTO event_types( + id,host_id,schedule_id,slug,title,description,length_minutes, + slot_interval,buffer_before,buffer_after,locations_json,active,created_at + ) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)""", + ( + eid, + hid, + sid, + slug, + title, + desc, + length, + 15, + 0, + 0, + _json(locs), + 1, + now, + ), + ) + + # sample booking tomorrow 10:00 Asia/Shanghai for alice coffee + tz = ZoneInfo("Asia/Shanghai") + tomorrow = datetime.now(tz).date() + timedelta(days=1) + start_local = datetime(tomorrow.year, tomorrow.month, tomorrow.day, 10, 0, tzinfo=tz) + end_local = start_local + timedelta(minutes=30) + c.execute( + """INSERT INTO bookings( + id,uid,event_type_id,host_id,title,status,start_utc,end_utc,location,notes, + attendee_name,attendee_email,attendee_device,created_at,cancelled_at + ) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""", + ( + _id("bk"), + _id("uid"), + "et_alice_coffee", + "host_alice", + "☕ 咖啡聊 30′", + "accepted", + start_local.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), + end_local.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), + "咖啡馆(见面后定)", + "种子预约", + "Demo Attendee", + "demo@nomadro.com", + None, + now, + None, + ), + ) + + +# —— hosts / event types —— + + +def list_hosts() -> list[dict[str, Any]]: + with _conn() as c: + rows = c.execute("SELECT * FROM hosts ORDER BY username").fetchall() + out = [] + for r in rows: + n = c.execute( + "SELECT COUNT(*) AS n FROM event_types WHERE host_id=? AND active=1", + (r["id"],), + ).fetchone()["n"] + out.append(_host_out(dict(r), event_count=n)) + return out + + +def get_host(username: str) -> dict[str, Any] | None: + with _conn() as c: + r = c.execute( + "SELECT * FROM hosts WHERE username=? OR id=?", + (username, username), + ).fetchone() + if not r: + return None + events = [ + _event_out(dict(e)) + for e in c.execute( + "SELECT * FROM event_types WHERE host_id=? AND active=1 ORDER BY length_minutes", + (r["id"],), + ).fetchall() + ] + h = _host_out(dict(r), event_count=len(events)) + h["event_types"] = events + return h + + +def _host_out(r: dict[str, Any], *, event_count: int = 0) -> dict[str, Any]: + return { + "id": r["id"], + "username": r["username"], + "name": r["name"], + "bio": r.get("bio") or "", + "avatar": r.get("avatar"), + "timezone": r.get("timezone") or "Asia/Shanghai", + "city": r.get("city") or "", + "event_count": event_count, + "created_at": r.get("created_at"), + } + + +def get_event_type(username: str, slug: str) -> dict[str, Any] | None: + with _conn() as c: + h = c.execute( + "SELECT * FROM hosts WHERE username=? OR id=?", + (username, username), + ).fetchone() + if not h: + return None + e = c.execute( + "SELECT * FROM event_types WHERE host_id=? AND slug=?", + (h["id"], slug), + ).fetchone() + if not e: + return None + out = _event_out(dict(e)) + out["host"] = _host_out(dict(h)) + sch = c.execute( + "SELECT * FROM schedules WHERE id=?", (e["schedule_id"],) + ).fetchone() + if sch: + out["schedule"] = _schedule_out(dict(sch)) + return out + + +def _event_out(r: dict[str, Any]) -> dict[str, Any]: + return { + "id": r["id"], + "host_id": r["host_id"], + "schedule_id": r["schedule_id"], + "slug": r["slug"], + "title": r["title"], + "description": r.get("description") or "", + "length_minutes": int(r["length_minutes"]), + "slot_interval": int(r.get("slot_interval") or 15), + "buffer_before": int(r.get("buffer_before") or 0), + "buffer_after": int(r.get("buffer_after") or 0), + "locations": _parse(r.get("locations_json"), []), + "active": bool(r.get("active")), + "created_at": r.get("created_at"), + } + + +def _schedule_out(r: dict[str, Any]) -> dict[str, Any]: + return { + "id": r["id"], + "host_id": r["host_id"], + "name": r["name"], + "timezone": r["timezone"], + "availability": _parse(r.get("availability_json"), []), + "created_at": r["created_at"], + } + + +def get_schedule(host_username: str) -> dict[str, Any] | None: + with _conn() as c: + h = c.execute( + "SELECT * FROM hosts WHERE username=? OR id=?", + (host_username, host_username), + ).fetchone() + if not h: + return None + s = c.execute( + "SELECT * FROM schedules WHERE host_id=? ORDER BY created_at LIMIT 1", + (h["id"],), + ).fetchone() + return _schedule_out(dict(s)) if s else None + + +def update_schedule( + host_username: str, + *, + availability: list[dict[str, Any]] | None = None, + timezone_name: str | None = None, + name: str | None = None, +) -> dict[str, Any]: + with _conn() as c: + h = c.execute( + "SELECT * FROM hosts WHERE username=? OR id=?", + (host_username, host_username), + ).fetchone() + if not h: + raise ValueError("host_not_found") + s = c.execute( + "SELECT * FROM schedules WHERE host_id=? ORDER BY created_at LIMIT 1", + (h["id"],), + ).fetchone() + if not s: + raise ValueError("schedule_not_found") + avail = ( + _json(availability) + if availability is not None + else s["availability_json"] + ) + tz = timezone_name or s["timezone"] + nm = name or s["name"] + c.execute( + "UPDATE schedules SET availability_json=?, timezone=?, name=? WHERE id=?", + (avail, tz, nm, s["id"]), + ) + if timezone_name: + c.execute( + "UPDATE hosts SET timezone=? WHERE id=?", + (timezone_name, h["id"]), + ) + row = c.execute("SELECT * FROM schedules WHERE id=?", (s["id"],)).fetchone() + return _schedule_out(dict(row)) + + +def upsert_event_type( + host_username: str, + data: dict[str, Any], +) -> dict[str, Any]: + slug = (data.get("slug") or "").strip() + title = (data.get("title") or "").strip() + if not slug or not title: + raise ValueError("slug_and_title_required") + with _conn() as c: + h = c.execute( + "SELECT * FROM hosts WHERE username=? OR id=?", + (host_username, host_username), + ).fetchone() + if not h: + raise ValueError("host_not_found") + sch = c.execute( + "SELECT id FROM schedules WHERE host_id=? LIMIT 1", + (h["id"],), + ).fetchone() + if not sch: + raise ValueError("schedule_not_found") + existing = c.execute( + "SELECT * FROM event_types WHERE host_id=? AND slug=?", + (h["id"], slug), + ).fetchone() + length = int(data.get("length_minutes") or 30) + interval = int(data.get("slot_interval") or 15) + locs = data.get("locations") or [ + {"type": "inPerson", "label": "咖啡馆(见面后定)"} + ] + now = _now() + if existing: + c.execute( + """UPDATE event_types SET title=?,description=?,length_minutes=?, + slot_interval=?,locations_json=?,active=? WHERE id=?""", + ( + title, + data.get("description") or "", + length, + interval, + _json(locs), + 1 if data.get("active", True) else 0, + existing["id"], + ), + ) + eid = existing["id"] + else: + eid = _id("et") + c.execute( + """INSERT INTO event_types( + id,host_id,schedule_id,slug,title,description,length_minutes, + slot_interval,buffer_before,buffer_after,locations_json,active,created_at + ) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)""", + ( + eid, + h["id"], + sch["id"], + slug, + title, + data.get("description") or "", + length, + interval, + int(data.get("buffer_before") or 0), + int(data.get("buffer_after") or 0), + _json(locs), + 1, + now, + ), + ) + row = c.execute("SELECT * FROM event_types WHERE id=?", (eid,)).fetchone() + return _event_out(dict(row)) + + +# —— slots (Cal.com getSchedule / availableSlots parity) —— + + +def _parse_utc(s: str) -> datetime: + if s.endswith("Z"): + s = s[:-1] + "+00:00" + return datetime.fromisoformat(s).astimezone(timezone.utc) + + +def available_slots( + username: str, + event_slug: str, + day: str, +) -> dict[str, Any]: + """Return bookable UTC slots for a local calendar day (YYYY-MM-DD).""" + et = get_event_type(username, event_slug) + if not et or not et.get("active"): + raise ValueError("event_type_not_found") + host = et["host"] + sch = et.get("schedule") or {} + tz_name = sch.get("timezone") or host.get("timezone") or "Asia/Shanghai" + try: + tz = ZoneInfo(tz_name) + except Exception: + tz = ZoneInfo("Asia/Shanghai") + tz_name = "Asia/Shanghai" + + try: + day_d = date.fromisoformat(day) + except ValueError as e: + raise ValueError("invalid_day") from e + + length = int(et["length_minutes"]) + interval = int(et.get("slot_interval") or 15) + buf_before = int(et.get("buffer_before") or 0) + buf_after = int(et.get("buffer_after") or 0) + cal_day = PY_TO_CAL[day_d.weekday()] + windows = [ + w + for w in (sch.get("availability") or []) + if cal_day in (w.get("days") or []) + ] + if not windows: + return { + "ok": True, + "day": day, + "timezone": tz_name, + "slots": [], + "event_type": {"slug": et["slug"], "length_minutes": length}, + } + + # busy from accepted bookings that day (host local) + day_start = datetime(day_d.year, day_d.month, day_d.day, 0, 0, tzinfo=tz) + day_end = day_start + timedelta(days=1) + with _conn() as c: + busy_rows = c.execute( + """SELECT start_utc,end_utc FROM bookings + WHERE host_id=? AND status='accepted' + AND start_utc < ? AND end_utc > ?""", + ( + host["id"], + day_end.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), + day_start.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), + ), + ).fetchall() + busy = [(_parse_utc(b["start_utc"]), _parse_utc(b["end_utc"])) for b in busy_rows] + + now_utc = datetime.now(timezone.utc) + slots: list[dict[str, str]] = [] + for w in windows: + start_m = int(w.get("startTime") or 0) + end_m = int(w.get("endTime") or 0) + cursor = day_start + timedelta(minutes=start_m) + window_end = day_start + timedelta(minutes=end_m) + while cursor + timedelta(minutes=length) <= window_end: + slot_start = cursor + slot_end = cursor + timedelta(minutes=length) + slot_start_utc = slot_start.astimezone(timezone.utc) + slot_end_utc = slot_end.astimezone(timezone.utc) + # past + if slot_start_utc <= now_utc + timedelta(minutes=5): + cursor += timedelta(minutes=interval) + continue + # overlap busy with buffers + blocked = False + for b0, b1 in busy: + a0 = slot_start_utc - timedelta(minutes=buf_before) + a1 = slot_end_utc + timedelta(minutes=buf_after) + if a0 < b1 and a1 > b0: + blocked = True + break + if not blocked: + slots.append( + { + "start": slot_start_utc.strftime("%Y-%m-%dT%H:%M:%SZ"), + "end": slot_end_utc.strftime("%Y-%m-%dT%H:%M:%SZ"), + "local": slot_start.strftime("%H:%M"), + } + ) + cursor += timedelta(minutes=interval) + + return { + "ok": True, + "day": day, + "timezone": tz_name, + "slots": slots, + "event_type": { + "slug": et["slug"], + "title": et["title"], + "length_minutes": length, + }, + "host": {"username": host["username"], "name": host["name"]}, + } + + +# —— bookings —— + + +def create_booking(data: dict[str, Any]) -> dict[str, Any]: + username = (data.get("username") or "").strip() + slug = (data.get("event_slug") or data.get("slug") or "").strip() + start = (data.get("start") or "").strip() + attendee_name = (data.get("attendee_name") or "").strip() + if not username or not slug or not start or not attendee_name: + raise ValueError("username_slug_start_attendee_required") + + et = get_event_type(username, slug) + if not et or not et.get("active"): + raise ValueError("event_type_not_found") + + start_utc = _parse_utc(start if "T" in start else start + "Z") + end_utc = start_utc + timedelta(minutes=int(et["length_minutes"])) + day = start_utc.astimezone( + ZoneInfo(et["host"].get("timezone") or "Asia/Shanghai") + ).date().isoformat() + + # re-validate slot still free + avail = available_slots(username, slug, day) + ok_starts = {s["start"] for s in avail["slots"]} + start_key = start_utc.strftime("%Y-%m-%dT%H:%M:%SZ") + if start_key not in ok_starts: + raise ValueError("slot_unavailable") + + locs = et.get("locations") or [] + loc_label = data.get("location") or ( + locs[0].get("label") if locs else "Coffeechat" + ) + now = _now() + bid = _id("bk") + uid = _id("uid") + with _conn() as c: + c.execute( + """INSERT INTO bookings( + id,uid,event_type_id,host_id,title,status,start_utc,end_utc,location,notes, + attendee_name,attendee_email,attendee_device,created_at,cancelled_at + ) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""", + ( + bid, + uid, + et["id"], + et["host"]["id"], + et["title"], + "accepted", + start_key, + end_utc.strftime("%Y-%m-%dT%H:%M:%SZ"), + loc_label, + data.get("notes") or "", + attendee_name, + data.get("attendee_email"), + data.get("attendee_device"), + now, + None, + ), + ) + return get_booking(bid) # type: ignore[return-value] + + +def get_booking(booking_id: str) -> dict[str, Any] | None: + with _conn() as c: + r = c.execute( + "SELECT * FROM bookings WHERE id=? OR uid=?", + (booking_id, booking_id), + ).fetchone() + if not r: + return None + h = c.execute("SELECT username,name,city FROM hosts WHERE id=?", (r["host_id"],)).fetchone() + return _booking_out(dict(r), host=dict(h) if h else None) + + +def list_bookings( + *, + host_username: str | None = None, + status: str | None = None, +) -> list[dict[str, Any]]: + with _conn() as c: + q = "SELECT b.* FROM bookings b" + args: list[Any] = [] + if host_username: + q += " JOIN hosts h ON h.id=b.host_id WHERE (h.username=? OR h.id=?)" + args.extend([host_username, host_username]) + else: + q += " WHERE 1=1" + if status: + q += " AND b.status=?" + args.append(status) + q += " ORDER BY b.start_utc DESC LIMIT 100" + rows = c.execute(q, args).fetchall() + out = [] + for r in rows: + h = c.execute( + "SELECT username,name,city FROM hosts WHERE id=?", + (r["host_id"],), + ).fetchone() + out.append(_booking_out(dict(r), host=dict(h) if h else None)) + return out + + +def cancel_booking(booking_id: str) -> dict[str, Any] | None: + with _conn() as c: + r = c.execute( + "SELECT id FROM bookings WHERE id=? OR uid=?", + (booking_id, booking_id), + ).fetchone() + if not r: + return None + c.execute( + "UPDATE bookings SET status='cancelled', cancelled_at=? WHERE id=?", + (_now(), r["id"]), + ) + return get_booking(r["id"]) + + +def _booking_out(r: dict[str, Any], host: dict[str, Any] | None = None) -> dict[str, Any]: + return { + "id": r["id"], + "uid": r["uid"], + "event_type_id": r["event_type_id"], + "host_id": r["host_id"], + "host": host, + "title": r["title"], + "status": r["status"], + "start": r["start_utc"], + "end": r["end_utc"], + "location": r.get("location") or "", + "notes": r.get("notes") or "", + "attendee": { + "name": r["attendee_name"], + "email": r.get("attendee_email"), + "device": r.get("attendee_device"), + }, + "created_at": r["created_at"], + "cancelled_at": r.get("cancelled_at"), + } diff --git a/apps/api/services/community_svc/config.py b/apps/api/services/community_svc/config.py index 0c326b5..5d33278 100644 --- a/apps/api/services/community_svc/config.py +++ b/apps/api/services/community_svc/config.py @@ -5,9 +5,10 @@ class Settings(BaseSettings): # 忽略 .env 中其它模块键,避免本地/统一 env 拖垮启动(不改业务字段) model_config = SettingsConfigDict(env_file=".env", extra="ignore") + # .com/US: same-box PB. China/hackrobot only via env on that deploy. pocketbase_url: str = "http://127.0.0.1:8090" - pocketbase_admin_email: str = "admin@nomadro.com" - pocketbase_admin_password: str = "Xiao4669805" + pocketbase_admin_email: str = "" + pocketbase_admin_password: str = "" api_host: str = "0.0.0.0" api_port: int = 8000 cors_origins: str = "http://localhost:3000,http://127.0.0.1:3000" diff --git a/apps/api/services/community_svc/services/auth.py b/apps/api/services/community_svc/services/auth.py index 51455ed..f46bd8c 100644 --- a/apps/api/services/community_svc/services/auth.py +++ b/apps/api/services/community_svc/services/auth.py @@ -66,27 +66,31 @@ def _migrate_json_to_pb() -> None: data = json.loads(STORE_PATH.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError): return - if pb.list_records("nomad_accounts", per_page=1).get("totalItems", 0) > 0: + try: + if pb.list_records("nomad_accounts", per_page=1).get("totalItems", 0) > 0: + return + for email, user in (data.get("users") or {}).items(): + uid = user.get("id", secrets.token_hex(8)) + pb.create_record( + "nomad_accounts", + { + "email": email, + "passwordHash": user.get("password_hash", ""), + "name": user.get("name", ""), + "avatar": user.get("avatar", "🧑‍💻"), + "legacyUserId": uid, + "favorites": data.get("favorites", {}).get(uid, []), + "plan": data.get("plans", {}).get(uid, _empty_plan()), + }, + ) + for token, uid in (data.get("sessions") or {}).items(): + pb.create_record( + "nomad_sessions", + {"token": token, "userId": uid, "expiresAt": int(time.time()) + 86400 * 30}, + ) + except Exception: + # Online PB may lack legacy community collections — never block API boot return - for email, user in (data.get("users") or {}).items(): - uid = user.get("id", secrets.token_hex(8)) - pb.create_record( - "nomad_accounts", - { - "email": email, - "passwordHash": user.get("password_hash", ""), - "name": user.get("name", ""), - "avatar": user.get("avatar", "🧑‍💻"), - "legacyUserId": uid, - "favorites": data.get("favorites", {}).get(uid, []), - "plan": data.get("plans", {}).get(uid, _empty_plan()), - }, - ) - for token, uid in (data.get("sessions") or {}).items(): - pb.create_record( - "nomad_sessions", - {"token": token, "userId": uid, "expiresAt": int(time.time()) + 86400 * 30}, - ) def _restore_json() -> bool: diff --git a/apps/api/services/ebook_svc/routers/social_ugc_admin.py b/apps/api/services/ebook_svc/routers/social_ugc_admin.py index bc03cbd..a30efbe 100644 --- a/apps/api/services/ebook_svc/routers/social_ugc_admin.py +++ b/apps/api/services/ebook_svc/routers/social_ugc_admin.py @@ -20,6 +20,8 @@ class RosterPatch(BaseModel): linktree: str | None = None skills: str | None = None bio: str | None = None + restore: bool | None = None + status: str | None = None @router.get("/overview") @@ -27,6 +29,28 @@ async def get_overview(_: str = Depends(require_admin)) -> dict[str, Any]: return ugc.overview() +@router.get("/stats") +async def get_stats(_: str = Depends(require_admin)) -> dict[str, Any]: + """Dashboard visualization payload (counts, city bars, day series, soft-delete).""" + try: + return ugc.stats() + except Exception as e: + raise HTTPException(503, f"social stats unavailable: {e}") from e + + +@router.get("/archives") +async def get_archives( + entity: str = "", + limit: int = Query(100, ge=1, le=500), + offset: int = Query(0, ge=0), + _: str = Depends(require_admin), +) -> dict[str, Any]: + try: + return ugc.list_archives(entity=entity, limit=limit, offset=offset) + except Exception as e: + raise HTTPException(503, f"archives unavailable: {e}") from e + + @router.get("/messages") async def get_messages( channelId: str = "", @@ -45,7 +69,7 @@ async def get_messages( async def del_message(message_id: str, _: str = Depends(require_admin)) -> dict[str, Any]: if not ugc.delete_message(message_id): raise HTTPException(404, "消息不存在") - return {"ok": True} + return {"ok": True, "soft": True, "archived": True} @router.get("/roster") @@ -75,7 +99,7 @@ async def put_roster( async def del_roster(guest_id: str, _: str = Depends(require_admin)) -> dict[str, Any]: if not ugc.delete_roster(guest_id): raise HTTPException(404, "介绍不存在") - return {"ok": True} + return {"ok": True, "soft": True, "archived": True} @router.get("/reviews") @@ -95,7 +119,7 @@ async def get_reviews( async def del_review(review_id: str, _: str = Depends(require_admin)) -> dict[str, Any]: if not ugc.delete_review(review_id): raise HTTPException(404, "评价不存在") - return {"ok": True} + return {"ok": True, "soft": True, "archived": True} @router.get("/gig-apps") @@ -115,7 +139,7 @@ async def get_gig_apps( async def del_gig_app(app_id: str, _: str = Depends(require_admin)) -> dict[str, Any]: if not ugc.delete_gig_app(app_id): raise HTTPException(404, "申请不存在") - return {"ok": True} + return {"ok": True, "soft": True, "archived": True} @router.get("/feedback") @@ -134,7 +158,7 @@ async def get_feedback( async def del_feedback(fid: str, _: str = Depends(require_admin)) -> dict[str, Any]: if not ugc.delete_feedback(fid): raise HTTPException(404, "反馈不存在") - return {"ok": True} + return {"ok": True, "soft": True, "archived": True} class CatalogBody(BaseModel): @@ -195,3 +219,25 @@ async def put_catalog(body: CatalogBody, _: str = Depends(require_admin)) -> dic "videos": catalogs.get("videos") if isinstance(catalogs.get("videos"), list) else [], }, } + + +@router.get("/detail/{entity}/{entity_id}") +async def get_entity_detail( + entity: str, entity_id: str, _: str = Depends(require_admin) +) -> dict[str, Any]: + """Detail page: live record + archive history. Soft-delete never erases payload.""" + allowed = { + "roster", + "messages", + "reviews", + "gigApps", + "feedback", + "skills", + "liveness", + } + if entity not in allowed: + raise HTTPException(404, "unknown entity") + item = ugc.get_detail(entity, entity_id) + if not item: + raise HTTPException(404, "记录不存在(或仅存于存档,请查 /archives)") + return item diff --git a/apps/api/services/ebook_svc/services/social_ugc.py b/apps/api/services/ebook_svc/services/social_ugc.py index 9cccfb2..e80c5dd 100644 --- a/apps/api/services/ebook_svc/services/social_ugc.py +++ b/apps/api/services/ebook_svc/services/social_ugc.py @@ -1,327 +1,127 @@ -"""游民社区 UGC 管理 — 直连 social.db(与 nomadro-social 同库)。 +"""游民社区 UGC 管理 — PocketBase(与 social_svc 同库)。 -默认路径可通过 SOCIAL_DB_PATH 覆盖;生产:/var/www/nomadro-data/social/social.db -只读写 messages / roster / cafe_reviews / gig_apps / feedback,不碰 remote-config catalogs。 +历史 SQLite social.db 已停用;管理后台经本模块读写 PB collections。 """ from __future__ import annotations -import os -import sqlite3 -from contextlib import contextmanager +import sys from pathlib import Path -from typing import Any, Iterator +from typing import Any -from ebook_svc.core.sqlite_util import connect as _connect - -_DEFAULT = Path("/var/www/nomadro-data/social/social.db") -SOCIAL_DB_PATH = Path(os.getenv("SOCIAL_DB_PATH", str(_DEFAULT))).resolve() +# ebook_svc may run without social_svc on PYTHONPATH +_SERVICES = Path(__file__).resolve().parents[2] +if str(_SERVICES) not in sys.path: + sys.path.insert(0, str(_SERVICES)) -@contextmanager -def _db(*, readonly: bool = False) -> Iterator[sqlite3.Connection]: - SOCIAL_DB_PATH.parent.mkdir(parents=True, exist_ok=True) - if readonly and SOCIAL_DB_PATH.is_file(): - uri = f"file:{SOCIAL_DB_PATH.as_posix()}?mode=ro" - conn = sqlite3.connect(uri, uri=True, timeout=30.0) - conn.row_factory = sqlite3.Row - else: - conn = _connect(SOCIAL_DB_PATH) - try: - yield conn - if not readonly: - conn.commit() - except Exception: - if not readonly: - conn.rollback() - raise - finally: - conn.close() +def _pb(): + from social_svc import pb_data + + return pb_data def available() -> dict[str, Any]: - exists = SOCIAL_DB_PATH.is_file() - size = SOCIAL_DB_PATH.stat().st_size if exists else 0 - writable = False - if exists: - try: - writable = os.access(SOCIAL_DB_PATH, os.W_OK) - except Exception: - writable = False + try: + h = _pb().health() return { - "ok": True, - "path": str(SOCIAL_DB_PATH), - "exists": exists, - "bytes": size, - "writable": writable, + "ok": bool(h.get("ok")), + "path": h.get("pb") or h.get("db") or "", + "exists": True, + "bytes": 0, + "writable": True, + "backend": "pocketbase", + } + except Exception as e: + return { + "ok": False, + "path": "", + "exists": False, + "bytes": 0, + "writable": False, + "error": str(e), + "backend": "pocketbase", } def overview() -> dict[str, Any]: + try: + return _pb().admin_overview() + except Exception as e: info = available() - counts = { + return { + **info, + "counts": { "messages": 0, "roster": 0, "reviews": 0, "gigApps": 0, "feedback": 0, + }, + "error": str(e), } - if not info["exists"]: - return {**info, "counts": counts} - try: - with _db(readonly=True) as c: - counts["messages"] = c.execute("SELECT COUNT(*) AS n FROM messages").fetchone()["n"] - counts["roster"] = c.execute("SELECT COUNT(*) AS n FROM roster").fetchone()["n"] - counts["reviews"] = c.execute("SELECT COUNT(*) AS n FROM cafe_reviews").fetchone()["n"] - counts["gigApps"] = c.execute("SELECT COUNT(*) AS n FROM gig_apps").fetchone()["n"] - counts["feedback"] = c.execute("SELECT COUNT(*) AS n FROM feedback").fetchone()["n"] - except Exception as e: - return {**info, "counts": counts, "error": str(e)} - return {**info, "counts": counts} def list_messages( - *, - channel_id: str = "", - q: str = "", - limit: int = 100, - offset: int = 0, + *, + channel_id: str = "", + q: str = "", + limit: int = 100, + offset: int = 0, ) -> dict[str, Any]: - limit = max(1, min(int(limit or 100), 500)) - offset = max(0, int(offset or 0)) - clauses: list[str] = [] - params: list[Any] = [] - if channel_id.strip(): - clauses.append("channel_id=?") - params.append(channel_id.strip()) - if q.strip(): - clauses.append("(author LIKE ? OR text LIKE ? OR guest_id LIKE ?)") - like = f"%{q.strip()}%" - params.extend([like, like, like]) - where = f" WHERE {' AND '.join(clauses)}" if clauses else "" - with _db(readonly=True) as c: - total = c.execute(f"SELECT COUNT(*) AS n FROM messages{where}", tuple(params)).fetchone()["n"] - rows = c.execute( - f""" - SELECT id, channel_id, author, text, guest_id, created_at - FROM messages{where} - ORDER BY created_at DESC, rowid DESC - LIMIT ? OFFSET ? - """, - (*params, limit, offset), - ).fetchall() - items = [ - { - "id": r["id"], - "channelId": r["channel_id"], - "author": r["author"], - "text": r["text"], - "guestId": r["guest_id"], - "at": r["created_at"], - } - for r in rows - ] - return {"ok": True, "total": total, "items": items} + return _pb().admin_list_messages( + channel_id=channel_id, q=q, limit=limit, offset=offset + ) def delete_message(message_id: str) -> bool: - with _db() as c: - cur = c.execute("DELETE FROM messages WHERE id=?", (message_id,)) - return cur.rowcount > 0 + return _pb().admin_delete_message(message_id) def list_roster(*, q: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]: - limit = max(1, min(int(limit or 100), 500)) - offset = max(0, int(offset or 0)) - clauses: list[str] = [] - params: list[Any] = [] - if q.strip(): - clauses.append("(name LIKE ? OR city LIKE ? OR title LIKE ? OR guest_id LIKE ? OR bio LIKE ?)") - like = f"%{q.strip()}%" - params.extend([like, like, like, like, like]) - where = f" WHERE {' AND '.join(clauses)}" if clauses else "" - with _db(readonly=True) as c: - total = c.execute(f"SELECT COUNT(*) AS n FROM roster{where}", tuple(params)).fetchone()["n"] - rows = c.execute( - f""" - SELECT guest_id, name, title, city, phone, linktree, skills, bio, updated_at - FROM roster{where} - ORDER BY updated_at DESC - LIMIT ? OFFSET ? - """, - (*params, limit, offset), - ).fetchall() - items = [ - { - "guestId": r["guest_id"], - "name": r["name"], - "title": r["title"] or "", - "city": r["city"] or "", - "phone": r["phone"] or "", - "linktree": r["linktree"] or "", - "skills": r["skills"] or "", - "bio": r["bio"] or "", - "updatedAt": r["updated_at"], - } - for r in rows - ] - return {"ok": True, "total": total, "items": items} + return _pb().admin_list_roster(q=q, limit=limit, offset=offset) def update_roster(guest_id: str, patch: dict[str, Any]) -> dict[str, Any] | None: - with _db() as c: - row = c.execute("SELECT * FROM roster WHERE guest_id=?", (guest_id,)).fetchone() - if not row: - return None - fields = { - "name": str(patch.get("name", row["name"] or ""))[:64] or "游民", - "title": str(patch.get("title", row["title"] or ""))[:80], - "city": str(patch.get("city", row["city"] or ""))[:64], - "phone": str(patch.get("phone", row["phone"] or ""))[:32], - "linktree": str(patch.get("linktree", row["linktree"] or ""))[:240], - "skills": str(patch.get("skills", row["skills"] or ""))[:200], - "bio": str(patch.get("bio", row["bio"] or ""))[:2000], - } - import time - - updated = time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime()) - c.execute( - """ - UPDATE roster SET name=?, title=?, city=?, phone=?, linktree=?, skills=?, bio=?, updated_at=? - WHERE guest_id=? - """, - ( - fields["name"], - fields["title"], - fields["city"], - fields["phone"], - fields["linktree"], - fields["skills"], - fields["bio"], - updated, - guest_id, - ), - ) - return {**fields, "guestId": guest_id, "updatedAt": updated} + return _pb().admin_update_roster(guest_id, patch) def delete_roster(guest_id: str) -> bool: - with _db() as c: - cur = c.execute("DELETE FROM roster WHERE guest_id=?", (guest_id,)) - return cur.rowcount > 0 + return _pb().admin_delete_roster(guest_id) def list_reviews(*, cafe_id: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]: - limit = max(1, min(int(limit or 100), 500)) - offset = max(0, int(offset or 0)) - clauses: list[str] = [] - params: list[Any] = [] - if cafe_id.strip(): - clauses.append("cafe_id=?") - params.append(cafe_id.strip()) - where = f" WHERE {' AND '.join(clauses)}" if clauses else "" - with _db(readonly=True) as c: - total = c.execute(f"SELECT COUNT(*) AS n FROM cafe_reviews{where}", tuple(params)).fetchone()["n"] - rows = c.execute( - f""" - SELECT id, cafe_id, author, score, text, photo_note, guest_id, created_at - FROM cafe_reviews{where} - ORDER BY created_at DESC - LIMIT ? OFFSET ? - """, - (*params, limit, offset), - ).fetchall() - items = [ - { - "id": r["id"], - "cafeId": r["cafe_id"], - "author": r["author"], - "score": r["score"], - "text": r["text"], - "photoNote": r["photo_note"] or "", - "guestId": r["guest_id"], - "at": r["created_at"], - } - for r in rows - ] - return {"ok": True, "total": total, "items": items} + return _pb().admin_list_cafe_reviews(cafe_id=cafe_id, limit=limit, offset=offset) def delete_review(review_id: str) -> bool: - with _db() as c: - cur = c.execute("DELETE FROM cafe_reviews WHERE id=?", (review_id,)) - return cur.rowcount > 0 + return _pb().admin_delete_cafe_review(review_id) def list_gig_apps(*, gig_id: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]: - limit = max(1, min(int(limit or 100), 500)) - offset = max(0, int(offset or 0)) - clauses: list[str] = [] - params: list[Any] = [] - if gig_id.strip(): - clauses.append("gig_id=?") - params.append(gig_id.strip()) - where = f" WHERE {' AND '.join(clauses)}" if clauses else "" - with _db(readonly=True) as c: - total = c.execute(f"SELECT COUNT(*) AS n FROM gig_apps{where}", tuple(params)).fetchone()["n"] - rows = c.execute( - f""" - SELECT id, gig_id, name, contact, note, guest_id, created_at - FROM gig_apps{where} - ORDER BY created_at DESC - LIMIT ? OFFSET ? - """, - (*params, limit, offset), - ).fetchall() - items = [ - { - "id": r["id"], - "gigId": r["gig_id"], - "name": r["name"], - "contact": r["contact"], - "note": r["note"] or "", - "guestId": r["guest_id"], - "at": r["created_at"], - } - for r in rows - ] - return {"ok": True, "total": total, "items": items} + return _pb().admin_list_gig_apps(gig_id=gig_id, limit=limit, offset=offset) def delete_gig_app(app_id: str) -> bool: - with _db() as c: - cur = c.execute("DELETE FROM gig_apps WHERE id=?", (app_id,)) - return cur.rowcount > 0 + return _pb().admin_delete_gig_app(app_id) def list_feedback(*, limit: int = 100, offset: int = 0) -> dict[str, Any]: - limit = max(1, min(int(limit or 100), 500)) - offset = max(0, int(offset or 0)) - with _db(readonly=True) as c: - total = c.execute("SELECT COUNT(*) AS n FROM feedback").fetchone()["n"] - rows = c.execute( - """ - SELECT id, kind, text, contact, guest_id, created_at - FROM feedback - ORDER BY created_at DESC - LIMIT ? OFFSET ? - """, - (limit, offset), - ).fetchall() - items = [ - { - "id": r["id"], - "kind": r["kind"], - "text": r["text"], - "contact": r["contact"] or "", - "guestId": r["guest_id"], - "at": r["created_at"], - } - for r in rows - ] - return {"ok": True, "total": total, "items": items} + return _pb().admin_list_feedback(limit=limit, offset=offset) def delete_feedback(fid: str) -> bool: - with _db() as c: - cur = c.execute("DELETE FROM feedback WHERE id=?", (fid,)) - return cur.rowcount > 0 + return _pb().admin_delete_feedback(fid) + + +def stats() -> dict[str, Any]: + return _pb().admin_stats() + + +def get_detail(entity: str, entity_id: str) -> dict[str, Any] | None: + return _pb().admin_get_detail(entity, entity_id) + + +def list_archives( + *, entity: str = "", limit: int = 100, offset: int = 0 +) -> dict[str, Any]: + return _pb().admin_list_archives(entity=entity, limit=limit, offset=offset) diff --git a/apps/api/services/nomadro_pb/__init__.py b/apps/api/services/nomadro_pb/__init__.py new file mode 100644 index 0000000..f40eff4 --- /dev/null +++ b/apps/api/services/nomadro_pb/__init__.py @@ -0,0 +1,22 @@ +"""Shared PocketBase access for Nomadro FastAPI services (.com/US first).""" +from __future__ import annotations + +from nomadro_pb.client import PocketBaseClient, PocketBaseError, get_pb, pb_quote +from nomadro_pb.config import DEFAULT_PB_URL, PB_ADMIN_EMAIL, PB_URL +from nomadro_pb.ensure import ensure_all_collections, ensure_once + +# Back-compat alias — was wrongly pointing at hackrobot.cn +ONLINE_PB_URL = DEFAULT_PB_URL + +__all__ = [ + "DEFAULT_PB_URL", + "ONLINE_PB_URL", + "PB_ADMIN_EMAIL", + "PB_URL", + "PocketBaseClient", + "PocketBaseError", + "ensure_all_collections", + "ensure_once", + "get_pb", + "pb_quote", +] diff --git a/apps/api/services/nomadro_pb/client.py b/apps/api/services/nomadro_pb/client.py new file mode 100644 index 0000000..2a8e13d --- /dev/null +++ b/apps/api/services/nomadro_pb/client.py @@ -0,0 +1,197 @@ +"""Shared PocketBase admin client for all FastAPI verticals.""" +from __future__ import annotations + +import logging +import time +from typing import Any + +import httpx + +from nomadro_pb.config import PB_ADMIN_EMAIL, PB_ADMIN_PASSWORD, PB_URL + +log = logging.getLogger("nomadro_pb") + + +class PocketBaseError(RuntimeError): + pass + + +def pb_quote(value: str) -> str: + return '"' + str(value).replace("\\", "\\\\").replace('"', '\\"') + '"' + + +class PocketBaseClient: + def __init__( + self, + *, + base_url: str | None = None, + email: str | None = None, + password: str | None = None, + ) -> None: + self.base_url = (base_url or PB_URL).rstrip("/") + self.email = email or PB_ADMIN_EMAIL + self.password = password or PB_ADMIN_PASSWORD + self._admin_token: str | None = None + self._token_at = 0.0 + self._client: httpx.Client | None = None + + def _http(self) -> httpx.Client: + if self._client is None: + self._client = httpx.Client(timeout=25.0, trust_env=False) + return self._client + + def request( + self, + method: str, + path: str, + *, + admin: bool = False, + json: dict[str, Any] | None = None, + params: dict[str, Any] | None = None, + ) -> Any: + headers: dict[str, str] = {} + if admin: + headers["Authorization"] = self.admin_token() + url = f"{self.base_url}{path}" + res = self._http().request(method, url, headers=headers, json=json, params=params) + if res.status_code >= 400: + try: + detail = res.json() + except Exception: + detail = res.text + raise PocketBaseError(f"PocketBase {res.status_code}: {detail}") + if not res.content: + return None + return res.json() + + def admin_token(self) -> str: + if self._admin_token and (time.time() - self._token_at) < 280: + return self._admin_token + body = {"identity": self.email, "password": self.password} + last: Exception | None = None + for endpoint in ( + "/api/collections/_superusers/auth-with-password", + "/api/admins/auth-with-password", + ): + try: + data = self.request("POST", endpoint, json=body) + token = (data or {}).get("token") + if token: + self._admin_token = str(token) + self._token_at = time.time() + return self._admin_token + except Exception as exc: + last = exc + raise PocketBaseError(f"Unable to authenticate PocketBase admin: {last}") + + def health_ok(self) -> bool: + try: + res = self._http().get(f"{self.base_url}/api/health", timeout=3.0) + return res.status_code == 200 + except Exception: + return False + + def get_collection(self, name: str) -> dict[str, Any] | None: + try: + return self.request("GET", f"/api/collections/{name}", admin=True) + except PocketBaseError: + return None + + def create_collection(self, body: dict[str, Any]) -> dict[str, Any]: + return self.request("POST", "/api/collections", admin=True, json=body) + + def list_records( + self, + collection: str, + *, + filter: str | None = None, + sort: str | None = None, + page: int = 1, + per_page: int = 200, + ) -> dict[str, Any]: + params: dict[str, Any] = {"page": page, "perPage": per_page} + if filter: + params["filter"] = filter + if sort: + params["sort"] = sort + return self.request( + "GET", + f"/api/collections/{collection}/records", + admin=True, + params=params, + ) + + def list_all( + self, + collection: str, + *, + filter: str | None = None, + sort: str | None = None, + hard_limit: int = 5000, + ) -> list[dict[str, Any]]: + page = 1 + items: list[dict[str, Any]] = [] + while True: + data = self.list_records( + collection, filter=filter, sort=sort, page=page, per_page=200 + ) + batch = data.get("items") or [] + items.extend(batch) + if page >= (data.get("totalPages") or 1) or len(items) >= hard_limit: + break + page += 1 + return items[:hard_limit] + + def first( + self, collection: str, *, filter: str + ) -> dict[str, Any] | None: + data = self.list_records(collection, filter=filter, per_page=1) + items = data.get("items") or [] + return items[0] if items else None + + def create(self, collection: str, payload: dict[str, Any]) -> dict[str, Any]: + return self.request( + "POST", + f"/api/collections/{collection}/records", + admin=True, + json=payload, + ) + + def update( + self, collection: str, record_id: str, payload: dict[str, Any] + ) -> dict[str, Any]: + return self.request( + "PATCH", + f"/api/collections/{collection}/records/{record_id}", + admin=True, + json=payload, + ) + + def delete(self, collection: str, record_id: str) -> None: + self.request( + "DELETE", + f"/api/collections/{collection}/records/{record_id}", + admin=True, + ) + + def upsert( + self, + collection: str, + *, + filter: str, + payload: dict[str, Any], + ) -> dict[str, Any]: + existing = self.first(collection, filter=filter) + if existing: + return self.update(collection, existing["id"], payload) + return self.create(collection, payload) + + +_pb: PocketBaseClient | None = None + + +def get_pb() -> PocketBaseClient: + global _pb + if _pb is None: + _pb = PocketBaseClient() + return _pb diff --git a/apps/api/services/nomadro_pb/config.py b/apps/api/services/nomadro_pb/config.py new file mode 100644 index 0000000..3d6e6f3 --- /dev/null +++ b/apps/api/services/nomadro_pb/config.py @@ -0,0 +1,48 @@ +"""PocketBase connection for Nomadro verticals. + +`.com` (US) and `.cn` / hackrobot are **independent**. Never hardcode +China-side hosts as the default for the .com stack. + +Resolution order: +1. PB_INTERNAL_URL / POCKETBASE_INTERNAL_URL (same-machine / loopback) +2. PB_URL / POCKETBASE_URL (explicit env) +3. http://127.0.0.1:8090 (US VPS / local sibling PB) + +China / hackrobot PB only via explicit env on that deploy — not in code defaults. +""" +from __future__ import annotations + +import os + +# Same-box default (US VPS or local). Do NOT point at hackrobot.cn. +DEFAULT_PB_URL = "http://127.0.0.1:8090" + + +def resolve_pb_url() -> str: + internal = ( + os.getenv("PB_INTERNAL_URL") or os.getenv("POCKETBASE_INTERNAL_URL") or "" + ).strip() + explicit = (os.getenv("PB_URL") or os.getenv("POCKETBASE_URL") or "").strip() + if internal: + return internal.rstrip("/") + if explicit: + return explicit.rstrip("/") + return DEFAULT_PB_URL + + +def resolve_pb_admin() -> tuple[str, str]: + email = ( + os.getenv("PB_ADMIN_EMAIL") + or os.getenv("POCKETBASE_EMAIL") + or "" + ).strip() + password = ( + os.getenv("PB_ADMIN_PASSWORD") + or os.getenv("POCKETBASE_PASSWORD") + or "" + ).strip() + return email, password + + +PB_URL = resolve_pb_url() +PB_ADMIN_EMAIL, PB_ADMIN_PASSWORD = resolve_pb_admin() diff --git a/apps/api/services/nomadro_pb/ensure.py b/apps/api/services/nomadro_pb/ensure.py new file mode 100644 index 0000000..7b20cf7 --- /dev/null +++ b/apps/api/services/nomadro_pb/ensure.py @@ -0,0 +1,83 @@ +"""Create missing PocketBase collections (idempotent).""" +from __future__ import annotations + +import logging +from typing import Any + +from nomadro_pb.client import PocketBaseClient, PocketBaseError, get_pb +from nomadro_pb.schemas import ALL_COLLECTIONS + +log = logging.getLogger("nomadro_pb.ensure") +_ensured = False + + +def _legacy_schema(fields: list[dict[str, Any]]) -> list[dict[str, Any]]: + out: list[dict[str, Any]] = [] + for f in fields: + item = { + "name": f["name"], + "type": f["type"], + "required": bool(f.get("required")), + } + if f["type"] == "select" and "values" in f: + item["options"] = { + "maxSelect": f.get("maxSelect", 1), + "values": f["values"], + } + out.append(item) + return out + + +def ensure_collection(client: PocketBaseClient, body: dict[str, Any]) -> bool: + name = body["name"] + existing = client.get_collection(name) + if existing: + return True + try: + client.create_collection(body) + log.info("created PB collection %s", name) + return True + except PocketBaseError as exc: + # Older PocketBase: schema instead of fields + legacy = { + "name": name, + "type": "base", + "listRule": None, + "viewRule": None, + "createRule": None, + "updateRule": None, + "deleteRule": None, + "schema": _legacy_schema(body.get("fields") or []), + } + try: + client.create_collection(legacy) + log.info("created PB collection %s (legacy schema)", name) + return True + except PocketBaseError as exc2: + log.warning("PB create %s failed: %s / %s", name, exc, exc2) + return False + + +def ensure_all_collections(client: PocketBaseClient | None = None) -> dict[str, bool]: + global _ensured + pb = client or get_pb() + results: dict[str, bool] = {} + for body in ALL_COLLECTIONS: + name = body["name"] + try: + results[name] = ensure_collection(pb, body) + except Exception as exc: # pragma: no cover + log.warning("ensure %s: %s", name, exc) + results[name] = False + _ensured = all(results.values()) if results else False + return results + + +def ensure_once() -> bool: + global _ensured + if _ensured: + return True + results = ensure_all_collections() + ok = all(results.values()) if results else False + _ensured = ok + return ok diff --git a/apps/api/services/nomadro_pb/schemas.py b/apps/api/services/nomadro_pb/schemas.py new file mode 100644 index 0000000..4d00332 --- /dev/null +++ b/apps/api/services/nomadro_pb/schemas.py @@ -0,0 +1,534 @@ +"""PocketBase collection schemas for Nomadro verticals (admin API create).""" +from __future__ import annotations + +from typing import Any + + +def _text(name: str, required: bool = False, max_len: int | None = None) -> dict[str, Any]: + f: dict[str, Any] = {"name": name, "type": "text", "required": required} + if max_len: + f["max"] = max_len + return f + + +def _num(name: str, required: bool = False) -> dict[str, Any]: + return {"name": name, "type": "number", "required": required} + + +def _bool(name: str, required: bool = False) -> dict[str, Any]: + return {"name": name, "type": "bool", "required": required} + + +def _json(name: str, required: bool = False) -> dict[str, Any]: + return {"name": name, "type": "json", "required": required} + + +def _base(name: str, fields: list[dict[str, Any]], indexes: list[str] | None = None) -> dict[str, Any]: + body: dict[str, Any] = { + "name": name, + "type": "base", + "listRule": "", + "viewRule": "", + "createRule": "", + "updateRule": "", + "deleteRule": "", + "fields": fields, + } + if indexes: + body["indexes"] = indexes + return body + + +# —— Social —— +SOCIAL_ROSTER = _base( + "social_roster", + [ + _text("guest_id", True), + _text("name", True), + _text("title"), + _text("city"), + _text("phone"), + _text("linktree"), + _text("skills"), + _text("bio"), + _text("avatar"), + _text("gender"), + _text("intents"), + _text("availability"), + _text("status"), + _text("looking_for"), + _text("relationship"), + _text("education"), + _text("graduation"), + _text("wechat"), + _bool("discoverable"), + _bool("face_ok"), + _text("liveness_status"), + _text("liveness_at"), + _text("liveness_video_url"), + _text("liveness_front_url"), + _text("liveness_turn_url"), + _text("onboarded_at"), + _text("updated_at", True), + ], + indexes=[ + "CREATE UNIQUE INDEX idx_social_roster_guest ON social_roster (guest_id)", + "CREATE INDEX idx_social_roster_city ON social_roster (city)", + ], +) + +SOCIAL_LIVENESS = _base( + "social_liveness_audits", + [ + _text("guest_id", True), + _text("avatar_url"), + _text("front_url"), + _text("turn_url"), + _text("video_url"), + _num("video_size"), + _num("similarity"), + _num("yaw_delta"), + _text("status"), + _json("meta"), + _text("created_at", True), + ], + indexes=["CREATE INDEX idx_social_live_guest ON social_liveness_audits (guest_id)"], +) + +SOCIAL_SKILLS = _base( + "social_skill_posts", + [ + _text("guest_id", True), + _text("author", True), + _text("city"), + _text("offer", True), + _text("want", True), + _text("note"), + _text("status"), + _text("created_at", True), + ], + indexes=["CREATE INDEX idx_social_skill_city ON social_skill_posts (city)"], +) + +SOCIAL_REVIEWS = _base( + "social_meetup_reviews", + [ + _text("booking_id"), + _text("from_guest", True), + _text("to_guest", True), + _text("to_name"), + _num("punctuality", True), + _num("chemistry", True), + _num("professionalism", True), + _text("text"), + _text("created_at", True), + ], + indexes=["CREATE INDEX idx_social_rev_to ON social_meetup_reviews (to_guest)"], +) + +SOCIAL_BLOCKS = _base( + "social_blocks", + [ + _text("guest_id", True), + _text("blocked_guest", True), + _text("reason"), + _text("created_at", True), + ], +) + +SOCIAL_REPORTS = _base( + "social_reports", + [ + _text("guest_id", True), + _text("target_guest", True), + _text("target_name"), + _text("reason", True), + _text("detail"), + _text("status"), + _text("result_note"), + _text("created_at", True), + _text("resolved_at"), + ], +) + +SOCIAL_MESSAGES = _base( + "social_messages", + [ + _text("channel_id", True), + _num("seq", True), + _text("guest_id", True), + _text("nick"), + _text("text"), + _text("kind"), + _json("meta"), + _json("attachments"), + _json("reply_to"), + _json("reactions"), + _bool("pinned"), + _bool("recalled"), + _text("created_at", True), + _text("edited_at"), + ], + indexes=[ + "CREATE INDEX idx_social_msg_ch ON social_messages (channel_id)", + "CREATE INDEX idx_social_msg_seq ON social_messages (channel_id, seq)", + ], +) + +SOCIAL_CHANNEL_META = _base( + "social_channel_meta", + [ + _text("channel_id", True), + _num("seq"), + _json("pins"), + _json("presence"), + _json("reads"), + _text("updated_at"), + ], + indexes=["CREATE UNIQUE INDEX idx_social_chmeta ON social_channel_meta (channel_id)"], +) + +SOCIAL_CHANNEL_READS = _base( + "social_channel_reads", + [ + _text("guest_id", True), + _text("channel_id", True), + _num("recv_seq"), + _num("read_seq"), + _text("updated_at"), + ], + indexes=[ + "CREATE UNIQUE INDEX idx_social_chread ON social_channel_reads (guest_id, channel_id)", + ], +) + +SOCIAL_FILES = _base( + "social_files", + [ + _text("file_id", True), + _text("channel_id", True), + _text("guest_id"), + _text("kind"), + _text("name"), + _text("mime"), + _num("size"), + _text("path"), + _text("created_at", True), + ], + indexes=["CREATE UNIQUE INDEX idx_social_files ON social_files (file_id)"], +) + +SOCIAL_TRIPS = _base( + "social_trips", + [ + _text("guest_id", True), + _text("city_id"), + _text("city", True), + _text("country"), + _num("lat"), + _num("lng"), + _text("h3_cell"), + _text("arrival_date"), + _text("departure_date"), + _text("visibility"), + _text("status"), + _text("updated_at", True), + ], + indexes=[ + "CREATE INDEX idx_social_trips_guest ON social_trips (guest_id)", + "CREATE INDEX idx_social_trips_city ON social_trips (city_id)", + ], +) + +SOCIAL_CAFE_REVIEWS = _base( + "social_cafe_reviews", + [ + _text("cafe_id", True), + _text("guest_id"), + _text("author"), + _num("score"), + _text("text"), + _text("photo_note"), + _text("created_at", True), + ], +) + +SOCIAL_FEEDBACK = _base( + "social_feedback", + [ + _text("guest_id"), + _text("kind"), + _text("text"), + _text("contact"), + _text("created_at", True), + ], +) + +SOCIAL_GIG_APPS = _base( + "social_gig_apps", + [ + _text("gig_id", True), + _text("guest_id"), + _text("name"), + _text("contact"), + _text("note"), + _text("request_id"), + _text("created_at", True), + ], +) + +# Immutable audit trail — never hard-delete user content without a snapshot here. +SOCIAL_ARCHIVES = _base( + "social_archives", + [ + _text("entity", True), + _text("entity_id", True), + _text("guest_id"), + _text("action", True), + _json("payload"), + _text("note"), + _text("created_at", True), + ], + indexes=[ + "CREATE INDEX idx_social_arch_entity ON social_archives (entity, entity_id)", + "CREATE INDEX idx_social_arch_guest ON social_archives (guest_id)", + "CREATE INDEX idx_social_arch_at ON social_archives (created_at)", + ], +) + +# —— Coffee —— +COFFEE_HOSTS = _base( + "coffee_hosts", + [ + _text("username", True), + _text("name", True), + _text("bio"), + _text("avatar"), + _text("city"), + _text("timezone"), + _text("created_at", True), + ], + indexes=["CREATE UNIQUE INDEX idx_coffee_host_user ON coffee_hosts (username)"], +) + +COFFEE_SCHEDULES = _base( + "coffee_schedules", + [ + _text("host_id", True), + _text("name"), + _text("timezone"), + _json("availability"), + _text("created_at", True), + ], +) + +COFFEE_EVENT_TYPES = _base( + "coffee_event_types", + [ + _text("host_id", True), + _text("schedule_id"), + _text("slug", True), + _text("title", True), + _text("description"), + _num("length_minutes"), + _num("slot_interval"), + _num("buffer_before"), + _num("buffer_after"), + _json("locations"), + _bool("active"), + _text("created_at", True), + ], +) + +COFFEE_BOOKINGS = _base( + "coffee_bookings", + [ + _text("uid", True), + _text("event_type_id"), + _text("host_id", True), + _text("title"), + _text("status"), + _text("start_utc"), + _text("end_utc"), + _text("location"), + _text("notes"), + _text("attendee_name"), + _text("attendee_email"), + _text("attendee_device"), + _text("created_at", True), + _text("cancelled_at"), + ], +) + +# —— Notify —— +NOTIFY_SUBSCRIBERS = _base( + "notify_subscribers", + [ + _text("subscriber_id", True), + _text("email"), + _text("phone"), + _text("first_name"), + _text("last_name"), + _text("avatar"), + _text("locale"), + _json("data"), + _text("created_at", True), + _text("updated_at"), + ], + indexes=["CREATE UNIQUE INDEX idx_notify_sub ON notify_subscribers (subscriber_id)"], +) + +NOTIFY_TOPICS = _base( + "notify_topics", + [ + _text("key", True), + _text("name", True), + _json("subscribers"), + _text("created_at", True), + ], + indexes=["CREATE UNIQUE INDEX idx_notify_topic ON notify_topics (key)"], +) + +NOTIFY_WORKFLOWS = _base( + "notify_workflows", + [ + _text("workflow_id", True), + _text("name", True), + _text("description"), + _bool("active"), + _json("tags"), + _json("steps"), + _text("created_at", True), + _text("updated_at"), + ], + indexes=["CREATE UNIQUE INDEX idx_notify_wf ON notify_workflows (workflow_id)"], +) + +NOTIFY_PREFS = _base( + "notify_preferences", + [ + _text("subscriber_id", True), + _json("channels"), + _text("updated_at"), + ], + indexes=["CREATE UNIQUE INDEX idx_notify_prefs ON notify_preferences (subscriber_id)"], +) + +NOTIFY_MESSAGES = _base( + "notify_messages", + [ + _text("subscriber_id", True), + _text("notification_id"), + _text("channel"), + _text("category"), + _text("subject"), + _text("body"), + _text("cta_label"), + _text("cta_url"), + _text("href"), + _json("payload"), + _bool("read"), + _bool("archived"), + _bool("deleted"), + _text("created_at", True), + ], + indexes=["CREATE INDEX idx_notify_inbox ON notify_messages (subscriber_id)"], +) + +NOTIFY_ACTIVITY = _base( + "notify_activity", + [ + _text("status"), + _text("subscriber_id"), + _text("workflow_id"), + _text("workflow_name"), + _text("transaction_id"), + _json("payload"), + _json("jobs"), + _text("created_at", True), + ], +) + +NOTIFY_INTEGRATIONS = _base( + "notify_integrations", + [ + _text("channel", True), + _text("provider"), + _bool("active"), + _json("config"), + _text("created_at", True), + ], +) + +# —— Work (document-oriented board blob + pads) —— +WORK_PROJECTS = _base( + "work_projects", + [ + _text("name", True), + _text("description"), + _text("background_type"), + _text("background_gradient"), + _text("board_id"), + _text("created_at", True), + _text("updated_at"), + ], +) + +WORK_BOARDS = _base( + "work_boards", + [ + _text("project_id", True), + _text("name", True), + _num("position"), + _text("default_view"), + _text("background_gradient"), + _bool("show_card_counter"), + _json("doc"), + _text("created_at", True), + _text("updated_at"), + ], +) + +WORK_PADS = _base( + "work_pads", + [ + _text("title", True), + _text("text"), + _json("authors"), + _json("revisions"), + _text("created_at", True), + _text("updated_at"), + ], +) + +ALL_COLLECTIONS: list[dict[str, Any]] = [ + SOCIAL_ROSTER, + SOCIAL_LIVENESS, + SOCIAL_SKILLS, + SOCIAL_REVIEWS, + SOCIAL_BLOCKS, + SOCIAL_REPORTS, + SOCIAL_MESSAGES, + SOCIAL_CHANNEL_META, + SOCIAL_CHANNEL_READS, + SOCIAL_FILES, + SOCIAL_TRIPS, + SOCIAL_CAFE_REVIEWS, + SOCIAL_FEEDBACK, + SOCIAL_GIG_APPS, + SOCIAL_ARCHIVES, + COFFEE_HOSTS, + COFFEE_SCHEDULES, + COFFEE_EVENT_TYPES, + COFFEE_BOOKINGS, + NOTIFY_SUBSCRIBERS, + NOTIFY_TOPICS, + NOTIFY_WORKFLOWS, + NOTIFY_PREFS, + NOTIFY_MESSAGES, + NOTIFY_ACTIVITY, + NOTIFY_INTEGRATIONS, + WORK_PROJECTS, + WORK_BOARDS, + WORK_PADS, +] diff --git a/apps/api/services/notify_svc/pb_store.py b/apps/api/services/notify_svc/pb_store.py new file mode 100644 index 0000000..84dae02 --- /dev/null +++ b/apps/api/services/notify_svc/pb_store.py @@ -0,0 +1,529 @@ +"""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" diff --git a/apps/api/services/notify_svc/store.py b/apps/api/services/notify_svc/store.py index b58bf2d..d0463ab 100644 --- a/apps/api/services/notify_svc/store.py +++ b/apps/api/services/notify_svc/store.py @@ -1,1421 +1,31 @@ -""" -SQLite store — domain shaped after Novu -(Organization/Environment · Subscriber · Topic · Workflow · Event · Notification · Message). -Secondary-dev reimplementation for Nomadro (not upstream runtime / Docker Novu). -""" +"""Notify store — PocketBase (online-first).""" 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_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"]), - ) - - -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: 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, - } +from notify_svc.pb_store import ( # noqa: F401 + add_topic_subscriber, + create_topic, + create_workflow, + default_env_id, + delete_message, + delete_subscriber, + delete_workflow, + get_preferences, + get_subscriber, + get_workflow, + init_db, + list_activity, + list_inbox, + list_integrations, + list_subscribers, + list_topics, + list_workflows, + mark_all_read, + patch_message, + remove_topic_subscriber, + set_preferences, + trigger_event, + unread_by_category, + unread_count, + update_workflow, + upsert_subscriber, +) diff --git a/apps/api/services/notify_svc/store_sqlite_legacy.py b/apps/api/services/notify_svc/store_sqlite_legacy.py new file mode 100644 index 0000000..b1be522 --- /dev/null +++ b/apps/api/services/notify_svc/store_sqlite_legacy.py @@ -0,0 +1,1587 @@ +""" +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, + } diff --git a/apps/api/services/pay_svc/config.py b/apps/api/services/pay_svc/config.py index 66329d2..6dc7cc7 100644 --- a/apps/api/services/pay_svc/config.py +++ b/apps/api/services/pay_svc/config.py @@ -36,9 +36,8 @@ NOWPAYMENTS_API_KEY = os.getenv("NOWPAYMENTS_API_KEY", "") NOWPAYMENTS_IPN_SECRET = os.getenv("NOWPAYMENTS_IPN_SECRET", "") # PocketBase(支持 PB_ADMIN_* 或 POCKETBASE_*) -# 为了避免线上环境遗留 PB_URL=公网域名导致慢查询,默认强制优先本机。 -# 本地无 PocketBase、需连线上 PB 时:在 .env.local 设置 PB_INTERNAL_URL=https://pocketbase.hackrobot.cn -# (该变量优先级最高,且不改变下方对 PB_URL 的解析规则) +# 默认本机 8090(.com/US 同机)。勿把 hackrobot.cn 写进代码默认。 +# 中国机若要用自家 PB:部署 env 设 PB_URL / PB_INTERNAL_URL。 _pb_internal = os.getenv("PB_INTERNAL_URL") or os.getenv("POCKETBASE_INTERNAL_URL") _pb_explicit = os.getenv("PB_URL") or os.getenv("POCKETBASE_URL") if _pb_internal: diff --git a/apps/api/services/social_svc/community_board.py b/apps/api/services/social_svc/community_board.py new file mode 100644 index 0000000..9447a75 --- /dev/null +++ b/apps/api/services/social_svc/community_board.py @@ -0,0 +1,439 @@ +"""Skill swap · meetup reviews · report/block · wrapped — PocketBase only.""" +from __future__ import annotations + +from typing import Any + +from nomadro_pb import ensure_once, get_pb, pb_quote +from social_svc import pb_data +from social_svc.pb_data import _now, _uid + +C_SKILLS = "social_skill_posts" +C_REVIEWS = "social_meetup_reviews" +C_BLOCKS = "social_blocks" +C_REPORTS = "social_reports" + + +def ensure_community_tables() -> None: + ensure_once() + + +def create_skill_post( + guest_id: str, + *, + author: str, + city: str, + offer: str, + want: str, + note: str = "", +) -> dict[str, Any]: + ensure_community_tables() + item = { + "id": _uid("sk"), + "guestId": guest_id, + "author": (author or "游民").strip()[:64] or "游民", + "city": (city or "").strip()[:64], + "offer": (offer or "").strip()[:200], + "want": (want or "").strip()[:200], + "note": (note or "").strip()[:800], + "status": "open", + "createdAt": _now(), + } + if not item["offer"] or not item["want"]: + raise ValueError("请填写能提供什么、想换什么") + rec = get_pb().create( + C_SKILLS, + { + "guest_id": guest_id, + "author": item["author"], + "city": item["city"], + "offer": item["offer"], + "want": item["want"], + "note": item["note"], + "status": "open", + "created_at": item["createdAt"], + }, + ) + item["id"] = rec.get("id") or item["id"] + return item + + +def list_skill_posts(*, city: str = "", limit: int = 60) -> list[dict[str, Any]]: + ensure_community_tables() + limit = max(1, min(int(limit or 60), 120)) + filt = 'status="open"' + rows = get_pb().list_all(C_SKILLS, filter=filt, sort="-created_at", hard_limit=200) + city_f = city.strip().lower() + out = [] + for r in rows: + if city_f and city_f not in (r.get("city") or "").lower(): + continue + out.append( + { + "id": r.get("id"), + "guestId": r.get("guest_id"), + "author": r.get("author"), + "city": r.get("city") or "", + "offer": r.get("offer"), + "want": r.get("want"), + "note": r.get("note") or "", + "status": r.get("status"), + "createdAt": r.get("created_at"), + } + ) + if len(out) >= limit: + break + return out + + +def close_skill_post(guest_id: str, post_id: str) -> dict[str, Any]: + ensure_community_tables() + r = get_pb().first(C_SKILLS, filter=f"id={pb_quote(post_id)}") + if not r: + # PB id filter uses record id field + try: + r = get_pb().request( + "GET", f"/api/collections/{C_SKILLS}/records/{post_id}", admin=True + ) + except Exception: + r = None + if not r: + raise ValueError("帖子不存在") + if r.get("guest_id") != guest_id: + raise ValueError("只能关闭自己的帖子") + get_pb().update(C_SKILLS, r["id"], {"status": "closed"}) + return {"ok": True, "id": post_id, "status": "closed"} + + +def create_meetup_review( + from_guest: str, + *, + to_guest: str, + to_name: str = "", + booking_id: str = "", + punctuality: int, + chemistry: int, + professionalism: int, + text: str = "", +) -> dict[str, Any]: + ensure_community_tables() + if from_guest == to_guest: + raise ValueError("不能评价自己") + for n in (punctuality, chemistry, professionalism): + if not 1 <= int(n) <= 5: + raise ValueError("评分须为 1–5") + if booking_id: + hit = get_pb().first( + C_REVIEWS, + filter=( + f"booking_id={pb_quote(booking_id)} && " + f"from_guest={pb_quote(from_guest)} && " + f"to_guest={pb_quote(to_guest)}" + ), + ) + if hit: + raise ValueError("你已经评价过这次见面") + item = { + "id": _uid("rv"), + "bookingId": (booking_id or "").strip()[:80], + "fromGuest": from_guest, + "toGuest": to_guest, + "toName": (to_name or "").strip()[:64], + "punctuality": int(punctuality), + "chemistry": int(chemistry), + "professionalism": int(professionalism), + "text": (text or "").strip()[:800], + "createdAt": _now(), + } + rec = get_pb().create( + C_REVIEWS, + { + "booking_id": item["bookingId"], + "from_guest": from_guest, + "to_guest": to_guest, + "to_name": item["toName"], + "punctuality": item["punctuality"], + "chemistry": item["chemistry"], + "professionalism": item["professionalism"], + "text": item["text"], + "created_at": item["createdAt"], + }, + ) + item["id"] = rec.get("id") or item["id"] + return item + + +def reviews_for_guest(guest_id: str, limit: int = 40) -> dict[str, Any]: + ensure_community_tables() + limit = max(1, min(int(limit or 40), 100)) + rows = get_pb().list_all( + C_REVIEWS, + filter=f"to_guest={pb_quote(guest_id)}", + sort="-created_at", + hard_limit=limit, + ) + items = [ + { + "id": r.get("id"), + "bookingId": r.get("booking_id") or "", + "fromGuest": r.get("from_guest"), + "toGuest": r.get("to_guest"), + "toName": r.get("to_name") or "", + "punctuality": r.get("punctuality"), + "chemistry": r.get("chemistry"), + "professionalism": r.get("professionalism"), + "text": r.get("text") or "", + "createdAt": r.get("created_at"), + "avg": round( + ( + float(r.get("punctuality") or 0) + + float(r.get("chemistry") or 0) + + float(r.get("professionalism") or 0) + ) + / 3, + 2, + ), + } + for r in rows + ] + if not items: + return {"guestId": guest_id, "count": 0, "averages": None, "items": []} + n = len(items) + averages = { + "punctuality": round(sum(i["punctuality"] for i in items) / n, 2), + "chemistry": round(sum(i["chemistry"] for i in items) / n, 2), + "professionalism": round(sum(i["professionalism"] for i in items) / n, 2), + "overall": round(sum(i["avg"] for i in items) / n, 2), + } + return {"guestId": guest_id, "count": n, "averages": averages, "items": items} + + +def block_user(guest_id: str, blocked_guest: str, reason: str = "") -> dict[str, Any]: + ensure_community_tables() + if guest_id == blocked_guest: + raise ValueError("不能屏蔽自己") + get_pb().upsert( + C_BLOCKS, + filter=( + f"guest_id={pb_quote(guest_id)} && blocked_guest={pb_quote(blocked_guest)}" + ), + payload={ + "guest_id": guest_id, + "blocked_guest": blocked_guest, + "reason": (reason or "").strip()[:200], + "created_at": _now(), + }, + ) + return {"ok": True, "blockedGuest": blocked_guest} + + +def unblock_user(guest_id: str, blocked_guest: str) -> dict[str, Any]: + ensure_community_tables() + r = get_pb().first( + C_BLOCKS, + filter=( + f"guest_id={pb_quote(guest_id)} && blocked_guest={pb_quote(blocked_guest)}" + ), + ) + if r: + get_pb().delete(C_BLOCKS, r["id"]) + return {"ok": True} + + +def list_blocks(guest_id: str) -> list[dict[str, Any]]: + ensure_community_tables() + rows = get_pb().list_all( + C_BLOCKS, filter=f"guest_id={pb_quote(guest_id)}", sort="-created_at" + ) + return [ + { + "blockedGuest": r.get("blocked_guest"), + "reason": r.get("reason") or "", + "createdAt": r.get("created_at"), + } + for r in rows + ] + + +def is_blocked(viewer: str, other: str) -> bool: + ensure_community_tables() + a = get_pb().first( + C_BLOCKS, + filter=f"guest_id={pb_quote(viewer)} && blocked_guest={pb_quote(other)}", + ) + if a: + return True + b = get_pb().first( + C_BLOCKS, + filter=f"guest_id={pb_quote(other)} && blocked_guest={pb_quote(viewer)}", + ) + return bool(b) + + +def create_report( + guest_id: str, + *, + target_guest: str, + target_name: str = "", + reason: str, + detail: str = "", +) -> dict[str, Any]: + ensure_community_tables() + if guest_id == target_guest: + raise ValueError("不能举报自己") + reason = (reason or "").strip()[:80] + if not reason: + raise ValueError("请选择举报原因") + item = { + "id": _uid("rp"), + "guestId": guest_id, + "targetGuest": target_guest, + "targetName": (target_name or "").strip()[:64], + "reason": reason, + "detail": (detail or "").strip()[:1000], + "status": "open", + "createdAt": _now(), + } + rec = get_pb().create( + C_REPORTS, + { + "guest_id": guest_id, + "target_guest": target_guest, + "target_name": item["targetName"], + "reason": reason, + "detail": item["detail"], + "status": "open", + "result_note": "", + "created_at": item["createdAt"], + "resolved_at": "", + }, + ) + item["id"] = rec.get("id") or item["id"] + return item + + +def resolve_report( + report_id: str, *, status: str = "resolved", result_note: str = "" +) -> dict[str, Any]: + ensure_community_tables() + try: + r = get_pb().request( + "GET", f"/api/collections/{C_REPORTS}/records/{report_id}", admin=True + ) + except Exception as exc: + raise ValueError("举报不存在") from exc + now = _now() + get_pb().update( + C_REPORTS, + report_id, + { + "status": status, + "result_note": (result_note or "").strip()[:500], + "resolved_at": now if status != "open" else "", + }, + ) + return { + "id": report_id, + "guestId": r.get("guest_id"), + "targetGuest": r.get("target_guest"), + "status": status, + "resultNote": result_note, + "resolvedAt": now, + } + + +def list_reports(*, status: str = "open", limit: int = 40) -> list[dict[str, Any]]: + ensure_community_tables() + limit = max(1, min(int(limit or 40), 100)) + filt = f"status={pb_quote(status)}" if status else None + rows = get_pb().list_all(C_REPORTS, filter=filt, sort="-created_at", hard_limit=limit) + return [ + { + "id": r.get("id"), + "guestId": r.get("guest_id"), + "targetGuest": r.get("target_guest"), + "targetName": r.get("target_name") or "", + "reason": r.get("reason"), + "detail": r.get("detail") or "", + "status": r.get("status"), + "resultNote": r.get("result_note") or "", + "createdAt": r.get("created_at"), + "resolvedAt": r.get("resolved_at") or "", + } + for r in rows + ] + + +def wrapped_stats(guest_id: str, year: int | None = None) -> dict[str, Any]: + ensure_community_tables() + from datetime import datetime, timezone + + y = year or datetime.now(timezone.utc).year + prefix = f"{y}-" + roster = pb_data.get_roster(guest_id) or {} + cities: list[str] = [] + if roster.get("city"): + cities = [roster["city"]] + try: + from social_svc import geo_pb + + trips = geo_pb.list_trips_for_guest(guest_id) if hasattr(geo_pb, "list_trips_for_guest") else [] + for t in trips or []: + c = t.get("city") or "" + if c and c not in cities: + cities.append(c) + except Exception: + pass + reviews = get_pb().list_all( + C_REVIEWS, + filter=f"(from_guest={pb_quote(guest_id)} || to_guest={pb_quote(guest_id)})", + hard_limit=500, + ) + reviews = [r for r in reviews if str(r.get("created_at") or "").startswith(prefix)] + skills = get_pb().list_all( + C_SKILLS, filter=f"guest_id={pb_quote(guest_id)}", hard_limit=200 + ) + skills = [s for s in skills if str(s.get("created_at") or "").startswith(prefix)] + peers = set() + for r in reviews: + a, b = r.get("from_guest"), r.get("to_guest") + if a == guest_id and b: + peers.add(b) + elif b == guest_id and a: + peers.add(a) + return { + "year": y, + "name": roster.get("name") or "游民", + "homeCity": roster.get("city") or "", + "cities": cities[:24], + "cityCount": len(cities), + "peopleMet": len(peers), + "meetups": len(reviews), + "skillPosts": len(skills), + "livenessVerified": (roster.get("livenessStatus") or "") == "verified", + } + + +def city_digest_payload(city: str, limit: int = 8) -> dict[str, Any]: + ensure_community_tables() + city = (city or "").strip() + people = ( + pb_data.list_discovery_roster(city=city, limit=limit) if city else [] + ) + skills = list_skill_posts(city=city, limit=5) if city else list_skill_posts(limit=5) + lines = [] + for p in people[:5]: + lines.append( + f"· {p.get('name')} · {p.get('city') or city} · {p.get('lookingFor') or p.get('title') or ''}" + ) + for s in skills[:3]: + lines.append( + f"· 互换:{s['offer']} ↔ {s['want']}({s.get('city') or '全球'})" + ) + return { + "city": city or "全球", + "peopleCount": len(people), + "skillCount": len(skills), + "digestText": "\n".join(lines) + if lines + else "这周同城还比较安静,去发一条技能互换吧。", + } diff --git a/apps/api/services/social_svc/config.py b/apps/api/services/social_svc/config.py index 207005d..9741ab4 100644 --- a/apps/api/services/social_svc/config.py +++ b/apps/api/services/social_svc/config.py @@ -49,21 +49,34 @@ PHOTON_BASE_URL = os.getenv( PHOTON_TIMEOUT_SEC = float(os.getenv("PHOTON_TIMEOUT_SEC", "6")) H3_CITY_RES = int(os.getenv("H3_CITY_RES", "4")) H3_NEAR_RES = int(os.getenv("H3_NEAR_RES", "7")) -# PocketBase for social_trips (same env family as pay_svc) -_pb_internal = os.getenv("PB_INTERNAL_URL") or os.getenv("POCKETBASE_INTERNAL_URL") -_pb_explicit = os.getenv("PB_URL") or os.getenv("POCKETBASE_URL") -if _pb_internal: - PB_URL = _pb_internal.rstrip("/") -elif _pb_explicit: - PB_URL = _pb_explicit.rstrip("/") -else: - PB_URL = "http://127.0.0.1:8090" -PB_ADMIN_EMAIL = ( - os.getenv("PB_ADMIN_EMAIL") or os.getenv("POCKETBASE_EMAIL") or "" -) -PB_ADMIN_PASSWORD = ( - os.getenv("PB_ADMIN_PASSWORD") or os.getenv("POCKETBASE_PASSWORD") or "" -) +# PocketBase — .com/US defaults to same-box 8090; never hardcode hackrobot.cn +try: + from nomadro_pb.config import ( # type: ignore + PB_ADMIN_EMAIL as _PB_EMAIL, + PB_ADMIN_PASSWORD as _PB_PASS, + PB_URL as _PB_URL, + ) + + PB_URL = _PB_URL + PB_ADMIN_EMAIL = _PB_EMAIL + PB_ADMIN_PASSWORD = _PB_PASS +except Exception: + _pb_internal = os.getenv("PB_INTERNAL_URL") or os.getenv( + "POCKETBASE_INTERNAL_URL" + ) + _pb_explicit = os.getenv("PB_URL") or os.getenv("POCKETBASE_URL") + if _pb_internal: + PB_URL = _pb_internal.rstrip("/") + elif _pb_explicit: + PB_URL = _pb_explicit.rstrip("/") + else: + PB_URL = "http://127.0.0.1:8090" + PB_ADMIN_EMAIL = ( + os.getenv("PB_ADMIN_EMAIL") or os.getenv("POCKETBASE_EMAIL") or "" + ) + PB_ADMIN_PASSWORD = ( + os.getenv("PB_ADMIN_PASSWORD") or os.getenv("POCKETBASE_PASSWORD") or "" + ) SOCIAL_TRIPS_COLLECTION = os.getenv("SOCIAL_TRIPS_COLLECTION", "social_trips") SOCIAL_GEO_USE_PB = os.getenv("SOCIAL_GEO_USE_PB", "true").lower() in { "1", diff --git a/apps/api/services/social_svc/notify_bridge.py b/apps/api/services/social_svc/notify_bridge.py new file mode 100644 index 0000000..c52f43b --- /dev/null +++ b/apps/api/services/social_svc/notify_bridge.py @@ -0,0 +1,199 @@ +"""Fire Novu-domain notify_svc events from social (likes, coffee, board, city, rooms).""" +from __future__ import annotations + +import json +import logging +import os +import urllib.error +import urllib.parse +import urllib.request +from datetime import datetime +from typing import Any +from zoneinfo import ZoneInfo + +log = logging.getLogger("social_svc.notify_bridge") + +NOTIFY_INTERNAL_URL = os.getenv( + "NOTIFY_INTERNAL_URL", + os.getenv("NOTIFY_API_URL", "http://127.0.0.1:8023"), +).rstrip("/") + + +def _request( + method: str, + path: str, + body: dict[str, Any] | None = None, + timeout: float = 4.0, +) -> dict[str, Any] | None: + url = f"{NOTIFY_INTERNAL_URL}{path}" + data = json.dumps(body).encode("utf-8") if body is not None else None + headers = {"Accept": "application/json"} + if data is not None: + headers["Content-Type"] = "application/json" + req = urllib.request.Request(url, data=data, headers=headers, method=method) + try: + with urllib.request.urlopen(req, timeout=timeout) as res: + raw = res.read().decode("utf-8", errors="replace") + return json.loads(raw) if raw else {} + except (urllib.error.URLError, TimeoutError, json.JSONDecodeError, OSError) as exc: + log.warning("notify %s %s failed: %s", method, path, exc) + return None + + +def ensure_subscriber(guest_id: str, name: str = "游民") -> None: + _request( + "POST", + "/api/notify/v1/subscribers", + {"subscriber_id": guest_id, "first_name": (name or "游民")[:40]}, + ) + + +def in_quiet_hours(channels: dict[str, Any] | None, *, dnd: bool = False) -> bool: + if dnd: + return True + if not channels: + return False + start = str(channels.get("quiet_start") or "").strip() + end = str(channels.get("quiet_end") or "").strip() + if not start or not end: + return False + tz_name = str(channels.get("timezone") or "Asia/Shanghai").strip() or "Asia/Shanghai" + try: + tz = ZoneInfo(tz_name) + except Exception: + tz = ZoneInfo("Asia/Shanghai") + now = datetime.now(tz) + try: + sh, sm = [int(x) for x in start.split(":")[:2]] + eh, em = [int(x) for x in end.split(":")[:2]] + except Exception: + return False + minutes = now.hour * 60 + now.minute + a = sh * 60 + sm + b = eh * 60 + em + if a == b: + return False + if a < b: + return a <= minutes < b + return minutes >= a or minutes < b + + +def _load_prefs(subscriber_id: str) -> tuple[dict[str, Any], bool]: + raw = _request( + "GET", + f"/api/notify/v1/subscribers/{urllib.parse.quote(subscriber_id)}/preferences", + ) + if not raw: + return {}, False + prefs = raw.get("preferences") or raw + channels = prefs.get("channels") if isinstance(prefs.get("channels"), dict) else prefs + if not isinstance(channels, dict): + channels = {} + dnd = bool(prefs.get("dnd") or channels.get("dnd")) + return channels, dnd + + +def trigger( + workflow_id: str, + subscriber_id: str, + payload: dict[str, Any] | None = None, + *, + name: str = "游民", + respect_quiet: bool = True, +) -> dict[str, Any] | None: + ensure_subscriber(subscriber_id, name) + channels, dnd = _load_prefs(subscriber_id) + payload = dict(payload or {}) + if respect_quiet and in_quiet_hours(channels, dnd=dnd): + payload["quietHours"] = True + return _request( + "POST", + "/api/notify/v1/events/trigger", + { + "workflow_id": workflow_id, + "subscriber_id": subscriber_id, + "payload": {**payload, "category": payload.get("category") or "social"}, + }, + ) + + +def notify_like(to_guest: str, from_name: str) -> None: + trigger( + "social-like", + to_guest, + {"actor": from_name, "firstName": from_name, "ctaUrl": "/social/people"}, + name=from_name, + ) + + +def notify_coffee_invite(to_guest: str, host_name: str, title: str) -> None: + trigger( + "coffee-invite", + to_guest, + {"firstName": host_name, "title": title, "ctaUrl": "/social/coffeechat"}, + name=host_name, + ) + + +def notify_board_join(owner_guest: str, actor_name: str, board_title: str) -> None: + trigger( + "board-join", + owner_guest, + { + "firstName": actor_name, + "title": board_title, + "category": "project", + "ctaUrl": "/social/work/boards", + }, + name=actor_name, + ) + + +def notify_city_online(to_guest: str, city: str, peer_name: str) -> None: + trigger( + "city-online", + to_guest, + {"firstName": peer_name, "city": city, "ctaUrl": "/social/people"}, + name=peer_name, + ) + + +def notify_room_live(to_guest: str, room_title: str) -> None: + trigger( + "room-live", + to_guest, + {"title": room_title, "ctaUrl": "/social/meetup"}, + ) + + +def notify_report_result(reporter_guest: str, note: str, status: str) -> None: + trigger( + "report-result", + reporter_guest, + { + "status": status, + "resultNote": note, + "category": "system", + "ctaUrl": "/social/notifications", + }, + respect_quiet=False, + ) + + +def fire_city_digest( + subscriber_id: str, + city: str, + digest_text: str, + *, + weekly: bool = False, +) -> None: + trigger( + "city-digest-weekly" if weekly else "city-digest-daily", + subscriber_id, + { + "city": city, + "digestText": digest_text, + "firstName": "游民", + "ctaUrl": "/social/people", + }, + ) diff --git a/apps/api/services/social_svc/pb_data.py b/apps/api/services/social_svc/pb_data.py new file mode 100644 index 0000000..8376914 --- /dev/null +++ b/apps/api/services/social_svc/pb_data.py @@ -0,0 +1,1436 @@ +"""Social data access via online PocketBase (no SQLite).""" +from __future__ import annotations + +import time +import uuid +from typing import Any + +from nomadro_pb import ensure_once, get_pb, pb_quote + +C_ROSTER = "social_roster" +C_LIVENESS = "social_liveness_audits" +C_SKILLS = "social_skill_posts" +C_REVIEWS = "social_meetup_reviews" +C_BLOCKS = "social_blocks" +C_REPORTS = "social_reports" +C_MESSAGES = "social_messages" +C_CHMETA = "social_channel_meta" +C_CAFE = "social_cafe_reviews" +C_FEEDBACK = "social_feedback" +C_GIGS = "social_gig_apps" +C_READS = "social_channel_reads" +C_FILES = "social_files" +C_ARCHIVES = "social_archives" + +# Live collection names keyed by admin entity +ENTITY_COLLECTIONS = { + "roster": C_ROSTER, + "messages": C_MESSAGES, + "reviews": C_CAFE, + "gigApps": C_GIGS, + "feedback": C_FEEDBACK, + "skills": C_SKILLS, + "liveness": C_LIVENESS, +} + + +def _uid(prefix: str) -> str: + return f"{prefix}_{uuid.uuid4().hex[:12]}" + + +def _now() -> str: + return time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime()) + + +def init_pb() -> None: + ensure_once() + + +def archive_snapshot( + *, + entity: str, + entity_id: str, + action: str, + payload: dict[str, Any] | None, + guest_id: str = "", + note: str = "", +) -> dict[str, Any]: + """Append-only archive. Never overwrite; never hard-delete archives.""" + init_pb() + body = { + "entity": (entity or "unknown")[:64], + "entity_id": str(entity_id or "")[:120], + "guest_id": str(guest_id or "")[:120], + "action": (action or "update")[:48], + "payload": payload if isinstance(payload, dict) else {"raw": payload}, + "note": (note or "")[:500], + "created_at": _now(), + } + return get_pb().create(C_ARCHIVES, body) + + +def _soft_deleted_ids(entity: str) -> set[str]: + """Entity ids with a soft_delete archive (latest wins conceptually).""" + init_pb() + rows = get_pb().list_all( + C_ARCHIVES, + filter=f"entity={pb_quote(entity)} && action={pb_quote('soft_delete')}", + hard_limit=5000, + ) + return {str(r.get("entity_id") or "") for r in rows if r.get("entity_id")} + + +def soft_delete_record( + *, + entity: str, + entity_id: str, + live_collection: str, + record: dict[str, Any] | None = None, + guest_id: str = "", + note: str = "", +) -> bool: + """Soft-delete: full snapshot → archive, then hide live row (never PB delete).""" + init_pb() + pb = get_pb() + rec = record + if rec is None: + try: + rec = pb.request( + "GET", f"/api/collections/{live_collection}/records/{entity_id}", admin=True + ) + except Exception: + # roster keyed by guest_id + if entity == "roster": + rec = pb.first(live_collection, filter=f"guest_id={pb_quote(entity_id)}") + else: + rec = None + if not rec: + return False + rid = str(rec.get("id") or entity_id) + gid = guest_id or str(rec.get("guest_id") or "") + archive_snapshot( + entity=entity, + entity_id=str(entity_id or rid), + action="soft_delete", + payload=dict(rec), + guest_id=gid, + note=note or "admin soft delete", + ) + # Hide without destroying bytes + patch: dict[str, Any] = {"updated_at": _now()} + if entity == "roster": + patch.update({"discoverable": False, "status": "deleted"}) + elif entity == "messages": + patch.update({"recalled": True, "text": "", "reactions": {}}) + elif entity in {"reviews", "gigApps", "feedback", "skills"}: + # status field exists on skills; others get note marker in archive only + if "status" in rec or entity == "skills": + patch["status"] = "deleted" + try: + pb.update(live_collection, rid, patch) + except Exception: + # Field may be missing on older PB schema — archive already persisted. + pass + return True + + +def health() -> dict[str, Any]: + pb = get_pb() + ok = pb.health_ok() + return { + "ok": ok, + "backend": "pocketbase", + "pb": pb.base_url, + "db": pb.base_url, + "dbBytes": 0, + } + + +# —— roster —— + + +def _roster_from_rec(r: dict[str, Any], *, public: bool = False) -> dict[str, Any]: + status = (r.get("status") or "online").strip() or "online" + skills = r.get("skills") or "" + intents = r.get("intents") or "" + tags = [t.strip() for t in skills.replace(",", ",").replace("、", ",").split(",") if t.strip()][:8] + item: dict[str, Any] = { + "guestId": r.get("guest_id") or "", + "name": r.get("name") or "游民", + "title": r.get("title") or "", + "city": r.get("city") or "", + "skills": skills, + "bio": r.get("bio") or "", + "avatar": r.get("avatar") or "", + "gender": r.get("gender") or "", + "intents": intents, + "availability": r.get("availability") or "", + "status": status, + "lookingFor": r.get("looking_for") or "", + "updatedAt": r.get("updated_at") or "", + "online": status in {"online", "here", "available"}, + "tags": tags, + "faceOk": bool(r.get("face_ok")), + "livenessStatus": r.get("liveness_status") or "none", + "livenessAt": r.get("liveness_at") or "", + "livenessVideoUrl": r.get("liveness_video_url") or "", + "onboardedAt": r.get("onboarded_at") or "", + "_id": r.get("id") or "", + } + if not public: + item.update( + { + "phone": r.get("phone") or "", + "linktree": r.get("linktree") or "", + "relationship": r.get("relationship") or "", + "education": r.get("education") or "", + "graduation": r.get("graduation") or "", + "wechat": r.get("wechat") or "", + "discoverable": bool(r.get("discoverable", True)), + "livenessFrontUrl": r.get("liveness_front_url") or "", + "livenessTurnUrl": r.get("liveness_turn_url") or "", + } + ) + return item + + +def get_roster(guest_id: str) -> dict[str, Any] | None: + init_pb() + rec = get_pb().first(C_ROSTER, filter=f"guest_id={pb_quote(guest_id)}") + return _roster_from_rec(rec, public=False) if rec else None + + +def upsert_roster(guest_id: str, payload: dict[str, Any]) -> dict[str, Any]: + init_pb() + existing = get_roster(guest_id) + is_first = existing is None + updated = _now() + avatar = str(payload.get("avatar") or "").strip()[:500] + if avatar and not ( + avatar.startswith("https://") + or avatar.startswith("http://") + or avatar.startswith("/api/social/") + ): + avatar = "" + intents_raw = payload.get("intents") + if isinstance(intents_raw, list): + intents = ",".join(str(x).strip() for x in intents_raw if str(x).strip())[:240] + else: + intents = str(intents_raw or "").strip()[:240] + status = str(payload.get("status") or "online").strip()[:32] or "online" + if status not in {"online", "away", "offline", "here", "available"}: + status = "online" + looking = str(payload.get("lookingFor") or payload.get("looking_for") or "").strip()[:200] + if not looking and intents: + looking = intents.replace(",", " · ")[:200] + discoverable = payload.get("discoverable") + if discoverable is None: + discoverable = True + else: + discoverable = str(discoverable).lower() not in {"0", "false", "no", "off"} + onboarded_at = (existing or {}).get("onboardedAt") or (updated if is_first else "") + + body = { + "guest_id": guest_id, + "name": str(payload.get("name") or "").strip()[:64] or "游民", + "title": str(payload.get("title") or "").strip()[:80], + "city": str(payload.get("city") or "").strip()[:64], + "phone": str(payload.get("phone") or "").strip()[:32], + "linktree": str(payload.get("linktree") or "").strip()[:240], + "skills": str(payload.get("skills") or "").strip()[:200], + "bio": str(payload.get("bio") or "").strip()[:2000], + "avatar": avatar, + "gender": str(payload.get("gender") or "").strip()[:16], + "intents": intents, + "availability": str(payload.get("availability") or "").strip()[:120], + "status": status, + "looking_for": looking, + "relationship": str(payload.get("relationship") or "").strip()[:32], + "education": str(payload.get("education") or "").strip()[:32], + "graduation": str(payload.get("graduation") or "").strip()[:32], + "wechat": str(payload.get("wechat") or "").strip()[:64], + "discoverable": discoverable, + "onboarded_at": onboarded_at, + "updated_at": updated, + } + # Preserve face/liveness unless caller overwrites avatar via mark_face + if existing: + body.setdefault("face_ok", existing.get("faceOk", False)) + body.setdefault("liveness_status", existing.get("livenessStatus") or "none") + body.setdefault("liveness_at", existing.get("livenessAt") or "") + body.setdefault("liveness_video_url", existing.get("livenessVideoUrl") or "") + body.setdefault("liveness_front_url", existing.get("livenessFrontUrl") or "") + body.setdefault("liveness_turn_url", existing.get("livenessTurnUrl") or "") + if not avatar and existing.get("avatar"): + body["avatar"] = existing["avatar"] + + if existing: + archive_snapshot( + entity="roster", + entity_id=guest_id, + action="update", + payload=dict(existing), + guest_id=guest_id, + note="roster upsert before-write", + ) + get_pb().upsert(C_ROSTER, filter=f"guest_id={pb_quote(guest_id)}", payload=body) + row = get_roster(guest_id) or {} + row["isFirstProfile"] = is_first + archive_snapshot( + entity="roster", + entity_id=guest_id, + action="create" if is_first else "update_after", + payload=dict(body), + guest_id=guest_id, + note="roster upsert after-write", + ) + return row + + +def mark_face_photo(guest_id: str, avatar_url: str) -> None: + """Album/selfie → avatar + face_ok. Does NOT set liveness verified.""" + init_pb() + existing = get_pb().first(C_ROSTER, filter=f"guest_id={pb_quote(guest_id)}") + url = avatar_url[:500] + now = _now() + if not existing: + get_pb().create( + C_ROSTER, + { + "guest_id": guest_id, + "name": "游民", + "avatar": url, + "face_ok": True, + "liveness_status": "none", + "discoverable": True, + "status": "online", + "updated_at": now, + }, + ) + return + live = (existing.get("liveness_status") or "").strip() + get_pb().update( + C_ROSTER, + existing["id"], + { + "avatar": url, + "face_ok": True, + "liveness_status": live if live in {"verified", "pending"} else "none", + "updated_at": now, + }, + ) + + +def save_liveness_audit( + guest_id: str, + *, + front_url: str, + turn_url: str, + video_url: str, + video_size: int, + similarity: float | None, + yaw_delta: float | None, + meta: dict[str, Any] | None = None, +) -> dict[str, Any]: + """Live capture audit only — never overwrites roster.avatar.""" + init_pb() + now = _now() + item = { + "id": _uid("live"), + "guestId": guest_id, + "frontUrl": front_url, + "turnUrl": turn_url, + "videoUrl": video_url, + "videoSize": int(video_size or 0), + "similarity": similarity, + "yawDelta": yaw_delta, + "status": "verified", + "createdAt": now, + } + rec = get_pb().create( + C_LIVENESS, + { + "guest_id": guest_id, + "avatar_url": "", # not an avatar + "front_url": front_url[:500], + "turn_url": turn_url[:500], + "video_url": (video_url or "")[:500], + "video_size": item["videoSize"], + "similarity": similarity, + "yaw_delta": yaw_delta, + "status": "verified", + "meta": meta or {}, + "created_at": now, + }, + ) + item["id"] = rec.get("id") or item["id"] + + existing = get_pb().first(C_ROSTER, filter=f"guest_id={pb_quote(guest_id)}") + patch = { + "face_ok": True, + "liveness_status": "verified", + "liveness_at": now, + "liveness_video_url": (video_url or "")[:500], + "liveness_front_url": front_url[:500], + "liveness_turn_url": turn_url[:500], + "updated_at": now, + } + if existing: + get_pb().update(C_ROSTER, existing["id"], patch) + else: + get_pb().create( + C_ROSTER, + { + "guest_id": guest_id, + "name": "游民", + "avatar": "", + "discoverable": True, + "status": "online", + **patch, + }, + ) + return item + + +def list_liveness_audits(*, status: str = "", limit: int = 50) -> list[dict[str, Any]]: + init_pb() + filt = f"status={pb_quote(status)}" if status else None + rows = get_pb().list_all(C_LIVENESS, filter=filt, sort="-created_at", hard_limit=limit) + return [ + { + "id": r.get("id"), + "guestId": r.get("guest_id"), + "frontUrl": r.get("front_url") or "", + "turnUrl": r.get("turn_url") or "", + "videoUrl": r.get("video_url") or "", + "videoSize": r.get("video_size") or 0, + "status": r.get("status"), + "createdAt": r.get("created_at"), + } + for r in rows + ] + + +def list_discovery_roster( + *, + viewer_guest_id: str | None = None, + city: str = "", + limit: int = 48, + exclude_self: bool = True, +) -> list[dict[str, Any]]: + init_pb() + rows = get_pb().list_all(C_ROSTER, sort="-updated_at", hard_limit=400) + city_f = "".join((city or "").strip().lower().split()) + viewer = get_roster(viewer_guest_id) if viewer_guest_id else None + items: list[dict[str, Any]] = [] + for r in rows: + if exclude_self and viewer_guest_id and r.get("guest_id") == viewer_guest_id: + continue + if r.get("discoverable") is False: + continue + if not (r.get("name") or "").strip(): + continue + item = _roster_from_rec(r, public=True) + if city_f and city_f not in "".join((item.get("city") or "").lower().split()): + # still allow if no city filter strict — filter when city provided + if city_f: + continue + items.append(item) + + def score(it: dict[str, Any]) -> float: + s = 0.0 + if viewer and viewer.get("city") and viewer["city"] and viewer["city"] in (it.get("city") or ""): + s += 100 + if it.get("online"): + s += 20 + return s + + items.sort(key=score, reverse=True) + return items[: max(1, min(int(limit or 48), 100))] + + +def city_recommendations(guest_id: str, *, limit: int = 3) -> list[dict[str, Any]]: + return list_discovery_roster( + viewer_guest_id=guest_id, limit=limit, exclude_self=True + ) + + +def clear_liveness_for_guest(guest_id: str) -> dict[str, Any]: + """Soft-clear live audits (archive each) and reset liveness fields; keep album avatar.""" + init_pb() + pb = get_pb() + audits = pb.list_all(C_LIVENESS, filter=f"guest_id={pb_quote(guest_id)}") + for a in audits: + soft_delete_record( + entity="liveness", + entity_id=str(a.get("id")), + live_collection=C_LIVENESS, + record=a, + guest_id=guest_id, + note="clear_liveness_for_guest", + ) + rec = pb.first(C_ROSTER, filter=f"guest_id={pb_quote(guest_id)}") + if rec: + archive_snapshot( + entity="roster", + entity_id=guest_id, + action="liveness_reset", + payload=dict(rec), + guest_id=guest_id, + ) + pb.update( + C_ROSTER, + rec["id"], + { + "liveness_status": "none", + "liveness_at": "", + "liveness_video_url": "", + "liveness_front_url": "", + "liveness_turn_url": "", + "updated_at": _now(), + }, + ) + return {"ok": True, "deletedAudits": len(audits), "soft": True} + + +# —— channel messages —— + + +def _ch_meta(channel_id: str) -> dict[str, Any] | None: + return get_pb().first(C_CHMETA, filter=f"channel_id={pb_quote(channel_id)}") + + +def channel_seq(channel_id: str) -> int: + init_pb() + meta = _ch_meta(channel_id) + if meta: + return max(0, int(meta.get("seq") or 0)) + rows = get_pb().list_all( + C_MESSAGES, + filter=f"channel_id={pb_quote(channel_id)}", + sort="-seq", + hard_limit=1, + ) + return int(rows[0].get("seq") or 0) if rows else 0 + + +def list_messages( + channel_id: str, + limit: int = 100, + *, + since: int | None = None, + before: int | None = None, + q: str | None = None, +) -> list[dict[str, Any]]: + init_pb() + lim = max(1, min(int(limit or 100), 500)) + rows = get_pb().list_all( + C_MESSAGES, + filter=f"channel_id={pb_quote(channel_id)}", + sort="seq", + hard_limit=2000, + ) + needle = (q or "").strip().lower() + out: list[dict[str, Any]] = [] + for r in rows: + seq = int(r.get("seq") or 0) + if since is not None and since > 0 and seq <= since: + continue + if before is not None and before > 0 and seq >= before: + continue + text = r.get("text") or "" + nick = r.get("nick") or "" + if needle and needle not in text.lower() and needle not in nick.lower(): + continue + if r.get("recalled"): + continue + out.append( + { + "id": r.get("id"), + "channelId": channel_id, + "seq": seq, + "guestId": r.get("guest_id"), + "author": nick or "游民", + "text": text, + "kind": r.get("kind") or "text", + "meta": r.get("meta") or {}, + "attachments": r.get("attachments") or [], + "replyTo": r.get("reply_to"), + "reactions": r.get("reactions") or {}, + "pinned": bool(r.get("pinned")), + "createdAt": r.get("created_at"), + "editedAt": r.get("edited_at") or "", + } + ) + if before is not None and before > 0: + out = out[-lim:] + else: + out = out[-lim:] + return out + + +def add_message( + channel_id: str, + author: str, + text: str, + guest_id: str, + *, + kind: str = "text", + meta: dict[str, Any] | None = None, + attachments: list[Any] | None = None, + reply_to: dict[str, Any] | None = None, +) -> dict[str, Any]: + init_pb() + pb = get_pb() + seq = channel_seq(channel_id) + 1 + now = _now() + body = { + "channel_id": channel_id, + "seq": seq, + "guest_id": guest_id, + "nick": (author or "游民")[:48], + "text": (text or "")[:4000], + "kind": kind or "text", + "meta": meta or {}, + "attachments": attachments or [], + "reply_to": reply_to, + "reactions": {}, + "pinned": False, + "recalled": False, + "created_at": now, + "edited_at": "", + } + rec = pb.create(C_MESSAGES, body) + meta_rec = _ch_meta(channel_id) + if meta_rec: + pb.update(C_CHMETA, meta_rec["id"], {"seq": seq, "updated_at": now}) + else: + pb.create( + C_CHMETA, + { + "channel_id": channel_id, + "seq": seq, + "pins": [], + "presence": {}, + "updated_at": now, + }, + ) + return { + "id": rec.get("id"), + "channelId": channel_id, + "seq": seq, + "guestId": guest_id, + "author": body["nick"], + "text": body["text"], + "kind": body["kind"], + "meta": body["meta"], + "attachments": body["attachments"], + "replyTo": reply_to, + "reactions": {}, + "pinned": False, + "createdAt": now, + } + + +def get_message(msg_id: str) -> dict[str, Any] | None: + init_pb() + try: + r = get_pb().request( + "GET", f"/api/collections/{C_MESSAGES}/records/{msg_id}", admin=True + ) + except Exception: + return None + return { + "id": r.get("id"), + "channelId": r.get("channel_id"), + "seq": int(r.get("seq") or 0), + "guestId": r.get("guest_id"), + "author": r.get("nick") or "游民", + "text": r.get("text") or "", + "kind": r.get("kind") or "text", + "meta": r.get("meta") or {}, + "attachments": r.get("attachments") or [], + "replyTo": r.get("reply_to"), + "reactions": r.get("reactions") or {}, + "pinned": bool(r.get("pinned")), + "recalled": bool(r.get("recalled")), + "createdAt": r.get("created_at"), + "editedAt": r.get("edited_at") or "", + } + + +def edit_message(channel_id: str, msg_id: str, guest_id: str, text: str) -> dict[str, Any]: + m = get_message(msg_id) + if not m or m.get("channelId") != channel_id: + raise ValueError("message not found") + if m.get("guestId") != guest_id: + raise ValueError("not your message") + if m.get("recalled"): + raise ValueError("recalled") + now = _now() + get_pb().update( + C_MESSAGES, + msg_id, + {"text": (text or "").strip()[:2000], "edited_at": now}, + ) + out = get_message(msg_id) + if not out: + raise ValueError("message not found") + return out + + +def recall_message(channel_id: str, msg_id: str, guest_id: str) -> dict[str, Any]: + m = get_message(msg_id) + if not m or m.get("channelId") != channel_id: + raise ValueError("message not found") + if m.get("guestId") != guest_id: + raise ValueError("not your message") + get_pb().update( + C_MESSAGES, + msg_id, + {"text": "", "recalled": True, "attachments": [], "reactions": {}}, + ) + out = get_message(msg_id) + if not out: + raise ValueError("message not found") + return out + + +def _public_message(m: dict[str, Any]) -> dict[str, Any]: + """Flatten PB message for API clients (matches legacy store shape).""" + item: dict[str, Any] = { + "id": m.get("id"), + "channelId": m.get("channelId"), + "author": m.get("author") or "游民", + "text": "" if m.get("recalled") else (m.get("text") or ""), + "guestId": m.get("guestId"), + "at": m.get("createdAt"), + "seq": int(m.get("seq") or 0), + } + if m.get("replyTo"): + item["replyTo"] = m["replyTo"] + if m.get("attachments"): + item["attachments"] = m["attachments"] + if m.get("reactions"): + item["reactions"] = m["reactions"] + if m.get("editedAt"): + item["editedAt"] = m["editedAt"] + if m.get("recalled"): + item["recalled"] = True + if m.get("pinned"): + item["pinned"] = True + meta = m.get("meta") or {} + if meta.get("pinnedAt"): + item["pinnedAt"] = meta["pinnedAt"] + meta = m.get("meta") or {} + if meta.get("reported"): + item["reported"] = True + if meta.get("mentions"): + item["mentions"] = meta["mentions"] + return item + + +def react_message( + channel_id: str, msg_id: str, guest_id: str, emoji: str +) -> dict[str, Any]: + key = (emoji or "").strip()[:16] + if not key: + raise ValueError("empty emoji") + m = get_message(msg_id) + if not m or m.get("channelId") != channel_id: + raise ValueError("message not found") + if m.get("recalled"): + raise ValueError("recalled") + reactions: dict[str, list[str]] = dict(m.get("reactions") or {}) + holders = list(reactions.get(key) or []) + if guest_id in holders: + holders = [g for g in holders if g != guest_id] + else: + holders.append(guest_id) + if holders: + reactions[key] = holders[:64] + else: + reactions.pop(key, None) + get_pb().update(C_MESSAGES, msg_id, {"reactions": reactions}) + out = get_message(msg_id) + if not out: + raise ValueError("message not found") + return _public_message(out) + + +def pin_message( + channel_id: str, msg_id: str, guest_id: str, pinned: bool = True +) -> dict[str, Any]: + m = get_message(msg_id) + if not m or m.get("channelId") != channel_id: + raise ValueError("message not found") + if m.get("recalled"): + raise ValueError("recalled") + meta = dict(m.get("meta") or {}) + now = _now() + if pinned: + meta["pinned"] = True + meta["pinnedAt"] = now + meta["pinnedBy"] = guest_id + else: + meta.pop("pinned", None) + meta.pop("pinnedAt", None) + meta.pop("pinnedBy", None) + get_pb().update(C_MESSAGES, msg_id, {"pinned": bool(pinned), "meta": meta}) + out = get_message(msg_id) + if not out: + raise ValueError("message not found") + return _public_message(out) + + +def report_message( + channel_id: str, msg_id: str, guest_id: str, reason: str = "" +) -> dict[str, Any]: + m = get_message(msg_id) + if not m or m.get("channelId") != channel_id: + raise ValueError("message not found") + meta = dict(m.get("meta") or {}) + reporters = list(meta.get("reporters") or []) + if guest_id not in reporters: + reporters.append(guest_id) + meta["reported"] = True + meta["reporters"] = reporters[:64] + meta["reportReason"] = (reason or "").strip()[:240] + meta["reportedAt"] = _now() + get_pb().update(C_MESSAGES, msg_id, {"meta": meta}) + out = get_message(msg_id) + if not out: + raise ValueError("message not found") + return _public_message(out) + + +def set_note(channel_id: str, guest_id: str, what: str, seq: int) -> dict[str, Any]: + what = (what or "").strip().lower() + if what not in {"recv", "read"}: + raise ValueError("what must be recv or read") + seq = max(0, int(seq)) + init_pb() + pb = get_pb() + filt = f"guest_id={pb_quote(guest_id)} && channel_id={pb_quote(channel_id)}" + existing = pb.first(C_READS, filter=filt) + recv = int((existing or {}).get("recv_seq") or 0) + read = int((existing or {}).get("read_seq") or 0) + if what == "recv": + recv = max(recv, seq) + else: + read = max(read, seq) + recv = max(recv, read) + now = _now() + pb.upsert( + C_READS, + filter=filt, + payload={ + "guest_id": guest_id, + "channel_id": channel_id, + "recv_seq": recv, + "read_seq": read, + "updated_at": now, + }, + ) + return {"channelId": channel_id, "what": what, "seq": seq, "recv": recv, "read": read} + + +def channel_desc(channel_id: str, guest_id: str | None = None) -> dict[str, Any]: + init_pb() + seq = channel_seq(channel_id) + recv = read = 0 + if guest_id: + mark = get_pb().first( + C_READS, + filter=f"guest_id={pb_quote(guest_id)} && channel_id={pb_quote(channel_id)}", + ) + if mark: + recv = int(mark.get("recv_seq") or 0) + read = int(mark.get("read_seq") or 0) + return { + "channelId": channel_id, + "seq": seq, + "recv": recv, + "read": read, + "unread": max(0, seq - read), + } + + +def save_file_meta( + file_id: str, + channel_id: str, + guest_id: str, + *, + kind: str, + name: str, + mime: str, + size: int, + path: str, +) -> dict[str, Any]: + init_pb() + now = _now() + get_pb().upsert( + C_FILES, + filter=f"file_id={pb_quote(file_id)}", + payload={ + "file_id": file_id, + "channel_id": channel_id, + "guest_id": guest_id, + "kind": kind, + "name": name, + "mime": mime, + "size": size, + "path": path, + "created_at": now, + }, + ) + return { + "id": file_id, + "kind": kind, + "name": name, + "mime": mime, + "size": size, + "url": f"/api/social/v1/files/{file_id}", + } + + +def get_file(file_id: str) -> dict[str, Any] | None: + init_pb() + row = get_pb().first(C_FILES, filter=f"file_id={pb_quote(file_id)}") + if not row: + return None + return { + "id": row.get("file_id") or file_id, + "channelId": row.get("channel_id"), + "kind": row.get("kind"), + "name": row.get("name"), + "mime": row.get("mime"), + "size": int(row.get("size") or 0), + "path": row.get("path"), + } + + +def list_cafe_reviews(cafe_id: str, limit: int = 50) -> list[dict[str, Any]]: + init_pb() + lim = max(1, min(int(limit or 50), 200)) + rows = get_pb().list_all( + C_CAFE, + filter=f"cafe_id={pb_quote(cafe_id)}" if cafe_id else None, + sort="-created_at", + hard_limit=lim, + ) + return [ + { + "id": r.get("id"), + "cafeId": r.get("cafe_id"), + "author": r.get("author"), + "score": r.get("score"), + "text": r.get("text"), + "photoNote": r.get("photo_note") or "", + "guestId": r.get("guest_id"), + "at": r.get("created_at"), + } + for r in rows[:lim] + ] + + +def add_cafe_review( + cafe_id: str, + author: str, + score: int, + text: str, + photo_note: str, + guest_id: str, +) -> dict[str, Any]: + init_pb() + now = _now() + body = { + "cafe_id": cafe_id, + "guest_id": guest_id, + "author": (author or "游民").strip()[:48] or "游民", + "score": max(1, min(int(score or 5), 5)), + "text": (text or "").strip()[:2000], + "photo_note": (photo_note or "").strip()[:200], + "created_at": now, + } + rec = get_pb().create(C_CAFE, body) + return { + "id": rec.get("id"), + "cafeId": cafe_id, + "author": body["author"], + "score": body["score"], + "text": body["text"], + "photoNote": body["photo_note"], + "guestId": guest_id, + "at": now, + } + + +def add_feedback(kind: str, text: str, contact: str, guest_id: str) -> dict[str, Any]: + init_pb() + now = _now() + body = { + "guest_id": guest_id, + "kind": kind if kind in {"反馈", "建议"} else "建议", + "text": (text or "").strip()[:4000], + "contact": (contact or "").strip()[:120], + "created_at": now, + } + rec = get_pb().create(C_FEEDBACK, body) + return { + "id": rec.get("id"), + "kind": body["kind"], + "text": body["text"], + "contact": body["contact"], + "guestId": guest_id, + "at": now, + } + + +def add_gig_app( + gig_id: str, + name: str, + contact: str, + note: str, + guest_id: str, + request_id: str | None = None, +) -> dict[str, Any]: + import hashlib + import json as _json + + init_pb() + now = _now() + stable_id = None + if request_id: + stable_id = ( + "app_" + + hashlib.sha256( + _json.dumps([guest_id, gig_id, request_id]).encode() + ).hexdigest()[:32] + ) + body = { + "gig_id": gig_id, + "guest_id": guest_id, + "name": (name or "").strip()[:64], + "contact": (contact or "").strip()[:120], + "note": (note or "").strip()[:2000], + "request_id": request_id or "", + "created_at": now, + } + pb = get_pb() + if stable_id: + existing = pb.first( + C_GIGS, + filter=f"request_id={pb_quote(request_id or '')} && guest_id={pb_quote(guest_id)} && gig_id={pb_quote(gig_id)}", + ) + if existing: + if ( + (existing.get("name"), existing.get("contact"), existing.get("note")) + != (body["name"], body["contact"], body["note"]) + ): + raise ValueError("同一请求标识不能用于不同申请") + return { + "id": existing.get("id"), + "gigId": gig_id, + "name": existing.get("name"), + "contact": existing.get("contact"), + "note": existing.get("note") or "", + "guestId": guest_id, + "at": existing.get("created_at") or now, + } + rec = pb.create(C_GIGS, body) + return { + "id": rec.get("id") or stable_id, + "gigId": gig_id, + "name": body["name"], + "contact": body["contact"], + "note": body["note"], + "guestId": guest_id, + "at": now, + } + + +# —— admin / ugc helpers —— + + +def admin_overview() -> dict[str, Any]: + init_pb() + pb = get_pb() + counts = { + "messages": len(pb.list_all(C_MESSAGES, hard_limit=5000)), + "roster": len(pb.list_all(C_ROSTER, hard_limit=5000)), + "reviews": len(pb.list_all(C_CAFE, hard_limit=5000)), + "gigApps": len(pb.list_all(C_GIGS, hard_limit=5000)), + "feedback": len(pb.list_all(C_FEEDBACK, hard_limit=5000)), + "archives": len(pb.list_all(C_ARCHIVES, hard_limit=5000)), + } + return { + "ok": pb.health_ok(), + "backend": "pocketbase", + "path": pb.base_url, + "exists": True, + "bytes": 0, + "writable": True, + "counts": counts, + } + + +def admin_list_messages( + *, channel_id: str = "", q: str = "", limit: int = 100, offset: int = 0 +) -> dict[str, Any]: + init_pb() + lim = max(1, min(int(limit or 100), 500)) + off = max(0, int(offset or 0)) + filt = f"channel_id={pb_quote(channel_id)}" if channel_id.strip() else None + rows = get_pb().list_all(C_MESSAGES, filter=filt, sort="-created_at", hard_limit=5000) + needle = q.strip().lower() + if needle: + rows = [ + r + for r in rows + if needle in (r.get("nick") or "").lower() + or needle in (r.get("text") or "").lower() + or needle in (r.get("guest_id") or "").lower() + ] + total = len(rows) + page = rows[off : off + lim] + return { + "ok": True, + "total": total, + "items": [ + { + "id": r.get("id"), + "channelId": r.get("channel_id"), + "author": r.get("nick") or "游民", + "text": r.get("text") or "", + "guestId": r.get("guest_id"), + "at": r.get("created_at"), + } + for r in page + ], + } + + +def admin_delete_message(message_id: str) -> bool: + return soft_delete_record( + entity="messages", + entity_id=message_id, + live_collection=C_MESSAGES, + ) + + +def admin_list_roster( + *, q: str = "", limit: int = 100, offset: int = 0 +) -> dict[str, Any]: + init_pb() + lim = max(1, min(int(limit or 100), 500)) + off = max(0, int(offset or 0)) + rows = get_pb().list_all(C_ROSTER, sort="-updated_at", hard_limit=5000) + needle = q.strip().lower() + if needle: + rows = [ + r + for r in rows + if needle in (r.get("name") or "").lower() + or needle in (r.get("city") or "").lower() + or needle in (r.get("title") or "").lower() + or needle in (r.get("guest_id") or "").lower() + or needle in (r.get("bio") or "").lower() + ] + total = len(rows) + page = rows[off : off + lim] + return { + "ok": True, + "total": total, + "items": [ + { + "guestId": r.get("guest_id"), + "name": r.get("name"), + "title": r.get("title") or "", + "city": r.get("city") or "", + "phone": r.get("phone") or "", + "linktree": r.get("linktree") or "", + "skills": r.get("skills") or "", + "bio": r.get("bio") or "", + "updatedAt": r.get("updated_at"), + } + for r in page + ], + } + + +def admin_update_roster(guest_id: str, patch: dict[str, Any]) -> dict[str, Any] | None: + init_pb() + existing = get_pb().first(C_ROSTER, filter=f"guest_id={pb_quote(guest_id)}") + if not existing: + return None + archive_snapshot( + entity="roster", + entity_id=guest_id, + action="admin_update", + payload=dict(existing), + guest_id=guest_id, + ) + fields = { + "name": str(patch.get("name", existing.get("name") or ""))[:64] or "游民", + "title": str(patch.get("title", existing.get("title") or ""))[:80], + "city": str(patch.get("city", existing.get("city") or ""))[:64], + "phone": str(patch.get("phone", existing.get("phone") or ""))[:32], + "linktree": str(patch.get("linktree", existing.get("linktree") or ""))[:240], + "skills": str(patch.get("skills", existing.get("skills") or ""))[:200], + "bio": str(patch.get("bio", existing.get("bio") or ""))[:2000], + "updated_at": _now(), + } + # Admin restore from soft-delete + if patch.get("restore"): + fields["status"] = str(patch.get("status") or "online")[:32] + fields["discoverable"] = True + get_pb().update(C_ROSTER, existing["id"], fields) + out = { + **{k: fields[k] for k in ("name", "title", "city", "phone", "linktree", "skills", "bio")}, + "guestId": guest_id, + "updatedAt": fields["updated_at"], + } + archive_snapshot( + entity="roster", + entity_id=guest_id, + action="admin_update_after", + payload=dict(fields), + guest_id=guest_id, + ) + return out + + +def admin_delete_roster(guest_id: str) -> bool: + return soft_delete_record( + entity="roster", + entity_id=guest_id, + live_collection=C_ROSTER, + guest_id=guest_id, + ) + + +def admin_list_cafe_reviews( + *, cafe_id: str = "", limit: int = 100, offset: int = 0 +) -> dict[str, Any]: + init_pb() + lim = max(1, min(int(limit or 100), 500)) + off = max(0, int(offset or 0)) + filt = f"cafe_id={pb_quote(cafe_id)}" if cafe_id.strip() else None + rows = get_pb().list_all(C_CAFE, filter=filt, sort="-created_at", hard_limit=5000) + total = len(rows) + page = rows[off : off + lim] + return { + "ok": True, + "total": total, + "items": [ + { + "id": r.get("id"), + "cafeId": r.get("cafe_id"), + "author": r.get("author"), + "score": r.get("score"), + "text": r.get("text"), + "photoNote": r.get("photo_note") or "", + "guestId": r.get("guest_id"), + "at": r.get("created_at"), + } + for r in page + ], + } + + +def admin_delete_cafe_review(review_id: str) -> bool: + return soft_delete_record( + entity="reviews", + entity_id=review_id, + live_collection=C_CAFE, + ) + + +def admin_list_gig_apps( + *, gig_id: str = "", limit: int = 100, offset: int = 0 +) -> dict[str, Any]: + init_pb() + lim = max(1, min(int(limit or 100), 500)) + off = max(0, int(offset or 0)) + filt = f"gig_id={pb_quote(gig_id)}" if gig_id.strip() else None + rows = get_pb().list_all(C_GIGS, filter=filt, sort="-created_at", hard_limit=5000) + total = len(rows) + page = rows[off : off + lim] + return { + "ok": True, + "total": total, + "items": [ + { + "id": r.get("id"), + "gigId": r.get("gig_id"), + "name": r.get("name"), + "contact": r.get("contact"), + "note": r.get("note") or "", + "guestId": r.get("guest_id"), + "at": r.get("created_at"), + } + for r in page + ], + } + + +def admin_delete_gig_app(app_id: str) -> bool: + return soft_delete_record( + entity="gigApps", + entity_id=app_id, + live_collection=C_GIGS, + ) + + +def admin_list_feedback(*, limit: int = 100, offset: int = 0) -> dict[str, Any]: + init_pb() + lim = max(1, min(int(limit or 100), 500)) + off = max(0, int(offset or 0)) + rows = get_pb().list_all(C_FEEDBACK, sort="-created_at", hard_limit=5000) + total = len(rows) + page = rows[off : off + lim] + return { + "ok": True, + "total": total, + "items": [ + { + "id": r.get("id"), + "kind": r.get("kind"), + "text": r.get("text"), + "contact": r.get("contact") or "", + "guestId": r.get("guest_id"), + "at": r.get("created_at"), + } + for r in page + ], + } + + +def admin_delete_feedback(fid: str) -> bool: + return soft_delete_record( + entity="feedback", + entity_id=fid, + live_collection=C_FEEDBACK, + ) + + +def admin_stats() -> dict[str, Any]: + """Dashboard aggregates for admin visualization.""" + init_pb() + pb = get_pb() + counts = { + "messages": len(pb.list_all(C_MESSAGES, hard_limit=5000)), + "roster": len(pb.list_all(C_ROSTER, hard_limit=5000)), + "reviews": len(pb.list_all(C_CAFE, hard_limit=5000)), + "gigApps": len(pb.list_all(C_GIGS, hard_limit=5000)), + "feedback": len(pb.list_all(C_FEEDBACK, hard_limit=5000)), + "archives": len(pb.list_all(C_ARCHIVES, hard_limit=5000)), + } + soft = { + "roster": len(_soft_deleted_ids("roster")), + "messages": len(_soft_deleted_ids("messages")), + "reviews": len(_soft_deleted_ids("reviews")), + "gigApps": len(_soft_deleted_ids("gigApps")), + "feedback": len(_soft_deleted_ids("feedback")), + } + # city breakdown from live roster (exclude soft-deleted) + gone = _soft_deleted_ids("roster") + roster = [ + r + for r in pb.list_all(C_ROSTER, hard_limit=5000) + if str(r.get("guest_id") or "") not in gone and (r.get("status") or "") != "deleted" + ] + by_city: dict[str, int] = {} + by_day: dict[str, int] = {} + for r in roster: + city = (r.get("city") or "未填").strip() or "未填" + by_city[city] = by_city.get(city, 0) + 1 + day = str(r.get("updated_at") or r.get("onboarded_at") or "")[:10] + if day: + by_day[day] = by_day.get(day, 0) + 1 + city_top = sorted(by_city.items(), key=lambda x: -x[1])[:12] + day_series = sorted(by_day.items())[-30:] + return { + "ok": True, + "counts": counts, + "softDeleted": soft, + "activeRoster": len(roster), + "byCity": [{"name": k, "value": v} for k, v in city_top], + "rosterByDay": [{"date": d, "value": n} for d, n in day_series], + } + + +def admin_get_detail(entity: str, entity_id: str) -> dict[str, Any] | None: + init_pb() + pb = get_pb() + coll = ENTITY_COLLECTIONS.get(entity) + if not coll: + return None + rec = None + if entity == "roster": + rec = pb.first(coll, filter=f"guest_id={pb_quote(entity_id)}") + else: + try: + rec = pb.request( + "GET", f"/api/collections/{coll}/records/{entity_id}", admin=True + ) + except Exception: + rec = None + if not rec: + return None + hist = pb.list_all( + C_ARCHIVES, + filter=f"entity={pb_quote(entity)} && entity_id={pb_quote(entity_id)}", + sort="-created_at", + hard_limit=50, + ) + return { + "ok": True, + "entity": entity, + "id": entity_id, + "item": rec, + "softDeleted": entity_id in _soft_deleted_ids(entity) + or (rec.get("status") == "deleted"), + "history": [ + { + "id": h.get("id"), + "action": h.get("action"), + "at": h.get("created_at"), + "note": h.get("note") or "", + "payload": h.get("payload") or {}, + } + for h in hist + ], + } + + +def admin_list_archives( + *, entity: str = "", limit: int = 100, offset: int = 0 +) -> dict[str, Any]: + init_pb() + lim = max(1, min(int(limit or 100), 500)) + off = max(0, int(offset or 0)) + filt = f"entity={pb_quote(entity)}" if entity.strip() else None + rows = get_pb().list_all( + C_ARCHIVES, filter=filt, sort="-created_at", hard_limit=5000 + ) + total = len(rows) + page = rows[off : off + lim] + return { + "ok": True, + "total": total, + "items": [ + { + "id": r.get("id"), + "entity": r.get("entity"), + "entityId": r.get("entity_id"), + "guestId": r.get("guest_id") or "", + "action": r.get("action"), + "note": r.get("note") or "", + "at": r.get("created_at"), + "payload": r.get("payload") or {}, + } + for r in page + ], + } diff --git a/apps/api/services/social_svc/routers/api.py b/apps/api/services/social_svc/routers/api.py index da4024b..a89ea03 100644 --- a/apps/api/services/social_svc/routers/api.py +++ b/apps/api/services/social_svc/routers/api.py @@ -457,17 +457,18 @@ async def avatar_pose_challenge( challenge = verify_pose_challenge(front_raw, turn_raw) if not challenge.ok: raise ValueError(challenge.detail or "真人核验失败") + # Live frames are audit-only — never purpose=avatar front_up = upload_bytes( front_raw, - filename=front.filename or "avatar-front.jpg", + filename=front.filename or "liveness-front.jpg", content_type=front.content_type or "image/jpeg", - purpose="avatar", + purpose="liveness-front", guest_id=peer, max_size=max_avatar, ) turn_up = upload_bytes( turn_raw, - filename=turn.filename or "avatar-turn.jpg", + filename=turn.filename or "liveness-turn.jpg", content_type=turn.content_type or "image/jpeg", purpose="liveness-turn", guest_id=peer, @@ -490,7 +491,6 @@ async def avatar_pose_challenge( video_size = video_up.size audit = store.save_liveness_audit( peer, - avatar_url=front_up.url, front_url=front_up.url, turn_url=turn_up.url, video_url=video_url, @@ -503,29 +503,30 @@ async def avatar_pose_challenge( "has_video": bool(video_url), }, ) - return front_up, turn_up, video_url, video_size, challenge, audit + roster = store.get_roster(peer) or {} + return front_up, turn_up, video_url, video_size, challenge, audit, roster try: - front_up, turn_up, video_url, video_size, challenge, audit = await run_in_threadpool( - work + front_up, turn_up, video_url, video_size, challenge, audit, roster = ( + await run_in_threadpool(work) ) except ValueError as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc except Exception as exc: raise HTTPException(status_code=503, detail=f"核验失败: {exc}") from exc + # Do not return live frame as avatar url — keep existing album/selfie avatar + avatar_url = (roster.get("avatar") or "").strip() return { "ok": True, "success": True, - "url": front_up.url, - "object_key": front_up.object_key, - "size": front_up.size, - "content_type": front_up.content_type, - "storage": front_up.storage, + "url": avatar_url, + "avatarUrl": avatar_url, "livenessStatus": "verified", "faceOk": True, "videoUrl": video_url, "videoSize": video_size, + "frontUrl": front_up.url, "turnUrl": turn_up.url, "auditId": audit.get("id"), "challenge": { @@ -756,6 +757,20 @@ def put_my_roster( ) except Exception as exc: # noqa: BLE001 — never block profile save onboarding = {"ok": False, "error": str(exc)[:160]} + # Same-city online ping (best-effort, capped) + try: + status = str(row.get("status") or "") + city = str(row.get("city") or "").strip() + if city and status in {"online", "here", "available"}: + from social_svc.notify_bridge import notify_city_online + + peers = store.city_recommendations(guest, limit=3) + for p in peers: + pid = str(p.get("guestId") or p.get("id") or "") + if pid and pid != guest: + notify_city_online(pid, city, str(row.get("name") or "游民")) + except Exception: + pass out = {k: v for k, v in row.items() if k != "isFirstProfile"} if onboarding is not None: out["onboarding"] = onboarding @@ -823,6 +838,16 @@ async def live_join( pass # 附带实时通道 token,前端可订 live 频道 payload["realtime"] = issue_connection_token(peer, payload["channelId"]) + # Best-effort: tell other peers a room went live + try: + from social_svc.notify_bridge import notify_room_live + + for other in live.list_peers(payload.get("roomId") or room_id): + oid = str(other.get("peerId") or other.get("guestId") or "") + if oid and oid != peer: + notify_room_live(oid, f"视频厅 {payload.get('roomId') or room_id}") + except Exception: + pass return payload @@ -861,3 +886,302 @@ async def live_leave( except Exception: pass return out + + +# —— Skill swap · reviews · moderation · wrapped · digests —— + + +class SkillPostIn(BaseModel): + author: str = Field(default="游民", max_length=64) + city: str = Field(default="", max_length=64) + offer: str = Field(min_length=1, max_length=200) + want: str = Field(min_length=1, max_length=200) + note: str = Field(default="", max_length=800) + + +class MeetupReviewIn(BaseModel): + toGuest: str = Field(min_length=1, max_length=80) + toName: str = Field(default="", max_length=64) + bookingId: str = Field(default="", max_length=80) + punctuality: int = Field(ge=1, le=5) + chemistry: int = Field(ge=1, le=5) + professionalism: int = Field(ge=1, le=5) + text: str = Field(default="", max_length=800) + + +class BlockIn(BaseModel): + blockedGuest: str = Field(min_length=1, max_length=80) + reason: str = Field(default="", max_length=200) + + +class ReportIn(BaseModel): + targetGuest: str = Field(min_length=1, max_length=80) + targetName: str = Field(default="", max_length=64) + reason: str = Field(min_length=1, max_length=80) + detail: str = Field(default="", max_length=1000) + + +class ReportResolveIn(BaseModel): + status: str = Field(default="resolved", max_length=20) + resultNote: str = Field(default="", max_length=500) + + +class SocialLikeIn(BaseModel): + toGuest: str = Field(min_length=1, max_length=80) + fromName: str = Field(default="游民", max_length=64) + + +class DigestIn(BaseModel): + city: str = Field(default="", max_length=64) + weekly: bool = False + + +@router.get("/skills") +def list_skills( + city: str = Query(default=""), + limit: int = Query(default=60, ge=1, le=120), +): + from social_svc import community_board as board + + store.init_db() + return {"ok": True, "items": board.list_skill_posts(city=city, limit=limit)} + + +@router.post("/skills") +def create_skill( + body: SkillPostIn, + x_social_guest_id: str | None = Header(default=None), +): + from social_svc import community_board as board + + guest = _guest(x_social_guest_id) + store.init_db() + try: + item = board.create_skill_post( + guest, + author=body.author, + city=body.city, + offer=body.offer, + want=body.want, + note=body.note, + ) + except ValueError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + return item + + +@router.post("/skills/{post_id}/close") +def close_skill( + post_id: str, + x_social_guest_id: str | None = Header(default=None), +): + from social_svc import community_board as board + + guest = _guest(x_social_guest_id) + store.init_db() + try: + return board.close_skill_post(guest, post_id) + except ValueError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + + +@router.post("/meetup-reviews") +@router.post("/reviews") +def post_meetup_review( + body: MeetupReviewIn, + x_social_guest_id: str | None = Header(default=None), +): + from social_svc import community_board as board + + guest = _guest(x_social_guest_id) + store.init_db() + try: + return board.create_meetup_review( + guest, + to_guest=body.toGuest, + to_name=body.toName, + booking_id=body.bookingId, + punctuality=body.punctuality, + chemistry=body.chemistry, + professionalism=body.professionalism, + text=body.text, + ) + except ValueError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + + +@router.get("/meetup-reviews/{guest_id}") +@router.get("/reviews/{guest_id}") +def get_meetup_reviews( + guest_id: str, limit: int = Query(default=40, ge=1, le=100) +): + from social_svc import community_board as board + + store.init_db() + return {"ok": True, **board.reviews_for_guest(guest_id, limit=limit)} + + +@router.post("/blocks") +def post_block( + body: BlockIn, + x_social_guest_id: str | None = Header(default=None), +): + from social_svc import community_board as board + + guest = _guest(x_social_guest_id) + store.init_db() + try: + return board.block_user(guest, body.blockedGuest, body.reason) + except ValueError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + + +@router.delete("/blocks/{blocked_guest}") +def delete_block( + blocked_guest: str, + x_social_guest_id: str | None = Header(default=None), +): + from social_svc import community_board as board + + guest = _guest(x_social_guest_id) + store.init_db() + return board.unblock_user(guest, blocked_guest) + + +@router.get("/blocks") +def get_blocks(x_social_guest_id: str | None = Header(default=None)): + from social_svc import community_board as board + + guest = _guest(x_social_guest_id) + store.init_db() + return {"ok": True, "items": board.list_blocks(guest)} + + +@router.post("/reports") +def post_report( + body: ReportIn, + x_social_guest_id: str | None = Header(default=None), +): + from social_svc import community_board as board + + guest = _guest(x_social_guest_id) + store.init_db() + try: + return board.create_report( + guest, + target_guest=body.targetGuest, + target_name=body.targetName, + reason=body.reason, + detail=body.detail, + ) + except ValueError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + + +@router.post("/reports/{report_id}/resolve") +def resolve_report( + report_id: str, + body: ReportResolveIn, + x_social_guest_id: str | None = Header(default=None), +): + from social_svc import community_board as board + from social_svc.notify_bridge import notify_report_result + + _guest(x_social_guest_id) + store.init_db() + try: + item = board.resolve_report( + report_id, status=body.status, result_note=body.resultNote + ) + except ValueError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + try: + notify_report_result( + item["guestId"], + body.resultNote or f"举报已处理:{body.status}", + body.status, + ) + except Exception: + pass + return item + + +@router.get("/reports") +def get_reports( + status: str = Query(default="open"), + limit: int = Query(default=40, ge=1, le=100), + x_social_guest_id: str | None = Header(default=None), +): + from social_svc import community_board as board + + _guest(x_social_guest_id) + store.init_db() + return {"ok": True, "items": board.list_reports(status=status, limit=limit)} + + +@router.post("/social-events/like") +def social_like_event( + body: SocialLikeIn, + x_social_guest_id: str | None = Header(default=None), +): + from social_svc.notify_bridge import notify_like + + _guest(x_social_guest_id) + try: + notify_like(body.toGuest, body.fromName) + except Exception as exc: + raise HTTPException(status_code=503, detail=str(exc)[:160]) from exc + return {"ok": True} + + +class BoardJoinEventIn(BaseModel): + ownerGuest: str = Field(min_length=1, max_length=80) + actorName: str = Field(default="游民", max_length=64) + boardTitle: str = Field(default="看板", max_length=120) + + +@router.post("/social-events/board-join") +def social_board_join_event( + body: BoardJoinEventIn, + x_social_guest_id: str | None = Header(default=None), +): + from social_svc.notify_bridge import notify_board_join + + _guest(x_social_guest_id) + try: + notify_board_join(body.ownerGuest, body.actorName, body.boardTitle) + except Exception as exc: + raise HTTPException(status_code=503, detail=str(exc)[:160]) from exc + return {"ok": True} + + +@router.get("/wrapped") +def get_wrapped( + year: int | None = Query(default=None), + x_social_guest_id: str | None = Header(default=None), +): + from social_svc import community_board as board + + guest = _guest(x_social_guest_id) + store.init_db() + return {"ok": True, **board.wrapped_stats(guest, year=year)} + + +@router.post("/digests/city") +def post_city_digest( + body: DigestIn, + x_social_guest_id: str | None = Header(default=None), +): + from social_svc import community_board as board + from social_svc.notify_bridge import fire_city_digest + + guest = _guest(x_social_guest_id) + store.init_db() + payload = board.city_digest_payload(body.city) + fire_city_digest( + guest, + payload["city"], + payload["digestText"], + weekly=body.weekly, + ) + return {"ok": True, **payload} diff --git a/apps/api/services/social_svc/s3_upload.py b/apps/api/services/social_svc/s3_upload.py index ffeac30..2ee08ba 100644 --- a/apps/api/services/social_svc/s3_upload.py +++ b/apps/api/services/social_svc/s3_upload.py @@ -145,7 +145,14 @@ def upload_bytes( pass # Local fallback (dev / S3 off / S3 error) - sub = "liveness" if allow_video or ctype.startswith("video/") else "avatars" + # Live audit assets never land in avatars/ + sub = ( + "liveness" + if allow_video + or ctype.startswith("video/") + or (purpose or "").startswith("liveness") + else "avatars" + ) path = SOCIAL_UPLOAD_DIR / sub / Path(key).name path.parent.mkdir(parents=True, exist_ok=True) path.write_bytes(data) diff --git a/apps/api/services/social_svc/store.py b/apps/api/services/social_svc/store.py index 13742f6..45c99fa 100644 --- a/apps/api/services/social_svc/store.py +++ b/apps/api/services/social_svc/store.py @@ -34,27 +34,30 @@ def _now() -> str: @contextmanager def db(*, commit: bool = True) -> Iterator[sqlite3.Connection]: - SOCIAL_DB_PATH.parent.mkdir(parents=True, exist_ok=True) - conn = _connect(SOCIAL_DB_PATH) - try: - try: - conn.execute("PRAGMA busy_timeout=5000") - except Exception: - pass - yield conn - if commit: - conn.commit() - except Exception: - conn.rollback() - raise - finally: - conn.close() + """SQLite removed — use PocketBase via social_svc.pb_data / nomadro_pb.""" + raise RuntimeError( + "social_svc SQLite disabled; use PocketBase via social_svc.pb_data / nomadro_pb" + ) + yield # pragma: no cover _DB_READY = False def init_db() -> None: + """PocketBase online SoT — no SQLite.""" + try: + from nomadro_pb import ensure_once + + ensure_once() + except Exception: + pass + return + # legacy sqlite bootstrap kept below for reference but unreachable + _legacy_init_db() + + +def _legacy_init_db() -> None: global _DB_READY if _DB_READY: return @@ -163,6 +166,12 @@ def init_db() -> None: roster_cols = {r[1] for r in conn.execute("PRAGMA table_info(roster)").fetchall()} if "avatar" not in roster_cols: conn.execute("ALTER TABLE roster ADD COLUMN avatar TEXT") + try: + from social_svc.community_board import ensure_community_tables + + ensure_community_tables() + except Exception: + pass # P0 cold-start profile fields (join → discovery ranking) for col, decl in ( ("gender", "TEXT"), @@ -345,52 +354,19 @@ def _get_message_row(conn: sqlite3.Connection, msg_id: str) -> sqlite3.Row | Non def channel_seq(channel_id: str) -> int: """Latest message seq for a channel (cheap; no presence / read marks).""" - init_db() - with db(commit=False) as conn: - meta = conn.execute( - "SELECT next_seq FROM channel_meta WHERE channel_id = ?", (channel_id,) - ).fetchone() - if meta: - return max(0, int(meta["next_seq"]) - 1) - row = conn.execute( - "SELECT MAX(seq) AS m FROM messages WHERE channel_id = ?", (channel_id,) - ).fetchone() - return int(row["m"] or 0) + from social_svc import pb_data + + return pb_data.channel_seq(channel_id) def channel_desc(channel_id: str, guest_id: str | None = None) -> dict[str, Any]: """Tinode-like topic desc: latest seq + caller's recv/read watermarks.""" - init_db() - with db(commit=False) as conn: - meta = conn.execute( - "SELECT next_seq FROM channel_meta WHERE channel_id = ?", (channel_id,) - ).fetchone() - if meta: - seq = max(0, int(meta["next_seq"]) - 1) - else: - row = conn.execute( - "SELECT MAX(seq) AS m FROM messages WHERE channel_id = ?", (channel_id,) - ).fetchone() - seq = int(row["m"] or 0) - recv = read = 0 - if guest_id: - mark = conn.execute( - """ - SELECT recv_seq, read_seq FROM channel_read - WHERE guest_id = ? AND channel_id = ? - """, - (guest_id, channel_id), - ).fetchone() - if mark: - recv = int(mark["recv_seq"] or 0) - read = int(mark["read_seq"] or 0) + from social_svc import pb_data + + base = pb_data.channel_desc(channel_id, guest_id) peers = online_peers(channel_id) return { - "channelId": channel_id, - "seq": seq, - "recv": recv, - "read": read, - "unread": max(0, seq - read), + **base, "online": len(peers), "peers": peers, } @@ -405,59 +381,11 @@ def list_messages( q: str | None = None, ) -> list[dict[str, Any]]: """History with Tinode-style seq cursors (since exclusive, before exclusive).""" - lim = max(1, min(int(limit or 100), 500)) - needle = (q or "").strip()[:80] - with db(commit=False) as conn: - if needle: - like = f"%{needle}%" - rows = conn.execute( - f""" - SELECT {_MSG_COLS} - FROM messages - WHERE channel_id = ? - AND COALESCE(json_extract(meta, '$.recalled'), 0) = 0 - AND (text LIKE ? OR author LIKE ?) - ORDER BY COALESCE(seq, 0) DESC, rowid DESC - LIMIT ? - """, - (channel_id, like, like, lim), - ).fetchall() - return [_row_message(r) for r in reversed(rows)] - if since is not None and since > 0: - rows = conn.execute( - f""" - SELECT {_MSG_COLS} - FROM messages - WHERE channel_id = ? AND seq IS NOT NULL AND seq > ? - ORDER BY seq ASC - LIMIT ? - """, - (channel_id, since, lim), - ).fetchall() - return [_row_message(r) for r in rows] - if before is not None and before > 0: - rows = conn.execute( - f""" - SELECT {_MSG_COLS} - FROM messages - WHERE channel_id = ? AND seq IS NOT NULL AND seq < ? - ORDER BY seq DESC - LIMIT ? - """, - (channel_id, before, lim), - ).fetchall() - return [_row_message(r) for r in reversed(rows)] - rows = conn.execute( - f""" - SELECT {_MSG_COLS} - FROM messages - WHERE channel_id = ? - ORDER BY COALESCE(seq, 0) DESC, rowid DESC - LIMIT ? - """, - (channel_id, lim), - ).fetchall() - return [_row_message(r) for r in reversed(rows)] + from social_svc import pb_data + + return pb_data.list_messages( + channel_id, limit, since=since, before=before, q=q + ) def _normalize_reply(reply_to: dict[str, Any] | None) -> dict[str, Any] | None: @@ -530,176 +458,57 @@ def add_message( if mention_list: meta["mentions"] = mention_list - msg_id = ( - "msg_" - + hashlib.sha256(json.dumps([guest_id, channel_id, client_id]).encode()).hexdigest()[:32] - if client_id - else _uid("msg") - ) - item = { - "id": msg_id, - "channelId": channel_id, - "author": (author or "游民").strip()[:48] or "游民", - "text": body, - "guestId": guest_id, - "at": _now(), - "seq": 0, - } - with db() as conn: - existing = _get_message(conn, msg_id) - if existing: - if existing["text"] != item["text"] or existing["author"] != item["author"]: - raise ValueError("同一请求标识不能用于不同消息") - out = _row_message(existing) - if client_id: - out["clientId"] = client_id - return out + from social_svc import pb_data - ch_meta = conn.execute( - "SELECT next_seq FROM channel_meta WHERE channel_id = ?", (channel_id,) - ).fetchone() - if ch_meta: - seq = int(ch_meta["next_seq"]) - conn.execute( - "UPDATE channel_meta SET next_seq = ? WHERE channel_id = ?", - (seq + 1, channel_id), - ) - else: - seq = 1 - conn.execute( - "INSERT INTO channel_meta(channel_id, next_seq) VALUES (?, ?)", - (channel_id, 2), - ) - item["seq"] = seq - conn.execute( - f""" - INSERT INTO messages({_MSG_COLS}) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) - """, - ( - item["id"], - item["channelId"], - item["author"], - item["text"], - guest_id, - item["at"], - seq, - client_id, - _dump_meta(meta), - ), - ) - out = {**item, **{k: v for k, v in { - "clientId": client_id, - "replyTo": reply, - "attachments": atts or None, - "mentions": mention_list or None, - }.items() if v}} + out = pb_data.add_message( + channel_id, + author, + body, + guest_id, + kind="text", + meta=meta, + attachments=atts, + reply_to=reply, + ) + if client_id: + out["clientId"] = client_id + if mention_list: + out["mentions"] = mention_list + out["at"] = out.get("createdAt") or _now() return out def edit_message(channel_id: str, msg_id: str, guest_id: str, text: str) -> dict[str, Any]: + from social_svc import pb_data + body = (text or "").strip()[:2000] if not body: raise ValueError("empty text") - with db() as conn: - row = _get_message(conn, msg_id) - if not row or row["channel_id"] != channel_id: - raise ValueError("message not found") - if row["guest_id"] != guest_id: - raise ValueError("not your message") - meta = _parse_meta(row["meta"] if "meta" in row.keys() else None) - if meta.get("recalled"): - raise ValueError("recalled") - meta["editedAt"] = _now() - conn.execute( - "UPDATE messages SET text = ?, meta = ? WHERE id = ?", - (body, _dump_meta(meta), msg_id), - ) - row = _get_message(conn, msg_id) - return _row_message(row) # type: ignore[arg-type] + return pb_data.edit_message(channel_id, msg_id, guest_id, body) def recall_message(channel_id: str, msg_id: str, guest_id: str) -> dict[str, Any]: """Element-style redact: clear body, keep shell for timeline continuity.""" - with db() as conn: - row = _get_message(conn, msg_id) - if not row or row["channel_id"] != channel_id: - raise ValueError("message not found") - if row["guest_id"] != guest_id: - raise ValueError("not your message") - meta = _parse_meta(row["meta"] if "meta" in row.keys() else None) - meta["recalled"] = True - meta["recalledAt"] = _now() - meta.pop("attachments", None) - meta.pop("reactions", None) - conn.execute( - "UPDATE messages SET text = '', meta = ? WHERE id = ?", - (_dump_meta(meta), msg_id), - ) - row = _get_message(conn, msg_id) - return _row_message(row) # type: ignore[arg-type] + from social_svc import pb_data + + return pb_data.recall_message(channel_id, msg_id, guest_id) def react_message( channel_id: str, msg_id: str, guest_id: str, emoji: str ) -> dict[str, Any]: """Toggle annotation reaction (Element / Matrix m.annotation pattern).""" - key = (emoji or "").strip()[:16] - if not key: - raise ValueError("empty emoji") - with db() as conn: - row = _get_message(conn, msg_id) - if not row or row["channel_id"] != channel_id: - raise ValueError("message not found") - meta = _parse_meta(row["meta"] if "meta" in row.keys() else None) - if meta.get("recalled"): - raise ValueError("recalled") - reactions: dict[str, list[str]] = dict(meta.get("reactions") or {}) - holders = list(reactions.get(key) or []) - if guest_id in holders: - holders = [g for g in holders if g != guest_id] - else: - holders.append(guest_id) - if holders: - reactions[key] = holders[:64] - else: - reactions.pop(key, None) - if reactions: - meta["reactions"] = reactions - else: - meta.pop("reactions", None) - conn.execute( - "UPDATE messages SET meta = ? WHERE id = ?", - (_dump_meta(meta), msg_id), - ) - row = _get_message(conn, msg_id) - return _row_message(row) # type: ignore[arg-type] + from social_svc import pb_data + + return pb_data.react_message(channel_id, msg_id, guest_id, emoji) def pin_message( channel_id: str, msg_id: str, guest_id: str, pinned: bool = True ) -> dict[str, Any]: - with db() as conn: - row = _get_message(conn, msg_id) - if not row or row["channel_id"] != channel_id: - raise ValueError("message not found") - meta = _parse_meta(row["meta"] if "meta" in row.keys() else None) - if meta.get("recalled"): - raise ValueError("recalled") - if pinned: - meta["pinned"] = True - meta["pinnedAt"] = _now() - meta["pinnedBy"] = guest_id - else: - meta.pop("pinned", None) - meta.pop("pinnedAt", None) - meta.pop("pinnedBy", None) - conn.execute( - "UPDATE messages SET meta = ? WHERE id = ?", - (_dump_meta(meta), msg_id), - ) - row = _get_message(conn, msg_id) - return _row_message(row) # type: ignore[arg-type] + from social_svc import pb_data + + return pb_data.pin_message(channel_id, msg_id, guest_id, pinned) def save_upload( @@ -712,6 +521,7 @@ def save_upload( data: bytes, ) -> dict[str, Any]: from social_svc.config import SOCIAL_UPLOAD_DIR, SOCIAL_UPLOAD_MAX_BYTES + from social_svc import pb_data if len(data) > SOCIAL_UPLOAD_MAX_BYTES: raise ValueError("file too large") @@ -723,49 +533,22 @@ def save_upload( root.mkdir(parents=True, exist_ok=True) path = root / f"{file_id}_{safe_name}" path.write_bytes(data) - item = { - "id": file_id, - "kind": kind, - "name": safe_name, - "mime": (mime or "application/octet-stream")[:120], - "size": len(data), - "url": f"/api/social/v1/files/{file_id}", - } - with db() as conn: - conn.execute( - """ - INSERT INTO files(id, channel_id, guest_id, kind, name, mime, size, path, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) - """, - ( - file_id, - channel_id, - guest_id, - kind, - safe_name, - item["mime"], - item["size"], - str(path), - _now(), - ), - ) - return item + return pb_data.save_file_meta( + file_id, + channel_id, + guest_id, + kind=kind, + name=safe_name, + mime=(mime or "application/octet-stream")[:120], + size=len(data), + path=str(path), + ) def get_file(file_id: str) -> dict[str, Any] | None: - with db() as conn: - row = conn.execute("SELECT * FROM files WHERE id = ?", (file_id,)).fetchone() - if not row: - return None - return { - "id": row["id"], - "channelId": row["channel_id"], - "kind": row["kind"], - "name": row["name"], - "mime": row["mime"], - "size": row["size"], - "path": row["path"], - } + from social_svc import pb_data + + return pb_data.get_file(file_id) # Element-like soft presence (TTL heartbeat; UI-agnostic) @@ -776,6 +559,7 @@ _PRESENCE_TTL_SEC = 45 def touch_presence( channel_id: str, guest_id: str, nick: str = "" ) -> dict[str, Any]: + """Soft presence: process-local TTL map (fast path). PB ch_meta.presence is best-effort mirror.""" now = time.time() room = _PRESENCE.setdefault(channel_id, {}) room[guest_id] = { @@ -788,6 +572,34 @@ def touch_presence( for gid in dead: room.pop(gid, None) peers = online_peers(channel_id) + try: + from social_svc import pb_data + from nomadro_pb import get_pb, pb_quote + + pb_data.init_pb() + meta = get_pb().first( + pb_data.C_CHMETA, filter=f"channel_id={pb_quote(channel_id)}" + ) + presence = { + p["guestId"]: {"nick": p["nick"], "at": now} for p in peers + } + if meta: + get_pb().update( + pb_data.C_CHMETA, meta["id"], {"presence": presence, "updated_at": _now()} + ) + else: + get_pb().create( + pb_data.C_CHMETA, + { + "channel_id": channel_id, + "seq": 0, + "pins": [], + "presence": presence, + "updated_at": _now(), + }, + ) + except Exception: + pass return {"channelId": channel_id, "online": len(peers), "peers": peers} @@ -807,88 +619,22 @@ def online_peers(channel_id: str) -> list[dict[str, Any]]: def report_message( channel_id: str, msg_id: str, guest_id: str, reason: str = "" ) -> dict[str, Any]: - with db() as conn: - row = _get_message(conn, msg_id) - if not row or row["channel_id"] != channel_id: - raise ValueError("message not found") - meta = _parse_meta(row["meta"] if "meta" in row.keys() else None) - reporters = list(meta.get("reporters") or []) - if guest_id not in reporters: - reporters.append(guest_id) - meta["reported"] = True - meta["reporters"] = reporters[:64] - meta["reportReason"] = (reason or "").strip()[:240] - meta["reportedAt"] = _now() - conn.execute( - "UPDATE messages SET meta = ? WHERE id = ?", - (_dump_meta(meta), msg_id), - ) - row = _get_message(conn, msg_id) - return _row_message(row) # type: ignore[arg-type] + from social_svc import pb_data + + return pb_data.report_message(channel_id, msg_id, guest_id, reason) def set_note(channel_id: str, guest_id: str, what: str, seq: int) -> dict[str, Any]: """Persist recv/read watermark (Tinode {note}).""" - what = (what or "").strip().lower() - if what not in {"recv", "read"}: - raise ValueError("what must be recv or read") - seq = max(0, int(seq)) - init_db() - now = _now() - with db() as conn: - row = conn.execute( - """ - SELECT recv_seq, read_seq FROM channel_read - WHERE guest_id = ? AND channel_id = ? - """, - (guest_id, channel_id), - ).fetchone() - recv = int(row["recv_seq"]) if row else 0 - read = int(row["read_seq"]) if row else 0 - if what == "recv": - recv = max(recv, seq) - else: - read = max(read, seq) - recv = max(recv, read) - conn.execute( - """ - INSERT INTO channel_read(guest_id, channel_id, recv_seq, read_seq, updated_at) - VALUES (?, ?, ?, ?, ?) - ON CONFLICT(guest_id, channel_id) DO UPDATE SET - recv_seq = excluded.recv_seq, - read_seq = excluded.read_seq, - updated_at = excluded.updated_at - """, - (guest_id, channel_id, recv, read, now), - ) - return {"channelId": channel_id, "what": what, "seq": seq, "recv": recv, "read": read} + from social_svc import pb_data + + return pb_data.set_note(channel_id, guest_id, what, seq) def list_reviews(cafe_id: str, limit: int = 50) -> list[dict[str, Any]]: - with db() as conn: - rows = conn.execute( - """ - SELECT id, cafe_id, author, score, text, photo_note, guest_id, created_at - FROM cafe_reviews - WHERE cafe_id = ? - ORDER BY created_at DESC - LIMIT ? - """, - (cafe_id, max(1, min(limit, 200))), - ).fetchall() - return [ - { - "id": r["id"], - "cafeId": r["cafe_id"], - "author": r["author"], - "score": r["score"], - "text": r["text"], - "photoNote": r["photo_note"] or "", - "guestId": r["guest_id"], - "at": r["created_at"], - } - for r in rows - ] + from social_svc import pb_data + + return pb_data.list_cafe_reviews(cafe_id, limit) def add_review( @@ -899,34 +645,11 @@ def add_review( photo_note: str, guest_id: str, ) -> dict[str, Any]: - item = { - "id": _uid("rv"), - "cafeId": cafe_id, - "author": (author or "游民").strip()[:48] or "游民", - "score": max(1, min(int(score or 5), 5)), - "text": text.strip()[:2000], - "photoNote": (photo_note or "").strip()[:200], - "guestId": guest_id, - "at": _now(), - } - with db() as conn: - conn.execute( - """ - INSERT INTO cafe_reviews(id, cafe_id, author, score, text, photo_note, guest_id, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?) - """, - ( - item["id"], - item["cafeId"], - item["author"], - item["score"], - item["text"], - item["photoNote"], - guest_id, - item["at"], - ), - ) - return item + from social_svc import pb_data + + return pb_data.add_cafe_review( + cafe_id, author, score, text, photo_note, guest_id + ) def _norm_city(city: str) -> str: @@ -988,126 +711,16 @@ def _roster_row_to_dict(r: Any, *, public: bool = False) -> dict[str, Any]: def get_roster(guest_id: str) -> dict[str, Any] | None: - with db() as conn: - r = conn.execute("SELECT * FROM roster WHERE guest_id = ?", (guest_id,)).fetchone() - if not r: - return None - return _roster_row_to_dict(r, public=False) + from social_svc import pb_data + + return pb_data.get_roster(guest_id) def upsert_roster(guest_id: str, payload: dict[str, Any]) -> dict[str, Any]: - """Insert/update roster. Returns (row, is_first_profile).""" - updated = _now() - avatar = str(payload.get("avatar") or "").strip()[:500] - if avatar and not ( - avatar.startswith("https://") - or avatar.startswith("http://") - or avatar.startswith("/api/social/") - ): - avatar = "" - intents_raw = payload.get("intents") - if isinstance(intents_raw, list): - intents = ",".join(str(x).strip() for x in intents_raw if str(x).strip())[:240] - else: - intents = str(intents_raw or "").strip()[:240] - status = str(payload.get("status") or "online").strip()[:32] or "online" - if status not in {"online", "away", "offline", "here", "available"}: - status = "online" - looking = str( - payload.get("lookingFor") or payload.get("looking_for") or "" - ).strip()[:200] - if not looking and intents: - looking = intents.replace(",", " · ")[:200] - discoverable = payload.get("discoverable") - if discoverable is None: - discoverable = 1 - else: - discoverable = 1 if str(discoverable).lower() not in {"0", "false", "no", "off"} else 0 + """Insert/update roster on PocketBase.""" + from social_svc import pb_data - existing = get_roster(guest_id) - is_first = existing is None - onboarded_at = (existing or {}).get("onboardedAt") or (updated if is_first else "") - - row = { - "guestId": guest_id, - "name": str(payload.get("name") or "").strip()[:64] or "游民", - "title": str(payload.get("title") or "").strip()[:80], - "city": str(payload.get("city") or "").strip()[:64], - "phone": str(payload.get("phone") or "").strip()[:32], - "linktree": str(payload.get("linktree") or "").strip()[:240], - "skills": str(payload.get("skills") or "").strip()[:200], - "bio": str(payload.get("bio") or "").strip()[:2000], - "avatar": avatar, - "gender": str(payload.get("gender") or "").strip()[:16], - "intents": intents, - "availability": str(payload.get("availability") or "").strip()[:120], - "status": status, - "lookingFor": looking, - "relationship": str(payload.get("relationship") or "").strip()[:32], - "education": str(payload.get("education") or "").strip()[:32], - "graduation": str(payload.get("graduation") or "").strip()[:32], - "wechat": str(payload.get("wechat") or "").strip()[:64], - "discoverable": discoverable, - "onboardedAt": onboarded_at, - "updatedAt": updated, - "isFirstProfile": is_first, - } - with db() as conn: - conn.execute( - """ - INSERT INTO roster( - guest_id, name, title, city, phone, linktree, skills, bio, avatar, - gender, intents, availability, status, looking_for, - relationship, education, graduation, wechat, discoverable, onboarded_at, updated_at - ) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - ON CONFLICT(guest_id) DO UPDATE SET - name=excluded.name, - title=excluded.title, - city=excluded.city, - phone=excluded.phone, - linktree=excluded.linktree, - skills=excluded.skills, - bio=excluded.bio, - avatar=excluded.avatar, - gender=excluded.gender, - intents=excluded.intents, - availability=excluded.availability, - status=excluded.status, - looking_for=excluded.looking_for, - relationship=excluded.relationship, - education=excluded.education, - graduation=excluded.graduation, - wechat=excluded.wechat, - discoverable=excluded.discoverable, - onboarded_at=COALESCE(roster.onboarded_at, excluded.onboarded_at), - updated_at=excluded.updated_at - """, - ( - guest_id, - row["name"], - row["title"], - row["city"], - row["phone"], - row["linktree"], - row["skills"], - row["bio"], - row["avatar"], - row["gender"], - row["intents"], - row["availability"], - row["status"], - row["lookingFor"], - row["relationship"], - row["education"], - row["graduation"], - row["wechat"], - row["discoverable"], - row["onboardedAt"], - updated, - ), - ) - return row + return pb_data.upsert_roster(guest_id, payload) def score_discovery( @@ -1155,34 +768,14 @@ def list_discovery_roster( exclude_self: bool = True, ) -> list[dict[str, Any]]: """Public discovery cards ranked for viewer (same-city + online + tags).""" - limit = max(1, min(int(limit or 48), 100)) - viewer = get_roster(viewer_guest_id) if viewer_guest_id else None - with db() as conn: - rows = conn.execute( - """ - SELECT * FROM roster - WHERE COALESCE(discoverable, 1) = 1 - AND TRIM(COALESCE(name, '')) != '' - ORDER BY updated_at DESC - LIMIT 400 - """ - ).fetchall() - items: list[dict[str, Any]] = [] - city_f = _norm_city(city) - for r in rows: - if exclude_self and viewer_guest_id and r["guest_id"] == viewer_guest_id: - continue - item = _roster_row_to_dict(r, public=True) - if city_f: - ic = _norm_city(item.get("city") or "") - if not ic or (city_f not in ic and ic not in city_f): - continue - item["score"] = score_discovery(viewer, item) - items.append(item) - items.sort( - key=lambda x: (-int(x.get("score") or 0), str(x.get("updatedAt") or "")), + from social_svc import pb_data + + return pb_data.list_discovery_roster( + viewer_guest_id=viewer_guest_id, + city=city, + limit=limit, + exclude_self=exclude_self, ) - return items[:limit] def city_recommendations( @@ -1191,47 +784,22 @@ def city_recommendations( limit: int = 3, ) -> list[dict[str, Any]]: """Top same-city (then tag-matched) people for onboarding push.""" - return list_discovery_roster( - viewer_guest_id=guest_id, - limit=limit, - exclude_self=True, - ) + from social_svc import pb_data + + return pb_data.city_recommendations(guest_id, limit=limit) def mark_face_photo(guest_id: str, avatar_url: str) -> None: - """Album/selfie photo passed face presence — liveness still required.""" - with db() as conn: - row = conn.execute( - "SELECT guest_id FROM roster WHERE guest_id=?", (guest_id,) - ).fetchone() - if not row: - conn.execute( - """ - INSERT INTO roster(guest_id, name, title, city, phone, linktree, skills, bio, avatar, - face_ok, liveness_status, updated_at) - VALUES (?, '游民', '', '', '', '', '', '', ?, 1, 'none', ?) - """, - (guest_id, avatar_url[:500], _now()), - ) - return - conn.execute( - """ - UPDATE roster SET avatar=?, face_ok=1, - liveness_status=CASE - WHEN COALESCE(liveness_status,'') IN ('verified','pending') THEN liveness_status - ELSE 'none' - END, - updated_at=? - WHERE guest_id=? - """, - (avatar_url[:500], _now(), guest_id), - ) + """Album/selfie → avatar + face_ok. Does not verify liveness.""" + from social_svc import pb_data + + pb_data.mark_face_photo(guest_id, avatar_url) def save_liveness_audit( guest_id: str, *, - avatar_url: str, + avatar_url: str = "", front_url: str, turn_url: str, video_url: str, @@ -1240,187 +808,56 @@ def save_liveness_audit( yaw_delta: float | None, meta: dict[str, Any] | None = None, ) -> dict[str, Any]: - """Store challenge frames + full camera recording for human review.""" - import json + """Live capture audit only — never overwrites roster.avatar.""" + from social_svc import pb_data - now = _now() - item = { - "id": _uid("live"), - "guestId": guest_id, - "avatarUrl": avatar_url, - "frontUrl": front_url, - "turnUrl": turn_url, - "videoUrl": video_url, - "videoSize": int(video_size or 0), - "similarity": similarity, - "yawDelta": yaw_delta, - "status": "pending", - "createdAt": now, - } - with db() as conn: - conn.execute( - """ - INSERT INTO liveness_audits( - id, guest_id, avatar_url, front_url, turn_url, video_url, video_size, - similarity, yaw_delta, status, meta_json, created_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - """, - ( - item["id"], - guest_id, - avatar_url[:500], - front_url[:500], - turn_url[:500], - video_url[:500], - item["videoSize"], - similarity, - yaw_delta, - "pending", - json.dumps(meta or {}, ensure_ascii=False)[:4000], - now, - ), - ) - # Auto-pass machine challenge → verified; video kept for spot-check - conn.execute( - """ - UPDATE roster SET - avatar=COALESCE(NULLIF(?, ''), avatar), - face_ok=1, - liveness_status='verified', - liveness_at=?, - liveness_video_url=?, - liveness_front_url=?, - liveness_turn_url=?, - updated_at=? - WHERE guest_id=? - """, - ( - avatar_url[:500], - now, - video_url[:500], - front_url[:500], - turn_url[:500], - now, - guest_id, - ), - ) - # Ensure roster row exists if guest only uploaded challenge - if not conn.execute( - "SELECT 1 FROM roster WHERE guest_id=?", (guest_id,) - ).fetchone(): - conn.execute( - """ - INSERT INTO roster( - guest_id, name, avatar, face_ok, liveness_status, liveness_at, - liveness_video_url, liveness_front_url, liveness_turn_url, updated_at - ) VALUES (?, '游民', ?, 1, 'verified', ?, ?, ?, ?, ?) - """, - ( - guest_id, - avatar_url[:500], - now, - video_url[:500], - front_url[:500], - turn_url[:500], - now, - ), - ) - item["status"] = "verified" - return item + return pb_data.save_liveness_audit( + guest_id, + front_url=front_url, + turn_url=turn_url, + video_url=video_url, + video_size=video_size, + similarity=similarity, + yaw_delta=yaw_delta, + meta=meta, + ) def list_liveness_audits(*, status: str = "", limit: int = 50) -> list[dict[str, Any]]: - limit = max(1, min(int(limit or 50), 200)) - with db() as conn: - if status: - rows = conn.execute( - """ - SELECT * FROM liveness_audits WHERE status=? - ORDER BY created_at DESC LIMIT ? - """, - (status, limit), - ).fetchall() - else: - rows = conn.execute( - """ - SELECT * FROM liveness_audits - ORDER BY created_at DESC LIMIT ? - """, - (limit,), - ).fetchall() - out = [] - for r in rows: - out.append( - { - "id": r["id"], - "guestId": r["guest_id"], - "avatarUrl": r["avatar_url"] or "", - "frontUrl": r["front_url"] or "", - "turnUrl": r["turn_url"] or "", - "videoUrl": r["video_url"] or "", - "videoSize": r["video_size"] or 0, - "similarity": r["similarity"], - "yawDelta": r["yaw_delta"], - "status": r["status"], - "createdAt": r["created_at"], - } - ) - return out + from social_svc import pb_data + + return pb_data.list_liveness_audits(status=status, limit=limit) def add_feedback(kind: str, text: str, contact: str, guest_id: str) -> dict[str, Any]: - item = { - "id": _uid("fb"), - "kind": kind if kind in {"反馈", "建议"} else "建议", - "text": text.strip()[:4000], - "contact": (contact or "").strip()[:120], - "guestId": guest_id, - "at": _now(), - } - with db() as conn: - conn.execute( - """ - INSERT INTO feedback(id, kind, text, contact, guest_id, created_at) - VALUES (?, ?, ?, ?, ?, ?) - """, - (item["id"], item["kind"], item["text"], item["contact"], guest_id, item["at"]), - ) - return item + from social_svc import pb_data + + return pb_data.add_feedback(kind, text, contact, guest_id) -def add_gig_app(gig_id: str, name: str, contact: str, note: str, guest_id: str, request_id: str | None = None) -> dict[str, Any]: - item = { - "id": ("app_" + hashlib.sha256(json.dumps([guest_id, gig_id, request_id]).encode()).hexdigest()[:32]) if request_id else _uid("app"), - "gigId": gig_id, - "name": name.strip()[:64], - "contact": contact.strip()[:120], - "note": (note or "").strip()[:2000], - "guestId": guest_id, - "at": _now(), - } - with db() as conn: - conn.execute( - """ - INSERT OR IGNORE INTO gig_apps(id, gig_id, name, contact, note, guest_id, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?) - """, - (item["id"], item["gigId"], item["name"], item["contact"], item["note"], guest_id, item["at"]), - ) - row = conn.execute("SELECT * FROM gig_apps WHERE id = ?", (item["id"],)).fetchone() - if (row["name"], row["contact"], row["note"]) != (item["name"], item["contact"], item["note"]): - raise ValueError("同一请求标识不能用于不同申请") - item["at"] = row["created_at"] - return item +def add_gig_app( + gig_id: str, + name: str, + contact: str, + note: str, + guest_id: str, + request_id: str | None = None, +) -> dict[str, Any]: + from social_svc import pb_data + + return pb_data.add_gig_app(gig_id, name, contact, note, guest_id, request_id) def health() -> dict[str, Any]: init_db() - exists = SOCIAL_DB_PATH.exists() - size = SOCIAL_DB_PATH.stat().st_size if exists else 0 + from social_svc import pb_data + + h = pb_data.health() return { - "ok": True, + "ok": bool(h.get("ok")), "module": "social", - "db": str(SOCIAL_DB_PATH), - "dbBytes": size, + "backend": "pocketbase", + "db": h.get("pb") or h.get("db") or "", + "dbBytes": 0, "isolated": True, } diff --git a/apps/api/services/work_svc/pb_store.py b/apps/api/services/work_svc/pb_store.py new file mode 100644 index 0000000..92ae9e6 --- /dev/null +++ b/apps/api/services/work_svc/pb_store.py @@ -0,0 +1,506 @@ +"""Work boards/pads on PocketBase — board stored as JSON doc.""" +from __future__ import annotations + +import time +import uuid +from typing import Any + +from nomadro_pb import ensure_once, get_pb, pb_quote + +C_PROJ = "work_projects" +C_BOARD = "work_boards" +C_PAD = "work_pads" + + +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[:10]}" + + +def init_db() -> None: + ensure_once() + + +def list_projects() -> list[dict[str, Any]]: + init_db() + rows = get_pb().list_all(C_PROJ, sort="-updated_at") + return [ + { + "id": r.get("id"), + "name": r.get("name"), + "description": r.get("description") or "", + "background_type": r.get("background_type") or "gradient", + "background_gradient": r.get("background_gradient") or "ocean-dive", + "board_id": r.get("board_id"), + "created_at": r.get("created_at"), + "updated_at": r.get("updated_at"), + } + for r in rows + ] + + +def create_project(name: str, description: str = "") -> dict[str, Any]: + init_db() + now = _now() + proj = get_pb().create( + C_PROJ, + { + "name": (name or "Untitled").strip()[:120], + "description": (description or "")[:2000], + "background_type": "gradient", + "background_gradient": "ocean-dive", + "board_id": "", + "created_at": now, + "updated_at": now, + }, + ) + board = create_board(proj["id"], name.strip() or "Board") + get_pb().update(C_PROJ, proj["id"], {"board_id": board["id"], "updated_at": _now()}) + proj["board_id"] = board["id"] + return proj + + +def list_boards(project_id: str | None = None) -> list[dict[str, Any]]: + init_db() + rows = get_pb().list_all(C_BOARD, sort="position") + out = [] + for r in rows: + if project_id and r.get("project_id") != project_id: + continue + out.append(_board_summary(r)) + return out + + +def _board_summary(r: dict[str, Any]) -> dict[str, Any]: + return { + "id": r.get("id"), + "project_id": r.get("project_id"), + "name": r.get("name"), + "position": r.get("position") or 0, + "default_view": r.get("default_view") or "kanban", + "background_gradient": r.get("background_gradient") or "ocean-dive", + "show_card_counter": bool(r.get("show_card_counter", True)), + "created_at": r.get("created_at"), + "updated_at": r.get("updated_at"), + } + + +def _empty_doc() -> dict[str, Any]: + lid = _id("list") + return { + "lists": [ + {"id": lid, "name": "Todo", "type": "active", "position": 0, "color": None} + ], + "cards": [], + "labels": [], + "activities": [], + } + + +def create_board(project_id: str, name: str) -> dict[str, Any]: + init_db() + now = _now() + rec = get_pb().create( + C_BOARD, + { + "project_id": project_id, + "name": (name or "Board").strip()[:120], + "position": 0, + "default_view": "kanban", + "background_gradient": "ocean-dive", + "show_card_counter": True, + "doc": _empty_doc(), + "created_at": now, + "updated_at": now, + }, + ) + return get_board(rec["id"]) # type: ignore[return-value] + + +def get_board(board_id: str) -> dict[str, Any] | None: + init_db() + try: + r = get_pb().request( + "GET", f"/api/collections/{C_BOARD}/records/{board_id}", admin=True + ) + except Exception: + return None + doc = r.get("doc") if isinstance(r.get("doc"), dict) else _empty_doc() + return { + **_board_summary(r), + "lists": doc.get("lists") or [], + "cards": doc.get("cards") or [], + "labels": doc.get("labels") or [], + "activities": (doc.get("activities") or [])[-40:], + "card_members": doc.get("card_members") or [], + "attachments": doc.get("attachments") or [], + "comments": doc.get("comments") or [], + "task_lists": doc.get("task_lists") or [], + "tasks": doc.get("tasks") or [], + } + + +def _save_doc(board_id: str, doc: dict[str, Any]) -> dict[str, Any] | None: + get_pb().update(C_BOARD, board_id, {"doc": doc, "updated_at": _now()}) + return get_board(board_id) + + +def _load_doc(board_id: str) -> tuple[dict[str, Any], dict[str, Any]] | None: + b = get_board(board_id) + if not b: + return None + doc = { + "lists": b.get("lists") or [], + "cards": b.get("cards") or [], + "labels": b.get("labels") or [], + "activities": b.get("activities") or [], + "card_members": b.get("card_members") or [], + "attachments": b.get("attachments") or [], + "comments": b.get("comments") or [], + "task_lists": b.get("task_lists") or [], + "tasks": b.get("tasks") or [], + } + return b, doc + + +def update_board(board_id: str, **patch: Any) -> dict[str, Any] | None: + body = {k: v for k, v in patch.items() if v is not None} + body["updated_at"] = _now() + try: + get_pb().update(C_BOARD, board_id, body) + except Exception: + return None + return get_board(board_id) + + +def add_list(board_id: str, name: str, typ: str = "active") -> dict[str, Any] | None: + loaded = _load_doc(board_id) + if not loaded: + return None + _, doc = loaded + doc["lists"].append( + { + "id": _id("list"), + "name": name, + "type": typ, + "position": len(doc["lists"]), + "color": None, + } + ) + return _save_doc(board_id, doc) + + +def add_card( + board_id: str, list_id: str, name: str, description: str = "" +) -> dict[str, Any] | None: + loaded = _load_doc(board_id) + if not loaded: + return None + _, doc = loaded + doc["cards"].append( + { + "id": _id("card"), + "list_id": list_id, + "board_id": board_id, + "name": name, + "description": description, + "position": len([c for c in doc["cards"] if c.get("list_id") == list_id]), + "cover": None, + "due": None, + "completed": False, + "stopwatch": None, + "label_ids": [], + "created_at": _now(), + } + ) + return _save_doc(board_id, doc) + + +def update_card(board_id: str, card_id: str, **patch: Any) -> dict[str, Any] | None: + loaded = _load_doc(board_id) + if not loaded: + return None + _, doc = loaded + for c in doc["cards"]: + if c.get("id") == card_id: + c.update({k: v for k, v in patch.items() if v is not None}) + break + else: + return None + return _save_doc(board_id, doc) + + +def move_card( + board_id: str, card_id: str, list_id: str, position: int +) -> dict[str, Any] | None: + return update_card(board_id, card_id, list_id=list_id, position=position) + + +def delete_card(board_id: str, card_id: str) -> dict[str, Any] | None: + loaded = _load_doc(board_id) + if not loaded: + return None + _, doc = loaded + doc["cards"] = [c for c in doc["cards"] if c.get("id") != card_id] + return _save_doc(board_id, doc) + + +def archive_card(board_id: str, card_id: str) -> dict[str, Any] | None: + return update_card(board_id, card_id, archived=True) + + +def update_list( + board_id: str, list_id: str, *, name: str | None = None, color: str | None = None +) -> dict[str, Any] | None: + loaded = _load_doc(board_id) + if not loaded: + return None + _, doc = loaded + for lst in doc["lists"]: + if lst.get("id") == list_id: + if name is not None: + lst["name"] = name + if color is not None: + lst["color"] = color + break + else: + return None + return _save_doc(board_id, doc) + + +def delete_list(board_id: str, list_id: str) -> dict[str, Any] | None: + loaded = _load_doc(board_id) + if not loaded: + return None + _, doc = loaded + doc["lists"] = [l for l in doc["lists"] if l.get("id") != list_id] + doc["cards"] = [c for c in doc["cards"] if c.get("list_id") != list_id] + return _save_doc(board_id, doc) + + +def move_list(board_id: str, list_id: str, position: int) -> dict[str, Any] | None: + loaded = _load_doc(board_id) + if not loaded: + return None + _, doc = loaded + for lst in doc["lists"]: + if lst.get("id") == list_id: + lst["position"] = position + break + return _save_doc(board_id, doc) + + +def toggle_card_label(board_id: str, card_id: str, label_id: str) -> dict[str, Any] | None: + loaded = _load_doc(board_id) + if not loaded: + return None + _, doc = loaded + for c in doc["cards"]: + if c.get("id") == card_id: + ids = list(c.get("label_ids") or []) + if label_id in ids: + ids.remove(label_id) + else: + ids.append(label_id) + c["label_ids"] = ids + break + else: + return None + return _save_doc(board_id, doc) + + +def toggle_card_member(board_id: str, card_id: str, name: str) -> dict[str, Any] | None: + loaded = _load_doc(board_id) + if not loaded: + return None + _, doc = loaded + members = [m for m in (doc.get("card_members") or []) if not (m.get("card_id") == card_id and m.get("name") == name)] + existed = len(members) != len(doc.get("card_members") or []) + if not existed: + members.append({"card_id": card_id, "name": name}) + doc["card_members"] = members + return _save_doc(board_id, doc) + + +def add_comment( + board_id: str, card_id: str, author: str, text: str +) -> dict[str, Any] | None: + loaded = _load_doc(board_id) + if not loaded: + return None + _, doc = loaded + now = _now() + doc.setdefault("comments", []).append( + { + "id": _id("cmt"), + "card_id": card_id, + "author": author, + "text": text, + "created_at": now, + "updated_at": now, + } + ) + return _save_doc(board_id, doc) + + +def add_attachment( + board_id: str, card_id: str, name: str, url: str +) -> dict[str, Any] | None: + loaded = _load_doc(board_id) + if not loaded: + return None + _, doc = loaded + doc.setdefault("attachments", []).append( + {"id": _id("att"), "card_id": card_id, "name": name, "url": url} + ) + return _save_doc(board_id, doc) + + +def delete_attachment(board_id: str, attachment_id: str) -> dict[str, Any] | None: + loaded = _load_doc(board_id) + if not loaded: + return None + _, doc = loaded + doc["attachments"] = [ + a for a in (doc.get("attachments") or []) if a.get("id") != attachment_id + ] + return _save_doc(board_id, doc) + + +def ensure_task_list(card_id: str) -> str: + return _id("tl") + + +def add_task(board_id: str, card_id: str, name: str) -> dict[str, Any] | None: + loaded = _load_doc(board_id) + if not loaded: + return None + _, doc = loaded + tls = doc.setdefault("task_lists", []) + tl = next((t for t in tls if t.get("card_id") == card_id), None) + if not tl: + tl = {"id": _id("tl"), "card_id": card_id} + tls.append(tl) + doc.setdefault("tasks", []).append( + { + "id": _id("task"), + "task_list_id": tl["id"], + "card_id": card_id, + "name": name, + "completed": False, + } + ) + return _save_doc(board_id, doc) + + +def toggle_task(board_id: str, task_id: str) -> dict[str, Any] | None: + loaded = _load_doc(board_id) + if not loaded: + return None + _, doc = loaded + for t in doc.get("tasks") or []: + if t.get("id") == task_id: + t["completed"] = not bool(t.get("completed")) + break + else: + return None + return _save_doc(board_id, doc) + + +def toggle_stopwatch(board_id: str, card_id: str) -> dict[str, Any] | None: + loaded = _load_doc(board_id) + if not loaded: + return None + _, doc = loaded + for c in doc["cards"]: + if c.get("id") == card_id: + sw = c.get("stopwatch") or {"total": 0, "startedAt": None} + if sw.get("startedAt"): + sw["startedAt"] = None + else: + sw["startedAt"] = _now() + c["stopwatch"] = sw + break + else: + return None + return _save_doc(board_id, doc) + + +def list_pads() -> list[dict[str, Any]]: + init_db() + rows = get_pb().list_all(C_PAD, sort="-updated_at") + return [ + { + "id": r.get("id"), + "title": r.get("title"), + "authors": r.get("authors") or [], + "created_at": r.get("created_at"), + "updated_at": r.get("updated_at"), + } + for r in rows + ] + + +def get_pad(pad_id: str) -> dict[str, Any] | None: + init_db() + try: + r = get_pb().request( + "GET", f"/api/collections/{C_PAD}/records/{pad_id}", admin=True + ) + except Exception: + return None + return { + "id": r.get("id"), + "title": r.get("title"), + "text": r.get("text") or "", + "authors": r.get("authors") or [], + "revisions": r.get("revisions") or [], + "created_at": r.get("created_at"), + "updated_at": r.get("updated_at"), + } + + +def create_pad(title: str, author: str = "guest") -> dict[str, Any]: + init_db() + now = _now() + r = get_pb().create( + C_PAD, + { + "title": (title or "Untitled").strip()[:200], + "text": "", + "authors": [author], + "revisions": [{"id": _id("rev"), "author": author, "text": "", "at": now}], + "created_at": now, + "updated_at": now, + }, + ) + return get_pad(r["id"]) # type: ignore[return-value] + + +def update_pad( + pad_id: str, text: str, author: str = "guest", title: str | None = None +) -> dict[str, Any] | None: + p = get_pad(pad_id) + if not p: + return None + authors = list(p.get("authors") or []) + if author not in authors: + authors.append(author) + now = _now() + revs = list(p.get("revisions") or []) + revs.insert(0, {"id": _id("rev"), "author": author, "text": text, "at": now}) + get_pb().update( + C_PAD, + pad_id, + { + "text": text, + "title": title if title is not None else p.get("title"), + "authors": authors, + "revisions": revs[:40], + "updated_at": now, + }, + ) + return get_pad(pad_id) diff --git a/apps/api/services/work_svc/store.py b/apps/api/services/work_svc/store.py index d3dcb67..e848fab 100644 --- a/apps/api/services/work_svc/store.py +++ b/apps/api/services/work_svc/store.py @@ -1,1091 +1,34 @@ -""" -SQLite store — domain shaped after Planka (Project/Board/List/Card) + Etherpad pads. -Secondary-dev reimplementation for Nomadro (not a dump of upstream runtime). -""" +"""Work store — PocketBase (online-first).""" 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 - -# reuse ebook helper if importable; else local -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 - - -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 _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 init_db() -> None: - with _conn() as c: - c.executescript( - """ - CREATE TABLE IF NOT EXISTS projects ( - id TEXT PRIMARY KEY, - name TEXT NOT NULL, - description TEXT NOT NULL DEFAULT '', - background_type TEXT DEFAULT 'gradient', - background_gradient TEXT DEFAULT 'ocean-dive', - created_at TEXT NOT NULL, - updated_at TEXT NOT NULL - ); - CREATE TABLE IF NOT EXISTS boards ( - id TEXT PRIMARY KEY, - project_id TEXT NOT NULL, - name TEXT NOT NULL, - position REAL NOT NULL DEFAULT 0, - default_view TEXT NOT NULL DEFAULT 'kanban', - background_gradient TEXT DEFAULT 'ocean-dive', - show_card_counter INTEGER NOT NULL DEFAULT 1, - created_at TEXT NOT NULL, - updated_at TEXT NOT NULL, - FOREIGN KEY(project_id) REFERENCES projects(id) - ); - CREATE TABLE IF NOT EXISTS lists ( - id TEXT PRIMARY KEY, - board_id TEXT NOT NULL, - name TEXT NOT NULL, - type TEXT NOT NULL DEFAULT 'active', - position REAL NOT NULL DEFAULT 0, - color TEXT, - FOREIGN KEY(board_id) REFERENCES boards(id) - ); - CREATE TABLE IF NOT EXISTS cards ( - id TEXT PRIMARY KEY, - list_id TEXT NOT NULL, - board_id TEXT NOT NULL, - name TEXT NOT NULL, - description TEXT NOT NULL DEFAULT '', - type TEXT NOT NULL DEFAULT 'project', - position REAL NOT NULL DEFAULT 0, - due_date TEXT, - is_due_completed INTEGER NOT NULL DEFAULT 0, - stopwatch_json TEXT, - cover_color TEXT, - is_closed INTEGER NOT NULL DEFAULT 0, - created_at TEXT NOT NULL, - updated_at TEXT NOT NULL, - FOREIGN KEY(list_id) REFERENCES lists(id), - FOREIGN KEY(board_id) REFERENCES boards(id) - ); - CREATE TABLE IF NOT EXISTS attachments ( - id TEXT PRIMARY KEY, - card_id TEXT NOT NULL, - name TEXT NOT NULL, - url TEXT NOT NULL, - created_at TEXT NOT NULL, - FOREIGN KEY(card_id) REFERENCES cards(id) - ); - CREATE TABLE IF NOT EXISTS pads ( - id TEXT PRIMARY KEY, - title TEXT NOT NULL, - text TEXT NOT NULL DEFAULT '', - authors_json TEXT NOT NULL DEFAULT '[]', - created_at TEXT NOT NULL, - updated_at TEXT NOT NULL - ); - CREATE TABLE IF NOT EXISTS pad_revisions ( - id TEXT PRIMARY KEY, - pad_id TEXT NOT NULL, - author TEXT NOT NULL, - text TEXT NOT NULL, - at TEXT NOT NULL, - FOREIGN KEY(pad_id) REFERENCES pads(id) - ); - CREATE TABLE IF NOT EXISTS labels ( - id TEXT PRIMARY KEY, - board_id TEXT NOT NULL, - name TEXT, - color TEXT NOT NULL, - position REAL NOT NULL DEFAULT 0, - created_at TEXT NOT NULL, - updated_at TEXT NOT NULL, - FOREIGN KEY(board_id) REFERENCES boards(id) - ); - CREATE TABLE IF NOT EXISTS card_labels ( - card_id TEXT NOT NULL, - label_id TEXT NOT NULL, - PRIMARY KEY(card_id, label_id), - FOREIGN KEY(card_id) REFERENCES cards(id), - FOREIGN KEY(label_id) REFERENCES labels(id) - ); - CREATE TABLE IF NOT EXISTS task_lists ( - id TEXT PRIMARY KEY, - card_id TEXT NOT NULL, - name TEXT NOT NULL DEFAULT 'Checklist', - position REAL NOT NULL DEFAULT 0, - FOREIGN KEY(card_id) REFERENCES cards(id) - ); - CREATE TABLE IF NOT EXISTS tasks ( - id TEXT PRIMARY KEY, - task_list_id TEXT NOT NULL, - name TEXT NOT NULL, - is_completed INTEGER NOT NULL DEFAULT 0, - position REAL NOT NULL DEFAULT 0, - created_at TEXT NOT NULL, - updated_at TEXT NOT NULL, - FOREIGN KEY(task_list_id) REFERENCES task_lists(id) - ); - CREATE TABLE IF NOT EXISTS comments ( - id TEXT PRIMARY KEY, - card_id TEXT NOT NULL, - author TEXT NOT NULL, - text TEXT NOT NULL, - created_at TEXT NOT NULL, - updated_at TEXT NOT NULL, - FOREIGN KEY(card_id) REFERENCES cards(id) - ); - CREATE TABLE IF NOT EXISTS card_members ( - card_id TEXT NOT NULL, - name TEXT NOT NULL, - PRIMARY KEY(card_id, name), - FOREIGN KEY(card_id) REFERENCES cards(id) - ); - CREATE TABLE IF NOT EXISTS activities ( - id TEXT PRIMARY KEY, - board_id TEXT NOT NULL, - card_id TEXT, - actor TEXT NOT NULL DEFAULT 'system', - type TEXT NOT NULL, - data_json TEXT NOT NULL DEFAULT '{}', - created_at TEXT NOT NULL, - FOREIGN KEY(board_id) REFERENCES boards(id) - ); - """ - ) - # Planka-parity columns for DBs created before this revision - _ensure_column(c, "projects", "background_type", "TEXT DEFAULT 'gradient'") - _ensure_column(c, "projects", "background_gradient", "TEXT DEFAULT 'ocean-dive'") - _ensure_column(c, "boards", "background_gradient", "TEXT DEFAULT 'ocean-dive'") - _ensure_column(c, "boards", "show_card_counter", "INTEGER NOT NULL DEFAULT 1") - _ensure_column(c, "cards", "is_due_completed", "INTEGER NOT NULL DEFAULT 0") - _ensure_column(c, "cards", "stopwatch_json", "TEXT") - _ensure_column(c, "cards", "cover_color", "TEXT") - n = c.execute("SELECT COUNT(*) AS n FROM projects").fetchone()["n"] - if n == 0: - _seed(c) - - -def _seed(c: sqlite3.Connection) -> None: - t = _now() - pid = _id("proj") - bid = _id("board") - c.execute( - "INSERT INTO projects(id,name,description,background_type,background_gradient,created_at,updated_at) VALUES(?,?,?,?,?,?,?)", - (pid, "Nomadro Remote", "二次开发种子项目(Planka 模型)", "gradient", "ocean-dive", t, t), - ) - c.execute( - "INSERT INTO boards(id,project_id,name,position,default_view,background_gradient,show_card_counter,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?)", - (bid, pid, "Sprint board", 0, "kanban", "ocean-dive", 1, t, t), - ) - lists = [ - (_id("list"), "Backlog", "active", 0), - (_id("list"), "Doing", "active", 1), - (_id("list"), "Done", "closed", 2), - (_id("list"), "Archive", "archive", 3), - ] - for lid, name, typ, pos in lists: - c.execute( - "INSERT INTO lists(id,board_id,name,type,position) VALUES(?,?,?,?,?)", - (lid, bid, name, typ, pos), - ) - c.execute( - "INSERT INTO cards(id,list_id,board_id,name,description,type,position,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?)", - ( - _id("card"), - lists[1][0], - bid, - "Native Next + FastAPI work module", - "From Planka/Etherpad domain analysis", - "project", - 0, - t, - t, - ), - ) - pad_id = _id("pad") - text = "# Nomadro Pad\n\nEtherpad 模型二次开发 · 修订历史进 FastAPI。\n" - c.execute( - "INSERT INTO pads(id,title,text,authors_json,created_at,updated_at) VALUES(?,?,?,?,?,?)", - (pad_id, "Welcome pad", text, json.dumps(["system"]), t, t), - ) - c.execute( - "INSERT INTO pad_revisions(id,pad_id,author,text,at) VALUES(?,?,?,?,?)", - (_id("rev"), pad_id, "system", text, t), - ) - - -def list_projects() -> list[dict[str, Any]]: - with _conn() as c: - rows = c.execute( - "SELECT id,name,description,created_at,updated_at FROM projects ORDER BY updated_at DESC" - ).fetchall() - return [dict(r) for r in rows] - - -def create_project(name: str, description: str = "") -> dict[str, Any]: - t = _now() - pid = _id("proj") - with _conn() as c: - c.execute( - "INSERT INTO projects(id,name,description,background_type,background_gradient,created_at,updated_at) VALUES(?,?,?,?,?,?,?)", - (pid, name.strip() or "Untitled", description.strip(), "gradient", "ocean-dive", t, t), - ) - bid = _id("board") - c.execute( - "INSERT INTO boards(id,project_id,name,position,default_view,background_gradient,show_card_counter,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?)", - (bid, pid, "Main board", 0, "kanban", "ocean-dive", 1, t, t), - ) - for i, (nm, typ) in enumerate( - [ - ("Backlog", "active"), - ("Doing", "active"), - ("Done", "closed"), - ("Archive", "archive"), - ] - ): - c.execute( - "INSERT INTO lists(id,board_id,name,type,position) VALUES(?,?,?,?,?)", - (_id("list"), bid, nm, typ, i), - ) - return {"id": pid, "name": name, "description": description, "created_at": t, "updated_at": t, "board_id": bid} - - -def list_boards(project_id: str | None = None) -> list[dict[str, Any]]: - with _conn() as c: - if project_id: - rows = c.execute( - "SELECT id,project_id,name,position,default_view,background_gradient,show_card_counter,created_at,updated_at FROM boards WHERE project_id=? ORDER BY position", - (project_id,), - ).fetchall() - else: - rows = c.execute( - "SELECT id,project_id,name,position,default_view,background_gradient,show_card_counter,created_at,updated_at FROM boards ORDER BY updated_at DESC" - ).fetchall() - return [dict(r) for r in rows] - - -def _ensure_board_labels(c: sqlite3.Connection, board_id: str) -> None: - n = c.execute( - "SELECT COUNT(*) AS n FROM labels WHERE board_id=?", (board_id,) - ).fetchone()["n"] - if n: - return - t = _now() - defaults = [ - ("Bug", "berry-red"), - ("Feature", "lagoon-blue"), - ("Urgent", "pumpkin-orange"), - ("Design", "pink-tulip"), - ] - for i, (name, color) in enumerate(defaults): - c.execute( - "INSERT INTO labels(id,board_id,name,color,position,created_at,updated_at) VALUES(?,?,?,?,?,?,?)", - (_id("label"), board_id, name, color, i, t, t), - ) - - -def _parse_card_row(r: sqlite3.Row) -> dict[str, Any]: - d = dict(r) - raw = d.pop("stopwatch_json", None) - try: - d["stopwatch"] = json.loads(raw) if raw else None - except Exception: - d["stopwatch"] = None - return d - - -def get_board(board_id: str) -> dict[str, Any] | None: - with _conn() as c: - b = c.execute( - "SELECT id,project_id,name,position,default_view,background_gradient,show_card_counter,created_at,updated_at FROM boards WHERE id=?", - (board_id,), - ).fetchone() - if not b: - return None - _ensure_board_labels(c, board_id) - lists = [ - dict(r) - for r in c.execute( - "SELECT id,board_id,name,type,position,color FROM lists WHERE board_id=? ORDER BY position", - (board_id,), - ).fetchall() - ] - # Ensure archive list exists (Planka ListTypes.ARCHIVE) - if not any(x["type"] == "archive" for x in lists): - pos = max((x["position"] for x in lists), default=-1) + 1 - aid = _id("list") - c.execute( - "INSERT INTO lists(id,board_id,name,type,position) VALUES(?,?,?,?,?)", - (aid, board_id, "Archive", "archive", pos), - ) - lists.append( - { - "id": aid, - "board_id": board_id, - "name": "Archive", - "type": "archive", - "position": pos, - "color": None, - } - ) - cards = [ - _parse_card_row(r) - for r in c.execute( - "SELECT id,list_id,board_id,name,description,type,position,due_date,is_due_completed,stopwatch_json,cover_color,is_closed,created_at,updated_at FROM cards WHERE board_id=? ORDER BY position", - (board_id,), - ).fetchall() - ] - labels = [ - dict(r) - for r in c.execute( - "SELECT id,board_id,name,color,position FROM labels WHERE board_id=? ORDER BY position", - (board_id,), - ).fetchall() - ] - card_ids = [x["id"] for x in cards] - card_labels: list[dict[str, Any]] = [] - task_lists: list[dict[str, Any]] = [] - tasks: list[dict[str, Any]] = [] - comments: list[dict[str, Any]] = [] - card_members: list[dict[str, Any]] = [] - if card_ids: - qmarks = ",".join("?" * len(card_ids)) - card_labels = [ - dict(r) - for r in c.execute( - f"SELECT card_id,label_id FROM card_labels WHERE card_id IN ({qmarks})", - card_ids, - ).fetchall() - ] - task_lists = [ - dict(r) - for r in c.execute( - f"SELECT id,card_id,name,position FROM task_lists WHERE card_id IN ({qmarks}) ORDER BY position", - card_ids, - ).fetchall() - ] - tl_ids = [t["id"] for t in task_lists] - if tl_ids: - tqm = ",".join("?" * len(tl_ids)) - tasks = [ - dict(r) - for r in c.execute( - f"SELECT id,task_list_id,name,is_completed,position,created_at,updated_at FROM tasks WHERE task_list_id IN ({tqm}) ORDER BY position", - tl_ids, - ).fetchall() - ] - comments = [ - dict(r) - for r in c.execute( - f"SELECT id,card_id,author,text,created_at,updated_at FROM comments WHERE card_id IN ({qmarks}) ORDER BY created_at", - card_ids, - ).fetchall() - ] - card_members = [ - dict(r) - for r in c.execute( - f"SELECT card_id,name FROM card_members WHERE card_id IN ({qmarks})", - card_ids, - ).fetchall() - ] - attachments: list[dict[str, Any]] = [] - if card_ids: - attachments = [ - dict(r) - for r in c.execute( - f"SELECT id,card_id,name,url,created_at FROM attachments WHERE card_id IN ({qmarks}) ORDER BY created_at", - card_ids, - ).fetchall() - ] - activities = [ - { - **dict(r), - "data": json.loads(r["data_json"] or "{}"), - } - for r in c.execute( - "SELECT id,board_id,card_id,actor,type,data_json,created_at FROM activities WHERE board_id=? ORDER BY created_at DESC LIMIT 40", - (board_id,), - ).fetchall() - ] - for a in activities: - a.pop("data_json", None) - out = dict(b) - out["lists"] = lists - out["cards"] = cards - out["labels"] = labels - out["card_labels"] = card_labels - out["task_lists"] = task_lists - out["tasks"] = tasks - out["comments"] = comments - out["card_members"] = card_members - out["attachments"] = attachments - out["activities"] = activities - return out - - -def _activity( - c: sqlite3.Connection, - board_id: str, - typ: str, - *, - card_id: str | None = None, - actor: str = "system", - data: dict[str, Any] | None = None, -) -> None: - c.execute( - "INSERT INTO activities(id,board_id,card_id,actor,type,data_json,created_at) VALUES(?,?,?,?,?,?,?)", - ( - _id("act"), - board_id, - card_id, - actor, - typ, - json.dumps(data or {}), - _now(), - ), - ) - - -def create_board(project_id: str, name: str) -> dict[str, Any]: - t = _now() - bid = _id("board") - with _conn() as c: - pos = c.execute( - "SELECT COALESCE(MAX(position),-1)+1 AS p FROM boards WHERE project_id=?", - (project_id,), - ).fetchone()["p"] - c.execute( - "INSERT INTO boards(id,project_id,name,position,default_view,background_gradient,show_card_counter,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?)", - (bid, project_id, name.strip() or "Board", pos, "kanban", "ocean-dive", 1, t, t), - ) - for i, (nm, typ) in enumerate( - [ - ("Backlog", "active"), - ("Doing", "active"), - ("Done", "closed"), - ("Archive", "archive"), - ] - ): - c.execute( - "INSERT INTO lists(id,board_id,name,type,position) VALUES(?,?,?,?,?)", - (_id("list"), bid, nm, typ, i), - ) - c.execute("UPDATE projects SET updated_at=? WHERE id=?", (t, project_id)) - return get_board(bid) # type: ignore - - -def add_list(board_id: str, name: str, typ: str = "active") -> dict[str, Any] | None: - with _conn() as c: - if not c.execute("SELECT 1 FROM boards WHERE id=?", (board_id,)).fetchone(): - return None - pos = c.execute( - "SELECT COALESCE(MAX(position),-1)+1 AS p FROM lists WHERE board_id=?", - (board_id,), - ).fetchone()["p"] - lid = _id("list") - c.execute( - "INSERT INTO lists(id,board_id,name,type,position) VALUES(?,?,?,?,?)", - (lid, board_id, name.strip() or "List", typ, pos), - ) - c.execute("UPDATE boards SET updated_at=? WHERE id=?", (_now(), board_id)) - return get_board(board_id) - - -def add_card(board_id: str, list_id: str, name: str, description: str = "") -> dict[str, Any] | None: - t = _now() - with _conn() as c: - if not c.execute( - "SELECT 1 FROM lists WHERE id=? AND board_id=?", (list_id, board_id) - ).fetchone(): - return None - pos = c.execute( - "SELECT COALESCE(MAX(position),-1)+1 AS p FROM cards WHERE list_id=?", - (list_id,), - ).fetchone()["p"] - cid = _id("card") - cname = name.strip() or "Card" - c.execute( - "INSERT INTO cards(id,list_id,board_id,name,description,type,position,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?)", - (cid, list_id, board_id, cname, description.strip(), "project", pos, t, t), - ) - _activity( - c, - board_id, - "createCard", - card_id=cid, - data={"card": {"name": cname}, "listId": list_id}, - ) - c.execute("UPDATE boards SET updated_at=? WHERE id=?", (t, board_id)) - return get_board(board_id) - - -def update_card( - board_id: str, - card_id: str, - *, - name: str | None = None, - description: str | None = None, - due_date: str | None = None, - clear_due: bool = False, - is_due_completed: bool | None = None, - cover_color: str | None = None, - clear_cover: bool = False, -) -> dict[str, Any] | None: - t = _now() - with _conn() as c: - card = c.execute( - "SELECT * FROM cards WHERE id=? AND board_id=?", (card_id, board_id) - ).fetchone() - if not card: - return None - new_name = name.strip() if name is not None else card["name"] - new_desc = description if description is not None else card["description"] - if name is not None and not new_name: - new_name = card["name"] - new_due = card["due_date"] - if clear_due: - new_due = None - elif due_date is not None: - new_due = due_date or None - due_done = ( - int(bool(is_due_completed)) - if is_due_completed is not None - else card["is_due_completed"] - ) - cover = card["cover_color"] if "cover_color" in card.keys() else None - if clear_cover: - cover = None - elif cover_color is not None: - cover = cover_color or None - c.execute( - "UPDATE cards SET name=?, description=?, due_date=?, is_due_completed=?, cover_color=?, updated_at=? WHERE id=?", - (new_name, new_desc or "", new_due, due_done, cover, t, card_id), - ) - c.execute("UPDATE boards SET updated_at=? WHERE id=?", (t, board_id)) - return get_board(board_id) - - -def update_board( - board_id: str, - *, - name: str | None = None, - background_gradient: str | None = None, - show_card_counter: bool | None = None, -) -> dict[str, Any] | None: - t = _now() - with _conn() as c: - b = c.execute("SELECT * FROM boards WHERE id=?", (board_id,)).fetchone() - if not b: - return None - new_name = name.strip() if name is not None else b["name"] - if name is not None and not new_name: - new_name = b["name"] - grad = ( - background_gradient - if background_gradient is not None - else b["background_gradient"] - ) - counter = ( - int(bool(show_card_counter)) - if show_card_counter is not None - else b["show_card_counter"] - ) - c.execute( - "UPDATE boards SET name=?, background_gradient=?, show_card_counter=?, updated_at=? WHERE id=?", - (new_name, grad, counter, t, board_id), - ) - return get_board(board_id) - - -def toggle_stopwatch(board_id: str, card_id: str) -> dict[str, Any] | None: - """Planka startStopwatch / stopStopwatch parity.""" - t = _now() - with _conn() as c: - card = c.execute( - "SELECT * FROM cards WHERE id=? AND board_id=?", (card_id, board_id) - ).fetchone() - if not card: - return None - try: - sw = json.loads(card["stopwatch_json"] or "null") or { - "startedAt": None, - "total": 0, - } - except Exception: - sw = {"startedAt": None, "total": 0} - if sw.get("startedAt"): - started = time.strptime(sw["startedAt"], "%Y-%m-%dT%H:%M:%SZ") - elapsed = int(time.mktime(time.gmtime()) - time.mktime(started)) - # started was UTC via strptime without tz — use fromisoformat style - try: - from datetime import datetime, timezone - - started_dt = datetime.strptime( - sw["startedAt"], "%Y-%m-%dT%H:%M:%SZ" - ).replace(tzinfo=timezone.utc) - elapsed = int((datetime.now(timezone.utc) - started_dt).total_seconds()) - except Exception: - elapsed = max(0, elapsed) - sw = {"startedAt": None, "total": int(sw.get("total") or 0) + max(0, elapsed)} - else: - sw = {"startedAt": t, "total": int(sw.get("total") or 0)} - c.execute( - "UPDATE cards SET stopwatch_json=?, updated_at=? WHERE id=?", - (json.dumps(sw), t, card_id), - ) - c.execute("UPDATE boards SET updated_at=? WHERE id=?", (t, board_id)) - return get_board(board_id) - - -def add_attachment( - board_id: str, card_id: str, name: str, url: str -) -> dict[str, Any] | None: - t = _now() - with _conn() as c: - if not c.execute( - "SELECT 1 FROM cards WHERE id=? AND board_id=?", (card_id, board_id) - ).fetchone(): - return None - c.execute( - "INSERT INTO attachments(id,card_id,name,url,created_at) VALUES(?,?,?,?,?)", - ( - _id("att"), - card_id, - (name or "Link").strip() or "Link", - url.strip(), - t, - ), - ) - c.execute("UPDATE boards SET updated_at=? WHERE id=?", (t, board_id)) - return get_board(board_id) - - -def delete_attachment(board_id: str, attachment_id: str) -> dict[str, Any] | None: - with _conn() as c: - row = c.execute( - "SELECT a.id, a.card_id FROM attachments a JOIN cards c ON c.id=a.card_id WHERE a.id=? AND c.board_id=?", - (attachment_id, board_id), - ).fetchone() - if not row: - return None - c.execute("DELETE FROM attachments WHERE id=?", (attachment_id,)) - c.execute("UPDATE boards SET updated_at=? WHERE id=?", (_now(), board_id)) - return get_board(board_id) - - -def archive_card(board_id: str, card_id: str) -> dict[str, Any] | None: - """Move card into Archive list (Planka moveCurrentCardToArchive).""" - with _conn() as c: - card = c.execute( - "SELECT * FROM cards WHERE id=? AND board_id=?", (card_id, board_id) - ).fetchone() - if not card: - return None - arch = c.execute( - "SELECT id FROM lists WHERE board_id=? AND type='archive' ORDER BY position LIMIT 1", - (board_id,), - ).fetchone() - if not arch: - return None - list_id = arch["id"] - return move_card(board_id, card_id, list_id, 0) - - -def move_list(board_id: str, list_id: str, position: int) -> dict[str, Any] | None: - with _conn() as c: - if not c.execute( - "SELECT 1 FROM lists WHERE id=? AND board_id=?", (list_id, board_id) - ).fetchone(): - return None - others = c.execute( - "SELECT id FROM lists WHERE board_id=? AND id!=? ORDER BY position", - (board_id, list_id), - ).fetchall() - ids = [r["id"] for r in others] - pos = max(0, min(int(position), len(ids))) - ids.insert(pos, list_id) - for i, lid in enumerate(ids): - c.execute("UPDATE lists SET position=? WHERE id=?", (i, lid)) - c.execute("UPDATE boards SET updated_at=? WHERE id=?", (_now(), board_id)) - return get_board(board_id) - - -def toggle_card_label(board_id: str, card_id: str, label_id: str) -> dict[str, Any] | None: - with _conn() as c: - if not c.execute( - "SELECT 1 FROM cards WHERE id=? AND board_id=?", (card_id, board_id) - ).fetchone(): - return None - if not c.execute( - "SELECT 1 FROM labels WHERE id=? AND board_id=?", (label_id, board_id) - ).fetchone(): - return None - hit = c.execute( - "SELECT 1 FROM card_labels WHERE card_id=? AND label_id=?", - (card_id, label_id), - ).fetchone() - if hit: - c.execute( - "DELETE FROM card_labels WHERE card_id=? AND label_id=?", - (card_id, label_id), - ) - else: - c.execute( - "INSERT INTO card_labels(card_id,label_id) VALUES(?,?)", - (card_id, label_id), - ) - c.execute("UPDATE boards SET updated_at=? WHERE id=?", (_now(), board_id)) - return get_board(board_id) - - -def ensure_task_list(card_id: str) -> str: - with _conn() as c: - row = c.execute( - "SELECT id FROM task_lists WHERE card_id=? ORDER BY position LIMIT 1", - (card_id,), - ).fetchone() - if row: - return row["id"] - tid = _id("tlist") - c.execute( - "INSERT INTO task_lists(id,card_id,name,position) VALUES(?,?,?,?)", - (tid, card_id, "Checklist", 0), - ) - return tid - - -def add_task(board_id: str, card_id: str, name: str) -> dict[str, Any] | None: - t = _now() - with _conn() as c: - if not c.execute( - "SELECT 1 FROM cards WHERE id=? AND board_id=?", (card_id, board_id) - ).fetchone(): - return None - tl = ensure_task_list(card_id) - with _conn() as c: - pos = c.execute( - "SELECT COALESCE(MAX(position),-1)+1 AS p FROM tasks WHERE task_list_id=?", - (tl,), - ).fetchone()["p"] - c.execute( - "INSERT INTO tasks(id,task_list_id,name,is_completed,position,created_at,updated_at) VALUES(?,?,?,?,?,?,?)", - (_id("task"), tl, name.strip() or "Task", 0, pos, t, t), - ) - c.execute("UPDATE boards SET updated_at=? WHERE id=?", (t, board_id)) - return get_board(board_id) - - -def toggle_task(board_id: str, task_id: str) -> dict[str, Any] | None: - t = _now() - with _conn() as c: - task = c.execute("SELECT * FROM tasks WHERE id=?", (task_id,)).fetchone() - if not task: - return None - done = 0 if task["is_completed"] else 1 - c.execute( - "UPDATE tasks SET is_completed=?, updated_at=? WHERE id=?", - (done, t, task_id), - ) - tl = c.execute( - "SELECT card_id FROM task_lists WHERE id=?", (task["task_list_id"],) - ).fetchone() - _activity( - c, - board_id, - "completeTask" if done else "uncompleteTask", - card_id=tl["card_id"] if tl else None, - data={"task": {"id": task_id, "name": task["name"]}}, - ) - c.execute("UPDATE boards SET updated_at=? WHERE id=?", (t, board_id)) - return get_board(board_id) - - -def add_comment(board_id: str, card_id: str, author: str, text: str) -> dict[str, Any] | None: - t = _now() - with _conn() as c: - if not c.execute( - "SELECT 1 FROM cards WHERE id=? AND board_id=?", (card_id, board_id) - ).fetchone(): - return None - who = (author or "guest").strip() or "guest" - c.execute( - "INSERT INTO comments(id,card_id,author,text,created_at,updated_at) VALUES(?,?,?,?,?,?)", - (_id("cmt"), card_id, who, text.strip(), t, t), - ) - _activity( - c, - board_id, - "comment", - card_id=card_id, - actor=who, - data={"text": text.strip()[:120]}, - ) - c.execute("UPDATE boards SET updated_at=? WHERE id=?", (t, board_id)) - return get_board(board_id) - - -def update_list( - board_id: str, - list_id: str, - *, - name: str | None = None, - color: str | None = None, -) -> dict[str, Any] | None: - with _conn() as c: - row = c.execute( - "SELECT * FROM lists WHERE id=? AND board_id=?", (list_id, board_id) - ).fetchone() - if not row: - return None - new_name = name.strip() if name is not None else row["name"] - if name is not None and not new_name: - new_name = row["name"] - new_color = color if color is not None else row["color"] - c.execute( - "UPDATE lists SET name=?, color=? WHERE id=?", - (new_name, new_color, list_id), - ) - c.execute("UPDATE boards SET updated_at=? WHERE id=?", (_now(), board_id)) - return get_board(board_id) - - -def delete_list(board_id: str, list_id: str) -> dict[str, Any] | None: - with _conn() as c: - if not c.execute( - "SELECT 1 FROM lists WHERE id=? AND board_id=?", (list_id, board_id) - ).fetchone(): - return None - cards = c.execute( - "SELECT id FROM cards WHERE list_id=?", (list_id,) - ).fetchall() - for card in cards: - cid = card["id"] - c.execute("DELETE FROM card_labels WHERE card_id=?", (cid,)) - c.execute("DELETE FROM card_members WHERE card_id=?", (cid,)) - c.execute("DELETE FROM comments WHERE card_id=?", (cid,)) - tls = c.execute( - "SELECT id FROM task_lists WHERE card_id=?", (cid,) - ).fetchall() - for tl in tls: - c.execute("DELETE FROM tasks WHERE task_list_id=?", (tl["id"],)) - c.execute("DELETE FROM task_lists WHERE card_id=?", (cid,)) - c.execute("DELETE FROM cards WHERE list_id=?", (list_id,)) - c.execute("DELETE FROM lists WHERE id=?", (list_id,)) - _activity(c, board_id, "delete_list", data={"list_id": list_id}) - c.execute("UPDATE boards SET updated_at=? WHERE id=?", (_now(), board_id)) - return get_board(board_id) - - -def delete_card(board_id: str, card_id: str) -> dict[str, Any] | None: - with _conn() as c: - if not c.execute( - "SELECT 1 FROM cards WHERE id=? AND board_id=?", (card_id, board_id) - ).fetchone(): - return None - c.execute("DELETE FROM card_labels WHERE card_id=?", (card_id,)) - c.execute("DELETE FROM card_members WHERE card_id=?", (card_id,)) - c.execute("DELETE FROM comments WHERE card_id=?", (card_id,)) - tls = c.execute( - "SELECT id FROM task_lists WHERE card_id=?", (card_id,) - ).fetchall() - for tl in tls: - c.execute("DELETE FROM tasks WHERE task_list_id=?", (tl["id"],)) - c.execute("DELETE FROM task_lists WHERE card_id=?", (card_id,)) - c.execute("DELETE FROM cards WHERE id=?", (card_id,)) - _activity(c, board_id, "delete_card", card_id=card_id) - c.execute("UPDATE boards SET updated_at=? WHERE id=?", (_now(), board_id)) - return get_board(board_id) - - -def toggle_card_member(board_id: str, card_id: str, name: str) -> dict[str, Any] | None: - who = (name or "").strip() - if not who: - return None - with _conn() as c: - if not c.execute( - "SELECT 1 FROM cards WHERE id=? AND board_id=?", (card_id, board_id) - ).fetchone(): - return None - hit = c.execute( - "SELECT 1 FROM card_members WHERE card_id=? AND name=?", - (card_id, who), - ).fetchone() - if hit: - c.execute( - "DELETE FROM card_members WHERE card_id=? AND name=?", - (card_id, who), - ) - act = "removeMemberFromCard" - else: - c.execute( - "INSERT INTO card_members(card_id,name) VALUES(?,?)", - (card_id, who), - ) - act = "addMemberToCard" - _activity( - c, - board_id, - act, - card_id=card_id, - actor=who, - data={"name": who}, - ) - c.execute("UPDATE boards SET updated_at=? WHERE id=?", (_now(), board_id)) - return get_board(board_id) - - -def move_card(board_id: str, card_id: str, list_id: str, position: int) -> dict[str, Any] | None: - t = _now() - with _conn() as c: - card = c.execute( - "SELECT * FROM cards WHERE id=? AND board_id=?", (card_id, board_id) - ).fetchone() - if not card: - return None - if not c.execute( - "SELECT 1 FROM lists WHERE id=? AND board_id=?", (list_id, board_id) - ).fetchone(): - return None - from_list = card["list_id"] - others = c.execute( - "SELECT id FROM cards WHERE list_id=? AND id!=? ORDER BY position", - (list_id, card_id), - ).fetchall() - ids = [r["id"] for r in others] - pos = max(0, min(int(position), len(ids))) - ids.insert(pos, card_id) - c.execute( - "UPDATE cards SET list_id=?, updated_at=? WHERE id=?", - (list_id, t, card_id), - ) - for i, cid in enumerate(ids): - c.execute("UPDATE cards SET position=? WHERE id=?", (i, cid)) - if from_list != list_id: - rest = c.execute( - "SELECT id FROM cards WHERE list_id=? ORDER BY position", (from_list,) - ).fetchall() - for i, r in enumerate(rest): - c.execute("UPDATE cards SET position=? WHERE id=?", (i, r["id"])) - _activity( - c, - board_id, - "moveCard", - card_id=card_id, - data={ - "fromList": {"id": from_list}, - "toList": {"id": list_id}, - "position": position, - }, - ) - c.execute("UPDATE boards SET updated_at=? WHERE id=?", (t, board_id)) - return get_board(board_id) - - -def list_pads() -> list[dict[str, Any]]: - with _conn() as c: - rows = c.execute( - "SELECT id,title,authors_json,created_at,updated_at FROM pads ORDER BY updated_at DESC" - ).fetchall() - out = [] - for r in rows: - d = dict(r) - d["authors"] = json.loads(d.pop("authors_json") or "[]") - out.append(d) - return out - - -def get_pad(pad_id: str) -> dict[str, Any] | None: - with _conn() as c: - p = c.execute( - "SELECT id,title,text,authors_json,created_at,updated_at FROM pads WHERE id=?", - (pad_id,), - ).fetchone() - if not p: - return None - revs = [ - dict(r) - for r in c.execute( - "SELECT id,author,text,at FROM pad_revisions WHERE pad_id=? ORDER BY at DESC LIMIT 40", - (pad_id,), - ).fetchall() - ] - d = dict(p) - d["authors"] = json.loads(d.pop("authors_json") or "[]") - d["revisions"] = list(reversed(revs)) - return d - - -def create_pad(title: str, author: str = "guest") -> dict[str, Any]: - t = _now() - pid = _id("pad") - author = (author or "guest").strip() or "guest" - with _conn() as c: - c.execute( - "INSERT INTO pads(id,title,text,authors_json,created_at,updated_at) VALUES(?,?,?,?,?,?)", - (pid, title.strip() or "Untitled", "", json.dumps([author]), t, t), - ) - c.execute( - "INSERT INTO pad_revisions(id,pad_id,author,text,at) VALUES(?,?,?,?,?)", - (_id("rev"), pid, author, "", t), - ) - return get_pad(pid) # type: ignore - - -def update_pad(pad_id: str, text: str, author: str = "guest", title: str | None = None) -> dict[str, Any] | None: - t = _now() - author = (author or "guest").strip() or "guest" - with _conn() as c: - p = c.execute("SELECT * FROM pads WHERE id=?", (pad_id,)).fetchone() - if not p: - return None - authors = json.loads(p["authors_json"] or "[]") - if author not in authors: - authors.append(author) - new_title = title.strip() if title and title.strip() else p["title"] - c.execute( - "UPDATE pads SET title=?, text=?, authors_json=?, updated_at=? WHERE id=?", - (new_title, text, json.dumps(authors), t, pad_id), - ) - c.execute( - "INSERT INTO pad_revisions(id,pad_id,author,text,at) VALUES(?,?,?,?,?)", - (_id("rev"), pad_id, author, text, t), - ) - # trim - old = c.execute( - "SELECT id FROM pad_revisions WHERE pad_id=? ORDER BY at DESC", - (pad_id,), - ).fetchall() - for r in old[40:]: - c.execute("DELETE FROM pad_revisions WHERE id=?", (r["id"],)) - return get_pad(pad_id) +from work_svc.pb_store import ( # noqa: F401 + add_attachment, + add_card, + add_comment, + add_list, + add_task, + archive_card, + create_board, + create_pad, + create_project, + delete_attachment, + delete_card, + delete_list, + ensure_task_list, + get_board, + get_pad, + init_db, + list_boards, + list_pads, + list_projects, + move_card, + move_list, + toggle_card_label, + toggle_card_member, + toggle_stopwatch, + toggle_task, + update_board, + update_card, + update_list, + update_pad, +) diff --git a/apps/api/services/work_svc/store_sqlite_legacy.py b/apps/api/services/work_svc/store_sqlite_legacy.py new file mode 100644 index 0000000..d3dcb67 --- /dev/null +++ b/apps/api/services/work_svc/store_sqlite_legacy.py @@ -0,0 +1,1091 @@ +""" +SQLite store — domain shaped after Planka (Project/Board/List/Card) + Etherpad pads. +Secondary-dev reimplementation for Nomadro (not a dump of upstream runtime). +""" +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 + +# reuse ebook helper if importable; else local +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 + + +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 _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 init_db() -> None: + with _conn() as c: + c.executescript( + """ + CREATE TABLE IF NOT EXISTS projects ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + description TEXT NOT NULL DEFAULT '', + background_type TEXT DEFAULT 'gradient', + background_gradient TEXT DEFAULT 'ocean-dive', + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL + ); + CREATE TABLE IF NOT EXISTS boards ( + id TEXT PRIMARY KEY, + project_id TEXT NOT NULL, + name TEXT NOT NULL, + position REAL NOT NULL DEFAULT 0, + default_view TEXT NOT NULL DEFAULT 'kanban', + background_gradient TEXT DEFAULT 'ocean-dive', + show_card_counter INTEGER NOT NULL DEFAULT 1, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + FOREIGN KEY(project_id) REFERENCES projects(id) + ); + CREATE TABLE IF NOT EXISTS lists ( + id TEXT PRIMARY KEY, + board_id TEXT NOT NULL, + name TEXT NOT NULL, + type TEXT NOT NULL DEFAULT 'active', + position REAL NOT NULL DEFAULT 0, + color TEXT, + FOREIGN KEY(board_id) REFERENCES boards(id) + ); + CREATE TABLE IF NOT EXISTS cards ( + id TEXT PRIMARY KEY, + list_id TEXT NOT NULL, + board_id TEXT NOT NULL, + name TEXT NOT NULL, + description TEXT NOT NULL DEFAULT '', + type TEXT NOT NULL DEFAULT 'project', + position REAL NOT NULL DEFAULT 0, + due_date TEXT, + is_due_completed INTEGER NOT NULL DEFAULT 0, + stopwatch_json TEXT, + cover_color TEXT, + is_closed INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + FOREIGN KEY(list_id) REFERENCES lists(id), + FOREIGN KEY(board_id) REFERENCES boards(id) + ); + CREATE TABLE IF NOT EXISTS attachments ( + id TEXT PRIMARY KEY, + card_id TEXT NOT NULL, + name TEXT NOT NULL, + url TEXT NOT NULL, + created_at TEXT NOT NULL, + FOREIGN KEY(card_id) REFERENCES cards(id) + ); + CREATE TABLE IF NOT EXISTS pads ( + id TEXT PRIMARY KEY, + title TEXT NOT NULL, + text TEXT NOT NULL DEFAULT '', + authors_json TEXT NOT NULL DEFAULT '[]', + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL + ); + CREATE TABLE IF NOT EXISTS pad_revisions ( + id TEXT PRIMARY KEY, + pad_id TEXT NOT NULL, + author TEXT NOT NULL, + text TEXT NOT NULL, + at TEXT NOT NULL, + FOREIGN KEY(pad_id) REFERENCES pads(id) + ); + CREATE TABLE IF NOT EXISTS labels ( + id TEXT PRIMARY KEY, + board_id TEXT NOT NULL, + name TEXT, + color TEXT NOT NULL, + position REAL NOT NULL DEFAULT 0, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + FOREIGN KEY(board_id) REFERENCES boards(id) + ); + CREATE TABLE IF NOT EXISTS card_labels ( + card_id TEXT NOT NULL, + label_id TEXT NOT NULL, + PRIMARY KEY(card_id, label_id), + FOREIGN KEY(card_id) REFERENCES cards(id), + FOREIGN KEY(label_id) REFERENCES labels(id) + ); + CREATE TABLE IF NOT EXISTS task_lists ( + id TEXT PRIMARY KEY, + card_id TEXT NOT NULL, + name TEXT NOT NULL DEFAULT 'Checklist', + position REAL NOT NULL DEFAULT 0, + FOREIGN KEY(card_id) REFERENCES cards(id) + ); + CREATE TABLE IF NOT EXISTS tasks ( + id TEXT PRIMARY KEY, + task_list_id TEXT NOT NULL, + name TEXT NOT NULL, + is_completed INTEGER NOT NULL DEFAULT 0, + position REAL NOT NULL DEFAULT 0, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + FOREIGN KEY(task_list_id) REFERENCES task_lists(id) + ); + CREATE TABLE IF NOT EXISTS comments ( + id TEXT PRIMARY KEY, + card_id TEXT NOT NULL, + author TEXT NOT NULL, + text TEXT NOT NULL, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + FOREIGN KEY(card_id) REFERENCES cards(id) + ); + CREATE TABLE IF NOT EXISTS card_members ( + card_id TEXT NOT NULL, + name TEXT NOT NULL, + PRIMARY KEY(card_id, name), + FOREIGN KEY(card_id) REFERENCES cards(id) + ); + CREATE TABLE IF NOT EXISTS activities ( + id TEXT PRIMARY KEY, + board_id TEXT NOT NULL, + card_id TEXT, + actor TEXT NOT NULL DEFAULT 'system', + type TEXT NOT NULL, + data_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL, + FOREIGN KEY(board_id) REFERENCES boards(id) + ); + """ + ) + # Planka-parity columns for DBs created before this revision + _ensure_column(c, "projects", "background_type", "TEXT DEFAULT 'gradient'") + _ensure_column(c, "projects", "background_gradient", "TEXT DEFAULT 'ocean-dive'") + _ensure_column(c, "boards", "background_gradient", "TEXT DEFAULT 'ocean-dive'") + _ensure_column(c, "boards", "show_card_counter", "INTEGER NOT NULL DEFAULT 1") + _ensure_column(c, "cards", "is_due_completed", "INTEGER NOT NULL DEFAULT 0") + _ensure_column(c, "cards", "stopwatch_json", "TEXT") + _ensure_column(c, "cards", "cover_color", "TEXT") + n = c.execute("SELECT COUNT(*) AS n FROM projects").fetchone()["n"] + if n == 0: + _seed(c) + + +def _seed(c: sqlite3.Connection) -> None: + t = _now() + pid = _id("proj") + bid = _id("board") + c.execute( + "INSERT INTO projects(id,name,description,background_type,background_gradient,created_at,updated_at) VALUES(?,?,?,?,?,?,?)", + (pid, "Nomadro Remote", "二次开发种子项目(Planka 模型)", "gradient", "ocean-dive", t, t), + ) + c.execute( + "INSERT INTO boards(id,project_id,name,position,default_view,background_gradient,show_card_counter,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?)", + (bid, pid, "Sprint board", 0, "kanban", "ocean-dive", 1, t, t), + ) + lists = [ + (_id("list"), "Backlog", "active", 0), + (_id("list"), "Doing", "active", 1), + (_id("list"), "Done", "closed", 2), + (_id("list"), "Archive", "archive", 3), + ] + for lid, name, typ, pos in lists: + c.execute( + "INSERT INTO lists(id,board_id,name,type,position) VALUES(?,?,?,?,?)", + (lid, bid, name, typ, pos), + ) + c.execute( + "INSERT INTO cards(id,list_id,board_id,name,description,type,position,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?)", + ( + _id("card"), + lists[1][0], + bid, + "Native Next + FastAPI work module", + "From Planka/Etherpad domain analysis", + "project", + 0, + t, + t, + ), + ) + pad_id = _id("pad") + text = "# Nomadro Pad\n\nEtherpad 模型二次开发 · 修订历史进 FastAPI。\n" + c.execute( + "INSERT INTO pads(id,title,text,authors_json,created_at,updated_at) VALUES(?,?,?,?,?,?)", + (pad_id, "Welcome pad", text, json.dumps(["system"]), t, t), + ) + c.execute( + "INSERT INTO pad_revisions(id,pad_id,author,text,at) VALUES(?,?,?,?,?)", + (_id("rev"), pad_id, "system", text, t), + ) + + +def list_projects() -> list[dict[str, Any]]: + with _conn() as c: + rows = c.execute( + "SELECT id,name,description,created_at,updated_at FROM projects ORDER BY updated_at DESC" + ).fetchall() + return [dict(r) for r in rows] + + +def create_project(name: str, description: str = "") -> dict[str, Any]: + t = _now() + pid = _id("proj") + with _conn() as c: + c.execute( + "INSERT INTO projects(id,name,description,background_type,background_gradient,created_at,updated_at) VALUES(?,?,?,?,?,?,?)", + (pid, name.strip() or "Untitled", description.strip(), "gradient", "ocean-dive", t, t), + ) + bid = _id("board") + c.execute( + "INSERT INTO boards(id,project_id,name,position,default_view,background_gradient,show_card_counter,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?)", + (bid, pid, "Main board", 0, "kanban", "ocean-dive", 1, t, t), + ) + for i, (nm, typ) in enumerate( + [ + ("Backlog", "active"), + ("Doing", "active"), + ("Done", "closed"), + ("Archive", "archive"), + ] + ): + c.execute( + "INSERT INTO lists(id,board_id,name,type,position) VALUES(?,?,?,?,?)", + (_id("list"), bid, nm, typ, i), + ) + return {"id": pid, "name": name, "description": description, "created_at": t, "updated_at": t, "board_id": bid} + + +def list_boards(project_id: str | None = None) -> list[dict[str, Any]]: + with _conn() as c: + if project_id: + rows = c.execute( + "SELECT id,project_id,name,position,default_view,background_gradient,show_card_counter,created_at,updated_at FROM boards WHERE project_id=? ORDER BY position", + (project_id,), + ).fetchall() + else: + rows = c.execute( + "SELECT id,project_id,name,position,default_view,background_gradient,show_card_counter,created_at,updated_at FROM boards ORDER BY updated_at DESC" + ).fetchall() + return [dict(r) for r in rows] + + +def _ensure_board_labels(c: sqlite3.Connection, board_id: str) -> None: + n = c.execute( + "SELECT COUNT(*) AS n FROM labels WHERE board_id=?", (board_id,) + ).fetchone()["n"] + if n: + return + t = _now() + defaults = [ + ("Bug", "berry-red"), + ("Feature", "lagoon-blue"), + ("Urgent", "pumpkin-orange"), + ("Design", "pink-tulip"), + ] + for i, (name, color) in enumerate(defaults): + c.execute( + "INSERT INTO labels(id,board_id,name,color,position,created_at,updated_at) VALUES(?,?,?,?,?,?,?)", + (_id("label"), board_id, name, color, i, t, t), + ) + + +def _parse_card_row(r: sqlite3.Row) -> dict[str, Any]: + d = dict(r) + raw = d.pop("stopwatch_json", None) + try: + d["stopwatch"] = json.loads(raw) if raw else None + except Exception: + d["stopwatch"] = None + return d + + +def get_board(board_id: str) -> dict[str, Any] | None: + with _conn() as c: + b = c.execute( + "SELECT id,project_id,name,position,default_view,background_gradient,show_card_counter,created_at,updated_at FROM boards WHERE id=?", + (board_id,), + ).fetchone() + if not b: + return None + _ensure_board_labels(c, board_id) + lists = [ + dict(r) + for r in c.execute( + "SELECT id,board_id,name,type,position,color FROM lists WHERE board_id=? ORDER BY position", + (board_id,), + ).fetchall() + ] + # Ensure archive list exists (Planka ListTypes.ARCHIVE) + if not any(x["type"] == "archive" for x in lists): + pos = max((x["position"] for x in lists), default=-1) + 1 + aid = _id("list") + c.execute( + "INSERT INTO lists(id,board_id,name,type,position) VALUES(?,?,?,?,?)", + (aid, board_id, "Archive", "archive", pos), + ) + lists.append( + { + "id": aid, + "board_id": board_id, + "name": "Archive", + "type": "archive", + "position": pos, + "color": None, + } + ) + cards = [ + _parse_card_row(r) + for r in c.execute( + "SELECT id,list_id,board_id,name,description,type,position,due_date,is_due_completed,stopwatch_json,cover_color,is_closed,created_at,updated_at FROM cards WHERE board_id=? ORDER BY position", + (board_id,), + ).fetchall() + ] + labels = [ + dict(r) + for r in c.execute( + "SELECT id,board_id,name,color,position FROM labels WHERE board_id=? ORDER BY position", + (board_id,), + ).fetchall() + ] + card_ids = [x["id"] for x in cards] + card_labels: list[dict[str, Any]] = [] + task_lists: list[dict[str, Any]] = [] + tasks: list[dict[str, Any]] = [] + comments: list[dict[str, Any]] = [] + card_members: list[dict[str, Any]] = [] + if card_ids: + qmarks = ",".join("?" * len(card_ids)) + card_labels = [ + dict(r) + for r in c.execute( + f"SELECT card_id,label_id FROM card_labels WHERE card_id IN ({qmarks})", + card_ids, + ).fetchall() + ] + task_lists = [ + dict(r) + for r in c.execute( + f"SELECT id,card_id,name,position FROM task_lists WHERE card_id IN ({qmarks}) ORDER BY position", + card_ids, + ).fetchall() + ] + tl_ids = [t["id"] for t in task_lists] + if tl_ids: + tqm = ",".join("?" * len(tl_ids)) + tasks = [ + dict(r) + for r in c.execute( + f"SELECT id,task_list_id,name,is_completed,position,created_at,updated_at FROM tasks WHERE task_list_id IN ({tqm}) ORDER BY position", + tl_ids, + ).fetchall() + ] + comments = [ + dict(r) + for r in c.execute( + f"SELECT id,card_id,author,text,created_at,updated_at FROM comments WHERE card_id IN ({qmarks}) ORDER BY created_at", + card_ids, + ).fetchall() + ] + card_members = [ + dict(r) + for r in c.execute( + f"SELECT card_id,name FROM card_members WHERE card_id IN ({qmarks})", + card_ids, + ).fetchall() + ] + attachments: list[dict[str, Any]] = [] + if card_ids: + attachments = [ + dict(r) + for r in c.execute( + f"SELECT id,card_id,name,url,created_at FROM attachments WHERE card_id IN ({qmarks}) ORDER BY created_at", + card_ids, + ).fetchall() + ] + activities = [ + { + **dict(r), + "data": json.loads(r["data_json"] or "{}"), + } + for r in c.execute( + "SELECT id,board_id,card_id,actor,type,data_json,created_at FROM activities WHERE board_id=? ORDER BY created_at DESC LIMIT 40", + (board_id,), + ).fetchall() + ] + for a in activities: + a.pop("data_json", None) + out = dict(b) + out["lists"] = lists + out["cards"] = cards + out["labels"] = labels + out["card_labels"] = card_labels + out["task_lists"] = task_lists + out["tasks"] = tasks + out["comments"] = comments + out["card_members"] = card_members + out["attachments"] = attachments + out["activities"] = activities + return out + + +def _activity( + c: sqlite3.Connection, + board_id: str, + typ: str, + *, + card_id: str | None = None, + actor: str = "system", + data: dict[str, Any] | None = None, +) -> None: + c.execute( + "INSERT INTO activities(id,board_id,card_id,actor,type,data_json,created_at) VALUES(?,?,?,?,?,?,?)", + ( + _id("act"), + board_id, + card_id, + actor, + typ, + json.dumps(data or {}), + _now(), + ), + ) + + +def create_board(project_id: str, name: str) -> dict[str, Any]: + t = _now() + bid = _id("board") + with _conn() as c: + pos = c.execute( + "SELECT COALESCE(MAX(position),-1)+1 AS p FROM boards WHERE project_id=?", + (project_id,), + ).fetchone()["p"] + c.execute( + "INSERT INTO boards(id,project_id,name,position,default_view,background_gradient,show_card_counter,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?)", + (bid, project_id, name.strip() or "Board", pos, "kanban", "ocean-dive", 1, t, t), + ) + for i, (nm, typ) in enumerate( + [ + ("Backlog", "active"), + ("Doing", "active"), + ("Done", "closed"), + ("Archive", "archive"), + ] + ): + c.execute( + "INSERT INTO lists(id,board_id,name,type,position) VALUES(?,?,?,?,?)", + (_id("list"), bid, nm, typ, i), + ) + c.execute("UPDATE projects SET updated_at=? WHERE id=?", (t, project_id)) + return get_board(bid) # type: ignore + + +def add_list(board_id: str, name: str, typ: str = "active") -> dict[str, Any] | None: + with _conn() as c: + if not c.execute("SELECT 1 FROM boards WHERE id=?", (board_id,)).fetchone(): + return None + pos = c.execute( + "SELECT COALESCE(MAX(position),-1)+1 AS p FROM lists WHERE board_id=?", + (board_id,), + ).fetchone()["p"] + lid = _id("list") + c.execute( + "INSERT INTO lists(id,board_id,name,type,position) VALUES(?,?,?,?,?)", + (lid, board_id, name.strip() or "List", typ, pos), + ) + c.execute("UPDATE boards SET updated_at=? WHERE id=?", (_now(), board_id)) + return get_board(board_id) + + +def add_card(board_id: str, list_id: str, name: str, description: str = "") -> dict[str, Any] | None: + t = _now() + with _conn() as c: + if not c.execute( + "SELECT 1 FROM lists WHERE id=? AND board_id=?", (list_id, board_id) + ).fetchone(): + return None + pos = c.execute( + "SELECT COALESCE(MAX(position),-1)+1 AS p FROM cards WHERE list_id=?", + (list_id,), + ).fetchone()["p"] + cid = _id("card") + cname = name.strip() or "Card" + c.execute( + "INSERT INTO cards(id,list_id,board_id,name,description,type,position,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?)", + (cid, list_id, board_id, cname, description.strip(), "project", pos, t, t), + ) + _activity( + c, + board_id, + "createCard", + card_id=cid, + data={"card": {"name": cname}, "listId": list_id}, + ) + c.execute("UPDATE boards SET updated_at=? WHERE id=?", (t, board_id)) + return get_board(board_id) + + +def update_card( + board_id: str, + card_id: str, + *, + name: str | None = None, + description: str | None = None, + due_date: str | None = None, + clear_due: bool = False, + is_due_completed: bool | None = None, + cover_color: str | None = None, + clear_cover: bool = False, +) -> dict[str, Any] | None: + t = _now() + with _conn() as c: + card = c.execute( + "SELECT * FROM cards WHERE id=? AND board_id=?", (card_id, board_id) + ).fetchone() + if not card: + return None + new_name = name.strip() if name is not None else card["name"] + new_desc = description if description is not None else card["description"] + if name is not None and not new_name: + new_name = card["name"] + new_due = card["due_date"] + if clear_due: + new_due = None + elif due_date is not None: + new_due = due_date or None + due_done = ( + int(bool(is_due_completed)) + if is_due_completed is not None + else card["is_due_completed"] + ) + cover = card["cover_color"] if "cover_color" in card.keys() else None + if clear_cover: + cover = None + elif cover_color is not None: + cover = cover_color or None + c.execute( + "UPDATE cards SET name=?, description=?, due_date=?, is_due_completed=?, cover_color=?, updated_at=? WHERE id=?", + (new_name, new_desc or "", new_due, due_done, cover, t, card_id), + ) + c.execute("UPDATE boards SET updated_at=? WHERE id=?", (t, board_id)) + return get_board(board_id) + + +def update_board( + board_id: str, + *, + name: str | None = None, + background_gradient: str | None = None, + show_card_counter: bool | None = None, +) -> dict[str, Any] | None: + t = _now() + with _conn() as c: + b = c.execute("SELECT * FROM boards WHERE id=?", (board_id,)).fetchone() + if not b: + return None + new_name = name.strip() if name is not None else b["name"] + if name is not None and not new_name: + new_name = b["name"] + grad = ( + background_gradient + if background_gradient is not None + else b["background_gradient"] + ) + counter = ( + int(bool(show_card_counter)) + if show_card_counter is not None + else b["show_card_counter"] + ) + c.execute( + "UPDATE boards SET name=?, background_gradient=?, show_card_counter=?, updated_at=? WHERE id=?", + (new_name, grad, counter, t, board_id), + ) + return get_board(board_id) + + +def toggle_stopwatch(board_id: str, card_id: str) -> dict[str, Any] | None: + """Planka startStopwatch / stopStopwatch parity.""" + t = _now() + with _conn() as c: + card = c.execute( + "SELECT * FROM cards WHERE id=? AND board_id=?", (card_id, board_id) + ).fetchone() + if not card: + return None + try: + sw = json.loads(card["stopwatch_json"] or "null") or { + "startedAt": None, + "total": 0, + } + except Exception: + sw = {"startedAt": None, "total": 0} + if sw.get("startedAt"): + started = time.strptime(sw["startedAt"], "%Y-%m-%dT%H:%M:%SZ") + elapsed = int(time.mktime(time.gmtime()) - time.mktime(started)) + # started was UTC via strptime without tz — use fromisoformat style + try: + from datetime import datetime, timezone + + started_dt = datetime.strptime( + sw["startedAt"], "%Y-%m-%dT%H:%M:%SZ" + ).replace(tzinfo=timezone.utc) + elapsed = int((datetime.now(timezone.utc) - started_dt).total_seconds()) + except Exception: + elapsed = max(0, elapsed) + sw = {"startedAt": None, "total": int(sw.get("total") or 0) + max(0, elapsed)} + else: + sw = {"startedAt": t, "total": int(sw.get("total") or 0)} + c.execute( + "UPDATE cards SET stopwatch_json=?, updated_at=? WHERE id=?", + (json.dumps(sw), t, card_id), + ) + c.execute("UPDATE boards SET updated_at=? WHERE id=?", (t, board_id)) + return get_board(board_id) + + +def add_attachment( + board_id: str, card_id: str, name: str, url: str +) -> dict[str, Any] | None: + t = _now() + with _conn() as c: + if not c.execute( + "SELECT 1 FROM cards WHERE id=? AND board_id=?", (card_id, board_id) + ).fetchone(): + return None + c.execute( + "INSERT INTO attachments(id,card_id,name,url,created_at) VALUES(?,?,?,?,?)", + ( + _id("att"), + card_id, + (name or "Link").strip() or "Link", + url.strip(), + t, + ), + ) + c.execute("UPDATE boards SET updated_at=? WHERE id=?", (t, board_id)) + return get_board(board_id) + + +def delete_attachment(board_id: str, attachment_id: str) -> dict[str, Any] | None: + with _conn() as c: + row = c.execute( + "SELECT a.id, a.card_id FROM attachments a JOIN cards c ON c.id=a.card_id WHERE a.id=? AND c.board_id=?", + (attachment_id, board_id), + ).fetchone() + if not row: + return None + c.execute("DELETE FROM attachments WHERE id=?", (attachment_id,)) + c.execute("UPDATE boards SET updated_at=? WHERE id=?", (_now(), board_id)) + return get_board(board_id) + + +def archive_card(board_id: str, card_id: str) -> dict[str, Any] | None: + """Move card into Archive list (Planka moveCurrentCardToArchive).""" + with _conn() as c: + card = c.execute( + "SELECT * FROM cards WHERE id=? AND board_id=?", (card_id, board_id) + ).fetchone() + if not card: + return None + arch = c.execute( + "SELECT id FROM lists WHERE board_id=? AND type='archive' ORDER BY position LIMIT 1", + (board_id,), + ).fetchone() + if not arch: + return None + list_id = arch["id"] + return move_card(board_id, card_id, list_id, 0) + + +def move_list(board_id: str, list_id: str, position: int) -> dict[str, Any] | None: + with _conn() as c: + if not c.execute( + "SELECT 1 FROM lists WHERE id=? AND board_id=?", (list_id, board_id) + ).fetchone(): + return None + others = c.execute( + "SELECT id FROM lists WHERE board_id=? AND id!=? ORDER BY position", + (board_id, list_id), + ).fetchall() + ids = [r["id"] for r in others] + pos = max(0, min(int(position), len(ids))) + ids.insert(pos, list_id) + for i, lid in enumerate(ids): + c.execute("UPDATE lists SET position=? WHERE id=?", (i, lid)) + c.execute("UPDATE boards SET updated_at=? WHERE id=?", (_now(), board_id)) + return get_board(board_id) + + +def toggle_card_label(board_id: str, card_id: str, label_id: str) -> dict[str, Any] | None: + with _conn() as c: + if not c.execute( + "SELECT 1 FROM cards WHERE id=? AND board_id=?", (card_id, board_id) + ).fetchone(): + return None + if not c.execute( + "SELECT 1 FROM labels WHERE id=? AND board_id=?", (label_id, board_id) + ).fetchone(): + return None + hit = c.execute( + "SELECT 1 FROM card_labels WHERE card_id=? AND label_id=?", + (card_id, label_id), + ).fetchone() + if hit: + c.execute( + "DELETE FROM card_labels WHERE card_id=? AND label_id=?", + (card_id, label_id), + ) + else: + c.execute( + "INSERT INTO card_labels(card_id,label_id) VALUES(?,?)", + (card_id, label_id), + ) + c.execute("UPDATE boards SET updated_at=? WHERE id=?", (_now(), board_id)) + return get_board(board_id) + + +def ensure_task_list(card_id: str) -> str: + with _conn() as c: + row = c.execute( + "SELECT id FROM task_lists WHERE card_id=? ORDER BY position LIMIT 1", + (card_id,), + ).fetchone() + if row: + return row["id"] + tid = _id("tlist") + c.execute( + "INSERT INTO task_lists(id,card_id,name,position) VALUES(?,?,?,?)", + (tid, card_id, "Checklist", 0), + ) + return tid + + +def add_task(board_id: str, card_id: str, name: str) -> dict[str, Any] | None: + t = _now() + with _conn() as c: + if not c.execute( + "SELECT 1 FROM cards WHERE id=? AND board_id=?", (card_id, board_id) + ).fetchone(): + return None + tl = ensure_task_list(card_id) + with _conn() as c: + pos = c.execute( + "SELECT COALESCE(MAX(position),-1)+1 AS p FROM tasks WHERE task_list_id=?", + (tl,), + ).fetchone()["p"] + c.execute( + "INSERT INTO tasks(id,task_list_id,name,is_completed,position,created_at,updated_at) VALUES(?,?,?,?,?,?,?)", + (_id("task"), tl, name.strip() or "Task", 0, pos, t, t), + ) + c.execute("UPDATE boards SET updated_at=? WHERE id=?", (t, board_id)) + return get_board(board_id) + + +def toggle_task(board_id: str, task_id: str) -> dict[str, Any] | None: + t = _now() + with _conn() as c: + task = c.execute("SELECT * FROM tasks WHERE id=?", (task_id,)).fetchone() + if not task: + return None + done = 0 if task["is_completed"] else 1 + c.execute( + "UPDATE tasks SET is_completed=?, updated_at=? WHERE id=?", + (done, t, task_id), + ) + tl = c.execute( + "SELECT card_id FROM task_lists WHERE id=?", (task["task_list_id"],) + ).fetchone() + _activity( + c, + board_id, + "completeTask" if done else "uncompleteTask", + card_id=tl["card_id"] if tl else None, + data={"task": {"id": task_id, "name": task["name"]}}, + ) + c.execute("UPDATE boards SET updated_at=? WHERE id=?", (t, board_id)) + return get_board(board_id) + + +def add_comment(board_id: str, card_id: str, author: str, text: str) -> dict[str, Any] | None: + t = _now() + with _conn() as c: + if not c.execute( + "SELECT 1 FROM cards WHERE id=? AND board_id=?", (card_id, board_id) + ).fetchone(): + return None + who = (author or "guest").strip() or "guest" + c.execute( + "INSERT INTO comments(id,card_id,author,text,created_at,updated_at) VALUES(?,?,?,?,?,?)", + (_id("cmt"), card_id, who, text.strip(), t, t), + ) + _activity( + c, + board_id, + "comment", + card_id=card_id, + actor=who, + data={"text": text.strip()[:120]}, + ) + c.execute("UPDATE boards SET updated_at=? WHERE id=?", (t, board_id)) + return get_board(board_id) + + +def update_list( + board_id: str, + list_id: str, + *, + name: str | None = None, + color: str | None = None, +) -> dict[str, Any] | None: + with _conn() as c: + row = c.execute( + "SELECT * FROM lists WHERE id=? AND board_id=?", (list_id, board_id) + ).fetchone() + if not row: + return None + new_name = name.strip() if name is not None else row["name"] + if name is not None and not new_name: + new_name = row["name"] + new_color = color if color is not None else row["color"] + c.execute( + "UPDATE lists SET name=?, color=? WHERE id=?", + (new_name, new_color, list_id), + ) + c.execute("UPDATE boards SET updated_at=? WHERE id=?", (_now(), board_id)) + return get_board(board_id) + + +def delete_list(board_id: str, list_id: str) -> dict[str, Any] | None: + with _conn() as c: + if not c.execute( + "SELECT 1 FROM lists WHERE id=? AND board_id=?", (list_id, board_id) + ).fetchone(): + return None + cards = c.execute( + "SELECT id FROM cards WHERE list_id=?", (list_id,) + ).fetchall() + for card in cards: + cid = card["id"] + c.execute("DELETE FROM card_labels WHERE card_id=?", (cid,)) + c.execute("DELETE FROM card_members WHERE card_id=?", (cid,)) + c.execute("DELETE FROM comments WHERE card_id=?", (cid,)) + tls = c.execute( + "SELECT id FROM task_lists WHERE card_id=?", (cid,) + ).fetchall() + for tl in tls: + c.execute("DELETE FROM tasks WHERE task_list_id=?", (tl["id"],)) + c.execute("DELETE FROM task_lists WHERE card_id=?", (cid,)) + c.execute("DELETE FROM cards WHERE list_id=?", (list_id,)) + c.execute("DELETE FROM lists WHERE id=?", (list_id,)) + _activity(c, board_id, "delete_list", data={"list_id": list_id}) + c.execute("UPDATE boards SET updated_at=? WHERE id=?", (_now(), board_id)) + return get_board(board_id) + + +def delete_card(board_id: str, card_id: str) -> dict[str, Any] | None: + with _conn() as c: + if not c.execute( + "SELECT 1 FROM cards WHERE id=? AND board_id=?", (card_id, board_id) + ).fetchone(): + return None + c.execute("DELETE FROM card_labels WHERE card_id=?", (card_id,)) + c.execute("DELETE FROM card_members WHERE card_id=?", (card_id,)) + c.execute("DELETE FROM comments WHERE card_id=?", (card_id,)) + tls = c.execute( + "SELECT id FROM task_lists WHERE card_id=?", (card_id,) + ).fetchall() + for tl in tls: + c.execute("DELETE FROM tasks WHERE task_list_id=?", (tl["id"],)) + c.execute("DELETE FROM task_lists WHERE card_id=?", (card_id,)) + c.execute("DELETE FROM cards WHERE id=?", (card_id,)) + _activity(c, board_id, "delete_card", card_id=card_id) + c.execute("UPDATE boards SET updated_at=? WHERE id=?", (_now(), board_id)) + return get_board(board_id) + + +def toggle_card_member(board_id: str, card_id: str, name: str) -> dict[str, Any] | None: + who = (name or "").strip() + if not who: + return None + with _conn() as c: + if not c.execute( + "SELECT 1 FROM cards WHERE id=? AND board_id=?", (card_id, board_id) + ).fetchone(): + return None + hit = c.execute( + "SELECT 1 FROM card_members WHERE card_id=? AND name=?", + (card_id, who), + ).fetchone() + if hit: + c.execute( + "DELETE FROM card_members WHERE card_id=? AND name=?", + (card_id, who), + ) + act = "removeMemberFromCard" + else: + c.execute( + "INSERT INTO card_members(card_id,name) VALUES(?,?)", + (card_id, who), + ) + act = "addMemberToCard" + _activity( + c, + board_id, + act, + card_id=card_id, + actor=who, + data={"name": who}, + ) + c.execute("UPDATE boards SET updated_at=? WHERE id=?", (_now(), board_id)) + return get_board(board_id) + + +def move_card(board_id: str, card_id: str, list_id: str, position: int) -> dict[str, Any] | None: + t = _now() + with _conn() as c: + card = c.execute( + "SELECT * FROM cards WHERE id=? AND board_id=?", (card_id, board_id) + ).fetchone() + if not card: + return None + if not c.execute( + "SELECT 1 FROM lists WHERE id=? AND board_id=?", (list_id, board_id) + ).fetchone(): + return None + from_list = card["list_id"] + others = c.execute( + "SELECT id FROM cards WHERE list_id=? AND id!=? ORDER BY position", + (list_id, card_id), + ).fetchall() + ids = [r["id"] for r in others] + pos = max(0, min(int(position), len(ids))) + ids.insert(pos, card_id) + c.execute( + "UPDATE cards SET list_id=?, updated_at=? WHERE id=?", + (list_id, t, card_id), + ) + for i, cid in enumerate(ids): + c.execute("UPDATE cards SET position=? WHERE id=?", (i, cid)) + if from_list != list_id: + rest = c.execute( + "SELECT id FROM cards WHERE list_id=? ORDER BY position", (from_list,) + ).fetchall() + for i, r in enumerate(rest): + c.execute("UPDATE cards SET position=? WHERE id=?", (i, r["id"])) + _activity( + c, + board_id, + "moveCard", + card_id=card_id, + data={ + "fromList": {"id": from_list}, + "toList": {"id": list_id}, + "position": position, + }, + ) + c.execute("UPDATE boards SET updated_at=? WHERE id=?", (t, board_id)) + return get_board(board_id) + + +def list_pads() -> list[dict[str, Any]]: + with _conn() as c: + rows = c.execute( + "SELECT id,title,authors_json,created_at,updated_at FROM pads ORDER BY updated_at DESC" + ).fetchall() + out = [] + for r in rows: + d = dict(r) + d["authors"] = json.loads(d.pop("authors_json") or "[]") + out.append(d) + return out + + +def get_pad(pad_id: str) -> dict[str, Any] | None: + with _conn() as c: + p = c.execute( + "SELECT id,title,text,authors_json,created_at,updated_at FROM pads WHERE id=?", + (pad_id,), + ).fetchone() + if not p: + return None + revs = [ + dict(r) + for r in c.execute( + "SELECT id,author,text,at FROM pad_revisions WHERE pad_id=? ORDER BY at DESC LIMIT 40", + (pad_id,), + ).fetchall() + ] + d = dict(p) + d["authors"] = json.loads(d.pop("authors_json") or "[]") + d["revisions"] = list(reversed(revs)) + return d + + +def create_pad(title: str, author: str = "guest") -> dict[str, Any]: + t = _now() + pid = _id("pad") + author = (author or "guest").strip() or "guest" + with _conn() as c: + c.execute( + "INSERT INTO pads(id,title,text,authors_json,created_at,updated_at) VALUES(?,?,?,?,?,?)", + (pid, title.strip() or "Untitled", "", json.dumps([author]), t, t), + ) + c.execute( + "INSERT INTO pad_revisions(id,pad_id,author,text,at) VALUES(?,?,?,?,?)", + (_id("rev"), pid, author, "", t), + ) + return get_pad(pid) # type: ignore + + +def update_pad(pad_id: str, text: str, author: str = "guest", title: str | None = None) -> dict[str, Any] | None: + t = _now() + author = (author or "guest").strip() or "guest" + with _conn() as c: + p = c.execute("SELECT * FROM pads WHERE id=?", (pad_id,)).fetchone() + if not p: + return None + authors = json.loads(p["authors_json"] or "[]") + if author not in authors: + authors.append(author) + new_title = title.strip() if title and title.strip() else p["title"] + c.execute( + "UPDATE pads SET title=?, text=?, authors_json=?, updated_at=? WHERE id=?", + (new_title, text, json.dumps(authors), t, pad_id), + ) + c.execute( + "INSERT INTO pad_revisions(id,pad_id,author,text,at) VALUES(?,?,?,?,?)", + (_id("rev"), pad_id, author, text, t), + ) + # trim + old = c.execute( + "SELECT id FROM pad_revisions WHERE pad_id=? ORDER BY at DESC", + (pad_id,), + ).fetchall() + for r in old[40:]: + c.execute("DELETE FROM pad_revisions WHERE id=?", (r["id"],)) + return get_pad(pad_id) diff --git a/apps/com/admin/src/App.tsx b/apps/com/admin/src/App.tsx index 37db665..eddbda2 100644 --- a/apps/com/admin/src/App.tsx +++ b/apps/com/admin/src/App.tsx @@ -10,6 +10,7 @@ import Orders from './pages/Orders' import Users from './pages/Users' import Ntfy from './pages/Ntfy' import Social from './pages/Social' +import SocialDetail from './pages/SocialDetail' import Blog from './pages/Blog' import LaneHub, { type LaneKey } from './pages/LaneHub' @@ -59,7 +60,23 @@ export default function App() { > } /> } /> - } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> } /> } /> } /> diff --git a/apps/com/admin/src/components/WebLayout.tsx b/apps/com/admin/src/components/WebLayout.tsx index 935f21a..127072a 100644 --- a/apps/com/admin/src/components/WebLayout.tsx +++ b/apps/com/admin/src/components/WebLayout.tsx @@ -1,9 +1,19 @@ -import { useEffect, useState } from 'react' +import { useEffect, useMemo, useState } from 'react' import { NavLink, Outlet, useLocation, useNavigate, useParams } from 'react-router-dom' import { clearToken } from '../api/client' import type { LaneKey } from '../pages/LaneHub' -type NavItem = { to: string; end?: boolean; ico: string; label: string } +type NavLeaf = { kind?: 'link'; to: string; end?: boolean; ico: string; label: string } +type NavBranch = { + kind: 'branch' + id: string + ico: string + label: string + match: string[] + defaultTo: string + children: NavLeaf[] +} +type NavItem = NavLeaf | NavBranch const LANE_META: Record = { cn: { title: '中文用户', sub: 'Chinese · 特殊对待', mark: '中' }, @@ -15,7 +25,24 @@ function laneNav(lane: LaneKey): NavItem[] { return [ { to: p, end: true, ico: '◈', label: '模块总览' }, { to: `${p}/switches`, ico: '⏻', label: '动态开关' }, - { to: `${p}/social`, ico: '💕', label: '游民社区' }, + { + kind: 'branch', + id: 'social', + ico: '💕', + label: '游民社区', + match: [`${p}/social`], + defaultTo: `${p}/social/overview`, + children: [ + { to: `${p}/social/overview`, end: true, ico: '◈', label: '数据概览' }, + { to: `${p}/social/roster`, ico: '👤', label: '花名册' }, + { to: `${p}/social/messages`, ico: '💬', label: '聊天' }, + { to: `${p}/social/reviews`, ico: '☕', label: '咖啡馆评价' }, + { to: `${p}/social/gigs`, ico: '🛠️', label: '接单申请' }, + { to: `${p}/social/feedback`, ico: '📩', label: '反馈' }, + { to: `${p}/social/archives`, ico: '🗄️', label: '存档' }, + { to: `${p}/social/catalog`, ico: '📁', label: '目录配置' }, + ], + }, { to: `${p}/blog`, ico: '📝', label: 'Nomad Blog' }, { to: `${p}/events`, ico: '📊', label: '埋点' }, { to: `${p}/orders`, ico: '🧾', label: '订单' }, @@ -25,26 +52,51 @@ function laneNav(lane: LaneKey): NavItem[] { ] } -function titleFromPath(lane: LaneKey, pathname: string) { - const items = laneNav(lane) - const hit = items.find((n) => (n.end ? pathname === n.to : pathname.startsWith(n.to))) - const mod = LANE_META[lane].title - return hit && !hit.end ? `${mod} · ${hit.label}` : mod +function flattenLeaves(items: NavItem[]): NavLeaf[] { + const out: NavLeaf[] = [] + for (const item of items) { + if (item.kind === 'branch') out.push(...item.children) + else out.push(item) + } + return out } -/** 已选模块后的壳:只显示当前模块侧栏;切模块回选择页 */ +function titleFromPath(lane: LaneKey, pathname: string) { + const leaves = flattenLeaves(laneNav(lane)) + const sorted = [...leaves].sort((a, b) => b.to.length - a.to.length) + const hit = sorted.find((n) => (n.end ? pathname === n.to : pathname.startsWith(n.to))) + const mod = LANE_META[lane].title + return hit && !(hit.end && hit.to === `/${lane}`) ? `${mod} · ${hit.label}` : mod +} + +function isBranchActive(branch: NavBranch, pathname: string) { + return branch.match.some((m) => pathname === m || pathname.startsWith(`${m}/`)) +} + +/** 已选模块后的壳:一级 / 二级侧栏;切模块回选择页 */ export default function WebLayout() { const nav = useNavigate() const { pathname } = useLocation() const { lane: laneParam } = useParams() const lane: LaneKey = laneParam === 'cn' ? 'cn' : 'intl' const meta = LANE_META[lane] + const items = useMemo(() => laneNav(lane), [lane]) const [open, setOpen] = useState(false) + const socialBranch = items.find((x) => x.kind === 'branch' && x.id === 'social') as + | NavBranch + | undefined + const socialActive = socialBranch ? isBranchActive(socialBranch, pathname) : false + const [socialOpen, setSocialOpen] = useState(() => socialActive) + useEffect(() => { setOpen(false) }, [pathname]) + useEffect(() => { + if (socialActive) setSocialOpen(true) + }, [socialActive]) + useEffect(() => { document.body.style.overflow = open ? 'hidden' : '' return () => { @@ -57,6 +109,15 @@ export default function WebLayout() { nav('/login') } + function toggleSocial() { + if (!socialBranch) return + setSocialOpen((v) => { + const next = !v + if (next && !socialActive) nav(socialBranch.defaultTo) + return next + }) + } + return (
@@ -101,20 +162,66 @@ export default function WebLayout() { 切换模块 · 中文 / 国际 -
+ + ) : null} - - - {tab === 'catalog' ? ( + {section === 'catalog' ? (

socialCatalogs

-

meetups / gigs / cafes / roster / ebooks / videos(JSON)

+

meetups / gigs / cafes / roster / ebooks / videos

-