"""微信后台「开关」— 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