diff --git a/app/android/app/build.gradle.kts b/app/android/app/build.gradle.kts
index e3e60ca..b2212ae 100644
--- a/app/android/app/build.gradle.kts
+++ b/app/android/app/build.gradle.kts
@@ -26,6 +26,19 @@ android {
// 极光推送(jpush_flutter 插件占位符)
manifestPlaceholders["JPUSH_APPKEY"] = "ba2236956024b8644a83e8c3"
manifestPlaceholders["JPUSH_CHANNEL"] = "developer_default"
+ // 原生层(推送到达回执)用:主选 + 兜底(手机蜂窝常拦 3003,80 端口兜底)
+ buildConfigField(
+ "String", "API_BASE_URL",
+ "\"${project.findProperty("apiBaseUrl") ?: "http://42.194.179.190:3003"}\"",
+ )
+ buildConfigField(
+ "String", "API_FALLBACK_URL",
+ "\"${project.findProperty("apiFallbackUrl") ?: "http://42.194.179.190"}\"",
+ )
+ }
+
+ buildFeatures {
+ buildConfig = true
}
buildTypes {
diff --git a/app/android/app/src/main/kotlin/com/xuanlong/xuanlong_futures/AlarmReceiver.kt b/app/android/app/src/main/kotlin/com/xuanlong/xuanlong_futures/AlarmReceiver.kt
index f5ce57c..3cf3292 100644
--- a/app/android/app/src/main/kotlin/com/xuanlong/xuanlong_futures/AlarmReceiver.kt
+++ b/app/android/app/src/main/kotlin/com/xuanlong/xuanlong_futures/AlarmReceiver.kt
@@ -24,7 +24,12 @@ class AlarmReceiver : JPushMessageReceiver() {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
putExtra("kind", extras.optString("kind", "divergence"))
if (extras.optString("kind") == "digest") {
- putExtra("summary", "本轮新增 ${extras.optString("signal_ids").split(",").size} 个信号,打开查看")
+ // 服务端把本轮全部信号点拼好放在 summary(2026-12-03)
+ val s = extras.optString("summary", "")
+ putExtra(
+ "summary",
+ s.ifEmpty { "本轮新增 ${extras.optString("signal_ids").split(",").size} 个信号,打开查看" },
+ )
} else {
putExtra("symbol", extras.optString("symbol"))
putExtra("interval", extras.optString("interval"))
@@ -32,6 +37,9 @@ class AlarmReceiver : JPushMessageReceiver() {
}
}
+ // 到达回执:带 receipt_token 的推送上报一次,服务端统计到达率(2026-12-03)
+ reportReceipt(extras.optString("receipt_token"))
+
// App 在前台:直接拉起,不经通知
if (isAppForeground(context)) {
context.startActivity(intent)
@@ -40,17 +48,48 @@ class AlarmReceiver : JPushMessageReceiver() {
notifyFullScreen(context, intent)
}
updatePersistentStatus(context, extras.optString("kind"), extras.optString("symbol"),
- extras.optString("interval"), extras.optString("divergence_time"))
+ extras.optString("interval"), extras.optString("divergence_time"),
+ extras.optString("summary"))
+ }
+
+ /** 推送到达回执:带 receipt_token 才上报;主选地址失败自动换兜底地址。
+ * 失败不重试(与后端约定一致),只影响到达率统计不影响业务。 */
+ private fun reportReceipt(token: String) {
+ if (token.isEmpty()) return
+ Thread {
+ val body = "{\"token\":\"$token\"}".toByteArray()
+ for (base in listOf(BuildConfig.API_BASE_URL, BuildConfig.API_FALLBACK_URL)) {
+ var conn: java.net.HttpURLConnection? = null
+ try {
+ conn = (java.net.URL("$base/api/notifications/receipt").openConnection()
+ as java.net.HttpURLConnection).apply {
+ requestMethod = "POST"
+ connectTimeout = 5000
+ readTimeout = 5000
+ doOutput = true
+ setRequestProperty("Content-Type", "application/json")
+ }
+ conn.outputStream.use { it.write(body) }
+ val code = conn.responseCode
+ if (code in 200..299) return@Thread
+ } catch (_: Exception) {
+ // 换下一个地址
+ } finally {
+ try { conn?.disconnect() } catch (_: Exception) {}
+ }
+ }
+ }.start()
}
/** 信号到达即更新常驻状态文本(flutter.xl_status_text)并即时刷新前台服务。 */
private fun updatePersistentStatus(
context: Context, kind: String, symbol: String, interval: String, divTime: String,
+ summary: String = "",
) {
val hm = java.text.SimpleDateFormat("HH:mm", java.util.Locale.CHINA).format(java.util.Date())
val label = labelOf(kind)
val body = if (kind == "digest") {
- "$hm · 最新:$label"
+ "$hm · ${summary.ifEmpty { label }}".let { if (it.length > 60) it.take(58) + "…" else it }
} else {
"$hm · 最新 $symbol $interval $label ${divTime.takeLast(5)}"
}
@@ -97,7 +136,12 @@ class AlarmReceiver : JPushMessageReceiver() {
}
val notification = builder
.setContentTitle("玄龙期货")
- .setContentText(intent.getStringExtra("kind")?.let { labelOf(it) } ?: "新信号")
+ // digest:通知正文显示本轮信号点列表;单条:显示类型
+ .setContentText(
+ if (intent.getStringExtra("kind") == "digest")
+ intent.getStringExtra("summary") ?: "新信号"
+ else intent.getStringExtra("kind")?.let { labelOf(it) } ?: "新信号",
+ )
.setSmallIcon(android.R.drawable.ic_dialog_alert)
.setCategory(Notification.CATEGORY_ALARM)
.setVisibility(Notification.VISIBILITY_PUBLIC)
diff --git a/app/lib/features/misc/app_updater.dart b/app/lib/features/misc/app_updater.dart
index 4169dd0..e8a0c1b 100644
--- a/app/lib/features/misc/app_updater.dart
+++ b/app/lib/features/misc/app_updater.dart
@@ -14,7 +14,7 @@ import 'package:path_provider/path_provider.dart';
import '../../core/network/api_client.dart';
import '../../core/theme/app_colors.dart';
-const kAppVersion = '1.4.6'; // 与 pubspec.yaml version 同步
+const kAppVersion = '1.4.7'; // 与 pubspec.yaml version 同步
/// 比较语义化版本:a < b 返回 -1,> 返回 1,相等 0
int compareVersion(String a, String b) {
diff --git a/app/pubspec.yaml b/app/pubspec.yaml
index 7d60629..50a9f6f 100644
--- a/app/pubspec.yaml
+++ b/app/pubspec.yaml
@@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
-version: 1.4.6+17
+version: 1.4.7+18
environment:
sdk: ^3.12.2
diff --git a/server/app/admin.html b/server/app/admin.html
index 9a16fff..735f821 100644
--- a/server/app/admin.html
+++ b/server/app/admin.html
@@ -70,14 +70,24 @@
用户管理
@@ -158,7 +168,7 @@ async function uploadApk() {
function enter(){
document.getElementById('login').classList.add('hide');
document.getElementById('main').classList.remove('hide');
- loadUsers(); loadSignals();
+ loadUsers(); loadSignals(); loadPushStats();
}
async function genCodes(){
@@ -174,6 +184,24 @@ async function testSignal(){
toast(`测试推送已发送(${d.devices} 台设备)` + (d.jpush && d.jpush.http_status === 200 ? '' : ',极光返回异常:' + JSON.stringify(d.jpush)));
}
+async function loadPushStats(){
+ const days = document.getElementById('psDays').value || '7';
+ const d = await api('/api/admin/push-stats?days=' + days);
+ document.getElementById('psSummary').textContent =
+ `发送 ${d.total} 条 · 成功 ${d.success} · 失败 ${d.failed} · 客户端回执 ${d.received} 条 · 到达率 ${d.rate}%`;
+ const rows = d.recent.map(r => {
+ const delay = r.received_at
+ ? Math.round((new Date(r.received_at.replace(' ','T')) - new Date(r.sent_at.replace(' ','T')))/1000) + 's'
+ : '—';
+ return `
| ${r.id} | ${r.phone||r.user_id} | ${r.item_count} |
+ ${r.status==='success'?'成功':'失败'} | ${r.sent_at.slice(5)} |
+ ${r.received_at?r.received_at.slice(5):'未回执'} | ${delay} |
+ ${r.error||''} |
`;
+ }).join('');
+ document.getElementById('pushStats').innerHTML =
+ '
| 批次 | 用户 | 信号数 | 发送 | 发送时间 | 回执时间 | 延迟 | 错误 |
|---|
' + rows;
+}
+
async function loadUsers(){
const q = document.getElementById('uq').value.trim();
const rows = await api('/api/admin/users?q='+encodeURIComponent(q));
diff --git a/server/app/db.py b/server/app/db.py
index dce0864..6b071ce 100644
--- a/server/app/db.py
+++ b/server/app/db.py
@@ -138,6 +138,22 @@ CREATE TABLE IF NOT EXISTS push_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
notification_id INTEGER, provider TEXT, status TEXT, error TEXT, sent_at TEXT
);
+-- 推送批次:每轮扫描每个用户只发一条聚合推送,一条批次即一次发送;
+-- receipt_token 随推送下发,客户端收到后回执,received_at 用于统计到达率
+CREATE TABLE IF NOT EXISTS push_batches (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ user_id INTEGER NOT NULL,
+ rid TEXT,
+ device_id TEXT,
+ signal_ids TEXT NOT NULL,
+ item_count INTEGER NOT NULL,
+ status TEXT NOT NULL DEFAULT 'pending', -- success | failed
+ error TEXT,
+ receipt_token TEXT NOT NULL UNIQUE,
+ sent_at TEXT NOT NULL,
+ received_at TEXT,
+ received_rid TEXT
+);
CREATE TABLE IF NOT EXISTS sms_codes (
phone TEXT NOT NULL, scene TEXT NOT NULL, code_hash TEXT,
expires_at TEXT, attempts INTEGER NOT NULL DEFAULT 0, sent_at TEXT,
@@ -166,6 +182,7 @@ CREATE INDEX IF NOT EXISTS idx_sig_time ON signals(divergence_time DESC);
CREATE INDEX IF NOT EXISTS idx_sig_symbol ON signals(symbol, interval, divergence_time DESC);
CREATE INDEX IF NOT EXISTS idx_bars_lookup ON bars_cache(symbol, interval, dt DESC);
CREATE INDEX IF NOT EXISTS idx_smslog_phone ON sms_log(phone, sent_at);
+CREATE INDEX IF NOT EXISTS idx_push_batches_time ON push_batches(sent_at DESC);
"""
diff --git a/server/app/notify/push.py b/server/app/notify/push.py
index b3df003..28e725b 100644
--- a/server/app/notify/push.py
+++ b/server/app/notify/push.py
@@ -1,4 +1,12 @@
-"""JPush 批量下发。未配置凭证时全部标记 skipped(不阻塞扫描)。"""
+"""JPush 下发。
+
+2026-12-03 改版(用户要求):
+ 1. 推送失败**不重试**,但必须把失败原因写进日志(此前 error 字段一直是空)。
+ 2. 每一轮扫描,每个用户只发**一条**聚合推送,正文列出本轮全部信号点,
+ 避免短时间内对同一台设备连推多条(极光频控会延迟甚至丢弃)。
+ 3. 每条推送带 receipt_token,客户端收到后回执,服务端据此统计到达率。
+未配置凭证时返回 skipped(不阻塞扫描)。
+"""
from __future__ import annotations
import httpx
@@ -7,59 +15,88 @@ from ..config import settings
API = "https://api.jpush.cn/v3/push"
+_KIND_LABEL = {
+ "long_ignition": "做多起爆点",
+ "short_ignition": "做空起爆点",
+ "bd_resonance": "卖出(BD共振)",
+ "divergence": "量价背离",
+}
-def push_batch(rows: list[dict]) -> dict[int, str]:
- """rows: [{id, user_id, signal_id, symbol, interval, divergence_time}, ...]
- 返回 {notification_id: status},status ∈ success | failed | skipped
+def _label(kind: str) -> str:
+ return _KIND_LABEL.get(kind, "量价背离")
+
+
+def _describe(it) -> str:
+ """单条信号的简报:量价背离 RB 30m 12-03 09:30"""
+ return f"{_label(it['kind'])} {it['symbol']} {it['interval']} {it['divergence_time'][5:]}"
+
+
+def build_content(items: list) -> str:
+ """一份推送的正文:列出全部信号点(超过 3 个时省略并标注总数)。"""
+ parts = [_describe(it) for it in items]
+ if len(parts) == 1:
+ it = items[0]
+ return f"【{_label(it['kind'])}】{it['symbol']} · {it['interval']} · {it['divergence_time'][5:]}"
+ shown = parts[:3]
+ more = f"…等 {len(parts)} 个" if len(parts) > 3 else ""
+ return f"本轮 {len(parts)} 个信号:" + ";".join(shown) + more
+
+
+def build_payload(items: list, rids: list[str], batch: dict) -> dict:
+ """一条聚合推送。单个信号保留其 kind(闹钟页显示类型),多个信号用 digest。"""
+ if len(items) == 1:
+ it = items[0]
+ kind = it["kind"]
+ else:
+ kind = "digest"
+ summary = build_content(items)
+ extras = {
+ "type": "signal_alarm",
+ "kind": kind,
+ "signal_ids": ",".join(str(it["signal_id"]) for it in items),
+ "summary": summary,
+ "batch_id": str(batch["id"]),
+ "receipt_token": batch["receipt_token"],
+ }
+ if len(items) == 1:
+ # 单条:闹钟页按明细渲染(symbol · interval · 时间),客户端依赖这三项
+ it = items[0]
+ extras.update({
+ "signal_id": str(it["signal_id"]),
+ "symbol": it["symbol"],
+ "interval": it["interval"],
+ "divergence_time": it["divergence_time"],
+ })
+ return {
+ "platform": "android",
+ "audience": {"registration_id": rids[:1000]},
+ "message": {"title": "玄龙期货", "msg_content": summary, "extras": extras},
+ "options": {"time_to_live": 86400},
+ }
+
+
+def send_round_push(items: list, rids: list[str], batch: dict) -> tuple[str, str | None]:
+ """发送一条聚合推送。返回 (status, error)。
+
+ status ∈ success | failed;失败时 error 记录极光返回体或异常原文——
+ 按用户要求失败不重试,但必须留下可查的原因。
"""
if not settings.jpush_app_key or not settings.jpush_master_secret:
- return {r["id"]: "skipped" for r in rows}
-
- results: dict[int, str] = {}
- batch_size = max(1, settings.push_batch_size)
- for i in range(0, len(rows), batch_size):
- chunk = rows[i : i + batch_size]
- results.update(_push_chunk(chunk))
- return results
-
-
-def _push_chunk(chunk: list[dict]) -> dict[int, str]:
- out: dict[int, str] = {}
- # 同一用户多条信号:JPush 一次调用只能一个 payload,按用户聚合,单用户
- # 一轮 >3 条合并为一条摘要(PRD §11.1 突发合流)。
- by_user: dict[int, list[dict]] = {}
- for r in chunk:
- by_user.setdefault(r["user_id"], []).append(r)
-
- with httpx.Client(timeout=10) as http:
- for user_id, items in by_user.items():
- rids = []
- for it in items:
- rid = it["jpush_rid"] if "jpush_rid" in it.keys() else None
- if rid and rid not in rids:
- rids.append(rid)
- if not rids:
- for it in items:
- out[it["id"]] = "skipped"
- continue
- payload = _payload(items, rids)
- try:
- resp = http.post(
- API,
- json=payload,
- auth=(settings.jpush_app_key, settings.jpush_master_secret),
- )
- ok = resp.status_code == 200
- for it in items:
- out[it["id"]] = "success" if ok else "failed"
- except Exception:
- for it in items:
- out[it["id"]] = "failed"
- return out
-
-
-_KIND_LABEL = {"long_ignition": "做多起爆点", "short_ignition": "做空起爆点", "bd_resonance": "卖出(BD共振)"}
+ return "failed", "JPush 凭证未配置"
+ payload = build_payload(items, rids, batch)
+ try:
+ resp = httpx.post(
+ API, json=payload,
+ auth=(settings.jpush_app_key, settings.jpush_master_secret),
+ timeout=10,
+ )
+ except Exception as exc: # 网络/超时:记录原文
+ return "failed", f"{type(exc).__name__}: {exc}"
+ if resp.status_code == 200:
+ return "success", None
+ body = resp.text[:500]
+ return "failed", f"HTTP {resp.status_code}: {body}"
def push_test_signal(rids: list[str]) -> dict:
@@ -97,31 +134,6 @@ def push_test_signal(rids: list[str]) -> dict:
return {"http_status": resp.status_code, "body": body}
-def _payload(items: list[dict], rids: list[str]) -> dict:
- first = items[0]
- sig_ids = [it["signal_id"] for it in items]
- row_kind = first["kind"] if "kind" in first.keys() else "divergence"
- label = _KIND_LABEL.get(row_kind, "量价背离")
- if len(items) > 3:
- content = f"本轮新增 {len(items)} 个信号"
- extras = {"type": "signal_alarm", "kind": "digest",
- "signal_ids": ",".join(str(s) for s in sig_ids)}
- else:
- content = (
- f"【{label}】{first['symbol']} · {first['interval']} · {first['divergence_time'][5:]}"
- )
- extras = {"type": "signal_alarm", "kind": row_kind,
- "signal_id": str(first["signal_id"]),
- "symbol": first["symbol"], "interval": first["interval"],
- "divergence_time": first["divergence_time"]}
- return {
- "platform": "all",
- "audience": {"registration_id": rids},
- "message": {"title": "玄龙期货", "msg_content": content, "extras": extras},
- "options": {"time_to_live": 86400},
- }
-
-
def push_text(rids: list[str], title: str, body: str) -> None:
"""纯文本推送(到期提醒等),无深链 extras。"""
if not settings.jpush_app_key or not rids:
@@ -136,3 +148,8 @@ def push_text(rids: list[str], title: str, body: str) -> None:
httpx.post(API, json=payload, auth=(settings.jpush_app_key, settings.jpush_master_secret), timeout=8)
except Exception:
pass
+
+
+__all__ = [
+ "build_content", "build_payload", "send_round_push", "push_test_signal", "push_text",
+]
\ No newline at end of file
diff --git a/server/app/routers/admin.py b/server/app/routers/admin.py
index 7accf58..d0e90e9 100644
--- a/server/app/routers/admin.py
+++ b/server/app/routers/admin.py
@@ -115,6 +115,41 @@ def unbind(user_id: int, _: None = Depends(verify_admin)):
return ok({})
+# ---- 推送收发统计(2026-12-03) -------------------------------------------------
+# 发送:每轮扫描每个用户一条聚合推送 = 一条 push_batches 记录
+# 到达:客户端收到推送后带 receipt_token 回执,写 received_at
+
+@router.get("/push-stats")
+def push_stats(days: int = 7, _: None = Depends(verify_admin)):
+ days = max(1, min(days, 90))
+ since = (now_dt() - timedelta(days=days)).strftime("%Y-%m-%d %H:%M:%S")
+ agg = query(
+ "SELECT COUNT(*) AS total,"
+ " SUM(CASE WHEN status='success' THEN 1 ELSE 0 END) AS success,"
+ " SUM(CASE WHEN status='failed' THEN 1 ELSE 0 END) AS failed,"
+ " SUM(CASE WHEN received_at IS NOT NULL THEN 1 ELSE 0 END) AS received"
+ " FROM push_batches WHERE sent_at >= ?",
+ (since,),
+ )[0]
+ total = agg["total"] or 0
+ received = agg["received"] or 0
+ recent = query(
+ "SELECT b.id, b.user_id, u.phone, b.item_count, b.status, b.error, b.sent_at, b.received_at"
+ " FROM push_batches b LEFT JOIN users u ON u.id = b.user_id"
+ " WHERE b.sent_at >= ? ORDER BY b.id DESC LIMIT 50",
+ (since,),
+ )
+ return ok({
+ "days": days,
+ "total": total,
+ "success": agg["success"] or 0,
+ "failed": agg["failed"] or 0,
+ "received": received,
+ "rate": round(received * 100.0 / total, 1) if total else 0.0,
+ "recent": [dict(r) for r in recent],
+ })
+
+
# ---- 信号流水 --------------------------------------------------------------------
@router.get("/signals")
diff --git a/server/app/routers/notifications.py b/server/app/routers/notifications.py
index d579f51..a7037de 100644
--- a/server/app/routers/notifications.py
+++ b/server/app/routers/notifications.py
@@ -4,7 +4,7 @@ from __future__ import annotations
from datetime import timedelta
from fastapi import APIRouter, Depends
-from pydantic import BaseModel
+from pydantic import BaseModel, Field
from ..db import execute, query
from ..deps import active_user
@@ -16,6 +16,25 @@ 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"],
diff --git a/server/app/services/dispatch.py b/server/app/services/dispatch.py
index ee5f78f..786dd8a 100644
--- a/server/app/services/dispatch.py
+++ b/server/app/services/dispatch.py
@@ -1,10 +1,12 @@
-"""信号分发:四类用户过滤(SQL 层)→ notifications 行 → JPush 批量下发。
+"""信号分发:四类用户过滤(SQL 层)→ notifications 行 → JPush 下发。
enqueue:在扫描事务内调用(与 signals/checkpoint 同事务提交)。
-push_pending:事务外执行;失败保持 pending,下一轮开头补发。
+push_pending:事务外执行。2026-12-03 起:每轮扫描每个用户只发一条聚合推送,
+失败不重试,但把原因写入 push_batches/push_log 供排查与统计。
"""
from __future__ import annotations
+import secrets
from datetime import datetime, timedelta, timezone
from ..db import execute, query
@@ -135,12 +137,14 @@ def send_signal_sms() -> None:
def push_pending() -> None:
- """把 pending 通知推出去。失败保持 pending;>30 分钟置 expired。
+ """把 pending 通知推出去:每轮每个用户一条聚合推送。
- 旧信号闸门(2026-11-24):判定失败修复/宕机重启/数据回流补判会批量产出
- 历史日期的信号,divergence_time 距今 >30 分钟的不弹推送(置 skipped),
- 只保留 App 内通知列表可见——避免补扫把半年前的点半夜推成闹钟。"""
- from ..notify.push import push_batch # 延迟导入,避免无凭证时报错
+ - 旧信号闸门(2026-11-24):divergence_time 距今 >30 分钟不弹推送(skipped)
+ - >30 分钟仍未发出的 pending 置 expired
+ - 失败不重试(用户 2026-12-03 要求),原因写入 push_batches.error / push_log.error
+ - 每条推送生成 push_batches 批次行并带 receipt_token,客户端回执后写 received_at
+ """
+ from ..notify.push import send_round_push # 延迟导入,避免无凭证时报错
gate = (_now() - timedelta(minutes=30)).strftime("%Y-%m-%d %H:%M:%S")
execute(
@@ -169,16 +173,37 @@ def push_pending() -> None:
)
if not rows:
return
- results = push_batch(rows)
- _apply_results(results)
+ # JOIN devices 会把同一通知按设备行放大:按通知 id 去重,同时收集该用户的全部有效 rid
+ by_user: dict[int, dict] = {}
+ for r in rows:
+ u = by_user.setdefault(r["user_id"], {"items": {}, "rids": []})
+ u["items"][r["id"]] = {
+ "id": r["id"], "signal_id": r["signal_id"], "symbol": r["symbol"],
+ "interval": r["interval"], "divergence_time": r["divergence_time"], "kind": r["kind"],
+ }
+ rid = r["jpush_rid"]
+ if rid and rid not in u["rids"]:
+ u["rids"].append(rid)
-def _apply_results(results: dict[int, str]) -> None:
- from ..db import execute
-
- for nid, status in results.items():
- execute("UPDATE notifications SET push_status=? WHERE id=?", (status, nid))
+ now_str = _now().strftime("%Y-%m-%d %H:%M:%S")
+ for user_id, u in by_user.items():
+ items = sorted(u["items"].values(), key=lambda x: x["divergence_time"])
+ rids = u["rids"]
+ token = secrets.token_urlsafe(24)
+ # 先落批次再发送:发送途中进程崩溃也留有记录
execute(
- "INSERT INTO push_log(notification_id, provider, status, sent_at) VALUES(?,?,?,?)",
- (nid, "jpush", status, _now().strftime("%Y-%m-%d %H:%M:%S")),
+ "INSERT INTO push_batches(user_id, rid, signal_ids, item_count, status, receipt_token, sent_at)"
+ " VALUES(?,?,?,?,?,?,?)",
+ (user_id, ",".join(rids), ",".join(str(it["signal_id"]) for it in items),
+ len(items), "pending", token, now_str),
)
+ batch = query("SELECT id, receipt_token FROM push_batches WHERE receipt_token=?", (token,))[0]
+ status, error = send_round_push(items, rids, batch)
+ execute("UPDATE push_batches SET status=?, error=? WHERE id=?", (status, error, batch["id"]))
+ for it in items:
+ execute("UPDATE notifications SET push_status=? WHERE id=?", (status, it["id"]))
+ execute(
+ "INSERT INTO push_log(notification_id, provider, status, error, sent_at) VALUES(?,?,?,?,?)",
+ (it["id"], "jpush", status, error, now_str),
+ )
diff --git a/server/tests/test_push.py b/server/tests/test_push.py
index 35d332e..7feca4a 100644
--- a/server/tests/test_push.py
+++ b/server/tests/test_push.py
@@ -1,5 +1,11 @@
-"""_payload:信号推送改发 JPush 自定义消息(闹钟 payload)。"""
-from app.notify.push import _payload
+"""build_payload:信号推送走 JPush 自定义消息(闹钟 payload)。
+
+2026-12-03 改版后仍必须保证:自定义消息(不发通知栏)、单条信号带明细 extras
+(闹钟页按 symbol · interval · 时间渲染)、多条聚合为 digest、带回执令牌。
+"""
+from app.notify.push import build_payload
+
+_BATCH = {"id": 9, "receipt_token": "tok-abcdefgh"}
def test_single_signal_uses_message_with_alarm_extras():
@@ -7,7 +13,7 @@ def test_single_signal_uses_message_with_alarm_extras():
"id": 1, "user_id": 7, "signal_id": 42, "symbol": "FUL9",
"interval": "30m", "divergence_time": "2026-11-22 10:15", "kind": "divergence",
}]
- p = _payload(items, ["ridA"])
+ p = build_payload(items, ["ridA"], _BATCH)
assert "notification" not in p # 不再发通知栏
msg = p["message"]
assert msg["title"] == "玄龙期货"
@@ -19,6 +25,8 @@ def test_single_signal_uses_message_with_alarm_extras():
assert ex["symbol"] == "FUL9"
assert ex["interval"] == "30m"
assert ex["divergence_time"] == "2026-11-22 10:15"
+ assert ex["receipt_token"] == "tok-abcdefgh"
+ assert ex["batch_id"] == "9"
def test_digest_merges_and_marks_kind_digest():
@@ -26,15 +34,16 @@ def test_digest_merges_and_marks_kind_digest():
"id": i, "user_id": 7, "signal_id": 100 + i, "symbol": f"S{i}",
"interval": "30m", "divergence_time": "2026-11-22 10:15", "kind": "divergence",
} for i in range(5)]
- p = _payload(items, ["ridA"])
+ p = build_payload(items, ["ridA"], _BATCH)
ex = p["message"]["extras"]
assert ex["kind"] == "digest"
assert ex["signal_ids"] == "100,101,102,103,104"
- assert "本轮新增 5 个信号" in p["message"]["msg_content"]
+ assert p["message"]["msg_content"].startswith("本轮 5 个信号:")
+ assert "等 5 个" in p["message"]["msg_content"]
def test_audience_uses_registration_ids():
items = [{"id": 1, "user_id": 7, "signal_id": 42, "symbol": "FUL9",
"interval": "30m", "divergence_time": "2026-11-22 10:15", "kind": "bd_resonance"}]
- p = _payload(items, ["r1", "r2"])
- assert p["audience"] == {"registration_id": ["r1", "r2"]}
+ p = build_payload(items, ["r1", "r2"], _BATCH)
+ assert p["audience"] == {"registration_id": ["r1", "r2"]}
\ No newline at end of file
diff --git a/server/tests/test_push_round.py b/server/tests/test_push_round.py
new file mode 100644
index 0000000..db2b5f9
--- /dev/null
+++ b/server/tests/test_push_round.py
@@ -0,0 +1,198 @@
+"""推送改版回归(2026-12-03,用户三项要求):
+1. 发送失败不重试,但必须记录原因
+2. 每轮扫描每个用户只发一条聚合推送,正文列出本轮全部信号点
+3. 每条推送带 receipt_token,客户端回执后写入 received_at(到达率统计)
+"""
+from datetime import datetime, timedelta, timezone
+
+import pytest
+
+from app.notify import push as push_mod
+
+
+def _item(symbol="RB", interval="30m", dt="2026-12-03 09:30", kind="divergence", sid=1):
+ return {"id": sid, "signal_id": sid, "symbol": symbol, "interval": interval,
+ "divergence_time": dt, "kind": kind}
+
+
+_BATCH = {"id": 7, "receipt_token": "tok-abcdefgh"}
+
+
+# ---- 正文:列出本轮全部信号点 -------------------------------------------------------
+
+def test_content_single_signal_keeps_kind_style():
+ assert push_mod.build_content([_item()]) == "【量价背离】RB · 30m · 12-03 09:30"
+
+
+def test_content_multiple_lists_each_point():
+ items = [
+ _item("RB", "30m", "2026-12-03 09:30"),
+ _item("CU", "90m", "2026-12-03 10:00", "short_ignition", 2),
+ ]
+ text = push_mod.build_content(items)
+ assert text.startswith("本轮 2 个信号:")
+ assert "量价背离 RB 30m 12-03 09:30" in text
+ assert "做空起爆点 CU 90m 12-03 10:00" in text
+
+
+def test_content_truncates_after_three_but_states_total():
+ items = [_item(f"S{i}", "30m", f"2026-12-03 0{i}:30", sid=i) for i in range(1, 6)]
+ text = push_mod.build_content(items)
+ assert text.startswith("本轮 5 个信号:")
+ assert "等 5 个" in text
+ assert text.count("量价背离") == 3 # 只列前 3 个
+
+
+# ---- 载荷:聚合 + 回执令牌 ---------------------------------------------------------
+
+def test_payload_digest_carries_all_signal_ids_and_receipt():
+ items = [_item(sid=1), _item("CU", sid=2)]
+ p = push_mod.build_payload(items, ["rid1"], _BATCH)
+ ex = p["message"]["extras"]
+ assert ex["kind"] == "digest"
+ assert ex["signal_ids"] == "1,2"
+ assert ex["receipt_token"] == "tok-abcdefgh"
+ assert ex["batch_id"] == "7"
+ assert ex["summary"].startswith("本轮 2 个信号")
+ assert p["audience"]["registration_id"] == ["rid1"]
+ assert p["message"]["msg_content"] == ex["summary"]
+
+
+def test_payload_single_signal_keeps_its_kind():
+ ex = push_mod.build_payload([_item(kind="bd_resonance")], ["r"], _BATCH)["message"]["extras"]
+ assert ex["kind"] == "bd_resonance"
+ assert ex["receipt_token"] == "tok-abcdefgh"
+
+
+# ---- 失败:不重试,必须记录原因 ----------------------------------------------------
+
+def test_http_error_records_response_body(monkeypatch):
+ class Resp:
+ status_code = 400
+ text = '{"error":{"code":1003,"message":"invalid parameter"}}'
+
+ monkeypatch.setattr(push_mod.httpx, "post", lambda *a, **k: Resp())
+ monkeypatch.setattr(push_mod.settings, "jpush_app_key", "k")
+ monkeypatch.setattr(push_mod.settings, "jpush_master_secret", "s")
+ status, err = push_mod.send_round_push([_item()], ["r"], _BATCH)
+ assert status == "failed"
+ assert "HTTP 400" in err and "1003" in err
+
+
+def test_network_exception_is_recorded(monkeypatch):
+ def boom(*a, **k):
+ raise TimeoutError("read timed out")
+
+ monkeypatch.setattr(push_mod.httpx, "post", boom)
+ monkeypatch.setattr(push_mod.settings, "jpush_app_key", "k")
+ monkeypatch.setattr(push_mod.settings, "jpush_master_secret", "s")
+ status, err = push_mod.send_round_push([_item()], ["r"], _BATCH)
+ assert status == "failed"
+ assert "TimeoutError" in err and "read timed out" in err
+
+
+def test_missing_credentials_fail_with_reason(monkeypatch):
+ monkeypatch.setattr(push_mod.settings, "jpush_app_key", "")
+ status, err = push_mod.send_round_push([_item()], ["r"], _BATCH)
+ assert status == "failed" and "凭证" in err
+
+
+def test_success_has_no_error(monkeypatch):
+ class Resp:
+ status_code = 200
+ text = ""
+
+ monkeypatch.setattr(push_mod.httpx, "post", lambda *a, **k: Resp())
+ monkeypatch.setattr(push_mod.settings, "jpush_app_key", "k")
+ monkeypatch.setattr(push_mod.settings, "jpush_master_secret", "s")
+ assert push_mod.send_round_push([_item()], ["r"], _BATCH) == ("success", None)
+
+
+# ---- 分发:每轮每用户一条推送 -------------------------------------------------------
+
+@pytest.fixture()
+def seeded(monkeypatch):
+ """两个用户各 2 个信号、一台设备;第三个用户无设备。"""
+ from app import db
+ from app.services import dispatch
+
+ db.init_db()
+ # 同一临时库会被多个用例复用:先清空相关表
+ for t in ("notifications", "signals", "devices", "users", "push_batches", "push_log"):
+ db.execute(f"DELETE FROM {t}")
+ now = (datetime.now(timezone(timedelta(hours=8)))).strftime("%Y-%m-%d %H:%M:%S")
+ dt = now # 新鲜信号,不被 30 分钟闸门拦
+ for uid in (1, 2, 3):
+ db.execute(
+ "INSERT OR REPLACE INTO users(id, phone, password_hash, active_until, is_banned, created_at)"
+ " VALUES(?,?,?,?,0,?)", (uid, f"13{uid:09d}", "x", "2099-01-01", now),
+ )
+ for uid in (1, 2):
+ db.execute(
+ "INSERT INTO devices(user_id, device_id, brand, jpush_rid, rid_invalid, last_seen)"
+ " VALUES(?,?,?,?,0,?)", (uid, f"dev{uid}", "android", f"rid-{uid}", now),
+ )
+ sig_ids = []
+ for i, (sym, kind) in enumerate([("RB", "divergence"), ("CU", "short_ignition")], start=1):
+ db.execute(
+ "INSERT INTO signals(symbol, interval, divergence_time, kind, created_at)"
+ " VALUES(?,?,?,?,?)", (sym, "30m", dt, kind, now),
+ )
+ sig_ids.append(db.query("SELECT last_insert_rowid() AS i")[0]["i"])
+ for uid in (1, 2, 3):
+ for sid in sig_ids:
+ db.execute(
+ "INSERT INTO notifications(user_id, signal_id, created_at, push_status) VALUES(?,?,?,?)",
+ (uid, sid, now, "pending"),
+ )
+ calls = []
+
+ def fake_send(items, rids, batch):
+ calls.append({"items": items, "rids": rids, "batch": batch})
+ return "success", None
+
+ monkeypatch.setattr("app.notify.push.send_round_push", fake_send)
+ dispatch.push_pending()
+ return {"calls": calls, "sig_ids": sig_ids, "db": db}
+
+
+def test_one_push_per_user_per_round(seeded):
+ """两个有设备的用户各只有 1 次发送调用,且各含本轮全部 2 个信号。"""
+ calls = seeded["calls"]
+ assert len(calls) == 2
+ for c in calls:
+ assert len(c["items"]) == 2 # 聚合,不按信号拆多条
+ assert len({it["id"] for it in c["items"]}) == 2 # JOIN devices 未造成重复
+
+
+def test_batch_row_and_notification_status(seeded):
+ db = seeded["db"]
+ batch = db.query("SELECT id, status, item_count, signal_ids, received_at FROM push_batches ORDER BY id")
+ assert len(batch) == 2
+ assert all(b["status"] == "success" and b["item_count"] == 2 for b in batch)
+ assert all(b["received_at"] is None for b in batch) # 未回执前为空
+ st = db.query("SELECT push_status, COUNT(*) c FROM notifications GROUP BY push_status")
+ status = {r["push_status"]: r["c"] for r in st}
+ assert status.get("success") == 4 # 1、2 号用户各 2 条
+ assert status.get("pending") == 2 # 3 号用户无设备,保持 pending
+
+
+def test_failure_is_recorded_not_retried(seeded, monkeypatch):
+ from app import db
+ from app.services import dispatch
+
+ db.execute("UPDATE notifications SET push_status='pending'")
+ db.execute("DELETE FROM push_batches")
+ db.execute("DELETE FROM push_log")
+ monkeypatch.setattr(
+ "app.notify.push.send_round_push", lambda items, rids, batch: ("failed", "HTTP 500: boom"),
+ )
+ dispatch.push_pending()
+ rows = db.query("SELECT status, error FROM push_batches")
+ assert len(rows) == 2 and all(r["status"] == "failed" and "boom" in r["error"] for r in rows)
+ logs = db.query("SELECT status, error FROM push_log")
+ assert logs and all(r["status"] == "failed" and r["error"] for r in logs)
+ # 失败不重试:再跑一轮,pending 已清零,不应产生新批次
+ n_before = len(db.query("SELECT id FROM push_batches"))
+ dispatch.push_pending()
+ assert len(db.query("SELECT id FROM push_batches")) == n_before
\ No newline at end of file