Ship WeChat audit release 2026-11-02: realtime config, audit vip-ebook shell, admin ops.
Document test9 tag 2026-11-02 for upload; POST config pull + WS, fixed dark home, no debug bar. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
f20406397a
commit
4389ebe6cb
@ -14,7 +14,7 @@ Follow `.cursor/rules/*.mdc`.
|
|||||||
|
|
||||||
根目录:`pnpm install` → `pnpm dev` / `dev:h5` / `dev:admin` / `dev:api` / `typecheck` / `clean`。
|
根目录:`pnpm install` → `pnpm dev` / `dev:h5` / `dev:admin` / `dev:api` / `typecheck` / `clean`。
|
||||||
|
|
||||||
Remote config: `/api/config` + offline defaults. Do not reintroduce deleted vertical trees (`payjsapi` / `community-api` / `ebook` / `navmini` / `nomadweb` / `nomadvip` / `wemini`).
|
Remote config: `POST /api/config/pull` · `WS /api/config/ws` · offline defaults. Current WeChat audit branch/tag: `test9` / `2026-11-02`. Do not reintroduce deleted vertical trees (`payjsapi` / `community-api` / `ebook` / `navmini` / `nomadweb` / `nomadvip` / `wemini`).
|
||||||
|
|
||||||
**全端小程序禁止 web-view**(微信 / 抖音 / 小红书 / H5 SoT):业务内容必须原生页;见 `.cursor/rules/no-webview-content.mdc`。
|
**全端小程序禁止 web-view**(微信 / 抖音 / 小红书 / H5 SoT):业务内容必须原生页;见 `.cursor/rules/no-webview-content.mdc`。
|
||||||
|
|
||||||
|
|||||||
36
README.md
36
README.md
@ -116,10 +116,10 @@ pnpm dev:api
|
|||||||
- **远程配置 + 离线兜底**:`/api/config` · `data/remote-config.json` · `/admin/config`
|
- **远程配置 + 离线兜底**:`/api/config` · `data/remote-config.json` · `/admin/config`
|
||||||
- **禁止**再引入已删垂直树(见 `AGENTS.md`)
|
- **禁止**再引入已删垂直树(见 `AGENTS.md`)
|
||||||
- **发布流**:本地调试 → 当前开发分支 commit/push → 部署脚本上线 → 冒烟;配置与发版均以 git 为准
|
- **发布流**:本地调试 → 当前开发分支 commit/push → 部署脚本上线 → 冒烟;配置与发版均以 git 为准
|
||||||
- 审核冻结分支:`pre4`(**微信审核包,勿在本分支继续功能迭代**)
|
- 审核冻结分支:`pre4`(历史审核包);**本轮微信提审包:`test9` + tag `2026-11-02`**
|
||||||
- `pre5`:承接 pre4 之后的功能(含游民社区 `/social`)
|
- `pre5`:承接 pre4 之后的功能(含游民社区 `/social`)
|
||||||
- `test5` / `test6`:游民社区实时层与 H5 初版(已合入后续分支)
|
- `test5`–`test8`:游民社区 / 原生 weapp 迭代线(已合入 `test9`)
|
||||||
- **当前开发分支:`test8`**(从 `test7` 拉出);发版线 `test7` 已含 H5 深优
|
- **当前开发 / 提审分支:`test9`**(tag `2026-11-02`)
|
||||||
|
|
||||||
### 游民社区(`/social`)
|
### 游民社区(`/social`)
|
||||||
|
|
||||||
@ -182,9 +182,31 @@ pnpm dev:api
|
|||||||
- **Meetup**:活动卡保留参与者头像 + 声纹条
|
- **Meetup**:活动卡保留参与者头像 + 声纹条
|
||||||
- **发版**:`python deploy/social/deploy_82.py`(仅 82;**2C/4G**:堆 1536MB + swap + nice;打包跳过 `__pycache__`;勿并发 SSH);冒烟 `https://nomadro.cn/social`
|
- **发版**:`python deploy/social/deploy_82.py`(仅 82;**2C/4G**:堆 1536MB + swap + nice;打包跳过 `__pycache__`;勿并发 SSH);冒烟 `https://nomadro.cn/social`
|
||||||
|
|
||||||
## test8(当前开发)
|
## test8
|
||||||
|
|
||||||
从 `test7` 切出,承接后续 `/social` 与门户迭代。后续还可做:课时资料后台可视化、桥接 UX、真机网络/域名排查。
|
从 `test7` 切出;原生 weapp 游民社区、SRS 直播、加群支付等已合入 `test9`。
|
||||||
|
|
||||||
|
## test9 · tag `2026-11-02`(微信提审包)
|
||||||
|
|
||||||
|
从 `test8` / `f204063` 线切出并定版,准备上传微信审核与上线。
|
||||||
|
|
||||||
|
| 项 | 说明 |
|
||||||
|
|---|---|
|
||||||
|
| 分支 / Tag | `test9` · **`2026-11-02`** |
|
||||||
|
| 启动页 | `pages/home/index`;门户入口 2×2;固定暗色(无主题切换) |
|
||||||
|
| 远程配置 | `POST /api/config/pull`(避微信 GET 缓存)· `WS /api/config/ws` · SSE `/stream` · meta 兜底;后台 `/wechat/switches` |
|
||||||
|
| 数字游民提审 | VIP→电子书→数字游民开关;开则 `vip-ebook` 同壳读 audit 正文(失联才包内兜底);关则正式 nomad |
|
||||||
|
| 管理后台 | 开关 / Social / 社群数据 / Books CRUD;`admin.nomadro.cn` |
|
||||||
|
| API | `config_live` 推送;admin CRUD;sqlite 加固;已部署 `api.nomadro.cn` |
|
||||||
|
| 禁令 | 全端无业务 web-view;WXSS 禁裸 `*`(sanitize) |
|
||||||
|
|
||||||
|
提审上传:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pnpm build:weapp
|
||||||
|
# 微信开发者工具打开 apps/miniprogram/weapp(miniprogramRoot=dist/)→ 上传
|
||||||
|
# 后台按需打开「数字游民」提审;socket 合法域名含 api.nomadro.cn
|
||||||
|
```
|
||||||
|
|
||||||
## pre3 摘要(已合入)
|
## pre3 摘要(已合入)
|
||||||
|
|
||||||
@ -197,6 +219,4 @@ pnpm dev:api
|
|||||||
|
|
||||||
构建微信包:`pnpm build:weapp` / `pnpm dev:weapp` → 开发者工具打开 `apps/miniprogram/weapp`(读 `dist/`)。图片域名需放行 `nomadro.cn`。
|
构建微信包:`pnpm build:weapp` / `pnpm dev:weapp` → 开发者工具打开 `apps/miniprogram/weapp`(读 `dist/`)。图片域名需放行 `nomadro.cn`。
|
||||||
|
|
||||||
微信启动首页为 **`pages/home/index`**(官方话题/体验码同路径;视觉对齐 **`20261011`**;路径 **`20261011b`**;**审核包 tag `20261011-2`**)。`pages/index/index` 仅作兼容:`reLaunch` → home(勿与 home 共用组件入口,否则页面 wxss 缺失)。详见 `apps/miniprogram/weapp/README.md`。
|
微信启动首页为 **`pages/home/index`**。历史审核 tag:`20261011` / `20261011b` / `20261011-2`;**本轮提审 tag:`2026-11-02`(分支 `test9`)**。`pages/index/index` 仅兼容 `reLaunch` → home。详见 `apps/miniprogram/weapp/README.md`。
|
||||||
|
|
||||||
提审上传:本地 `pnpm build:weapp` → 开发者工具打开 `apps/miniprogram/weapp`(读 `dist/`)→ 上传体验版;后台「数字游民」提审开关按需开启。
|
|
||||||
|
|||||||
19
apps/admin/deploy/_check_book_audit.py
Normal file
19
apps/admin/deploy/_check_book_audit.py
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||||
|
url = "https://api.nomadro.cn/api/ebook/config"
|
||||||
|
with urllib.request.urlopen(url, timeout=15) as r:
|
||||||
|
d = json.loads(r.read().decode("utf-8", "replace"))
|
||||||
|
cfg = d.get("config") or {}
|
||||||
|
flags = cfg.get("flags") or {}
|
||||||
|
copy = cfg.get("copy") or {}
|
||||||
|
plat = ((cfg.get("platforms") or {}).get("weapp") or {})
|
||||||
|
print("flags.reviewMode / bookAudit =", {k: flags.get(k) for k in flags if "audit" in k.lower() or "review" in k.lower()})
|
||||||
|
print("copy keys sample", [k for k in copy if "audit" in k.lower() or "book" in k.lower() or "review" in k.lower()])
|
||||||
|
print("weapp keys", list(plat.keys())[:20])
|
||||||
|
# dump relevant
|
||||||
|
import pprint
|
||||||
|
pprint.pp({k: flags[k] for k in sorted(flags) if k in flags})
|
||||||
110
apps/admin/deploy/_fix_audit_book_api.py
Normal file
110
apps/admin/deploy/_fix_audit_book_api.py
Normal file
@ -0,0 +1,110 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""Fix audit book API 500 (missing chapter order) + deploy read_policy/store."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import paramiko
|
||||||
|
|
||||||
|
REPO = Path(__file__).resolve().parents[3]
|
||||||
|
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
|
||||||
|
|
||||||
|
FILES = [
|
||||||
|
(
|
||||||
|
REPO / "apps/api/services/ebook_svc/domains/books/read_policy.py",
|
||||||
|
"/opt/nomadmini/backend/app/domains/books/read_policy.py",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
REPO / "apps/api/services/ebook_svc/services/store.py",
|
||||||
|
"/opt/nomadmini/backend/app/services/store.py",
|
||||||
|
),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
c = paramiko.SSHClient()
|
||||||
|
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||||
|
c.connect(HOST, username=USER, password=PASS, timeout=60, allow_agent=False, look_for_keys=False)
|
||||||
|
sftp = c.open_sftp()
|
||||||
|
for src, dest in FILES:
|
||||||
|
data = src.read_text(encoding="utf-8").replace("ebook_svc.", "app.").encode("utf-8")
|
||||||
|
tmp = f"/tmp/{Path(dest).name}"
|
||||||
|
with sftp.file(tmp, "wb") as rf:
|
||||||
|
rf.write(data)
|
||||||
|
print("upload", src.name, flush=True)
|
||||||
|
sftp.close()
|
||||||
|
|
||||||
|
cmd = r"""
|
||||||
|
set -e
|
||||||
|
sudo cp /tmp/read_policy.py /opt/nomadmini/backend/app/domains/books/read_policy.py
|
||||||
|
sudo cp /tmp/store.py /opt/nomadmini/backend/app/services/store.py
|
||||||
|
|
||||||
|
python3 - <<'PY'
|
||||||
|
import json, sqlite3, time
|
||||||
|
db='/opt/nomadmini/data/nomadmini.db'
|
||||||
|
con=sqlite3.connect(db)
|
||||||
|
row=con.execute("select chapters_json from books where id='audit'").fetchone()
|
||||||
|
if row:
|
||||||
|
ch=json.loads(row[0] or '[]')
|
||||||
|
fixed=[]
|
||||||
|
for i,c in enumerate(ch if isinstance(ch,list) else []):
|
||||||
|
if not isinstance(c, dict):
|
||||||
|
continue
|
||||||
|
c=dict(c)
|
||||||
|
c['id']=str(c.get('id') or f'ch-{i+1}')
|
||||||
|
c['title']=str(c.get('title') or f'章节 {i+1}')
|
||||||
|
c['order']=int(c['order']) if c.get('order') is not None else i+1
|
||||||
|
c['content']=str(c.get('content') or '')
|
||||||
|
fixed.append(c)
|
||||||
|
if not fixed:
|
||||||
|
fixed=[{
|
||||||
|
'id':'01-audit','title':'欢迎阅读','order':1,
|
||||||
|
'content':'# 数字游民·提审版\n\n这是微信提审用的独立内容,与会员正式书无关。\n'
|
||||||
|
}]
|
||||||
|
con.execute(
|
||||||
|
"update books set title=?, subtitle=?, unlock_percent=100, price_fen=0, product_id='', chapters_json=?, updated_at=? where id='audit'",
|
||||||
|
('数字游民·提审版','微信提审专用 · 与正式会员书无关', json.dumps(fixed, ensure_ascii=False), time.time())
|
||||||
|
)
|
||||||
|
con.commit()
|
||||||
|
print('fixed chapters', len(fixed), 'orders', [x['order'] for x in fixed])
|
||||||
|
else:
|
||||||
|
print('no audit row')
|
||||||
|
PY
|
||||||
|
|
||||||
|
sudo systemctl restart nomadmini-api
|
||||||
|
sleep 2
|
||||||
|
systemctl is-active nomadmini-api
|
||||||
|
curl -sk -o /tmp/audit.json -w "books/audit %{http_code}\n" "https://api.nomadro.cn/api/ebook/books/audit"
|
||||||
|
python3 - <<'PY'
|
||||||
|
import json
|
||||||
|
d=json.load(open('/tmp/audit.json',encoding='utf-8'))
|
||||||
|
print('title', d.get('title'), 'chapters', len(d.get('chapters') or []), 'free', d.get('is_free'))
|
||||||
|
print('ch0', (d.get('chapters') or [{}])[0])
|
||||||
|
PY
|
||||||
|
curl -sk -o /tmp/audit_read.json -w "books/audit/read %{http_code}\n" "https://api.nomadro.cn/api/ebook/books/audit/read"
|
||||||
|
python3 - <<'PY'
|
||||||
|
import json
|
||||||
|
d=json.load(open('/tmp/audit_read.json',encoding='utf-8'))
|
||||||
|
chs=d.get('chapters') or []
|
||||||
|
print('read chapters', len(chs), 'title', (d.get('book') or {}).get('title'))
|
||||||
|
if chs:
|
||||||
|
print('body', (chs[0].get('content') or '')[:120].replace('\n',' '))
|
||||||
|
PY
|
||||||
|
rm -f /tmp/read_policy.py /tmp/store.py /tmp/audit.json /tmp/audit_read.json
|
||||||
|
"""
|
||||||
|
_, stdout, _ = c.exec_command(cmd, timeout=120, get_pty=True)
|
||||||
|
while not stdout.channel.exit_status_ready():
|
||||||
|
if stdout.channel.recv_ready():
|
||||||
|
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
|
||||||
|
time.sleep(0.05)
|
||||||
|
while stdout.channel.recv_ready():
|
||||||
|
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
|
||||||
|
code = stdout.channel.recv_exit_status()
|
||||||
|
print(f"[exit {code}]", flush=True)
|
||||||
|
c.close()
|
||||||
|
return code
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
56
apps/admin/deploy/_fix_audit_read_anon.py
Normal file
56
apps/admin/deploy/_fix_audit_read_anon.py
Normal file
@ -0,0 +1,56 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import paramiko
|
||||||
|
|
||||||
|
REPO = Path(__file__).resolve().parents[3]
|
||||||
|
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
|
||||||
|
FILES = [
|
||||||
|
(REPO / "apps/api/services/ebook_svc/core/deps.py", "/opt/nomadmini/backend/app/core/deps.py"),
|
||||||
|
(REPO / "apps/api/services/ebook_svc/routers/books.py", "/opt/nomadmini/backend/app/routers/books.py"),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
c = paramiko.SSHClient()
|
||||||
|
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||||
|
c.connect(HOST, username=USER, password=PASS, timeout=60, allow_agent=False, look_for_keys=False)
|
||||||
|
sftp = c.open_sftp()
|
||||||
|
for src, dest in FILES:
|
||||||
|
data = src.read_text(encoding="utf-8").replace("ebook_svc.", "app.").encode("utf-8")
|
||||||
|
with sftp.file(f"/tmp/{Path(dest).name}", "wb") as rf:
|
||||||
|
rf.write(data)
|
||||||
|
sftp.close()
|
||||||
|
cmd = r"""
|
||||||
|
set -e
|
||||||
|
sudo cp /tmp/deps.py /opt/nomadmini/backend/app/core/deps.py
|
||||||
|
sudo cp /tmp/books.py /opt/nomadmini/backend/app/routers/books.py
|
||||||
|
sudo systemctl restart nomadmini-api
|
||||||
|
sleep 2
|
||||||
|
curl -sk -o /tmp/r.json -w "read %{http_code}\n" https://api.nomadro.cn/api/ebook/books/audit/read
|
||||||
|
python3 - <<'PY'
|
||||||
|
import json
|
||||||
|
d=json.load(open('/tmp/r.json',encoding='utf-8'))
|
||||||
|
print('title', (d.get('book') or {}).get('title'))
|
||||||
|
print('chapters', len(d.get('chapters') or []))
|
||||||
|
body=((d.get('chapters') or [{}])[0].get('content') or '')[:100]
|
||||||
|
print('body', body.replace('\n',' '))
|
||||||
|
PY
|
||||||
|
"""
|
||||||
|
_, stdout, _ = c.exec_command(cmd, timeout=90, get_pty=True)
|
||||||
|
while not stdout.channel.exit_status_ready():
|
||||||
|
if stdout.channel.recv_ready():
|
||||||
|
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
|
||||||
|
time.sleep(0.05)
|
||||||
|
while stdout.channel.recv_ready():
|
||||||
|
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
|
||||||
|
code = stdout.channel.recv_exit_status()
|
||||||
|
c.close()
|
||||||
|
return code
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
39
apps/admin/deploy/_fix_config_ws_nginx.py
Normal file
39
apps/admin/deploy/_fix_config_ws_nginx.py
Normal file
@ -0,0 +1,39 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import paramiko
|
||||||
|
|
||||||
|
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
|
||||||
|
|
||||||
|
REMOTE = r"""
|
||||||
|
set -e
|
||||||
|
ls -la /www/server/panel/vhost/nginx/*api* 2>/dev/null || true
|
||||||
|
echo ---CONF---
|
||||||
|
CONF=/www/server/panel/vhost/nginx/api.nomadro.cn.conf
|
||||||
|
if [ -f "$CONF" ]; then
|
||||||
|
grep -n 'config/ws\|proxy_pass\|location /' "$CONF" | head -80
|
||||||
|
else
|
||||||
|
echo missing_conf
|
||||||
|
ls /www/server/panel/vhost/nginx/ | head
|
||||||
|
fi
|
||||||
|
echo ---DIRECT---
|
||||||
|
curl -sk -i -N --max-time 3 \
|
||||||
|
-H 'Connection: Upgrade' \
|
||||||
|
-H 'Upgrade: websocket' \
|
||||||
|
-H 'Sec-WebSocket-Version: 13' \
|
||||||
|
-H 'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==' \
|
||||||
|
http://127.0.0.1:8010/api/config/ws | head -30
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
c = paramiko.SSHClient()
|
||||||
|
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||||
|
c.connect(HOST, username=USER, password=PASS, timeout=30, allow_agent=False, look_for_keys=False)
|
||||||
|
_, stdout, _ = c.exec_command(REMOTE, timeout=60)
|
||||||
|
print(stdout.read().decode("utf-8", "replace"))
|
||||||
|
c.close()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
30
apps/admin/deploy/_fix_config_ws_nginx2.py
Normal file
30
apps/admin/deploy/_fix_config_ws_nginx2.py
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import paramiko
|
||||||
|
|
||||||
|
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
|
||||||
|
|
||||||
|
REMOTE = r"""
|
||||||
|
set -e
|
||||||
|
echo '=== find api host conf ==='
|
||||||
|
sudo grep -RIl 'api.nomadro.cn' /www/server/panel/vhost/nginx /etc/nginx /www/server/nginx/conf 2>/dev/null | head -30
|
||||||
|
echo '=== find 8010 ==='
|
||||||
|
sudo grep -RIl '8010' /www/server/panel/vhost/nginx /etc/nginx /www/server/nginx/conf 2>/dev/null | head -30
|
||||||
|
echo '=== our bak? ==='
|
||||||
|
ls -la /www/server/panel/vhost/nginx/api.nomadro.cn.conf* 2>/dev/null || true
|
||||||
|
ls -la /www/server/panel/vhost/nginx/*.bak-config-ws 2>/dev/null || true
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
c = paramiko.SSHClient()
|
||||||
|
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||||
|
c.connect(HOST, username=USER, password=PASS, timeout=30, allow_agent=False, look_for_keys=False)
|
||||||
|
_, stdout, _ = c.exec_command(REMOTE, timeout=90)
|
||||||
|
print(stdout.read().decode("utf-8", "replace"))
|
||||||
|
c.close()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
26
apps/admin/deploy/_fix_nginx_ws3.py
Normal file
26
apps/admin/deploy/_fix_nginx_ws3.py
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import paramiko
|
||||||
|
|
||||||
|
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
|
||||||
|
|
||||||
|
REMOTE = r"""
|
||||||
|
CONF=/www/server/panel/vhost/nginx/api.nomadro.cn.conf
|
||||||
|
sudo sed -n '1,220p' "$CONF"
|
||||||
|
echo '===== WS LOC ====='
|
||||||
|
sudo grep -n 'config/ws\|Upgrade\|location ' "$CONF" | head -80
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
c = paramiko.SSHClient()
|
||||||
|
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||||
|
c.connect(HOST, username=USER, password=PASS, timeout=30, allow_agent=False, look_for_keys=False)
|
||||||
|
_, stdout, _ = c.exec_command(REMOTE, timeout=60)
|
||||||
|
print(stdout.read().decode("utf-8", "replace"))
|
||||||
|
c.close()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
89
apps/admin/deploy/_fix_nginx_ws_ssl.py
Normal file
89
apps/admin/deploy/_fix_nginx_ws_ssl.py
Normal file
@ -0,0 +1,89 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""Patch api.nomadro.cn 443 block for /api/config/ws Upgrade."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import paramiko
|
||||||
|
|
||||||
|
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
|
||||||
|
|
||||||
|
PATCHER = r'''
|
||||||
|
from pathlib import Path
|
||||||
|
import shutil
|
||||||
|
p = Path("/www/server/panel/vhost/nginx/api.nomadro.cn.conf")
|
||||||
|
text = p.read_text(encoding="utf-8")
|
||||||
|
marker = "location /api/config/ws"
|
||||||
|
parts = text.split("listen 443")
|
||||||
|
if len(parts) < 2:
|
||||||
|
raise SystemExit("no 443 block")
|
||||||
|
if marker in parts[1]:
|
||||||
|
print("ssl_ws_already")
|
||||||
|
raise SystemExit(0)
|
||||||
|
lines = [
|
||||||
|
"",
|
||||||
|
" location /api/config/ws {",
|
||||||
|
" proxy_pass http://127.0.0.1:8010;",
|
||||||
|
" proxy_http_version 1.1;",
|
||||||
|
" proxy_set_header Upgrade $http_upgrade;",
|
||||||
|
' proxy_set_header Connection "upgrade";',
|
||||||
|
" proxy_set_header Host $host;",
|
||||||
|
" proxy_set_header X-Real-IP $remote_addr;",
|
||||||
|
" proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;",
|
||||||
|
" proxy_set_header X-Forwarded-Proto $scheme;",
|
||||||
|
" proxy_read_timeout 3600s;",
|
||||||
|
" proxy_send_timeout 3600s;",
|
||||||
|
" proxy_buffering off;",
|
||||||
|
" }",
|
||||||
|
" location /api/ebook/config/ws {",
|
||||||
|
" proxy_pass http://127.0.0.1:8010;",
|
||||||
|
" proxy_http_version 1.1;",
|
||||||
|
" proxy_set_header Upgrade $http_upgrade;",
|
||||||
|
' proxy_set_header Connection "upgrade";',
|
||||||
|
" proxy_set_header Host $host;",
|
||||||
|
" proxy_set_header X-Real-IP $remote_addr;",
|
||||||
|
" proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;",
|
||||||
|
" proxy_set_header X-Forwarded-Proto $scheme;",
|
||||||
|
" proxy_read_timeout 3600s;",
|
||||||
|
" proxy_send_timeout 3600s;",
|
||||||
|
" proxy_buffering off;",
|
||||||
|
" }",
|
||||||
|
"",
|
||||||
|
]
|
||||||
|
snippet = "\n".join(lines)
|
||||||
|
ssl = parts[1]
|
||||||
|
idx = ssl.find("location / {")
|
||||||
|
if idx < 0:
|
||||||
|
raise SystemExit("no location / in 443")
|
||||||
|
ssl2 = ssl[:idx] + snippet + "\n" + ssl[idx:]
|
||||||
|
out = parts[0] + "listen 443" + ssl2
|
||||||
|
shutil.copy2(p, str(p) + ".bak-ws-ssl")
|
||||||
|
p.write_text(out, encoding="utf-8")
|
||||||
|
print("ssl_ws_patched")
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
c = paramiko.SSHClient()
|
||||||
|
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||||
|
c.connect(HOST, username=USER, password=PASS, timeout=30, allow_agent=False, look_for_keys=False)
|
||||||
|
sftp = c.open_sftp()
|
||||||
|
with sftp.file("/tmp/patch_ws_ssl.py", "w") as rf:
|
||||||
|
rf.write(PATCHER)
|
||||||
|
sftp.close()
|
||||||
|
cmd = "sudo python3 /tmp/patch_ws_ssl.py && sudo nginx -t && sudo nginx -s reload && rm -f /tmp/patch_ws_ssl.py && echo DONE"
|
||||||
|
_, stdout, _ = c.exec_command(cmd, timeout=90, get_pty=True)
|
||||||
|
while not stdout.channel.exit_status_ready():
|
||||||
|
if stdout.channel.recv_ready():
|
||||||
|
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
|
||||||
|
time.sleep(0.05)
|
||||||
|
while stdout.channel.recv_ready():
|
||||||
|
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
|
||||||
|
code = stdout.channel.recv_exit_status()
|
||||||
|
c.close()
|
||||||
|
return code
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
257
apps/admin/deploy/_push_admin_crud.py
Normal file
257
apps/admin/deploy/_push_admin_crud.py
Normal file
@ -0,0 +1,257 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""Deploy admin SPA + CRUD APIs (stats series, social ugc, community, memo/books/orders).
|
||||||
|
|
||||||
|
- Never wipe catalogs unless catalog PUT is called by operator
|
||||||
|
- Snapshot /api/config version before/after
|
||||||
|
- Set SOCIAL_DB_PATH + fix social.db perms for www
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import subprocess
|
||||||
|
import tarfile
|
||||||
|
import time
|
||||||
|
import urllib.request
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import paramiko
|
||||||
|
|
||||||
|
REPO = Path(__file__).resolve().parents[3]
|
||||||
|
ADMIN = REPO / "apps/admin"
|
||||||
|
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
|
||||||
|
|
||||||
|
API_FILES = [
|
||||||
|
("apps/api/services/ebook_svc/services/store.py", "services/store.py"),
|
||||||
|
("apps/api/services/ebook_svc/services/social_ugc.py", "services/social_ugc.py"),
|
||||||
|
("apps/api/services/ebook_svc/services/memo_store.py", "services/memo_store.py"),
|
||||||
|
("apps/api/services/ebook_svc/services/shop_store.py", "services/shop_store.py"),
|
||||||
|
("apps/api/services/ebook_svc/schemas/admin.py", "schemas/admin.py"),
|
||||||
|
("apps/api/services/ebook_svc/routers/admin.py", "routers/admin.py"),
|
||||||
|
("apps/api/services/ebook_svc/routers/social_ugc_admin.py", "routers/social_ugc_admin.py"),
|
||||||
|
("apps/api/services/ebook_svc/routers/community_admin.py", "routers/community_admin.py"),
|
||||||
|
("apps/api/services/ebook_svc/routers/memo_admin.py", "routers/memo_admin.py"),
|
||||||
|
("apps/api/services/ebook_svc/routers/shop_admin.py", "routers/shop_admin.py"),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def rewrite(text: str) -> str:
|
||||||
|
return text.replace("ebook_svc.", "app.")
|
||||||
|
|
||||||
|
|
||||||
|
def snapshot() -> dict:
|
||||||
|
req = urllib.request.Request(
|
||||||
|
"https://api.nomadro.cn/api/config",
|
||||||
|
headers={"User-Agent": "nomadro-admin-crud-deploy"},
|
||||||
|
)
|
||||||
|
with urllib.request.urlopen(req, timeout=20) as resp:
|
||||||
|
data = json.loads(resp.read().decode("utf-8"))
|
||||||
|
cfg = data.get("config") if isinstance(data.get("config"), dict) else {}
|
||||||
|
mods = cfg.get("modules") if isinstance(cfg.get("modules"), dict) else {}
|
||||||
|
return {
|
||||||
|
"version": cfg.get("version"),
|
||||||
|
"social": mods.get("social"),
|
||||||
|
"source": data.get("source"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def build_admin() -> None:
|
||||||
|
print("vite build…", flush=True)
|
||||||
|
r = subprocess.run(
|
||||||
|
["pnpm", "exec", "vite", "build"],
|
||||||
|
cwd=ADMIN,
|
||||||
|
shell=True,
|
||||||
|
capture_output=True,
|
||||||
|
encoding="utf-8",
|
||||||
|
errors="replace",
|
||||||
|
)
|
||||||
|
if r.returncode != 0:
|
||||||
|
print(r.stdout)
|
||||||
|
print(r.stderr)
|
||||||
|
raise SystemExit(r.returncode)
|
||||||
|
|
||||||
|
|
||||||
|
def pack() -> bytes:
|
||||||
|
buf = io.BytesIO()
|
||||||
|
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
|
||||||
|
for rel, dest in API_FILES:
|
||||||
|
src = REPO / rel
|
||||||
|
text = rewrite(src.read_text(encoding="utf-8"))
|
||||||
|
if "ebook_svc" in text and dest != "main.py":
|
||||||
|
# main may mention ebook only in comments; services must be clean
|
||||||
|
if "ebook_svc." in text:
|
||||||
|
raise SystemExit(f"rewrite failed: {rel}")
|
||||||
|
data = text.encode("utf-8")
|
||||||
|
info = tarfile.TarInfo(name="api/" + dest)
|
||||||
|
info.size = len(data)
|
||||||
|
tar.addfile(info, io.BytesIO(data))
|
||||||
|
dist = ADMIN / "dist"
|
||||||
|
for p in dist.rglob("*"):
|
||||||
|
if p.is_file():
|
||||||
|
tar.add(p, arcname="admin-dist/" + p.relative_to(dist).as_posix())
|
||||||
|
buf.seek(0)
|
||||||
|
blob = buf.read()
|
||||||
|
print("pack", len(blob), flush=True)
|
||||||
|
return blob
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
before = snapshot()
|
||||||
|
print("BEFORE", before, flush=True)
|
||||||
|
build_admin()
|
||||||
|
blob = pack()
|
||||||
|
|
||||||
|
c = paramiko.SSHClient()
|
||||||
|
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||||
|
c.connect(HOST, username=USER, password=PASS, timeout=60, allow_agent=False, look_for_keys=False)
|
||||||
|
sftp = c.open_sftp()
|
||||||
|
with sftp.file("/tmp/admin-crud.tar.gz", "wb") as rf:
|
||||||
|
rf.write(blob)
|
||||||
|
sftp.close()
|
||||||
|
|
||||||
|
cmd = r"""
|
||||||
|
set -e
|
||||||
|
cd /tmp
|
||||||
|
rm -rf admin-crud && mkdir admin-crud
|
||||||
|
tar -xzf admin-crud.tar.gz -C admin-crud
|
||||||
|
|
||||||
|
API_ROOT=$(systemctl show nomadmini-api -p WorkingDirectory --value 2>/dev/null || true)
|
||||||
|
if [ -z "$API_ROOT" ] || [ "$API_ROOT" = "/" ]; then API_ROOT=/opt/nomadmini/backend; fi
|
||||||
|
B=$API_ROOT/app
|
||||||
|
if [ ! -d "$B" ]; then B=$API_ROOT/backend/app; fi
|
||||||
|
echo B=$B
|
||||||
|
TS=$(date -u +%Y%m%dT%H%M%SZ)
|
||||||
|
|
||||||
|
sudo mkdir -p "$B/services" "$B/routers" "$B/schemas"
|
||||||
|
for f in \
|
||||||
|
services/store.py \
|
||||||
|
services/social_ugc.py \
|
||||||
|
services/memo_store.py \
|
||||||
|
services/shop_store.py \
|
||||||
|
schemas/admin.py \
|
||||||
|
routers/admin.py \
|
||||||
|
routers/social_ugc_admin.py \
|
||||||
|
routers/community_admin.py \
|
||||||
|
routers/memo_admin.py \
|
||||||
|
routers/shop_admin.py
|
||||||
|
do
|
||||||
|
if [ -f "$B/$f" ]; then sudo cp "$B/$f" "$B/$f.bak-$TS"; fi
|
||||||
|
sudo cp "admin-crud/api/$f" "$B/$f"
|
||||||
|
done
|
||||||
|
|
||||||
|
# Patch main.py to include new routers (idempotent)
|
||||||
|
python3 - <<'PY'
|
||||||
|
from pathlib import Path
|
||||||
|
p = Path("/opt/nomadmini/backend/app/main.py")
|
||||||
|
text = p.read_text(encoding="utf-8")
|
||||||
|
changed = False
|
||||||
|
if "social_ugc_admin" not in text:
|
||||||
|
needle = "from app.routers import social_ops_admin"
|
||||||
|
if needle in text:
|
||||||
|
text = text.replace(
|
||||||
|
needle,
|
||||||
|
needle
|
||||||
|
+ "\nfrom app.routers import social_ugc_admin # noqa: E402\nfrom app.routers import community_admin # noqa: E402",
|
||||||
|
1,
|
||||||
|
)
|
||||||
|
changed = True
|
||||||
|
if "include_router(social_ugc_admin.router)" not in text:
|
||||||
|
needle2 = "include_router(social_ops_admin.router)"
|
||||||
|
if needle2 in text:
|
||||||
|
text = text.replace(
|
||||||
|
needle2,
|
||||||
|
needle2
|
||||||
|
+ "\napp.include_router(social_ugc_admin.router)\napp.include_router(community_admin.router)",
|
||||||
|
1,
|
||||||
|
)
|
||||||
|
changed = True
|
||||||
|
if changed:
|
||||||
|
p.write_text(text, encoding="utf-8")
|
||||||
|
print("patched_main")
|
||||||
|
else:
|
||||||
|
print("main_ok")
|
||||||
|
PY
|
||||||
|
|
||||||
|
# social db perms + env for nomadmini-api
|
||||||
|
sudo mkdir -p /var/www/nomadro-data/social /var/www/nomadro-data/community
|
||||||
|
if [ -f /var/www/nomadro-data/social/social.db ]; then
|
||||||
|
sudo chown www:www /var/www/nomadro-data/social/social.db || true
|
||||||
|
sudo chmod 664 /var/www/nomadro-data/social/social.db || true
|
||||||
|
sudo chown www:www /var/www/nomadro-data/social || true
|
||||||
|
fi
|
||||||
|
sudo mkdir -p /etc/systemd/system/nomadmini-api.service.d
|
||||||
|
sudo tee /etc/systemd/system/nomadmini-api.service.d/social-db.conf >/dev/null <<'EOF'
|
||||||
|
[Service]
|
||||||
|
Environment=SOCIAL_DB_PATH=/var/www/nomadro-data/social/social.db
|
||||||
|
Environment=COMMUNITY_STORE_PATH=/var/www/nomadro-data/community/community_store.json
|
||||||
|
EOF
|
||||||
|
sudo systemctl daemon-reload
|
||||||
|
|
||||||
|
sudo rsync -a --delete /tmp/admin-crud/admin-dist/ /www/wwwroot/admin.nomadro.cn/
|
||||||
|
sudo chown -R www:www /www/wwwroot/admin.nomadro.cn
|
||||||
|
echo admin_synced
|
||||||
|
|
||||||
|
sudo systemctl restart nomadmini-api
|
||||||
|
sleep 3
|
||||||
|
systemctl is-active nomadmini-api
|
||||||
|
|
||||||
|
TOK=$(curl -sk -X POST https://api.nomadro.cn/api/admin/login -H 'Content-Type: application/json' -d '{"username":"admin","password":"Xiao4669805"}' | python3 -c "import sys,json; print(json.load(sys.stdin).get('token',''))")
|
||||||
|
AUTH="Authorization: Bearer $TOK"
|
||||||
|
|
||||||
|
echo -n 'stats '
|
||||||
|
curl -sk -o /tmp/st.json -w "%{http_code}\n" -H "$AUTH" https://api.nomadro.cn/api/admin/stats
|
||||||
|
python3 - <<'PY'
|
||||||
|
import json
|
||||||
|
d=json.load(open('/tmp/st.json',encoding='utf-8'))
|
||||||
|
assert 'series' in d, d
|
||||||
|
print('series_ok', len(d['series'].get('revenue',[])), 'top', len(d.get('topEvents') or []))
|
||||||
|
PY
|
||||||
|
|
||||||
|
echo -n 'social_ugc '
|
||||||
|
curl -sk -o /tmp/su.json -w "%{http_code}\n" -H "$AUTH" https://api.nomadro.cn/api/admin/social/ugc/overview
|
||||||
|
python3 - <<'PY'
|
||||||
|
import json
|
||||||
|
d=json.load(open('/tmp/su.json',encoding='utf-8'))
|
||||||
|
print('ugc', d.get('exists'), d.get('writable'), d.get('counts'))
|
||||||
|
PY
|
||||||
|
|
||||||
|
echo -n 'community '
|
||||||
|
curl -sk -o /tmp/co.json -w "%{http_code}\n" -H "$AUTH" https://api.nomadro.cn/api/admin/community/overview
|
||||||
|
|
||||||
|
for u in /wechat /wechat/social/data /wechat/community /wechat/books; do
|
||||||
|
curl -sk -o /dev/null -w "admin$u %{http_code}\n" "https://admin.nomadro.cn$u"
|
||||||
|
done
|
||||||
|
|
||||||
|
curl -sk https://api.nomadro.cn/api/config -o /tmp/cfg-after.json
|
||||||
|
python3 - <<'PY'
|
||||||
|
import json
|
||||||
|
d=json.load(open('/tmp/cfg-after.json',encoding='utf-8'))
|
||||||
|
social=d.get('config',{}).get('modules',{}).get('social')
|
||||||
|
print('live_social', social)
|
||||||
|
assert isinstance(social, dict) and social.get('enabled') is True
|
||||||
|
print('config_ok')
|
||||||
|
PY
|
||||||
|
|
||||||
|
rm -rf /tmp/admin-crud /tmp/admin-crud.tar.gz /tmp/st.json /tmp/su.json /tmp/co.json /tmp/cfg-after.json
|
||||||
|
"""
|
||||||
|
_, stdout, _ = c.exec_command(cmd, timeout=300, get_pty=True)
|
||||||
|
while not stdout.channel.exit_status_ready():
|
||||||
|
if stdout.channel.recv_ready():
|
||||||
|
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
|
||||||
|
time.sleep(0.05)
|
||||||
|
while stdout.channel.recv_ready():
|
||||||
|
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
|
||||||
|
code = stdout.channel.recv_exit_status()
|
||||||
|
c.close()
|
||||||
|
|
||||||
|
after = snapshot()
|
||||||
|
print("AFTER", after, flush=True)
|
||||||
|
if after.get("version") != before.get("version") or after.get("social") != before.get("social"):
|
||||||
|
print("FAIL config drifted", flush=True)
|
||||||
|
return 3
|
||||||
|
print(f"[exit {code}] admin CRUD deployed; version {after.get('version')}", flush=True)
|
||||||
|
return code
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
229
apps/admin/deploy/_push_api_backend.py
Normal file
229
apps/admin/deploy/_push_api_backend.py
Normal file
@ -0,0 +1,229 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""Deploy pending ebook API backend only (no admin SPA).
|
||||||
|
|
||||||
|
- Rewrite ebook_svc.* → app.*
|
||||||
|
- Hot-copy into /opt/nomadmini/backend/app
|
||||||
|
- Restart nomadmini-api only
|
||||||
|
- Snapshot /api/config version before/after (must not drift)
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import tarfile
|
||||||
|
import time
|
||||||
|
import urllib.request
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import paramiko
|
||||||
|
|
||||||
|
REPO = Path(__file__).resolve().parents[3]
|
||||||
|
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
|
||||||
|
|
||||||
|
API_FILES = [
|
||||||
|
("apps/api/services/ebook_svc/services/store.py", "services/store.py"),
|
||||||
|
("apps/api/services/ebook_svc/services/memo_store.py", "services/memo_store.py"),
|
||||||
|
("apps/api/services/ebook_svc/services/shop_store.py", "services/shop_store.py"),
|
||||||
|
("apps/api/services/ebook_svc/services/weapp_switches.py", "services/weapp_switches.py"),
|
||||||
|
("apps/api/services/ebook_svc/services/social_ugc.py", "services/social_ugc.py"),
|
||||||
|
("apps/api/services/ebook_svc/services/social_ops.py", "services/social_ops.py"),
|
||||||
|
(
|
||||||
|
"apps/api/services/ebook_svc/services/public_config_snapshot.py",
|
||||||
|
"services/public_config_snapshot.py",
|
||||||
|
),
|
||||||
|
("apps/api/services/ebook_svc/schemas/admin.py", "schemas/admin.py"),
|
||||||
|
("apps/api/services/ebook_svc/routers/admin.py", "routers/admin.py"),
|
||||||
|
("apps/api/services/ebook_svc/routers/memo_admin.py", "routers/memo_admin.py"),
|
||||||
|
("apps/api/services/ebook_svc/routers/shop_admin.py", "routers/shop_admin.py"),
|
||||||
|
("apps/api/services/ebook_svc/routers/social_ugc_admin.py", "routers/social_ugc_admin.py"),
|
||||||
|
("apps/api/services/ebook_svc/routers/community_admin.py", "routers/community_admin.py"),
|
||||||
|
("apps/api/services/ebook_svc/routers/social_ops_admin.py", "routers/social_ops_admin.py"),
|
||||||
|
("apps/api/services/ebook_svc/routers/public_config.py", "routers/public_config.py"),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def rewrite(text: str) -> str:
|
||||||
|
return text.replace("ebook_svc.", "app.")
|
||||||
|
|
||||||
|
|
||||||
|
def snapshot() -> dict:
|
||||||
|
req = urllib.request.Request(
|
||||||
|
"https://api.nomadro.cn/api/config",
|
||||||
|
headers={"User-Agent": "nomadro-api-backend-deploy"},
|
||||||
|
)
|
||||||
|
with urllib.request.urlopen(req, timeout=20) as resp:
|
||||||
|
data = json.loads(resp.read().decode("utf-8"))
|
||||||
|
cfg = data.get("config") if isinstance(data.get("config"), dict) else {}
|
||||||
|
mods = cfg.get("modules") if isinstance(cfg.get("modules"), dict) else {}
|
||||||
|
return {
|
||||||
|
"version": cfg.get("version"),
|
||||||
|
"social": mods.get("social"),
|
||||||
|
"book": mods.get("book"),
|
||||||
|
"source": data.get("source"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def pack() -> bytes:
|
||||||
|
buf = io.BytesIO()
|
||||||
|
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
|
||||||
|
for rel, dest in API_FILES:
|
||||||
|
src = REPO / rel
|
||||||
|
if not src.is_file():
|
||||||
|
raise SystemExit(f"missing {rel}")
|
||||||
|
text = rewrite(src.read_text(encoding="utf-8"))
|
||||||
|
if "ebook_svc." in text:
|
||||||
|
raise SystemExit(f"rewrite failed: {rel}")
|
||||||
|
data = text.encode("utf-8")
|
||||||
|
info = tarfile.TarInfo(name="api/" + dest)
|
||||||
|
info.size = len(data)
|
||||||
|
tar.addfile(info, io.BytesIO(data))
|
||||||
|
buf.seek(0)
|
||||||
|
blob = buf.read()
|
||||||
|
print("pack", len(blob), "files", len(API_FILES), flush=True)
|
||||||
|
return blob
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
before = snapshot()
|
||||||
|
print("BEFORE", before, flush=True)
|
||||||
|
blob = pack()
|
||||||
|
|
||||||
|
c = paramiko.SSHClient()
|
||||||
|
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||||
|
c.connect(HOST, username=USER, password=PASS, timeout=60, allow_agent=False, look_for_keys=False)
|
||||||
|
sftp = c.open_sftp()
|
||||||
|
with sftp.file("/tmp/api-backend.tar.gz", "wb") as rf:
|
||||||
|
rf.write(blob)
|
||||||
|
sftp.close()
|
||||||
|
|
||||||
|
cmd = r"""
|
||||||
|
set -e
|
||||||
|
cd /tmp
|
||||||
|
rm -rf api-backend && mkdir api-backend
|
||||||
|
tar -xzf api-backend.tar.gz -C api-backend
|
||||||
|
|
||||||
|
API_ROOT=$(systemctl show nomadmini-api -p WorkingDirectory --value 2>/dev/null || true)
|
||||||
|
if [ -z "$API_ROOT" ] || [ "$API_ROOT" = "/" ]; then API_ROOT=/opt/nomadmini/backend; fi
|
||||||
|
B=$API_ROOT/app
|
||||||
|
if [ ! -d "$B" ]; then B=$API_ROOT/backend/app; fi
|
||||||
|
echo B=$B
|
||||||
|
TS=$(date -u +%Y%m%dT%H%M%SZ)
|
||||||
|
|
||||||
|
sudo mkdir -p "$B/services" "$B/routers" "$B/schemas"
|
||||||
|
for f in \
|
||||||
|
services/store.py \
|
||||||
|
services/memo_store.py \
|
||||||
|
services/shop_store.py \
|
||||||
|
services/weapp_switches.py \
|
||||||
|
services/social_ugc.py \
|
||||||
|
services/social_ops.py \
|
||||||
|
services/public_config_snapshot.py \
|
||||||
|
schemas/admin.py \
|
||||||
|
routers/admin.py \
|
||||||
|
routers/memo_admin.py \
|
||||||
|
routers/shop_admin.py \
|
||||||
|
routers/social_ugc_admin.py \
|
||||||
|
routers/community_admin.py \
|
||||||
|
routers/social_ops_admin.py \
|
||||||
|
routers/public_config.py
|
||||||
|
do
|
||||||
|
if [ -f "$B/$f" ]; then sudo cp "$B/$f" "$B/$f.bak-$TS"; fi
|
||||||
|
sudo cp "api-backend/api/$f" "$B/$f"
|
||||||
|
echo copied $f
|
||||||
|
done
|
||||||
|
|
||||||
|
# Ensure main.py registers new admin routers (idempotent)
|
||||||
|
python3 - <<'PY'
|
||||||
|
from pathlib import Path
|
||||||
|
candidates = [
|
||||||
|
Path("/opt/nomadmini/backend/app/main.py"),
|
||||||
|
]
|
||||||
|
for p in candidates:
|
||||||
|
if not p.is_file():
|
||||||
|
continue
|
||||||
|
text = p.read_text(encoding="utf-8")
|
||||||
|
changed = False
|
||||||
|
imports = [
|
||||||
|
("social_ops_admin", "from app.routers import social_ops_admin # noqa: E402"),
|
||||||
|
("social_ugc_admin", "from app.routers import social_ugc_admin # noqa: E402"),
|
||||||
|
("community_admin", "from app.routers import community_admin # noqa: E402"),
|
||||||
|
]
|
||||||
|
for key, line in imports:
|
||||||
|
if key not in text:
|
||||||
|
# append near other router imports
|
||||||
|
anchor = "from app.routers import"
|
||||||
|
idx = text.rfind(anchor)
|
||||||
|
if idx >= 0:
|
||||||
|
end = text.find("\n", idx)
|
||||||
|
text = text[: end + 1] + line + "\n" + text[end + 1 :]
|
||||||
|
changed = True
|
||||||
|
else:
|
||||||
|
text = line + "\n" + text
|
||||||
|
changed = True
|
||||||
|
includes = [
|
||||||
|
("social_ops_admin.router", "app.include_router(social_ops_admin.router)"),
|
||||||
|
("social_ugc_admin.router", "app.include_router(social_ugc_admin.router)"),
|
||||||
|
("community_admin.router", "app.include_router(community_admin.router)"),
|
||||||
|
]
|
||||||
|
for key, line in includes:
|
||||||
|
if key not in text:
|
||||||
|
# after last include_router
|
||||||
|
needle = "app.include_router("
|
||||||
|
idx = text.rfind(needle)
|
||||||
|
if idx >= 0:
|
||||||
|
end = text.find("\n", idx)
|
||||||
|
text = text[: end + 1] + line + "\n" + text[end + 1 :]
|
||||||
|
changed = True
|
||||||
|
if changed:
|
||||||
|
p.write_text(text, encoding="utf-8")
|
||||||
|
print("patched_main", p)
|
||||||
|
else:
|
||||||
|
print("main_ok", p)
|
||||||
|
PY
|
||||||
|
|
||||||
|
cd "$API_ROOT"
|
||||||
|
if [ -x .venv/bin/python ]; then
|
||||||
|
.venv/bin/python - <<'PY'
|
||||||
|
from app.services.weapp_switches import read_weapp_switches
|
||||||
|
from app.services import public_config_snapshot
|
||||||
|
print("import_ok", read_weapp_switches().get("bookAudit"))
|
||||||
|
print("snapshot_cls", public_config_snapshot.PublicConfigSnapshot)
|
||||||
|
PY
|
||||||
|
fi
|
||||||
|
|
||||||
|
sudo systemctl restart nomadmini-api
|
||||||
|
sleep 4
|
||||||
|
systemctl is-active nomadmini-api
|
||||||
|
curl -sk -o /dev/null -w "health %{http_code}\n" https://api.nomadro.cn/health
|
||||||
|
curl -sk -o /dev/null -w "config %{http_code}\n" https://api.nomadro.cn/api/config
|
||||||
|
curl -sk -o /dev/null -w "meta %{http_code}\n" https://api.nomadro.cn/api/config/meta
|
||||||
|
|
||||||
|
TOK=$(curl -sk -X POST https://api.nomadro.cn/api/admin/login -H 'Content-Type: application/json' -d '{"username":"admin","password":"Xiao4669805"}' | python3 -c "import sys,json; print(json.load(sys.stdin).get('token',''))")
|
||||||
|
echo token_len=${#TOK}
|
||||||
|
AUTH="Authorization: Bearer $TOK"
|
||||||
|
curl -sk -o /dev/null -w "switches %{http_code}\n" -H "$AUTH" https://api.nomadro.cn/api/admin/weapp/switches
|
||||||
|
curl -sk -o /dev/null -w "stats %{http_code}\n" -H "$AUTH" https://api.nomadro.cn/api/admin/stats
|
||||||
|
|
||||||
|
rm -rf /tmp/api-backend /tmp/api-backend.tar.gz
|
||||||
|
"""
|
||||||
|
_, stdout, _ = c.exec_command(cmd, timeout=300, get_pty=True)
|
||||||
|
while not stdout.channel.exit_status_ready():
|
||||||
|
if stdout.channel.recv_ready():
|
||||||
|
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
|
||||||
|
time.sleep(0.05)
|
||||||
|
while stdout.channel.recv_ready():
|
||||||
|
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
|
||||||
|
code = stdout.channel.recv_exit_status()
|
||||||
|
c.close()
|
||||||
|
|
||||||
|
after = snapshot()
|
||||||
|
print("AFTER", after, flush=True)
|
||||||
|
if after.get("version") != before.get("version") or after.get("social") != before.get("social"):
|
||||||
|
print("FAIL config drifted", flush=True)
|
||||||
|
return 3
|
||||||
|
print(f"[exit {code}] api backend deployed; version {after.get('version')}", flush=True)
|
||||||
|
return code
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
48
apps/admin/deploy/_push_config_post.py
Normal file
48
apps/admin/deploy/_push_config_post.py
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import paramiko
|
||||||
|
|
||||||
|
REPO = Path(__file__).resolve().parents[3]
|
||||||
|
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
|
||||||
|
SRC = REPO / "apps/api/services/ebook_svc/routers/public_config.py"
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
text = SRC.read_text(encoding="utf-8").replace("ebook_svc.", "app.")
|
||||||
|
if "ebook_svc." in text:
|
||||||
|
raise SystemExit("rewrite failed")
|
||||||
|
c = paramiko.SSHClient()
|
||||||
|
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||||
|
c.connect(HOST, username=USER, password=PASS, timeout=60, allow_agent=False, look_for_keys=False)
|
||||||
|
sftp = c.open_sftp()
|
||||||
|
with sftp.file("/tmp/public_config.py", "w") as rf:
|
||||||
|
rf.write(text)
|
||||||
|
sftp.close()
|
||||||
|
cmd = r"""
|
||||||
|
set -e
|
||||||
|
sudo cp /tmp/public_config.py /opt/nomadmini/backend/app/routers/public_config.py
|
||||||
|
sudo systemctl restart nomadmini-api
|
||||||
|
sleep 3
|
||||||
|
systemctl is-active nomadmini-api
|
||||||
|
curl -sk -X POST https://api.nomadro.cn/api/config/pull -H 'Content-Type: application/json' -d '{}' | python3 -c "import sys,json;d=json.load(sys.stdin);c=d['config'];print('POST_PULL',c.get('version'),c.get('modules',{}).get('nav'))"
|
||||||
|
curl -sk -X POST https://api.nomadro.cn/api/config -H 'Content-Type: application/json' -d '{}' | python3 -c "import sys,json;d=json.load(sys.stdin);print('POST_CFG',d['config'].get('version'))"
|
||||||
|
rm -f /tmp/public_config.py
|
||||||
|
"""
|
||||||
|
_, stdout, _ = c.exec_command(cmd, timeout=90, get_pty=True)
|
||||||
|
while not stdout.channel.exit_status_ready():
|
||||||
|
if stdout.channel.recv_ready():
|
||||||
|
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
|
||||||
|
time.sleep(0.05)
|
||||||
|
while stdout.channel.recv_ready():
|
||||||
|
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
|
||||||
|
code = stdout.channel.recv_exit_status()
|
||||||
|
c.close()
|
||||||
|
return code
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
164
apps/admin/deploy/_push_config_realtime.py
Normal file
164
apps/admin/deploy/_push_config_realtime.py
Normal file
@ -0,0 +1,164 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""Deploy config SSE/WebSocket realtime to api.nomadro.cn (nomadmini-api)."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import tarfile
|
||||||
|
import time
|
||||||
|
import urllib.request
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import paramiko
|
||||||
|
|
||||||
|
REPO = Path(__file__).resolve().parents[3]
|
||||||
|
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
|
||||||
|
|
||||||
|
FILES = [
|
||||||
|
(
|
||||||
|
"apps/api/services/ebook_svc/services/config_live.py",
|
||||||
|
"services/config_live.py",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"apps/api/services/ebook_svc/routers/public_config.py",
|
||||||
|
"routers/public_config.py",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"apps/api/services/ebook_svc/services/weapp_switches.py",
|
||||||
|
"services/weapp_switches.py",
|
||||||
|
),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def rewrite(text: str) -> str:
|
||||||
|
return text.replace("ebook_svc.", "app.")
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
buf = io.BytesIO()
|
||||||
|
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
|
||||||
|
for rel, dest in FILES:
|
||||||
|
src = REPO / rel
|
||||||
|
text = rewrite(src.read_text(encoding="utf-8"))
|
||||||
|
if "ebook_svc." in text:
|
||||||
|
raise SystemExit(f"rewrite failed {rel}")
|
||||||
|
data = text.encode("utf-8")
|
||||||
|
info = tarfile.TarInfo(name=dest)
|
||||||
|
info.size = len(data)
|
||||||
|
tar.addfile(info, io.BytesIO(data))
|
||||||
|
blob = buf.getvalue()
|
||||||
|
print("pack", len(blob), flush=True)
|
||||||
|
|
||||||
|
c = paramiko.SSHClient()
|
||||||
|
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||||
|
c.connect(HOST, username=USER, password=PASS, timeout=60, allow_agent=False, look_for_keys=False)
|
||||||
|
sftp = c.open_sftp()
|
||||||
|
with sftp.file("/tmp/config-rt.tar.gz", "wb") as rf:
|
||||||
|
rf.write(blob)
|
||||||
|
sftp.close()
|
||||||
|
|
||||||
|
cmd = r"""
|
||||||
|
set -e
|
||||||
|
cd /tmp
|
||||||
|
rm -rf config-rt && mkdir config-rt
|
||||||
|
tar -xzf config-rt.tar.gz -C config-rt
|
||||||
|
B=/opt/nomadmini/backend/app
|
||||||
|
TS=$(date -u +%Y%m%dT%H%M%SZ)
|
||||||
|
sudo mkdir -p "$B/services" "$B/routers"
|
||||||
|
for f in services/config_live.py routers/public_config.py services/weapp_switches.py; do
|
||||||
|
if [ -f "$B/$f" ]; then sudo cp "$B/$f" "$B/$f.bak-$TS"; fi
|
||||||
|
sudo cp "config-rt/$f" "$B/$f"
|
||||||
|
echo copied $f
|
||||||
|
done
|
||||||
|
|
||||||
|
# nginx websocket:写到 /tmp 再 sudo 覆盖
|
||||||
|
sudo python3 - <<'PY'
|
||||||
|
from pathlib import Path
|
||||||
|
import shutil
|
||||||
|
src = Path("/www/server/panel/vhost/nginx/api.nomadro.cn.conf")
|
||||||
|
if not src.is_file():
|
||||||
|
print("nginx_ws_skip_no_conf")
|
||||||
|
raise SystemExit(0)
|
||||||
|
text = src.read_text(encoding="utf-8")
|
||||||
|
if "location /api/config/ws" in text:
|
||||||
|
print("nginx_ws_ok")
|
||||||
|
raise SystemExit(0)
|
||||||
|
upstream = "http://127.0.0.1:8000"
|
||||||
|
for line in text.splitlines():
|
||||||
|
s = line.strip()
|
||||||
|
if s.startswith("proxy_pass ") and "127.0.0.1" in s:
|
||||||
|
upstream = s.split("proxy_pass", 1)[1].strip().rstrip(";")
|
||||||
|
break
|
||||||
|
snippet = (
|
||||||
|
"\n location /api/config/ws {\n"
|
||||||
|
f" proxy_pass {upstream};\n"
|
||||||
|
" proxy_http_version 1.1;\n"
|
||||||
|
" proxy_set_header Upgrade $http_upgrade;\n"
|
||||||
|
' proxy_set_header Connection "upgrade";\n'
|
||||||
|
" proxy_set_header Host $host;\n"
|
||||||
|
" proxy_set_header X-Real-IP $remote_addr;\n"
|
||||||
|
" proxy_read_timeout 3600s;\n"
|
||||||
|
" proxy_send_timeout 3600s;\n"
|
||||||
|
" }\n"
|
||||||
|
" location /api/ebook/config/ws {\n"
|
||||||
|
f" proxy_pass {upstream};\n"
|
||||||
|
" proxy_http_version 1.1;\n"
|
||||||
|
" proxy_set_header Upgrade $http_upgrade;\n"
|
||||||
|
' proxy_set_header Connection "upgrade";\n'
|
||||||
|
" proxy_set_header Host $host;\n"
|
||||||
|
" proxy_set_header X-Real-IP $remote_addr;\n"
|
||||||
|
" proxy_read_timeout 3600s;\n"
|
||||||
|
" proxy_send_timeout 3600s;\n"
|
||||||
|
" }\n"
|
||||||
|
)
|
||||||
|
idx = text.find("location /")
|
||||||
|
if idx < 0:
|
||||||
|
idx = text.rfind("}")
|
||||||
|
if idx <= 0:
|
||||||
|
print("nginx_ws_skip")
|
||||||
|
raise SystemExit(0)
|
||||||
|
out = text[:idx] + snippet + "\n" + text[idx:]
|
||||||
|
bak = src.with_suffix(src.suffix + ".bak-config-ws")
|
||||||
|
shutil.copy2(src, bak)
|
||||||
|
src.write_text(out, encoding="utf-8")
|
||||||
|
print("nginx_ws_patched", upstream)
|
||||||
|
PY
|
||||||
|
sudo nginx -t && sudo nginx -s reload || true
|
||||||
|
|
||||||
|
cd /opt/nomadmini/backend
|
||||||
|
.venv/bin/python - <<'PY'
|
||||||
|
from app.services import config_live
|
||||||
|
from app.routers import public_config
|
||||||
|
print("import_ok", config_live.read_config_meta())
|
||||||
|
PY
|
||||||
|
|
||||||
|
sudo systemctl restart nomadmini-api
|
||||||
|
sleep 4
|
||||||
|
systemctl is-active nomadmini-api
|
||||||
|
curl -sk -o /dev/null -w "health %{http_code}\n" https://api.nomadro.cn/health
|
||||||
|
curl -sk -o /dev/null -w "config %{http_code}\n" https://api.nomadro.cn/api/config
|
||||||
|
curl -sk -o /dev/null -w "meta %{http_code}\n" https://api.nomadro.cn/api/config/meta
|
||||||
|
# SSE hello (2s)
|
||||||
|
timeout 3 curl -sk -N -H 'Accept: text/event-stream' https://api.nomadro.cn/api/config/stream | head -c 400 || true
|
||||||
|
echo
|
||||||
|
rm -rf /tmp/config-rt /tmp/config-rt.tar.gz
|
||||||
|
"""
|
||||||
|
_, stdout, _ = c.exec_command(cmd, timeout=180, get_pty=True)
|
||||||
|
while not stdout.channel.exit_status_ready():
|
||||||
|
if stdout.channel.recv_ready():
|
||||||
|
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
|
||||||
|
time.sleep(0.05)
|
||||||
|
while stdout.channel.recv_ready():
|
||||||
|
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
|
||||||
|
code = stdout.channel.recv_exit_status()
|
||||||
|
c.close()
|
||||||
|
|
||||||
|
# local meta check
|
||||||
|
meta = json.loads(urllib.request.urlopen("https://api.nomadro.cn/api/config/meta", timeout=15).read())
|
||||||
|
print("META", meta, flush=True)
|
||||||
|
print(f"[exit {code}] config realtime deployed", flush=True)
|
||||||
|
return code
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
114
apps/admin/deploy/_push_weapp_switches.py
Normal file
114
apps/admin/deploy/_push_weapp_switches.py
Normal file
@ -0,0 +1,114 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""Deploy weapp switches API + admin SPA."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import subprocess
|
||||||
|
import tarfile
|
||||||
|
import time
|
||||||
|
from io import BytesIO
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import paramiko
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
REPO = ROOT.parents[1]
|
||||||
|
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
|
||||||
|
|
||||||
|
API_FILES = [
|
||||||
|
(REPO / "apps/api/services/ebook_svc/services/weapp_switches.py", "services/weapp_switches.py"),
|
||||||
|
(REPO / "apps/api/services/ebook_svc/routers/weapp_switches_admin.py", "routers/weapp_switches_admin.py"),
|
||||||
|
(REPO / "apps/api/services/ebook_svc/services/store.py", "services/store.py"),
|
||||||
|
(REPO / "apps/api/services/ebook_svc/main.py", "main.py"),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def to_app(src: Path) -> bytes:
|
||||||
|
return src.read_text(encoding="utf-8").replace("ebook_svc.", "app.").encode("utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
print("vite build…", flush=True)
|
||||||
|
r = subprocess.run(
|
||||||
|
["pnpm", "exec", "vite", "build"],
|
||||||
|
cwd=ROOT,
|
||||||
|
shell=True,
|
||||||
|
capture_output=True,
|
||||||
|
encoding="utf-8",
|
||||||
|
errors="replace",
|
||||||
|
)
|
||||||
|
if r.returncode != 0:
|
||||||
|
print(r.stdout)
|
||||||
|
print(r.stderr)
|
||||||
|
return r.returncode
|
||||||
|
|
||||||
|
dist = ROOT / "dist"
|
||||||
|
buf = BytesIO()
|
||||||
|
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
|
||||||
|
for p in dist.rglob("*"):
|
||||||
|
if p.is_file():
|
||||||
|
tar.add(p, arcname="admin-dist/" + p.relative_to(dist).as_posix())
|
||||||
|
for src, rel in API_FILES:
|
||||||
|
data = to_app(src)
|
||||||
|
info = tarfile.TarInfo(name="api/" + rel.replace("/", "__"))
|
||||||
|
info.size = len(data)
|
||||||
|
tar.addfile(info, BytesIO(data))
|
||||||
|
buf.seek(0)
|
||||||
|
print("pack", buf.getbuffer().nbytes, flush=True)
|
||||||
|
|
||||||
|
c = paramiko.SSHClient()
|
||||||
|
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||||
|
c.connect(HOST, username=USER, password=PASS, timeout=60, allow_agent=False, look_for_keys=False)
|
||||||
|
sftp = c.open_sftp()
|
||||||
|
with sftp.file("/tmp/weapp-switches.tar.gz", "wb") as rf:
|
||||||
|
rf.write(buf.read())
|
||||||
|
sftp.close()
|
||||||
|
|
||||||
|
cmd = r"""
|
||||||
|
set -e
|
||||||
|
cd /tmp
|
||||||
|
rm -rf sw-unpack && mkdir sw-unpack
|
||||||
|
tar -xzf weapp-switches.tar.gz -C sw-unpack
|
||||||
|
sudo rsync -a --delete sw-unpack/admin-dist/ /www/wwwroot/admin.nomadro.cn/
|
||||||
|
sudo chown -R www:www /www/wwwroot/admin.nomadro.cn
|
||||||
|
B=/opt/nomadmini/backend/app
|
||||||
|
sudo mkdir -p "$B/services" "$B/routers"
|
||||||
|
sudo cp sw-unpack/api/services__weapp_switches.py "$B/services/weapp_switches.py"
|
||||||
|
sudo cp sw-unpack/api/routers__weapp_switches_admin.py "$B/routers/weapp_switches_admin.py"
|
||||||
|
sudo cp sw-unpack/api/services__store.py "$B/services/store.py"
|
||||||
|
sudo cp sw-unpack/api/main.py "$B/../main.py" 2>/dev/null || sudo cp sw-unpack/api/main.py /opt/nomadmini/backend/main.py
|
||||||
|
# main may live as app package entry
|
||||||
|
if [ -f /opt/nomadmini/backend/app/main.py ]; then
|
||||||
|
sudo cp sw-unpack/api/main.py /opt/nomadmini/backend/app/main.py
|
||||||
|
elif [ -f /opt/nomadmini/backend/main.py ]; then
|
||||||
|
sudo cp sw-unpack/api/main.py /opt/nomadmini/backend/main.py
|
||||||
|
fi
|
||||||
|
cd /opt/nomadmini/backend
|
||||||
|
.venv/bin/python - <<'PY'
|
||||||
|
from app.services.weapp_switches import read_weapp_switches
|
||||||
|
from app.routers import weapp_switches_admin
|
||||||
|
from app.services.store import store
|
||||||
|
assert hasattr(store, "ensure_book")
|
||||||
|
print("ok", "switches", list(read_weapp_switches().get("modules", {}).keys())[:3])
|
||||||
|
PY
|
||||||
|
sudo systemctl restart nomadmini-api
|
||||||
|
sleep 3
|
||||||
|
systemctl is-active nomadmini-api
|
||||||
|
curl -sk -o /dev/null -w "admin %{http_code}\n" https://admin.nomadro.cn/wechat/switches
|
||||||
|
curl -sk -o /dev/null -w "api %{http_code}\n" https://api.nomadro.cn/health
|
||||||
|
rm -rf sw-unpack weapp-switches.tar.gz
|
||||||
|
"""
|
||||||
|
_, stdout, _ = c.exec_command(cmd, timeout=180, get_pty=True)
|
||||||
|
while not stdout.channel.exit_status_ready():
|
||||||
|
if stdout.channel.recv_ready():
|
||||||
|
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
|
||||||
|
time.sleep(0.05)
|
||||||
|
while stdout.channel.recv_ready():
|
||||||
|
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
|
||||||
|
code = stdout.channel.recv_exit_status()
|
||||||
|
print(f"[exit {code}]", flush=True)
|
||||||
|
c.close()
|
||||||
|
return code
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
46
apps/admin/deploy/_push_weapp_switches_svc.py
Normal file
46
apps/admin/deploy/_push_weapp_switches_svc.py
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import paramiko
|
||||||
|
|
||||||
|
REPO = Path(__file__).resolve().parents[3]
|
||||||
|
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
|
||||||
|
SRC = REPO / "apps/api/services/ebook_svc/services/weapp_switches.py"
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
data = SRC.read_text(encoding="utf-8").replace("ebook_svc.", "app.").encode("utf-8")
|
||||||
|
c = paramiko.SSHClient()
|
||||||
|
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||||
|
c.connect(HOST, username=USER, password=PASS, timeout=60, allow_agent=False, look_for_keys=False)
|
||||||
|
sftp = c.open_sftp()
|
||||||
|
with sftp.file("/tmp/weapp_switches.py", "wb") as rf:
|
||||||
|
rf.write(data)
|
||||||
|
sftp.close()
|
||||||
|
cmd = r"""
|
||||||
|
set -e
|
||||||
|
sudo cp /tmp/weapp_switches.py /opt/nomadmini/backend/app/services/weapp_switches.py
|
||||||
|
cd /opt/nomadmini/backend
|
||||||
|
.venv/bin/python -c 'from app.services.weapp_switches import read_weapp_switches; print("ok", read_weapp_switches()["bookAudit"])'
|
||||||
|
sudo systemctl restart nomadmini-api
|
||||||
|
sleep 2
|
||||||
|
systemctl is-active nomadmini-api
|
||||||
|
rm -f /tmp/weapp_switches.py
|
||||||
|
"""
|
||||||
|
_, stdout, _ = c.exec_command(cmd, timeout=90, get_pty=True)
|
||||||
|
while not stdout.channel.exit_status_ready():
|
||||||
|
if stdout.channel.recv_ready():
|
||||||
|
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
|
||||||
|
time.sleep(0.05)
|
||||||
|
while stdout.channel.recv_ready():
|
||||||
|
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
|
||||||
|
code = stdout.channel.recv_exit_status()
|
||||||
|
c.close()
|
||||||
|
return code
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
116
apps/admin/deploy/_seed_audit_book.py
Normal file
116
apps/admin/deploy/_seed_audit_book.py
Normal file
@ -0,0 +1,116 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""Write WeChat-safe digital-nomad audit booklet into prod DB."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import paramiko
|
||||||
|
|
||||||
|
HERE = Path(__file__).resolve().parent
|
||||||
|
MD = (HERE / "audit_book_seed.md").read_text(encoding="utf-8")
|
||||||
|
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
|
||||||
|
|
||||||
|
|
||||||
|
def split_markdown_chapters(md: str) -> list[dict]:
|
||||||
|
text = (md or "").replace("\r\n", "\n").replace("\r", "\n").strip()
|
||||||
|
if not text:
|
||||||
|
return []
|
||||||
|
parts = re.split(r"(?m)^(#{1} .+)$", text)
|
||||||
|
chapters: list[dict] = []
|
||||||
|
preamble = (parts[0] or "").strip()
|
||||||
|
order = 1
|
||||||
|
if preamble and len(parts) == 1:
|
||||||
|
return [{"id": "c1", "title": "正文", "order": 1, "content": preamble + "\n"}]
|
||||||
|
if preamble:
|
||||||
|
chapters.append({"id": "c0", "title": "前言", "order": order, "content": preamble + "\n"})
|
||||||
|
order += 1
|
||||||
|
i = 1
|
||||||
|
while i < len(parts):
|
||||||
|
heading = parts[i].strip()
|
||||||
|
body = parts[i + 1] if i + 1 < len(parts) else ""
|
||||||
|
title = re.sub(r"^#\s+", "", heading).strip() or f"第{order}章"
|
||||||
|
content = f"{heading}\n{body}".strip() + "\n"
|
||||||
|
chapters.append({"id": f"c{order}", "title": title, "order": order, "content": content})
|
||||||
|
order += 1
|
||||||
|
i += 2
|
||||||
|
return chapters
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
chapters = split_markdown_chapters(MD)
|
||||||
|
assert chapters, "no chapters"
|
||||||
|
payload = {
|
||||||
|
"title": "数字游民入门指南",
|
||||||
|
"subtitle": "远程办公 · 自律生活 · 稳健成长",
|
||||||
|
"description": "面向普通人的数字游民与远程办公入门读本:时间管理、协作沟通、健康作息与职业成长。",
|
||||||
|
"chapters": chapters,
|
||||||
|
}
|
||||||
|
raw = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
||||||
|
|
||||||
|
c = paramiko.SSHClient()
|
||||||
|
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||||
|
c.connect(HOST, username=USER, password=PASS, timeout=60, allow_agent=False, look_for_keys=False)
|
||||||
|
sftp = c.open_sftp()
|
||||||
|
with sftp.file("/tmp/audit_book_seed.json", "wb") as rf:
|
||||||
|
rf.write(raw)
|
||||||
|
sftp.close()
|
||||||
|
|
||||||
|
cmd = r"""
|
||||||
|
set -e
|
||||||
|
python3 <<'PY'
|
||||||
|
import json, sqlite3, time
|
||||||
|
data=json.load(open('/tmp/audit_book_seed.json',encoding='utf-8'))
|
||||||
|
chapters=data['chapters']
|
||||||
|
con=sqlite3.connect('/opt/nomadmini/data/nomadmini.db')
|
||||||
|
now=time.time()
|
||||||
|
row=con.execute("select id from books where id='audit'").fetchone()
|
||||||
|
meta=(
|
||||||
|
data['title'], data['subtitle'], '', '📗', data['description'],
|
||||||
|
json.dumps(['数字游民','远程办公','生活方式'], ensure_ascii=False),
|
||||||
|
0, '', 100, 5.0, json.dumps(chapters, ensure_ascii=False), now,
|
||||||
|
)
|
||||||
|
if row:
|
||||||
|
con.execute(
|
||||||
|
'UPDATE books SET title=?, subtitle=?, author=?, cover_emoji=?, description=?, tags=?,'
|
||||||
|
' price_fen=?, product_id=?, unlock_percent=?, rating=?, chapters_json=?, updated_at=? WHERE id=?',
|
||||||
|
meta + ('audit',),
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
con.execute(
|
||||||
|
'INSERT INTO books(id,title,subtitle,author,cover_emoji,description,tags,'
|
||||||
|
'price_fen,product_id,unlock_percent,rating,chapters_json,updated_at) '
|
||||||
|
"VALUES ('audit',?,?,?,?,?,?,?,?,?,?,?,?)",
|
||||||
|
meta,
|
||||||
|
)
|
||||||
|
con.commit()
|
||||||
|
print('chapters', len(chapters))
|
||||||
|
print('titles', [c['title'] for c in chapters])
|
||||||
|
print('words', sum(len(c.get('content') or '') for c in chapters))
|
||||||
|
PY
|
||||||
|
curl -sk -o /tmp/audit_check.json -w "audit %{http_code}\n" https://api.nomadro.cn/api/ebook/books/audit
|
||||||
|
python3 <<'PY'
|
||||||
|
import json
|
||||||
|
d=json.load(open('/tmp/audit_check.json',encoding='utf-8'))
|
||||||
|
print('api', d.get('title'), d.get('chapter_count'), d.get('is_free'))
|
||||||
|
print('toc', [c.get('title') for c in (d.get('chapters') or [])])
|
||||||
|
PY
|
||||||
|
rm -f /tmp/audit_book_seed.json /tmp/audit_check.json
|
||||||
|
"""
|
||||||
|
_, stdout, _ = c.exec_command(cmd, timeout=90, get_pty=True)
|
||||||
|
while not stdout.channel.exit_status_ready():
|
||||||
|
if stdout.channel.recv_ready():
|
||||||
|
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
|
||||||
|
time.sleep(0.05)
|
||||||
|
while stdout.channel.recv_ready():
|
||||||
|
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
|
||||||
|
code = stdout.channel.recv_exit_status()
|
||||||
|
print(f"[exit {code}]", flush=True)
|
||||||
|
c.close()
|
||||||
|
return code
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
@ -4,6 +4,10 @@ import Login from './pages/Login'
|
|||||||
import PlatformSelect from './pages/PlatformSelect'
|
import PlatformSelect from './pages/PlatformSelect'
|
||||||
import Dashboard from './pages/Dashboard'
|
import Dashboard from './pages/Dashboard'
|
||||||
import Switches from './pages/Switches'
|
import Switches from './pages/Switches'
|
||||||
|
import Social from './pages/Social'
|
||||||
|
import SocialData from './pages/SocialData'
|
||||||
|
import Community from './pages/Community'
|
||||||
|
import Books from './pages/Books'
|
||||||
import BookEdit from './pages/BookEdit'
|
import BookEdit from './pages/BookEdit'
|
||||||
import './pages/BookEdit.css'
|
import './pages/BookEdit.css'
|
||||||
import Orders from './pages/Orders'
|
import Orders from './pages/Orders'
|
||||||
@ -69,6 +73,10 @@ export default function App() {
|
|||||||
>
|
>
|
||||||
<Route index element={<Dashboard />} />
|
<Route index element={<Dashboard />} />
|
||||||
<Route path="switches" element={<Switches />} />
|
<Route path="switches" element={<Switches />} />
|
||||||
|
<Route path="social" element={<Social />} />
|
||||||
|
<Route path="social/data" element={<SocialData />} />
|
||||||
|
<Route path="community" element={<Community />} />
|
||||||
|
<Route path="books" element={<Books />} />
|
||||||
<Route path="books/:id" element={<BookEdit />} />
|
<Route path="books/:id" element={<BookEdit />} />
|
||||||
<Route path="vip" element={<Vip />} />
|
<Route path="vip" element={<Vip />} />
|
||||||
<Route path="vip/users" element={<VipUsers />} />
|
<Route path="vip/users" element={<VipUsers />} />
|
||||||
|
|||||||
@ -30,6 +30,19 @@ const NAV_GROUPS: NavGroup[] = [
|
|||||||
label: '内容',
|
label: '内容',
|
||||||
items: [
|
items: [
|
||||||
{ to: '/wechat/nav', ico: '🧭', label: '导航' },
|
{ to: '/wechat/nav', ico: '🧭', label: '导航' },
|
||||||
|
{
|
||||||
|
kind: 'branch',
|
||||||
|
id: 'social',
|
||||||
|
ico: '💕',
|
||||||
|
label: '游民社区',
|
||||||
|
match: ['/wechat/social'],
|
||||||
|
defaultTo: '/wechat/social/data',
|
||||||
|
children: [
|
||||||
|
{ to: '/wechat/social/data', ico: '🗄️', label: 'UGC 数据' },
|
||||||
|
{ to: '/wechat/social', end: true, ico: '⏻', label: '开关文案' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{ to: '/wechat/community', ico: '🌍', label: '门户社区' },
|
||||||
{
|
{
|
||||||
kind: 'branch',
|
kind: 'branch',
|
||||||
id: 'vip',
|
id: 'vip',
|
||||||
@ -46,8 +59,9 @@ const NAV_GROUPS: NavGroup[] = [
|
|||||||
ico: '📖',
|
ico: '📖',
|
||||||
label: '电子书',
|
label: '电子书',
|
||||||
match: ['/wechat/vip/ebooks', '/wechat/books'],
|
match: ['/wechat/vip/ebooks', '/wechat/books'],
|
||||||
defaultTo: '/wechat/vip/ebooks/nomad',
|
defaultTo: '/wechat/books',
|
||||||
children: [
|
children: [
|
||||||
|
{ to: '/wechat/books', end: true, ico: '📚', label: '小册列表' },
|
||||||
{ to: '/wechat/vip/ebooks/nomad', ico: '🌍', label: '数字游民' },
|
{ to: '/wechat/vip/ebooks/nomad', ico: '🌍', label: '数字游民' },
|
||||||
{ to: '/wechat/vip/ebooks/cloudphone', ico: '📱', label: '云手机' },
|
{ to: '/wechat/vip/ebooks/cloudphone', ico: '📱', label: '云手机' },
|
||||||
{ to: '/wechat/books/default', ico: '▶️', label: 'youtube运营笔记' },
|
{ to: '/wechat/books/default', ico: '▶️', label: 'youtube运营笔记' },
|
||||||
|
|||||||
115
apps/admin/src/components/WxCharts.tsx
Normal file
115
apps/admin/src/components/WxCharts.tsx
Normal file
@ -0,0 +1,115 @@
|
|||||||
|
/** Lightweight SVG charts — no chart lib dependency. */
|
||||||
|
|
||||||
|
type Point = { date: string; value: number }
|
||||||
|
|
||||||
|
function niceMax(n: number) {
|
||||||
|
if (n <= 0) return 1
|
||||||
|
const p = 10 ** Math.floor(Math.log10(n))
|
||||||
|
return Math.ceil(n / p) * p
|
||||||
|
}
|
||||||
|
|
||||||
|
export function WxSparkBars({
|
||||||
|
title,
|
||||||
|
subtitle,
|
||||||
|
points,
|
||||||
|
format = (v) => String(v),
|
||||||
|
accent = '#5ec478',
|
||||||
|
}: {
|
||||||
|
title: string
|
||||||
|
subtitle?: string
|
||||||
|
points: Point[]
|
||||||
|
format?: (v: number) => string
|
||||||
|
accent?: string
|
||||||
|
}) {
|
||||||
|
const w = 560
|
||||||
|
const h = 160
|
||||||
|
const pad = { t: 12, r: 8, b: 28, l: 8 }
|
||||||
|
const max = niceMax(Math.max(...points.map((p) => p.value), 0))
|
||||||
|
const bw = points.length
|
||||||
|
? (w - pad.l - pad.r) / points.length
|
||||||
|
: 0
|
||||||
|
const innerH = h - pad.t - pad.b
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="wx-chart">
|
||||||
|
<div className="wx-chart-head">
|
||||||
|
<div>
|
||||||
|
<strong>{title}</strong>
|
||||||
|
{subtitle ? <span className="wx-chart-sub">{subtitle}</span> : null}
|
||||||
|
</div>
|
||||||
|
<span className="wx-chart-max">峰值 {format(max)}</span>
|
||||||
|
</div>
|
||||||
|
<svg viewBox={`0 0 ${w} ${h}`} className="wx-chart-svg" role="img" aria-label={title}>
|
||||||
|
{points.map((p, i) => {
|
||||||
|
const barH = max ? (p.value / max) * innerH : 0
|
||||||
|
const x = pad.l + i * bw + bw * 0.15
|
||||||
|
const y = pad.t + innerH - barH
|
||||||
|
const showLabel = i === 0 || i === points.length - 1 || i % 3 === 0
|
||||||
|
return (
|
||||||
|
<g key={p.date}>
|
||||||
|
<rect
|
||||||
|
x={x}
|
||||||
|
y={y}
|
||||||
|
width={bw * 0.7}
|
||||||
|
height={Math.max(barH, p.value > 0 ? 2 : 0)}
|
||||||
|
rx={3}
|
||||||
|
fill={accent}
|
||||||
|
opacity={0.85}
|
||||||
|
>
|
||||||
|
<title>
|
||||||
|
{p.date}: {format(p.value)}
|
||||||
|
</title>
|
||||||
|
</rect>
|
||||||
|
{showLabel ? (
|
||||||
|
<text
|
||||||
|
x={x + bw * 0.35}
|
||||||
|
y={h - 8}
|
||||||
|
textAnchor="middle"
|
||||||
|
fill="currentColor"
|
||||||
|
fontSize={10}
|
||||||
|
opacity={0.55}
|
||||||
|
>
|
||||||
|
{p.date.slice(5)}
|
||||||
|
</text>
|
||||||
|
) : null}
|
||||||
|
</g>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function WxRankList({
|
||||||
|
title,
|
||||||
|
items,
|
||||||
|
}: {
|
||||||
|
title: string
|
||||||
|
items: Array<{ name: string; count: number }>
|
||||||
|
}) {
|
||||||
|
const max = Math.max(...items.map((i) => i.count), 1)
|
||||||
|
return (
|
||||||
|
<div className="wx-chart">
|
||||||
|
<div className="wx-chart-head">
|
||||||
|
<strong>{title}</strong>
|
||||||
|
</div>
|
||||||
|
<ul className="wx-rank">
|
||||||
|
{items.length ? (
|
||||||
|
items.map((it) => (
|
||||||
|
<li key={it.name}>
|
||||||
|
<div className="wx-rank-row">
|
||||||
|
<span className="wx-rank-name">{it.name || '(empty)'}</span>
|
||||||
|
<span className="wx-rank-n">{it.count}</span>
|
||||||
|
</div>
|
||||||
|
<div className="wx-rank-track">
|
||||||
|
<i style={{ width: `${(it.count / max) * 100}%` }} />
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
))
|
||||||
|
) : (
|
||||||
|
<li className="wx-rank-empty">暂无数据</li>
|
||||||
|
)}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@ -25,21 +25,25 @@ export function WxHead({
|
|||||||
|
|
||||||
export function WxToast({
|
export function WxToast({
|
||||||
kind,
|
kind,
|
||||||
|
tone,
|
||||||
children,
|
children,
|
||||||
onClose,
|
onClose,
|
||||||
}: {
|
}: {
|
||||||
kind: 'ok' | 'err' | 'info'
|
kind?: 'ok' | 'err' | 'info'
|
||||||
|
/** @deprecated use kind */
|
||||||
|
tone?: 'ok' | 'err' | 'info'
|
||||||
children: ReactNode
|
children: ReactNode
|
||||||
onClose?: () => void
|
onClose?: () => void
|
||||||
}) {
|
}) {
|
||||||
|
const k = kind || tone || 'info'
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!onClose || kind === 'err') return
|
if (!onClose || k === 'err') return
|
||||||
const t = window.setTimeout(onClose, 4200)
|
const t = window.setTimeout(onClose, 4200)
|
||||||
return () => window.clearTimeout(t)
|
return () => window.clearTimeout(t)
|
||||||
}, [children, kind, onClose])
|
}, [children, k, onClose])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={`wx-toast wx-toast--${kind}`} role="status">
|
<div className={`wx-toast wx-toast--${k}`} role="status">
|
||||||
<span>{children}</span>
|
<span>{children}</span>
|
||||||
{onClose ? (
|
{onClose ? (
|
||||||
<button type="button" onClick={onClose}>
|
<button type="button" onClick={onClose}>
|
||||||
|
|||||||
192
apps/admin/src/pages/Books.tsx
Normal file
192
apps/admin/src/pages/Books.tsx
Normal file
@ -0,0 +1,192 @@
|
|||||||
|
/** 小册列表 · 创建 / 进入编辑 / 删除 */
|
||||||
|
import { useCallback, useEffect, useState } from 'react'
|
||||||
|
import { Link } from 'react-router-dom'
|
||||||
|
import { api } from '../api'
|
||||||
|
import { WxEmpty, WxHead, WxToast, fmtTime } from '../components/wxUi'
|
||||||
|
|
||||||
|
type Book = {
|
||||||
|
id: string
|
||||||
|
title: string
|
||||||
|
subtitle?: string
|
||||||
|
cover_emoji?: string
|
||||||
|
price_fen?: number
|
||||||
|
unlock_percent?: number
|
||||||
|
chapter_count?: number
|
||||||
|
word_count?: number
|
||||||
|
updated_at?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function Books() {
|
||||||
|
const [items, setItems] = useState<Book[]>([])
|
||||||
|
const [loading, setLoading] = useState(true)
|
||||||
|
const [busy, setBusy] = useState(false)
|
||||||
|
const [err, setErr] = useState('')
|
||||||
|
const [msg, setMsg] = useState('')
|
||||||
|
const [newId, setNewId] = useState('')
|
||||||
|
const [newTitle, setNewTitle] = useState('')
|
||||||
|
|
||||||
|
const load = useCallback(async () => {
|
||||||
|
setLoading(true)
|
||||||
|
setErr('')
|
||||||
|
try {
|
||||||
|
const data = await api<Book[]>('/api/admin/books')
|
||||||
|
setItems(Array.isArray(data) ? data : [])
|
||||||
|
} catch (e: any) {
|
||||||
|
setErr(e.message || '加载失败')
|
||||||
|
} finally {
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void load()
|
||||||
|
}, [load])
|
||||||
|
|
||||||
|
async function create() {
|
||||||
|
const id = newId.trim()
|
||||||
|
if (!id) {
|
||||||
|
setErr('需要书籍 id')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
setBusy(true)
|
||||||
|
setErr('')
|
||||||
|
try {
|
||||||
|
await api('/api/admin/books', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ id, title: newTitle.trim() || id, free: true }),
|
||||||
|
})
|
||||||
|
setMsg('已创建')
|
||||||
|
setNewId('')
|
||||||
|
setNewTitle('')
|
||||||
|
await load()
|
||||||
|
} catch (e: any) {
|
||||||
|
setErr(e.message || '创建失败')
|
||||||
|
} finally {
|
||||||
|
setBusy(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function remove(id: string) {
|
||||||
|
if (!confirm(`删除小册 ${id}?`)) return
|
||||||
|
setBusy(true)
|
||||||
|
try {
|
||||||
|
await api(`/api/admin/books/${encodeURIComponent(id)}`, { method: 'DELETE' })
|
||||||
|
setMsg('已删除')
|
||||||
|
await load()
|
||||||
|
} catch (e: any) {
|
||||||
|
setErr(e.message || '删除失败')
|
||||||
|
} finally {
|
||||||
|
setBusy(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="wx-page">
|
||||||
|
<WxHead
|
||||||
|
eyebrow="内容"
|
||||||
|
title="小册列表"
|
||||||
|
desc="SQLite books 表:创建壳、进入章节编辑、删除(default / __vip__ 不可删)。"
|
||||||
|
>
|
||||||
|
<button type="button" className="wx-btn" onClick={() => void load()} disabled={loading}>
|
||||||
|
刷新
|
||||||
|
</button>
|
||||||
|
</WxHead>
|
||||||
|
|
||||||
|
{err ? (
|
||||||
|
<WxToast kind="err" onClose={() => setErr('')}>
|
||||||
|
{err}
|
||||||
|
</WxToast>
|
||||||
|
) : null}
|
||||||
|
{msg ? (
|
||||||
|
<WxToast kind="ok" onClose={() => setMsg('')}>
|
||||||
|
{msg}
|
||||||
|
</WxToast>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<div className="wx-panel" style={{ marginBottom: 16 }}>
|
||||||
|
<div className="wx-panel-head">
|
||||||
|
<div>
|
||||||
|
<h2>新建小册</h2>
|
||||||
|
<p>id 用作路由 `/wechat/books/:id`</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="wx-toolbar">
|
||||||
|
<input
|
||||||
|
placeholder="id,如 audit / youtube-notes"
|
||||||
|
value={newId}
|
||||||
|
onChange={(e) => setNewId(e.target.value)}
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
placeholder="标题(可选)"
|
||||||
|
value={newTitle}
|
||||||
|
onChange={(e) => setNewTitle(e.target.value)}
|
||||||
|
/>
|
||||||
|
<button type="button" className="wx-btn" disabled={busy} onClick={() => void create()}>
|
||||||
|
创建
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="wx-table-wrap">
|
||||||
|
{items.length ? (
|
||||||
|
<table className="wx-table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>书籍</th>
|
||||||
|
<th>试读 / 价格</th>
|
||||||
|
<th>章节</th>
|
||||||
|
<th>更新</th>
|
||||||
|
<th>操作</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{items.map((b) => (
|
||||||
|
<tr key={b.id}>
|
||||||
|
<td>
|
||||||
|
<strong>
|
||||||
|
{b.cover_emoji || '📗'} {b.title}
|
||||||
|
</strong>
|
||||||
|
<div className="wx-mono" style={{ opacity: 0.65, fontSize: 12 }}>
|
||||||
|
{b.id}
|
||||||
|
</div>
|
||||||
|
{b.subtitle ? (
|
||||||
|
<div className="wx-muted" style={{ fontSize: 12 }}>
|
||||||
|
{b.subtitle}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
{b.unlock_percent ?? '—'}% · ¥{((b.price_fen || 0) / 100).toFixed(2)}
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
{b.chapter_count ?? 0} 章 · {b.word_count ?? 0} 字
|
||||||
|
</td>
|
||||||
|
<td>{b.updated_at ? fmtTime(b.updated_at) : '—'}</td>
|
||||||
|
<td>
|
||||||
|
<div className="wx-row-actions">
|
||||||
|
<Link className="wx-btn-sm primary" to={`/wechat/books/${b.id}`}>
|
||||||
|
编辑
|
||||||
|
</Link>
|
||||||
|
{b.id !== 'default' && b.id !== '__vip__' ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="wx-btn-sm danger"
|
||||||
|
disabled={busy}
|
||||||
|
onClick={() => void remove(b.id)}
|
||||||
|
>
|
||||||
|
删除
|
||||||
|
</button>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
) : (
|
||||||
|
<WxEmpty title={loading ? '加载中…' : '暂无小册'} />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
255
apps/admin/src/pages/Community.tsx
Normal file
255
apps/admin/src/pages/Community.tsx
Normal file
@ -0,0 +1,255 @@
|
|||||||
|
/** 门户社区运营 — meetups / discussions / gigs JSON CRUD */
|
||||||
|
import { useCallback, useEffect, useState } from 'react'
|
||||||
|
import { api } from '../api'
|
||||||
|
import { WxEmpty, WxHead, WxTabs, WxToast } from '../components/wxUi'
|
||||||
|
|
||||||
|
type Tab = 'meetups' | 'discussions' | 'gigs'
|
||||||
|
|
||||||
|
type Overview = {
|
||||||
|
ok: boolean
|
||||||
|
source?: string
|
||||||
|
path?: string
|
||||||
|
exists?: boolean
|
||||||
|
stats?: Record<string, number>
|
||||||
|
}
|
||||||
|
|
||||||
|
const TABS: Array<{ key: Tab; label: string }> = [
|
||||||
|
{ key: 'meetups', label: '活动' },
|
||||||
|
{ key: 'discussions', label: '讨论' },
|
||||||
|
{ key: 'gigs', label: '机会' },
|
||||||
|
]
|
||||||
|
|
||||||
|
export default function Community() {
|
||||||
|
const [tab, setTab] = useState<Tab>('meetups')
|
||||||
|
const [overview, setOverview] = useState<Overview | null>(null)
|
||||||
|
const [items, setItems] = useState<any[]>([])
|
||||||
|
const [loading, setLoading] = useState(true)
|
||||||
|
const [busy, setBusy] = useState(false)
|
||||||
|
const [err, setErr] = useState('')
|
||||||
|
const [msg, setMsg] = useState('')
|
||||||
|
const [draft, setDraft] = useState('')
|
||||||
|
const [editingId, setEditingId] = useState<string | null>(null)
|
||||||
|
|
||||||
|
const load = useCallback(async () => {
|
||||||
|
setLoading(true)
|
||||||
|
setErr('')
|
||||||
|
try {
|
||||||
|
const ov = await api<Overview>('/api/admin/community/overview')
|
||||||
|
setOverview(ov)
|
||||||
|
const data = await api<{ items: any[] }>(`/api/admin/community/${tab}`)
|
||||||
|
setItems(data.items || [])
|
||||||
|
} catch (e: any) {
|
||||||
|
setErr(e.message || '加载失败')
|
||||||
|
setItems([])
|
||||||
|
} finally {
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
}, [tab])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void load()
|
||||||
|
}, [load])
|
||||||
|
|
||||||
|
function startCreate() {
|
||||||
|
setEditingId('__new__')
|
||||||
|
setDraft(
|
||||||
|
JSON.stringify(
|
||||||
|
tab === 'meetups'
|
||||||
|
? {
|
||||||
|
id: `meetup_${Date.now().toString(36)}`,
|
||||||
|
title: '新活动',
|
||||||
|
city: '线上',
|
||||||
|
emoji: '🎙️',
|
||||||
|
date: '',
|
||||||
|
time: '',
|
||||||
|
description: '',
|
||||||
|
mode: 'online',
|
||||||
|
is_upcoming: true,
|
||||||
|
}
|
||||||
|
: tab === 'gigs'
|
||||||
|
? {
|
||||||
|
id: `gig_${Date.now().toString(36)}`,
|
||||||
|
title: '新机会',
|
||||||
|
role: '',
|
||||||
|
pay: '',
|
||||||
|
tags: [],
|
||||||
|
remote: true,
|
||||||
|
}
|
||||||
|
: {
|
||||||
|
id: `disc_${Date.now().toString(36)}`,
|
||||||
|
title: '新讨论',
|
||||||
|
category: 'general',
|
||||||
|
body: '',
|
||||||
|
},
|
||||||
|
null,
|
||||||
|
2,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function startEdit(item: any) {
|
||||||
|
setEditingId(String(item.id))
|
||||||
|
setDraft(JSON.stringify(item, null, 2))
|
||||||
|
}
|
||||||
|
|
||||||
|
async function save() {
|
||||||
|
setBusy(true)
|
||||||
|
setErr('')
|
||||||
|
setMsg('')
|
||||||
|
try {
|
||||||
|
const item = JSON.parse(draft)
|
||||||
|
await api(`/api/admin/community/${tab}`, {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ item }),
|
||||||
|
})
|
||||||
|
setMsg('已保存')
|
||||||
|
setEditingId(null)
|
||||||
|
await load()
|
||||||
|
} catch (e: any) {
|
||||||
|
setErr(e.message || '保存失败')
|
||||||
|
} finally {
|
||||||
|
setBusy(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function remove(id: string) {
|
||||||
|
if (!confirm(`删除 ${id}?`)) return
|
||||||
|
setBusy(true)
|
||||||
|
try {
|
||||||
|
await api(`/api/admin/community/${tab}/${encodeURIComponent(id)}`, { method: 'DELETE' })
|
||||||
|
setMsg('已删除')
|
||||||
|
await load()
|
||||||
|
} catch (e: any) {
|
||||||
|
setErr(e.message || '删除失败')
|
||||||
|
} finally {
|
||||||
|
setBusy(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const stats = overview?.stats || {}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="wx-page">
|
||||||
|
<WxHead
|
||||||
|
eyebrow="门户社区"
|
||||||
|
title="Community 运营"
|
||||||
|
desc="活动 / 讨论 / 共创机会。优先读写 JSON 兜底库;community_svc 在线时仅展示。"
|
||||||
|
>
|
||||||
|
<button type="button" className="wx-btn wx-btn-ghost" onClick={() => void load()}>
|
||||||
|
刷新
|
||||||
|
</button>
|
||||||
|
<button type="button" className="wx-btn" onClick={startCreate}>
|
||||||
|
新建
|
||||||
|
</button>
|
||||||
|
</WxHead>
|
||||||
|
|
||||||
|
{err ? (
|
||||||
|
<WxToast kind="err" onClose={() => setErr('')}>
|
||||||
|
{err}
|
||||||
|
</WxToast>
|
||||||
|
) : null}
|
||||||
|
{msg ? (
|
||||||
|
<WxToast kind="ok" onClose={() => setMsg('')}>
|
||||||
|
{msg}
|
||||||
|
</WxToast>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<div className="wx-stats">
|
||||||
|
<div className="wx-stat">
|
||||||
|
<div className="wx-stat-val">{stats.meetups ?? '—'}</div>
|
||||||
|
<div className="wx-stat-label">活动</div>
|
||||||
|
</div>
|
||||||
|
<div className="wx-stat">
|
||||||
|
<div className="wx-stat-val">{stats.discussions ?? '—'}</div>
|
||||||
|
<div className="wx-stat-label">讨论</div>
|
||||||
|
</div>
|
||||||
|
<div className="wx-stat">
|
||||||
|
<div className="wx-stat-val">{stats.gigs ?? '—'}</div>
|
||||||
|
<div className="wx-stat-label">机会</div>
|
||||||
|
</div>
|
||||||
|
<div className="wx-stat">
|
||||||
|
<div className="wx-stat-val">{overview?.source || '—'}</div>
|
||||||
|
<div className="wx-stat-label">数据源</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p className="wx-muted" style={{ fontSize: 13, marginBottom: 12 }}>
|
||||||
|
{overview?.path || '—'} {overview?.exists === false ? '(文件尚未创建,保存后生成)' : ''}
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<WxTabs value={tab} onChange={setTab} items={TABS} />
|
||||||
|
|
||||||
|
<div className="wx-table-wrap">
|
||||||
|
{items.length ? (
|
||||||
|
<table className="wx-table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>ID</th>
|
||||||
|
<th>标题</th>
|
||||||
|
<th>摘要</th>
|
||||||
|
<th>操作</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{items.map((it) => (
|
||||||
|
<tr key={it.id}>
|
||||||
|
<td className="wx-mono">{it.id}</td>
|
||||||
|
<td>
|
||||||
|
<strong>
|
||||||
|
{it.emoji ? `${it.emoji} ` : ''}
|
||||||
|
{it.title || it.role || '—'}
|
||||||
|
</strong>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
{(it.city || it.category || it.pay || '').toString()}{' '}
|
||||||
|
{(it.description || it.body || it.role || '').toString().slice(0, 80)}
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<div className="wx-row-actions">
|
||||||
|
<button type="button" className="wx-btn-sm" onClick={() => startEdit(it)}>
|
||||||
|
编辑
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="wx-btn-sm danger"
|
||||||
|
disabled={busy}
|
||||||
|
onClick={() => void remove(String(it.id))}
|
||||||
|
>
|
||||||
|
删除
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
) : (
|
||||||
|
<WxEmpty title={loading ? '加载中…' : '暂无条目'} hint="点击新建,或从种子导入后编辑" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{editingId ? (
|
||||||
|
<div className="wx-modal-mask" onClick={() => setEditingId(null)}>
|
||||||
|
<div className="wx-modal wx-modal-lg" onClick={(e) => e.stopPropagation()}>
|
||||||
|
<h3>{editingId === '__new__' ? '新建' : `编辑 ${editingId}`}</h3>
|
||||||
|
<textarea
|
||||||
|
className="wx-code"
|
||||||
|
rows={18}
|
||||||
|
value={draft}
|
||||||
|
onChange={(e) => setDraft(e.target.value)}
|
||||||
|
spellCheck={false}
|
||||||
|
/>
|
||||||
|
<div className="wx-row-actions">
|
||||||
|
<button type="button" className="wx-btn wx-btn-ghost" onClick={() => setEditingId(null)}>
|
||||||
|
取消
|
||||||
|
</button>
|
||||||
|
<button type="button" className="wx-btn" disabled={busy} onClick={() => void save()}>
|
||||||
|
保存
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@ -1,6 +1,7 @@
|
|||||||
import { useCallback, useEffect, useState } from 'react'
|
import { useCallback, useEffect, useState } from 'react'
|
||||||
import { Link } from 'react-router-dom'
|
import { Link } from 'react-router-dom'
|
||||||
import { api } from '../api'
|
import { api } from '../api'
|
||||||
|
import { WxRankList, WxSparkBars } from '../components/WxCharts'
|
||||||
|
|
||||||
type Stats = {
|
type Stats = {
|
||||||
users: number
|
users: number
|
||||||
@ -9,6 +10,14 @@ type Stats = {
|
|||||||
paid_amount_fen: number
|
paid_amount_fen: number
|
||||||
pending_orders: number
|
pending_orders: number
|
||||||
track_events?: number
|
track_events?: number
|
||||||
|
books?: number
|
||||||
|
refunded_orders?: number
|
||||||
|
series?: {
|
||||||
|
revenue: Array<{ date: string; amountFen: number }>
|
||||||
|
orders: Array<{ date: string; count: number }>
|
||||||
|
events: Array<{ date: string; count: number }>
|
||||||
|
}
|
||||||
|
topEvents?: Array<{ name: string; count: number }>
|
||||||
}
|
}
|
||||||
|
|
||||||
const HUBS: Array<{
|
const HUBS: Array<{
|
||||||
@ -25,6 +34,31 @@ const HUBS: Array<{
|
|||||||
desc: '页面 / 入口 / 文案',
|
desc: '页面 / 入口 / 文案',
|
||||||
primary: true,
|
primary: true,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
to: '/wechat/social',
|
||||||
|
ico: '💕',
|
||||||
|
title: '游民社区开关',
|
||||||
|
desc: '子页 / 区块 / 功能 / 按钮 / 文案',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
to: '/wechat/social/data',
|
||||||
|
ico: '🗄️',
|
||||||
|
title: '游民社区数据',
|
||||||
|
desc: '消息 / 介绍 / 评价 / 报名 CRUD',
|
||||||
|
primary: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
to: '/wechat/community',
|
||||||
|
ico: '🏕️',
|
||||||
|
title: '门户 Community',
|
||||||
|
desc: '活动 / 讨论 / 机会列表与编辑',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
to: '/wechat/books',
|
||||||
|
ico: '📚',
|
||||||
|
title: '小册列表',
|
||||||
|
desc: '创建 / 编辑 / 删除 SQLite 小册',
|
||||||
|
},
|
||||||
{
|
{
|
||||||
to: '/wechat/books/default',
|
to: '/wechat/books/default',
|
||||||
ico: '▶️',
|
ico: '▶️',
|
||||||
@ -196,7 +230,7 @@ export default function Dashboard() {
|
|||||||
<div className="wx-eyebrow">微信小程序</div>
|
<div className="wx-eyebrow">微信小程序</div>
|
||||||
<h1>微信运营台</h1>
|
<h1>微信运营台</h1>
|
||||||
<p>
|
<p>
|
||||||
小册试读、VIP、导航、电商与社群同一后台。虚拟支付订单与读者运营在此查看——与抖音控制台数据隔离。
|
小册试读、VIP、导航、电商、旅居社群与游民社区(pages/social)同一后台。虚拟支付订单与读者运营在此查看——与抖音控制台数据隔离;开关只改 remote-config,不写业务库。
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="wx-head-actions">
|
<div className="wx-head-actions">
|
||||||
@ -242,6 +276,37 @@ export default function Dashboard() {
|
|||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<section className="wx-chart-grid">
|
||||||
|
<WxSparkBars
|
||||||
|
title="近 14 日成交额"
|
||||||
|
subtitle="已发货订单金额(元)"
|
||||||
|
accent="#d7b35a"
|
||||||
|
points={(stats?.series?.revenue || []).map((p) => ({
|
||||||
|
date: p.date,
|
||||||
|
value: (p.amountFen || 0) / 100,
|
||||||
|
}))}
|
||||||
|
format={(v) => v.toFixed(0)}
|
||||||
|
/>
|
||||||
|
<WxSparkBars
|
||||||
|
title="近 14 日订单数"
|
||||||
|
subtitle="已发货笔数"
|
||||||
|
points={(stats?.series?.orders || []).map((p) => ({
|
||||||
|
date: p.date,
|
||||||
|
value: p.count || 0,
|
||||||
|
}))}
|
||||||
|
/>
|
||||||
|
<WxSparkBars
|
||||||
|
title="近 14 日埋点"
|
||||||
|
subtitle="track_events"
|
||||||
|
accent="#7be0a4"
|
||||||
|
points={(stats?.series?.events || []).map((p) => ({
|
||||||
|
date: p.date,
|
||||||
|
value: p.count || 0,
|
||||||
|
}))}
|
||||||
|
/>
|
||||||
|
<WxRankList title="近 7 日热门事件" items={stats?.topEvents || []} />
|
||||||
|
</section>
|
||||||
|
|
||||||
<section className="wx-panel">
|
<section className="wx-panel">
|
||||||
<div className="wx-panel-head">
|
<div className="wx-panel-head">
|
||||||
<div>
|
<div>
|
||||||
|
|||||||
@ -87,6 +87,7 @@ export default function MemoAdmin() {
|
|||||||
const [err, setErr] = useState('')
|
const [err, setErr] = useState('')
|
||||||
const [msg, setMsg] = useState('')
|
const [msg, setMsg] = useState('')
|
||||||
const [busy, setBusy] = useState(false)
|
const [busy, setBusy] = useState(false)
|
||||||
|
const [editId, setEditId] = useState<string | null>(null)
|
||||||
const [feedFilter, setFeedFilter] = useState<
|
const [feedFilter, setFeedFilter] = useState<
|
||||||
'all' | 'trial' | 'vip' | 'pinned' | 'featured' | 'hidden'
|
'all' | 'trial' | 'vip' | 'pinned' | 'featured' | 'hidden'
|
||||||
>('all')
|
>('all')
|
||||||
@ -175,33 +176,58 @@ export default function MemoAdmin() {
|
|||||||
setErr('')
|
setErr('')
|
||||||
setMsg('')
|
setMsg('')
|
||||||
try {
|
try {
|
||||||
await api('/api/admin/memo/memos', {
|
if (editId) {
|
||||||
method: 'POST',
|
await api(`/api/admin/memo/memos/${editId}`, {
|
||||||
body: JSON.stringify({
|
method: 'PUT',
|
||||||
title: title.trim(),
|
body: JSON.stringify({
|
||||||
content: draft.trim(),
|
title: title.trim(),
|
||||||
nickname: '博主',
|
content: draft.trim(),
|
||||||
pinned: pinNew,
|
nickname: '博主',
|
||||||
featured: featNew,
|
trial: trialNew,
|
||||||
trial: trialNew,
|
resources,
|
||||||
resources,
|
}),
|
||||||
}),
|
})
|
||||||
})
|
setMsg('已更新')
|
||||||
|
setEditId(null)
|
||||||
|
} else {
|
||||||
|
await api('/api/admin/memo/memos', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({
|
||||||
|
title: title.trim(),
|
||||||
|
content: draft.trim(),
|
||||||
|
nickname: '博主',
|
||||||
|
pinned: pinNew,
|
||||||
|
featured: featNew,
|
||||||
|
trial: trialNew,
|
||||||
|
resources,
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
setMsg('已发布')
|
||||||
|
}
|
||||||
setTitle('')
|
setTitle('')
|
||||||
setDraft('')
|
setDraft('')
|
||||||
setImgUrls('')
|
setImgUrls('')
|
||||||
setPinNew(false)
|
setPinNew(false)
|
||||||
setFeatNew(false)
|
setFeatNew(false)
|
||||||
setTrialNew(true)
|
setTrialNew(true)
|
||||||
setMsg('已发布')
|
|
||||||
await load()
|
await load()
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setErr((e as Error).message || '发布失败')
|
setErr((e as Error).message || (editId ? '更新失败' : '发布失败'))
|
||||||
} finally {
|
} finally {
|
||||||
setBusy(false)
|
setBusy(false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function startEdit(m: Memo) {
|
||||||
|
setEditId(m.id)
|
||||||
|
setTitle(m.title || '')
|
||||||
|
setDraft(m.content || '')
|
||||||
|
setImgUrls((m.resources || []).map((r) => r.url).join('\n'))
|
||||||
|
setTrialNew(!!(m.trial || m.visibility === 'trial'))
|
||||||
|
setTab('feed')
|
||||||
|
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||||
|
}
|
||||||
|
|
||||||
async function del(id: string) {
|
async function del(id: string) {
|
||||||
if (!confirm('删除该帖?不可恢复')) return
|
if (!confirm('删除该帖?不可恢复')) return
|
||||||
setBusy(true)
|
setBusy(true)
|
||||||
@ -507,8 +533,27 @@ export default function MemoAdmin() {
|
|||||||
) : null}
|
) : null}
|
||||||
<div className="wx-sticky-bar">
|
<div className="wx-sticky-bar">
|
||||||
<div className="wx-row-actions">
|
<div className="wx-row-actions">
|
||||||
|
{editId ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="wx-btn-sm"
|
||||||
|
onClick={() => {
|
||||||
|
setEditId(null)
|
||||||
|
setTitle('')
|
||||||
|
setDraft('')
|
||||||
|
setImgUrls('')
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
取消编辑
|
||||||
|
</button>
|
||||||
|
) : null}
|
||||||
<label style={{ display: 'flex', gap: 6, alignItems: 'center', fontSize: 13 }}>
|
<label style={{ display: 'flex', gap: 6, alignItems: 'center', fontSize: 13 }}>
|
||||||
<input type="checkbox" checked={pinNew} onChange={(e) => setPinNew(e.target.checked)} />
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={pinNew}
|
||||||
|
disabled={!!editId}
|
||||||
|
onChange={(e) => setPinNew(e.target.checked)}
|
||||||
|
/>
|
||||||
置顶
|
置顶
|
||||||
</label>
|
</label>
|
||||||
<label style={{ display: 'flex', gap: 6, alignItems: 'center', fontSize: 13 }}>
|
<label style={{ display: 'flex', gap: 6, alignItems: 'center', fontSize: 13 }}>
|
||||||
@ -529,7 +574,7 @@ export default function MemoAdmin() {
|
|||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<button type="button" className="wx-btn" disabled={busy} onClick={() => void publish()}>
|
<button type="button" className="wx-btn" disabled={busy} onClick={() => void publish()}>
|
||||||
{busy ? '发布中…' : '发布'}
|
{busy ? (editId ? '保存中…' : '发布中…') : editId ? '保存修改' : '发布'}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
@ -585,6 +630,14 @@ export default function MemoAdmin() {
|
|||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
<div className="wx-row-actions">
|
<div className="wx-row-actions">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="wx-btn-sm primary"
|
||||||
|
disabled={busy}
|
||||||
|
onClick={() => startEdit(m)}
|
||||||
|
>
|
||||||
|
编辑
|
||||||
|
</button>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className="wx-btn-sm"
|
className="wx-btn-sm"
|
||||||
|
|||||||
@ -145,6 +145,22 @@ export default function Orders() {
|
|||||||
setMsg(ok ? `已复制 ${label}` : '复制失败')
|
setMsg(ok ? `已复制 ${label}` : '复制失败')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function markStatus(outTradeNo: string, status: string) {
|
||||||
|
const label = status === 'refunded' ? '标记退款' : '取消订单'
|
||||||
|
if (!confirm(`${label}?仅改本地状态,不直连微信退款。`)) return
|
||||||
|
setErr('')
|
||||||
|
try {
|
||||||
|
await api(`/api/admin/orders/${encodeURIComponent(outTradeNo)}/status`, {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ status }),
|
||||||
|
})
|
||||||
|
setMsg(`已${label}`)
|
||||||
|
load()
|
||||||
|
} catch (e: any) {
|
||||||
|
setErr(e.message || '操作失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function clearDeepLink() {
|
function clearDeepLink() {
|
||||||
if (searchParams.has('openid') || searchParams.has('kind')) {
|
if (searchParams.has('openid') || searchParams.has('kind')) {
|
||||||
const next = new URLSearchParams(searchParams)
|
const next = new URLSearchParams(searchParams)
|
||||||
@ -340,6 +356,28 @@ export default function Orders() {
|
|||||||
>
|
>
|
||||||
复制单号
|
复制单号
|
||||||
</button>
|
</button>
|
||||||
|
{!String(o.status || '')
|
||||||
|
.toLowerCase()
|
||||||
|
.includes('refund') ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="wx-btn-sm danger"
|
||||||
|
onClick={() => void markStatus(o.out_trade_no, 'refunded')}
|
||||||
|
>
|
||||||
|
标退款
|
||||||
|
</button>
|
||||||
|
) : null}
|
||||||
|
{!String(o.status || '')
|
||||||
|
.toLowerCase()
|
||||||
|
.includes('cancel') ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="wx-btn-sm"
|
||||||
|
onClick={() => void markStatus(o.out_trade_no, 'cancel')}
|
||||||
|
>
|
||||||
|
取消
|
||||||
|
</button>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
|||||||
@ -239,6 +239,24 @@ export default function Shop() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function markShopStatus(orderId: string, status: string) {
|
||||||
|
if (!confirm('仅改本地订单状态,不直连微信退款。继续?')) return
|
||||||
|
setBusy(true)
|
||||||
|
setErr('')
|
||||||
|
try {
|
||||||
|
await api(`/api/admin/shop/orders/${orderId}/status`, {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ status }),
|
||||||
|
})
|
||||||
|
setMsg('订单状态已更新')
|
||||||
|
await load()
|
||||||
|
} catch (e) {
|
||||||
|
setErr((e as Error).message || '更新失败')
|
||||||
|
} finally {
|
||||||
|
setBusy(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function ship(orderId: string) {
|
async function ship(orderId: string) {
|
||||||
if (!trackingNo.trim()) {
|
if (!trackingNo.trim()) {
|
||||||
setErr('请填写运单号')
|
setErr('请填写运单号')
|
||||||
@ -688,7 +706,20 @@ export default function Shop() {
|
|||||||
</button>
|
</button>
|
||||||
)
|
)
|
||||||
) : (
|
) : (
|
||||||
<span className="wx-muted">—</span>
|
<div className="wx-row-actions">
|
||||||
|
{o.status !== 'refunded' && o.status !== 'cancelled' ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="wx-btn-sm danger"
|
||||||
|
disabled={busy}
|
||||||
|
onClick={() => void markShopStatus(o.id, 'refunded')}
|
||||||
|
>
|
||||||
|
标退款
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
<span className="wx-muted">{o.status}</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
|||||||
338
apps/admin/src/pages/Social.tsx
Normal file
338
apps/admin/src/pages/Social.tsx
Normal file
@ -0,0 +1,338 @@
|
|||||||
|
/**
|
||||||
|
* 游民社区运营 — 页面 / 区块 / 功能 / 按钮 / 文案
|
||||||
|
* 深合并 remote-config,不碰订单与业务库。
|
||||||
|
*/
|
||||||
|
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||||
|
import { Link } from 'react-router-dom'
|
||||||
|
import { api } from '../api'
|
||||||
|
import { WxToast } from '../components/wxUi'
|
||||||
|
import './Vip.css'
|
||||||
|
import './switches.css'
|
||||||
|
|
||||||
|
type FlagGroup = 'pages' | 'sections' | 'features' | 'buttons'
|
||||||
|
type TabKey = 'pages' | 'sections' | 'features' | 'buttons' | 'copy'
|
||||||
|
|
||||||
|
type SocialOps = {
|
||||||
|
moduleEnabled: boolean
|
||||||
|
moduleTitle: string
|
||||||
|
flags: Record<FlagGroup, Record<string, boolean>>
|
||||||
|
copy: Record<string, string>
|
||||||
|
pageCopy: Record<string, { eyebrow?: string; title?: string; accent?: string; description?: string }>
|
||||||
|
meta: {
|
||||||
|
pages: Record<string, [string, string]>
|
||||||
|
sections: Record<string, string>
|
||||||
|
features: Record<string, string>
|
||||||
|
buttons: Record<string, string>
|
||||||
|
}
|
||||||
|
version?: number
|
||||||
|
updatedAt?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
const TABS: Array<{ key: TabKey; label: string }> = [
|
||||||
|
{ key: 'pages', label: '子页面' },
|
||||||
|
{ key: 'sections', label: '首页区块' },
|
||||||
|
{ key: 'features', label: '功能' },
|
||||||
|
{ key: 'buttons', label: '按钮' },
|
||||||
|
{ key: 'copy', label: '文案' },
|
||||||
|
]
|
||||||
|
|
||||||
|
const COPY_LABELS: Record<string, string> = {
|
||||||
|
socialEyebrow: '首屏眉题',
|
||||||
|
socialHeroLine1: '标题首行',
|
||||||
|
socialHeroAccent: '标题强调词',
|
||||||
|
socialHeroLead: '首屏导语',
|
||||||
|
socialJoinCta: '主按钮文案',
|
||||||
|
socialInviteTitle: '底部邀请标题',
|
||||||
|
socialInviteLead: '底部邀请说明',
|
||||||
|
socialOnlineTitle: '线上入口标题',
|
||||||
|
socialOfflineTitle: '线下入口标题',
|
||||||
|
socialTeamTitle: '共创入口标题',
|
||||||
|
socialWayGroup: '方式 · 群聊',
|
||||||
|
socialWayChat: '方式 · 视频',
|
||||||
|
socialWayDate: '方式 · 认识',
|
||||||
|
socialWayCafe: '方式 · 同城',
|
||||||
|
socialWayTeam: '方式 · 共创',
|
||||||
|
socialPromoUrl: '宣传片 URL(空=默认)',
|
||||||
|
}
|
||||||
|
|
||||||
|
function Switch({
|
||||||
|
checked,
|
||||||
|
onChange,
|
||||||
|
label,
|
||||||
|
disabled,
|
||||||
|
}: {
|
||||||
|
checked: boolean
|
||||||
|
onChange: (v: boolean) => void
|
||||||
|
label: string
|
||||||
|
disabled?: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<label className="vip-switch" title={label}>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={checked}
|
||||||
|
disabled={disabled}
|
||||||
|
onChange={(e) => onChange(e.target.checked)}
|
||||||
|
aria-label={label}
|
||||||
|
/>
|
||||||
|
<span className="vip-switch-track">
|
||||||
|
<span className="vip-switch-thumb" />
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function Social() {
|
||||||
|
const [cfg, setCfg] = useState<SocialOps | null>(null)
|
||||||
|
const [busy, setBusy] = useState(false)
|
||||||
|
const [msg, setMsg] = useState('')
|
||||||
|
const [err, setErr] = useState('')
|
||||||
|
const [tab, setTab] = useState<TabKey>('pages')
|
||||||
|
const [draftCopy, setDraftCopy] = useState<Record<string, string>>({})
|
||||||
|
|
||||||
|
const load = useCallback(async () => {
|
||||||
|
setErr('')
|
||||||
|
const data = await api<SocialOps>('/api/admin/weapp/social')
|
||||||
|
setCfg(data)
|
||||||
|
setDraftCopy(data.copy || {})
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
load().catch((e) => setErr(e.message || '加载失败'))
|
||||||
|
}, [load])
|
||||||
|
|
||||||
|
async function patch(body: Record<string, unknown>, okHint: string) {
|
||||||
|
setBusy(true)
|
||||||
|
setMsg('')
|
||||||
|
setErr('')
|
||||||
|
try {
|
||||||
|
const data = await api<SocialOps>('/api/admin/weapp/social', {
|
||||||
|
method: 'PUT',
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
})
|
||||||
|
setCfg(data)
|
||||||
|
setDraftCopy(data.copy || {})
|
||||||
|
setMsg(okHint)
|
||||||
|
} catch (e: any) {
|
||||||
|
setErr(e.message || '保存失败')
|
||||||
|
await load().catch(() => undefined)
|
||||||
|
} finally {
|
||||||
|
setBusy(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const onCount = useMemo(() => {
|
||||||
|
if (!cfg) return { pages: 0, features: 0 }
|
||||||
|
const pages = Object.values(cfg.flags.pages || {}).filter(Boolean).length
|
||||||
|
const features = Object.values(cfg.flags.features || {}).filter(Boolean).length
|
||||||
|
return { pages, features }
|
||||||
|
}, [cfg])
|
||||||
|
|
||||||
|
if (!cfg) {
|
||||||
|
return (
|
||||||
|
<div className="wx-page sw-page">
|
||||||
|
<div className="sw-hero">
|
||||||
|
<h1>游民社区</h1>
|
||||||
|
<p className="sw-hero-lead">加载运营配置…</p>
|
||||||
|
</div>
|
||||||
|
{err ? (
|
||||||
|
<div className="sw-toast">
|
||||||
|
<WxToast tone="err">{err}</WxToast>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const renderFlagGrid = (group: FlagGroup) => {
|
||||||
|
const meta =
|
||||||
|
group === 'pages'
|
||||||
|
? cfg.meta.pages
|
||||||
|
: group === 'sections'
|
||||||
|
? cfg.meta.sections
|
||||||
|
: group === 'features'
|
||||||
|
? cfg.meta.features
|
||||||
|
: cfg.meta.buttons
|
||||||
|
const flags = cfg.flags[group] || {}
|
||||||
|
return (
|
||||||
|
<div className="sw-grid">
|
||||||
|
{Object.keys(meta).map((key) => {
|
||||||
|
const on = flags[key] !== false
|
||||||
|
const label =
|
||||||
|
group === 'pages'
|
||||||
|
? (meta as Record<string, [string, string]>)[key]?.[0] || key
|
||||||
|
: (meta as Record<string, string>)[key] || key
|
||||||
|
const desc =
|
||||||
|
group === 'pages'
|
||||||
|
? (meta as Record<string, [string, string]>)[key]?.[1] || key
|
||||||
|
: key
|
||||||
|
return (
|
||||||
|
<article key={key} className={`sw-mod${on ? ' is-on' : ' is-off'}`}>
|
||||||
|
<div className="sw-mod-top">
|
||||||
|
<div className="sw-mod-ico" aria-hidden>
|
||||||
|
{on ? '●' : '○'}
|
||||||
|
</div>
|
||||||
|
<Switch
|
||||||
|
checked={on}
|
||||||
|
disabled={busy}
|
||||||
|
label={label}
|
||||||
|
onChange={(v) =>
|
||||||
|
void patch(
|
||||||
|
{ flags: { [group]: { [key]: v } } },
|
||||||
|
`${label}已${v ? '开启' : '关闭'}`,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<h3>{label}</h3>
|
||||||
|
<p>{desc}</p>
|
||||||
|
<div className="sw-mod-foot">
|
||||||
|
<span className={`sw-status ${on ? 'on' : 'off'}`}>{on ? 'ON' : 'OFF'}</span>
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="wx-page sw-page">
|
||||||
|
<header className="sw-hero">
|
||||||
|
<div className="sw-hero-top">
|
||||||
|
<div>
|
||||||
|
<div className="sw-kicker">
|
||||||
|
<span className="sw-kicker-dot" />
|
||||||
|
Social Ops · 约 3s 热更新
|
||||||
|
</div>
|
||||||
|
<h1>游民社区运营</h1>
|
||||||
|
<p className="sw-hero-lead">
|
||||||
|
控制 pages/social 全部子页、首页区块、功能模块、按钮与文案。只深合并 remote-config,不写订单库。
|
||||||
|
</p>
|
||||||
|
<div className="sw-hero-meta">
|
||||||
|
<span className="sw-pill">
|
||||||
|
版本 <strong>v{cfg.version ?? '-'}</strong>
|
||||||
|
</span>
|
||||||
|
<span className="sw-pill is-ok">
|
||||||
|
子页开 <strong>{onCount.pages}</strong>
|
||||||
|
</span>
|
||||||
|
<span className="sw-pill">
|
||||||
|
功能开 <strong>{onCount.features}</strong>
|
||||||
|
</span>
|
||||||
|
<Link className="sw-pill" to="/wechat/social/data">
|
||||||
|
UGC 数据 →
|
||||||
|
</Link>
|
||||||
|
<Link className="sw-pill" to="/wechat/switches">
|
||||||
|
总开关 →
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<article className={`sw-mod${cfg.moduleEnabled ? ' is-on' : ' is-off'}`} style={{ minWidth: 220 }}>
|
||||||
|
<div className="sw-mod-top">
|
||||||
|
<div className="sw-mod-ico" aria-hidden>
|
||||||
|
💕
|
||||||
|
</div>
|
||||||
|
<Switch
|
||||||
|
checked={cfg.moduleEnabled}
|
||||||
|
disabled={busy}
|
||||||
|
label="总模块"
|
||||||
|
onChange={(v) =>
|
||||||
|
void patch(
|
||||||
|
{ moduleEnabled: v },
|
||||||
|
v ? '游民社区总模块已开启' : '游民社区总模块已关闭',
|
||||||
|
)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<h3>{cfg.moduleTitle || '游民社区'}</h3>
|
||||||
|
<p>modules.social · 关则首页入口与分包拦截</p>
|
||||||
|
</article>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
{msg ? (
|
||||||
|
<div className="sw-toast">
|
||||||
|
<WxToast tone="ok">{msg}</WxToast>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
{err ? (
|
||||||
|
<div className="sw-toast">
|
||||||
|
<WxToast tone="err">{err}</WxToast>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<nav className="sw-tabs" aria-label="社区运营分类">
|
||||||
|
{TABS.map((t) => (
|
||||||
|
<button
|
||||||
|
key={t.key}
|
||||||
|
type="button"
|
||||||
|
className={`sw-tab${tab === t.key ? ' is-on' : ''}`}
|
||||||
|
onClick={() => setTab(t.key)}
|
||||||
|
>
|
||||||
|
{t.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
{tab !== 'copy' ? (
|
||||||
|
<section className="sw-panel is-on">
|
||||||
|
<div className="sw-section-head">
|
||||||
|
<h2>
|
||||||
|
{tab === 'pages'
|
||||||
|
? '子页面'
|
||||||
|
: tab === 'sections'
|
||||||
|
? '首页区块'
|
||||||
|
: tab === 'features'
|
||||||
|
? '功能模块'
|
||||||
|
: '按钮'}
|
||||||
|
</h2>
|
||||||
|
<p>关闭后对应入口/组件隐藏或拦截;缺省全开,兼容旧配置</p>
|
||||||
|
</div>
|
||||||
|
{renderFlagGrid(tab)}
|
||||||
|
</section>
|
||||||
|
) : (
|
||||||
|
<section className="sw-panel is-on">
|
||||||
|
<div className="sw-section-head">
|
||||||
|
<h2>落地文案</h2>
|
||||||
|
<p>覆盖包内 SOCIAL_COPY;留空保存会写入空串(客户端会回退种子)</p>
|
||||||
|
</div>
|
||||||
|
<div className="sw-grid" style={{ gridTemplateColumns: '1fr' }}>
|
||||||
|
{Object.keys(COPY_LABELS).map((key) => (
|
||||||
|
<label key={key} className="sw-mod" style={{ display: 'block' }}>
|
||||||
|
<span className="sw-mod-foot">{COPY_LABELS[key]} · {key}</span>
|
||||||
|
{key === 'socialHeroLead' ? (
|
||||||
|
<textarea
|
||||||
|
className="wx-input"
|
||||||
|
rows={4}
|
||||||
|
style={{ width: '100%', marginTop: 8 }}
|
||||||
|
value={draftCopy[key] ?? ''}
|
||||||
|
disabled={busy}
|
||||||
|
onChange={(e) => setDraftCopy((c) => ({ ...c, [key]: e.target.value }))}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<input
|
||||||
|
className="wx-input"
|
||||||
|
style={{ width: '100%', marginTop: 8 }}
|
||||||
|
value={draftCopy[key] ?? ''}
|
||||||
|
disabled={busy}
|
||||||
|
onChange={(e) => setDraftCopy((c) => ({ ...c, [key]: e.target.value }))}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<div style={{ marginTop: 16 }}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="wx-btn"
|
||||||
|
disabled={busy}
|
||||||
|
onClick={() => void patch({ copy: draftCopy }, '文案已保存')}
|
||||||
|
>
|
||||||
|
{busy ? '保存中…' : '保存文案'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
478
apps/admin/src/pages/SocialData.tsx
Normal file
478
apps/admin/src/pages/SocialData.tsx
Normal file
@ -0,0 +1,478 @@
|
|||||||
|
/**
|
||||||
|
* 游民社区 · UGC 数据台
|
||||||
|
* messages / roster / reviews / gig-apps / feedback + catalogs JSON
|
||||||
|
*/
|
||||||
|
import { useCallback, useEffect, useState } from 'react'
|
||||||
|
import { Link } from 'react-router-dom'
|
||||||
|
import { api } from '../api'
|
||||||
|
import { WxEmpty, WxHead, WxTabs, WxToast } from '../components/wxUi'
|
||||||
|
|
||||||
|
type Tab = 'messages' | 'roster' | 'reviews' | 'gigApps' | 'feedback' | 'catalog'
|
||||||
|
|
||||||
|
type Overview = {
|
||||||
|
ok: boolean
|
||||||
|
path?: string
|
||||||
|
exists?: boolean
|
||||||
|
writable?: boolean
|
||||||
|
counts?: Record<string, number>
|
||||||
|
error?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
type ListResp = { ok: boolean; total: number; items: any[] }
|
||||||
|
|
||||||
|
const TABS: Array<{ key: Tab; label: string }> = [
|
||||||
|
{ key: 'messages', label: '大厅消息' },
|
||||||
|
{ key: 'roster', label: '成员介绍' },
|
||||||
|
{ key: 'reviews', label: '咖啡馆评价' },
|
||||||
|
{ key: 'gigApps', label: '共创报名' },
|
||||||
|
{ key: 'feedback', label: '反馈' },
|
||||||
|
{ key: 'catalog', label: '目录配置' },
|
||||||
|
]
|
||||||
|
|
||||||
|
const ENDPOINTS: Record<Exclude<Tab, 'catalog'>, string> = {
|
||||||
|
messages: '/api/admin/social/ugc/messages',
|
||||||
|
roster: '/api/admin/social/ugc/roster',
|
||||||
|
reviews: '/api/admin/social/ugc/reviews',
|
||||||
|
gigApps: '/api/admin/social/ugc/gig-apps',
|
||||||
|
feedback: '/api/admin/social/ugc/feedback',
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function SocialData() {
|
||||||
|
const [tab, setTab] = useState<Tab>('messages')
|
||||||
|
const [overview, setOverview] = useState<Overview | null>(null)
|
||||||
|
const [items, setItems] = useState<any[]>([])
|
||||||
|
const [total, setTotal] = useState(0)
|
||||||
|
const [q, setQ] = useState('')
|
||||||
|
const [loading, setLoading] = useState(true)
|
||||||
|
const [busy, setBusy] = useState(false)
|
||||||
|
const [err, setErr] = useState('')
|
||||||
|
const [msg, setMsg] = useState('')
|
||||||
|
const [catalogJson, setCatalogJson] = useState('')
|
||||||
|
const [editRoster, setEditRoster] = useState<any | null>(null)
|
||||||
|
|
||||||
|
const loadOverview = useCallback(async () => {
|
||||||
|
const data = await api<Overview>('/api/admin/social/ugc/overview')
|
||||||
|
setOverview(data)
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const loadList = useCallback(async () => {
|
||||||
|
setLoading(true)
|
||||||
|
setErr('')
|
||||||
|
try {
|
||||||
|
if (tab === 'catalog') {
|
||||||
|
const data = await api<{ catalogs: Record<string, unknown> }>(
|
||||||
|
'/api/admin/social/ugc/catalog',
|
||||||
|
)
|
||||||
|
setCatalogJson(JSON.stringify(data.catalogs || {}, null, 2))
|
||||||
|
setItems([])
|
||||||
|
setTotal(0)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const qs = new URLSearchParams()
|
||||||
|
if (q.trim()) qs.set('q', q.trim())
|
||||||
|
qs.set('limit', '100')
|
||||||
|
const data = await api<ListResp>(`${ENDPOINTS[tab]}?${qs}`)
|
||||||
|
setItems(data.items || [])
|
||||||
|
setTotal(data.total || 0)
|
||||||
|
} catch (e: any) {
|
||||||
|
setErr(e.message || '加载失败')
|
||||||
|
setItems([])
|
||||||
|
setTotal(0)
|
||||||
|
} finally {
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
}, [tab, q])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
loadOverview().catch((e) => setErr(e.message || '概览失败'))
|
||||||
|
}, [loadOverview])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void loadList()
|
||||||
|
}, [loadList])
|
||||||
|
|
||||||
|
async function remove(kind: Tab, id: string) {
|
||||||
|
if (!confirm('确认删除?不可恢复')) return
|
||||||
|
setBusy(true)
|
||||||
|
setMsg('')
|
||||||
|
setErr('')
|
||||||
|
try {
|
||||||
|
const map: Record<string, string> = {
|
||||||
|
messages: `/api/admin/social/ugc/messages/${id}`,
|
||||||
|
roster: `/api/admin/social/ugc/roster/${id}`,
|
||||||
|
reviews: `/api/admin/social/ugc/reviews/${id}`,
|
||||||
|
gigApps: `/api/admin/social/ugc/gig-apps/${id}`,
|
||||||
|
feedback: `/api/admin/social/ugc/feedback/${id}`,
|
||||||
|
}
|
||||||
|
await api(map[kind], { method: 'DELETE' })
|
||||||
|
setMsg('已删除')
|
||||||
|
await loadList()
|
||||||
|
await loadOverview()
|
||||||
|
} catch (e: any) {
|
||||||
|
setErr(e.message || '删除失败')
|
||||||
|
} finally {
|
||||||
|
setBusy(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveRoster() {
|
||||||
|
if (!editRoster?.guestId) return
|
||||||
|
setBusy(true)
|
||||||
|
setErr('')
|
||||||
|
try {
|
||||||
|
await api(`/api/admin/social/ugc/roster/${editRoster.guestId}`, {
|
||||||
|
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()
|
||||||
|
} catch (e: any) {
|
||||||
|
setErr(e.message || '保存失败')
|
||||||
|
} finally {
|
||||||
|
setBusy(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveCatalog() {
|
||||||
|
setBusy(true)
|
||||||
|
setErr('')
|
||||||
|
setMsg('')
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(catalogJson)
|
||||||
|
await api('/api/admin/social/ugc/catalog', {
|
||||||
|
method: 'PUT',
|
||||||
|
body: JSON.stringify(parsed),
|
||||||
|
})
|
||||||
|
setMsg('目录已保存(remote-config 深合并)')
|
||||||
|
await loadList()
|
||||||
|
} catch (e: any) {
|
||||||
|
setErr(e.message || '目录保存失败(检查 JSON)')
|
||||||
|
} finally {
|
||||||
|
setBusy(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const counts = overview?.counts || {}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="wx-page">
|
||||||
|
<WxHead
|
||||||
|
eyebrow="游民社区"
|
||||||
|
title="UGC 数据台"
|
||||||
|
desc="大厅消息、成员介绍、评价、共创报名与反馈;目录配置写入 remote-config.socialCatalogs。"
|
||||||
|
>
|
||||||
|
<Link className="wx-btn wx-btn-ghost" to="/wechat/social">
|
||||||
|
开关 / 文案
|
||||||
|
</Link>
|
||||||
|
<button type="button" className="wx-btn" onClick={() => void loadList()} disabled={loading}>
|
||||||
|
{loading ? '刷新中…' : '刷新'}
|
||||||
|
</button>
|
||||||
|
</WxHead>
|
||||||
|
|
||||||
|
{err ? (
|
||||||
|
<WxToast kind="err" onClose={() => setErr('')}>
|
||||||
|
{err}
|
||||||
|
</WxToast>
|
||||||
|
) : null}
|
||||||
|
{msg ? (
|
||||||
|
<WxToast kind="ok" onClose={() => setMsg('')}>
|
||||||
|
{msg}
|
||||||
|
</WxToast>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<div className="wx-stats">
|
||||||
|
{[
|
||||||
|
['messages', '消息', counts.messages],
|
||||||
|
['roster', '介绍', counts.roster],
|
||||||
|
['reviews', '评价', counts.reviews],
|
||||||
|
['gigApps', '报名', counts.gigApps],
|
||||||
|
['feedback', '反馈', counts.feedback],
|
||||||
|
].map(([k, label, n]) => (
|
||||||
|
<button
|
||||||
|
key={k}
|
||||||
|
type="button"
|
||||||
|
className="wx-stat"
|
||||||
|
onClick={() => setTab(k as Tab)}
|
||||||
|
>
|
||||||
|
<div className="wx-stat-val">{n ?? '—'}</div>
|
||||||
|
<div className="wx-stat-label">{label}</div>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{overview ? (
|
||||||
|
<p className="wx-muted" style={{ margin: '0 0 12px', fontSize: 13 }}>
|
||||||
|
DB: {overview.path || '—'} · {overview.exists ? '已挂载' : '缺失'} ·{' '}
|
||||||
|
{overview.writable ? '可写' : '只读'}
|
||||||
|
{overview.error ? ` · ${overview.error}` : ''}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<WxTabs value={tab} onChange={setTab} items={TABS.map((t) => ({ key: t.key, label: t.label }))} />
|
||||||
|
|
||||||
|
{tab !== 'catalog' ? (
|
||||||
|
<div className="wx-toolbar">
|
||||||
|
<input
|
||||||
|
type="search"
|
||||||
|
value={q}
|
||||||
|
placeholder="搜索…"
|
||||||
|
onChange={(e) => setQ(e.target.value)}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === 'Enter') void loadList()
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<button type="button" className="wx-btn wx-btn-ghost" onClick={() => void loadList()}>
|
||||||
|
搜索
|
||||||
|
</button>
|
||||||
|
<span className="wx-muted" style={{ fontSize: 13 }}>
|
||||||
|
共 {total} 条
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{tab === 'catalog' ? (
|
||||||
|
<div className="wx-panel">
|
||||||
|
<div className="wx-panel-head">
|
||||||
|
<div>
|
||||||
|
<h2>socialCatalogs</h2>
|
||||||
|
<p>meetups / gigs / cafes / roster / ebooks / videos(JSON 数组)</p>
|
||||||
|
</div>
|
||||||
|
<button type="button" className="wx-btn" disabled={busy} onClick={() => void saveCatalog()}>
|
||||||
|
保存目录
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<textarea
|
||||||
|
className="wx-code"
|
||||||
|
rows={22}
|
||||||
|
value={catalogJson}
|
||||||
|
onChange={(e) => setCatalogJson(e.target.value)}
|
||||||
|
spellCheck={false}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="wx-table-wrap">
|
||||||
|
{items.length ? (
|
||||||
|
<table className="wx-table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
{tab === 'messages' ? (
|
||||||
|
<>
|
||||||
|
<th>频道</th>
|
||||||
|
<th>作者</th>
|
||||||
|
<th>内容</th>
|
||||||
|
<th>时间</th>
|
||||||
|
<th>操作</th>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
{tab === 'roster' ? (
|
||||||
|
<>
|
||||||
|
<th>昵称</th>
|
||||||
|
<th>城市 / 职业</th>
|
||||||
|
<th>介绍</th>
|
||||||
|
<th>更新</th>
|
||||||
|
<th>操作</th>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
{tab === 'reviews' ? (
|
||||||
|
<>
|
||||||
|
<th>咖啡馆</th>
|
||||||
|
<th>评分</th>
|
||||||
|
<th>评价</th>
|
||||||
|
<th>时间</th>
|
||||||
|
<th>操作</th>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
{tab === 'gigApps' ? (
|
||||||
|
<>
|
||||||
|
<th>机会</th>
|
||||||
|
<th>姓名</th>
|
||||||
|
<th>联系 / 备注</th>
|
||||||
|
<th>时间</th>
|
||||||
|
<th>操作</th>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
{tab === 'feedback' ? (
|
||||||
|
<>
|
||||||
|
<th>类型</th>
|
||||||
|
<th>内容</th>
|
||||||
|
<th>联系</th>
|
||||||
|
<th>时间</th>
|
||||||
|
<th>操作</th>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{items.map((it) => {
|
||||||
|
if (tab === 'messages') {
|
||||||
|
return (
|
||||||
|
<tr key={it.id}>
|
||||||
|
<td className="wx-mono">{it.channelId}</td>
|
||||||
|
<td>{it.author}</td>
|
||||||
|
<td>{(it.text || '').slice(0, 120)}</td>
|
||||||
|
<td>{it.at}</td>
|
||||||
|
<td>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="wx-btn-sm danger"
|
||||||
|
disabled={busy}
|
||||||
|
onClick={() => void remove('messages', it.id)}
|
||||||
|
>
|
||||||
|
删除
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (tab === 'roster') {
|
||||||
|
return (
|
||||||
|
<tr key={it.guestId}>
|
||||||
|
<td>
|
||||||
|
<strong>{it.name}</strong>
|
||||||
|
<div className="wx-mono" style={{ opacity: 0.6, fontSize: 12 }}>
|
||||||
|
{it.guestId}
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
{it.city || '—'} · {it.title || '—'}
|
||||||
|
</td>
|
||||||
|
<td>{(it.bio || '').slice(0, 100)}</td>
|
||||||
|
<td>{it.updatedAt}</td>
|
||||||
|
<td>
|
||||||
|
<div className="wx-row-actions">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="wx-btn-sm"
|
||||||
|
onClick={() => setEditRoster({ ...it })}
|
||||||
|
>
|
||||||
|
编辑
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="wx-btn-sm danger"
|
||||||
|
disabled={busy}
|
||||||
|
onClick={() => void remove('roster', it.guestId)}
|
||||||
|
>
|
||||||
|
删除
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (tab === 'reviews') {
|
||||||
|
return (
|
||||||
|
<tr key={it.id}>
|
||||||
|
<td className="wx-mono">{it.cafeId}</td>
|
||||||
|
<td>{it.score}★</td>
|
||||||
|
<td>
|
||||||
|
<strong>{it.author}</strong> · {(it.text || '').slice(0, 100)}
|
||||||
|
</td>
|
||||||
|
<td>{it.at}</td>
|
||||||
|
<td>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="wx-btn-sm danger"
|
||||||
|
disabled={busy}
|
||||||
|
onClick={() => void remove('reviews', it.id)}
|
||||||
|
>
|
||||||
|
删除
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (tab === 'gigApps') {
|
||||||
|
return (
|
||||||
|
<tr key={it.id}>
|
||||||
|
<td className="wx-mono">{it.gigId}</td>
|
||||||
|
<td>{it.name}</td>
|
||||||
|
<td>
|
||||||
|
{it.contact}
|
||||||
|
<div style={{ opacity: 0.7 }}>{(it.note || '').slice(0, 80)}</div>
|
||||||
|
</td>
|
||||||
|
<td>{it.at}</td>
|
||||||
|
<td>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="wx-btn-sm danger"
|
||||||
|
disabled={busy}
|
||||||
|
onClick={() => void remove('gigApps', it.id)}
|
||||||
|
>
|
||||||
|
删除
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<tr key={it.id}>
|
||||||
|
<td>{it.kind}</td>
|
||||||
|
<td>{(it.text || '').slice(0, 140)}</td>
|
||||||
|
<td>{it.contact || '—'}</td>
|
||||||
|
<td>{it.at}</td>
|
||||||
|
<td>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="wx-btn-sm danger"
|
||||||
|
disabled={busy}
|
||||||
|
onClick={() => void remove('feedback', it.id)}
|
||||||
|
>
|
||||||
|
删除
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
) : (
|
||||||
|
<WxEmpty title={loading ? '加载中…' : '暂无数据'} />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{editRoster ? (
|
||||||
|
<div className="wx-modal-mask" onClick={() => setEditRoster(null)}>
|
||||||
|
<div className="wx-modal" onClick={(e) => e.stopPropagation()}>
|
||||||
|
<h3>编辑介绍 · {editRoster.guestId}</h3>
|
||||||
|
{(['name', 'title', 'city', 'phone', 'linktree', 'skills'] as const).map((k) => (
|
||||||
|
<label key={k} className="wx-field">
|
||||||
|
<span>{k}</span>
|
||||||
|
<input
|
||||||
|
value={editRoster[k] || ''}
|
||||||
|
onChange={(e) => setEditRoster({ ...editRoster, [k]: e.target.value })}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
<label className="wx-field">
|
||||||
|
<span>bio</span>
|
||||||
|
<textarea
|
||||||
|
rows={5}
|
||||||
|
value={editRoster.bio || ''}
|
||||||
|
onChange={(e) => setEditRoster({ ...editRoster, bio: e.target.value })}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<div className="wx-row-actions">
|
||||||
|
<button type="button" className="wx-btn wx-btn-ghost" onClick={() => setEditRoster(null)}>
|
||||||
|
取消
|
||||||
|
</button>
|
||||||
|
<button type="button" className="wx-btn" disabled={busy} onClick={() => void saveRoster()}>
|
||||||
|
保存
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@ -1,6 +1,6 @@
|
|||||||
/**
|
/**
|
||||||
* 微信后台「开关」— 页面 / 入口 / 文案
|
* 微信后台「开关」— 页面 / 入口 / 文案
|
||||||
* 近实时写入 remote-config,小程序约 3s 热更新。
|
* 近实时写入 remote-config,小程序约 2s meta 轮询热更新。
|
||||||
* 数字游民小册审核在 VIP → 电子书 → 数字游民。
|
* 数字游民小册审核在 VIP → 电子书 → 数字游民。
|
||||||
*/
|
*/
|
||||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||||
@ -58,6 +58,12 @@ const PAGE_MODS: Array<{ key: string; label: string; ico: string; desc: string }
|
|||||||
{ key: 'nav', label: '出海导航', ico: '🧭', desc: '导航页 / Tab' },
|
{ key: 'nav', label: '出海导航', ico: '🧭', desc: '导航页 / Tab' },
|
||||||
{ key: 'book', label: '数字游民小册', ico: '📕', desc: '小册 Tab → 正式读 nomad' },
|
{ key: 'book', label: '数字游民小册', ico: '📕', desc: '小册 Tab → 正式读 nomad' },
|
||||||
{ key: 'community', label: '旅居社群', ico: '🏕️', desc: '社群入口' },
|
{ key: 'community', label: '旅居社群', ico: '🏕️', desc: '社群入口' },
|
||||||
|
{
|
||||||
|
key: 'social',
|
||||||
|
label: '游民社区',
|
||||||
|
ico: '💕',
|
||||||
|
desc: 'pages/social/index · 大厅聊天 / 认识 / 视频厅;关则首页入口与分包页拦截',
|
||||||
|
},
|
||||||
{ key: 'vip', label: 'VIP 中心', ico: '👑', desc: '会员落地页;关闭后「加群」改弹公众号' },
|
{ key: 'vip', label: 'VIP 中心', ico: '👑', desc: '会员落地页;关闭后「加群」改弹公众号' },
|
||||||
{ key: 'destinations', label: '目的地', ico: '📍', desc: '目的地列表' },
|
{ key: 'destinations', label: '目的地', ico: '📍', desc: '目的地列表' },
|
||||||
{ key: 'meetups', label: '活动', ico: '📅', desc: '活动入口' },
|
{ key: 'meetups', label: '活动', ico: '📅', desc: '活动入口' },
|
||||||
@ -217,7 +223,7 @@ export default function Switches() {
|
|||||||
<section className={`sw-panel${tab === 'pages' ? ' is-on' : ''}`}>
|
<section className={`sw-panel${tab === 'pages' ? ' is-on' : ''}`}>
|
||||||
<div className="sw-section-head">
|
<div className="sw-section-head">
|
||||||
<h2>页面模块</h2>
|
<h2>页面模块</h2>
|
||||||
<p>关闭后小程序对应页拦截,约 3 秒生效</p>
|
<p>关闭后小程序对应页拦截;微信端 WebSocket + 每秒 POST 全量同步</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="sw-grid">
|
<div className="sw-grid">
|
||||||
{PAGE_MODS.map((m) => {
|
{PAGE_MODS.map((m) => {
|
||||||
|
|||||||
@ -1449,6 +1449,141 @@ a.wx-stat:hover .wx-stat-go {
|
|||||||
color: var(--wx-muted);
|
color: var(--wx-muted);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.wx-chart-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
gap: 14px;
|
||||||
|
margin: 0 0 18px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wx-chart {
|
||||||
|
background: var(--wx-panel);
|
||||||
|
border: 1px solid var(--wx-line);
|
||||||
|
border-radius: var(--wx-radius);
|
||||||
|
padding: 14px 14px 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wx-chart-head {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 12px;
|
||||||
|
align-items: baseline;
|
||||||
|
margin-bottom: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wx-chart-head strong {
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wx-chart-sub,
|
||||||
|
.wx-chart-max {
|
||||||
|
display: block;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--wx-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.wx-chart-svg {
|
||||||
|
width: 100%;
|
||||||
|
height: auto;
|
||||||
|
color: var(--wx-faint);
|
||||||
|
}
|
||||||
|
|
||||||
|
.wx-rank {
|
||||||
|
list-style: none;
|
||||||
|
margin: 0;
|
||||||
|
padding: 4px 0 8px;
|
||||||
|
display: grid;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wx-rank-row {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 8px;
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wx-rank-name {
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wx-rank-n {
|
||||||
|
color: var(--wx-green-2);
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wx-rank-track {
|
||||||
|
height: 6px;
|
||||||
|
border-radius: 99px;
|
||||||
|
background: rgba(150, 210, 170, 0.12);
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wx-rank-track i {
|
||||||
|
display: block;
|
||||||
|
height: 100%;
|
||||||
|
background: linear-gradient(90deg, #5ec478, #d7b35a);
|
||||||
|
border-radius: 99px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wx-rank-empty {
|
||||||
|
color: var(--wx-muted);
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wx-code {
|
||||||
|
width: 100%;
|
||||||
|
min-height: 240px;
|
||||||
|
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
|
||||||
|
font-size: 12px;
|
||||||
|
line-height: 1.45;
|
||||||
|
color: var(--wx-text);
|
||||||
|
background: #0a120e;
|
||||||
|
border: 1px solid var(--wx-line);
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 12px;
|
||||||
|
resize: vertical;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wx-modal-mask {
|
||||||
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
|
z-index: 80;
|
||||||
|
background: rgba(0, 0, 0, 0.55);
|
||||||
|
display: grid;
|
||||||
|
place-items: center;
|
||||||
|
padding: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wx-modal {
|
||||||
|
width: min(520px, 100%);
|
||||||
|
max-height: min(88vh, 900px);
|
||||||
|
overflow: auto;
|
||||||
|
background: var(--wx-panel-solid);
|
||||||
|
border: 1px solid var(--wx-line-strong);
|
||||||
|
border-radius: 16px;
|
||||||
|
padding: 18px;
|
||||||
|
display: grid;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wx-modal-lg {
|
||||||
|
width: min(720px, 100%);
|
||||||
|
}
|
||||||
|
|
||||||
|
.wx-modal h3 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 980px) {
|
||||||
|
.wx-chart-grid {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@media (max-width: 720px) {
|
@media (max-width: 720px) {
|
||||||
.wx-form-grid {
|
.wx-form-grid {
|
||||||
grid-template-columns: 1fr;
|
grid-template-columns: 1fr;
|
||||||
|
|||||||
@ -8,11 +8,20 @@
|
|||||||
|
|
||||||
线上只读检查显示 `nomadro-social` 监听 8020、单进程运行且不支持热重载;`live.py` 的视频房间状态保存在进程内。为满足不影响现有业务的约束,本轮未执行直接重启、数据库同步或线上测试写入。发布须先处理活动视频房间的状态连续性,并保留旧版本与回滚路径;客户端可先构建验收,后端可选字段兼容现有请求。
|
线上只读检查显示 `nomadro-social` 监听 8020、单进程运行且不支持热重载;`live.py` 的视频房间状态保存在进程内。为满足不影响现有业务的约束,本轮未执行直接重启、数据库同步或线上测试写入。发布须先处理活动视频房间的状态连续性,并保留旧版本与回滚路径;客户端可先构建验收,后端可选字段兼容现有请求。
|
||||||
|
|
||||||
## 2026-11-02:公开配置读取优化(未部署)
|
## 2026-11-02:公开配置读取优化(已部署 api.nomadro.cn)
|
||||||
|
|
||||||
`public_config_snapshot.py` 按文件修改时间、大小及 inode 复用 JSON 解析结果;文件变化立即重新读取。文件短暂缺失、写入未完成或 JSON 损坏时,保留同一路径最近一次有效快照;首次读取失败仍返回原有默认配置。路径变化不会复用旧路径数据。返回深拷贝防止调用方污染缓存,meta 遇到非法 version 返回 0,避免 500。
|
`public_config_snapshot.py` 按文件修改时间、大小及 inode 复用 JSON 解析结果;文件变化立即重新读取。
|
||||||
|
|
||||||
保持 `/api/config`、`/api/ebook/config` 及对应 `/meta` 的路由、响应结构、CORS 和 no-store 头兼容。此次改动只有文件读取和进程内缓存,没有数据库访问、迁移、配置写回或支付/订单/会员修改,尚未更新线上服务。
|
## 2026-11-02:远程配置严格实时(已部署 · tag `2026-11-02`)
|
||||||
|
|
||||||
|
| 通道 | 路径 | 客户端 |
|
||||||
|
|---|---|---|
|
||||||
|
| 全量拉取 | `POST /api/config/pull`(及 `POST /api/config`) | 微信避 GET 缓存 |
|
||||||
|
| SSE | `GET /api/config/stream` | H5 EventSource |
|
||||||
|
| WebSocket | `WS /api/config/ws` | 微信 `Taro.connectSocket` |
|
||||||
|
| meta | `GET /api/config/meta` | 版本探测兜底 |
|
||||||
|
|
||||||
|
后台写 `remote-config`(含 weapp 开关)立刻 `notify_config_written`;服务端另有读盘轮询。部署:`_push_config_realtime.py` · `_push_config_post.py` · `_fix_nginx_ws_ssl.py`。
|
||||||
|
|
||||||
隔离验证(仅临时 JSON 文件,不启动业务应用、不连接生产):
|
隔离验证(仅临时 JSON 文件,不启动业务应用、不连接生产):
|
||||||
|
|
||||||
|
|||||||
@ -42,6 +42,7 @@ from ebook_svc.routers import ( # noqa: E402
|
|||||||
vip_library_admin,
|
vip_library_admin,
|
||||||
vip_library_public,
|
vip_library_public,
|
||||||
weapp_switches_admin,
|
weapp_switches_admin,
|
||||||
|
social_ops_admin,
|
||||||
)
|
)
|
||||||
from community_svc.routers import ( # noqa: E402
|
from community_svc.routers import ( # noqa: E402
|
||||||
api as community_api,
|
api as community_api,
|
||||||
@ -143,6 +144,11 @@ app.include_router(vip_admin.router)
|
|||||||
app.include_router(vip_library_admin.router)
|
app.include_router(vip_library_admin.router)
|
||||||
app.include_router(vip_library_public.router)
|
app.include_router(vip_library_public.router)
|
||||||
app.include_router(weapp_switches_admin.router)
|
app.include_router(weapp_switches_admin.router)
|
||||||
|
app.include_router(social_ops_admin.router)
|
||||||
|
from ebook_svc.routers import social_ugc_admin, community_admin # noqa: E402
|
||||||
|
|
||||||
|
app.include_router(social_ugc_admin.router)
|
||||||
|
app.include_router(community_admin.router)
|
||||||
app.include_router(shop_admin.router)
|
app.include_router(shop_admin.router)
|
||||||
app.include_router(memo_admin.router)
|
app.include_router(memo_admin.router)
|
||||||
app.include_router(nav_admin.router)
|
app.include_router(nav_admin.router)
|
||||||
|
|||||||
@ -83,8 +83,14 @@ app.include_router(memo_admin.router)
|
|||||||
app.include_router(nav_admin.router)
|
app.include_router(nav_admin.router)
|
||||||
# 微信「开关」总控(页面/入口/文案/小册审核)
|
# 微信「开关」总控(页面/入口/文案/小册审核)
|
||||||
from ebook_svc.routers import weapp_switches_admin # noqa: E402
|
from ebook_svc.routers import weapp_switches_admin # noqa: E402
|
||||||
|
from ebook_svc.routers import social_ops_admin # noqa: E402
|
||||||
|
from ebook_svc.routers import social_ugc_admin # noqa: E402
|
||||||
|
from ebook_svc.routers import community_admin # noqa: E402
|
||||||
|
|
||||||
app.include_router(weapp_switches_admin.router)
|
app.include_router(weapp_switches_admin.router)
|
||||||
|
app.include_router(social_ops_admin.router)
|
||||||
|
app.include_router(social_ugc_admin.router)
|
||||||
|
app.include_router(community_admin.router)
|
||||||
# 公开远程配置(抖音真机:dyapi/api 合法域名 + 有效证书)
|
# 公开远程配置(抖音真机:dyapi/api 合法域名 + 有效证书)
|
||||||
app.include_router(public_config.router)
|
app.include_router(public_config.router)
|
||||||
|
|
||||||
|
|||||||
@ -10,10 +10,12 @@ from ebook_svc.core.security import create_admin_token, require_admin
|
|||||||
from ebook_svc.domains.books import apply_offer_key, is_book_free, match_offer, offer_public_list
|
from ebook_svc.domains.books import apply_offer_key, is_book_free, match_offer, offer_public_list
|
||||||
from ebook_svc.schemas.admin import (
|
from ebook_svc.schemas.admin import (
|
||||||
AdminLoginBody,
|
AdminLoginBody,
|
||||||
|
BookCreateBody,
|
||||||
BookPatch,
|
BookPatch,
|
||||||
ManualUnlockBody,
|
ManualUnlockBody,
|
||||||
MarkdownImportBody,
|
MarkdownImportBody,
|
||||||
OfferApplyBody,
|
OfferApplyBody,
|
||||||
|
OrderStatusBody,
|
||||||
RevokeUnlockBody,
|
RevokeUnlockBody,
|
||||||
UserPatchBody,
|
UserPatchBody,
|
||||||
)
|
)
|
||||||
@ -59,6 +61,34 @@ async def admin_books(_: str = Depends(require_admin)):
|
|||||||
return store.list_books()
|
return store.list_books()
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/books")
|
||||||
|
async def admin_create_book(body: BookCreateBody, _: str = Depends(require_admin)):
|
||||||
|
data = body.model_dump(exclude_none=True)
|
||||||
|
bid = str(data.pop("id", "") or "").strip()
|
||||||
|
if not bid:
|
||||||
|
raise HTTPException(400, "需要 id")
|
||||||
|
try:
|
||||||
|
book = store.create_book(bid, data)
|
||||||
|
except ValueError as e:
|
||||||
|
raise HTTPException(400, str(e)) from e
|
||||||
|
try:
|
||||||
|
await pb.upsert_book(book)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
offer = match_offer(book)
|
||||||
|
return {**book, "offer_key": offer["key"], "is_free": is_book_free(book)}
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/books/{book_id}")
|
||||||
|
async def admin_delete_book(book_id: str, _: str = Depends(require_admin)):
|
||||||
|
if book_id in {"default", "__vip__"}:
|
||||||
|
raise HTTPException(400, "系统书不可删除")
|
||||||
|
ok = store.delete_book(book_id)
|
||||||
|
if not ok:
|
||||||
|
raise HTTPException(404, "不存在")
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
@router.get("/books/{book_id}")
|
@router.get("/books/{book_id}")
|
||||||
async def admin_book(book_id: str, _: str = Depends(require_admin)):
|
async def admin_book(book_id: str, _: str = Depends(require_admin)):
|
||||||
book = store.get_book(book_id)
|
book = store.get_book(book_id)
|
||||||
@ -182,6 +212,19 @@ async def admin_orders(_: str = Depends(require_admin)):
|
|||||||
return store.list_orders()
|
return store.list_orders()
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/orders/{out_trade_no}/status")
|
||||||
|
async def admin_order_status(
|
||||||
|
out_trade_no: str, body: OrderStatusBody, _: str = Depends(require_admin)
|
||||||
|
):
|
||||||
|
try:
|
||||||
|
row = store.mark_order_status(out_trade_no, body.status)
|
||||||
|
except ValueError as e:
|
||||||
|
raise HTTPException(400, str(e)) from e
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(404, "订单不存在")
|
||||||
|
return {"ok": True, "order": row}
|
||||||
|
|
||||||
|
|
||||||
@router.post("/unlock")
|
@router.post("/unlock")
|
||||||
async def admin_manual_unlock(body: ManualUnlockBody, _: str = Depends(require_admin)):
|
async def admin_manual_unlock(body: ManualUnlockBody, _: str = Depends(require_admin)):
|
||||||
"""后台手动发货:小册 default / VIP __vip__ / 其它 book_id。"""
|
"""后台手动发货:小册 default / VIP __vip__ / 其它 book_id。"""
|
||||||
|
|||||||
179
apps/api/services/ebook_svc/routers/community_admin.py
Normal file
179
apps/api/services/ebook_svc/routers/community_admin.py
Normal file
@ -0,0 +1,179 @@
|
|||||||
|
"""门户社区运营 — meetups / discussions / gigs(JSON 兜底;有 community_svc 则走其 store)。"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
from copy import deepcopy
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
from ebook_svc.core.security import require_admin
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/admin/community", tags=["community-admin"])
|
||||||
|
|
||||||
|
_DEFAULT_PATH = Path(
|
||||||
|
os.getenv(
|
||||||
|
"COMMUNITY_STORE_PATH",
|
||||||
|
"/var/www/nomadro-data/community/community_store.json",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _seed() -> dict[str, Any]:
|
||||||
|
try:
|
||||||
|
from community_svc.data import community_data as cd # type: ignore
|
||||||
|
|
||||||
|
return {
|
||||||
|
"seeded": True,
|
||||||
|
"seed_version": 4,
|
||||||
|
"meetups": deepcopy(getattr(cd, "MEETUPS", []) or []),
|
||||||
|
"discussions": deepcopy(getattr(cd, "DISCUSSIONS", []) or []),
|
||||||
|
"gigs": deepcopy(getattr(cd, "GIGS", []) or []),
|
||||||
|
"meetup_rsvps": [],
|
||||||
|
"gig_applications": [],
|
||||||
|
"discussion_replies": [],
|
||||||
|
}
|
||||||
|
except Exception:
|
||||||
|
return {
|
||||||
|
"seeded": True,
|
||||||
|
"seed_version": 1,
|
||||||
|
"meetups": [],
|
||||||
|
"discussions": [],
|
||||||
|
"gigs": [],
|
||||||
|
"meetup_rsvps": [],
|
||||||
|
"gig_applications": [],
|
||||||
|
"discussion_replies": [],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _path() -> Path:
|
||||||
|
return Path(os.getenv("COMMUNITY_STORE_PATH", str(_DEFAULT_PATH))).resolve()
|
||||||
|
|
||||||
|
|
||||||
|
def _load() -> dict[str, Any]:
|
||||||
|
path = _path()
|
||||||
|
if path.is_file():
|
||||||
|
try:
|
||||||
|
data = json.loads(path.read_text(encoding="utf-8"))
|
||||||
|
if isinstance(data, dict):
|
||||||
|
return data
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
# try community_svc live store
|
||||||
|
try:
|
||||||
|
from community_svc.services import community_store as cs # type: ignore
|
||||||
|
|
||||||
|
return {
|
||||||
|
"ok": True,
|
||||||
|
"source": "community_svc",
|
||||||
|
"meetups": cs.list_meetups(upcoming=False),
|
||||||
|
"discussions": cs.list_discussions(),
|
||||||
|
"gigs": cs.list_gigs(),
|
||||||
|
"stats": cs.stats_overview(),
|
||||||
|
}
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return _seed()
|
||||||
|
|
||||||
|
|
||||||
|
def _save(data: dict[str, Any]) -> None:
|
||||||
|
path = _path()
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
data["updatedAt"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
||||||
|
path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/overview")
|
||||||
|
async def overview(_: str = Depends(require_admin)) -> dict[str, Any]:
|
||||||
|
data = _load()
|
||||||
|
if data.get("source") == "community_svc":
|
||||||
|
return {
|
||||||
|
"ok": True,
|
||||||
|
"source": "community_svc",
|
||||||
|
"path": str(_path()),
|
||||||
|
"stats": data.get("stats")
|
||||||
|
or {
|
||||||
|
"meetups": len(data.get("meetups") or []),
|
||||||
|
"discussions": len(data.get("discussions") or []),
|
||||||
|
"gigs": len(data.get("gigs") or []),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
"ok": True,
|
||||||
|
"source": "json",
|
||||||
|
"path": str(_path()),
|
||||||
|
"exists": _path().is_file(),
|
||||||
|
"stats": {
|
||||||
|
"meetups": len(data.get("meetups") or []),
|
||||||
|
"discussions": len(data.get("discussions") or []),
|
||||||
|
"gigs": len(data.get("gigs") or []),
|
||||||
|
"rsvps": len(data.get("meetup_rsvps") or []),
|
||||||
|
"gigApps": len(data.get("gig_applications") or []),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _list_key(key: str) -> list[dict[str, Any]]:
|
||||||
|
data = _load()
|
||||||
|
items = data.get(key)
|
||||||
|
return items if isinstance(items, list) else []
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{collection}")
|
||||||
|
async def list_collection(collection: str, _: str = Depends(require_admin)) -> dict[str, Any]:
|
||||||
|
if collection not in {"meetups", "discussions", "gigs", "meetup_rsvps", "gig_applications"}:
|
||||||
|
raise HTTPException(404, "unknown collection")
|
||||||
|
items = _list_key(collection)
|
||||||
|
return {"ok": True, "items": items, "total": len(items)}
|
||||||
|
|
||||||
|
|
||||||
|
class ItemBody(BaseModel):
|
||||||
|
item: dict[str, Any] = Field(default_factory=dict)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{collection}")
|
||||||
|
async def upsert_item(
|
||||||
|
collection: str, body: ItemBody, _: str = Depends(require_admin)
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
if collection not in {"meetups", "discussions", "gigs"}:
|
||||||
|
raise HTTPException(400, "仅支持 meetups/discussions/gigs 写入")
|
||||||
|
data = _load()
|
||||||
|
if data.get("source") == "community_svc":
|
||||||
|
raise HTTPException(501, "community_svc 在线写入请改用门户 API;本后台仅管 JSON 兜底库")
|
||||||
|
items = list(data.get(collection) or [])
|
||||||
|
item = dict(body.item or {})
|
||||||
|
iid = str(item.get("id") or "").strip() or f"{collection[:3]}_{uuid.uuid4().hex[:10]}"
|
||||||
|
item["id"] = iid
|
||||||
|
found = False
|
||||||
|
for i, old in enumerate(items):
|
||||||
|
if isinstance(old, dict) and str(old.get("id")) == iid:
|
||||||
|
items[i] = {**old, **item}
|
||||||
|
found = True
|
||||||
|
break
|
||||||
|
if not found:
|
||||||
|
items.insert(0, item)
|
||||||
|
data[collection] = items
|
||||||
|
_save(data)
|
||||||
|
return {"ok": True, "item": item}
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{collection}/{item_id}")
|
||||||
|
async def delete_item(
|
||||||
|
collection: str, item_id: str, _: str = Depends(require_admin)
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
if collection not in {"meetups", "discussions", "gigs", "meetup_rsvps", "gig_applications"}:
|
||||||
|
raise HTTPException(404, "unknown collection")
|
||||||
|
data = _load()
|
||||||
|
if data.get("source") == "community_svc":
|
||||||
|
raise HTTPException(501, "community_svc 在线删除请改用门户 API")
|
||||||
|
items = [x for x in (data.get(collection) or []) if not (isinstance(x, dict) and str(x.get("id")) == item_id)]
|
||||||
|
if len(items) == len(data.get(collection) or []):
|
||||||
|
raise HTTPException(404, "不存在")
|
||||||
|
data[collection] = items
|
||||||
|
_save(data)
|
||||||
|
return {"ok": True}
|
||||||
@ -119,6 +119,31 @@ async def admin_post(body: AdminPostBody, _: str = Depends(require_admin)) -> di
|
|||||||
return {"ok": True, "memo": memo}
|
return {"ok": True, "memo": memo}
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/memos/{memo_id}")
|
||||||
|
async def admin_update_memo(
|
||||||
|
memo_id: str, body: AdminPostBody, _: str = Depends(require_admin)
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
vis = body.visibility
|
||||||
|
if body.trial is True:
|
||||||
|
vis = "trial"
|
||||||
|
elif body.trial is False:
|
||||||
|
vis = "vip"
|
||||||
|
try:
|
||||||
|
memo = memo_store.update_memo(
|
||||||
|
memo_id,
|
||||||
|
content=body.content,
|
||||||
|
title=body.title,
|
||||||
|
nickname=body.nickname,
|
||||||
|
visibility=vis,
|
||||||
|
resources=body.resources,
|
||||||
|
)
|
||||||
|
except ValueError as e:
|
||||||
|
raise HTTPException(400, str(e)) from e
|
||||||
|
if not memo:
|
||||||
|
raise HTTPException(404, "不存在")
|
||||||
|
return {"ok": True, "memo": memo}
|
||||||
|
|
||||||
|
|
||||||
@router.delete("/memos/{memo_id}")
|
@router.delete("/memos/{memo_id}")
|
||||||
async def admin_delete(memo_id: str, _: str = Depends(require_admin)) -> dict[str, Any]:
|
async def admin_delete(memo_id: str, _: str = Depends(require_admin)) -> dict[str, Any]:
|
||||||
ok = memo_store.delete_memo(memo_id, admin=True)
|
ok = memo_store.delete_memo(memo_id, admin=True)
|
||||||
|
|||||||
@ -1,57 +1,143 @@
|
|||||||
"""公开远程配置 — 供抖音真机拉配置(合法域名 + 有效证书)。
|
"""公开远程配置 — 供抖音/微信真机拉配置(合法域名 + 有效证书)。
|
||||||
|
|
||||||
门户 nomadro.cn 证书与主机名不匹配,真机会 TLS 失败;
|
门户 nomadro.cn 证书与主机名不匹配,真机会 TLS 失败;
|
||||||
开发者工具不校验证书所以看起来正常。
|
开发者工具不校验证书所以看起来正常。
|
||||||
走 dyapi.nomadro.cn / api.nomadro.cn(已在 request 合法域名且证书 OK)。
|
走 dyapi.nomadro.cn / api.nomadro.cn(已在 request 合法域名且证书 OK)。
|
||||||
|
|
||||||
|
实时通道:
|
||||||
|
- GET /api/config/stream → SSE(H5 / 门户 EventSource)
|
||||||
|
- WS /api/config/ws → WebSocket(微信小程序 Taro.connectSocket)
|
||||||
|
- GET /api/config/meta → 轮询兜底
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from fastapi import APIRouter
|
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
|
||||||
from fastapi.responses import JSONResponse
|
from fastapi.responses import JSONResponse, StreamingResponse
|
||||||
|
|
||||||
from ebook_svc.services.tt_platform_config import resolve_config_file
|
from ebook_svc.services.config_live import fanout, notify_config_changed, read_config_meta
|
||||||
from ebook_svc.services.public_config_snapshot import PublicConfigSnapshot
|
from ebook_svc.services.public_config_snapshot import PublicConfigSnapshot
|
||||||
|
from ebook_svc.services.tt_platform_config import resolve_config_file
|
||||||
|
|
||||||
router = APIRouter(tags=["public-config"])
|
router = APIRouter(tags=["public-config"])
|
||||||
_snapshot = PublicConfigSnapshot()
|
_snapshot = PublicConfigSnapshot()
|
||||||
|
|
||||||
|
_NO_STORE = {
|
||||||
|
"Cache-Control": "no-store, no-cache, must-revalidate",
|
||||||
|
"Access-Control-Allow-Origin": "*",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
def _read_full_config() -> dict[str, Any]:
|
def _read_full_config() -> dict[str, Any]:
|
||||||
return _snapshot.read(resolve_config_file())
|
return _snapshot.read(resolve_config_file())
|
||||||
|
|
||||||
|
|
||||||
|
def _config_response() -> JSONResponse:
|
||||||
|
config = _read_full_config()
|
||||||
|
return JSONResponse(
|
||||||
|
content={"ok": True, "source": "file", "config": config},
|
||||||
|
headers=_NO_STORE,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.get("/api/config")
|
@router.get("/api/config")
|
||||||
@router.get("/api/ebook/config")
|
@router.get("/api/ebook/config")
|
||||||
async def public_remote_config() -> JSONResponse:
|
async def public_remote_config() -> JSONResponse:
|
||||||
"""对齐门户 GET /api/config:{ ok, source, config }。"""
|
"""对齐门户 GET /api/config:{ ok, source, config }。"""
|
||||||
config = _read_full_config()
|
return _config_response()
|
||||||
return JSONResponse(
|
|
||||||
content={"ok": True, "source": "file", "config": config},
|
|
||||||
headers={
|
@router.post("/api/config")
|
||||||
"Cache-Control": "no-store, no-cache, must-revalidate",
|
@router.post("/api/ebook/config")
|
||||||
"Access-Control-Allow-Origin": "*",
|
@router.post("/api/config/pull")
|
||||||
},
|
@router.post("/api/ebook/config/pull")
|
||||||
)
|
async def public_remote_config_pull() -> JSONResponse:
|
||||||
|
"""POST 拉全量:微信小程序会强缓存 GET,开关热更新必须走 POST。"""
|
||||||
|
return _config_response()
|
||||||
|
|
||||||
|
|
||||||
@router.get("/api/config/meta")
|
@router.get("/api/config/meta")
|
||||||
@router.get("/api/ebook/config/meta")
|
@router.get("/api/ebook/config/meta")
|
||||||
async def public_remote_config_meta() -> JSONResponse:
|
async def public_remote_config_meta() -> JSONResponse:
|
||||||
config = _read_full_config()
|
meta = read_config_meta()
|
||||||
try:
|
return JSONResponse(content=meta, headers=_NO_STORE)
|
||||||
version = int(config.get("version") or 0)
|
|
||||||
except (TypeError, ValueError, OverflowError):
|
|
||||||
version = 0
|
@router.get("/api/config/stream")
|
||||||
return JSONResponse(
|
@router.get("/api/ebook/config/stream")
|
||||||
content={
|
async def public_remote_config_stream() -> StreamingResponse:
|
||||||
"ok": True,
|
"""SSE:后台改 remote-config → 立刻推 version/updatedAt。"""
|
||||||
"version": version,
|
queue = fanout.register()
|
||||||
"updatedAt": str(config.get("updatedAt") or ""),
|
|
||||||
},
|
async def event_gen():
|
||||||
|
try:
|
||||||
|
meta = notify_config_changed(read_config_meta(), source="sse-hello")
|
||||||
|
yield f"event: config\ndata: {json.dumps(meta, ensure_ascii=False)}\n\n"
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
payload = await asyncio.wait_for(queue.get(), timeout=15.0)
|
||||||
|
yield f"event: config\ndata: {json.dumps(payload, ensure_ascii=False)}\n\n"
|
||||||
|
except asyncio.TimeoutError:
|
||||||
|
yield ": ping\n\n"
|
||||||
|
finally:
|
||||||
|
fanout.unregister(queue)
|
||||||
|
|
||||||
|
return StreamingResponse(
|
||||||
|
event_gen(),
|
||||||
|
media_type="text/event-stream",
|
||||||
headers={
|
headers={
|
||||||
"Cache-Control": "no-store, no-cache, must-revalidate",
|
"Cache-Control": "no-cache, no-transform",
|
||||||
|
"Connection": "keep-alive",
|
||||||
|
"X-Accel-Buffering": "no",
|
||||||
"Access-Control-Allow-Origin": "*",
|
"Access-Control-Allow-Origin": "*",
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.websocket("/api/config/ws")
|
||||||
|
@router.websocket("/api/ebook/config/ws")
|
||||||
|
async def public_remote_config_ws(ws: WebSocket) -> None:
|
||||||
|
"""WebSocket:微信小程序实时配置(无 EventSource)。"""
|
||||||
|
await ws.accept()
|
||||||
|
queue = fanout.register()
|
||||||
|
try:
|
||||||
|
meta = notify_config_changed(read_config_meta(), source="ws-hello")
|
||||||
|
await ws.send_text(json.dumps({"type": "config", **meta}, ensure_ascii=False))
|
||||||
|
|
||||||
|
async def pump_out() -> None:
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
payload = await asyncio.wait_for(queue.get(), timeout=20.0)
|
||||||
|
await ws.send_text(
|
||||||
|
json.dumps({"type": "config", **payload}, ensure_ascii=False)
|
||||||
|
)
|
||||||
|
except asyncio.TimeoutError:
|
||||||
|
await ws.send_text(json.dumps({"type": "ping"}))
|
||||||
|
|
||||||
|
async def pump_in() -> None:
|
||||||
|
while True:
|
||||||
|
raw = await ws.receive_text()
|
||||||
|
# 客户端可发 {"type":"pull"} 强制再推当前 meta
|
||||||
|
try:
|
||||||
|
msg = json.loads(raw) if raw else {}
|
||||||
|
except Exception:
|
||||||
|
msg = {}
|
||||||
|
if isinstance(msg, dict) and msg.get("type") in ("pull", "hello", "ping"):
|
||||||
|
cur = read_config_meta()
|
||||||
|
await ws.send_text(
|
||||||
|
json.dumps({"type": "config", **cur, "source": "pull"}, ensure_ascii=False)
|
||||||
|
)
|
||||||
|
|
||||||
|
await asyncio.gather(pump_out(), pump_in())
|
||||||
|
except WebSocketDisconnect:
|
||||||
|
pass
|
||||||
|
except Exception:
|
||||||
|
try:
|
||||||
|
await ws.close()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
fanout.unregister(queue)
|
||||||
|
|||||||
@ -157,6 +157,25 @@ async def list_orders(
|
|||||||
return {"ok": True, "items": shop_store.list_orders(status=status, limit=200)}
|
return {"ok": True, "items": shop_store.list_orders(status=status, limit=200)}
|
||||||
|
|
||||||
|
|
||||||
|
class OrderStatusBody(BaseModel):
|
||||||
|
status: str = Field(..., min_length=1)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/orders/{order_id}/status")
|
||||||
|
async def order_status(
|
||||||
|
order_id: str,
|
||||||
|
body: OrderStatusBody,
|
||||||
|
_: str = Depends(require_admin),
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
try:
|
||||||
|
order = shop_store.mark_order_status(order_id, body.status)
|
||||||
|
except ValueError as e:
|
||||||
|
raise HTTPException(400, str(e)) from e
|
||||||
|
if not order:
|
||||||
|
raise HTTPException(404, "订单不存在")
|
||||||
|
return {"ok": True, "order": order}
|
||||||
|
|
||||||
|
|
||||||
@router.post("/orders/{order_id}/ship")
|
@router.post("/orders/{order_id}/ship")
|
||||||
async def ship_order(
|
async def ship_order(
|
||||||
order_id: str,
|
order_id: str,
|
||||||
|
|||||||
45
apps/api/services/ebook_svc/routers/social_ops_admin.py
Normal file
45
apps/api/services/ebook_svc/routers/social_ops_admin.py
Normal file
@ -0,0 +1,45 @@
|
|||||||
|
"""微信后台 · 游民社区运营开关 admin.nomadro.cn/wechat/social"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
from ebook_svc.core.security import require_admin
|
||||||
|
from ebook_svc.services.social_ops import read_social_ops, write_social_ops
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/admin/weapp/social", tags=["weapp-social-ops"])
|
||||||
|
|
||||||
|
|
||||||
|
class FlagsPatch(BaseModel):
|
||||||
|
pages: dict[str, bool] | None = None
|
||||||
|
sections: dict[str, bool] | None = None
|
||||||
|
features: dict[str, bool] | None = None
|
||||||
|
buttons: dict[str, bool] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class SocialOpsBody(BaseModel):
|
||||||
|
moduleEnabled: bool | None = None
|
||||||
|
flags: FlagsPatch | None = None
|
||||||
|
copy: dict[str, str] | None = None
|
||||||
|
pageCopy: dict[str, dict[str, str] | None] | None = Field(default=None)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("")
|
||||||
|
async def get_social_ops(_: str = Depends(require_admin)) -> dict[str, Any]:
|
||||||
|
return read_social_ops()
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("")
|
||||||
|
async def put_social_ops(body: SocialOpsBody, _: str = Depends(require_admin)) -> dict[str, Any]:
|
||||||
|
patch: dict[str, Any] = {}
|
||||||
|
if body.moduleEnabled is not None:
|
||||||
|
patch["moduleEnabled"] = body.moduleEnabled
|
||||||
|
if body.flags is not None:
|
||||||
|
patch["flags"] = body.flags.model_dump(exclude_none=True)
|
||||||
|
if body.copy is not None:
|
||||||
|
patch["copy"] = body.copy
|
||||||
|
if body.pageCopy is not None:
|
||||||
|
patch["pageCopy"] = body.pageCopy
|
||||||
|
return write_social_ops(patch)
|
||||||
197
apps/api/services/ebook_svc/routers/social_ugc_admin.py
Normal file
197
apps/api/services/ebook_svc/routers/social_ugc_admin.py
Normal file
@ -0,0 +1,197 @@
|
|||||||
|
"""微信后台 · 游民社区 UGC 增删查改"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
from ebook_svc.core.security import require_admin
|
||||||
|
from ebook_svc.services import social_ugc as ugc
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/admin/social/ugc", tags=["social-ugc-admin"])
|
||||||
|
|
||||||
|
|
||||||
|
class RosterPatch(BaseModel):
|
||||||
|
name: str | None = None
|
||||||
|
title: str | None = None
|
||||||
|
city: str | None = None
|
||||||
|
phone: str | None = None
|
||||||
|
linktree: str | None = None
|
||||||
|
skills: str | None = None
|
||||||
|
bio: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/overview")
|
||||||
|
async def get_overview(_: str = Depends(require_admin)) -> dict[str, Any]:
|
||||||
|
return ugc.overview()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/messages")
|
||||||
|
async def get_messages(
|
||||||
|
channelId: str = "",
|
||||||
|
q: 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_messages(channel_id=channelId, q=q, limit=limit, offset=offset)
|
||||||
|
except Exception as e:
|
||||||
|
raise HTTPException(503, f"social db unavailable: {e}") from e
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/messages/{message_id}")
|
||||||
|
async def del_message(message_id: str, _: str = Depends(require_admin)) -> dict[str, Any]:
|
||||||
|
if not ugc.delete_message(message_id):
|
||||||
|
raise HTTPException(404, "消息不存在")
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/roster")
|
||||||
|
async def get_roster(
|
||||||
|
q: 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_roster(q=q, limit=limit, offset=offset)
|
||||||
|
except Exception as e:
|
||||||
|
raise HTTPException(503, f"social db unavailable: {e}") from e
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/roster/{guest_id}")
|
||||||
|
async def put_roster(
|
||||||
|
guest_id: str, body: RosterPatch, _: str = Depends(require_admin)
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
item = ugc.update_roster(guest_id, body.model_dump(exclude_none=True))
|
||||||
|
if not item:
|
||||||
|
raise HTTPException(404, "介绍不存在")
|
||||||
|
return {"ok": True, "item": item}
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/roster/{guest_id}")
|
||||||
|
async def del_roster(guest_id: str, _: str = Depends(require_admin)) -> dict[str, Any]:
|
||||||
|
if not ugc.delete_roster(guest_id):
|
||||||
|
raise HTTPException(404, "介绍不存在")
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/reviews")
|
||||||
|
async def get_reviews(
|
||||||
|
cafeId: 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_reviews(cafe_id=cafeId, limit=limit, offset=offset)
|
||||||
|
except Exception as e:
|
||||||
|
raise HTTPException(503, f"social db unavailable: {e}") from e
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/reviews/{review_id}")
|
||||||
|
async def del_review(review_id: str, _: str = Depends(require_admin)) -> dict[str, Any]:
|
||||||
|
if not ugc.delete_review(review_id):
|
||||||
|
raise HTTPException(404, "评价不存在")
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/gig-apps")
|
||||||
|
async def get_gig_apps(
|
||||||
|
gigId: 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_gig_apps(gig_id=gigId, limit=limit, offset=offset)
|
||||||
|
except Exception as e:
|
||||||
|
raise HTTPException(503, f"social db unavailable: {e}") from e
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/gig-apps/{app_id}")
|
||||||
|
async def del_gig_app(app_id: str, _: str = Depends(require_admin)) -> dict[str, Any]:
|
||||||
|
if not ugc.delete_gig_app(app_id):
|
||||||
|
raise HTTPException(404, "申请不存在")
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/feedback")
|
||||||
|
async def get_feedback(
|
||||||
|
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_feedback(limit=limit, offset=offset)
|
||||||
|
except Exception as e:
|
||||||
|
raise HTTPException(503, f"social db unavailable: {e}") from e
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/feedback/{fid}")
|
||||||
|
async def del_feedback(fid: str, _: str = Depends(require_admin)) -> dict[str, Any]:
|
||||||
|
if not ugc.delete_feedback(fid):
|
||||||
|
raise HTTPException(404, "反馈不存在")
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
class CatalogBody(BaseModel):
|
||||||
|
meetups: list[dict[str, Any]] | None = None
|
||||||
|
gigs: list[dict[str, Any]] | None = None
|
||||||
|
cafes: list[dict[str, Any]] | None = None
|
||||||
|
roster: list[dict[str, Any]] | None = None
|
||||||
|
ebooks: list[dict[str, Any]] | None = None
|
||||||
|
videos: list[dict[str, Any]] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/catalog")
|
||||||
|
async def get_catalog(_: str = Depends(require_admin)) -> dict[str, Any]:
|
||||||
|
from ebook_svc.services.social_ops import _read_raw
|
||||||
|
|
||||||
|
raw = _read_raw()
|
||||||
|
copy = raw.get("copy") if isinstance(raw.get("copy"), dict) else {}
|
||||||
|
catalogs = copy.get("socialCatalogs") if isinstance(copy.get("socialCatalogs"), dict) else {}
|
||||||
|
return {
|
||||||
|
"ok": True,
|
||||||
|
"version": raw.get("version"),
|
||||||
|
"catalogs": {
|
||||||
|
"meetups": catalogs.get("meetups") if isinstance(catalogs.get("meetups"), list) else [],
|
||||||
|
"gigs": catalogs.get("gigs") if isinstance(catalogs.get("gigs"), list) else [],
|
||||||
|
"cafes": catalogs.get("cafes") if isinstance(catalogs.get("cafes"), list) else [],
|
||||||
|
"roster": catalogs.get("roster") if isinstance(catalogs.get("roster"), list) else [],
|
||||||
|
"ebooks": catalogs.get("ebooks") if isinstance(catalogs.get("ebooks"), list) else [],
|
||||||
|
"videos": catalogs.get("videos") if isinstance(catalogs.get("videos"), list) else [],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/catalog")
|
||||||
|
async def put_catalog(body: CatalogBody, _: str = Depends(require_admin)) -> dict[str, Any]:
|
||||||
|
"""深合并 socialCatalogs 数组键;不碰其它配置。"""
|
||||||
|
from ebook_svc.services.social_ops import _read_raw, _write_raw
|
||||||
|
|
||||||
|
raw = _read_raw()
|
||||||
|
out = dict(raw) if raw else {"version": 1, "modules": {}, "copy": {}}
|
||||||
|
copy = dict(out.get("copy") or {})
|
||||||
|
catalogs = dict(copy.get("socialCatalogs") or {}) if isinstance(copy.get("socialCatalogs"), dict) else {}
|
||||||
|
patch = body.model_dump(exclude_none=True)
|
||||||
|
for key, val in patch.items():
|
||||||
|
if isinstance(val, list):
|
||||||
|
catalogs[key] = val
|
||||||
|
copy["socialCatalogs"] = catalogs
|
||||||
|
out["copy"] = copy
|
||||||
|
_write_raw(out)
|
||||||
|
return {
|
||||||
|
"ok": True,
|
||||||
|
"version": out.get("version"),
|
||||||
|
"catalogs": {
|
||||||
|
"meetups": catalogs.get("meetups") if isinstance(catalogs.get("meetups"), list) else [],
|
||||||
|
"gigs": catalogs.get("gigs") if isinstance(catalogs.get("gigs"), list) else [],
|
||||||
|
"cafes": catalogs.get("cafes") if isinstance(catalogs.get("cafes"), list) else [],
|
||||||
|
"roster": catalogs.get("roster") if isinstance(catalogs.get("roster"), list) else [],
|
||||||
|
"ebooks": catalogs.get("ebooks") if isinstance(catalogs.get("ebooks"), list) else [],
|
||||||
|
"videos": catalogs.get("videos") if isinstance(catalogs.get("videos"), list) else [],
|
||||||
|
},
|
||||||
|
}
|
||||||
@ -24,6 +24,15 @@ class BookPatch(BaseModel):
|
|||||||
offer_key: str | None = None
|
offer_key: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class BookCreateBody(BookPatch):
|
||||||
|
id: str = Field(..., min_length=1, max_length=64)
|
||||||
|
free: bool | None = True
|
||||||
|
|
||||||
|
|
||||||
|
class OrderStatusBody(BaseModel):
|
||||||
|
status: str # cancel | refunded | pending | paid
|
||||||
|
|
||||||
|
|
||||||
class OfferApplyBody(BaseModel):
|
class OfferApplyBody(BaseModel):
|
||||||
offer_key: str
|
offer_key: str
|
||||||
# 付费模式下可保留当前试读比例;免费固定 100
|
# 付费模式下可保留当前试读比例;免费固定 100
|
||||||
|
|||||||
166
apps/api/services/ebook_svc/services/config_live.py
Normal file
166
apps/api/services/ebook_svc/services/config_live.py
Normal file
@ -0,0 +1,166 @@
|
|||||||
|
"""远程配置实时总线:写入通知 + 1s 文件轮询 → SSE / WebSocket 推送。"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import threading
|
||||||
|
from typing import Any, Callable
|
||||||
|
|
||||||
|
from ebook_svc.services.tt_platform_config import resolve_config_file
|
||||||
|
|
||||||
|
Listener = Callable[[dict[str, Any]], None]
|
||||||
|
|
||||||
|
_lock = threading.RLock()
|
||||||
|
_listeners: set[Listener] = set()
|
||||||
|
_last_meta: dict[str, Any] | None = None
|
||||||
|
_watcher_started = False
|
||||||
|
_poll_stop = threading.Event()
|
||||||
|
|
||||||
|
|
||||||
|
def _meta_from_raw(raw: dict[str, Any] | None) -> dict[str, Any]:
|
||||||
|
data = raw if isinstance(raw, dict) else {}
|
||||||
|
try:
|
||||||
|
version = int(data.get("version") or 0)
|
||||||
|
except (TypeError, ValueError, OverflowError):
|
||||||
|
version = 0
|
||||||
|
return {
|
||||||
|
"ok": True,
|
||||||
|
"version": version,
|
||||||
|
"updatedAt": str(data.get("updatedAt") or ""),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def read_config_meta() -> dict[str, Any]:
|
||||||
|
path = resolve_config_file()
|
||||||
|
if not path.is_file():
|
||||||
|
return {"ok": True, "version": 0, "updatedAt": ""}
|
||||||
|
try:
|
||||||
|
raw = json.loads(path.read_text(encoding="utf-8"))
|
||||||
|
return _meta_from_raw(raw if isinstance(raw, dict) else {})
|
||||||
|
except Exception:
|
||||||
|
with _lock:
|
||||||
|
if _last_meta:
|
||||||
|
return dict(_last_meta)
|
||||||
|
return {"ok": True, "version": 0, "updatedAt": ""}
|
||||||
|
|
||||||
|
|
||||||
|
def notify_config_changed(
|
||||||
|
meta: dict[str, Any] | None = None,
|
||||||
|
*,
|
||||||
|
source: str = "write",
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""广播 version/updatedAt;同 meta 去重。"""
|
||||||
|
global _last_meta
|
||||||
|
payload = dict(meta or read_config_meta())
|
||||||
|
payload["source"] = source
|
||||||
|
payload["ok"] = True
|
||||||
|
with _lock:
|
||||||
|
prev = _last_meta
|
||||||
|
if (
|
||||||
|
prev
|
||||||
|
and prev.get("version") == payload.get("version")
|
||||||
|
and prev.get("updatedAt") == payload.get("updatedAt")
|
||||||
|
):
|
||||||
|
return payload
|
||||||
|
_last_meta = {
|
||||||
|
"ok": True,
|
||||||
|
"version": payload.get("version"),
|
||||||
|
"updatedAt": payload.get("updatedAt"),
|
||||||
|
}
|
||||||
|
listeners = list(_listeners)
|
||||||
|
for fn in listeners:
|
||||||
|
try:
|
||||||
|
fn(payload)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return payload
|
||||||
|
|
||||||
|
|
||||||
|
def notify_config_written(raw: dict[str, Any] | None = None) -> None:
|
||||||
|
notify_config_changed(_meta_from_raw(raw), source="write")
|
||||||
|
|
||||||
|
|
||||||
|
def subscribe(listener: Listener) -> Callable[[], None]:
|
||||||
|
with _lock:
|
||||||
|
_listeners.add(listener)
|
||||||
|
|
||||||
|
def _off() -> None:
|
||||||
|
with _lock:
|
||||||
|
_listeners.discard(listener)
|
||||||
|
|
||||||
|
return _off
|
||||||
|
|
||||||
|
|
||||||
|
def ensure_config_watcher() -> None:
|
||||||
|
"""进程内单例:1s 读盘轮询(覆盖本进程写入以外的文件变更)。"""
|
||||||
|
global _watcher_started
|
||||||
|
with _lock:
|
||||||
|
if _watcher_started:
|
||||||
|
return
|
||||||
|
_watcher_started = True
|
||||||
|
|
||||||
|
notify_config_changed(read_config_meta(), source="boot")
|
||||||
|
|
||||||
|
def _loop() -> None:
|
||||||
|
while not _poll_stop.wait(1.0):
|
||||||
|
notify_config_changed(read_config_meta(), source="poll")
|
||||||
|
|
||||||
|
threading.Thread(target=_loop, name="config-live", daemon=True).start()
|
||||||
|
|
||||||
|
|
||||||
|
class AsyncFanout:
|
||||||
|
"""同步 bus → asyncio Queue,供 SSE / WS 使用。"""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self._queues: set[asyncio.Queue[dict[str, Any]]] = set()
|
||||||
|
self._loop: asyncio.AbstractEventLoop | None = None
|
||||||
|
self._unsub: Callable[[], None] | None = None
|
||||||
|
self._started = False
|
||||||
|
|
||||||
|
def ensure(self) -> None:
|
||||||
|
if self._started:
|
||||||
|
return
|
||||||
|
ensure_config_watcher()
|
||||||
|
try:
|
||||||
|
self._loop = asyncio.get_running_loop()
|
||||||
|
except RuntimeError:
|
||||||
|
self._loop = asyncio.get_event_loop()
|
||||||
|
self._started = True
|
||||||
|
|
||||||
|
def _on(payload: dict[str, Any]) -> None:
|
||||||
|
loop = self._loop
|
||||||
|
if not loop:
|
||||||
|
return
|
||||||
|
for q in list(self._queues):
|
||||||
|
try:
|
||||||
|
loop.call_soon_threadsafe(self._put, q, payload)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
self._unsub = subscribe(_on)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _put(q: asyncio.Queue[dict[str, Any]], payload: dict[str, Any]) -> None:
|
||||||
|
try:
|
||||||
|
q.put_nowait(payload)
|
||||||
|
except asyncio.QueueFull:
|
||||||
|
try:
|
||||||
|
q.get_nowait()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
q.put_nowait(payload)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def register(self) -> asyncio.Queue[dict[str, Any]]:
|
||||||
|
self.ensure()
|
||||||
|
q: asyncio.Queue[dict[str, Any]] = asyncio.Queue(maxsize=16)
|
||||||
|
self._queues.add(q)
|
||||||
|
return q
|
||||||
|
|
||||||
|
def unregister(self, q: asyncio.Queue[dict[str, Any]]) -> None:
|
||||||
|
self._queues.discard(q)
|
||||||
|
|
||||||
|
|
||||||
|
fanout = AsyncFanout()
|
||||||
@ -578,6 +578,75 @@ class MemoStore:
|
|||||||
self.bump_content_revision()
|
self.bump_content_revision()
|
||||||
return memo
|
return memo
|
||||||
|
|
||||||
|
def update_memo(
|
||||||
|
self,
|
||||||
|
memo_id: str,
|
||||||
|
*,
|
||||||
|
content: str | None = None,
|
||||||
|
title: str | None = None,
|
||||||
|
nickname: str | None = None,
|
||||||
|
visibility: str | None = None,
|
||||||
|
resources: list[dict[str, Any]] | None = None,
|
||||||
|
) -> dict[str, Any] | None:
|
||||||
|
memo = self.get_memo(memo_id, admin=True)
|
||||||
|
if not memo:
|
||||||
|
return None
|
||||||
|
if str(memo.get("status") or "") == "deleted":
|
||||||
|
raise ValueError("已删除的帖子不能编辑")
|
||||||
|
s = self.get_settings()
|
||||||
|
max_len = int(s.get("maxContentLen") or 20000)
|
||||||
|
max_images = int(s.get("maxImages") or 9)
|
||||||
|
new_content = memo.get("content") or ""
|
||||||
|
if content is not None:
|
||||||
|
new_content = (content or "").strip()
|
||||||
|
if len(new_content) > max_len:
|
||||||
|
raise ValueError(f"内容超过 {max_len} 字")
|
||||||
|
new_title = memo.get("title") or ""
|
||||||
|
if title is not None:
|
||||||
|
new_title = extract_title(new_content, title)
|
||||||
|
new_nick = memo.get("nickname") or "博主"
|
||||||
|
if nickname is not None:
|
||||||
|
new_nick = (nickname or "博主").strip()[:32] or "博主"
|
||||||
|
vis = memo.get("visibility") or "vip"
|
||||||
|
if visibility is not None:
|
||||||
|
vis = (visibility or "vip").strip().lower()
|
||||||
|
if vis not in {"vip", "trial", "public", "free"}:
|
||||||
|
vis = "vip"
|
||||||
|
clean_res = memo.get("resources") or []
|
||||||
|
if resources is not None:
|
||||||
|
clean_res = []
|
||||||
|
for r in resources:
|
||||||
|
url = str((r or {}).get("url") or "").strip()
|
||||||
|
if not url:
|
||||||
|
continue
|
||||||
|
clean_res.append({"type": str((r or {}).get("type") or "image"), "url": url})
|
||||||
|
if len(clean_res) > max_images:
|
||||||
|
raise ValueError(f"最多 {max_images} 张图")
|
||||||
|
if not new_content and not clean_res:
|
||||||
|
raise ValueError("内容或图片至少一项")
|
||||||
|
tags = extract_tags(new_content)
|
||||||
|
now = time.time()
|
||||||
|
with self.conn() as c:
|
||||||
|
c.execute(
|
||||||
|
"""
|
||||||
|
UPDATE memos SET nickname=?, title=?, content=?, resources_json=?, tags_json=?,
|
||||||
|
visibility=?, updated_at=?
|
||||||
|
WHERE id=?
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
new_nick,
|
||||||
|
new_title,
|
||||||
|
new_content,
|
||||||
|
json.dumps(clean_res, ensure_ascii=False),
|
||||||
|
json.dumps(tags, ensure_ascii=False),
|
||||||
|
vis,
|
||||||
|
now,
|
||||||
|
memo_id,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
self.bump_content_revision()
|
||||||
|
return self.get_memo(memo_id, admin=True)
|
||||||
|
|
||||||
def delete_memo(self, memo_id: str, *, openid: str = "", admin: bool = False) -> bool:
|
def delete_memo(self, memo_id: str, *, openid: str = "", admin: bool = False) -> bool:
|
||||||
memo = self.get_memo(memo_id, openid=openid, admin=True)
|
memo = self.get_memo(memo_id, openid=openid, admin=True)
|
||||||
if not memo:
|
if not memo:
|
||||||
|
|||||||
@ -590,6 +590,24 @@ class ShopStore:
|
|||||||
)
|
)
|
||||||
return self.get_order(order_id)
|
return self.get_order(order_id)
|
||||||
|
|
||||||
|
def mark_order_status(self, order_id: str, status: str) -> dict[str, Any] | None:
|
||||||
|
"""运营标记 cancel/refunded(不直连微信退款)。"""
|
||||||
|
st = (status or "").strip().lower()
|
||||||
|
if st in {"cancel", "cancelled"}:
|
||||||
|
st = "cancelled"
|
||||||
|
if st not in {"cancelled", "refunded", "paid", "pending", "shipped"}:
|
||||||
|
raise ValueError("unsupported status")
|
||||||
|
order = self.get_order(order_id)
|
||||||
|
if not order:
|
||||||
|
return None
|
||||||
|
now = time.time()
|
||||||
|
with self.conn() as c:
|
||||||
|
c.execute(
|
||||||
|
"UPDATE shop_orders SET status=?, updated_at=? WHERE id=?",
|
||||||
|
(st, now, order_id),
|
||||||
|
)
|
||||||
|
return self.get_order(order_id)
|
||||||
|
|
||||||
def catalog_public(self) -> dict[str, Any]:
|
def catalog_public(self) -> dict[str, Any]:
|
||||||
products = self.list_products(enabled_only=True)
|
products = self.list_products(enabled_only=True)
|
||||||
groups: list[str] = []
|
groups: list[str] = []
|
||||||
|
|||||||
331
apps/api/services/ebook_svc/services/social_ops.py
Normal file
331
apps/api/services/ebook_svc/services/social_ops.py
Normal file
@ -0,0 +1,331 @@
|
|||||||
|
"""游民社区运营开关 — pages / sections / features / buttons / copy。
|
||||||
|
|
||||||
|
只深合并 remote-config 的 copy.social* 与 copy.socialFlags;
|
||||||
|
不碰 orders、PocketBase、platforms.tt、socialCatalogs 内容数组(除非显式传入)。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from copy import deepcopy
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from ebook_svc.services.tt_platform_config import resolve_config_file
|
||||||
|
|
||||||
|
PAGE_KEYS = (
|
||||||
|
"index",
|
||||||
|
"chat",
|
||||||
|
"date",
|
||||||
|
"people",
|
||||||
|
"peopleProfile",
|
||||||
|
"roster",
|
||||||
|
"meetup",
|
||||||
|
"meetupLive",
|
||||||
|
"team",
|
||||||
|
)
|
||||||
|
|
||||||
|
SECTION_KEYS = (
|
||||||
|
"people",
|
||||||
|
"date",
|
||||||
|
"meetup",
|
||||||
|
"cities",
|
||||||
|
"team",
|
||||||
|
"ways",
|
||||||
|
"promo",
|
||||||
|
"invite",
|
||||||
|
)
|
||||||
|
|
||||||
|
FEATURE_KEYS = (
|
||||||
|
"joinPay",
|
||||||
|
"cafeReviews",
|
||||||
|
"creationSheet",
|
||||||
|
"chatRealtime",
|
||||||
|
"livePusher",
|
||||||
|
"dateSwipe",
|
||||||
|
"rosterEdit",
|
||||||
|
"teamApply",
|
||||||
|
"dock",
|
||||||
|
"homeEntry",
|
||||||
|
)
|
||||||
|
|
||||||
|
BUTTON_KEYS = (
|
||||||
|
"heroJoin",
|
||||||
|
"heroChat",
|
||||||
|
"heroDate",
|
||||||
|
"heroStory",
|
||||||
|
"wayGroup",
|
||||||
|
"wayDate",
|
||||||
|
"wayMeetup",
|
||||||
|
"wayCafe",
|
||||||
|
"wayTeam",
|
||||||
|
"dockHome",
|
||||||
|
"dockChat",
|
||||||
|
"dockDate",
|
||||||
|
"dockPeople",
|
||||||
|
"dockRoster",
|
||||||
|
)
|
||||||
|
|
||||||
|
COPY_KEYS = (
|
||||||
|
"socialEyebrow",
|
||||||
|
"socialHeroLine1",
|
||||||
|
"socialHeroAccent",
|
||||||
|
"socialHeroLead",
|
||||||
|
"socialJoinCta",
|
||||||
|
"socialInviteTitle",
|
||||||
|
"socialInviteLead",
|
||||||
|
"socialOnlineTitle",
|
||||||
|
"socialOfflineTitle",
|
||||||
|
"socialTeamTitle",
|
||||||
|
"socialWayGroup",
|
||||||
|
"socialWayChat",
|
||||||
|
"socialWayDate",
|
||||||
|
"socialWayCafe",
|
||||||
|
"socialWayTeam",
|
||||||
|
"socialPromoUrl",
|
||||||
|
)
|
||||||
|
|
||||||
|
PAGE_META = {
|
||||||
|
"index": ("社区首页", "pages/social/index"),
|
||||||
|
"chat": ("游民大厅", "pages/social/chat"),
|
||||||
|
"date": ("认识一下", "pages/social/date"),
|
||||||
|
"people": ("想见的人", "pages/social/people"),
|
||||||
|
"peopleProfile": ("成员详情", "pages/social/people/profile"),
|
||||||
|
"roster": ("我的介绍", "pages/social/roster"),
|
||||||
|
"meetup": ("视频场次", "pages/social/meetup"),
|
||||||
|
"meetupLive": ("语音视频厅", "pages/social/meetup-live"),
|
||||||
|
"team": ("找搭子/共创", "pages/social/team"),
|
||||||
|
}
|
||||||
|
|
||||||
|
SECTION_META = {
|
||||||
|
"people": "首页 · 成员目录",
|
||||||
|
"date": "首页 · 认识一下",
|
||||||
|
"meetup": "首页 · 语音视频",
|
||||||
|
"cities": "首页 · 同城见面",
|
||||||
|
"team": "首页 · 团队共创",
|
||||||
|
"ways": "首页 · 连接方式卡片",
|
||||||
|
"promo": "首页 · 宣传片/故事",
|
||||||
|
"invite": "首页 · 底部邀请",
|
||||||
|
}
|
||||||
|
|
||||||
|
FEATURE_META = {
|
||||||
|
"joinPay": "加群虚拟支付底栏",
|
||||||
|
"cafeReviews": "咖啡馆评价",
|
||||||
|
"creationSheet": "共创/视频详情抽屉",
|
||||||
|
"chatRealtime": "大厅实时消息",
|
||||||
|
"livePusher": "原生推流预览",
|
||||||
|
"dateSwipe": "认识一下滑卡",
|
||||||
|
"rosterEdit": "编辑我的介绍",
|
||||||
|
"teamApply": "共创报名表单",
|
||||||
|
"dock": "底部 SocialDock",
|
||||||
|
"homeEntry": "小程序首页「游民社区」入口",
|
||||||
|
}
|
||||||
|
|
||||||
|
BUTTON_META = {
|
||||||
|
"heroJoin": "首屏主 CTA(加群)",
|
||||||
|
"heroChat": "首屏 · 群组聊天",
|
||||||
|
"heroDate": "首屏 · 认识一下",
|
||||||
|
"heroStory": "首屏 · 社区故事",
|
||||||
|
"wayGroup": "方式卡 · 群聊",
|
||||||
|
"wayDate": "方式卡 · 认识",
|
||||||
|
"wayMeetup": "方式卡 · 视频",
|
||||||
|
"wayCafe": "方式卡 · 同城",
|
||||||
|
"wayTeam": "方式卡 · 共创",
|
||||||
|
"dockHome": "Dock · 首页",
|
||||||
|
"dockChat": "Dock · 聊天",
|
||||||
|
"dockDate": "Dock · 认识",
|
||||||
|
"dockPeople": "Dock · 看看谁",
|
||||||
|
"dockRoster": "Dock · 我",
|
||||||
|
}
|
||||||
|
|
||||||
|
DEFAULT_COPY = {
|
||||||
|
"socialEyebrow": "自由生活,同频相遇",
|
||||||
|
"socialHeroLine1": "世界很大,",
|
||||||
|
"socialHeroAccent": "同类",
|
||||||
|
"socialHeroLead": "换一座城市,不必重新孤独。\n从一句你好、一杯咖啡开始,找到一起生活、\n一起探索、一起做点什么的人。",
|
||||||
|
"socialJoinCta": "找到我的同频",
|
||||||
|
"socialInviteTitle": "下一站,和同类一起。",
|
||||||
|
"socialInviteLead": "无论你正在出发,还是已经在路上,这里都有一个属于你的位置。",
|
||||||
|
"socialOnlineTitle": "随时,聊得来",
|
||||||
|
"socialOfflineTitle": "同城,见一面",
|
||||||
|
"socialTeamTitle": "一起,做点事",
|
||||||
|
"socialWayGroup": "群组聊天",
|
||||||
|
"socialWayChat": "开视频聊聊",
|
||||||
|
"socialWayDate": "认识一下",
|
||||||
|
"socialWayCafe": "找个地方见面",
|
||||||
|
"socialWayTeam": "找搭子 · 共创",
|
||||||
|
"socialPromoUrl": "",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _all_true(keys: tuple[str, ...]) -> dict[str, bool]:
|
||||||
|
return {k: True for k in keys}
|
||||||
|
|
||||||
|
|
||||||
|
def _read_raw() -> dict[str, Any]:
|
||||||
|
path = resolve_config_file()
|
||||||
|
if not path.is_file():
|
||||||
|
return {}
|
||||||
|
try:
|
||||||
|
import json
|
||||||
|
|
||||||
|
raw = json.loads(path.read_text(encoding="utf-8"))
|
||||||
|
return raw if isinstance(raw, dict) else {}
|
||||||
|
except Exception:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
|
||||||
|
def _write_raw(out: dict[str, Any]) -> None:
|
||||||
|
import json
|
||||||
|
|
||||||
|
path = resolve_config_file()
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
out["updatedAt"] = datetime.now(timezone.utc).isoformat()
|
||||||
|
try:
|
||||||
|
out["version"] = int(out.get("version") or 1) + 1
|
||||||
|
except Exception:
|
||||||
|
out["version"] = 2
|
||||||
|
if path.is_file():
|
||||||
|
bak = path.with_suffix(path.suffix + f".bak-social-{out['updatedAt'].replace(':', '-')}")
|
||||||
|
try:
|
||||||
|
bak.write_text(path.read_text(encoding="utf-8"), encoding="utf-8")
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
path.write_text(json.dumps(out, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
def _bool_map(raw: Any, keys: tuple[str, ...], default: bool = True) -> dict[str, bool]:
|
||||||
|
src = raw if isinstance(raw, dict) else {}
|
||||||
|
out: dict[str, bool] = {}
|
||||||
|
for k in keys:
|
||||||
|
if k in src:
|
||||||
|
out[k] = bool(src[k])
|
||||||
|
else:
|
||||||
|
out[k] = default
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _norm_flags(raw: Any) -> dict[str, dict[str, bool]]:
|
||||||
|
src = raw if isinstance(raw, dict) else {}
|
||||||
|
return {
|
||||||
|
"pages": _bool_map(src.get("pages"), PAGE_KEYS, True),
|
||||||
|
"sections": _bool_map(src.get("sections"), SECTION_KEYS, True),
|
||||||
|
"features": _bool_map(src.get("features"), FEATURE_KEYS, True),
|
||||||
|
"buttons": _bool_map(src.get("buttons"), BUTTON_KEYS, True),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _hidden_from_sections(sections: dict[str, bool]) -> list[str]:
|
||||||
|
return [k for k, on in sections.items() if not on]
|
||||||
|
|
||||||
|
|
||||||
|
def _sections_from_hidden(hidden: Any, base: dict[str, bool]) -> dict[str, bool]:
|
||||||
|
out = dict(base)
|
||||||
|
if not isinstance(hidden, list):
|
||||||
|
return out
|
||||||
|
for item in hidden:
|
||||||
|
if isinstance(item, str) and item in out:
|
||||||
|
out[item] = False
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def read_social_ops() -> dict[str, Any]:
|
||||||
|
raw = _read_raw()
|
||||||
|
modules = raw.get("modules") if isinstance(raw.get("modules"), dict) else {}
|
||||||
|
social_mod = modules.get("social") if isinstance(modules.get("social"), dict) else {}
|
||||||
|
copy_raw = raw.get("copy") if isinstance(raw.get("copy"), dict) else {}
|
||||||
|
flags = _norm_flags(copy_raw.get("socialFlags"))
|
||||||
|
# 兼容旧 socialHiddenSections
|
||||||
|
flags["sections"] = _sections_from_hidden(
|
||||||
|
copy_raw.get("socialHiddenSections"), flags["sections"]
|
||||||
|
)
|
||||||
|
|
||||||
|
copy_out: dict[str, str] = {}
|
||||||
|
for k in COPY_KEYS:
|
||||||
|
v = copy_raw.get(k)
|
||||||
|
copy_out[k] = str(v).strip() if isinstance(v, str) else str(DEFAULT_COPY.get(k) or "")
|
||||||
|
|
||||||
|
pages_meta = copy_raw.get("socialPages") if isinstance(copy_raw.get("socialPages"), dict) else {}
|
||||||
|
|
||||||
|
return {
|
||||||
|
"ok": True,
|
||||||
|
"moduleEnabled": social_mod.get("enabled", True) is not False,
|
||||||
|
"moduleTitle": str(social_mod.get("title") or "游民社区"),
|
||||||
|
"flags": flags,
|
||||||
|
"copy": copy_out,
|
||||||
|
"pageCopy": pages_meta,
|
||||||
|
"meta": {
|
||||||
|
"pages": PAGE_META,
|
||||||
|
"sections": SECTION_META,
|
||||||
|
"features": FEATURE_META,
|
||||||
|
"buttons": BUTTON_META,
|
||||||
|
"copyKeys": {k: k for k in COPY_KEYS},
|
||||||
|
},
|
||||||
|
"version": raw.get("version"),
|
||||||
|
"updatedAt": raw.get("updatedAt"),
|
||||||
|
"configPath": str(resolve_config_file()),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def write_social_ops(patch: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
raw = _read_raw()
|
||||||
|
out: dict[str, Any] = dict(raw) if raw else {"version": 1, "modules": {}, "flags": {}, "copy": {}}
|
||||||
|
modules = dict(out.get("modules") or {})
|
||||||
|
copy = dict(out.get("copy") or {})
|
||||||
|
flags = _norm_flags(copy.get("socialFlags"))
|
||||||
|
flags["sections"] = _sections_from_hidden(copy.get("socialHiddenSections"), flags["sections"])
|
||||||
|
|
||||||
|
if "moduleEnabled" in patch:
|
||||||
|
prev = modules.get("social") if isinstance(modules.get("social"), dict) else {}
|
||||||
|
modules["social"] = {
|
||||||
|
**{
|
||||||
|
"enabled": True,
|
||||||
|
"title": "游民社区",
|
||||||
|
"tabLabel": "社区",
|
||||||
|
"note": "Taro 原生 pages/social",
|
||||||
|
},
|
||||||
|
**prev,
|
||||||
|
"enabled": bool(patch["moduleEnabled"]),
|
||||||
|
}
|
||||||
|
|
||||||
|
if isinstance(patch.get("flags"), dict):
|
||||||
|
fp = patch["flags"]
|
||||||
|
for group in ("pages", "sections", "features", "buttons"):
|
||||||
|
if isinstance(fp.get(group), dict):
|
||||||
|
keys = {
|
||||||
|
"pages": PAGE_KEYS,
|
||||||
|
"sections": SECTION_KEYS,
|
||||||
|
"features": FEATURE_KEYS,
|
||||||
|
"buttons": BUTTON_KEYS,
|
||||||
|
}[group]
|
||||||
|
for k, v in fp[group].items():
|
||||||
|
if k in keys:
|
||||||
|
flags[group][k] = bool(v)
|
||||||
|
|
||||||
|
if isinstance(patch.get("copy"), dict):
|
||||||
|
for k, v in patch["copy"].items():
|
||||||
|
if k in COPY_KEYS and v is not None:
|
||||||
|
copy[k] = str(v)
|
||||||
|
|
||||||
|
if isinstance(patch.get("pageCopy"), dict):
|
||||||
|
pages = copy.get("socialPages") if isinstance(copy.get("socialPages"), dict) else {}
|
||||||
|
pages = dict(pages)
|
||||||
|
for pid, val in patch["pageCopy"].items():
|
||||||
|
if not isinstance(pid, str) or not pid:
|
||||||
|
continue
|
||||||
|
if val is None:
|
||||||
|
pages.pop(pid, None)
|
||||||
|
continue
|
||||||
|
if not isinstance(val, dict):
|
||||||
|
continue
|
||||||
|
cur = dict(pages.get(pid) or {}) if isinstance(pages.get(pid), dict) else {}
|
||||||
|
for field in ("eyebrow", "title", "accent", "description"):
|
||||||
|
if field in val and val[field] is not None:
|
||||||
|
cur[field] = str(val[field]).strip()
|
||||||
|
pages[pid] = cur
|
||||||
|
copy["socialPages"] = pages
|
||||||
|
|
||||||
|
copy["socialFlags"] = flags
|
||||||
|
copy["socialHiddenSections"] = _hidden_from_sections(flags["sections"])
|
||||||
|
out["modules"] = modules
|
||||||
|
out["copy"] = copy
|
||||||
|
_write_raw(out)
|
||||||
|
return read_social_ops()
|
||||||
327
apps/api/services/ebook_svc/services/social_ugc.py
Normal file
327
apps/api/services/ebook_svc/services/social_ugc.py
Normal file
@ -0,0 +1,327 @@
|
|||||||
|
"""游民社区 UGC 管理 — 直连 social.db(与 nomadro-social 同库)。
|
||||||
|
|
||||||
|
默认路径可通过 SOCIAL_DB_PATH 覆盖;生产:/var/www/nomadro-data/social/social.db
|
||||||
|
只读写 messages / roster / cafe_reviews / gig_apps / feedback,不碰 remote-config catalogs。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sqlite3
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any, Iterator
|
||||||
|
|
||||||
|
from ebook_svc.core.sqlite_util import connect as _connect
|
||||||
|
|
||||||
|
_DEFAULT = Path("/var/www/nomadro-data/social/social.db")
|
||||||
|
SOCIAL_DB_PATH = Path(os.getenv("SOCIAL_DB_PATH", str(_DEFAULT))).resolve()
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def _db(*, readonly: bool = False) -> Iterator[sqlite3.Connection]:
|
||||||
|
SOCIAL_DB_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
if readonly and SOCIAL_DB_PATH.is_file():
|
||||||
|
uri = f"file:{SOCIAL_DB_PATH.as_posix()}?mode=ro"
|
||||||
|
conn = sqlite3.connect(uri, uri=True, timeout=30.0)
|
||||||
|
conn.row_factory = sqlite3.Row
|
||||||
|
else:
|
||||||
|
conn = _connect(SOCIAL_DB_PATH)
|
||||||
|
try:
|
||||||
|
yield conn
|
||||||
|
if not readonly:
|
||||||
|
conn.commit()
|
||||||
|
except Exception:
|
||||||
|
if not readonly:
|
||||||
|
conn.rollback()
|
||||||
|
raise
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def 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,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
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(readonly=True) as c:
|
||||||
|
counts["messages"] = c.execute("SELECT COUNT(*) AS n FROM messages").fetchone()["n"]
|
||||||
|
counts["roster"] = c.execute("SELECT COUNT(*) AS n FROM roster").fetchone()["n"]
|
||||||
|
counts["reviews"] = c.execute("SELECT COUNT(*) AS n FROM cafe_reviews").fetchone()["n"]
|
||||||
|
counts["gigApps"] = c.execute("SELECT COUNT(*) AS n FROM gig_apps").fetchone()["n"]
|
||||||
|
counts["feedback"] = c.execute("SELECT COUNT(*) AS n FROM feedback").fetchone()["n"]
|
||||||
|
except Exception as e:
|
||||||
|
return {**info, "counts": counts, "error": str(e)}
|
||||||
|
return {**info, "counts": counts}
|
||||||
|
|
||||||
|
|
||||||
|
def list_messages(
|
||||||
|
*,
|
||||||
|
channel_id: str = "",
|
||||||
|
q: str = "",
|
||||||
|
limit: int = 100,
|
||||||
|
offset: int = 0,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
limit = max(1, min(int(limit or 100), 500))
|
||||||
|
offset = max(0, int(offset or 0))
|
||||||
|
clauses: list[str] = []
|
||||||
|
params: list[Any] = []
|
||||||
|
if channel_id.strip():
|
||||||
|
clauses.append("channel_id=?")
|
||||||
|
params.append(channel_id.strip())
|
||||||
|
if q.strip():
|
||||||
|
clauses.append("(author LIKE ? OR text LIKE ? OR guest_id LIKE ?)")
|
||||||
|
like = f"%{q.strip()}%"
|
||||||
|
params.extend([like, like, like])
|
||||||
|
where = f" WHERE {' AND '.join(clauses)}" if clauses else ""
|
||||||
|
with _db(readonly=True) as c:
|
||||||
|
total = c.execute(f"SELECT COUNT(*) AS n FROM messages{where}", tuple(params)).fetchone()["n"]
|
||||||
|
rows = c.execute(
|
||||||
|
f"""
|
||||||
|
SELECT id, channel_id, author, text, guest_id, created_at
|
||||||
|
FROM messages{where}
|
||||||
|
ORDER BY created_at DESC, rowid DESC
|
||||||
|
LIMIT ? OFFSET ?
|
||||||
|
""",
|
||||||
|
(*params, limit, offset),
|
||||||
|
).fetchall()
|
||||||
|
items = [
|
||||||
|
{
|
||||||
|
"id": r["id"],
|
||||||
|
"channelId": r["channel_id"],
|
||||||
|
"author": r["author"],
|
||||||
|
"text": r["text"],
|
||||||
|
"guestId": r["guest_id"],
|
||||||
|
"at": r["created_at"],
|
||||||
|
}
|
||||||
|
for r in rows
|
||||||
|
]
|
||||||
|
return {"ok": True, "total": total, "items": items}
|
||||||
|
|
||||||
|
|
||||||
|
def delete_message(message_id: str) -> bool:
|
||||||
|
with _db() as c:
|
||||||
|
cur = c.execute("DELETE FROM messages WHERE id=?", (message_id,))
|
||||||
|
return cur.rowcount > 0
|
||||||
|
|
||||||
|
|
||||||
|
def list_roster(*, q: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]:
|
||||||
|
limit = max(1, min(int(limit or 100), 500))
|
||||||
|
offset = max(0, int(offset or 0))
|
||||||
|
clauses: list[str] = []
|
||||||
|
params: list[Any] = []
|
||||||
|
if q.strip():
|
||||||
|
clauses.append("(name LIKE ? OR city LIKE ? OR title LIKE ? OR guest_id LIKE ? OR bio LIKE ?)")
|
||||||
|
like = f"%{q.strip()}%"
|
||||||
|
params.extend([like, like, like, like, like])
|
||||||
|
where = f" WHERE {' AND '.join(clauses)}" if clauses else ""
|
||||||
|
with _db(readonly=True) as c:
|
||||||
|
total = c.execute(f"SELECT COUNT(*) AS n FROM roster{where}", tuple(params)).fetchone()["n"]
|
||||||
|
rows = c.execute(
|
||||||
|
f"""
|
||||||
|
SELECT guest_id, name, title, city, phone, linktree, skills, bio, updated_at
|
||||||
|
FROM roster{where}
|
||||||
|
ORDER BY updated_at DESC
|
||||||
|
LIMIT ? OFFSET ?
|
||||||
|
""",
|
||||||
|
(*params, limit, offset),
|
||||||
|
).fetchall()
|
||||||
|
items = [
|
||||||
|
{
|
||||||
|
"guestId": r["guest_id"],
|
||||||
|
"name": r["name"],
|
||||||
|
"title": r["title"] or "",
|
||||||
|
"city": r["city"] or "",
|
||||||
|
"phone": r["phone"] or "",
|
||||||
|
"linktree": r["linktree"] or "",
|
||||||
|
"skills": r["skills"] or "",
|
||||||
|
"bio": r["bio"] or "",
|
||||||
|
"updatedAt": r["updated_at"],
|
||||||
|
}
|
||||||
|
for r in rows
|
||||||
|
]
|
||||||
|
return {"ok": True, "total": total, "items": items}
|
||||||
|
|
||||||
|
|
||||||
|
def update_roster(guest_id: str, patch: dict[str, Any]) -> dict[str, Any] | None:
|
||||||
|
with _db() as c:
|
||||||
|
row = c.execute("SELECT * FROM roster WHERE guest_id=?", (guest_id,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
fields = {
|
||||||
|
"name": str(patch.get("name", row["name"] or ""))[:64] or "游民",
|
||||||
|
"title": str(patch.get("title", row["title"] or ""))[:80],
|
||||||
|
"city": str(patch.get("city", row["city"] or ""))[:64],
|
||||||
|
"phone": str(patch.get("phone", row["phone"] or ""))[:32],
|
||||||
|
"linktree": str(patch.get("linktree", row["linktree"] or ""))[:240],
|
||||||
|
"skills": str(patch.get("skills", row["skills"] or ""))[:200],
|
||||||
|
"bio": str(patch.get("bio", row["bio"] or ""))[:2000],
|
||||||
|
}
|
||||||
|
import time
|
||||||
|
|
||||||
|
updated = time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime())
|
||||||
|
c.execute(
|
||||||
|
"""
|
||||||
|
UPDATE roster SET name=?, title=?, city=?, phone=?, linktree=?, skills=?, bio=?, updated_at=?
|
||||||
|
WHERE guest_id=?
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
fields["name"],
|
||||||
|
fields["title"],
|
||||||
|
fields["city"],
|
||||||
|
fields["phone"],
|
||||||
|
fields["linktree"],
|
||||||
|
fields["skills"],
|
||||||
|
fields["bio"],
|
||||||
|
updated,
|
||||||
|
guest_id,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
return {**fields, "guestId": guest_id, "updatedAt": updated}
|
||||||
|
|
||||||
|
|
||||||
|
def delete_roster(guest_id: str) -> bool:
|
||||||
|
with _db() as c:
|
||||||
|
cur = c.execute("DELETE FROM roster WHERE guest_id=?", (guest_id,))
|
||||||
|
return cur.rowcount > 0
|
||||||
|
|
||||||
|
|
||||||
|
def list_reviews(*, cafe_id: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]:
|
||||||
|
limit = max(1, min(int(limit or 100), 500))
|
||||||
|
offset = max(0, int(offset or 0))
|
||||||
|
clauses: list[str] = []
|
||||||
|
params: list[Any] = []
|
||||||
|
if cafe_id.strip():
|
||||||
|
clauses.append("cafe_id=?")
|
||||||
|
params.append(cafe_id.strip())
|
||||||
|
where = f" WHERE {' AND '.join(clauses)}" if clauses else ""
|
||||||
|
with _db(readonly=True) as c:
|
||||||
|
total = c.execute(f"SELECT COUNT(*) AS n FROM cafe_reviews{where}", tuple(params)).fetchone()["n"]
|
||||||
|
rows = c.execute(
|
||||||
|
f"""
|
||||||
|
SELECT id, cafe_id, author, score, text, photo_note, guest_id, created_at
|
||||||
|
FROM cafe_reviews{where}
|
||||||
|
ORDER BY created_at DESC
|
||||||
|
LIMIT ? OFFSET ?
|
||||||
|
""",
|
||||||
|
(*params, limit, offset),
|
||||||
|
).fetchall()
|
||||||
|
items = [
|
||||||
|
{
|
||||||
|
"id": r["id"],
|
||||||
|
"cafeId": r["cafe_id"],
|
||||||
|
"author": r["author"],
|
||||||
|
"score": r["score"],
|
||||||
|
"text": r["text"],
|
||||||
|
"photoNote": r["photo_note"] or "",
|
||||||
|
"guestId": r["guest_id"],
|
||||||
|
"at": r["created_at"],
|
||||||
|
}
|
||||||
|
for r in rows
|
||||||
|
]
|
||||||
|
return {"ok": True, "total": total, "items": items}
|
||||||
|
|
||||||
|
|
||||||
|
def delete_review(review_id: str) -> bool:
|
||||||
|
with _db() as c:
|
||||||
|
cur = c.execute("DELETE FROM cafe_reviews WHERE id=?", (review_id,))
|
||||||
|
return cur.rowcount > 0
|
||||||
|
|
||||||
|
|
||||||
|
def list_gig_apps(*, gig_id: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]:
|
||||||
|
limit = max(1, min(int(limit or 100), 500))
|
||||||
|
offset = max(0, int(offset or 0))
|
||||||
|
clauses: list[str] = []
|
||||||
|
params: list[Any] = []
|
||||||
|
if gig_id.strip():
|
||||||
|
clauses.append("gig_id=?")
|
||||||
|
params.append(gig_id.strip())
|
||||||
|
where = f" WHERE {' AND '.join(clauses)}" if clauses else ""
|
||||||
|
with _db(readonly=True) as c:
|
||||||
|
total = c.execute(f"SELECT COUNT(*) AS n FROM gig_apps{where}", tuple(params)).fetchone()["n"]
|
||||||
|
rows = c.execute(
|
||||||
|
f"""
|
||||||
|
SELECT id, gig_id, name, contact, note, guest_id, created_at
|
||||||
|
FROM gig_apps{where}
|
||||||
|
ORDER BY created_at DESC
|
||||||
|
LIMIT ? OFFSET ?
|
||||||
|
""",
|
||||||
|
(*params, limit, offset),
|
||||||
|
).fetchall()
|
||||||
|
items = [
|
||||||
|
{
|
||||||
|
"id": r["id"],
|
||||||
|
"gigId": r["gig_id"],
|
||||||
|
"name": r["name"],
|
||||||
|
"contact": r["contact"],
|
||||||
|
"note": r["note"] or "",
|
||||||
|
"guestId": r["guest_id"],
|
||||||
|
"at": r["created_at"],
|
||||||
|
}
|
||||||
|
for r in rows
|
||||||
|
]
|
||||||
|
return {"ok": True, "total": total, "items": items}
|
||||||
|
|
||||||
|
|
||||||
|
def delete_gig_app(app_id: str) -> bool:
|
||||||
|
with _db() as c:
|
||||||
|
cur = c.execute("DELETE FROM gig_apps WHERE id=?", (app_id,))
|
||||||
|
return cur.rowcount > 0
|
||||||
|
|
||||||
|
|
||||||
|
def list_feedback(*, limit: int = 100, offset: int = 0) -> dict[str, Any]:
|
||||||
|
limit = max(1, min(int(limit or 100), 500))
|
||||||
|
offset = max(0, int(offset or 0))
|
||||||
|
with _db(readonly=True) as c:
|
||||||
|
total = c.execute("SELECT COUNT(*) AS n FROM feedback").fetchone()["n"]
|
||||||
|
rows = c.execute(
|
||||||
|
"""
|
||||||
|
SELECT id, kind, text, contact, guest_id, created_at
|
||||||
|
FROM feedback
|
||||||
|
ORDER BY created_at DESC
|
||||||
|
LIMIT ? OFFSET ?
|
||||||
|
""",
|
||||||
|
(limit, offset),
|
||||||
|
).fetchall()
|
||||||
|
items = [
|
||||||
|
{
|
||||||
|
"id": r["id"],
|
||||||
|
"kind": r["kind"],
|
||||||
|
"text": r["text"],
|
||||||
|
"contact": r["contact"] or "",
|
||||||
|
"guestId": r["guest_id"],
|
||||||
|
"at": r["created_at"],
|
||||||
|
}
|
||||||
|
for r in rows
|
||||||
|
]
|
||||||
|
return {"ok": True, "total": total, "items": items}
|
||||||
|
|
||||||
|
|
||||||
|
def delete_feedback(fid: str) -> bool:
|
||||||
|
with _db() as c:
|
||||||
|
cur = c.execute("DELETE FROM feedback WHERE id=?", (fid,))
|
||||||
|
return cur.rowcount > 0
|
||||||
@ -667,14 +667,159 @@ class Store:
|
|||||||
tracks = c.execute("SELECT COUNT(*) AS n FROM track_events").fetchone()["n"]
|
tracks = c.execute("SELECT COUNT(*) AS n FROM track_events").fetchone()["n"]
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
return {
|
books = 0
|
||||||
|
try:
|
||||||
|
books = c.execute("SELECT COUNT(*) AS n FROM books").fetchone()["n"]
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
refunded = 0
|
||||||
|
try:
|
||||||
|
refunded = c.execute(
|
||||||
|
"SELECT COUNT(*) AS n FROM orders WHERE lower(status) LIKE '%refund%'"
|
||||||
|
).fetchone()["n"]
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
base = {
|
||||||
"users": users,
|
"users": users,
|
||||||
"unlocks": unlocks,
|
"unlocks": unlocks,
|
||||||
"paid_orders": paid["n"],
|
"paid_orders": paid["n"],
|
||||||
"paid_amount_fen": paid["s"],
|
"paid_amount_fen": paid["s"],
|
||||||
"pending_orders": pending,
|
"pending_orders": pending,
|
||||||
"track_events": tracks,
|
"track_events": tracks,
|
||||||
|
"books": books,
|
||||||
|
"refunded_orders": refunded,
|
||||||
}
|
}
|
||||||
|
base.update(self._stats_series(c))
|
||||||
|
return base
|
||||||
|
|
||||||
|
def _stats_series(self, c: sqlite3.Connection) -> dict[str, Any]:
|
||||||
|
"""最近 14 天成交额 / 订单数 / 埋点(按本地日切)。"""
|
||||||
|
days = 14
|
||||||
|
revenue: list[dict[str, Any]] = []
|
||||||
|
orders: list[dict[str, Any]] = []
|
||||||
|
events: list[dict[str, Any]] = []
|
||||||
|
try:
|
||||||
|
rev_rows = c.execute(
|
||||||
|
"""
|
||||||
|
SELECT date(created_at, 'unixepoch', 'localtime') AS d,
|
||||||
|
COUNT(*) AS n,
|
||||||
|
COALESCE(SUM(amount_fen), 0) AS fen
|
||||||
|
FROM orders
|
||||||
|
WHERE delivered=1
|
||||||
|
AND created_at >= strftime('%s', 'now', ?)
|
||||||
|
GROUP BY d
|
||||||
|
ORDER BY d
|
||||||
|
""",
|
||||||
|
(f"-{days} days",),
|
||||||
|
).fetchall()
|
||||||
|
by_day = {r["d"]: {"n": r["n"], "fen": r["fen"]} for r in rev_rows}
|
||||||
|
except Exception:
|
||||||
|
by_day = {}
|
||||||
|
try:
|
||||||
|
ev_rows = c.execute(
|
||||||
|
"""
|
||||||
|
SELECT date(ts, 'unixepoch', 'localtime') AS d, COUNT(*) AS n
|
||||||
|
FROM track_events
|
||||||
|
WHERE ts >= strftime('%s', 'now', ?)
|
||||||
|
GROUP BY d
|
||||||
|
ORDER BY d
|
||||||
|
""",
|
||||||
|
(f"-{days} days",),
|
||||||
|
).fetchall()
|
||||||
|
ev_by = {r["d"]: r["n"] for r in ev_rows}
|
||||||
|
except Exception:
|
||||||
|
ev_by = {}
|
||||||
|
|
||||||
|
import datetime as _dt
|
||||||
|
|
||||||
|
today = _dt.date.today()
|
||||||
|
for i in range(days - 1, -1, -1):
|
||||||
|
d = (today - _dt.timedelta(days=i)).isoformat()
|
||||||
|
cell = by_day.get(d) or {"n": 0, "fen": 0}
|
||||||
|
revenue.append({"date": d, "amountFen": int(cell["fen"] or 0)})
|
||||||
|
orders.append({"date": d, "count": int(cell["n"] or 0)})
|
||||||
|
events.append({"date": d, "count": int(ev_by.get(d) or 0)})
|
||||||
|
|
||||||
|
top_events: list[dict[str, Any]] = []
|
||||||
|
try:
|
||||||
|
for r in c.execute(
|
||||||
|
"""
|
||||||
|
SELECT name, COUNT(*) AS n FROM track_events
|
||||||
|
WHERE ts >= strftime('%s', 'now', '-7 days')
|
||||||
|
GROUP BY name ORDER BY n DESC LIMIT 8
|
||||||
|
"""
|
||||||
|
).fetchall():
|
||||||
|
top_events.append({"name": r["name"], "count": r["n"]})
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
return {
|
||||||
|
"series": {"revenue": revenue, "orders": orders, "events": events},
|
||||||
|
"topEvents": top_events,
|
||||||
|
}
|
||||||
|
|
||||||
|
def mark_order_status(self, out_trade_no: str, status: str) -> dict[str, Any] | None:
|
||||||
|
"""运营标记:cancel / refunded(不直连微信退款,只改本地状态)。"""
|
||||||
|
st = (status or "").strip().lower()
|
||||||
|
if st not in {"cancel", "cancelled", "refunded", "pending", "paid"}:
|
||||||
|
raise ValueError("unsupported status")
|
||||||
|
if st == "cancel":
|
||||||
|
st = "cancelled"
|
||||||
|
with self.conn() as c:
|
||||||
|
row = c.execute(
|
||||||
|
"SELECT * FROM orders WHERE out_trade_no=?", (out_trade_no,)
|
||||||
|
).fetchone()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
delivered = 0 if st in {"cancelled", "refunded", "pending"} else int(row["delivered"] or 0)
|
||||||
|
if st == "paid":
|
||||||
|
delivered = 1
|
||||||
|
c.execute(
|
||||||
|
"UPDATE orders SET status=?, delivered=? WHERE out_trade_no=?",
|
||||||
|
(st, delivered, out_trade_no),
|
||||||
|
)
|
||||||
|
row = c.execute(
|
||||||
|
"SELECT * FROM orders WHERE out_trade_no=?", (out_trade_no,)
|
||||||
|
).fetchone()
|
||||||
|
return dict(row) if row else None
|
||||||
|
|
||||||
|
def create_book(self, book_id: str, patch: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||||
|
bid = (book_id or "").strip()[:64]
|
||||||
|
if not bid:
|
||||||
|
raise ValueError("book_id required")
|
||||||
|
if self.get_book(bid):
|
||||||
|
raise ValueError("book already exists")
|
||||||
|
patch = dict(patch or {})
|
||||||
|
free = bool(patch.pop("free", True))
|
||||||
|
patch.pop("id", None)
|
||||||
|
patch.pop("offer_key", None)
|
||||||
|
title = str(patch.get("title") or bid)[:120]
|
||||||
|
book = self.ensure_book(bid, title=title, free=free)
|
||||||
|
allowed = {
|
||||||
|
"title",
|
||||||
|
"subtitle",
|
||||||
|
"author",
|
||||||
|
"cover_emoji",
|
||||||
|
"description",
|
||||||
|
"tags",
|
||||||
|
"price_fen",
|
||||||
|
"product_id",
|
||||||
|
"unlock_percent",
|
||||||
|
"rating",
|
||||||
|
"chapters",
|
||||||
|
}
|
||||||
|
clean = {k: v for k, v in patch.items() if k in allowed and v is not None}
|
||||||
|
if clean:
|
||||||
|
return self.update_book(bid, clean)
|
||||||
|
return book
|
||||||
|
|
||||||
|
def delete_book(self, book_id: str) -> bool:
|
||||||
|
bid = (book_id or "").strip()
|
||||||
|
if not bid:
|
||||||
|
return False
|
||||||
|
with self.conn() as c:
|
||||||
|
cur = c.execute("DELETE FROM books WHERE id=?", (bid,))
|
||||||
|
return cur.rowcount > 0
|
||||||
|
|
||||||
def list_track_events(
|
def list_track_events(
|
||||||
self,
|
self,
|
||||||
|
|||||||
@ -26,6 +26,7 @@ MODULE_KEYS = (
|
|||||||
"nav",
|
"nav",
|
||||||
"book",
|
"book",
|
||||||
"community",
|
"community",
|
||||||
|
"social",
|
||||||
"vip",
|
"vip",
|
||||||
"destinations",
|
"destinations",
|
||||||
"meetups",
|
"meetups",
|
||||||
@ -36,6 +37,13 @@ DEFAULT_MODULES: dict[str, dict[str, Any]] = {
|
|||||||
"nav": {"enabled": True, "title": "出海导航", "tabLabel": "导航"},
|
"nav": {"enabled": True, "title": "出海导航", "tabLabel": "导航"},
|
||||||
"book": {"enabled": True, "title": "数字游民小册", "tabLabel": "小册"},
|
"book": {"enabled": True, "title": "数字游民小册", "tabLabel": "小册"},
|
||||||
"community": {"enabled": True, "title": "旅居社群", "tabLabel": "社群"},
|
"community": {"enabled": True, "title": "旅居社群", "tabLabel": "社群"},
|
||||||
|
# 对齐线上 remote-config:游民社区 / pages/social/index;缺省开启,写入只改 enabled
|
||||||
|
"social": {
|
||||||
|
"enabled": True,
|
||||||
|
"title": "游民社区",
|
||||||
|
"tabLabel": "社区",
|
||||||
|
"note": "Taro 原生 pages/social · 开关不碰业务库",
|
||||||
|
},
|
||||||
"vip": {"enabled": False, "title": "会员中心"},
|
"vip": {"enabled": False, "title": "会员中心"},
|
||||||
"destinations": {"enabled": True, "title": "目的地"},
|
"destinations": {"enabled": True, "title": "目的地"},
|
||||||
"meetups": {"enabled": True, "title": "活动"},
|
"meetups": {"enabled": True, "title": "活动"},
|
||||||
@ -80,6 +88,12 @@ def _write_raw(out: dict[str, Any]) -> None:
|
|||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
path.write_text(json.dumps(out, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
path.write_text(json.dumps(out, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||||
|
try:
|
||||||
|
from ebook_svc.services.config_live import notify_config_written
|
||||||
|
|
||||||
|
notify_config_written(out)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
def _norm_mod(raw: Any, fallback: dict[str, Any]) -> dict[str, Any]:
|
def _norm_mod(raw: Any, fallback: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
|||||||
@ -8,7 +8,7 @@ import {
|
|||||||
startRemoteConfigLiveSync,
|
startRemoteConfigLiveSync,
|
||||||
} from './services/remoteConfig'
|
} from './services/remoteConfig'
|
||||||
import { startH5RemLock } from './utils/h5RemLock'
|
import { startH5RemLock } from './utils/h5RemLock'
|
||||||
import { applyH5Theme, getStoredH5Theme } from './utils/h5Theme'
|
import { applyH5Theme } from './utils/h5Theme'
|
||||||
import { startPresenceHeartbeat } from './utils/presence'
|
import { startPresenceHeartbeat } from './utils/presence'
|
||||||
import { startVipAccessLiveSync } from './utils/vipAccess'
|
import { startVipAccessLiveSync } from './utils/vipAccess'
|
||||||
import DebugFab from './components/DebugFab'
|
import DebugFab from './components/DebugFab'
|
||||||
@ -20,9 +20,7 @@ function App({ children }: PropsWithChildren) {
|
|||||||
useLaunch(() => {
|
useLaunch(() => {
|
||||||
trackAppLaunch()
|
trackAppLaunch()
|
||||||
void loadRemoteConfig(true)
|
void loadRemoteConfig(true)
|
||||||
if (process.env.TARO_ENV === 'h5') {
|
applyH5Theme('dark')
|
||||||
applyH5Theme(getStoredH5Theme())
|
|
||||||
}
|
|
||||||
// 小程序 AI 接力:账号卡片进入页时同步 payload(仅 weapp + 基础库支持时)
|
// 小程序 AI 接力:账号卡片进入页时同步 payload(仅 weapp + 基础库支持时)
|
||||||
if (process.env.TARO_ENV === 'weapp') {
|
if (process.env.TARO_ENV === 'weapp') {
|
||||||
try {
|
try {
|
||||||
@ -79,7 +77,7 @@ function App({ children }: PropsWithChildren) {
|
|||||||
startSide()
|
startSide()
|
||||||
}
|
}
|
||||||
if (process.env.TARO_ENV === 'h5') {
|
if (process.env.TARO_ENV === 'h5') {
|
||||||
applyH5Theme(getStoredH5Theme())
|
applyH5Theme('dark')
|
||||||
}
|
}
|
||||||
return () => {
|
return () => {
|
||||||
if (defer) clearTimeout(defer)
|
if (defer) clearTimeout(defer)
|
||||||
|
|||||||
@ -1,26 +1,90 @@
|
|||||||
import { useMemo, useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import { View, Text } from '@tarojs/components'
|
import { View, Text } from '@tarojs/components'
|
||||||
import { AUDIT_BOOK_CHAPTERS, AUDIT_BOOK_META } from '../data/auditBook'
|
import { AUDIT_BOOK_META } from '../data/auditBook'
|
||||||
|
import { AuditPlainBody } from './AuditPlainBody'
|
||||||
|
import {
|
||||||
|
fetchAuditRead,
|
||||||
|
getAuditOfflineRead,
|
||||||
|
type ReadPayload,
|
||||||
|
} from '../services/ebookApi'
|
||||||
import { safePx } from '../utils/safeArea'
|
import { safePx } from '../utils/safeArea'
|
||||||
|
|
||||||
const FALLBACK_BODY =
|
|
||||||
'欢迎阅读《数字游民入门指南》。这是一本面向普通人的生活方式小册:讲如何在合法合规的前提下,把工作做得更灵活,把生活安排得更从容。'
|
|
||||||
|
|
||||||
const block = (extra?: Record<string, string | number>) => ({
|
const block = (extra?: Record<string, string | number>) => ({
|
||||||
display: 'block' as const,
|
display: 'block' as const,
|
||||||
...extra,
|
...extra,
|
||||||
})
|
})
|
||||||
|
|
||||||
/** 提审小册:包内数据 + View/Text + safePx,无网络 / 无 RichText / 无 scss */
|
type Props = {
|
||||||
export function AuditBookScreen(_props?: { bookId?: string }) {
|
bookId?: string
|
||||||
const chapters = AUDIT_BOOK_CHAPTERS
|
onBack?: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 提审阅读:优先拉后台正文;包内写死章只在服务端完全失联时兜底。
|
||||||
|
* 留在主包内联,避免 reader 分包未预载黑屏。
|
||||||
|
*/
|
||||||
|
export function AuditBookScreen({ bookId = 'audit', onBack }: Props) {
|
||||||
|
const id = bookId || 'audit'
|
||||||
|
const [payload, setPayload] = useState<ReadPayload | null>(null)
|
||||||
|
const [fromOffline, setFromOffline] = useState(false)
|
||||||
|
const [loading, setLoading] = useState(true)
|
||||||
const [idx, setIdx] = useState(0)
|
const [idx, setIdx] = useState(0)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let cancelled = false
|
||||||
|
setLoading(true)
|
||||||
|
setPayload(null)
|
||||||
|
setIdx(0)
|
||||||
|
void fetchAuditRead(id)
|
||||||
|
.then((res) => {
|
||||||
|
if (cancelled) return
|
||||||
|
setPayload(res.payload)
|
||||||
|
setFromOffline(res.fromOffline)
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
if (cancelled) return
|
||||||
|
setPayload(getAuditOfflineRead(id))
|
||||||
|
setFromOffline(true)
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
if (!cancelled) setLoading(false)
|
||||||
|
})
|
||||||
|
return () => {
|
||||||
|
cancelled = true
|
||||||
|
}
|
||||||
|
}, [id])
|
||||||
|
|
||||||
|
const chapters = payload?.chapters || []
|
||||||
|
const book = payload?.book
|
||||||
const safeIdx = Math.min(Math.max(0, idx), Math.max(0, chapters.length - 1))
|
const safeIdx = Math.min(Math.max(0, idx), Math.max(0, chapters.length - 1))
|
||||||
const chapter = chapters[safeIdx]
|
const chapter = chapters[safeIdx]
|
||||||
const lines = useMemo(() => {
|
|
||||||
const plain = markdownToPlain(chapter?.content || '') || FALLBACK_BODY
|
if (loading && !payload) {
|
||||||
return plain.split('\n')
|
return (
|
||||||
}, [chapter?.content])
|
<View
|
||||||
|
style={{
|
||||||
|
minHeight: '100vh',
|
||||||
|
width: '100%',
|
||||||
|
backgroundColor: '#0c0b12',
|
||||||
|
paddingTop: safePx(48),
|
||||||
|
paddingLeft: safePx(16),
|
||||||
|
paddingRight: safePx(16),
|
||||||
|
boxSizing: 'border-box',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{onBack ? (
|
||||||
|
<View onClick={onBack} style={{ marginBottom: safePx(16) }}>
|
||||||
|
<Text style={block({ fontSize: safePx(14), color: '#4ecdc4' })}>← 返回封面</Text>
|
||||||
|
</View>
|
||||||
|
) : null}
|
||||||
|
<Text style={block({ fontSize: safePx(15), color: '#94a3b8' })}>正在从服务器加载小册…</Text>
|
||||||
|
</View>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const title = book?.title || AUDIT_BOOK_META.title
|
||||||
|
const subtitle = book?.subtitle || AUDIT_BOOK_META.subtitle
|
||||||
|
const emoji = book?.cover_emoji || AUDIT_BOOK_META.cover_emoji
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<View
|
<View
|
||||||
@ -35,8 +99,16 @@ export function AuditBookScreen(_props?: { bookId?: string }) {
|
|||||||
boxSizing: 'border-box',
|
boxSizing: 'border-box',
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
|
{onBack ? (
|
||||||
|
<View onClick={onBack} style={{ marginBottom: safePx(8) }}>
|
||||||
|
<Text style={block({ fontSize: safePx(14), color: '#4ecdc4', lineHeight: '2' })}>
|
||||||
|
← 返回封面
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
) : null}
|
||||||
|
|
||||||
<Text style={block({ fontSize: safePx(28), marginBottom: safePx(8), color: '#f8fafc' })}>
|
<Text style={block({ fontSize: safePx(28), marginBottom: safePx(8), color: '#f8fafc' })}>
|
||||||
{AUDIT_BOOK_META.cover_emoji}
|
{emoji}
|
||||||
</Text>
|
</Text>
|
||||||
<Text
|
<Text
|
||||||
style={block({
|
style={block({
|
||||||
@ -46,19 +118,40 @@ export function AuditBookScreen(_props?: { bookId?: string }) {
|
|||||||
lineHeight: '1.35',
|
lineHeight: '1.35',
|
||||||
})}
|
})}
|
||||||
>
|
>
|
||||||
{AUDIT_BOOK_META.title}
|
{title}
|
||||||
</Text>
|
</Text>
|
||||||
<Text
|
<Text
|
||||||
style={block({
|
style={block({
|
||||||
fontSize: safePx(13),
|
fontSize: safePx(13),
|
||||||
color: '#94a3b8',
|
color: '#94a3b8',
|
||||||
marginTop: safePx(8),
|
marginTop: safePx(8),
|
||||||
marginBottom: safePx(16),
|
marginBottom: safePx(8),
|
||||||
lineHeight: '1.45',
|
lineHeight: '1.45',
|
||||||
})}
|
})}
|
||||||
>
|
>
|
||||||
{AUDIT_BOOK_META.subtitle}
|
{subtitle}
|
||||||
</Text>
|
</Text>
|
||||||
|
{fromOffline ? (
|
||||||
|
<Text
|
||||||
|
style={block({
|
||||||
|
fontSize: safePx(12),
|
||||||
|
color: '#f59e0b',
|
||||||
|
marginBottom: safePx(12),
|
||||||
|
})}
|
||||||
|
>
|
||||||
|
离线模式 · 本地兜底正文(服务器暂不可用)
|
||||||
|
</Text>
|
||||||
|
) : (
|
||||||
|
<Text
|
||||||
|
style={block({
|
||||||
|
fontSize: safePx(12),
|
||||||
|
color: '#64748b',
|
||||||
|
marginBottom: safePx(12),
|
||||||
|
})}
|
||||||
|
>
|
||||||
|
已同步服务器内容
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
|
||||||
<View style={{ marginBottom: safePx(16) }}>
|
<View style={{ marginBottom: safePx(16) }}>
|
||||||
{chapters.map((c, i) => (
|
{chapters.map((c, i) => (
|
||||||
@ -93,23 +186,7 @@ export function AuditBookScreen(_props?: { bookId?: string }) {
|
|||||||
>
|
>
|
||||||
{`${safeIdx + 1}. ${chapter?.title || '正文'}`}
|
{`${safeIdx + 1}. ${chapter?.title || '正文'}`}
|
||||||
</Text>
|
</Text>
|
||||||
{lines.map((line, i) =>
|
<AuditPlainBody markdown={chapter?.content || ''} />
|
||||||
line ? (
|
|
||||||
<Text
|
|
||||||
key={`b-${i}`}
|
|
||||||
style={block({
|
|
||||||
fontSize: safePx(15),
|
|
||||||
color: '#cbd5e1',
|
|
||||||
lineHeight: '1.75',
|
|
||||||
marginBottom: safePx(6),
|
|
||||||
})}
|
|
||||||
>
|
|
||||||
{line}
|
|
||||||
</Text>
|
|
||||||
) : (
|
|
||||||
<View key={`b-${i}`} style={{ height: safePx(8) }} />
|
|
||||||
),
|
|
||||||
)}
|
|
||||||
</View>
|
</View>
|
||||||
|
|
||||||
<View
|
<View
|
||||||
@ -136,7 +213,7 @@ export function AuditBookScreen(_props?: { bookId?: string }) {
|
|||||||
</Text>
|
</Text>
|
||||||
</View>
|
</View>
|
||||||
<Text style={block({ fontSize: safePx(13), color: '#64748b' })}>
|
<Text style={block({ fontSize: safePx(13), color: '#64748b' })}>
|
||||||
{`${safeIdx + 1}/${chapters.length}`}
|
{`${safeIdx + 1}/${chapters.length || 1}`}
|
||||||
</Text>
|
</Text>
|
||||||
<View
|
<View
|
||||||
onClick={() => setIdx((v) => Math.min(chapters.length - 1, v + 1))}
|
onClick={() => setIdx((v) => Math.min(chapters.length - 1, v + 1))}
|
||||||
@ -155,47 +232,3 @@ export function AuditBookScreen(_props?: { bookId?: string }) {
|
|||||||
</View>
|
</View>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function stripInline(s: string) {
|
|
||||||
return s
|
|
||||||
.replace(/\*\*(.+?)\*\*/g, '$1')
|
|
||||||
.replace(/\*(.+?)\*/g, '$1')
|
|
||||||
.replace(/`([^`]+)`/g, '$1')
|
|
||||||
.replace(/\[(.+?)\]\((https?:\/\/.+?)\)/g, '$1')
|
|
||||||
}
|
|
||||||
|
|
||||||
function markdownToPlain(markdown: string): string {
|
|
||||||
const raw = (markdown || '').replace(/\r\n/g, '\n').split('\n')
|
|
||||||
const out: string[] = []
|
|
||||||
for (const line of raw) {
|
|
||||||
const trimmed = line.trim()
|
|
||||||
if (!trimmed) {
|
|
||||||
if (out.length && out[out.length - 1] !== '') out.push('')
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if (/^---+$/.test(trimmed)) continue
|
|
||||||
const heading = /^(#{1,3})\s+(.+)$/.exec(trimmed)
|
|
||||||
if (heading) {
|
|
||||||
out.push(stripInline(heading[2]))
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
const quote = /^>\s?(.*)$/.exec(trimmed)
|
|
||||||
if (quote) {
|
|
||||||
out.push(stripInline(quote[1]))
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
const ol = /^\d+\.\s+(.+)$/.exec(trimmed)
|
|
||||||
if (ol) {
|
|
||||||
out.push(`${ol[0].match(/^\d+/)?.[0] || '·'}. ${stripInline(ol[1])}`)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
const ul = /^[-*]\s+(.+)$/.exec(trimmed)
|
|
||||||
if (ul) {
|
|
||||||
out.push(`· ${stripInline(ul[1])}`)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if (/^\|?\s*-{2,}/.test(trimmed)) continue
|
|
||||||
out.push(stripInline(trimmed.replace(/\|/g, ' ')))
|
|
||||||
}
|
|
||||||
return out.join('\n').replace(/\n{3,}/g, '\n\n').trim()
|
|
||||||
}
|
|
||||||
|
|||||||
49
apps/miniprogram/h5/src/components/SocialPageGate.tsx
Normal file
49
apps/miniprogram/h5/src/components/SocialPageGate.tsx
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
import { useEffect, useState, type ReactNode } from 'react'
|
||||||
|
import { View, Text } from '@tarojs/components'
|
||||||
|
import {
|
||||||
|
getCachedRemoteConfig,
|
||||||
|
isModuleEnabled,
|
||||||
|
loadRemoteConfig,
|
||||||
|
subscribeRemoteConfig,
|
||||||
|
} from '@/services/remoteConfig'
|
||||||
|
import { isSocialPageEnabled, resolveSocialOps, type SocialPageKey } from '@/utils/socialOps'
|
||||||
|
|
||||||
|
/** 社区子页闸门:modules.social + socialFlags.pages.* */
|
||||||
|
export function SocialPageGate({
|
||||||
|
pageKey,
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
pageKey: SocialPageKey
|
||||||
|
children: ReactNode
|
||||||
|
}) {
|
||||||
|
const [ok, setOk] = useState(() => {
|
||||||
|
const cfg = getCachedRemoteConfig()
|
||||||
|
return isModuleEnabled(cfg, 'social') && isSocialPageEnabled(resolveSocialOps(cfg), pageKey)
|
||||||
|
})
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let alive = true
|
||||||
|
const apply = () => {
|
||||||
|
const cfg = getCachedRemoteConfig()
|
||||||
|
if (!alive) return
|
||||||
|
setOk(isModuleEnabled(cfg, 'social') && isSocialPageEnabled(resolveSocialOps(cfg), pageKey))
|
||||||
|
}
|
||||||
|
const unsub = subscribeRemoteConfig(() => apply())
|
||||||
|
void loadRemoteConfig(true).finally(apply)
|
||||||
|
return () => {
|
||||||
|
alive = false
|
||||||
|
unsub()
|
||||||
|
}
|
||||||
|
}, [pageKey])
|
||||||
|
|
||||||
|
if (!ok) {
|
||||||
|
return (
|
||||||
|
<View className='sub'>
|
||||||
|
<Text className='h'>暂时无法打开</Text>
|
||||||
|
<Text className='p'>该社区页面暂未开放,稍后再来看看吧。</Text>
|
||||||
|
</View>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return <>{children}</>
|
||||||
|
}
|
||||||
@ -126,11 +126,11 @@ export type WeappBookAudit = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 包内种子:提审期默认开(首屏不等远程配置)。
|
* 包内种子:默认关提审(与后台 DEFAULT 一致)。
|
||||||
* 审过之后台 platforms.weapp.bookAudit.reviewMode=false 覆盖即可。
|
* 线上以 platforms.weapp.bookAudit 覆盖;勿在客户端写死开着导致后台关了界面仍提审。
|
||||||
*/
|
*/
|
||||||
export const DEFAULT_BOOK_AUDIT: WeappBookAudit = {
|
export const DEFAULT_BOOK_AUDIT: WeappBookAudit = {
|
||||||
reviewMode: true,
|
reviewMode: false,
|
||||||
bookId: 'audit',
|
bookId: 'audit',
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
27
apps/miniprogram/h5/src/hooks/useRemoteConfig.ts
Normal file
27
apps/miniprogram/h5/src/hooks/useRemoteConfig.ts
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
import type { NomadroRemoteConfig } from '@/data/remoteConfig.defaults'
|
||||||
|
import {
|
||||||
|
getCachedRemoteConfig,
|
||||||
|
loadRemoteConfig,
|
||||||
|
subscribeRemoteConfig,
|
||||||
|
} from '@/services/remoteConfig'
|
||||||
|
|
||||||
|
/** 页面级:订阅远程配置,后台开关约 2s 内热更新 */
|
||||||
|
export function useRemoteConfig() {
|
||||||
|
const [config, setConfig] = useState<NomadroRemoteConfig>(() => getCachedRemoteConfig())
|
||||||
|
const [fromOffline, setFromOffline] = useState(false)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const unsub = subscribeRemoteConfig((r) => {
|
||||||
|
setConfig(r.config)
|
||||||
|
setFromOffline(r.fromOffline)
|
||||||
|
})
|
||||||
|
void loadRemoteConfig(true).then((r) => {
|
||||||
|
setConfig(r.config)
|
||||||
|
setFromOffline(r.fromOffline)
|
||||||
|
})
|
||||||
|
return unsub
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
return { config, fromOffline }
|
||||||
|
}
|
||||||
@ -5,6 +5,8 @@ import { createSocialRequestId, getSocialGuestId, socialApi, type SocialChatMess
|
|||||||
import { connectChatRealtime } from '@/services/socialRealtime'
|
import { connectChatRealtime } from '@/services/socialRealtime'
|
||||||
import { mergeChatMessages } from '@/services/socialChatState'
|
import { mergeChatMessages } from '@/services/socialChatState'
|
||||||
import { readSocialLocal, writeSocialLocal } from '@/services/socialLocal'
|
import { readSocialLocal, writeSocialLocal } from '@/services/socialLocal'
|
||||||
|
import { getCachedRemoteConfig } from '@/services/remoteConfig'
|
||||||
|
import { isSocialFeatureEnabled, resolveSocialOps } from '@/utils/socialOps'
|
||||||
|
|
||||||
export type ChatLinkStatus = 'connecting' | 'live' | 'polling' | 'offline'
|
export type ChatLinkStatus = 'connecting' | 'live' | 'polling' | 'offline'
|
||||||
|
|
||||||
@ -79,16 +81,24 @@ export function useSocialChat(channelId: string) {
|
|||||||
const timer = setInterval(() => {
|
const timer = setInterval(() => {
|
||||||
if (Date.now() >= nextRefresh) void refresh()
|
if (Date.now() >= nextRefresh) void refresh()
|
||||||
}, 8000)
|
}, 8000)
|
||||||
void connectChatRealtime(channelId, (item) => {
|
const realtimeOn = isSocialFeatureEnabled(
|
||||||
if (cancelled) return
|
resolveSocialOps(getCachedRemoteConfig()),
|
||||||
setMessages((current) => mergeChatMessages(current, [item], guest))
|
'chatRealtime',
|
||||||
}, (connected) => {
|
)
|
||||||
realtime = connected
|
if (realtimeOn) {
|
||||||
if (!cancelled) setStatus(connected ? 'live' : 'polling')
|
void connectChatRealtime(channelId, (item) => {
|
||||||
}).then((connection) => {
|
if (cancelled) return
|
||||||
if (cancelled) connection?.disconnect()
|
setMessages((current) => mergeChatMessages(current, [item], guest))
|
||||||
else stopWs = connection?.disconnect
|
}, (connected) => {
|
||||||
}).catch(() => { if (!cancelled) setStatus('polling') })
|
realtime = connected
|
||||||
|
if (!cancelled) setStatus(connected ? 'live' : 'polling')
|
||||||
|
}).then((connection) => {
|
||||||
|
if (cancelled) connection?.disconnect()
|
||||||
|
else stopWs = connection?.disconnect
|
||||||
|
}).catch(() => { if (!cancelled) setStatus('polling') })
|
||||||
|
} else if (!cancelled) {
|
||||||
|
setStatus('polling')
|
||||||
|
}
|
||||||
return () => {
|
return () => {
|
||||||
cancelled = true
|
cancelled = true
|
||||||
mounted.current = false
|
mounted.current = false
|
||||||
|
|||||||
@ -1,6 +1,13 @@
|
|||||||
import { useEffect, useMemo, useState } from 'react'
|
import { useEffect, useMemo, useState } from 'react'
|
||||||
import { getCachedRemoteConfig, subscribeRemoteConfig } from '@/services/remoteConfig'
|
import { getCachedRemoteConfig, subscribeRemoteConfig } from '@/services/remoteConfig'
|
||||||
import { DEFAULT_PROMO, MOCK_ROSTER, SEED_CAFES, SEED_EBOOKS, SEED_GIGS, SEED_MEETUPS, SEED_VIDEOS, SOCIAL_COPY, type SocialLandingCopy } from '@/data/socialSeed'
|
import { DEFAULT_PROMO, MOCK_ROSTER, SEED_CAFES, SEED_EBOOKS, SEED_GIGS, SEED_MEETUPS, SEED_VIDEOS, SOCIAL_COPY, type SocialLandingCopy } from '@/data/socialSeed'
|
||||||
|
import {
|
||||||
|
isSocialButtonEnabled,
|
||||||
|
isSocialFeatureEnabled,
|
||||||
|
isSocialPageEnabled,
|
||||||
|
isSocialSectionEnabled,
|
||||||
|
resolveSocialOps,
|
||||||
|
} from '@/utils/socialOps'
|
||||||
|
|
||||||
function catalog<T>(value: unknown, fallback: T[], valid: (row: any) => boolean): T[] {
|
function catalog<T>(value: unknown, fallback: T[], valid: (row: any) => boolean): T[] {
|
||||||
if (!Array.isArray(value)) return fallback
|
if (!Array.isArray(value)) return fallback
|
||||||
@ -25,11 +32,20 @@ export function useSocialContent() {
|
|||||||
const value = config.copy[key] ?? source.copy?.[key]
|
const value = config.copy[key] ?? source.copy?.[key]
|
||||||
if (typeof value === 'string') copy[key] = value
|
if (typeof value === 'string') copy[key] = value
|
||||||
}
|
}
|
||||||
|
const ops = resolveSocialOps(config)
|
||||||
|
const hiddenSections = (Object.keys(ops.sections) as Array<keyof typeof ops.sections>).filter(
|
||||||
|
(key) => !ops.sections[key],
|
||||||
|
)
|
||||||
return {
|
return {
|
||||||
copy,
|
copy,
|
||||||
pages: config.copy.socialPages || {},
|
pages: config.copy.socialPages || {},
|
||||||
promoUrl: typeof config.copy.socialPromoUrl === 'string' ? config.copy.socialPromoUrl : typeof source.promoUrl === 'string' ? source.promoUrl : DEFAULT_PROMO,
|
promoUrl: typeof config.copy.socialPromoUrl === 'string' ? config.copy.socialPromoUrl : typeof source.promoUrl === 'string' ? source.promoUrl : DEFAULT_PROMO,
|
||||||
hiddenSections: Array.isArray(config.copy.socialHiddenSections) ? config.copy.socialHiddenSections.filter((key) => typeof key === 'string') : (Array.isArray(source.hiddenSections) ? source.hiddenSections : []),
|
hiddenSections,
|
||||||
|
ops,
|
||||||
|
pageOn: (key: Parameters<typeof isSocialPageEnabled>[1]) => isSocialPageEnabled(ops, key),
|
||||||
|
sectionOn: (key: Parameters<typeof isSocialSectionEnabled>[1]) => isSocialSectionEnabled(ops, key),
|
||||||
|
featureOn: (key: Parameters<typeof isSocialFeatureEnabled>[1]) => isSocialFeatureEnabled(ops, key),
|
||||||
|
buttonOn: (key: Parameters<typeof isSocialButtonEnabled>[1]) => isSocialButtonEnabled(ops, key),
|
||||||
roster: catalog(source.roster, MOCK_ROSTER, (r) => text(r, ['name', 'title', 'city', 'bio', 'lookingFor', 'avatar']) && tags(r) && (!r.gallery || (Array.isArray(r.gallery) && r.gallery.every((url: unknown) => typeof url === 'string'))) && (!r.languages || (Array.isArray(r.languages) && r.languages.every((value: unknown) => typeof value === 'string')))),
|
roster: catalog(source.roster, MOCK_ROSTER, (r) => text(r, ['name', 'title', 'city', 'bio', 'lookingFor', 'avatar']) && tags(r) && (!r.gallery || (Array.isArray(r.gallery) && r.gallery.every((url: unknown) => typeof url === 'string'))) && (!r.languages || (Array.isArray(r.languages) && r.languages.every((value: unknown) => typeof value === 'string')))),
|
||||||
gigs: catalog(source.gigs, SEED_GIGS, (r) => text(r, ['title', 'role', 'pay']) && tags(r)),
|
gigs: catalog(source.gigs, SEED_GIGS, (r) => text(r, ['title', 'role', 'pay']) && tags(r)),
|
||||||
meetups: catalog(source.meetups, SEED_MEETUPS, (r) => text(r, ['title', 'city', 'date', 'time', 'mirotalkRoom', 'channelId'])),
|
meetups: catalog(source.meetups, SEED_MEETUPS, (r) => text(r, ['title', 'city', 'date', 'time', 'mirotalkRoom', 'channelId'])),
|
||||||
|
|||||||
@ -5,14 +5,8 @@
|
|||||||
*/
|
*/
|
||||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||||
import { Button } from '@tarojs/components'
|
import { Button } from '@tarojs/components'
|
||||||
import { useDidShow, useLoad } from '@tarojs/taro'
|
import Taro, { useDidShow, useLoad } from '@tarojs/taro'
|
||||||
import {
|
import { fetchBook, type BookDetail } from '../../services/ebookApi'
|
||||||
fetchBook,
|
|
||||||
fetchRead,
|
|
||||||
getAuditOfflineRead,
|
|
||||||
type BookDetail,
|
|
||||||
type ReadPayload,
|
|
||||||
} from '../../services/ebookApi'
|
|
||||||
import { COVER_BOOK } from '../../data/coverBook'
|
import { COVER_BOOK } from '../../data/coverBook'
|
||||||
import {
|
import {
|
||||||
formatAgo,
|
formatAgo,
|
||||||
@ -112,7 +106,7 @@ const CHIP_TAGS = COVER_BOOK.viralTags.slice(0, 3)
|
|||||||
|
|
||||||
function BookPageInner() {
|
function BookPageInner() {
|
||||||
const theme = useNomadroTheme()
|
const theme = useNomadroTheme()
|
||||||
// 封面视觉一律 COVER_BOOK(对齐 H5);解锁/章节仍可走 API 进阅读器
|
// 封面视觉:正式 COVER_BOOK;提审时用线上 audit 书名(失联才兜底文案)
|
||||||
const [book, setBook] = useState<BookDetail | null>(coverAsBookDetail())
|
const [book, setBook] = useState<BookDetail | null>(coverAsBookDetail())
|
||||||
const [apiBook, setApiBook] = useState<BookDetail | null>(null)
|
const [apiBook, setApiBook] = useState<BookDetail | null>(null)
|
||||||
const [loading, setLoading] = useState(false)
|
const [loading, setLoading] = useState(false)
|
||||||
@ -121,32 +115,9 @@ function BookPageInner() {
|
|||||||
const [tw, setTw] = useState('')
|
const [tw, setTw] = useState('')
|
||||||
const [audit, setAudit] = useState(() => resolveBookAudit(getCachedRemoteConfig()))
|
const [audit, setAudit] = useState(() => resolveBookAudit(getCachedRemoteConfig()))
|
||||||
const auditKeyRef = useRef(`${audit.reviewMode}:${audit.bookId}`)
|
const auditKeyRef = useRef(`${audit.reviewMode}:${audit.bookId}`)
|
||||||
// 提审:本页内联正文(不跳 reader 分包,避免未预载黑屏)
|
|
||||||
const [auditRead, setAuditRead] = useState<ReadPayload | null>(() => {
|
|
||||||
const a = resolveBookAudit(getCachedRemoteConfig())
|
|
||||||
return a.reviewMode ? getAuditOfflineRead(a.bookId || 'audit') : null
|
|
||||||
})
|
|
||||||
|
|
||||||
function loadAuditRead(bookId: string) {
|
|
||||||
const id = bookId || 'audit'
|
|
||||||
setAuditRead(getAuditOfflineRead(id))
|
|
||||||
void fetchRead(id)
|
|
||||||
.then((res) => {
|
|
||||||
if (res?.chapters?.length) setAuditRead(res)
|
|
||||||
})
|
|
||||||
.catch(() => {
|
|
||||||
/* 已有离线 */
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
useLoad(() => {
|
useLoad(() => {
|
||||||
trackPage('pages/book/index', '小册封面')
|
trackPage('pages/book/index', '小册封面')
|
||||||
const a = resolveBookAudit(getCachedRemoteConfig())
|
|
||||||
if (a.reviewMode) {
|
|
||||||
setAudit(a)
|
|
||||||
loadAuditRead(a.bookId || 'audit')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
loadBook()
|
loadBook()
|
||||||
})
|
})
|
||||||
|
|
||||||
@ -154,10 +125,7 @@ function BookPageInner() {
|
|||||||
void loadRemoteConfig(true).then((r) => {
|
void loadRemoteConfig(true).then((r) => {
|
||||||
applyAudit(resolveBookAudit(r.config))
|
applyAudit(resolveBookAudit(r.config))
|
||||||
})
|
})
|
||||||
// 提审壳不拉封面,避免无意义请求与闪烁
|
loadBook(true)
|
||||||
if (!resolveBookAudit(getCachedRemoteConfig()).reviewMode) {
|
|
||||||
loadBook(true)
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@ -178,18 +146,13 @@ function BookPageInner() {
|
|||||||
const pid = next.reviewMode ? next.bookId || 'audit' : 'nomad'
|
const pid = next.reviewMode ? next.bookId || 'audit' : 'nomad'
|
||||||
setProgress(getReadingProgress(pid))
|
setProgress(getReadingProgress(pid))
|
||||||
if (changed) {
|
if (changed) {
|
||||||
if (next.reviewMode) {
|
void loadBook(true)
|
||||||
loadAuditRead(next.bookId || 'audit')
|
|
||||||
} else {
|
|
||||||
setAuditRead(null)
|
|
||||||
void loadBook(true)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 对齐小红书 startTypewriter:hooks 轮播打字机(提审壳不跑)
|
// 对齐正式封面:hooks 轮播打字机(提审同样跑)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (loading || audit.reviewMode) return
|
if (loading) return
|
||||||
const phrases = HOOK_LINES.length ? HOOK_LINES : [COVER_BOOK.subtitle]
|
const phrases = HOOK_LINES.length ? HOOK_LINES : [COVER_BOOK.subtitle]
|
||||||
let phraseIdx = 0
|
let phraseIdx = 0
|
||||||
let charIdx = 0
|
let charIdx = 0
|
||||||
@ -219,7 +182,7 @@ function BookPageInner() {
|
|||||||
}
|
}
|
||||||
timer = setTimeout(type, 380)
|
timer = setTimeout(type, 380)
|
||||||
return () => clearTimeout(timer)
|
return () => clearTimeout(timer)
|
||||||
}, [loading, audit.reviewMode])
|
}, [loading])
|
||||||
|
|
||||||
async function loadBook(silent = false) {
|
async function loadBook(silent = false) {
|
||||||
setError('')
|
setError('')
|
||||||
@ -291,8 +254,7 @@ function BookPageInner() {
|
|||||||
|
|
||||||
function goRead() {
|
function goRead() {
|
||||||
const a = resolveBookAudit(getCachedRemoteConfig())
|
const a = resolveBookAudit(getCachedRemoteConfig())
|
||||||
// 仅针对「数字游民小册」:审核→备用 Markdown;正式→VIP 电子书 nomad
|
// 提审 / 正式同一套 vip-ebook 阅读壳(样式一致);提审只换正文来源
|
||||||
// youtube运营笔记(default) 不受此开关影响
|
|
||||||
const bookId = a.reviewMode ? a.bookId || 'audit' : 'nomad'
|
const bookId = a.reviewMode ? a.bookId || 'audit' : 'nomad'
|
||||||
const continuing = !!progress?.chapterId
|
const continuing = !!progress?.chapterId
|
||||||
trackClick(continuing ? '继续阅读' : '开始阅读', {
|
trackClick(continuing ? '继续阅读' : '开始阅读', {
|
||||||
@ -305,10 +267,6 @@ function BookPageInner() {
|
|||||||
label: continuing ? '继续阅读' : '开始阅读',
|
label: continuing ? '继续阅读' : '开始阅读',
|
||||||
props: { book_id: bookId, audit: a.reviewMode },
|
props: { book_id: bookId, audit: a.reviewMode },
|
||||||
})
|
})
|
||||||
if (a.reviewMode) {
|
|
||||||
// 提审正文已在本页,无需再跳
|
|
||||||
return
|
|
||||||
}
|
|
||||||
goPage('/pages/vip-ebook/index?id=nomad')
|
goPage('/pages/vip-ebook/index?id=nomad')
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -441,8 +399,18 @@ function BookPageInner() {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 正式封面(审后 reviewMode=false 时由 book/index 挂载) */
|
/** 正式 / 提审同一封面壳;点阅读都进 vip-ebook(提审换线上 audit 正文) */
|
||||||
export default function BookCoverPage() {
|
export default function BookCoverPage() {
|
||||||
|
useDidShow(() => {
|
||||||
|
void loadRemoteConfig(true)
|
||||||
|
// 预下载阅读壳,避免提审点开黑屏
|
||||||
|
try {
|
||||||
|
void Taro.loadSubPackage?.({ name: 'vip-ebook' })
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<MiniModuleGate moduleKey="book">
|
<MiniModuleGate moduleKey="book">
|
||||||
<BookPageInner />
|
<BookPageInner />
|
||||||
|
|||||||
@ -1,8 +1,4 @@
|
|||||||
export default definePageConfig({
|
export default definePageConfig({
|
||||||
navigationBarTitleText: '数字游民入门指南',
|
navigationBarTitleText: '数字游民',
|
||||||
navigationBarBackgroundColor: '#0c0b12',
|
navigationStyle: 'custom',
|
||||||
navigationBarTextStyle: 'white',
|
|
||||||
backgroundColor: '#0c0b12',
|
|
||||||
// 提审:用系统导航(返回+标题),避免 custom 无顶栏像黑屏
|
|
||||||
navigationStyle: 'default',
|
|
||||||
})
|
})
|
||||||
|
|||||||
@ -1,120 +1,13 @@
|
|||||||
/**
|
/**
|
||||||
* 提审小册:静态页,无 hooks / 无外部数据依赖。
|
* 数字游民小册入口 — 对齐 tag 20261011-2 / 线上:
|
||||||
|
* 正式 / 提审同一封面;CTA 都进 vip-ebook?id=nomad(提审换 audit 正文,壳样式一致)。
|
||||||
*/
|
*/
|
||||||
import { View, Text } from '@tarojs/components'
|
import { usePageShare, markPageShare } from '@/utils/pageShare'
|
||||||
|
import BookCoverPage from './BookCoverPage'
|
||||||
|
|
||||||
function px(n: number) {
|
function BookPage() {
|
||||||
return `${n}PX`
|
usePageShare({ title: 'nomadro · 数字游民小册', path: '/pages/book/index' })
|
||||||
|
return <BookCoverPage />
|
||||||
}
|
}
|
||||||
|
|
||||||
const box = {
|
export default markPageShare(BookPage)
|
||||||
minHeight: '100vh',
|
|
||||||
width: '100%',
|
|
||||||
backgroundColor: '#0c0b12',
|
|
||||||
paddingTop: px(20),
|
|
||||||
paddingRight: px(16),
|
|
||||||
paddingBottom: px(40),
|
|
||||||
paddingLeft: px(16),
|
|
||||||
boxSizing: 'border-box' as const,
|
|
||||||
}
|
|
||||||
|
|
||||||
const h1 = {
|
|
||||||
display: 'block' as const,
|
|
||||||
fontSize: px(22),
|
|
||||||
fontWeight: '700' as const,
|
|
||||||
color: '#f8fafc',
|
|
||||||
lineHeight: '1.35',
|
|
||||||
marginBottom: px(8),
|
|
||||||
}
|
|
||||||
|
|
||||||
const h2 = {
|
|
||||||
display: 'block' as const,
|
|
||||||
fontSize: px(16),
|
|
||||||
fontWeight: '700' as const,
|
|
||||||
color: '#e2e8f0',
|
|
||||||
lineHeight: '1.4',
|
|
||||||
marginTop: px(20),
|
|
||||||
marginBottom: px(8),
|
|
||||||
}
|
|
||||||
|
|
||||||
const p = {
|
|
||||||
display: 'block' as const,
|
|
||||||
fontSize: px(15),
|
|
||||||
color: '#cbd5e1',
|
|
||||||
lineHeight: '1.75',
|
|
||||||
marginBottom: px(8),
|
|
||||||
}
|
|
||||||
|
|
||||||
const sub = {
|
|
||||||
display: 'block' as const,
|
|
||||||
fontSize: px(13),
|
|
||||||
color: '#94a3b8',
|
|
||||||
lineHeight: '1.45',
|
|
||||||
marginBottom: px(16),
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function BookPage() {
|
|
||||||
return (
|
|
||||||
<View style={box}>
|
|
||||||
<Text style={h1}>数字游民入门指南</Text>
|
|
||||||
<Text style={sub}>远程办公 · 自律生活 · 稳健成长</Text>
|
|
||||||
|
|
||||||
<Text style={h2}>1. 写在前面</Text>
|
|
||||||
<Text style={p}>欢迎阅读《数字游民入门指南》。</Text>
|
|
||||||
<Text style={p}>
|
|
||||||
这是一本面向普通人的生活方式小册:讲如何在合法合规的前提下,把工作做得更灵活,把生活安排得更从容。内容偏实用、偏日常,不涉及灰色产业,也不讨论敏感话题。
|
|
||||||
</Text>
|
|
||||||
<Text style={p}>
|
|
||||||
你可以把本书当作「远程办公入门笔记」:哪怕暂时还不能频繁出差,里面的时间管理、沟通方法和健康习惯,同样适用于居家办公与混合办公。
|
|
||||||
</Text>
|
|
||||||
|
|
||||||
<Text style={h2}>2. 什么是数字游民</Text>
|
|
||||||
<Text style={p}>
|
|
||||||
「数字游民」通常指:工作主要依赖电脑与网络完成,地点不必固定在同一间办公室。
|
|
||||||
</Text>
|
|
||||||
<Text style={p}>
|
|
||||||
它不是逃避现实。更常见的状态是:工作目标清晰、沟通及时、作息稳定、遵守公司制度与当地法律法规。
|
|
||||||
</Text>
|
|
||||||
<Text style={p}>
|
|
||||||
对很多职场人来说,第一步并不是「周游世界」,而是先学会高质量远程协作:按时开会、按时交付、把协作工具用熟。
|
|
||||||
</Text>
|
|
||||||
|
|
||||||
<Text style={h2}>3. 远程办公的基本功</Text>
|
|
||||||
<Text style={p}>远程办公的核心不是换风景,而是换一种可协作的工作方式。</Text>
|
|
||||||
<Text style={p}>建议每天有固定核心工作时间,并告诉同事哪些时段适合会议、哪些时段专注深度工作。</Text>
|
|
||||||
<Text style={p}>每天开工前列三件必须完成的事;每周五花十五分钟复盘完成项与卡点。</Text>
|
|
||||||
<Text style={p}>工具只保留必要的。开会前写清目的,会后写清结论:谁负责、做什么、何时完成。</Text>
|
|
||||||
|
|
||||||
<Text style={h2}>4. 居家与旅居的工作环境</Text>
|
|
||||||
<Text style={p}>环境会直接影响专注力。不必追求豪华,但要够用、安静、可持续。</Text>
|
|
||||||
<Text style={p}>居家建议:稳定桌椅与屏幕高度、充足光线、耳机、备用电源,以及减少打扰的约定。</Text>
|
|
||||||
<Text style={p}>若允许短期异地办公,优先网络稳定、住宿安静、餐饮运动方便、交通可预期。</Text>
|
|
||||||
|
|
||||||
<Text style={h2}>5. 时间管理</Text>
|
|
||||||
<Text style={p}>灵活工作最大的风险是时间碎、注意力散、任务拖。</Text>
|
|
||||||
<Text style={p}>可用简化番茄法:25 分钟专注一件事,休息 5 分钟;深度工作时关闭无关通知。</Text>
|
|
||||||
<Text style={p}>建议每天至少留 90 分钟不被会议打断的时间,用来做深度工作。</Text>
|
|
||||||
|
|
||||||
<Text style={h2}>6. 沟通与团队协作</Text>
|
|
||||||
<Text style={p}>远程场景里,沟通质量几乎等于工作质量。</Text>
|
|
||||||
<Text style={p}>同步信息:默认公开、结论先行、可执行(下一步、负责人、时间)。</Text>
|
|
||||||
<Text style={p}>远程信任来自稳定交付:承诺按时完成,延期提前说明,问题主动暴露。</Text>
|
|
||||||
|
|
||||||
<Text style={h2}>7. 健康、作息与心态</Text>
|
|
||||||
<Text style={p}>尽量固定睡眠与起床时间;每工作一小时起身活动两分钟;中午真正休息。</Text>
|
|
||||||
<Text style={p}>运动不必复杂:散步、拉伸即可,关键是每周能坚持。</Text>
|
|
||||||
|
|
||||||
<Text style={h2}>8. 学习成长与职业规划</Text>
|
|
||||||
<Text style={p}>真正护城河仍是能力与口碑:专业技能、表达能力、项目管理。</Text>
|
|
||||||
<Text style={p}>请遵守劳动合同、信息安全与所在地法律法规。稳健发展,才能走得长远。</Text>
|
|
||||||
|
|
||||||
<Text style={h2}>9. 七天起步计划</Text>
|
|
||||||
<Text style={p}>第1天整理工位;第2天三个每日目标;第3天文档归位;第4天练习结论先行;第5天短复盘;第6天轻度运动;第7天只改一件事。</Text>
|
|
||||||
|
|
||||||
<Text style={h2}>10. 结语</Text>
|
|
||||||
<Text style={p}>
|
|
||||||
先把远程协作做好,把身体照顾好,把专业能力垒扎实。祝你工作顺利,生活安定,步履从容。
|
|
||||||
</Text>
|
|
||||||
</View>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|||||||
@ -2,22 +2,26 @@
|
|||||||
* 对齐门户 components/sections/hero.tsx(结构 / PORTALS / 开发快捷入口)
|
* 对齐门户 components/sections/hero.tsx(结构 / PORTALS / 开发快捷入口)
|
||||||
* H5 真布局用原生 div(Taro View 自定义元素会弄塌 grid/绝对定位)。
|
* H5 真布局用原生 div(Taro View 自定义元素会弄塌 grid/绝对定位)。
|
||||||
*/
|
*/
|
||||||
import { useEffect, useState, type CSSProperties, type ReactNode } from 'react'
|
import { useEffect, useRef, useState, type CSSProperties, type ReactNode } from 'react'
|
||||||
import { View, Text, Button } from '@tarojs/components'
|
import { View, Text, Button } from '@tarojs/components'
|
||||||
import Taro, { useDidShow, usePageScroll } from '@tarojs/taro'
|
import Taro, { useDidHide, useDidShow, useLoad, usePageScroll } from '@tarojs/taro'
|
||||||
import {
|
import {
|
||||||
getCachedRemoteConfig,
|
getCachedRemoteConfig,
|
||||||
isModuleEnabled,
|
isModuleEnabled,
|
||||||
loadRemoteConfig,
|
loadRemoteConfig,
|
||||||
|
softRefreshRemoteConfig,
|
||||||
subscribeRemoteConfig,
|
subscribeRemoteConfig,
|
||||||
} from '@/services/remoteConfig'
|
} from '@/services/remoteConfig'
|
||||||
import type { NomadroRemoteConfig } from '@/data/remoteConfig.defaults'
|
import type { NomadroRemoteConfig } from '@/data/remoteConfig.defaults'
|
||||||
import { applyH5Theme, toggleH5Theme, useNomadroTheme } from '@/utils/h5Theme'
|
import { applyH5Theme, useNomadroTheme } from '@/utils/h5Theme'
|
||||||
import { goPage } from '@/utils/nav'
|
import { goPage } from '@/utils/nav'
|
||||||
import { usePageShare, markPageShare } from '@/utils/pageShare'
|
import { usePageShare, markPageShare } from '@/utils/pageShare'
|
||||||
import { safePx, useSafeAreaMetrics } from '@/utils/safeArea'
|
import { safePx, useSafeAreaMetrics } from '@/utils/safeArea'
|
||||||
import { usePageTrack } from '@/hooks/usePageTrack'
|
import { usePageTrack } from '@/hooks/usePageTrack'
|
||||||
import './index.scss'
|
import './index.scss'
|
||||||
|
|
||||||
|
/** pages/home/index 页内硬轮询:不依赖 App 层是否挂上 live sync */
|
||||||
|
const HOME_CONFIG_POLL_MS = 1000
|
||||||
type PortalId = 'nav' | 'book' | 'community' | 'social' | 'vip'
|
type PortalId = 'nav' | 'book' | 'community' | 'social' | 'vip'
|
||||||
|
|
||||||
type Portal = {
|
type Portal = {
|
||||||
@ -169,30 +173,66 @@ function IndexPage() {
|
|||||||
const [navScrolled, setNavScrolled] = useState(false)
|
const [navScrolled, setNavScrolled] = useState(false)
|
||||||
const [offline, setOffline] = useState(false)
|
const [offline, setOffline] = useState(false)
|
||||||
const [refreshing, setRefreshing] = useState(false)
|
const [refreshing, setRefreshing] = useState(false)
|
||||||
|
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null)
|
||||||
|
|
||||||
|
function applyConfig(r: { config: NomadroRemoteConfig; fromOffline: boolean }) {
|
||||||
|
setConfig({
|
||||||
|
...r.config,
|
||||||
|
modules: { ...r.config.modules },
|
||||||
|
flags: { ...r.config.flags },
|
||||||
|
})
|
||||||
|
setOffline(r.fromOffline)
|
||||||
|
}
|
||||||
|
|
||||||
async function refreshConfig() {
|
async function refreshConfig() {
|
||||||
if (refreshing) return
|
if (refreshing) return
|
||||||
setRefreshing(true)
|
setRefreshing(true)
|
||||||
try {
|
try {
|
||||||
const result = await loadRemoteConfig(true)
|
const result = await loadRemoteConfig(true)
|
||||||
setConfig(result.config)
|
applyConfig(result)
|
||||||
setOffline(result.fromOffline)
|
|
||||||
} finally {
|
} finally {
|
||||||
setRefreshing(false)
|
setRefreshing(false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function pullHomeConfig() {
|
||||||
|
softRefreshRemoteConfig()
|
||||||
|
void loadRemoteConfig(true).then(applyConfig).catch(() => undefined)
|
||||||
|
}
|
||||||
|
|
||||||
|
function startHomePoll() {
|
||||||
|
if (pollRef.current) return
|
||||||
|
pullHomeConfig()
|
||||||
|
pollRef.current = setInterval(pullHomeConfig, HOME_CONFIG_POLL_MS)
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopHomePoll() {
|
||||||
|
if (!pollRef.current) return
|
||||||
|
clearInterval(pollRef.current)
|
||||||
|
pollRef.current = null
|
||||||
|
}
|
||||||
|
|
||||||
|
useLoad(() => {
|
||||||
|
pullHomeConfig()
|
||||||
|
})
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const unsub = subscribeRemoteConfig((r) => {
|
const unsub = subscribeRemoteConfig((r) => applyConfig(r))
|
||||||
setConfig(r.config)
|
|
||||||
setOffline(r.fromOffline)
|
|
||||||
})
|
|
||||||
applyH5Theme(theme)
|
applyH5Theme(theme)
|
||||||
return unsub
|
startHomePoll()
|
||||||
|
return () => {
|
||||||
|
unsub()
|
||||||
|
stopHomePoll()
|
||||||
|
}
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
useDidShow(() => {
|
useDidShow(() => {
|
||||||
void loadRemoteConfig(true).then((r) => setConfig(r.config))
|
pullHomeConfig()
|
||||||
|
startHomePoll()
|
||||||
|
})
|
||||||
|
|
||||||
|
useDidHide(() => {
|
||||||
|
stopHomePoll()
|
||||||
})
|
})
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@ -304,7 +344,15 @@ function IndexPage() {
|
|||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
const cfg = config
|
const cfg = config
|
||||||
const portals = PORTALS.filter((p) => isModuleEnabled(cfg, p.moduleKey))
|
const portals = PORTALS.filter((p) => {
|
||||||
|
if (!isModuleEnabled(cfg, p.moduleKey)) return false
|
||||||
|
if (p.id === 'social') {
|
||||||
|
const flags = (cfg.copy as { socialFlags?: { features?: { homeEntry?: boolean } } })
|
||||||
|
?.socialFlags?.features
|
||||||
|
if (flags && flags.homeEntry === false) return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
})
|
||||||
const brand = cfg.copy.homeBrand || 'nomadro'
|
const brand = cfg.copy.homeBrand || 'nomadro'
|
||||||
const safe = useSafeAreaMetrics()
|
const safe = useSafeAreaMetrics()
|
||||||
const rootSafeStyle = {
|
const rootSafeStyle = {
|
||||||
@ -358,13 +406,6 @@ function IndexPage() {
|
|||||||
<Txt className="hub-logo-text">{brand}</Txt>
|
<Txt className="hub-logo-text">{brand}</Txt>
|
||||||
</Box>
|
</Box>
|
||||||
<Box className="hub-nav-actions">
|
<Box className="hub-nav-actions">
|
||||||
<Button
|
|
||||||
className="hub-theme-toggle"
|
|
||||||
aria-label={theme === 'dark' ? '切换日间模式' : '切换夜间模式'}
|
|
||||||
onClick={() => toggleH5Theme(theme)}
|
|
||||||
>
|
|
||||||
{theme === 'dark' ? '☀' : '☾'}
|
|
||||||
</Button>
|
|
||||||
{showQuickNav && isH5 && isDev ? (
|
{showQuickNav && isH5 && isDev ? (
|
||||||
<Box className="hub-dev-nav">
|
<Box className="hub-dev-nav">
|
||||||
<Box className="hub-dev-link" onClick={() => openDevLink('admin')}>
|
<Box className="hub-dev-link" onClick={() => openDevLink('admin')}>
|
||||||
@ -442,7 +483,11 @@ function IndexPage() {
|
|||||||
</Box>
|
</Box>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
<Box className="hub-portal-grid hub-reveal visible">
|
<Box
|
||||||
|
className={`hub-portal-grid hub-reveal visible${
|
||||||
|
portals.length > 3 ? ' hub-portal-grid--2x2' : ' hub-portal-grid--row'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
{portals.map((portal) => (
|
{portals.map((portal) => (
|
||||||
<Box
|
<Box
|
||||||
key={portal.id}
|
key={portal.id}
|
||||||
|
|||||||
@ -56,10 +56,8 @@ function ReaderPage() {
|
|||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const bookId = router.params.id || 'default'
|
const bookId = router.params.id || 'default'
|
||||||
const chapterParam = router.params.chapter || ''
|
const chapterParam = router.params.chapter || ''
|
||||||
// 提审书:首帧就有正文,避免 showLoading + 空壳黑屏
|
// 提审书也不预填包内写死章:先走线上,失联才在 load() 里兜底
|
||||||
const [data, setData] = useState<ReadPayload | null>(() =>
|
const [data, setData] = useState<ReadPayload | null>(null)
|
||||||
isAuditBookId(bookId) ? getAuditOfflineRead(bookId) : null,
|
|
||||||
)
|
|
||||||
const [drawerOpen, setDrawerOpen] = useState(false)
|
const [drawerOpen, setDrawerOpen] = useState(false)
|
||||||
const [settingsOpen, setSettingsOpen] = useState(false)
|
const [settingsOpen, setSettingsOpen] = useState(false)
|
||||||
const [tocFilter, setTocFilter] = useState('')
|
const [tocFilter, setTocFilter] = useState('')
|
||||||
@ -145,29 +143,26 @@ function ReaderPage() {
|
|||||||
async function load(silent = false) {
|
async function load(silent = false) {
|
||||||
const auditBook = isAuditBookId(bookId)
|
const auditBook = isAuditBookId(bookId)
|
||||||
try {
|
try {
|
||||||
// 提审:已有离线首屏,不再弹「打开中」遮罩
|
if (!silent) Taro.showLoading({ title: auditBook ? '同步中' : '打开中' })
|
||||||
if (!silent && !auditBook) Taro.showLoading({ title: '打开中' })
|
|
||||||
if (auditBook) {
|
|
||||||
loadedRef.current = true
|
|
||||||
}
|
|
||||||
const res = await fetchRead(bookId)
|
const res = await fetchRead(bookId)
|
||||||
setData(res)
|
setData(res)
|
||||||
accessFpRef.current = accessFingerprint(res)
|
accessFpRef.current = accessFingerprint(res)
|
||||||
loadedRef.current = true
|
loadedRef.current = true
|
||||||
if (!silent && !auditBook) {
|
if (!silent) {
|
||||||
setActiveChapter(0)
|
setActiveChapter(0)
|
||||||
setProgress(0)
|
setProgress(0)
|
||||||
restored.current = false
|
restored.current = false
|
||||||
}
|
}
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
if (auditBook) {
|
if (auditBook) {
|
||||||
|
// 服务端完全失联:包内写死章兜底
|
||||||
setData(getAuditOfflineRead(bookId))
|
setData(getAuditOfflineRead(bookId))
|
||||||
loadedRef.current = true
|
loadedRef.current = true
|
||||||
} else if (!silent) {
|
} else if (!silent) {
|
||||||
Taro.showToast({ title: e.message || '加载失败', icon: 'none' })
|
Taro.showToast({ title: e.message || '加载失败', icon: 'none' })
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
if (!silent && !auditBook) Taro.hideLoading()
|
if (!silent) Taro.hideLoading()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -49,7 +49,7 @@ export function ConnectionHero({
|
|||||||
copy?: SocialLandingCopy
|
copy?: SocialLandingCopy
|
||||||
}) {
|
}) {
|
||||||
const [videoOpen, setVideoOpen] = useState(false)
|
const [videoOpen, setVideoOpen] = useState(false)
|
||||||
const { roster } = useSocialContent()
|
const { roster, buttonOn, sectionOn, featureOn } = useSocialContent()
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@ -81,43 +81,51 @@ export function ConnectionHero({
|
|||||||
{copy.socialHeroLead}
|
{copy.socialHeroLead}
|
||||||
</H5El>
|
</H5El>
|
||||||
<H5El className='connection-actions'>
|
<H5El className='connection-actions'>
|
||||||
<H5El
|
{buttonOn('heroJoin') && featureOn('joinPay') ? (
|
||||||
as='button'
|
<H5El
|
||||||
className='btn connection-join'
|
as='button'
|
||||||
onClick={onJoin}
|
className='btn connection-join'
|
||||||
trackLabel='social_join'
|
onClick={onJoin}
|
||||||
>
|
trackLabel='social_join'
|
||||||
{copy.socialJoinCta} <H5El as='span'>↗</H5El>
|
>
|
||||||
</H5El>
|
{copy.socialJoinCta} <H5El as='span'>↗</H5El>
|
||||||
<H5El
|
</H5El>
|
||||||
as='a'
|
) : null}
|
||||||
className='connection-film'
|
{buttonOn('heroChat') ? (
|
||||||
href='#chat'
|
<H5El
|
||||||
onClick={() => goPage('/pages/social/chat/index')}
|
as='a'
|
||||||
trackLabel='social_film_chat'
|
className='connection-film'
|
||||||
>
|
href='#chat'
|
||||||
<H5El as='span'>💬</H5El>
|
onClick={() => goPage('/pages/social/chat/index')}
|
||||||
群组聊天
|
trackLabel='social_film_chat'
|
||||||
</H5El>
|
>
|
||||||
<H5El
|
<H5El as='span'>💬</H5El>
|
||||||
as='a'
|
群组聊天
|
||||||
className='connection-film'
|
</H5El>
|
||||||
href='#date'
|
) : null}
|
||||||
onClick={() => goPage('/pages/social/date/index')}
|
{buttonOn('heroDate') ? (
|
||||||
trackLabel='social_film_date'
|
<H5El
|
||||||
>
|
as='a'
|
||||||
<H5El as='span'>💕</H5El>
|
className='connection-film'
|
||||||
认识一下
|
href='#date'
|
||||||
</H5El>
|
onClick={() => goPage('/pages/social/date/index')}
|
||||||
<H5El
|
trackLabel='social_film_date'
|
||||||
as='button'
|
>
|
||||||
className='connection-film connection-film-story'
|
<H5El as='span'>💕</H5El>
|
||||||
onClick={() => setVideoOpen(true)}
|
认识一下
|
||||||
trackLabel='social_film_story'
|
</H5El>
|
||||||
>
|
) : null}
|
||||||
<H5El as='span'>▶</H5El>
|
{buttonOn('heroStory') && sectionOn('promo') ? (
|
||||||
社区故事
|
<H5El
|
||||||
</H5El>
|
as='button'
|
||||||
|
className='connection-film connection-film-story'
|
||||||
|
onClick={() => setVideoOpen(true)}
|
||||||
|
trackLabel='social_film_story'
|
||||||
|
>
|
||||||
|
<H5El as='span'>▶</H5El>
|
||||||
|
社区故事
|
||||||
|
</H5El>
|
||||||
|
) : null}
|
||||||
</H5El>
|
</H5El>
|
||||||
<H5El className='connection-proof'>
|
<H5El className='connection-proof'>
|
||||||
<H5El className='connection-avatar-stack' aria-hidden>
|
<H5El className='connection-avatar-stack' aria-hidden>
|
||||||
@ -305,6 +313,8 @@ export function ConnectionHero({
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function ConnectionWays({ copy = SOCIAL_COPY }: { copy?: SocialLandingCopy }) {
|
export function ConnectionWays({ copy = SOCIAL_COPY }: { copy?: SocialLandingCopy }) {
|
||||||
|
const { buttonOn, sectionOn } = useSocialContent()
|
||||||
|
if (!sectionOn('ways')) return null
|
||||||
const ways = [
|
const ways = [
|
||||||
{
|
{
|
||||||
id: '01',
|
id: '01',
|
||||||
@ -314,6 +324,7 @@ export function ConnectionWays({ copy = SOCIAL_COPY }: { copy?: SocialLandingCop
|
|||||||
sub: '大家一起聊 · 先打个招呼',
|
sub: '大家一起聊 · 先打个招呼',
|
||||||
cta: '进群聊',
|
cta: '进群聊',
|
||||||
className: 'mint',
|
className: 'mint',
|
||||||
|
button: 'wayGroup' as const,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: '02',
|
id: '02',
|
||||||
@ -323,6 +334,7 @@ export function ConnectionWays({ copy = SOCIAL_COPY }: { copy?: SocialLandingCop
|
|||||||
sub: '左右滑,慢慢认识',
|
sub: '左右滑,慢慢认识',
|
||||||
cta: '开始看看',
|
cta: '开始看看',
|
||||||
className: 'coral',
|
className: 'coral',
|
||||||
|
button: 'wayDate' as const,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: '03',
|
id: '03',
|
||||||
@ -332,6 +344,7 @@ export function ConnectionWays({ copy = SOCIAL_COPY }: { copy?: SocialLandingCop
|
|||||||
sub: '聊天群组 · 语音视频',
|
sub: '聊天群组 · 语音视频',
|
||||||
cta: '去聊聊',
|
cta: '去聊聊',
|
||||||
className: 'mint',
|
className: 'mint',
|
||||||
|
button: 'wayMeetup' as const,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: '04',
|
id: '04',
|
||||||
@ -341,6 +354,7 @@ export function ConnectionWays({ copy = SOCIAL_COPY }: { copy?: SocialLandingCop
|
|||||||
sub: copy.socialOfflineTitle,
|
sub: copy.socialOfflineTitle,
|
||||||
cta: '选城市',
|
cta: '选城市',
|
||||||
className: 'yellow',
|
className: 'yellow',
|
||||||
|
button: 'wayCafe' as const,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: '05',
|
id: '05',
|
||||||
@ -350,8 +364,10 @@ export function ConnectionWays({ copy = SOCIAL_COPY }: { copy?: SocialLandingCop
|
|||||||
sub: copy.socialTeamTitle,
|
sub: copy.socialTeamTitle,
|
||||||
cta: '看看机会',
|
cta: '看看机会',
|
||||||
className: 'mint',
|
className: 'mint',
|
||||||
|
button: 'wayTeam' as const,
|
||||||
},
|
},
|
||||||
]
|
].filter((way) => buttonOn(way.button))
|
||||||
|
if (!ways.length) return null
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<H5El className='container connection-ways is-alive' aria-label='选择连接方式'>
|
<H5El className='container connection-ways is-alive' aria-label='选择连接方式'>
|
||||||
|
|||||||
@ -1,7 +1,9 @@
|
|||||||
import { useMemo } from 'react'
|
import { useMemo } from 'react'
|
||||||
import Taro, { useRouter } from '@tarojs/taro'
|
import Taro, { useRouter } from '@tarojs/taro'
|
||||||
import { SOCIAL_DOCK } from '@/data/socialSeed'
|
import { SOCIAL_DOCK } from '@/data/socialSeed'
|
||||||
|
import { useSocialContent } from '@/hooks/useSocialContent'
|
||||||
import { goSocialPage as goPage } from '@/utils/socialNavigation'
|
import { goSocialPage as goPage } from '@/utils/socialNavigation'
|
||||||
|
import { dockButtonKey } from '@/utils/socialOps'
|
||||||
import { H5El } from './H5El'
|
import { H5El } from './H5El'
|
||||||
|
|
||||||
function normalize(path: string) {
|
function normalize(path: string) {
|
||||||
@ -12,6 +14,7 @@ function normalize(path: string) {
|
|||||||
|
|
||||||
export function SocialDock() {
|
export function SocialDock() {
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
|
const { featureOn, buttonOn } = useSocialContent()
|
||||||
const current = useMemo(() => {
|
const current = useMemo(() => {
|
||||||
const fromRouter = normalize(router?.path || '')
|
const fromRouter = normalize(router?.path || '')
|
||||||
if (fromRouter) return fromRouter
|
if (fromRouter) return fromRouter
|
||||||
@ -24,9 +27,17 @@ export function SocialDock() {
|
|||||||
}
|
}
|
||||||
}, [router?.path])
|
}, [router?.path])
|
||||||
|
|
||||||
|
if (!featureOn('dock')) return null
|
||||||
|
|
||||||
|
const items = SOCIAL_DOCK.filter((item) => {
|
||||||
|
const btn = dockButtonKey(item.path)
|
||||||
|
return !btn || buttonOn(btn)
|
||||||
|
})
|
||||||
|
if (!items.length) return null
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<H5El as='nav' className='social-mobile-dock' aria-label='快捷导航'>
|
<H5El as='nav' className='social-mobile-dock' aria-label='快捷导航'>
|
||||||
{SOCIAL_DOCK.map((item) => {
|
{items.map((item) => {
|
||||||
const target = normalize(item.path)
|
const target = normalize(item.path)
|
||||||
const active =
|
const active =
|
||||||
item.match === 'exact'
|
item.match === 'exact'
|
||||||
|
|||||||
@ -6,7 +6,7 @@ import {
|
|||||||
type ReactNode,
|
type ReactNode,
|
||||||
} from 'react'
|
} from 'react'
|
||||||
import { H5El } from './H5El'
|
import { H5El } from './H5El'
|
||||||
import { toggleH5Theme, useNomadroTheme } from '@/utils/h5Theme'
|
import { useNomadroTheme } from '@/utils/h5Theme'
|
||||||
|
|
||||||
const isH5 = process.env.TARO_ENV === 'h5'
|
const isH5 = process.env.TARO_ENV === 'h5'
|
||||||
|
|
||||||
@ -231,8 +231,6 @@ export function SocialExperience({
|
|||||||
return (
|
return (
|
||||||
<H5El className='social-experience' data-theme={theme}>
|
<H5El className='social-experience' data-theme={theme}>
|
||||||
{children}
|
{children}
|
||||||
<H5El as='button' className='social-theme-control' aria-label={theme === 'dark' ? '切换日间模式' : '切换夜间模式'}
|
|
||||||
onClick={() => toggleH5Theme(theme)}>{theme === 'dark' ? '☀' : '☾'}</H5El>
|
|
||||||
</H5El>
|
</H5El>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@ -253,8 +251,6 @@ export function SocialExperience({
|
|||||||
<H5El className='social-pointer-glow' aria-hidden />
|
<H5El className='social-pointer-glow' aria-hidden />
|
||||||
{showEmojiField ? <FloatingEmojiField /> : null}
|
{showEmojiField ? <FloatingEmojiField /> : null}
|
||||||
{children}
|
{children}
|
||||||
<H5El as='button' className='social-theme-control' aria-label={theme === 'dark' ? '切换日间模式' : '切换夜间模式'}
|
|
||||||
onClick={() => toggleH5Theme(theme)}>{theme === 'dark' ? '☀' : '☾'}</H5El>
|
|
||||||
<H5El
|
<H5El
|
||||||
as='button'
|
as='button'
|
||||||
type='button'
|
type='button'
|
||||||
|
|||||||
@ -3,7 +3,7 @@ import { useSocialContent } from '@/hooks/useSocialContent'
|
|||||||
import { useEffect, useRef, useState } from 'react'
|
import { useEffect, useRef, useState } from 'react'
|
||||||
import { Input, ScrollView, Text } from '@tarojs/components'
|
import { Input, ScrollView, Text } from '@tarojs/components'
|
||||||
import Taro from '@tarojs/taro'
|
import Taro from '@tarojs/taro'
|
||||||
import { MiniModuleGate } from '@/components/MiniModuleGate'
|
import { SocialPageGate } from '@/components/SocialPageGate'
|
||||||
import { H5Box } from '@/components/H5Box'
|
import { H5Box } from '@/components/H5Box'
|
||||||
import { useSocialChat } from '@/hooks/useSocialChat'
|
import { useSocialChat } from '@/hooks/useSocialChat'
|
||||||
import { usePageShare } from '@/utils/pageShare'
|
import { usePageShare } from '@/utils/pageShare'
|
||||||
@ -222,8 +222,8 @@ function SocialChatLobby() {
|
|||||||
|
|
||||||
export default function SocialChatPage() {
|
export default function SocialChatPage() {
|
||||||
return (
|
return (
|
||||||
<MiniModuleGate moduleKey='social'>
|
<SocialPageGate pageKey='chat'>
|
||||||
<SocialChatLobby />
|
<SocialChatLobby />
|
||||||
</MiniModuleGate>
|
</SocialPageGate>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@ -5,7 +5,7 @@ import { useSocialPage } from '@/hooks/useSocialPage'
|
|||||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||||
import { Text } from '@tarojs/components'
|
import { Text } from '@tarojs/components'
|
||||||
import Taro from '@tarojs/taro'
|
import Taro from '@tarojs/taro'
|
||||||
import { MiniModuleGate } from '@/components/MiniModuleGate'
|
import { SocialPageGate } from '@/components/SocialPageGate'
|
||||||
import { H5Box } from '@/components/H5Box'
|
import { H5Box } from '@/components/H5Box'
|
||||||
import { MOCK_ROSTER, type SocialRosterMember } from '@/data/socialSeed'
|
import { MOCK_ROSTER, type SocialRosterMember } from '@/data/socialSeed'
|
||||||
import { goSocialPage as goPage } from '@/utils/socialNavigation'
|
import { goSocialPage as goPage } from '@/utils/socialNavigation'
|
||||||
@ -71,7 +71,8 @@ function SocialDate() {
|
|||||||
const { theme, pageStyle } = useSocialPage()
|
const { theme, pageStyle } = useSocialPage()
|
||||||
usePageShare({ title: 'nomadro · 认识一下', path: '/pages/social/date/index' })
|
usePageShare({ title: 'nomadro · 认识一下', path: '/pages/social/date/index' })
|
||||||
usePageTrack('social_date')
|
usePageTrack('social_date')
|
||||||
const { roster, pages } = useSocialContent()
|
const { roster, pages, featureOn } = useSocialContent()
|
||||||
|
const swipeOn = featureOn('dateSwipe')
|
||||||
const [filter, setFilter] = useState<Filter>('all')
|
const [filter, setFilter] = useState<Filter>('all')
|
||||||
const [swipes, setSwipes] = useSocialLocal<Record<string, Decision>>('swipes_v1', {})
|
const [swipes, setSwipes] = useSocialLocal<Record<string, Decision>>('swipes_v1', {})
|
||||||
const [history, setHistory] = useSocialLocal<{ id: string; decision: Decision; previousLiked?: boolean }[]>('swipe_history_v1', [])
|
const [history, setHistory] = useSocialLocal<{ id: string; decision: Decision; previousLiked?: boolean }[]>('swipe_history_v1', [])
|
||||||
@ -248,8 +249,9 @@ function SocialDate() {
|
|||||||
<H5Box>
|
<H5Box>
|
||||||
<Text style={{ fontWeight: 700 }}>{pages.date?.title || '认识一下'}</Text>
|
<Text style={{ fontWeight: 700 }}>{pages.date?.title || '认识一下'}</Text>
|
||||||
<Text className='social-muted'>
|
<Text className='social-muted'>
|
||||||
左滑划走 · 右滑想认识
|
{swipeOn
|
||||||
{totalForFilter ? ` · 还剩 ${remaining}/${totalForFilter}` : ''}
|
? `左滑划走 · 右滑想认识${totalForFilter ? ` · 还剩 ${remaining}/${totalForFilter}` : ''}`
|
||||||
|
: '滑动认识暂未开放'}
|
||||||
</Text>
|
</Text>
|
||||||
</H5Box>
|
</H5Box>
|
||||||
<Text className='social-demo-badge'>示例介绍,方便先逛逛</Text>
|
<Text className='social-demo-badge'>示例介绍,方便先逛逛</Text>
|
||||||
@ -281,7 +283,16 @@ function SocialDate() {
|
|||||||
</H5Box>
|
</H5Box>
|
||||||
|
|
||||||
<H5Box className='social-date-stage'>
|
<H5Box className='social-date-stage'>
|
||||||
{totalForFilter > 0 ? (
|
{!featureOn('dateSwipe') ? (
|
||||||
|
<H5Box className='social-date-empty'>
|
||||||
|
<Text style={{ fontWeight: 700 }}>认识一下暂未开放</Text>
|
||||||
|
<Text className='social-muted'>运营已关闭划卡,稍后再来或去聊聊。</Text>
|
||||||
|
<H5Box className='social-btn' onClick={() => goPage('/pages/social/chat/index')}>
|
||||||
|
<Text>先去群组聊聊</Text>
|
||||||
|
</H5Box>
|
||||||
|
</H5Box>
|
||||||
|
) : null}
|
||||||
|
{featureOn('dateSwipe') && totalForFilter > 0 ? (
|
||||||
<H5Box className='social-date-progress' aria-label={`还剩 ${remaining} 人`}>
|
<H5Box className='social-date-progress' aria-label={`还剩 ${remaining} 人`}>
|
||||||
<H5Box
|
<H5Box
|
||||||
style={{
|
style={{
|
||||||
@ -294,97 +305,100 @@ function SocialDate() {
|
|||||||
</H5Box>
|
</H5Box>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
<H5Box className='social-date-deck' style={{ touchAction: 'pan-y' }}>
|
{swipeOn ? (
|
||||||
{!current ? (
|
<>
|
||||||
<H5Box className='social-date-empty'>
|
<H5Box className='social-date-deck' style={{ touchAction: 'pan-y' }}>
|
||||||
<Text style={{ fontSize: 36 }}>✨</Text>
|
{!current ? (
|
||||||
<Text style={{ fontWeight: 700 }}>这批看完了</Text>
|
<H5Box className='social-date-empty'>
|
||||||
<Text className='social-muted'>
|
<Text style={{ fontSize: 36 }}>✨</Text>
|
||||||
想认识的人会先记在你这边。可以再看一轮,或去聊天室打个招呼。
|
<Text style={{ fontWeight: 700 }}>这批看完了</Text>
|
||||||
</Text>
|
<Text className='social-muted'>
|
||||||
<H5Box className='social-btn primary' onClick={resetDeck}>
|
想认识的人会先记在你这边。可以再看一轮,或去聊天室打个招呼。
|
||||||
<Text>再来一轮</Text>
|
</Text>
|
||||||
|
<H5Box className='social-btn primary' onClick={resetDeck}>
|
||||||
|
<Text>再来一轮</Text>
|
||||||
|
</H5Box>
|
||||||
|
<H5Box
|
||||||
|
className='social-btn'
|
||||||
|
onClick={() => goPage('/pages/social/chat/index')}
|
||||||
|
>
|
||||||
|
<Text>先去群组聊聊</Text>
|
||||||
|
</H5Box>
|
||||||
|
</H5Box>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{next ? (
|
||||||
|
<H5Box className='social-date-card is-next' aria-hidden>
|
||||||
|
<DateCardFace member={next} />
|
||||||
|
</H5Box>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{current ? (
|
||||||
|
<H5Box
|
||||||
|
className={`social-date-card is-top${drag.active ? ' is-dragging' : ''}${fly ? ` is-fly-${fly.dir}` : ''}`}
|
||||||
|
style={
|
||||||
|
fly
|
||||||
|
? undefined
|
||||||
|
: {
|
||||||
|
transform: `translate3d(${drag.x}px, ${drag.y}px, 0) rotate(${rotate}deg)`,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
onClick={undefined}
|
||||||
|
>
|
||||||
|
<H5Box
|
||||||
|
className='social-date-card-hit'
|
||||||
|
style={{ position: 'absolute', inset: 0, zIndex: 2 }}
|
||||||
|
onPointerDown={onPointerDown}
|
||||||
|
onPointerMove={onPointerMove}
|
||||||
|
onPointerUp={onPointerUp}
|
||||||
|
onPointerCancel={() => {
|
||||||
|
dragging.current = false
|
||||||
|
dragRef.current = { x: 0, y: 0 }
|
||||||
|
setDrag({ x: 0, y: 0, active: false })
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<Text
|
||||||
|
className='social-date-stamp like'
|
||||||
|
style={{ opacity: fly?.dir === 'like' ? 1 : likeOpacity }}
|
||||||
|
>
|
||||||
|
想认识
|
||||||
|
</Text>
|
||||||
|
<Text
|
||||||
|
className='social-date-stamp pass'
|
||||||
|
style={{ opacity: fly?.dir === 'pass' ? 1 : passOpacity }}
|
||||||
|
>
|
||||||
|
划走
|
||||||
|
</Text>
|
||||||
|
<DateCardFace member={current} />
|
||||||
|
</H5Box>
|
||||||
|
) : null}
|
||||||
|
</H5Box>
|
||||||
|
|
||||||
|
<H5Box className='social-date-hint is-alive'>
|
||||||
|
<Text className='social-date-hint-side pass'>← 划走</Text>
|
||||||
|
<Text>拖卡片左右滑 · 或点下面按钮</Text>
|
||||||
|
<Text className='social-date-hint-side like'>想认识 →</Text>
|
||||||
|
</H5Box>
|
||||||
|
|
||||||
|
<H5Box className='social-date-actions is-alive'>
|
||||||
|
<H5Box
|
||||||
|
className='social-date-act pass'
|
||||||
|
onClick={() => current && commit(current, 'pass')}
|
||||||
|
>
|
||||||
|
<Text>✕</Text>
|
||||||
|
</H5Box>
|
||||||
|
<H5Box className='social-date-act undo' onClick={undo}>
|
||||||
|
<Text>↩</Text>
|
||||||
</H5Box>
|
</H5Box>
|
||||||
<H5Box
|
<H5Box
|
||||||
className='social-btn'
|
className='social-date-act like'
|
||||||
onClick={() => goPage('/pages/social/chat/index')}
|
onClick={() => current && commit(current, 'like')}
|
||||||
>
|
>
|
||||||
<Text>先去群组聊聊</Text>
|
<Text>♥</Text>
|
||||||
</H5Box>
|
</H5Box>
|
||||||
</H5Box>
|
</H5Box>
|
||||||
) : null}
|
</>
|
||||||
|
) : null}
|
||||||
{next ? (
|
|
||||||
<H5Box className='social-date-card is-next' aria-hidden>
|
|
||||||
<DateCardFace member={next} />
|
|
||||||
</H5Box>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
{current ? (
|
|
||||||
<H5Box
|
|
||||||
className={`social-date-card is-top${drag.active ? ' is-dragging' : ''}${fly ? ` is-fly-${fly.dir}` : ''}`}
|
|
||||||
style={
|
|
||||||
fly
|
|
||||||
? undefined
|
|
||||||
: {
|
|
||||||
transform: `translate3d(${drag.x}px, ${drag.y}px, 0) rotate(${rotate}deg)`,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
onClick={undefined}
|
|
||||||
>
|
|
||||||
{/* pointer events via native listeners on H5 */}
|
|
||||||
<H5Box
|
|
||||||
className='social-date-card-hit'
|
|
||||||
style={{ position: 'absolute', inset: 0, zIndex: 2 }}
|
|
||||||
onPointerDown={onPointerDown}
|
|
||||||
onPointerMove={onPointerMove}
|
|
||||||
onPointerUp={onPointerUp}
|
|
||||||
onPointerCancel={() => {
|
|
||||||
dragging.current = false
|
|
||||||
dragRef.current = { x: 0, y: 0 }
|
|
||||||
setDrag({ x: 0, y: 0, active: false })
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<Text
|
|
||||||
className='social-date-stamp like'
|
|
||||||
style={{ opacity: fly?.dir === 'like' ? 1 : likeOpacity }}
|
|
||||||
>
|
|
||||||
想认识
|
|
||||||
</Text>
|
|
||||||
<Text
|
|
||||||
className='social-date-stamp pass'
|
|
||||||
style={{ opacity: fly?.dir === 'pass' ? 1 : passOpacity }}
|
|
||||||
>
|
|
||||||
划走
|
|
||||||
</Text>
|
|
||||||
<DateCardFace member={current} />
|
|
||||||
</H5Box>
|
|
||||||
) : null}
|
|
||||||
</H5Box>
|
|
||||||
|
|
||||||
<H5Box className='social-date-hint is-alive'>
|
|
||||||
<Text className='social-date-hint-side pass'>← 划走</Text>
|
|
||||||
<Text>拖卡片左右滑 · 或点下面按钮</Text>
|
|
||||||
<Text className='social-date-hint-side like'>想认识 →</Text>
|
|
||||||
</H5Box>
|
|
||||||
|
|
||||||
<H5Box className='social-date-actions is-alive'>
|
|
||||||
<H5Box
|
|
||||||
className='social-date-act pass'
|
|
||||||
onClick={() => current && commit(current, 'pass')}
|
|
||||||
>
|
|
||||||
<Text>✕</Text>
|
|
||||||
</H5Box>
|
|
||||||
<H5Box className='social-date-act undo' onClick={undo}>
|
|
||||||
<Text>↩</Text>
|
|
||||||
</H5Box>
|
|
||||||
<H5Box
|
|
||||||
className='social-date-act like'
|
|
||||||
onClick={() => current && commit(current, 'like')}
|
|
||||||
>
|
|
||||||
<Text>♥</Text>
|
|
||||||
</H5Box>
|
|
||||||
</H5Box>
|
|
||||||
</H5Box>
|
</H5Box>
|
||||||
|
|
||||||
<SocialDock />
|
<SocialDock />
|
||||||
@ -395,8 +409,8 @@ function SocialDate() {
|
|||||||
|
|
||||||
export default function SocialDatePage() {
|
export default function SocialDatePage() {
|
||||||
return (
|
return (
|
||||||
<MiniModuleGate moduleKey='social'>
|
<SocialPageGate pageKey='date'>
|
||||||
<SocialDate />
|
<SocialDate />
|
||||||
</MiniModuleGate>
|
</SocialPageGate>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@ -2,7 +2,7 @@ import { useSocialContent } from '@/hooks/useSocialContent'
|
|||||||
import { useSocialPage } from '@/hooks/useSocialPage'
|
import { useSocialPage } from '@/hooks/useSocialPage'
|
||||||
import { useEffect, useMemo, useState, type CSSProperties } from 'react'
|
import { useEffect, useMemo, useState, type CSSProperties } from 'react'
|
||||||
import Taro, { usePageScroll } from '@tarojs/taro'
|
import Taro, { usePageScroll } from '@tarojs/taro'
|
||||||
import { MiniModuleGate } from '@/components/MiniModuleGate'
|
import { SocialPageGate } from '@/components/SocialPageGate'
|
||||||
import {
|
import {
|
||||||
DEFAULT_PROMO,
|
DEFAULT_PROMO,
|
||||||
MOCK_ROSTER,
|
MOCK_ROSTER,
|
||||||
@ -74,7 +74,8 @@ function SocialHome() {
|
|||||||
const [joinOpen, setJoinOpen] = useState(false)
|
const [joinOpen, setJoinOpen] = useState(false)
|
||||||
const [teamTab, setTeamTab] = useState<'gigs' | 'creation'>('gigs')
|
const [teamTab, setTeamTab] = useState<'gigs' | 'creation'>('gigs')
|
||||||
const [creation, setCreation] = useState<{ item: SocialEbook | SocialVideo; kind: 'ebook' | 'video' } | null>(null)
|
const [creation, setCreation] = useState<{ item: SocialEbook | SocialVideo; kind: 'ebook' | 'video' } | null>(null)
|
||||||
const { copy, roster, meetups, gigs, ebooks, videos, promoUrl, hiddenSections } = useSocialContent()
|
const { copy, roster, meetups, gigs, ebooks, videos, promoUrl, hiddenSections, featureOn, sectionOn } =
|
||||||
|
useSocialContent()
|
||||||
const datePreview = useMemo(
|
const datePreview = useMemo(
|
||||||
() => roster.filter((m) => m.online).slice(0, 3),
|
() => roster.filter((m) => m.online).slice(0, 3),
|
||||||
[roster],
|
[roster],
|
||||||
@ -93,6 +94,7 @@ function SocialHome() {
|
|||||||
)
|
)
|
||||||
|
|
||||||
const onJoin = () => {
|
const onJoin = () => {
|
||||||
|
if (!featureOn('joinPay')) return
|
||||||
// 加群收费(虚拟支付)≠ VIP / community 付费体系
|
// 加群收费(虚拟支付)≠ VIP / community 付费体系
|
||||||
setJoinOpen(true)
|
setJoinOpen(true)
|
||||||
}
|
}
|
||||||
@ -100,11 +102,11 @@ function SocialHome() {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
try {
|
try {
|
||||||
const q = Taro.getCurrentInstance()?.router?.params || {}
|
const q = Taro.getCurrentInstance()?.router?.params || {}
|
||||||
if (String(q.join || '') === '1') setJoinOpen(true)
|
if (String(q.join || '') === '1' && featureOn('joinPay')) setJoinOpen(true)
|
||||||
} catch {
|
} catch {
|
||||||
/* ignore */
|
/* ignore */
|
||||||
}
|
}
|
||||||
}, [])
|
}, [featureOn])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isH5 || typeof document === 'undefined') return
|
if (!isH5 || typeof document === 'undefined') return
|
||||||
@ -628,25 +630,29 @@ function SocialHome() {
|
|||||||
</H5El>
|
</H5El>
|
||||||
</H5El>
|
</H5El>
|
||||||
|
|
||||||
<H5El as='section' className='connection-invite container' aria-label='加入社区'>
|
{sectionOn('invite') ? (
|
||||||
<H5El className='connection-invite-orbit' aria-hidden>
|
<H5El as='section' className='connection-invite container' aria-label='加入社区'>
|
||||||
<H5El as='span' />
|
<H5El className='connection-invite-orbit' aria-hidden>
|
||||||
<H5El as='span' />
|
<H5El as='span' />
|
||||||
<H5El as='span' style={{ fontSize: 52 }}>
|
<H5El as='span' />
|
||||||
✨
|
<H5El as='span' style={{ fontSize: 52 }}>
|
||||||
|
✨
|
||||||
|
</H5El>
|
||||||
</H5El>
|
</H5El>
|
||||||
</H5El>
|
<H5El>
|
||||||
<H5El>
|
<H5El as='span' className='connection-eyebrow'>
|
||||||
<H5El as='span' className='connection-eyebrow'>
|
加入社区
|
||||||
加入社区
|
</H5El>
|
||||||
|
<H5El as='h2'>{copy.socialInviteTitle}</H5El>
|
||||||
|
<H5El as='p'>{copy.socialInviteLead}</H5El>
|
||||||
</H5El>
|
</H5El>
|
||||||
<H5El as='h2'>{copy.socialInviteTitle}</H5El>
|
{featureOn('joinPay') ? (
|
||||||
<H5El as='p'>{copy.socialInviteLead}</H5El>
|
<H5El as='button' type='button' className='btn connection-join' onClick={onJoin}>
|
||||||
|
加入游民社区 ↗
|
||||||
|
</H5El>
|
||||||
|
) : null}
|
||||||
</H5El>
|
</H5El>
|
||||||
<H5El as='button' type='button' className='btn connection-join' onClick={onJoin}>
|
) : null}
|
||||||
加入游民社区 ↗
|
|
||||||
</H5El>
|
|
||||||
</H5El>
|
|
||||||
</H5El>
|
</H5El>
|
||||||
|
|
||||||
<H5El as='footer' className='footer'>
|
<H5El as='footer' className='footer'>
|
||||||
@ -695,8 +701,12 @@ function SocialHome() {
|
|||||||
</H5El>
|
</H5El>
|
||||||
</H5El>
|
</H5El>
|
||||||
|
|
||||||
<JoinPaySheet open={joinOpen} onClose={() => setJoinOpen(false)} />
|
{featureOn('joinPay') ? (
|
||||||
{creation ? <CreationSheet {...creation} onClose={() => setCreation(null)} /> : null}
|
<JoinPaySheet open={joinOpen} onClose={() => setJoinOpen(false)} />
|
||||||
|
) : null}
|
||||||
|
{featureOn('creationSheet') && creation ? (
|
||||||
|
<CreationSheet {...creation} onClose={() => setCreation(null)} />
|
||||||
|
) : null}
|
||||||
<SocialDock />
|
<SocialDock />
|
||||||
</H5El>
|
</H5El>
|
||||||
</SocialExperience>
|
</SocialExperience>
|
||||||
@ -705,8 +715,8 @@ function SocialHome() {
|
|||||||
|
|
||||||
export default function SocialIndexPage() {
|
export default function SocialIndexPage() {
|
||||||
return (
|
return (
|
||||||
<MiniModuleGate moduleKey='social'>
|
<SocialPageGate pageKey='index'>
|
||||||
<SocialHome />
|
<SocialHome />
|
||||||
</MiniModuleGate>
|
</SocialPageGate>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@ -16,7 +16,7 @@ import {
|
|||||||
View,
|
View,
|
||||||
} from '@tarojs/components'
|
} from '@tarojs/components'
|
||||||
import Taro, { useDidHide, useRouter } from '@tarojs/taro'
|
import Taro, { useDidHide, useRouter } from '@tarojs/taro'
|
||||||
import { MiniModuleGate } from '@/components/MiniModuleGate'
|
import { SocialPageGate } from '@/components/SocialPageGate'
|
||||||
import { MIROTALK_URL, MOCK_ROSTER, SEED_MEETUPS } from '@/data/socialSeed'
|
import { MIROTALK_URL, MOCK_ROSTER, SEED_MEETUPS } from '@/data/socialSeed'
|
||||||
import { socialApi, type LivePeer } from '@/services/socialApi'
|
import { socialApi, type LivePeer } from '@/services/socialApi'
|
||||||
import { goSocialPage as goPage } from '@/utils/socialNavigation'
|
import { goSocialPage as goPage } from '@/utils/socialNavigation'
|
||||||
@ -132,7 +132,8 @@ async function ensureMediaAuth(): Promise<boolean> {
|
|||||||
function SocialMeetupLive() {
|
function SocialMeetupLive() {
|
||||||
const { theme, pageStyle } = useSocialPage()
|
const { theme, pageStyle } = useSocialPage()
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const { meetups } = useSocialContent()
|
const { meetups, featureOn } = useSocialContent()
|
||||||
|
const liveOnFlag = featureOn('livePusher')
|
||||||
const meetupId = String(router.params?.id || meetups[0]?.id || 'office')
|
const meetupId = String(router.params?.id || meetups[0]?.id || 'office')
|
||||||
const meetup =
|
const meetup =
|
||||||
meetups.find((m) => m.id === meetupId) || {
|
meetups.find((m) => m.id === meetupId) || {
|
||||||
@ -432,10 +433,14 @@ function SocialMeetupLive() {
|
|||||||
as='button'
|
as='button'
|
||||||
type='button'
|
type='button'
|
||||||
className='btn btn-primary'
|
className='btn btn-primary'
|
||||||
disabled={joining} loading={joining}
|
disabled={joining || !liveOnFlag}
|
||||||
onClick={() => void (isWeapp ? startWeappLive() : startH5())}
|
loading={joining}
|
||||||
|
onClick={() => {
|
||||||
|
if (!liveOnFlag) return
|
||||||
|
void (isWeapp ? startWeappLive() : startH5())
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
{joining ? '正在进入…' : '进入语音视频厅'}
|
{!liveOnFlag ? '语音视频厅暂未开放' : joining ? '正在进入…' : '进入语音视频厅'}
|
||||||
</H5El>
|
</H5El>
|
||||||
</H5El>
|
</H5El>
|
||||||
) : isWeapp ? (
|
) : isWeapp ? (
|
||||||
@ -587,8 +592,8 @@ function SocialMeetupLive() {
|
|||||||
|
|
||||||
export default function SocialMeetupLivePage() {
|
export default function SocialMeetupLivePage() {
|
||||||
return (
|
return (
|
||||||
<MiniModuleGate moduleKey='social'>
|
<SocialPageGate pageKey='meetupLive'>
|
||||||
<SocialMeetupLive />
|
<SocialMeetupLive />
|
||||||
</MiniModuleGate>
|
</SocialPageGate>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
import { useSocialContent } from '@/hooks/useSocialContent'
|
import { useSocialContent } from '@/hooks/useSocialContent'
|
||||||
import { useSocialPage } from '@/hooks/useSocialPage'
|
import { useSocialPage } from '@/hooks/useSocialPage'
|
||||||
import { useMemo, type CSSProperties } from 'react'
|
import { useMemo, type CSSProperties } from 'react'
|
||||||
import { MiniModuleGate } from '@/components/MiniModuleGate'
|
import { SocialPageGate } from '@/components/SocialPageGate'
|
||||||
import { MOCK_ROSTER, SEED_MEETUPS } from '@/data/socialSeed'
|
import { MOCK_ROSTER, SEED_MEETUPS } from '@/data/socialSeed'
|
||||||
import { goSocialPage as goPage } from '@/utils/socialNavigation'
|
import { goSocialPage as goPage } from '@/utils/socialNavigation'
|
||||||
import { usePageShare } from '@/utils/pageShare'
|
import { usePageShare } from '@/utils/pageShare'
|
||||||
@ -101,8 +101,8 @@ function SocialMeetupList() {
|
|||||||
|
|
||||||
export default function SocialMeetupPage() {
|
export default function SocialMeetupPage() {
|
||||||
return (
|
return (
|
||||||
<MiniModuleGate moduleKey='social'>
|
<SocialPageGate pageKey='meetup'>
|
||||||
<SocialMeetupList />
|
<SocialMeetupList />
|
||||||
</MiniModuleGate>
|
</SocialPageGate>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@ -6,7 +6,7 @@ import { useRouter } from '@tarojs/taro'
|
|||||||
import { Input } from '@tarojs/components'
|
import { Input } from '@tarojs/components'
|
||||||
import type { SocialCafe } from '@/data/socialTypes'
|
import type { SocialCafe } from '@/data/socialTypes'
|
||||||
import { CafeReviews } from '../_components/CafeReviews'
|
import { CafeReviews } from '../_components/CafeReviews'
|
||||||
import { MiniModuleGate } from '@/components/MiniModuleGate'
|
import { SocialPageGate } from '@/components/SocialPageGate'
|
||||||
import {
|
import {
|
||||||
MOCK_ROSTER,
|
MOCK_ROSTER,
|
||||||
SEED_CAFES,
|
SEED_CAFES,
|
||||||
@ -32,7 +32,7 @@ function SocialPeople() {
|
|||||||
usePageTrack('social_people')
|
usePageTrack('social_people')
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const mode = ['all', 'cafe', 'team'].includes(String(router.params?.mode)) ? String(router.params?.mode) : 'all'
|
const mode = ['all', 'cafe', 'team'].includes(String(router.params?.mode)) ? String(router.params?.mode) : 'all'
|
||||||
const { roster, cafes, pages } = useSocialContent()
|
const { roster, cafes, pages, featureOn } = useSocialContent()
|
||||||
const [filter, setFilter] = useState<'all' | 'online' | 'f' | 'm' | 'liked'>('all')
|
const [filter, setFilter] = useState<'all' | 'online' | 'f' | 'm' | 'liked'>('all')
|
||||||
const [query, setQuery] = useState('')
|
const [query, setQuery] = useState('')
|
||||||
const [city, setCity] = useState(() => {
|
const [city, setCity] = useState(() => {
|
||||||
@ -136,7 +136,9 @@ function SocialPeople() {
|
|||||||
{cafe.city} · WiFi {cafe.wifiMbps}Mbps
|
{cafe.city} · WiFi {cafe.wifiMbps}Mbps
|
||||||
</H5El>
|
</H5El>
|
||||||
<H5El as='p'>{cafe.vibe}</H5El>
|
<H5El as='p'>{cafe.vibe}</H5El>
|
||||||
<H5El as='button' className='btn' onClick={() => setActiveCafe(cafe)}>查看与分享评价</H5El>
|
{featureOn('cafeReviews') ? (
|
||||||
|
<H5El as='button' className='btn' onClick={() => setActiveCafe(cafe)}>查看与分享评价</H5El>
|
||||||
|
) : null}
|
||||||
</H5El>
|
</H5El>
|
||||||
))}
|
))}
|
||||||
</H5El>
|
</H5El>
|
||||||
@ -206,7 +208,9 @@ function SocialPeople() {
|
|||||||
</>
|
</>
|
||||||
) : null}
|
) : null}
|
||||||
</H5El>
|
</H5El>
|
||||||
{activeCafe ? <CafeReviews key={activeCafe.id} cafe={activeCafe} onClose={() => setActiveCafe(null)} /> : null}
|
{featureOn('cafeReviews') && activeCafe ? (
|
||||||
|
<CafeReviews key={activeCafe.id} cafe={activeCafe} onClose={() => setActiveCafe(null)} />
|
||||||
|
) : null}
|
||||||
<SocialDock />
|
<SocialDock />
|
||||||
</H5El>
|
</H5El>
|
||||||
</SocialExperience>
|
</SocialExperience>
|
||||||
@ -215,8 +219,8 @@ function SocialPeople() {
|
|||||||
|
|
||||||
export default function SocialPeoplePage() {
|
export default function SocialPeoplePage() {
|
||||||
return (
|
return (
|
||||||
<MiniModuleGate moduleKey='social'>
|
<SocialPageGate pageKey='people'>
|
||||||
<SocialPeople />
|
<SocialPeople />
|
||||||
</MiniModuleGate>
|
</SocialPageGate>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@ -4,7 +4,7 @@ import { useSocialPage } from '@/hooks/useSocialPage'
|
|||||||
import { useMemo, useState, type CSSProperties } from 'react'
|
import { useMemo, useState, type CSSProperties } from 'react'
|
||||||
import { Image } from '@tarojs/components'
|
import { Image } from '@tarojs/components'
|
||||||
import Taro, { useRouter } from '@tarojs/taro'
|
import Taro, { useRouter } from '@tarojs/taro'
|
||||||
import { MiniModuleGate } from '@/components/MiniModuleGate'
|
import { SocialPageGate } from '@/components/SocialPageGate'
|
||||||
import { findRosterMember, MOCK_ROSTER } from '@/data/socialSeed'
|
import { findRosterMember, MOCK_ROSTER } from '@/data/socialSeed'
|
||||||
import { goSocialPage as goPage } from '@/utils/socialNavigation'
|
import { goSocialPage as goPage } from '@/utils/socialNavigation'
|
||||||
import { usePageShare } from '@/utils/pageShare'
|
import { usePageShare } from '@/utils/pageShare'
|
||||||
@ -264,8 +264,8 @@ function SocialPeopleProfile() {
|
|||||||
|
|
||||||
export default function SocialPeopleProfilePage() {
|
export default function SocialPeopleProfilePage() {
|
||||||
return (
|
return (
|
||||||
<MiniModuleGate moduleKey='social'>
|
<SocialPageGate pageKey='peopleProfile'>
|
||||||
<SocialPeopleProfile />
|
<SocialPeopleProfile />
|
||||||
</MiniModuleGate>
|
</SocialPageGate>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,7 +1,8 @@
|
|||||||
import { useEffect, useRef, useState } from 'react'
|
import { useEffect, useRef, useState } from 'react'
|
||||||
import { Input, Textarea } from '@tarojs/components'
|
import { Input, Textarea } from '@tarojs/components'
|
||||||
import Taro from '@tarojs/taro'
|
import Taro from '@tarojs/taro'
|
||||||
import { MiniModuleGate } from '@/components/MiniModuleGate'
|
import { SocialPageGate } from '@/components/SocialPageGate'
|
||||||
|
import { useSocialContent } from '@/hooks/useSocialContent'
|
||||||
import { useSocialPage } from '@/hooks/useSocialPage'
|
import { useSocialPage } from '@/hooks/useSocialPage'
|
||||||
import { usePageShare } from '@/utils/pageShare'
|
import { usePageShare } from '@/utils/pageShare'
|
||||||
import { usePageTrack } from '@/hooks/usePageTrack'
|
import { usePageTrack } from '@/hooks/usePageTrack'
|
||||||
@ -26,6 +27,8 @@ const FIELDS = [
|
|||||||
|
|
||||||
function SocialRoster() {
|
function SocialRoster() {
|
||||||
const { theme, pageStyle } = useSocialPage()
|
const { theme, pageStyle } = useSocialPage()
|
||||||
|
const { featureOn } = useSocialContent()
|
||||||
|
const editOn = featureOn('rosterEdit')
|
||||||
usePageShare({ title: 'nomadro · 我的介绍', path: '/pages/social/roster/index' })
|
usePageShare({ title: 'nomadro · 我的介绍', path: '/pages/social/roster/index' })
|
||||||
usePageTrack('social_roster')
|
usePageTrack('social_roster')
|
||||||
const [profile, setProfile] = useState<SocialRosterProfile>(() => ({ ...EMPTY, ...readSocialLocal('profile_draft_v1', EMPTY) }))
|
const [profile, setProfile] = useState<SocialRosterProfile>(() => ({ ...EMPTY, ...readSocialLocal('profile_draft_v1', EMPTY) }))
|
||||||
@ -145,17 +148,21 @@ function SocialRoster() {
|
|||||||
{FIELDS.map(([key, label, placeholder, limit]) => <H5El key={key} className='social-profile-field'>
|
{FIELDS.map(([key, label, placeholder, limit]) => <H5El key={key} className='social-profile-field'>
|
||||||
<H5El as='label' htmlFor={`profile_${key}`}>{label}</H5El>
|
<H5El as='label' htmlFor={`profile_${key}`}>{label}</H5El>
|
||||||
<Input id={`profile_${key}`} className='social-field-input' value={profile[key] || ''} maxlength={limit}
|
<Input id={`profile_${key}`} className='social-field-input' value={profile[key] || ''} maxlength={limit}
|
||||||
placeholder={placeholder} disabled={saving} onInput={(e) => update(key, e.detail.value)} />
|
placeholder={placeholder} disabled={saving || !editOn} onInput={(e) => update(key, e.detail.value)} />
|
||||||
</H5El>)}
|
</H5El>)}
|
||||||
<H5El className='social-profile-field'>
|
<H5El className='social-profile-field'>
|
||||||
<H5El as='label' htmlFor='profile_bio'>自我介绍 · {profile.bio.length}/2000</H5El>
|
<H5El as='label' htmlFor='profile_bio'>自我介绍 · {profile.bio.length}/2000</H5El>
|
||||||
<Textarea id='profile_bio' className='social-field-input' value={profile.bio} maxlength={2000}
|
<Textarea id='profile_bio' className='social-field-input' value={profile.bio} maxlength={2000}
|
||||||
placeholder='最近在做什么?想认识怎样的朋友或搭档?' autoHeight disabled={saving} onInput={(e) => update('bio', e.detail.value)} />
|
placeholder='最近在做什么?想认识怎样的朋友或搭档?' autoHeight disabled={saving || !editOn} onInput={(e) => update('bio', e.detail.value)} />
|
||||||
</H5El>
|
</H5El>
|
||||||
<H5El className='social-profile-save-row'>
|
<H5El className='social-profile-save-row'>
|
||||||
<H5El as='button' className='btn btn-primary' disabled={loading || saving} loading={saving} onClick={() => void save()}>
|
{editOn ? (
|
||||||
{saving ? '正在同步…' : '保存到社区'}
|
<H5El as='button' className='btn btn-primary' disabled={loading || saving} loading={saving} onClick={() => void save()}>
|
||||||
</H5El>
|
{saving ? '正在同步…' : '保存到社区'}
|
||||||
|
</H5El>
|
||||||
|
) : (
|
||||||
|
<H5El as='p' className='social-muted'>介绍编辑暂未开放</H5El>
|
||||||
|
)}
|
||||||
<H5El as='button' className='btn btn-ghost' disabled={loading || saving} onClick={() => void load()}>重新连接</H5El>
|
<H5El as='button' className='btn btn-ghost' disabled={loading || saving} onClick={() => void load()}>重新连接</H5El>
|
||||||
</H5El>
|
</H5El>
|
||||||
</H5El>
|
</H5El>
|
||||||
@ -165,5 +172,5 @@ function SocialRoster() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function SocialRosterPage() {
|
export default function SocialRosterPage() {
|
||||||
return <MiniModuleGate moduleKey='social'><SocialRoster /></MiniModuleGate>
|
return <SocialPageGate pageKey='roster'><SocialRoster /></SocialPageGate>
|
||||||
}
|
}
|
||||||
|
|||||||
@ -3,7 +3,7 @@ import { useSocialPage } from '@/hooks/useSocialPage'
|
|||||||
import { useEffect, useMemo, useRef, useState, type CSSProperties } from 'react'
|
import { useEffect, useMemo, useRef, useState, type CSSProperties } from 'react'
|
||||||
import { Input, Textarea } from '@tarojs/components'
|
import { Input, Textarea } from '@tarojs/components'
|
||||||
import Taro, { useRouter } from '@tarojs/taro'
|
import Taro, { useRouter } from '@tarojs/taro'
|
||||||
import { MiniModuleGate } from '@/components/MiniModuleGate'
|
import { SocialPageGate } from '@/components/SocialPageGate'
|
||||||
import { ROLE_EMOJI, SEED_GIGS, TEAM_KIND_LABEL } from '@/data/socialSeed'
|
import { ROLE_EMOJI, SEED_GIGS, TEAM_KIND_LABEL } from '@/data/socialSeed'
|
||||||
import type { SocialGig, SocialTeamKind } from '@/data/socialTypes'
|
import type { SocialGig, SocialTeamKind } from '@/data/socialTypes'
|
||||||
import { socialApi, getLocalApply, markLocalApplySent } from '@/services/socialApi'
|
import { socialApi, getLocalApply, markLocalApplySent } from '@/services/socialApi'
|
||||||
@ -249,7 +249,7 @@ function SocialTeam() {
|
|||||||
usePageTrack('social_team')
|
usePageTrack('social_team')
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const safe = useMemo(() => getSafeAreaMetrics(), [])
|
const safe = useMemo(() => getSafeAreaMetrics(), [])
|
||||||
const { gigs, pages } = useSocialContent()
|
const { gigs, pages, featureOn } = useSocialContent()
|
||||||
const initialKind = (router.params?.kind as string) || 'all'
|
const initialKind = (router.params?.kind as string) || 'all'
|
||||||
const [kind, setKind] = useState<string>(initialKind)
|
const [kind, setKind] = useState<string>(initialKind)
|
||||||
const [query, setQuery] = useState(String(router.params?.q || ''))
|
const [query, setQuery] = useState(String(router.params?.q || ''))
|
||||||
@ -347,15 +347,17 @@ function SocialTeam() {
|
|||||||
</H5El>
|
</H5El>
|
||||||
))}
|
))}
|
||||||
</H5El>
|
</H5El>
|
||||||
<H5El
|
{featureOn('teamApply') ? (
|
||||||
as='button'
|
<H5El
|
||||||
type='button'
|
as='button'
|
||||||
className='btn btn-primary btn-sm'
|
type='button'
|
||||||
style={{ ['--stagger' as string]: `${i * 40}ms` }}
|
className='btn btn-primary btn-sm'
|
||||||
onClick={() => setActive(g)}
|
style={{ ['--stagger' as string]: `${i * 40}ms` }}
|
||||||
>
|
onClick={() => setActive(g)}
|
||||||
我想参与 ↗
|
>
|
||||||
</H5El>
|
我想参与 ↗
|
||||||
|
</H5El>
|
||||||
|
) : null}
|
||||||
</H5El>
|
</H5El>
|
||||||
))}
|
))}
|
||||||
</H5El>
|
</H5El>
|
||||||
@ -381,7 +383,9 @@ function SocialTeam() {
|
|||||||
) : null}
|
) : null}
|
||||||
</H5El>
|
</H5El>
|
||||||
|
|
||||||
{active ? <ApplySheet key={active.id} gig={active} onClose={() => setActive(null)} /> : null}
|
{featureOn('teamApply') && active ? (
|
||||||
|
<ApplySheet key={active.id} gig={active} onClose={() => setActive(null)} />
|
||||||
|
) : null}
|
||||||
<SocialDock />
|
<SocialDock />
|
||||||
</H5El>
|
</H5El>
|
||||||
</SocialExperience>
|
</SocialExperience>
|
||||||
@ -390,8 +394,8 @@ function SocialTeam() {
|
|||||||
|
|
||||||
export default function SocialTeamPage() {
|
export default function SocialTeamPage() {
|
||||||
return (
|
return (
|
||||||
<MiniModuleGate moduleKey='social'>
|
<SocialPageGate pageKey='team'>
|
||||||
<SocialTeam />
|
<SocialTeam />
|
||||||
</MiniModuleGate>
|
</SocialPageGate>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@ -37,7 +37,7 @@ import {
|
|||||||
toggleBookmark,
|
toggleBookmark,
|
||||||
} from '../../utils/vipLearning'
|
} from '../../utils/vipLearning'
|
||||||
import { getSafeAreaMetrics } from '../../utils/safeArea'
|
import { getSafeAreaMetrics } from '../../utils/safeArea'
|
||||||
import { toggleH5Theme, useNomadroTheme } from '@/utils/h5Theme'
|
import { useNomadroTheme } from '@/utils/h5Theme'
|
||||||
import './index.scss'
|
import './index.scss'
|
||||||
|
|
||||||
export default function VipCoursePage() {
|
export default function VipCoursePage() {
|
||||||
@ -196,9 +196,6 @@ export default function VipCoursePage() {
|
|||||||
🌍 异度星球
|
🌍 异度星球
|
||||||
</Text>
|
</Text>
|
||||||
<View className="vip-topic-header-nav">
|
<View className="vip-topic-header-nav">
|
||||||
<Text className="vip-topic-theme" onClick={() => toggleH5Theme(theme)}>
|
|
||||||
{theme === 'dark' ? '☀️' : '🌙'}
|
|
||||||
</Text>
|
|
||||||
<View
|
<View
|
||||||
className="vip-topic-header-cta"
|
className="vip-topic-header-cta"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
|
|||||||
@ -29,8 +29,28 @@ import {
|
|||||||
subscribeRemoteConfig,
|
subscribeRemoteConfig,
|
||||||
} from '../../services/remoteConfig'
|
} from '../../services/remoteConfig'
|
||||||
import { resolveBookAudit } from '../../data/remoteConfig.defaults'
|
import { resolveBookAudit } from '../../data/remoteConfig.defaults'
|
||||||
|
import { fetchAuditRead, getAuditOfflineRead } from '../../services/ebookApi'
|
||||||
import './index.scss'
|
import './index.scss'
|
||||||
|
|
||||||
|
function auditPayloadToPack(
|
||||||
|
bookId: string,
|
||||||
|
payload: ReturnType<typeof getAuditOfflineRead>,
|
||||||
|
): VipEbookPack {
|
||||||
|
const chapters = payload.chapters || []
|
||||||
|
const headers = chapters.map((c) => c.title)
|
||||||
|
const sections = chapters.map((c) => c.content || '')
|
||||||
|
const words = sections.reduce((n, s) => n + s.length, 0)
|
||||||
|
return {
|
||||||
|
id: bookId === 'audit' ? 'nomad' : ((bookId as VipEbookPack['id']) || 'nomad'),
|
||||||
|
title: payload.book?.title || '数字游民入门指南',
|
||||||
|
free: true,
|
||||||
|
estimatedMinutes: Math.max(5, Math.round(words / 400)),
|
||||||
|
headers,
|
||||||
|
sections,
|
||||||
|
markdown: sections.join('\n\n'),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const EBOOK_PREFS = {
|
const EBOOK_PREFS = {
|
||||||
fontSize: 16,
|
fontSize: 16,
|
||||||
lineHeight: '1.85',
|
lineHeight: '1.85',
|
||||||
@ -100,7 +120,7 @@ export default function VipEbookPage() {
|
|||||||
setReady(false)
|
setReady(false)
|
||||||
void (async () => {
|
void (async () => {
|
||||||
try {
|
try {
|
||||||
// 数字游民:提审开 → 改读审核版;用 redirect 避免页面栈卡死
|
// 数字游民提审:同一 vip-ebook 壳 + 线上 audit 正文(失联才包内兜底)
|
||||||
if (bookId === 'nomad') {
|
if (bookId === 'nomad') {
|
||||||
try {
|
try {
|
||||||
await loadRemoteConfig(true)
|
await loadRemoteConfig(true)
|
||||||
@ -110,9 +130,18 @@ export default function VipEbookPage() {
|
|||||||
if (cancelled) return
|
if (cancelled) return
|
||||||
const audit = resolveBookAudit(getCachedRemoteConfig())
|
const audit = resolveBookAudit(getCachedRemoteConfig())
|
||||||
if (audit.reviewMode) {
|
if (audit.reviewMode) {
|
||||||
// 提审正文在小册页内联,勿跳 reader 分包
|
const auditId = audit.bookId || 'audit'
|
||||||
const url = '/pages/book/index'
|
let pack: VipEbookPack
|
||||||
await Taro.redirectTo({ url }).catch(() => goPage(url))
|
try {
|
||||||
|
const res = await fetchAuditRead(auditId)
|
||||||
|
pack = auditPayloadToPack(auditId, res.payload)
|
||||||
|
} catch {
|
||||||
|
pack = auditPayloadToPack(auditId, getAuditOfflineRead(auditId))
|
||||||
|
}
|
||||||
|
if (cancelled) return
|
||||||
|
setBook(pack)
|
||||||
|
setAllowed(true)
|
||||||
|
Taro.setNavigationBarTitle({ title: pack.title })
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -155,14 +184,34 @@ export default function VipEbookPage() {
|
|||||||
}
|
}
|
||||||
}, [bookId])
|
}, [bookId])
|
||||||
|
|
||||||
// 后台打开提审:静默 redirect,不弹 toast、不卡加载
|
// 后台开关提审:仍在本页换正文,保持与正式相同阅读壳
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (bookId !== 'nomad') return
|
if (bookId !== 'nomad') return
|
||||||
return subscribeRemoteConfig((r) => {
|
return subscribeRemoteConfig((r) => {
|
||||||
const audit = resolveBookAudit(r.config)
|
const audit = resolveBookAudit(r.config)
|
||||||
if (!audit.reviewMode) return
|
// 开关变化时重拉:关提审 → 正式 VIP 包;开提审 → audit 正文
|
||||||
const url = '/pages/book/index'
|
setReady(false)
|
||||||
void Taro.redirectTo({ url }).catch(() => goPage(url))
|
void (async () => {
|
||||||
|
try {
|
||||||
|
if (audit.reviewMode) {
|
||||||
|
const auditId = audit.bookId || 'audit'
|
||||||
|
const res = await fetchAuditRead(auditId)
|
||||||
|
const pack = auditPayloadToPack(auditId, res.payload)
|
||||||
|
setBook(pack)
|
||||||
|
setAllowed(true)
|
||||||
|
Taro.setNavigationBarTitle({ title: pack.title })
|
||||||
|
} else {
|
||||||
|
const { book: next } = await loadVipEbook('nomad')
|
||||||
|
setBook(next)
|
||||||
|
setAllowed(!!next.free || (await resolveVipContentAccess(true)))
|
||||||
|
Taro.setNavigationBarTitle({ title: next.title })
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* keep current */
|
||||||
|
} finally {
|
||||||
|
setReady(true)
|
||||||
|
}
|
||||||
|
})()
|
||||||
})
|
})
|
||||||
}, [bookId])
|
}, [bookId])
|
||||||
|
|
||||||
@ -207,7 +256,10 @@ export default function VipEbookPage() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function goBack() {
|
function goBack() {
|
||||||
Taro.navigateBack({ fail: () => goPage('/pages/vip/index') })
|
// 数字游民(含提审)从封面进,返回小册封面;其它 VIP 书回会员中心
|
||||||
|
const fallback =
|
||||||
|
bookId === 'nomad' ? '/pages/book/index' : '/pages/vip/index'
|
||||||
|
Taro.navigateBack({ fail: () => goPage(fallback) })
|
||||||
}
|
}
|
||||||
|
|
||||||
if (youtubeMisroute) {
|
if (youtubeMisroute) {
|
||||||
|
|||||||
@ -61,11 +61,57 @@ export function isAuditBookId(bookId: string) {
|
|||||||
return id === 'audit' || id.startsWith('audit')
|
return id === 'audit' || id.startsWith('audit')
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 提审离线正文:阅读页可立刻渲染,避免「打开中」黑屏感 */
|
/** 提审离线正文:仅当后台完全失联时兜底 */
|
||||||
export function getAuditOfflineRead(bookId = 'audit'): ReadPayload {
|
export function getAuditOfflineRead(bookId = 'audit'): ReadPayload {
|
||||||
return auditOfflineRead(bookId || 'audit')
|
return auditOfflineRead(bookId || 'audit')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type AuditReadResult = {
|
||||||
|
payload: ReadPayload
|
||||||
|
/** true = 请求失败/空正文,已回落到包内写死章 */
|
||||||
|
fromOffline: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 提审正文:线上优先;包内 AUDIT_BOOK_* 只在服务端失联或空响应时兜底。
|
||||||
|
*/
|
||||||
|
export async function fetchAuditRead(bookId = 'audit'): Promise<AuditReadResult> {
|
||||||
|
const id = bookId || 'audit'
|
||||||
|
try {
|
||||||
|
const remote = await request<ReadPayload>({
|
||||||
|
url: `/api/ebook/books/${id}/read?_=${Date.now()}`,
|
||||||
|
_retried: true,
|
||||||
|
})
|
||||||
|
const remoteChapters = Array.isArray(remote?.chapters) ? remote.chapters : []
|
||||||
|
const withBody = remoteChapters.filter((c) => String(c?.content || '').trim().length > 20)
|
||||||
|
if (withBody.length > 0) {
|
||||||
|
return { payload: { ...remote, chapters: withBody }, fromOffline: false }
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* fall through */
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const remoteBook = await request<BookDetail>({
|
||||||
|
url: `/api/ebook/books/${id}?_=${Date.now()}`,
|
||||||
|
_retried: true,
|
||||||
|
})
|
||||||
|
if (remoteBook && (remoteBook.chapter_count || remoteBook.chapters?.length)) {
|
||||||
|
// 有元数据但无 read 正文:仍算半在线,读页用离线章 + 线上书名
|
||||||
|
const offline = auditOfflineRead(id)
|
||||||
|
return {
|
||||||
|
payload: {
|
||||||
|
...offline,
|
||||||
|
book: { ...offline.book, ...remoteBook, id, is_free: true, unlock_percent: 100 },
|
||||||
|
},
|
||||||
|
fromOffline: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* fall through */
|
||||||
|
}
|
||||||
|
return { payload: auditOfflineRead(id), fromOffline: true }
|
||||||
|
}
|
||||||
|
|
||||||
/** 提审书绝不能回退到正式离线包 —— 正文与 audit_book_seed.md 对齐 */
|
/** 提审书绝不能回退到正式离线包 —— 正文与 audit_book_seed.md 对齐 */
|
||||||
function auditOfflineBook(bookId: string): BookDetail {
|
function auditOfflineBook(bookId: string): BookDetail {
|
||||||
const wordCount = AUDIT_BOOK_CHAPTERS.reduce((n, c) => n + (c.content?.length || 0), 0)
|
const wordCount = AUDIT_BOOK_CHAPTERS.reduce((n, c) => n + (c.content?.length || 0), 0)
|
||||||
@ -122,7 +168,6 @@ export async function fetchBook(bookId = 'default'): Promise<BookDetail> {
|
|||||||
return { ...OFFLINE_BOOK, id }
|
return { ...OFFLINE_BOOK, id }
|
||||||
}
|
}
|
||||||
if (isAuditBookId(id)) {
|
if (isAuditBookId(id)) {
|
||||||
const offline = auditOfflineBook(id)
|
|
||||||
try {
|
try {
|
||||||
const remote = await request<BookDetail>({
|
const remote = await request<BookDetail>({
|
||||||
url: `/api/ebook/books/${id}?_=${Date.now()}`,
|
url: `/api/ebook/books/${id}?_=${Date.now()}`,
|
||||||
@ -131,9 +176,9 @@ export async function fetchBook(bookId = 'default'): Promise<BookDetail> {
|
|||||||
})
|
})
|
||||||
if (remote && (remote.chapter_count || remote.chapters?.length)) return remote
|
if (remote && (remote.chapter_count || remote.chapters?.length)) return remote
|
||||||
} catch {
|
} catch {
|
||||||
/* keep offline */
|
/* 失联才包内兜底 */
|
||||||
}
|
}
|
||||||
return offline
|
return auditOfflineBook(id)
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
return await request({ url: `/api/ebook/books/${id}?_=${Date.now()}` })
|
return await request({ url: `/api/ebook/books/${id}?_=${Date.now()}` })
|
||||||
@ -149,24 +194,10 @@ export async function fetchRead(bookId = 'default'): Promise<ReadPayload> {
|
|||||||
payload.book = { ...payload.book, id }
|
payload.book = { ...payload.book, id }
|
||||||
return payload
|
return payload
|
||||||
}
|
}
|
||||||
// 提审书:离线优先(包内 10 章),有网再覆盖;空响应不覆盖,避免黑屏
|
// 提审书:线上优先,失联才包内兜底(见 fetchAuditRead)
|
||||||
if (isAuditBookId(id)) {
|
if (isAuditBookId(id)) {
|
||||||
const offline = auditOfflineRead(id)
|
const { payload } = await fetchAuditRead(id)
|
||||||
try {
|
return payload
|
||||||
const remote = await request<ReadPayload>({
|
|
||||||
url: `/api/ebook/books/${id}/read?_=${Date.now()}`,
|
|
||||||
_retried: true,
|
|
||||||
})
|
|
||||||
// 必须有实质正文才覆盖离线,避免空 content 把页面「读成」黑屏
|
|
||||||
const remoteChapters = Array.isArray(remote?.chapters) ? remote.chapters : []
|
|
||||||
const withBody = remoteChapters.filter((c) => String(c?.content || '').trim().length > 20)
|
|
||||||
if (withBody.length > 0) {
|
|
||||||
return { ...remote, chapters: withBody }
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
/* keep offline */
|
|
||||||
}
|
|
||||||
return offline
|
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
if (process.env.TARO_ENV !== 'h5') {
|
if (process.env.TARO_ENV !== 'h5') {
|
||||||
|
|||||||
@ -6,11 +6,10 @@ import {
|
|||||||
type NomadroRemoteConfig,
|
type NomadroRemoteConfig,
|
||||||
} from '../data/remoteConfig.defaults'
|
} from '../data/remoteConfig.defaults'
|
||||||
|
|
||||||
/** v2:作废旧缓存里 bookAudit.reviewMode=false 的种子,提审首屏走包内默认 true */
|
/** v4:改走 POST 拉配置,作废会被微信缓存的 GET 结果 */
|
||||||
const STORAGE_KEY = 'nomadro_remote_config_v2'
|
const STORAGE_KEY = 'nomadro_remote_config_v4'
|
||||||
const CACHE_TTL_MS = 1000 * 60 * 30
|
const CACHE_TTL_MS = 1000 * 60 * 30
|
||||||
/** 小程序无 EventSource:meta 轮询间隔(近实时) */
|
const FULL_POLL_MS = 1000
|
||||||
const META_POLL_MS = 3000
|
|
||||||
|
|
||||||
type LoadResult = {
|
type LoadResult = {
|
||||||
config: NomadroRemoteConfig
|
config: NomadroRemoteConfig
|
||||||
@ -23,17 +22,38 @@ type Listener = (result: LoadResult) => void
|
|||||||
let memory: LoadResult | null = null
|
let memory: LoadResult | null = null
|
||||||
const listeners = new Set<Listener>()
|
const listeners = new Set<Listener>()
|
||||||
let liveStarted = false
|
let liveStarted = false
|
||||||
let metaTimer: ReturnType<typeof setInterval> | null = null
|
let pollTimer: ReturnType<typeof setInterval> | null = null
|
||||||
let knownVersion = 0
|
let knownVersion = 0
|
||||||
|
let knownFp = ''
|
||||||
let configInFlight: Promise<LoadResult> | null = null
|
let configInFlight: Promise<LoadResult> | null = null
|
||||||
let metaInFlight: Promise<void> | null = null
|
let forceQueued = false
|
||||||
let appVisible = true
|
let appVisible = true
|
||||||
let retryMetaAfter = 0
|
let socketTask: Taro.SocketTask | null = null
|
||||||
let metaFailures = 0
|
let socketReconnect: ReturnType<typeof setTimeout> | null = null
|
||||||
|
let eventSource: EventSource | null = null
|
||||||
|
let stoppedFlag = false
|
||||||
|
|
||||||
function emit(result: LoadResult) {
|
function configFingerprint(cfg: NomadroRemoteConfig): string {
|
||||||
|
try {
|
||||||
|
return JSON.stringify({
|
||||||
|
v: cfg.version,
|
||||||
|
at: cfg.updatedAt,
|
||||||
|
modules: cfg.modules,
|
||||||
|
flags: cfg.flags,
|
||||||
|
bookAudit: cfg.platforms?.weapp?.bookAudit,
|
||||||
|
})
|
||||||
|
} catch {
|
||||||
|
return String(cfg.version || 0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function emit(result: LoadResult, opts?: { forceNotify?: boolean }) {
|
||||||
|
const fp = configFingerprint(result.config)
|
||||||
|
const changed = fp !== knownFp
|
||||||
memory = result
|
memory = result
|
||||||
knownVersion = Number(result.config.version) || knownVersion
|
knownVersion = Number(result.config.version) || knownVersion
|
||||||
|
knownFp = fp
|
||||||
|
if (!changed && !opts?.forceNotify) return
|
||||||
listeners.forEach((fn) => {
|
listeners.forEach((fn) => {
|
||||||
try {
|
try {
|
||||||
fn(result)
|
fn(result)
|
||||||
@ -64,25 +84,50 @@ function writeStorage(config: NomadroRemoteConfig) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function metaUrls(): string[] {
|
function clearLegacyCaches() {
|
||||||
if (APP_TARGET === 'h5') return ['/api/config/meta']
|
for (const k of [
|
||||||
// 小程序优先 api(证书合法 + 原始 flags,含 joinGroupAction);门户作兜底
|
'nomadro_remote_config_v1',
|
||||||
return [`${API_BASE}/api/config/meta`, `${WEB_BASE}/api/config/meta`]
|
'nomadro_remote_config_v2',
|
||||||
|
'nomadro_remote_config_v3',
|
||||||
|
]) {
|
||||||
|
try {
|
||||||
|
Taro.removeStorageSync(k)
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function configUrls(): string[] {
|
||||||
|
// POST /api/config/pull 优先;兼容旧 POST /api/config
|
||||||
|
if (APP_TARGET === 'h5') {
|
||||||
|
return [
|
||||||
|
'/api/config/pull',
|
||||||
|
'/api/config',
|
||||||
|
`${API_BASE}/api/config/pull`,
|
||||||
|
`${API_BASE}/api/config`,
|
||||||
|
]
|
||||||
|
}
|
||||||
|
return [
|
||||||
|
`${API_BASE}/api/config/pull`,
|
||||||
|
`${API_BASE}/api/config`,
|
||||||
|
`${WEB_BASE}/api/config/pull`,
|
||||||
|
`${WEB_BASE}/api/config`,
|
||||||
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
async function fetchRemote(): Promise<NomadroRemoteConfig | null> {
|
async function fetchRemote(): Promise<NomadroRemoteConfig | null> {
|
||||||
const urls =
|
for (const url of configUrls()) {
|
||||||
APP_TARGET === 'h5'
|
|
||||||
? ['/api/config']
|
|
||||||
: // 后台 VIP 写的是 API 侧 remote-config;门户旧 merge 会丢掉 joinGroupAction
|
|
||||||
[`${API_BASE}/api/config`, `${WEB_BASE}/api/config`]
|
|
||||||
|
|
||||||
for (const url of urls) {
|
|
||||||
try {
|
try {
|
||||||
const res = await Taro.request({
|
const res = await Taro.request({
|
||||||
url,
|
url: `${url}${url.includes('?') ? '&' : '?'}_=${Date.now()}`,
|
||||||
method: 'GET',
|
method: 'POST',
|
||||||
timeout: 6000,
|
data: { t: Date.now() },
|
||||||
|
timeout: 8000,
|
||||||
|
header: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Cache-Control': 'no-store',
|
||||||
|
},
|
||||||
})
|
})
|
||||||
if (res.statusCode >= 400) continue
|
if (res.statusCode >= 400) continue
|
||||||
const body = res.data as { config?: Partial<NomadroRemoteConfig> }
|
const body = res.data as { config?: Partial<NomadroRemoteConfig> }
|
||||||
@ -97,78 +142,60 @@ async function fetchRemote(): Promise<NomadroRemoteConfig | null> {
|
|||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
async function fetchMeta(): Promise<{ version: number; updatedAt: string } | null> {
|
export function loadRemoteConfig(force = false): Promise<LoadResult> {
|
||||||
for (const url of metaUrls()) {
|
if (!force && memory) return Promise.resolve(memory)
|
||||||
|
|
||||||
|
if (configInFlight) {
|
||||||
|
if (force) forceQueued = true
|
||||||
|
return configInFlight
|
||||||
|
}
|
||||||
|
|
||||||
|
const pending = (async () => {
|
||||||
|
const cached = readStorage()
|
||||||
try {
|
try {
|
||||||
const res = await Taro.request({ url, method: 'GET', timeout: 5000 })
|
const remote = await fetchRemote()
|
||||||
if (res.statusCode >= 400) continue
|
if (remote) {
|
||||||
const body = res.data as { version?: number; updatedAt?: string }
|
writeStorage(remote)
|
||||||
if (body?.version != null) {
|
const result: LoadResult = {
|
||||||
return {
|
config: remote,
|
||||||
version: Number(body.version) || 0,
|
fromOffline: false,
|
||||||
updatedAt: String(body.updatedAt || ''),
|
source: 'network',
|
||||||
}
|
}
|
||||||
|
emit(result)
|
||||||
|
return result
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
/* try next */
|
/* fall through */
|
||||||
}
|
}
|
||||||
}
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
if (memory || cached) {
|
||||||
* 兜底顺序:内存 → 网络 → Storage → 包内 DEFAULT
|
|
||||||
* force=true:跳过内存,强制打 API(加群弹窗 / 前台唤醒)
|
|
||||||
*/
|
|
||||||
export function loadRemoteConfig(force = false): Promise<LoadResult> {
|
|
||||||
if (configInFlight) return configInFlight
|
|
||||||
if (!force && memory) return Promise.resolve(memory)
|
|
||||||
const pending = fetchConfigWithFallback()
|
|
||||||
configInFlight = pending
|
|
||||||
const cleanup = () => {
|
|
||||||
if (configInFlight === pending) configInFlight = null
|
|
||||||
}
|
|
||||||
void pending.then(cleanup, cleanup)
|
|
||||||
return pending
|
|
||||||
}
|
|
||||||
|
|
||||||
async function fetchConfigWithFallback(): Promise<LoadResult> {
|
|
||||||
const cached = readStorage()
|
|
||||||
|
|
||||||
try {
|
|
||||||
const remote = await fetchRemote()
|
|
||||||
if (remote) {
|
|
||||||
writeStorage(remote)
|
|
||||||
const result: LoadResult = {
|
const result: LoadResult = {
|
||||||
config: remote,
|
config: memory?.config || cached!,
|
||||||
fromOffline: false,
|
fromOffline: true,
|
||||||
source: 'network',
|
source: 'storage',
|
||||||
}
|
}
|
||||||
emit(result)
|
emit(result, { forceNotify: true })
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
} catch {
|
|
||||||
/* fall through */
|
|
||||||
}
|
|
||||||
|
|
||||||
// 断网仍保留最近一次成功配置,避免缓存过期后误恢复包内开关。
|
|
||||||
if (memory || cached) {
|
|
||||||
const result: LoadResult = {
|
const result: LoadResult = {
|
||||||
config: memory?.config || cached!,
|
config: mergeRemoteConfig(DEFAULT_REMOTE_CONFIG),
|
||||||
fromOffline: true,
|
fromOffline: true,
|
||||||
source: 'storage',
|
source: 'bundle',
|
||||||
}
|
}
|
||||||
emit(result)
|
emit(result, { forceNotify: true })
|
||||||
return result
|
return result
|
||||||
}
|
})()
|
||||||
|
|
||||||
const result: LoadResult = {
|
configInFlight = pending
|
||||||
config: mergeRemoteConfig(DEFAULT_REMOTE_CONFIG),
|
void pending.finally(() => {
|
||||||
fromOffline: true,
|
if (configInFlight === pending) configInFlight = null
|
||||||
source: 'bundle',
|
if (forceQueued) {
|
||||||
}
|
forceQueued = false
|
||||||
emit(result)
|
void loadRemoteConfig(true)
|
||||||
return result
|
}
|
||||||
|
})
|
||||||
|
return pending
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getCachedRemoteConfig(): NomadroRemoteConfig {
|
export function getCachedRemoteConfig(): NomadroRemoteConfig {
|
||||||
@ -183,122 +210,190 @@ export function isModuleEnabled(
|
|||||||
config: NomadroRemoteConfig,
|
config: NomadroRemoteConfig,
|
||||||
key: keyof NomadroRemoteConfig['modules'],
|
key: keyof NomadroRemoteConfig['modules'],
|
||||||
): boolean {
|
): boolean {
|
||||||
return Boolean(config.modules[key]?.enabled)
|
return config.modules[key]?.enabled === true
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 订阅配置变更(模块闸门 / 页面热刷新) */
|
|
||||||
export function subscribeRemoteConfig(listener: Listener): () => void {
|
export function subscribeRemoteConfig(listener: Listener): () => void {
|
||||||
listeners.add(listener)
|
listeners.add(listener)
|
||||||
if (memory) listener(memory)
|
if (memory) listener(memory)
|
||||||
return () => listeners.delete(listener)
|
return () => listeners.delete(listener)
|
||||||
}
|
}
|
||||||
|
|
||||||
function softCheckMeta(): Promise<void> {
|
function wsUrl(): string {
|
||||||
if (metaInFlight) return metaInFlight
|
return `${API_BASE.replace(/^http:/i, 'ws:').replace(/^https:/i, 'wss:')}/api/config/ws`
|
||||||
const pending = (async () => {
|
}
|
||||||
const meta = await fetchMeta()
|
|
||||||
if (!meta) {
|
function connectWebSocket() {
|
||||||
// 弱网时避免每三秒堆积 meta + 全量配置请求。
|
if (stoppedFlag || APP_TARGET === 'h5') return
|
||||||
metaFailures += 1
|
const url = wsUrl()
|
||||||
retryMetaAfter = Date.now() + Math.min(60000, META_POLL_MS * 2 ** Math.min(metaFailures, 5))
|
|
||||||
return
|
const open = () => {
|
||||||
}
|
if (stoppedFlag) return
|
||||||
metaFailures = 0
|
try {
|
||||||
retryMetaAfter = 0
|
const taskPromise = Taro.connectSocket({
|
||||||
if (memory?.source === 'network' && meta.version === knownVersion) return
|
url,
|
||||||
await loadRemoteConfig(true)
|
fail: () => {
|
||||||
})()
|
socketTask = null
|
||||||
metaInFlight = pending
|
socketReconnect = setTimeout(open, 2000)
|
||||||
const cleanup = () => {
|
},
|
||||||
if (metaInFlight === pending) metaInFlight = null
|
})
|
||||||
}
|
void Promise.resolve(taskPromise).then((sock) => {
|
||||||
void pending.then(cleanup, cleanup)
|
if (stoppedFlag) {
|
||||||
return pending
|
try {
|
||||||
|
sock.close({})
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
socketTask = sock
|
||||||
|
sock.onOpen(() => {
|
||||||
|
try {
|
||||||
|
sock.send({ data: JSON.stringify({ type: 'pull' }) })
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
void loadRemoteConfig(true)
|
||||||
|
})
|
||||||
|
sock.onMessage(() => {
|
||||||
|
void loadRemoteConfig(true)
|
||||||
|
})
|
||||||
|
sock.onClose(() => {
|
||||||
|
socketTask = null
|
||||||
|
if (!stoppedFlag) socketReconnect = setTimeout(open, 1200)
|
||||||
|
})
|
||||||
|
sock.onError(() => {
|
||||||
|
try {
|
||||||
|
sock.close({})
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
} catch {
|
||||||
|
socketReconnect = setTimeout(open, 2000)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
open()
|
||||||
|
}
|
||||||
|
|
||||||
|
function connectSse() {
|
||||||
|
if (APP_TARGET !== 'h5' || typeof EventSource === 'undefined') return
|
||||||
|
const urls = [`/api/config/stream`, `${API_BASE}/api/config/stream`]
|
||||||
|
let idx = 0
|
||||||
|
const open = () => {
|
||||||
|
if (stoppedFlag) return
|
||||||
|
if (idx >= urls.length) {
|
||||||
|
socketReconnect = setTimeout(() => {
|
||||||
|
idx = 0
|
||||||
|
open()
|
||||||
|
}, 2500)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
eventSource?.close()
|
||||||
|
const es = new EventSource(urls[idx++])
|
||||||
|
eventSource = es
|
||||||
|
es.addEventListener('config', () => {
|
||||||
|
void loadRemoteConfig(true)
|
||||||
|
})
|
||||||
|
es.onerror = () => {
|
||||||
|
es.close()
|
||||||
|
eventSource = null
|
||||||
|
if (!stoppedFlag) socketReconnect = setTimeout(open, 1500)
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
open()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
open()
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 启动实时同步:
|
|
||||||
* - H5:EventSource → /api/config/stream
|
|
||||||
* - 小程序:meta 轮询 + onShow(无 SSE)
|
|
||||||
*/
|
|
||||||
export function startRemoteConfigLiveSync(): () => void {
|
export function startRemoteConfigLiveSync(): () => void {
|
||||||
if (liveStarted) return () => {}
|
if (liveStarted) return () => {}
|
||||||
liveStarted = true
|
liveStarted = true
|
||||||
knownVersion = Number(getCachedRemoteConfig().version) || 0
|
stoppedFlag = false
|
||||||
|
clearLegacyCaches()
|
||||||
|
|
||||||
|
const cached = getCachedRemoteConfig()
|
||||||
|
knownVersion = Number(cached.version) || 0
|
||||||
|
knownFp = configFingerprint(cached)
|
||||||
|
|
||||||
let es: EventSource | null = null
|
|
||||||
let stopped = false
|
|
||||||
const onShow = () => {
|
const onShow = () => {
|
||||||
appVisible = true
|
appVisible = true
|
||||||
retryMetaAfter = 0
|
void loadRemoteConfig(true)
|
||||||
void softCheckMeta()
|
try {
|
||||||
|
socketTask?.send({ data: JSON.stringify({ type: 'pull' }) })
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const onHide = () => {
|
||||||
|
appVisible = false
|
||||||
}
|
}
|
||||||
const onHide = () => { appVisible = false }
|
|
||||||
if (APP_TARGET !== 'h5') {
|
if (APP_TARGET !== 'h5') {
|
||||||
Taro.onAppShow(onShow)
|
Taro.onAppShow(onShow)
|
||||||
Taro.onAppHide(onHide)
|
Taro.onAppHide(onHide)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (APP_TARGET === 'h5') connectSse()
|
||||||
|
else connectWebSocket()
|
||||||
|
|
||||||
|
pollTimer = setInterval(() => {
|
||||||
|
if (stoppedFlag) return
|
||||||
|
const visible =
|
||||||
|
APP_TARGET === 'h5' && typeof document !== 'undefined'
|
||||||
|
? document.visibilityState !== 'hidden'
|
||||||
|
: appVisible
|
||||||
|
if (visible) void loadRemoteConfig(true)
|
||||||
|
}, FULL_POLL_MS)
|
||||||
|
|
||||||
|
void loadRemoteConfig(true)
|
||||||
|
|
||||||
const stop = () => {
|
const stop = () => {
|
||||||
stopped = true
|
stoppedFlag = true
|
||||||
liveStarted = false
|
liveStarted = false
|
||||||
if (metaTimer) {
|
if (pollTimer) {
|
||||||
clearInterval(metaTimer)
|
clearInterval(pollTimer)
|
||||||
metaTimer = null
|
pollTimer = null
|
||||||
}
|
}
|
||||||
es?.close()
|
if (socketReconnect) {
|
||||||
es = null
|
clearTimeout(socketReconnect)
|
||||||
|
socketReconnect = null
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
socketTask?.close({})
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
socketTask = null
|
||||||
|
eventSource?.close()
|
||||||
|
eventSource = null
|
||||||
if (APP_TARGET !== 'h5') {
|
if (APP_TARGET !== 'h5') {
|
||||||
Taro.offAppShow(onShow)
|
Taro.offAppShow(onShow)
|
||||||
Taro.offAppHide(onHide)
|
Taro.offAppHide(onHide)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (APP_TARGET === 'h5' && typeof EventSource !== 'undefined') {
|
|
||||||
try {
|
|
||||||
es = new EventSource('/api/config/stream')
|
|
||||||
es.addEventListener('config', (ev) => {
|
|
||||||
try {
|
|
||||||
const data = JSON.parse(String((ev as MessageEvent).data || '{}')) as {
|
|
||||||
version?: number
|
|
||||||
}
|
|
||||||
const v = Number(data.version) || 0
|
|
||||||
if (v && v !== knownVersion) void loadRemoteConfig(true)
|
|
||||||
} catch {
|
|
||||||
void loadRemoteConfig(true)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
es.onerror = () => {
|
|
||||||
/* 断线后靠 meta 轮询兜底 */
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
/* fall through to poll */
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
metaTimer = setInterval(() => {
|
|
||||||
const visible = APP_TARGET === 'h5' && typeof document !== 'undefined'
|
|
||||||
? document.visibilityState !== 'hidden' : appVisible
|
|
||||||
if (!stopped && visible && Date.now() >= retryMetaAfter) void softCheckMeta()
|
|
||||||
}, META_POLL_MS)
|
|
||||||
|
|
||||||
// 前台可见 / 小程序 onShow 由 app 层再调 softRefreshRemoteConfig
|
|
||||||
if (APP_TARGET === 'h5' && typeof document !== 'undefined') {
|
if (APP_TARGET === 'h5' && typeof document !== 'undefined') {
|
||||||
const onVis = () => {
|
const onVis = () => {
|
||||||
if (document.visibilityState === 'visible') void softCheckMeta()
|
if (document.visibilityState === 'visible') void loadRemoteConfig(true)
|
||||||
}
|
}
|
||||||
document.addEventListener('visibilitychange', onVis)
|
document.addEventListener('visibilitychange', onVis)
|
||||||
const prevStop = stop
|
|
||||||
return () => {
|
return () => {
|
||||||
document.removeEventListener('visibilitychange', onVis)
|
document.removeEventListener('visibilitychange', onVis)
|
||||||
prevStop()
|
stop()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return stop
|
return stop
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 前台唤醒:强制检查后台 version */
|
|
||||||
export function softRefreshRemoteConfig(): void {
|
export function softRefreshRemoteConfig(): void {
|
||||||
void softCheckMeta()
|
void loadRemoteConfig(true)
|
||||||
|
try {
|
||||||
|
socketTask?.send({ data: JSON.stringify({ type: 'pull' }) })
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -334,6 +334,26 @@ html.light .hub-navbar.scrolled,
|
|||||||
margin-top: 0;
|
margin-top: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ≤3:单行;>3:2×2(由 home 按 portals.length 挂 class) */
|
||||||
|
.hub-portal-grid--row {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: row;
|
||||||
|
gap: 10px;
|
||||||
|
max-width: 640px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hub-portal-grid--row .hub-portal-card {
|
||||||
|
flex: 1 1 0%;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hub-portal-grid--2x2 {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
gap: 12px;
|
||||||
|
max-width: 520px;
|
||||||
|
}
|
||||||
|
|
||||||
.hub-gradient-text {
|
.hub-gradient-text {
|
||||||
background: var(--hub-gradient-text);
|
background: var(--hub-gradient-text);
|
||||||
-webkit-background-clip: text;
|
-webkit-background-clip: text;
|
||||||
@ -1087,18 +1107,28 @@ html.light .nd-theme-toggle,
|
|||||||
|
|
||||||
.hub-root--mini .hub-portal-grid {
|
.hub-root--mini .hub-portal-grid {
|
||||||
order: 3;
|
order: 3;
|
||||||
display: flex !important;
|
|
||||||
flex-direction: row !important;
|
|
||||||
width: 100% !important;
|
width: 100% !important;
|
||||||
max-width: 100% !important;
|
max-width: 100% !important;
|
||||||
gap: 8px !important;
|
/* 入口整体下移,视觉更松 */
|
||||||
/* 三入口整体下移,视觉更松 */
|
|
||||||
margin: 28px 0 0 !important;
|
margin: 28px 0 0 !important;
|
||||||
padding-top: 8px !important;
|
padding-top: 8px !important;
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
}
|
}
|
||||||
|
|
||||||
.hub-root--mini .hub-portal-card {
|
/* ≤3:单行均分;>3:强制 2×2 */
|
||||||
|
.hub-root--mini .hub-portal-grid--row {
|
||||||
|
display: flex !important;
|
||||||
|
flex-direction: row !important;
|
||||||
|
gap: 8px !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hub-root--mini .hub-portal-grid--2x2 {
|
||||||
|
display: grid !important;
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr)) !important;
|
||||||
|
gap: 10px !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hub-root--mini .hub-portal-grid--row .hub-portal-card {
|
||||||
flex: 1 1 0% !important;
|
flex: 1 1 0% !important;
|
||||||
min-width: 0 !important;
|
min-width: 0 !important;
|
||||||
width: auto !important;
|
width: auto !important;
|
||||||
@ -1108,6 +1138,15 @@ html.light .nd-theme-toggle,
|
|||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.hub-root--mini .hub-portal-grid--2x2 .hub-portal-card {
|
||||||
|
min-width: 0 !important;
|
||||||
|
width: auto !important;
|
||||||
|
align-items: center !important;
|
||||||
|
text-align: center !important;
|
||||||
|
padding: 16px 10px !important;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
.hub-root--mini .hub-portal-name {
|
.hub-root--mini .hub-portal-name {
|
||||||
font-size: 13px !important;
|
font-size: 13px !important;
|
||||||
white-space: normal !important;
|
white-space: normal !important;
|
||||||
|
|||||||
@ -47,7 +47,33 @@
|
|||||||
* used to false-match it and corrupt the file.
|
* used to false-match it and corrupt the file.
|
||||||
*/
|
*/
|
||||||
@layer base {
|
@layer base {
|
||||||
*, *::before, *::after {
|
/* 不用裸 * — 微信 WXSS 直接编译失败;H5 用常见标签兜底 */
|
||||||
|
page,
|
||||||
|
view,
|
||||||
|
text,
|
||||||
|
div,
|
||||||
|
span,
|
||||||
|
a,
|
||||||
|
p,
|
||||||
|
h1,
|
||||||
|
h2,
|
||||||
|
h3,
|
||||||
|
h4,
|
||||||
|
h5,
|
||||||
|
h6,
|
||||||
|
ul,
|
||||||
|
ol,
|
||||||
|
li,
|
||||||
|
button,
|
||||||
|
input,
|
||||||
|
textarea,
|
||||||
|
img,
|
||||||
|
section,
|
||||||
|
article,
|
||||||
|
header,
|
||||||
|
footer,
|
||||||
|
main,
|
||||||
|
nav {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
padding: 0;
|
padding: 0;
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
|
|||||||
@ -1275,9 +1275,12 @@
|
|||||||
.social-card:nth-child(4) {
|
.social-card:nth-child(4) {
|
||||||
animation-delay: 0.21s;
|
animation-delay: 0.21s;
|
||||||
}
|
}
|
||||||
.social-experience[data-immersive="false"] *,
|
/* 不用 * — 微信 WXSS 编译失败 */
|
||||||
.social-experience[data-immersive="false"] *::before,
|
.social-experience[data-immersive="false"],
|
||||||
.social-experience[data-immersive="false"] *::after {
|
.social-experience[data-immersive="false"] view,
|
||||||
|
.social-experience[data-immersive="false"] text,
|
||||||
|
.social-experience[data-immersive="false"] div,
|
||||||
|
.social-experience[data-immersive="false"] span {
|
||||||
animation: none !important;
|
animation: none !important;
|
||||||
transition-duration: 0.12s !important;
|
transition-duration: 0.12s !important;
|
||||||
}
|
}
|
||||||
@ -1604,10 +1607,13 @@
|
|||||||
html:has(.social-experience) {
|
html:has(.social-experience) {
|
||||||
scroll-behavior: auto;
|
scroll-behavior: auto;
|
||||||
}
|
}
|
||||||
/* Light mode only — immersive opt-in keeps motion (see motion.css). */
|
/* Light mode only — immersive opt-in keeps motion (see motion.css).
|
||||||
.social-experience[data-immersive="false"] *,
|
不用 * — 微信 WXSS 编译失败 */
|
||||||
.social-experience[data-immersive="false"] *::before,
|
.social-experience[data-immersive="false"],
|
||||||
.social-experience[data-immersive="false"] *::after {
|
.social-experience[data-immersive="false"] view,
|
||||||
|
.social-experience[data-immersive="false"] text,
|
||||||
|
.social-experience[data-immersive="false"] div,
|
||||||
|
.social-experience[data-immersive="false"] span {
|
||||||
animation: none !important;
|
animation: none !important;
|
||||||
transition: none !important;
|
transition: none !important;
|
||||||
scroll-behavior: auto !important;
|
scroll-behavior: auto !important;
|
||||||
|
|||||||
@ -1462,7 +1462,12 @@ html[data-theme="light"] .social-mobile-dock a[aria-current="page"] {
|
|||||||
.social-meetup-live .social-live-stage { flex: none; height: 480px; }
|
.social-meetup-live .social-live-stage { flex: none; height: 480px; }
|
||||||
}
|
}
|
||||||
@media (prefers-reduced-motion: reduce) {
|
@media (prefers-reduced-motion: reduce) {
|
||||||
.social-experience *, .social-experience *::before, .social-experience *::after {
|
/* 不用 * — 微信 WXSS 编译失败 */
|
||||||
|
.social-experience,
|
||||||
|
.social-experience view,
|
||||||
|
.social-experience text,
|
||||||
|
.social-experience div,
|
||||||
|
.social-experience span {
|
||||||
animation-duration: 0.01ms !important;
|
animation-duration: 0.01ms !important;
|
||||||
animation-iteration-count: 1 !important;
|
animation-iteration-count: 1 !important;
|
||||||
transition-duration: 0.01ms !important;
|
transition-duration: 0.01ms !important;
|
||||||
|
|||||||
@ -1914,10 +1914,13 @@
|
|||||||
html:has(.social-home) {
|
html:has(.social-home) {
|
||||||
scroll-behavior: auto;
|
scroll-behavior: auto;
|
||||||
}
|
}
|
||||||
/* Only when immersive is off — otherwise motion.css owns FX. */
|
/* Only when immersive is off — otherwise motion.css owns FX.
|
||||||
.social-experience[data-immersive="false"] .social-home *,
|
不用 *(微信 WXSS 直接编译失败);H5/weapp 用 view/text 兜底。 */
|
||||||
.social-experience[data-immersive="false"] .social-home *::before,
|
.social-experience[data-immersive="false"] .social-home,
|
||||||
.social-experience[data-immersive="false"] .social-home *::after {
|
.social-experience[data-immersive="false"] .social-home view,
|
||||||
|
.social-experience[data-immersive="false"] .social-home text,
|
||||||
|
.social-experience[data-immersive="false"] .social-home div,
|
||||||
|
.social-experience[data-immersive="false"] .social-home span {
|
||||||
animation: none !important;
|
animation: none !important;
|
||||||
transition: none !important;
|
transition: none !important;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -72,6 +72,8 @@ export function clearDevCaches(): void {
|
|||||||
'nomadro_memo_rev_v1',
|
'nomadro_memo_rev_v1',
|
||||||
'nomadro_shop_catalog_v2',
|
'nomadro_shop_catalog_v2',
|
||||||
'nomadro_remote_config_v1',
|
'nomadro_remote_config_v1',
|
||||||
|
'nomadro_remote_config_v2',
|
||||||
|
'nomadro_remote_config_v3',
|
||||||
'nomadro_vip_paid',
|
'nomadro_vip_paid',
|
||||||
]
|
]
|
||||||
for (const k of keys) {
|
for (const k of keys) {
|
||||||
|
|||||||
@ -6,13 +6,8 @@ export type H5Theme = 'dark' | 'light'
|
|||||||
const KEY = 'nomadro-theme'
|
const KEY = 'nomadro-theme'
|
||||||
export const THEME_EVENT = 'nomadro:theme'
|
export const THEME_EVENT = 'nomadro:theme'
|
||||||
|
|
||||||
|
/** 全端固定暗色;不再读本地 light 缓存 */
|
||||||
export function getStoredH5Theme(): H5Theme {
|
export function getStoredH5Theme(): H5Theme {
|
||||||
try {
|
|
||||||
const t = Taro.getStorageSync(KEY)
|
|
||||||
if (t === 'light' || t === 'dark') return t
|
|
||||||
} catch {
|
|
||||||
/* ignore */
|
|
||||||
}
|
|
||||||
return 'dark'
|
return 'dark'
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -37,10 +32,10 @@ export function applyH5Theme(theme: H5Theme) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function toggleH5Theme(current: H5Theme): H5Theme {
|
/** 主题切换已下线,始终暗色 */
|
||||||
const next: H5Theme = current === 'dark' ? 'light' : 'dark'
|
export function toggleH5Theme(_current?: H5Theme): H5Theme {
|
||||||
applyH5Theme(next)
|
applyH5Theme('dark')
|
||||||
return next
|
return 'dark'
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 页面订阅主题(小程序根节点挂 data-theme,对齐 H5 html[data-theme]) */
|
/** 页面订阅主题(小程序根节点挂 data-theme,对齐 H5 html[data-theme]) */
|
||||||
|
|||||||
154
apps/miniprogram/h5/src/utils/socialOps.ts
Normal file
154
apps/miniprogram/h5/src/utils/socialOps.ts
Normal file
@ -0,0 +1,154 @@
|
|||||||
|
import type { NomadroRemoteConfig } from '@/data/remoteConfig.defaults'
|
||||||
|
|
||||||
|
export const SOCIAL_PAGE_KEYS = [
|
||||||
|
'index',
|
||||||
|
'chat',
|
||||||
|
'date',
|
||||||
|
'people',
|
||||||
|
'peopleProfile',
|
||||||
|
'roster',
|
||||||
|
'meetup',
|
||||||
|
'meetupLive',
|
||||||
|
'team',
|
||||||
|
] as const
|
||||||
|
|
||||||
|
export const SOCIAL_SECTION_KEYS = [
|
||||||
|
'people',
|
||||||
|
'date',
|
||||||
|
'meetup',
|
||||||
|
'cities',
|
||||||
|
'team',
|
||||||
|
'ways',
|
||||||
|
'promo',
|
||||||
|
'invite',
|
||||||
|
] as const
|
||||||
|
|
||||||
|
export const SOCIAL_FEATURE_KEYS = [
|
||||||
|
'joinPay',
|
||||||
|
'cafeReviews',
|
||||||
|
'creationSheet',
|
||||||
|
'chatRealtime',
|
||||||
|
'livePusher',
|
||||||
|
'dateSwipe',
|
||||||
|
'rosterEdit',
|
||||||
|
'teamApply',
|
||||||
|
'dock',
|
||||||
|
'homeEntry',
|
||||||
|
] as const
|
||||||
|
|
||||||
|
export const SOCIAL_BUTTON_KEYS = [
|
||||||
|
'heroJoin',
|
||||||
|
'heroChat',
|
||||||
|
'heroDate',
|
||||||
|
'heroStory',
|
||||||
|
'wayGroup',
|
||||||
|
'wayDate',
|
||||||
|
'wayMeetup',
|
||||||
|
'wayCafe',
|
||||||
|
'wayTeam',
|
||||||
|
'dockHome',
|
||||||
|
'dockChat',
|
||||||
|
'dockDate',
|
||||||
|
'dockPeople',
|
||||||
|
'dockRoster',
|
||||||
|
] as const
|
||||||
|
|
||||||
|
export type SocialPageKey = (typeof SOCIAL_PAGE_KEYS)[number]
|
||||||
|
export type SocialSectionKey = (typeof SOCIAL_SECTION_KEYS)[number]
|
||||||
|
export type SocialFeatureKey = (typeof SOCIAL_FEATURE_KEYS)[number]
|
||||||
|
export type SocialButtonKey = (typeof SOCIAL_BUTTON_KEYS)[number]
|
||||||
|
|
||||||
|
export type SocialOpsFlags = {
|
||||||
|
pages: Record<SocialPageKey, boolean>
|
||||||
|
sections: Record<SocialSectionKey, boolean>
|
||||||
|
features: Record<SocialFeatureKey, boolean>
|
||||||
|
buttons: Record<SocialButtonKey, boolean>
|
||||||
|
}
|
||||||
|
|
||||||
|
const PAGE_PATH: Record<SocialPageKey, string> = {
|
||||||
|
index: '/pages/social/index',
|
||||||
|
chat: '/pages/social/chat/index',
|
||||||
|
date: '/pages/social/date/index',
|
||||||
|
people: '/pages/social/people/index',
|
||||||
|
peopleProfile: '/pages/social/people/profile/index',
|
||||||
|
roster: '/pages/social/roster/index',
|
||||||
|
meetup: '/pages/social/meetup/index',
|
||||||
|
meetupLive: '/pages/social/meetup-live/index',
|
||||||
|
team: '/pages/social/team/index',
|
||||||
|
}
|
||||||
|
|
||||||
|
const DOCK_BUTTON: Record<string, SocialButtonKey> = {
|
||||||
|
'/pages/social/index': 'dockHome',
|
||||||
|
'/pages/social/chat/index': 'dockChat',
|
||||||
|
'/pages/social/date/index': 'dockDate',
|
||||||
|
'/pages/social/people/index': 'dockPeople',
|
||||||
|
'/pages/social/roster/index': 'dockRoster',
|
||||||
|
}
|
||||||
|
|
||||||
|
function allTrue<T extends string>(keys: readonly T[]): Record<T, boolean> {
|
||||||
|
return Object.fromEntries(keys.map((k) => [k, true])) as Record<T, boolean>
|
||||||
|
}
|
||||||
|
|
||||||
|
function mergeBoolMap<T extends string>(
|
||||||
|
keys: readonly T[],
|
||||||
|
raw: unknown,
|
||||||
|
fallback: Record<T, boolean>,
|
||||||
|
): Record<T, boolean> {
|
||||||
|
const src = raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : {}
|
||||||
|
const out = { ...fallback }
|
||||||
|
for (const key of keys) {
|
||||||
|
if (key in src) out[key] = Boolean(src[key])
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 解析运营开关;缺省全开,兼容旧 socialHiddenSections */
|
||||||
|
export function resolveSocialOps(config: NomadroRemoteConfig): SocialOpsFlags {
|
||||||
|
const flagsRaw = (config.copy as { socialFlags?: unknown })?.socialFlags
|
||||||
|
const src = flagsRaw && typeof flagsRaw === 'object' ? (flagsRaw as Record<string, unknown>) : {}
|
||||||
|
const pages = mergeBoolMap(SOCIAL_PAGE_KEYS, src.pages, allTrue(SOCIAL_PAGE_KEYS))
|
||||||
|
const sections = mergeBoolMap(SOCIAL_SECTION_KEYS, src.sections, allTrue(SOCIAL_SECTION_KEYS))
|
||||||
|
const features = mergeBoolMap(SOCIAL_FEATURE_KEYS, src.features, allTrue(SOCIAL_FEATURE_KEYS))
|
||||||
|
const buttons = mergeBoolMap(SOCIAL_BUTTON_KEYS, src.buttons, allTrue(SOCIAL_BUTTON_KEYS))
|
||||||
|
|
||||||
|
const hidden = config.copy.socialHiddenSections
|
||||||
|
if (Array.isArray(hidden)) {
|
||||||
|
for (const id of hidden) {
|
||||||
|
if (typeof id === 'string' && id in sections) {
|
||||||
|
sections[id as SocialSectionKey] = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { pages, sections, features, buttons }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isSocialPageEnabled(flags: SocialOpsFlags, key: SocialPageKey) {
|
||||||
|
return flags.pages[key] !== false
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isSocialSectionEnabled(flags: SocialOpsFlags, key: SocialSectionKey) {
|
||||||
|
return flags.sections[key] !== false
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isSocialFeatureEnabled(flags: SocialOpsFlags, key: SocialFeatureKey) {
|
||||||
|
return flags.features[key] !== false
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isSocialButtonEnabled(flags: SocialOpsFlags, key: SocialButtonKey) {
|
||||||
|
return flags.buttons[key] !== false
|
||||||
|
}
|
||||||
|
|
||||||
|
export function socialPageKeyFromPath(path: string): SocialPageKey | null {
|
||||||
|
const clean = (path || '').split('?')[0]
|
||||||
|
const hit = (Object.keys(PAGE_PATH) as SocialPageKey[]).find((k) => PAGE_PATH[k] === clean)
|
||||||
|
return hit || null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function dockButtonKey(path: string): SocialButtonKey | null {
|
||||||
|
const clean = (path || '').split('?')[0]
|
||||||
|
return DOCK_BUTTON[clean] || null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function pagePathForKey(key: SocialPageKey) {
|
||||||
|
return PAGE_PATH[key]
|
||||||
|
}
|
||||||
@ -1,6 +1,16 @@
|
|||||||
# 微信 weapp
|
# 微信 weapp
|
||||||
|
|
||||||
## 2026-11-02:社区全部页面优化(本地验收,尚未发布)
|
## 提审定版 · tag `2026-11-02`(分支 `test9`)
|
||||||
|
|
||||||
|
准备上传微信审核 / 上线的源码定版。H5 SoT:`../h5/src`。
|
||||||
|
|
||||||
|
- **首页** `pages/home/index`:入口 2×2;固定暗色;远程开关热更新(POST `/api/config/pull` + WS)
|
||||||
|
- **数字游民小册**:封面与正式一致;提审开 → `vip-ebook` 同壳 + 线上 audit 正文;失联才包内兜底
|
||||||
|
- **游民社区**:原生分包(无 web-view);大厅 / 聊天 / 认识 / 视频等
|
||||||
|
- **WXSS**:sanitize 去掉裸 `*` / `:has` 等微信不支持选择器
|
||||||
|
- **构建**:`pnpm build:weapp` → 开发者工具打开本目录(`dist/`)→ 上传;socket 合法域名:`api.nomadro.cn`
|
||||||
|
|
||||||
|
## 2026-11-02:社区全部页面优化(已合入 test9)
|
||||||
|
|
||||||
范围为 `pages/social/index` 及 8 个原生子页面:聊天、认识一下、成员列表、成员详情、我的介绍、视频场次、视频厅、团队;包含咖啡馆评价、共创介绍、社区故事和加群支付底栏。
|
范围为 `pages/social/index` 及 8 个原生子页面:聊天、认识一下、成员列表、成员详情、我的介绍、视频场次、视频厅、团队;包含咖啡馆评价、共创介绍、社区故事和加群支付底栏。
|
||||||
|
|
||||||
|
|||||||
68
apps/miniprogram/weapp/scripts/_check-star-sel.cjs
Normal file
68
apps/miniprogram/weapp/scripts/_check-star-sel.cjs
Normal file
@ -0,0 +1,68 @@
|
|||||||
|
const fs = require('fs')
|
||||||
|
const path = require('path')
|
||||||
|
|
||||||
|
const file = path.resolve(__dirname, '../dist/pages/social/sub-vendors.wxss')
|
||||||
|
const s = fs.readFileSync(file, 'utf8')
|
||||||
|
|
||||||
|
function findMatchingBrace(css, openIdx) {
|
||||||
|
let depth = 0
|
||||||
|
for (let i = openIdx; i < css.length; i += 1) {
|
||||||
|
if (css[i] === '/' && css[i + 1] === '*') {
|
||||||
|
const end = css.indexOf('*/', i + 2)
|
||||||
|
i = end < 0 ? css.length - 1 : end + 1
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if (css[i] === '{') depth += 1
|
||||||
|
else if (css[i] === '}') {
|
||||||
|
depth -= 1
|
||||||
|
if (depth === 0) return i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
|
||||||
|
const bad = []
|
||||||
|
function walk(css) {
|
||||||
|
let i = 0
|
||||||
|
while (i < css.length) {
|
||||||
|
if (css[i] === '/' && css[i + 1] === '*') {
|
||||||
|
const end = css.indexOf('*/', i + 2)
|
||||||
|
i = end < 0 ? css.length : end + 2
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if (/\s/.test(css[i])) {
|
||||||
|
i += 1
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if (css[i] === '@') {
|
||||||
|
const brace = css.indexOf('{', i)
|
||||||
|
const semi = css.indexOf(';', i)
|
||||||
|
const name = (css.slice(i).match(/^@[a-zA-Z\-]+/) || [''])[0]
|
||||||
|
if (brace >= 0 && (semi < 0 || brace < semi)) {
|
||||||
|
const end = findMatchingBrace(css, brace)
|
||||||
|
if (end < 0) break
|
||||||
|
if (name === '@media' || name === '@supports') walk(css.slice(brace + 1, end))
|
||||||
|
i = end + 1
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if (semi >= 0) {
|
||||||
|
i = semi + 1
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
const brace = css.indexOf('{', i)
|
||||||
|
if (brace < 0) break
|
||||||
|
const end = findMatchingBrace(css, brace)
|
||||||
|
if (end < 0) break
|
||||||
|
const sel = css.slice(i, brace).trim()
|
||||||
|
if (sel && !sel.startsWith('@') && /(^|[\s>+~,])\*/.test(sel)) {
|
||||||
|
bad.push(sel.replace(/\s+/g, ' ').slice(0, 140))
|
||||||
|
}
|
||||||
|
i = end + 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
walk(s)
|
||||||
|
console.log('bad selectors', bad.length)
|
||||||
|
bad.slice(0, 30).forEach((x, idx) => console.log(idx, x))
|
||||||
29
apps/miniprogram/weapp/scripts/_dump-css.cjs
Normal file
29
apps/miniprogram/weapp/scripts/_dump-css.cjs
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
const fs = require('fs')
|
||||||
|
const s = fs.readFileSync(
|
||||||
|
require('path').join(__dirname, '../dist/pages/social/sub-vendors.wxss'),
|
||||||
|
'utf8',
|
||||||
|
)
|
||||||
|
|
||||||
|
function dumpAround(needle, pad = 300) {
|
||||||
|
let from = 0
|
||||||
|
let n = 0
|
||||||
|
while (n < 4) {
|
||||||
|
const i = s.indexOf(needle, from)
|
||||||
|
if (i < 0) break
|
||||||
|
console.log('\n====', needle, '@', i, '====')
|
||||||
|
console.log(s.slice(i, i + pad))
|
||||||
|
from = i + needle.length
|
||||||
|
n += 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
;[
|
||||||
|
'.connection-ways{',
|
||||||
|
'.connection-way{',
|
||||||
|
'.social-home .connection-ways{',
|
||||||
|
'.social-home .connection-copy, .social-home .connection-universe{',
|
||||||
|
'.footer-grid{',
|
||||||
|
'.footer-links{',
|
||||||
|
'opacity: 0',
|
||||||
|
'connection-rise',
|
||||||
|
].forEach((n) => dumpAround(n, 280))
|
||||||
17
apps/miniprogram/weapp/scripts/_nuke-star-wxss.cjs
Normal file
17
apps/miniprogram/weapp/scripts/_nuke-star-wxss.cjs
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
/** 最后兜底:直接从 dist wxss 删除选择器含 * 的规则 */
|
||||||
|
const fs = require('fs')
|
||||||
|
const path = require('path')
|
||||||
|
const { sanitizeDir, sanitizeWxssSource } = require('./sanitize-wxss-plugin.cjs')
|
||||||
|
|
||||||
|
const dist = path.resolve(__dirname, '..', 'dist')
|
||||||
|
console.log(sanitizeDir(dist))
|
||||||
|
|
||||||
|
const file = path.join(dist, 'pages/social/sub-vendors.wxss')
|
||||||
|
if (fs.existsSync(file)) {
|
||||||
|
let s = fs.readFileSync(file, 'utf8')
|
||||||
|
s = sanitizeWxssSource(s)
|
||||||
|
fs.writeFileSync(file, s)
|
||||||
|
const stars = s.match(/(?:^|[\s>+~,])\*[^{]*\{/gm) || []
|
||||||
|
console.log('sub-vendors star rules left:', stars.length)
|
||||||
|
if (stars[0]) console.log('sample', stars[0].slice(0, 80))
|
||||||
|
}
|
||||||
36
apps/miniprogram/weapp/scripts/_run-sanitize-once.cjs
Normal file
36
apps/miniprogram/weapp/scripts/_run-sanitize-once.cjs
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
const fs = require('fs')
|
||||||
|
const path = require('path')
|
||||||
|
const { sanitizeDir, sanitizeWxssSource, rewriteSelectorList } = require('./sanitize-wxss-plugin.cjs')
|
||||||
|
|
||||||
|
const samples = [
|
||||||
|
'.connection-copy h1',
|
||||||
|
'.social-home .nav-links:not(.open)',
|
||||||
|
'.social-cafe-grid .social-card > :not(.social-cafe-art)',
|
||||||
|
'.social-meetup-faces > *:first-child',
|
||||||
|
'.social-home :is(a, button):focus-visible',
|
||||||
|
]
|
||||||
|
for (const s of samples) {
|
||||||
|
console.log(s, '=>', rewriteSelectorList(s) || '(dropped)')
|
||||||
|
}
|
||||||
|
|
||||||
|
const dist = path.resolve(__dirname, '../dist')
|
||||||
|
const t0 = Date.now()
|
||||||
|
const r = sanitizeDir(dist)
|
||||||
|
console.log('sanitizeDir', r, 'ms', Date.now() - t0)
|
||||||
|
|
||||||
|
const vendors = path.join(dist, 'pages/social/sub-vendors.wxss')
|
||||||
|
if (fs.existsSync(vendors)) {
|
||||||
|
const s = fs.readFileSync(vendors, 'utf8')
|
||||||
|
console.log({
|
||||||
|
bytes: s.length,
|
||||||
|
asH1: (s.match(/\.as-h1/g) || []).length,
|
||||||
|
asA: (s.match(/\.as-a/g) || []).length,
|
||||||
|
asButton: (s.match(/\.as-button/g) || []).length,
|
||||||
|
connectionCopy: (s.match(/\.connection-copy\s+\.as-h1/g) || []).length,
|
||||||
|
rawTagH1: (s.match(/(^|[^\w-])h1(\s|,|\{|>)/gm) || []).length,
|
||||||
|
notLeft: (s.match(/:not\(/g) || []).length,
|
||||||
|
hasLeft: (s.match(/:has\(/g) || []).length,
|
||||||
|
})
|
||||||
|
const idx = s.indexOf('.connection-copy .as-h1')
|
||||||
|
console.log('snippet', s.slice(Math.max(0, idx), idx + 180))
|
||||||
|
}
|
||||||
28
apps/miniprogram/weapp/scripts/_test-rewrite.cjs
Normal file
28
apps/miniprogram/weapp/scripts/_test-rewrite.cjs
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
const { rewriteSelectorList, sanitizeWxssSource } = require('./sanitize-wxss-plugin.cjs')
|
||||||
|
|
||||||
|
const samples = [
|
||||||
|
'.connection-copy h1',
|
||||||
|
'.social-home :is(a, button, input):focus-visible',
|
||||||
|
'.social-page-intro > :not(.social-emoji-field)',
|
||||||
|
'html:has(.social-home)',
|
||||||
|
'.social-meetup-faces > *:first-child',
|
||||||
|
'.navbar a, .navbar button',
|
||||||
|
'.social-panel-meta > :is(span, time)',
|
||||||
|
]
|
||||||
|
|
||||||
|
for (const s of samples) {
|
||||||
|
console.log(s, '=>', rewriteSelectorList(s) || '(dropped)')
|
||||||
|
}
|
||||||
|
|
||||||
|
const css = `
|
||||||
|
.connection-copy h1 { font-size: 32px; color: #fff; }
|
||||||
|
.social-home :is(a, button) { color: red; }
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
.social-home h2 { animation: none; }
|
||||||
|
}
|
||||||
|
@media (max-width: 640px) {
|
||||||
|
.connection-hero h1 { font-size: 28px; }
|
||||||
|
}
|
||||||
|
`
|
||||||
|
console.log('--- sanitized ---')
|
||||||
|
console.log(sanitizeWxssSource(css))
|
||||||
43
apps/miniprogram/weapp/scripts/_test-sanitize.mjs
Normal file
43
apps/miniprogram/weapp/scripts/_test-sanitize.mjs
Normal file
@ -0,0 +1,43 @@
|
|||||||
|
import { createRequire } from 'module'
|
||||||
|
const require = createRequire(import.meta.url)
|
||||||
|
const { sanitizeWxssSource, sanitizeDir } = require('./sanitize-wxss-plugin.cjs')
|
||||||
|
const fs = require('fs')
|
||||||
|
const path = require('path')
|
||||||
|
|
||||||
|
const sample = `/* MUST stay in layer base. Unlayered * { padding:0; margin:0 } beats Tailwind */
|
||||||
|
@layer base {
|
||||||
|
*, *::before, *::after {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@media (max-width: 900px) {
|
||||||
|
.social-home .social-panel-meta > :is(span, time) { font-size: 8px; }
|
||||||
|
html:has(.social-home) { scroll-behavior: auto; }
|
||||||
|
.ok { color: red; }
|
||||||
|
}
|
||||||
|
`
|
||||||
|
const out = sanitizeWxssSource(sample)
|
||||||
|
console.log(out)
|
||||||
|
console.log('---counts---', {
|
||||||
|
layer: (out.match(/@layer/g) || []).length,
|
||||||
|
has: (out.match(/:has\s*\(/g) || []).length,
|
||||||
|
is: (out.match(/:is\s*\(/g) || []).length,
|
||||||
|
star: /\*, \*::before/.test(out),
|
||||||
|
ok: out.includes('.ok'),
|
||||||
|
pageReset: out.includes('page, .soc-taro-root'),
|
||||||
|
})
|
||||||
|
|
||||||
|
const dist = path.resolve('dist')
|
||||||
|
if (fs.existsSync(path.join(dist, 'pages/social/sub-vendors.wxss'))) {
|
||||||
|
const raw = fs.readFileSync(path.join(dist, 'pages/social/sub-vendors.wxss'), 'utf8')
|
||||||
|
const cleaned = sanitizeWxssSource(raw)
|
||||||
|
fs.writeFileSync(path.join(dist, 'pages/social/sub-vendors.wxss'), cleaned)
|
||||||
|
console.log('dist cleaned', {
|
||||||
|
layer: (cleaned.match(/@layer/g) || []).length,
|
||||||
|
has: (cleaned.match(/:has\s*\(/g) || []).length,
|
||||||
|
is: (cleaned.match(/:is\s*\(/g) || []).length,
|
||||||
|
star: /\*, \*::before/.test(cleaned),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
console.log(sanitizeDir(dist))
|
||||||
@ -64,8 +64,9 @@ class EnsurePageWxssPlugin {
|
|||||||
// 落盘前清洗:避免微信热重载抢在 setTimeout sanitize 前编译 :is()
|
// 落盘前清洗:避免微信热重载抢在 setTimeout sanitize 前编译 :is()
|
||||||
if (RawSource && compiler.hooks.compilation) {
|
if (RawSource && compiler.hooks.compilation) {
|
||||||
compiler.hooks.compilation.tap('EnsurePageWxssPlugin', (compilation) => {
|
compiler.hooks.compilation.tap('EnsurePageWxssPlugin', (compilation) => {
|
||||||
|
// 尽量靠后:等 mini-css/extract 写完再洗,避免微信抢编译脏 * / :has
|
||||||
const stage =
|
const stage =
|
||||||
compilation.constructor.PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE ?? 7000
|
compilation.constructor.PROCESS_ASSETS_STAGE_REPORT ?? 5000
|
||||||
compilation.hooks.processAssets.tap(
|
compilation.hooks.processAssets.tap(
|
||||||
{ name: 'EnsurePageWxssPlugin', stage },
|
{ name: 'EnsurePageWxssPlugin', stage },
|
||||||
(assets) => {
|
(assets) => {
|
||||||
@ -110,6 +111,10 @@ class EnsurePageWxssPlugin {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// afterEmit:文件已落盘立刻同步洗,抢在微信热编译前
|
||||||
|
compiler.hooks.afterEmit.tap('EnsurePageWxssPlugin', () => {
|
||||||
|
run('afterEmit')
|
||||||
|
})
|
||||||
compiler.hooks.done.tap('EnsurePageWxssPlugin', () => {
|
compiler.hooks.done.tap('EnsurePageWxssPlugin', () => {
|
||||||
run('done')
|
run('done')
|
||||||
setTimeout(() => run('300ms'), 300)
|
setTimeout(() => run('300ms'), 300)
|
||||||
|
|||||||
@ -323,13 +323,19 @@ html.light .hub-navbar.scrolled,
|
|||||||
margin-top: 0;
|
margin-top: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ≤3 入口:宽屏可单行;>3 始终 2×2,避免四格挤成一条 */
|
||||||
@media (min-width: 900px) {
|
@media (min-width: 900px) {
|
||||||
.hub-portal-grid {
|
.hub-portal-grid--row {
|
||||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||||
max-width: 720px;
|
max-width: 640px;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.hub-portal-grid--2x2 {
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
max-width: 520px;
|
||||||
|
}
|
||||||
|
|
||||||
.hub-gradient-text {
|
.hub-gradient-text {
|
||||||
background: var(--hub-gradient-text);
|
background: var(--hub-gradient-text);
|
||||||
-webkit-background-clip: text;
|
-webkit-background-clip: text;
|
||||||
|
|||||||
@ -397,7 +397,11 @@ export function Hero() {
|
|||||||
<GlobeVisual />
|
<GlobeVisual />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="hub-portal-grid hub-reveal">
|
<div
|
||||||
|
className={`hub-portal-grid hub-reveal${
|
||||||
|
portals.length > 3 ? " hub-portal-grid--2x2" : " hub-portal-grid--row"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
{portals.map((portal) => {
|
{portals.map((portal) => {
|
||||||
const href = EXTERNAL_JUMP_ENABLED
|
const href = EXTERNAL_JUMP_ENABLED
|
||||||
? EXTERNAL_PORTALS[portal.id]
|
? EXTERNAL_PORTALS[portal.id]
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user