Ship WeChat audit mode, package-size fixes, and live VIP switches.
Harden weapp for review: silent audit book, no flashy module defaults, safe-area PX, subpackages/lazyCodeLoading, and CDN nav icons. Document pre3 and move next work to pre4. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
9779b80d25
commit
2366cff896
20
README.md
20
README.md
@ -35,11 +35,12 @@ scripts/ 本地开发 / 清理(dev-api · clean-artifacts)
|
||||
| 内容 | 导航(组内第一) | `/wechat/nav` |
|
||||
| 内容 | 小册与试读% | `/wechat/books/default` |
|
||||
| 内容 | **VIP**(二级)→ 运营配置 | `/wechat/vip` |
|
||||
| | → 电子书 | `/wechat/vip/ebooks` |
|
||||
| | → 电子书(含数字游民提审开关) | `/wechat/vip/ebooks` |
|
||||
| | → 视频课程 | `/wechat/vip/course` |
|
||||
| | → 电商 | `/wechat/shop` |
|
||||
| | → 知识社群 | `/wechat/memo` |
|
||||
| 运营 | 读者 · 订单 | `/wechat/users` · `/wechat/orders` |
|
||||
| 总览 | **开关**(模块/入口远程配置) | `/wechat/switches` |
|
||||
| 运营 | 读者 · VIP 用户 · 订单 | `/wechat/users` · `/wechat/vip-users` · `/wechat/orders` |
|
||||
| 数据 | 埋点 · 部署检查清单 | `/wechat/events` · `/wechat/checklist` |
|
||||
|
||||
兼容:`/wechat/vip/library` → 重定向到 `/wechat/vip/ebooks`。
|
||||
@ -113,5 +114,16 @@ pnpm dev:api
|
||||
- **业务在 `src/modules/`**,`src/app/` 只挂路由与薄 re-export
|
||||
- **远程配置 + 离线兜底**:`/api/config` · `data/remote-config.json` · `/admin/config`
|
||||
- **禁止**再引入已删垂直树(见 `AGENTS.md`)
|
||||
- **发布流**:本地调试 → `pre3` commit/push → 部署脚本上线 → 冒烟;配置与发版均以 git 为准
|
||||
- 主开发分支常见 `pre3`;发版前与 README / 远程对齐
|
||||
- **发布流**:本地调试 → 当前开发分支 commit/push → 部署脚本上线 → 冒烟;配置与发版均以 git 为准
|
||||
- 主开发分支:`pre4`(`pre3` 已封存本轮);发版前与 README / 远程对齐
|
||||
|
||||
## pre3 摘要(已合入)
|
||||
|
||||
微信提审与包体:
|
||||
|
||||
- **数字游民小册提审**:后台 VIP→电子书→数字游民开关;开则读合规备用书,关则回正式 VIP 书;前端不展示「提审」文案
|
||||
- **入口默认隐藏**:远程配置未就绪不渲染门户卡片 / 模块闸门,避免先闪后藏
|
||||
- **安全区**:自定义顶栏内联尺寸用大写 `PX` 跳过 Taro rpx;阅读页顶栏不再叠状态栏 padding
|
||||
- **代码质量**:`lazyCodeLoading` · 分包 + `optimizeMainPackage`(主包 ≪1.5MB)· 导航图标走 `https://nomadro.cn/icons`(包内图片合计 ≤200K)
|
||||
|
||||
构建微信包:`pnpm build:weapp` → 开发者工具打开 `apps/miniprogram/weapp`(读 `dist/`)。图片域名需放行 `nomadro.cn`。
|
||||
|
||||
@ -60,7 +60,7 @@ API:`GET/PUT /api/admin/join-group`
|
||||
|
||||
## 部署(git 管理)
|
||||
|
||||
本地改 → `pre3` commit/push → 构建 dist → 部署脚本同步线上:
|
||||
本地改 → `pre4`(或当前开发分支)commit/push → 构建 dist → 部署脚本同步线上:
|
||||
|
||||
```bash
|
||||
pnpm build:admin
|
||||
|
||||
241
apps/admin/deploy/audit_book_seed.md
Normal file
241
apps/admin/deploy/audit_book_seed.md
Normal file
@ -0,0 +1,241 @@
|
||||
# 写在前面
|
||||
|
||||
欢迎阅读《数字游民入门指南》。
|
||||
|
||||
这是一本面向普通人的生活方式小册:讲如何在合法合规的前提下,把工作做得更灵活,把生活安排得更从容。内容偏实用、偏日常,不涉及灰色产业,也不讨论敏感话题。
|
||||
|
||||
你可以把本书当作「远程办公入门笔记」:哪怕暂时还不能频繁出差,里面的时间管理、沟通方法和健康习惯,同样适用于居家办公与混合办公。
|
||||
|
||||
建议按顺序阅读。每章不长,方便通勤或午休时翻完。
|
||||
|
||||
# 什么是数字游民
|
||||
|
||||
「数字游民」通常指:工作主要依赖电脑与网络完成,地点不必固定在同一间办公室。
|
||||
|
||||
它不是逃避现实,也不是只顾旅行不顾责任。更常见的状态是:
|
||||
|
||||
- 工作目标清晰,交付结果可衡量
|
||||
- 沟通及时,团队协作顺畅
|
||||
- 作息稳定,身心健康有保障
|
||||
- 遵守公司制度与当地法律法规
|
||||
|
||||
对很多职场人来说,第一步并不是「周游世界」,而是先学会高质量远程协作:按时开会、按时交付、把协作工具用熟。
|
||||
|
||||
## 它适合谁
|
||||
|
||||
更适合这些情况:
|
||||
|
||||
- 内容创作、设计、开发、运营、客服、翻译、数据分析等可线上完成的工作
|
||||
- 公司已支持居家办公或混合办公
|
||||
- 个人执行力较强,能自我管理进度
|
||||
|
||||
不太适合:强依赖现场设备、面对面服务、或必须到岗的岗位——除非岗位本身已经改为线上流程。
|
||||
|
||||
## 先建立正确预期
|
||||
|
||||
灵活不等于松散。远程工作往往更考验:
|
||||
|
||||
1. **结果导向**:用可验收的成果说话
|
||||
2. **可见度**:主动同步进度,减少信息不对称
|
||||
3. **边界感**:工作与生活有节奏,避免「一直在线却效率很低」
|
||||
|
||||
# 远程办公的基本功
|
||||
|
||||
远程办公的核心不是「换一个风景」,而是「换一种可协作的工作方式」。
|
||||
|
||||
## 1. 固定工作时段
|
||||
|
||||
建议每天有固定的核心工作时间(例如 9:30–12:00、14:00–18:00),并告诉同事:
|
||||
|
||||
- 哪些时段适合会议
|
||||
- 哪些时段专注深度工作
|
||||
- 紧急事项如何联系
|
||||
|
||||
时间透明,协作成本会明显下降。
|
||||
|
||||
## 2. 日计划与周复盘
|
||||
|
||||
每天开工前列三件「今天必须完成」的事;每周五花十五分钟复盘:
|
||||
|
||||
- 本周完成了什么
|
||||
- 卡在哪里
|
||||
- 下周优先做什么
|
||||
|
||||
简单记录即可,不必写成复杂文档。
|
||||
|
||||
## 3. 工具只保留必要的
|
||||
|
||||
常见组合已经足够:
|
||||
|
||||
- 文档协作:在线文档 / 表格
|
||||
- 沟通:即时消息 + 邮件
|
||||
- 会议:视频会议软件
|
||||
- 任务:看板或待办清单
|
||||
|
||||
工具越多越容易分心。优先把「任务状态」和「最终交付物」放在团队约定的地方。
|
||||
|
||||
## 4. 会议要短、要有结论
|
||||
|
||||
开会前写清楚目的;开会后写三条结论:谁负责、做什么、何时完成。没有结论的会,尽量少开。
|
||||
|
||||
# 居家与旅居的工作环境
|
||||
|
||||
环境会直接影响专注力。不必追求豪华,但要「够用、安静、可持续」。
|
||||
|
||||
## 居家办公清单
|
||||
|
||||
- 稳定的桌椅与屏幕高度,减少颈椎负担
|
||||
- 光线充足,白天尽量靠近自然光
|
||||
- 耳机(隔音或降噪均可)
|
||||
- 备用充电器与移动电源
|
||||
- 水杯与简单加餐,减少频繁打断
|
||||
|
||||
如果家里容易被打扰,可以约定「工作时关门」或使用图书馆、咖啡馆的安静时段。
|
||||
|
||||
## 短途旅居怎么选地方
|
||||
|
||||
如果公司允许短期异地办公,优先考虑:
|
||||
|
||||
1. 网络稳定、电源方便
|
||||
2. 住宿安静,适合睡眠
|
||||
3. 周边有餐饮与运动条件
|
||||
4. 往返交通可预期,不耽误会议
|
||||
|
||||
先从周末附近城市试住一两晚,再考虑更长的停留。陌生城市的第一周,把作息跑稳比「打卡景点」更重要。
|
||||
|
||||
# 时间管理:让灵活真正有效
|
||||
|
||||
灵活工作最大的风险是:时间碎、注意力散、任务拖。
|
||||
|
||||
## 番茄工作法(简化版)
|
||||
|
||||
- 25 分钟专注做一件事
|
||||
- 休息 5 分钟
|
||||
- 四个循环后休息 15–20 分钟
|
||||
|
||||
深度工作时关闭无关通知。回复消息可以集中到固定时段处理。
|
||||
|
||||
## 分清「紧急」和「重要」
|
||||
|
||||
每天真正重要的通常只有少数几项。把「看起来很忙」和「真正推进目标」分开:
|
||||
|
||||
| 类型 | 例子 | 建议 |
|
||||
| --- | --- | --- |
|
||||
| 重要且紧急 | 当天截止的交付 | 立刻做 |
|
||||
| 重要不紧急 | 学习新技能、健康锻炼 | 排进日程 |
|
||||
| 紧急不重要 | 部分临时打扰 | 能委托就委托 |
|
||||
| 都不紧急 | 无目的刷信息 | 自觉限制 |
|
||||
|
||||
## 保护深度工作时段
|
||||
|
||||
建议每天至少留 90 分钟不被会议打断的时间,用来写方案、写代码、做设计或复盘数据。这段时间尽量提前在日历里标出来。
|
||||
|
||||
# 沟通与团队协作
|
||||
|
||||
远程场景里,沟通质量几乎等于工作质量。
|
||||
|
||||
## 同步信息的三个原则
|
||||
|
||||
1. **默认公开**:进度写在团队可见的地方,少用只有你知道的私聊结论
|
||||
2. **结论先行**:先说结果,再补背景
|
||||
3. **可执行**:说清楚下一步、负责人和时间
|
||||
|
||||
## 异步沟通模板
|
||||
|
||||
需要同事处理时,可以这样写:
|
||||
|
||||
> 背景:……
|
||||
> 需要你:……
|
||||
> 截止:……
|
||||
> 参考资料:……
|
||||
|
||||
对方不用来回追问,效率会高很多。
|
||||
|
||||
## 信任来自稳定交付
|
||||
|
||||
远程信任不是靠「一直在线」,而是靠:
|
||||
|
||||
- 承诺的事按时完成
|
||||
- 延期提前说明原因与新时间
|
||||
- 问题主动暴露,而不是临近截止才说
|
||||
|
||||
把「靠谱」做成习惯,比任何管理鸡汤都管用。
|
||||
|
||||
# 健康、作息与心态
|
||||
|
||||
身体垮了,任何生活方式都不可持续。
|
||||
|
||||
## 作息建议
|
||||
|
||||
- 尽量固定睡眠与起床时间
|
||||
- 每工作一小时起身活动两分钟
|
||||
- 中午留一段真正休息,而不是边吃边回消息
|
||||
- 晚上给眼睛和大脑降温,少熬夜赶工
|
||||
|
||||
## 运动不必复杂
|
||||
|
||||
散步、拉伸、居家力量训练都可以。关键是「每周能坚持」,而不是一次练到力竭。
|
||||
|
||||
## 孤独感怎么处理
|
||||
|
||||
长期独处容易闷。可以:
|
||||
|
||||
- 定期与同事语音同步
|
||||
- 参加健康正向的兴趣社群或线下读书会
|
||||
- 与家人朋友保持固定联系时间
|
||||
|
||||
把社交安排进日历,和安排会议一样认真。
|
||||
|
||||
# 学习成长与职业规划
|
||||
|
||||
数字游民不是终点,而是一种工作形态。真正护城河仍是能力与口碑。
|
||||
|
||||
## 持续提升三件事
|
||||
|
||||
1. **专业技能**:让你的交付更稳、更快、质量更高
|
||||
2. **表达能力**:把复杂问题讲清楚
|
||||
3. **项目管理**:把事情拆小、排期、闭环
|
||||
|
||||
每周抽出固定学习时间,哪怕只有三十分钟,也比「有空再说」强。
|
||||
|
||||
## 作品集思维
|
||||
|
||||
把完成的项目整理成可展示的说明:
|
||||
|
||||
- 解决了什么问题
|
||||
- 你做了哪些关键决策
|
||||
- 结果如何衡量
|
||||
|
||||
这对转岗、晋升或接更匹配的远程岗位都很有帮助。
|
||||
|
||||
## 合规与边界
|
||||
|
||||
请始终遵守:
|
||||
|
||||
- 劳动合同与公司远程办公制度
|
||||
- 信息安全与保密要求
|
||||
- 所在地法律法规与税务规定
|
||||
|
||||
不传播不当内容,不从事违法违规业务。稳健发展,才能走得长远。
|
||||
|
||||
# 七天起步计划
|
||||
|
||||
如果你想从零开始尝试更灵活的工作节奏,可以用这一周做轻量实验(在公司制度允许的前提下):
|
||||
|
||||
**第 1 天**:整理工位,列出核心工作时段
|
||||
**第 2 天**:建立待办清单,只保留三个每日目标
|
||||
**第 3 天**:把常用文档放到团队约定位置
|
||||
**第 4 天**:练习「结论先行」的消息写法
|
||||
**第 5 天**:完成一次短复盘,记下卡点
|
||||
**第 6 天**:安排一次户外散步或轻度运动
|
||||
**第 7 天**:回顾本周,写下下周只改一件事
|
||||
|
||||
目标不是完美,而是建立可重复的节奏。
|
||||
|
||||
# 结语
|
||||
|
||||
数字游民生活方式的本质,是用更好的方式完成工作、照顾生活,而不是追逐表象上的「自由」。
|
||||
|
||||
先把远程协作做好,把身体照顾好,把专业能力垒扎实。地点可以慢慢变化,但秩序、责任与成长不能丢。
|
||||
|
||||
祝你工作顺利,生活安定,步履从容。
|
||||
@ -3,10 +3,12 @@ import { getToken } from './api'
|
||||
import Login from './pages/Login'
|
||||
import PlatformSelect from './pages/PlatformSelect'
|
||||
import Dashboard from './pages/Dashboard'
|
||||
import Switches from './pages/Switches'
|
||||
import BookEdit from './pages/BookEdit'
|
||||
import './pages/BookEdit.css'
|
||||
import Orders from './pages/Orders'
|
||||
import Users from './pages/Users'
|
||||
import VipUsers from './pages/VipUsers'
|
||||
import Events from './pages/Events'
|
||||
import Checklist from './pages/Checklist'
|
||||
import Vip from './pages/Vip'
|
||||
@ -66,11 +68,14 @@ export default function App() {
|
||||
}
|
||||
>
|
||||
<Route index element={<Dashboard />} />
|
||||
<Route path="switches" element={<Switches />} />
|
||||
<Route path="books/:id" element={<BookEdit />} />
|
||||
<Route path="vip" element={<Vip />} />
|
||||
<Route path="vip/ebooks" element={<VipLibrary />} />
|
||||
<Route path="vip/users" element={<VipUsers />} />
|
||||
<Route path="vip/ebooks" element={<Navigate to="/wechat/vip/ebooks/nomad" replace />} />
|
||||
<Route path="vip/ebooks/:bookId" element={<VipLibrary />} />
|
||||
<Route path="vip/course" element={<VipLibrary />} />
|
||||
<Route path="vip/library" element={<Navigate to="/wechat/vip/ebooks" replace />} />
|
||||
<Route path="vip/library" element={<Navigate to="/wechat/vip/ebooks/nomad" replace />} />
|
||||
<Route path="nav" element={<Nav />} />
|
||||
<Route path="shop" element={<Shop />} />
|
||||
<Route path="memo" element={<Memo />} />
|
||||
@ -102,6 +107,7 @@ 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="/vip/users" element={<WechatRedirect to="/wechat/vip/users" />} />
|
||||
<Route path="/nav" element={<WechatRedirect to="/wechat/nav" />} />
|
||||
<Route path="/shop" element={<WechatRedirect to="/wechat/shop" />} />
|
||||
<Route path="/memo" element={<WechatRedirect to="/wechat/memo" />} />
|
||||
|
||||
@ -11,30 +11,48 @@ type NavBranch = {
|
||||
label: string
|
||||
/** 任一前缀命中则父级高亮并保持展开 */
|
||||
match: string[]
|
||||
children: NavLeaf[]
|
||||
children: NavItem[]
|
||||
/** 展开时默认跳转 */
|
||||
defaultTo?: string
|
||||
}
|
||||
type NavEntry = NavLeaf | NavBranch
|
||||
type NavGroup = { label: string; items: NavEntry[] }
|
||||
type NavItem = NavLeaf | NavBranch
|
||||
type NavGroup = { label: string; items: NavItem[] }
|
||||
|
||||
const NAV_GROUPS: NavGroup[] = [
|
||||
{
|
||||
label: '总览',
|
||||
items: [{ to: '/wechat', end: true, ico: '◈', label: '运营概览' }],
|
||||
items: [
|
||||
{ to: '/wechat', end: true, ico: '◈', label: '运营概览' },
|
||||
{ to: '/wechat/switches', ico: '⏻', label: '开关' },
|
||||
],
|
||||
},
|
||||
{
|
||||
label: '内容',
|
||||
items: [
|
||||
{ to: '/wechat/nav', ico: '🧭', label: '导航' },
|
||||
{ to: '/wechat/books/default', ico: '📕', label: '小册与试读%' },
|
||||
{
|
||||
kind: 'branch',
|
||||
id: 'vip',
|
||||
ico: '👑',
|
||||
label: 'VIP',
|
||||
match: ['/wechat/vip', '/wechat/shop', '/wechat/memo'],
|
||||
match: ['/wechat/vip', '/wechat/shop', '/wechat/memo', '/wechat/books'],
|
||||
defaultTo: '/wechat/vip',
|
||||
children: [
|
||||
{ to: '/wechat/vip', end: true, ico: '⚙', label: '运营配置' },
|
||||
{ to: '/wechat/vip/ebooks', ico: '📖', label: '电子书' },
|
||||
{ to: '/wechat/vip/users', ico: '👑', label: 'VIP用户' },
|
||||
{
|
||||
kind: 'branch',
|
||||
id: 'ebooks',
|
||||
ico: '📖',
|
||||
label: '电子书',
|
||||
match: ['/wechat/vip/ebooks', '/wechat/books'],
|
||||
defaultTo: '/wechat/vip/ebooks/nomad',
|
||||
children: [
|
||||
{ to: '/wechat/vip/ebooks/nomad', ico: '🌍', label: '数字游民' },
|
||||
{ to: '/wechat/vip/ebooks/cloudphone', ico: '📱', label: '云手机' },
|
||||
{ to: '/wechat/books/default', ico: '▶️', label: 'youtube运营笔记' },
|
||||
],
|
||||
},
|
||||
{ to: '/wechat/vip/course', ico: '🎬', label: '视频课程' },
|
||||
{ to: '/wechat/shop', ico: '🛒', label: '电商' },
|
||||
{ to: '/wechat/memo', ico: '🏕️', label: '知识社群' },
|
||||
@ -46,6 +64,7 @@ const NAV_GROUPS: NavGroup[] = [
|
||||
label: '运营',
|
||||
items: [
|
||||
{ to: '/wechat/users', ico: '👥', label: '读者' },
|
||||
{ to: '/wechat/vip/users', ico: '👑', label: 'VIP用户' },
|
||||
{ to: '/wechat/orders', ico: '🧾', label: '订单' },
|
||||
],
|
||||
},
|
||||
@ -58,18 +77,16 @@ const NAV_GROUPS: NavGroup[] = [
|
||||
},
|
||||
]
|
||||
|
||||
function flattenLeaves(groups: NavGroup[]): NavLeaf[] {
|
||||
function flattenLeaves(items: NavItem[]): NavLeaf[] {
|
||||
const out: NavLeaf[] = []
|
||||
for (const g of groups) {
|
||||
for (const item of g.items) {
|
||||
if (item.kind === 'branch') out.push(...item.children)
|
||||
else out.push(item)
|
||||
}
|
||||
for (const item of items) {
|
||||
if (item.kind === 'branch') out.push(...flattenLeaves(item.children))
|
||||
else out.push(item)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
const FLAT_NAV = flattenLeaves(NAV_GROUPS)
|
||||
const FLAT_NAV = NAV_GROUPS.flatMap((g) => flattenLeaves(g.items))
|
||||
|
||||
function titleFromPath(pathname: string) {
|
||||
const sorted = [...FLAT_NAV].sort((a, b) => b.to.length - a.to.length)
|
||||
@ -78,25 +95,31 @@ function titleFromPath(pathname: string) {
|
||||
}
|
||||
|
||||
function isBranchActive(branch: NavBranch, pathname: string) {
|
||||
return branch.match.some(
|
||||
(m) => pathname === m || pathname.startsWith(`${m}/`),
|
||||
)
|
||||
return branch.match.some((m) => pathname === m || pathname.startsWith(`${m}/`))
|
||||
}
|
||||
|
||||
/** 微信小程序后台壳层 — 仅 /wechat/*;VIP 二级菜单;移动端抽屉 */
|
||||
/** 微信小程序后台壳层 — 仅 /wechat/*;VIP / 电子书二级菜单;移动端抽屉 */
|
||||
export default function Layout() {
|
||||
const nav = useNavigate()
|
||||
const { pathname } = useLocation()
|
||||
const [drawerOpen, setDrawerOpen] = useState(false)
|
||||
|
||||
const vipActive = useMemo(
|
||||
() =>
|
||||
pathname === '/wechat/vip' ||
|
||||
pathname.startsWith('/wechat/vip/') ||
|
||||
pathname.startsWith('/wechat/shop') ||
|
||||
pathname.startsWith('/wechat/memo'),
|
||||
pathname.startsWith('/wechat/memo') ||
|
||||
pathname.startsWith('/wechat/books'),
|
||||
[pathname],
|
||||
)
|
||||
const ebooksActive = useMemo(
|
||||
() => pathname.startsWith('/wechat/vip/ebooks') || pathname.startsWith('/wechat/books'),
|
||||
[pathname],
|
||||
)
|
||||
|
||||
const [vipOpen, setVipOpen] = useState(() => vipActive)
|
||||
const [ebooksOpen, setEbooksOpen] = useState(() => ebooksActive)
|
||||
|
||||
useEffect(() => {
|
||||
setDrawerOpen(false)
|
||||
@ -106,6 +129,13 @@ export default function Layout() {
|
||||
if (vipActive) setVipOpen(true)
|
||||
}, [vipActive])
|
||||
|
||||
useEffect(() => {
|
||||
if (ebooksActive) {
|
||||
setVipOpen(true)
|
||||
setEbooksOpen(true)
|
||||
}
|
||||
}, [ebooksActive])
|
||||
|
||||
useEffect(() => {
|
||||
document.body.style.overflow = drawerOpen ? 'hidden' : ''
|
||||
return () => {
|
||||
@ -118,28 +148,45 @@ export default function Layout() {
|
||||
nav('/login')
|
||||
}
|
||||
|
||||
function renderEntry(item: NavEntry) {
|
||||
function toggleBranch(branch: NavBranch) {
|
||||
if (branch.id === 'vip') {
|
||||
setVipOpen((v) => {
|
||||
const next = !v
|
||||
if (next && !vipActive) nav(branch.defaultTo || '/wechat/vip')
|
||||
return next
|
||||
})
|
||||
return
|
||||
}
|
||||
if (branch.id === 'ebooks') {
|
||||
setEbooksOpen((v) => {
|
||||
const next = !v
|
||||
if (next && !ebooksActive) nav(branch.defaultTo || '/wechat/vip/ebooks/nomad')
|
||||
return next
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function isOpen(branch: NavBranch) {
|
||||
if (branch.id === 'vip') return vipOpen
|
||||
if (branch.id === 'ebooks') return ebooksOpen
|
||||
return false
|
||||
}
|
||||
|
||||
function renderEntry(item: NavItem, depth = 0) {
|
||||
if (item.kind === 'branch') {
|
||||
const open = item.id === 'vip' ? vipOpen : false
|
||||
const open = isOpen(item)
|
||||
const active = isBranchActive(item, pathname)
|
||||
const nestClass = depth > 0 ? ' wx-nav-branch--nested' : ''
|
||||
return (
|
||||
<div
|
||||
key={item.id}
|
||||
className={`wx-nav-branch${open ? ' is-open' : ''}${active ? ' is-active' : ''}`}
|
||||
className={`wx-nav-branch${nestClass}${open ? ' is-open' : ''}${active ? ' is-active' : ''}`}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className="wx-nav-parent"
|
||||
className={`wx-nav-parent${depth > 0 ? ' wx-nav-parent--nested' : ''}`}
|
||||
aria-expanded={open}
|
||||
onClick={() => {
|
||||
if (item.id === 'vip') {
|
||||
setVipOpen((v) => {
|
||||
const next = !v
|
||||
if (next && !vipActive) nav('/wechat/vip')
|
||||
return next
|
||||
})
|
||||
}
|
||||
}}
|
||||
onClick={() => toggleBranch(item)}
|
||||
>
|
||||
<span className="wx-nav-ico" aria-hidden>
|
||||
{item.ico}
|
||||
@ -151,20 +198,24 @@ export default function Layout() {
|
||||
</button>
|
||||
{open ? (
|
||||
<div className="wx-nav-sub" role="group" aria-label={`${item.label}子菜单`}>
|
||||
{item.children.map((child) => (
|
||||
<NavLink
|
||||
key={child.to}
|
||||
to={child.to}
|
||||
end={!!child.end}
|
||||
className="wx-nav-sublink"
|
||||
onClick={() => setDrawerOpen(false)}
|
||||
>
|
||||
<span className="wx-nav-ico" aria-hidden>
|
||||
{child.ico}
|
||||
</span>
|
||||
{child.label}
|
||||
</NavLink>
|
||||
))}
|
||||
{item.children.map((child) =>
|
||||
child.kind === 'branch' ? (
|
||||
renderEntry(child, depth + 1)
|
||||
) : (
|
||||
<NavLink
|
||||
key={child.to}
|
||||
to={child.to}
|
||||
end={!!child.end}
|
||||
className={depth > 0 ? 'wx-nav-sublink wx-nav-sublink--deep' : 'wx-nav-sublink'}
|
||||
onClick={() => setDrawerOpen(false)}
|
||||
>
|
||||
<span className="wx-nav-ico" aria-hidden>
|
||||
{child.ico}
|
||||
</span>
|
||||
{child.label}
|
||||
</NavLink>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
@ -54,6 +54,12 @@ function simplePreviewHtml(md: string): string {
|
||||
.replace(/\n/g, '<br/>')
|
||||
}
|
||||
|
||||
function bookPageTitle(id: string, bookTitle?: string) {
|
||||
if (id === 'default') return 'youtube运营笔记'
|
||||
if (id === 'audit') return bookTitle || '数字游民 · 审核版'
|
||||
return bookTitle || id
|
||||
}
|
||||
|
||||
export default function BookEdit() {
|
||||
const { id = 'default' } = useParams()
|
||||
const [book, setBook] = useState<Book | null>(null)
|
||||
@ -212,10 +218,16 @@ export default function BookEdit() {
|
||||
await importMarkdown(fullMd, false)
|
||||
}
|
||||
|
||||
const isAuditBook = id === 'audit'
|
||||
|
||||
if (!book) {
|
||||
return (
|
||||
<div className="wx-page">
|
||||
<WxHead eyebrow="微信小册" title="小册与试读 %" desc="加载中…" />
|
||||
<WxHead
|
||||
eyebrow={isAuditBook ? '数字游民 · 提审' : '会员电子书'}
|
||||
title={bookPageTitle(id)}
|
||||
desc="加载中…"
|
||||
/>
|
||||
{msg ? <WxToast kind="err">{msg}</WxToast> : null}
|
||||
</div>
|
||||
)
|
||||
@ -224,14 +236,21 @@ export default function BookEdit() {
|
||||
return (
|
||||
<div className="wx-page book-edit-page">
|
||||
<WxHead
|
||||
eyebrow="微信小册"
|
||||
title="小册与试读 %"
|
||||
desc={`数据库实时读写 · ${book.chapter_count || book.chapters.length} 章 · ${
|
||||
book.word_count || 0
|
||||
} 字 · 保存后小程序下次打开即更新`}
|
||||
eyebrow={isAuditBook ? '数字游民 · 提审' : '会员电子书'}
|
||||
title={bookPageTitle(id, book.title)}
|
||||
desc={
|
||||
isAuditBook
|
||||
? `给微信审核员看的独立正文 · ${book.chapter_count || book.chapters.length} 章 · 与正式会员书无关`
|
||||
: `${book.chapter_count || book.chapters.length} 章 · 约 ${book.word_count || 0} 字 · 保存后小程序下次打开即更新`
|
||||
}
|
||||
>
|
||||
{isAuditBook ? (
|
||||
<Link className="wx-btn wx-btn-ghost" to="/wechat/vip/ebooks/nomad">
|
||||
← 返回数字游民
|
||||
</Link>
|
||||
) : null}
|
||||
<label className="file-btn wx-btn wx-btn-ghost" style={{ cursor: 'pointer' }}>
|
||||
导入 ebook.md
|
||||
导入文稿
|
||||
<input
|
||||
type="file"
|
||||
accept=".md,text/markdown,text/plain"
|
||||
@ -244,14 +263,14 @@ export default function BookEdit() {
|
||||
className={`wx-btn${mode === 'full' ? '' : ' wx-btn-ghost'}`}
|
||||
onClick={() => loadFullMarkdown()}
|
||||
>
|
||||
全文模式
|
||||
全文编辑
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`wx-btn${mode === 'chapter' ? '' : ' wx-btn-ghost'}`}
|
||||
onClick={() => setMode('chapter')}
|
||||
>
|
||||
分章模式
|
||||
分章编辑
|
||||
</button>
|
||||
</WxHead>
|
||||
|
||||
@ -262,12 +281,25 @@ export default function BookEdit() {
|
||||
) : null}
|
||||
|
||||
<form className="panel form meta-form" onSubmit={onSave}>
|
||||
{isAuditBook ? (
|
||||
<section className="monetize-panel" style={{ marginBottom: 16 }}>
|
||||
<div className="monetize-head">
|
||||
<div>
|
||||
<h2 className="monetize-title">这是审核版,不是正式会员书</h2>
|
||||
<p className="hint">
|
||||
内容单独存放,不会自动抄正式版。在「数字游民」页打开「微信提审」后,小程序小册才会读到这里。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
{!isAuditBook ? (
|
||||
<section className="monetize-panel">
|
||||
<div className="monetize-head">
|
||||
<div>
|
||||
<h2 className="monetize-title">阅读与付费控制</h2>
|
||||
<h2 className="monetize-title">阅读与付费</h2>
|
||||
<p className="hint">
|
||||
一键切换免费 / 已发布道具。切换后小程序「解锁全文」按钮文案与价格立即跟随(需重新打开阅读页)。
|
||||
切换免费或付费方案后,小程序「解锁全文」按钮会跟着变(需重新打开阅读页)。
|
||||
</p>
|
||||
</div>
|
||||
<div className="live-preview">
|
||||
@ -349,6 +381,7 @@ export default function BookEdit() {
|
||||
<div className="free-banner">当前为免费全书:读者无支付墙,目录全部可读。</div>
|
||||
)}
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
<div className="grid-2">
|
||||
<label>
|
||||
@ -404,7 +437,7 @@ export default function BookEdit() {
|
||||
<div className="pane-head">
|
||||
<strong>编辑 · {chapter?.title || ''}</strong>
|
||||
<button type="button" onClick={saveMetaAndChapters} disabled={saving}>
|
||||
{saving ? '保存中…' : '保存到数据库'}
|
||||
{saving ? '保存中…' : '保存本章'}
|
||||
</button>
|
||||
</div>
|
||||
<textarea
|
||||
@ -426,9 +459,9 @@ export default function BookEdit() {
|
||||
<div className="editor-grid full panel">
|
||||
<section className="editor-pane">
|
||||
<div className="pane-head">
|
||||
<strong>全文 Markdown</strong>
|
||||
<strong>全文编辑</strong>
|
||||
<button type="button" onClick={saveFullMarkdown} disabled={importing}>
|
||||
{importing ? '写入中…' : '拆章并写入数据库'}
|
||||
{importing ? '保存中…' : '按标题拆章并保存'}
|
||||
</button>
|
||||
</div>
|
||||
<textarea
|
||||
@ -449,13 +482,22 @@ export default function BookEdit() {
|
||||
|
||||
<div className="wx-sticky-bar">
|
||||
<span className="wx-muted">
|
||||
模式 {mode === 'chapter' ? '分章' : '全文'} · 试读 {book.unlock_percent}% ·{' '}
|
||||
{isFree ? '免费全书' : `道具 ${book.product_id || '—'}`}
|
||||
{isAuditBook
|
||||
? `审核版 · ${mode === 'chapter' ? '分章' : '全文'} · ${book.chapters.length} 章`
|
||||
: `${mode === 'chapter' ? '分章' : '全文'} · ${
|
||||
isFree ? '免费全书' : `试读 ${book.unlock_percent}%`
|
||||
}`}
|
||||
</span>
|
||||
<div className="wx-row-actions">
|
||||
<Link className="wx-btn-sm" to="/wechat/users">
|
||||
读者运营 →
|
||||
</Link>
|
||||
{isAuditBook ? (
|
||||
<Link className="wx-btn-sm" to="/wechat/vip/ebooks/nomad">
|
||||
← 数字游民
|
||||
</Link>
|
||||
) : (
|
||||
<Link className="wx-btn-sm" to="/wechat/users">
|
||||
读者运营 →
|
||||
</Link>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="wx-btn"
|
||||
|
||||
@ -19,12 +19,18 @@ const HUBS: Array<{
|
||||
primary?: boolean
|
||||
}> = [
|
||||
{
|
||||
to: '/wechat/books/default',
|
||||
ico: '📕',
|
||||
title: '小册与试读 %',
|
||||
desc: '章节、解锁阈值与虚拟支付道具',
|
||||
to: '/wechat/switches',
|
||||
ico: '⏻',
|
||||
title: '开关',
|
||||
desc: '页面 / 入口 / 文案',
|
||||
primary: true,
|
||||
},
|
||||
{
|
||||
to: '/wechat/books/default',
|
||||
ico: '▶️',
|
||||
title: 'youtube运营笔记',
|
||||
desc: '专属小册 · 试读% 与虚拟支付道具',
|
||||
},
|
||||
{
|
||||
to: '/wechat/vip',
|
||||
ico: '👑',
|
||||
@ -32,10 +38,10 @@ const HUBS: Array<{
|
||||
desc: '价格、入口开关、加群行为与落地页',
|
||||
},
|
||||
{
|
||||
to: '/wechat/vip/ebooks',
|
||||
to: '/wechat/vip/ebooks/nomad',
|
||||
ico: '📖',
|
||||
title: 'VIP 电子书',
|
||||
desc: '章节 Markdown,远程正文',
|
||||
title: '电子书 · 数字游民',
|
||||
desc: '正式正文 · 微信提审内容',
|
||||
},
|
||||
{
|
||||
to: '/wechat/vip/course',
|
||||
@ -85,19 +91,19 @@ const QUICK = [
|
||||
desc: '上架 / 发版前自检清单',
|
||||
},
|
||||
{
|
||||
to: '/wechat/vip/ebooks',
|
||||
title: '✎ 改电子书',
|
||||
desc: 'VIP 电子书章节正文',
|
||||
to: '/wechat/vip/ebooks/nomad',
|
||||
title: '✎ 数字游民',
|
||||
desc: '正式正文 · 微信提审',
|
||||
},
|
||||
{
|
||||
to: '/wechat/vip/course',
|
||||
title: '🎬 改视频课',
|
||||
desc: 'VIP 课时与配套文档',
|
||||
to: '/wechat/vip/ebooks/cloudphone',
|
||||
title: '📱 云手机',
|
||||
desc: 'VIP 云手机电子书',
|
||||
},
|
||||
{
|
||||
to: '/wechat/books/default',
|
||||
title: '⏱ 调试读',
|
||||
desc: '快速改解锁百分比',
|
||||
title: '▶️ youtube运营笔记',
|
||||
desc: '专属小册试读与道具',
|
||||
},
|
||||
] as const
|
||||
|
||||
|
||||
@ -17,7 +17,14 @@ type Settings = {
|
||||
canFavorite: boolean
|
||||
canUpload: boolean
|
||||
adminOnlyPost: boolean
|
||||
/** false=关闭付费墙,全员当 VIP */
|
||||
requireVip: boolean
|
||||
/** 未付费可浏览列表 + 试读帖 */
|
||||
allowTrialBrowse: boolean
|
||||
/** 后台发帖默认试读 */
|
||||
defaultTrial: boolean
|
||||
/** 未付费可读试读帖评论 */
|
||||
trialComments: boolean
|
||||
maxContentLen: number
|
||||
maxImages: number
|
||||
planetName: string
|
||||
@ -37,6 +44,8 @@ type Memo = {
|
||||
tags?: string[]
|
||||
pinned: boolean
|
||||
featured?: boolean
|
||||
trial?: boolean
|
||||
visibility?: string
|
||||
status: string
|
||||
likeCount: number
|
||||
commentCount: number
|
||||
@ -53,6 +62,9 @@ const emptySettings: Settings = {
|
||||
canUpload: true,
|
||||
adminOnlyPost: true,
|
||||
requireVip: true,
|
||||
allowTrialBrowse: true,
|
||||
defaultTrial: true,
|
||||
trialComments: false,
|
||||
maxContentLen: 20000,
|
||||
maxImages: 9,
|
||||
planetName: 'Nomadro 知识社群',
|
||||
@ -71,12 +83,16 @@ export default function MemoAdmin() {
|
||||
const [imgUrls, setImgUrls] = useState('')
|
||||
const [pinNew, setPinNew] = useState(false)
|
||||
const [featNew, setFeatNew] = useState(false)
|
||||
const [trialNew, setTrialNew] = useState(true)
|
||||
const [err, setErr] = useState('')
|
||||
const [msg, setMsg] = useState('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [feedFilter, setFeedFilter] = useState<'all' | 'pinned' | 'featured' | 'hidden'>('all')
|
||||
const [feedFilter, setFeedFilter] = useState<
|
||||
'all' | 'trial' | 'vip' | 'pinned' | 'featured' | 'hidden'
|
||||
>('all')
|
||||
const [stats, setStats] = useState({
|
||||
memos: 0,
|
||||
trial: 0,
|
||||
comments: 0,
|
||||
likes: 0,
|
||||
favorites: 0,
|
||||
@ -90,9 +106,12 @@ export default function MemoAdmin() {
|
||||
stats: typeof stats
|
||||
recent: Memo[]
|
||||
}>('/api/admin/memo')
|
||||
setSettings({ ...emptySettings, ...(data.settings || {}) })
|
||||
const nextSettings = { ...emptySettings, ...(data.settings || {}) }
|
||||
setSettings(nextSettings)
|
||||
setTrialNew(!!nextSettings.defaultTrial)
|
||||
setStats({
|
||||
memos: data.stats?.memos ?? 0,
|
||||
trial: data.stats?.trial ?? 0,
|
||||
comments: data.stats?.comments ?? 0,
|
||||
likes: data.stats?.likes ?? 0,
|
||||
favorites: data.stats?.favorites ?? 0,
|
||||
@ -105,8 +124,13 @@ export default function MemoAdmin() {
|
||||
load().catch((e) => setErr(e.message || '加载失败'))
|
||||
}, [load])
|
||||
|
||||
const isTrialMemo = (m: Memo) =>
|
||||
!!m.trial || m.visibility === 'trial' || m.visibility === 'public' || m.visibility === 'free'
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
return items.filter((m) => {
|
||||
if (feedFilter === 'trial') return isTrialMemo(m)
|
||||
if (feedFilter === 'vip') return !isTrialMemo(m)
|
||||
if (feedFilter === 'pinned') return m.pinned
|
||||
if (feedFilter === 'featured') return !!m.featured
|
||||
if (feedFilter === 'hidden') return m.status !== 'active'
|
||||
@ -159,6 +183,7 @@ export default function MemoAdmin() {
|
||||
nickname: '博主',
|
||||
pinned: pinNew,
|
||||
featured: featNew,
|
||||
trial: trialNew,
|
||||
resources,
|
||||
}),
|
||||
})
|
||||
@ -167,6 +192,7 @@ export default function MemoAdmin() {
|
||||
setImgUrls('')
|
||||
setPinNew(false)
|
||||
setFeatNew(false)
|
||||
setTrialNew(true)
|
||||
setMsg('已发布')
|
||||
await load()
|
||||
} catch (e) {
|
||||
@ -220,6 +246,22 @@ export default function MemoAdmin() {
|
||||
}
|
||||
}
|
||||
|
||||
async function setTrial(id: string, trial: boolean) {
|
||||
setBusy(true)
|
||||
try {
|
||||
await api(`/api/admin/memo/memos/${id}/visibility`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ trial }),
|
||||
})
|
||||
setMsg(trial ? '已设为试读' : '已改为会员专享')
|
||||
await load()
|
||||
} catch (e) {
|
||||
setErr((e as Error).message || '操作失败')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function hide(id: string) {
|
||||
setBusy(true)
|
||||
try {
|
||||
@ -233,9 +275,41 @@ export default function MemoAdmin() {
|
||||
}
|
||||
}
|
||||
|
||||
async function unhide(id: string) {
|
||||
setBusy(true)
|
||||
try {
|
||||
await api(`/api/admin/memo/memos/${id}/unhide`, { method: 'POST' })
|
||||
setMsg('已恢复显示')
|
||||
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: 'enabled', label: '社群总开关', hint: '关闭后小程序接口 403' },
|
||||
{
|
||||
key: 'requireVip',
|
||||
label: '互动需 VIP',
|
||||
hint: '开启后点赞/评论/收藏需真实付费;关闭=全员当 VIP(慎用)',
|
||||
},
|
||||
{
|
||||
key: 'allowTrialBrowse',
|
||||
label: '允许试读浏览',
|
||||
hint: '未付费可进列表;试读帖可读全文,会员帖仅摘要',
|
||||
},
|
||||
{
|
||||
key: 'defaultTrial',
|
||||
label: '发帖默认试读',
|
||||
hint: '后台新发帖默认 visibility=trial',
|
||||
},
|
||||
{
|
||||
key: 'trialComments',
|
||||
label: '试读可见评论',
|
||||
hint: '未付费是否可读试读帖下的讨论(默认关)',
|
||||
},
|
||||
{ key: 'adminOnlyPost', label: '仅博主发帖', hint: '知识星球模式:会员只读互动' },
|
||||
{ key: 'canPost', label: '允许会员发帖', hint: '关闭 adminOnlyPost 后生效' },
|
||||
{ key: 'canComment', label: '允许评论', hint: '会员是否可讨论' },
|
||||
@ -251,7 +325,7 @@ export default function MemoAdmin() {
|
||||
<WxHead
|
||||
eyebrow="知识社群"
|
||||
title="知识社群"
|
||||
desc="对标知识星球:博主发干货帖,会员阅读 / 点赞 / 评论 / 收藏。"
|
||||
desc="试读策略:未付费可浏览 + 读试读帖;会员帖摘要锁定;互动需 VIP。后台可配 allowTrialBrowse / defaultTrial。"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
@ -274,11 +348,15 @@ export default function MemoAdmin() {
|
||||
</WxToast>
|
||||
) : null}
|
||||
|
||||
<div className="wx-stats" style={{ gridTemplateColumns: 'repeat(5, minmax(0, 1fr))' }}>
|
||||
<div className="wx-stats" style={{ gridTemplateColumns: 'repeat(6, minmax(0, 1fr))' }}>
|
||||
<div className="wx-stat">
|
||||
<div className="wx-stat-label">帖子</div>
|
||||
<div className="wx-stat-val">{stats.memos}</div>
|
||||
</div>
|
||||
<div className="wx-stat">
|
||||
<div className="wx-stat-label">试读</div>
|
||||
<div className="wx-stat-val">{stats.trial}</div>
|
||||
</div>
|
||||
<div className="wx-stat">
|
||||
<div className="wx-stat-label">精华</div>
|
||||
<div className="wx-stat-val">{stats.featured}</div>
|
||||
@ -441,6 +519,14 @@ export default function MemoAdmin() {
|
||||
/>
|
||||
精华
|
||||
</label>
|
||||
<label style={{ display: 'flex', gap: 6, alignItems: 'center', fontSize: 13 }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={trialNew}
|
||||
onChange={(e) => setTrialNew(e.target.checked)}
|
||||
/>
|
||||
试读(未付费可读)
|
||||
</label>
|
||||
</div>
|
||||
<button type="button" className="wx-btn" disabled={busy} onClick={() => void publish()}>
|
||||
{busy ? '发布中…' : '发布'}
|
||||
@ -452,6 +538,8 @@ export default function MemoAdmin() {
|
||||
{(
|
||||
[
|
||||
['all', '全部'],
|
||||
['trial', '试读'],
|
||||
['vip', '会员'],
|
||||
['pinned', '置顶'],
|
||||
['featured', '精华'],
|
||||
['hidden', '已隐藏'],
|
||||
@ -474,6 +562,7 @@ export default function MemoAdmin() {
|
||||
<h3>
|
||||
{m.pinned ? '📌 ' : ''}
|
||||
{m.featured ? '✨ ' : ''}
|
||||
{m.trial || m.visibility === 'trial' ? '📖 ' : ''}
|
||||
{m.title || '未命名'}
|
||||
</h3>
|
||||
<div style={{ fontSize: 13, color: 'var(--wx-muted)', lineHeight: 1.5 }}>
|
||||
@ -482,6 +571,9 @@ export default function MemoAdmin() {
|
||||
</div>
|
||||
<div className="wx-feed-meta">
|
||||
<WxBadge tone={m.status === 'active' ? 'ok' : 'muted'}>{m.status}</WxBadge>
|
||||
<WxBadge tone={m.trial || m.visibility === 'trial' ? 'ok' : 'muted'}>
|
||||
{m.trial || m.visibility === 'trial' ? '试读' : '会员'}
|
||||
</WxBadge>
|
||||
<span>👍 {m.likeCount}</span>
|
||||
<span>💬 {m.commentCount}</span>
|
||||
<span>★ {m.favoriteCount || 0}</span>
|
||||
@ -509,6 +601,16 @@ export default function MemoAdmin() {
|
||||
>
|
||||
{m.featured ? '取消精华' : '精华'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="wx-btn-sm"
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
void setTrial(m.id, !(m.trial || m.visibility === 'trial'))
|
||||
}
|
||||
>
|
||||
{m.trial || m.visibility === 'trial' ? '取消试读' : '设为试读'}
|
||||
</button>
|
||||
{m.status === 'active' ? (
|
||||
<button
|
||||
type="button"
|
||||
@ -518,6 +620,15 @@ export default function MemoAdmin() {
|
||||
>
|
||||
隐藏
|
||||
</button>
|
||||
) : m.status === 'hidden' ? (
|
||||
<button
|
||||
type="button"
|
||||
className="wx-btn-sm primary"
|
||||
disabled={busy}
|
||||
onClick={() => void unhide(m.id)}
|
||||
>
|
||||
恢复显示
|
||||
</button>
|
||||
) : null}
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { Link, useSearchParams } from 'react-router-dom'
|
||||
import { api } from '../api'
|
||||
import {
|
||||
WxBadge,
|
||||
@ -24,6 +25,9 @@ type Order = {
|
||||
}
|
||||
|
||||
type StatusTab = 'all' | 'paid' | 'pending' | 'other'
|
||||
type KindTab = 'all' | 'vip' | 'ebook' | 'other'
|
||||
|
||||
const VIP_BOOK_ID = '__vip__'
|
||||
|
||||
function statusTone(status: string): 'ok' | 'warn' | 'bad' | 'muted' {
|
||||
const s = (status || '').toLowerCase()
|
||||
@ -43,13 +47,32 @@ function statusLabel(status: string) {
|
||||
return status || '未知'
|
||||
}
|
||||
|
||||
function orderKind(bookId: string): KindTab {
|
||||
if (bookId === VIP_BOOK_ID) return 'vip'
|
||||
if (!bookId || bookId === 'default') return 'ebook'
|
||||
return 'other'
|
||||
}
|
||||
|
||||
function kindLabel(bookId: string) {
|
||||
if (bookId === VIP_BOOK_ID) return 'VIP 订单'
|
||||
if (!bookId || bookId === 'default') return '小册'
|
||||
return bookId
|
||||
}
|
||||
|
||||
export default function Orders() {
|
||||
const [searchParams, setSearchParams] = useSearchParams()
|
||||
const deepOpenid = (searchParams.get('openid') || '').trim()
|
||||
const deepKind = (searchParams.get('kind') || '').trim() as KindTab | ''
|
||||
|
||||
const [orders, setOrders] = useState<Order[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [err, setErr] = useState('')
|
||||
const [msg, setMsg] = useState('')
|
||||
const [q, setQ] = useState('')
|
||||
const [q, setQ] = useState(deepOpenid)
|
||||
const [tab, setTab] = useState<StatusTab>('all')
|
||||
const [kind, setKind] = useState<KindTab>(
|
||||
deepKind === 'vip' || deepKind === 'ebook' || deepKind === 'other' ? deepKind : 'all',
|
||||
)
|
||||
const [openId, setOpenId] = useState<string | null>(null)
|
||||
|
||||
const load = useCallback(() => {
|
||||
@ -65,11 +88,19 @@ export default function Orders() {
|
||||
load()
|
||||
}, [load])
|
||||
|
||||
useEffect(() => {
|
||||
if (deepOpenid) setQ(deepOpenid)
|
||||
if (deepKind === 'vip' || deepKind === 'ebook' || deepKind === 'other') setKind(deepKind)
|
||||
}, [deepOpenid, deepKind])
|
||||
|
||||
const stats = useMemo(() => {
|
||||
let paid = 0
|
||||
let pending = 0
|
||||
let amount = 0
|
||||
let delivered = 0
|
||||
let vip = 0
|
||||
let ebook = 0
|
||||
let otherKind = 0
|
||||
for (const o of orders) {
|
||||
const s = (o.status || '').toLowerCase()
|
||||
const isPaid = s.includes('paid') || s.includes('success')
|
||||
@ -79,8 +110,12 @@ export default function Orders() {
|
||||
amount += o.amount_fen || 0
|
||||
} else if (isPend) pending += 1
|
||||
if (o.delivered) delivered += 1
|
||||
const k = orderKind(o.book_id || '')
|
||||
if (k === 'vip') vip += 1
|
||||
else if (k === 'ebook') ebook += 1
|
||||
else otherKind += 1
|
||||
}
|
||||
return { paid, pending, amount, delivered, total: orders.length }
|
||||
return { paid, pending, amount, delivered, total: orders.length, vip, ebook, otherKind }
|
||||
}, [orders])
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
@ -92,6 +127,8 @@ export default function Orders() {
|
||||
if (tab === 'paid' && !isPaid) return false
|
||||
if (tab === 'pending' && !isPend) return false
|
||||
if (tab === 'other' && (isPaid || isPend)) return false
|
||||
const k = orderKind(o.book_id || '')
|
||||
if (kind !== 'all' && k !== kind) return false
|
||||
if (!needle) return true
|
||||
return (
|
||||
o.out_trade_no.toLowerCase().includes(needle) ||
|
||||
@ -101,20 +138,32 @@ export default function Orders() {
|
||||
(o.status || '').toLowerCase().includes(needle)
|
||||
)
|
||||
})
|
||||
}, [orders, q, tab])
|
||||
}, [orders, q, tab, kind])
|
||||
|
||||
async function onCopy(text: string, label: string) {
|
||||
const ok = await copyText(text)
|
||||
setMsg(ok ? `已复制 ${label}` : '复制失败')
|
||||
}
|
||||
|
||||
function clearDeepLink() {
|
||||
if (searchParams.has('openid') || searchParams.has('kind')) {
|
||||
const next = new URLSearchParams(searchParams)
|
||||
next.delete('openid')
|
||||
next.delete('kind')
|
||||
setSearchParams(next, { replace: true })
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="wx-page">
|
||||
<WxHead
|
||||
eyebrow="虚拟支付"
|
||||
title="订单"
|
||||
desc="虚拟支付道具直购订单、金额与发货状态。支持搜索、状态筛选与一键复制单号。"
|
||||
desc="支付流水与发货状态。会员身份请在 VIP用户 管理;可用类型筛选与 OpenID 跳转关联。"
|
||||
>
|
||||
<Link className="wx-btn wx-btn-ghost" to="/wechat/vip/users">
|
||||
VIP用户
|
||||
</Link>
|
||||
<button type="button" className="wx-btn wx-btn-ghost" onClick={load} disabled={loading}>
|
||||
{loading ? '刷新中…' : '刷新'}
|
||||
</button>
|
||||
@ -131,6 +180,13 @@ export default function Orders() {
|
||||
</WxToast>
|
||||
) : null}
|
||||
|
||||
{deepOpenid ? (
|
||||
<WxToast kind="ok" onClose={clearDeepLink}>
|
||||
已按用户筛选:{shortId(deepOpenid, 16)}
|
||||
{deepKind === 'vip' ? ' · 仅 VIP 订单' : ''}
|
||||
</WxToast>
|
||||
) : null}
|
||||
|
||||
<div className="wx-stats" style={{ gridTemplateColumns: 'repeat(4, minmax(0, 1fr))' }}>
|
||||
<div className="wx-stat">
|
||||
<div className="wx-stat-label">全部订单</div>
|
||||
@ -151,11 +207,22 @@ export default function Orders() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<WxTabs
|
||||
value={kind}
|
||||
onChange={setKind}
|
||||
items={[
|
||||
{ key: 'all', label: '全部类型', count: stats.total },
|
||||
{ key: 'vip', label: 'VIP', count: stats.vip },
|
||||
{ key: 'ebook', label: '小册', count: stats.ebook },
|
||||
{ key: 'other', label: '其它', count: stats.otherKind },
|
||||
]}
|
||||
/>
|
||||
|
||||
<WxTabs
|
||||
value={tab}
|
||||
onChange={setTab}
|
||||
items={[
|
||||
{ key: 'all', label: '全部', count: stats.total },
|
||||
{ key: 'all', label: '全部状态', count: stats.total },
|
||||
{ key: 'paid', label: '已支付', count: stats.paid },
|
||||
{ key: 'pending', label: '待支付', count: stats.pending },
|
||||
{ key: 'other', label: '其他', count: Math.max(0, stats.total - stats.paid - stats.pending) },
|
||||
@ -172,7 +239,14 @@ export default function Orders() {
|
||||
if (e.key === 'Escape') setQ('')
|
||||
}}
|
||||
/>
|
||||
<button type="button" className="wx-btn wx-btn-ghost" onClick={() => setQ('')}>
|
||||
<button
|
||||
type="button"
|
||||
className="wx-btn wx-btn-ghost"
|
||||
onClick={() => {
|
||||
setQ('')
|
||||
clearDeepLink()
|
||||
}}
|
||||
>
|
||||
清空
|
||||
</button>
|
||||
</div>
|
||||
@ -194,6 +268,7 @@ export default function Orders() {
|
||||
<tbody>
|
||||
{filtered.map((o) => {
|
||||
const open = openId === o.out_trade_no
|
||||
const isVip = o.book_id === VIP_BOOK_ID
|
||||
return (
|
||||
<tr key={o.out_trade_no} className={open ? 'is-open' : undefined}>
|
||||
<td>
|
||||
@ -201,6 +276,9 @@ export default function Orders() {
|
||||
<div className="wx-mono" style={{ opacity: 0.65, marginTop: 4 }}>
|
||||
{o.wx_order_id || '无平台单号'}
|
||||
</div>
|
||||
<div style={{ marginTop: 4 }}>
|
||||
<WxBadge tone={isVip ? 'ok' : 'muted'}>{kindLabel(o.book_id || '')}</WxBadge>
|
||||
</div>
|
||||
{open ? (
|
||||
<div className="wx-detail">
|
||||
book_id: {o.book_id || '—'}
|
||||
@ -230,6 +308,14 @@ export default function Orders() {
|
||||
>
|
||||
{shortId(o.openid, 10)}
|
||||
</button>
|
||||
<div style={{ marginTop: 6 }}>
|
||||
<Link
|
||||
className="wx-link"
|
||||
to={`/wechat/vip/users?openid=${encodeURIComponent(o.openid)}`}
|
||||
>
|
||||
VIP用户
|
||||
</Link>
|
||||
</div>
|
||||
</td>
|
||||
<td>{fmtTime(o.created_at)}</td>
|
||||
<td>
|
||||
@ -241,6 +327,12 @@ export default function Orders() {
|
||||
>
|
||||
{open ? '收起' : '详情'}
|
||||
</button>
|
||||
<Link
|
||||
className="wx-btn-sm"
|
||||
to={`/wechat/vip/users?openid=${encodeURIComponent(o.openid)}`}
|
||||
>
|
||||
用户
|
||||
</Link>
|
||||
<button
|
||||
type="button"
|
||||
className="wx-btn-sm"
|
||||
@ -257,7 +349,13 @@ export default function Orders() {
|
||||
</table>
|
||||
) : (
|
||||
<WxEmpty
|
||||
title={loading ? '加载中…' : q || tab !== 'all' ? '无匹配订单' : '暂无订单'}
|
||||
title={
|
||||
loading
|
||||
? '加载中…'
|
||||
: q || tab !== 'all' || kind !== 'all'
|
||||
? '无匹配订单'
|
||||
: '暂无订单'
|
||||
}
|
||||
hint={loading ? undefined : '用户完成虚拟支付后会出现在此列表'}
|
||||
/>
|
||||
)}
|
||||
|
||||
432
apps/admin/src/pages/Switches.tsx
Normal file
432
apps/admin/src/pages/Switches.tsx
Normal file
@ -0,0 +1,432 @@
|
||||
/**
|
||||
* 微信后台「开关」— 页面 / 入口 / 文案
|
||||
* 近实时写入 remote-config,小程序约 3s 热更新。
|
||||
* 数字游民小册审核在 VIP → 电子书 → 数字游民。
|
||||
*/
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { api } from '../api'
|
||||
import { WxToast } from '../components/wxUi'
|
||||
import './Vip.css'
|
||||
import './switches.css'
|
||||
|
||||
type Mod = { enabled: boolean; title: string; tabLabel?: string; note?: string }
|
||||
type BookRow = { id: string; title: string; is_free?: boolean; chapter_count?: number }
|
||||
|
||||
type SwitchesCfg = {
|
||||
modules: Record<string, Mod>
|
||||
flags: {
|
||||
payEnabled: boolean
|
||||
socialFollow: boolean
|
||||
offlineBadge: boolean
|
||||
joinGroupAction: 'popup' | 'vip'
|
||||
memoTrialBrowse: boolean
|
||||
joinGroupWechat: boolean
|
||||
}
|
||||
copy: {
|
||||
homeBrand: string
|
||||
homeTagline: string
|
||||
homeLead: string
|
||||
vipCta: string
|
||||
wechatOaName: string
|
||||
memoUnlockCta: string
|
||||
}
|
||||
vipEntries: Record<string, boolean>
|
||||
vipHero: {
|
||||
heroEyebrow: string
|
||||
heroTitleAccent: string
|
||||
heroTitleRest: string
|
||||
heroLead: string
|
||||
}
|
||||
bookAudit?: { reviewMode: boolean; bookId: string }
|
||||
books?: BookRow[]
|
||||
version?: number
|
||||
updatedAt?: string
|
||||
}
|
||||
|
||||
type TabKey = 'pages' | 'flags' | 'vip' | 'copy'
|
||||
|
||||
const TABS: Array<{ key: TabKey; label: string }> = [
|
||||
{ key: 'pages', label: '页面' },
|
||||
{ key: 'flags', label: '功能' },
|
||||
{ key: 'vip', label: 'VIP 入口' },
|
||||
{ key: 'copy', label: '文案' },
|
||||
]
|
||||
|
||||
const PAGE_MODS: Array<{ key: string; label: string; ico: string; desc: string }> = [
|
||||
{ key: 'home', label: '首页', ico: '⌂', desc: '小程序首页模块' },
|
||||
{ key: 'nav', label: '出海导航', ico: '🧭', desc: '导航页 / Tab' },
|
||||
{ key: 'book', label: '数字游民小册', ico: '📕', desc: '小册 Tab → 正式读 nomad' },
|
||||
{ key: 'community', label: '旅居社群', ico: '🏕️', desc: '社群入口' },
|
||||
{ key: 'vip', label: 'VIP 中心', ico: '👑', desc: '会员落地页' },
|
||||
{ key: 'destinations', label: '目的地', ico: '📍', desc: '目的地列表' },
|
||||
{ key: 'meetups', label: '活动', ico: '📅', desc: '活动入口' },
|
||||
]
|
||||
|
||||
const VIP_ENTRIES: Array<{ key: string; label: string; desc: string }> = [
|
||||
{ key: 'showStats', label: '数据条', desc: '落地页统计数字' },
|
||||
{ key: 'showTopics', label: '模块入口', desc: '社群 / 商城卡片' },
|
||||
{ key: 'showVideos', label: '视频教程', desc: '视频课区块' },
|
||||
{ key: 'showEbooks', label: '电子书', desc: '电子书区块' },
|
||||
{ key: 'showCompare', label: '对比表', desc: '单买 vs 会员' },
|
||||
{ key: 'showFaq', label: 'FAQ', desc: '常见问题' },
|
||||
{ key: 'showCta', label: '开通 CTA', desc: '底部立即加入' },
|
||||
{ key: 'reviewMode', label: 'VIP 审核', desc: '隐藏促销诱导' },
|
||||
]
|
||||
|
||||
function Switch({
|
||||
checked,
|
||||
onChange,
|
||||
label,
|
||||
disabled,
|
||||
}: {
|
||||
checked: boolean
|
||||
onChange: (v: boolean) => void
|
||||
label: string
|
||||
disabled?: boolean
|
||||
}) {
|
||||
return (
|
||||
<label className="vip-switch" title={label}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={checked}
|
||||
disabled={disabled}
|
||||
onChange={(e) => onChange(e.target.checked)}
|
||||
aria-label={label}
|
||||
/>
|
||||
<span className="vip-switch-track">
|
||||
<span className="vip-switch-thumb" />
|
||||
</span>
|
||||
</label>
|
||||
)
|
||||
}
|
||||
|
||||
export default function Switches() {
|
||||
const [cfg, setCfg] = useState<SwitchesCfg | null>(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [msg, setMsg] = useState('')
|
||||
const [err, setErr] = useState('')
|
||||
const [tab, setTab] = useState<TabKey>('pages')
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setErr('')
|
||||
const data = await api<SwitchesCfg>('/api/admin/weapp/switches')
|
||||
setCfg(data)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
load().catch((e) => setErr(e.message || '加载失败'))
|
||||
}, [load])
|
||||
|
||||
async function patch(body: Record<string, unknown>, okHint: string) {
|
||||
setBusy(true)
|
||||
setMsg('')
|
||||
setErr('')
|
||||
try {
|
||||
const data = await api<SwitchesCfg>('/api/admin/weapp/switches', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
setCfg(data)
|
||||
setMsg(okHint)
|
||||
} catch (e: any) {
|
||||
setErr(e.message || '保存失败')
|
||||
await load().catch(() => undefined)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const onCount = useMemo(() => {
|
||||
if (!cfg) return 0
|
||||
return PAGE_MODS.filter((m) => cfg.modules[m.key]?.enabled !== false).length
|
||||
}, [cfg])
|
||||
|
||||
if (!cfg) {
|
||||
return (
|
||||
<div className="wx-page sw-page">
|
||||
<div className="sw-hero">
|
||||
<div className="sw-kicker">
|
||||
<span className="sw-kicker-dot" />
|
||||
Live Control
|
||||
</div>
|
||||
<h1>开关</h1>
|
||||
<p className="sw-hero-lead">加载远程配置…</p>
|
||||
</div>
|
||||
{err ? (
|
||||
<div className="sw-toast">
|
||||
<WxToast tone="err">{err}</WxToast>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="wx-page sw-page">
|
||||
<header className="sw-hero">
|
||||
<div className="sw-hero-top">
|
||||
<div>
|
||||
<div className="sw-kicker">
|
||||
<span className="sw-kicker-dot" />
|
||||
Live Control · 约 3s 热更新
|
||||
</div>
|
||||
<h1>开关</h1>
|
||||
<p className="sw-hero-lead">
|
||||
一处管页面显示、入口按钮与文案。数字游民微信提审请到「电子书 · 数字游民」。
|
||||
</p>
|
||||
<div className="sw-hero-meta">
|
||||
<span className="sw-pill">
|
||||
版本 <strong>v{cfg.version ?? '-'}</strong>
|
||||
</span>
|
||||
<span className="sw-pill is-ok">
|
||||
页面开启 <strong>{onCount}/{PAGE_MODS.length}</strong>
|
||||
</span>
|
||||
<Link className="sw-pill" to="/wechat/vip/ebooks/nomad">
|
||||
数字游民提审 →
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{msg ? (
|
||||
<div className="sw-toast">
|
||||
<WxToast tone="ok">{msg}</WxToast>
|
||||
</div>
|
||||
) : null}
|
||||
{err ? (
|
||||
<div className="sw-toast">
|
||||
<WxToast tone="err">{err}</WxToast>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<nav className="sw-tabs" aria-label="开关分类">
|
||||
{TABS.map((t) => (
|
||||
<button
|
||||
key={t.key}
|
||||
type="button"
|
||||
className={`sw-tab${tab === t.key ? ' is-on' : ''}`}
|
||||
onClick={() => setTab(t.key)}
|
||||
>
|
||||
{t.label}
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
<section className={`sw-panel${tab === 'pages' ? ' is-on' : ''}`}>
|
||||
<div className="sw-section-head">
|
||||
<h2>页面模块</h2>
|
||||
<p>关闭后小程序对应页拦截,约 3 秒生效</p>
|
||||
</div>
|
||||
<div className="sw-grid">
|
||||
{PAGE_MODS.map((m) => {
|
||||
const on = cfg.modules[m.key]?.enabled !== false
|
||||
return (
|
||||
<article key={m.key} className={`sw-mod${on ? ' is-on' : ' is-off'}`}>
|
||||
<div className="sw-mod-top">
|
||||
<div className="sw-mod-ico" aria-hidden>
|
||||
{m.ico}
|
||||
</div>
|
||||
<Switch
|
||||
checked={on}
|
||||
disabled={busy}
|
||||
label={m.label}
|
||||
onChange={(v) =>
|
||||
void patch(
|
||||
{ modules: { [m.key]: { enabled: v } } },
|
||||
`${m.label}已${v ? '开启' : '关闭'}`,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<h3>{m.label}</h3>
|
||||
<p>{m.desc}</p>
|
||||
<div className="sw-mod-foot">
|
||||
<span className={`sw-status ${on ? 'on' : 'off'}`}>{on ? 'ON' : 'OFF'}</span>
|
||||
</div>
|
||||
</article>
|
||||
)
|
||||
})}
|
||||
<article className="sw-mod is-frozen">
|
||||
<div className="sw-mod-top">
|
||||
<div className="sw-mod-ico" aria-hidden>
|
||||
🎮
|
||||
</div>
|
||||
<Switch checked={false} disabled label="游戏" onChange={() => undefined} />
|
||||
</div>
|
||||
<h3>3D 游戏</h3>
|
||||
<p>已冻结,强制关闭</p>
|
||||
<div className="sw-mod-foot">
|
||||
<span className="sw-status off">FROZEN</span>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className={`sw-panel${tab === 'flags' ? ' is-on' : ''}`}>
|
||||
<div className="sw-card">
|
||||
<div className="sw-card-head">
|
||||
<div>
|
||||
<h2>功能 Flags</h2>
|
||||
<p>支付、关注、试读与加群行为</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="sw-list">
|
||||
{(
|
||||
[
|
||||
['payEnabled', '虚拟支付', '关则无法拉起支付'],
|
||||
['socialFollow', '关注引导', '社交关注弹层'],
|
||||
['offlineBadge', '离线角标', '网络失败时提示本地数据'],
|
||||
['memoTrialBrowse', '知识社群试读', '未开通可浏览试读列表'],
|
||||
] as const
|
||||
).map(([key, title, desc]) => (
|
||||
<div key={key} className="sw-row">
|
||||
<div>
|
||||
<strong>{title}</strong>
|
||||
<span>{desc}</span>
|
||||
</div>
|
||||
<Switch
|
||||
checked={!!cfg.flags[key]}
|
||||
disabled={busy}
|
||||
label={title}
|
||||
onChange={(v) =>
|
||||
void patch({ flags: { [key]: v } }, `${title}已${v ? '开' : '关'}`)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
<div className="sw-row">
|
||||
<div>
|
||||
<strong>加群行为</strong>
|
||||
<span>点击加群:弹窗或跳转 VIP</span>
|
||||
</div>
|
||||
<div className="sw-seg">
|
||||
<button
|
||||
type="button"
|
||||
className={cfg.flags.joinGroupAction === 'popup' ? 'is-on' : ''}
|
||||
disabled={busy}
|
||||
onClick={() => void patch({ flags: { joinGroupAction: 'popup' } }, '加群 → 弹窗')}
|
||||
>
|
||||
弹窗
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={cfg.flags.joinGroupAction === 'vip' ? 'is-on' : ''}
|
||||
disabled={busy}
|
||||
onClick={() => void patch({ flags: { joinGroupAction: 'vip' } }, '加群 → VIP')}
|
||||
>
|
||||
跳 VIP
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className={`sw-panel${tab === 'vip' ? ' is-on' : ''}`}>
|
||||
<div className="sw-card">
|
||||
<div className="sw-card-head">
|
||||
<div>
|
||||
<h2>VIP 落地 · 入口区块</h2>
|
||||
<p>显示 / 隐藏落地页各区块</p>
|
||||
</div>
|
||||
<Link className="sw-btn ghost" to="/wechat/vip">
|
||||
完整 VIP 配置
|
||||
</Link>
|
||||
</div>
|
||||
<div className="sw-grid">
|
||||
{VIP_ENTRIES.map((e) => {
|
||||
const on = !!cfg.vipEntries[e.key]
|
||||
return (
|
||||
<article key={e.key} className={`sw-mod${on ? ' is-on' : ' is-off'}`}>
|
||||
<div className="sw-mod-top">
|
||||
<h3 style={{ marginTop: 4 }}>{e.label}</h3>
|
||||
<Switch
|
||||
checked={on}
|
||||
disabled={busy}
|
||||
label={e.label}
|
||||
onChange={(v) =>
|
||||
void patch(
|
||||
{ vipEntries: { [e.key]: v } },
|
||||
`${e.label}已${v ? '显示' : '隐藏'}`,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<p>{e.desc}</p>
|
||||
<div className="sw-mod-foot">
|
||||
<span className={`sw-status ${on ? 'on' : 'off'}`}>{on ? 'SHOW' : 'HIDE'}</span>
|
||||
</div>
|
||||
</article>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className={`sw-panel${tab === 'copy' ? ' is-on' : ''}`}>
|
||||
<div className="sw-card">
|
||||
<div className="sw-card-head">
|
||||
<div>
|
||||
<h2>文案</h2>
|
||||
<p>失焦自动保存 · CTA 不含价格</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="sw-fields">
|
||||
{(
|
||||
[
|
||||
['homeBrand', '首页品牌'],
|
||||
['homeTagline', '首页副标'],
|
||||
['homeLead', '首页导语'],
|
||||
['vipCta', 'VIP 主按钮'],
|
||||
['wechatOaName', '公众号名'],
|
||||
['memoUnlockCta', '社群解锁文案'],
|
||||
] as const
|
||||
).map(([key, label]) => (
|
||||
<div key={key} className="sw-field">
|
||||
<label>{label}</label>
|
||||
<input
|
||||
value={cfg.copy[key] || ''}
|
||||
disabled={busy}
|
||||
onChange={(e) =>
|
||||
setCfg({
|
||||
...cfg,
|
||||
copy: { ...cfg.copy, [key]: e.target.value },
|
||||
})
|
||||
}
|
||||
onBlur={() => void patch({ copy: { [key]: cfg.copy[key] } }, `${label}已保存`)}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
{(
|
||||
[
|
||||
['heroEyebrow', 'VIP 眉题'],
|
||||
['heroTitleAccent', 'VIP 标题强调'],
|
||||
['heroTitleRest', 'VIP 标题其余'],
|
||||
['heroLead', 'VIP 导语'],
|
||||
] as const
|
||||
).map(([key, label]) => (
|
||||
<div key={key} className="sw-field">
|
||||
<label>{label}</label>
|
||||
<input
|
||||
value={cfg.vipHero[key] || ''}
|
||||
disabled={busy}
|
||||
onChange={(e) =>
|
||||
setCfg({
|
||||
...cfg,
|
||||
vipHero: { ...cfg.vipHero, [key]: e.target.value },
|
||||
})
|
||||
}
|
||||
onBlur={() =>
|
||||
void patch({ vipHero: { [key]: cfg.vipHero[key] } }, `${label}已保存`)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@ -24,10 +24,12 @@ type UserRow = {
|
||||
updated_at: number
|
||||
created_at?: number
|
||||
unlocked_default: boolean
|
||||
unlocked_vip?: boolean
|
||||
unlocks: UnlockRow[]
|
||||
}
|
||||
|
||||
type Tab = 'all' | 'unlocked' | 'locked' | 'blocked'
|
||||
type Tab = 'all' | 'unlocked' | 'vip' | 'locked' | 'blocked'
|
||||
const VIP_BOOK_ID = '__vip__'
|
||||
|
||||
export default function Users() {
|
||||
const [users, setUsers] = useState<UserRow[]>([])
|
||||
@ -62,20 +64,23 @@ export default function Users() {
|
||||
|
||||
const counts = useMemo(() => {
|
||||
let unlocked = 0
|
||||
let vip = 0
|
||||
let locked = 0
|
||||
let blocked = 0
|
||||
for (const u of users) {
|
||||
if ((u.status || 'active') === 'blocked') blocked += 1
|
||||
if (u.unlocked_vip) vip += 1
|
||||
if (u.unlocked_default) unlocked += 1
|
||||
else locked += 1
|
||||
}
|
||||
return { total: users.length, unlocked, locked, blocked }
|
||||
return { total: users.length, unlocked, vip, locked, blocked }
|
||||
}, [users])
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
return users.filter((u) => {
|
||||
const blocked = (u.status || 'active') === 'blocked'
|
||||
if (tab === 'unlocked' && !u.unlocked_default) return false
|
||||
if (tab === 'vip' && !u.unlocked_vip) return false
|
||||
if (tab === 'locked' && u.unlocked_default) return false
|
||||
if (tab === 'blocked' && !blocked) return false
|
||||
return true
|
||||
@ -102,10 +107,13 @@ export default function Users() {
|
||||
<WxHead
|
||||
eyebrow="读者运营"
|
||||
title="读者"
|
||||
desc={`openid 绑定读者(SQLite 主存)。共 ${counts.total} 人,拉黑 ${counts.blocked}。可搜索、筛选、解锁 / 收回 / 拉黑。`}
|
||||
desc={`全量读者与小册解锁。VIP 会员身份建议在「VIP用户」管理。共 ${counts.total} 人 · VIP ${counts.vip}。`}
|
||||
>
|
||||
<Link className="wx-btn wx-btn-ghost" to="/wechat/checklist">
|
||||
部署清单
|
||||
<Link className="wx-btn wx-btn-ghost" to="/wechat/vip/users">
|
||||
VIP用户
|
||||
</Link>
|
||||
<Link className="wx-btn wx-btn-ghost" to="/wechat/orders">
|
||||
订单
|
||||
</Link>
|
||||
<button type="button" className="wx-btn" onClick={() => void refresh()} disabled={loading}>
|
||||
{loading ? '刷新中…' : '刷新'}
|
||||
@ -123,17 +131,21 @@ export default function Users() {
|
||||
</WxToast>
|
||||
) : null}
|
||||
|
||||
<div className="wx-stats" style={{ gridTemplateColumns: 'repeat(4, minmax(0, 1fr))' }}>
|
||||
<div className="wx-stats" style={{ gridTemplateColumns: 'repeat(5, minmax(0, 1fr))' }}>
|
||||
<div className="wx-stat">
|
||||
<div className="wx-stat-label">读者</div>
|
||||
<div className="wx-stat-val">{counts.total}</div>
|
||||
</div>
|
||||
<div className="wx-stat">
|
||||
<div className="wx-stat-label">已解锁</div>
|
||||
<div className="wx-stat-label">VIP</div>
|
||||
<div className="wx-stat-val">{counts.vip}</div>
|
||||
</div>
|
||||
<div className="wx-stat">
|
||||
<div className="wx-stat-label">小册已解锁</div>
|
||||
<div className="wx-stat-val">{counts.unlocked}</div>
|
||||
</div>
|
||||
<div className="wx-stat wx-stat--warn">
|
||||
<div className="wx-stat-label">未解锁</div>
|
||||
<div className="wx-stat-label">小册未解锁</div>
|
||||
<div className="wx-stat-val">{counts.locked}</div>
|
||||
</div>
|
||||
<div className="wx-stat">
|
||||
@ -159,7 +171,7 @@ export default function Users() {
|
||||
<input
|
||||
type="text"
|
||||
value={manualOpenid}
|
||||
placeholder="补录 openid 并解锁全书"
|
||||
placeholder="补录 openid"
|
||||
onChange={(e) => setManualOpenid(e.target.value)}
|
||||
/>
|
||||
<button
|
||||
@ -176,15 +188,35 @@ export default function Users() {
|
||||
})
|
||||
setManualOpenid('')
|
||||
},
|
||||
`已解锁 ${manualOpenid.trim()}`,
|
||||
`已解锁小册 ${manualOpenid.trim()}`,
|
||||
)
|
||||
}
|
||||
>
|
||||
手动解锁
|
||||
补发小册
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="wx-btn wx-btn-ghost"
|
||||
disabled={!manualOpenid.trim() || busy === 'manual-vip'}
|
||||
onClick={() =>
|
||||
void run(
|
||||
'manual-vip',
|
||||
async () => {
|
||||
await api('/api/admin/unlock', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ openid: manualOpenid.trim(), book_id: VIP_BOOK_ID }),
|
||||
})
|
||||
setManualOpenid('')
|
||||
},
|
||||
`已开通 VIP ${manualOpenid.trim()}`,
|
||||
)
|
||||
}
|
||||
>
|
||||
补发 VIP
|
||||
</button>
|
||||
</div>
|
||||
<p className="wx-hint" style={{ marginTop: 12 }}>
|
||||
绑定:小程序 wx.login → code2session → openid 作为主键。详见{' '}
|
||||
<p className="wx-hint" style={{ marginTop: 12, display: 'block' }}>
|
||||
小册 = book_id default;VIP = book_id __vip__(支付发货写入)。详见{' '}
|
||||
<Link className="wx-link" to="/wechat/checklist">
|
||||
部署清单
|
||||
</Link>
|
||||
@ -197,8 +229,9 @@ export default function Users() {
|
||||
onChange={setTab}
|
||||
items={[
|
||||
{ key: 'all', label: '全部', count: counts.total },
|
||||
{ key: 'unlocked', label: '已解锁', count: counts.unlocked },
|
||||
{ key: 'locked', label: '未解锁', count: counts.locked },
|
||||
{ key: 'vip', label: 'VIP', count: counts.vip },
|
||||
{ key: 'unlocked', label: '小册已解锁', count: counts.unlocked },
|
||||
{ key: 'locked', label: '小册未解锁', count: counts.locked },
|
||||
{ key: 'blocked', label: '拉黑', count: counts.blocked },
|
||||
]}
|
||||
/>
|
||||
@ -210,7 +243,8 @@ export default function Users() {
|
||||
<tr>
|
||||
<th>读者</th>
|
||||
<th>状态</th>
|
||||
<th>解锁</th>
|
||||
<th>小册</th>
|
||||
<th>VIP</th>
|
||||
<th>备注</th>
|
||||
<th>活跃</th>
|
||||
<th>操作</th>
|
||||
@ -256,6 +290,11 @@ export default function Users() {
|
||||
{u.unlocked_default ? '全书' : '未解锁'}
|
||||
</WxBadge>
|
||||
</td>
|
||||
<td>
|
||||
<WxBadge tone={u.unlocked_vip ? 'ok' : 'muted'}>
|
||||
{u.unlocked_vip ? 'VIP' : '非会员'}
|
||||
</WxBadge>
|
||||
</td>
|
||||
<td style={{ minWidth: 160 }}>
|
||||
<input
|
||||
defaultValue={u.notes || ''}
|
||||
@ -283,6 +322,18 @@ export default function Users() {
|
||||
>
|
||||
{open ? '收起' : '详情'}
|
||||
</button>
|
||||
<Link
|
||||
className="wx-btn-sm"
|
||||
to={`/wechat/orders?openid=${encodeURIComponent(u.openid)}`}
|
||||
>
|
||||
订单
|
||||
</Link>
|
||||
<Link
|
||||
className="wx-btn-sm"
|
||||
to={`/wechat/vip/users?openid=${encodeURIComponent(u.openid)}`}
|
||||
>
|
||||
VIP页
|
||||
</Link>
|
||||
<button
|
||||
type="button"
|
||||
className="wx-btn-sm primary"
|
||||
@ -296,18 +347,18 @@ export default function Users() {
|
||||
body: JSON.stringify({ openid: u.openid, book_id: 'default' }),
|
||||
})
|
||||
},
|
||||
`已解锁 ${shortId(u.openid)}`,
|
||||
'已补发小册',
|
||||
)
|
||||
}
|
||||
>
|
||||
解锁
|
||||
小册
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="wx-btn-sm"
|
||||
disabled={!u.unlocked_default || busy === `revoke-${u.openid}`}
|
||||
onClick={() => {
|
||||
if (!confirm(`收回 ${u.openid} 的全书解锁?`)) return
|
||||
if (!confirm(`收回 ${u.openid} 的小册解锁?`)) return
|
||||
void run(
|
||||
`revoke-${u.openid}`,
|
||||
async () => {
|
||||
@ -316,11 +367,50 @@ export default function Users() {
|
||||
body: JSON.stringify({ openid: u.openid, book_id: 'default' }),
|
||||
})
|
||||
},
|
||||
'已收回解锁',
|
||||
'已收回小册',
|
||||
)
|
||||
}}
|
||||
>
|
||||
收回
|
||||
收小册
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="wx-btn-sm primary"
|
||||
disabled={!!u.unlocked_vip || busy === `vip-${u.openid}`}
|
||||
onClick={() =>
|
||||
void run(
|
||||
`vip-${u.openid}`,
|
||||
async () => {
|
||||
await api('/api/admin/unlock', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ openid: u.openid, book_id: VIP_BOOK_ID }),
|
||||
})
|
||||
},
|
||||
'已开通 VIP',
|
||||
)
|
||||
}
|
||||
>
|
||||
VIP
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="wx-btn-sm"
|
||||
disabled={!u.unlocked_vip || busy === `rvip-${u.openid}`}
|
||||
onClick={() => {
|
||||
if (!confirm(`收回 ${u.openid} 的 VIP?`)) return
|
||||
void run(
|
||||
`rvip-${u.openid}`,
|
||||
async () => {
|
||||
await api('/api/admin/revoke-unlock', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ openid: u.openid, book_id: VIP_BOOK_ID }),
|
||||
})
|
||||
},
|
||||
'已收回 VIP',
|
||||
)
|
||||
}}
|
||||
>
|
||||
收VIP
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@ -33,6 +33,7 @@ type VipEbook = {
|
||||
title: string
|
||||
desc: string
|
||||
ebookId: string
|
||||
href?: string
|
||||
free: boolean
|
||||
enabled: boolean
|
||||
sort?: number
|
||||
@ -119,7 +120,7 @@ const empty: VipCfg = {
|
||||
joinGroupAction: 'popup',
|
||||
vipPriceFen: 29800,
|
||||
vipProductId: 'tiktok',
|
||||
vipCta: '立即加入 · ¥298',
|
||||
vipCta: '立即加入',
|
||||
vipOfferKey: 'tiktok',
|
||||
is_free: false,
|
||||
vipContent: emptyContent,
|
||||
@ -144,12 +145,24 @@ const TABS: { key: TabKey; label: string }[] = [
|
||||
|
||||
const CONTENT_HUB = [
|
||||
{
|
||||
to: '/wechat/vip/ebooks',
|
||||
ico: '📖',
|
||||
title: '电子书',
|
||||
desc: '章节 Markdown — VIP 正式正文',
|
||||
to: '/wechat/vip/ebooks/nomad',
|
||||
ico: '🌍',
|
||||
title: '数字游民',
|
||||
desc: 'VIP 电子书 · 章节 Markdown',
|
||||
primary: true,
|
||||
},
|
||||
{
|
||||
to: '/wechat/vip/ebooks/cloudphone',
|
||||
ico: '📱',
|
||||
title: '云手机',
|
||||
desc: 'VIP 电子书 · 章节 Markdown',
|
||||
},
|
||||
{
|
||||
to: '/wechat/books/default',
|
||||
ico: '▶️',
|
||||
title: 'youtube运营笔记',
|
||||
desc: '专属小册 · 试读% 与道具',
|
||||
},
|
||||
{
|
||||
to: '/wechat/vip/course',
|
||||
ico: '🎬',
|
||||
@ -517,7 +530,7 @@ export default function Vip() {
|
||||
</div>
|
||||
) : (
|
||||
<div className="vip-free-banner">
|
||||
当前为免费会员:小程序不拉起支付,「立即加入」显示「免费加入」。
|
||||
当前为临时免费:前端权限临时放行,不写用户 VIP;切回收费后未开通用户仍须付费。
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { Link, useLocation, useNavigate } from 'react-router-dom'
|
||||
import { Link, useLocation, useNavigate, useParams } from 'react-router-dom'
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { api } from '../api'
|
||||
import './Vip.css'
|
||||
@ -55,14 +55,29 @@ type Library = {
|
||||
|
||||
type Tab = 'ebooks' | 'course'
|
||||
|
||||
type BookRow = { id: string; title: string; is_free?: boolean; chapter_count?: number }
|
||||
|
||||
type BookAuditCfg = {
|
||||
bookAudit: { reviewMode: boolean; bookId: string }
|
||||
books?: BookRow[]
|
||||
}
|
||||
|
||||
const BOOK_IDS = ['nomad', 'cloudphone'] as const
|
||||
|
||||
const BOOK_LABELS: Record<(typeof BOOK_IDS)[number], string> = {
|
||||
nomad: '数字游民',
|
||||
cloudphone: '云手机',
|
||||
}
|
||||
|
||||
export default function VipLibrary() {
|
||||
const { pathname } = useLocation()
|
||||
const { bookId: bookIdParam } = useParams()
|
||||
const navigate = useNavigate()
|
||||
const tab: Tab = pathname.includes('/vip/course') ? 'course' : 'ebooks'
|
||||
const [lib, setLib] = useState<Library | null>(null)
|
||||
const [bookId, setBookId] = useState<(typeof BOOK_IDS)[number]>('nomad')
|
||||
const routeBook =
|
||||
bookIdParam === 'cloudphone' || bookIdParam === 'nomad' ? bookIdParam : 'nomad'
|
||||
const [bookId, setBookId] = useState<(typeof BOOK_IDS)[number]>(routeBook)
|
||||
const [chapterIdx, setChapterIdx] = useState(0)
|
||||
const [draftTitle, setDraftTitle] = useState('')
|
||||
const [draftHeaders, setDraftHeaders] = useState<string[]>([])
|
||||
@ -75,6 +90,8 @@ export default function VipLibrary() {
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [err, setErr] = useState('')
|
||||
const [msg, setMsg] = useState('')
|
||||
const [auditOn, setAuditOn] = useState(false)
|
||||
const [auditBookId, setAuditBookId] = useState('audit')
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setErr('')
|
||||
@ -91,10 +108,52 @@ export default function VipLibrary() {
|
||||
}
|
||||
}, [bookId])
|
||||
|
||||
const loadAudit = useCallback(async () => {
|
||||
const data = await api<BookAuditCfg>('/api/admin/weapp/switches')
|
||||
const id = data.bookAudit?.bookId || 'audit'
|
||||
setAuditOn(!!data.bookAudit?.reviewMode)
|
||||
setAuditBookId(id)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
load().catch((e) => setErr(e.message || '加载失败'))
|
||||
}, [load])
|
||||
|
||||
useEffect(() => {
|
||||
if (tab !== 'ebooks' || bookId !== 'nomad') return
|
||||
loadAudit().catch(() => undefined)
|
||||
}, [tab, bookId, loadAudit])
|
||||
|
||||
async function setAuditMode(on: boolean) {
|
||||
setBusy(true)
|
||||
setMsg('')
|
||||
setErr('')
|
||||
try {
|
||||
const data = await api<BookAuditCfg>('/api/admin/weapp/switches', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({
|
||||
bookAudit: { reviewMode: on, bookId: auditBookId || 'audit' },
|
||||
}),
|
||||
})
|
||||
setAuditOn(!!data.bookAudit?.reviewMode)
|
||||
setAuditBookId(data.bookAudit?.bookId || 'audit')
|
||||
setMsg(on ? '已切换为提审内容:小程序「小册」将显示审核版' : '已恢复正式会员书')
|
||||
} catch (e: any) {
|
||||
setErr(e.message || '保存失败')
|
||||
await loadAudit().catch(() => undefined)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (tab !== 'ebooks') return
|
||||
if (routeBook === bookId) return
|
||||
setBookId(routeBook)
|
||||
const book = lib?.ebooks?.[routeBook]
|
||||
if (book) applyBook(book)
|
||||
}, [routeBook, tab, bookId, lib])
|
||||
|
||||
function applyBook(book: Ebook) {
|
||||
setDraftTitle(book.title || '')
|
||||
setDraftFree(!!book.free)
|
||||
@ -126,6 +185,9 @@ export default function VipLibrary() {
|
||||
|
||||
async function switchBook(id: (typeof BOOK_IDS)[number]) {
|
||||
setBookId(id)
|
||||
if (tab === 'ebooks') {
|
||||
navigate(`/wechat/vip/ebooks/${id}`, { replace: true })
|
||||
}
|
||||
const book = lib?.ebooks?.[id]
|
||||
if (book) applyBook(book)
|
||||
}
|
||||
@ -158,7 +220,7 @@ export default function VipLibrary() {
|
||||
: prev,
|
||||
)
|
||||
applyBook(data.ebook)
|
||||
setMsg(`电子书「${data.ebook.title}」已保存 · 小程序热更新`)
|
||||
setMsg(`「${data.ebook.title}」已保存,小程序稍后可见`)
|
||||
} catch (e: any) {
|
||||
setErr(e.message || '保存失败')
|
||||
} finally {
|
||||
@ -286,41 +348,47 @@ export default function VipLibrary() {
|
||||
}
|
||||
|
||||
if (!lib && !err) {
|
||||
return <div className="wx-page page vip-page vip-skeleton">加载 VIP 内容库…</div>
|
||||
return <div className="wx-page page vip-page vip-skeleton">加载中…</div>
|
||||
}
|
||||
|
||||
const isNomad = tab === 'ebooks' && bookId === 'nomad'
|
||||
const bookLabel = BOOK_LABELS[bookId]
|
||||
|
||||
return (
|
||||
<div className="wx-page page vip-page">
|
||||
<header className="page-head">
|
||||
<div>
|
||||
<div className="vip-eyebrow">VIP · {tab === 'ebooks' ? '电子书' : '视频课程'}</div>
|
||||
<h1>{tab === 'ebooks' ? '电子书' : '视频课程'}</h1>
|
||||
<div className="vip-eyebrow">
|
||||
{tab === 'ebooks' ? '会员电子书' : '会员视频课'}
|
||||
</div>
|
||||
<h1>{tab === 'ebooks' ? bookLabel : '视频课程'}</h1>
|
||||
<p>
|
||||
{tab === 'ebooks'
|
||||
? '编辑 VIP 电子书章节 Markdown。写入 vip-library.json,小程序优先读远程,失败用包内兜底。'
|
||||
: '编辑视频课目录、课时视频 URL 与配套文档。写入 vip-library.json,小程序优先读远程,失败用包内兜底。'}
|
||||
{isNomad
|
||||
? '这里改的是会员正式版正文。微信提审请用上方「提审内容」,不要和正式版混着改。'
|
||||
: tab === 'ebooks'
|
||||
? '改书名、章节标题与正文。保存后小程序会同步更新。'
|
||||
: '改课程目录、课时视频与配套说明。保存后小程序会同步更新。'}
|
||||
</p>
|
||||
<div className="vip-chips">
|
||||
{tab === 'ebooks' ? (
|
||||
<span className="vip-chip on">
|
||||
电子书 {Object.keys(lib?.ebooks || {}).length}
|
||||
</span>
|
||||
<span className="vip-chip on">{draftSections.length} 章</span>
|
||||
) : (
|
||||
<span className="vip-chip on">
|
||||
课时 {lib?.meta?.courseLessons ?? flatLessons.length}
|
||||
{lib?.meta?.courseLessons ?? flatLessons.length} 课时
|
||||
</span>
|
||||
)}
|
||||
<span className={`vip-chip ${lib?.meta?.hasFile ? 'ok' : ''}`}>
|
||||
{lib?.meta?.hasFile ? '已落盘' : '种子未落盘'}
|
||||
</span>
|
||||
{lib?.version != null ? <span className="vip-chip">v{lib.version}</span> : null}
|
||||
{isNomad ? (
|
||||
<span className={`vip-chip ${auditOn ? 'warn' : 'ok'}`}>
|
||||
{auditOn ? '提审中 · 用户看审核版' : '正式上线'}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
<div className="vip-actions" style={{ marginTop: 0 }}>
|
||||
<button
|
||||
type="button"
|
||||
className={tab === 'ebooks' ? 'vip-btn' : 'vip-btn-ghost'}
|
||||
onClick={() => navigate('/wechat/vip/ebooks')}
|
||||
onClick={() => navigate(`/wechat/vip/ebooks/${bookId}`)}
|
||||
>
|
||||
电子书
|
||||
</button>
|
||||
@ -332,7 +400,7 @@ export default function VipLibrary() {
|
||||
视频课程
|
||||
</button>
|
||||
<Link className="vip-btn-ghost" to="/wechat/vip">
|
||||
← 运营配置
|
||||
← 返回 VIP
|
||||
</Link>
|
||||
</div>
|
||||
</header>
|
||||
@ -354,12 +422,60 @@ export default function VipLibrary() {
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{isNomad ? (
|
||||
<section
|
||||
className="vip-card"
|
||||
style={auditOn ? { borderColor: 'rgba(248, 113, 113, 0.4)' } : undefined}
|
||||
>
|
||||
<div className="vip-card-head">
|
||||
<div>
|
||||
<h2>微信提审</h2>
|
||||
<p>
|
||||
打开后,小程序「小册」只展示独立的审核版正文(不是下面这本正式会员书)。关了就恢复正式版。不影响云手机、youtube运营笔记。
|
||||
</p>
|
||||
</div>
|
||||
<div className="vip-row" style={{ border: 'none', padding: 0, margin: 0 }}>
|
||||
<div style={{ textAlign: 'right', marginRight: 12 }}>
|
||||
<strong>{auditOn ? '提审中' : '正式上线'}</strong>
|
||||
<p className="vip-hint">
|
||||
{auditOn ? '用户正在看审核版' : '用户正在看正式会员书'}
|
||||
</p>
|
||||
</div>
|
||||
<label className="vip-switch" title="微信提审">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={auditOn}
|
||||
disabled={busy}
|
||||
onChange={(e) => void setAuditMode(e.target.checked)}
|
||||
aria-label="微信提审"
|
||||
/>
|
||||
<span className="vip-switch-track">
|
||||
<span className="vip-switch-thumb" />
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div className="vip-actions" style={{ marginTop: 0 }}>
|
||||
<Link className="vip-btn" to={`/wechat/books/${encodeURIComponent(auditBookId || 'audit')}`}>
|
||||
去写审核版正文 →
|
||||
</Link>
|
||||
<span className="vip-hint" style={{ alignSelf: 'center' }}>
|
||||
审核版是单独一本,不会自动抄正式会员书
|
||||
</span>
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{tab === 'ebooks' ? (
|
||||
<section className="vip-card">
|
||||
<div className="vip-card-head">
|
||||
<div>
|
||||
<h2>电子书 · 章节正文</h2>
|
||||
<p>改标题、是否免费、各章 Markdown;保存后小程序 vip-ebook 优先读远程。</p>
|
||||
<h2>{isNomad ? '正式会员书 · 章节' : `${bookLabel} · 章节`}</h2>
|
||||
<p>
|
||||
{isNomad
|
||||
? '会员开通后读到的内容。提审时请改上面的「审核版」,不要改这里。'
|
||||
: '改书名、章节标题与正文。保存后小程序同步。'}
|
||||
</p>
|
||||
</div>
|
||||
<div className="vip-actions" style={{ marginTop: 0 }}>
|
||||
{BOOK_IDS.map((id) => (
|
||||
@ -368,9 +484,9 @@ export default function VipLibrary() {
|
||||
type="button"
|
||||
className={bookId === id ? 'vip-btn' : 'vip-btn-ghost'}
|
||||
disabled={busy}
|
||||
onClick={() => void switchBook(id)}
|
||||
onClick={() => switchBook(id)}
|
||||
>
|
||||
{id === 'nomad' ? '数字游民' : '云手机'}
|
||||
{BOOK_LABELS[id]}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
@ -387,8 +503,8 @@ export default function VipLibrary() {
|
||||
</div>
|
||||
<div className="vip-row" style={{ border: 'none', padding: '0 0 8px' }}>
|
||||
<div>
|
||||
<strong>免费试读</strong>
|
||||
<p className="vip-hint">开启后无需 VIP 即可阅读全书</p>
|
||||
<strong>免费开放</strong>
|
||||
<p className="vip-hint">打开后无需会员也能读完全书</p>
|
||||
</div>
|
||||
<label className="vip-switch">
|
||||
<input
|
||||
@ -439,7 +555,7 @@ export default function VipLibrary() {
|
||||
<div>
|
||||
<div className="vip-fields">
|
||||
<div className="vip-field">
|
||||
<label>章节标题(目录)</label>
|
||||
<label>章节标题</label>
|
||||
<input
|
||||
value={chapterTitle}
|
||||
disabled={busy}
|
||||
@ -447,21 +563,22 @@ export default function VipLibrary() {
|
||||
/>
|
||||
</div>
|
||||
<div className="vip-field">
|
||||
<label>章节 Markdown</label>
|
||||
<label>章节正文</label>
|
||||
<textarea
|
||||
style={{ minHeight: 360, fontFamily: 'ui-monospace, monospace', fontSize: 13 }}
|
||||
value={chapterBody}
|
||||
disabled={busy}
|
||||
onChange={(e) => updateChapterBody(e.target.value)}
|
||||
placeholder="写这一章的正文…"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="vip-actions">
|
||||
<button type="button" className="vip-btn" disabled={busy} onClick={() => void saveEbook()}>
|
||||
{busy ? '保存中…' : '保存整本书'}
|
||||
{busy ? '保存中…' : '保存全书'}
|
||||
</button>
|
||||
<span className="vip-dirty">
|
||||
{draftSections.length} 章 · 当前第 {chapterIdx + 1} 章
|
||||
共 {draftSections.length} 章 · 正在编辑第 {chapterIdx + 1} 章
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
@ -473,8 +590,8 @@ export default function VipLibrary() {
|
||||
<section className="vip-card">
|
||||
<div className="vip-card-head">
|
||||
<div>
|
||||
<h2>视频课 · 课时正文</h2>
|
||||
<p>改课时名、时长、视频地址与配套 Markdown;目录结构可一并保存。</p>
|
||||
<h2>视频课 · 课时内容</h2>
|
||||
<p>改课时名称、时长、视频链接与配套说明;目录可单独保存。</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
@ -564,17 +681,18 @@ export default function VipLibrary() {
|
||||
/>
|
||||
</div>
|
||||
<div className="vip-field">
|
||||
<label>视频 URL</label>
|
||||
<label>视频链接</label>
|
||||
<input
|
||||
value={lessonDoc.videoUrl}
|
||||
disabled={busy}
|
||||
onChange={(e) =>
|
||||
setLessonDoc((d) => ({ ...d, videoUrl: e.target.value }))
|
||||
}
|
||||
placeholder="https://"
|
||||
/>
|
||||
</div>
|
||||
<div className="vip-field">
|
||||
<label>配套文档 Markdown</label>
|
||||
<label>配套说明</label>
|
||||
<textarea
|
||||
style={{ minHeight: 280, fontFamily: 'ui-monospace, monospace', fontSize: 13 }}
|
||||
value={lessonDoc.markdown}
|
||||
@ -582,6 +700,7 @@ export default function VipLibrary() {
|
||||
onChange={(e) =>
|
||||
setLessonDoc((d) => ({ ...d, markdown: e.target.value }))
|
||||
}
|
||||
placeholder="这一课的文字说明…"
|
||||
/>
|
||||
</div>
|
||||
<div className="vip-actions">
|
||||
@ -593,7 +712,6 @@ export default function VipLibrary() {
|
||||
>
|
||||
{busy ? '保存中…' : '保存本课时'}
|
||||
</button>
|
||||
<span className="vip-dirty">key · {lessonKey}</span>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
@ -605,14 +723,16 @@ export default function VipLibrary() {
|
||||
) : null}
|
||||
|
||||
{lib?.updatedAt ? (
|
||||
<p className="vip-meta">
|
||||
最近更新 · v{lib.version ?? '—'} · {lib.updatedAt}
|
||||
</p>
|
||||
<p className="vip-meta">最近保存 · {lib.updatedAt}</p>
|
||||
) : null}
|
||||
|
||||
<div className="wx-sticky-bar">
|
||||
<span className="wx-muted">
|
||||
{tab === 'ebooks' ? `电子书 · ${bookId}` : `视频课 · ${lessonKey || '未选课时'}`}
|
||||
{tab === 'ebooks'
|
||||
? isNomad
|
||||
? '正式会员书'
|
||||
: bookLabel
|
||||
: lessonMeta?.name || '未选课时'}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
@ -624,7 +744,7 @@ export default function VipLibrary() {
|
||||
else void saveCourseStructure()
|
||||
}}
|
||||
>
|
||||
{busy ? '保存中…' : tab === 'ebooks' ? '保存整本书' : lessonKey ? '保存本课时' : '保存目录'}
|
||||
{busy ? '保存中…' : tab === 'ebooks' ? '保存全书' : lessonKey ? '保存本课时' : '保存目录'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
453
apps/admin/src/pages/VipUsers.tsx
Normal file
453
apps/admin/src/pages/VipUsers.tsx
Normal file
@ -0,0 +1,453 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { Link, useSearchParams } from 'react-router-dom'
|
||||
import { api } from '../api'
|
||||
import {
|
||||
WxBadge,
|
||||
WxEmpty,
|
||||
WxHead,
|
||||
WxTabs,
|
||||
WxToast,
|
||||
copyText,
|
||||
fmtTime,
|
||||
shortId,
|
||||
} from '../components/wxUi'
|
||||
|
||||
type UnlockRow = { book_id: string; unlocked_at: number; source: string }
|
||||
|
||||
type UserRow = {
|
||||
openid: string
|
||||
unionid?: string | null
|
||||
nickname?: string | null
|
||||
status?: string
|
||||
notes?: string | null
|
||||
pb_record_id?: string | null
|
||||
updated_at: number
|
||||
created_at?: number
|
||||
last_seen_at?: number | null
|
||||
online?: boolean
|
||||
unlocked_default: boolean
|
||||
unlocked_vip?: boolean
|
||||
unlocks: UnlockRow[]
|
||||
}
|
||||
|
||||
const POLL_MS = 12_000
|
||||
|
||||
type Tab = 'vip' | 'nonvip' | 'all' | 'blocked'
|
||||
const VIP_BOOK_ID = '__vip__'
|
||||
|
||||
export default function VipUsers() {
|
||||
const [searchParams, setSearchParams] = useSearchParams()
|
||||
const deepOpenid = (searchParams.get('openid') || searchParams.get('q') || '').trim()
|
||||
|
||||
const [users, setUsers] = useState<UserRow[]>([])
|
||||
const [q, setQ] = useState(deepOpenid)
|
||||
const [tab, setTab] = useState<Tab>('vip')
|
||||
const [msg, setMsg] = useState('')
|
||||
const [err, setErr] = useState('')
|
||||
const [manualOpenid, setManualOpenid] = useState(deepOpenid)
|
||||
const [busy, setBusy] = useState('')
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [openId, setOpenId] = useState<string | null>(deepOpenid || null)
|
||||
|
||||
const refresh = useCallback(
|
||||
async (search = q, quiet = false) => {
|
||||
if (!quiet) {
|
||||
setLoading(true)
|
||||
setErr('')
|
||||
}
|
||||
try {
|
||||
const qs = search.trim() ? `?q=${encodeURIComponent(search.trim())}` : ''
|
||||
setUsers(await api<UserRow[]>(`/api/admin/users${qs}`))
|
||||
} catch (e: any) {
|
||||
if (!quiet) setErr(e.message || String(e))
|
||||
} finally {
|
||||
if (!quiet) setLoading(false)
|
||||
}
|
||||
},
|
||||
[q],
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
const seed = deepOpenid
|
||||
if (seed) {
|
||||
setQ(seed)
|
||||
setManualOpenid(seed)
|
||||
setOpenId(seed)
|
||||
void refresh(seed)
|
||||
} else {
|
||||
void refresh('')
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- mount / deep-link only
|
||||
}, [deepOpenid])
|
||||
|
||||
// 轮询在线态(小程序心跳 → last_seen)
|
||||
useEffect(() => {
|
||||
const id = window.setInterval(() => void refresh(q, true), POLL_MS)
|
||||
return () => window.clearInterval(id)
|
||||
}, [q, refresh])
|
||||
|
||||
const counts = useMemo(() => {
|
||||
let vip = 0
|
||||
let nonvip = 0
|
||||
let blocked = 0
|
||||
let online = 0
|
||||
for (const u of users) {
|
||||
if ((u.status || 'active') === 'blocked') blocked += 1
|
||||
if (u.online) online += 1
|
||||
if (u.unlocked_vip) vip += 1
|
||||
else nonvip += 1
|
||||
}
|
||||
return { total: users.length, vip, nonvip, blocked, online }
|
||||
}, [users])
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
const rows = users.filter((u) => {
|
||||
const blocked = (u.status || 'active') === 'blocked'
|
||||
if (tab === 'vip' && !u.unlocked_vip) return false
|
||||
if (tab === 'nonvip' && u.unlocked_vip) return false
|
||||
if (tab === 'blocked' && !blocked) return false
|
||||
return true
|
||||
})
|
||||
// 在线置顶
|
||||
return rows.slice().sort((a, b) => {
|
||||
const ao = a.online ? 0 : 1
|
||||
const bo = b.online ? 0 : 1
|
||||
if (ao !== bo) return ao - bo
|
||||
return (b.last_seen_at || b.updated_at || 0) - (a.last_seen_at || a.updated_at || 0)
|
||||
})
|
||||
}, [users, tab])
|
||||
|
||||
async function run(key: string, fn: () => Promise<void>, okMsg?: string) {
|
||||
setBusy(key)
|
||||
setMsg('')
|
||||
setErr('')
|
||||
try {
|
||||
await fn()
|
||||
await refresh()
|
||||
if (okMsg) setMsg(okMsg)
|
||||
} catch (e: any) {
|
||||
setErr(e.message || String(e))
|
||||
} finally {
|
||||
setBusy('')
|
||||
}
|
||||
}
|
||||
|
||||
function clearDeepLink() {
|
||||
if (searchParams.has('openid') || searchParams.has('q')) {
|
||||
setSearchParams({}, { replace: true })
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="wx-page">
|
||||
<WxHead
|
||||
eyebrow="VIP 会员"
|
||||
title="VIP用户"
|
||||
desc={`会员身份(unlocks.__vip__)。小程序在线心跳约 90s 窗口;在线用户光效置顶。共 ${counts.total} 人 · VIP ${counts.vip} · 在线 ${counts.online}。`}
|
||||
>
|
||||
<Link className="wx-btn wx-btn-ghost" to="/wechat/orders?kind=vip">
|
||||
VIP 订单
|
||||
</Link>
|
||||
<Link className="wx-btn wx-btn-ghost" to="/wechat/orders">
|
||||
全部订单
|
||||
</Link>
|
||||
<button type="button" className="wx-btn" onClick={() => void refresh()} disabled={loading}>
|
||||
{loading ? '刷新中…' : '刷新'}
|
||||
</button>
|
||||
</WxHead>
|
||||
|
||||
{err ? (
|
||||
<WxToast kind="err" onClose={() => setErr('')}>
|
||||
{err}
|
||||
</WxToast>
|
||||
) : null}
|
||||
{msg ? (
|
||||
<WxToast kind="ok" onClose={() => setMsg('')}>
|
||||
{msg}
|
||||
</WxToast>
|
||||
) : null}
|
||||
|
||||
{deepOpenid ? (
|
||||
<WxToast kind="ok" onClose={clearDeepLink}>
|
||||
已按 openid 定位:{shortId(deepOpenid, 16)}(来自订单跳转)
|
||||
</WxToast>
|
||||
) : null}
|
||||
|
||||
<div className="wx-stats" style={{ gridTemplateColumns: 'repeat(5, minmax(0, 1fr))' }}>
|
||||
<div className="wx-stat">
|
||||
<div className="wx-stat-label">读者池</div>
|
||||
<div className="wx-stat-val">{counts.total}</div>
|
||||
</div>
|
||||
<div className="wx-stat wx-stat--online">
|
||||
<div className="wx-stat-label">在线</div>
|
||||
<div className="wx-stat-val">{counts.online}</div>
|
||||
</div>
|
||||
<div className="wx-stat">
|
||||
<div className="wx-stat-label">VIP</div>
|
||||
<div className="wx-stat-val">{counts.vip}</div>
|
||||
</div>
|
||||
<div className="wx-stat wx-stat--warn">
|
||||
<div className="wx-stat-label">非会员</div>
|
||||
<div className="wx-stat-val">{counts.nonvip}</div>
|
||||
</div>
|
||||
<div className="wx-stat">
|
||||
<div className="wx-stat-label">拉黑</div>
|
||||
<div className="wx-stat-val">{counts.blocked}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<section className="wx-panel">
|
||||
<div className="wx-toolbar" style={{ marginBottom: 0 }}>
|
||||
<input
|
||||
type="search"
|
||||
value={q}
|
||||
placeholder="搜索 openid / 备注 / 昵称,回车搜索"
|
||||
onChange={(e) => setQ(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') void refresh()
|
||||
}}
|
||||
/>
|
||||
<button type="button" className="wx-btn wx-btn-ghost" onClick={() => void refresh()}>
|
||||
搜索
|
||||
</button>
|
||||
<input
|
||||
type="text"
|
||||
value={manualOpenid}
|
||||
placeholder="补录 openid 开通 VIP"
|
||||
onChange={(e) => setManualOpenid(e.target.value)}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
className="wx-btn"
|
||||
disabled={!manualOpenid.trim() || busy === 'manual-vip'}
|
||||
onClick={() =>
|
||||
void run(
|
||||
'manual-vip',
|
||||
async () => {
|
||||
await api('/api/admin/unlock', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ openid: manualOpenid.trim(), book_id: VIP_BOOK_ID }),
|
||||
})
|
||||
setManualOpenid('')
|
||||
},
|
||||
`已开通 VIP ${manualOpenid.trim()}`,
|
||||
)
|
||||
}
|
||||
>
|
||||
补发 VIP
|
||||
</button>
|
||||
</div>
|
||||
<p className="wx-hint" style={{ marginTop: 12, display: 'block' }}>
|
||||
身份改动在此;流水在{' '}
|
||||
<Link className="wx-link" to="/wechat/orders">
|
||||
订单
|
||||
</Link>
|
||||
。小册解锁请去{' '}
|
||||
<Link className="wx-link" to="/wechat/users">
|
||||
读者
|
||||
</Link>
|
||||
。
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<WxTabs
|
||||
value={tab}
|
||||
onChange={setTab}
|
||||
items={[
|
||||
{ key: 'vip', label: 'VIP', count: counts.vip },
|
||||
{ key: 'nonvip', label: '非会员', count: counts.nonvip },
|
||||
{ key: 'all', label: '全部', count: counts.total },
|
||||
{ key: 'blocked', label: '拉黑', count: counts.blocked },
|
||||
]}
|
||||
/>
|
||||
|
||||
<div className="wx-table-wrap">
|
||||
{filtered.length ? (
|
||||
<table className="wx-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>用户</th>
|
||||
<th>在线</th>
|
||||
<th>状态</th>
|
||||
<th>VIP</th>
|
||||
<th>备注</th>
|
||||
<th>活跃</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{filtered.map((u) => {
|
||||
const blocked = (u.status || 'active') === 'blocked'
|
||||
const open = openId === u.openid
|
||||
const highlight = deepOpenid && u.openid === deepOpenid
|
||||
const online = !!u.online
|
||||
return (
|
||||
<tr
|
||||
key={u.openid}
|
||||
className={`${blocked ? 'is-dim ' : ''}${open || highlight ? 'is-open ' : ''}${
|
||||
online ? 'is-online' : ''
|
||||
}`}
|
||||
>
|
||||
<td>
|
||||
<div className="wx-user-cell">
|
||||
{online ? <span className="wx-online-dot" aria-hidden /> : null}
|
||||
<button
|
||||
type="button"
|
||||
className="wx-btn-sm"
|
||||
title={u.openid}
|
||||
onClick={() =>
|
||||
void copyText(u.openid).then((ok) =>
|
||||
setMsg(ok ? '已复制 OpenID' : '复制失败'),
|
||||
)
|
||||
}
|
||||
>
|
||||
{shortId(u.openid, 12)}
|
||||
</button>
|
||||
</div>
|
||||
{u.nickname ? <div style={{ marginTop: 4 }}>{u.nickname}</div> : null}
|
||||
{open ? (
|
||||
<div className="wx-detail">
|
||||
openid: {u.openid}
|
||||
{u.unionid ? `\nunionid: ${u.unionid}` : ''}
|
||||
{u.pb_record_id ? `\nPB: ${u.pb_record_id}` : ''}
|
||||
{'\n'}unlocks:{' '}
|
||||
{u.unlocks?.length
|
||||
? u.unlocks
|
||||
.map((x) => `${x.book_id}${x.source ? `(${x.source})` : ''}`)
|
||||
.join(' · ')
|
||||
: '无'}
|
||||
</div>
|
||||
) : null}
|
||||
</td>
|
||||
<td>
|
||||
{online ? (
|
||||
<span className="wx-online-badge">在线</span>
|
||||
) : (
|
||||
<WxBadge tone="muted">离线</WxBadge>
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
<WxBadge tone={blocked ? 'bad' : 'ok'}>{blocked ? '拉黑' : '正常'}</WxBadge>
|
||||
</td>
|
||||
<td>
|
||||
<WxBadge tone={u.unlocked_vip ? 'ok' : 'muted'}>
|
||||
{u.unlocked_vip ? 'VIP' : '非会员'}
|
||||
</WxBadge>
|
||||
</td>
|
||||
<td style={{ minWidth: 160 }}>
|
||||
<input
|
||||
defaultValue={u.notes || ''}
|
||||
key={`${u.openid}-notes-${u.updated_at}`}
|
||||
placeholder="备注,失焦保存"
|
||||
onBlur={(e) => {
|
||||
const notes = e.target.value
|
||||
if (notes === (u.notes || '')) return
|
||||
void run(`notes-${u.openid}`, async () => {
|
||||
await api(`/api/admin/users/${encodeURIComponent(u.openid)}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify({ notes }),
|
||||
})
|
||||
}, '备注已保存')
|
||||
}}
|
||||
/>
|
||||
</td>
|
||||
<td>{fmtTime(u.last_seen_at || u.updated_at)}</td>
|
||||
<td>
|
||||
<div className="wx-row-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="wx-btn-sm"
|
||||
onClick={() => setOpenId(open ? null : u.openid)}
|
||||
>
|
||||
{open ? '收起' : '详情'}
|
||||
</button>
|
||||
<Link
|
||||
className="wx-btn-sm"
|
||||
to={`/wechat/orders?openid=${encodeURIComponent(u.openid)}&kind=vip`}
|
||||
>
|
||||
VIP订单
|
||||
</Link>
|
||||
<Link
|
||||
className="wx-btn-sm"
|
||||
to={`/wechat/orders?openid=${encodeURIComponent(u.openid)}`}
|
||||
>
|
||||
全部订单
|
||||
</Link>
|
||||
<button
|
||||
type="button"
|
||||
className="wx-btn-sm primary"
|
||||
disabled={!!u.unlocked_vip || busy === `vip-${u.openid}`}
|
||||
onClick={() =>
|
||||
void run(
|
||||
`vip-${u.openid}`,
|
||||
async () => {
|
||||
await api('/api/admin/unlock', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ openid: u.openid, book_id: VIP_BOOK_ID }),
|
||||
})
|
||||
},
|
||||
'已开通 VIP',
|
||||
)
|
||||
}
|
||||
>
|
||||
开通
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="wx-btn-sm"
|
||||
disabled={!u.unlocked_vip || busy === `rvip-${u.openid}`}
|
||||
onClick={() => {
|
||||
if (!confirm(`收回 ${u.openid} 的 VIP?`)) return
|
||||
void run(
|
||||
`rvip-${u.openid}`,
|
||||
async () => {
|
||||
await api('/api/admin/revoke-unlock', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ openid: u.openid, book_id: VIP_BOOK_ID }),
|
||||
})
|
||||
},
|
||||
'已收回 VIP',
|
||||
)
|
||||
}}
|
||||
>
|
||||
收回
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`wx-btn-sm${blocked ? '' : ' danger'}`}
|
||||
disabled={busy === `block-${u.openid}`}
|
||||
onClick={() => {
|
||||
if (!blocked && !confirm(`拉黑 ${u.openid}?`)) return
|
||||
void run(
|
||||
`block-${u.openid}`,
|
||||
async () => {
|
||||
await api(
|
||||
`/api/admin/users/${encodeURIComponent(u.openid)}/${
|
||||
blocked ? 'unblock' : 'block'
|
||||
}`,
|
||||
{ method: 'POST' },
|
||||
)
|
||||
},
|
||||
blocked ? '已恢复' : '已拉黑',
|
||||
)
|
||||
}}
|
||||
>
|
||||
{blocked ? '解除' : '拉黑'}
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
) : (
|
||||
<WxEmpty
|
||||
title={loading ? '加载中…' : '暂无匹配用户'}
|
||||
hint="用户打开小程序登录后会出现;也可上方补录 openid 开通 VIP"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
573
apps/admin/src/pages/switches.css
Normal file
573
apps/admin/src/pages/switches.css
Normal file
@ -0,0 +1,573 @@
|
||||
/* 开关页 — 总览运营控制台 */
|
||||
|
||||
.sw-page {
|
||||
--sw-accent: #5ec478;
|
||||
--sw-accent-2: #7be0a4;
|
||||
--sw-amber: #e4b45a;
|
||||
--sw-rose: #f07160;
|
||||
max-width: 1120px;
|
||||
}
|
||||
|
||||
.sw-hero {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
border-radius: 20px;
|
||||
padding: 22px 24px 20px;
|
||||
margin-bottom: 18px;
|
||||
background:
|
||||
radial-gradient(520px 220px at 8% -20%, rgba(94, 196, 120, 0.28), transparent 60%),
|
||||
radial-gradient(420px 180px at 92% 0%, rgba(228, 180, 90, 0.16), transparent 55%),
|
||||
linear-gradient(145deg, rgba(22, 36, 28, 0.96), rgba(12, 18, 15, 0.98));
|
||||
border: 1px solid rgba(150, 210, 170, 0.16);
|
||||
box-shadow: 0 18px 48px rgba(0, 0, 0, 0.28);
|
||||
}
|
||||
|
||||
.sw-hero::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: auto -10% -40% auto;
|
||||
width: 220px;
|
||||
height: 220px;
|
||||
border-radius: 50%;
|
||||
background: radial-gradient(circle, rgba(94, 196, 120, 0.12), transparent 70%);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.sw-hero-top {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
flex-wrap: wrap;
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.sw-kicker {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 12px;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
color: rgba(123, 224, 164, 0.85);
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.sw-kicker-dot {
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-radius: 50%;
|
||||
background: var(--sw-accent);
|
||||
box-shadow: 0 0 0 4px rgba(94, 196, 120, 0.18);
|
||||
animation: sw-pulse 2.2s ease-in-out infinite;
|
||||
}
|
||||
|
||||
@keyframes sw-pulse {
|
||||
0%,
|
||||
100% {
|
||||
transform: scale(1);
|
||||
opacity: 1;
|
||||
}
|
||||
50% {
|
||||
transform: scale(0.85);
|
||||
opacity: 0.7;
|
||||
}
|
||||
}
|
||||
|
||||
.sw-hero h1 {
|
||||
margin: 0;
|
||||
font-size: clamp(1.45rem, 2.4vw, 1.85rem);
|
||||
font-weight: 700;
|
||||
letter-spacing: -0.02em;
|
||||
color: #eef8f0;
|
||||
}
|
||||
|
||||
.sw-hero-lead {
|
||||
margin: 8px 0 0;
|
||||
max-width: 46ch;
|
||||
color: #8fad99;
|
||||
font-size: 13.5px;
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
.sw-hero-meta {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-top: 14px;
|
||||
}
|
||||
|
||||
.sw-pill {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 5px 10px;
|
||||
border-radius: 999px;
|
||||
font-size: 12px;
|
||||
background: rgba(255, 255, 255, 0.04);
|
||||
border: 1px solid rgba(150, 210, 170, 0.16);
|
||||
color: #b7d0bf;
|
||||
}
|
||||
|
||||
.sw-pill strong {
|
||||
color: #e7f3ea;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.sw-pill.is-hot {
|
||||
border-color: rgba(228, 180, 90, 0.35);
|
||||
background: rgba(228, 180, 90, 0.1);
|
||||
color: #f0d59a;
|
||||
}
|
||||
|
||||
.sw-pill.is-ok {
|
||||
border-color: rgba(94, 196, 120, 0.35);
|
||||
background: rgba(94, 196, 120, 0.12);
|
||||
color: #9fe0b4;
|
||||
}
|
||||
|
||||
.sw-tabs {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin: 0 0 16px;
|
||||
padding: 4px;
|
||||
border-radius: 14px;
|
||||
background: rgba(15, 24, 20, 0.7);
|
||||
border: 1px solid rgba(150, 210, 170, 0.1);
|
||||
}
|
||||
|
||||
.sw-tab {
|
||||
appearance: none;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: #8fad99;
|
||||
font: inherit;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
padding: 10px 14px;
|
||||
border-radius: 11px;
|
||||
cursor: pointer;
|
||||
min-height: 40px;
|
||||
transition: background 0.18s, color 0.18s, transform 0.18s;
|
||||
}
|
||||
|
||||
.sw-tab:hover {
|
||||
color: #e7f3ea;
|
||||
background: rgba(255, 255, 255, 0.04);
|
||||
}
|
||||
|
||||
.sw-tab.is-on {
|
||||
color: #0c1410;
|
||||
background: linear-gradient(135deg, #7be0a4, #5ec478);
|
||||
box-shadow: 0 8px 20px rgba(94, 196, 120, 0.25);
|
||||
}
|
||||
|
||||
.sw-panel {
|
||||
display: none;
|
||||
animation: sw-in 0.28s ease;
|
||||
}
|
||||
|
||||
.sw-panel.is-on {
|
||||
display: block;
|
||||
}
|
||||
|
||||
@keyframes sw-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(6px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: none;
|
||||
}
|
||||
}
|
||||
|
||||
.sw-section-head {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
margin: 0 0 12px;
|
||||
}
|
||||
|
||||
.sw-section-head h2 {
|
||||
margin: 0;
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
color: #e7f3ea;
|
||||
}
|
||||
|
||||
.sw-section-head p {
|
||||
margin: 0;
|
||||
font-size: 12.5px;
|
||||
color: #6f8a78;
|
||||
}
|
||||
|
||||
.sw-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.sw-mod {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
padding: 16px;
|
||||
border-radius: 16px;
|
||||
background: rgba(18, 28, 22, 0.92);
|
||||
border: 1px solid rgba(150, 210, 170, 0.12);
|
||||
transition: border-color 0.2s, transform 0.2s, box-shadow 0.2s;
|
||||
min-height: 128px;
|
||||
}
|
||||
|
||||
.sw-mod:hover {
|
||||
border-color: rgba(94, 196, 120, 0.28);
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 12px 28px rgba(0, 0, 0, 0.22);
|
||||
}
|
||||
|
||||
.sw-mod.is-on {
|
||||
border-color: rgba(94, 196, 120, 0.32);
|
||||
background:
|
||||
radial-gradient(140px 80px at 100% 0%, rgba(94, 196, 120, 0.14), transparent 70%),
|
||||
rgba(18, 28, 22, 0.96);
|
||||
}
|
||||
|
||||
.sw-mod.is-off {
|
||||
opacity: 0.72;
|
||||
}
|
||||
|
||||
.sw-mod.is-frozen {
|
||||
opacity: 0.45;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.sw-mod-top {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.sw-mod-ico {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
border-radius: 12px;
|
||||
font-size: 18px;
|
||||
background: rgba(94, 196, 120, 0.12);
|
||||
border: 1px solid rgba(94, 196, 120, 0.16);
|
||||
}
|
||||
|
||||
.sw-mod h3 {
|
||||
margin: 0;
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
color: #eef6f0;
|
||||
}
|
||||
|
||||
.sw-mod p {
|
||||
margin: 0;
|
||||
font-size: 12px;
|
||||
line-height: 1.45;
|
||||
color: #7d9788;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.sw-mod-foot {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
margin-top: auto;
|
||||
padding-top: 4px;
|
||||
}
|
||||
|
||||
.sw-status {
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.sw-status.on {
|
||||
color: #6ee7b7;
|
||||
}
|
||||
|
||||
.sw-status.off {
|
||||
color: #6f8a78;
|
||||
}
|
||||
|
||||
.sw-card {
|
||||
border-radius: 18px;
|
||||
padding: 18px 18px 16px;
|
||||
margin-bottom: 14px;
|
||||
background: rgba(16, 24, 20, 0.9);
|
||||
border: 1px solid rgba(150, 210, 170, 0.12);
|
||||
}
|
||||
|
||||
.sw-card-head {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
.sw-card-head h2 {
|
||||
margin: 0 0 4px;
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.sw-card-head p {
|
||||
margin: 0;
|
||||
font-size: 12.5px;
|
||||
color: #7d9788;
|
||||
line-height: 1.45;
|
||||
max-width: 56ch;
|
||||
}
|
||||
|
||||
.sw-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.sw-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
padding: 14px 4px;
|
||||
border-top: 1px solid rgba(150, 210, 170, 0.08);
|
||||
}
|
||||
|
||||
.sw-row:first-child {
|
||||
border-top: none;
|
||||
padding-top: 2px;
|
||||
}
|
||||
|
||||
.sw-row strong {
|
||||
display: block;
|
||||
font-size: 13.5px;
|
||||
color: #e7f3ea;
|
||||
margin-bottom: 3px;
|
||||
}
|
||||
|
||||
.sw-row span {
|
||||
display: block;
|
||||
font-size: 12px;
|
||||
color: #6f8a78;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.sw-seg {
|
||||
display: inline-flex;
|
||||
padding: 3px;
|
||||
border-radius: 999px;
|
||||
background: rgba(0, 0, 0, 0.25);
|
||||
border: 1px solid rgba(150, 210, 170, 0.12);
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.sw-seg button {
|
||||
appearance: none;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: #8fad99;
|
||||
font: inherit;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
padding: 7px 12px;
|
||||
border-radius: 999px;
|
||||
cursor: pointer;
|
||||
min-height: 32px;
|
||||
}
|
||||
|
||||
.sw-seg button.is-on {
|
||||
background: rgba(94, 196, 120, 0.2);
|
||||
color: #c8f0d4;
|
||||
}
|
||||
|
||||
.sw-audit {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
border-radius: 18px;
|
||||
padding: 20px;
|
||||
margin-bottom: 14px;
|
||||
border: 1px solid rgba(228, 180, 90, 0.22);
|
||||
background:
|
||||
radial-gradient(360px 160px at 100% 0%, rgba(228, 180, 90, 0.14), transparent 55%),
|
||||
rgba(22, 20, 14, 0.92);
|
||||
}
|
||||
|
||||
.sw-audit.is-live {
|
||||
border-color: rgba(94, 196, 120, 0.35);
|
||||
background:
|
||||
radial-gradient(360px 160px at 100% 0%, rgba(94, 196, 120, 0.16), transparent 55%),
|
||||
rgba(14, 22, 18, 0.95);
|
||||
}
|
||||
|
||||
.sw-audit-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 4px 10px;
|
||||
border-radius: 999px;
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.03em;
|
||||
background: rgba(228, 180, 90, 0.14);
|
||||
color: #f0d59a;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.sw-audit.is-live .sw-audit-badge {
|
||||
background: rgba(94, 196, 120, 0.16);
|
||||
color: #9fe0b4;
|
||||
}
|
||||
|
||||
.sw-audit h2 {
|
||||
margin: 0 0 6px;
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.sw-audit > p {
|
||||
margin: 0 0 16px;
|
||||
font-size: 13px;
|
||||
color: #a89a78;
|
||||
line-height: 1.5;
|
||||
max-width: 58ch;
|
||||
}
|
||||
|
||||
.sw-audit.is-live > p {
|
||||
color: #8fad99;
|
||||
}
|
||||
|
||||
.sw-audit-controls {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr auto;
|
||||
gap: 14px;
|
||||
align-items: end;
|
||||
}
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.sw-audit-controls {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
.sw-field label {
|
||||
display: block;
|
||||
font-size: 12px;
|
||||
color: #8fad99;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.sw-field input,
|
||||
.sw-field textarea {
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
border-radius: 12px;
|
||||
border: 1px solid rgba(150, 210, 170, 0.16);
|
||||
background: rgba(0, 0, 0, 0.22);
|
||||
color: #e7f3ea;
|
||||
font: inherit;
|
||||
font-size: 13.5px;
|
||||
padding: 11px 12px;
|
||||
outline: none;
|
||||
transition: border-color 0.18s, box-shadow 0.18s;
|
||||
}
|
||||
|
||||
.sw-field input:focus,
|
||||
.sw-field textarea:focus {
|
||||
border-color: rgba(94, 196, 120, 0.45);
|
||||
box-shadow: 0 0 0 3px rgba(94, 196, 120, 0.12);
|
||||
}
|
||||
|
||||
.sw-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.sw-btn {
|
||||
appearance: none;
|
||||
border: none;
|
||||
border-radius: 11px;
|
||||
padding: 10px 14px;
|
||||
min-height: 40px;
|
||||
font: inherit;
|
||||
font-size: 13px;
|
||||
font-weight: 650;
|
||||
cursor: pointer;
|
||||
background: linear-gradient(135deg, #7be0a4, #5ec478);
|
||||
color: #0c1410;
|
||||
text-decoration: none;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.sw-btn:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.sw-btn.ghost {
|
||||
background: rgba(255, 255, 255, 0.04);
|
||||
color: #c5d9cb;
|
||||
border: 1px solid rgba(150, 210, 170, 0.16);
|
||||
}
|
||||
|
||||
.sw-book-chips {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.sw-book-chip {
|
||||
appearance: none;
|
||||
border: 1px solid rgba(150, 210, 170, 0.14);
|
||||
background: rgba(0, 0, 0, 0.18);
|
||||
color: #9eb8a8;
|
||||
border-radius: 999px;
|
||||
padding: 6px 11px;
|
||||
font: inherit;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.sw-book-chip.is-on {
|
||||
border-color: rgba(94, 196, 120, 0.4);
|
||||
background: rgba(94, 196, 120, 0.14);
|
||||
color: #c8f0d4;
|
||||
}
|
||||
|
||||
.sw-fields {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.sw-fields {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.sw-hero {
|
||||
padding: 18px 16px;
|
||||
}
|
||||
}
|
||||
|
||||
.sw-toast {
|
||||
position: sticky;
|
||||
top: 12px;
|
||||
z-index: 20;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
@ -274,6 +274,28 @@
|
||||
border-radius: 7px !important;
|
||||
}
|
||||
|
||||
.wx-nav-branch--nested {
|
||||
margin: 2px 0;
|
||||
}
|
||||
|
||||
.wx-nav-parent--nested {
|
||||
padding: 8px 10px;
|
||||
min-height: 38px;
|
||||
font-size: 13px;
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.wx-nav-branch--nested > .wx-nav-sub {
|
||||
margin-left: 10px;
|
||||
padding-left: 8px;
|
||||
}
|
||||
|
||||
.wx-nav-sublink--deep {
|
||||
padding-left: 8px !important;
|
||||
font-size: 12.5px !important;
|
||||
min-height: 36px !important;
|
||||
}
|
||||
|
||||
.wx-side-foot {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@ -1124,6 +1146,87 @@ a.wx-stat:hover .wx-stat-go {
|
||||
background: rgba(94, 196, 120, 0.07);
|
||||
}
|
||||
|
||||
@keyframes wx-online-pulse {
|
||||
0%,
|
||||
100% {
|
||||
box-shadow:
|
||||
0 0 0 0 rgba(94, 196, 120, 0.55),
|
||||
inset 0 0 0 1px rgba(123, 224, 164, 0.35);
|
||||
background: rgba(94, 196, 120, 0.1);
|
||||
}
|
||||
50% {
|
||||
box-shadow:
|
||||
0 0 18px 2px rgba(94, 196, 120, 0.45),
|
||||
inset 0 0 0 1px rgba(123, 224, 164, 0.65);
|
||||
background: rgba(94, 196, 120, 0.18);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes wx-online-dot {
|
||||
0%,
|
||||
100% {
|
||||
transform: scale(1);
|
||||
box-shadow: 0 0 0 0 rgba(94, 196, 120, 0.7);
|
||||
}
|
||||
50% {
|
||||
transform: scale(1.15);
|
||||
box-shadow: 0 0 10px 2px rgba(123, 224, 164, 0.85);
|
||||
}
|
||||
}
|
||||
|
||||
.wx-table tr.is-online td {
|
||||
animation: wx-online-pulse 2.2s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.wx-table tr.is-online td:first-child {
|
||||
box-shadow: inset 3px 0 0 #5ec478;
|
||||
}
|
||||
|
||||
.wx-user-cell {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.wx-online-dot {
|
||||
width: 9px;
|
||||
height: 9px;
|
||||
border-radius: 50%;
|
||||
background: #5ec478;
|
||||
flex-shrink: 0;
|
||||
animation: wx-online-dot 1.6s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.wx-online-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
min-height: 26px;
|
||||
padding: 2px 10px;
|
||||
border-radius: 999px;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
color: #0a100e;
|
||||
background: linear-gradient(120deg, #7be0a4, #5ec478 55%, #d7b35a);
|
||||
background-size: 180% 100%;
|
||||
animation: wx-online-badge-shine 2.4s linear infinite;
|
||||
box-shadow: 0 0 12px rgba(94, 196, 120, 0.45);
|
||||
}
|
||||
|
||||
@keyframes wx-online-badge-shine {
|
||||
0% {
|
||||
background-position: 0% 50%;
|
||||
}
|
||||
100% {
|
||||
background-position: 180% 50%;
|
||||
}
|
||||
}
|
||||
|
||||
.wx-stat--online .wx-stat-val {
|
||||
color: #7be0a4;
|
||||
text-shadow: 0 0 16px rgba(94, 196, 120, 0.45);
|
||||
}
|
||||
|
||||
.wx-mono {
|
||||
font-family: ui-monospace, Consolas, 'Courier New', monospace;
|
||||
font-size: 12px;
|
||||
|
||||
@ -1,11 +1,16 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import Header, HTTPException
|
||||
|
||||
from ebook_svc.services.store import store
|
||||
|
||||
# 鉴权成功时节流写 last_seen,减轻 SQLite 写入
|
||||
_LAST_TOUCH: dict[str, float] = {}
|
||||
_TOUCH_MIN_INTERVAL = 20.0
|
||||
|
||||
|
||||
async def get_current_openid(authorization: Annotated[str | None, Header()] = None) -> str:
|
||||
if not authorization or not authorization.startswith("Bearer "):
|
||||
@ -16,4 +21,25 @@ async def get_current_openid(authorization: Annotated[str | None, Header()] = No
|
||||
raise HTTPException(401, "登录已失效")
|
||||
if (user.get("status") or "active") == "blocked":
|
||||
raise HTTPException(403, "账号不可用")
|
||||
return user["openid"]
|
||||
openid = str(user["openid"])
|
||||
now = time.time()
|
||||
prev = _LAST_TOUCH.get(openid, 0.0)
|
||||
if now - prev >= _TOUCH_MIN_INTERVAL:
|
||||
_LAST_TOUCH[openid] = now
|
||||
try:
|
||||
store.touch_last_seen(openid)
|
||||
except Exception:
|
||||
pass
|
||||
return openid
|
||||
|
||||
|
||||
async def get_optional_openid(
|
||||
authorization: Annotated[str | None, Header()] = None,
|
||||
) -> str:
|
||||
"""登录则返回 openid;未登录返回空串(供免费/提审书匿名阅读)。"""
|
||||
if not authorization or not authorization.startswith("Bearer "):
|
||||
return ""
|
||||
try:
|
||||
return await get_current_openid(authorization)
|
||||
except HTTPException:
|
||||
return ""
|
||||
|
||||
@ -62,8 +62,12 @@ def truncate_by_percent(chapters: list[dict], percent: int) -> list[dict]:
|
||||
|
||||
def public_book(book: dict) -> dict:
|
||||
chapters = [
|
||||
{"id": c["id"], "title": c["title"], "order": c["order"]}
|
||||
for c in book.get("chapters") or []
|
||||
{
|
||||
"id": c.get("id") or f"ch-{i + 1}",
|
||||
"title": c.get("title") or f"章节 {i + 1}",
|
||||
"order": int(c["order"]) if c.get("order") is not None else i + 1,
|
||||
}
|
||||
for i, c in enumerate(book.get("chapters") or [])
|
||||
]
|
||||
free = is_book_free(book)
|
||||
offer = match_offer(book)
|
||||
|
||||
@ -79,6 +79,10 @@ app.include_router(shop_admin.router)
|
||||
app.include_router(memo_admin.router)
|
||||
# 导航远程 CRUD(navContent)
|
||||
app.include_router(nav_admin.router)
|
||||
# 微信「开关」总控(页面/入口/文案/小册审核)
|
||||
from ebook_svc.routers import weapp_switches_admin # noqa: E402
|
||||
|
||||
app.include_router(weapp_switches_admin.router)
|
||||
# 公开远程配置(抖音真机:dyapi/api 合法域名 + 有效证书)
|
||||
app.include_router(public_config.router)
|
||||
|
||||
|
||||
@ -22,6 +22,8 @@ from ebook_svc.services.store import store
|
||||
|
||||
router = APIRouter(prefix="/api/admin", tags=["admin"])
|
||||
|
||||
VIP_BOOK_ID = "__vip__"
|
||||
|
||||
|
||||
@router.post("/login")
|
||||
async def admin_login(body: AdminLoginBody):
|
||||
@ -60,6 +62,17 @@ async def admin_books(_: str = Depends(require_admin)):
|
||||
@router.get("/books/{book_id}")
|
||||
async def admin_book(book_id: str, _: str = Depends(require_admin)):
|
||||
book = store.get_book(book_id)
|
||||
# 审核备用书等:首次打开自动建壳,避免 404
|
||||
if not book:
|
||||
try:
|
||||
book = store.ensure_book(
|
||||
book_id,
|
||||
title="数字游民·提审版" if book_id == "audit" else book_id,
|
||||
subtitle="微信提审专用 · 与正式会员书无关",
|
||||
free=True,
|
||||
)
|
||||
except Exception:
|
||||
book = None
|
||||
if not book:
|
||||
raise HTTPException(404, "不存在")
|
||||
offer = match_offer(book)
|
||||
@ -171,17 +184,19 @@ async def admin_orders(_: str = Depends(require_admin)):
|
||||
|
||||
@router.post("/unlock")
|
||||
async def admin_manual_unlock(body: ManualUnlockBody, _: str = Depends(require_admin)):
|
||||
"""后台手动发货:用于道具未发布前联调,或客服补发。"""
|
||||
book = store.get_book(body.book_id)
|
||||
if not book:
|
||||
raise HTTPException(404, "书籍不存在")
|
||||
"""后台手动发货:小册 default / VIP __vip__ / 其它 book_id。"""
|
||||
book_id = (body.book_id or "").strip() or "default"
|
||||
if book_id != VIP_BOOK_ID:
|
||||
book = store.get_book(book_id)
|
||||
if not book:
|
||||
raise HTTPException(404, "书籍不存在")
|
||||
if not body.openid.strip():
|
||||
raise HTTPException(400, "openid 不能为空")
|
||||
openid = body.openid.strip()
|
||||
if not store.get_user(openid):
|
||||
# 允许客服先录入 openid 再解锁:创建占位用户
|
||||
store.upsert_user(openid, "", secrets.token_urlsafe(12), None)
|
||||
store.grant_unlock(openid, body.book_id, source="manual")
|
||||
store.grant_unlock(openid, book_id, source="manual")
|
||||
user = store.get_user(openid)
|
||||
try:
|
||||
if user:
|
||||
@ -190,15 +205,16 @@ async def admin_manual_unlock(body: ManualUnlockBody, _: str = Depends(require_a
|
||||
store.set_user_pb_id(openid, rid)
|
||||
except Exception:
|
||||
pass
|
||||
return {"ok": True, "openid": openid, "book_id": body.book_id, "unlocked": True}
|
||||
return {"ok": True, "openid": openid, "book_id": book_id, "unlocked": True}
|
||||
|
||||
|
||||
@router.post("/revoke-unlock")
|
||||
async def admin_revoke_unlock(body: RevokeUnlockBody, _: str = Depends(require_admin)):
|
||||
if not body.openid.strip():
|
||||
raise HTTPException(400, "openid 不能为空")
|
||||
ok = store.revoke_unlock(body.openid.strip(), body.book_id)
|
||||
return {"ok": ok, "openid": body.openid.strip(), "book_id": body.book_id}
|
||||
book_id = (body.book_id or "").strip() or "default"
|
||||
ok = store.revoke_unlock(body.openid.strip(), book_id)
|
||||
return {"ok": ok, "openid": body.openid.strip(), "book_id": book_id}
|
||||
|
||||
|
||||
@router.get("/users")
|
||||
|
||||
@ -60,3 +60,15 @@ async def login(body: LoginBody):
|
||||
client="api",
|
||||
)
|
||||
return {"openid": openid, "token": token, "session_ready": bool(session_key)}
|
||||
|
||||
|
||||
@router.post("/presence")
|
||||
async def presence_ping(openid: str = Depends(get_current_openid)):
|
||||
"""小程序前台心跳:刷新 last_seen,并带回 isVip 供端上近实时刷新会员态。"""
|
||||
store.touch_last_seen(openid)
|
||||
return {
|
||||
"ok": True,
|
||||
"openid": openid,
|
||||
"onlineWindowSec": store.ONLINE_WINDOW_SEC,
|
||||
"isVip": store.is_unlocked(openid, "__vip__"),
|
||||
}
|
||||
|
||||
@ -2,18 +2,32 @@ from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Response
|
||||
|
||||
from ebook_svc.core.deps import get_current_openid
|
||||
from ebook_svc.core.deps import get_current_openid, get_optional_openid
|
||||
from ebook_svc.domains.books import access_snapshot, is_free_unlock, public_book, truncate_by_percent
|
||||
from ebook_svc.services.store import store
|
||||
|
||||
router = APIRouter(prefix="/books", tags=["books"])
|
||||
|
||||
# 原小册(对外文案 Youtube运营笔记)book_id=default:单买解锁 或 VIP(__vip__) 均可全文
|
||||
VIP_BOOK_ID = "__vip__"
|
||||
VIP_ALSO_UNLOCKS = frozenset({"default"})
|
||||
|
||||
|
||||
def _no_store(resp: Response) -> None:
|
||||
resp.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, max-age=0"
|
||||
resp.headers["Pragma"] = "no-cache"
|
||||
|
||||
|
||||
def _book_unlocked(openid: str, book_id: str, *, free: bool) -> bool:
|
||||
if free:
|
||||
return True
|
||||
if store.is_unlocked(openid, book_id):
|
||||
return True
|
||||
if book_id in VIP_ALSO_UNLOCKS and store.is_unlocked(openid, VIP_BOOK_ID):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
@router.get("/{book_id}")
|
||||
async def get_book(book_id: str, response: Response):
|
||||
_no_store(response)
|
||||
@ -35,7 +49,7 @@ async def book_access(
|
||||
if not book:
|
||||
raise HTTPException(404, "书籍不存在")
|
||||
free = is_free_unlock(book.get("unlock_percent"))
|
||||
unlocked = free or store.is_unlocked(openid, book_id)
|
||||
unlocked = _book_unlocked(openid, book_id, free=free)
|
||||
return access_snapshot(book, openid=openid, unlocked=unlocked)
|
||||
|
||||
|
||||
@ -43,14 +57,17 @@ async def book_access(
|
||||
async def read_book(
|
||||
book_id: str,
|
||||
response: Response,
|
||||
openid: str = Depends(get_current_openid),
|
||||
openid: str = Depends(get_optional_openid),
|
||||
):
|
||||
_no_store(response)
|
||||
book = store.get_book(book_id)
|
||||
if not book:
|
||||
raise HTTPException(404, "书籍不存在")
|
||||
free = is_free_unlock(book.get("unlock_percent"))
|
||||
unlocked = free or store.is_unlocked(openid, book_id)
|
||||
# 付费书必须登录;免费/提审书可匿名全文
|
||||
if not free and not openid:
|
||||
raise HTTPException(401, "未登录")
|
||||
unlocked = _book_unlocked(openid or "anon", book_id, free=free)
|
||||
chapters = book["chapters"]
|
||||
if not unlocked:
|
||||
chapters = truncate_by_percent(chapters, book["unlock_percent"])
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
"""VIP 知识社群公开 API — 知识星球风格阅读 + 互动。"""
|
||||
"""VIP 知识社群公开 API — 试读浏览 + VIP 互动。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import mimetypes
|
||||
@ -22,14 +22,32 @@ VIP_BOOK_ID = "__vip__"
|
||||
UPLOAD_DIR = Path(settings.sqlite_path).resolve().parent / "uploads" / "memo"
|
||||
|
||||
|
||||
def _require_vip(openid: str) -> None:
|
||||
def _is_vip(openid: str) -> bool:
|
||||
"""付费方案下查 unlocks(__vip__);免费方案 / requireVip=false 视为全员 VIP。"""
|
||||
cfg = read_vip_config()
|
||||
s = memo_store.get_settings()
|
||||
if not s.get("requireVip"):
|
||||
return
|
||||
return True
|
||||
if cfg.get("is_free") or int(cfg.get("vipPriceFen") or 0) <= 0:
|
||||
return
|
||||
if not store.is_unlocked(openid, VIP_BOOK_ID):
|
||||
return True
|
||||
return store.is_unlocked(openid, VIP_BOOK_ID)
|
||||
|
||||
|
||||
def _require_vip(openid: str) -> None:
|
||||
if not _is_vip(openid):
|
||||
raise HTTPException(403, "开通 VIP 后可互动")
|
||||
|
||||
|
||||
def _allow_browse(openid: str) -> bool:
|
||||
"""列表/详情浏览:VIP 或 allowTrialBrowse。"""
|
||||
if _is_vip(openid):
|
||||
return True
|
||||
s = memo_store.get_settings()
|
||||
return bool(s.get("allowTrialBrowse", True))
|
||||
|
||||
|
||||
def _require_browse(openid: str) -> None:
|
||||
if not _allow_browse(openid):
|
||||
raise HTTPException(403, "开通 VIP 后可进入知识社群")
|
||||
|
||||
|
||||
@ -47,31 +65,48 @@ def _gate_enabled() -> dict[str, Any]:
|
||||
return s
|
||||
|
||||
|
||||
@router.get("/settings")
|
||||
async def public_settings(openid: str = Depends(get_current_openid)) -> dict[str, Any]:
|
||||
_require_vip(openid)
|
||||
def _public_settings_payload(openid: str) -> dict[str, Any]:
|
||||
s = memo_store.get_settings()
|
||||
is_vip = _is_vip(openid)
|
||||
allow_browse = is_vip or bool(s.get("allowTrialBrowse", True))
|
||||
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)),
|
||||
"isVip": is_vip,
|
||||
"allowTrialBrowse": bool(s.get("allowTrialBrowse", True)),
|
||||
"defaultTrial": bool(s.get("defaultTrial", True)),
|
||||
"trialComments": bool(s.get("trialComments", False)),
|
||||
"requireVip": bool(s.get("requireVip", True)),
|
||||
"canBrowse": allow_browse,
|
||||
"canPost": bool(is_vip)
|
||||
and bool(s.get("canPost"))
|
||||
and not bool(s.get("adminOnlyPost")),
|
||||
"canComment": bool(is_vip) and bool(s.get("canComment")),
|
||||
"canLike": bool(is_vip) and bool(s.get("canLike")),
|
||||
"canFavorite": bool(is_vip) and bool(s.get("canFavorite", True)),
|
||||
"canUpload": bool(is_vip) and 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),
|
||||
"unlockHint": "开通 VIP 后可读全文并参与讨论",
|
||||
# 前端轮询:隐藏/发帖/改配置后变化 → 立刻重拉列表
|
||||
"contentRevision": int(s.get("_contentRevision") or 0),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/settings")
|
||||
async def public_settings(openid: str = Depends(get_current_openid)) -> dict[str, Any]:
|
||||
"""社群配置 + 当前用户 VIP/试读策略(不强制 enabled,前端可展示关闭态)。"""
|
||||
return _public_settings_payload(openid)
|
||||
|
||||
|
||||
@router.get("/tags")
|
||||
async def tags(openid: str = Depends(get_current_openid)) -> dict[str, Any]:
|
||||
_require_vip(openid)
|
||||
_gate_enabled()
|
||||
_require_browse(openid)
|
||||
return {"ok": True, "items": memo_store.list_tags()}
|
||||
|
||||
|
||||
@ -84,11 +119,19 @@ async def feed(
|
||||
tag: str = "",
|
||||
tab: str = "all",
|
||||
) -> dict[str, Any]:
|
||||
_require_vip(openid)
|
||||
"""
|
||||
试读策略:
|
||||
- allowTrialBrowse + 未付费:可拉列表;trial 帖保留正文,vip 帖仅摘要(locked)
|
||||
- 未开 allowTrialBrowse:非 VIP 403
|
||||
"""
|
||||
_gate_enabled()
|
||||
_require_browse(openid)
|
||||
is_vip = _is_vip(openid)
|
||||
tab_n = (tab or "all").strip().lower()
|
||||
if tab_n not in {"all", "featured", "latest", "mine"}:
|
||||
tab_n = "all"
|
||||
if tab_n == "mine" and not is_vip:
|
||||
return {"ok": True, "items": [], "offline": False, "isVip": False}
|
||||
featured = True if tab_n == "featured" else None
|
||||
favorited_by = openid if tab_n == "mine" else ""
|
||||
items = memo_store.list_memos(
|
||||
@ -99,21 +142,41 @@ async def feed(
|
||||
tag=tag,
|
||||
featured=featured,
|
||||
favorited_by=favorited_by,
|
||||
safe_search=not is_vip,
|
||||
)
|
||||
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}
|
||||
items = [memo_store.apply_access(x, is_vip=is_vip) for x in items]
|
||||
return {
|
||||
"ok": True,
|
||||
"items": items,
|
||||
"offline": False,
|
||||
"isVip": is_vip,
|
||||
"contentRevision": memo_store.content_revision(),
|
||||
}
|
||||
|
||||
|
||||
@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()
|
||||
"""试读帖全文;会员帖未付费 → locked + excerpt;评论默认仅 VIP。"""
|
||||
s = _gate_enabled()
|
||||
_require_browse(openid)
|
||||
is_vip = _is_vip(openid)
|
||||
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}
|
||||
memo = memo_store.apply_access(memo, is_vip=is_vip)
|
||||
show_comments = is_vip or (
|
||||
bool(memo.get("trial")) and bool(s.get("trialComments", False))
|
||||
)
|
||||
comments = memo_store.list_comments(memo_id) if show_comments else []
|
||||
return {
|
||||
"ok": True,
|
||||
"memo": memo,
|
||||
"comments": comments,
|
||||
"isVip": is_vip,
|
||||
"commentsLocked": not show_comments,
|
||||
}
|
||||
|
||||
|
||||
class ResourceIn(BaseModel):
|
||||
@ -172,7 +235,6 @@ async def upload_image(
|
||||
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
|
||||
@ -222,17 +284,19 @@ async def create_memo(body: PostBody, openid: str = Depends(get_current_openid))
|
||||
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),
|
||||
visibility="vip",
|
||||
resources=resources,
|
||||
)
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, str(e)) from e
|
||||
return {"ok": True, "memo": memo}
|
||||
return {"ok": True, "memo": memo_store.apply_access(memo, is_vip=True)}
|
||||
|
||||
|
||||
@router.delete("/memos/{memo_id}")
|
||||
@ -257,7 +321,7 @@ async def like_memo(memo_id: str, openid: str = Depends(get_current_openid)) ->
|
||||
memo = memo_store.toggle_like(memo_id, openid)
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, str(e)) from e
|
||||
return {"ok": True, "memo": memo}
|
||||
return {"ok": True, "memo": memo_store.apply_access(memo, is_vip=True)}
|
||||
|
||||
|
||||
@router.post("/memos/{memo_id}/favorite")
|
||||
@ -270,7 +334,7 @@ async def favorite_memo(memo_id: str, openid: str = Depends(get_current_openid))
|
||||
memo = memo_store.toggle_favorite(memo_id, openid)
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, str(e)) from e
|
||||
return {"ok": True, "memo": memo}
|
||||
return {"ok": True, "memo": memo_store.apply_access(memo, is_vip=True)}
|
||||
|
||||
|
||||
class CommentBody(BaseModel):
|
||||
@ -297,18 +361,3 @@ async def comment_memo(
|
||||
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}
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
"""知识社群管理:admin.nomadro.cn/wechat/memo"""
|
||||
"""知识社群管理:admin.nomadro.cn/wechat/memo — 含试读配置。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
@ -18,6 +18,9 @@ class AdminPostBody(BaseModel):
|
||||
nickname: str = "博主"
|
||||
pinned: bool = False
|
||||
featured: bool = False
|
||||
# None → 跟随 settings.defaultTrial
|
||||
trial: bool | None = None
|
||||
visibility: str | None = None
|
||||
resources: list[dict[str, Any]] = Field(default_factory=list)
|
||||
|
||||
|
||||
@ -30,6 +33,9 @@ class SettingsBody(BaseModel):
|
||||
canUpload: bool | None = None
|
||||
adminOnlyPost: bool | None = None
|
||||
requireVip: bool | None = None
|
||||
allowTrialBrowse: bool | None = None
|
||||
defaultTrial: bool | None = None
|
||||
trialComments: 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
|
||||
@ -45,6 +51,12 @@ class FeaturedBody(BaseModel):
|
||||
featured: bool = True
|
||||
|
||||
|
||||
class VisibilityBody(BaseModel):
|
||||
"""trial=试读(未付费可读全文);vip=会员专享。"""
|
||||
trial: bool | None = None
|
||||
visibility: str | None = None
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def overview(_: str = Depends(require_admin)) -> dict[str, Any]:
|
||||
settings = memo_store.get_settings()
|
||||
@ -67,15 +79,30 @@ async def put_settings(body: SettingsBody, _: str = Depends(require_admin)) -> d
|
||||
@router.get("/memos")
|
||||
async def list_memos(
|
||||
q: str = "",
|
||||
visibility: 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)
|
||||
items = memo_store.list_memos(
|
||||
limit=limit,
|
||||
include_hidden=True,
|
||||
q=q,
|
||||
visibility=visibility,
|
||||
)
|
||||
return {"ok": True, "items": items}
|
||||
|
||||
|
||||
@router.post("/memos")
|
||||
async def admin_post(body: AdminPostBody, _: str = Depends(require_admin)) -> dict[str, Any]:
|
||||
s = memo_store.get_settings()
|
||||
if body.trial is True:
|
||||
vis = "trial"
|
||||
elif body.trial is False:
|
||||
vis = "vip"
|
||||
elif body.visibility:
|
||||
vis = body.visibility
|
||||
else:
|
||||
vis = "trial" if s.get("defaultTrial", True) else "vip"
|
||||
try:
|
||||
memo = memo_store.create_memo(
|
||||
openid="__admin__",
|
||||
@ -84,6 +111,7 @@ async def admin_post(body: AdminPostBody, _: str = Depends(require_admin)) -> di
|
||||
nickname=body.nickname or "博主",
|
||||
pinned=body.pinned,
|
||||
featured=body.featured,
|
||||
visibility=vis,
|
||||
resources=body.resources or [],
|
||||
)
|
||||
except ValueError as e:
|
||||
@ -107,6 +135,17 @@ async def admin_hide(memo_id: str, _: str = Depends(require_admin)) -> dict[str,
|
||||
return {"ok": True, "memo": memo}
|
||||
|
||||
|
||||
@router.post("/memos/{memo_id}/unhide")
|
||||
async def admin_unhide(memo_id: str, _: str = Depends(require_admin)) -> dict[str, Any]:
|
||||
try:
|
||||
memo = memo_store.unhide_memo(memo_id)
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, str(e)) from e
|
||||
if not memo:
|
||||
raise HTTPException(404, "不存在")
|
||||
return {"ok": True, "memo": memo}
|
||||
|
||||
|
||||
@router.post("/memos/{memo_id}/pin")
|
||||
async def admin_pin(
|
||||
memo_id: str,
|
||||
@ -131,6 +170,27 @@ async def admin_featured(
|
||||
return {"ok": True, "memo": memo}
|
||||
|
||||
|
||||
@router.post("/memos/{memo_id}/visibility")
|
||||
async def admin_visibility(
|
||||
memo_id: str,
|
||||
body: VisibilityBody,
|
||||
_: str = Depends(require_admin),
|
||||
) -> dict[str, Any]:
|
||||
if body.trial is True:
|
||||
vis = "trial"
|
||||
elif body.trial is False:
|
||||
vis = "vip"
|
||||
else:
|
||||
vis = (body.visibility or "vip").strip().lower()
|
||||
try:
|
||||
memo = memo_store.set_visibility(memo_id, vis)
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, str(e)) from e
|
||||
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)}
|
||||
|
||||
@ -32,6 +32,42 @@ class ShopOrderBody(BaseModel):
|
||||
address: dict[str, Any] | None = None
|
||||
|
||||
|
||||
def _validate_shop_email(email: str) -> None:
|
||||
s = (email or "").strip()
|
||||
if not s:
|
||||
raise HTTPException(400, "虚拟商品请填写邮箱")
|
||||
if "@" not in s or "." not in s.split("@")[-1] or " " in s:
|
||||
raise HTTPException(400, "邮箱格式不正确")
|
||||
|
||||
|
||||
def _validate_shop_address(addr: dict[str, Any] | None) -> dict[str, str]:
|
||||
a = addr or {}
|
||||
user_name = str(a.get("userName") or "").strip()
|
||||
tel = str(a.get("telNumber") or "").strip()
|
||||
province = str(a.get("provinceName") or "").strip()
|
||||
city = str(a.get("cityName") or "").strip() or province
|
||||
county = str(a.get("countyName") or "").strip()
|
||||
detail = str(a.get("detailInfo") or "").strip()
|
||||
if len(user_name) < 2 or len(user_name) > 20:
|
||||
raise HTTPException(400, "请填写有效收货人姓名")
|
||||
if not all("\u4e00" <= ch <= "\u9fff" or ch.isalpha() or ch in "· " for ch in user_name):
|
||||
raise HTTPException(400, "收货人姓名仅支持中英文")
|
||||
if not (tel.isdigit() and len(tel) == 11 and tel.startswith("1")):
|
||||
raise HTTPException(400, "请填写正确的 11 位手机号")
|
||||
if not province:
|
||||
raise HTTPException(400, "请选择省市区")
|
||||
if len(detail) < 5 or len(detail) > 80:
|
||||
raise HTTPException(400, "请填写完整详细地址")
|
||||
return {
|
||||
"userName": user_name,
|
||||
"telNumber": tel,
|
||||
"provinceName": province,
|
||||
"cityName": city,
|
||||
"countyName": county,
|
||||
"detailInfo": detail,
|
||||
}
|
||||
|
||||
|
||||
def _vip_product_ids() -> set[str]:
|
||||
return {
|
||||
str(o["product_id"])
|
||||
@ -162,13 +198,12 @@ async def create_shop_pay_order(
|
||||
if not wx_pid and not settings.debug:
|
||||
raise HTTPException(400, "商品未配置虚拟支付道具 ID")
|
||||
|
||||
address_clean: dict[str, str] | None = None
|
||||
email_clean = (body.email or "").strip()
|
||||
if product["goodsType"] == "physical":
|
||||
addr = body.address or {}
|
||||
if not (addr.get("userName") and addr.get("telNumber") and addr.get("detailInfo")):
|
||||
raise HTTPException(400, "实体商品请选择收货地址")
|
||||
address_clean = _validate_shop_address(body.address)
|
||||
else:
|
||||
if not (body.email or "").strip():
|
||||
raise HTTPException(400, "虚拟商品请填写邮箱")
|
||||
_validate_shop_email(email_clean)
|
||||
|
||||
user = store.get_user(openid)
|
||||
if not user or not user.get("session_key"):
|
||||
@ -200,8 +235,8 @@ async def create_shop_pay_order(
|
||||
openid=openid,
|
||||
product=product,
|
||||
qty=body.qty,
|
||||
email=(body.email or "").strip(),
|
||||
address=body.address,
|
||||
email=email_clean,
|
||||
address=address_clean,
|
||||
out_trade_no=out_trade_no,
|
||||
)
|
||||
|
||||
@ -256,6 +291,9 @@ async def create_pay_order(body: OrderBody, openid: str = Depends(get_current_op
|
||||
raise HTTPException(400, "当前为免费模式,无需购买")
|
||||
if store.is_unlocked(openid, body.book_id):
|
||||
raise HTTPException(400, "已解锁,无需重复购买")
|
||||
# 原小册 default:已是 VIP 则视为已解锁(与 /books 读权限一致)
|
||||
if body.book_id == "default" and store.is_unlocked(openid, VIP_BOOK_ID):
|
||||
raise HTTPException(400, "已解锁,无需重复购买")
|
||||
if not book.get("product_id") or int(book.get("price_fen") or 0) <= 0:
|
||||
raise HTTPException(400, "未配置付费道具")
|
||||
|
||||
@ -318,6 +356,8 @@ async def create_pay_order(body: OrderBody, openid: str = Depends(get_current_op
|
||||
async def pay_status(body: StatusBody, openid: str = Depends(get_current_openid)):
|
||||
order = store.get_order(body.out_trade_no)
|
||||
unlocked = store.is_unlocked(openid, body.book_id)
|
||||
if not unlocked and body.book_id == "default":
|
||||
unlocked = store.is_unlocked(openid, VIP_BOOK_ID)
|
||||
return {
|
||||
"unlocked": unlocked,
|
||||
"status": (order or {}).get("status", "unknown"),
|
||||
|
||||
116
apps/api/services/ebook_svc/routers/weapp_switches_admin.py
Normal file
116
apps/api/services/ebook_svc/routers/weapp_switches_admin.py
Normal file
@ -0,0 +1,116 @@
|
||||
"""微信后台「开关」— admin.nomadro.cn/wechat/switches。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Literal
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from ebook_svc.core.security import require_admin
|
||||
from ebook_svc.services.store import store
|
||||
from ebook_svc.services.weapp_switches import read_weapp_switches, write_weapp_switches
|
||||
|
||||
router = APIRouter(prefix="/api/admin/weapp/switches", tags=["weapp-switches"])
|
||||
|
||||
|
||||
class ModuleIn(BaseModel):
|
||||
enabled: bool | None = None
|
||||
title: str | None = None
|
||||
tabLabel: str | None = None
|
||||
note: str | None = None
|
||||
|
||||
|
||||
class FlagsIn(BaseModel):
|
||||
payEnabled: bool | None = None
|
||||
socialFollow: bool | None = None
|
||||
offlineBadge: bool | None = None
|
||||
joinGroupAction: Literal["popup", "vip"] | None = None
|
||||
memoTrialBrowse: bool | None = None
|
||||
joinGroupWechat: bool | None = None
|
||||
|
||||
|
||||
class CopyIn(BaseModel):
|
||||
homeBrand: str | None = None
|
||||
homeTagline: str | None = None
|
||||
homeLead: str | None = None
|
||||
vipCta: str | None = None
|
||||
wechatOaName: str | None = None
|
||||
memoUnlockCta: str | None = None
|
||||
|
||||
|
||||
class BookAuditIn(BaseModel):
|
||||
reviewMode: bool | None = None
|
||||
bookId: str | None = None
|
||||
|
||||
|
||||
class VipHeroIn(BaseModel):
|
||||
heroEyebrow: str | None = None
|
||||
heroTitleAccent: str | None = None
|
||||
heroTitleRest: str | None = None
|
||||
heroLead: str | None = None
|
||||
|
||||
|
||||
class SwitchesBody(BaseModel):
|
||||
modules: dict[str, ModuleIn] | None = None
|
||||
flags: FlagsIn | None = None
|
||||
copy: CopyIn | None = Field(default=None, alias="copy")
|
||||
vipEntries: dict[str, bool] | None = None
|
||||
vipHero: VipHeroIn | None = None
|
||||
bookAudit: BookAuditIn | None = None
|
||||
|
||||
model_config = {"populate_by_name": True}
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def get_switches(_: str = Depends(require_admin)) -> dict[str, Any]:
|
||||
data = read_weapp_switches()
|
||||
books = []
|
||||
try:
|
||||
for b in store.list_books():
|
||||
books.append(
|
||||
{
|
||||
"id": b.get("id"),
|
||||
"title": b.get("title"),
|
||||
"is_free": b.get("is_free"),
|
||||
"chapter_count": b.get("chapter_count"),
|
||||
}
|
||||
)
|
||||
except Exception:
|
||||
books = []
|
||||
data["books"] = books
|
||||
return data
|
||||
|
||||
|
||||
@router.put("")
|
||||
async def put_switches(body: SwitchesBody, _: str = Depends(require_admin)) -> dict[str, Any]:
|
||||
patch: dict[str, Any] = {}
|
||||
if body.modules is not None:
|
||||
patch["modules"] = {
|
||||
k: v.model_dump(exclude_none=True) for k, v in body.modules.items()
|
||||
}
|
||||
if body.flags is not None:
|
||||
patch["flags"] = body.flags.model_dump(exclude_none=True)
|
||||
if body.copy is not None:
|
||||
patch["copy"] = body.copy.model_dump(exclude_none=True)
|
||||
if body.vipEntries is not None:
|
||||
patch["vipEntries"] = body.vipEntries
|
||||
if body.vipHero is not None:
|
||||
patch["vipHero"] = body.vipHero.model_dump(exclude_none=True)
|
||||
if body.bookAudit is not None:
|
||||
patch["bookAudit"] = body.bookAudit.model_dump(exclude_none=True)
|
||||
saved = write_weapp_switches(patch)
|
||||
books = []
|
||||
try:
|
||||
for b in store.list_books():
|
||||
books.append(
|
||||
{
|
||||
"id": b.get("id"),
|
||||
"title": b.get("title"),
|
||||
"is_free": b.get("is_free"),
|
||||
"chapter_count": b.get("chapter_count"),
|
||||
}
|
||||
)
|
||||
except Exception:
|
||||
books = []
|
||||
saved["books"] = books
|
||||
return saved
|
||||
@ -23,12 +23,19 @@ DEFAULT_SETTINGS: dict[str, Any] = {
|
||||
"canFavorite": True,
|
||||
"canUpload": True,
|
||||
"adminOnlyPost": True,
|
||||
# requireVip=False → 全员视为 VIP(关闭付费墙)
|
||||
"requireVip": True,
|
||||
# 未付费可浏览列表 + 试读帖;关闭则 feed/detail 也需 VIP
|
||||
"allowTrialBrowse": True,
|
||||
# 后台发帖默认试读
|
||||
"defaultTrial": True,
|
||||
# 未付费是否可读试读帖下的评论(默认否,防讨论区泄露)
|
||||
"trialComments": False,
|
||||
"maxContentLen": 20000,
|
||||
"maxImages": 9,
|
||||
"planetName": "Nomadro 知识社群",
|
||||
"planetDesc": "博主分享实战干货,会员阅读互动",
|
||||
"notice": "置顶与精华优先 · 支持 Markdown / 图片 / #话题",
|
||||
"notice": "置顶与精华优先 · 支持 Markdown / 图片 / #话题 · 未付费可试读",
|
||||
}
|
||||
|
||||
SEED_MEMOS = [
|
||||
@ -47,6 +54,7 @@ SEED_MEMOS = [
|
||||
"openid": "__system__",
|
||||
"pinned": 1,
|
||||
"featured": 1,
|
||||
"visibility": "trial",
|
||||
"resources": [],
|
||||
},
|
||||
{
|
||||
@ -63,6 +71,7 @@ SEED_MEMOS = [
|
||||
"openid": "__system__",
|
||||
"pinned": 0,
|
||||
"featured": 1,
|
||||
"visibility": "trial",
|
||||
"resources": [],
|
||||
},
|
||||
]
|
||||
@ -238,13 +247,16 @@ class MemoStore:
|
||||
for i, m in enumerate(SEED_MEMOS):
|
||||
mid = f"mseed{i+1}"
|
||||
tags = extract_tags(m["content"])
|
||||
vis = str(m.get("visibility") or "trial")
|
||||
if vis not in {"trial", "public", "free", "vip"}:
|
||||
vis = "trial"
|
||||
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,?,?)
|
||||
) VALUES (?,?,?,?,?,?,?,?,?,?,'active',0,0,0,?,?)
|
||||
""",
|
||||
(
|
||||
mid,
|
||||
@ -254,6 +266,7 @@ class MemoStore:
|
||||
m["content"],
|
||||
json.dumps(m.get("resources") or [], ensure_ascii=False),
|
||||
json.dumps(tags, ensure_ascii=False),
|
||||
vis,
|
||||
m["pinned"],
|
||||
m.get("featured") or 0,
|
||||
now - (len(SEED_MEMOS) - i) * 120,
|
||||
@ -261,6 +274,11 @@ class MemoStore:
|
||||
),
|
||||
)
|
||||
else:
|
||||
# 系统欢迎帖默认开放试读(已有库一次性抬升)
|
||||
c.execute(
|
||||
"UPDATE memos SET visibility='trial' "
|
||||
"WHERE id IN ('mseed1','mseed2') AND IFNULL(visibility,'vip')='vip'"
|
||||
)
|
||||
rows = c.execute(
|
||||
"SELECT id, content, tags_json FROM memos WHERE IFNULL(tags_json,'') IN ('','[]')"
|
||||
).fetchall()
|
||||
@ -286,11 +304,31 @@ class MemoStore:
|
||||
pass
|
||||
return base
|
||||
|
||||
def content_revision(self) -> int:
|
||||
s = self.get_settings()
|
||||
try:
|
||||
return int(s.get("_contentRevision") or 0)
|
||||
except Exception:
|
||||
return 0
|
||||
|
||||
def bump_content_revision(self) -> int:
|
||||
"""后台隐藏/发帖/改配置后递增,前端轮询此值做近实时同步。"""
|
||||
cur = self.get_settings()
|
||||
rev = int(time.time() * 1000)
|
||||
cur["_contentRevision"] = rev
|
||||
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 rev
|
||||
|
||||
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
|
||||
cur["_contentRevision"] = int(time.time() * 1000)
|
||||
with self.conn() as c:
|
||||
c.execute(
|
||||
"UPDATE memo_settings SET json=?, updated_at=? WHERE id=1",
|
||||
@ -322,6 +360,8 @@ class MemoStore:
|
||||
if isinstance(r, dict) and str(r.get("type") or "image") == "image" and r.get("url"):
|
||||
cover = str(r["url"])
|
||||
break
|
||||
visibility = (row["visibility"] if "visibility" in keys else None) or "vip"
|
||||
is_trial = visibility in {"trial", "public", "free"}
|
||||
item = {
|
||||
"id": row["id"],
|
||||
"openid": row["openid"],
|
||||
@ -332,7 +372,9 @@ class MemoStore:
|
||||
"resources": resources,
|
||||
"cover": cover,
|
||||
"tags": tags,
|
||||
"visibility": (row["visibility"] if "visibility" in keys else None) or "vip",
|
||||
"visibility": visibility,
|
||||
"trial": is_trial,
|
||||
"locked": False,
|
||||
"pinned": bool(row["pinned"]),
|
||||
"featured": bool(row["featured"] if "featured" in keys else 0),
|
||||
"status": row["status"],
|
||||
@ -352,6 +394,23 @@ class MemoStore:
|
||||
item["favorited"] = self.has_favorited(row["id"], openid)
|
||||
return item
|
||||
|
||||
@staticmethod
|
||||
def apply_access(memo: dict[str, Any], *, is_vip: bool) -> dict[str, Any]:
|
||||
"""未付费:试读贴全文;非试读仅摘要 + locked。"""
|
||||
out = dict(memo)
|
||||
is_trial = bool(out.get("trial")) or str(out.get("visibility") or "") in {
|
||||
"trial",
|
||||
"public",
|
||||
"free",
|
||||
}
|
||||
out["trial"] = is_trial
|
||||
locked = not is_vip and not is_trial
|
||||
out["locked"] = locked
|
||||
if locked:
|
||||
out["content"] = ""
|
||||
out["resources"] = []
|
||||
return out
|
||||
|
||||
def has_liked(self, memo_id: str, openid: str) -> bool:
|
||||
with self.conn() as c:
|
||||
return bool(
|
||||
@ -381,6 +440,9 @@ class MemoStore:
|
||||
tag: str = "",
|
||||
featured: bool | None = None,
|
||||
favorited_by: str = "",
|
||||
visibility: str = "",
|
||||
# 未付费搜索不扫会员帖正文,避免关键词泄露
|
||||
safe_search: bool = False,
|
||||
) -> list[dict[str, Any]]:
|
||||
with self.conn() as c:
|
||||
clauses: list[str] = []
|
||||
@ -388,14 +450,28 @@ class MemoStore:
|
||||
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 safe_search:
|
||||
clauses.append(
|
||||
"("
|
||||
"title LIKE ? OR tags_json LIKE ? OR "
|
||||
"(IFNULL(visibility,'vip') IN ('trial','public','free') AND content LIKE ?)"
|
||||
")"
|
||||
)
|
||||
params.extend([like, like, like])
|
||||
else:
|
||||
clauses.append("(title LIKE ? OR content LIKE ? OR tags_json LIKE ?)")
|
||||
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")
|
||||
vis = (visibility or "").strip().lower()
|
||||
if vis == "trial":
|
||||
clauses.append("IFNULL(visibility,'vip') IN ('trial','public','free')")
|
||||
elif vis == "vip":
|
||||
clauses.append("IFNULL(visibility,'vip') NOT IN ('trial','public','free')")
|
||||
if favorited_by:
|
||||
clauses.append(
|
||||
"id IN (SELECT memo_id FROM memo_favorites WHERE openid=?)"
|
||||
@ -444,6 +520,7 @@ class MemoStore:
|
||||
title: str = "",
|
||||
pinned: bool = False,
|
||||
featured: bool = False,
|
||||
visibility: str = "vip",
|
||||
resources: list[dict[str, Any]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
content = (content or "").strip()
|
||||
@ -467,6 +544,9 @@ class MemoStore:
|
||||
)
|
||||
tags = extract_tags(content)
|
||||
title_f = extract_title(content, title)
|
||||
vis = (visibility or "vip").strip().lower()
|
||||
if vis not in {"vip", "trial", "public", "free"}:
|
||||
vis = "vip"
|
||||
mid = f"m{uuid.uuid4().hex[:16]}"
|
||||
now = time.time()
|
||||
with self.conn() as c:
|
||||
@ -476,7 +556,7 @@ class MemoStore:
|
||||
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,?,?)
|
||||
) VALUES (?,?,?,?,?,?,?,?,?,?,'active',0,0,0,?,?)
|
||||
""",
|
||||
(
|
||||
mid,
|
||||
@ -486,13 +566,16 @@ class MemoStore:
|
||||
content,
|
||||
json.dumps(clean_res, ensure_ascii=False),
|
||||
json.dumps(tags, ensure_ascii=False),
|
||||
vis,
|
||||
1 if pinned else 0,
|
||||
1 if featured else 0,
|
||||
now,
|
||||
now,
|
||||
),
|
||||
)
|
||||
return self.get_memo(mid, openid=openid) # type: ignore
|
||||
memo = self.get_memo(mid, openid=openid) # type: ignore
|
||||
self.bump_content_revision()
|
||||
return memo
|
||||
|
||||
def delete_memo(self, memo_id: str, *, openid: str = "", admin: bool = False) -> bool:
|
||||
memo = self.get_memo(memo_id, openid=openid, admin=True)
|
||||
@ -505,6 +588,7 @@ class MemoStore:
|
||||
"UPDATE memos SET status='deleted', updated_at=? WHERE id=?",
|
||||
(time.time(), memo_id),
|
||||
)
|
||||
self.bump_content_revision()
|
||||
return True
|
||||
|
||||
def hide_memo(self, memo_id: str) -> dict[str, Any] | None:
|
||||
@ -513,6 +597,22 @@ class MemoStore:
|
||||
"UPDATE memos SET status='hidden', updated_at=? WHERE id=?",
|
||||
(time.time(), memo_id),
|
||||
)
|
||||
self.bump_content_revision()
|
||||
return self.get_memo(memo_id, admin=True)
|
||||
|
||||
def unhide_memo(self, memo_id: str) -> dict[str, Any] | None:
|
||||
"""已隐藏 → 恢复公开显示(已删除不可恢复)。"""
|
||||
memo = self.get_memo(memo_id, admin=True)
|
||||
if not memo:
|
||||
return None
|
||||
if str(memo.get("status") or "") == "deleted":
|
||||
raise ValueError("已删除的帖子不能恢复,请重新发布")
|
||||
with self.conn() as c:
|
||||
c.execute(
|
||||
"UPDATE memos SET status='active', updated_at=? WHERE id=?",
|
||||
(time.time(), memo_id),
|
||||
)
|
||||
self.bump_content_revision()
|
||||
return self.get_memo(memo_id, admin=True)
|
||||
|
||||
def set_pin(self, memo_id: str, pinned: bool) -> dict[str, Any] | None:
|
||||
@ -521,6 +621,7 @@ class MemoStore:
|
||||
"UPDATE memos SET pinned=?, updated_at=? WHERE id=?",
|
||||
(1 if pinned else 0, time.time(), memo_id),
|
||||
)
|
||||
self.bump_content_revision()
|
||||
return self.get_memo(memo_id, admin=True)
|
||||
|
||||
def set_featured(self, memo_id: str, featured: bool) -> dict[str, Any] | None:
|
||||
@ -529,6 +630,21 @@ class MemoStore:
|
||||
"UPDATE memos SET featured=?, updated_at=? WHERE id=?",
|
||||
(1 if featured else 0, time.time(), memo_id),
|
||||
)
|
||||
self.bump_content_revision()
|
||||
return self.get_memo(memo_id, admin=True)
|
||||
|
||||
def set_visibility(self, memo_id: str, visibility: str) -> dict[str, Any] | None:
|
||||
vis = (visibility or "vip").strip().lower()
|
||||
if vis not in {"vip", "trial", "public", "free"}:
|
||||
raise ValueError("visibility 仅支持 vip / trial")
|
||||
if vis in {"public", "free"}:
|
||||
vis = "trial"
|
||||
with self.conn() as c:
|
||||
c.execute(
|
||||
"UPDATE memos SET visibility=?, updated_at=? WHERE id=?",
|
||||
(vis, time.time(), memo_id),
|
||||
)
|
||||
self.bump_content_revision()
|
||||
return self.get_memo(memo_id, admin=True)
|
||||
|
||||
def toggle_like(self, memo_id: str, openid: str) -> dict[str, Any]:
|
||||
@ -683,6 +799,10 @@ class MemoStore:
|
||||
memos = c.execute(
|
||||
"SELECT COUNT(*) AS n FROM memos WHERE status='active'"
|
||||
).fetchone()["n"]
|
||||
trial = c.execute(
|
||||
"SELECT COUNT(*) AS n FROM memos WHERE status='active' "
|
||||
"AND IFNULL(visibility,'vip') IN ('trial','public','free')"
|
||||
).fetchone()["n"]
|
||||
comments = c.execute(
|
||||
"SELECT COUNT(*) AS n FROM memo_comments WHERE status='active'"
|
||||
).fetchone()["n"]
|
||||
@ -693,6 +813,7 @@ class MemoStore:
|
||||
).fetchone()["n"]
|
||||
return {
|
||||
"memos": memos,
|
||||
"trial": trial,
|
||||
"comments": comments,
|
||||
"likes": likes,
|
||||
"favorites": favorites,
|
||||
|
||||
@ -98,6 +98,7 @@ class Store:
|
||||
("notes", "ALTER TABLE users ADD COLUMN notes TEXT"),
|
||||
("pb_record_id", "ALTER TABLE users ADD COLUMN pb_record_id TEXT"),
|
||||
("created_at", "ALTER TABLE users ADD COLUMN created_at REAL"),
|
||||
("last_seen_at", "ALTER TABLE users ADD COLUMN last_seen_at REAL"),
|
||||
]
|
||||
for name, sql in alters:
|
||||
if name not in cols:
|
||||
@ -238,7 +239,20 @@ class Store:
|
||||
return [self._book_row(r) for r in rows]
|
||||
|
||||
def _book_row(self, row: sqlite3.Row) -> dict[str, Any]:
|
||||
chapters = json.loads(row["chapters_json"] or "[]")
|
||||
raw_chapters = json.loads(row["chapters_json"] or "[]")
|
||||
chapters: list[dict[str, Any]] = []
|
||||
for i, ch in enumerate(raw_chapters if isinstance(raw_chapters, list) else []):
|
||||
if not isinstance(ch, dict):
|
||||
continue
|
||||
chapters.append(
|
||||
{
|
||||
**ch,
|
||||
"id": str(ch.get("id") or f"ch-{i + 1}"),
|
||||
"title": str(ch.get("title") or f"章节 {i + 1}"),
|
||||
"order": int(ch["order"]) if ch.get("order") is not None else i + 1,
|
||||
"content": str(ch.get("content") or ""),
|
||||
}
|
||||
)
|
||||
tags = json.loads(row["tags"] or "[]")
|
||||
word_count = sum(len(ch.get("content") or "") for ch in chapters)
|
||||
return {
|
||||
@ -259,6 +273,60 @@ class Store:
|
||||
"updated_at": row["updated_at"],
|
||||
}
|
||||
|
||||
def ensure_book(
|
||||
self,
|
||||
book_id: str,
|
||||
*,
|
||||
title: str = "审核用小册",
|
||||
subtitle: str = "审核模式展示内容",
|
||||
free: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""若不存在则创建(审核模式备用书);已存在则原样返回。"""
|
||||
bid = (book_id or "").strip()[:64]
|
||||
if not bid:
|
||||
raise ValueError("book_id required")
|
||||
existing = self.get_book(bid)
|
||||
if existing:
|
||||
return existing
|
||||
now = time.time()
|
||||
chapters = [
|
||||
{
|
||||
"id": "01-audit",
|
||||
"title": "写在前面",
|
||||
"order": 1,
|
||||
"content": (
|
||||
"# 写在前面\n\n"
|
||||
"欢迎阅读《数字游民入门指南》。\n\n"
|
||||
"这是一本面向普通人的远程办公与自律生活入门读本:"
|
||||
"讲时间管理、团队协作、健康作息与职业成长。\n"
|
||||
),
|
||||
}
|
||||
]
|
||||
with self.conn() as c:
|
||||
c.execute(
|
||||
"""
|
||||
INSERT INTO books(id,title,subtitle,author,cover_emoji,description,tags,
|
||||
price_fen,product_id,unlock_percent,rating,chapters_json,updated_at)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)
|
||||
""",
|
||||
(
|
||||
bid,
|
||||
title,
|
||||
subtitle,
|
||||
"",
|
||||
"📗",
|
||||
"微信提审专用,与正式会员书分开存放。",
|
||||
json.dumps(["提审"], ensure_ascii=False),
|
||||
0 if free else settings.default_price_fen,
|
||||
"" if free else settings.default_product_id,
|
||||
100 if free else settings.default_unlock_percent,
|
||||
5.0,
|
||||
json.dumps(chapters, ensure_ascii=False),
|
||||
now,
|
||||
),
|
||||
)
|
||||
return self.get_book(bid) or {"id": bid}
|
||||
|
||||
def update_book(self, book_id: str, patch: dict[str, Any]) -> dict[str, Any]:
|
||||
book = self.get_book(book_id)
|
||||
if not book:
|
||||
@ -289,20 +357,33 @@ class Store:
|
||||
)
|
||||
return self.get_book(book_id) # type: ignore
|
||||
|
||||
# 后台判定「在线」:最近心跳 / 鉴权请求落在此窗口内
|
||||
ONLINE_WINDOW_SEC = 90
|
||||
|
||||
def upsert_user(self, openid: str, session_key: str, token: str, unionid: str | None = None):
|
||||
now = time.time()
|
||||
with self.conn() as c:
|
||||
c.execute(
|
||||
"""
|
||||
INSERT INTO users(openid, session_key, unionid, token, status, created_at, updated_at)
|
||||
VALUES(?,?,?,?, 'active', ?, ?)
|
||||
INSERT INTO users(openid, session_key, unionid, token, status, created_at, updated_at, last_seen_at)
|
||||
VALUES(?,?,?,?, 'active', ?, ?, ?)
|
||||
ON CONFLICT(openid) DO UPDATE SET
|
||||
session_key=excluded.session_key,
|
||||
unionid=COALESCE(excluded.unionid, users.unionid),
|
||||
token=excluded.token,
|
||||
updated_at=excluded.updated_at
|
||||
updated_at=excluded.updated_at,
|
||||
last_seen_at=excluded.last_seen_at
|
||||
""",
|
||||
(openid, session_key, unionid, token, now, now),
|
||||
(openid, session_key, unionid, token, now, now, now),
|
||||
)
|
||||
|
||||
def touch_last_seen(self, openid: str) -> None:
|
||||
if not openid:
|
||||
return
|
||||
with self.conn() as c:
|
||||
c.execute(
|
||||
"UPDATE users SET last_seen_at=? WHERE openid=?",
|
||||
(time.time(), openid),
|
||||
)
|
||||
|
||||
def get_user_by_token(self, token: str) -> dict[str, Any] | None:
|
||||
@ -381,6 +462,7 @@ class Store:
|
||||
"source": u["source"] or "",
|
||||
}
|
||||
)
|
||||
now = time.time()
|
||||
out = []
|
||||
for r in rows:
|
||||
item = dict(r)
|
||||
@ -389,7 +471,18 @@ class Store:
|
||||
item["status"] = item.get("status") or "active"
|
||||
item["unlocks"] = unlock_map.get(item["openid"], [])
|
||||
item["unlocked_default"] = any(x["book_id"] == "default" for x in item["unlocks"])
|
||||
item["unlocked_vip"] = any(x["book_id"] == "__vip__" for x in item["unlocks"])
|
||||
last_seen = float(item.get("last_seen_at") or 0)
|
||||
item["last_seen_at"] = last_seen or None
|
||||
item["online"] = bool(last_seen and (now - last_seen) <= self.ONLINE_WINDOW_SEC)
|
||||
out.append(item)
|
||||
# 在线置顶,其次按最近心跳 / 活跃时间
|
||||
out.sort(
|
||||
key=lambda x: (
|
||||
0 if x.get("online") else 1,
|
||||
-(float(x.get("last_seen_at") or x.get("updated_at") or 0)),
|
||||
)
|
||||
)
|
||||
return out
|
||||
|
||||
def is_unlocked(self, openid: str, book_id: str) -> bool:
|
||||
|
||||
@ -24,7 +24,8 @@ DEFAULT_VIP = {
|
||||
"joinGroupAction": "popup",
|
||||
"vipPriceFen": 29800,
|
||||
"vipProductId": "tiktok",
|
||||
"vipCta": "立即加入 · ¥298",
|
||||
# CTA 不含价格;价格由方案卡片/后台展示
|
||||
"vipCta": "立即加入",
|
||||
"vipOfferKey": "tiktok",
|
||||
}
|
||||
|
||||
@ -44,14 +45,11 @@ def _as_action(v: Any, fallback: JoinAction = "popup") -> JoinAction:
|
||||
return "popup" if v == "popup" else "vip" if v == "vip" else fallback
|
||||
|
||||
|
||||
def vip_cta_text(*, free: bool, price_fen: int) -> str:
|
||||
"""小程序「立即加入」按钮文案(方案驱动,对齐小册 unlock_button_text)。"""
|
||||
def vip_cta_text(*, free: bool, price_fen: int = 0) -> str:
|
||||
"""小程序主按钮文案:不含价格。免费=临时放行,切回收费后仍须付费开通。"""
|
||||
if free or price_fen <= 0:
|
||||
return "免费加入"
|
||||
yuan = price_fen / 100
|
||||
if yuan == int(yuan):
|
||||
return f"立即加入 · ¥{int(yuan)}"
|
||||
return f"立即加入 · ¥{yuan:.2f}"
|
||||
return "立即加入"
|
||||
|
||||
|
||||
def match_vip_offer(
|
||||
@ -145,6 +143,9 @@ def read_vip_config() -> dict[str, Any]:
|
||||
is_free = bool(offer.get("free")) or (price <= 0 and not product_id.strip())
|
||||
|
||||
cta = str(copy.get("vipCta") or "").strip()
|
||||
# 旧配置可能带「· ¥298」;主按钮统一不含价格
|
||||
if "¥" in cta or "¥" in cta:
|
||||
cta = vip_cta_text(free=is_free, price_fen=price)
|
||||
if not cta:
|
||||
cta = vip_cta_text(free=is_free, price_fen=price)
|
||||
|
||||
@ -215,6 +216,19 @@ def write_vip_config(patch: dict[str, Any]) -> dict[str, Any]:
|
||||
if "joinGroupAction" in patch:
|
||||
flags["joinGroupAction"] = _as_action(patch["joinGroupAction"], "popup")
|
||||
|
||||
# 主按钮文案统一不含价格;免费=临时放行文案
|
||||
try:
|
||||
_price = int(copy.get("vipPriceFen") or 0)
|
||||
except Exception:
|
||||
_price = 0
|
||||
_pid = str(copy.get("vipProductId") or "").strip()
|
||||
_free = _price <= 0 and not _pid
|
||||
_cta = str(copy.get("vipCta") or "").strip()
|
||||
if not _cta or "¥" in _cta or "¥" in _cta:
|
||||
copy["vipCta"] = vip_cta_text(free=_free, price_fen=_price)
|
||||
elif _free:
|
||||
copy["vipCta"] = "免费加入"
|
||||
|
||||
out["modules"] = modules
|
||||
out["flags"] = flags
|
||||
out["copy"] = copy
|
||||
|
||||
259
apps/api/services/ebook_svc/services/weapp_switches.py
Normal file
259
apps/api/services/ebook_svc/services/weapp_switches.py
Normal file
@ -0,0 +1,259 @@
|
||||
"""微信小程序「开关」— modules / flags / copy / VIP 区块 / 小册审核模式。
|
||||
|
||||
写入 remote-config.json;不碰 platforms.tt、订单与 PocketBase。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from copy import deepcopy
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from ebook_svc.services.store import store
|
||||
from ebook_svc.services.tt_platform_config import resolve_config_file
|
||||
from ebook_svc.services.vip_content import (
|
||||
apply_vip_content_patch,
|
||||
read_vip_content_from_raw,
|
||||
)
|
||||
|
||||
DEFAULT_BOOK_AUDIT: dict[str, Any] = {
|
||||
"reviewMode": False,
|
||||
"bookId": "audit",
|
||||
}
|
||||
|
||||
MODULE_KEYS = (
|
||||
"home",
|
||||
"nav",
|
||||
"book",
|
||||
"community",
|
||||
"vip",
|
||||
"destinations",
|
||||
"meetups",
|
||||
)
|
||||
|
||||
DEFAULT_MODULES: dict[str, dict[str, Any]] = {
|
||||
"home": {"enabled": True, "title": "首页", "tabLabel": "首页"},
|
||||
"nav": {"enabled": True, "title": "出海导航", "tabLabel": "导航"},
|
||||
"book": {"enabled": True, "title": "数字游民小册", "tabLabel": "小册"},
|
||||
"community": {"enabled": True, "title": "旅居社群", "tabLabel": "社群"},
|
||||
"vip": {"enabled": False, "title": "会员中心"},
|
||||
"destinations": {"enabled": True, "title": "目的地"},
|
||||
"meetups": {"enabled": True, "title": "活动"},
|
||||
"game": {"enabled": False, "title": "数字游民", "note": "冻结隐藏 · 勿开入口"},
|
||||
}
|
||||
|
||||
VIP_ENTRY_BOOLS = (
|
||||
"showStats",
|
||||
"showTopics",
|
||||
"showVideos",
|
||||
"showEbooks",
|
||||
"showCompare",
|
||||
"showFaq",
|
||||
"showCta",
|
||||
"reviewMode",
|
||||
)
|
||||
|
||||
|
||||
def _read_raw() -> dict[str, Any]:
|
||||
path = resolve_config_file()
|
||||
if not path.is_file():
|
||||
return {}
|
||||
try:
|
||||
raw = json.loads(path.read_text(encoding="utf-8"))
|
||||
return raw if isinstance(raw, dict) else {}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def _write_raw(out: dict[str, Any]) -> None:
|
||||
path = resolve_config_file()
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
out["updatedAt"] = datetime.now(timezone.utc).isoformat()
|
||||
try:
|
||||
out["version"] = int(out.get("version") or 1) + 1
|
||||
except Exception:
|
||||
out["version"] = 2
|
||||
if path.is_file():
|
||||
bak = path.with_suffix(path.suffix + f".bak-{out['updatedAt'].replace(':', '-')}")
|
||||
try:
|
||||
bak.write_text(path.read_text(encoding="utf-8"), encoding="utf-8")
|
||||
except Exception:
|
||||
pass
|
||||
path.write_text(json.dumps(out, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
def _norm_mod(raw: Any, fallback: dict[str, Any]) -> dict[str, Any]:
|
||||
m = raw if isinstance(raw, dict) else {}
|
||||
out = deepcopy(fallback)
|
||||
if "enabled" in m:
|
||||
out["enabled"] = bool(m["enabled"])
|
||||
if m.get("title"):
|
||||
out["title"] = str(m["title"]).strip() or out["title"]
|
||||
if "tabLabel" in m and m["tabLabel"] is not None:
|
||||
out["tabLabel"] = str(m["tabLabel"]).strip()
|
||||
if "note" in m and m["note"] is not None:
|
||||
out["note"] = str(m["note"]).strip()
|
||||
return out
|
||||
|
||||
|
||||
def read_book_audit(raw: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
data = raw if raw is not None else _read_raw()
|
||||
platforms = data.get("platforms") if isinstance(data.get("platforms"), dict) else {}
|
||||
weapp = platforms.get("weapp") if isinstance(platforms.get("weapp"), dict) else {}
|
||||
ba = weapp.get("bookAudit") if isinstance(weapp.get("bookAudit"), dict) else {}
|
||||
book_id = str(ba.get("bookId") or DEFAULT_BOOK_AUDIT["bookId"]).strip() or "audit"
|
||||
return {
|
||||
"reviewMode": bool(ba.get("reviewMode")),
|
||||
"bookId": book_id,
|
||||
}
|
||||
|
||||
|
||||
def read_weapp_switches() -> dict[str, Any]:
|
||||
raw = _read_raw()
|
||||
modules_raw = raw.get("modules") if isinstance(raw.get("modules"), dict) else {}
|
||||
flags_raw = raw.get("flags") if isinstance(raw.get("flags"), dict) else {}
|
||||
copy_raw = raw.get("copy") if isinstance(raw.get("copy"), dict) else {}
|
||||
|
||||
modules: dict[str, Any] = {}
|
||||
for key in MODULE_KEYS:
|
||||
modules[key] = _norm_mod(modules_raw.get(key), DEFAULT_MODULES[key])
|
||||
# game 只读展示(强制关)
|
||||
modules["game"] = {
|
||||
**DEFAULT_MODULES["game"],
|
||||
"enabled": False,
|
||||
}
|
||||
|
||||
vip_content = read_vip_content_from_raw(raw)
|
||||
vip_entries = {k: bool(vip_content.get(k)) for k in VIP_ENTRY_BOOLS}
|
||||
|
||||
return {
|
||||
"ok": True,
|
||||
"modules": modules,
|
||||
"flags": {
|
||||
"payEnabled": flags_raw.get("payEnabled", True) is not False,
|
||||
"socialFollow": flags_raw.get("socialFollow", True) is not False,
|
||||
"offlineBadge": bool(flags_raw.get("offlineBadge")),
|
||||
"joinGroupAction": (
|
||||
"vip" if flags_raw.get("joinGroupAction") == "vip" else "popup"
|
||||
),
|
||||
"memoTrialBrowse": flags_raw.get("memoTrialBrowse", True) is not False,
|
||||
"joinGroupWechat": flags_raw.get("joinGroupWechat", True) is not False,
|
||||
},
|
||||
"copy": {
|
||||
"homeBrand": str(copy_raw.get("homeBrand") or "nomadro"),
|
||||
"homeTagline": str(copy_raw.get("homeTagline") or ""),
|
||||
"homeLead": str(copy_raw.get("homeLead") or ""),
|
||||
"vipCta": str(copy_raw.get("vipCta") or "立即加入"),
|
||||
"wechatOaName": str(copy_raw.get("wechatOaName") or "异度世界"),
|
||||
"memoUnlockCta": str(copy_raw.get("memoUnlockCta") or "解锁 VIP 读全文"),
|
||||
},
|
||||
"vipEntries": vip_entries,
|
||||
"vipHero": {
|
||||
"heroEyebrow": str(vip_content.get("heroEyebrow") or ""),
|
||||
"heroTitleAccent": str(vip_content.get("heroTitleAccent") or ""),
|
||||
"heroTitleRest": str(vip_content.get("heroTitleRest") or ""),
|
||||
"heroLead": str(vip_content.get("heroLead") or ""),
|
||||
},
|
||||
"bookAudit": read_book_audit(raw),
|
||||
"version": raw.get("version"),
|
||||
"updatedAt": raw.get("updatedAt"),
|
||||
"configPath": str(resolve_config_file()),
|
||||
}
|
||||
|
||||
|
||||
def write_weapp_switches(patch: dict[str, Any]) -> dict[str, Any]:
|
||||
raw = _read_raw()
|
||||
out: dict[str, Any] = (
|
||||
dict(raw) if raw else {"version": 2, "modules": {}, "flags": {}, "copy": {}}
|
||||
)
|
||||
modules = dict(out.get("modules") or {})
|
||||
flags = dict(out.get("flags") or {})
|
||||
copy = dict(out.get("copy") or {})
|
||||
|
||||
if isinstance(patch.get("modules"), dict):
|
||||
for key, val in patch["modules"].items():
|
||||
if key == "game":
|
||||
modules["game"] = {**DEFAULT_MODULES["game"], "enabled": False}
|
||||
continue
|
||||
if key not in MODULE_KEYS:
|
||||
continue
|
||||
if not isinstance(val, dict):
|
||||
continue
|
||||
base = _norm_mod(modules.get(key), DEFAULT_MODULES[key])
|
||||
modules[key] = _norm_mod(val, base)
|
||||
|
||||
if isinstance(patch.get("flags"), dict):
|
||||
fp = patch["flags"]
|
||||
if "payEnabled" in fp:
|
||||
flags["payEnabled"] = bool(fp["payEnabled"])
|
||||
if "socialFollow" in fp:
|
||||
flags["socialFollow"] = bool(fp["socialFollow"])
|
||||
if "offlineBadge" in fp:
|
||||
flags["offlineBadge"] = bool(fp["offlineBadge"])
|
||||
if "memoTrialBrowse" in fp:
|
||||
flags["memoTrialBrowse"] = bool(fp["memoTrialBrowse"])
|
||||
if "joinGroupWechat" in fp:
|
||||
flags["joinGroupWechat"] = bool(fp["joinGroupWechat"])
|
||||
if "joinGroupAction" in fp:
|
||||
flags["joinGroupAction"] = (
|
||||
"vip" if fp["joinGroupAction"] == "vip" else "popup"
|
||||
)
|
||||
|
||||
if isinstance(patch.get("copy"), dict):
|
||||
cp = patch["copy"]
|
||||
for k in (
|
||||
"homeBrand",
|
||||
"homeTagline",
|
||||
"homeLead",
|
||||
"vipCta",
|
||||
"wechatOaName",
|
||||
"memoUnlockCta",
|
||||
):
|
||||
if k in cp and cp[k] is not None:
|
||||
copy[k] = str(cp[k]).strip()
|
||||
|
||||
out["modules"] = modules
|
||||
out["flags"] = flags
|
||||
out["copy"] = copy
|
||||
|
||||
# VIP 入口区块 + hero 文案 → platforms.weapp.vipContent
|
||||
vip_patch: dict[str, Any] = {}
|
||||
if isinstance(patch.get("vipEntries"), dict):
|
||||
for k in VIP_ENTRY_BOOLS:
|
||||
if k in patch["vipEntries"]:
|
||||
vip_patch[k] = bool(patch["vipEntries"][k])
|
||||
if isinstance(patch.get("vipHero"), dict):
|
||||
for k in ("heroEyebrow", "heroTitleAccent", "heroTitleRest", "heroLead"):
|
||||
if k in patch["vipHero"] and patch["vipHero"][k] is not None:
|
||||
vip_patch[k] = str(patch["vipHero"][k]).strip()
|
||||
if vip_patch:
|
||||
out = apply_vip_content_patch(out, vip_patch)
|
||||
|
||||
# 小册审核模式 → platforms.weapp.bookAudit(不碰 tt)
|
||||
if isinstance(patch.get("bookAudit"), dict):
|
||||
platforms = dict(out.get("platforms") or {})
|
||||
weapp = dict(platforms.get("weapp") or {})
|
||||
prev = weapp.get("bookAudit") if isinstance(weapp.get("bookAudit"), dict) else {}
|
||||
ba = {**DEFAULT_BOOK_AUDIT, **prev}
|
||||
bp = patch["bookAudit"]
|
||||
if "reviewMode" in bp:
|
||||
ba["reviewMode"] = bool(bp["reviewMode"])
|
||||
if "bookId" in bp and bp["bookId"] is not None:
|
||||
bid = str(bp["bookId"]).strip() or "audit"
|
||||
ba["bookId"] = bid[:64]
|
||||
weapp["bookAudit"] = ba
|
||||
platforms["weapp"] = weapp
|
||||
out["platforms"] = platforms
|
||||
# 确保审核书存在(免费全文,与 default 隔离)
|
||||
try:
|
||||
store.ensure_book(
|
||||
str(ba["bookId"]),
|
||||
title="数字游民·提审版",
|
||||
subtitle="仅给微信审核员看 · 与正式会员书无关",
|
||||
free=True,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
_write_raw(out)
|
||||
return read_weapp_switches()
|
||||
@ -45,7 +45,107 @@ const isH5 =
|
||||
process.env.TARO_ENV === 'h5' || process.env.TARO_APP_TARGET === 'h5'
|
||||
const wantTabBar = !isH5 && process.env.TARO_APP_TABBAR === '1'
|
||||
|
||||
export default defineAppConfig({
|
||||
/** 微信主包必须 ≤1.5MB:首页/我的留主包,其余进分包 */
|
||||
const weappConfig = {
|
||||
pages: ['pages/index/index', 'pages/mine/index'],
|
||||
subPackages: [
|
||||
{
|
||||
root: 'pages/nav',
|
||||
name: 'nav',
|
||||
pages: ['index'],
|
||||
},
|
||||
{
|
||||
root: 'pages/book',
|
||||
name: 'book',
|
||||
pages: ['index'],
|
||||
},
|
||||
{
|
||||
root: 'pages/reader',
|
||||
name: 'reader',
|
||||
pages: ['index'],
|
||||
},
|
||||
{
|
||||
root: 'pages/community',
|
||||
name: 'community',
|
||||
pages: ['index'],
|
||||
},
|
||||
{
|
||||
root: 'pages/destinations',
|
||||
name: 'destinations',
|
||||
pages: ['index'],
|
||||
},
|
||||
{
|
||||
root: 'pages/destination',
|
||||
name: 'destination',
|
||||
pages: ['index'],
|
||||
},
|
||||
{
|
||||
root: 'pages/meetups',
|
||||
name: 'meetups',
|
||||
pages: ['index'],
|
||||
},
|
||||
{
|
||||
root: 'pages/vip',
|
||||
name: 'vip',
|
||||
pages: ['index'],
|
||||
},
|
||||
{
|
||||
root: 'pages/vip-course',
|
||||
name: 'vip-course',
|
||||
pages: ['index'],
|
||||
},
|
||||
{
|
||||
root: 'pages/vip-lesson',
|
||||
name: 'vip-lesson',
|
||||
pages: ['index'],
|
||||
},
|
||||
{
|
||||
root: 'pages/vip-ebook',
|
||||
name: 'vip-ebook',
|
||||
pages: ['index'],
|
||||
},
|
||||
{
|
||||
root: 'pages/vip-store',
|
||||
name: 'vip-store',
|
||||
pages: ['index'],
|
||||
},
|
||||
{
|
||||
root: 'pages/vip-store-detail',
|
||||
name: 'vip-store-detail',
|
||||
pages: ['index'],
|
||||
},
|
||||
{
|
||||
root: 'pages/vip-store-orders',
|
||||
name: 'vip-store-orders',
|
||||
pages: ['index'],
|
||||
},
|
||||
{
|
||||
root: 'pages/vip-memo',
|
||||
name: 'vip-memo',
|
||||
pages: ['index'],
|
||||
},
|
||||
{
|
||||
root: 'pages/vip-memo-detail',
|
||||
name: 'vip-memo-detail',
|
||||
pages: ['index'],
|
||||
},
|
||||
{
|
||||
root: 'pages/game',
|
||||
name: 'game',
|
||||
pages: ['index'],
|
||||
},
|
||||
],
|
||||
preloadRule: {
|
||||
'pages/index/index': {
|
||||
network: 'all',
|
||||
packages: ['book', 'nav'],
|
||||
},
|
||||
},
|
||||
/** 组件按需注入:代码质量扫描必过项 */
|
||||
lazyCodeLoading: 'requiredComponents' as const,
|
||||
}
|
||||
|
||||
const h5Config = {
|
||||
pages: [
|
||||
'pages/index/index',
|
||||
'pages/nav/index',
|
||||
@ -67,6 +167,10 @@ export default defineAppConfig({
|
||||
'pages/vip-memo-detail/index',
|
||||
'pages/game/index',
|
||||
],
|
||||
}
|
||||
|
||||
export default defineAppConfig({
|
||||
...(isH5 ? h5Config : weappConfig),
|
||||
window: {
|
||||
backgroundTextStyle: 'light',
|
||||
navigationBarBackgroundColor: '#0c0c0f',
|
||||
@ -74,10 +178,5 @@ export default defineAppConfig({
|
||||
navigationBarTextStyle: 'white',
|
||||
backgroundColor: '#0c0c0f',
|
||||
},
|
||||
permission: {
|
||||
'scope.address': {
|
||||
desc: '用于实体商品发货填写收货地址',
|
||||
},
|
||||
},
|
||||
...(wantTabBar ? { tabBar } : {}),
|
||||
})
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { useEffect } from 'react'
|
||||
import { Fragment, useEffect } from 'react'
|
||||
import type { PropsWithChildren } from 'react'
|
||||
import { useDidHide, useDidShow, useLaunch } from '@tarojs/taro'
|
||||
import { flush, trackAppLaunch } from './utils/track'
|
||||
@ -9,6 +9,9 @@ import {
|
||||
} from './services/remoteConfig'
|
||||
import { startH5RemLock } from './utils/h5RemLock'
|
||||
import { applyH5Theme, getStoredH5Theme } from './utils/h5Theme'
|
||||
import { startPresenceHeartbeat } from './utils/presence'
|
||||
import { startVipAccessLiveSync } from './utils/vipAccess'
|
||||
import DebugFab from './components/DebugFab'
|
||||
import './styles/theme'
|
||||
import './styles/ebook.scss'
|
||||
import './app.scss'
|
||||
@ -18,6 +21,7 @@ function App({ children }: PropsWithChildren) {
|
||||
trackAppLaunch()
|
||||
void loadRemoteConfig(true)
|
||||
startRemoteConfigLiveSync()
|
||||
startVipAccessLiveSync()
|
||||
if (process.env.TARO_ENV === 'h5') {
|
||||
applyH5Theme(getStoredH5Theme())
|
||||
}
|
||||
@ -34,16 +38,26 @@ function App({ children }: PropsWithChildren) {
|
||||
useEffect(() => {
|
||||
const stopRem = startH5RemLock()
|
||||
const stopLive = startRemoteConfigLiveSync()
|
||||
const stopPresence = startPresenceHeartbeat()
|
||||
const stopVip = startVipAccessLiveSync()
|
||||
if (process.env.TARO_ENV === 'h5') {
|
||||
applyH5Theme(getStoredH5Theme())
|
||||
}
|
||||
return () => {
|
||||
stopRem()
|
||||
stopLive()
|
||||
stopPresence()
|
||||
stopVip()
|
||||
}
|
||||
}, [])
|
||||
|
||||
return children
|
||||
// DebugFab 内部按 envVersion/NODE_ENV 自判;正式版 release 不渲染
|
||||
return (
|
||||
<Fragment>
|
||||
{children}
|
||||
<DebugFab />
|
||||
</Fragment>
|
||||
)
|
||||
}
|
||||
|
||||
export default App
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { usePageScroll } from '@tarojs/taro'
|
||||
import { H5Box, H5Txt } from './H5Box'
|
||||
import {
|
||||
@ -7,7 +7,7 @@ import {
|
||||
type H5Theme,
|
||||
} from '../utils/h5Theme'
|
||||
import { goPage } from '../utils/nav'
|
||||
import { getSafeAreaMetrics } from '../utils/safeArea'
|
||||
import { safePx, useSafeAreaMetrics } from '../utils/safeArea'
|
||||
|
||||
const LOGO_SVG = `<svg class="logo-icon" viewBox="0 0 40 40" fill="none" aria-hidden="true">
|
||||
<circle cx="20" cy="20" r="18" stroke="#f06664" stroke-width="2.5"/>
|
||||
@ -24,7 +24,7 @@ const isH5 = process.env.TARO_ENV === 'h5'
|
||||
export function CommunityNavbar() {
|
||||
const [theme, setTheme] = useState<H5Theme>(() => getStoredH5Theme())
|
||||
const [scrolled, setScrolled] = useState(false)
|
||||
const safe = useMemo(() => getSafeAreaMetrics(), [])
|
||||
const safe = useSafeAreaMetrics()
|
||||
|
||||
useEffect(() => {
|
||||
setTheme(getStoredH5Theme())
|
||||
@ -55,7 +55,7 @@ export function CommunityNavbar() {
|
||||
style={
|
||||
!isH5
|
||||
? {
|
||||
paddingTop: safe.statusBarHeight,
|
||||
paddingTop: safePx(safe.statusBarHeight),
|
||||
height: 'auto',
|
||||
}
|
||||
: undefined
|
||||
@ -66,8 +66,8 @@ export function CommunityNavbar() {
|
||||
style={
|
||||
!isH5
|
||||
? {
|
||||
height: safe.navBarHeight,
|
||||
paddingRight: safe.menuRightPad,
|
||||
height: safePx(safe.navBarHeight),
|
||||
paddingRight: safePx(safe.menuRightPad),
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
|
||||
109
apps/miniprogram/h5/src/components/DebugFab.scss
Normal file
109
apps/miniprogram/h5/src/components/DebugFab.scss
Normal file
@ -0,0 +1,109 @@
|
||||
/* 真实 px:仅 development 挂载;weapp pxExclude */
|
||||
.dbg-fab-root {
|
||||
position: fixed;
|
||||
right: 12px;
|
||||
bottom: calc(88px + env(safe-area-inset-bottom));
|
||||
z-index: 100000;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.dbg-fab-ball {
|
||||
pointer-events: auto;
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
border-radius: 50%;
|
||||
background: linear-gradient(145deg, #fbbf24, #f59e0b);
|
||||
color: #0c0c0f;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
box-shadow: 0 6px 20px rgba(245, 158, 11, 0.45);
|
||||
border: 2px solid rgba(255, 255, 255, 0.25);
|
||||
}
|
||||
|
||||
.dbg-fab-ball-txt {
|
||||
font-size: 12px;
|
||||
font-weight: 800;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.dbg-fab-panel {
|
||||
pointer-events: auto;
|
||||
position: absolute;
|
||||
right: 0;
|
||||
bottom: 56px;
|
||||
width: 220px;
|
||||
max-height: 70vh;
|
||||
overflow-y: auto;
|
||||
padding: 12px;
|
||||
border-radius: 14px;
|
||||
background: rgba(18, 18, 24, 0.96);
|
||||
border: 1px solid rgba(245, 158, 11, 0.35);
|
||||
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.55);
|
||||
backdrop-filter: blur(12px);
|
||||
}
|
||||
|
||||
.dbg-fab-title {
|
||||
display: block;
|
||||
font-size: 13px;
|
||||
font-weight: 800;
|
||||
color: #fbbf24;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.dbg-fab-hint {
|
||||
display: block;
|
||||
font-size: 10px;
|
||||
color: #64748b;
|
||||
margin-bottom: 10px;
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
.dbg-fab-label {
|
||||
display: block;
|
||||
font-size: 11px;
|
||||
color: #94a3b8;
|
||||
margin: 8px 0 6px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.dbg-fab-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.dbg-fab-chip {
|
||||
min-height: 32px;
|
||||
padding: 0 10px;
|
||||
border-radius: 8px;
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.dbg-fab-chip.on {
|
||||
background: rgba(245, 158, 11, 0.22);
|
||||
border-color: rgba(245, 158, 11, 0.55);
|
||||
}
|
||||
|
||||
.dbg-fab-chip-txt {
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
color: #e2e8f0;
|
||||
}
|
||||
|
||||
.dbg-fab-chip.on .dbg-fab-chip-txt {
|
||||
color: #fbbf24;
|
||||
}
|
||||
|
||||
.dbg-fab-status {
|
||||
display: block;
|
||||
margin-top: 10px;
|
||||
font-size: 11px;
|
||||
color: #94a3b8;
|
||||
line-height: 1.4;
|
||||
}
|
||||
161
apps/miniprogram/h5/src/components/DebugFab.tsx
Normal file
161
apps/miniprogram/h5/src/components/DebugFab.tsx
Normal file
@ -0,0 +1,161 @@
|
||||
/**
|
||||
* 本地调试悬浮球
|
||||
* 显示:dev 构建 / 微信开发版(develop) / H5 localhost
|
||||
* 隐藏:正式版 release(及体验版 trial)
|
||||
*/
|
||||
import { useEffect, useState } from 'react'
|
||||
import { View, Text } from '@tarojs/components'
|
||||
import Taro from '@tarojs/taro'
|
||||
import {
|
||||
DEBUG_FAB_VISIBLE,
|
||||
clearDevCaches,
|
||||
getDevVipOverride,
|
||||
isDevDebugEnabled,
|
||||
setDevVipOverride,
|
||||
type DevVipOverride,
|
||||
} from '@/utils/devDebug'
|
||||
import { clearVipPaidLocal, isVipPaidLocal, resolveVipAccess } from '@/utils/vipAccess'
|
||||
import { loadRemoteConfig } from '@/services/remoteConfig'
|
||||
import { goPage } from '@/utils/nav'
|
||||
import './DebugFab.scss'
|
||||
|
||||
function vipLabel(ov: DevVipOverride): string {
|
||||
if (ov === true) return '强制 VIP'
|
||||
if (ov === false) return '强制非 VIP'
|
||||
return '跟随服务端'
|
||||
}
|
||||
|
||||
export default function DebugFab() {
|
||||
const [open, setOpen] = useState(false)
|
||||
const [override, setOverride] = useState<DevVipOverride>(null)
|
||||
const [resolved, setResolved] = useState<boolean | null>(null)
|
||||
const [localPaid, setLocalPaid] = useState(false)
|
||||
|
||||
async function refreshStatus() {
|
||||
setOverride(getDevVipOverride())
|
||||
setLocalPaid(isVipPaidLocal())
|
||||
try {
|
||||
setResolved(await resolveVipAccess(true))
|
||||
} catch {
|
||||
setResolved(null)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!DEBUG_FAB_VISIBLE || !isDevDebugEnabled()) return
|
||||
void refreshStatus()
|
||||
}, [])
|
||||
|
||||
// 默认隐藏:VIP 权限走 admin;改 DEBUG_FAB_VISIBLE=true 可再显示
|
||||
if (!DEBUG_FAB_VISIBLE || !isDevDebugEnabled()) return null
|
||||
|
||||
async function applyVip(next: DevVipOverride) {
|
||||
setDevVipOverride(next)
|
||||
if (next === true) {
|
||||
try {
|
||||
Taro.setStorageSync('nomadro_vip_paid', '1')
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
} else if (next === false) {
|
||||
clearVipPaidLocal()
|
||||
}
|
||||
setOverride(next)
|
||||
Taro.showToast({ title: vipLabel(next), icon: 'none', duration: 1200 })
|
||||
await refreshStatus()
|
||||
}
|
||||
|
||||
return (
|
||||
<View className="dbg-fab-root" catchMove>
|
||||
{open ? (
|
||||
<View className="dbg-fab-panel">
|
||||
<Text className="dbg-fab-title">🛠 调试面板</Text>
|
||||
<Text className="dbg-fab-hint">开发版可见 · 正式版 release 不显示</Text>
|
||||
|
||||
<Text className="dbg-fab-label">VIP 身份</Text>
|
||||
<View className="dbg-fab-row">
|
||||
{(
|
||||
[
|
||||
[null, '自动'],
|
||||
[true, 'VIP'],
|
||||
[false, '非VIP'],
|
||||
] as const
|
||||
).map(([val, label]) => (
|
||||
<View
|
||||
key={label}
|
||||
className={`dbg-fab-chip${override === val ? ' on' : ''}`}
|
||||
onClick={() => void applyVip(val)}
|
||||
>
|
||||
<Text className="dbg-fab-chip-txt">{label}</Text>
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
|
||||
<Text className="dbg-fab-label">快捷</Text>
|
||||
<View className="dbg-fab-row">
|
||||
<View
|
||||
className="dbg-fab-chip"
|
||||
onClick={() => {
|
||||
void loadRemoteConfig(true).then(() => {
|
||||
Taro.showToast({ title: '配置已刷新', icon: 'none' })
|
||||
void refreshStatus()
|
||||
})
|
||||
}}
|
||||
>
|
||||
<Text className="dbg-fab-chip-txt">刷新配置</Text>
|
||||
</View>
|
||||
<View
|
||||
className="dbg-fab-chip"
|
||||
onClick={() => {
|
||||
clearDevCaches()
|
||||
Taro.showToast({ title: '缓存已清', icon: 'none' })
|
||||
void refreshStatus()
|
||||
}}
|
||||
>
|
||||
<Text className="dbg-fab-chip-txt">清缓存</Text>
|
||||
</View>
|
||||
<View
|
||||
className="dbg-fab-chip"
|
||||
onClick={() => {
|
||||
setOpen(false)
|
||||
goPage('/pages/vip/index')
|
||||
}}
|
||||
>
|
||||
<Text className="dbg-fab-chip-txt">VIP页</Text>
|
||||
</View>
|
||||
<View
|
||||
className="dbg-fab-chip"
|
||||
onClick={() => {
|
||||
setOpen(false)
|
||||
goPage('/pages/vip-memo/index')
|
||||
}}
|
||||
>
|
||||
<Text className="dbg-fab-chip-txt">社群</Text>
|
||||
</View>
|
||||
<View
|
||||
className="dbg-fab-chip"
|
||||
onClick={() => {
|
||||
setOpen(false)
|
||||
goPage('/pages/vip-store/index')
|
||||
}}
|
||||
>
|
||||
<Text className="dbg-fab-chip-txt">商城</Text>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<Text className="dbg-fab-status">
|
||||
覆盖:{vipLabel(override)}
|
||||
{'\n'}
|
||||
resolveVip:{resolved === null ? '…' : resolved ? '是' : '否'}
|
||||
{'\n'}
|
||||
本地 paid:{localPaid ? '1' : '0'}
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
<View className="dbg-fab-ball" onClick={() => setOpen((v) => !v)}>
|
||||
<Text className="dbg-fab-ball-txt">{open ? '收起' : '调试'}</Text>
|
||||
</View>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
@ -1,7 +1,6 @@
|
||||
import { useEffect, useState, type ReactNode } from 'react'
|
||||
import { View, Text } from '@tarojs/components'
|
||||
import {
|
||||
getCachedRemoteConfig,
|
||||
isModuleEnabled,
|
||||
loadRemoteConfig,
|
||||
subscribeRemoteConfig,
|
||||
@ -10,7 +9,7 @@ import type { NomadroRemoteConfig } from '@/data/remoteConfig.defaults'
|
||||
|
||||
type ModuleKey = keyof NomadroRemoteConfig['modules']
|
||||
|
||||
/** 小程序页级模块闸门:订阅远程配置实时变更 */
|
||||
/** 小程序页级模块闸门:配置未确认前不渲染业务,杜绝先闪后关 */
|
||||
export function MiniModuleGate({
|
||||
moduleKey,
|
||||
children,
|
||||
@ -18,18 +17,26 @@ export function MiniModuleGate({
|
||||
moduleKey: ModuleKey
|
||||
children: ReactNode
|
||||
}) {
|
||||
const [enabled, setEnabled] = useState(true)
|
||||
const [enabled, setEnabled] = useState<boolean | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true
|
||||
const apply = (cfg: NomadroRemoteConfig) => {
|
||||
if (!alive) return
|
||||
setEnabled(isModuleEnabled(cfg, moduleKey))
|
||||
}
|
||||
apply(getCachedRemoteConfig())
|
||||
const unsub = subscribeRemoteConfig((r) => apply(r.config))
|
||||
void loadRemoteConfig(true)
|
||||
return unsub
|
||||
void loadRemoteConfig(true).then((r) => apply(r.config))
|
||||
return () => {
|
||||
alive = false
|
||||
unsub()
|
||||
}
|
||||
}, [moduleKey])
|
||||
|
||||
if (enabled === null) {
|
||||
return <View className="sub" />
|
||||
}
|
||||
|
||||
if (!enabled) {
|
||||
return (
|
||||
<View className="sub">
|
||||
|
||||
@ -68,6 +68,8 @@ export type NomadroRemoteConfig = {
|
||||
/** 加群点击:popup=弹窗(默认关跳转);vip=跳会员页 */
|
||||
joinGroupAction?: 'popup' | 'vip'
|
||||
offlineBadge: boolean
|
||||
/** VIP 知识社群:未付费可进列表试读(与 memo_settings.allowTrialBrowse 对齐意图) */
|
||||
memoTrialBrowse?: boolean
|
||||
}
|
||||
copy: {
|
||||
homeBrand: string
|
||||
@ -79,6 +81,8 @@ export type NomadroRemoteConfig = {
|
||||
wechatOaName?: string
|
||||
joinGroupDouyinHint?: string
|
||||
joinGroupDouyinQr?: string
|
||||
/** 知识社群解锁文案 */
|
||||
memoUnlockCta?: string
|
||||
}
|
||||
/** 导航分类/链接(后台 CRUD);离线用 links.json */
|
||||
navContent?: NavContent
|
||||
@ -86,11 +90,36 @@ export type NomadroRemoteConfig = {
|
||||
platforms?: {
|
||||
weapp?: {
|
||||
vipContent?: Partial<WeappVipContent>
|
||||
/** 数字游民小册审核模式:开则读备用 Markdown 书 */
|
||||
bookAudit?: {
|
||||
reviewMode?: boolean
|
||||
bookId?: string
|
||||
}
|
||||
}
|
||||
tt?: Record<string, unknown>
|
||||
}
|
||||
}
|
||||
|
||||
export type WeappBookAudit = {
|
||||
reviewMode: boolean
|
||||
bookId: string
|
||||
}
|
||||
|
||||
export const DEFAULT_BOOK_AUDIT: WeappBookAudit = {
|
||||
reviewMode: false,
|
||||
bookId: 'audit',
|
||||
}
|
||||
|
||||
/** 小册 Tab 审核用书:开审核则返回备用 bookId,否则 null(走正式路径) */
|
||||
export function resolveBookAudit(config: NomadroRemoteConfig): WeappBookAudit {
|
||||
const raw = config.platforms?.weapp?.bookAudit
|
||||
const bookId = String(raw?.bookId || DEFAULT_BOOK_AUDIT.bookId).trim() || 'audit'
|
||||
return {
|
||||
reviewMode: !!raw?.reviewMode,
|
||||
bookId,
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeNav(raw: unknown): NavContent {
|
||||
const r = (raw && typeof raw === 'object' ? raw : {}) as Record<string, unknown>
|
||||
const cats = Array.isArray(r.categories) ? r.categories : []
|
||||
@ -128,12 +157,13 @@ export const DEFAULT_REMOTE_CONFIG: NomadroRemoteConfig = {
|
||||
version: 1,
|
||||
updatedAt: '2026-03-28T00:00:00.000Z',
|
||||
modules: {
|
||||
// 离线种子默认全关入口(除首页/小册);线上以服务端覆盖。避免审核看到闪一下的入口。
|
||||
home: { enabled: true, title: '首页', tabLabel: '首页' },
|
||||
nav: { enabled: true, title: '出海导航', tabLabel: '导航', note: 'navContent 远程可改' },
|
||||
nav: { enabled: false, title: '出海导航', tabLabel: '导航', note: 'navContent 远程可改' },
|
||||
book: { enabled: true, title: '数字游民小册', tabLabel: '小册' },
|
||||
community: { enabled: true, title: '旅居社群', tabLabel: '社群' },
|
||||
destinations: { enabled: true, title: '目的地' },
|
||||
meetups: { enabled: true, title: '活动' },
|
||||
community: { enabled: false, title: '旅居社群', tabLabel: '社群' },
|
||||
destinations: { enabled: false, title: '目的地' },
|
||||
meetups: { enabled: false, title: '活动' },
|
||||
vip: { enabled: false, title: '会员中心' },
|
||||
game: { enabled: false, title: '数字游民', note: '冻结隐藏 · 勿开入口' },
|
||||
},
|
||||
@ -145,6 +175,7 @@ export const DEFAULT_REMOTE_CONFIG: NomadroRemoteConfig = {
|
||||
joinGroupDouyin: false,
|
||||
joinGroupAction: 'popup',
|
||||
offlineBadge: false,
|
||||
memoTrialBrowse: true,
|
||||
},
|
||||
copy: {
|
||||
homeBrand: 'nomadro',
|
||||
@ -152,15 +183,17 @@ export const DEFAULT_REMOTE_CONFIG: NomadroRemoteConfig = {
|
||||
homeLead: '',
|
||||
vipPriceFen: 29800,
|
||||
vipProductId: 'tiktok',
|
||||
vipCta: '立即加入 · ¥298',
|
||||
vipCta: '立即加入',
|
||||
wechatOaName: '异度世界',
|
||||
joinGroupDouyinHint: '打开抖音搜群「数字游民」或扫码进群',
|
||||
joinGroupDouyinQr: '',
|
||||
memoUnlockCta: '解锁 VIP 读全文',
|
||||
},
|
||||
navContent: JSON.parse(JSON.stringify(DEFAULT_NAV_CONTENT)) as NavContent,
|
||||
platforms: {
|
||||
weapp: {
|
||||
vipContent: JSON.parse(JSON.stringify(DEFAULT_WEAPP_VIP)) as WeappVipContent,
|
||||
bookAudit: { ...DEFAULT_BOOK_AUDIT },
|
||||
},
|
||||
},
|
||||
}
|
||||
@ -208,8 +241,19 @@ function mergePlatforms(
|
||||
): NomadroRemoteConfig['platforms'] {
|
||||
const b = base || {}
|
||||
const p = patch || {}
|
||||
const baseWeapp = (b.weapp || {}) as { vipContent?: Partial<WeappVipContent> }
|
||||
const patchWeapp = (p.weapp || {}) as { vipContent?: Partial<WeappVipContent> }
|
||||
const baseWeapp = (b.weapp || {}) as {
|
||||
vipContent?: Partial<WeappVipContent>
|
||||
bookAudit?: Partial<WeappBookAudit>
|
||||
}
|
||||
const patchWeapp = (p.weapp || {}) as {
|
||||
vipContent?: Partial<WeappVipContent>
|
||||
bookAudit?: Partial<WeappBookAudit>
|
||||
}
|
||||
const mergedAudit = {
|
||||
...DEFAULT_BOOK_AUDIT,
|
||||
...(baseWeapp.bookAudit || {}),
|
||||
...(patchWeapp.bookAudit || {}),
|
||||
}
|
||||
return {
|
||||
...b,
|
||||
...p,
|
||||
@ -219,6 +263,10 @@ function mergePlatforms(
|
||||
vipContent: mergeWeappVipContent(
|
||||
patchWeapp.vipContent ?? baseWeapp.vipContent,
|
||||
),
|
||||
bookAudit: {
|
||||
reviewMode: !!mergedAudit.reviewMode,
|
||||
bookId: String(mergedAudit.bookId || 'audit').trim() || 'audit',
|
||||
},
|
||||
},
|
||||
// tt 原样透传(若远端有);勿用微信默认覆盖抖音
|
||||
...(p.tt != null ? { tt: p.tt } : b.tt != null ? { tt: b.tt } : {}),
|
||||
|
||||
@ -29,6 +29,8 @@ export type VipEbookItem = {
|
||||
title: string
|
||||
desc: string
|
||||
ebookId: string
|
||||
/** 有则优先进该原生页(如原小册 /pages/book/index),否则走 vip-ebook */
|
||||
href?: string
|
||||
free?: boolean
|
||||
enabled?: boolean
|
||||
sort?: number
|
||||
@ -94,7 +96,7 @@ export const DEFAULT_WEAPP_VIP: WeappVipContent = {
|
||||
reviewMode: false,
|
||||
stats: {
|
||||
topics: '4',
|
||||
ebooks: '2',
|
||||
ebooks: '3',
|
||||
videos: '40+',
|
||||
updateFrequency: '每周',
|
||||
},
|
||||
@ -112,19 +114,19 @@ export const DEFAULT_WEAPP_VIP: WeappVipContent = {
|
||||
id: 'community',
|
||||
icon: '👥',
|
||||
title: '知识社群',
|
||||
desc: '抱团出海',
|
||||
desc: '抱团出海 · 可试读',
|
||||
href: '/pages/vip-memo/index',
|
||||
enabled: true,
|
||||
locked: true,
|
||||
locked: false,
|
||||
},
|
||||
{
|
||||
id: 'tools',
|
||||
icon: '🛒',
|
||||
title: '设备自助下单',
|
||||
desc: '开箱即用',
|
||||
desc: '可浏览 · VIP 下单',
|
||||
href: '/pages/vip-store/index',
|
||||
enabled: true,
|
||||
locked: true,
|
||||
locked: false,
|
||||
},
|
||||
],
|
||||
videos: [
|
||||
@ -170,6 +172,16 @@ export const DEFAULT_WEAPP_VIP: WeappVipContent = {
|
||||
free: true,
|
||||
enabled: true,
|
||||
},
|
||||
{
|
||||
// 原小册 book_id=default:收费展示;直达试读阅读器,单买或 VIP 解锁全文
|
||||
id: 'youtube-notes',
|
||||
title: 'Youtube运营笔记',
|
||||
desc: '原小册 · 试读可进,单买或 VIP 解锁全文',
|
||||
ebookId: 'default',
|
||||
href: '/pages/reader/index?id=default',
|
||||
free: false,
|
||||
enabled: true,
|
||||
},
|
||||
{
|
||||
id: '2',
|
||||
title: '云手机',
|
||||
@ -184,7 +196,7 @@ export const DEFAULT_WEAPP_VIP: WeappVipContent = {
|
||||
compare: [
|
||||
{ feature: '电子书', single: '按需开通', member: '全解锁' },
|
||||
{ feature: '视频教程', single: '按需开通', member: '全解锁' },
|
||||
{ feature: '知识社群', single: '—', member: '✓' },
|
||||
{ feature: '知识社群', single: '试读', member: '全文+互动' },
|
||||
{ feature: '即时问答', single: '—', member: '✓' },
|
||||
{ feature: '持续更新', single: '—', member: '✓' },
|
||||
],
|
||||
@ -222,6 +234,39 @@ function mergeList<T extends { id?: string; enabled?: boolean; sort?: number }>(
|
||||
.sort((a, b) => Number(a.sort || 0) - Number(b.sort || 0))
|
||||
}
|
||||
|
||||
/** 远程配置缺「Youtube运营笔记」时补上;已存在则校正到试读阅读器 */
|
||||
function ensureYoutubeNotesEbook(ebooks: VipEbookItem[]): VipEbookItem[] {
|
||||
const seed = DEFAULT_WEAPP_VIP.ebooks.find((e) => e.id === 'youtube-notes')
|
||||
if (!seed) return ebooks
|
||||
const readerHref = '/pages/reader/index?id=default'
|
||||
const hit = ebooks.findIndex(
|
||||
(e) =>
|
||||
e.id === 'youtube-notes' ||
|
||||
e.href === '/pages/book/index' ||
|
||||
e.href === readerHref ||
|
||||
(e.title === 'Youtube运营笔记' && e.ebookId === 'default'),
|
||||
)
|
||||
if (hit >= 0) {
|
||||
const next = ebooks.slice()
|
||||
next[hit] = {
|
||||
...next[hit],
|
||||
...seed,
|
||||
href: readerHref,
|
||||
ebookId: 'default',
|
||||
free: false,
|
||||
enabled: next[hit].enabled !== false,
|
||||
}
|
||||
return next
|
||||
}
|
||||
const idx = ebooks.findIndex((e) => e.id === '1' || e.title === '数字游民')
|
||||
if (idx >= 0) {
|
||||
const next = ebooks.slice()
|
||||
next.splice(idx + 1, 0, { ...seed })
|
||||
return next
|
||||
}
|
||||
return [...ebooks, { ...seed }]
|
||||
}
|
||||
|
||||
export function mergeWeappVipContent(
|
||||
partial?: Partial<WeappVipContent> | null,
|
||||
): WeappVipContent {
|
||||
@ -241,7 +286,7 @@ export function mergeWeappVipContent(
|
||||
stats: { ...base.stats, ...(partial.stats || {}) },
|
||||
topics: mergeList(base.topics, partial.topics ?? base.topics),
|
||||
videos: mergeList(base.videos, partial.videos ?? base.videos),
|
||||
ebooks: mergeList(base.ebooks, partial.ebooks ?? base.ebooks),
|
||||
ebooks: ensureYoutubeNotesEbook(mergeList(base.ebooks, partial.ebooks ?? base.ebooks)),
|
||||
compare: Array.isArray(partial.compare) ? partial.compare : base.compare,
|
||||
faq: Array.isArray(partial.faq) ? partial.faq : base.faq,
|
||||
ctaChips: Array.isArray(partial.ctaChips) ? partial.ctaChips.map(String) : base.ctaChips,
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
* (CommunityNavbar + hero shapes + gradient + typewriter + 固定 CTA)
|
||||
* 内容 SoT: COVER_BOOK / nomadCodeBook;阅读入口 → /pages/reader
|
||||
*/
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { Button } from '@tarojs/components'
|
||||
import Taro, { useDidShow, useLoad } from '@tarojs/taro'
|
||||
import { fetchBook, type BookDetail } from '../../services/ebookApi'
|
||||
@ -19,7 +19,14 @@ import { CommunityNavbar } from '../../components/Chrome'
|
||||
import { H5Box, H5Txt } from '../../components/H5Box'
|
||||
import { applyH5Theme, useNomadroTheme } from '../../utils/h5Theme'
|
||||
import { usePageShare, markPageShare } from '@/utils/pageShare'
|
||||
import { goPage } from '@/utils/nav'
|
||||
import { getSafeAreaMetrics } from '../../utils/safeArea'
|
||||
import {
|
||||
getCachedRemoteConfig,
|
||||
loadRemoteConfig,
|
||||
subscribeRemoteConfig,
|
||||
} from '@/services/remoteConfig'
|
||||
import { resolveBookAudit } from '@/data/remoteConfig.defaults'
|
||||
import './index.scss'
|
||||
|
||||
const isH5 = process.env.TARO_ENV === 'h5'
|
||||
@ -107,22 +114,54 @@ function BookPageInner() {
|
||||
const [error, setError] = useState('')
|
||||
const [progress, setProgress] = useState<ReadingProgress | null>(null)
|
||||
const [tw, setTw] = useState('')
|
||||
const [audit, setAudit] = useState(() => resolveBookAudit(getCachedRemoteConfig()))
|
||||
const auditKeyRef = useRef(`${audit.reviewMode}:${audit.bookId}`)
|
||||
|
||||
useLoad(() => {
|
||||
trackPage('pages/book/index', '小册封面')
|
||||
const a = resolveBookAudit(getCachedRemoteConfig())
|
||||
if (a.reviewMode) {
|
||||
const url = `/pages/reader/index?id=${encodeURIComponent(a.bookId || 'audit')}`
|
||||
void Taro.redirectTo({ url }).catch(() => goPage(url))
|
||||
return
|
||||
}
|
||||
loadBook()
|
||||
})
|
||||
|
||||
useDidShow(() => {
|
||||
setProgress(getReadingProgress('default'))
|
||||
void loadRemoteConfig(true).then((r) => {
|
||||
applyAudit(resolveBookAudit(r.config))
|
||||
})
|
||||
loadBook(true)
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
setProgress(getReadingProgress('default'))
|
||||
return subscribeRemoteConfig((r) => {
|
||||
applyAudit(resolveBookAudit(r.config))
|
||||
})
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
applyH5Theme(theme)
|
||||
}, [theme])
|
||||
|
||||
function applyAudit(next: ReturnType<typeof resolveBookAudit>) {
|
||||
const key = `${next.reviewMode}:${next.bookId}`
|
||||
const changed = key !== auditKeyRef.current
|
||||
auditKeyRef.current = key
|
||||
setAudit(next)
|
||||
const pid = next.reviewMode ? next.bookId || 'audit' : 'nomad'
|
||||
setProgress(getReadingProgress(pid))
|
||||
if (changed) {
|
||||
void loadBook(true)
|
||||
// 提审开:直接进审核版;提审关:留在封面展示正式入口
|
||||
if (next.reviewMode) {
|
||||
const url = `/pages/reader/index?id=${encodeURIComponent(next.bookId || 'audit')}`
|
||||
void Taro.redirectTo({ url }).catch(() => goPage(url))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 对齐小红书 startTypewriter:hooks 轮播打字机
|
||||
useEffect(() => {
|
||||
if (loading) return
|
||||
@ -158,16 +197,43 @@ function BookPageInner() {
|
||||
}, [loading])
|
||||
|
||||
async function loadBook(silent = false) {
|
||||
// 封面始终用 COVER_BOOK,保证与 H5 同标题/同视觉
|
||||
setBook(coverAsBookDetail())
|
||||
setError('')
|
||||
if (isH5) return
|
||||
const a = resolveBookAudit(getCachedRemoteConfig())
|
||||
setAudit(a)
|
||||
auditKeyRef.current = `${a.reviewMode}:${a.bookId}`
|
||||
// 正式:封面品牌视觉;提审:立刻换成审核版书名/章节,保证开关可见
|
||||
if (!a.reviewMode) {
|
||||
setBook(coverAsBookDetail())
|
||||
setApiBook(null)
|
||||
}
|
||||
try {
|
||||
if (!silent) setLoading(true)
|
||||
const data = await fetchBook('default')
|
||||
const bookId = a.reviewMode ? a.bookId || 'audit' : 'nomad'
|
||||
const data = await fetchBook(bookId)
|
||||
setApiBook(data)
|
||||
if (a.reviewMode && data) {
|
||||
setBook({
|
||||
...coverAsBookDetail(),
|
||||
id: data.id,
|
||||
title: data.title || '数字游民入门指南',
|
||||
subtitle: data.subtitle || '远程办公 · 自律生活 · 稳健成长',
|
||||
description: data.description || coverAsBookDetail().description,
|
||||
chapters: data.chapters?.length ? data.chapters : coverAsBookDetail().chapters,
|
||||
is_free: true,
|
||||
unlock_percent: 100,
|
||||
})
|
||||
}
|
||||
} catch (e: any) {
|
||||
// 封面已有离线兜底,静默即可
|
||||
if (a.reviewMode) {
|
||||
setBook({
|
||||
...coverAsBookDetail(),
|
||||
id: a.bookId || 'audit',
|
||||
title: '数字游民入门指南',
|
||||
subtitle: '远程办公 · 自律生活 · 稳健成长',
|
||||
is_free: true,
|
||||
unlock_percent: 100,
|
||||
})
|
||||
}
|
||||
track('error', {
|
||||
page: 'pages/book/index',
|
||||
label: 'load_book',
|
||||
@ -187,21 +253,26 @@ function BookPageInner() {
|
||||
}, [book, apiBook, progress])
|
||||
|
||||
function goRead() {
|
||||
const a = resolveBookAudit(getCachedRemoteConfig())
|
||||
// 仅针对「数字游民小册」:审核→备用 Markdown;正式→VIP 电子书 nomad
|
||||
// youtube运营笔记(default) 不受此开关影响
|
||||
const bookId = a.reviewMode ? a.bookId || 'audit' : 'nomad'
|
||||
const continuing = !!progress?.chapterId
|
||||
trackClick(continuing ? '继续阅读' : '开始阅读', {
|
||||
book_id: apiBook?.id || book?.id || 'default',
|
||||
book_id: bookId,
|
||||
has_progress: continuing,
|
||||
audit: a.reviewMode,
|
||||
})
|
||||
track('read_start', {
|
||||
page: 'pages/book/index',
|
||||
label: continuing ? '继续阅读' : '开始阅读',
|
||||
props: { book_id: apiBook?.id || book?.id || 'default' },
|
||||
props: { book_id: bookId, audit: a.reviewMode },
|
||||
})
|
||||
const bookId = apiBook?.id || book?.id || 'default'
|
||||
const chapter = progress?.chapterId
|
||||
? `&chapter=${encodeURIComponent(String(progress.chapterId))}`
|
||||
: ''
|
||||
Taro.navigateTo({ url: `/pages/reader/index?id=${bookId}${chapter}` })
|
||||
if (a.reviewMode) {
|
||||
goPage(`/pages/reader/index?id=${encodeURIComponent(bookId)}`)
|
||||
return
|
||||
}
|
||||
goPage('/pages/vip-ebook/index?id=nomad')
|
||||
}
|
||||
|
||||
if (loading && !book) {
|
||||
@ -248,8 +319,14 @@ function BookPageInner() {
|
||||
? '点一下,直接进入正文'
|
||||
: '先翻开前面的章节'
|
||||
|
||||
/** 封面副标题只保留「低成本工作室」,不拼公众号引导(与弹窗重复) */
|
||||
const tagParts = [book.subtitle || COVER_BOOK.subtitle || '低成本工作室']
|
||||
const displayTitle = audit.reviewMode
|
||||
? book.title || '数字游民入门指南'
|
||||
: COVER_BOOK.title
|
||||
const tagParts = [
|
||||
audit.reviewMode
|
||||
? book.subtitle || '远程办公 · 自律生活 · 稳健成长'
|
||||
: book.subtitle || COVER_BOOK.subtitle || '低成本工作室',
|
||||
]
|
||||
const safe = useMemo(() => getSafeAreaMetrics(), [])
|
||||
const safeStyle = useMemo(
|
||||
() => ({
|
||||
@ -280,7 +357,7 @@ function BookPageInner() {
|
||||
<H5Box className="hero-top">
|
||||
<H5Box className="hero-content">
|
||||
<H5Box className="hero-title book-hero-title">
|
||||
<H5Txt className="hero-title-line book-title-brand">{COVER_BOOK.title}</H5Txt>
|
||||
<H5Txt className="hero-title-line book-title-brand">{displayTitle}</H5Txt>
|
||||
<H5Box className="hero-title-line book-tagline">
|
||||
<H5Txt>{tagParts[0]}</H5Txt>
|
||||
</H5Box>
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
* 对齐门户 components/sections/hero.tsx(结构 / PORTALS / 开发快捷入口)
|
||||
* H5 真布局用原生 div(Taro View 自定义元素会弄塌 grid/绝对定位)。
|
||||
*/
|
||||
import { useEffect, useMemo, useState, type CSSProperties, type ReactNode } from 'react'
|
||||
import { useEffect, useState, type CSSProperties, type ReactNode } from 'react'
|
||||
import { View, Text } from '@tarojs/components'
|
||||
import Taro, { useDidShow, usePageScroll } from '@tarojs/taro'
|
||||
import {
|
||||
@ -14,7 +14,7 @@ import type { NomadroRemoteConfig } from '@/data/remoteConfig.defaults'
|
||||
import { applyH5Theme, useNomadroTheme } from '@/utils/h5Theme'
|
||||
import { goPage } from '@/utils/nav'
|
||||
import { usePageShare, markPageShare } from '@/utils/pageShare'
|
||||
import { getSafeAreaMetrics } from '@/utils/safeArea'
|
||||
import { safePx, useSafeAreaMetrics } from '@/utils/safeArea'
|
||||
import { usePageTrack } from '@/hooks/usePageTrack'
|
||||
import './index.scss'
|
||||
type PortalId = 'nav' | 'book' | 'community' | 'vip'
|
||||
@ -284,10 +284,12 @@ function IndexPage() {
|
||||
}, [])
|
||||
|
||||
const cfg = config
|
||||
const portals = PORTALS.filter((p) => !cfg || isModuleEnabled(cfg, p.moduleKey))
|
||||
// 配置未就绪:一个入口都不渲染,避免「先闪后藏」被审核盯上
|
||||
const portals = cfg ? PORTALS.filter((p) => isModuleEnabled(cfg, p.moduleKey)) : []
|
||||
const brand = cfg?.copy.homeBrand || 'nomadro'
|
||||
const safe = useMemo(() => getSafeAreaMetrics(), [])
|
||||
const safe = useSafeAreaMetrics()
|
||||
const rootSafeStyle = {
|
||||
// CSS 变量用小写 px(样式表已排除 rpx 转换);内联尺寸必须用 safePx
|
||||
['--safe-status-bar' as string]: `${safe.statusBarHeight}px`,
|
||||
['--safe-nav-bar' as string]: `${safe.navBarHeight}px`,
|
||||
['--safe-menu-pad' as string]: `${safe.menuRightPad}px`,
|
||||
@ -308,7 +310,7 @@ function IndexPage() {
|
||||
style={
|
||||
!isH5
|
||||
? {
|
||||
paddingTop: safe.statusBarHeight,
|
||||
paddingTop: safePx(safe.statusBarHeight),
|
||||
height: 'auto',
|
||||
}
|
||||
: undefined
|
||||
@ -319,8 +321,8 @@ function IndexPage() {
|
||||
style={
|
||||
!isH5
|
||||
? {
|
||||
height: safe.navBarHeight,
|
||||
paddingRight: safe.menuRightPad,
|
||||
height: safePx(safe.navBarHeight),
|
||||
paddingRight: safePx(safe.menuRightPad),
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
@ -356,7 +358,7 @@ function IndexPage() {
|
||||
style={
|
||||
!isH5
|
||||
? {
|
||||
paddingTop: safe.headerHeight + 8,
|
||||
paddingTop: safePx(safe.headerHeight + 8),
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
|
||||
@ -68,17 +68,19 @@ function countLinks(cat: NavCategory) {
|
||||
return cat.groups.reduce((s, g) => s + g.links.length, 0)
|
||||
}
|
||||
|
||||
/** 微信包内图片合计须 ≤200K(代码质量);导航图标走门户 CDN */
|
||||
const WEAPP_ICON_CDN = 'https://nomadro.cn/icons'
|
||||
|
||||
function iconSrc(icon: string) {
|
||||
if (!icon) return ''
|
||||
// 真机调试:绝对路径 /icons 偶发解析失败;相对 pages/nav → ../../icons
|
||||
// 资源以 webp 为主;dev 可能未跑 webp→png,优先 webp,避免空白
|
||||
const cleaned = icon.replace(/^\//, '').replace(/^icons\//, '')
|
||||
const base = cleaned.replace(/\.(webp|png|jpe?g)$/i, '')
|
||||
if (process.env.TARO_ENV === 'h5') {
|
||||
// H5 public 多为 webp;有 png 时亦可
|
||||
return `/icons/${base}.webp`
|
||||
}
|
||||
return `../../icons/${base}.webp`
|
||||
// 已是 https 则原样用(远程配置可直接给 CDN)
|
||||
if (/^https?:\/\//i.test(icon)) return icon
|
||||
return `${WEAPP_ICON_CDN}/${base}.webp`
|
||||
}
|
||||
|
||||
|
||||
|
||||
@ -15,7 +15,9 @@
|
||||
--r-soft: rgba(255, 255, 255, 0.06);
|
||||
--r-border: rgba(255, 255, 255, 0.1);
|
||||
--r-paper: rgba(28, 22, 45, 0.92);
|
||||
--r-chrome: rgba(12, 11, 18, 0.94);
|
||||
/* 不透明,避免正文滚到顶栏下透出「鬼影标题」 */
|
||||
--r-chrome: #0c0b12;
|
||||
--r-topbar-body: 60px;
|
||||
}
|
||||
|
||||
.reader.theme-sepia {
|
||||
@ -29,7 +31,7 @@
|
||||
--r-soft: rgba(120, 80, 40, 0.08);
|
||||
--r-border: rgba(120, 80, 40, 0.16);
|
||||
--r-paper: rgba(255, 252, 245, 0.95);
|
||||
--r-chrome: rgba(243, 233, 215, 0.96);
|
||||
--r-chrome: #f3e9d7;
|
||||
}
|
||||
|
||||
.reader.theme-light {
|
||||
@ -43,7 +45,7 @@
|
||||
--r-soft: rgba(30, 22, 48, 0.05);
|
||||
--r-border: rgba(30, 22, 48, 0.1);
|
||||
--r-paper: rgba(255, 255, 255, 0.96);
|
||||
--r-chrome: rgba(247, 244, 251, 0.96);
|
||||
--r-chrome: #f7f4fb;
|
||||
}
|
||||
|
||||
.reader-bg {
|
||||
@ -105,11 +107,13 @@
|
||||
left: 0;
|
||||
right: 0;
|
||||
z-index: 40;
|
||||
padding: calc(8px + var(--safe-status-bar, 0px)) 12px 8px;
|
||||
/* 本页用系统导航栏,勿再叠 statusBar,否则顶栏过高、正文钻进去 */
|
||||
padding: 8px 12px;
|
||||
padding-right: max(12px, var(--safe-menu-pad, 12px));
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-height: var(--r-topbar-body, 60px);
|
||||
background: var(--r-chrome);
|
||||
border-bottom: 1px solid var(--r-border);
|
||||
box-sizing: border-box;
|
||||
@ -186,7 +190,7 @@
|
||||
background: var(--r-paper);
|
||||
border: 1px solid var(--r-border);
|
||||
border-radius: 20px;
|
||||
margin: 68px 16px 36px;
|
||||
margin: calc(12px + var(--r-topbar-body, 60px)) 16px 36px;
|
||||
padding: 16px 14px 20px;
|
||||
box-shadow: 0 16px 40px rgba(0, 0, 0, 0.18);
|
||||
}
|
||||
@ -717,7 +721,7 @@
|
||||
.chapter-block,
|
||||
#paywall,
|
||||
[data-anchor] {
|
||||
scroll-margin-top: 72px;
|
||||
scroll-margin-top: 64px;
|
||||
}
|
||||
|
||||
.top-btn {
|
||||
@ -736,7 +740,7 @@
|
||||
}
|
||||
|
||||
.paper {
|
||||
margin: 60px 12px 28px;
|
||||
margin: calc(10px + var(--r-topbar-body, 60px)) 12px 28px;
|
||||
padding: 14px 12px 16px;
|
||||
border-radius: 16px;
|
||||
}
|
||||
|
||||
@ -40,9 +40,12 @@ import {
|
||||
needsRepin,
|
||||
shouldAcceptJumpMeasurement,
|
||||
} from '../../modules/reader'
|
||||
import { subscribeRemoteConfig } from '../../services/remoteConfig'
|
||||
import { resolveBookAudit } from '../../data/remoteConfig.defaults'
|
||||
import './index.scss'
|
||||
|
||||
const TOPBAR_OFFSET = 72
|
||||
/** 系统导航下自定义顶栏高度(8+44+8),与 scss --r-topbar-body 对齐 */
|
||||
const TOPBAR_OFFSET = 64
|
||||
const isH5 = process.env.TARO_ENV === 'h5'
|
||||
|
||||
function ReaderPage() {
|
||||
@ -99,6 +102,39 @@ function ReaderPage() {
|
||||
if (!loadedRef.current) load()
|
||||
}, [bookId])
|
||||
|
||||
// 提审开关热切换:redirect,避免 navigate 叠栈导致一直「加载中」
|
||||
useEffect(() => {
|
||||
let switching = false
|
||||
return subscribeRemoteConfig((r) => {
|
||||
if (switching) return
|
||||
const audit = resolveBookAudit(r.config)
|
||||
const auditId = audit.bookId || 'audit'
|
||||
if (audit.reviewMode) {
|
||||
if (bookId === auditId || bookId === 'audit') return
|
||||
if (bookId === 'nomad' || bookId === 'default') {
|
||||
switching = true
|
||||
const url = `/pages/reader/index?id=${encodeURIComponent(auditId)}`
|
||||
void Taro.redirectTo({ url })
|
||||
.catch(() => goPage(url))
|
||||
.finally(() => {
|
||||
switching = false
|
||||
})
|
||||
}
|
||||
return
|
||||
}
|
||||
// 提审关:从审核版回到正式会员书
|
||||
if (bookId === auditId || bookId === 'audit') {
|
||||
switching = true
|
||||
const url = '/pages/vip-ebook/index?id=nomad'
|
||||
void Taro.redirectTo({ url })
|
||||
.catch(() => goPage(url))
|
||||
.finally(() => {
|
||||
switching = false
|
||||
})
|
||||
}
|
||||
})
|
||||
}, [bookId])
|
||||
|
||||
async function load(silent = false) {
|
||||
try {
|
||||
if (!silent) Taro.showLoading({ title: '打开中' })
|
||||
@ -136,7 +172,6 @@ function ReaderPage() {
|
||||
})
|
||||
accessFpRef.current = next
|
||||
await load(true)
|
||||
Taro.showToast({ title: '阅读权限已更新', icon: 'none' })
|
||||
}
|
||||
} catch {
|
||||
/* 静默 */
|
||||
|
||||
@ -22,7 +22,7 @@ import {
|
||||
CLOUDPHONE_HERO,
|
||||
} from '../../data/vipCloudphoneLanding'
|
||||
import { goPage } from '../../utils/nav'
|
||||
import { resolveVipAccess } from '../../utils/vipAccess'
|
||||
import { goVipUnlock, resolveVipContentAccess } from '../../utils/vipAccess'
|
||||
import {
|
||||
getLastWatched,
|
||||
getProgress,
|
||||
@ -98,7 +98,7 @@ export default function VipCoursePage() {
|
||||
/* keep local */
|
||||
}
|
||||
}
|
||||
const ok = await resolveVipAccess(true)
|
||||
const ok = await resolveVipContentAccess(true)
|
||||
setIsVip(ok)
|
||||
setReady(true)
|
||||
})()
|
||||
@ -127,7 +127,7 @@ export default function VipCoursePage() {
|
||||
const showPrep = (topicId === 'indie' || topicId === 'aiagent') && !curriculum.hasContent
|
||||
|
||||
function onEnroll() {
|
||||
goPage('/pages/vip/index')
|
||||
goVipUnlock()
|
||||
}
|
||||
|
||||
function onPrimaryCta() {
|
||||
|
||||
@ -10,9 +10,15 @@ import { MarkdownView } from '../../components/MarkdownView'
|
||||
import { resolveVipEbookId, VIP_EBOOKS, type VipEbookPack } from '../../data/vipEbooks'
|
||||
import { loadVipEbook } from '../../services/vipLibrary'
|
||||
import { goPage } from '../../utils/nav'
|
||||
import { resolveVipAccess } from '../../utils/vipAccess'
|
||||
import { goVipUnlock, resolveVipContentAccess } from '../../utils/vipAccess'
|
||||
import { getSafeAreaMetrics } from '../../utils/safeArea'
|
||||
import { useNomadroTheme } from '@/utils/h5Theme'
|
||||
import {
|
||||
getCachedRemoteConfig,
|
||||
loadRemoteConfig,
|
||||
subscribeRemoteConfig,
|
||||
} from '../../services/remoteConfig'
|
||||
import { resolveBookAudit } from '../../data/remoteConfig.defaults'
|
||||
import './index.scss'
|
||||
|
||||
const EBOOK_PREFS = {
|
||||
@ -66,6 +72,7 @@ export default function VipEbookPage() {
|
||||
}, [toc, tocFilter])
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
setScrollInto('')
|
||||
setDrawerOpen(false)
|
||||
setTocFilter('')
|
||||
@ -73,29 +80,70 @@ export default function VipEbookPage() {
|
||||
setReadProgress(0)
|
||||
setReady(false)
|
||||
void (async () => {
|
||||
const { book: next } = await loadVipEbook(bookId)
|
||||
setBook(next)
|
||||
Taro.setNavigationBarTitle({ title: next.title })
|
||||
if (next.free) {
|
||||
setAllowed(true)
|
||||
setReady(true)
|
||||
return
|
||||
}
|
||||
const vip = await resolveVipAccess(true)
|
||||
setAllowed(vip)
|
||||
setReady(true)
|
||||
if (!vip) {
|
||||
Taro.showModal({
|
||||
title: '会员专享',
|
||||
content: `开通 VIP 后可读《${next.title}》`,
|
||||
confirmText: '去开通',
|
||||
success: (r) => {
|
||||
if (r.confirm) goPage('/pages/vip/index')
|
||||
else Taro.navigateBack({ fail: () => goPage('/pages/vip/index') })
|
||||
},
|
||||
})
|
||||
try {
|
||||
// 数字游民:提审开 → 改读审核版;用 redirect 避免页面栈卡死
|
||||
if (bookId === 'nomad') {
|
||||
try {
|
||||
await loadRemoteConfig(true)
|
||||
} catch {
|
||||
/* cache */
|
||||
}
|
||||
if (cancelled) return
|
||||
const audit = resolveBookAudit(getCachedRemoteConfig())
|
||||
if (audit.reviewMode) {
|
||||
const url = `/pages/reader/index?id=${encodeURIComponent(audit.bookId || 'audit')}`
|
||||
await Taro.redirectTo({ url }).catch(() => goPage(url))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
const { book: next } = await loadVipEbook(bookId)
|
||||
if (cancelled) return
|
||||
setBook(next)
|
||||
Taro.setNavigationBarTitle({ title: next.title })
|
||||
if (next.free) {
|
||||
setAllowed(true)
|
||||
return
|
||||
}
|
||||
const vip = await resolveVipContentAccess(true)
|
||||
if (cancelled) return
|
||||
setAllowed(vip)
|
||||
if (!vip) {
|
||||
Taro.showModal({
|
||||
title: '会员专享',
|
||||
content: `开通 VIP 后可读《${next.title}》`,
|
||||
confirmText: '去开通',
|
||||
success: (r) => {
|
||||
if (r.confirm) goVipUnlock()
|
||||
else Taro.navigateBack({ fail: () => goPage('/pages/vip/index') })
|
||||
},
|
||||
})
|
||||
}
|
||||
} catch {
|
||||
if (cancelled) return
|
||||
// 失败也必须结束加载态,展示包内正式书
|
||||
const fallback = VIP_EBOOKS[bookId] || VIP_EBOOKS.nomad
|
||||
setBook(fallback)
|
||||
setAllowed(!!fallback.free)
|
||||
Taro.setNavigationBarTitle({ title: fallback.title })
|
||||
} finally {
|
||||
if (!cancelled) setReady(true)
|
||||
}
|
||||
})()
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [bookId])
|
||||
|
||||
// 后台打开提审:静默 redirect,不弹 toast、不卡加载
|
||||
useEffect(() => {
|
||||
if (bookId !== 'nomad') return
|
||||
return subscribeRemoteConfig((r) => {
|
||||
const audit = resolveBookAudit(r.config)
|
||||
if (!audit.reviewMode) return
|
||||
const url = `/pages/reader/index?id=${encodeURIComponent(audit.bookId || 'audit')}`
|
||||
void Taro.redirectTo({ url }).catch(() => goPage(url))
|
||||
})
|
||||
}, [bookId])
|
||||
|
||||
function onScroll(e: {
|
||||
@ -142,7 +190,7 @@ export default function VipEbookPage() {
|
||||
return (
|
||||
<H5Box className="veb" data-theme={theme}>
|
||||
<H5Txt className="veb-loading">🔒 开通会员后阅读《{book.title}》</H5Txt>
|
||||
<View className="veb-locked-cta" onClick={() => goPage('/pages/vip/index')}>
|
||||
<View className="veb-locked-cta" onClick={() => goVipUnlock()}>
|
||||
<Text>立即开通</Text>
|
||||
</View>
|
||||
</H5Box>
|
||||
|
||||
@ -10,7 +10,7 @@ import { MarkdownView } from '../../components/MarkdownView'
|
||||
import { VIP_COURSE_MODULES, type VipLesson, type VipModule } from '../../data/vipCourse'
|
||||
import { loadVipLesson } from '../../services/vipLibrary'
|
||||
import { goPage } from '../../utils/nav'
|
||||
import { resolveVipAccess } from '../../utils/vipAccess'
|
||||
import { goVipUnlock, resolveVipContentAccess } from '../../utils/vipAccess'
|
||||
import {
|
||||
getProgress,
|
||||
markCompleted,
|
||||
@ -57,7 +57,7 @@ export default function VipLessonPage() {
|
||||
setModules(loaded.modules)
|
||||
setVideoUrl(loaded.doc.videoUrl || loaded.lesson?.videoUrl || '')
|
||||
setMarkdown(loaded.doc.markdown || '')
|
||||
const vip = await resolveVipAccess(true)
|
||||
const vip = await resolveVipContentAccess(true)
|
||||
setIsVip(vip)
|
||||
setReady(true)
|
||||
const tot = loaded.modules.reduce((s, mod) => s + mod.lessons.length, 0)
|
||||
@ -68,7 +68,7 @@ export default function VipLessonPage() {
|
||||
content: '开通 VIP 后可观看本课视频与配套文档',
|
||||
confirmText: '去开通',
|
||||
success: (r) => {
|
||||
if (r.confirm) goPage('/pages/vip/index')
|
||||
if (r.confirm) goVipUnlock()
|
||||
else
|
||||
Taro.navigateBack({
|
||||
fail: () => goPage('/pages/vip-course/index?id=cloudphone'),
|
||||
@ -118,7 +118,7 @@ export default function VipLessonPage() {
|
||||
<View className="vip-lesson-lock">
|
||||
<Text className="vip-lesson-lock-ico">🔒</Text>
|
||||
<Text>报名解锁本章节</Text>
|
||||
<View className="vip-lesson-lock-btn" onClick={() => goPage('/pages/vip/index')}>
|
||||
<View className="vip-lesson-lock-btn" onClick={() => goVipUnlock()}>
|
||||
<Text>立即报名</Text>
|
||||
</View>
|
||||
</View>
|
||||
@ -155,7 +155,7 @@ export default function VipLessonPage() {
|
||||
className="vip-lesson-nav-btn"
|
||||
onClick={() => {
|
||||
if (!isVip) {
|
||||
goPage('/pages/vip/index')
|
||||
goVipUnlock()
|
||||
return
|
||||
}
|
||||
goPage(`/pages/vip-lesson/index?m=${prev.m}&l=${prev.l}`)
|
||||
@ -174,7 +174,7 @@ export default function VipLessonPage() {
|
||||
className="vip-lesson-nav-btn"
|
||||
onClick={() => {
|
||||
if (!isVip) {
|
||||
goPage('/pages/vip/index')
|
||||
goVipUnlock()
|
||||
return
|
||||
}
|
||||
goPage(`/pages/vip-lesson/index?m=${next.m}&l=${next.l}`)
|
||||
|
||||
@ -99,6 +99,124 @@
|
||||
background: rgba(94, 234, 212, 0.15);
|
||||
color: #5eead4;
|
||||
}
|
||||
.zd-badge.trial {
|
||||
background: rgba(96, 165, 250, 0.18);
|
||||
color: #93c5fd;
|
||||
}
|
||||
.zd-badge.trial {
|
||||
background: rgba(96, 165, 250, 0.18);
|
||||
color: #93c5fd;
|
||||
}
|
||||
.zd-lock {
|
||||
margin: 8px 0 20px;
|
||||
padding: 16px 14px 18px;
|
||||
border-radius: 14px;
|
||||
background: linear-gradient(160deg, rgba(245, 158, 11, 0.12), rgba(15, 23, 42, 0.55));
|
||||
border: 1px solid rgba(245, 158, 11, 0.28);
|
||||
text-align: center;
|
||||
}
|
||||
.zd-lock-excerpt {
|
||||
display: block;
|
||||
font-size: 14px;
|
||||
color: #cbd5e1;
|
||||
line-height: 1.65;
|
||||
text-align: left;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.zd-lock-ghost {
|
||||
position: relative;
|
||||
margin-bottom: 14px;
|
||||
padding: 10px 0 4px;
|
||||
overflow: hidden;
|
||||
border-radius: 8px;
|
||||
}
|
||||
.zd-lock-line {
|
||||
height: 10px;
|
||||
border-radius: 5px;
|
||||
margin: 0 0 8px;
|
||||
background: linear-gradient(
|
||||
90deg,
|
||||
rgba(255, 255, 255, 0.06),
|
||||
rgba(245, 158, 11, 0.14),
|
||||
rgba(255, 255, 255, 0.06)
|
||||
);
|
||||
background-size: 200% 100%;
|
||||
animation: zd-shimmer 1.8s ease-in-out infinite;
|
||||
filter: blur(2.5px);
|
||||
}
|
||||
.zd-lock-line.w95 {
|
||||
width: 95%;
|
||||
}
|
||||
.zd-lock-line.w88 {
|
||||
width: 88%;
|
||||
}
|
||||
.zd-lock-line.w72 {
|
||||
width: 72%;
|
||||
}
|
||||
.zd-lock-line.w90 {
|
||||
width: 90%;
|
||||
}
|
||||
.zd-lock-line.w60 {
|
||||
width: 60%;
|
||||
}
|
||||
@keyframes zd-shimmer {
|
||||
0% {
|
||||
background-position: 100% 0;
|
||||
}
|
||||
100% {
|
||||
background-position: -100% 0;
|
||||
}
|
||||
}
|
||||
.zd-lock-mosaic {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background:
|
||||
repeating-linear-gradient(
|
||||
-28deg,
|
||||
rgba(12, 12, 15, 0.12) 0 3px,
|
||||
rgba(245, 158, 11, 0.05) 3px 6px
|
||||
),
|
||||
linear-gradient(180deg, transparent, rgba(12, 12, 15, 0.75));
|
||||
}
|
||||
.zd-lock-title {
|
||||
display: block;
|
||||
font-size: 17px;
|
||||
font-weight: 800;
|
||||
color: #fbbf24;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
.zd-lock-desc {
|
||||
display: block;
|
||||
font-size: 13px;
|
||||
color: #94a3b8;
|
||||
margin-bottom: 14px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
.zd-lock-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 44px;
|
||||
padding: 0 22px;
|
||||
border-radius: 12px;
|
||||
background: #f59e0b;
|
||||
color: #0c0c0f;
|
||||
font-weight: 800;
|
||||
font-size: 15px;
|
||||
}
|
||||
.zd-bar-unlock {
|
||||
flex: 1;
|
||||
min-height: 40px;
|
||||
border-radius: 10px;
|
||||
background: rgba(245, 158, 11, 0.18);
|
||||
border: 1px solid rgba(245, 158, 11, 0.4);
|
||||
color: #fbbf24;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
.zd-title {
|
||||
display: block;
|
||||
font-size: 24px;
|
||||
|
||||
@ -1,11 +1,16 @@
|
||||
/**
|
||||
* 知识帖详情 — 缓存秒开 · 静默刷新 · 旋转 loading
|
||||
* 知识帖详情 — 试读全文;非试读未付费提示解锁 VIP
|
||||
*/
|
||||
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 {
|
||||
goVipUnlock,
|
||||
isFreeVipScheme,
|
||||
resolveVipAccess,
|
||||
} from '@/utils/vipAccess'
|
||||
import { subscribeRemoteConfig } from '@/services/remoteConfig'
|
||||
import { MarkdownView } from '@/components/MarkdownView'
|
||||
import {
|
||||
commentMemo,
|
||||
@ -44,6 +49,18 @@ function hydrate(id: string): { memo: MemoItem | null; comments: MemoComment[] }
|
||||
return { memo: null, comments: [] }
|
||||
}
|
||||
|
||||
function promptUnlockVip(hint?: string) {
|
||||
void Taro.showModal({
|
||||
title: '解锁 VIP',
|
||||
content: hint || '开通 VIP 后可读全文并参与讨论',
|
||||
confirmText: '去开通',
|
||||
cancelText: '再看看',
|
||||
success: (r) => {
|
||||
if (r.confirm) goVipUnlock()
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export default function VipMemoDetailPage() {
|
||||
const router = useRouter()
|
||||
const id = String(router.params.id || '')
|
||||
@ -51,6 +68,9 @@ export default function VipMemoDetailPage() {
|
||||
const [memo, setMemo] = useState<MemoItem | null>(boot.memo)
|
||||
const [comments, setComments] = useState<MemoComment[]>(boot.comments)
|
||||
const [settings, setSettings] = useState<MemoSettings | null>(() => getCachedMemoSettings())
|
||||
const [isVip, setIsVip] = useState(false)
|
||||
const [freeScheme, setFreeScheme] = useState(() => isFreeVipScheme())
|
||||
const canAccess = isVip || freeScheme
|
||||
const [text, setText] = useState('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [refreshing, setRefreshing] = useState(!boot.memo)
|
||||
@ -60,10 +80,11 @@ export default function VipMemoDetailPage() {
|
||||
let cancelled = false
|
||||
;(async () => {
|
||||
try {
|
||||
const vip = isVipPaidLocal() ? true : await resolveVipAccess()
|
||||
if (!vip) {
|
||||
goPage('/pages/vip/index')
|
||||
return
|
||||
// 真实会员;内容权限另算(免费临时放行)
|
||||
const realVip = await resolveVipAccess(true)
|
||||
if (!cancelled) {
|
||||
setIsVip(realVip)
|
||||
setFreeScheme(isFreeVipScheme())
|
||||
}
|
||||
if (!cancelled && !memo) setRefreshing(true)
|
||||
const [s, data] = await Promise.all([
|
||||
@ -87,8 +108,22 @@ export default function VipMemoDetailPage() {
|
||||
}
|
||||
}, [id])
|
||||
|
||||
useEffect(() => {
|
||||
return subscribeRemoteConfig(() => {
|
||||
setFreeScheme(isFreeVipScheme())
|
||||
void resolveVipAccess(false).then(setIsVip)
|
||||
})
|
||||
}, [])
|
||||
|
||||
const locked = !!memo?.locked && !canAccess && !memo?.trial
|
||||
const unlockHint = settings?.unlockHint || '开通 VIP 后可读全文并参与讨论'
|
||||
|
||||
async function onLike() {
|
||||
if (!memo) return
|
||||
if (!canAccess) {
|
||||
promptUnlockVip(unlockHint)
|
||||
return
|
||||
}
|
||||
if (settings && !settings.canLike) {
|
||||
Taro.showToast({ title: '暂不允许点赞', icon: 'none' })
|
||||
return
|
||||
@ -102,6 +137,10 @@ export default function VipMemoDetailPage() {
|
||||
|
||||
async function onFavorite() {
|
||||
if (!memo) return
|
||||
if (!canAccess) {
|
||||
promptUnlockVip(unlockHint)
|
||||
return
|
||||
}
|
||||
if (settings && settings.canFavorite === false) {
|
||||
Taro.showToast({ title: '暂不允许收藏', icon: 'none' })
|
||||
return
|
||||
@ -115,6 +154,10 @@ export default function VipMemoDetailPage() {
|
||||
|
||||
async function onComment() {
|
||||
if (!memo || !text.trim() || busy) return
|
||||
if (!canAccess) {
|
||||
promptUnlockVip(unlockHint)
|
||||
return
|
||||
}
|
||||
if (settings && !settings.canComment) {
|
||||
Taro.showToast({ title: '暂不允许评论', icon: 'none' })
|
||||
return
|
||||
@ -189,6 +232,9 @@ export default function VipMemoDetailPage() {
|
||||
<View className="zd-badges">
|
||||
{memo.pinned ? <Text className="zd-badge pin">置顶</Text> : null}
|
||||
{memo.featured ? <Text className="zd-badge feat">精华</Text> : null}
|
||||
{memo.trial || memo.visibility === 'trial' ? (
|
||||
<Text className="zd-badge trial">试读</Text>
|
||||
) : null}
|
||||
</View>
|
||||
<Text className="zd-title">{memo.title || '未命名'}</Text>
|
||||
<View className="zd-byline">
|
||||
@ -201,24 +247,47 @@ export default function VipMemoDetailPage() {
|
||||
</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 })}
|
||||
/>
|
||||
))}
|
||||
{locked ? (
|
||||
<View className="zd-lock" onClick={() => goVipUnlock()}>
|
||||
{memo.excerpt ? (
|
||||
<Text className="zd-lock-excerpt">{memo.excerpt}</Text>
|
||||
) : null}
|
||||
<View className="zd-lock-ghost" aria-hidden>
|
||||
<View className="zd-lock-line w95" />
|
||||
<View className="zd-lock-line w88" />
|
||||
<View className="zd-lock-line w72" />
|
||||
<View className="zd-lock-line w90" />
|
||||
<View className="zd-lock-line w60" />
|
||||
<View className="zd-lock-mosaic" />
|
||||
</View>
|
||||
<Text className="zd-lock-title">全文需解锁 VIP</Text>
|
||||
<Text className="zd-lock-desc">开通后可读完整内容、评论互动、持续更新</Text>
|
||||
<View className="zd-lock-btn">
|
||||
<Text>解锁 VIP · 阅读全文</Text>
|
||||
</View>
|
||||
</View>
|
||||
) : null}
|
||||
) : (
|
||||
<>
|
||||
<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">
|
||||
@ -231,17 +300,19 @@ export default function VipMemoDetailPage() {
|
||||
) : 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>
|
||||
{!locked ? (
|
||||
<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>
|
||||
) : null}
|
||||
|
||||
<View className="zd-bar">
|
||||
<View className="zd-bar-acts">
|
||||
@ -252,16 +323,24 @@ export default function VipMemoDetailPage() {
|
||||
{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>
|
||||
{locked || !canAccess ? (
|
||||
<View className="zd-bar-unlock" onClick={() => goVipUnlock()}>
|
||||
<Text>解锁 VIP 参与讨论</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>
|
||||
)
|
||||
|
||||
@ -271,6 +271,23 @@
|
||||
background: rgba(94, 234, 212, 0.15);
|
||||
color: #5eead4;
|
||||
}
|
||||
.zk-badge.trial {
|
||||
background: rgba(96, 165, 250, 0.18);
|
||||
color: #93c5fd;
|
||||
}
|
||||
.zk-badge.lock {
|
||||
background: rgba(248, 113, 113, 0.16);
|
||||
color: #fca5a5;
|
||||
}
|
||||
.zk-nav-unlock {
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
color: #f59e0b;
|
||||
padding: 8px 4px;
|
||||
min-height: 44px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
.zk-card-title {
|
||||
display: block;
|
||||
font-size: 16px;
|
||||
@ -289,6 +306,30 @@
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
}
|
||||
.zk-card-excerpt.is-mosaic {
|
||||
filter: blur(3.5px);
|
||||
opacity: 0.55;
|
||||
user-select: none;
|
||||
}
|
||||
.zk-card.is-locked {
|
||||
position: relative;
|
||||
border-color: rgba(245, 158, 11, 0.22);
|
||||
}
|
||||
.zk-card-paywall {
|
||||
margin: 2px 0 8px;
|
||||
min-height: 32px;
|
||||
border-radius: 8px;
|
||||
background: rgba(245, 158, 11, 0.1);
|
||||
border: 1px dashed rgba(245, 158, 11, 0.35);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
.zk-card-paywall-txt {
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
color: #fbbf24;
|
||||
}
|
||||
.zk-card-meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@ -387,3 +428,168 @@
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
/* —— 非 VIP 付费诱导:马赛克骨架 —— */
|
||||
.zk-tease {
|
||||
position: relative;
|
||||
margin: 8px 0 24px;
|
||||
padding-bottom: 8px;
|
||||
}
|
||||
.zk-tease-head {
|
||||
padding: 4px 2px 14px;
|
||||
}
|
||||
.zk-tease-kicker {
|
||||
display: block;
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
color: #f59e0b;
|
||||
letter-spacing: 0.06em;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.zk-tease-title {
|
||||
display: block;
|
||||
font-size: 17px;
|
||||
font-weight: 800;
|
||||
color: #f1f5f9;
|
||||
line-height: 1.35;
|
||||
}
|
||||
.zk-tease-sub {
|
||||
display: block;
|
||||
margin-top: 4px;
|
||||
font-size: 12px;
|
||||
color: #64748b;
|
||||
line-height: 1.4;
|
||||
}
|
||||
.zk-tease-card {
|
||||
position: relative;
|
||||
margin-bottom: 10px;
|
||||
border-radius: 14px;
|
||||
overflow: hidden;
|
||||
border: 1px solid rgba(255, 255, 255, 0.06);
|
||||
background: #15151c;
|
||||
min-height: 108px;
|
||||
}
|
||||
.zk-tease-card.delay-1 {
|
||||
opacity: 0.92;
|
||||
}
|
||||
.zk-tease-card.delay-2 {
|
||||
opacity: 0.78;
|
||||
}
|
||||
.zk-tease-card-inner {
|
||||
padding: 14px 14px 16px;
|
||||
filter: blur(5px);
|
||||
transform: scale(1.02);
|
||||
user-select: none;
|
||||
}
|
||||
.zk-tease-badge {
|
||||
display: inline-block;
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
padding: 2px 6px;
|
||||
border-radius: 4px;
|
||||
background: rgba(245, 158, 11, 0.2);
|
||||
color: #fbbf24;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.zk-tease-card-t {
|
||||
display: block;
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
color: #e2e8f0;
|
||||
margin-bottom: 4px;
|
||||
line-height: 1.35;
|
||||
}
|
||||
.zk-tease-card-tag {
|
||||
display: block;
|
||||
font-size: 11px;
|
||||
color: #64748b;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.zk-tease-lines {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
.zk-tease-line {
|
||||
height: 8px;
|
||||
border-radius: 4px;
|
||||
background: linear-gradient(
|
||||
90deg,
|
||||
rgba(255, 255, 255, 0.06),
|
||||
rgba(245, 158, 11, 0.12),
|
||||
rgba(255, 255, 255, 0.06)
|
||||
);
|
||||
background-size: 200% 100%;
|
||||
animation: zk-shimmer 1.8s ease-in-out infinite;
|
||||
}
|
||||
.zk-tease-line.w90 {
|
||||
width: 90%;
|
||||
}
|
||||
.zk-tease-line.w70 {
|
||||
width: 70%;
|
||||
}
|
||||
.zk-tease-line.w55 {
|
||||
width: 55%;
|
||||
}
|
||||
@keyframes zk-shimmer {
|
||||
0% {
|
||||
background-position: 100% 0;
|
||||
}
|
||||
100% {
|
||||
background-position: -100% 0;
|
||||
}
|
||||
}
|
||||
.zk-tease-mosaic {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
pointer-events: none;
|
||||
background:
|
||||
repeating-linear-gradient(
|
||||
-28deg,
|
||||
rgba(12, 12, 15, 0.15) 0 3px,
|
||||
rgba(245, 158, 11, 0.05) 3px 6px
|
||||
),
|
||||
linear-gradient(180deg, rgba(12, 12, 15, 0.15), rgba(12, 12, 15, 0.55));
|
||||
backdrop-filter: blur(1px);
|
||||
}
|
||||
.zk-tease-lock {
|
||||
position: absolute;
|
||||
right: 14px;
|
||||
top: 14px;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: 50%;
|
||||
background: rgba(12, 12, 15, 0.72);
|
||||
border: 1px solid rgba(245, 158, 11, 0.35);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 14px;
|
||||
z-index: 2;
|
||||
}
|
||||
.zk-tease-fade {
|
||||
pointer-events: none;
|
||||
height: 56px;
|
||||
margin-top: -40px;
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
background: linear-gradient(180deg, transparent, #0c0c0f 85%);
|
||||
}
|
||||
.zk-tease-cta {
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
margin-top: 4px;
|
||||
height: 48px;
|
||||
border-radius: 12px;
|
||||
background: linear-gradient(135deg, #fbbf24, #f59e0b);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
box-shadow: 0 8px 24px rgba(245, 158, 11, 0.28);
|
||||
}
|
||||
.zk-tease-cta-txt {
|
||||
font-size: 15px;
|
||||
font-weight: 800;
|
||||
color: #0c0c0f;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
@ -1,20 +1,28 @@
|
||||
/**
|
||||
* VIP 知识社群 — 缓存秒开 · 后台静默刷新 · 无文案 loading
|
||||
* VIP 知识社群 — 未付费可进列表 / 试读;非试读提示解锁 VIP
|
||||
*/
|
||||
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 {
|
||||
goVipUnlock,
|
||||
isFreeVipScheme,
|
||||
resolveVipAccess,
|
||||
subscribeVipAccess,
|
||||
} from '@/utils/vipAccess'
|
||||
import { subscribeRemoteConfig } from '@/services/remoteConfig'
|
||||
import {
|
||||
createMemo,
|
||||
deleteMemo,
|
||||
favoriteMemo,
|
||||
getCachedMemoFeed,
|
||||
getCachedMemoRevision,
|
||||
getCachedMemoSettings,
|
||||
getCachedMemoTags,
|
||||
likeMemo,
|
||||
loadMemoHome,
|
||||
peekMemoContentRevision,
|
||||
uploadMemoImage,
|
||||
type FeedTab,
|
||||
type MemoItem,
|
||||
@ -51,6 +59,18 @@ function Spin() {
|
||||
)
|
||||
}
|
||||
|
||||
function promptUnlockVip(hint?: string) {
|
||||
void Taro.showModal({
|
||||
title: '解锁 VIP',
|
||||
content: hint || '开通 VIP 后可读全文并互动',
|
||||
confirmText: '去开通',
|
||||
cancelText: '再看看',
|
||||
success: (r) => {
|
||||
if (r.confirm) goVipUnlock()
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export default function VipMemoPage() {
|
||||
const cachedSettings = getCachedMemoSettings()
|
||||
const [items, setItems] = useState<MemoItem[]>(() => getCachedMemoFeed())
|
||||
@ -59,6 +79,10 @@ export default function VipMemoPage() {
|
||||
const [tab, setTab] = useState<FeedTab>('all')
|
||||
const [query, setQuery] = useState('')
|
||||
const [settings, setSettings] = useState<MemoSettings | null>(cachedSettings)
|
||||
const [isVip, setIsVip] = useState(false)
|
||||
const [freeScheme, setFreeScheme] = useState(() => isFreeVipScheme())
|
||||
/** 内容权限:真实 VIP 或后台临时免费;切收费后未开通立刻失效 */
|
||||
const canAccess = isVip || freeScheme
|
||||
const [draft, setDraft] = useState('')
|
||||
const [images, setImages] = useState<string[]>([])
|
||||
const [offline, setOffline] = useState(false)
|
||||
@ -66,6 +90,7 @@ export default function VipMemoPage() {
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [composerOpen, setComposerOpen] = useState(false)
|
||||
const bootRef = useRef(false)
|
||||
const revRef = useRef(getCachedMemoRevision())
|
||||
const safe = getSafeAreaMetrics()
|
||||
|
||||
async function refresh(opts?: { q?: string; tag?: string; tab?: FeedTab; soft?: boolean }) {
|
||||
@ -73,29 +98,39 @@ export default function VipMemoPage() {
|
||||
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
|
||||
}
|
||||
// 真实会员;勿用 settings.isVip(免费方案会为 true,切收费后仍会误留会员态)
|
||||
setIsVip(!!(await resolveVipAccess(true)))
|
||||
const home = await loadMemoHome({
|
||||
q: opts?.q ?? query,
|
||||
tag: opts?.tag ?? activeTag,
|
||||
tab: opts?.tab ?? tab,
|
||||
})
|
||||
setSettings(home.settings)
|
||||
if (home.settings.enabled === false) {
|
||||
setItems([])
|
||||
setTags([])
|
||||
setOffline(false)
|
||||
return
|
||||
}
|
||||
if (home.settings.canBrowse === false && !home.settings.isVip) {
|
||||
setItems([])
|
||||
setTags([])
|
||||
return
|
||||
}
|
||||
setTags(home.tags)
|
||||
setItems(home.items)
|
||||
setOffline(!!home.offline)
|
||||
} catch {
|
||||
if (!items.length) setItems(getCachedMemoFeed())
|
||||
setOffline(true)
|
||||
const rev = Number(home.settings.contentRevision || 0)
|
||||
if (rev) revRef.current = rev
|
||||
} catch (e) {
|
||||
const msg = String((e as Error).message || '')
|
||||
if (/社群暂未开放|开通 VIP 后可进入/i.test(msg)) {
|
||||
setItems([])
|
||||
if (/开通 VIP/i.test(msg)) promptUnlockVip(msg)
|
||||
} else if (!items.length) {
|
||||
setItems(getCachedMemoFeed())
|
||||
setOffline(true)
|
||||
}
|
||||
} finally {
|
||||
setRefreshing(false)
|
||||
}
|
||||
@ -107,14 +142,47 @@ export default function VipMemoPage() {
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
// H5 无 didShow 时兜底;weapp 已由 didShow 拉,跳过重复
|
||||
if (process.env.TARO_ENV === 'h5' && !bootRef.current) {
|
||||
bootRef.current = true
|
||||
void refresh({ soft: true })
|
||||
}
|
||||
}, [])
|
||||
|
||||
/** 近实时:每 3s 探 contentRevision,后台隐藏/发帖立刻重拉 */
|
||||
useEffect(() => {
|
||||
const tick = async () => {
|
||||
const rev = await peekMemoContentRevision()
|
||||
if (rev && rev !== revRef.current) {
|
||||
revRef.current = rev
|
||||
void refresh({ soft: true })
|
||||
}
|
||||
}
|
||||
const timer = setInterval(() => {
|
||||
void tick()
|
||||
}, 3000)
|
||||
return () => clearInterval(timer)
|
||||
}, [query, activeTag, tab])
|
||||
|
||||
/** 真实 VIP + 免费↔收费方案切换:立刻改内容权限 */
|
||||
useEffect(() => {
|
||||
const unsubVip = subscribeVipAccess(setIsVip)
|
||||
const unsubCfg = subscribeRemoteConfig(() => {
|
||||
setFreeScheme(isFreeVipScheme())
|
||||
void resolveVipAccess(false).then(setIsVip)
|
||||
})
|
||||
return () => {
|
||||
unsubVip()
|
||||
unsubCfg()
|
||||
}
|
||||
}, [])
|
||||
|
||||
const unlockHint = settings?.unlockHint || '开通 VIP 后可读全文并互动'
|
||||
|
||||
async function pickImages() {
|
||||
if (!canAccess) {
|
||||
promptUnlockVip(unlockHint)
|
||||
return
|
||||
}
|
||||
if (settings && settings.canUpload === false) {
|
||||
Taro.showToast({ title: '暂不允许上传', icon: 'none' })
|
||||
return
|
||||
@ -149,6 +217,10 @@ export default function VipMemoPage() {
|
||||
}
|
||||
|
||||
async function onPost() {
|
||||
if (!canAccess) {
|
||||
promptUnlockVip(unlockHint)
|
||||
return
|
||||
}
|
||||
if ((!draft.trim() && !images.length) || busy) return
|
||||
setBusy(true)
|
||||
try {
|
||||
@ -167,6 +239,10 @@ export default function VipMemoPage() {
|
||||
}
|
||||
|
||||
async function onLike(id: string) {
|
||||
if (!canAccess) {
|
||||
promptUnlockVip(unlockHint)
|
||||
return
|
||||
}
|
||||
if (settings && !settings.canLike) {
|
||||
Taro.showToast({ title: '暂不允许点赞', icon: 'none' })
|
||||
return
|
||||
@ -180,6 +256,10 @@ export default function VipMemoPage() {
|
||||
}
|
||||
|
||||
async function onFavorite(id: string) {
|
||||
if (!canAccess) {
|
||||
promptUnlockVip(unlockHint)
|
||||
return
|
||||
}
|
||||
if (settings && settings.canFavorite === false) {
|
||||
Taro.showToast({ title: '暂不允许收藏', icon: 'none' })
|
||||
return
|
||||
@ -207,10 +287,17 @@ export default function VipMemoPage() {
|
||||
}
|
||||
}
|
||||
|
||||
const canPost = !!settings?.canPost && !settings?.adminOnlyPost
|
||||
function openMemo(m: MemoItem) {
|
||||
// 列表可进详情:试读看全文,非试读详情页提示解锁
|
||||
goPage(`/pages/vip-memo-detail/index?id=${m.id}`)
|
||||
}
|
||||
|
||||
const canPost = !!settings?.canPost && !settings?.adminOnlyPost && canAccess
|
||||
const planetName = settings?.planetName || '知识社群'
|
||||
const planetDesc = settings?.planetDesc || '博主分享 · 会员阅读互动'
|
||||
const showBootSpin = refreshing && !items.length
|
||||
const closed = settings?.enabled === false
|
||||
const browseDenied = !closed && settings?.canBrowse === false && !canAccess
|
||||
|
||||
return (
|
||||
<View className="zk" style={{ paddingTop: `${safe.statusBarHeight}px` }}>
|
||||
@ -231,21 +318,56 @@ export default function VipMemoPage() {
|
||||
</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 }} />
|
||||
{refreshing && items.length ? (
|
||||
<View className="zk-spin zk-spin-sm">
|
||||
<View className="zk-spin-ring" />
|
||||
</View>
|
||||
) : null}
|
||||
{!isVip ? (
|
||||
<Text className="zk-nav-unlock" onClick={() => goVipUnlock()}>
|
||||
{canAccess ? '临时' : '开通'}
|
||||
</Text>
|
||||
) : (
|
||||
<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-badge">
|
||||
{isVip ? 'VIP · 知识星球' : canAccess ? '临时开放 · 知识星球' : '试读 · 知识星球'}
|
||||
</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}
|
||||
{!isVip && !canAccess && !closed ? (
|
||||
<Text className="zk-hero-notice" onClick={() => goVipUnlock()}>
|
||||
{settings?.allowTrialBrowse !== false
|
||||
? '未开通可看试读 · 点此解锁全文 →'
|
||||
: `${unlockHint} →`}
|
||||
</Text>
|
||||
) : null}
|
||||
{!isVip && canAccess && !closed ? (
|
||||
<Text className="zk-hero-notice">当前临时开放 · 切回收费后需开通 VIP</Text>
|
||||
) : null}
|
||||
{offline ? <Text className="zk-offline">离线 · 本地缓存</Text> : null}
|
||||
</View>
|
||||
|
||||
{closed || browseDenied ? (
|
||||
<View className="zk-empty">
|
||||
<Text>{closed ? '社群暂未开放' : unlockHint}</Text>
|
||||
{!closed ? (
|
||||
<Text className="zk-nav-unlock" onClick={() => goVipUnlock()} style={{ marginTop: 12 }}>
|
||||
去开通 VIP
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{!closed && !browseDenied ? (
|
||||
<>
|
||||
<View className="zk-search">
|
||||
<Input
|
||||
className="zk-search-input"
|
||||
@ -266,6 +388,10 @@ export default function VipMemoPage() {
|
||||
key={t.key}
|
||||
className={`zk-tab ${tab === t.key ? 'on' : ''}`}
|
||||
onClick={() => {
|
||||
if (t.key === 'mine' && !canAccess) {
|
||||
promptUnlockVip(unlockHint)
|
||||
return
|
||||
}
|
||||
setTab(t.key)
|
||||
void refresh({ tab: t.key, soft: false })
|
||||
}}
|
||||
@ -356,19 +482,33 @@ export default function VipMemoPage() {
|
||||
<View className="zk-list">
|
||||
{items.map((m) => {
|
||||
const cover = m.cover || (m.resources || []).find((r) => r.url)?.url
|
||||
const locked = !!m.locked && !canAccess
|
||||
return (
|
||||
<View
|
||||
key={m.id}
|
||||
className="zk-card"
|
||||
onClick={() => goPage(`/pages/vip-memo-detail/index?id=${m.id}`)}
|
||||
className={`zk-card${locked ? ' is-locked' : ''}`}
|
||||
onClick={() => openMemo(m)}
|
||||
>
|
||||
<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}
|
||||
{m.trial || m.visibility === 'trial' ? (
|
||||
<Text className="zk-badge trial">试读</Text>
|
||||
) : null}
|
||||
{locked ? <Text className="zk-badge lock">VIP</Text> : null}
|
||||
</View>
|
||||
<Text className="zk-card-title">{m.title || '未命名'}</Text>
|
||||
{m.excerpt ? <Text className="zk-card-excerpt">{m.excerpt}</Text> : null}
|
||||
{m.excerpt ? (
|
||||
<Text className={`zk-card-excerpt${locked ? ' is-mosaic' : ''}`}>
|
||||
{m.excerpt}
|
||||
</Text>
|
||||
) : null}
|
||||
{locked ? (
|
||||
<View className="zk-card-paywall">
|
||||
<Text className="zk-card-paywall-txt">🔒 会员全文 · 点此解锁</Text>
|
||||
</View>
|
||||
) : null}
|
||||
<View className="zk-card-meta">
|
||||
<Text className="zk-card-author">{m.nickname}</Text>
|
||||
<Text className="zk-card-dot">·</Text>
|
||||
@ -427,8 +567,47 @@ export default function VipMemoPage() {
|
||||
<Text>{tab === 'mine' ? '还没有收藏' : '暂无帖子'}</Text>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{/* 无内容权限时:试读列表下方马赛克骨架 + 付费诱导 */}
|
||||
{!canAccess && tab !== 'mine' ? (
|
||||
<View className="zk-tease" onClick={() => goVipUnlock()}>
|
||||
<View className="zk-tease-head">
|
||||
<Text className="zk-tease-kicker">VIP 专属干货</Text>
|
||||
<Text className="zk-tease-title">下面还有更多会员内容</Text>
|
||||
<Text className="zk-tease-sub">解锁后可读全文 · 评论互动 · 持续更新</Text>
|
||||
</View>
|
||||
{[
|
||||
{ t: '油管无人直播:从 0 到稳定日更', tag: '#油管 #设备', hot: '置顶干货' },
|
||||
{ t: 'TikTok 养号避坑:封号前必看', tag: '#TikTok #出海', hot: '精华' },
|
||||
{ t: '跨境收款通道对比与踩坑实录', tag: '#收款 #支付', hot: '高热' },
|
||||
].map((row, i) => (
|
||||
<View key={row.t} className={`zk-tease-card delay-${i}`} aria-hidden>
|
||||
<View className="zk-tease-card-inner">
|
||||
<Text className="zk-tease-badge">{row.hot}</Text>
|
||||
<Text className="zk-tease-card-t">{row.t}</Text>
|
||||
<Text className="zk-tease-card-tag">{row.tag}</Text>
|
||||
<View className="zk-tease-lines">
|
||||
<View className="zk-tease-line w90" />
|
||||
<View className="zk-tease-line w70" />
|
||||
<View className="zk-tease-line w55" />
|
||||
</View>
|
||||
</View>
|
||||
<View className="zk-tease-mosaic" />
|
||||
<View className="zk-tease-lock">
|
||||
<Text>🔒</Text>
|
||||
</View>
|
||||
</View>
|
||||
))}
|
||||
<View className="zk-tease-fade" />
|
||||
<View className="zk-tease-cta">
|
||||
<Text className="zk-tease-cta-txt">解锁 VIP · 查看全部干货</Text>
|
||||
</View>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
)}
|
||||
</>
|
||||
) : null}
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
@ -1,27 +1,31 @@
|
||||
/* 真实 px:weapp pxExclude — 确认订单表单 */
|
||||
.vsd {
|
||||
min-height: 100vh;
|
||||
background: #0c0c0f;
|
||||
color: #e8eef7;
|
||||
padding-bottom: 96px;
|
||||
padding-bottom: calc(88px + env(safe-area-inset-bottom));
|
||||
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;
|
||||
padding: 72px 16px;
|
||||
color: #64748b;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.vsd-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
height: 44px;
|
||||
padding: 0 4px;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
.vsd-back {
|
||||
|
||||
.vsd-back,
|
||||
.vsd-head-spacer {
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
display: flex;
|
||||
@ -29,133 +33,262 @@
|
||||
justify-content: center;
|
||||
color: #f59e0b;
|
||||
font-size: 18px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.vsd-title {
|
||||
flex: 1;
|
||||
text-align: center;
|
||||
font-weight: 600;
|
||||
font-size: 16px;
|
||||
line-height: 44px;
|
||||
}
|
||||
.vsd-hero {
|
||||
padding: 24px 20px 12px;
|
||||
|
||||
.vsd-body {
|
||||
padding: 8px 16px 0;
|
||||
}
|
||||
|
||||
.vsd-goods {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
padding: 8px 0 18px;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
|
||||
.vsd-goods-emoji {
|
||||
width: 52px;
|
||||
height: 52px;
|
||||
border-radius: 10px;
|
||||
background: rgba(245, 158, 11, 0.1);
|
||||
font-size: 26px;
|
||||
flex-shrink: 0;
|
||||
text-align: center;
|
||||
line-height: 52px;
|
||||
}
|
||||
.vsd-emoji {
|
||||
display: block;
|
||||
font-size: 40px;
|
||||
line-height: 1;
|
||||
margin-bottom: 12px;
|
||||
|
||||
.vsd-goods-main {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
.vsd-name {
|
||||
|
||||
.vsd-goods-title {
|
||||
display: block;
|
||||
font-size: 18px;
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
line-height: 1.35;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
.vsd-desc {
|
||||
|
||||
.vsd-goods-sub {
|
||||
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 {
|
||||
margin-top: 4px;
|
||||
font-size: 12px;
|
||||
color: #64748b;
|
||||
font-weight: 400;
|
||||
line-height: 1.4;
|
||||
}
|
||||
.vsd-form {
|
||||
margin: 8px 16px;
|
||||
padding: 14px;
|
||||
border-radius: 12px;
|
||||
background: #15151c;
|
||||
border: 1px solid rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
.vsd-row {
|
||||
|
||||
.vsd-goods-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.vsd-row.col {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
margin-top: 10px;
|
||||
gap: 8px;
|
||||
}
|
||||
.vsd-label {
|
||||
font-size: 13px;
|
||||
color: #cbd5e1;
|
||||
font-weight: 500;
|
||||
|
||||
.vsd-goods-price {
|
||||
color: #f59e0b;
|
||||
font-size: 20px;
|
||||
font-weight: 800;
|
||||
line-height: 1.2;
|
||||
}
|
||||
.vsd-qty {
|
||||
|
||||
.vsd-stepper {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
background: #1a1a22;
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.vsd-qty-btn {
|
||||
|
||||
.vsd-step {
|
||||
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;
|
||||
|
||||
.vsd-step.is-off {
|
||||
opacity: 0.3;
|
||||
}
|
||||
|
||||
.vsd-step-n {
|
||||
min-width: 32px;
|
||||
text-align: center;
|
||||
font-weight: 700;
|
||||
font-size: 14px;
|
||||
line-height: 36px;
|
||||
}
|
||||
|
||||
.vsd-goods-meta {
|
||||
display: block;
|
||||
margin-top: 6px;
|
||||
font-size: 11px;
|
||||
color: #475569;
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
.vsd-form {
|
||||
padding: 20px 0 8px;
|
||||
}
|
||||
|
||||
.vsd-form-title {
|
||||
display: block;
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
margin-bottom: 16px;
|
||||
color: #f1f5f9;
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
.vsd-field {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.vsd-label {
|
||||
display: block;
|
||||
font-size: 12px;
|
||||
color: #94a3b8;
|
||||
margin-bottom: 8px;
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
/* 小程序 Input:外层定高 + 内层 height/line-height 对齐,避免 placeholder 裁切 */
|
||||
.vsd-control {
|
||||
height: 48px;
|
||||
border-radius: 10px;
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
white-space: pre-wrap;
|
||||
font-weight: 400;
|
||||
background: #1a1a22;
|
||||
border: 1px solid rgba(255, 255, 255, 0.08);
|
||||
padding: 0 14px;
|
||||
box-sizing: border-box;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
overflow: hidden;
|
||||
}
|
||||
.vsd-addr-hint {
|
||||
color: #f59e0b;
|
||||
font-size: 13px;
|
||||
|
||||
.vsd-control.is-err {
|
||||
border-color: rgba(248, 113, 113, 0.7);
|
||||
}
|
||||
.vsd-cta-wrap {
|
||||
|
||||
.vsd-input {
|
||||
width: 100%;
|
||||
height: 48px;
|
||||
min-height: 48px;
|
||||
line-height: 48px;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
border: none;
|
||||
background: transparent;
|
||||
font-size: 15px;
|
||||
color: #e8eef7;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.vsd-picker {
|
||||
width: 100%;
|
||||
height: 48px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.vsd-picker-txt {
|
||||
flex: 1;
|
||||
font-size: 15px;
|
||||
line-height: 48px;
|
||||
color: #e8eef7;
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.vsd-picker-txt.is-placeholder {
|
||||
color: #64748b;
|
||||
}
|
||||
|
||||
.vsd-picker-chev {
|
||||
flex-shrink: 0;
|
||||
margin-left: 8px;
|
||||
color: #64748b;
|
||||
font-size: 18px;
|
||||
line-height: 48px;
|
||||
}
|
||||
|
||||
.vsd-err {
|
||||
display: block;
|
||||
margin-top: 6px;
|
||||
font-size: 12px;
|
||||
color: #f87171;
|
||||
line-height: 1.35;
|
||||
min-height: 16px;
|
||||
}
|
||||
|
||||
.vsd-bar {
|
||||
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);
|
||||
z-index: 20;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 12px 16px calc(12px + env(safe-area-inset-bottom));
|
||||
background: #0c0c0f;
|
||||
border-top: 1px solid rgba(255, 255, 255, 0.06);
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.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;
|
||||
|
||||
.vsd-bar-left {
|
||||
flex-shrink: 0;
|
||||
min-width: 96px;
|
||||
}
|
||||
|
||||
.vsd-bar-label {
|
||||
display: block;
|
||||
font-size: 11px;
|
||||
color: #64748b;
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.vsd-bar-price {
|
||||
display: block;
|
||||
font-size: 20px;
|
||||
font-weight: 800;
|
||||
color: #f59e0b;
|
||||
line-height: 1.2;
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
/* 不用原生 Button,避免微信默认 padding 导致文案上偏 */
|
||||
.vsd-pay {
|
||||
flex: 1;
|
||||
height: 48px;
|
||||
border-radius: 12px;
|
||||
background: #f59e0b;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.vsd-pay.is-busy {
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.vsd-pay-txt {
|
||||
font-size: 16px;
|
||||
font-weight: 800;
|
||||
color: #0c0c0f;
|
||||
line-height: 1;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
@ -1,13 +1,12 @@
|
||||
/**
|
||||
* 商品详情 + 下单(虚拟邮箱 / 实体 chooseAddress)
|
||||
* 确认订单 — 手填收货信息;输入即时校验 + 支付前二次校验
|
||||
*/
|
||||
import { useEffect, useState } from 'react'
|
||||
import { View, Text, Input, Button } from '@tarojs/components'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { View, Text, Input, Picker } from '@tarojs/components'
|
||||
import Taro, { useRouter } from '@tarojs/taro'
|
||||
import { goPage } from '@/utils/nav'
|
||||
import { resolveVipAccess } from '@/utils/vipAccess'
|
||||
import { goVipUnlock, isVipPaidLocal, resolveVipContentAccess } from '@/utils/vipAccess'
|
||||
import {
|
||||
chooseShopAddress,
|
||||
createShopPayOrder,
|
||||
devConfirmShopOrder,
|
||||
loadShopProduct,
|
||||
@ -17,6 +16,81 @@ import type { ShopProduct } from '@/data/vipStoreCatalog'
|
||||
import { getSafeAreaMetrics } from '@/utils/safeArea'
|
||||
import './index.scss'
|
||||
|
||||
const ADDR_CACHE = 'nomadro_shop_addr_draft_v3'
|
||||
const PLACEHOLDER_STYLE = 'color:#64748b;font-size:15px;line-height:48px;'
|
||||
|
||||
type AddrDraft = {
|
||||
userName: string
|
||||
telNumber: string
|
||||
region: string[]
|
||||
detailInfo: string
|
||||
}
|
||||
|
||||
type FieldKey = 'userName' | 'telNumber' | 'region' | 'detailInfo' | 'email'
|
||||
|
||||
function loadAddrDraft(): AddrDraft {
|
||||
try {
|
||||
const raw = Taro.getStorageSync(ADDR_CACHE)
|
||||
if (raw && typeof raw === 'object') {
|
||||
const d = raw as AddrDraft
|
||||
return {
|
||||
userName: String(d.userName || ''),
|
||||
telNumber: String(d.telNumber || '').replace(/\D/g, '').slice(0, 11),
|
||||
region: Array.isArray(d.region) ? d.region.map(String) : [],
|
||||
detailInfo: String(d.detailInfo || ''),
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
return { userName: '', telNumber: '', region: [], detailInfo: '' }
|
||||
}
|
||||
|
||||
function saveAddrDraft(d: AddrDraft) {
|
||||
try {
|
||||
Taro.setStorageSync(ADDR_CACHE, d)
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
function validateName(v: string): string {
|
||||
const s = v.trim()
|
||||
if (!s) return '请填写收货人'
|
||||
if (s.length < 2) return '姓名至少 2 个字'
|
||||
if (s.length > 20) return '姓名最多 20 个字'
|
||||
if (!/^[\u4e00-\u9fa5a-zA-Z·\s]+$/.test(s)) return '姓名仅支持中英文'
|
||||
return ''
|
||||
}
|
||||
|
||||
function validatePhone(v: string): string {
|
||||
const s = v.trim()
|
||||
if (!s) return '请填写手机号'
|
||||
if (!/^1\d{10}$/.test(s)) return '请输入 11 位有效手机号'
|
||||
return ''
|
||||
}
|
||||
|
||||
function validateRegion(region: string[]): string {
|
||||
if (!region.length || !region[0]) return '请选择省市区'
|
||||
if (region.length < 2) return '请选择完整省市区'
|
||||
return ''
|
||||
}
|
||||
|
||||
function validateDetail(v: string): string {
|
||||
const s = v.trim()
|
||||
if (!s) return '请填写详细地址'
|
||||
if (s.length < 5) return '详细地址至少 5 个字'
|
||||
if (s.length > 80) return '详细地址过长'
|
||||
return ''
|
||||
}
|
||||
|
||||
function validateEmail(v: string): string {
|
||||
const s = v.trim()
|
||||
if (!s) return '请填写接收邮箱'
|
||||
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s)) return '邮箱格式不正确'
|
||||
return ''
|
||||
}
|
||||
|
||||
function invokeVirtualPayment(payData: {
|
||||
signData: string
|
||||
mode: string
|
||||
@ -42,25 +116,39 @@ function invokeVirtualPayment(payData: {
|
||||
})
|
||||
}
|
||||
|
||||
function goBackStore() {
|
||||
Taro.navigateBack({
|
||||
fail: () => goPage('/pages/vip-store/index'),
|
||||
})
|
||||
}
|
||||
|
||||
export default function VipStoreDetailPage() {
|
||||
const router = useRouter()
|
||||
const id = String(router.params.id || '')
|
||||
const [product, setProduct] = useState<ShopProduct | null>(null)
|
||||
const [isVip, setIsVip] = useState(() => isVipPaidLocal())
|
||||
const [email, setEmail] = useState('')
|
||||
const [address, setAddress] = useState<ShopAddress | null>(null)
|
||||
const [draft, setDraft] = useState<AddrDraft>(() => loadAddrDraft())
|
||||
const [qty, setQty] = useState(1)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [touched, setTouched] = useState<Partial<Record<FieldKey, boolean>>>({})
|
||||
const [errors, setErrors] = useState<Partial<Record<FieldKey, string>>>({})
|
||||
const safe = getSafeAreaMetrics()
|
||||
|
||||
useEffect(() => {
|
||||
void (async () => {
|
||||
const access = await resolveVipAccess()
|
||||
const access = await resolveVipContentAccess(true)
|
||||
setIsVip(!!access)
|
||||
if (!access) {
|
||||
Taro.showModal({
|
||||
title: 'VIP 专属',
|
||||
content: '开通 VIP 后可下单',
|
||||
showCancel: false,
|
||||
success: () => goPage('/pages/vip/index'),
|
||||
title: '解锁 VIP',
|
||||
content: '开通 VIP 后可自助下单',
|
||||
confirmText: '去开通',
|
||||
cancelText: '返回',
|
||||
success: (r) => {
|
||||
if (r.confirm) goVipUnlock()
|
||||
else goBackStore()
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
@ -73,29 +161,100 @@ export default function VipStoreDetailPage() {
|
||||
})()
|
||||
}, [id])
|
||||
|
||||
async function pickAddress() {
|
||||
try {
|
||||
const addr = await chooseShopAddress()
|
||||
setAddress(addr)
|
||||
} catch (e) {
|
||||
Taro.showToast({ title: (e as Error).message || '地址获取失败', icon: 'none' })
|
||||
function fieldMsg(key: FieldKey, next: AddrDraft): string {
|
||||
if (key === 'userName') return validateName(next.userName)
|
||||
if (key === 'telNumber') return validatePhone(next.telNumber)
|
||||
if (key === 'region') return validateRegion(next.region)
|
||||
return validateDetail(next.detailInfo)
|
||||
}
|
||||
|
||||
/** 输入时强制校验(过滤/写错误态),失焦或支付时才展示红字 */
|
||||
function updateDraft(patch: Partial<AddrDraft>, key: FieldKey, reveal = false) {
|
||||
const next = { ...draft, ...patch }
|
||||
setDraft(next)
|
||||
saveAddrDraft(next)
|
||||
const msg = fieldMsg(key, next)
|
||||
setErrors((prev) => ({ ...prev, [key]: msg }))
|
||||
if (reveal) setTouched((prev) => ({ ...prev, [key]: true }))
|
||||
}
|
||||
|
||||
function onBlurField(key: FieldKey) {
|
||||
setTouched((prev) => ({ ...prev, [key]: true }))
|
||||
setErrors((prev) => ({ ...prev, [key]: fieldMsg(key, draft) }))
|
||||
}
|
||||
|
||||
const regionLabel = useMemo(() => {
|
||||
if (draft.region.length >= 2) return draft.region.filter(Boolean).join(' ')
|
||||
return ''
|
||||
}, [draft.region])
|
||||
|
||||
function validateAll(physical: boolean): Partial<Record<FieldKey, string>> {
|
||||
if (!physical) {
|
||||
const emailErr = validateEmail(email)
|
||||
return emailErr ? { email: emailErr } : {}
|
||||
}
|
||||
return {
|
||||
userName: validateName(draft.userName),
|
||||
telNumber: validatePhone(draft.telNumber),
|
||||
region: validateRegion(draft.region),
|
||||
detailInfo: validateDetail(draft.detailInfo),
|
||||
}
|
||||
}
|
||||
|
||||
function buildAddress(): ShopAddress | null {
|
||||
const userName = draft.userName.trim()
|
||||
const telNumber = draft.telNumber.trim()
|
||||
const detailInfo = draft.detailInfo.trim()
|
||||
const [provinceName = '', cityName = '', countyName = ''] = draft.region
|
||||
if (validateName(userName) || validatePhone(telNumber) || validateRegion(draft.region) || validateDetail(detailInfo)) {
|
||||
return null
|
||||
}
|
||||
return {
|
||||
userName,
|
||||
telNumber,
|
||||
provinceName,
|
||||
cityName: cityName || provinceName,
|
||||
countyName: countyName || cityName || '',
|
||||
detailInfo,
|
||||
}
|
||||
}
|
||||
|
||||
async function onBuy() {
|
||||
if (!product || busy) return
|
||||
if (!isVip) {
|
||||
goVipUnlock()
|
||||
return
|
||||
}
|
||||
if (product.stock < qty) {
|
||||
Taro.showToast({ title: '库存不足', icon: 'none' })
|
||||
return
|
||||
}
|
||||
if (product.goodsType === 'virtual' && !email.trim()) {
|
||||
Taro.showToast({ title: '请填写邮箱', icon: 'none' })
|
||||
|
||||
const physical = product.goodsType === 'physical'
|
||||
const nextErrors = validateAll(physical)
|
||||
setErrors(nextErrors)
|
||||
setTouched({
|
||||
userName: true,
|
||||
telNumber: true,
|
||||
region: true,
|
||||
detailInfo: true,
|
||||
email: true,
|
||||
})
|
||||
const firstErr = Object.values(nextErrors).find((m) => !!m)
|
||||
if (firstErr) {
|
||||
Taro.showToast({ title: firstErr, icon: 'none' })
|
||||
return
|
||||
}
|
||||
if (product.goodsType === 'physical' && !address) {
|
||||
Taro.showToast({ title: '请选择收货地址', icon: 'none' })
|
||||
return
|
||||
|
||||
let address: ShopAddress | null = null
|
||||
if (physical) {
|
||||
address = buildAddress()
|
||||
if (!address) {
|
||||
Taro.showToast({ title: '请完善收货信息', icon: 'none' })
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
setBusy(true)
|
||||
try {
|
||||
const pay = await createShopPayOrder({
|
||||
@ -130,89 +289,187 @@ export default function VipStoreDetailPage() {
|
||||
if (!product) {
|
||||
return (
|
||||
<View className="vsd" style={{ paddingTop: `${safe.statusBarHeight}px` }}>
|
||||
<Text className="vsd-loading">加载中…</Text>
|
||||
<View className="vsd-head">
|
||||
<View className="vsd-back" onClick={goBackStore}>
|
||||
<Text>←</Text>
|
||||
</View>
|
||||
<Text className="vsd-title">确认订单</Text>
|
||||
<View className="vsd-head-spacer" />
|
||||
</View>
|
||||
<Text className="vsd-loading">{isVip ? '加载中…' : '校验会员中…'}</Text>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
const totalYuan = ((product.priceFen * qty) / 100).toFixed(2)
|
||||
const show = (key: FieldKey) => !!(touched[key] && errors[key])
|
||||
|
||||
return (
|
||||
<View className="vsd" style={{ paddingTop: `${safe.statusBarHeight}px` }}>
|
||||
<View className="vsd-head">
|
||||
<View className="vsd-back" onClick={() => goPage('/pages/vip-store/index')}>
|
||||
<View className="vsd-back" onClick={goBackStore}>
|
||||
<Text>←</Text>
|
||||
</View>
|
||||
<Text className="vsd-title">下单</Text>
|
||||
<View style={{ width: 44 }} />
|
||||
<Text className="vsd-title">确认订单</Text>
|
||||
<View className="vsd-head-spacer" />
|
||||
</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))}
|
||||
>
|
||||
+
|
||||
<View className="vsd-body">
|
||||
<View className="vsd-goods">
|
||||
<Text className="vsd-goods-emoji">{product.coverEmoji || '🛒'}</Text>
|
||||
<View className="vsd-goods-main">
|
||||
<Text className="vsd-goods-title">{product.title}</Text>
|
||||
<Text className="vsd-goods-sub">{product.desc}</Text>
|
||||
<View className="vsd-goods-row">
|
||||
<Text className="vsd-goods-price">¥{(product.priceFen / 100).toFixed(2)}</Text>
|
||||
<View className="vsd-stepper">
|
||||
<Text
|
||||
className={`vsd-step${qty <= 1 ? ' is-off' : ''}`}
|
||||
onClick={() => setQty((q) => Math.max(1, q - 1))}
|
||||
>
|
||||
−
|
||||
</Text>
|
||||
<Text className="vsd-step-n">{qty}</Text>
|
||||
<Text
|
||||
className={`vsd-step${qty >= product.stock ? ' is-off' : ''}`}
|
||||
onClick={() => setQty((q) => Math.min(product.stock || 1, q + 1))}
|
||||
>
|
||||
+
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
<Text className="vsd-goods-meta">
|
||||
{product.goodsType === 'virtual' ? '虚拟发卡' : '实体发货'} · 库存 {product.stock}
|
||||
</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 className="vsd-form">
|
||||
<Text className="vsd-form-title">接收邮箱</Text>
|
||||
<View className="vsd-field">
|
||||
<Text className="vsd-label">邮箱</Text>
|
||||
<View className={`vsd-control${show('email') ? ' is-err' : ''}`}>
|
||||
<Input
|
||||
className="vsd-input"
|
||||
type="text"
|
||||
placeholder="name@example.com"
|
||||
placeholderStyle={PLACEHOLDER_STYLE}
|
||||
value={email}
|
||||
onInput={(e) => {
|
||||
const v = e.detail.value
|
||||
setEmail(v)
|
||||
setErrors((prev) => ({ ...prev, email: validateEmail(v) }))
|
||||
}}
|
||||
onBlur={() => {
|
||||
setTouched((prev) => ({ ...prev, email: true }))
|
||||
setErrors((prev) => ({ ...prev, email: validateEmail(email) }))
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
{show('email') ? <Text className="vsd-err">{errors.email}</Text> : null}
|
||||
</View>
|
||||
</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 className="vsd-form">
|
||||
<Text className="vsd-form-title">收货信息</Text>
|
||||
|
||||
<View className="vsd-field">
|
||||
<Text className="vsd-label">收货人</Text>
|
||||
<View className={`vsd-control${show('userName') ? ' is-err' : ''}`}>
|
||||
<Input
|
||||
className="vsd-input"
|
||||
type="text"
|
||||
maxlength={20}
|
||||
placeholder="请输入真实姓名"
|
||||
placeholderStyle={PLACEHOLDER_STYLE}
|
||||
value={draft.userName}
|
||||
onInput={(e) => updateDraft({ userName: e.detail.value }, 'userName')}
|
||||
onBlur={() => onBlurField('userName')}
|
||||
/>
|
||||
</View>
|
||||
{show('userName') ? <Text className="vsd-err">{errors.userName}</Text> : null}
|
||||
</View>
|
||||
|
||||
<View className="vsd-field">
|
||||
<Text className="vsd-label">手机号</Text>
|
||||
<View className={`vsd-control${show('telNumber') ? ' is-err' : ''}`}>
|
||||
<Input
|
||||
className="vsd-input"
|
||||
type="digit"
|
||||
maxlength={11}
|
||||
placeholder="请输入 11 位手机号"
|
||||
placeholderStyle={PLACEHOLDER_STYLE}
|
||||
value={draft.telNumber}
|
||||
onInput={(e) => {
|
||||
const tel = String(e.detail.value || '')
|
||||
.replace(/\D/g, '')
|
||||
.slice(0, 11)
|
||||
updateDraft({ telNumber: tel }, 'telNumber')
|
||||
}}
|
||||
onBlur={() => onBlurField('telNumber')}
|
||||
/>
|
||||
</View>
|
||||
{show('telNumber') ? <Text className="vsd-err">{errors.telNumber}</Text> : null}
|
||||
</View>
|
||||
|
||||
<View className="vsd-field">
|
||||
<Text className="vsd-label">所在地区</Text>
|
||||
<Picker
|
||||
mode="region"
|
||||
value={draft.region.length ? draft.region : ['广东省', '深圳市', '南山区']}
|
||||
onChange={(e) => {
|
||||
const v = (e.detail.value || []) as string[]
|
||||
updateDraft({ region: v }, 'region', true)
|
||||
}}
|
||||
>
|
||||
<View className={`vsd-control${show('region') ? ' is-err' : ''}`}>
|
||||
<View className="vsd-picker">
|
||||
<Text className={`vsd-picker-txt${regionLabel ? '' : ' is-placeholder'}`}>
|
||||
{regionLabel || '请选择省 / 市 / 区'}
|
||||
</Text>
|
||||
<Text className="vsd-picker-chev">›</Text>
|
||||
</View>
|
||||
</View>
|
||||
</Picker>
|
||||
{show('region') ? <Text className="vsd-err">{errors.region}</Text> : null}
|
||||
</View>
|
||||
|
||||
<View className="vsd-field">
|
||||
<Text className="vsd-label">详细地址</Text>
|
||||
<View className={`vsd-control${show('detailInfo') ? ' is-err' : ''}`}>
|
||||
<Input
|
||||
className="vsd-input"
|
||||
type="text"
|
||||
maxlength={80}
|
||||
placeholder="街道、门牌号、楼栋单元"
|
||||
placeholderStyle={PLACEHOLDER_STYLE}
|
||||
value={draft.detailInfo}
|
||||
onInput={(e) => updateDraft({ detailInfo: e.detail.value }, 'detailInfo')}
|
||||
onBlur={() => onBlurField('detailInfo')}
|
||||
/>
|
||||
</View>
|
||||
{show('detailInfo') ? <Text className="vsd-err">{errors.detailInfo}</Text> : null}
|
||||
</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 className="vsd-bar">
|
||||
<View className="vsd-bar-left">
|
||||
<Text className="vsd-bar-label">合计</Text>
|
||||
<Text className="vsd-bar-price">¥{totalYuan}</Text>
|
||||
</View>
|
||||
<View
|
||||
className={`vsd-pay${busy ? ' is-busy' : ''}`}
|
||||
onClick={() => {
|
||||
if (!busy) void onBuy()
|
||||
}}
|
||||
>
|
||||
<Text className="vsd-pay-txt">
|
||||
{busy ? '支付中…' : isVip ? '立即支付' : '解锁 VIP'}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
)
|
||||
|
||||
@ -59,6 +59,15 @@
|
||||
line-height: 1.5;
|
||||
font-weight: 400;
|
||||
}
|
||||
.vs-hero-vip {
|
||||
display: block;
|
||||
margin-top: 10px;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
color: #f59e0b;
|
||||
min-height: 36px;
|
||||
line-height: 36px;
|
||||
}
|
||||
.vs-tabs {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
@ -157,6 +166,88 @@
|
||||
font-weight: 400;
|
||||
color: #64748b;
|
||||
}
|
||||
.vs-card.is-locked .vs-card-img,
|
||||
.vs-card.is-locked .vs-card-emoji {
|
||||
filter: blur(3px) saturate(0.55);
|
||||
opacity: 0.72;
|
||||
}
|
||||
.vs-cover-mosaic {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background:
|
||||
repeating-linear-gradient(
|
||||
-32deg,
|
||||
rgba(12, 12, 15, 0.08) 0 3px,
|
||||
rgba(245, 158, 11, 0.06) 3px 6px
|
||||
),
|
||||
rgba(12, 12, 15, 0.28);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
pointer-events: none;
|
||||
}
|
||||
.vs-cover-lock {
|
||||
font-size: 18px;
|
||||
line-height: 1;
|
||||
opacity: 0.9;
|
||||
}
|
||||
.vs-mosaic {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
border-radius: 6px;
|
||||
background:
|
||||
repeating-linear-gradient(
|
||||
115deg,
|
||||
#2a2a34 0 4px,
|
||||
#1a1a22 4px 8px
|
||||
);
|
||||
border: 1px solid rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
.vs-mosaic::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: linear-gradient(
|
||||
90deg,
|
||||
transparent 0%,
|
||||
rgba(255, 255, 255, 0.06) 45%,
|
||||
transparent 100%
|
||||
);
|
||||
animation: vs-shimmer 1.8s ease-in-out infinite;
|
||||
}
|
||||
.vs-mosaic-price {
|
||||
min-width: 52px;
|
||||
height: 22px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 0 8px;
|
||||
}
|
||||
.vs-mosaic-stock {
|
||||
min-width: 48px;
|
||||
height: 18px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 0 6px;
|
||||
}
|
||||
.vs-mosaic-txt {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
color: rgba(241, 245, 249, 0.35);
|
||||
letter-spacing: 0.04em;
|
||||
filter: blur(2.5px);
|
||||
}
|
||||
@keyframes vs-shimmer {
|
||||
0% {
|
||||
transform: translateX(-60%);
|
||||
}
|
||||
100% {
|
||||
transform: translateX(60%);
|
||||
}
|
||||
}
|
||||
.vs-empty {
|
||||
grid-column: 1 / -1;
|
||||
text-align: center;
|
||||
|
||||
@ -5,7 +5,14 @@ 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 {
|
||||
goVipUnlock,
|
||||
isFreeVipScheme,
|
||||
isVipPaidLocal,
|
||||
resolveVipAccess,
|
||||
subscribeVipAccess,
|
||||
} from '@/utils/vipAccess'
|
||||
import { subscribeRemoteConfig } from '@/services/remoteConfig'
|
||||
import { loadShopCatalog } from '@/services/shopApi'
|
||||
import type { ShopCatalog } from '@/data/vipStoreCatalog'
|
||||
import { LOCAL_SHOP_CATALOG } from '@/data/vipStoreCatalog'
|
||||
@ -16,14 +23,16 @@ 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)
|
||||
// 真实会员态;免费方案=临时放行,不写 unlocks
|
||||
const [isVip, setIsVip] = useState(() => isVipPaidLocal())
|
||||
const [freeScheme, setFreeScheme] = useState(() => isFreeVipScheme())
|
||||
const canAccess = isVip || freeScheme
|
||||
const safe = getSafeAreaMetrics()
|
||||
|
||||
async function refresh() {
|
||||
setLoading(true)
|
||||
try {
|
||||
const access = await resolveVipAccess()
|
||||
setIsVip(!!access)
|
||||
setIsVip(!!(await resolveVipAccess(true)))
|
||||
const data = await loadShopCatalog()
|
||||
setCatalog(data)
|
||||
} finally {
|
||||
@ -36,7 +45,15 @@ export default function VipStorePage() {
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
void refresh()
|
||||
const unsubVip = subscribeVipAccess(setIsVip)
|
||||
const unsubCfg = subscribeRemoteConfig(() => {
|
||||
setFreeScheme(isFreeVipScheme())
|
||||
void resolveVipAccess(false).then(setIsVip)
|
||||
})
|
||||
return () => {
|
||||
unsubVip()
|
||||
unsubCfg()
|
||||
}
|
||||
}, [])
|
||||
|
||||
const products = useMemo(() => {
|
||||
@ -46,17 +63,18 @@ export default function VipStorePage() {
|
||||
|
||||
function onLocked() {
|
||||
Taro.showModal({
|
||||
title: 'VIP 专属',
|
||||
content: '开通 VIP 后解锁设备自助下单',
|
||||
title: '解锁 VIP',
|
||||
content: '开通 VIP 后可自助下单设备',
|
||||
confirmText: '去开通',
|
||||
cancelText: '再看看',
|
||||
success: (r) => {
|
||||
if (r.confirm) goPage('/pages/vip/index')
|
||||
if (r.confirm) goVipUnlock()
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
function openProduct(id: string) {
|
||||
if (!isVip) {
|
||||
if (!canAccess) {
|
||||
onLocked()
|
||||
return
|
||||
}
|
||||
@ -66,13 +84,18 @@ export default function VipStorePage() {
|
||||
return (
|
||||
<View className="vs" style={{ paddingTop: `${safe.statusBarHeight}px` }}>
|
||||
<View className="vs-head">
|
||||
<View className="vs-back" onClick={() => goPage('/pages/vip/index')}>
|
||||
<View
|
||||
className="vs-back"
|
||||
onClick={() =>
|
||||
Taro.navigateBack({ fail: () => 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())}
|
||||
onClick={() => (canAccess ? goPage('/pages/vip-store-orders/index') : onLocked())}
|
||||
>
|
||||
<Text>订单</Text>
|
||||
</View>
|
||||
@ -87,6 +110,11 @@ export default function VipStorePage() {
|
||||
<View className="vs-hero">
|
||||
<Text className="vs-hero-h">今天需要一点什么?</Text>
|
||||
<Text className="vs-hero-s">虚拟发卡即时到账 · 实体设备填写收货地址</Text>
|
||||
{!canAccess && !loading ? (
|
||||
<Text className="vs-hero-vip" onClick={() => onLocked()}>
|
||||
价格库存已隐藏 · 解锁 VIP 可下单 →
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
<View className="vs-tabs">
|
||||
@ -101,14 +129,18 @@ export default function VipStorePage() {
|
||||
))}
|
||||
</View>
|
||||
|
||||
{loading ? (
|
||||
{loading && !catalog.products.length ? (
|
||||
<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
|
||||
key={p.id}
|
||||
className={`vs-card${!canAccess ? ' is-locked' : ''}`}
|
||||
onClick={() => openProduct(p.id)}
|
||||
>
|
||||
<View className="vs-card-cover">
|
||||
{p.cover ? (
|
||||
<Image src={p.cover} mode="aspectFill" className="vs-card-img" />
|
||||
@ -118,12 +150,30 @@ export default function VipStorePage() {
|
||||
<Text className="vs-badge">
|
||||
{p.goodsType === 'virtual' ? '虚拟发卡' : '实体发货'}
|
||||
</Text>
|
||||
{!canAccess ? (
|
||||
<View className="vs-cover-mosaic" aria-hidden>
|
||||
<Text className="vs-cover-lock">🔒</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</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>
|
||||
{canAccess ? (
|
||||
<>
|
||||
<Text className="vs-price">¥{(p.priceFen / 100).toFixed(0)}</Text>
|
||||
<Text className="vs-stock">库存 {p.stock}</Text>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<View className="vs-mosaic vs-mosaic-price">
|
||||
<Text className="vs-mosaic-txt">¥???</Text>
|
||||
</View>
|
||||
<View className="vs-mosaic vs-mosaic-stock">
|
||||
<Text className="vs-mosaic-txt">库存 **</Text>
|
||||
</View>
|
||||
</>
|
||||
)}
|
||||
</View>
|
||||
</View>
|
||||
))}
|
||||
|
||||
@ -4,7 +4,7 @@
|
||||
*/
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { Text, Button, View } from '@tarojs/components'
|
||||
import Taro from '@tarojs/taro'
|
||||
import Taro, { useDidShow, useRouter } from '@tarojs/taro'
|
||||
import { MiniModuleGate } from '@/components/MiniModuleGate'
|
||||
import { H5Box, H5Txt } from '@/components/H5Box'
|
||||
import { payVirtualProduct } from '@/utils/virtualPay'
|
||||
@ -13,7 +13,10 @@ import {
|
||||
loadRemoteConfig,
|
||||
subscribeRemoteConfig,
|
||||
} from '@/services/remoteConfig'
|
||||
import type { NomadroRemoteConfig } from '@/data/remoteConfig.defaults'
|
||||
import {
|
||||
resolveBookAudit,
|
||||
type NomadroRemoteConfig,
|
||||
} from '@/data/remoteConfig.defaults'
|
||||
import {
|
||||
mergeWeappVipContent,
|
||||
resolveWeappVipContent,
|
||||
@ -25,12 +28,21 @@ import { useNomadroTheme } from '@/utils/h5Theme'
|
||||
import { goHome, goPage } from '@/utils/nav'
|
||||
import { usePageShare, markPageShare } from '@/utils/pageShare'
|
||||
import { getSafeAreaMetrics } from '@/utils/safeArea'
|
||||
import { markVipPaidLocal, resolveVipAccess } from '@/utils/vipAccess'
|
||||
import {
|
||||
isVipPaidLocal,
|
||||
markVipPaidLocal,
|
||||
resolveVipAccess,
|
||||
subscribeVipAccess,
|
||||
} from '@/utils/vipAccess'
|
||||
import { ensureLogin } from '@/utils/request'
|
||||
import './index.scss'
|
||||
|
||||
const isH5 = process.env.TARO_ENV === 'h5'
|
||||
|
||||
/** 隐藏 CTA 次按钮 / 支付提示文案(逻辑保留,改 true 可恢复) */
|
||||
const SHOW_CTA_SECONDARY = false
|
||||
const SHOW_CTA_PAY_HINT = false
|
||||
|
||||
const STAT_ITEMS = [
|
||||
{ key: 'topics' as const, label: '模块' },
|
||||
{ key: 'ebooks' as const, label: '电子书' },
|
||||
@ -69,12 +81,13 @@ export default markPageShare(VipPage)
|
||||
|
||||
function VipLanding() {
|
||||
const theme = useNomadroTheme()
|
||||
const router = useRouter()
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [cfg, setCfg] = useState<NomadroRemoteConfig>(getCachedRemoteConfig())
|
||||
const [offline, setOffline] = useState(false)
|
||||
const [faqOpen, setFaqOpen] = useState<number | null>(0)
|
||||
const [restoreDate] = useState(() => formatRestoreDateShort())
|
||||
const [isVip, setIsVip] = useState(false)
|
||||
const [isVip, setIsVip] = useState(() => isVipPaidLocal())
|
||||
|
||||
const vc = useMemo(() => pickVipContent(cfg), [cfg])
|
||||
|
||||
@ -88,10 +101,17 @@ function VipLanding() {
|
||||
setOffline(r.fromOffline)
|
||||
})
|
||||
void refreshVipStatus()
|
||||
return subscribeRemoteConfig((r) => {
|
||||
const unsubCfg = subscribeRemoteConfig((r) => {
|
||||
setCfg(r.config)
|
||||
setOffline(r.fromOffline)
|
||||
// 免费/付费方案切换时立刻重算会员态
|
||||
void resolveVipAccess(false).then(setIsVip)
|
||||
})
|
||||
const unsubVip = subscribeVipAccess(setIsVip)
|
||||
return () => {
|
||||
unsubCfg()
|
||||
unsubVip()
|
||||
}
|
||||
}, [])
|
||||
|
||||
// H5:锁定 16px 根字号,让 rem 与 Next 一致
|
||||
@ -113,8 +133,17 @@ function VipLanding() {
|
||||
const payOk = cfg.flags.payEnabled !== false
|
||||
const priceFen = Number(cfg.copy.vipPriceFen) || 0
|
||||
const productId = String(cfg.copy.vipProductId || '')
|
||||
/** 后台免费=临时放行内容,不代表用户已开通 */
|
||||
const isFreeVip = priceFen <= 0 || !productId
|
||||
const cta = cfg.copy.vipCta || (isFreeVip ? '免费加入' : '立即加入')
|
||||
const canAccess = isVip || isFreeVip
|
||||
// CTA 不含价格(兼容旧配置「立即加入 · ¥298」)
|
||||
const rawCta = String(cfg.copy.vipCta || '').trim()
|
||||
const cta =
|
||||
!rawCta || /[¥¥]/.test(rawCta)
|
||||
? isFreeVip
|
||||
? '免费加入'
|
||||
: '立即加入'
|
||||
: rawCta
|
||||
const brand = cfg.copy.homeBrand || 'nomadro'
|
||||
const safe = useMemo(() => getSafeAreaMetrics(), [])
|
||||
const safeStyle = useMemo(
|
||||
@ -142,20 +171,38 @@ function VipLanding() {
|
||||
}
|
||||
|
||||
const offset = Math.max(safe.headerHeight, 64) + 8
|
||||
setTimeout(() => {
|
||||
const run = (attempt: number) => {
|
||||
const q = Taro.createSelectorQuery()
|
||||
q.select(`#${id}`).boundingClientRect()
|
||||
q.selectViewport().scrollOffset()
|
||||
q.exec((res) => {
|
||||
const rect = res?.[0] as { top?: number } | undefined
|
||||
const vp = res?.[1] as { scrollTop?: number } | undefined
|
||||
if (!rect || typeof rect.top !== 'number') return
|
||||
if (!rect || typeof rect.top !== 'number') {
|
||||
if (attempt < 6) setTimeout(() => run(attempt + 1), 80)
|
||||
return
|
||||
}
|
||||
const scrollTop = Math.max(0, Number(vp?.scrollTop || 0) + rect.top - offset)
|
||||
void Taro.pageScrollTo({ scrollTop, duration: 320 })
|
||||
})
|
||||
}, 32)
|
||||
}
|
||||
setTimeout(() => run(0), 48)
|
||||
}
|
||||
|
||||
/** 仅未开通且带 focus=cta 时滚到开通区;已是会员正常停留,不强制下滚 */
|
||||
useDidShow(() => {
|
||||
void (async () => {
|
||||
const vip = await resolveVipAccess(true)
|
||||
setIsVip(vip)
|
||||
if (vip) return
|
||||
const focus = String(router.params?.focus || '').toLowerCase()
|
||||
if (focus === 'cta' || focus === 'join' || focus === 'vip-cta') {
|
||||
setTimeout(() => scrollToAnchor('vip-cta'), 120)
|
||||
setTimeout(() => scrollToAnchor('vip-cta'), 420)
|
||||
}
|
||||
})()
|
||||
})
|
||||
|
||||
async function onLogin() {
|
||||
if (isH5) {
|
||||
Taro.showToast({ title: '请在门户登录', icon: 'none' })
|
||||
@ -208,7 +255,7 @@ function VipLanding() {
|
||||
}
|
||||
|
||||
if (href.includes('ebook/cloudphone') || href.includes('/ebook/cloudphone')) {
|
||||
if (!isVip && !isFreeVip) {
|
||||
if (!canAccess) {
|
||||
onLocked()
|
||||
return
|
||||
}
|
||||
@ -220,7 +267,14 @@ function VipLanding() {
|
||||
href === '/ebook' ||
|
||||
(href.includes('ebook') && !href.includes('cloudphone'))
|
||||
) {
|
||||
goPage('/pages/vip-ebook/index?id=nomad')
|
||||
{
|
||||
const audit = resolveBookAudit(getCachedRemoteConfig())
|
||||
if (audit.reviewMode) {
|
||||
goPage(`/pages/reader/index?id=${encodeURIComponent(audit.bookId || 'audit')}`)
|
||||
} else {
|
||||
goPage('/pages/vip-ebook/index?id=nomad')
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
@ -297,9 +351,8 @@ function VipLanding() {
|
||||
const free = latestPrice <= 0 || !latestPid
|
||||
|
||||
if (free) {
|
||||
markVipPaidLocal()
|
||||
setIsVip(true)
|
||||
Taro.showToast({ title: '已免费开放', icon: 'success' })
|
||||
// 临时放行:不写本地已付费、不写 unlocks;切回收费后仍须开通
|
||||
Taro.showToast({ title: '当前临时开放,切收费后需开通', icon: 'none' })
|
||||
return
|
||||
}
|
||||
|
||||
@ -378,9 +431,9 @@ function VipLanding() {
|
||||
<H5Txt className="vip-sectionTitle">模块</H5Txt>
|
||||
<H5Box className="vip-topicGrid" style={{ marginBottom: '1.5rem' }}>
|
||||
{topics.map((t) => {
|
||||
const hardLock =
|
||||
t.locked === true || t.id === 'community' || t.id === 'tools'
|
||||
const locked = hardLock && !isVip
|
||||
// 社群 / 设备商城:未付费可进页(页内试读或下单再拦)
|
||||
const browseOpen = t.id === 'community' || t.id === 'tools'
|
||||
const locked = !browseOpen && t.locked === true && !canAccess
|
||||
return (
|
||||
<H5Box
|
||||
key={t.id}
|
||||
@ -388,6 +441,12 @@ function VipLanding() {
|
||||
onClick={() => (locked ? onLocked() : openHref(t.href))}
|
||||
>
|
||||
{locked ? <H5Txt className="vip-topicLock">🔒</H5Txt> : null}
|
||||
{!canAccess && t.id === 'community' ? (
|
||||
<H5Txt className="vip-topicLock">试读</H5Txt>
|
||||
) : null}
|
||||
{!canAccess && t.id === 'tools' ? (
|
||||
<H5Txt className="vip-topicLock">逛一逛</H5Txt>
|
||||
) : null}
|
||||
<H5Txt className="vip-topicIcon">{t.icon}</H5Txt>
|
||||
<H5Txt className="vip-topicTitle">{t.title}</H5Txt>
|
||||
<H5Txt className="vip-topicDesc">{t.desc}</H5Txt>
|
||||
@ -426,29 +485,48 @@ function VipLanding() {
|
||||
</View>
|
||||
<H5Box className="vip-ebookGrid">
|
||||
{ebooks.map((e) => {
|
||||
const isFree = Boolean(e.free) || isFreeVip
|
||||
const locked = !isFree && !isVip
|
||||
// 原小册 Youtube运营笔记:谁都能进(自带试读/单买);另支持 VIP 全文;不标「免费」
|
||||
const isPaidBooklet =
|
||||
e.id === 'youtube-notes' ||
|
||||
(typeof e.href === 'string' && e.href.includes('/pages/reader'))
|
||||
const isFree = !isPaidBooklet && (Boolean(e.free) || isFreeVip)
|
||||
const vipLocked = !isPaidBooklet && !isFree && !canAccess
|
||||
return (
|
||||
<H5Box
|
||||
key={e.id}
|
||||
className="vip-card vip-ebookCard"
|
||||
onClick={() => {
|
||||
if (locked) {
|
||||
// 原小册始终可进;VIP 专属电子书才拦
|
||||
if (vipLocked) {
|
||||
onLocked()
|
||||
return
|
||||
}
|
||||
goPage(`/pages/vip-ebook/index?id=${e.ebookId}`)
|
||||
if (e.href) {
|
||||
goPage(e.href)
|
||||
return
|
||||
}
|
||||
const ebookId = e.ebookId || 'nomad'
|
||||
if (ebookId === 'nomad') {
|
||||
const audit = resolveBookAudit(getCachedRemoteConfig())
|
||||
if (audit.reviewMode) {
|
||||
goPage(
|
||||
`/pages/reader/index?id=${encodeURIComponent(audit.bookId || 'audit')}`,
|
||||
)
|
||||
return
|
||||
}
|
||||
}
|
||||
goPage(`/pages/vip-ebook/index?id=${ebookId}`)
|
||||
}}
|
||||
>
|
||||
<H5Txt className="vip-ebookEmoji">📖</H5Txt>
|
||||
<H5Box className="vip-ebookTitleRow">
|
||||
<H5Txt className="vip-ebookTitle">《{e.title}》</H5Txt>
|
||||
{isFree ? <H5Txt className="vip-freeBadge">免费</H5Txt> : null}
|
||||
{locked ? <H5Txt className="vip-ebookLock">🔒</H5Txt> : null}
|
||||
{vipLocked ? <H5Txt className="vip-ebookLock">🔒</H5Txt> : null}
|
||||
</H5Box>
|
||||
<H5Txt className="vip-ebookDesc">{e.desc}</H5Txt>
|
||||
<H5Txt className="vip-ebookCta">
|
||||
{locked ? '开通VIP解锁 →' : '阅读 →'}
|
||||
{vipLocked ? '开通VIP解锁 →' : '阅读 →'}
|
||||
</H5Txt>
|
||||
</H5Box>
|
||||
)
|
||||
@ -531,13 +609,35 @@ function VipLanding() {
|
||||
</H5Box>
|
||||
) : null}
|
||||
|
||||
{/* LandingCTA — reviewMode 仍展示,但不强调付费文案时可隐藏芯片 */}
|
||||
{/* LandingCTA — 已开通切换为会员态,不再推销「立即加入」 */}
|
||||
{vc.showCta ? (
|
||||
<H5Box className="vip-section vip-ctaSection" id="vip-cta">
|
||||
<H5Box className="vip-ctaInner">
|
||||
<H5Box className="vip-ctaGlow" aria-hidden />
|
||||
<H5Box className="vip-ctaCard">
|
||||
{!vc.reviewMode ? (
|
||||
{isVip ? (
|
||||
<H5Box className="vip-ctaPromoLine">
|
||||
<H5Box className="vip-ctaPromoClickable">
|
||||
<H5Box className="vip-ctaBadgePulse" />
|
||||
<H5Txt>会员已开通</H5Txt>
|
||||
</H5Box>
|
||||
<H5Txt className="vip-ctaPromoDivider">·</H5Txt>
|
||||
<H5Box className="vip-ctaPromoMain">
|
||||
<H5Txt className="vip-ctaPromoSuffix">权益持续生效中</H5Txt>
|
||||
</H5Box>
|
||||
</H5Box>
|
||||
) : isFreeVip ? (
|
||||
<H5Box className="vip-ctaPromoLine">
|
||||
<H5Box className="vip-ctaPromoClickable">
|
||||
<H5Box className="vip-ctaBadgePulse" />
|
||||
<H5Txt>临时开放</H5Txt>
|
||||
</H5Box>
|
||||
<H5Txt className="vip-ctaPromoDivider">·</H5Txt>
|
||||
<H5Box className="vip-ctaPromoMain">
|
||||
<H5Txt className="vip-ctaPromoSuffix">切收费后需开通</H5Txt>
|
||||
</H5Box>
|
||||
</H5Box>
|
||||
) : !vc.reviewMode ? (
|
||||
<H5Box className="vip-ctaPromoLine">
|
||||
<H5Box className="vip-ctaPromoClickable">
|
||||
<H5Box className="vip-ctaBadgePulse" />
|
||||
@ -551,7 +651,7 @@ function VipLanding() {
|
||||
</H5Box>
|
||||
) : null}
|
||||
|
||||
{!vc.reviewMode && vc.ctaChips.length > 0 ? (
|
||||
{!isVip && !vc.reviewMode && vc.ctaChips.length > 0 ? (
|
||||
<H5Box className="vip-ctaChips">
|
||||
{vc.ctaChips.map((c) => (
|
||||
<H5Txt key={c} className="vip-ctaChip">
|
||||
@ -561,29 +661,47 @@ function VipLanding() {
|
||||
</H5Box>
|
||||
) : null}
|
||||
|
||||
{offline ? (
|
||||
{offline && !isVip ? (
|
||||
<H5Txt className="vip-ctaOffline">📦 价格/文案来自离线配置</H5Txt>
|
||||
) : null}
|
||||
|
||||
<H5Box className="vip-ctaActions">
|
||||
<Button
|
||||
className="vip-btnPrimary vip-btnLarge vip-ctaBtnPrimary"
|
||||
loading={busy}
|
||||
disabled={!isH5 && !payOk}
|
||||
onClick={onJoin}
|
||||
>
|
||||
{busy ? '拉起支付…' : `🔒 ${cta}`}
|
||||
</Button>
|
||||
<Button className="vip-ctaBtnSecondary" onClick={() => void onLogin()}>
|
||||
{vc.ctaSecondary || '已有账号'}
|
||||
</Button>
|
||||
{isVip ? (
|
||||
<Button
|
||||
className="vip-btnPrimary vip-btnLarge vip-ctaBtnPrimary"
|
||||
onClick={() => scrollToAnchor('topics')}
|
||||
>
|
||||
✓ 已是会员 · 浏览权益
|
||||
</Button>
|
||||
) : (
|
||||
<>
|
||||
<Button
|
||||
className="vip-btnPrimary vip-btnLarge vip-ctaBtnPrimary"
|
||||
loading={busy}
|
||||
disabled={!isH5 && !payOk}
|
||||
onClick={onJoin}
|
||||
>
|
||||
{busy ? '拉起支付…' : `🔒 ${cta}`}
|
||||
</Button>
|
||||
{/* 隐藏「已有账号」:保留登录逻辑,改 SHOW_CTA_SECONDARY=true 可恢复 */}
|
||||
{SHOW_CTA_SECONDARY ? (
|
||||
<Button className="vip-ctaBtnSecondary" onClick={() => void onLogin()}>
|
||||
{vc.ctaSecondary || '已有账号'}
|
||||
</Button>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
</H5Box>
|
||||
|
||||
{isH5 ? (
|
||||
<H5Txt className="vip-ctaHint">{vc.ctaHintH5}</H5Txt>
|
||||
) : (
|
||||
<H5Txt className="vip-ctaHint">{vc.ctaHintWeapp}</H5Txt>
|
||||
)}
|
||||
{isVip ? (
|
||||
<H5Txt className="vip-ctaHint">权益已解锁,可从上方模块进入</H5Txt>
|
||||
) : SHOW_CTA_PAY_HINT ? (
|
||||
isH5 ? (
|
||||
<H5Txt className="vip-ctaHint">{vc.ctaHintH5}</H5Txt>
|
||||
) : (
|
||||
<H5Txt className="vip-ctaHint">{vc.ctaHintWeapp}</H5Txt>
|
||||
)
|
||||
) : null}
|
||||
</H5Box>
|
||||
</H5Box>
|
||||
</H5Box>
|
||||
|
||||
@ -55,37 +55,95 @@ export type AccessSnapshot = {
|
||||
updated_at: number
|
||||
}
|
||||
|
||||
function isAuditBookId(bookId: string) {
|
||||
const id = (bookId || '').trim()
|
||||
return id === 'audit' || id.startsWith('audit')
|
||||
}
|
||||
|
||||
/** 提审书绝不能回退到正式离线包 */
|
||||
function auditOfflineBook(bookId: string): BookDetail {
|
||||
return {
|
||||
id: bookId || 'audit',
|
||||
title: '数字游民入门指南',
|
||||
subtitle: '远程办公 · 自律生活 · 稳健成长',
|
||||
author: '',
|
||||
cover_emoji: '📗',
|
||||
description: '面向普通人的远程办公与生活方式入门读本。',
|
||||
tags: ['数字游民', '远程办公'],
|
||||
price_fen: 0,
|
||||
product_id: '',
|
||||
unlock_percent: 100,
|
||||
is_free: true,
|
||||
chapter_count: 1,
|
||||
word_count: 0,
|
||||
rating: 5,
|
||||
chapters: [{ id: '01-audit', title: '写在前面', order: 1 }],
|
||||
}
|
||||
}
|
||||
|
||||
function auditOfflineRead(bookId: string): ReadPayload {
|
||||
const book = auditOfflineBook(bookId)
|
||||
return {
|
||||
book,
|
||||
chapters: [
|
||||
{
|
||||
id: '01-audit',
|
||||
title: '写在前面',
|
||||
order: 1,
|
||||
content:
|
||||
'# 写在前面\n\n欢迎阅读《数字游民入门指南》。\n\n这是一本面向普通人的远程办公与自律生活入门读本。\n',
|
||||
},
|
||||
],
|
||||
unlocked: true,
|
||||
is_free: true,
|
||||
unlock_percent: 100,
|
||||
preview_ratio: 1,
|
||||
access: {
|
||||
book_id: book.id,
|
||||
unlocked: true,
|
||||
is_free: true,
|
||||
unlock_percent: 100,
|
||||
product_id: '',
|
||||
price_fen: 0,
|
||||
updated_at: Date.now(),
|
||||
},
|
||||
updated_at: Date.now(),
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchBook(bookId = 'default'): Promise<BookDetail> {
|
||||
// H5 must match Next /book (数字游民 pack), not VIP API titles
|
||||
if (process.env.TARO_ENV === 'h5') {
|
||||
return { ...OFFLINE_BOOK, id: bookId || 'default' }
|
||||
const id = bookId || 'default'
|
||||
// H5:正式书用离线包;提审书必须打 API,失败也不回正式包
|
||||
if (process.env.TARO_ENV === 'h5' && !isAuditBookId(id)) {
|
||||
return { ...OFFLINE_BOOK, id }
|
||||
}
|
||||
try {
|
||||
return await request({ url: `/api/ebook/books/${bookId}?_=${Date.now()}` })
|
||||
return await request({ url: `/api/ebook/books/${id}?_=${Date.now()}` })
|
||||
} catch {
|
||||
return { ...OFFLINE_BOOK, id: bookId || 'default' }
|
||||
if (isAuditBookId(id)) return auditOfflineBook(id)
|
||||
return { ...OFFLINE_BOOK, id }
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchRead(bookId = 'default'): Promise<ReadPayload> {
|
||||
if (process.env.TARO_ENV === 'h5') {
|
||||
const id = bookId || 'default'
|
||||
if (process.env.TARO_ENV === 'h5' && !isAuditBookId(id)) {
|
||||
const payload = offlineReadPayload()
|
||||
payload.book = { ...payload.book, id: bookId || 'default' }
|
||||
payload.book = { ...payload.book, id }
|
||||
return payload
|
||||
}
|
||||
try {
|
||||
// H5 浏览器无 wx.login:先拉公开预览;小程序仍走登录态
|
||||
if (process.env.TARO_ENV !== 'h5') {
|
||||
await ensureLogin()
|
||||
}
|
||||
return await request({ url: `/api/ebook/books/${bookId}/read?_=${Date.now()}` })
|
||||
return await request({ url: `/api/ebook/books/${id}/read?_=${Date.now()}` })
|
||||
} catch {
|
||||
try {
|
||||
// 登录失败时仍尝试匿名预览(小程序沙箱 / H5)
|
||||
return await request({ url: `/api/ebook/books/${bookId}/read?_=${Date.now()}` })
|
||||
return await request({ url: `/api/ebook/books/${id}/read?_=${Date.now()}` })
|
||||
} catch {
|
||||
if (isAuditBookId(id)) return auditOfflineRead(id)
|
||||
const payload = offlineReadPayload()
|
||||
payload.book = { ...payload.book, id: bookId || 'default' }
|
||||
payload.book = { ...payload.book, id }
|
||||
return payload
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,10 +2,12 @@ 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_'
|
||||
/** v5:清掉仍含已隐藏帖的旧缓存 */
|
||||
const FEED_CACHE = 'nomadro_memo_feed_v5'
|
||||
const SETTINGS_CACHE = 'nomadro_memo_settings_v2'
|
||||
const TAGS_CACHE = 'nomadro_memo_tags_v2'
|
||||
const DETAIL_PREFIX = 'nomadro_memo_detail_v2_'
|
||||
const REVISION_CACHE = 'nomadro_memo_rev_v1'
|
||||
|
||||
/** 只打 ebook 前缀,避免双路径串行拖慢 */
|
||||
const P = '/api/ebook/memo'
|
||||
@ -25,6 +27,11 @@ export type MemoItem = {
|
||||
tags?: string[]
|
||||
pinned: boolean
|
||||
featured?: boolean
|
||||
/** 未付费可读全文 */
|
||||
trial?: boolean
|
||||
/** 非试读且未付费 */
|
||||
locked?: boolean
|
||||
visibility?: string
|
||||
likeCount: number
|
||||
commentCount: number
|
||||
favoriteCount?: number
|
||||
@ -45,6 +52,12 @@ export type MemoComment = {
|
||||
|
||||
export type MemoSettings = {
|
||||
enabled: boolean
|
||||
isVip?: boolean
|
||||
canBrowse?: boolean
|
||||
allowTrialBrowse?: boolean
|
||||
defaultTrial?: boolean
|
||||
trialComments?: boolean
|
||||
requireVip?: boolean
|
||||
canPost: boolean
|
||||
canComment: boolean
|
||||
canLike: boolean
|
||||
@ -54,8 +67,11 @@ export type MemoSettings = {
|
||||
planetName?: string
|
||||
planetDesc?: string
|
||||
notice: string
|
||||
unlockHint?: string
|
||||
maxContentLen: number
|
||||
maxImages?: number
|
||||
/** 后台隐藏/发帖/改配置递增,前端轮询近实时同步 */
|
||||
contentRevision?: number
|
||||
}
|
||||
|
||||
export type MemoTag = { name: string; count: number }
|
||||
@ -74,6 +90,9 @@ const OFFLINE_FEED: MemoItem[] = [
|
||||
tags: ['欢迎'],
|
||||
pinned: true,
|
||||
featured: true,
|
||||
trial: true,
|
||||
locked: false,
|
||||
visibility: 'trial',
|
||||
likeCount: 0,
|
||||
commentCount: 0,
|
||||
favoriteCount: 0,
|
||||
@ -83,6 +102,12 @@ const OFFLINE_FEED: MemoItem[] = [
|
||||
|
||||
const DEFAULT_SETTINGS: MemoSettings = {
|
||||
enabled: true,
|
||||
isVip: false,
|
||||
canBrowse: true,
|
||||
allowTrialBrowse: true,
|
||||
defaultTrial: true,
|
||||
trialComments: false,
|
||||
requireVip: true,
|
||||
canPost: false,
|
||||
canComment: true,
|
||||
canLike: true,
|
||||
@ -92,6 +117,7 @@ const DEFAULT_SETTINGS: MemoSettings = {
|
||||
planetName: 'Nomadro 知识社群',
|
||||
planetDesc: '博主分享实战干货,会员阅读互动',
|
||||
notice: '',
|
||||
unlockHint: '开通 VIP 后可读全文并参与讨论',
|
||||
maxContentLen: 20000,
|
||||
maxImages: 9,
|
||||
}
|
||||
@ -123,15 +149,18 @@ async function req<T>(
|
||||
init?: { method?: string; data?: unknown },
|
||||
): Promise<T> {
|
||||
await ensureLogin(false)
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
'Cache-Control': 'no-cache',
|
||||
Pragma: 'no-cache',
|
||||
...authHeader(),
|
||||
}
|
||||
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(),
|
||||
},
|
||||
header: headers,
|
||||
})
|
||||
if (res.statusCode < 400) return res.data as T
|
||||
if (res.statusCode === 401) {
|
||||
@ -143,6 +172,8 @@ async function req<T>(
|
||||
timeout: TIMEOUT_MS,
|
||||
header: {
|
||||
'Content-Type': 'application/json',
|
||||
'Cache-Control': 'no-cache',
|
||||
Pragma: 'no-cache',
|
||||
...authHeader(),
|
||||
},
|
||||
})
|
||||
@ -154,6 +185,16 @@ async function req<T>(
|
||||
throw new Error(typeof detail === 'string' ? detail : '请求失败')
|
||||
}
|
||||
|
||||
function rememberRevision(rev: number) {
|
||||
if (!rev) return
|
||||
writeCache(REVISION_CACHE, rev)
|
||||
}
|
||||
|
||||
export function getCachedMemoRevision(): number {
|
||||
const n = Number(readCache<number>(REVISION_CACHE) || 0)
|
||||
return Number.isFinite(n) ? n : 0
|
||||
}
|
||||
|
||||
export function getCachedMemoFeed(): MemoItem[] {
|
||||
const raw = readCache<MemoItem[]>(FEED_CACHE)
|
||||
if (Array.isArray(raw) && raw.length) return raw
|
||||
@ -203,6 +244,7 @@ export async function loadMemoHome(opts?: {
|
||||
if (settingsR.status === 'fulfilled') {
|
||||
settings = { ...DEFAULT_SETTINGS, ...settingsR.value }
|
||||
writeCache(SETTINGS_CACHE, settings)
|
||||
rememberRevision(Number(settings.contentRevision || 0))
|
||||
}
|
||||
|
||||
let tags = getCachedMemoTags()
|
||||
@ -211,12 +253,21 @@ export async function loadMemoHome(opts?: {
|
||||
writeCache(TAGS_CACHE, tags)
|
||||
}
|
||||
|
||||
let items = getCachedMemoFeed()
|
||||
// 网络优先:成功则整表替换(含空列表),禁止用旧缓存顶回已隐藏帖
|
||||
let items: MemoItem[] = []
|
||||
let offline = true
|
||||
if (feedR.status === 'fulfilled') {
|
||||
items = feedR.value.items || []
|
||||
offline = false
|
||||
const rev = Number(
|
||||
(feedR.value as { contentRevision?: number }).contentRevision ||
|
||||
settings.contentRevision ||
|
||||
0,
|
||||
)
|
||||
rememberRevision(rev)
|
||||
if (!q && !tag && tab === 'all') writeCache(FEED_CACHE, items)
|
||||
} else {
|
||||
items = getCachedMemoFeed()
|
||||
}
|
||||
|
||||
return { settings, tags, items, offline }
|
||||
@ -227,12 +278,25 @@ export async function loadMemoSettings(): Promise<MemoSettings> {
|
||||
const data = await req<MemoSettings>(`${P}/settings`)
|
||||
const next = { ...DEFAULT_SETTINGS, ...data }
|
||||
writeCache(SETTINGS_CACHE, next)
|
||||
rememberRevision(Number(next.contentRevision || 0))
|
||||
return next
|
||||
} catch {
|
||||
return getCachedMemoSettings()
|
||||
}
|
||||
}
|
||||
|
||||
/** 轻量探活:仅拉 settings.revision,变了再全量 refresh */
|
||||
export async function peekMemoContentRevision(): Promise<number> {
|
||||
try {
|
||||
const data = await req<MemoSettings>(`${P}/settings`)
|
||||
const rev = Number(data.contentRevision || 0)
|
||||
rememberRevision(rev)
|
||||
return rev
|
||||
} catch {
|
||||
return getCachedMemoRevision()
|
||||
}
|
||||
}
|
||||
|
||||
export async function loadMemoTags(): Promise<MemoTag[]> {
|
||||
try {
|
||||
const data = await req<{ items: MemoTag[] }>(`${P}/tags`)
|
||||
|
||||
@ -97,28 +97,6 @@ export async function loadShopProduct(id: string): Promise<ShopProduct> {
|
||||
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
|
||||
|
||||
@ -835,22 +835,26 @@ html.light .nd-theme-toggle,
|
||||
}
|
||||
|
||||
.hub-root--mini .hub-navbar {
|
||||
height: auto;
|
||||
min-height: 0;
|
||||
/* 覆盖基础 height:72px,避免首屏把 logo 挤进状态栏 */
|
||||
height: auto !important;
|
||||
min-height: 0 !important;
|
||||
/* JS 注入 --safe-status-bar;env 在模拟器常为 0 */
|
||||
padding-top: var(--safe-status-bar, 47px);
|
||||
padding-bottom: 0;
|
||||
box-sizing: content-box;
|
||||
padding-top: var(--safe-status-bar, 47px) !important;
|
||||
padding-bottom: 0 !important;
|
||||
box-sizing: content-box !important;
|
||||
/* 首屏即有底,避免「一块黑/透」闪一下 */
|
||||
background: rgba(12, 12, 15, 0.92);
|
||||
}
|
||||
|
||||
.hub-root--mini .hub-nav-container {
|
||||
height: var(--safe-nav-bar, 44px);
|
||||
height: var(--safe-nav-bar, 44px) !important;
|
||||
width: 100% !important;
|
||||
max-width: 100% !important;
|
||||
margin: 0 !important;
|
||||
padding: 0 12px;
|
||||
padding-right: var(--safe-menu-pad, 96px);
|
||||
box-sizing: border-box;
|
||||
padding: 0 12px !important;
|
||||
padding-right: var(--safe-menu-pad, 96px) !important;
|
||||
box-sizing: border-box !important;
|
||||
align-items: center !important;
|
||||
}
|
||||
|
||||
.hub-root--mini .hub-hero-inner {
|
||||
|
||||
84
apps/miniprogram/h5/src/utils/devDebug.ts
Normal file
84
apps/miniprogram/h5/src/utils/devDebug.ts
Normal file
@ -0,0 +1,84 @@
|
||||
import Taro from '@tarojs/taro'
|
||||
|
||||
/**
|
||||
* 本地调试悬浮球总开关(逻辑保留,默认隐藏)。
|
||||
* VIP 身份以 admin.nomadro.cn 用户侧权限为准;需要本地强制切换时改回 true。
|
||||
*/
|
||||
export const DEBUG_FAB_VISIBLE = false
|
||||
|
||||
/**
|
||||
* 调试能力是否可用(与悬浮球是否展示分开):
|
||||
* - 本地 NODE_ENV=development
|
||||
* - 微信开发者工具 / 开发版(envVersion=develop)
|
||||
* - H5 localhost
|
||||
* 正式版 release 一律关闭(含体验版 trial 也不开,避免外泄)
|
||||
*/
|
||||
export function isDevDebugEnabled(): boolean {
|
||||
if (process.env.NODE_ENV === 'development') return true
|
||||
|
||||
try {
|
||||
const env = Taro.getAccountInfoSync?.()?.miniProgram?.envVersion
|
||||
if (env === 'develop') return true
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
|
||||
try {
|
||||
if (typeof location !== 'undefined') {
|
||||
const h = String(location.hostname || '')
|
||||
if (h === 'localhost' || h === '127.0.0.1') return true
|
||||
}
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
const VIP_OVERRIDE_KEY = 'nomadro_dev_vip_override'
|
||||
|
||||
/** null=跟随服务端;true/false=强制 */
|
||||
export type DevVipOverride = boolean | null
|
||||
|
||||
export function getDevVipOverride(): DevVipOverride {
|
||||
// 悬浮球隐藏时不读本地强制,VIP 以服务端 / admin 为准
|
||||
if (!DEBUG_FAB_VISIBLE || !isDevDebugEnabled()) return null
|
||||
try {
|
||||
const v = String(Taro.getStorageSync(VIP_OVERRIDE_KEY) || '')
|
||||
if (v === '1') return true
|
||||
if (v === '0') return false
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export function setDevVipOverride(next: DevVipOverride): void {
|
||||
if (!DEBUG_FAB_VISIBLE || !isDevDebugEnabled()) return
|
||||
try {
|
||||
if (next === null) Taro.removeStorageSync(VIP_OVERRIDE_KEY)
|
||||
else Taro.setStorageSync(VIP_OVERRIDE_KEY, next ? '1' : '0')
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
export function clearDevCaches(): void {
|
||||
if (!DEBUG_FAB_VISIBLE || !isDevDebugEnabled()) return
|
||||
const keys = [
|
||||
'nomadro_memo_feed_v5',
|
||||
'nomadro_memo_settings_v2',
|
||||
'nomadro_memo_tags_v2',
|
||||
'nomadro_memo_rev_v1',
|
||||
'nomadro_shop_catalog_v2',
|
||||
'nomadro_remote_config_v1',
|
||||
'nomadro_vip_paid',
|
||||
]
|
||||
for (const k of keys) {
|
||||
try {
|
||||
Taro.removeStorageSync(k)
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
}
|
||||
57
apps/miniprogram/h5/src/utils/presence.ts
Normal file
57
apps/miniprogram/h5/src/utils/presence.ts
Normal file
@ -0,0 +1,57 @@
|
||||
import Taro from '@tarojs/taro'
|
||||
import { ensureLogin, requestEbook } from './request'
|
||||
import { applyServerVipFlag } from './vipAccess'
|
||||
|
||||
const INTERVAL_MS = 25_000
|
||||
let timer: ReturnType<typeof setInterval> | null = null
|
||||
let started = false
|
||||
|
||||
async function ping(): Promise<void> {
|
||||
try {
|
||||
await ensureLogin(false)
|
||||
const data = await requestEbook<{ isVip?: boolean }>({
|
||||
url: '/api/ebook/auth/presence',
|
||||
method: 'POST',
|
||||
data: {},
|
||||
})
|
||||
if (typeof data?.isVip === 'boolean') {
|
||||
applyServerVipFlag(data.isVip)
|
||||
}
|
||||
} catch {
|
||||
/* 未登录 / 网络失败时静默,不影响业务 */
|
||||
}
|
||||
}
|
||||
|
||||
/** 小程序前台心跳:登录后周期上报,后台 VIP用户页据此显示在线 */
|
||||
export function startPresenceHeartbeat(): () => void {
|
||||
if (started) {
|
||||
return () => stopPresenceHeartbeat()
|
||||
}
|
||||
started = true
|
||||
void ping()
|
||||
timer = setInterval(() => void ping(), INTERVAL_MS)
|
||||
|
||||
const onShow = () => void ping()
|
||||
try {
|
||||
Taro.onAppShow?.(onShow)
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
|
||||
return () => {
|
||||
try {
|
||||
Taro.offAppShow?.(onShow)
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
stopPresenceHeartbeat()
|
||||
}
|
||||
}
|
||||
|
||||
export function stopPresenceHeartbeat(): void {
|
||||
started = false
|
||||
if (timer) {
|
||||
clearInterval(timer)
|
||||
timer = null
|
||||
}
|
||||
}
|
||||
@ -1,4 +1,5 @@
|
||||
import Taro from '@tarojs/taro'
|
||||
import Taro, { useDidShow, useReady } from '@tarojs/taro'
|
||||
import { useCallback, useState } from 'react'
|
||||
|
||||
export type SafeAreaMetrics = {
|
||||
/** 状态栏高度(刘海/灵动岛下方) */
|
||||
@ -9,6 +10,10 @@ export type SafeAreaMetrics = {
|
||||
menuRightPad: number
|
||||
/** 自定义顶栏总占位 = statusBar + navBar */
|
||||
headerHeight: number
|
||||
/** 胶囊 top(用于精确对齐) */
|
||||
menuTop: number
|
||||
/** 胶囊 height */
|
||||
menuHeight: number
|
||||
}
|
||||
|
||||
const H5_FALLBACK: SafeAreaMetrics = {
|
||||
@ -16,6 +21,17 @@ const H5_FALLBACK: SafeAreaMetrics = {
|
||||
navBarHeight: 48,
|
||||
menuRightPad: 16,
|
||||
headerHeight: 48,
|
||||
menuTop: 0,
|
||||
menuHeight: 32,
|
||||
}
|
||||
|
||||
/**
|
||||
* Taro 默认会把内联样式的 px 转成 rpx(designWidth 750 下约减半),
|
||||
* 状态栏/胶囊必须用大写 PX 才能跳过转换,否则顶栏首屏会顶到状态栏,下拉才像「正常」。
|
||||
*/
|
||||
export function safePx(n: number): string {
|
||||
const v = Math.max(0, Math.round(Number(n) || 0))
|
||||
return `${v}PX`
|
||||
}
|
||||
|
||||
/** 微信/抖音自定义导航:用系统 API,勿信 env(safe-area-inset-top)(模拟器常为 0) */
|
||||
@ -23,7 +39,10 @@ export function getSafeAreaMetrics(): SafeAreaMetrics {
|
||||
if (process.env.TARO_ENV === 'h5') return H5_FALLBACK
|
||||
|
||||
try {
|
||||
const sys = Taro.getSystemInfoSync()
|
||||
const sys =
|
||||
typeof Taro.getWindowInfo === 'function'
|
||||
? Taro.getWindowInfo()
|
||||
: Taro.getSystemInfoSync()
|
||||
const statusBarHeight = Number(sys.statusBarHeight) || 44
|
||||
const windowWidth = Number(sys.windowWidth) || 375
|
||||
|
||||
@ -43,6 +62,8 @@ export function getSafeAreaMetrics(): SafeAreaMetrics {
|
||||
navBarHeight,
|
||||
menuRightPad,
|
||||
headerHeight: statusBarHeight + navBarHeight,
|
||||
menuTop: menu.top,
|
||||
menuHeight: menu.height,
|
||||
}
|
||||
}
|
||||
|
||||
@ -51,6 +72,8 @@ export function getSafeAreaMetrics(): SafeAreaMetrics {
|
||||
navBarHeight: 44,
|
||||
menuRightPad: 96,
|
||||
headerHeight: statusBarHeight + 44,
|
||||
menuTop: statusBarHeight + 6,
|
||||
menuHeight: 32,
|
||||
}
|
||||
} catch {
|
||||
return {
|
||||
@ -58,6 +81,29 @@ export function getSafeAreaMetrics(): SafeAreaMetrics {
|
||||
navBarHeight: 44,
|
||||
menuRightPad: 96,
|
||||
headerHeight: 91,
|
||||
menuTop: 53,
|
||||
menuHeight: 32,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 首屏 + Ready + 回前台重测,避免胶囊 API 首帧为 0 */
|
||||
export function useSafeAreaMetrics(): SafeAreaMetrics {
|
||||
const [safe, setSafe] = useState<SafeAreaMetrics>(() => getSafeAreaMetrics())
|
||||
|
||||
const refresh = useCallback(() => {
|
||||
setSafe(getSafeAreaMetrics())
|
||||
}, [])
|
||||
|
||||
useReady(() => {
|
||||
refresh()
|
||||
setTimeout(refresh, 32)
|
||||
setTimeout(refresh, 120)
|
||||
})
|
||||
|
||||
useDidShow(() => {
|
||||
refresh()
|
||||
})
|
||||
|
||||
return safe
|
||||
}
|
||||
|
||||
@ -1,14 +1,64 @@
|
||||
import Taro from '@tarojs/taro'
|
||||
import { API_BASE, STORAGE_TOKEN } from './config'
|
||||
import { ensureLogin } from './request'
|
||||
import { ensureLogin, requestEbook } from './request'
|
||||
import { goPage } from './nav'
|
||||
import { getDevVipOverride, isDevDebugEnabled } from './devDebug'
|
||||
import {
|
||||
getCachedRemoteConfig,
|
||||
loadRemoteConfig,
|
||||
} from '../services/remoteConfig'
|
||||
|
||||
const LOCAL_PAID_KEY = 'nomadro_vip_paid'
|
||||
/** 与 remote-config meta / memo revision 同级:近实时探 VIP 准入 */
|
||||
const VIP_POLL_MS = 3000
|
||||
|
||||
/** 对齐 nomadvip paidType=vip */
|
||||
type VipListener = (isVip: boolean) => void
|
||||
|
||||
const listeners = new Set<VipListener>()
|
||||
let lastKnown: boolean | null = null
|
||||
let liveStarted = false
|
||||
let liveTimer: ReturnType<typeof setInterval> | null = null
|
||||
let polling = false
|
||||
|
||||
/** 后台「免费」方案:临时放行内容权限,不代表用户已开通 VIP */
|
||||
export function isFreeVipScheme(): boolean {
|
||||
const cfg = getCachedRemoteConfig()
|
||||
const price = Number(cfg.copy.vipPriceFen) || 0
|
||||
const pid = String(cfg.copy.vipProductId || '').trim()
|
||||
return price <= 0 || !pid
|
||||
}
|
||||
|
||||
function emitVip(isVip: boolean) {
|
||||
if (lastKnown === isVip) return
|
||||
lastKnown = isVip
|
||||
if (isVip) markVipPaidLocal()
|
||||
else clearVipPaidLocal()
|
||||
listeners.forEach((fn) => {
|
||||
try {
|
||||
fn(isVip)
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/** 未开通:跳 VIP 落地并滚到开通区;已是会员:正常进首页,不强制下滚 */
|
||||
export function goVipUnlock(): void {
|
||||
void (async () => {
|
||||
// 免费方案:临时可进,无需推销开通
|
||||
if (isFreeVipScheme()) {
|
||||
goPage('/pages/vip/index')
|
||||
return
|
||||
}
|
||||
const vip = await resolveVipAccess()
|
||||
if (vip) {
|
||||
goPage('/pages/vip/index')
|
||||
return
|
||||
}
|
||||
goPage('/pages/vip/index?focus=cta')
|
||||
})()
|
||||
}
|
||||
|
||||
/** 支付成功或服务端确认后写入本地缓存(不能单独当凭证) */
|
||||
export function markVipPaidLocal(): void {
|
||||
try {
|
||||
Taro.setStorageSync(LOCAL_PAID_KEY, '1')
|
||||
@ -17,6 +67,14 @@ export function markVipPaidLocal(): void {
|
||||
}
|
||||
}
|
||||
|
||||
export function clearVipPaidLocal(): void {
|
||||
try {
|
||||
Taro.removeStorageSync(LOCAL_PAID_KEY)
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
export function isVipPaidLocal(): boolean {
|
||||
try {
|
||||
return Taro.getStorageSync(LOCAL_PAID_KEY) === '1'
|
||||
@ -25,33 +83,149 @@ export function isVipPaidLocal(): boolean {
|
||||
}
|
||||
}
|
||||
|
||||
/** 后台免费方案 / 已购 VIP / 本地已付标记 */
|
||||
/** 订阅真实 VIP 变更(unlocks.__vip__;免费方案不会推 true) */
|
||||
export function subscribeVipAccess(listener: VipListener): () => void {
|
||||
listeners.add(listener)
|
||||
if (lastKnown !== null) {
|
||||
try {
|
||||
listener(lastKnown)
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
return () => {
|
||||
listeners.delete(listener)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 心跳带回的服务端 isVip(原始 unlocks)。
|
||||
* 免费方案不改写会员态——切回收费后仍须服务端解锁才算 VIP。
|
||||
*/
|
||||
export function applyServerVipFlag(serverIsVip: boolean): void {
|
||||
if (isDevDebugEnabled()) {
|
||||
const ov = getDevVipOverride()
|
||||
if (ov !== null) {
|
||||
emitVip(ov)
|
||||
return
|
||||
}
|
||||
}
|
||||
emitVip(!!serverIsVip)
|
||||
}
|
||||
|
||||
/**
|
||||
* 真实会员:仅 unlocks(__vip__)。
|
||||
* 后台免费方案不算开通;切回收费后未解锁用户必须付费。
|
||||
*/
|
||||
export async function resolveVipAccess(forceRefresh = false): Promise<boolean> {
|
||||
if (isDevDebugEnabled()) {
|
||||
const ov = getDevVipOverride()
|
||||
if (ov !== null) {
|
||||
emitVip(ov)
|
||||
return ov
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
if (forceRefresh) await loadRemoteConfig(true)
|
||||
} catch {
|
||||
/* use cache */
|
||||
}
|
||||
const cfg = getCachedRemoteConfig()
|
||||
const price = Number(cfg.copy.vipPriceFen) || 0
|
||||
const pid = String(cfg.copy.vipProductId || '').trim()
|
||||
if (price <= 0 || !pid) return true
|
||||
if (isVipPaidLocal()) return true
|
||||
|
||||
try {
|
||||
await ensureLogin(false)
|
||||
const token = Taro.getStorageSync(STORAGE_TOKEN)
|
||||
const res = await Taro.request({
|
||||
url: `${API_BASE}/api/ebook/pay/vip-status`,
|
||||
method: 'GET',
|
||||
header: token ? { Authorization: `Bearer ${token}` } : {},
|
||||
})
|
||||
if (res.statusCode < 400 && (res.data as { isVip?: boolean })?.isVip) {
|
||||
markVipPaidLocal()
|
||||
return true
|
||||
}
|
||||
} catch {
|
||||
/* offline */
|
||||
// 免费方案下本地缓存不能冒充已开通
|
||||
if (isFreeVipScheme()) {
|
||||
emitVip(false)
|
||||
return false
|
||||
}
|
||||
const local = isVipPaidLocal()
|
||||
emitVip(local)
|
||||
return local
|
||||
}
|
||||
|
||||
try {
|
||||
const data = await requestEbook<{ isVip?: boolean }>({
|
||||
url: '/api/ebook/pay/vip-status',
|
||||
method: 'GET',
|
||||
})
|
||||
const vip = !!data?.isVip
|
||||
emitVip(vip)
|
||||
return vip
|
||||
} catch {
|
||||
if (isFreeVipScheme()) {
|
||||
emitVip(false)
|
||||
return false
|
||||
}
|
||||
const local = isVipPaidLocal()
|
||||
if (lastKnown === null) emitVip(local)
|
||||
return lastKnown ?? local
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 内容权限:真实 VIP,或后台临时免费开放。
|
||||
* 免费仅临时放行,不写本地「已付费」、不写 unlocks。
|
||||
*/
|
||||
export async function resolveVipContentAccess(forceRefresh = false): Promise<boolean> {
|
||||
try {
|
||||
if (forceRefresh) await loadRemoteConfig(true)
|
||||
} catch {
|
||||
/* use cache */
|
||||
}
|
||||
if (isFreeVipScheme()) return true
|
||||
return resolveVipAccess(false)
|
||||
}
|
||||
|
||||
export function hasVipContentAccessSync(isVip: boolean): boolean {
|
||||
return isVip || isFreeVipScheme()
|
||||
}
|
||||
|
||||
async function pollVipStatus(): Promise<void> {
|
||||
if (polling) return
|
||||
polling = true
|
||||
try {
|
||||
await resolveVipAccess(false)
|
||||
} finally {
|
||||
polling = false
|
||||
}
|
||||
}
|
||||
|
||||
/** App 级近实时:每 3s 探 vip-status(真实会员态) */
|
||||
export function startVipAccessLiveSync(): () => void {
|
||||
if (liveStarted) {
|
||||
return () => stopVipAccessLiveSync()
|
||||
}
|
||||
liveStarted = true
|
||||
void pollVipStatus()
|
||||
liveTimer = setInterval(() => {
|
||||
void pollVipStatus()
|
||||
}, VIP_POLL_MS)
|
||||
|
||||
const onShow = () => {
|
||||
void pollVipStatus()
|
||||
}
|
||||
try {
|
||||
Taro.onAppShow?.(onShow)
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
|
||||
return () => {
|
||||
try {
|
||||
Taro.offAppShow?.(onShow)
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
stopVipAccessLiveSync()
|
||||
}
|
||||
}
|
||||
|
||||
export function stopVipAccessLiveSync(): void {
|
||||
liveStarted = false
|
||||
if (liveTimer) {
|
||||
clearInterval(liveTimer)
|
||||
liveTimer = null
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
@ -10,6 +10,17 @@ pnpm --dir apps/miniprogram/weapp build:weapp # 或根目录 pnpm build:weapp
|
||||
|
||||
改页面请改 `apps/miniprogram/h5/src`,不要再复制一份 weapp/src。
|
||||
|
||||
## 包体与代码质量
|
||||
|
||||
| 项 | 做法 |
|
||||
|----|------|
|
||||
| 主包 ≤1.5MB | `app.config.ts`:首页/我的留主包,其余 `subPackages`;`mini.optimizeMainPackage.enable` |
|
||||
| 组件按需注入 | `lazyCodeLoading: "requiredComponents"` |
|
||||
| 图片合计 ≤200K | 导航图标不进包,运行时 `https://nomadro.cn/icons/*.webp`(后台 download/图片域名放行 `nomadro.cn`) |
|
||||
| 安全区 | `utils/safeArea.ts` → `safePx()` 大写 `PX`,避免内联被转 rpx |
|
||||
|
||||
`scripts/copy-weapp-static.mjs`:清历史 `icons/`,只同步必要 `assets`(如公众号二维码)。
|
||||
|
||||
## VIP(原生页,禁止 web-view)
|
||||
|
||||
对齐门户 / nomadvip:`vip` 落地 · `vip-course` 专题 · `vip-lesson` 课时 · `vip-ebook` 电子书 · **`vip-memo` 知识社群** · **`vip-store` 设备商城**。
|
||||
@ -19,6 +30,7 @@ pnpm --dir apps/miniprogram/weapp build:weapp # 或根目录 pnpm build:weapp
|
||||
|----|------|
|
||||
| `vip-memo` / `vip-memo-detail` | 知识星球风格:精华/收藏/Markdown;本地缓存秒开 + 静默刷新 |
|
||||
| `vip-store` / `vip-store-detail` / `vip-store-orders` | 虚拟卡 + 实物;微信收货地址 |
|
||||
| `book` / `reader` | 数字游民小册;后台提审开则读备用合规书(无「提审」UI 文案) |
|
||||
|
||||
电子书 / 课时内容从 `src/modules/vip/app/data` 抽取:
|
||||
|
||||
|
||||
@ -36,7 +36,8 @@ const pxExclude = (file: string) =>
|
||||
/[\\/]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)
|
||||
/[\\/]pages[\\/]vip-memo-detail[\\/]index\.scss/.test(file) ||
|
||||
/[\\/]components[\\/]DebugFab\.scss/.test(file)
|
||||
|
||||
export default defineConfig(async (merge) => {
|
||||
const baseConfig: UserConfigExport = {
|
||||
@ -64,8 +65,11 @@ export default defineConfig(async (merge) => {
|
||||
},
|
||||
copy: {
|
||||
patterns: [
|
||||
{ from: path.join(h5Src, 'assets'), to: 'assets/', ignore: ['**/.DS_Store'] },
|
||||
{ from: path.join(h5Src, 'public', 'icons'), to: 'icons' },
|
||||
{
|
||||
from: path.join(h5Src, 'assets'),
|
||||
to: 'assets/',
|
||||
ignore: ['**/.DS_Store', '**/icons/**'],
|
||||
},
|
||||
],
|
||||
options: {},
|
||||
},
|
||||
@ -85,22 +89,14 @@ export default defineConfig(async (merge) => {
|
||||
'@tarojs/plugin-platform-weapp',
|
||||
path.join(weappNm, '@tarojs/plugin-platform-weapp'),
|
||||
)
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
const CopyWebpackPlugin = require('copy-webpack-plugin')
|
||||
chain.plugin('nomadro-copy-icons').use(CopyWebpackPlugin, [
|
||||
{
|
||||
patterns: [
|
||||
{
|
||||
from: path.join(h5Src, 'public', 'icons'),
|
||||
to: 'icons',
|
||||
noErrorOnMissing: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
])
|
||||
// 导航图标不进包:运行时用 https://nomadro.cn/icons(代码质量:图片合计≤200K)
|
||||
},
|
||||
mini: {
|
||||
enableSourceMap: false,
|
||||
/** 分包独占依赖不进主包 common(压主包 ≤1.5MB) */
|
||||
optimizeMainPackage: {
|
||||
enable: true,
|
||||
},
|
||||
postcss: {
|
||||
pxtransform: {
|
||||
enable: true,
|
||||
|
||||
@ -1,13 +1,12 @@
|
||||
/**
|
||||
* Taro copy.patterns 偶发不落盘;构建后强制把 icons / assets 拷进 dist/weapp。
|
||||
* 真机调试:本地 webp 在部分机型 Image 不渲染 → 同步导出 png,页面统一读 .png。
|
||||
* 分享开关由 markPageShare 挂到 Page 组件(勿写入 page.json)。
|
||||
* 仅微信;抖音见 tt/scripts/copy-static.mjs,小红书见 xhs/。
|
||||
* 构建后静态资源整理(微信):
|
||||
* - 导航图标不进代码包(走 https://nomadro.cn/icons,满足图片合计≤200K)
|
||||
* - 仅保留必要 assets(如公众号二维码)
|
||||
* - 清掉历史误写入的 enableShare*
|
||||
*/
|
||||
import fs from 'fs'
|
||||
import path from 'path'
|
||||
import { fileURLToPath } from 'url'
|
||||
import { spawnSync } from 'child_process'
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const out = 'dist'
|
||||
@ -32,7 +31,11 @@ function copyDir(from, to) {
|
||||
return n
|
||||
}
|
||||
|
||||
/** 清掉历史误写入的 enableShare*,避免开发者工具刷黄字警告 */
|
||||
function rmDir(dir) {
|
||||
if (!fs.existsSync(dir)) return
|
||||
fs.rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
|
||||
function stripInvalidShareKeys(pagesRoot) {
|
||||
if (!fs.existsSync(pagesRoot)) return 0
|
||||
let n = 0
|
||||
@ -54,53 +57,33 @@ function stripInvalidShareKeys(pagesRoot) {
|
||||
return n
|
||||
}
|
||||
|
||||
/**
|
||||
* webp → png(真机兼容)。保留原 webp 作备用。
|
||||
* 用 Pillow;失败时不阻断构建。
|
||||
*/
|
||||
function convertIconsWebpToPng(iconsDir) {
|
||||
if (!fs.existsSync(iconsDir)) return 0
|
||||
const py = `
|
||||
from pathlib import Path
|
||||
try:
|
||||
from PIL import Image
|
||||
except ImportError:
|
||||
raise SystemExit(2)
|
||||
root = Path(r'''${iconsDir.replace(/\\/g, '/')}''')
|
||||
n = 0
|
||||
for src in root.glob('*.webp'):
|
||||
dst = src.with_suffix('.png')
|
||||
im = Image.open(src)
|
||||
if im.mode not in ('RGB', 'RGBA'):
|
||||
im = im.convert('RGBA')
|
||||
im.save(dst, format='PNG', optimize=True)
|
||||
n += 1
|
||||
print(n)
|
||||
`
|
||||
const r = spawnSync('python', ['-c', py], { encoding: 'utf8' })
|
||||
if (r.status === 2) {
|
||||
console.warn('[copy-weapp-static] Pillow missing — skip webp→png (真机图标可能空白)')
|
||||
return 0
|
||||
const h5Src = path.join(root, '..', 'h5', 'src')
|
||||
|
||||
// 主包/分包历史图标一律删掉(改 CDN)
|
||||
rmDir(path.join(root, out, 'icons'))
|
||||
rmDir(path.join(root, out, 'assets', 'icons'))
|
||||
rmDir(path.join(root, out, 'pages', 'nav', 'icons'))
|
||||
|
||||
// assets:只拷非 icons
|
||||
const assetsSrc = path.join(h5Src, 'assets')
|
||||
const assetsDst = path.join(root, out, 'assets')
|
||||
let assets = 0
|
||||
if (fs.existsSync(assetsSrc)) {
|
||||
fs.mkdirSync(assetsDst, { recursive: true })
|
||||
for (const name of fs.readdirSync(assetsSrc)) {
|
||||
if (name === 'icons') continue
|
||||
const src = path.join(assetsSrc, name)
|
||||
const dest = path.join(assetsDst, name)
|
||||
const st = fs.statSync(src)
|
||||
if (st.isDirectory()) assets += copyDir(src, dest)
|
||||
else {
|
||||
fs.copyFileSync(src, dest)
|
||||
assets += 1
|
||||
}
|
||||
}
|
||||
if (r.status !== 0) {
|
||||
console.warn('[copy-weapp-static] webp→png failed:', r.stderr || r.stdout)
|
||||
return 0
|
||||
}
|
||||
const n = Number((r.stdout || '').trim()) || 0
|
||||
return n
|
||||
}
|
||||
|
||||
const h5Src = path.join(root, '..', 'h5', 'src')
|
||||
const icons = copyDir(
|
||||
path.join(h5Src, 'public', 'icons'),
|
||||
path.join(root, out, 'icons'),
|
||||
)
|
||||
const pngs = convertIconsWebpToPng(path.join(root, out, 'icons'))
|
||||
const assets = copyDir(
|
||||
path.join(h5Src, 'assets'),
|
||||
path.join(root, out, 'assets'),
|
||||
)
|
||||
const stripped = stripInvalidShareKeys(path.join(root, out, 'pages'))
|
||||
console.log(
|
||||
`[copy-weapp-static] ${out}: icons=${icons} png=${pngs} assets=${assets} strippedShareJson=${stripped}`,
|
||||
`[copy-weapp-static] ${out}: icons=cdn assets=${assets} strippedShareJson=${stripped}`,
|
||||
)
|
||||
|
||||
@ -115,6 +115,8 @@ export type NomadroRemoteConfig = {
|
||||
/** 加群点击:popup=弹窗;vip=跳会员页。本地默认 vip */
|
||||
joinGroupAction: "popup" | "vip";
|
||||
offlineBadge: boolean;
|
||||
/** VIP 知识社群试读浏览意图(运行时以 memo_settings 为准) */
|
||||
memoTrialBrowse?: boolean;
|
||||
};
|
||||
copy: {
|
||||
homeBrand: string;
|
||||
@ -126,6 +128,7 @@ export type NomadroRemoteConfig = {
|
||||
wechatOaName?: string;
|
||||
joinGroupDouyinHint?: string;
|
||||
joinGroupDouyinQr?: string;
|
||||
memoUnlockCta?: string;
|
||||
};
|
||||
/** 导航页分类 / 链接(后台可增删改隐) */
|
||||
navContent?: NavContent;
|
||||
@ -313,6 +316,7 @@ export const DEFAULT_REMOTE_CONFIG: NomadroRemoteConfig = {
|
||||
joinGroupDouyin: false,
|
||||
joinGroupAction: "popup",
|
||||
offlineBadge: false,
|
||||
memoTrialBrowse: true,
|
||||
},
|
||||
copy: {
|
||||
homeBrand: "nomadro",
|
||||
@ -324,6 +328,7 @@ export const DEFAULT_REMOTE_CONFIG: NomadroRemoteConfig = {
|
||||
wechatOaName: "异度世界",
|
||||
joinGroupDouyinHint: "打开抖音搜群「数字游民」或扫码进群",
|
||||
joinGroupDouyinQr: "",
|
||||
memoUnlockCta: "解锁 VIP 读全文",
|
||||
},
|
||||
navContent: structuredClone(DEFAULT_NAV_CONTENT),
|
||||
platforms: {
|
||||
@ -446,6 +451,10 @@ export function mergeRemoteConfig(
|
||||
joinGroupDouyin: asBool(pf.joinGroupDouyin, base.flags.joinGroupDouyin),
|
||||
joinGroupAction: joinAction,
|
||||
offlineBadge: asBool(pf.offlineBadge, base.flags.offlineBadge),
|
||||
memoTrialBrowse: asBool(
|
||||
pf.memoTrialBrowse,
|
||||
base.flags.memoTrialBrowse !== false,
|
||||
),
|
||||
},
|
||||
copy: { ...base.copy, ...(partial.copy || {}) },
|
||||
navContent: mergeNavContent(
|
||||
|
||||
Loading…
Reference in New Issue
Block a user