from __future__ import annotations import re import secrets from fastapi import APIRouter, Depends, HTTPException from ebook_svc.config import settings from ebook_svc.core.security import create_admin_token, require_admin from ebook_svc.domains.books import ( apply_offer_key, is_audit_book_id, is_book_free, match_offer, offer_public_list, ) from ebook_svc.schemas.admin import ( AdminLoginBody, BookCreateBody, BookPatch, ManualUnlockBody, MarkdownImportBody, OfferApplyBody, OrderStatusBody, RevokeUnlockBody, UserPatchBody, ) from ebook_svc.services.pocketbase import pb from ebook_svc.services.store import store router = APIRouter(prefix="/api/admin", tags=["admin"]) VIP_BOOK_ID = "__vip__" @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 = "", client: str = "", _: str = Depends(require_admin), ): lim = max(1, min(limit, 500)) return store.list_track_events(limit=lim, name=name, client=client) @router.get("/track-analytics") async def admin_track_analytics( days: int = 14, client: str = "", _: str = Depends(require_admin), ): """用户分析:独立访客(Fingerprint visitorId / openid)、DAU、漏斗、端与页面排行。""" return store.track_analytics(days=days, client=client) @router.get("/track-visitor") async def admin_track_visitor( visitorId: str = "", openid: str = "", days: int = 14, limit: int = 200, client: str = "", _: str = Depends(require_admin), ): """单个访客访问明细时间线。""" data = store.list_visitor_timeline( visitor_id=visitorId, openid=openid, days=days, limit=limit, client=client, ) if not data.get("ok"): raise HTTPException(400, str(data.get("error") or "参数错误")) return data @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.post("/books") async def admin_create_book(body: BookCreateBody, _: str = Depends(require_admin)): data = body.model_dump(exclude_none=True) bid = str(data.pop("id", "") or "").strip() if not bid: raise HTTPException(400, "需要 id") try: book = store.create_book(bid, data) except ValueError as e: raise HTTPException(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.delete("/books/{book_id}") async def admin_delete_book(book_id: str, _: str = Depends(require_admin)): if book_id in {"default", "__vip__"}: raise HTTPException(400, "系统书不可删除") ok = store.delete_book(book_id) if not ok: raise HTTPException(404, "不存在") return {"ok": True} _BOOK_SHELL_TITLES = { "audit": ("数字游民·提审版", "微信提审专用 · 与正式会员书无关"), "nomad": ("数字游民", "VIP 电子书 · 本册独立试读/付费"), "cloudphone": ("云手机", "VIP 电子书 · 本册独立试读/付费"), "default": ("Youtube运营笔记", "专属小册 · 本册独立试读/付费"), } @router.get("/books/{book_id}") async def admin_book(book_id: str, _: str = Depends(require_admin)): book = store.get_book(book_id) # 审核备用书 / VIP 电子书付费壳:首次打开自动建壳(每本独立,互不影响) if not book: try: title, subtitle = _BOOK_SHELL_TITLES.get( book_id, (book_id, "本册独立试读/付费壳") ) book = store.ensure_book( book_id, title=title, subtitle=subtitle, free=True, ) except Exception: book = None if not book: raise HTTPException(404, "不存在") offer = match_offer(book) return { **book, "offer_key": offer["key"], "offer_name": offer.get("name") or offer.get("label"), "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) # 提审书永远免费,禁止改成付费方案以免与正式书数据串台 if is_audit_book_id(book_id): if offer_key and offer_key != "free": raise HTTPException(400, "提审书默认免费,不可配置付费方案") patch["unlock_percent"] = 100 patch["price_fen"] = 0 patch["product_id"] = "" offer_key = "free" 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 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, free=is_book_free(book)) except Exception: pass offer = match_offer(book) return { **book, "offer_key": offer["key"], "offer_name": offer.get("name") or offer.get("label"), "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, "不存在") if is_audit_book_id(book_id) and body.offer_key != "free": raise HTTPException(400, "提审书默认免费,不可配置付费方案") try: keep = book.get("unlock_percent") if body.keep_preview_percent else None patch = apply_offer_key(body.offer_key, keep) if is_audit_book_id(book_id): patch = apply_offer_key("free", None) 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 try: from ebook_svc.services.books_live import bump_books_offer_live bump_books_offer_live(book_id, free=is_book_free(updated)) except Exception: pass offer = match_offer(updated) return { **updated, "offer_key": offer["key"], "offer_name": offer.get("name") or offer.get("label"), "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 ebook_svc.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 ebook_svc.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("/orders/{out_trade_no}/status") async def admin_order_status( out_trade_no: str, body: OrderStatusBody, _: str = Depends(require_admin) ): try: row = store.mark_order_status(out_trade_no, body.status) except ValueError as e: raise HTTPException(400, str(e)) from e if not row: raise HTTPException(404, "订单不存在") return {"ok": True, "order": row} @router.post("/unlock") async def admin_manual_unlock(body: ManualUnlockBody, _: str = Depends(require_admin)): """后台手动发货:小册 default / VIP __vip__ / 其它 book_id。""" book_id = (body.book_id or "").strip() or "default" if is_audit_book_id(book_id): raise HTTPException(400, "提审书默认免费,无需手动解锁") if book_id != VIP_BOOK_ID: book = store.get_book(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, 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": 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 不能为空") book_id = (body.book_id or "").strip() or "default" ok = store.revoke_unlock(body.openid.strip(), book_id) return {"ok": ok, "openid": body.openid.strip(), "book_id": 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", "后台「内容编辑台」可在 免费 / 道具 间一键切换;读者页可手动解锁/拉黑", ], }, }