fix(P0-P2): 自动还车不再永久丢失 + 还车永不拦人 + 订阅调度补发 + 告警去重修正

## 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 全绿
This commit is contained in:
zzy
2026-11-15 17:25:07 +08:00
parent e01bd67cd8
commit ff80c31b04
14 changed files with 976 additions and 94 deletions
+106 -12
View File
@@ -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():