From 32d3b8d4262c8448e07d2ad68b2d27ce4ab0a819 Mon Sep 17 00:00:00 2001 From: NekoYume517 <3146527494@qq.com> Date: Sun, 15 Nov 2026 22:34:53 +0800 Subject: [PATCH] =?UTF-8?q?fix(=E6=89=B9=E6=AC=A1A):=20=E6=98=8E=E6=96=87?= =?UTF-8?q?=E7=9B=91=E5=90=AC=E3=80=81=E7=BB=AD=E7=A7=9F=E6=8D=A2=E5=8D=95?= =?UTF-8?q?=E5=90=8E=E5=81=87=E6=88=90=E5=8A=9F=E3=80=81share=20=E5=81=87?= =?UTF-8?q?=E6=88=90=E5=8A=9F=E3=80=81=E5=BC=80=E9=94=81=E5=A4=B1=E8=B4=A5?= =?UTF-8?q?=E4=B8=8D=E6=92=A4=E5=8D=95=E3=80=81admin=20=E5=8F=A3=E4=BB=A4?= =?UTF-8?q?=E5=93=88=E5=B8=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - app.py:默认监听改 127.0.0.1(原本 0.0.0.0,与同文件注释矛盾, 明文 HTTP 可直取 Bearer token/access_token;需要时用 XBCR_HOST 显式放宽) - admin 口令:支持 admin_password_hash(pbkdf2)+ 恒定时间比较, 登录成功写 session.permanent;本地 admin_config 已改为哈希存储(口令 070517zhan) - timer._auto_return_bike:读完行立刻关连接(原来一直挂到函数末尾,中途异常就泄漏); 还车成功后 pop routes.rental._user_info_cache —— 续租会换 order_id, 不清缓存的话前端 60 秒内还车会拿到旧单号被判「已结束」,而车已在第 2 轮计费 - timer._mark_returned:try/finally 关连接 - timer 复活 expired=1 的行时同时复位 notified_*(否则提醒与 0 分钟自动还车永久失效, 极简 schema 无这些列时自动回退) - routes/share.py:_upstream_order_finished 补「同车牌仍在骑行」兜底(与 rental 版对齐); 204010/「订单信息不存在」直接硬拒,不再走状态确认假成功 - routes/rental.py 开锁失败:调用 _discard_pending_order 撤销半成品订单 (上游不残留未支付单,避免下次开锁用月卡替它付钱); rentals.id 撞历史自增行时改用 lastrowid,计时器不再挂到别人单上 - subscribe 自动开锁落单冲突兜底:改用 lastrowid 当 rental_id 测试:161 pytest + 32 node 全绿 --- app.py | 6 ++- routes/admin.py | 38 ++++++++++++++++-- routes/rental.py | 46 ++++++++++++++++------ routes/share.py | 30 ++++++++++---- static/js/map.js | 3 ++ static/js/navigation.js | 38 ++++++++++++++---- subscribe.py | 37 ++++++++++++------ timer.py | 87 +++++++++++++++++++++++++++-------------- 8 files changed, 214 insertions(+), 71 deletions(-) diff --git a/app.py b/app.py index 95ec8ae..a7f2aae 100644 --- a/app.py +++ b/app.py @@ -728,4 +728,8 @@ if __name__ == "__main__": # 只监听本机回环:对外统一走 nginx 的 HTTPS(同机回环转发到本端口)。 # 绑定 0.0.0.0 会让明文 HTTP 绕过 nginx 直接暴露,token/凭据可被局域网窃听。 print(f"[启动] HTTP 服务: http://127.0.0.1:{PORT} (请由 nginx 反代对外提供 HTTPS)") - app.run(host=os.environ.get("XBCR_HOST","0.0.0.0"), port=int(os.environ.get("XBCR_PORT",PORT)), debug=False) + # 默认只听回环:对外统一由 nginx 反代 HTTPS。绑定 0.0.0.0 会让明文 HTTP + # 绕过 nginx 直接暴露,Bearer token / access_token 可被同网段窃听。 + # 需要直连(例如容器内自测)时显式设 XBCR_HOST。 + app.run(host=os.environ.get("XBCR_HOST", "127.0.0.1"), + port=int(os.environ.get("XBCR_PORT", PORT)), debug=False) diff --git a/routes/admin.py b/routes/admin.py index 9fa8280..4551998 100644 --- a/routes/admin.py +++ b/routes/admin.py @@ -27,7 +27,7 @@ ADMIN_LOGIN_LOCK_SECONDS = 15 * 60 def _load_admin_config() -> dict: - cfg = {"admin_username": "", "admin_password": ""} + cfg = {"admin_username": "", "admin_password": "", "admin_password_hash": ""} try: if _ADMIN_CONFIG_PATH.exists(): for line in _ADMIN_CONFIG_PATH.read_text("utf-8").splitlines(): @@ -42,6 +42,35 @@ def _load_admin_config() -> dict: return cfg +def _verify_admin_password(cfg: dict, password: str) -> bool: + """校验管理员口令:优先比对 pbkdf2 哈希,其次明文(老配置兼容)。 + + 两边都用恒定时间比较,避免按响应时间猜口令。 + """ + import hmac + + pwd = password or "" + hash_value = (cfg.get("admin_password_hash") or "").strip() + if hash_value: + try: + from werkzeug.security import check_password_hash + return check_password_hash(hash_value, pwd) + except Exception as exc: + print(f"[admin配置] 口令哈希校验失败: {exc}") + return False + plain = (cfg.get("admin_password") or "").strip() + if not plain: + return False + return hmac.compare_digest(pwd.encode("utf-8"), plain.encode("utf-8")) + + +def hash_admin_password(password: str) -> str: + """生成可写进 admin_config.txt 的口令哈希(部署/运维用)。""" + from werkzeug.security import generate_password_hash + return generate_password_hash(password) + + + def _nearby_coord(lat, lng, jitter=0.0001): """在车辆坐标附近加随机抖动,模拟真实定位(避免每次上报同一精确点被判远程操作)""" try: @@ -91,10 +120,13 @@ def admin_login(): return jsonify({"rtn_code": 429, "message": f"失败次数过多,请 {max(wait_seconds // 60, 1)} 分钟后再试"}), 429 return _login_page(f"失败次数过多,请 {max(wait_seconds // 60, 1)} 分钟后再试"), 429 - if (cfg["admin_username"] and cfg["admin_password"] - and username == cfg["admin_username"] and password == cfg["admin_password"]): + if (cfg["admin_username"] + and (cfg.get("admin_password_hash") or cfg.get("admin_password")) + and username == cfg["admin_username"] + and _verify_admin_password(cfg, password)): rate_limit.record_success(rl_key) session["admin_logged_in"] = True + session.permanent = True # 配合 PERMANENT_SESSION_LIFETIME 过期 if request.is_json: return jsonify({"rtn_code": 0, "message": "登录成功"}) return redirect("/admin") diff --git a/routes/rental.py b/routes/rental.py index 6caae9b..83d58dc 100644 --- a/routes/rental.py +++ b/routes/rental.py @@ -4,6 +4,7 @@ import json import math import random +import sqlite3 import datetime as dt import threading import time @@ -670,23 +671,37 @@ def order_unlock(): end_time = now_beijing + dt.timedelta(minutes=duration) conn = get_db() cursor = conn.cursor() - cursor.execute(""" - INSERT INTO rentals (id, order_id, bike_code, email, user_id, start_time, end_time, - duration, expired, source) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, 'unlock') - """, (int(order_id), order_id, code, user["email"], user["id"], - now_beijing.strftime("%Y-%m-%d %H:%M:%S"), - end_time.strftime("%Y-%m-%d %H:%M:%S"), duration)) + try: + cursor.execute(""" + INSERT INTO rentals (id, order_id, bike_code, email, user_id, start_time, end_time, + duration, expired, source) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, 'unlock') + """, (int(order_id), order_id, code, user["email"], user["id"], + now_beijing.strftime("%Y-%m-%d %H:%M:%S"), + end_time.strftime("%Y-%m-%d %H:%M:%S"), duration)) + rental_row_id = int(order_id) + except sqlite3.IntegrityError: + # rentals.id 可能被 reminder/sync 的自增行占用(序列漂移):改用自增 id, + # order_id 仍记录真实上游单号。用 lastrowid 当 rental_id,别把计时器挂到别人单上。 + print(f"[开锁] rentals.id={order_id} 已被占用,改用自增 id") + cur2 = conn.execute(""" + INSERT INTO rentals (order_id, bike_code, email, user_id, start_time, end_time, + duration, expired, source) + VALUES (?, ?, ?, ?, ?, ?, ?, 0, 'unlock') + """, (order_id, code, user["email"], user["id"], + now_beijing.strftime("%Y-%m-%d %H:%M:%S"), + end_time.strftime("%Y-%m-%d %H:%M:%S"), duration)) + rental_row_id = cur2.lastrowid conn.commit() conn.close() - start_rental_timer(rental_id=int(order_id), email=user["email"], + start_rental_timer(rental_id=int(rental_row_id), email=user["email"], bike_code=code, duration_minutes=duration, user_id=user["id"]) - _record_rental_start(int(order_id), latitude, longitude) + _record_rental_start(int(rental_row_id), latitude, longitude) # 带上轮次预估:前端租车条要显示「共N轮 · 预计HH:MM还车」 row = get_db().execute( "SELECT renewal_round, rounds_override, end_time FROM rentals WHERE id = ?", - (int(order_id),)).fetchone() + (int(rental_row_id),)).fetchone() summary = _rounds_summary( dict(row) if row else {"order_id": str(order_id), "end_time": end_time.strftime("%Y-%m-%d %H:%M:%S")}, @@ -696,10 +711,19 @@ def order_unlock(): else: from wechat import friendly_upstream_message raw_open_msg = open_result.get("message", "") + # 上车失败必须把刚下的单撤掉,否则上游留一张没人骑的「未支付」订单; + # 下次开锁命中「未支付」分支时会用月卡把它付掉 —— 白扣一次卡次。 + try: + from subscribe import _discard_pending_order + cleaned = _discard_pending_order(user["id"], order_id, code, latitude, longitude) + except Exception as exc: + cleaned = False + print(f"[开锁] 撤销半成品订单异常: {exc}") if open_result.get("rtn_code") == 102001 or "token" in raw_open_msg.lower(): return jsonify({"rtn_code": 102001, "message": "Token失效,微信凭据已过期,请在个人中心重新配置"}) return jsonify({"rtn_code": open_result.get("rtn_code", 500), - "message": friendly_upstream_message(raw_open_msg, fallback="开锁失败,请稍后重试"), + "message": friendly_upstream_message(raw_open_msg, fallback="开锁失败,请稍后重试") + + ("(已撤销本次下单)" if cleaned else ""), "order_id": order_id}) diff --git a/routes/share.py b/routes/share.py index f31c406..530b27e 100644 --- a/routes/share.py +++ b/routes/share.py @@ -49,17 +49,25 @@ def _today_str(): return _beijing_now().strftime("%Y-%m-%d") -def _upstream_order_finished(user_id: int, order_id) -> bool: - """在还车调用响应不明确时,以用户真实订单状态做二次确认。""" +def _upstream_order_finished(user_id: int, order_id, bike_code=None) -> bool: + """还车响应不明确时,确认指定订单是否已经不再骑行。 + + 与 routes/rental.py 的同名函数保持一致:上游 `nonDealOrder` 只保留 + **当前那一张**进行中的订单,如果挂着的是另一张单(多轮续租/共享轮换), + 不能直接判本单结束 —— 否则会把「仍在计费的车」当成功还掉。 + 所以再按车牌兜一层:上游挂着同车牌的订单,就当本单还没结束。 + """ result = request_with_user_auth(user_id, "GET", "/user/info", _silent=True) if result.get("rtn_code") != 0: return False non_deal = (result.get("data") or {}).get("nonDealOrder") if not non_deal or not non_deal.get("order_id"): return True - if str(non_deal.get("order_id")) != str(order_id): - return True - return str(non_deal.get("status")) != "2" + if str(non_deal.get("order_id")) == str(order_id): + return str(non_deal.get("status")) != "2" + if bike_code and str(non_deal.get("code") or "") == str(bike_code): + return False + return True def _user_email(user_id: int): @@ -870,18 +878,26 @@ def share_return(): "longitude": longitude, "latitude": latitude}, _silent=True) confirmed_by_status = False - if return_result.get("rtn_code") != 0: + # 「订单信息不存在」(204010) 是硬错误:本来就没有这张单,别去状态确认, + # 否则会把上游另一张进行中的订单当成本单已结束,用户看到「还车成功」而车还在计费。 + hard_reject = (return_result.get("rtn_code") == 204010 + or "订单信息不存在" in str(return_result.get("message") or "")) + if return_result.get("rtn_code") != 0 and not hard_reject: # 锁车指令可能已经被车辆执行,但 HTTP 响应超时/异常。短暂复查真实订单 # 状态;只在上游明确显示不再骑行时按成功处理,避免误报也避免误清理。 for attempt in range(4): if attempt: time.sleep(1) - if _upstream_order_finished(owner_user_id, upstream_order_id): + if _upstream_order_finished( + owner_user_id, upstream_order_id, + (rental["bike_code"] if rental is not None else None)): confirmed_by_status = True break if not confirmed_by_status: return jsonify({"rtn_code": return_result.get("rtn_code", 500), "message": return_result.get("message", "还车失败")}) + elif hard_reject: + return jsonify({"rtn_code": 204010, "message": "订单信息不存在,请刷新后重试"}) conn = get_db() cur = conn.cursor() diff --git a/static/js/map.js b/static/js/map.js index a61a579..80ce00c 100644 --- a/static/js/map.js +++ b/static/js/map.js @@ -3001,6 +3001,9 @@ // 初始化百度地图 GL map = new BMapGL.Map("baidu_map"); + // 地图实例刚建好:立刻把导航模块的拖动监听绑上(浏览器里唯一可靠的时机, + // 之前 navigation.js 只靠 setTimeout(0),那时 map 还是 null,监听从未生效) + try { if (typeof bindNavMapEvents === "function") bindNavMapEvents(); } catch (e) {} map.centerAndZoom(new BMapGL.Point(c.lng, c.lat), cfg.scale || 17); map.enableScrollWheelZoom(true); map.enableDragging(true); diff --git a/static/js/navigation.js b/static/js/navigation.js index 6045846..38bc8be 100644 --- a/static/js/navigation.js +++ b/static/js/navigation.js @@ -532,10 +532,15 @@ async function _recomputeRoute(gcj) { // gcj = {lat, lng}(GCJ02) if (!_nav || !_nav.destLat) return; + // 快照:重算期间用户可能点了「结束导航」或改导航到另一辆车, + // 回包若不再属于这次导航就必须丢弃,否则旧路线会盖掉新导航。 + const myNav = _nav; + const epoch = _navEpoch; try { const data = await _requestNavRoute(gcj.lat, gcj.lng, _nav.destLat, _nav.destLng); if (!data) return; + if (_nav !== myNav || epoch !== _navEpoch || !_nav) return; _applyRoute(data); showToast("已重新规划路线"); } catch (e) { @@ -751,16 +756,33 @@ } } - // 地图拖动事件(只注册一次) - (function _bindNavMapEvents() { - const bind = () => { - // navigation.js 在 map.js 之前执行,此时 `let map` 还在 TDZ, - // 直接读会抛 ReferenceError,所以统一延后到下一轮宏任务再绑。 - if (typeof map === "undefined" || !map || !map.addEventListener || map.__navBound) return; + // 地图拖动事件(只注册一次)。map 由 map.js 在 /api/config 回来后才创建, + // 所以这里只负责「准备好就绑」;map.js 建好地图后会显式调一次 bindNavMapEvents()。 + function bindNavMapEvents() { + // navigation.js 在 map.js 之前执行,此时 `let map` 还在 TDZ, + // 连 typeof 都会抛 ReferenceError,所以整段包在 try 里。 + try { + if (typeof map === "undefined" || !map || !map.addEventListener) return false; + if (map.__navBound) return true; map.__navBound = true; map.addEventListener("dragstart", _onMapDragStart); map.addEventListener("dragging", _onMapDragging); map.addEventListener("dragend", _onMapDragEnd); - }; - setTimeout(bind, 0); + } catch (e) { + return false; // map 还没声明(或地图未就绪) + } + try { console.info("[导航] 已绑定地图拖动事件"); } catch (e) {} + return true; + } + // 给 map.js 用(它创建完地图主动调一次) + window.bindNavMapEvents = bindNavMapEvents; + + // 兜底:万一 map.js 忘了调,这里再轮询几次(最多约 10 秒) + (function _retryBindNavMapEvents(tries = 0) { + if (bindNavMapEvents()) return; + if (tries >= 20) { + console.warn("[导航] 地图拖动事件未能绑定(map 一直未就绪)"); + return; + } + setTimeout(() => _retryBindNavMapEvents(tries + 1), 500); })(); diff --git a/subscribe.py b/subscribe.py index a44a7be..5e14b4c 100644 --- a/subscribe.py +++ b/subscribe.py @@ -413,29 +413,33 @@ def _try_auto_unlock(user_id: int, bike_code: str) -> dict: if row: email = row["email"] or "" try: - conn.execute(""" + cur = conn.execute(""" INSERT INTO rentals (id, order_id, bike_code, email, user_id, start_time, end_time, duration, expired, source, renewal_round) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, 'subscribe', 1) """, (int(order_id), str(order_id), code, email, user_id, now.strftime("%Y-%m-%d %H:%M:%S"), end.strftime("%Y-%m-%d %H:%M:%S"), duration)) + rental_id = cur.lastrowid or int(order_id) except sqlite3.IntegrityError: - # id 与历史行冲突(极少见):改用自增 id,order_id 仍记录真实订单号 - conn.execute(""" + # id 与历史行冲突(极少见):改用自增 id,order_id 仍记录真实订单号。 + # 一定要用 lastrowid 当 rental_id —— 之前继续用 int(order_id), + # 计时器/起点回填会作用到撞冲突的那条旧单上,新车完全没有计时器。 + cur = conn.execute(""" INSERT INTO rentals (order_id, bike_code, email, user_id, start_time, end_time, duration, expired, source, renewal_round) VALUES (?, ?, ?, ?, ?, ?, ?, 0, 'subscribe', 1) """, (str(order_id), code, email, user_id, now.strftime("%Y-%m-%d %H:%M:%S"), end.strftime("%Y-%m-%d %H:%M:%S"), duration)) + rental_id = cur.lastrowid conn.commit() conn.close() - start_rental_timer(rental_id=int(order_id), email=email, bike_code=code, + start_rental_timer(rental_id=int(rental_id), email=email, bike_code=code, duration_minutes=duration, user_id=user_id) try: from routes.rental import _record_rental_start - _record_rental_start(int(order_id), lat, lng) + _record_rental_start(int(rental_id), lat, lng) except Exception as exc: print(f"[订阅开锁] 回填起点失败: {exc}") except Exception as exc: @@ -662,13 +666,24 @@ def _tick(): if not rules: conn.close() return - # 先占位再发送,避免重试窗口内重复触发 - for r in rules: - conn.execute("UPDATE subscribe_rules SET last_fired_on = ? WHERE id = ?", (today, r["id"])) - conn.commit() - conn.close() - for r in rules: + # 抢占式置位(CAS):多进程/多实例下两个 worker 会同时选到同一批规则, + # 只让 UPDATE 真正命中(rowcount==1)的那个进程去发信/开锁, + # 否则同一分钟会发两封邮件、勾了自动开锁的还会重复调 /record/order。 + claimed = [] + try: + for r in rules: + cur = conn.execute( + "UPDATE subscribe_rules SET last_fired_on = ? " + "WHERE id = ? AND last_fired_on != ?", + (today, r["id"], today)) + if cur.rowcount == 1: + claimed.append(r) + conn.commit() + finally: + conn.close() + + for r in claimed: rule = dict(r) if not rule.get("notify_enabled") and not rule.get("auto_unlock"): continue diff --git a/timer.py b/timer.py index c269462..c9d8f5d 100644 --- a/timer.py +++ b/timer.py @@ -240,26 +240,30 @@ def _mark_returned(rental_id: int, latitude=None, longitude=None): label = None conn = get_db() try: - conn.execute(""" - UPDATE rentals SET expired = 1, returned_at = datetime('now', '+8 hours'), - end_latitude = ?, end_longitude = ?, end_label = ? - WHERE id = ? - """, (latitude, longitude, label, rental_id)) - except sqlite3.OperationalError: - # 轻量兜底:旧库/极简 schema 缺列时补齐再重试一次 - for col_def in [("returned_at", "TIMESTAMP"), ("end_latitude", "REAL"), - ("end_longitude", "REAL"), ("end_label", "TEXT")]: - try: - conn.execute(f"ALTER TABLE rentals ADD COLUMN {col_def[0]} {col_def[1]}") - except sqlite3.OperationalError: - pass - conn.execute(""" - UPDATE rentals SET expired = 1, returned_at = datetime('now', '+8 hours'), - end_latitude = ?, end_longitude = ?, end_label = ? - WHERE id = ? - """, (latitude, longitude, label, rental_id)) - conn.commit() - conn.close() + try: + conn.execute(""" + UPDATE rentals SET expired = 1, returned_at = datetime('now', '+8 hours'), + end_latitude = ?, end_longitude = ?, end_label = ? + WHERE id = ? + """, (latitude, longitude, label, rental_id)) + except sqlite3.OperationalError: + # 轻量兜底:旧库/极简 schema 缺列时补齐再重试一次 + for col_def in [("returned_at", "TIMESTAMP"), ("end_latitude", "REAL"), + ("end_longitude", "REAL"), ("end_label", "TEXT")]: + try: + conn.execute(f"ALTER TABLE rentals ADD COLUMN {col_def[0]} {col_def[1]}") + except sqlite3.OperationalError: + pass + conn.execute(""" + UPDATE rentals SET expired = 1, returned_at = datetime('now', '+8 hours'), + end_latitude = ?, end_longitude = ?, end_label = ? + WHERE id = ? + """, (latitude, longitude, label, rental_id)) + conn.commit() + finally: + # 写失败也要关连接:以前这里异常会泄漏连接(fd 累积), + # 而且调用方拿不到「状态没落库」的信号 + conn.close() def _reopen_same_bike(user_id: int, bike_code: str) -> dict: @@ -440,15 +444,18 @@ def _auto_return_bike(rental_id: int, user_id: int, allow_renewal: bool = True): 3. 万一对齐后仍失败,第 2 次重试前再吸附一次(应对上游边界与本地不一致)。 """ conn = get_db() - cursor = conn.cursor() - cursor.execute("SELECT * FROM rentals WHERE id = ?", (rental_id,)) - rental = cursor.fetchone() - if not rental: + try: + cursor = conn.cursor() + cursor.execute("SELECT * FROM rentals WHERE id = ?", (rental_id,)) + rental = cursor.fetchone() + finally: + # 这个连接只用来读这一行,读完立刻关:以前一直挂到函数末尾, + # 中间任何异常(上游超时、写库失败)都会把连接漏掉。 conn.close() + if not rental: print(f"[自动还车] 记录不存在: rental_id={rental_id}") return {"success": False, "rtn_code": 404, "message": "本地租车记录不存在"} if rental["expired"]: - conn.close() return {"success": True, "rtn_code": 0, "message": "订单已结束"} bike_code = rental["bike_code"] @@ -517,7 +524,14 @@ def _auto_return_bike(rental_id: int, user_id: int, allow_renewal: bool = True): # 让邮件按钮可重试,后台对账也能继续跟踪真实状态。 if success: _mark_returned(rental_id, latitude, longitude) - conn.close() + # 续租会换新的 order_id;不清掉 60 秒的 /user/info 缓存的话, + # 前端在缓存窗口内点还车会拿到旧 order_id、被判「已结束」返回 rtn 0, + # 而车其实已经在第 2 轮计费。 + try: + from routes.rental import _user_info_cache + _user_info_cache.pop(user_id, None) + except Exception: + pass renewal_result = {"renewed": False} if success: _cancel_rental_timers(rental_id) @@ -1193,10 +1207,23 @@ def _check_user_order(user_id: int): if existing: rental_id = existing["id"] - cursor.execute(""" - UPDATE rentals SET expired = 0, source = 'sync', - start_time = ?, end_time = ?, duration = ?, email = ? WHERE id = ? - """, (start_str, end_str, duration, email, rental_id)) + # 复活这张单时把 notified_* 一起复位:本地可能刚被 _close_rental_locally / + # _finish_active_wechat_rentals 置过 expired=1,那些提醒位还留着 1, + # 复活的单就再也收不到 5/3/2/1 提醒和 0 分钟自动还车了。 + try: + cursor.execute(""" + UPDATE rentals SET expired = 0, source = 'sync', + start_time = ?, end_time = ?, duration = ?, email = ?, + notified_10 = 0, notified_5 = 0, notified_3 = 0, + notified_2 = 0, notified_1 = 0, notified_0 = 0 + WHERE id = ? + """, (start_str, end_str, duration, email, rental_id)) + except sqlite3.OperationalError: + # 极简 schema 没有这些列:退回原来的更新 + cursor.execute(""" + UPDATE rentals SET expired = 0, source = 'sync', + start_time = ?, end_time = ?, duration = ?, email = ? WHERE id = ? + """, (start_str, end_str, duration, email, rental_id)) old_source = existing["source"] print(f"[订单检测] 升级租车记录: rental_id={rental_id}, order_id={order_id}, " f"source={old_source}→sync, 剩余={remaining}分钟")