Hot-sync ebook and VIP offer changes from admin to clients within 1-2s.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
76c22c23f4
commit
1c2486a9c5
50
apps/admin/deploy/_deploy_books_live_82.py
Normal file
50
apps/admin/deploy/_deploy_books_live_82.py
Normal file
@ -0,0 +1,50 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Deploy books_live + admin router (offer hot bump) to api.nomadro.cn."""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import paramiko
|
||||
|
||||
REPO = Path(__file__).resolve().parents[3]
|
||||
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
|
||||
FILES = [
|
||||
(
|
||||
REPO / "apps/api/services/ebook_svc/services/books_live.py",
|
||||
"/opt/nomadmini/backend/app/services/books_live.py",
|
||||
),
|
||||
(
|
||||
REPO / "apps/api/services/ebook_svc/routers/admin.py",
|
||||
"/opt/nomadmini/backend/app/routers/admin.py",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def main() -> None:
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect(HOST, username=USER, password=PASS, timeout=40, allow_agent=False, look_for_keys=False)
|
||||
sftp = c.open_sftp()
|
||||
for src, dest in FILES:
|
||||
data = src.read_text(encoding="utf-8").replace("ebook_svc.", "app.").encode("utf-8")
|
||||
tmp = f"/tmp/{Path(dest).name}"
|
||||
with sftp.file(tmp, "wb") as rf:
|
||||
rf.write(data)
|
||||
print("up", src.name, len(data))
|
||||
sftp.close()
|
||||
_, o, e = c.exec_command(
|
||||
"sudo cp /tmp/books_live.py /opt/nomadmini/backend/app/services/books_live.py && "
|
||||
"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 -s http://127.0.0.1:8010/health",
|
||||
timeout=60,
|
||||
)
|
||||
print(o.read().decode())
|
||||
err = e.read().decode()
|
||||
if err:
|
||||
print("STDERR", err[-800:])
|
||||
c.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
50
apps/admin/deploy/_smoke_live_offer_82.py
Normal file
50
apps/admin/deploy/_smoke_live_offer_82.py
Normal file
@ -0,0 +1,50 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Smoke: admin VIP + book offer switch bumps remote config for live sync."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import urllib.request
|
||||
|
||||
BASE = "https://api.nomadro.cn"
|
||||
|
||||
|
||||
def post(url: str, data: dict | None = None, token: str = "") -> dict:
|
||||
body = None if data is None else json.dumps(data).encode()
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if token:
|
||||
headers["Authorization"] = "Bearer " + token
|
||||
req = urllib.request.Request(url, data=body, headers=headers, method="POST" if body else "GET")
|
||||
with urllib.request.urlopen(req, timeout=20) as r:
|
||||
return json.loads(r.read().decode())
|
||||
|
||||
|
||||
def main() -> None:
|
||||
tok = post(f"{BASE}/api/admin/login", {"username": "admin", "password": "Xiao4669805"})["token"]
|
||||
before = post(f"{BASE}/api/config/pull", {"t": 1})
|
||||
cfg0 = before.get("config") or {}
|
||||
print("before", cfg0.get("version"), (cfg0.get("copy") or {}).get("vipProductId"), (cfg0.get("copy") or {}).get("booksOfferRev"))
|
||||
|
||||
vip = post(f"{BASE}/api/admin/vip/offer", {"offer_key": "nomad"}, tok)
|
||||
print("vip", vip.get("vipProductId"), vip.get("vipPriceFen"), vip.get("vipCta"))
|
||||
|
||||
book = post(f"{BASE}/api/admin/books/default/offer", {"offer_key": "yen29"}, tok)
|
||||
print("book", book.get("product_id"), book.get("price_fen"), book.get("offer_name"))
|
||||
|
||||
after = post(f"{BASE}/api/config/pull", {"t": 2})
|
||||
cfg1 = after.get("config") or {}
|
||||
copy = cfg1.get("copy") or {}
|
||||
print(
|
||||
"after",
|
||||
cfg1.get("version"),
|
||||
copy.get("vipProductId"),
|
||||
copy.get("vipPriceFen"),
|
||||
copy.get("booksOfferRev"),
|
||||
copy.get("booksOfferBookId"),
|
||||
)
|
||||
# restore book to nomad (main push)
|
||||
restored = post(f"{BASE}/api/admin/books/default/offer", {"offer_key": "nomad"}, tok)
|
||||
print("restore_book", restored.get("product_id"), restored.get("offer_name"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@ -300,7 +300,7 @@ export default function BookEdit() {
|
||||
<div>
|
||||
<h2 className="monetize-title">阅读与付费</h2>
|
||||
<p className="hint">
|
||||
切换免费或付费方案后,小程序「解锁全文」按钮会跟着变(需重新打开阅读页)。
|
||||
随时切换免费 / 付费档。小程序封面与阅读页约 1–2 秒热更新价格与解锁按钮,无需重进。
|
||||
</p>
|
||||
</div>
|
||||
<div className="live-preview">
|
||||
|
||||
@ -392,7 +392,7 @@ export default function Vip() {
|
||||
setMsg(
|
||||
saved.is_free
|
||||
? '已切换免费 · 小程序「立即加入」→ 免费加入'
|
||||
: `已切换 ${saved.vipProductId} · CTA「${saved.vipCta}」约 3s 热更新`,
|
||||
: `已切换 ${saved.vipProductId || saved.vipOfferKey} · CTA「${saved.vipCta}」约 1s 热更新`,
|
||||
)
|
||||
} catch (e: any) {
|
||||
setErr(e.message || '切换方案失败')
|
||||
@ -416,7 +416,7 @@ export default function Vip() {
|
||||
<div className="vip-eyebrow">WeChat · VIP · Remote</div>
|
||||
<h1>VIP 运营</h1>
|
||||
<p>
|
||||
只影响微信小程序 · 不改抖音 · 不改订单。付费与落地页写远程配置,小程序约 3 秒热更新。
|
||||
只影响微信小程序 · 不改抖音 · 不改订单。付费与落地页写远程配置,小程序约 1 秒热更新(WS + 轮询)。
|
||||
</p>
|
||||
<div className="vip-chips">
|
||||
<span className={`vip-chip ${draft.vipEnabled ? 'on' : ''}`}>
|
||||
@ -474,7 +474,7 @@ export default function Vip() {
|
||||
<div>
|
||||
<h2>立即加入 · 付费控制</h2>
|
||||
<p>
|
||||
一键切换免费 / 已发布道具。切换后小程序按钮文案与价格立即跟随(已打开会员页约 3s
|
||||
一键切换免费 / 已发布道具。切换后小程序 CTA 与价格立即跟随(已打开会员页约 1s
|
||||
热更新)。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@ -164,6 +164,13 @@ async def admin_update_book(book_id: str, body: BookPatch, _: str = Depends(requ
|
||||
await pb.upsert_book(book)
|
||||
except Exception:
|
||||
pass
|
||||
if offer_key or any(k in patch for k in ("product_id", "price_fen", "unlock_percent")):
|
||||
try:
|
||||
from ebook_svc.services.books_live import bump_books_offer_live
|
||||
|
||||
bump_books_offer_live(book_id)
|
||||
except Exception:
|
||||
pass
|
||||
offer = match_offer(book)
|
||||
return {
|
||||
**book,
|
||||
@ -190,6 +197,12 @@ async def admin_apply_offer(
|
||||
await pb.upsert_book(updated)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
from ebook_svc.services.books_live import bump_books_offer_live
|
||||
|
||||
bump_books_offer_live(book_id)
|
||||
except Exception:
|
||||
pass
|
||||
offer = match_offer(updated)
|
||||
return {
|
||||
**updated,
|
||||
|
||||
50
apps/api/services/ebook_svc/services/books_live.py
Normal file
50
apps/api/services/ebook_svc/services/books_live.py
Normal file
@ -0,0 +1,50 @@
|
||||
"""小册付费方案变更 → 轻触 remote-config,走现有 WS/SSE/1s 轮询热推。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from ebook_svc.services.tt_platform_config import resolve_config_file
|
||||
|
||||
|
||||
def bump_books_offer_live(book_id: str) -> dict[str, Any]:
|
||||
"""后台切换小册道具后调用:copy.booksOfferRev++ 并 notify。"""
|
||||
path = resolve_config_file()
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
raw: dict[str, Any] = {}
|
||||
if path.is_file():
|
||||
try:
|
||||
parsed = json.loads(path.read_text(encoding="utf-8"))
|
||||
if isinstance(parsed, dict):
|
||||
raw = parsed
|
||||
except Exception:
|
||||
raw = {}
|
||||
|
||||
out = dict(raw) if raw else {"version": 1, "modules": {}, "flags": {}, "copy": {}}
|
||||
copy = dict(out.get("copy") or {})
|
||||
try:
|
||||
rev = int(copy.get("booksOfferRev") or 0) + 1
|
||||
except Exception:
|
||||
rev = 1
|
||||
copy["booksOfferRev"] = rev
|
||||
copy["booksOfferBookId"] = str(book_id or "").strip()
|
||||
out["copy"] = copy
|
||||
out["updatedAt"] = datetime.now(timezone.utc).isoformat()
|
||||
try:
|
||||
out["version"] = int(out.get("version") or 1) + 1
|
||||
except Exception:
|
||||
out["version"] = 2
|
||||
|
||||
path.write_text(json.dumps(out, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
try:
|
||||
from ebook_svc.services.config_live import notify_config_written
|
||||
|
||||
notify_config_written(out)
|
||||
except Exception:
|
||||
pass
|
||||
return {
|
||||
"booksOfferRev": rev,
|
||||
"booksOfferBookId": copy["booksOfferBookId"],
|
||||
"version": out["version"],
|
||||
}
|
||||
@ -169,6 +169,13 @@ async def admin_update_book(book_id: str, body: BookPatch, _: str = Depends(requ
|
||||
await pb.upsert_book(book)
|
||||
except Exception:
|
||||
pass
|
||||
if offer_key or any(k in patch for k in ("product_id", "price_fen", "unlock_percent")):
|
||||
try:
|
||||
from app.services.books_live import bump_books_offer_live
|
||||
|
||||
bump_books_offer_live(book_id)
|
||||
except Exception:
|
||||
pass
|
||||
offer = match_offer(book)
|
||||
return {
|
||||
**book,
|
||||
@ -195,6 +202,12 @@ async def admin_apply_offer(
|
||||
await pb.upsert_book(updated)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
from app.services.books_live import bump_books_offer_live
|
||||
|
||||
bump_books_offer_live(book_id)
|
||||
except Exception:
|
||||
pass
|
||||
offer = match_offer(updated)
|
||||
return {
|
||||
**updated,
|
||||
|
||||
50
apps/hackrobot/nomadmini/backend/app/services/books_live.py
Normal file
50
apps/hackrobot/nomadmini/backend/app/services/books_live.py
Normal file
@ -0,0 +1,50 @@
|
||||
"""小册付费方案变更 → 轻触 remote-config,走现有 WS/SSE/1s 轮询热推。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from app.services.tt_platform_config import resolve_config_file
|
||||
|
||||
|
||||
def bump_books_offer_live(book_id: str) -> dict[str, Any]:
|
||||
"""后台切换小册道具后调用:copy.booksOfferRev++ 并 notify。"""
|
||||
path = resolve_config_file()
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
raw: dict[str, Any] = {}
|
||||
if path.is_file():
|
||||
try:
|
||||
parsed = json.loads(path.read_text(encoding="utf-8"))
|
||||
if isinstance(parsed, dict):
|
||||
raw = parsed
|
||||
except Exception:
|
||||
raw = {}
|
||||
|
||||
out = dict(raw) if raw else {"version": 1, "modules": {}, "flags": {}, "copy": {}}
|
||||
copy = dict(out.get("copy") or {})
|
||||
try:
|
||||
rev = int(copy.get("booksOfferRev") or 0) + 1
|
||||
except Exception:
|
||||
rev = 1
|
||||
copy["booksOfferRev"] = rev
|
||||
copy["booksOfferBookId"] = str(book_id or "").strip()
|
||||
out["copy"] = copy
|
||||
out["updatedAt"] = datetime.now(timezone.utc).isoformat()
|
||||
try:
|
||||
out["version"] = int(out.get("version") or 1) + 1
|
||||
except Exception:
|
||||
out["version"] = 2
|
||||
|
||||
path.write_text(json.dumps(out, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
try:
|
||||
from app.services.config_live import notify_config_written
|
||||
|
||||
notify_config_written(out)
|
||||
except Exception:
|
||||
pass
|
||||
return {
|
||||
"booksOfferRev": rev,
|
||||
"booksOfferBookId": copy["booksOfferBookId"],
|
||||
"version": out["version"],
|
||||
}
|
||||
@ -81,6 +81,10 @@ export type NomadroRemoteConfig = {
|
||||
vipPriceFen: number
|
||||
vipProductId: string
|
||||
vipCta: string
|
||||
vipOfferKey?: string
|
||||
/** 后台改小册付费方案时递增,驱动封面/阅读页热刷新 */
|
||||
booksOfferRev?: number
|
||||
booksOfferBookId?: string
|
||||
wechatOaName?: string
|
||||
joinGroupDouyinHint?: string
|
||||
joinGroupDouyinQr?: string
|
||||
@ -182,9 +186,9 @@ export const DEFAULT_REMOTE_CONFIG: NomadroRemoteConfig = {
|
||||
version: 1,
|
||||
updatedAt: '2026-03-28T00:00:00.000Z',
|
||||
modules: {
|
||||
// 离线种子默认全关入口(除首页/小册);线上以服务端覆盖。避免审核看到闪一下的入口。
|
||||
// 离线种子:首页 + 出海导航 + 数字游民小册默认开;其余入口默认关,线上可覆盖。
|
||||
home: { enabled: true, title: '首页', tabLabel: '首页' },
|
||||
nav: { enabled: false, title: '出海导航', tabLabel: '导航', note: 'navContent 远程可改' },
|
||||
nav: { enabled: true, title: '出海导航', tabLabel: '导航', note: 'navContent 远程可改' },
|
||||
book: { enabled: true, title: '数字游民小册', tabLabel: '小册' },
|
||||
community: { enabled: false, title: '旅居社群', tabLabel: '社群' },
|
||||
destinations: { enabled: false, title: '目的地' },
|
||||
|
||||
@ -129,11 +129,25 @@ function BookPageInner() {
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
let lastOfferRev = -1
|
||||
return subscribeRemoteConfig((r) => {
|
||||
applyAudit(resolveBookAudit(r.config))
|
||||
const rev = Number(r.config.copy?.booksOfferRev || 0)
|
||||
if (rev !== lastOfferRev) {
|
||||
lastOfferRev = rev
|
||||
void loadBook(true)
|
||||
}
|
||||
})
|
||||
}, [])
|
||||
|
||||
// 后台随时改小册方案:封面价/免费态约 2s 跟随
|
||||
useEffect(() => {
|
||||
const timer = setInterval(() => {
|
||||
void loadBook(true)
|
||||
}, 2000)
|
||||
return () => clearInterval(timer)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
applyH5Theme(theme)
|
||||
}, [theme])
|
||||
|
||||
@ -106,10 +106,19 @@ function ReaderPage() {
|
||||
if (!loadedRef.current) load()
|
||||
}, [bookId])
|
||||
|
||||
// 提审开关热切换:redirect,避免 navigate 叠栈导致一直「加载中」
|
||||
// 提审开关热切换 + 后台改付费方案 → 静默刷新价格/按钮
|
||||
useEffect(() => {
|
||||
let switching = false
|
||||
let lastOfferRev = -1
|
||||
return subscribeRemoteConfig((r) => {
|
||||
const rev = Number(r.config.copy?.booksOfferRev || 0)
|
||||
if (rev !== lastOfferRev) {
|
||||
lastOfferRev = rev
|
||||
const bumpedId = String(r.config.copy?.booksOfferBookId || '')
|
||||
if (!bumpedId || bumpedId === bookId) {
|
||||
void load(true)
|
||||
}
|
||||
}
|
||||
if (switching) return
|
||||
const audit = resolveBookAudit(r.config)
|
||||
const auditId = audit.bookId || 'audit'
|
||||
@ -195,12 +204,14 @@ function ReaderPage() {
|
||||
}
|
||||
|
||||
useDidShow(() => {
|
||||
void load(true)
|
||||
syncAccess()
|
||||
})
|
||||
|
||||
// 后台随时改价/道具:2s 轮询 access 指纹(含 product_id / price_fen / offer_key)
|
||||
useEffect(() => {
|
||||
if (isH5) return
|
||||
const timer = setInterval(() => syncAccess(), 8000)
|
||||
const timer = setInterval(() => syncAccess(), 2000)
|
||||
return () => clearInterval(timer)
|
||||
}, [bookId])
|
||||
|
||||
@ -542,6 +553,8 @@ function ReaderPage() {
|
||||
|
||||
async function handleUnlock() {
|
||||
if (paying) return
|
||||
// 支付前强制拉最新方案(后台随时改价/道具)
|
||||
await load(true)
|
||||
setPaying(true)
|
||||
track('unlock_click', {
|
||||
page: 'pages/reader/index',
|
||||
|
||||
@ -233,7 +233,12 @@ function VipLanding() {
|
||||
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 ctaBase = cfg.copy.vipCta || (isFreeVip ? '免费加入' : '立即加入')
|
||||
// 价格跟远程配置走:后台改档后 CTA 立刻显示新价
|
||||
const cta =
|
||||
isFreeVip || priceFen <= 0
|
||||
? ctaBase
|
||||
: `${ctaBase.replace(/\s*[·•]\s*¥\d+.*$/, '')} · ¥${Math.round(priceFen / 100)}`
|
||||
const brand = cfg.copy.homeBrand || 'nomadro'
|
||||
const vipContent = useMemo(() => resolveWeappVipContent(cfg as never), [cfg])
|
||||
const ebooksDisplay = useMemo(
|
||||
|
||||
@ -35,11 +35,21 @@ let stoppedFlag = false
|
||||
|
||||
function configFingerprint(cfg: NomadroRemoteConfig): string {
|
||||
try {
|
||||
// 必须含 copy:VIP 价/道具/CTA、小册 live bump,否则后台改档 UI 不刷新
|
||||
return JSON.stringify({
|
||||
v: cfg.version,
|
||||
at: cfg.updatedAt,
|
||||
modules: cfg.modules,
|
||||
flags: cfg.flags,
|
||||
copy: {
|
||||
vipPriceFen: cfg.copy?.vipPriceFen,
|
||||
vipProductId: cfg.copy?.vipProductId,
|
||||
vipCta: cfg.copy?.vipCta,
|
||||
vipOfferKey: cfg.copy?.vipOfferKey,
|
||||
booksOfferRev: (cfg.copy as { booksOfferRev?: number } | undefined)?.booksOfferRev,
|
||||
booksOfferBookId: (cfg.copy as { booksOfferBookId?: string } | undefined)
|
||||
?.booksOfferBookId,
|
||||
},
|
||||
bookAudit: cfg.platforms?.weapp?.bookAudit,
|
||||
})
|
||||
} catch {
|
||||
|
||||
Loading…
Reference in New Issue
Block a user