diff --git a/scripts/backfill_rental_locations.py b/scripts/backfill_rental_locations.py new file mode 100644 index 0000000..0e587e2 --- /dev/null +++ b/scripts/backfill_rental_locations.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""一次性回填订单起终点坐标(给历史数据用)。 + +背景:`source='sync'` 的单是从上游"发现"的订单,`/record/detail` 只给分钟数和车牌, +没有坐标,所以订单表里一直显示「起点未知 / 终点未知」。新写入的 sync 单已经在 +`timer._check_user_order` 里回填了(用 bike_history 里开始时间附近的采集点), +这个脚本负责把**历史**的单也补上。 + +用法: + python scripts/backfill_rental_locations.py # dry-run,只统计 + python scripts/backfill_rental_locations.py --apply # 真正写库 + +判定规则: +- 起点:`start_latitude` 为空 且 `start_time` 落在 bike_history 保留期内(30 天), + 取该时刻 ±15 分钟最近的采集点; +- 终点:`expired=1` 且 `end_latitude` 为空,取 `returned_at`(没有就用 `end_time`) + ±15 分钟最近的采集点; +- 取不到就跳过,不编造坐标。 +""" +import argparse +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +os.environ.setdefault("XBCR_DISABLE_BACKGROUND", "1") + +import timer # noqa: E402 +from db import get_db # noqa: E402 + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--apply", action="store_true", help="真正写库(默认 dry-run)") + parser.add_argument("--limit", type=int, default=5000, help="最多处理多少行") + args = parser.parse_args() + + conn = get_db() + conn.row_factory = None + # reminder 是纯本地计时(没有真实骑行/没有车在动),补坐标没有意义 + starts = conn.execute( + "SELECT id, bike_code, start_time FROM rentals " + "WHERE (start_latitude IS NULL OR start_longitude IS NULL) " + " AND start_time IS NOT NULL AND COALESCE(source, '') != 'reminder' " + "ORDER BY id DESC LIMIT ?", (args.limit,)).fetchall() + ends = conn.execute( + "SELECT id, bike_code, end_time, returned_at FROM rentals " + "WHERE expired = 1 AND (end_latitude IS NULL OR end_longitude IS NULL) " + " AND COALESCE(source, '') != 'reminder' " + "ORDER BY id DESC LIMIT ?", (args.limit,)).fetchall() + conn.close() + + print(f"待补起点 {len(starts)} 行,待补终点 {len(ends)} 行" + f"({'写库' if args.apply else 'dry-run'})") + + filled_start = filled_end = 0 + for rid, code, start_time in starts: + pos = timer._bike_pos_from_history(code, start_time) + if not pos: + continue + if args.apply: + timer._fill_missing_start(rid, code, start_time) + else: + print(f" [起点] rental_id={rid} code={code} t={start_time} → {pos}") + filled_start += 1 + + for rid, code, end_time, returned_at in ends: + when = returned_at or end_time + pos = timer._bike_pos_from_history(code, when) if when else None + if not pos: + continue + if args.apply: + timer._mark_returned(rid, pos[0], pos[1]) + else: + print(f" [终点] rental_id={rid} code={code} t={when} → {pos}") + filled_end += 1 + + print(f"可补:起点 {filled_start} 行、终点 {filled_end} 行" + + ("" if args.apply else "(加 --apply 才会写入)")) + + +if __name__ == "__main__": + main() diff --git a/tests/test_order_sync.py b/tests/test_order_sync.py index d07e392..53c0a63 100644 --- a/tests/test_order_sync.py +++ b/tests/test_order_sync.py @@ -47,7 +47,11 @@ class OrderSyncTests(unittest.TestCase): notified_2 INTEGER DEFAULT 0, notified_1 INTEGER DEFAULT 0, notified_0 INTEGER DEFAULT 0, - renewal_round INTEGER DEFAULT 1 + renewal_round INTEGER DEFAULT 1, + start_latitude REAL, start_longitude REAL, start_label TEXT, + end_latitude REAL, end_longitude REAL, end_label TEXT, + returned_at TEXT, raw_latitude REAL, raw_longitude REAL, + rounds_override INTEGER ); INSERT INTO users (id, email) VALUES (7, 'rider@example.test'); INSERT INTO users (id, email) VALUES (8, 'shared-rider@example.test'); @@ -56,7 +60,15 @@ class OrderSyncTests(unittest.TestCase): VALUES (101, '9001', 7, 'sync', 0, '2026-01-01 08:00:00', '2099-01-01 00:00:00'), (102, NULL, 7, 'reminder', 0, '2026-01-01 08:00:00', '2099-01-01 00:00:00'); - """) + CREATE TABLE bike_history ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + bike_code TEXT NOT NULL, + latitude REAL, longitude REAL, + status INTEGER DEFAULT 1, state INTEGER DEFAULT 1, + electric REAL DEFAULT 100, + recorded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP + ); +""") conn.commit() conn.close() @@ -538,6 +550,68 @@ class OrderSyncTests(unittest.TestCase): auto_return.assert_called_once_with(101, 7) notify.assert_not_called() + def test_sync_rental_backfills_start_from_bike_history(self): + """sync 单没有坐标:用开始时间附近的采集点回填起点,别显示「起点未知」。""" + active = {"rtn_code": 0, "data": {"nonDealOrder": { + "order_id": "9101", "status": 2, "code": "60001" + }}} + detail = {"rtn_code": 0, "data": {"minutes": 5, "code": "60001"}} + settings = {"reminder_enabled": False, "reminder_minutes": [], + "rental_duration_minutes": 19, "auto_return_enabled": False} + + def fake_auth(user_id, method, path, **kwargs): + if path == "/user/info": + return active + if path == "/record/detail": + return detail + return {"rtn_code": 0, "data": {}} + + with patch.object(timer, "get_db", self._get_db), \ + patch.object(timer, "get_user_auth", return_value=("token", "access")), \ + patch.object(timer, "get_user_rental_settings", return_value=settings), \ + patch.object(timer, "request_with_user_auth", side_effect=fake_auth), \ + patch.object(timer, "start_rental_timer"), \ + patch.object(timer, "_bike_pos_from_history", return_value=(36.5318, 116.7802)), \ + patch("campus.resolve_location_label", return_value="博学楼附近", create=True): + timer._check_user_order(7) + + conn = self._get_db() + row = conn.execute( + "SELECT start_latitude, start_longitude, start_label FROM rentals " + "WHERE order_id = '9101'").fetchone() + conn.close() + self.assertIsNotNone(row) + self.assertAlmostEqual(36.5318, row["start_latitude"], places=4) + self.assertAlmostEqual(116.7802, row["start_longitude"], places=4) + self.assertEqual("博学楼附近", row["start_label"]) + + def test_wechat_side_return_fills_end_position_from_history(self): + """微信端自行还车:上游不给坐标,用最新采集点补终点。""" + conn = self._get_db() + conn.execute(""" + INSERT INTO rentals + (id, order_id, user_id, source, expired, start_time, end_time, bike_code, email) + VALUES (103, '9103', 7, 'sync', 0, '2026-01-01 09:00:00', + '2099-01-01 00:00:00', '60003', 'rider@example.test') + """) + conn.commit() + conn.close() + + with patch.object(timer, "get_db", self._get_db), \ + patch.object(timer, "_bike_pos_from_history", return_value=(36.5321, 116.7805)), \ + patch("campus.resolve_location_label", return_value="图书馆附近", create=True): + timer._finish_active_wechat_rentals(7, "测试:上游已无订单") + + conn = self._get_db() + row = conn.execute( + "SELECT expired, end_latitude, end_longitude, end_label FROM rentals WHERE id = 103" + ).fetchone() + conn.close() + self.assertEqual(1, row["expired"]) + self.assertAlmostEqual(36.5321, row["end_latitude"], places=4) + self.assertEqual("图书馆附近", row["end_label"]) + + def test_auto_return_failure_keeps_notified_zero_and_schedules_retry(self): """上游还车失败时不能把 notified_0 置位,否则这一单再也不会重试。""" class ImmediateTimer: diff --git a/timer.py b/timer.py index eed9a60..ee0fa5f 100644 --- a/timer.py +++ b/timer.py @@ -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}")