后端 · 订单与计时器(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
252 lines
16 KiB
JavaScript
252 lines
16 KiB
JavaScript
// 前端修复(F1–F14)的单元测试:只测能脱离 DOM 跑的纯函数 + 模板/源码级约束。
|
||
// 纯函数模块用 esbuild(devDependency)现场转成 CJS 再 require;模块级带 DOM 副作用的文件用 vm 切片执行。
|
||
const { test } = require('node:test');
|
||
const assert = require('node:assert/strict');
|
||
const fs = require('node:fs');
|
||
const path = require('node:path');
|
||
const vm = require('node:vm');
|
||
const Module = require('node:module');
|
||
|
||
const ROOT = path.join(__dirname, '..');
|
||
const read = rel => fs.readFileSync(path.join(ROOT, rel), 'utf8');
|
||
|
||
/** 把一个没有 import 的 TS 模块转成 CJS 并 require */
|
||
function loadTs(rel) {
|
||
const esbuild = require('esbuild');
|
||
const src = read(rel);
|
||
const out = esbuild.transformSync(src, { loader: 'ts', format: 'cjs', target: 'es2019' }).code;
|
||
const m = new Module(rel, null);
|
||
m.filename = path.join(ROOT, rel);
|
||
m.paths = Module._nodeModulePaths(ROOT);
|
||
m._compile(out, m.filename);
|
||
return m.exports;
|
||
}
|
||
|
||
/** 从源码里切出一个顶层函数,在沙箱里执行 */
|
||
function evalFunction(rel, name, sandbox = {}) {
|
||
const src = read(rel);
|
||
const start = src.indexOf(`export function ${name}(`);
|
||
assert.ok(start >= 0, `${rel} 里找不到 ${name}`);
|
||
const end = src.indexOf('\n}\n', start);
|
||
const code = src.slice(start, end + 3).replace(/^export /m, '') + `\n;${name}`;
|
||
return vm.runInNewContext(code, sandbox);
|
||
}
|
||
|
||
// ---------- F6:fetchWithTimeout ----------
|
||
const { fetchWithTimeout, fetchJsonWithTimeout, makeTimeoutError } = loadTs('src-ts/core/fetch.ts');
|
||
|
||
test('fetchWithTimeout aborts a hanging request after the given ms and reports a timeout error', async () => {
|
||
let signalSeen = null;
|
||
const fakeFetch = (url, opts) => new Promise((_, reject) => {
|
||
signalSeen = opts.signal;
|
||
opts.signal.addEventListener('abort', () => {
|
||
const e = new Error('The operation was aborted');
|
||
e.name = 'AbortError';
|
||
reject(e);
|
||
});
|
||
});
|
||
const timers = [];
|
||
const saved = { fetch: global.fetch, setTimeout: global.setTimeout, clearTimeout: global.clearTimeout, AbortController: global.AbortController };
|
||
global.fetch = fakeFetch;
|
||
global.setTimeout = (fn, ms) => { timers.push({ fn, ms }); return timers.length; };
|
||
global.clearTimeout = id => { timers[id - 1].cleared = true; };
|
||
try {
|
||
const p = fetchWithTimeout('/api/config', {}, 250);
|
||
assert.ok(signalSeen, '必须把 AbortController.signal 挂到 fetch 上');
|
||
assert.equal(timers[0].ms, 250, '超时计时器应等于传入的 ms');
|
||
timers[0].fn(); // 模拟计时器到点
|
||
await assert.rejects(p, err => err.name === 'AbortError' && err.timeout === true && /超时/.test(err.message));
|
||
} finally {
|
||
Object.assign(global, saved);
|
||
}
|
||
});
|
||
|
||
test('fetchWithTimeout clears the timer on success and keeps a caller-provided signal', async () => {
|
||
const timers = [];
|
||
const saved = { fetch: global.fetch, setTimeout: global.setTimeout, clearTimeout: global.clearTimeout };
|
||
global.fetch = async (url, opts) => ({ ok: true, url, opts });
|
||
global.setTimeout = (fn, ms) => { timers.push({ fn, ms }); return timers.length; };
|
||
global.clearTimeout = id => { timers[id - 1].cleared = true; };
|
||
try {
|
||
const resp = await fetchWithTimeout('/api/map?type=3', {}, 1000);
|
||
assert.equal(resp.url, '/api/map?type=3');
|
||
assert.equal(timers[0].cleared, true, '请求完成后必须清掉计时器');
|
||
// 调用方自带 signal:不新建 controller,直接透传
|
||
const own = new AbortController().signal;
|
||
const r2 = await fetchWithTimeout('/x', { signal: own }, 10);
|
||
assert.equal(r2.opts.signal, own);
|
||
assert.equal(timers.length, 1, '自带 signal 时不应再起计时器');
|
||
} finally {
|
||
Object.assign(global, saved);
|
||
}
|
||
});
|
||
|
||
test('fetchJsonWithTimeout returns ok=false instead of throwing on a non-JSON body', async () => {
|
||
const saved = global.fetch;
|
||
global.fetch = async () => ({ status: 502, json: async () => { throw new SyntaxError('Unexpected token <'); } });
|
||
try {
|
||
const r = await fetchJsonWithTimeout('/api/bicycle', {}, 1000);
|
||
assert.equal(r.resp.status, 502);
|
||
assert.equal(r.body, null);
|
||
assert.equal(r.ok, false);
|
||
} finally { global.fetch = saved; }
|
||
assert.equal(makeTimeoutError(8).timeout, true);
|
||
});
|
||
|
||
test('friendlyError turns a timeout abort into a readable message', () => {
|
||
const { friendlyError } = loadTs('src-ts/core/format.ts');
|
||
assert.equal(friendlyError(makeTimeoutError(8000)), '请求超时,请检查网络后重试');
|
||
assert.equal(friendlyError({ name: 'AbortError', message: '' }), '请求超时,请检查网络后重试');
|
||
assert.equal(friendlyError(new Error('boom')), 'boom');
|
||
});
|
||
|
||
// ---------- F7:getBikeState 判定顺序 ----------
|
||
const { getBikeState, getBikeStateText } = loadTs('src-ts/map/icons.ts');
|
||
|
||
test('getBikeState order: 损坏 → 使用中 → 欠压 → 低电量 → 空闲', () => {
|
||
assert.equal(getBikeState({ state: 2, status: 0, electric_quantity: 90 }), 'reserved');
|
||
assert.equal(getBikeState({ state: 1, status: 1, electric_quantity: 90 }), 'inuse');
|
||
assert.equal(getBikeState({ state: 4, status: 0, electric_quantity: 90 }), 'locked');
|
||
assert.equal(getBikeState({ state: 10, status: 0, electric_quantity: 90 }), 'lowbattery');
|
||
// 15% 的空闲车:到处都是「低电量」,不再是「空闲」
|
||
assert.equal(getBikeState({ state: 1, status: 0, electric_quantity: 15 }), 'lowbattery');
|
||
assert.equal(getBikeStateText({ state: 1, status: 0, electric_quantity: 15 }), '低电量');
|
||
assert.equal(getBikeState({ state: 1, status: 0, electric_quantity: 20 }), 'available');
|
||
assert.equal(getBikeStateText({ state: 1, status: 0, electric_quantity: 20 }), '空闲');
|
||
assert.equal(getBikeState({ state: 1, status: 0, electricQuantity: 55 }), 'available');
|
||
assert.equal(getBikeState({ state: 1, status: 0 }), 'available', '缺电量字段默认 100');
|
||
assert.equal(getBikeState({ state: 9, status: 0 }), 'unknown');
|
||
// 顺序:损坏优先于使用中/低电量;使用中优先于低电量
|
||
assert.equal(getBikeState({ state: 2, status: 1, electric_quantity: 10 }), 'reserved');
|
||
assert.equal(getBikeState({ state: 1, status: 1, electric_quantity: 10 }), 'inuse');
|
||
assert.equal(getBikeState({ state: 4, status: 0, electric_quantity: 10 }), 'locked');
|
||
});
|
||
|
||
// ---------- F4:toast 栈位置(纯函数切片) ----------
|
||
test('toastStackTop sits below the order banner when it is shown, otherwise at the default top', () => {
|
||
const toastStackTop = evalFunction('src-ts/ui/modals.ts', 'toastStackTop', { Number });
|
||
assert.equal(toastStackTop(58.5), 66.5, '横幅底边 58.5px → toast 栈贴在它下方 8px');
|
||
assert.equal(toastStackTop(null), 80);
|
||
assert.equal(toastStackTop(0), 80);
|
||
assert.equal(toastStackTop(undefined, 100), 100);
|
||
});
|
||
|
||
test('toast stack DOM/CSS/JS constraints (max 3, independent 2500ms, role=status)', () => {
|
||
const src = read('src-ts/ui/modals.ts');
|
||
assert.match(src, /const TOAST_MAX = 3;/);
|
||
assert.match(src, /export const TOAST_MS = 2500;/);
|
||
assert.match(src, /item\.setAttribute\("role", "status"\)/);
|
||
assert.match(src, /while \(stack\.children\.length >= TOAST_MAX/, '超过 3 条要先移除最旧的');
|
||
assert.doesNotMatch(src.slice(src.indexOf('export function showToast'), src.indexOf('// ========== 定位失败兜底弹窗')),
|
||
/getElementById\("toast"\)\.textContent/, '新路径不能再写死单个 #toast');
|
||
assert.match(read('templates/map.html'), /<div id="toast-stack" aria-live="polite"><\/div>/);
|
||
assert.match(read('static/css/map.css'), /#toast-stack\s*\{/);
|
||
});
|
||
|
||
// ---------- F1:定位策略 ----------
|
||
test('location strategy: no auto locate at init, silent start after login, FAB goes through ensureLocation', () => {
|
||
const core = read('src-ts/map/core.ts');
|
||
const initCore = core.slice(core.indexOf('export function initMapCore'), core.indexOf('// ========== 深色模式适配'));
|
||
assert.doesNotMatch(initCore, /\n\s*startAutoLocation\(\);/, '地图初始化里不能再对访客直接 startAutoLocation()');
|
||
assert.match(initCore, /startAutoLocationIfLoggedIn\(\);/);
|
||
assert.match(core, /if \(!S\.authToken \|\| !S\.map\) return Promise\.resolve\(false\);/, '静默定位必须同时满足已登录 + 地图就绪');
|
||
const startAuto = core.slice(core.indexOf('export function startAutoLocation('), core.indexOf('export function startAutoLocationIfLoggedIn'));
|
||
assert.ok(startAuto.includes('const silent = !!(opts && opts.silent);'), 'startAutoLocation 要认 silent 选项');
|
||
assert.ok(startAuto.includes('if (!silent) showToast("正在获取您的位置...");'), 'silent 时不弹「正在获取您的位置...」');
|
||
const fab = core.slice(core.indexOf('export function findNearestBikeManual'), core.indexOf('// 显示我的位置'));
|
||
assert.match(fab, /ensureLocation\(point => findNearestBike\(point\)/);
|
||
assert.doesNotMatch(fab.replace(/\/\/.*$/mg, ''), /请先开启定位/, 'FAB 不再只 toast「请先开启定位」');
|
||
const ensure = core.slice(core.indexOf('export function ensureLocation'));
|
||
assert.match(ensure, /Number\(err\.code\) === 1/, 'PERMISSION_DENIED 走卡片');
|
||
assert.match(ensure, /iOS:设置 → Safari → 位置;微信:右上角 … → 设置 → 位置/);
|
||
assert.match(ensure, /okText: "用地图中心找车"/);
|
||
assert.match(read('src-ts/nav/navigation.ts'), /ensureLocation\(pt => startNavigation\(bike, pt\), \{ verb: "导航" \}\)/, '卡片「导航」按钮走同一条定位路径');
|
||
assert.match(read('src-ts/order/actions.ts'), /ensureLocation\(point => applyCurrentLocation\(point\)/);
|
||
const settings = read('src-ts/ui/settings.ts');
|
||
assert.ok((settings.match(/startAutoLocationIfLoggedIn\(\);/g) || []).length >= 3, '登录/注册/登录态校验三条路径都要挂静默定位');
|
||
assert.match(read('templates/map.html'), /id="location-fallback-modal"[\s\S]*id="location-fallback-ok">用地图中心找车</);
|
||
});
|
||
|
||
// ---------- F2 / F3:计时条 & 登出清理 ----------
|
||
test('rental/status must not clear an unlock/share timer bar', () => {
|
||
const rentalIsFromRealOrder = evalFunction('src-ts/order/actions.ts', 'rentalIsFromRealOrder', { S: {} });
|
||
assert.equal(rentalIsFromRealOrder({ source: 'unlock' }), true);
|
||
assert.equal(rentalIsFromRealOrder({ source: 'share' }), true);
|
||
assert.equal(rentalIsFromRealOrder({ source: 'reminder' }), false);
|
||
assert.equal(rentalIsFromRealOrder({}), false);
|
||
assert.equal(rentalIsFromRealOrder(null), false);
|
||
const actions = read('src-ts/order/actions.ts');
|
||
const check = actions.slice(actions.indexOf('export function checkRentalStatus'), actions.indexOf('export function resetUserState'));
|
||
assert.doesNotMatch(check, /^\s*clearRentalState\(\);/m, 'checkRentalStatus 里不能再直接 clearRentalState()');
|
||
assert.ok((check.match(/clearRentalStateUnlessRealOrder\(\)/g) || []).length === 2);
|
||
const sync = actions.slice(actions.indexOf('export async function syncWechatOrder'), actions.indexOf('export function rentalIsFromRealOrder'));
|
||
assert.doesNotMatch(sync, /^\s*clearRentalState\(\);/m);
|
||
assert.match(actions, /order_id: rentalId \|\| null,[\s\S]*bike_code: bikeCode,/, 'startRentalFromServer 要存 order_id');
|
||
const status = read('src-ts/order/status.ts');
|
||
assert.match(status, /if \(hadOrder && rentalIsFromRealOrder\(\)\) clearRentalState\(\);/, '只有订单横幅报告订单结束才清真实订单计时条');
|
||
});
|
||
|
||
test('resetUserState clears banner, timer, order, share banners and localStorage; wired into logout and kick', () => {
|
||
const actions = read('src-ts/order/actions.ts');
|
||
const fn = actions.slice(actions.indexOf('export function resetUserState'), actions.indexOf('// static/js/map.js:3894'));
|
||
for (const piece of ['hideOrderBanner()', 'clearRentalState()', 'S.currentOrder = null', 'getElementById("share-banners")', 'localStorage.removeItem(RENTAL_KEY)']) {
|
||
assert.ok(fn.includes(piece), `resetUserState 缺少 ${piece}`);
|
||
}
|
||
const settings = read('src-ts/ui/settings.ts');
|
||
const logout = settings.slice(settings.indexOf('export async function handleLogout'), settings.indexOf('export function updateAuthButton'));
|
||
assert.match(logout, /resetUserState\(\);/);
|
||
const check = settings.slice(settings.indexOf('export async function checkAuthStatus'), settings.indexOf('// ========== 订单状态检测'));
|
||
assert.match(check, /resetUserState\(\);/);
|
||
});
|
||
|
||
// ---------- F6:core/actions 里的业务 fetch 都带超时 ----------
|
||
test('no bare fetch( left in map/core.ts, order/actions.ts, core/http.ts (SSE excluded)', () => {
|
||
for (const f of ['src-ts/map/core.ts', 'src-ts/order/actions.ts', 'src-ts/core/http.ts']) {
|
||
assert.doesNotMatch(read(f), /(^|[^\w.])fetch\(/, `${f} 仍有裸 fetch(`);
|
||
}
|
||
assert.match(read('src-ts/map/core.ts'), /showMapLoadFailure\("config", friendlyError\(err\)\)/, 'config 超时/失败要落到失败卡片');
|
||
});
|
||
|
||
// ---------- F8 / F13 / F14 ----------
|
||
test('renderMap refreshes or closes the open card; scanCode guards 401/non-JSON; refreshMap forces a request', () => {
|
||
const markers = read('src-ts/map/markers.ts');
|
||
assert.match(markers, /showBikeDetail\(fresh\.code, \{ pan: false \}\)/);
|
||
assert.match(markers, /showToast\("这辆车已离开实时列表"\)/);
|
||
assert.match(read('src-ts/card/bike-card.ts'), /showBikeDetail\(id, opts\?: any\)/);
|
||
const actions = read('src-ts/order/actions.ts');
|
||
const scan = actions.slice(actions.indexOf('export async function scanCode'), actions.indexOf('export function handleScanResult'));
|
||
assert.match(scan, /btn\.disabled = true; btn\.textContent = "查询中\.\.\."/);
|
||
assert.match(scan, /if \(resp\.status === 401\) \{ showLoginGate\(\); return; \}/);
|
||
assert.match(scan, /if \(!data \|\| typeof data !== "object"\) \{ showLoginGate\(\); return; \}/);
|
||
assert.match(actions, /S\.map\?\.panTo\(/);
|
||
const core = read('src-ts/map/core.ts');
|
||
assert.match(core, /export function loadMapData\(type, showLoading = true, quiet = false, force = false\)/);
|
||
assert.match(core, /if \(mapRequest && mapRequest\.type === String\(type\) && !force\) return mapRequest\.promise;/);
|
||
const refresh = core.slice(core.indexOf('export function refreshMap'), core.indexOf('// ========== 渲染地图'));
|
||
assert.match(refresh, /loadMapData\(S\.currentType, false, false, true\)/);
|
||
assert.match(refresh, /\.finally\(\(\) => btn\.classList\.remove\("spinning"\)\)/, '转圈必须跟真实请求绑定');
|
||
assert.doesNotMatch(refresh, /setTimeout\(/);
|
||
});
|
||
|
||
// ---------- F10 / F11 / F12 / bike-clusters ----------
|
||
test('templates and static script constraints', () => {
|
||
const map = read('templates/map.html');
|
||
assert.match(map, /<label class="share-cfg-check">\s*<input type="checkbox" id="sharecfg-card" checked \/>/);
|
||
assert.doesNotMatch(map, /sharecfg-card'\)\.checked=!document/, '外层 div 的 onclick 切换要删掉');
|
||
const analysis = read('templates/analysis.html');
|
||
assert.match(analysis, /<script defer src="https:\/\/cdn\.jsdelivr\.net\/npm\/echarts@5\.4\.3\/dist\/echarts\.min\.js" onerror="chartLibLoadFailed\('echarts'\)"><\/script>/);
|
||
assert.match(analysis, /<script defer src="https:\/\/unpkg\.com\/mapvgl\/dist\/mapvgl\.min\.js" onerror=/);
|
||
assert.match(analysis, /图表库加载失败,请检查网络后刷新/);
|
||
assert.match(analysis, /if \(typeof window\.echarts === 'undefined'\) \{ chartLibLoadFailed\('echarts'\); return; \}/, 'echarts.init 前要判空');
|
||
const bmap = analysis.slice(analysis.indexOf('function initBaiduMap'), analysis.indexOf('function showMapFailure'));
|
||
assert.match(bmap, /showMapFailure\(containerId,/, 'BMap 超时要显示失败卡片');
|
||
assert.match(analysis, /const loading = el\.querySelector\('\.loading'\);\s*if \(loading\) loading\.remove\(\);\s*if \(el\.querySelector\('\.map-failure'\)\) return;/);
|
||
const sub = read('src-ts/subscribe/subscribe.ts');
|
||
assert.match(sub, /await appConfirm\("删除这条订阅规则?"/);
|
||
assert.match(sub, /class="btn tap-44"[^>]*deleteSubscribeRule/);
|
||
assert.match(read('static/css/map.css'), /\.tap-44 \{ min-height: 44px; min-width: 44px; \}/);
|
||
const clusters = read('static/js/bike-clusters.js');
|
||
assert.match(clusters, /typeof motionQuery\.addEventListener === 'function'\) motionQuery\.addEventListener\('change', schedule\);/);
|
||
assert.match(clusters, /else if \(typeof motionQuery\.addListener === 'function'\) motionQuery\.addListener\(schedule\);/);
|
||
});
|