Add VIP knowledge community and device shop with native weapp UX.
Document memo/shop admin routes, deploy scripts, and cache-first feed performance in README. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
98a54730ff
commit
3f7528f824
15
README.md
15
README.md
@ -35,9 +35,20 @@ scripts/ 本地开发 / 清理(dev-api · clean-artifacts)
|
||||
| 专题课 | `pages/vip-course/index?id=` | `cloudphone` / `livestream` / `indie` / `aiagent` |
|
||||
| 课时 | `pages/vip-lesson/index` | 原生 Video + 配套 markdown |
|
||||
| 电子书 | `pages/vip-ebook/index?id=` | `nomad`(免费)/ `cloudphone`(VIP),目录抽屉 |
|
||||
| **知识社群** | `pages/vip-memo` · `vip-memo-detail` | 知识星球风格:精华/收藏/Markdown/图/#话题;缓存秒开 |
|
||||
| **设备商城** | `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/memo`)· **电商**(`/wechat/shop`)。
|
||||
下单:`POST /api/ebook/pay/vip-order` · 商城 ` /api/ebook/shop/*` · 社群 `/api/ebook/memo/*`。
|
||||
|
||||
部署脚本(本地构建 admin + 同步 API):
|
||||
|
||||
```bash
|
||||
python apps/admin/deploy/deploy_shop.py # 电商
|
||||
python apps/admin/deploy/deploy_memo.py # 知识社群
|
||||
```
|
||||
|
||||
内容种子:`h5/src/data/vipEbooks.ts` · `vipLessonContent.ts`(可由 `h5/scripts/extract-vip-*.py` 从 `src/modules/vip/app/data` 重生)。
|
||||
后台 VIP 方案:`apps/admin` → VIP;下单 `POST /api/ebook/pay/vip-order`。
|
||||
|
||||
## 本地
|
||||
|
||||
|
||||
@ -17,9 +17,28 @@ pnpm build:admin
|
||||
|
||||
| 入口 | 路径 | 说明 |
|
||||
|------|------|------|
|
||||
| 微信小程序 | `/wechat/*` | 读者 · 订单 · 书籍 · 埋点 |
|
||||
| 微信小程序 | `/wechat/*` | 读者 · 订单 · 书籍 · VIP · **知识社群** · **电商** · 埋点 |
|
||||
| 抖音小程序 | `/douyin/*` | 首页 A/B · 入口 · **加群弹窗** · 小册 · 验收 |
|
||||
|
||||
### 微信:知识社群(对标知识星球)
|
||||
|
||||
路径 **`/wechat/memo`**:
|
||||
|
||||
- 博主发帖(Markdown / 图片 URL / #话题 / 置顶 / 精华)
|
||||
- 星球名称、简介、公告与权限(默认仅博主发帖,会员点赞/评论/收藏)
|
||||
- 小程序页:`vip-memo` 列表(全部/精华/最新/收藏)· `vip-memo-detail` 阅读页
|
||||
- API:`/api/ebook/memo/*` · 管理 `/api/admin/memo/*`
|
||||
- 部署:`python apps/admin/deploy/deploy_memo.py`
|
||||
|
||||
### 微信:设备商城
|
||||
|
||||
路径 **`/wechat/shop`**:
|
||||
|
||||
- 商品(虚拟卡密 / 实物发货)、订单履约
|
||||
- 小程序:`vip-store` · `vip-store-detail` · `vip-store-orders`(含 `chooseAddress`)
|
||||
- API:`/api/ebook/shop*` · 支付扩展 `shop-order`
|
||||
- 部署:`python apps/admin/deploy/deploy_shop.py`
|
||||
|
||||
### 抖音:加群弹窗(非独立页)
|
||||
|
||||
配置在 **`/douyin/modules`**(侧栏「首页与入口」)同页下半段:
|
||||
@ -37,6 +56,8 @@ API:`GET/PUT /api/admin/join-group`
|
||||
```bash
|
||||
pnpm build:admin
|
||||
python apps/admin/deploy/deploy_join_group.py # 前端 dist + 加群 API
|
||||
python apps/admin/deploy/deploy_memo.py # 知识社群
|
||||
python apps/admin/deploy/deploy_shop.py # 设备商城
|
||||
# 或仅前端:python apps/admin/deploy/_deploy_douyin_ui.py
|
||||
```
|
||||
|
||||
|
||||
@ -9,7 +9,9 @@ SPA 根目录即 `apps/admin`(已拍平,无嵌套 `admin/`)。
|
||||
cd apps/admin
|
||||
pnpm build
|
||||
python deploy/redeploy_admin.py # 仅前端 dist
|
||||
python deploy/deploy_memo.py # 知识社群 API + admin
|
||||
python deploy/deploy_shop.py # 设备商城 API + admin
|
||||
# 或历史全量:python deploy/deploy.py(backend 已迁 apps/api,慎用)
|
||||
```
|
||||
|
||||
常用文件:`redeploy_admin.py`、`deploy.py`、nginx / systemd 配置,以及历史调试脚本。
|
||||
常用文件:`redeploy_admin.py`、`deploy_memo.py`、`deploy_shop.py`、`deploy.py`、nginx / systemd 配置。
|
||||
|
||||
205
apps/admin/deploy/deploy_memo.py
Normal file
205
apps/admin/deploy/deploy_memo.py
Normal file
@ -0,0 +1,205 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Deploy VIP 社群 (memo feed) admin + API to 82.157.112.245."""
|
||||
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"
|
||||
|
||||
|
||||
def to_app_pkg(text: str) -> str:
|
||||
return text.replace("ebook_svc.", "app.")
|
||||
|
||||
|
||||
def _remote_script() -> str:
|
||||
return r'''#!/bin/bash
|
||||
set -euo pipefail
|
||||
cd /tmp
|
||||
rm -rf memo-unpack && mkdir memo-unpack
|
||||
tar -xzf memo-release.tar.gz -C memo-unpack
|
||||
|
||||
if [ -d memo-unpack/admin-dist ]; then
|
||||
sudo rsync -a --delete memo-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
|
||||
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 memo-unpack/backend/routers/memo.py "$B/routers/"
|
||||
sudo cp memo-unpack/backend/routers/memo_admin.py "$B/routers/"
|
||||
sudo cp memo-unpack/backend/services/memo_store.py "$B/services/"
|
||||
|
||||
MAIN="$B/main.py"
|
||||
export MAIN
|
||||
sudo -E python3 <<'PY'
|
||||
from pathlib import Path
|
||||
import os, re
|
||||
p = Path(os.environ["MAIN"])
|
||||
t = p.read_text(encoding="utf-8")
|
||||
changed = False
|
||||
|
||||
m = re.search(r"from app\.routers import ([^\n]+)", t)
|
||||
if not m:
|
||||
raise SystemExit("no routers import")
|
||||
line = m.group(0)
|
||||
names = m.group(1)
|
||||
parts = [x.strip() for x in names.split(",")]
|
||||
for mod in ("memo", "memo_admin"):
|
||||
if mod not in parts:
|
||||
names = names.rstrip() + f", {mod}"
|
||||
changed = True
|
||||
print("import +", mod)
|
||||
newt = f"from app.routers import {names}"
|
||||
if newt != line:
|
||||
t = t.replace(line, newt, 1)
|
||||
changed = True
|
||||
|
||||
if "include_router(memo.router" not in t:
|
||||
if re.search(r"app\.include_router\(shop\.router,\s*prefix=_api_prefix\)", t):
|
||||
t = re.sub(
|
||||
r"(app\.include_router\(shop\.router,\s*prefix=_api_prefix\))",
|
||||
r"\1\n app.include_router(memo.router, prefix=_api_prefix)",
|
||||
t,
|
||||
count=1,
|
||||
)
|
||||
changed = True
|
||||
print("memo in _api_prefix loop")
|
||||
elif re.search(r"app\.include_router\(track\.router,\s*prefix=_api_prefix\)", t):
|
||||
t = re.sub(
|
||||
r"(app\.include_router\(track\.router,\s*prefix=_api_prefix\))",
|
||||
r"\1\n app.include_router(memo.router, prefix=_api_prefix)",
|
||||
t,
|
||||
count=1,
|
||||
)
|
||||
changed = True
|
||||
print("memo after track loop")
|
||||
else:
|
||||
raise SystemExit("failed memo include in loop")
|
||||
|
||||
if "include_router(memo_admin.router)" not in t:
|
||||
for a in (
|
||||
"app.include_router(shop_admin.router)",
|
||||
"app.include_router(vip_admin.router)",
|
||||
"app.include_router(admin.router)",
|
||||
):
|
||||
if a in t:
|
||||
t = t.replace(a, a + "\napp.include_router(memo_admin.router)", 1)
|
||||
changed = True
|
||||
print("memo_admin after", a)
|
||||
break
|
||||
if "include_router(memo_admin.router)" not in t:
|
||||
raise SystemExit("failed memo_admin include")
|
||||
|
||||
if changed:
|
||||
p.write_text(t, encoding="utf-8")
|
||||
print("main.py patched")
|
||||
else:
|
||||
print("main.py already ok")
|
||||
PY
|
||||
|
||||
sudo systemctl restart nomadmini-api
|
||||
sleep 5
|
||||
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 "memo_page %{http_code}\n" https://admin.nomadro.cn/wechat/memo
|
||||
curl -sk http://127.0.0.1:8010/health; echo
|
||||
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/memo | python3 -c "import sys,json; d=json.load(sys.stdin); print('memo_admin', d.get('ok'), d.get('stats'), (d.get('settings') or {}).get('canPost'))"
|
||||
fi
|
||||
curl -sk http://127.0.0.1:8010/openapi.json | python3 -c "import sys,json; p=json.load(sys.stdin).get('paths') or {}; ks=[k for k in p if 'memo' in k]; print('memo_paths', len(ks), ks[:10])"
|
||||
rm -rf memo-unpack memo-release.tar.gz
|
||||
echo DONE
|
||||
'''
|
||||
|
||||
|
||||
def main() -> int:
|
||||
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",
|
||||
)
|
||||
print((r.stdout or "")[-600:], flush=True)
|
||||
if r.returncode != 0:
|
||||
print(r.stderr or "", flush=True)
|
||||
return r.returncode or 1
|
||||
|
||||
dist = ROOT / "dist"
|
||||
if not (dist / "index.html").exists():
|
||||
print("missing admin dist")
|
||||
return 1
|
||||
|
||||
files = (
|
||||
("backend/routers/memo.py", EBOOK / "routers" / "memo.py"),
|
||||
("backend/routers/memo_admin.py", EBOOK / "routers" / "memo_admin.py"),
|
||||
("backend/services/memo_store.py", EBOOK / "services" / "memo_store.py"),
|
||||
)
|
||||
|
||||
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 files:
|
||||
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)
|
||||
|
||||
remote = _remote_script()
|
||||
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/memo-release.tar.gz", "wb") as rf:
|
||||
rf.write(payload)
|
||||
with sftp.file("/tmp/memo-deploy.sh", "w") as sf:
|
||||
sf.write(remote.replace("\r\n", "\n"))
|
||||
sftp.chmod("/tmp/memo-deploy.sh", 0o755)
|
||||
sftp.close()
|
||||
print("uploaded", flush=True)
|
||||
|
||||
_, stdout, _ = c.exec_command("bash /tmp/memo-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
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
227
apps/admin/deploy/deploy_shop.py
Normal file
227
apps/admin/deploy/deploy_shop.py
Normal file
@ -0,0 +1,227 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Deploy WeChat shop (电商) admin UI + API to 82.157.112.245.
|
||||
|
||||
- Admin SPA → /www/wwwroot/admin.nomadro.cn
|
||||
- shop / shop_admin / shop_store + pay.py / store.py (shop fulfill)
|
||||
- Patch main.py include_router (idempotent)
|
||||
- Restart nomadmini-api
|
||||
"""
|
||||
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.")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
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",
|
||||
)
|
||||
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
|
||||
|
||||
files = (
|
||||
("backend/routers/shop.py", EBOOK / "routers" / "shop.py"),
|
||||
("backend/routers/shop_admin.py", EBOOK / "routers" / "shop_admin.py"),
|
||||
("backend/services/shop_store.py", EBOOK / "services" / "shop_store.py"),
|
||||
("backend/routers/pay.py", EBOOK / "routers" / "pay.py"),
|
||||
("backend/services/store.py", EBOOK / "services" / "store.py"),
|
||||
)
|
||||
|
||||
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 files:
|
||||
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)
|
||||
|
||||
remote = _remote_script()
|
||||
|
||||
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/shop-release.tar.gz", "wb") as rf:
|
||||
rf.write(payload)
|
||||
with sftp.file("/tmp/shop-deploy.sh", "w") as sf:
|
||||
sf.write(remote.replace("\r\n", "\n"))
|
||||
sftp.chmod("/tmp/shop-deploy.sh", 0o755)
|
||||
sftp.close()
|
||||
print("uploaded", flush=True)
|
||||
|
||||
_, stdout, _ = c.exec_command("bash /tmp/shop-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
|
||||
|
||||
|
||||
def _remote_script() -> str:
|
||||
return r'''#!/bin/bash
|
||||
set -euo pipefail
|
||||
cd /tmp
|
||||
rm -rf shop-unpack && mkdir shop-unpack
|
||||
tar -xzf shop-release.tar.gz -C shop-unpack
|
||||
|
||||
if [ -d shop-unpack/admin-dist ]; then
|
||||
sudo rsync -a --delete shop-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
|
||||
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 shop-unpack/backend/routers/shop.py "$B/routers/"
|
||||
sudo cp shop-unpack/backend/routers/shop_admin.py "$B/routers/"
|
||||
sudo cp shop-unpack/backend/services/shop_store.py "$B/services/"
|
||||
sudo cp shop-unpack/backend/routers/pay.py "$B/routers/"
|
||||
sudo cp shop-unpack/backend/services/store.py "$B/services/"
|
||||
|
||||
MAIN="$B/main.py"
|
||||
export MAIN
|
||||
sudo -E python3 <<'PY'
|
||||
from pathlib import Path
|
||||
import os, re
|
||||
p = Path(os.environ["MAIN"])
|
||||
t = p.read_text(encoding="utf-8")
|
||||
changed = False
|
||||
|
||||
m = re.search(r"from app\.routers import ([^\n]+)", t)
|
||||
if not m:
|
||||
raise SystemExit("no routers import")
|
||||
line = m.group(0)
|
||||
names = m.group(1)
|
||||
for mod in ("shop", "shop_admin", "vip_admin", "join_group_admin", "public_config"):
|
||||
# crude: check token
|
||||
parts = [x.strip() for x in names.split(",")]
|
||||
if mod not in parts:
|
||||
names = names.rstrip() + f", {mod}"
|
||||
changed = True
|
||||
print("import +", mod)
|
||||
newt = f"from app.routers import {names}"
|
||||
if newt != line:
|
||||
t = t.replace(line, newt, 1)
|
||||
changed = True
|
||||
|
||||
# shop under api prefix loop
|
||||
if "include_router(shop.router" not in t:
|
||||
if re.search(r"app\.include_router\(track\.router,\s*prefix=_api_prefix\)", t):
|
||||
t = re.sub(
|
||||
r"(app\.include_router\(track\.router,\s*prefix=_api_prefix\))",
|
||||
r"\1\n app.include_router(shop.router, prefix=_api_prefix)",
|
||||
t,
|
||||
count=1,
|
||||
)
|
||||
changed = True
|
||||
print("shop in _api_prefix loop")
|
||||
elif re.search(r"app\.include_router\(track\.router,\s*prefix=_prefix\)", t):
|
||||
t = re.sub(
|
||||
r"(app\.include_router\(track\.router,\s*prefix=_prefix\))",
|
||||
r"\1\n app.include_router(shop.router, prefix=_prefix)",
|
||||
t,
|
||||
count=1,
|
||||
)
|
||||
changed = True
|
||||
print("shop in _prefix loop")
|
||||
else:
|
||||
for a in ("app.include_router(track.router)", "app.include_router(pay.router)"):
|
||||
if a in t and "include_router(shop.router)" not in t:
|
||||
t = t.replace(a, a + "\napp.include_router(shop.router)", 1)
|
||||
changed = True
|
||||
print("shop include fallback")
|
||||
break
|
||||
|
||||
if "include_router(shop_admin.router)" not in t:
|
||||
for a in (
|
||||
"app.include_router(vip_admin.router)",
|
||||
"app.include_router(join_group_admin.router)",
|
||||
"app.include_router(douyin_admin.router)",
|
||||
"app.include_router(admin.router)",
|
||||
):
|
||||
if a in t:
|
||||
t = t.replace(a, a + "\napp.include_router(shop_admin.router)", 1)
|
||||
changed = True
|
||||
print("shop_admin include after", a)
|
||||
break
|
||||
if "include_router(shop_admin.router)" not in t:
|
||||
raise SystemExit("failed shop_admin include")
|
||||
|
||||
if changed:
|
||||
p.write_text(t, encoding="utf-8")
|
||||
print("main.py patched")
|
||||
else:
|
||||
print("main.py already ok")
|
||||
PY
|
||||
|
||||
sudo systemctl restart nomadmini-api
|
||||
sleep 5
|
||||
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 "shop_page %{http_code}\n" https://admin.nomadro.cn/wechat/shop
|
||||
curl -sk http://127.0.0.1:8010/health; echo
|
||||
curl -sk http://127.0.0.1:8010/api/shop/catalog | python3 -c "import sys,json; d=json.load(sys.stdin); print('catalog', d.get('ok'), len(d.get('products') or []))" || echo catalog_fail
|
||||
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/shop/products | python3 -c "import sys,json; d=json.load(sys.stdin); ps=d.get('items') or []; print('admin_products', len(ps)); print([(p.get('id'), p.get('wxProductId'), p.get('priceFen')) for p in ps[:4]])"
|
||||
fi
|
||||
curl -sk http://127.0.0.1:8010/openapi.json | python3 -c "import sys,json; p=json.load(sys.stdin).get('paths') or {}; ks=[k for k in p if 'shop' in k]; print('shop_paths', len(ks), ks[:12])"
|
||||
rm -rf shop-unpack shop-release.tar.gz
|
||||
echo DONE
|
||||
'''
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@ -10,6 +10,8 @@ import Users from './pages/Users'
|
||||
import Events from './pages/Events'
|
||||
import Checklist from './pages/Checklist'
|
||||
import Vip from './pages/Vip'
|
||||
import Shop from './pages/Shop'
|
||||
import Memo from './pages/Memo'
|
||||
import Layout from './components/Layout'
|
||||
import DouyinLayout from './pages/douyin/DouyinLayout'
|
||||
import DouyinOverview from './pages/douyin/DouyinOverview'
|
||||
@ -64,6 +66,8 @@ export default function App() {
|
||||
<Route index element={<Dashboard />} />
|
||||
<Route path="books/:id" element={<BookEdit />} />
|
||||
<Route path="vip" element={<Vip />} />
|
||||
<Route path="shop" element={<Shop />} />
|
||||
<Route path="memo" element={<Memo />} />
|
||||
<Route path="orders" element={<Orders />} />
|
||||
<Route path="users" element={<Users />} />
|
||||
<Route path="events" element={<Events />} />
|
||||
@ -92,6 +96,8 @@ export default function App() {
|
||||
<Route path="/events" element={<WechatRedirect to="/wechat/events" />} />
|
||||
<Route path="/checklist" element={<WechatRedirect to="/wechat/checklist" />} />
|
||||
<Route path="/vip" element={<WechatRedirect to="/wechat/vip" />} />
|
||||
<Route path="/shop" element={<WechatRedirect to="/wechat/shop" />} />
|
||||
<Route path="/memo" element={<WechatRedirect to="/wechat/memo" />} />
|
||||
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
|
||||
@ -20,6 +20,8 @@ export default function Layout() {
|
||||
</NavLink>
|
||||
<NavLink to="/wechat/books/default">书籍与试读%</NavLink>
|
||||
<NavLink to="/wechat/vip">VIP</NavLink>
|
||||
<NavLink to="/wechat/shop">电商</NavLink>
|
||||
<NavLink to="/wechat/memo">知识社群</NavLink>
|
||||
<NavLink to="/wechat/users">读者</NavLink>
|
||||
<NavLink to="/wechat/orders">订单</NavLink>
|
||||
<NavLink to="/wechat/events">埋点</NavLink>
|
||||
|
||||
469
apps/admin/src/pages/Memo.tsx
Normal file
469
apps/admin/src/pages/Memo.tsx
Normal file
@ -0,0 +1,469 @@
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { api } from '../api'
|
||||
import './BookEdit.css'
|
||||
|
||||
type Settings = {
|
||||
enabled: boolean
|
||||
canPost: boolean
|
||||
canComment: boolean
|
||||
canLike: boolean
|
||||
canFavorite: boolean
|
||||
canUpload: boolean
|
||||
adminOnlyPost: boolean
|
||||
requireVip: boolean
|
||||
maxContentLen: number
|
||||
maxImages: number
|
||||
planetName: string
|
||||
planetDesc: string
|
||||
notice: string
|
||||
}
|
||||
|
||||
type MemoResource = { type: string; url: string }
|
||||
|
||||
type Memo = {
|
||||
id: string
|
||||
openid: string
|
||||
nickname: string
|
||||
title?: string
|
||||
content: string
|
||||
resources?: MemoResource[]
|
||||
tags?: string[]
|
||||
pinned: boolean
|
||||
featured?: boolean
|
||||
status: string
|
||||
likeCount: number
|
||||
commentCount: number
|
||||
favoriteCount?: number
|
||||
createdAt: number
|
||||
}
|
||||
|
||||
const emptySettings: Settings = {
|
||||
enabled: true,
|
||||
canPost: false,
|
||||
canComment: true,
|
||||
canLike: true,
|
||||
canFavorite: true,
|
||||
canUpload: true,
|
||||
adminOnlyPost: true,
|
||||
requireVip: true,
|
||||
maxContentLen: 20000,
|
||||
maxImages: 9,
|
||||
planetName: 'Nomadro 知识社群',
|
||||
planetDesc: '博主分享实战干货,会员阅读互动',
|
||||
notice: '',
|
||||
}
|
||||
|
||||
type Tab = 'feed' | 'planet'
|
||||
|
||||
export default function MemoAdmin() {
|
||||
const [tab, setTab] = useState<Tab>('feed')
|
||||
const [settings, setSettings] = useState<Settings>(emptySettings)
|
||||
const [items, setItems] = useState<Memo[]>([])
|
||||
const [title, setTitle] = useState('')
|
||||
const [draft, setDraft] = useState('')
|
||||
const [imgUrls, setImgUrls] = useState('')
|
||||
const [pinNew, setPinNew] = useState(false)
|
||||
const [featNew, setFeatNew] = useState(false)
|
||||
const [err, setErr] = useState('')
|
||||
const [msg, setMsg] = useState('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [stats, setStats] = useState({
|
||||
memos: 0,
|
||||
comments: 0,
|
||||
likes: 0,
|
||||
favorites: 0,
|
||||
featured: 0,
|
||||
})
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setErr('')
|
||||
const data = await api<{
|
||||
settings: Settings
|
||||
stats: typeof stats
|
||||
recent: Memo[]
|
||||
}>('/api/admin/memo')
|
||||
setSettings({ ...emptySettings, ...(data.settings || {}) })
|
||||
setStats({
|
||||
memos: 0,
|
||||
comments: 0,
|
||||
likes: 0,
|
||||
favorites: 0,
|
||||
featured: 0,
|
||||
...(data.stats || {}),
|
||||
})
|
||||
setItems(data.recent || [])
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
load().catch((e) => setErr(e.message || '加载失败'))
|
||||
}, [load])
|
||||
|
||||
async function saveSettings(patch: Partial<Settings>, hint: string) {
|
||||
setBusy(true)
|
||||
setMsg('')
|
||||
setErr('')
|
||||
try {
|
||||
const saved = await api<Settings & { ok?: boolean }>('/api/admin/memo/settings', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(patch),
|
||||
})
|
||||
setSettings({ ...emptySettings, ...saved })
|
||||
setMsg(hint)
|
||||
} catch (e) {
|
||||
setErr((e as Error).message || '保存失败')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
function parseResources(): MemoResource[] {
|
||||
return imgUrls
|
||||
.split(/[\n,]+/)
|
||||
.map((s) => s.trim())
|
||||
.filter((s) => /^https?:\/\//i.test(s))
|
||||
.slice(0, settings.maxImages || 9)
|
||||
.map((url) => ({ type: 'image', url }))
|
||||
}
|
||||
|
||||
async function publish() {
|
||||
const resources = parseResources()
|
||||
if (!draft.trim() && !resources.length) return
|
||||
setBusy(true)
|
||||
setErr('')
|
||||
setMsg('')
|
||||
try {
|
||||
await api('/api/admin/memo/memos', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
title: title.trim(),
|
||||
content: draft.trim(),
|
||||
nickname: '博主',
|
||||
pinned: pinNew,
|
||||
featured: featNew,
|
||||
resources,
|
||||
}),
|
||||
})
|
||||
setTitle('')
|
||||
setDraft('')
|
||||
setImgUrls('')
|
||||
setPinNew(false)
|
||||
setFeatNew(false)
|
||||
setMsg('已发布')
|
||||
await load()
|
||||
} catch (e) {
|
||||
setErr((e as Error).message || '发布失败')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function del(id: string) {
|
||||
if (!confirm('删除该帖?')) return
|
||||
setBusy(true)
|
||||
try {
|
||||
await api(`/api/admin/memo/memos/${id}`, { method: 'DELETE' })
|
||||
await load()
|
||||
} catch (e) {
|
||||
setErr((e as Error).message || '删除失败')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function pin(id: string, pinned: boolean) {
|
||||
setBusy(true)
|
||||
try {
|
||||
await api(`/api/admin/memo/memos/${id}/pin`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ pinned }),
|
||||
})
|
||||
await load()
|
||||
} catch (e) {
|
||||
setErr((e as Error).message || '操作失败')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function feature(id: string, featured: boolean) {
|
||||
setBusy(true)
|
||||
try {
|
||||
await api(`/api/admin/memo/memos/${id}/featured`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ featured }),
|
||||
})
|
||||
await load()
|
||||
} catch (e) {
|
||||
setErr((e as Error).message || '操作失败')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function hide(id: string) {
|
||||
setBusy(true)
|
||||
try {
|
||||
await api(`/api/admin/memo/memos/${id}/hide`, { method: 'POST' })
|
||||
await load()
|
||||
} catch (e) {
|
||||
setErr((e as Error).message || '隐藏失败')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const toggles: { key: keyof Settings; label: string; hint: string }[] = [
|
||||
{ key: 'enabled', label: '社群总开关', hint: '关闭后小程序无法进入' },
|
||||
{ key: 'requireVip', label: '仅 VIP 可进', hint: '关闭后登录用户均可(慎用)' },
|
||||
{ key: 'adminOnlyPost', label: '仅博主发帖', hint: '知识星球模式:会员只读互动' },
|
||||
{ key: 'canPost', label: '允许会员发帖', hint: '关闭 adminOnlyPost 后生效' },
|
||||
{ key: 'canComment', label: '允许评论', hint: '会员是否可讨论' },
|
||||
{ key: 'canLike', label: '允许点赞', hint: '会员是否可点赞' },
|
||||
{ key: 'canFavorite', label: '允许收藏', hint: '会员是否可收藏' },
|
||||
{ key: 'canUpload', label: '允许传图', hint: '会员发帖是否可上传图片' },
|
||||
]
|
||||
|
||||
return (
|
||||
<div className="page">
|
||||
<header className="page-head">
|
||||
<div>
|
||||
<h1>知识社群</h1>
|
||||
<p>
|
||||
对标知识星球:博主发干货帖,会员阅读 / 点赞 / 评论 / 收藏(能力参考 Memos)
|
||||
</p>
|
||||
</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>
|
||||
|
||||
{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>
|
||||
{toggles.map((t) => (
|
||||
<div className="vip-row" key={t.key}>
|
||||
<div>
|
||||
<strong>{t.label}</strong>
|
||||
<p className="vip-hint">{t.hint}</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className={settings[t.key] ? 'primary-link' : 'ghost-btn'}
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
void saveSettings(
|
||||
{ [t.key]: !settings[t.key] } as Partial<Settings>,
|
||||
`${t.label}已更新`,
|
||||
)
|
||||
}
|
||||
>
|
||||
{settings[t.key] ? '已开启' : '已关闭'}
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<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) => (
|
||||
<img
|
||||
key={r.url}
|
||||
src={r.url}
|
||||
alt=""
|
||||
style={{
|
||||
width: 72,
|
||||
height: 72,
|
||||
objectFit: 'cover',
|
||||
borderRadius: 8,
|
||||
background: '#111',
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</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()}>
|
||||
发布
|
||||
</button>
|
||||
</div>
|
||||
</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>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
548
apps/admin/src/pages/Shop.tsx
Normal file
548
apps/admin/src/pages/Shop.tsx
Normal file
@ -0,0 +1,548 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { api } from '../api'
|
||||
import './BookEdit.css'
|
||||
|
||||
type GoodsType = 'virtual' | 'physical'
|
||||
|
||||
type Product = {
|
||||
id: string
|
||||
title: string
|
||||
desc: string
|
||||
cover: string
|
||||
coverEmoji: string
|
||||
groupName: string
|
||||
goodsType: GoodsType
|
||||
priceFen: number
|
||||
stock: number
|
||||
wxProductId: string
|
||||
offerKey?: string
|
||||
sort: number
|
||||
enabled: boolean
|
||||
}
|
||||
|
||||
type ProductOffer = {
|
||||
key: string
|
||||
label: string
|
||||
name: string
|
||||
product_id: string
|
||||
price_fen: number
|
||||
price_yuan: string
|
||||
free: boolean
|
||||
image: string
|
||||
remark?: string
|
||||
}
|
||||
|
||||
type ShopOrder = {
|
||||
id: string
|
||||
outTradeNo: string
|
||||
openid: string
|
||||
productId: string
|
||||
productTitle: string
|
||||
goodsType: GoodsType
|
||||
qty: number
|
||||
amountFen: number
|
||||
status: string
|
||||
email: string
|
||||
address?: Record<string, string>
|
||||
carmis?: string[]
|
||||
trackingNo?: string
|
||||
expressCompany?: string
|
||||
createdAt: number
|
||||
}
|
||||
|
||||
type Tab = 'products' | 'carmis' | 'orders'
|
||||
|
||||
const emptyProduct: Product = {
|
||||
id: '',
|
||||
title: '',
|
||||
desc: '',
|
||||
cover: '',
|
||||
coverEmoji: '🛒',
|
||||
groupName: '全部',
|
||||
goodsType: 'virtual',
|
||||
priceFen: 18800,
|
||||
stock: 0,
|
||||
wxProductId: '',
|
||||
offerKey: '',
|
||||
sort: 100,
|
||||
enabled: true,
|
||||
}
|
||||
|
||||
export default function Shop() {
|
||||
const [tab, setTab] = useState<Tab>('products')
|
||||
const [products, setProducts] = useState<Product[]>([])
|
||||
const [orders, setOrders] = useState<ShopOrder[]>([])
|
||||
const [offers, setOffers] = useState<ProductOffer[]>([])
|
||||
const [draft, setDraft] = useState<Product>(emptyProduct)
|
||||
const [carmiProductId, setCarmiProductId] = useState('')
|
||||
const [carmiText, setCarmiText] = useState('')
|
||||
const [shipId, setShipId] = useState('')
|
||||
const [trackingNo, setTrackingNo] = useState('')
|
||||
const [expressCompany, setExpressCompany] = useState('')
|
||||
const [err, setErr] = useState('')
|
||||
const [msg, setMsg] = useState('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setErr('')
|
||||
const [p, o, offerRes] = await Promise.all([
|
||||
api<{ items: Product[] }>('/api/admin/shop/products'),
|
||||
api<{ items: ShopOrder[] }>('/api/admin/shop/orders'),
|
||||
api<{ items: ProductOffer[] }>('/api/admin/product-offers'),
|
||||
])
|
||||
setProducts(p.items || [])
|
||||
setOrders(o.items || [])
|
||||
setOffers((offerRes.items || []).filter((x) => !x.free))
|
||||
if (!carmiProductId && p.items?.length) {
|
||||
const v = p.items.find((x) => x.goodsType === 'virtual')
|
||||
if (v) setCarmiProductId(v.id)
|
||||
}
|
||||
}, [carmiProductId])
|
||||
|
||||
useEffect(() => {
|
||||
load().catch((e) => setErr(e.message || '加载失败'))
|
||||
}, [load])
|
||||
|
||||
const virtualProducts = useMemo(
|
||||
() => products.filter((p) => p.goodsType === 'virtual'),
|
||||
[products],
|
||||
)
|
||||
|
||||
const activeOfferKey = useMemo(() => {
|
||||
if (draft.offerKey) return draft.offerKey
|
||||
return (
|
||||
offers.find((o) => o.product_id === draft.wxProductId || o.key === draft.wxProductId)?.key ||
|
||||
''
|
||||
)
|
||||
}, [draft.offerKey, draft.wxProductId, offers])
|
||||
|
||||
function pickOffer(o: ProductOffer) {
|
||||
setDraft((d) => ({
|
||||
...d,
|
||||
offerKey: o.key,
|
||||
wxProductId: o.product_id,
|
||||
priceFen: o.price_fen,
|
||||
}))
|
||||
}
|
||||
|
||||
async function saveProduct() {
|
||||
setBusy(true)
|
||||
setMsg('')
|
||||
setErr('')
|
||||
try {
|
||||
await api('/api/admin/shop/products', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(draft),
|
||||
})
|
||||
setMsg(
|
||||
draft.wxProductId
|
||||
? `已保存 · 道具 ${draft.wxProductId} · ¥${(draft.priceFen / 100).toFixed(0)}`
|
||||
: '商品已保存(未选道具)',
|
||||
)
|
||||
setDraft(emptyProduct)
|
||||
await load()
|
||||
} catch (e) {
|
||||
setErr((e as Error).message || '保存失败')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function removeProduct(id: string) {
|
||||
if (!confirm(`删除商品 ${id}?`)) return
|
||||
setBusy(true)
|
||||
try {
|
||||
await api(`/api/admin/shop/products/${id}`, { method: 'DELETE' })
|
||||
await load()
|
||||
} catch (e) {
|
||||
setErr((e as Error).message || '删除失败')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function importCarmis() {
|
||||
const codes = carmiText
|
||||
.split(/\r?\n/)
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean)
|
||||
if (!carmiProductId || !codes.length) {
|
||||
setErr('请选择商品并粘贴卡密(一行一个)')
|
||||
return
|
||||
}
|
||||
setBusy(true)
|
||||
setErr('')
|
||||
setMsg('')
|
||||
try {
|
||||
const res = await api<{ imported: number; stock: number }>('/api/admin/shop/carmis', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ productId: carmiProductId, codes }),
|
||||
})
|
||||
setMsg(`已导入 ${res.imported} 条,当前库存 ${res.stock}`)
|
||||
setCarmiText('')
|
||||
await load()
|
||||
} catch (e) {
|
||||
setErr((e as Error).message || '导入失败')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function ship(orderId: string) {
|
||||
setBusy(true)
|
||||
setErr('')
|
||||
setMsg('')
|
||||
try {
|
||||
await api(`/api/admin/shop/orders/${orderId}/ship`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ trackingNo, expressCompany, shipNote: '' }),
|
||||
})
|
||||
setMsg('已标记发货')
|
||||
setShipId('')
|
||||
setTrackingNo('')
|
||||
setExpressCompany('')
|
||||
await load()
|
||||
} catch (e) {
|
||||
setErr((e as Error).message || '发货失败')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="page">
|
||||
<header className="page-head">
|
||||
<div>
|
||||
<h1>电商</h1>
|
||||
<p>付费方案与 VIP / 小册相同(已发布虚拟支付道具);每个商品单独选道具,勿共用同一道具。</p>
|
||||
</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>
|
||||
|
||||
{tab === 'products' ? (
|
||||
<>
|
||||
<div className="panel monetize-panel">
|
||||
<h2 style={{ marginTop: 0 }}>{draft.id ? `编辑 ${draft.id}` : '新建 / 编辑商品'}</h2>
|
||||
<p className="hint">先点选付费方案(道具 + 价格),再填写标题与类型后保存。</p>
|
||||
|
||||
<div className="offer-grid offer-grid-6" style={{ marginBottom: 16 }}>
|
||||
{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' : ''}`}
|
||||
disabled={busy}
|
||||
onClick={() => pickOffer(o)}
|
||||
>
|
||||
{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.product_id}</span>
|
||||
<em>{o.price_yuan}</em>
|
||||
{o.remark ? <i className="offer-remark">{o.remark}</i> : null}
|
||||
{active ? <b className="offer-on">已选</b> : null}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</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>
|
||||
ID(空则自动)
|
||||
<input
|
||||
value={draft.id}
|
||||
onChange={(e) => setDraft({ ...draft, id: e.target.value })}
|
||||
placeholder="yt-device"
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
标题
|
||||
<input
|
||||
value={draft.title}
|
||||
onChange={(e) => setDraft({ ...draft, title: e.target.value })}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
分组
|
||||
<input
|
||||
value={draft.groupName}
|
||||
onChange={(e) => setDraft({ ...draft, groupName: e.target.value })}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
类型
|
||||
<select
|
||||
value={draft.goodsType}
|
||||
onChange={(e) =>
|
||||
setDraft({ ...draft, goodsType: e.target.value as GoodsType })
|
||||
}
|
||||
>
|
||||
<option value="virtual">虚拟发卡</option>
|
||||
<option value="physical">实体发货</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
库存(实体手动;虚拟跟卡密)
|
||||
<input
|
||||
type="number"
|
||||
value={draft.stock}
|
||||
onChange={(e) => setDraft({ ...draft, stock: Number(e.target.value) || 0 })}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Emoji
|
||||
<input
|
||||
value={draft.coverEmoji}
|
||||
onChange={(e) => setDraft({ ...draft, coverEmoji: e.target.value })}
|
||||
/>
|
||||
</label>
|
||||
<label style={{ gridColumn: '1 / -1' }}>
|
||||
描述
|
||||
<input
|
||||
value={draft.desc}
|
||||
onChange={(e) => setDraft({ ...draft, desc: e.target.value })}
|
||||
/>
|
||||
</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>
|
||||
</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 && (
|
||||
<tr>
|
||||
<td colSpan={8}>暂无商品</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</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>
|
||||
) : 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)}>
|
||||
发货
|
||||
</button>
|
||||
)
|
||||
) : (
|
||||
'—'
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{!orders.length && (
|
||||
<tr>
|
||||
<td colSpan={7}>暂无订单</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@ -5,6 +5,7 @@
|
||||
| 模块 | 来源 | 路径前缀 |
|
||||
|---|---|---|
|
||||
| `services/ebook_svc` | 原 wemini/backend | `/api` `/api/ebook` `/api/admin` `/api/admin/douyin` |
|
||||
| └ shop / memo | VIP 设备商城 · 知识社群 | `/api/ebook/shop*` `/api/ebook/memo*` · `/api/admin/shop` `/api/admin/memo` |
|
||||
| `services/community_svc` | 原 community-api | `/api/v1/*` |
|
||||
| `services/pay_svc` | 原 payjsapi | `/nomadvip` `/digital` `/api/meetup` … |
|
||||
|
||||
|
||||
@ -22,7 +22,21 @@ if str(SERVICES) not in sys.path:
|
||||
sys.path.insert(0, str(SERVICES))
|
||||
|
||||
from ebook_svc.jobs import reconcile_pending_orders # noqa: E402
|
||||
from ebook_svc.routers import admin, auth, books, douyin_admin, pay, track # noqa: E402
|
||||
from ebook_svc.routers import ( # noqa: E402
|
||||
admin,
|
||||
auth,
|
||||
books,
|
||||
douyin_admin,
|
||||
join_group_admin,
|
||||
memo,
|
||||
memo_admin,
|
||||
pay,
|
||||
public_config,
|
||||
shop,
|
||||
shop_admin,
|
||||
track,
|
||||
vip_admin,
|
||||
)
|
||||
from community_svc.routers import ( # noqa: E402
|
||||
api as community_api,
|
||||
auth as community_auth,
|
||||
@ -93,8 +107,15 @@ for _prefix in ("/api", "/api/ebook"):
|
||||
app.include_router(books.router, prefix=_prefix)
|
||||
app.include_router(pay.router, prefix=_prefix)
|
||||
app.include_router(track.router, prefix=_prefix)
|
||||
app.include_router(shop.router, prefix=_prefix)
|
||||
app.include_router(memo.router, prefix=_prefix)
|
||||
app.include_router(admin.router)
|
||||
app.include_router(douyin_admin.router)
|
||||
app.include_router(join_group_admin.router)
|
||||
app.include_router(vip_admin.router)
|
||||
app.include_router(shop_admin.router)
|
||||
app.include_router(memo_admin.router)
|
||||
app.include_router(public_config.router)
|
||||
|
||||
# —— 社群 ——
|
||||
app.include_router(community_api.router, prefix="/api/v1")
|
||||
|
||||
@ -11,7 +11,21 @@ from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from ebook_svc.config import settings
|
||||
from ebook_svc.jobs import reconcile_pending_orders
|
||||
from ebook_svc.routers import admin, auth, books, douyin_admin, join_group_admin, pay, public_config, track, vip_admin
|
||||
from ebook_svc.routers import (
|
||||
admin,
|
||||
auth,
|
||||
books,
|
||||
douyin_admin,
|
||||
join_group_admin,
|
||||
memo,
|
||||
memo_admin,
|
||||
pay,
|
||||
public_config,
|
||||
shop,
|
||||
shop_admin,
|
||||
track,
|
||||
vip_admin,
|
||||
)
|
||||
|
||||
scheduler = AsyncIOScheduler()
|
||||
|
||||
@ -42,6 +56,8 @@ for _api_prefix in ("/api", "/api/ebook"):
|
||||
app.include_router(books.router, prefix=_api_prefix)
|
||||
app.include_router(pay.router, prefix=_api_prefix)
|
||||
app.include_router(track.router, prefix=_api_prefix)
|
||||
app.include_router(shop.router, prefix=_api_prefix)
|
||||
app.include_router(memo.router, prefix=_api_prefix)
|
||||
|
||||
# Admin 仅挂 /api/admin(admin.nomadro.cn),避免双后台路径
|
||||
app.include_router(admin.router)
|
||||
@ -51,6 +67,10 @@ app.include_router(douyin_admin.router)
|
||||
app.include_router(join_group_admin.router)
|
||||
# 微信 VIP / 加群行为 / 3D 入口
|
||||
app.include_router(vip_admin.router)
|
||||
# 电商(商品 / 卡密 / 发货)
|
||||
app.include_router(shop_admin.router)
|
||||
# VIP 私密社群(类微博)
|
||||
app.include_router(memo_admin.router)
|
||||
# 公开远程配置(抖音真机:dyapi/api 合法域名 + 有效证书)
|
||||
app.include_router(public_config.router)
|
||||
|
||||
|
||||
314
apps/api/services/ebook_svc/routers/memo.py
Normal file
314
apps/api/services/ebook_svc/routers/memo.py
Normal file
@ -0,0 +1,314 @@
|
||||
"""VIP 知识社群公开 API — 知识星球风格阅读 + 互动。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import mimetypes
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, File, HTTPException, Query, UploadFile
|
||||
from fastapi.responses import FileResponse
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from ebook_svc.config import settings
|
||||
from ebook_svc.core.deps import get_current_openid
|
||||
from ebook_svc.services.memo_store import memo_store
|
||||
from ebook_svc.services.store import store
|
||||
from ebook_svc.services.vip_config import read_vip_config
|
||||
|
||||
router = APIRouter(prefix="/memo", tags=["memo"])
|
||||
|
||||
VIP_BOOK_ID = "__vip__"
|
||||
UPLOAD_DIR = Path(settings.sqlite_path).resolve().parent / "uploads" / "memo"
|
||||
|
||||
|
||||
def _require_vip(openid: str) -> None:
|
||||
cfg = read_vip_config()
|
||||
s = memo_store.get_settings()
|
||||
if not s.get("requireVip"):
|
||||
return
|
||||
if cfg.get("is_free") or int(cfg.get("vipPriceFen") or 0) <= 0:
|
||||
return
|
||||
if not store.is_unlocked(openid, VIP_BOOK_ID):
|
||||
raise HTTPException(403, "开通 VIP 后可进入知识社群")
|
||||
|
||||
|
||||
def _nick(openid: str) -> str:
|
||||
u = store.get_user(openid)
|
||||
if u and (u.get("nickname") or "").strip():
|
||||
return str(u["nickname"]).strip()[:32]
|
||||
return f"会员{openid[-4:]}" if openid else "会员"
|
||||
|
||||
|
||||
def _gate_enabled() -> dict[str, Any]:
|
||||
s = memo_store.get_settings()
|
||||
if not s.get("enabled"):
|
||||
raise HTTPException(403, "社群暂未开放")
|
||||
return s
|
||||
|
||||
|
||||
@router.get("/settings")
|
||||
async def public_settings(openid: str = Depends(get_current_openid)) -> dict[str, Any]:
|
||||
_require_vip(openid)
|
||||
s = memo_store.get_settings()
|
||||
return {
|
||||
"ok": True,
|
||||
"enabled": bool(s.get("enabled")),
|
||||
"canPost": bool(s.get("canPost")) and not bool(s.get("adminOnlyPost")),
|
||||
"canComment": bool(s.get("canComment")),
|
||||
"canLike": bool(s.get("canLike")),
|
||||
"canFavorite": bool(s.get("canFavorite", True)),
|
||||
"canUpload": bool(s.get("canUpload", True)),
|
||||
"adminOnlyPost": bool(s.get("adminOnlyPost")),
|
||||
"planetName": s.get("planetName") or "知识社群",
|
||||
"planetDesc": s.get("planetDesc") or "",
|
||||
"notice": s.get("notice") or "",
|
||||
"maxContentLen": int(s.get("maxContentLen") or 20000),
|
||||
"maxImages": int(s.get("maxImages") or 9),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/tags")
|
||||
async def tags(openid: str = Depends(get_current_openid)) -> dict[str, Any]:
|
||||
_require_vip(openid)
|
||||
_gate_enabled()
|
||||
return {"ok": True, "items": memo_store.list_tags()}
|
||||
|
||||
|
||||
@router.get("/feed")
|
||||
async def feed(
|
||||
openid: str = Depends(get_current_openid),
|
||||
limit: int = Query(30, ge=1, le=100),
|
||||
offset: int = Query(0, ge=0),
|
||||
q: str = "",
|
||||
tag: str = "",
|
||||
tab: str = "all",
|
||||
) -> dict[str, Any]:
|
||||
_require_vip(openid)
|
||||
_gate_enabled()
|
||||
tab_n = (tab or "all").strip().lower()
|
||||
if tab_n not in {"all", "featured", "latest", "mine"}:
|
||||
tab_n = "all"
|
||||
featured = True if tab_n == "featured" else None
|
||||
favorited_by = openid if tab_n == "mine" else ""
|
||||
items = memo_store.list_memos(
|
||||
openid=openid,
|
||||
limit=limit,
|
||||
offset=offset,
|
||||
q=q,
|
||||
tag=tag,
|
||||
featured=featured,
|
||||
favorited_by=favorited_by,
|
||||
)
|
||||
if tab_n == "latest":
|
||||
items = sorted(items, key=lambda x: float(x.get("createdAt") or 0), reverse=True)
|
||||
return {"ok": True, "items": items, "offline": False}
|
||||
|
||||
|
||||
@router.get("/memos/{memo_id}")
|
||||
async def memo_detail(memo_id: str, openid: str = Depends(get_current_openid)) -> dict[str, Any]:
|
||||
_require_vip(openid)
|
||||
_gate_enabled()
|
||||
memo = memo_store.get_memo(memo_id, openid=openid)
|
||||
if not memo:
|
||||
raise HTTPException(404, "帖子不存在")
|
||||
comments = memo_store.list_comments(memo_id)
|
||||
return {"ok": True, "memo": memo, "comments": comments}
|
||||
|
||||
|
||||
class ResourceIn(BaseModel):
|
||||
type: str = "image"
|
||||
url: str = Field(..., min_length=4)
|
||||
|
||||
|
||||
class PostBody(BaseModel):
|
||||
content: str = ""
|
||||
title: str = ""
|
||||
resources: list[ResourceIn] = Field(default_factory=list)
|
||||
|
||||
|
||||
def _save_local_bytes(
|
||||
data: bytes,
|
||||
*,
|
||||
filename: str,
|
||||
content_type: str,
|
||||
max_size: int,
|
||||
) -> dict[str, Any]:
|
||||
if not data:
|
||||
raise HTTPException(400, "空文件")
|
||||
if len(data) > max_size:
|
||||
raise HTTPException(400, f"文件不能超过 {max_size // 1024 // 1024}MB")
|
||||
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
|
||||
suffix = Path(filename or "img.jpg").suffix.lower() or ".jpg"
|
||||
if suffix not in {".jpg", ".jpeg", ".png", ".gif", ".webp"}:
|
||||
suffix = ".jpg"
|
||||
name = f"{uuid.uuid4().hex}{suffix}"
|
||||
path = UPLOAD_DIR / name
|
||||
path.write_bytes(data)
|
||||
base = (settings.public_api_base or "https://api.nomadro.cn").rstrip("/")
|
||||
url = f"{base}/api/ebook/memo/files/{name}"
|
||||
return {
|
||||
"ok": True,
|
||||
"url": url,
|
||||
"object_key": name,
|
||||
"size": len(data),
|
||||
"content_type": content_type or "image/jpeg",
|
||||
}
|
||||
|
||||
|
||||
@router.post("/upload")
|
||||
async def upload_image(
|
||||
file: UploadFile = File(...),
|
||||
openid: str = Depends(get_current_openid),
|
||||
) -> dict[str, Any]:
|
||||
_require_vip(openid)
|
||||
s = _gate_enabled()
|
||||
if not s.get("canUpload", True):
|
||||
raise HTTPException(403, "当前不允许上传图片")
|
||||
ctype = (file.content_type or "").lower()
|
||||
if not ctype.startswith("image/"):
|
||||
raise HTTPException(400, "仅支持图片")
|
||||
data = await file.read()
|
||||
try:
|
||||
from community_svc.services import s3_storage
|
||||
|
||||
# community S3 path when running unified apps/api
|
||||
class _MemFile:
|
||||
def __init__(self, raw: bytes, name: str, content_type: str):
|
||||
self.filename = name
|
||||
self.content_type = content_type
|
||||
self._raw = raw
|
||||
|
||||
async def read(self):
|
||||
return self._raw
|
||||
|
||||
result = await s3_storage.upload_file(
|
||||
_MemFile(data, file.filename or "img.jpg", file.content_type or "image/jpeg"), # type: ignore[arg-type]
|
||||
purpose="memo",
|
||||
max_size=10 * 1024 * 1024,
|
||||
)
|
||||
return {
|
||||
"ok": True,
|
||||
"url": result.url,
|
||||
"object_key": result.object_key,
|
||||
"size": result.size,
|
||||
"content_type": result.content_type,
|
||||
}
|
||||
except Exception:
|
||||
return _save_local_bytes(
|
||||
data,
|
||||
filename=file.filename or "img.jpg",
|
||||
content_type=file.content_type or "image/jpeg",
|
||||
max_size=10 * 1024 * 1024,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/files/{name}")
|
||||
async def get_uploaded_file(name: str):
|
||||
safe = Path(name).name
|
||||
if safe != name or ".." in name:
|
||||
raise HTTPException(400, "非法文件名")
|
||||
path = UPLOAD_DIR / safe
|
||||
if not path.is_file():
|
||||
raise HTTPException(404, "文件不存在")
|
||||
media = mimetypes.guess_type(safe)[0] or "application/octet-stream"
|
||||
return FileResponse(path, media_type=media)
|
||||
|
||||
|
||||
@router.post("/memos")
|
||||
async def create_memo(body: PostBody, openid: str = Depends(get_current_openid)) -> dict[str, Any]:
|
||||
_require_vip(openid)
|
||||
s = _gate_enabled()
|
||||
if s.get("adminOnlyPost") or not s.get("canPost"):
|
||||
raise HTTPException(403, "当前仅博主可发帖")
|
||||
resources = [r.model_dump() for r in (body.resources or [])]
|
||||
try:
|
||||
memo = memo_store.create_memo(
|
||||
openid=openid,
|
||||
content=body.content or "",
|
||||
title=body.title or "",
|
||||
nickname=_nick(openid),
|
||||
resources=resources,
|
||||
)
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, str(e)) from e
|
||||
return {"ok": True, "memo": memo}
|
||||
|
||||
|
||||
@router.delete("/memos/{memo_id}")
|
||||
async def delete_memo(memo_id: str, openid: str = Depends(get_current_openid)) -> dict[str, Any]:
|
||||
_require_vip(openid)
|
||||
try:
|
||||
ok = memo_store.delete_memo(memo_id, openid=openid, admin=False)
|
||||
except ValueError as e:
|
||||
raise HTTPException(403, str(e)) from e
|
||||
if not ok:
|
||||
raise HTTPException(404, "帖子不存在")
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/memos/{memo_id}/like")
|
||||
async def like_memo(memo_id: str, openid: str = Depends(get_current_openid)) -> dict[str, Any]:
|
||||
_require_vip(openid)
|
||||
s = _gate_enabled()
|
||||
if not s.get("canLike"):
|
||||
raise HTTPException(403, "当前不允许点赞")
|
||||
try:
|
||||
memo = memo_store.toggle_like(memo_id, openid)
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, str(e)) from e
|
||||
return {"ok": True, "memo": memo}
|
||||
|
||||
|
||||
@router.post("/memos/{memo_id}/favorite")
|
||||
async def favorite_memo(memo_id: str, openid: str = Depends(get_current_openid)) -> dict[str, Any]:
|
||||
_require_vip(openid)
|
||||
s = _gate_enabled()
|
||||
if not s.get("canFavorite", True):
|
||||
raise HTTPException(403, "当前不允许收藏")
|
||||
try:
|
||||
memo = memo_store.toggle_favorite(memo_id, openid)
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, str(e)) from e
|
||||
return {"ok": True, "memo": memo}
|
||||
|
||||
|
||||
class CommentBody(BaseModel):
|
||||
content: str = Field(..., min_length=1, max_length=1000)
|
||||
|
||||
|
||||
@router.post("/memos/{memo_id}/comments")
|
||||
async def comment_memo(
|
||||
memo_id: str,
|
||||
body: CommentBody,
|
||||
openid: str = Depends(get_current_openid),
|
||||
) -> dict[str, Any]:
|
||||
_require_vip(openid)
|
||||
s = _gate_enabled()
|
||||
if not s.get("canComment"):
|
||||
raise HTTPException(403, "当前不允许评论")
|
||||
try:
|
||||
c = memo_store.add_comment(
|
||||
memo_id,
|
||||
openid=openid,
|
||||
content=body.content,
|
||||
nickname=_nick(openid),
|
||||
)
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, str(e)) from e
|
||||
return {"ok": True, "comment": c}
|
||||
|
||||
|
||||
@router.delete("/comments/{comment_id}")
|
||||
async def delete_comment(
|
||||
comment_id: str,
|
||||
openid: str = Depends(get_current_openid),
|
||||
) -> dict[str, Any]:
|
||||
_require_vip(openid)
|
||||
try:
|
||||
ok = memo_store.delete_comment(comment_id, openid=openid, admin=False)
|
||||
except ValueError as e:
|
||||
raise HTTPException(403, str(e)) from e
|
||||
if not ok:
|
||||
raise HTTPException(404, "评论不存在")
|
||||
return {"ok": True}
|
||||
144
apps/api/services/ebook_svc/routers/memo_admin.py
Normal file
144
apps/api/services/ebook_svc/routers/memo_admin.py
Normal file
@ -0,0 +1,144 @@
|
||||
"""知识社群管理:admin.nomadro.cn/wechat/memo"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from ebook_svc.core.security import require_admin
|
||||
from ebook_svc.services.memo_store import memo_store
|
||||
|
||||
router = APIRouter(prefix="/api/admin/memo", tags=["memo-admin"])
|
||||
|
||||
|
||||
class AdminPostBody(BaseModel):
|
||||
content: str = ""
|
||||
title: str = ""
|
||||
nickname: str = "博主"
|
||||
pinned: bool = False
|
||||
featured: bool = False
|
||||
resources: list[dict[str, Any]] = Field(default_factory=list)
|
||||
|
||||
|
||||
class SettingsBody(BaseModel):
|
||||
enabled: bool | None = None
|
||||
canPost: bool | None = None
|
||||
canComment: bool | None = None
|
||||
canLike: bool | None = None
|
||||
canFavorite: bool | None = None
|
||||
canUpload: bool | None = None
|
||||
adminOnlyPost: bool | None = None
|
||||
requireVip: bool | None = None
|
||||
maxContentLen: int | None = Field(default=None, ge=100, le=50000)
|
||||
maxImages: int | None = Field(default=None, ge=1, le=18)
|
||||
planetName: str | None = None
|
||||
planetDesc: str | None = None
|
||||
notice: str | None = None
|
||||
|
||||
|
||||
class PinBody(BaseModel):
|
||||
pinned: bool = True
|
||||
|
||||
|
||||
class FeaturedBody(BaseModel):
|
||||
featured: bool = True
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def overview(_: str = Depends(require_admin)) -> dict[str, Any]:
|
||||
settings = memo_store.get_settings()
|
||||
stats = memo_store.stats()
|
||||
recent = memo_store.list_memos(limit=30, include_hidden=True)
|
||||
return {"ok": True, "settings": settings, "stats": stats, "recent": recent}
|
||||
|
||||
|
||||
@router.get("/settings")
|
||||
async def get_settings(_: str = Depends(require_admin)) -> dict[str, Any]:
|
||||
return {"ok": True, **memo_store.get_settings()}
|
||||
|
||||
|
||||
@router.put("/settings")
|
||||
async def put_settings(body: SettingsBody, _: str = Depends(require_admin)) -> dict[str, Any]:
|
||||
saved = memo_store.save_settings(body.model_dump(exclude_none=True))
|
||||
return {"ok": True, **saved}
|
||||
|
||||
|
||||
@router.get("/memos")
|
||||
async def list_memos(
|
||||
q: str = "",
|
||||
limit: int = Query(100, ge=1, le=200),
|
||||
_: str = Depends(require_admin),
|
||||
) -> dict[str, Any]:
|
||||
items = memo_store.list_memos(limit=limit, include_hidden=True, q=q)
|
||||
return {"ok": True, "items": items}
|
||||
|
||||
|
||||
@router.post("/memos")
|
||||
async def admin_post(body: AdminPostBody, _: str = Depends(require_admin)) -> dict[str, Any]:
|
||||
try:
|
||||
memo = memo_store.create_memo(
|
||||
openid="__admin__",
|
||||
content=body.content or "",
|
||||
title=body.title or "",
|
||||
nickname=body.nickname or "博主",
|
||||
pinned=body.pinned,
|
||||
featured=body.featured,
|
||||
resources=body.resources or [],
|
||||
)
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, str(e)) from e
|
||||
return {"ok": True, "memo": memo}
|
||||
|
||||
|
||||
@router.delete("/memos/{memo_id}")
|
||||
async def admin_delete(memo_id: str, _: str = Depends(require_admin)) -> dict[str, Any]:
|
||||
ok = memo_store.delete_memo(memo_id, admin=True)
|
||||
if not ok:
|
||||
raise HTTPException(404, "不存在")
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/memos/{memo_id}/hide")
|
||||
async def admin_hide(memo_id: str, _: str = Depends(require_admin)) -> dict[str, Any]:
|
||||
memo = memo_store.hide_memo(memo_id)
|
||||
if not memo:
|
||||
raise HTTPException(404, "不存在")
|
||||
return {"ok": True, "memo": memo}
|
||||
|
||||
|
||||
@router.post("/memos/{memo_id}/pin")
|
||||
async def admin_pin(
|
||||
memo_id: str,
|
||||
body: PinBody,
|
||||
_: str = Depends(require_admin),
|
||||
) -> dict[str, Any]:
|
||||
memo = memo_store.set_pin(memo_id, body.pinned)
|
||||
if not memo:
|
||||
raise HTTPException(404, "不存在")
|
||||
return {"ok": True, "memo": memo}
|
||||
|
||||
|
||||
@router.post("/memos/{memo_id}/featured")
|
||||
async def admin_featured(
|
||||
memo_id: str,
|
||||
body: FeaturedBody,
|
||||
_: str = Depends(require_admin),
|
||||
) -> dict[str, Any]:
|
||||
memo = memo_store.set_featured(memo_id, body.featured)
|
||||
if not memo:
|
||||
raise HTTPException(404, "不存在")
|
||||
return {"ok": True, "memo": memo}
|
||||
|
||||
|
||||
@router.get("/memos/{memo_id}/comments")
|
||||
async def admin_comments(memo_id: str, _: str = Depends(require_admin)) -> dict[str, Any]:
|
||||
return {"ok": True, "items": memo_store.list_comments(memo_id)}
|
||||
|
||||
|
||||
@router.delete("/comments/{comment_id}")
|
||||
async def admin_del_comment(comment_id: str, _: str = Depends(require_admin)) -> dict[str, Any]:
|
||||
ok = memo_store.delete_comment(comment_id, admin=True)
|
||||
if not ok:
|
||||
raise HTTPException(404, "不存在")
|
||||
return {"ok": True}
|
||||
@ -6,11 +6,14 @@ from typing import Any
|
||||
import xmltodict
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, Response
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from ebook_svc.config import settings
|
||||
from ebook_svc.core.deps import get_current_openid
|
||||
from ebook_svc.domains.books import is_book_free
|
||||
from ebook_svc.domains.books.products import PRODUCT_OFFERS
|
||||
from ebook_svc.schemas.pay import DevConfirmBody, OrderBody, StatusBody
|
||||
from ebook_svc.services.shop_store import shop_store
|
||||
from ebook_svc.services.store import store
|
||||
from ebook_svc.services.vip_config import read_vip_config
|
||||
from ebook_svc.services.wxpay import build_sign_data, calc_pay_sig, calc_signature, query_order
|
||||
@ -19,6 +22,14 @@ router = APIRouter(prefix="/pay", tags=["pay"])
|
||||
|
||||
# VIP 订单在 unlocks / orders 里用的哨兵 book_id(不是真实小册)
|
||||
VIP_BOOK_ID = "__vip__"
|
||||
SHOP_BOOK_ID = "__shop__"
|
||||
|
||||
|
||||
class ShopOrderBody(BaseModel):
|
||||
productId: str = Field(..., min_length=1)
|
||||
qty: int = Field(default=1, ge=1, le=20)
|
||||
email: str = ""
|
||||
address: dict[str, Any] | None = None
|
||||
|
||||
|
||||
def _vip_product_ids() -> set[str]:
|
||||
@ -123,6 +134,111 @@ async def vip_status(openid: str = Depends(get_current_openid)):
|
||||
}
|
||||
|
||||
|
||||
def _require_shop_vip(openid: str) -> None:
|
||||
cfg = read_vip_config()
|
||||
if cfg.get("is_free") or int(cfg.get("vipPriceFen") or 0) <= 0:
|
||||
return
|
||||
if not store.is_unlocked(openid, VIP_BOOK_ID):
|
||||
raise HTTPException(403, "开通 VIP 后可使用设备商城")
|
||||
|
||||
|
||||
@router.post("/shop-order")
|
||||
async def create_shop_pay_order(
|
||||
body: ShopOrderBody,
|
||||
openid: str = Depends(get_current_openid),
|
||||
):
|
||||
"""电商虚拟支付下单:虚拟发卡 / 实体待发货。"""
|
||||
_require_shop_vip(openid)
|
||||
product = shop_store.get_product(body.productId)
|
||||
if not product:
|
||||
raise HTTPException(404, "商品不存在")
|
||||
if int(product.get("stock") or 0) < body.qty:
|
||||
raise HTTPException(400, "库存不足")
|
||||
|
||||
wx_pid = str(product.get("wxProductId") or "").strip()
|
||||
price_fen = int(product["priceFen"]) * body.qty
|
||||
if price_fen <= 0:
|
||||
raise HTTPException(400, "商品价格无效")
|
||||
if not wx_pid and not settings.debug:
|
||||
raise HTTPException(400, "商品未配置虚拟支付道具 ID")
|
||||
|
||||
if product["goodsType"] == "physical":
|
||||
addr = body.address or {}
|
||||
if not (addr.get("userName") and addr.get("telNumber") and addr.get("detailInfo")):
|
||||
raise HTTPException(400, "实体商品请选择收货地址")
|
||||
else:
|
||||
if not (body.email or "").strip():
|
||||
raise HTTPException(400, "虚拟商品请填写邮箱")
|
||||
|
||||
user = store.get_user(openid)
|
||||
if not user or not user.get("session_key"):
|
||||
raise HTTPException(401, "session_key 缺失,请重新登录")
|
||||
|
||||
# debug 且无道具:用占位 product_id,前端可走 /pay/dev-confirm
|
||||
pay_product_id = wx_pid or "shop_dev"
|
||||
|
||||
attach = json.dumps(
|
||||
{
|
||||
"type": "shop",
|
||||
"book_id": SHOP_BOOK_ID,
|
||||
"openid": openid,
|
||||
"product_id": product["id"],
|
||||
"qty": body.qty,
|
||||
"goods_type": product["goodsType"],
|
||||
},
|
||||
ensure_ascii=False,
|
||||
separators=(",", ":"),
|
||||
)
|
||||
out_trade_no = store.create_order(
|
||||
openid=openid,
|
||||
book_id=SHOP_BOOK_ID,
|
||||
product_id=pay_product_id,
|
||||
amount_fen=price_fen,
|
||||
attach=attach,
|
||||
)
|
||||
shop_store.create_shop_order(
|
||||
openid=openid,
|
||||
product=product,
|
||||
qty=body.qty,
|
||||
email=(body.email or "").strip(),
|
||||
address=body.address,
|
||||
out_trade_no=out_trade_no,
|
||||
)
|
||||
|
||||
if not wx_pid and settings.debug:
|
||||
return {
|
||||
"signData": "",
|
||||
"mode": "short_series_goods",
|
||||
"paySig": "",
|
||||
"signature": "",
|
||||
"outTradeNo": out_trade_no,
|
||||
"productId": pay_product_id,
|
||||
"goodsPrice": price_fen,
|
||||
"kind": "shop",
|
||||
"devPay": True,
|
||||
}
|
||||
|
||||
sign_data = build_sign_data(
|
||||
offer_id=settings.wx_offer_id,
|
||||
product_id=pay_product_id,
|
||||
goods_price=price_fen,
|
||||
out_trade_no=out_trade_no,
|
||||
attach=attach,
|
||||
)
|
||||
pay_sig = calc_pay_sig("requestVirtualPayment", sign_data, settings.wx_app_key)
|
||||
signature = calc_signature(sign_data, user["session_key"])
|
||||
return {
|
||||
"signData": sign_data,
|
||||
"mode": "short_series_goods",
|
||||
"paySig": pay_sig,
|
||||
"signature": signature,
|
||||
"outTradeNo": out_trade_no,
|
||||
"productId": pay_product_id,
|
||||
"goodsPrice": price_fen,
|
||||
"kind": "shop",
|
||||
}
|
||||
|
||||
|
||||
@router.post("/order")
|
||||
async def create_pay_order(body: OrderBody, openid: str = Depends(get_current_openid)):
|
||||
book = store.get_book(body.book_id)
|
||||
|
||||
63
apps/api/services/ebook_svc/routers/shop.py
Normal file
63
apps/api/services/ebook_svc/routers/shop.py
Normal file
@ -0,0 +1,63 @@
|
||||
"""小程序电商公开 API:目录 / 下单查询。支付走 /pay/shop-order。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from ebook_svc.core.deps import get_current_openid
|
||||
from ebook_svc.services.shop_store import shop_store
|
||||
from ebook_svc.services.store import store as ebook_store
|
||||
from ebook_svc.services.vip_config import read_vip_config
|
||||
|
||||
router = APIRouter(prefix="/shop", tags=["shop"])
|
||||
|
||||
VIP_BOOK_ID = "__vip__"
|
||||
|
||||
|
||||
def _require_vip(openid: str) -> None:
|
||||
cfg = read_vip_config()
|
||||
if cfg.get("is_free") or int(cfg.get("vipPriceFen") or 0) <= 0:
|
||||
return
|
||||
if not ebook_store.is_unlocked(openid, VIP_BOOK_ID):
|
||||
raise HTTPException(403, "开通 VIP 后可使用设备商城")
|
||||
|
||||
|
||||
@router.get("/catalog")
|
||||
async def catalog() -> dict[str, Any]:
|
||||
"""商品目录(可匿名;下单仍需 VIP + 登录)。"""
|
||||
return shop_store.catalog_public()
|
||||
|
||||
|
||||
@router.get("/goods/{product_id}")
|
||||
async def goods_detail(product_id: str) -> dict[str, Any]:
|
||||
p = shop_store.get_product(product_id)
|
||||
if not p:
|
||||
raise HTTPException(404, "商品不存在")
|
||||
# 不向前端暴露未配置的 wx 道具细节以外字段已安全
|
||||
return {"ok": True, "product": p}
|
||||
|
||||
|
||||
class MyOrdersQuery(BaseModel):
|
||||
limit: int = Field(default=50, ge=1, le=100)
|
||||
|
||||
|
||||
@router.get("/my-orders")
|
||||
async def my_orders(openid: str = Depends(get_current_openid)) -> dict[str, Any]:
|
||||
_require_vip(openid)
|
||||
items = shop_store.list_orders(openid=openid, limit=50)
|
||||
# 用户侧可看卡密
|
||||
return {"ok": True, "items": items}
|
||||
|
||||
|
||||
@router.get("/orders/{order_id}")
|
||||
async def order_detail(order_id: str, openid: str = Depends(get_current_openid)) -> dict[str, Any]:
|
||||
_require_vip(openid)
|
||||
order = shop_store.get_order(order_id)
|
||||
if not order or order["openid"] != openid:
|
||||
# 也允许用 out_trade_no
|
||||
order = shop_store.get_order_by_out_trade_no(order_id)
|
||||
if not order or order["openid"] != openid:
|
||||
raise HTTPException(404, "订单不存在")
|
||||
return {"ok": True, "order": order}
|
||||
177
apps/api/services/ebook_svc/routers/shop_admin.py
Normal file
177
apps/api/services/ebook_svc/routers/shop_admin.py
Normal file
@ -0,0 +1,177 @@
|
||||
"""电商管理:admin.nomadro.cn/wechat/shop"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from ebook_svc.core.security import require_admin
|
||||
from ebook_svc.domains.books.products import PRODUCT_OFFERS
|
||||
from ebook_svc.services.shop_store import shop_store
|
||||
|
||||
router = APIRouter(prefix="/api/admin/shop", tags=["shop-admin"])
|
||||
|
||||
|
||||
class ProductBody(BaseModel):
|
||||
id: str | None = None
|
||||
title: str = Field(..., min_length=1)
|
||||
desc: str = ""
|
||||
cover: str = ""
|
||||
coverEmoji: str = "🛒"
|
||||
groupName: str = "全部"
|
||||
goodsType: str = Field(..., pattern="^(virtual|physical)$")
|
||||
priceFen: int = Field(..., ge=0)
|
||||
stock: int = Field(default=0, ge=0)
|
||||
wxProductId: str = ""
|
||||
offerKey: str = ""
|
||||
sort: int = 100
|
||||
enabled: bool = True
|
||||
|
||||
|
||||
class ApplyOfferBody(BaseModel):
|
||||
offerKey: str = Field(..., min_length=1)
|
||||
|
||||
|
||||
class CarmisBody(BaseModel):
|
||||
productId: str = Field(..., min_length=1)
|
||||
codes: list[str] = Field(..., min_length=1)
|
||||
|
||||
|
||||
class ShipBody(BaseModel):
|
||||
trackingNo: str = ""
|
||||
expressCompany: str = ""
|
||||
shipNote: str = ""
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def overview(_: str = Depends(require_admin)) -> dict[str, Any]:
|
||||
products = shop_store.list_products(admin=True)
|
||||
orders = shop_store.list_orders(limit=20)
|
||||
pending_ship = [o for o in shop_store.list_orders(status="paid", limit=100) if o["goodsType"] == "physical"]
|
||||
return {
|
||||
"ok": True,
|
||||
"stats": {
|
||||
"products": len(products),
|
||||
"enabled": sum(1 for p in products if p["enabled"]),
|
||||
"pendingShip": len(pending_ship),
|
||||
"recentOrders": len(orders),
|
||||
},
|
||||
"products": products,
|
||||
"recentOrders": orders,
|
||||
"pendingShip": pending_ship,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/products")
|
||||
async def list_products(_: str = Depends(require_admin)) -> dict[str, Any]:
|
||||
return {"ok": True, "items": shop_store.list_products(admin=True)}
|
||||
|
||||
|
||||
@router.post("/products")
|
||||
async def upsert_product(body: ProductBody, _: str = Depends(require_admin)) -> dict[str, Any]:
|
||||
data = body.model_dump()
|
||||
# 选了已发布方案则同步道具 ID + 价格(对齐 VIP)
|
||||
key = (data.get("offerKey") or "").strip()
|
||||
if key and key != "free":
|
||||
for o in PRODUCT_OFFERS:
|
||||
if o.get("free"):
|
||||
continue
|
||||
if o["key"] == key or o["product_id"] == key:
|
||||
data["offerKey"] = o["key"]
|
||||
data["wxProductId"] = o["product_id"]
|
||||
data["priceFen"] = int(o["price_fen"])
|
||||
break
|
||||
try:
|
||||
saved = shop_store.upsert_product(data)
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, str(e)) from e
|
||||
return {"ok": True, "product": saved}
|
||||
|
||||
|
||||
@router.post("/products/{product_id}/offer")
|
||||
async def apply_product_offer(
|
||||
product_id: str,
|
||||
body: ApplyOfferBody,
|
||||
_: str = Depends(require_admin),
|
||||
) -> dict[str, Any]:
|
||||
p = shop_store.get_product(product_id, admin=True)
|
||||
if not p:
|
||||
raise HTTPException(404, "商品不存在")
|
||||
offer = None
|
||||
for o in PRODUCT_OFFERS:
|
||||
if o.get("free"):
|
||||
continue
|
||||
if o["key"] == body.offerKey or o["product_id"] == body.offerKey:
|
||||
offer = o
|
||||
break
|
||||
if not offer:
|
||||
raise HTTPException(400, "未知付费方案(电商不支持免费)")
|
||||
saved = shop_store.upsert_product(
|
||||
{
|
||||
**p,
|
||||
"offerKey": offer["key"],
|
||||
"wxProductId": offer["product_id"],
|
||||
"priceFen": int(offer["price_fen"]),
|
||||
}
|
||||
)
|
||||
return {"ok": True, "product": saved}
|
||||
|
||||
|
||||
@router.delete("/products/{product_id}")
|
||||
async def delete_product(product_id: str, _: str = Depends(require_admin)) -> dict[str, Any]:
|
||||
ok = shop_store.delete_product(product_id)
|
||||
if not ok:
|
||||
raise HTTPException(404, "商品不存在")
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.get("/carmis")
|
||||
async def list_carmis(
|
||||
productId: str = "",
|
||||
status: str = "",
|
||||
_: str = Depends(require_admin),
|
||||
) -> dict[str, Any]:
|
||||
return {
|
||||
"ok": True,
|
||||
"items": shop_store.list_carmis(product_id=productId, status=status, limit=500),
|
||||
}
|
||||
|
||||
|
||||
@router.post("/carmis")
|
||||
async def import_carmis(body: CarmisBody, _: str = Depends(require_admin)) -> dict[str, Any]:
|
||||
p = shop_store.get_product(body.productId, admin=True)
|
||||
if not p:
|
||||
raise HTTPException(404, "商品不存在")
|
||||
if p["goodsType"] != "virtual":
|
||||
raise HTTPException(400, "仅虚拟商品可导入卡密")
|
||||
n = shop_store.add_carmis(body.productId, body.codes)
|
||||
return {"ok": True, "imported": n, "stock": shop_store.count_unused_carmis(body.productId)}
|
||||
|
||||
|
||||
@router.get("/orders")
|
||||
async def list_orders(
|
||||
status: str = "",
|
||||
_: str = Depends(require_admin),
|
||||
) -> dict[str, Any]:
|
||||
return {"ok": True, "items": shop_store.list_orders(status=status, limit=200)}
|
||||
|
||||
|
||||
@router.post("/orders/{order_id}/ship")
|
||||
async def ship_order(
|
||||
order_id: str,
|
||||
body: ShipBody,
|
||||
_: str = Depends(require_admin),
|
||||
) -> dict[str, Any]:
|
||||
try:
|
||||
order = shop_store.ship_order(
|
||||
order_id,
|
||||
tracking_no=body.trackingNo,
|
||||
express_company=body.expressCompany,
|
||||
ship_note=body.shipNote,
|
||||
)
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, str(e)) from e
|
||||
if not order:
|
||||
raise HTTPException(404, "订单不存在")
|
||||
return {"ok": True, "order": order}
|
||||
703
apps/api/services/ebook_svc/services/memo_store.py
Normal file
703
apps/api/services/ebook_svc/services/memo_store.py
Normal file
@ -0,0 +1,703 @@
|
||||
"""VIP 知识社群(知识星球风格):标题 / 精华 / 收藏 / Markdown / 图 / 标签。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import sqlite3
|
||||
import time
|
||||
import uuid
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from ebook_svc.config import settings
|
||||
|
||||
TAG_RE = re.compile(r"#([\w\u4e00-\u9fff\-]{1,32})")
|
||||
TITLE_RE = re.compile(r"^#{1,3}\s+(.+)$", re.M)
|
||||
|
||||
DEFAULT_SETTINGS: dict[str, Any] = {
|
||||
"enabled": True,
|
||||
"canPost": False,
|
||||
"canComment": True,
|
||||
"canLike": True,
|
||||
"canFavorite": True,
|
||||
"canUpload": True,
|
||||
"adminOnlyPost": True,
|
||||
"requireVip": True,
|
||||
"maxContentLen": 20000,
|
||||
"maxImages": 9,
|
||||
"planetName": "Nomadro 知识社群",
|
||||
"planetDesc": "博主分享实战干货,会员阅读互动",
|
||||
"notice": "置顶与精华优先 · 支持 Markdown / 图片 / #话题",
|
||||
}
|
||||
|
||||
SEED_MEMOS = [
|
||||
{
|
||||
"title": "欢迎加入知识社群",
|
||||
"content": (
|
||||
"## 欢迎加入知识社群\n\n"
|
||||
"这里是 VIP 专属内容区(对标知识星球的阅读体验)。\n\n"
|
||||
"- 博主发帖分享干货\n"
|
||||
"- 支持 **Markdown**、图片、`#话题`\n"
|
||||
"- 会员可点赞、评论、收藏\n\n"
|
||||
"> 友善交流,禁止广告刷屏。\n\n"
|
||||
"#欢迎 #VIP"
|
||||
),
|
||||
"nickname": "Nomadro",
|
||||
"openid": "__system__",
|
||||
"pinned": 1,
|
||||
"featured": 1,
|
||||
"resources": [],
|
||||
},
|
||||
{
|
||||
"title": "如何高效读帖",
|
||||
"content": (
|
||||
"## 如何高效读帖\n\n"
|
||||
"1. 用顶部 **精华 / 最新** 筛选\n"
|
||||
"2. 点 `#话题` 看同主题系列\n"
|
||||
"3. 详情页可收藏,方便回看\n\n"
|
||||
"有问题直接在帖下评论。\n\n"
|
||||
"#使用指南"
|
||||
),
|
||||
"nickname": "Nomadro",
|
||||
"openid": "__system__",
|
||||
"pinned": 0,
|
||||
"featured": 1,
|
||||
"resources": [],
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def extract_tags(content: str) -> list[str]:
|
||||
found: list[str] = []
|
||||
for m in TAG_RE.finditer(content or ""):
|
||||
t = m.group(1).strip()
|
||||
if t and t not in found:
|
||||
found.append(t)
|
||||
return found[:20]
|
||||
|
||||
|
||||
def extract_title(content: str, explicit: str = "") -> str:
|
||||
t = (explicit or "").strip()
|
||||
if t:
|
||||
return t[:120]
|
||||
m = TITLE_RE.search(content or "")
|
||||
if m:
|
||||
return m.group(1).strip()[:120]
|
||||
plain = re.sub(r"[#>*`_\-\[\]\(\)]+", " ", content or "")
|
||||
plain = re.sub(r"\s+", " ", plain).strip()
|
||||
return (plain[:40] + ("…" if len(plain) > 40 else "")) if plain else "未命名"
|
||||
|
||||
|
||||
def extract_excerpt(content: str, limit: int = 96) -> str:
|
||||
lines = []
|
||||
for line in (content or "").splitlines():
|
||||
s = line.strip()
|
||||
if not s or s.startswith("#"):
|
||||
continue
|
||||
if s.startswith(">"):
|
||||
s = s.lstrip("> ").strip()
|
||||
s = re.sub(r"[*_`]", "", s)
|
||||
if s:
|
||||
lines.append(s)
|
||||
plain = " ".join(lines) if lines else re.sub(r"\s+", " ", content or "").strip()
|
||||
plain = re.sub(r"#([\w\u4e00-\u9fff\-]+)", "", plain).strip()
|
||||
if len(plain) <= limit:
|
||||
return plain
|
||||
return plain[: limit - 1] + "…"
|
||||
|
||||
|
||||
class MemoStore:
|
||||
def __init__(self, path: str):
|
||||
self.path = Path(path)
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self._init_db()
|
||||
|
||||
@contextmanager
|
||||
def conn(self):
|
||||
c = sqlite3.connect(self.path)
|
||||
c.row_factory = sqlite3.Row
|
||||
try:
|
||||
yield c
|
||||
c.commit()
|
||||
finally:
|
||||
c.close()
|
||||
|
||||
def _migrate(self, c: sqlite3.Connection) -> None:
|
||||
cols = {r[1] for r in c.execute("PRAGMA table_info(memos)").fetchall()}
|
||||
if not cols:
|
||||
return
|
||||
alters = [
|
||||
("resources_json", "TEXT DEFAULT '[]'"),
|
||||
("tags_json", "TEXT DEFAULT '[]'"),
|
||||
("visibility", "TEXT DEFAULT 'vip'"),
|
||||
("title", "TEXT DEFAULT ''"),
|
||||
("featured", "INTEGER DEFAULT 0"),
|
||||
("favorite_count", "INTEGER DEFAULT 0"),
|
||||
]
|
||||
for name, decl in alters:
|
||||
if name not in cols:
|
||||
c.execute(f"ALTER TABLE memos ADD COLUMN {name} {decl}")
|
||||
c.executescript(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS memo_favorites (
|
||||
memo_id TEXT NOT NULL,
|
||||
openid TEXT NOT NULL,
|
||||
created_at REAL,
|
||||
PRIMARY KEY (memo_id, openid)
|
||||
);
|
||||
"""
|
||||
)
|
||||
# backfill titles
|
||||
rows = c.execute(
|
||||
"SELECT id, content, title FROM memos WHERE IFNULL(title,'')='' "
|
||||
).fetchall()
|
||||
for r in rows:
|
||||
title = extract_title(r["content"] or "")
|
||||
if title:
|
||||
c.execute("UPDATE memos SET title=? WHERE id=?", (title, r["id"]))
|
||||
|
||||
def _init_db(self):
|
||||
with self.conn() as c:
|
||||
c.executescript(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS memo_settings (
|
||||
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||
json TEXT NOT NULL,
|
||||
updated_at REAL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS memos (
|
||||
id TEXT PRIMARY KEY,
|
||||
openid TEXT NOT NULL,
|
||||
nickname TEXT,
|
||||
title TEXT DEFAULT '',
|
||||
content TEXT NOT NULL,
|
||||
resources_json TEXT DEFAULT '[]',
|
||||
tags_json TEXT DEFAULT '[]',
|
||||
visibility TEXT DEFAULT 'vip',
|
||||
pinned INTEGER DEFAULT 0,
|
||||
featured INTEGER DEFAULT 0,
|
||||
status TEXT DEFAULT 'active',
|
||||
like_count INTEGER DEFAULT 0,
|
||||
comment_count INTEGER DEFAULT 0,
|
||||
favorite_count INTEGER DEFAULT 0,
|
||||
created_at REAL,
|
||||
updated_at REAL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_memos_created
|
||||
ON memos(pinned DESC, featured DESC, created_at DESC);
|
||||
CREATE TABLE IF NOT EXISTS memo_comments (
|
||||
id TEXT PRIMARY KEY,
|
||||
memo_id TEXT NOT NULL,
|
||||
openid TEXT NOT NULL,
|
||||
nickname TEXT,
|
||||
content TEXT NOT NULL,
|
||||
status TEXT DEFAULT 'active',
|
||||
created_at REAL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_memo_comments_memo
|
||||
ON memo_comments(memo_id, created_at ASC);
|
||||
CREATE TABLE IF NOT EXISTS memo_likes (
|
||||
memo_id TEXT NOT NULL,
|
||||
openid TEXT NOT NULL,
|
||||
created_at REAL,
|
||||
PRIMARY KEY (memo_id, openid)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS memo_favorites (
|
||||
memo_id TEXT NOT NULL,
|
||||
openid TEXT NOT NULL,
|
||||
created_at REAL,
|
||||
PRIMARY KEY (memo_id, openid)
|
||||
);
|
||||
"""
|
||||
)
|
||||
self._migrate(c)
|
||||
row = c.execute("SELECT id FROM memo_settings WHERE id=1").fetchone()
|
||||
if not row:
|
||||
c.execute(
|
||||
"INSERT INTO memo_settings(id, json, updated_at) VALUES (1, ?, ?)",
|
||||
(json.dumps(DEFAULT_SETTINGS, ensure_ascii=False), time.time()),
|
||||
)
|
||||
else:
|
||||
try:
|
||||
cur = json.loads(
|
||||
c.execute("SELECT json FROM memo_settings WHERE id=1").fetchone()["json"]
|
||||
)
|
||||
if isinstance(cur, dict):
|
||||
merged = dict(DEFAULT_SETTINGS)
|
||||
merged.update(cur)
|
||||
c.execute(
|
||||
"UPDATE memo_settings SET json=? WHERE id=1",
|
||||
(json.dumps(merged, ensure_ascii=False),),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
n = c.execute("SELECT COUNT(*) AS n FROM memos").fetchone()["n"]
|
||||
if n == 0:
|
||||
now = time.time()
|
||||
for i, m in enumerate(SEED_MEMOS):
|
||||
mid = f"mseed{i+1}"
|
||||
tags = extract_tags(m["content"])
|
||||
c.execute(
|
||||
"""
|
||||
INSERT INTO memos(
|
||||
id,openid,nickname,title,content,resources_json,tags_json,visibility,
|
||||
pinned,featured,status,like_count,comment_count,favorite_count,
|
||||
created_at,updated_at
|
||||
) VALUES (?,?,?,?,?,?,?,'vip',?,?,'active',0,0,0,?,?)
|
||||
""",
|
||||
(
|
||||
mid,
|
||||
m["openid"],
|
||||
m["nickname"],
|
||||
m.get("title") or extract_title(m["content"]),
|
||||
m["content"],
|
||||
json.dumps(m.get("resources") or [], ensure_ascii=False),
|
||||
json.dumps(tags, ensure_ascii=False),
|
||||
m["pinned"],
|
||||
m.get("featured") or 0,
|
||||
now - (len(SEED_MEMOS) - i) * 120,
|
||||
now,
|
||||
),
|
||||
)
|
||||
else:
|
||||
rows = c.execute(
|
||||
"SELECT id, content, tags_json FROM memos WHERE IFNULL(tags_json,'') IN ('','[]')"
|
||||
).fetchall()
|
||||
for r in rows:
|
||||
tags = extract_tags(r["content"] or "")
|
||||
if tags:
|
||||
c.execute(
|
||||
"UPDATE memos SET tags_json=? WHERE id=?",
|
||||
(json.dumps(tags, ensure_ascii=False), r["id"]),
|
||||
)
|
||||
|
||||
def get_settings(self) -> dict[str, Any]:
|
||||
with self.conn() as c:
|
||||
row = c.execute("SELECT json FROM memo_settings WHERE id=1").fetchone()
|
||||
base = dict(DEFAULT_SETTINGS)
|
||||
if not row:
|
||||
return base
|
||||
try:
|
||||
raw = json.loads(row["json"] or "{}")
|
||||
if isinstance(raw, dict):
|
||||
base.update(raw)
|
||||
except Exception:
|
||||
pass
|
||||
return base
|
||||
|
||||
def save_settings(self, patch: dict[str, Any]) -> dict[str, Any]:
|
||||
cur = self.get_settings()
|
||||
for k, v in patch.items():
|
||||
if k in DEFAULT_SETTINGS and v is not None:
|
||||
cur[k] = v
|
||||
with self.conn() as c:
|
||||
c.execute(
|
||||
"UPDATE memo_settings SET json=?, updated_at=? WHERE id=1",
|
||||
(json.dumps(cur, ensure_ascii=False), time.time()),
|
||||
)
|
||||
return cur
|
||||
|
||||
def _parse_json_list(self, raw: Any) -> list[Any]:
|
||||
try:
|
||||
v = json.loads(raw or "[]")
|
||||
return v if isinstance(v, list) else []
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
def _memo_row(
|
||||
self,
|
||||
row: sqlite3.Row,
|
||||
*,
|
||||
openid: str = "",
|
||||
with_flags: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
keys = set(row.keys())
|
||||
resources = self._parse_json_list(row["resources_json"] if "resources_json" in keys else "[]")
|
||||
tags = self._parse_json_list(row["tags_json"] if "tags_json" in keys else "[]")
|
||||
content = row["content"] or ""
|
||||
title = (row["title"] if "title" in keys else "") or extract_title(content)
|
||||
cover = ""
|
||||
for r in resources:
|
||||
if isinstance(r, dict) and str(r.get("type") or "image") == "image" and r.get("url"):
|
||||
cover = str(r["url"])
|
||||
break
|
||||
item = {
|
||||
"id": row["id"],
|
||||
"openid": row["openid"],
|
||||
"nickname": row["nickname"] or "博主",
|
||||
"title": title,
|
||||
"excerpt": extract_excerpt(content),
|
||||
"content": content,
|
||||
"resources": resources,
|
||||
"cover": cover,
|
||||
"tags": tags,
|
||||
"visibility": (row["visibility"] if "visibility" in keys else None) or "vip",
|
||||
"pinned": bool(row["pinned"]),
|
||||
"featured": bool(row["featured"] if "featured" in keys else 0),
|
||||
"status": row["status"],
|
||||
"likeCount": int(row["like_count"] or 0),
|
||||
"commentCount": int(row["comment_count"] or 0),
|
||||
"favoriteCount": int(
|
||||
(row["favorite_count"] if "favorite_count" in keys else 0) or 0
|
||||
),
|
||||
"createdAt": row["created_at"],
|
||||
"updatedAt": row["updated_at"],
|
||||
"isMine": bool(openid and row["openid"] == openid),
|
||||
"liked": False,
|
||||
"favorited": False,
|
||||
}
|
||||
if with_flags and openid:
|
||||
item["liked"] = self.has_liked(row["id"], openid)
|
||||
item["favorited"] = self.has_favorited(row["id"], openid)
|
||||
return item
|
||||
|
||||
def has_liked(self, memo_id: str, openid: str) -> bool:
|
||||
with self.conn() as c:
|
||||
return bool(
|
||||
c.execute(
|
||||
"SELECT 1 FROM memo_likes WHERE memo_id=? AND openid=?",
|
||||
(memo_id, openid),
|
||||
).fetchone()
|
||||
)
|
||||
|
||||
def has_favorited(self, memo_id: str, openid: str) -> bool:
|
||||
with self.conn() as c:
|
||||
return bool(
|
||||
c.execute(
|
||||
"SELECT 1 FROM memo_favorites WHERE memo_id=? AND openid=?",
|
||||
(memo_id, openid),
|
||||
).fetchone()
|
||||
)
|
||||
|
||||
def list_memos(
|
||||
self,
|
||||
*,
|
||||
openid: str = "",
|
||||
limit: int = 50,
|
||||
offset: int = 0,
|
||||
include_hidden: bool = False,
|
||||
q: str = "",
|
||||
tag: str = "",
|
||||
featured: bool | None = None,
|
||||
favorited_by: str = "",
|
||||
) -> list[dict[str, Any]]:
|
||||
with self.conn() as c:
|
||||
clauses: list[str] = []
|
||||
params: list[Any] = []
|
||||
if not include_hidden:
|
||||
clauses.append("status='active'")
|
||||
if q.strip():
|
||||
clauses.append("(title LIKE ? OR content LIKE ? OR tags_json LIKE ?)")
|
||||
like = f"%{q.strip()}%"
|
||||
params.extend([like, like, like])
|
||||
if tag.strip():
|
||||
clauses.append("tags_json LIKE ?")
|
||||
params.append(f'%"{tag.strip()}"%')
|
||||
if featured is True:
|
||||
clauses.append("featured=1")
|
||||
if favorited_by:
|
||||
clauses.append(
|
||||
"id IN (SELECT memo_id FROM memo_favorites WHERE openid=?)"
|
||||
)
|
||||
params.append(favorited_by)
|
||||
where = f" WHERE {' AND '.join(clauses)}" if clauses else ""
|
||||
params.extend([limit, offset])
|
||||
rows = c.execute(
|
||||
f"""
|
||||
SELECT * FROM memos{where}
|
||||
ORDER BY pinned DESC, featured DESC, created_at DESC
|
||||
LIMIT ? OFFSET ?
|
||||
""",
|
||||
tuple(params),
|
||||
).fetchall()
|
||||
return [self._memo_row(r, openid=openid, with_flags=True) for r in rows]
|
||||
|
||||
def list_tags(self, limit: int = 40) -> list[dict[str, Any]]:
|
||||
counts: dict[str, int] = {}
|
||||
with self.conn() as c:
|
||||
rows = c.execute(
|
||||
"SELECT tags_json FROM memos WHERE status='active'"
|
||||
).fetchall()
|
||||
for r in rows:
|
||||
for t in self._parse_json_list(r["tags_json"]):
|
||||
if isinstance(t, str) and t:
|
||||
counts[t] = counts.get(t, 0) + 1
|
||||
ordered = sorted(counts.items(), key=lambda x: (-x[1], x[0]))[:limit]
|
||||
return [{"name": k, "count": v} for k, v in ordered]
|
||||
|
||||
def get_memo(self, memo_id: str, *, openid: str = "", admin: bool = False) -> dict[str, Any] | None:
|
||||
with self.conn() as c:
|
||||
row = c.execute("SELECT * FROM memos WHERE id=?", (memo_id,)).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
if not admin and row["status"] != "active":
|
||||
return None
|
||||
return self._memo_row(row, openid=openid, with_flags=True)
|
||||
|
||||
def create_memo(
|
||||
self,
|
||||
*,
|
||||
openid: str,
|
||||
content: str,
|
||||
nickname: str = "",
|
||||
title: str = "",
|
||||
pinned: bool = False,
|
||||
featured: bool = False,
|
||||
resources: list[dict[str, Any]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
content = (content or "").strip()
|
||||
resources = resources or []
|
||||
if not content and not resources:
|
||||
raise ValueError("内容或图片至少一项")
|
||||
s = self.get_settings()
|
||||
max_len = int(s.get("maxContentLen") or 20000)
|
||||
max_images = int(s.get("maxImages") or 9)
|
||||
if len(content) > max_len:
|
||||
raise ValueError(f"内容超过 {max_len} 字")
|
||||
if len(resources) > max_images:
|
||||
raise ValueError(f"最多 {max_images} 张图")
|
||||
clean_res: list[dict[str, Any]] = []
|
||||
for r in resources:
|
||||
url = str((r or {}).get("url") or "").strip()
|
||||
if not url:
|
||||
continue
|
||||
clean_res.append(
|
||||
{"type": str((r or {}).get("type") or "image"), "url": url}
|
||||
)
|
||||
tags = extract_tags(content)
|
||||
title_f = extract_title(content, title)
|
||||
mid = f"m{uuid.uuid4().hex[:16]}"
|
||||
now = time.time()
|
||||
with self.conn() as c:
|
||||
c.execute(
|
||||
"""
|
||||
INSERT INTO memos(
|
||||
id,openid,nickname,title,content,resources_json,tags_json,visibility,
|
||||
pinned,featured,status,like_count,comment_count,favorite_count,
|
||||
created_at,updated_at
|
||||
) VALUES (?,?,?,?,?,?,?,'vip',?,?,'active',0,0,0,?,?)
|
||||
""",
|
||||
(
|
||||
mid,
|
||||
openid,
|
||||
nickname or "博主",
|
||||
title_f,
|
||||
content,
|
||||
json.dumps(clean_res, ensure_ascii=False),
|
||||
json.dumps(tags, ensure_ascii=False),
|
||||
1 if pinned else 0,
|
||||
1 if featured else 0,
|
||||
now,
|
||||
now,
|
||||
),
|
||||
)
|
||||
return self.get_memo(mid, openid=openid) # type: ignore
|
||||
|
||||
def delete_memo(self, memo_id: str, *, openid: str = "", admin: bool = False) -> bool:
|
||||
memo = self.get_memo(memo_id, openid=openid, admin=True)
|
||||
if not memo:
|
||||
return False
|
||||
if not admin and memo["openid"] != openid:
|
||||
raise ValueError("无权删除")
|
||||
with self.conn() as c:
|
||||
c.execute(
|
||||
"UPDATE memos SET status='deleted', updated_at=? WHERE id=?",
|
||||
(time.time(), memo_id),
|
||||
)
|
||||
return True
|
||||
|
||||
def hide_memo(self, memo_id: str) -> dict[str, Any] | None:
|
||||
with self.conn() as c:
|
||||
c.execute(
|
||||
"UPDATE memos SET status='hidden', updated_at=? WHERE id=?",
|
||||
(time.time(), memo_id),
|
||||
)
|
||||
return self.get_memo(memo_id, admin=True)
|
||||
|
||||
def set_pin(self, memo_id: str, pinned: bool) -> dict[str, Any] | None:
|
||||
with self.conn() as c:
|
||||
c.execute(
|
||||
"UPDATE memos SET pinned=?, updated_at=? WHERE id=?",
|
||||
(1 if pinned else 0, time.time(), memo_id),
|
||||
)
|
||||
return self.get_memo(memo_id, admin=True)
|
||||
|
||||
def set_featured(self, memo_id: str, featured: bool) -> dict[str, Any] | None:
|
||||
with self.conn() as c:
|
||||
c.execute(
|
||||
"UPDATE memos SET featured=?, updated_at=? WHERE id=?",
|
||||
(1 if featured else 0, time.time(), memo_id),
|
||||
)
|
||||
return self.get_memo(memo_id, admin=True)
|
||||
|
||||
def toggle_like(self, memo_id: str, openid: str) -> dict[str, Any]:
|
||||
memo = self.get_memo(memo_id, openid=openid)
|
||||
if not memo:
|
||||
raise ValueError("帖子不存在")
|
||||
with self.conn() as c:
|
||||
existed = c.execute(
|
||||
"SELECT 1 FROM memo_likes WHERE memo_id=? AND openid=?",
|
||||
(memo_id, openid),
|
||||
).fetchone()
|
||||
if existed:
|
||||
c.execute(
|
||||
"DELETE FROM memo_likes WHERE memo_id=? AND openid=?",
|
||||
(memo_id, openid),
|
||||
)
|
||||
c.execute(
|
||||
"UPDATE memos SET like_count=CASE WHEN like_count>0 THEN like_count-1 ELSE 0 END, updated_at=? WHERE id=?",
|
||||
(time.time(), memo_id),
|
||||
)
|
||||
liked = False
|
||||
else:
|
||||
c.execute(
|
||||
"INSERT INTO memo_likes(memo_id, openid, created_at) VALUES (?,?,?)",
|
||||
(memo_id, openid, time.time()),
|
||||
)
|
||||
c.execute(
|
||||
"UPDATE memos SET like_count=like_count+1, updated_at=? WHERE id=?",
|
||||
(time.time(), memo_id),
|
||||
)
|
||||
liked = True
|
||||
out = self.get_memo(memo_id, openid=openid)
|
||||
if out:
|
||||
out["liked"] = liked
|
||||
return out # type: ignore
|
||||
|
||||
def toggle_favorite(self, memo_id: str, openid: str) -> dict[str, Any]:
|
||||
memo = self.get_memo(memo_id, openid=openid)
|
||||
if not memo:
|
||||
raise ValueError("帖子不存在")
|
||||
with self.conn() as c:
|
||||
existed = c.execute(
|
||||
"SELECT 1 FROM memo_favorites WHERE memo_id=? AND openid=?",
|
||||
(memo_id, openid),
|
||||
).fetchone()
|
||||
if existed:
|
||||
c.execute(
|
||||
"DELETE FROM memo_favorites WHERE memo_id=? AND openid=?",
|
||||
(memo_id, openid),
|
||||
)
|
||||
c.execute(
|
||||
"UPDATE memos SET favorite_count=CASE WHEN favorite_count>0 THEN favorite_count-1 ELSE 0 END, updated_at=? WHERE id=?",
|
||||
(time.time(), memo_id),
|
||||
)
|
||||
favorited = False
|
||||
else:
|
||||
c.execute(
|
||||
"INSERT INTO memo_favorites(memo_id, openid, created_at) VALUES (?,?,?)",
|
||||
(memo_id, openid, time.time()),
|
||||
)
|
||||
c.execute(
|
||||
"UPDATE memos SET favorite_count=favorite_count+1, updated_at=? WHERE id=?",
|
||||
(time.time(), memo_id),
|
||||
)
|
||||
favorited = True
|
||||
out = self.get_memo(memo_id, openid=openid)
|
||||
if out:
|
||||
out["favorited"] = favorited
|
||||
return out # type: ignore
|
||||
|
||||
def list_comments(self, memo_id: str, *, limit: int = 100) -> list[dict[str, Any]]:
|
||||
with self.conn() as c:
|
||||
rows = c.execute(
|
||||
"""
|
||||
SELECT * FROM memo_comments
|
||||
WHERE memo_id=? AND status='active'
|
||||
ORDER BY created_at ASC LIMIT ?
|
||||
""",
|
||||
(memo_id, limit),
|
||||
).fetchall()
|
||||
return [
|
||||
{
|
||||
"id": r["id"],
|
||||
"memoId": r["memo_id"],
|
||||
"openid": r["openid"],
|
||||
"nickname": r["nickname"] or "会员",
|
||||
"content": r["content"],
|
||||
"createdAt": r["created_at"],
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
|
||||
def add_comment(
|
||||
self,
|
||||
memo_id: str,
|
||||
*,
|
||||
openid: str,
|
||||
content: str,
|
||||
nickname: str = "",
|
||||
) -> dict[str, Any]:
|
||||
content = (content or "").strip()
|
||||
if not content:
|
||||
raise ValueError("评论不能为空")
|
||||
memo = self.get_memo(memo_id, openid=openid)
|
||||
if not memo:
|
||||
raise ValueError("帖子不存在")
|
||||
cid = f"c{uuid.uuid4().hex[:14]}"
|
||||
now = time.time()
|
||||
with self.conn() as c:
|
||||
c.execute(
|
||||
"""
|
||||
INSERT INTO memo_comments(id,memo_id,openid,nickname,content,status,created_at)
|
||||
VALUES (?,?,?,?,?,'active',?)
|
||||
""",
|
||||
(cid, memo_id, openid, nickname or "会员", content, now),
|
||||
)
|
||||
c.execute(
|
||||
"UPDATE memos SET comment_count=comment_count+1, updated_at=? WHERE id=?",
|
||||
(now, memo_id),
|
||||
)
|
||||
return {
|
||||
"id": cid,
|
||||
"memoId": memo_id,
|
||||
"openid": openid,
|
||||
"nickname": nickname or "会员",
|
||||
"content": content,
|
||||
"createdAt": now,
|
||||
}
|
||||
|
||||
def delete_comment(self, comment_id: str, *, openid: str = "", admin: bool = False) -> bool:
|
||||
with self.conn() as c:
|
||||
row = c.execute("SELECT * FROM memo_comments WHERE id=?", (comment_id,)).fetchone()
|
||||
if not row:
|
||||
return False
|
||||
if not admin and row["openid"] != openid:
|
||||
raise ValueError("无权删除")
|
||||
c.execute(
|
||||
"UPDATE memo_comments SET status='deleted' WHERE id=?",
|
||||
(comment_id,),
|
||||
)
|
||||
c.execute(
|
||||
"""
|
||||
UPDATE memos SET comment_count=CASE WHEN comment_count>0 THEN comment_count-1 ELSE 0 END, updated_at=?
|
||||
WHERE id=?
|
||||
""",
|
||||
(time.time(), row["memo_id"]),
|
||||
)
|
||||
return True
|
||||
|
||||
def stats(self) -> dict[str, Any]:
|
||||
with self.conn() as c:
|
||||
memos = c.execute(
|
||||
"SELECT COUNT(*) AS n FROM memos WHERE status='active'"
|
||||
).fetchone()["n"]
|
||||
comments = c.execute(
|
||||
"SELECT COUNT(*) AS n FROM memo_comments WHERE status='active'"
|
||||
).fetchone()["n"]
|
||||
likes = c.execute("SELECT COUNT(*) AS n FROM memo_likes").fetchone()["n"]
|
||||
favorites = c.execute("SELECT COUNT(*) AS n FROM memo_favorites").fetchone()["n"]
|
||||
featured = c.execute(
|
||||
"SELECT COUNT(*) AS n FROM memos WHERE status='active' AND featured=1"
|
||||
).fetchone()["n"]
|
||||
return {
|
||||
"memos": memos,
|
||||
"comments": comments,
|
||||
"likes": likes,
|
||||
"favorites": favorites,
|
||||
"featured": featured,
|
||||
}
|
||||
|
||||
|
||||
memo_store = MemoStore(settings.sqlite_path)
|
||||
607
apps/api/services/ebook_svc/services/shop_store.py
Normal file
607
apps/api/services/ebook_svc/services/shop_store.py
Normal file
@ -0,0 +1,607 @@
|
||||
"""电商:商品 / 卡密 / 订单(SQLite,与 ebook store 同库)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sqlite3
|
||||
import time
|
||||
import uuid
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from typing import Any, Literal
|
||||
|
||||
from ebook_svc.config import settings
|
||||
|
||||
GoodsType = Literal["virtual", "physical"]
|
||||
|
||||
SEED_PRODUCTS: list[dict[str, Any]] = [
|
||||
{
|
||||
"id": "yt-device",
|
||||
"title": "油管 (无人直播)设备",
|
||||
"desc": "开箱即用 · 人工处理发货",
|
||||
"cover": "",
|
||||
"cover_emoji": "📺",
|
||||
"group_name": "硬件",
|
||||
"goods_type": "physical",
|
||||
"price_fen": 99800,
|
||||
"stock": 1,
|
||||
"wx_product_id": "svip",
|
||||
"offer_key": "svip",
|
||||
"sort": 10,
|
||||
"enabled": 1,
|
||||
},
|
||||
{
|
||||
"id": "tt-device",
|
||||
"title": "Tiktok无人直播-设备",
|
||||
"desc": "开箱即用 · 人工处理发货",
|
||||
"cover": "",
|
||||
"cover_emoji": "📱",
|
||||
"group_name": "硬件",
|
||||
"goods_type": "physical",
|
||||
"price_fen": 29800,
|
||||
"stock": 0,
|
||||
"wx_product_id": "tiktok",
|
||||
"offer_key": "tiktok",
|
||||
"sort": 20,
|
||||
"enabled": 1,
|
||||
},
|
||||
{
|
||||
"id": "ypp-account",
|
||||
"title": "Ypp油管账号",
|
||||
"desc": "虚拟发卡 · 支付后自动发放卡密",
|
||||
"cover": "",
|
||||
"cover_emoji": "🔑",
|
||||
"group_name": "账号",
|
||||
"goods_type": "virtual",
|
||||
"price_fen": 18800,
|
||||
"stock": 0,
|
||||
"wx_product_id": "youtube",
|
||||
"offer_key": "youtube",
|
||||
"sort": 30,
|
||||
"enabled": 1,
|
||||
},
|
||||
{
|
||||
"id": "tt-midvideo",
|
||||
"title": "Tiktok中视频账号",
|
||||
"desc": "虚拟发卡 · 支付后自动发放卡密",
|
||||
"cover": "",
|
||||
"cover_emoji": "🎬",
|
||||
"group_name": "账号",
|
||||
"goods_type": "virtual",
|
||||
"price_fen": 4900,
|
||||
"stock": 0,
|
||||
"wx_product_id": "nomad",
|
||||
"offer_key": "nomad",
|
||||
"sort": 40,
|
||||
"enabled": 1,
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
class ShopStore:
|
||||
def __init__(self, path: str):
|
||||
self.path = Path(path)
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self._init_db()
|
||||
|
||||
@contextmanager
|
||||
def conn(self):
|
||||
c = sqlite3.connect(self.path)
|
||||
c.row_factory = sqlite3.Row
|
||||
try:
|
||||
yield c
|
||||
c.commit()
|
||||
finally:
|
||||
c.close()
|
||||
|
||||
def _init_db(self):
|
||||
with self.conn() as c:
|
||||
c.executescript(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS shop_products (
|
||||
id TEXT PRIMARY KEY,
|
||||
title TEXT NOT NULL,
|
||||
desc_text TEXT,
|
||||
cover TEXT,
|
||||
cover_emoji TEXT,
|
||||
group_name TEXT,
|
||||
goods_type TEXT NOT NULL,
|
||||
price_fen INTEGER NOT NULL,
|
||||
stock INTEGER DEFAULT 0,
|
||||
wx_product_id TEXT,
|
||||
offer_key TEXT,
|
||||
sort INTEGER DEFAULT 100,
|
||||
enabled INTEGER DEFAULT 1,
|
||||
created_at REAL,
|
||||
updated_at REAL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS shop_carmis (
|
||||
id TEXT PRIMARY KEY,
|
||||
product_id TEXT NOT NULL,
|
||||
code TEXT NOT NULL,
|
||||
status TEXT DEFAULT 'unused',
|
||||
order_id TEXT,
|
||||
sold_at REAL,
|
||||
created_at REAL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_shop_carmis_product
|
||||
ON shop_carmis(product_id, status);
|
||||
CREATE TABLE IF NOT EXISTS shop_orders (
|
||||
id TEXT PRIMARY KEY,
|
||||
out_trade_no TEXT UNIQUE,
|
||||
openid TEXT NOT NULL,
|
||||
product_id TEXT NOT NULL,
|
||||
product_title TEXT,
|
||||
goods_type TEXT NOT NULL,
|
||||
qty INTEGER DEFAULT 1,
|
||||
amount_fen INTEGER NOT NULL,
|
||||
status TEXT DEFAULT 'pending',
|
||||
email TEXT,
|
||||
address_json TEXT,
|
||||
carmis_json TEXT,
|
||||
tracking_no TEXT,
|
||||
express_company TEXT,
|
||||
ship_note TEXT,
|
||||
shipped_at REAL,
|
||||
paid_at REAL,
|
||||
created_at REAL,
|
||||
updated_at REAL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_shop_orders_openid
|
||||
ON shop_orders(openid, created_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_shop_orders_status
|
||||
ON shop_orders(status);
|
||||
"""
|
||||
)
|
||||
self._migrate_shop(c)
|
||||
n = c.execute("SELECT COUNT(*) AS n FROM shop_products").fetchone()["n"]
|
||||
if n == 0:
|
||||
now = time.time()
|
||||
for p in SEED_PRODUCTS:
|
||||
c.execute(
|
||||
"""
|
||||
INSERT INTO shop_products(
|
||||
id,title,desc_text,cover,cover_emoji,group_name,goods_type,
|
||||
price_fen,stock,wx_product_id,offer_key,sort,enabled,created_at,updated_at
|
||||
) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
|
||||
""",
|
||||
(
|
||||
p["id"],
|
||||
p["title"],
|
||||
p["desc"],
|
||||
p["cover"],
|
||||
p["cover_emoji"],
|
||||
p["group_name"],
|
||||
p["goods_type"],
|
||||
p["price_fen"],
|
||||
p["stock"],
|
||||
p["wx_product_id"],
|
||||
p.get("offer_key") or "",
|
||||
p["sort"],
|
||||
p["enabled"],
|
||||
now,
|
||||
now,
|
||||
),
|
||||
)
|
||||
|
||||
def _migrate_shop(self, c: sqlite3.Connection) -> None:
|
||||
cols = {r[1] for r in c.execute("PRAGMA table_info(shop_products)").fetchall()}
|
||||
if cols and "offer_key" not in cols:
|
||||
c.execute("ALTER TABLE shop_products ADD COLUMN offer_key TEXT")
|
||||
# 旧种子无道具:按 id 补齐已发布方案(与 VIP 同一套 PRODUCT_OFFERS)
|
||||
seed_map = {p["id"]: p for p in SEED_PRODUCTS}
|
||||
rows = c.execute("SELECT id, wx_product_id, offer_key, price_fen FROM shop_products").fetchall()
|
||||
now = time.time()
|
||||
for r in rows:
|
||||
pid = r["id"]
|
||||
seed = seed_map.get(pid)
|
||||
if not seed:
|
||||
continue
|
||||
need = not (r["wx_product_id"] or "").strip() or not (r["offer_key"] or "").strip()
|
||||
if need:
|
||||
c.execute(
|
||||
"""
|
||||
UPDATE shop_products
|
||||
SET wx_product_id=?, offer_key=?, price_fen=?, updated_at=?
|
||||
WHERE id=?
|
||||
""",
|
||||
(
|
||||
seed["wx_product_id"],
|
||||
seed.get("offer_key") or "",
|
||||
seed["price_fen"],
|
||||
now,
|
||||
pid,
|
||||
),
|
||||
)
|
||||
|
||||
def _product_row(self, row: sqlite3.Row, *, with_carmi_stock: bool = False) -> dict[str, Any]:
|
||||
item = {
|
||||
"id": row["id"],
|
||||
"title": row["title"],
|
||||
"desc": row["desc_text"] or "",
|
||||
"cover": row["cover"] or "",
|
||||
"coverEmoji": row["cover_emoji"] or "🛒",
|
||||
"groupName": row["group_name"] or "全部",
|
||||
"goodsType": row["goods_type"],
|
||||
"priceFen": int(row["price_fen"] or 0),
|
||||
"stock": int(row["stock"] or 0),
|
||||
"wxProductId": row["wx_product_id"] or "",
|
||||
"offerKey": (row["offer_key"] if "offer_key" in row.keys() else "") or "",
|
||||
"sort": int(row["sort"] or 100),
|
||||
"enabled": bool(row["enabled"]),
|
||||
"updatedAt": row["updated_at"],
|
||||
}
|
||||
if with_carmi_stock and row["goods_type"] == "virtual":
|
||||
unused = self.count_unused_carmis(row["id"])
|
||||
item["stock"] = unused
|
||||
item["carmiStock"] = unused
|
||||
return item
|
||||
|
||||
def list_products(self, *, enabled_only: bool = True, admin: bool = False) -> list[dict[str, Any]]:
|
||||
with self.conn() as c:
|
||||
if enabled_only and not admin:
|
||||
rows = c.execute(
|
||||
"SELECT * FROM shop_products WHERE enabled=1 ORDER BY sort ASC, updated_at DESC"
|
||||
).fetchall()
|
||||
else:
|
||||
rows = c.execute(
|
||||
"SELECT * FROM shop_products ORDER BY sort ASC, updated_at DESC"
|
||||
).fetchall()
|
||||
return [self._product_row(r, with_carmi_stock=True) for r in rows]
|
||||
|
||||
def get_product(self, product_id: str, *, admin: bool = False) -> dict[str, Any] | None:
|
||||
with self.conn() as c:
|
||||
row = c.execute("SELECT * FROM shop_products WHERE id=?", (product_id,)).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
if not admin and not row["enabled"]:
|
||||
return None
|
||||
return self._product_row(row, with_carmi_stock=True)
|
||||
|
||||
def upsert_product(self, data: dict[str, Any]) -> dict[str, Any]:
|
||||
pid = str(data.get("id") or "").strip() or f"p{uuid.uuid4().hex[:10]}"
|
||||
now = time.time()
|
||||
goods_type = data.get("goodsType") or data.get("goods_type") or "virtual"
|
||||
if goods_type not in ("virtual", "physical"):
|
||||
raise ValueError("goodsType must be virtual or physical")
|
||||
with self.conn() as c:
|
||||
exists = c.execute("SELECT id FROM shop_products WHERE id=?", (pid,)).fetchone()
|
||||
fields = (
|
||||
data.get("title") or "未命名商品",
|
||||
data.get("desc") or data.get("desc_text") or "",
|
||||
data.get("cover") or "",
|
||||
data.get("coverEmoji") or data.get("cover_emoji") or "🛒",
|
||||
data.get("groupName") or data.get("group_name") or "全部",
|
||||
goods_type,
|
||||
int(data.get("priceFen") if data.get("priceFen") is not None else data.get("price_fen") or 0),
|
||||
int(data.get("stock") if data.get("stock") is not None else 0),
|
||||
data.get("wxProductId") or data.get("wx_product_id") or "",
|
||||
data.get("offerKey") or data.get("offer_key") or "",
|
||||
int(data.get("sort") if data.get("sort") is not None else 100),
|
||||
1 if data.get("enabled", True) else 0,
|
||||
now,
|
||||
)
|
||||
if exists:
|
||||
c.execute(
|
||||
"""
|
||||
UPDATE shop_products SET title=?, desc_text=?, cover=?, cover_emoji=?,
|
||||
group_name=?, goods_type=?, price_fen=?, stock=?, wx_product_id=?,
|
||||
offer_key=?, sort=?, enabled=?, updated_at=?
|
||||
WHERE id=?
|
||||
""",
|
||||
(*fields, pid),
|
||||
)
|
||||
else:
|
||||
c.execute(
|
||||
"""
|
||||
INSERT INTO shop_products(
|
||||
id,title,desc_text,cover,cover_emoji,group_name,goods_type,
|
||||
price_fen,stock,wx_product_id,offer_key,sort,enabled,created_at,updated_at
|
||||
) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
|
||||
""",
|
||||
(pid, *fields[:-1], now, now),
|
||||
)
|
||||
return self.get_product(pid, admin=True) # type: ignore
|
||||
|
||||
def delete_product(self, product_id: str) -> bool:
|
||||
with self.conn() as c:
|
||||
cur = c.execute("DELETE FROM shop_products WHERE id=?", (product_id,))
|
||||
return cur.rowcount > 0
|
||||
|
||||
def count_unused_carmis(self, product_id: str) -> int:
|
||||
with self.conn() as c:
|
||||
row = c.execute(
|
||||
"SELECT COUNT(*) AS n FROM shop_carmis WHERE product_id=? AND status='unused'",
|
||||
(product_id,),
|
||||
).fetchone()
|
||||
return int(row["n"] if row else 0)
|
||||
|
||||
def add_carmis(self, product_id: str, codes: list[str]) -> int:
|
||||
now = time.time()
|
||||
n = 0
|
||||
with self.conn() as c:
|
||||
for raw in codes:
|
||||
code = str(raw or "").strip()
|
||||
if not code:
|
||||
continue
|
||||
c.execute(
|
||||
"""
|
||||
INSERT INTO shop_carmis(id, product_id, code, status, created_at)
|
||||
VALUES(?,?,?,?,?)
|
||||
""",
|
||||
(f"c{uuid.uuid4().hex}", product_id, code, "unused", now),
|
||||
)
|
||||
n += 1
|
||||
# 虚拟商品库存与卡密对齐
|
||||
unused = c.execute(
|
||||
"SELECT COUNT(*) AS n FROM shop_carmis WHERE product_id=? AND status='unused'",
|
||||
(product_id,),
|
||||
).fetchone()["n"]
|
||||
c.execute(
|
||||
"UPDATE shop_products SET stock=?, updated_at=? WHERE id=? AND goods_type='virtual'",
|
||||
(unused, now, product_id),
|
||||
)
|
||||
return n
|
||||
|
||||
def list_carmis(
|
||||
self, product_id: str = "", status: str = "", limit: int = 200
|
||||
) -> list[dict[str, Any]]:
|
||||
with self.conn() as c:
|
||||
clauses: list[str] = []
|
||||
params: list[Any] = []
|
||||
if product_id:
|
||||
clauses.append("product_id=?")
|
||||
params.append(product_id)
|
||||
if status:
|
||||
clauses.append("status=?")
|
||||
params.append(status)
|
||||
where = f" WHERE {' AND '.join(clauses)}" if clauses else ""
|
||||
params.append(limit)
|
||||
rows = c.execute(
|
||||
f"SELECT * FROM shop_carmis{where} ORDER BY created_at DESC LIMIT ?",
|
||||
tuple(params),
|
||||
).fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
def consume_carmis(self, product_id: str, qty: int, order_id: str) -> list[str]:
|
||||
if qty < 1:
|
||||
raise ValueError("qty invalid")
|
||||
with self.conn() as c:
|
||||
rows = c.execute(
|
||||
"""
|
||||
SELECT id, code FROM shop_carmis
|
||||
WHERE product_id=? AND status='unused'
|
||||
ORDER BY created_at ASC LIMIT ?
|
||||
""",
|
||||
(product_id, qty),
|
||||
).fetchall()
|
||||
if len(rows) < qty:
|
||||
raise ValueError("卡密库存不足")
|
||||
now = time.time()
|
||||
codes: list[str] = []
|
||||
for r in rows:
|
||||
c.execute(
|
||||
"""
|
||||
UPDATE shop_carmis SET status='sold', order_id=?, sold_at=?
|
||||
WHERE id=? AND status='unused'
|
||||
""",
|
||||
(order_id, now, r["id"]),
|
||||
)
|
||||
codes.append(r["code"])
|
||||
unused = c.execute(
|
||||
"SELECT COUNT(*) AS n FROM shop_carmis WHERE product_id=? AND status='unused'",
|
||||
(product_id,),
|
||||
).fetchone()["n"]
|
||||
c.execute(
|
||||
"UPDATE shop_products SET stock=?, updated_at=? WHERE id=?",
|
||||
(unused, now, product_id),
|
||||
)
|
||||
return codes
|
||||
|
||||
def dec_physical_stock(self, product_id: str, qty: int) -> None:
|
||||
with self.conn() as c:
|
||||
row = c.execute(
|
||||
"SELECT stock FROM shop_products WHERE id=? AND goods_type='physical'",
|
||||
(product_id,),
|
||||
).fetchone()
|
||||
if not row:
|
||||
raise ValueError("商品不存在")
|
||||
if int(row["stock"] or 0) < qty:
|
||||
raise ValueError("库存不足")
|
||||
c.execute(
|
||||
"UPDATE shop_products SET stock=stock-?, updated_at=? WHERE id=?",
|
||||
(qty, time.time(), product_id),
|
||||
)
|
||||
|
||||
def create_shop_order(
|
||||
self,
|
||||
*,
|
||||
openid: str,
|
||||
product: dict[str, Any],
|
||||
qty: int,
|
||||
email: str = "",
|
||||
address: dict[str, Any] | None = None,
|
||||
out_trade_no: str,
|
||||
) -> dict[str, Any]:
|
||||
oid = f"S{uuid.uuid4().hex[:16]}"
|
||||
now = time.time()
|
||||
amount = int(product["priceFen"]) * qty
|
||||
with self.conn() as c:
|
||||
c.execute(
|
||||
"""
|
||||
INSERT INTO shop_orders(
|
||||
id,out_trade_no,openid,product_id,product_title,goods_type,qty,
|
||||
amount_fen,status,email,address_json,created_at,updated_at
|
||||
) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)
|
||||
""",
|
||||
(
|
||||
oid,
|
||||
out_trade_no,
|
||||
openid,
|
||||
product["id"],
|
||||
product["title"],
|
||||
product["goodsType"],
|
||||
qty,
|
||||
amount,
|
||||
"pending",
|
||||
email or "",
|
||||
json.dumps(address or {}, ensure_ascii=False),
|
||||
now,
|
||||
now,
|
||||
),
|
||||
)
|
||||
return self.get_order_by_out_trade_no(out_trade_no) # type: ignore
|
||||
|
||||
def get_order(self, order_id: str) -> dict[str, Any] | None:
|
||||
with self.conn() as c:
|
||||
row = c.execute("SELECT * FROM shop_orders WHERE id=?", (order_id,)).fetchone()
|
||||
return self._order_row(row) if row else None
|
||||
|
||||
def get_order_by_out_trade_no(self, out_trade_no: str) -> dict[str, Any] | None:
|
||||
with self.conn() as c:
|
||||
row = c.execute(
|
||||
"SELECT * FROM shop_orders WHERE out_trade_no=?", (out_trade_no,)
|
||||
).fetchone()
|
||||
return self._order_row(row) if row else None
|
||||
|
||||
def _order_row(self, row: sqlite3.Row) -> dict[str, Any]:
|
||||
try:
|
||||
address = json.loads(row["address_json"] or "{}")
|
||||
except Exception:
|
||||
address = {}
|
||||
try:
|
||||
carmis = json.loads(row["carmis_json"] or "[]")
|
||||
except Exception:
|
||||
carmis = []
|
||||
return {
|
||||
"id": row["id"],
|
||||
"outTradeNo": row["out_trade_no"],
|
||||
"openid": row["openid"],
|
||||
"productId": row["product_id"],
|
||||
"productTitle": row["product_title"],
|
||||
"goodsType": row["goods_type"],
|
||||
"qty": int(row["qty"] or 1),
|
||||
"amountFen": int(row["amount_fen"] or 0),
|
||||
"status": row["status"],
|
||||
"email": row["email"] or "",
|
||||
"address": address,
|
||||
"carmis": carmis,
|
||||
"trackingNo": row["tracking_no"] or "",
|
||||
"expressCompany": row["express_company"] or "",
|
||||
"shipNote": row["ship_note"] or "",
|
||||
"shippedAt": row["shipped_at"],
|
||||
"paidAt": row["paid_at"],
|
||||
"createdAt": row["created_at"],
|
||||
"updatedAt": row["updated_at"],
|
||||
}
|
||||
|
||||
def list_orders(
|
||||
self,
|
||||
*,
|
||||
openid: str = "",
|
||||
status: str = "",
|
||||
limit: int = 100,
|
||||
) -> list[dict[str, Any]]:
|
||||
with self.conn() as c:
|
||||
clauses: list[str] = []
|
||||
params: list[Any] = []
|
||||
if openid:
|
||||
clauses.append("openid=?")
|
||||
params.append(openid)
|
||||
if status:
|
||||
clauses.append("status=?")
|
||||
params.append(status)
|
||||
where = f" WHERE {' AND '.join(clauses)}" if clauses else ""
|
||||
params.append(limit)
|
||||
rows = c.execute(
|
||||
f"SELECT * FROM shop_orders{where} ORDER BY created_at DESC LIMIT ?",
|
||||
tuple(params),
|
||||
).fetchall()
|
||||
return [self._order_row(r) for r in rows]
|
||||
|
||||
def fulfill_paid(self, out_trade_no: str) -> dict[str, Any] | None:
|
||||
"""支付成功:虚拟发卡 / 实体扣库存并待发货。幂等。"""
|
||||
order = self.get_order_by_out_trade_no(out_trade_no)
|
||||
if not order:
|
||||
return None
|
||||
if order["status"] in ("paid", "delivered", "shipped"):
|
||||
return order
|
||||
|
||||
product = self.get_product(order["productId"], admin=True)
|
||||
if not product:
|
||||
raise ValueError("商品不存在")
|
||||
|
||||
now = time.time()
|
||||
carmis: list[str] = []
|
||||
if order["goodsType"] == "virtual":
|
||||
carmis = self.consume_carmis(order["productId"], order["qty"], order["id"])
|
||||
status = "delivered"
|
||||
else:
|
||||
self.dec_physical_stock(order["productId"], order["qty"])
|
||||
status = "paid" # 待发货
|
||||
|
||||
with self.conn() as c:
|
||||
c.execute(
|
||||
"""
|
||||
UPDATE shop_orders SET status=?, carmis_json=?, paid_at=?, updated_at=?
|
||||
WHERE out_trade_no=? AND status='pending'
|
||||
""",
|
||||
(
|
||||
status,
|
||||
json.dumps(carmis, ensure_ascii=False),
|
||||
now,
|
||||
now,
|
||||
out_trade_no,
|
||||
),
|
||||
)
|
||||
return self.get_order_by_out_trade_no(out_trade_no)
|
||||
|
||||
def ship_order(
|
||||
self,
|
||||
order_id: str,
|
||||
*,
|
||||
tracking_no: str = "",
|
||||
express_company: str = "",
|
||||
ship_note: str = "",
|
||||
) -> dict[str, Any] | None:
|
||||
order = self.get_order(order_id)
|
||||
if not order:
|
||||
return None
|
||||
if order["goodsType"] != "physical":
|
||||
raise ValueError("仅实体订单可发货")
|
||||
if order["status"] not in ("paid", "shipped"):
|
||||
raise ValueError("订单状态不可发货")
|
||||
now = time.time()
|
||||
with self.conn() as c:
|
||||
c.execute(
|
||||
"""
|
||||
UPDATE shop_orders SET status='shipped', tracking_no=?, express_company=?,
|
||||
ship_note=?, shipped_at=?, updated_at=?
|
||||
WHERE id=?
|
||||
""",
|
||||
(
|
||||
tracking_no.strip(),
|
||||
express_company.strip(),
|
||||
ship_note.strip(),
|
||||
now,
|
||||
now,
|
||||
order_id,
|
||||
),
|
||||
)
|
||||
return self.get_order(order_id)
|
||||
|
||||
def catalog_public(self) -> dict[str, Any]:
|
||||
products = self.list_products(enabled_only=True)
|
||||
groups: list[str] = []
|
||||
for p in products:
|
||||
g = p["groupName"] or "全部"
|
||||
if g not in groups:
|
||||
groups.append(g)
|
||||
return {
|
||||
"ok": True,
|
||||
"groups": [{"id": "all", "name": "全部"}]
|
||||
+ [{"id": g, "name": g} for g in groups],
|
||||
"products": products,
|
||||
}
|
||||
|
||||
|
||||
shop_store = ShopStore(settings.sqlite_path)
|
||||
@ -479,6 +479,24 @@ class Store:
|
||||
""",
|
||||
("paid", wx_order_id, raw_notify, time.time(), out_trade_no),
|
||||
)
|
||||
|
||||
# 电商订单:虚拟发卡 / 实体待发货(不走小册 unlock)
|
||||
attach_type = ""
|
||||
try:
|
||||
attach_obj = json.loads(order.get("attach") or "{}")
|
||||
if isinstance(attach_obj, dict):
|
||||
attach_type = str(attach_obj.get("type") or "")
|
||||
except Exception:
|
||||
attach_type = ""
|
||||
if attach_type == "shop" or str(order.get("book_id") or "").startswith("__shop__"):
|
||||
try:
|
||||
from ebook_svc.services.shop_store import shop_store
|
||||
|
||||
shop_store.fulfill_paid(out_trade_no)
|
||||
except Exception:
|
||||
pass
|
||||
return True
|
||||
|
||||
self.grant_unlock(order["openid"], order["book_id"])
|
||||
return True
|
||||
|
||||
|
||||
@ -60,6 +60,11 @@ export default defineAppConfig({
|
||||
'pages/vip-course/index',
|
||||
'pages/vip-lesson/index',
|
||||
'pages/vip-ebook/index',
|
||||
'pages/vip-store/index',
|
||||
'pages/vip-store-detail/index',
|
||||
'pages/vip-store-orders/index',
|
||||
'pages/vip-memo/index',
|
||||
'pages/vip-memo-detail/index',
|
||||
'pages/game/index',
|
||||
],
|
||||
window: {
|
||||
@ -69,5 +74,10 @@ export default defineAppConfig({
|
||||
navigationBarTextStyle: 'white',
|
||||
backgroundColor: '#0c0c0f',
|
||||
},
|
||||
permission: {
|
||||
'scope.address': {
|
||||
desc: '用于实体商品发货填写收货地址',
|
||||
},
|
||||
},
|
||||
...(wantTabBar ? { tabBar } : {}),
|
||||
})
|
||||
|
||||
90
apps/miniprogram/h5/src/data/vipStoreCatalog.ts
Normal file
90
apps/miniprogram/h5/src/data/vipStoreCatalog.ts
Normal file
@ -0,0 +1,90 @@
|
||||
/** Offline seed — 道具与 VIP PRODUCT_OFFERS 对齐(各商品不同道具) */
|
||||
export type ShopGoodsType = 'virtual' | 'physical'
|
||||
|
||||
export type ShopProduct = {
|
||||
id: string
|
||||
title: string
|
||||
desc: string
|
||||
cover: string
|
||||
coverEmoji: string
|
||||
groupName: string
|
||||
goodsType: ShopGoodsType
|
||||
priceFen: number
|
||||
stock: number
|
||||
wxProductId?: string
|
||||
offerKey?: string
|
||||
enabled?: boolean
|
||||
}
|
||||
|
||||
export type ShopGroup = { id: string; name: string }
|
||||
|
||||
export type ShopCatalog = {
|
||||
ok: boolean
|
||||
groups: ShopGroup[]
|
||||
products: ShopProduct[]
|
||||
offline?: boolean
|
||||
}
|
||||
|
||||
export const LOCAL_SHOP_CATALOG: ShopCatalog = {
|
||||
ok: true,
|
||||
offline: true,
|
||||
groups: [
|
||||
{ id: 'all', name: '全部' },
|
||||
{ id: '硬件', name: '硬件' },
|
||||
{ id: '账号', name: '账号' },
|
||||
],
|
||||
products: [
|
||||
{
|
||||
id: 'yt-device',
|
||||
title: '油管 (无人直播)设备',
|
||||
desc: '开箱即用 · 实体发货',
|
||||
cover: '',
|
||||
coverEmoji: '📺',
|
||||
groupName: '硬件',
|
||||
goodsType: 'physical',
|
||||
priceFen: 99800,
|
||||
stock: 1,
|
||||
wxProductId: 'svip',
|
||||
offerKey: 'svip',
|
||||
},
|
||||
{
|
||||
id: 'tt-device',
|
||||
title: 'Tiktok无人直播-设备',
|
||||
desc: '开箱即用 · 实体发货',
|
||||
cover: '',
|
||||
coverEmoji: '📱',
|
||||
groupName: '硬件',
|
||||
goodsType: 'physical',
|
||||
priceFen: 29800,
|
||||
stock: 0,
|
||||
wxProductId: 'tiktok',
|
||||
offerKey: 'tiktok',
|
||||
},
|
||||
{
|
||||
id: 'ypp-account',
|
||||
title: 'Ypp油管账号',
|
||||
desc: '虚拟发卡 · 支付后自动发放',
|
||||
cover: '',
|
||||
coverEmoji: '🔑',
|
||||
groupName: '账号',
|
||||
goodsType: 'virtual',
|
||||
priceFen: 18800,
|
||||
stock: 0,
|
||||
wxProductId: 'youtube',
|
||||
offerKey: 'youtube',
|
||||
},
|
||||
{
|
||||
id: 'tt-midvideo',
|
||||
title: 'Tiktok中视频账号',
|
||||
desc: '虚拟发卡 · 支付后自动发放',
|
||||
cover: '',
|
||||
coverEmoji: '🎬',
|
||||
groupName: '账号',
|
||||
goodsType: 'virtual',
|
||||
priceFen: 4900,
|
||||
stock: 0,
|
||||
wxProductId: 'nomad',
|
||||
offerKey: 'nomad',
|
||||
},
|
||||
],
|
||||
}
|
||||
265
apps/miniprogram/h5/src/pages/vip-memo-detail/index.scss
Normal file
265
apps/miniprogram/h5/src/pages/vip-memo-detail/index.scss
Normal file
@ -0,0 +1,265 @@
|
||||
/* 真实 px:weapp pxExclude — 知识帖阅读页 */
|
||||
.zd {
|
||||
min-height: 100vh;
|
||||
background: #0c0c0f;
|
||||
color: #e8eef7;
|
||||
padding-bottom: 80px;
|
||||
box-sizing: border-box;
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'PingFang SC', 'Helvetica Neue',
|
||||
'Noto Sans SC', 'Microsoft YaHei', sans-serif;
|
||||
}
|
||||
.zd-loading {
|
||||
display: block;
|
||||
text-align: center;
|
||||
padding: 64px 16px;
|
||||
color: #94a3b8;
|
||||
font-size: 14px;
|
||||
}
|
||||
.zd-boot {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 80px 16px;
|
||||
}
|
||||
.zd-nav-trail {
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
.zd-spin {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
}
|
||||
.zd-spin-sm {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
}
|
||||
.zd-spin-ring {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border-radius: 50%;
|
||||
border: 2px solid rgba(245, 158, 11, 0.2);
|
||||
border-top-color: #f59e0b;
|
||||
animation: zd-spin 0.7s linear infinite;
|
||||
}
|
||||
.zd-spin-sm .zd-spin-ring {
|
||||
border-width: 1.5px;
|
||||
}
|
||||
@keyframes zd-spin {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
.zd-nav {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
height: 44px;
|
||||
padding-left: 4px;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
.zd-back {
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: #f59e0b;
|
||||
font-size: 18px;
|
||||
}
|
||||
.zd-nav-title {
|
||||
flex: 1;
|
||||
text-align: center;
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
color: #94a3b8;
|
||||
}
|
||||
.zd-article {
|
||||
padding: 18px 18px 8px;
|
||||
}
|
||||
.zd-badges {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.zd-badge {
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
padding: 2px 6px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
.zd-badge.pin {
|
||||
background: rgba(245, 158, 11, 0.2);
|
||||
color: #fbbf24;
|
||||
}
|
||||
.zd-badge.feat {
|
||||
background: rgba(94, 234, 212, 0.15);
|
||||
color: #5eead4;
|
||||
}
|
||||
.zd-title {
|
||||
display: block;
|
||||
font-size: 24px;
|
||||
font-weight: 800;
|
||||
line-height: 1.35;
|
||||
letter-spacing: -0.02em;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
.zd-byline {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin-bottom: 20px;
|
||||
padding-bottom: 16px;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
.zd-avatar {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: 50%;
|
||||
background: linear-gradient(135deg, #f59e0b, #b45309);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
color: #0c0c0f;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.zd-by {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
.zd-nick {
|
||||
display: block;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.zd-time {
|
||||
display: block;
|
||||
font-size: 11px;
|
||||
color: #64748b;
|
||||
margin-top: 2px;
|
||||
}
|
||||
.zd-md {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.zd-md :global(.md-root),
|
||||
.zd-md :global(.md-p),
|
||||
.zd-md :global(.md-li) {
|
||||
font-size: 16px !important;
|
||||
line-height: 1.75 !important;
|
||||
color: #e8eef7 !important;
|
||||
}
|
||||
.zd-imgs {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.zd-img {
|
||||
width: 100%;
|
||||
border-radius: 12px;
|
||||
background: #0f172a;
|
||||
}
|
||||
.zd-tags {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.zd-tag {
|
||||
font-size: 12px;
|
||||
color: #f59e0b;
|
||||
background: rgba(245, 158, 11, 0.1);
|
||||
padding: 4px 10px;
|
||||
border-radius: 999px;
|
||||
}
|
||||
.zd-section {
|
||||
padding: 8px 18px 28px;
|
||||
}
|
||||
.zd-section-title {
|
||||
display: block;
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
color: #cbd5e1;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.zd-cmt {
|
||||
padding: 12px 0;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.05);
|
||||
}
|
||||
.zd-cmt-nick {
|
||||
display: block;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: #f59e0b;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.zd-cmt-body {
|
||||
display: block;
|
||||
font-size: 14px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.zd-cmt-time {
|
||||
display: block;
|
||||
font-size: 11px;
|
||||
color: #64748b;
|
||||
margin-top: 4px;
|
||||
}
|
||||
.zd-empty {
|
||||
display: block;
|
||||
font-size: 12px;
|
||||
color: #64748b;
|
||||
padding: 12px 0;
|
||||
}
|
||||
.zd-bar {
|
||||
position: fixed;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
padding: 8px 12px calc(8px + env(safe-area-inset-bottom));
|
||||
background: rgba(12, 12, 15, 0.96);
|
||||
border-top: 1px solid rgba(255, 255, 255, 0.06);
|
||||
backdrop-filter: blur(12px);
|
||||
}
|
||||
.zd-bar-acts {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.zd-act {
|
||||
font-size: 13px;
|
||||
color: #94a3b8;
|
||||
min-height: 36px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 0 4px;
|
||||
}
|
||||
.zd-act.on {
|
||||
color: #f59e0b;
|
||||
}
|
||||
.zd-input {
|
||||
flex: 1;
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
border-radius: 10px;
|
||||
padding: 8px 12px;
|
||||
font-size: 14px;
|
||||
color: #e8eef7;
|
||||
min-width: 0;
|
||||
}
|
||||
.zd-send {
|
||||
background: #f59e0b !important;
|
||||
color: #0c0c0f !important;
|
||||
border: none !important;
|
||||
border-radius: 10px !important;
|
||||
font-size: 13px !important;
|
||||
font-weight: 700 !important;
|
||||
margin: 0 !important;
|
||||
padding: 0 14px !important;
|
||||
line-height: 36px !important;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
256
apps/miniprogram/h5/src/pages/vip-memo-detail/index.tsx
Normal file
256
apps/miniprogram/h5/src/pages/vip-memo-detail/index.tsx
Normal file
@ -0,0 +1,256 @@
|
||||
/**
|
||||
* 知识帖详情 — 缓存秒开 · 静默刷新 · 旋转 loading
|
||||
*/
|
||||
import { useEffect, useState } from 'react'
|
||||
import { View, Text, Input, Button, Image } from '@tarojs/components'
|
||||
import Taro, { useRouter } from '@tarojs/taro'
|
||||
import { goPage } from '@/utils/nav'
|
||||
import { isVipPaidLocal, resolveVipAccess } from '@/utils/vipAccess'
|
||||
import { MarkdownView } from '@/components/MarkdownView'
|
||||
import {
|
||||
commentMemo,
|
||||
favoriteMemo,
|
||||
getCachedMemoDetail,
|
||||
getCachedMemoFeed,
|
||||
getCachedMemoSettings,
|
||||
likeMemo,
|
||||
loadMemoDetail,
|
||||
loadMemoSettings,
|
||||
type MemoComment,
|
||||
type MemoItem,
|
||||
type MemoSettings,
|
||||
} from '@/services/memoApi'
|
||||
import { getSafeAreaMetrics } from '@/utils/safeArea'
|
||||
import './index.scss'
|
||||
|
||||
const MD_PREFS = {
|
||||
fontSize: 16,
|
||||
lineHeight: '1.7',
|
||||
fontFamily: 'sans' as const,
|
||||
theme: 'dark' as const,
|
||||
}
|
||||
|
||||
function fmtTime(ts: number) {
|
||||
if (!ts) return ''
|
||||
const d = new Date(ts * 1000)
|
||||
return `${d.getFullYear()}/${d.getMonth() + 1}/${d.getDate()} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
|
||||
}
|
||||
|
||||
function hydrate(id: string): { memo: MemoItem | null; comments: MemoComment[] } {
|
||||
const cached = getCachedMemoDetail(id)
|
||||
if (cached?.memo) return { memo: cached.memo, comments: cached.comments || [] }
|
||||
const fromFeed = getCachedMemoFeed().find((m) => m.id === id)
|
||||
if (fromFeed) return { memo: fromFeed, comments: [] }
|
||||
return { memo: null, comments: [] }
|
||||
}
|
||||
|
||||
export default function VipMemoDetailPage() {
|
||||
const router = useRouter()
|
||||
const id = String(router.params.id || '')
|
||||
const boot = hydrate(id)
|
||||
const [memo, setMemo] = useState<MemoItem | null>(boot.memo)
|
||||
const [comments, setComments] = useState<MemoComment[]>(boot.comments)
|
||||
const [settings, setSettings] = useState<MemoSettings | null>(() => getCachedMemoSettings())
|
||||
const [text, setText] = useState('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [refreshing, setRefreshing] = useState(!boot.memo)
|
||||
const safe = getSafeAreaMetrics()
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
;(async () => {
|
||||
try {
|
||||
const vip = isVipPaidLocal() ? true : await resolveVipAccess()
|
||||
if (!vip) {
|
||||
goPage('/pages/vip/index')
|
||||
return
|
||||
}
|
||||
if (!cancelled && !memo) setRefreshing(true)
|
||||
const [s, data] = await Promise.all([
|
||||
loadMemoSettings().catch(() => getCachedMemoSettings()),
|
||||
loadMemoDetail(id),
|
||||
])
|
||||
if (cancelled) return
|
||||
setSettings(s)
|
||||
setMemo(data.memo)
|
||||
setComments(data.comments || [])
|
||||
} catch (e) {
|
||||
if (!cancelled && !memo) {
|
||||
Taro.showToast({ title: (e as Error).message || '加载失败', icon: 'none' })
|
||||
}
|
||||
} finally {
|
||||
if (!cancelled) setRefreshing(false)
|
||||
}
|
||||
})()
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [id])
|
||||
|
||||
async function onLike() {
|
||||
if (!memo) return
|
||||
if (settings && !settings.canLike) {
|
||||
Taro.showToast({ title: '暂不允许点赞', icon: 'none' })
|
||||
return
|
||||
}
|
||||
try {
|
||||
setMemo(await likeMemo(memo.id))
|
||||
} catch (e) {
|
||||
Taro.showToast({ title: (e as Error).message || '失败', icon: 'none' })
|
||||
}
|
||||
}
|
||||
|
||||
async function onFavorite() {
|
||||
if (!memo) return
|
||||
if (settings && settings.canFavorite === false) {
|
||||
Taro.showToast({ title: '暂不允许收藏', icon: 'none' })
|
||||
return
|
||||
}
|
||||
try {
|
||||
setMemo(await favoriteMemo(memo.id))
|
||||
} catch (e) {
|
||||
Taro.showToast({ title: (e as Error).message || '失败', icon: 'none' })
|
||||
}
|
||||
}
|
||||
|
||||
async function onComment() {
|
||||
if (!memo || !text.trim() || busy) return
|
||||
if (settings && !settings.canComment) {
|
||||
Taro.showToast({ title: '暂不允许评论', icon: 'none' })
|
||||
return
|
||||
}
|
||||
setBusy(true)
|
||||
try {
|
||||
const c = await commentMemo(memo.id, text.trim())
|
||||
setComments((prev) => [...prev, c])
|
||||
setMemo((m) => (m ? { ...m, commentCount: (m.commentCount || 0) + 1 } : m))
|
||||
setText('')
|
||||
} catch (e) {
|
||||
Taro.showToast({ title: (e as Error).message || '失败', icon: 'none' })
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (!memo) {
|
||||
return (
|
||||
<View className="zd" style={{ paddingTop: safe.statusBarHeight }}>
|
||||
<View className="zd-nav" style={{ paddingRight: safe.menuRightPad }}>
|
||||
<View className="zd-back" onClick={() => goPage('/pages/vip-memo/index')}>
|
||||
<Text>←</Text>
|
||||
</View>
|
||||
<Text className="zd-nav-title">阅读</Text>
|
||||
<View style={{ width: 44 }} />
|
||||
</View>
|
||||
<View className="zd-boot">
|
||||
{refreshing ? (
|
||||
<View className="zd-spin">
|
||||
<View className="zd-spin-ring" />
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
const imgs = (memo.resources || []).map((r) => r.url).filter(Boolean)
|
||||
|
||||
return (
|
||||
<View className="zd" style={{ paddingTop: safe.statusBarHeight }}>
|
||||
<View className="zd-nav" style={{ paddingRight: safe.menuRightPad }}>
|
||||
<View className="zd-back" onClick={() => goPage('/pages/vip-memo/index')}>
|
||||
<Text>←</Text>
|
||||
</View>
|
||||
<Text className="zd-nav-title">阅读</Text>
|
||||
<View className="zd-nav-trail">
|
||||
{refreshing ? (
|
||||
<View className="zd-spin zd-spin-sm">
|
||||
<View className="zd-spin-ring" />
|
||||
</View>
|
||||
) : (
|
||||
<View style={{ width: 18 }} />
|
||||
)}
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<View className="zd-article">
|
||||
<View className="zd-badges">
|
||||
{memo.pinned ? <Text className="zd-badge pin">置顶</Text> : null}
|
||||
{memo.featured ? <Text className="zd-badge feat">精华</Text> : null}
|
||||
</View>
|
||||
<Text className="zd-title">{memo.title || '未命名'}</Text>
|
||||
<View className="zd-byline">
|
||||
<View className="zd-avatar">
|
||||
<Text>{(memo.nickname || '博').slice(0, 1)}</Text>
|
||||
</View>
|
||||
<View className="zd-by">
|
||||
<Text className="zd-nick">{memo.nickname}</Text>
|
||||
<Text className="zd-time">{fmtTime(memo.createdAt)}</Text>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<View className="zd-md">
|
||||
{memo.content ? <MarkdownView markdown={memo.content} prefs={MD_PREFS} /> : null}
|
||||
</View>
|
||||
|
||||
{imgs.length ? (
|
||||
<View className={`zd-imgs ${imgs.length === 1 ? 'one' : ''}`}>
|
||||
{imgs.map((u, i) => (
|
||||
<Image
|
||||
key={u + i}
|
||||
src={u}
|
||||
mode="widthFix"
|
||||
className="zd-img"
|
||||
lazyLoad
|
||||
onClick={() => void Taro.previewImage({ urls: imgs, current: u })}
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{memo.tags?.length ? (
|
||||
<View className="zd-tags">
|
||||
{memo.tags.map((t) => (
|
||||
<Text key={t} className="zd-tag">
|
||||
#{t}
|
||||
</Text>
|
||||
))}
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
<View className="zd-section">
|
||||
<Text className="zd-section-title">讨论 · {comments.length}</Text>
|
||||
{comments.map((c) => (
|
||||
<View key={c.id} className="zd-cmt">
|
||||
<Text className="zd-cmt-nick">{c.nickname}</Text>
|
||||
<Text className="zd-cmt-body">{c.content}</Text>
|
||||
<Text className="zd-cmt-time">{fmtTime(c.createdAt)}</Text>
|
||||
</View>
|
||||
))}
|
||||
{!comments.length ? <Text className="zd-empty">还没有讨论</Text> : null}
|
||||
</View>
|
||||
|
||||
<View className="zd-bar">
|
||||
<View className="zd-bar-acts">
|
||||
<Text className={`zd-act ${memo.liked ? 'on' : ''}`} onClick={() => void onLike()}>
|
||||
{memo.liked ? '♥' : '♡'} {memo.likeCount || 0}
|
||||
</Text>
|
||||
<Text className={`zd-act ${memo.favorited ? 'on' : ''}`} onClick={() => void onFavorite()}>
|
||||
{memo.favorited ? '★' : '☆'} 收藏
|
||||
</Text>
|
||||
</View>
|
||||
<Input
|
||||
className="zd-input"
|
||||
value={text}
|
||||
placeholder={settings?.canComment === false ? '评论已关闭' : '写想法…'}
|
||||
disabled={settings?.canComment === false}
|
||||
onInput={(e) => setText(e.detail.value)}
|
||||
/>
|
||||
<Button className="zd-send" loading={busy} onClick={() => void onComment()}>
|
||||
发
|
||||
</Button>
|
||||
</View>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
387
apps/miniprogram/h5/src/pages/vip-memo/index.scss
Normal file
387
apps/miniprogram/h5/src/pages/vip-memo/index.scss
Normal file
@ -0,0 +1,387 @@
|
||||
/* 真实 px:weapp pxExclude — 知识星球风格阅读流 */
|
||||
.zk {
|
||||
min-height: 100vh;
|
||||
background: #0c0c0f;
|
||||
color: #e8eef7;
|
||||
padding-bottom: 48px;
|
||||
box-sizing: border-box;
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'PingFang SC', 'Helvetica Neue',
|
||||
'Noto Sans SC', 'Microsoft YaHei', sans-serif;
|
||||
}
|
||||
.zk-nav {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
height: 44px;
|
||||
padding-left: 4px;
|
||||
}
|
||||
.zk-back,
|
||||
.zk-nav-btn {
|
||||
min-width: 44px;
|
||||
min-height: 44px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: #f59e0b;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
}
|
||||
.zk-nav-title {
|
||||
flex: 1;
|
||||
text-align: center;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.zk-hero {
|
||||
position: relative;
|
||||
margin: 4px 16px 0;
|
||||
padding: 20px 16px 16px;
|
||||
border-radius: 16px;
|
||||
overflow: hidden;
|
||||
background: linear-gradient(145deg, #1a1510 0%, #15151c 55%, #0f1419 100%);
|
||||
border: 1px solid rgba(245, 158, 11, 0.18);
|
||||
}
|
||||
.zk-hero-glow {
|
||||
position: absolute;
|
||||
top: -40px;
|
||||
right: -20px;
|
||||
width: 140px;
|
||||
height: 140px;
|
||||
border-radius: 50%;
|
||||
background: radial-gradient(circle, rgba(245, 158, 11, 0.22), transparent 70%);
|
||||
pointer-events: none;
|
||||
}
|
||||
.zk-hero-badge {
|
||||
display: inline-block;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.04em;
|
||||
color: #f59e0b;
|
||||
background: rgba(245, 158, 11, 0.12);
|
||||
padding: 3px 8px;
|
||||
border-radius: 6px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.zk-hero-name {
|
||||
display: block;
|
||||
font-size: 22px;
|
||||
font-weight: 700;
|
||||
line-height: 1.3;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
.zk-hero-desc {
|
||||
display: block;
|
||||
font-size: 13px;
|
||||
color: #94a3b8;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.zk-hero-notice {
|
||||
display: block;
|
||||
margin-top: 10px;
|
||||
font-size: 12px;
|
||||
color: #5eead4;
|
||||
line-height: 1.4;
|
||||
}
|
||||
.zk-offline {
|
||||
display: block;
|
||||
margin-top: 8px;
|
||||
font-size: 11px;
|
||||
color: #fbbf24;
|
||||
}
|
||||
.zk-search {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
padding: 12px 16px 0;
|
||||
}
|
||||
.zk-search-input {
|
||||
flex: 1;
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
border-radius: 12px;
|
||||
padding: 10px 14px;
|
||||
font-size: 13px;
|
||||
color: #e8eef7;
|
||||
}
|
||||
.zk-search-go {
|
||||
color: #f59e0b;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
padding: 8px;
|
||||
min-width: 36px;
|
||||
text-align: center;
|
||||
}
|
||||
.zk-tabs {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
padding: 12px 16px 0;
|
||||
}
|
||||
.zk-tab {
|
||||
flex: 1;
|
||||
height: 34px;
|
||||
border-radius: 10px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
color: #94a3b8;
|
||||
background: rgba(255, 255, 255, 0.04);
|
||||
}
|
||||
.zk-tab.on {
|
||||
background: #f59e0b;
|
||||
color: #0c0c0f;
|
||||
font-weight: 700;
|
||||
}
|
||||
.zk-topics {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
padding: 10px 16px;
|
||||
overflow-x: auto;
|
||||
}
|
||||
.zk-topic {
|
||||
flex-shrink: 0;
|
||||
min-height: 28px;
|
||||
padding: 0 10px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
font-size: 12px;
|
||||
color: #cbd5e1;
|
||||
}
|
||||
.zk-topic.on {
|
||||
border-color: #f59e0b;
|
||||
color: #f59e0b;
|
||||
background: rgba(245, 158, 11, 0.1);
|
||||
}
|
||||
.zk-composer {
|
||||
margin: 8px 16px 0;
|
||||
padding: 12px;
|
||||
border-radius: 14px;
|
||||
background: #15151c;
|
||||
border: 1px solid rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
.zk-composer-hint {
|
||||
display: block;
|
||||
font-size: 11px;
|
||||
color: #64748b;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
.zk-textarea {
|
||||
width: 100%;
|
||||
min-height: 110px;
|
||||
font-size: 14px;
|
||||
color: #e8eef7;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.zk-composer-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-top: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.zk-tool,
|
||||
.zk-cancel {
|
||||
font-size: 13px;
|
||||
color: #94a3b8;
|
||||
padding: 8px;
|
||||
}
|
||||
.zk-tool {
|
||||
color: #f59e0b;
|
||||
}
|
||||
.zk-send {
|
||||
background: #f59e0b !important;
|
||||
color: #0c0c0f !important;
|
||||
border: none !important;
|
||||
border-radius: 10px !important;
|
||||
font-size: 13px !important;
|
||||
font-weight: 600 !important;
|
||||
padding: 0 16px !important;
|
||||
margin: 0 !important;
|
||||
line-height: 36px !important;
|
||||
}
|
||||
.zk-img-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr 1fr;
|
||||
gap: 4px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
.zk-img-cell {
|
||||
position: relative;
|
||||
}
|
||||
.zk-img {
|
||||
width: 100%;
|
||||
height: 88px;
|
||||
border-radius: 8px;
|
||||
background: #0f172a;
|
||||
}
|
||||
.zk-img-x {
|
||||
position: absolute;
|
||||
top: 2px;
|
||||
right: 4px;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
border-radius: 50%;
|
||||
background: rgba(0, 0, 0, 0.55);
|
||||
color: #fff;
|
||||
text-align: center;
|
||||
line-height: 22px;
|
||||
font-size: 14px;
|
||||
}
|
||||
.zk-list {
|
||||
padding: 8px 16px 32px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
.zk-card {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
padding: 14px;
|
||||
border-radius: 14px;
|
||||
background: #15151c;
|
||||
border: 1px solid rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
.zk-card-main {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
.zk-card-badges {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
.zk-badge {
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
padding: 2px 6px;
|
||||
border-radius: 4px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
.zk-badge.pin {
|
||||
background: rgba(245, 158, 11, 0.2);
|
||||
color: #fbbf24;
|
||||
}
|
||||
.zk-badge.feat {
|
||||
background: rgba(94, 234, 212, 0.15);
|
||||
color: #5eead4;
|
||||
}
|
||||
.zk-card-title {
|
||||
display: block;
|
||||
font-size: 16px;
|
||||
font-weight: 700;
|
||||
line-height: 1.4;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
.zk-card-excerpt {
|
||||
display: block;
|
||||
font-size: 13px;
|
||||
color: #94a3b8;
|
||||
line-height: 1.5;
|
||||
margin-bottom: 8px;
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
}
|
||||
.zk-card-meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
.zk-card-author {
|
||||
font-size: 12px;
|
||||
color: #f59e0b;
|
||||
font-weight: 500;
|
||||
}
|
||||
.zk-card-dot,
|
||||
.zk-card-time {
|
||||
font-size: 11px;
|
||||
color: #64748b;
|
||||
}
|
||||
.zk-card-tags {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.zk-card-tag {
|
||||
font-size: 11px;
|
||||
color: #64748b;
|
||||
}
|
||||
.zk-card-stats {
|
||||
display: flex;
|
||||
gap: 14px;
|
||||
align-items: center;
|
||||
}
|
||||
.zk-stat {
|
||||
font-size: 12px;
|
||||
color: #94a3b8;
|
||||
min-height: 32px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
.zk-stat.on {
|
||||
color: #f59e0b;
|
||||
}
|
||||
.zk-stat.dim {
|
||||
color: #64748b;
|
||||
margin-left: auto;
|
||||
}
|
||||
.zk-card-cover {
|
||||
width: 84px;
|
||||
height: 84px;
|
||||
border-radius: 10px;
|
||||
flex-shrink: 0;
|
||||
background: #0f172a;
|
||||
}
|
||||
.zk-empty {
|
||||
text-align: center;
|
||||
padding: 48px 16px;
|
||||
color: #94a3b8;
|
||||
font-size: 13px;
|
||||
}
|
||||
.zk-nav-trail {
|
||||
min-width: 44px;
|
||||
min-height: 44px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
.zk-boot {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 64px 16px;
|
||||
}
|
||||
.zk-spin {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
.zk-spin-sm {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
}
|
||||
.zk-spin-ring {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border-radius: 50%;
|
||||
border: 2px solid rgba(245, 158, 11, 0.2);
|
||||
border-top-color: #f59e0b;
|
||||
animation: zk-spin 0.7s linear infinite;
|
||||
}
|
||||
.zk-spin-sm .zk-spin-ring {
|
||||
border-width: 1.5px;
|
||||
}
|
||||
@keyframes zk-spin {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
428
apps/miniprogram/h5/src/pages/vip-memo/index.tsx
Normal file
428
apps/miniprogram/h5/src/pages/vip-memo/index.tsx
Normal file
@ -0,0 +1,428 @@
|
||||
/**
|
||||
* VIP 知识社群 — 缓存秒开 · 后台静默刷新 · 无文案 loading
|
||||
*/
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { View, Text, Textarea, Button, Image, Input } from '@tarojs/components'
|
||||
import Taro, { useDidShow } from '@tarojs/taro'
|
||||
import { goPage } from '@/utils/nav'
|
||||
import { isVipPaidLocal, resolveVipAccess } from '@/utils/vipAccess'
|
||||
import {
|
||||
createMemo,
|
||||
deleteMemo,
|
||||
favoriteMemo,
|
||||
getCachedMemoFeed,
|
||||
getCachedMemoSettings,
|
||||
getCachedMemoTags,
|
||||
likeMemo,
|
||||
loadMemoHome,
|
||||
uploadMemoImage,
|
||||
type FeedTab,
|
||||
type MemoItem,
|
||||
type MemoResource,
|
||||
type MemoSettings,
|
||||
type MemoTag,
|
||||
} from '@/services/memoApi'
|
||||
import { getSafeAreaMetrics } from '@/utils/safeArea'
|
||||
import './index.scss'
|
||||
|
||||
function fmtTime(ts: number) {
|
||||
if (!ts) return ''
|
||||
const d = new Date(ts * 1000)
|
||||
const diff = (Date.now() - d.getTime()) / 1000
|
||||
if (diff < 60) return '刚刚'
|
||||
if (diff < 3600) return `${Math.floor(diff / 60)} 分钟前`
|
||||
if (diff < 86400) return `${Math.floor(diff / 3600)} 小时前`
|
||||
if (diff < 86400 * 30) return `${Math.floor(diff / 86400)} 天前`
|
||||
return `${d.getMonth() + 1}/${d.getDate()}`
|
||||
}
|
||||
|
||||
const TABS: { key: FeedTab; label: string }[] = [
|
||||
{ key: 'all', label: '全部' },
|
||||
{ key: 'featured', label: '精华' },
|
||||
{ key: 'latest', label: '最新' },
|
||||
{ key: 'mine', label: '收藏' },
|
||||
]
|
||||
|
||||
function Spin() {
|
||||
return (
|
||||
<View className="zk-spin" aria-hidden>
|
||||
<View className="zk-spin-ring" />
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
export default function VipMemoPage() {
|
||||
const cachedSettings = getCachedMemoSettings()
|
||||
const [items, setItems] = useState<MemoItem[]>(() => getCachedMemoFeed())
|
||||
const [tags, setTags] = useState<MemoTag[]>(() => getCachedMemoTags())
|
||||
const [activeTag, setActiveTag] = useState('')
|
||||
const [tab, setTab] = useState<FeedTab>('all')
|
||||
const [query, setQuery] = useState('')
|
||||
const [settings, setSettings] = useState<MemoSettings | null>(cachedSettings)
|
||||
const [draft, setDraft] = useState('')
|
||||
const [images, setImages] = useState<string[]>([])
|
||||
const [offline, setOffline] = useState(false)
|
||||
const [refreshing, setRefreshing] = useState(false)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [composerOpen, setComposerOpen] = useState(false)
|
||||
const bootRef = useRef(false)
|
||||
const safe = getSafeAreaMetrics()
|
||||
|
||||
async function refresh(opts?: { q?: string; tag?: string; tab?: FeedTab; soft?: boolean }) {
|
||||
const soft = opts?.soft !== false
|
||||
const hasList = items.length > 0
|
||||
if (!soft || !hasList) setRefreshing(true)
|
||||
try {
|
||||
// 本地已付则跳过 VIP 网络探测,秒开
|
||||
const vip = isVipPaidLocal() ? true : await resolveVipAccess()
|
||||
if (!vip) {
|
||||
Taro.showModal({
|
||||
title: 'VIP 专属',
|
||||
content: '开通 VIP 后进入知识社群',
|
||||
showCancel: false,
|
||||
success: () => goPage('/pages/vip/index'),
|
||||
})
|
||||
return
|
||||
}
|
||||
const home = await loadMemoHome({
|
||||
q: opts?.q ?? query,
|
||||
tag: opts?.tag ?? activeTag,
|
||||
tab: opts?.tab ?? tab,
|
||||
})
|
||||
setSettings(home.settings)
|
||||
setTags(home.tags)
|
||||
setItems(home.items)
|
||||
setOffline(!!home.offline)
|
||||
} catch {
|
||||
if (!items.length) setItems(getCachedMemoFeed())
|
||||
setOffline(true)
|
||||
} finally {
|
||||
setRefreshing(false)
|
||||
}
|
||||
}
|
||||
|
||||
useDidShow(() => {
|
||||
void refresh({ soft: bootRef.current })
|
||||
bootRef.current = true
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
// H5 无 didShow 时兜底;weapp 已由 didShow 拉,跳过重复
|
||||
if (process.env.TARO_ENV === 'h5' && !bootRef.current) {
|
||||
bootRef.current = true
|
||||
void refresh({ soft: true })
|
||||
}
|
||||
}, [])
|
||||
|
||||
async function pickImages() {
|
||||
if (settings && settings.canUpload === false) {
|
||||
Taro.showToast({ title: '暂不允许上传', icon: 'none' })
|
||||
return
|
||||
}
|
||||
const max = settings?.maxImages || 9
|
||||
const left = max - images.length
|
||||
if (left <= 0) {
|
||||
Taro.showToast({ title: `最多 ${max} 张`, icon: 'none' })
|
||||
return
|
||||
}
|
||||
try {
|
||||
const chosen = await Taro.chooseImage({
|
||||
count: left,
|
||||
sizeType: ['compressed'],
|
||||
sourceType: ['album', 'camera'],
|
||||
})
|
||||
const paths = chosen.tempFilePaths || []
|
||||
setBusy(true)
|
||||
const urls: string[] = []
|
||||
for (const p of paths) {
|
||||
urls.push(await uploadMemoImage(p))
|
||||
}
|
||||
setImages((prev) => [...prev, ...urls].slice(0, max))
|
||||
} catch (e) {
|
||||
const msg = String((e as Error).message || e || '')
|
||||
if (!/cancel|取消/i.test(msg)) {
|
||||
Taro.showToast({ title: msg.slice(0, 36) || '选图失败', icon: 'none' })
|
||||
}
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function onPost() {
|
||||
if ((!draft.trim() && !images.length) || busy) return
|
||||
setBusy(true)
|
||||
try {
|
||||
const resources: MemoResource[] = images.map((url) => ({ type: 'image', url }))
|
||||
const memo = await createMemo(draft.trim(), resources)
|
||||
setItems((prev) => [memo, ...prev.filter((x) => x.id !== memo.id)])
|
||||
setDraft('')
|
||||
setImages([])
|
||||
setComposerOpen(false)
|
||||
Taro.showToast({ title: '已发布', icon: 'success' })
|
||||
} catch (e) {
|
||||
Taro.showToast({ title: (e as Error).message || '发布失败', icon: 'none' })
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function onLike(id: string) {
|
||||
if (settings && !settings.canLike) {
|
||||
Taro.showToast({ title: '暂不允许点赞', icon: 'none' })
|
||||
return
|
||||
}
|
||||
try {
|
||||
const memo = await likeMemo(id)
|
||||
setItems((prev) => prev.map((x) => (x.id === id ? { ...x, ...memo } : x)))
|
||||
} catch (err) {
|
||||
Taro.showToast({ title: (err as Error).message || '失败', icon: 'none' })
|
||||
}
|
||||
}
|
||||
|
||||
async function onFavorite(id: string) {
|
||||
if (settings && settings.canFavorite === false) {
|
||||
Taro.showToast({ title: '暂不允许收藏', icon: 'none' })
|
||||
return
|
||||
}
|
||||
try {
|
||||
const memo = await favoriteMemo(id)
|
||||
setItems((prev) => {
|
||||
const next = prev.map((x) => (x.id === id ? { ...x, ...memo } : x))
|
||||
if (tab === 'mine' && !memo.favorited) return next.filter((x) => x.id !== id)
|
||||
return next
|
||||
})
|
||||
} catch (err) {
|
||||
Taro.showToast({ title: (err as Error).message || '失败', icon: 'none' })
|
||||
}
|
||||
}
|
||||
|
||||
async function onDelete(id: string) {
|
||||
const conf = await Taro.showModal({ title: '删除帖子?', confirmText: '删除' })
|
||||
if (!conf.confirm) return
|
||||
try {
|
||||
await deleteMemo(id)
|
||||
setItems((prev) => prev.filter((x) => x.id !== id))
|
||||
} catch (e) {
|
||||
Taro.showToast({ title: (e as Error).message || '删除失败', icon: 'none' })
|
||||
}
|
||||
}
|
||||
|
||||
const canPost = !!settings?.canPost && !settings?.adminOnlyPost
|
||||
const planetName = settings?.planetName || '知识社群'
|
||||
const planetDesc = settings?.planetDesc || '博主分享 · 会员阅读互动'
|
||||
const showBootSpin = refreshing && !items.length
|
||||
|
||||
return (
|
||||
<View className="zk" style={{ paddingTop: safe.statusBarHeight }}>
|
||||
<View className="zk-nav" style={{ paddingRight: safe.menuRightPad }}>
|
||||
<View className="zk-back" onClick={() => goPage('/pages/vip/index')}>
|
||||
<Text>←</Text>
|
||||
</View>
|
||||
<Text className="zk-nav-title">{planetName}</Text>
|
||||
{canPost ? (
|
||||
<View className="zk-nav-btn" onClick={() => setComposerOpen(true)}>
|
||||
<Text>发帖</Text>
|
||||
</View>
|
||||
) : (
|
||||
<View className="zk-nav-trail">
|
||||
{refreshing && items.length ? <View className="zk-spin zk-spin-sm"><View className="zk-spin-ring" /></View> : null}
|
||||
<View style={{ width: 8 }} />
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
|
||||
<View className="zk-hero">
|
||||
<View className="zk-hero-glow" />
|
||||
<Text className="zk-hero-badge">VIP · 知识星球</Text>
|
||||
<Text className="zk-hero-name">{planetName}</Text>
|
||||
<Text className="zk-hero-desc">{planetDesc}</Text>
|
||||
{settings?.notice ? <Text className="zk-hero-notice">{settings.notice}</Text> : null}
|
||||
{offline ? <Text className="zk-offline">离线 · 本地缓存</Text> : null}
|
||||
</View>
|
||||
|
||||
<View className="zk-search">
|
||||
<Input
|
||||
className="zk-search-input"
|
||||
value={query}
|
||||
placeholder="搜索标题 / 内容 / 话题"
|
||||
confirmType="search"
|
||||
onInput={(e) => setQuery(e.detail.value)}
|
||||
onConfirm={() => void refresh({ q: query, soft: false })}
|
||||
/>
|
||||
<Text className="zk-search-go" onClick={() => void refresh({ q: query, soft: false })}>
|
||||
搜
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
<View className="zk-tabs">
|
||||
{TABS.map((t) => (
|
||||
<View
|
||||
key={t.key}
|
||||
className={`zk-tab ${tab === t.key ? 'on' : ''}`}
|
||||
onClick={() => {
|
||||
setTab(t.key)
|
||||
void refresh({ tab: t.key, soft: false })
|
||||
}}
|
||||
>
|
||||
<Text>{t.label}</Text>
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
|
||||
{tags.length ? (
|
||||
<View className="zk-topics">
|
||||
<View
|
||||
className={`zk-topic ${!activeTag ? 'on' : ''}`}
|
||||
onClick={() => {
|
||||
setActiveTag('')
|
||||
void refresh({ tag: '', soft: false })
|
||||
}}
|
||||
>
|
||||
<Text>全部话题</Text>
|
||||
</View>
|
||||
{tags.map((t) => (
|
||||
<View
|
||||
key={t.name}
|
||||
className={`zk-topic ${activeTag === t.name ? 'on' : ''}`}
|
||||
onClick={() => {
|
||||
const next = activeTag === t.name ? '' : t.name
|
||||
setActiveTag(next)
|
||||
void refresh({ tag: next, soft: false })
|
||||
}}
|
||||
>
|
||||
<Text>#{t.name}</Text>
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{composerOpen ? (
|
||||
<View className="zk-composer">
|
||||
<Text className="zk-composer-hint">支持 Markdown · #话题 · 图片</Text>
|
||||
<Textarea
|
||||
className="zk-textarea"
|
||||
value={draft}
|
||||
maxlength={settings?.maxContentLen || 20000}
|
||||
placeholder={'## 标题\n\n写点干货…'}
|
||||
onInput={(e) => setDraft(e.detail.value)}
|
||||
/>
|
||||
{images.length ? (
|
||||
<View className="zk-img-grid">
|
||||
{images.map((u, i) => (
|
||||
<View key={u} className="zk-img-cell">
|
||||
<Image src={u} mode="aspectFill" className="zk-img" />
|
||||
<Text
|
||||
className="zk-img-x"
|
||||
onClick={() => setImages((prev) => prev.filter((_, j) => j !== i))}
|
||||
>
|
||||
×
|
||||
</Text>
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
) : null}
|
||||
<View className="zk-composer-actions">
|
||||
<Text className="zk-tool" onClick={() => void pickImages()}>
|
||||
图片
|
||||
</Text>
|
||||
<Text
|
||||
className="zk-tool"
|
||||
onClick={() => setDraft((d) => `${d}${d && !d.endsWith(' ') ? ' ' : ''}#`)}
|
||||
>
|
||||
#话题
|
||||
</Text>
|
||||
<View style={{ flex: 1 }} />
|
||||
<Text className="zk-cancel" onClick={() => setComposerOpen(false)}>
|
||||
取消
|
||||
</Text>
|
||||
<Button className="zk-send" loading={busy} onClick={() => void onPost()}>
|
||||
发布
|
||||
</Button>
|
||||
</View>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{showBootSpin ? (
|
||||
<View className="zk-boot">
|
||||
<Spin />
|
||||
</View>
|
||||
) : (
|
||||
<View className="zk-list">
|
||||
{items.map((m) => {
|
||||
const cover = m.cover || (m.resources || []).find((r) => r.url)?.url
|
||||
return (
|
||||
<View
|
||||
key={m.id}
|
||||
className="zk-card"
|
||||
onClick={() => goPage(`/pages/vip-memo-detail/index?id=${m.id}`)}
|
||||
>
|
||||
<View className="zk-card-main">
|
||||
<View className="zk-card-badges">
|
||||
{m.pinned ? <Text className="zk-badge pin">置顶</Text> : null}
|
||||
{m.featured ? <Text className="zk-badge feat">精华</Text> : null}
|
||||
</View>
|
||||
<Text className="zk-card-title">{m.title || '未命名'}</Text>
|
||||
{m.excerpt ? <Text className="zk-card-excerpt">{m.excerpt}</Text> : null}
|
||||
<View className="zk-card-meta">
|
||||
<Text className="zk-card-author">{m.nickname}</Text>
|
||||
<Text className="zk-card-dot">·</Text>
|
||||
<Text className="zk-card-time">{fmtTime(m.createdAt)}</Text>
|
||||
</View>
|
||||
{m.tags?.length ? (
|
||||
<View className="zk-card-tags">
|
||||
{m.tags.slice(0, 3).map((tg) => (
|
||||
<Text key={tg} className="zk-card-tag">
|
||||
#{tg}
|
||||
</Text>
|
||||
))}
|
||||
</View>
|
||||
) : null}
|
||||
<View className="zk-card-stats">
|
||||
<Text
|
||||
className={`zk-stat ${m.liked ? 'on' : ''}`}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
void onLike(m.id)
|
||||
}}
|
||||
>
|
||||
{m.liked ? '♥' : '♡'} {m.likeCount || 0}
|
||||
</Text>
|
||||
<Text className="zk-stat">💬 {m.commentCount || 0}</Text>
|
||||
<Text
|
||||
className={`zk-stat ${m.favorited ? 'on' : ''}`}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
void onFavorite(m.id)
|
||||
}}
|
||||
>
|
||||
{m.favorited ? '★' : '☆'} {m.favoriteCount || 0}
|
||||
</Text>
|
||||
{m.isMine ? (
|
||||
<Text
|
||||
className="zk-stat dim"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
void onDelete(m.id)
|
||||
}}
|
||||
>
|
||||
删
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
{cover ? (
|
||||
<Image src={cover} mode="aspectFill" className="zk-card-cover" lazyLoad />
|
||||
) : null}
|
||||
</View>
|
||||
)
|
||||
})}
|
||||
{!items.length ? (
|
||||
<View className="zk-empty">
|
||||
<Text>{tab === 'mine' ? '还没有收藏' : '暂无帖子'}</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
)
|
||||
}
|
||||
161
apps/miniprogram/h5/src/pages/vip-store-detail/index.scss
Normal file
161
apps/miniprogram/h5/src/pages/vip-store-detail/index.scss
Normal file
@ -0,0 +1,161 @@
|
||||
.vsd {
|
||||
min-height: 100vh;
|
||||
background: #0c0c0f;
|
||||
color: #e8eef7;
|
||||
padding-bottom: 96px;
|
||||
box-sizing: border-box;
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'PingFang SC', 'Helvetica Neue',
|
||||
'Noto Sans SC', 'Microsoft YaHei', sans-serif;
|
||||
}
|
||||
.vsd-loading {
|
||||
display: block;
|
||||
text-align: center;
|
||||
padding: 64px 16px;
|
||||
color: #94a3b8;
|
||||
font-size: 14px;
|
||||
}
|
||||
.vsd-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
height: 44px;
|
||||
padding: 0 4px;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
.vsd-back {
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: #f59e0b;
|
||||
font-size: 18px;
|
||||
}
|
||||
.vsd-title {
|
||||
flex: 1;
|
||||
text-align: center;
|
||||
font-weight: 600;
|
||||
font-size: 16px;
|
||||
}
|
||||
.vsd-hero {
|
||||
padding: 24px 20px 12px;
|
||||
text-align: center;
|
||||
}
|
||||
.vsd-emoji {
|
||||
display: block;
|
||||
font-size: 40px;
|
||||
line-height: 1;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.vsd-name {
|
||||
display: block;
|
||||
font-size: 18px;
|
||||
font-weight: 700;
|
||||
line-height: 1.35;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
.vsd-desc {
|
||||
display: block;
|
||||
font-size: 12px;
|
||||
font-weight: 400;
|
||||
color: #94a3b8;
|
||||
margin-bottom: 14px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.vsd-meta {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: baseline;
|
||||
gap: 10px;
|
||||
}
|
||||
.vsd-price {
|
||||
color: #f59e0b;
|
||||
font-size: 24px;
|
||||
font-weight: 700;
|
||||
}
|
||||
.vsd-tag {
|
||||
font-size: 12px;
|
||||
color: #64748b;
|
||||
font-weight: 400;
|
||||
}
|
||||
.vsd-form {
|
||||
margin: 8px 16px;
|
||||
padding: 14px;
|
||||
border-radius: 12px;
|
||||
background: #15151c;
|
||||
border: 1px solid rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
.vsd-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.vsd-row.col {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
gap: 8px;
|
||||
}
|
||||
.vsd-label {
|
||||
font-size: 13px;
|
||||
color: #cbd5e1;
|
||||
font-weight: 500;
|
||||
}
|
||||
.vsd-qty {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
.vsd-qty-btn {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border-radius: 10px;
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
text-align: center;
|
||||
line-height: 36px;
|
||||
font-size: 18px;
|
||||
}
|
||||
.vsd-qty-n {
|
||||
min-width: 24px;
|
||||
text-align: center;
|
||||
font-weight: 600;
|
||||
font-size: 15px;
|
||||
}
|
||||
.vsd-input {
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border-radius: 10px;
|
||||
padding: 10px 12px;
|
||||
font-size: 14px;
|
||||
color: #e8eef7;
|
||||
}
|
||||
.vsd-addr {
|
||||
min-height: 64px;
|
||||
padding: 12px;
|
||||
border-radius: 10px;
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
white-space: pre-wrap;
|
||||
font-weight: 400;
|
||||
}
|
||||
.vsd-addr-hint {
|
||||
color: #f59e0b;
|
||||
font-size: 13px;
|
||||
}
|
||||
.vsd-cta-wrap {
|
||||
position: fixed;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
padding: 10px 16px calc(10px + env(safe-area-inset-bottom));
|
||||
background: rgba(12, 12, 15, 0.94);
|
||||
border-top: 1px solid rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
.vsd-cta {
|
||||
background: linear-gradient(135deg, #fbbf24, #f59e0b) !important;
|
||||
color: #0c0c0f !important;
|
||||
border: none !important;
|
||||
border-radius: 12px !important;
|
||||
font-weight: 700 !important;
|
||||
font-size: 15px !important;
|
||||
line-height: 1.2 !important;
|
||||
}
|
||||
219
apps/miniprogram/h5/src/pages/vip-store-detail/index.tsx
Normal file
219
apps/miniprogram/h5/src/pages/vip-store-detail/index.tsx
Normal file
@ -0,0 +1,219 @@
|
||||
/**
|
||||
* 商品详情 + 下单(虚拟邮箱 / 实体 chooseAddress)
|
||||
*/
|
||||
import { useEffect, useState } from 'react'
|
||||
import { View, Text, Input, Button } from '@tarojs/components'
|
||||
import Taro, { useRouter } from '@tarojs/taro'
|
||||
import { goPage } from '@/utils/nav'
|
||||
import { resolveVipAccess } from '@/utils/vipAccess'
|
||||
import {
|
||||
chooseShopAddress,
|
||||
createShopPayOrder,
|
||||
devConfirmShopOrder,
|
||||
loadShopProduct,
|
||||
type ShopAddress,
|
||||
} from '@/services/shopApi'
|
||||
import type { ShopProduct } from '@/data/vipStoreCatalog'
|
||||
import { getSafeAreaMetrics } from '@/utils/safeArea'
|
||||
import './index.scss'
|
||||
|
||||
function invokeVirtualPayment(payData: {
|
||||
signData: string
|
||||
mode: string
|
||||
paySig: string
|
||||
signature: string
|
||||
}): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const api = Taro as unknown as {
|
||||
requestVirtualPayment?: (opts: Record<string, unknown>) => void
|
||||
}
|
||||
if (typeof api.requestVirtualPayment !== 'function') {
|
||||
reject(new Error('当前环境不支持虚拟支付'))
|
||||
return
|
||||
}
|
||||
api.requestVirtualPayment({
|
||||
signData: payData.signData,
|
||||
mode: payData.mode,
|
||||
paySig: payData.paySig,
|
||||
signature: payData.signature,
|
||||
success: () => resolve(),
|
||||
fail: (err: { errMsg?: string }) => reject(new Error(err?.errMsg || '支付失败')),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
export default function VipStoreDetailPage() {
|
||||
const router = useRouter()
|
||||
const id = String(router.params.id || '')
|
||||
const [product, setProduct] = useState<ShopProduct | null>(null)
|
||||
const [email, setEmail] = useState('')
|
||||
const [address, setAddress] = useState<ShopAddress | null>(null)
|
||||
const [qty, setQty] = useState(1)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const safe = getSafeAreaMetrics()
|
||||
|
||||
useEffect(() => {
|
||||
void (async () => {
|
||||
const access = await resolveVipAccess()
|
||||
if (!access) {
|
||||
Taro.showModal({
|
||||
title: 'VIP 专属',
|
||||
content: '开通 VIP 后可下单',
|
||||
showCancel: false,
|
||||
success: () => goPage('/pages/vip/index'),
|
||||
})
|
||||
return
|
||||
}
|
||||
try {
|
||||
const p = await loadShopProduct(id)
|
||||
setProduct(p)
|
||||
} catch (e) {
|
||||
Taro.showToast({ title: (e as Error).message || '加载失败', icon: 'none' })
|
||||
}
|
||||
})()
|
||||
}, [id])
|
||||
|
||||
async function pickAddress() {
|
||||
try {
|
||||
const addr = await chooseShopAddress()
|
||||
setAddress(addr)
|
||||
} catch (e) {
|
||||
Taro.showToast({ title: (e as Error).message || '地址获取失败', icon: 'none' })
|
||||
}
|
||||
}
|
||||
|
||||
async function onBuy() {
|
||||
if (!product || busy) return
|
||||
if (product.stock < qty) {
|
||||
Taro.showToast({ title: '库存不足', icon: 'none' })
|
||||
return
|
||||
}
|
||||
if (product.goodsType === 'virtual' && !email.trim()) {
|
||||
Taro.showToast({ title: '请填写邮箱', icon: 'none' })
|
||||
return
|
||||
}
|
||||
if (product.goodsType === 'physical' && !address) {
|
||||
Taro.showToast({ title: '请选择收货地址', icon: 'none' })
|
||||
return
|
||||
}
|
||||
setBusy(true)
|
||||
try {
|
||||
const pay = await createShopPayOrder({
|
||||
productId: product.id,
|
||||
qty,
|
||||
email: email.trim(),
|
||||
address,
|
||||
})
|
||||
if (pay.devPay) {
|
||||
const conf = await Taro.showModal({
|
||||
title: '调试支付',
|
||||
content: '未配置道具 ID,是否模拟支付成功?',
|
||||
confirmText: '模拟成功',
|
||||
})
|
||||
if (!conf.confirm) return
|
||||
await devConfirmShopOrder(pay.outTradeNo)
|
||||
} else {
|
||||
await invokeVirtualPayment(pay)
|
||||
}
|
||||
Taro.showToast({ title: '支付成功', icon: 'success' })
|
||||
setTimeout(() => goPage('/pages/vip-store-orders/index'), 600)
|
||||
} catch (e) {
|
||||
const msg = String((e as Error).message || e || '')
|
||||
if (!/cancel|取消/i.test(msg)) {
|
||||
Taro.showToast({ title: msg.slice(0, 40) || '下单失败', icon: 'none' })
|
||||
}
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (!product) {
|
||||
return (
|
||||
<View className="vsd" style={{ paddingTop: safe.safeTop }}>
|
||||
<Text className="vsd-loading">加载中…</Text>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<View className="vsd" style={{ paddingTop: safe.safeTop }}>
|
||||
<View className="vsd-head">
|
||||
<View className="vsd-back" onClick={() => goPage('/pages/vip-store/index')}>
|
||||
<Text>←</Text>
|
||||
</View>
|
||||
<Text className="vsd-title">下单</Text>
|
||||
<View style={{ width: 44 }} />
|
||||
</View>
|
||||
|
||||
<View className="vsd-hero">
|
||||
<Text className="vsd-emoji">{product.coverEmoji || '🛒'}</Text>
|
||||
<Text className="vsd-name">{product.title}</Text>
|
||||
<Text className="vsd-desc">{product.desc}</Text>
|
||||
<View className="vsd-meta">
|
||||
<Text className="vsd-price">¥{(product.priceFen / 100).toFixed(2)}</Text>
|
||||
<Text className="vsd-tag">
|
||||
{product.goodsType === 'virtual' ? '虚拟发卡' : '实体发货'} · 库存 {product.stock}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<View className="vsd-form">
|
||||
<View className="vsd-row">
|
||||
<Text className="vsd-label">数量</Text>
|
||||
<View className="vsd-qty">
|
||||
<Text
|
||||
className="vsd-qty-btn"
|
||||
onClick={() => setQty((q) => Math.max(1, q - 1))}
|
||||
>
|
||||
−
|
||||
</Text>
|
||||
<Text className="vsd-qty-n">{qty}</Text>
|
||||
<Text
|
||||
className="vsd-qty-btn"
|
||||
onClick={() => setQty((q) => Math.min(product.stock || 1, q + 1))}
|
||||
>
|
||||
+
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
{product.goodsType === 'virtual' ? (
|
||||
<View className="vsd-row col">
|
||||
<Text className="vsd-label">接收邮箱</Text>
|
||||
<Input
|
||||
className="vsd-input"
|
||||
type="text"
|
||||
placeholder="用于接收卡密通知"
|
||||
value={email}
|
||||
onInput={(e) => setEmail(e.detail.value)}
|
||||
/>
|
||||
</View>
|
||||
) : (
|
||||
<View className="vsd-row col">
|
||||
<Text className="vsd-label">收货地址</Text>
|
||||
<View className="vsd-addr" onClick={() => void pickAddress()}>
|
||||
{address ? (
|
||||
<Text>
|
||||
{address.userName} {address.telNumber}
|
||||
{'\n'}
|
||||
{address.provinceName}
|
||||
{address.cityName}
|
||||
{address.countyName}
|
||||
{address.detailInfo}
|
||||
</Text>
|
||||
) : (
|
||||
<Text className="vsd-addr-hint">点击选择微信收货地址</Text>
|
||||
)}
|
||||
</View>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
|
||||
<View className="vsd-cta-wrap">
|
||||
<Button className="vsd-cta" loading={busy} onClick={() => void onBuy()}>
|
||||
立即支付 · ¥{((product.priceFen * qty) / 100).toFixed(2)}
|
||||
</Button>
|
||||
</View>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
100
apps/miniprogram/h5/src/pages/vip-store-orders/index.scss
Normal file
100
apps/miniprogram/h5/src/pages/vip-store-orders/index.scss
Normal file
@ -0,0 +1,100 @@
|
||||
.vso {
|
||||
min-height: 100vh;
|
||||
background: #0c0c0f;
|
||||
color: #e8eef7;
|
||||
padding-bottom: 40px;
|
||||
box-sizing: border-box;
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'PingFang SC', 'Helvetica Neue',
|
||||
'Noto Sans SC', 'Microsoft YaHei', sans-serif;
|
||||
}
|
||||
.vso-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
height: 44px;
|
||||
padding: 0 4px;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
.vso-back {
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: #f59e0b;
|
||||
font-size: 18px;
|
||||
}
|
||||
.vso-title {
|
||||
flex: 1;
|
||||
text-align: center;
|
||||
font-weight: 600;
|
||||
font-size: 16px;
|
||||
}
|
||||
.vso-list {
|
||||
padding: 14px 16px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
.vso-card {
|
||||
padding: 12px 14px;
|
||||
border-radius: 12px;
|
||||
background: #15151c;
|
||||
border: 1px solid rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
.vso-top {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.vso-name {
|
||||
flex: 1;
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
line-height: 1.35;
|
||||
}
|
||||
.vso-status {
|
||||
color: #f59e0b;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.vso-sub {
|
||||
display: block;
|
||||
font-size: 12px;
|
||||
color: #94a3b8;
|
||||
margin-bottom: 8px;
|
||||
font-weight: 400;
|
||||
}
|
||||
.vso-carmi {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
padding: 8px 10px;
|
||||
border-radius: 8px;
|
||||
background: rgba(245, 158, 11, 0.1);
|
||||
font-size: 12px;
|
||||
margin-bottom: 6px;
|
||||
word-break: break-all;
|
||||
font-weight: 400;
|
||||
}
|
||||
.vso-copy {
|
||||
color: #f59e0b;
|
||||
flex-shrink: 0;
|
||||
font-weight: 500;
|
||||
}
|
||||
.vso-ship,
|
||||
.vso-addr,
|
||||
.vso-time {
|
||||
display: block;
|
||||
font-size: 12px;
|
||||
color: #64748b;
|
||||
line-height: 1.45;
|
||||
margin-top: 4px;
|
||||
font-weight: 400;
|
||||
}
|
||||
.vso-empty {
|
||||
text-align: center;
|
||||
padding: 48px 16px;
|
||||
color: #94a3b8;
|
||||
font-size: 13px;
|
||||
}
|
||||
98
apps/miniprogram/h5/src/pages/vip-store-orders/index.tsx
Normal file
98
apps/miniprogram/h5/src/pages/vip-store-orders/index.tsx
Normal file
@ -0,0 +1,98 @@
|
||||
import { useState } from 'react'
|
||||
import { View, Text } from '@tarojs/components'
|
||||
import Taro, { useDidShow } from '@tarojs/taro'
|
||||
import { goPage } from '@/utils/nav'
|
||||
import { fetchMyShopOrders, type ShopOrder } from '@/services/shopApi'
|
||||
import { getSafeAreaMetrics } from '@/utils/safeArea'
|
||||
import './index.scss'
|
||||
|
||||
const STATUS_LABEL: Record<string, string> = {
|
||||
pending: '待支付',
|
||||
paid: '待发货',
|
||||
shipped: '已发货',
|
||||
delivered: '已发卡',
|
||||
}
|
||||
|
||||
export default function VipStoreOrdersPage() {
|
||||
const [items, setItems] = useState<ShopOrder[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const safe = getSafeAreaMetrics()
|
||||
|
||||
async function refresh() {
|
||||
setLoading(true)
|
||||
try {
|
||||
setItems(await fetchMyShopOrders())
|
||||
} catch (e) {
|
||||
Taro.showToast({ title: (e as Error).message || '加载失败', icon: 'none' })
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
useDidShow(() => {
|
||||
void refresh()
|
||||
})
|
||||
|
||||
function copyCarmi(codes: string[]) {
|
||||
void Taro.setClipboardData({ data: codes.join('\n') }).then(() => {
|
||||
Taro.showToast({ title: '卡密已复制', icon: 'success' })
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<View className="vso" style={{ paddingTop: safe.safeTop }}>
|
||||
<View className="vso-head">
|
||||
<View className="vso-back" onClick={() => goPage('/pages/vip-store/index')}>
|
||||
<Text>←</Text>
|
||||
</View>
|
||||
<Text className="vso-title">我的订单</Text>
|
||||
<View style={{ width: 44 }} />
|
||||
</View>
|
||||
|
||||
{loading ? (
|
||||
<View className="vso-empty">
|
||||
<Text>加载中…</Text>
|
||||
</View>
|
||||
) : (
|
||||
<View className="vso-list">
|
||||
{items.map((o) => (
|
||||
<View key={o.id} className="vso-card">
|
||||
<View className="vso-top">
|
||||
<Text className="vso-name">{o.productTitle}</Text>
|
||||
<Text className="vso-status">{STATUS_LABEL[o.status] || o.status}</Text>
|
||||
</View>
|
||||
<Text className="vso-sub">
|
||||
{o.goodsType === 'virtual' ? '虚拟' : '实体'} · ×{o.qty} · ¥
|
||||
{(o.amountFen / 100).toFixed(2)}
|
||||
</Text>
|
||||
{o.carmis?.length ? (
|
||||
<View className="vso-carmi" onClick={() => copyCarmi(o.carmis || [])}>
|
||||
<Text>卡密:{o.carmis.join(' / ')}</Text>
|
||||
<Text className="vso-copy">复制</Text>
|
||||
</View>
|
||||
) : null}
|
||||
{o.trackingNo ? (
|
||||
<Text className="vso-ship">
|
||||
物流 {o.expressCompany} {o.trackingNo}
|
||||
</Text>
|
||||
) : null}
|
||||
{o.address?.userName ? (
|
||||
<Text className="vso-addr">
|
||||
{o.address.userName} {o.address.telNumber} · {o.address.detailInfo}
|
||||
</Text>
|
||||
) : null}
|
||||
<Text className="vso-time">
|
||||
{o.createdAt ? new Date(o.createdAt * 1000).toLocaleString() : ''}
|
||||
</Text>
|
||||
</View>
|
||||
))}
|
||||
{!items.length ? (
|
||||
<View className="vso-empty">
|
||||
<Text>暂无订单</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
)
|
||||
}
|
||||
166
apps/miniprogram/h5/src/pages/vip-store/index.scss
Normal file
166
apps/miniprogram/h5/src/pages/vip-store/index.scss
Normal file
@ -0,0 +1,166 @@
|
||||
/* 真实 px:已加入 weapp pxExclude,勿再按 750 放大 */
|
||||
.vs {
|
||||
min-height: 100vh;
|
||||
background: #0c0c0f;
|
||||
color: #e8eef7;
|
||||
padding-bottom: 40px;
|
||||
box-sizing: border-box;
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'PingFang SC', 'Helvetica Neue',
|
||||
'Noto Sans SC', 'Microsoft YaHei', sans-serif;
|
||||
}
|
||||
.vs-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
height: 44px;
|
||||
padding: 0 4px 0 0;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
.vs-back,
|
||||
.vs-orders {
|
||||
min-width: 44px;
|
||||
min-height: 44px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: #f59e0b;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
}
|
||||
.vs-title {
|
||||
flex: 1;
|
||||
text-align: center;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
.vs-offline {
|
||||
margin: 10px 16px 0;
|
||||
padding: 6px 10px;
|
||||
border-radius: 8px;
|
||||
background: rgba(245, 158, 11, 0.1);
|
||||
color: #fbbf24;
|
||||
font-size: 12px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
.vs-hero {
|
||||
padding: 20px 16px 8px;
|
||||
}
|
||||
.vs-hero-h {
|
||||
display: block;
|
||||
font-size: 20px;
|
||||
font-weight: 700;
|
||||
line-height: 1.35;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
.vs-hero-s {
|
||||
display: block;
|
||||
font-size: 12px;
|
||||
color: #94a3b8;
|
||||
line-height: 1.5;
|
||||
font-weight: 400;
|
||||
}
|
||||
.vs-tabs {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
padding: 10px 16px 14px;
|
||||
overflow-x: auto;
|
||||
}
|
||||
.vs-tab {
|
||||
flex-shrink: 0;
|
||||
min-height: 32px;
|
||||
padding: 0 14px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.12);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
color: #cbd5e1;
|
||||
}
|
||||
.vs-tab.is-on {
|
||||
background: #f59e0b;
|
||||
border-color: #f59e0b;
|
||||
color: #0c0c0f;
|
||||
font-weight: 600;
|
||||
}
|
||||
.vs-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 10px;
|
||||
padding: 0 16px;
|
||||
}
|
||||
.vs-card {
|
||||
background: #15151c;
|
||||
border-radius: 12px;
|
||||
overflow: hidden;
|
||||
border: 1px solid rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
.vs-card-cover {
|
||||
position: relative;
|
||||
height: 88px;
|
||||
background: linear-gradient(160deg, #1c1c26, #111827);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
.vs-card-img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
.vs-card-emoji {
|
||||
font-size: 32px;
|
||||
line-height: 1;
|
||||
}
|
||||
.vs-badge {
|
||||
position: absolute;
|
||||
left: 8px;
|
||||
top: 8px;
|
||||
font-size: 10px;
|
||||
font-weight: 500;
|
||||
padding: 2px 6px;
|
||||
border-radius: 4px;
|
||||
background: rgba(12, 12, 15, 0.72);
|
||||
color: #fbbf24;
|
||||
line-height: 1.3;
|
||||
}
|
||||
.vs-card-title {
|
||||
display: block;
|
||||
padding: 10px 10px 2px;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
line-height: 1.35;
|
||||
color: #f1f5f9;
|
||||
}
|
||||
.vs-card-desc {
|
||||
display: block;
|
||||
padding: 0 10px;
|
||||
font-size: 11px;
|
||||
font-weight: 400;
|
||||
color: #94a3b8;
|
||||
line-height: 1.4;
|
||||
min-height: 28px;
|
||||
}
|
||||
.vs-card-foot {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: baseline;
|
||||
padding: 8px 10px 12px;
|
||||
}
|
||||
.vs-price {
|
||||
color: #f59e0b;
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
line-height: 1;
|
||||
}
|
||||
.vs-stock {
|
||||
font-size: 11px;
|
||||
font-weight: 400;
|
||||
color: #64748b;
|
||||
}
|
||||
.vs-empty {
|
||||
grid-column: 1 / -1;
|
||||
text-align: center;
|
||||
padding: 40px 16px;
|
||||
color: #94a3b8;
|
||||
font-size: 13px;
|
||||
}
|
||||
139
apps/miniprogram/h5/src/pages/vip-store/index.tsx
Normal file
139
apps/miniprogram/h5/src/pages/vip-store/index.tsx
Normal file
@ -0,0 +1,139 @@
|
||||
/**
|
||||
* VIP 设备商城 — 原生页(无 web-view)
|
||||
*/
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { View, Text, Image } from '@tarojs/components'
|
||||
import Taro, { useDidShow } from '@tarojs/taro'
|
||||
import { goPage } from '@/utils/nav'
|
||||
import { resolveVipAccess } from '@/utils/vipAccess'
|
||||
import { loadShopCatalog } from '@/services/shopApi'
|
||||
import type { ShopCatalog } from '@/data/vipStoreCatalog'
|
||||
import { LOCAL_SHOP_CATALOG } from '@/data/vipStoreCatalog'
|
||||
import { getSafeAreaMetrics } from '@/utils/safeArea'
|
||||
import './index.scss'
|
||||
|
||||
export default function VipStorePage() {
|
||||
const [catalog, setCatalog] = useState<ShopCatalog>(LOCAL_SHOP_CATALOG)
|
||||
const [group, setGroup] = useState('all')
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [isVip, setIsVip] = useState(false)
|
||||
const safe = getSafeAreaMetrics()
|
||||
|
||||
async function refresh() {
|
||||
setLoading(true)
|
||||
try {
|
||||
const access = await resolveVipAccess()
|
||||
setIsVip(!!access)
|
||||
const data = await loadShopCatalog()
|
||||
setCatalog(data)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
useDidShow(() => {
|
||||
void refresh()
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
void refresh()
|
||||
}, [])
|
||||
|
||||
const products = useMemo(() => {
|
||||
if (group === 'all') return catalog.products
|
||||
return catalog.products.filter((p) => p.groupName === group)
|
||||
}, [catalog, group])
|
||||
|
||||
function onLocked() {
|
||||
Taro.showModal({
|
||||
title: 'VIP 专属',
|
||||
content: '开通 VIP 后解锁设备自助下单',
|
||||
confirmText: '去开通',
|
||||
success: (r) => {
|
||||
if (r.confirm) goPage('/pages/vip/index')
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
function openProduct(id: string) {
|
||||
if (!isVip) {
|
||||
onLocked()
|
||||
return
|
||||
}
|
||||
goPage(`/pages/vip-store-detail/index?id=${id}`)
|
||||
}
|
||||
|
||||
return (
|
||||
<View className="vs" style={{ paddingTop: safe.safeTop }}>
|
||||
<View className="vs-head">
|
||||
<View className="vs-back" onClick={() => goPage('/pages/vip/index')}>
|
||||
<Text>←</Text>
|
||||
</View>
|
||||
<Text className="vs-title">设备自助下单</Text>
|
||||
<View
|
||||
className="vs-orders"
|
||||
onClick={() => (isVip ? goPage('/pages/vip-store-orders/index') : onLocked())}
|
||||
>
|
||||
<Text>订单</Text>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
{catalog.offline ? (
|
||||
<View className="vs-offline">
|
||||
<Text>离线目录 · 本地数据</Text>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
<View className="vs-hero">
|
||||
<Text className="vs-hero-h">今天需要一点什么?</Text>
|
||||
<Text className="vs-hero-s">虚拟发卡即时到账 · 实体设备填写收货地址</Text>
|
||||
</View>
|
||||
|
||||
<View className="vs-tabs">
|
||||
{catalog.groups.map((g) => (
|
||||
<View
|
||||
key={g.id}
|
||||
className={`vs-tab ${group === g.id ? 'is-on' : ''}`}
|
||||
onClick={() => setGroup(g.id)}
|
||||
>
|
||||
<Text>{g.name}</Text>
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
|
||||
{loading ? (
|
||||
<View className="vs-empty">
|
||||
<Text>加载中…</Text>
|
||||
</View>
|
||||
) : (
|
||||
<View className="vs-grid">
|
||||
{products.map((p) => (
|
||||
<View key={p.id} className="vs-card" onClick={() => openProduct(p.id)}>
|
||||
<View className="vs-card-cover">
|
||||
{p.cover ? (
|
||||
<Image src={p.cover} mode="aspectFill" className="vs-card-img" />
|
||||
) : (
|
||||
<Text className="vs-card-emoji">{p.coverEmoji || '🛒'}</Text>
|
||||
)}
|
||||
<Text className="vs-badge">
|
||||
{p.goodsType === 'virtual' ? '虚拟发卡' : '实体发货'}
|
||||
</Text>
|
||||
</View>
|
||||
<Text className="vs-card-title">{p.title}</Text>
|
||||
<Text className="vs-card-desc">{p.desc}</Text>
|
||||
<View className="vs-card-foot">
|
||||
<Text className="vs-price">¥{(p.priceFen / 100).toFixed(0)}</Text>
|
||||
<Text className="vs-stock">库存 {p.stock}</Text>
|
||||
</View>
|
||||
</View>
|
||||
))}
|
||||
{!products.length ? (
|
||||
<View className="vs-empty">
|
||||
<Text>暂无商品</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
)
|
||||
}
|
||||
@ -45,9 +45,9 @@ const TOPICS_DISPLAY = [
|
||||
{
|
||||
id: 'community',
|
||||
icon: '👥',
|
||||
title: '私密社群',
|
||||
title: '知识社群',
|
||||
desc: '抱团出海',
|
||||
href: 'https://qun.hackrobot.cn',
|
||||
href: '/pages/vip-memo/index',
|
||||
locked: true,
|
||||
},
|
||||
{
|
||||
@ -55,7 +55,7 @@ const TOPICS_DISPLAY = [
|
||||
icon: '🛒',
|
||||
title: '设备自助下单',
|
||||
desc: '开箱即用',
|
||||
href: 'https://store.hackrobot.cn/',
|
||||
href: '/pages/vip-store/index',
|
||||
locked: true,
|
||||
},
|
||||
] as const
|
||||
@ -113,7 +113,7 @@ const EBOOKS_DISPLAY = [
|
||||
const COMPARE_ITEMS = [
|
||||
{ feature: '电子书', single: '按需开通', member: '全解锁' },
|
||||
{ feature: '视频教程', single: '按需开通', member: '全解锁' },
|
||||
{ feature: '私密社群', single: '—', member: '✓' },
|
||||
{ feature: '知识社群', single: '—', member: '✓' },
|
||||
{ feature: '即时问答', single: '—', member: '✓' },
|
||||
{ feature: '持续更新', single: '—', member: '✓' },
|
||||
] as const
|
||||
@ -121,7 +121,7 @@ const COMPARE_ITEMS = [
|
||||
const FAQ_ITEMS = [
|
||||
{
|
||||
q: '会员包含哪些内容?',
|
||||
a: '电子书、视频教程、私密社群、即时问答、设备自助下单等全部解锁,并享受持续更新。',
|
||||
a: '电子书、视频教程、知识社群、即时问答、设备自助下单等全部解锁,并享受持续更新。',
|
||||
},
|
||||
{
|
||||
q: '如何加入?',
|
||||
@ -260,7 +260,7 @@ function VipLanding() {
|
||||
function onLocked() {
|
||||
void Taro.showModal({
|
||||
title: '会员专享',
|
||||
content: '开通 VIP 后解锁私密社群、设备商城等权益',
|
||||
content: '开通 VIP 后解锁知识社群、设备商城等权益',
|
||||
confirmText: '去开通',
|
||||
cancelText: '再看看',
|
||||
success: (r) => {
|
||||
@ -324,6 +324,24 @@ function VipLanding() {
|
||||
return
|
||||
}
|
||||
|
||||
if (
|
||||
href.includes('vip-store') ||
|
||||
href === '/pages/vip-store/index' ||
|
||||
href.includes('/store')
|
||||
) {
|
||||
goPage('/pages/vip-store/index')
|
||||
return
|
||||
}
|
||||
|
||||
if (
|
||||
href.includes('vip-memo') ||
|
||||
href.includes('qun.hackrobot') ||
|
||||
href === '/pages/vip-memo/index'
|
||||
) {
|
||||
goPage('/pages/vip-memo/index')
|
||||
return
|
||||
}
|
||||
|
||||
const url = href.startsWith('http')
|
||||
? href
|
||||
: `https://nomadro.cn${href.startsWith('/') ? href : `/${href}`}`
|
||||
@ -422,7 +440,7 @@ function VipLanding() {
|
||||
<H5Txt className="vip-heroTitleRest">持续更新 · 抱团出海</H5Txt>
|
||||
</H5Box>
|
||||
<H5Txt className="vip-heroLead">
|
||||
一次付费,解锁电子书、视频教程、私密社群、即时问答,每周更新
|
||||
一次付费,解锁电子书、视频教程、知识社群、即时问答,每周更新
|
||||
</H5Txt>
|
||||
</H5Box>
|
||||
|
||||
|
||||
328
apps/miniprogram/h5/src/services/memoApi.ts
Normal file
328
apps/miniprogram/h5/src/services/memoApi.ts
Normal file
@ -0,0 +1,328 @@
|
||||
import Taro from '@tarojs/taro'
|
||||
import { API_BASE, STORAGE_TOKEN } from '@/utils/config'
|
||||
import { ensureLogin } from '@/utils/request'
|
||||
|
||||
const FEED_CACHE = 'nomadro_memo_feed_v4'
|
||||
const SETTINGS_CACHE = 'nomadro_memo_settings_v1'
|
||||
const TAGS_CACHE = 'nomadro_memo_tags_v1'
|
||||
const DETAIL_PREFIX = 'nomadro_memo_detail_v1_'
|
||||
|
||||
/** 只打 ebook 前缀,避免双路径串行拖慢 */
|
||||
const P = '/api/ebook/memo'
|
||||
const TIMEOUT_MS = 8000
|
||||
|
||||
export type MemoResource = { type: string; url: string }
|
||||
|
||||
export type MemoItem = {
|
||||
id: string
|
||||
openid: string
|
||||
nickname: string
|
||||
title?: string
|
||||
excerpt?: string
|
||||
content: string
|
||||
resources?: MemoResource[]
|
||||
cover?: string
|
||||
tags?: string[]
|
||||
pinned: boolean
|
||||
featured?: boolean
|
||||
likeCount: number
|
||||
commentCount: number
|
||||
favoriteCount?: number
|
||||
liked?: boolean
|
||||
favorited?: boolean
|
||||
isMine?: boolean
|
||||
createdAt: number
|
||||
}
|
||||
|
||||
export type MemoComment = {
|
||||
id: string
|
||||
memoId: string
|
||||
openid: string
|
||||
nickname: string
|
||||
content: string
|
||||
createdAt: number
|
||||
}
|
||||
|
||||
export type MemoSettings = {
|
||||
enabled: boolean
|
||||
canPost: boolean
|
||||
canComment: boolean
|
||||
canLike: boolean
|
||||
canFavorite?: boolean
|
||||
canUpload?: boolean
|
||||
adminOnlyPost: boolean
|
||||
planetName?: string
|
||||
planetDesc?: string
|
||||
notice: string
|
||||
maxContentLen: number
|
||||
maxImages?: number
|
||||
}
|
||||
|
||||
export type MemoTag = { name: string; count: number }
|
||||
|
||||
export type FeedTab = 'all' | 'featured' | 'latest' | 'mine'
|
||||
|
||||
const OFFLINE_FEED: MemoItem[] = [
|
||||
{
|
||||
id: 'offline-1',
|
||||
openid: '__system__',
|
||||
nickname: 'Nomadro',
|
||||
title: '欢迎加入知识社群',
|
||||
excerpt: 'VIP 专属内容区,博主分享干货,会员阅读互动。',
|
||||
content: '## 欢迎加入知识社群\n\n支持 Markdown、图片与话题。\n\n#欢迎',
|
||||
resources: [],
|
||||
tags: ['欢迎'],
|
||||
pinned: true,
|
||||
featured: true,
|
||||
likeCount: 0,
|
||||
commentCount: 0,
|
||||
favoriteCount: 0,
|
||||
createdAt: Date.now() / 1000,
|
||||
},
|
||||
]
|
||||
|
||||
const DEFAULT_SETTINGS: MemoSettings = {
|
||||
enabled: true,
|
||||
canPost: false,
|
||||
canComment: true,
|
||||
canLike: true,
|
||||
canFavorite: true,
|
||||
canUpload: true,
|
||||
adminOnlyPost: true,
|
||||
planetName: 'Nomadro 知识社群',
|
||||
planetDesc: '博主分享实战干货,会员阅读互动',
|
||||
notice: '',
|
||||
maxContentLen: 20000,
|
||||
maxImages: 9,
|
||||
}
|
||||
|
||||
function authHeader(): Record<string, string> {
|
||||
const token = Taro.getStorageSync(STORAGE_TOKEN)
|
||||
return token ? { Authorization: `Bearer ${token}` } : {}
|
||||
}
|
||||
|
||||
function readCache<T>(key: string): T | null {
|
||||
try {
|
||||
const raw = Taro.getStorageSync(key)
|
||||
return raw != null && raw !== '' ? (raw as T) : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function writeCache(key: string, val: unknown) {
|
||||
try {
|
||||
Taro.setStorageSync(key, val)
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
async function req<T>(
|
||||
path: string,
|
||||
init?: { method?: string; data?: unknown },
|
||||
): Promise<T> {
|
||||
await ensureLogin(false)
|
||||
const res = await Taro.request({
|
||||
url: `${API_BASE}${path}`,
|
||||
method: (init?.method as 'GET' | 'POST' | 'DELETE') || 'GET',
|
||||
data: init?.data,
|
||||
timeout: TIMEOUT_MS,
|
||||
header: {
|
||||
'Content-Type': 'application/json',
|
||||
...authHeader(),
|
||||
},
|
||||
})
|
||||
if (res.statusCode < 400) return res.data as T
|
||||
if (res.statusCode === 401) {
|
||||
await ensureLogin(true)
|
||||
const res2 = await Taro.request({
|
||||
url: `${API_BASE}${path}`,
|
||||
method: (init?.method as 'GET' | 'POST' | 'DELETE') || 'GET',
|
||||
data: init?.data,
|
||||
timeout: TIMEOUT_MS,
|
||||
header: {
|
||||
'Content-Type': 'application/json',
|
||||
...authHeader(),
|
||||
},
|
||||
})
|
||||
if (res2.statusCode < 400) return res2.data as T
|
||||
const d2 = (res2.data as { detail?: string })?.detail
|
||||
throw new Error(typeof d2 === 'string' ? d2 : '请求失败')
|
||||
}
|
||||
const detail = (res.data as { detail?: string })?.detail
|
||||
throw new Error(typeof detail === 'string' ? detail : '请求失败')
|
||||
}
|
||||
|
||||
export function getCachedMemoFeed(): MemoItem[] {
|
||||
const raw = readCache<MemoItem[]>(FEED_CACHE)
|
||||
if (Array.isArray(raw) && raw.length) return raw
|
||||
return OFFLINE_FEED
|
||||
}
|
||||
|
||||
export function getCachedMemoSettings(): MemoSettings {
|
||||
const raw = readCache<MemoSettings>(SETTINGS_CACHE)
|
||||
return raw ? { ...DEFAULT_SETTINGS, ...raw } : DEFAULT_SETTINGS
|
||||
}
|
||||
|
||||
export function getCachedMemoTags(): MemoTag[] {
|
||||
const raw = readCache<MemoTag[]>(TAGS_CACHE)
|
||||
return Array.isArray(raw) ? raw : []
|
||||
}
|
||||
|
||||
export function getCachedMemoDetail(id: string): {
|
||||
memo: MemoItem
|
||||
comments: MemoComment[]
|
||||
} | null {
|
||||
return readCache(`${DETAIL_PREFIX}${id}`)
|
||||
}
|
||||
|
||||
/** 列表页一次拉齐:settings + tags + feed 并行 */
|
||||
export async function loadMemoHome(opts?: {
|
||||
q?: string
|
||||
tag?: string
|
||||
tab?: FeedTab
|
||||
}): Promise<{
|
||||
settings: MemoSettings
|
||||
tags: MemoTag[]
|
||||
items: MemoItem[]
|
||||
offline: boolean
|
||||
}> {
|
||||
const q = opts?.q || ''
|
||||
const tag = opts?.tag || ''
|
||||
const tab = opts?.tab || 'all'
|
||||
const qs = `limit=40&q=${encodeURIComponent(q)}&tag=${encodeURIComponent(tag)}&tab=${tab}`
|
||||
|
||||
const [settingsR, tagsR, feedR] = await Promise.allSettled([
|
||||
req<MemoSettings>(`${P}/settings`),
|
||||
req<{ items: MemoTag[] }>(`${P}/tags`),
|
||||
req<{ items: MemoItem[] }>(`${P}/feed?${qs}`),
|
||||
])
|
||||
|
||||
let settings = getCachedMemoSettings()
|
||||
if (settingsR.status === 'fulfilled') {
|
||||
settings = { ...DEFAULT_SETTINGS, ...settingsR.value }
|
||||
writeCache(SETTINGS_CACHE, settings)
|
||||
}
|
||||
|
||||
let tags = getCachedMemoTags()
|
||||
if (tagsR.status === 'fulfilled') {
|
||||
tags = tagsR.value.items || []
|
||||
writeCache(TAGS_CACHE, tags)
|
||||
}
|
||||
|
||||
let items = getCachedMemoFeed()
|
||||
let offline = true
|
||||
if (feedR.status === 'fulfilled') {
|
||||
items = feedR.value.items || []
|
||||
offline = false
|
||||
if (!q && !tag && tab === 'all') writeCache(FEED_CACHE, items)
|
||||
}
|
||||
|
||||
return { settings, tags, items, offline }
|
||||
}
|
||||
|
||||
export async function loadMemoSettings(): Promise<MemoSettings> {
|
||||
try {
|
||||
const data = await req<MemoSettings>(`${P}/settings`)
|
||||
const next = { ...DEFAULT_SETTINGS, ...data }
|
||||
writeCache(SETTINGS_CACHE, next)
|
||||
return next
|
||||
} catch {
|
||||
return getCachedMemoSettings()
|
||||
}
|
||||
}
|
||||
|
||||
export async function loadMemoTags(): Promise<MemoTag[]> {
|
||||
try {
|
||||
const data = await req<{ items: MemoTag[] }>(`${P}/tags`)
|
||||
const items = data.items || []
|
||||
writeCache(TAGS_CACHE, items)
|
||||
return items
|
||||
} catch {
|
||||
return getCachedMemoTags()
|
||||
}
|
||||
}
|
||||
|
||||
export async function loadMemoFeed(opts?: {
|
||||
q?: string
|
||||
tag?: string
|
||||
tab?: FeedTab
|
||||
}): Promise<{ items: MemoItem[]; offline?: boolean }> {
|
||||
const home = await loadMemoHome(opts)
|
||||
return { items: home.items, offline: home.offline }
|
||||
}
|
||||
|
||||
export async function loadMemoDetail(id: string): Promise<{
|
||||
memo: MemoItem
|
||||
comments: MemoComment[]
|
||||
}> {
|
||||
const data = await req<{ memo: MemoItem; comments: MemoComment[] }>(`${P}/memos/${id}`)
|
||||
writeCache(`${DETAIL_PREFIX}${id}`, data)
|
||||
return data
|
||||
}
|
||||
|
||||
export async function uploadMemoImage(filePath: string): Promise<string> {
|
||||
await ensureLogin(false)
|
||||
const token = Taro.getStorageSync(STORAGE_TOKEN)
|
||||
const res = await Taro.uploadFile({
|
||||
url: `${API_BASE}${P}/upload`,
|
||||
filePath,
|
||||
name: 'file',
|
||||
timeout: 20000,
|
||||
header: token ? { Authorization: `Bearer ${token}` } : {},
|
||||
})
|
||||
if (res.statusCode < 400) {
|
||||
const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data
|
||||
const u = (data as { url?: string })?.url
|
||||
if (u) return u
|
||||
}
|
||||
let last = '上传失败'
|
||||
try {
|
||||
const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data
|
||||
if ((data as { detail?: string })?.detail) last = (data as { detail: string }).detail
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
throw new Error(last)
|
||||
}
|
||||
|
||||
export async function createMemo(
|
||||
content: string,
|
||||
resources: MemoResource[] = [],
|
||||
title = '',
|
||||
): Promise<MemoItem> {
|
||||
const data = await req<{ memo: MemoItem }>(`${P}/memos`, {
|
||||
method: 'POST',
|
||||
data: { content, resources, title },
|
||||
})
|
||||
return data.memo
|
||||
}
|
||||
|
||||
export async function deleteMemo(id: string): Promise<void> {
|
||||
await req(`${P}/memos/${id}`, { method: 'DELETE' })
|
||||
}
|
||||
|
||||
export async function likeMemo(id: string): Promise<MemoItem> {
|
||||
const data = await req<{ memo: MemoItem }>(`${P}/memos/${id}/like`, {
|
||||
method: 'POST',
|
||||
data: {},
|
||||
})
|
||||
return data.memo
|
||||
}
|
||||
|
||||
export async function favoriteMemo(id: string): Promise<MemoItem> {
|
||||
const data = await req<{ memo: MemoItem }>(`${P}/memos/${id}/favorite`, {
|
||||
method: 'POST',
|
||||
data: {},
|
||||
})
|
||||
return data.memo
|
||||
}
|
||||
|
||||
export async function commentMemo(id: string, content: string): Promise<MemoComment> {
|
||||
const data = await req<{ comment: MemoComment }>(`${P}/memos/${id}/comments`, {
|
||||
method: 'POST',
|
||||
data: { content },
|
||||
})
|
||||
return data.comment
|
||||
}
|
||||
200
apps/miniprogram/h5/src/services/shopApi.ts
Normal file
200
apps/miniprogram/h5/src/services/shopApi.ts
Normal file
@ -0,0 +1,200 @@
|
||||
import Taro from '@tarojs/taro'
|
||||
import { API_BASE, STORAGE_TOKEN } from '@/utils/config'
|
||||
import { ensureLogin } from '@/utils/request'
|
||||
import { LOCAL_SHOP_CATALOG, type ShopCatalog, type ShopProduct } from '@/data/vipStoreCatalog'
|
||||
import type { VirtualPayPayload } from '@/utils/virtualPay'
|
||||
|
||||
const CACHE_KEY = 'nomadro_shop_catalog_v2'
|
||||
|
||||
export type ShopAddress = {
|
||||
userName: string
|
||||
postalCode?: string
|
||||
provinceName: string
|
||||
cityName: string
|
||||
countyName: string
|
||||
detailInfo: string
|
||||
nationalCode?: string
|
||||
telNumber: string
|
||||
}
|
||||
|
||||
export type ShopOrder = {
|
||||
id: string
|
||||
outTradeNo: string
|
||||
productId: string
|
||||
productTitle: string
|
||||
goodsType: 'virtual' | 'physical'
|
||||
qty: number
|
||||
amountFen: number
|
||||
status: string
|
||||
email?: string
|
||||
address?: ShopAddress
|
||||
carmis?: string[]
|
||||
trackingNo?: string
|
||||
expressCompany?: string
|
||||
createdAt: number
|
||||
}
|
||||
|
||||
function authHeader(): Record<string, string> {
|
||||
const token = Taro.getStorageSync(STORAGE_TOKEN)
|
||||
return token ? { Authorization: `Bearer ${token}` } : {}
|
||||
}
|
||||
|
||||
export function getCachedShopCatalog(): ShopCatalog {
|
||||
try {
|
||||
const raw = Taro.getStorageSync(CACHE_KEY)
|
||||
if (raw && typeof raw === 'object' && Array.isArray((raw as ShopCatalog).products)) {
|
||||
return raw as ShopCatalog
|
||||
}
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
return LOCAL_SHOP_CATALOG
|
||||
}
|
||||
|
||||
export async function loadShopCatalog(): Promise<ShopCatalog> {
|
||||
const urls = [`${API_BASE}/api/ebook/shop/catalog`, `${API_BASE}/api/shop/catalog`]
|
||||
for (const url of urls) {
|
||||
try {
|
||||
const res = await Taro.request({ url, method: 'GET', timeout: 8000 })
|
||||
if (res.statusCode < 400 && res.data && (res.data as ShopCatalog).products) {
|
||||
const data = { ...(res.data as ShopCatalog), offline: false, ok: true }
|
||||
try {
|
||||
Taro.setStorageSync(CACHE_KEY, data)
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
return data
|
||||
}
|
||||
} catch {
|
||||
/* try next */
|
||||
}
|
||||
}
|
||||
return { ...getCachedShopCatalog(), offline: true }
|
||||
}
|
||||
|
||||
export function findLocalProduct(id: string): ShopProduct | undefined {
|
||||
return getCachedShopCatalog().products.find((p) => p.id === id)
|
||||
}
|
||||
|
||||
export async function loadShopProduct(id: string): Promise<ShopProduct> {
|
||||
const urls = [
|
||||
`${API_BASE}/api/ebook/shop/goods/${id}`,
|
||||
`${API_BASE}/api/shop/goods/${id}`,
|
||||
]
|
||||
for (const url of urls) {
|
||||
try {
|
||||
const res = await Taro.request({ url, method: 'GET', timeout: 8000 })
|
||||
if (res.statusCode < 400) {
|
||||
const p = (res.data as { product?: ShopProduct })?.product
|
||||
if (p) return p
|
||||
}
|
||||
} catch {
|
||||
/* next */
|
||||
}
|
||||
}
|
||||
const local = findLocalProduct(id)
|
||||
if (local) return local
|
||||
throw new Error('商品不存在')
|
||||
}
|
||||
|
||||
export async function chooseShopAddress(): Promise<ShopAddress> {
|
||||
return new Promise((resolve, reject) => {
|
||||
Taro.chooseAddress({
|
||||
success: (res) => {
|
||||
resolve({
|
||||
userName: res.userName,
|
||||
postalCode: res.postalCode,
|
||||
provinceName: res.provinceName,
|
||||
cityName: res.cityName,
|
||||
countyName: res.countyName,
|
||||
detailInfo: res.detailInfo,
|
||||
nationalCode: res.nationalCode,
|
||||
telNumber: res.telNumber,
|
||||
})
|
||||
},
|
||||
fail: (err) => {
|
||||
reject(new Error(err?.errMsg || '未能获取收货地址'))
|
||||
},
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
type ShopPayPayload = VirtualPayPayload & {
|
||||
goodsPrice?: number
|
||||
productId?: string
|
||||
kind?: string
|
||||
devPay?: boolean
|
||||
}
|
||||
|
||||
export async function createShopPayOrder(input: {
|
||||
productId: string
|
||||
qty?: number
|
||||
email?: string
|
||||
address?: ShopAddress | null
|
||||
}): Promise<ShopPayPayload> {
|
||||
await ensureLogin(true)
|
||||
const urls = [
|
||||
`${API_BASE}/api/ebook/pay/shop-order`,
|
||||
`${API_BASE}/api/pay/shop-order`,
|
||||
]
|
||||
let last = '下单失败'
|
||||
for (const url of urls) {
|
||||
const res = await Taro.request({
|
||||
url,
|
||||
method: 'POST',
|
||||
data: {
|
||||
productId: input.productId,
|
||||
qty: input.qty || 1,
|
||||
email: input.email || '',
|
||||
address: input.address || null,
|
||||
},
|
||||
header: {
|
||||
'Content-Type': 'application/json',
|
||||
...authHeader(),
|
||||
},
|
||||
})
|
||||
if (res.statusCode < 400) return res.data as ShopPayPayload
|
||||
const detail = (res.data as { detail?: string })?.detail
|
||||
if (typeof detail === 'string' && detail) last = detail
|
||||
if (res.statusCode === 401) await ensureLogin(true)
|
||||
}
|
||||
throw new Error(last)
|
||||
}
|
||||
|
||||
export async function devConfirmShopOrder(outTradeNo: string): Promise<void> {
|
||||
await ensureLogin(true)
|
||||
const urls = [
|
||||
`${API_BASE}/api/ebook/pay/dev-confirm`,
|
||||
`${API_BASE}/api/pay/dev-confirm`,
|
||||
]
|
||||
for (const url of urls) {
|
||||
const res = await Taro.request({
|
||||
url,
|
||||
method: 'POST',
|
||||
data: { out_trade_no: outTradeNo, book_id: '__shop__' },
|
||||
header: { 'Content-Type': 'application/json', ...authHeader() },
|
||||
})
|
||||
if (res.statusCode < 400) return
|
||||
}
|
||||
throw new Error('模拟支付失败')
|
||||
}
|
||||
|
||||
export async function fetchMyShopOrders(): Promise<ShopOrder[]> {
|
||||
await ensureLogin(true)
|
||||
const urls = [
|
||||
`${API_BASE}/api/ebook/shop/my-orders`,
|
||||
`${API_BASE}/api/shop/my-orders`,
|
||||
]
|
||||
for (const url of urls) {
|
||||
const res = await Taro.request({
|
||||
url,
|
||||
method: 'GET',
|
||||
header: authHeader(),
|
||||
})
|
||||
if (res.statusCode < 400) {
|
||||
return ((res.data as { items?: ShopOrder[] })?.items || []) as ShopOrder[]
|
||||
}
|
||||
if (res.statusCode === 401) await ensureLogin(true)
|
||||
}
|
||||
return []
|
||||
}
|
||||
@ -12,8 +12,13 @@ pnpm --dir apps/miniprogram/weapp build:weapp # 或根目录 pnpm build:weapp
|
||||
|
||||
## VIP(原生页,禁止 web-view)
|
||||
|
||||
对齐门户 / nomadvip:`vip` 落地 · `vip-course` 专题 · `vip-lesson` 课时 · `vip-ebook` 电子书。
|
||||
`config/index.ts` 对 VIP / 落地 scss 走 **真 px**(`pxExclude`),避免 `designWidth:750` 把字号压成一半。
|
||||
对齐门户 / nomadvip:`vip` 落地 · `vip-course` 专题 · `vip-lesson` 课时 · `vip-ebook` 电子书 · **`vip-memo` 知识社群** · **`vip-store` 设备商城**。
|
||||
`config/index.ts` 对 VIP / 商城 / 社群 scss 走 **真 px**(`pxExclude`),避免 `designWidth:750` 把字号压成一半。
|
||||
|
||||
| 页 | 说明 |
|
||||
|----|------|
|
||||
| `vip-memo` / `vip-memo-detail` | 知识星球风格:精华/收藏/Markdown;本地缓存秒开 + 静默刷新 |
|
||||
| `vip-store` / `vip-store-detail` / `vip-store-orders` | 虚拟卡 + 实物;微信收货地址 |
|
||||
|
||||
电子书 / 课时内容从 `src/modules/vip/app/data` 抽取:
|
||||
|
||||
|
||||
@ -31,7 +31,12 @@ const pxExclude = (file: string) =>
|
||||
/[\\/]pages[\\/]vip[\\/]index\.scss/.test(file) ||
|
||||
/[\\/]pages[\\/]vip-course[\\/]index\.scss/.test(file) ||
|
||||
/[\\/]pages[\\/]vip-lesson[\\/]index\.scss/.test(file) ||
|
||||
/[\\/]pages[\\/]vip-ebook[\\/]index\.scss/.test(file)
|
||||
/[\\/]pages[\\/]vip-ebook[\\/]index\.scss/.test(file) ||
|
||||
/[\\/]pages[\\/]vip-store[\\/]index\.scss/.test(file) ||
|
||||
/[\\/]pages[\\/]vip-store-detail[\\/]index\.scss/.test(file) ||
|
||||
/[\\/]pages[\\/]vip-store-orders[\\/]index\.scss/.test(file) ||
|
||||
/[\\/]pages[\\/]vip-memo[\\/]index\.scss/.test(file) ||
|
||||
/[\\/]pages[\\/]vip-memo-detail[\\/]index\.scss/.test(file)
|
||||
|
||||
export default defineConfig(async (merge) => {
|
||||
const baseConfig: UserConfigExport = {
|
||||
|
||||
Loading…
Reference in New Issue
Block a user