nomadro/apps/api/services/ebook_svc/services/vip_config.py
Eric 9b7ffb24dc Ship social-first admin console, soft trials, and safer join gates.
Rebuild admin.nomadro.com around community ops, add configurable free peeks instead of nav locks, humanize user copy, and harden UGC/liveness admin APIs with backup/self-test scripts.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-04 23:47:04 +08:00

266 lines
9.6 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
from ebook_svc.services.vip_content import (
apply_vip_content_patch,
read_vip_content_from_raw,
)
JoinAction = Literal["popup", "vip"]
DEFAULT_VIP = {
"vipEnabled": False,
"gameEnabled": False,
# VIP 跳转默认关 → 加群仍弹窗(现网);后台可开 vip
"joinGroupAction": "popup",
"vipPriceFen": 8800,
"vipProductId": "tiktok",
# CTA 不含价格;价格由方案卡片/后台展示
"vipCta": "立即加入",
"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 = 0) -> str:
"""小程序主按钮文案:不含价格。免费=临时放行,切回收费后仍须付费开通。"""
if free or price_fen <= 0:
return "免费加入"
return "立即加入"
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()
# 旧配置可能带「· ¥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)
return {
"vipEnabled": bool(vip_enabled),
"gameEnabled": bool(game_enabled),
"joinGroupAction": _as_action(flags.get("joinGroupAction"), "popup"),
# Web ↔ 小程序账号打通(默认关;开启不改既有订单/会员行)
"vipWebBridgeEnabled": flags.get("vipWebBridgeEnabled") is True,
"vipPriceFen": price,
"vipProductId": product_id,
"vipCta": cta,
"vipOfferKey": str(offer.get("key") or offer_key or ""),
"is_free": is_free,
# 落地页运营位:缺省=现网 UI;不自动写盘
"vipContent": read_vip_content_from_raw(raw),
"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": "数字游民", "note": "冻结隐藏 · 勿开入口"})
game["enabled"] = False
game["title"] = "数字游民"
game["note"] = "冻结隐藏 · 勿开入口"
modules["game"] = game
if "joinGroupAction" in patch:
flags["joinGroupAction"] = _as_action(patch["joinGroupAction"], "popup")
if "vipWebBridgeEnabled" in patch and isinstance(patch["vipWebBridgeEnabled"], bool):
flags["vipWebBridgeEnabled"] = bool(patch["vipWebBridgeEnabled"])
# 主按钮文案统一不含价格;免费=临时放行文案
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
# 仅当运营显式提交 vipContent 时写入 platforms.weapp(不碰 platforms.tt)
if "vipContent" in patch and isinstance(patch.get("vipContent"), dict):
out = apply_vip_content_patch(out, patch["vipContent"])
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")
try:
from ebook_svc.services.config_live import notify_config_written
notify_config_written(out)
except Exception:
pass
return read_vip_config()