diff --git a/routes/admin.py b/routes/admin.py index 6ebffdb..9fa8280 100644 --- a/routes/admin.py +++ b/routes/admin.py @@ -267,21 +267,29 @@ def admin_api_return(): latitude, longitude = used_point if return_result.get("rtn_code") == 0: - # 写回 expired + 实际还车时间 + 终点坐标,否则「已骑行」会一直往上爬 + # 写回 expired + 实际还车时间 + 终点坐标,否则「已骑行」会一直往上爬。 + # 上游已经还车成功,本地写库失败只记日志 —— 不能把成功报成失败, + # 否则管理员会再点一次,第二次拿到「订单信息不存在」更看不懂。 + sync_warning = "" updated = 0 try: updated = _record_rental_end(order_id, int(user_id), latitude, longitude) or 0 except Exception as exc: print(f"[管理端代还车] 回填终点失败: {exc}") - if not updated: + sync_warning = "本地记录稍后同步" + if not updated and not sync_warning: # 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() + try: + 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() + except Exception as exc: + print(f"[管理端代还车] 兜底回写失败: {exc}") + sync_warning = "本地记录稍后同步" # 尝试月卡支付 from timer import _try_card_pay_auto @@ -292,7 +300,10 @@ def admin_api_return(): conn.close() msg = "还车成功" if not use_nearest else "还车成功(已换到最近的还车点)" - return jsonify({"rtn_code": 0, "message": msg, "used_nearest": use_nearest}) + if sync_warning: + msg += f"({sync_warning})" + return jsonify({"rtn_code": 0, "message": msg, "used_nearest": use_nearest, + "local_synced": not sync_warning}) else: conn.close() tried_text = "、".join(tried) diff --git a/routes/rental.py b/routes/rental.py index 14103c5..6caae9b 100644 --- a/routes/rental.py +++ b/routes/rental.py @@ -856,10 +856,21 @@ def order_return(): """, (str(order_id), user["id"])) rental_ids = [row["id"] for row in cursor.fetchall()] conn.close() - # 统一回填:expired=1 + 实际还车时间 + 终点坐标/位置标签 - _record_rental_end(order_id, user["id"], latitude, longitude) - # 你当时真实上报的位置单独留一份(吸附后的点会失真,做分析要用原始值) - _record_raw_coords(order_id, user["id"], raw_lat, raw_lng) + # 统一回填:expired=1 + 实际还车时间 + 终点坐标/位置标签。 + # 上游已经还车成功,这两行写库失败也只记日志 —— 不能因为本地写不进去 + # 就把「还车成功」报成失败(用户会再点一次,撞上 204010 更看不懂)。 + local_sync_warning = "" + try: + _record_rental_end(order_id, user["id"], latitude, longitude) + except Exception as exc: + print(f"[order_return] 本地回填终点失败(不影响还车结果): {exc}") + local_sync_warning = "本地记录稍后同步" + try: + # 你当时真实上报的位置单独留一份(吸附后的点会失真,做分析要用原始值) + _record_raw_coords(order_id, user["id"], raw_lat, raw_lng) + except Exception as exc: + print(f"[order_return] 本地记录原始坐标失败(不影响还车结果): {exc}") + local_sync_warning = "本地记录稍后同步" for rental_id in rental_ids: _cancel_rental_timers(rental_id) _user_info_cache.pop(user["id"], None) @@ -877,9 +888,12 @@ def order_return(): success_message = "还车成功" if confirmed_by_status: success_message += "(已通过订单状态确认)" + if local_sync_warning: + success_message += f"({local_sync_warning})" return jsonify({"rtn_code": 0, "message": success_message + (f",{pay_msg}" if pay_success else ""), - "used_nearest": use_nearest, "card_pay": pay_result}) + "used_nearest": use_nearest, "card_pay": pay_result, + "local_synced": not local_sync_warning}) else: return jsonify({"rtn_code": return_result.get("rtn_code", 500), "message": return_result.get("message", "还车失败")}) diff --git a/tests/test_admin_riding_minutes.py b/tests/test_admin_riding_minutes.py index d12b458..fdfacba 100644 --- a/tests/test_admin_riding_minutes.py +++ b/tests/test_admin_riding_minutes.py @@ -110,6 +110,30 @@ class AdminReturnTests(unittest.TestCase): self.assertEqual(1, row["expired"]) self.assertTrue(row["returned_at"]) # 兜底也写了实际还车时间 + def test_admin_return_reports_success_when_local_write_fails(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), ["你上报的位置"])), \ + patch("routes.rental._record_rental_end", + side_effect=RuntimeError("database is locked")), \ + 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"]) + self.assertFalse(body["local_synced"]) + self.assertIn("本地记录稍后同步", body["message"]) + if __name__ == "__main__": unittest.main() diff --git a/tests/test_order_sync.py b/tests/test_order_sync.py index 15fdf1b..7259c70 100644 --- a/tests/test_order_sync.py +++ b/tests/test_order_sync.py @@ -673,6 +673,39 @@ class OrderSyncTests(unittest.TestCase): self.assertIn(107, recovered_ids) # subscribe 要补 self.assertNotIn(106, recovered_ids) # reminder 不补 + def test_return_succeeds_even_when_local_write_fails(self): + """上游还车成功、本地写库抛异常:不能报「还车失败」(否则用户会再点一次撞 204010)。""" + app = Flask(__name__) + app.secret_key = "test" + app.register_blueprint(rental_routes.bp) + client = app.test_client() + + def fake_auth(user_id, method, path, **kwargs): + if path == "/record/return": + return {"rtn_code": 0, "message": "ok"} + return {"rtn_code": 0, "data": {}} + + with patch.object(rental_routes, "get_db", self._get_db), \ + patch.object(rental_routes, "get_current_user", return_value={ + "id": 7, "email": "rider@example.test"}), \ + patch.object(rental_routes, "get_user_display_name", return_value="骑行人"), \ + patch.object(rental_routes, "request_with_user_auth", side_effect=fake_auth), \ + patch.object(rental_routes, "_record_rental_end", + side_effect=RuntimeError("database is locked")), \ + patch.object(rental_routes, "_record_raw_coords", + side_effect=RuntimeError("database is locked")), \ + patch.object(rental_routes, "_try_card_pay_auto", return_value={}), \ + patch.object(rental_routes, "_cancel_rental_timers"): + resp = client.post("/api/order/return", json={ + "order_id": "9001", "code": "50001", + "latitude": 36.67, "longitude": 116.98, + }) + + body = resp.get_json() + self.assertEqual(0, body["rtn_code"]) + self.assertFalse(body["local_synced"]) + self.assertIn("本地记录稍后同步", body["message"]) + def test_retry_success_sends_final_notice(self): """重试后终于还上,要再发一封收尾,别让用户去点旧邮件里的还车按钮。""" class ImmediateTimer: diff --git a/timer.py b/timer.py index d581e22..4e1a32f 100644 --- a/timer.py +++ b/timer.py @@ -916,8 +916,7 @@ def _recover_overdue_rental(rental: dict): if not user_id: print(f"[计时系统] rental_id={rental_id} 没有 user_id,跳过补还车") return - result = _run_recovery(rental_id, user_id) if _should_auto_return(rental) \ - else auto_return_bike(rental_id, user_id) + result = _run_recovery(rental_id, user_id) print(f"[计时系统] 补还车结果 rental_id={rental_id}: {result.get('message')}") except Exception as exc: print(f"[计时系统] 补还车异常 rental_id={rental_id}: {exc}")