Ship social admin nested menus with list/detail CRUD, soft-archive UGC, and PocketBase-ready stores.
admin.nomadro.com gets sidebar L1/L2 social ops (paginated lists + entity detail); API adds soft-delete archives/stats and shared nomadro_pb for social/coffee/notify/work. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
3e8458581a
commit
b06a14b6aa
104
apps/admin/deploy/_deploy_admin_com_us.py
Normal file
104
apps/admin/deploy/_deploy_admin_com_us.py
Normal file
@ -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())
|
||||||
186
apps/admin/deploy/_push_social_ugc_admin_us.py
Normal file
186
apps/admin/deploy/_push_social_ugc_admin_us.py
Normal file
@ -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())
|
||||||
97
apps/admin/deploy/_push_ugc_sqlite_us.py
Normal file
97
apps/admin/deploy/_push_ugc_sqlite_us.py
Normal file
@ -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())
|
||||||
66
apps/admin/deploy/_restore_social_sqlite_us.py
Normal file
66
apps/admin/deploy/_restore_social_sqlite_us.py
Normal file
@ -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())
|
||||||
77
apps/admin/deploy/_smoke_admin_com_us.py
Normal file
77
apps/admin/deploy/_smoke_admin_com_us.py
Normal file
@ -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())
|
||||||
674
apps/admin/deploy/_us_social_ugc_sqlite.py
Normal file
674
apps/admin/deploy/_us_social_ugc_sqlite.py
Normal file
@ -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}
|
||||||
@ -92,7 +92,7 @@ export default function SocialData() {
|
|||||||
}, [loadList])
|
}, [loadList])
|
||||||
|
|
||||||
async function remove(kind: Tab, id: string) {
|
async function remove(kind: Tab, id: string) {
|
||||||
if (!confirm('确认删除?不可恢复')) return
|
if (!confirm('软删除?内容会写入存档(social_archives),不会物理抹除。')) return
|
||||||
setBusy(true)
|
setBusy(true)
|
||||||
setMsg('')
|
setMsg('')
|
||||||
setErr('')
|
setErr('')
|
||||||
@ -105,7 +105,7 @@ export default function SocialData() {
|
|||||||
feedback: `/api/admin/social/ugc/feedback/${id}`,
|
feedback: `/api/admin/social/ugc/feedback/${id}`,
|
||||||
}
|
}
|
||||||
await api(map[kind], { method: 'DELETE' })
|
await api(map[kind], { method: 'DELETE' })
|
||||||
setMsg('已删除')
|
setMsg('已软删除并写入存档')
|
||||||
await loadList()
|
await loadList()
|
||||||
await loadOverview()
|
await loadOverview()
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
|
|||||||
405
apps/api/services/coffee_svc/pb_store.py
Normal file
405
apps/api/services/coffee_svc/pb_store.py
Normal file
@ -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,
|
||||||
|
}
|
||||||
@ -131,6 +131,20 @@ def book(body: BookingIn):
|
|||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
code = 409 if str(e) == "slot_unavailable" else 400
|
code = 409 if str(e) == "slot_unavailable" else 400
|
||||||
raise HTTPException(code, str(e)) from e
|
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}
|
return {"ok": True, "booking": b}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -1,719 +1,17 @@
|
|||||||
"""
|
"""Coffeechat store — PocketBase (online-first)."""
|
||||||
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
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
from coffee_svc.pb_store import ( # noqa: F401
|
||||||
import sqlite3
|
available_slots,
|
||||||
import time
|
cancel_booking,
|
||||||
import uuid
|
create_booking,
|
||||||
from datetime import date, datetime, timedelta, timezone
|
get_booking,
|
||||||
from pathlib import Path
|
get_event_type,
|
||||||
from typing import Any
|
get_host,
|
||||||
from zoneinfo import ZoneInfo
|
get_schedule,
|
||||||
|
init_db,
|
||||||
from .config import DATA_DIR, DB_PATH
|
list_bookings,
|
||||||
|
list_hosts,
|
||||||
try:
|
update_schedule,
|
||||||
from ebook_svc.core.sqlite_util import connect as _connect
|
upsert_event_type,
|
||||||
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"),
|
|
||||||
}
|
|
||||||
|
|||||||
719
apps/api/services/coffee_svc/store_sqlite_legacy.py
Normal file
719
apps/api/services/coffee_svc/store_sqlite_legacy.py
Normal file
@ -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"),
|
||||||
|
}
|
||||||
@ -5,9 +5,10 @@ class Settings(BaseSettings):
|
|||||||
# 忽略 .env 中其它模块键,避免本地/统一 env 拖垮启动(不改业务字段)
|
# 忽略 .env 中其它模块键,避免本地/统一 env 拖垮启动(不改业务字段)
|
||||||
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
|
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_url: str = "http://127.0.0.1:8090"
|
||||||
pocketbase_admin_email: str = "admin@nomadro.com"
|
pocketbase_admin_email: str = ""
|
||||||
pocketbase_admin_password: str = "Xiao4669805"
|
pocketbase_admin_password: str = ""
|
||||||
api_host: str = "0.0.0.0"
|
api_host: str = "0.0.0.0"
|
||||||
api_port: int = 8000
|
api_port: int = 8000
|
||||||
cors_origins: str = "http://localhost:3000,http://127.0.0.1:3000"
|
cors_origins: str = "http://localhost:3000,http://127.0.0.1:3000"
|
||||||
|
|||||||
@ -66,6 +66,7 @@ def _migrate_json_to_pb() -> None:
|
|||||||
data = json.loads(STORE_PATH.read_text(encoding="utf-8"))
|
data = json.loads(STORE_PATH.read_text(encoding="utf-8"))
|
||||||
except (OSError, json.JSONDecodeError):
|
except (OSError, json.JSONDecodeError):
|
||||||
return
|
return
|
||||||
|
try:
|
||||||
if pb.list_records("nomad_accounts", per_page=1).get("totalItems", 0) > 0:
|
if pb.list_records("nomad_accounts", per_page=1).get("totalItems", 0) > 0:
|
||||||
return
|
return
|
||||||
for email, user in (data.get("users") or {}).items():
|
for email, user in (data.get("users") or {}).items():
|
||||||
@ -87,6 +88,9 @@ def _migrate_json_to_pb() -> None:
|
|||||||
"nomad_sessions",
|
"nomad_sessions",
|
||||||
{"token": token, "userId": uid, "expiresAt": int(time.time()) + 86400 * 30},
|
{"token": token, "userId": uid, "expiresAt": int(time.time()) + 86400 * 30},
|
||||||
)
|
)
|
||||||
|
except Exception:
|
||||||
|
# Online PB may lack legacy community collections — never block API boot
|
||||||
|
return
|
||||||
|
|
||||||
|
|
||||||
def _restore_json() -> bool:
|
def _restore_json() -> bool:
|
||||||
|
|||||||
@ -20,6 +20,8 @@ class RosterPatch(BaseModel):
|
|||||||
linktree: str | None = None
|
linktree: str | None = None
|
||||||
skills: str | None = None
|
skills: str | None = None
|
||||||
bio: str | None = None
|
bio: str | None = None
|
||||||
|
restore: bool | None = None
|
||||||
|
status: str | None = None
|
||||||
|
|
||||||
|
|
||||||
@router.get("/overview")
|
@router.get("/overview")
|
||||||
@ -27,6 +29,28 @@ async def get_overview(_: str = Depends(require_admin)) -> dict[str, Any]:
|
|||||||
return ugc.overview()
|
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")
|
@router.get("/messages")
|
||||||
async def get_messages(
|
async def get_messages(
|
||||||
channelId: str = "",
|
channelId: str = "",
|
||||||
@ -45,7 +69,7 @@ async def get_messages(
|
|||||||
async def del_message(message_id: str, _: str = Depends(require_admin)) -> dict[str, Any]:
|
async def del_message(message_id: str, _: str = Depends(require_admin)) -> dict[str, Any]:
|
||||||
if not ugc.delete_message(message_id):
|
if not ugc.delete_message(message_id):
|
||||||
raise HTTPException(404, "消息不存在")
|
raise HTTPException(404, "消息不存在")
|
||||||
return {"ok": True}
|
return {"ok": True, "soft": True, "archived": True}
|
||||||
|
|
||||||
|
|
||||||
@router.get("/roster")
|
@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]:
|
async def del_roster(guest_id: str, _: str = Depends(require_admin)) -> dict[str, Any]:
|
||||||
if not ugc.delete_roster(guest_id):
|
if not ugc.delete_roster(guest_id):
|
||||||
raise HTTPException(404, "介绍不存在")
|
raise HTTPException(404, "介绍不存在")
|
||||||
return {"ok": True}
|
return {"ok": True, "soft": True, "archived": True}
|
||||||
|
|
||||||
|
|
||||||
@router.get("/reviews")
|
@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]:
|
async def del_review(review_id: str, _: str = Depends(require_admin)) -> dict[str, Any]:
|
||||||
if not ugc.delete_review(review_id):
|
if not ugc.delete_review(review_id):
|
||||||
raise HTTPException(404, "评价不存在")
|
raise HTTPException(404, "评价不存在")
|
||||||
return {"ok": True}
|
return {"ok": True, "soft": True, "archived": True}
|
||||||
|
|
||||||
|
|
||||||
@router.get("/gig-apps")
|
@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]:
|
async def del_gig_app(app_id: str, _: str = Depends(require_admin)) -> dict[str, Any]:
|
||||||
if not ugc.delete_gig_app(app_id):
|
if not ugc.delete_gig_app(app_id):
|
||||||
raise HTTPException(404, "申请不存在")
|
raise HTTPException(404, "申请不存在")
|
||||||
return {"ok": True}
|
return {"ok": True, "soft": True, "archived": True}
|
||||||
|
|
||||||
|
|
||||||
@router.get("/feedback")
|
@router.get("/feedback")
|
||||||
@ -134,7 +158,7 @@ async def get_feedback(
|
|||||||
async def del_feedback(fid: str, _: str = Depends(require_admin)) -> dict[str, Any]:
|
async def del_feedback(fid: str, _: str = Depends(require_admin)) -> dict[str, Any]:
|
||||||
if not ugc.delete_feedback(fid):
|
if not ugc.delete_feedback(fid):
|
||||||
raise HTTPException(404, "反馈不存在")
|
raise HTTPException(404, "反馈不存在")
|
||||||
return {"ok": True}
|
return {"ok": True, "soft": True, "archived": True}
|
||||||
|
|
||||||
|
|
||||||
class CatalogBody(BaseModel):
|
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 [],
|
"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
|
||||||
|
|||||||
@ -1,82 +1,64 @@
|
|||||||
"""游民社区 UGC 管理 — 直连 social.db(与 nomadro-social 同库)。
|
"""游民社区 UGC 管理 — PocketBase(与 social_svc 同库)。
|
||||||
|
|
||||||
默认路径可通过 SOCIAL_DB_PATH 覆盖;生产:/var/www/nomadro-data/social/social.db
|
历史 SQLite social.db 已停用;管理后台经本模块读写 PB collections。
|
||||||
只读写 messages / roster / cafe_reviews / gig_apps / feedback,不碰 remote-config catalogs。
|
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import os
|
import sys
|
||||||
import sqlite3
|
|
||||||
from contextlib import contextmanager
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, Iterator
|
from typing import Any
|
||||||
|
|
||||||
from ebook_svc.core.sqlite_util import connect as _connect
|
# ebook_svc may run without social_svc on PYTHONPATH
|
||||||
|
_SERVICES = Path(__file__).resolve().parents[2]
|
||||||
_DEFAULT = Path("/var/www/nomadro-data/social/social.db")
|
if str(_SERVICES) not in sys.path:
|
||||||
SOCIAL_DB_PATH = Path(os.getenv("SOCIAL_DB_PATH", str(_DEFAULT))).resolve()
|
sys.path.insert(0, str(_SERVICES))
|
||||||
|
|
||||||
|
|
||||||
@contextmanager
|
def _pb():
|
||||||
def _db(*, readonly: bool = False) -> Iterator[sqlite3.Connection]:
|
from social_svc import pb_data
|
||||||
SOCIAL_DB_PATH.parent.mkdir(parents=True, exist_ok=True)
|
|
||||||
if readonly and SOCIAL_DB_PATH.is_file():
|
return pb_data
|
||||||
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 available() -> dict[str, Any]:
|
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:
|
try:
|
||||||
writable = os.access(SOCIAL_DB_PATH, os.W_OK)
|
h = _pb().health()
|
||||||
except Exception:
|
|
||||||
writable = False
|
|
||||||
return {
|
return {
|
||||||
"ok": True,
|
"ok": bool(h.get("ok")),
|
||||||
"path": str(SOCIAL_DB_PATH),
|
"path": h.get("pb") or h.get("db") or "",
|
||||||
"exists": exists,
|
"exists": True,
|
||||||
"bytes": size,
|
"bytes": 0,
|
||||||
"writable": writable,
|
"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]:
|
def overview() -> dict[str, Any]:
|
||||||
|
try:
|
||||||
|
return _pb().admin_overview()
|
||||||
|
except Exception as e:
|
||||||
info = available()
|
info = available()
|
||||||
counts = {
|
return {
|
||||||
|
**info,
|
||||||
|
"counts": {
|
||||||
"messages": 0,
|
"messages": 0,
|
||||||
"roster": 0,
|
"roster": 0,
|
||||||
"reviews": 0,
|
"reviews": 0,
|
||||||
"gigApps": 0,
|
"gigApps": 0,
|
||||||
"feedback": 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(
|
def list_messages(
|
||||||
@ -86,242 +68,60 @@ def list_messages(
|
|||||||
limit: int = 100,
|
limit: int = 100,
|
||||||
offset: int = 0,
|
offset: int = 0,
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
limit = max(1, min(int(limit or 100), 500))
|
return _pb().admin_list_messages(
|
||||||
offset = max(0, int(offset or 0))
|
channel_id=channel_id, q=q, limit=limit, offset=offset
|
||||||
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}
|
|
||||||
|
|
||||||
|
|
||||||
def delete_message(message_id: str) -> bool:
|
def delete_message(message_id: str) -> bool:
|
||||||
with _db() as c:
|
return _pb().admin_delete_message(message_id)
|
||||||
cur = c.execute("DELETE FROM messages WHERE id=?", (message_id,))
|
|
||||||
return cur.rowcount > 0
|
|
||||||
|
|
||||||
|
|
||||||
def list_roster(*, q: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]:
|
def list_roster(*, q: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]:
|
||||||
limit = max(1, min(int(limit or 100), 500))
|
return _pb().admin_list_roster(q=q, limit=limit, offset=offset)
|
||||||
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}
|
|
||||||
|
|
||||||
|
|
||||||
def update_roster(guest_id: str, patch: dict[str, Any]) -> dict[str, Any] | None:
|
def update_roster(guest_id: str, patch: dict[str, Any]) -> dict[str, Any] | None:
|
||||||
with _db() as c:
|
return _pb().admin_update_roster(guest_id, patch)
|
||||||
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}
|
|
||||||
|
|
||||||
|
|
||||||
def delete_roster(guest_id: str) -> bool:
|
def delete_roster(guest_id: str) -> bool:
|
||||||
with _db() as c:
|
return _pb().admin_delete_roster(guest_id)
|
||||||
cur = c.execute("DELETE FROM roster WHERE guest_id=?", (guest_id,))
|
|
||||||
return cur.rowcount > 0
|
|
||||||
|
|
||||||
|
|
||||||
def list_reviews(*, cafe_id: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]:
|
def list_reviews(*, cafe_id: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]:
|
||||||
limit = max(1, min(int(limit or 100), 500))
|
return _pb().admin_list_cafe_reviews(cafe_id=cafe_id, limit=limit, offset=offset)
|
||||||
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}
|
|
||||||
|
|
||||||
|
|
||||||
def delete_review(review_id: str) -> bool:
|
def delete_review(review_id: str) -> bool:
|
||||||
with _db() as c:
|
return _pb().admin_delete_cafe_review(review_id)
|
||||||
cur = c.execute("DELETE FROM cafe_reviews WHERE id=?", (review_id,))
|
|
||||||
return cur.rowcount > 0
|
|
||||||
|
|
||||||
|
|
||||||
def list_gig_apps(*, gig_id: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]:
|
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))
|
return _pb().admin_list_gig_apps(gig_id=gig_id, limit=limit, offset=offset)
|
||||||
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}
|
|
||||||
|
|
||||||
|
|
||||||
def delete_gig_app(app_id: str) -> bool:
|
def delete_gig_app(app_id: str) -> bool:
|
||||||
with _db() as c:
|
return _pb().admin_delete_gig_app(app_id)
|
||||||
cur = c.execute("DELETE FROM gig_apps WHERE id=?", (app_id,))
|
|
||||||
return cur.rowcount > 0
|
|
||||||
|
|
||||||
|
|
||||||
def list_feedback(*, limit: int = 100, offset: int = 0) -> dict[str, Any]:
|
def list_feedback(*, limit: int = 100, offset: int = 0) -> dict[str, Any]:
|
||||||
limit = max(1, min(int(limit or 100), 500))
|
return _pb().admin_list_feedback(limit=limit, offset=offset)
|
||||||
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}
|
|
||||||
|
|
||||||
|
|
||||||
def delete_feedback(fid: str) -> bool:
|
def delete_feedback(fid: str) -> bool:
|
||||||
with _db() as c:
|
return _pb().admin_delete_feedback(fid)
|
||||||
cur = c.execute("DELETE FROM feedback WHERE id=?", (fid,))
|
|
||||||
return cur.rowcount > 0
|
|
||||||
|
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)
|
||||||
|
|||||||
22
apps/api/services/nomadro_pb/__init__.py
Normal file
22
apps/api/services/nomadro_pb/__init__.py
Normal file
@ -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",
|
||||||
|
]
|
||||||
197
apps/api/services/nomadro_pb/client.py
Normal file
197
apps/api/services/nomadro_pb/client.py
Normal file
@ -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
|
||||||
48
apps/api/services/nomadro_pb/config.py
Normal file
48
apps/api/services/nomadro_pb/config.py
Normal file
@ -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()
|
||||||
83
apps/api/services/nomadro_pb/ensure.py
Normal file
83
apps/api/services/nomadro_pb/ensure.py
Normal file
@ -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
|
||||||
534
apps/api/services/nomadro_pb/schemas.py
Normal file
534
apps/api/services/nomadro_pb/schemas.py
Normal file
@ -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,
|
||||||
|
]
|
||||||
529
apps/api/services/notify_svc/pb_store.py
Normal file
529
apps/api/services/notify_svc/pb_store.py
Normal file
@ -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"
|
||||||
File diff suppressed because it is too large
Load Diff
1587
apps/api/services/notify_svc/store_sqlite_legacy.py
Normal file
1587
apps/api/services/notify_svc/store_sqlite_legacy.py
Normal file
File diff suppressed because it is too large
Load Diff
@ -36,9 +36,8 @@ NOWPAYMENTS_API_KEY = os.getenv("NOWPAYMENTS_API_KEY", "")
|
|||||||
NOWPAYMENTS_IPN_SECRET = os.getenv("NOWPAYMENTS_IPN_SECRET", "")
|
NOWPAYMENTS_IPN_SECRET = os.getenv("NOWPAYMENTS_IPN_SECRET", "")
|
||||||
|
|
||||||
# PocketBase(支持 PB_ADMIN_* 或 POCKETBASE_*)
|
# PocketBase(支持 PB_ADMIN_* 或 POCKETBASE_*)
|
||||||
# 为了避免线上环境遗留 PB_URL=公网域名导致慢查询,默认强制优先本机。
|
# 默认本机 8090(.com/US 同机)。勿把 hackrobot.cn 写进代码默认。
|
||||||
# 本地无 PocketBase、需连线上 PB 时:在 .env.local 设置 PB_INTERNAL_URL=https://pocketbase.hackrobot.cn
|
# 中国机若要用自家 PB:部署 env 设 PB_URL / PB_INTERNAL_URL。
|
||||||
# (该变量优先级最高,且不改变下方对 PB_URL 的解析规则)
|
|
||||||
_pb_internal = os.getenv("PB_INTERNAL_URL") or os.getenv("POCKETBASE_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")
|
_pb_explicit = os.getenv("PB_URL") or os.getenv("POCKETBASE_URL")
|
||||||
if _pb_internal:
|
if _pb_internal:
|
||||||
|
|||||||
439
apps/api/services/social_svc/community_board.py
Normal file
439
apps/api/services/social_svc/community_board.py
Normal file
@ -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 "这周同城还比较安静,去发一条技能互换吧。",
|
||||||
|
}
|
||||||
@ -49,21 +49,34 @@ PHOTON_BASE_URL = os.getenv(
|
|||||||
PHOTON_TIMEOUT_SEC = float(os.getenv("PHOTON_TIMEOUT_SEC", "6"))
|
PHOTON_TIMEOUT_SEC = float(os.getenv("PHOTON_TIMEOUT_SEC", "6"))
|
||||||
H3_CITY_RES = int(os.getenv("H3_CITY_RES", "4"))
|
H3_CITY_RES = int(os.getenv("H3_CITY_RES", "4"))
|
||||||
H3_NEAR_RES = int(os.getenv("H3_NEAR_RES", "7"))
|
H3_NEAR_RES = int(os.getenv("H3_NEAR_RES", "7"))
|
||||||
# PocketBase for social_trips (same env family as pay_svc)
|
# PocketBase — .com/US defaults to same-box 8090; never hardcode hackrobot.cn
|
||||||
_pb_internal = os.getenv("PB_INTERNAL_URL") or os.getenv("POCKETBASE_INTERNAL_URL")
|
try:
|
||||||
_pb_explicit = os.getenv("PB_URL") or os.getenv("POCKETBASE_URL")
|
from nomadro_pb.config import ( # type: ignore
|
||||||
if _pb_internal:
|
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("/")
|
PB_URL = _pb_internal.rstrip("/")
|
||||||
elif _pb_explicit:
|
elif _pb_explicit:
|
||||||
PB_URL = _pb_explicit.rstrip("/")
|
PB_URL = _pb_explicit.rstrip("/")
|
||||||
else:
|
else:
|
||||||
PB_URL = "http://127.0.0.1:8090"
|
PB_URL = "http://127.0.0.1:8090"
|
||||||
PB_ADMIN_EMAIL = (
|
PB_ADMIN_EMAIL = (
|
||||||
os.getenv("PB_ADMIN_EMAIL") or os.getenv("POCKETBASE_EMAIL") or ""
|
os.getenv("PB_ADMIN_EMAIL") or os.getenv("POCKETBASE_EMAIL") or ""
|
||||||
)
|
)
|
||||||
PB_ADMIN_PASSWORD = (
|
PB_ADMIN_PASSWORD = (
|
||||||
os.getenv("PB_ADMIN_PASSWORD") or os.getenv("POCKETBASE_PASSWORD") or ""
|
os.getenv("PB_ADMIN_PASSWORD") or os.getenv("POCKETBASE_PASSWORD") or ""
|
||||||
)
|
)
|
||||||
SOCIAL_TRIPS_COLLECTION = os.getenv("SOCIAL_TRIPS_COLLECTION", "social_trips")
|
SOCIAL_TRIPS_COLLECTION = os.getenv("SOCIAL_TRIPS_COLLECTION", "social_trips")
|
||||||
SOCIAL_GEO_USE_PB = os.getenv("SOCIAL_GEO_USE_PB", "true").lower() in {
|
SOCIAL_GEO_USE_PB = os.getenv("SOCIAL_GEO_USE_PB", "true").lower() in {
|
||||||
"1",
|
"1",
|
||||||
|
|||||||
199
apps/api/services/social_svc/notify_bridge.py
Normal file
199
apps/api/services/social_svc/notify_bridge.py
Normal file
@ -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",
|
||||||
|
},
|
||||||
|
)
|
||||||
1436
apps/api/services/social_svc/pb_data.py
Normal file
1436
apps/api/services/social_svc/pb_data.py
Normal file
File diff suppressed because it is too large
Load Diff
@ -457,17 +457,18 @@ async def avatar_pose_challenge(
|
|||||||
challenge = verify_pose_challenge(front_raw, turn_raw)
|
challenge = verify_pose_challenge(front_raw, turn_raw)
|
||||||
if not challenge.ok:
|
if not challenge.ok:
|
||||||
raise ValueError(challenge.detail or "真人核验失败")
|
raise ValueError(challenge.detail or "真人核验失败")
|
||||||
|
# Live frames are audit-only — never purpose=avatar
|
||||||
front_up = upload_bytes(
|
front_up = upload_bytes(
|
||||||
front_raw,
|
front_raw,
|
||||||
filename=front.filename or "avatar-front.jpg",
|
filename=front.filename or "liveness-front.jpg",
|
||||||
content_type=front.content_type or "image/jpeg",
|
content_type=front.content_type or "image/jpeg",
|
||||||
purpose="avatar",
|
purpose="liveness-front",
|
||||||
guest_id=peer,
|
guest_id=peer,
|
||||||
max_size=max_avatar,
|
max_size=max_avatar,
|
||||||
)
|
)
|
||||||
turn_up = upload_bytes(
|
turn_up = upload_bytes(
|
||||||
turn_raw,
|
turn_raw,
|
||||||
filename=turn.filename or "avatar-turn.jpg",
|
filename=turn.filename or "liveness-turn.jpg",
|
||||||
content_type=turn.content_type or "image/jpeg",
|
content_type=turn.content_type or "image/jpeg",
|
||||||
purpose="liveness-turn",
|
purpose="liveness-turn",
|
||||||
guest_id=peer,
|
guest_id=peer,
|
||||||
@ -490,7 +491,6 @@ async def avatar_pose_challenge(
|
|||||||
video_size = video_up.size
|
video_size = video_up.size
|
||||||
audit = store.save_liveness_audit(
|
audit = store.save_liveness_audit(
|
||||||
peer,
|
peer,
|
||||||
avatar_url=front_up.url,
|
|
||||||
front_url=front_up.url,
|
front_url=front_up.url,
|
||||||
turn_url=turn_up.url,
|
turn_url=turn_up.url,
|
||||||
video_url=video_url,
|
video_url=video_url,
|
||||||
@ -503,29 +503,30 @@ async def avatar_pose_challenge(
|
|||||||
"has_video": bool(video_url),
|
"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:
|
try:
|
||||||
front_up, turn_up, video_url, video_size, challenge, audit = await run_in_threadpool(
|
front_up, turn_up, video_url, video_size, challenge, audit, roster = (
|
||||||
work
|
await run_in_threadpool(work)
|
||||||
)
|
)
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
raise HTTPException(status_code=503, detail=f"核验失败: {exc}") from 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 {
|
return {
|
||||||
"ok": True,
|
"ok": True,
|
||||||
"success": True,
|
"success": True,
|
||||||
"url": front_up.url,
|
"url": avatar_url,
|
||||||
"object_key": front_up.object_key,
|
"avatarUrl": avatar_url,
|
||||||
"size": front_up.size,
|
|
||||||
"content_type": front_up.content_type,
|
|
||||||
"storage": front_up.storage,
|
|
||||||
"livenessStatus": "verified",
|
"livenessStatus": "verified",
|
||||||
"faceOk": True,
|
"faceOk": True,
|
||||||
"videoUrl": video_url,
|
"videoUrl": video_url,
|
||||||
"videoSize": video_size,
|
"videoSize": video_size,
|
||||||
|
"frontUrl": front_up.url,
|
||||||
"turnUrl": turn_up.url,
|
"turnUrl": turn_up.url,
|
||||||
"auditId": audit.get("id"),
|
"auditId": audit.get("id"),
|
||||||
"challenge": {
|
"challenge": {
|
||||||
@ -756,6 +757,20 @@ def put_my_roster(
|
|||||||
)
|
)
|
||||||
except Exception as exc: # noqa: BLE001 — never block profile save
|
except Exception as exc: # noqa: BLE001 — never block profile save
|
||||||
onboarding = {"ok": False, "error": str(exc)[:160]}
|
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"}
|
out = {k: v for k, v in row.items() if k != "isFirstProfile"}
|
||||||
if onboarding is not None:
|
if onboarding is not None:
|
||||||
out["onboarding"] = onboarding
|
out["onboarding"] = onboarding
|
||||||
@ -823,6 +838,16 @@ async def live_join(
|
|||||||
pass
|
pass
|
||||||
# 附带实时通道 token,前端可订 live 频道
|
# 附带实时通道 token,前端可订 live 频道
|
||||||
payload["realtime"] = issue_connection_token(peer, payload["channelId"])
|
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
|
return payload
|
||||||
|
|
||||||
|
|
||||||
@ -861,3 +886,302 @@ async def live_leave(
|
|||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
return out
|
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}
|
||||||
|
|||||||
@ -145,7 +145,14 @@ def upload_bytes(
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
# Local fallback (dev / S3 off / S3 error)
|
# 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 = SOCIAL_UPLOAD_DIR / sub / Path(key).name
|
||||||
path.parent.mkdir(parents=True, exist_ok=True)
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
path.write_bytes(data)
|
path.write_bytes(data)
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
506
apps/api/services/work_svc/pb_store.py
Normal file
506
apps/api/services/work_svc/pb_store.py
Normal file
@ -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)
|
||||||
File diff suppressed because it is too large
Load Diff
1091
apps/api/services/work_svc/store_sqlite_legacy.py
Normal file
1091
apps/api/services/work_svc/store_sqlite_legacy.py
Normal file
File diff suppressed because it is too large
Load Diff
@ -10,6 +10,7 @@ import Orders from './pages/Orders'
|
|||||||
import Users from './pages/Users'
|
import Users from './pages/Users'
|
||||||
import Ntfy from './pages/Ntfy'
|
import Ntfy from './pages/Ntfy'
|
||||||
import Social from './pages/Social'
|
import Social from './pages/Social'
|
||||||
|
import SocialDetail from './pages/SocialDetail'
|
||||||
import Blog from './pages/Blog'
|
import Blog from './pages/Blog'
|
||||||
import LaneHub, { type LaneKey } from './pages/LaneHub'
|
import LaneHub, { type LaneKey } from './pages/LaneHub'
|
||||||
|
|
||||||
@ -59,7 +60,23 @@ export default function App() {
|
|||||||
>
|
>
|
||||||
<Route index element={<LaneHome />} />
|
<Route index element={<LaneHome />} />
|
||||||
<Route path="switches" element={<Switches />} />
|
<Route path="switches" element={<Switches />} />
|
||||||
<Route path="social" element={<Social />} />
|
<Route path="social" element={<Navigate to="overview" replace />} />
|
||||||
|
<Route path="social/overview" element={<Social />} />
|
||||||
|
<Route path="social/roster" element={<Social />} />
|
||||||
|
<Route path="social/messages" element={<Social />} />
|
||||||
|
<Route path="social/reviews" element={<Social />} />
|
||||||
|
<Route path="social/gigs" element={<Social />} />
|
||||||
|
<Route path="social/feedback" element={<Social />} />
|
||||||
|
<Route path="social/archives" element={<Social />} />
|
||||||
|
<Route path="social/catalog" element={<Social />} />
|
||||||
|
<Route path="social/roster/:id" element={<SocialDetail />} />
|
||||||
|
<Route path="social/messages/:id" element={<SocialDetail />} />
|
||||||
|
<Route path="social/reviews/:id" element={<SocialDetail />} />
|
||||||
|
<Route path="social/gigs/:id" element={<SocialDetail />} />
|
||||||
|
<Route path="social/gigApps/:id" element={<SocialDetail />} />
|
||||||
|
<Route path="social/feedback/:id" element={<SocialDetail />} />
|
||||||
|
<Route path="social/archives/:id" element={<SocialDetail />} />
|
||||||
|
<Route path="social/:section" element={<Social />} />
|
||||||
<Route path="blog" element={<Blog />} />
|
<Route path="blog" element={<Blog />} />
|
||||||
<Route path="events" element={<Events />} />
|
<Route path="events" element={<Events />} />
|
||||||
<Route path="orders" element={<Orders />} />
|
<Route path="orders" element={<Orders />} />
|
||||||
|
|||||||
@ -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 { NavLink, Outlet, useLocation, useNavigate, useParams } from 'react-router-dom'
|
||||||
import { clearToken } from '../api/client'
|
import { clearToken } from '../api/client'
|
||||||
import type { LaneKey } from '../pages/LaneHub'
|
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<LaneKey, { title: string; sub: string; mark: string }> = {
|
const LANE_META: Record<LaneKey, { title: string; sub: string; mark: string }> = {
|
||||||
cn: { title: '中文用户', sub: 'Chinese · 特殊对待', mark: '中' },
|
cn: { title: '中文用户', sub: 'Chinese · 特殊对待', mark: '中' },
|
||||||
@ -15,7 +25,24 @@ function laneNav(lane: LaneKey): NavItem[] {
|
|||||||
return [
|
return [
|
||||||
{ to: p, end: true, ico: '◈', label: '模块总览' },
|
{ to: p, end: true, ico: '◈', label: '模块总览' },
|
||||||
{ to: `${p}/switches`, 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}/blog`, ico: '📝', label: 'Nomad Blog' },
|
||||||
{ to: `${p}/events`, ico: '📊', label: '埋点' },
|
{ to: `${p}/events`, ico: '📊', label: '埋点' },
|
||||||
{ to: `${p}/orders`, ico: '🧾', label: '订单' },
|
{ to: `${p}/orders`, ico: '🧾', label: '订单' },
|
||||||
@ -25,26 +52,51 @@ function laneNav(lane: LaneKey): NavItem[] {
|
|||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
function titleFromPath(lane: LaneKey, pathname: string) {
|
function flattenLeaves(items: NavItem[]): NavLeaf[] {
|
||||||
const items = laneNav(lane)
|
const out: NavLeaf[] = []
|
||||||
const hit = items.find((n) => (n.end ? pathname === n.to : pathname.startsWith(n.to)))
|
for (const item of items) {
|
||||||
const mod = LANE_META[lane].title
|
if (item.kind === 'branch') out.push(...item.children)
|
||||||
return hit && !hit.end ? `${mod} · ${hit.label}` : mod
|
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() {
|
export default function WebLayout() {
|
||||||
const nav = useNavigate()
|
const nav = useNavigate()
|
||||||
const { pathname } = useLocation()
|
const { pathname } = useLocation()
|
||||||
const { lane: laneParam } = useParams()
|
const { lane: laneParam } = useParams()
|
||||||
const lane: LaneKey = laneParam === 'cn' ? 'cn' : 'intl'
|
const lane: LaneKey = laneParam === 'cn' ? 'cn' : 'intl'
|
||||||
const meta = LANE_META[lane]
|
const meta = LANE_META[lane]
|
||||||
|
const items = useMemo(() => laneNav(lane), [lane])
|
||||||
const [open, setOpen] = useState(false)
|
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(() => {
|
useEffect(() => {
|
||||||
setOpen(false)
|
setOpen(false)
|
||||||
}, [pathname])
|
}, [pathname])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (socialActive) setSocialOpen(true)
|
||||||
|
}, [socialActive])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
document.body.style.overflow = open ? 'hidden' : ''
|
document.body.style.overflow = open ? 'hidden' : ''
|
||||||
return () => {
|
return () => {
|
||||||
@ -57,6 +109,15 @@ export default function WebLayout() {
|
|||||||
nav('/login')
|
nav('/login')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function toggleSocial() {
|
||||||
|
if (!socialBranch) return
|
||||||
|
setSocialOpen((v) => {
|
||||||
|
const next = !v
|
||||||
|
if (next && !socialActive) nav(socialBranch.defaultTo)
|
||||||
|
return next
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={`com-shell com-shell--${lane}${open ? ' com-shell--nav-open' : ''}`}>
|
<div className={`com-shell com-shell--${lane}${open ? ' com-shell--nav-open' : ''}`}>
|
||||||
<header className="com-topbar">
|
<header className="com-topbar">
|
||||||
@ -101,8 +162,53 @@ export default function WebLayout() {
|
|||||||
切换模块 · 中文 / 国际
|
切换模块 · 中文 / 国际
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<nav className="com-nav">
|
<nav className="com-nav" aria-label="后台导航">
|
||||||
{laneNav(lane).map((item) => (
|
{items.map((item) => {
|
||||||
|
if (item.kind === 'branch') {
|
||||||
|
const branchOpen = item.id === 'social' ? socialOpen : false
|
||||||
|
const active = isBranchActive(item, pathname)
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={item.id}
|
||||||
|
className={`com-nav-branch${branchOpen ? ' is-open' : ''}${active ? ' is-active' : ''}`}
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="com-nav-parent"
|
||||||
|
aria-expanded={branchOpen}
|
||||||
|
onClick={toggleSocial}
|
||||||
|
>
|
||||||
|
<span className="com-nav-ico" aria-hidden>
|
||||||
|
{item.ico}
|
||||||
|
</span>
|
||||||
|
<span className="com-nav-parent-label">{item.label}</span>
|
||||||
|
<span className="com-nav-caret" aria-hidden>
|
||||||
|
{branchOpen ? '▾' : '▸'}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
{branchOpen ? (
|
||||||
|
<div className="com-nav-sub" role="group" aria-label={`${item.label}子菜单`}>
|
||||||
|
{item.children.map((child) => (
|
||||||
|
<NavLink
|
||||||
|
key={child.to}
|
||||||
|
to={child.to}
|
||||||
|
end={child.end}
|
||||||
|
className={({ isActive }) =>
|
||||||
|
`com-nav-sublink${isActive ? ' active' : ''}`
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<span className="com-nav-ico" aria-hidden>
|
||||||
|
{child.ico}
|
||||||
|
</span>
|
||||||
|
{child.label}
|
||||||
|
</NavLink>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return (
|
||||||
<NavLink
|
<NavLink
|
||||||
key={item.to}
|
key={item.to}
|
||||||
to={item.to}
|
to={item.to}
|
||||||
@ -114,7 +220,8 @@ export default function WebLayout() {
|
|||||||
</span>
|
</span>
|
||||||
{item.label}
|
{item.label}
|
||||||
</NavLink>
|
</NavLink>
|
||||||
))}
|
)
|
||||||
|
})}
|
||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
<button type="button" className="com-logout" onClick={logout}>
|
<button type="button" className="com-logout" onClick={logout}>
|
||||||
|
|||||||
@ -144,7 +144,7 @@ export default function LaneHub({ lane }: { lane: LaneKey }) {
|
|||||||
|
|
||||||
const tools = [
|
const tools = [
|
||||||
{ to: `/${lane}/switches`, ico: '⏻', title: '动态开关', desc: '页面 / flag / VIP 入口' },
|
{ to: `/${lane}/switches`, ico: '⏻', title: '动态开关', desc: '页面 / flag / VIP 入口' },
|
||||||
{ to: `/${lane}/social`, ico: '💕', title: '游民社区', desc: '聊天 / 花名册 / 反馈审核' },
|
{ to: `/${lane}/social/overview`, ico: '💕', title: '游民社区', desc: '概览 / 花名册 / 聊天 / 存档' },
|
||||||
{ to: `/${lane}/blog`, ico: '📝', title: 'Nomad Blog', desc: '文章显隐 / AdSense / 置顶' },
|
{ to: `/${lane}/blog`, ico: '📝', title: 'Nomad Blog', desc: '文章显隐 / AdSense / 置顶' },
|
||||||
{ to: `/${lane}/events`, ico: '📊', title: '埋点', desc: '本轨相关行为回放' },
|
{ to: `/${lane}/events`, ico: '📊', title: '埋点', desc: '本轨相关行为回放' },
|
||||||
{ to: `/${lane}/orders`, ico: '🧾', title: '订单', desc: '支付与发货' },
|
{ to: `/${lane}/orders`, ico: '🧾', title: '订单', desc: '支付与发货' },
|
||||||
|
|||||||
@ -1,74 +1,192 @@
|
|||||||
/**
|
/**
|
||||||
* 游民社区 UGC — 直连 social.db(与 nomadro-social 同库)
|
* 游民社区 · 列表页(无页内 Tab;侧栏二级菜单切入)
|
||||||
* overview / 聊天 / 花名册 / 评价 / 接单申请 / 反馈 / 目录
|
* 整行可进详情;分页;软删除进存档。
|
||||||
*/
|
*/
|
||||||
import { useCallback, useEffect, useState } from 'react'
|
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||||
|
import { Link, Navigate, useLocation, useNavigate, useParams } from 'react-router-dom'
|
||||||
import { api } from '../api/client'
|
import { api } from '../api/client'
|
||||||
|
import {
|
||||||
|
SECTIONS,
|
||||||
|
SECTION_DESC,
|
||||||
|
SECTION_TITLE,
|
||||||
|
type SectionKey,
|
||||||
|
fmtTime,
|
||||||
|
pickId,
|
||||||
|
short,
|
||||||
|
} from './socialMeta'
|
||||||
|
|
||||||
|
type Stats = {
|
||||||
|
ok?: boolean
|
||||||
|
counts?: Record<string, number>
|
||||||
|
softDeleted?: Record<string, number>
|
||||||
|
activeRoster?: number
|
||||||
|
byCity?: Array<{ name: string; value: number }>
|
||||||
|
rosterByDay?: Array<{ date: string; value: number }>
|
||||||
|
}
|
||||||
|
|
||||||
type Overview = {
|
type Overview = {
|
||||||
path?: string
|
path?: string
|
||||||
exists?: boolean
|
exists?: boolean
|
||||||
writable?: boolean
|
writable?: boolean
|
||||||
bytes?: number
|
backend?: string
|
||||||
counts?: {
|
counts?: Record<string, number>
|
||||||
messages?: number
|
|
||||||
roster?: number
|
|
||||||
reviews?: number
|
|
||||||
gigApps?: number
|
|
||||||
gig_apps?: number
|
|
||||||
feedback?: number
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type TabKey = 'messages' | 'roster' | 'reviews' | 'gigs' | 'feedback' | 'catalog'
|
const PAGE = 40
|
||||||
|
|
||||||
const TABS: Array<{ key: TabKey; label: string }> = [
|
function BarChart({
|
||||||
{ key: 'messages', label: '聊天' },
|
data,
|
||||||
{ key: 'roster', label: '花名册' },
|
color = '#f59e0b',
|
||||||
{ key: 'reviews', label: '咖啡馆评价' },
|
}: {
|
||||||
{ key: 'gigs', label: '接单申请' },
|
data: Array<{ name: string; value: number }>
|
||||||
{ key: 'feedback', label: '反馈' },
|
color?: string
|
||||||
{ key: 'catalog', label: '目录配置' },
|
}) {
|
||||||
]
|
const max = Math.max(1, ...data.map((d) => d.value))
|
||||||
|
if (!data.length) return <p className="com-muted">暂无分布数据</p>
|
||||||
function fmtTime(v: unknown) {
|
return (
|
||||||
if (!v) return '—'
|
<div className="com-bars" role="img" aria-label="分布图">
|
||||||
const s = String(v)
|
{data.map((d) => (
|
||||||
if (/^\d+$/.test(s)) {
|
<div className="com-bar-row" key={d.name}>
|
||||||
const n = Number(s)
|
<span className="com-bar-label" title={d.name}>
|
||||||
return new Date(n < 1e12 ? n * 1000 : n).toLocaleString('zh-CN', { hour12: false })
|
{short(d.name, 10)}
|
||||||
}
|
</span>
|
||||||
return s.slice(0, 19).replace('T', ' ')
|
<div className="com-bar-track">
|
||||||
|
<i style={{ width: `${(d.value / max) * 100}%`, background: color }} />
|
||||||
|
</div>
|
||||||
|
<strong className="com-bar-val">{d.value}</strong>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function short(v: unknown, n = 48) {
|
function Sparkline({ data }: { data: Array<{ date: string; value: number }> }) {
|
||||||
const s = String(v ?? '')
|
if (!data.length) return <p className="com-muted">暂无时间序列</p>
|
||||||
return s.length <= n ? s || '—' : `${s.slice(0, n)}…`
|
const max = Math.max(1, ...data.map((d) => d.value))
|
||||||
|
const w = 320
|
||||||
|
const h = 72
|
||||||
|
const pts = data
|
||||||
|
.map((d, i) => {
|
||||||
|
const x = data.length === 1 ? w / 2 : (i / (data.length - 1)) * w
|
||||||
|
const y = h - (d.value / max) * (h - 8) - 4
|
||||||
|
return `${x},${y}`
|
||||||
|
})
|
||||||
|
.join(' ')
|
||||||
|
return (
|
||||||
|
<svg className="com-spark" viewBox={`0 0 ${w} ${h}`} width="100%" height={h} aria-hidden>
|
||||||
|
<polyline
|
||||||
|
fill="none"
|
||||||
|
stroke="#f59e0b"
|
||||||
|
strokeWidth="2.5"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
points={pts}
|
||||||
|
/>
|
||||||
|
{data.map((d, i) => {
|
||||||
|
const x = data.length === 1 ? w / 2 : (i / (data.length - 1)) * w
|
||||||
|
const y = h - (d.value / max) * (h - 8) - 4
|
||||||
|
return <circle key={d.date} cx={x} cy={y} r="2.5" fill="#fbbf24" />
|
||||||
|
})}
|
||||||
|
</svg>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function Donut({
|
||||||
|
segments,
|
||||||
|
}: {
|
||||||
|
segments: Array<{ label: string; value: number; color: string }>
|
||||||
|
}) {
|
||||||
|
const total = segments.reduce((s, x) => s + x.value, 0) || 1
|
||||||
|
let acc = 0
|
||||||
|
const r = 42
|
||||||
|
const c = 2 * Math.PI * r
|
||||||
|
return (
|
||||||
|
<div className="com-donut-wrap">
|
||||||
|
<svg viewBox="0 0 120 120" width="120" height="120" aria-hidden>
|
||||||
|
<circle cx="60" cy="60" r={r} fill="none" stroke="rgba(255,255,255,0.06)" strokeWidth="14" />
|
||||||
|
{segments.map((seg) => {
|
||||||
|
const len = (seg.value / total) * c
|
||||||
|
const dash = `${len} ${c - len}`
|
||||||
|
const rot = (acc / total) * 360 - 90
|
||||||
|
acc += seg.value
|
||||||
|
return (
|
||||||
|
<circle
|
||||||
|
key={seg.label}
|
||||||
|
cx="60"
|
||||||
|
cy="60"
|
||||||
|
r={r}
|
||||||
|
fill="none"
|
||||||
|
stroke={seg.color}
|
||||||
|
strokeWidth="14"
|
||||||
|
strokeDasharray={dash}
|
||||||
|
strokeLinecap="butt"
|
||||||
|
transform={`rotate(${rot} 60 60)`}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
<text x="60" y="58" textAnchor="middle" fill="#f8fafc" fontSize="16" fontWeight="700">
|
||||||
|
{total}
|
||||||
|
</text>
|
||||||
|
<text x="60" y="74" textAnchor="middle" fill="#94a3b8" fontSize="9">
|
||||||
|
records
|
||||||
|
</text>
|
||||||
|
</svg>
|
||||||
|
<ul className="com-donut-legend">
|
||||||
|
{segments.map((s) => (
|
||||||
|
<li key={s.label}>
|
||||||
|
<i style={{ background: s.color }} />
|
||||||
|
{s.label} · {s.value}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function Social() {
|
export default function Social() {
|
||||||
const [tab, setTab] = useState<TabKey>('messages')
|
const { lane = 'intl', section: sectionParam } = useParams()
|
||||||
|
const { pathname } = useLocation()
|
||||||
|
const navigate = useNavigate()
|
||||||
|
const base = `/${lane}/social`
|
||||||
|
const fromPath = pathname.split('/').filter(Boolean)[2] || 'overview'
|
||||||
|
const sectionRaw = (sectionParam || fromPath || 'overview') as SectionKey
|
||||||
|
const sectionValid = SECTIONS.includes(sectionRaw)
|
||||||
|
const section: SectionKey = sectionValid ? sectionRaw : 'overview'
|
||||||
|
|
||||||
const [overview, setOverview] = useState<Overview | null>(null)
|
const [overview, setOverview] = useState<Overview | null>(null)
|
||||||
|
const [stats, setStats] = useState<Stats | null>(null)
|
||||||
const [items, setItems] = useState<Record<string, unknown>[]>([])
|
const [items, setItems] = useState<Record<string, unknown>[]>([])
|
||||||
const [total, setTotal] = useState(0)
|
const [total, setTotal] = useState(0)
|
||||||
const [q, setQ] = useState('')
|
const [q, setQ] = useState('')
|
||||||
|
const [qDraft, setQDraft] = useState('')
|
||||||
|
const [offset, setOffset] = useState(0)
|
||||||
const [loading, setLoading] = useState(false)
|
const [loading, setLoading] = useState(false)
|
||||||
const [busyId, setBusyId] = useState('')
|
const [busyId, setBusyId] = useState('')
|
||||||
const [busy, setBusy] = useState(false)
|
const [busy, setBusy] = useState(false)
|
||||||
const [err, setErr] = useState('')
|
const [err, setErr] = useState('')
|
||||||
const [msg, setMsg] = useState('')
|
const [msg, setMsg] = useState('')
|
||||||
const [catalogJson, setCatalogJson] = useState('')
|
const [catalogJson, setCatalogJson] = useState('')
|
||||||
|
const [editRoster, setEditRoster] = useState<Record<string, unknown> | null>(null)
|
||||||
|
|
||||||
const loadOverview = useCallback(async () => {
|
const loadOverview = useCallback(async () => {
|
||||||
const data = await api<Overview>('/api/admin/social/ugc/overview')
|
const data = await api<Overview>('/api/admin/social/ugc/overview')
|
||||||
setOverview(data)
|
setOverview(data)
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
|
const loadStats = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
const data = await api<Stats>('/api/admin/social/ugc/stats')
|
||||||
|
setStats(data)
|
||||||
|
} catch {
|
||||||
|
setStats(null)
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
const loadList = useCallback(async () => {
|
const loadList = useCallback(async () => {
|
||||||
|
if (section === 'overview') return
|
||||||
setLoading(true)
|
setLoading(true)
|
||||||
setErr('')
|
setErr('')
|
||||||
try {
|
try {
|
||||||
if (tab === 'catalog') {
|
if (section === 'catalog') {
|
||||||
const data = await api<{ catalogs?: Record<string, unknown> }>(
|
const data = await api<{ catalogs?: Record<string, unknown> }>(
|
||||||
'/api/admin/social/ugc/catalog',
|
'/api/admin/social/ugc/catalog',
|
||||||
)
|
)
|
||||||
@ -77,16 +195,22 @@ export default function Social() {
|
|||||||
setTotal(0)
|
setTotal(0)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
const qs = new URLSearchParams()
|
||||||
|
qs.set('limit', String(PAGE))
|
||||||
|
qs.set('offset', String(offset))
|
||||||
|
if (q.trim() && (section === 'messages' || section === 'roster')) qs.set('q', q.trim())
|
||||||
const path =
|
const path =
|
||||||
tab === 'messages'
|
section === 'messages'
|
||||||
? `/api/admin/social/ugc/messages?limit=80&q=${encodeURIComponent(q)}`
|
? `/api/admin/social/ugc/messages?${qs}`
|
||||||
: tab === 'roster'
|
: section === 'roster'
|
||||||
? `/api/admin/social/ugc/roster?limit=80&q=${encodeURIComponent(q)}`
|
? `/api/admin/social/ugc/roster?${qs}`
|
||||||
: tab === 'reviews'
|
: section === 'reviews'
|
||||||
? `/api/admin/social/ugc/reviews?limit=80`
|
? `/api/admin/social/ugc/reviews?${qs}`
|
||||||
: tab === 'gigs'
|
: section === 'gigs'
|
||||||
? `/api/admin/social/ugc/gig-apps?limit=80`
|
? `/api/admin/social/ugc/gig-apps?${qs}`
|
||||||
: `/api/admin/social/ugc/feedback?limit=80`
|
: section === 'archives'
|
||||||
|
? `/api/admin/social/ugc/archives?${qs}`
|
||||||
|
: `/api/admin/social/ugc/feedback?${qs}`
|
||||||
const data = await api<{ items?: Record<string, unknown>[]; total?: number }>(path)
|
const data = await api<{ items?: Record<string, unknown>[]; total?: number }>(path)
|
||||||
setItems(Array.isArray(data.items) ? data.items : [])
|
setItems(Array.isArray(data.items) ? data.items : [])
|
||||||
setTotal(Number(data.total || 0))
|
setTotal(Number(data.total || 0))
|
||||||
@ -97,36 +221,73 @@ export default function Social() {
|
|||||||
} finally {
|
} finally {
|
||||||
setLoading(false)
|
setLoading(false)
|
||||||
}
|
}
|
||||||
}, [tab, q])
|
}, [section, q, offset])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setQ('')
|
||||||
|
setQDraft('')
|
||||||
|
setOffset(0)
|
||||||
|
setMsg('')
|
||||||
|
setErr('')
|
||||||
|
setEditRoster(null)
|
||||||
|
}, [section])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
loadOverview().catch((e: Error) => setErr(e.message || '概览失败'))
|
loadOverview().catch((e: Error) => setErr(e.message || '概览失败'))
|
||||||
}, [loadOverview])
|
loadStats().catch(() => undefined)
|
||||||
|
}, [loadOverview, loadStats])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
void loadList()
|
void loadList()
|
||||||
}, [loadList])
|
}, [loadList])
|
||||||
|
|
||||||
async function removeRow(kind: TabKey, id: string) {
|
const donutSegs = useMemo(() => {
|
||||||
if (kind === 'catalog' || !id || !window.confirm(`确认删除这条 ${kind} 记录?不可恢复。`)) return
|
const c = stats?.counts || overview?.counts || {}
|
||||||
|
return [
|
||||||
|
{ label: '花名册', value: Number(c.roster || 0), color: '#f59e0b' },
|
||||||
|
{ label: '聊天', value: Number(c.messages || 0), color: '#4ecdc4' },
|
||||||
|
{ label: '评价', value: Number(c.reviews || 0), color: '#a78bfa' },
|
||||||
|
{ label: '接单', value: Number(c.gigApps || c.gig_apps || 0), color: '#fb7185' },
|
||||||
|
{ label: '反馈', value: Number(c.feedback || 0), color: '#38bdf8' },
|
||||||
|
].filter((x) => x.value > 0)
|
||||||
|
}, [stats, overview])
|
||||||
|
|
||||||
|
function detailPath(row: Record<string, unknown>) {
|
||||||
|
const id = pickId(row, section)
|
||||||
|
if (!id || section === 'overview' || section === 'catalog') return ''
|
||||||
|
if (section === 'gigs') return `${base}/gigs/${encodeURIComponent(id)}`
|
||||||
|
return `${base}/${section}/${encodeURIComponent(id)}`
|
||||||
|
}
|
||||||
|
|
||||||
|
function openDetail(row: Record<string, unknown>) {
|
||||||
|
const href = detailPath(row)
|
||||||
|
if (href) navigate(href)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function removeRow(row: Record<string, unknown>) {
|
||||||
|
if (section === 'catalog' || section === 'archives' || section === 'overview') return
|
||||||
|
const id = pickId(row, section)
|
||||||
|
if (!id) return
|
||||||
|
if (!window.confirm(`软删除这条记录?会写入 social_archives,不会物理抹除。`)) return
|
||||||
setBusyId(id)
|
setBusyId(id)
|
||||||
setMsg('')
|
setMsg('')
|
||||||
setErr('')
|
setErr('')
|
||||||
try {
|
try {
|
||||||
const path =
|
const path =
|
||||||
kind === 'messages'
|
section === 'messages'
|
||||||
? `/api/admin/social/ugc/messages/${encodeURIComponent(id)}`
|
? `/api/admin/social/ugc/messages/${encodeURIComponent(id)}`
|
||||||
: kind === 'roster'
|
: section === 'roster'
|
||||||
? `/api/admin/social/ugc/roster/${encodeURIComponent(id)}`
|
? `/api/admin/social/ugc/roster/${encodeURIComponent(id)}`
|
||||||
: kind === 'reviews'
|
: section === 'reviews'
|
||||||
? `/api/admin/social/ugc/reviews/${encodeURIComponent(id)}`
|
? `/api/admin/social/ugc/reviews/${encodeURIComponent(id)}`
|
||||||
: kind === 'gigs'
|
: section === 'gigs'
|
||||||
? `/api/admin/social/ugc/gig-apps/${encodeURIComponent(id)}`
|
? `/api/admin/social/ugc/gig-apps/${encodeURIComponent(id)}`
|
||||||
: `/api/admin/social/ugc/feedback/${encodeURIComponent(id)}`
|
: `/api/admin/social/ugc/feedback/${encodeURIComponent(id)}`
|
||||||
await api(path, { method: 'DELETE' })
|
await api(path, { method: 'DELETE' })
|
||||||
setMsg('已删除')
|
setMsg('已软删除并写入存档')
|
||||||
await loadList()
|
await loadList()
|
||||||
await loadOverview().catch(() => undefined)
|
await loadOverview().catch(() => undefined)
|
||||||
|
await loadStats().catch(() => undefined)
|
||||||
} catch (e: unknown) {
|
} catch (e: unknown) {
|
||||||
setErr(e instanceof Error ? e.message : '删除失败')
|
setErr(e instanceof Error ? e.message : '删除失败')
|
||||||
} finally {
|
} finally {
|
||||||
@ -134,6 +295,35 @@ export default function Social() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function saveRoster() {
|
||||||
|
if (!editRoster?.guestId && !editRoster?.guest_id) return
|
||||||
|
const gid = String(editRoster.guestId || editRoster.guest_id)
|
||||||
|
setBusy(true)
|
||||||
|
setErr('')
|
||||||
|
try {
|
||||||
|
await api(`/api/admin/social/ugc/roster/${encodeURIComponent(gid)}`, {
|
||||||
|
method: 'PUT',
|
||||||
|
body: JSON.stringify({
|
||||||
|
name: editRoster.name,
|
||||||
|
title: editRoster.title,
|
||||||
|
city: editRoster.city,
|
||||||
|
phone: editRoster.phone,
|
||||||
|
linktree: editRoster.linktree,
|
||||||
|
skills: editRoster.skills,
|
||||||
|
bio: editRoster.bio,
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
setMsg('已保存')
|
||||||
|
setEditRoster(null)
|
||||||
|
await loadList()
|
||||||
|
await loadStats().catch(() => undefined)
|
||||||
|
} catch (e: unknown) {
|
||||||
|
setErr(e instanceof Error ? e.message : '保存失败')
|
||||||
|
} finally {
|
||||||
|
setBusy(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function saveCatalog() {
|
async function saveCatalog() {
|
||||||
setBusy(true)
|
setBusy(true)
|
||||||
setMsg('')
|
setMsg('')
|
||||||
@ -144,7 +334,7 @@ export default function Social() {
|
|||||||
method: 'PUT',
|
method: 'PUT',
|
||||||
body: JSON.stringify(parsed),
|
body: JSON.stringify(parsed),
|
||||||
})
|
})
|
||||||
setMsg('目录已保存(remote-config 深合并)')
|
setMsg('目录已保存')
|
||||||
await loadList()
|
await loadList()
|
||||||
} catch (e: unknown) {
|
} catch (e: unknown) {
|
||||||
setErr(e instanceof Error ? e.message : '目录保存失败(检查 JSON)')
|
setErr(e instanceof Error ? e.message : '目录保存失败(检查 JSON)')
|
||||||
@ -153,34 +343,45 @@ export default function Social() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const counts = overview?.counts || {}
|
const counts = stats?.counts || overview?.counts || {}
|
||||||
|
const pageFrom = total === 0 ? 0 : offset + 1
|
||||||
|
const pageTo = Math.min(offset + items.length, total)
|
||||||
|
const canPrev = offset > 0
|
||||||
|
const canNext = offset + PAGE < total
|
||||||
|
|
||||||
|
if (!sectionValid) {
|
||||||
|
return <Navigate to={`${base}/overview`} replace />
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="com-page">
|
<div className="com-page">
|
||||||
<header className="com-page-head com-page-head-row">
|
<header className="com-page-head com-page-head-row">
|
||||||
<div>
|
<div>
|
||||||
<h1>游民社区</h1>
|
<h1>{SECTION_TITLE[section]}</h1>
|
||||||
<p>
|
<p>{SECTION_DESC[section]}</p>
|
||||||
管理 <code>/social</code> UGC:聊天、花名册、评价、接单申请、反馈与目录。库文件与{' '}
|
{section === 'overview' ? (
|
||||||
<code>nomadro-social</code> 同源。
|
|
||||||
</p>
|
|
||||||
<div className="com-chip-row">
|
<div className="com-chip-row">
|
||||||
<span className={`com-chip${overview?.exists ? ' com-chip-ok' : ''}`}>
|
<span className={`com-chip${overview?.exists ? ' com-chip-ok' : ''}`}>
|
||||||
DB {overview?.exists ? '在线' : '缺失'}
|
{overview?.backend || 'db'} {overview?.exists === false ? '缺失' : '在线'}
|
||||||
</span>
|
</span>
|
||||||
{overview?.writable === false ? <span className="com-chip">只读</span> : null}
|
<span className="com-chip">活跃花名册 {stats?.activeRoster ?? '—'}</span>
|
||||||
{overview?.path ? (
|
<span className="com-chip">存档 {counts.archives ?? '—'}</span>
|
||||||
<span className="com-chip" title={overview.path}>
|
|
||||||
{short(overview.path, 36)}
|
|
||||||
</span>
|
|
||||||
) : null}
|
|
||||||
</div>
|
</div>
|
||||||
|
) : section !== 'catalog' ? (
|
||||||
|
<div className="com-chip-row">
|
||||||
|
<span className="com-chip">共 {total} 条</span>
|
||||||
|
<span className="com-chip">
|
||||||
|
本页 {pageFrom}-{pageTo}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className="com-btn com-btn-ghost"
|
className="com-btn com-btn-ghost"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
void loadOverview()
|
void loadOverview()
|
||||||
|
void loadStats()
|
||||||
void loadList()
|
void loadList()
|
||||||
}}
|
}}
|
||||||
disabled={loading}
|
disabled={loading}
|
||||||
@ -192,193 +393,337 @@ export default function Social() {
|
|||||||
{msg ? <div className="com-toast com-toast-ok">{msg}</div> : null}
|
{msg ? <div className="com-toast com-toast-ok">{msg}</div> : null}
|
||||||
{err ? <div className="com-toast com-toast-err">{err}</div> : null}
|
{err ? <div className="com-toast com-toast-err">{err}</div> : null}
|
||||||
|
|
||||||
|
{section === 'overview' ? (
|
||||||
|
<>
|
||||||
|
<section className="com-viz-grid" aria-label="数据可视化">
|
||||||
|
<article className="com-panel com-viz-card">
|
||||||
|
<h2>内容构成</h2>
|
||||||
|
<Donut
|
||||||
|
segments={
|
||||||
|
donutSegs.length
|
||||||
|
? donutSegs
|
||||||
|
: [{ label: '空', value: 1, color: 'rgba(255,255,255,0.12)' }]
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</article>
|
||||||
|
<article className="com-panel com-viz-card">
|
||||||
|
<h2>城市分布(花名册)</h2>
|
||||||
|
<BarChart data={stats?.byCity || []} />
|
||||||
|
</article>
|
||||||
|
<article className="com-panel com-viz-card">
|
||||||
|
<h2>花名册活跃(按日)</h2>
|
||||||
|
<Sparkline data={stats?.rosterByDay || []} />
|
||||||
|
</article>
|
||||||
|
<article className="com-panel com-viz-card">
|
||||||
|
<h2>软删除计数</h2>
|
||||||
|
<div className="com-stat-grid com-stat-grid-compact">
|
||||||
|
{(['roster', 'messages', 'reviews', 'gigApps', 'feedback'] as const).map((k) => (
|
||||||
|
<div className="com-stat" key={k}>
|
||||||
|
<span className="com-stat-label">{k}</span>
|
||||||
|
<strong>{stats?.softDeleted?.[k] ?? 0}</strong>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
</section>
|
||||||
<div className="com-stat-grid">
|
<div className="com-stat-grid">
|
||||||
{(
|
{(
|
||||||
[
|
[
|
||||||
['聊天', counts.messages],
|
['花名册', counts.roster, 'roster'],
|
||||||
['花名册', counts.roster],
|
['聊天', counts.messages, 'messages'],
|
||||||
['评价', counts.reviews],
|
['评价', counts.reviews, 'reviews'],
|
||||||
['接单', counts.gigApps ?? counts.gig_apps],
|
['接单', counts.gigApps ?? counts.gig_apps, 'gigs'],
|
||||||
['反馈', counts.feedback],
|
['反馈', counts.feedback, 'feedback'],
|
||||||
|
['存档', counts.archives, 'archives'],
|
||||||
] as const
|
] as const
|
||||||
).map(([label, n]) => (
|
).map(([label, n, key]) => (
|
||||||
<article key={label} className="com-stat">
|
<button
|
||||||
|
key={label}
|
||||||
|
type="button"
|
||||||
|
className="com-stat com-stat-link"
|
||||||
|
onClick={() => navigate(`${base}/${key}`)}
|
||||||
|
>
|
||||||
<span className="com-stat-label">{label}</span>
|
<span className="com-stat-label">{label}</span>
|
||||||
<strong>{n ?? '—'}</strong>
|
<strong>{n ?? '—'}</strong>
|
||||||
</article>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<nav className="com-tabs" aria-label="UGC 分类">
|
|
||||||
{TABS.map((t) => (
|
|
||||||
<button
|
|
||||||
key={t.key}
|
|
||||||
type="button"
|
|
||||||
className={`com-tab${tab === t.key ? ' is-on' : ''}`}
|
|
||||||
onClick={() => {
|
|
||||||
setTab(t.key)
|
|
||||||
setQ('')
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{t.label}
|
|
||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
</nav>
|
</div>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
|
||||||
{tab === 'catalog' ? (
|
{section === 'catalog' ? (
|
||||||
<section className="com-panel">
|
<section className="com-panel">
|
||||||
<div className="com-panel-head">
|
<div className="com-panel-head">
|
||||||
<div>
|
<div>
|
||||||
<h2>socialCatalogs</h2>
|
<h2>socialCatalogs</h2>
|
||||||
<p>meetups / gigs / cafes / roster / ebooks / videos(JSON)</p>
|
<p>meetups / gigs / cafes / roster / ebooks / videos</p>
|
||||||
</div>
|
</div>
|
||||||
<button
|
<button type="button" className="com-btn" disabled={busy} onClick={() => void saveCatalog()}>
|
||||||
type="button"
|
|
||||||
className="com-btn"
|
|
||||||
disabled={busy}
|
|
||||||
onClick={() => void saveCatalog()}
|
|
||||||
>
|
|
||||||
{busy ? '保存中…' : '保存目录'}
|
{busy ? '保存中…' : '保存目录'}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<textarea
|
<textarea
|
||||||
className="com-pre"
|
className="com-pre"
|
||||||
style={{ width: '100%', minHeight: 360, resize: 'vertical', fontFamily: 'ui-monospace, monospace' }}
|
style={{ width: '100%', minHeight: 420, resize: 'vertical', fontFamily: 'ui-monospace, monospace' }}
|
||||||
value={catalogJson}
|
value={catalogJson}
|
||||||
onChange={(e) => setCatalogJson(e.target.value)}
|
onChange={(e) => setCatalogJson(e.target.value)}
|
||||||
spellCheck={false}
|
spellCheck={false}
|
||||||
/>
|
/>
|
||||||
</section>
|
</section>
|
||||||
) : (
|
) : null}
|
||||||
|
|
||||||
|
{section !== 'overview' && section !== 'catalog' ? (
|
||||||
<>
|
<>
|
||||||
{(tab === 'messages' || tab === 'roster') && (
|
|
||||||
<div className="com-toolbar">
|
<div className="com-toolbar">
|
||||||
|
{(section === 'messages' || section === 'roster') && (
|
||||||
|
<>
|
||||||
<input
|
<input
|
||||||
className="com-input"
|
className="com-input"
|
||||||
placeholder={tab === 'messages' ? '搜正文 / 昵称' : '搜名字 / 城市 / 技能'}
|
placeholder={section === 'messages' ? '搜正文 / 昵称 / guestId' : '搜名字 / 城市 / 技能 / guestId'}
|
||||||
value={q}
|
value={qDraft}
|
||||||
onChange={(e) => setQ(e.target.value)}
|
onChange={(e) => setQDraft(e.target.value)}
|
||||||
onKeyDown={(e) => {
|
onKeyDown={(e) => {
|
||||||
if (e.key === 'Enter') void loadList()
|
if (e.key === 'Enter') {
|
||||||
|
setOffset(0)
|
||||||
|
setQ(qDraft)
|
||||||
|
}
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<button type="button" className="com-btn com-btn-ghost" onClick={() => void loadList()}>
|
<button
|
||||||
|
type="button"
|
||||||
|
className="com-btn com-btn-ghost"
|
||||||
|
onClick={() => {
|
||||||
|
setOffset(0)
|
||||||
|
setQ(qDraft)
|
||||||
|
}}
|
||||||
|
>
|
||||||
搜索
|
搜索
|
||||||
</button>
|
</button>
|
||||||
<span className="com-muted">共 {total || items.length} 条</span>
|
</>
|
||||||
</div>
|
|
||||||
)}
|
)}
|
||||||
|
<span className="com-muted" style={{ marginLeft: 'auto' }}>
|
||||||
|
{loading ? '加载中…' : `第 ${pageFrom || 0}–${pageTo} / ${total}`}
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="com-btn com-btn-ghost"
|
||||||
|
disabled={!canPrev || loading}
|
||||||
|
onClick={() => setOffset((o) => Math.max(0, o - PAGE))}
|
||||||
|
>
|
||||||
|
上一页
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="com-btn com-btn-ghost"
|
||||||
|
disabled={!canNext || loading}
|
||||||
|
onClick={() => setOffset((o) => o + PAGE)}
|
||||||
|
>
|
||||||
|
下一页
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
<section className="com-panel com-table-wrap">
|
<section className="com-panel com-table-wrap">
|
||||||
{loading && !items.length ? (
|
{loading && !items.length ? (
|
||||||
<p className="com-muted">加载中…</p>
|
<p className="com-muted">加载中…</p>
|
||||||
) : !items.length ? (
|
) : !items.length ? (
|
||||||
<p className="com-muted">暂无数据</p>
|
<div className="com-empty">
|
||||||
|
<p className="com-muted">本列表暂无数据</p>
|
||||||
|
<p className="com-muted" style={{ fontSize: 12 }}>
|
||||||
|
有写入后点刷新;软删记录在「存档」里。
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<table className="com-table">
|
<table className="com-table com-table-click">
|
||||||
<thead>
|
<thead>
|
||||||
{tab === 'messages' ? (
|
{section === 'messages' ? (
|
||||||
<tr>
|
<tr>
|
||||||
<th>频道</th>
|
<th>频道</th>
|
||||||
<th>作者</th>
|
<th>作者</th>
|
||||||
<th>内容</th>
|
<th>内容</th>
|
||||||
|
<th>访客</th>
|
||||||
<th>时间</th>
|
<th>时间</th>
|
||||||
<th />
|
<th>操作</th>
|
||||||
</tr>
|
</tr>
|
||||||
) : null}
|
) : null}
|
||||||
{tab === 'roster' ? (
|
{section === 'roster' ? (
|
||||||
<tr>
|
<tr>
|
||||||
<th>名字</th>
|
<th>名字</th>
|
||||||
<th>城市</th>
|
<th>城市</th>
|
||||||
<th>标题</th>
|
<th>头衔</th>
|
||||||
|
<th>技能</th>
|
||||||
<th>更新</th>
|
<th>更新</th>
|
||||||
<th />
|
<th>操作</th>
|
||||||
</tr>
|
</tr>
|
||||||
) : null}
|
) : null}
|
||||||
{tab === 'reviews' ? (
|
{section === 'reviews' ? (
|
||||||
<tr>
|
<tr>
|
||||||
<th>咖啡馆</th>
|
<th>咖啡馆</th>
|
||||||
<th>作者</th>
|
<th>作者</th>
|
||||||
<th>分</th>
|
<th>分</th>
|
||||||
<th>评语</th>
|
<th>评语</th>
|
||||||
<th />
|
<th>时间</th>
|
||||||
|
<th>操作</th>
|
||||||
</tr>
|
</tr>
|
||||||
) : null}
|
) : null}
|
||||||
{tab === 'gigs' ? (
|
{section === 'gigs' ? (
|
||||||
<tr>
|
<tr>
|
||||||
<th>Gig</th>
|
<th>岗位</th>
|
||||||
<th>姓名</th>
|
<th>姓名</th>
|
||||||
<th>联系</th>
|
<th>联系</th>
|
||||||
<th>备注</th>
|
<th>备注</th>
|
||||||
<th />
|
<th>时间</th>
|
||||||
|
<th>操作</th>
|
||||||
</tr>
|
</tr>
|
||||||
) : null}
|
) : null}
|
||||||
{tab === 'feedback' ? (
|
{section === 'feedback' ? (
|
||||||
<tr>
|
<tr>
|
||||||
<th>类型</th>
|
<th>类型</th>
|
||||||
<th>内容</th>
|
<th>内容</th>
|
||||||
<th>联系</th>
|
<th>联系</th>
|
||||||
|
<th>访客</th>
|
||||||
<th>时间</th>
|
<th>时间</th>
|
||||||
<th />
|
<th>操作</th>
|
||||||
|
</tr>
|
||||||
|
) : null}
|
||||||
|
{section === 'archives' ? (
|
||||||
|
<tr>
|
||||||
|
<th>实体</th>
|
||||||
|
<th>动作</th>
|
||||||
|
<th>对象 ID</th>
|
||||||
|
<th>访客</th>
|
||||||
|
<th>时间</th>
|
||||||
|
<th>操作</th>
|
||||||
</tr>
|
</tr>
|
||||||
) : null}
|
) : null}
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{items.map((row) => {
|
{items.map((row) => {
|
||||||
const id = String(
|
const id = pickId(row, section)
|
||||||
row.id || row.messageId || row.guestId || row.guest_id || '',
|
const href = detailPath(row)
|
||||||
)
|
|
||||||
return (
|
return (
|
||||||
<tr key={id || JSON.stringify(row).slice(0, 40)}>
|
<tr
|
||||||
{tab === 'messages' ? (
|
key={id || JSON.stringify(row).slice(0, 40)}
|
||||||
|
className="com-tr-link"
|
||||||
|
onClick={() => openDetail(row)}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === 'Enter' || e.key === ' ') {
|
||||||
|
e.preventDefault()
|
||||||
|
openDetail(row)
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
tabIndex={href ? 0 : undefined}
|
||||||
|
role={href ? 'link' : undefined}
|
||||||
|
>
|
||||||
|
{section === 'messages' ? (
|
||||||
<>
|
<>
|
||||||
<td>{String(row.channelId || row.channel_id || '—')}</td>
|
<td>
|
||||||
<td>{String(row.author || '—')}</td>
|
<code>{String(row.channelId || row.channel_id || '—')}</code>
|
||||||
<td title={String(row.text || '')}>{short(row.text, 56)}</td>
|
</td>
|
||||||
|
<td>
|
||||||
|
<strong>{String(row.author || '—')}</strong>
|
||||||
|
</td>
|
||||||
|
<td title={String(row.text || '')}>{short(row.text, 64)}</td>
|
||||||
|
<td>
|
||||||
|
<code className="com-id">{short(row.guestId || row.guest_id, 16)}</code>
|
||||||
|
</td>
|
||||||
<td>{fmtTime(row.at || row.created_at || row.createdAt)}</td>
|
<td>{fmtTime(row.at || row.created_at || row.createdAt)}</td>
|
||||||
</>
|
</>
|
||||||
) : null}
|
) : null}
|
||||||
{tab === 'roster' ? (
|
{section === 'roster' ? (
|
||||||
<>
|
<>
|
||||||
<td>{String(row.name || '—')}</td>
|
<td>
|
||||||
|
<strong>{String(row.name || '—')}</strong>
|
||||||
|
<div className="com-muted" style={{ fontSize: 11 }}>
|
||||||
|
<code>{String(row.guestId || row.guest_id || '')}</code>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
<td>{String(row.city || '—')}</td>
|
<td>{String(row.city || '—')}</td>
|
||||||
<td>{short(row.title, 28)}</td>
|
<td>{short(row.title, 28)}</td>
|
||||||
|
<td>{short(row.skills, 28)}</td>
|
||||||
<td>{fmtTime(row.updatedAt || row.updated_at)}</td>
|
<td>{fmtTime(row.updatedAt || row.updated_at)}</td>
|
||||||
</>
|
</>
|
||||||
) : null}
|
) : null}
|
||||||
{tab === 'reviews' ? (
|
{section === 'reviews' ? (
|
||||||
<>
|
<>
|
||||||
<td>{String(row.cafeId || row.cafe_id || '—')}</td>
|
<td>
|
||||||
|
<code>{String(row.cafeId || row.cafe_id || '—')}</code>
|
||||||
|
</td>
|
||||||
<td>{String(row.author || '—')}</td>
|
<td>{String(row.author || '—')}</td>
|
||||||
<td>{String(row.score ?? '—')}</td>
|
<td>
|
||||||
<td>{short(row.text, 40)}</td>
|
<strong>{String(row.score ?? '—')}</strong>
|
||||||
</>
|
</td>
|
||||||
) : null}
|
|
||||||
{tab === 'gigs' ? (
|
|
||||||
<>
|
|
||||||
<td>{String(row.gigId || row.gig_id || '—')}</td>
|
|
||||||
<td>{String(row.name || '—')}</td>
|
|
||||||
<td>{short(row.contact, 24)}</td>
|
|
||||||
<td>{short(row.note, 32)}</td>
|
|
||||||
</>
|
|
||||||
) : null}
|
|
||||||
{tab === 'feedback' ? (
|
|
||||||
<>
|
|
||||||
<td>{String(row.kind || '—')}</td>
|
|
||||||
<td>{short(row.text, 48)}</td>
|
<td>{short(row.text, 48)}</td>
|
||||||
<td>{short(row.contact, 20)}</td>
|
<td>{fmtTime(row.at || row.created_at)}</td>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
{section === 'gigs' ? (
|
||||||
|
<>
|
||||||
|
<td>
|
||||||
|
<code>{String(row.gigId || row.gig_id || '—')}</code>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<strong>{String(row.name || '—')}</strong>
|
||||||
|
</td>
|
||||||
|
<td>{short(row.contact, 28)}</td>
|
||||||
|
<td>{short(row.note, 36)}</td>
|
||||||
|
<td>{fmtTime(row.at || row.created_at)}</td>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
{section === 'feedback' ? (
|
||||||
|
<>
|
||||||
|
<td>
|
||||||
|
<span className="com-badge tone-info">{String(row.kind || '—')}</span>
|
||||||
|
</td>
|
||||||
|
<td>{short(row.text, 56)}</td>
|
||||||
|
<td>{short(row.contact, 24)}</td>
|
||||||
|
<td>
|
||||||
|
<code className="com-id">{short(row.guestId || row.guest_id, 14)}</code>
|
||||||
|
</td>
|
||||||
<td>{fmtTime(row.created_at || row.createdAt || row.at)}</td>
|
<td>{fmtTime(row.created_at || row.createdAt || row.at)}</td>
|
||||||
</>
|
</>
|
||||||
) : null}
|
) : null}
|
||||||
|
{section === 'archives' ? (
|
||||||
|
<>
|
||||||
|
<td>{String(row.entity || '—')}</td>
|
||||||
<td>
|
<td>
|
||||||
|
<span className="com-badge tone-info">{String(row.action || '—')}</span>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<code className="com-id">{short(row.entityId || row.entity_id, 18)}</code>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<code className="com-id">{short(row.guestId || row.guest_id, 14)}</code>
|
||||||
|
</td>
|
||||||
|
<td>{fmtTime(row.at || row.created_at)}</td>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
<td onClick={(e) => e.stopPropagation()}>
|
||||||
|
<div className="com-row-actions">
|
||||||
|
{href ? (
|
||||||
|
<Link className="com-btn com-btn-ghost com-btn-sm" to={href}>
|
||||||
|
详情
|
||||||
|
</Link>
|
||||||
|
) : null}
|
||||||
|
{section === 'roster' ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="com-btn com-btn-ghost com-btn-sm"
|
||||||
|
onClick={() => setEditRoster({ ...row })}
|
||||||
|
>
|
||||||
|
编辑
|
||||||
|
</button>
|
||||||
|
) : null}
|
||||||
|
{section !== 'archives' ? (
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className="com-btn com-btn-danger com-btn-sm"
|
className="com-btn com-btn-danger com-btn-sm"
|
||||||
disabled={!id || busyId === id}
|
disabled={!id || busyId === id}
|
||||||
onClick={() => void removeRow(tab, id)}
|
onClick={() => void removeRow(row)}
|
||||||
>
|
>
|
||||||
{busyId === id ? '…' : '删除'}
|
{busyId === id ? '…' : '软删除'}
|
||||||
</button>
|
</button>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
)
|
)
|
||||||
@ -388,7 +733,42 @@ export default function Social() {
|
|||||||
)}
|
)}
|
||||||
</section>
|
</section>
|
||||||
</>
|
</>
|
||||||
)}
|
) : null}
|
||||||
|
|
||||||
|
{editRoster ? (
|
||||||
|
<div className="com-modal-mask" onClick={() => setEditRoster(null)}>
|
||||||
|
<div className="com-modal" onClick={(e) => e.stopPropagation()}>
|
||||||
|
<h3>编辑花名册 · {String(editRoster.guestId || editRoster.guest_id)}</h3>
|
||||||
|
{(['name', 'title', 'city', 'phone', 'linktree', 'skills'] as const).map((k) => (
|
||||||
|
<label key={k} className="com-field">
|
||||||
|
<span>{k}</span>
|
||||||
|
<input
|
||||||
|
className="com-input"
|
||||||
|
value={String(editRoster[k] ?? '')}
|
||||||
|
onChange={(e) => setEditRoster({ ...editRoster, [k]: e.target.value })}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
<label className="com-field">
|
||||||
|
<span>bio</span>
|
||||||
|
<textarea
|
||||||
|
className="com-input"
|
||||||
|
rows={5}
|
||||||
|
value={String(editRoster.bio ?? '')}
|
||||||
|
onChange={(e) => setEditRoster({ ...editRoster, bio: e.target.value })}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<div className="com-row-actions">
|
||||||
|
<button type="button" className="com-btn com-btn-ghost" onClick={() => setEditRoster(null)}>
|
||||||
|
取消
|
||||||
|
</button>
|
||||||
|
<button type="button" className="com-btn" disabled={busy} onClick={() => void saveRoster()}>
|
||||||
|
保存
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
486
apps/com/admin/src/pages/SocialDetail.tsx
Normal file
486
apps/com/admin/src/pages/SocialDetail.tsx
Normal file
@ -0,0 +1,486 @@
|
|||||||
|
/**
|
||||||
|
* 游民社区 · 详情页:摘要卡 + 中文字段 + 存档时间线 + 编辑/软删/恢复
|
||||||
|
*/
|
||||||
|
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||||
|
import { Link, useLocation, useNavigate, useParams } from 'react-router-dom'
|
||||||
|
import { api } from '../api/client'
|
||||||
|
import { fmtTime, labelOf, short, toEntity, toListSegment } from './socialMeta'
|
||||||
|
|
||||||
|
const ENTITY_LABEL: Record<string, string> = {
|
||||||
|
roster: '花名册',
|
||||||
|
messages: '聊天',
|
||||||
|
reviews: '咖啡馆评价',
|
||||||
|
gigApps: '接单申请',
|
||||||
|
feedback: '反馈',
|
||||||
|
skills: '技能板',
|
||||||
|
liveness: '实拍核验',
|
||||||
|
archives: '存档快照',
|
||||||
|
}
|
||||||
|
|
||||||
|
type Detail = {
|
||||||
|
ok?: boolean
|
||||||
|
entity?: string
|
||||||
|
id?: string
|
||||||
|
item?: Record<string, unknown>
|
||||||
|
softDeleted?: boolean
|
||||||
|
history?: Array<{
|
||||||
|
id?: string
|
||||||
|
action?: string
|
||||||
|
at?: string
|
||||||
|
note?: string
|
||||||
|
payload?: Record<string, unknown>
|
||||||
|
}>
|
||||||
|
}
|
||||||
|
|
||||||
|
function val(item: Record<string, unknown>, ...keys: string[]) {
|
||||||
|
for (const k of keys) {
|
||||||
|
if (item[k] != null && item[k] !== '') return item[k]
|
||||||
|
}
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
function PrimaryFields({
|
||||||
|
entity,
|
||||||
|
item,
|
||||||
|
}: {
|
||||||
|
entity: string
|
||||||
|
item: Record<string, unknown>
|
||||||
|
}) {
|
||||||
|
if (entity === 'messages') {
|
||||||
|
return (
|
||||||
|
<div className="com-detail-hero">
|
||||||
|
<blockquote className="com-detail-quote">{String(val(item, 'text') ?? '—')}</blockquote>
|
||||||
|
<div className="com-detail-meta">
|
||||||
|
<span>
|
||||||
|
作者 <strong>{String(val(item, 'author') ?? '—')}</strong>
|
||||||
|
</span>
|
||||||
|
<span>
|
||||||
|
频道 <code>{String(val(item, 'channelId', 'channel_id') ?? '—')}</code>
|
||||||
|
</span>
|
||||||
|
<span>
|
||||||
|
访客 <code>{String(val(item, 'guestId', 'guest_id') ?? '—')}</code>
|
||||||
|
</span>
|
||||||
|
<span>{fmtTime(val(item, 'at', 'created_at', 'createdAt'))}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (entity === 'roster') {
|
||||||
|
const skills = String(val(item, 'skills') ?? '')
|
||||||
|
.split(/[,,|/]/)
|
||||||
|
.map((s) => s.trim())
|
||||||
|
.filter(Boolean)
|
||||||
|
return (
|
||||||
|
<div className="com-detail-hero">
|
||||||
|
<div className="com-detail-name-row">
|
||||||
|
<h2 className="com-detail-name">{String(val(item, 'name') ?? '未命名')}</h2>
|
||||||
|
<span className="com-badge tone-info">{String(val(item, 'city') ?? '未填城市')}</span>
|
||||||
|
</div>
|
||||||
|
<p className="com-detail-title">{String(val(item, 'title') ?? '—')}</p>
|
||||||
|
<p className="com-detail-bio">{String(val(item, 'bio') ?? '暂无简介')}</p>
|
||||||
|
{skills.length ? (
|
||||||
|
<div className="com-chip-row">
|
||||||
|
{skills.map((s) => (
|
||||||
|
<span className="com-chip" key={s}>
|
||||||
|
{s}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
<div className="com-detail-meta">
|
||||||
|
<span>
|
||||||
|
电话 {String(val(item, 'phone') ?? '—')}
|
||||||
|
</span>
|
||||||
|
<span>
|
||||||
|
链接 {String(val(item, 'linktree') ?? '—')}
|
||||||
|
</span>
|
||||||
|
<span>
|
||||||
|
guest <code>{String(val(item, 'guestId', 'guest_id') ?? '—')}</code>
|
||||||
|
</span>
|
||||||
|
<span>更新 {fmtTime(val(item, 'updatedAt', 'updated_at'))}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (entity === 'reviews') {
|
||||||
|
return (
|
||||||
|
<div className="com-detail-hero">
|
||||||
|
<div className="com-detail-name-row">
|
||||||
|
<h2 className="com-detail-name">评分 {String(val(item, 'score') ?? '—')}</h2>
|
||||||
|
<span className="com-badge tone-info">
|
||||||
|
{String(val(item, 'cafeId', 'cafe_id') ?? '咖啡馆')}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<blockquote className="com-detail-quote">{String(val(item, 'text') ?? '—')}</blockquote>
|
||||||
|
<div className="com-detail-meta">
|
||||||
|
<span>作者 {String(val(item, 'author') ?? '—')}</span>
|
||||||
|
<span>实拍 {String(val(item, 'photoNote', 'photo_note') ?? '—')}</span>
|
||||||
|
<span>访客 <code>{String(val(item, 'guestId', 'guest_id') ?? '—')}</code></span>
|
||||||
|
<span>{fmtTime(val(item, 'at', 'created_at'))}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (entity === 'gigApps') {
|
||||||
|
return (
|
||||||
|
<div className="com-detail-hero">
|
||||||
|
<div className="com-detail-name-row">
|
||||||
|
<h2 className="com-detail-name">{String(val(item, 'name') ?? '—')}</h2>
|
||||||
|
<span className="com-badge tone-info">{String(val(item, 'gigId', 'gig_id') ?? 'gig')}</span>
|
||||||
|
</div>
|
||||||
|
<p className="com-detail-bio">联系:{String(val(item, 'contact') ?? '—')}</p>
|
||||||
|
<p className="com-detail-bio">备注:{String(val(item, 'note') ?? '—')}</p>
|
||||||
|
<div className="com-detail-meta">
|
||||||
|
<span>访客 <code>{String(val(item, 'guestId', 'guest_id') ?? '—')}</code></span>
|
||||||
|
<span>{fmtTime(val(item, 'at', 'created_at'))}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (entity === 'feedback') {
|
||||||
|
return (
|
||||||
|
<div className="com-detail-hero">
|
||||||
|
<div className="com-detail-name-row">
|
||||||
|
<h2 className="com-detail-name">反馈</h2>
|
||||||
|
<span className="com-badge tone-info">{String(val(item, 'kind') ?? '—')}</span>
|
||||||
|
</div>
|
||||||
|
<blockquote className="com-detail-quote">{String(val(item, 'text') ?? '—')}</blockquote>
|
||||||
|
<div className="com-detail-meta">
|
||||||
|
<span>联系 {String(val(item, 'contact') ?? '—')}</span>
|
||||||
|
<span>访客 <code>{String(val(item, 'guestId', 'guest_id') ?? '—')}</code></span>
|
||||||
|
<span>{fmtTime(val(item, 'at', 'created_at', 'createdAt'))}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (entity === 'archives') {
|
||||||
|
const payload = val(item, 'payload')
|
||||||
|
return (
|
||||||
|
<div className="com-detail-hero">
|
||||||
|
<div className="com-detail-name-row">
|
||||||
|
<h2 className="com-detail-name">{String(val(item, 'action') ?? 'archive')}</h2>
|
||||||
|
<span className="com-badge tone-info">{String(val(item, 'entity') ?? '—')}</span>
|
||||||
|
</div>
|
||||||
|
<div className="com-detail-meta">
|
||||||
|
<span>
|
||||||
|
对象 <code>{String(val(item, 'entityId', 'entity_id') ?? '—')}</code>
|
||||||
|
</span>
|
||||||
|
<span>
|
||||||
|
访客 <code>{String(val(item, 'guestId', 'guest_id') ?? '—')}</code>
|
||||||
|
</span>
|
||||||
|
<span>{fmtTime(val(item, 'at', 'created_at'))}</span>
|
||||||
|
</div>
|
||||||
|
{val(item, 'note') ? <p className="com-detail-bio">{String(val(item, 'note'))}</p> : null}
|
||||||
|
<pre className="com-pre com-pre-sm">{JSON.stringify(payload ?? {}, null, 2)}</pre>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function SocialDetail() {
|
||||||
|
const { lane = 'intl', kind: kindParam = '', id = '' } = useParams()
|
||||||
|
const { pathname } = useLocation()
|
||||||
|
const nav = useNavigate()
|
||||||
|
const base = `/${lane}/social`
|
||||||
|
const [data, setData] = useState<Detail | null>(null)
|
||||||
|
const [err, setErr] = useState('')
|
||||||
|
const [msg, setMsg] = useState('')
|
||||||
|
const [busy, setBusy] = useState(false)
|
||||||
|
const [loading, setLoading] = useState(true)
|
||||||
|
const [edit, setEdit] = useState(false)
|
||||||
|
const [draft, setDraft] = useState<Record<string, string>>({})
|
||||||
|
|
||||||
|
// explicit routes like /cn/social/messages/:id 只有 :id,kind 从路径取
|
||||||
|
const kind = kindParam || pathname.split('/').filter(Boolean)[2] || ''
|
||||||
|
const entity = toEntity(kind)
|
||||||
|
const listPath = `${base}/${toListSegment(kind || 'overview')}`
|
||||||
|
|
||||||
|
const load = useCallback(async () => {
|
||||||
|
setErr('')
|
||||||
|
setLoading(true)
|
||||||
|
try {
|
||||||
|
if (entity === 'archives') {
|
||||||
|
const res = await api<{ items?: Array<Record<string, unknown>>; total?: number }>(
|
||||||
|
'/api/admin/social/ugc/archives?limit=500',
|
||||||
|
)
|
||||||
|
const hit = (res.items || []).find((x) => String(x.id) === id)
|
||||||
|
if (!hit) throw new Error('存档不存在')
|
||||||
|
setData({
|
||||||
|
ok: true,
|
||||||
|
entity: 'archives',
|
||||||
|
id,
|
||||||
|
item: hit,
|
||||||
|
softDeleted: false,
|
||||||
|
history: [],
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const res = await api<Detail>(
|
||||||
|
`/api/admin/social/ugc/detail/${encodeURIComponent(entity)}/${encodeURIComponent(id)}`,
|
||||||
|
)
|
||||||
|
setData(res)
|
||||||
|
const item = res.item || {}
|
||||||
|
if (entity === 'roster') {
|
||||||
|
setDraft({
|
||||||
|
name: String(item.name || ''),
|
||||||
|
title: String(item.title || ''),
|
||||||
|
city: String(item.city || ''),
|
||||||
|
phone: String(item.phone || ''),
|
||||||
|
linktree: String(item.linktree || ''),
|
||||||
|
skills: String(item.skills || ''),
|
||||||
|
bio: String(item.bio || ''),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
}, [entity, id])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
load().catch((e: Error) => {
|
||||||
|
setErr(e.message || '加载失败')
|
||||||
|
setLoading(false)
|
||||||
|
})
|
||||||
|
}, [load])
|
||||||
|
|
||||||
|
async function softDelete() {
|
||||||
|
if (!window.confirm('软删除并写入存档?不会物理抹除。')) return
|
||||||
|
setBusy(true)
|
||||||
|
setMsg('')
|
||||||
|
setErr('')
|
||||||
|
try {
|
||||||
|
const path =
|
||||||
|
entity === 'roster'
|
||||||
|
? `/api/admin/social/ugc/roster/${encodeURIComponent(id)}`
|
||||||
|
: entity === 'messages'
|
||||||
|
? `/api/admin/social/ugc/messages/${encodeURIComponent(id)}`
|
||||||
|
: entity === 'reviews'
|
||||||
|
? `/api/admin/social/ugc/reviews/${encodeURIComponent(id)}`
|
||||||
|
: entity === 'gigApps'
|
||||||
|
? `/api/admin/social/ugc/gig-apps/${encodeURIComponent(id)}`
|
||||||
|
: `/api/admin/social/ugc/feedback/${encodeURIComponent(id)}`
|
||||||
|
await api(path, { method: 'DELETE' })
|
||||||
|
setMsg('已软删除并存档')
|
||||||
|
await load()
|
||||||
|
} catch (e: unknown) {
|
||||||
|
setErr(e instanceof Error ? e.message : '删除失败')
|
||||||
|
} finally {
|
||||||
|
setBusy(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function restore() {
|
||||||
|
if (entity !== 'roster') return
|
||||||
|
setBusy(true)
|
||||||
|
setErr('')
|
||||||
|
try {
|
||||||
|
await api(`/api/admin/social/ugc/roster/${encodeURIComponent(id)}`, {
|
||||||
|
method: 'PUT',
|
||||||
|
body: JSON.stringify({ ...draft, restore: true, status: 'online' }),
|
||||||
|
})
|
||||||
|
setMsg('已恢复可见')
|
||||||
|
setEdit(false)
|
||||||
|
await load()
|
||||||
|
} catch (e: unknown) {
|
||||||
|
setErr(e instanceof Error ? e.message : '恢复失败')
|
||||||
|
} finally {
|
||||||
|
setBusy(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function save() {
|
||||||
|
if (entity !== 'roster') return
|
||||||
|
setBusy(true)
|
||||||
|
setErr('')
|
||||||
|
try {
|
||||||
|
await api(`/api/admin/social/ugc/roster/${encodeURIComponent(id)}`, {
|
||||||
|
method: 'PUT',
|
||||||
|
body: JSON.stringify(draft),
|
||||||
|
})
|
||||||
|
setMsg('已保存(变更前进存档)')
|
||||||
|
setEdit(false)
|
||||||
|
await load()
|
||||||
|
} catch (e: unknown) {
|
||||||
|
setErr(e instanceof Error ? e.message : '保存失败')
|
||||||
|
} finally {
|
||||||
|
setBusy(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const item = data?.item || {}
|
||||||
|
const fields = useMemo(
|
||||||
|
() =>
|
||||||
|
Object.entries(item).filter(
|
||||||
|
([k]) => !['collectionId', 'collectionName', 'expand'].includes(k),
|
||||||
|
),
|
||||||
|
[item],
|
||||||
|
)
|
||||||
|
const title = ENTITY_LABEL[entity] || entity
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="com-page">
|
||||||
|
<header className="com-page-head com-page-head-row">
|
||||||
|
<div>
|
||||||
|
<p className="com-muted" style={{ margin: '0 0 6px' }}>
|
||||||
|
<Link to={listPath}>← {title}列表</Link>
|
||||||
|
</p>
|
||||||
|
<h1>
|
||||||
|
{title} · 详情
|
||||||
|
</h1>
|
||||||
|
<p>
|
||||||
|
ID <code>{id || '—'}</code>
|
||||||
|
{loading ? (
|
||||||
|
<span className="com-badge" style={{ marginLeft: 8 }}>
|
||||||
|
加载中
|
||||||
|
</span>
|
||||||
|
) : data?.softDeleted ? (
|
||||||
|
<span className="com-badge tone-warn" style={{ marginLeft: 8 }}>
|
||||||
|
已软删除
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<span className="com-badge tone-ok" style={{ marginLeft: 8 }}>
|
||||||
|
在线
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="com-row-actions">
|
||||||
|
<button type="button" className="com-btn com-btn-ghost" onClick={() => nav(listPath)}>
|
||||||
|
返回列表
|
||||||
|
</button>
|
||||||
|
{entity === 'roster' && !edit ? (
|
||||||
|
<button type="button" className="com-btn" onClick={() => setEdit(true)}>
|
||||||
|
编辑
|
||||||
|
</button>
|
||||||
|
) : null}
|
||||||
|
{entity === 'roster' && data?.softDeleted ? (
|
||||||
|
<button type="button" className="com-btn" disabled={busy} onClick={() => void restore()}>
|
||||||
|
恢复
|
||||||
|
</button>
|
||||||
|
) : null}
|
||||||
|
{entity !== 'archives' ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="com-btn com-btn-danger"
|
||||||
|
disabled={busy || !!data?.softDeleted || loading}
|
||||||
|
onClick={() => void softDelete()}
|
||||||
|
>
|
||||||
|
软删除
|
||||||
|
</button>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
{msg ? <div className="com-toast com-toast-ok">{msg}</div> : null}
|
||||||
|
{err ? <div className="com-toast com-toast-err">{err}</div> : null}
|
||||||
|
|
||||||
|
{loading && !data ? <p className="com-muted">正在拉取详情…</p> : null}
|
||||||
|
|
||||||
|
{!loading && !err && data ? (
|
||||||
|
<section className="com-panel">
|
||||||
|
<h2>摘要</h2>
|
||||||
|
<PrimaryFields entity={entity} item={item} />
|
||||||
|
</section>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{edit && entity === 'roster' ? (
|
||||||
|
<section className="com-panel">
|
||||||
|
<h2>编辑资料</h2>
|
||||||
|
<div className="com-form-grid">
|
||||||
|
{(['name', 'title', 'city', 'phone', 'linktree', 'skills'] as const).map((k) => (
|
||||||
|
<label key={k} className="com-field">
|
||||||
|
<span>{labelOf(k)}</span>
|
||||||
|
<input
|
||||||
|
className="com-input"
|
||||||
|
value={draft[k] || ''}
|
||||||
|
onChange={(e) => setDraft({ ...draft, [k]: e.target.value })}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
<label className="com-field" style={{ gridColumn: '1 / -1' }}>
|
||||||
|
<span>{labelOf('bio')}</span>
|
||||||
|
<textarea
|
||||||
|
className="com-input"
|
||||||
|
rows={5}
|
||||||
|
value={draft.bio || ''}
|
||||||
|
onChange={(e) => setDraft({ ...draft, bio: e.target.value })}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div className="com-row-actions" style={{ marginTop: 12 }}>
|
||||||
|
<button type="button" className="com-btn com-btn-ghost" onClick={() => setEdit(false)}>
|
||||||
|
取消
|
||||||
|
</button>
|
||||||
|
<button type="button" className="com-btn" disabled={busy} onClick={() => void save()}>
|
||||||
|
保存
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<section className="com-panel">
|
||||||
|
<h2>完整字段({fields.length})</h2>
|
||||||
|
{!fields.length ? (
|
||||||
|
<p className="com-muted">{loading ? '加载中…' : '无字段'}</p>
|
||||||
|
) : (
|
||||||
|
<dl className="com-detail-dl">
|
||||||
|
{fields.map(([k, v]) => (
|
||||||
|
<div key={k} className="com-detail-row">
|
||||||
|
<dt>
|
||||||
|
{labelOf(k)}
|
||||||
|
<div className="com-muted" style={{ fontSize: 10 }}>
|
||||||
|
{k}
|
||||||
|
</div>
|
||||||
|
</dt>
|
||||||
|
<dd>
|
||||||
|
{typeof v === 'object' && v !== null ? (
|
||||||
|
<pre className="com-pre com-pre-sm">{JSON.stringify(v, null, 2)}</pre>
|
||||||
|
) : k.includes('at') || k.includes('_at') || k.includes('At') ? (
|
||||||
|
fmtTime(v)
|
||||||
|
) : (
|
||||||
|
String(v ?? '—')
|
||||||
|
)}
|
||||||
|
</dd>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</dl>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{entity !== 'archives' ? (
|
||||||
|
<section className="com-panel">
|
||||||
|
<h2>存档时间线({data?.history?.length || 0})</h2>
|
||||||
|
{!data?.history?.length ? (
|
||||||
|
<p className="com-muted">尚无变更 / 删除存档。软删除或保存后会出现在这里。</p>
|
||||||
|
) : (
|
||||||
|
<ol className="com-timeline">
|
||||||
|
{data.history.map((h) => (
|
||||||
|
<li key={h.id || `${h.action}-${h.at}`}>
|
||||||
|
<div className="com-timeline-head">
|
||||||
|
<span className="com-badge tone-info">{h.action || '—'}</span>
|
||||||
|
<time>{fmtTime(h.at)}</time>
|
||||||
|
</div>
|
||||||
|
{h.note ? <p className="com-muted">{h.note}</p> : null}
|
||||||
|
<details>
|
||||||
|
<summary>快照 JSON</summary>
|
||||||
|
<pre className="com-pre com-pre-sm">
|
||||||
|
{JSON.stringify(h.payload || {}, null, 2)}
|
||||||
|
</pre>
|
||||||
|
</details>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ol>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<p className="com-muted" style={{ fontSize: 12 }}>
|
||||||
|
列表入口:<Link to={listPath}>{title}</Link>
|
||||||
|
{' · '}
|
||||||
|
摘要字段展示优先;完整键值在下方。消息样例可用「聊天」列表点任意行进入。
|
||||||
|
{short(id, 8) === '—' ? null : null}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
122
apps/com/admin/src/pages/socialMeta.ts
Normal file
122
apps/com/admin/src/pages/socialMeta.ts
Normal file
@ -0,0 +1,122 @@
|
|||||||
|
/** 游民社区后台 · 分区与字段元数据 */
|
||||||
|
|
||||||
|
export type SectionKey =
|
||||||
|
| 'overview'
|
||||||
|
| 'messages'
|
||||||
|
| 'roster'
|
||||||
|
| 'reviews'
|
||||||
|
| 'gigs'
|
||||||
|
| 'feedback'
|
||||||
|
| 'archives'
|
||||||
|
| 'catalog'
|
||||||
|
|
||||||
|
export const SECTIONS: SectionKey[] = [
|
||||||
|
'overview',
|
||||||
|
'roster',
|
||||||
|
'messages',
|
||||||
|
'reviews',
|
||||||
|
'gigs',
|
||||||
|
'feedback',
|
||||||
|
'archives',
|
||||||
|
'catalog',
|
||||||
|
]
|
||||||
|
|
||||||
|
export const SECTION_TITLE: Record<SectionKey, string> = {
|
||||||
|
overview: '数据概览',
|
||||||
|
roster: '花名册',
|
||||||
|
messages: '聊天',
|
||||||
|
reviews: '咖啡馆评价',
|
||||||
|
gigs: '接单申请',
|
||||||
|
feedback: '反馈',
|
||||||
|
archives: '存档',
|
||||||
|
catalog: '目录配置',
|
||||||
|
}
|
||||||
|
|
||||||
|
export const SECTION_DESC: Record<SectionKey, string> = {
|
||||||
|
overview: '整体可视化;点左侧二级菜单进各列表。',
|
||||||
|
roster: '成员介绍列表。点行进详情,可编辑 / 软删除 / 恢复。',
|
||||||
|
messages: '大厅消息列表。点行查看完整字段与存档时间线。',
|
||||||
|
reviews: '咖啡馆评价。点行进详情,支持软删除存档。',
|
||||||
|
gigs: '共创 / 接单申请。点行进详情。',
|
||||||
|
feedback: '用户反馈列表。点行进详情。',
|
||||||
|
archives: '软删除与变更快照。点行查看 payload。',
|
||||||
|
catalog: 'remote-config socialCatalogs JSON。',
|
||||||
|
}
|
||||||
|
|
||||||
|
/** URL kind → API entity */
|
||||||
|
export function toEntity(kind: string): string {
|
||||||
|
if (kind === 'gigs' || kind === 'gigApps') return 'gigApps'
|
||||||
|
return kind
|
||||||
|
}
|
||||||
|
|
||||||
|
/** API entity / URL kind → 列表 path segment */
|
||||||
|
export function toListSegment(kind: string): string {
|
||||||
|
if (kind === 'gigApps') return 'gigs'
|
||||||
|
return kind
|
||||||
|
}
|
||||||
|
|
||||||
|
export const FIELD_LABEL: Record<string, string> = {
|
||||||
|
id: 'ID',
|
||||||
|
guest_id: '访客 ID',
|
||||||
|
guestId: '访客 ID',
|
||||||
|
channel_id: '频道',
|
||||||
|
channelId: '频道',
|
||||||
|
author: '作者',
|
||||||
|
text: '正文',
|
||||||
|
created_at: '创建时间',
|
||||||
|
createdAt: '创建时间',
|
||||||
|
updated_at: '更新时间',
|
||||||
|
updatedAt: '更新时间',
|
||||||
|
at: '时间',
|
||||||
|
name: '名字',
|
||||||
|
title: '头衔',
|
||||||
|
city: '城市',
|
||||||
|
phone: '电话',
|
||||||
|
linktree: '主页链接',
|
||||||
|
skills: '技能',
|
||||||
|
bio: '简介',
|
||||||
|
status: '状态',
|
||||||
|
deleted_at: '软删时间',
|
||||||
|
cafe_id: '咖啡馆',
|
||||||
|
cafeId: '咖啡馆',
|
||||||
|
score: '评分',
|
||||||
|
photo_note: '实拍备注',
|
||||||
|
photoNote: '实拍备注',
|
||||||
|
gig_id: '岗位',
|
||||||
|
gigId: '岗位',
|
||||||
|
contact: '联系方式',
|
||||||
|
note: '备注',
|
||||||
|
kind: '类型',
|
||||||
|
entity: '实体',
|
||||||
|
entity_id: '实体 ID',
|
||||||
|
entityId: '实体 ID',
|
||||||
|
action: '动作',
|
||||||
|
payload: '快照',
|
||||||
|
seq: '序号',
|
||||||
|
client_id: '客户端 ID',
|
||||||
|
meta: '元数据',
|
||||||
|
}
|
||||||
|
|
||||||
|
export function labelOf(key: string): string {
|
||||||
|
return FIELD_LABEL[key] || key
|
||||||
|
}
|
||||||
|
|
||||||
|
export function fmtTime(v: unknown) {
|
||||||
|
if (v == null || v === '') return '—'
|
||||||
|
const s = String(v)
|
||||||
|
if (/^\d+$/.test(s)) {
|
||||||
|
const n = Number(s)
|
||||||
|
return new Date(n < 1e12 ? n * 1000 : n).toLocaleString('zh-CN', { hour12: false })
|
||||||
|
}
|
||||||
|
return s.slice(0, 19).replace('T', ' ')
|
||||||
|
}
|
||||||
|
|
||||||
|
export function short(v: unknown, n = 48) {
|
||||||
|
const s = String(v ?? '')
|
||||||
|
return s.length <= n ? s || '—' : `${s.slice(0, n)}…`
|
||||||
|
}
|
||||||
|
|
||||||
|
export function pickId(row: Record<string, unknown>, section: SectionKey): string {
|
||||||
|
if (section === 'roster') return String(row.guestId || row.guest_id || '')
|
||||||
|
return String(row.id || row.messageId || row.entityId || '')
|
||||||
|
}
|
||||||
@ -199,6 +199,9 @@ input {
|
|||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
gap: 6px;
|
gap: 6px;
|
||||||
flex: 1;
|
flex: 1;
|
||||||
|
overflow-y: auto;
|
||||||
|
min-height: 0;
|
||||||
|
padding-right: 2px;
|
||||||
}
|
}
|
||||||
.com-nav a {
|
.com-nav a {
|
||||||
display: flex;
|
display: flex;
|
||||||
@ -217,6 +220,66 @@ input {
|
|||||||
.com-nav-ico {
|
.com-nav-ico {
|
||||||
width: 1.25em;
|
width: 1.25em;
|
||||||
text-align: center;
|
text-align: center;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
.com-nav-branch {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 4px;
|
||||||
|
}
|
||||||
|
.com-nav-parent {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
width: 100%;
|
||||||
|
padding: 12px 14px;
|
||||||
|
border-radius: 12px;
|
||||||
|
border: 0;
|
||||||
|
background: transparent;
|
||||||
|
color: var(--muted);
|
||||||
|
min-height: 44px;
|
||||||
|
cursor: pointer;
|
||||||
|
text-align: left;
|
||||||
|
font: inherit;
|
||||||
|
}
|
||||||
|
.com-nav-parent:hover {
|
||||||
|
background: rgba(245, 158, 11, 0.08);
|
||||||
|
color: var(--text);
|
||||||
|
}
|
||||||
|
.com-nav-branch.is-active > .com-nav-parent {
|
||||||
|
color: var(--text);
|
||||||
|
background: rgba(245, 158, 11, 0.1);
|
||||||
|
}
|
||||||
|
.com-nav-parent-label {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.com-nav-caret {
|
||||||
|
font-size: 12px;
|
||||||
|
opacity: 0.7;
|
||||||
|
}
|
||||||
|
.com-nav-sub {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 2px;
|
||||||
|
padding: 0 0 4px 8px;
|
||||||
|
margin: 0 0 4px 10px;
|
||||||
|
border-left: 1px solid rgba(245, 158, 11, 0.28);
|
||||||
|
}
|
||||||
|
.com-nav-sublink {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 10px 12px;
|
||||||
|
border-radius: 10px;
|
||||||
|
color: var(--muted);
|
||||||
|
min-height: 40px;
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
.com-nav-sublink.active,
|
||||||
|
.com-nav-sublink:hover {
|
||||||
|
background: rgba(245, 158, 11, 0.14);
|
||||||
|
color: var(--text);
|
||||||
}
|
}
|
||||||
.com-logout {
|
.com-logout {
|
||||||
border: 1px solid var(--line);
|
border: 1px solid var(--line);
|
||||||
@ -1241,3 +1304,259 @@ button.com-chip.is-on,
|
|||||||
grid-template-columns: 1fr;
|
grid-template-columns: 1fr;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* —— Social UGC ops: viz / CRUD / detail —— */
|
||||||
|
.com-viz-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
gap: 14px;
|
||||||
|
margin-bottom: 18px;
|
||||||
|
}
|
||||||
|
.com-viz-card h2 {
|
||||||
|
margin: 0 0 12px;
|
||||||
|
font-size: 14px;
|
||||||
|
letter-spacing: 0.04em;
|
||||||
|
color: var(--muted);
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
.com-viz-note {
|
||||||
|
margin: 8px 0 0;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
.com-bars {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
.com-bar-row {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 72px 1fr 36px;
|
||||||
|
gap: 8px;
|
||||||
|
align-items: center;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
.com-bar-label {
|
||||||
|
color: var(--muted);
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.com-bar-track {
|
||||||
|
height: 10px;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: rgba(255, 255, 255, 0.06);
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
.com-bar-track i {
|
||||||
|
display: block;
|
||||||
|
height: 100%;
|
||||||
|
border-radius: inherit;
|
||||||
|
min-width: 2px;
|
||||||
|
}
|
||||||
|
.com-bar-val {
|
||||||
|
text-align: right;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
.com-spark {
|
||||||
|
display: block;
|
||||||
|
margin-top: 4px;
|
||||||
|
}
|
||||||
|
.com-donut-wrap {
|
||||||
|
display: flex;
|
||||||
|
gap: 16px;
|
||||||
|
align-items: center;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
.com-donut-legend {
|
||||||
|
list-style: none;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 6px;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
.com-donut-legend i {
|
||||||
|
display: inline-block;
|
||||||
|
width: 8px;
|
||||||
|
height: 8px;
|
||||||
|
border-radius: 50%;
|
||||||
|
margin-right: 6px;
|
||||||
|
}
|
||||||
|
.com-stat-grid-compact {
|
||||||
|
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||||
|
}
|
||||||
|
.com-row-actions {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 6px;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
.com-btn-sm {
|
||||||
|
padding: 6px 10px;
|
||||||
|
font-size: 12px;
|
||||||
|
min-height: 32px;
|
||||||
|
}
|
||||||
|
.com-modal-mask {
|
||||||
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
|
z-index: 80;
|
||||||
|
background: rgba(0, 0, 0, 0.55);
|
||||||
|
display: grid;
|
||||||
|
place-items: center;
|
||||||
|
padding: 20px;
|
||||||
|
}
|
||||||
|
.com-modal {
|
||||||
|
width: min(520px, 100%);
|
||||||
|
max-height: min(86vh, 720px);
|
||||||
|
overflow: auto;
|
||||||
|
padding: 20px;
|
||||||
|
border-radius: 16px;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
background: #121216;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
.com-modal h3 {
|
||||||
|
margin: 0 0 4px;
|
||||||
|
font-size: 16px;
|
||||||
|
}
|
||||||
|
.com-tr-link {
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.com-tr-link:hover td {
|
||||||
|
background: rgba(245, 158, 11, 0.06);
|
||||||
|
}
|
||||||
|
.com-id {
|
||||||
|
font-size: 11px;
|
||||||
|
opacity: 0.85;
|
||||||
|
}
|
||||||
|
.com-empty {
|
||||||
|
padding: 28px 12px;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
.com-detail-hero {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
.com-detail-quote {
|
||||||
|
margin: 0;
|
||||||
|
padding: 16px 18px;
|
||||||
|
border-left: 3px solid var(--accent);
|
||||||
|
background: rgba(245, 158, 11, 0.08);
|
||||||
|
border-radius: 0 12px 12px 0;
|
||||||
|
font-size: 16px;
|
||||||
|
line-height: 1.55;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
}
|
||||||
|
.com-detail-name-row {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 10px;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
.com-detail-name {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 22px;
|
||||||
|
}
|
||||||
|
.com-detail-title {
|
||||||
|
margin: 0;
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
.com-detail-bio {
|
||||||
|
margin: 0;
|
||||||
|
line-height: 1.55;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
}
|
||||||
|
.com-detail-meta {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 10px 16px;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
.com-form-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
@media (max-width: 720px) {
|
||||||
|
.com-form-grid {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.com-detail-dl {
|
||||||
|
margin: 0;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
.com-detail-row {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 140px 1fr;
|
||||||
|
gap: 10px;
|
||||||
|
padding-bottom: 10px;
|
||||||
|
border-bottom: 1px solid rgba(255, 255, 255, 0.05);
|
||||||
|
}
|
||||||
|
.com-detail-row dt {
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 12px;
|
||||||
|
word-break: break-all;
|
||||||
|
}
|
||||||
|
.com-detail-row dd {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 13px;
|
||||||
|
word-break: break-word;
|
||||||
|
}
|
||||||
|
.com-pre-sm {
|
||||||
|
margin: 0;
|
||||||
|
max-height: 220px;
|
||||||
|
overflow: auto;
|
||||||
|
font-size: 11px;
|
||||||
|
padding: 10px;
|
||||||
|
border-radius: 10px;
|
||||||
|
background: #09090b;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
}
|
||||||
|
.com-timeline {
|
||||||
|
list-style: none;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 14px;
|
||||||
|
}
|
||||||
|
.com-timeline li {
|
||||||
|
padding: 12px 14px;
|
||||||
|
border-radius: 12px;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
background: rgba(255, 255, 255, 0.02);
|
||||||
|
}
|
||||||
|
.com-timeline-head {
|
||||||
|
display: flex;
|
||||||
|
gap: 10px;
|
||||||
|
align-items: center;
|
||||||
|
margin-bottom: 6px;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
.com-timeline details summary {
|
||||||
|
cursor: pointer;
|
||||||
|
color: var(--accent-2, #f59e0b);
|
||||||
|
font-size: 12px;
|
||||||
|
margin-top: 6px;
|
||||||
|
}
|
||||||
|
@media (max-width: 900px) {
|
||||||
|
.com-viz-grid {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
.com-detail-row {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
.com-stat-grid-compact {
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
5
src/app/social/skills/page.tsx
Normal file
5
src/app/social/skills/page.tsx
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
import SkillsBoardClient from "@social/components/SkillsBoardClient";
|
||||||
|
|
||||||
|
export default function Page() {
|
||||||
|
return <SkillsBoardClient />;
|
||||||
|
}
|
||||||
5
src/app/social/wrapped/page.tsx
Normal file
5
src/app/social/wrapped/page.tsx
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
import WrappedClient from "@social/components/WrappedClient";
|
||||||
|
|
||||||
|
export default function Page() {
|
||||||
|
return <WrappedClient />;
|
||||||
|
}
|
||||||
@ -6,6 +6,7 @@ import { useRouter } from "next/navigation";
|
|||||||
import SiteShell from "@social/components/SiteShell";
|
import SiteShell from "@social/components/SiteShell";
|
||||||
import { socialPath } from "@social/lib/socialPath";
|
import { socialPath } from "@social/lib/socialPath";
|
||||||
import { socialTx } from "@social/lib/socialTx";
|
import { socialTx } from "@social/lib/socialTx";
|
||||||
|
import { getGuestId } from "@social/lib/api";
|
||||||
import { useSocialI18n } from "@social/lib/useSocialI18n";
|
import { useSocialI18n } from "@social/lib/useSocialI18n";
|
||||||
import { coffeeApi } from "../lib/api";
|
import { coffeeApi } from "../lib/api";
|
||||||
import type { CoffeeEventType, CoffeeSlot } from "../lib/types";
|
import type { CoffeeEventType, CoffeeSlot } from "../lib/types";
|
||||||
@ -83,6 +84,7 @@ export default function CoffeeBookPage({
|
|||||||
start: slot.start,
|
start: slot.start,
|
||||||
attendee_name: name.trim(),
|
attendee_name: name.trim(),
|
||||||
attendee_email: email.trim() || undefined,
|
attendee_email: email.trim() || undefined,
|
||||||
|
attendee_device: getGuestId(),
|
||||||
location: loc,
|
location: loc,
|
||||||
notes: notes.trim(),
|
notes: notes.trim(),
|
||||||
});
|
});
|
||||||
|
|||||||
@ -5,9 +5,11 @@ import Link from "next/link";
|
|||||||
import SiteShell from "@social/components/SiteShell";
|
import SiteShell from "@social/components/SiteShell";
|
||||||
import { socialPath } from "@social/lib/socialPath";
|
import { socialPath } from "@social/lib/socialPath";
|
||||||
import { socialTx } from "@social/lib/socialTx";
|
import { socialTx } from "@social/lib/socialTx";
|
||||||
|
import { getGuestId } from "@social/lib/api";
|
||||||
import { useSocialI18n } from "@social/lib/useSocialI18n";
|
import { useSocialI18n } from "@social/lib/useSocialI18n";
|
||||||
import { coffeeApi } from "../lib/api";
|
import { coffeeApi } from "../lib/api";
|
||||||
import type { CoffeeBooking } from "../lib/types";
|
import type { CoffeeBooking } from "../lib/types";
|
||||||
|
import CoffeeReviewForm from "./CoffeeReviewForm";
|
||||||
import "./coffee.css";
|
import "./coffee.css";
|
||||||
|
|
||||||
export default function CoffeeBookingDetail({ id }: { id: string }) {
|
export default function CoffeeBookingDetail({ id }: { id: string }) {
|
||||||
@ -15,6 +17,7 @@ export default function CoffeeBookingDetail({ id }: { id: string }) {
|
|||||||
const zh = locale === "zh";
|
const zh = locale === "zh";
|
||||||
const [booking, setBooking] = useState<CoffeeBooking | null>(null);
|
const [booking, setBooking] = useState<CoffeeBooking | null>(null);
|
||||||
const [err, setErr] = useState<string | null>(null);
|
const [err, setErr] = useState<string | null>(null);
|
||||||
|
const me = typeof window !== "undefined" ? getGuestId() : "";
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
void coffeeApi
|
void coffeeApi
|
||||||
@ -28,6 +31,22 @@ export default function CoffeeBookingDetail({ id }: { id: string }) {
|
|||||||
setBooking(r.booking);
|
setBooking(r.booking);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const hostGuest =
|
||||||
|
booking?.host_id || booking?.host?.username || "";
|
||||||
|
const attendeeGuest = booking?.attendee.device || "";
|
||||||
|
// Attendee reviews host; host reviews attendee when device guest matches me
|
||||||
|
const reviewTarget =
|
||||||
|
me && hostGuest && me === attendeeGuest
|
||||||
|
? { guest: hostGuest, name: booking?.host?.name || "" }
|
||||||
|
: me && hostGuest && me === hostGuest && attendeeGuest
|
||||||
|
? {
|
||||||
|
guest: attendeeGuest,
|
||||||
|
name: booking?.attendee.name || "",
|
||||||
|
}
|
||||||
|
: hostGuest
|
||||||
|
? { guest: hostGuest, name: booking?.host?.name || "" }
|
||||||
|
: null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<SiteShell title={socialTx("预约详情")}>
|
<SiteShell title={socialTx("预约详情")}>
|
||||||
<div className="cf-root">
|
<div className="cf-root">
|
||||||
@ -86,6 +105,14 @@ export default function CoffeeBookingDetail({ id }: { id: string }) {
|
|||||||
{zh ? "去视频厅" : "Video room"}
|
{zh ? "去视频厅" : "Video room"}
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
|
{reviewTarget && booking.status !== "cancelled" ? (
|
||||||
|
<CoffeeReviewForm
|
||||||
|
bookingId={booking.id}
|
||||||
|
toGuest={reviewTarget.guest}
|
||||||
|
toName={reviewTarget.name}
|
||||||
|
zh={zh}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
</section>
|
</section>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
122
src/modules/coffee/components/CoffeeReviewForm.tsx
Normal file
122
src/modules/coffee/components/CoffeeReviewForm.tsx
Normal file
@ -0,0 +1,122 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState, type FormEvent } from "react";
|
||||||
|
import { socialApi } from "@social/lib/api";
|
||||||
|
import { socialTx } from "@social/lib/socialTx";
|
||||||
|
|
||||||
|
function ScoreRow({
|
||||||
|
label,
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
}: {
|
||||||
|
label: string;
|
||||||
|
value: number;
|
||||||
|
onChange: (n: number) => void;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<label className="cf-score-row">
|
||||||
|
<span>{label}</span>
|
||||||
|
<input
|
||||||
|
type="range"
|
||||||
|
min={1}
|
||||||
|
max={5}
|
||||||
|
step={1}
|
||||||
|
value={value}
|
||||||
|
onChange={(e) => onChange(Number(e.target.value))}
|
||||||
|
/>
|
||||||
|
<em>{value}</em>
|
||||||
|
</label>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function CoffeeReviewForm({
|
||||||
|
bookingId,
|
||||||
|
toGuest,
|
||||||
|
toName,
|
||||||
|
zh,
|
||||||
|
}: {
|
||||||
|
bookingId: string;
|
||||||
|
toGuest: string;
|
||||||
|
toName: string;
|
||||||
|
zh: boolean;
|
||||||
|
}) {
|
||||||
|
const [punctuality, setPunctuality] = useState(5);
|
||||||
|
const [chemistry, setChemistry] = useState(5);
|
||||||
|
const [professionalism, setProfessionalism] = useState(5);
|
||||||
|
const [text, setText] = useState("");
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [done, setDone] = useState(false);
|
||||||
|
const [err, setErr] = useState("");
|
||||||
|
|
||||||
|
if (!toGuest) return null;
|
||||||
|
|
||||||
|
const submit = async (e: FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (busy || done) return;
|
||||||
|
setBusy(true);
|
||||||
|
setErr("");
|
||||||
|
try {
|
||||||
|
await socialApi.postMeetupReview({
|
||||||
|
toGuest,
|
||||||
|
toName,
|
||||||
|
bookingId,
|
||||||
|
punctuality,
|
||||||
|
chemistry,
|
||||||
|
professionalism,
|
||||||
|
text,
|
||||||
|
});
|
||||||
|
setDone(true);
|
||||||
|
} catch (ex) {
|
||||||
|
setErr(ex instanceof Error ? ex.message : socialTx("评价失败"));
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (done) {
|
||||||
|
return (
|
||||||
|
<p className="cf-hint">
|
||||||
|
{zh ? "评价已提交,对方主页会显示平均分。" : "Review submitted."}
|
||||||
|
</p>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form className="cf-review" onSubmit={(ev) => void submit(ev)}>
|
||||||
|
<h3>{zh ? "见面评价(双向)" : "Meetup review"}</h3>
|
||||||
|
<p className="cf-hint">
|
||||||
|
{zh
|
||||||
|
? `评价 ${toName || "对方"} · 守时 / 聊得来 / 靠谱`
|
||||||
|
: `Rate ${toName || "peer"} · punctuality / chemistry / professionalism`}
|
||||||
|
</p>
|
||||||
|
<ScoreRow
|
||||||
|
label={zh ? "守时" : "Punctuality"}
|
||||||
|
value={punctuality}
|
||||||
|
onChange={setPunctuality}
|
||||||
|
/>
|
||||||
|
<ScoreRow
|
||||||
|
label={zh ? "聊得来" : "Chemistry"}
|
||||||
|
value={chemistry}
|
||||||
|
onChange={setChemistry}
|
||||||
|
/>
|
||||||
|
<ScoreRow
|
||||||
|
label={zh ? "靠谱" : "Professionalism"}
|
||||||
|
value={professionalism}
|
||||||
|
onChange={setProfessionalism}
|
||||||
|
/>
|
||||||
|
<label>
|
||||||
|
{zh ? "想说的话(选填)" : "Notes (optional)"}
|
||||||
|
<textarea
|
||||||
|
rows={3}
|
||||||
|
value={text}
|
||||||
|
onChange={(e) => setText(e.target.value)}
|
||||||
|
maxLength={800}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
{err ? <p className="cf-error">{err}</p> : null}
|
||||||
|
<button type="submit" className="cf-btn cf-btn-primary" disabled={busy}>
|
||||||
|
{busy ? (zh ? "提交中…" : "Sending…") : zh ? "提交评价" : "Submit review"}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -284,3 +284,51 @@
|
|||||||
.cf-event:hover { border-color: rgba(245, 158, 11, 0.4); }
|
.cf-event:hover { border-color: rgba(245, 158, 11, 0.4); }
|
||||||
.cf-event h3 { margin: 0; font-size: 1rem; }
|
.cf-event h3 { margin: 0; font-size: 1rem; }
|
||||||
.cf-list { display: grid; gap: 0.55rem; }
|
.cf-list { display: grid; gap: 0.55rem; }
|
||||||
|
|
||||||
|
.cf-review {
|
||||||
|
display: grid;
|
||||||
|
gap: 0.65rem;
|
||||||
|
margin-top: 1.15rem;
|
||||||
|
padding-top: 1rem;
|
||||||
|
border-top: 1px solid var(--cf-line);
|
||||||
|
}
|
||||||
|
.cf-review h3 {
|
||||||
|
margin: 0;
|
||||||
|
font-family: Syne, sans-serif;
|
||||||
|
font-size: 1.05rem;
|
||||||
|
}
|
||||||
|
.cf-review label {
|
||||||
|
display: grid;
|
||||||
|
gap: 0.3rem;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
color: var(--cf-muted);
|
||||||
|
}
|
||||||
|
.cf-review textarea {
|
||||||
|
min-height: 88px;
|
||||||
|
border-radius: 12px;
|
||||||
|
border: 1px solid var(--cf-line);
|
||||||
|
background: rgba(0, 0, 0, 0.25);
|
||||||
|
color: var(--cf-ink);
|
||||||
|
padding: 0.5rem 0.75rem;
|
||||||
|
font: inherit;
|
||||||
|
resize: vertical;
|
||||||
|
}
|
||||||
|
.cf-score-row {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: minmax(4.5rem, auto) 1fr auto;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.55rem;
|
||||||
|
font-size: 0.88rem;
|
||||||
|
color: var(--cf-muted);
|
||||||
|
}
|
||||||
|
.cf-score-row input[type="range"] {
|
||||||
|
width: 100%;
|
||||||
|
accent-color: var(--cf-amber);
|
||||||
|
}
|
||||||
|
.cf-score-row em {
|
||||||
|
font-style: normal;
|
||||||
|
font-weight: 700;
|
||||||
|
color: var(--cf-amber);
|
||||||
|
min-width: 1.2rem;
|
||||||
|
text-align: right;
|
||||||
|
}
|
||||||
|
|||||||
@ -63,6 +63,7 @@ export const coffeeApi = {
|
|||||||
start: string;
|
start: string;
|
||||||
attendee_name: string;
|
attendee_name: string;
|
||||||
attendee_email?: string;
|
attendee_email?: string;
|
||||||
|
attendee_device?: string;
|
||||||
location?: string;
|
location?: string;
|
||||||
notes?: string;
|
notes?: string;
|
||||||
}) =>
|
}) =>
|
||||||
|
|||||||
@ -65,6 +65,7 @@ export type CoffeeBooking = {
|
|||||||
end: string;
|
end: string;
|
||||||
location: string;
|
location: string;
|
||||||
notes: string;
|
notes: string;
|
||||||
|
host_id?: string;
|
||||||
attendee: { name: string; email?: string | null; device?: string | null };
|
attendee: { name: string; email?: string | null; device?: string | null };
|
||||||
host?: { username: string; name: string; city?: string } | null;
|
host?: { username: string; name: string; city?: string } | null;
|
||||||
created_at: string;
|
created_at: string;
|
||||||
|
|||||||
@ -192,6 +192,92 @@ export default function NotificationSettingsClient() {
|
|||||||
onChange={(v) => void patch({ in_app: v })}
|
onChange={(v) => void patch({ in_app: v })}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div className="ntf-setting ntf-setting-stack">
|
||||||
|
<div>
|
||||||
|
<h3>{zh ? "时区静默时段" : "Quiet hours"}</h3>
|
||||||
|
<p>
|
||||||
|
{zh
|
||||||
|
? "该时段内暂停邮件 / 推送 / 短信;站内收件箱仍可收到。默认 22:00–08:00。"
|
||||||
|
: "Mute email / push / SMS in this window. Inbox still receives. Default 22:00–08:00."}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="ntf-quiet-fields">
|
||||||
|
<label>
|
||||||
|
{zh ? "时区" : "Timezone"}
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={String(
|
||||||
|
prefs.channels.timezone ||
|
||||||
|
(prefs as { timezone?: string }).timezone ||
|
||||||
|
"Asia/Shanghai",
|
||||||
|
)}
|
||||||
|
onChange={(e) => void patch({ timezone: e.target.value })}
|
||||||
|
placeholder="Asia/Shanghai"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
{zh ? "开始" : "Start"}
|
||||||
|
<input
|
||||||
|
type="time"
|
||||||
|
value={String(
|
||||||
|
prefs.channels.quiet_start ||
|
||||||
|
(prefs as { quiet_start?: string }).quiet_start ||
|
||||||
|
"22:00",
|
||||||
|
).slice(0, 5)}
|
||||||
|
onChange={(e) => void patch({ quiet_start: e.target.value })}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
{zh ? "结束" : "End"}
|
||||||
|
<input
|
||||||
|
type="time"
|
||||||
|
value={String(
|
||||||
|
prefs.channels.quiet_end ||
|
||||||
|
(prefs as { quiet_end?: string }).quiet_end ||
|
||||||
|
"08:00",
|
||||||
|
).slice(0, 5)}
|
||||||
|
onChange={(e) => void patch({ quiet_end: e.target.value })}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="ntf-setting">
|
||||||
|
<div>
|
||||||
|
<h3>{zh ? "同城日报" : "Daily city digest"}</h3>
|
||||||
|
<p>
|
||||||
|
{zh
|
||||||
|
? "每天汇总同城上线与活动(走静默时段规则)。"
|
||||||
|
: "Daily same-city summary (respects quiet hours)."}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Switch
|
||||||
|
id="digest_daily"
|
||||||
|
checked={
|
||||||
|
prefs.channels.digest_daily !== false &&
|
||||||
|
(prefs as { digest_daily?: boolean }).digest_daily !== false
|
||||||
|
}
|
||||||
|
onChange={(v) => void patch({ digest_daily: v })}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="ntf-setting">
|
||||||
|
<div>
|
||||||
|
<h3>{zh ? "同城周报" : "Weekly city digest"}</h3>
|
||||||
|
<p>
|
||||||
|
{zh ? "每周一次同城摘要。" : "Weekly same-city digest."}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Switch
|
||||||
|
id="digest_weekly"
|
||||||
|
checked={
|
||||||
|
prefs.channels.digest_weekly !== false &&
|
||||||
|
(prefs as { digest_weekly?: boolean }).digest_weekly !== false
|
||||||
|
}
|
||||||
|
onChange={(v) => void patch({ digest_weekly: v })}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@ -455,3 +455,34 @@ html[data-theme="light"] .nav-notify-panel {
|
|||||||
border-radius: 18px;
|
border-radius: 18px;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.ntf-setting-stack {
|
||||||
|
align-items: start;
|
||||||
|
}
|
||||||
|
.ntf-quiet-fields {
|
||||||
|
display: grid;
|
||||||
|
gap: 0.55rem;
|
||||||
|
width: min(100%, 280px);
|
||||||
|
justify-self: end;
|
||||||
|
}
|
||||||
|
.ntf-quiet-fields label {
|
||||||
|
display: grid;
|
||||||
|
gap: 0.25rem;
|
||||||
|
font-size: 0.78rem;
|
||||||
|
color: var(--nt-muted);
|
||||||
|
}
|
||||||
|
.ntf-quiet-fields input {
|
||||||
|
min-height: 44px;
|
||||||
|
border-radius: 12px;
|
||||||
|
border: 1px solid var(--nt-line);
|
||||||
|
background: rgba(0, 0, 0, 0.25);
|
||||||
|
color: var(--nt-ink);
|
||||||
|
padding: 0.45rem 0.65rem;
|
||||||
|
font: inherit;
|
||||||
|
}
|
||||||
|
@media (max-width: 640px) {
|
||||||
|
.ntf-quiet-fields {
|
||||||
|
width: 100%;
|
||||||
|
justify-self: stretch;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@ -2591,6 +2591,243 @@
|
|||||||
width: 38px;
|
width: 38px;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
/* —— Skill swap · Wrapped · moderation · reviews —— */
|
||||||
|
.social-skills-compose {
|
||||||
|
display: grid;
|
||||||
|
gap: 0.75rem;
|
||||||
|
margin: 1rem 0 1.25rem;
|
||||||
|
padding: 1rem 1.05rem;
|
||||||
|
border-radius: 18px;
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.08);
|
||||||
|
background: rgba(255, 255, 255, 0.03);
|
||||||
|
}
|
||||||
|
.social-skills-compose h2 {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.4rem;
|
||||||
|
margin: 0;
|
||||||
|
font-size: 1rem;
|
||||||
|
}
|
||||||
|
.social-skills-compose label,
|
||||||
|
.social-moderation-sheet label,
|
||||||
|
.social-skills-filter {
|
||||||
|
display: grid;
|
||||||
|
gap: 0.3rem;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
color: rgba(244, 244, 245, 0.68);
|
||||||
|
}
|
||||||
|
.social-skills-compose input,
|
||||||
|
.social-skills-compose textarea,
|
||||||
|
.social-skills-filter input,
|
||||||
|
.social-moderation-sheet input,
|
||||||
|
.social-moderation-sheet select,
|
||||||
|
.social-moderation-sheet textarea {
|
||||||
|
min-height: 44px;
|
||||||
|
border-radius: 12px;
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||||
|
background: rgba(0, 0, 0, 0.28);
|
||||||
|
color: inherit;
|
||||||
|
padding: 0.5rem 0.75rem;
|
||||||
|
font: inherit;
|
||||||
|
}
|
||||||
|
.social-skills-compose textarea,
|
||||||
|
.social-moderation-sheet textarea {
|
||||||
|
min-height: 72px;
|
||||||
|
resize: vertical;
|
||||||
|
}
|
||||||
|
.social-skills-filter {
|
||||||
|
grid-template-columns: auto 1fr auto;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
.social-skills-grid {
|
||||||
|
display: grid;
|
||||||
|
gap: 0.75rem;
|
||||||
|
grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
|
||||||
|
}
|
||||||
|
.social-skills-card {
|
||||||
|
padding: 0.95rem 1rem;
|
||||||
|
border-radius: 16px;
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.08);
|
||||||
|
background: rgba(255, 255, 255, 0.025);
|
||||||
|
}
|
||||||
|
.social-skills-card header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 0.5rem;
|
||||||
|
font-size: 0.82rem;
|
||||||
|
color: rgba(244, 244, 245, 0.65);
|
||||||
|
margin-bottom: 0.55rem;
|
||||||
|
}
|
||||||
|
.social-skills-card header span {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.25rem;
|
||||||
|
}
|
||||||
|
.social-skills-swap {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.45rem;
|
||||||
|
margin: 0 0 0.4rem;
|
||||||
|
font-size: 0.95rem;
|
||||||
|
}
|
||||||
|
.social-skills-swap em {
|
||||||
|
font-style: normal;
|
||||||
|
color: #f59e0b;
|
||||||
|
font-weight: 650;
|
||||||
|
}
|
||||||
|
.social-skills-note {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 0.82rem;
|
||||||
|
color: rgba(244, 244, 245, 0.62);
|
||||||
|
line-height: 1.45;
|
||||||
|
}
|
||||||
|
|
||||||
|
.social-wrapped {
|
||||||
|
max-width: 720px;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 0.5rem 0 2.5rem;
|
||||||
|
}
|
||||||
|
.social-wrapped-kicker {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.35rem;
|
||||||
|
color: #f59e0b;
|
||||||
|
font-size: 0.82rem;
|
||||||
|
font-weight: 650;
|
||||||
|
margin: 0 0 0.5rem;
|
||||||
|
}
|
||||||
|
.social-wrapped h1 {
|
||||||
|
font-family: Syne, sans-serif;
|
||||||
|
font-size: clamp(1.6rem, 4vw, 2.2rem);
|
||||||
|
letter-spacing: -0.03em;
|
||||||
|
margin: 0 0 1rem;
|
||||||
|
}
|
||||||
|
.social-wrapped h1 span {
|
||||||
|
display: block;
|
||||||
|
font-size: 0.55em;
|
||||||
|
color: rgba(244, 244, 245, 0.55);
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
.social-wrapped-hero {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 0.75rem 1.25rem;
|
||||||
|
align-items: center;
|
||||||
|
margin-bottom: 1.25rem;
|
||||||
|
color: rgba(244, 244, 245, 0.72);
|
||||||
|
}
|
||||||
|
.social-wrapped-hero em {
|
||||||
|
font-style: normal;
|
||||||
|
color: #34d399;
|
||||||
|
font-weight: 650;
|
||||||
|
}
|
||||||
|
.social-wrapped-stats {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
gap: 0.75rem;
|
||||||
|
margin-bottom: 1.5rem;
|
||||||
|
}
|
||||||
|
@media (min-width: 640px) {
|
||||||
|
.social-wrapped-stats {
|
||||||
|
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.social-wrapped-stats > div {
|
||||||
|
display: grid;
|
||||||
|
gap: 0.25rem;
|
||||||
|
padding: 1rem 0.9rem;
|
||||||
|
border-radius: 16px;
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.08);
|
||||||
|
background: linear-gradient(
|
||||||
|
160deg,
|
||||||
|
rgba(245, 158, 11, 0.08),
|
||||||
|
rgba(255, 255, 255, 0.02)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
.social-wrapped-stats strong {
|
||||||
|
font-family: Syne, sans-serif;
|
||||||
|
font-size: 1.65rem;
|
||||||
|
letter-spacing: -0.03em;
|
||||||
|
}
|
||||||
|
.social-wrapped-stats span {
|
||||||
|
font-size: 0.78rem;
|
||||||
|
color: rgba(244, 244, 245, 0.6);
|
||||||
|
}
|
||||||
|
.social-wrapped-cities {
|
||||||
|
margin-bottom: 1.5rem;
|
||||||
|
}
|
||||||
|
.social-wrapped-cta {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 0.55rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.social-moderation {
|
||||||
|
margin: 1.25rem 0;
|
||||||
|
padding: 0.9rem 1rem;
|
||||||
|
border-radius: 16px;
|
||||||
|
border: 1px dashed rgba(255, 255, 255, 0.12);
|
||||||
|
}
|
||||||
|
.social-moderation-actions {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 0.45rem;
|
||||||
|
margin-bottom: 0.55rem;
|
||||||
|
}
|
||||||
|
.social-moderation-sheet {
|
||||||
|
display: grid;
|
||||||
|
gap: 0.65rem;
|
||||||
|
margin-top: 0.65rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.social-profile-reviews h2 {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.4rem;
|
||||||
|
}
|
||||||
|
.social-profile-reviews h2 em {
|
||||||
|
font-style: normal;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
color: #f59e0b;
|
||||||
|
font-weight: 650;
|
||||||
|
}
|
||||||
|
.social-review-avgs {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 0.55rem;
|
||||||
|
list-style: none;
|
||||||
|
padding: 0;
|
||||||
|
margin: 0.5rem 0 0.75rem;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
color: rgba(244, 244, 245, 0.7);
|
||||||
|
}
|
||||||
|
.social-review-list {
|
||||||
|
display: grid;
|
||||||
|
gap: 0.55rem;
|
||||||
|
}
|
||||||
|
.social-review-list blockquote {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0.65rem 0.8rem;
|
||||||
|
border-radius: 12px;
|
||||||
|
background: rgba(0, 0, 0, 0.22);
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.06);
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: auto 1fr;
|
||||||
|
gap: 0.55rem;
|
||||||
|
}
|
||||||
|
.social-review-list blockquote strong {
|
||||||
|
color: #f59e0b;
|
||||||
|
}
|
||||||
|
.social-review-list blockquote p {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 0.88rem;
|
||||||
|
color: rgba(244, 244, 245, 0.72);
|
||||||
|
}
|
||||||
|
|
||||||
@media (prefers-reduced-motion: reduce) {
|
@media (prefers-reduced-motion: reduce) {
|
||||||
html:has(.social-experience) {
|
html:has(.social-experience) {
|
||||||
scroll-behavior: auto;
|
scroll-behavior: auto;
|
||||||
|
|||||||
@ -2206,3 +2206,345 @@
|
|||||||
display: none;
|
display: none;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* —— Home UX boost: status / actions / skills / coffee —— */
|
||||||
|
.connection-hero.is-tight .connection-brand-mark {
|
||||||
|
margin: 0 0 10px;
|
||||||
|
font-size: clamp(28px, 4vw, 40px);
|
||||||
|
font-weight: 800;
|
||||||
|
letter-spacing: -0.04em;
|
||||||
|
line-height: 1.1;
|
||||||
|
color: var(--text-primary);
|
||||||
|
}
|
||||||
|
.connection-hero.is-tight .connection-copy h1 {
|
||||||
|
margin-top: 12px;
|
||||||
|
font-size: clamp(28px, 3.4vw, 48px);
|
||||||
|
}
|
||||||
|
.connection-actions-tight {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 10px;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
.connection-actions-tight .connection-join,
|
||||||
|
.connection-actions-tight .connection-secondary,
|
||||||
|
.connection-actions-tight .connection-film {
|
||||||
|
min-height: 44px;
|
||||||
|
}
|
||||||
|
.connection-actions-tight .connection-secondary {
|
||||||
|
border: 1px solid var(--connection-border);
|
||||||
|
border-radius: 999px;
|
||||||
|
padding-inline: 18px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-status-strip {
|
||||||
|
margin: 8px auto 18px;
|
||||||
|
}
|
||||||
|
.home-status-card {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: auto 1fr auto;
|
||||||
|
grid-template-areas:
|
||||||
|
"ava meta steps"
|
||||||
|
"hint hint hint"
|
||||||
|
"acts acts acts";
|
||||||
|
gap: 10px 14px;
|
||||||
|
align-items: center;
|
||||||
|
padding: 14px 16px;
|
||||||
|
border: 1px solid color-mix(in srgb, #f59e0b 28%, var(--connection-border));
|
||||||
|
border-radius: 16px;
|
||||||
|
background: linear-gradient(
|
||||||
|
120deg,
|
||||||
|
color-mix(in srgb, #f59e0b 8%, transparent),
|
||||||
|
color-mix(in srgb, #0c0c0f 80%, transparent)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
.home-status-ava {
|
||||||
|
grid-area: ava;
|
||||||
|
display: grid;
|
||||||
|
place-items: center;
|
||||||
|
border-radius: 50%;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
.home-status-meta {
|
||||||
|
grid-area: meta;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 2px;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.home-status-meta strong {
|
||||||
|
font-size: 15px;
|
||||||
|
color: var(--text-primary);
|
||||||
|
}
|
||||||
|
.home-status-meta span {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 4px;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
}
|
||||||
|
.home-status-steps {
|
||||||
|
grid-area: steps;
|
||||||
|
display: flex;
|
||||||
|
gap: 8px;
|
||||||
|
list-style: none;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
.home-status-steps li {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 5px;
|
||||||
|
min-height: 36px;
|
||||||
|
padding: 0 10px;
|
||||||
|
border-radius: 999px;
|
||||||
|
border: 1px solid var(--connection-border);
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
}
|
||||||
|
.home-status-steps li.is-done {
|
||||||
|
border-color: color-mix(in srgb, #4ecdc4 50%, transparent);
|
||||||
|
color: #4ecdc4;
|
||||||
|
}
|
||||||
|
.home-status-steps li.is-pending {
|
||||||
|
border-color: color-mix(in srgb, #f59e0b 50%, transparent);
|
||||||
|
color: #f59e0b;
|
||||||
|
}
|
||||||
|
.home-status-steps li.is-todo {
|
||||||
|
opacity: 0.75;
|
||||||
|
}
|
||||||
|
.home-status-hint {
|
||||||
|
grid-area: hint;
|
||||||
|
margin: 0;
|
||||||
|
font-size: 13px;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
}
|
||||||
|
.home-status-acts {
|
||||||
|
grid-area: acts;
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
.home-status-acts .btn {
|
||||||
|
min-height: 44px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-action-rail {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(5, minmax(0, 1fr));
|
||||||
|
gap: 10px;
|
||||||
|
margin-bottom: 28px;
|
||||||
|
}
|
||||||
|
.home-action-chip {
|
||||||
|
--chip-accent: var(--connection-mint);
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
min-height: 64px;
|
||||||
|
padding: 12px 12px;
|
||||||
|
border-radius: 14px;
|
||||||
|
border: 1px solid var(--connection-border);
|
||||||
|
background: color-mix(in srgb, var(--chip-accent) 6%, transparent);
|
||||||
|
transition:
|
||||||
|
transform 0.25s ease,
|
||||||
|
border-color 0.25s ease;
|
||||||
|
}
|
||||||
|
.home-action-chip.coral {
|
||||||
|
--chip-accent: var(--connection-coral);
|
||||||
|
}
|
||||||
|
.home-action-chip.yellow {
|
||||||
|
--chip-accent: var(--connection-yellow);
|
||||||
|
}
|
||||||
|
.home-action-chip.amber {
|
||||||
|
--chip-accent: #f59e0b;
|
||||||
|
}
|
||||||
|
.home-action-chip:hover {
|
||||||
|
transform: translateY(-2px);
|
||||||
|
border-color: color-mix(in srgb, var(--chip-accent) 45%, transparent);
|
||||||
|
}
|
||||||
|
.home-action-chip.is-soft-locked {
|
||||||
|
opacity: 0.88;
|
||||||
|
}
|
||||||
|
.home-action-ico {
|
||||||
|
display: grid;
|
||||||
|
place-items: center;
|
||||||
|
width: 40px;
|
||||||
|
height: 40px;
|
||||||
|
border-radius: 12px;
|
||||||
|
background: color-mix(in srgb, var(--chip-accent) 16%, transparent);
|
||||||
|
color: var(--chip-accent);
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
.home-action-copy {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 2px;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.home-action-copy strong {
|
||||||
|
font-size: 13px;
|
||||||
|
color: var(--text-primary);
|
||||||
|
}
|
||||||
|
.home-action-copy small {
|
||||||
|
font-size: 11px;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-skills-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
.home-skill-card {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 6px;
|
||||||
|
min-height: 120px;
|
||||||
|
padding: 14px;
|
||||||
|
border-radius: 14px;
|
||||||
|
border: 1px solid var(--connection-border);
|
||||||
|
background: color-mix(in srgb, #f59e0b 5%, transparent);
|
||||||
|
color: inherit;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
.home-skill-card:hover {
|
||||||
|
border-color: color-mix(in srgb, #f59e0b 40%, transparent);
|
||||||
|
}
|
||||||
|
.home-skill-city {
|
||||||
|
font-size: 11px;
|
||||||
|
color: #f59e0b;
|
||||||
|
letter-spacing: 0.04em;
|
||||||
|
}
|
||||||
|
.home-skill-card strong {
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
.home-skill-card p {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
line-height: 1.45;
|
||||||
|
}
|
||||||
|
.home-skill-card em {
|
||||||
|
font-style: normal;
|
||||||
|
color: var(--text-primary);
|
||||||
|
opacity: 0.7;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-coffee-card {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 16px;
|
||||||
|
padding: 18px;
|
||||||
|
border-radius: 16px;
|
||||||
|
border: 1px solid color-mix(in srgb, #f59e0b 35%, var(--connection-border));
|
||||||
|
background: linear-gradient(
|
||||||
|
110deg,
|
||||||
|
color-mix(in srgb, #f59e0b 12%, transparent),
|
||||||
|
transparent 70%
|
||||||
|
);
|
||||||
|
text-decoration: none;
|
||||||
|
color: inherit;
|
||||||
|
}
|
||||||
|
.home-coffee-copy {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 4px;
|
||||||
|
}
|
||||||
|
.home-coffee-copy em {
|
||||||
|
font-style: normal;
|
||||||
|
font-size: 11px;
|
||||||
|
color: #f59e0b;
|
||||||
|
letter-spacing: 0.06em;
|
||||||
|
}
|
||||||
|
.home-coffee-copy strong {
|
||||||
|
font-size: 16px;
|
||||||
|
}
|
||||||
|
.home-coffee-copy p {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 13px;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
}
|
||||||
|
.home-coffee-lock {
|
||||||
|
font-size: 12px;
|
||||||
|
color: #f59e0b;
|
||||||
|
}
|
||||||
|
.home-coffee-card .btn {
|
||||||
|
min-height: 44px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.home-wrapped-strip {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 12px;
|
||||||
|
margin: 18px 0 8px;
|
||||||
|
padding: 12px 14px;
|
||||||
|
border-radius: 12px;
|
||||||
|
border: 1px dashed color-mix(in srgb, #f59e0b 35%, transparent);
|
||||||
|
color: var(--text-secondary);
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
.home-wrapped-strip .btn {
|
||||||
|
min-height: 40px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.social-people-empty {
|
||||||
|
padding: 28px 16px;
|
||||||
|
text-align: center;
|
||||||
|
border: 1px dashed var(--connection-border);
|
||||||
|
border-radius: 14px;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
}
|
||||||
|
.social-people-empty p {
|
||||||
|
margin: 0 0 14px;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
}
|
||||||
|
.social-people-empty .social-section-actions {
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 980px) {
|
||||||
|
.home-action-rail {
|
||||||
|
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||||
|
}
|
||||||
|
.home-skills-grid {
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
}
|
||||||
|
.home-status-card {
|
||||||
|
grid-template-columns: auto 1fr;
|
||||||
|
grid-template-areas:
|
||||||
|
"ava meta"
|
||||||
|
"steps steps"
|
||||||
|
"hint hint"
|
||||||
|
"acts acts";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@media (max-width: 640px) {
|
||||||
|
.home-action-rail {
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
}
|
||||||
|
.home-action-chip {
|
||||||
|
min-height: 56px;
|
||||||
|
}
|
||||||
|
.home-skills-grid {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
.home-coffee-card {
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: flex-start;
|
||||||
|
}
|
||||||
|
.home-coffee-card .btn {
|
||||||
|
width: 100%;
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
.home-wrapped-strip {
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: stretch;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@ -6,6 +6,7 @@ import {
|
|||||||
useMemo,
|
useMemo,
|
||||||
useRef,
|
useRef,
|
||||||
useState,
|
useState,
|
||||||
|
useSyncExternalStore,
|
||||||
} from "react";
|
} from "react";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import type { SocialRosterMember } from "@social/lib/rosterMock";
|
import type { SocialRosterMember } from "@social/lib/rosterMock";
|
||||||
@ -14,26 +15,55 @@ import {
|
|||||||
useDiscoveryRoster,
|
useDiscoveryRoster,
|
||||||
} from "@social/lib/discoveryRoster";
|
} from "@social/lib/discoveryRoster";
|
||||||
import { useRosterLikes, setRosterLike } from "@social/lib/useRosterLikes";
|
import { useRosterLikes, setRosterLike } from "@social/lib/useRosterLikes";
|
||||||
|
import { loadJson } from "@social/lib/storage";
|
||||||
import { socialPath } from "@social/lib/socialPath";
|
import { socialPath } from "@social/lib/socialPath";
|
||||||
import SocialAvatar from "./SocialAvatar";
|
import SocialAvatar from "./SocialAvatar";
|
||||||
import SectionSpark from "./SectionSpark";
|
import SectionSpark from "./SectionSpark";
|
||||||
import { socialTx } from "@social/lib/socialTx";
|
import { socialTx } from "@social/lib/socialTx";
|
||||||
|
|
||||||
const FILTERS = [
|
const STORAGE_CHANGE = "nomadro-social-storage";
|
||||||
{ id: "all" as const, label: "全部", emoji: "✨" },
|
|
||||||
{ id: "online" as const, label: "在线", emoji: "🟢" },
|
function subscribeRosterCity(cb: () => void) {
|
||||||
{ id: "f" as const, label: "女生", emoji: "👩" },
|
window.addEventListener("storage", cb);
|
||||||
{ id: "m" as const, label: "男生", emoji: "👨" },
|
window.addEventListener(STORAGE_CHANGE, cb);
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener("storage", cb);
|
||||||
|
window.removeEventListener(STORAGE_CHANGE, cb);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
type FilterId = "all" | "online" | "city" | "liked" | "f" | "m";
|
||||||
|
|
||||||
|
const FILTERS: { id: FilterId; label: string; emoji: string }[] = [
|
||||||
|
{ id: "all", label: "全部", emoji: "✨" },
|
||||||
|
{ id: "online", label: "在线", emoji: "🟢" },
|
||||||
|
{ id: "city", label: "同城", emoji: "📍" },
|
||||||
|
{ id: "liked", label: "已关注", emoji: "♥" },
|
||||||
|
{ id: "f", label: "女生", emoji: "👩" },
|
||||||
|
{ id: "m", label: "男生", emoji: "👨" },
|
||||||
];
|
];
|
||||||
|
|
||||||
|
function cityKey(city: string) {
|
||||||
|
return city.split(/[·,,]/)[0]?.trim().toLowerCase() || "";
|
||||||
|
}
|
||||||
|
|
||||||
export default function AttractiveRoster({ onJoin }: { onJoin: () => void }) {
|
export default function AttractiveRoster({ onJoin }: { onJoin: () => void }) {
|
||||||
const roster = useDiscoveryRoster();
|
const roster = useDiscoveryRoster();
|
||||||
const likes = useRosterLikes();
|
const likes = useRosterLikes();
|
||||||
const [filter, setFilter] = useState<"all" | "online" | "f" | "m">("all");
|
const [filter, setFilter] = useState<FilterId>("all");
|
||||||
const [highlightId, setHighlightId] = useState<string | null>(null);
|
const [highlightId, setHighlightId] = useState<string | null>(null);
|
||||||
const [burst, setBurst] = useState(false);
|
const [burst, setBurst] = useState(false);
|
||||||
const burstTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
const burstTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||||
const filterId = useId();
|
const filterId = useId();
|
||||||
|
const profileCity = useSyncExternalStore(
|
||||||
|
subscribeRosterCity,
|
||||||
|
() => loadJson<{ city?: string }>("roster", {}).city || "",
|
||||||
|
() => "",
|
||||||
|
);
|
||||||
|
const myCity = useMemo(() => {
|
||||||
|
const self = roster.find((m) => m.id === SELF_MEMBER_ID);
|
||||||
|
return cityKey(self?.city || profileCity);
|
||||||
|
}, [roster, profileCity]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const selectMember = (event: Event) => {
|
const selectMember = (event: Event) => {
|
||||||
@ -62,9 +92,14 @@ export default function AttractiveRoster({ onJoin }: { onJoin: () => void }) {
|
|||||||
return roster.filter((m) => {
|
return roster.filter((m) => {
|
||||||
if (filter === "online") return m.online;
|
if (filter === "online") return m.online;
|
||||||
if (filter === "f" || filter === "m") return m.gender === filter;
|
if (filter === "f" || filter === "m") return m.gender === filter;
|
||||||
|
if (filter === "liked") return Boolean(likes[m.id]);
|
||||||
|
if (filter === "city") {
|
||||||
|
if (!myCity) return false;
|
||||||
|
return cityKey(m.city) === myCity;
|
||||||
|
}
|
||||||
return true;
|
return true;
|
||||||
});
|
});
|
||||||
}, [filter, roster]);
|
}, [filter, roster, likes, myCity]);
|
||||||
|
|
||||||
const online = useMemo(() => roster.filter((m) => m.online), [roster]);
|
const online = useMemo(() => roster.filter((m) => m.online), [roster]);
|
||||||
|
|
||||||
@ -81,6 +116,15 @@ export default function AttractiveRoster({ onJoin }: { onJoin: () => void }) {
|
|||||||
burstTimer.current = setTimeout(() => setBurst(false), 700);
|
burstTimer.current = setTimeout(() => setBurst(false), 700);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const emptyCopy =
|
||||||
|
filter === "city" && !myCity
|
||||||
|
? socialTx("先填写你的城市,才能筛同城的人")
|
||||||
|
: filter === "city"
|
||||||
|
? socialTx("暂时没有同城的人,先完善介绍或换个城市看看")
|
||||||
|
: filter === "liked"
|
||||||
|
? socialTx("还没有关注的人,点爱心收藏想见的人")
|
||||||
|
: socialTx("这里暂时没人,去写介绍或加入社区吧");
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section
|
<section
|
||||||
className="section section-compact"
|
className="section section-compact"
|
||||||
@ -101,10 +145,10 @@ export default function AttractiveRoster({ onJoin }: { onJoin: () => void }) {
|
|||||||
{socialTx("想见的人")}
|
{socialTx("想见的人")}
|
||||||
</h2>
|
</h2>
|
||||||
<p>
|
<p>
|
||||||
点开卡片,看看对方在做什么、想认识谁。
|
{socialTx("点开卡片,看看对方在做什么、想认识谁。")}
|
||||||
现在是示例介绍,方便你先逛逛
|
{socialTx("现在是示例介绍,方便你先逛逛")}
|
||||||
{roster.some((m) => m.id === SELF_MEMBER_ID)
|
{roster.some((m) => m.id === SELF_MEMBER_ID)
|
||||||
? "(也包含你写好的介绍)"
|
? socialTx("(也包含你写好的介绍)")
|
||||||
: ""}
|
: ""}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
@ -117,8 +161,8 @@ export default function AttractiveRoster({ onJoin }: { onJoin: () => void }) {
|
|||||||
</div>
|
</div>
|
||||||
<p>
|
<p>
|
||||||
<strong className="social-count-pulse">{online.length}</strong>{" "}
|
<strong className="social-count-pulse">{online.length}</strong>{" "}
|
||||||
位现在在线
|
{socialTx("位现在在线")}
|
||||||
<span> · 示例数据</span>
|
<span> · {socialTx("示例数据")}</span>
|
||||||
</p>
|
</p>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
@ -168,11 +212,33 @@ export default function AttractiveRoster({ onJoin }: { onJoin: () => void }) {
|
|||||||
document.getElementById(`${filterId}-${next.id}`)?.focus();
|
document.getElementById(`${filterId}-${next.id}`)?.focus();
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<span aria-hidden>{f.emoji}</span> {f.label}
|
<span aria-hidden>{f.emoji}</span> {socialTx(f.label)}
|
||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{list.length === 0 ? (
|
||||||
|
<div className="social-people-empty reveal">
|
||||||
|
<p>{emptyCopy}</p>
|
||||||
|
<div className="social-section-actions">
|
||||||
|
{(filter === "city" && !myCity) || filter === "all" ? (
|
||||||
|
<Link href={socialPath("/roster")} className="btn btn-primary">
|
||||||
|
{socialTx("去完善介绍")}
|
||||||
|
</Link>
|
||||||
|
) : null}
|
||||||
|
<button type="button" className="btn btn-ghost" onClick={onJoin}>
|
||||||
|
{socialTx("加入社区")}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn-ghost"
|
||||||
|
onClick={() => setFilter("all")}
|
||||||
|
>
|
||||||
|
{socialTx("看全部")}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
<div
|
<div
|
||||||
className="social-people-grid"
|
className="social-people-grid"
|
||||||
id={`${filterId}-panel`}
|
id={`${filterId}-panel`}
|
||||||
@ -198,7 +264,7 @@ export default function AttractiveRoster({ onJoin }: { onJoin: () => void }) {
|
|||||||
</span>
|
</span>
|
||||||
<strong>
|
<strong>
|
||||||
{m.name}
|
{m.name}
|
||||||
{m.id === SELF_MEMBER_ID ? " · 我" : ""}
|
{m.id === SELF_MEMBER_ID ? ` · ${socialTx("我")}` : ""}
|
||||||
</strong>
|
</strong>
|
||||||
<span className="connection-member-role">
|
<span className="connection-member-role">
|
||||||
{m.title}
|
{m.title}
|
||||||
@ -215,7 +281,9 @@ export default function AttractiveRoster({ onJoin }: { onJoin: () => void }) {
|
|||||||
role="button"
|
role="button"
|
||||||
tabIndex={0}
|
tabIndex={0}
|
||||||
className="social-people-chip-like"
|
className="social-people-chip-like"
|
||||||
aria-label={likes[m.id] ? "取消关注" : "关注"}
|
aria-label={
|
||||||
|
likes[m.id] ? socialTx("取消关注") : socialTx("关注")
|
||||||
|
}
|
||||||
onClick={(e) => toggleLike(e, m)}
|
onClick={(e) => toggleLike(e, m)}
|
||||||
onKeyDown={(e) => {
|
onKeyDown={(e) => {
|
||||||
if (e.key === "Enter" || e.key === " ") toggleLike(e, m);
|
if (e.key === "Enter" || e.key === " ") toggleLike(e, m);
|
||||||
@ -226,6 +294,7 @@ export default function AttractiveRoster({ onJoin }: { onJoin: () => void }) {
|
|||||||
</Link>
|
</Link>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{burst ? (
|
{burst ? (
|
||||||
<span className="social-burst social-burst-float" aria-hidden>
|
<span className="social-burst social-burst-float" aria-hidden>
|
||||||
@ -233,7 +302,9 @@ export default function AttractiveRoster({ onJoin }: { onJoin: () => void }) {
|
|||||||
</span>
|
</span>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
<p className="social-people-hint">👆 点卡片看看详情,也可以先点爱心关注</p>
|
<p className="social-people-hint">
|
||||||
|
{socialTx("👆 点卡片看看详情,也可以先点爱心关注")}
|
||||||
|
</p>
|
||||||
|
|
||||||
<div className="social-section-actions reveal">
|
<div className="social-section-actions reveal">
|
||||||
<Link href={socialPath("/people")} className="btn btn-primary">
|
<Link href={socialPath("/people")} className="btn btn-primary">
|
||||||
|
|||||||
@ -41,6 +41,7 @@ import {
|
|||||||
JOIN_RELATIONSHIP_OPTIONS,
|
JOIN_RELATIONSHIP_OPTIONS,
|
||||||
JOIN_STATUS_OPTIONS,
|
JOIN_STATUS_OPTIONS,
|
||||||
isJoinPaid,
|
isJoinPaid,
|
||||||
|
clearJoinProfileDone,
|
||||||
isJoinProfileDone,
|
isJoinProfileDone,
|
||||||
markJoinPaid,
|
markJoinPaid,
|
||||||
markJoinProfileDone,
|
markJoinProfileDone,
|
||||||
@ -244,8 +245,11 @@ function stepFromParam(param: string | null): JoinStep {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function resolveJoinStep(param: string | null): JoinStep {
|
function resolveJoinStep(param: string | null): JoinStep {
|
||||||
if (isJoinProfileDone() || param === "done") return "done";
|
// Explicit ?step=profile always opens the form (re-fill / localhost QA).
|
||||||
if (param === "profile" || isJoinPaid()) return "profile";
|
// Do not let a stale social-join-profile-done flag skip the form.
|
||||||
|
if (param === "profile") return "profile";
|
||||||
|
if (param === "done" || isJoinProfileDone()) return "done";
|
||||||
|
if (isJoinPaid()) return "profile";
|
||||||
return "pay";
|
return "pay";
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -348,7 +352,12 @@ function JoinProfileForm({ onDone }: { onDone: () => void }) {
|
|||||||
const avatarHint = (() => {
|
const avatarHint = (() => {
|
||||||
if (avatarBusy) return socialTx("检测人脸并上传中…");
|
if (avatarBusy) return socialTx("检测人脸并上传中…");
|
||||||
if (!capture.ready) return socialTx("检测设备中…");
|
if (!capture.ready) return socialTx("检测设备中…");
|
||||||
if (liveOk) return socialTx("真人核验已通过,头像可用于社区");
|
if (liveOk && (draft.avatar || "").trim()) {
|
||||||
|
return socialTx("头像已就绪 · 真人核验已通过,约会等功能已开放");
|
||||||
|
}
|
||||||
|
if (liveOk) {
|
||||||
|
return socialTx("真人核验已通过。请上传正脸照片作为头像(实拍仅用于核验,不是头像)");
|
||||||
|
}
|
||||||
if (faceOk) {
|
if (faceOk) {
|
||||||
return socialTx("已检测到人脸。请继续现场实拍(全程录像)以开放约会等功能");
|
return socialTx("已检测到人脸。请继续现场实拍(全程录像)以开放约会等功能");
|
||||||
}
|
}
|
||||||
@ -461,11 +470,10 @@ function JoinProfileForm({ onDone }: { onDone: () => void }) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const onSelfieChallenge = async (payload: SelfieCapturePayload) => {
|
const onSelfieChallenge = async (payload: SelfieCapturePayload) => {
|
||||||
|
// Live capture = liveness gate only — never replace album/selfie avatar
|
||||||
setAvatarBusy(true);
|
setAvatarBusy(true);
|
||||||
setAvatarErr("");
|
setAvatarErr("");
|
||||||
setErr("");
|
setErr("");
|
||||||
const preview = URL.createObjectURL(payload.front);
|
|
||||||
setDraft((current) => ({ ...current, avatar: preview }));
|
|
||||||
try {
|
try {
|
||||||
const uploaded = await socialApi.uploadAvatarChallenge(
|
const uploaded = await socialApi.uploadAvatarChallenge(
|
||||||
payload.front,
|
payload.front,
|
||||||
@ -473,32 +481,17 @@ function JoinProfileForm({ onDone }: { onDone: () => void }) {
|
|||||||
payload.video,
|
payload.video,
|
||||||
payload.videoMime,
|
payload.videoMime,
|
||||||
);
|
);
|
||||||
const url = (uploaded?.url || "").trim();
|
|
||||||
if (!url) throw new Error(socialTx("头像上传失败"));
|
|
||||||
setDraft((current) => {
|
|
||||||
const next = { ...current, avatar: url };
|
|
||||||
saveJson("join-profile", next);
|
|
||||||
const roster = loadJson<SocialRosterProfile>("roster", {
|
|
||||||
name: "",
|
|
||||||
title: "",
|
|
||||||
city: "",
|
|
||||||
phone: "",
|
|
||||||
linktree: "",
|
|
||||||
skills: "",
|
|
||||||
bio: "",
|
|
||||||
avatar: "",
|
|
||||||
});
|
|
||||||
saveJson("roster", { ...roster, avatar: url });
|
|
||||||
return next;
|
|
||||||
});
|
|
||||||
markFaceOk();
|
markFaceOk();
|
||||||
markLivenessVerified({ videoUrl: uploaded.videoUrl || "" });
|
markLivenessVerified({ videoUrl: uploaded.videoUrl || "" });
|
||||||
setFaceOk(true);
|
setFaceOk(true);
|
||||||
setLiveOk(true);
|
setLiveOk(true);
|
||||||
setAvatarErr("");
|
setAvatarErr("");
|
||||||
requestAnimationFrame(() => URL.revokeObjectURL(preview));
|
if (!(draft.avatar || "").trim()) {
|
||||||
|
setAvatarErr(
|
||||||
|
socialTx("真人核验已通过。请再上传一张正脸照片作为头像(相册或自拍)。"),
|
||||||
|
);
|
||||||
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
URL.revokeObjectURL(preview);
|
|
||||||
const raw =
|
const raw =
|
||||||
e instanceof Error ? e.message.slice(0, 160).trim() : "";
|
e instanceof Error ? e.message.slice(0, 160).trim() : "";
|
||||||
setAvatarErr(
|
setAvatarErr(
|
||||||
@ -1073,13 +1066,17 @@ export function CommunityJoin() {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const next = resolveJoinStep(stepParam);
|
const next = resolveJoinStep(stepParam);
|
||||||
setStep(next);
|
setStep(next);
|
||||||
if (next === "profile" && !isJoinPaid()) {
|
if (next === "profile") {
|
||||||
// Arrived via ?step=profile after pay confirm
|
// Explicit profile step → allow re-fill even if done flag was set earlier
|
||||||
|
clearJoinProfileDone();
|
||||||
|
if (!isJoinPaid()) {
|
||||||
|
// Arrived via ?step=profile after pay confirm / localhost skip
|
||||||
markJoinPaid();
|
markJoinPaid();
|
||||||
}
|
}
|
||||||
if (next === "profile" && stepParam !== "profile") {
|
if (stepParam !== "profile") {
|
||||||
router.replace(JOIN_PROFILE_RETURN);
|
router.replace(JOIN_PROFILE_RETURN);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}, [stepParam, router]);
|
}, [stepParam, router]);
|
||||||
|
|
||||||
const goDone = () => {
|
const goDone = () => {
|
||||||
|
|||||||
@ -1,25 +1,18 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useEffect, useRef, useState, type CSSProperties } from "react";
|
import { useEffect, useRef, useState, type CSSProperties } from "react";
|
||||||
import Link from "next/link";
|
|
||||||
import {
|
import {
|
||||||
ArrowDown,
|
ArrowDown,
|
||||||
ArrowUpRight,
|
ArrowUpRight,
|
||||||
Coffee,
|
Coffee,
|
||||||
Globe2,
|
Globe2,
|
||||||
Heart,
|
|
||||||
MessageCircle,
|
|
||||||
MoveUpRight,
|
MoveUpRight,
|
||||||
Play,
|
Play,
|
||||||
Radio,
|
|
||||||
Sparkles,
|
Sparkles,
|
||||||
Users,
|
|
||||||
X,
|
X,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { socialPath } from "@social/lib/socialPath";
|
|
||||||
import { useAudienceRoster } from "@social/lib/useAudienceRoster";
|
import { useAudienceRoster } from "@social/lib/useAudienceRoster";
|
||||||
import SocialAvatar from "./SocialAvatar";
|
import SocialAvatar from "./SocialAvatar";
|
||||||
import FloatingEmojiField from "./FloatingEmojiField";
|
|
||||||
import type { SocialLandingCopy } from "@social/lib/landing";
|
import type { SocialLandingCopy } from "@social/lib/landing";
|
||||||
import { useSocialI18n } from "@social/lib/useSocialI18n";
|
import { useSocialI18n } from "@social/lib/useSocialI18n";
|
||||||
import { socialTx } from "@social/lib/socialTx";
|
import { socialTx } from "@social/lib/socialTx";
|
||||||
@ -67,17 +60,16 @@ export default function ConnectionHero({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<section
|
<section
|
||||||
className="connection-hero"
|
className="connection-hero is-tight"
|
||||||
id="hero"
|
id="hero"
|
||||||
aria-labelledby="connection-title"
|
aria-labelledby="connection-title"
|
||||||
>
|
>
|
||||||
<div className="connection-hero-grid" aria-hidden="true" />
|
<div className="connection-hero-grid" aria-hidden="true" />
|
||||||
<FloatingEmojiField />
|
|
||||||
<div className="container connection-hero-layout">
|
<div className="container connection-hero-layout">
|
||||||
<div className="connection-copy">
|
<div className="connection-copy">
|
||||||
|
<p className="connection-brand-mark">{t.brand}</p>
|
||||||
<div className="connection-eyebrow">
|
<div className="connection-eyebrow">
|
||||||
<span className="connection-status-dot" /> {t.brand}{" "}
|
<span className="connection-status-dot" /> {copy.socialEyebrow}
|
||||||
<span className="connection-eyebrow-divider" /> {copy.socialEyebrow}
|
|
||||||
</div>
|
</div>
|
||||||
<h1 id="connection-title">
|
<h1 id="connection-title">
|
||||||
{copy.socialHeroLine1}
|
{copy.socialHeroLine1}
|
||||||
@ -88,35 +80,27 @@ export default function ConnectionHero({
|
|||||||
</span>
|
</span>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
还好
|
{socialTx("还好")}
|
||||||
<span className="connection-title-accent">
|
<span className="connection-title-accent">
|
||||||
{copy.socialHeroAccent}
|
{copy.socialHeroAccent}
|
||||||
</span>
|
</span>
|
||||||
不远<span className="connection-title-period">。</span>
|
{socialTx("不远")}
|
||||||
|
<span className="connection-title-period">。</span>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</h1>
|
</h1>
|
||||||
<p className="connection-description">{copy.socialHeroLead}</p>
|
<p className="connection-description">{copy.socialHeroLead}</p>
|
||||||
<div className="connection-actions">
|
<div className="connection-actions connection-actions-tight">
|
||||||
|
<a className="btn connection-join" href="#people">
|
||||||
|
{socialTx("找同频的人")} <ArrowUpRight size={19} />
|
||||||
|
</a>
|
||||||
<button
|
<button
|
||||||
className="btn connection-join"
|
className="btn btn-ghost connection-secondary"
|
||||||
type="button"
|
type="button"
|
||||||
onClick={onJoin}
|
onClick={onJoin}
|
||||||
>
|
>
|
||||||
{copy.socialJoinCta} <ArrowUpRight size={19} />
|
{copy.socialJoinCta}
|
||||||
</button>
|
</button>
|
||||||
<Link className="connection-film" href={socialPath("/chat")}>
|
|
||||||
<span>
|
|
||||||
<Users size={13} />
|
|
||||||
</span>
|
|
||||||
{copy.socialWayGroup}
|
|
||||||
</Link>
|
|
||||||
<Link className="connection-film" href={socialPath("/date")}>
|
|
||||||
<span>
|
|
||||||
<Heart size={13} />
|
|
||||||
</span>
|
|
||||||
{copy.socialWayDate}
|
|
||||||
</Link>
|
|
||||||
<button
|
<button
|
||||||
ref={triggerRef}
|
ref={triggerRef}
|
||||||
className="connection-film connection-film-story"
|
className="connection-film connection-film-story"
|
||||||
@ -370,78 +354,8 @@ export default function ConnectionHero({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @deprecated Prefer HomeActionRail on the homepage — kept for import safety. */
|
||||||
export function ConnectionWays({ copy }: { copy: SocialLandingCopy }) {
|
export function ConnectionWays({ copy }: { copy: SocialLandingCopy }) {
|
||||||
const ways = [
|
void copy;
|
||||||
{
|
return null;
|
||||||
id: "01",
|
|
||||||
href: "/chat",
|
|
||||||
icon: MessageCircle,
|
|
||||||
title: copy.socialWayGroup,
|
|
||||||
sub: "大家一起聊 · 先打个招呼",
|
|
||||||
cta: "进群聊",
|
|
||||||
className: "mint",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "02",
|
|
||||||
href: "/date",
|
|
||||||
icon: Heart,
|
|
||||||
title: copy.socialWayDate,
|
|
||||||
sub: "左右滑,慢慢认识",
|
|
||||||
cta: "开始看看",
|
|
||||||
className: "coral",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "03",
|
|
||||||
href: "/meetup",
|
|
||||||
icon: Radio,
|
|
||||||
title: copy.socialWayChat,
|
|
||||||
sub: "聊天群组 · 语音视频",
|
|
||||||
cta: "去聊聊",
|
|
||||||
className: "mint",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "04",
|
|
||||||
href: "/places",
|
|
||||||
icon: Coffee,
|
|
||||||
title: copy.socialWayCafe,
|
|
||||||
sub: copy.socialOfflineTitle,
|
|
||||||
cta: "逛城市",
|
|
||||||
className: "yellow",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "05",
|
|
||||||
href: "/team",
|
|
||||||
icon: Users,
|
|
||||||
title: copy.socialWayTeam,
|
|
||||||
sub: copy.socialTeamTitle,
|
|
||||||
cta: "看看机会",
|
|
||||||
className: "mint",
|
|
||||||
},
|
|
||||||
];
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
className="container connection-ways is-alive"
|
|
||||||
aria-label={socialTx("选择连接方式")}
|
|
||||||
>
|
|
||||||
{ways.map((way, index) => (
|
|
||||||
<Link
|
|
||||||
href={socialPath(way.href)}
|
|
||||||
className={`connection-way ${way.className}`}
|
|
||||||
key={way.id}
|
|
||||||
style={{ ["--stagger" as string]: `${index * 70}ms` }}
|
|
||||||
>
|
|
||||||
<span className="connection-way-index">{way.id}</span>
|
|
||||||
<span className="connection-way-icon">
|
|
||||||
<way.icon size={23} strokeWidth={1.5} />
|
|
||||||
</span>
|
|
||||||
<span className="connection-way-copy">
|
|
||||||
<strong>{way.title}</strong>
|
|
||||||
<small>{way.sub}</small>
|
|
||||||
<em>{way.cta}</em>
|
|
||||||
</span>
|
|
||||||
<ArrowUpRight className="connection-way-arrow" size={19} />
|
|
||||||
</Link>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -26,6 +26,8 @@ import { useDiscoveryRoster, SELF_MEMBER_ID } from "@social/lib/discoveryRoster"
|
|||||||
import { socialPath } from "@social/lib/socialPath";
|
import { socialPath } from "@social/lib/socialPath";
|
||||||
import { setRosterLike, useRosterLikes } from "@social/lib/useRosterLikes";
|
import { setRosterLike, useRosterLikes } from "@social/lib/useRosterLikes";
|
||||||
import { useLocalState } from "@social/lib/useLocalState";
|
import { useLocalState } from "@social/lib/useLocalState";
|
||||||
|
import { socialApi } from "@social/lib/api";
|
||||||
|
import { loadJson } from "@social/lib/storage";
|
||||||
import { socialTx } from "@social/lib/socialTx";
|
import { socialTx } from "@social/lib/socialTx";
|
||||||
|
|
||||||
type Filter = "all" | "f" | "m";
|
type Filter = "all" | "f" | "m";
|
||||||
@ -126,6 +128,10 @@ export default function DateClient() {
|
|||||||
setRosterLike(member.id, true);
|
setRosterLike(member.id, true);
|
||||||
setMatchId(member.id);
|
setMatchId(member.id);
|
||||||
flash(`想认识 ${member.name}`);
|
flash(`想认识 ${member.name}`);
|
||||||
|
const me = loadJson<{ name?: string }>("roster", {});
|
||||||
|
void socialApi
|
||||||
|
.notifyLike(member.id, me.name || "游民")
|
||||||
|
.catch(() => undefined);
|
||||||
} else {
|
} else {
|
||||||
flash("已跳过");
|
flash("已跳过");
|
||||||
}
|
}
|
||||||
|
|||||||
104
src/modules/social/components/HomeActionRail.tsx
Normal file
104
src/modules/social/components/HomeActionRail.tsx
Normal file
@ -0,0 +1,104 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import Link from "next/link";
|
||||||
|
import {
|
||||||
|
ArrowLeftRight,
|
||||||
|
Coffee,
|
||||||
|
Heart,
|
||||||
|
Map,
|
||||||
|
Users,
|
||||||
|
} from "lucide-react";
|
||||||
|
import { socialPath } from "@social/lib/socialPath";
|
||||||
|
import { socialTx } from "@social/lib/socialTx";
|
||||||
|
import { useHomeLivenessGate } from "./HomeStatusStrip";
|
||||||
|
|
||||||
|
type Action = {
|
||||||
|
id: string;
|
||||||
|
href: string;
|
||||||
|
gated?: boolean;
|
||||||
|
icon: typeof Users;
|
||||||
|
title: string;
|
||||||
|
sub: string;
|
||||||
|
className: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function HomeActionRail() {
|
||||||
|
const { liveOk, verifyHref } = useHomeLivenessGate();
|
||||||
|
|
||||||
|
const actions: Action[] = [
|
||||||
|
{
|
||||||
|
id: "people",
|
||||||
|
href: "#people",
|
||||||
|
icon: Users,
|
||||||
|
title: socialTx("想见的人"),
|
||||||
|
sub: socialTx("先逛逛同频"),
|
||||||
|
className: "mint",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "date",
|
||||||
|
href: socialPath("/date"),
|
||||||
|
gated: true,
|
||||||
|
icon: Heart,
|
||||||
|
title: socialTx("左右滑"),
|
||||||
|
sub: socialTx("一张一张认识"),
|
||||||
|
className: "coral",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "coffee",
|
||||||
|
href: socialPath("/coffeechat"),
|
||||||
|
gated: true,
|
||||||
|
icon: Coffee,
|
||||||
|
title: socialTx("咖啡聊"),
|
||||||
|
sub: socialTx("约一杯见面"),
|
||||||
|
className: "amber",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "skills",
|
||||||
|
href: socialPath("/skills"),
|
||||||
|
icon: ArrowLeftRight,
|
||||||
|
title: socialTx("技能板"),
|
||||||
|
sub: socialTx("互换互助"),
|
||||||
|
className: "mint",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "map",
|
||||||
|
href: socialPath("/map"),
|
||||||
|
gated: true,
|
||||||
|
icon: Map,
|
||||||
|
title: socialTx("地图"),
|
||||||
|
sub: socialTx("同城足迹"),
|
||||||
|
className: "yellow",
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<nav
|
||||||
|
className="container home-action-rail reveal"
|
||||||
|
aria-label={socialTx("行动入口")}
|
||||||
|
>
|
||||||
|
{actions.map((action, index) => {
|
||||||
|
const locked = Boolean(action.gated) && !liveOk;
|
||||||
|
const href = locked ? verifyHref : action.href;
|
||||||
|
const Icon = action.icon;
|
||||||
|
return (
|
||||||
|
<Link
|
||||||
|
key={action.id}
|
||||||
|
href={href}
|
||||||
|
className={`home-action-chip ${action.className}${locked ? " is-soft-locked" : ""}`}
|
||||||
|
style={{ ["--stagger" as string]: `${index * 50}ms` }}
|
||||||
|
>
|
||||||
|
<span className="home-action-ico" aria-hidden>
|
||||||
|
<Icon size={20} strokeWidth={1.6} />
|
||||||
|
</span>
|
||||||
|
<span className="home-action-copy">
|
||||||
|
<strong>{action.title}</strong>
|
||||||
|
<small>
|
||||||
|
{locked ? socialTx("先完成实拍") : action.sub}
|
||||||
|
</small>
|
||||||
|
</span>
|
||||||
|
</Link>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</nav>
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -5,7 +5,11 @@ import Link from "next/link";
|
|||||||
import SiteShell from "./SiteShell";
|
import SiteShell from "./SiteShell";
|
||||||
import JoinPayModal from "./JoinPayModal";
|
import JoinPayModal from "./JoinPayModal";
|
||||||
import AttractiveRoster from "./AttractiveRoster";
|
import AttractiveRoster from "./AttractiveRoster";
|
||||||
import ConnectionHero, { ConnectionWays } from "./ConnectionHero";
|
import ConnectionHero from "./ConnectionHero";
|
||||||
|
import HomeStatusStrip, { useHomeLivenessGate } from "./HomeStatusStrip";
|
||||||
|
import HomeActionRail from "./HomeActionRail";
|
||||||
|
import HomeSkillsPreview from "./HomeSkillsPreview";
|
||||||
|
import HomeCoffeeEntry from "./HomeCoffeeEntry";
|
||||||
import FxBelt from "./FxBelt";
|
import FxBelt from "./FxBelt";
|
||||||
import SectionSpark from "./SectionSpark";
|
import SectionSpark from "./SectionSpark";
|
||||||
import CityDirectory from "./CityDirectory";
|
import CityDirectory from "./CityDirectory";
|
||||||
@ -46,6 +50,7 @@ export default function HomeClient() {
|
|||||||
const config = useSocialConfig();
|
const config = useSocialConfig();
|
||||||
const { locale, t } = useSocialI18n();
|
const { locale, t } = useSocialI18n();
|
||||||
const roster = useDiscoveryRoster();
|
const roster = useDiscoveryRoster();
|
||||||
|
const { liveOk, verifyHref } = useHomeLivenessGate();
|
||||||
const [joinOpen, setJoinOpen] = useState(false);
|
const [joinOpen, setJoinOpen] = useState(false);
|
||||||
const [activeSection, setActiveSection] = useState("people");
|
const [activeSection, setActiveSection] = useState("people");
|
||||||
const promoUrl =
|
const promoUrl =
|
||||||
@ -139,7 +144,8 @@ export default function HomeClient() {
|
|||||||
promoUrl={promoUrl}
|
promoUrl={promoUrl}
|
||||||
copy={landingCopy}
|
copy={landingCopy}
|
||||||
/>
|
/>
|
||||||
<ConnectionWays copy={landingCopy} />
|
<HomeStatusStrip />
|
||||||
|
<HomeActionRail />
|
||||||
|
|
||||||
<nav className="social-path" aria-label={socialTx("本页导航")}>
|
<nav className="social-path" aria-label={socialTx("本页导航")}>
|
||||||
<div className="container">
|
<div className="container">
|
||||||
@ -407,29 +413,40 @@ export default function HomeClient() {
|
|||||||
</div>
|
</div>
|
||||||
<div className="social-map-teaser reveal">
|
<div className="social-map-teaser reveal">
|
||||||
<div className="social-map-teaser-copy">
|
<div className="social-map-teaser-copy">
|
||||||
<strong>地图摘要</strong>
|
<strong>{socialTx("地图摘要")}</strong>
|
||||||
<p>热门城市聚合 · 不暴露精确位置</p>
|
<p>{socialTx("热门城市聚合 · 不暴露精确位置")}</p>
|
||||||
<div className="social-map-teaser-chips">
|
<div className="social-map-teaser-chips">
|
||||||
{["清迈", "巴厘岛", "大理", "里斯本", "成都"].map((name) => (
|
{[
|
||||||
|
socialTx("清迈"),
|
||||||
|
socialTx("巴厘岛"),
|
||||||
|
socialTx("大理"),
|
||||||
|
socialTx("里斯本"),
|
||||||
|
socialTx("成都"),
|
||||||
|
].map((name) => (
|
||||||
<span key={name}>{name}</span>
|
<span key={name}>{name}</span>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<Link href={socialPath("/map")} className="btn btn-primary">
|
<Link
|
||||||
打开地图
|
href={liveOk ? socialPath("/map") : verifyHref}
|
||||||
|
className="btn btn-primary"
|
||||||
|
>
|
||||||
|
{liveOk
|
||||||
|
? socialTx("打开地图")
|
||||||
|
: socialTx("去完善核验")}
|
||||||
<ArrowUpRight size={15} aria-hidden />
|
<ArrowUpRight size={15} aria-hidden />
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
<CityDirectory compact limit={8} />
|
<CityDirectory compact limit={8} />
|
||||||
<div className="social-section-actions reveal">
|
<div className="social-section-actions reveal">
|
||||||
<Link href={socialPath("/places")} className="btn btn-primary">
|
<Link href={socialPath("/places")} className="btn btn-primary">
|
||||||
逛城市
|
{socialTx("逛城市")}
|
||||||
</Link>
|
</Link>
|
||||||
<Link
|
<Link
|
||||||
href={socialPath("/places?tab=cafes")}
|
href={socialPath("/places?tab=cafes")}
|
||||||
className="btn btn-ghost"
|
className="btn btn-ghost"
|
||||||
>
|
>
|
||||||
咖啡馆见面
|
{socialTx("咖啡馆见面")}
|
||||||
</Link>
|
</Link>
|
||||||
<Link href={socialPath("/people")} className="btn btn-ghost">
|
<Link href={socialPath("/people")} className="btn btn-ghost">
|
||||||
{socialTx("找同城的人")}
|
{socialTx("找同城的人")}
|
||||||
@ -438,6 +455,9 @@ export default function HomeClient() {
|
|||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<HomeCoffeeEntry />
|
||||||
|
<FxBelt />
|
||||||
|
<HomeSkillsPreview />
|
||||||
<FxBelt />
|
<FxBelt />
|
||||||
|
|
||||||
<section
|
<section
|
||||||
@ -616,15 +636,26 @@ export default function HomeClient() {
|
|||||||
</div>
|
</div>
|
||||||
<div className="footer-links footer-links-more">
|
<div className="footer-links footer-links-more">
|
||||||
<h4>{socialTx("更多")}</h4>
|
<h4>{socialTx("更多")}</h4>
|
||||||
|
<Link href={socialPath("/skills")}>{socialTx("技能交换")}</Link>
|
||||||
|
<Link href={socialPath("/coffeechat")}>
|
||||||
|
{socialTx("咖啡聊预约")}
|
||||||
|
</Link>
|
||||||
|
<Link href={socialPath("/wrapped")}>{socialTx("年度回顾")}</Link>
|
||||||
<Link href="/">{socialTx("门户首页")}</Link>
|
<Link href="/">{socialTx("门户首页")}</Link>
|
||||||
<Link href="/community">{socialTx("旅居社群")}</Link>
|
<Link href="/community">{socialTx("旅居社群")}</Link>
|
||||||
<Link href="/book">{socialTx("数字游民小册")}</Link>
|
<Link href="/book">{socialTx("数字游民小册")}</Link>
|
||||||
<Link href={socialPath("/blog")}>{socialTx("博客")}</Link>
|
<Link href={socialPath("/blog")}>{socialTx("博客")}</Link>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div className="home-wrapped-strip">
|
||||||
|
<span>{socialTx("回看这一年的足迹与遇见")}</span>
|
||||||
|
<Link href={socialPath("/wrapped")} className="btn btn-ghost btn-sm">
|
||||||
|
{socialTx("年度回顾")} <ArrowUpRight size={14} />
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
<div className="footer-bottom social-home-footer-bottom">
|
<div className="footer-bottom social-home-footer-bottom">
|
||||||
<p suppressHydrationWarning>
|
<p suppressHydrationWarning>
|
||||||
© {new Date().getFullYear()} nomadro · 游民社区
|
© {new Date().getFullYear()} nomadro · {socialTx("游民社区")}
|
||||||
</p>
|
</p>
|
||||||
<div className="social-home-follow-row">
|
<div className="social-home-follow-row">
|
||||||
<Link href={socialPath("/blog")}>{socialTx("博客")}</Link>
|
<Link href={socialPath("/blog")}>{socialTx("博客")}</Link>
|
||||||
|
|||||||
73
src/modules/social/components/HomeCoffeeEntry.tsx
Normal file
73
src/modules/social/components/HomeCoffeeEntry.tsx
Normal file
@ -0,0 +1,73 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import Link from "next/link";
|
||||||
|
import { ArrowUpRight, Coffee } from "lucide-react";
|
||||||
|
import { socialPath } from "@social/lib/socialPath";
|
||||||
|
import { socialTx } from "@social/lib/socialTx";
|
||||||
|
import { useHomeLivenessGate } from "./HomeStatusStrip";
|
||||||
|
import SectionSpark from "./SectionSpark";
|
||||||
|
import SocialAvatar from "./SocialAvatar";
|
||||||
|
|
||||||
|
const HOST = {
|
||||||
|
name: "Alice",
|
||||||
|
city: "清迈 · Chiang Mai",
|
||||||
|
avatar:
|
||||||
|
"https://api.dicebear.com/7.x/lorelei/svg?seed=AliceHost&backgroundColor=f59e0b",
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function HomeCoffeeEntry() {
|
||||||
|
const { liveOk, verifyHref } = useHomeLivenessGate();
|
||||||
|
const href = liveOk ? socialPath("/coffeechat") : verifyHref;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section
|
||||||
|
className="section section-compact"
|
||||||
|
id="coffeechat"
|
||||||
|
aria-label={socialTx("咖啡聊")}
|
||||||
|
>
|
||||||
|
<div className="container">
|
||||||
|
<div className="section-header reveal">
|
||||||
|
<SectionSpark label="coffee" />
|
||||||
|
<span className="section-tag">
|
||||||
|
<span>{socialTx("咖啡聊")}</span>
|
||||||
|
<span>{socialTx("约一杯见面")}</span>
|
||||||
|
</span>
|
||||||
|
<h2>
|
||||||
|
<span className="social-title-emoji" aria-hidden>
|
||||||
|
☕
|
||||||
|
</span>
|
||||||
|
{socialTx("咖啡聊预约")}
|
||||||
|
</h2>
|
||||||
|
<p>
|
||||||
|
{socialTx(
|
||||||
|
"不想自己硬约?先和主持人喝杯咖啡,轻松认识同城游民。",
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Link href={href} className="home-coffee-card reveal">
|
||||||
|
<SocialAvatar src={HOST.avatar} size={64} />
|
||||||
|
<div className="home-coffee-copy">
|
||||||
|
<em>{socialTx("主持人")}</em>
|
||||||
|
<strong>
|
||||||
|
{HOST.name} · {HOST.city}
|
||||||
|
</strong>
|
||||||
|
<p>
|
||||||
|
{socialTx("数字游民主持人 · 咖啡馆轻聊,帮你破冰同城")}
|
||||||
|
</p>
|
||||||
|
{!liveOk ? (
|
||||||
|
<span className="home-coffee-lock">
|
||||||
|
{socialTx("完成实拍后可预约")}
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
<span className="btn btn-primary btn-sm">
|
||||||
|
<Coffee size={14} />{" "}
|
||||||
|
{liveOk ? socialTx("去预约") : socialTx("去完善核验")}
|
||||||
|
<ArrowUpRight size={14} />
|
||||||
|
</span>
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
134
src/modules/social/components/HomeSkillsPreview.tsx
Normal file
134
src/modules/social/components/HomeSkillsPreview.tsx
Normal file
@ -0,0 +1,134 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import Link from "next/link";
|
||||||
|
import { ArrowLeftRight, ArrowUpRight } from "lucide-react";
|
||||||
|
import { socialApi } from "@social/lib/api";
|
||||||
|
import { socialPath } from "@social/lib/socialPath";
|
||||||
|
import { socialTx } from "@social/lib/socialTx";
|
||||||
|
import SectionSpark from "./SectionSpark";
|
||||||
|
|
||||||
|
type SkillItem = {
|
||||||
|
id: string;
|
||||||
|
author: string;
|
||||||
|
city: string;
|
||||||
|
offer: string;
|
||||||
|
want: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const SEED: SkillItem[] = [
|
||||||
|
{
|
||||||
|
id: "seed-1",
|
||||||
|
author: "Mia",
|
||||||
|
city: "清迈",
|
||||||
|
offer: "英语口语陪练",
|
||||||
|
want: "帮拍短视频 / 剪辑",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "seed-2",
|
||||||
|
author: "Ken",
|
||||||
|
city: "里斯本",
|
||||||
|
offer: "帮看代码 / 架构 review",
|
||||||
|
want: "签证 / D7 经验咨询",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "seed-3",
|
||||||
|
author: "Lin",
|
||||||
|
city: "成都",
|
||||||
|
offer: "小红书运营陪跑",
|
||||||
|
want: "摄影设备借用一天",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "seed-4",
|
||||||
|
author: "Jay",
|
||||||
|
city: "线上",
|
||||||
|
offer: "简历 / LinkedIn 点评",
|
||||||
|
want: "葡萄牙语入门交换",
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
export default function HomeSkillsPreview() {
|
||||||
|
const [items, setItems] = useState<SkillItem[]>(SEED);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let cancelled = false;
|
||||||
|
void socialApi
|
||||||
|
.listSkills({ limit: 4 })
|
||||||
|
.then((res) => {
|
||||||
|
if (cancelled) return;
|
||||||
|
const live = res?.items || [];
|
||||||
|
if (live.length) {
|
||||||
|
setItems(
|
||||||
|
live.slice(0, 4).map((s) => ({
|
||||||
|
id: s.id,
|
||||||
|
author: s.author,
|
||||||
|
city: s.city,
|
||||||
|
offer: s.offer,
|
||||||
|
want: s.want,
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
/* keep SEED */
|
||||||
|
});
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section
|
||||||
|
className="section section-compact social-section-alt"
|
||||||
|
id="skills"
|
||||||
|
aria-label={socialTx("技能交换")}
|
||||||
|
>
|
||||||
|
<div className="container">
|
||||||
|
<div className="section-header reveal">
|
||||||
|
<SectionSpark label="skills" />
|
||||||
|
<span className="section-tag">
|
||||||
|
<span>{socialTx("技能板")}</span>
|
||||||
|
<span>{socialTx("互换互助")}</span>
|
||||||
|
</span>
|
||||||
|
<h2>
|
||||||
|
<span className="social-title-emoji" aria-hidden>
|
||||||
|
🔄
|
||||||
|
</span>
|
||||||
|
{socialTx("技能交换")}
|
||||||
|
</h2>
|
||||||
|
<p>
|
||||||
|
{socialTx(
|
||||||
|
"教英语换拍视频、帮忙看代码换签证咨询——写清楚你能给什么、想换什么。",
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="home-skills-grid reveal">
|
||||||
|
{items.map((item) => (
|
||||||
|
<Link
|
||||||
|
key={item.id}
|
||||||
|
href={socialPath("/skills")}
|
||||||
|
className="home-skill-card"
|
||||||
|
>
|
||||||
|
<span className="home-skill-city">{item.city}</span>
|
||||||
|
<strong>{item.author}</strong>
|
||||||
|
<p>
|
||||||
|
<em>{socialTx("能提供")}</em> {item.offer}
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
<em>{socialTx("想换到")}</em> {item.want}
|
||||||
|
</p>
|
||||||
|
</Link>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="social-section-actions reveal">
|
||||||
|
<Link href={socialPath("/skills")} className="btn btn-primary">
|
||||||
|
<ArrowLeftRight size={15} /> {socialTx("去发互换")}
|
||||||
|
<ArrowUpRight size={14} />
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
158
src/modules/social/components/HomeStatusStrip.tsx
Normal file
158
src/modules/social/components/HomeStatusStrip.tsx
Normal file
@ -0,0 +1,158 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import Link from "next/link";
|
||||||
|
import { useMemo, useSyncExternalStore } from "react";
|
||||||
|
import { ArrowUpRight, Camera, Check, MapPin, UserRound } from "lucide-react";
|
||||||
|
import {
|
||||||
|
getLivenessState,
|
||||||
|
type LivenessState,
|
||||||
|
} from "@social/lib/livenessGate";
|
||||||
|
import { loadJson } from "@social/lib/storage";
|
||||||
|
import type { SocialRosterProfile } from "@social/lib/types";
|
||||||
|
import { socialPath } from "@social/lib/socialPath";
|
||||||
|
import { socialTx } from "@social/lib/socialTx";
|
||||||
|
import SocialAvatar from "./SocialAvatar";
|
||||||
|
|
||||||
|
const CHANGE = "nomadro-social-storage";
|
||||||
|
|
||||||
|
function subscribe(cb: () => void) {
|
||||||
|
window.addEventListener(CHANGE, cb);
|
||||||
|
window.addEventListener("storage", cb);
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener(CHANGE, cb);
|
||||||
|
window.removeEventListener("storage", cb);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const EMPTY_PROFILE: SocialRosterProfile = {
|
||||||
|
name: "",
|
||||||
|
title: "",
|
||||||
|
city: "",
|
||||||
|
phone: "",
|
||||||
|
linktree: "",
|
||||||
|
skills: "",
|
||||||
|
bio: "",
|
||||||
|
avatar: "",
|
||||||
|
intents: "",
|
||||||
|
availability: "",
|
||||||
|
status: "",
|
||||||
|
lookingFor: "",
|
||||||
|
gender: "",
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function HomeStatusStrip() {
|
||||||
|
const liveSnap = useSyncExternalStore(
|
||||||
|
subscribe,
|
||||||
|
() => JSON.stringify(getLivenessState()),
|
||||||
|
() => JSON.stringify({ faceOk: false, livenessStatus: "none" }),
|
||||||
|
);
|
||||||
|
const profileSnap = useSyncExternalStore(
|
||||||
|
subscribe,
|
||||||
|
() => JSON.stringify(loadJson<SocialRosterProfile>("roster", EMPTY_PROFILE)),
|
||||||
|
() => JSON.stringify(EMPTY_PROFILE),
|
||||||
|
);
|
||||||
|
|
||||||
|
const state = useMemo(
|
||||||
|
() => JSON.parse(liveSnap) as LivenessState,
|
||||||
|
[liveSnap],
|
||||||
|
);
|
||||||
|
const profile = useMemo(() => {
|
||||||
|
const raw = JSON.parse(profileSnap) as Partial<SocialRosterProfile>;
|
||||||
|
return { ...EMPTY_PROFILE, ...raw };
|
||||||
|
}, [profileSnap]);
|
||||||
|
|
||||||
|
const name = profile.name.trim() || socialTx("游民");
|
||||||
|
const city = profile.city.trim() || socialTx("城市待填");
|
||||||
|
const avatar = (profile.avatar || "").trim();
|
||||||
|
const faceOk = state.faceOk;
|
||||||
|
const liveOk = state.livenessStatus === "verified";
|
||||||
|
const livePending = state.livenessStatus === "pending";
|
||||||
|
|
||||||
|
let nextHref = socialPath("/join?step=profile");
|
||||||
|
let nextLabel = socialTx("去完善核验");
|
||||||
|
let nextHint = socialTx("上传正脸后,再完成现场实拍");
|
||||||
|
|
||||||
|
if (!faceOk) {
|
||||||
|
nextHint = socialTx("下一步:上传清晰正脸照片(头像 ≠ 实拍)");
|
||||||
|
} else if (!liveOk) {
|
||||||
|
nextHint = livePending
|
||||||
|
? socialTx("实拍已提交,等待审核通过")
|
||||||
|
: socialTx("下一步:现场实拍核验(全程录像)");
|
||||||
|
} else {
|
||||||
|
nextHref = socialPath("/coffeechat");
|
||||||
|
nextLabel = socialTx("去咖啡聊");
|
||||||
|
nextHint = socialTx("核验已通过 · 可以约会 / 咖啡聊");
|
||||||
|
}
|
||||||
|
|
||||||
|
const secondaryHref = liveOk
|
||||||
|
? socialPath("/date")
|
||||||
|
: socialPath("/roster");
|
||||||
|
const secondaryLabel = liveOk
|
||||||
|
? socialTx("去左右滑")
|
||||||
|
: socialTx("我的介绍");
|
||||||
|
|
||||||
|
const avatarSrc =
|
||||||
|
avatar ||
|
||||||
|
`https://api.dicebear.com/7.x/initials/svg?seed=${encodeURIComponent(name)}`;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section
|
||||||
|
className="home-status-strip container reveal"
|
||||||
|
aria-label={socialTx("我的状态")}
|
||||||
|
>
|
||||||
|
<div className="home-status-card">
|
||||||
|
<span className="home-status-ava">
|
||||||
|
<SocialAvatar src={avatarSrc} size={52} />
|
||||||
|
</span>
|
||||||
|
<div className="home-status-meta">
|
||||||
|
<strong>{name}</strong>
|
||||||
|
<span>
|
||||||
|
<MapPin size={12} aria-hidden /> {city}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<ul className="home-status-steps" aria-label={socialTx("核验进度")}>
|
||||||
|
<li className={faceOk ? "is-done" : "is-todo"}>
|
||||||
|
{faceOk ? <Check size={14} /> : <UserRound size={14} />}
|
||||||
|
<em>{socialTx("正脸")}</em>
|
||||||
|
</li>
|
||||||
|
<li
|
||||||
|
className={
|
||||||
|
liveOk ? "is-done" : livePending ? "is-pending" : "is-todo"
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{liveOk ? <Check size={14} /> : <Camera size={14} />}
|
||||||
|
<em>{socialTx("实拍")}</em>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<p className="home-status-hint">{nextHint}</p>
|
||||||
|
<div className="home-status-acts">
|
||||||
|
<Link className="btn btn-primary btn-sm" href={nextHref}>
|
||||||
|
{nextLabel} <ArrowUpRight size={14} />
|
||||||
|
</Link>
|
||||||
|
<Link className="btn btn-ghost btn-sm" href={secondaryHref}>
|
||||||
|
{secondaryLabel}
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Soft-gate helper for home CTAs (date / coffee / map). */
|
||||||
|
export function useHomeLivenessGate(): {
|
||||||
|
faceOk: boolean;
|
||||||
|
liveOk: boolean;
|
||||||
|
verifyHref: string;
|
||||||
|
} {
|
||||||
|
const liveSnap = useSyncExternalStore(
|
||||||
|
subscribe,
|
||||||
|
() => JSON.stringify(getLivenessState()),
|
||||||
|
() => JSON.stringify({ faceOk: false, livenessStatus: "none" }),
|
||||||
|
);
|
||||||
|
const state = JSON.parse(liveSnap) as LivenessState;
|
||||||
|
return {
|
||||||
|
faceOk: state.faceOk,
|
||||||
|
liveOk: state.livenessStatus === "verified",
|
||||||
|
verifyHref: socialPath("/join?step=profile"),
|
||||||
|
};
|
||||||
|
}
|
||||||
@ -1,5 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import {
|
import {
|
||||||
ArrowLeft,
|
ArrowLeft,
|
||||||
@ -7,10 +8,12 @@ import {
|
|||||||
MapPin,
|
MapPin,
|
||||||
MessageCircle,
|
MessageCircle,
|
||||||
Sparkles,
|
Sparkles,
|
||||||
|
Star,
|
||||||
Video,
|
Video,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import SiteShell from "./SiteShell";
|
import SiteShell from "./SiteShell";
|
||||||
import SocialAvatar from "./SocialAvatar";
|
import SocialAvatar from "./SocialAvatar";
|
||||||
|
import ReportBlockPanel from "./ReportBlockPanel";
|
||||||
import {
|
import {
|
||||||
BookmarkButton,
|
BookmarkButton,
|
||||||
DemoBadge,
|
DemoBadge,
|
||||||
@ -26,15 +29,51 @@ import {
|
|||||||
useDiscoveryRoster,
|
useDiscoveryRoster,
|
||||||
} from "@social/lib/discoveryRoster";
|
} from "@social/lib/discoveryRoster";
|
||||||
import { useRosterLikes, setRosterLike } from "@social/lib/useRosterLikes";
|
import { useRosterLikes, setRosterLike } from "@social/lib/useRosterLikes";
|
||||||
|
import { socialApi } from "@social/lib/api";
|
||||||
|
import { loadJson } from "@social/lib/storage";
|
||||||
import { socialPath } from "@social/lib/socialPath";
|
import { socialPath } from "@social/lib/socialPath";
|
||||||
import { socialTx } from "@social/lib/socialTx";
|
import { socialTx } from "@social/lib/socialTx";
|
||||||
|
|
||||||
|
type ReviewSummary = {
|
||||||
|
count: number;
|
||||||
|
averages: {
|
||||||
|
punctuality: number;
|
||||||
|
chemistry: number;
|
||||||
|
professionalism: number;
|
||||||
|
overall: number;
|
||||||
|
} | null;
|
||||||
|
items: Array<{
|
||||||
|
id: string;
|
||||||
|
punctuality: number;
|
||||||
|
chemistry: number;
|
||||||
|
professionalism: number;
|
||||||
|
text: string;
|
||||||
|
avg: number;
|
||||||
|
createdAt: string;
|
||||||
|
}>;
|
||||||
|
};
|
||||||
|
|
||||||
export default function PeopleProfileClient({ id }: { id: string }) {
|
export default function PeopleProfileClient({ id }: { id: string }) {
|
||||||
const roster = useDiscoveryRoster();
|
const roster = useDiscoveryRoster();
|
||||||
const member =
|
const member =
|
||||||
roster.find((m) => m.id === id) || findRosterMember(id);
|
roster.find((m) => m.id === id) || findRosterMember(id);
|
||||||
|
|
||||||
const likes = useRosterLikes();
|
const likes = useRosterLikes();
|
||||||
|
const [reviews, setReviews] = useState<ReviewSummary | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!member || member.id === SELF_MEMBER_ID) return;
|
||||||
|
void socialApi
|
||||||
|
.getReviews(member.id)
|
||||||
|
.then((r) =>
|
||||||
|
setReviews({
|
||||||
|
count: r.count,
|
||||||
|
averages: r.averages,
|
||||||
|
items: r.items || [],
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.catch(() => setReviews(null));
|
||||||
|
}, [member]);
|
||||||
|
|
||||||
if (!member) {
|
if (!member) {
|
||||||
return (
|
return (
|
||||||
@ -62,7 +101,14 @@ export default function PeopleProfileClient({ id }: { id: string }) {
|
|||||||
.slice(0, 4);
|
.slice(0, 4);
|
||||||
|
|
||||||
const toggleLike = () => {
|
const toggleLike = () => {
|
||||||
setRosterLike(member.id, !liked);
|
const next = !liked;
|
||||||
|
setRosterLike(member.id, next);
|
||||||
|
if (next && member.id !== SELF_MEMBER_ID) {
|
||||||
|
const me = loadJson<{ name?: string }>("roster", {});
|
||||||
|
void socialApi
|
||||||
|
.notifyLike(member.id, me.name || "游民")
|
||||||
|
.catch(() => undefined);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const intro = encodeURIComponent(
|
const intro = encodeURIComponent(
|
||||||
@ -184,6 +230,41 @@ export default function PeopleProfileClient({ id }: { id: string }) {
|
|||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{reviews && reviews.count > 0 && reviews.averages ? (
|
||||||
|
<section className="social-profile-card social-profile-reviews">
|
||||||
|
<h2>
|
||||||
|
<Star size={15} aria-hidden /> {socialTx("见面评价")}
|
||||||
|
<em>
|
||||||
|
{reviews.averages.overall.toFixed(1)} · {reviews.count}
|
||||||
|
{socialTx("条")}
|
||||||
|
</em>
|
||||||
|
</h2>
|
||||||
|
<ul className="social-review-avgs">
|
||||||
|
<li>
|
||||||
|
{socialTx("守时")} {reviews.averages.punctuality.toFixed(1)}
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
{socialTx("聊得来")} {reviews.averages.chemistry.toFixed(1)}
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
{socialTx("靠谱")} {reviews.averages.professionalism.toFixed(1)}
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<div className="social-review-list">
|
||||||
|
{reviews.items.slice(0, 3).map((r) => (
|
||||||
|
<blockquote key={r.id}>
|
||||||
|
<strong>{r.avg.toFixed(1)}</strong>
|
||||||
|
<p>{r.text || socialTx("未写文字评价")}</p>
|
||||||
|
</blockquote>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{member.id !== SELF_MEMBER_ID ? (
|
||||||
|
<ReportBlockPanel targetGuest={member.id} targetName={member.name} />
|
||||||
|
) : null}
|
||||||
|
|
||||||
{member.gallery && member.gallery.length > 0 ? (
|
{member.gallery && member.gallery.length > 0 ? (
|
||||||
<section className="social-profile-gallery">
|
<section className="social-profile-gallery">
|
||||||
<h2>{socialTx("生活瞬间")}</h2>
|
<h2>{socialTx("生活瞬间")}</h2>
|
||||||
|
|||||||
122
src/modules/social/components/ReportBlockPanel.tsx
Normal file
122
src/modules/social/components/ReportBlockPanel.tsx
Normal file
@ -0,0 +1,122 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { Flag, Ban } from "lucide-react";
|
||||||
|
import { socialApi } from "@social/lib/api";
|
||||||
|
import { socialTx } from "@social/lib/socialTx";
|
||||||
|
|
||||||
|
const REASONS = [
|
||||||
|
"骚扰 / 不当言论",
|
||||||
|
"虚假资料",
|
||||||
|
"垃圾广告",
|
||||||
|
"人身安全顾虑",
|
||||||
|
"其他",
|
||||||
|
];
|
||||||
|
|
||||||
|
export default function ReportBlockPanel({
|
||||||
|
targetGuest,
|
||||||
|
targetName,
|
||||||
|
}: {
|
||||||
|
targetGuest: string;
|
||||||
|
targetName: string;
|
||||||
|
}) {
|
||||||
|
const [open, setOpen] = useState<"report" | "block" | null>(null);
|
||||||
|
const [reason, setReason] = useState(REASONS[0]);
|
||||||
|
const [detail, setDetail] = useState("");
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [msg, setMsg] = useState("");
|
||||||
|
|
||||||
|
const submitReport = async () => {
|
||||||
|
if (busy) return;
|
||||||
|
setBusy(true);
|
||||||
|
setMsg("");
|
||||||
|
try {
|
||||||
|
await socialApi.reportUser({
|
||||||
|
targetGuest,
|
||||||
|
targetName,
|
||||||
|
reason,
|
||||||
|
detail,
|
||||||
|
});
|
||||||
|
setMsg(socialTx("已提交举报,处理结果会通知你"));
|
||||||
|
setOpen(null);
|
||||||
|
} catch (e) {
|
||||||
|
setMsg(e instanceof Error ? e.message : socialTx("提交失败"));
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const submitBlock = async () => {
|
||||||
|
if (busy) return;
|
||||||
|
setBusy(true);
|
||||||
|
setMsg("");
|
||||||
|
try {
|
||||||
|
await socialApi.blockUser(targetGuest, reason);
|
||||||
|
setMsg(socialTx("已屏蔽,双方将不再互相看到"));
|
||||||
|
setOpen(null);
|
||||||
|
} catch (e) {
|
||||||
|
setMsg(e instanceof Error ? e.message : socialTx("操作失败"));
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="social-moderation">
|
||||||
|
<div className="social-moderation-actions">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="social-btn"
|
||||||
|
onClick={() => setOpen(open === "report" ? null : "report")}
|
||||||
|
>
|
||||||
|
<Flag size={14} aria-hidden /> {socialTx("举报")}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="social-btn"
|
||||||
|
onClick={() => setOpen(open === "block" ? null : "block")}
|
||||||
|
>
|
||||||
|
<Ban size={14} aria-hidden /> {socialTx("屏蔽")}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{msg ? <p className="social-muted">{msg}</p> : null}
|
||||||
|
{open ? (
|
||||||
|
<div className="social-moderation-sheet">
|
||||||
|
<label>
|
||||||
|
{socialTx("原因")}
|
||||||
|
<select value={reason} onChange={(e) => setReason(e.target.value)}>
|
||||||
|
{REASONS.map((r) => (
|
||||||
|
<option key={r} value={r}>
|
||||||
|
{socialTx(r)}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
{open === "report" ? (
|
||||||
|
<label>
|
||||||
|
{socialTx("补充说明")}
|
||||||
|
<textarea
|
||||||
|
rows={3}
|
||||||
|
value={detail}
|
||||||
|
onChange={(e) => setDetail(e.target.value)}
|
||||||
|
maxLength={800}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
) : null}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="social-btn coral"
|
||||||
|
disabled={busy}
|
||||||
|
onClick={() => void (open === "report" ? submitReport() : submitBlock())}
|
||||||
|
>
|
||||||
|
{busy
|
||||||
|
? socialTx("提交中…")
|
||||||
|
: open === "report"
|
||||||
|
? socialTx("提交举报")
|
||||||
|
: socialTx("确认屏蔽")}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
211
src/modules/social/components/SkillsBoardClient.tsx
Normal file
211
src/modules/social/components/SkillsBoardClient.tsx
Normal file
@ -0,0 +1,211 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useState, type FormEvent } from "react";
|
||||||
|
import { ArrowLeftRight, MapPin, Plus } from "lucide-react";
|
||||||
|
import SiteShell from "./SiteShell";
|
||||||
|
import { PageIntro } from "./SocialUI";
|
||||||
|
import { socialApi, getGuestId } from "@social/lib/api";
|
||||||
|
import { loadJson } from "@social/lib/storage";
|
||||||
|
import { socialTx } from "@social/lib/socialTx";
|
||||||
|
|
||||||
|
type SkillItem = {
|
||||||
|
id: string;
|
||||||
|
guestId: string;
|
||||||
|
author: string;
|
||||||
|
city: string;
|
||||||
|
offer: string;
|
||||||
|
want: string;
|
||||||
|
note: string;
|
||||||
|
createdAt: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const SEED: SkillItem[] = [
|
||||||
|
{
|
||||||
|
id: "seed-1",
|
||||||
|
guestId: "seed",
|
||||||
|
author: "Mia",
|
||||||
|
city: "清迈",
|
||||||
|
offer: "英语口语陪练",
|
||||||
|
want: "帮拍短视频 / 剪辑",
|
||||||
|
note: "每周 2 次 · 咖啡馆或线上均可",
|
||||||
|
createdAt: "",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "seed-2",
|
||||||
|
guestId: "seed",
|
||||||
|
author: "Ken",
|
||||||
|
city: "里斯本",
|
||||||
|
offer: "帮看代码 / 架构 review",
|
||||||
|
want: "签证 / D7 经验咨询",
|
||||||
|
note: "远程异步也行",
|
||||||
|
createdAt: "",
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
export default function SkillsBoardClient() {
|
||||||
|
const me = typeof window !== "undefined" ? getGuestId() : "";
|
||||||
|
const [items, setItems] = useState<SkillItem[]>(SEED);
|
||||||
|
const [city, setCity] = useState("");
|
||||||
|
const [offer, setOffer] = useState("");
|
||||||
|
const [want, setWant] = useState("");
|
||||||
|
const [note, setNote] = useState("");
|
||||||
|
const [postCity, setPostCity] = useState("");
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [err, setErr] = useState("");
|
||||||
|
|
||||||
|
const load = async (filterCity = city) => {
|
||||||
|
try {
|
||||||
|
const res = await socialApi.listSkills({
|
||||||
|
city: filterCity || undefined,
|
||||||
|
limit: 80,
|
||||||
|
});
|
||||||
|
const live = res.items || [];
|
||||||
|
setItems(live.length ? live : SEED);
|
||||||
|
} catch {
|
||||||
|
setItems(SEED);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const roster = loadJson<{ name?: string; city?: string }>("roster", {});
|
||||||
|
if (roster.city) {
|
||||||
|
setPostCity(roster.city);
|
||||||
|
setCity(roster.city);
|
||||||
|
}
|
||||||
|
void load(roster.city || "");
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const submit = async (e: FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (busy) return;
|
||||||
|
setBusy(true);
|
||||||
|
setErr("");
|
||||||
|
try {
|
||||||
|
const roster = loadJson<{ name?: string }>("roster", {});
|
||||||
|
await socialApi.createSkill({
|
||||||
|
author: roster.name || "游民",
|
||||||
|
city: postCity.trim(),
|
||||||
|
offer: offer.trim(),
|
||||||
|
want: want.trim(),
|
||||||
|
note: note.trim(),
|
||||||
|
});
|
||||||
|
setOffer("");
|
||||||
|
setWant("");
|
||||||
|
setNote("");
|
||||||
|
await load();
|
||||||
|
} catch (ex) {
|
||||||
|
setErr(ex instanceof Error ? ex.message : socialTx("发布失败"));
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<SiteShell title={socialTx("技能交换")}>
|
||||||
|
<PageIntro title={socialTx("技能交换 / 互助板")} accent="以物易物式互助">
|
||||||
|
<p className="social-muted">
|
||||||
|
{socialTx("教英语换拍视频、帮忙看代码换签证咨询——写清楚你能给什么、想换什么。")}
|
||||||
|
</p>
|
||||||
|
</PageIntro>
|
||||||
|
|
||||||
|
<form className="social-skills-compose social-panel" onSubmit={(ev) => void submit(ev)}>
|
||||||
|
<h2>
|
||||||
|
<Plus size={16} aria-hidden /> {socialTx("发一条互换")}
|
||||||
|
</h2>
|
||||||
|
<label>
|
||||||
|
{socialTx("城市")}
|
||||||
|
<input
|
||||||
|
value={postCity}
|
||||||
|
onChange={(e) => setPostCity(e.target.value)}
|
||||||
|
placeholder={socialTx("清迈 / 线上")}
|
||||||
|
maxLength={64}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
{socialTx("我能提供")}
|
||||||
|
<input
|
||||||
|
required
|
||||||
|
value={offer}
|
||||||
|
onChange={(e) => setOffer(e.target.value)}
|
||||||
|
placeholder={socialTx("英语陪练 / 代码 review / …")}
|
||||||
|
maxLength={200}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
{socialTx("想换到")}
|
||||||
|
<input
|
||||||
|
required
|
||||||
|
value={want}
|
||||||
|
onChange={(e) => setWant(e.target.value)}
|
||||||
|
placeholder={socialTx("拍视频 / 签证咨询 / …")}
|
||||||
|
maxLength={200}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
{socialTx("补充说明")}
|
||||||
|
<textarea
|
||||||
|
rows={2}
|
||||||
|
value={note}
|
||||||
|
onChange={(e) => setNote(e.target.value)}
|
||||||
|
maxLength={800}
|
||||||
|
placeholder={socialTx("时间、线上线下、期望频率…")}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
{err ? (
|
||||||
|
<p className="social-join-err" role="alert">
|
||||||
|
{err}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
<button type="submit" className="social-btn coral" disabled={busy}>
|
||||||
|
{busy ? socialTx("发布中…") : socialTx("发布互换")}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<div className="social-skills-filter">
|
||||||
|
<MapPin size={14} aria-hidden />
|
||||||
|
<input
|
||||||
|
value={city}
|
||||||
|
onChange={(e) => setCity(e.target.value)}
|
||||||
|
placeholder={socialTx("按城市筛选")}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === "Enter") void load(city);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<button type="button" className="social-btn" onClick={() => void load(city)}>
|
||||||
|
{socialTx("筛选")}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="social-skills-grid">
|
||||||
|
{items.map((item) => (
|
||||||
|
<article key={item.id} className="social-skills-card">
|
||||||
|
<header>
|
||||||
|
<strong>{item.author}</strong>
|
||||||
|
<span>
|
||||||
|
<MapPin size={12} aria-hidden /> {item.city || socialTx("全球 / 线上")}
|
||||||
|
</span>
|
||||||
|
</header>
|
||||||
|
<p className="social-skills-swap">
|
||||||
|
<em>{item.offer}</em>
|
||||||
|
<ArrowLeftRight size={14} aria-hidden />
|
||||||
|
<em>{item.want}</em>
|
||||||
|
</p>
|
||||||
|
{item.note ? <p className="social-skills-note">{item.note}</p> : null}
|
||||||
|
{item.guestId === me && item.id.startsWith("sk_") ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="social-btn"
|
||||||
|
onClick={() =>
|
||||||
|
void socialApi.closeSkill(item.id).then(() => load(city))
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{socialTx("关闭")}
|
||||||
|
</button>
|
||||||
|
) : null}
|
||||||
|
</article>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</SiteShell>
|
||||||
|
);
|
||||||
|
}
|
||||||
133
src/modules/social/components/WrappedClient.tsx
Normal file
133
src/modules/social/components/WrappedClient.tsx
Normal file
@ -0,0 +1,133 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import Link from "next/link";
|
||||||
|
import { MapPin, Sparkles, Users, Coffee, ArrowLeftRight } from "lucide-react";
|
||||||
|
import SiteShell from "./SiteShell";
|
||||||
|
import { socialApi } from "@social/lib/api";
|
||||||
|
import { socialPath } from "@social/lib/socialPath";
|
||||||
|
import { socialTx } from "@social/lib/socialTx";
|
||||||
|
|
||||||
|
type Wrapped = {
|
||||||
|
year: number;
|
||||||
|
name: string;
|
||||||
|
homeCity: string;
|
||||||
|
cities: string[];
|
||||||
|
cityCount: number;
|
||||||
|
peopleMet: number;
|
||||||
|
meetups: number;
|
||||||
|
skillPosts: number;
|
||||||
|
livenessVerified: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
const FALLBACK: Wrapped = {
|
||||||
|
year: new Date().getFullYear(),
|
||||||
|
name: "游民",
|
||||||
|
homeCity: "",
|
||||||
|
cities: [],
|
||||||
|
cityCount: 0,
|
||||||
|
peopleMet: 0,
|
||||||
|
meetups: 0,
|
||||||
|
skillPosts: 0,
|
||||||
|
livenessVerified: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function WrappedClient() {
|
||||||
|
const [data, setData] = useState<Wrapped | null>(null);
|
||||||
|
const [err, setErr] = useState("");
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void socialApi
|
||||||
|
.getWrapped()
|
||||||
|
.then((r) =>
|
||||||
|
setData({
|
||||||
|
year: r.year,
|
||||||
|
name: r.name || "游民",
|
||||||
|
homeCity: r.homeCity || "",
|
||||||
|
cities: r.cities || [],
|
||||||
|
cityCount: r.cityCount || 0,
|
||||||
|
peopleMet: r.peopleMet || 0,
|
||||||
|
meetups: r.meetups || 0,
|
||||||
|
skillPosts: r.skillPosts || 0,
|
||||||
|
livenessVerified: !!r.livenessVerified,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.catch((e) => {
|
||||||
|
setErr(e instanceof Error ? e.message : socialTx("加载失败"));
|
||||||
|
setData(FALLBACK);
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const w = data || FALLBACK;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<SiteShell title={socialTx("年度回顾")}>
|
||||||
|
<article className="social-wrapped">
|
||||||
|
<p className="social-wrapped-kicker">
|
||||||
|
<Sparkles size={14} aria-hidden /> Nomadro Wrapped · {w.year}
|
||||||
|
</p>
|
||||||
|
<h1>
|
||||||
|
{w.name}
|
||||||
|
<span>{socialTx("的这一年")}</span>
|
||||||
|
</h1>
|
||||||
|
{err ? <p className="social-join-err">{err}</p> : null}
|
||||||
|
|
||||||
|
<div className="social-wrapped-hero">
|
||||||
|
<p>
|
||||||
|
{w.homeCity
|
||||||
|
? socialTx("主场在") + ` ${w.homeCity}`
|
||||||
|
: socialTx("还在路上,主场待填写")}
|
||||||
|
</p>
|
||||||
|
{w.livenessVerified ? (
|
||||||
|
<em>{socialTx("真人核验已通过")}</em>
|
||||||
|
) : (
|
||||||
|
<Link href={socialPath("/roster")}>{socialTx("去完成真人核验")}</Link>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="social-wrapped-stats">
|
||||||
|
<div>
|
||||||
|
<MapPin size={18} aria-hidden />
|
||||||
|
<strong>{w.cityCount}</strong>
|
||||||
|
<span>{socialTx("座城市足迹")}</span>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<Users size={18} aria-hidden />
|
||||||
|
<strong>{w.peopleMet}</strong>
|
||||||
|
<span>{socialTx("位想认识的人")}</span>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<Coffee size={18} aria-hidden />
|
||||||
|
<strong>{w.meetups}</strong>
|
||||||
|
<span>{socialTx("次咖啡聊评价")}</span>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<ArrowLeftRight size={18} aria-hidden />
|
||||||
|
<strong>{w.skillPosts}</strong>
|
||||||
|
<span>{socialTx("条技能互换")}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{w.cities.length > 0 ? (
|
||||||
|
<section className="social-wrapped-cities">
|
||||||
|
<h2>{socialTx("足迹城市")}</h2>
|
||||||
|
<div className="social-tags">
|
||||||
|
{w.cities.map((c) => (
|
||||||
|
<span key={c}>{c}</span>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<div className="social-wrapped-cta">
|
||||||
|
<Link className="social-btn coral" href={socialPath("/skills")}>
|
||||||
|
{socialTx("去技能板")}
|
||||||
|
</Link>
|
||||||
|
<Link className="social-btn" href={socialPath("/people")}>
|
||||||
|
{socialTx("回去看看大家")}
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
</SiteShell>
|
||||||
|
);
|
||||||
|
}
|
||||||
598
src/modules/social/lib/_phrases_raw.json
Normal file
598
src/modules/social/lib/_phrases_raw.json
Normal file
@ -0,0 +1,598 @@
|
|||||||
|
[
|
||||||
|
"onClick={resetDeck}\n >\n <RotateCcw size={14} />\n 再看一轮\n </button>\n </div>\n </SocialDialog>\n ) : null}\n <SocialMobileDock />\n </div>\n );\n}\n\nfunction DateCardFace({ member }: { member: SocialRosterMember }) {\n const photos = useMemo(() => {\n const list = [member.avatar, ...(member.gallery || [])].filter(Boolean);\n return Array.from(new Set(list));\n }, [member.avatar, member.gallery]);\n const [photoIndex, setPhotoIndex] = useState(0);\n const cover = photos[Math.min(photoIndex, photos.length - 1)] || member.avatar;\n\n return (\n <>\n <div\n className=",
|
||||||
|
",\n detail: `${book.chapters} 章 · ${book.minutes} 分钟`,\n }))\n : SEED_VIDEOS.map((video) => ({\n ...video,\n detail: `${video.city} · ${video.minutes} 分钟`,\n }));\n const shown = items.filter(\n (item) =>\n (!savedOnly || saved.includes(item.id)) &&\n `${item.title} ${item.summary} ${item.city}`\n .toLowerCase()\n .includes(query.toLowerCase().trim()),\n );\n const active = items.find((item) => item.id === selected);\n const source =\n active && safeSource(config.copy.socialVideoSources?.[active.id]);\n return (\n <SiteShell\n title={books ?",
|
||||||
|
"aria-hidden>\n <BookOpen size={20} />\n </span>\n <div>\n <em>共创 · 小册</em>\n <strong>{book.title}</strong>\n <p>{book.blurb}</p>\n </div>\n <ArrowUpRight size={16} />\n </Link>\n ))}\n {SEED_VIDEOS.slice(0, 2).map((vid) => (\n <Link\n key={vid.id}\n href={socialPath(",
|
||||||
|
")}>\n 回去看看大家\n </Link>\n </EmptyState>\n </SiteShell>\n );\n }\n\n const liked = !!likes[member.id];\n const cityKey = member.city.split(/[·/]/)[0].trim();\n const similar = roster\n .filter(\n (m) =>\n m.id !== member.id && m.city.includes(cityKey.slice(0, 2)),\n )\n .slice(0, 4);\n\n const toggleLike = () => {\n setRosterLike(member.id, !liked);\n };\n\n const intro = encodeURIComponent(\n `嗨 ${member.name}!看到你在做${member.tags[0] ||",
|
||||||
|
"aria-hidden>\n {vid.coverEmoji}\n </span>\n <div>\n <em>共创 · 视频</em>\n <strong>{vid.title}</strong>\n <p>\n {vid.city} · {vid.minutes} 分钟\n </p>\n </div>\n <ArrowUpRight size={16} />\n </Link>\n ))}\n </div>\n\n <div className=",
|
||||||
|
"}`}\n href={socialPath(\n `/chat?intro=${encodeURIComponent(`看到「${active.title}」,想聊聊。`)}`,\n )}\n >\n <MessageCircle size={15} />\n 去聊天室聊聊\n </Link>\n <BookmarkButton id={active.id} collection={`saved-${kind}`} />\n </div>\n </SocialDialog>\n )}\n {contributeOpen && (\n <SocialDialog title=",
|
||||||
|
"aria-hidden>\n {MOCK_ROSTER.slice(i + 1, i + 5).map((p) => (\n <SocialAvatar key={p.id} src={p.avatar} size={24} lazy />\n ))}\n <em>+{6 + i} 想参加</em>\n </div>\n <h3>{m.title}</h3>\n <p>群里打个招呼 → 开麦 / 开视频 → 认识新朋友</p>\n <Link\n className=",
|
||||||
|
"disabled={!chat.draft.trim() || chat.sending}\n >\n <Send size={14} />\n 发送\n </button>\n </div>\n </form>\n </section>\n );\n}\n\nexport default function ChatWorkspace() {\n const channel =\n SEED_CHANNELS.find((item) => item.id === SOCIAL_CHAT_ID) ||\n SEED_CHANNELS[0];\n const id = channel?.id || SOCIAL_CHAT_ID;\n return (\n <div className=",
|
||||||
|
"onClick={() => {\n setReply({ author: message.author, text: message.text });\n composerRef.current?.focus();\n }}\n aria-label={`回复${message.author}`}\n >\n <CornerUpLeft size={12} />\n 回复\n </button>\n <button\n type=",
|
||||||
|
"disabled={busy}\n onClick={() => void submit(undefined, review)}\n >\n 还没发出 · 再发一次\n </button>\n )}\n </article>\n ))}\n </div>\n )}\n </div>\n </div>\n {status && (\n <p\n className={`social-status${status.includes(",
|
||||||
|
"onClick={() => setSelection(item.id)}\n >\n 打开\n <ArrowUpRight size={14} />\n </button>\n <ShareButton\n path={`/social/${kind}#${item.id}`}\n title={item.title}\n />\n </div>\n </article>\n ))}\n {!shown.length && (\n <EmptyState title=",
|
||||||
|
"onClick={() => setLikesOpen(true)}\n >\n <span>想认识 · {liked.length}</span>\n <div>\n {liked.slice(0, 8).map((m) => (\n <SocialAvatar key={m.id} src={m.avatar} size={34} lazy />\n ))}\n </div>\n <em>查看</em>\n </button>\n )}\n </div>\n\n {toast ? (\n <div className=",
|
||||||
|
";\n\ntype Props = {\n open: boolean;\n onClose: () => void;\n};\n\nconst EMAIL_RE = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n\n/**\n * 加群:填邮箱 → 调起门户统一支付\n * PC/H5 → zpay;微信内 H5 → xpay(xorpay);小程序 WebView 提示走虚拟支付\n */\nexport default function JoinPayModal({ open, onClose }: Props) {\n return open ? <JoinPaySheet onClose={onClose} /> : null;\n}\n\nfunction JoinPaySheet({ onClose }: Pick<Props,",
|
||||||
|
"disabled={!scheduled}\n onClick={() => saveEventCalendar(event)}\n >\n <CalendarPlus size={14} />\n 加到日历\n </button>\n <ShareButton\n path={socialPath(`/meetup/${event.id}`)}\n title={event.title}\n />\n <Link className=",
|
||||||
|
"aria-label={`插入${emoji}`}\n onClick={() => {\n chat.setDraft((chat.draft + emoji).slice(0, 2000));\n setEmojiOpen(false);\n composerRef.current?.focus();\n }}\n >\n {emoji}\n </button>\n ))}\n </div>\n )}\n <div className=",
|
||||||
|
", kind)}\n >\n {kind}\n </button>\n ))}\n </div>\n <label>\n 内容\n <textarea\n rows={6}\n required\n maxLength={3000}\n value={draft.text}\n onChange={(event) => update(",
|
||||||
|
";\n }, [chat.messages]);\n\n const submit = async (event?: FormEvent) => {\n event?.preventDefault();\n if (!chat.draft.trim() || chat.sending) return;\n const submittedDraft = chat.draft;\n const body = reply\n ? `回复 ${reply.author}:${reply.text.slice(0, 100)}\\n${chat.draft}`\n : chat.draft;\n if (body.length > 2000) {\n setComposerError(",
|
||||||
|
"aria-hidden>\n 🌆\n </span>\n {landingCopy.socialOfflineTitle}\n </h2>\n <p>\n 认识了、聊过之后,出来见一面会更自然。\n 先挑一座城市,再找适合见面的咖啡馆。\n </p>\n </div>\n <CityDirectory compact limit={8} />\n <div className=",
|
||||||
|
"aria-hidden>\n {MOCK_ROSTER.filter((m) => m.online)\n .slice(0, 5)\n .map((m) => (\n <SocialAvatar key={m.id} src={m.avatar} size={28} lazy />\n ))}\n <em>示例成员 · 可先进入了解</em>\n </div>\n <button\n type=",
|
||||||
|
">\n <Sparkles size={27} strokeWidth={1.3} />\n </div>\n <strong>同频,自有引力</strong>\n <span>想见的人</span>\n </div>\n {NODES.map(({ member, x, y, rotate }, i) => {\n const m = MOCK_ROSTER[member];\n return (\n <a\n href=",
|
||||||
|
"onSubmit={(event) => void submit(event)}\n >\n <label>\n 名字\n <input\n value={author}\n onChange={(event) => setAuthor(event.target.value)}\n maxLength={40}\n required\n />\n </label>\n <fieldset className=",
|
||||||
|
">\n <li>\n <em>←</em> 划走\n </li>\n <li>\n <em>→</em> 想认识\n </li>\n <li>\n <em>♥</em> 稍后打招呼\n </li>\n </ul>\n <div className=",
|
||||||
|
")}>\n <Radio size={14} />\n 看看语音视频场\n </Link>\n </div>\n </EmptyState>\n )}\n {chat.messages.map((message) => (\n <article\n key={message.id}\n className={`social-message${message.mine ?",
|
||||||
|
"onClick={() => setContributeOpen(true)}\n >\n <PenLine size={14} />\n 我想投稿\n </button>\n </EmptyState>\n )}\n </div>\n {active && (\n <SocialDialog title={active.title} onClose={() => setSelection(null)}>\n <div className=",
|
||||||
|
"aria-hidden>\n 🚀\n </span>\n {landingCopy.socialTeamTitle}\n </h2>\n <p>\n 有人在找帮手;也有人一起写小册、拍视频做共创。\n 点卡片看看详情,合适再表达兴趣。\n </p>\n </div>\n\n <div className=",
|
||||||
|
">\n 该标签暂无城市 · 换一个试试\n </p>\n ) : null}\n </div>\n );\n}\n\nfunction CityCard({ city, index }: { city: SocialCity; index: number }) {\n return (\n <Link\n href={socialPath(`/people?city=${encodeURIComponent(city.name)}`)}\n className={`social-city-card reveal${city.hot ?",
|
||||||
|
"aria-hidden>\n 📡\n </span>\n {landingCopy.socialOnlineTitle}\n </h2>\n <p>\n 先进聊天群组热热身,再开语音或视频见面。\n 「想参加」会先记在你这边。\n </p>\n </div>\n <div className=",
|
||||||
|
"aria-hidden>\n <LockKeyhole size={24} strokeWidth={1.4} />\n </span>\n <h2>{copy.socialPayJoinLabel}</h2>\n <p>\n 填一下邮箱,按提示完成支付就能加入。电脑、手机浏览器和微信里都会带你走合适的支付方式。\n </p>\n {config.flags.payEnabled ? (\n <button\n type=",
|
||||||
|
";\n\n/**\n * Three.js 游民轨道球:线框地球 + 粒子轨道 + 漂浮 emoji 精灵。\n * 尊重 prefers-reduced-motion;不可见时暂停。\n */\nexport default function SocialOrbitScene() {\n const mountRef = useRef<HTMLDivElement>(null);\n\n useEffect(() => {\n const mount = mountRef.current;\n if (!mount) return;\n if (window.matchMedia(",
|
||||||
|
"aria-hidden>\n {MOCK_ROSTER.slice(index + 2, index + 6).map((p) => (\n <SocialAvatar key={p.id} src={p.avatar} size={22} lazy />\n ))}\n <em>示例成员</em>\n </div>\n <h2>{event.title}</h2>\n <p className=",
|
||||||
|
">合照:{review.photoNote}</p>\n ) : null}\n <small suppressHydrationWarning>\n {new Date(review.at).toLocaleDateString()}\n </small>\n {review.local && (\n <button\n type=",
|
||||||
|
">在线</span>\n ) : (\n <span>离线</span>\n )}\n <span>{member.vibe}</span>\n {member.id === SELF_MEMBER_ID ? <span>这是我</span> : null}\n </p>\n <h1>{member.name}</h1>\n <p className=",
|
||||||
|
")}>\n 写写我的介绍\n </Link>\n </div>\n </article>\n </SiteShell>\n );\n}\n\nfunction PersonMini({ m }: { m: SocialRosterMember }) {\n return (\n <Link\n href={socialPath(`/people/${m.id}`)}\n className={`social-people-chip social-chip-pop${m.online ?",
|
||||||
|
">\n <strong>文字频道还很安静</strong>\n <p>先打个招呼,或问问今晚谁在听。</p>\n </div>\n ) : null}\n {chat.messages.map((m) => (\n <div\n key={m.id}\n className={`social-bubble${m.mine ?",
|
||||||
|
"aria-hidden>\n 💕\n </span>\n 一张一张认识新朋友\n </h2>\n <p>\n 像翻相册一样:不感兴趣就划走,想认识就留下。\n 记在你这边,之后再决定要不要打招呼。\n </p>\n <ul className=",
|
||||||
|
";\n\n/** Ambient particle field — same feel as 旅居社群 homepage. */\nexport default function ParticleCanvas() {\n const canvasRef = useRef<HTMLCanvasElement>(null);\n\n useEffect(() => {\n const canvas = canvasRef.current;\n if (!canvas) return;\n const ctx = canvas.getContext(",
|
||||||
|
">\n <small>共创</small>\n <BookOpen size={27} strokeWidth={1} />\n <strong>{item.title}</strong>\n <span>阅读</span>\n </div>\n ) : (\n <>\n <span className=",
|
||||||
|
"aria-hidden>\n <MessageCircle size={24} strokeWidth={1.4} />\n </span>\n <h2>{copy.socialOaJoinLabel}</h2>\n <p>\n 关注\n {config.copy.wechatOaName\n ? `「${config.copy.wechatOaName}」`\n :",
|
||||||
|
"href={socialPath(`/meetup/${m.id}`)}\n >\n 进入聊聊\n <ArrowUpRight size={14} />\n </Link>\n </article>\n ))}\n </div>\n <div className=",
|
||||||
|
"aria-label={`还剩 ${remaining} 人`}\n >\n <i\n style={{\n width: `${Math.max(4, (remaining / totalForFilter) * 100)}%`,\n }}\n />\n </div>\n ) : null}\n <div\n className=",
|
||||||
|
"onClick={() => setLikesOpen(true)}\n >\n <Heart size={15} />\n 查看想认识 ({liked.length})\n </button>\n )}\n </div>\n )}\n\n {next && (\n <article className=",
|
||||||
|
"onClick={() => startVideo(true)}>重试连接</button>}\n </div>\n )}\n <iframe\n key={frameKey}\n title={`${meetup.title} video`}\n src={videoSrc}\n className=",
|
||||||
|
")}>\n <MessageCircle size={14} />\n 去聊天\n </Link>\n </div>\n </div>\n </article>\n );\n })}\n {!events.length && (\n <EmptyState\n emoji=",
|
||||||
|
"aria-hidden>\n <i />\n <i />\n <i />\n <span>LIVE</span>\n </div>\n <h2>群组 · 语音视频</h2>\n <p>\n {preferEmbed\n ?",
|
||||||
|
", event.target.value)}\n />\n </label>\n <label>\n 你能带来什么\n <textarea\n rows={5}\n maxLength={2000}\n value={draft.note}\n onChange={(event) => update(",
|
||||||
|
">\n {member.tags.map((t) => (\n <span key={t}>{t}</span>\n ))}\n </div>\n {member.languages?.length ? (\n <>\n <h2>语言</h2>\n <div className=",
|
||||||
|
"disabled={chat.sending}\n onClick={() => void chat.send(message.text, message.id)}\n >\n 重试\n </button>\n ) : message.mine && message.delivery ===",
|
||||||
|
"aria-hidden>\n 👋\n </span>\n 想见的人\n </h2>\n <p>\n 点开卡片,看看对方在做什么、想认识谁。\n 现在是示例介绍,方便你先逛逛\n {roster.some((m) => m.id === SELF_MEMBER_ID)\n ?",
|
||||||
|
"href={socialPath(`/meetup/${event.id}`)}\n >\n 进入聊聊 <ArrowUpRight size={15} />\n </Link>\n <BookmarkButton\n id={event.id}\n collection=",
|
||||||
|
">\n <Heart size={14} /> 点这里开始滑\n </span>\n </Link>\n </div>\n </div>\n </section>\n\n <FxBelt />\n\n <section\n className=",
|
||||||
|
">\n {toast}\n </div>\n ) : null}\n\n {matchMember ? (\n <SocialDialog\n title={`想认识 ${matchMember.name}`}\n onClose={() => setMatchId(null)}\n >\n <div className=",
|
||||||
|
">\n <span>详情</span>\n <ShareButton\n path={socialPath(`/coffeechat#${cafe.id}`)}\n title={`${cafe.city} · ${cafe.name}`}\n />\n </div>\n <h2>{cafe.name}</h2>\n <p className=",
|
||||||
|
"? <span>先留在你这边</span> : null}\n </header>\n <p>{m.text}</p>\n </div>\n ))}\n <div ref={bottomRef} />\n </div>\n <div className=",
|
||||||
|
"onClick={() => setActive(gig)}\n >\n 我想参与 <ArrowUpRight size={14} />\n </button>\n </article>\n ))}\n {!roles.length && (\n <EmptyState\n title=",
|
||||||
|
"href={socialPath(\n `/chat?intro=${encodeURIComponent(invitation)}`,\n )}\n >\n <MessageCircle size={15} />\n 去聊天室约人 <ArrowUpRight size={15} />\n </Link>\n <p className=",
|
||||||
|
"onClick={() => setContributeOpen(true)}\n >\n <PenLine size={14} />\n 我想投稿\n </button>\n </div>\n </div>\n <ResultSummary count={shown.length} unit={books ?",
|
||||||
|
"onClick={() => window.location.assign(videoSrc)}\n >\n 立即进入\n </button>\n </div>\n )}\n </section>\n )}\n\n {(layout ===",
|
||||||
|
"key={value}\n aria-label={`评分 ${value} 星`}\n aria-pressed={score === value}\n onClick={() => setScore(value)}\n className={value <= score ?",
|
||||||
|
">\n <Sparkles size={14} aria-hidden />\n <strong>想认识:</strong>\n {member.lookingFor}\n </p>\n {member.availability ? (\n <p className=",
|
||||||
|
"className={`social-library-art library-tone-${index % 3}`}\n onClick={() => setSelection(item.id)}\n aria-label={`查看${item.title}`}\n >\n <span className=",
|
||||||
|
"? 1 : passOpacity }}\n >\n 划走\n </span>\n <DateCardFace member={current} />\n </article>\n )}\n </div>\n\n <p className=",
|
||||||
|
"onClick={() => setLikesOpen(true)}\n >\n <Heart size={14} />\n 想认识 {liked.length}\n </button>\n ) : null}\n <ShareButton path={socialPath(",
|
||||||
|
">\n 草稿离线也能写。提交不等于立刻上线,只是先把想法放进来。\n </small>\n </form>\n </div>\n );\n}\n\nexport default function ResourceLibrary({ kind }: { kind: Kind }) {\n const [query, setQuery] = useState(",
|
||||||
|
"onClick={() => setMatchId(null)}\n >\n 继续看看\n </button>\n </div>\n </SocialDialog>\n ) : null}\n\n {likesOpen ? (\n <SocialDialog title=",
|
||||||
|
">\n 自我介绍\n <textarea\n rows={4}\n maxLength={600}\n value={profile.bio}\n onChange={(event) => update(",
|
||||||
|
");\n }\n } finally {\n lock.current = false;\n setBusy(false);\n }\n };\n const invitation = `有人约在 ${cafe.city} · ${cafe.name} 喝咖啡,一起聊聊远程生活?`;\n return (\n <section className=",
|
||||||
|
"href={socialPath(\n `/chat?intro=${encodeURIComponent(\n `嗨 ${m.name}!想认识你,方便聊聊吗?`,\n )}`,\n )}\n title=",
|
||||||
|
", e.target.value)}\n />\n </label>\n <label>\n 一句话介绍\n <textarea\n rows={4}\n maxLength={1200}\n placeholder=",
|
||||||
|
", event.target.value)}\n />\n </label>\n <label>\n 联系方式\n <input\n required\n maxLength={120}\n autoComplete=",
|
||||||
|
")}\n >\n 开始认识\n <ArrowUpRight size={16} />\n </Link>\n <Link\n className=",
|
||||||
|
")}\n >\n 先浏览大家\n </Link>\n </div>\n </div>\n <Link\n href={socialPath(",
|
||||||
|
", e.target.value)}\n />\n </label>\n <label>\n 联系方式\n <input\n required\n maxLength={120}\n placeholder=",
|
||||||
|
": `${i * -1.4}s`,\n } as CSSProperties\n }\n aria-label={`认识${m.name},${m.title}`}\n >\n <span className=",
|
||||||
|
"}\n aria-pressed={savedOnly}\n onClick={() => setSavedOnly(true)}\n >\n 收藏 · {saved.length}\n </button>\n <button\n type=",
|
||||||
|
">\n 视频暂时播不了,过一会儿再试试。\n </p>\n )}\n </>\n );\n}\n\nfunction ContributeForm({\n kind,\n onClose,\n}: {\n kind: Kind;\n onClose: () => void;\n}) {\n const books = kind ===",
|
||||||
|
"}」。`,\n )}`,\n )}\n >\n <MessageCircle size={15} />\n 进群组打招呼\n </Link>\n <Link\n className=",
|
||||||
|
"onClick={() => setJoinOpen(true)}\n >\n 加入游民社区 <ArrowUpRight size={19} />\n </button>\n </section>\n </main>\n\n <footer className=",
|
||||||
|
"}`}\n aria-pressed={savedOnly}\n onClick={() => setSavedOnly(!savedOnly)}\n >\n 收藏 · {saved.length}\n </button>\n </div>\n <div className=",
|
||||||
|
"}\n />\n </button>\n ))}\n </fieldset>\n <label>\n 体验\n <textarea\n aria-label=",
|
||||||
|
")}>\n <MessageCircle size={15} />\n 先去群组聊聊\n </Link>\n {liked.length > 0 && (\n <button\n type=",
|
||||||
|
"aria-hidden>\n <PenLine size={20} />\n </span>\n <strong>共创意向已提交</strong>\n <p>\n 已发送给社区运营。请保留联系方式,方便后续沟通。\n </p>\n <div className=",
|
||||||
|
")}>\n <Sparkles size={14} />\n 去共创逛逛\n </Link>\n </EmptyState>\n )}\n </div>\n {active && (\n <SocialDialog title=",
|
||||||
|
", e.target.value)}\n />\n </label>\n <label>\n 主题 / 暂定标题\n <input\n maxLength={120}\n placeholder={books ?",
|
||||||
|
">\n 找同城的人\n </Link>\n </div>\n </div>\n </section>\n\n <FxBelt />\n\n <section\n className=",
|
||||||
|
">\n <Globe2 size={15} />\n <span>\n 每场标注活动时区,并换算你的本地时间 · 「想参加」先记在你这边,还不等于已经约好\n </span>\n </div>\n <ResultSummary count={events.length} unit=",
|
||||||
|
">\n <div>\n <span>写好了多少</span>\n <strong>{complete}/5</strong>\n </div>\n <progress max={5} value={complete} aria-label=",
|
||||||
|
"}\n aria-pressed={!savedOnly}\n onClick={() => setSavedOnly(false)}\n >\n 全部\n </button>\n <button\n type=",
|
||||||
|
");\n }}\n >\n 重置筛选\n </button>\n </EmptyState>\n )}\n </div>\n {active && (\n <aside className=",
|
||||||
|
">\n <Coffee size={17} />\n <span>下一杯咖啡,和新朋友。</span>\n <span>↗</span>\n </div>\n </div>\n <div className=",
|
||||||
|
">\n <span aria-hidden style={{ fontSize: 36 }}>\n ✨\n </span>\n <strong>这批看完了</strong>\n <p className=",
|
||||||
|
">\n <span>认识一下</span>\n <span>左右滑</span>\n </span>\n <h2>\n <span className=",
|
||||||
|
">\n <ArrowDown size={14} /> 继续往下看\n </a>\n <span>认识人 · 开视频 · 见一面</span>\n </div>\n\n <dialog\n ref={dialogRef}\n className=",
|
||||||
|
">昵称</span>\n <input\n value={chat.nick}\n onChange={(e) => chat.setNick(e.target.value)}\n onBlur={() => saveJson(",
|
||||||
|
"href={socialPath(`/chat?intro=${intro}`)}\n >\n <MessageCircle size={15} />\n 进群组打招呼\n </Link>\n <Link className=",
|
||||||
|
"}}\n onClick={() => window.location.reload()}\n >\n 刷新重连\n </button>\n ) : null}\n </div>\n <div className=",
|
||||||
|
">\n <span>聊天群组</span>\n <span>语音 · 视频</span>\n </span>\n <h2>\n <span className=",
|
||||||
|
">\n <span>挑一座城</span>\n <span>再出来见面</span>\n </span>\n <h2>\n <span className=",
|
||||||
|
"href={socialPath(`/people/${m.id}`)}\n >\n 看看 TA\n </Link>\n <Link\n className=",
|
||||||
|
">\n 「想参加」还不等于已经约好 · 随时可以离开回去看别的场\n </p>\n </div>\n ) : preferEmbed ? (\n <div className=",
|
||||||
|
") {\n setRosterLike(member.id, true);\n setMatchId(member.id);\n flash(`想认识 ${member.name}`);\n } else {\n flash(",
|
||||||
|
");\n setSavedOnly(false);\n }}\n >\n 重置筛选\n </button>\n <button\n type=",
|
||||||
|
">\n <ArrowLeft size={15} /> 回去看看大家\n </Link>\n <DemoBadge>示例介绍 · 方便先逛逛</DemoBadge>\n </div>\n\n <header className=",
|
||||||
|
"onClick={resetDeck}\n >\n <RotateCcw size={15} />\n 再来一轮\n </button>\n <Link className=",
|
||||||
|
">\n <span>找搭子</span>\n <span>共创</span>\n </span>\n <h2>\n <span className=",
|
||||||
|
">\n 打开书库 <BookOpen size={15} />\n </Link>\n )}\n <Link\n className={`social-btn${books ?",
|
||||||
|
">\n <ArrowLeft size={14} />\n 返回\n </Link>\n <div>\n <strong>游民大厅</strong>\n <p className=",
|
||||||
|
">\n <ArrowLeft size={14} />\n 首页\n </Link>\n <div>\n <strong>认识一下</strong>\n <p className=",
|
||||||
|
");\n }}\n >\n 重新看看\n </button>\n </EmptyState>\n )}\n </div>\n <div className=",
|
||||||
|
">\n <DemoBadge>\n {list.length} 位 · 示例介绍,方便先逛逛\n </DemoBadge>\n </div>\n </PageIntro>\n <div className=",
|
||||||
|
"href={socialPath(\n `/chat?intro=${encodeURIComponent(\n `嗨 ${matchMember.name}!刚看到你,想聊聊「${matchMember.tags[0] ||",
|
||||||
|
">\n <SocialBrandLogo />\n <p>认识同频的人 · 开视频聊聊 · 出来见一面 · 一起做点事</p>\n </div>\n <div className=",
|
||||||
|
">\n 草稿会先留在你这边。提交只是表达兴趣,不代表已经被录用。\n </small>\n </form>\n </div>\n );\n}\n\nexport default function RoleBoard({\n initialKind =",
|
||||||
|
");\n setSavedOnly(false);\n }}\n >\n 重新看看\n </button>\n <Link className=",
|
||||||
|
")}\n >\n <Users size={14} />\n 找搭子\n </Link>\n <Link\n className={`social-btn${books ?",
|
||||||
|
"href={socialPath(`/people/${matchMember.id}`)}\n >\n 看看 TA\n </Link>\n <button\n type=",
|
||||||
|
">\n {draft.note.length}/2000 · 多写一点,对方更容易回你\n </small>\n </label>\n </fieldset>\n <div className=",
|
||||||
|
">\n 视频还没放出来,可以先收藏,或去聊天室聊聊。\n </p>\n )}\n {books && <p>先看看简介;想读全文可以去书库。</p>}\n <div className=",
|
||||||
|
">\n <span>\n 回复 {reply.author}:{reply.text.slice(0, 48)}\n </span>\n <button\n type=",
|
||||||
|
">\n <label>\n 怎么称呼你\n <input\n required\n maxLength={64}\n autoComplete=",
|
||||||
|
">\n <label>\n 怎么称呼你\n <input\n required\n maxLength={64}\n placeholder=",
|
||||||
|
")}>\n <MessageCircle size={14} />\n 群组约见面\n </Link>\n </div>\n </PageIntro>\n <p className=",
|
||||||
|
">\n 左滑划走 · 右滑想认识\n {totalForFilter\n ? ` · 还剩 ${remaining}/${totalForFilter}`\n :",
|
||||||
|
">\n 介绍还差 {5 - complete} 项,补全后再出现会更完整。\n </p>\n ) : null}\n <button\n type=",
|
||||||
|
">\n 打招呼\n </Link>\n </article>\n ))}\n </div>\n <div className=",
|
||||||
|
">\n <legend>评分</legend>\n {[1, 2, 3, 4, 5].map((value) => (\n <button\n type=",
|
||||||
|
"/> 连接没有边界\n </span>\n <span>先用示例看看感觉</span>\n </div>\n </div>\n </div>\n <div className=",
|
||||||
|
"aria-hidden>\n <Check size={22} strokeWidth={2.4} />\n </span>\n <strong>已表达兴趣</strong>\n <p>{status ||",
|
||||||
|
")}>\n <BookOpen size={14} />\n 共创\n </Link>\n <DemoBadge>\n {catalog.source ===",
|
||||||
|
">\n <h2>本页跳转进房</h2>\n <p>不新开标签;浏览器返回即可回到游民社区。</p>\n <button\n type=",
|
||||||
|
">\n <span>看看谁在这儿</span>\n <span>点开认识</span>\n </span>\n <h2>\n <span className=",
|
||||||
|
">\n ← 回去看场次\n </Link>\n <div>\n <strong>{meetup.title}</strong>\n <p className=",
|
||||||
|
">\n 评价 <span>{reviews.length}</span>\n </div>\n {!reviews.length ? (\n <EmptyState title=",
|
||||||
|
"? 1 : likeOpacity }}\n >\n 想认识\n </span>\n <span\n className=",
|
||||||
|
"onClick={() => startVideo()}\n >\n 进入聊聊\n </button>\n <p className=",
|
||||||
|
")}>\n 回社区首页\n </Link>\n </div>\n </div>\n ) : (\n <form className=",
|
||||||
|
")}>\n <Heart size={14} />\n 先去认识一下\n </Link>\n <Link className=",
|
||||||
|
">\n 认识同频的人 · 开视频聊聊 · 出来见一面 · 一起做点事\n <br />\n {channelHint}\n </p>\n\n <label className=",
|
||||||
|
"onClick={onReset}><X size={14} />重置筛选</button>}\n </div>\n );\n}\n\nexport function BookmarkButton({\n id,\n collection =",
|
||||||
|
",\n });\n }}\n >\n 最新消息 ↓\n </button>\n </div>\n <form\n className=",
|
||||||
|
")}\n >\n 小册\n </Link>\n <Link\n className={`social-btn${!books && kind ===",
|
||||||
|
"}\n </p>\n </div>\n <DemoBadge>示例介绍,方便先逛逛</DemoBadge>\n </div>\n <div className=",
|
||||||
|
"onClick={onJoin}\n >\n 加入社区认识\n </button>\n </div>\n\n <div\n className=",
|
||||||
|
">\n <Hash size={13} />\n <span>约咖啡、打招呼、找人聊天,都在这里说一声就行。</span>\n </div>\n <div className=",
|
||||||
|
"suppressHydrationWarning>\n {scheduled ? `你那边大约是:${start.toLocaleString([], {\n month:",
|
||||||
|
"&& <span>示例</span>}\n </header>\n <p>{message.text}</p>\n <div className=",
|
||||||
|
")}>\n 去左右滑\n </Link>\n <BookmarkButton\n id={member.id}\n collection=",
|
||||||
|
")}>\n <MessageCircle size={14} />\n 进群组聊天\n </Link>\n <Link className=",
|
||||||
|
">\n 想认识的人会先记在你这边。可以再看一轮,或去聊天室打个招呼。\n </p>\n <button\n type=",
|
||||||
|
")}>\n <BookOpen size={14} />\n 逛逛共创\n </Link>\n <button\n type=",
|
||||||
|
">什么时候方便 · {member.availability}</p>\n ) : null}\n </section>\n\n <section className=",
|
||||||
|
">\n <span>预览</span>\n <Sparkles size={16} />\n </div>\n <div className=",
|
||||||
|
"onClick={reset}\n >\n 再提一条\n </button>\n <Link className=",
|
||||||
|
">\n <Radio size={14} />\n 语音 / 视频场\n </Link>\n <Link href={socialPath(",
|
||||||
|
")}\n >\n 全部\n </button>\n <button\n aria-pressed={filter ===",
|
||||||
|
"}\n 位现在在线\n <span> · 示例数据</span>\n </p>\n <button\n type=",
|
||||||
|
")}\n >\n 我想参加的\n </button>\n </div>\n </div>\n <div className=",
|
||||||
|
"onClick={() => { setVideoReady(false); setLoadSlow(false); }}>离开视频</button>\n <button type=",
|
||||||
|
">\n {copy.socialHeroLine1}\n <br />\n 还好\n <span className=",
|
||||||
|
")}>\n <Video size={15} />\n 语音视频场\n </Link>\n <Link className=",
|
||||||
|
">\n 共创\n </Link>\n </div>\n\n <div className=",
|
||||||
|
">\n <Globe2 size={13} />\n <span>不止在线,更在身边</span>\n <span className=",
|
||||||
|
">\n 进入群聊 <ArrowUpRight size={14} />\n </Link>\n <Link href={socialPath(",
|
||||||
|
">\n 文字群聊\n </Link>\n <button\n type=",
|
||||||
|
"onClick={onClose}>\n 取消\n </button>\n </div>\n {status && <p role=",
|
||||||
|
">\n 逛共创\n </Link>\n <button\n type=",
|
||||||
|
">\n <Sparkles size={17} /> 游民社区\n </span>\n <button\n type=",
|
||||||
|
")}>\n <Users size={14} />\n 去找搭子\n </Link>\n <button type=",
|
||||||
|
">\n 写个主题或素材想法就行。不用一次写完,先表达兴趣。\n </p>\n </div>\n <form\n className=",
|
||||||
|
")}>\n 去加入社区\n </Link>\n </div>\n </section>\n <div className=",
|
||||||
|
">\n 「想认识」会先记在你这边。去群组打个招呼吧——是大家一起聊,不是一对一私信。\n </p>\n <div className=",
|
||||||
|
"}); }}>再写一个主题</button>\n </div>\n </div>\n );\n }\n\n return (\n <div className=",
|
||||||
|
")}>\n 去左右滑\n </Link>\n </div>\n </PageIntro>\n <p className=",
|
||||||
|
")}>查看全部场次</Link></EmptyState><SocialMobileDock /></div>;\n }\n\n return (\n <div className=",
|
||||||
|
"href={socialPath(\n `/chat?intro=${encodeURIComponent(`大家好,我是${profile.name ||",
|
||||||
|
")}\n >\n 视频\n </Link>\n <DemoBadge>\n {books ?",
|
||||||
|
">\n {copy.socialHeroAccent}\n </span>\n 不远<span className=",
|
||||||
|
">\n 看看咖啡馆\n </Link>\n <Link href={socialPath(",
|
||||||
|
"},想认识一下。`,\n );\n\n return (\n <SiteShell title={member.name}>\n <article className=",
|
||||||
|
"/>\n <p>名字 · 做什么 · 城市 · 兴趣 · 介绍</p>\n </div>\n <div className=",
|
||||||
|
">\n 更多机会\n </Link>\n <Link href={socialPath(",
|
||||||
|
">\n 看看全部\n </Link>\n <Link href={socialPath(",
|
||||||
|
"}\n ,先看看社区动态和活动,再决定要不要正式加入。\n </p>\n <button\n type=",
|
||||||
|
">\n 找搭子\n </Link>\n <Link href={socialPath(",
|
||||||
|
">也可以先写在你这边</span>\n </EmptyState>\n ) : (\n <div className=",
|
||||||
|
";\n\n/** @deprecated 请用 TeamClient;保留 re-export 避免旧 import 断裂 */\nexport { default } from",
|
||||||
|
">\n <h2>关于 TA</h2>\n <p>{member.bio}</p>\n <p className=",
|
||||||
|
">总频道 · 大家一起聊</p>\n </div>\n </div>\n </header>\n <div className=",
|
||||||
|
")}>\n 回去看看大家\n </Link>\n <button\n type=",
|
||||||
|
")}>\n <Sparkles size={15} /> 写写我的介绍\n </Link>\n <Link className=",
|
||||||
|
">\n 发不出去也没关系,会先留在你这边,有网后再试。我们会看,但不保证马上回复。\n </p>\n {delivery ===",
|
||||||
|
">\n <span />\n 方式一\n </span>\n <span className=",
|
||||||
|
">\n <span />\n 方式二\n </span>\n <span className=",
|
||||||
|
">数字游民小册</Link>\n </div>\n </div>\n <div className=",
|
||||||
|
">{roles.length} 个机会</span>\n </div>\n </PageIntro>\n <p className=",
|
||||||
|
">在线</span>\n ) : null}\n <div className=",
|
||||||
|
">\n <h4>认识人</h4>\n <button\n type=",
|
||||||
|
">\n 18.79° N · 清迈\n </span>\n <span className=",
|
||||||
|
">← 划走</span>\n <span>拖卡片左右滑 · 或点下面按钮</span>\n <span className=",
|
||||||
|
">\n 25.60° N · 大理\n </span>\n <div className=",
|
||||||
|
">\n <div>\n <h3>写评价</h3>\n <form\n className=",
|
||||||
|
">\n 先在聊天室约好时间,再出来见面。评分供参考,你也可以留下自己的体验。\n </p>\n <div className=",
|
||||||
|
"onClick={onClose}>\n 关闭\n </button>\n <button type=",
|
||||||
|
"style={{ marginTop: 28 }}>\n 适合见面的咖啡馆\n </h3>\n <div className=",
|
||||||
|
">\n 邮箱\n <input\n ref={inputRef}\n type=",
|
||||||
|
">\n <span />\n 说说你的想法\n </div>\n <h2 className=",
|
||||||
|
">\n 先在群里打个招呼;想开麦或开视频,再去「随时,聊得来」。\n </p>\n <section className=",
|
||||||
|
">\n 小册和视频都算「共创」——先逛逛现成的,也可以提交你想做的主题。\n </p>\n <div className=",
|
||||||
|
">暂时还不能购买</span>\n )}\n </article>\n <article className=",
|
||||||
|
">\n <h4>见面 · 做事</h4>\n <Link href={socialPath(",
|
||||||
|
">\n <span />\n 会员通行证\n </div>\n <h2 className=",
|
||||||
|
">\n 加入游民社区\n </h2>\n <p id={descriptionId} className=",
|
||||||
|
">\n 开通后能更方便参与社区。具体权益以支付页说明为准。\n </p>\n <ul className=",
|
||||||
|
">\n 先进聊天群组热热身,再开语音或视频见面——比只打字更近一点。\n </p>\n <div className=",
|
||||||
|
")}>\n 去认识一下\n </Link>\n <Link className=",
|
||||||
|
">\n 去左右滑认识\n </Link>\n <Link href={socialPath(",
|
||||||
|
"onClick={() => startVideo(true)}>重新连接</button>\n <a className=",
|
||||||
|
")}>\n 看发现页\n </Link>\n <Link className=",
|
||||||
|
">\n 看看更多人\n </Link>\n <Link href={socialPath(",
|
||||||
|
">\n 先选城市 → 找到同城的人 → 再挑一家咖啡馆出来坐坐。\n </p>\n <div className=",
|
||||||
|
"}`}\n aria-label={`${channel.name} 聊天`}\n >\n <div className=",
|
||||||
|
")}>\n 去左右滑认识更多人\n </Link>\n <Link className=",
|
||||||
|
">\n 远程也能一起推进:认领角色、写申请,草稿会先留在本机。\n </p>\n <div className=",
|
||||||
|
")}>\n 去群里打个招呼\n </Link>\n <Link className=",
|
||||||
|
">\n 写得越完整,别人越容易想认识你。草稿会先留在本机。\n </p>\n <div className=",
|
||||||
|
")}>\n 看看大家那边\n </Link>\n <Link className=",
|
||||||
|
")}>\n 找同城的人\n </Link>\n <Link className=",
|
||||||
|
")}>大家聊天</Link>\n </div>\n <div className=",
|
||||||
|
")}>说说想法</Link>\n </div>\n <div className=",
|
||||||
|
">收藏</option>\n </select>\n </div>\n <div className=",
|
||||||
|
">可以先看看</span>\n </div>\n <div className=",
|
||||||
|
"aria-label={`已填 ${filled} / 3`}\n >\n <span className=",
|
||||||
|
">\n 找搭子\n </span>\n <Link className=",
|
||||||
|
")}>\n 去左右滑认识\n </Link>\n <Link className=",
|
||||||
|
">\n 昵称\n <input\n aria-label=",
|
||||||
|
">\n 进群组聊天\n </Link>\n <button type=",
|
||||||
|
">随时可进</span>\n </div>\n <strong>{channel?.name ||",
|
||||||
|
"? <span>示例</span> : null}\n {m.delivery ===",
|
||||||
|
")}>\n 进群组聊天\n </Link>\n <Link className=",
|
||||||
|
">\n <h2>附近可能同城的人</h2>\n <div className=",
|
||||||
|
";\n\n/** 全站唯一聊天室频道(分类页暂时隐藏) */\nexport const SOCIAL_CHAT_ID =",
|
||||||
|
">\n <h4>更多</h4>\n <Link href=",
|
||||||
|
">新窗口打开</a>\n </div>}\n <label className=",
|
||||||
|
")}>开视频聊聊</Link>\n <Link href={socialPath(",
|
||||||
|
")}>找城市见面</Link>\n <Link href={socialPath(",
|
||||||
|
")}>找搭子做事</Link>\n <Link href={socialPath(",
|
||||||
|
">\n <h2>兴趣标签</h2>\n <div className=",
|
||||||
|
">\n <h2>生活瞬间</h2>\n <div className=",
|
||||||
|
">暂时还不能购买</span>\n )}\n <Link className=",
|
||||||
|
")}>想见的人</Link>\n <Link href={socialPath(",
|
||||||
|
")}>认识一下</Link>\n <Link href={socialPath(",
|
||||||
|
">先看看效果</span>\n <h2>{profile.name.trim() ||",
|
||||||
|
")}>共创</Link>\n <Link href={socialPath(",
|
||||||
|
">想认识 →</span>\n </p>\n <div className=",
|
||||||
|
">现在在线</span>\n ) : null}\n <div className=",
|
||||||
|
">👆 点卡片看看详情,也可以先点爱心关注</p>\n\n <div className=",
|
||||||
|
">哪里用得不顺手?告诉我们</h2>\n <p className=",
|
||||||
|
">旅居社群</Link>\n <Link href=",
|
||||||
|
">门户首页</Link>\n <Link href=",
|
||||||
|
">加入后可以先去这些地方</h3>\n <div className=",
|
||||||
|
">推荐</option>\n <option value=",
|
||||||
|
">网速</option>\n <option value=",
|
||||||
|
">评分</option>\n <option value=",
|
||||||
|
">中文</option>\n <option value=",
|
||||||
|
">游民会员</h2>\n <p className=",
|
||||||
|
"已加入当前设备的发现列表,方便预览。不会向其他用户公开发布。",
|
||||||
|
"点一句现成的话,或自己写一句。网络不好时,话会先留在你这边。",
|
||||||
|
"认识同频的人 · 开视频聊聊 · 出来见一面 · 一起做点事",
|
||||||
|
"作品链接请以 https:// 或 http:// 开头。",
|
||||||
|
"网络不太好:评价先留在你这边了,有网后再点「再发一次」。",
|
||||||
|
"这位朋友可能已离开,或者链接有点旧。回去再看看其他人吧。",
|
||||||
|
"先留在你这边了。有网后点评价下面的「再发一次」就行。",
|
||||||
|
"群里打个招呼 → 开麦 / 开视频 → 认识新朋友",
|
||||||
|
"这里暂时不能直接嵌视频,点下面会跳转到语音视频页。",
|
||||||
|
"名字 · 做什么 · 城市 · 兴趣 · 介绍",
|
||||||
|
"换个城市或兴趣关键词试试,也可以清空筛选再看。",
|
||||||
|
"暂时未发送,草稿已保留在当前设备。请重试提交。",
|
||||||
|
"约咖啡、打招呼、找人聊天,都在这里说一声就行。",
|
||||||
|
"评价已发布;列表暂未刷新,请稍后重新打开查看。",
|
||||||
|
"},目前在${profile.city ||",
|
||||||
|
"报到 / 找 cowork / 下一站去哪…",
|
||||||
|
"申请已提交。对方看到后会再联系你——先不急。",
|
||||||
|
"介绍已保存。你可以去聊天室跟大家打个招呼。",
|
||||||
|
"你可以继续编辑。资料草稿会保存在当前设备。",
|
||||||
|
"申请已先留在本机。有网后再点一次即可重试。",
|
||||||
|
"网络不太好 · 消息先留在你这边,有网再发",
|
||||||
|
"不新开标签;浏览器返回即可回到游民社区。",
|
||||||
|
"先留在你这边了。有网后再点一次保存就行。",
|
||||||
|
"独立开发者 / 设计师 / 自由撰稿人…",
|
||||||
|
"在当前设备的「想见的人」中预览我的介绍",
|
||||||
|
"邮箱 / 微信 / Telegram…",
|
||||||
|
"👆 点卡片看看详情,也可以先点爱心关注",
|
||||||
|
"先看看示例 · 连上后会变成实时聊天",
|
||||||
|
"场次可能已下线,请返回选择其他活动。",
|
||||||
|
"换个词试试,或者看看共创内容找灵感。",
|
||||||
|
"相关经历、作品链接、每周能投入多久…",
|
||||||
|
"网速 / 插座 / 适合工作还是聊天",
|
||||||
|
"设计, 摄影, 冲浪, 开源项目…",
|
||||||
|
"先看看简介;想读全文可以去书库。",
|
||||||
|
"刚左右滑认识了几位,来打个招呼~",
|
||||||
|
"连接较慢,可以重试或在新窗口打开",
|
||||||
|
"先打个招呼,或问问今晚谁在听。",
|
||||||
|
"先留在你这边了,有网后再试一次",
|
||||||
|
"具体页面 / 操作 / 期望…",
|
||||||
|
"拖卡片左右滑 · 或点下面按钮",
|
||||||
|
"换个词试试,或者看看全部场次。",
|
||||||
|
"换关键词,或提交你想做的主题。",
|
||||||
|
"排期待更新,请在活动频道确认。",
|
||||||
|
"有人一起找 cowork 吗?",
|
||||||
|
"认识人 · 开视频 · 见一面",
|
||||||
|
"已从当前设备的发现列表隐藏。",
|
||||||
|
"让别人更了解你的链接(选填)",
|
||||||
|
"例如:二楼靠窗合影位很好拍",
|
||||||
|
"大家一起聊 · 先打个招呼",
|
||||||
|
"清迈、里斯本,或者正在路上",
|
||||||
|
"游民闲聊 · 打个招呼就好",
|
||||||
|
"确认邮箱后,前往安全支付。",
|
||||||
|
"示例成员 · 可先进入了解",
|
||||||
|
"视频见面与同城活动更新提醒",
|
||||||
|
"角色 / 技能 / 关键词",
|
||||||
|
"先进群打个招呼,混个脸熟",
|
||||||
|
"哪里用得不顺手?告诉我们",
|
||||||
|
"城市 / 名字 / 兴趣",
|
||||||
|
"大家好,第一次来,我在…",
|
||||||
|
"将在微信内完成安全支付。",
|
||||||
|
"店名 / 城市 / 氛围",
|
||||||
|
"换个关键词,或清空筛选。",
|
||||||
|
"支付唤起失败,请稍后重试",
|
||||||
|
"有的可以看,有的先看封面",
|
||||||
|
"示例介绍 · 方便先逛逛",
|
||||||
|
"群组热身后,开麦或开视频",
|
||||||
|
"下一杯咖啡,和新朋友。",
|
||||||
|
"加入后可以先去这些地方",
|
||||||
|
"在哪、做什么、想认识谁",
|
||||||
|
"将前往小程序支付入口。",
|
||||||
|
"左右滑,慢慢认识新朋友",
|
||||||
|
"总频道 · 大家一起聊",
|
||||||
|
"游民社区 · 认识一下",
|
||||||
|
"聊天群组 · 语音视频",
|
||||||
|
"一个聊天室,简单好找",
|
||||||
|
"一个让人记得住的名字",
|
||||||
|
"仅在你愿意提供时填写",
|
||||||
|
"写几句,让别人认识你",
|
||||||
|
"可以再改一版后提交。",
|
||||||
|
"想拍 / 想聊的话题",
|
||||||
|
"找搭子做事时优先沟通",
|
||||||
|
"更好地展示自己的介绍",
|
||||||
|
"有人晚上开麦闲聊吗?",
|
||||||
|
"用新名字重新进入视频",
|
||||||
|
"示例介绍,方便先逛逛",
|
||||||
|
"下一站想去哪座城?",
|
||||||
|
"不止在线,更在身边",
|
||||||
|
"也可以先写在你这边",
|
||||||
|
"关注保存在当前设备",
|
||||||
|
"写一条帮后来的人。",
|
||||||
|
"发到活动文字频道…",
|
||||||
|
"已提交,感谢反馈。",
|
||||||
|
"换城市或清空筛选。",
|
||||||
|
"擅长什么,喜欢什么",
|
||||||
|
"收藏保存在当前设备",
|
||||||
|
"更方便认识想见的人",
|
||||||
|
"群组 · 语音视频",
|
||||||
|
"先用示例看看感觉",
|
||||||
|
"切换视觉动效强度",
|
||||||
|
"城市 / 关键词",
|
||||||
|
"左右滑,慢慢认识",
|
||||||
|
"已连上,可以聊天",
|
||||||
|
"很高兴认识大家!",
|
||||||
|
"文字频道还很安静",
|
||||||
|
"暂时没有合适的场",
|
||||||
|
"没有找到这个场次",
|
||||||
|
"群组 · 可线下",
|
||||||
|
"联系方式(选填)",
|
||||||
|
"评价已连接社区。",
|
||||||
|
"请复制地址栏链接",
|
||||||
|
"附近可能同城的人",
|
||||||
|
"主题 / 城市",
|
||||||
|
"书名 / 主题",
|
||||||
|
"做过类似项目…",
|
||||||
|
"先看看有哪些场",
|
||||||
|
"先看看这些地方",
|
||||||
|
"先看看这些机会",
|
||||||
|
"先简单介绍自己",
|
||||||
|
"共创 · 小册",
|
||||||
|
"共创 · 视频",
|
||||||
|
"共创 · 访谈",
|
||||||
|
"共创意向已提交",
|
||||||
|
"同频,自有引力",
|
||||||
|
"想一起做内容?",
|
||||||
|
"昵称或真名都行",
|
||||||
|
"暂时还不能购买",
|
||||||
|
"正在前往支付…",
|
||||||
|
"此刻在哪座城市",
|
||||||
|
"群组 · 文字",
|
||||||
|
"草稿还在你这边",
|
||||||
|
"见面 · 做事",
|
||||||
|
"视频 / 访谈",
|
||||||
|
"语音 · 视频",
|
||||||
|
"请输入有效邮箱",
|
||||||
|
"还没写自我介绍",
|
||||||
|
"邮箱 / 微信",
|
||||||
|
"· 示例数据",
|
||||||
|
"一起,做点事",
|
||||||
|
"作品在这里…",
|
||||||
|
"你正在做什么",
|
||||||
|
"先留在你这边",
|
||||||
|
"再写一个主题",
|
||||||
|
"发送参与申请",
|
||||||
|
"同城,见一面",
|
||||||
|
"城市与咖啡馆",
|
||||||
|
"想一起做成…",
|
||||||
|
"数字游民小册",
|
||||||
|
"本页跳转进房",
|
||||||
|
"查看全部场次",
|
||||||
|
"每周可投入…",
|
||||||
|
"没有这位游民",
|
||||||
|
"看看谁在这儿",
|
||||||
|
"群里还很安静",
|
||||||
|
"聊天暂时断了",
|
||||||
|
"让别人认识你",
|
||||||
|
"选择连接方式",
|
||||||
|
"随时,聊得来",
|
||||||
|
"一起做点事",
|
||||||
|
"上一张照片",
|
||||||
|
"下一张照片",
|
||||||
|
"你在做什么",
|
||||||
|
"先看看效果",
|
||||||
|
"先看看示例",
|
||||||
|
"关于 TA",
|
||||||
|
"关闭宣传片",
|
||||||
|
"再出来见面",
|
||||||
|
"写好了多少",
|
||||||
|
"可以先看看",
|
||||||
|
"可以提交了",
|
||||||
|
"可以见面做",
|
||||||
|
"同城见一面",
|
||||||
|
"咖啡馆排序",
|
||||||
|
"已表达兴趣",
|
||||||
|
"已重新洗牌",
|
||||||
|
"开视频聊聊",
|
||||||
|
"开视频见面",
|
||||||
|
"怎么称呼你",
|
||||||
|
"想认识 →",
|
||||||
|
"找城市见面",
|
||||||
|
"找搭子做事",
|
||||||
|
"推荐见面点",
|
||||||
|
"搜索咖啡馆",
|
||||||
|
"撤销上一次",
|
||||||
|
"新窗口打开",
|
||||||
|
"时间待确认",
|
||||||
|
"暂时没找到",
|
||||||
|
"正在连上…",
|
||||||
|
"没有咖啡馆",
|
||||||
|
"确认并支付",
|
||||||
|
"线上也能做",
|
||||||
|
"网络不太好",
|
||||||
|
"聊天已接通",
|
||||||
|
"认识新朋友",
|
||||||
|
"评价已发布",
|
||||||
|
"还没写城市",
|
||||||
|
"这批看完了",
|
||||||
|
"← 划走",
|
||||||
|
"一起做事",
|
||||||
|
"你的邮箱",
|
||||||
|
"保存中…",
|
||||||
|
"保存介绍",
|
||||||
|
"先看封面",
|
||||||
|
"共创小册",
|
||||||
|
"关注一下",
|
||||||
|
"兴趣标签",
|
||||||
|
"加入社区",
|
||||||
|
"北京时间",
|
||||||
|
"取消关注",
|
||||||
|
"取消回复",
|
||||||
|
"只看聊天",
|
||||||
|
"只看视频",
|
||||||
|
"听听大家",
|
||||||
|
"在线游民",
|
||||||
|
"城市筛选",
|
||||||
|
"大家写的",
|
||||||
|
"大家拍的",
|
||||||
|
"大家聊天",
|
||||||
|
"家咖啡馆",
|
||||||
|
"开始看看",
|
||||||
|
"开始认识",
|
||||||
|
"开通会员",
|
||||||
|
"想见的人",
|
||||||
|
"想认识:",
|
||||||
|
"意见反馈",
|
||||||
|
"我们在听",
|
||||||
|
"我关注的",
|
||||||
|
"我的介绍",
|
||||||
|
"找咖啡馆",
|
||||||
|
"挑一座城",
|
||||||
|
"接通中…",
|
||||||
|
"提交中…",
|
||||||
|
"提交意向",
|
||||||
|
"文字频道",
|
||||||
|
"旅居社群",
|
||||||
|
"暂时没有",
|
||||||
|
"最新地点",
|
||||||
|
"最新场次",
|
||||||
|
"最新机会",
|
||||||
|
"本页导航",
|
||||||
|
"消息内容",
|
||||||
|
"清空搜索",
|
||||||
|
"游民会员",
|
||||||
|
"游民大厅",
|
||||||
|
"点开认识",
|
||||||
|
"现在在线",
|
||||||
|
"生活瞬间",
|
||||||
|
"看看机会",
|
||||||
|
"示例在线",
|
||||||
|
"示例成员",
|
||||||
|
"社区收录",
|
||||||
|
"离开视频",
|
||||||
|
"群组聊天",
|
||||||
|
"聊天消息",
|
||||||
|
"聊天群组",
|
||||||
|
"认识一下",
|
||||||
|
"说说想法",
|
||||||
|
"选择表情",
|
||||||
|
"重新连接",
|
||||||
|
"重置筛选",
|
||||||
|
"重试提交",
|
||||||
|
"重试连接",
|
||||||
|
"门户首页",
|
||||||
|
"随时可进",
|
||||||
|
"· 我",
|
||||||
|
"一起看",
|
||||||
|
"个机会",
|
||||||
|
"个视频",
|
||||||
|
"位朋友",
|
||||||
|
"写评价",
|
||||||
|
"去写写",
|
||||||
|
"去看看",
|
||||||
|
"去聊聊",
|
||||||
|
"可以看",
|
||||||
|
"可播放",
|
||||||
|
"左右滑",
|
||||||
|
"已保存",
|
||||||
|
"已关注",
|
||||||
|
"已分享",
|
||||||
|
"已复制",
|
||||||
|
"已提交",
|
||||||
|
"已撤销",
|
||||||
|
"已收藏",
|
||||||
|
"开视频",
|
||||||
|
"待讨论",
|
||||||
|
"怎么看",
|
||||||
|
"想参加",
|
||||||
|
"想认识",
|
||||||
|
"找搭子",
|
||||||
|
"显示名",
|
||||||
|
"未找到",
|
||||||
|
"查看中",
|
||||||
|
"见一面",
|
||||||
|
"认识人",
|
||||||
|
"这是我",
|
||||||
|
"进群聊",
|
||||||
|
"选城市",
|
||||||
|
"项结果",
|
||||||
|
"中文",
|
||||||
|
"会员",
|
||||||
|
"全部",
|
||||||
|
"共创",
|
||||||
|
"关注",
|
||||||
|
"关闭",
|
||||||
|
"分享",
|
||||||
|
"反馈",
|
||||||
|
"发布",
|
||||||
|
"在线",
|
||||||
|
"女生",
|
||||||
|
"小册",
|
||||||
|
"建议",
|
||||||
|
"推荐",
|
||||||
|
"提交",
|
||||||
|
"搜索",
|
||||||
|
"收藏",
|
||||||
|
"昵称",
|
||||||
|
"更多",
|
||||||
|
"查看",
|
||||||
|
"沉浸",
|
||||||
|
"游民",
|
||||||
|
"男生",
|
||||||
|
"示例",
|
||||||
|
"离线",
|
||||||
|
"筛选",
|
||||||
|
"网速",
|
||||||
|
"评分",
|
||||||
|
"详情",
|
||||||
|
"语言",
|
||||||
|
"跳过",
|
||||||
|
"轻量",
|
||||||
|
"重试",
|
||||||
|
"阅读",
|
||||||
|
"预览"
|
||||||
|
]
|
||||||
@ -46,7 +46,23 @@ async function req<T>(
|
|||||||
});
|
});
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
const err = await res.text().catch(() => "");
|
const err = await res.text().catch(() => "");
|
||||||
throw new Error(err || `HTTP ${res.status}`);
|
let msg = err || `HTTP ${res.status}`;
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(err) as { detail?: unknown };
|
||||||
|
if (typeof parsed.detail === "string") msg = parsed.detail;
|
||||||
|
else if (Array.isArray(parsed.detail)) {
|
||||||
|
msg = parsed.detail
|
||||||
|
.map((d) =>
|
||||||
|
typeof d === "object" && d && "msg" in d
|
||||||
|
? String((d as { msg: string }).msg)
|
||||||
|
: String(d),
|
||||||
|
)
|
||||||
|
.join("; ");
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* keep raw */
|
||||||
|
}
|
||||||
|
throw new Error(msg);
|
||||||
}
|
}
|
||||||
const data = (await res.json()) as T;
|
const data = (await res.json()) as T;
|
||||||
if (cacheKey) _memTtl.set(cacheKey, { at: Date.now(), data });
|
if (cacheKey) _memTtl.set(cacheKey, { at: Date.now(), data });
|
||||||
@ -496,4 +512,122 @@ export const socialApi = {
|
|||||||
req<{ ok: boolean }>(`/trips/${encodeURIComponent(tripId)}`, {
|
req<{ ok: boolean }>(`/trips/${encodeURIComponent(tripId)}`, {
|
||||||
method: "DELETE",
|
method: "DELETE",
|
||||||
}),
|
}),
|
||||||
|
|
||||||
|
listSkills: (opts?: { city?: string; limit?: number }) => {
|
||||||
|
const q = new URLSearchParams();
|
||||||
|
if (opts?.city) q.set("city", opts.city);
|
||||||
|
if (opts?.limit) q.set("limit", String(opts.limit));
|
||||||
|
const qs = q.toString();
|
||||||
|
return req<{
|
||||||
|
ok: boolean;
|
||||||
|
items: Array<{
|
||||||
|
id: string;
|
||||||
|
guestId: string;
|
||||||
|
author: string;
|
||||||
|
city: string;
|
||||||
|
offer: string;
|
||||||
|
want: string;
|
||||||
|
note: string;
|
||||||
|
status: string;
|
||||||
|
createdAt: string;
|
||||||
|
}>;
|
||||||
|
}>(`/skills${qs ? `?${qs}` : ""}`, { ttlMs: 15_000 });
|
||||||
|
},
|
||||||
|
|
||||||
|
createSkill: (payload: {
|
||||||
|
author: string;
|
||||||
|
city: string;
|
||||||
|
offer: string;
|
||||||
|
want: string;
|
||||||
|
note?: string;
|
||||||
|
}) => req("/skills", { method: "POST", json: payload }),
|
||||||
|
|
||||||
|
closeSkill: (id: string) =>
|
||||||
|
req(`/skills/${encodeURIComponent(id)}/close`, { method: "POST" }),
|
||||||
|
|
||||||
|
postMeetupReview: (payload: {
|
||||||
|
toGuest: string;
|
||||||
|
toName?: string;
|
||||||
|
bookingId?: string;
|
||||||
|
punctuality: number;
|
||||||
|
chemistry: number;
|
||||||
|
professionalism: number;
|
||||||
|
text?: string;
|
||||||
|
}) => req("/reviews", { method: "POST", json: payload }),
|
||||||
|
|
||||||
|
getReviews: (guestId: string) =>
|
||||||
|
req<{
|
||||||
|
ok: boolean;
|
||||||
|
count: number;
|
||||||
|
averages: {
|
||||||
|
punctuality: number;
|
||||||
|
chemistry: number;
|
||||||
|
professionalism: number;
|
||||||
|
overall: number;
|
||||||
|
} | null;
|
||||||
|
items: Array<{
|
||||||
|
id: string;
|
||||||
|
punctuality: number;
|
||||||
|
chemistry: number;
|
||||||
|
professionalism: number;
|
||||||
|
text: string;
|
||||||
|
avg: number;
|
||||||
|
createdAt: string;
|
||||||
|
}>;
|
||||||
|
}>(`/reviews/${encodeURIComponent(guestId)}`, { ttlMs: 20_000 }),
|
||||||
|
|
||||||
|
blockUser: (blockedGuest: string, reason?: string) =>
|
||||||
|
req("/blocks", {
|
||||||
|
method: "POST",
|
||||||
|
json: { blockedGuest, reason: reason || "" },
|
||||||
|
}),
|
||||||
|
|
||||||
|
unblockUser: (blockedGuest: string) =>
|
||||||
|
req(`/blocks/${encodeURIComponent(blockedGuest)}`, { method: "DELETE" }),
|
||||||
|
|
||||||
|
listBlocks: () =>
|
||||||
|
req<{ ok: boolean; items: Array<{ blockedGuest: string; reason: string }> }>(
|
||||||
|
"/blocks",
|
||||||
|
),
|
||||||
|
|
||||||
|
reportUser: (payload: {
|
||||||
|
targetGuest: string;
|
||||||
|
targetName?: string;
|
||||||
|
reason: string;
|
||||||
|
detail?: string;
|
||||||
|
}) => req("/reports", { method: "POST", json: payload }),
|
||||||
|
|
||||||
|
notifyLike: (toGuest: string, fromName: string) =>
|
||||||
|
req("/social-events/like", {
|
||||||
|
method: "POST",
|
||||||
|
json: { toGuest, fromName },
|
||||||
|
}),
|
||||||
|
|
||||||
|
notifyBoardJoin: (ownerGuest: string, actorName: string, boardTitle: string) =>
|
||||||
|
req("/social-events/board-join", {
|
||||||
|
method: "POST",
|
||||||
|
json: { ownerGuest, actorName, boardTitle },
|
||||||
|
}),
|
||||||
|
|
||||||
|
getWrapped: (year?: number) => {
|
||||||
|
const q = year ? `?year=${year}` : "";
|
||||||
|
return req<{
|
||||||
|
ok: boolean;
|
||||||
|
year: number;
|
||||||
|
name: string;
|
||||||
|
homeCity: string;
|
||||||
|
cities: string[];
|
||||||
|
cityCount: number;
|
||||||
|
peopleMet: number;
|
||||||
|
meetups: number;
|
||||||
|
skillPosts: number;
|
||||||
|
livenessVerified: boolean;
|
||||||
|
}>(`/wrapped${q}`);
|
||||||
|
},
|
||||||
|
|
||||||
|
fireCityDigest: (city: string, weekly = false) =>
|
||||||
|
req("/digests/city", {
|
||||||
|
method: "POST",
|
||||||
|
json: { city, weekly },
|
||||||
|
}),
|
||||||
};
|
};
|
||||||
|
|||||||
@ -117,23 +117,26 @@ const zh: SocialDictionary = {
|
|||||||
{ href: "/map", label: "地图", emoji: "🗺️" },
|
{ href: "/map", label: "地图", emoji: "🗺️" },
|
||||||
{ href: "/places", label: "城市", emoji: "📍" },
|
{ href: "/places", label: "城市", emoji: "📍" },
|
||||||
{ href: "/coffeechat", label: "咖啡聊预约", emoji: "☕" },
|
{ href: "/coffeechat", label: "咖啡聊预约", emoji: "☕" },
|
||||||
|
{ href: "/skills", label: "技能交换", emoji: "🔄" },
|
||||||
{ href: "/date", label: "认识一下", emoji: "💕" },
|
{ href: "/date", label: "认识一下", emoji: "💕" },
|
||||||
{ href: "/meetup", label: "聊得来", emoji: "📡" },
|
{ href: "/meetup", label: "聊得来", emoji: "📡" },
|
||||||
{ href: "/chat", label: "群聊", emoji: "💬" },
|
{ href: "/chat", label: "群聊", emoji: "💬" },
|
||||||
{ href: "/team", label: "一起做事", emoji: "🚀" },
|
{ href: "/team", label: "一起做事", emoji: "🚀" },
|
||||||
{ href: "/work", label: "远程工作", emoji: "🗂️" },
|
{ href: "/work", label: "远程工作", emoji: "🗂️" },
|
||||||
{ href: "/ebook", label: "共创", emoji: "🎨" },
|
{ href: "/ebook", label: "共创", emoji: "🎨" },
|
||||||
|
{ href: "/wrapped", label: "年度回顾", emoji: "✨" },
|
||||||
{ href: "/roster", label: "我的介绍", emoji: "🪪" },
|
{ href: "/roster", label: "我的介绍", emoji: "🪪" },
|
||||||
{ href: "/join", label: "加入社区", emoji: "✨" },
|
{ href: "/join", label: "加入社区", emoji: "✨" },
|
||||||
],
|
],
|
||||||
homePath: [
|
homePath: [
|
||||||
{ href: "#people", label: "想见的人", emoji: "👋" },
|
{ href: "#people", label: "想见的人", emoji: "👋" },
|
||||||
{ href: "#date", label: "认识一下", emoji: "💕" },
|
{ href: "#date", label: "认识一下", emoji: "💕" },
|
||||||
{ href: "#meetup", label: "聊得来", emoji: "📡" },
|
{ href: "#coffeechat", label: "咖啡聊", emoji: "☕" },
|
||||||
|
{ href: "#skills", label: "技能交换", emoji: "🔄" },
|
||||||
{ href: "#cities", label: "城市", emoji: "📍" },
|
{ href: "#cities", label: "城市", emoji: "📍" },
|
||||||
{ href: "/map", label: "地图", emoji: "🗺️", external: true },
|
{ href: "/map", label: "地图", emoji: "🗺️", external: true },
|
||||||
{ href: "#team", label: "一起做事", emoji: "🚀" },
|
{ href: "#team", label: "一起做事", emoji: "🚀" },
|
||||||
{ href: "/chat", label: "群聊", emoji: "💬", external: true },
|
{ href: "/wrapped", label: "年度回顾", emoji: "✨", external: true },
|
||||||
],
|
],
|
||||||
landing: {
|
landing: {
|
||||||
socialEyebrow: "自由生活,同频相遇",
|
socialEyebrow: "自由生活,同频相遇",
|
||||||
@ -220,23 +223,26 @@ const en: SocialDictionary = {
|
|||||||
{ href: "/map", label: "Map", emoji: "🗺️" },
|
{ href: "/map", label: "Map", emoji: "🗺️" },
|
||||||
{ href: "/places", label: "Cities", emoji: "📍" },
|
{ href: "/places", label: "Cities", emoji: "📍" },
|
||||||
{ href: "/coffeechat", label: "Coffee booking", emoji: "☕" },
|
{ href: "/coffeechat", label: "Coffee booking", emoji: "☕" },
|
||||||
|
{ href: "/skills", label: "Skill swap", emoji: "🔄" },
|
||||||
{ href: "/date", label: "Say hi", emoji: "💕" },
|
{ href: "/date", label: "Say hi", emoji: "💕" },
|
||||||
{ href: "/meetup", label: "Sync", emoji: "📡" },
|
{ href: "/meetup", label: "Sync", emoji: "📡" },
|
||||||
{ href: "/chat", label: "Chat", emoji: "💬" },
|
{ href: "/chat", label: "Chat", emoji: "💬" },
|
||||||
{ href: "/team", label: "Collaborate", emoji: "🚀" },
|
{ href: "/team", label: "Collaborate", emoji: "🚀" },
|
||||||
{ href: "/work", label: "Remote work", emoji: "🗂️" },
|
{ href: "/work", label: "Remote work", emoji: "🗂️" },
|
||||||
{ href: "/ebook", label: "Co-create", emoji: "🎨" },
|
{ href: "/ebook", label: "Co-create", emoji: "🎨" },
|
||||||
|
{ href: "/wrapped", label: "Year wrapped", emoji: "✨" },
|
||||||
{ href: "/roster", label: "My intro", emoji: "🪪" },
|
{ href: "/roster", label: "My intro", emoji: "🪪" },
|
||||||
{ href: "/join", label: "Join", emoji: "✨" },
|
{ href: "/join", label: "Join", emoji: "✨" },
|
||||||
],
|
],
|
||||||
homePath: [
|
homePath: [
|
||||||
{ href: "#people", label: "People", emoji: "👋" },
|
{ href: "#people", label: "People", emoji: "👋" },
|
||||||
{ href: "#date", label: "Say hi", emoji: "💕" },
|
{ href: "#date", label: "Say hi", emoji: "💕" },
|
||||||
{ href: "#meetup", label: "Sync", emoji: "📡" },
|
{ href: "#coffeechat", label: "Coffee chat", emoji: "☕" },
|
||||||
|
{ href: "#skills", label: "Skill swap", emoji: "🔄" },
|
||||||
{ href: "#cities", label: "Cities", emoji: "📍" },
|
{ href: "#cities", label: "Cities", emoji: "📍" },
|
||||||
{ href: "/map", label: "Map", emoji: "🗺️", external: true },
|
{ href: "/map", label: "Map", emoji: "🗺️", external: true },
|
||||||
{ href: "#team", label: "Collaborate", emoji: "🚀" },
|
{ href: "#team", label: "Collaborate", emoji: "🚀" },
|
||||||
{ href: "/chat", label: "Chat", emoji: "💬", external: true },
|
{ href: "/wrapped", label: "Year wrapped", emoji: "✨", external: true },
|
||||||
],
|
],
|
||||||
landing: {
|
landing: {
|
||||||
socialEyebrow: "Free living · same wavelength",
|
socialEyebrow: "Free living · same wavelength",
|
||||||
|
|||||||
@ -138,6 +138,15 @@ export function markJoinProfileDone(): void {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Re-open profile form (e.g. ?step=profile after wipe / localhost QA). */
|
||||||
|
export function clearJoinProfileDone(): void {
|
||||||
|
try {
|
||||||
|
localStorage.removeItem(JOIN_PROFILE_DONE_KEY);
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** After /paid confirms success — send joiners to profile step. */
|
/** After /paid confirms success — send joiners to profile step. */
|
||||||
export function resolvePostPayHref(): string {
|
export function resolvePostPayHref(): string {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@ -348,7 +348,13 @@ export const SOCIAL_PHRASES_EN: Record<string, string> = {
|
|||||||
"已检测到人脸。请继续现场实拍(全程录像)以开放约会等功能":
|
"已检测到人脸。请继续现场实拍(全程录像)以开放约会等功能":
|
||||||
"Face found — finish live capture (full recording) to unlock dating & more",
|
"Face found — finish live capture (full recording) to unlock dating & more",
|
||||||
"真人核验已通过,头像可用于社区":
|
"真人核验已通过,头像可用于社区":
|
||||||
"Liveness verified — avatar ready for the community",
|
"Liveness verified — gated features unlocked",
|
||||||
|
"头像已就绪 · 真人核验已通过,约会等功能已开放":
|
||||||
|
"Avatar ready · liveness verified — dating & coffeechat unlocked",
|
||||||
|
"真人核验已通过。请上传正脸照片作为头像(实拍仅用于核验,不是头像)":
|
||||||
|
"Liveness verified. Upload a front-face photo as your avatar (live capture is not the avatar).",
|
||||||
|
"真人核验已通过。请再上传一张正脸照片作为头像(相册或自拍)。":
|
||||||
|
"Liveness verified. Please upload a front-face photo as your avatar (album or selfie).",
|
||||||
"人脸已通过。必须完成现场实拍核验(全程录像,供人工审核),否则约会 / 咖啡聊 / 视频厅等功能无法开放。":
|
"人脸已通过。必须完成现场实拍核验(全程录像,供人工审核),否则约会 / 咖啡聊 / 视频厅等功能无法开放。":
|
||||||
"Face OK. Live capture with full recording is required for dating / coffeechat / rooms — kept for human review.",
|
"Face OK. Live capture with full recording is required for dating / coffeechat / rooms — kept for human review.",
|
||||||
"开始实拍核验": "Start live verification",
|
"开始实拍核验": "Start live verification",
|
||||||
@ -471,4 +477,136 @@ export const SOCIAL_PHRASES_EN: Record<string, string> = {
|
|||||||
"怎么称呼你": "What should we call you",
|
"怎么称呼你": "What should we call you",
|
||||||
"还好": "Lucky",
|
"还好": "Lucky",
|
||||||
"不远": "are close",
|
"不远": "are close",
|
||||||
|
"技能交换": "Skill swap",
|
||||||
|
"技能交换 / 互助板": "Skill swap / help board",
|
||||||
|
"教英语换拍视频、帮忙看代码换签证咨询——写清楚你能给什么、想换什么。":
|
||||||
|
"Trade English practice for video shoots, code review for visa tips — say what you offer and want.",
|
||||||
|
"发一条互换": "Post a swap",
|
||||||
|
"城市": "City",
|
||||||
|
"清迈 / 线上": "Chiang Mai / remote",
|
||||||
|
"我能提供": "I can offer",
|
||||||
|
"英语陪练 / 代码 review / …": "English practice / code review / …",
|
||||||
|
"想换到": "Looking for",
|
||||||
|
"拍视频 / 签证咨询 / …": "Video / visa tips / …",
|
||||||
|
"补充说明": "Notes",
|
||||||
|
"时间、线上线下、期望频率…": "Timing, online/offline, frequency…",
|
||||||
|
"发布失败": "Publish failed",
|
||||||
|
"发布中…": "Publishing…",
|
||||||
|
"发布互换": "Publish swap",
|
||||||
|
"按城市筛选": "Filter by city",
|
||||||
|
"筛选": "Filter",
|
||||||
|
"全球 / 线上": "Global / remote",
|
||||||
|
"关闭": "Close",
|
||||||
|
"年度回顾": "Year wrapped",
|
||||||
|
"的这一年": "’s year",
|
||||||
|
"加载失败": "Failed to load",
|
||||||
|
"主场在": "Home base",
|
||||||
|
"还在路上,主场待填写": "Still on the road — set your home base",
|
||||||
|
"真人核验已通过": "Liveness verified",
|
||||||
|
"去完成真人核验": "Finish liveness check",
|
||||||
|
"座城市足迹": "cities visited",
|
||||||
|
"位想认识的人": "people you met",
|
||||||
|
"次咖啡聊评价": "coffeechat reviews",
|
||||||
|
"条技能互换": "skill swaps",
|
||||||
|
"足迹城市": "Cities",
|
||||||
|
"去技能板": "Skill board",
|
||||||
|
"举报": "Report",
|
||||||
|
"屏蔽": "Block",
|
||||||
|
"原因": "Reason",
|
||||||
|
"已提交举报,处理结果会通知你": "Report submitted — we’ll notify you of the result",
|
||||||
|
"提交失败": "Submit failed",
|
||||||
|
"已屏蔽,双方将不再互相看到": "Blocked — you won’t see each other",
|
||||||
|
"操作失败": "Action failed",
|
||||||
|
"提交中…": "Submitting…",
|
||||||
|
"提交举报": "Submit report",
|
||||||
|
"确认屏蔽": "Confirm block",
|
||||||
|
"骚扰 / 不当言论": "Harassment / abuse",
|
||||||
|
"虚假资料": "Fake profile",
|
||||||
|
"垃圾广告": "Spam",
|
||||||
|
"人身安全顾虑": "Safety concern",
|
||||||
|
"其他": "Other",
|
||||||
|
"见面评价": "Meetup reviews",
|
||||||
|
"条": "",
|
||||||
|
"守时": "Punctuality",
|
||||||
|
"聊得来": "Chemistry",
|
||||||
|
"靠谱": "Professionalism",
|
||||||
|
"未写文字评价": "No written note",
|
||||||
|
"评价失败": "Review failed",
|
||||||
|
"找同频的人": "Find your people",
|
||||||
|
"还好": "thankfully ",
|
||||||
|
"不远": " isn’t far",
|
||||||
|
"我的状态": "My status",
|
||||||
|
"城市待填": "City unset",
|
||||||
|
"核验进度": "Verification",
|
||||||
|
"正脸": "Face",
|
||||||
|
"实拍": "Live",
|
||||||
|
"去完善核验": "Finish verification",
|
||||||
|
"上传正脸后,再完成现场实拍": "Upload a face photo, then live-verify",
|
||||||
|
"下一步:上传清晰正脸照片(头像 ≠ 实拍)":
|
||||||
|
"Next: upload a clear face photo (avatar ≠ live capture)",
|
||||||
|
"实拍已提交,等待审核通过": "Live capture submitted — awaiting review",
|
||||||
|
"下一步:现场实拍核验(全程录像)": "Next: live selfie verification (full recording)",
|
||||||
|
"去咖啡聊": "Coffee chat",
|
||||||
|
"核验已通过 · 可以约会 / 咖啡聊":
|
||||||
|
"Verified — dating & coffeechat unlocked",
|
||||||
|
"去左右滑": "Start swiping",
|
||||||
|
"行动入口": "Quick actions",
|
||||||
|
"先逛逛同频": "Browse people first",
|
||||||
|
"左右滑": "Swipe",
|
||||||
|
"一张一张认识": "Meet one by one",
|
||||||
|
"咖啡聊": "Coffee chat",
|
||||||
|
"约一杯见面": "Book a café meet",
|
||||||
|
"技能板": "Skill board",
|
||||||
|
"互换互助": "Trade & help",
|
||||||
|
"同城足迹": "City footprint",
|
||||||
|
"先完成实拍": "Verify live first",
|
||||||
|
"能提供": "Offers",
|
||||||
|
"去发互换": "Post a swap",
|
||||||
|
"主持人": "Host",
|
||||||
|
"数字游民主持人 · 咖啡馆轻聊,帮你破冰同城":
|
||||||
|
"Nomad host · easy café chats to break the ice in-city",
|
||||||
|
"不想自己硬约?先和主持人喝杯咖啡,轻松认识同城游民。":
|
||||||
|
"Rather not cold-DM? Book a host coffee and meet locals easily.",
|
||||||
|
"完成实拍后可预约": "Available after live verification",
|
||||||
|
"去预约": "Book now",
|
||||||
|
"地图摘要": "Map snapshot",
|
||||||
|
"热门城市聚合 · 不暴露精确位置":
|
||||||
|
"Hot cities clustered · no exact location shared",
|
||||||
|
"打开地图": "Open map",
|
||||||
|
"逛城市": "Browse cities",
|
||||||
|
"咖啡馆见面": "Café meetups",
|
||||||
|
"清迈": "Chiang Mai",
|
||||||
|
"巴厘岛": "Bali",
|
||||||
|
"大理": "Dali",
|
||||||
|
"里斯本": "Lisbon",
|
||||||
|
"成都": "Chengdu",
|
||||||
|
"回看这一年的足迹与遇见": "Look back at this year’s places & meets",
|
||||||
|
"同城": "Same city",
|
||||||
|
"已关注": "Following",
|
||||||
|
"全部": "All",
|
||||||
|
"在线": "Online",
|
||||||
|
"女生": "Women",
|
||||||
|
"男生": "Men",
|
||||||
|
"先填写你的城市,才能筛同城的人":
|
||||||
|
"Add your city first to filter people nearby",
|
||||||
|
"暂时没有同城的人,先完善介绍或换个城市看看":
|
||||||
|
"No one in your city yet — finish your intro or try another city",
|
||||||
|
"还没有关注的人,点爱心收藏想见的人":
|
||||||
|
"No follows yet — tap ♥ on people you want to meet",
|
||||||
|
"这里暂时没人,去写介绍或加入社区吧":
|
||||||
|
"No one here yet — write your intro or join",
|
||||||
|
"去完善介绍": "Complete my intro",
|
||||||
|
"看全部": "Show all",
|
||||||
|
"点开卡片,看看对方在做什么、想认识谁。":
|
||||||
|
"Open a card to see what they’re up to and who they want to meet.",
|
||||||
|
"现在是示例介绍,方便你先逛逛": " Sample intros so you can browse first",
|
||||||
|
"(也包含你写好的介绍)": " (includes your intro)",
|
||||||
|
"位现在在线": "online now",
|
||||||
|
"示例数据": "sample data",
|
||||||
|
"加入社区认识": "Join to meet people",
|
||||||
|
"我": "me",
|
||||||
|
"取消关注": "Unfollow",
|
||||||
|
"关注": "Follow",
|
||||||
|
"👆 点卡片看看详情,也可以先点爱心关注":
|
||||||
|
"👆 Tap a card for details, or ♥ to follow",
|
||||||
};
|
};
|
||||||
|
|||||||
@ -53,6 +53,15 @@ export default function BoardsClient() {
|
|||||||
setName("");
|
setName("");
|
||||||
await load();
|
await load();
|
||||||
if (project.board_id) {
|
if (project.board_id) {
|
||||||
|
try {
|
||||||
|
const { getGuestId } = await import("@social/lib/api");
|
||||||
|
window.localStorage.setItem(
|
||||||
|
`work-board-owner:${project.board_id}`,
|
||||||
|
getGuestId(),
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
window.location.href = socialPath(`/work/boards/${project.board_id}`);
|
window.location.href = socialPath(`/work/boards/${project.board_id}`);
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
|
|||||||
@ -142,13 +142,29 @@ export default function CardModal({
|
|||||||
async function addMember(e: FormEvent) {
|
async function addMember(e: FormEvent) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
if (!memberName.trim()) return;
|
if (!memberName.trim()) return;
|
||||||
const data = await workApi.toggleMember(
|
const who = memberName.trim();
|
||||||
boardId,
|
const data = await workApi.toggleMember(boardId, card.id, who);
|
||||||
card.id,
|
|
||||||
memberName.trim(),
|
|
||||||
);
|
|
||||||
onBoard(data.board);
|
onBoard(data.board);
|
||||||
setMemberName("");
|
setMemberName("");
|
||||||
|
// Best-effort: notify board "owner" stored locally when project was created
|
||||||
|
try {
|
||||||
|
const { socialApi, getGuestId } = await import("@social/lib/api");
|
||||||
|
const ownerKey = `work-board-owner:${boardId}`;
|
||||||
|
const owner =
|
||||||
|
(typeof window !== "undefined" &&
|
||||||
|
window.localStorage.getItem(ownerKey)) ||
|
||||||
|
"";
|
||||||
|
const me = getGuestId();
|
||||||
|
if (owner && owner !== me) {
|
||||||
|
void socialApi
|
||||||
|
.notifyBoardJoin(owner, who, board.name || "看板")
|
||||||
|
.catch(() => undefined);
|
||||||
|
} else if (!owner) {
|
||||||
|
window.localStorage.setItem(ownerKey, me);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function addAttachment(e: FormEvent) {
|
async function addAttachment(e: FormEvent) {
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user