nomadro/apps/ebook/wemini/backend/app/routers/admin.py
eric d93a355fd5 Migrate navmini/ebook/nomadweb into apps/ as same-origin portal subpaths.
Shield external portal jumps (keep EXTERNAL_* for later), serve /nav from static build, and proxy /book + /community to vertical Next apps with Caddy notes.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 03:30:34 -05:00

342 lines
12 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.

from __future__ import annotations
import re
import secrets
from fastapi import APIRouter, Depends, HTTPException
from app.config import settings
from app.core.security import create_admin_token, require_admin
from app.domains.books import apply_offer_key, is_book_free, match_offer, offer_public_list
from app.schemas.admin import (
AdminLoginBody,
BookPatch,
ManualUnlockBody,
MarkdownImportBody,
OfferApplyBody,
RevokeUnlockBody,
UserPatchBody,
)
from app.services.pocketbase import pb
from app.services.store import store
router = APIRouter(prefix="/api/admin", tags=["admin"])
@router.post("/login")
async def admin_login(body: AdminLoginBody):
if body.username != settings.admin_username or body.password != settings.admin_password:
raise HTTPException(401, "用户名或密码错误")
return {"token": create_admin_token(body.username), "username": body.username}
@router.get("/stats")
async def admin_stats(_: str = Depends(require_admin)):
return store.stats()
@router.get("/track-events")
async def admin_track_events(
limit: int = 100,
name: str = "",
_: str = Depends(require_admin),
):
lim = max(1, min(limit, 500))
return store.list_track_events(limit=lim, name=name)
@router.get("/product-offers")
async def admin_product_offers(_: str = Depends(require_admin)):
"""免费 + 4 个道具方案目录。"""
return {"items": offer_public_list()}
@router.get("/books")
async def admin_books(_: str = Depends(require_admin)):
return store.list_books()
@router.get("/books/{book_id}")
async def admin_book(book_id: str, _: str = Depends(require_admin)):
book = store.get_book(book_id)
if not book:
raise HTTPException(404, "不存在")
offer = match_offer(book)
return {**book, "offer_key": offer["key"], "is_free": is_book_free(book)}
@router.put("/books/{book_id}")
async def admin_update_book(book_id: str, body: BookPatch, _: str = Depends(require_admin)):
patch = body.model_dump(exclude_none=True)
offer_key = patch.pop("offer_key", None)
try:
if offer_key:
book = store.get_book(book_id)
if not book:
raise ValueError("book not found")
keep = book.get("unlock_percent")
patch.update(apply_offer_key(offer_key, keep))
book = store.update_book(book_id, patch)
except ValueError as e:
raise HTTPException(404 if "not found" in str(e) else 400, str(e)) from e
try:
await pb.upsert_book(book)
except Exception:
pass
offer = match_offer(book)
return {**book, "offer_key": offer["key"], "is_free": is_book_free(book)}
@router.post("/books/{book_id}/offer")
async def admin_apply_offer(
book_id: str, body: OfferApplyBody, _: str = Depends(require_admin)
):
book = store.get_book(book_id)
if not book:
raise HTTPException(404, "不存在")
try:
keep = book.get("unlock_percent") if body.keep_preview_percent else None
patch = apply_offer_key(body.offer_key, keep)
updated = store.update_book(book_id, patch)
except ValueError as e:
raise HTTPException(400, str(e)) from e
try:
await pb.upsert_book(updated)
except Exception:
pass
offer = match_offer(updated)
return {**updated, "offer_key": offer["key"], "is_free": is_book_free(updated)}
@router.get("/books/{book_id}/markdown")
async def admin_export_markdown(book_id: str, _: str = Depends(require_admin)):
book = store.get_book(book_id)
if not book:
raise HTTPException(404, "不存在")
from app.services.markdown_book import join_markdown_chapters
md = join_markdown_chapters(book.get("chapters") or [])
return {
"book_id": book_id,
"markdown": md,
"chapter_count": book.get("chapter_count"),
"word_count": book.get("word_count"),
}
@router.post("/books/{book_id}/import-markdown")
async def admin_import_markdown(
book_id: str, body: MarkdownImportBody, _: str = Depends(require_admin)
):
book = store.get_book(book_id)
if not book:
raise HTTPException(404, "不存在")
from app.services.markdown_book import sanitize_local_images, split_markdown_chapters
md = sanitize_local_images(body.markdown or "")
chapters = split_markdown_chapters(md)
if not chapters:
raise HTTPException(400, "Markdown 为空或无法解析章节")
patch: dict = {"chapters": chapters}
if body.replace_meta:
if body.title:
patch["title"] = body.title
if body.subtitle:
patch["subtitle"] = body.subtitle
if body.description:
patch["description"] = body.description
elif chapters:
raw = re.sub(r"[#>*`\[\]]+", "", chapters[0]["content"])
patch["description"] = re.sub(r"\s+", " ", raw).strip()[:120]
updated = store.update_book(book_id, patch)
try:
await pb.upsert_book(updated)
except Exception:
pass
return {
"ok": True,
"chapter_count": updated["chapter_count"],
"word_count": updated["word_count"],
"book": updated,
}
@router.get("/orders")
async def admin_orders(_: str = Depends(require_admin)):
return store.list_orders()
@router.post("/unlock")
async def admin_manual_unlock(body: ManualUnlockBody, _: str = Depends(require_admin)):
"""后台手动发货:用于道具未发布前联调,或客服补发。"""
book = store.get_book(body.book_id)
if not book:
raise HTTPException(404, "书籍不存在")
if not body.openid.strip():
raise HTTPException(400, "openid 不能为空")
openid = body.openid.strip()
if not store.get_user(openid):
# 允许客服先录入 openid 再解锁:创建占位用户
store.upsert_user(openid, "", secrets.token_urlsafe(12), None)
store.grant_unlock(openid, body.book_id, source="manual")
user = store.get_user(openid)
try:
if user:
rid = await pb.upsert_wx_reader(user)
if rid and rid != user.get("pb_record_id"):
store.set_user_pb_id(openid, rid)
except Exception:
pass
return {"ok": True, "openid": openid, "book_id": body.book_id, "unlocked": True}
@router.post("/revoke-unlock")
async def admin_revoke_unlock(body: RevokeUnlockBody, _: str = Depends(require_admin)):
if not body.openid.strip():
raise HTTPException(400, "openid 不能为空")
ok = store.revoke_unlock(body.openid.strip(), body.book_id)
return {"ok": ok, "openid": body.openid.strip(), "book_id": body.book_id}
@router.get("/users")
async def admin_users(q: str = "", _: str = Depends(require_admin)):
return store.list_users(limit=200, q=q)
@router.get("/users/{openid}")
async def admin_user_detail(openid: str, _: str = Depends(require_admin)):
user = store.get_user(openid)
if not user:
raise HTTPException(404, "用户不存在")
rows = store.list_users(limit=1, q=openid)
return rows[0] if rows else user
@router.patch("/users/{openid}")
async def admin_patch_user(openid: str, body: UserPatchBody, _: str = Depends(require_admin)):
try:
user = store.update_user_admin(
openid,
status=body.status,
notes=body.notes,
nickname=body.nickname,
)
except ValueError as e:
raise HTTPException(400, str(e)) from e
if not user:
raise HTTPException(404, "用户不存在")
try:
rid = await pb.upsert_wx_reader(user)
if rid and rid != user.get("pb_record_id"):
store.set_user_pb_id(openid, rid)
user = store.get_user(openid) or user
except Exception:
pass
rows = store.list_users(limit=1, q=openid)
return rows[0] if rows else user
@router.post("/users/{openid}/block")
async def admin_block_user(openid: str, _: str = Depends(require_admin)):
user = store.update_user_admin(openid, status="blocked")
if not user:
raise HTTPException(404, "用户不存在")
try:
await pb.upsert_wx_reader(user)
except Exception:
pass
return {"ok": True, "openid": openid, "status": "blocked"}
@router.post("/users/{openid}/unblock")
async def admin_unblock_user(openid: str, _: str = Depends(require_admin)):
user = store.update_user_admin(openid, status="active")
if not user:
raise HTTPException(404, "用户不存在")
try:
await pb.upsert_wx_reader(user)
except Exception:
pass
return {"ok": True, "openid": openid, "status": "active"}
@router.get("/checklist")
async def checklist(_: str = Depends(require_admin)):
"""部署前检查清单状态。"""
book = store.get_book("default")
product_id = book["product_id"] if book else "-"
price_fen = book["price_fen"] if book else 0
free = is_book_free(book)
paid_offers = [o for o in offer_public_list() if not o["free"]]
return {
"items": [
{"id": "condition", "title": "开放条件:个人主体 + 工具类目 + 认证备案", "status": "manual"},
{"id": "limit", "title": "已了解月支付限额 10 万元", "status": "manual"},
{"id": "opened", "title": "MP 后台虚拟支付已开通", "status": "manual"},
{
"id": "creds",
"title": "已配置 AppID / OfferID / 现网 AppKey",
"status": "ok"
if settings.wx_appid and settings.wx_offer_id and settings.wx_app_key
else "missing",
},
{"id": "ios_name", "title": "iOS 支付:已配置小程序简称(如需)", "status": "manual"},
{
"id": "notify",
"title": f"发货推送 URL:{settings.public_api_base}/api/pay/notify",
"status": "manual",
},
{"id": "sign", "title": "服务器验签逻辑已实现(paySig + signature)", "status": "ok"},
{"id": "idempotent", "title": "发货幂等(wx_order_id / delivered)", "status": "ok"},
{"id": "frontend_pay", "title": "前端 requestVirtualPayment 已接入", "status": "ok"},
{"id": "query", "title": "兜底查单 query_order 已就绪", "status": "ok"},
{"id": "fee", "title": "费率:Android 1% / iOS 12%;结算 T+3 / 约45-60天", "status": "manual"},
{"id": "live_test", "title": "上线后小额真单验证支付→推送→发货→账单", "status": "manual"},
{
"id": "product",
"title": (
"当前免费全书(unlock=100%)"
if free
else (
f"当前道具 productId={product_id},"
f"价格={price_fen}分(¥{price_fen/100:.2f});"
f"需发布:{', '.join(o['product_id'] for o in paid_offers)}"
)
),
"status": "manual",
},
{
"id": "unlock",
"title": (
"免费模式:unlock_percent=100%"
if free
else f"付费试读比例:{book['unlock_percent'] if book else '-'}%(100%=免费开关)"
),
"status": "ok",
},
{
"id": "wx_readers",
"title": "读者以 openid 存 SQLite,可选同步 PocketBase 集合 wx_readers",
"status": "ok",
},
],
"product_guide": {
"product_id": product_id,
"price_fen": price_fen,
"offers": paid_offers,
"steps": [
"登录 mp.weixin.qq.com",
"支付与交易 → 虚拟支付 → 道具管理",
*[
f"发布道具 ID={o['product_id']},价格={o['price_fen']}分({o['price_yuan']})"
for o in paid_offers
],
"提交并发布;等待约 10 分钟后再测支付",
f"消息推送 URL 配置为:{settings.public_api_base}/api/pay/notify",
"后台「内容编辑台」可在 免费 / 道具 间一键切换;读者页可手动解锁/拉黑",
],
},
}