fix: sync 单不再显示「起点/终点未知」

原因
- sync 单是巡检从上游发现到的订单:/record/detail 只返回分钟数和车牌,没有坐标,
  创建/升级时从未写 start_latitude/start_label
- 微信端自行还车走 _finish_active_wechat_rentals,只调 _mark_returned(id) 不传坐标,
  所以 end_latitude/end_label 也是空
- 后台 routeCell 的逻辑是「标签优先 → 坐标 → 否则未知」,两列都空就显示未知

修法
- 新增 _bike_pos_from_history(code, when?):从 bike_history 取这辆车的位置
  (给了时间就取 ±15 分钟内最近一条,否则取最新一条),拿不到返回 None,不编造
- sync 单创建/升级后调 _fill_missing_start:只在坐标为空时回填起点 + 楼栋标签
- _finish_active_wechat_rentals:用最新采集点补终点(SELECT 增加 bike_code)
- 新增 scripts/backfill_rental_locations.py:历史单一次性回填,
  默认 dry-run,--apply 才写库;排除 reminder(纯本地计时,没有车在动)

测试:169 pytest(新增 sync 起点回填、微信端还车补终点)+ 32 node 全绿
本地库 dry-run:339/336 行缺坐标、0 行可补(订单都是 7 月的,超出 30 天采集保留期)
This commit is contained in:
zzy
2026-11-16 12:47:08 +08:00
parent 400f083a5e
commit 598fadec0e
3 changed files with 251 additions and 4 deletions
+92 -2
View File
@@ -1263,11 +1263,95 @@ def _check_user_order(user_id: int):
conn.commit()
conn.close()
# sync 单来自上游已有订单,没有坐标:用开始时间附近的采集点回填起点,
# 否则后台订单表一直显示「起点未知」
try:
_fill_missing_start(rental_id, code, start_str)
except Exception as exc:
print(f"[订单检测] 回填 sync 起点失败: {exc}")
_cancel_rental_timers(rental_id)
start_rental_timer(rental_id, email, code, remaining, user_id)
return {"ok": True, "active": True, "order_id": order_id}
SYNC_START_TOLERANCE_MINUTES = 15 # sync 单起点回填:用开始时间附近的历史点
def _bike_pos_from_history(bike_code: str, when_str: str = None,
tolerance_minutes: int = SYNC_START_TOLERANCE_MINUTES):
"""从 bike_history 取这辆车的位置(GCJ02)。
- 给了 when_str:取该时刻附近(±tolerance)最近的一条 —— 用于 sync 单回填起点;
- 没给:取最新一条 —— 用于还车时补终点。
采集频率是 5~10 分钟,所以只能近似;拿不到就返回 None,不编造坐标。
"""
if not bike_code:
return None
conn = get_db()
try:
if when_str:
try:
when = dt.datetime.strptime(str(when_str), "%Y-%m-%d %H:%M:%S")
except (TypeError, ValueError):
return None
tz = dt.timezone(dt.timedelta(hours=8))
lo = (when - dt.timedelta(minutes=tolerance_minutes)).strftime("%Y-%m-%d %H:%M:%S")
hi = (when + dt.timedelta(minutes=tolerance_minutes)).strftime("%Y-%m-%d %H:%M:%S")
row = conn.execute("""
SELECT latitude, longitude FROM bike_history
WHERE bike_code = ? AND recorded_at BETWEEN ? AND ?
ORDER BY ABS(julianday(recorded_at) - julianday(?)) LIMIT 1
""", (str(bike_code), lo, hi, str(when_str))).fetchone()
else:
row = conn.execute("""
SELECT latitude, longitude FROM bike_history
WHERE bike_code = ? AND latitude IS NOT NULL AND longitude IS NOT NULL
ORDER BY recorded_at DESC LIMIT 1
""", (str(bike_code),)).fetchone()
except Exception as exc:
print(f"[位置回填] 查询 bike_history 失败: {exc}")
return None
finally:
conn.close()
if not row:
return None
try:
return float(row["latitude"]), float(row["longitude"])
except (TypeError, ValueError):
return None
def _fill_missing_start(rental_id: int, bike_code: str, start_str: str):
"""给 sync 单补起点坐标与位置标签(只在为空时补,不覆盖已有值)。
sync 单是我们从上游"发现"的订单:`/record/detail` 只给分钟数和车牌,
没有坐标,所以之前后台一直显示「起点未知」。用开始时间附近的采集点近似。
"""
pos = _bike_pos_from_history(bike_code, start_str)
if not pos:
return False
lat, lng = pos
label = None
try:
from campus import resolve_location_label
label = resolve_location_label(lat, lng)
except Exception:
label = None
conn = get_db()
try:
conn.execute("""
UPDATE rentals SET start_latitude = ?, start_longitude = ?, start_label = ?
WHERE id = ? AND (start_latitude IS NULL OR start_longitude IS NULL)
""", (lat, lng, label, rental_id))
conn.commit()
except Exception as exc:
print(f"[位置回填] 写起点失败 rental_id={rental_id}: {exc}")
return False
finally:
conn.close()
return True
def _finish_active_wechat_rentals(user_id: int, reason: str):
"""微信已确认没有进行中骑行时,结束本地镜像记录并取消邮件计时器。
@@ -1278,7 +1362,7 @@ def _finish_active_wechat_rentals(user_id: int, reason: str):
conn = get_db()
cursor = conn.cursor()
cursor.execute("""
SELECT id, order_id, source FROM rentals
SELECT id, order_id, source, bike_code FROM rentals
WHERE user_id = ? AND expired = 0
AND source IN ('unlock', 'sync', 'shared')
""", (user_id,))
@@ -1286,7 +1370,13 @@ def _finish_active_wechat_rentals(user_id: int, reason: str):
conn.close()
for row in active_rows:
_mark_returned(row["id"]) # 微信端自行还车:无终点坐标,只记时间
# 微信端自行还车:上游只告诉我们"订单没了",没有坐标;
# 用这辆车最新的采集点当作终点,避免后台显示「终点未知」
pos = _bike_pos_from_history(row["bike_code"])
if pos:
_mark_returned(row["id"], pos[0], pos[1])
else:
_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}")