Files
xuanlong-future/server/app/routers/notifications.py
T

159 lines
5.4 KiB
Python

"""通知接口:列表(since/page 互斥)/ 统计 / 已读。"""
from __future__ import annotations
from datetime import timedelta
from fastapi import APIRouter, Depends
from pydantic import BaseModel, Field
from ..db import execute, query
from ..deps import active_user
from ..errors import ok
from ..security import now_dt, now_s
router = APIRouter(prefix="/api/notifications", tags=["notifications"])
MAX_PAGE_SIZE = 50
class ReceiptIn(BaseModel):
token: str = Field(min_length=8, max_length=128)
@router.post("/receipt")
def push_receipt(body: ReceiptIn):
"""推送到达回执(客户端埋点,2026-12-03)。
无需登录:receipt_token 是随推送下发的随机密钥,本身就是凭证。
幂等:重复回执只记录第一次。
"""
rows = query("SELECT id, received_at FROM push_batches WHERE receipt_token=?", (body.token,))
if not rows:
return ok({"recorded": False})
if rows[0]["received_at"] is None:
execute("UPDATE push_batches SET received_at=? WHERE id=?", (now_s(), rows[0]["id"]))
return ok({"recorded": True})
def _item(r, now_s_: str) -> dict:
return {
"id": r["id"],
"signal_id": r["signal_id"],
"symbol": r["symbol"],
"name": r["name"],
"interval": r["interval"],
"divergence_time": r["divergence_time"],
"kind": r["kind"],
"trigger_close": round(r["trigger_close"], 2) if r["trigger_close"] is not None else None,
"path": r["path"],
"is_new": r["read_at"] is None and r["created_at"] > _cutoff15(now_s_),
"read_at": r["read_at"],
"created_at": r["created_at"],
}
def _cutoff15(now_s_: str) -> str:
return (now_dt() - timedelta(minutes=15)).strftime("%Y-%m-%d %H:%M:%S")
@router.get("")
def list_notifications(
user: dict = Depends(active_user),
since: str | None = None,
page: int = 1,
size: int = 10,
interval: str | None = None,
symbol: str | None = None,
kind: str | None = None, # all 缺省 | divergence | ignition
):
now_s_ = now_s()
conds = ["n.user_id = ?"]
params: list = [user["id"]]
if interval:
conds.append("s.interval = ?")
params.append(interval)
if symbol:
conds.append("s.symbol = ?")
params.append(symbol)
if kind == "divergence":
conds.append("s.kind = 'divergence'")
elif kind == "ignition":
conds.append("s.kind = 'short_ignition'") # 做多起爆点统一不显示
elif kind == "bd_resonance":
conds.append("s.kind = 'bd_resonance'")
# 默认(全部)也排除做多起爆点
if "s.kind = 'short_ignition'" not in conds and "s.kind = 'divergence'" not in conds:
conds.append("s.kind != 'long_ignition'")
where = " AND ".join(conds)
total = query(
f"SELECT COUNT(*) c FROM notifications n JOIN signals s ON s.id = n.signal_id WHERE {where}",
tuple(params),
)[0]["c"]
mode = "incremental" if since else "page"
if since:
# 增量轮询:created_at > since(严格大于),忽略分页,上限 50
rows = query(
f"SELECT n.*, s.symbol, COALESCE(p.name, s.symbol) AS name, s.interval, s.divergence_time, s.trigger_close, s.path, s.kind "
f"FROM notifications n JOIN signals s ON s.id = n.signal_id "
f"LEFT JOIN products p ON p.code = s.symbol "
f"WHERE {where} AND n.created_at > ? ORDER BY n.created_at DESC LIMIT 50",
tuple(params + [since]),
)
else:
page = max(1, page)
size = max(1, min(size, MAX_PAGE_SIZE))
rows = query(
f"SELECT n.*, s.symbol, COALESCE(p.name, s.symbol) AS name, s.interval, s.divergence_time, s.trigger_close, s.path, s.kind "
f"FROM notifications n JOIN signals s ON s.id = n.signal_id "
f"LEFT JOIN products p ON p.code = s.symbol "
f"WHERE {where} ORDER BY n.created_at DESC, n.id DESC LIMIT ? OFFSET ?",
tuple(params + [size, (page - 1) * size]),
)
has_more = False
if not since:
has_more = page * size < total
return ok(
{
"total": total,
"has_more": has_more,
"mode": mode,
"items": [_item(r, now_s_) for r in rows],
}
)
@router.get("/stats")
def stats(user: dict = Depends(active_user)):
# total 读 user_counters(归档不倒退);today/week 现算
counters = query("SELECT notified_total FROM user_counters WHERE user_id=?", (user["id"],))
total = counters[0]["notified_total"] if counters else 0
today = now_dt().strftime("%Y-%m-%d")
week = (now_dt() - timedelta(days=7)).strftime("%Y-%m-%d %H:%M:%S")
today_n = query(
"SELECT COUNT(*) c FROM notifications WHERE user_id=? AND created_at >= ?",
(user["id"], today),
)[0]["c"]
week_n = query(
"SELECT COUNT(*) c FROM notifications WHERE user_id=? AND created_at >= ?",
(user["id"], week),
)[0]["c"]
return ok({"total": total, "today": today_n, "week": week_n})
class ReadIn(BaseModel):
ids: list[int]
@router.post("/read")
def mark_read(body: ReadIn, user: dict = Depends(active_user)):
ids = body.ids[:100]
now = now_s()
for nid in ids:
execute(
"UPDATE notifications SET read_at=? WHERE user_id=? AND id=? AND read_at IS NULL",
(now, user["id"], nid),
)
return ok({})