feat: drill defect trends into detailed rates and preserve query context

This commit is contained in:
2026-11-13 13:37:32 +08:00
parent 48ae58e577
commit 63bf8c16d3
31 changed files with 1215 additions and 107 deletions
+113 -17
View File
@@ -1,12 +1,13 @@
import { isValidElement, type Key } from 'react';
import { getStoredWorkspaceThemeId, getWorkspaceTheme, type WorkspaceThemeId } from './ui-themes.ts';
type ExportColumn = { exportRate?: boolean; key?: Key; title?: unknown; children?: readonly ExportColumn[] };
type ExportColumn = { exportRate?: boolean; key?: Key; title?: unknown; width?: string | number; children?: readonly ExportColumn[] };
type ExportValue = string | number | null;
function nodeText(node: unknown): string {
if (typeof node === 'string' || typeof node === 'number') return String(node);
if (Array.isArray(node)) return node.map(nodeText).join('');
if (isValidElement<{ children?: unknown }>(node)) return nodeText(node.props.children);
if (isValidElement<{ children?: unknown }>(node)) return `${node.type === 'small' ? '\n' : ''}${nodeText(node.props.children)}`;
return '';
}
@@ -22,24 +23,119 @@ export function workbookColumns(columns: readonly ExportColumn[], parents: strin
});
}
export async function createMetricWorkbook<T>(columns: readonly ExportColumn[], rows: readonly T[], value: (key: string, row: T) => ExportValue) {
function dataColumns(columns: readonly ExportColumn[]): ExportColumn[] {
return columns.flatMap(column => {
if (column.children) {
const children = dataColumns(column.children);
return children.length ? [{ ...column, children }] : [];
}
return String(column.key ?? '') && column.key !== 'actions' ? [column] : [];
});
}
function mix(foreground: string, background: string, proportion: number): string {
return 'FF' + [1, 3, 5].map(offset => Math.round(
parseInt(foreground.slice(offset, offset + 2), 16) * proportion
+ parseInt(background.slice(offset, offset + 2), 16) * (1 - proportion),
).toString(16).padStart(2, '0')).join('').toUpperCase();
}
// Mirrors the query table's theme tokens and semantic colors. Dark always exports as light.
export function metricWorkbookPalette(themeId: WorkspaceThemeId = 'light') {
const theme = getWorkspaceTheme(themeId === 'dark' ? 'light' : themeId);
return {
ink: mix(theme.ink, theme.surface, 1), surface: mix(theme.surface, theme.surface, 1),
grid: mix(theme.metricGrid, theme.surface, 1), headGrid: mix(theme.metricGridHead, theme.surface, 1),
head: mix(theme.surface, theme.background, .55), alternate: mix(theme.surface, theme.soft, .97),
black: 'FF20252B', bright: mix(theme.primary, theme.surface, 1), combined: mix(theme.teal, theme.surface, 1),
blackHead: mix('#20252B', theme.surface, .07), brightHead: mix(theme.primary, theme.surface, .10),
combinedFill: mix(theme.teal, theme.surface, .05),
};
}
export async function createMetricWorkbook<T>(columns: readonly ExportColumn[], rows: readonly T[], value: (key: string, row: T) => ExportValue, themeId: WorkspaceThemeId = getStoredWorkspaceThemeId()) {
const { default: ExcelJS } = await import('exceljs');
const workbook = new ExcelJS.Workbook();
const sheet = workbook.addWorksheet('质量汇总', { views: [{ state: 'frozen', xSplit: 1, ySplit: 1 }] });
const fields = workbookColumns(columns);
sheet.columns = fields.map(field => ({ header: field.header, key: field.key, width: field.key === 'object' ? 38 : Math.max(18, Math.min(field.header.length * 2, 48)) }));
for (const row of rows) sheet.addRow(fields.map(field => {
const result = value(field.key, row);
return typeof result === 'number' && !Number.isFinite(result) ? null : result;
}));
fields.forEach((field, index) => {
if (field.key !== 'object') sheet.getColumn(index + 1).numFmt = field.rate ? '0.00%' : '#,##0.0';
workbook.creator = '质量数据分析平台';
const tree = dataColumns(columns);
const fields = workbookColumns(tree);
const depth = (items: readonly ExportColumn[]): number => Math.max(1, ...items.map(column => column.children ? 1 + depth(column.children) : 1));
const headerRows = depth(tree);
const palette = metricWorkbookPalette(themeId);
const sheet = workbook.addWorksheet('质量汇总', {
views: [{ state: 'frozen', xSplit: fields.length ? 1 : 0, ySplit: headerRows, showGridLines: false }],
properties: { defaultRowHeight: 26.25 },
pageSetup: { orientation: 'landscape', paperSize: 9, fitToPage: true, fitToWidth: 1, fitToHeight: 0 },
});
sheet.getRow(1).font = { bold: true, color: { argb: 'FFFFFFFF' } };
sheet.getRow(1).fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FF6379DF' } };
sheet.getRow(1).alignment = { vertical: 'middle', wrapText: true };
sheet.getRow(1).height = 36;
sheet.autoFilter = { from: { row: 1, column: 1 }, to: { row: Math.max(1, rows.length + 1), column: fields.length } };
if (!fields.length) return workbook;
const border = (argb: string) => ({
top: { style: 'thin' as const, color: { argb } }, bottom: { style: 'thin' as const, color: { argb } },
left: { style: 'thin' as const, color: { argb } }, right: { style: 'thin' as const, color: { argb } },
});
const solid = (argb: string) => ({ type: 'pattern' as const, pattern: 'solid' as const, fgColor: { argb } });
let leafIndex = 0;
const writeHeaders = (items: readonly ExportColumn[], level: number) => {
for (const column of items) {
const start = leafIndex + 1;
const key = String(column.key ?? '');
const isGroup = !!column.children;
if (column.children) writeHeaders(column.children, level + 1);
else {
leafIndex++;
const pixels = Number(column.width) || (key === 'object' ? 220 : 112);
sheet.getColumn(start).width = Math.max(14, Math.min(60, (pixels - 5) / 7));
sheet.getColumn(start).key = key;
sheet.getColumn(start).numFmt = key === 'object' ? '@' : fields[start - 1].rate ? '0.00%' : '#,##0.0';
}
const lastRow = isGroup ? level : headerRows;
const end = leafIndex;
const black = key === 'stage-black' || key === 'black-rate';
const bright = key === 'stage-bright' || key === 'bright-rate';
const combined = key === 'compositeRate';
const fill = combined ? palette.combinedFill : isGroup && black ? palette.blackHead : isGroup && bright ? palette.brightHead : palette.head;
const color = combined ? palette.combined : black ? palette.black : bright ? palette.bright : palette.ink;
for (let r = level; r <= lastRow; r++) for (let c = start; c <= end; c++) {
const cell = sheet.getCell(r, c);
cell.fill = solid(fill);
cell.border = border(palette.headGrid);
cell.font = { name: '微软雅黑', size: 10.5, bold: true, color: { argb: color } };
cell.alignment = { horizontal: 'center', vertical: 'middle', wrapText: true };
}
if (lastRow > level || end > start) sheet.mergeCells(level, start, lastRow, end);
const label = nodeText(column.title).trim();
sheet.getCell(level, start).value = !isGroup && key !== 'object' && !fields[start - 1].rate ? `${label}\n(kg)` : label;
}
};
writeHeaders(tree, 1);
for (let i = 1; i <= headerRows; i++) {
let lines = 1;
sheet.getRow(i).eachCell(cell => { if (typeof cell.value === 'string') lines = Math.max(lines, cell.value.split('\n').length); });
sheet.getRow(i).height = Math.max(27, lines * 16 + 6);
}
rows.forEach((row, index) => {
const exported = sheet.getRow(headerRows + index + 1);
let lines = 1;
fields.forEach((field, column) => {
const result = value(field.key, row);
const cell = exported.getCell(column + 1);
cell.value = typeof result === 'number' && !Number.isFinite(result) ? null : result;
const combined = field.key === 'compositeRate';
const color = combined ? palette.combined : field.key === 'black-rate' ? palette.black : field.key === 'bright-rate' ? palette.bright : palette.ink;
cell.font = { name: field.key === 'object' ? '微软雅黑' : 'Arial', size: combined ? 11.25 : field.key === 'object' ? 12 : 9.75, bold: field.key === 'object' || field.key.endsWith('-rate') || combined, color: { argb: color } };
cell.fill = solid(combined ? palette.combinedFill : index % 2 ? palette.alternate : palette.surface);
cell.border = border(palette.grid);
cell.alignment = { horizontal: 'center', vertical: 'middle', wrapText: true };
if (typeof result === 'string') {
const width = sheet.getColumn(column + 1).width! - 2;
const textLines = result.split(/\r?\n/).reduce((total, line) => total + Math.max(1, Math.ceil(Array.from(line).reduce((length, char) => length + (/[^\x00-\xff]/.test(char) ? 2 : 1), 0) / width)), 0);
lines = Math.max(lines, textLines);
}
});
exported.height = Math.max(26.25, lines * 16 + 8);
});
sheet.autoFilter = { from: { row: headerRows, column: 1 }, to: { row: headerRows + rows.length, column: fields.length } };
sheet.pageSetup.printTitlesRow = `1:${headerRows}`;
sheet.pageSetup.printArea = `A1:${sheet.getColumn(fields.length).letter}${headerRows + rows.length}`;
return workbook;
}