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
+103 -6
View File
@@ -2,6 +2,7 @@
import { S } from "../core/state";
import { escHtml } from "../core/format";
import { fetchWithTimeout } from "../core/fetch";
import { startRental } from "../order/actions";
import { checkPendingShareRequests, refreshShareBanners } from "../share/share";
// static/js/map.js:4085-4085
@@ -233,12 +234,108 @@ export function appConfirmClose() {
}
}
// static/js/map.js:4357-4366
// F4:toast 改成「栈」。
// 以前只有 1 个 #toast 节点,后一条直接覆盖前一条,而且每次都新起一个 setTimeout:
// 连点几下后,第一条的计时器会把后一条的 .show 提前摘掉(看起来像 toast 凭空消失)。
// 现在 #toast-stack 里最多同时放 3 条,每条 role="status",各自 2500ms 后独立移除;
// 位置放在订单横幅下方(横幅显示时贴着它的底边,不遮挡横幅按钮)。
const TOAST_MAX = 3;
export const TOAST_MS = 2500;
/** 纯函数:给定订单横幅的底边(px,null = 没显示),算 toast 栈的 top。 */
export function toastStackTop(bannerBottom, fallbackTop = 80) {
return Number.isFinite(bannerBottom) && bannerBottom > 0 ? bannerBottom + 8 : fallbackTop;
}
/** 保留的模块级计时器句柄(旧版单 toast 模板用;栈模式下每条 toast 自带计时器) */
export let _toastTimer: any = null;
function placeToastStack(stack) {
try {
const banner = document.getElementById("order-banner");
let bottom: any = null;
if (banner && banner.classList.contains("show")) {
const r = banner.getBoundingClientRect();
if (r && r.height > 0) bottom = r.bottom;
}
stack.style.top = toastStackTop(bottom) + "px";
} catch (e) { /* 极端布局下量不到就用 CSS 默认值 */ }
}
export function showToast(msg) {
const t = document.getElementById("toast");
t.textContent = msg;
t.classList.add("show");
setTimeout(() => t.classList.remove("show"), 2500);
const stack = document.getElementById("toast-stack");
if (!stack) {
// 模板变体兜底:还是旧的单节点 #toast
const t = document.getElementById("toast");
if (!t) return;
t.textContent = msg;
t.classList.add("show");
if (_toastTimer) clearTimeout(_toastTimer);
_toastTimer = setTimeout(() => t.classList.remove("show"), TOAST_MS);
return;
}
// 最多 3 条:多了就把最旧的拿掉
while (stack.children.length >= TOAST_MAX && stack.firstChild) stack.removeChild(stack.firstChild);
const item = document.createElement("div");
item.className = "toast show";
item.setAttribute("role", "status");
item.textContent = msg;
stack.appendChild(item);
placeToastStack(stack);
// 各自独立计时,互不影响
setTimeout(() => { if (item.parentNode) item.parentNode.removeChild(item); }, TOAST_MS);
}
// ========== 定位失败兜底弹窗(F1)==========
// 找车/导航时没有定位:用户拒绝授权(code=1)或定位超时,都不能只弹一句 toast 就完事。
// 给一张小卡片:说明原因 + 各平台开定位的路径 + 「用地图中心找车」的兜底按钮。
// resolve(true) = 用地图中心;resolve(false) = 取消。
let _locFallbackResolve: any = null;
export function showLocationFallbackModal(opts) {
const o = opts || {};
const modal = document.getElementById("location-fallback-modal");
const titleEl = document.getElementById("location-fallback-title");
const textEl = document.getElementById("location-fallback-text");
const okBtn = document.getElementById("location-fallback-ok");
const cancelBtn = document.getElementById("location-fallback-cancel");
if (!modal || !textEl || !okBtn || !cancelBtn) {
// 极老页面兜底:没有这张卡片就退回 appConfirm
return appConfirm(String(o.text || "需要定位权限才能找车/导航"), { title: o.title || "需要定位权限", okText: o.okText || "用地图中心找车" });
}
titleEl.textContent = o.title || "需要定位权限才能找车/导航";
textEl.innerHTML = String(o.text || "")
.split("\n")
.map(line => escHtml(line))
.join("<br/>");
okBtn.textContent = o.okText || "用地图中心找车";
return new Promise<any>(resolve => {
_locFallbackResolve = resolve;
const finish = (val) => {
modal.classList.remove("show");
okBtn.onclick = null;
cancelBtn.onclick = null;
modal.onclick = null;
_locFallbackResolve = null;
resolve(val);
};
okBtn.onclick = (e) => { e.stopPropagation(); finish(true); };
cancelBtn.onclick = (e) => { e.stopPropagation(); finish(false); };
modal.onclick = (e) => { if (e.target === modal) finish(false); };
modal.classList.add("show");
});
}
export function closeLocationFallbackModal() {
if (_locFallbackResolve) {
const r = _locFallbackResolve;
_locFallbackResolve = null;
const modal = document.getElementById("location-fallback-modal");
if (modal) modal.classList.remove("show");
r(false);
}
}
// ========== 抓包工具下载 ==========
@@ -370,7 +467,7 @@ export async function exportHistoryCsv() {
if (!S.authToken) { showToast("请先登录"); return; }
showToast("正在生成导出链接...");
try {
const resp = await fetch("/api/export/create", {
const resp = await fetchWithTimeout("/api/export/create", {
method: "POST",
headers: { "Content-Type": "application/json",
"Authorization": `Bearer ${S.authToken}` },
+16 -6
View File
@@ -2,11 +2,12 @@
import { S } from "../core/state";
import { describeTokenExpiry, escHtml, fmtLocalTime, fmtRemainShort, fmtTime } from "../core/format";
import { loadMapData, mapRefreshTimer } from "../map/core";
import { loadMapData, mapRefreshTimer, startAutoLocationIfLoggedIn } from "../map/core";
import { bikeBubbleLayer } from "../map/markers";
import { checkRentalStatus } from "../order/actions";
import { checkRentalStatus, resetUserState } from "../order/actions";
import { checkOrderStatus } from "../order/status";
import { appConfirm, appConfirmClose, shareAfterLogin, showToast, showTokenExpiredModal } from "./modals";
import { fetchWithTimeout } from "../core/fetch";
// static/js/map.js:493-501
export function handleAuthBtnClick() {
if (S.currentUser) {
@@ -616,7 +617,7 @@ export async function doLogin(email, password, tip, submitBtn) {
submitBtn.disabled = true;
submitBtn.textContent = "登录中...";
try {
const resp = await fetch("/api/auth/login", {
const resp = await fetchWithTimeout("/api/auth/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, password, device_id: getDeviceId(), device_name: getDeviceName() })
@@ -637,6 +638,8 @@ export async function doLogin(email, password, tip, submitBtn) {
checkRentalStatus();
refreshAuthExpiry(); // 登录态有效期不足 2 天时挂顶部提醒
if (S.map) loadMapData(S.currentType, false);
// F1:登录成功后才启动定位(静默,不弹「正在获取您的位置...」)
startAutoLocationIfLoggedIn();
} else {
tip.textContent = data.message || "登录失败";
}
@@ -737,7 +740,7 @@ export async function handleRegisterSubmit(e) {
}
try {
const resp = await fetch("/api/auth/register", {
const resp = await fetchWithTimeout("/api/auth/register", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
@@ -765,6 +768,7 @@ export async function handleRegisterSubmit(e) {
shareAfterLogin();
refreshAuthExpiry(); // 注册时可能已填凭证,立即评估有效期
if (S.map) loadMapData(S.currentType, false);
startAutoLocationIfLoggedIn(); // F1:注册即登录,同样走登录后静默定位
} else {
tip.textContent = data.message || "注册失败";
}
@@ -781,7 +785,7 @@ export async function handleLogout() {
clearTimeout(mapRefreshTimer);
if (S.authToken) {
try {
await fetch("/api/auth/logout", {
await fetchWithTimeout("/api/auth/logout", {
method: "POST",
headers: { "Authorization": `Bearer ${S.authToken}` }
});
@@ -792,6 +796,8 @@ export async function handleLogout() {
localStorage.removeItem("auth_token");
S.authKickToastShown = false;
_savedTokenExpiry = null;
// F3:订单横幅 / 计时条 / 共享横幅 / 本地计时记录一起清,别留给下一个登录的人
resetUserState();
renderAuthExpiryBanner(); // 登出后隐藏登录态到期提醒
updateAuthButton();
closeProfileModal();
@@ -847,7 +853,7 @@ export async function checkAuthStatus() {
if (!S.authToken) return;
try {
const resp = await fetch("/api/auth/status", {
const resp = await fetchWithTimeout("/api/auth/status", {
headers: { "Authorization": `Bearer ${S.authToken}` }
});
const data = await resp.json();
@@ -855,12 +861,16 @@ export async function checkAuthStatus() {
if (data.rtn_code === 0 && data.data.logged_in) {
S.currentUser = { email: data.data.email };
updateAuthButton();
// F1:登录态有效 + 地图已就绪 → 静默启动一次持续定位(重复调用无副作用)
startAutoLocationIfLoggedIn();
} else {
// token无效(可能被本设备或其他设备下线),清除登录状态
const hadToken = !!S.authToken;
S.authToken = null;
S.currentUser = null;
localStorage.removeItem("auth_token");
// F3:被踢下线和主动登出一样,要把订单/计时条/共享横幅清干净
resetUserState();
updateAuthButton();
if (hadToken && !S.authKickToastShown) {
S.authKickToastShown = true;