Files
quality_analyse/web/src/analysisProductDrilldown.ts
T
lyun ff7bbe3e46 同步:完善质量分析工作台并更新主题字体
同步已上线的智能分析执行协议、来源查询、图表报告与管理页面配套代码。
补齐数据库迁移、运行依赖和回归测试,保留原有指标计算口径。
统一午夜黑及其他主题的控件细节、中文和业务数字字体。
排除本地业务数据、凭据、预览、发布与验收产物。

验证:生产构建通过,320项前端回归通过;本轮仅同步Git,不再次部署。
2026-10-30 22:40:58 +08:00

164 lines
13 KiB
TypeScript

import { parseAnalysisVisuals } from './analysisVisualsModel.ts';
import type { AnalysisVisual } from './analysisVisualsModel.ts';
import type { FocusProductRow } from './analysisReportModel.ts';
import type { MetricsResponse, QueryParams, Stage, TrendMetricRow } from './types.ts';
import { analysisPeriodLabel, parseAnalysisPeriod } from './analysisPeriodModel.ts';
type Data = Record<string, unknown>;
export type ProductDrilldownView = 'defects' | 'trend' | 'records';
export type DrilldownPeriod = { year: number; month?: number; quarter?: number; monthStart?: number; monthEnd?: number };
export interface ProductDrilldownBinding {
turnId: string;
product: string;
stages: Stage[];
query: QueryParams & { releaseId: string };
periods: Array<{ key: 'current' | 'comparison'; label: string; period: DrilldownPeriod }>;
evidenceRefs: string[];
}
export type ProductDrilldownResolution = { binding: ProductDrilldownBinding; reason?: never } | { binding?: never; reason: string };
const record = (value: unknown): Data => value && typeof value === 'object' && !Array.isArray(value) ? value as Data : {};
const present = (value: unknown) => value !== undefined && value !== null && value !== '';
const canonical = (value: unknown): string => JSON.stringify(value && typeof value === 'object'
? Array.isArray(value) ? value.map(item => canonical(item)) : Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, canonical(item)])) : value);
const dimensions = ['department', 'group', 'product', 'projectGroup'] as const;
const scopeKeys = new Set(['year', 'month', 'quarter', 'monthStart', 'monthEnd', 'releaseId', ...dimensions, 'productSearch', 'includeUnassigned', 'extraFilters', 'exclusions', 'stage', 'view', 'trendGranularity']);
const hasExclusions = (value: unknown) => present(value) && (typeof value !== 'object' || Array.isArray(value) || Object.keys(record(value)).length > 0);
function periodOf(value: unknown): DrilldownPeriod | null {
const raw = record(value);
if (Object.keys(raw).some(key => !['year', 'month', 'quarter', 'monthStart', 'monthEnd'].includes(key))) return null;
const period = parseAnalysisPeriod(raw, 2000, 2100);
return period?.year ? period as DrilldownPeriod : null;
}
export function drilldownPeriodLabel(period: DrilldownPeriod): string {
return analysisPeriodLabel(period, 2000, 2100);
}
function selection(value: unknown): string[] | null {
if (Array.isArray(value)) return value.every(item => typeof item === 'string' && item.trim()) ? value as string[] : null;
if (typeof value !== 'string' || !value.trim()) return null;
if (value.startsWith('[')) { try { return selection(JSON.parse(value)); } catch { return null; } }
if (value.startsWith('~qv1~')) {
try {
const encoded = value.slice(5).replaceAll('-', '+').replaceAll('_', '/');
return selection(JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(encoded.padEnd(Math.ceil(encoded.length / 4) * 4, '=')), character => character.charCodeAt(0)))));
} catch { return null; }
}
return [value];
}
function wireSelection(value: unknown): string | null {
const values = selection(value);
if (!values?.length) return null;
if (values.length === 1) return values[0];
let binary = '';
new TextEncoder().encode(JSON.stringify(values)).forEach(byte => { binary += String.fromCharCode(byte); });
return `~qv1~${btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/g, '')}`;
}
function sameValue(key: string, a: unknown, b: unknown): boolean {
if (dimensions.includes(key as typeof dimensions[number])) return canonical(selection(a)) === canonical(selection(b));
return canonical(a) === canonical(b);
}
/** A row must have its own cited, server-bound product chart. Never infer a
* period from prose or borrow the mutable session / query-page filters. */
export function resolveProductDrilldown(turn: Data, row: FocusProductRow): ProductDrilldownResolution {
const result = Object.keys(record(turn.result)).length ? record(turn.result) : turn;
const plan = record(turn.plan || result.plan);
const turnId = String(turn.id || turn.turnId || '');
if (!turnId) return { reason: '本轮结果尚未保存,暂不能下钻。' };
const visuals = parseAnalysisVisuals(result.visuals || turn.visuals).visuals.filter(visual => visual.originTurnId === turnId
&& visual.dimension === 'product' && row.evidenceRefs.length === 1 && visual.evidenceRefs.includes(row.evidenceRefs[0])
&& visual.categories.some(category => category.key === row.product && category.label === row.product));
if (!visuals.length) return { reason: '本条依据未保存完整查询条件,暂不能下钻。' };
const bindings = visuals.map(visual => ({ scope: visual.scope, period: visual.period, comparisonPeriod: visual.comparisonPeriod, stage: visual.stage }));
if (new Set(bindings.map(canonical)).size !== 1) return { reason: '本条依据对应多个查询范围,暂不能下钻。' };
const visual = visuals[0], scope = record(visual.scope);
const current = periodOf(visual.period), comparison = visual.comparisonPeriod ? periodOf(visual.comparisonPeriod) : null;
if (!current || (visual.comparisonPeriod && !comparison)) return { reason: '本条依据的期间不完整,暂不能下钻。' };
if (Object.keys(scope).some(key => !scopeKeys.has(key))) return { reason: '本条依据含当前下钻不支持的筛选条件。' };
const contexts = [record(plan.context), record(plan.frozenContext), record(result.context), record(turn.context)];
if ([scope, ...contexts].some(context => hasExclusions(context.exclusions))) return { reason: '本轮含排除条件,现有查询入口无法完整沿用,暂不能下钻。' };
const releases = [scope.releaseId, result.releaseId, turn.releaseId, plan.releaseId, ...contexts.map(context => context.releaseId)].filter(present);
if (!releases.length || releases.some(value => typeof value !== 'string' || !value.trim()) || new Set(releases).size !== 1) return { reason: '本轮数据版本缺失或不一致,暂不能下钻。' };
for (const key of ['year', 'month', 'quarter', 'monthStart', 'monthEnd']) if (present(scope[key]) && scope[key] !== current[key as keyof DrilldownPeriod]) return { reason: '本条依据的期间与筛选不一致,暂不能下钻。' };
const stage = visual.stage || scope.stage || row.stage;
if (!['black', 'bright', 'all', 'combined'].includes(String(stage)) || (row.stage && row.stage !== 'all' && row.stage !== stage)
|| (visual.stage && present(scope.stage) && visual.stage !== scope.stage)) return { reason: '本条依据的阶段不明确,暂不能下钻。' };
const merged = { ...scope, ...current, stage };
for (const context of contexts) {
for (const [key, value] of Object.entries(context)) {
if (!present(value) || ['releaseId', 'view', 'resultRef', 'metricCode', 'trendGranularity'].includes(key)) continue;
if (!scopeKeys.has(key)) return { reason: '本轮冻结条件无法完整沿用,暂不能下钻。' };
if (key === 'exclusions' && !Object.keys(record(value)).length) continue;
if (key === 'extraFilters' && !Object.keys(record(value)).length) continue;
if (key === 'stage' && ['all', 'combined'].includes(String(value))) continue;
if (!sameValue(key, value, merged[key as keyof typeof merged])) return { reason: '本条依据与本轮冻结条件不一致,暂不能下钻。' };
}
}
const semantic = record(plan.semantic);
if (semantic.compare === true && Object.keys(record(semantic.priorContext)).length) {
const prior = record(semantic.priorContext);
if (!comparison || ['year', 'month', 'quarter', 'monthStart', 'monthEnd'].some(key => present(prior[key]) && prior[key] !== comparison[key as keyof DrilldownPeriod])
|| Object.entries(prior).some(([key, value]) => present(value) && !['year', 'month', 'quarter', 'monthStart', 'monthEnd', 'view', 'trendGranularity', 'resultRef', 'metricCode'].includes(key)
&& !(key === 'exclusions' && !hasExclusions(value)) && !(key === 'extraFilters' && !Object.keys(record(value)).length)
&& !sameValue(key, value, key === 'releaseId' ? releases[0] : merged[key as keyof typeof merged]))) return { reason: '比较期的冻结条件不同,暂不能沿用同一范围下钻。' };
}
if (present(scope.product) && !selection(scope.product)?.includes(row.product)) return { reason: '该产品不在本条依据的查询范围内。' };
if (present(scope.productSearch) && (typeof scope.productSearch !== 'string' || !row.product.toLocaleLowerCase().includes(scope.productSearch.toLocaleLowerCase()))) return { reason: '该产品与本轮检索条件不一致。' };
const query: ProductDrilldownBinding['query'] = { ...current, view: 'product', releaseId: String(releases[0]), product: row.product };
for (const key of dimensions.filter(key => key !== 'product')) {
if (!present(scope[key])) continue;
const value = wireSelection(scope[key]);
if (!value) return { reason: '本条依据的组织筛选不完整,暂不能下钻。' };
query[key] = value;
}
if (present(scope.includeUnassigned) && typeof scope.includeUnassigned !== 'boolean') return { reason: '本轮未分类筛选无效,暂不能下钻。' };
query.includeUnassigned = scope.includeUnassigned === true;
if (typeof scope.productSearch === 'string') query.productSearch = scope.productSearch;
if (present(scope.extraFilters)) {
if (typeof scope.extraFilters !== 'object' || Array.isArray(scope.extraFilters) || Object.values(record(scope.extraFilters)).some(value => !Array.isArray(value) || value.some(item => typeof item !== 'string'))) return { reason: '本轮附加筛选无效,暂不能下钻。' };
query.extraFilters = structuredClone(scope.extraFilters) as Record<string, string[]>;
}
return { binding: { turnId, product: row.product, stages: stage === 'black' || stage === 'bright' ? [stage] : ['black', 'bright'], query,
periods: [{ key: 'current', label: drilldownPeriodLabel(current), period: current }, ...(comparison ? [{ key: 'comparison' as const, label: drilldownPeriodLabel(comparison), period: comparison }] : [])], evidenceRefs: [...row.evidenceRefs] } };
}
export function productDrilldownQuery(binding: ProductDrilldownBinding, period: DrilldownPeriod): QueryParams & { releaseId: string } {
const { month: _month, quarter: _quarter, monthStart: _monthStart, monthEnd: _monthEnd, ...query } = binding.query;
return { ...structuredClone(query), ...period };
}
/** Only dates inside the original periods can appear in this drawer. The
* metrics API also supplies the whole year's trend, so slice it explicitly. */
export function productTrendVisual(binding: ProductDrilldownBinding, snapshots: MetricsResponse[]): AnalysisVisual[] {
const points = new Map<string, TrendMetricRow>();
snapshots.forEach((snapshot, index) => {
const period = binding.periods[index].period;
if (snapshot.release?.id !== binding.query.releaseId) throw new Error('查询返回的数据版本已变化,请重新打开本轮分析。');
if (period.month) {
const key = `${period.year}-${String(period.month).padStart(2, '0')}`;
points.set(key, { ...snapshot.summary, month: key, period: key });
return;
}
snapshot.trend.forEach(row => {
const raw = String(row.period ?? row.month);
const match = raw.match(/^(\d{4})-(\d{1,2})$/);
const year = match ? Number(match[1]) : row.year ?? period.year;
const month = match ? Number(match[2]) : Number(row.month);
if (year !== period.year || !Number.isInteger(month) || month < 1 || month > 12
|| period.quarter && Math.ceil(month / 3) !== period.quarter
|| period.monthStart !== undefined && (month < period.monthStart || month > Number(period.monthEnd))) return;
points.set(`${year}-${String(month).padStart(2, '0')}`, row);
});
});
const entries = [...points].sort(([a], [b]) => a.localeCompare(b));
if (!entries.length) return [];
const series = binding.stages.map(stage => ({ key: `${stage}_rate`, label: stage === 'black' ? '黑片合格率' : '亮片合格率', values: entries.map(([, row]) => row.coverage?.[stage === 'black' ? 'blackRows' : 'brightRows'] > 0 ? row[stage]?.rate ?? null : null) }));
if (binding.stages.length === 2) series.unshift({ key: 'composite_rate', label: '综合合格率', values: entries.map(([, row]) => row.coverage?.blackRows > 0 && row.coverage?.brightRows > 0 ? row.compositeRate ?? null : null) });
if (!series.some(item => item.values.some(value => value !== null))) return [];
return parseAnalysisVisuals([{ id: `drill-trend-${binding.turnId}`, type: 'line', title: '合格率趋势', subtitle: '', unit: 'ratio',
categories: entries.map(([key]) => ({ key, label: key })), series, evidenceRefs: [], requiredFields: [], scope: { product: binding.product }, period: binding.periods[0].period,
metric: 'composite_rate', coverage: { totalRows: entries.length, returnedRows: entries.length, truncated: false }, originTurnId: binding.turnId }]).visuals;
}