From ff80c31b044978b95352df63a322a7fb1d528d35 Mon Sep 17 00:00:00 2001
From: NekoYume517 <3146527494@qq.com>
Date: Sun, 15 Nov 2026 17:25:07 +0800
Subject: [PATCH] =?UTF-8?q?fix(P0-P2):=20=E8=87=AA=E5=8A=A8=E8=BF=98?=
=?UTF-8?q?=E8=BD=A6=E4=B8=8D=E5=86=8D=E6=B0=B8=E4=B9=85=E4=B8=A2=E5=A4=B1?=
=?UTF-8?q?=20+=20=E8=BF=98=E8=BD=A6=E6=B0=B8=E4=B8=8D=E6=8B=A6=E4=BA=BA?=
=?UTF-8?q?=20+=20=E8=AE=A2=E9=98=85=E8=B0=83=E5=BA=A6=E8=A1=A5=E5=8F=91?=
=?UTF-8?q?=20+=20=E5=91=8A=E8=AD=A6=E5=8E=BB=E9=87=8D=E4=BF=AE=E6=AD=A3?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
## P0:多花钱 / 静默失效
- 重启跨过 end_time 的单子:restore_active_timers 改为捞全部 expired=0,
已过期的直接进后台补一次 auto_return_bike;巡检 _check_user_order 发现
end_time 已过也补还车(返回 recovered=True),不再无脑 return
- 删除死代码 _cleanup_stale_rentals(只标记本地、不调上游,接了反而更危险)
- notified_0 改为「还车成功后才置位」:失败保留未置位,30 秒 × 6 次短重试,
避免上游三次失败后这单永远不再重试、在上游继续计费
- 自动开锁半成品订单:/record/order 成功但 /record/qrOrder 失败时,
用 /record/return 或 /record/orderClose 撤销,避免重试叠加多张订单
## P1:承诺兑现
- 订阅调度改固定节拍(单调时钟对齐,不再「干完再睡 30 秒」漂移);
查询条件 minute_of_day <= 当前分钟 + last_fired_on != 今天,
整分钟漏掉也能当天补发;fire_rule 改为独立线程并发,避免拖过一分钟
- 订阅判定前先实时刷新地图(用户凭据 → type=3/1),503 先重试一次,
失败才回退快照
- 手动还车改为「先发原坐标,失败换候选点重试」:上游 parkeArea →
全局快照 → campus_locations(kind=parking),最多三个点;位置不再当准入条件
- 还车留痕:raw_latitude/raw_longitude 单独保存用户上报位置
- 告警去重:user-alive 的 target 加入 token_id 指纹(重新配置凭据会自动重新武装);
expired 一级单独放行一封,不再「1 天那封被划掉就永远静默」
## P2:体验 / 文案
- 删掉「打开一次微信小程序就会使网页凭据失效」的错误说法;
token_invalid 文案改为「凭据需要更新(上游判定已失效/已过期)」
- 到期前 60 秒:页面可见时震动一次 + 横幅整条变红 + 「再骑 N 秒就到期 · 超时要加钱」
- 加轮确认写明「消耗 1 次优惠卡次数」;扫码查到但地图上没标记时补一个高亮 marker;
吸附话术改为「不在停车区也没关系,已替你记到最近的还车点」
- 管理员订单表增加「已骑行」列(开始 → 实际还车/现在)
## 顺手修的
- share.js: /api/share/active 返回非数组时 forEach 抛错并每秒刷屏,
改为 Array.isArray 兜底(浏览器实测 JS 异常从每秒一条降为 0)
测试:145 pytest(含新增 timer 补还车/重试 3 条、订阅补发与撤销 3 条、
管理员分钟数 3 条)+ 32 node 全绿
---
alerts.py | 19 ++-
routes/admin.py | 23 +++
routes/rental.py | 148 +++++++++++++++++++-
static/css/map.css | 11 ++
static/js/map.js | 215 ++++++++++++++++++++++++++++-
static/js/share.js | 4 +-
subscribe.py | 118 ++++++++++++++--
templates/admin.html | 6 +-
tests/test_admin_riding_minutes.py | 28 ++++
tests/test_order_return.cjs | 26 ++++
tests/test_order_sync.py | 139 +++++++++++++++++--
tests/test_subscribe_flow.py | 139 +++++++++++++++++++
timer.py | 186 ++++++++++++++++++-------
wechat.py | 8 +-
14 files changed, 976 insertions(+), 94 deletions(-)
create mode 100644 tests/test_admin_riding_minutes.py
create mode 100644 tests/test_subscribe_flow.py
diff --git a/alerts.py b/alerts.py
index d4e347b..8ce65a4 100644
--- a/alerts.py
+++ b/alerts.py
@@ -13,6 +13,7 @@
用户重新登录拿到新 JWT 后自动重新武装告警。
"""
import datetime as dt
+import hashlib
import html
import json
import threading
@@ -69,8 +70,16 @@ def _now_bj_str():
def _sent_already(conn, target, level=None):
- """该凭据是否已发过提醒邮件(level 仅保留兼容签名,不再参与过滤)。"""
+ """该凭据是否已发过这一级别的提醒邮件。
+
+ 免打扰口径:同一凭据(target 里带凭据指纹/过期时间)在 1天/1小时 之间只发一封,
+ 但 **expired 单独放行一封** —— 否则“还剩 1 天”那封被划掉就再也没有第二次机会。
+ """
try:
+ if level == "expired":
+ return conn.execute(
+ "SELECT 1 FROM credential_alerts WHERE target = ? AND level = 'expired' LIMIT 1",
+ (target,)).fetchone() is not None
return conn.execute(
"SELECT 1 FROM credential_alerts WHERE target = ? LIMIT 1",
(target,)).fetchone() is not None
@@ -121,7 +130,7 @@ def _send_alert(recipients, level, owner_desc, expiry):
# 未填 AccessToken 的凭据:通过上游探测发现已失效,无法给出过期时刻
lead = ("凭据已失效(探测到上游已拒绝该 Token),该账号的开锁/还车/地图数据"
"已不可用,请立即在小程序重新登录并更新凭据。"
- "提示:打开一次微信小程序就会使网页凭据失效。")
+ "提示:重新登录小程序会顶掉旧会话,请把新凭据更新到本页覆盖旧的。")
elif level == "expired":
lead = "凭据已过期,该账号的上游接口(地图/开锁/还车/订单检测)已全部失效,请立即在小程序重新登录并更新凭据。"
elif level == "1hour":
@@ -202,7 +211,11 @@ def check_user_credentials_alive():
" AND (access_token IS NULL OR access_token = '')").fetchall()
admin_emails = set(get_alert_emails())
for u in users:
- target = f"user-alive:{u['id']}"
+ # target 里揉进凭据指纹:用户重新配置 token_id 后会自动重新武装。
+ # 原来只写 user-alive:{id},一个用户历史上失效过一次、发过一封之后,
+ # 以后每次失效都被永久静音(注释里那句“重新配置会重新武装”并不成立)。
+ fp = hashlib.sha1(str(u["token_id"]).encode("utf-8")).hexdigest()[:8]
+ target = f"user-alive:{u['id']}:{fp}"
if _sent_already(conn, target, "expired"):
continue
try:
diff --git a/routes/admin.py b/routes/admin.py
index 3dcb9b4..d8385fc 100644
--- a/routes/admin.py
+++ b/routes/admin.py
@@ -1,6 +1,7 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""管理后台路由"""
+import datetime as dt
import json
import random
from functools import wraps
@@ -172,6 +173,27 @@ def admin_api_summary():
}})
+def _riding_minutes(rental) -> int:
+ """已骑行分钟:开始时间 → 实际还车时间(未还车就按「现在」算)。"""
+ start = rental.get("start_time")
+ if not start:
+ return 0
+ try:
+ start_at = dt.datetime.strptime(str(start), "%Y-%m-%d %H:%M:%S")
+ except (TypeError, ValueError):
+ return 0
+ end_at = None
+ if rental.get("returned_at"):
+ try:
+ end_at = dt.datetime.strptime(str(rental["returned_at"]), "%Y-%m-%d %H:%M:%S")
+ except (TypeError, ValueError):
+ end_at = None
+ if end_at is None:
+ tz = dt.timezone(dt.timedelta(hours=8))
+ end_at = dt.datetime.now(tz).replace(tzinfo=None)
+ return max(0, int((end_at - start_at).total_seconds() // 60))
+
+
@bp.route("/api/admin/rentals")
@admin_required
def admin_api_rentals():
@@ -199,6 +221,7 @@ def admin_api_rentals():
"end_latitude": r.get("end_latitude"),
"end_longitude": r.get("end_longitude"),
"returned_at": r.get("returned_at"),
+ "riding_minutes": _riding_minutes(r),
})
return jsonify({"rtn_code": 0, "data": result})
diff --git a/routes/rental.py b/routes/rental.py
index 21a2ad0..8962dff 100644
--- a/routes/rental.py
+++ b/routes/rental.py
@@ -207,6 +207,105 @@ def _snap_to_park_area(lat: float, lng: float, user_id=None):
return resolved
+def _approx_m(lat1, lng1, lat2, lng2) -> float:
+ """两点近似距离(米),只用来做候选点去重,不需要高精度。"""
+ dx = (lng1 - lng2) * 111320.0 * math.cos(math.radians(lat1))
+ dy = (lat1 - lat2) * 110540.0
+ return math.hypot(dx, dy)
+
+
+def _campus_parking_points(lat, lng, limit=2):
+ """校园停车点表(`campus_locations.kind='parking'`)—— 不依赖上游的保底候选。
+
+ 上游 parkeArea 与全局快照同时失效时(全站地图空白那种状态),
+ 这份自己在地图上点出来的坐标仍然可用。
+ """
+ conn = None
+ try:
+ conn = get_db()
+ rows = conn.execute(
+ "SELECT name, latitude, longitude FROM campus_locations WHERE kind = 'parking'"
+ ).fetchall()
+ except Exception as exc:
+ print(f"[还车位置] 读取校园停车点失败: {exc}")
+ return []
+ finally:
+ if conn is not None:
+ conn.close()
+ scored = []
+ for row in rows:
+ try:
+ plat, plng = float(row["latitude"]), float(row["longitude"])
+ except (TypeError, ValueError):
+ continue
+ scored.append((_approx_m(lat, lng, plat, plng), plat, plng, row["name"]))
+ scored.sort(key=lambda x: x[0])
+ return [(p[1], p[2], p[3] or "校园停车点") for p in scored[:limit]]
+
+
+def _return_candidates(lat: float, lng: float, user_id=None, area_limit=2):
+ """还车候选坐标(GCJ02),按「先原坐标、再近处合法点」的顺序。
+
+ 设计口径:**位置只是修坐标的手段,不是还车的前置条件**。
+ 上游 parkeArea → 全局快照 → 校园停车点表,三级逐级兜底。
+ """
+ candidates = [(lat, lng, "你上报的位置")]
+
+ areas = _park_areas(user_id)
+ scored = []
+ for area in areas:
+ boundary = park_area.closest_boundary_point(lat, lng, area.get("points") or [])
+ if boundary:
+ scored.append((boundary["distance"], area))
+ scored.sort(key=lambda x: x[0])
+ for _, area in scored[:area_limit]:
+ resolved = park_area.resolve_return_coord(lat, lng, [area])
+ if resolved:
+ candidates.append((resolved["latitude"], resolved["longitude"],
+ "附近停车区"))
+
+ for plat, plng, name in _campus_parking_points(lat, lng):
+ candidates.append((plat, plng, name))
+
+ return _distinct_points(candidates)
+
+
+def _distinct_points(points, min_gap_m=12.0):
+ """去掉彼此太近的候选点,避免对着同一个位置重复试。"""
+ out = []
+ for p in points:
+ if all(_approx_m(p[0], p[1], q[0], q[1]) >= min_gap_m for q in out):
+ out.append(p)
+ return out
+
+
+def _try_return_candidates(user_id, order_id, code, lat, lng):
+ """按候选点依次调 `/record/return`,返回 (结果, 用到的点, 试过的次数)。
+
+ 「先发原坐标」是刻意的:大多数还车一次就成,不该为了判定先多打两次上游接口。
+ 只有真的失败了才换下一个候选点。
+ """
+ tried = []
+ last_result = None
+ for plat, plng, label in _return_candidates(lat, lng, user_id):
+ tried.append(label)
+ result = request_with_user_auth(
+ user_id, "POST", "/record/return",
+ data={"order_id": order_id, "longitude": plng, "latitude": plat, "code": code}
+ )
+ last_result = result
+ if result.get("rtn_code") == 0:
+ if len(tried) > 1:
+ print(f"[还车位置] 第 {len(tried)} 个候选点成功({label})")
+ return result, (plat, plng), tried
+ # 「订单信息不存在」换坐标也没用,直接收工
+ if (result.get("rtn_code") == 204010
+ or "订单信息不存在" in str(result.get("message") or "")):
+ return result, (plat, plng), tried
+ print(f"[还车位置] 候选点 {label} 失败: {result.get('message')}")
+ return last_result or {"rtn_code": 500, "message": "没有可用坐标"}, (lat, lng), tried
+
+
def _legacy_nearest_bike_point(lat: float, lng: float, user_id=None) -> dict:
"""旧兜底:拿最近的一辆 type=1 共享单车当停车点。只在没有 parkeArea 时用。
@@ -418,6 +517,39 @@ def _set_rental_finished(conn, where_sql, where_params, latitude, longitude):
conn.execute(sql, params)
+def _record_raw_coords(order_id: str, user_id: int, latitude, longitude):
+ """单独留存用户「当时真实上报」的坐标(吸附/换点之后的点会失真)。
+
+ 以后要做「车到底停在哪」的分析时,end_latitude/end_longitude 是判定用点,
+ raw_latitude/raw_longitude 才是现场位置。缺列时自动补。
+ """
+ try:
+ lat, lng = float(latitude), float(longitude)
+ except (TypeError, ValueError):
+ return
+ sql = """
+ UPDATE rentals SET raw_latitude = ?, raw_longitude = ?
+ WHERE order_id = ? AND user_id = ?
+ """
+ params = (lat, lng, str(order_id), user_id)
+ conn = get_db()
+ try:
+ try:
+ conn.execute(sql, params)
+ except Exception as e:
+ if "no such column" not in str(e).lower():
+ raise
+ for col, decl in (("raw_latitude", "REAL"), ("raw_longitude", "REAL")):
+ try:
+ conn.execute(f"ALTER TABLE rentals ADD COLUMN {col} {decl}")
+ except Exception:
+ pass
+ conn.execute(sql, params)
+ conn.commit()
+ finally:
+ conn.close()
+
+
def _record_rental_end(order_id: str, user_id: int, latitude, longitude):
"""标记订单结束:实际还车时间 + 终点坐标与位置标签。"""
conn = get_db()
@@ -673,14 +805,14 @@ def order_return():
user_name = get_user_display_name(user["id"])
print(f"[操作日志] 手动还车: order_id={order_id}, code={data.get('code','')}, lat={latitude}, lng={longitude}, user={user_name}")
- latitude, longitude, use_nearest = _resolve_order_location(
- user["id"], data.get("code", ""), latitude, longitude
- )
-
- return_result = request_with_user_auth(
- user["id"], "POST", "/record/return",
- data={"order_id": order_id, "longitude": longitude, "latitude": latitude}
+ # 位置只用来「修坐标」,不再当还车的前置条件:
+ # 先拿你上报的坐标直接发,失败了再换最近的合法点,最多试几个候选点。
+ raw_lat, raw_lng = to_upstream_coords(latitude, longitude)
+ return_result, used_point, tried_labels = _try_return_candidates(
+ user["id"], order_id, data.get("code", ""), raw_lat, raw_lng
)
+ latitude, longitude = used_point
+ use_nearest = len(tried_labels) > 1
confirmed_by_status = False
# 「订单信息不存在」(实测 204010) 不能当成功:本来就没有这张单,
@@ -709,6 +841,8 @@ def order_return():
conn.close()
# 统一回填:expired=1 + 实际还车时间 + 终点坐标/位置标签
_record_rental_end(order_id, user["id"], latitude, longitude)
+ # 你当时真实上报的位置单独留一份(吸附后的点会失真,做分析要用原始值)
+ _record_raw_coords(order_id, user["id"], raw_lat, raw_lng)
for rental_id in rental_ids:
_cancel_rental_timers(rental_id)
_user_info_cache.pop(user["id"], None)
diff --git a/static/css/map.css b/static/css/map.css
index 2e028a6..0de836d 100644
--- a/static/css/map.css
+++ b/static/css/map.css
@@ -2885,3 +2885,14 @@
.bike-card.compact-actions .bike-card-find-btn .btn-label { display: none; }
.bike-card.compact-actions .bike-card-find-btn { padding: 7px; border-radius: 11px; }
.bike-card.compact-actions .bike-card-header { gap: 6px; }
+
+/* 订单横幅:进入「即将到期」状态时整条变红,兜里也能看见 */
+.order-banner.expiring {
+ background: linear-gradient(135deg, #B3261E, #8E1B15) !important;
+ border-color: rgba(255, 120, 110, .55) !important;
+ animation: order-expiring-pulse 1.6s ease-in-out infinite;
+}
+@keyframes order-expiring-pulse {
+ 0%, 100% { box-shadow: 0 6px 18px rgba(179, 38, 30, .35); }
+ 50% { box-shadow: 0 6px 26px rgba(179, 38, 30, .65); }
+}
diff --git a/static/js/map.js b/static/js/map.js
index a4e1813..08693d4 100644
--- a/static/js/map.js
+++ b/static/js/map.js
@@ -1844,20 +1844,51 @@
}
}
+ // 到期提醒:手机在兜里时页面横幅看不见,这里补一次震动 + 明确文案。
+ // 只在跨过阈值的瞬间触发,不会每秒抖。
+ let _orderLastAlertAt = 0;
+ function _alertOrderExpiring(remaining) {
+ const banner = document.getElementById("order-banner");
+ if (banner) banner.classList.add("expiring");
+ const el = document.getElementById("order-countdown");
+ if (el) el.textContent = `再骑 ${Math.max(0, remaining)} 秒就到期 · 超时要加钱`;
+ const now = Date.now();
+ if (now - _orderLastAlertAt < 25000) return; // 25 秒内只提醒一次
+ _orderLastAlertAt = now;
+ try {
+ if (navigator.vibrate) navigator.vibrate([200, 100, 200]);
+ } catch (e) { /* 不支持就算了 */ }
+ if (document.visibilityState === "visible") {
+ showToast("还有不到 1 分钟到期,就近停车还车");
+ }
+ }
+ let _orderAlerted = false;
+
function updateOrderCountdownText() {
const el = document.getElementById("order-countdown");
const remaining = Math.max(0, orderCountdownSeconds);
const mins = Math.floor(remaining / 60);
const secs = remaining % 60;
- el.textContent = remaining > 0 ? `本轮剩余 ${mins}:${secs.toString().padStart(2, "0")}` : "本轮到期 · 同步状态中";
-
+
+ if (remaining > 0 && remaining <= 60) {
+ _alertOrderExpiring(remaining); // 内部会写文案/变色/震动
+ } else {
+ el.textContent = remaining > 0
+ ? `本轮剩余 ${mins}:${secs.toString().padStart(2, "0")}`
+ : "本轮到期 · 同步状态中";
+ }
+
// 变色提示
+ const banner = document.getElementById("order-banner");
if (remaining <= 60) {
el.style.color = "#ff3b30";
+ if (banner) banner.classList.add("expiring");
} else if (remaining <= 300) {
el.style.color = "#ffcc00";
+ if (banner) banner.classList.remove("expiring");
} else {
el.style.color = "white";
+ if (banner) banner.classList.remove("expiring");
}
}
@@ -2181,7 +2212,9 @@
const data = await resp.json();
if (data.rtn_code === 0) {
- let msg = data.used_nearest ? "还车成功(已切换至最近停车点)" : "还车成功";
+ let msg = data.used_nearest
+ ? "还车成功 · 不在停车区也没关系,已替你记到最近的还车点"
+ : "还车成功";
// 显示月卡支付结果
if (data.card_pay) {
msg += data.card_pay.success ? `,${data.card_pay.message}` : `,${data.card_pay.message}`;
@@ -2235,7 +2268,9 @@
});
const data = await resp.json();
if (data.rtn_code === 0) {
- showToast(data.used_nearest ? "临时锁车成功(已切换至最近停车点)" : "临时锁车成功");
+ showToast(data.used_nearest
+ ? "临时锁车成功 · 已替你记到最近的还车点"
+ : "临时锁车成功");
const status = document.getElementById("order-actions-status");
if (status) status.textContent = "车辆已临时锁定,订单仍在进行中";
} else {
@@ -2890,6 +2925,7 @@
const text = document.getElementById("add-round-text");
if (text) {
text.innerHTML =
+ `加 1 轮会消耗 1 次优惠卡次数(没有卡就按单次计费)。
` +
`当前这一轮还剩约 ${mins} 分钟,不会延长。
` +
`到点后系统会自动:还车 → 用优惠卡支付 → 立刻重新开锁同一辆车,进入下一轮。`;
}
@@ -3458,8 +3494,177 @@
const code = document.getElementById("scan-input").value.trim();
if (!code) { showToast("请输入车牌号"); return; }
- // 订阅提醒已拆到 static/js/subscribe.js
+ showToast("正在查询...");
+ fetch("/api/bicycle", {
+ method: "POST",
+ headers: { "Content-Type": "application/json", "Authorization": `Bearer ${authToken}` },
+ body: JSON.stringify({ code })
+ })
+ .then(r => r.json())
+ .then(data => {
+ const codeNum = parseInt(code);
+ if (data.rtn_code === 401) { showLoginGate(); return; }
+ // 成功查询:正常处理
+ if (data.rtn_code === 0 && data.data) {
+ const bike = data.data;
+ bike.code = code;
+
+ // 优先用 markersData 的实时位置,其次用 API 返回的位置
+ const mapBike = markersData[codeNum] || markersData[code];
+ let hasLocation = false;
+
+ if (mapBike && mapBike.latitude && mapBike.longitude) {
+ bike.latitude = mapBike.latitude;
+ bike.longitude = mapBike.longitude;
+ bike.state = mapBike.state;
+ bike.electric_quantity = mapBike.electric_quantity;
+ hasLocation = true;
+ } else if (bike.latitude && bike.longitude) {
+ hasLocation = true;
+ }
+
+ if (hasLocation) {
+ const c = offsetCoord(bike.latitude, bike.longitude);
+ map.panTo(new BMapGL.Point(c.lng, c.lat));
+ setTimeout(() => map.setZoom(map.getZoom() + 1), 300);
+ } else {
+ showToast("该车暂无实时位置,请在地图上查看");
+ }
+
+ // 如果车辆在使用中,额外提示
+ if (bike.state === 1 && bike.status === 1) {
+ showToast("该车正在使用中");
+ }
+
+ markersData[codeNum] = bike;
+
+ // 地图上可能还没有这辆车(已被骑走 / 不在当前车型里):
+ // 补一个高亮标记,否则「查到了但地图上什么都没有」
+ if (hasLocation && !currentMarkersById[codeNum]) {
+ try {
+ const c = offsetCoord(bike.latitude, bike.longitude);
+ const marker = new BMapGL.Marker(
+ new BMapGL.Point(c.lng, c.lat),
+ { icon: getBikeIcon(bike, true) }
+ );
+ map.addOverlay(marker);
+ currentMarkers.push(marker);
+ currentMarkersById[codeNum] = marker;
+ bindMarkerTap(marker, codeNum);
+ } catch (e) {
+ console.warn("[扫码] 补标记失败:", e);
+ }
+ }
+
+ showBikeDetail(codeNum);
+ }
+ // success=false 时,也尝试用 markersData 显示详情和定位
+ else if (data.success === false) {
+ const mapBike = markersData[codeNum] || markersData[code];
+ if (mapBike && mapBike.latitude && mapBike.longitude) {
+ // 跳转并放大
+ const c = offsetCoord(mapBike.latitude, mapBike.longitude);
+ map.panTo(new BMapGL.Point(c.lng, c.lat));
+ setTimeout(() => map.setZoom(map.getZoom() + 1), 300);
+ // 弹详情窗口
+ mapBike.code = code;
+ markersData[codeNum] = mapBike;
+ showBikeDetail(codeNum);
+ // toast 提示
+ showToast(data.message || "该车辆已被使用");
+ } else {
+ showToast(data.message || "查询失败");
+ }
+ }
+ else {
+ showToast(data.message || "查询失败");
+ }
+ })
+ .catch(err => showToast("请求失败: " + friendlyError(err)));
+ }
+
+ // ========== 寻车功能 ==========
+
+ // ----- 丢失模式状态 -----
+ let _lostModeActive = false; // 是否处于丢失模式
+ let _lostModeTimer = null; // setInterval 句柄
+ let _findClickCount = 0; // 连续点击次数计数
+ let _findClickTimer = null; // 连续点击重置计时器
+ let _findLongPressTimer = null; // 长按计时器
+ const LOST_TRIGGER_CLICKS = 3; // 连续点击 N 次触发
+ const LOST_TRIGGER_LONG = 700; // 长按毫秒数触发
+ const LOST_INTERVAL = 3000; // 丢失模式下每次寻车间隔(ms)
+
+ /** 发送单次寻车请求(内部使用,不操作按钮状态) */
+ function _doFindBikeRequest(code) {
+ return fetch("/api/find_bike", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ "Authorization": `Bearer ${authToken}`
+ },
+ body: JSON.stringify({ code: code, school_id: 10 })
+ }).then(r => r.json()).catch(() => null);
+ }
+
+ /** 打开丢失模式确认弹窗 */
+ function showLostModal() {
+ document.getElementById("lost-modal").classList.add("show");
+ }
+
+ /** 关闭丢失模式确认弹窗(不启用) */
+ function closeLostModal() {
+ document.getElementById("lost-modal").classList.remove("show");
+ }
+
+ /** 启用丢失模式(弹窗确认后调用) */
+ function enableLostMode() {
+ closeLostModal();
+ if (!selectedBike) return;
+ _lostModeActive = true;
+
+ const btn = document.getElementById("bike-find-btn-header");
+ const span = btn.querySelector("span");
+ btn.classList.add("lost-mode");
+ btn.title = "丢失模式(点击退出)";
+ if (span) span.textContent = "丢失模式";
+
+ showToast("丢失模式已开启,持续帮你寻车");
+
+ // 立即发一次
+ _doFindBikeRequest(selectedBike.code);
+
+ // 持续循环
+ _lostModeTimer = setInterval(() => {
+ if (!_lostModeActive || !selectedBike) {
+ disableLostMode();
+ return;
+ }
+ _doFindBikeRequest(selectedBike.code);
+ }, LOST_INTERVAL);
+
+ // 页面隐藏或关闭时自动停止
+ window.addEventListener("beforeunload", _onPageUnload);
+ document.addEventListener("visibilitychange", _onVisibilityChange);
+ }
+
+ /** 停止丢失模式 */
+ function disableLostMode() {
+ if (!_lostModeActive) return;
+ _lostModeActive = false;
+ clearInterval(_lostModeTimer);
+ _lostModeTimer = null;
+ _findClickCount = 0;
+
+ const btn = document.getElementById("bike-find-btn-header");
+ const span = btn.querySelector("span");
+ if (btn) {
+ btn.classList.remove("lost-mode");
+ btn.disabled = false;
+ btn.title = "寻车";
+ }
+ if (span) span.textContent = "寻车";
window.removeEventListener("beforeunload", _onPageUnload);
document.removeEventListener("visibilitychange", _onVisibilityChange);
diff --git a/static/js/share.js b/static/js/share.js
index c3a3915..53354fb 100644
--- a/static/js/share.js
+++ b/static/js/share.js
@@ -250,7 +250,8 @@
try {
const data = await shareApi("/api/share/active");
if (data.rtn_code !== 0) return;
- shareActiveList = data.data || [];
+ // 接口异常时 data.data 可能是对象/字符串,不是数组 → forEach 会抛错并每秒刷屏
+ shareActiveList = Array.isArray(data.data) ? data.data : [];
shareActiveList.forEach(it => { it._countdownDeadline = performance.now() + Math.max(0, Number(it.remaining_seconds) || 0) * 1000; });
let html = "";
shareActiveList.forEach((it, idx) => {
@@ -289,6 +290,7 @@
document.getElementById("share-return-modal").classList.add("show");
}
function updateShareCountdowns() {
+ if (!Array.isArray(shareActiveList)) return; // 接口异常时不刷屏
shareActiveList.forEach((it, idx) => {
const el = document.getElementById('share-countdown-' + idx);
if (!el) return;
diff --git a/subscribe.py b/subscribe.py
index 4418fcc..72c4255 100644
--- a/subscribe.py
+++ b/subscribe.py
@@ -184,7 +184,48 @@ def latest_bike_points():
return [dict(r) for r in rows]
-def stat_location(loc):
+def refresh_bike_points(user_id=None):
+ """判定前实时拉一次地图,别拿几十秒前的快照或库里的旧点数车。
+
+ 拿不到就返回 None,调用方退回 `latest_bike_points()`。
+ 上游偶发 503 时先重试一次再放弃,免得一次抖动就退回旧快照。
+ """
+ from wechat import request_with_user_auth, request_api
+ rows = []
+ for btype in ("3", "1"):
+ res = None
+ for attempt in range(2):
+ try:
+ if user_id:
+ res = request_with_user_auth(user_id, "GET", "/project/map",
+ params={"type": btype}, _silent=True)
+ else:
+ res = request_api("GET", "/project/map", params={"type": btype})
+ except Exception as exc:
+ print(f"[订阅提醒] 刷新地图失败(type={btype}): {exc}")
+ res = None
+ if isinstance(res, dict) and res.get("rtn_code") == 0:
+ break
+ if attempt == 0:
+ time.sleep(0.6) # 上游 503/抖动:等半秒再试一次
+ if not isinstance(res, dict) or res.get("rtn_code") != 0:
+ continue
+ for st in ((res.get("data") or {}).get("bicycleStation") or []):
+ lat, lng = st.get("latitude"), st.get("longitude")
+ if lat is None or lng is None:
+ continue
+ rows.append({
+ "bike_code": str(st.get("code") or ""),
+ "latitude": lat,
+ "longitude": lng,
+ "state": st.get("state"),
+ "status": st.get("status"),
+ "electric": st.get("electric"),
+ })
+ return rows or None
+
+
+def stat_location(loc, user_id=None, fresh=True):
"""统计某个停车点附近的车辆。返回 None 表示该地点没有可用判定(缺坐标)。"""
if loc is None:
return None
@@ -193,7 +234,11 @@ def stat_location(loc):
return None
except Exception:
return None
- points = latest_bike_points()
+ points = None
+ if fresh:
+ points = refresh_bike_points(user_id)
+ if not points:
+ points = latest_bike_points()
return bikes_near_parking(points, loc)
@@ -231,6 +276,31 @@ def _live_coord(user_id: int, code: str, btype=None):
return None
+def _discard_pending_order(user_id: int, order_id, code: str,
+ lat=None, lng=None) -> bool:
+ """下单成功但开锁失败:把这张半成品订单关掉。
+
+ 不清理的话,下一次重试会再叠一张新订单 —— 上游会同时挂着几张
+ 没人骑的订单,用户还可能被算未支付。
+ """
+ from wechat import request_with_user_auth
+ data = {"order_id": order_id}
+ if lat is not None and lng is not None:
+ data.update({"latitude": lat, "longitude": lng, "code": code})
+ for path in ("/record/return", "/record/orderClose"):
+ try:
+ res = request_with_user_auth(user_id, "POST", path, data=data, _silent=True)
+ except Exception as exc:
+ print(f"[订阅开锁] 清理半成品订单 {order_id} 调 {path} 异常: {exc}")
+ continue
+ if isinstance(res, dict) and res.get("rtn_code") == 0:
+ print(f"[订阅开锁] 半成品订单 {order_id} 已通过 {path} 关闭")
+ return True
+ msg = (res or {}).get("message") if isinstance(res, dict) else None
+ print(f"[订阅开锁] 清理半成品订单 {order_id} 失败({path}): {msg}")
+ return False
+
+
def _try_auto_unlock(user_id: int, bike_code: str) -> dict:
"""真实自动开锁:扫码 → 创建订单 → 开锁(全部使用订阅人自己的凭据)。
@@ -300,8 +370,15 @@ def _try_auto_unlock(user_id: int, bike_code: str) -> dict:
opened = request_with_user_auth(user_id, "POST", "/record/qrOrder",
data={"order_id": order_id}, _silent=True)
if opened.get("rtn_code") != 0:
+ # 半成品订单必须撤销,否则下一次重试会再叠一张
+ cleaned = _discard_pending_order(user_id, order_id, code, lat, lng)
+ msg = opened.get("message") or "开锁指令失败"
+ if cleaned:
+ msg += "(已撤销本次下单)"
+ else:
+ msg += "(本次下单可能残留在上游,请稍后在订单页检查)"
return {"success": False, "occupied": False, "order_id": str(order_id),
- "message": opened.get("message") or "开锁指令失败"}
+ "message": msg}
# 4) 本地落单 + 计时器 + 起点位置(与手动开锁一致,source='subscribe')
try:
@@ -426,7 +503,8 @@ def fire_rule(rule: dict):
return False
flt = rule_filters(rule)
- points = latest_bike_points()
+ # 先刷新地图再看有几辆:订阅最怕“看到的是别人已经骑走的数据”
+ points = refresh_bike_points(rule.get("user_id")) or latest_bike_points()
stat = bikes_near_parking(points, loc)
# 候选:只含「符合车型/电量筛选」的空闲可用车,已按排序规则排好
candidates = parking_candidates(
@@ -503,12 +581,31 @@ def fire_rule(rule: dict):
# ========== 调度 ==========
def _scheduler_loop():
+ """固定节拍扫描:按单调时钟对齐,不用「干完活再睡 30 秒」,
+ 否则发信/自动开锁一慢,节拍就整体漂移。"""
+ next_at = time.monotonic()
while True:
try:
_tick()
except Exception as e:
print(f"[订阅提醒] 调度异常: {e}")
- time.sleep(CHECK_INTERVAL)
+ next_at += CHECK_INTERVAL
+ delay = next_at - time.monotonic()
+ if delay <= 0:
+ # 落后太多(比如机器卡了一下)就重新对齐,不追帧
+ next_at = time.monotonic() + CHECK_INTERVAL
+ continue
+ time.sleep(delay)
+
+
+def _fire_rule_async(rule: dict):
+ """单条规则在独立线程里执行,避免串行 fire 把整轮节拍拖过一分钟。"""
+ try:
+ ok = fire_rule(rule)
+ except Exception as e:
+ ok = False
+ print(f"[订阅提醒] 规则 {rule['id']} 发送失败: {e}")
+ print(f"[订阅提醒] 规则 {rule['id']} 已触发 (user={rule.get('user_id')}, 发送={ok})")
def _tick():
@@ -519,9 +616,11 @@ def _tick():
minute_of_day = now.hour * 60 + now.minute
conn = get_db()
+ # `<=` 而不是 `=`:只要今天还没发过,到点或过点都补一次。
+ # 用 `=` 的时候,一轮跑超过一分钟就会漏掉那一分钟,当天不再补。
rules = conn.execute("""
SELECT * FROM subscribe_rules
- WHERE enabled = 1 AND weekday IN (0, ?) AND minute_of_day = ?
+ WHERE enabled = 1 AND weekday IN (0, ?) AND minute_of_day <= ?
AND last_fired_on != ?
""", (weekday, minute_of_day, today)).fetchall()
if not rules:
@@ -537,12 +636,7 @@ def _tick():
rule = dict(r)
if not rule.get("notify_enabled") and not rule.get("auto_unlock"):
continue
- try:
- ok = fire_rule(rule)
- except Exception as e:
- ok = False
- print(f"[订阅提醒] 规则 {rule['id']} 发送失败: {e}")
- print(f"[订阅提醒] 规则 {rule['id']} 已触发 (user={rule['user_id']}, 发送={ok})")
+ threading.Thread(target=_fire_rule_async, args=(rule,), daemon=True).start()
def start_subscribe_scheduler():
diff --git a/templates/admin.html b/templates/admin.html
index b330d29..959eba6 100644
--- a/templates/admin.html
+++ b/templates/admin.html
@@ -471,11 +471,13 @@ function renderOrders(){
};
const rows=list.map(r=>`
| ${r.id} | ${esc(r.order_id||'-')} | #${esc(r.bike_code)} |
- ${userCell(r)} | ${routeCell(r)} | ${sourceCell(r)} |
+ ${userCell(r)} | ${routeCell(r)} |
+ ${r.riding_minutes!=null ? esc(r.riding_minutes)+' 分钟' : '-'} |
+ ${sourceCell(r)} |
${esc((r.start_time||'').replace('T',' '))} | ${esc((r.end_time||'').replace('T',' '))} |
${badgeFor(r.status)} |
${(r.status==='进行中'||r.status==='已超时')?``:'-'} |
`).join('');
- document.getElementById('od-table').innerHTML=`| 本地ID | 订单号 | 车辆 | 用户 | 起点 → 终点 | 来源 | 开始 | 到期 | 状态 | 操作 |
${rows||'| 无 |
'}
`;
+ document.getElementById('od-table').innerHTML=`| 本地ID | 订单号 | 车辆 | 用户 | 起点 → 终点 | 已骑行 | 来源 | 开始 | 预计到期 | 状态 | 操作 |
${rows||'| 无 |
'}
`;
}
let returnTarget=null;
function returnOrder(rentalId){
diff --git a/tests/test_admin_riding_minutes.py b/tests/test_admin_riding_minutes.py
new file mode 100644
index 0000000..9aa6f65
--- /dev/null
+++ b/tests/test_admin_riding_minutes.py
@@ -0,0 +1,28 @@
+# -*- coding: utf-8 -*-
+"""管理员订单列表:已骑行分钟数。"""
+import datetime as dt
+import unittest
+from unittest.mock import patch
+
+from routes import admin as admin_routes
+
+
+class RidingMinutesTests(unittest.TestCase):
+ def test_finished_order_uses_returned_at(self):
+ rental = {"start_time": "2026-01-01 09:00:00",
+ "returned_at": "2026-01-01 09:23:30"}
+ self.assertEqual(23, admin_routes._riding_minutes(rental))
+
+ def test_active_order_uses_now(self):
+ tz = dt.timezone(dt.timedelta(hours=8))
+ start = dt.datetime.now(tz).replace(tzinfo=None) - dt.timedelta(minutes=7)
+ rental = {"start_time": start.strftime("%Y-%m-%d %H:%M:%S"), "returned_at": None}
+ self.assertIn(admin_routes._riding_minutes(rental), (6, 7))
+
+ def test_bad_timestamps_do_not_break_the_list(self):
+ self.assertEqual(0, admin_routes._riding_minutes({"start_time": None}))
+ self.assertEqual(0, admin_routes._riding_minutes({"start_time": "not-a-date"}))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_order_return.cjs b/tests/test_order_return.cjs
index 4663de2..e4bde59 100644
--- a/tests/test_order_return.cjs
+++ b/tests/test_order_return.cjs
@@ -167,6 +167,32 @@ test('countdown accounts for background throttling instead of decrementing only
assert.match(e.element('order-final-time').textContent, /第 1\/1 轮/);
});
+// 回归:拆分模块时曾把「寻车 / 丢失模式 / 车牌查询」整段定义切走,
+// 只剩调用处 → 点按钮直接 ReferenceError。这里钉住关键入口必须存在。
+test('find-bike, plate lookup and lost-mode entry points are all defined', async () => {
+ const e = await environment();
+ const must = ['findBike', '_doFindBikeRequest', 'scanCode',
+ 'showLostModal', 'closeLostModal', 'enableLostMode', 'disableLostMode',
+ '_onPageUnload', '_onVisibilityChange', 'findCurrentOrderBike'];
+ const missing = must.filter(name => vm.runInContext(`typeof ${name}`, e.context) !== 'function');
+ assert.deepEqual(missing, []);
+});
+
+// 回归:寻车必须真的打到 /api/find_bike,而不是被 try/catch 吞掉
+test('findBike posts to the find_bike endpoint and reports success', async () => {
+ const e = await environment();
+ const calls = [];
+ e.context.fetch = async (url, options) => {
+ calls.push({ url: String(url), options });
+ return { json: async () => ({ rtn_code: 0 }) };
+ };
+ vm.runInContext(`selectedBike = { code: '51241' }; _findClickCount = 0; findBike();`, e.context);
+ await new Promise(resolve => setImmediate(resolve));
+ assert.equal(calls.length, 1);
+ assert.match(calls[0].url, /\/api\/find_bike/);
+ assert.match(JSON.stringify(calls[0].options.body), /51241/);
+});
+
// 回归:自己账号开锁成功时,closeUnlockConfirm 会清空 unlockPendingCode,
// 本地 activeRental / localStorage 绝不能把车牌写成 null。
test('self unlock keeps the bike code after the confirm dialog clears the pending code', async () => {
diff --git a/tests/test_order_sync.py b/tests/test_order_sync.py
index 0847c4d..85ee677 100644
--- a/tests/test_order_sync.py
+++ b/tests/test_order_sync.py
@@ -429,17 +429,25 @@ class OrderSyncTests(unittest.TestCase):
app.secret_key = "test"
app.register_blueprint(rental_routes.bp)
client = app.test_client()
- responses = [
- {"rtn_code": 0, "parkNoShow": False},
- {"rtn_code": -1, "message": "response timeout"},
- {"rtn_code": 0, "data": {"nonDealOrder": None}},
- ]
+
+ # 新版还车链路:先发用户坐标,失败才换候选点重试(不再有 checkLocation 预检)。
+ # 这里让 /record/return 一直超时,靠订单状态确认判成功。
+ calls = []
+
+ def fake_auth(user_id, method, path, **kwargs):
+ calls.append(path)
+ if path == "/record/return":
+ return {"rtn_code": -1, "message": "response timeout"}
+ if path == "/user/info":
+ return {"rtn_code": 0, "data": {"nonDealOrder": None}}
+ return {"rtn_code": 0, "data": {}}
+
with patch.object(rental_routes, "get_db", self._get_db), \
patch.object(rental_routes, "get_current_user", return_value={
"id": 7, "email": "rider@example.test"
}), \
patch.object(rental_routes, "get_user_display_name", return_value="骑行人"), \
- patch.object(rental_routes, "request_with_user_auth", side_effect=responses), \
+ patch.object(rental_routes, "request_with_user_auth", side_effect=fake_auth), \
patch.object(rental_routes, "_try_card_pay_auto", return_value={}), \
patch.object(rental_routes, "_cancel_rental_timers"):
response = client.post("/api/order/return", json={
@@ -450,6 +458,8 @@ class OrderSyncTests(unittest.TestCase):
self.assertEqual(0, data["rtn_code"])
self.assertIn("订单状态确认", data["message"])
self.assertEqual(1, self._expired(101))
+ self.assertNotIn("/record/checkLocation", calls) # 位置不再当准入条件
+ self.assertGreaterEqual(calls.count("/record/return"), 1)
def test_manual_timer_finish_requires_owner_and_rejects_real_orders(self):
app = Flask(__name__)
@@ -479,23 +489,27 @@ class OrderSyncTests(unittest.TestCase):
active = {"rtn_code": 0, "data": {"nonDealOrder": {
"order_id": "9001", "status": 2
}}}
- responses = [
- {"rtn_code": 0, "parkNoShow": False},
- {"rtn_code": 500, "message": "return rejected"},
- active, active, active, active,
- ]
+
+ # 所有候选点都被上游拒绝,且订单状态一直是骑行中 → 保持 active,不能假装成功
+ def fake_auth(user_id, method, path, **kwargs):
+ if path == "/record/return":
+ return {"rtn_code": 500, "message": "return rejected"}
+ if path == "/user/info":
+ return active
+ return {"rtn_code": 0, "data": {}}
+
with patch.object(rental_routes, "get_db", self._get_db), \
patch.object(rental_routes, "get_current_user", return_value={
"id": 7, "email": "rider@example.test"
}), \
patch.object(rental_routes, "get_user_display_name", return_value="骑行人"), \
- patch.object(rental_routes, "request_with_user_auth", side_effect=responses), \
+ patch.object(rental_routes, "request_with_user_auth", side_effect=fake_auth), \
patch.object(rental_routes.time, "sleep"):
response = client.post("/api/order/return", json={
"order_id": "9001", "code": "50001",
"latitude": 36.67, "longitude": 116.98,
})
- self.assertEqual(500, response.get_json()["rtn_code"])
+ self.assertNotEqual(0, response.get_json()["rtn_code"])
self.assertEqual(0, self._expired(101))
def test_silent_zero_minute_event_runs_auto_return_without_email(self):
@@ -521,6 +535,105 @@ class OrderSyncTests(unittest.TestCase):
auto_return.assert_called_once_with(101, 7)
notify.assert_not_called()
+ def test_auto_return_failure_keeps_notified_zero_and_schedules_retry(self):
+ """上游还车失败时不能把 notified_0 置位,否则这一单再也不会重试。"""
+ class ImmediateTimer:
+ def __init__(self, delay, callback):
+ self.callback = callback
+ def start(self):
+ self.callback()
+ def cancel(self):
+ pass
+
+ with patch.object(timer, "get_db", self._get_db), \
+ patch.object(timer.threading, "Timer", ImmediateTimer), \
+ patch.object(timer, "auto_return_bike", return_value={
+ "attempted": True, "success": False, "message": "upstream boom"
+ }), \
+ patch.object(timer, "_schedule_reminder") as reschedule, \
+ patch.object(timer, "send_rental_notification"):
+ timer._schedule_reminder(
+ 101, 0, "0", "rider@example.test", "50001", 7,
+ send_notification=False, auto_return_enabled=True,
+ auto_return_configured=True,
+ )
+
+ conn = self._get_db()
+ row = conn.execute("SELECT notified_0 FROM rentals WHERE id = 101").fetchone()
+ conn.close()
+ self.assertEqual(0, row["notified_0"]) # 保持未置位
+ reschedule.assert_called_once()
+ self.assertEqual("0", reschedule.call_args.args[2]) # 安排了短周期重试
+ self.assertEqual(0, self._expired(101))
+
+ def test_restart_recovers_rental_that_expired_while_process_was_down(self):
+ """重启时 end_time 已过:必须补一次自动还车,而不是当它不存在。"""
+ class ImmediateThread:
+ def __init__(self, target=None, args=(), **kwargs):
+ self.target, self.args = target, args
+ def start(self):
+ if self.target:
+ self.target(*self.args)
+
+ conn = self._get_db()
+ conn.execute("""
+ INSERT INTO rentals
+ (id, order_id, user_id, source, expired, start_time, end_time, bike_code, email)
+ VALUES (104, '9004', 7, 'unlock', 0, '2026-01-01 09:00:00',
+ '2026-01-01 09:19:00', '50004', 'rider@example.test')
+ """)
+ conn.commit()
+ conn.close()
+
+ with patch.object(timer, "get_db", self._get_db), \
+ patch.object(timer.threading, "Thread", ImmediateThread), \
+ patch.object(timer, "_time") as fake_time, \
+ patch.object(timer, "auto_return_bike", return_value={
+ "success": True, "message": "ok"
+ }) as auto_return, \
+ patch.object(timer, "start_rental_timer"):
+ fake_time.sleep = lambda *_: None
+ timer.restore_active_timers()
+
+ auto_return.assert_called_once()
+ self.assertEqual(104, auto_return.call_args.args[0])
+
+ def test_checker_recovers_rental_past_end_time_instead_of_returning(self):
+ """巡检看到 expired=0 但 end_time 已过:补还车,不能直接 return。"""
+ class ImmediateThread:
+ def __init__(self, target=None, args=(), **kwargs):
+ self.target, self.args = target, args
+ def start(self):
+ if self.target:
+ self.target(*self.args)
+
+ conn = self._get_db()
+ conn.execute("""
+ INSERT INTO rentals
+ (id, order_id, user_id, source, expired, start_time, end_time, bike_code, email)
+ VALUES (105, '9005', 7, 'unlock', 0, '2026-01-01 09:00:00',
+ '2026-01-01 09:19:00', '50005', 'rider@example.test')
+ """)
+ conn.commit()
+ conn.close()
+
+ active = {"rtn_code": 0, "data": {"nonDealOrder": {
+ "order_id": "9005", "status": 2, "code": "50005"
+ }}}
+ with patch.object(timer, "get_db", self._get_db), \
+ patch.object(timer, "get_user_auth", return_value=("token", "access")), \
+ patch.object(timer, "threading", wraps=timer.threading), \
+ patch.object(timer.threading, "Thread", ImmediateThread), \
+ patch.object(timer, "request_with_user_auth", return_value=active), \
+ patch.object(timer, "auto_return_bike", return_value={
+ "success": True, "message": "ok"
+ }) as auto_return:
+ result = timer._check_user_order(7)
+
+ self.assertTrue(result.get("recovered"))
+ auto_return.assert_called_once()
+ self.assertEqual(105, auto_return.call_args.args[0])
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_subscribe_flow.py b/tests/test_subscribe_flow.py
new file mode 100644
index 0000000..68830ea
--- /dev/null
+++ b/tests/test_subscribe_flow.py
@@ -0,0 +1,139 @@
+# -*- coding: utf-8 -*-
+"""订阅调度与自动开锁的关键回归。
+
+覆盖两件事:
+1) 整分钟漏触发后当天要能补(`minute_of_day <= 当前分钟`);
+2) 开锁失败时必须撤销刚下的半成品订单,避免重试叠加。
+"""
+import datetime as dt
+import sqlite3
+import tempfile
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+
+import subscribe
+
+
+SCHEMA = """
+CREATE TABLE subscribe_rules (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ user_id INTEGER NOT NULL,
+ location_id INTEGER,
+ weekday INTEGER DEFAULT 0,
+ minute_of_day INTEGER NOT NULL,
+ enabled INTEGER DEFAULT 1,
+ notify_enabled INTEGER DEFAULT 1,
+ auto_unlock INTEGER DEFAULT 0,
+ last_fired_on TEXT DEFAULT '',
+ kinds TEXT DEFAULT 'small,big,red',
+ min_electric INTEGER DEFAULT 0,
+ max_electric INTEGER DEFAULT 100,
+ sort_by TEXT DEFAULT 'electric_desc',
+ retry_times INTEGER DEFAULT 3
+);
+"""
+
+
+class ImmediateThread:
+ def __init__(self, target=None, args=(), kwargs=None, **rest):
+ self.target = target
+ self.args = args
+ self.kwargs = kwargs or {}
+
+ def start(self):
+ if self.target:
+ self.target(*self.args, **self.kwargs)
+
+
+class SubscribeFlowTests(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.db_path = Path(self.tmp.name) / "sub.db"
+ conn = sqlite3.connect(self.db_path)
+ conn.executescript(SCHEMA)
+ conn.commit()
+ conn.close()
+
+ def tearDown(self):
+ self.tmp.cleanup()
+
+ def _get_db(self):
+ conn = sqlite3.connect(self.db_path)
+ conn.row_factory = sqlite3.Row
+ return conn
+
+ def test_missed_minute_is_caught_up_later_same_day(self):
+ """7:50 的规则,8:10 才跑到,仍然要发,且当天只发一次。"""
+ now = dt.datetime.now(dt.timezone(dt.timedelta(hours=8)))
+ conn = self._get_db()
+ past_minute = max(0, now.hour * 60 + now.minute - 5)
+ conn.execute("""
+ INSERT INTO subscribe_rules (user_id, location_id, weekday, minute_of_day,
+ enabled, notify_enabled, last_fired_on)
+ VALUES (7, 1, 0, ?, 1, 1, '')
+ """, (past_minute,))
+ conn.commit()
+ conn.close()
+
+ fired = []
+ with patch.object(subscribe, "get_db", self._get_db), \
+ patch.object(subscribe.threading, "Thread", ImmediateThread), \
+ patch.object(subscribe, "fire_rule", side_effect=lambda r: fired.append(r["id"]) or True):
+ subscribe._tick()
+
+ self.assertEqual(1, len(fired), "过点的规则应该补发一次")
+
+ # 同一天再扫一遍不应重复触发
+ with patch.object(subscribe, "get_db", self._get_db), \
+ patch.object(subscribe.threading, "Thread", ImmediateThread), \
+ patch.object(subscribe, "fire_rule", side_effect=lambda r: fired.append(r["id"]) or True):
+ subscribe._tick()
+ self.assertEqual(1, len(fired), "当天已经发过就不该再发")
+
+ def test_future_minute_is_not_fired_early(self):
+ now = dt.datetime.now(dt.timezone(dt.timedelta(hours=8)))
+ conn = self._get_db()
+ future_minute = min(23 * 60 + 59, now.hour * 60 + now.minute + 30)
+ conn.execute("""
+ INSERT INTO subscribe_rules (user_id, location_id, weekday, minute_of_day,
+ enabled, notify_enabled, last_fired_on)
+ VALUES (7, 1, 0, ?, 1, 1, '')
+ """, (future_minute,))
+ conn.commit()
+ conn.close()
+
+ fired = []
+ with patch.object(subscribe, "get_db", self._get_db), \
+ patch.object(subscribe.threading, "Thread", ImmediateThread), \
+ patch.object(subscribe, "fire_rule", side_effect=lambda r: fired.append(r["id"]) or True):
+ subscribe._tick()
+ self.assertEqual([], fired)
+
+ def test_failed_unlock_discards_the_pending_order(self):
+ """下单成功但开锁失败:必须撤销那张单,否则重试会再叠一张。"""
+ responses = {
+ "/project/bicycle": {"rtn_code": 0, "data": {"status": 0, "code": "50001",
+ "latitude": 36.53, "longitude": 116.78}},
+ "/record/order": {"rtn_code": 0, "data": {"order_id": "777"}},
+ "/record/qrOrder": {"rtn_code": 500, "message": "open failed"},
+ "/record/return": {"rtn_code": 0, "message": "closed"},
+ }
+
+ def fake_auth(user_id, method, path, **kwargs):
+ return responses.get(path, {"rtn_code": 0, "data": {}})
+
+ with patch.object(subscribe, "_live_coord", return_value=(36.53, 116.78)), \
+ patch.object(subscribe, "AUTO_UNLOCK_ENABLED", True), \
+ patch("wechat.request_with_user_auth", side_effect=fake_auth), \
+ patch.object(subscribe, "_discard_pending_order", return_value=True) as discard:
+ result = subscribe._try_auto_unlock(7, "50001")
+
+ self.assertFalse(result["success"])
+ discard.assert_called_once()
+ self.assertEqual("777", str(discard.call_args.args[1]))
+ self.assertIn("已撤销本次下单", result["message"])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/timer.py b/timer.py
index 0d9af33..6a6b883 100644
--- a/timer.py
+++ b/timer.py
@@ -38,6 +38,19 @@ def _get_remaining_seconds(rental: dict) -> int:
return max(0, remaining)
+def _rental_end_time_passed(rental: dict) -> bool:
+ """end_time 是否已经过去(重启补还车 / 巡检补还车共用)。"""
+ end_time = (rental or {}).get("end_time")
+ if not end_time:
+ return False
+ try:
+ end = dt.datetime.strptime(end_time, "%Y-%m-%d %H:%M:%S")
+ except (TypeError, ValueError):
+ return False
+ tz = dt.timezone(dt.timedelta(hours=8))
+ return end.replace(tzinfo=tz) <= dt.datetime.now(tz)
+
+
def _extract_pay_methods(methods_result: dict):
data = methods_result.get("data", {}) if isinstance(methods_result, dict) else {}
if not isinstance(data, (list, dict)):
@@ -551,6 +564,41 @@ def _cancel_rental_timers(rental_id: int):
del _active_timers[rental_id]
+def _mark_notified(rental_id: int, reminder_type: str):
+ """把 notified_X 置位(缺列就跳过)。"""
+ col = f"notified_{reminder_type}"
+ conn = get_db()
+ try:
+ cols = [d[0] for d in conn.execute("SELECT * FROM rentals WHERE id = ?", (rental_id,)).description]
+ if col in cols:
+ conn.execute(f"UPDATE rentals SET {col} = 1 WHERE id = ?", (rental_id,))
+ conn.commit()
+ except Exception as exc:
+ print(f"[提醒] 置位 {col} 失败: {exc}")
+ finally:
+ conn.close()
+
+
+# 0 分钟自动还车失败后的重试计数(进程内即可:重启后 restore/巡检会自动补还)
+_auto_return_retries: dict = {}
+AUTO_RETURN_RETRY_DELAY = 30 # 秒
+AUTO_RETURN_MAX_RETRIES = 6
+
+
+def _schedule_auto_return_retry(rental_id: int, email: str, bike_code: str, user_id):
+ """自动还车失败:30 秒后再试,最多 6 次。notified_0 保持 0,让各处调度还能再次触发。"""
+ n = _auto_return_retries.get(rental_id, 0)
+ if n >= AUTO_RETURN_MAX_RETRIES:
+ print(f"[自动还车] rental_id={rental_id} 已重试 {n} 次仍失败,等巡检继续兜底")
+ return
+ _auto_return_retries[rental_id] = n + 1
+ print(f"[自动还车] rental_id={rental_id} 第 {n+1} 次重试将在 "
+ f"{AUTO_RETURN_RETRY_DELAY}s 后执行")
+ _schedule_reminder(rental_id, AUTO_RETURN_RETRY_DELAY, "0", email, bike_code,
+ user_id, send_notification=False,
+ auto_return_enabled=True, auto_return_configured=True)
+
+
def _schedule_reminder(rental_id: int, delay_seconds: int, reminder_type: str,
email: str, bike_code: str, user_id: int = None,
send_notification: bool = True,
@@ -566,28 +614,49 @@ def _schedule_reminder(rental_id: int, delay_seconds: int, reminder_type: str,
conn.close()
return
col = f"notified_{reminder_type}"
- if col in [d[0] for d in cursor.description] and rental[col] == 0:
+ has_col = col in [d[0] for d in cursor.description]
+ if not (has_col and rental[col] == 0):
+ conn.close()
+ return
+
+ # 5/3/2/1 分钟这类纯提醒:先置位再发,发失败也不重发
+ if reminder_type != "0":
cursor.execute(f"UPDATE rentals SET {col} = 1 WHERE id = ?", (rental_id,))
conn.commit()
conn.close()
- return_result = None
- if reminder_type == "0":
- if auto_return_enabled and user_id:
- try:
- return_result = auto_return_bike(rental_id, user_id)
- except Exception as e:
- print(f"[自动还车] 失败: {e}")
- return_result = {"attempted": True, "success": False, "message": str(e)}
- elif not auto_return_configured:
- return_result = {"attempted": False, "success": False,
- "message": "用户未开启自动还车"}
- else:
- return_result = {"attempted": False, "success": False,
- "message": "该提醒未绑定微信订单,无法自动还车"}
if send_notification:
- send_rental_notification(rental_id, reminder_type, return_result)
+ send_rental_notification(rental_id, reminder_type, None)
+ return
+
+ # 0 分钟:先把车还了,成功了才置位。
+ # 原来先置位再还车,上游三次重试一失败就再也不会重试,订单在上游继续计费。
+ conn.close()
+ return_result = None
+ if auto_return_enabled and user_id:
+ try:
+ return_result = auto_return_bike(rental_id, user_id)
+ except Exception as e:
+ print(f"[自动还车] 失败: {e}")
+ return_result = {"attempted": True, "success": False, "message": str(e)}
+ elif not auto_return_configured:
+ return_result = {"attempted": False, "success": False,
+ "message": "用户未开启自动还车"}
else:
- conn.close()
+ return_result = {"attempted": False, "success": False,
+ "message": "该提醒未绑定微信订单,无法自动还车"}
+
+ success = bool(return_result and return_result.get("success"))
+ if success:
+ _auto_return_retries.pop(rental_id, None)
+ _mark_notified(rental_id, "0")
+ elif auto_return_enabled and user_id:
+ # 失败:不置位,短周期重试;页面横幅会提示「自动还车失败,点我重试」
+ _schedule_auto_return_retry(rental_id, email, bike_code, user_id)
+ else:
+ _mark_notified(rental_id, "0") # 未绑定/未开启:一次性事件,直接置位
+
+ if send_notification:
+ send_rental_notification(rental_id, reminder_type, return_result)
timer = threading.Timer(delay_seconds, fire)
timer.daemon = True
@@ -687,22 +756,51 @@ def reschedule_user_rental_timers(user_id: int, apply_duration: bool = False):
def restore_active_timers():
- """启动时恢复所有未过期的计时器"""
+ """启动时恢复计时器;**重启前就已越过到期时间**的单子立刻补一次自动还车。
+
+ 以前这里只捞 `end_time > now`,服务重启时刚好跨过 19 分钟的那一单
+ 既不会恢复计时器、也不会补还车,于是永久失去「自动还车」,
+ 月卡还会按超时继续扣钱。现在把「已过期但没有 expired」的行单独捡出来补还。
+ """
conn = get_db()
cursor = conn.cursor()
- tz = dt.timezone(dt.timedelta(hours=8))
- now_beijing = dt.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
- cursor.execute("""
- SELECT * FROM rentals
- WHERE expired = 0 AND end_time > ?
- """, (now_beijing,))
- for rental in cursor.fetchall():
- remaining = _get_remaining_seconds(dict(rental))
+ cursor.execute("SELECT * FROM rentals WHERE expired = 0")
+ active_rows = [dict(r) for r in cursor.fetchall()]
+ conn.close()
+
+ restored = 0
+ overdue = []
+ for rental in active_rows:
+ remaining = _get_remaining_seconds(rental)
if remaining > 0:
start_rental_timer(rental["id"], rental["email"], rental["bike_code"],
remaining / 60, rental["user_id"])
- conn.close()
- print(f"[计时系统] 已恢复 {len(_active_timers)} 个活跃计时器")
+ restored += 1
+ else:
+ overdue.append(rental)
+
+ print(f"[计时系统] 已恢复 {restored} 个活跃计时器")
+
+ # 补还车放到后台线程,别把启动流程卡住
+ for rental in overdue:
+ print(f"[计时系统] rental_id={rental['id']} 在重启前已过期,补一次自动还车")
+ threading.Thread(target=_recover_overdue_rental, args=(rental,),
+ daemon=True).start()
+
+
+def _recover_overdue_rental(rental: dict):
+ """重启补还车:失败就交给巡检线程与告警,不在这里死磕。"""
+ rental_id = rental.get("id")
+ user_id = rental.get("user_id")
+ try:
+ _time.sleep(3) # 等调度线程和上游会话就绪
+ if not user_id:
+ print(f"[计时系统] rental_id={rental_id} 没有 user_id,跳过补还车")
+ return
+ result = auto_return_bike(rental_id, user_id)
+ print(f"[计时系统] 补还车结果 rental_id={rental_id}: {result.get('message')}")
+ except Exception as exc:
+ print(f"[计时系统] 补还车异常 rental_id={rental_id}: {exc}")
# ========== 用户订单检测系统 ==========
@@ -802,6 +900,18 @@ def _check_user_order(user_id: int):
existing = cursor.fetchone()
if existing and existing["source"] in ("unlock", "sync", "shared") and existing["expired"] == 0:
+ rental = dict(existing)
+ # 到期时间已经过了却还挂着(重启丢了计时器、或 0 点那次失败):
+ # 巡检必须补一次自动还车,不能再无脑 return,否则这一单永远还不掉。
+ if _rental_end_time_passed(rental):
+ conn.close()
+ print(f"[订单检测] rental_id={rental['id']} 已过到期时间,补一次自动还车")
+ threading.Thread(
+ target=lambda: auto_return_bike(rental["id"], user_id),
+ daemon=True
+ ).start()
+ return {"ok": True, "active": True, "order_id": order_id,
+ "recovered": True}
conn.close()
return {"ok": True, "active": True, "order_id": order_id}
@@ -883,26 +993,6 @@ def _finish_active_wechat_rentals(user_id: int, reason: str):
f"order_id={row['order_id']}, source={row['source']}, reason={reason}")
-def _cleanup_stale_rentals(user_id: int):
- """用户无活跃订单时,清理本地残留的 active 记录"""
- import datetime as dt
- tz = dt.timezone(dt.timedelta(hours=8))
- now_str = dt.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
- conn = get_db()
- cursor = conn.cursor()
- cursor.execute("""
- SELECT id, order_id, source FROM rentals
- WHERE user_id = ? AND expired = 0 AND end_time < ?
- """, (user_id, now_str))
- for row in cursor.fetchall():
- rental_id = row["id"]
- _cancel_rental_timers(rental_id)
- _mark_returned(rental_id)
- print(f"[订单检测] 清理过期记录: rental_id={rental_id}, order_id={row['order_id']}, source={row['source']}")
- conn.commit()
- conn.close()
-
-
def start_all_order_checkers():
"""启动所有有凭据用户的订单检测线程。
错峰启动:每个线程间隔 5 秒,避免启动瞬间并发请求上游被限流。"""
diff --git a/wechat.py b/wechat.py
index 68bd005..b804f74 100644
--- a/wechat.py
+++ b/wechat.py
@@ -3,8 +3,9 @@
"""微信API通信模块
凭据模型(对照 98/ 反编译小程序与实机抓包还原):
-- token_id:登录后服务端下发的会话标识(单会话:小程序重新登录即失效)。
- 上游目前唯一强校验的头,必填。
+- token_id:登录后服务端下发的会话标识(上游对同一账号做**单会话**:再次登录会顶掉旧会话,
+ AccessToken 的 30 天有效期只是上限,实际随时可能被新登录顶掉)。上游目前唯一强校验的头,必填。
+ → 所以「打开小程序」本身不会让网页凭据失效,**重新登录**才会;本模块的告警文案不要再说反了。
- access_token:登录响应里的 JWT(30 天有效)。小程序用它在本地实时计算签名:
hsf-x-signature = sha1(access_token + base64(签名串))。选填。
@@ -265,7 +266,8 @@ def _normalize_token_invalid(result: dict, scope: str):
if isinstance(result, dict) and result.get("rtn_code") == 102001:
result["token_invalid"] = True
if scope == "user":
- result["message"] = "Token失效,微信凭据已过期,请在个人中心重新配置"
+ result["message"] = ("微信凭据需要更新(上游判定已失效/已过期),"
+ "请到个人中心重新获取并保存凭据")
else:
result["message"] = "地图数据暂不可用:服务器全局凭据已失效,请联系管理员更新"
return result