from __future__ import annotations import json import sqlite3 import time import uuid from contextlib import contextmanager from pathlib import Path from typing import Any from ebook_svc.config import settings SEED_CHAPTERS = [ { "id": "c1", "title": "序章 · 夜色书页", "order": 1, "content": """# 序章 · 夜色书页 风穿过窗缝,把台灯的光吹成一枚晃动的金币。 你摊开这本数字之书时,墨迹还带着刚写完的温度。Nomadro 不是一本急着讲完的故事,它更像一盏会呼吸的灯——照见你今天想慢下来的那几分钟。 ## 为什么从这里开始 - **阅读是一种节奏**:不是赶路,是散步。 - **试读是邀请**:走到约定的百分比,再决定要不要推开下一扇门。 - **解锁是承诺**:你愿意把完整旅程带回家。 > 💡 小提示:左侧目录可以随时跳转;顶部进度条会轻轻告诉你走了多远。 ``` 呼吸一次。 翻一页。 世界会安静一点。 ``` 夜里最适合读的句子,往往不是最华丽的,而是最诚实的。 """, }, { "id": "c2", "title": "第一章 · 绿意算法", "order": 2, "content": """# 第一章 · 绿意算法 城市里很少有真正的森林,但屏幕上可以长出一片。 Nomadro 的视觉语汇来自苔藓、晨雾和雨后的柏油路反光。我们用深绿做底,用亮叶做强调,让阅读区像一块被灯光温柔切开的林间空地。 ## 三个小原则 1. **少即是多**:一屏只做一件事。 2. **动效有意义**:浮动、呼吸、渐显都在帮你建立层次。 3. **付费要清晰**:试读边界可见,解锁理由可见。 当你滑到试读线附近,系统会像守门人一样礼貌地拦一句:继续的风景需要一把钥匙。 那把钥匙,就是虚拟支付开通的「道具」——一本完整的书。 """, }, { "id": "c3", "title": "第二章 · 钥匙与回声", "order": 3, "content": """# 第二章 · 钥匙与回声 支付成功不是终点,是回声的开始。 微信会把「发货推送」敲到你的服务器门上。服务器验签、幂等、记账,再把解锁状态写回读者档案。若推送在风雨里走丢,定时查单会再敲一次门。 ## 工程师札记 - `outTradeNo` 只使用一次 - 以 `wx_order_id` 做幂等 - 前端 success 回调可以丢,不能当唯一发货依据 于是整本书像被重新装订:目录亮起,锁落下来,文字不再在某个百分比戛然而止。 你听见的,是完整故事终于回到你手里的声音。 """, }, ] class Store: def __init__(self, path: str): self.path = Path(path) self.path.parent.mkdir(parents=True, exist_ok=True) self._init_db() def _migrate_users(self, c: sqlite3.Connection): cols = {r[1] for r in c.execute("PRAGMA table_info(users)").fetchall()} alters = [ ("nickname", "ALTER TABLE users ADD COLUMN nickname TEXT"), ("avatar_url", "ALTER TABLE users ADD COLUMN avatar_url TEXT"), ("status", "ALTER TABLE users ADD COLUMN status TEXT DEFAULT 'active'"), ("notes", "ALTER TABLE users ADD COLUMN notes TEXT"), ("pb_record_id", "ALTER TABLE users ADD COLUMN pb_record_id TEXT"), ("created_at", "ALTER TABLE users ADD COLUMN created_at REAL"), ("last_seen_at", "ALTER TABLE users ADD COLUMN last_seen_at REAL"), # Web VIP 桥接映射(仅新增列,不改既有行数据) ("vip_email", "ALTER TABLE users ADD COLUMN vip_email TEXT"), ("web_user_id", "ALTER TABLE users ADD COLUMN web_user_id TEXT"), ("vip_email_bound_at", "ALTER TABLE users ADD COLUMN vip_email_bound_at REAL"), ] for name, sql in alters: if name not in cols: c.execute(sql) unlock_cols = {r[1] for r in c.execute("PRAGMA table_info(unlocks)").fetchall()} if "source" not in unlock_cols: c.execute("ALTER TABLE unlocks ADD COLUMN source TEXT") c.execute( "UPDATE users SET status='active' WHERE status IS NULL OR status=''" ) c.execute( "UPDATE users SET created_at=COALESCE(created_at, updated_at, ?) WHERE created_at IS NULL", (time.time(),), ) @contextmanager def conn(self): from ebook_svc.core.sqlite_util import connect as sqlite_connect c = sqlite_connect(self.path) try: yield c c.commit() finally: c.close() def _init_db(self): with self.conn() as c: c.executescript( """ CREATE TABLE IF NOT EXISTS books ( id TEXT PRIMARY KEY, title TEXT NOT NULL, subtitle TEXT, author TEXT, cover_emoji TEXT, description TEXT, tags TEXT, price_fen INTEGER, product_id TEXT, unlock_percent INTEGER, rating REAL, chapters_json TEXT, updated_at REAL ); CREATE TABLE IF NOT EXISTS users ( openid TEXT PRIMARY KEY, session_key TEXT, unionid TEXT, token TEXT, nickname TEXT, avatar_url TEXT, status TEXT DEFAULT 'active', notes TEXT, pb_record_id TEXT, created_at REAL, updated_at REAL ); CREATE TABLE IF NOT EXISTS unlocks ( openid TEXT NOT NULL, book_id TEXT NOT NULL, unlocked_at REAL, source TEXT, PRIMARY KEY (openid, book_id) ); CREATE TABLE IF NOT EXISTS orders ( out_trade_no TEXT PRIMARY KEY, wx_order_id TEXT, openid TEXT, book_id TEXT, product_id TEXT, amount_fen INTEGER, status TEXT, delivered INTEGER DEFAULT 0, attach TEXT, raw_notify TEXT, created_at REAL, updated_at REAL ); CREATE TABLE IF NOT EXISTS track_events ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, page TEXT, label TEXT, props_json TEXT, openid TEXT, client TEXT, ts REAL, created_at REAL ); CREATE INDEX IF NOT EXISTS idx_orders_wx ON orders(wx_order_id); CREATE INDEX IF NOT EXISTS idx_orders_status ON orders(status); CREATE INDEX IF NOT EXISTS idx_track_ts ON track_events(ts DESC); CREATE INDEX IF NOT EXISTS idx_track_name ON track_events(name); CREATE INDEX IF NOT EXISTS idx_track_client ON track_events(client); """ ) self._migrate_users(c) row = c.execute("SELECT id FROM books WHERE id=?", ("default",)).fetchone() if not row: now = time.time() c.execute( """ INSERT INTO books(id,title,subtitle,author,cover_emoji,description,tags, price_fen,product_id,unlock_percent,rating,chapters_json,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?) """, ( "default", "Nomadro 夜读手记", "一本关于节奏、边界与完整旅程的数字书", "", "📗", "从一盏绿灯开始,走到试读线,再决定是否推开完整章节。适合想把阅读体验做得克制而好看的人。", json.dumps(["电子书", "设计", "支付"], ensure_ascii=False), settings.default_price_fen, settings.default_product_id, settings.default_unlock_percent, 4.8, json.dumps(SEED_CHAPTERS, ensure_ascii=False), now, ), ) # 清理历史种子作者文案,避免首页露出 c.execute( "UPDATE books SET author='' WHERE author IN (?, ?)", ("Nomadro Studio", "Nomadro studio"), ) def get_book(self, book_id: str = "default") -> dict[str, Any] | None: with self.conn() as c: row = c.execute("SELECT * FROM books WHERE id=?", (book_id,)).fetchone() if not row: return None return self._book_row(row) def list_books(self) -> list[dict[str, Any]]: with self.conn() as c: rows = c.execute("SELECT * FROM books ORDER BY updated_at DESC").fetchall() return [self._book_row(r) for r in rows] def _book_row(self, row: sqlite3.Row) -> dict[str, Any]: raw_chapters = json.loads(row["chapters_json"] or "[]") chapters: list[dict[str, Any]] = [] for i, ch in enumerate(raw_chapters if isinstance(raw_chapters, list) else []): if not isinstance(ch, dict): continue chapters.append( { **ch, "id": str(ch.get("id") or f"ch-{i + 1}"), "title": str(ch.get("title") or f"章节 {i + 1}"), "order": int(ch["order"]) if ch.get("order") is not None else i + 1, "content": str(ch.get("content") or ""), } ) tags = json.loads(row["tags"] or "[]") word_count = sum(len(ch.get("content") or "") for ch in chapters) return { "id": row["id"], "title": row["title"], "subtitle": row["subtitle"], "author": row["author"], "cover_emoji": row["cover_emoji"], "description": row["description"], "tags": tags, "price_fen": row["price_fen"], "product_id": row["product_id"], "unlock_percent": row["unlock_percent"], "rating": row["rating"], "chapters": chapters, "chapter_count": len(chapters), "word_count": word_count, "updated_at": row["updated_at"], } def ensure_book( self, book_id: str, *, title: str = "审核用小册", subtitle: str = "审核模式展示内容", free: bool = True, ) -> dict[str, Any]: """若不存在则创建(审核模式备用书);已存在则原样返回。""" bid = (book_id or "").strip()[:64] if not bid: raise ValueError("book_id required") existing = self.get_book(bid) if existing: return existing now = time.time() chapters = [ { "id": "01-audit", "title": "写在前面", "order": 1, "content": ( "# 写在前面\n\n" "欢迎阅读《数字游民入门指南》。\n\n" "这是一本面向普通人的远程办公与自律生活入门读本:" "讲时间管理、团队协作、健康作息与职业成长。\n" ), } ] with self.conn() as c: c.execute( """ INSERT INTO books(id,title,subtitle,author,cover_emoji,description,tags, price_fen,product_id,unlock_percent,rating,chapters_json,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?) """, ( bid, title, subtitle, "", "📗", "微信提审专用,与正式会员书分开存放。", json.dumps(["提审"], ensure_ascii=False), 0 if free else settings.default_price_fen, "" if free else settings.default_product_id, 100 if free else settings.default_unlock_percent, 5.0, json.dumps(chapters, ensure_ascii=False), now, ), ) return self.get_book(bid) or {"id": bid} def update_book(self, book_id: str, patch: dict[str, Any]) -> dict[str, Any]: book = self.get_book(book_id) if not book: raise ValueError("book not found") book.update({k: v for k, v in patch.items() if v is not None}) with self.conn() as c: c.execute( """ UPDATE books SET title=?, subtitle=?, author=?, cover_emoji=?, description=?, tags=?, price_fen=?, product_id=?, unlock_percent=?, rating=?, chapters_json=?, updated_at=? WHERE id=? """, ( book["title"], book["subtitle"], book["author"], book["cover_emoji"], book["description"], json.dumps(book["tags"], ensure_ascii=False), book["price_fen"], book["product_id"], book["unlock_percent"], book["rating"], json.dumps(book["chapters"], ensure_ascii=False), time.time(), book_id, ), ) return self.get_book(book_id) # type: ignore # 后台判定「在线」:最近心跳 / 鉴权请求落在此窗口内 ONLINE_WINDOW_SEC = 90 def upsert_user(self, openid: str, session_key: str, token: str, unionid: str | None = None): now = time.time() with self.conn() as c: c.execute( """ INSERT INTO users(openid, session_key, unionid, token, status, created_at, updated_at, last_seen_at) VALUES(?,?,?,?, 'active', ?, ?, ?) ON CONFLICT(openid) DO UPDATE SET session_key=excluded.session_key, unionid=COALESCE(excluded.unionid, users.unionid), token=excluded.token, updated_at=excluded.updated_at, last_seen_at=excluded.last_seen_at """, (openid, session_key, unionid, token, now, now, now), ) def touch_last_seen(self, openid: str) -> None: if not openid: return with self.conn() as c: c.execute( "UPDATE users SET last_seen_at=? WHERE openid=?", (time.time(), openid), ) # Notify admin live SSE (best-effort; ignore if bus unavailable) try: from ebook_svc.services import ops_live ops_live._fanout({"type": "presence", "openid": openid, "source": "app"}) except Exception: pass def get_user_by_token(self, token: str) -> dict[str, Any] | None: with self.conn() as c: row = c.execute("SELECT * FROM users WHERE token=?", (token,)).fetchone() return dict(row) if row else None def get_user(self, openid: str) -> dict[str, Any] | None: with self.conn() as c: row = c.execute("SELECT * FROM users WHERE openid=?", (openid,)).fetchone() return dict(row) if row else None def is_blocked(self, openid: str) -> bool: user = self.get_user(openid) return bool(user and (user.get("status") or "active") == "blocked") def set_user_pb_id(self, openid: str, pb_record_id: str): with self.conn() as c: c.execute( "UPDATE users SET pb_record_id=?, updated_at=? WHERE openid=?", (pb_record_id, time.time(), openid), ) def ensure_web_user_id(self, openid: str, web_user_id: str) -> str: """只给当前 openid 写入/保留 web_user_id,不碰其他用户。""" user = self.get_user(openid) if not user: raise ValueError("user not found") existing = (user.get("web_user_id") or "").strip() if existing: return existing with self.conn() as c: c.execute( "UPDATE users SET web_user_id=?, updated_at=? WHERE openid=?", (web_user_id, time.time(), openid), ) return web_user_id def set_vip_email_bound(self, openid: str, email: str, web_user_id: str | None = None): """仅更新当前 openid 的邮箱绑定字段。""" email = (email or "").strip().lower() with self.conn() as c: if web_user_id: c.execute( """ UPDATE users SET vip_email=?, web_user_id=COALESCE(web_user_id, ?), vip_email_bound_at=?, updated_at=? WHERE openid=? """, (email, web_user_id, time.time(), time.time(), openid), ) else: c.execute( """ UPDATE users SET vip_email=?, vip_email_bound_at=?, updated_at=? WHERE openid=? """, (email, time.time(), time.time(), openid), ) def update_user_admin( self, openid: str, *, status: str | None = None, notes: str | None = None, nickname: str | None = None, ) -> dict[str, Any] | None: user = self.get_user(openid) if not user: return None next_status = status if status is not None else user.get("status") or "active" if next_status not in ("active", "blocked"): raise ValueError("status must be active or blocked") next_notes = notes if notes is not None else user.get("notes") next_nick = nickname if nickname is not None else user.get("nickname") with self.conn() as c: c.execute( """ UPDATE users SET status=?, notes=?, nickname=?, updated_at=? WHERE openid=? """, (next_status, next_notes, next_nick, time.time(), openid), ) return self.get_user(openid) def list_users(self, limit: int = 200, q: str = "") -> list[dict[str, Any]]: with self.conn() as c: if q.strip(): like = f"%{q.strip()}%" rows = c.execute( """ SELECT * FROM users WHERE openid LIKE ? OR IFNULL(nickname,'') LIKE ? OR IFNULL(notes,'') LIKE ? ORDER BY updated_at DESC LIMIT ? """, (like, like, like, limit), ).fetchall() else: rows = c.execute( "SELECT * FROM users ORDER BY updated_at DESC LIMIT ?", (limit,), ).fetchall() unlocks = c.execute( "SELECT openid, book_id, unlocked_at, source FROM unlocks" ).fetchall() unlock_map: dict[str, list[dict[str, Any]]] = {} for u in unlocks: unlock_map.setdefault(u["openid"], []).append( { "book_id": u["book_id"], "unlocked_at": u["unlocked_at"], "source": u["source"] or "", } ) now = time.time() out = [] for r in rows: item = dict(r) item.pop("session_key", None) item.pop("token", None) item["status"] = item.get("status") or "active" item["unlocks"] = unlock_map.get(item["openid"], []) item["unlocked_default"] = any(x["book_id"] == "default" for x in item["unlocks"]) item["unlocked_vip"] = any(x["book_id"] == "__vip__" for x in item["unlocks"]) last_seen = float(item.get("last_seen_at") or 0) item["last_seen_at"] = last_seen or None item["online"] = bool(last_seen and (now - last_seen) <= self.ONLINE_WINDOW_SEC) out.append(item) # 在线置顶,其次按最近心跳 / 活跃时间 out.sort( key=lambda x: ( 0 if x.get("online") else 1, -(float(x.get("last_seen_at") or x.get("updated_at") or 0)), ) ) return out def is_unlocked(self, openid: str, book_id: str) -> bool: with self.conn() as c: row = c.execute( "SELECT 1 FROM unlocks WHERE openid=? AND book_id=?", (openid, book_id), ).fetchone() return bool(row) def grant_unlock(self, openid: str, book_id: str, source: str = "pay"): with self.conn() as c: c.execute( """ INSERT INTO unlocks(openid, book_id, unlocked_at, source) VALUES(?,?,?,?) ON CONFLICT(openid, book_id) DO UPDATE SET unlocked_at=excluded.unlocked_at, source=COALESCE(excluded.source, unlocks.source) """, (openid, book_id, time.time(), source), ) def revoke_unlock(self, openid: str, book_id: str) -> bool: with self.conn() as c: cur = c.execute( "DELETE FROM unlocks WHERE openid=? AND book_id=?", (openid, book_id), ) return cur.rowcount > 0 def create_order( self, *, openid: str, book_id: str, product_id: str, amount_fen: int, attach: str, ) -> str: out_trade_no = f"T{int(time.time())}{uuid.uuid4().hex[:10]}"[:32] now = time.time() with self.conn() as c: c.execute( """ INSERT INTO orders(out_trade_no, openid, book_id, product_id, amount_fen, status, delivered, attach, created_at, updated_at) VALUES(?,?,?,?,?,?,?,?,?,?) """, (out_trade_no, openid, book_id, product_id, amount_fen, "pending", 0, attach, now, now), ) return out_trade_no def get_order(self, out_trade_no: str) -> dict[str, Any] | None: with self.conn() as c: row = c.execute("SELECT * FROM orders WHERE out_trade_no=?", (out_trade_no,)).fetchone() return dict(row) if row else None def get_order_by_wx(self, wx_order_id: str) -> dict[str, Any] | None: with self.conn() as c: row = c.execute("SELECT * FROM orders WHERE wx_order_id=?", (wx_order_id,)).fetchone() return dict(row) if row else None def mark_delivered( self, out_trade_no: str, *, wx_order_id: str | None = None, raw_notify: str | None = None, ) -> bool: """幂等发货:已发货返回 False;新发货返回 True。""" order = self.get_order(out_trade_no) if not order: return False if wx_order_id: existed = self.get_order_by_wx(wx_order_id) if existed and existed["delivered"]: return False if order["delivered"]: return False with self.conn() as c: c.execute( """ UPDATE orders SET status=?, delivered=1, wx_order_id=COALESCE(?, wx_order_id), raw_notify=COALESCE(?, raw_notify), updated_at=? WHERE out_trade_no=? """, ("paid", wx_order_id, raw_notify, time.time(), out_trade_no), ) # 电商订单:虚拟发卡 / 实体待发货(不走小册 unlock) attach_type = "" try: attach_obj = json.loads(order.get("attach") or "{}") if isinstance(attach_obj, dict): attach_type = str(attach_obj.get("type") or "") except Exception: attach_type = "" if attach_type == "shop" or str(order.get("book_id") or "").startswith("__shop__"): try: from ebook_svc.services.shop_store import shop_store shop_store.fulfill_paid(out_trade_no) except Exception: pass return True self.grant_unlock(order["openid"], order["book_id"]) return True def list_orders(self, limit: int = 100) -> list[dict[str, Any]]: with self.conn() as c: rows = c.execute( "SELECT * FROM orders ORDER BY created_at DESC LIMIT ?", (limit,), ).fetchall() return [dict(r) for r in rows] def list_pending_orders(self) -> list[dict[str, Any]]: with self.conn() as c: rows = c.execute( "SELECT * FROM orders WHERE status='pending' AND delivered=0 ORDER BY created_at ASC" ).fetchall() return [dict(r) for r in rows] def stats(self) -> dict[str, Any]: with self.conn() as c: users = c.execute("SELECT COUNT(*) AS n FROM users").fetchone()["n"] unlocks = c.execute("SELECT COUNT(*) AS n FROM unlocks").fetchone()["n"] paid = c.execute( "SELECT COUNT(*) AS n, COALESCE(SUM(amount_fen),0) AS s FROM orders WHERE delivered=1" ).fetchone() pending = c.execute( "SELECT COUNT(*) AS n FROM orders WHERE status='pending'" ).fetchone()["n"] tracks = 0 try: tracks = c.execute("SELECT COUNT(*) AS n FROM track_events").fetchone()["n"] except Exception: pass books = 0 try: books = c.execute("SELECT COUNT(*) AS n FROM books").fetchone()["n"] except Exception: pass refunded = 0 try: refunded = c.execute( "SELECT COUNT(*) AS n FROM orders WHERE lower(status) LIKE '%refund%'" ).fetchone()["n"] except Exception: pass base = { "users": users, "unlocks": unlocks, "paid_orders": paid["n"], "paid_amount_fen": paid["s"], "pending_orders": pending, "track_events": tracks, "books": books, "refunded_orders": refunded, } base.update(self._stats_series(c)) return base def _stats_series(self, c: sqlite3.Connection) -> dict[str, Any]: """最近 14 天成交额 / 订单数 / 埋点(按本地日切)。""" days = 14 revenue: list[dict[str, Any]] = [] orders: list[dict[str, Any]] = [] events: list[dict[str, Any]] = [] try: rev_rows = c.execute( """ SELECT date(created_at, 'unixepoch', 'localtime') AS d, COUNT(*) AS n, COALESCE(SUM(amount_fen), 0) AS fen FROM orders WHERE delivered=1 AND created_at >= strftime('%s', 'now', ?) GROUP BY d ORDER BY d """, (f"-{days} days",), ).fetchall() by_day = {r["d"]: {"n": r["n"], "fen": r["fen"]} for r in rev_rows} except Exception: by_day = {} try: ev_rows = c.execute( """ SELECT date(ts, 'unixepoch', 'localtime') AS d, COUNT(*) AS n FROM track_events WHERE ts >= strftime('%s', 'now', ?) GROUP BY d ORDER BY d """, (f"-{days} days",), ).fetchall() ev_by = {r["d"]: r["n"] for r in ev_rows} except Exception: ev_by = {} import datetime as _dt today = _dt.date.today() for i in range(days - 1, -1, -1): d = (today - _dt.timedelta(days=i)).isoformat() cell = by_day.get(d) or {"n": 0, "fen": 0} revenue.append({"date": d, "amountFen": int(cell["fen"] or 0)}) orders.append({"date": d, "count": int(cell["n"] or 0)}) events.append({"date": d, "count": int(ev_by.get(d) or 0)}) top_events: list[dict[str, Any]] = [] try: for r in c.execute( """ SELECT name, COUNT(*) AS n FROM track_events WHERE ts >= strftime('%s', 'now', '-7 days') GROUP BY name ORDER BY n DESC LIMIT 8 """ ).fetchall(): top_events.append({"name": r["name"], "count": r["n"]}) except Exception: pass return { "series": {"revenue": revenue, "orders": orders, "events": events}, "topEvents": top_events, } def mark_order_status(self, out_trade_no: str, status: str) -> dict[str, Any] | None: """运营标记:cancel / refunded(不直连微信退款,只改本地状态)。""" st = (status or "").strip().lower() if st not in {"cancel", "cancelled", "refunded", "pending", "paid"}: raise ValueError("unsupported status") if st == "cancel": st = "cancelled" with self.conn() as c: row = c.execute( "SELECT * FROM orders WHERE out_trade_no=?", (out_trade_no,) ).fetchone() if not row: return None delivered = 0 if st in {"cancelled", "refunded", "pending"} else int(row["delivered"] or 0) if st == "paid": delivered = 1 c.execute( "UPDATE orders SET status=?, delivered=? WHERE out_trade_no=?", (st, delivered, out_trade_no), ) row = c.execute( "SELECT * FROM orders WHERE out_trade_no=?", (out_trade_no,) ).fetchone() return dict(row) if row else None def create_book(self, book_id: str, patch: dict[str, Any] | None = None) -> dict[str, Any]: bid = (book_id or "").strip()[:64] if not bid: raise ValueError("book_id required") if self.get_book(bid): raise ValueError("book already exists") patch = dict(patch or {}) free = bool(patch.pop("free", True)) patch.pop("id", None) patch.pop("offer_key", None) title = str(patch.get("title") or bid)[:120] book = self.ensure_book(bid, title=title, free=free) allowed = { "title", "subtitle", "author", "cover_emoji", "description", "tags", "price_fen", "product_id", "unlock_percent", "rating", "chapters", } clean = {k: v for k, v in patch.items() if k in allowed and v is not None} if clean: return self.update_book(bid, clean) return book def delete_book(self, book_id: str) -> bool: bid = (book_id or "").strip() if not bid: return False with self.conn() as c: cur = c.execute("DELETE FROM books WHERE id=?", (bid,)) return cur.rowcount > 0 def list_track_events( self, limit: int = 100, name: str = "", client: str = "", ) -> list[dict[str, Any]]: with self.conn() as c: clauses: list[str] = [] params: list[Any] = [] if name.strip(): clauses.append("name=?") params.append(name.strip()) if client.strip(): clauses.append("client=?") params.append(client.strip()) where = f" WHERE {' AND '.join(clauses)}" if clauses else "" params.append(limit) rows = c.execute( f""" SELECT id, name, page, label, props_json, openid, client, ts, created_at FROM track_events{where} ORDER BY ts DESC LIMIT ? """, tuple(params), ).fetchall() out = [] for r in rows: item = dict(r) try: item["props"] = json.loads(item.pop("props_json") or "{}") except Exception: item["props"] = {} out.append(item) return out @staticmethod def _visitor_key(openid: str, props_json: str) -> str: """FingerprintJS visitorId 优先,其次 openid;皆空则不计独立访客。""" vid = "" try: props = json.loads(props_json or "{}") if isinstance(props, dict): raw = props.get("visitorId") or props.get("visitor_id") or "" vid = str(raw).strip() except Exception: vid = "" if vid: return f"v:{vid[:128]}" oid = (openid or "").strip() if oid: return f"o:{oid[:128]}" return "" def track_analytics( self, days: int = 14, client: str = "", visitor_limit: int = 40, ) -> dict[str, Any]: """管理后台用户分析:独立访客 / DAU / 漏斗 / 端与页排行。""" import datetime as _dt days = max(1, min(int(days or 14), 90)) visitor_limit = max(5, min(int(visitor_limit or 40), 100)) client_f = (client or "").strip() since = time.time() - days * 86400 since_7 = time.time() - 7 * 86400 since_1 = time.time() - 86400 clauses = ["ts >= ?"] params: list[Any] = [since] if client_f: clauses.append("client=?") params.append(client_f) where = " WHERE " + " AND ".join(clauses) with self.conn() as c: try: c.execute("CREATE INDEX IF NOT EXISTS idx_track_client ON track_events(client)") except Exception: pass rows = c.execute( f""" SELECT name, page, label, props_json, openid, client, ts FROM track_events{where} ORDER BY ts DESC """, tuple(params), ).fetchall() total_events = len(rows) by_day_events: dict[str, int] = {} by_day_visitors: dict[str, set[str]] = {} by_client: dict[str, int] = {} by_name: dict[str, int] = {} by_page: dict[str, int] = {} by_audience: dict[str, int] = {} visitors_meta: dict[str, dict[str, Any]] = {} funnel_sets = { "page_view": set(), "pay_start": set(), "pay_success": set(), "login_ok": set(), "join_group_open": set(), "session_start": set(), } unique_all: set[str] = set() unique_1d: set[str] = set() unique_7d: set[str] = set() today = _dt.date.today() for i in range(days - 1, -1, -1): d = (today - _dt.timedelta(days=i)).isoformat() by_day_events[d] = 0 by_day_visitors[d] = set() for r in rows: name = str(r["name"] or "") page = str(r["page"] or "")[:64] cl = str(r["client"] or "") or "unknown" ts = float(r["ts"] or 0) day = _dt.datetime.fromtimestamp(ts).date().isoformat() if ts else "" vk = self._visitor_key(str(r["openid"] or ""), str(r["props_json"] or "")) by_client[cl] = by_client.get(cl, 0) + 1 by_name[name] = by_name.get(name, 0) + 1 if page: by_page[page] = by_page.get(page, 0) + 1 if day in by_day_events: by_day_events[day] += 1 props: dict[str, Any] = {} aud = "" try: raw_props = json.loads(r["props_json"] or "{}") if isinstance(raw_props, dict): props = raw_props aud = str(props.get("audience") or "").strip().lower() except Exception: props = {} if aud in ("cn", "intl"): by_audience[aud] = by_audience.get(aud, 0) + 1 if not vk: continue unique_all.add(vk) if ts >= since_1: unique_1d.add(vk) if ts >= since_7: unique_7d.add(vk) if day in by_day_visitors: by_day_visitors[day].add(vk) if name in funnel_sets: funnel_sets[name].add(vk) meta = visitors_meta.get(vk) if meta is None: # rows 按 ts DESC:首次出现即最近一次 visitors_meta[vk] = { "visitorKey": vk, "visitorId": vk[2:] if vk.startswith("v:") else "", "openid": vk[2:] if vk.startswith("o:") else "", "events": 1, "lastTs": ts, "firstTs": ts, "clients": {cl}, "pages": {page} if page else set(), "lastName": name, "lastPage": page, "hasFingerprint": vk.startswith("v:"), "lastIp": str(props.get("ip") or ""), "lastBrowser": str(props.get("browser") or ""), "lastOs": str(props.get("os") or ""), "lastDevice": str(props.get("device") or ""), "lastCountry": str(props.get("country") or ""), } else: meta["events"] += 1 meta["firstTs"] = min(float(meta["firstTs"]), ts) meta["clients"].add(cl) if page: meta["pages"].add(page) dau_series = [ {"date": d, "events": by_day_events[d], "visitors": len(by_day_visitors[d])} for d in sorted(by_day_events.keys()) ] top_events = [ {"name": n, "count": c} for n, c in sorted(by_name.items(), key=lambda x: -x[1])[:12] ] top_pages = [ {"name": n, "count": c} for n, c in sorted(by_page.items(), key=lambda x: -x[1])[:12] ] clients = [ {"name": n, "count": c} for n, c in sorted(by_client.items(), key=lambda x: -x[1]) ] audience = [ {"name": n, "count": c} for n, c in sorted(by_audience.items(), key=lambda x: -x[1]) ] pv = len(funnel_sets["page_view"] | funnel_sets["session_start"]) pay_start = len(funnel_sets["pay_start"]) pay_ok = len(funnel_sets["pay_success"]) login_ok = len(funnel_sets["login_ok"]) join_open = len(funnel_sets["join_group_open"]) def _rate(num: int, den: int) -> float: return round((num / den) * 100, 1) if den else 0.0 funnel = [ {"key": "visit", "label": "访问", "count": max(pv, len(unique_all)), "rate": 100.0}, { "key": "pay_start", "label": "发起支付", "count": pay_start, "rate": _rate(pay_start, max(pv, len(unique_all), 1)), }, { "key": "pay_success", "label": "支付成功", "count": pay_ok, "rate": _rate(pay_ok, max(pay_start, 1)), }, { "key": "login_ok", "label": "登录成功", "count": login_ok, "rate": _rate(login_ok, max(len(unique_all), 1)), }, { "key": "join_group_open", "label": "打开入群", "count": join_open, "rate": _rate(join_open, max(len(unique_all), 1)), }, ] recent_visitors: list[dict[str, Any]] = [] for meta in sorted(visitors_meta.values(), key=lambda m: -float(m["lastTs"]))[ :visitor_limit ]: recent_visitors.append( { "visitorKey": meta["visitorKey"], "visitorId": meta["visitorId"], "openid": meta["openid"], "events": int(meta["events"]), "lastTs": float(meta["lastTs"]), "firstTs": float(meta["firstTs"]), "clients": sorted(meta["clients"]), "pageCount": len(meta["pages"]), "lastName": meta["lastName"], "lastPage": meta["lastPage"], "hasFingerprint": bool(meta["hasFingerprint"]), "lastIp": meta.get("lastIp") or "", "lastBrowser": meta.get("lastBrowser") or "", "lastOs": meta.get("lastOs") or "", "lastDevice": meta.get("lastDevice") or "", "lastCountry": meta.get("lastCountry") or "", } ) return { "days": days, "client": client_f, "totals": { "events": total_events, "visitors": len(unique_all), "visitors1d": len(unique_1d), "visitors7d": len(unique_7d), "payStartVisitors": pay_start, "paySuccessVisitors": pay_ok, "payConversion": _rate(pay_ok, max(pay_start, 1)), "avgEventsPerVisitor": round(total_events / len(unique_all), 2) if unique_all else 0.0, }, "series": {"daily": dau_series}, "topEvents": top_events, "topPages": top_pages, "clients": clients, "audience": audience, "funnel": funnel, "visitors": recent_visitors, } def list_visitor_timeline( self, *, visitor_id: str = "", openid: str = "", days: int = 14, limit: int = 200, client: str = "", ) -> dict[str, Any]: """单个访客的访问明细时间线(Fingerprint visitorId 或 openid)。""" vid = (visitor_id or "").strip() oid = (openid or "").strip() if not vid and not oid: return { "ok": False, "error": "需要 visitorId 或 openid", "events": [], "summary": {}, } days = max(1, min(int(days or 14), 90)) limit = max(1, min(int(limit or 200), 500)) client_f = (client or "").strip() since = time.time() - days * 86400 clauses = ["ts >= ?"] params: list[Any] = [since] if client_f: clauses.append("client=?") params.append(client_f) where = " WHERE " + " AND ".join(clauses) with self.conn() as c: rows = c.execute( f""" SELECT id, name, page, label, props_json, openid, client, ts, created_at FROM track_events{where} ORDER BY ts DESC LIMIT 8000 """, tuple(params), ).fetchall() matched: list[dict[str, Any]] = [] pages: dict[str, int] = {} names: dict[str, int] = {} clients: set[str] = set() first_ts = 0.0 last_ts = 0.0 referrers: list[str] = [] sessions: set[str] = set() ips: list[str] = [] browsers: list[str] = [] os_list: list[str] = [] devices: list[str] = [] langs: list[str] = [] tzs: list[str] = [] countries: list[str] = [] screens: list[str] = [] uas: list[str] = [] last_traits: dict[str, Any] = {} for r in rows: props: dict[str, Any] = {} try: raw = json.loads(r["props_json"] or "{}") if isinstance(raw, dict): props = raw except Exception: props = {} p_vid = str(props.get("visitorId") or props.get("visitor_id") or "").strip() p_oid = str(r["openid"] or "").strip() hit = False if vid and (p_vid == vid or p_oid == vid): hit = True if oid and (p_oid == oid or p_vid == oid): hit = True if not hit: continue ts = float(r["ts"] or r["created_at"] or 0) page = str(r["page"] or "") name = str(r["name"] or "") cl = str(r["client"] or "") item = { "id": int(r["id"]), "name": name, "page": page, "label": r["label"], "props": props, "openid": p_oid, "client": cl, "ts": ts, "created_at": float(r["created_at"] or ts), "visitorId": p_vid, "sid": str(props.get("sid") or ""), "referrer": str(props.get("referrer") or ""), "query": str(props.get("query") or ""), "audience": str(props.get("audience") or ""), "host": str(props.get("host") or ""), "lang": str(props.get("lang") or ""), "ip": str(props.get("ip") or ""), "ua": str(props.get("ua") or ""), "browser": str(props.get("browser") or ""), "os": str(props.get("os") or ""), "device": str(props.get("device") or ""), "screen": str(props.get("screen") or ""), "tz": str(props.get("tz") or ""), "country": str(props.get("country") or ""), } matched.append(item) if page: pages[page] = pages.get(page, 0) + 1 if name: names[name] = names.get(name, 0) + 1 if cl: clients.add(cl) if ts: last_ts = max(last_ts, ts) if last_ts else ts first_ts = min(first_ts, ts) if first_ts else ts ref = str(props.get("referrer") or "").strip() if ref and ref not in referrers: referrers.append(ref) sid = str(props.get("sid") or "").strip() if sid: sessions.add(sid) def _uniq(bucket: list[str], val: str, cap: int = 8) -> None: v = (val or "").strip() if v and v not in bucket and len(bucket) < cap: bucket.append(v) _uniq(ips, str(props.get("ip") or "")) _uniq(browsers, str(props.get("browser") or "")) _uniq(os_list, str(props.get("os") or "")) _uniq(devices, str(props.get("device") or "")) _uniq(langs, str(props.get("lang") or "")) _uniq(tzs, str(props.get("tz") or "")) _uniq(countries, str(props.get("country") or "")) _uniq(screens, str(props.get("screen") or "")) _uniq(uas, str(props.get("ua") or "")[:120], 3) # rows DESC:第一条命中即最近特征 if not last_traits: last_traits = { "ip": item["ip"], "ua": item["ua"], "browser": item["browser"], "os": item["os"], "device": item["device"], "screen": item["screen"], "viewport": str(props.get("viewport") or ""), "lang": item["lang"], "langs": str(props.get("langs") or ""), "tz": item["tz"], "country": item["country"], "platform": str(props.get("platform") or ""), "touch": props.get("touch"), "cores": props.get("cores"), "mem": props.get("mem"), "conn": str(props.get("conn") or ""), "dpr": props.get("dpr"), "visitorId": p_vid, } if len(matched) >= limit: break # 时间线按时间正序更易读(列表已是 DESC 截断) timeline = list(reversed(matched)) return { "ok": True, "visitorId": vid, "openid": oid, "days": days, "summary": { "events": len(matched), "pages": len(pages), "sessions": len(sessions), "clients": sorted(clients), "firstTs": first_ts, "lastTs": last_ts, "topPages": [ {"name": n, "count": c} for n, c in sorted(pages.items(), key=lambda x: -x[1])[:8] ], "topEvents": [ {"name": n, "count": c} for n, c in sorted(names.items(), key=lambda x: -x[1])[:8] ], "referrers": referrers[:8], "traits": last_traits, "ips": ips, "browsers": browsers, "os": os_list, "devices": devices, "langs": langs, "timezones": tzs, "countries": countries, "screens": screens, "userAgents": uas, }, "events": timeline, } def add_track_event(self, ev: dict[str, Any]) -> None: with self.conn() as c: c.execute( """ CREATE TABLE IF NOT EXISTS track_events ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, page TEXT, label TEXT, props_json TEXT, openid TEXT, client TEXT, ts REAL, created_at REAL ) """ ) c.execute( """ INSERT INTO track_events(name, page, label, props_json, openid, client, ts, created_at) VALUES(?,?,?,?,?,?,?,?) """, ( ev.get("name"), ev.get("page"), ev.get("label"), json.dumps(ev.get("props") or {}, ensure_ascii=False), ev.get("openid") or "", ev.get("client") or "miniapp", float(ev.get("ts") or time.time()), time.time(), ), ) store = Store(settings.sqlite_path)