Compare commits
9
Commits
19bd9b0122
...
8b8f9b7728
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8b8f9b7728 | ||
|
|
5bcf1dee4f | ||
|
|
db5349dbde | ||
|
|
f8f289395e | ||
|
|
46b920f28a | ||
|
|
d0fee1544a | ||
|
|
5c37b39858 | ||
|
|
fb245f7d2e | ||
|
|
e6ceae12f0 |
@@ -79,3 +79,39 @@
|
||||
- 六个查询页默认月份、六主题切换、手动选择的慢加载保护、显式年月和返回时的筛选/滚动位置均已在本地验证。页面转场补充快速连续点击、取消等待及不可见控件保护验证,53 项相关检查通过,尚未发布。
|
||||
- 黑片与亮片页移除指标卡下方的来源统计与计算口径整行,回收空隙;计算说明仍可从指标卡或表头查看。趋势图关联已生效的月份/季度,默认月份及查询后同步选中加深,年度取消月份高亮。六主题选中效果已检查。
|
||||
- 2026-11-01 发布前生产构建与 57 项相关检查通过;此次仅更新前端,不修改计算逻辑或业务数据。
|
||||
|
||||
## 2026-11-01:取消内部缩放(本地)
|
||||
|
||||
- 保留侧栏、指标卡、趋势图、表格和不良构成的现有结构与顺序,移除整页 80% 缩放。字号采用原有真实尺寸,不再通过整体缩放压缩内容。
|
||||
- 图表移除反向缩放与字体补偿,趋势图和柏拉图使用正常坐标尺寸;页面高度直接对应浏览器视口。
|
||||
- 顶部栏、筛选栏及管理页签共享冻结起点,桌面 53px、手机 40px;管理页签每级追加 47px,保留表格左右冻结列。
|
||||
- 本地已检查 1920×1080、1536×864、1366×768、390×844 视口、六个查询页、六主题、图表点击和完整字段的冻结列。实际 Windows 硬件尚未验收,使用隔离演示数据预览,未发布。
|
||||
|
||||
## 2026-11-01:黑片与亮片更多筛选(本地)
|
||||
|
||||
- 黑片与亮片查询页将项目组、添加来源筛选字段及其条件行统一收入“更多筛选”,默认收起,主行保留期间、产业部、业务分组和产品。
|
||||
- 复用其他查询页的展开/收起样式、已选条件数量及清除入口;收起保留筛选,仍按原方式点击查询生效。
|
||||
- 本地实测两页展开收起、条件保留及实际查询参数、清除后查询;类型检查与阶段查询回归通过,未发布。
|
||||
|
||||
## 2026-11-01:侧栏内容字号(本地)
|
||||
|
||||
- 侧栏菜单从 13px 调到 14px,分组标题与账户主文字从 12px 调到 13px,菜单图标从 16px 调到 18px;侧栏宽度和主内容字号不变。
|
||||
- 已检查六种主题、长菜单名称和折叠状态,无文字换行或图标裁切,未发布。
|
||||
|
||||
## 2026-11-01:统一查询指标卡高度
|
||||
|
||||
- 六个查询页桌面端指标卡统一最小高度 96px,避免黑片与亮片页因没有辅助说明而矮一截;保留手机端原有 84px 最小高度。
|
||||
- 六个查询页和六种主题的卡片高度已实测一致;数据、字号、卡片排列与口径切换保持原有行为。
|
||||
|
||||
## 2026-11-01:筛选框统一与钻取趋势过渡(本地)
|
||||
|
||||
- 黑片、亮片取消独立的筛选框最小宽度与间距,年份、月份、季度复用其他查询页的尺寸规则;月份统一为两位显示,原查询方式保留。
|
||||
- 钻取时保留上次成功的趋势及目标线,新数据返回后使用同一图表实例进行 520ms 更新动画;减少动态效果时直接更新。
|
||||
- 旧范围图表在更新或失败时禁止交互;加载失败保留原图并允许重试。已取消的请求不能覆盖后续相同范围的新请求。
|
||||
- 本地复现原钻取存在 23 帧空白,修复后三级钻取与六主题均为零空白帧;快速返回重入、失败保留、实际筛选框尺寸及相关检查通过,未发布。
|
||||
|
||||
## 2026-11-01:查询操作强调与底部精简
|
||||
|
||||
- 各级返回按钮统一为带左箭头的“返回上一级”,沿用原有父级路径,使用主题色描边与浅底;Excel 导出使用实色主按钮,两者统一加粗。
|
||||
- 趋势数据表取消底部分页统计与月份汇总链接,直接展示已返回的期间;保留月份行的筛选操作。各查询页删除“点击期间筛选”类提示。
|
||||
- 本地实测三级返回、月份行筛选及六主题按钮效果;主汇总表分页和 Excel 导出行为保持原有方式。
|
||||
|
||||
@@ -171,7 +171,7 @@ export function M01Insights({ query, onUnauthorized }: { query: QueryParams; onU
|
||||
<div className="completion-panel-heading"><div><strong>目标与期间比较</strong><span>目标与比较结果均来自指标分析服务</span></div><Button icon={<ReloadOutlined />} loading={busy} onClick={() => { setCompare(null); setCompareError(''); void refreshAll(); }}>刷新比较</Button></div>
|
||||
<div className="completion-insight-grid">
|
||||
<div className="completion-insight-card">
|
||||
<div className="completion-card-heading"><strong>当前筛选综合率目标</strong><Tag color={configured ? 'green' : targetState === 'CONFLICT' ? 'red' : 'default'}>{targetState === 'CONFIGURED' ? '已配置' : targetState === 'UNCONFIGURED' ? '未配置' : targetState === 'CONFLICT' ? '配置冲突' : targetState}</Tag></div>
|
||||
<div className="completion-card-heading"><strong>当前筛选综合合格率目标</strong><Tag color={configured ? 'green' : targetState === 'CONFLICT' ? 'red' : 'default'}>{targetState === 'CONFIGURED' ? '已配置' : targetState === 'UNCONFIGURED' ? '未配置' : targetState === 'CONFLICT' ? '配置冲突' : targetState}</Tag></div>
|
||||
{targetError ? <Alert showIcon type="error" message="目标读取失败" description={targetError} /> : configured
|
||||
? <><div className="completion-target-value">{pct(configuredTarget)} <small>{text(targetValue.unit, '比例')}</small></div><p className="completion-note">当前目标已启用 · 匹配配置 {text(targetBody.matchingCount, '—')}</p></>
|
||||
: <><div className="completion-empty-value">当前筛选没有唯一的已启用目标</div>{targetState === 'CONFLICT' && <p className="completion-note">存在 {list(targetBody.alternatives).length} 项候选配置;请到“指标与规则”检查配置冲突。</p>}</>}
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import * as echarts from 'echarts/core';
|
||||
import { BarChart } from 'echarts/charts';
|
||||
import { GridComponent, TooltipComponent } from 'echarts/components';
|
||||
import { SVGRenderer } from 'echarts/renderers';
|
||||
import type { DefectMetric, Stage } from './types';
|
||||
import { defectWeightRate } from './trendMetrics';
|
||||
import './defect-composition.css';
|
||||
|
||||
echarts.use([BarChart, GridComponent, TooltipComponent, SVGRenderer]);
|
||||
const weightText = (value: number | null | undefined) => typeof value === 'number' && Number.isFinite(value) ? value.toLocaleString('en-US', { minimumFractionDigits: 1, maximumFractionDigits: 1 }) : '—';
|
||||
const rateText = (value: number | null | undefined) => typeof value === 'number' && Number.isFinite(value) ? `${(value * 100).toFixed(2)}%` : '—';
|
||||
const escape = (value: string) => value.replace(/[&<>"']/g, char => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[char]!));
|
||||
|
||||
function categoryColors(color: string, surface: string, count: number): string[] {
|
||||
return Array.from({ length: count }, (_, index) => {
|
||||
const mix = index === 0 ? 0 : Math.min(.8, .3 + (index - 1) * .25);
|
||||
return `#${[1, 3, 5].map(offset => Math.round(parseInt(color.slice(offset, offset + 2), 16) * (1 - mix) + parseInt(surface.slice(offset, offset + 2), 16) * mix).toString(16).padStart(2, '0')).join('')}`;
|
||||
});
|
||||
}
|
||||
|
||||
export default function DefectComposition({ items, stage, totalWeight, onDetail }: {
|
||||
items: DefectMetric[];
|
||||
stage: Stage;
|
||||
totalWeight?: number | null;
|
||||
onDetail: () => void;
|
||||
}) {
|
||||
const container = useRef<HTMLDivElement>(null);
|
||||
const latest = useRef({ items, stage, totalWeight, onDetail });
|
||||
latest.current = { items, stage, totalWeight, onDetail };
|
||||
const redraw = useRef<() => void>(() => undefined);
|
||||
const [colors, setColors] = useState<string[]>([]);
|
||||
const hasShares = items.some(item => typeof item.rate === 'number' && Number.isFinite(item.rate) && item.rate > 0 && item.rate <= 1);
|
||||
|
||||
useEffect(() => {
|
||||
const node = container.current;
|
||||
if (!node) return;
|
||||
let chart: ReturnType<typeof echarts.init> | undefined;
|
||||
redraw.current = () => {
|
||||
if (!node.clientWidth) return;
|
||||
const current = latest.current;
|
||||
const css = getComputedStyle(node);
|
||||
const ink = css.getPropertyValue('--ink').trim() || '#222C3C';
|
||||
const muted = css.getPropertyValue('--muted-ink').trim() || '#637187';
|
||||
const line = css.getPropertyValue('--line').trim() || '#DCE2EC';
|
||||
const surface = css.getPropertyValue('--surface').trim() || '#FFFFFF';
|
||||
const color = css.getPropertyValue(current.stage === 'black' ? '--defect-black' : '--defect-bright').trim() || (current.stage === 'black' ? '#718797' : '#607AE1');
|
||||
const palette = categoryColors(color, surface, current.items.length);
|
||||
if (current.stage === 'black' && document.documentElement.dataset.workspaceTheme !== 'dark') {
|
||||
// Match the selected blue-gray swatches; keep the existing dark-theme contrast treatment.
|
||||
for (const index of [1, 2]) {
|
||||
const tone = css.getPropertyValue(`--defect-black-${index + 1}`).trim();
|
||||
if (tone && index < palette.length) palette[index] = tone;
|
||||
}
|
||||
}
|
||||
setColors(old => old.join() === palette.join() ? old : palette);
|
||||
const fontFamily = css.getPropertyValue('--font-ui').trim() || css.fontFamily;
|
||||
const numericFamily = css.getPropertyValue('--font-numeric').trim() || 'Arial';
|
||||
const stageName = current.stage === 'black' ? '黑片' : '亮片';
|
||||
if (!chart) {
|
||||
chart = echarts.init(node, undefined, { renderer: 'svg' });
|
||||
chart.on('click', () => latest.current.onDetail());
|
||||
}
|
||||
const option: echarts.EChartsCoreOption = {
|
||||
animation: !window.matchMedia('(prefers-reduced-motion: reduce)').matches,
|
||||
animationDuration: 420,
|
||||
animationDurationUpdate: 520,
|
||||
textStyle: { color: ink, fontFamily, fontSize: 12 },
|
||||
grid: { top: 8, left: 20, right: 20, bottom: 28 },
|
||||
tooltip: {
|
||||
trigger: 'item', backgroundColor: surface, borderColor: line,
|
||||
textStyle: { color: ink, fontFamily, fontSize: 12 },
|
||||
formatter: (raw: unknown) => {
|
||||
const item = current.items[(raw as { seriesIndex: number }).seriesIndex];
|
||||
return item ? `${stageName} · ${escape(item.name)}<br/>重量:${weightText(item.weight)} kg<br/>占比:${rateText(item.rate)}<br/>废率:${rateText(defectWeightRate(item.weight, current.totalWeight))}` : '';
|
||||
},
|
||||
},
|
||||
xAxis: { type: 'value', min: 0, max: 100, interval: 25, axisLine: { show: true, lineStyle: { color: line } }, axisTick: { show: false }, splitLine: { show: false }, axisLabel: { fontFamily: numericFamily, fontSize: 11, color: muted, formatter: '{value}%' } },
|
||||
yAxis: { type: 'category', data: [''], show: false },
|
||||
series: current.items.map((item, index) => ({
|
||||
id: `composition-${current.stage}-${item.name}`, name: item.name, type: 'bar', stack: 'composition', barWidth: 28,
|
||||
data: [typeof item.rate === 'number' && Number.isFinite(item.rate) && item.rate >= 0 && item.rate <= 1 ? item.rate * 100 : null],
|
||||
itemStyle: { color: palette[index] },
|
||||
label: { show: typeof item.rate === 'number' && item.rate >= .15, position: 'inside', formatter: rateText(item.rate), color: index === 0 && document.documentElement.dataset.workspaceTheme !== 'dark' ? '#FFFFFF' : ink, fontFamily: numericFamily, fontSize: 13, fontWeight: 600 },
|
||||
emphasis: { itemStyle: { opacity: .85 } },
|
||||
})),
|
||||
};
|
||||
chart.setOption(option, { replaceMerge: ['series'] });
|
||||
};
|
||||
redraw.current();
|
||||
const resize = new ResizeObserver(() => {
|
||||
const { clientWidth: width, clientHeight: height } = node;
|
||||
if (width <= 0 || height <= 0) return;
|
||||
if (chart) chart.resize({ width, height, animation: { duration: 0 } }); else redraw.current();
|
||||
});
|
||||
resize.observe(node);
|
||||
const theme = new MutationObserver(() => redraw.current());
|
||||
theme.observe(document.documentElement, { attributes: true, attributeFilter: ['data-workspace-theme'] });
|
||||
return () => { resize.disconnect(); theme.disconnect(); chart?.dispose(); redraw.current = () => undefined; };
|
||||
}, []);
|
||||
|
||||
useEffect(() => { redraw.current(); }, [items, stage, totalWeight]);
|
||||
|
||||
return <div className="defect-composition">
|
||||
<div className="defect-composition-unit">占比 / %</div>
|
||||
<div className="defect-composition-plot" ref={container} role="img" aria-label={`${stage === 'black' ? '黑片' : '亮片'}分类报废占比,详细数值见下方表格`} style={{ visibility: hasShares ? undefined : 'hidden' }} />
|
||||
{!hasShares && <div className="defect-composition-empty">暂无可绘制的构成占比</div>}
|
||||
<table className="defect-composition-table"><thead><tr><th scope="col">不良分类</th><th scope="col">重量 / kg</th><th scope="col">占比</th><th scope="col">废率</th></tr></thead><tbody>
|
||||
{items.map((item, index) => <tr key={item.name} onClick={() => { if (window.getSelection()?.isCollapsed !== false) onDetail(); }}>
|
||||
<td><button type="button" className="defect-composition-category" aria-label={`查看${stage === 'black' ? '黑片' : '亮片'}${item.name}来源明细`}><i aria-hidden="true" style={{ backgroundColor: colors[index] }} />{item.name}</button></td>
|
||||
<td className="defect-composition-weight">{weightText(item.weight)}</td><td>{rateText(item.rate)}</td><td>{rateText(defectWeightRate(item.weight, totalWeight))}</td>
|
||||
</tr>)}
|
||||
</tbody></table>
|
||||
</div>;
|
||||
}
|
||||
@@ -17,7 +17,6 @@ import {
|
||||
CheckOutlined,
|
||||
DatabaseOutlined,
|
||||
DownOutlined,
|
||||
DeploymentUnitOutlined,
|
||||
KeyOutlined,
|
||||
LineChartOutlined,
|
||||
LoadingOutlined,
|
||||
@@ -40,7 +39,7 @@ import { CachedWorkspacePages, type WorkspaceNavigation } from './CachedWorkspac
|
||||
export type PageKey = 'overall' | 'department' | 'group' | 'product' | 'blackProduct' | 'brightProduct' | 'basis' | 'analysis' | 'sources' | 'imports' | 'rules' | 'mappings' | 'masterData' | 'tasks' | 'access';
|
||||
|
||||
const pageNames: Record<PageKey, string> = {
|
||||
overall: '总体汇总', department: '产业部汇总', group: '产业部-业务分组', product: '产品汇总', blackProduct: '黑片汇总', brightProduct: '亮片汇总',
|
||||
overall: '总体合格率', department: '产业部', group: '产业部-业务分组', product: '产品汇总', blackProduct: '黑片汇总', brightProduct: '亮片汇总',
|
||||
basis: '数据与计算依据', analysis: '智能分析', sources: '数据接入', imports: '导入与校验',
|
||||
rules: '计算规则', mappings: '对应关系', masterData: '基础数据', tasks: '任务与监控', access: '权限与审计',
|
||||
};
|
||||
@@ -65,9 +64,8 @@ const navGroups = [
|
||||
{
|
||||
label: '质量查询',
|
||||
items: [
|
||||
['overall', '总体汇总', AppstoreOutlined],
|
||||
['department', '产业部汇总', ApartmentOutlined],
|
||||
['group', '产业部-业务分组', DeploymentUnitOutlined],
|
||||
['overall', '总体合格率', AppstoreOutlined],
|
||||
['department', '产业部', ApartmentOutlined],
|
||||
['product', '产品汇总', DatabaseOutlined],
|
||||
['blackProduct', '黑片汇总', DatabaseOutlined],
|
||||
['brightProduct', '亮片汇总', DatabaseOutlined],
|
||||
@@ -195,11 +193,10 @@ export default function QualityWorkspace({ appearance, onAppearanceChange }: Qua
|
||||
return (
|
||||
<div className={`app-shell${sidebarCollapsed ? ' sidebar-collapsed' : ''}`}>
|
||||
<aside className="sidebar" id="workspace-sidebar">
|
||||
<button className="brand" onClick={() => navigate('overall')} aria-label="回到总体汇总">
|
||||
<button className="brand" onClick={() => navigate('overall')} aria-label="回到总体合格率">
|
||||
<span className="brand-mark" aria-hidden="true"><i /><i /><i /></span>
|
||||
<span className="brand-copy">质量数据分析平台</span>
|
||||
</button>
|
||||
<div className="workspace-caption">分析工作台</div>
|
||||
<nav className="side-navigation" aria-label="主导航">
|
||||
{navGroups.map(group => (
|
||||
<div className="nav-group" key={group.label}>
|
||||
|
||||
+85
-109
@@ -25,7 +25,7 @@ import {
|
||||
Tooltip,
|
||||
} from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import { DownloadOutlined, InfoCircleOutlined, ReloadOutlined, SearchOutlined } from '@ant-design/icons';
|
||||
import { ArrowLeftOutlined, DownloadOutlined, InfoCircleOutlined, ReloadOutlined, SearchOutlined } from '@ant-design/icons';
|
||||
import { ApiError, api, decodeQueryValueList, encodeQueryValueList } from './api';
|
||||
import type {
|
||||
DefectMetric,
|
||||
@@ -47,6 +47,9 @@ import { readableSelectPopup } from './readableSelectPopup';
|
||||
import { isInternalDataField, readableMetricFormula } from './publicDataDisplay';
|
||||
import { defaultQueryMonth, previousCompleteMonth, previousCompleteQuarter } from './periodDefaults';
|
||||
import { defectWeightRate } from './trendMetrics';
|
||||
import DefectComposition from './DefectComposition';
|
||||
import { QueryTrendPanel, QueryTablePanel } from './QueryPanels';
|
||||
import { selectTrendPeriod as nextTrendPeriod } from './trendPeriodSelection';
|
||||
import './query-motion.css';
|
||||
import { ExtraQueryFilters } from './ExtraQueryFilters';
|
||||
import { freezeSourceRecordsQuery } from './sourceRecordsContext';
|
||||
@@ -55,11 +58,10 @@ import { downloadMetricWorkbook } from './metricWorkbook';
|
||||
echarts.use([BarChart, LineChart, GraphicComponent, GridComponent, LegendComponent, MarkLineComponent, TooltipComponent, SVGRenderer]);
|
||||
|
||||
const MONTHS = Array.from({ length: 12 }, (_, index) => `${String(index + 1).padStart(2, '0')}月`);
|
||||
// 图表为保持坐标交互准确使用局部 zoom,字体需抵消该缩放以匹配页面正文。
|
||||
// 图表直接沿用页面字号,不再补偿内部缩放。
|
||||
function queryChartTypography(node: HTMLElement) {
|
||||
const css = getComputedStyle(node);
|
||||
const zoom = Number.parseFloat(css.zoom) || 1;
|
||||
const size = (token: string, fallback: number) => Math.round((Number.parseFloat(css.getPropertyValue(token)) || fallback) / zoom * 10) / 10;
|
||||
const size = (token: string, fallback: number) => Math.round((Number.parseFloat(css.getPropertyValue(token)) || fallback) * 10) / 10;
|
||||
return {
|
||||
fontFamily: css.getPropertyValue('--font-ui').trim() || css.fontFamily,
|
||||
numericFamily: css.getPropertyValue('--font-numeric').trim() || css.fontFamily,
|
||||
@@ -300,10 +302,10 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
const [options, setOptions] = useState<OptionsResponse | null>(null);
|
||||
const [optionsError, setOptionsError] = useState('');
|
||||
const [optionsLoading, setOptionsLoading] = useState(true);
|
||||
const automaticPeriod = useRef(!initialQuery.year && !initialQuery.month && !initialQuery.quarter);
|
||||
const automaticPeriod = useRef(page !== 'overall' && !initialQuery.year && !initialQuery.month && !initialQuery.quarter);
|
||||
const defaultMonth = previousCompleteMonth();
|
||||
const defaultQuarter = previousCompleteQuarter();
|
||||
const [period, setPeriod] = useState<PeriodKind>(initialQuery.month ? 'month' : initialQuery.quarter ? 'quarter' : initialQuery.year ? 'year' : 'month');
|
||||
const [period, setPeriod] = useState<PeriodKind>(initialQuery.month ? 'month' : initialQuery.quarter ? 'quarter' : initialQuery.year || page === 'overall' ? 'year' : 'month');
|
||||
const [year, setYear] = useState(initialQuery.year || (period === 'month' ? defaultMonth.year : period === 'quarter' ? defaultQuarter.year : new Date().getFullYear()));
|
||||
const [month, setMonth] = useState(initialQuery.month || defaultMonth.month);
|
||||
const [quarter, setQuarter] = useState(initialQuery.quarter || defaultQuarter.quarter);
|
||||
@@ -322,6 +324,7 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
const [dataKey, setDataKey] = useState('');
|
||||
const [trendData, setTrendData] = useState<TrendMetricRow[]>([]);
|
||||
const [trendDataKey, setTrendDataKey] = useState('');
|
||||
const [trendFailure, setTrendFailure] = useState<{ key: string; message: string } | null>(null);
|
||||
const [trendTarget, setTrendTarget] = useState<number | null>(null);
|
||||
const [trendTargetKey, setTrendTargetKey] = useState('');
|
||||
const [trendObject, setTrendObject] = useState('');
|
||||
@@ -492,6 +495,7 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
|
||||
useEffect(() => {
|
||||
if (optionsLoading) return;
|
||||
setTrendFailure(null);
|
||||
if (useSummaryTrend) {
|
||||
setTrendLoading(false);
|
||||
return;
|
||||
@@ -499,15 +503,15 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
const controller = new AbortController();
|
||||
setTrendLoading(true);
|
||||
api.metrics(trendParams, controller.signal).then(result => {
|
||||
if (trendKeyRef.current !== trendKey) return;
|
||||
if (controller.signal.aborted || trendKeyRef.current !== trendKey) return;
|
||||
setTrendData(Array.isArray(result.trend) ? result.trend : []);
|
||||
setTrendDataKey(trendKey);
|
||||
})
|
||||
.catch(errorValue => {
|
||||
if (!controller.signal.aborted && !onUnauthorized(errorValue)) message.error(`趋势加载失败:${chooseError(errorValue)}`);
|
||||
if (!controller.signal.aborted && !onUnauthorized(errorValue)) setTrendFailure({ key: trendKey, message: chooseError(errorValue) });
|
||||
}).finally(() => { if (!controller.signal.aborted) setTrendLoading(false); });
|
||||
return () => controller.abort();
|
||||
}, [trendKey, useSummaryTrend, queryRevision, onUnauthorized, message, optionsLoading]);
|
||||
}, [trendKey, useSummaryTrend, queryRevision, onUnauthorized, optionsLoading]);
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
@@ -532,6 +536,12 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
|
||||
const currentTrendTarget = trendTargetKey === trendKey ? trendTarget : null;
|
||||
const visibleTrendData = useMemo(() => fullYearTrend(trendDataKey === trendKey ? trendData : [], year, trendGranularity), [trendData, trendDataKey, trendKey, year, trendGranularity]);
|
||||
const currentTrendError = trendFailure?.key === trendKey ? trendFailure.message : '';
|
||||
const trendRefreshing = trendLoading || (useSummaryTrend && queryBusy) || (trendDataKey !== trendKey && !(useSummaryTrend ? currentMetricsError : currentTrendError));
|
||||
// 只在当前查询返回后替换画面;钻取等待期间保留上一次趋势和目标线。
|
||||
const retainedTrend = useRetainedResult(trendDataKey === trendKey ? { rows: visibleTrendData, target: currentTrendTarget } : null);
|
||||
const renderedTrendData = retainedTrend?.rows || visibleTrendData;
|
||||
const renderedTrendTarget = retainedTrend ? retainedTrend.target : currentTrendTarget;
|
||||
const drilledTrendData = useMemo(
|
||||
() => trendDataKey === trendKey ? visibleTrendData : fullYearTrend([], year, 'month'),
|
||||
[trendDataKey, trendKey, visibleTrendData, year],
|
||||
@@ -592,35 +602,9 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
}, []);
|
||||
const selectTrendPeriod = useCallback((value: number | string) => {
|
||||
automaticPeriod.current = false;
|
||||
const raw = String(value);
|
||||
const quarterMatch = raw.match(/^(\d{4})-Q([1-4])$/);
|
||||
const yearMonth = raw.match(/^(\d{4})-(\d{1,2})$/);
|
||||
const yearMatch = raw.match(/^(\d{4})$/);
|
||||
if (quarterMatch) {
|
||||
if (period === 'quarter' && year === Number(quarterMatch[1]) && quarter === Number(quarterMatch[2])) {
|
||||
captureTrendAnchor(); setPeriod('year'); return;
|
||||
}
|
||||
if (period !== 'quarter' || year !== Number(quarterMatch[1]) || quarter !== Number(quarterMatch[2])) captureTrendAnchor();
|
||||
setYear(Number(quarterMatch[1])); setQuarter(Number(quarterMatch[2])); setPeriod('quarter');
|
||||
} else if (yearMonth) {
|
||||
if (period === 'month' && year === Number(yearMonth[1]) && month === Number(yearMonth[2])) {
|
||||
captureTrendAnchor(); setPeriod('year'); return;
|
||||
}
|
||||
if (period !== 'month' || year !== Number(yearMonth[1]) || month !== Number(yearMonth[2])) captureTrendAnchor();
|
||||
setYear(Number(yearMonth[1])); setMonth(Number(yearMonth[2])); setPeriod('month');
|
||||
} else if (yearMatch) {
|
||||
if (period !== 'year' || year !== Number(yearMatch[1])) captureTrendAnchor();
|
||||
setYear(Number(yearMatch[1])); setPeriod('year');
|
||||
} else {
|
||||
const selected = monthNumber(value);
|
||||
if (selected) {
|
||||
if (period === 'month' && month === selected) {
|
||||
captureTrendAnchor(); setPeriod('year'); return;
|
||||
}
|
||||
if (period !== 'month' || month !== selected) captureTrendAnchor();
|
||||
setPeriod('month'); setMonth(selected);
|
||||
}
|
||||
}
|
||||
const next = nextTrendPeriod(value, { period, year, month, quarter });
|
||||
if (next.period !== period || next.year !== year || next.month !== month || next.quarter !== quarter) captureTrendAnchor();
|
||||
setYear(next.year); setMonth(next.month); setQuarter(next.quarter); setPeriod(next.period);
|
||||
}, [period, year, month, quarter, captureTrendAnchor]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
@@ -763,7 +747,7 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
<ExtraQueryFilters key={queryRevision} projectGroup={projectGroup} projectGroups={options?.projectGroupStatus === 'READY' ? options.projectGroups : undefined} onProjectGroup={setProjectGroup} value={extraFilters} onChange={setExtraFilters} onUnauthorized={onUnauthorized} />
|
||||
<div className="query-toolbar-tail">
|
||||
<span className={`query-status ${queryBusy || summaryBusy ? 'busy' : currentMetricsError || summaryMetricsError ? 'failed' : ''}`}><i />{queryBusy || summaryBusy ? '正在查询' : currentMetricsError || summaryMetricsError ? '查询失败' : '查询完成'}</span>
|
||||
<Button type="default" onClick={() => { automaticPeriod.current = false; const previous = defaultQueryMonth(options); const previousQuarter = previousCompleteQuarter(); setDepartment([]); setGroup([]); setProduct([]); setProjectGroup([]); setExtraFilters({}); setSearch(''); setAppliedSearch(''); setTrendObject(''); setYear(previous.year); setMonth(previous.month); setQuarter(previousQuarter.quarter); setPeriod('month'); setTrendGranularity('month'); }}>重置</Button>
|
||||
<Button type="default" onClick={() => { automaticPeriod.current = false; const previous = defaultQueryMonth(options); const previousQuarter = previousCompleteQuarter(); setViewOverride(); setDrilledProduct(''); setDepartment([]); setGroup([]); setProduct([]); setProjectGroup([]); setExtraFilters({}); setSearch(''); setAppliedSearch(''); setTrendObject(''); setYear(page === 'overall' ? new Date().getFullYear() : previous.year); setMonth(previous.month); setQuarter(previousQuarter.quarter); setPeriod(page === 'overall' ? 'year' : 'month'); setTrendGranularity('month'); }}>重置</Button>
|
||||
</div>
|
||||
{organizationSummary.length > 0 && <div className="organization-breadcrumb" aria-label="当前组织路径">
|
||||
<span>组织路径</span><Button type="link" onClick={() => { setDepartment([]); setGroup([]); setProduct([]); }}>全部组织</Button>
|
||||
@@ -787,48 +771,34 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
|
||||
<>
|
||||
<div className="analysis-stack">
|
||||
<section className="panel section-panel trend-panel" ref={trendSection} id={active ? 'monthly-trend' : undefined}>
|
||||
<div className="section-heading-row trend-heading-row">
|
||||
<SectionHeading title={`${trendGranularity === 'month' ? '月度' : trendGranularity === 'quarter' ? '季度' : '年度'}变化趋势`} />
|
||||
<Segmented value={trendMode} options={[{ label: '合格率与产量', value: 'production' }, { label: '不良率', value: 'defects' }, { label: `${trendGranularity === 'quarter' ? '季度' : trendGranularity === 'year' ? '年度' : '月度'}数据`, value: 'data' }]} onChange={value => setTrendMode(value as typeof trendMode)} aria-label="趋势视图" />
|
||||
</div>
|
||||
<div className="trend-controls">
|
||||
{trendMode==='data'&&<Segmented value={defectDisplay} options={[{label:'不良重量',value:'weight'},{label:'不良率',value:'rate'}]} onChange={value=>setDefectDisplay(value as typeof defectDisplay)} aria-label="趋势不良显示方式"/>}
|
||||
<label className="query-field trend-granularity"><span>趋势粒度</span><Select {...readableSelectPopup} value={trendGranularity} options={[{ label: '按月', value: 'month' }, { label: '按季度', value: 'quarter' }, { label: '按年度', value: 'year' }]} onChange={value => setTrendGranularity(value)} aria-label="趋势粒度" /></label>
|
||||
<label className="query-field trend-object"><span>趋势对象</span><Select {...readableSelectPopup} allowClear placeholder={`当前${scopeName}筛选`} value={trendObject || undefined} options={trendOptions} onChange={setSynchronizedTrendObject} aria-label="趋势对象" />
|
||||
</label>
|
||||
{trendMode !== 'data' && <Segmented value={trendStage} options={[{ label: '亮片', value: 'bright' }, { label: '黑片', value: 'black' }]} onChange={value => setTrendStage(value as Stage)} aria-label="趋势阶段" />}
|
||||
</div>
|
||||
<div className="trend-chart-shell" aria-busy={trendLoading}>
|
||||
<QueryTrendPanel panelRef={trendSection} id={active ? 'monthly-trend' : undefined}
|
||||
mode={trendMode} onMode={setTrendMode} granularity={trendGranularity} onGranularity={setTrendGranularity}
|
||||
defectDisplay={defectDisplay} onDefectDisplay={setDefectDisplay} object={trendObject} onObject={setSynchronizedTrendObject}
|
||||
objects={trendOptions} scopeName={scopeName}
|
||||
stageSwitch={<Segmented value={trendStage} options={[{ label: '亮片', value: 'bright' }, { label: '黑片', value: 'black' }]} onChange={value => setTrendStage(value as Stage)} aria-label="趋势阶段" />}>
|
||||
{currentTrendError && <Alert type="warning" showIcon message="趋势读取失败" description={currentTrendError} action={<Button onClick={() => setQueryRevision(value => value + 1)}>重试</Button>} />}
|
||||
<div className="trend-chart-shell" aria-busy={trendRefreshing} inert={trendRefreshing || trendDataKey !== trendKey}>
|
||||
{trendMode === 'data'
|
||||
? <TrendTable rows={visibleTrendData} defectDisplay={defectDisplay} rateBasis={rateBasis} onMonth={selectTrendPeriod} />
|
||||
: <TrendChart rows={visibleTrendData} mode={trendMode} stage={trendStage} rateBasis={rateBasis} targetRate={currentTrendTarget} selectedPeriod={selectedTrendPeriod} onMonth={selectTrendPeriod} />}
|
||||
{(trendLoading || (useSummaryTrend && queryBusy)) && <span className="trend-refresh-indicator"><Spin size="small" />正在更新趋势</span>}
|
||||
? <TrendTable rows={renderedTrendData} defectDisplay={defectDisplay} rateBasis={rateBasis} onMonth={selectTrendPeriod} />
|
||||
: <TrendChart rows={renderedTrendData} mode={trendMode} stage={trendStage} rateBasis={rateBasis} targetRate={renderedTrendTarget} selectedPeriod={selectedTrendPeriod} onMonth={selectTrendPeriod} />}
|
||||
{trendRefreshing && <span className="trend-refresh-indicator"><Spin size="small" />正在更新趋势</span>}
|
||||
</div>
|
||||
<div className="chart-footnote"><span style={{ marginLeft: 'auto' }}>点击期间筛选,再次点击可取消</span></div>
|
||||
</section>
|
||||
</QueryTrendPanel>
|
||||
|
||||
|
||||
<section className="panel section-panel table-panel">
|
||||
<div className="section-heading-row">
|
||||
<SectionHeading title={tableProduct ? '产品月度质量数据' : page === 'overall' ? `${tablePeriod === 'year' ? '年度月度' : tablePeriod === 'quarter' ? '季度' : '月度'}汇总` : `${scopeName}质量汇总`} subtitle={tableProduct ? `${retainedTable?.year || year} 年 · ${tableProduct} · 重量 / kg 合格率 / %` : '重量 / kg 合格率 / %'} />
|
||||
<div className="table-tools">
|
||||
{(queryBusy || !tableReady) && <span className="defect-refresh-indicator"><Spin size="small" />正在更新</span>}
|
||||
<Input allowClear={!drilledProduct} disabled={Boolean(drilledProduct)} maxLength={view === 'product' ? 256 : undefined} prefix={<SearchOutlined />} placeholder={view === 'product' ? '输入关键词或完整产品名称' : `搜索${view === 'group' ? '业务分组' : '汇总对象'}`} value={drilledProduct || search} onChange={event => setSearch(event.target.value)} aria-label={view === 'product' ? '搜索产品名称并同步筛选指标和趋势' : '搜索汇总对象'} />
|
||||
<Button type="primary" disabled={Boolean(drilledProduct)} onClick={() => applySearch()} aria-label="开始搜索">搜索</Button>
|
||||
<Segmented value={fullFields ? 'full' : 'key'} options={[{ label: '关键指标', value: 'key' }, { label: '完整字段', value: 'full' }]} onChange={value => setFullFields(value === 'full')} aria-label="字段显示" />
|
||||
<Segmented value={defectDisplay} options={[{label:'不良重量',value:'weight'},{label:'不良率',value:'rate'}]} onChange={value=>setDefectDisplay(value as typeof defectDisplay)} aria-label="不良显示方式" />
|
||||
{!drilledProduct && (view === 'group' || view === 'product' && (group.length > 0 || department.length > 0)) && <Button onClick={() => { setSearch(''); setAppliedSearch(''); setTrendObject(''); if (view === 'product') { setProduct([]); setGroup([]); setViewOverride('group'); } else { setGroup([]); setDepartment([]); setViewOverride('department'); } }}>{view === 'product' ? '返回业务分组' : '返回产业部'}</Button>}
|
||||
{drilledProduct && <Button onClick={() => { setDrilledProduct(''); setTrendObject(''); setTrendMode('production'); }}>返回产品汇总</Button>}
|
||||
<Button icon={<DownloadOutlined />} aria-label="Excel导出" loading={summaryExporting} disabled={queryBusy || summaryBusy || !summaryMetricsData || Boolean(drilledProduct && trendLoading) || !(drilledProduct ? drilledTrendData : visibleRows).length} onClick={async () => {
|
||||
<QueryTablePanel
|
||||
heading={<SectionHeading title={tableProduct ? '产品月度质量数据' : page === 'overall' ? `${tablePeriod === 'year' ? '年度月度' : tablePeriod === 'quarter' ? '季度' : '月度'}汇总` : `${scopeName}质量汇总`} subtitle={tableProduct ? `${retainedTable?.year || year} 年 · ${tableProduct} · 重量 / kg 合格率 / %` : '重量 / kg 合格率 / %'} />} busy={queryBusy || !tableReady}
|
||||
search={drilledProduct || search} onSearchChange={setSearch} onSearch={() => applySearch()} productView={view === 'product'} searchPlaceholder={view === 'group' ? '搜索业务分组' : undefined} searchDisabled={Boolean(drilledProduct)}
|
||||
fullFields={fullFields} onFullFields={setFullFields} defectDisplay={defectDisplay} onDefectDisplay={setDefectDisplay}
|
||||
returnControls={<>{!drilledProduct && (view !== baseView || view === 'group' || view === 'product' && (group.length > 0 || department.length > 0)) && <Button className="query-return-button" icon={<ArrowLeftOutlined />} onClick={() => { setSearch(''); setAppliedSearch(''); setTrendObject(''); if (view === 'product') { setProduct([]); setGroup([]); setViewOverride('group'); } else if (view === 'group') { setGroup([]); setDepartment([]); setViewOverride('department'); } else { setViewOverride(); } }}>返回上一级</Button>}
|
||||
{drilledProduct && <Button className="query-return-button" icon={<ArrowLeftOutlined />} onClick={() => { setDrilledProduct(''); setTrendObject(''); setTrendMode('production'); }}>返回上一级</Button>}</>}
|
||||
exporting={summaryExporting} exportDisabled={queryBusy || summaryBusy || !summaryMetricsData || Boolean(drilledProduct && trendLoading) || !(drilledProduct ? drilledTrendData : visibleRows).length}
|
||||
onExport={async () => {
|
||||
setSummaryExporting(true);
|
||||
try { await summaryExport.current?.exportExcel(); }
|
||||
catch (error) { message.error(`导出失败:${chooseError(error)}`); }
|
||||
finally { setSummaryExporting(false); }
|
||||
}}>Excel导出</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mobile-scroll-hint">横向滑动查看完整指标</div>
|
||||
}}>
|
||||
<SmoothTableFrame busy={queryBusy || !tableReady} blocked={queryBusy || summaryBusy || !tableReady}>
|
||||
<MetricTable
|
||||
ref={summaryExport}
|
||||
@@ -862,7 +832,7 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
}}
|
||||
/>
|
||||
</SmoothTableFrame>
|
||||
</section>
|
||||
</QueryTablePanel>
|
||||
|
||||
<section className="panel section-panel defects-panel" ref={defectsSection} aria-busy={defectsRefreshing} style={{ minHeight: queryBusy && trendAnchorTop.current != null ? defectsHeight.current : undefined }}>
|
||||
<div className="section-heading-row">
|
||||
@@ -930,23 +900,15 @@ export function MetricCard({ primary, label, value, note, stage, onClick }: { pr
|
||||
</button>;
|
||||
}
|
||||
|
||||
export function DefectBreakdown({ items, stage, totalWeight, maximum, onDetail }: { items: DefectMetric[]; stage: Stage; totalWeight?: number | null; maximum: number; onDetail: () => void }) {
|
||||
return <div className="defect-list">
|
||||
<div className="defect-header"><span>不良分类</span><span aria-hidden="true" /><span>重量 / kg</span><span>占比</span><span>废率</span></div>
|
||||
{items.map(item => <button className="defect-row" key={item.name} onClick={onDetail}>
|
||||
<span className="defect-name">{item.name}</span>
|
||||
<span className="defect-track"><i className={stage} style={{ width: `${maximum > 0 ? Math.max(0, (item.weight || 0) / maximum * 100) : 0}%` }} /></span>
|
||||
<span className="defect-weight">{numberText(item.weight)}</span>
|
||||
<span className="defect-rate">{rateText(item.rate)}</span>
|
||||
<span className="defect-rate">{rateText(defectWeightRate(item.weight, totalWeight))}</span>
|
||||
</button>)}
|
||||
</div>;
|
||||
export function DefectBreakdown({ items, stage, totalWeight, onDetail }: { items: DefectMetric[]; stage: Stage; totalWeight?: number | null; maximum: number; onDetail: () => void }) {
|
||||
return <DefectComposition items={items} stage={stage} totalWeight={totalWeight} onDetail={onDetail} />;
|
||||
}
|
||||
|
||||
|
||||
export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUnauthorized, onlyStage, refreshKey = 0, pending = false }: {
|
||||
releaseId?: string; query: QueryParams; externalScrapWeight?: number | null; onUnauthorized: (error: unknown) => boolean; onlyStage?: Stage; refreshKey?: number; pending?: boolean;
|
||||
}) {
|
||||
const { active } = usePageCache();
|
||||
const container = useRef<HTMLDivElement>(null);
|
||||
const chart = useRef<ReturnType<typeof echarts.init> | null>(null);
|
||||
const [responses, setResponses] = useState<{ black: FineDefectTopResponse; bright: FineDefectTopResponse; externalScrapWeight?: number | null } | null>(null);
|
||||
@@ -998,13 +960,18 @@ export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUna
|
||||
|
||||
useEffect(() => {
|
||||
const node = container.current;
|
||||
if (!node) return;
|
||||
const instance = echarts.init(node, undefined, { renderer: 'svg' });
|
||||
if (!node || !active) return;
|
||||
const instance = echarts.init(node, undefined, { renderer: 'svg', width: node.clientWidth, height: node.clientHeight });
|
||||
chart.current = instance;
|
||||
const observer = new ResizeObserver(() => instance.resize());
|
||||
const observer = new ResizeObserver(() => {
|
||||
const { clientWidth: width, clientHeight: height } = node;
|
||||
if (width > 0 && height > 0 && (width !== instance.getWidth() || height !== instance.getHeight())) {
|
||||
instance.resize({ width, height, animation: { duration: 0 } });
|
||||
}
|
||||
});
|
||||
observer.observe(node);
|
||||
return () => { observer.disconnect(); instance.dispose(); if (chart.current === instance) chart.current = null; };
|
||||
}, []);
|
||||
}, [active]);
|
||||
|
||||
const items = useMemo(() => {
|
||||
if (!responses) return [];
|
||||
@@ -1032,8 +999,8 @@ export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUna
|
||||
const styles = getComputedStyle(container.current);
|
||||
const ink = styles.getPropertyValue('--ink').trim() || '#222222';
|
||||
const line = styles.getPropertyValue('--line').trim() || '#dfe5ef';
|
||||
const blue = styles.getPropertyValue('--blue').trim() || '#607ae1';
|
||||
const teal = styles.getPropertyValue('--teal').trim() || '#008f7d';
|
||||
const black = styles.getPropertyValue('--defect-black').trim() || '#718797';
|
||||
const bright = styles.getPropertyValue('--defect-bright').trim() || '#607AE1';
|
||||
const surface = styles.getPropertyValue('--surface').trim() || '#ffffff';
|
||||
let accumulated = 0;
|
||||
const cumulative = items.map(item => {
|
||||
@@ -1074,12 +1041,12 @@ export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUna
|
||||
{ type: 'value', name: '累计占比', min: 0, max: 100, nameTextStyle: { color: ink, fontSize }, axisLabel: { color: ink, fontFamily: numericFamily, fontSize, formatter: '{value}%' }, splitLine: { show: false } },
|
||||
],
|
||||
series: [
|
||||
{ id: 'pareto-weight', name: '报废重量', type: 'bar', z: 1, barMaxWidth: 36, data: items.map(item => ({ id: item.key, name: item.label, value: item.weight, itemStyle: { color: item.kind === 'category' ? '#9aa4b2' : item.key.startsWith('black:') ? blue : teal } })) },
|
||||
{ id: 'pareto-weight', name: '报废重量', type: 'bar', z: 1, barMaxWidth: 36, itemStyle: { color: onlyStage === 'black' ? black : bright }, data: items.map(item => ({ id: item.key, name: item.label, value: item.weight, itemStyle: { color: item.kind === 'category' ? '#9aa4b2' : item.key.startsWith('black:') ? black : bright } })) },
|
||||
{ id: 'pareto-cumulative', name: '累计占比', type: 'line', z: 10, yAxisIndex: 1, symbol: 'circle', symbolSize: 5, lineStyle: { width: 2, color: '#d58c35' }, itemStyle: { color: '#d58c35', borderColor: surface, borderWidth: 1 }, data: cumulative.map((value, index) => ({ id: items[index].key, name: items[index].label, value })) },
|
||||
],
|
||||
};
|
||||
instance.setOption(option, { replaceMerge: ['series'], lazyUpdate: false });
|
||||
}, [items, totalWeight, themeRevision]);
|
||||
}, [items, totalWeight, themeRevision, active]);
|
||||
|
||||
return <section className="defect-pareto-section" aria-busy={loading || pending} aria-label={onlyStage ? `${onlyStage === 'black' ? '黑片' : '亮片'}报废重量柏拉图` : '综合报废重量柏拉图'}>
|
||||
<div className="defect-pareto-heading"><strong>{onlyStage ? `${onlyStage === 'black' ? '黑片' : '亮片'}报废重量柏拉图` : '黑片与亮片综合报废重量柏拉图'}</strong>{loading && <span className="defect-refresh-indicator"><Spin size="small" />正在更新</span>}</div>
|
||||
@@ -1212,6 +1179,7 @@ function trendBarWidth(chartWidth: number, count: number): number {
|
||||
}
|
||||
|
||||
export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedPeriod, onMonth, onlyStage }: { rows: TrendMetricRow[]; mode: 'production' | 'defects'; stage: Stage; rateBasis: 'original' | 'withoutHeadquartersScrap'; targetRate: number | null; selectedPeriod?: string; onMonth: (value: number | string) => void; onlyStage?: Stage }) {
|
||||
const { active } = usePageCache();
|
||||
const container = useRef<HTMLDivElement>(null);
|
||||
const chart = useRef<ReturnType<typeof echarts.init> | null>(null);
|
||||
const onMonthRef = useRef(onMonth);
|
||||
@@ -1260,10 +1228,12 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!container.current || !hasRows) return;
|
||||
const instance = echarts.init(container.current, undefined, { renderer: 'svg' });
|
||||
if (!container.current || !hasRows || !active) return;
|
||||
const instance = echarts.init(container.current, undefined, { renderer: 'svg', width: container.current.clientWidth, height: container.current.clientHeight });
|
||||
chart.current = instance;
|
||||
graphicIds.current.clear();
|
||||
selectionReady.current = false;
|
||||
setBarMasks([]);
|
||||
instance.on('click', params => {
|
||||
if (params.componentType !== 'series' && params.componentType !== 'xAxis') return;
|
||||
const currentRows = rowsRef.current;
|
||||
@@ -1278,8 +1248,9 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
|
||||
const observer = new ResizeObserver(() => {
|
||||
if (!container.current) return;
|
||||
const { clientWidth, clientHeight } = container.current;
|
||||
if (clientWidth <= 0 || clientHeight <= 0) return;
|
||||
if (clientWidth !== instance.getWidth() || clientHeight !== instance.getHeight()) {
|
||||
instance.resize();
|
||||
instance.resize({ width: clientWidth, height: clientHeight, animation: { duration: 0 } });
|
||||
if (modeRef.current === 'production') {
|
||||
const barWidth = trendBarWidth(instance.getWidth(), rowsRef.current.length);
|
||||
instance.setOption({ series: [{ id: 'qualified-weight', barWidth }, { id: 'scrap-weight', barWidth }] });
|
||||
@@ -1289,7 +1260,7 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
|
||||
});
|
||||
observer.observe(container.current);
|
||||
return () => { observer.disconnect(); instance.dispose(); chart.current = null; };
|
||||
}, [hasRows, refreshBarMasks]);
|
||||
}, [hasRows, refreshBarMasks, active]);
|
||||
|
||||
useEffect(() => {
|
||||
const instance = chart.current;
|
||||
@@ -1301,10 +1272,13 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
|
||||
const bars = trendBarPalette(getWorkspaceTheme(document.documentElement.dataset.workspaceTheme).id);
|
||||
const barColor = bars.qualified;
|
||||
const teal = css.getPropertyValue('--teal').trim() || '#008f7d';
|
||||
const blackLine = css.getPropertyValue('--defect-black').trim() || '#718797';
|
||||
const brightLine = css.getPropertyValue('--defect-bright').trim() || blue;
|
||||
const line = css.getPropertyValue('--line').trim() || '#dfe5ef';
|
||||
const surface = css.getPropertyValue('--surface').trim() || '#ffffff';
|
||||
const labels = rows.map(row => row.periodLabel || String(row.month));
|
||||
const barData = (field: 'qualifiedWeight' | 'scrapWeight') => rows.map(row => ({
|
||||
id: String(row.period ?? row.month),
|
||||
value: hasStageRows(row, stage) ? stageValue(row, stage, field, rateBasis) : null,
|
||||
itemStyle: { color: field === 'qualifiedWeight'
|
||||
? (String(row.period ?? row.month) === selectedPeriod ? bars.selectedQualified : bars.qualified)
|
||||
@@ -1320,7 +1294,11 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
|
||||
})].join('<br/>');
|
||||
};
|
||||
const base: echarts.EChartsCoreOption = {
|
||||
animation: false,
|
||||
animation: !window.matchMedia('(prefers-reduced-motion: reduce)').matches,
|
||||
animationDuration: 520,
|
||||
animationEasing: 'cubicOut',
|
||||
animationDurationUpdate: 520,
|
||||
animationEasingUpdate: 'cubicOut',
|
||||
textStyle: { fontFamily, color: ink, fontSize },
|
||||
grid: { left: 65, right: mode === 'production' ? 67 : 32, top: 70, bottom: 38 },
|
||||
legend: { type: 'scroll', top: 0, left: 9, right: 9, itemWidth: 14, itemHeight: 7, itemGap: 20, textStyle: { color: ink, fontFamily, fontSize, fontWeight: 500 } },
|
||||
@@ -1335,11 +1313,12 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
|
||||
const maxRate = rates.length ? Math.max(100, Math.ceil(Math.max(...rates) + 1)) : 100;
|
||||
const stageName = stage === 'black' ? '黑片' : '亮片';
|
||||
const barWidth = trendBarWidth(instance.getWidth(), rows.length);
|
||||
const ratePoints = { ...pointStyle, symbol: 'emptyCircle', symbolSize: 6 };
|
||||
const targetLine = targetRate == null ? {} : { markLine: {
|
||||
silent: true,
|
||||
symbol: 'none',
|
||||
lineStyle: { color: '#c47a47', width: 1.5, type: 'dashed' as const },
|
||||
label: { show: true, formatter: `综合率目标 ${targetRate.toFixed(2)}%`, position: 'insideEndTop' as const, color: '#a55d30', fontSize },
|
||||
label: { show: true, formatter: `综合合格率目标 ${targetRate.toFixed(2)}%`, position: 'insideEndTop' as const, color: '#a55d30', fontSize },
|
||||
data: [{ yAxis: targetRate }],
|
||||
} };
|
||||
option = {
|
||||
@@ -1351,9 +1330,9 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
|
||||
series: [
|
||||
{ id: 'qualified-weight', name: `${stageName}合格重量`, type: 'bar', z: 1, stack: 'weight', yAxisIndex: 0, barWidth, itemStyle: { color: barColor }, emphasis: { itemStyle: { color: bars.hoverQualified } }, data: barData('qualifiedWeight') },
|
||||
{ id: 'scrap-weight', name: `${stageName}报废重量`, type: 'bar', z: 1, stack: 'weight', yAxisIndex: 0, barWidth, itemStyle: { color: bars.scrap }, emphasis: { itemStyle: { color: bars.hoverScrap } }, data: barData('scrapWeight') },
|
||||
{ id: 'composite-rate', name: '综合合格率', type: 'line', yAxisIndex: 1, ...pointStyle, ...targetLine, lineStyle: { width: 2.5, color: blue }, itemStyle: { color: blue, borderColor: surface, borderWidth: 1.5 }, data: rows.map(row => rateNumber(visibleCompositeRate(row, rateBasis))) },
|
||||
{ id: 'black-rate', name: '黑片合格率', type: 'line', yAxisIndex: 1, ...pointStyle, lineStyle: { width: 1.8, color: '#9278bf' }, itemStyle: { color: '#9278bf', borderColor: surface, borderWidth: 1 }, data: rows.map(row => rateNumber(visibleStageRate(row, 'black'))) },
|
||||
{ id: 'bright-rate', name: '亮片合格率', type: 'line', yAxisIndex: 1, ...pointStyle, lineStyle: { width: 1.8, color: teal }, itemStyle: { color: teal, borderColor: surface, borderWidth: 1 }, data: rows.map(row => rateNumber(visibleStageRate(row, 'bright', rateBasis))) },
|
||||
{ id: 'composite-rate', name: '综合合格率', type: 'line', yAxisIndex: 1, ...ratePoints, ...targetLine, symbolSize: 7, emphasis: { ...pointStyle.emphasis, scale: 1.15 }, lineStyle: { width: 3.2, color: teal, cap: 'round', join: 'round' }, itemStyle: { color: teal, borderColor: teal, borderWidth: 2 }, data: rows.map(row => rateNumber(visibleCompositeRate(row, rateBasis))) },
|
||||
{ id: 'black-rate', name: '黑片合格率', type: 'line', yAxisIndex: 1, ...ratePoints, lineStyle: { width: 2.6, color: blackLine, cap: 'round', join: 'round' }, itemStyle: { color: blackLine, borderColor: blackLine, borderWidth: 2 }, data: rows.map(row => rateNumber(visibleStageRate(row, 'black'))) },
|
||||
{ id: 'bright-rate', name: '亮片合格率', type: 'line', yAxisIndex: 1, ...ratePoints, lineStyle: { width: 2.6, color: brightLine, cap: 'round', join: 'round' }, itemStyle: { color: brightLine, borderColor: brightLine, borderWidth: 2 }, data: rows.map(row => rateNumber(visibleStageRate(row, 'bright', rateBasis))) },
|
||||
],
|
||||
};
|
||||
} else {
|
||||
@@ -1371,7 +1350,7 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
|
||||
}
|
||||
instance.setOption(option, { replaceMerge: ['series', 'yAxis'], lazyUpdate: false });
|
||||
refreshBarMasks();
|
||||
}, [rows, mode, stage, rateBasis, targetRate, themeRevision, refreshBarMasks, onlyStage, selectedPeriod]);
|
||||
}, [rows, mode, stage, rateBasis, targetRate, themeRevision, refreshBarMasks, onlyStage, selectedPeriod, active]);
|
||||
|
||||
const dimmedPeriod = selectedPeriod === lineSelectedPeriod ? undefined : selectedPeriod;
|
||||
|
||||
@@ -1415,11 +1394,8 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
|
||||
</div>;
|
||||
}
|
||||
|
||||
function TrendTable({ rows, rateBasis, onMonth, defectDisplay = 'weight', showMonthLinks = true }: { rows: TrendMetricRow[]; rateBasis: 'original' | 'withoutHeadquartersScrap'; onMonth: (value: number | string) => void; defectDisplay?: 'weight'|'rate'; showMonthLinks?: boolean }) {
|
||||
export function TrendTable({ rows, rateBasis, onMonth, defectDisplay = 'weight', onlyStage }: { rows: TrendMetricRow[]; rateBasis: 'original' | 'withoutHeadquartersScrap'; onMonth: (value: number | string) => void; defectDisplay?: 'weight'|'rate'; onlyStage?: Stage }) {
|
||||
const compact = useCompactTable();
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(SUMMARY_PAGE_SIZE);
|
||||
useEffect(() => setCurrentPage(1), [rows]);
|
||||
const columns: ColumnsType<TrendMetricRow> = [
|
||||
{ title: '统计期间', dataIndex: 'month', key: 'month', align: 'center', fixed: 'left', width: 130, render: (_: unknown, row) => <Button type="link" onClick={() => onMonth(row.month)}>{row.periodLabel || String(row.month)}</Button> },
|
||||
{ title: totalWeightTitle('黑片总重量 / kg'), dataIndex: ['black', 'totalWeight'], key: 'blackTotal', align: 'center', width: 160, render: value => numberText(value) },
|
||||
@@ -1432,8 +1408,8 @@ function TrendTable({ rows, rateBasis, onMonth, defectDisplay = 'weight', showMo
|
||||
{ title: rateBasisTitle('亮片合格率', rateBasis, 'bright'), dataIndex: ['bright', 'rate'], key: 'brightRate', align: 'center', width: rateBasis === 'original' ? 180 : 194, className: 'rate-cell bright', render: (_: number | null, row: TrendMetricRow) => rateText(visibleStageRate(row, 'bright', rateBasis)) },
|
||||
{ title: rateBasisTitle('综合合格率', rateBasis, 'composite'), dataIndex: 'compositeRate', key: 'compositeRate', align: 'center', width: 120, fixed: compact ? undefined : 'right', className: 'combined-column', render: (_: number | null, row: MetricRow) => rateText(visibleCompositeRate(row, rateBasis)) },
|
||||
];
|
||||
return rows.length ? <div className="metric-table-scroll trend-data-table"><Table size="small" bordered tableLayout="fixed" columns={columns} dataSource={rows} rowKey={row => String(row.month)} pagination={{ current: currentPage, pageSize, showSizeChanger: rows.length > SUMMARY_PAGE_SIZE, pageSizeOptions: SUMMARY_PAGE_SIZE_OPTIONS, showTotal: (total, range) => `显示 ${range[0]}–${range[1]} 行,共 ${total} 个月`, onChange: (nextPage, nextPageSize) => { setPageSize(nextPageSize); setCurrentPage(nextPageSize === pageSize ? nextPage : 1); } }} scroll={{ x: columns.reduce((total, column) => total + Number(column.width || 0), 0) }} />
|
||||
{showMonthLinks && <div className="trend-month-links">{rows.map(row => <Button key={row.key} type="link" onClick={() => onMonth(row.month)}>{row.periodLabel || row.month}汇总</Button>)}</div>}
|
||||
const visibleColumns = onlyStage ? columns.filter(column => column.key === 'month' || String(column.key).startsWith(onlyStage)) : columns;
|
||||
return rows.length ? <div className="metric-table-scroll trend-data-table"><Table size="small" bordered tableLayout="fixed" columns={visibleColumns} dataSource={rows} rowKey={row => String(row.month)} pagination={false} scroll={{ x: visibleColumns.reduce((total, column) => total + Number(column.width || 0), 0) }} />
|
||||
</div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前数据未返回趋势" />;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import type { ReactNode, Ref } from 'react';
|
||||
import { Button, Input, Segmented, Select, Spin } from 'antd';
|
||||
import { DownloadOutlined, SearchOutlined } from '@ant-design/icons';
|
||||
import { readableSelectPopup } from './readableSelectPopup';
|
||||
|
||||
type Granularity = 'month' | 'quarter' | 'year';
|
||||
type TrendMode = 'production' | 'defects' | 'data';
|
||||
type DefectDisplay = 'weight' | 'rate';
|
||||
|
||||
export function QueryTrendPanel({ panelRef, id, mode, onMode, granularity, onGranularity, defectDisplay, onDefectDisplay, object, onObject, objects, scopeName, stageSwitch, children }: {
|
||||
panelRef?: Ref<HTMLElement>; id?: string; mode: TrendMode; onMode: (value: TrendMode) => void;
|
||||
granularity: Granularity; onGranularity: (value: Granularity) => void;
|
||||
defectDisplay: DefectDisplay; onDefectDisplay: (value: DefectDisplay) => void;
|
||||
object?: string; onObject: (value?: string) => void; objects: Array<{ label: string; value: string }>;
|
||||
scopeName: string; stageSwitch?: ReactNode; children: ReactNode;
|
||||
}) {
|
||||
const periodName = granularity === 'month' ? '月度' : granularity === 'quarter' ? '季度' : '年度';
|
||||
return <section className="panel section-panel trend-panel" ref={panelRef} id={id}>
|
||||
<div className="section-heading-row trend-heading-row">
|
||||
<div className="section-heading"><h2>{periodName}变化趋势</h2></div>
|
||||
<Segmented value={mode} options={[{ label: '合格率与产量', value: 'production' }, { label: '不良率', value: 'defects' }, { label: `${periodName}数据`, value: 'data' }]} onChange={onMode} aria-label="趋势视图" />
|
||||
</div>
|
||||
<div className="trend-controls">
|
||||
{mode === 'data' && <Segmented value={defectDisplay} options={[{ label: '不良重量', value: 'weight' }, { label: '不良率', value: 'rate' }]} onChange={onDefectDisplay} aria-label="趋势不良显示方式" />}
|
||||
<label className="query-field trend-granularity"><span>趋势粒度</span><Select {...readableSelectPopup} value={granularity} options={[{ label: '按月', value: 'month' }, { label: '按季度', value: 'quarter' }, { label: '按年度', value: 'year' }]} onChange={onGranularity} aria-label="趋势粒度" /></label>
|
||||
<label className="query-field trend-object"><span>趋势对象</span><Select {...readableSelectPopup} allowClear placeholder={`当前${scopeName}筛选`} value={object || undefined} options={objects} onChange={onObject} aria-label="趋势对象" /></label>
|
||||
{mode !== 'data' && stageSwitch}
|
||||
</div>
|
||||
{children}
|
||||
</section>;
|
||||
}
|
||||
|
||||
export function QueryTablePanel({ heading, busy, search, onSearchChange, onSearch, productView = true, searchPlaceholder, searchDisabled = false, searchUnavailable = false, fullFields, onFullFields, defectDisplay, onDefectDisplay, returnControls, exporting, exportDisabled, onExport, children }: {
|
||||
heading: ReactNode; busy?: boolean; search: string; onSearchChange: (value: string) => void; onSearch: () => void;
|
||||
productView?: boolean; searchPlaceholder?: string; searchDisabled?: boolean; searchUnavailable?: boolean;
|
||||
fullFields: boolean; onFullFields: (value: boolean) => void; defectDisplay: DefectDisplay; onDefectDisplay: (value: DefectDisplay) => void;
|
||||
returnControls?: ReactNode; exporting: boolean; exportDisabled: boolean; onExport: () => void; children: ReactNode;
|
||||
}) {
|
||||
return <section className="panel section-panel table-panel">
|
||||
<div className="section-heading-row">
|
||||
{heading}
|
||||
<div className="table-tools">
|
||||
{busy && <span className="defect-refresh-indicator"><Spin size="small" />正在更新</span>}
|
||||
<Input allowClear={!searchDisabled} disabled={searchDisabled} maxLength={productView ? 256 : undefined} prefix={<SearchOutlined />} placeholder={searchPlaceholder || (productView ? '输入关键词或完整产品名称' : '搜索汇总对象')} value={search} onChange={event => onSearchChange(event.target.value)} onPressEnter={onSearch} aria-label={productView ? '搜索产品名称并同步筛选指标和趋势' : '搜索汇总对象'} />
|
||||
<Button type="primary" disabled={searchDisabled || searchUnavailable} onClick={onSearch} aria-label="开始搜索">搜索</Button>
|
||||
<Segmented value={fullFields ? 'full' : 'key'} options={[{ label: '关键指标', value: 'key' }, { label: '完整字段', value: 'full' }]} onChange={value => onFullFields(value === 'full')} aria-label="字段显示" />
|
||||
<Segmented value={defectDisplay} options={[{ label: '不良重量', value: 'weight' }, { label: '不良率', value: 'rate' }]} onChange={onDefectDisplay} aria-label="不良显示方式" />
|
||||
{returnControls}
|
||||
<Button type="primary" className="query-export-button" icon={<DownloadOutlined />} aria-label="Excel导出" loading={exporting} disabled={exportDisabled} onClick={onExport}>Excel导出</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mobile-scroll-hint">横向滑动查看完整指标</div>
|
||||
{children}
|
||||
</section>;
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
import { SmoothTableFrame, useRetainedResult } from './QueryResultMotion';
|
||||
import { queryScrapWeight } from './queryMetricValues';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Alert, App, Button, Empty, Input, Modal, Segmented, Select, Spin } from 'antd';
|
||||
import { DownloadOutlined, ReloadOutlined, SearchOutlined } from '@ant-design/icons';
|
||||
import { Alert, App, Button, Empty, Modal, Segmented, Select, Spin } from 'antd';
|
||||
import { ArrowLeftOutlined, DownOutlined, UpOutlined } from '@ant-design/icons';
|
||||
import { api, decodeQueryValueList, encodeQueryValueList } from './api';
|
||||
import { MetricTable, MetricCard, DefectBreakdown, DefectParetoPanel, SectionHeading, RecordsDrawer, TrendChart, fullYearTrend, queryFromLocation } from './QueryPage';
|
||||
import { MetricTable, MetricCard, DefectBreakdown, DefectParetoPanel, SectionHeading, RecordsDrawer, TrendChart, TrendTable, fullYearTrend, queryFromLocation } from './QueryPage';
|
||||
import { StageSourceFilters } from './StageSourceFilters';
|
||||
import { stageProductQuery, sortStageRowsByTotalWeight } from './stageProductQuery';
|
||||
import { usePageCache } from './pageCache';
|
||||
@@ -12,6 +12,8 @@ import { defaultQueryMonth, previousCompleteMonth, previousCompleteQuarter } fro
|
||||
import { readableSelectPopup } from './readableSelectPopup';
|
||||
import { readableMetricFormula } from './publicDataDisplay';
|
||||
import type { MetricRow, MetricsResponse, OptionsResponse, PeriodKind, QueryParams, SourceColumnField, SourceColumnFilter, Stage } from './types';
|
||||
import { QueryTrendPanel, QueryTablePanel } from './QueryPanels';
|
||||
import { selectTrendPeriod as nextTrendPeriod } from './trendPeriodSelection';
|
||||
import './stage-product.css';
|
||||
|
||||
const weight=(v:number|null|undefined)=>typeof v==='number'?v.toLocaleString('zh-CN',{maximumFractionDigits:2}):'—';
|
||||
@@ -23,11 +25,13 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
|
||||
const [period,setPeriod]=useState<PeriodKind>(initial.quarter?'quarter':initial.month?'month':initial.year?'year':'month');
|
||||
const [year,setYear]=useState(initial.year||defaults.year);const [month,setMonth]=useState(initial.month||defaults.month);const [quarter,setQuarter]=useState(initial.quarter||previousCompleteQuarter().quarter);
|
||||
const [department,setDepartment]=useState(()=>decodeQueryValueList(initial.department));const [group,setGroup]=useState(()=>decodeQueryValueList(initial.group));const [product,setProduct]=useState(()=>decodeQueryValueList(initial.product));const [projectGroup,setProjectGroup]=useState(()=>decodeQueryValueList(initial.projectGroup));
|
||||
const [sourceFilters,setSourceFilters]=useState<SourceColumnFilter[]>(initial.columnFilters||[]);const [search,setSearch]=useState(initial.productSearch||'');const includeUnassigned=true;
|
||||
const [sourceFilters,setSourceFilters]=useState<SourceColumnFilter[]>(initial.columnFilters||[]);const [search,setSearch]=useState(initial.productSearch||'');const [appliedSearch,setAppliedSearch]=useState(initial.productSearch||'');const includeUnassigned=true;
|
||||
const [moreFiltersOpen,setMoreFiltersOpen]=useState(false);
|
||||
const [options,setOptions]=useState<OptionsResponse|null>(null);const [catalog,setCatalog]=useState<{releaseId:string;sourceFields:SourceColumnField[]}|null>(null);const [supportError,setSupportError]=useState('');const [supportLoading,setSupportLoading]=useState(true);
|
||||
const [applied,setApplied]=useState<QueryParams|null>(null);const [revision,setRevision]=useState(0);const [response,setResponse]=useState<{key:string;value:MetricsResponse}|null>(null);const [loading,setLoading]=useState(false);const [failure,setFailure]=useState<{key:string;message:string}|null>(null);
|
||||
const [defectDisplay,setDefectDisplay]=useState<'weight'|'rate'>('weight');
|
||||
const [fullFields,setFullFields]=useState(true);const [rateBasis,setRateBasis]=useState<'original'|'withoutHeadquartersScrap'>('original');const [basisOpen,setBasisOpen]=useState(false);const [trendMode,setTrendMode]=useState<'production'|'defects'|'data'>('production');
|
||||
const [drilledProduct,setDrilledProduct]=useState('');const drillParentSearch=useRef('');
|
||||
const [trendGranularity,setTrendGranularity]=useState<'month'|'quarter'|'year'>('month');
|
||||
const [trendResponse,setTrendResponse]=useState<{key:string;value:MetricsResponse}|null>(null);const [trendError,setTrendError]=useState('');const [trendLoading,setTrendLoading]=useState(false);
|
||||
const [recordVisible,setRecordVisible]=useState(false);const [records,setRecords]=useState<{row:MetricRow|null;query:QueryParams}|null>(null);const exporter=useRef<{exportExcel:()=>Promise<void>}>(null);const [exporting,setExporting]=useState(false);
|
||||
@@ -40,9 +44,12 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
|
||||
},[onUnauthorized]);
|
||||
useEffect(()=>{if(active)void loadSupport();},[active,refreshKey,loadSupport]);
|
||||
const fields=useMemo(()=>catalog?.sourceFields.filter(field=>field.type==='source_value'&&field.stages.includes(stage))||[],[catalog,stage]);
|
||||
const draft=useMemo(()=>stageProductQuery({year,...(period==='month'?{month}:period==='quarter'?{quarter}:{}),department:encodeQueryValueList(department),group:encodeQueryValueList(group),product:encodeQueryValueList(product),projectGroup:encodeQueryValueList(projectGroup),productSearch:search.trim()||undefined,includeUnassigned,view:'product',trendGranularity:'month',releaseId:catalog?.releaseId},stage,sourceFilters),[year,period,month,quarter,department,group,product,projectGroup,search,includeUnassigned,catalog,stage,sourceFilters]);
|
||||
// A new release resets the data binding; hidden cached pages never issue queries.
|
||||
useEffect(()=>{if(catalog)setApplied(draft);},[catalog]);
|
||||
const exactProductSearch=useMemo(()=>(options?.products||[]).find(name=>name.trim().toLocaleLowerCase()===appliedSearch.trim().toLocaleLowerCase())||'', [options,appliedSearch]);
|
||||
const queryProducts=useMemo(()=>drilledProduct?[drilledProduct]:exactProductSearch?product.length&&!product.includes(exactProductSearch)?['__codex_no_product_search_match__']:[exactProductSearch]:product,[drilledProduct,exactProductSearch,product]);
|
||||
useEffect(()=>{setDrilledProduct('');},[year,department,group,product,projectGroup,sourceFilters]);
|
||||
const draft=useMemo(()=>stageProductQuery({year,...(period==='month'?{month}:period==='quarter'?{quarter}:{}),department:encodeQueryValueList(department),group:encodeQueryValueList(group),product:encodeQueryValueList(queryProducts),projectGroup:encodeQueryValueList(projectGroup),productSearch:drilledProduct?undefined:appliedSearch.trim()||undefined,includeUnassigned,view:'product',trendGranularity:'month',releaseId:catalog?.releaseId},stage,sourceFilters),[year,period,month,quarter,department,group,queryProducts,drilledProduct,projectGroup,appliedSearch,includeUnassigned,catalog,stage,sourceFilters]);
|
||||
// Apply organizational/source filters directly, like the other query pages. Product text search keeps its explicit submit.
|
||||
useEffect(()=>{if(active&&catalog&&!supportLoading&&!supportError)setApplied(previous=>JSON.stringify(previous)===JSON.stringify(draft)?previous:draft);},[active,catalog,draft,supportLoading,supportError]);
|
||||
const queryKey=JSON.stringify({query:applied,revision});const current=response?.key===queryKey?response.value:null;const error=failure?.key===queryKey?failure.message:'';
|
||||
useEffect(()=>{
|
||||
if(!active||!applied||supportError)return;const controller=new AbortController();setLoading(true);setFailure(null);
|
||||
@@ -58,14 +65,27 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
|
||||
const selectedTrendPeriod=trendGranularity==='month'&&applied?.month
|
||||
? `${applied.year}-${String(applied.month).padStart(2,'0')}`
|
||||
: trendGranularity==='quarter'&&applied?.quarter ? `${applied.year}-Q${applied.quarter}` : undefined;
|
||||
const selectTrendPeriod=(value:number|string)=>{if(!applied)return;automaticPeriod.current=false;const text=String(value);if(trendGranularity==='year'){const selectedYear=Number(text);if(Number.isFinite(selectedYear)){setYear(selectedYear);setPeriod('year');setApplied({...applied,year:selectedYear,month:undefined,quarter:undefined});}}else if(trendGranularity==='quarter'){const selectedQuarter=Number(text.replace(/^.*Q/,''));if(selectedQuarter>=1&&selectedQuarter<=4){setQuarter(selectedQuarter);setPeriod('quarter');setApplied({...applied,quarter:selectedQuarter,month:undefined});}}else{const selectedMonth=Number(text.slice(-2));if(selectedMonth>=1&&selectedMonth<=12){setMonth(selectedMonth);setPeriod('month');setApplied({...applied,month:selectedMonth,quarter:undefined});}}setRevision(v=>v+1);};
|
||||
const dirty=!!applied&&JSON.stringify(draft)!==JSON.stringify(applied);const submit=()=>{automaticPeriod.current=false;setApplied(draft);setRevision(v=>v+1);};
|
||||
const selectTrendPeriod=(value:number|string)=>{automaticPeriod.current=false;const next=nextTrendPeriod(value,{period,year,month,quarter});setYear(next.year);setMonth(next.month);setQuarter(next.quarter);setPeriod(next.period);};
|
||||
const dirty=!!applied&&JSON.stringify(draft)!==JSON.stringify(applied);
|
||||
const queryBusy=supportLoading||loading||(!error&&!supportError&&(dirty||!current));
|
||||
const queryFailed=!!(error||supportError);
|
||||
const submit=()=>{automaticPeriod.current=false;setAppliedSearch(search.trim());setDrilledProduct('');setRevision(v=>v+1);};
|
||||
const setTrendObject=(value?:string)=>{const selected=value||'';setDrilledProduct('');setSearch(selected);setAppliedSearch(selected);};
|
||||
const returnToProducts=()=>{setDrilledProduct('');setSearch(drillParentSearch.current);setAppliedSearch(drillParentSearch.current);setTrendMode('production');};
|
||||
const reset=()=>{automaticPeriod.current=false;const previous=defaultQueryMonth(options);setYear(previous.year);setMonth(previous.month);setQuarter(previousCompleteQuarter().quarter);setPeriod('month');setTrendGranularity('month');setDepartment([]);setGroup([]);setProduct([]);setProjectGroup([]);setSourceFilters([]);setSearch('');setAppliedSearch('');setDrilledProduct('');setApplied(stageProductQuery({year:previous.year,month:previous.month,includeUnassigned,view:'product',trendGranularity:'month',releaseId:catalog?.releaseId},stage,[]));setRevision(v=>v+1);};
|
||||
const groups=(options?.groups||[]).filter(name=>!department.length||department.includes(options?.groupDepartments?.[name]||''));
|
||||
const paths=options?.organizationPaths||[];const products=department.length||group.length?[...new Set(paths.filter(path=>(!department.length||department.includes(path.department||''))&&(!group.length||group.includes(path.group||''))).map(path=>path.product).filter((v):v is string=>!!v))]:options?.products||[];
|
||||
const select=(name:string,value:string[],choices:string[],change:(v:string[])=>void)=><label className="query-field query-primary-field"><span>{name}</span><Select {...readableSelectPopup} mode="multiple" allowClear showSearch optionFilterProp="label" aria-label={name} placeholder="全部" maxTagCount="responsive" value={value} options={[...new Set([...choices,...value])].map(v=>({label:v==='__UNASSIGNED__'?'未分类':v,value:v}))} onChange={change}/></label>;
|
||||
const trendOptions=useMemo(()=>[...products.map(value=>({label:value,value})),...(drilledProduct==='__UNASSIGNED__'?[{label:'未分类',value:drilledProduct}]:[])],[products,drilledProduct]);
|
||||
const trendObject=drilledProduct||exactProductSearch;
|
||||
const drilledLabel=drilledProduct==='__UNASSIGNED__'?'未分类':drilledProduct;
|
||||
const select=(name:string,value:string[],choices:string[],change:(v:string[])=>void,extra=false)=><label className={`query-field ${extra?'query-extra-field':'query-primary-field'}`}><span>{name}</span><Select {...readableSelectPopup} mode="multiple" allowClear showSearch optionFilterProp="label" aria-label={name} placeholder="全部" maxTagCount="responsive" value={value} options={[...new Set([...choices,...value])].map(v=>({label:v==='__UNASSIGNED__'?'未分类':v,value:v}))} onChange={change}/></label>;
|
||||
const moreFilterCount=(projectGroup.length?1:0)+sourceFilters.length;
|
||||
const moreFilterSummary=[projectGroup.length?`项目组:${projectGroup.map(v=>v==='__UNASSIGNED__'?'未分类':v).join('、')}`:'',...sourceFilters.map(rule=>fields.find(field=>field.key===rule.field)?.label||rule.field)].filter(Boolean).join(';');
|
||||
const displayed = useRetainedResult(current && applied ? { data: current, query: applied } : null);
|
||||
const displayedQuery = displayed?.query || applied;
|
||||
const sortedRows=useMemo(()=>sortStageRowsByTotalWeight(displayed?.data.rows||[],stage),[displayed?.data,stage]);
|
||||
const trendRefreshing=trendLoading||!current||trendResponse?.key!==trendKey;
|
||||
const tableReady=!!current&&(!drilledProduct||!trendRefreshing);
|
||||
const table=useRetainedResult(tableReady&&applied?{rows:drilledProduct?visibleTrend:sortedRows,query:applied,drilledProduct,period:drilledProduct?'year' as const:applied.month?'month' as const:applied.quarter?'quarter' as const:'year' as const}:null);
|
||||
const summary=displayed?.data.summary[stage];const stageRate=stage==='bright'&&rateBasis==='withoutHeadquartersScrap'?summary?.rateWithoutHeadquartersScrap:summary?.rate;
|
||||
const openDetail=(row:MetricRow|null,_stage:Stage,selectedMonth?:number)=>{if(!applied||!current?.release)return;setRecordVisible(true);setRecords({row,query:{...applied,releaseId:current.release.id,...(row&&selectedMonth==null?{product:row.product||'__UNASSIGNED__'}:{}),...(selectedMonth?{month:selectedMonth,quarter:undefined}: {})}});};
|
||||
const runExport=async()=>{setExporting(true);try{await exporter.current?.exportExcel();}catch(e){message.error(e instanceof Error?e.message:'导出失败');}finally{setExporting(false);}};
|
||||
@@ -74,17 +94,21 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
|
||||
{supportError&&<Alert showIcon type="error" message="查询条件读取失败" description={supportError} action={<Button onClick={()=>void loadSupport()}>重试</Button>}/>}
|
||||
<section className="query-toolbar panel" aria-label={`${label}汇总条件`}>
|
||||
<Segmented aria-label="统计周期" value={period} options={[{label:'年度',value:'year'},{label:'季度',value:'quarter'},{label:'月度',value:'month'}]} onChange={v=>{automaticPeriod.current=false;setPeriod(v as PeriodKind);}}/>
|
||||
<label className="query-field query-period-field"><span>年份</span><Select aria-label="年份" value={year} onChange={v=>{automaticPeriod.current=false;setYear(v);}} options={(options?.years?.length?options.years:[year]).map(v=>({label:`${v}年`,value:v}))}/></label>
|
||||
{period==='month'&&<label className="query-field query-period-field"><span>月份</span><Select aria-label="月份" value={month} onChange={v=>{automaticPeriod.current=false;setMonth(v);}} options={Array.from({length:12},(_,i)=>({label:`${i+1}月`,value:i+1}))}/></label>}
|
||||
{period==='quarter'&&<label className="query-field query-period-field"><span>季度</span><Select aria-label="季度" value={quarter} onChange={v=>{automaticPeriod.current=false;setQuarter(v);}} options={[1,2,3,4].map(v=>({label:`第${v}季度`,value:v}))}/></label>}
|
||||
<label className="query-field query-period-field query-period-year"><span>年份</span><Select aria-label="年份" value={year} onChange={v=>{automaticPeriod.current=false;setYear(v);}} options={(options?.years?.length?options.years:[year]).map(v=>({label:`${v}年`,value:v}))}/></label>
|
||||
{period==='month'&&<label className="query-field query-period-field query-period-month"><span>月份</span><Select aria-label="月份" value={month} onChange={v=>{automaticPeriod.current=false;setMonth(v);}} options={Array.from({length:12},(_,i)=>({label:`${String(i+1).padStart(2,'0')}月`,value:i+1}))}/></label>}
|
||||
{period==='quarter'&&<label className="query-field query-period-field query-period-quarter"><span>季度</span><Select aria-label="季度" value={quarter} onChange={v=>{automaticPeriod.current=false;setQuarter(v);}} options={[1,2,3,4].map(v=>({label:`第${v}季度`,value:v}))}/></label>}
|
||||
{select('产业部',department,options?.departments||[],values=>{setDepartment(values);setGroup([]);setProduct([]);})}
|
||||
{select('业务分组',group,groups,values=>{setGroup(values);setProduct([]);})}
|
||||
{select('产品',product,products,setProduct)}
|
||||
{options?.projectGroupStatus==='READY'&&select('项目组',projectGroup,options.projectGroups||[],setProjectGroup)}
|
||||
{catalog&&<StageSourceFilters part="picker" stage={stage} fields={fields} query={draft} value={sourceFilters} onChange={setSourceFilters} onUnauthorized={onUnauthorized}/>}
|
||||
<div className="query-toolbar-tail"><Button type="text" icon={<ReloadOutlined/>} loading={supportLoading} onClick={()=>void loadSupport()}>刷新</Button><Button type="primary" icon={<SearchOutlined/>} disabled={supportLoading||!!supportError||!catalog} loading={loading} onClick={submit}>查询</Button></div>
|
||||
{catalog&&<StageSourceFilters part="rows" stage={stage} fields={fields} query={draft} value={sourceFilters} onChange={setSourceFilters} onUnauthorized={onUnauthorized}/>}
|
||||
{dirty&&<div className="stage-query-pending">筛选条件已修改,点击“查询”更新统计结果</div>}
|
||||
<div className="query-more-toggle" title={moreFilterSummary||undefined}>
|
||||
<Button type="text" size="small" icon={moreFiltersOpen?<UpOutlined/>:<DownOutlined/>} aria-expanded={moreFiltersOpen} aria-controls={`stage-more-filters-${stage}`} onClick={()=>setMoreFiltersOpen(open=>!open)}>更多筛选{moreFilterCount?`(已选 ${moreFilterCount} 项)`:''}</Button>
|
||||
{moreFilterCount>0&&<Button type="link" size="small" onClick={()=>{setProjectGroup([]);setSourceFilters([]);}}>清除</Button>}
|
||||
</div>
|
||||
<div className="query-toolbar-tail"><span className={`query-status ${queryBusy?'busy':queryFailed?'failed':''}`}><i/>{queryBusy?'正在查询':queryFailed?'查询失败':'查询完成'}</span><Button type="default" onClick={reset}>重置</Button></div>
|
||||
{moreFiltersOpen&&<div className="query-extra-fields" id={`stage-more-filters-${stage}`}>
|
||||
{options?.projectGroupStatus==='READY'&&select('项目组',projectGroup,options.projectGroups||[],setProjectGroup,true)}
|
||||
{catalog&&<StageSourceFilters stage={stage} fields={fields} query={draft} value={sourceFilters} onChange={setSourceFilters} onUnauthorized={onUnauthorized}/>}
|
||||
</div>}
|
||||
</section>
|
||||
{error&&<Alert showIcon type="error" message="查询失败" description={error} action={<Button onClick={()=>setRevision(v=>v+1)}>重试</Button>}/>}
|
||||
<section className="metric-strip stage-metric-strip" aria-label="质量指标" aria-busy={loading} inert={!current}>
|
||||
@@ -94,17 +118,40 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
|
||||
<MetricCard label="报废重量" value={`${weight(queryScrapWeight(summary,stage,rateBasis))} kg`} onClick={()=>openDetail(null,stage)}/>
|
||||
<MetricCard label="总重量" value={`${weight(summary?.totalWeight)} kg`} onClick={()=>openDetail(null,stage)}/>
|
||||
</section>
|
||||
<div className="analysis-stack"><section className="panel section-panel trend-panel"><div className="section-heading-row trend-heading-row"><SectionHeading title={`${trendGranularity==='year'?'年度':trendGranularity==='quarter'?'季度':'月度'}变化趋势`} subtitle={`${year} 年 · 当前${label}筛选`}/><Segmented value={trendMode} aria-label="趋势视图" options={[{label:'合格率与产量',value:'production'},{label:'不良率',value:'defects'},{label:`${trendGranularity==='year'?'年度':trendGranularity==='quarter'?'季度':'月度'}数据`,value:'data'}]} onChange={v=>setTrendMode(v as typeof trendMode)}/></div><div className="trend-controls">{trendMode==='data'&&<Segmented value={defectDisplay} aria-label="趋势不良显示方式" options={[{label:'不良重量',value:'weight'},{label:'不良率',value:'rate'}]} onChange={v=>setDefectDisplay(v as typeof defectDisplay)}/>}<label className="query-field trend-granularity"><span>趋势粒度</span><Select {...readableSelectPopup} value={trendGranularity} options={[{label:'按月',value:'month'},{label:'按季度',value:'quarter'},{label:'按年度',value:'year'}]} onChange={setTrendGranularity} aria-label="趋势粒度"/></label></div>{trendError&&<Alert type="warning" message="趋势读取失败" description={trendError}/>}<div className="trend-chart-shell" aria-busy={trendLoading}>{trendMode==='data'?<MetricTable exportFilename={`${label}月度趋势-${year}`} rows={displayedTrend} view="overall" layoutView="product" period="year" month={month} quarter={quarter} fullFields={fullFields} defectDisplay={defectDisplay} rateBasis={rateBasis} onlyStage={stage} onDetail={openDetail} onBasis={()=>setBasisOpen(true)} onDrilldown={()=>{}}/>:<TrendChart rows={displayedTrend} mode={trendMode} stage={stage} onlyStage={stage} rateBasis={rateBasis} targetRate={null} selectedPeriod={selectedTrendPeriod} onMonth={selectTrendPeriod}/>}{trendLoading&&<span className="trend-refresh-indicator"><Spin size="small"/>正在更新趋势</span>}</div><div className="chart-footnote"><span>指标由来源分量汇总,使用当前生效公式。</span><span>点击期间筛选</span></div></section>
|
||||
<section className="panel section-panel table-panel"><div className="section-heading-row"><SectionHeading title={`${label}汇总`} subtitle="重量 / kg 合格率 / %"/><div className="table-tools"><Input aria-label="搜索产品名称" placeholder="输入产品名称关键词" allowClear value={search} onChange={e=>setSearch(e.target.value)} onPressEnter={submit}/><Button onClick={submit} disabled={!catalog||!!supportError}>搜索</Button><Segmented value={fullFields?'full':'key'} aria-label="字段显示" options={[{label:'关键指标',value:'key'},{label:'完整字段',value:'full'}]} onChange={v=>setFullFields(v==='full')}/><Segmented value={defectDisplay} aria-label="不良显示方式" options={[{label:'不良重量',value:'weight'},{label:'不良率',value:'rate'}]} onChange={v=>setDefectDisplay(v as typeof defectDisplay)}/><Button icon={<DownloadOutlined/>} aria-label="Excel导出" loading={exporting} disabled={!current||loading} onClick={()=>void runExport()}>Excel导出</Button></div></div>
|
||||
<SmoothTableFrame busy={loading||!current} blocked={!current||loading}><MetricTable ref={exporter} exportFilename={`${label}产品汇总-${year}`} rows={sortedRows} view="product" period={displayedQuery?.month?'month':displayedQuery?.quarter?'quarter':'year'} month={displayedQuery?.month||month} quarter={displayedQuery?.quarter||quarter} fullFields={fullFields} defectDisplay={defectDisplay} rateBasis={rateBasis} onlyStage={stage} onDetail={openDetail} onBasis={()=>setBasisOpen(true)} onDrilldown={row=>{setProduct([row.product||'__UNASSIGNED__']);setSearch('');setApplied({...applied!,product:row.product||'__UNASSIGNED__',productSearch:undefined});setRevision(v=>v+1);}}/></SmoothTableFrame>
|
||||
</section>
|
||||
<div className="analysis-stack">
|
||||
<QueryTrendPanel mode={trendMode} onMode={setTrendMode} granularity={trendGranularity} onGranularity={setTrendGranularity}
|
||||
defectDisplay={defectDisplay} onDefectDisplay={setDefectDisplay} object={trendObject} onObject={setTrendObject} objects={trendOptions} scopeName="产品">
|
||||
{trendError&&<Alert type="warning" showIcon message="趋势读取失败" description={trendError} action={<Button onClick={()=>setRevision(v=>v+1)}>重试</Button>}/>}
|
||||
<div className="trend-chart-shell" aria-busy={trendRefreshing} inert={trendRefreshing||!!trendError}>
|
||||
{trendMode==='data'
|
||||
? <TrendTable rows={displayedTrend} defectDisplay={defectDisplay} rateBasis={rateBasis} onlyStage={stage} onMonth={selectTrendPeriod}/>
|
||||
: <TrendChart rows={displayedTrend} mode={trendMode} stage={stage} onlyStage={stage} rateBasis={rateBasis} targetRate={null} selectedPeriod={selectedTrendPeriod} onMonth={selectTrendPeriod}/>}
|
||||
{trendRefreshing&&<span className="trend-refresh-indicator"><Spin size="small"/>正在更新趋势</span>}
|
||||
</div>
|
||||
</QueryTrendPanel>
|
||||
<QueryTablePanel heading={<SectionHeading title={table?.drilledProduct?'产品月度质量数据':`${label}产品质量汇总`} subtitle={table?.drilledProduct?`${table.query.year} 年 · ${table.drilledProduct==='__UNASSIGNED__'?'未分类':table.drilledProduct} · 重量 / kg 合格率 / %`:'重量 / kg 合格率 / %'}/>}
|
||||
busy={queryBusy||!tableReady} search={drilledLabel||search} onSearchChange={setSearch} onSearch={submit} searchDisabled={!!drilledProduct} searchUnavailable={!catalog||!!supportError}
|
||||
fullFields={fullFields} onFullFields={setFullFields} defectDisplay={defectDisplay} onDefectDisplay={setDefectDisplay}
|
||||
returnControls={drilledProduct&&<Button className="query-return-button" icon={<ArrowLeftOutlined/>} onClick={returnToProducts}>返回上一级</Button>}
|
||||
exporting={exporting} exportDisabled={!current||loading||!tableReady||!table?.rows.length} onExport={()=>void runExport()}>
|
||||
<SmoothTableFrame busy={queryBusy||!tableReady} blocked={queryBusy||!tableReady}>
|
||||
<MetricTable ref={exporter} exportFilename={`${table?.drilledProduct||label}产品汇总-${table?.query.year||year}-${fullFields?'完整字段':'关键指标'}`}
|
||||
rows={table?.rows||[]} view={table?.drilledProduct?'overall':'product'} layoutView="product" pageSizeOverride={table?.drilledProduct?12:undefined}
|
||||
period={table?.period||period} month={table?.query.month||month} quarter={table?.query.quarter||quarter}
|
||||
fullFields={fullFields} defectDisplay={defectDisplay} rateBasis={rateBasis} onlyStage={stage} onDetail={openDetail} onBasis={()=>setBasisOpen(true)}
|
||||
emptyText={queryBusy?'正在更新数据…':error?'查询失败,暂无可展示结果':'当前条件下暂无数据'}
|
||||
onDrilldown={row=>{if(drilledProduct)return;const selected=row.product||'__UNASSIGNED__';drillParentSearch.current=appliedSearch;setDrilledProduct(selected);setTrendGranularity('month');setTrendMode('production');}}/>
|
||||
</SmoothTableFrame>
|
||||
</QueryTablePanel>
|
||||
<section className="panel section-panel defects-panel" aria-busy={loading||!current}>
|
||||
<div className="section-heading-row"><SectionHeading title="不良具体构成" subtitle={`${label} · 占比为分类报废内占比;废率为该类重量 ÷ 总重量`}/></div>
|
||||
<div className="section-heading-row"><SectionHeading title="不良具体构成"/></div>
|
||||
<div className="stage-defect-comparison">
|
||||
<section className="defect-stage-column" inert={!current||loading} aria-label={`${label}不良构成`}>
|
||||
<h3 className={`defect-stage-title ${stage}`}><i/>{label}</h3>
|
||||
{displayed?.data.defects[stage]?.length ? <DefectBreakdown items={displayed.data.defects[stage]} stage={stage} totalWeight={summary?.totalWeight} maximum={Math.max(0,...displayed.data.defects[stage].map(item=>item.weight||0))} onDetail={()=>openDetail(null,stage)}/> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={loading?'正在查询不良数据…':'当前条件下暂无不良分类数据'}/>}
|
||||
</section>
|
||||
{displayed&&<DefectParetoPanel releaseId={displayed.data.release?.id} query={displayed.query} pending={!current||loading} refreshKey={revision} onlyStage={stage} externalScrapWeight={stage==='black'?displayed.data.defects.black.find(item=>item.name==='外废')?.weight:undefined} onUnauthorized={onUnauthorized}/>}
|
||||
</div>
|
||||
</section></div>
|
||||
<Modal open={basisOpen} title={`${label}计算口径`} onCancel={()=>setBasisOpen(false)} footer={<Button onClick={()=>setBasisOpen(false)}>关闭</Button>}><p>{readableMetricFormula((current?.context.metricFormulaDescriptions as Record<string,unknown>|undefined)?.[formulaKey])}</p></Modal>
|
||||
{records&&<RecordsDrawer key={JSON.stringify(records)} open={recordVisible} row={records.row} query={records.query} stage={stage} lockedStage onStage={()=>{}} onClose={()=>setRecordVisible(false)} onUnauthorized={onUnauthorized}/>}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
.query-page { --defect-black: #718797; --defect-black-2: #A9BAC5; --defect-black-3: #D5E0E6; --defect-bright: var(--query-bright,var(--blue)); }
|
||||
:root[data-workspace-theme='dark'] .query-page { --defect-black: #B9BEC8; }
|
||||
.query-page .defect-stage-title.black { color: var(--defect-black); }
|
||||
.query-page .defect-stage-title.bright { color: var(--defect-bright); }
|
||||
.query-page .defect-stage-title.black i,.query-page .defect-stage-title.bright i { background: currentColor; }
|
||||
.defect-composition { position: relative; min-width: 0; padding-top: 2px; }
|
||||
.defect-composition-unit { font-size: var(--font-note); line-height: 18px; color: var(--muted-ink); }
|
||||
.defect-composition-plot { width: 100%; min-width: 0; height: 94px; }
|
||||
.defect-composition-empty { position: absolute; inset: 23px 0 auto; height: 65px; display: flex; align-items: center; justify-content: center; color: var(--muted-ink); font-size: var(--font-control); }
|
||||
.defect-composition-table { width: 100%; table-layout: fixed; border-collapse: collapse; margin: 8px 0 0; font-size: var(--font-table); }
|
||||
.defect-composition-table th { width: 25%; padding: 0 4px; text-align: center; height: 30px; font-size: var(--font-note); font-weight: 500; color: var(--ink); }
|
||||
.defect-composition-table td { height: 37px; padding: 0 4px; text-align: center; border-top: 1px solid color-mix(in srgb,var(--line) 65%,transparent); color: var(--muted-ink); font-family: var(--font-numeric); font-variant-numeric: tabular-nums; cursor: pointer; }
|
||||
.defect-composition-table td.defect-composition-weight { color: var(--ink); font-weight: 600; }
|
||||
.defect-composition-table tr:hover td { background: var(--hover); }
|
||||
.defect-composition-category { display: inline-grid; grid-template-columns: 9px minmax(0,1fr); align-items: center; gap: 9px; width: calc(3em + 18px); max-width: 100%; padding: 5px 0; text-align: center; color: var(--ink); font: var(--font-table) var(--font-ui); background: transparent; border: 0; cursor: pointer; }
|
||||
.defect-composition-category i { flex: 0 0 9px; height: 9px; background: var(--blue); }
|
||||
.defect-composition-category:focus-visible { outline: 2px solid var(--blue); outline-offset: 3px; }
|
||||
.defect-stage-grid:has(.defect-composition) > .defect-stage-column { padding: 0 16px 14px; }
|
||||
.defect-stage-grid:has(.defect-composition) .defect-stage-title { padding: 14px 1px 10px; }
|
||||
@media(max-width:760px) { :is(.defect-stage-grid,.stage-defect-comparison):has(.defect-composition) > .defect-stage-column { padding: 0 12px 12px; } }
|
||||
@@ -1,12 +1,9 @@
|
||||
.stage-product-page .query-toolbar { gap: 10px; }
|
||||
.stage-source-filters { display: contents; }
|
||||
.stage-source-filters > .ant-select { width: 220px; }
|
||||
.stage-source-filter-row { flex: 1 0 100%; display: grid; grid-template-columns: minmax(120px,180px) 150px minmax(240px,1fr) 32px; align-items: center; gap: 10px; }
|
||||
.stage-source-filter-row > strong { overflow-wrap: anywhere; font-size: var(--font-body); }
|
||||
.stage-source-filter-row > .ant-select { width: 100%; min-width: 0; }
|
||||
.stage-query-pending { flex-basis: 100%; color: var(--muted-ink); font-size: var(--font-control); }
|
||||
.stage-product-page .query-field > .ant-select { min-width: 110px; }
|
||||
.stage-product-page .query-primary-field > .ant-select { min-width: 0; }
|
||||
@media(max-width:760px) {
|
||||
.stage-source-filter-row { grid-template-columns: minmax(0,1fr) 140px 32px; }
|
||||
.stage-source-filter-row > .ant-select:nth-of-type(2) { grid-column: 1 / 3; grid-row: 2; }
|
||||
@@ -14,4 +11,12 @@
|
||||
.stage-metric-strip { grid-template-columns: repeat(2,minmax(0,1fr)); }
|
||||
}
|
||||
|
||||
.stage-product-page .defects-panel > .defect-stage-column { padding: 14px; }
|
||||
.stage-defect-comparison { display: grid; grid-template-columns: minmax(300px,1fr) minmax(0,2fr); border-top: 1px solid var(--line); }
|
||||
.stage-defect-comparison > .defect-stage-column { padding: 0 16px 14px; }
|
||||
.stage-defect-comparison .defect-stage-title { min-height: 40px; padding: 10px 0; }
|
||||
.stage-defect-comparison > .defect-pareto-section { min-width: 0; border-top: 0; border-left: 1px solid var(--line); padding: 0 12px 10px; }
|
||||
.stage-defect-comparison .defect-pareto-chart { height: 360px; }
|
||||
@media(max-width:1000px) {
|
||||
.stage-defect-comparison { grid-template-columns: 1fr; }
|
||||
.stage-defect-comparison > .defect-pareto-section { border-left: 0; border-top: 1px solid var(--line); }
|
||||
}
|
||||
|
||||
+17
-17
@@ -15,21 +15,21 @@
|
||||
--sidebar-surface: #f8fafd;
|
||||
--sidebar: 202px;
|
||||
--mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
||||
--ui-scale: .8;
|
||||
--viewport-height: calc(100vh / var(--ui-scale));
|
||||
--dynamic-viewport-height: calc(100dvh / var(--ui-scale));
|
||||
--small-viewport-height: calc(100svh / var(--ui-scale));
|
||||
--viewport-height: 100vh;
|
||||
--dynamic-viewport-height: 100dvh;
|
||||
--small-viewport-height: 100svh;
|
||||
--topbar-height: 53px;
|
||||
--workspace-sticky-top: var(--topbar-height);
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
html { zoom: var(--ui-scale); }
|
||||
@media (max-width: 760px) { :root { --ui-scale: 1; } }
|
||||
@media (max-width: 760px) { :root { --topbar-height: 40px; } }
|
||||
html, body, #root { min-width: 320px; min-height: 100%; margin: 0; }
|
||||
body { color: var(--ink); background: #f4f6fb; font-size: var(--font-body); }
|
||||
button, input, textarea, select { font: inherit; }
|
||||
button { color: inherit; }
|
||||
.app-shell { min-height: var(--viewport-height); }
|
||||
.sidebar { position: fixed; inset: 0 auto 0 0; z-index: 15; display: flex; width: var(--sidebar); flex-direction: column; padding: 16px 12px 10px; background: #f8f9fc; border-right: 1px solid var(--line); }
|
||||
.sidebar { --font-body: 14px; --font-control: 13px; position: fixed; inset: 0 auto 0 0; z-index: 15; display: flex; width: var(--sidebar); flex-direction: column; padding: 16px 12px 10px; background: #f8f9fc; border-right: 1px solid var(--line); }
|
||||
.brand { display: flex; align-items: center; gap: 8px; min-height: 34px; padding: 0 7px; border: 0; background: transparent; text-align: left; font-size: var(--font-dialog-title); font-weight: 700; cursor: pointer; white-space: nowrap; }
|
||||
.brand-mark { display: inline-flex; align-items: center; gap: 2px; width: 22px; height: 23px; transform: skew(-17deg); }
|
||||
.brand-mark i { display: block; width: 4px; height: 17px; background: var(--blue); }
|
||||
@@ -40,7 +40,7 @@ button { color: inherit; }
|
||||
.nav-group { margin-top: 12px; }
|
||||
.nav-group-label { padding: 7px 9px 6px; color: var(--ink); font-size: var(--font-control); font-weight: 650; }
|
||||
.nav-item { display: flex; width: 100%; min-height: 36px; align-items: center; gap: 10px; padding: 7px 9px; border: 0; background: transparent; text-align: left; cursor: pointer; font-size: var(--font-body); }
|
||||
.nav-item .anticon { width: 16px; color: var(--ink); font-size: var(--font-dialog-title); }
|
||||
.nav-item .anticon { width: 18px; flex: 0 0 18px; color: var(--ink); font-size: 18px; }
|
||||
.nav-item:hover { background: #eef2fb; }
|
||||
.nav-item.active { color: var(--blue-dark); background: #e3ebff; font-weight: 650; }
|
||||
.nav-item.active .anticon { color: var(--blue); }
|
||||
@@ -69,7 +69,7 @@ button { color: inherit; }
|
||||
.sidebar-collapsed .user-profile-trigger { flex: 0; }
|
||||
}
|
||||
@media (max-width: 760px) { .sidebar-toggle.ant-btn { display: none; } }
|
||||
.topbar { position: sticky; top: 0; z-index: 40; display: flex; height: 44px; align-items: center; justify-content: space-between; padding: 0 22px; background: var(--surface); border-bottom: 1px solid var(--line); }
|
||||
.topbar { position: sticky; top: 0; z-index: 40; display: flex; height: var(--topbar-height); align-items: center; justify-content: space-between; padding: 0 22px; background: var(--surface); border-bottom: 1px solid var(--line); }
|
||||
.breadcrumb { display: flex; align-items: center; gap: 10px; font-size: var(--font-control); }
|
||||
.breadcrumb strong { font-weight: 650; }
|
||||
.breadcrumb-slash { color: #63738a; }
|
||||
@@ -78,7 +78,7 @@ button { color: inherit; }
|
||||
.page-content { width: 100%; min-width: 0; margin: 0; padding: 15px 20px 20px; }
|
||||
.panel { background: var(--surface); border: 1px solid var(--line); border-radius: var(--panel-radius, 5px) !important; }
|
||||
.query-page { display: flex; min-width: 0; flex-direction: column; gap: 11px; overflow-anchor: none; }
|
||||
.query-toolbar { position: sticky; top: 53px; z-index: 35; display: flex; min-height: 48px; flex-wrap: wrap; align-items: center; gap: 10px 13px; padding: 7px 11px; }
|
||||
.query-toolbar { position: sticky; top: var(--workspace-sticky-top); z-index: 35; display: flex; min-height: 48px; flex-wrap: wrap; align-items: center; gap: 10px 13px; padding: 7px 11px; }
|
||||
.query-toolbar::before { content: ''; position: absolute; right: -20px; bottom: 100%; left: -20px; height: 18px; background: var(--background); pointer-events: none; }
|
||||
.query-field { display: inline-flex; min-width: 0; align-items: center; gap: 7px; }
|
||||
.query-field > span { flex: 0 0 auto; white-space: nowrap; font-size: var(--font-control); }
|
||||
@@ -155,8 +155,8 @@ button { color: inherit; }
|
||||
.trend-object .ant-select { width: min(420px, 100%); }
|
||||
.chart-viewport { width: 100%; overflow-x: auto; }
|
||||
.chart-surface { position: relative; width: 100%; min-width: 0; }
|
||||
/* Keep SVG chart coordinates aligned with pointer events under the app's global UI zoom. */
|
||||
.chart-container { width: 100%; height: calc(380px * var(--ui-scale)); min-width: 0; zoom: calc(1 / var(--ui-scale)); }
|
||||
/* 图表与页面使用同一坐标尺寸,保持 SVG 和鼠标位置一致。 */
|
||||
.chart-container { width: 100%; height: 380px; min-width: 0; }
|
||||
.chart-footnote { display: flex; justify-content: space-between; gap: 12px; padding: 0 13px 10px; font-size: var(--font-note); }
|
||||
.defects-panel { min-height: 120px; }
|
||||
.defect-stage-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); border-top: 1px solid var(--line); }
|
||||
@@ -164,7 +164,7 @@ button { color: inherit; }
|
||||
.defect-pareto-heading { display: flex; min-height: 38px; flex-wrap: wrap; align-items: baseline; gap: 5px 12px; padding: 8px 1px 0; }
|
||||
.defect-pareto-heading strong { font-size: var(--font-body); font-weight: 650; }
|
||||
.defect-pareto-heading span { color: var(--ink); font-size: var(--font-note); }
|
||||
.defect-pareto-chart { width: 100%; height: calc(470px * var(--ui-scale)); min-width: 0; zoom: calc(1 / var(--ui-scale)); }
|
||||
.defect-pareto-chart { width: 100%; height: 470px; min-width: 0; }
|
||||
.defect-pareto-status { display: flex; min-height: 52px; align-items: center; justify-content: center; gap: 8px; font-size: var(--font-control); }
|
||||
.defect-stage-column { min-width: 0; padding: 0 12px 10px; }
|
||||
.defect-stage-column + .defect-stage-column { border-left: 1px solid var(--line); }
|
||||
@@ -374,7 +374,7 @@ button { color: inherit; }
|
||||
:root { --sidebar: 0px; }
|
||||
.sidebar { display: none; }
|
||||
.main-column { margin-left: 0; }
|
||||
.topbar { height: 40px; padding: 0 12px; }
|
||||
.topbar { padding: 0 12px; }
|
||||
.top-organization { display: none; }
|
||||
.mobile-brand { display: flex; min-height: 44px; align-items: center; gap: 7px; padding: 4px 10px; background: #f8f9fc; border-bottom: 1px solid var(--line); font-size: var(--font-section); }
|
||||
.mobile-brand > strong { white-space: nowrap; }
|
||||
@@ -478,7 +478,7 @@ body { background: var(--background); }
|
||||
.nav-item:hover { background: var(--hover); }
|
||||
.nav-item.active { color: var(--blue-dark); background: var(--blue-soft); }
|
||||
.nav-item.active .anticon { color: var(--blue); }
|
||||
.topbar { height: 53px; padding: 0 20px; }
|
||||
.topbar { height: var(--topbar-height); padding: 0 20px; }
|
||||
.topbar-actions { display: flex; align-items: center; gap: 8px; }
|
||||
.topbar-search.ant-btn {
|
||||
display: inline-flex;
|
||||
@@ -559,7 +559,7 @@ body { background: var(--background); }
|
||||
.query-toolbar::before { right: -15px; left: -15px; height: 16px; }
|
||||
}
|
||||
@media (max-width: 760px) {
|
||||
.topbar { height: 40px; padding: 0 12px; }
|
||||
.topbar { padding: 0 12px; }
|
||||
.topbar-actions { gap: 2px; }
|
||||
.topbar-search.ant-btn { width: 30px; justify-content: center; padding: 0; }
|
||||
.topbar-search > span:not(.anticon), .topbar-search kbd { display: none; }
|
||||
@@ -568,7 +568,7 @@ body { background: var(--background); }
|
||||
.top-organization { display: none; }
|
||||
.mobile-brand { background: var(--sidebar-surface); }
|
||||
.page-content { padding: 11px 10px 18px; }
|
||||
.query-toolbar { top: 40px; }
|
||||
.query-toolbar { top: var(--workspace-sticky-top); }
|
||||
.query-toolbar::before { right: -10px; left: -10px; height: 12px; }
|
||||
.navigation-search-modal { max-width: calc(100vw - 24px); }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { PeriodKind } from './types';
|
||||
|
||||
type PeriodSelection = { period: PeriodKind; year: number; month: number; quarter: number };
|
||||
|
||||
export function selectTrendPeriod(value: number | string, current: PeriodSelection): PeriodSelection {
|
||||
const raw = String(value);
|
||||
const quarterly = raw.match(/^(\d{4})-Q([1-4])$/);
|
||||
const monthly = raw.match(/^(\d{4})-(\d{1,2})$/);
|
||||
if (quarterly) {
|
||||
const year = Number(quarterly[1]), quarter = Number(quarterly[2]);
|
||||
return { ...current, year, quarter, period: current.period === 'quarter' && current.year === year && current.quarter === quarter ? 'year' : 'quarter' };
|
||||
}
|
||||
if (monthly) {
|
||||
const year = Number(monthly[1]), month = Number(monthly[2]);
|
||||
if (month < 1 || month > 12) return current;
|
||||
return { ...current, year, month, period: current.period === 'month' && current.year === year && current.month === month ? 'year' : 'month' };
|
||||
}
|
||||
if (/^\d{4}$/.test(raw)) return { ...current, year: Number(raw), period: 'year' };
|
||||
const month = Number(raw.match(/\d{1,2}/)?.[0]);
|
||||
return Number.isInteger(month) && month >= 1 && month <= 12
|
||||
? { ...current, month, period: current.period === 'month' && current.month === month ? 'year' : 'month' }
|
||||
: current;
|
||||
}
|
||||
@@ -17,7 +17,7 @@
|
||||
|
||||
body, button, input, textarea, select { font-family: var(--font-ui); }
|
||||
|
||||
/* 查询区在既有缩放下保留可读正文,避免指标与明细的字号反差过大。 */
|
||||
/* 查询区保留统一的可读正文,避免指标与明细的字号反差过大。 */
|
||||
.query-page {
|
||||
--font-control: 13px;
|
||||
--font-table: 13px;
|
||||
|
||||
@@ -37,6 +37,13 @@ body, .app-shell, .main-column { color: var(--ink); background: var(--background
|
||||
.ant-segmented .ant-segmented-item-selected { color: var(--blue-dark); background: var(--blue-soft); box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--blue) 22%, transparent); }
|
||||
.ant-segmented .ant-segmented-item, .ant-segmented .ant-segmented-thumb { border-radius: calc(var(--control-radius) - 1px); }
|
||||
.ant-btn-primary { box-shadow: 0 1px 2px #101b3010; }
|
||||
.table-tools :is(.query-return-button, .query-export-button) { font-weight: 600; }
|
||||
.table-tools .query-return-button:not(:disabled) {
|
||||
border-color: var(--blue);
|
||||
color: var(--blue-dark);
|
||||
background: var(--blue-soft);
|
||||
}
|
||||
.table-tools .query-return-button:not(:disabled):hover { background: var(--hover); }
|
||||
.ant-btn:focus-visible, .nav-item:focus-visible, .metric-card:focus-visible { outline: 2px solid var(--blue); outline-offset: 2px; }
|
||||
.workspace-theme-dropdown .ant-dropdown-menu { border-radius: var(--panel-radius); }
|
||||
.workspace-theme-dropdown .ant-dropdown-menu-item { border-radius: calc(var(--control-radius) - 1px); }
|
||||
@@ -92,12 +99,13 @@ body, .app-shell, .main-column { color: var(--ink); background: var(--background
|
||||
z-index: 1;
|
||||
}
|
||||
.query-page .metric-strip > .metric-card {
|
||||
min-height: 84px;
|
||||
min-height: 96px;
|
||||
padding: 8px 13px;
|
||||
gap: 3px;
|
||||
}
|
||||
.query-page .metric-strip:has(> .rate-basis-control) > .metric-card:last-child .metric-label { padding-right: 140px; }
|
||||
@media (max-width: 760px) {
|
||||
.query-page .metric-strip > .metric-card { min-height: 84px; }
|
||||
.query-page .metric-strip > .rate-basis-control { position: static; padding: 0 8px; }
|
||||
.query-page .metric-strip:has(> .rate-basis-control) > .metric-card:last-child .metric-label { padding-right: 0; }
|
||||
}
|
||||
@@ -106,19 +114,19 @@ body, .app-shell, .main-column { color: var(--ink); background: var(--background
|
||||
.mapping-issue-filters .ant-select { min-width: 180px; flex: 0 1 240px; }
|
||||
|
||||
/* Retained maintenance sections share a compact, sticky navigation bar. */
|
||||
.management-sections > .ant-tabs-nav { position: sticky; top: 53px; z-index: 34; margin: 0 0 12px; padding: 0 16px; background: var(--surface); border: 1px solid var(--line); }
|
||||
.management-sections > .ant-tabs-nav { position: sticky; top: var(--workspace-sticky-top); z-index: 34; margin: 0 0 12px; padding: 0 16px; background: var(--surface); border: 1px solid var(--line); }
|
||||
.management-sections > .ant-tabs-body-holder > .ant-tabs-body > .ant-tabs-content { padding: 12px; background: var(--surface); border: 1px solid var(--line); }
|
||||
.management-sections .management-page { gap: 10px; }
|
||||
.management-module-actions { display: flex; justify-content: flex-end; margin: 0; padding: 0 0 6px; }
|
||||
.management-module-actions .page-heading-actions { margin: 0; }
|
||||
.management-sections .nc-simple-config-tabs > .ant-tabs-nav { position: sticky; top: 100px; z-index: 33; background: var(--surface); }
|
||||
@media (max-width: 760px) { .management-sections > .ant-tabs-nav { top: 40px; } .management-sections .nc-simple-config-tabs > .ant-tabs-nav { top: 87px; } }
|
||||
.management-sections .nc-simple-config-tabs > .ant-tabs-nav { position: sticky; top: calc(var(--workspace-sticky-top) + 47px); z-index: 33; background: var(--surface); }
|
||||
|
||||
|
||||
.management-sections > .ant-tabs-body-holder, .management-sections > .ant-tabs-body-holder > .ant-tabs-body { overflow: visible; }
|
||||
.management-sections { overflow: visible; }
|
||||
.management-sections .management-sections > .ant-tabs-nav { top: 100px; z-index: 33; }
|
||||
.management-sections .management-sections .management-sections > .ant-tabs-nav { top: 147px; z-index: 32; }
|
||||
@media (max-width: 760px) { .management-sections .management-sections > .ant-tabs-nav { top: 87px; } .management-sections .management-sections .management-sections > .ant-tabs-nav { top: 134px; } }
|
||||
.management-sections .management-sections > .ant-tabs-nav { top: calc(var(--workspace-sticky-top) + 47px); z-index: 33; }
|
||||
.management-sections .management-sections .management-sections > .ant-tabs-nav { top: calc(var(--workspace-sticky-top) + 94px); z-index: 32; }
|
||||
|
||||
/* A clipping panel becomes a false scroll ancestor for sticky tab navigation. */
|
||||
.management-sections .panel:has(.ant-tabs-nav) { overflow: visible; }
|
||||
.management-sections .resource-toolbar > .completion-actions { margin-left: auto; }
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import ts from 'typescript';
|
||||
import React from 'react';
|
||||
function fixture() {
|
||||
const source=fs.readFileSync(process.env.QUERY_CHART_SOURCE || new URL('../src/QueryPage.tsx',import.meta.url),'utf8');
|
||||
const end=source.includes('export function TrendTable(')?source.indexOf('export function TrendTable('):source.indexOf('function TrendTable(');
|
||||
const code=source.slice(source.indexOf('export function TrendChart('),end).replace('export function','function');
|
||||
const slots=new Map(),effects=new Map(),observers=[],charts=[];let cursor=0,dirty=false,queued=[],active=true;
|
||||
const node={clientWidth:900,clientHeight:380};
|
||||
const hooks={useRef(initial){const i=cursor++;if(!slots.has(i))slots.set(i,{current:initial});return slots.get(i);},useState(initial){const i=cursor++;if(!slots.has(i))slots.set(i,initial);return [slots.get(i),v=>{const next=typeof v==='function'?v(slots.get(i)):v;if(!Object.is(next,slots.get(i))){slots.set(i,next);dirty=true;}}];},useCallback(fn,deps){const i=cursor++;const old=slots.get(i);if(!old||deps.some((d,j)=>!Object.is(d,old.deps[j])))slots.set(i,{fn,deps});return slots.get(i).fn;},useEffect(fn,deps){const i=cursor++,old=effects.get(i);if(!old||deps.some((d,j)=>!Object.is(d,old.deps[j])))queued.push(()=>{old?.cleanup?.();effects.set(i,{deps,cleanup:fn()});});}};
|
||||
hooks.useLayoutEffect=hooks.useEffect;
|
||||
const ec={init(_node,_theme,opts){const c={opts,options:[],resizes:[],disposed:false,getWidth:()=>c.opts.width??100,getHeight:()=>c.opts.height??380,on(){},resize(o){c.resizes.push(o);},setOption(o){c.options.push(o);},convertToPixel:()=>0,dispose(){c.disposed=true;}};charts.push(c);return c;}};
|
||||
const prelude=`const {useRef,useState,useEffect,useLayoutEffect,useCallback}=hooks;
|
||||
const usePageCache=()=>({active:getActive()});
|
||||
const Empty=Object.assign('Empty',{PRESENTED_IMAGE_SIMPLE:'simple'});
|
||||
const MutationObserver=class{observe(){}disconnect(){}},ResizeObserver=class{constructor(fn){this.fn=fn;observers.push(this)}observe(){}disconnect(){this.disconnected=true}};
|
||||
const document={documentElement:{dataset:{}}},window={matchMedia:()=>({matches:false,addEventListener(){},removeEventListener(){}})};
|
||||
const queryChartTypography=()=>({fontFamily:'sans',numericFamily:'sans',fontSize:12,tooltipFontSize:12});
|
||||
const getComputedStyle=()=>({getPropertyValue:()=>''}),getWorkspaceTheme=()=>({id:'light'}),trendBarPalette=()=>({qualified:'#607ae1',scrap:'#d58c35'});
|
||||
const trendBarWidth=()=>32,hasStageRows=()=>true,stageValue=(r,s,f)=>r[s][f],visibleCompositeRate=()=>.95,visibleStageRate=()=>.97,rateNumber=v=>v*100,numberText=String,escapeTooltipText=String,defectWeightRate=()=>0;
|
||||
`;
|
||||
const compiled=ts.transpileModule(prelude+code+'\nreturn TrendChart;',{fileName:'motion.tsx',compilerOptions:{target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.React}}).outputText;
|
||||
const Component=new Function('React','hooks','echarts','getActive','observers',compiled)(React,hooks,ec,()=>active,observers);
|
||||
const stage={qualifiedWeight:90,scrapWeight:10,totalWeight:100,defects:[]};const props={rows:[{month:1,black:stage,bright:stage}],mode:'production',stage:'bright',rateBasis:'original',targetRate:null,onMonth(){}};
|
||||
function attach(t){if(!t||typeof t!=='object')return;if(t.props?.ref)t.props.ref.current=node;React.Children.forEach(t.props?.children,attach);}
|
||||
function render(){let n=0;do{cursor=0;dirty=false;queued=[];attach(Component(props));queued.forEach(f=>f());assert.ok(++n<10);}while(dirty);}
|
||||
return {charts,node,render,setActive(v){active=v;render();},resize(){for(const o of observers)if(!o.disconnected)o.fn();},unmount(){effects.forEach(e=>e.cleanup?.());}};
|
||||
}
|
||||
test('visible entry uses the actual chart size and enables native vertical bar growth',()=>{
|
||||
const f=fixture();f.render();const c=f.charts[0];assert.equal(c.opts.width,900);assert.equal(c.opts.height,380);
|
||||
const o=c.options.find(o=>o.series);assert.ok(o.animationDuration>0);assert.equal(o.xAxis.type,'category');assert.equal(o.yAxis[0].type,'value');assert.ok(o.series.filter(s=>s.type==='bar').every(s=>s.yAxisIndex===0));f.unmount();
|
||||
});
|
||||
test('cached page reentry creates a fresh vertical reveal and never resizes a hidden chart to zero',()=>{
|
||||
const f=fixture();f.render();f.node.clientWidth=0;f.resize();assert.equal(f.charts[0].resizes.length,0);
|
||||
f.setActive(false);assert.equal(f.charts[0].disposed,true);assert.equal(f.charts.length,1);
|
||||
f.node.clientWidth=900;f.setActive(true);assert.equal(f.charts.length,2);assert.equal(f.charts[1].opts.width,900);assert.ok(f.charts[1].options.find(o=>o.series).animationDuration>0);f.unmount();
|
||||
});
|
||||
@@ -19,6 +19,7 @@ function fixture(){
|
||||
const Spin='Spin',Alert='Alert',Empty=Object.assign('Empty',{PRESENTED_IMAGE_SIMPLE:'simple'});
|
||||
const MutationObserver=class{observe(){}disconnect(){}},ResizeObserver=class{observe(){}disconnect(){}};
|
||||
const document={documentElement:{}},window={matchMedia:()=>({matches:false,addEventListener(){},removeEventListener(){}})};
|
||||
const usePageCache=()=>({active:true});
|
||||
const queryChartTypography=()=>({fontFamily:'sans',numericFamily:'sans',fontSize:12,tooltipFontSize:12});
|
||||
const getComputedStyle=()=>({getPropertyValue:()=>''}),escapeTooltipText=v=>v,numberText=v=>String(v),chooseError=e=>e.message;
|
||||
class ApiError extends Error{};
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { selectTrendPeriod } from '../src/trendPeriodSelection.ts';
|
||||
const current={year:2026,month:9,quarter:3,period:'month'};
|
||||
test('clicking the selected month returns to annual scope; another month selects that month',()=>{
|
||||
assert.deepEqual(selectTrendPeriod('2026-09',current),{...current,period:'year'});
|
||||
assert.deepEqual(selectTrendPeriod('2026-08',current),{...current,month:8});
|
||||
assert.deepEqual(selectTrendPeriod('08月',current),{...current,month:8});
|
||||
});
|
||||
test('quarter selection and toggling preserve the selected year',()=>{
|
||||
assert.deepEqual(selectTrendPeriod('2025-Q4',current),{...current,year:2025,quarter:4,period:'quarter'});
|
||||
assert.deepEqual(selectTrendPeriod('2026-Q3',{...current,period:'quarter'}),{...current,period:'year'});
|
||||
});
|
||||
test('annual selection and invalid values cannot produce an invalid month',()=>{
|
||||
assert.deepEqual(selectTrendPeriod('2025',current),{...current,year:2025,period:'year'});
|
||||
assert.equal(selectTrendPeriod('2026-13',current),current);
|
||||
assert.equal(selectTrendPeriod('invalid',current),current);
|
||||
});
|
||||
Reference in New Issue
Block a user