Files
quality_analyse/web/src/querySnapshot.ts
T
lyun 147b56d0fd 修复:快照合并分析图并支持导出订单对应表
快照将不良构成与柏拉图合并为一个选项,完整保留页面容器,黑片和亮片继续并排展示两张分析图;迁移旧快照选项并等待组合图的数据准备完成。

销售订单类型对应表支持下载当前生效版本的完整Excel,订单号按文本写入,保留前导零,沿用管理员角色与来源字段权限。导出开始时固定版本,使用滚动工作簿限制内存。

菜单、页面及快照标题统一改为黑片数据和亮片数据。

验证:11项前端检查、8项后端单元测试通过;157698条实际对应关系与数据库逐条一致,重新导入预览零变更;黑片完整快照和亮片单模块快照均通过视觉检查。
2026-11-04 09:06:07 +08:00

125 lines
8.5 KiB
TypeScript

export const QUERY_SNAPSHOT_MODULES = [
{ key: 'filters', label: '查询条件' }, { key: 'metrics', label: '指标卡片' },
{ key: 'trend', label: '变化趋势' }, { key: 'table', label: '汇总表' },
{ key: 'defects', label: '不良构成与柏拉图' },
] as const;
export type QuerySnapshotModule = typeof QUERY_SNAPSHOT_MODULES[number]['key'];
const KEYS = new Set<string>(QUERY_SNAPSHOT_MODULES.map(module => module.key));
export function parseSnapshotModules(raw: unknown): QuerySnapshotModule[] {
if (!Array.isArray(raw)) return QUERY_SNAPSHOT_MODULES.map(module => module.key);
const migrated = raw.map(key => key === 'pareto' ? 'defects' : key);
return QUERY_SNAPSHOT_MODULES.filter(module => migrated.includes(module.key) && KEYS.has(module.key)).map(module => module.key);
}
export function snapshotImageSize(width: number, height: number) {
if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) throw new Error('页面尺寸无效,请重试');
const pixelRatio = Math.min(2, 16384 / width, 16384 / height, Math.sqrt(32_000_000 / (width * height)));
if (pixelRatio < 1) throw new Error('所选内容过长,请减少模块或汇总表每页条数');
return { width: Math.ceil(width), height: Math.ceil(height), pixelRatio };
}
export function snapshotFilename(title: string, date = new Date()) {
const stamp = `${date.getFullYear()}${String(date.getMonth() + 1).padStart(2, '0')}${String(date.getDate()).padStart(2, '0')}-${String(date.getHours()).padStart(2, '0')}${String(date.getMinutes()).padStart(2, '0')}${String(date.getSeconds()).padStart(2, '0')}`;
return `${title.replace(/[\\/:*?"<>|]/g, '_')}-页面快照-${stamp}.png`;
}
export function snapshotModuleElements(root: HTMLElement, selected: QuerySnapshotModule[]) {
return QUERY_SNAPSHOT_MODULES.filter(module => selected.includes(module.key)).map(module => {
const node = root.querySelector<HTMLElement>(`[data-snapshot-module="${module.key}"]`);
if (!node || !node.offsetWidth) throw new Error(`当前页面没有可导出的“${module.label}”`);
return { ...module, node };
});
}
export function snapshotTask<T>(task: Promise<T>, signal: AbortSignal, timeoutMs: number, timeoutMessage: string): Promise<T> {
return new Promise((resolve, reject) => {
let settled = false;
const abort = () => finish(() => reject(new Error('已取消生成快照')));
const timer = setTimeout(() => finish(() => reject(new Error(timeoutMessage))), timeoutMs);
function finish(done: () => void) { if (settled) return; settled = true; clearTimeout(timer); signal.removeEventListener('abort', abort); done(); }
task.then(value => finish(() => resolve(value)), error => finish(() => reject(error)));
if (signal.aborted) abort();
else signal.addEventListener('abort', abort, { once: true });
});
}
/** Clone the selected modules only; never hide or reflow the live query page. */
export async function captureQuerySnapshot(root: HTMLElement, selected: QuerySnapshotModule[], title: string, cancelled: () => boolean, signal: AbortSignal, progress: (message: string) => void): Promise<Blob> {
if (!selected.length) throw new Error('请至少选择一个模块');
const check = () => { if (cancelled() || !root.isConnected || !root.offsetWidth) throw new Error('查询页面已变化,请重新生成快照'); };
check();
root.dispatchEvent(new CustomEvent('quality:query-snapshot', { detail: { modules: selected.includes('defects') ? [...selected, 'pareto'] : selected } }));
const modules = snapshotModuleElements(root, selected);
progress('正在等待所选模块加载完成…');
const started = performance.now();
let previous = '', stableSince = performance.now();
while (true) {
check();
const failed = modules.find(({ node }) => node.dataset.snapshotReady === 'error' || node.querySelector('[data-snapshot-ready="error"]'));
if (failed) throw new Error(`“${failed.label}”读取失败,请重试后生成快照`);
const busy = modules.some(({ node }) => node.dataset.snapshotReady === 'false' || node.matches('[aria-busy="true"],[inert]') || node.querySelector('[aria-busy="true"],[inert],[data-snapshot-ready="false"]'));
const signature = modules.map(({ node }) => node.innerHTML).join('');
if (signature !== previous || busy) { previous = signature; stableSince = performance.now(); }
if (!busy && performance.now() - stableSince >= 250) break;
if (performance.now() - started > 30_000) throw new Error('所选模块仍在更新,请等待查询完成后重试');
await new Promise(resolve => setTimeout(resolve, 80));
}
await snapshotTask(root.ownerDocument.fonts.ready, signal, 5000, '字体尚未加载完成,请稍后重试');
progress('正在生成图片…');
check();
const frame = document.createElement('div');
frame.className = `${root.className} query-snapshot-capture`;
frame.setAttribute('aria-hidden', 'true');
frame.inert = true;
Object.assign(frame.style, { position: 'fixed', left: '-100000px', top: '0', width: `${root.offsetWidth + 32}px`, padding: '16px', margin: '0', zIndex: '-1', pointerEvents: 'none', background: getComputedStyle(document.documentElement).backgroundColor });
const heading = document.createElement('header');
heading.className = 'query-snapshot-heading';
const name = document.createElement('strong'); name.textContent = title;
const time = document.createElement('span'); time.textContent = new Date().toLocaleString('zh-CN');
heading.append(name, time); frame.append(heading);
try {
for (const { key, node } of modules) {
const clone = node.cloneNode(true) as HTMLElement;
clone.removeAttribute('inert'); clone.removeAttribute('aria-busy');
// Canvas-based renderers need their pixels copied; SVG charts already clone losslessly.
const canvases = [...node.querySelectorAll('canvas')];
[...clone.querySelectorAll('canvas')].forEach((canvas, index) => {
const image = document.createElement('img'); image.src = canvases[index].toDataURL();
image.style.cssText = canvas.style.cssText; image.width = canvases[index].width; image.height = canvases[index].height;
canvas.replaceWith(image);
});
const sourceInputs = [...node.querySelectorAll<HTMLInputElement>('input')];
[...clone.querySelectorAll<HTMLInputElement>('input')].forEach((input, index) => {
input.value = sourceInputs[index].value; input.setAttribute('value', input.value); input.checked = sourceInputs[index].checked;
});
// Preserve the current horizontal table viewport in the rasterizer's non-scrolling clone.
const sourceScrollers = [...node.querySelectorAll<HTMLElement>('.ant-table-content,.ant-table-body')];
[...clone.querySelectorAll<HTMLElement>('.ant-table-content,.ant-table-body')].forEach((scroll, index) => {
const original = sourceScrollers[index];
if (original.scrollLeft && scroll.firstElementChild) {
scroll.style.overflow = 'hidden';
(scroll.firstElementChild as HTMLElement).style.transform = `translateX(-${original.scrollLeft}px)`;
}
});
if (key === 'filters') {
const more = node.querySelector<HTMLElement>('.query-more-toggle');
if (more?.title && more.querySelector('[aria-expanded="false"]')) {
const summary = document.createElement('div'); summary.className = 'query-snapshot-filter-summary'; summary.textContent = more.title; clone.append(summary);
}
}
clone.querySelectorAll('.query-snapshot-controls,.query-toolbar-tail,.query-status,.query-more-toggle,.query-export-button,.ant-select-dropdown,.ant-table-filter-trigger,.ant-tooltip,.mobile-scroll-hint').forEach(element => element.remove());
frame.append(clone);
}
root.append(frame);
await snapshotTask(Promise.all([...frame.querySelectorAll('img')].map(image => image.decode().catch(() => undefined))), signal, 5000, '图片资源读取超时,请重试');
check();
const size = snapshotImageSize(frame.offsetWidth, frame.scrollHeight);
const { toBlob } = await snapshotTask(import('html-to-image'), signal, 10000, '图片组件加载超时,请重试');
const blob = await snapshotTask(toBlob(frame, { ...size, skipAutoScale: true, skipFonts: true, backgroundColor: frame.style.background, style: { position: 'static', left: '0', top: '0', zIndex: 'auto', pointerEvents: 'none' } }), signal, 15000, '图片生成超时,请减少模块后重试');
check();
if (!blob || blob.size < 100) throw new Error('图片生成失败,请重试');
return blob;
} finally { frame.remove(); }
}