Ship WeChat admin UX overhaul and VIP content library.

Restructure /wechat nav (VIP submenu for ebooks/course/shop/memo), rebuild ops pages with shared wx UI, and wire vip-library remote content end-to-end with README paths.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Eric 2026-10-11 09:59:57 +08:00
parent 02232177e9
commit 9779b80d25
44 changed files with 7999 additions and 1450 deletions

View File

@ -25,6 +25,27 @@ scripts/ 本地开发 / 清理(dev-api · clean-artifacts)
后台平台:`/wechat/*` 微信 · `/douyin/*` 抖音。抖音加群弹窗(公众号 / 抖音群)集成在 **`/douyin/modules`**(非独立页)。
### 微信后台(admin.nomadro.cn/wechat)
侧栏分组:**总览** · **内容** · **运营** · **数据与发布**。系统字体;侧栏菜单区单独滚动、底栏固定。
| 分组 | 菜单 | 路径 |
|------|------|------|
| 总览 | 运营概览 | `/wechat` |
| 内容 | 导航(组内第一) | `/wechat/nav` |
| 内容 | 小册与试读% | `/wechat/books/default` |
| 内容 | **VIP**(二级)→ 运营配置 | `/wechat/vip` |
| | → 电子书 | `/wechat/vip/ebooks` |
| | → 视频课程 | `/wechat/vip/course` |
| | → 电商 | `/wechat/shop` |
| | → 知识社群 | `/wechat/memo` |
| 运营 | 读者 · 订单 | `/wechat/users` · `/wechat/orders` |
| 数据 | 埋点 · 部署检查清单 | `/wechat/events` · `/wechat/checklist` |
兼容:`/wechat/vip/library` → 重定向到 `/wechat/vip/ebooks`。
UI 组件:`apps/admin/src/pages/wechat.css` · `apps/admin/src/components/wxUi.tsx`。
发版 admin:`cd apps/admin && pnpm exec vite build && python deploy/redeploy_admin.py`(根仓 `@types/react@19` 时勿裸跑 `tsc -b`)。
### 微信小程序 VIP(原生,禁止 web-view)
对照 `src/modules/vip` / nomadvip H5,微信端业务内容必须原生页(见 `.cursor/rules/no-webview-content.mdc`):
@ -39,15 +60,18 @@ scripts/ 本地开发 / 清理(dev-api · clean-artifacts)
| **设备商城** | `pages/vip-store*` | 虚拟卡 + 实物发货;微信 `chooseAddress` |
内容种子:`h5/src/data/vipEbooks.ts` · `vipLessonContent.ts` · `vipStoreCatalog.ts`(可由 `h5/scripts/extract-vip-*.py` 从 `src/modules/vip/app/data` 重生)。
后台:`apps/admin` → VIP · **导航**(`/wechat/nav`)· **知识社群**(`/wechat/memo`)· **电商**(`/wechat/shop`)。
正式正文库:`data/vip-library.json`(电子书章节 / 视频课 / 课时文档);公开 `GET /api/vip/ebooks/{id}` · `/api/vip/course` · `/api/vip/lessons/{key}`;小程序优先拉远程,失败用包内兜底。落地页运营仍走 `platforms.weapp.vipContent`(`/api/config`)。
下单:`POST /api/ebook/pay/vip-order` · 商城 `/api/ebook/shop/*` · 社群 `/api/ebook/memo/*` · 导航 `/api/admin/nav`。
部署脚本(本地构建 admin + 同步 API):
```bash
python apps/admin/deploy/deploy_nav.py # 导航远程 CRUD
python apps/admin/deploy/deploy_shop.py # 电商
python apps/admin/deploy/deploy_memo.py # 知识社群
python apps/admin/deploy/deploy_vip_library.py # VIP 正式内容库 + Admin
python apps/admin/deploy/deploy_vip_admin.py # VIP 付费/落地页运营
python apps/admin/deploy/deploy_nav.py # 导航远程 CRUD
python apps/admin/deploy/deploy_shop.py # 电商
python apps/admin/deploy/deploy_memo.py # 知识社群
python apps/admin/deploy/redeploy_admin.py # 仅同步 admin dist 到线上
```

View File

@ -0,0 +1,124 @@
#!/usr/bin/env python3
"""Export VIP formal content seed JSON from miniprogram H5 data TS files."""
from __future__ import annotations
import json
import re
from datetime import datetime, timezone
from pathlib import Path
REPO = Path(__file__).resolve().parents[3]
H5 = REPO / "apps" / "miniprogram" / "h5" / "src" / "data"
OUT = REPO / "apps" / "api" / "services" / "ebook_svc" / "data" / "vip_library_seed.json"
def _extract_json_assign(text: str, name: str):
m = re.search(rf"(?:export\s+)?const {name}\s*(?::[^=]+)?=\s*", text)
if not m:
raise SystemExit(f"missing {name}")
i = m.end()
while i < len(text) and text[i].isspace():
i += 1
if text[i] not in "{[":
raise SystemExit(f"{name}: expected object/array")
open_ch, close_ch = ("{", "}") if text[i] == "{" else ("[", "]")
depth = 0
in_str = False
esc = False
j = i
while j < len(text):
ch = text[j]
if in_str:
if esc:
esc = False
elif ch == "\\":
esc = True
elif ch == '"':
in_str = False
else:
if ch == '"':
in_str = True
elif ch == open_ch:
depth += 1
elif ch == close_ch:
depth -= 1
if depth == 0:
raw = text[i : j + 1]
# TS → JSON: trailing commas, quotes, bare keys
raw = re.sub(r",\s*([}\]])", r"\1", raw)
raw = re.sub(r"(?m)^\s*'([^']+)'\s*:", r'"\1":', raw)
raw = re.sub(r"([{\[,]\s*)([A-Za-z_][A-Za-z0-9_]*)\s*:", r'\1"\2":', raw)
raw = re.sub(r":\s*'([^']*)'", r': "\1"', raw)
return json.loads(raw)
j += 1
raise SystemExit(f"{name}: unclosed")
def main() -> int:
ebooks = _extract_json_assign((H5 / "vipEbooks.ts").read_text(encoding="utf-8"), "VIP_EBOOKS")
course_txt = (H5 / "vipCourse.ts").read_text(encoding="utf-8")
videos = _extract_json_assign(course_txt, "V")
fallback = (
"https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"
)
# RAW uses unquoted keys — parse lesson rows via regex
row_re = re.compile(
r"\{\s*name:\s*'([^']*)'\s*,\s*duration:\s*'([^']*)'\s*,\s*key:\s*'([^']*)'\s*\}"
)
mod_re = re.compile(
r"\{\s*emoji:\s*'([^']*)'\s*,\s*title:\s*'([^']*)'\s*,\s*lessons:\s*\[(.*?)\]\s*,?\s*\}",
re.S,
)
# slice RAW block
mi0 = course_txt.find("const RAW =")
mi1 = course_txt.find("] as const", mi0)
raw_block = course_txt[mi0:mi1]
course_mods = []
for mi, mm in enumerate(mod_re.finditer(raw_block)):
lessons_list = []
for li, lm in enumerate(row_re.finditer(mm.group(3))):
key = lm.group(3)
lessons_list.append(
{
"key": key,
"moduleIndex": mi,
"lessonIndex": li,
"name": lm.group(1),
"duration": lm.group(2),
"videoUrl": str(videos.get(key) or fallback),
}
)
course_mods.append(
{"emoji": mm.group(1), "title": mm.group(2), "lessons": lessons_list}
)
if not course_mods:
raise SystemExit("failed to parse RAW modules")
lessons = _extract_json_assign(
(H5 / "vipLessonContent.ts").read_text(encoding="utf-8"), "VIP_LESSON_CONTENT"
)
lib = {
"version": 1,
"updatedAt": datetime.now(timezone.utc).isoformat(),
"ebooks": ebooks,
"course": {"id": "cloudphone", "title": "云手机实战课", "modules": course_mods},
"lessons": lessons,
}
OUT.parent.mkdir(parents=True, exist_ok=True)
OUT.write_text(json.dumps(lib, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
print(
"wrote",
OUT,
"ebooks",
list(ebooks.keys()),
"modules",
len(course_mods),
"lessons",
len(lessons),
"kb",
OUT.stat().st_size // 1024,
)
return 0
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,259 @@
#!/usr/bin/env python3
"""Deploy WeChat VIP admin UI + API (additive; does not wipe remote-config / orders / users).
- Admin SPA → /www/wwwroot/admin.nomadro.cn
- New vip_admin / vip_config + patch main.py (idempotent)
- remote-config: ONLY add missing keys (joinGroupAction=popup, game.enabled=false)
never overwrite existing flags/modules/platforms/copy values
- Restart nomadmini-api (fast); does not touch SQLite / ebook content
"""
from __future__ import annotations
import io
import subprocess
import tarfile
import time
from pathlib import Path
import paramiko
ROOT = Path(__file__).resolve().parents[1] # apps/admin
REPO = ROOT.parents[1]
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
EBOOK = REPO / "apps" / "api" / "services" / "ebook_svc"
def to_app_pkg(text: str) -> str:
return text.replace("ebook_svc.", "app.")
REMOTE_SH = r"""
set -euo pipefail
cd /tmp
rm -rf vip-unpack && mkdir vip-unpack
tar -xzf vip-release.tar.gz -C vip-unpack
# --- admin SPA (static only) ---
if [ -d vip-unpack/admin-dist ]; then
sudo rsync -a --delete vip-unpack/admin-dist/ /www/wwwroot/admin.nomadro.cn/
sudo chown -R www:www /www/wwwroot/admin.nomadro.cn
echo admin_dist_synced
fi
# --- API additive files ---
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
echo API_ROOT=$API_ROOT
B=$API_ROOT/app
if [ ! -d "$B" ]; then B=$API_ROOT/backend/app; fi
sudo mkdir -p "$B/routers" "$B/services"
sudo cp vip-unpack/backend/routers/vip_admin.py "$B/routers/"
sudo cp vip-unpack/backend/services/vip_config.py "$B/services/"
sudo cp vip-unpack/backend/services/vip_content.py "$B/services/"
MAIN="$B/main.py"
sudo python3 <<PY
from pathlib import Path
p = Path("$MAIN")
t = p.read_text(encoding="utf-8")
changed = False
# ensure import
if "vip_admin" not in t:
for old, new in (
(
"from app.routers import admin, auth, books, douyin_admin, join_group_admin, pay, public_config, track",
"from app.routers import admin, auth, books, douyin_admin, join_group_admin, pay, public_config, track, vip_admin",
),
(
"from app.routers import admin, auth, books, douyin_admin, join_group_admin, pay, track",
"from app.routers import admin, auth, books, douyin_admin, join_group_admin, pay, track, vip_admin",
),
(
"from app.routers import admin, auth, books, douyin_admin, pay, track",
"from app.routers import admin, auth, books, douyin_admin, pay, track, vip_admin",
),
):
if old in t:
t = t.replace(old, new, 1)
changed = True
break
if "vip_admin" not in t:
raise SystemExit("failed to patch vip_admin import")
# ensure include_router
if "include_router(vip_admin.router)" not in t:
for needle in (
"app.include_router(join_group_admin.router)",
"app.include_router(public_config.router)",
"app.include_router(douyin_admin.router)",
):
if needle in t:
t = t.replace(needle, needle + "\napp.include_router(vip_admin.router)", 1)
changed = True
break
if "include_router(vip_admin.router)" not in t:
raise SystemExit("failed to patch vip_admin include_router")
if changed:
p.write_text(t, encoding="utf-8")
print("main.py patched")
else:
print("main.py already ok")
PY
# remote-config: ADDITIVE ONLY — defaults closed; never overwrite existing values
for CFG in /var/www/nomadro.cn/data/remote-config.json /www/wwwroot/nomadro.cn/data/remote-config.json; do
if [ -f "$CFG" ]; then
echo "seed $CFG"
sudo python3 <<PY
import json
from pathlib import Path
p = Path("$CFG")
cfg = json.loads(p.read_text(encoding="utf-8"))
flags = cfg.setdefault("flags", {})
modules = cfg.setdefault("modules", {})
changed = False
if "joinGroupAction" not in flags:
flags["joinGroupAction"] = "popup"
changed = True
game = modules.get("game")
if not isinstance(game, dict):
modules["game"] = {"enabled": False, "title": "Nomad Day 3D", "note": "default hidden"}
changed = True
elif "enabled" not in game:
game = dict(game)
game["enabled"] = False
modules["game"] = game
changed = True
vip = modules.get("vip")
if not isinstance(vip, dict):
modules["vip"] = {"enabled": False, "title": "会员中心"}
changed = True
# do NOT flip existing vip.enabled — preserves online if already on
if changed:
cfg["flags"] = flags
cfg["modules"] = modules
try:
cfg["version"] = int(cfg.get("version") or 1) + 1
except Exception:
cfg["version"] = 2
bak = p.with_suffix(p.suffix + ".bak-vip-seed")
try:
bak.write_text(p.read_text(encoding="utf-8"), encoding="utf-8")
except Exception:
pass
p.write_text(json.dumps(cfg, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print("remote-config additive seed ok")
else:
print("remote-config already has keys; untouched values")
print("joinGroupAction=", flags.get("joinGroupAction"), "game=", modules.get("game"), "vip=", modules.get("vip"))
PY
fi
done
sudo systemctl restart nomadmini-api
sleep 4
systemctl is-active nomadmini-api
echo "--- smoke ---"
curl -sk -o /dev/null -w "admin %{http_code}\n" https://admin.nomadro.cn/
curl -sk -o /dev/null -w "wechat_vip_page %{http_code}\n" https://admin.nomadro.cn/wechat/vip
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',''))" || true)
echo "token_len=${#TOK}"
if [ -n "$TOK" ]; then
curl -sk -H "Authorization: Bearer $TOK" https://api.nomadro.cn/api/admin/vip | python3 -c "
import sys,json
d=json.load(sys.stdin)
vc=d.get('vipContent') or {}
print('vip_api', d.get('ok'), d.get('vipOfferKey'), d.get('vipCta'), d.get('vipProductId'), d.get('is_free'))
print('vipContent', bool(vc), 'topics', len(vc.get('topics') or []), 'showCta', vc.get('showCta'), 'hero', (vc.get('heroTitleAccent') or '')[:12])
print('price_untouched', d.get('vipPriceFen'), d.get('vipProductId'))
"
curl -sk -H "Authorization: Bearer $TOK" https://api.nomadro.cn/api/admin/product-offers | python3 -c "import sys,json; d=json.load(sys.stdin); print('offers', len(d.get('items') or []))"
curl -sk -H "Authorization: Bearer $TOK" https://api.nomadro.cn/api/admin/stats | python3 -c "import sys,json; d=json.load(sys.stdin); print('stats_ok', 'users' in d, 'paid_orders' in d)"
# platforms.tt must still exist if present; public config must expose platforms
curl -sk https://api.nomadro.cn/api/config | python3 -c "
import sys,json
d=json.load(sys.stdin)
cfg=d.get('config') or d
plats=cfg.get('platforms') or {}
print('public_platforms', sorted(plats.keys()), 'weapp_vip', isinstance((plats.get('weapp') or {}).get('vipContent'), dict) or 'weapp' not in plats)
print('tt_present', 'tt' in plats)
print('copy_vipPriceFen', (cfg.get('copy') or {}).get('vipPriceFen'))
"
fi
rm -rf vip-unpack vip-release.tar.gz
echo DONE
"""
def main() -> int:
print("building admin (vite only; skip tsc type friction)…", flush=True)
r = subprocess.run(
["pnpm", "exec", "vite", "build"],
cwd=ROOT,
shell=True,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
)
out = (r.stdout or "").encode("ascii", "replace").decode("ascii")
print(out[-800:], flush=True)
if r.returncode != 0:
err = (r.stderr or "").encode("ascii", "replace").decode("ascii")
print(err, flush=True)
return r.returncode or 1
dist = ROOT / "dist"
if not (dist / "index.html").exists():
print("missing admin dist")
return 1
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
for p in dist.rglob("*"):
if p.is_file():
tar.add(p, arcname="admin-dist/" + p.relative_to(dist).as_posix())
for name, src in (
("backend/routers/vip_admin.py", EBOOK / "routers" / "vip_admin.py"),
("backend/services/vip_config.py", EBOOK / "services" / "vip_config.py"),
("backend/services/vip_content.py", EBOOK / "services" / "vip_content.py"),
):
text = to_app_pkg(src.read_text(encoding="utf-8")).encode("utf-8")
info = tarfile.TarInfo(name=name)
info.size = len(text)
tar.addfile(info, io.BytesIO(text))
payload = buf.getvalue()
print(f"pack {len(payload)/1024:.1f} KB", 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/vip-release.tar.gz", "wb") as rf:
rf.write(payload)
sftp.close()
print("uploaded", flush=True)
_, stdout, _ = c.exec_command(REMOTE_SH, timeout=240, 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()
print(f"[exit {code}]", flush=True)
return code
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,226 @@
#!/usr/bin/env python3
"""Deploy VIP formal content library (ebooks/courses) + Admin VIP Library UI.
Additive: does not wipe remote-config / orders / platforms.tt.
Seeds vip-library.json only when missing (from package seed).
"""
from __future__ import annotations
import io
import subprocess
import tarfile
import time
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"
EBOOK = REPO / "apps" / "api" / "services" / "ebook_svc"
SEED = EBOOK / "data" / "vip_library_seed.json"
def to_app_pkg(text: str) -> str:
return text.replace("ebook_svc.", "app.")
def main() -> int:
# refresh seed from H5 SoT
print("exporting vip_library_seed.json…", flush=True)
er = subprocess.run(
[
"node",
"--experimental-strip-types",
"--experimental-transform-types",
str(ROOT / "deploy" / "_export_vip_library_seed.mts"),
],
cwd=REPO,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
)
print((er.stdout or "")[-400:], flush=True)
if er.returncode != 0:
print(er.stderr[-800:], flush=True)
return er.returncode or 1
if not SEED.is_file():
print("missing seed", SEED)
return 1
print("building admin…", flush=True)
r = subprocess.run(
["pnpm", "exec", "vite", "build"],
cwd=ROOT,
shell=True,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
)
log = ((r.stdout or "") + (r.stderr or ""))[-800:]
print(log.encode("ascii", "replace").decode("ascii"), flush=True)
if r.returncode != 0:
return r.returncode or 1
dist = ROOT / "dist"
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
for p in dist.rglob("*"):
if p.is_file():
tar.add(p, arcname="admin-dist/" + p.relative_to(dist).as_posix())
files = (
("backend/routers/vip_admin.py", EBOOK / "routers" / "vip_admin.py"),
("backend/routers/vip_library_admin.py", EBOOK / "routers" / "vip_library_admin.py"),
("backend/routers/vip_library_public.py", EBOOK / "routers" / "vip_library_public.py"),
("backend/services/vip_config.py", EBOOK / "services" / "vip_config.py"),
("backend/services/vip_content.py", EBOOK / "services" / "vip_content.py"),
("backend/services/vip_library.py", EBOOK / "services" / "vip_library.py"),
("backend/data/vip_library_seed.json", SEED),
)
for name, src in files:
data = src.read_bytes()
if name.endswith(".py"):
data = to_app_pkg(data.decode("utf-8")).encode("utf-8")
info = tarfile.TarInfo(name=name)
info.size = len(data)
tar.addfile(info, io.BytesIO(data))
payload = buf.getvalue()
print(f"pack {len(payload)/1024:.1f} KB", 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/vip-library-release.tar.gz", "wb") as rf:
rf.write(payload)
with sftp.file("/tmp/vip-library-deploy.sh", "w") as sf:
sf.write(_REMOTE_CLEAN)
sftp.close()
print("uploaded", flush=True)
_, stdout, _ = c.exec_command("bash /tmp/vip-library-deploy.sh", 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()
print(f"[exit {code}]", flush=True)
return code
_REMOTE_CLEAN = r"""#!/bin/bash
set -euo pipefail
cd /tmp
rm -rf vip-lib-unpack && mkdir vip-lib-unpack
tar -xzf vip-library-release.tar.gz -C vip-lib-unpack
if [ -d vip-lib-unpack/admin-dist ]; then
sudo rsync -a --delete vip-lib-unpack/admin-dist/ /www/wwwroot/admin.nomadro.cn/
sudo chown -R www:www /www/wwwroot/admin.nomadro.cn
echo admin_dist_synced
fi
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
[ -d "$B" ] || B=$API_ROOT/backend/app
echo API_ROOT=$API_ROOT B=$B
sudo mkdir -p "$B/routers" "$B/services" "$B/data"
sudo cp vip-lib-unpack/backend/routers/vip_admin.py "$B/routers/"
sudo cp vip-lib-unpack/backend/routers/vip_library_admin.py "$B/routers/"
sudo cp vip-lib-unpack/backend/routers/vip_library_public.py "$B/routers/"
sudo cp vip-lib-unpack/backend/services/vip_config.py "$B/services/"
sudo cp vip-lib-unpack/backend/services/vip_content.py "$B/services/"
sudo cp vip-lib-unpack/backend/services/vip_library.py "$B/services/"
sudo cp vip-lib-unpack/backend/data/vip_library_seed.json "$B/data/"
for DIR in /var/www/nomadro.cn/data /www/wwwroot/nomadro.cn/data; do
if [ -d "$DIR" ]; then
if [ ! -f "$DIR/vip-library.json" ]; then
sudo cp vip-lib-unpack/backend/data/vip_library_seed.json "$DIR/vip-library.json"
sudo chown ubuntu:ubuntu "$DIR/vip-library.json" 2>/dev/null || sudo chown www:www "$DIR/vip-library.json" 2>/dev/null || true
echo "seeded $DIR/vip-library.json"
else
echo "keep existing $DIR/vip-library.json"
fi
fi
done
MAIN="$B/main.py"
sudo python3 - <<PY
from pathlib import Path
import ast, re
p = Path("$MAIN")
t = p.read_text(encoding="utf-8")
changed = False
m = re.search(r"from app\.routers import \((.*?)\)\n", t, re.S)
if m:
names = []
for part in m.group(1).replace("\n", ",").split(","):
n = part.strip()
if n and n not in names:
names.append(n)
for req in ("vip_admin", "vip_library_admin", "vip_library_public"):
if req not in names:
names.append(req)
changed = True
block = "from app.routers import (\n" + ",\n".join(f" {n}" for n in names) + "\n)\n"
t = t[: m.start()] + block + t[m.end() :]
elif "vip_library_admin" not in t:
# single-line import → parenthesize and append
m2 = re.search(r"from app\.routers import ([^\n]+)\n", t)
if not m2:
raise SystemExit("cannot find routers import")
names = [x.strip() for x in m2.group(1).split(",") if x.strip()]
for req in ("vip_admin", "vip_library_admin", "vip_library_public"):
if req not in names:
names.append(req)
block = "from app.routers import (\n" + ",\n".join(f" {n}" for n in names) + "\n)\n"
t = t[: m2.start()] + block + t[m2.end() :]
changed = True
if "include_router(vip_library_admin.router)" not in t:
if "include_router(vip_admin.router)" in t:
t = t.replace(
"app.include_router(vip_admin.router)",
"app.include_router(vip_admin.router)\napp.include_router(vip_library_admin.router)\napp.include_router(vip_library_public.router)",
1,
)
changed = True
else:
raise SystemExit("vip_admin router missing")
ast.parse(t)
if changed:
p.write_text(t, encoding="utf-8")
print("main.py patched for vip_library")
else:
print("main.py already has vip_library")
PY
sudo systemctl restart nomadmini-api
sleep 4
systemctl is-active nomadmini-api
echo "--- smoke ---"
curl -sk -o /dev/null -w "admin %{http_code}\n" https://admin.nomadro.cn/
curl -sk -o /dev/null -w "vip_library_page %{http_code}\n" https://admin.nomadro.cn/wechat/vip/library
curl -sk -o /dev/null -w "public_course %{http_code}\n" https://api.nomadro.cn/api/vip/course
curl -sk https://api.nomadro.cn/api/vip/library/meta | python3 -c "import sys,json; d=json.load(sys.stdin); print('meta', d.get('ok'), d.get('ebookIds'), d.get('courseLessons'), d.get('hasFile'))" || true
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',''))" || true)
if [ -n "$TOK" ]; then
curl -sk -H "Authorization: Bearer $TOK" https://api.nomadro.cn/api/admin/vip/library/meta | python3 -c "import sys,json; d=json.load(sys.stdin); print('admin_meta', d.get('ok'), d.get('ebookIds'), d.get('courseLessons'))"
curl -sk -H "Authorization: Bearer $TOK" https://api.nomadro.cn/api/admin/vip | python3 -c "import sys,json; d=json.load(sys.stdin); print('vip_price', d.get('vipPriceFen'), d.get('is_free'))"
fi
curl -sk https://api.nomadro.cn/api/config | python3 -c "import sys,json; d=json.load(sys.stdin); c=d.get('config') or d; print('tt_ok', 'tt' in (c.get('platforms') or {}))"
rm -rf vip-lib-unpack vip-library-release.tar.gz
echo DONE
"""
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -23,9 +23,6 @@
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<title>Nomadro Admin</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Syne:wght@600;700;800&family=IBM+Plex+Sans:wght@400;500;600&display=swap" rel="stylesheet" />
</head>
<body>
<div id="root"></div>

View File

@ -10,6 +10,7 @@ import Users from './pages/Users'
import Events from './pages/Events'
import Checklist from './pages/Checklist'
import Vip from './pages/Vip'
import VipLibrary from './pages/VipLibrary'
import Shop from './pages/Shop'
import Memo from './pages/Memo'
import Nav from './pages/Nav'
@ -67,6 +68,9 @@ export default function App() {
<Route index element={<Dashboard />} />
<Route path="books/:id" element={<BookEdit />} />
<Route path="vip" element={<Vip />} />
<Route path="vip/ebooks" element={<VipLibrary />} />
<Route path="vip/course" element={<VipLibrary />} />
<Route path="vip/library" element={<Navigate to="/wechat/vip/ebooks" replace />} />
<Route path="nav" element={<Nav />} />
<Route path="shop" element={<Shop />} />
<Route path="memo" element={<Memo />} />

View File

@ -1,106 +1,260 @@
import { useEffect, useState } from 'react'
import { useEffect, useMemo, useState } from 'react'
import { NavLink, Outlet, useLocation, useNavigate } from 'react-router-dom'
import { clearToken } from '../api'
import '../pages/wechat.css'
const NAV = [
{ to: '/wechat', end: true, label: '概览' },
{ to: '/wechat/books/default', end: false, label: '书籍与试读%' },
{ to: '/wechat/nav', end: false, label: '导航' },
{ to: '/wechat/vip', end: false, label: 'VIP' },
{ to: '/wechat/shop', end: false, label: '电商' },
{ to: '/wechat/memo', end: false, label: '知识社群' },
{ to: '/wechat/users', end: false, label: '读者' },
{ to: '/wechat/orders', end: false, label: '订单' },
{ to: '/wechat/events', end: false, label: '埋点' },
{ to: '/wechat/checklist', end: false, label: '部署检查清单' },
] as const
type NavLeaf = { kind?: 'link'; to: string; end?: boolean; ico: string; label: string }
type NavBranch = {
kind: 'branch'
id: string
ico: string
label: string
/** 任一前缀命中则父级高亮并保持展开 */
match: string[]
children: NavLeaf[]
}
type NavEntry = NavLeaf | NavBranch
type NavGroup = { label: string; items: NavEntry[] }
const NAV_GROUPS: NavGroup[] = [
{
label: '总览',
items: [{ to: '/wechat', end: true, ico: '◈', label: '运营概览' }],
},
{
label: '内容',
items: [
{ to: '/wechat/nav', ico: '🧭', label: '导航' },
{ to: '/wechat/books/default', ico: '📕', label: '小册与试读%' },
{
kind: 'branch',
id: 'vip',
ico: '👑',
label: 'VIP',
match: ['/wechat/vip', '/wechat/shop', '/wechat/memo'],
children: [
{ to: '/wechat/vip', end: true, ico: '⚙', label: '运营配置' },
{ to: '/wechat/vip/ebooks', ico: '📖', label: '电子书' },
{ to: '/wechat/vip/course', ico: '🎬', label: '视频课程' },
{ to: '/wechat/shop', ico: '🛒', label: '电商' },
{ to: '/wechat/memo', ico: '🏕️', label: '知识社群' },
],
},
],
},
{
label: '运营',
items: [
{ to: '/wechat/users', ico: '👥', label: '读者' },
{ to: '/wechat/orders', ico: '🧾', label: '订单' },
],
},
{
label: '数据与发布',
items: [
{ to: '/wechat/events', ico: '📊', label: '埋点事件' },
{ to: '/wechat/checklist', ico: '✓', label: '部署检查清单' },
],
},
]
function flattenLeaves(groups: NavGroup[]): NavLeaf[] {
const out: NavLeaf[] = []
for (const g of groups) {
for (const item of g.items) {
if (item.kind === 'branch') out.push(...item.children)
else out.push(item)
}
}
return out
}
const FLAT_NAV = flattenLeaves(NAV_GROUPS)
function titleFromPath(pathname: string) {
const hit = NAV.find((n) => (n.end ? pathname === n.to : pathname.startsWith(n.to)))
const sorted = [...FLAT_NAV].sort((a, b) => b.to.length - a.to.length)
const hit = sorted.find((n) => (n.end ? pathname === n.to : pathname.startsWith(n.to)))
return hit?.label || '微信后台'
}
/** 微信小程序后台壳层 — 仅 /wechat/*,不碰抖音;移动端抽屉导航 */
function isBranchActive(branch: NavBranch, pathname: string) {
return branch.match.some(
(m) => pathname === m || pathname.startsWith(`${m}/`),
)
}
/** 微信小程序后台壳层 — 仅 /wechat/*;VIP 二级菜单;移动端抽屉 */
export default function Layout() {
const nav = useNavigate()
const { pathname } = useLocation()
const [open, setOpen] = useState(false)
const [drawerOpen, setDrawerOpen] = useState(false)
const vipActive = useMemo(
() =>
pathname === '/wechat/vip' ||
pathname.startsWith('/wechat/vip/') ||
pathname.startsWith('/wechat/shop') ||
pathname.startsWith('/wechat/memo'),
[pathname],
)
const [vipOpen, setVipOpen] = useState(() => vipActive)
useEffect(() => {
setOpen(false)
setDrawerOpen(false)
}, [pathname])
useEffect(() => {
document.body.style.overflow = open ? 'hidden' : ''
if (vipActive) setVipOpen(true)
}, [vipActive])
useEffect(() => {
document.body.style.overflow = drawerOpen ? 'hidden' : ''
return () => {
document.body.style.overflow = ''
}
}, [open])
}, [drawerOpen])
function logout() {
clearToken()
nav('/login')
}
const side = (
<>
<div className="logo">
<img className="logo-mark-img" src="/apple-touch-icon.png" width={42} height={42} alt="" />
<div>
<div className="logo-title">Nomadro</div>
<div className="logo-sub">微信小程序后台</div>
function renderEntry(item: NavEntry) {
if (item.kind === 'branch') {
const open = item.id === 'vip' ? vipOpen : false
const active = isBranchActive(item, pathname)
return (
<div
key={item.id}
className={`wx-nav-branch${open ? ' is-open' : ''}${active ? ' is-active' : ''}`}
>
<button
type="button"
className="wx-nav-parent"
aria-expanded={open}
onClick={() => {
if (item.id === 'vip') {
setVipOpen((v) => {
const next = !v
if (next && !vipActive) nav('/wechat/vip')
return next
})
}
}}
>
<span className="wx-nav-ico" aria-hidden>
{item.ico}
</span>
<span className="wx-nav-parent-label">{item.label}</span>
<span className="wx-nav-caret" aria-hidden>
{open ? '▾' : '▸'}
</span>
</button>
{open ? (
<div className="wx-nav-sub" role="group" aria-label={`${item.label}子菜单`}>
{item.children.map((child) => (
<NavLink
key={child.to}
to={child.to}
end={!!child.end}
className="wx-nav-sublink"
onClick={() => setDrawerOpen(false)}
>
<span className="wx-nav-ico" aria-hidden>
{child.ico}
</span>
{child.label}
</NavLink>
))}
</div>
) : null}
</div>
</div>
<nav className="nav" aria-label="微信后台导航">
{NAV.map((item) => (
<NavLink key={item.to} to={item.to} end={item.end} onClick={() => setOpen(false)}>
{item.label}
</NavLink>
))}
</nav>
<button type="button" className="ghost-btn" onClick={() => nav('/')}>
← 切换平台
</button>
<button type="button" className="ghost-btn" onClick={logout}>
退出登录
</button>
</>
)
)
}
return (
<NavLink
key={item.to}
to={item.to}
end={!!item.end}
onClick={() => setDrawerOpen(false)}
>
<span className="wx-nav-ico" aria-hidden>
{item.ico}
</span>
{item.label}
</NavLink>
)
}
return (
<div className={`shell${open ? ' shell--nav-open' : ''}`}>
<header className="topbar">
<div className={`wx-shell${drawerOpen ? ' wx-shell--nav-open' : ''}`}>
<header className="wx-topbar">
<button
type="button"
className="topbar-menu"
aria-label={open ? '关闭菜单' : '打开菜单'}
aria-expanded={open}
onClick={() => setOpen((v) => !v)}
className="wx-topbar-menu"
aria-label={drawerOpen ? '关闭菜单' : '打开菜单'}
aria-expanded={drawerOpen}
onClick={() => setDrawerOpen((v) => !v)}
>
<span />
<span />
<span />
</button>
<div className="topbar-brand">
<div className="wx-topbar-brand">
<img src="/favicon-32x32.png" width={28} height={28} alt="" />
<div>
<div className="topbar-title">Nomadro</div>
<div className="topbar-sub">{titleFromPath(pathname)}</div>
<div className="wx-topbar-title">微信后台</div>
<div className="wx-topbar-sub">{titleFromPath(pathname)}</div>
</div>
</div>
<button type="button" className="topbar-action" onClick={() => nav('/')}>
<button type="button" className="wx-topbar-action" onClick={() => nav('/')}>
平台
</button>
</header>
{open && (
<button type="button" className="nav-scrim" aria-label="关闭菜单" onClick={() => setOpen(false)} />
{drawerOpen && (
<button
type="button"
className="wx-nav-scrim"
aria-label="关闭菜单"
onClick={() => setDrawerOpen(false)}
/>
)}
<aside className="side" aria-hidden={!open}>
{side}
<aside className="wx-side" aria-hidden={!drawerOpen}>
<div className="wx-logo">
<img src="/apple-touch-icon.png" width={42} height={42} alt="" />
<div>
<div className="wx-title">微信后台</div>
<div className="wx-sub">小程序 · 虚拟支付运营</div>
</div>
</div>
<div className="wx-pill">
<span className="wx-pill-dot" />
与抖音数据隔离
</div>
<nav className="wx-nav" aria-label="微信后台导航">
{NAV_GROUPS.map((group) => (
<div className="wx-nav-group" key={group.label}>
<div className="wx-nav-label">{group.label}</div>
{group.items.map((item) => renderEntry(item))}
</div>
))}
</nav>
<div className="wx-side-foot">
<button type="button" className="wx-ghost" onClick={() => nav('/')}>
← 切换平台
</button>
<button type="button" className="wx-ghost" onClick={logout}>
退出登录
</button>
</div>
</aside>
<main className="main">
<main className="wx-main">
<Outlet />
</main>
</div>

View File

@ -0,0 +1,134 @@
import { ReactNode, useEffect } from 'react'
export function WxHead({
eyebrow,
title,
desc,
children,
}: {
eyebrow?: string
title: string
desc?: string
children?: ReactNode
}) {
return (
<header className="wx-head">
<div>
{eyebrow ? <div className="wx-eyebrow">{eyebrow}</div> : null}
<h1>{title}</h1>
{desc ? <p>{desc}</p> : null}
</div>
{children ? <div className="wx-head-actions">{children}</div> : null}
</header>
)
}
export function WxToast({
kind,
children,
onClose,
}: {
kind: 'ok' | 'err' | 'info'
children: ReactNode
onClose?: () => void
}) {
useEffect(() => {
if (!onClose || kind === 'err') return
const t = window.setTimeout(onClose, 4200)
return () => window.clearTimeout(t)
}, [children, kind, onClose])
return (
<div className={`wx-toast wx-toast--${kind}`} role="status">
<span>{children}</span>
{onClose ? (
<button type="button" onClick={onClose}>
关闭
</button>
) : null}
</div>
)
}
export function WxTabs<T extends string>({
value,
onChange,
items,
}: {
value: T
onChange: (v: T) => void
items: { key: T; label: string; count?: number }[]
}) {
return (
<div className="wx-tabs" role="tablist">
{items.map((it) => (
<button
key={it.key}
type="button"
role="tab"
aria-selected={value === it.key}
className={`wx-tab${value === it.key ? ' is-on' : ''}`}
onClick={() => onChange(it.key)}
>
{it.label}
{typeof it.count === 'number' ? <em>{it.count}</em> : null}
</button>
))}
</div>
)
}
export function WxBadge({
tone,
children,
}: {
tone?: 'ok' | 'warn' | 'bad' | 'muted' | 'info'
children: ReactNode
}) {
return <span className={`wx-badge wx-badge--${tone || 'muted'}`}>{children}</span>
}
export function WxEmpty({ title, hint }: { title: string; hint?: string }) {
return (
<div className="wx-empty">
<strong>{title}</strong>
{hint ? <span>{hint}</span> : null}
</div>
)
}
export async function copyText(text: string) {
try {
await navigator.clipboard.writeText(text)
return true
} catch {
try {
const ta = document.createElement('textarea')
ta.value = text
ta.style.position = 'fixed'
ta.style.left = '-9999px'
document.body.appendChild(ta)
ta.select()
document.execCommand('copy')
document.body.removeChild(ta)
return true
} catch {
return false
}
}
}
export function fmtYuan(fen: number) {
return `¥${(Number(fen || 0) / 100).toFixed(2)}`
}
export function fmtTime(sec?: number | null) {
if (!sec) return '—'
return new Date(sec * 1000).toLocaleString()
}
export function shortId(id?: string | null, keep = 8) {
if (!id) return '—'
if (id.length <= keep + 2) return id
return `…${id.slice(-keep)}`
}

View File

@ -223,7 +223,7 @@
.live-preview-label {
font-size: 12px;
color: var(--muted);
letter-spacing: 0.04em;
letter-spacing: 0;
}
.live-btn {
@ -335,7 +335,7 @@
background: linear-gradient(145deg, #1f2937, #111827);
color: #a7f3d0;
font-weight: 800;
letter-spacing: 1px;
letter-spacing: 0;
font-size: 13px;
}

View File

@ -1,6 +1,7 @@
import { FormEvent, useEffect, useMemo, useState } from 'react'
import { Link, useParams } from 'react-router-dom'
import { api } from '../api'
import { WxHead, WxToast } from '../components/wxUi'
import './BookEdit.css'
type Chapter = { id: string; title: string; order: number; content: string }
@ -211,38 +212,54 @@ export default function BookEdit() {
await importMarkdown(fullMd, false)
}
if (!book) return <div className="page">加载中… {msg}</div>
if (!book) {
return (
<div className="wx-page">
<WxHead eyebrow="微信小册" title="小册与试读 %" desc="加载中…" />
{msg ? <WxToast kind="err">{msg}</WxToast> : null}
</div>
)
}
return (
<div className="page book-edit-page">
<header className="page-head">
<div>
<h1>内容编辑台</h1>
<p>
数据库实时读写 · {book.chapter_count || book.chapters.length} 章 ·{' '}
{book.word_count || 0} 字 · 保存后小程序下次打开即更新
</p>
</div>
<div className="head-actions">
<label className="file-btn">
导入 ebook.md
<input
type="file"
accept=".md,text/markdown,text/plain"
hidden
onChange={(e) => onPickFile(e.target.files?.[0] || null)}
/>
</label>
<button type="button" className="ghost" onClick={() => loadFullMarkdown()}>
全文模式
</button>
<button type="button" className="ghost" onClick={() => setMode('chapter')}>
分章模式
</button>
</div>
</header>
<div className="wx-page book-edit-page">
<WxHead
eyebrow="微信小册"
title="小册与试读 %"
desc={`数据库实时读写 · ${book.chapter_count || book.chapters.length} 章 · ${
book.word_count || 0
} 字 · 保存后小程序下次打开即更新`}
>
<label className="file-btn wx-btn wx-btn-ghost" style={{ cursor: 'pointer' }}>
导入 ebook.md
<input
type="file"
accept=".md,text/markdown,text/plain"
hidden
onChange={(e) => onPickFile(e.target.files?.[0] || null)}
/>
</label>
<button
type="button"
className={`wx-btn${mode === 'full' ? '' : ' wx-btn-ghost'}`}
onClick={() => loadFullMarkdown()}
>
全文模式
</button>
<button
type="button"
className={`wx-btn${mode === 'chapter' ? '' : ' wx-btn-ghost'}`}
onClick={() => setMode('chapter')}
>
分章模式
</button>
</WxHead>
{msg && <div className="banner">{msg}</div>}
{msg ? (
<WxToast kind={msg.includes('失败') || msg.includes('error') ? 'err' : 'ok'} onClose={() => setMsg('')}>
{msg}
</WxToast>
) : null}
<form className="panel form meta-form" onSubmit={onSave}>
<section className="monetize-panel">
@ -430,15 +447,32 @@ export default function BookEdit() {
</div>
)}
<section className="panel" style={{ marginTop: 16 }}>
<h2>读者运营</h2>
<p className="muted">
手动解锁、收回、拉黑、备注等操作已迁到独立页面,按微信 openid 管理。
</p>
<Link className="primary-link" to="/wechat/users">
打开读者页 →
</Link>
</section>
<div className="wx-sticky-bar">
<span className="wx-muted">
模式 {mode === 'chapter' ? '分章' : '全文'} · 试读 {book.unlock_percent}% ·{' '}
{isFree ? '免费全书' : `道具 ${book.product_id || '—'}`}
</span>
<div className="wx-row-actions">
<Link className="wx-btn-sm" to="/wechat/users">
读者运营 →
</Link>
<button
type="button"
className="wx-btn"
disabled={saving || importing}
onClick={() => {
if (mode === 'full') void saveFullMarkdown()
else void saveMetaAndChapters()
}}
>
{saving || importing
? '保存中…'
: mode === 'full'
? '拆章并写入'
: '保存章节与元数据'}
</button>
</div>
</div>
</div>
)
}

View File

@ -1,5 +1,6 @@
import { useEffect, useState } from 'react'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { api } from '../api'
import { WxBadge, WxEmpty, WxHead, WxToast } from '../components/wxUi'
type Item = { id: string; title: string; status: string }
type Guide = { product_id: string; price_fen: number; steps: string[] }
@ -7,59 +8,151 @@ type Guide = { product_id: string; price_fen: number; steps: string[] }
export default function Checklist() {
const [items, setItems] = useState<Item[]>([])
const [guide, setGuide] = useState<Guide | null>(null)
const [loading, setLoading] = useState(true)
const [err, setErr] = useState('')
const [filter, setFilter] = useState<'all' | 'ok' | 'missing' | 'manual'>('all')
useEffect(() => {
api<{ items: Item[]; product_guide?: Guide }>('/api/admin/checklist').then((d) => {
setItems(d.items)
setGuide(d.product_guide || null)
})
const load = useCallback(() => {
setLoading(true)
setErr('')
api<{ items: Item[]; product_guide?: Guide }>('/api/admin/checklist')
.then((d) => {
setItems(d.items || [])
setGuide(d.product_guide || null)
})
.catch((e: Error) => setErr(e.message || '加载失败'))
.finally(() => setLoading(false))
}, [])
const badge = (s: string) => {
if (s === 'ok') return <span className="badge ok">已就绪</span>
if (s === 'missing') return <span className="badge bad">缺失</span>
return <span className="badge manual">需人工确认</span>
useEffect(() => {
load()
}, [load])
const counts = useMemo(() => {
let ok = 0
let missing = 0
let manual = 0
for (const it of items) {
if (it.status === 'ok') ok += 1
else if (it.status === 'missing') missing += 1
else manual += 1
}
return { ok, missing, manual, total: items.length }
}, [items])
const filtered = useMemo(() => {
if (filter === 'all') return items
if (filter === 'ok') return items.filter((i) => i.status === 'ok')
if (filter === 'missing') return items.filter((i) => i.status === 'missing')
return items.filter((i) => i.status !== 'ok' && i.status !== 'missing')
}, [items, filter])
function badge(s: string) {
if (s === 'ok') return <WxBadge tone="ok">已就绪</WxBadge>
if (s === 'missing') return <WxBadge tone="bad">缺失</WxBadge>
return <WxBadge tone="warn">需人工确认</WxBadge>
}
return (
<div className="page">
<header className="page-head">
<div>
<h1>部署前检查清单</h1>
<p>对照微信「虚拟支付:个人」文末清单逐项验收</p>
</div>
</header>
<div className="wx-page">
<WxHead
eyebrow="上架验收"
title="部署检查清单"
desc="对照微信「虚拟支付:个人」文末清单逐项验收。缺失项优先处理再上架。"
>
<button type="button" className="wx-btn" onClick={load} disabled={loading}>
{loading ? '检查中…' : '重新检查'}
</button>
</WxHead>
{guide && (
<div className="panel" style={{ marginBottom: 16 }}>
<h2>先解决 PRODUCT_ID_NOT_PUBLISH</h2>
<ol className="guide-ol">
{err ? (
<WxToast kind="err" onClose={() => setErr('')}>
{err}
</WxToast>
) : null}
<div className="wx-stats" style={{ gridTemplateColumns: 'repeat(4, minmax(0, 1fr))' }}>
<div className="wx-stat">
<div className="wx-stat-label">检查项</div>
<div className="wx-stat-val">{counts.total}</div>
</div>
<div className="wx-stat">
<div className="wx-stat-label">已就绪</div>
<div className="wx-stat-val">{counts.ok}</div>
</div>
<div className="wx-stat">
<div className="wx-stat-label">缺失</div>
<div className="wx-stat-val">{counts.missing}</div>
</div>
<div className="wx-stat wx-stat--warn">
<div className="wx-stat-label">需人工</div>
<div className="wx-stat-val">{counts.manual}</div>
</div>
</div>
{guide ? (
<section className="wx-panel">
<div className="wx-panel-head">
<div>
<h2>先解决 PRODUCT_ID_NOT_PUBLISH</h2>
<p>
道具 <code>{guide.product_id}</code> ·{' '}
¥{((guide.price_fen || 0) / 100).toFixed(2)}
</p>
</div>
</div>
<ol className="wx-guide-ol">
{guide.steps.map((s) => (
<li key={s}>{s}</li>
))}
</ol>
</div>
)}
</section>
) : null}
<div className="panel">
<ul className="checklist">
{items.map((it) => (
<li key={it.id}>
<div>{it.title}</div>
{badge(it.status)}
</li>
))}
</ul>
<div className="fee-note">
<h3>费率 / 结算 / 退款(需告知运营方)</h3>
<ul>
<div className="wx-chip-row">
{(
[
['all', `全部 ${counts.total}`],
['ok', `已就绪 ${counts.ok}`],
['missing', `缺失 ${counts.missing}`],
['manual', `需人工 ${counts.manual}`],
] as const
).map(([k, label]) => (
<button
key={k}
type="button"
className={`wx-chip${filter === k ? ' is-on' : ''}`}
onClick={() => setFilter(k)}
>
{label}
</button>
))}
</div>
<section className="wx-panel">
{filtered.length ? (
<ul className="wx-check-list">
{filtered.map((it) => (
<li key={it.id}>
<strong>{it.title}</strong>
{badge(it.status)}
</li>
))}
</ul>
) : (
<WxEmpty title={loading ? '检查中…' : '无匹配项'} />
)}
<div style={{ marginTop: 20 }}>
<h3 style={{ margin: '0 0 10px', fontFamily: 'var(--wx-font)' }}>费率 / 结算 / 退款</h3>
<ul className="wx-guide-ol" style={{ listStyle: 'disc' }}>
<li>Android 等:费率 1%;结算 T+3</li>
<li>iOS:费率 12%;结算约 45–60 天;退款由用户向 App Store 申请</li>
<li>个人主体月支付限额 10 万元</li>
<li>发货以推送为主,query_order 每 5 分钟兜底</li>
</ul>
</div>
</div>
</section>
</div>
)
}

View File

@ -1,4 +1,4 @@
import { useEffect, useState } from 'react'
import { useCallback, useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { api } from '../api'
@ -11,57 +11,273 @@ type Stats = {
track_events?: number
}
const HUBS: Array<{
to: string
ico: string
title: string
desc: string
primary?: boolean
}> = [
{
to: '/wechat/books/default',
ico: '📕',
title: '小册与试读 %',
desc: '章节、解锁阈值与虚拟支付道具',
primary: true,
},
{
to: '/wechat/vip',
ico: '👑',
title: 'VIP 运营',
desc: '价格、入口开关、加群行为与落地页',
},
{
to: '/wechat/vip/ebooks',
ico: '📖',
title: 'VIP 电子书',
desc: '章节 Markdown,远程正文',
},
{
to: '/wechat/vip/course',
ico: '🎬',
title: 'VIP 视频课程',
desc: '课时视频与配套文档',
},
{
to: '/wechat/memo',
ico: '🏕️',
title: '知识社群',
desc: '动态、置顶与星球相关配置',
},
{
to: '/wechat/shop',
ico: '🛒',
title: '设备商城',
desc: '商品、卡密发货与商城订单',
},
{
to: '/wechat/nav',
ico: '🧭',
title: '出海导航',
desc: '目的地与导航入口远程配置',
},
]
const QUICK = [
{
to: '/wechat/users',
title: '👥 读者运营',
desc: '解锁状态、标签与人工干预',
},
{
to: '/wechat/orders',
title: '🧾 订单列表',
desc: '已付 / 待付与金额核对',
},
{
to: '/wechat/events',
title: '📊 埋点事件',
desc: '漏斗与关键行为回放',
},
{
to: '/wechat/checklist',
title: '✓ 部署检查',
desc: '上架 / 发版前自检清单',
},
{
to: '/wechat/vip/ebooks',
title: '✎ 改电子书',
desc: 'VIP 电子书章节正文',
},
{
to: '/wechat/vip/course',
title: '🎬 改视频课',
desc: 'VIP 课时与配套文档',
},
{
to: '/wechat/books/default',
title: '⏱ 调试读',
desc: '快速改解锁百分比',
},
] as const
function fmtMoney(fen: number) {
return (fen / 100).toFixed(2)
}
export default function Dashboard() {
const [stats, setStats] = useState<Stats | null>(null)
const [err, setErr] = useState('')
const [loading, setLoading] = useState(true)
useEffect(() => {
api<Stats>('/api/admin/stats').then(setStats).catch(console.error)
const load = useCallback(() => {
setLoading(true)
setErr('')
api<Stats>('/api/admin/stats')
.then((s) => {
setStats(s)
setErr('')
})
.catch((e: Error) => {
setErr(e?.message || '统计加载失败')
})
.finally(() => setLoading(false))
}, [])
const cards = [
{ label: '读者', value: stats?.users ?? '—', emoji: '👥' },
{ label: '已解锁', value: stats?.unlocks ?? '—', emoji: '🔓' },
{ label: '已支付订单', value: stats?.paid_orders ?? '—', emoji: '💳' },
useEffect(() => {
load()
}, [load])
const cards: Array<{
key: string
label: string
value: string | number | undefined
emoji: string
to: string
money?: boolean
warn?: boolean
}> = [
{
label: '成交额(元)',
value: stats ? (stats.paid_amount_fen / 100).toFixed(2) : '—',
emoji: '📈',
key: 'users',
label: '读者',
value: stats?.users,
emoji: '👥',
to: '/wechat/users',
},
{
key: 'unlocks',
label: '已解锁',
value: stats?.unlocks,
emoji: '🔓',
to: '/wechat/users',
},
{
key: 'paid',
label: '已支付订单',
value: stats?.paid_orders,
emoji: '💳',
to: '/wechat/orders',
},
{
key: 'amount',
label: '成交额 (元)',
value: stats ? fmtMoney(stats.paid_amount_fen) : undefined,
emoji: '📈',
to: '/wechat/orders',
money: true,
},
{
key: 'pending',
label: '待支付',
value: stats?.pending_orders,
emoji: '⏳',
to: '/wechat/orders',
warn: true,
},
{
key: 'events',
label: '埋点事件',
value: stats?.track_events,
emoji: '📊',
to: '/wechat/events',
},
{ label: '待支付', value: stats?.pending_orders ?? '—', emoji: '⏳' },
{ label: '埋点事件', value: stats?.track_events ?? '—', emoji: '📊' },
]
return (
<div className="page">
<header className="page-head">
<div className="wx-dash">
<header className="wx-head">
<div>
<h1>概览</h1>
<p>电子书业务与虚拟支付运行状态</p>
<div className="wx-eyebrow">微信小程序</div>
<h1>微信运营台</h1>
<p>
小册试读、VIP、导航、电商与社群同一后台。虚拟支付订单与读者运营在此查看——与抖音控制台数据隔离。
</p>
</div>
<div className="wx-head-actions">
<button type="button" className="wx-btn wx-btn-ghost" onClick={load} disabled={loading}>
{loading ? '刷新中…' : '刷新数据'}
</button>
<Link className="wx-btn" to="/wechat/books/default">
编辑试读 % →
</Link>
</div>
<Link className="primary-link" to="/wechat/books/default">
编辑试读百分比 →
</Link>
</header>
<div className="stat-grid">
{cards.map((c) => (
<div className="stat-card" key={c.label}>
<div className="stat-emoji">{c.emoji}</div>
<div className="stat-value">{c.value}</div>
<div className="stat-label">{c.label}</div>
</div>
))}
{err ? (
<div className="wx-toast" role="alert">
<span>{err}(仍可进入各模块)</span>
<button type="button" onClick={load}>
重试
</button>
</div>
) : null}
<div className="wx-stats">
{cards.map((c) => {
const show = c.value === undefined || c.value === null
return (
<Link
key={c.key}
className={`wx-stat${c.money ? ' wx-stat--money' : ''}${c.warn ? ' wx-stat--warn' : ''}`}
to={c.to}
>
<div className="wx-stat-top">
<span className="wx-stat-ico" aria-hidden>
{c.emoji}
</span>
<span className="wx-stat-go">查看 →</span>
</div>
<div className={`wx-stat-val${show && loading ? ' is-loading' : ''}`}>
{show ? (loading ? '…' : '—') : c.value}
</div>
<div className="wx-stat-label">{c.label}</div>
</Link>
)
})}
</div>
<section className="panel">
<h2>快捷操作</h2>
<div className="quick">
<Link to="/wechat/books/default">📚 书籍 / 解锁阈值</Link>
<Link to="/wechat/vip">👑 VIP / 加群行为</Link>
<Link to="/wechat/users">👥 读者运营</Link>
<Link to="/wechat/orders">🧾 订单列表</Link>
<Link to="/wechat/events">📊 埋点事件</Link>
<Link to="/wechat/checklist">✅ 部署前检查清单</Link>
<section className="wx-panel">
<div className="wx-panel-head">
<div>
<h2>内容与模块</h2>
<p>按业务入口直达,改完保存即影响小程序远程配置</p>
</div>
<Link className="wx-link" to="/wechat/vip">
VIP 运营 →
</Link>
</div>
<div className="wx-hubs">
{HUBS.map((h) => (
<Link key={h.to + h.title} className={`wx-hub${h.primary ? ' primary' : ''}`} to={h.to}>
<span className="wx-hub-ico" aria-hidden>
{h.ico}
</span>
<div>
<strong>{h.title}</strong>
<span>{h.desc}</span>
</div>
<span className="wx-hub-arrow" aria-hidden>
→
</span>
</Link>
))}
</div>
</section>
<section className="wx-panel">
<div className="wx-panel-head">
<div>
<h2>快捷操作</h2>
<p>日常高频路径,一键到达</p>
</div>
</div>
<div className="wx-quick">
{QUICK.map((q) => (
<Link key={q.to + q.title} to={q.to}>
<strong>{q.title}</strong>
<span>{q.desc}</span>
</Link>
))}
</div>
</section>
</div>

View File

@ -1,5 +1,14 @@
import { useCallback, useEffect, useState } from 'react'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { api } from '../api'
import {
WxBadge,
WxEmpty,
WxHead,
WxToast,
copyText,
fmtTime,
shortId,
} from '../components/wxUi'
type TrackEvent = {
id: number
@ -37,22 +46,43 @@ const FILTERS = [
'join_group_qr_preview',
]
const CLIENTS = ['', 'tt', 'weapp', 'h5', 'miniapp', 'api', 'wx_push']
const CLIENTS = ['', 'weapp', 'tt', 'h5', 'miniapp', 'api', 'wx_push']
function clientLabel(c: string) {
if (c === 'tt') return '抖音'
if (c === 'weapp') return '微信'
if (c === 'h5') return 'H5'
return c || '全部'
}
function eventTone(name: string): 'ok' | 'warn' | 'bad' | 'info' | 'muted' {
if (name.includes('success') || name === 'login_ok' || name === 'pay_deliver') return 'ok'
if (name.includes('fail') || name === 'error' || name === 'login_fail') return 'bad'
if (name.includes('cancel') || name.includes('pend')) return 'warn'
if (name.startsWith('pay_') || name.startsWith('join_')) return 'info'
return 'muted'
}
export default function Events() {
const [events, setEvents] = useState<TrackEvent[]>([])
const [filter, setFilter] = useState('')
const [clientFilter, setClientFilter] = useState('')
const [clientFilter, setClientFilter] = useState('weapp')
const [q, setQ] = useState('')
const [loading, setLoading] = useState(false)
const [err, setErr] = useState('')
const [msg, setMsg] = useState('')
const [openId, setOpenId] = useState<number | null>(null)
const [auto, setAuto] = useState(false)
const load = useCallback(() => {
setLoading(true)
setErr('')
const qs = new URLSearchParams({ limit: '200' })
if (filter) qs.set('name', filter)
if (clientFilter) qs.set('client', clientFilter)
api<TrackEvent[]>(`/api/admin/track-events?${qs}`)
.then(setEvents)
.catch(console.error)
.catch((e: Error) => setErr(e.message || '加载失败'))
.finally(() => setLoading(false))
}, [filter, clientFilter])
@ -60,79 +90,209 @@ export default function Events() {
load()
}, [load])
useEffect(() => {
if (!auto) return
const t = window.setInterval(load, 12000)
return () => window.clearInterval(t)
}, [auto, load])
const filtered = useMemo(() => {
const needle = q.trim().toLowerCase()
if (!needle) return events
return events.filter((ev) => {
const blob = [
ev.name,
ev.page,
ev.label,
ev.openid,
ev.client,
JSON.stringify(ev.props || {}),
]
.join(' ')
.toLowerCase()
return blob.includes(needle)
})
}, [events, q])
const topNames = useMemo(() => {
const map = new Map<string, number>()
for (const ev of events) map.set(ev.name, (map.get(ev.name) || 0) + 1)
return [...map.entries()].sort((a, b) => b[1] - a[1]).slice(0, 6)
}, [events])
async function onCopy(text: string, label: string) {
setMsg((await copyText(text)) ? `已复制 ${label}` : '复制失败')
}
return (
<div className="page">
<header className="page-head">
<div>
<h1>埋点事件</h1>
<p>小程序行为与支付链路;关键事件同步推送到 ntfy</p>
</div>
<button className="primary-link" type="button" onClick={load} disabled={loading}>
<div className="wx-page">
<WxHead
eyebrow="行为埋点"
title="埋点事件"
desc="小程序行为与支付链路。支持事件/渠道筛选、关键词搜索、展开属性与自动刷新。"
>
<button
type="button"
className={`wx-btn wx-btn-ghost${auto ? '' : ''}`}
onClick={() => setAuto((v) => !v)}
style={auto ? { borderColor: 'rgba(94,196,120,.4)', color: 'var(--wx-green-2)' } : undefined}
>
{auto ? '自动刷新 · 开' : '自动刷新 · 关'}
</button>
<button type="button" className="wx-btn" onClick={load} disabled={loading}>
{loading ? '刷新中…' : '刷新'}
</button>
</header>
</WxHead>
<div className="panel" style={{ marginBottom: 16, display: 'flex', flexWrap: 'wrap', gap: 16 }}>
<label style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
<span>筛选事件</span>
<select value={filter} onChange={(e) => setFilter(e.target.value)}>
{FILTERS.map((f) => (
<option key={f || 'all'} value={f}>
{f || '全部'}
</option>
))}
</select>
</label>
<label style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
<span>渠道</span>
<select value={clientFilter} onChange={(e) => setClientFilter(e.target.value)}>
{CLIENTS.map((c) => (
<option key={c || 'all'} value={c}>
{c === 'tt' ? '抖音' : c === 'weapp' ? '微信' : c === 'h5' ? 'H5' : c || '全部'}
</option>
))}
</select>
</label>
{err ? (
<WxToast kind="err" onClose={() => setErr('')}>
{err}
</WxToast>
) : null}
{msg ? (
<WxToast kind="ok" onClose={() => setMsg('')}>
{msg}
</WxToast>
) : null}
<div className="wx-stats" style={{ gridTemplateColumns: 'repeat(3, minmax(0, 1fr))' }}>
<div className="wx-stat">
<div className="wx-stat-label">当前结果</div>
<div className="wx-stat-val">{filtered.length}</div>
</div>
<div className="wx-stat">
<div className="wx-stat-label">渠道</div>
<div className="wx-stat-val" style={{ fontSize: 18 }}>
{clientLabel(clientFilter)}
</div>
</div>
<div className="wx-stat">
<div className="wx-stat-label">高频事件</div>
<div className="wx-stat-label" style={{ marginTop: 8, lineHeight: 1.5 }}>
{topNames.length
? topNames.map(([n, c]) => `${n}×${c}`).join(' · ')
: '—'}
</div>
</div>
</div>
<div className="panel table-wrap">
<table>
<thead>
<tr>
<th>时间</th>
<th>事件</th>
<th>页面</th>
<th>标签</th>
<th>OpenID</th>
<th>客户端</th>
<th>属性</th>
</tr>
</thead>
<tbody>
{events.map((ev) => (
<tr key={ev.id}>
<td>{new Date((ev.ts || ev.created_at) * 1000).toLocaleString()}</td>
<td>
<code>{ev.name}</code>
</td>
<td>{ev.page || '—'}</td>
<td>{ev.label || '—'}</td>
<td className="mono">{ev.openid ? `…${ev.openid.slice(-8)}` : '—'}</td>
<td>{ev.client || '—'}</td>
<td className="mono" style={{ maxWidth: 280, overflow: 'hidden', textOverflow: 'ellipsis' }}>
{Object.keys(ev.props || {}).length
? JSON.stringify(ev.props)
: '—'}
</td>
</tr>
))}
{!events.length && (
{topNames.length ? (
<div className="wx-chip-row">
<button
type="button"
className={`wx-chip${!filter ? ' is-on' : ''}`}
onClick={() => setFilter('')}
>
全部事件
</button>
{topNames.map(([n, c]) => (
<button
key={n}
type="button"
className={`wx-chip${filter === n ? ' is-on' : ''}`}
onClick={() => setFilter(n)}
>
{n} <em style={{ opacity: 0.7 }}>{c}</em>
</button>
))}
</div>
) : null}
<div className="wx-toolbar">
<select value={filter} onChange={(e) => setFilter(e.target.value)}>
{FILTERS.map((f) => (
<option key={f || 'all'} value={f}>
{f || '全部事件类型'}
</option>
))}
</select>
<select value={clientFilter} onChange={(e) => setClientFilter(e.target.value)}>
{CLIENTS.map((c) => (
<option key={c || 'all'} value={c}>
{clientLabel(c)}
</option>
))}
</select>
<input
type="search"
value={q}
placeholder="搜索 page / label / openid / props"
onChange={(e) => setQ(e.target.value)}
/>
</div>
<div className="wx-table-wrap">
{filtered.length ? (
<table className="wx-table">
<thead>
<tr>
<td colSpan={7}>{loading ? '加载中…' : '暂无埋点数据'}</td>
<th>时间</th>
<th>事件</th>
<th>页面</th>
<th>标签</th>
<th>用户</th>
<th>端</th>
<th>操作</th>
</tr>
)}
</tbody>
</table>
</thead>
<tbody>
{filtered.map((ev) => {
const open = openId === ev.id
const propsText = Object.keys(ev.props || {}).length
? JSON.stringify(ev.props, null, 2)
: ''
return (
<tr key={ev.id} className={open ? 'is-open' : undefined}>
<td>{fmtTime(ev.ts || ev.created_at)}</td>
<td>
<WxBadge tone={eventTone(ev.name)}>{ev.name}</WxBadge>
{open && propsText ? <div className="wx-detail">{propsText}</div> : null}
</td>
<td>{ev.page || '—'}</td>
<td>{ev.label || '—'}</td>
<td>
<button
type="button"
className="wx-btn-sm"
onClick={() => onCopy(ev.openid, 'OpenID')}
disabled={!ev.openid}
>
{shortId(ev.openid, 8)}
</button>
</td>
<td>{clientLabel(ev.client)}</td>
<td>
<div className="wx-row-actions">
<button
type="button"
className="wx-btn-sm"
onClick={() => setOpenId(open ? null : ev.id)}
disabled={!propsText}
>
{open ? '收起' : '属性'}
</button>
{propsText ? (
<button
type="button"
className="wx-btn-sm"
onClick={() => onCopy(propsText, '属性 JSON')}
>
复制
</button>
) : null}
</div>
</td>
</tr>
)
})}
</tbody>
</table>
) : (
<WxEmpty
title={loading ? '加载中…' : '暂无埋点数据'}
hint="切换渠道或清空筛选后再试;关键事件会同步 ntfy"
/>
)}
</div>
</div>
)

View File

@ -1,6 +1,13 @@
import { useCallback, useEffect, useState } from 'react'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { api } from '../api'
import './BookEdit.css'
import {
WxBadge,
WxEmpty,
WxHead,
WxTabs,
WxToast,
fmtTime,
} from '../components/wxUi'
type Settings = {
enabled: boolean
@ -67,6 +74,7 @@ export default function MemoAdmin() {
const [err, setErr] = useState('')
const [msg, setMsg] = useState('')
const [busy, setBusy] = useState(false)
const [feedFilter, setFeedFilter] = useState<'all' | 'pinned' | 'featured' | 'hidden'>('all')
const [stats, setStats] = useState({
memos: 0,
comments: 0,
@ -84,12 +92,11 @@ export default function MemoAdmin() {
}>('/api/admin/memo')
setSettings({ ...emptySettings, ...(data.settings || {}) })
setStats({
memos: 0,
comments: 0,
likes: 0,
favorites: 0,
featured: 0,
...(data.stats || {}),
memos: data.stats?.memos ?? 0,
comments: data.stats?.comments ?? 0,
likes: data.stats?.likes ?? 0,
favorites: data.stats?.favorites ?? 0,
featured: data.stats?.featured ?? 0,
})
setItems(data.recent || [])
}, [])
@ -98,6 +105,15 @@ export default function MemoAdmin() {
load().catch((e) => setErr(e.message || '加载失败'))
}, [load])
const filtered = useMemo(() => {
return items.filter((m) => {
if (feedFilter === 'pinned') return m.pinned
if (feedFilter === 'featured') return !!m.featured
if (feedFilter === 'hidden') return m.status !== 'active'
return true
})
}, [items, feedFilter])
async function saveSettings(patch: Partial<Settings>, hint: string) {
setBusy(true)
setMsg('')
@ -127,7 +143,10 @@ export default function MemoAdmin() {
async function publish() {
const resources = parseResources()
if (!draft.trim() && !resources.length) return
if (!draft.trim() && !resources.length) {
setErr('请填写正文或至少一张图片')
return
}
setBusy(true)
setErr('')
setMsg('')
@ -158,10 +177,11 @@ export default function MemoAdmin() {
}
async function del(id: string) {
if (!confirm('删除该帖?')) return
if (!confirm('删除该帖?不可恢复')) return
setBusy(true)
try {
await api(`/api/admin/memo/memos/${id}`, { method: 'DELETE' })
setMsg('已删除')
await load()
} catch (e) {
setErr((e as Error).message || '删除失败')
@ -204,6 +224,7 @@ export default function MemoAdmin() {
setBusy(true)
try {
await api(`/api/admin/memo/memos/${id}/hide`, { method: 'POST' })
setMsg('已隐藏')
await load()
} catch (e) {
setErr((e as Error).message || '隐藏失败')
@ -223,96 +244,119 @@ export default function MemoAdmin() {
{ key: 'canUpload', label: '允许传图', hint: '会员发帖是否可上传图片' },
]
const resources = parseResources()
return (
<div className="page">
<header className="page-head">
<div>
<h1>知识社群</h1>
<p>
对标知识星球:博主发干货帖,会员阅读 / 点赞 / 评论 / 收藏(能力参考 Memos)
</p>
<div className="wx-page">
<WxHead
eyebrow="知识社群"
title="知识社群"
desc="对标知识星球:博主发干货帖,会员阅读 / 点赞 / 评论 / 收藏。"
>
<button
type="button"
className="wx-btn wx-btn-ghost"
disabled={busy}
onClick={() => load().catch((e) => setErr(e.message || '加载失败'))}
>
刷新
</button>
</WxHead>
{err ? (
<WxToast kind="err" onClose={() => setErr('')}>
{err}
</WxToast>
) : null}
{msg ? (
<WxToast kind="ok" onClose={() => setMsg('')}>
{msg}
</WxToast>
) : null}
<div className="wx-stats" style={{ gridTemplateColumns: 'repeat(5, minmax(0, 1fr))' }}>
<div className="wx-stat">
<div className="wx-stat-label">帖子</div>
<div className="wx-stat-val">{stats.memos}</div>
</div>
<div className="wx-stat">
<div className="wx-stat-label">精华</div>
<div className="wx-stat-val">{stats.featured}</div>
</div>
<div className="wx-stat">
<div className="wx-stat-label">评论</div>
<div className="wx-stat-val">{stats.comments}</div>
</div>
<div className="wx-stat">
<div className="wx-stat-label">赞</div>
<div className="wx-stat-val">{stats.likes}</div>
</div>
<div className="wx-stat">
<div className="wx-stat-label">收藏</div>
<div className="wx-stat-val">{stats.favorites}</div>
</div>
</header>
{err ? <div className="banner err">{err}</div> : null}
{msg ? <div className="banner ok">{msg}</div> : null}
<div className="panel" style={{ display: 'flex', gap: 16, flexWrap: 'wrap' }}>
<span>
帖子 <strong>{stats.memos}</strong>
</span>
<span>
精华 <strong>{stats.featured}</strong>
</span>
<span>
评论 <strong>{stats.comments}</strong>
</span>
<span>
赞 <strong>{stats.likes}</strong>
</span>
<span>
收藏 <strong>{stats.favorites}</strong>
</span>
</div>
<div className="panel" style={{ display: 'flex', gap: 8 }}>
<button
type="button"
className={tab === 'feed' ? 'primary-btn' : 'ghost-btn'}
onClick={() => setTab('feed')}
>
发帖 / 管理
</button>
<button
type="button"
className={tab === 'planet' ? 'primary-btn' : 'ghost-btn'}
onClick={() => setTab('planet')}
>
星球设置
</button>
</div>
<WxTabs
value={tab}
onChange={setTab}
items={[
{ key: 'feed', label: '发帖 / 管理', count: items.length },
{ key: 'planet', label: '星球设置' },
]}
/>
{tab === 'planet' ? (
<div className="panel">
<h2 style={{ marginTop: 0 }}>星球品牌</h2>
<label style={{ display: 'block', marginBottom: 12 }}>
星球名称
<input
value={settings.planetName || ''}
onChange={(e) => setSettings({ ...settings, planetName: e.target.value })}
onBlur={() =>
void saveSettings({ planetName: settings.planetName }, '名称已保存')
}
/>
</label>
<label style={{ display: 'block', marginBottom: 12 }}>
简介
<input
value={settings.planetDesc || ''}
onChange={(e) => setSettings({ ...settings, planetDesc: e.target.value })}
onBlur={() =>
void saveSettings({ planetDesc: settings.planetDesc }, '简介已保存')
}
/>
</label>
<label style={{ display: 'block', marginBottom: 16 }}>
公告
<input
value={settings.notice || ''}
onChange={(e) => setSettings({ ...settings, notice: e.target.value })}
onBlur={() => void saveSettings({ notice: settings.notice }, '公告已保存')}
/>
</label>
<h2>权限</h2>
<section className="wx-panel">
<div className="wx-panel-head">
<div>
<h2>星球品牌</h2>
<p>失焦自动保存名称 / 简介 / 公告</p>
</div>
<WxBadge tone={settings.enabled ? 'ok' : 'bad'}>
{settings.enabled ? '社群开启' : '社群关闭'}
</WxBadge>
</div>
<div className="wx-form-grid">
<label className="wx-field span-2">
星球名称
<input
value={settings.planetName || ''}
onChange={(e) => setSettings({ ...settings, planetName: e.target.value })}
onBlur={() =>
void saveSettings({ planetName: settings.planetName }, '名称已保存')
}
/>
</label>
<label className="wx-field span-2">
简介
<input
value={settings.planetDesc || ''}
onChange={(e) => setSettings({ ...settings, planetDesc: e.target.value })}
onBlur={() =>
void saveSettings({ planetDesc: settings.planetDesc }, '简介已保存')
}
/>
</label>
<label className="wx-field span-2">
公告
<input
value={settings.notice || ''}
onChange={(e) => setSettings({ ...settings, notice: e.target.value })}
onBlur={() => void saveSettings({ notice: settings.notice }, '公告已保存')}
/>
</label>
</div>
<h2 style={{ marginTop: 20, fontFamily: 'var(--wx-font)', fontSize: 18 }}>权限开关</h2>
{toggles.map((t) => (
<div className="vip-row" key={t.key}>
<div className="wx-switch-row" key={t.key}>
<div>
<strong>{t.label}</strong>
<p className="vip-hint">{t.hint}</p>
<span>{t.hint}</span>
</div>
<button
type="button"
className={settings[t.key] ? 'primary-link' : 'ghost-btn'}
className={settings[t.key] ? 'wx-btn' : 'wx-btn wx-btn-ghost'}
disabled={busy}
onClick={() =>
void saveSettings(
@ -325,42 +369,48 @@ export default function MemoAdmin() {
</button>
</div>
))}
</div>
</section>
) : (
<>
<div className="panel">
<h2 style={{ marginTop: 0 }}>发布知识帖</h2>
<p className="vip-hint" style={{ marginTop: 0 }}>
Markdown 正文;可用 ## 标题;#话题 自动归档;图片填 HTTPS 地址
</p>
<label style={{ display: 'block', marginBottom: 8 }}>
标题(可选,不填则取正文首个标题)
<input
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="例如:跨境收款避坑清单"
/>
</label>
<textarea
rows={8}
style={{ width: '100%', fontFamily: 'ui-monospace, Menlo, Consolas, monospace' }}
value={draft}
onChange={(e) => setDraft(e.target.value)}
placeholder={'## 标题\n\n正文支持 **Markdown**\n\n- 要点一\n- 要点二\n\n#话题'}
/>
<label style={{ display: 'block', marginTop: 10 }}>
封面 / 配图 URL(可选)
<textarea
rows={2}
style={{ width: '100%', marginTop: 4 }}
value={imgUrls}
onChange={(e) => setImgUrls(e.target.value)}
placeholder="https://…/cover.jpg"
/>
</label>
{parseResources().length ? (
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginTop: 8 }}>
{parseResources().map((r) => (
<section className="wx-panel">
<div className="wx-panel-head">
<div>
<h2>发布知识帖</h2>
<p>Markdown 正文;## 标题;#话题 自动归档;图片填 HTTPS</p>
</div>
</div>
<div className="wx-form-grid">
<label className="wx-field span-2">
标题(可选)
<input
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="例如:跨境收款避坑清单"
/>
</label>
<label className="wx-field span-2">
正文
<textarea
rows={10}
style={{ fontFamily: 'ui-monospace, Menlo, Consolas, monospace' }}
value={draft}
onChange={(e) => setDraft(e.target.value)}
placeholder={'## 标题\n\n正文支持 **Markdown**\n\n- 要点一\n\n#话题'}
/>
</label>
<label className="wx-field span-2">
封面 / 配图 URL
<textarea
rows={2}
value={imgUrls}
onChange={(e) => setImgUrls(e.target.value)}
placeholder="https://…/cover.jpg"
/>
</label>
</div>
{resources.length ? (
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginTop: 10 }}>
{resources.map((r) => (
<img
key={r.url}
src={r.url}
@ -371,97 +421,120 @@ export default function MemoAdmin() {
objectFit: 'cover',
borderRadius: 8,
background: '#111',
border: '1px solid rgba(150,210,170,.2)',
}}
/>
))}
</div>
) : null}
<div style={{ display: 'flex', gap: 16, marginTop: 10, alignItems: 'center', flexWrap: 'wrap' }}>
<label style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
<input type="checkbox" checked={pinNew} onChange={(e) => setPinNew(e.target.checked)} />
置顶
</label>
<label style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
<input
type="checkbox"
checked={featNew}
onChange={(e) => setFeatNew(e.target.checked)}
/>
精华
</label>
<button type="button" className="primary-btn" disabled={busy} onClick={() => void publish()}>
发布
<div className="wx-sticky-bar">
<div className="wx-row-actions">
<label style={{ display: 'flex', gap: 6, alignItems: 'center', fontSize: 13 }}>
<input type="checkbox" checked={pinNew} onChange={(e) => setPinNew(e.target.checked)} />
置顶
</label>
<label style={{ display: 'flex', gap: 6, alignItems: 'center', fontSize: 13 }}>
<input
type="checkbox"
checked={featNew}
onChange={(e) => setFeatNew(e.target.checked)}
/>
精华
</label>
</div>
<button type="button" className="wx-btn" disabled={busy} onClick={() => void publish()}>
{busy ? '发布中…' : '发布'}
</button>
</div>
</section>
<div className="wx-chip-row">
{(
[
['all', '全部'],
['pinned', '置顶'],
['featured', '精华'],
['hidden', '已隐藏'],
] as const
).map(([k, label]) => (
<button
key={k}
type="button"
className={`wx-chip${feedFilter === k ? ' is-on' : ''}`}
onClick={() => setFeedFilter(k)}
>
{label}
</button>
))}
</div>
<div className="panel table-wrap">
<table>
<thead>
<tr>
<th>标题</th>
<th>标签</th>
<th>互动</th>
<th>状态</th>
<th>时间</th>
<th />
</tr>
</thead>
<tbody>
{items.map((m) => (
<tr key={m.id}>
<td style={{ maxWidth: 280 }}>
<div>
{m.pinned ? '📌 ' : ''}
{m.featured ? '✨ ' : ''}
<strong>{m.title || '未命名'}</strong>
</div>
<div style={{ fontSize: 12, opacity: 0.65, marginTop: 4 }}>
{(m.content || '').slice(0, 80)}
</div>
</td>
<td style={{ fontSize: 12, color: '#f59e0b' }}>
{(m.tags || []).map((t) => `#${t}`).join(' ') || '—'}
</td>
<td>
👍{m.likeCount} · 💬{m.commentCount} · ★{m.favoriteCount || 0}
</td>
<td>{m.status}</td>
<td>{m.createdAt ? new Date(m.createdAt * 1000).toLocaleString() : ''}</td>
<td>
<button
type="button"
className="ghost-btn"
onClick={() => void pin(m.id, !m.pinned)}
>
{m.pinned ? '取消置顶' : '置顶'}
</button>
<button
type="button"
className="ghost-btn"
onClick={() => void feature(m.id, !m.featured)}
>
{m.featured ? '取消精华' : '精华'}
</button>
{m.status === 'active' ? (
<button type="button" className="ghost-btn" onClick={() => void hide(m.id)}>
隐藏
</button>
) : null}
<button type="button" className="ghost-btn" onClick={() => void del(m.id)}>
删
</button>
</td>
</tr>
))}
{!items.length && (
<tr>
<td colSpan={6}>暂无帖子 — 在上方发布第一条</td>
</tr>
)}
</tbody>
</table>
</div>
{filtered.length ? (
filtered.map((m) => (
<article key={m.id} className="wx-feed-card">
<h3>
{m.pinned ? '📌 ' : ''}
{m.featured ? '✨ ' : ''}
{m.title || '未命名'}
</h3>
<div style={{ fontSize: 13, color: 'var(--wx-muted)', lineHeight: 1.5 }}>
{(m.content || '').slice(0, 160)}
{(m.content || '').length > 160 ? '…' : ''}
</div>
<div className="wx-feed-meta">
<WxBadge tone={m.status === 'active' ? 'ok' : 'muted'}>{m.status}</WxBadge>
<span>👍 {m.likeCount}</span>
<span>💬 {m.commentCount}</span>
<span>★ {m.favoriteCount || 0}</span>
<span>{fmtTime(m.createdAt)}</span>
{(m.tags || []).length ? (
<span style={{ color: '#f59e0b' }}>
{(m.tags || []).map((t) => `#${t}`).join(' ')}
</span>
) : null}
</div>
<div className="wx-row-actions">
<button
type="button"
className="wx-btn-sm"
disabled={busy}
onClick={() => void pin(m.id, !m.pinned)}
>
{m.pinned ? '取消置顶' : '置顶'}
</button>
<button
type="button"
className="wx-btn-sm"
disabled={busy}
onClick={() => void feature(m.id, !m.featured)}
>
{m.featured ? '取消精华' : '精华'}
</button>
{m.status === 'active' ? (
<button
type="button"
className="wx-btn-sm"
disabled={busy}
onClick={() => void hide(m.id)}
>
隐藏
</button>
) : null}
<button
type="button"
className="wx-btn-sm danger"
disabled={busy}
onClick={() => void del(m.id)}
>
删除
</button>
</div>
</article>
))
) : (
<div className="wx-panel">
<WxEmpty title="暂无帖子" hint="在上方发布第一条知识帖" />
</div>
)}
</>
)}
</div>

View File

@ -1,5 +1,6 @@
import { useCallback, useEffect, useState } from 'react'
import { api } from '../api'
import { WxHead, WxToast } from '../components/wxUi'
import './BookEdit.css'
type NavLink = {
@ -104,11 +105,18 @@ export default function NavAdmin() {
}
}
if (!nav && !err) return <div className="page"><p>加载中…</p></div>
if (!nav && !err) {
return (
<div className="wx-page">
<WxHead eyebrow="导航" title="导航" desc="加载中…" />
</div>
)
}
if (!nav) {
return (
<div className="page">
<div className="banner err">{err}</div>
<div className="wx-page">
<WxHead eyebrow="导航" title="导航" desc="加载失败" />
<WxToast kind="err">{err}</WxToast>
</div>
)
}
@ -146,35 +154,45 @@ export default function NavAdmin() {
}
return (
<div className="page">
<header className="page-head">
<div>
<h1>导航</h1>
<p>
远程控制门户 <code>/nav</code> 与小程序导航:新增 / 编辑 / 隐藏 / 删除 · 保存后客户端实时刷新
</p>
</div>
<button type="button" className="primary-btn" disabled={busy} onClick={() => void save()}>
<div className="wx-page">
<WxHead
eyebrow="导航配置"
title="导航"
desc="远程控制门户 /nav 与小程序导航:新增 / 编辑 / 隐藏 / 删除 · 保存后客户端刷新。"
>
<button type="button" className="wx-btn" disabled={busy} onClick={() => void save()}>
{busy ? '保存中…' : '保存并发布'}
</button>
</header>
</WxHead>
{err ? <div className="banner err">{err}</div> : null}
{msg ? <div className="banner ok">{msg}</div> : null}
{err ? (
<WxToast kind="err" onClose={() => setErr('')}>
{err}
</WxToast>
) : null}
{msg ? (
<WxToast kind="ok" onClose={() => setMsg('')}>
{msg}
</WxToast>
) : null}
<div className="panel" style={{ display: 'flex', gap: 16, flexWrap: 'wrap' }}>
<span>
分类 <strong>{stats.categories}</strong>
</span>
<span>
分组 <strong>{stats.groups}</strong>
</span>
<span>
链接 <strong>{stats.links}</strong>
</span>
<span>
已隐藏分类 <strong>{stats.hiddenCategories}</strong>
</span>
<div className="wx-stats" style={{ gridTemplateColumns: 'repeat(4, minmax(0, 1fr))' }}>
<div className="wx-stat">
<div className="wx-stat-label">分类</div>
<div className="wx-stat-val">{stats.categories}</div>
</div>
<div className="wx-stat">
<div className="wx-stat-label">分组</div>
<div className="wx-stat-val">{stats.groups}</div>
</div>
<div className="wx-stat">
<div className="wx-stat-label">链接</div>
<div className="wx-stat-val">{stats.links}</div>
</div>
<div className="wx-stat wx-stat--warn">
<div className="wx-stat-label">已隐藏分类</div>
<div className="wx-stat-val">{stats.hiddenCategories}</div>
</div>
</div>
<div className="panel">
@ -210,7 +228,7 @@ export default function NavAdmin() {
<h2 style={{ margin: 0, fontSize: 15 }}>分类</h2>
<button
type="button"
className="ghost-btn"
className="wx-btn-sm"
onClick={() => {
const cats = [...nav.categories, emptyCategory()]
patch({ ...nav, categories: cats })
@ -226,7 +244,7 @@ export default function NavAdmin() {
<button
key={c.id}
type="button"
className={i === catIdx ? 'primary-btn' : 'ghost-btn'}
className={i === catIdx ? 'wx-btn-sm primary' : 'wx-btn-sm'}
style={{
textAlign: 'left',
opacity: c.hidden ? 0.5 : 1,
@ -290,7 +308,7 @@ export default function NavAdmin() {
<div style={{ display: 'flex', gap: 8, marginTop: 12, flexWrap: 'wrap' }}>
<button
type="button"
className="ghost-btn"
className="wx-btn-sm"
onClick={() => {
const cats = nav.categories.map((c, i) =>
i === catIdx ? { ...c, hidden: !c.hidden } : c,
@ -300,15 +318,15 @@ export default function NavAdmin() {
>
{cat.hidden ? '取消隐藏' : '隐藏分类'}
</button>
<button type="button" className="ghost-btn" onClick={() => moveCat(catIdx, catIdx - 1)}>
<button type="button" className="wx-btn-sm" onClick={() => moveCat(catIdx, catIdx - 1)}>
↑ 上移
</button>
<button type="button" className="ghost-btn" onClick={() => moveCat(catIdx, catIdx + 1)}>
<button type="button" className="wx-btn-sm" onClick={() => moveCat(catIdx, catIdx + 1)}>
↓ 下移
</button>
<button
type="button"
className="ghost-btn"
className="wx-btn-sm"
onClick={() => {
if (!confirm('删除该分类?')) return
const cats = nav.categories.filter((_, i) => i !== catIdx)
@ -327,7 +345,7 @@ export default function NavAdmin() {
<h2 style={{ margin: 0 }}>分组</h2>
<button
type="button"
className="ghost-btn"
className="wx-btn-sm"
onClick={() => {
const groups = [...cat.groups, emptyGroup()]
const cats = nav.categories.map((c, i) =>
@ -345,7 +363,7 @@ export default function NavAdmin() {
<button
key={g.id}
type="button"
className={i === groupIdx ? 'primary-btn' : 'ghost-btn'}
className={i === groupIdx ? 'wx-btn-sm primary' : 'wx-btn-sm'}
style={{ opacity: g.hidden ? 0.5 : 1 }}
onClick={() => setGroupIdx(i)}
>
@ -392,7 +410,7 @@ export default function NavAdmin() {
<div style={{ display: 'flex', gap: 8, marginTop: 10, flexWrap: 'wrap' }}>
<button
type="button"
className="ghost-btn"
className="wx-btn-sm"
onClick={() => {
const groups = cat.groups.map((g, i) =>
i === groupIdx ? { ...g, hidden: !g.hidden } : g,
@ -407,21 +425,21 @@ export default function NavAdmin() {
</button>
<button
type="button"
className="ghost-btn"
className="wx-btn-sm"
onClick={() => moveGroup(groupIdx, groupIdx - 1)}
>
↑
</button>
<button
type="button"
className="ghost-btn"
className="wx-btn-sm"
onClick={() => moveGroup(groupIdx, groupIdx + 1)}
>
↓
</button>
<button
type="button"
className="ghost-btn"
className="wx-btn-sm"
onClick={() => {
if (!confirm('删除该分组?')) return
const groups = cat.groups.filter((_, i) => i !== groupIdx)
@ -436,7 +454,7 @@ export default function NavAdmin() {
</button>
<button
type="button"
className="primary-btn"
className="wx-btn-sm primary"
onClick={() => {
const links = [...group.links, emptyLink()]
const groups = cat.groups.map((g, i) =>
@ -561,7 +579,7 @@ export default function NavAdmin() {
<td style={{ whiteSpace: 'nowrap' }}>
<button
type="button"
className="ghost-btn"
className="wx-btn-sm"
onClick={() => {
const links = group.links.map((l, j) =>
j === li ? { ...l, hidden: !l.hidden } : l,
@ -579,21 +597,21 @@ export default function NavAdmin() {
</button>
<button
type="button"
className="ghost-btn"
className="wx-btn-sm"
onClick={() => moveLink(li, li - 1)}
>
↑
</button>
<button
type="button"
className="ghost-btn"
className="wx-btn-sm"
onClick={() => moveLink(li, li + 1)}
>
↓
</button>
<button
type="button"
className="ghost-btn"
className="wx-btn-sm"
onClick={() => {
if (!confirm('删除链接?')) return
const links = group.links.filter((_, j) => j !== li)
@ -632,6 +650,15 @@ export default function NavAdmin() {
)}
</div>
</div>
<div className="wx-sticky-bar">
<span className="wx-muted">
{stats.categories} 分类 · {stats.groups} 分组 · {stats.links} 链接 · 改完务必发布
</span>
<button type="button" className="wx-btn" disabled={busy} onClick={() => void save()}>
{busy ? '保存中…' : '保存并发布'}
</button>
</div>
</div>
)
}

View File

@ -1,5 +1,16 @@
import { useEffect, useState } from 'react'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { api } from '../api'
import {
WxBadge,
WxEmpty,
WxHead,
WxTabs,
WxToast,
copyText,
fmtTime,
fmtYuan,
shortId,
} from '../components/wxUi'
type Order = {
out_trade_no: string
@ -12,53 +23,244 @@ type Order = {
created_at: number
}
type StatusTab = 'all' | 'paid' | 'pending' | 'other'
function statusTone(status: string): 'ok' | 'warn' | 'bad' | 'muted' {
const s = (status || '').toLowerCase()
if (s.includes('paid') || s.includes('success') || s === 'ok') return 'ok'
if (s.includes('pend') || s.includes('creat') || s.includes('wait')) return 'warn'
if (s.includes('fail') || s.includes('cancel') || s.includes('refund')) return 'bad'
return 'muted'
}
function statusLabel(status: string) {
const s = (status || '').toLowerCase()
if (s.includes('paid') || s.includes('success')) return '已支付'
if (s.includes('pend') || s.includes('creat') || s.includes('wait')) return '待支付'
if (s.includes('cancel')) return '已取消'
if (s.includes('fail')) return '失败'
if (s.includes('refund')) return '退款'
return status || '未知'
}
export default function Orders() {
const [orders, setOrders] = useState<Order[]>([])
const [loading, setLoading] = useState(true)
const [err, setErr] = useState('')
const [msg, setMsg] = useState('')
const [q, setQ] = useState('')
const [tab, setTab] = useState<StatusTab>('all')
const [openId, setOpenId] = useState<string | null>(null)
useEffect(() => {
api<Order[]>('/api/admin/orders').then(setOrders).catch(console.error)
const load = useCallback(() => {
setLoading(true)
setErr('')
api<Order[]>('/api/admin/orders')
.then(setOrders)
.catch((e: Error) => setErr(e.message || '加载失败'))
.finally(() => setLoading(false))
}, [])
useEffect(() => {
load()
}, [load])
const stats = useMemo(() => {
let paid = 0
let pending = 0
let amount = 0
let delivered = 0
for (const o of orders) {
const s = (o.status || '').toLowerCase()
const isPaid = s.includes('paid') || s.includes('success')
const isPend = s.includes('pend') || s.includes('creat') || s.includes('wait')
if (isPaid) {
paid += 1
amount += o.amount_fen || 0
} else if (isPend) pending += 1
if (o.delivered) delivered += 1
}
return { paid, pending, amount, delivered, total: orders.length }
}, [orders])
const filtered = useMemo(() => {
const needle = q.trim().toLowerCase()
return orders.filter((o) => {
const s = (o.status || '').toLowerCase()
const isPaid = s.includes('paid') || s.includes('success')
const isPend = s.includes('pend') || s.includes('creat') || s.includes('wait')
if (tab === 'paid' && !isPaid) return false
if (tab === 'pending' && !isPend) return false
if (tab === 'other' && (isPaid || isPend)) return false
if (!needle) return true
return (
o.out_trade_no.toLowerCase().includes(needle) ||
(o.wx_order_id || '').toLowerCase().includes(needle) ||
o.openid.toLowerCase().includes(needle) ||
(o.book_id || '').toLowerCase().includes(needle) ||
(o.status || '').toLowerCase().includes(needle)
)
})
}, [orders, q, tab])
async function onCopy(text: string, label: string) {
const ok = await copyText(text)
setMsg(ok ? `已复制 ${label}` : '复制失败')
}
return (
<div className="page">
<header className="page-head">
<div>
<h1>订单</h1>
<p>虚拟支付道具直购订单与发货状态</p>
<div className="wx-page">
<WxHead
eyebrow="虚拟支付"
title="订单"
desc="虚拟支付道具直购订单、金额与发货状态。支持搜索、状态筛选与一键复制单号。"
>
<button type="button" className="wx-btn wx-btn-ghost" onClick={load} 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" style={{ gridTemplateColumns: 'repeat(4, minmax(0, 1fr))' }}>
<div className="wx-stat">
<div className="wx-stat-label">全部订单</div>
<div className="wx-stat-val">{stats.total}</div>
</div>
</header>
<div className="panel table-wrap">
<table>
<thead>
<tr>
<th>业务单号</th>
<th>平台单号</th>
<th>OpenID</th>
<th>金额</th>
<th>状态</th>
<th>发货</th>
<th>时间</th>
</tr>
</thead>
<tbody>
{orders.map((o) => (
<tr key={o.out_trade_no}>
<td>{o.out_trade_no}</td>
<td>{o.wx_order_id || '—'}</td>
<td className="mono">{o.openid}</td>
<td>¥{(o.amount_fen / 100).toFixed(2)}</td>
<td>{o.status}</td>
<td>{o.delivered ? '✅' : '—'}</td>
<td>{new Date(o.created_at * 1000).toLocaleString()}</td>
</tr>
))}
{!orders.length && (
<div className="wx-stat wx-stat--money">
<div className="wx-stat-label">已支付成交</div>
<div className="wx-stat-val">{fmtYuan(stats.amount)}</div>
<div className="wx-stat-label">{stats.paid} 笔已付</div>
</div>
<div className="wx-stat wx-stat--warn">
<div className="wx-stat-label">待支付</div>
<div className="wx-stat-val">{stats.pending}</div>
</div>
<div className="wx-stat">
<div className="wx-stat-label">已发货</div>
<div className="wx-stat-val">{stats.delivered}</div>
</div>
</div>
<WxTabs
value={tab}
onChange={setTab}
items={[
{ key: 'all', label: '全部', count: stats.total },
{ key: 'paid', label: '已支付', count: stats.paid },
{ key: 'pending', label: '待支付', count: stats.pending },
{ key: 'other', label: '其他', count: Math.max(0, stats.total - stats.paid - stats.pending) },
]}
/>
<div className="wx-toolbar">
<input
type="search"
value={q}
placeholder="搜索业务单号 / 平台单号 / OpenID / 书籍"
onChange={(e) => setQ(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Escape') setQ('')
}}
/>
<button type="button" className="wx-btn wx-btn-ghost" onClick={() => setQ('')}>
清空
</button>
</div>
<div className="wx-table-wrap">
{filtered.length ? (
<table className="wx-table">
<thead>
<tr>
<td colSpan={7}>暂无订单</td>
<th>业务单号</th>
<th>金额</th>
<th>状态</th>
<th>发货</th>
<th>用户</th>
<th>时间</th>
<th>操作</th>
</tr>
)}
</tbody>
</table>
</thead>
<tbody>
{filtered.map((o) => {
const open = openId === o.out_trade_no
return (
<tr key={o.out_trade_no} className={open ? 'is-open' : undefined}>
<td>
<div className="wx-mono">{o.out_trade_no}</div>
<div className="wx-mono" style={{ opacity: 0.65, marginTop: 4 }}>
{o.wx_order_id || '无平台单号'}
</div>
{open ? (
<div className="wx-detail">
book_id: {o.book_id || '—'}
{'\n'}openid: {o.openid}
{'\n'}wx_order_id: {o.wx_order_id || '—'}
{'\n'}raw status: {o.status}
</div>
) : null}
</td>
<td>
<strong>{fmtYuan(o.amount_fen)}</strong>
</td>
<td>
<WxBadge tone={statusTone(o.status)}>{statusLabel(o.status)}</WxBadge>
</td>
<td>
<WxBadge tone={o.delivered ? 'ok' : 'muted'}>
{o.delivered ? '已发货' : '未发货'}
</WxBadge>
</td>
<td>
<button
type="button"
className="wx-btn-sm"
title={o.openid}
onClick={() => onCopy(o.openid, 'OpenID')}
>
{shortId(o.openid, 10)}
</button>
</td>
<td>{fmtTime(o.created_at)}</td>
<td>
<div className="wx-row-actions">
<button
type="button"
className="wx-btn-sm"
onClick={() => setOpenId(open ? null : o.out_trade_no)}
>
{open ? '收起' : '详情'}
</button>
<button
type="button"
className="wx-btn-sm"
onClick={() => onCopy(o.out_trade_no, '业务单号')}
>
复制单号
</button>
</div>
</td>
</tr>
)
})}
</tbody>
</table>
) : (
<WxEmpty
title={loading ? '加载中…' : q || tab !== 'all' ? '无匹配订单' : '暂无订单'}
hint={loading ? undefined : '用户完成虚拟支付后会出现在此列表'}
/>
)}
</div>
</div>
)

View File

@ -1,6 +1,17 @@
import { useCallback, useEffect, useMemo, useState } from 'react'
import { api } from '../api'
import './BookEdit.css'
import {
WxBadge,
WxEmpty,
WxHead,
WxTabs,
WxToast,
copyText,
fmtTime,
fmtYuan,
shortId,
} from '../components/wxUi'
type GoodsType = 'virtual' | 'physical'
@ -82,6 +93,8 @@ export default function Shop() {
const [err, setErr] = useState('')
const [msg, setMsg] = useState('')
const [busy, setBusy] = useState(false)
const [q, setQ] = useState('')
const [orderFilter, setOrderFilter] = useState<'all' | 'paid' | 'ship'>('all')
const load = useCallback(async () => {
setErr('')
@ -108,6 +121,33 @@ export default function Shop() {
[products],
)
const productStats = useMemo(() => {
const on = products.filter((p) => p.enabled).length
const low = products.filter((p) => p.goodsType === 'virtual' && p.stock <= 3).length
return { total: products.length, on, low, orders: orders.length }
}, [products, orders])
const filteredProducts = useMemo(() => {
const needle = q.trim().toLowerCase()
if (!needle) return products
return products.filter(
(p) =>
p.id.toLowerCase().includes(needle) ||
p.title.toLowerCase().includes(needle) ||
(p.wxProductId || '').toLowerCase().includes(needle) ||
(p.groupName || '').toLowerCase().includes(needle),
)
}, [products, q])
const filteredOrders = useMemo(() => {
return orders.filter((o) => {
if (orderFilter === 'paid' && o.status !== 'paid') return false
if (orderFilter === 'ship' && !(o.goodsType === 'physical' && o.status === 'paid' && !o.trackingNo))
return false
return true
})
}, [orders, orderFilter])
const activeOfferKey = useMemo(() => {
if (draft.offerKey) return draft.offerKey
return (
@ -116,6 +156,15 @@ export default function Shop() {
)
}, [draft.offerKey, draft.wxProductId, offers])
const carmiLines = useMemo(
() =>
carmiText
.split(/\r?\n/)
.map((s) => s.trim())
.filter(Boolean),
[carmiText],
)
function pickOffer(o: ProductOffer) {
setDraft((d) => ({
...d,
@ -126,6 +175,10 @@ export default function Shop() {
}
async function saveProduct() {
if (!draft.title.trim()) {
setErr('请填写商品标题')
return
}
setBusy(true)
setMsg('')
setErr('')
@ -136,7 +189,7 @@ export default function Shop() {
})
setMsg(
draft.wxProductId
? `已保存 · 道具 ${draft.wxProductId} · ¥${(draft.priceFen / 100).toFixed(0)}`
? `已保存 · 道具 ${draft.wxProductId} · ${fmtYuan(draft.priceFen)}`
: '商品已保存(未选道具)',
)
setDraft(emptyProduct)
@ -149,10 +202,12 @@ export default function Shop() {
}
async function removeProduct(id: string) {
if (!confirm(`删除商品 ${id}?`)) return
if (!confirm(`删除商品 ${id}?此操作不可撤销`)) return
setBusy(true)
try {
await api(`/api/admin/shop/products/${id}`, { method: 'DELETE' })
setMsg(`已删除 ${id}`)
if (draft.id === id) setDraft(emptyProduct)
await load()
} catch (e) {
setErr((e as Error).message || '删除失败')
@ -162,11 +217,7 @@ export default function Shop() {
}
async function importCarmis() {
const codes = carmiText
.split(/\r?\n/)
.map((s) => s.trim())
.filter(Boolean)
if (!carmiProductId || !codes.length) {
if (!carmiProductId || !carmiLines.length) {
setErr('请选择商品并粘贴卡密(一行一个)')
return
}
@ -176,7 +227,7 @@ export default function Shop() {
try {
const res = await api<{ imported: number; stock: number }>('/api/admin/shop/carmis', {
method: 'POST',
body: JSON.stringify({ productId: carmiProductId, codes }),
body: JSON.stringify({ productId: carmiProductId, codes: carmiLines }),
})
setMsg(`已导入 ${res.imported} 条,当前库存 ${res.stock}`)
setCarmiText('')
@ -189,6 +240,10 @@ export default function Shop() {
}
async function ship(orderId: string) {
if (!trackingNo.trim()) {
setErr('请填写运单号')
return
}
setBusy(true)
setErr('')
setMsg('')
@ -210,41 +265,71 @@ export default function Shop() {
}
return (
<div className="page">
<header className="page-head">
<div>
<h1>电商</h1>
<p>付费方案与 VIP / 小册相同(已发布虚拟支付道具);每个商品单独选道具,勿共用同一道具。</p>
<div className="wx-page">
<WxHead
eyebrow="设备商城"
title="电商"
desc="付费方案与 VIP / 小册同源道具。商品、卡密、实体发货分栏管理;每商品单独选道具。"
>
<button
type="button"
className="wx-btn wx-btn-ghost"
disabled={busy}
onClick={() => load().catch((e) => setErr(e.message || '加载失败'))}
>
刷新
</button>
</WxHead>
{err ? (
<WxToast kind="err" onClose={() => setErr('')}>
{err}
</WxToast>
) : null}
{msg ? (
<WxToast kind="ok" onClose={() => setMsg('')}>
{msg}
</WxToast>
) : null}
<div className="wx-stats" style={{ gridTemplateColumns: 'repeat(4, minmax(0, 1fr))' }}>
<div className="wx-stat">
<div className="wx-stat-label">商品</div>
<div className="wx-stat-val">{productStats.total}</div>
</div>
<div className="wx-stat">
<div className="wx-stat-label">上架中</div>
<div className="wx-stat-val">{productStats.on}</div>
</div>
<div className="wx-stat wx-stat--warn">
<div className="wx-stat-label">低库存(≤3)</div>
<div className="wx-stat-val">{productStats.low}</div>
</div>
<div className="wx-stat">
<div className="wx-stat-label">商城订单</div>
<div className="wx-stat-val">{productStats.orders}</div>
</div>
</header>
{err ? <div className="banner err">{err}</div> : null}
{msg ? <div className="banner ok">{msg}</div> : null}
<div className="panel" style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
{(
[
['products', '商品'],
['carmis', '卡密'],
['orders', '订单'],
] as const
).map(([k, label]) => (
<button
key={k}
type="button"
className={tab === k ? 'primary-btn' : 'ghost-btn'}
onClick={() => setTab(k)}
>
{label}
</button>
))}
</div>
<WxTabs
value={tab}
onChange={setTab}
items={[
{ key: 'products', label: '商品', count: products.length },
{ key: 'carmis', label: '卡密', count: virtualProducts.length },
{ key: 'orders', label: '订单', count: orders.length },
]}
/>
{tab === 'products' ? (
<>
<div className="panel monetize-panel">
<h2 style={{ marginTop: 0 }}>{draft.id ? `编辑 ${draft.id}` : '新建 / 编辑商品'}</h2>
<p className="hint">先点选付费方案(道具 + 价格),再填写标题与类型后保存。</p>
<section className="wx-panel monetize-panel">
<div className="wx-panel-head">
<div>
<h2>{draft.id ? `编辑 ${draft.id}` : '新建 / 编辑商品'}</h2>
<p>先点选付费方案(道具 + 价格),再填标题与类型后保存。</p>
</div>
</div>
<div className="offer-grid offer-grid-6" style={{ marginBottom: 16 }}>
{offers.map((o) => {
@ -273,27 +358,8 @@ export default function Shop() {
})}
</div>
<div className="unlock-hero monetize-unlock" style={{ marginBottom: 16 }}>
<div className="price-box mono-box" style={{ width: '100%' }}>
<div>
<label>道具 ID</label>
<code>{draft.wxProductId || '—'}</code>
</div>
<div>
<label>价格</label>
<code>
¥{(draft.priceFen / 100).toFixed(0)}({draft.priceFen} 分)
</code>
</div>
<div>
<label>方案</label>
<code>{draft.offerKey || '—'}</code>
</div>
</div>
</div>
<div className="form-grid">
<label>
<div className="wx-form-grid">
<label className="wx-field">
ID(空则自动)
<input
value={draft.id}
@ -301,21 +367,21 @@ export default function Shop() {
placeholder="yt-device"
/>
</label>
<label>
<label className="wx-field">
标题
<input
value={draft.title}
onChange={(e) => setDraft({ ...draft, title: e.target.value })}
/>
</label>
<label>
<label className="wx-field">
分组
<input
value={draft.groupName}
onChange={(e) => setDraft({ ...draft, groupName: e.target.value })}
/>
</label>
<label>
<label className="wx-field">
类型
<select
value={draft.goodsType}
@ -327,22 +393,22 @@ export default function Shop() {
<option value="physical">实体发货</option>
</select>
</label>
<label>
库存(实体手动;虚拟跟卡密)
<label className="wx-field">
库存
<input
type="number"
value={draft.stock}
onChange={(e) => setDraft({ ...draft, stock: Number(e.target.value) || 0 })}
/>
</label>
<label>
<label className="wx-field">
Emoji
<input
value={draft.coverEmoji}
onChange={(e) => setDraft({ ...draft, coverEmoji: e.target.value })}
/>
</label>
<label style={{ gridColumn: '1 / -1' }}>
<label className="wx-field span-2">
描述
<input
value={draft.desc}
@ -350,198 +416,290 @@ export default function Shop() {
/>
</label>
</div>
<div style={{ display: 'flex', gap: 8, marginTop: 12, flexWrap: 'wrap' }}>
<label style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<input
type="checkbox"
checked={draft.enabled}
onChange={(e) => setDraft({ ...draft, enabled: e.target.checked })}
/>
上架
</label>
<button type="button" className="primary-btn" disabled={busy} onClick={saveProduct}>
保存
</button>
<button type="button" className="ghost-btn" onClick={() => setDraft(emptyProduct)}>
清空
</button>
<div className="wx-sticky-bar">
<div className="wx-muted">
道具 <code>{draft.wxProductId || '—'}</code> · {fmtYuan(draft.priceFen)} ·{' '}
{draft.offerKey || '未选方案'}
</div>
<div className="wx-row-actions">
<label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13 }}>
<input
type="checkbox"
checked={draft.enabled}
onChange={(e) => setDraft({ ...draft, enabled: e.target.checked })}
/>
上架
</label>
<button type="button" className="wx-btn-sm" onClick={() => setDraft(emptyProduct)}>
清空
</button>
<button type="button" className="wx-btn" disabled={busy} onClick={() => void saveProduct()}>
{busy ? '保存中…' : '保存商品'}
</button>
</div>
</div>
</section>
<div className="wx-toolbar">
<input
type="search"
value={q}
placeholder="筛选商品 ID / 标题 / 道具"
onChange={(e) => setQ(e.target.value)}
/>
</div>
<div className="panel table-wrap">
<table>
<thead>
<tr>
<th>ID</th>
<th>标题</th>
<th>类型</th>
<th>道具</th>
<th>价格</th>
<th>库存</th>
<th>状态</th>
<th />
</tr>
</thead>
<tbody>
{products.map((p) => (
<tr key={p.id}>
<td className="mono">{p.id}</td>
<td>
{p.coverEmoji} {p.title}
</td>
<td>{p.goodsType === 'virtual' ? '虚拟' : '实体'}</td>
<td className="mono">{p.wxProductId || '—'}</td>
<td>¥{(p.priceFen / 100).toFixed(0)}</td>
<td>{p.stock}</td>
<td>{p.enabled ? '上架' : '下架'}</td>
<td>
<button type="button" className="ghost-btn" onClick={() => setDraft(p)}>
编辑
</button>
<button
type="button"
className="ghost-btn"
onClick={() => removeProduct(p.id)}
>
删
</button>
</td>
</tr>
))}
{!products.length && (
<div className="wx-table-wrap">
{filteredProducts.length ? (
<table className="wx-table">
<thead>
<tr>
<td colSpan={8}>暂无商品</td>
<th>商品</th>
<th>类型</th>
<th>道具</th>
<th>价格</th>
<th>库存</th>
<th>状态</th>
<th>操作</th>
</tr>
)}
</tbody>
</table>
</thead>
<tbody>
{filteredProducts.map((p) => (
<tr key={p.id}>
<td>
<strong>
{p.coverEmoji} {p.title}
</strong>
<div className="wx-mono" style={{ marginTop: 4 }}>
{p.id}
</div>
</td>
<td>{p.goodsType === 'virtual' ? '虚拟' : '实体'}</td>
<td className="wx-mono">{p.wxProductId || '—'}</td>
<td>{fmtYuan(p.priceFen)}</td>
<td>
<WxBadge tone={p.stock <= 3 && p.goodsType === 'virtual' ? 'warn' : 'muted'}>
{p.stock}
</WxBadge>
</td>
<td>
<WxBadge tone={p.enabled ? 'ok' : 'muted'}>
{p.enabled ? '上架' : '下架'}
</WxBadge>
</td>
<td>
<div className="wx-row-actions">
<button
type="button"
className="wx-btn-sm primary"
onClick={() => {
setDraft(p)
window.scrollTo({ top: 0, behavior: 'smooth' })
}}
>
编辑
</button>
<button
type="button"
className="wx-btn-sm danger"
onClick={() => void removeProduct(p.id)}
>
删
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
) : (
<WxEmpty title="暂无商品" hint="上方选择付费方案并保存后出现" />
)}
</div>
</>
) : null}
{tab === 'carmis' ? (
<div className="panel">
<h2 style={{ marginTop: 0 }}>导入卡密</h2>
<p style={{ opacity: 0.7 }}>一行一个;导入后自动更新虚拟商品库存。</p>
<label>
虚拟商品
<select value={carmiProductId} onChange={(e) => setCarmiProductId(e.target.value)}>
<option value="">选择…</option>
{virtualProducts.map((p) => (
<option key={p.id} value={p.id}>
{p.title}(库存 {p.stock} · {p.wxProductId || '无道具'})
</option>
))}
</select>
</label>
<textarea
rows={10}
style={{ width: '100%', marginTop: 12 }}
value={carmiText}
onChange={(e) => setCarmiText(e.target.value)}
placeholder={'CARD-001\nCARD-002'}
/>
<button
type="button"
className="primary-btn"
style={{ marginTop: 12 }}
disabled={busy}
onClick={importCarmis}
>
导入
</button>
</div>
<section className="wx-panel">
<div className="wx-panel-head">
<div>
<h2>导入卡密</h2>
<p>一行一个;导入后自动更新虚拟商品库存。</p>
</div>
</div>
<div className="wx-form-grid">
<label className="wx-field span-2">
虚拟商品
<select value={carmiProductId} onChange={(e) => setCarmiProductId(e.target.value)}>
<option value="">选择…</option>
{virtualProducts.map((p) => (
<option key={p.id} value={p.id}>
{p.title}(库存 {p.stock} · {p.wxProductId || '无道具'})
</option>
))}
</select>
</label>
<label className="wx-field span-2">
卡密列表(已识别 {carmiLines.length} 行)
<textarea
rows={12}
value={carmiText}
onChange={(e) => setCarmiText(e.target.value)}
placeholder={'CARD-001\nCARD-002'}
/>
</label>
</div>
<div className="wx-sticky-bar">
<span className="wx-muted">重复行会按服务端规则去重</span>
<button type="button" className="wx-btn" disabled={busy} onClick={() => void importCarmis()}>
{busy ? '导入中…' : `导入 ${carmiLines.length || ''}`.trim()}
</button>
</div>
</section>
) : null}
{tab === 'orders' ? (
<div className="panel table-wrap">
<table>
<thead>
<tr>
<th>订单</th>
<th>商品</th>
<th>类型</th>
<th>金额</th>
<th>状态</th>
<th>用户/地址/卡密</th>
<th>发货</th>
</tr>
</thead>
<tbody>
{orders.map((o) => (
<tr key={o.id}>
<td className="mono">
{o.id}
<div style={{ opacity: 0.6 }}>{o.outTradeNo}</div>
</td>
<td>
{o.productTitle} ×{o.qty}
</td>
<td>{o.goodsType === 'virtual' ? '虚拟' : '实体'}</td>
<td>¥{(o.amountFen / 100).toFixed(2)}</td>
<td>{o.status}</td>
<td style={{ maxWidth: 240, fontSize: 12 }}>
<div className="mono">{o.openid.slice(0, 16)}…</div>
{o.email ? <div>{o.email}</div> : null}
{o.address?.userName ? (
<div>
{o.address.userName} {o.address.telNumber}
<br />
{o.address.provinceName}
{o.address.cityName}
{o.address.countyName}
{o.address.detailInfo}
</div>
) : null}
{o.carmis?.length ? <div>卡密: {o.carmis.join(', ')}</div> : null}
{o.trackingNo ? (
<div>
物流 {o.expressCompany} {o.trackingNo}
</div>
) : null}
</td>
<td>
{o.goodsType === 'physical' && o.status === 'paid' ? (
shipId === o.id ? (
<div style={{ display: 'grid', gap: 4 }}>
<input
placeholder="快递公司"
value={expressCompany}
onChange={(e) => setExpressCompany(e.target.value)}
/>
<input
placeholder="运单号"
value={trackingNo}
onChange={(e) => setTrackingNo(e.target.value)}
/>
<button
type="button"
className="primary-btn"
disabled={busy}
onClick={() => ship(o.id)}
>
确认发货
</button>
</div>
) : (
<button type="button" className="ghost-btn" onClick={() => setShipId(o.id)}>
发货
<>
<div className="wx-chip-row">
{(
[
['all', '全部'],
['paid', '已支付'],
['ship', '待发货(实体)'],
] as const
).map(([k, label]) => (
<button
key={k}
type="button"
className={`wx-chip${orderFilter === k ? ' is-on' : ''}`}
onClick={() => setOrderFilter(k)}
>
{label}
</button>
))}
</div>
<div className="wx-table-wrap">
{filteredOrders.length ? (
<table className="wx-table">
<thead>
<tr>
<th>订单</th>
<th>商品</th>
<th>金额</th>
<th>状态</th>
<th>用户 / 履约</th>
<th>时间</th>
<th>发货</th>
</tr>
</thead>
<tbody>
{filteredOrders.map((o) => (
<tr key={o.id}>
<td>
<div className="wx-mono">{o.id}</div>
<button
type="button"
className="wx-btn-sm"
style={{ marginTop: 4 }}
onClick={() =>
void copyText(o.outTradeNo).then((ok) =>
setMsg(ok ? '已复制业务单号' : '复制失败'),
)
}
>
{shortId(o.outTradeNo, 10)}
</button>
)
) : (
'—'
)}
</td>
</tr>
))}
{!orders.length && (
<tr>
<td colSpan={7}>暂无订单</td>
</tr>
)}
</tbody>
</table>
</div>
</td>
<td>
{o.productTitle} ×{o.qty}
<div style={{ marginTop: 4 }}>
<WxBadge tone="muted">
{o.goodsType === 'virtual' ? '虚拟' : '实体'}
</WxBadge>
</div>
</td>
<td>{fmtYuan(o.amountFen)}</td>
<td>
<WxBadge tone={o.status === 'paid' ? 'ok' : 'warn'}>{o.status}</WxBadge>
</td>
<td style={{ maxWidth: 260, fontSize: 12 }}>
<div className="wx-mono">{shortId(o.openid, 12)}</div>
{o.email ? <div>{o.email}</div> : null}
{o.address?.userName ? (
<div>
{o.address.userName} {o.address.telNumber}
<br />
{o.address.provinceName}
{o.address.cityName}
{o.address.countyName}
{o.address.detailInfo}
</div>
) : null}
{o.carmis?.length ? (
<div className="wx-detail">卡密: {o.carmis.join(', ')}</div>
) : null}
{o.trackingNo ? (
<div>
物流 {o.expressCompany} {o.trackingNo}
</div>
) : null}
</td>
<td>{fmtTime(o.createdAt)}</td>
<td>
{o.goodsType === 'physical' && o.status === 'paid' && !o.trackingNo ? (
shipId === o.id ? (
<div style={{ display: 'grid', gap: 6 }}>
<input
placeholder="快递公司"
value={expressCompany}
onChange={(e) => setExpressCompany(e.target.value)}
/>
<input
placeholder="运单号"
value={trackingNo}
onChange={(e) => setTrackingNo(e.target.value)}
/>
<div className="wx-row-actions">
<button
type="button"
className="wx-btn-sm primary"
disabled={busy}
onClick={() => void ship(o.id)}
>
确认
</button>
<button
type="button"
className="wx-btn-sm"
onClick={() => setShipId('')}
>
取消
</button>
</div>
</div>
) : (
<button
type="button"
className="wx-btn-sm primary"
onClick={() => setShipId(o.id)}
>
发货
</button>
)
) : (
<span className="wx-muted">—</span>
)}
</td>
</tr>
))}
</tbody>
</table>
) : (
<WxEmpty title="暂无订单" />
)}
</div>
</>
) : null}
</div>
)

View File

@ -1,6 +1,16 @@
import { useEffect, useMemo, useState } from 'react'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { Link } from 'react-router-dom'
import { api } from '../api'
import {
WxBadge,
WxEmpty,
WxHead,
WxTabs,
WxToast,
copyText,
fmtTime,
shortId,
} from '../components/wxUi'
type UnlockRow = { book_id: string; unlocked_at: number; source: string }
@ -17,207 +27,336 @@ type UserRow = {
unlocks: UnlockRow[]
}
type Tab = 'all' | 'unlocked' | 'locked' | 'blocked'
export default function Users() {
const [users, setUsers] = useState<UserRow[]>([])
const [q, setQ] = useState('')
const [tab, setTab] = useState<Tab>('all')
const [msg, setMsg] = useState('')
const [err, setErr] = useState('')
const [manualOpenid, setManualOpenid] = useState('')
const [busy, setBusy] = useState('')
const [loading, setLoading] = useState(true)
const [openId, setOpenId] = useState<string | null>(null)
async function refresh(search = q) {
const qs = search.trim() ? `?q=${encodeURIComponent(search.trim())}` : ''
setUsers(await api<UserRow[]>(`/api/admin/users${qs}`))
}
useEffect(() => {
refresh().catch((e) => setMsg(String(e.message || e)))
}, [])
const blockedCount = useMemo(
() => users.filter((u) => (u.status || 'active') === 'blocked').length,
[users],
const refresh = useCallback(
async (search = q) => {
setLoading(true)
setErr('')
try {
const qs = search.trim() ? `?q=${encodeURIComponent(search.trim())}` : ''
setUsers(await api<UserRow[]>(`/api/admin/users${qs}`))
} catch (e: any) {
setErr(e.message || String(e))
} finally {
setLoading(false)
}
},
[q],
)
async function run(key: string, fn: () => Promise<void>) {
useEffect(() => {
void refresh('')
}, [])
const counts = useMemo(() => {
let unlocked = 0
let locked = 0
let blocked = 0
for (const u of users) {
if ((u.status || 'active') === 'blocked') blocked += 1
if (u.unlocked_default) unlocked += 1
else locked += 1
}
return { total: users.length, unlocked, locked, blocked }
}, [users])
const filtered = useMemo(() => {
return users.filter((u) => {
const blocked = (u.status || 'active') === 'blocked'
if (tab === 'unlocked' && !u.unlocked_default) return false
if (tab === 'locked' && u.unlocked_default) return false
if (tab === 'blocked' && !blocked) return false
return true
})
}, [users, tab])
async function run(key: string, fn: () => Promise<void>, okMsg?: string) {
setBusy(key)
setMsg('')
setErr('')
try {
await fn()
await refresh()
if (okMsg) setMsg(okMsg)
} catch (e: any) {
setMsg(e.message || String(e))
setErr(e.message || String(e))
} finally {
setBusy('')
}
}
return (
<div className="page">
<header className="page-head">
<div>
<h1>读者</h1>
<p>
以微信 openid 绑定(SQLite 主存;PocketBase 可选同步集合 wx_readers)。共 {users.length}{' '}
人,拉黑 {blockedCount}。
</p>
<div className="wx-page">
<WxHead
eyebrow="读者运营"
title="读者"
desc={`openid 绑定读者(SQLite 主存)。共 ${counts.total} 人,拉黑 ${counts.blocked}。可搜索、筛选、解锁 / 收回 / 拉黑。`}
>
<Link className="wx-btn wx-btn-ghost" to="/wechat/checklist">
部署清单
</Link>
<button type="button" className="wx-btn" onClick={() => void refresh()} 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" style={{ gridTemplateColumns: 'repeat(4, minmax(0, 1fr))' }}>
<div className="wx-stat">
<div className="wx-stat-label">读者</div>
<div className="wx-stat-val">{counts.total}</div>
</div>
</header>
<div className="wx-stat">
<div className="wx-stat-label">已解锁</div>
<div className="wx-stat-val">{counts.unlocked}</div>
</div>
<div className="wx-stat wx-stat--warn">
<div className="wx-stat-label">未解锁</div>
<div className="wx-stat-val">{counts.locked}</div>
</div>
<div className="wx-stat">
<div className="wx-stat-label">拉黑</div>
<div className="wx-stat-val">{counts.blocked}</div>
</div>
</div>
{msg ? <div className="banner">{msg}</div> : null}
<section className="panel" style={{ marginBottom: 16 }}>
<div className="row" style={{ gap: 12, flexWrap: 'wrap', alignItems: 'center' }}>
<section className="wx-panel">
<div className="wx-toolbar" style={{ marginBottom: 0 }}>
<input
type="search"
value={q}
placeholder="搜索 openid / 备注 / 昵称"
placeholder="搜索 openid / 备注 / 昵称,回车搜索"
onChange={(e) => setQ(e.target.value)}
style={{ minWidth: 240, flex: 1 }}
onKeyDown={(e) => {
if (e.key === 'Enter') void refresh()
}}
/>
<button type="button" onClick={() => refresh().catch(console.error)}>
<button type="button" className="wx-btn wx-btn-ghost" onClick={() => void refresh()}>
搜索
</button>
<input
type="text"
value={manualOpenid}
placeholder="补录 openid 并解锁"
placeholder="补录 openid 并解锁全书"
onChange={(e) => setManualOpenid(e.target.value)}
style={{ minWidth: 220, flex: 1 }}
/>
<button
type="button"
className="wx-btn"
disabled={!manualOpenid.trim() || busy === 'manual'}
onClick={() =>
run('manual', async () => {
await api('/api/admin/unlock', {
method: 'POST',
body: JSON.stringify({ openid: manualOpenid.trim(), book_id: 'default' }),
})
setMsg(`已解锁 ${manualOpenid.trim()}`)
setManualOpenid('')
})
void run(
'manual',
async () => {
await api('/api/admin/unlock', {
method: 'POST',
body: JSON.stringify({ openid: manualOpenid.trim(), book_id: 'default' }),
})
setManualOpenid('')
},
`已解锁 ${manualOpenid.trim()}`,
)
}
>
手动解锁
</button>
</div>
<p className="muted" style={{ marginTop: 10 }}>
绑定方案:小程序 wx.login → code2session → openid 作为读者主键;不把微信用户做成 PocketBase
Auth 密码账号。详见 <Link to="/wechat/checklist">部署清单</Link>。
<p className="wx-hint" style={{ marginTop: 12 }}>
绑定:小程序 wx.login → code2session → openid 作为主键。详见{' '}
<Link className="wx-link" to="/wechat/checklist">
部署清单
</Link>
。
</p>
</section>
<div className="panel table-wrap">
<table>
<thead>
<tr>
<th>OpenID</th>
<th>状态</th>
<th>解锁</th>
<th>备注</th>
<th>最近活跃</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{users.map((u) => {
const blocked = (u.status || 'active') === 'blocked'
return (
<tr key={u.openid} style={blocked ? { opacity: 0.72 } : undefined}>
<td className="mono">
{u.openid}
{u.pb_record_id ? (
<div className="muted" style={{ fontSize: 12 }}>
PB:{u.pb_record_id}
</div>
) : null}
</td>
<td>{blocked ? '拉黑' : '正常'}</td>
<td>
{u.unlocked_default ? '✅ 全书' : '—'}
{u.unlocks?.length ? (
<div className="muted" style={{ fontSize: 12 }}>
{u.unlocks
.map((x) => `${x.book_id}${x.source ? `(${x.source})` : ''}`)
.join(' · ')}
</div>
) : null}
</td>
<td style={{ minWidth: 160 }}>
<input
defaultValue={u.notes || ''}
key={`${u.openid}-notes-${u.updated_at}`}
placeholder="备注"
onBlur={(e) => {
const notes = e.target.value
if (notes === (u.notes || '')) return
run(`notes-${u.openid}`, async () => {
await api(`/api/admin/users/${encodeURIComponent(u.openid)}`, {
method: 'PATCH',
body: JSON.stringify({ notes }),
})
})
}}
/>
</td>
<td>{u.updated_at ? new Date(u.updated_at * 1000).toLocaleString() : '—'}</td>
<td style={{ whiteSpace: 'nowrap' }}>
<button
type="button"
disabled={u.unlocked_default || busy === `unlock-${u.openid}`}
onClick={() =>
run(`unlock-${u.openid}`, async () => {
await api('/api/admin/unlock', {
method: 'POST',
body: JSON.stringify({ openid: u.openid, book_id: 'default' }),
})
setMsg(`已解锁 ${u.openid}`)
})
}
>
解锁
</button>{' '}
<button
type="button"
disabled={!u.unlocked_default || busy === `revoke-${u.openid}`}
onClick={() =>
run(`revoke-${u.openid}`, async () => {
await api('/api/admin/revoke-unlock', {
method: 'POST',
body: JSON.stringify({ openid: u.openid, book_id: 'default' }),
})
setMsg(`已收回解锁 ${u.openid}`)
})
}
>
收回
</button>{' '}
<button
type="button"
disabled={busy === `block-${u.openid}`}
onClick={() =>
run(`block-${u.openid}`, async () => {
await api(
`/api/admin/users/${encodeURIComponent(u.openid)}/${
blocked ? 'unblock' : 'block'
}`,
{ method: 'POST' },
)
setMsg(blocked ? `已恢复 ${u.openid}` : `已拉黑 ${u.openid}`)
})
}
>
{blocked ? '解除拉黑' : '拉黑'}
</button>
</td>
</tr>
)
})}
{!users.length && (
<WxTabs
value={tab}
onChange={setTab}
items={[
{ key: 'all', label: '全部', count: counts.total },
{ key: 'unlocked', label: '已解锁', count: counts.unlocked },
{ key: 'locked', label: '未解锁', count: counts.locked },
{ key: 'blocked', label: '拉黑', count: counts.blocked },
]}
/>
<div className="wx-table-wrap">
{filtered.length ? (
<table className="wx-table">
<thead>
<tr>
<td colSpan={6}>暂无读者(用户打开小程序登录后会出现)</td>
<th>读者</th>
<th>状态</th>
<th>解锁</th>
<th>备注</th>
<th>活跃</th>
<th>操作</th>
</tr>
)}
</tbody>
</table>
</thead>
<tbody>
{filtered.map((u) => {
const blocked = (u.status || 'active') === 'blocked'
const open = openId === u.openid
return (
<tr key={u.openid} className={`${blocked ? 'is-dim ' : ''}${open ? 'is-open' : ''}`}>
<td>
<button
type="button"
className="wx-btn-sm"
title={u.openid}
onClick={() =>
void copyText(u.openid).then((ok) => setMsg(ok ? '已复制 OpenID' : '复制失败'))
}
>
{shortId(u.openid, 12)}
</button>
{u.nickname ? <div style={{ marginTop: 4 }}>{u.nickname}</div> : null}
{open ? (
<div className="wx-detail">
openid: {u.openid}
{u.unionid ? `\nunionid: ${u.unionid}` : ''}
{u.pb_record_id ? `\nPB: ${u.pb_record_id}` : ''}
{'\n'}unlocks:{' '}
{u.unlocks?.length
? u.unlocks
.map((x) => `${x.book_id}${x.source ? `(${x.source})` : ''}`)
.join(' · ')
: '无'}
</div>
) : null}
</td>
<td>
<WxBadge tone={blocked ? 'bad' : 'ok'}>{blocked ? '拉黑' : '正常'}</WxBadge>
</td>
<td>
<WxBadge tone={u.unlocked_default ? 'ok' : 'muted'}>
{u.unlocked_default ? '全书' : '未解锁'}
</WxBadge>
</td>
<td style={{ minWidth: 160 }}>
<input
defaultValue={u.notes || ''}
key={`${u.openid}-notes-${u.updated_at}`}
placeholder="备注,失焦保存"
onBlur={(e) => {
const notes = e.target.value
if (notes === (u.notes || '')) return
void run(`notes-${u.openid}`, async () => {
await api(`/api/admin/users/${encodeURIComponent(u.openid)}`, {
method: 'PATCH',
body: JSON.stringify({ notes }),
})
}, '备注已保存')
}}
/>
</td>
<td>{fmtTime(u.updated_at)}</td>
<td>
<div className="wx-row-actions">
<button
type="button"
className="wx-btn-sm"
onClick={() => setOpenId(open ? null : u.openid)}
>
{open ? '收起' : '详情'}
</button>
<button
type="button"
className="wx-btn-sm primary"
disabled={u.unlocked_default || busy === `unlock-${u.openid}`}
onClick={() =>
void run(
`unlock-${u.openid}`,
async () => {
await api('/api/admin/unlock', {
method: 'POST',
body: JSON.stringify({ openid: u.openid, book_id: 'default' }),
})
},
`已解锁 ${shortId(u.openid)}`,
)
}
>
解锁
</button>
<button
type="button"
className="wx-btn-sm"
disabled={!u.unlocked_default || busy === `revoke-${u.openid}`}
onClick={() => {
if (!confirm(`收回 ${u.openid} 的全书解锁?`)) return
void run(
`revoke-${u.openid}`,
async () => {
await api('/api/admin/revoke-unlock', {
method: 'POST',
body: JSON.stringify({ openid: u.openid, book_id: 'default' }),
})
},
'已收回解锁',
)
}}
>
收回
</button>
<button
type="button"
className={`wx-btn-sm${blocked ? '' : ' danger'}`}
disabled={busy === `block-${u.openid}`}
onClick={() => {
if (!blocked && !confirm(`拉黑 ${u.openid}?`)) return
void run(
`block-${u.openid}`,
async () => {
await api(
`/api/admin/users/${encodeURIComponent(u.openid)}/${
blocked ? 'unblock' : 'block'
}`,
{ method: 'POST' },
)
},
blocked ? '已恢复' : '已拉黑',
)
}}
>
{blocked ? '解除' : '拉黑'}
</button>
</div>
</td>
</tr>
)
})}
</tbody>
</table>
) : (
<WxEmpty
title={loading ? '加载中…' : '暂无读者'}
hint="用户打开小程序登录后会出现;也可上方补录 openid"
/>
)}
</div>
</div>
)

View File

@ -0,0 +1,664 @@
/* 微信 VIP 运营台 — 琥珀强调,贴合微信绿壳 */
.vip-page {
--vip-amber: #f59e0b;
--vip-amber-2: #fbbf24;
--vip-amber-dim: rgba(245, 158, 11, 0.14);
--vip-amber-line: rgba(245, 158, 11, 0.28);
--vip-ink: #1c1408;
--vip-ok: #6ee7b7;
--vip-danger: #f87171;
--vip-radius: 16px;
--vip-radius-sm: 12px;
max-width: 1120px;
}
.vip-page .page-head {
align-items: flex-start;
margin-bottom: 18px;
}
.vip-eyebrow {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 11px;
font-weight: 600;
letter-spacing: 0.08em;
text-transform: uppercase;
color: var(--vip-amber-2);
margin-bottom: 8px;
}
.vip-eyebrow::before {
content: '';
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--vip-amber);
box-shadow: 0 0 10px var(--vip-amber);
animation: vip-pulse 2s ease-in-out infinite;
}
@keyframes vip-pulse {
0%,
100% {
opacity: 1;
}
50% {
opacity: 0.35;
}
}
.vip-chips {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 14px;
}
.vip-chip {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 6px 11px;
border-radius: 999px;
font-size: 12px;
font-weight: 600;
border: 1px solid var(--line);
background: rgba(0, 0, 0, 0.22);
color: var(--muted);
}
.vip-chip.on {
border-color: var(--vip-amber-line);
background: var(--vip-amber-dim);
color: var(--vip-amber-2);
}
.vip-chip.ok {
border-color: rgba(110, 231, 183, 0.28);
background: rgba(110, 231, 183, 0.1);
color: var(--vip-ok);
}
.vip-chip.warn {
border-color: rgba(248, 113, 113, 0.3);
background: rgba(248, 113, 113, 0.1);
color: var(--vip-danger);
}
.vip-toast {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 12px 14px;
border-radius: var(--vip-radius-sm);
margin-bottom: 14px;
font-size: 13px;
font-weight: 500;
animation: vip-toast-in 0.28s ease;
}
@keyframes vip-toast-in {
from {
opacity: 0;
transform: translateY(-6px);
}
to {
opacity: 1;
transform: none;
}
}
.vip-toast.ok {
border: 1px solid rgba(110, 231, 183, 0.28);
background: rgba(110, 231, 183, 0.1);
color: var(--vip-ok);
}
.vip-toast.err {
border: 1px solid rgba(248, 113, 113, 0.3);
background: rgba(248, 113, 113, 0.1);
color: #fecaca;
}
.vip-toast button {
border: none;
background: transparent;
color: inherit;
cursor: pointer;
opacity: 0.7;
font-size: 16px;
line-height: 1;
padding: 4px;
}
.vip-tabs {
display: flex;
gap: 6px;
padding: 4px;
margin-bottom: 16px;
border-radius: 14px;
background: rgba(0, 0, 0, 0.28);
border: 1px solid var(--line);
width: fit-content;
max-width: 100%;
overflow-x: auto;
}
.vip-tab {
border: none;
background: transparent;
color: var(--muted);
font: inherit;
font-size: 13px;
font-weight: 600;
padding: 10px 16px;
border-radius: 11px;
cursor: pointer;
min-height: 40px;
white-space: nowrap;
transition: background 0.15s, color 0.15s;
}
.vip-tab:hover {
color: var(--text);
background: rgba(255, 255, 255, 0.04);
}
.vip-tab.active {
background: linear-gradient(135deg, rgba(245, 158, 11, 0.95), rgba(251, 191, 36, 0.88));
color: var(--vip-ink);
box-shadow: 0 6px 18px rgba(245, 158, 11, 0.22);
}
.vip-card {
margin-bottom: 16px;
padding: 20px;
border-radius: var(--vip-radius);
border: 1px solid var(--line);
background:
radial-gradient(520px 200px at 0% 0%, var(--vip-amber-dim), transparent 55%),
rgba(0, 0, 0, 0.22);
}
.vip-card-head {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 16px;
flex-wrap: wrap;
margin-bottom: 16px;
}
.vip-card-head h2 {
margin: 0 0 6px;
font-family: var(--font-display);
font-size: 20px;
letter-spacing: -0.02em;
}
.vip-card-head p {
margin: 0;
color: var(--muted);
font-size: 13px;
line-height: 1.5;
max-width: 52ch;
}
.vip-preview-btn {
min-width: 200px;
padding: 14px 16px;
border-radius: 14px;
border: 1px solid rgba(255, 255, 255, 0.1);
background: rgba(12, 11, 14, 0.55);
display: flex;
flex-direction: column;
gap: 8px;
}
.vip-preview-btn span {
font-size: 11px;
color: var(--muted);
letter-spacing: 0.04em;
}
.vip-preview-btn strong {
height: 44px;
border-radius: 999px;
display: grid;
place-items: center;
font-size: 15px;
font-weight: 700;
color: var(--vip-ink);
background: linear-gradient(135deg, #fff7ed, #fbbf24);
box-shadow: 0 10px 24px rgba(0, 0, 0, 0.25);
}
.vip-preview-btn strong.free {
background: linear-gradient(135deg, #bbf7d0, #6ee7b7);
color: #062012;
}
.vip-preview-btn em {
font-style: normal;
font-size: 12px;
color: #d6c4a0;
}
.vip-switch {
position: relative;
display: inline-flex;
align-items: center;
cursor: pointer;
flex-shrink: 0;
}
.vip-switch input {
position: absolute;
opacity: 0;
width: 0;
height: 0;
}
.vip-switch-track {
width: 48px;
height: 28px;
border-radius: 999px;
background: rgba(255, 255, 255, 0.1);
border: 1px solid rgba(255, 255, 255, 0.08);
position: relative;
transition: background 0.18s, border-color 0.18s;
}
.vip-switch-thumb {
position: absolute;
top: 3px;
left: 3px;
width: 20px;
height: 20px;
border-radius: 50%;
background: #e7f3ea;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.35);
transition: transform 0.18s;
}
.vip-switch input:checked + .vip-switch-track {
background: linear-gradient(135deg, #d97706, #f59e0b);
border-color: transparent;
}
.vip-switch input:checked + .vip-switch-track .vip-switch-thumb {
transform: translateX(20px);
}
.vip-switch input:disabled + .vip-switch-track {
opacity: 0.45;
cursor: not-allowed;
}
.vip-switch input:focus-visible + .vip-switch-track {
outline: 2px solid var(--vip-amber);
outline-offset: 2px;
}
.vip-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
padding: 14px 0;
border-bottom: 1px solid rgba(255, 255, 255, 0.05);
}
.vip-row:last-child {
border-bottom: none;
padding-bottom: 0;
}
.vip-row:first-of-type {
padding-top: 0;
}
.vip-row strong {
display: block;
font-size: 14px;
margin-bottom: 3px;
}
.vip-row .vip-hint {
margin: 0;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
.vip-section-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(148px, 1fr));
gap: 10px;
margin: 8px 0 4px;
}
.vip-section-tile {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
padding: 12px 14px;
border-radius: var(--vip-radius-sm);
border: 1px solid var(--line);
background: rgba(0, 0, 0, 0.18);
min-height: 52px;
transition: border-color 0.15s, background 0.15s;
}
.vip-section-tile.on {
border-color: var(--vip-amber-line);
background: var(--vip-amber-dim);
}
.vip-section-tile span {
font-size: 13px;
font-weight: 600;
}
.vip-layout {
display: grid;
grid-template-columns: 1.15fr 0.85fr;
gap: 16px;
align-items: start;
}
.vip-fields {
display: flex;
flex-direction: column;
gap: 12px;
}
.vip-field label {
display: block;
font-size: 12px;
font-weight: 600;
color: var(--muted);
margin-bottom: 6px;
}
.vip-field input,
.vip-field textarea {
width: 100%;
border: 1px solid var(--line);
background: rgba(0, 0, 0, 0.28);
color: var(--text);
border-radius: 12px;
padding: 12px 14px;
font: inherit;
font-size: 14px;
min-height: 44px;
outline: none;
transition: border-color 0.15s, box-shadow 0.15s;
}
.vip-field input:focus,
.vip-field textarea:focus {
border-color: var(--vip-amber-line);
box-shadow: 0 0 0 3px var(--vip-amber-dim);
}
.vip-field textarea {
min-height: 72px;
resize: vertical;
line-height: 1.45;
}
.vip-phone {
border-radius: 28px;
border: 1px solid rgba(255, 255, 255, 0.1);
background: linear-gradient(180deg, #14120f 0%, #0c0c0f 100%);
padding: 18px 16px 22px;
box-shadow: 0 18px 40px rgba(0, 0, 0, 0.35);
position: sticky;
top: 16px;
}
.vip-phone-bar {
width: 72px;
height: 5px;
border-radius: 999px;
background: rgba(255, 255, 255, 0.12);
margin: 0 auto 16px;
}
.vip-phone-eyebrow {
font-size: 11px;
letter-spacing: 0.12em;
text-transform: uppercase;
color: #a8a29e;
margin-bottom: 8px;
}
.vip-phone-title {
font-family: var(--font-display);
font-size: 22px;
line-height: 1.25;
margin: 0 0 8px;
letter-spacing: -0.02em;
}
.vip-phone-title b {
color: var(--vip-amber-2);
font-weight: 800;
}
.vip-phone-lead {
margin: 0 0 16px;
color: #a8a29e;
font-size: 12px;
line-height: 1.5;
}
.vip-phone-blocks {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-bottom: 16px;
}
.vip-phone-blocks i {
font-style: normal;
font-size: 11px;
padding: 5px 8px;
border-radius: 8px;
background: rgba(255, 255, 255, 0.05);
color: #d6d3d1;
border: 1px solid rgba(255, 255, 255, 0.06);
}
.vip-phone-blocks i.off {
opacity: 0.35;
text-decoration: line-through;
}
.vip-phone-cta {
height: 44px;
border-radius: 999px;
display: grid;
place-items: center;
font-weight: 700;
font-size: 14px;
color: var(--vip-ink);
background: linear-gradient(135deg, #fff7ed, #f59e0b);
}
.vip-phone-cta.free {
background: linear-gradient(135deg, #bbf7d0, #6ee7b7);
color: #062012;
}
.vip-phone-hint {
margin: 10px 0 0;
text-align: center;
font-size: 11px;
color: #78716c;
}
.vip-item-list {
display: flex;
flex-direction: column;
gap: 8px;
}
.vip-item {
display: flex;
align-items: center;
gap: 12px;
padding: 12px 14px;
border-radius: var(--vip-radius-sm);
border: 1px solid var(--line);
background: rgba(0, 0, 0, 0.18);
transition: border-color 0.15s, opacity 0.15s;
}
.vip-item.off {
opacity: 0.55;
}
.vip-item.on {
border-color: var(--vip-amber-line);
}
.vip-item-ico {
width: 40px;
height: 40px;
border-radius: 12px;
display: grid;
place-items: center;
background: rgba(255, 255, 255, 0.05);
font-size: 18px;
flex-shrink: 0;
}
.vip-item-body {
flex: 1;
min-width: 0;
}
.vip-item-body strong {
display: block;
font-size: 14px;
margin-bottom: 2px;
}
.vip-item-body span {
display: block;
font-size: 12px;
color: var(--muted);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.vip-item-tag {
font-size: 11px;
font-weight: 600;
padding: 3px 8px;
border-radius: 999px;
background: rgba(110, 231, 183, 0.12);
color: var(--vip-ok);
flex-shrink: 0;
}
.vip-actions {
display: flex;
flex-wrap: wrap;
gap: 10px;
margin-top: 14px;
align-items: center;
}
.vip-btn {
border: none;
border-radius: 12px;
padding: 11px 16px;
min-height: 44px;
font: inherit;
font-size: 13px;
font-weight: 700;
cursor: pointer;
background: linear-gradient(135deg, #d97706, #f59e0b);
color: var(--vip-ink);
box-shadow: 0 8px 20px rgba(245, 158, 11, 0.2);
transition: transform 0.12s, filter 0.12s;
}
.vip-btn:hover:not(:disabled) {
filter: brightness(1.05);
transform: translateY(-1px);
}
.vip-btn:disabled {
opacity: 0.55;
cursor: wait;
}
.vip-btn-ghost {
border: 1px solid var(--line);
background: rgba(255, 255, 255, 0.03);
color: var(--muted);
border-radius: 12px;
padding: 11px 16px;
min-height: 44px;
font: inherit;
font-size: 13px;
font-weight: 600;
cursor: pointer;
}
.vip-btn-ghost:hover:not(:disabled) {
color: var(--text);
border-color: rgba(255, 255, 255, 0.16);
}
.vip-dirty {
color: var(--vip-amber-2);
font-size: 12px;
font-weight: 600;
}
.vip-meta {
margin: 16px 0 0;
color: var(--muted);
font-size: 12px;
}
.vip-free-banner {
margin-top: 14px;
padding: 12px 14px;
border-radius: 12px;
border: 1px solid rgba(110, 231, 183, 0.25);
background: rgba(110, 231, 183, 0.08);
color: var(--vip-ok);
font-size: 13px;
}
.vip-skeleton {
padding: 48px 20px;
text-align: center;
color: var(--muted);
}
@media (max-width: 900px) {
.vip-layout {
grid-template-columns: 1fr;
}
.vip-phone {
position: static;
}
.vip-tabs {
width: 100%;
}
}

View File

@ -1,8 +1,66 @@
import { Link } from 'react-router-dom'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { api } from '../api'
import './BookEdit.css'
import './Vip.css'
type JoinAction = 'popup' | 'vip'
type TabKey = 'pay' | 'switches' | 'landing' | 'content'
type VipTopic = {
id: string
icon: string
title: string
desc: string
href: string
enabled: boolean
locked?: boolean
sort?: number
}
type VipVideo = {
id: string
icon: string
title: string
desc: string
href: string
enabled: boolean
sort?: number
}
type VipEbook = {
id: string
title: string
desc: string
ebookId: string
free: boolean
enabled: boolean
sort?: number
}
type VipContent = {
heroEyebrow: string
heroTitleAccent: string
heroTitleRest: string
heroLead: string
showStats: boolean
showTopics: boolean
showVideos: boolean
showEbooks: boolean
showCompare: boolean
showFaq: boolean
showCta: boolean
reviewMode: boolean
topics: VipTopic[]
videos: VipVideo[]
ebooks: VipEbook[]
compareTitle: string
compareDesc: string
faqTitle: string
faqSub: string
ctaChips: string[]
ctaSecondary: string
}
type VipCfg = {
ok?: boolean
@ -14,6 +72,7 @@ type VipCfg = {
vipCta: string
vipOfferKey?: string
is_free?: boolean
vipContent?: VipContent
updatedAt?: string
version?: number
}
@ -30,6 +89,30 @@ type ProductOffer = {
remark?: string
}
const emptyContent: VipContent = {
heroEyebrow: 'nomadro',
heroTitleAccent: '全模块解锁',
heroTitleRest: '持续更新 · 抱团出海',
heroLead: '一次付费,解锁电子书、视频教程、知识社群、即时问答,每周更新',
showStats: true,
showTopics: true,
showVideos: true,
showEbooks: true,
showCompare: true,
showFaq: true,
showCta: true,
reviewMode: false,
topics: [],
videos: [],
ebooks: [],
compareTitle: '单品 vs 会员',
compareDesc: '一次付费,全部解锁',
faqTitle: '常见问题',
faqSub: '购买前可快速了解会员权益与流程',
ctaChips: ['阶梯定价', '数字交付', '持续更新', '不支持退款'],
ctaSecondary: '已有账号',
}
const empty: VipCfg = {
vipEnabled: false,
gameEnabled: false,
@ -39,6 +122,77 @@ const empty: VipCfg = {
vipCta: '立即加入 · ¥298',
vipOfferKey: 'tiktok',
is_free: false,
vipContent: emptyContent,
}
const SECTION_TOGGLES = [
['showStats', '数据条'],
['showTopics', '模块入口'],
['showVideos', '视频教程'],
['showEbooks', '电子书'],
['showCompare', '单品对比'],
['showFaq', 'FAQ'],
['showCta', '底部 CTA'],
] as const
const TABS: { key: TabKey; label: string }[] = [
{ key: 'pay', label: '付费方案' },
{ key: 'switches', label: '入口开关' },
{ key: 'landing', label: '落地页' },
{ key: 'content', label: '正式内容' },
]
const CONTENT_HUB = [
{
to: '/wechat/vip/ebooks',
ico: '📖',
title: '电子书',
desc: '章节 Markdown — VIP 正式正文',
primary: true,
},
{
to: '/wechat/vip/course',
ico: '🎬',
title: '视频课程',
desc: '课时视频 URL 与配套文档',
},
{
to: '/wechat/memo',
ico: '👥',
title: '知识社群',
desc: '动态帖子、置顶与星球设置',
},
{
to: '/wechat/shop',
ico: '🛒',
title: '设备商城',
desc: '商品、卡密、订单发货',
},
{
to: '/wechat/books/default',
ico: '📕',
title: '微信小册',
desc: '试读 % 与章节(非 VIP 电子书)',
},
] as const
function fromContent(raw: Partial<VipContent> | undefined): VipContent {
const c = { ...emptyContent, ...(raw || {}) }
return {
...c,
showStats: c.showStats !== false,
showTopics: c.showTopics !== false,
showVideos: c.showVideos !== false,
showEbooks: c.showEbooks !== false,
showCompare: c.showCompare !== false,
showFaq: c.showFaq !== false,
showCta: c.showCta !== false,
reviewMode: !!c.reviewMode,
topics: Array.isArray(c.topics) ? c.topics : [],
videos: Array.isArray(c.videos) ? c.videos : [],
ebooks: Array.isArray(c.ebooks) ? c.ebooks : [],
ctaChips: Array.isArray(c.ctaChips) ? c.ctaChips : emptyContent.ctaChips,
}
}
function fromApi(data: VipCfg): VipCfg {
@ -51,12 +205,40 @@ function fromApi(data: VipCfg): VipCfg {
vipCta: String(data.vipCta || '立即加入'),
vipOfferKey: String(data.vipOfferKey || ''),
is_free: !!data.is_free,
vipContent: fromContent(data.vipContent),
updatedAt: data.updatedAt,
version: data.version,
}
}
/** 微信小程序 · VIP / 加群行为 / 3D 入口 + 动态付费方案(对齐小册「阅读与付费控制」) */
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>
)
}
/** 微信小程序 · VIP / 加群 / 落地页运营(只写微信 · 不改抖音 · 不改订单) */
export default function Vip() {
const [cfg, setCfg] = useState<VipCfg | null>(null)
const [draft, setDraft] = useState<VipCfg>(empty)
@ -64,6 +246,7 @@ export default function Vip() {
const [err, setErr] = useState('')
const [msg, setMsg] = useState('')
const [busy, setBusy] = useState(false)
const [tab, setTab] = useState<TabKey>('pay')
const load = useCallback(async () => {
setErr('')
@ -82,6 +265,18 @@ export default function Vip() {
}, [load])
const isFree = !!draft.is_free || (draft.vipPriceFen <= 0 && !draft.vipProductId)
const content = draft.vipContent || emptyContent
const savedContent = cfg?.vipContent || emptyContent
const copyDirty = useMemo(() => {
return (
content.heroTitleAccent !== savedContent.heroTitleAccent ||
content.heroTitleRest !== savedContent.heroTitleRest ||
content.heroLead !== savedContent.heroLead ||
content.heroEyebrow !== savedContent.heroEyebrow
)
}, [content, savedContent])
const activeOfferKey = useMemo(() => {
if (draft.vipOfferKey) return draft.vipOfferKey
const hit = offers.find(
@ -97,19 +292,26 @@ export default function Vip() {
setMsg('')
setErr('')
const next = { ...draft, ...patch }
if (patch.vipContent) {
next.vipContent = fromContent({ ...content, ...patch.vipContent })
}
setDraft(next)
try {
const body: Record<string, unknown> = {
vipEnabled: next.vipEnabled,
gameEnabled: next.gameEnabled,
joinGroupAction: next.joinGroupAction,
vipPriceFen: next.vipPriceFen,
vipProductId: next.vipProductId,
vipCta: next.vipCta,
vipOfferKey: next.vipOfferKey,
}
if (patch.vipContent) {
body.vipContent = next.vipContent
}
const data = await api<VipCfg>('/api/admin/vip', {
method: 'PUT',
body: JSON.stringify({
vipEnabled: next.vipEnabled,
gameEnabled: next.gameEnabled,
joinGroupAction: next.joinGroupAction,
vipPriceFen: next.vipPriceFen,
vipProductId: next.vipProductId,
vipCta: next.vipCta,
vipOfferKey: next.vipOfferKey,
}),
body: JSON.stringify(body),
})
const saved = fromApi(data)
setCfg(saved)
@ -123,6 +325,32 @@ export default function Vip() {
}
}
function patchContent(partial: Partial<VipContent>, okHint: string) {
void save({ vipContent: { ...content, ...partial } }, okHint)
}
function updateContentLocal(partial: Partial<VipContent>) {
setDraft({
...draft,
vipContent: { ...content, ...partial },
})
}
function toggleTopic(id: string, enabled: boolean) {
const topics = content.topics.map((t) => (t.id === id ? { ...t, enabled } : t))
patchContent({ topics }, enabled ? `模块「${id}」已显示` : `模块「${id}」已隐藏`)
}
function toggleVideo(id: string, enabled: boolean) {
const videos = content.videos.map((t) => (t.id === id ? { ...t, enabled } : t))
patchContent({ videos }, enabled ? `视频「${id}」已显示` : `视频「${id}」已隐藏`)
}
function toggleEbook(id: string, enabled: boolean) {
const ebooks = content.ebooks.map((t) => (t.id === id ? { ...t, enabled } : t))
patchContent({ ebooks }, enabled ? `电子书「${id}」已显示` : `电子书「${id}」已隐藏`)
}
async function applyOffer(offerKey: string) {
setBusy(true)
setMsg('')
@ -149,163 +377,472 @@ export default function Vip() {
}
if (!cfg && !err) {
return <div className="page">加载 VIP 配置…</div>
return <div className="page vip-page vip-skeleton">加载 VIP 配置…</div>
}
const vipJumpOn = draft.joinGroupAction === 'vip'
const visibleSections = SECTION_TOGGLES.filter(([k]) => content[k]).length
return (
<div className="page">
<div className="wx-page page vip-page">
<header className="page-head">
<div>
<h1>VIP</h1>
<div className="vip-eyebrow">WeChat · VIP · Remote</div>
<h1>VIP 运营</h1>
<p>
默认全关。付费方案与小册相同(免费 / 已发布道具);改完写远程配置并升 version,小程序约 3
秒热更新。
只影响微信小程序 · 不改抖音 · 不改订单。付费与落地页写远程配置,小程序约 3 秒热更新。
</p>
<div className="vip-chips">
<span className={`vip-chip ${draft.vipEnabled ? 'on' : ''}`}>
{draft.vipEnabled ? '会员入口开' : '会员入口关'}
</span>
<span className={`vip-chip ${isFree ? 'ok' : 'on'}`}>
{isFree ? '免费模式' : `¥${(draft.vipPriceFen / 100).toFixed(0)}`}
</span>
<span className={`vip-chip ${content.reviewMode ? 'warn' : ''}`}>
{content.reviewMode ? '审核模式' : '正式模式'}
</span>
<span className="vip-chip">
区块 {visibleSections}/{SECTION_TOGGLES.length}
</span>
{cfg?.version != null ? <span className="vip-chip">v{cfg.version}</span> : null}
</div>
</div>
</header>
{err ? (
<p className="badge bad" style={{ display: 'inline-block', marginBottom: 12 }}>
{err}
</p>
<div className="vip-toast err">
<span>{err}</span>
<button type="button" onClick={() => setErr('')} aria-label="关闭">
×
</button>
</div>
) : null}
{msg ? (
<p className="badge ok" style={{ display: 'inline-block', marginBottom: 12 }}>
{msg}
</p>
<div className="vip-toast ok">
<span>{msg}</span>
<button type="button" onClick={() => setMsg('')} aria-label="关闭">
×
</button>
</div>
) : null}
<section className="panel monetize-panel" style={{ marginBottom: 16 }}>
<div className="monetize-head">
<div>
<h2 className="monetize-title">立即加入 · 付费控制</h2>
<p className="hint">
一键切换免费 / 已发布道具。切换后小程序「立即加入」按钮文案与价格立即跟随(已打开会员页约
3s 热更新;否则重新进入即可)。
</p>
</div>
<div className="live-preview">
<span className="live-preview-label">小程序按钮预览</span>
<div className={`live-btn ${isFree ? 'free' : ''}`}>{draft.vipCta || '立即加入'}</div>
<span className="live-preview-sub">
{isFree
? '免费模式 · 不拉起虚拟支付'
: `道具 ${draft.vipProductId || '-'} · ¥${(draft.vipPriceFen / 100).toFixed(0)}`}
</span>
</div>
</div>
<div className="vip-tabs" role="tablist">
{TABS.map((t) => (
<button
key={t.key}
type="button"
role="tab"
aria-selected={tab === t.key}
className={`vip-tab${tab === t.key ? ' active' : ''}`}
onClick={() => setTab(t.key)}
>
{t.label}
</button>
))}
</div>
<div className="offer-grid offer-grid-6">
{offers.map((o) => {
const active = o.key === activeOfferKey
const img = o.image ? `/${o.image.replace(/^\/+/, '')}` : ''
return (
<button
key={o.key}
type="button"
className={`offer-card ${active ? 'active' : ''} ${o.free ? 'is-free' : ''}`}
disabled={busy}
onClick={() => void applyOffer(o.key)}
>
{o.free ? (
<div className="offer-free-badge">FREE</div>
) : img ? (
<img className="offer-img" src={img} alt={o.label} />
) : (
<div className="offer-free-badge">{o.product_id.slice(0, 6)}</div>
)}
<strong>{o.label}</strong>
<span className="offer-id">{o.free ? '免费加入' : o.product_id}</span>
<em>{o.price_yuan}</em>
{o.remark && !o.remark.includes('unlock_percent') ? (
<i className="offer-remark">{o.remark}</i>
) : o.free ? (
<i className="offer-remark">不拉起支付 · 内容全开</i>
) : null}
{active ? <b className="offer-on">使用中</b> : null}
</button>
)
})}
</div>
{!isFree ? (
<div className="unlock-hero monetize-unlock">
<div className="price-box mono-box" style={{ width: '100%' }}>
<div>
<label>道具 ID</label>
<code>{draft.vipProductId || '—'}</code>
</div>
<div>
<label>价格</label>
<code>
¥{(draft.vipPriceFen / 100).toFixed(0)}({draft.vipPriceFen} 分)
</code>
</div>
<div>
<label>CTA</label>
<code>{draft.vipCta}</code>
</div>
{tab === 'pay' ? (
<section className="vip-card">
<div className="vip-card-head">
<div>
<h2>立即加入 · 付费控制</h2>
<p>
一键切换免费 / 已发布道具。切换后小程序按钮文案与价格立即跟随(已打开会员页约 3s
热更新)。
</p>
</div>
<div className="vip-preview-btn">
<span>小程序按钮预览</span>
<strong className={isFree ? 'free' : ''}>{draft.vipCta || '立即加入'}</strong>
<em>
{isFree
? '免费模式 · 不拉起虚拟支付'
: `道具 ${draft.vipProductId || '-'} · ¥${(draft.vipPriceFen / 100).toFixed(0)}`}
</em>
</div>
</div>
) : (
<div className="free-banner">当前为免费会员:小程序不拉起支付,「立即加入」显示「免费加入」。</div>
)}
</section>
<section className="panel" style={{ marginBottom: 16 }}>
<h2>开关(默认关闭)</h2>
<div className="vip-row">
<div>
<strong>VIP 会员入口</strong>
<p className="vip-hint">关闭后会员页闸门拦截</p>
</div>
<button
type="button"
className={draft.vipEnabled ? 'primary-link' : 'ghost-btn'}
disabled={busy}
onClick={() =>
void save({ vipEnabled: !draft.vipEnabled }, draft.vipEnabled ? 'VIP 已关闭' : 'VIP 已开启')
}
>
{draft.vipEnabled ? '已开启' : '已关闭'}
</button>
</div>
<div className="vip-row">
<div>
<strong>加群 → 跳转 VIP</strong>
<p className="vip-hint">关闭=社群「加群」弹窗引导;开启=跳转会员页</p>
</div>
<button
type="button"
className={vipJumpOn ? 'primary-link' : 'ghost-btn'}
disabled={busy}
onClick={() =>
void save(
{ joinGroupAction: vipJumpOn ? 'popup' : 'vip' },
vipJumpOn ? '加群跳 VIP 已关闭(弹窗)' : '加群跳 VIP 已开启',
<div className="offer-grid offer-grid-6">
{offers.map((o) => {
const active = o.key === activeOfferKey
const img = o.image ? `/${o.image.replace(/^\/+/, '')}` : ''
return (
<button
key={o.key}
type="button"
className={`offer-card ${active ? 'active' : ''} ${o.free ? 'is-free' : ''}`}
disabled={busy}
onClick={() => void applyOffer(o.key)}
>
{o.free ? (
<div className="offer-free-badge">FREE</div>
) : img ? (
<img className="offer-img" src={img} alt={o.label} />
) : (
<div className="offer-free-badge">{o.product_id.slice(0, 6)}</div>
)}
<strong>{o.label}</strong>
<span className="offer-id">{o.free ? '免费加入' : o.product_id}</span>
<em>{o.price_yuan}</em>
{o.remark && !o.remark.includes('unlock_percent') ? (
<i className="offer-remark">{o.remark}</i>
) : o.free ? (
<i className="offer-remark">不拉起支付 · 内容全开</i>
) : null}
{active ? <b className="offer-on">使用中</b> : null}
</button>
)
}
>
{vipJumpOn ? '已开启' : '已关闭'}
</button>
</div>
<div className="vip-row">
<div>
<strong>数字游民 · 游戏入口</strong>
<p className="vip-hint">已冻结隐藏,首页不展示;请勿开启</p>
})}
</div>
<button type="button" className="ghost-btn" disabled>
已冻结
</button>
</div>
{cfg?.updatedAt ? (
<p className="vip-hint" style={{ marginTop: 16 }}>
最近更新 · v{cfg.version ?? '—'} · {cfg.updatedAt}
</p>
) : null}
</section>
{!isFree ? (
<div className="unlock-hero monetize-unlock">
<div className="price-box mono-box" style={{ width: '100%' }}>
<div>
<label>道具 ID</label>
<code>{draft.vipProductId || '—'}</code>
</div>
<div>
<label>价格</label>
<code>
¥{(draft.vipPriceFen / 100).toFixed(0)}({draft.vipPriceFen} 分)
</code>
</div>
<div>
<label>CTA</label>
<code>{draft.vipCta}</code>
</div>
</div>
</div>
) : (
<div className="vip-free-banner">
当前为免费会员:小程序不拉起支付,「立即加入」显示「免费加入」。
</div>
)}
</section>
) : null}
{tab === 'switches' ? (
<section className="vip-card">
<div className="vip-card-head">
<div>
<h2>入口与行为开关</h2>
<p>默认关闭项保持安全;游戏入口已冻结,请勿开启。</p>
</div>
</div>
<div className="vip-row">
<div>
<strong>VIP 会员入口</strong>
<p className="vip-hint">关闭后会员页闸门拦截</p>
</div>
<Switch
checked={draft.vipEnabled}
disabled={busy}
label="VIP 会员入口"
onChange={(v) => void save({ vipEnabled: v }, v ? 'VIP 已开启' : 'VIP 已关闭')}
/>
</div>
<div className="vip-row">
<div>
<strong>加群 → 跳转 VIP</strong>
<p className="vip-hint">关闭=社群「加群」弹窗引导;开启=跳转会员页</p>
</div>
<Switch
checked={vipJumpOn}
disabled={busy}
label="加群跳转 VIP"
onChange={(v) =>
void save(
{ joinGroupAction: v ? 'vip' : 'popup' },
v ? '加群跳 VIP 已开启' : '加群跳 VIP 已关闭(弹窗)',
)
}
/>
</div>
<div className="vip-row">
<div>
<strong>数字游民 · 游戏入口</strong>
<p className="vip-hint">已冻结隐藏,首页不展示</p>
</div>
<button type="button" className="vip-btn-ghost" disabled>
已冻结
</button>
</div>
<div className="vip-row">
<div>
<strong>审核模式 reviewMode</strong>
<p className="vip-hint">开启后隐藏限时特惠等付费敏感强调(默认关)</p>
</div>
<Switch
checked={content.reviewMode}
disabled={busy}
label="审核模式"
onChange={(v) =>
patchContent({ reviewMode: v }, v ? '审核模式已开' : '审核模式已关')
}
/>
</div>
</section>
) : null}
{tab === 'content' ? (
<section className="vip-card">
<div className="vip-card-head">
<div>
<h2>正式内容枢纽</h2>
<p>
落地页只是入口卡片;正文在内容库。电子书章节与视频课在「VIP 内容」编辑,社群 /
商城走既有后台。
</p>
</div>
</div>
<div className="vip-item-list">
{CONTENT_HUB.map((item) => (
<Link
key={item.to}
to={item.to}
className={`vip-item${'primary' in item && item.primary ? ' on' : ''}`}
style={{ textDecoration: 'none' }}
>
<div className="vip-item-ico">{item.ico}</div>
<div className="vip-item-body">
<strong>{item.title}</strong>
<span>{item.desc}</span>
</div>
<span className="vip-item-tag">打开 →</span>
</Link>
))}
</div>
</section>
) : null}
{tab === 'landing' ? (
<>
<section className="vip-card">
<div className="vip-card-head">
<div>
<h2>落地页 · platforms.weapp</h2>
<p>
区块与文案只写微信;未保存过时小程序用包内默认(与现网一致)。左侧编辑,右侧即时预览。
</p>
</div>
</div>
<h3 style={{ margin: '0 0 10px', fontSize: 14, color: 'var(--muted)' }}>区块显隐</h3>
<div className="vip-section-grid">
{SECTION_TOGGLES.map(([key, label]) => (
<div
key={key}
className={`vip-section-tile${content[key] ? ' on' : ''}`}
>
<span>{label}</span>
<Switch
checked={content[key]}
disabled={busy}
label={label}
onChange={(v) =>
patchContent({ [key]: v }, `${label}已${v ? '显示' : '隐藏'}`)
}
/>
</div>
))}
</div>
</section>
<section className="vip-card">
<div className="vip-layout">
<div>
<h3 style={{ margin: '0 0 14px', fontSize: 16 }}>主视觉文案</h3>
<div className="vip-fields">
<div className="vip-field">
<label>眉标 eyebrow</label>
<input
value={content.heroEyebrow}
disabled={busy}
onChange={(e) => updateContentLocal({ heroEyebrow: e.target.value })}
/>
</div>
<div className="vip-field">
<label>主标题(强调色)</label>
<input
value={content.heroTitleAccent}
disabled={busy}
onChange={(e) => updateContentLocal({ heroTitleAccent: e.target.value })}
/>
</div>
<div className="vip-field">
<label>主标题(其余)</label>
<input
value={content.heroTitleRest}
disabled={busy}
onChange={(e) => updateContentLocal({ heroTitleRest: e.target.value })}
/>
</div>
<div className="vip-field">
<label>副文案</label>
<textarea
value={content.heroLead}
disabled={busy}
onChange={(e) => updateContentLocal({ heroLead: e.target.value })}
/>
</div>
</div>
<div className="vip-actions">
<button
type="button"
className="vip-btn"
disabled={busy || !copyDirty}
onClick={() =>
patchContent(
{
heroEyebrow: content.heroEyebrow,
heroTitleAccent: content.heroTitleAccent,
heroTitleRest: content.heroTitleRest,
heroLead: content.heroLead,
},
'落地页文案已保存',
)
}
>
{busy ? '保存中…' : '保存文案'}
</button>
{copyDirty ? (
<span className="vip-dirty">有未保存修改</span>
) : (
<button
type="button"
className="vip-btn-ghost"
disabled={busy}
onClick={() =>
setDraft({
...draft,
vipContent: fromContent(cfg?.vipContent),
})
}
>
重置
</button>
)}
</div>
</div>
<aside className="vip-phone" aria-label="落地页预览">
<div className="vip-phone-bar" />
<div className="vip-phone-eyebrow">{content.heroEyebrow || 'nomadro'}</div>
<p className="vip-phone-title">
<b>{content.heroTitleAccent || '全模块解锁'}</b>
<br />
{content.heroTitleRest || '持续更新 · 抱团出海'}
</p>
<p className="vip-phone-lead">{content.heroLead}</p>
<div className="vip-phone-blocks">
{SECTION_TOGGLES.map(([key, label]) => (
<i key={key} className={content[key] ? '' : 'off'}>
{label}
</i>
))}
</div>
{content.showCta ? (
<>
<div className={`vip-phone-cta${isFree ? ' free' : ''}`}>
🔒 {draft.vipCta || '立即加入'}
</div>
<p className="vip-phone-hint">
{content.reviewMode ? '审核模式 · 已藏促销强调' : '微信小程序虚拟支付'}
</p>
</>
) : (
<p className="vip-phone-hint">底部 CTA 已隐藏</p>
)}
</aside>
</div>
</section>
<section className="vip-card">
<h3 style={{ margin: '0 0 12px', fontSize: 16 }}>模块入口</h3>
<div className="vip-item-list">
{content.topics.map((t) => {
const on = t.enabled !== false
return (
<div key={t.id} className={`vip-item${on ? ' on' : ' off'}`}>
<div className="vip-item-ico">{t.icon || '◆'}</div>
<div className="vip-item-body">
<strong>{t.title}</strong>
<span>{t.desc}</span>
</div>
{t.locked ? <span className="vip-item-tag">需 VIP</span> : null}
<Switch
checked={on}
disabled={busy}
label={t.title}
onChange={(v) => toggleTopic(t.id, v)}
/>
</div>
)
})}
</div>
<h3 style={{ margin: '22px 0 12px', fontSize: 16 }}>视频教程</h3>
<div className="vip-item-list">
{content.videos.map((t) => {
const on = t.enabled !== false
return (
<div key={t.id} className={`vip-item${on ? ' on' : ' off'}`}>
<div className="vip-item-ico">{t.icon || '▶'}</div>
<div className="vip-item-body">
<strong>{t.title}</strong>
<span>{t.desc}</span>
</div>
<Switch
checked={on}
disabled={busy}
label={t.title}
onChange={(v) => toggleVideo(t.id, v)}
/>
</div>
)
})}
</div>
<h3 style={{ margin: '22px 0 12px', fontSize: 16 }}>电子书</h3>
<div className="vip-item-list">
{content.ebooks.map((t) => {
const on = t.enabled !== false
return (
<div key={t.id} className={`vip-item${on ? ' on' : ' off'}`}>
<div className="vip-item-ico">📖</div>
<div className="vip-item-body">
<strong>《{t.title}》</strong>
<span>
{t.desc}
{t.free ? ' · 免费' : ''}
</span>
</div>
{t.free ? <span className="vip-item-tag">免费</span> : null}
<Switch
checked={on}
disabled={busy}
label={t.title}
onChange={(v) => toggleEbook(t.id, v)}
/>
</div>
)
})}
</div>
{cfg?.updatedAt ? (
<p className="vip-meta">
最近更新 · v{cfg.version ?? '—'} · {cfg.updatedAt}
</p>
) : null}
</section>
</>
) : null}
</div>
)
}

View File

@ -0,0 +1,632 @@
import { Link, useLocation, useNavigate } from 'react-router-dom'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { api } from '../api'
import './Vip.css'
type Ebook = {
id: string
title: string
free: boolean
estimatedMinutes?: number
headers: string[]
sections: string[]
markdown?: string
}
type Lesson = {
key: string
moduleIndex: number
lessonIndex: number
name: string
duration: string
videoUrl: string
}
type Module = {
emoji: string
title: string
lessons: Lesson[]
}
type Course = {
id: string
title: string
modules: Module[]
}
type LessonDoc = {
markdown: string
videoUrl: string
}
type Library = {
version?: number
updatedAt?: string
ebooks: Record<string, Ebook>
course: Course
lessons: Record<string, LessonDoc>
meta?: {
ebookChapters?: Record<string, number>
courseModules?: number
courseLessons?: number
hasFile?: boolean
}
}
type Tab = 'ebooks' | 'course'
const BOOK_IDS = ['nomad', 'cloudphone'] as const
export default function VipLibrary() {
const { pathname } = useLocation()
const navigate = useNavigate()
const tab: Tab = pathname.includes('/vip/course') ? 'course' : 'ebooks'
const [lib, setLib] = useState<Library | null>(null)
const [bookId, setBookId] = useState<(typeof BOOK_IDS)[number]>('nomad')
const [chapterIdx, setChapterIdx] = useState(0)
const [draftTitle, setDraftTitle] = useState('')
const [draftHeaders, setDraftHeaders] = useState<string[]>([])
const [draftSections, setDraftSections] = useState<string[]>([])
const [draftFree, setDraftFree] = useState(false)
const [course, setCourse] = useState<Course | null>(null)
const [lessonKey, setLessonKey] = useState('')
const [lessonDoc, setLessonDoc] = useState<LessonDoc>({ markdown: '', videoUrl: '' })
const [lessonMeta, setLessonMeta] = useState<Lesson | null>(null)
const [busy, setBusy] = useState(false)
const [err, setErr] = useState('')
const [msg, setMsg] = useState('')
const load = useCallback(async () => {
setErr('')
const data = await api<Library>('/api/admin/vip/library')
setLib(data)
setCourse(data.course)
const firstBook = data.ebooks?.[bookId] || data.ebooks?.nomad
if (firstBook) {
applyBook(firstBook)
}
const firstLesson = data.course?.modules?.[0]?.lessons?.[0]
if (firstLesson) {
selectLesson(firstLesson, data.lessons || {})
}
}, [bookId])
useEffect(() => {
load().catch((e) => setErr(e.message || '加载失败'))
}, [load])
function applyBook(book: Ebook) {
setDraftTitle(book.title || '')
setDraftFree(!!book.free)
setDraftHeaders([...(book.headers || [])])
setDraftSections([...(book.sections || [])])
setChapterIdx(0)
}
function selectLesson(les: Lesson, lessonsMap: Record<string, LessonDoc>) {
setLessonKey(les.key)
setLessonMeta(les)
const doc = lessonsMap[les.key] || { markdown: '', videoUrl: les.videoUrl || '' }
setLessonDoc({
markdown: doc.markdown || '',
videoUrl: doc.videoUrl || les.videoUrl || '',
})
}
const chapterTitle = draftHeaders[chapterIdx] || `章节 ${chapterIdx + 1}`
const chapterBody = draftSections[chapterIdx] || ''
const flatLessons = useMemo(() => {
const out: Lesson[] = []
;(course?.modules || []).forEach((m) => {
;(m.lessons || []).forEach((l) => out.push(l))
})
return out
}, [course])
async function switchBook(id: (typeof BOOK_IDS)[number]) {
setBookId(id)
const book = lib?.ebooks?.[id]
if (book) applyBook(book)
}
async function saveEbook() {
if (!lib) return
setBusy(true)
setMsg('')
setErr('')
try {
const data = await api<{ ebook: Ebook; meta: Library['meta'] }>(
`/api/admin/vip/library/ebooks/${bookId}`,
{
method: 'PUT',
body: JSON.stringify({
title: draftTitle,
free: draftFree,
headers: draftHeaders,
sections: draftSections,
}),
},
)
setLib((prev) =>
prev
? {
...prev,
ebooks: { ...prev.ebooks, [bookId]: data.ebook },
meta: data.meta,
}
: prev,
)
applyBook(data.ebook)
setMsg(`电子书「${data.ebook.title}」已保存 · 小程序热更新`)
} catch (e: any) {
setErr(e.message || '保存失败')
} finally {
setBusy(false)
}
}
async function saveCourseStructure() {
if (!course) return
setBusy(true)
setMsg('')
setErr('')
try {
const data = await api<{ course: Course; meta: Library['meta'] }>(
'/api/admin/vip/library/course',
{
method: 'PUT',
body: JSON.stringify(course),
},
)
setCourse(data.course)
setLib((prev) => (prev ? { ...prev, course: data.course, meta: data.meta } : prev))
setMsg('课程目录已保存')
} catch (e: any) {
setErr(e.message || '保存失败')
} finally {
setBusy(false)
}
}
async function saveLesson() {
if (!lessonKey) return
setBusy(true)
setMsg('')
setErr('')
try {
// sync videoUrl into course lesson row as well
if (course && lessonMeta) {
const nextMods = course.modules.map((m, mi) => ({
...m,
lessons: m.lessons.map((l, li) =>
l.key === lessonKey
? {
...l,
name: lessonMeta.name,
duration: lessonMeta.duration,
videoUrl: lessonDoc.videoUrl,
moduleIndex: mi,
lessonIndex: li,
}
: l,
),
}))
await api('/api/admin/vip/library/course', {
method: 'PUT',
body: JSON.stringify({ ...course, modules: nextMods }),
})
setCourse({ ...course, modules: nextMods })
}
const data = await api<{ lesson: LessonDoc; meta: Library['meta'] }>(
`/api/admin/vip/library/lessons/${encodeURIComponent(lessonKey)}`,
{
method: 'PUT',
body: JSON.stringify(lessonDoc),
},
)
setLessonDoc(data.lesson)
setLib((prev) =>
prev
? {
...prev,
lessons: { ...prev.lessons, [lessonKey]: data.lesson },
meta: data.meta,
}
: prev,
)
setMsg(`课时 ${lessonKey} 已保存(视频 + 文档)`)
} catch (e: any) {
setErr(e.message || '保存失败')
} finally {
setBusy(false)
}
}
function updateChapterTitle(v: string) {
const next = [...draftHeaders]
while (next.length <= chapterIdx) next.push(`章节 ${next.length + 1}`)
next[chapterIdx] = v
setDraftHeaders(next)
}
function updateChapterBody(v: string) {
const next = [...draftSections]
while (next.length <= chapterIdx) next.push('')
next[chapterIdx] = v
setDraftSections(next)
}
function addChapter() {
setDraftHeaders([...draftHeaders, `新章节 ${draftHeaders.length + 1}`])
setDraftSections([...draftSections, '# 新章节\n\n'])
setChapterIdx(draftHeaders.length)
}
function removeChapter() {
if (draftSections.length <= 1) return
const h = draftHeaders.filter((_, i) => i !== chapterIdx)
const s = draftSections.filter((_, i) => i !== chapterIdx)
setDraftHeaders(h)
setDraftSections(s)
setChapterIdx(Math.max(0, chapterIdx - 1))
}
function patchLessonMeta(partial: Partial<Lesson>) {
if (!lessonMeta || !course) return
const next = { ...lessonMeta, ...partial }
setLessonMeta(next)
setCourse({
...course,
modules: course.modules.map((m) => ({
...m,
lessons: m.lessons.map((l) => (l.key === lessonKey ? { ...l, ...partial } : l)),
})),
})
}
if (!lib && !err) {
return <div className="wx-page page vip-page vip-skeleton">加载 VIP 内容库…</div>
}
return (
<div className="wx-page page vip-page">
<header className="page-head">
<div>
<div className="vip-eyebrow">VIP · {tab === 'ebooks' ? '电子书' : '视频课程'}</div>
<h1>{tab === 'ebooks' ? '电子书' : '视频课程'}</h1>
<p>
{tab === 'ebooks'
? '编辑 VIP 电子书章节 Markdown。写入 vip-library.json,小程序优先读远程,失败用包内兜底。'
: '编辑视频课目录、课时视频 URL 与配套文档。写入 vip-library.json,小程序优先读远程,失败用包内兜底。'}
</p>
<div className="vip-chips">
{tab === 'ebooks' ? (
<span className="vip-chip on">
电子书 {Object.keys(lib?.ebooks || {}).length}
</span>
) : (
<span className="vip-chip on">
课时 {lib?.meta?.courseLessons ?? flatLessons.length}
</span>
)}
<span className={`vip-chip ${lib?.meta?.hasFile ? 'ok' : ''}`}>
{lib?.meta?.hasFile ? '已落盘' : '种子未落盘'}
</span>
{lib?.version != null ? <span className="vip-chip">v{lib.version}</span> : null}
</div>
</div>
<div className="vip-actions" style={{ marginTop: 0 }}>
<button
type="button"
className={tab === 'ebooks' ? 'vip-btn' : 'vip-btn-ghost'}
onClick={() => navigate('/wechat/vip/ebooks')}
>
电子书
</button>
<button
type="button"
className={tab === 'course' ? 'vip-btn' : 'vip-btn-ghost'}
onClick={() => navigate('/wechat/vip/course')}
>
视频课程
</button>
<Link className="vip-btn-ghost" to="/wechat/vip">
← 运营配置
</Link>
</div>
</header>
{err ? (
<div className="vip-toast err">
<span>{err}</span>
<button type="button" onClick={() => setErr('')} aria-label="关闭">
×
</button>
</div>
) : null}
{msg ? (
<div className="vip-toast ok">
<span>{msg}</span>
<button type="button" onClick={() => setMsg('')} aria-label="关闭">
×
</button>
</div>
) : null}
{tab === 'ebooks' ? (
<section className="vip-card">
<div className="vip-card-head">
<div>
<h2>电子书 · 章节正文</h2>
<p>改标题、是否免费、各章 Markdown;保存后小程序 vip-ebook 优先读远程。</p>
</div>
<div className="vip-actions" style={{ marginTop: 0 }}>
{BOOK_IDS.map((id) => (
<button
key={id}
type="button"
className={bookId === id ? 'vip-btn' : 'vip-btn-ghost'}
disabled={busy}
onClick={() => void switchBook(id)}
>
{id === 'nomad' ? '数字游民' : '云手机'}
</button>
))}
</div>
</div>
<div className="vip-fields" style={{ marginBottom: 14 }}>
<div className="vip-field">
<label>书名</label>
<input
value={draftTitle}
disabled={busy}
onChange={(e) => setDraftTitle(e.target.value)}
/>
</div>
<div className="vip-row" style={{ border: 'none', padding: '0 0 8px' }}>
<div>
<strong>免费试读</strong>
<p className="vip-hint">开启后无需 VIP 即可阅读全书</p>
</div>
<label className="vip-switch">
<input
type="checkbox"
checked={draftFree}
disabled={busy}
onChange={(e) => setDraftFree(e.target.checked)}
/>
<span className="vip-switch-track">
<span className="vip-switch-thumb" />
</span>
</label>
</div>
</div>
<div className="vip-layout">
<aside className="vip-item-list" style={{ maxHeight: 520, overflow: 'auto' }}>
{draftSections.map((_, i) => (
<button
key={i}
type="button"
className={`vip-item${i === chapterIdx ? ' on' : ''}`}
style={{ width: '100%', textAlign: 'left', cursor: 'pointer', border: undefined }}
onClick={() => setChapterIdx(i)}
>
<div className="vip-item-ico">{i + 1}</div>
<div className="vip-item-body">
<strong>{draftHeaders[i] || `章节 ${i + 1}`}</strong>
<span>{(draftSections[i] || '').slice(0, 48).replace(/\n/g, ' ')}…</span>
</div>
</button>
))}
<div className="vip-actions">
<button type="button" className="vip-btn-ghost" disabled={busy} onClick={addChapter}>
+ 加章节
</button>
<button
type="button"
className="vip-btn-ghost"
disabled={busy || draftSections.length <= 1}
onClick={removeChapter}
>
删本章
</button>
</div>
</aside>
<div>
<div className="vip-fields">
<div className="vip-field">
<label>章节标题(目录)</label>
<input
value={chapterTitle}
disabled={busy}
onChange={(e) => updateChapterTitle(e.target.value)}
/>
</div>
<div className="vip-field">
<label>章节 Markdown</label>
<textarea
style={{ minHeight: 360, fontFamily: 'ui-monospace, monospace', fontSize: 13 }}
value={chapterBody}
disabled={busy}
onChange={(e) => updateChapterBody(e.target.value)}
/>
</div>
</div>
<div className="vip-actions">
<button type="button" className="vip-btn" disabled={busy} onClick={() => void saveEbook()}>
{busy ? '保存中…' : '保存整本书'}
</button>
<span className="vip-dirty">
{draftSections.length} 章 · 当前第 {chapterIdx + 1} 章
</span>
</div>
</div>
</div>
</section>
) : null}
{tab === 'course' ? (
<section className="vip-card">
<div className="vip-card-head">
<div>
<h2>视频课 · 课时正文</h2>
<p>改课时名、时长、视频地址与配套 Markdown;目录结构可一并保存。</p>
</div>
<button
type="button"
className="vip-btn-ghost"
disabled={busy}
onClick={() => void saveCourseStructure()}
>
保存目录结构
</button>
</div>
<div className="vip-field" style={{ marginBottom: 14 }}>
<label>课程标题</label>
<input
value={course?.title || ''}
disabled={busy}
onChange={(e) =>
setCourse((c) => (c ? { ...c, title: e.target.value } : c))
}
/>
</div>
<div className="vip-layout">
<aside className="vip-item-list" style={{ maxHeight: 560, overflow: 'auto' }}>
{(course?.modules || []).map((m) => (
<div key={m.title} style={{ marginBottom: 10 }}>
<div className="vip-field" style={{ marginBottom: 6 }}>
<label>
{m.emoji} 模块名
</label>
<input
value={m.title}
disabled={busy}
onChange={(e) => {
const title = e.target.value
setCourse((c) =>
c
? {
...c,
modules: c.modules.map((x) =>
x === m ? { ...x, title } : x,
),
}
: c,
)
}}
/>
</div>
{m.lessons.map((l) => (
<button
key={l.key}
type="button"
className={`vip-item${l.key === lessonKey ? ' on' : ''}`}
style={{ width: '100%', textAlign: 'left', marginBottom: 6 }}
onClick={() => selectLesson(l, lib?.lessons || {})}
>
<div className="vip-item-ico">▶</div>
<div className="vip-item-body">
<strong>{l.name}</strong>
<span>
{l.duration} · {l.key}
</span>
</div>
</button>
))}
</div>
))}
</aside>
<div>
{lessonMeta ? (
<div className="vip-fields">
<div className="vip-field">
<label>课时标题</label>
<input
value={lessonMeta.name}
disabled={busy}
onChange={(e) => patchLessonMeta({ name: e.target.value })}
/>
</div>
<div className="vip-field">
<label>时长</label>
<input
value={lessonMeta.duration}
disabled={busy}
onChange={(e) => patchLessonMeta({ duration: e.target.value })}
/>
</div>
<div className="vip-field">
<label>视频 URL</label>
<input
value={lessonDoc.videoUrl}
disabled={busy}
onChange={(e) =>
setLessonDoc((d) => ({ ...d, videoUrl: e.target.value }))
}
/>
</div>
<div className="vip-field">
<label>配套文档 Markdown</label>
<textarea
style={{ minHeight: 280, fontFamily: 'ui-monospace, monospace', fontSize: 13 }}
value={lessonDoc.markdown}
disabled={busy}
onChange={(e) =>
setLessonDoc((d) => ({ ...d, markdown: e.target.value }))
}
/>
</div>
<div className="vip-actions">
<button
type="button"
className="vip-btn"
disabled={busy}
onClick={() => void saveLesson()}
>
{busy ? '保存中…' : '保存本课时'}
</button>
<span className="vip-dirty">key · {lessonKey}</span>
</div>
</div>
) : (
<p className="vip-hint">选择左侧课时开始编辑</p>
)}
</div>
</div>
</section>
) : null}
{lib?.updatedAt ? (
<p className="vip-meta">
最近更新 · v{lib.version ?? '—'} · {lib.updatedAt}
</p>
) : null}
<div className="wx-sticky-bar">
<span className="wx-muted">
{tab === 'ebooks' ? `电子书 · ${bookId}` : `视频课 · ${lessonKey || '未选课时'}`}
</span>
<button
type="button"
className="wx-btn"
disabled={busy}
onClick={() => {
if (tab === 'ebooks') void saveEbook()
else if (lessonKey) void saveLesson()
else void saveCourseStructure()
}}
>
{busy ? '保存中…' : tab === 'ebooks' ? '保存整本书' : lessonKey ? '保存本课时' : '保存目录'}
</button>
</div>
</div>
)
}

View File

@ -3,15 +3,23 @@ import { api } from '../../api'
type Mod = { enabled: boolean; title: string; tabLabel?: string; note?: string }
type HomeVariant = 'bmi' | 'hub'
type TtJoin = {
joinGroupWechat: boolean
joinGroupDouyin: boolean
socialFollowAuto: boolean
wechatOaName: string
joinGroupDouyinHint: string
joinGroupDouyinQr: string
}
type TtCfg = {
homeVariant?: HomeVariant
modules: { nav: Mod; book: Mod; community: Mod }
bookContent: Record<string, unknown>
join?: Partial<TtJoin>
}
type JoinChannel = 'wechat' | 'douyin'
type JoinCfg = {
ok?: boolean
flags: {
joinGroupWechat: boolean
joinGroupDouyin: boolean
@ -22,7 +30,42 @@ type JoinCfg = {
joinGroupDouyinQr: string
wechatOaName: string
}
updatedAt?: string
}
const DEFAULT_JOIN: TtJoin = {
joinGroupWechat: true,
joinGroupDouyin: false,
socialFollowAuto: false,
wechatOaName: '异度世界',
joinGroupDouyinHint: '打开抖音搜群「数字游民」或扫码进群',
joinGroupDouyinQr: '',
}
function joinFromTt(cfg: TtCfg | null | undefined): JoinCfg {
const j = { ...DEFAULT_JOIN, ...(cfg?.join || {}) }
return {
flags: {
joinGroupWechat: !!j.joinGroupWechat,
joinGroupDouyin: !!j.joinGroupDouyin,
socialFollowAuto: !!j.socialFollowAuto,
},
copy: {
wechatOaName: String(j.wechatOaName || DEFAULT_JOIN.wechatOaName),
joinGroupDouyinHint: String(j.joinGroupDouyinHint || DEFAULT_JOIN.joinGroupDouyinHint),
joinGroupDouyinQr: String(j.joinGroupDouyinQr || ''),
},
}
}
function ttJoinPatch(next: JoinCfg): TtJoin {
return {
joinGroupWechat: !!next.flags.joinGroupWechat,
joinGroupDouyin: !!next.flags.joinGroupDouyin,
socialFollowAuto: !!next.flags.socialFollowAuto,
wechatOaName: String(next.copy.wechatOaName || DEFAULT_JOIN.wechatOaName),
joinGroupDouyinHint: String(next.copy.joinGroupDouyinHint || DEFAULT_JOIN.joinGroupDouyinHint),
joinGroupDouyinQr: String(next.copy.joinGroupDouyinQr || ''),
}
}
const KEYS = [
@ -107,18 +150,14 @@ export default function DouyinModules() {
const loadModules = useCallback(async () => {
const data = await api<{ config: TtCfg }>('/api/admin/douyin/config')
setCfg(normalize(data.config))
}, [])
const loadJoin = useCallback(async () => {
const data = await api<JoinCfg>('/api/admin/join-group')
setJoin(data)
const next = normalize(data.config)
setCfg(next)
setJoin(joinFromTt(next))
}, [])
useEffect(() => {
Promise.all([loadModules(), loadJoin()])
.catch((e) => setErr(e instanceof Error ? e.message : '加载失败'))
}, [loadModules, loadJoin])
loadModules().catch((e) => setErr(e instanceof Error ? e.message : '加载失败'))
}, [loadModules])
useEffect(() => {
if (!cfg || !join) return
@ -204,15 +243,17 @@ export default function DouyinModules() {
setJoinErr('')
setJoin(next)
try {
const data = await api<JoinCfg>('/api/admin/join-group', {
const data = await api<{ config: TtCfg }>('/api/admin/douyin/config', {
method: 'PUT',
body: JSON.stringify({ flags: next.flags, copy: next.copy }),
body: JSON.stringify({ join: ttJoinPatch(next) }),
})
setJoin(data)
const saved = normalize(data.config)
setCfg(saved)
setJoin(joinFromTt(saved))
setJoinMsg(okHint)
} catch (e: any) {
setJoinErr(e.message || '加群配置保存失败')
await loadJoin().catch(() => undefined)
await loadModules().catch(() => undefined)
} finally {
setJoinBusy(false)
}
@ -257,7 +298,7 @@ export default function DouyinModules() {
<div className="dy-eyebrow">Home · Entries · Join</div>
<h1>首页 · 入口 · 加群</h1>
<p>
首页 A/B、门户入口与加群弹窗同页配置。切换即写后端;小程序约 3 秒轮询生效。
只写 platforms.tt(与微信后台隔离)。加群渠道切换即生效;小程序约 3 秒轮询。
</p>
</div>
</header>
@ -406,7 +447,7 @@ export default function DouyinModules() {
<div>
<h2>加群弹窗</h2>
<p className="dy-muted" style={{ margin: '4px 0 0' }}>
用户点「加群」时弹出。点选渠道即生效,用户端无感知开关。
仅抖音端 platforms.tt.join。点选渠道即写入,不改微信 VIP / 顶层 flags。
</p>
</div>
{join ? (

View File

@ -1,5 +1,4 @@
/* Douyin 控制台 — 黑底 + 抖音粉/青,区别微信翠绿后台 */
@import url('https://fonts.googleapis.com/css2?family=Sora:wght@500;600;700;800&family=IBM+Plex+Sans:wght@400;500;600&family=IBM+Plex+Mono:wght@400;500&display=swap');
.dy-shell {
--dy-bg: #050507;
@ -19,9 +18,9 @@
--dy-radius: 16px;
--dy-radius-sm: 12px;
--dy-shadow: 0 12px 40px rgba(0, 0, 0, 0.4);
--dy-font: 'Sora', system-ui, sans-serif;
--dy-body: 'IBM Plex Sans', system-ui, sans-serif;
--dy-mono: 'IBM Plex Mono', ui-monospace, monospace;
--dy-font: system-ui, -apple-system, 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
--dy-body: system-ui, -apple-system, 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
--dy-mono: ui-monospace, Consolas, 'Courier New', monospace;
--dy-side-w: 250px;
min-height: 100vh;

File diff suppressed because it is too large Load Diff

View File

@ -7,8 +7,8 @@
--accent: #5ec478;
--accent-2: #d7b35a;
--danger: #e07060;
--font-display: 'Syne', sans-serif;
--font-body: 'IBM Plex Sans', sans-serif;
--font-display: system-ui, -apple-system, 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
--font-body: system-ui, -apple-system, 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
}
* { box-sizing: border-box; }

File diff suppressed because one or more lines are too long

View File

@ -26,6 +26,8 @@ from ebook_svc.routers import (
shop_admin,
track,
vip_admin,
vip_library_admin,
vip_library_public,
)
scheduler = AsyncIOScheduler()
@ -68,6 +70,9 @@ app.include_router(douyin_admin.router)
app.include_router(join_group_admin.router)
# 微信 VIP / 加群行为 / 3D 入口
app.include_router(vip_admin.router)
# VIP 正式内容(电子书 / 视频课)
app.include_router(vip_library_admin.router)
app.include_router(vip_library_public.router)
# 电商(商品 / 卡密 / 发货)
app.include_router(shop_admin.router)
# VIP 私密社群(类微博)

View File

@ -40,10 +40,22 @@ class BookContent(BaseModel):
updatedAt: str | None = None
class TtJoinBody(BaseModel):
"""抖音加群弹窗 — 仅 platforms.tt.join,与微信 VIP/join-group 隔离。"""
joinGroupWechat: bool | None = None
joinGroupDouyin: bool | None = None
socialFollowAuto: bool | None = None
wechatOaName: str | None = None
joinGroupDouyinHint: str | None = None
joinGroupDouyinQr: str | None = None
class TtPlatformBody(BaseModel):
homeVariant: str | None = None
modules: dict[str, ModuleToggle] | None = None
bookContent: BookContent | None = None
join: TtJoinBody | None = None
@router.get("/config")
@ -63,6 +75,8 @@ async def put_douyin_config(body: TtPlatformBody, _: str = Depends(require_admin
patch["modules"] = {k: v.model_dump() for k, v in body.modules.items()}
if body.bookContent is not None:
patch["bookContent"] = body.bookContent.model_dump()
if body.join is not None:
patch["join"] = body.join.model_dump(exclude_none=True)
saved = write_tt_platform(patch)
# 埋点 + ntfy(首页切换 / 入口开关)
@ -81,6 +95,14 @@ async def put_douyin_config(body: TtPlatformBody, _: str = Depends(require_admin
changed.append(f"{key}:{'开' if n else '关'}")
if body.bookContent is not None:
changed.append("bookContent")
if body.join is not None:
oj = before.get("join") or {}
nj = saved.get("join") or {}
if bool(oj.get("joinGroupWechat")) != bool(nj.get("joinGroupWechat")) or bool(
oj.get("joinGroupDouyin")
) != bool(nj.get("joinGroupDouyin")):
ch = "公众号" if nj.get("joinGroupWechat") and not nj.get("joinGroupDouyin") else "抖音群"
changed.append(f"join→{ch}")
if changed:
label = " · ".join(changed)[:120]

View File

@ -20,6 +20,8 @@ class VipBody(BaseModel):
vipProductId: str | None = None
vipCta: str | None = None
vipOfferKey: str | None = None
# 微信落地页运营配置 → platforms.weapp.vipContent(可选增量)
vipContent: dict[str, Any] | None = None
class VipOfferBody(BaseModel):

View File

@ -0,0 +1,106 @@
"""VIP 正式内容管理 — /api/admin/vip/library*"""
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.vip_library import (
get_ebook,
get_course,
get_lesson,
library_meta,
read_library,
write_library,
)
router = APIRouter(prefix="/api/admin/vip/library", tags=["vip-library-admin"])
class LibraryPatch(BaseModel):
ebooks: dict[str, Any] | None = None
course: dict[str, Any] | None = None
lessons: dict[str, Any] | None = None
class EbookPatch(BaseModel):
title: str | None = None
free: bool | None = None
estimatedMinutes: int | None = Field(default=None, ge=0)
headers: list[str] | None = None
sections: list[str] | None = None
markdown: str | None = None
class LessonPatch(BaseModel):
markdown: str | None = None
videoUrl: str | None = None
@router.get("")
async def get_library(_: str = Depends(require_admin)) -> dict[str, Any]:
lib = read_library()
return {"ok": True, "meta": library_meta(), **lib}
@router.get("/meta")
async def get_meta(_: str = Depends(require_admin)) -> dict[str, Any]:
return {"ok": True, **library_meta()}
@router.put("")
async def put_library(body: LibraryPatch, _: str = Depends(require_admin)) -> dict[str, Any]:
saved = write_library(body.model_dump(exclude_none=True))
return {"ok": True, "meta": library_meta(), **saved}
@router.get("/ebooks/{book_id}")
async def get_ebook_admin(book_id: str, _: str = Depends(require_admin)) -> dict[str, Any]:
book = get_ebook(book_id)
if not book:
return {"ok": False, "error": "not_found", "id": book_id}
return {"ok": True, "ebook": book}
@router.put("/ebooks/{book_id}")
async def put_ebook_admin(
book_id: str, body: EbookPatch, _: str = Depends(require_admin)
) -> dict[str, Any]:
patch = body.model_dump(exclude_none=True)
patch["id"] = book_id
saved = write_library({"ebooks": {book_id: patch}})
return {"ok": True, "ebook": (saved.get("ebooks") or {}).get(book_id), "meta": library_meta()}
@router.get("/course")
async def get_course_admin(_: str = Depends(require_admin)) -> dict[str, Any]:
return {"ok": True, "course": get_course()}
@router.put("/course")
async def put_course_admin(body: dict[str, Any], _: str = Depends(require_admin)) -> dict[str, Any]:
saved = write_library({"course": body})
return {"ok": True, "course": saved.get("course"), "meta": library_meta()}
@router.get("/lessons/{lesson_key}")
async def get_lesson_admin(lesson_key: str, _: str = Depends(require_admin)) -> dict[str, Any]:
lesson = get_lesson(lesson_key)
if not lesson:
return {"ok": False, "error": "not_found", "key": lesson_key}
return {"ok": True, "key": lesson_key, "lesson": lesson}
@router.put("/lessons/{lesson_key}")
async def put_lesson_admin(
lesson_key: str, body: LessonPatch, _: str = Depends(require_admin)
) -> dict[str, Any]:
saved = write_library({"lessons": {lesson_key: body.model_dump(exclude_none=True)}})
return {
"ok": True,
"key": lesson_key,
"lesson": (saved.get("lessons") or {}).get(lesson_key),
"meta": library_meta(),
}

View File

@ -0,0 +1,79 @@
"""公开 VIP 正式内容 — 小程序拉电子书/课程(合法域名 API)。"""
from __future__ import annotations
from typing import Any
from fastapi import APIRouter
from fastapi.responses import JSONResponse
from ebook_svc.services.vip_library import get_course, get_ebook, get_lesson, library_meta, read_library
router = APIRouter(tags=["vip-library-public"])
_NO_STORE = {
"Cache-Control": "no-store, no-cache, must-revalidate",
"Access-Control-Allow-Origin": "*",
}
@router.get("/api/vip/library/meta")
@router.get("/api/ebook/vip/library/meta")
async def public_library_meta() -> JSONResponse:
return JSONResponse(content={"ok": True, **library_meta()}, headers=_NO_STORE)
@router.get("/api/vip/library")
@router.get("/api/ebook/vip/library")
async def public_library() -> JSONResponse:
lib = read_library()
return JSONResponse(content={"ok": True, **lib}, headers=_NO_STORE)
@router.get("/api/vip/ebooks/{book_id}")
@router.get("/api/ebook/vip/ebooks/{book_id}")
async def public_ebook(book_id: str) -> JSONResponse:
book = get_ebook(book_id)
if not book:
return JSONResponse(
content={"ok": False, "error": "not_found", "id": book_id},
status_code=404,
headers=_NO_STORE,
)
return JSONResponse(content={"ok": True, "ebook": book}, headers=_NO_STORE)
@router.get("/api/vip/course")
@router.get("/api/ebook/vip/course")
async def public_course() -> JSONResponse:
return JSONResponse(content={"ok": True, "course": get_course()}, headers=_NO_STORE)
@router.get("/api/vip/lessons/{lesson_key}")
@router.get("/api/ebook/vip/lessons/{lesson_key}")
async def public_lesson(lesson_key: str) -> JSONResponse:
lesson = get_lesson(lesson_key)
course = get_course()
# also resolve lesson meta from course modules
meta: dict[str, Any] | None = None
for m in course.get("modules") or []:
if not isinstance(m, dict):
continue
for les in m.get("lessons") or []:
if isinstance(les, dict) and str(les.get("key")) == lesson_key:
meta = les
break
if not lesson and not meta:
return JSONResponse(
content={"ok": False, "error": "not_found", "key": lesson_key},
status_code=404,
headers=_NO_STORE,
)
return JSONResponse(
content={
"ok": True,
"key": lesson_key,
"lesson": lesson or {},
"meta": meta,
},
headers=_NO_STORE,
)

View File

@ -28,6 +28,16 @@ _FALLBACK_BOOK: dict[str, Any] = {
],
}
# 抖音加群弹窗(仅 platforms.tt.join,绝不写顶层微信 flags)
DEFAULT_TT_JOIN: dict[str, Any] = {
"joinGroupWechat": True,
"joinGroupDouyin": False,
"socialFollowAuto": False,
"wechatOaName": "异度世界",
"joinGroupDouyinHint": "打开抖音搜群「数字游民」或扫码进群",
"joinGroupDouyinQr": "",
}
DEFAULT_TT: dict[str, Any] = {
"homeVariant": "bmi", # 过审默认 BMI;后台可切 hub
"modules": {
@ -50,6 +60,7 @@ DEFAULT_TT: dict[str, Any] = {
"note": "抖音默认隐藏,后台可开",
},
},
"join": dict(DEFAULT_TT_JOIN),
"bookContent": _FALLBACK_BOOK,
}
@ -117,9 +128,24 @@ def default_tt_platform() -> dict[str, Any]:
return cfg
def _merge_join(base: dict[str, Any], patch: dict[str, Any] | None) -> dict[str, Any]:
out = dict(DEFAULT_TT_JOIN)
out.update({k: v for k, v in (base or {}).items() if k in DEFAULT_TT_JOIN})
if not patch:
return out
for k in ("joinGroupWechat", "joinGroupDouyin", "socialFollowAuto"):
if k in patch and isinstance(patch[k], bool):
out[k] = patch[k]
for k in ("wechatOaName", "joinGroupDouyinHint", "joinGroupDouyinQr"):
if k in patch and patch[k] is not None:
out[k] = str(patch[k])
return out
def _merge_tt(base: dict[str, Any], patch: dict[str, Any] | None) -> dict[str, Any]:
out = deepcopy(base)
if not patch:
out["join"] = _merge_join(out.get("join") if isinstance(out.get("join"), dict) else {}, None)
return out
hv = patch.get("homeVariant")
if hv in ("bmi", "hub"):
@ -128,6 +154,13 @@ def _merge_tt(base: dict[str, Any], patch: dict[str, Any] | None) -> dict[str, A
for key in ("nav", "book", "community"):
if key in mods and isinstance(mods[key], dict):
out["modules"][key] = {**out["modules"].get(key, {}), **mods[key]}
if "join" in patch and isinstance(patch.get("join"), dict):
out["join"] = _merge_join(
out.get("join") if isinstance(out.get("join"), dict) else {},
patch["join"],
)
else:
out["join"] = _merge_join(out.get("join") if isinstance(out.get("join"), dict) else {}, None)
bc = patch.get("bookContent")
if isinstance(bc, dict):
chapters = bc.get("chapters")
@ -148,6 +181,32 @@ def resolve_config_file() -> Path:
return local
def _seed_join_from_legacy_flags(raw: dict[str, Any], tt: dict[str, Any]) -> dict[str, Any]:
"""若 tt.join 尚未落盘,从顶层 flags/copy 只读迁移一次(不写回顶层微信配置)。"""
out = dict(tt) if isinstance(tt, dict) else {}
if isinstance(out.get("join"), dict) and any(
k in out["join"] for k in ("joinGroupWechat", "joinGroupDouyin")
):
return out
flags = raw.get("flags") if isinstance(raw.get("flags"), dict) else {}
copy = raw.get("copy") if isinstance(raw.get("copy"), dict) else {}
seeded = dict(DEFAULT_TT_JOIN)
if isinstance(flags.get("joinGroupWechat"), bool):
seeded["joinGroupWechat"] = flags["joinGroupWechat"]
if isinstance(flags.get("joinGroupDouyin"), bool):
seeded["joinGroupDouyin"] = flags["joinGroupDouyin"]
if isinstance(flags.get("socialFollowAuto"), bool):
seeded["socialFollowAuto"] = flags["socialFollowAuto"]
if copy.get("wechatOaName"):
seeded["wechatOaName"] = str(copy["wechatOaName"])
if copy.get("joinGroupDouyinHint"):
seeded["joinGroupDouyinHint"] = str(copy["joinGroupDouyinHint"])
if copy.get("joinGroupDouyinQr") is not None:
seeded["joinGroupDouyinQr"] = str(copy.get("joinGroupDouyinQr") or "")
out["join"] = seeded
return out
def read_tt_platform() -> dict[str, Any]:
base = default_tt_platform()
path = resolve_config_file()
@ -159,7 +218,8 @@ def read_tt_platform() -> dict[str, Any]:
# 门户整包 remote-config
if isinstance(raw.get("platforms"), dict) or "modules" in raw and "flags" in raw:
tt = (raw.get("platforms") or {}).get("tt") or {}
return _merge_tt(base, tt if isinstance(tt, dict) else {})
tt = _seed_join_from_legacy_flags(raw if isinstance(raw, dict) else {}, tt if isinstance(tt, dict) else {})
return _merge_tt(base, tt)
# 独立 tt 文件
return _merge_tt(base, raw if isinstance(raw, dict) else {})

View File

@ -10,6 +10,10 @@ from typing import Any, Literal
from ebook_svc.domains.books.products import PRODUCT_OFFERS, _LEGACY_PRODUCT_IDS
from ebook_svc.services.tt_platform_config import resolve_config_file
from ebook_svc.services.vip_content import (
apply_vip_content_patch,
read_vip_content_from_raw,
)
JoinAction = Literal["popup", "vip"]
@ -153,6 +157,8 @@ def read_vip_config() -> dict[str, Any]:
"vipCta": cta,
"vipOfferKey": str(offer.get("key") or offer_key or ""),
"is_free": is_free,
# 落地页运营位:缺省=现网 UI;不自动写盘
"vipContent": read_vip_content_from_raw(raw),
"updatedAt": raw.get("updatedAt"),
"version": raw.get("version"),
"configPath": str(resolve_config_file()),
@ -212,6 +218,11 @@ def write_vip_config(patch: dict[str, Any]) -> dict[str, Any]:
out["modules"] = modules
out["flags"] = flags
out["copy"] = copy
# 仅当运营显式提交 vipContent 时写入 platforms.weapp(不碰 platforms.tt)
if "vipContent" in patch and isinstance(patch.get("vipContent"), dict):
out = apply_vip_content_patch(out, patch["vipContent"])
out["updatedAt"] = datetime.now(timezone.utc).isoformat()
try:
out["version"] = int(out.get("version") or 1) + 1

View File

@ -0,0 +1,283 @@
"""微信 VIP 落地页运营配置 — platforms.weapp.vipContent。
只增不改顶层业务键;缺省=现网硬编码 UI;不碰抖音 platforms.tt / 订单。
"""
from __future__ import annotations
from copy import deepcopy
from typing import Any
# 对齐 apps/miniprogram/h5/src/pages/vip/index.tsx 现网硬编码
DEFAULT_VIP_CONTENT: dict[str, Any] = {
"heroEyebrow": "nomadro",
"heroTitleAccent": "全模块解锁",
"heroTitleRest": "持续更新 · 抱团出海",
"heroLead": "一次付费,解锁电子书、视频教程、知识社群、即时问答,每周更新",
"showStats": True,
"showTopics": True,
"showVideos": True,
"showEbooks": True,
"showCompare": True,
"showFaq": True,
"showCta": True,
"reviewMode": False,
"stats": {
"topics": "4",
"ebooks": "2",
"videos": "40+",
"updateFrequency": "每周",
},
"topics": [
{
"id": "ebook",
"icon": "📖",
"title": "电子书",
"desc": "知识沉淀·随时阅读",
"href": "#ebooks",
"enabled": True,
"locked": False,
"sort": 0,
},
{
"id": "cloudphone",
"icon": "🎬",
"title": "视频教程",
"desc": "实战演练·即学即用",
"href": "#video-courses",
"enabled": True,
"locked": False,
"sort": 1,
},
{
"id": "community",
"icon": "👥",
"title": "知识社群",
"desc": "抱团出海",
"href": "/pages/vip-memo/index",
"enabled": True,
"locked": True,
"sort": 2,
},
{
"id": "tools",
"icon": "🛒",
"title": "设备自助下单",
"desc": "开箱即用",
"href": "/pages/vip-store/index",
"enabled": True,
"locked": True,
"sort": 3,
},
],
"videos": [
{
"id": "cloudphone",
"icon": "☁️",
"title": "云手机",
"desc": "低成本自建云手机,TikTok/YouTube 无人直播实战指南",
"href": "/vip/cloudphone",
"enabled": True,
"sort": 0,
},
{
"id": "livestream",
"icon": "📺",
"title": "无人直播",
"desc": "TikTok/YouTube 无人直播,24 小时自动化",
"href": "/vip/topic/livestream",
"enabled": True,
"sort": 1,
},
{
"id": "indie",
"icon": "🛠️",
"title": "独立开发",
"desc": "从想法到产品,独立开发者全流程指南",
"href": "/vip/topic/indie",
"enabled": True,
"sort": 2,
},
{
"id": "aiagent",
"icon": "🤖",
"title": "AI Agent",
"desc": "AIGC 与智能体,Vibe Coding 跨界创造",
"href": "/vip/topic/aiagent",
"enabled": True,
"sort": 3,
},
],
"ebooks": [
{
"id": "1",
"title": "数字游民",
"desc": "地理套利与自动化杠杆",
"ebookId": "nomad",
"free": True,
"enabled": True,
"sort": 0,
},
{
"id": "2",
"title": "云手机",
"desc": "低成本集群搭建指南",
"ebookId": "cloudphone",
"free": False,
"enabled": True,
"sort": 1,
},
],
"compareTitle": "单品 vs 会员",
"compareDesc": "一次付费,全部解锁",
"compare": [
{"feature": "电子书", "single": "按需开通", "member": "全解锁"},
{"feature": "视频教程", "single": "按需开通", "member": "全解锁"},
{"feature": "知识社群", "single": "—", "member": "✓"},
{"feature": "即时问答", "single": "—", "member": "✓"},
{"feature": "持续更新", "single": "—", "member": "✓"},
],
"faqTitle": "常见问题",
"faqSub": "购买前可快速了解会员权益与流程;点击问题展开详情。",
"faq": [
{
"q": "会员包含哪些内容?",
"a": "电子书、视频教程、知识社群、即时问答、设备自助下单等全部解锁,并享受持续更新。",
},
{
"q": "如何加入?",
"a": "点击「立即加入」完成支付即可,支付成功后自动开通,无需人工审核。",
},
{
"q": "为什么越早加入越划算?",
"a": "会员采用阶梯定价:越早锁定席位,单价越低;在恢复原价前完成支付,可长期享受全部内容与后续更新,整体投入更省、权益不打折。",
},
],
"ctaChips": ["阶梯定价", "数字交付", "持续更新", "不支持退款"],
"ctaSecondary": "已有账号",
"ctaHintWeapp": "微信小程序虚拟支付",
"ctaHintH5": "浏览器请走门户 /vip 支付",
}
_BOOL_KEYS = (
"showStats",
"showTopics",
"showVideos",
"showEbooks",
"showCompare",
"showFaq",
"showCta",
"reviewMode",
)
_STR_KEYS = (
"heroEyebrow",
"heroTitleAccent",
"heroTitleRest",
"heroLead",
"compareTitle",
"compareDesc",
"faqTitle",
"faqSub",
"ctaSecondary",
"ctaHintWeapp",
"ctaHintH5",
)
def default_vip_content() -> dict[str, Any]:
return deepcopy(DEFAULT_VIP_CONTENT)
def _merge_list(base: list[Any], patch: Any, *, id_key: str = "id") -> list[Any]:
if not isinstance(patch, list):
return deepcopy(base)
if not patch:
return []
# 运营整表替换(含 enabled/sort);非法项跳过
out: list[Any] = []
for i, item in enumerate(patch):
if not isinstance(item, dict):
continue
row = dict(item)
if id_key not in row:
row[id_key] = f"item-{i}"
if "enabled" in row:
row["enabled"] = bool(row["enabled"])
if "sort" in row:
try:
row["sort"] = int(row["sort"])
except Exception:
row["sort"] = i
out.append(row)
out.sort(key=lambda x: int(x.get("sort") or 0))
return out
def merge_vip_content(base: dict[str, Any] | None, patch: dict[str, Any] | None) -> dict[str, Any]:
out = deepcopy(base) if isinstance(base, dict) else default_vip_content()
if not isinstance(patch, dict) or not patch:
return out
for k in _BOOL_KEYS:
if k in patch and isinstance(patch[k], bool):
out[k] = patch[k]
for k in _STR_KEYS:
if k in patch and patch[k] is not None:
out[k] = str(patch[k])
if isinstance(patch.get("stats"), dict):
stats = dict(out.get("stats") or {})
for sk, sv in patch["stats"].items():
if sv is not None:
stats[str(sk)] = str(sv)
out["stats"] = stats
if "topics" in patch:
out["topics"] = _merge_list(out.get("topics") or [], patch["topics"])
if "videos" in patch:
out["videos"] = _merge_list(out.get("videos") or [], patch["videos"])
if "ebooks" in patch:
out["ebooks"] = _merge_list(out.get("ebooks") or [], patch["ebooks"])
if "compare" in patch and isinstance(patch["compare"], list):
out["compare"] = [
{
"feature": str(x.get("feature") or ""),
"single": str(x.get("single") or ""),
"member": str(x.get("member") or ""),
}
for x in patch["compare"]
if isinstance(x, dict) and str(x.get("feature") or "").strip()
]
if "faq" in patch and isinstance(patch["faq"], list):
out["faq"] = [
{"q": str(x.get("q") or ""), "a": str(x.get("a") or "")}
for x in patch["faq"]
if isinstance(x, dict) and str(x.get("q") or "").strip()
]
if "ctaChips" in patch and isinstance(patch["ctaChips"], list):
out["ctaChips"] = [str(x) for x in patch["ctaChips"] if str(x).strip()]
return out
def read_vip_content_from_raw(raw: dict[str, Any]) -> dict[str, Any]:
"""只读合并;文件无 platforms.weapp.vipContent 时返回默认(不写盘)。"""
platforms = raw.get("platforms") if isinstance(raw.get("platforms"), dict) else {}
weapp = platforms.get("weapp") if isinstance(platforms.get("weapp"), dict) else {}
stored = weapp.get("vipContent") if isinstance(weapp.get("vipContent"), dict) else None
return merge_vip_content(default_vip_content(), stored)
def apply_vip_content_patch(raw: dict[str, Any], patch: dict[str, Any] | None) -> dict[str, Any]:
"""增量写入 platforms.weapp.vipContent;保留 platforms.tt 与其它顶层键。"""
out = dict(raw)
platforms = dict(out.get("platforms") or {})
weapp = dict(platforms.get("weapp") or {})
current = weapp.get("vipContent") if isinstance(weapp.get("vipContent"), dict) else {}
merged = merge_vip_content(merge_vip_content(default_vip_content(), current), patch)
weapp["vipContent"] = merged
platforms["weapp"] = weapp
out["platforms"] = platforms
return out

View File

@ -0,0 +1,169 @@
"""VIP 正式内容库 — 电子书章节 / 视频课 / 课时文档。
存 data/vip-library.json(与 remote-config 同目录);缺省用包内 seed;
不碰订单、抖音 platforms.tt、PocketBase。
"""
from __future__ import annotations
import json
from copy import deepcopy
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
from ebook_svc.services.tt_platform_config import resolve_config_file
_SEED_PATH = Path(__file__).resolve().parents[1] / "data" / "vip_library_seed.json"
_EMPTY: dict[str, Any] = {
"version": 1,
"updatedAt": "",
"ebooks": {},
"course": {"id": "cloudphone", "title": "云手机实战课", "modules": []},
"lessons": {},
}
def library_path() -> Path:
cfg = resolve_config_file()
return cfg.parent / "vip-library.json"
def _load_seed() -> dict[str, Any]:
if _SEED_PATH.is_file():
try:
raw = json.loads(_SEED_PATH.read_text(encoding="utf-8"))
if isinstance(raw, dict):
return raw
except Exception:
pass
return deepcopy(_EMPTY)
def _normalize(raw: dict[str, Any] | None) -> dict[str, Any]:
base = _load_seed()
if not isinstance(raw, dict):
return deepcopy(base)
out = deepcopy(base)
if isinstance(raw.get("ebooks"), dict) and raw["ebooks"]:
out["ebooks"] = raw["ebooks"]
if isinstance(raw.get("course"), dict) and raw["course"]:
course = dict(out.get("course") or {})
course.update({k: v for k, v in raw["course"].items() if v is not None})
if isinstance(raw["course"].get("modules"), list):
course["modules"] = raw["course"]["modules"]
out["course"] = course
if isinstance(raw.get("lessons"), dict) and raw["lessons"]:
out["lessons"] = raw["lessons"]
try:
out["version"] = int(raw.get("version") or out.get("version") or 1)
except Exception:
out["version"] = 1
out["updatedAt"] = str(raw.get("updatedAt") or out.get("updatedAt") or "")
return out
def read_library(*, prefer_file: bool = True) -> dict[str, Any]:
"""读库:有文件用文件(merge seed 补缺),无文件返回 seed(不写盘)。"""
path = library_path()
if prefer_file and path.is_file():
try:
stored = json.loads(path.read_text(encoding="utf-8"))
return _normalize(stored if isinstance(stored, dict) else None)
except Exception:
pass
return _normalize(None)
def write_library(patch: dict[str, Any] | None) -> dict[str, Any]:
"""整库或分块写入;升 version。"""
current = read_library()
patch = patch if isinstance(patch, dict) else {}
out = deepcopy(current)
if isinstance(patch.get("ebooks"), dict):
ebooks = dict(out.get("ebooks") or {})
for bid, book in patch["ebooks"].items():
if not isinstance(book, dict):
continue
key = str(bid)
prev = dict(ebooks.get(key) or {})
prev.update(book)
if "id" not in prev:
prev["id"] = key
ebooks[key] = prev
out["ebooks"] = ebooks
if isinstance(patch.get("course"), dict):
course = dict(out.get("course") or {})
course.update({k: v for k, v in patch["course"].items() if k != "modules" and v is not None})
if isinstance(patch["course"].get("modules"), list):
course["modules"] = patch["course"]["modules"]
out["course"] = course
if isinstance(patch.get("lessons"), dict):
lessons = dict(out.get("lessons") or {})
for lid, body in patch["lessons"].items():
if not isinstance(body, dict):
continue
prev = dict(lessons.get(str(lid)) or {})
prev.update(body)
lessons[str(lid)] = prev
out["lessons"] = lessons
try:
out["version"] = int(out.get("version") or 1) + 1
except Exception:
out["version"] = 2
out["updatedAt"] = datetime.now(timezone.utc).isoformat()
path = library_path()
path.parent.mkdir(parents=True, exist_ok=True)
bak = path.with_suffix(path.suffix + ".bak")
if path.is_file():
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")
return out
def get_ebook(book_id: str) -> dict[str, Any] | None:
lib = read_library()
book = (lib.get("ebooks") or {}).get(book_id)
return book if isinstance(book, dict) else None
def get_course() -> dict[str, Any]:
lib = read_library()
course = lib.get("course")
return course if isinstance(course, dict) else {"id": "cloudphone", "title": "云手机实战课", "modules": []}
def get_lesson(lesson_key: str) -> dict[str, Any] | None:
lib = read_library()
body = (lib.get("lessons") or {}).get(lesson_key)
return body if isinstance(body, dict) else None
def library_meta() -> dict[str, Any]:
lib = read_library()
ebooks = lib.get("ebooks") or {}
course = lib.get("course") or {}
mods = course.get("modules") if isinstance(course, dict) else []
lesson_n = sum(len(m.get("lessons") or []) for m in mods if isinstance(m, dict))
return {
"version": lib.get("version"),
"updatedAt": lib.get("updatedAt"),
"ebookIds": list(ebooks.keys()) if isinstance(ebooks, dict) else [],
"ebookChapters": {
k: len((v or {}).get("sections") or [])
for k, v in (ebooks.items() if isinstance(ebooks, dict) else [])
if isinstance(v, dict)
},
"courseModules": len(mods) if isinstance(mods, list) else 0,
"courseLessons": lesson_n,
"lessonDocs": len(lib.get("lessons") or {}),
"path": str(library_path()),
"hasFile": library_path().is_file(),
}

View File

@ -1,5 +1,10 @@
/** Offline seed — keep in sync with lib/remote-config.ts DEFAULT */
import linksSeed from './links.json'
import {
DEFAULT_WEAPP_VIP,
mergeWeappVipContent,
type WeappVipContent,
} from './vipContent'
export type ModuleToggle = {
enabled: boolean
@ -77,6 +82,13 @@ export type NomadroRemoteConfig = {
}
/** 导航分类/链接(后台 CRUD);离线用 links.json */
navContent?: NavContent
/** 分端配置:weapp.vipContent 仅微信 VIP 落地页;tt 由抖音端读,此处透传不解析 */
platforms?: {
weapp?: {
vipContent?: Partial<WeappVipContent>
}
tt?: Record<string, unknown>
}
}
function normalizeNav(raw: unknown): NavContent {
@ -146,6 +158,11 @@ export const DEFAULT_REMOTE_CONFIG: NomadroRemoteConfig = {
joinGroupDouyinQr: '',
},
navContent: JSON.parse(JSON.stringify(DEFAULT_NAV_CONTENT)) as NavContent,
platforms: {
weapp: {
vipContent: JSON.parse(JSON.stringify(DEFAULT_WEAPP_VIP)) as WeappVipContent,
},
},
}
export function mergeNavContent(
@ -185,6 +202,29 @@ export function visibleNavContent(nav: NavContent): NavContent {
}
}
function mergePlatforms(
base: NomadroRemoteConfig['platforms'],
patch: NomadroRemoteConfig['platforms'] | undefined,
): NomadroRemoteConfig['platforms'] {
const b = base || {}
const p = patch || {}
const baseWeapp = (b.weapp || {}) as { vipContent?: Partial<WeappVipContent> }
const patchWeapp = (p.weapp || {}) as { vipContent?: Partial<WeappVipContent> }
return {
...b,
...p,
weapp: {
...baseWeapp,
...patchWeapp,
vipContent: mergeWeappVipContent(
patchWeapp.vipContent ?? baseWeapp.vipContent,
),
},
// tt 原样透传(若远端有);勿用微信默认覆盖抖音
...(p.tt != null ? { tt: p.tt } : b.tt != null ? { tt: b.tt } : {}),
}
}
export function mergeRemoteConfig(
partial: Partial<NomadroRemoteConfig> | null | undefined,
): NomadroRemoteConfig {
@ -202,5 +242,6 @@ export function mergeRemoteConfig(
base.navContent || DEFAULT_NAV_CONTENT,
partial.navContent ?? base.navContent,
),
platforms: mergePlatforms(base.platforms, partial.platforms),
}
}

View File

@ -0,0 +1,268 @@
/**
* 微信 VIP 落地页远程配置 — platforms.weapp.vipContent
* 缺省=现网硬编码;离线兜底;抖音端勿读。
*/
export type VipTopicItem = {
id: string
icon: string
title: string
desc: string
href: string
enabled?: boolean
locked?: boolean
sort?: number
}
export type VipVideoItem = {
id: string
icon: string
title: string
desc: string
href: string
enabled?: boolean
sort?: number
}
export type VipEbookItem = {
id: string
title: string
desc: string
ebookId: string
free?: boolean
enabled?: boolean
sort?: number
}
export type VipCompareItem = {
feature: string
single: string
member: string
}
export type VipFaqItem = {
q: string
a: string
}
export type WeappVipContent = {
heroEyebrow: string
heroTitleAccent: string
heroTitleRest: string
heroLead: string
showStats: boolean
showTopics: boolean
showVideos: boolean
showEbooks: boolean
showCompare: boolean
showFaq: boolean
showCta: boolean
reviewMode: boolean
stats: {
topics: string
ebooks: string
videos: string
updateFrequency: string
}
topics: VipTopicItem[]
videos: VipVideoItem[]
ebooks: VipEbookItem[]
compareTitle: string
compareDesc: string
compare: VipCompareItem[]
faqTitle: string
faqSub: string
faq: VipFaqItem[]
ctaChips: string[]
ctaSecondary: string
ctaHintWeapp: string
ctaHintH5: string
}
export const DEFAULT_WEAPP_VIP: WeappVipContent = {
heroEyebrow: 'nomadro',
heroTitleAccent: '全模块解锁',
heroTitleRest: '持续更新 · 抱团出海',
heroLead: '一次付费,解锁电子书、视频教程、知识社群、即时问答,每周更新',
showStats: true,
showTopics: true,
showVideos: true,
showEbooks: true,
showCompare: true,
showFaq: true,
showCta: true,
reviewMode: false,
stats: {
topics: '4',
ebooks: '2',
videos: '40+',
updateFrequency: '每周',
},
topics: [
{ id: 'ebook', icon: '📖', title: '电子书', desc: '知识沉淀·随时阅读', href: '#ebooks', enabled: true },
{
id: 'cloudphone',
icon: '🎬',
title: '视频教程',
desc: '实战演练·即学即用',
href: '#video-courses',
enabled: true,
},
{
id: 'community',
icon: '👥',
title: '知识社群',
desc: '抱团出海',
href: '/pages/vip-memo/index',
enabled: true,
locked: true,
},
{
id: 'tools',
icon: '🛒',
title: '设备自助下单',
desc: '开箱即用',
href: '/pages/vip-store/index',
enabled: true,
locked: true,
},
],
videos: [
{
id: 'cloudphone',
icon: '☁️',
title: '云手机',
desc: '低成本自建云手机,TikTok/YouTube 无人直播实战指南',
href: '/vip/cloudphone',
enabled: true,
},
{
id: 'livestream',
icon: '📺',
title: '无人直播',
desc: 'TikTok/YouTube 无人直播,24 小时自动化',
href: '/vip/topic/livestream',
enabled: true,
},
{
id: 'indie',
icon: '🛠️',
title: '独立开发',
desc: '从想法到产品,独立开发者全流程指南',
href: '/vip/topic/indie',
enabled: true,
},
{
id: 'aiagent',
icon: '🤖',
title: 'AI Agent',
desc: 'AIGC 与智能体,Vibe Coding 跨界创造',
href: '/vip/topic/aiagent',
enabled: true,
},
],
ebooks: [
{
id: '1',
title: '数字游民',
desc: '地理套利与自动化杠杆',
ebookId: 'nomad',
free: true,
enabled: true,
},
{
id: '2',
title: '云手机',
desc: '低成本集群搭建指南',
ebookId: 'cloudphone',
free: false,
enabled: true,
},
],
compareTitle: '单品 vs 会员',
compareDesc: '一次付费,全部解锁',
compare: [
{ feature: '电子书', single: '按需开通', member: '全解锁' },
{ feature: '视频教程', single: '按需开通', member: '全解锁' },
{ feature: '知识社群', single: '—', member: '✓' },
{ feature: '即时问答', single: '—', member: '✓' },
{ feature: '持续更新', single: '—', member: '✓' },
],
faqTitle: '常见问题',
faqSub: '购买前可快速了解会员权益与流程;点击问题展开详情。',
faq: [
{
q: '会员包含哪些内容?',
a: '电子书、视频教程、知识社群、即时问答、设备自助下单等全部解锁,并享受持续更新。',
},
{
q: '如何加入?',
a: '点击「立即加入」完成支付即可,支付成功后自动开通,无需人工审核。',
},
{
q: '为什么越早加入越划算?',
a: '会员采用阶梯定价:越早锁定席位,单价越低;在恢复原价前完成支付,可长期享受全部内容与后续更新,整体投入更省、权益不打折。',
},
],
ctaChips: ['阶梯定价', '数字交付', '持续更新', '不支持退款'],
ctaSecondary: '已有账号',
ctaHintWeapp: '微信小程序虚拟支付',
ctaHintH5: '浏览器请走门户 /vip 支付',
}
function mergeList<T extends { id?: string; enabled?: boolean; sort?: number }>(
base: T[],
patch: unknown,
): T[] {
if (!Array.isArray(patch)) return base.map((x) => ({ ...x }))
if (!patch.length) return []
return patch
.filter((x): x is T => !!x && typeof x === 'object')
.map((x, i) => ({ ...x, sort: typeof x.sort === 'number' ? x.sort : i }))
.sort((a, b) => Number(a.sort || 0) - Number(b.sort || 0))
}
export function mergeWeappVipContent(
partial?: Partial<WeappVipContent> | null,
): WeappVipContent {
const base = JSON.parse(JSON.stringify(DEFAULT_WEAPP_VIP)) as WeappVipContent
if (!partial) return base
return {
...base,
...partial,
showStats: typeof partial.showStats === 'boolean' ? partial.showStats : base.showStats,
showTopics: typeof partial.showTopics === 'boolean' ? partial.showTopics : base.showTopics,
showVideos: typeof partial.showVideos === 'boolean' ? partial.showVideos : base.showVideos,
showEbooks: typeof partial.showEbooks === 'boolean' ? partial.showEbooks : base.showEbooks,
showCompare: typeof partial.showCompare === 'boolean' ? partial.showCompare : base.showCompare,
showFaq: typeof partial.showFaq === 'boolean' ? partial.showFaq : base.showFaq,
showCta: typeof partial.showCta === 'boolean' ? partial.showCta : base.showCta,
reviewMode: typeof partial.reviewMode === 'boolean' ? partial.reviewMode : base.reviewMode,
stats: { ...base.stats, ...(partial.stats || {}) },
topics: mergeList(base.topics, partial.topics ?? base.topics),
videos: mergeList(base.videos, partial.videos ?? base.videos),
ebooks: mergeList(base.ebooks, partial.ebooks ?? base.ebooks),
compare: Array.isArray(partial.compare) ? partial.compare : base.compare,
faq: Array.isArray(partial.faq) ? partial.faq : base.faq,
ctaChips: Array.isArray(partial.ctaChips) ? partial.ctaChips.map(String) : base.ctaChips,
}
}
export type ConfigWithWeapp = {
platforms?: {
weapp?: {
vipContent?: Partial<WeappVipContent>
}
tt?: unknown
}
}
/** 只读微信 platforms.weapp.vipContent;缺省=包内默认(现网 UI) */
export function resolveWeappVipContent(config: ConfigWithWeapp | null | undefined): WeappVipContent {
const stored = config?.platforms?.weapp?.vipContent
return mergeWeappVipContent(stored)
}
export function visibleItems<T extends { enabled?: boolean }>(items: T[]): T[] {
return items.filter((x) => x.enabled !== false)
}

View File

@ -11,7 +11,9 @@ import {
getVipTopicConfig,
getVipTopicCurriculum,
resolveTopicId,
type VipTopicModule,
} from '../../data/vipTopics'
import { loadVipCourse } from '../../services/vipLibrary'
import {
CLOUDPHONE_AUDIENCE,
CLOUDPHONE_BENEFITS,
@ -39,7 +41,14 @@ export default function VipCoursePage() {
const topicId = resolveTopicId(router.params?.id)
const isCloudphone = topicId === 'cloudphone'
const config = getVipTopicConfig(topicId)
const curriculum = useMemo(() => getVipTopicCurriculum(topicId), [topicId])
const localCurriculum = useMemo(() => getVipTopicCurriculum(topicId), [topicId])
const [remoteModules, setRemoteModules] = useState<VipTopicModule[] | null>(null)
const curriculum = useMemo(() => {
if (isCloudphone && remoteModules?.length) {
return { modules: remoteModules, hasContent: true }
}
return localCurriculum
}, [isCloudphone, remoteModules, localCurriculum])
const totalLessons = curriculum.modules.reduce((s, m) => s + m.lessons.length, 0)
const [isVip, setIsVip] = useState(false)
@ -67,10 +76,32 @@ export default function VipCoursePage() {
Taro.setNavigationBarTitle({
title: isCloudphone ? '云手机实战课' : config?.title || '视频课程',
})
void resolveVipAccess(true).then((ok) => {
void (async () => {
if (isCloudphone) {
try {
const { course } = await loadVipCourse()
if (course.modules?.length) {
setRemoteModules(
course.modules.map((m) => ({
emoji: m.emoji,
title: m.title,
lessons: m.lessons.map((l) => ({
name: l.name,
duration: l.duration,
moduleIndex: l.moduleIndex,
lessonIndex: l.lessonIndex,
})),
})),
)
}
} catch {
/* keep local */
}
}
const ok = await resolveVipAccess(true)
setIsVip(ok)
setReady(true)
})
})()
}, [config?.title, isCloudphone])
useEffect(() => {

View File

@ -7,7 +7,8 @@ import Taro, { useRouter } from '@tarojs/taro'
import { useEffect, useMemo, useState } from 'react'
import { H5Box, H5Txt } from '../../components/H5Box'
import { MarkdownView } from '../../components/MarkdownView'
import { resolveVipEbookId, VIP_EBOOKS } from '../../data/vipEbooks'
import { resolveVipEbookId, VIP_EBOOKS, type VipEbookPack } from '../../data/vipEbooks'
import { loadVipEbook } from '../../services/vipLibrary'
import { goPage } from '../../utils/nav'
import { resolveVipAccess } from '../../utils/vipAccess'
import { getSafeAreaMetrics } from '../../utils/safeArea'
@ -27,10 +28,9 @@ export default function VipEbookPage() {
const theme = useNomadroTheme()
const router = useRouter()
const bookId = resolveVipEbookId(router.params?.id)
const book = VIP_EBOOKS[bookId]
const safe = getSafeAreaMetrics()
const [allowed, setAllowed] = useState(book.free)
const [book, setBook] = useState<VipEbookPack>(VIP_EBOOKS[bookId])
const [allowed, setAllowed] = useState(VIP_EBOOKS[bookId].free)
const [ready, setReady] = useState(false)
const [drawerOpen, setDrawerOpen] = useState(false)
const [tocFilter, setTocFilter] = useState('')
@ -66,14 +66,17 @@ export default function VipEbookPage() {
}, [toc, tocFilter])
useEffect(() => {
Taro.setNavigationBarTitle({ title: book.title })
setScrollInto('')
setDrawerOpen(false)
setTocFilter('')
setActiveSec(0)
setReadProgress(0)
setReady(false)
void (async () => {
if (book.free) {
const { book: next } = await loadVipEbook(bookId)
setBook(next)
Taro.setNavigationBarTitle({ title: next.title })
if (next.free) {
setAllowed(true)
setReady(true)
return
@ -84,7 +87,7 @@ export default function VipEbookPage() {
if (!vip) {
Taro.showModal({
title: '会员专享',
content: `开通 VIP 后可读《${book.title}》`,
content: `开通 VIP 后可读《${next.title}》`,
confirmText: '去开通',
success: (r) => {
if (r.confirm) goPage('/pages/vip/index')
@ -93,7 +96,7 @@ export default function VipEbookPage() {
})
}
})()
}, [book.free, book.title, bookId])
}, [bookId])
function onScroll(e: {
detail?: { scrollTop?: number; scrollHeight?: number }

View File

@ -7,8 +7,8 @@ import Taro, { useRouter } from '@tarojs/taro'
import { useEffect, useMemo, useState } from 'react'
import { H5Box, H5Txt } from '../../components/H5Box'
import { MarkdownView } from '../../components/MarkdownView'
import { getVipLesson, VIP_COURSE_MODULES } from '../../data/vipCourse'
import { VIP_LESSON_CONTENT } from '../../data/vipLessonContent'
import { VIP_COURSE_MODULES, type VipLesson, type VipModule } from '../../data/vipCourse'
import { loadVipLesson } from '../../services/vipLibrary'
import { goPage } from '../../utils/nav'
import { resolveVipAccess } from '../../utils/vipAccess'
import {
@ -20,17 +20,16 @@ import { DEFAULT_PREFS, loadReaderPrefs } from '../../utils/readerPrefs'
import { useNomadroTheme } from '@/utils/h5Theme'
import './index.scss'
const TOTAL = VIP_COURSE_MODULES.reduce((s, m) => s + m.lessons.length, 0)
function findPrevNext(m: number, l: number) {
function findPrevNext(modules: VipModule[], m: number, l: number) {
const flat: { m: number; l: number; name: string }[] = []
VIP_COURSE_MODULES.forEach((mod, mi) => {
modules.forEach((mod, mi) => {
mod.lessons.forEach((les, li) => flat.push({ m: mi, l: li, name: les.name }))
})
const idx = flat.findIndex((x) => x.m === m && x.l === l)
return {
prev: idx > 0 ? flat[idx - 1] : null,
next: idx >= 0 && idx < flat.length - 1 ? flat[idx + 1] : null,
total: flat.length,
}
}
@ -39,22 +38,30 @@ export default function VipLessonPage() {
const router = useRouter()
const m = Number(router.params?.m || 0)
const l = Number(router.params?.l || 0)
const lesson = useMemo(() => getVipLesson(m, l), [m, l])
const content = lesson ? VIP_LESSON_CONTENT[lesson.key] : null
const videoUrl = content?.videoUrl || lesson?.videoUrl || ''
const markdown = content?.markdown || ''
const prefs = useMemo(() => loadReaderPrefs() || DEFAULT_PREFS, [])
const { prev, next } = useMemo(() => findPrevNext(m, l), [m, l])
const [lesson, setLesson] = useState<VipLesson | null>(null)
const [videoUrl, setVideoUrl] = useState('')
const [markdown, setMarkdown] = useState('')
const [modules, setModules] = useState<VipModule[]>(VIP_COURSE_MODULES)
const [isVip, setIsVip] = useState(false)
const [ready, setReady] = useState(false)
const nav = useMemo(() => findPrevNext(modules, m, l), [modules, m, l])
const { prev, next, total: TOTAL } = nav
const [progress, setProgress] = useState(() => getProgress(TOTAL))
useEffect(() => {
setReady(false)
void (async () => {
const loaded = await loadVipLesson(m, l)
setLesson(loaded.lesson)
setModules(loaded.modules)
setVideoUrl(loaded.doc.videoUrl || loaded.lesson?.videoUrl || '')
setMarkdown(loaded.doc.markdown || '')
const vip = await resolveVipAccess(true)
setIsVip(vip)
setReady(true)
setProgress(getProgress(TOTAL))
const tot = loaded.modules.reduce((s, mod) => s + mod.lessons.length, 0)
setProgress(getProgress(tot))
if (!vip) {
Taro.showModal({
title: '会员专享',
@ -68,19 +75,14 @@ export default function VipLessonPage() {
})
},
})
} else if (lesson) {
setLastWatched(m, l, lesson.name)
} else if (loaded.lesson) {
setLastWatched(m, l, loaded.lesson.name)
Taro.setNavigationBarTitle({
title: loaded.lesson.name.replace(/^\d+\s*/, '').slice(0, 12),
})
}
})()
}, [m, l, lesson])
useEffect(() => {
if (lesson) {
Taro.setNavigationBarTitle({
title: lesson.name.replace(/^\d+\s*/, '').slice(0, 12),
})
}
}, [lesson])
}, [m, l])
function onVideoEnded() {
markCompleted(m, l)

View File

@ -1,5 +1,6 @@
/**
* Taro VIP landing — mirrors modules/vip LandingPage structure.
* 微信:读 platforms.weapp.vipContent;缺省=包内 DEFAULT(现网 UI);抖音不读 weapp。
*/
import { useEffect, useMemo, useState } from 'react'
import { Text, Button, View } from '@tarojs/components'
@ -13,6 +14,13 @@ import {
subscribeRemoteConfig,
} from '@/services/remoteConfig'
import type { NomadroRemoteConfig } from '@/data/remoteConfig.defaults'
import {
mergeWeappVipContent,
resolveWeappVipContent,
visibleItems,
type WeappVipContent,
} from '@/data/vipContent'
import { APP_TARGET } from '@/utils/config'
import { useNomadroTheme } from '@/utils/h5Theme'
import { goHome, goPage } from '@/utils/nav'
import { usePageShare, markPageShare } from '@/utils/pageShare'
@ -23,117 +31,12 @@ import './index.scss'
const isH5 = process.env.TARO_ENV === 'h5'
/** Offline seed from modules/vip/app/data/vip.mock.ts */
const ASSET_STATS = {
topics: 4,
ebooks: 2,
videos: '40+',
updateFrequency: '每周',
} as const
const STAT_ITEMS = [
{ key: 'topics', label: '模块' },
{ key: 'ebooks', label: '电子书' },
{ key: 'videos', label: '视频' },
{ key: 'updateFrequency', label: '更新' },
] as const
/** Offline seeds from modules/vip/app/data/vip.mock.ts */
const TOPICS_DISPLAY = [
{ id: 'ebook', icon: '📖', title: '电子书', desc: '知识沉淀·随时阅读', href: '#ebooks' },
{ id: 'cloudphone', icon: '🎬', title: '视频教程', desc: '实战演练·即学即用', href: '#video-courses' },
{
id: 'community',
icon: '👥',
title: '知识社群',
desc: '抱团出海',
href: '/pages/vip-memo/index',
locked: true,
},
{
id: 'tools',
icon: '🛒',
title: '设备自助下单',
desc: '开箱即用',
href: '/pages/vip-store/index',
locked: true,
},
] as const
const VIDEO_COURSES_DISPLAY = [
{
id: 'cloudphone',
icon: '☁️',
title: '云手机',
desc: '低成本自建云手机,TikTok/YouTube 无人直播实战指南',
href: '/vip/cloudphone',
},
{
id: 'livestream',
icon: '📺',
title: '无人直播',
desc: 'TikTok/YouTube 无人直播,24 小时自动化',
href: '/vip/topic/livestream',
},
{
id: 'indie',
icon: '🛠️',
title: '独立开发',
desc: '从想法到产品,独立开发者全流程指南',
href: '/vip/topic/indie',
},
{
id: 'aiagent',
icon: '🤖',
title: 'AI Agent',
desc: 'AIGC 与智能体,Vibe Coding 跨界创造',
href: '/vip/topic/aiagent',
},
] as const
const EBOOKS_DISPLAY = [
{
id: '1',
title: '数字游民',
desc: '地理套利与自动化杠杆',
href: '/vip/ebook',
free: true,
ebookId: 'nomad' as const,
},
{
id: '2',
title: '云手机',
desc: '低成本工作室搭建指南',
href: '/vip/ebook/cloudphone',
free: false,
ebookId: 'cloudphone' as const,
},
] as const
const COMPARE_ITEMS = [
{ feature: '电子书', single: '按需开通', member: '全解锁' },
{ feature: '视频教程', single: '按需开通', member: '全解锁' },
{ feature: '知识社群', single: '—', member: '✓' },
{ feature: '即时问答', single: '—', member: '✓' },
{ feature: '持续更新', single: '—', member: '✓' },
] as const
const FAQ_ITEMS = [
{
q: '会员包含哪些内容?',
a: '电子书、视频教程、知识社群、即时问答、设备自助下单等全部解锁,并享受持续更新。',
},
{
q: '如何加入?',
a: '点击「立即加入」完成支付即可,支付成功后自动开通,无需人工审核。',
},
{
q: '为什么越早加入越划算?',
a: '会员采用阶梯定价:越早锁定席位,单价越低;在恢复原价前完成支付,可长期享受全部内容与后续更新,整体投入更省、权益不打折。',
},
] as const
const CTA_CHIPS = ['阶梯定价', '数字交付', '持续更新', '不支持退款'] as const
{ key: 'topics' as const, label: '模块' },
{ key: 'ebooks' as const, label: '电子书' },
{ key: 'videos' as const, label: '视频' },
{ key: 'updateFrequency' as const, label: '更新' },
]
const LOGO_SVG = `<svg class="vip-logoMark" viewBox="0 0 40 40" fill="none" aria-hidden="true">
<circle cx="20" cy="20" r="18" stroke="#f06664" stroke-width="2.5"/>
@ -147,6 +50,12 @@ function formatRestoreDateShort(): string {
return `${d.getMonth() + 1}月${d.getDate()}日`
}
/** 抖音不读 platforms.weapp;微信/H5 读远程,缺省=包内现网 UI */
function pickVipContent(cfg: NomadroRemoteConfig): WeappVipContent {
if (APP_TARGET === 'tt') return mergeWeappVipContent(null)
return resolveWeappVipContent(cfg)
}
function VipPage() {
usePageShare({ title: 'nomadro · VIP 会员', path: '/pages/vip/index' })
return (
@ -158,7 +67,6 @@ function VipPage() {
export default markPageShare(VipPage)
function VipLanding() {
const theme = useNomadroTheme()
const [busy, setBusy] = useState(false)
@ -168,6 +76,8 @@ function VipLanding() {
const [restoreDate] = useState(() => formatRestoreDateShort())
const [isVip, setIsVip] = useState(false)
const vc = useMemo(() => pickVipContent(cfg), [cfg])
async function refreshVipStatus() {
setIsVip(await resolveVipAccess(true))
}
@ -217,6 +127,10 @@ function VipLanding() {
[safe],
)
const topics = useMemo(() => visibleItems(vc.topics), [vc.topics])
const videos = useMemo(() => visibleItems(vc.videos), [vc.videos])
const ebooks = useMemo(() => visibleItems(vc.ebooks), [vc.ebooks])
/** 页内锚点真滚动(小程序用 pageScrollTo,禁止 toast 糊弄) */
function scrollToAnchor(anchorId: string) {
const id = anchorId.replace(/^#/, '').trim()
@ -434,224 +348,246 @@ function VipLanding() {
<H5Box className="vip-landingSceneInner">
{/* LandingHero */}
<H5Box className="vip-section vip-heroSection vip-heroSection3d">
<H5Txt className="vip-heroEyebrow">nomadro</H5Txt>
<H5Txt className="vip-heroEyebrow">{vc.heroEyebrow || 'nomadro'}</H5Txt>
<H5Box className="vip-heroTitle">
<H5Txt className="vip-heroTitleAccent">全模块解锁</H5Txt>
<H5Txt className="vip-heroTitleRest">持续更新 · 抱团出海</H5Txt>
<H5Txt className="vip-heroTitleAccent">{vc.heroTitleAccent}</H5Txt>
<H5Txt className="vip-heroTitleRest">{vc.heroTitleRest}</H5Txt>
</H5Box>
<H5Txt className="vip-heroLead">
一次付费,解锁电子书、视频教程、知识社群、即时问答,每周更新
</H5Txt>
<H5Txt className="vip-heroLead">{vc.heroLead}</H5Txt>
</H5Box>
{/* AssetStats */}
<H5Box className="vip-section vip-statsSection">
<H5Box className="vip-statsGrid">
{STAT_ITEMS.map(({ key, label }) => (
<H5Box key={key} className="vip-card vip-landingStatCard">
<H5Txt className="vip-bigNumber">{ASSET_STATS[key]}</H5Txt>
<H5Txt className="vip-bigNumberLabel">{label}</H5Txt>
</H5Box>
))}
</H5Box>
</H5Box>
{/* TopicEbookShowcase */}
<H5Box className="vip-section vip-topicsSection" id="topics">
<H5Txt className="vip-sectionTitle">模块</H5Txt>
<H5Box className="vip-topicGrid" style={{ marginBottom: '1.5rem' }}>
{TOPICS_DISPLAY.map((t) => {
// 社群/商城等外链仍按配置锁;内容模块不锁入口(进页后再鉴权)
const hardLock = t.id === 'community' || t.id === 'tools'
const locked = hardLock && !isVip
return (
<H5Box
key={t.id}
className="vip-topicCard"
onClick={() => (locked ? onLocked() : openHref(t.href))}
>
{locked ? <H5Txt className="vip-topicLock">🔒</H5Txt> : null}
<H5Txt className="vip-topicIcon">{t.icon}</H5Txt>
<H5Txt className="vip-topicTitle">{t.title}</H5Txt>
<H5Txt className="vip-topicDesc">{t.desc}</H5Txt>
</H5Box>
)
})}
</H5Box>
<View id="video-courses" className="vip-sectionTitle">
<Text>视频教程</Text>
</View>
<H5Box className="vip-topicGrid" style={{ marginBottom: '1.5rem' }}>
{VIDEO_COURSES_DISPLAY.map((v) => (
<H5Box
key={v.id}
className="vip-topicCard"
onClick={() => openHref(v.href)}
>
<H5Txt className="vip-topicIcon">{v.icon}</H5Txt>
<H5Txt className="vip-topicTitle">{v.title}</H5Txt>
<H5Txt className="vip-topicDesc">{v.desc}</H5Txt>
</H5Box>
))}
</H5Box>
<View id="ebooks" className="vip-sectionTitle">
<Text>电子书</Text>
</View>
<H5Box className="vip-ebookGrid">
{EBOOKS_DISPLAY.map((e) => {
const isFree = Boolean(e.free) || isFreeVip
const locked = !isFree && !isVip
return (
<H5Box
key={e.id}
className="vip-card vip-ebookCard"
onClick={() => {
if (locked) {
onLocked()
return
}
goPage(`/pages/vip-ebook/index?id=${e.ebookId}`)
}}
>
<H5Txt className="vip-ebookEmoji">📖</H5Txt>
<H5Box className="vip-ebookTitleRow">
<H5Txt className="vip-ebookTitle">《{e.title}》</H5Txt>
{isFree ? <H5Txt className="vip-freeBadge">免费</H5Txt> : null}
{locked ? <H5Txt className="vip-ebookLock">🔒</H5Txt> : null}
</H5Box>
<H5Txt className="vip-ebookDesc">{e.desc}</H5Txt>
<H5Txt className="vip-ebookCta">
{locked ? '开通VIP解锁 →' : '阅读 →'}
</H5Txt>
</H5Box>
)
})}
</H5Box>
</H5Box>
{/* CompareSection */}
<H5Box className="vip-section">
<H5Txt className="vip-sectionTitle">单品 vs 会员</H5Txt>
<H5Txt className="vip-sectionDesc">一次付费,全部解锁</H5Txt>
<H5Box className="vip-compareWrap">
<H5Box className="vip-compareTable">
<H5Box className="vip-compareRow vip-compareRow--head">
<H5Txt className="vip-compareCell vip-compareCell--feature">权益</H5Txt>
<H5Txt className="vip-compareCell vip-compareCell--single">单品</H5Txt>
<H5Txt className="vip-compareCell vip-compareCell--member">会员</H5Txt>
</H5Box>
{COMPARE_ITEMS.map((row, i) => (
<H5Box
key={row.feature}
className={`vip-compareRow vip-compareRow--body${
i % 2 === 1 ? ' vip-compareRow--alt' : ''
}`}
>
<H5Txt className="vip-compareCell vip-compareCell--bodyFeature">
{row.feature}
</H5Txt>
<H5Txt className="vip-compareCell vip-compareCell--bodySingle">
{row.single}
</H5Txt>
<H5Txt className="vip-compareCell vip-compareCell--bodyMember">
{row.member}
</H5Txt>
{vc.showStats ? (
<H5Box className="vip-section vip-statsSection">
<H5Box className="vip-statsGrid">
{STAT_ITEMS.map(({ key, label }) => (
<H5Box key={key} className="vip-card vip-landingStatCard">
<H5Txt className="vip-bigNumber">{vc.stats[key]}</H5Txt>
<H5Txt className="vip-bigNumberLabel">{label}</H5Txt>
</H5Box>
))}
</H5Box>
</H5Box>
</H5Box>
) : null}
{/* FAQSection */}
<H5Box className="vip-section vip-faqSection">
<H5Box className="vip-faqInner">
<H5Box className="vip-faqEyebrow">
<H5Box className="vip-faqEyebrowDot" />
<H5Txt>FAQ</H5Txt>
</H5Box>
<H5Txt className="vip-faqHeadline">常见问题</H5Txt>
<H5Txt className="vip-faqSub">
购买前可快速了解会员权益与流程;点击问题展开详情。
</H5Txt>
<H5Box className="vip-faqList">
{FAQ_ITEMS.map((item, i) => {
const open = faqOpen === i
return (
<H5Box
key={item.q}
className={`vip-faqItem${open ? ' vip-faqItemOpen' : ''}`}
>
<Button
className="vip-faqTrigger"
onClick={() => setFaqOpen(open ? null : i)}
{/* TopicEbookShowcase */}
{vc.showTopics || vc.showVideos || vc.showEbooks ? (
<H5Box className="vip-section vip-topicsSection" id="topics">
{vc.showTopics && topics.length > 0 ? (
<>
<H5Txt className="vip-sectionTitle">模块</H5Txt>
<H5Box className="vip-topicGrid" style={{ marginBottom: '1.5rem' }}>
{topics.map((t) => {
const hardLock =
t.locked === true || t.id === 'community' || t.id === 'tools'
const locked = hardLock && !isVip
return (
<H5Box
key={t.id}
className="vip-topicCard"
onClick={() => (locked ? onLocked() : openHref(t.href))}
>
{locked ? <H5Txt className="vip-topicLock">🔒</H5Txt> : null}
<H5Txt className="vip-topicIcon">{t.icon}</H5Txt>
<H5Txt className="vip-topicTitle">{t.title}</H5Txt>
<H5Txt className="vip-topicDesc">{t.desc}</H5Txt>
</H5Box>
)
})}
</H5Box>
</>
) : null}
{vc.showVideos && videos.length > 0 ? (
<>
<View id="video-courses" className="vip-sectionTitle">
<Text>视频教程</Text>
</View>
<H5Box className="vip-topicGrid" style={{ marginBottom: '1.5rem' }}>
{videos.map((v) => (
<H5Box
key={v.id}
className="vip-topicCard"
onClick={() => openHref(v.href)}
>
<Text className="vip-faqIndex">{i + 1}</Text>
<Text className="vip-faqQuestionText">{item.q}</Text>
<Text className="vip-faqChevron">▾</Text>
</Button>
<H5Box className={`vip-faqPanel${open ? ' vip-faqPanelOpen' : ''}`}>
<H5Txt className="vip-faqAnswer">{item.a}</H5Txt>
<H5Txt className="vip-topicIcon">{v.icon}</H5Txt>
<H5Txt className="vip-topicTitle">{v.title}</H5Txt>
<H5Txt className="vip-topicDesc">{v.desc}</H5Txt>
</H5Box>
</H5Box>
)
})}
</H5Box>
))}
</H5Box>
</>
) : null}
{vc.showEbooks && ebooks.length > 0 ? (
<>
<View id="ebooks" className="vip-sectionTitle">
<Text>电子书</Text>
</View>
<H5Box className="vip-ebookGrid">
{ebooks.map((e) => {
const isFree = Boolean(e.free) || isFreeVip
const locked = !isFree && !isVip
return (
<H5Box
key={e.id}
className="vip-card vip-ebookCard"
onClick={() => {
if (locked) {
onLocked()
return
}
goPage(`/pages/vip-ebook/index?id=${e.ebookId}`)
}}
>
<H5Txt className="vip-ebookEmoji">📖</H5Txt>
<H5Box className="vip-ebookTitleRow">
<H5Txt className="vip-ebookTitle">《{e.title}》</H5Txt>
{isFree ? <H5Txt className="vip-freeBadge">免费</H5Txt> : null}
{locked ? <H5Txt className="vip-ebookLock">🔒</H5Txt> : null}
</H5Box>
<H5Txt className="vip-ebookDesc">{e.desc}</H5Txt>
<H5Txt className="vip-ebookCta">
{locked ? '开通VIP解锁 →' : '阅读 →'}
</H5Txt>
</H5Box>
)
})}
</H5Box>
</>
) : null}
</H5Box>
</H5Box>
) : null}
{/* LandingCTA */}
<H5Box className="vip-section vip-ctaSection" id="vip-cta">
<H5Box className="vip-ctaInner">
<H5Box className="vip-ctaGlow" aria-hidden />
<H5Box className="vip-ctaCard">
<H5Box className="vip-ctaPromoLine">
<H5Box className="vip-ctaPromoClickable">
<H5Box className="vip-ctaBadgePulse" />
<H5Txt>限时特惠</H5Txt>
{/* CompareSection */}
{vc.showCompare && vc.compare.length > 0 ? (
<H5Box className="vip-section">
<H5Txt className="vip-sectionTitle">{vc.compareTitle}</H5Txt>
<H5Txt className="vip-sectionDesc">{vc.compareDesc}</H5Txt>
<H5Box className="vip-compareWrap">
<H5Box className="vip-compareTable">
<H5Box className="vip-compareRow vip-compareRow--head">
<H5Txt className="vip-compareCell vip-compareCell--feature">权益</H5Txt>
<H5Txt className="vip-compareCell vip-compareCell--single">单品</H5Txt>
<H5Txt className="vip-compareCell vip-compareCell--member">会员</H5Txt>
</H5Box>
<H5Txt className="vip-ctaPromoDivider">·</H5Txt>
<H5Box className="vip-ctaPromoMain">
<H5Txt className="vip-ctaHighlight">{restoreDate}</H5Txt>
<H5Txt className="vip-ctaPromoSuffix">恢复原价</H5Txt>
</H5Box>
</H5Box>
<H5Box className="vip-ctaChips">
{CTA_CHIPS.map((c) => (
<H5Txt key={c} className="vip-ctaChip">
{c}
</H5Txt>
{vc.compare.map((row, i) => (
<H5Box
key={row.feature}
className={`vip-compareRow vip-compareRow--body${
i % 2 === 1 ? ' vip-compareRow--alt' : ''
}`}
>
<H5Txt className="vip-compareCell vip-compareCell--bodyFeature">
{row.feature}
</H5Txt>
<H5Txt className="vip-compareCell vip-compareCell--bodySingle">
{row.single}
</H5Txt>
<H5Txt className="vip-compareCell vip-compareCell--bodyMember">
{row.member}
</H5Txt>
</H5Box>
))}
</H5Box>
{offline ? (
<H5Txt className="vip-ctaOffline">📦 价格/文案来自离线配置</H5Txt>
) : null}
<H5Box className="vip-ctaActions">
<Button
className="vip-btnPrimary vip-btnLarge vip-ctaBtnPrimary"
loading={busy}
disabled={!isH5 && !payOk}
onClick={onJoin}
>
{busy ? '拉起支付…' : `🔒 ${cta}`}
</Button>
<Button className="vip-ctaBtnSecondary" onClick={() => void onLogin()}>
已有账号
</Button>
</H5Box>
{isH5 ? (
<H5Txt className="vip-ctaHint">浏览器请走门户 /vip 支付</H5Txt>
) : (
<H5Txt className="vip-ctaHint">微信小程序虚拟支付</H5Txt>
)}
</H5Box>
</H5Box>
</H5Box>
) : null}
{/* FAQSection */}
{vc.showFaq && vc.faq.length > 0 ? (
<H5Box className="vip-section vip-faqSection">
<H5Box className="vip-faqInner">
<H5Box className="vip-faqEyebrow">
<H5Box className="vip-faqEyebrowDot" />
<H5Txt>FAQ</H5Txt>
</H5Box>
<H5Txt className="vip-faqHeadline">{vc.faqTitle}</H5Txt>
<H5Txt className="vip-faqSub">{vc.faqSub}</H5Txt>
<H5Box className="vip-faqList">
{vc.faq.map((item, i) => {
const open = faqOpen === i
return (
<H5Box
key={item.q}
className={`vip-faqItem${open ? ' vip-faqItemOpen' : ''}`}
>
<Button
className="vip-faqTrigger"
onClick={() => setFaqOpen(open ? null : i)}
>
<Text className="vip-faqIndex">{i + 1}</Text>
<Text className="vip-faqQuestionText">{item.q}</Text>
<Text className="vip-faqChevron">▾</Text>
</Button>
<H5Box className={`vip-faqPanel${open ? ' vip-faqPanelOpen' : ''}`}>
<H5Txt className="vip-faqAnswer">{item.a}</H5Txt>
</H5Box>
</H5Box>
)
})}
</H5Box>
</H5Box>
</H5Box>
) : null}
{/* LandingCTA — reviewMode 仍展示,但不强调付费文案时可隐藏芯片 */}
{vc.showCta ? (
<H5Box className="vip-section vip-ctaSection" id="vip-cta">
<H5Box className="vip-ctaInner">
<H5Box className="vip-ctaGlow" aria-hidden />
<H5Box className="vip-ctaCard">
{!vc.reviewMode ? (
<H5Box className="vip-ctaPromoLine">
<H5Box className="vip-ctaPromoClickable">
<H5Box className="vip-ctaBadgePulse" />
<H5Txt>限时特惠</H5Txt>
</H5Box>
<H5Txt className="vip-ctaPromoDivider">·</H5Txt>
<H5Box className="vip-ctaPromoMain">
<H5Txt className="vip-ctaHighlight">{restoreDate}</H5Txt>
<H5Txt className="vip-ctaPromoSuffix">恢复原价</H5Txt>
</H5Box>
</H5Box>
) : null}
{!vc.reviewMode && vc.ctaChips.length > 0 ? (
<H5Box className="vip-ctaChips">
{vc.ctaChips.map((c) => (
<H5Txt key={c} className="vip-ctaChip">
{c}
</H5Txt>
))}
</H5Box>
) : null}
{offline ? (
<H5Txt className="vip-ctaOffline">📦 价格/文案来自离线配置</H5Txt>
) : null}
<H5Box className="vip-ctaActions">
<Button
className="vip-btnPrimary vip-btnLarge vip-ctaBtnPrimary"
loading={busy}
disabled={!isH5 && !payOk}
onClick={onJoin}
>
{busy ? '拉起支付…' : `🔒 ${cta}`}
</Button>
<Button className="vip-ctaBtnSecondary" onClick={() => void onLogin()}>
{vc.ctaSecondary || '已有账号'}
</Button>
</H5Box>
{isH5 ? (
<H5Txt className="vip-ctaHint">{vc.ctaHintH5}</H5Txt>
) : (
<H5Txt className="vip-ctaHint">{vc.ctaHintWeapp}</H5Txt>
)}
</H5Box>
</H5Box>
</H5Box>
) : null}
</H5Box>
</H5Box>
</H5Box>

View File

@ -0,0 +1,226 @@
/**
* VIP 正式内容远程库 — 电子书 / 课程 / 课时
* 网络失败 → 包内 vipEbooks / vipCourse / vipLessonContent 兜底
*/
import Taro from '@tarojs/taro'
import { API_BASE, APP_TARGET, WEB_BASE } from '../utils/config'
import {
VIP_EBOOKS,
type VipEbookId,
type VipEbookPack,
resolveVipEbookId,
} from '../data/vipEbooks'
import {
VIP_COURSE_MODULES,
type VipLesson,
type VipModule,
getVipLesson as getLocalLesson,
} from '../data/vipCourse'
import { VIP_LESSON_CONTENT } from '../data/vipLessonContent'
export type VipCoursePack = {
id: string
title: string
modules: VipModule[]
}
export type VipLessonDoc = {
markdown: string
videoUrl: string
}
type LibraryPayload = {
ok?: boolean
version?: number
ebooks?: Record<string, VipEbookPack>
course?: VipCoursePack
lessons?: Record<string, VipLessonDoc>
}
const CACHE_KEY = 'nomadro_vip_library_v1'
const CACHE_TTL_MS = 1000 * 60 * 30
let memory: LibraryPayload | null = null
function urls(path: string): string[] {
if (APP_TARGET === 'h5') return [`/ebook-api${path}`, path]
return [`${API_BASE}${path}`, `${WEB_BASE}${path}`]
}
function readCache(): LibraryPayload | null {
try {
const raw = Taro.getStorageSync(CACHE_KEY)
if (!raw) return null
const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw
if (Date.now() - Number(parsed.ts || 0) > CACHE_TTL_MS * 48) return null
return parsed.data as LibraryPayload
} catch {
return null
}
}
function writeCache(data: LibraryPayload) {
try {
Taro.setStorageSync(CACHE_KEY, JSON.stringify({ ts: Date.now(), data }))
} catch {
/* ignore */
}
}
async function fetchJson(path: string): Promise<LibraryPayload | null> {
for (const url of urls(path)) {
try {
const res = await Taro.request({ url, method: 'GET', timeout: 8000 })
if (res.statusCode >= 400) continue
const body = res.data as LibraryPayload
if (body && (body.ebooks || body.course || body.ok)) return body
} catch {
/* next */
}
}
return null
}
export async function loadVipLibrary(force = false): Promise<{
data: LibraryPayload
fromOffline: boolean
}> {
if (!force && memory) return { data: memory, fromOffline: false }
const cached = readCache()
try {
const remote = await fetchJson('/api/vip/library')
if (remote && (remote.ebooks || remote.course)) {
memory = remote
writeCache(remote)
return { data: remote, fromOffline: false }
}
} catch {
/* fallthrough */
}
if (cached) {
memory = cached
return { data: cached, fromOffline: true }
}
const bundle: LibraryPayload = {
ok: true,
ebooks: VIP_EBOOKS,
course: { id: 'cloudphone', title: '云手机实战课', modules: VIP_COURSE_MODULES },
lessons: VIP_LESSON_CONTENT,
}
memory = bundle
return { data: bundle, fromOffline: true }
}
export async function loadVipEbook(id?: string): Promise<{
book: VipEbookPack
fromOffline: boolean
}> {
const bookId = resolveVipEbookId(id)
const local = VIP_EBOOKS[bookId]
try {
const remote = await fetchJson(`/api/vip/ebooks/${bookId}`)
const book = (remote as { ebook?: VipEbookPack } | null)?.ebook
if (book && Array.isArray(book.sections) && book.sections.length) {
return {
book: {
...local,
...book,
id: bookId as VipEbookId,
headers: book.headers || local.headers,
sections: book.sections,
},
fromOffline: false,
}
}
} catch {
/* offline */
}
const lib = await loadVipLibrary()
const fromLib = lib.data.ebooks?.[bookId]
if (fromLib?.sections?.length) {
return {
book: { ...local, ...fromLib, id: bookId as VipEbookId },
fromOffline: lib.fromOffline,
}
}
return { book: local, fromOffline: true }
}
export async function loadVipCourse(): Promise<{
course: VipCoursePack
fromOffline: boolean
}> {
try {
const remote = await fetchJson('/api/vip/course')
const course = (remote as { course?: VipCoursePack } | null)?.course
if (course?.modules?.length) {
return { course, fromOffline: false }
}
} catch {
/* offline */
}
const lib = await loadVipLibrary()
if (lib.data.course?.modules?.length) {
return { course: lib.data.course, fromOffline: lib.fromOffline }
}
return {
course: { id: 'cloudphone', title: '云手机实战课', modules: VIP_COURSE_MODULES },
fromOffline: true,
}
}
export async function loadVipLesson(
moduleIndex: number,
lessonIndex: number,
): Promise<{
lesson: VipLesson | null
doc: VipLessonDoc
modules: VipModule[]
fromOffline: boolean
}> {
const { course, fromOffline } = await loadVipCourse()
const modules = course.modules?.length ? course.modules : VIP_COURSE_MODULES
const lesson =
modules[moduleIndex]?.lessons?.[lessonIndex] ||
getLocalLesson(moduleIndex, lessonIndex)
if (!lesson) {
return {
lesson: null,
doc: { markdown: '', videoUrl: '' },
modules,
fromOffline,
}
}
const localDoc = VIP_LESSON_CONTENT[lesson.key] || {
markdown: '',
videoUrl: lesson.videoUrl || '',
}
try {
const remote = await fetchJson(`/api/vip/lessons/${encodeURIComponent(lesson.key)}`)
const body = remote as { lesson?: VipLessonDoc; meta?: VipLesson } | null
if (body?.lesson || body?.meta) {
return {
lesson: { ...lesson, ...(body.meta || {}), key: lesson.key },
doc: {
markdown: body.lesson?.markdown ?? localDoc.markdown,
videoUrl: body.lesson?.videoUrl || body.meta?.videoUrl || lesson.videoUrl || localDoc.videoUrl,
},
modules,
fromOffline: false,
}
}
} catch {
/* offline */
}
const lib = await loadVipLibrary()
const fromLib = lib.data.lessons?.[lesson.key]
return {
lesson,
doc: {
markdown: fromLib?.markdown ?? localDoc.markdown,
videoUrl: fromLib?.videoUrl || lesson.videoUrl || localDoc.videoUrl,
},
modules,
fromOffline: fromOffline || lib.fromOffline,
}
}

View File

@ -3,6 +3,7 @@ import Taro from '@tarojs/taro'
import { View, Text, Image } from '@tarojs/components'
import ttGroupQr from '../assets/tt-group-qr.png'
import wechatOaQr from '../assets/wechat-oa-qr.png'
import { resolveTtJoin } from '../data/remoteConfig.defaults'
import { loadRemoteConfig } from '../services/remoteConfig'
import { trackJoinGroup } from '../utils/track'
import './WechatOaModal.scss'
@ -83,17 +84,23 @@ export function WechatOaModal({
const cfg = result.config
const offline = result.fromOffline
// 抖音只读 platforms.tt.join,不读微信顶层 flags/copy
const ttJoin = resolveTtJoin(cfg)
setCopy({
wechatName: String(cfg.copy?.wechatOaName || WECHAT_OA_NAME),
wechatName: String(ttJoin.wechatOaName || WECHAT_OA_NAME),
douyinHint: String(
cfg.copy?.joinGroupDouyinHint ||
'打开抖音搜群「数字游民」或扫码进群',
ttJoin.joinGroupDouyinHint || '打开抖音搜群「数字游民」或扫码进群',
),
douyinQr: String(cfg.copy?.joinGroupDouyinQr || ''),
douyinQr: String(ttJoin.joinGroupDouyinQr || ''),
})
// 失败 / 离线:默认抖音;联网:严格跟后台
const ch = offline ? 'douyin' : resolveChannelOnline(cfg.flags || {})
// 失败 / 离线:默认抖音;联网:严格跟抖音后台 platforms.tt.join
const ch = offline
? 'douyin'
: resolveChannelOnline({
joinGroupWechat: ttJoin.joinGroupWechat,
joinGroupDouyin: ttJoin.joinGroupDouyin,
})
if (ch === 'none') {
Taro.showToast({ title: '加群暂未开放', icon: 'none' })

View File

@ -31,6 +31,16 @@ export type TtBookContent = {
/** 抖音首页变体:bmi=BMI指数首页;hub=数字游民门户 */
export type TtHomeVariant = 'bmi' | 'hub'
/** 抖音加群弹窗(仅 platforms.tt.join,不读顶层微信 flags) */
export type TtJoinConfig = {
joinGroupWechat: boolean
joinGroupDouyin: boolean
socialFollowAuto: boolean
wechatOaName: string
joinGroupDouyinHint: string
joinGroupDouyinQr: string
}
export type TtPlatformConfig = {
/** 首页 A/B:默认 bmi;后台可切 hub */
homeVariant: TtHomeVariant
@ -40,6 +50,7 @@ export type TtPlatformConfig = {
community: ModuleToggle
}
bookContent: TtBookContent
join: TtJoinConfig
}
export type NomadroRemoteConfig = {
@ -97,6 +108,15 @@ export const DEFAULT_TT_BOOK_CONTENT: TtBookContent = {
})),
}
export const DEFAULT_TT_JOIN: TtJoinConfig = {
joinGroupWechat: true,
joinGroupDouyin: false,
socialFollowAuto: false,
wechatOaName: '异度世界',
joinGroupDouyinHint: '打开抖音搜群「数字游民」或扫码进群',
joinGroupDouyinQr: '',
}
export const DEFAULT_TT_PLATFORM: TtPlatformConfig = {
/** 默认 BMI 指数首页;后台可切 hub */
homeVariant: 'bmi',
@ -121,6 +141,7 @@ export const DEFAULT_TT_PLATFORM: TtPlatformConfig = {
},
},
bookContent: DEFAULT_TT_BOOK_CONTENT,
join: { ...DEFAULT_TT_JOIN },
}
export const DEFAULT_REMOTE_CONFIG: NomadroRemoteConfig = {
@ -198,6 +219,23 @@ function resolveTtHomeVariant(v: unknown, fallback: TtHomeVariant): TtHomeVarian
return v === 'hub' || v === 'bmi' ? v : fallback
}
function mergeTtJoin(base: TtJoinConfig, patch?: Partial<TtJoinConfig> | null): TtJoinConfig {
if (!patch) return { ...base }
return {
joinGroupWechat:
typeof patch.joinGroupWechat === 'boolean' ? patch.joinGroupWechat : base.joinGroupWechat,
joinGroupDouyin:
typeof patch.joinGroupDouyin === 'boolean' ? patch.joinGroupDouyin : base.joinGroupDouyin,
socialFollowAuto:
typeof patch.socialFollowAuto === 'boolean' ? patch.socialFollowAuto : base.socialFollowAuto,
wechatOaName: patch.wechatOaName != null ? String(patch.wechatOaName) : base.wechatOaName,
joinGroupDouyinHint:
patch.joinGroupDouyinHint != null ? String(patch.joinGroupDouyinHint) : base.joinGroupDouyinHint,
joinGroupDouyinQr:
patch.joinGroupDouyinQr != null ? String(patch.joinGroupDouyinQr) : base.joinGroupDouyinQr,
}
}
export function mergeTtPlatform(partial?: Partial<TtPlatformConfig> | null): TtPlatformConfig {
const base = JSON.parse(JSON.stringify(DEFAULT_TT_PLATFORM)) as TtPlatformConfig
if (!partial) return base
@ -209,9 +247,15 @@ export function mergeTtPlatform(partial?: Partial<TtPlatformConfig> | null): TtP
community: mergeModuleToggle(base.modules.community, partial.modules?.community),
},
bookContent: mergeTtBookContent(base.bookContent, partial.bookContent),
join: mergeTtJoin(base.join, partial.join),
}
}
/** 抖音加群渠道:只看 platforms.tt.join */
export function resolveTtJoin(config: NomadroRemoteConfig): TtJoinConfig {
return mergeTtJoin(DEFAULT_TT_JOIN, config.platforms?.tt?.join)
}
/** 抖音当前首页变体 */
export function resolveTtHomeVariantFromConfig(config: NomadroRemoteConfig): TtHomeVariant {
return resolveTtHomeVariant(config.platforms?.tt?.homeVariant, DEFAULT_TT_PLATFORM.homeVariant)