nomadro/apps/ebook/dymini/backend/app/services/store.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

598 lines
22 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 json
import sqlite3
import time
import uuid
from contextlib import contextmanager
from pathlib import Path
from typing import Any
from app.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"),
]
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):
c = sqlite3.connect(self.path)
c.row_factory = sqlite3.Row
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);
"""
)
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,
),
)
# 默认免费全书:覆盖已有 default 书的试读比例(个人主体无法支付)
if settings.default_unlock_percent >= 100:
c.execute(
"""
UPDATE books
SET unlock_percent=100, price_fen=0, product_id='', updated_at=?
WHERE id='default'
""",
(time.time(),),
)
# 清理历史种子作者文案,避免首页露出
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]:
chapters = json.loads(row["chapters_json"] 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 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
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)
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
""",
(openid, session_key, unionid, token, now, now),
)
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 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 "",
}
)
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"])
out.append(item)
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),
)
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
return {
"users": users,
"unlocks": unlocks,
"paid_orders": paid["n"],
"paid_amount_fen": paid["s"],
"pending_orders": pending,
"track_events": tracks,
}
def list_track_events(self, limit: int = 100, name: str = "") -> list[dict[str, Any]]:
with self.conn() as c:
if name.strip():
rows = c.execute(
"""
SELECT id, name, page, label, props_json, openid, client, ts, created_at
FROM track_events WHERE name=? ORDER BY ts DESC LIMIT ?
""",
(name.strip(), limit),
).fetchall()
else:
rows = c.execute(
"""
SELECT id, name, page, label, props_json, openid, client, ts, created_at
FROM track_events ORDER BY ts DESC LIMIT ?
""",
(limit,),
).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
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)