fix: 订单生命周期 / 鉴权基础设施 / 前端 UX 批量修复(R2-R12、A3-A12、F1-F14)

后端 · 订单与计时器(timer.py / routes/rental.py / routes/share.py)
- R2 关闭自动还车后,巡检 / 重启恢复 / sweep 不再强制还车(_should_auto_return 读骑行人设置)
- R3 手动还车撞续租窗口:先等 _renewal_lock,再按同车活跃行重查,不再误回「订单已结束」
- R4 续租复用巡检行时补齐 renewal_round / rounds_override / rider_user_id / source
- R5 续租策略统一读骑行人(rider_user_id or user_id);上游调用与卡支付仍用车主
- R6 续租落库失败立即 _check_user_order 兜底,仍失败则管理员告警
- R7 /record/qrOrder 失败撤销半成品订单(续租 + 共享开锁两处)
- R8 跨进程租约移入 auto_return_bike 本体(ttl 180);线程内重入只由最外层释放一次;新增 _background_enabled 总开关
- R9 自动还车失败先复查 expired,已结束则不再重试、不发紧急邮件
- R10 开锁响应 SELECT 补 order_id,轮次预估不再恒为 1 轮
- R11 共享开锁落库:IntegrityError 复用活跃行;其它异常同步订单并在响应带 warning
- R12 0 分钟自动还车的结果邮件不再依赖「0 分钟提醒」被勾选

后端 · 鉴权与基础设施
- A3  /api/admin/users 不再返回完整 access_token / token_id(只留掩码)
- A4  采集调度循环 try/except;后台线程登记,看门狗按 is_alive 重拉;租约 True/False/None 三态显式
- A5  采集改走 _request_api_uncached;map_cache 失败标 stale / stale_since,fetched_at 保持上次成功时间
- A6  bootstrap try/finally,异常时复位 _bootstrap_started
- A7  删除含明文 AK/SK 的旧分发包 1.zip
- A8  record_cooldown 不再翻转已有有效验证码的 purpose(修注册验证码 DoS)
- A9  登录新增邮箱维度限流(10 次 / 900 秒)
- A10 管理员代还车一律按订单归属用户执行,body user_id 不一致时返回 warning
- A11 /api/ring_progress 改用 /api/ring_ticket 签发的一次性 ticket,不再接受 ?token=
- A12 导出令牌绑定创建者、下载一次性、可撤销(POST /api/export/revoke)
- 时区:CURRENT_TIMESTAMP 全部统一为 datetime('now', '+8 hours')(db.py / admin.py / share.py)
- JSON:auth 入参非字符串时返回 400 而非 500

前端(src-ts / templates / static)
- F1  登录后静默定位;找车 / 导航无定位时现场申请;被拒弹卡片并提供「用地图中心找车」
- F2  真实订单的计时条不再被 status 轮询清掉;startRentalFromServer 记录 order_id
- F3  登出 / 会话失效时 resetUserState 清掉横幅、计时条、共享横幅与本地存储
- F4  toast 改为 #toast-stack(最多 3 条、role=status),不再互相覆盖
- F6  新增 fetchWithTimeout(8 秒),全站 fetch 接入;/api/config 超时显示失败卡片
- F7  getBikeState 顺序统一为 损坏→使用中→欠压→低电量→空闲,图例与卡片同源
- F8  快照刷新后卡片按车牌重绘,车辆离开实时列表则关闭并提示
- F10 共享权限复选框改为 label 包裹
- F11 分析页 echarts / mapvgl 加 defer + onerror;BMap 超时显示失败卡片
- F12 删除订阅规则增加二次确认,按钮加 tap-44
- F13 扫码查询按钮禁用态;401 / 非 JSON 响应走登录门
- F14 刷新按钮绑定真实请求,失败必提示
- ring_progress.html 改两步 ticket 流程;bike-clusters addEventListener 特性检测

测试
- 新增 tests/test_fix_order_lifecycle.py(27)、tests/test_fix_infra_fixes.py(24)、tests/test_fix_frontend.cjs(13)
- tests/test_order_sync.py、tests/test_ring_owner.py 按 R12 / A11 新语义更新
- pytest 322 passed;tsc / esbuild / verify:globals 通过;cjs 58 passed
This commit is contained in:
zzy
2026-11-23 19:37:28 +08:00
parent 364b1c77c6
commit aa6132f3e1
36 changed files with 3490 additions and 647 deletions
+84 -3
View File
@@ -318,6 +318,30 @@
}
@keyframes spin { to { transform: rotate(360deg); } }
/* 地图/图表库加载失败卡片(F11,与主页 loading-failure 一个样式语言) */
.map-failure {
display: none;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
gap: 10px;
padding: 28px 16px;
color: var(--text-secondary);
font-size: 13.5px;
line-height: 1.7;
}
.map-failure-icon {
width: 44px; height: 44px; border-radius: 50%;
display: flex; align-items: center; justify-content: center;
font-size: 22px; font-weight: 700; color: #fff; background: var(--error-color, #ff3b30);
}
.map-failure-title { font-size: 16px; font-weight: 700; color: var(--text-primary); }
.map-failure button {
min-height: 44px; min-width: 140px; padding: 10px 20px; border: none; border-radius: 12px;
background: var(--accent-color, #0a84ff); color: #fff; font-size: 14px; font-weight: 600; cursor: pointer;
}
/* 提示信息 */
.tip {
font-size: 12px;
@@ -553,9 +577,27 @@
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
<script src="https://api.map.baidu.com/api?v=1.0&type=webgl&ak=GzzqszczKmI7RNTclpLtOXZDTT4mq8a6"></script>
<script src="https://unpkg.com/mapvgl/dist/mapvgl.min.js"></script>
<script>
// F11:图表/地图库走 defer(不阻塞首屏),加载失败时在页面里给一句人话提示,而不是留一块空白
function chartLibLoadFailed(name) {
console.error('[图表库] 加载失败:', name);
let box = document.getElementById('chart-lib-error');
if (!box) {
box = document.createElement('div');
box.id = 'chart-lib-error';
box.className = 'map-failure';
box.setAttribute('role', 'alert');
const host = document.querySelector('.tab-content') || document.body;
host.insertBefore(box, host.firstChild);
}
box.textContent = '图表库加载失败,请检查网络后刷新';
box.style.display = 'flex';
}
</script>
<script defer src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js" onerror="chartLibLoadFailed('echarts')"></script>
<!-- 百度地图 loader 保持同步(其内部加载方式依赖同步写入),只加 onerror;echarts/mapvgl 走 defer -->
<script src="https://api.map.baidu.com/api?v=1.0&type=webgl&ak=GzzqszczKmI7RNTclpLtOXZDTT4mq8a6" onerror="chartLibLoadFailed('BMapGL')"></script>
<script defer src="https://unpkg.com/mapvgl/dist/mapvgl.min.js" onerror="chartLibLoadFailed('mapvgl')"></script>
<!-- 坐标转换库(本地内置,车辆数据 GCJ02 -> 百度 BD09) -->
<script src="/static/js/coordtransform.js"></script>
<script>
@@ -838,8 +880,24 @@
}
// 渲染小时图表(堆叠柱状图)
let _echartsWaitTries = 0;
function renderHourlyChart(data, avgData, days = 1) {
// F11:echarts 是 defer 加载的,统计接口可能先回来——等它一会儿(最多约 10s),再不行给提示
if (typeof window.echarts === 'undefined') {
if (_echartsWaitTries++ < 50) {
setTimeout(() => renderHourlyChart(data, avgData, days), 200);
} else {
chartLibLoadFailed('echarts');
}
return;
}
_echartsWaitTries = 0;
renderHourlyChartNow(data, avgData, days);
}
function renderHourlyChartNow(data, avgData, days = 1) {
if (!hourlyChart) {
if (typeof window.echarts === 'undefined') { chartLibLoadFailed('echarts'); return; }
hourlyChart = echarts.init(document.getElementById('hourly-chart'));
}
@@ -1416,11 +1474,29 @@
setTimeout(() => waitForBMap(retries - 1), 500);
} else {
console.error("百度地图GL API加载失败");
// F11:别留一块永远转圈的「加载中...」,换成可自救的失败卡片(与主页一致)
showMapFailure(containerId, '地图组件没有加载成功,可能是网络不稳定,或微信拦下了地图脚本。');
}
}
waitForBMap();
}
// F11:地图容器里的 loading 换成失败卡片(带「重新加载」)
function showMapFailure(containerId, reason) {
const el = document.getElementById(containerId);
if (!el) return;
const loading = el.querySelector('.loading');
if (loading) loading.remove();
if (el.querySelector('.map-failure')) return; // 已经是失败态,不重绘
el.insertAdjacentHTML('afterbegin',
'<div class="map-failure" style="display:flex;" role="alert">' +
'<div class="map-failure-icon" aria-hidden="true">!</div>' +
'<div class="map-failure-title">地图加载失败</div>' +
'<div>' + reason + '</div>' +
'<button type="button" onclick="location.reload()">重新加载</button>' +
'</div>');
}
function doInitMap(containerId, isHeatmap, initLng, initLat) {
// 初始化前清掉 loading overlay,避免遮挡地图
const el = document.getElementById(containerId);
@@ -1441,6 +1517,11 @@
mapInstance.enableDragging();
if (isHeatmap) {
if (typeof mapvgl === 'undefined') {
// F11:mapvgl 外链没下来:热力图画不了,给失败卡片而不是抛 ReferenceError
showMapFailure(containerId, '热力图组件加载失败,请检查网络后刷新');
return;
}
window.heatMap = mapInstance;
// 初始化 MapVGL View
heatmapView = new mapvgl.View({ map: mapInstance });
+16 -3
View File
@@ -520,9 +520,9 @@
<label>每天最多可给TA使用几次</label>
<input type="number" id="sharecfg-daily" min="0" max="99" value="3" />
</div>
<div class="share-cfg-check" onclick="document.getElementById('sharecfg-card').checked=!document.getElementById('sharecfg-card').checked">
<label class="share-cfg-check">
<input type="checkbox" id="sharecfg-card" checked /> <span>TA使用时,我必须持有可用优惠卡</span>
</div>
</label>
<div class="share-cfg-row" id="sharecfg-minrow">
<label>我的优惠卡剩余次数低于该值时,TA不能使用(保护我不掏钱)</label>
<input type="number" id="sharecfg-mintimes" min="0" max="999" value="1" />
@@ -835,7 +835,8 @@
</div>
</div>
<div class="toast" id="toast"></div>
<!-- 提示栈(F4):最多同时 3 条,各自独立 2.5s 消失;位置由 showToast 按订单横幅底边计算 -->
<div id="toast-stack" aria-live="polite"></div>
<!-- 忘记密码弹窗 -->
<div class="auth-modal" id="forgot-modal">
@@ -1000,6 +1001,18 @@
</div>
</div>
<!-- 定位失败兜底卡片(F1):找车/导航时没有定位 → 说明原因 + 平台开启路径 + 「用地图中心找车」 -->
<div class="unlock-confirm-modal" id="location-fallback-modal">
<div class="unlock-confirm-content">
<div class="unlock-confirm-title" id="location-fallback-title">需要定位权限才能找车/导航</div>
<div class="unlock-confirm-text" id="location-fallback-text">--</div>
<div class="unlock-confirm-btns">
<button class="unlock-confirm-btn cancel" id="location-fallback-cancel">取消</button>
<button class="unlock-confirm-btn confirm" id="location-fallback-ok">用地图中心找车</button>
</div>
</div>
</div>
<!-- 追加一轮确认弹窗 -->
<div class="unlock-confirm-modal" id="add-round-modal" onclick="if(event.target===this) closeAddRoundModal()">
<div class="unlock-confirm-content">
+36 -20
View File
@@ -174,15 +174,15 @@
const taskId = params.get('task_id') || '';
const total = parseInt(params.get('total') || '0');
// ===== 登录态(BUG-20)=====
// 批次 C 之后 /api/ring_status | ring_cancel | ring_progress 都要求登录,
// 鉴权接受 Authorization: Bearer 或 ?token=。EventSource 不能自定义 header,
// 只能走查询参数;POST 取消请求两边都带上,任一通道生效即可。
// ===== 登录态(BUG-20 / A11)=====
// /api/ring_status | ring_cancel | ring_progress 都要求登录。
// EventSource 不能自定义 header,所以不再把会话 token 拼进 URL(会进反代访问日志):
// 先用 Bearer 换一张 60 秒一次性 ticket,再拿 ticket 连 SSE。
function getAuthToken() {
try { return localStorage.getItem('auth_token') || ''; } catch (e) { return ''; }
}
const authToken = getAuthToken();
const tokenQuery = authToken ? `?token=${encodeURIComponent(authToken)}` : '';
const authHeaders = authToken ? { 'Authorization': 'Bearer ' + authToken } : {};
document.getElementById('status-text').textContent = `共 ${total} 辆车`;
@@ -231,11 +231,9 @@
cancelled = true;
document.getElementById('cancel-btn').disabled = true;
document.getElementById('cancel-btn').textContent = '取消中...';
const headers = {};
if (authToken) headers['Authorization'] = 'Bearer ' + authToken;
fetch(`/api/ring_cancel/${encodeURIComponent(taskId)}${tokenQuery}`, {
fetch(`/api/ring_cancel/${encodeURIComponent(taskId)}`, {
method: 'POST',
headers
headers: authHeaders
})
.then(r => r.json())
.then(d => {
@@ -251,18 +249,24 @@
uiCloseWindow();
}
// SSE 连接(带 ?token=;没有任务号或未登录时不要连,否则 EventSource 会 401 反复重试)
// SSE 连接:先用 Bearer 换一次性 ticket,再连 SSE(不把会话 token 拼进 URL)
let es = null;
if (!taskId) {
document.getElementById('status-text').textContent = '缺少任务号';
document.getElementById('cancel-btn').disabled = true;
addLog('缺少 task_id,请从主页面重新发起全车寻铃', 'failed');
} else if (!authToken) {
document.getElementById('status-text').textContent = '请先在主页面登录';
document.getElementById('cancel-btn').disabled = true;
addLog('未登录:请先在主页面登录后再查看寻车进度', 'failed');
} else {
es = new EventSource(`/api/ring_progress/${encodeURIComponent(taskId)}${tokenQuery}`);
function connectProgress() {
fetch('/api/ring_ticket', { headers: authHeaders })
.then(r => r.json())
.then(d => {
const ticket = (d && d.data && d.data.ticket) || '';
if (d.rtn_code !== 0 || !ticket) {
addLog(d.message || '获取进度凭证失败,请重新登录', 'failed');
return;
}
openStream(ticket);
})
.catch(() => addLog('获取进度凭证失败', 'failed'));
}
function openStream(ticket) {
es = new EventSource(`/api/ring_progress/${encodeURIComponent(taskId)}?ticket=${encodeURIComponent(ticket)}`);
es.onmessage = (e) => {
try {
@@ -285,6 +289,18 @@
addLog('开始监听进度...', '');
}
if (!taskId) {
document.getElementById('status-text').textContent = '缺少任务号';
document.getElementById('cancel-btn').disabled = true;
addLog('缺少 task_id,请从主页面重新发起全车寻铃', 'failed');
} else if (!authToken) {
document.getElementById('status-text').textContent = '请先在主页面登录';
document.getElementById('cancel-btn').disabled = true;
addLog('未登录:请先在主页面登录后再查看寻车进度', 'failed');
} else {
connectProgress();
}
</script>
</body>
</html>