后端 · 订单与计时器(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
312 lines
15 KiB
JavaScript
312 lines
15 KiB
JavaScript
/* Numeric coordinates, pixel-distance clustering and native, cross-fading overlays. */
|
||
(function (root) {
|
||
'use strict';
|
||
|
||
// BMapGL's top three levels (19, 20, 21) always show individual bikes.
|
||
const SINGLE_BIKE_ZOOM = 19;
|
||
const PREFERENCE_KEY = 'xbniu_map_clustering';
|
||
|
||
function readClusteringPreference(storage) {
|
||
try { return storage.getItem(PREFERENCE_KEY) !== 'false'; }
|
||
catch (error) { return true; }
|
||
}
|
||
|
||
function writeClusteringPreference(storage, enabled) {
|
||
try { storage.setItem(PREFERENCE_KEY, String(!!enabled)); return true; }
|
||
catch (error) { return false; }
|
||
}
|
||
|
||
function coordinate(value, limit) {
|
||
if (typeof value !== 'number' && typeof value !== 'string') return null;
|
||
if (typeof value === 'string' && !value.trim()) return null;
|
||
const n = Number(value);
|
||
return Number.isFinite(n) && Math.abs(n) <= limit ? n : null;
|
||
}
|
||
|
||
function normalizeBikes(bikes) {
|
||
return (bikes || []).flatMap(bike => {
|
||
if (!bike) return [];
|
||
const latitude = coordinate(bike.latitude, 90);
|
||
const longitude = coordinate(bike.longitude, 180);
|
||
if (latitude === null || longitude === null || (latitude === 0 && longitude === 0)) return [];
|
||
return [{ ...bike, latitude, longitude, state: Number(bike.state), status: Number(bike.status) }];
|
||
});
|
||
}
|
||
|
||
function bikeId(bike) {
|
||
return String(parseInt(bike.code, 10) || bike.code || bike.id || `${bike.latitude},${bike.longitude}`);
|
||
}
|
||
|
||
// Look in neighbouring spatial buckets, then measure an actual pixel radius.
|
||
// Anchors stay fixed during each pass: a chain of cars cannot swallow the campus.
|
||
// Sorting by ID makes results independent of response order and map panning.
|
||
function clusterBikes(bikes, project, getPoint, getState, radius = 64, selectedId = null, zoom = 0, enabled = true) {
|
||
const buckets = new Map();
|
||
const groups = [];
|
||
const clusteringEnabled = enabled && zoom < SINGLE_BIKE_ZOOM;
|
||
const sorted = normalizeBikes(bikes).sort((a, b) => bikeId(a).localeCompare(bikeId(b), 'en'));
|
||
sorted.forEach(bike => {
|
||
const point = getPoint(bike);
|
||
if (!point || !Number.isFinite(point.lat) || !Number.isFinite(point.lng)) return;
|
||
const pixel = project(point);
|
||
if (!pixel || !Number.isFinite(pixel.x) || !Number.isFinite(pixel.y)) return;
|
||
const id = bikeId(bike);
|
||
const gx = Math.floor(pixel.x / radius), gy = Math.floor(pixel.y / radius);
|
||
let nearest = null, distance = radius * radius;
|
||
if (clusteringEnabled && id !== String(selectedId)) {
|
||
for (let x = gx - 1; x <= gx + 1; x++) {
|
||
for (let y = gy - 1; y <= gy + 1; y++) {
|
||
(buckets.get(`${x}:${y}`) || []).forEach(group => {
|
||
const d = (group.x - pixel.x) ** 2 + (group.y - pixel.y) ** 2;
|
||
if (d < distance) { nearest = group; distance = d; }
|
||
});
|
||
}
|
||
}
|
||
}
|
||
if (!nearest) {
|
||
nearest = { x: pixel.x, y: pixel.y, members: [], lat: 0, lng: 0 };
|
||
groups.push(nearest);
|
||
if (clusteringEnabled && id !== String(selectedId)) {
|
||
const key = `${gx}:${gy}`;
|
||
if (!buckets.has(key)) buckets.set(key, []);
|
||
buckets.get(key).push(nearest);
|
||
}
|
||
}
|
||
nearest.members.push(bike);
|
||
nearest.lat += point.lat;
|
||
nearest.lng += point.lng;
|
||
});
|
||
return groups.map(group => {
|
||
const count = group.members.length;
|
||
const ids = group.members.map(bikeId);
|
||
return {
|
||
key: `${count === 1 ? 'bike' : 'cluster'}:${ids.join(',')}`, ids,
|
||
members: group.members, count,
|
||
point: { lat: group.lat / count, lng: group.lng / count },
|
||
available: group.members.filter(bike => getState(bike) === 'available').length,
|
||
size: count === 1 ? 36 : Math.min(72, 48 + Math.log2(count) * 3),
|
||
offset: { x: 0, y: 0 }
|
||
};
|
||
});
|
||
}
|
||
|
||
function createLayer(options) {
|
||
const { map, getPoint, getState, getIcon, onBikeClick } = options;
|
||
const layer = document.createElement('div');
|
||
layer.className = 'bike-bubble-layer';
|
||
// Native overlay pixels and the SDK's pane share the same camera transform.
|
||
// Screen pixels in a sibling DOM layer can lag behind a reverse zoom.
|
||
function BubbleOverlay() {}
|
||
BubbleOverlay.prototype = new BMapGL.Overlay();
|
||
const overlay = new BubbleOverlay();
|
||
overlay.initialize = () => {
|
||
map.getPanes().labelPane.appendChild(layer);
|
||
return layer;
|
||
};
|
||
overlay.draw = () => { records.forEach(position); };
|
||
const motionQuery = window.matchMedia('(prefers-reduced-motion: reduce)');
|
||
let records = new Map(), bikes = [], selectedId = null;
|
||
let clusteringEnabled = options.enabled !== false;
|
||
let frame = 0, regroupFrame = 0, expandedKey = null, destroyed = false;
|
||
const listeners = [];
|
||
map.addOverlay(overlay);
|
||
|
||
function point(value) { return new BMapGL.Point(value.lng, value.lat); }
|
||
function schedule() {
|
||
if (!frame && !destroyed) frame = requestAnimationFrame(draw);
|
||
}
|
||
function position(record) {
|
||
const p = map.pointToOverlayPixel(point(record.position));
|
||
if (!p || !Number.isFinite(p.x) || !Number.isFinite(p.y)) {
|
||
record.el.style.visibility = 'hidden';
|
||
return;
|
||
}
|
||
record.el.style.visibility = '';
|
||
record.el.style.transform = `translate3d(${p.x + record.offset.x}px,${p.y + record.offset.y}px,0)`;
|
||
record.button.style.transform = 'translate(-50%,-50%)';
|
||
record.button.style.opacity = record.opacity;
|
||
}
|
||
// Only opacity changes: every marker stays anchored to its actual coordinate.
|
||
function fade(record, retiring) {
|
||
record.retiring = retiring;
|
||
record.fadeFrom = record.opacity;
|
||
record.fadeStart = performance.now();
|
||
}
|
||
function draw(now) {
|
||
frame = 0;
|
||
let moving = false;
|
||
records.forEach((record, key) => {
|
||
const progress = motionQuery.matches ? 1 : Math.min(Math.max((now - record.fadeStart) / 160, 0), 1);
|
||
const eased = 1 - (1 - progress) ** 3;
|
||
record.opacity = record.fadeFrom + ((record.retiring ? 0 : 1) - record.fadeFrom) * eased;
|
||
position(record);
|
||
if (record.retiring && progress === 1) { record.el.remove(); records.delete(key); }
|
||
moving = moving || progress < 1;
|
||
});
|
||
if (moving) schedule();
|
||
}
|
||
|
||
function updateContent(record, node) {
|
||
record.node = node;
|
||
record.position = { ...node.point };
|
||
record.offset = node.offset;
|
||
record.el.style.zIndex = node.count > 1 ? '2' : '3';
|
||
const button = record.button;
|
||
button.className = node.count > 1 ? 'bike-bubble' : 'bike-dot';
|
||
button.style.setProperty('--bubble-size', `${node.size}px`);
|
||
if (node.count > 1) {
|
||
button.classList.toggle('is-unavailable', node.available === 0);
|
||
button.style.setProperty('--available-angle', `${node.available / node.count * 360}deg`);
|
||
if (!record.countEl) {
|
||
button.replaceChildren();
|
||
const ring = document.createElement('span'); ring.className = 'bike-bubble-ring';
|
||
ring.setAttribute('aria-hidden', 'true');
|
||
record.countEl = document.createElement('span'); record.countEl.className = 'bike-bubble-count';
|
||
record.labelEl = document.createElement('span'); record.labelEl.className = 'bike-bubble-label';
|
||
button.append(ring, record.countEl, record.labelEl);
|
||
}
|
||
record.countEl.textContent = node.count;
|
||
record.labelEl.textContent = node.available ? `${node.available} 可用` : '暂无可用';
|
||
button.setAttribute('aria-label', `${node.count} 辆电动车,${node.available} 辆可用,点击展开`);
|
||
} else {
|
||
record.setIcon(getIcon(node.members[0], node.ids[0] === String(selectedId)));
|
||
record.setTitle(`#${node.members[0].code}`);
|
||
button.setAttribute('aria-label', `查看电动车 #${node.members[0].code}`);
|
||
}
|
||
}
|
||
|
||
function createRecord(node) {
|
||
const el = document.createElement('div'); el.className = 'bike-bubble-anchor';
|
||
const button = document.createElement('button'); button.type = 'button';
|
||
el.appendChild(button); layer.appendChild(el);
|
||
const record = {
|
||
el, button, node, position: { ...node.point }, offset: node.offset,
|
||
opacity: 0, fadeFrom: 0, fadeStart: performance.now(), retiring: false,
|
||
__animId: node.ids[0],
|
||
getPosition() { return point(this.position); },
|
||
getTitle() { return this.button.title; },
|
||
setTitle(title) { this.button.title = title; },
|
||
setIcon(icon) {
|
||
const appearance = icon.__xbniuAppearance;
|
||
if (!appearance) return;
|
||
let img = this.button.querySelector('img');
|
||
if (!img) { img = document.createElement('img'); img.alt = ''; this.button.replaceChildren(img); }
|
||
if (img.getAttribute('src') !== appearance.url) img.src = appearance.url;
|
||
this.button.style.width = this.button.style.height = `${appearance.size}px`;
|
||
this.el.style.zIndex = appearance.size > 36 ? '5' : '3';
|
||
},
|
||
bringToTop() { this.el.style.zIndex = '6'; }
|
||
};
|
||
// Never turn movement across a bubble into a tap.
|
||
let down = null;
|
||
button.addEventListener('pointerdown', event => { down = { x: event.clientX, y: event.clientY }; });
|
||
button.addEventListener('click', event => {
|
||
event.stopPropagation();
|
||
if (down && Math.hypot(event.clientX - down.x, event.clientY - down.y) > 8) { down = null; return; }
|
||
down = null;
|
||
if (record.retiring) return;
|
||
if (record.node.count === 1) onBikeClick(record.node.ids[0]);
|
||
else expand(record.node);
|
||
});
|
||
button.addEventListener('dblclick', event => event.stopPropagation());
|
||
updateContent(record, node);
|
||
position(record);
|
||
return record;
|
||
}
|
||
|
||
function render(nodes) {
|
||
const nextKeys = new Set(nodes.map(node => node.key));
|
||
nodes.forEach(node => {
|
||
let record = records.get(node.key);
|
||
if (!record) {
|
||
record = createRecord(node);
|
||
records.set(node.key, record);
|
||
} else {
|
||
updateContent(record, node);
|
||
if (record.retiring) fade(record, false);
|
||
}
|
||
record.button.disabled = false;
|
||
});
|
||
records.forEach((record, key) => {
|
||
if (nextKeys.has(key)) return;
|
||
if (!record.retiring) fade(record, true);
|
||
record.button.disabled = true;
|
||
});
|
||
options.onMarkersChanged(Array.from(records.values()).filter(r => !r.retiring && r.node.count === 1));
|
||
schedule();
|
||
}
|
||
|
||
function regroup() {
|
||
regroupFrame = 0;
|
||
if (destroyed) return;
|
||
expandedKey = null;
|
||
render(clusterBikes(bikes, p => map.pointToOverlayPixel(point(p)), getPoint, getState, 64, selectedId, map.getZoom(), clusteringEnabled));
|
||
}
|
||
function requestRegroup() {
|
||
schedule();
|
||
if (!regroupFrame) regroupFrame = requestAnimationFrame(regroup);
|
||
}
|
||
function expand(node) {
|
||
const zoom = map.getZoom();
|
||
const coincident = node.members.every(bike => {
|
||
const p = getPoint(bike);
|
||
return Math.abs(p.lat - node.point.lat) + Math.abs(p.lng - node.point.lng) < 1e-8;
|
||
});
|
||
if (zoom < 21 && !coincident) {
|
||
map.centerAndZoom(point(node.point), Math.min(21, zoom + 2));
|
||
return;
|
||
}
|
||
// Identical GPS positions still need individually tappable cars.
|
||
// A golden-angle spiral keeps even a dense parking spot separated.
|
||
expandedKey = node.key;
|
||
const others = Array.from(records.values()).filter(r => !r.retiring && r.node.key !== node.key).map(r => r.node);
|
||
const singles = node.members.map((bike, index) => {
|
||
const angle = index * 2.399963229728653;
|
||
const radius = 38 * Math.sqrt(index + 1);
|
||
const id = bikeId(bike);
|
||
return { key: `bike:${id}`, ids: [id], members: [bike], count: 1,
|
||
available: getState(bike) === 'available' ? 1 : 0, size: 36,
|
||
point: getPoint(bike), offset: { x: Math.cos(angle) * radius, y: Math.sin(angle) * radius } };
|
||
});
|
||
render(others.concat(singles));
|
||
}
|
||
function listen(name, fn) { map.addEventListener(name, fn); listeners.push([name, fn]); }
|
||
listen('moving', schedule);
|
||
listen('zooming', schedule);
|
||
listen('moveend', () => { if (expandedKey) requestRegroup(); else schedule(); });
|
||
listen('zoomend', requestRegroup);
|
||
listen('resize', requestRegroup);
|
||
listen('click', () => { if (expandedKey) requestRegroup(); });
|
||
// 老 Safari(<14)的 MediaQueryList 只有 addListener,没有 addEventListener
|
||
if (typeof motionQuery.addEventListener === 'function') motionQuery.addEventListener('change', schedule);
|
||
else if (typeof motionQuery.addListener === 'function') motionQuery.addListener(schedule);
|
||
|
||
return {
|
||
setData(data) { bikes = normalizeBikes(data); regroup(); },
|
||
setClusteringEnabled(enabled) {
|
||
clusteringEnabled = !!enabled;
|
||
regroup();
|
||
},
|
||
setSelected(id) {
|
||
if (String(selectedId) === String(id)) return;
|
||
selectedId = id;
|
||
requestRegroup();
|
||
},
|
||
refresh: requestRegroup,
|
||
destroy() {
|
||
destroyed = true;
|
||
cancelAnimationFrame(frame); cancelAnimationFrame(regroupFrame);
|
||
listeners.forEach(([name, fn]) => map.removeEventListener(name, fn));
|
||
motionQuery.removeEventListener('change', schedule);
|
||
map.removeOverlay(overlay);
|
||
layer.remove(); records.clear();
|
||
}
|
||
};
|
||
}
|
||
|
||
const api = { normalizeBikes, bikeId, clusterBikes, createLayer,
|
||
PREFERENCE_KEY, readClusteringPreference, writeClusteringPreference };
|
||
if (typeof module !== 'undefined' && module.exports) module.exports = api;
|
||
else root.BikeClusters = api;
|
||
})(typeof window === 'undefined' ? globalThis : window);
|