fix: 巡检补还车节流 + 管理端代还车复用换点重试 + 回填实际还车时间
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 全绿
This commit is contained in:
+23
-21
@@ -254,27 +254,26 @@ def admin_api_return():
|
|||||||
latitude = pos["lat"]
|
latitude = pos["lat"]
|
||||||
longitude = pos["lng"]
|
longitude = pos["lng"]
|
||||||
|
|
||||||
# 先校验当前位置是否为合法还车点;不在还车点则选择最近停车点(与用户端 order_return 一致)
|
# 与用户端还车同一条链路:先发原坐标,失败再按候选点换点重试
|
||||||
check_result = request_with_user_auth(
|
# (自动还车因坐标失败 → 邮件叫管理员代还,代还却用单点老逻辑就永远还不上)
|
||||||
int(user_id), "POST", "/record/checkLocation",
|
from routes.rental import _try_return_candidates, _record_rental_end
|
||||||
data={"longitude": longitude, "latitude": latitude, "bicycleCode": rental["bike_code"]}, _silent=True)
|
upstream_order_id = int(order_id) if str(order_id).isdigit() else order_id
|
||||||
use_nearest = False
|
return_result, used_point, tried = _try_return_candidates(
|
||||||
if check_result.get("rtn_code") != 0 or check_result.get("parkNoShow") is True:
|
int(user_id), upstream_order_id, rental["bike_code"],
|
||||||
from routes.rental import get_nearest_park_point
|
float(latitude), float(longitude)
|
||||||
nearest = get_nearest_park_point(latitude, longitude, int(user_id))
|
)
|
||||||
if nearest:
|
use_nearest = len(tried) > 1
|
||||||
latitude = nearest.get("latitude") or nearest.get("lat")
|
if use_nearest:
|
||||||
longitude = nearest.get("longitude") or nearest.get("lng")
|
latitude, longitude = used_point
|
||||||
use_nearest = True
|
|
||||||
|
|
||||||
return_result = request_with_user_auth(int(user_id), "POST", "/record/return", data={
|
|
||||||
"order_id": int(order_id) if str(order_id).isdigit() else order_id,
|
|
||||||
"longitude": longitude, "latitude": latitude, "code": rental["bike_code"]
|
|
||||||
})
|
|
||||||
|
|
||||||
if return_result.get("rtn_code") == 0:
|
if return_result.get("rtn_code") == 0:
|
||||||
cursor.execute("UPDATE rentals SET expired = 1 WHERE id = ?", (rental_id,))
|
# 写回 expired + 实际还车时间 + 终点坐标,否则「已骑行」会一直往上爬
|
||||||
conn.commit()
|
try:
|
||||||
|
_record_rental_end(order_id, int(user_id), latitude, longitude)
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[管理端代还车] 回填终点失败: {exc}")
|
||||||
|
cursor.execute("UPDATE rentals SET expired = 1 WHERE id = ?", (rental_id,))
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
# 尝试月卡支付
|
# 尝试月卡支付
|
||||||
from timer import _try_card_pay_auto
|
from timer import _try_card_pay_auto
|
||||||
@@ -284,11 +283,14 @@ def admin_api_return():
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
conn.close()
|
conn.close()
|
||||||
return jsonify({"rtn_code": 0, "message": "还车成功"})
|
msg = "还车成功" if not use_nearest else "还车成功(已换到最近的还车点)"
|
||||||
|
return jsonify({"rtn_code": 0, "message": msg, "used_nearest": use_nearest})
|
||||||
else:
|
else:
|
||||||
conn.close()
|
conn.close()
|
||||||
|
tried_text = "、".join(tried)
|
||||||
return jsonify({"rtn_code": return_result.get("rtn_code", 500),
|
return jsonify({"rtn_code": return_result.get("rtn_code", 500),
|
||||||
"message": return_result.get("message", "还车失败")})
|
"message": (return_result.get("message") or "还车失败")
|
||||||
|
+ f"(已尝试 {len(tried)} 个位置:{tried_text})"})
|
||||||
|
|
||||||
|
|
||||||
@bp.route("/api/admin/unlock", methods=["POST"])
|
@bp.route("/api/admin/unlock", methods=["POST"])
|
||||||
|
|||||||
@@ -1,9 +1,14 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
"""管理员订单列表:已骑行分钟数。"""
|
"""管理员订单列表:已骑行分钟数。"""
|
||||||
import datetime as dt
|
import datetime as dt
|
||||||
|
import sqlite3
|
||||||
|
import tempfile
|
||||||
import unittest
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from flask import Flask
|
||||||
|
|
||||||
from routes import admin as admin_routes
|
from routes import admin as admin_routes
|
||||||
|
|
||||||
|
|
||||||
@@ -24,5 +29,62 @@ class RidingMinutesTests(unittest.TestCase):
|
|||||||
self.assertEqual(0, admin_routes._riding_minutes({"start_time": "not-a-date"}))
|
self.assertEqual(0, admin_routes._riding_minutes({"start_time": "not-a-date"}))
|
||||||
|
|
||||||
|
|
||||||
|
class AdminReturnTests(unittest.TestCase):
|
||||||
|
"""管理端代还车必须复用「换点重试」链路,并回填实际还车时间。"""
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
self.tmp = tempfile.TemporaryDirectory()
|
||||||
|
self.db_path = Path(self.tmp.name) / "admin.db"
|
||||||
|
conn = sqlite3.connect(self.db_path)
|
||||||
|
conn.executescript("""
|
||||||
|
CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT);
|
||||||
|
CREATE TABLE rentals (
|
||||||
|
id INTEGER PRIMARY KEY, order_id TEXT, bike_code TEXT, email TEXT,
|
||||||
|
user_id INTEGER, source TEXT, expired INTEGER DEFAULT 0,
|
||||||
|
start_time TEXT, end_time TEXT, returned_at TEXT,
|
||||||
|
end_latitude REAL, end_longitude REAL, end_label TEXT
|
||||||
|
);
|
||||||
|
INSERT INTO users (id, email) VALUES (7, 'rider@example.test');
|
||||||
|
INSERT INTO rentals (id, order_id, bike_code, email, user_id, source,
|
||||||
|
expired, start_time, end_time)
|
||||||
|
VALUES (101, '9001', '50001', 'rider@example.test', 7, 'unlock',
|
||||||
|
0, '2026-01-01 09:00:00', '2026-01-01 09:19:00');
|
||||||
|
""")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
self.tmp.cleanup()
|
||||||
|
|
||||||
|
def _get_db(self):
|
||||||
|
conn = sqlite3.connect(self.db_path)
|
||||||
|
conn.row_factory = sqlite3.Row
|
||||||
|
return conn
|
||||||
|
|
||||||
|
def test_admin_return_uses_candidate_chain_and_records_returned_at(self):
|
||||||
|
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),
|
||||||
|
["你上报的位置", "附近停车区"])) as chain, \
|
||||||
|
patch("routes.rental._record_rental_end") as record_end, \
|
||||||
|
patch("timer._try_card_pay_auto", return_value={}):
|
||||||
|
resp = client.post("/api/admin/return", json={"rental_id": 101, "user_id": 7})
|
||||||
|
|
||||||
|
body = resp.get_json()
|
||||||
|
self.assertEqual(0, body["rtn_code"])
|
||||||
|
chain.assert_called_once()
|
||||||
|
record_end.assert_called_once() # 回填 returned_at + 终点
|
||||||
|
self.assertIn("used_nearest", body)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|||||||
@@ -712,6 +712,46 @@ class OrderSyncTests(unittest.TestCase):
|
|||||||
timer._auto_return_retries.pop(101, None)
|
timer._auto_return_retries.pop(101, None)
|
||||||
alert.assert_called_once()
|
alert.assert_called_once()
|
||||||
|
|
||||||
|
def test_checker_throttles_repeated_recovery_attempts(self):
|
||||||
|
"""彻底还不上时,巡检不能每分钟重打上游(5 分钟一次)。"""
|
||||||
|
class ImmediateThread:
|
||||||
|
def __init__(self, target=None, args=(), **kwargs):
|
||||||
|
self.target, self.args = target, args
|
||||||
|
def start(self):
|
||||||
|
if self.target:
|
||||||
|
self.target(*self.args)
|
||||||
|
|
||||||
|
conn = self._get_db()
|
||||||
|
conn.execute("""
|
||||||
|
INSERT INTO rentals
|
||||||
|
(id, order_id, user_id, source, expired, start_time, end_time, bike_code, email)
|
||||||
|
VALUES (108, '9008', 7, 'unlock', 0, '2026-01-01 09:00:00',
|
||||||
|
'2026-01-01 09:19:00', '50008', 'rider@example.test')
|
||||||
|
""")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
active = {"rtn_code": 0, "data": {"nonDealOrder": {
|
||||||
|
"order_id": "9008", "status": 2, "code": "50008"
|
||||||
|
}}}
|
||||||
|
timer._recover_last_at.clear()
|
||||||
|
try:
|
||||||
|
with patch.object(timer, "get_db", self._get_db), \
|
||||||
|
patch.object(timer, "get_user_auth", return_value=("token", "access")), \
|
||||||
|
patch.object(timer.threading, "Thread", ImmediateThread), \
|
||||||
|
patch.object(timer, "request_with_user_auth", return_value=active), \
|
||||||
|
patch.object(timer, "auto_return_bike", return_value={
|
||||||
|
"success": False, "message": "boom"
|
||||||
|
}) as auto_return:
|
||||||
|
first = timer._check_user_order(7)
|
||||||
|
second = timer._check_user_order(7)
|
||||||
|
finally:
|
||||||
|
timer._recover_last_at.clear()
|
||||||
|
|
||||||
|
self.assertTrue(first.get("recovered"))
|
||||||
|
self.assertTrue(second.get("recovering")) # 第二次被节流
|
||||||
|
self.assertEqual(1, auto_return.call_count) # 只补了一次
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|||||||
@@ -570,6 +570,21 @@ def _cancel_rental_timers(rental_id: int):
|
|||||||
AUTO_RETURN_SOURCES = ("unlock", "sync", "shared", "subscribe")
|
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:
|
def _should_auto_return(rental) -> bool:
|
||||||
"""这张单能不能走上游自动还车(restore / 巡检共用同一判断)。"""
|
"""这张单能不能走上游自动还车(restore / 巡检共用同一判断)。"""
|
||||||
if not rental:
|
if not rental:
|
||||||
@@ -697,8 +712,7 @@ def _schedule_reminder(rental_id: int, delay_seconds: int, reminder_type: str,
|
|||||||
|
|
||||||
# 5/3/2/1 分钟这类纯提醒:先置位再发,发失败也不重发
|
# 5/3/2/1 分钟这类纯提醒:先置位再发,发失败也不重发
|
||||||
if reminder_type != "0":
|
if reminder_type != "0":
|
||||||
cursor.execute(f"UPDATE rentals SET {col} = 1 WHERE id = ?", (rental_id,))
|
_mark_notified(rental_id, reminder_type, conn=conn, cursor=cursor)
|
||||||
conn.commit()
|
|
||||||
conn.close()
|
conn.close()
|
||||||
if send_notification:
|
if send_notification:
|
||||||
send_rental_notification(rental_id, reminder_type, None)
|
send_rental_notification(rental_id, reminder_type, None)
|
||||||
@@ -1000,6 +1014,11 @@ def _check_user_order(user_id: int):
|
|||||||
# 只有「真的有上游订单」的来源才补(reminder 之类拿本地 id 当订单号必然失败)。
|
# 只有「真的有上游订单」的来源才补(reminder 之类拿本地 id 当订单号必然失败)。
|
||||||
if _should_auto_return(rental) and _rental_end_time_passed(rental):
|
if _should_auto_return(rental) and _rental_end_time_passed(rental):
|
||||||
conn.close()
|
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']} 已过到期时间,补一次自动还车")
|
print(f"[订单检测] rental_id={rental['id']} 已过到期时间,补一次自动还车")
|
||||||
threading.Thread(
|
threading.Thread(
|
||||||
target=lambda: auto_return_bike(rental["id"], user_id),
|
target=lambda: auto_return_bike(rental["id"], user_id),
|
||||||
|
|||||||
Reference in New Issue
Block a user