#!/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()