polish: 还车回填返回行数 + 管理端兜底 + 节流记录成功即清理

1) _record_rental_end 返回命中行数
- _set_rental_finished 返回 cursor.rowcount,_record_rental_end 透传;
  管理端代还车能知道「order_id 没匹配到任何一行」(脏 order_id 场景)

2) 管理端代还车兜底
- 回填命中 0 行时按 rental_id 补一次 UPDATE(expired=1 + returned_at),
  后台立刻正确,不再等下一轮巡检自愈

3) _recover_last_at 成功后清理
- 新增 _run_recovery(rental_id, user_id):成功清掉节流记录,失败保留;
  巡检与重启补还车都改走它

测试:154 pytest(新增脏 order_id 兜底、节流清理 2 条)+ 32 node 全绿
This commit is contained in:
zzy
2026-11-15 18:28:27 +08:00
parent 7181973c1f
commit 9b1aac9942
5 changed files with 83 additions and 9 deletions
+10 -2
View File
@@ -268,11 +268,19 @@ def admin_api_return():
if return_result.get("rtn_code") == 0:
# 写回 expired + 实际还车时间 + 终点坐标,否则「已骑行」会一直往上爬
updated = 0
try:
_record_rental_end(order_id, int(user_id), latitude, longitude)
updated = _record_rental_end(order_id, int(user_id), latitude, longitude) or 0
except Exception as exc:
print(f"[管理端代还车] 回填终点失败: {exc}")
cursor.execute("UPDATE rentals SET expired = 1 WHERE id = ?", (rental_id,))
if not updated:
# order_id 是脏字符串之类没匹配到行:按 rental_id 兜底,后台立刻正确
print(f"[管理端代还车] order_id={order_id} 未匹配到进行中的单,按 rental_id={rental_id} 兜底")
cursor.execute(
"UPDATE rentals SET expired = 1, returned_at = COALESCE(returned_at, ?) "
"WHERE id = ?",
(dt.datetime.now(dt.timezone(dt.timedelta(hours=8))).strftime("%Y-%m-%d %H:%M:%S"),
rental_id))
conn.commit()
# 尝试月卡支付
+12 -4
View File
@@ -512,7 +512,7 @@ def _set_rental_finished(conn, where_sql, where_params, latitude, longitude):
"""
params = (now_str, end_lat, end_lng, label, *where_params)
try:
conn.execute(sql, params)
cursor = conn.execute(sql, params)
except Exception as e:
if "no such column" not in str(e).lower():
raise
@@ -523,7 +523,10 @@ def _set_rental_finished(conn, where_sql, where_params, latitude, longitude):
conn.execute(f"ALTER TABLE rentals ADD COLUMN {col_def[0]} {col_def[1]}")
except Exception:
pass
conn.execute(sql, params)
cursor = conn.execute(sql, params)
# 返回命中行数:调用方(管理端代还车)需要知道「没匹配到任何一行」,
# 比如库里 order_id 是脏字符串时,否则后台会继续显示「进行中」
return cursor.rowcount
def _record_raw_coords(order_id: str, user_id: int, latitude, longitude):
@@ -560,12 +563,17 @@ def _record_raw_coords(order_id: str, user_id: int, latitude, longitude):
def _record_rental_end(order_id: str, user_id: int, latitude, longitude):
"""标记订单结束:实际还车时间 + 终点坐标与位置标签。"""
"""标记订单结束:实际还车时间 + 终点坐标与位置标签。
返回命中的行数(0 表示这条 order_id 在库里没匹配到进行中的单)。
"""
conn = get_db()
try:
_set_rental_finished(conn, "WHERE order_id = ? AND user_id = ? AND expired = 0",
updated = _set_rental_finished(
conn, "WHERE order_id = ? AND user_id = ? AND expired = 0",
(str(order_id), user_id), latitude, longitude)
conn.commit()
return updated
finally:
conn.close()
+25
View File
@@ -85,6 +85,31 @@ class AdminReturnTests(unittest.TestCase):
record_end.assert_called_once() # 回填 returned_at + 终点
self.assertIn("used_nearest", body)
def test_admin_return_falls_back_to_rental_id_when_order_id_matches_nothing(self):
"""order_id 是脏字符串、回填命中 0 行时,仍要按 rental_id 把单子收掉。"""
app = Flask(__name__)
app.secret_key = "test"
app.register_blueprint(admin_routes.bp)
client = app.test_client()
with client.session_transaction() as sess:
sess["admin_logged_in"] = True
with patch.object(admin_routes, "get_db", self._get_db), \
patch.object(admin_routes, "request_with_user_auth", return_value={
"rtn_code": 0, "data": {"latitude": 36.53, "longitude": 116.78}}), \
patch("routes.rental._try_return_candidates",
return_value=({"rtn_code": 0}, (36.53, 116.78), ["你上报的位置"])), \
patch("routes.rental._record_rental_end", return_value=0), \
patch("timer._try_card_pay_auto", return_value={}):
resp = client.post("/api/admin/return", json={"rental_id": 101, "user_id": 7})
self.assertEqual(0, resp.get_json()["rtn_code"])
conn = self._get_db()
row = conn.execute("SELECT expired, returned_at FROM rentals WHERE id = 101").fetchone()
conn.close()
self.assertEqual(1, row["expired"])
self.assertTrue(row["returned_at"]) # 兜底也写了实际还车时间
if __name__ == "__main__":
unittest.main()
+20
View File
@@ -752,6 +752,26 @@ class OrderSyncTests(unittest.TestCase):
self.assertTrue(second.get("recovering")) # 第二次被节流
self.assertEqual(1, auto_return.call_count) # 只补了一次
def test_recovery_success_clears_throttle_record(self):
"""补还车成功后要清掉节流记录,别在进程里留失败痕迹。"""
timer._recover_last_at[109] = timer._time.time()
try:
with patch.object(timer, "auto_return_bike", return_value={
"success": True, "message": "ok"
}):
timer._run_recovery(109, 7)
self.assertNotIn(109, timer._recover_last_at)
timer._recover_last_at[110] = timer._time.time()
with patch.object(timer, "auto_return_bike", return_value={
"success": False, "message": "boom"
}):
timer._run_recovery(110, 7)
self.assertIn(110, timer._recover_last_at) # 失败保留,供节流判断
finally:
timer._recover_last_at.pop(109, None)
timer._recover_last_at.pop(110, None)
if __name__ == "__main__":
unittest.main()
+15 -2
View File
@@ -585,6 +585,18 @@ def _recover_throttled(rental_id: int) -> bool:
return False
def _run_recovery(rental_id: int, user_id: int):
"""巡检/重启的补还车入口:成功后清掉节流记录,别让进程里留失败痕迹。"""
try:
result = auto_return_bike(rental_id, user_id) or {}
if result.get("success"):
_recover_last_at.pop(rental_id, None)
return result
except Exception as exc:
print(f"[自动还车] 补还车异常 rental_id={rental_id}: {exc}")
return {"success": False, "message": str(exc)}
def _should_auto_return(rental) -> bool:
"""这张单能不能走上游自动还车(restore / 巡检共用同一判断)。"""
if not rental:
@@ -904,7 +916,8 @@ def _recover_overdue_rental(rental: dict):
if not user_id:
print(f"[计时系统] rental_id={rental_id} 没有 user_id,跳过补还车")
return
result = auto_return_bike(rental_id, user_id)
result = _run_recovery(rental_id, user_id) if _should_auto_return(rental) \
else 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}")
@@ -1021,7 +1034,7 @@ def _check_user_order(user_id: int):
"recovering": True}
print(f"[订单检测] rental_id={rental['id']} 已过到期时间,补一次自动还车")
threading.Thread(
target=lambda: auto_return_bike(rental["id"], user_id),
target=lambda: _run_recovery(rental["id"], user_id),
daemon=True
).start()
return {"ok": True, "active": True, "order_id": order_id,