1) 彻底失败的单被巡检无限重试
- 新增 _recover_last_at + RECOVER_INTERVAL_SECONDS=300:同一单 5 分钟内
只补一次还车,返回 {recovering: True};
原来每 60 秒就起一个线程、每次 3~4 个上游请求 + 睡 15 秒,永远循环
2) 管理端「代还车」还是单点老逻辑
- admin_api_return 改为复用 routes.rental._try_return_candidates:
先发原坐标 → 失败换候选点(上游 parkeArea → 快照 → 校园停车点)
- 失败时把「已尝试 N 个位置」写进返回消息,不再是干巴巴的「还车失败」
3) 代还车只置 expired=1,不写 returned_at
- 成功后改调 _record_rental_end(order_id, user_id, lat, lng):
同时写 returned_at + 终点坐标/标签,「已骑行」列不再一直往上爬;
回填异常时仍兜底 UPDATE expired=1
4) _mark_notified 的 conn/cursor 参数没人用
- 5/3/2/1 分钟分支改为传已有的 conn/cursor(不再为一次 UPDATE 新开连接)
测试:152 pytest(新增巡检节流、管理端代还车链路与回填 2 条)+ 32 node 全绿
1127 lines
49 KiB
Python
1127 lines
49 KiB
Python
#!/usr/bin/env python3
|
||
# -*- coding: utf-8 -*-
|
||
"""计时器系统 + 后台订单检测模块"""
|
||
import threading
|
||
import time as _time
|
||
import datetime as dt
|
||
import sqlite3
|
||
|
||
from db import get_db, get_user_auth, get_user_rental_settings
|
||
from wechat import request_api, request_with_user_auth
|
||
from rental_mail import mark_return_tokens_used, send_rental_notification
|
||
|
||
# ========== 计时器系统 ==========
|
||
TIMER_CHECK_INTERVAL = 30
|
||
_active_timers: dict = {}
|
||
_renewal_locks: dict = {}
|
||
_renewal_locks_guard = threading.Lock()
|
||
|
||
# ========== 用户订单检测系统 ==========
|
||
_order_checker_threads: dict[int, threading.Thread] = {}
|
||
_order_checker_stop: dict[int, threading.Event] = {}
|
||
_checker_lock = threading.Lock()
|
||
# 外部(例如微信小程序)还车后,要尽快取消本地的邮件提醒。
|
||
# 10 分钟轮询会让 5/3/2/1/0 分钟提醒继续发送,改为每分钟核对一次。
|
||
ORDER_CHECK_INTERVAL = 60
|
||
|
||
# 自动还车用的停车区缓存:{user_id: (ts, parkeArea)},避免续租链反复拉地图
|
||
_PARK_AREA_CACHE: dict = {}
|
||
_PARK_AREA_TTL = 60
|
||
|
||
|
||
def _get_remaining_seconds(rental: dict) -> int:
|
||
"""计算距离过期的秒数"""
|
||
now = dt.datetime.now(dt.timezone(dt.timedelta(hours=8)))
|
||
end = dt.datetime.strptime(rental["end_time"], "%Y-%m-%d %H:%M:%S")
|
||
end = end.replace(tzinfo=dt.timezone(dt.timedelta(hours=8)))
|
||
remaining = int((end - now).total_seconds())
|
||
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)):
|
||
return []
|
||
methods = data if isinstance(data, list) else data.get(
|
||
"payMethods", data.get("methods", [])
|
||
)
|
||
if not isinstance(methods, list):
|
||
return []
|
||
return [method for method in methods if isinstance(method, dict)]
|
||
|
||
|
||
def _card_remaining_times(method: dict):
|
||
"""读取优惠卡的剩余次数;None 表示接口未提供可识别的次数。"""
|
||
values = []
|
||
infinite = False
|
||
|
||
def visit(value):
|
||
nonlocal infinite
|
||
if isinstance(value, dict):
|
||
for key, child in value.items():
|
||
normalized = str(key).lower().replace("_", "")
|
||
is_count = (
|
||
("remain" in normalized or "left" in normalized or
|
||
"surplus" in normalized or "available" in normalized)
|
||
and any(token in normalized for token in ("time", "count", "num"))
|
||
)
|
||
if is_count:
|
||
if child is None or str(child).strip().lower() in (
|
||
"", "none", "null", "infinity", "infinite", "∞"
|
||
):
|
||
infinite = True
|
||
else:
|
||
try:
|
||
values.append(int(float(child)))
|
||
except (TypeError, ValueError):
|
||
pass
|
||
visit(child)
|
||
elif isinstance(value, list):
|
||
for child in value:
|
||
visit(child)
|
||
|
||
visit(method)
|
||
if values:
|
||
return max(values)
|
||
if infinite:
|
||
return None
|
||
return None
|
||
|
||
|
||
def _has_available_card(user_id: int, code: str, package_id: str = "") -> bool:
|
||
"""确认支付后是否仍有可用优惠卡,供“优先保护月卡”使用。"""
|
||
try:
|
||
methods_result = request_with_user_auth(
|
||
user_id, "GET", "/pay/methods", params={"code": code}
|
||
)
|
||
except Exception as exc:
|
||
print(f"[自动续租] 查询优惠卡剩余次数异常: {exc}")
|
||
return False
|
||
if not isinstance(methods_result, dict) or methods_result.get("rtn_code") != 0:
|
||
return False
|
||
card_methods = [
|
||
method for method in _extract_pay_methods(methods_result)
|
||
if str(method.get("type")) in ("3", "4")
|
||
]
|
||
if not card_methods:
|
||
return False
|
||
target_methods = card_methods
|
||
if package_id:
|
||
matched = [method for method in card_methods
|
||
if str(method.get("package_id", "")) == str(package_id)]
|
||
if matched:
|
||
target_methods = matched
|
||
|
||
# /pay/methods 的部分版本不带剩余次数;/user/packages 是前端展示
|
||
# remainTimes 的同一份数据,优先用已支付的卡包进行精确保护。
|
||
try:
|
||
package_result = request_with_user_auth(user_id, "GET", "/user/packages")
|
||
except Exception as exc:
|
||
print(f"[自动续租] 查询优惠卡包异常: {exc}")
|
||
package_result = None
|
||
if isinstance(package_result, dict) and package_result.get("rtn_code") == 0:
|
||
package_data = package_result.get("data") or {}
|
||
packages = package_data.get("bike_packages", package_data.get("packages", [])) \
|
||
if isinstance(package_data, dict) else []
|
||
if isinstance(packages, list):
|
||
target_packages = packages
|
||
if package_id:
|
||
matched = [package for package in packages
|
||
if str(package.get("package_id", "")) == str(package_id)]
|
||
if matched:
|
||
target_packages = matched
|
||
package_counts = [_card_remaining_times(package) for package in target_packages
|
||
if isinstance(package, dict)]
|
||
if package_counts and any(count is not None for count in package_counts):
|
||
return any(count is None or count > 0 for count in package_counts)
|
||
|
||
# 兜底:带次数的支付方式严格判断;未带次数时,沿用上游“可用支付方式”结论。
|
||
return any(
|
||
_card_remaining_times(method) is None or _card_remaining_times(method) > 0
|
||
for method in target_methods
|
||
)
|
||
|
||
|
||
def _try_card_pay_auto(user_id: int, order_id: str, code: str) -> dict:
|
||
"""
|
||
自动尝试用月卡/周卡支付订单(从 app.py.bak 原样复制)
|
||
返回: {"success": True/False, "message": "xxx"}
|
||
"""
|
||
methods_result = request_with_user_auth(
|
||
user_id, "GET", "/pay/methods",
|
||
params={"code": code}
|
||
)
|
||
if methods_result.get("rtn_code") != 0:
|
||
return {"success": False, "message": "查询支付方式失败"}
|
||
|
||
card_methods = [
|
||
method for method in _extract_pay_methods(methods_result)
|
||
if str(method.get("type")) in ("3", "4")
|
||
and (_card_remaining_times(method) is None or _card_remaining_times(method) > 0)
|
||
]
|
||
|
||
if not card_methods:
|
||
return {"success": False, "message": "没有可用的月卡/周卡"}
|
||
|
||
preferred = card_methods[0]
|
||
for m in card_methods:
|
||
if m.get("get_type") == 2:
|
||
preferred = m
|
||
break
|
||
|
||
pay_type = str(preferred.get("type", "3"))
|
||
package_id = str(preferred.get("package_id", ""))
|
||
if not package_id:
|
||
return {"success": False, "message": "卡包ID为空"}
|
||
|
||
card_name = "月卡" if pay_type == "3" else "周卡"
|
||
print(f"[_try_card_pay_auto] 使用{card_name}支付: order_id={order_id}, code={code}, package_id={package_id}")
|
||
|
||
pay_result = request_with_user_auth(
|
||
user_id, "POST", "/pay/submit",
|
||
data={"platform": "1", "order_id": order_id, "code": code,
|
||
"type": pay_type, "package_id": package_id}
|
||
)
|
||
|
||
# 解析 /pay/submit 返回的支付状态:data 可能是 dict / 列表 / 空列表 / None,需全部兜底
|
||
_pd = pay_result.get("data")
|
||
if isinstance(_pd, list):
|
||
pay_status = str(_pd[0].get("status", "")) if _pd and isinstance(_pd[0], dict) else ""
|
||
elif isinstance(_pd, dict):
|
||
pay_status = str(_pd.get("status", ""))
|
||
else:
|
||
pay_status = ""
|
||
if pay_status == "0":
|
||
return {"success": True, "message": f"{card_name}支付成功",
|
||
"card_type": pay_type, "package_id": package_id}
|
||
elif pay_status == "1":
|
||
return {"success": False, "message": f"{card_name}余额不足,需要微信支付"}
|
||
else:
|
||
return {"success": False, "message": pay_result.get("message", "支付失败")}
|
||
|
||
|
||
def _renewal_round(rental: dict) -> int:
|
||
try:
|
||
return max(1, int(rental.get("renewal_round") or 1))
|
||
except (TypeError, ValueError):
|
||
return 1
|
||
|
||
|
||
def _planned_rounds(rental: dict, settings: dict) -> int:
|
||
"""订单计划总轮数:手动加轮的 rounds_override 优先于用户设置。"""
|
||
override = rental.get("rounds_override")
|
||
try:
|
||
return int(override) if override else int(settings.get("rental_rounds", 1))
|
||
except (TypeError, ValueError):
|
||
return int(settings.get("rental_rounds", 1))
|
||
|
||
|
||
def _mark_returned(rental_id: int, latitude=None, longitude=None):
|
||
"""结束订单并回填实际还车时间与终点(auto-return / 微信端还车共用)。"""
|
||
label = None
|
||
if latitude is not None and longitude is not None:
|
||
try:
|
||
from campus import resolve_location_label
|
||
label = resolve_location_label(latitude, longitude)
|
||
except Exception:
|
||
label = None
|
||
conn = get_db()
|
||
try:
|
||
conn.execute("""
|
||
UPDATE rentals SET expired = 1, returned_at = datetime('now', '+8 hours'),
|
||
end_latitude = ?, end_longitude = ?, end_label = ?
|
||
WHERE id = ?
|
||
""", (latitude, longitude, label, rental_id))
|
||
except sqlite3.OperationalError:
|
||
# 轻量兜底:旧库/极简 schema 缺列时补齐再重试一次
|
||
for col_def in [("returned_at", "TIMESTAMP"), ("end_latitude", "REAL"),
|
||
("end_longitude", "REAL"), ("end_label", "TEXT")]:
|
||
try:
|
||
conn.execute(f"ALTER TABLE rentals ADD COLUMN {col_def[0]} {col_def[1]}")
|
||
except sqlite3.OperationalError:
|
||
pass
|
||
conn.execute("""
|
||
UPDATE rentals SET expired = 1, returned_at = datetime('now', '+8 hours'),
|
||
end_latitude = ?, end_longitude = ?, end_label = ?
|
||
WHERE id = ?
|
||
""", (latitude, longitude, label, rental_id))
|
||
conn.commit()
|
||
conn.close()
|
||
|
||
|
||
def _reopen_same_bike(user_id: int, bike_code: str) -> dict:
|
||
"""还车后为同一辆车创建下一轮订单并开锁。"""
|
||
bike_result = request_with_user_auth(
|
||
user_id, "POST", "/project/bicycle", data={"code": bike_code}
|
||
)
|
||
if bike_result.get("rtn_code") != 0:
|
||
return {"success": False, "message": bike_result.get("message", "获取车辆信息失败")}
|
||
|
||
bike_data = bike_result.get("data") or {}
|
||
latitude = bike_data.get("latitude", 36.67)
|
||
longitude = bike_data.get("longitude", 116.98)
|
||
order_result = request_with_user_auth(
|
||
user_id, "POST", "/record/order",
|
||
data={"code": bike_code, "start_longitude": longitude,
|
||
"start_latitude": latitude}
|
||
)
|
||
order_data = order_result.get("data") or {}
|
||
if order_result.get("rtn_code") != 0 or not order_data.get("order_id"):
|
||
return {"success": False, "message": order_result.get("message", "创建下一轮订单失败")}
|
||
|
||
order_id = order_data["order_id"]
|
||
open_result = request_with_user_auth(
|
||
user_id, "POST", "/record/qrOrder", data={"order_id": order_id}
|
||
)
|
||
if open_result.get("rtn_code") != 0:
|
||
return {"success": False, "message": open_result.get("message", "下一轮开锁失败"),
|
||
"order_id": order_id}
|
||
return {"success": True, "order_id": str(order_id), "message": "下一轮开锁成功"}
|
||
|
||
|
||
def _create_renewal_rental(rental: dict, user_id: int, order_id: str,
|
||
settings: dict, next_round: int) -> int:
|
||
tz = dt.timezone(dt.timedelta(hours=8))
|
||
start_time = dt.datetime.now(tz)
|
||
duration = int(settings.get("rental_duration_minutes", 19))
|
||
end_time = start_time + dt.timedelta(minutes=duration)
|
||
source = rental.get("source") or "unlock"
|
||
if source == "reminder":
|
||
source = "unlock"
|
||
email = rental.get("email") or ""
|
||
rider_user_id = rental.get("rider_user_id")
|
||
conn = get_db()
|
||
try:
|
||
# 正常情况下由 init_db 完成迁移;这里再做一次轻量兜底,避免旧开发库
|
||
# 缺列时把下一轮记录成“第1轮”,导致后续轮次无法正确停止。
|
||
try:
|
||
conn.execute("SELECT renewal_round FROM rentals LIMIT 0")
|
||
except sqlite3.OperationalError:
|
||
conn.execute("ALTER TABLE rentals ADD COLUMN renewal_round INTEGER NOT NULL DEFAULT 1")
|
||
if rider_user_id:
|
||
cursor = conn.execute("""
|
||
INSERT INTO rentals (order_id, bike_code, email, user_id, rider_user_id,
|
||
start_time, end_time, duration, expired, source, renewal_round)
|
||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?)
|
||
""", (order_id, rental["bike_code"], email, user_id, rider_user_id,
|
||
start_time.strftime("%Y-%m-%d %H:%M:%S"),
|
||
end_time.strftime("%Y-%m-%d %H:%M:%S"), duration, source, next_round))
|
||
else:
|
||
cursor = conn.execute("""
|
||
INSERT INTO rentals (order_id, bike_code, email, user_id,
|
||
start_time, end_time, duration, expired, source, renewal_round)
|
||
VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?, ?)
|
||
""", (order_id, rental["bike_code"], email, user_id,
|
||
start_time.strftime("%Y-%m-%d %H:%M:%S"),
|
||
end_time.strftime("%Y-%m-%d %H:%M:%S"), duration, source, next_round))
|
||
rental_id = cursor.lastrowid
|
||
conn.commit()
|
||
finally:
|
||
conn.close()
|
||
|
||
try:
|
||
start_rental_timer(rental_id, email, rental["bike_code"], duration, user_id)
|
||
except Exception as exc:
|
||
# 上游订单和本地记录已经建立,计时器恢复流程仍可在下次启动时接管。
|
||
print(f"[自动续租] 新订单计时器启动失败: rental_id={rental_id}, error={exc}")
|
||
return rental_id
|
||
|
||
|
||
def _maybe_renew_after_return(rental: dict, user_id: int,
|
||
pay_result: dict, allow_renewal: bool = True) -> dict:
|
||
"""根据还车后实时读取的设置决定是否进入下一轮。"""
|
||
if not allow_renewal or not pay_result.get("success"):
|
||
return {"renewed": False}
|
||
|
||
settings = get_user_rental_settings(user_id)
|
||
current_round = _renewal_round(rental)
|
||
total_rounds = _planned_rounds(rental, settings)
|
||
if not settings.get("auto_return_enabled", True) or current_round >= total_rounds:
|
||
return {"renewed": False, "round": current_round, "total_rounds": total_rounds}
|
||
|
||
if settings.get("protect_card", True) and not _has_available_card(
|
||
user_id, rental["bike_code"], pay_result.get("package_id", "")):
|
||
return {"renewed": False, "blocked": True, "round": current_round,
|
||
"total_rounds": total_rounds,
|
||
"message": "优先保护优惠卡:支付后已无可用优惠卡,未开启下一轮"}
|
||
|
||
try:
|
||
reopen_result = _reopen_same_bike(user_id, rental["bike_code"])
|
||
except Exception as exc:
|
||
print(f"[自动续租] 重开车辆异常: {exc}")
|
||
return {"renewed": False, "round": current_round, "total_rounds": total_rounds,
|
||
"message": f"下一轮开锁异常: {exc}"}
|
||
if not reopen_result.get("success"):
|
||
return {"renewed": False, "round": current_round, "total_rounds": total_rounds,
|
||
"message": reopen_result.get("message", "下一轮开锁失败")}
|
||
|
||
next_round = current_round + 1
|
||
try:
|
||
new_rental_id = _create_renewal_rental(
|
||
rental, user_id, reopen_result["order_id"], settings, next_round
|
||
)
|
||
except Exception as exc:
|
||
print(f"[自动续租] 本地记录下一轮订单异常: {exc}")
|
||
return {"renewed": False, "round": current_round, "total_rounds": total_rounds,
|
||
"message": f"下一轮已开锁,但本地记录失败: {exc}"}
|
||
return {"renewed": True, "round": next_round, "total_rounds": total_rounds,
|
||
"rental_id": new_rental_id, "order_id": reopen_result["order_id"],
|
||
"message": f"已自动开启第{next_round}轮"}
|
||
|
||
|
||
def _renewal_lock(rental_id: int):
|
||
with _renewal_locks_guard:
|
||
return _renewal_locks.setdefault(rental_id, threading.Lock())
|
||
|
||
|
||
def _park_areas_for_user(user_id: int) -> list:
|
||
"""用用户凭据取上游停车区多边形(GCJ02)。结果短缓存,避免续租链反复拉地图。"""
|
||
import park_area
|
||
cached = _PARK_AREA_CACHE.get(user_id)
|
||
now = _time.time()
|
||
if cached and now - cached[0] < _PARK_AREA_TTL:
|
||
return cached[1]
|
||
try:
|
||
result = request_with_user_auth(
|
||
user_id, "GET", "/project/map", params={"type": "1"}, _silent=True
|
||
)
|
||
except Exception as exc:
|
||
print(f"[自动还车] 读取停车区失败: {exc}")
|
||
return []
|
||
if not isinstance(result, dict) or result.get("rtn_code") not in (None, 0):
|
||
return []
|
||
areas = park_area.parse_park_areas(result.get("data") or {})
|
||
if areas:
|
||
_PARK_AREA_CACHE[user_id] = (now, areas)
|
||
return areas
|
||
|
||
|
||
def _align_to_park_area(user_id: int, latitude, longitude):
|
||
"""把自动还车的坐标对齐到停车区(入参/返回都是 GCJ02)。
|
||
|
||
返回 (lat, lng, moved, distance)。拿不到 parkeArea 时原样返回。
|
||
自动还车前**先**对齐一次,绝大多数情况一次就还成功,不必靠重试撞。
|
||
"""
|
||
import park_area
|
||
areas = _park_areas_for_user(user_id)
|
||
if not areas:
|
||
return latitude, longitude, False, 0.0
|
||
try:
|
||
resolved = park_area.resolve_return_coord(latitude, longitude, areas)
|
||
except Exception as exc:
|
||
print(f"[自动还车] 停车区判定异常: {exc}")
|
||
return latitude, longitude, False, 0.0
|
||
if resolved and resolved.get("moved"):
|
||
return (resolved["latitude"], resolved["longitude"], True,
|
||
float(resolved.get("distance") or 0.0))
|
||
return latitude, longitude, False, 0.0
|
||
|
||
|
||
def _auto_return_bike(rental_id: int, user_id: int, allow_renewal: bool = True):
|
||
"""自动还车(含重试:最多3次),返回明确的成败结果。
|
||
|
||
坐标链路(与手动还车同一套停车区规则):
|
||
1. 取车辆坐标(`/project/bicycle`,上游 = GCJ02,不要再转);
|
||
2. **发还车前**先用本地 parkeArea 多边形判定一次,不在停车区就先吸附到
|
||
最近的合法点 —— 原来直接发原始坐标,parkNoShow 时三次重试注定全失败;
|
||
3. 万一对齐后仍失败,第 2 次重试前再吸附一次(应对上游边界与本地不一致)。
|
||
"""
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
cursor.execute("SELECT * FROM rentals WHERE id = ?", (rental_id,))
|
||
rental = cursor.fetchone()
|
||
if not rental:
|
||
conn.close()
|
||
print(f"[自动还车] 记录不存在: rental_id={rental_id}")
|
||
return {"success": False, "rtn_code": 404, "message": "本地租车记录不存在"}
|
||
if rental["expired"]:
|
||
conn.close()
|
||
return {"success": True, "rtn_code": 0, "message": "订单已结束"}
|
||
|
||
bike_code = rental["bike_code"]
|
||
# 统一使用用户 token 查询车辆(与开锁/下单保持同一身份)
|
||
bike_result = request_with_user_auth(user_id, "POST", "/project/bicycle", data={"code": bike_code})
|
||
latitude = bike_result.get("data", {}).get("latitude", 36.67) if bike_result.get("data") else 36.67
|
||
longitude = bike_result.get("data", {}).get("longitude", 116.98) if bike_result.get("data") else 116.98
|
||
|
||
# 上游要求真实订单号;老记录可能只有本地自增 id,则兜底用它
|
||
upstream_order_id = rental["order_id"] if rental["order_id"] else str(rental_id)
|
||
|
||
# 发还车前先对齐停车区:车辆坐标不在 parkeArea 内时直接换成最近的合法点,
|
||
# 否则 parkNoShow 会让三次重试全都打在同一个错坐标上。
|
||
latitude, longitude, aligned, aligned_m = _align_to_park_area(
|
||
user_id, latitude, longitude
|
||
)
|
||
if aligned:
|
||
print(f"[自动还车] 车辆坐标不在停车区,已对齐到最近停车区 "
|
||
f"({latitude:.6f}, {longitude:.6f}) [{aligned_m:.0f}m]")
|
||
|
||
return_result = None
|
||
last_error = None
|
||
snap_attempted = aligned # 已经对齐过的话,重试前不必再对齐一次
|
||
for attempt in range(1, 4):
|
||
try:
|
||
return_result = request_with_user_auth(
|
||
user_id, "POST", "/record/return",
|
||
data={"order_id": upstream_order_id, "longitude": longitude,
|
||
"latitude": latitude, "code": bike_code}
|
||
)
|
||
if return_result.get("rtn_code") == 0:
|
||
print(f"[自动还车] 第{attempt}次调用成功")
|
||
break
|
||
else:
|
||
last_error = f"API返回非0: {return_result.get('message')}"
|
||
print(f"[自动还车] 第{attempt}次失败: {last_error}")
|
||
except Exception as e:
|
||
last_error = str(e)
|
||
print(f"[自动还车] 第{attempt}次异常: {last_error}")
|
||
# 首次失败:再对齐一次停车区(应对上游边界与本地多边形不一致)
|
||
if not snap_attempted and attempt < 3:
|
||
snap_attempted = True
|
||
new_lat, new_lng, moved, moved_m = _align_to_park_area(
|
||
user_id, latitude, longitude
|
||
)
|
||
if moved:
|
||
latitude, longitude = new_lat, new_lng
|
||
print(f"[自动还车] 已吸附到最近停车区 "
|
||
f"({latitude:.6f}, {longitude:.6f}) [{moved_m:.0f}m],准备重试")
|
||
if attempt < 3:
|
||
_time.sleep(5)
|
||
|
||
success = bool(return_result and return_result.get("rtn_code") == 0)
|
||
pay_result = {"success": False, "message": "未执行自动支付"}
|
||
if success:
|
||
try:
|
||
pay_result = _try_card_pay_auto(user_id, upstream_order_id, bike_code)
|
||
print(f"[自动还车] 月卡支付结果: {pay_result}")
|
||
except Exception as e:
|
||
pay_result = {"success": False, "message": f"自动支付异常: {e}"}
|
||
print(f"[自动还车] 月卡支付异常: {e}")
|
||
elif last_error:
|
||
print(f"[自动还车] 所有重试失败: {last_error}")
|
||
|
||
# 只有上游明确返回成功才结束本地订单。失败时保留 active,
|
||
# 让邮件按钮可重试,后台对账也能继续跟踪真实状态。
|
||
if success:
|
||
_mark_returned(rental_id, latitude, longitude)
|
||
conn.close()
|
||
renewal_result = {"renewed": False}
|
||
if success:
|
||
_cancel_rental_timers(rental_id)
|
||
mark_return_tokens_used(rental_id)
|
||
try:
|
||
renewal_result = _maybe_renew_after_return(
|
||
dict(rental), user_id, pay_result, allow_renewal
|
||
)
|
||
except Exception as exc:
|
||
print(f"[自动续租] 处理下一轮异常: {exc}")
|
||
renewal_result = {"renewed": False, "message": f"自动续租处理异常: {exc}"}
|
||
status = "成功" if success else "失败"
|
||
print(f"[自动还车] rental_id={rental_id}, bike={bike_code}, {status}")
|
||
message = (return_result or {}).get("message") or last_error or (
|
||
"还车成功" if success else "自动还车失败"
|
||
)
|
||
if success and pay_result.get("message"):
|
||
message += f",{pay_result['message']}"
|
||
if renewal_result.get("renewed"):
|
||
message += f",{renewal_result['message']}"
|
||
elif renewal_result.get("blocked"):
|
||
message += f",{renewal_result['message']}"
|
||
return {
|
||
"attempted": True,
|
||
"success": success,
|
||
"rtn_code": return_result.get("rtn_code", 500) if return_result else 500,
|
||
"message": message,
|
||
"card_pay": pay_result,
|
||
"renewal": renewal_result,
|
||
}
|
||
|
||
|
||
def auto_return_bike(rental_id: int, user_id: int, allow_renewal: bool = True):
|
||
"""串行执行还车,避免定时器和手动入口同时触发重复续租。"""
|
||
with _renewal_lock(rental_id):
|
||
return _auto_return_bike(rental_id, user_id, allow_renewal)
|
||
|
||
|
||
def _cancel_rental_timers(rental_id: int):
|
||
"""取消某次租车的所有计时器"""
|
||
if rental_id in _active_timers:
|
||
for t in _active_timers[rental_id]:
|
||
t.cancel()
|
||
del _active_timers[rental_id]
|
||
|
||
|
||
# 只有这些来源才代表「真的有上游骑行订单」,才能走自动还车。
|
||
# reminder 是前端自己开的计时提醒,没有上游订单;把本地自增 id 当订单号发出去
|
||
# 必然 204010,白打三次上游还要 sleep 15 秒。
|
||
AUTO_RETURN_SOURCES = ("unlock", "sync", "shared", "subscribe")
|
||
|
||
|
||
# 巡检补还车的节流:彻底失败的单不能每分钟重打上游
|
||
_recover_last_at: dict = {}
|
||
RECOVER_INTERVAL_SECONDS = 300 # 5 分钟
|
||
|
||
|
||
def _recover_throttled(rental_id: int) -> bool:
|
||
"""5 分钟内已经补过就不再补,返回 True 表示这次要跳过。"""
|
||
now = _time.time()
|
||
last = _recover_last_at.get(rental_id, 0)
|
||
if now - last < RECOVER_INTERVAL_SECONDS:
|
||
return True
|
||
_recover_last_at[rental_id] = now
|
||
return False
|
||
|
||
|
||
def _should_auto_return(rental) -> bool:
|
||
"""这张单能不能走上游自动还车(restore / 巡检共用同一判断)。"""
|
||
if not rental:
|
||
return False
|
||
if str(rental.get("source") or "") not in AUTO_RETURN_SOURCES:
|
||
return False
|
||
return bool(rental.get("order_id"))
|
||
|
||
|
||
def _mark_notified(rental_id: int, reminder_type: str, conn=None, cursor=None):
|
||
"""把 notified_X 置位(缺列就跳过)。
|
||
|
||
调用方已经拿着连接/游标时直接复用,不再为一次 UPDATE 新开连接。
|
||
"""
|
||
col = f"notified_{reminder_type}"
|
||
if cursor is not None and conn is not None:
|
||
try:
|
||
cols = [d[0] for d in cursor.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}")
|
||
return
|
||
|
||
own_conn = get_db()
|
||
try:
|
||
cur = own_conn.execute("SELECT * FROM rentals WHERE id = ?", (rental_id,))
|
||
if col in [d[0] for d in cur.description]:
|
||
own_conn.execute(f"UPDATE rentals SET {col} = 1 WHERE id = ?", (rental_id,))
|
||
own_conn.commit()
|
||
except Exception as exc:
|
||
print(f"[提醒] 置位 {col} 失败: {exc}")
|
||
finally:
|
||
own_conn.close()
|
||
|
||
|
||
# 0 分钟自动还车失败后的重试计数(进程内即可:重启后 restore/巡检会自动补还)
|
||
_auto_return_retries: dict = {}
|
||
AUTO_RETURN_RETRY_DELAY = 30 # 秒
|
||
AUTO_RETURN_MAX_RETRIES = 6
|
||
|
||
|
||
def _notify_auto_return_recovered(rental_id: int):
|
||
"""重试若干次后终于还车成功:再发一封「已还上」,别让用户去点邮件里的旧按钮。"""
|
||
try:
|
||
from email_utils import send_email
|
||
conn = get_db()
|
||
row = conn.execute(
|
||
"SELECT bike_code, email FROM rentals WHERE id = ?", (rental_id,)).fetchone()
|
||
conn.close()
|
||
if not row:
|
||
return
|
||
to_email = (row["email"] or "").strip()
|
||
if not to_email:
|
||
return
|
||
titled = f"自动还车已成功(#{row['bike_code']})"
|
||
body = (f"上次自动还车失败后系统已重试并成功,车辆 #{row['bike_code']} 已还车,"
|
||
f"这单不会再计费。\n\n如果你刚才点了邮件里的「还车」按钮,"
|
||
f"看到「订单已结束」是正常的 —— 不用再操作。")
|
||
send_email(to_email, f"【小白超人】{titled}", body,
|
||
f"<p>{body.replace(chr(10), '<br/>')}</p>")
|
||
print(f"[自动还车] rental_id={rental_id} 重试成功,已发最终成功通知")
|
||
except Exception as exc:
|
||
print(f"[自动还车] 重试成功通知发送失败: {exc}")
|
||
|
||
|
||
def _alert_auto_return_exhausted(rental_id: int, bike_code: str, message: str = ""):
|
||
"""重试耗尽仍失败:给管理员发告警邮件,不能只留一行 print。"""
|
||
try:
|
||
from alerts import get_alert_emails
|
||
from email_utils import send_email
|
||
recipients = get_alert_emails()
|
||
if not recipients:
|
||
print(f"[自动还车] rental_id={rental_id} 重试耗尽且没有配置告警邮箱")
|
||
return
|
||
title = f"自动还车失败需人工处理(#{bike_code})"
|
||
body = (f"rental_id={rental_id} 车辆 #{bike_code} 自动还车已重试 "
|
||
f"{AUTO_RETURN_MAX_RETRIES} 次仍失败。\n"
|
||
f"最后一次错误:{message or '(无)'}\n\n"
|
||
f"这单还在上游计费,请到管理后台「代还车」处理。")
|
||
for to in recipients:
|
||
send_email(to, f"【小白超人·告警】{title}", body,
|
||
f"<p>{body.replace(chr(10), '<br/>')}</p>")
|
||
print(f"[自动还车] rental_id={rental_id} 重试耗尽,已发告警给 {len(recipients)} 个邮箱")
|
||
except Exception as exc:
|
||
print(f"[自动还车] 重试耗尽告警发送失败: {exc}")
|
||
|
||
|
||
def _schedule_auto_return_retry(rental_id: int, email: str, bike_code: str, user_id,
|
||
message: str = ""):
|
||
"""自动还车失败: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} 次仍失败,转人工")
|
||
_alert_auto_return_exhausted(rental_id, bike_code, message)
|
||
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,
|
||
auto_return_enabled: bool = True,
|
||
auto_return_configured: bool = True):
|
||
"""调度单个提醒"""
|
||
def fire():
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
cursor.execute("SELECT * FROM rentals WHERE id = ?", (rental_id,))
|
||
rental = cursor.fetchone()
|
||
if not rental or rental["expired"] == 1:
|
||
conn.close()
|
||
return
|
||
col = f"notified_{reminder_type}"
|
||
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":
|
||
_mark_notified(rental_id, reminder_type, conn=conn, cursor=cursor)
|
||
conn.close()
|
||
if send_notification:
|
||
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:
|
||
return_result = {"attempted": False, "success": False,
|
||
"message": "该提醒未绑定微信订单,无法自动还车"}
|
||
|
||
success = bool(return_result and return_result.get("success"))
|
||
had_retries = _auto_return_retries.get(rental_id, 0)
|
||
if success:
|
||
_auto_return_retries.pop(rental_id, None)
|
||
_mark_notified(rental_id, "0")
|
||
if had_retries:
|
||
# 之前发过「自动还车失败」,这次终于还上了,必须再发一封收尾,
|
||
# 否则用户会去点旧邮件里的还车按钮(那时订单已结束)
|
||
_notify_auto_return_recovered(rental_id)
|
||
elif auto_return_enabled and user_id:
|
||
# 失败:不置位,短周期重试;页面横幅会提示「自动还车失败,点我重试」
|
||
_schedule_auto_return_retry(
|
||
rental_id, email, bike_code, user_id,
|
||
str((return_result or {}).get("message") or ""))
|
||
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
|
||
if rental_id not in _active_timers:
|
||
_active_timers[rental_id] = []
|
||
_active_timers[rental_id].append(timer)
|
||
# 先登记再启动,避免 0 秒任务先完成/取消后又被追加回活动列表。
|
||
timer.start()
|
||
return timer
|
||
|
||
|
||
def start_rental_timer(rental_id: int, email: str, bike_code: str,
|
||
duration_minutes: int, user_id: int = None):
|
||
"""按订单双方的偏好启动提醒,并按实际骑行者偏好决定是否自动还车。"""
|
||
_cancel_rental_timers(rental_id)
|
||
_active_timers[rental_id] = []
|
||
|
||
conn = get_db()
|
||
row = conn.execute("SELECT * FROM rentals WHERE id = ?", (rental_id,)).fetchone()
|
||
conn.close()
|
||
rental = dict(row) if row else {}
|
||
owner_user_id = rental.get("user_id") or user_id
|
||
rider_user_id = rental.get("rider_user_id") or owner_user_id
|
||
recipient_ids = {uid for uid in (owner_user_id, rider_user_id) if uid}
|
||
settings_by_user = {uid: get_user_rental_settings(uid) for uid in recipient_ids}
|
||
policy_settings = settings_by_user.get(rider_user_id) or get_user_rental_settings(rider_user_id)
|
||
|
||
reminders = set()
|
||
for settings in settings_by_user.values():
|
||
if settings["reminder_enabled"]:
|
||
reminders.update(settings["reminder_minutes"])
|
||
can_auto_return = bool(policy_settings["auto_return_enabled"] and rental.get("order_id"))
|
||
schedule_points = set(reminders)
|
||
if can_auto_return:
|
||
schedule_points.add(0)
|
||
|
||
remaining = duration_minutes * 60
|
||
for mins in sorted(schedule_points, reverse=True):
|
||
delay = remaining - (mins * 60)
|
||
if delay >= 0:
|
||
_schedule_reminder(
|
||
rental_id, delay, str(mins), email, bike_code, owner_user_id,
|
||
send_notification=mins in reminders,
|
||
auto_return_enabled=can_auto_return if mins == 0 else False,
|
||
auto_return_configured=policy_settings["auto_return_enabled"],
|
||
)
|
||
|
||
|
||
def reschedule_user_rental_timers(user_id: int, apply_duration: bool = False):
|
||
"""立即应用用户设置并重排相关进行中订单。
|
||
|
||
提醒偏好会影响用户作为车主或骑行人的所有相关订单;到期时长属于
|
||
实际骑行人策略,只更新该用户本人正在骑行的订单。新到期时间始终按
|
||
``start_time + rental_duration_minutes`` 计算,避免在每次保存时重复续时。
|
||
"""
|
||
conn = get_db()
|
||
rows = conn.execute("""
|
||
SELECT * FROM rentals
|
||
WHERE expired = 0 AND (user_id = ? OR rider_user_id = ?)
|
||
""", (user_id, user_id)).fetchall()
|
||
if apply_duration:
|
||
duration = get_user_rental_settings(user_id)["rental_duration_minutes"]
|
||
for row in rows:
|
||
rental = dict(row)
|
||
policy_user_id = rental.get("rider_user_id") or rental.get("user_id")
|
||
if policy_user_id != user_id or not rental.get("start_time"):
|
||
continue
|
||
try:
|
||
start_time = dt.datetime.strptime(
|
||
rental["start_time"], "%Y-%m-%d %H:%M:%S"
|
||
)
|
||
except (TypeError, ValueError):
|
||
print(f"[计时系统] 无法解析开始时间,跳过实时改期: rental_id={rental['id']}")
|
||
continue
|
||
new_end = start_time + dt.timedelta(minutes=duration)
|
||
conn.execute(
|
||
"UPDATE rentals SET end_time = ?, duration = ? WHERE id = ?",
|
||
(new_end.strftime("%Y-%m-%d %H:%M:%S"), duration, rental["id"]),
|
||
)
|
||
conn.commit()
|
||
rows = conn.execute("""
|
||
SELECT * FROM rentals
|
||
WHERE expired = 0 AND (user_id = ? OR rider_user_id = ?)
|
||
""", (user_id, user_id)).fetchall()
|
||
conn.close()
|
||
count = 0
|
||
for row in rows:
|
||
rental = dict(row)
|
||
remaining = _get_remaining_seconds(rental)
|
||
# remaining=0 时仍需重排:缩短到已经到期应立即触发 0 分钟策略。
|
||
start_rental_timer(
|
||
rental["id"], rental.get("email", ""), rental.get("bike_code", ""),
|
||
remaining / 60, rental.get("user_id"),
|
||
)
|
||
count += 1
|
||
return count
|
||
|
||
|
||
def restore_active_timers():
|
||
"""启动时恢复计时器;**重启前就已越过到期时间**的单子立刻补一次自动还车。
|
||
|
||
以前这里只捞 `end_time > now`,服务重启时刚好跨过 19 分钟的那一单
|
||
既不会恢复计时器、也不会补还车,于是永久失去「自动还车」,
|
||
月卡还会按超时继续扣钱。现在把「已过期但没有 expired」的行单独捡出来补还。
|
||
"""
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
cursor.execute("SELECT * FROM rentals WHERE expired = 0")
|
||
active_rows = [dict(r) for r in cursor.fetchall()]
|
||
conn.close()
|
||
|
||
restored = 0
|
||
overdue = []
|
||
skipped = 0
|
||
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"])
|
||
restored += 1
|
||
elif _should_auto_return(rental):
|
||
overdue.append(rental)
|
||
else:
|
||
# reminder 之类没有真实上游订单的单子:不要拿本地 id 去猜订单号
|
||
skipped += 1
|
||
|
||
print(f"[计时系统] 已恢复 {restored} 个活跃计时器")
|
||
if skipped:
|
||
print(f"[计时系统] {skipped} 个过期单没有上游订单(reminder 等),跳过补还车")
|
||
|
||
# 补还车放到后台线程,别把启动流程卡住
|
||
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")
|
||
if not _should_auto_return(rental):
|
||
# 没有真实上游订单(reminder / 老记录),补还车必然 204010,别白打三次上游
|
||
print(f"[计时系统] rental_id={rental_id} 没有上游订单号,跳过补还车")
|
||
return
|
||
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}")
|
||
|
||
|
||
# ========== 用户订单检测系统 ==========
|
||
|
||
def start_user_order_checker(user_id: int):
|
||
"""为指定用户启动订单检测守护线程"""
|
||
with _checker_lock:
|
||
if user_id in _order_checker_threads and _order_checker_threads[user_id].is_alive():
|
||
return
|
||
stop_event = threading.Event()
|
||
_order_checker_stop[user_id] = stop_event
|
||
t = threading.Thread(
|
||
target=_user_order_checker_loop,
|
||
args=(user_id, stop_event), daemon=True,
|
||
name=f"order-checker-{user_id}"
|
||
)
|
||
t.start()
|
||
_order_checker_threads[user_id] = t
|
||
print(f"[订单检测] 为用户 {user_id} 启动检测线程")
|
||
|
||
|
||
def stop_user_order_checker(user_id: int):
|
||
"""停止指定用户的订单检测线程"""
|
||
with _checker_lock:
|
||
if user_id in _order_checker_stop:
|
||
_order_checker_stop[user_id].set()
|
||
del _order_checker_stop[user_id]
|
||
if user_id in _order_checker_threads:
|
||
del _order_checker_threads[user_id]
|
||
print(f"[订单检测] 已停止用户 {user_id} 的检测线程")
|
||
|
||
|
||
def _user_order_checker_loop(user_id: int, stop_event: threading.Event):
|
||
"""用户订单检测线程主循环"""
|
||
while not stop_event.is_set():
|
||
try:
|
||
_check_user_order(user_id)
|
||
except Exception as e:
|
||
print(f"[订单检测] 用户 {user_id} 检测异常: {e}")
|
||
stop_event.wait(ORDER_CHECK_INTERVAL)
|
||
|
||
|
||
def _check_user_order(user_id: int):
|
||
"""检查单个用户的微信订单状态并同步到本地"""
|
||
import datetime as dt
|
||
|
||
token_id, access_token = get_user_auth(user_id)
|
||
if not token_id:
|
||
print(f"[订单检测] 用户 {user_id} 无凭据,停止检测")
|
||
stop_user_order_checker(user_id)
|
||
return {"ok": False, "active": None, "message": "用户未配置微信凭据"}
|
||
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
cursor.execute("SELECT email FROM users WHERE id = ?", (user_id,))
|
||
row = cursor.fetchone()
|
||
if not row:
|
||
conn.close()
|
||
stop_user_order_checker(user_id)
|
||
return {"ok": False, "active": None, "message": "用户不存在"}
|
||
email = row["email"]
|
||
conn.close()
|
||
|
||
info = request_with_user_auth(user_id, "GET", "/user/info", _silent=True)
|
||
if info.get("rtn_code") != 0:
|
||
if info.get("rtn_code") == 102001 or info.get("token_invalid"):
|
||
# token_id 已被上游判定失效(凭据过期/被上游拒绝):
|
||
# 停止轮询避免无效请求;用户在个人中心/管理端更新凭据时会自动重启线程
|
||
print(f"[订单检测] 用户 {user_id} 凭据已失效,停止检测线程,等待更新凭据")
|
||
stop_user_order_checker(user_id)
|
||
return {"ok": False, "active": None,
|
||
"rtn_code": info.get("rtn_code", 500),
|
||
"message": info.get("message", "获取微信订单状态失败")}
|
||
|
||
non_deal = info.get("data", {}).get("nonDealOrder")
|
||
if not non_deal or not non_deal.get("order_id"):
|
||
_finish_active_wechat_rentals(user_id, "微信端已无未完成订单")
|
||
return {"ok": True, "active": False}
|
||
|
||
order_id = str(non_deal.get("order_id"))
|
||
order_status = non_deal.get("status") # 1=未支付, 2=进行中
|
||
if str(order_status) != "2":
|
||
# 微信端还车后,nonDealOrder 可能仍保留但状态变为 1(待支付)。
|
||
# 订单横幅仍由 /api/order/status 展示,但本地骑行计时和邮件必须立即停止。
|
||
_finish_active_wechat_rentals(
|
||
user_id, f"微信订单 {order_id} 已非骑行中(status={order_status})"
|
||
)
|
||
return {"ok": True, "active": False, "order_id": order_id,
|
||
"order_status": order_status}
|
||
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
cursor.execute(
|
||
"SELECT id, order_id, source, expired, end_time FROM rentals "
|
||
"WHERE order_id = ? AND user_id = ?",
|
||
(order_id, user_id)
|
||
)
|
||
existing = cursor.fetchone()
|
||
|
||
if existing and existing["expired"] == 0:
|
||
rental = dict(existing)
|
||
# 到期时间已经过了却还挂着(重启丢了计时器、或 0 点那次失败):
|
||
# 巡检必须补一次自动还车,不能再无脑 return,否则这一单永远还不掉。
|
||
# 只有「真的有上游订单」的来源才补(reminder 之类拿本地 id 当订单号必然失败)。
|
||
if _should_auto_return(rental) and _rental_end_time_passed(rental):
|
||
conn.close()
|
||
if _recover_throttled(rental["id"]):
|
||
# 彻底还不上(车被锁死/订单状态怪)时不能每分钟重打:
|
||
# 5 分钟一次,避免每分钟 3~4 个上游请求 + 线程睡 15 秒的死循环
|
||
return {"ok": True, "active": True, "order_id": order_id,
|
||
"recovering": True}
|
||
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}
|
||
|
||
detail = request_with_user_auth(user_id, "GET", "/record/detail",
|
||
params={"order_id": order_id}, _silent=True)
|
||
if detail.get("rtn_code") != 0 or not detail.get("data"):
|
||
conn.close()
|
||
return {"ok": False, "active": None,
|
||
"rtn_code": detail.get("rtn_code") or 502,
|
||
"message": detail.get("message", "获取微信订单详情失败")}
|
||
|
||
detail_data = detail["data"]
|
||
minutes = int(detail_data.get("minutes", 0))
|
||
code = detail_data.get("code", non_deal.get("code", ""))
|
||
|
||
duration = get_user_rental_settings(user_id)["rental_duration_minutes"]
|
||
remaining = max(duration - minutes, 1)
|
||
tz = dt.timezone(dt.timedelta(hours=8))
|
||
now = dt.datetime.now(tz)
|
||
end_time = now + dt.timedelta(minutes=remaining)
|
||
end_str = end_time.strftime("%Y-%m-%d %H:%M:%S")
|
||
# 上游 minutes 是本次订单已经骑行的分钟数,据此反推真实开始时间。
|
||
# 后续实时修改总时长时才能正确按整段骑行计算,而不是从同步时刻重新计时。
|
||
start_str = (now - dt.timedelta(minutes=minutes)).strftime("%Y-%m-%d %H:%M:%S")
|
||
|
||
if existing:
|
||
rental_id = existing["id"]
|
||
cursor.execute("""
|
||
UPDATE rentals SET expired = 0, source = 'sync',
|
||
start_time = ?, end_time = ?, duration = ?, email = ? WHERE id = ?
|
||
""", (start_str, end_str, duration, email, rental_id))
|
||
old_source = existing["source"]
|
||
print(f"[订单检测] 升级租车记录: rental_id={rental_id}, order_id={order_id}, "
|
||
f"source={old_source}→sync, 剩余={remaining}分钟")
|
||
else:
|
||
cursor.execute("""
|
||
INSERT INTO rentals (order_id, bike_code, email, user_id,
|
||
start_time, end_time, duration, expired, source)
|
||
VALUES (?, ?, ?, ?, ?, ?, ?, 0, 'sync')
|
||
""", (order_id, code, email, user_id, start_str, end_str, duration))
|
||
rental_id = cursor.lastrowid
|
||
print(f"[订单检测] 创建新租车记录: rental_id={rental_id}, order_id={order_id}, "
|
||
f"code={code}, 剩余={remaining}分钟")
|
||
cursor.execute("""
|
||
UPDATE rentals SET expired = 1 WHERE user_id = ? AND bike_code = ? AND source = 'reminder' AND expired = 0
|
||
""", (user_id, code))
|
||
cleaned = cursor.rowcount
|
||
if cleaned:
|
||
print(f"[订单检测] 已清理 {cleaned} 条旧的 reminder 记录")
|
||
|
||
conn.commit()
|
||
conn.close()
|
||
_cancel_rental_timers(rental_id)
|
||
start_rental_timer(rental_id, email, code, remaining, user_id)
|
||
return {"ok": True, "active": True, "order_id": order_id}
|
||
|
||
|
||
def _finish_active_wechat_rentals(user_id: int, reason: str):
|
||
"""微信已确认没有进行中骑行时,结束本地镜像记录并取消邮件计时器。
|
||
|
||
只处理由微信订单产生的 unlock/sync/shared 记录,不影响用户
|
||
单独创建的 reminder 计时。该函数只能在上游请求成功后调用,
|
||
避免把网络或凭据故障误判为已还车。
|
||
"""
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
cursor.execute("""
|
||
SELECT id, order_id, source FROM rentals
|
||
WHERE user_id = ? AND expired = 0
|
||
AND source IN ('unlock', 'sync', 'shared')
|
||
""", (user_id,))
|
||
active_rows = cursor.fetchall()
|
||
conn.close()
|
||
|
||
for row in active_rows:
|
||
_mark_returned(row["id"]) # 微信端自行还车:无终点坐标,只记时间
|
||
_cancel_rental_timers(row["id"])
|
||
print(f"[订单检测] 结束本地骑行记录: rental_id={row['id']}, "
|
||
f"order_id={row['order_id']}, source={row['source']}, reason={reason}")
|
||
|
||
|
||
def start_all_order_checkers():
|
||
"""启动所有有凭据用户的订单检测线程。
|
||
错峰启动:每个线程间隔 5 秒,避免启动瞬间并发请求上游被限流。"""
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
cursor.execute("SELECT id FROM users WHERE token_id IS NOT NULL AND token_id != ''")
|
||
users = cursor.fetchall()
|
||
conn.close()
|
||
|
||
def staggered():
|
||
for i, row in enumerate(users):
|
||
if i > 0:
|
||
_time.sleep(5)
|
||
start_user_order_checker(row["id"])
|
||
print(f"[订单检测] 已启动 {len(users)} 个用户的订单检测线程")
|
||
|
||
threading.Thread(target=staggered, daemon=True, name="order-checker-starter").start()
|