Give each ebook independent trial percent and paid unlock offers.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Eric 2026-11-22 11:45:01 +08:00
parent 1c2486a9c5
commit cee288b764
8 changed files with 630 additions and 81 deletions

View File

@ -0,0 +1,82 @@
# -*- coding: utf-8 -*-
"""Deploy admin.py (book shells) + admin SPA for per-book monetize."""
from __future__ import annotations
import subprocess
import tarfile
import time
from io import BytesIO
from pathlib import Path
import paramiko
REPO = Path(__file__).resolve().parents[3]
ROOT = REPO / "apps" / "admin"
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
def main() -> int:
print("vite build…", flush=True)
r = subprocess.run(
["pnpm", "exec", "vite", "build"],
cwd=ROOT,
shell=True,
capture_output=True,
encoding="utf-8",
errors="replace",
)
if r.returncode != 0:
print(r.stdout)
print(r.stderr)
return r.returncode
dist = ROOT / "dist"
buf = BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
for p in dist.rglob("*"):
if p.is_file():
tar.add(p, arcname="admin-dist/" + p.relative_to(dist).as_posix())
buf.seek(0)
api = (REPO / "apps/api/services/ebook_svc/routers/admin.py").read_text(encoding="utf-8")
api = api.replace("ebook_svc.", "app.").encode("utf-8")
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASS, timeout=60, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
with sftp.file("/tmp/admin-spa.tar.gz", "wb") as rf:
rf.write(buf.getvalue())
with sftp.file("/tmp/admin.py", "wb") as rf:
rf.write(api)
sftp.close()
cmd = r"""
set -e
# keep props
sudo mkdir -p /tmp/props-bak && sudo cp -a /www/wwwroot/admin.nomadro.cn/props/. /tmp/props-bak/ 2>/dev/null || true
cd /tmp
rm -rf admin-unpack && mkdir admin-unpack
tar -xzf admin-spa.tar.gz -C admin-unpack
sudo rsync -a --delete admin-unpack/admin-dist/ /www/wwwroot/admin.nomadro.cn/
sudo mkdir -p /www/wwwroot/admin.nomadro.cn/props
sudo cp -a /tmp/props-bak/. /www/wwwroot/admin.nomadro.cn/props/ 2>/dev/null || true
sudo chown -R www:www /www/wwwroot/admin.nomadro.cn
sudo cp /tmp/admin.py /opt/nomadmini/backend/app/routers/admin.py
sudo systemctl restart nomadmini-api.service
sleep 2
systemctl is-active nomadmini-api.service
curl -sk -o /dev/null -w "admin %{http_code}\n" https://admin.nomadro.cn/wechat/vip/ebooks/nomad
curl -sk -o /dev/null -w "props %{http_code}\n" https://admin.nomadro.cn/props/nomad_lite.png
"""
_, stdout, stderr = c.exec_command(cmd, timeout=120)
print(stdout.read().decode())
err = stderr.read().decode()
if err:
print("STDERR", err[-800:])
c.close()
return 0
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,235 @@
/**
* 单本小册独立试读/付费方案(互不影响)。
* 数据落在 books/{bookId}:product_id / price_fen / unlock_percent。
*/
import { useCallback, useEffect, useMemo, useState } from 'react'
import { api } from '../api'
import '../pages/BookEdit.css'
export type ProductOffer = {
key: string
label: string
name: string
product_id: string
price_fen: number
price_yuan: string
free: boolean
image: string
remark?: string
}
export type BookMonetize = {
id: string
title?: string
product_id: string
price_fen: number
unlock_percent: number
offer_key?: string
offer_name?: string
is_free?: boolean
}
type Props = {
bookId: string
/** 展示名,如「数字游民」 */
bookLabel?: string
/** 方案变更后回调(可用来同步 VIP 库 free 标记) */
onChanged?: (book: BookMonetize) => void
}
export default function BookMonetizePanel({ bookId, bookLabel, onChanged }: Props) {
const [book, setBook] = useState<BookMonetize | null>(null)
const [offers, setOffers] = useState<ProductOffer[]>([])
const [busy, setBusy] = useState(false)
const [msg, setMsg] = useState('')
const [err, setErr] = useState('')
const load = useCallback(async () => {
const [b, o] = await Promise.all([
api<BookMonetize>(`/api/admin/books/${encodeURIComponent(bookId)}`),
api<{ items: ProductOffer[] }>('/api/admin/product-offers'),
])
setBook(b)
setOffers(o.items || [])
}, [bookId])
useEffect(() => {
setMsg('')
setErr('')
load().catch((e) => setErr(e.message || '加载付费方案失败'))
}, [load])
const isFree = !!book && (book.is_free || book.unlock_percent >= 100 || !book.product_id)
const activeOfferKey = useMemo(() => {
if (!book) return ''
if (book.offer_key) return book.offer_key
if (isFree) return 'free'
return (
offers.find((o) => !o.free && o.product_id === book.product_id)?.key ||
''
)
}, [book, offers, isFree])
async function applyOffer(offerKey: string) {
if (!bookId || busy) return
setBusy(true)
setMsg('')
setErr('')
try {
const updated = await api<BookMonetize>(
`/api/admin/books/${encodeURIComponent(bookId)}/offer`,
{
method: 'POST',
body: JSON.stringify({ offer_key: offerKey, keep_preview_percent: true }),
},
)
setBook(updated)
onChanged?.(updated)
const label = offers.find((o) => o.key === offerKey)?.name || offerKey
setMsg(
updated.unlock_percent >= 100 || !updated.product_id
? `「${bookLabel || bookId}」已切免费 · 与其它小册互不影响`
: `「${bookLabel || bookId}」已切 ${label} · 试读 ${Math.min(99, updated.unlock_percent)}% · 仅本册`,
)
} catch (e: any) {
setErr(e.message || '切换方案失败')
await load().catch(() => undefined)
} finally {
setBusy(false)
}
}
async function savePreview() {
if (!book || busy) return
setBusy(true)
setMsg('')
setErr('')
try {
const updated = await api<BookMonetize>(
`/api/admin/books/${encodeURIComponent(bookId)}`,
{
method: 'PUT',
body: JSON.stringify({
unlock_percent: Math.min(99, Math.max(1, Number(book.unlock_percent) || 30)),
}),
},
)
setBook(updated)
onChanged?.(updated)
setMsg(`「${bookLabel || bookId}」试读 ${Math.min(99, updated.unlock_percent)}% 已保存 · 仅本册`)
} catch (e: any) {
setErr(e.message || '保存失败')
} finally {
setBusy(false)
}
}
if (!book && !err) {
return <section className="monetize-panel">加载本册付费方案…</section>
}
if (!book) {
return (
<section className="monetize-panel">
<p className="hint" style={{ color: '#f87171' }}>
{err}
</p>
</section>
)
}
return (
<section className="monetize-panel">
<div className="monetize-head">
<div>
<h2 className="monetize-title">本册 · 试读与付费</h2>
<p className="hint">
只改《{bookLabel || book.title || bookId}》的道具与试读比例,不影响其它小册 / VIP
会员价。后台切换后小程序约 1–2 秒热更新。
</p>
</div>
<div className="live-preview">
<span className="live-preview-label">本册按钮预览</span>
<div className={`live-btn ${isFree ? 'free' : ''}`}>
{isFree ? '开始阅读' : `解锁全文 · ¥${(book.price_fen / 100).toFixed(0)}`}
</div>
<span className="live-preview-sub">
{isFree
? '免费模式 · 无支付墙'
: `${book.offer_name || book.product_id || '-'} · 试读 ${Math.min(99, book.unlock_percent)}%`}
</span>
</div>
</div>
{err ? <p className="hint" style={{ color: '#f87171' }}>{err}</p> : null}
{msg ? <p className="hint" style={{ color: '#6ee7b7' }}>{msg}</p> : null}
<div className="offer-grid offer-grid-6">
{offers.map((o) => {
const active = o.key === activeOfferKey
const img = o.image ? `/${o.image.replace(/^\/+/, '')}` : ''
return (
<button
key={o.key}
type="button"
className={`offer-card ${active ? 'active' : ''} ${o.free ? 'is-free' : ''}`}
disabled={busy}
onClick={() => void applyOffer(o.key)}
>
{o.free ? (
<div className="offer-free-badge">FREE</div>
) : img ? (
<img className="offer-img" src={img} alt={o.label} />
) : (
<div className="offer-free-badge">{o.product_id.slice(0, 6)}</div>
)}
<strong>{o.name || o.label}</strong>
<span className="offer-id">{o.free ? '免费加入' : o.product_id}</span>
<em>{o.price_yuan}</em>
{o.remark ? <i className="offer-remark">{o.remark}</i> : null}
{active ? <b className="offer-on">本册使用中</b> : null}
</button>
)
})}
</div>
{!isFree ? (
<div className="unlock-hero monetize-unlock">
<div>
<label>本册试读比例</label>
<div className="unlock-row">
<input
type="range"
min={1}
max={99}
value={Math.min(99, book.unlock_percent)}
disabled={busy}
onChange={(e) =>
setBook({ ...book, unlock_percent: Number(e.target.value) })
}
/>
<strong>{Math.min(99, book.unlock_percent)}%</strong>
</div>
<p className="hint">点「保存试读」写入本册;点免费卡片 = 全书开放。</p>
<button type="button" className="file-btn" disabled={busy} onClick={() => void savePreview()}>
保存试读比例
</button>
</div>
<div className="price-box mono-box">
<div>
<label>本册道具 ID</label>
<code>{book.product_id || '—'}</code>
</div>
<div>
<label>本册价格</label>
<code>
¥{(book.price_fen / 100).toFixed(0)}({book.price_fen} 分)
</code>
</div>
</div>
</div>
) : (
<div className="free-banner">本册当前免费全书;其它小册付费设置不变。</div>
)}
</section>
)
}

View File

@ -298,9 +298,9 @@ export default function BookEdit() {
<section className="monetize-panel">
<div className="monetize-head">
<div>
<h2 className="monetize-title">阅读与付费</h2>
<h2 className="monetize-title">本册 · 试读与付费</h2>
<p className="hint">
随时切换免费 / 付费档。小程序封面与阅读页约 1–2 秒热更新价格与解锁按钮,无需重进。
只改本册道具与试读比例,与其它小册互不影响。小程序约 1–2 秒热更新。
</p>
</div>
<div className="live-preview">

View File

@ -1,6 +1,7 @@
import { Link, useLocation, useNavigate, useParams } from 'react-router-dom'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { api } from '../api'
import BookMonetizePanel, { type BookMonetize } from '../components/BookMonetizePanel'
import './Vip.css'
type Ebook = {
@ -501,25 +502,23 @@ export default function VipLibrary() {
onChange={(e) => setDraftTitle(e.target.value)}
/>
</div>
<div className="vip-row" style={{ border: 'none', padding: '0 0 8px' }}>
<div>
<strong>免费开放</strong>
<p className="vip-hint">打开后无需会员也能读完全书</p>
</div>
<label className="vip-switch">
<input
type="checkbox"
checked={draftFree}
disabled={busy}
onChange={(e) => setDraftFree(e.target.checked)}
/>
<span className="vip-switch-track">
<span className="vip-switch-thumb" />
</span>
</label>
</div>
</div>
{/* 每本独立试读/道具,与 youtube运营笔记(books/default) 同机制、互不影响 */}
<BookMonetizePanel
bookId={bookId}
bookLabel={bookLabel}
onChanged={(m: BookMonetize) => {
const free = !!(m.is_free || m.unlock_percent >= 100 || !m.product_id)
setDraftFree(free)
// 同步 VIP 库 free 标记,供落地页卡片展示;付费字段以 books 表为准
void api(`/api/admin/vip/library/ebooks/${bookId}`, {
method: 'PUT',
body: JSON.stringify({ free }),
}).catch(() => undefined)
}}
/>
<div className="vip-layout">
<aside className="vip-item-list" style={{ maxHeight: 520, overflow: 'auto' }}>
{draftSections.map((_, i) => (

View File

@ -121,16 +121,27 @@ async def admin_delete_book(book_id: str, _: str = Depends(require_admin)):
return {"ok": True}
_BOOK_SHELL_TITLES = {
"audit": ("数字游民·提审版", "微信提审专用 · 与正式会员书无关"),
"nomad": ("数字游民", "VIP 电子书 · 本册独立试读/付费"),
"cloudphone": ("云手机", "VIP 电子书 · 本册独立试读/付费"),
"default": ("Youtube运营笔记", "专属小册 · 本册独立试读/付费"),
}
@router.get("/books/{book_id}")
async def admin_book(book_id: str, _: str = Depends(require_admin)):
book = store.get_book(book_id)
# 审核备用书等:首次打开自动建壳,避免 404
# 审核备用书 / VIP 电子书付费壳:首次打开自动建壳(每本独立,互不影响)
if not book:
try:
title, subtitle = _BOOK_SHELL_TITLES.get(
book_id, (book_id, "本册独立试读/付费壳")
)
book = store.ensure_book(
book_id,
title="数字游民·提审版" if book_id == "audit" else book_id,
subtitle="微信提审专用 · 与正式会员书无关",
title=title,
subtitle=subtitle,
free=True,
)
except Exception:

View File

@ -126,16 +126,27 @@ async def admin_delete_book(book_id: str, _: str = Depends(require_admin)):
return {"ok": True}
_BOOK_SHELL_TITLES = {
"audit": ("数字游民·提审版", "微信提审专用 · 与正式会员书无关"),
"nomad": ("数字游民", "VIP 电子书 · 本册独立试读/付费"),
"cloudphone": ("云手机", "VIP 电子书 · 本册独立试读/付费"),
"default": ("Youtube运营笔记", "专属小册 · 本册独立试读/付费"),
}
@router.get("/books/{book_id}")
async def admin_book(book_id: str, _: str = Depends(require_admin)):
book = store.get_book(book_id)
# 审核备用书等:首次打开自动建壳,避免 404
# 审核 / VIP 电子书付费壳:每本独立,互不影响
if not book:
try:
title, subtitle = _BOOK_SHELL_TITLES.get(
book_id, (book_id, "本册独立试读/付费壳")
)
book = store.ensure_book(
book_id,
title="数字游民·提审版" if book_id == "audit" else book_id,
subtitle="微信提审专用 · 与正式会员书无关",
title=title,
subtitle=subtitle,
free=True,
)
except Exception:

View File

@ -117,6 +117,61 @@
padding: 24px 0 calc(48px + env(safe-area-inset-bottom, 0px));
}
.veb-paywall {
margin: 8px 16px calc(48px + env(safe-area-inset-bottom, 0px));
padding: 28px 20px 24px;
border-radius: 20px;
border: 1px solid rgba(255, 230, 109, 0.28);
background:
radial-gradient(280px 120px at 50% 0%, rgba(255, 107, 107, 0.18), transparent 60%),
rgba(15, 21, 36, 0.92);
text-align: center;
}
.veb-paywall-title {
display: block;
font-size: 18px;
font-weight: 800;
color: #f8fafc;
margin-bottom: 8px;
}
.veb-paywall-sub {
display: block;
font-size: 13px;
color: #94a3b8;
line-height: 1.5;
margin-bottom: 18px;
}
.veb-paywall-btn {
width: 100%;
min-height: 48px;
border-radius: 999px !important;
border: none !important;
font-size: 16px !important;
font-weight: 700 !important;
color: #0a0e17 !important;
background: linear-gradient(135deg, #ffe66d, #ff6b6b) !important;
}
.veb-paywall-vip {
margin-top: 14px;
min-height: 44px;
display: flex;
align-items: center;
justify-content: center;
color: #4ecdc4;
font-size: 14px;
}
.veb-drawer-item.is-locked {
opacity: 0.55;
}
.veb-drawer-lock {
margin-left: auto;
font-size: 11px;
color: #fbbf24;
padding: 2px 6px;
border-radius: 999px;
border: 1px solid rgba(251, 191, 36, 0.35);
}
/* —— 目录抽屉(左侧,对齐 reader) —— */
.veb-drawer-root {
position: fixed;

View File

@ -2,8 +2,8 @@
* VIP 电子书 — 复刻 nomadvip EbookViewer 目录交互
* 顶栏 ☰ 开目录(对齐小程序 reader),左侧抽屉可跳章节
*/
import { View, Text, ScrollView, Input } from '@tarojs/components'
import Taro, { useRouter } from '@tarojs/taro'
import { View, Text, ScrollView, Input, Button } from '@tarojs/components'
import Taro, { useDidShow, useRouter } from '@tarojs/taro'
import { useEffect, useMemo, useState } from 'react'
import { H5Box, H5Txt } from '../../components/H5Box'
import { MarkdownView } from '../../components/MarkdownView'
@ -29,9 +29,54 @@ import {
subscribeRemoteConfig,
} from '../../services/remoteConfig'
import { resolveBookAudit } from '../../data/remoteConfig.defaults'
import { fetchAuditRead, getAuditOfflineRead } from '../../services/ebookApi'
import {
fetchAccess,
fetchAuditRead,
fetchBook,
getAuditOfflineRead,
pollUnlock,
type BookDetail,
} from '../../services/ebookApi'
import { runUnlockPayment } from '../../utils/payFlow'
import './index.scss'
type BookPayMeta = {
is_free: boolean
unlock_percent: number
product_id: string
price_fen: number
unlock_btn_text: string
offer_name: string
unlocked: boolean
}
function metaFromBook(b: BookDetail | null | undefined, unlocked = false): BookPayMeta {
if (!b) {
return {
is_free: unlocked,
unlock_percent: unlocked ? 100 : 30,
product_id: '',
price_fen: 0,
unlock_btn_text: unlocked ? '开始阅读' : '解锁全文',
offer_name: '',
unlocked,
}
}
const unlock = Number(b.unlock_percent ?? 30)
const free = !!(b.is_free || unlock >= 100 || !b.product_id)
return {
is_free: free,
unlock_percent: free ? 100 : Math.min(99, Math.max(1, unlock)),
product_id: free ? '' : String(b.product_id || ''),
price_fen: free ? 0 : Number(b.price_fen || 0),
unlock_btn_text:
b.unlock_btn_text ||
(free ? '开始阅读' : `解锁全文 · ¥${Math.round(Number(b.price_fen || 0) / 100)}`),
offer_name: b.offer_name || '',
unlocked,
}
}
function auditPayloadToPack(
bookId: string,
payload: ReturnType<typeof getAuditOfflineRead>,
@ -74,8 +119,28 @@ export default function VipEbookPage() {
const bookId = resolveVipEbookId(rawParam)
const safe = getSafeAreaMetrics()
const [book, setBook] = useState<VipEbookPack>(VIP_EBOOKS[bookId])
const [allowed, setAllowed] = useState(VIP_EBOOKS[bookId].free)
const [payMeta, setPayMeta] = useState<BookPayMeta>(() =>
metaFromBook({
id: bookId,
title: '',
subtitle: '',
author: '',
cover_emoji: '',
description: '',
tags: [],
price_fen: 0,
product_id: '',
unlock_percent: 100,
is_free: true,
chapter_count: 0,
word_count: 0,
rating: 0,
chapters: [],
}),
)
const [isVip, setIsVip] = useState(false)
const [ready, setReady] = useState(false)
const [paying, setPaying] = useState(false)
const [drawerOpen, setDrawerOpen] = useState(false)
const [tocFilter, setTocFilter] = useState('')
const [scrollInto, setScrollInto] = useState('')
@ -83,6 +148,42 @@ export default function VipEbookPage() {
const [readProgress, setReadProgress] = useState(0)
const [showBackTop, setShowBackTop] = useState(false)
/** 本册全文:VIP / 本册已购 / 本册免费(与其它小册互不影响) */
const fullAccess =
payMeta.is_free || payMeta.unlocked || isVip || !!book.free
const previewCount = useMemo(() => {
const n = book.sections.length
if (fullAccess || n <= 0) return n
return Math.max(1, Math.floor((n * payMeta.unlock_percent) / 100))
}, [book.sections.length, fullAccess, payMeta.unlock_percent])
const visibleSections = useMemo(
() => (fullAccess ? book.sections : book.sections.slice(0, previewCount)),
[book.sections, fullAccess, previewCount],
)
async function refreshPayMeta(packFree?: boolean) {
try {
const [detail, access] = await Promise.all([
fetchBook(bookId).catch(() => null),
fetchAccess(bookId).catch(() => null),
])
const unlocked = !!(access?.unlocked || access?.is_free)
const next = metaFromBook(detail || undefined, unlocked)
if (packFree) {
next.is_free = true
next.unlock_percent = 100
next.product_id = ''
next.price_fen = 0
}
setPayMeta(next)
return next
} catch {
return payMeta
}
}
const toc: TocItem[] = useMemo(() => {
const titles =
book.headers.length > 0
@ -140,7 +241,8 @@ export default function VipEbookPage() {
}
if (cancelled) return
setBook(pack)
setAllowed(true)
setPayMeta(metaFromBook(undefined, true))
setIsVip(true)
Taro.setNavigationBarTitle({ title: pack.title })
return
}
@ -150,30 +252,16 @@ export default function VipEbookPage() {
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') })
},
})
}
setIsVip(vip)
await refreshPayMeta(!!next.free)
} catch {
if (cancelled) return
// 失败也必须结束加载态,展示包内正式书
const fallback = VIP_EBOOKS[bookId] || VIP_EBOOKS.nomad
setBook(fallback)
setAllowed(!!fallback.free)
setIsVip(false)
await refreshPayMeta(!!fallback.free)
Taro.setNavigationBarTitle({ title: fallback.title })
} finally {
if (!cancelled) setReady(true)
@ -184,12 +272,20 @@ export default function VipEbookPage() {
}
}, [bookId])
// 后台开关提审:仍在本页换正文,保持与正式相同阅读壳
// 提审开关 + 本册付费方案 bump → 热刷新(只动当前 bookId)
useEffect(() => {
if (bookId !== 'nomad') return
let lastOfferRev = -1
return subscribeRemoteConfig((r) => {
const rev = Number(r.config.copy?.booksOfferRev || 0)
const bumped = String(r.config.copy?.booksOfferBookId || '')
if (rev !== lastOfferRev) {
lastOfferRev = rev
if (!bumped || bumped === bookId) {
void refreshPayMeta(!!book.free)
}
}
if (bookId !== 'nomad') return
const audit = resolveBookAudit(r.config)
// 开关变化时重拉:关提审 → 正式 VIP 包;开提审 → audit 正文
setReady(false)
void (async () => {
try {
@ -198,34 +294,69 @@ export default function VipEbookPage() {
const res = await fetchAuditRead(auditId)
const pack = auditPayloadToPack(auditId, res.payload)
setBook(pack)
setAllowed(true)
setPayMeta(metaFromBook(undefined, true))
Taro.setNavigationBarTitle({ title: pack.title })
} else {
const { book: next } = await loadVipEbook('nomad')
setBook(next)
setAllowed(!!next.free || (await resolveVipContentAccess(true)))
setIsVip(await resolveVipContentAccess(true))
await refreshPayMeta(!!next.free)
Taro.setNavigationBarTitle({ title: next.title })
}
} catch {
/* keep current */
/* keep */
} finally {
setReady(true)
}
})()
})
}, [bookId])
}, [bookId, book.free])
// 后台开通 VIP:App 级 3s 轮询 → 近实时放行
useEffect(() => {
return subscribeVipAccess((vip) => {
const pack = VIP_EBOOKS[bookId]
if (pack?.free) {
setAllowed(true)
return
}
setAllowed(hasVipContentAccessSync(vip))
setIsVip(hasVipContentAccessSync(vip))
})
}, [bookId])
}, [])
useDidShow(() => {
if (youtubeMisroute) return
void refreshPayMeta(!!book.free)
void resolveVipContentAccess(true).then(setIsVip)
})
async function handleUnlockBook() {
if (paying || fullAccess) return
await refreshPayMeta(!!book.free)
if (payMeta.is_free || payMeta.unlocked) return
if (!payMeta.product_id || payMeta.price_fen <= 0) {
goVipUnlock()
return
}
setPaying(true)
try {
const { outTradeNo } = await runUnlockPayment(bookId)
for (let i = 0; i < 12; i++) {
await new Promise((r) => setTimeout(r, 700))
try {
if (await pollUnlock(bookId, outTradeNo)) {
setPayMeta((m) => ({ ...m, unlocked: true }))
Taro.showToast({ title: '已解锁本册', icon: 'success' })
return
}
} catch {
/* retry */
}
}
Taro.showToast({ title: '支付确认中,请稍后下拉刷新', icon: 'none' })
} catch (e) {
const msg = e instanceof Error ? e.message : String(e)
if (!/cancel|取消|-2/i.test(msg)) {
Taro.showModal({ title: '支付未完成', content: msg, showCancel: false })
}
} finally {
setPaying(false)
}
}
function onScroll(e: {
detail?: { scrollTop?: number; scrollHeight?: number }
@ -246,11 +377,13 @@ export default function VipEbookPage() {
}
function jumpTo(secIndex: number) {
const idx = Math.max(0, Math.min(secIndex, book.sections.length - 1))
const maxIdx = fullAccess
? book.sections.length - 1
: Math.max(0, previewCount - 1)
const idx = Math.max(0, Math.min(secIndex, maxIdx))
setActiveSec(idx)
setDrawerOpen(false)
const id = `veb-sec-${idx}`
// 先清空再设,触发 scroll-into-view
setScrollInto('')
setTimeout(() => setScrollInto(id), 120)
}
@ -278,22 +411,12 @@ export default function VipEbookPage() {
)
}
if (!allowed) {
return (
<H5Box className="veb" data-theme={theme}>
<H5Txt className="veb-loading">🔒 开通会员后阅读《{book.title}》</H5Txt>
<View className="veb-locked-cta" onClick={() => goVipUnlock()}>
<Text>立即开通</Text>
</View>
</H5Box>
)
}
const remainMin = Math.max(
0,
Math.ceil(book.estimatedMinutes * (1 - readProgress / 100)),
)
const drawerListH = `calc(100vh - ${safe.statusBarHeight + 200}px)`
const needsPaywall = !fullAccess && visibleSections.length < book.sections.length
return (
<H5Box className="veb" data-theme={theme}>
@ -311,7 +434,10 @@ export default function VipEbookPage() {
<View className="veb-title-wrap" onClick={openDrawer}>
<Text className="veb-title">{book.title}</Text>
<Text className="veb-sub">
{activeSec + 1}/{book.sections.length} · 约剩 {remainMin} 分钟 · 点此开目录
{fullAccess
? `${activeSec + 1}/${book.sections.length} · 约剩 ${remainMin} 分钟`
: `试读 ${payMeta.unlock_percent}% · ${visibleSections.length}/${book.sections.length} 章`}
{' · 点此开目录'}
</Text>
</View>
<View className="veb-icon-btn" onClick={goBack} hoverClass="veb-icon-btn-hover">
@ -331,13 +457,34 @@ export default function VipEbookPage() {
onScroll={onScroll}
>
<View className="veb-book">
{book.sections.map((sec, i) => (
{visibleSections.map((sec, i) => (
<View key={`sec-${i}`} id={`veb-sec-${i}`} className="veb-section">
<MarkdownView markdown={sec} prefs={EBOOK_PREFS} />
</View>
))}
</View>
<View className="veb-end">— 全书完 —</View>
{needsPaywall ? (
<View className="veb-paywall" id="veb-paywall">
<Text className="veb-paywall-title">试读结束 · 解锁本册全文</Text>
<Text className="veb-paywall-sub">
{payMeta.offer_name
? `${payMeta.offer_name} · 仅解锁《${book.title}》,不影响其它小册`
: `仅解锁《${book.title}》,与其它小册互不影响`}
</Text>
<Button
className="veb-paywall-btn"
loading={paying}
onClick={() => void handleUnlockBook()}
>
{paying ? '拉起支付…' : payMeta.unlock_btn_text}
</Button>
<View className="veb-paywall-vip" onClick={() => goVipUnlock()}>
<Text>或开通 VIP 读全部会员书</Text>
</View>
</View>
) : (
<View className="veb-end">— 全书完 —</View>
)}
</ScrollView>
{/* 目录抽屉:mask 与 drawer 分离,避免点击穿透 */}
@ -389,16 +536,25 @@ export default function VipEbookPage() {
) : (
filteredToc.map((item, listIdx) => {
const active = item.index === activeSec
const locked = !fullAccess && item.index >= previewCount
return (
<View
key={`toc-${listIdx}-${item.index}`}
className={`veb-drawer-item${active ? ' is-active' : ''}`}
onClick={() => jumpTo(item.index)}
className={`veb-drawer-item${active ? ' is-active' : ''}${locked ? ' is-locked' : ''}`}
onClick={() => {
if (locked) {
setDrawerOpen(false)
setTimeout(() => setScrollInto('veb-paywall'), 80)
return
}
jumpTo(item.index)
}}
>
<Text className="veb-drawer-idx">
{String(item.index + 1).padStart(2, '0')}
</Text>
<Text className="veb-drawer-name">{item.title}</Text>
{locked ? <Text className="veb-drawer-lock">锁</Text> : null}
</View>
)
})