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

174 lines
5.0 KiB
Python
Raw Permalink 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.

"""埋点:入库(轻量)+ 按级别推 ntfy。"""
from __future__ import annotations
import logging
import time
from typing import Any
from app.services import ntfy as ntfy_svc
from app.services.store import store
logger = logging.getLogger(__name__)
# 立即推 ntfy 的事件(高频浏览类不推,避免拖慢接口)
NTFY_ALWAYS = {
"unlock_click",
"pay_start",
"pay_success",
"pay_cancel",
"pay_fail",
"pay_pending",
"pay_order_created",
"pay_retry",
"pay_deliver",
"login_fail",
"error",
"wx_push",
}
PRIORITY = {
"pay_success": 5,
"pay_fail": 5,
"pay_deliver": 5,
"pay_order_created": 4,
"pay_start": 4,
"pay_cancel": 3,
"pay_pending": 4,
"pay_retry": 3,
"unlock_click": 4,
"login_fail": 4,
"wx_push": 4,
"error": 4,
"page_view": 2,
"btn_click": 2,
"app_launch": 3,
}
TAGS = {
"pay_success": "moneybag,tada",
"pay_fail": "warning,x",
"pay_deliver": "moneybag,tada",
"pay_order_created": "receipt",
"pay_start": "credit_card",
"pay_cancel": "wave",
"pay_pending": "hourglass",
"pay_retry": "repeat",
"unlock_click": "unlock",
"page_view": "eyes",
"btn_click": "point_right",
"app_launch": "rocket",
"login_ok": "key",
"login_fail": "key,warning",
"toc_open": "books",
"toc_jump": "bookmark",
"settings_open": "gear",
"error": "rotating_light",
"read_start": "book",
"access_updated": "arrows_counterclockwise",
"wx_push": "incoming_envelope",
}
def _short_openid(openid: str | None) -> str:
if not openid:
return "-"
o = openid.strip()
return f"…{o[-8:]}" if len(o) > 8 else o
def _title(name: str) -> str:
mapping = {
"app_launch": "打开小程序",
"page_view": "进入页面",
"btn_click": "点击按钮",
"read_start": "开始阅读",
"unlock_click": "点击解锁",
"pay_start": "拉起支付",
"pay_success": "支付成功",
"pay_cancel": "取消支付",
"pay_fail": "支付失败",
"pay_pending": "支付确认中",
"pay_order_created": "创建订单",
"pay_retry": "支付重试",
"pay_deliver": "支付发货",
"login_ok": "登录成功",
"login_fail": "登录失败",
"toc_open": "打开目录",
"toc_jump": "目录跳转",
"settings_open": "打开设置",
"access_updated": "权限更新",
"wx_push": "微信推送",
"error": "前端异常",
}
return mapping.get(name, f"埋点 {name}")
def format_event_message(ev: dict[str, Any], *, openid: str | None, client: str | None) -> str:
parts = [f"用户 {_short_openid(openid)}"]
if ev.get("page"):
parts.append(f"页 {ev['page']}")
if ev.get("label"):
parts.append(str(ev["label"]))
props = ev.get("props") or {}
if isinstance(props, dict) and props:
bits = []
for k, v in list(props.items())[:6]:
bits.append(f"{k}={v}")
if bits:
parts.append(" · ".join(bits))
if client:
parts.append(f"[{client}]")
return " · ".join(parts)[:480]
async def ingest_events(
events: list[dict[str, Any]],
*,
openid: str | None,
client: str | None = "miniapp",
) -> dict[str, Any]:
now = time.time()
saved = 0
notified = 0
for raw in events:
name = str(raw.get("name") or "").strip()
if not name:
continue
ev = {
"name": name[:64],
"page": (raw.get("page") or "")[:64] or None,
"label": (raw.get("label") or "")[:120] or None,
"props": raw.get("props") if isinstance(raw.get("props"), dict) else {},
"ts": float(raw.get("ts") or now),
"openid": openid or "",
"client": client or "miniapp",
}
try:
store.add_track_event(ev)
saved += 1
except Exception:
logger.exception("track save failed")
if name in NTFY_ALWAYS:
ntfy_title = _title(name)
if name == "wx_push" and ev.get("label"):
ntfy_title = str(ev["label"])[:80]
elif name == "pay_deliver" and ev.get("label"):
ntfy_title = f"支付发货 · {ev['label']}"[:80]
tags = TAGS.get(name, "bar_chart")
props = ev.get("props") or {}
if name == "wx_push" and isinstance(props, dict) and props.get("tags"):
tags = str(props["tags"])
elif name == "pay_deliver" and isinstance(props, dict) and not props.get("delivered"):
tags = "moneybag"
# 后台推送,不 await,避免拖慢登录/读接口
ntfy_svc.notify_later(
format_event_message(ev, openid=openid, client=client),
title=ntfy_title,
tags=tags,
priority=PRIORITY.get(name, 3),
)
notified += 1
return {"ok": True, "saved": saved, "notified": notified}