nomadro/apps/api/services/ebook_svc/services/vip_config.py
eric 98a54730ff Port nomadvip VIP into native WeChat pages and document the flow.
Add vip-course/lesson/ebook with source markdown seeds, VIP order API + admin offers, ban web-view for content, and update READMEs for weapp rebuild/extract scripts.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-04 22:30:27 +08:00

228 lines
8.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""微信 VIP / 加群行为 / 3D 入口 — 读写 remote-config,不碰订单与抖音 platforms.tt。
VIP「立即加入」付费方案复用小册 PRODUCT_OFFERS(免费 / 已发布道具)。
"""
from __future__ import annotations
import json
from datetime import datetime, timezone
from typing import Any, Literal
from ebook_svc.domains.books.products import PRODUCT_OFFERS, _LEGACY_PRODUCT_IDS
from ebook_svc.services.tt_platform_config import resolve_config_file
JoinAction = Literal["popup", "vip"]
DEFAULT_VIP = {
"vipEnabled": False,
"gameEnabled": False,
# VIP 跳转默认关 → 加群仍弹窗(现网);后台可开 vip
"joinGroupAction": "popup",
"vipPriceFen": 29800,
"vipProductId": "tiktok",
"vipCta": "立即加入 · ¥298",
"vipOfferKey": "tiktok",
}
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 _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)。"""
if free or price_fen <= 0:
return "免费加入"
yuan = price_fen / 100
if yuan == int(yuan):
return f"立即加入 · ¥{int(yuan)}"
return f"立即加入 · ¥{yuan:.2f}"
def match_vip_offer(
*,
offer_key: str = "",
product_id: str = "",
price_fen: int = 0,
) -> dict[str, Any]:
key = (offer_key or "").strip()
if key:
key = _LEGACY_PRODUCT_IDS.get(key, key)
for o in PRODUCT_OFFERS:
if o["key"] == key or o["product_id"] == key:
return o
pid = (product_id or "").strip()
mapped = _LEGACY_PRODUCT_IDS.get(pid, pid)
if not pid and price_fen <= 0:
return PRODUCT_OFFERS[0] # free
for o in PRODUCT_OFFERS:
if o["free"]:
continue
if o["product_id"] == pid or o["key"] == mapped or o["product_id"] == mapped:
return o
# 旧默认 vip_membership → 视为自定义
return {
"key": "custom",
"label": pid or "自定义",
"name": pid or "自定义",
"product_id": pid,
"price_fen": int(price_fen),
"free": price_fen <= 0 and not pid,
"image": "",
"remark": "未在目录中的自定义道具",
}
def apply_vip_offer_key(key: str) -> dict[str, Any]:
"""一键应用免费 / 已发布道具 → vipPriceFen / vipProductId / vipCta / vipOfferKey。"""
key = _LEGACY_PRODUCT_IDS.get((key or "").strip(), (key or "").strip())
offer = next(
(
o
for o in PRODUCT_OFFERS
if o["key"] == key or o["product_id"] == key or o["name"] == key
),
None,
)
if not offer:
raise ValueError(f"未知方案: {key}")
free = bool(offer["free"])
price = 0 if free else int(offer["price_fen"])
pid = "" if free else str(offer["product_id"])
return {
"vipOfferKey": str(offer["key"]),
"vipPriceFen": price,
"vipProductId": pid,
"vipCta": vip_cta_text(free=free, price_fen=price),
"is_free": free,
}
def read_vip_config() -> dict[str, Any]:
raw = _read_raw()
modules = raw.get("modules") if isinstance(raw.get("modules"), dict) else {}
flags = raw.get("flags") if isinstance(raw.get("flags"), dict) else {}
copy = raw.get("copy") if isinstance(raw.get("copy"), dict) else {}
vip_mod = modules.get("vip") if isinstance(modules.get("vip"), dict) else {}
game_mod = modules.get("game") if isinstance(modules.get("game"), dict) else {}
vip_enabled = vip_mod.get("enabled")
if not isinstance(vip_enabled, bool):
vip_enabled = DEFAULT_VIP["vipEnabled"]
game_enabled = game_mod.get("enabled")
if not isinstance(game_enabled, bool):
game_enabled = DEFAULT_VIP["gameEnabled"]
try:
price = int(copy.get("vipPriceFen", DEFAULT_VIP["vipPriceFen"]))
except Exception:
price = int(DEFAULT_VIP["vipPriceFen"])
product_id = str(copy.get("vipProductId") if "vipProductId" in copy else DEFAULT_VIP["vipProductId"])
offer_key = str(copy.get("vipOfferKey") or "")
offer = match_vip_offer(offer_key=offer_key, product_id=product_id, price_fen=price)
is_free = bool(offer.get("free")) or (price <= 0 and not product_id.strip())
cta = str(copy.get("vipCta") or "").strip()
if not cta:
cta = vip_cta_text(free=is_free, price_fen=price)
return {
"vipEnabled": bool(vip_enabled),
"gameEnabled": bool(game_enabled),
"joinGroupAction": _as_action(flags.get("joinGroupAction"), "popup"),
"vipPriceFen": price,
"vipProductId": product_id,
"vipCta": cta,
"vipOfferKey": str(offer.get("key") or offer_key or ""),
"is_free": is_free,
"updatedAt": raw.get("updatedAt"),
"version": raw.get("version"),
"configPath": str(resolve_config_file()),
}
def write_vip_config(patch: dict[str, Any]) -> dict[str, Any]:
path = resolve_config_file()
path.parent.mkdir(parents=True, exist_ok=True)
existing = _read_raw()
out: dict[str, Any] = (
dict(existing) if existing else {"version": 2, "modules": {}, "flags": {}, "copy": {}}
)
modules = dict(out.get("modules") or {})
flags = dict(out.get("flags") or {})
copy = dict(out.get("copy") or {})
# 一键方案优先:写出价格 / 道具 / CTA / offerKey
if "vipOfferKey" in patch and patch["vipOfferKey"] is not None:
applied = apply_vip_offer_key(str(patch["vipOfferKey"]))
copy["vipOfferKey"] = applied["vipOfferKey"]
copy["vipPriceFen"] = applied["vipPriceFen"]
copy["vipProductId"] = applied["vipProductId"]
copy["vipCta"] = applied["vipCta"]
else:
if "vipPriceFen" in patch and patch["vipPriceFen"] is not None:
try:
copy["vipPriceFen"] = max(0, int(patch["vipPriceFen"]))
except Exception:
pass
if "vipProductId" in patch and patch["vipProductId"] is not None:
# 允许空串 = 免费方案
copy["vipProductId"] = str(patch["vipProductId"]).strip()
if "vipCta" in patch and patch["vipCta"] is not None:
copy["vipCta"] = str(patch["vipCta"]).strip() or DEFAULT_VIP["vipCta"]
if "vipOfferKey" in patch and patch["vipOfferKey"] is not None:
copy["vipOfferKey"] = str(patch["vipOfferKey"]).strip()
if "vipEnabled" in patch and isinstance(patch["vipEnabled"], bool):
vip = dict(modules.get("vip") or {"title": "会员中心", "note": "deep link only"})
vip["enabled"] = patch["vipEnabled"]
vip.setdefault("title", "会员中心")
modules["vip"] = vip
if "gameEnabled" in patch and isinstance(patch["gameEnabled"], bool):
game = dict(modules.get("game") or {"title": "Nomad Day 3D", "note": "WebGL 数字游民一日"})
game["enabled"] = patch["gameEnabled"]
game.setdefault("title", "Nomad Day 3D")
modules["game"] = game
if "joinGroupAction" in patch:
flags["joinGroupAction"] = _as_action(patch["joinGroupAction"], "popup")
out["modules"] = modules
out["flags"] = flags
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
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")
return read_vip_config()