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:
@@ -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 秒,避免启动瞬间并发请求上游被限流。"""
|
||||
|
||||
Reference in New Issue
Block a user