初始化:质量数据分析平台源码
This commit is contained in:
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="color-scheme" content="light" />
|
||||
<title>质量中心 · 质量洞察</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"name": "quality-center-web",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite --host 127.0.0.1 --port 5280",
|
||||
"build": "tsc -b && vite build"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ant-design/icons": "6.0.0",
|
||||
"antd": "6.6.7",
|
||||
"echarts": "6.0.0",
|
||||
"html-to-image": "1.11.13",
|
||||
"react": "19.3.1",
|
||||
"react-dom": "19.3.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "19.0.0",
|
||||
"@types/react-dom": "19.0.0",
|
||||
"typescript": "5.9.3",
|
||||
"vite": "8.3.4"
|
||||
}
|
||||
}
|
||||
Generated
+1413
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,2 @@
|
||||
minimumReleaseAgeExclude:
|
||||
- antd@6.6.7
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 9.7 KiB |
@@ -0,0 +1,109 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { sanitizeAnalysisDisplayText } from './analysisDisplayText';
|
||||
|
||||
function inlineMarkdown(value: string, keyPrefix = 'inline'): ReactNode[] {
|
||||
return value.split(/(\*\*.+?\*\*|`[^`]+`)/g).map((part, index) => {
|
||||
if (part.startsWith('**') && part.endsWith('**') && part.length >= 4) {
|
||||
return <strong key={`${keyPrefix}-${index}`}>{part.slice(2, -2)}</strong>;
|
||||
}
|
||||
if (part.startsWith('`') && part.endsWith('`') && part.length >= 2) {
|
||||
return <code key={`${keyPrefix}-${index}`}>{part.slice(1, -1)}</code>;
|
||||
}
|
||||
return part;
|
||||
});
|
||||
}
|
||||
|
||||
function tableCells(line: string): string[] {
|
||||
const source = line.trim().replace(/^\|/, '').replace(/\|$/, '');
|
||||
return source.split('|').map(cell => cell.trim());
|
||||
}
|
||||
|
||||
function isTableStart(lines: string[], index: number): boolean {
|
||||
if (index + 1 >= lines.length || !lines[index].includes('|')) return false;
|
||||
const separators = tableCells(lines[index + 1]);
|
||||
return separators.length > 0 && separators.every(cell => /^:?-{3,}:?$/.test(cell));
|
||||
}
|
||||
|
||||
function isBlockStart(lines: string[], index: number): boolean {
|
||||
const line = lines[index];
|
||||
return /^\s*#{1,6}\s+/.test(line)
|
||||
|| /^\s*```/.test(line)
|
||||
|| /^\s*(?:[-*+]\s+|\d+[.)]\s+)/.test(line)
|
||||
|| isTableStart(lines, index);
|
||||
}
|
||||
|
||||
/** Renders the small Markdown subset used by analysis answers with React text nodes only. */
|
||||
export function AiMarkdown({ content, className }: { content: string; className?: string }) {
|
||||
const lines = sanitizeAnalysisDisplayText(content).replaceAll('\r\n', '\n').replaceAll('\r', '\n').split('\n');
|
||||
const blocks: ReactNode[] = [];
|
||||
let index = 0;
|
||||
|
||||
while (index < lines.length) {
|
||||
const line = lines[index];
|
||||
if (!line.trim()) { index += 1; continue; }
|
||||
|
||||
const fence = line.match(/^\s*```([^`]*)$/);
|
||||
if (fence) {
|
||||
const code: string[] = [];
|
||||
index += 1;
|
||||
while (index < lines.length && !/^\s*```\s*$/.test(lines[index])) code.push(lines[index++]);
|
||||
if (index < lines.length) index += 1;
|
||||
blocks.push(<pre key={`code-${blocks.length}`}><code>{code.join('\n')}</code></pre>);
|
||||
continue;
|
||||
}
|
||||
|
||||
const heading = line.match(/^\s*(#{1,6})\s+(.+?)\s*#*\s*$/);
|
||||
if (heading) {
|
||||
const level = heading[1].length;
|
||||
const key = `heading-${blocks.length}`;
|
||||
const children = inlineMarkdown(heading[2], key);
|
||||
if (level === 1) blocks.push(<h1 key={key}>{children}</h1>);
|
||||
else if (level === 2) blocks.push(<h2 key={key}>{children}</h2>);
|
||||
else if (level === 3) blocks.push(<h3 key={key}>{children}</h3>);
|
||||
else if (level === 4) blocks.push(<h4 key={key}>{children}</h4>);
|
||||
else if (level === 5) blocks.push(<h5 key={key}>{children}</h5>);
|
||||
else blocks.push(<h6 key={key}>{children}</h6>);
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isTableStart(lines, index)) {
|
||||
const headers = tableCells(lines[index]);
|
||||
index += 2;
|
||||
const body: string[][] = [];
|
||||
while (index < lines.length && lines[index].trim() && lines[index].includes('|')) body.push(tableCells(lines[index++]));
|
||||
blocks.push(<div className="ai-markdown-table-wrap" key={`table-${blocks.length}`}><table>
|
||||
<thead><tr>{headers.map((cell, cellIndex) => <th key={cellIndex}>{inlineMarkdown(cell, `th-${cellIndex}`)}</th>)}</tr></thead>
|
||||
<tbody>{body.map((row, rowIndex) => <tr key={rowIndex}>{headers.map((_, cellIndex) => <td key={cellIndex}>{inlineMarkdown(row[cellIndex] || '', `td-${rowIndex}-${cellIndex}`)}</td>)}</tr>)}</tbody>
|
||||
</table></div>);
|
||||
continue;
|
||||
}
|
||||
|
||||
const listItem = line.match(/^\s*(?:([-*+])\s+|(\d+)[.)]\s+)(.*)$/);
|
||||
if (listItem) {
|
||||
const ordered = Boolean(listItem[2]);
|
||||
const list: string[] = [];
|
||||
const firstNumber = ordered ? Number(listItem[2]) : undefined;
|
||||
while (index < lines.length) {
|
||||
const current = lines[index].match(/^\s*(?:([-*+])\s+|(\d+)[.)]\s+)(.*)$/);
|
||||
if (!current || Boolean(current[2]) !== ordered) break;
|
||||
list.push(current[3]);
|
||||
index += 1;
|
||||
}
|
||||
blocks.push(ordered
|
||||
? <ol key={`list-${blocks.length}`} start={firstNumber}>{list.map((item, itemIndex) => <li key={itemIndex}>{inlineMarkdown(item, `ol-${blocks.length}-${itemIndex}`)}</li>)}</ol>
|
||||
: <ul key={`list-${blocks.length}`}>{list.map((item, itemIndex) => <li key={itemIndex}>{inlineMarkdown(item, `ul-${blocks.length}-${itemIndex}`)}</li>)}</ul>);
|
||||
continue;
|
||||
}
|
||||
|
||||
const paragraph: string[] = [];
|
||||
while (index < lines.length && lines[index].trim() && !isBlockStart(lines, index)) paragraph.push(lines[index++]);
|
||||
if (!paragraph.length) { index += 1; continue; }
|
||||
blocks.push(<p key={`paragraph-${blocks.length}`}>{paragraph.flatMap((part, partIndex) => [
|
||||
...(partIndex ? [<br key={`break-${partIndex}`} />] : []),
|
||||
...inlineMarkdown(part, `paragraph-${blocks.length}-${partIndex}`),
|
||||
])}</p>);
|
||||
}
|
||||
|
||||
return <div className={className ? `ai-markdown ${className}` : 'ai-markdown'}>{blocks}</div>;
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { useRef, useState } from 'react';
|
||||
import { Alert, App, Button, Form, Input, Modal, Spin } from 'antd';
|
||||
import { SettingOutlined } from '@ant-design/icons';
|
||||
import { api } from './api';
|
||||
|
||||
export type AnalysisModelSettings = { baseUrl: string; model: string; hasApiKey: boolean; revision: string };
|
||||
export type AnalysisModelSettingsInput = { baseUrl: string; model: string; apiKey?: string; revision?: string };
|
||||
|
||||
export function AnalysisApiSettings({ onUnauthorized }: { onUnauthorized: (error: unknown) => boolean }) {
|
||||
const { message } = App.useApp();
|
||||
const [form] = Form.useForm<AnalysisModelSettingsInput>();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [testing, setTesting] = useState(false);
|
||||
const [settings, setSettings] = useState<AnalysisModelSettings>();
|
||||
const [notice, setNotice] = useState<{ type: 'success' | 'error'; text: string }>();
|
||||
const sequence = useRef(0);
|
||||
const close = () => { if (saving) return; sequence.current += 1; setOpen(false); form.resetFields(); setNotice(undefined); setTesting(false); };
|
||||
const load = async () => {
|
||||
const current = ++sequence.current;
|
||||
setOpen(true); setLoading(true); setSettings(undefined); setNotice(undefined); form.resetFields();
|
||||
try {
|
||||
const value = await api.analysisSettings();
|
||||
if (sequence.current !== current) return;
|
||||
setSettings(value); form.setFieldsValue({ baseUrl: value.baseUrl, model: value.model, apiKey: '' });
|
||||
} catch (error) {
|
||||
if (sequence.current === current && !onUnauthorized(error)) setNotice({ type: 'error', text: error instanceof Error ? error.message : '读取配置失败' });
|
||||
} finally { if (sequence.current === current) setLoading(false); }
|
||||
};
|
||||
const submit = async (test: boolean) => {
|
||||
if (!settings) return;
|
||||
let values: AnalysisModelSettingsInput;
|
||||
try { values = await form.validateFields(); } catch { return; }
|
||||
const current = sequence.current;
|
||||
setNotice(undefined); test ? setTesting(true) : setSaving(true);
|
||||
try {
|
||||
const body = { ...values, revision: settings.revision };
|
||||
if (test) {
|
||||
const result = await api.testAnalysisSettings(body);
|
||||
if (sequence.current === current) setNotice({ type: result.success ? 'success' : 'error', text: result.message });
|
||||
} else {
|
||||
const result = await api.saveAnalysisSettings(body);
|
||||
if (sequence.current !== current) return;
|
||||
setSettings(result); form.setFieldsValue({ apiKey: '' });
|
||||
setNotice({ type: 'success', text: '已保存,下一轮分析使用新配置。' }); message.success('API 配置已保存');
|
||||
}
|
||||
} catch (error) {
|
||||
if (sequence.current === current && !onUnauthorized(error)) setNotice({ type: 'error', text: error instanceof Error ? error.message : '操作失败,请重试' });
|
||||
} finally { if (sequence.current === current) { setTesting(false); setSaving(false); } }
|
||||
};
|
||||
return <>
|
||||
<Button type="text" size="small" icon={<SettingOutlined />} onClick={() => void load()}>API 配置</Button>
|
||||
<Modal title="API 配置" open={open} width={540} onCancel={close} footer={<>
|
||||
<Button onClick={close} disabled={saving}>关闭</Button>
|
||||
<Button loading={testing} disabled={loading || saving || !settings} onClick={() => void submit(true)}>测试连接</Button>
|
||||
<Button type="primary" loading={saving} disabled={loading || testing || !settings} onClick={() => void submit(false)}>保存配置</Button>
|
||||
</>}>
|
||||
{loading ? <div style={{ padding: 32, textAlign: 'center' }}><Spin /></div> : <>
|
||||
<Form form={form} layout="vertical" disabled={saving || testing} onValuesChange={() => setNotice(undefined)}>
|
||||
<Form.Item name="baseUrl" label="接口地址" rules={[{ required: true, whitespace: true, message: '请填写接口地址' }]} extra="支持 OpenAI 兼容接口,可填写含 /v1 的基础地址或完整的 /chat/completions 地址。"><Input placeholder="https://api.example.com/v1" autoComplete="off" maxLength={2048} /></Form.Item>
|
||||
<Form.Item name="apiKey" label="API Key" extra={settings?.hasApiKey ? '已配置密钥;留空保留。更换接口地址时需重新填写。' : '密钥仅保存在服务端,保存后不回显。'} rules={settings?.hasApiKey ? [] : [{ required: true, whitespace: true, message: '请填写 API Key' }]}><Input.Password placeholder={settings?.hasApiKey ? '已配置,留空保留' : '请输入 API Key'} autoComplete="new-password" maxLength={4096} /></Form.Item>
|
||||
<Form.Item name="model" label="模型名称" rules={[{ required: true, whitespace: true, message: '请填写模型名称' }]}><Input placeholder="例如 qwen3.8-27b-local" autoComplete="off" maxLength={160} /></Form.Item>
|
||||
</Form>
|
||||
{notice && <Alert showIcon type={notice.type} message={notice.text} />}
|
||||
{!settings && notice && <Button style={{ marginTop: 12 }} onClick={() => void load()}>重新读取</Button>}
|
||||
</>}
|
||||
</Modal>
|
||||
</>;
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
import { useMemo, useRef, useState } from 'react';
|
||||
import { Alert, App, Button, Modal } from 'antd';
|
||||
import { DownloadOutlined } from '@ant-design/icons';
|
||||
import { toPng } from 'html-to-image';
|
||||
import { AiMarkdown } from './AiMarkdown';
|
||||
import { analysisDisplayTextRemovalRanges, sanitizeAnalysisDisplayText } from './analysisDisplayText';
|
||||
|
||||
type Row = Record<string, unknown>;
|
||||
const record = (value: unknown): Row => value && typeof value === 'object' && !Array.isArray(value) ? value as Row : {};
|
||||
const rows = (value: unknown): Row[] => Array.isArray(value) ? value.map(record) : [];
|
||||
const text = (value: unknown) => value === null || value === undefined || value === '' ? '—' : String(value);
|
||||
const rate = (value: unknown) => typeof value === 'number' && Number.isFinite(value) ? `${(value * 100).toFixed(2)}%` : '—';
|
||||
const number = (value: unknown) => typeof value === 'number' && Number.isFinite(value) ? value.toLocaleString('zh-CN', { maximumFractionDigits: 2 }) : '—';
|
||||
const period = (value: unknown) => { const c = record(value); return c.year ? `${c.year}年${c.month ? `${c.month}月` : c.quarter ? `第${c.quarter}季度` : ''}` : ''; };
|
||||
const stageName = (value: unknown) => value === 'black' ? '黑片' : value === 'bright' ? '亮片' : '';
|
||||
const metricName = (value: unknown) => ({ BLACK_RATE: '黑片合格率', BRIGHT_RATE: '亮片合格率', COMPOSITE_RATE: '综合合格率', COMPOSITE_RATE_WITHOUT_HEADQUARTERS_SCRAP: '综合合格率(不含本部报废)', BRIGHT_RATE_WITHOUT_HEADQUARTERS_SCRAP: '亮片合格率(不含本部报废)' }[String(value)] || '合格率');
|
||||
const escape = (value: string) => value.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"');
|
||||
|
||||
const reportCss = `
|
||||
.q-report{box-sizing:border-box;width:900px;padding:52px;background:#fff;color:#202b3c;font:15px/1.85 -apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;overflow-wrap:anywhere}
|
||||
.q-report *{box-sizing:border-box}.q-report header{padding-bottom:26px;border-bottom:2px solid #355f9b}.q-report .q-eyebrow{font-size:12px;letter-spacing:2px;color:#53739c}.q-report h1{font-size:27px;line-height:1.5;margin:10px 0}.q-report .q-subtitle{font-size:12px;color:#69778b}.q-report h2{font-size:18px;margin:30px 0 12px}.q-report p{margin:10px 0}.q-report .q-prose{white-space:pre-wrap}.q-report .q-kpis{display:flex;gap:12px;margin:22px 0}.q-report .q-kpi{flex:1;padding:17px 18px;background:#f2f6fb;border-radius:6px}.q-report .q-kpi span{display:block;font-size:12px;color:#66778d}.q-report .q-kpi strong{display:block;font-size:27px;font-variant-numeric:tabular-nums;color:#254f87}.q-report table{width:100%;border-collapse:collapse;font-size:13px;table-layout:fixed}.q-report th{background:#f2f6fb;color:#53657c;text-align:left}.q-report th,.q-report td{padding:10px 12px;border-bottom:1px solid #e3e9f0;vertical-align:top}.q-report th:first-child,.q-report td:first-child{width:44%}.q-report .q-note{font-size:12px;color:#69778b}.q-report footer{margin-top:34px;padding-top:16px;border-top:1px solid #dde5ef;font-size:11px;color:#738197}.q-report .q-partial{color:#996b20}@media print{body{margin:0}.q-report{width:100%;padding:20px}tr{break-inside:avoid}}
|
||||
`;
|
||||
|
||||
function ReportDocument({ turn, stamp }: { turn: Row; stamp: string }) {
|
||||
const result = Object.keys(record(turn.result)).length ? record(turn.result) : turn;
|
||||
const results = rows(result.results || turn.results);
|
||||
const comparisons = results.filter(item => item.current && item.comparison && item.delta);
|
||||
const snapshots = results.filter(item => item.summary && item.context);
|
||||
const main = comparisons.length ? record(comparisons[0].current) : snapshots[0] || {};
|
||||
const summary = record(main.summary);
|
||||
const black = record(summary.black); const bright = record(summary.bright);
|
||||
const coverage = record(summary.coverage);
|
||||
const selectedMetric = String(comparisons[0]?.metric || record(record(result.task || turn.task).conditions).metricCode || 'COMPOSITE_RATE');
|
||||
const adjusted = selectedMetric.includes('WITHOUT_HEADQUARTERS_SCRAP');
|
||||
const answer = sanitizeAnalysisDisplayText(text(result.answer || turn.answer));
|
||||
const question = sanitizeAnalysisDisplayText(String(turn.question || '质量分析报告'));
|
||||
return <div className="q-report">
|
||||
<style>{reportCss}</style>
|
||||
<header><div className="q-eyebrow">质量中心 · 分析报告</div><h1>{question.length > 90 ? `${question.slice(0, 90)}…` : question}</h1><div className="q-subtitle">{period(main.context)}{period(main.context) ? ' · ' : ''}{stamp}</div></header>
|
||||
{String(turn.status || result.status) === 'PARTIAL' && <p className="q-partial">本次分析部分完成,以下保留已获得的结果。</p>}
|
||||
{Object.keys(summary).length > 0 && <div className="q-kpis">
|
||||
<div className="q-kpi"><span>{adjusted ? '综合合格率(不含本部报废)' : '综合合格率'}</span><strong>{coverage.blackRows === 0 || coverage.brightRows === 0 ? '—' : rate(adjusted ? summary.compositeRateWithoutHeadquartersScrap : summary.compositeRate)}</strong></div>
|
||||
<div className="q-kpi"><span>黑片合格率</span><strong>{coverage.blackRows === 0 ? '—' : rate(black.rate)}</strong></div>
|
||||
<div className="q-kpi"><span>{adjusted ? '亮片合格率(不含本部报废)' : '亮片合格率'}</span><strong>{coverage.brightRows === 0 ? '—' : rate(adjusted ? bright.rateWithoutHeadquartersScrap : bright.rate)}</strong></div>
|
||||
</div>}
|
||||
<section><h2>分析结论</h2><div className="q-prose">{answer}</div></section>
|
||||
{comparisons.map((item, index) => {
|
||||
const current = record(item.current), comparison = record(item.comparison), delta = record(item.delta), comparable = record(item.comparability);
|
||||
const value = (side: Row) => { const s = record(side.summary); switch (item.metric) { case 'BLACK_RATE': return rate(record(s.black).rate); case 'BRIGHT_RATE': return rate(record(s.bright).rate); case 'BRIGHT_RATE_WITHOUT_HEADQUARTERS_SCRAP': return rate(record(s.bright).rateWithoutHeadquartersScrap); case 'COMPOSITE_RATE_WITHOUT_HEADQUARTERS_SCRAP': return rate(s.compositeRateWithoutHeadquartersScrap); default: return rate(s.compositeRate); } };
|
||||
return <section key={`compare-${index}`}><h2>{metricName(item.metric)} · 期间比较</h2><table><thead><tr><th>期间</th><th>正式结果</th></tr></thead><tbody><tr><td>{period(current.context)}</td><td>{value(current)}</td></tr><tr><td>{period(comparison.context)}</td><td>{value(comparison)}</td></tr><tr><td>变化(百分点)</td><td>{number(delta.percentagePoints)}</td></tr></tbody></table>{comparable.comparable === false && <p className="q-note">{text(comparable.reason || (Array.isArray(comparable.reasons) ? comparable.reasons.join(';') : '所选期间不可比,不给出变化结论。'))}</p>}</section>;
|
||||
})}
|
||||
{results.filter(item => Array.isArray(item.groups)).map((item, index) => {
|
||||
const available = item.available === true;
|
||||
const ranked = [...rows(item.groups)].filter(row => typeof row[available ? 'impactPP' : 'scrapDelta'] === 'number').sort((a, b) => available ? Number(a.impactPP) - Number(b.impactPP) : Number(b.scrapDelta) - Number(a.scrapDelta)).slice(0, 10);
|
||||
if (!ranked.length) return null;
|
||||
return <section key={`impact-${index}`}><h2>{stageName(item.stage)} · 优先核查对象</h2><table><thead><tr><th>产品 / 规格</th><th>当前合格率</th><th>比较期合格率</th><th>{available ? '影响(百分点)' : '报废增量(kg)'}</th></tr></thead><tbody>{ranked.map((row, i) => <tr key={i}><td>{text(row.label || row.key)}</td><td>{rate(row.currentRate)}</td><td>{rate(row.comparisonRate)}</td><td>{number(available ? row.impactPP : row.scrapDelta)}</td></tr>)}</tbody></table>{!available && <p className="q-note">按报废增量列出前10项。分组无法完整回加,仅作核查线索,不能当作整体下降贡献。</p>}</section>;
|
||||
})}
|
||||
{results.filter(item => item.kind === 'analysis_statistics').map((item, index) => <section key={`trend-${index}`}><h2>{stageName(item.stage)} · 历史趋势</h2><table><thead><tr><th>期间</th><th>阶段合格率</th></tr></thead><tbody>{rows(item.trendChange).map((row, i) => <tr key={i}><td>{text(row.label || row.period)}</td><td>{rate(row.stageRate)}</td></tr>)}</tbody></table></section>)}
|
||||
{results.filter(item => Array.isArray(item.rows) && item.dimension && item.stage).map((item, index) => <section key={`top-${index}`}><h2>{stageName(item.stage)} · TOP核查对象</h2><table><thead><tr><th>对象</th><th>报废重量(kg)</th><th>占比</th></tr></thead><tbody>{rows(item.rows).slice(0, 10).map((row, i) => <tr key={i}><td>{text(row.label || row.key)}</td><td>{number(row.weight)}</td><td>{rate(row.share)}</td></tr>)}</tbody></table></section>)}
|
||||
<footer>数据来源:质量中心。指标沿用正式计算口径,原因判断的依据与局限见分析结论。</footer>
|
||||
</div>;
|
||||
}
|
||||
|
||||
function download(href: string, name: string) { const link = document.createElement('a'); link.href = href; link.download = name; link.click(); }
|
||||
|
||||
function removeDisplayMetadataFromElement(element: Element): void {
|
||||
const walker = element.ownerDocument.createTreeWalker(element, NodeFilter.SHOW_TEXT);
|
||||
const textNodes: Array<{ node: Text; start: number; end: number }> = [];
|
||||
let node: Node | null;
|
||||
let offset = 0;
|
||||
while ((node = walker.nextNode())) {
|
||||
const textNode = node as Text;
|
||||
const start = offset;
|
||||
offset += textNode.data.length;
|
||||
textNodes.push({ node: textNode, start, end: offset });
|
||||
}
|
||||
|
||||
const ranges = analysisDisplayTextRemovalRanges(textNodes.map(item => item.node.data).join(''));
|
||||
for (const range of [...ranges].reverse()) {
|
||||
for (const item of [...textNodes].reverse()) {
|
||||
const overlapStart = Math.max(range.start, item.start);
|
||||
const overlapEnd = Math.min(range.end, item.end);
|
||||
if (overlapStart >= overlapEnd) continue;
|
||||
const localStart = overlapStart - item.start;
|
||||
const localEnd = overlapEnd - item.start;
|
||||
item.node.data = item.node.data.slice(0, localStart) + item.node.data.slice(localEnd);
|
||||
}
|
||||
}
|
||||
|
||||
// Inline labels whose values were removed can otherwise leave empty bold/code wrappers.
|
||||
element.querySelectorAll('strong,b,em,i,code,span').forEach(child => {
|
||||
if (!child.textContent?.trim() && !child.querySelector('img,svg')) child.remove();
|
||||
});
|
||||
}
|
||||
|
||||
function safeNativeHtml(source: string): string {
|
||||
const parsed = new DOMParser().parseFromString(source, 'text/html');
|
||||
parsed.querySelectorAll('script,iframe,object,embed,base,form,link,video,audio,source,track').forEach(element => element.remove());
|
||||
parsed.querySelectorAll('meta[http-equiv]').forEach(meta => {
|
||||
const directive = (meta.getAttribute('http-equiv') || '').trim().toLowerCase();
|
||||
if (directive === 'content-security-policy' || directive === 'refresh') meta.remove();
|
||||
});
|
||||
|
||||
const safeRasterData = (value: string) => /^data:image\/(?:png|jpe?g|gif|webp);base64,/i.test(value.trim());
|
||||
const safeFontData = (value: string) => /^data:(?:font\/(?:woff2?|ttf|otf)|application\/(?:font-woff|vnd\.ms-fontobject|x-font-(?:ttf|otf)));base64,/i.test(value.trim());
|
||||
const safeCss = (value: string) => value
|
||||
.replace(/@import\s+(?:url\([^)]*\)|[^;]+);?/gi, '')
|
||||
.replace(/url\(\s*(['"]?)(.*?)\1\s*\)/gi, (whole, _quote: string, raw: string) => {
|
||||
const url = String(raw).trim();
|
||||
return url.startsWith('#') || safeRasterData(url) || safeFontData(url) ? whole : 'none';
|
||||
});
|
||||
|
||||
parsed.querySelectorAll('*').forEach(element => {
|
||||
for (const attribute of [...element.attributes]) {
|
||||
const name = attribute.name.toLowerCase();
|
||||
const value = sanitizeAnalysisDisplayText(attribute.value.trim());
|
||||
const tagName = element.tagName.toLowerCase();
|
||||
if (/^(?:data-)?(?:release[-_]?id|story[-_]?(?:id|slug|version)|version[-_]?(?:id|no|number))$/i.test(name)) {
|
||||
element.removeAttribute(attribute.name);
|
||||
continue;
|
||||
}
|
||||
const autoResource = ['src', 'srcset', 'poster'].includes(name)
|
||||
|| (['href', 'xlink:href'].includes(name) && ['image', 'use', 'feimage'].includes(tagName));
|
||||
const safeReference = value.startsWith('#') || (['src', 'href', 'xlink:href'].includes(name) && safeRasterData(value));
|
||||
if (name.startsWith('on') || name === 'srcdoc' || /^(?:javascript\s*:|data\s*:\s*text\/html)/i.test(value) || (autoResource && !safeReference)) {
|
||||
element.removeAttribute(attribute.name);
|
||||
} else if (name === 'style') {
|
||||
element.setAttribute(attribute.name, safeCss(value));
|
||||
} else if (value !== attribute.value) {
|
||||
element.setAttribute(attribute.name, value);
|
||||
}
|
||||
}
|
||||
});
|
||||
parsed.querySelectorAll('style').forEach(style => { style.textContent = safeCss(style.textContent || ''); });
|
||||
parsed.querySelectorAll('meta[name],meta[property]').forEach(meta => {
|
||||
const key = `${meta.getAttribute('name') || ''} ${meta.getAttribute('property') || ''}`;
|
||||
if (/release|story|version/i.test(key)) meta.remove();
|
||||
});
|
||||
parsed.querySelectorAll('blockquote').forEach(element => {
|
||||
if (/^v\d+(?:\.\d+)*\s*复核说明\s*[::]?/i.test(element.textContent?.trim() || '')) element.remove();
|
||||
});
|
||||
parsed.querySelectorAll('p,h1,h2,h3,h4,h5,h6,li,td,th,caption,figcaption,title').forEach(removeDisplayMetadataFromElement);
|
||||
const walker = parsed.createTreeWalker(parsed.body, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_COMMENT);
|
||||
let node: Node | null;
|
||||
while ((node = walker.nextNode())) {
|
||||
if (node.nodeType === Node.COMMENT_NODE) node.parentNode?.removeChild(node);
|
||||
else if (node.nodeValue) node.nodeValue = sanitizeAnalysisDisplayText(node.nodeValue);
|
||||
}
|
||||
parsed.title = sanitizeAnalysisDisplayText(parsed.title);
|
||||
|
||||
const policy = parsed.createElement('meta');
|
||||
policy.setAttribute('http-equiv', 'Content-Security-Policy');
|
||||
policy.setAttribute('content', "default-src 'none'; script-src 'none'; style-src 'unsafe-inline'; img-src data:; font-src data:; connect-src 'none'; media-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'");
|
||||
parsed.head.prepend(policy);
|
||||
const exportStyle = parsed.createElement('style');
|
||||
exportStyle.setAttribute('data-report-export-layout', '');
|
||||
exportStyle.textContent = 'html,body{box-sizing:border-box;width:900px!important;min-width:900px!important;max-width:900px!important;margin:0!important;overflow-wrap:anywhere}*,*:before,*:after{box-sizing:border-box}';
|
||||
parsed.head.append(exportStyle);
|
||||
return `<!doctype html>\n${parsed.documentElement.outerHTML}`;
|
||||
}
|
||||
|
||||
function frameContentHeight(doc: Document): number {
|
||||
return Math.ceil(Math.max(
|
||||
doc.body.scrollHeight,
|
||||
doc.body.offsetHeight,
|
||||
doc.body.getBoundingClientRect().height,
|
||||
doc.documentElement.scrollHeight,
|
||||
doc.documentElement.offsetHeight,
|
||||
doc.documentElement.getBoundingClientRect().height,
|
||||
));
|
||||
}
|
||||
|
||||
function frameFontCss(doc: Document): string {
|
||||
const fontRules: string[] = [];
|
||||
const collect = (rules: CSSRuleList) => {
|
||||
for (const rule of Array.from(rules)) {
|
||||
if (rule.type === CSSRule.FONT_FACE_RULE) fontRules.push(rule.cssText);
|
||||
const nested = (rule as CSSGroupingRule).cssRules;
|
||||
if (nested) collect(nested);
|
||||
}
|
||||
};
|
||||
for (const sheet of Array.from(doc.styleSheets)) {
|
||||
try { collect(sheet.cssRules); } catch { /* External style sheets are removed before rendering. */ }
|
||||
}
|
||||
return fontRules.join('\n');
|
||||
}
|
||||
|
||||
export function AnalysisReportExport({ turn }: { turn: Row }) {
|
||||
const { message } = App.useApp();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [exporting, setExporting] = useState(false);
|
||||
const [stamp, setStamp] = useState('');
|
||||
const node = useRef<HTMLDivElement>(null);
|
||||
const title = String(turn.question || '质量分析报告').replace(/[\\/:*?"<>|\n\r]/g, '').slice(0, 60);
|
||||
const saveHtml = () => {
|
||||
if (!node.current) return;
|
||||
const html = `<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; img-src data:"><title>${escape(title)}</title><style>body{margin:0;background:#edf1f5}.q-report{margin:0 auto}</style></head><body>${node.current.innerHTML}</body></html>`;
|
||||
const url = URL.createObjectURL(new Blob([html], { type: 'text/html;charset=utf-8' }));
|
||||
download(url, `${title}.html`); setTimeout(() => URL.revokeObjectURL(url), 10000);
|
||||
};
|
||||
const saveImage = async () => {
|
||||
const report = node.current?.querySelector<HTMLElement>('.q-report');
|
||||
if (!report) return;
|
||||
setExporting(true);
|
||||
try {
|
||||
await document.fonts.ready;
|
||||
const png = await toPng(report, { pixelRatio: 2, backgroundColor: '#ffffff', skipFonts: true });
|
||||
download(png, `${title}.png`);
|
||||
message.success('报告图片已生成');
|
||||
} catch { message.error('图片生成失败,请重试或下载 HTML 报告。'); }
|
||||
finally { setExporting(false); }
|
||||
};
|
||||
return <>
|
||||
<Button type="text" size="small" icon={<DownloadOutlined />} onClick={() => { setStamp(new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false })); setOpen(true); }}>生成报告</Button>
|
||||
<Modal title="分析报告" open={open} onCancel={() => { if (!exporting) setOpen(false); }} width={980} footer={<><Button disabled={exporting} onClick={saveHtml}>下载 HTML</Button><Button type="primary" loading={exporting} onClick={() => void saveImage()}>下载图片</Button></>}>
|
||||
<div className="analysis-report-preview" ref={node}><ReportDocument turn={turn} stamp={stamp} /></div>
|
||||
</Modal>
|
||||
</>;
|
||||
}
|
||||
|
||||
export function NativeAnalysisReport({ turn, reportMarkdown, reportHtml }: {
|
||||
turn: Row;
|
||||
reportMarkdown: string;
|
||||
reportHtml?: string;
|
||||
}) {
|
||||
const { message } = App.useApp();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [exporting, setExporting] = useState(false);
|
||||
const [frameHeight, setFrameHeight] = useState(1);
|
||||
const [frameReady, setFrameReady] = useState(false);
|
||||
const iframe = useRef<HTMLIFrameElement>(null);
|
||||
const fallbackNode = useRef<HTMLElement>(null);
|
||||
const safeHtml = useMemo(() => reportHtml?.trim() ? safeNativeHtml(reportHtml) : '', [reportHtml]);
|
||||
const title = useMemo(() => {
|
||||
const nativeTitle = safeHtml ? new DOMParser().parseFromString(safeHtml, 'text/html').title : '';
|
||||
const heading = reportMarkdown.match(/^#\s+(.+)$/m)?.[1];
|
||||
return String(nativeTitle || heading || turn.question || '质量分析报告').replace(/[\\/:*?"<>|\n\r]/g, '').slice(0, 60) || '质量分析报告';
|
||||
}, [safeHtml, reportMarkdown, turn.question]);
|
||||
|
||||
const saveHtml = () => {
|
||||
if (!safeHtml) return;
|
||||
const url = URL.createObjectURL(new Blob([safeHtml], { type: 'text/html;charset=utf-8' }));
|
||||
download(url, `${title}.html`);
|
||||
setTimeout(() => URL.revokeObjectURL(url), 10000);
|
||||
};
|
||||
|
||||
const handleFrameLoad = () => {
|
||||
const doc = iframe.current?.contentDocument;
|
||||
if (!doc?.body) return;
|
||||
setFrameReady(false);
|
||||
void doc.fonts?.ready.then(() => requestAnimationFrame(() => {
|
||||
const height = frameContentHeight(doc);
|
||||
setFrameHeight(Math.max(height, 1));
|
||||
setFrameReady(true);
|
||||
}));
|
||||
};
|
||||
|
||||
const saveImage = async () => {
|
||||
setExporting(true);
|
||||
try {
|
||||
let png: string;
|
||||
if (safeHtml) {
|
||||
const doc = iframe.current?.contentDocument;
|
||||
if (!doc?.body) throw new Error('原生报告尚未载入');
|
||||
await doc.fonts?.ready;
|
||||
await new Promise<void>(resolve => requestAnimationFrame(() => resolve()));
|
||||
const height = Math.max(frameContentHeight(doc), frameHeight);
|
||||
png = await toPng(doc.body, { width: 900, height, pixelRatio: 1, backgroundColor: '#ffffff', fontEmbedCSS: frameFontCss(doc) });
|
||||
} else {
|
||||
const report = fallbackNode.current;
|
||||
if (!report) throw new Error('Markdown 报告尚未载入');
|
||||
await document.fonts.ready;
|
||||
const height = Math.max(report.scrollHeight, report.offsetHeight);
|
||||
png = await toPng(report, { width: 900, height, pixelRatio: 1, backgroundColor: '#ffffff', skipFonts: true });
|
||||
}
|
||||
download(png, `${title}.png`);
|
||||
message.success('报告图片已生成');
|
||||
} catch {
|
||||
message.error('图片生成失败,请重试。');
|
||||
} finally {
|
||||
setExporting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return <>
|
||||
<Button type="text" size="small" icon={<DownloadOutlined />} onClick={() => setOpen(true)}>查看报告</Button>
|
||||
<Modal title="分析报告" open={open} onCancel={() => { if (!exporting) setOpen(false); }} width={980} footer={<>
|
||||
<Button disabled={exporting || !safeHtml} onClick={saveHtml}>下载 HTML</Button>
|
||||
<Button type="primary" loading={exporting} disabled={Boolean(safeHtml) && !frameReady} onClick={() => void saveImage()}>下载图片</Button>
|
||||
</>}>
|
||||
{!safeHtml && <Alert type="info" showIcon message="未提供原生 HTML" description="当前预览和 PNG 使用 Markdown 报告内容。" />}
|
||||
<div className="analysis-report-preview">
|
||||
{safeHtml
|
||||
? <iframe ref={iframe} className="native-analysis-report-frame" title="原生分析报告预览" sandbox="allow-same-origin" srcDoc={safeHtml} width={900} height={frameHeight} onLoad={handleFrameLoad} />
|
||||
: <article className="native-analysis-report" ref={fallbackNode}><AiMarkdown content={reportMarkdown} /></article>}
|
||||
</div>
|
||||
</Modal>
|
||||
</>;
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Alert, Button, Select, Switch, Tag } from 'antd';
|
||||
import { api } from './api';
|
||||
|
||||
const labels: Record<string, string> = { MONTH: '月报', QUARTER: '季报', YEAR: '年报' };
|
||||
export function AnalysisReportsPanel({ periodType, periodKey, disabled, onOpen }: {
|
||||
periodType: string; periodKey: string; disabled: boolean; onOpen: (sessionId: string, turnId: string) => void;
|
||||
}) {
|
||||
const [reports, setReports] = useState<Record<string, unknown>[]>([]);
|
||||
const [plans, setPlans] = useState<Record<string, unknown>[]>([]);
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [runDay, setRunDay] = useState(1);
|
||||
const load = async () => {
|
||||
try {
|
||||
const [history, savedPlans] = await Promise.all([api.analysisReports(), api.analysisReportPlans()]);
|
||||
setReports(history.items || []); setPlans(savedPlans.items || []);
|
||||
} catch (value) { setError(value instanceof Error ? value.message : '报告读取失败'); }
|
||||
};
|
||||
useEffect(() => { void load(); }, []);
|
||||
const generate = async () => {
|
||||
setBusy(true); setError('');
|
||||
try {
|
||||
const response = await api.createAnalysisReport({ periodType, periodKey });
|
||||
await load();
|
||||
const { sessionId, turnId } = response.report;
|
||||
if (typeof sessionId === 'string' && typeof turnId === 'string') onOpen(sessionId, turnId);
|
||||
else setError('报告已登记,正在准备分析任务,请稍后刷新列表。');
|
||||
} catch (value) { setError(value instanceof Error ? value.message : '报告生成失败'); }
|
||||
finally { setBusy(false); }
|
||||
};
|
||||
const toggle = async (type: string, enabled: boolean) => {
|
||||
setBusy(true); setError('');
|
||||
try {
|
||||
const found = plans.find(plan => plan.periodType === type || plan.reportType === type);
|
||||
const body = { periodType: type, enabled, runDay, runHour: 9 };
|
||||
if (found) await api.updateAnalysisReportPlan(String(found.id), body);
|
||||
else await api.createAnalysisReportPlan(body);
|
||||
await load();
|
||||
} catch (value) { setError(value instanceof Error ? value.message : '报告计划保存失败'); }
|
||||
finally { setBusy(false); }
|
||||
};
|
||||
const saveDay = async () => {
|
||||
setBusy(true); setError('');
|
||||
try {
|
||||
await Promise.all(plans.map(plan => api.updateAnalysisReportPlan(String(plan.id), { runDay, runHour: 9 })));
|
||||
await load();
|
||||
} catch (value) { setError(value instanceof Error ? value.message : '执行日期保存失败'); }
|
||||
finally { setBusy(false); }
|
||||
};
|
||||
return <details className="analysis-reports"><summary>月报、季报与年报</summary>
|
||||
<p>报告使用统一指标与同一分析任务,包含期间比较、趋势和异常追查。自动计划在本机服务运行时执行。</p>
|
||||
{error && <Alert type="warning" showIcon message={error} />}
|
||||
<div className="ai-actions"><span>{periodKey} · {labels[periodType]} · 总体范围</span><Button disabled={disabled || busy} loading={busy} onClick={() => void generate()}>生成本期{labels[periodType]}</Button><Button disabled={busy} onClick={() => void load()}>刷新报告</Button></div>
|
||||
<div className="analysis-report-plans"><span>自动生成上一完整周期:每个适用周期首月</span><Select aria-label="自动报告执行日" value={runDay} onChange={setRunDay} options={Array.from({ length: 28 }, (_, i) => ({ label: `${i + 1}日 09:00`, value: i + 1 }))} />
|
||||
{Object.entries(labels).map(([type, label]) => { const plan = plans.find(item => item.periodType === type || item.reportType === type); return <label key={type}>{label} <Switch aria-label={`自动${label}`} disabled={busy} checked={plan?.enabled === true} onChange={value => void toggle(type, value)} /></label>; })}
|
||||
<Button size="small" disabled={busy || !plans.length} onClick={() => void saveDay()}>保存执行日期</Button>
|
||||
</div>
|
||||
{reports.length > 0 && <ul>{reports.slice(0, 8).map(report => <li key={String(report.id)}><span>{String(report.periodKey)} {labels[String(report.periodType)] || ''}</span> <Tag>{String(report.status)}</Tag><Button type="link" disabled={disabled || !report.sessionId || !report.turnId} onClick={() => onOpen(String(report.sessionId), String(report.turnId))}>查看分析</Button></li>)}</ul>}
|
||||
</details>;
|
||||
}
|
||||
@@ -0,0 +1,774 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import {
|
||||
Alert, App, Button, Empty, Form, Input, InputNumber, Modal, Popconfirm,
|
||||
Select, Segmented, Spin, Table, Tag,
|
||||
} from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import { DeleteOutlined, PlusOutlined, ReloadOutlined, SaveOutlined } from '@ant-design/icons';
|
||||
import { ApiError, api, collectionItems } from './api';
|
||||
import type { QueryParams, Stage, ViewKind } from './types';
|
||||
import { readableSelectPopup } from './readableSelectPopup';
|
||||
import './completion.css';
|
||||
|
||||
type Row = Record<string, unknown>;
|
||||
const TABLE_PAGE_SIZE = 20;
|
||||
|
||||
function text(value: unknown, empty = '—'): string {
|
||||
if (value === null || value === undefined || value === '') return empty;
|
||||
return typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' ? String(value) : empty;
|
||||
}
|
||||
|
||||
function record(value: unknown): Row {
|
||||
return value && typeof value === 'object' && !Array.isArray(value) ? value as Row : {};
|
||||
}
|
||||
|
||||
function list(value: unknown): Row[] {
|
||||
return Array.isArray(value) ? value.filter(item => item && typeof item === 'object') as Row[] : [];
|
||||
}
|
||||
|
||||
function listOfNames(value: unknown): string[] {
|
||||
return Array.isArray(value) ? value.map(item => String(item || '').trim()).filter(Boolean) : [];
|
||||
}
|
||||
|
||||
function pct(value: unknown): string {
|
||||
return typeof value === 'number' && Number.isFinite(value) ? `${(value * 100).toFixed(2)}%` : '—';
|
||||
}
|
||||
|
||||
function pp(value: unknown): string {
|
||||
return typeof value === 'number' && Number.isFinite(value) ? `${value > 0 ? '+' : ''}${value.toFixed(2)} 个百分点` : '—';
|
||||
}
|
||||
|
||||
function objectContext(params: QueryParams): Row {
|
||||
const { view: _view, ...context } = params;
|
||||
return context as Row;
|
||||
}
|
||||
|
||||
function savedViewContext(params: QueryParams): Row {
|
||||
const context = objectContext(params);
|
||||
delete context.releaseId;
|
||||
return context;
|
||||
}
|
||||
|
||||
function previousPeriod(params: QueryParams): { year: number; month?: number; quarter?: number } {
|
||||
if (params.month) return params.month === 1 ? { year: params.year - 1, month: 12 } : { year: params.year, month: params.month - 1 };
|
||||
if (params.quarter) return params.quarter === 1 ? { year: params.year - 1, quarter: 4 } : { year: params.year, quarter: params.quarter - 1 };
|
||||
return { year: params.year - 1 };
|
||||
}
|
||||
|
||||
function samePeriodLastYear(params: QueryParams): { year: number; month?: number; quarter?: number } {
|
||||
return { year: params.year - 1, ...(params.month ? { month: params.month } : {}), ...(params.quarter ? { quarter: params.quarter } : {}) };
|
||||
}
|
||||
|
||||
function comparisonBody(current: QueryParams, comparisonPeriod: { year: number; month?: number; quarter?: number }, metric = 'compositeRate') {
|
||||
const filters = objectContext(current);
|
||||
delete filters.year; delete filters.month; delete filters.quarter; delete filters.releaseId; delete filters.view;
|
||||
const comparisonFilters = { ...filters };
|
||||
return {
|
||||
metric,
|
||||
current: { ...filters, ...(current.releaseId ? { releaseId: current.releaseId } : {}), year: current.year, ...(current.month ? { month: current.month } : {}), ...(current.quarter ? { quarter: current.quarter } : {}) },
|
||||
comparison: { ...comparisonFilters, ...(current.releaseId ? { releaseId: current.releaseId } : {}), ...comparisonPeriod },
|
||||
};
|
||||
}
|
||||
|
||||
function SnapshotRates({ label, value }: { label: string; value: unknown }) {
|
||||
const snapshot = record(value);
|
||||
const summary = record(snapshot.summary);
|
||||
const coverage = record(summary.coverage);
|
||||
const hasBlack = Number(coverage.blackRows || 0) > 0;
|
||||
const hasBright = Number(coverage.brightRows || 0) > 0;
|
||||
return <div className="completion-snapshot">
|
||||
<strong>{label}</strong>
|
||||
<dl>
|
||||
<dt>综合合格率</dt><dd>{hasBlack && hasBright ? pct(summary.compositeRate) : '—'}</dd>
|
||||
<dt>黑片合格率</dt><dd>{hasBlack ? pct(record(summary.black).rate) : '—'}</dd>
|
||||
<dt>亮片合格率</dt><dd>{hasBright ? pct(record(summary.bright).rate) : '—'}</dd>
|
||||
<dt>覆盖行数</dt><dd>黑 {text(coverage.blackRows, text(record(snapshot.coverage).blackRows, '0'))} · 亮 {text(coverage.brightRows, text(record(snapshot.coverage).brightRows, '0'))}</dd>
|
||||
</dl>
|
||||
</div>;
|
||||
}
|
||||
|
||||
function SharedQueryConditions({ label, value }: { label: string; value: unknown }) {
|
||||
const context = record(record(value).context);
|
||||
const periods = [
|
||||
...(context.year ? [text(context.year)] : []),
|
||||
...(context.quarter ? [`第${text(context.quarter)}季度`] : []),
|
||||
...(context.month ? [`${text(context.month)}月`] : []),
|
||||
];
|
||||
const dimensions: Array<[string, unknown]> = [
|
||||
['部门', context.department], ['分组', context.group], ['产品', context.product], ['项目组', context.projectGroup],
|
||||
];
|
||||
const conditions = [
|
||||
...(periods.length ? [`期间 ${periods.join(' ')}`] : []),
|
||||
...dimensions.filter(([, value]) => value !== null && value !== undefined && value !== '').map(([name, value]) => `${name} ${text(value)}`),
|
||||
...(context.view ? [`维度 ${({ overall: '总体', department: '部门', group: '分组', product: '产品', projectGroup: '项目组' } as Record<string, string>)[String(context.view)] || text(context.view)}`] : []),
|
||||
...(typeof context.includeUnassigned === 'boolean' ? [`未分配记录 ${context.includeUnassigned ? '包含' : '排除'}`] : []),
|
||||
];
|
||||
return conditions.length ? <p className="completion-note">{label}:{conditions.join(' · ')}</p> : null;
|
||||
}
|
||||
|
||||
export function M01Insights({ query, onUnauthorized }: { query: QueryParams; onUnauthorized: (error: unknown) => boolean }) {
|
||||
const [target, setTarget] = useState<Row | null>(null);
|
||||
const [targetError, setTargetError] = useState('');
|
||||
const [compare, setCompare] = useState<Row | null>(null);
|
||||
const [compareError, setCompareError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [compareMode, setCompareMode] = useState<'previous' | 'yearOverYear'>('previous');
|
||||
const prior = useMemo(() => compareMode === 'yearOverYear' ? samePeriodLastYear(query) : previousPeriod(query), [query.year, query.month, query.quarter, compareMode]);
|
||||
const contextKey = JSON.stringify(query);
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
setTargetError('');
|
||||
api.analyticsTarget({ ...objectContext(query), metric: 'COMPOSITE_RATE' }).then(value => {
|
||||
if (alive) { setTarget(value); setTargetError(''); }
|
||||
}).catch(error => { if (alive && !onUnauthorized(error)) setTargetError(error instanceof Error ? error.message : '目标状态读取失败'); });
|
||||
return () => { alive = false; };
|
||||
}, [contextKey, onUnauthorized]);
|
||||
|
||||
useEffect(() => { setCompare(null); setCompareError(''); }, [contextKey, compareMode]);
|
||||
|
||||
const runCompare = async () => {
|
||||
setBusy(true); setCompareError('');
|
||||
try { setCompare(await api.analyticsCompare(comparisonBody(query, prior))); }
|
||||
catch (error) { if (!onUnauthorized(error)) setCompareError(error instanceof Error ? error.message : '比较查询失败'); }
|
||||
finally { setBusy(false); }
|
||||
};
|
||||
const refreshAll = async () => {
|
||||
setBusy(true); setTargetError(''); setCompareError('');
|
||||
const [targetResult, compareResult] = await Promise.allSettled([
|
||||
api.analyticsTarget({ ...objectContext(query), metric: 'COMPOSITE_RATE' }),
|
||||
api.analyticsCompare(comparisonBody(query, prior)),
|
||||
]);
|
||||
if (targetResult.status === 'fulfilled') setTarget(targetResult.value);
|
||||
else if (!onUnauthorized(targetResult.reason)) setTargetError(targetResult.reason instanceof Error ? targetResult.reason.message : '目标状态读取失败');
|
||||
if (compareResult.status === 'fulfilled') setCompare(compareResult.value);
|
||||
else if (!onUnauthorized(compareResult.reason)) setCompareError(compareResult.reason instanceof Error ? compareResult.reason.message : '比较查询失败');
|
||||
setBusy(false);
|
||||
};
|
||||
const targetBody = record(target);
|
||||
const targetValue = record(targetBody.target);
|
||||
const comparison = record(compare);
|
||||
const targetState = text(targetBody.status, '未返回');
|
||||
const configuredTarget = typeof targetValue.value === 'number' ? targetValue.value : targetValue.targetRate;
|
||||
const configured = targetState === 'CONFIGURED' && typeof configuredTarget === 'number';
|
||||
const delta = record(comparison.delta);
|
||||
const legacyDelta = record(comparison.deltaPP);
|
||||
const percentagePoints = delta.percentagePoints ?? legacyDelta.composite ?? legacyDelta.compositeRate;
|
||||
const contributions = record(comparison.contributions);
|
||||
const blackContribution = contributions.black ?? contributions.blackPP;
|
||||
const brightContribution = contributions.bright ?? contributions.brightPP;
|
||||
const unexplainedContribution = contributions.unexplained ?? contributions.unexplainedPP ?? contributions.roundingResidualPP ?? contributions.residualPP;
|
||||
const compareTarget = record(record(comparison.targets || comparison.target).comparison);
|
||||
const compareTargetValue = record(compareTarget.target);
|
||||
const comparability = record(comparison.comparability);
|
||||
const comparable = comparison.coverageComparable === true || (comparability.comparable === true && comparability.coverageAligned !== false);
|
||||
const comparisonReason = Array.isArray(comparability.reasons)
|
||||
? (comparability.reasons as unknown[]).map(String).join(';') || text(comparability.coverageNotice, '规则口径与覆盖可比性由服务端返回')
|
||||
: text(comparability.reason || comparability.coverageNotice, '规则口径与覆盖可比性由服务端返回');
|
||||
|
||||
return <section className="panel section-panel completion-insights" aria-label="目标与期间比较">
|
||||
<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>
|
||||
{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>}</>}
|
||||
</div>
|
||||
<div className="completion-insight-card completion-compare-card">
|
||||
<div className="completion-card-heading"><strong>{compareMode === 'yearOverYear' && (query.month || query.quarter) ? '与上年同期比较' : '与上一期间比较'}</strong><div className="completion-compare-controls">
|
||||
<Segmented size="small" value={compareMode} options={[{ label: '上一期间', value: 'previous' }, { label: '上年同期', value: 'yearOverYear' }]} onChange={value => { setCompareMode(value as 'previous' | 'yearOverYear'); setCompare(null); }} aria-label="比较期间类型" />
|
||||
<Button type="primary" loading={busy} onClick={() => void runCompare()}>开始比较</Button>
|
||||
</div></div>
|
||||
<p className="completion-note">比较期:{prior.year}年{prior.month ? ` ${prior.month}月` : prior.quarter ? ` 第${prior.quarter}季度` : '度'} · 规则口径与覆盖状态由服务端核对</p>
|
||||
{compareError && <Alert showIcon type="error" message="比较失败" description={compareError} />}
|
||||
{compare && <>
|
||||
<div className="completion-compare-snapshots"><SnapshotRates label="当前期间" value={comparison.current} /><SnapshotRates label="比较期间" value={comparison.comparison} /></div>
|
||||
<div className="completion-delta-grid">
|
||||
<span><small>综合变化</small><strong>{pp(percentagePoints)}</strong></span>
|
||||
<span><small>黑片贡献</small><strong>{pp(blackContribution)}</strong></span>
|
||||
<span><small>亮片贡献</small><strong>{pp(brightContribution)}</strong></span>
|
||||
</div>
|
||||
<div className="completion-evidence-line"><Tag color={comparable ? 'green' : 'gold'}>{comparable ? '口径可比' : '需谨慎解释'}</Tag><span>{comparisonReason}</span><span>贡献未解释 {pp(unexplainedContribution)}</span></div>
|
||||
{compareTarget.status && <p className="completion-note">比较期目标:{text(compareTarget.status)}{typeof compareTargetValue.value === 'number' ? ` · ${pct(compareTargetValue.value)}` : ''}{compareTarget.deltaPercentagePoints !== undefined ? ` · 目标差 ${pp(compareTarget.deltaPercentagePoints)}` : ''}</p>}
|
||||
</>}
|
||||
{!compare && !compareError && <div className="completion-placeholder">选择比较期间类型后运行,系统将并列显示期间结果、覆盖和可比性。</div>}
|
||||
</div>
|
||||
</div>
|
||||
</section>;
|
||||
}
|
||||
|
||||
export function M02SavedViews({ query, view, onUnauthorized, onApply }: { query: QueryParams; view: ViewKind; onUnauthorized: (error: unknown) => boolean; onApply: (context: Partial<QueryParams>) => void }) {
|
||||
const { message } = App.useApp();
|
||||
const [items, setItems] = useState<Row[]>([]);
|
||||
const [sharedItems, setSharedItems] = useState<Row[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
const [busyId, setBusyId] = useState('');
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [shareItem, setShareItem] = useState<Row | null>(null);
|
||||
const [shareCandidates, setShareCandidates] = useState<Row[]>([]);
|
||||
const [shareRows, setShareRows] = useState<Row[]>([]);
|
||||
const [shareRecipient, setShareRecipient] = useState<string>();
|
||||
const [shareRowVersion, setShareRowVersion] = useState(0);
|
||||
const [shareLoading, setShareLoading] = useState(false);
|
||||
const [sharedPreview, setSharedPreview] = useState<Row | null>(null);
|
||||
const [form] = Form.useForm<{ name: string }>();
|
||||
const load = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [mine, shared] = await Promise.all([api.comparisonViews(), api.sharedComparisonViews()]);
|
||||
setItems(collectionItems(mine)); setSharedItems(collectionItems(shared)); setError('');
|
||||
}
|
||||
catch (value) { if (!onUnauthorized(value)) setError(value instanceof Error ? value.message : '比较视图读取失败'); }
|
||||
finally { setLoading(false); }
|
||||
};
|
||||
useEffect(() => { void load(); }, []);
|
||||
const refreshShareInfo = async (item: Row) => {
|
||||
const id = String(item.id || ''); if (!id) return;
|
||||
const [candidates, shares] = await Promise.all([api.comparisonViewShareCandidates(), api.comparisonViewShares(id)]);
|
||||
setShareCandidates(collectionItems(candidates)); setShareRows(collectionItems(shares));
|
||||
setShareRowVersion(Number(shares.viewRowVersion ?? item.rowVersion ?? 0));
|
||||
};
|
||||
const save = async () => {
|
||||
try {
|
||||
const values = await form.validateFields();
|
||||
await api.createComparisonView({ name: values.name.trim(), context: savedViewContext(query), groupBy: view, columns: ['compositeRate', 'black', 'bright'], releaseMode: 'CURRENT' });
|
||||
message.success('个人比较视图已保存'); setModalOpen(false); form.resetFields(); await load();
|
||||
} catch (value) { if (value && typeof value === 'object' && 'errorFields' in value) return; if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '保存失败'); }
|
||||
};
|
||||
const manageShares = async (item: Row) => {
|
||||
setShareItem(item); setShareRecipient(undefined); setShareRows([]); setShareLoading(true);
|
||||
try { await refreshShareInfo(item); setModalOpen(false); }
|
||||
catch (value) { if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '读取共享对象失败'); setShareItem(null); }
|
||||
finally { setShareLoading(false); }
|
||||
};
|
||||
const addShare = async () => {
|
||||
const id = String(shareItem?.id || ''); if (!id || !shareRecipient) return;
|
||||
setBusyId(id); setShareLoading(true);
|
||||
try {
|
||||
await api.shareComparisonView(id, { recipientUserId: shareRecipient, expectedRowVersion: shareRowVersion });
|
||||
message.success('已共享给所选用户'); setShareRecipient(undefined);
|
||||
await refreshShareInfo(shareItem!); await load();
|
||||
} catch (value) { if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '共享失败'); }
|
||||
finally { setBusyId(''); setShareLoading(false); }
|
||||
};
|
||||
const revokeShare = async (row: Row) => {
|
||||
const id = String(shareItem?.id || ''); const recipientId = String(row.recipientUserId || '');
|
||||
if (!id || !recipientId) return;
|
||||
setBusyId(`${id}:${recipientId}`); setShareLoading(true);
|
||||
try {
|
||||
await api.revokeComparisonViewShare(id, recipientId, shareRowVersion);
|
||||
message.success('已撤销共享'); await refreshShareInfo(shareItem!); await load();
|
||||
} catch (value) { if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '撤销共享失败'); }
|
||||
finally { setBusyId(''); setShareLoading(false); }
|
||||
};
|
||||
const open = async (item: Row) => {
|
||||
const id = String(item.id || ''); if (!id) return;
|
||||
setBusyId(id);
|
||||
try {
|
||||
const result = await api.openComparisonView(id);
|
||||
if (item.shared === true) {
|
||||
setSharedPreview({ name: item.name, ownerDisplayName: item.ownerDisplayName, snapshot: result.snapshot });
|
||||
return;
|
||||
}
|
||||
const saved = record(result.view);
|
||||
const definition = record(saved.definition || saved);
|
||||
const context = record(definition.context);
|
||||
delete context.releaseId;
|
||||
onApply({ ...context, view: text(definition.groupBy, 'overall') as ViewKind });
|
||||
message.success('已打开比较视图,结果使用当前数据重新查询');
|
||||
} catch (value) { if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '打开视图失败'); }
|
||||
finally { setBusyId(''); }
|
||||
};
|
||||
const remove = async (item: Row) => {
|
||||
const id = String(item.id || ''); if (!id) return;
|
||||
setBusyId(id);
|
||||
try { await api.deleteComparisonView(id); message.success('已删除个人视图'); await load(); }
|
||||
catch (value) { if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '删除视图失败'); }
|
||||
finally { setBusyId(''); }
|
||||
};
|
||||
const columns: ColumnsType<Row> = [
|
||||
{ title: '视图名称', dataIndex: 'name', key: 'name', width: 210 },
|
||||
{ title: '分组维度', key: 'groupBy', width: 140, render: (_, row) => text(record(row.definition).groupBy, '总体') },
|
||||
{ title: '数据范围', key: 'dataScope', width: 180, render: () => '打开时使用当前数据' },
|
||||
{ title: '操作', key: 'actions', width: 250, render: (_, row) => <span className="completion-actions"><Button type="link" loading={busyId === String(row.id)} onClick={() => void open(row)}>打开</Button><Button type="link" onClick={() => void manageShares(row)}>共享</Button><Popconfirm title="删除此个人比较视图?" onConfirm={() => void remove(row)}><Button type="link" danger loading={busyId === String(row.id)}>删除</Button></Popconfirm></span> },
|
||||
];
|
||||
const sharedColumns: ColumnsType<Row> = [
|
||||
{ title: '视图名称', dataIndex: 'name', key: 'name', width: 230 },
|
||||
{ title: '共享者', dataIndex: 'ownerDisplayName', key: 'owner', width: 160 },
|
||||
{ title: '共享时间', dataIndex: 'sharedAt', key: 'sharedAt', width: 210, render: value => text(value) },
|
||||
{ title: '操作', key: 'actions', width: 100, render: (_, row) => <Button type="link" loading={busyId === String(row.id)} onClick={() => void open(row)}>打开</Button> },
|
||||
];
|
||||
const shareColumns: ColumnsType<Row> = [
|
||||
{ title: '接收人', dataIndex: 'displayName', key: 'displayName' },
|
||||
{ title: '状态', key: 'valid', render: (_, row) => row.active !== true ? <Tag>已撤销</Tag> : row.valid === true ? <Tag color="green">有效</Tag> : <Tag color="orange">权限已变化</Tag> },
|
||||
{ title: '操作', key: 'action', width: 100, render: (_, row) => row.active === true ? <Popconfirm title="撤销此用户的访问权限?" onConfirm={() => void revokeShare(row)}><Button type="link" danger loading={busyId === `${String(shareItem?.id)}:${String(row.recipientUserId)}`}>撤销</Button></Popconfirm> : null },
|
||||
];
|
||||
const sharedSnapshot = record(sharedPreview?.snapshot);
|
||||
const isSharedComparison = Boolean(sharedSnapshot.current && sharedSnapshot.comparison);
|
||||
return <section className="panel section-panel completion-tools">
|
||||
<div className="completion-panel-heading"><div><strong>已保存比较视图</strong><span>打开视图时按当前数据和授权范围重新计算</span></div><div className="completion-actions"><Button icon={<ReloadOutlined />} onClick={() => void load()}>刷新</Button><Button icon={<SaveOutlined />} type="primary" onClick={() => { form.setFieldsValue({ name: '' }); setModalOpen(true); }}>保存当前视图</Button></div></div>
|
||||
{error && <Alert showIcon type="error" message="保存视图不可用" description={error} />}
|
||||
<div className="completion-section-heading"><strong>我的视图</strong></div>
|
||||
{loading ? <div className="completion-loading"><Spin />读取个人视图…</div> : items.length ? <Table size="small" bordered columns={columns} dataSource={items} rowKey={item => String(item.id)} pagination={false} scroll={{ x: 850 }} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前没有已保存的个人视图" />}
|
||||
<div className="completion-section-heading"><strong>共享给我的视图</strong></div>
|
||||
{!loading && (sharedItems.length ? <Table size="small" bordered columns={sharedColumns} dataSource={sharedItems} rowKey={item => String(item.id)} pagination={false} scroll={{ x: 700 }} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前没有可访问的共享视图" />)}
|
||||
<Modal className="management-modal" open={modalOpen} title="保存个人比较视图" okText="保存" onCancel={() => setModalOpen(false)} onOk={() => void save()}>
|
||||
<Form form={form} layout="vertical"><Form.Item name="name" label="视图名称" rules={[{ required: true, whitespace: true, message: '请填写名称' }]}><Input maxLength={80} /></Form.Item></Form>
|
||||
</Modal>
|
||||
<Modal className="management-modal" open={shareItem !== null} title={`共享视图:${text(shareItem?.name)}`} okText="共享给所选用户" confirmLoading={shareLoading} okButtonProps={{ disabled: !shareRecipient || !shareCandidates.length }} onCancel={() => setShareItem(null)} onOk={() => void addShare()}>
|
||||
<p className="completion-note">收件人仅显示当前数据范围、字段和查询权限与您相同的活跃用户。权限变化后,共享访问会自动失效。</p>
|
||||
<Select {...readableSelectPopup} showSearch optionFilterProp="label" placeholder="选择收件用户" value={shareRecipient} onChange={setShareRecipient} options={shareCandidates.map(user => ({ value: String(user.id), label: String(user.displayName) }))} style={{ width: '100%', marginBottom: 16 }} loading={shareLoading} />
|
||||
<Table size="small" bordered loading={shareLoading} columns={shareColumns} dataSource={shareRows} rowKey={row => String(row.recipientUserId)} pagination={false} locale={{ emptyText: '尚未共享给其他用户' }} />
|
||||
</Modal>
|
||||
<Modal className="management-modal" open={sharedPreview !== null} title={text(sharedPreview?.name, '共享视图')} footer={<Button type="primary" onClick={() => setSharedPreview(null)}>关闭</Button>} onCancel={() => setSharedPreview(null)}>
|
||||
<p className="completion-note">共享者:{text(sharedPreview?.ownerDisplayName)} · 本次结果按你的当前权限重新计算。</p>
|
||||
{isSharedComparison ? <>
|
||||
<SharedQueryConditions label="当前期口径" value={sharedSnapshot.current} />
|
||||
<SharedQueryConditions label="比较期口径" value={sharedSnapshot.comparison} />
|
||||
<div className="completion-compare-snapshots"><SnapshotRates label="当前期间" value={sharedSnapshot.current} /><SnapshotRates label="比较期间" value={sharedSnapshot.comparison} /></div>
|
||||
<div className="completion-delta-grid"><span><small>综合变化</small><strong>{pp(record(sharedSnapshot.delta).percentagePoints)}</strong></span></div>
|
||||
</> : <><SharedQueryConditions label="查询口径" value={sharedPreview?.snapshot} /><SnapshotRates label="重新计算结果" value={sharedPreview?.snapshot} /></>}
|
||||
</Modal>
|
||||
</section>;
|
||||
}
|
||||
|
||||
export function ScrapAnalyticsPanel({ query, onUnauthorized }: { query: QueryParams; onUnauthorized: (error: unknown) => boolean }) {
|
||||
const [stage, setStage] = useState<Stage>('black');
|
||||
const [dimension, setDimension] = useState('category');
|
||||
const [limit, setLimit] = useState(10);
|
||||
const [top, setTop] = useState<Row[]>([]);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [compareError, setCompareError] = useState('');
|
||||
const [compare, setCompare] = useState<Row | null>(null);
|
||||
const [decomposition, setDecomposition] = useState<Row | null>(null);
|
||||
const [impactResult, setImpactResult] = useState<Row | null>(null);
|
||||
const [impactBusy, setImpactBusy] = useState(false);
|
||||
const [impactError, setImpactError] = useState('');
|
||||
const [compareBusy, setCompareBusy] = useState(false);
|
||||
const [checklists, setChecklists] = useState<Row[]>([]);
|
||||
const [activeChecklistId, setActiveChecklistId] = useState('');
|
||||
const [checklistItems, setChecklistItems] = useState<Row[]>([]);
|
||||
const [checklistBusy, setChecklistBusy] = useState(false);
|
||||
const [checklistError, setChecklistError] = useState('');
|
||||
const [checklistModal, setChecklistModal] = useState(false);
|
||||
const [checklistTitle, setChecklistTitle] = useState('');
|
||||
const [topResultId, setTopResultId] = useState('');
|
||||
const [topResultQuery, setTopResultQuery] = useState<Row>({});
|
||||
const [topShareBasis, setTopShareBasis] = useState('');
|
||||
const [comparisonYear, setComparisonYear] = useState(query.year - 1);
|
||||
const [comparisonMonth, setComparisonMonth] = useState(query.month);
|
||||
const [comparisonQuarter, setComparisonQuarter] = useState(query.quarter);
|
||||
|
||||
useEffect(() => { setCompare(null); setDecomposition(null); setImpactResult(null); setCompareError(''); setImpactError(''); }, [JSON.stringify(query), stage, dimension, comparisonYear, comparisonMonth, comparisonQuarter]);
|
||||
const loadChecklists = async (preferredId?: string) => {
|
||||
try {
|
||||
const response = await api.checklists(); const rows = list(response.items); setChecklists(rows);
|
||||
const target = preferredId || activeChecklistId || String(rows[0]?.id || '');
|
||||
setActiveChecklistId(target);
|
||||
if (target) {
|
||||
const detail = await api.checklist(target);
|
||||
setChecklistItems(list(detail.items));
|
||||
} else setChecklistItems([]);
|
||||
setChecklistError('');
|
||||
} catch (value) { if (!onUnauthorized(value)) setChecklistError(value instanceof Error ? value.message : '个人核查清单读取失败'); }
|
||||
};
|
||||
useEffect(() => { void loadChecklists(); }, []);
|
||||
const currentBody = useMemo(() => objectContext(query), [query]);
|
||||
useEffect(() => {
|
||||
let alive = true; setBusy(true); setError(''); setTop([]); setTopResultId(''); setTopResultQuery({}); setTopShareBasis('');
|
||||
api.analyticsTop({ ...currentBody, stage, dimension, limit }).then(value => { if (alive) { setTop(list(value.rows)); setTopResultId(text(value.resultId, '')); setTopResultQuery(record(value.resultQuery)); setTopShareBasis(text(value.shareBasis, '')); } })
|
||||
.catch(value => { if (alive && !onUnauthorized(value)) setError(value instanceof Error ? value.message : '排名读取失败'); })
|
||||
.finally(() => { if (alive) setBusy(false); });
|
||||
return () => { alive = false; };
|
||||
}, [JSON.stringify(currentBody), stage, dimension, limit, onUnauthorized]);
|
||||
|
||||
const runChangeAnalysis = async () => {
|
||||
setCompareBusy(true); setCompareError(''); setCompare(null); setDecomposition(null);
|
||||
const body = comparisonBody(query, { year: comparisonYear, ...(comparisonMonth ? { month: comparisonMonth } : {}), ...(comparisonQuarter ? { quarter: comparisonQuarter } : {}) });
|
||||
try {
|
||||
const comparisonResult = await api.analyticsCompare(body);
|
||||
setCompare(comparisonResult);
|
||||
if (['department', 'group', 'product', 'projectGroup'].includes(dimension)) {
|
||||
const structureResult = await api.structureDecomposition({ stage, dimension, current: { ...currentBody, year: query.year, ...(query.month ? { month: query.month } : {}), ...(query.quarter ? { quarter: query.quarter } : {}) }, comparison: { ...currentBody, year: comparisonYear, ...(comparisonMonth ? { month: comparisonMonth } : {}), ...(comparisonQuarter ? { quarter: comparisonQuarter } : {}) } });
|
||||
setDecomposition(structureResult);
|
||||
} else setDecomposition(null);
|
||||
} catch (value) { if (!onUnauthorized(value)) setCompareError(value instanceof Error ? value.message : '影响分析失败'); }
|
||||
finally { setCompareBusy(false); }
|
||||
};
|
||||
const addEvidence = async (row: Row) => {
|
||||
if (!activeChecklistId || !topResultId) return;
|
||||
setChecklistBusy(true);
|
||||
try {
|
||||
const releaseId = text(topResultQuery.releaseId, '');
|
||||
if (!releaseId) throw new Error('服务端没有返回可引用的排名结果,无法保存核查项');
|
||||
const subject = `${stage === 'black' ? '黑片' : '亮片'} · ${dimension === 'category' ? '原报废类别' : dimension} · ${text(row.label)}`;
|
||||
const findings = `已确认事实:报废重量 ${text(row.weight)} kg;服务端排名分母 ${text(row.denominator)} kg;单项占比 ${pct(row.share)};来源覆盖行数 ${text(record(row.coverage).rows)}。`;
|
||||
const checks = `待核查动作:按原始来源明细核对该排名对象的阶段、分类及重量汇总,并记录核对结论。`;
|
||||
await api.addChecklistItem(activeChecklistId, {
|
||||
resultId: topResultId, resultKind: 'top', resultQuery: topResultQuery,
|
||||
releaseId, context: currentBody,
|
||||
title: `${stage === 'black' ? '黑片' : '亮片'} · ${text(row.label)}`,
|
||||
subject,
|
||||
findings,
|
||||
unconfirmed: '未确认推断:当前排名只反映所选条件下的重量排序,尚未由原始行复核原因或责任归属。',
|
||||
checks,
|
||||
evidenceRefs: [{ type: 'TOP_RESULT', value: topResultId }, ...(row.sourceCategory ? [{ type: 'SOURCE_CATEGORY', value: row.sourceCategory }] : [])],
|
||||
});
|
||||
const detail = await api.checklist(activeChecklistId); setChecklistItems(list(detail.items)); setChecklistError('');
|
||||
} catch (value) { if (!onUnauthorized(value)) setChecklistError(value instanceof Error ? value.message : '保存核查证据失败'); }
|
||||
finally { setChecklistBusy(false); }
|
||||
};
|
||||
const runObjectImpact = async () => {
|
||||
if (!['department', 'group', 'product', 'projectGroup'].includes(dimension)) return;
|
||||
setImpactBusy(true); setImpactError(''); setImpactResult(null);
|
||||
const toSide = (period: { year: number; month?: number; quarter?: number }) => {
|
||||
const filters = objectContext(query);
|
||||
delete filters.view; delete filters.year; delete filters.month; delete filters.quarter; delete filters.releaseId;
|
||||
return { ...filters, ...(query.releaseId ? { releaseId: query.releaseId } : {}), ...period };
|
||||
};
|
||||
try {
|
||||
const result = await api.analyticsImpact({
|
||||
stage, dimension,
|
||||
current: toSide({ year: query.year, ...(query.month ? { month: query.month } : {}), ...(query.quarter ? { quarter: query.quarter } : {}) }),
|
||||
comparison: toSide({ year: comparisonYear, ...(comparisonMonth ? { month: comparisonMonth } : {}), ...(comparisonQuarter ? { quarter: comparisonQuarter } : {}) }),
|
||||
});
|
||||
setImpactResult(result);
|
||||
} catch (value) { if (!onUnauthorized(value)) setImpactError(value instanceof Error ? value.message : '对象影响分析失败'); }
|
||||
finally { setImpactBusy(false); }
|
||||
};
|
||||
const createChecklist = async () => {
|
||||
const title = checklistTitle.trim(); if (!title) return;
|
||||
setChecklistBusy(true);
|
||||
try {
|
||||
const created = await api.createChecklist({ title });
|
||||
const id = text(created.id, ''); setChecklistTitle(''); setChecklistModal(false);
|
||||
await loadChecklists(id);
|
||||
} catch (value) { if (!onUnauthorized(value)) setChecklistError(value instanceof Error ? value.message : '创建核查清单失败'); }
|
||||
finally { setChecklistBusy(false); }
|
||||
};
|
||||
const removeChecklistItem = async (item: Row) => {
|
||||
if (!activeChecklistId || !item.id) return;
|
||||
setChecklistBusy(true);
|
||||
try { await api.deleteChecklistItem(activeChecklistId, String(item.id)); const detail = await api.checklist(activeChecklistId); setChecklistItems(list(detail.items)); }
|
||||
catch (value) { if (!onUnauthorized(value)) setChecklistError(value instanceof Error ? value.message : '移除核查证据失败'); }
|
||||
finally { setChecklistBusy(false); }
|
||||
};
|
||||
const topColumns: ColumnsType<Row> = [
|
||||
{ title: '排名', dataIndex: 'rank', key: 'rank', align: 'center', width: 70 },
|
||||
{ title: dimension === 'category' ? '原报废类别' : '分析对象', dataIndex: 'label', key: 'label', fixed: 'left', width: 230, render: (_, row) => <span className="object-cell"><strong>{text(row.label)}</strong>{Boolean(row.sourceCategory) && <small>原始类别:{text(row.sourceCategory)}</small>}</span> },
|
||||
{ title: '报废重量 / kg', dataIndex: 'weight', key: 'weight', align: 'right', width: 150, render: value => text(value) },
|
||||
{ title: '占比分母 / kg', dataIndex: 'denominator', key: 'denominator', align: 'right', width: 160, render: value => text(value) },
|
||||
{ title: '占比', dataIndex: 'share', key: 'share', align: 'right', width: 110, render: value => pct(value) },
|
||||
{ title: '覆盖行数', key: 'coverage', width: 105, align: 'right', render: (_, row) => text(record(row.coverage).rows) },
|
||||
{ title: '核查', key: 'evidence', width: 110, render: (_, row) => <Button type="link" loading={checklistBusy} disabled={!activeChecklistId || !topResultId} onClick={() => void addEvidence(row)}>加入清单</Button> },
|
||||
];
|
||||
const groupRows = list(record(decomposition).groups);
|
||||
const groupColumns: ColumnsType<Row> = [
|
||||
{ title: '对象', dataIndex: 'key', key: 'key', fixed: 'left', width: 180 },
|
||||
{ title: '状态', dataIndex: 'status', key: 'status', width: 110, render: value => <Tag>{text(value)}</Tag> },
|
||||
{ title: '当前 / 比较结构占比', key: 'share', align: 'right', width: 180, render: (_, row) => `${pct(row.currentShare)} / ${pct(row.comparisonShare)}` },
|
||||
{ title: '当前 / 比较率', key: 'rate', align: 'center', width: 170, render: (_, row) => `${pct(row.currentRate)} / ${pct(row.comparisonRate)}` },
|
||||
{ title: '表现贡献', dataIndex: 'performancePP', key: 'performancePP', align: 'right', width: 140, render: pp },
|
||||
{ title: '结构贡献', dataIndex: 'mixPP', key: 'mixPP', align: 'right', width: 140, render: pp },
|
||||
];
|
||||
const compareResult = record(compare);
|
||||
const delta = record(compareResult.delta);
|
||||
const legacyDelta = record(compareResult.deltaPP);
|
||||
const contributions = record(compareResult.contributions);
|
||||
const comparePp = delta.percentagePoints ?? legacyDelta.composite ?? legacyDelta.compositeRate;
|
||||
const blackPp = contributions.black ?? contributions.blackPP;
|
||||
const brightPp = contributions.bright ?? contributions.brightPP;
|
||||
const unexplainedPp = contributions.unexplained ?? contributions.unexplainedPP ?? contributions.roundingResidualPP ?? contributions.residualPP;
|
||||
const comparable = record(compareResult.comparability);
|
||||
const comparisonReason = Array.isArray(comparable.reasons)
|
||||
? (comparable.reasons as unknown[]).map(String).join(';') || text(comparable.coverageNotice, '比较状态由服务端返回')
|
||||
: text(comparable.reason || comparable.coverageNotice, '比较状态由服务端返回');
|
||||
const available = decomposition?.available === true;
|
||||
const checklistColumns: ColumnsType<Row> = [
|
||||
{ title: '核查事项', dataIndex: 'title', key: 'title', fixed: 'left', width: 250 },
|
||||
{ title: '阶段 / 对象', dataIndex: 'subject', key: 'subject', width: 260, render: value => typeof value === 'string' ? value : (() => { const subject = record(value); return `${subject.stage === 'black' ? '黑片' : subject.stage === 'bright' ? '亮片' : '—'} · ${text(subject.label)}`; })() },
|
||||
{ title: '重算综合率', key: 'snapshot', align: 'right', width: 130, render: (_, row) => { const summary = record(record(row.metricSnapshot || row.snapshot).summary); return pct(summary.compositeRate); } },
|
||||
{ title: '证据状态', key: 'evidence', width: 125, render: (_, row) => row.evidenceAvailable === false ? <Tag color="gold">当前不可见</Tag> : <Tag color="green">已重新授权</Tag> },
|
||||
{ title: '操作', key: 'remove', width: 90, render: (_, row) => <Button type="link" danger loading={checklistBusy} onClick={() => void removeChecklistItem(row)}>移除</Button> },
|
||||
];
|
||||
const impactRows = list(impactResult?.groups);
|
||||
const impactColumns: ColumnsType<Row> = [
|
||||
{ title: '对象', dataIndex: 'label', key: 'label', fixed: 'left', width: 190 },
|
||||
{ title: '状态', dataIndex: 'status', key: 'status', width: 100, render: value => <Tag>{text(value)}</Tag> },
|
||||
{ title: '当前 / 比较重量', key: 'weights', align: 'right', width: 180, render: (_, row) => `${text(row.currentWeight)} / ${text(row.comparisonWeight)}` },
|
||||
{ title: '当前 / 比较结构占比', key: 'share', align: 'right', width: 190, render: (_, row) => `${pct(row.currentShare)} / ${pct(row.comparisonShare)}` },
|
||||
{ title: '当前 / 比较率', key: 'rates', align: 'right', width: 170, render: (_, row) => `${pct(row.currentRate)} / ${pct(row.comparisonRate)}` },
|
||||
{ title: '重量变化', dataIndex: 'weightDelta', key: 'weightDelta', align: 'right', width: 120 },
|
||||
{ title: '表现 / 结构 / 总影响', key: 'impact', align: 'right', width: 230, render: (_, row) => `${pp(row.performancePP)} / ${pp(row.mixPP)} / ${pp(row.impactPP)}` },
|
||||
{ title: '当前 / 比较行数', key: 'rows', align: 'right', width: 160, render: (_, row) => `${text(row.currentRows)} / ${text(row.comparisonRows)}` },
|
||||
];
|
||||
|
||||
return <div className="completion-scrap-stack">
|
||||
<section className="panel section-panel completion-tools">
|
||||
<div className="completion-panel-heading"><div><strong>本期报废排名</strong><span>当前期间损失按重量降序;占比分母:{topShareBasis || '服务端未返回口径'};只展示服务端返回的单项占比,不计算累计 TOP 阈值</span></div><Button icon={<ReloadOutlined />} loading={busy} onClick={() => { setBusy(true); setTopShareBasis(''); api.analyticsTop({ ...currentBody, stage, dimension, limit }).then(value => { setTop(list(value.rows)); setTopResultId(text(value.resultId, '')); setTopResultQuery(record(value.resultQuery)); setTopShareBasis(text(value.shareBasis, '')); }).catch(value => { if (!onUnauthorized(value)) setError(value instanceof Error ? value.message : '排名读取失败'); }).finally(() => setBusy(false)); }}>刷新排名</Button></div>
|
||||
<div className="completion-filter-row"><Segmented value={stage} options={[{ label: '黑片', value: 'black' }, { label: '亮片', value: 'bright' }]} onChange={value => setStage(value as Stage)} aria-label="报废阶段" /><Select value={dimension} onChange={setDimension} aria-label="排名维度" options={[{ label: '原报废类别', value: 'category' }, { label: '产业部', value: 'department' }, { label: '业务分组', value: 'group' }, { label: '产品', value: 'product' }, { label: '项目组', value: 'projectGroup' }]} /><Select value={limit} onChange={setLimit} aria-label="显示排名数量" options={[10, 20, 50].map(value => ({ label: `TOP ${value}`, value }))} /></div>
|
||||
{error && <Alert showIcon type="error" message="报废排名不可用" description={error} />}
|
||||
{busy ? <div className="completion-loading"><Spin />读取排名…</div> : top.length ? <Table size="small" bordered columns={topColumns} dataSource={top} rowKey={row => String(row.key || row.rank)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1040 }} /> : !error && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前条件没有报废排名数据" />}
|
||||
</section>
|
||||
|
||||
<section className="panel section-panel completion-tools">
|
||||
<div className="completion-panel-heading"><div><strong>阶段贡献与影响分解</strong><span>比较服务端正式率,并核对阶段贡献与结构分解前提</span></div></div>
|
||||
<div className="completion-filter-row"><label className="completion-compare-period">比较年份<InputNumber min={2000} max={2200} value={comparisonYear} onChange={value => value && setComparisonYear(value)} /></label>{query.month && <Select aria-label="比较月份" value={comparisonMonth} onChange={setComparisonMonth} options={Array.from({ length: 12 }, (_, index) => ({ label: `${index + 1}月`, value: index + 1 }))} />}{query.quarter && <Select aria-label="比较季度" value={comparisonQuarter} onChange={setComparisonQuarter} options={[1, 2, 3, 4].map(value => ({ label: `第${value}季度`, value }))} />}<Button type="primary" loading={compareBusy} onClick={() => void runChangeAnalysis()}>执行同期影响分析</Button></div>
|
||||
{compareError && <Alert showIcon type="error" message="期间比较失败" description={compareError} />}
|
||||
{compare && <>
|
||||
<div className="completion-delta-grid"><span><small>综合变化</small><strong>{pp(comparePp)}</strong></span><span><small>黑片贡献</small><strong>{pp(blackPp)}</strong></span><span><small>亮片贡献</small><strong>{pp(brightPp)}</strong></span><span><small>未解释</small><strong>{pp(unexplainedPp)}</strong></span></div>
|
||||
<div className="completion-contribution"><span>比较可比性 <strong>{comparable.comparable === true ? '可比' : comparable.comparable === false ? '不可比' : '未确定'}</strong></span><span>覆盖可比 <strong>{comparable.coverageAligned === true ? '是' : comparable.coverageAligned === false ? '否' : '—'}</strong></span><span>{comparisonReason}</span></div>
|
||||
</>}
|
||||
{decomposition && <><Alert showIcon type={available ? 'info' : 'warning'} message={available ? `结构分解可用 · ${text(decomposition.methodId)}` : '结构分解前提未满足'} description={available ? `表现 ${pp(decomposition.performancePP)} · 结构 ${pp(decomposition.mixPP)} · 交互 ${pp(decomposition.interactionPP)} · 未解释 ${pp(decomposition.unexplainedPP)}` : text(decomposition.reason, '服务端未提供分解原因')} /><div className="completion-table-wrap">{groupRows.length > 0 && <Table size="small" bordered columns={groupColumns} dataSource={groupRows} rowKey={row => String(row.key)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 950 }} />}</div></>}
|
||||
{['department', 'group', 'product', 'projectGroup'].includes(dimension) ? <div className="completion-impact-tools"><Button onClick={() => void runObjectImpact()} loading={impactBusy}>执行对象影响分析</Button>{impactError && <Alert showIcon type="error" message="对象影响分析失败" description={impactError} />}{impactResult && <><Alert showIcon type={impactResult.available === true ? 'info' : 'warning'} message={impactResult.available === true ? `对象影响可用 · ${text(impactResult.methodId)}` : '对象影响暂不可用'} description={impactResult.available === true ? `总体变化 ${pp(impactResult.deltaPP)} · 对象影响合计 ${pp(impactResult.totalImpactPP)} · 未解释 ${pp(impactResult.unexplainedPP)}${impactResult.assumptions ? ` · ${text(impactResult.assumptions)}` : ''}` : text(impactResult.reason, '服务端未提供不可用原因')} />{impactRows.length > 0 && <Table size="small" bordered columns={impactColumns} dataSource={impactRows} rowKey={row => String(row.key)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1390 }} />}</>}</div> : <Alert showIcon type="info" message="对象影响分析需选择分类以外的分析维度" description="当前原报废类别不是可加总对象维度;请选择产业部、业务分组、产品或项目组后运行对象影响分析。" />}
|
||||
{compare && dimension === 'category' && <Alert showIcon type="info" message="类别排名已完成期间比较" description="原报废类别不是结构分解维度。选择产业部、业务分组、产品或项目组后,可查看对应结构分解。" />}
|
||||
{compareBusy && <div className="completion-loading"><Spin />正在对齐比较期间与指标口径…</div>}
|
||||
{!compare && !decomposition && !compareBusy && <div className="completion-placeholder">选择比较期间后运行。规则口径、覆盖、阶段缺失和结构分组由服务端判断。</div>}
|
||||
</section>
|
||||
|
||||
<section className="panel section-panel completion-tools">
|
||||
<div className="completion-panel-heading"><div><strong>个人核查清单</strong><span>私有持久化;打开时按当前授权范围重新计算快照</span></div><div className="completion-actions"><Select {...readableSelectPopup} aria-label="选择个人核查清单" placeholder="选择清单" value={activeChecklistId || undefined} options={checklists.map(item => ({ label: text(item.title || item.name), value: String(item.id) }))} onChange={value => { setActiveChecklistId(value); setChecklistBusy(true); api.checklist(value).then(detail => setChecklistItems(list(detail.items))).catch(valueError => { if (!onUnauthorized(valueError)) setChecklistError(valueError instanceof Error ? valueError.message : '清单打开失败'); }).finally(() => setChecklistBusy(false)); }} /><Button icon={<ReloadOutlined />} loading={checklistBusy} onClick={() => void loadChecklists()}>刷新</Button><Button type="primary" icon={<PlusOutlined />} onClick={() => setChecklistModal(true)}>新建清单</Button></div></div>
|
||||
{checklistError && <Alert showIcon type="error" message="个人核查清单操作失败" description={checklistError} />}
|
||||
{checklistBusy ? <div className="completion-loading"><Spin />读取清单与重新计算快照…</div> : checklistItems.length ? <Table size="small" bordered columns={checklistColumns} dataSource={checklistItems} rowKey={row => String(row.id)} pagination={false} expandable={{ expandedRowRender: row => <div className="completion-checklist-evidence"><div><strong>已确认事实</strong><p>{text(row.findings, '—')}</p></div><div><strong>未确认推断</strong><p>{text(row.unconfirmed, '无')}</p></div><div><strong>待核查动作</strong><p>{text(row.checks, '—')}</p></div></div> }} scroll={{ x: 920 }} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={activeChecklistId ? '当前清单没有核查项目;从上方排名加入结果' : '创建个人清单后,可保存排名结果及其服务端查询指纹'} />}
|
||||
{!activeChecklistId && top.length > 0 && <p className="completion-note">请先创建或选择清单;加入操作将保存服务端结果指纹、完整查询条件与可见快照,不使用排名序号充当证据编号。</p>}
|
||||
<Modal className="management-modal" open={checklistModal} title="新建个人核查清单" okText="创建清单" confirmLoading={checklistBusy} onCancel={() => setChecklistModal(false)} onOk={() => void createChecklist()}><Input autoFocus value={checklistTitle} maxLength={160} placeholder="清单名称" onChange={event => setChecklistTitle(event.target.value)} onPressEnter={() => void createChecklist()} /></Modal>
|
||||
</section>
|
||||
</div>;
|
||||
}
|
||||
|
||||
export function TargetVersionAdmin({ onUnauthorized }: { onUnauthorized: (error: unknown) => boolean }) {
|
||||
const { message } = App.useApp();
|
||||
const [items, setItems] = useState<Row[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
const [editing, setEditing] = useState<Row | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [targetRows, setTargetRows] = useState<Row[]>([]);
|
||||
const [targetYears, setTargetYears] = useState<number[]>([2026, 2027, 2028]);
|
||||
const [referenceNames, setReferenceNames] = useState<Row>({ departments: [], groups: [], groupDepartments: {} });
|
||||
const retiredDepartments = new Set(['美洲产业部', '欧洲产业部', '欧洲磁钢']);
|
||||
const normalizeDepartment = (value: unknown) => {
|
||||
const department = String(value || '').trim();
|
||||
return department === '质量管理部' ? '质量中心' : department;
|
||||
};
|
||||
const isRetiredDepartment = (value: unknown) => retiredDepartments.has(normalizeDepartment(value));
|
||||
const dimensionKeys = ['department', 'group', 'product', 'projectGroup'] as const;
|
||||
const dimensionLabels: Record<(typeof dimensionKeys)[number], string> = {
|
||||
department: '产业部', group: '业务分组', product: '产品', projectGroup: '项目组',
|
||||
};
|
||||
const metricOptions = [
|
||||
{ label: '综合合格率', value: 'COMPOSITE_RATE' },
|
||||
{ label: '黑片合格率', value: 'BLACK_RATE' },
|
||||
{ label: '亮片合格率', value: 'BRIGHT_RATE' },
|
||||
{ label: '综合合格率(不含本部报废)', value: 'COMPOSITE_RATE_WITHOUT_HEADQUARTERS_SCRAP' },
|
||||
{ label: '亮片合格率(不含本部报废)', value: 'BRIGHT_RATE_WITHOUT_HEADQUARTERS_SCRAP' },
|
||||
];
|
||||
const hasScope = (row: Row) => dimensionKeys.some(key => String(row[key] || '').trim());
|
||||
const rowKey = () => `target-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
||||
const newRow = (editorScope: boolean, dimensions: Row = {}): Row => ({
|
||||
editorKey: rowKey(), editorScope, metric: 'COMPOSITE_RATE', values: {}, metadataByYear: {},
|
||||
department: '', group: '', product: '', projectGroup: '', ...dimensions,
|
||||
});
|
||||
const patchRow = (row: Row, patch: Row) => {
|
||||
const key = String(row.editorKey || '');
|
||||
setTargetRows(current => current.map(item => String(item.editorKey || '') === key ? { ...item, ...patch } : item));
|
||||
};
|
||||
const patchCell = (row: Row, year: number, value: number | null) => {
|
||||
const key = String(row.editorKey || '');
|
||||
setTargetRows(current => current.map(item => String(item.editorKey || '') === key
|
||||
? { ...item, values: { ...record(item.values), [String(year)]: value } }
|
||||
: item));
|
||||
};
|
||||
const removeRow = (row: Row) => {
|
||||
const key = String(row.editorKey || '');
|
||||
setTargetRows(current => current.filter(item => String(item.editorKey || '') !== key));
|
||||
};
|
||||
const isScopeRow = (row: Row) => row.editorScope === true;
|
||||
const overallRows = targetRows.filter(row => !isScopeRow(row));
|
||||
const scopeRows = targetRows.filter(isScopeRow);
|
||||
const referenceGroupDepartments = record(referenceNames.groupDepartments);
|
||||
const departmentOptions = [...new Set([
|
||||
...listOfNames(referenceNames.departments),
|
||||
...scopeRows.map(row => normalizeDepartment(row.department)),
|
||||
].filter(value => value && !isRetiredDepartment(value)))].map(value => ({ label: value, value }));
|
||||
const groupOptionsFor = (row: Row) => {
|
||||
const department = normalizeDepartment(row.department);
|
||||
return [...new Set([
|
||||
...listOfNames(referenceNames.groups).filter(group => {
|
||||
const owner = normalizeDepartment(referenceGroupDepartments[group]);
|
||||
return !isRetiredDepartment(owner) && (!department || !owner || owner === department);
|
||||
}),
|
||||
String(row.group || '').trim(),
|
||||
].filter(Boolean))].map(value => ({ label: value, value }));
|
||||
};
|
||||
const metricColumn: ColumnsType<Row>[number] = {
|
||||
title: '指标', dataIndex: 'metric', key: 'metric', width: 150, align: 'center',
|
||||
render: (value, row) => <Select classNames={{ popup: { root: 'target-editor-select-popup' } }} popupMatchSelectWidth={320} aria-label="目标指标" value={text(value, 'COMPOSITE_RATE')} options={metricOptions} onChange={metric => patchRow(row, { metric })} />,
|
||||
};
|
||||
const rateColumns: ColumnsType<Row> = targetYears.map(year => ({
|
||||
title: String(year), key: `year-${year}`, width: 116, align: 'center',
|
||||
render: (_value, row) => {
|
||||
const raw = record(row.values)[String(year)];
|
||||
const value = raw === null || raw === undefined || raw === '' ? null : Number(raw);
|
||||
return <span className="target-editor-rate">
|
||||
<InputNumber min={0} max={100} step={0.1} precision={2} value={value}
|
||||
onChange={next => patchCell(row, year, next)} aria-label={`${year}年合格率目标百分比`} />
|
||||
{value !== null && <span>%</span>}
|
||||
</span>;
|
||||
},
|
||||
}));
|
||||
const overallColumns: ColumnsType<Row> = [
|
||||
metricColumn, ...rateColumns,
|
||||
{ title: '操作', key: 'actions', width: 48, fixed: 'right', align: 'center', render: (_, row) => <Button aria-label="删除总体目标行" title="删除" danger type="text" icon={<DeleteOutlined />} onClick={() => removeRow(row)} /> },
|
||||
];
|
||||
const scopeColumns: ColumnsType<Row> = [
|
||||
metricColumn,
|
||||
...dimensionKeys.map(key => ({
|
||||
title: key === 'department' ? '产业部 / 地区' : dimensionLabels[key], dataIndex: key, key,
|
||||
width: key === 'department' || key === 'group' ? 158 : 132, align: 'center' as const,
|
||||
render: (value: unknown, row: Row) => key === 'department' || key === 'group'
|
||||
? <Select classNames={{ popup: { root: 'target-editor-select-popup' } }} popupMatchSelectWidth={260}
|
||||
showSearch optionFilterProp="label" allowClear aria-label={key === 'department' ? '产业部 / 地区' : '业务分组'}
|
||||
value={String(value || '') || undefined}
|
||||
options={key === 'department' ? departmentOptions : groupOptionsFor(row)}
|
||||
onChange={selected => patchRow(row, { [key]: selected || '', editorScope: true })} />
|
||||
: <Input value={String(value || '')}
|
||||
aria-label={dimensionLabels[key]} maxLength={190}
|
||||
onChange={event => patchRow(row, { [key]: event.target.value, editorScope: true })} />,
|
||||
})),
|
||||
...rateColumns,
|
||||
{ title: '操作', key: 'actions', width: 48, fixed: 'right', align: 'center', render: (_, row) => <Button aria-label="删除范围目标行" title="删除" danger type="text" icon={<DeleteOutlined />} onClick={() => removeRow(row)} /> },
|
||||
];
|
||||
const load = async () => {
|
||||
setLoading(true);
|
||||
try { const response = await api.targetVersions(); setItems(collectionItems(response)); setError(''); }
|
||||
catch (value) { if (!onUnauthorized(value)) setError(value instanceof Error ? value.message : '质量目标读取失败'); }
|
||||
finally { setLoading(false); }
|
||||
};
|
||||
useEffect(() => { void load(); }, []);
|
||||
const open = async (item: Row) => {
|
||||
const id = String(item.id || ''); if (!id) return;
|
||||
setBusy(true); setError('');
|
||||
try {
|
||||
const detail = await api.targetVersion(id);
|
||||
const version = record(detail.version || item);
|
||||
let references: Row = { departments: [], groups: [], groupDepartments: {} };
|
||||
try { references = record(await api.referenceNames()); }
|
||||
catch (referenceError) {
|
||||
if (onUnauthorized(referenceError)) throw referenceError;
|
||||
message.warning('产业部和业务分组名录暂不可读,仍可编辑已有目标。');
|
||||
}
|
||||
setReferenceNames(references);
|
||||
const annualTargets = list(detail.targets).filter(target => String(target.periodType || '').toUpperCase() === 'YEAR');
|
||||
const years = [...new Set([2026, 2027, 2028, ...annualTargets.map(target => Number(target.year)).filter(year => Number.isInteger(year) && year >= 2000 && year <= 2100)])].sort((a, b) => a - b);
|
||||
const metrics = [...new Set(['COMPOSITE_RATE', ...annualTargets.map(target => String(target.metric || '').toUpperCase()).filter(metric => metricOptions.some(option => option.value === metric))])];
|
||||
const overallByMetric = new Map<string, Row>();
|
||||
const scopeByKey = new Map<string, Row>();
|
||||
const scopeSignature = (metric: string, dimensions: Row) => JSON.stringify([metric, ...dimensionKeys.map(key => String(dimensions[key] || '').trim())]);
|
||||
const ensureOverall = (metric: string) => {
|
||||
const existing = overallByMetric.get(metric);
|
||||
if (existing) return existing;
|
||||
const created = newRow(false, { metric });
|
||||
overallByMetric.set(metric, created);
|
||||
return created;
|
||||
};
|
||||
const ensureScope = (metric: string, dimensions: Row) => {
|
||||
const normalized = { ...dimensions, department: normalizeDepartment(dimensions.department) };
|
||||
const key = scopeSignature(metric, normalized);
|
||||
const existing = scopeByKey.get(key);
|
||||
if (existing) return existing;
|
||||
const created = newRow(true, { ...normalized, metric });
|
||||
scopeByKey.set(key, created);
|
||||
return created;
|
||||
};
|
||||
for (const metric of metrics) ensureOverall(metric);
|
||||
const departments = Array.isArray(references.departments) ? references.departments.map(value => String(value || '').trim()).filter(value => value && !isRetiredDepartment(value)) : [];
|
||||
const groups = Array.isArray(references.groups) ? references.groups.map(value => String(value || '').trim()).filter(Boolean) : [];
|
||||
const groupDepartments = record(references.groupDepartments);
|
||||
for (const department of [...new Set(departments)]) ensureScope('COMPOSITE_RATE', { department });
|
||||
for (const group of [...new Set(groups)]) if (!isRetiredDepartment(groupDepartments[group])) ensureScope('COMPOSITE_RATE', { department: groupDepartments[group] ? normalizeDepartment(groupDepartments[group]) : '', group });
|
||||
annualTargets.forEach(target => {
|
||||
const year = Number(target.year);
|
||||
const metric = String(target.metric || '').toUpperCase();
|
||||
if (!Number.isInteger(year) || !metricOptions.some(option => option.value === metric)) return;
|
||||
const dimensions = record(target.dimensions);
|
||||
if (isRetiredDepartment(dimensions.department)) return;
|
||||
const scoped = dimensionKeys.some(key => String(dimensions[key] || '').trim());
|
||||
const row = scoped ? ensureScope(metric, dimensions) : ensureOverall(metric);
|
||||
row.values = { ...record(row.values), [String(year)]: Number(target.value) * 100 };
|
||||
row.metadataByYear = { ...record(row.metadataByYear), [String(year)]: { source: target.source, note: target.note } };
|
||||
});
|
||||
if (!annualTargets.length) {
|
||||
const defaultOverall = ensureOverall('COMPOSITE_RATE');
|
||||
defaultOverall.values = { ...record(defaultOverall.values), '2026': 95.5 };
|
||||
}
|
||||
const matrixRows = [...overallByMetric.values(), ...scopeByKey.values()];
|
||||
if (!scopeByKey.size) matrixRows.push(newRow(true));
|
||||
setTargetYears(years); setTargetRows(matrixRows);
|
||||
setEditing({ ...version, targets: annualTargets });
|
||||
} catch (value) { if (!onUnauthorized(value)) setError(value instanceof Error ? value.message : '目标规则详情读取失败'); }
|
||||
finally { setBusy(false); }
|
||||
};
|
||||
const save = async () => {
|
||||
if (!editing?.id) return;
|
||||
try {
|
||||
const targets: Row[] = [];
|
||||
for (const target of overallRows) {
|
||||
if (!metricOptions.some(option => option.value === target.metric)) { message.warning('请选择有效的总体目标指标。'); return; }
|
||||
for (const year of targetYears) {
|
||||
const raw = record(target.values)[String(year)];
|
||||
if (raw === null || raw === undefined || raw === '') continue;
|
||||
const percent = Number(raw);
|
||||
if (!Number.isFinite(percent) || percent < 0 || percent > 100) { message.warning('总体目标合格率请填写 0–100。'); return; }
|
||||
const metadata = record(record(target.metadataByYear)[String(year)]);
|
||||
targets.push({ metric: target.metric, periodType: 'YEAR', year, dimensions: {}, value: percent / 100, unit: 'RATE', ...(metadata.source ? { source: metadata.source } : {}), ...(metadata.note ? { note: metadata.note } : {}) });
|
||||
}
|
||||
}
|
||||
if (!targets.some(target => Object.keys(record(target.dimensions)).length === 0)) { message.warning('请至少填写一项总体年度目标。'); return; }
|
||||
for (const target of scopeRows) {
|
||||
if (!metricOptions.some(option => option.value === target.metric)) { message.warning('请选择有效的范围目标指标。'); return; }
|
||||
const dimensions: Row = {};
|
||||
for (const key of dimensionKeys) if (String(target[key] || '').trim()) dimensions[key] = String(target[key]).trim();
|
||||
if (retiredDepartments.has(String(dimensions.department || ''))) { message.warning('已取消的产业部不能配置目标。'); return; }
|
||||
if (!hasScope(dimensions)) {
|
||||
if (targetYears.some(year => record(target.values)[String(year)] !== null && record(target.values)[String(year)] !== undefined && record(target.values)[String(year)] !== '')) {
|
||||
message.warning('请先填写产业部 / 地区、业务分组、产品或项目组,再填写范围目标。'); return;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
for (const year of targetYears) {
|
||||
const raw = record(target.values)[String(year)];
|
||||
if (raw === null || raw === undefined || raw === '') continue; // Blank cells inherit the overall annual target.
|
||||
const percent = Number(raw);
|
||||
if (!Number.isFinite(percent) || percent < 0 || percent > 100) { message.warning('范围目标合格率请填写 0–100。'); return; }
|
||||
const metadata = record(record(target.metadataByYear)[String(year)]);
|
||||
targets.push({ metric: target.metric, periodType: 'YEAR', year, dimensions, value: percent / 100, unit: 'RATE', ...(metadata.source ? { source: metadata.source } : {}), ...(metadata.note ? { note: metadata.note } : {}) });
|
||||
}
|
||||
}
|
||||
setBusy(true);
|
||||
await api.updateCurrentTargets({ targets, expectedRowVersion: Number(editing.rowVersion || 0) });
|
||||
message.success('质量目标已保存,当前报表立即生效'); setEditing(null); await load();
|
||||
} catch (value) { if (!onUnauthorized(value)) message.error(value instanceof ApiError && value.status === 409 ? '目标已被其他人修改,请刷新核对。' : value instanceof Error ? value.message : '质量目标保存失败'); if (value instanceof ApiError && value.status === 409) await load(); }
|
||||
finally { setBusy(false); }
|
||||
};
|
||||
const currentTarget = items.find(item => String(item.status).toUpperCase() === 'ACTIVE');
|
||||
return <section className="panel section-panel completion-tools target-admin">
|
||||
<div className="completion-panel-heading"><div><strong>质量目标配置</strong><span>直接维护当前目标;月度、季度查询使用所在年度目标,产业部和业务分组可按年覆盖</span></div><Button icon={<ReloadOutlined />} onClick={() => void load()}>刷新</Button></div>
|
||||
{error && <Alert showIcon type="error" message="目标配置不可用" description={error} />}
|
||||
{loading ? <div className="completion-loading"><Spin />读取质量目标…</div> : currentTarget ? <div className="target-current-summary"><strong>当前质量目标</strong><span>已配置 {text(currentTarget.targetCount, '0')} 项年度目标</span><Button type="primary" loading={busy} onClick={() => void open(currentTarget)}>编辑目标</Button></div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前没有启用的质量目标" />}
|
||||
<Modal className="management-modal target-editor-modal" open={Boolean(editing)} title="编辑质量目标" width="min(1280px, calc(100vw - 32px))" okText="保存并立即生效" confirmLoading={busy} onCancel={() => setEditing(null)} onOk={() => void save()}>
|
||||
<div className="target-editor-section">
|
||||
<div className="target-editor-heading"><div><strong>总体年度目标</strong><span>列为年份;每个指标按年维护,范围目标为空时引用此处目标</span></div><div className="completion-actions"><Button icon={<PlusOutlined />} onClick={() => { const year = Math.max(2028, ...targetYears) + 1; if (year > 2100) { message.warning('最多支持添加到 2100 年。'); return; } setTargetYears(current => [...current, year].sort((a, b) => a - b)); }}>新增年度</Button><Button icon={<PlusOutlined />} onClick={() => setTargetRows(rows => [...rows, newRow(false)])}>新增总体指标</Button></div></div>
|
||||
<Table className="target-editor-table" size="small" bordered columns={overallColumns} dataSource={overallRows} rowKey={row => String(row.editorKey)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 150 + targetYears.length * 116 + 48 }} />
|
||||
</div>
|
||||
<div className="target-editor-section">
|
||||
<div className="target-editor-heading"><div><strong>产业部 / 地区与业务分组年度目标</strong><span>产业部、业务分组从名录选择;产品和项目组可直接输入。目标留空表示沿用总体目标</span></div><Button icon={<PlusOutlined />} onClick={() => setTargetRows(rows => [...rows, newRow(true)])}>新增产业部 / 分组</Button></div>
|
||||
<Table className="target-editor-table" size="small" bordered columns={scopeColumns} dataSource={scopeRows} rowKey={row => String(row.editorKey)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 150 + 158 * 2 + 132 * 2 + targetYears.length * 116 + 48 }} locale={{ emptyText: '暂无产业部或业务分组;可新增后直接输入' }} />
|
||||
</div>
|
||||
<Alert showIcon type="info" message="保存后立即生效" description="例如输入 95.5 即为 95.5%。范围目标空白时沿用同一年、同一指标的总体目标;保存后当前及已发布报表使用更新后的目标。" />
|
||||
</Modal>
|
||||
</section>;
|
||||
}
|
||||
@@ -0,0 +1,722 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Alert, App, Button, Checkbox, Drawer, Empty, Form, Input, InputNumber, Modal, Select, Spin, Switch, Table, Tabs, Tag } from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import { DownloadOutlined, ReloadOutlined } from '@ant-design/icons';
|
||||
import { ApiError, api, collectionItems } from './api';
|
||||
import type { AuthUser, SourceItem } from './types';
|
||||
import { readableSelectPopup } from './readableSelectPopup';
|
||||
import { isInternalDataField } from './publicDataDisplay';
|
||||
import './completion.css';
|
||||
|
||||
type Row = Record<string, unknown>;
|
||||
const TABLE_PAGE_SIZE = 20;
|
||||
const INTERNAL_REVISION_FIELDS = new Set(['sourcerevisionid', 'targetrevisionid', 'expectedrevisionid', 'currentrevisionid', 'candidaterevisionid', 'baserevisionid']);
|
||||
const obj = (value: unknown): Row => value && typeof value === 'object' && !Array.isArray(value) ? value as Row : {};
|
||||
const rows = (value: unknown): Row[] => Array.isArray(value) ? value.filter(item => item && typeof item === 'object') as Row[] : [];
|
||||
const text = (value: unknown, empty = '—') => value === null || value === undefined || value === '' ? empty : typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' ? String(value) : empty;
|
||||
const withoutSystemMetadata = (value: unknown): unknown => {
|
||||
if (Array.isArray(value)) return value.map(withoutSystemMetadata);
|
||||
if (!value || typeof value !== 'object') return value;
|
||||
return Object.fromEntries(Object.entries(value as Row)
|
||||
.filter(([key]) => !isInternalDataField(key) && !INTERNAL_REVISION_FIELDS.has(key.replace(/[^a-z0-9]/gi, '').toLowerCase()))
|
||||
.map(([key, child]) => [key, withoutSystemMetadata(child)]));
|
||||
};
|
||||
const drilldownStatusText = (value: unknown) => ({
|
||||
DISABLED: '未启用', NOT_NEEDED: '本次无发现项', PENDING: '等待调度', QUEUED: '排队中', RUNNING: '分析中',
|
||||
COMPLETED: '已完成', FAILED: '失败', CANCELLED: '已取消', BLOCKED_AUTHORIZATION: '权限不足',
|
||||
} as Record<string, string>)[String(value)] || text(value, '未返回');
|
||||
|
||||
function showDownload(data: { blob: Blob; filename: string }) {
|
||||
const url = URL.createObjectURL(data.blob);
|
||||
const anchor = document.createElement('a');
|
||||
anchor.href = url;
|
||||
anchor.download = data.filename;
|
||||
document.body.appendChild(anchor);
|
||||
anchor.click();
|
||||
anchor.remove();
|
||||
window.setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
}
|
||||
|
||||
function ErrorPanel({ title, error, onRetry }: { title: string; error: string; onRetry: () => void }) {
|
||||
return error ? <Alert showIcon type="error" message={title} description={error} action={<Button size="small" onClick={onRetry}>重试</Button>} /> : null;
|
||||
}
|
||||
|
||||
const INSPECTION_DEFAULTS: Row = {
|
||||
rateDropEnabled: true, rateDropPp: 1,
|
||||
defectTopEnabled: true, minTopShare: 0.1,
|
||||
minStageRows: 1, quietPeriodHours: 24,
|
||||
productTopEnabled: true, productTopLimit: 5, productTopMinShare: 0.05,
|
||||
newObjectEnabled: true, newObjectMinRows: 1,
|
||||
sustainedWorseningEnabled: true, sustainedWorseningMonths: 3, sustainedWorseningPp: 1,
|
||||
targetGapEnabled: true, targetGapPp: 1,
|
||||
aiDrilldownEnabled: false, aiMaxFindings: 3,
|
||||
};
|
||||
|
||||
function analysisDeepLink(sessionId: string, turnId: string): string {
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.set('page', 'analysis');
|
||||
url.searchParams.set('sessionId', sessionId);
|
||||
url.searchParams.set('turnId', turnId);
|
||||
return `${url.pathname}${url.search}${url.hash}`;
|
||||
}
|
||||
|
||||
function InspectionStrategyPanel({ user, onUnauthorized }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean }) {
|
||||
const { message } = App.useApp();
|
||||
const canManage = user.roles.some(role => ['SYSTEM_ADMIN', 'SYSTEM_OPERATOR'].includes(role));
|
||||
const canRun = user.roles.some(role => ['QUALITY_VIEWER', 'BUSINESS_ANALYST'].includes(role));
|
||||
const [strategies, setStrategies] = useState<Row[]>([]);
|
||||
const [releaseId, setReleaseId] = useState('');
|
||||
const [runs, setRuns] = useState<Row[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [running, setRunning] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [selectedRun, setSelectedRun] = useState<Row | null>(null);
|
||||
const [editing, setEditing] = useState<Row | null>(null);
|
||||
const [form] = Form.useForm<Row>();
|
||||
|
||||
const load = async () => {
|
||||
setLoading(true); setError('');
|
||||
const results = await Promise.allSettled([
|
||||
canManage ? api.inspectionStrategies() : Promise.resolve({ items: [] }),
|
||||
api.releases(),
|
||||
]);
|
||||
if (results[0].status === 'fulfilled') setStrategies(collectionItems(results[0].value));
|
||||
else if (!onUnauthorized(results[0].reason)) setError(results[0].reason instanceof Error ? results[0].reason.message : '巡检策略读取失败');
|
||||
if (results[1].status === 'fulfilled') {
|
||||
const current = String(results[1].value.currentReleaseId || '');
|
||||
setReleaseId(current);
|
||||
} else if (!onUnauthorized(results[1].reason)) {
|
||||
const failure = results[1].reason;
|
||||
setError(value => [value, failure instanceof Error ? failure.message : '当前数据读取失败'].filter(Boolean).join(';'));
|
||||
}
|
||||
setLoading(false);
|
||||
};
|
||||
const loadRuns = async (selectedRelease = releaseId) => {
|
||||
if (!canRun || !selectedRelease) { setRuns([]); return; }
|
||||
setRuns([]);
|
||||
try { const result = await api.inspectionRuns(selectedRelease); setRuns(collectionItems(result)); }
|
||||
catch (value) { if (!onUnauthorized(value)) setError(value instanceof Error ? value.message : '巡检运行记录读取失败'); }
|
||||
};
|
||||
useEffect(() => { void load(); }, []);
|
||||
useEffect(() => { if (releaseId) void loadRuns(releaseId); }, [releaseId]);
|
||||
|
||||
const openEditor = async (row?: Row) => {
|
||||
if (!canManage) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
const source = row?.id ? await api.inspectionStrategy(String(row.id)) : {};
|
||||
const strategy = obj(source);
|
||||
setEditing(row ? { ...row, ...strategy } : {});
|
||||
const config = { ...INSPECTION_DEFAULTS, ...obj(strategy.config || row?.config) };
|
||||
form.setFieldsValue({ name: String(strategy.name || row?.name || ''), active: strategy.active === true || row?.active === true, ...config });
|
||||
} catch (value) { if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '巡检策略详情读取失败'); }
|
||||
finally { setSaving(false); }
|
||||
};
|
||||
const save = async () => {
|
||||
try {
|
||||
const value = await form.validateFields();
|
||||
const config = Object.fromEntries(Object.keys(INSPECTION_DEFAULTS).map(key => [key, value[key]]));
|
||||
setSaving(true);
|
||||
const body = { name: String(value.name).trim(), active: value.active === true, config, ...(editing?.id ? { expectedRowVersion: Number(editing.rowVersion || 0) } : {}) };
|
||||
if (editing?.id) await api.updateInspectionStrategy(String(editing.id), body); else await api.createInspectionStrategy(body);
|
||||
message.success('巡检策略已保存'); setEditing(null); form.resetFields(); await load();
|
||||
} catch (value) {
|
||||
if (value && typeof value === 'object' && 'errorFields' in value) return;
|
||||
if (!onUnauthorized(value)) message.error(value instanceof ApiError && value.status === 409 ? '巡检策略已被更新,请重新读取。' : value instanceof Error ? value.message : '巡检策略保存失败');
|
||||
} finally { setSaving(false); }
|
||||
};
|
||||
const run = async () => {
|
||||
if (!canRun || !releaseId) return;
|
||||
setRunning(true); setError('');
|
||||
try {
|
||||
const result = await api.runInspection(releaseId);
|
||||
setRuns(collectionItems(result));
|
||||
if (result.resultAvailable === false) message.warning('巡检已执行;当前授权不包含完整结果字段。');
|
||||
else message.success('巡检已执行,运行记录已刷新。');
|
||||
} catch (value) { if (!onUnauthorized(value)) setError(value instanceof Error ? value.message : '巡检执行失败'); }
|
||||
finally { setRunning(false); }
|
||||
};
|
||||
const strategyColumns: ColumnsType<Row> = [
|
||||
{ title: '策略名称', dataIndex: 'name', key: 'name', fixed: 'left', width: 220 },
|
||||
{ title: '状态', dataIndex: 'active', key: 'active', width: 100, render: value => <Tag color={value === true ? 'green' : 'default'}>{value === true ? '启用' : '停用'}</Tag> },
|
||||
{ title: '阈值配置', key: 'config', width: 620, render: (_, row) => { const config = obj(row.config); return `率降 ${config.rateDropEnabled === true ? `${text(config.rateDropPp)} pp` : '关闭'} · 缺陷 TOP ${config.defectTopEnabled === true ? `${text(config.minTopShare)} 占比` : '关闭'} · 产品 TOP ${config.productTopEnabled === true ? `${text(config.productTopLimit)} 项 / ${text(config.productTopMinShare)} 占比` : '关闭'} · 新对象 ${config.newObjectEnabled === true ? `${text(config.newObjectMinRows)} 行` : '关闭'} · 连续恶化 ${config.sustainedWorseningEnabled === true ? `${text(config.sustainedWorseningMonths)} 月 / ${text(config.sustainedWorseningPp)} pp` : '关闭'} · 目标差距 ${config.targetGapEnabled === true ? `${text(config.targetGapPp)} pp` : '关闭'} · AI 下钻 ${config.aiDrilldownEnabled === true ? `启用(最多 ${text(config.aiMaxFindings)} 项)` : '关闭'}`; } },
|
||||
{ title: '更新时间', dataIndex: 'updatedAt', key: 'updatedAt', width: 190 },
|
||||
...(canManage ? [{ title: '操作', key: 'actions', width: 110, render: (_: unknown, row: Row) => <Button type="link" loading={saving} onClick={() => void openEditor(row)}>编辑</Button> } as ColumnsType<Row>[number]] : []),
|
||||
];
|
||||
const runColumns: ColumnsType<Row> = [
|
||||
{ title: '巡检时间', dataIndex: 'createdAt', key: 'createdAt', width: 190 },
|
||||
{ title: '策略', dataIndex: 'strategyName', key: 'strategyName', width: 200 },
|
||||
{ title: '状态', dataIndex: 'status', key: 'status', width: 125, render: value => <Tag color={String(value).toUpperCase().includes('FAIL') ? 'red' : 'blue'}>{text(value)}</Tag> },
|
||||
{ title: '结果状态', key: 'result', width: 300, render: (_, row) => { const result = obj(row.result); const findings = rows(result.findings); return row.result === undefined ? text(row.errorCode, '受权限限制或未返回结果') : `发现项 ${findings.length} · 确定性 ${result.deterministic === true ? '是' : result.deterministic === false ? '否' : '—'} · AI 下钻 ${drilldownStatusText(result.aiDrilldownStatus)}`; } },
|
||||
{ title: '操作', key: 'actions', width: 100, render: (_, row) => <Button type="link" onClick={() => setSelectedRun(row)}>查看结果</Button> },
|
||||
];
|
||||
const metricFields: Array<{ key: string; label: string; min: number; max: number; step?: number }> = [
|
||||
{ key: 'rateDropPp', label: '合格率下降阈值(百分点)', min: 0, max: 100, step: 0.1 },
|
||||
{ key: 'minTopShare', label: '缺陷 TOP 最低占比', min: 0, max: 1, step: 0.01 },
|
||||
{ key: 'minStageRows', label: '阶段最少样本行数', min: 1, max: 100000 },
|
||||
{ key: 'quietPeriodHours', label: '重复告警静默(小时)', min: 0, max: 8760 },
|
||||
{ key: 'productTopLimit', label: '产品 TOP 数量', min: 1, max: 100 },
|
||||
{ key: 'productTopMinShare', label: '产品 TOP 最低占比', min: 0, max: 1, step: 0.01 },
|
||||
{ key: 'newObjectMinRows', label: '新对象最少行数', min: 1, max: 100000 },
|
||||
{ key: 'sustainedWorseningMonths', label: '连续恶化月数', min: 2, max: 24 },
|
||||
{ key: 'sustainedWorseningPp', label: '连续恶化阈值(百分点)', min: 0, max: 100, step: 0.1 },
|
||||
{ key: 'targetGapPp', label: '目标差距阈值(百分点)', min: 0, max: 100, step: 0.1 },
|
||||
{ key: 'aiMaxFindings', label: 'AI 下钻最多发现项', min: 1, max: 3 },
|
||||
];
|
||||
const booleanFields: Array<[string, string]> = [
|
||||
['rateDropEnabled', '合格率下降'], ['defectTopEnabled', '缺陷 TOP'], ['productTopEnabled', '产品 TOP'], ['newObjectEnabled', '新对象'], ['sustainedWorseningEnabled', '连续恶化'], ['targetGapEnabled', '目标差距'], ['aiDrilldownEnabled', '受控 AI 下钻'],
|
||||
];
|
||||
const selectedResult = obj(selectedRun?.result);
|
||||
const findingRows = rows(selectedResult.findings);
|
||||
const ruleRows = rows(selectedResult.rules).map(rule => ({ ...rule, reason: text(rule.reason, String(rule.status).toUpperCase() === 'UNAVAILABLE' ? '服务端标记为数据或适用条件不足,未返回具体原因' : '—') }));
|
||||
const coverage = obj(selectedResult.coverage);
|
||||
const missingStageRows = rows(coverage.missingStages);
|
||||
const sourceMonthRows = rows(coverage.sourceMonths);
|
||||
const drilldownRows = rows(selectedResult.aiDrilldowns);
|
||||
const drilldown = drilldownRows[0] || {
|
||||
sessionId: selectedResult.analysisSessionId,
|
||||
turnId: selectedResult.analysisTurnId,
|
||||
status: selectedResult.aiDrilldownStatus,
|
||||
findings: selectedResult.aiDrilldownFindings,
|
||||
};
|
||||
const findingTypeLabel = (value: unknown) => ({ RATE_DROP: '合格率下降', SCRAP_TOP: '缺陷 TOP', PRODUCT_SCRAP_TOP: '产品 TOP', SUSTAINED_WORSENING: '连续恶化', NEW_PRODUCT_OBJECT: '新产品对象', TARGET_GAP: '目标差距' } as Record<string, string>)[String(value)] || text(value);
|
||||
const severityLabel = (value: unknown) => ({ HIGH: '高', MEDIUM: '中', LOW: '低' } as Record<string, string>)[String(value)] || text(value);
|
||||
const findingColumns: ColumnsType<Row> = [
|
||||
{ title: '发现类型', dataIndex: 'type', key: 'type', width: 170, render: findingTypeLabel },
|
||||
{ title: '对象 / 指标', dataIndex: 'subject', key: 'subject', width: 230 },
|
||||
{ title: '级别', dataIndex: 'severity', key: 'severity', width: 85, render: value => <Tag color={String(value).toUpperCase() === 'HIGH' ? 'red' : 'gold'}>{severityLabel(value)}</Tag> },
|
||||
{ title: '发现说明', dataIndex: 'summary', key: 'summary', width: 420 },
|
||||
];
|
||||
const ruleColumns: ColumnsType<Row> = [
|
||||
{ title: '检查规则', dataIndex: 'id', key: 'id', width: 190 },
|
||||
{ title: '状态', dataIndex: 'status', key: 'status', width: 140, render: value => <Tag color={String(value).toUpperCase() === 'AVAILABLE' ? 'green' : String(value).toUpperCase() === 'UNAVAILABLE' ? 'gold' : 'default'}>{String(value).toUpperCase() === 'AVAILABLE' ? '可检查' : String(value).toUpperCase() === 'UNAVAILABLE' ? '数据不足' : String(value).toUpperCase() === 'NO_FINDINGS' ? '未发现异常' : String(value).toUpperCase() === 'DISABLED' ? '已关闭' : text(value)}</Tag> },
|
||||
{ title: '发现数', dataIndex: 'findingCount', key: 'findingCount', width: 95, align: 'right' },
|
||||
{ title: '未具备数据 / 原因', dataIndex: 'reason', key: 'reason', width: 440 },
|
||||
];
|
||||
const aiFindingRows = rows(drilldown.findings);
|
||||
const aiFindingColumns: ColumnsType<Row> = [
|
||||
{ title: '发现类型', dataIndex: 'type', key: 'type', width: 190, render: findingTypeLabel },
|
||||
{ title: '对象', dataIndex: 'subject', key: 'subject', width: 320 },
|
||||
{ title: '级别', dataIndex: 'severity', key: 'severity', width: 90, render: severityLabel },
|
||||
];
|
||||
const sessionIdForLink = text(drilldown.sessionId || selectedResult.analysisSessionId, '');
|
||||
const turnIdForLink = text(drilldown.turnId || selectedResult.analysisTurnId, '');
|
||||
return <section className="panel section-panel completion-tools">
|
||||
<div className="completion-panel-heading"><div><strong>质量巡检策略与运行记录</strong><span>策略阈值由服务端执行;运行结果受当前用户数据权限约束</span></div><div className="completion-actions"><Button icon={<ReloadOutlined />} onClick={() => { void load(); void loadRuns(); }}>刷新</Button>{canManage && <Button onClick={() => void openEditor()}>新建策略</Button>}</div></div>
|
||||
{!canManage && <Alert showIcon type="info" message="当前账号无巡检策略维护权限" description="服务端仅向授权角色返回可管理策略。" />}
|
||||
{error && <ErrorPanel title="巡检数据读取或执行失败" error={error} onRetry={() => { void load(); void loadRuns(); }} />}
|
||||
{loading ? <div className="completion-loading"><Spin />读取巡检策略…</div> : canManage ? strategies.length ? <Table size="small" bordered columns={strategyColumns} dataSource={strategies} rowKey={row => String(row.id)} pagination={false} scroll={{ x: 1300 }} /> : <Empty description="服务端当前没有已登记的巡检策略" /> : null}
|
||||
<div className="completion-filter-row">{canRun && <Button type="primary" loading={running} disabled={!releaseId} onClick={() => void run()}>对当前数据执行巡检</Button>}</div>
|
||||
{!canRun && <Alert showIcon type="info" message="当前账号不能执行巡检" description="运行和结果查看需要服务端授权的质量查看或业务分析角色及明细查询权限。" />}
|
||||
{canRun && (runs.length ? <Table size="small" bordered columns={runColumns} dataSource={runs} rowKey={row => String(row.id)} pagination={{ pageSize: 8, showSizeChanger: false }} scroll={{ x: 1120 }} /> : <Empty description={releaseId ? '当前数据尚无巡检运行记录' : '当前还没有可巡检的数据'} />)}
|
||||
<Modal className="management-modal" open={editing !== null} title={editing?.id ? `编辑巡检策略 · ${text(editing.name)}` : '新建巡检策略'} okText="保存策略" confirmLoading={saving} onCancel={() => { setEditing(null); form.resetFields(); }} onOk={() => void save()} width={Math.min(820, window.innerWidth - 24)}>
|
||||
<Form form={form} layout="vertical"><Form.Item name="name" label="策略名称" rules={[{ required: true, whitespace: true }]}><Input maxLength={100} /></Form.Item><Form.Item name="active" label="启用策略" valuePropName="checked"><Switch checkedChildren="启用" unCheckedChildren="停用" /></Form.Item><h3>巡检规则</h3><div className="governance-form-grid">{booleanFields.map(([key, label]) => <Form.Item key={key} name={key} label={label} valuePropName="checked"><Switch /></Form.Item>)}{metricFields.map(field => <Form.Item key={field.key} name={field.key} label={field.label} rules={[{ required: true }]}><InputNumber min={field.min} max={field.max} step={field.step} style={{ width: '100%' }} /></Form.Item>)}</div><p className="completion-note">阈值范围由服务端校验;保存后对后续巡检生效。</p></Form><Alert showIcon type="info" message="受控 AI 下钻" description="启用后仅为巡检发现创建绑定当前用户、当前数据与授权范围的持久化分析轮次;模型不接收业务数据行或业务数值。最多选择 1–3 项。" />
|
||||
</Modal>
|
||||
<Drawer className="management-drawer" open={selectedRun !== null} title="巡检运行结果" width={Math.min(820, window.innerWidth)} onClose={() => setSelectedRun(null)}>{selectedRun && <><div className="governance-monitor-grid"><div><small>状态</small><strong>{text(selectedRun.status)}</strong></div><div><small>适用数据</small><strong>当前数据</strong></div><div><small>创建时间</small><strong>{text(selectedRun.createdAt)}</strong></div><div><small>完成时间</small><strong>{text(selectedRun.completedAt)}</strong></div></div>{selectedRun.error && <Alert showIcon type="error" message={text(selectedRun.errorCode, '巡检错误')} description={text(selectedRun.error)} />}{selectedRun.result === undefined ? <Alert showIcon type="warning" message="结果字段未返回" description="当前账号可能没有完整明细权限,或服务端运行尚未产出结果。" /> : <>
|
||||
<p className="completion-note">确定性结果:{selectedResult.deterministic === true ? '是' : selectedResult.deterministic === false ? '否' : '—'}</p>
|
||||
<h3>巡检发现项({findingRows.length})</h3>
|
||||
{findingRows.length ? <Table size="small" bordered dataSource={findingRows} rowKey={(row, index) => `${text(row.type)}-${text(row.subject)}-${index}`} pagination={false} columns={findingColumns} expandable={{ expandedRowRender: row => <><p>{text(row.summary)}</p><details><summary>查看核查依据</summary><pre className="json-result">{JSON.stringify(withoutSystemMetadata(row.evidence || {}), null, 2)}</pre></details></> }} scroll={{ x: 900 }} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="本次没有触发已配置巡检规则的发现项" />}
|
||||
<h3>规则覆盖与未满足条件</h3>
|
||||
{ruleRows.length ? <Table size="small" bordered dataSource={ruleRows} rowKey={(row, index) => `${text(row.id)}-${index}`} pagination={false} columns={ruleColumns} scroll={{ x: 870 }} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="服务端没有返回规则覆盖结果" />}
|
||||
<h3>来源覆盖</h3>
|
||||
<div className="governance-monitor-grid"><div><small>原始行</small><strong>{text(coverage.rawRows)}</strong></div><div><small>纳入计算</small><strong>{text(coverage.includedRows)}</strong></div><div><small>未分类排除</small><strong>{text(coverage.excludedBlankRows)}</strong></div><div><small>未映射行</small><strong>{text(coverage.unmappedRows)}</strong></div><div><small>项目组未配置</small><strong>{text(coverage.projectGroupUnconfiguredRows)}</strong></div></div>
|
||||
{missingStageRows.length > 0 && <><h4>缺少阶段来源</h4><Table size="small" bordered dataSource={missingStageRows} rowKey={(row, index) => `${text(row.year)}-${text(row.month)}-${text(row.stage)}-${index}`} pagination={false} columns={[{ title: '年份', dataIndex: 'year', key: 'year', width: 100 }, { title: '月份', dataIndex: 'month', key: 'month', width: 100, render: value => `${text(value)} 月` }, { title: '缺失阶段', dataIndex: 'stage', key: 'stage', width: 160, render: value => value === 'black' ? '黑片' : value === 'bright' ? '亮片' : text(value) }]} scroll={{ x: 380 }} /></>}
|
||||
{sourceMonthRows.length > 0 && <><h4>月度来源覆盖</h4><Table size="small" bordered dataSource={sourceMonthRows} rowKey={(row, index) => `${text(row.year)}-${text(row.month)}-${index}`} pagination={false} columns={[{ title: '年份', dataIndex: 'year', key: 'year', width: 100 }, { title: '月份', dataIndex: 'month', key: 'month', width: 100 }, { title: '黑片行数', dataIndex: 'blackRows', key: 'blackRows', align: 'right', width: 130 }, { title: '亮片行数', dataIndex: 'brightRows', key: 'brightRows', align: 'right', width: 130 }]} scroll={{ x: 500 }} /></>}
|
||||
<h3>受控 AI 下钻</h3>
|
||||
<div className="inspection-ai-summary"><Tag color={['COMPLETED'].includes(String(drilldown.status || selectedResult.aiDrilldownStatus).toUpperCase()) ? 'green' : ['FAILED', 'BLOCKED_AUTHORIZATION'].includes(String(drilldown.status || selectedResult.aiDrilldownStatus).toUpperCase()) ? 'red' : 'blue'}>{drilldownStatusText(drilldown.status || selectedResult.aiDrilldownStatus)}</Tag><span>{text(selectedResult.aiDrilldownQuestion, '基于巡检时的当前数据与服务端受控查询执行。')}</span>{sessionIdForLink && turnIdForLink && <Button type="link" href={analysisDeepLink(sessionIdForLink, turnIdForLink)}>在智能分析中继续查看</Button>}</div>
|
||||
{aiFindingRows.length > 0 && <Table size="small" bordered dataSource={aiFindingRows} rowKey={(row, index) => `${text(row.type)}-${text(row.subject)}-${index}`} pagination={false} columns={aiFindingColumns} scroll={{ x: 620 }} />}
|
||||
<details><summary>查看其他运行信息</summary><pre className="json-result">{JSON.stringify(withoutSystemMetadata(selectedResult), null, 2)}</pre></details>
|
||||
</>}</>}</Drawer>
|
||||
</section>;
|
||||
}
|
||||
|
||||
export function SourceGovernancePanel({ user, currentReleaseId, onUnauthorized }: { user: AuthUser; currentReleaseId: string | null; onUnauthorized: (error: unknown) => boolean }) {
|
||||
const { message } = App.useApp();
|
||||
const [protocols, setProtocols] = useState<Row[]>([]);
|
||||
const [coverage, setCoverage] = useState<Row | null>(null);
|
||||
const [sourceChanges, setSourceChanges] = useState<Row[]>([]);
|
||||
const [sourceItems, setSourceItems] = useState<SourceItem[]>([]);
|
||||
const [documents, setDocuments] = useState<Row[]>([]);
|
||||
const [revisions, setRevisions] = useState<Row[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
const [protocolOpen, setProtocolOpen] = useState(false);
|
||||
const [changeOpen, setChangeOpen] = useState(false);
|
||||
const [reviewItem, setReviewItem] = useState<Row | null>(null);
|
||||
const [resolveItem, setResolveItem] = useState<SourceItem | null>(null);
|
||||
const [evidenceRevision, setEvidenceRevision] = useState('');
|
||||
const [evidence, setEvidence] = useState<Row | null>(null);
|
||||
const [actionBusy, setActionBusy] = useState('');
|
||||
const [protocolForm] = Form.useForm<Row>();
|
||||
const [changeForm] = Form.useForm<Row>();
|
||||
const [reviewForm] = Form.useForm<{ reason: string }>();
|
||||
const [resolveForm] = Form.useForm<Row>();
|
||||
const [tab, setTab] = useState('coverage');
|
||||
const canMaintain = user.roles.some(role => ['SYSTEM_ADMIN', 'DATA_MAINTAINER'].includes(role));
|
||||
const canReview = user.roles.some(role => ['SYSTEM_ADMIN', 'DATA_PUBLISHER'].includes(role));
|
||||
const canDownload = user.roles.some(role => ['SYSTEM_ADMIN', 'DATA_MAINTAINER', 'DATA_PUBLISHER', 'BUSINESS_ANALYST', 'QUALITY_VIEWER', 'AUDIT_VIEWER'].includes(role));
|
||||
const stage = Form.useWatch('stage', protocolForm);
|
||||
const changeType = Form.useWatch('type', changeForm);
|
||||
const resolveDecision = Form.useWatch('decision', resolveForm);
|
||||
|
||||
const load = async () => {
|
||||
setLoading(true);
|
||||
const failures: Record<string, string> = {};
|
||||
const results = await Promise.allSettled([
|
||||
api.governanceProtocols(), api.governanceCoverage(currentReleaseId || undefined), api.sourceChanges(), api.sources(), api.governanceSourceDocuments(),
|
||||
]);
|
||||
if (results[0].status === 'fulfilled') setProtocols(collectionItems(results[0].value)); else { if (!onUnauthorized(results[0].reason)) failures.protocols = results[0].reason instanceof Error ? results[0].reason.message : '协议读取失败'; }
|
||||
if (results[1].status === 'fulfilled') setCoverage(results[1].value); else { if (!onUnauthorized(results[1].reason)) failures.coverage = results[1].reason instanceof Error ? results[1].reason.message : '到齐矩阵读取失败'; }
|
||||
if (results[2].status === 'fulfilled') setSourceChanges(collectionItems(results[2].value)); else { if (!onUnauthorized(results[2].reason)) failures.changes = results[2].reason instanceof Error ? results[2].reason.message : '来源变更清单读取失败'; }
|
||||
if (results[3].status === 'fulfilled') setSourceItems(collectionItems(results[3].value)); else { if (!onUnauthorized(results[3].reason)) failures.candidates = results[3].reason instanceof Error ? results[3].reason.message : '候选文件读取失败'; }
|
||||
if (results[4].status === 'fulfilled') { setDocuments(collectionItems(results[4].value)); setRevisions(rows(results[4].value.revisions)); } else { if (!onUnauthorized(results[4].reason)) failures.documents = results[4].reason instanceof Error ? results[4].reason.message : '来源记录读取失败'; }
|
||||
setErrors(failures); setLoading(false);
|
||||
};
|
||||
useEffect(() => { void load(); }, [currentReleaseId]);
|
||||
|
||||
const submitProtocol = async () => {
|
||||
try {
|
||||
const value = await protocolForm.validateFields(); setActionBusy('protocol');
|
||||
const body: Row = {
|
||||
...value,
|
||||
...(String(value.sourceSlot || '').trim() ? {} : { sourceSlot: undefined }),
|
||||
stage: value.stage,
|
||||
year: Number(value.year), month: Number(value.month),
|
||||
requiredSheet: value.stage === 'black' ? '报废明细' : '明细',
|
||||
expected: value.expected !== false,
|
||||
applicable: value.applicable !== false,
|
||||
deadline: String(value.deadline || '').trim() || undefined,
|
||||
shardCode: String(value.shardCode || '').trim() || 'MAIN',
|
||||
reason: String(value.reason || '').trim(),
|
||||
};
|
||||
await api.createGovernanceProtocol(body); message.success('来源协议已保存'); setProtocolOpen(false); protocolForm.resetFields(); await load();
|
||||
} catch (value) { if (value && typeof value === 'object' && 'errorFields' in value) return; if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '协议保存失败'); }
|
||||
finally { setActionBusy(''); }
|
||||
};
|
||||
const submitChange = async () => {
|
||||
try {
|
||||
const value = await changeForm.validateFields(); setActionBusy('change');
|
||||
await api.createSourceChange({ ...value, reason: String(value.reason || '').trim(), idempotencyKey: crypto.randomUUID() });
|
||||
message.success('来源变更申请已提交,当前数据保持不变'); setChangeOpen(false); changeForm.resetFields(); await load();
|
||||
} catch (value) { if (value && typeof value === 'object' && 'errorFields' in value) return; if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '来源变更申请失败'); }
|
||||
finally { setActionBusy(''); }
|
||||
};
|
||||
const submitReview = async (approve: boolean) => {
|
||||
if (!reviewItem) return;
|
||||
try {
|
||||
const values = await reviewForm.validateFields(); setActionBusy(String(reviewItem.id));
|
||||
await api.reviewSourceChange(String(reviewItem.id), { approve, reason: values.reason.trim(), expectedRowVersion: Number(reviewItem.rowVersion || 0) });
|
||||
message.success(approve ? '变更申请已通过' : '变更申请已驳回'); setReviewItem(null); reviewForm.resetFields(); await load();
|
||||
} catch (value) { if (value && typeof value === 'object' && 'errorFields' in value) return; if (!onUnauthorized(value)) message.error(value instanceof ApiError && value.status === 409 ? '申请已被其他操作更新,请刷新后复核。' : value instanceof Error ? value.message : '审核失败'); if (value instanceof ApiError && value.status === 409) await load(); }
|
||||
finally { setActionBusy(''); }
|
||||
};
|
||||
const buildChange = async (item: Row) => {
|
||||
const id = String(item.id || ''); if (!id) return;
|
||||
setActionBusy(id);
|
||||
try {
|
||||
const result = await api.releases();
|
||||
await api.buildSourceChange(id, { expectedCurrentReleaseId: result.currentReleaseId ?? null, idempotencyKey: crypto.randomUUID() });
|
||||
message.success('来源变更处理已完成;请检查候选数据与校验状态。'); await load();
|
||||
} catch (value) { if (!onUnauthorized(value)) message.error(value instanceof ApiError && value.status === 409 ? '当前数据或申请状态已变化,请刷新核对。' : value instanceof Error ? value.message : '变更处理失败'); if (value instanceof ApiError && value.status === 409) await load(); }
|
||||
finally { setActionBusy(''); }
|
||||
};
|
||||
const resolveCandidate = async () => {
|
||||
if (!resolveItem) return;
|
||||
try {
|
||||
const value = await resolveForm.validateFields(); setActionBusy(resolveItem.id);
|
||||
await api.resolveSourceCandidate(resolveItem.id, { ...value, reason: String(value.reason || '').trim() });
|
||||
message.success('候选来源身份已裁决'); setResolveItem(null); resolveForm.resetFields(); await load();
|
||||
} catch (value) { if (value && typeof value === 'object' && 'errorFields' in value) return; if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '来源裁决失败'); }
|
||||
finally { setActionBusy(''); }
|
||||
};
|
||||
const showEvidence = async (id: string) => {
|
||||
setEvidenceRevision(id); setEvidence(null);
|
||||
try { setEvidence(await api.sourceRevisionEvidence(id)); }
|
||||
catch (value) { if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '证据读取失败'); }
|
||||
};
|
||||
const download = async (id: string) => {
|
||||
setActionBusy(id);
|
||||
try { showDownload(await api.downloadSourceRevision(id)); }
|
||||
catch (value) { if (!onUnauthorized(value)) message.error(value instanceof ApiError && value.status === 403 ? '当前账号无权下载此原始文件或文件超出组织范围。' : value instanceof Error ? value.message : '原文件下载失败'); }
|
||||
finally { setActionBusy(''); }
|
||||
};
|
||||
|
||||
const coverageItems = rows(coverage?.items);
|
||||
const coverageColumns: ColumnsType<Row> = [
|
||||
{ title: '来源槽位', dataIndex: 'sourceSlot', key: 'sourceSlot', fixed: 'left', width: 290 },
|
||||
{ title: '阶段', dataIndex: 'stage', key: 'stage', width: 85, render: value => value === 'black' ? '黑片' : value === 'bright' ? '亮片' : text(value) },
|
||||
{ title: '期间', key: 'period', width: 110, render: (_, row) => `${text(row.sourceYear)}-${String(row.sourceMonth ?? '').padStart(2, '0')}` },
|
||||
{ title: '预期', dataIndex: 'expected', key: 'expected', width: 80, render: value => value === true ? '是' : '否' },
|
||||
{ title: '已接收 / 已校验', key: 'received', align: 'right', width: 135, render: (_, row) => `${text(row.receivedCount, '0')} / ${text(row.validatedCount, '0')}` },
|
||||
{ title: '状态', dataIndex: 'status', key: 'status', width: 150, render: value => <Tag color={value === 'VALIDATED' ? 'green' : value === 'MISSING' ? 'red' : 'blue'}>{text(value)}</Tag> },
|
||||
{ title: '告警', key: 'alert', width: 120, render: (_, row) => row.blocking === true ? <Tag color="red">阻断</Tag> : row.overdue === true ? <Tag color="gold">逾期</Tag> : '—' },
|
||||
];
|
||||
const protocolColumns: ColumnsType<Row> = [
|
||||
{ title: '来源槽位', dataIndex: 'sourceSlot', key: 'sourceSlot', fixed: 'left', width: 270 },
|
||||
{ title: '阶段 / 期间', key: 'period', width: 130, render: (_, row) => `${text(row.stage)} · ${text(row.sourceYear)}-${String(row.sourceMonth ?? '').padStart(2, '0')}` },
|
||||
{ title: '范围 / 分片', key: 'scope', width: 170, render: (_, row) => `${text(row.scopeCode)} · ${text(row.shardCode, 'MAIN')}` },
|
||||
{ title: '来源模式', dataIndex: 'sourceMode', key: 'sourceMode', width: 160 },
|
||||
{ title: '工作表 / 文件规则', key: 'pattern', width: 210, render: (_, row) => `${text(row.requiredSheet)} · ${text(row.filenamePattern)}` },
|
||||
{ title: '状态', dataIndex: 'active', key: 'status', width: 100, render: value => value === true ? '启用' : '停用' },
|
||||
];
|
||||
const changeColumns: ColumnsType<Row> = [
|
||||
{ title: '申请类型', dataIndex: 'requestType', key: 'requestType', width: 100, render: value => value === 'WITHDRAW' ? '撤销来源' : value === 'REVISION' ? '替换/补录来源' : text(value) },
|
||||
{ title: '来源文件', dataIndex: 'sourceFile', key: 'sourceFile', width: 210, render: (_, row) => text(row.sourceFile || row.sourceSlot, '来源文件') },
|
||||
{ title: '申请原因', dataIndex: 'reason', key: 'reason', width: 270, ellipsis: true },
|
||||
{ title: '状态', dataIndex: 'status', key: 'status', width: 120, render: value => <Tag>{text(value)}</Tag> },
|
||||
{ title: '候选结果', key: 'result', width: 150, render: (_, row) => row.resultReleaseId ? '已生成候选' : row.importRunId ? '处理中' : '—' },
|
||||
{ title: '操作', key: 'actions', fixed: 'right', width: 220, render: (_, row) => <span className="completion-actions">
|
||||
{canReview && row.status === 'REQUESTED' && <Button type="link" onClick={() => { setReviewItem(row); reviewForm.resetFields(); }}>复核</Button>}
|
||||
{canReview && row.status === 'APPROVED' && <Button type="link" loading={actionBusy === String(row.id)} onClick={() => void buildChange(row)}>构建候选</Button>}
|
||||
</span> },
|
||||
];
|
||||
const revisionColumns: ColumnsType<Row> = [
|
||||
{ title: '原始文件', dataIndex: 'sourceFile', key: 'sourceFile', fixed: 'left', width: 260 },
|
||||
{ title: '来源槽位', dataIndex: 'sourceSlot', key: 'sourceSlot', width: 250, render: value => text(value, '关联来源') },
|
||||
{ title: 'SHA-256', dataIndex: 'sha256', key: 'sha256', width: 290, ellipsis: true },
|
||||
{ title: '文件大小', dataIndex: 'fileSize', key: 'fileSize', width: 110, align: 'right', render: value => typeof value === 'number' ? `${(value / 1024).toFixed(1)} KB` : text(value) },
|
||||
{ title: '归档状态', dataIndex: 'status', key: 'status', width: 110 },
|
||||
{ title: '接收时间', dataIndex: 'receivedAt', key: 'receivedAt', width: 190 },
|
||||
{ title: '操作', key: 'actions', fixed: 'right', width: 190, render: (_, row) => {
|
||||
const id = String(row.id || '');
|
||||
return <span className="completion-actions"><Button type="link" disabled={!id} onClick={() => void showEvidence(id)}>查看证据</Button>{canDownload && <Button type="link" icon={<DownloadOutlined />} loading={actionBusy === id} disabled={!id} onClick={() => void download(id)}>下载原文件</Button>}</span>;
|
||||
} },
|
||||
];
|
||||
const conflictCandidates = sourceItems.filter(item => ['UNIDENTIFIED', 'COVERAGE_CONFLICT'].includes(String(item.status).toUpperCase()));
|
||||
const documentChoices = documents.map(item => ({ label: text(item.sourceFile || item.sourceSlot, '来源文档'), value: String(item.id || '') })).filter(item => item.value);
|
||||
const candidateChoices = sourceItems.map(item => ({ label: `${item.sourceFile} · ${item.year}-${String(item.month).padStart(2, '0')} · ${item.status}`, value: item.id }));
|
||||
|
||||
return <section className="panel section-panel governance-source-panel">
|
||||
<div className="completion-panel-heading"><div><strong>来源协议、覆盖与变更</strong><span>当前数据的来源覆盖、到齐状态和原文件下载权限由服务端控制</span></div><div className="completion-actions"><Button icon={<ReloadOutlined />} loading={loading} onClick={() => void load()}>刷新治理信息</Button>{canMaintain && <><Button onClick={() => { protocolForm.setFieldsValue({ stage: 'black', year: new Date().getFullYear(), month: 1, scopeCode: 'ALL', shardCode: 'MAIN', sourceMode: 'MONTHLY_SNAPSHOT', filenamePattern: '*.xlsx', applicable: true, expected: true }); setProtocolOpen(true); }}>登记来源协议</Button><Button type="primary" onClick={() => { changeForm.setFieldsValue({ type: 'REVISION' }); setChangeOpen(true); }}>申请来源变更 / 撤销</Button></>}</div></div>
|
||||
<ErrorPanel title="协议读取失败" error={errors.protocols || ''} onRetry={() => void load()} /><ErrorPanel title="到齐矩阵读取失败" error={errors.coverage || ''} onRetry={() => void load()} /><ErrorPanel title="来源记录读取失败" error={errors.documents || ''} onRetry={() => void load()} />
|
||||
<Tabs activeKey={tab} onChange={setTab} items={[
|
||||
{ key: 'coverage', label: '到齐与告警', children: <div className="governance-panel-body"><div className="governance-status-strip"><span>适用数据 <strong>当前数据</strong></span><Tag color={coverage?.complete === true ? 'green' : 'red'}>{coverage?.complete === true ? '覆盖完整' : coverage?.complete === false ? '覆盖未齐' : '未返回'}</Tag></div>{coverageItems.length ? <Table size="small" bordered columns={coverageColumns} dataSource={coverageItems} rowKey={row => String(row.protocolId || row.sourceSlot)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 980 }} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前数据没有已登记的来源协议覆盖项" />}</div> },
|
||||
{ key: 'protocols', label: `来源协议(${protocols.length})`, children: <div className="governance-panel-body">{protocols.length ? <Table size="small" bordered columns={protocolColumns} dataSource={protocols} rowKey={row => String(row.id)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1120 }} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="服务端尚未登记来源协议" />}</div> },
|
||||
{ key: 'changes', label: `来源变更与撤销(${sourceChanges.length})`, children: <div className="governance-panel-body">{conflictCandidates.length > 0 && <Alert showIcon type="warning" message={`${conflictCandidates.length} 个来源身份待裁决`} description={<span>{conflictCandidates.map(item => <Button type="link" key={item.id} onClick={() => { setResolveItem(item); resolveForm.setFieldsValue({ decision: 'REPLACE' }); }}>{item.sourceFile} · 裁决</Button>)}</span>} />}{errors.changes ? <Alert type="error" message={errors.changes} /> : sourceChanges.length ? <Table size="small" bordered columns={changeColumns} dataSource={sourceChanges} rowKey={row => String(row.id)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1080 }} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无来源变更或撤销申请" />}</div> },
|
||||
{ key: 'revisions', label: `原文件记录与证据(${revisions.length})`, children: <div className="governance-panel-body">{revisions.length ? <Table size="small" bordered columns={revisionColumns} dataSource={revisions} rowKey={row => String(row.id)} pagination={{ pageSize: 10, showSizeChanger: false }} scroll={{ x: 1280 }} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="服务端尚未返回归档原文件记录" />}</div> },
|
||||
]} />
|
||||
<Modal className="management-modal" open={protocolOpen} title="登记来源协议" width={760} okText="保存协议" confirmLoading={actionBusy === 'protocol'} onCancel={() => setProtocolOpen(false)} onOk={() => void submitProtocol()}>
|
||||
<Alert showIcon type="info" message="协议定义用于来源身份和到齐校验" description="当前解析器仅验证月度快照和分片快照;来源槽位由阶段、期间、范围和分片共同确定。" />
|
||||
<Form form={protocolForm} layout="vertical"><div className="governance-form-grid"><Form.Item name="stage" label="阶段" rules={[{ required: true }]}><Select options={[{ label: '黑片', value: 'black' }, { label: '亮片', value: 'bright' }]} /></Form.Item><Form.Item name="year" label="年份" rules={[{ required: true }]}><InputNumber min={1900} max={2100} /></Form.Item><Form.Item name="month" label="月份" rules={[{ required: true }]}><InputNumber min={1} max={12} /></Form.Item><Form.Item name="scopeCode" label="范围编码" rules={[{ required: true, whitespace: true }]}><Input placeholder="如 ALL 或部门编码" /></Form.Item><Form.Item name="shardCode" label="分片编码"><Input placeholder="MAIN" /></Form.Item><Form.Item name="sourceMode" label="来源模式" rules={[{ required: true }]}><Select options={[{ label: '月度完整快照', value: 'MONTHLY_SNAPSHOT' }, { label: '完整分片快照', value: 'SHARD_SNAPSHOT' }]} /></Form.Item><Form.Item name="filenamePattern" label="文件名规则" rules={[{ required: true }]}><Input placeholder="*.xlsx" /></Form.Item><Form.Item name="sourceSlot" label="来源槽位(可选)"><Input placeholder="留空由服务端按身份生成" /></Form.Item><Form.Item name="deadline" label="到齐截止时间(ISO,可选)"><Input placeholder="2026-11-05T17:00:00Z" /></Form.Item></div><Form.Item name="applicable" valuePropName="checked"><Checkbox>该阶段适用</Checkbox></Form.Item><Form.Item name="expected" valuePropName="checked"><Checkbox>列为预期到齐来源</Checkbox></Form.Item><Form.Item name="reason" label="登记原因" rules={[{ required: true, whitespace: true }]}><Input.TextArea rows={2} maxLength={300} /></Form.Item><small className="completion-note">解析工作表将使用已验证名称:{stage === 'black' ? '报废明细' : '明细'}。</small></Form>
|
||||
</Modal>
|
||||
<Modal className="management-modal" open={changeOpen} title="申请来源变更或撤销" okText="提交申请" confirmLoading={actionBusy === 'change'} onCancel={() => setChangeOpen(false)} onOk={() => void submitChange()}>
|
||||
<Form form={changeForm} layout="vertical"><Form.Item name="type" label="申请类型" rules={[{ required: true }]}><Select options={[{ label: '替换/补录来源', value: 'REVISION' }, { label: '撤销当前来源', value: 'WITHDRAW' }]} /></Form.Item><Form.Item name="sourceDocumentId" label="当前已归档来源" rules={[{ required: true }]}><Select {...readableSelectPopup} showSearch optionFilterProp="label" options={documentChoices} placeholder="选择来源文档" /></Form.Item>{changeType === 'REVISION' && <Form.Item name="sourceCandidateId" label="待替换候选文件" rules={[{ required: true }]}><Select {...readableSelectPopup} showSearch optionFilterProp="label" options={candidateChoices} placeholder="选择已扫描或上传的候选文件" /></Form.Item>}<Form.Item name="reason" label="申请原因" rules={[{ required: true, whitespace: true }]}><Input.TextArea rows={3} maxLength={400} showCount /></Form.Item></Form>
|
||||
</Modal>
|
||||
<Modal className="management-modal" open={Boolean(reviewItem)} title="复核来源变更申请" okText="通过申请" confirmLoading={Boolean(actionBusy)} onCancel={() => setReviewItem(null)} onOk={() => void submitReview(true)} footer={(_, { OkBtn, CancelBtn }) => <><CancelBtn /><Button danger disabled={Boolean(actionBusy)} onClick={() => void submitReview(false)}>驳回申请</Button><OkBtn /></>}>
|
||||
<p>类型:{text(reviewItem?.requestType)} · 来源:{text(documents.find(item => String(item.id) === String(reviewItem?.sourceDocumentId))?.sourceFile || reviewItem?.sourceSlot, '当前来源')}</p><p>申请原因:{text(reviewItem?.reason)}</p><Form form={reviewForm} layout="vertical"><Form.Item name="reason" label="审核理由" rules={[{ required: true, whitespace: true }]}><Input.TextArea rows={3} maxLength={400} /></Form.Item></Form>
|
||||
</Modal>
|
||||
<Modal className="management-modal" open={Boolean(resolveItem)} title="裁决来源身份与覆盖" okText="提交裁决" confirmLoading={Boolean(actionBusy)} onCancel={() => setResolveItem(null)} onOk={() => void resolveCandidate()}>
|
||||
<p>候选文件:{resolveItem?.sourceFile} · 状态 {resolveItem?.status} · SHA-256 {resolveItem?.sha256}</p><Form form={resolveForm} layout="vertical"><Form.Item name="decision" label="处理方式" rules={[{ required: true }]}><Select options={[{ label: '替换同一来源', value: 'REPLACE' }, { label: '确认为合法分片', value: 'LEGAL_SHARD' }, { label: '退回候选', value: 'RETURN' }]} /></Form.Item>{resolveDecision !== 'RETURN' && <Form.Item name="protocolId" label="适用协议" rules={[{ required: true, message: '请选择协议' }]}><Select options={protocols.filter(item => item.active === true).map(item => ({ value: String(item.id), label: text(item.sourceSlot) }))} /></Form.Item>}<Form.Item name="reason" label="处理理由" rules={[{ required: true, whitespace: true }]}><Input.TextArea rows={3} maxLength={400} /></Form.Item></Form>
|
||||
</Modal>
|
||||
<Drawer className="management-drawer" open={Boolean(evidenceRevision)} title="原文件与处理证据" width={Math.min(850, window.innerWidth)} onClose={() => { setEvidenceRevision(''); setEvidence(null); }}>
|
||||
{evidence ? <><div className="governance-evidence-summary"><strong>{text(obj(evidence.revision).sourceFile)}</strong><span>SHA-256 {text(obj(evidence.revision).sha256)}</span><span>归档状态 {text(obj(evidence.revision).status)}</span><span>接收时间 {text(obj(evidence.revision).receivedAt)}</span></div>{rows(evidence.builds).length ? <Table size="small" bordered dataSource={rows(evidence.builds)} rowKey={row => String(row.id)} pagination={false} columns={[{ title: '处理状态', dataIndex: 'status', key: 'status', width: 120 }, { title: '行数 / 拒绝', key: 'counts', align: 'right', render: (_, row) => `${text(row.rowCount)} / ${text(row.rejectedCount)}` }, { title: '分量摘要', dataIndex: 'componentSummary', key: 'componentSummary', render: value => text(value) }]} scroll={{ x: 520 }} /> : <Empty description="该来源尚未返回处理记录" />}{canDownload && <Button type="primary" icon={<DownloadOutlined />} loading={actionBusy === evidenceRevision} onClick={() => void download(evidenceRevision)}>下载受权原文件</Button>}</> : <div className="completion-loading"><Spin />读取来源记录…</div>}
|
||||
</Drawer>
|
||||
</section>;
|
||||
}
|
||||
|
||||
export function CostConfigurationPanel({ user, onUnauthorized }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean }) {
|
||||
const { message } = App.useApp();
|
||||
const [items, setItems] = useState<Row[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [editing, setEditing] = useState<Row | null>(null);
|
||||
const [validation, setValidation] = useState<Row | null>(null);
|
||||
const [form] = Form.useForm<Row>();
|
||||
const canManage = user.roles.some(role => ['SYSTEM_ADMIN', 'DATA_MAINTAINER', 'RULE_MAINTAINER'].includes(role));
|
||||
const load = async () => {
|
||||
setLoading(true);
|
||||
try { setItems(collectionItems(await api.costConfigurations())); setError(''); }
|
||||
catch (value) { if (!onUnauthorized(value)) setError(value instanceof Error ? value.message : '成本来源配置读取失败'); }
|
||||
finally { setLoading(false); }
|
||||
};
|
||||
useEffect(() => { void load(); }, []);
|
||||
const open = (item?: Row) => {
|
||||
setEditing(item || {}); setValidation(null);
|
||||
const definition = obj(item?.definition);
|
||||
form.setFieldsValue({ name: text(item?.name, ''), reason: '', sources: rows(definition.sources) });
|
||||
};
|
||||
const save = async () => {
|
||||
try {
|
||||
const values = await form.validateFields(); setBusy(true);
|
||||
const body = { name: String(values.name || '').trim(), reason: String(values.reason || '').trim(), definition: { sources: values.sources || [] }, ...(editing?.id ? { expectedRowVersion: Number(editing.rowVersion || 0) } : {}) };
|
||||
if (editing?.id) await api.updateCostConfiguration(String(editing.id), body); else await api.createCostConfiguration(body);
|
||||
message.success('成本来源与公式基线已保存;未执行成本金额计算'); setEditing(null); await load();
|
||||
} catch (value) { if (value && typeof value === 'object' && 'errorFields' in value) return; if (!onUnauthorized(value)) message.error(value instanceof ApiError && value.status === 409 ? '配置已被其他操作更新,请刷新后重新编辑。' : value instanceof Error ? value.message : '成本配置保存失败'); }
|
||||
finally { setBusy(false); }
|
||||
};
|
||||
const validate = async (item: Row) => {
|
||||
setBusy(true);
|
||||
try { const result = await api.validateCostConfiguration(String(item.id), { expectedRowVersion: Number(item.rowVersion || 0) }); setValidation(obj(result.validation)); await load(); }
|
||||
catch (value) { if (!onUnauthorized(value)) message.error(value instanceof ApiError && value.status === 409 ? '配置已被其他操作更新,请刷新后重试。' : value instanceof Error ? value.message : '来源配置校验失败'); }
|
||||
finally { setBusy(false); }
|
||||
};
|
||||
const columns: ColumnsType<Row> = [
|
||||
{ title: '配置名称', dataIndex: 'name', key: 'name', fixed: 'left', width: 220 },
|
||||
{ title: '状态', dataIndex: 'status', key: 'status', width: 150, render: value => <Tag>{text(value)}</Tag> },
|
||||
{ title: '来源数', key: 'sources', align: 'right', width: 90, render: (_, row) => rows(obj(row.definition).sources).length },
|
||||
{ title: '操作', key: 'actions', width: 180, render: (_, row) => <span className="completion-actions"><Button type="link" disabled={!canManage || row.status !== 'DRAFT'} onClick={() => open(row)}>编辑</Button><Button type="link" loading={busy} onClick={() => void validate(row)}>校验</Button></span> },
|
||||
];
|
||||
return <section className="panel section-panel completion-tools">
|
||||
<div className="completion-panel-heading"><div><strong>成本来源与计算基线登记</strong><span>仅记录来源字段、单位、审批引用与原公式;成本金额和降本计算保持关闭</span></div><div className="completion-actions"><Button icon={<ReloadOutlined />} onClick={() => void load()}>刷新</Button>{canManage && <Button type="primary" onClick={() => open()}>新建成本来源配置</Button>}</div></div>
|
||||
{error && <Alert showIcon type="error" message="成本来源配置不可用" description={error} />}
|
||||
{loading ? <div className="completion-loading"><Spin />读取成本来源配置…</div> : items.length ? <Table size="small" bordered columns={columns} dataSource={items} rowKey={row => String(row.id)} pagination={false} scroll={{ x: 740 }} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="服务端当前没有成本来源登记" />}
|
||||
{validation && <Alert showIcon type={validation.valid === true ? 'success' : 'warning'} message={text(validation.readiness, validation.valid === true ? '来源字段已验证' : '来源信息需补充')} description={`错误 ${rows(validation.errors).length} 项 · 成本金额计算:${validation.calculationEnabled === false ? '未启用' : '未由服务端确认'}`} />}
|
||||
<Modal className="management-modal" open={Boolean(editing)} title={editing?.id ? '编辑成本来源配置' : '登记成本来源配置'} width={900} okText="保存配置" confirmLoading={busy} onCancel={() => setEditing(null)} onOk={() => void save()}>
|
||||
<Alert showIcon type="info" message="成本核算未启用" description="此表单只登记依赖和原公式,不接受成本金额,不生成成本或降本结论。" />
|
||||
<Form form={form} layout="vertical"><Form.Item name="name" label="配置名称" rules={[{ required: true, whitespace: true }]}><Input maxLength={180} /></Form.Item><Form.List name="sources">{(fields, { add, remove }) => <div className="target-rule-list"><div className="resource-toolbar"><strong>成本来源字段映射</strong><Button onClick={() => add({ unit: 'CNY/kg' })}>添加来源</Button></div>{fields.map(field => <div className="target-rule-row" key={field.key}><Form.Item {...field} name={[field.name, 'sourceReference']} label="来源引用" rules={[{ required: true, whitespace: true }]}><Input /></Form.Item><Form.Item {...field} name={[field.name, 'objectCode']} label="对象编码" rules={[{ required: true, whitespace: true }]}><Input /></Form.Item><Form.Item {...field} name={[field.name, 'costField']} label="成本字段" rules={[{ required: true, whitespace: true }]}><Input /></Form.Item><Form.Item {...field} name={[field.name, 'unit']} label="单位" rules={[{ required: true, whitespace: true }]}><Input /></Form.Item><Form.Item {...field} name={[field.name, 'currency']} label="币种"><Input placeholder="CNY" /></Form.Item><Form.Item {...field} name={[field.name, 'approvalReference']} label="审批引用"><Input /></Form.Item><Form.Item {...field} name={[field.name, 'originalFormula']} label="原公式"><Input /></Form.Item><Form.Item {...field} name={[field.name, 'fromMonth']} label="起始月 YYYY-MM"><Input /></Form.Item><Form.Item {...field} name={[field.name, 'toMonth']} label="结束月 YYYY-MM"><Input /></Form.Item><Button danger onClick={() => remove(field.name)}>移除</Button></div>)}</div>}</Form.List><Form.Item name="reason" label="登记原因" rules={[{ required: true, whitespace: true }]}><Input.TextArea rows={2} maxLength={300} /></Form.Item></Form>
|
||||
</Modal>
|
||||
</section>;
|
||||
}
|
||||
|
||||
export function BackupOperationsPanel({ user, onUnauthorized, onNavigate }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean; onNavigate?: () => void }) {
|
||||
const { message } = App.useApp();
|
||||
const [data, setData] = useState<Row | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [planOpen, setPlanOpen] = useState(false);
|
||||
const [form] = Form.useForm<Row>();
|
||||
const canManage = user.roles.some(role => ['SYSTEM_ADMIN', 'SYSTEM_OPERATOR'].includes(role));
|
||||
const load = async () => { setLoading(true); try { setData(await api.governanceBackups()); setError(''); } catch (value) { if (!onUnauthorized(value)) setError(value instanceof Error ? value.message : '备份状态读取失败'); } finally { setLoading(false); } };
|
||||
useEffect(() => { void load(); }, []);
|
||||
const runJob = async (type: string, backupId?: string) => {
|
||||
setBusy(true);
|
||||
try { await api.createBackupJob({ type, ...(backupId ? { backupId } : {}), idempotencyKey: crypto.randomUUID() }); message.success('备份任务已登记'); await load(); }
|
||||
catch (value) { if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '备份任务提交失败'); }
|
||||
finally { setBusy(false); }
|
||||
};
|
||||
const savePlan = async () => {
|
||||
try { const value = await form.validateFields(); setBusy(true); await api.updateBackupPlan({ ...value, reason: String(value.reason || '').trim(), expectedRowVersion: Number(obj(data?.plan).rowVersion || 0) }); message.success('备份计划已保存'); setPlanOpen(false); await load(); }
|
||||
catch (value) { if (value && typeof value === 'object' && 'errorFields' in value) return; if (!onUnauthorized(value)) message.error(value instanceof ApiError && value.status === 409 ? '备份计划已被更新,请刷新后重试。' : value instanceof Error ? value.message : '保存备份计划失败'); }
|
||||
finally { setBusy(false); }
|
||||
};
|
||||
const plan = obj(data?.plan); const backups = rows(data?.items);
|
||||
const columns: ColumnsType<Row> = [
|
||||
{ title: '备份时间', dataIndex: 'createdAt', key: 'createdAt', fixed: 'left', width: 190 },
|
||||
{ title: '状态', dataIndex: 'status', key: 'status', width: 130, render: value => <Tag>{text(value)}</Tag> },
|
||||
|
||||
{ title: '恢复验证时间', dataIndex: 'restoreVerifiedAt', key: 'restoreVerifiedAt', width: 190 },
|
||||
{ title: '还原用时', dataIndex: 'restoreElapsedSeconds', key: 'restoreElapsedSeconds', width: 110 },
|
||||
{ title: '操作', key: 'action', width: 130, render: (_, row) => <Button type="link" loading={busy} onClick={() => void runJob('BACKUP_VERIFY', String(row.id))}>复核备份</Button> },
|
||||
];
|
||||
return <section className="panel section-panel completion-tools">
|
||||
<div className="completion-panel-heading"><div><strong>备份、恢复验证与计划</strong><span>恢复验证仅在隔离目录执行;当前不开放在线业务库覆盖恢复</span></div><div className="completion-actions"><Button icon={<ReloadOutlined />} onClick={() => void load()}>刷新</Button>{canManage && <><Button onClick={() => { form.setFieldsValue({ ...plan, reason: '' }); setPlanOpen(true); }}>备份计划</Button><Button type="primary" loading={busy} onClick={() => void runJob('BACKUP_CREATE_VERIFY')}>创建并验证备份</Button></>}</div></div>
|
||||
{error && <Alert showIcon type="error" message="备份状态不可用" description={error} />}
|
||||
{loading ? <div className="completion-loading"><Spin />读取备份与恢复状态…</div> : <><div className="governance-monitor-grid"><div><small>计划</small><strong>{plan.active === true ? '已启用' : plan.active === false ? '已停用' : '未配置'}</strong></div><div><small>周期 / RPO</small><strong>{text(plan.intervalHours)} 小时 / {text(plan.rpoHours)} 小时</strong></div><div><small>RTO</small><strong>{text(plan.rtoHours)} 小时</strong></div><div><small>在线恢复</small><strong>{obj(data).liveRestoreEnabled === true ? '开放' : '关闭'}</strong></div></div>{backups.length ? <Table size="small" bordered columns={columns} dataSource={backups} rowKey={row => String(row.id)} pagination={{ pageSize: 10, showSizeChanger: false }} scroll={{ x: 920 }} /> : <Empty description="服务端当前没有备份记录" />}</>}
|
||||
{onNavigate && <Button type="link" onClick={onNavigate}>查看备份任务进度</Button>}
|
||||
<Modal className="management-modal" open={planOpen} title="备份计划配置" okText="保存计划" confirmLoading={busy} onCancel={() => setPlanOpen(false)} onOk={() => void savePlan()}><Form form={form} layout="vertical"><Form.Item name="active" label="计划状态" valuePropName="checked"><Switch checkedChildren="启用" unCheckedChildren="停用" /></Form.Item><div className="governance-form-grid"><Form.Item name="intervalHours" label="备份周期(小时)" rules={[{ required: true }]}><InputNumber min={1} max={8760} /></Form.Item><Form.Item name="rpoHours" label="RPO(小时)" rules={[{ required: true }]}><InputNumber min={1} max={8760} /></Form.Item><Form.Item name="rtoHours" label="RTO(小时)" rules={[{ required: true }]}><InputNumber min={1} max={8760} /></Form.Item></div><Form.Item name="reason" label="修改原因" rules={[{ required: true, whitespace: true }]}><Input.TextArea rows={2} /></Form.Item></Form></Modal>
|
||||
</section>;
|
||||
}
|
||||
|
||||
export function OperationsMonitorPanel({ user, onUnauthorized }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean }) {
|
||||
const { message } = App.useApp();
|
||||
const [data, setData] = useState<Row | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [alertPolicy, setAlertPolicy] = useState<Row | null>(null);
|
||||
const [policyOpen, setPolicyOpen] = useState(false);
|
||||
const [policyBusy, setPolicyBusy] = useState(false);
|
||||
const [policyError, setPolicyError] = useState('');
|
||||
const [policyForm] = Form.useForm<Row>();
|
||||
const canRefresh = user.roles.some(role => ['SYSTEM_ADMIN', 'SYSTEM_OPERATOR'].includes(role));
|
||||
const load = async () => {
|
||||
setLoading(true);
|
||||
try { setData(await api.governanceMonitor()); setError(''); }
|
||||
catch (value) { if (!onUnauthorized(value)) setError(value instanceof Error ? value.message : '运行监控读取失败'); }
|
||||
finally { setLoading(false); }
|
||||
};
|
||||
useEffect(() => { void load(); }, []);
|
||||
const loadPolicy = async () => {
|
||||
try { const response = await api.governanceAlertPolicy(); const policy = obj(response.policy); setAlertPolicy(policy); setPolicyError(''); }
|
||||
catch (value) { if (!onUnauthorized(value)) setPolicyError(value instanceof Error ? value.message : '告警策略读取失败'); }
|
||||
};
|
||||
useEffect(() => { if (canRefresh) void loadPolicy(); }, [canRefresh]);
|
||||
const editPolicy = () => {
|
||||
if (!alertPolicy) return;
|
||||
policyForm.setFieldsValue({ ...alertPolicy, severityOverrides: JSON.stringify(alertPolicy.severityOverrides || {}, null, 2), silenceUntil: text(alertPolicy.silenceUntil, ''), reason: '' }); setPolicyOpen(true);
|
||||
};
|
||||
const savePolicy = async () => {
|
||||
try {
|
||||
const values = await policyForm.validateFields(); let severityOverrides: unknown;
|
||||
try { severityOverrides = JSON.parse(String(values.severityOverrides || '{}')); } catch { message.error('严重度配置不是有效 JSON'); return; }
|
||||
setPolicyBusy(true);
|
||||
await api.updateGovernanceAlertPolicy({ queueAgeMinutes: Number(values.queueAgeMinutes), diskFreeBytes: Number(values.diskFreeBytes), backupAgeHours: Number(values.backupAgeHours), quietPeriodMinutes: Number(values.quietPeriodMinutes), slowRequestMillis: Number(values.slowRequestMillis), severityOverrides, silenceUntil: String(values.silenceUntil || '').trim() || null, expectedRowVersion: Number(alertPolicy?.rowVersion || 0), reason: String(values.reason || '').trim() });
|
||||
message.success('告警策略已保存'); setPolicyOpen(false); await loadPolicy();
|
||||
} catch (value) { if (value && typeof value === 'object' && 'errorFields' in value) return; if (!onUnauthorized(value)) setPolicyError(value instanceof ApiError && value.status === 409 ? '告警策略已发生并发修改,请重新读取。' : value instanceof Error ? value.message : '告警策略保存失败'); }
|
||||
finally { setPolicyBusy(false); }
|
||||
};
|
||||
const refresh = async () => {
|
||||
setRefreshing(true);
|
||||
try { const result = await api.refreshGovernanceMonitor(); setData(result); message.success('平台内巡检已完成'); setError(''); }
|
||||
catch (value) { if (!onUnauthorized(value)) setError(value instanceof Error ? value.message : '巡检失败'); }
|
||||
finally { setRefreshing(false); }
|
||||
};
|
||||
const summary = obj(data?.summary);
|
||||
const summaryEntries = Object.entries(summary).filter(([, value]) => ['string', 'number', 'boolean'].includes(typeof value));
|
||||
const alertRows = rows(data?.alerts);
|
||||
const requestMetricRows = rows(data?.requestMetrics);
|
||||
const alertColumns: ColumnsType<Row> = [
|
||||
{ title: '级别', dataIndex: 'severity', key: 'severity', width: 100, render: value => <Tag color={String(value).toUpperCase().includes('CRIT') || String(value).toUpperCase().includes('ERROR') ? 'red' : 'gold'}>{text(value)}</Tag> },
|
||||
{ title: '告警', dataIndex: 'title', key: 'title', width: 230, render: (_, row) => text(row.title || row.code) },
|
||||
{ title: '说明', dataIndex: 'message', key: 'message', width: 430 },
|
||||
{ title: '对象', key: 'target', width: 210, render: (_, row) => `${text(row.targetType)} · ${text(row.targetId)}` },
|
||||
{ title: '时间', dataIndex: 'createdAt', key: 'createdAt', width: 190 },
|
||||
{ title: '状态', dataIndex: 'status', key: 'status', width: 120 },
|
||||
];
|
||||
const requestMetricColumns: ColumnsType<Row> = [
|
||||
{ title: '路由', dataIndex: 'routePattern', key: 'routePattern', fixed: 'left', width: 280 },
|
||||
{ title: '方法', dataIndex: 'method', key: 'method', width: 90 },
|
||||
{ title: '请求数', dataIndex: 'requestCount', key: 'requestCount', align: 'right', width: 100 },
|
||||
{ title: '失败数', dataIndex: 'failureCount', key: 'failureCount', align: 'right', width: 100 },
|
||||
{ title: '慢请求数', dataIndex: 'slowCount', key: 'slowCount', align: 'right', width: 110 },
|
||||
{ title: '累计耗时 / ms', dataIndex: 'totalElapsedMillis', key: 'totalElapsedMillis', align: 'right', width: 140 },
|
||||
{ title: '最长耗时 / ms', dataIndex: 'maxElapsedMillis', key: 'maxElapsedMillis', align: 'right', width: 140 },
|
||||
{ title: '最近请求', dataIndex: 'lastSeen', key: 'lastSeen', width: 190 },
|
||||
];
|
||||
return <>
|
||||
<section className="panel section-panel governance-monitor">
|
||||
<div className="completion-panel-heading"><div><strong>运行指标、平台内告警与巡检</strong><span>只读取并更新服务端运行状态;不发送外部通知</span></div><div className="completion-actions"><Button icon={<ReloadOutlined />} loading={loading} onClick={() => void load()}>刷新</Button>{canRefresh && <><Button onClick={() => void editPolicy()} disabled={!alertPolicy}>告警阈值</Button><Button type="primary" loading={refreshing} onClick={() => void refresh()}>执行巡检</Button></>}</div></div>
|
||||
{error && <Alert showIcon type="error" message="运行监控暂不可用" description={error} />}
|
||||
{policyError && <Alert showIcon type="error" message="告警策略不可用" description={policyError} />}
|
||||
{loading ? <div className="completion-loading"><Spin />读取平台状态…</div> : <><div className="governance-monitor-grid">{summaryEntries.length ? summaryEntries.map(([key, value]) => <div key={key}><small>{key}</small><strong>{text(value)}</strong></div>) : <div className="completion-placeholder">服务端没有返回运行指标</div>}</div>{alertRows.length ? <Table size="small" bordered columns={alertColumns} dataSource={alertRows} rowKey={row => String(row.id || row.code)} pagination={{ pageSize: 10, showSizeChanger: false }} scroll={{ x: 1260 }} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前没有平台内告警" />}</>}
|
||||
<h3>接口请求指标</h3><p className="completion-note">按路由聚合请求数、失败数与耗时;服务端不保存请求正文。</p>
|
||||
{loading ? <div className="completion-loading"><Spin />读取接口指标…</div> : requestMetricRows.length ? <Table size="small" bordered columns={requestMetricColumns} dataSource={requestMetricRows} rowKey={row => `${text(row.routePattern)}-${text(row.method)}`} pagination={{ pageSize: 12, showSizeChanger: false }} scroll={{ x: 1200 }} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="服务端尚未记录接口请求指标" />}
|
||||
<Modal className="management-modal" open={policyOpen} title="告警阈值与静默策略" okText="保存策略" confirmLoading={policyBusy} onCancel={() => setPolicyOpen(false)} onOk={() => void savePolicy()}><Form form={policyForm} layout="vertical"><div className="governance-form-grid"><Form.Item name="queueAgeMinutes" label="队列告警(分钟)" rules={[{ required: true }]}><InputNumber min={1} max={1440} /></Form.Item><Form.Item name="diskFreeBytes" label="最低可用磁盘空间(字节)" rules={[{ required: true }]}><InputNumber min={104857600} max={1125899906842624} style={{ width: '100%' }} /></Form.Item><Form.Item name="backupAgeHours" label="备份超时(小时)" rules={[{ required: true }]}><InputNumber min={1} max={720} /></Form.Item><Form.Item name="quietPeriodMinutes" label="重复告警静默(分钟)" rules={[{ required: true }]}><InputNumber min={0} max={10080} /></Form.Item><Form.Item name="slowRequestMillis" label="慢请求阈值(毫秒)" rules={[{ required: true }]}><InputNumber min={100} max={120000} /></Form.Item><Form.Item name="silenceUntil" label="临时静默截止(ISO,可选)"><Input placeholder="2026-10-21T09:00:00Z" /></Form.Item></div><Form.Item name="severityOverrides" label="告警严重度覆盖(JSON)" rules={[{ required: true }]}><Input.TextArea rows={5} spellCheck={false} /></Form.Item><Form.Item name="reason" label="修改原因" rules={[{ required: true, whitespace: true }]}><Input.TextArea rows={2} /></Form.Item><p className="completion-note">保存后按新策略检查;严重度 key 只能使用服务端列出的告警类型。</p></Form></Modal>
|
||||
</section>
|
||||
<InspectionStrategyPanel user={user} onUnauthorized={onUnauthorized} />
|
||||
</>;
|
||||
}
|
||||
|
||||
const ACTIONS_BY_TYPE: Record<string, string[]> = {
|
||||
RECEIVER: ['source.receive'], IMPORTER: ['import.run'], QUERY: ['query.aggregate', 'query.detail'],
|
||||
WORKER: ['worker.execute', 'import.run'], MODEL: ['model.intent.parse'],
|
||||
};
|
||||
|
||||
export function ServiceIdentityPanel({ user, onUnauthorized }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean }) {
|
||||
const { message } = App.useApp();
|
||||
const [items, setItems] = useState<Row[]>([]);
|
||||
const [allowedActions, setAllowedActions] = useState<string[]>([]);
|
||||
const [serviceTypes, setServiceTypes] = useState<string[]>([]);
|
||||
const [bindings, setBindings] = useState<Row[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
const [editing, setEditing] = useState<Row | null>(null);
|
||||
const [rotating, setRotating] = useState<Row | null>(null);
|
||||
const [rotations, setRotations] = useState<Row[]>([]);
|
||||
const [bindingEdit, setBindingEdit] = useState<{ type: string; identityId: string } | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [form] = Form.useForm<Row>();
|
||||
const [rotateForm] = Form.useForm<Row>();
|
||||
const [bindingForm] = Form.useForm<{ reason: string }>();
|
||||
const canManage = user.roles.includes('SYSTEM_ADMIN');
|
||||
const serviceType = Form.useWatch('serviceType', form);
|
||||
const load = async () => {
|
||||
setLoading(true);
|
||||
const canReadBindings = user.roles.some(role => ['SYSTEM_ADMIN', 'SYSTEM_OPERATOR'].includes(role));
|
||||
const [identityResult, bindingResult] = await Promise.allSettled([api.serviceIdentities(), canReadBindings ? api.serviceBindings() : Promise.resolve({ items: [] as Row[] })]);
|
||||
if (identityResult.status === 'fulfilled') { setItems(collectionItems(identityResult.value)); setAllowedActions(Array.isArray(identityResult.value.allowedActions) ? identityResult.value.allowedActions.map(String) : []); setServiceTypes(Array.isArray(identityResult.value.serviceTypes) ? identityResult.value.serviceTypes.map(String) : []); }
|
||||
else if (!onUnauthorized(identityResult.reason)) setError(identityResult.reason instanceof Error ? identityResult.reason.message : '服务身份读取失败');
|
||||
if (bindingResult.status === 'fulfilled') setBindings(collectionItems(bindingResult.value)); else if (!onUnauthorized(bindingResult.reason)) setError(bindingResult.reason instanceof Error ? bindingResult.reason.message : '服务绑定读取失败');
|
||||
setLoading(false);
|
||||
};
|
||||
useEffect(() => { void load(); }, []);
|
||||
const open = (item?: Row) => {
|
||||
const next = item || {};
|
||||
setEditing(next);
|
||||
form.setFieldsValue({ name: text(next.name, ''), serviceType: text(next.serviceType, serviceTypes[0] || ''), allowedActions: Array.isArray(next.allowedActions) ? next.allowedActions.map(String) : [], credentialReference: text(next.credentialReference, ''), credentialStatus: text(next.credentialStatus, 'UNCONFIGURED'), active: next.active === true, reason: '' });
|
||||
};
|
||||
const save = async () => {
|
||||
try {
|
||||
const values = await form.validateFields(); setBusy(true);
|
||||
const id = String(editing?.id || '');
|
||||
const body = { name: String(values.name || '').trim(), serviceType: values.serviceType, allowedActions: values.allowedActions || [], credentialReference: values.credentialReference || null, credentialStatus: values.credentialStatus, active: id ? values.active === true : false, ...(id ? { expectedRowVersion: Number(editing?.rowVersion || 0) } : {}), reason: String(values.reason || '').trim() };
|
||||
if (id) await api.updateServiceIdentity(id, body); else await api.createServiceIdentity(body);
|
||||
message.success(id ? '服务身份已更新' : '服务身份已创建并保持停用'); setEditing(null); await load();
|
||||
} catch (value) { if (value && typeof value === 'object' && 'errorFields' in value) return; if (!onUnauthorized(value)) message.error(value instanceof ApiError && value.status === 409 ? '服务身份已被其他操作更新,请刷新后重试。' : value instanceof Error ? value.message : '服务身份保存失败'); }
|
||||
finally { setBusy(false); }
|
||||
};
|
||||
const rotate = async () => {
|
||||
if (!rotating?.id) return;
|
||||
try { const values = await rotateForm.validateFields(); setBusy(true); await api.rotateServiceIdentity(String(rotating.id), { credentialReference: values.credentialReference, credentialStatus: values.credentialStatus, reason: String(values.reason || '').trim(), expectedRowVersion: Number(rotating.rowVersion || 0) }); message.success('凭据引用状态已轮换,服务端未接收密钥内容'); setRotating(null); await load(); }
|
||||
catch (value) { if (value && typeof value === 'object' && 'errorFields' in value) return; if (!onUnauthorized(value)) message.error(value instanceof ApiError && value.status === 409 ? '服务身份已被其他操作更新。' : value instanceof Error ? value.message : '凭据轮换失败'); }
|
||||
finally { setBusy(false); }
|
||||
};
|
||||
const bind = async (type: string, identityId: string) => { bindingForm.resetFields(); setBindingEdit({ type, identityId }); };
|
||||
const submitBinding = async () => {
|
||||
if (!bindingEdit) return;
|
||||
let values: { reason: string };
|
||||
try { values = await bindingForm.validateFields(); } catch { return; }
|
||||
setBusy(true);
|
||||
try { await api.updateServiceBinding(bindingEdit.type, { identityId: bindingEdit.identityId, reason: values.reason.trim() }); message.success(`${bindingEdit.type} 服务绑定已更新`); setBindingEdit(null); await load(); }
|
||||
catch (value) { if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '服务身份绑定失败'); }
|
||||
finally { setBusy(false); }
|
||||
};
|
||||
const columns: ColumnsType<Row> = [
|
||||
{ title: '服务身份', dataIndex: 'name', key: 'name', fixed: 'left', width: 190 },
|
||||
{ title: '类型', dataIndex: 'serviceType', key: 'serviceType', width: 120 },
|
||||
{ title: '授权动作', dataIndex: 'allowedActions', key: 'allowedActions', width: 280, render: value => Array.isArray(value) ? value.join('、') : '—' },
|
||||
{ title: '凭据引用 / 状态', key: 'credential', width: 260, render: (_, row) => <span className="object-cell"><strong>{text(row.credentialStatus)}</strong><small>{text(row.credentialReference, '未配置引用')}</small></span> },
|
||||
{ title: '状态', dataIndex: 'active', key: 'active', width: 100, render: value => <Tag color={value === true ? 'green' : 'default'}>{value === true ? '启用' : '停用'}</Tag> },
|
||||
{ title: '操作', key: 'action', fixed: 'right', width: 230, render: (_, row) => <span className="completion-actions">{canManage && <><Button type="link" onClick={() => open(row)}>编辑</Button><Button type="link" onClick={() => { setRotating(row); rotateForm.setFieldsValue({ credentialReference: text(row.credentialReference, ''), credentialStatus: text(row.credentialStatus, 'UNCONFIGURED'), reason: '' }); }}>轮换</Button></>}<Button type="link" onClick={async () => { try { setRotations(collectionItems(await api.serviceRotations(String(row.id)))); setRotating({ ...row, showRotations: true }); } catch (value) { if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '轮换记录读取失败'); } }}>历史</Button></span> },
|
||||
];
|
||||
return <div className="governance-service-identities">
|
||||
<section className="panel section-panel">
|
||||
<div className="completion-panel-heading"><div><strong>服务身份与最小动作授权</strong><span>仅保存 env: 或 file: 凭据引用,不在浏览器或服务端表单中接收密钥文本</span></div><div className="completion-actions"><Button icon={<ReloadOutlined />} onClick={() => void load()}>刷新</Button>{canManage && <Button type="primary" onClick={() => open()}>新建服务身份</Button>}</div></div>
|
||||
{error && <Alert showIcon type="error" message="服务身份管理不可用" description={error} />}
|
||||
{loading ? <div className="completion-loading"><Spin />读取服务身份…</div> : items.length ? <Table size="small" bordered columns={columns} dataSource={items} rowKey={row => String(row.id)} pagination={false} scroll={{ x: 1200 }} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="尚未创建服务身份" />}
|
||||
</section>
|
||||
<section className="panel section-panel"><div className="completion-panel-heading"><div><strong>服务接入绑定</strong><span>只允许类型匹配且授权状态可用的身份</span></div></div>{serviceTypes.length ? <div className="governance-binding-list">{serviceTypes.map(type => <div key={type}><strong>{type}</strong><span>{text(bindings.find(item => item.serviceType === type)?.serviceIdentityId, '未绑定')}</span>{canManage && <Select aria-label={`${type}服务身份`} placeholder="选择身份" value={String(bindings.find(item => item.serviceType === type)?.serviceIdentityId || '') || undefined} loading={busy} options={items.filter(item => item.serviceType === type).map(item => ({ label: `${text(item.name)} · ${text(item.credentialStatus)}`, value: String(item.id) }))} onChange={value => void bind(type, value)} />}</div>)}</div> : <Empty description="服务类型尚未由服务端返回" />}</section>
|
||||
<Modal className="management-modal" open={Boolean(editing) && !editing?.showRotations} title={editing?.id ? '编辑服务身份' : '新建服务身份'} okText="保存配置" confirmLoading={busy} onCancel={() => setEditing(null)} onOk={() => void save()}>
|
||||
<Alert showIcon type="warning" message="服务身份默认停用" description="启用需要 READY 凭据引用和服务端允许的最小动作。输入凭据引用,不要粘贴密钥内容。" />
|
||||
<Form form={form} layout="vertical"><Form.Item name="name" label="身份名称" rules={[{ required: true, whitespace: true }]}><Input maxLength={190} /></Form.Item><Form.Item name="serviceType" label="服务类型" rules={[{ required: true }]}><Select disabled={Boolean(editing?.id)} options={serviceTypes.map(value => ({ label: value, value }))} /></Form.Item><Form.Item name="allowedActions" label="允许动作" rules={[{ required: true, type: 'array', min: 1 }]}><Select mode="multiple" options={(ACTIONS_BY_TYPE[String(serviceType || '')] || allowedActions).filter((value: string) => allowedActions.includes(value)).map((value: string) => ({ label: value, value }))} /></Form.Item><Form.Item name="credentialReference" label="凭据引用" rules={[{ pattern: /^(?:env:[A-Z][A-Z0-9_]{0,100}|file:[A-Za-z0-9_./-]{1,240})$/, message: '使用 env:NAME 或 file:relative/path 引用,不填密钥内容' }]}><Input placeholder="env:QUALITY_MODEL_KEY" autoComplete="off" /></Form.Item><Form.Item name="credentialStatus" label="凭据状态" rules={[{ required: true }]}><Select options={['UNCONFIGURED', 'READY', 'EXPIRED', 'REVOKED'].map(value => ({ label: value, value }))} /></Form.Item>{Boolean(editing?.id) && <Form.Item name="active" label="身份状态" valuePropName="checked"><Switch checkedChildren="启用" unCheckedChildren="停用" /></Form.Item>}<Form.Item name="reason" label="操作原因" rules={[{ required: true, whitespace: true }]}><Input.TextArea rows={2} maxLength={300} /></Form.Item></Form>
|
||||
</Modal>
|
||||
<Modal className="management-modal" open={Boolean(rotating?.id) && !rotating?.showRotations} title="轮换凭据引用" okText="提交轮换" confirmLoading={busy} onCancel={() => setRotating(null)} onOk={() => void rotate()}><Form form={rotateForm} layout="vertical"><Form.Item name="credentialReference" label="凭据引用" rules={[{ required: true, pattern: /^(?:env:[A-Z][A-Z0-9_]{0,100}|file:[A-Za-z0-9_./-]{1,240})$/, message: '使用 env:NAME 或 file:relative/path 引用' }]}><Input autoComplete="off" /></Form.Item><Form.Item name="credentialStatus" label="状态"><Select options={['READY', 'EXPIRED', 'REVOKED', 'UNCONFIGURED'].map(value => ({ label: value, value }))} /></Form.Item><Form.Item name="reason" label="轮换理由" rules={[{ required: true, whitespace: true }]}><Input.TextArea rows={2} /></Form.Item></Form></Modal>
|
||||
<Modal className="management-modal" open={Boolean(bindingEdit)} title="变更服务身份绑定" okText="保存绑定" confirmLoading={busy} onCancel={() => setBindingEdit(null)} onOk={() => void submitBinding()}><p>服务类型:{text(bindingEdit?.type)} · 身份 ID:{text(bindingEdit?.identityId)}</p><Form form={bindingForm} layout="vertical"><Form.Item name="reason" label="绑定原因" rules={[{ required: true, whitespace: true }]}><Input.TextArea rows={2} maxLength={300} /></Form.Item></Form></Modal>
|
||||
<Drawer className="management-drawer" open={rotating?.showRotations === true} title="凭据引用变更历史" width={Math.min(680, window.innerWidth)} onClose={() => setRotating(null)}>{rotations.length ? <Table size="small" bordered dataSource={rotations} rowKey={row => String(row.id)} pagination={{ pageSize: 8, showSizeChanger: false }} columns={[{ title: '引用', dataIndex: 'credentialReference', key: 'credentialReference' }, { title: '状态', dataIndex: 'credentialStatus', key: 'credentialStatus' }, { title: '原因', dataIndex: 'reason', key: 'reason' }, { title: '时间', dataIndex: 'createdAt', key: 'createdAt' }]} /> : <Empty description="没有已返回的轮换记录" />}</Drawer>
|
||||
</div>;
|
||||
}
|
||||
|
||||
export function UserAccessPolicyPanel({ onUnauthorized }: { onUnauthorized: (error: unknown) => boolean }) {
|
||||
const { message } = App.useApp();
|
||||
const [userId, setUserId] = useState<string>();
|
||||
const [policy, setPolicy] = useState<Row | null>(null);
|
||||
const [users, setUsers] = useState<Row[]>([]);
|
||||
const [effective, setEffective] = useState<Row | null>(null);
|
||||
const [scopePreview, setScopePreview] = useState<Row | null>(null);
|
||||
const [previewBusy, setPreviewBusy] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [form] = Form.useForm<Row>();
|
||||
const userOptions = users.map(item => ({ label: `${text(item.displayName || item.username)} · ${text(item.username)}`, value: String(item.id) })).filter(item => item.value);
|
||||
const load = async (id: string) => {
|
||||
setLoading(true);
|
||||
try { const result = await api.userAccessPolicy(id); const value = obj(result.policy || result); setPolicy(value); form.setFieldsValue({ detailAllowed: value.detailAllowed === true, evidenceAllowed: value.evidenceAllowed === true, originalDownloadAllowed: value.originalDownloadAllowed === true, inheritDepartmentChildren: value.inheritDepartmentChildren === true, allowedFields: Array.isArray(value.allowedFields) ? value.allowedFields.join('\n') : '*', validUntil: text(value.validUntil, ''), reason: '' }); setError(''); }
|
||||
catch (value) { if (!onUnauthorized(value)) setError(value instanceof Error ? value.message : '访问策略读取失败'); }
|
||||
finally { setLoading(false); }
|
||||
};
|
||||
useEffect(() => {
|
||||
api.users().then(value => setUsers(collectionItems(value))).catch(errorValue => { if (!onUnauthorized(errorValue)) setError(errorValue instanceof Error ? errorValue.message : '用户列表读取失败'); });
|
||||
}, []);
|
||||
useEffect(() => { if (userId) void load(userId); else setPolicy(null); }, [userId]);
|
||||
const save = async () => {
|
||||
if (!userId || !policy) return;
|
||||
try { const value = await form.validateFields(); setSaving(true); const allowedFields = String(value.allowedFields || '').split(/[\n,,]/).map(item => item.trim()).filter(Boolean); await api.updateUserAccessPolicy(userId, { detailAllowed: value.detailAllowed === true, evidenceAllowed: value.evidenceAllowed === true, originalDownloadAllowed: value.originalDownloadAllowed === true, inheritDepartmentChildren: value.inheritDepartmentChildren === true, allowedFields, validUntil: value.validUntil || null, reason: String(value.reason || '').trim(), expectedRowVersion: Number(policy.rowVersion || 0) }); message.success('明细、证据及组织范围策略已更新'); await load(userId); }
|
||||
catch (value) { if (value && typeof value === 'object' && 'errorFields' in value) return; if (!onUnauthorized(value)) message.error(value instanceof ApiError && value.status === 409 ? '授权策略已被更新,请重新读取。' : value instanceof Error ? value.message : '策略保存失败'); }
|
||||
finally { setSaving(false); }
|
||||
};
|
||||
const preview = async (kind: 'effective' | 'scope') => {
|
||||
if (!userId) return; setPreviewBusy(true);
|
||||
try { const result = kind === 'effective' ? await api.effectiveUserAccess(userId) : await api.userScopePreview(userId); if (kind === 'effective') setEffective(result); else setScopePreview(result); }
|
||||
catch (value) { if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '用户有效授权读取失败'); }
|
||||
finally { setPreviewBusy(false); }
|
||||
};
|
||||
const scopeCounts = rows(scopePreview?.counts);
|
||||
const effectiveDepartments = Array.isArray(effective?.departments) ? effective.departments.map(String).join('、') : '—';
|
||||
const grantedDepartments = Array.isArray(effective?.grantedDepartments) ? effective.grantedDepartments.map(String).join('、') : '—';
|
||||
const hierarchyRows = rows(effective?.hierarchySource);
|
||||
return <div className="governance-panel-body"><div className="completion-panel-heading"><div><strong>用户明细与证据访问策略</strong><span>明细、原文件下载与字段授权由服务端二次校验</span></div><div className="completion-actions"><Button disabled={!userId} loading={previewBusy} onClick={() => void preview('effective')}>预览有效授权</Button><Button disabled={!userId} loading={previewBusy} onClick={() => void preview('scope')}>预览授权行数</Button></div></div><div className="governance-policy-select"><Select showSearch optionFilterProp="label" placeholder="选择用户" value={userId} options={userOptions} onChange={value => { setUserId(value); setEffective(null); setScopePreview(null); }} /></div>{error && <Alert showIcon type="error" message="访问策略不可用" description={error} />}{loading ? <div className="completion-loading"><Spin />读取访问策略…</div> : policy && <Form form={form} layout="vertical" className="governance-policy-form"><div className="governance-form-grid"><Form.Item name="detailAllowed" label="允许读取来源明细" valuePropName="checked"><Switch /></Form.Item><Form.Item name="evidenceAllowed" label="允许查看来源变更证据" valuePropName="checked"><Switch /></Form.Item><Form.Item name="originalDownloadAllowed" label="允许下载原始文件" valuePropName="checked"><Switch /></Form.Item><Form.Item name="inheritDepartmentChildren" label="继承下级产业部范围" valuePropName="checked"><Switch /></Form.Item><Form.Item name="validUntil" label="授权有效截止时间(ISO,可选)"><Input placeholder="2026-12-31T23:59:59Z" /></Form.Item></div><Form.Item name="allowedFields" label="允许字段(每行一个;* 表示全部已授权字段)"><Input.TextArea rows={5} spellCheck={false} /></Form.Item><Form.Item name="reason" label="修改原因" rules={[{ required: true, whitespace: true }]}><Input.TextArea rows={2} maxLength={300} /></Form.Item><Button type="primary" loading={saving} onClick={() => void save()}>保存访问策略</Button><p className="completion-note">空字段集合将由服务端按其默认策略处理。</p></Form>}{effective && <section className="completion-insight-card"><div className="completion-card-heading"><strong>服务端有效授权</strong><Tag color={effective.authorizationEffective === true ? 'green' : 'red'}>{effective.authorizationEffective === true ? '有效' : '未生效'}</Tag></div><p>用户 {text(effective.userId)} · 身份 {effective.active === true ? '启用' : '停用'} · 数据范围已由服务端核验</p><p>角色:{Array.isArray(effective.roles) ? (effective.roles as unknown[]).map(String).join('、') : '—'}</p><p>原始授权产业部:{grantedDepartments} · 有效产业部:{effectiveDepartments}</p><p>业务分组:{Array.isArray(effective.groups) ? (effective.groups as unknown[]).map(String).join('、') : '—'}</p><p>动作:{Array.isArray(effective.allowedActions) ? (effective.allowedActions as unknown[]).map(String).join('、') : '—'}</p><p>字段策略:{JSON.stringify(withoutSystemMetadata(effective.fieldPolicy ?? {}))}</p>{hierarchyRows.length > 0 && <p>层级展开依据:当前映射配置</p>}</section>}{scopePreview && <section className="completion-insight-card"><div className="completion-card-heading"><strong>授权范围行数</strong><Tag>{scopePreview.dataReturned === false ? '仅计数,未返回数据' : '服务端返回状态'}</Tag></div><p>原始授权产业部:{Array.isArray(scopePreview.grantedDepartments) ? (scopePreview.grantedDepartments as unknown[]).map(String).join('、') : '—'} · 有效产业部:{Array.isArray(scopePreview.departments) ? (scopePreview.departments as unknown[]).map(String).join('、') : '—'}</p>{rows(scopePreview.hierarchySource).length > 0 && <p>层级依据:当前映射配置</p>}{scopeCounts.length ? <Table size="small" bordered dataSource={scopeCounts} rowKey={row => String(row.stage)} pagination={false} columns={[{ title: '阶段', dataIndex: 'stage', key: 'stage', width: 100, render: value => value === 'black' ? '黑片' : value === 'bright' ? '亮片' : text(value) }, { title: '总行数', dataIndex: 'totalRows', key: 'totalRows', align: 'right' }, { title: '授权行数', dataIndex: 'authorizedRows', key: 'authorizedRows', align: 'right' }]} /> : <Empty description="服务端没有返回授权计数" />}</section>}{!userId && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="选择用户后查看并编辑其访问范围" />}</div>;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,68 @@
|
||||
export type DataStage = 'black' | 'bright';
|
||||
export type DataField = { name: string; required: boolean };
|
||||
export type WorkbookPreview = {
|
||||
uploadId: string;
|
||||
sourceFile: string;
|
||||
sheets: { sheetName: string }[];
|
||||
preview: { sheetName: string; headerRow: number; headers: string[]; sampleRows: { rowNumber: number; values: Record<string, unknown> }[] };
|
||||
fields: Record<DataStage, DataField[]>;
|
||||
};
|
||||
export type PublishedSourceTarget = { documentId: string; revisionId: string; sourceSlot: string; stage: DataStage; year: number; month: number; scopeCode: string; sourceFile: string };
|
||||
export type SourceUploadOptions = { currentReleaseId: string | null; targets: PublishedSourceTarget[]; fields: Record<DataStage, DataField[]>; scopes: string[]; currentSourceIds?: string[]; currentSourcesComplete?: boolean };
|
||||
export type ConfigureSourceBody = { uploadId: string; stage: DataStage; year: number; month: number; sheetName: string; headerRow: number; fieldMap: Record<string, string>; mode: 'ADD' | 'REPLACE'; expectedCurrentReleaseId: string | null; targetDocumentId?: string; targetRevisionId?: string; reason: string; scopeCode: string };
|
||||
export type MasterWorkbookKind = 'departments' | 'groups' | 'products' | 'projectGroups' | 'categoryLookup' | 'projectGroupLookup' | 'departmentLookup' | 'productLookup' | 'standardBundle';
|
||||
export type MasterWorkbookKeyFormat = 'SEPARATE_COLUMNS' | 'PDT_REGION_COMBINED';
|
||||
export type MasterWorkbookPreview = {
|
||||
previewId: string;
|
||||
standardBundleAvailable?: boolean;
|
||||
suggestedTables?: { kind: MasterWorkbookKind; label?: string; sheetName: string; columns: Record<string, string>; keyFormat?: MasterWorkbookKeyFormat; rowCount: number }[];
|
||||
sheets: { name: string; headers: string[]; sampleRows: Record<string, unknown>[]; rowCount: number }[];
|
||||
};
|
||||
export type MasterWorkbookImportBody = { previewId: string; sheetName: string; kind: MasterWorkbookKind; mode: 'MERGE' | 'REPLACE'; columns: Record<string, string>; keyFormat?: MasterWorkbookKeyFormat; baseMappingVersionId: string; expectedBaseRowVersion: number; name: string; reason: string };
|
||||
export type DeletionSource = { id: string; sourceFile: string; stage: DataStage | null; year: number | null; month: number | null; status: string; sha256: string; scopeCode?: string; sizeBytes?: number; deletedAt?: string; deletionReason?: string };
|
||||
export type SourceDeletionPreview = {
|
||||
source: DeletionSource;
|
||||
currentReleaseId: string | null;
|
||||
mode: 'HIDE_ONLY' | 'WITHDRAW_CURRENT';
|
||||
currentUsage: { documentId: string; revisionId: string } | null;
|
||||
history: { revisionCount: number; publishedReleaseCount: number; candidateReleaseCount: number };
|
||||
deleteVersion: number;
|
||||
hidden: boolean;
|
||||
changeRequest: { id: string; status: string; rowVersion: number; reason?: string; reviewReason?: string; resultReleaseId?: string; [key: string]: unknown } | null;
|
||||
nextAction: 'REQUEST_WITHDRAWAL' | 'HIDE_SOURCE' | 'REVIEW_WITHDRAWAL' | 'BUILD_WITHDRAWAL_CANDIDATE' | 'RECONCILE_CANDIDATE' | 'RESTORE_SOURCE' | 'WAIT_FOR_TASK';
|
||||
physicalFilesRetained: boolean;
|
||||
canDelete: boolean;
|
||||
canRestore: boolean;
|
||||
canReview?: boolean;
|
||||
canBuild?: boolean;
|
||||
blockedReason?: string;
|
||||
};
|
||||
|
||||
export type DataWorkflowStatus = {
|
||||
simplified: boolean;
|
||||
mode: 'TEST' | 'DISABLED' | string;
|
||||
currentReleaseId: string | null;
|
||||
activeMappingId?: string | null;
|
||||
activeRuleId?: string | null;
|
||||
activeMapping?: { id?: string; name?: string; rowVersion?: number; definition?: Record<string, unknown> } | null;
|
||||
activeRule?: { id?: string; name?: string; description?: string; rowVersion?: number; definition?: Record<string, unknown> } | null;
|
||||
fields?: unknown[];
|
||||
operators?: unknown[];
|
||||
targets?: unknown[];
|
||||
stages?: unknown[];
|
||||
defaultRules?: unknown[];
|
||||
limits?: Record<string, unknown>;
|
||||
deletedSources?: DeletionSource[];
|
||||
capabilities?: { canApply?: boolean; canApplyMapping?: boolean; canApplyRule?: boolean; canRecalculate?: boolean; canImport?: boolean; canPublish?: boolean; canDeleteSource?: boolean; canDeleteCurrentSource?: boolean; canRestoreSource?: boolean; canViewOperations?: boolean };
|
||||
};
|
||||
|
||||
export type DataWorkflowOperation = {
|
||||
operationId: string;
|
||||
status: 'QUEUED' | 'RUNNING' | 'COMPLETED' | 'FAILED' | string;
|
||||
stage?: string;
|
||||
operationType?: string;
|
||||
releaseId?: string | null;
|
||||
currentReleaseId?: string | null;
|
||||
errors?: { code?: string; message?: string }[];
|
||||
[key: string]: unknown;
|
||||
};
|
||||
@@ -0,0 +1,580 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Alert, App, Button, Checkbox, Empty, Form, Input, InputNumber, Modal, Progress, Select, Spin, Steps, Table, Tag } from 'antd';
|
||||
import { ArrowRightOutlined, DeleteOutlined, FileExcelOutlined, ReloadOutlined, SwapOutlined, UndoOutlined, UploadOutlined } from '@ant-design/icons';
|
||||
import { api, collectionItems } from './api';
|
||||
import type { AuthUser, SourceItem } from './types';
|
||||
import type { DataField, DataStage, DataWorkflowOperation, DataWorkflowStatus, DeletionSource, MasterWorkbookKeyFormat, MasterWorkbookKind, MasterWorkbookPreview, SourceDeletionPreview, SourceUploadOptions, WorkbookPreview } from './NoCodeDataTypes';
|
||||
import { useDataWorkflowOperation } from './useDataWorkflowOperation';
|
||||
import { readableSelectPopup } from './readableSelectPopup';
|
||||
import './no-code-data-workflow.css';
|
||||
|
||||
type Row = Record<string, unknown>;
|
||||
const asRow = (value: unknown): Row => value && typeof value === 'object' && !Array.isArray(value) ? value as Row : {};
|
||||
const asRows = (value: unknown): Row[] => Array.isArray(value) ? value.filter(item => item && typeof item === 'object') as Row[] : [];
|
||||
const txt = (value: unknown): string => value === null || value === undefined || value === '' ? '—' : typeof value === 'object' ? Object.values(asRow(value)).map(txt).join(';') : String(value);
|
||||
const failure = (value: unknown) => value instanceof Error ? value.message : '操作未完成,请重试';
|
||||
const stageName = (stage: unknown) => stage === 'black' ? '黑片' : stage === 'bright' ? '亮片' : txt(stage);
|
||||
const metricLabel = (value: unknown) => String(value || '').split('.').map(part => ({ black: '黑片', bright: '亮片', totalWeight: '总重量', qualifiedWeight: '合格重量', scrapWeight: '报废重量', compositeRate: '综合合格率', rate: '合格率', rateWithoutHeadquartersScrap: '剔除本部报废后合格率', headquartersScrapWeight: '本部报废重量', objectPresence: '对象是否存在', applicability: '适用状态' } as Record<string, string>)[part] || part).join(' / ');
|
||||
const ratio = (value: unknown) => typeof value === 'number' ? `${(value * 100).toFixed(2)}%` : '—';
|
||||
const rolesAllow = (user: AuthUser, roles: string[]) => user.roles.some(role => roles.includes(role));
|
||||
const matchFields = (fields: DataField[], headers: string[]) => Object.fromEntries(fields.filter(field => headers.includes(field.name)).map(field => [field.name, field.name]));
|
||||
const statusLabel: Record<string, string> = { QUEUED: '等待处理', RUNNING: '正在处理', COMPLETED: '校验完成', FAILED: '处理失败', CANCELLED: '已取消', CANDIDATE_READY: '候选已生成', AUTO_PASSED: '对账通过', CONFIRMED: '差异已确认', REVIEW_REQUIRED: '差异待确认', BLOCKED: '存在阻断问题' };
|
||||
|
||||
function SampleTable({ headers, rows }: { headers: string[]; rows: Row[] }) {
|
||||
return <Table size="small" bordered dataSource={rows.map((row, index) => ({ ...row, __previewKey: index }))} rowKey="__previewKey" pagination={{ pageSize: 20, showSizeChanger: false }} scroll={{ x: 'max-content' }} columns={headers.map(header => ({ title: header, dataIndex: header, key: header, width: 150, render: txt }))} locale={{ emptyText: '当前工作表没有可预览数据' }} />;
|
||||
}
|
||||
|
||||
function ColumnMatching({ fields, headers, value, onChange, disabled = false }: { fields: DataField[]; headers: string[]; value: Record<string, string>; onChange: (value: Record<string, string>) => void; disabled?: boolean }) {
|
||||
return <div className="nc-column-matching">{fields.map(field => <label key={field.name} className="nc-field-match"><span>{field.name}{field.required ? <b>必填</b> : <small>选填</small>}</span><Select {...readableSelectPopup} disabled={disabled} aria-label={`${field.name}对应的Excel列`} allowClear showSearch optionFilterProp="label" placeholder="选择 Excel 中的列" value={value[field.name] || undefined} options={headers.map(header => ({ value: header, label: header }))} onChange={selected => { const next = { ...value }; if (selected) next[field.name] = selected; else delete next[field.name]; onChange(next); }} /></label>)}</div>;
|
||||
}
|
||||
|
||||
const workflowStageLabel: Record<string, string> = { QUEUED: '等待处理', VALIDATING: '检查来源与配置', VERSION_CREATED: '保存更新', REBUILDING: '重新计算报表', PUBLISHING: '更新当前报表', RESTORING_SOURCE: '恢复来源并重算', SOURCE_RESTORED: '来源已恢复并更新报表', COMPLETED: '已完成', FAILED: '处理失败' };
|
||||
|
||||
function WorkflowOperationFeedback({ operation, error, busy, onResume }: { operation: DataWorkflowOperation | null; error: string; busy: boolean; onResume: () => void }) {
|
||||
if (!operation && !error) return null;
|
||||
const status = String(operation?.status || '').toUpperCase();
|
||||
const errors = Array.isArray(operation?.errors) ? operation.errors.map(item => item.message).filter(Boolean) : [];
|
||||
return <section className="nc-operation-status panel">
|
||||
{error && <Alert showIcon type="error" message={status === 'FAILED' ? '操作未完成' : '进度读取失败'} description={[...errors, error].filter(Boolean).join(';')} action={operation?.operationId ? <Button size="small" onClick={onResume}>重试读取进度</Button> : undefined} />}
|
||||
<div><strong>{workflowStageLabel[String(operation?.stage || operation?.status)] || (busy ? '正在处理' : status === 'COMPLETED' ? '报表已更新' : '操作状态')}</strong></div>
|
||||
<Progress percent={busy ? undefined : status === 'COMPLETED' ? 100 : 0} status={status === 'FAILED' ? 'exception' : status === 'COMPLETED' ? 'success' : 'active'} />
|
||||
</section>;
|
||||
}
|
||||
|
||||
function SimplifiedDataWorkflow({ options, workflowStatus, onUnauthorized, onRefresh }: { options: SourceUploadOptions; workflowStatus: DataWorkflowStatus; onUnauthorized: (error: unknown) => boolean; onRefresh: () => void }) {
|
||||
const { message } = App.useApp();
|
||||
const input = useRef<HTMLInputElement>(null);
|
||||
const configuredUploadId = useRef<string | null>(null);
|
||||
const [workbook, setWorkbook] = useState<WorkbookPreview | null>(null);
|
||||
const [stage, setStage] = useState<DataStage>('black');
|
||||
const [year, setYear] = useState(new Date().getFullYear()); const [month, setMonth] = useState(new Date().getMonth() + 1);
|
||||
const [sheetName, setSheetName] = useState(''); const [headerRow, setHeaderRow] = useState(1); const [fieldMap, setFieldMap] = useState<Record<string, string>>({});
|
||||
const [mode, setMode] = useState<'ADD' | 'REPLACE'>('ADD'); const [targetId, setTargetId] = useState(''); const [scopeCode, setScopeCode] = useState(options.scopes[0] || 'ALL');
|
||||
const [configuredSourceId, setConfiguredSourceId] = useState(''); const [busy, setBusy] = useState(false); const [error, setError] = useState('');
|
||||
const uploadOperation = useDataWorkflowOperation('source-import', () => { onRefresh(); message.success('来源已导入,报表已更新'); });
|
||||
const recalcOperation = useDataWorkflowOperation('recalculate', () => { onRefresh(); message.success('已按当前来源重新计算并更新报表'); });
|
||||
const fields = options.fields[stage] || []; const headers = workbook?.preview.headers || [];
|
||||
const missing = fields.filter(field => field.required && !fieldMap[field.name]);
|
||||
const duplicate = Object.values(fieldMap).length !== new Set(Object.values(fieldMap)).size;
|
||||
const target = options.targets.find(item => item.documentId === targetId);
|
||||
const importBusy = busy || uploadOperation.busy;
|
||||
const hasImportCapability = workflowStatus.capabilities?.canImport !== false;
|
||||
const needsNewFile = Boolean(workbook && configuredUploadId.current === workbook.uploadId && !configuredSourceId);
|
||||
const canImport = Boolean(hasImportCapability && !needsNewFile && workbook && !missing.length && !duplicate && (mode !== 'REPLACE' || target));
|
||||
const reportError = (value: unknown) => { if (!onUnauthorized(value)) setError(failure(value)); };
|
||||
const invalidateConfiguredSource = () => {
|
||||
setConfiguredSourceId('');
|
||||
};
|
||||
const readFile = async (file?: File) => {
|
||||
if (!file) return; setBusy(true); setError(''); setConfiguredSourceId('');
|
||||
try {
|
||||
const result = await api.previewSourceWorkbook(file);
|
||||
setWorkbook(result); configuredUploadId.current = null; setSheetName(result.preview.sheetName); setHeaderRow(result.preview.headerRow);
|
||||
const scores = (['black', 'bright'] as DataStage[]).map(value => {
|
||||
const required = (options.fields[value] || []).filter(field => field.required);
|
||||
const matched = matchFields(options.fields[value] || [], result.preview.headers);
|
||||
return { stage: value, score: required.length ? required.filter(field => matched[field.name]).length / required.length : 0 };
|
||||
});
|
||||
const detected = scores.sort((a, b) => b.score - a.score)[0];
|
||||
const nextStage = detected.score > 0 ? detected.stage : stage;
|
||||
setStage(nextStage); setFieldMap(matchFields(options.fields[nextStage] || [], result.preview.headers));
|
||||
if (mode === 'ADD') {
|
||||
const monthMatch = file.name.match(/(?:^|\D)(0?[1-9]|1[0-2])月/);
|
||||
if (monthMatch) setMonth(Number(monthMatch[1]));
|
||||
}
|
||||
} catch (value) { reportError(value); }
|
||||
finally { setBusy(false); if (input.current) input.current.value = ''; }
|
||||
};
|
||||
const changePreview = async (nextSheet: string, nextHeader = headerRow, nextStage = stage, preferredMap?: Record<string, string>) => {
|
||||
if (!workbook) return; setBusy(true); setError(''); invalidateConfiguredSource();
|
||||
try {
|
||||
const result = await api.sourceWorkbookPreview(workbook.uploadId, { sheetName: nextSheet, headerRow: nextHeader, stage: nextStage });
|
||||
setWorkbook(result); setSheetName(result.preview.sheetName); setHeaderRow(result.preview.headerRow);
|
||||
const previous = preferredMap || fieldMap;
|
||||
setFieldMap({ ...matchFields(options.fields[nextStage] || [], result.preview.headers), ...Object.fromEntries(Object.entries(previous).filter(([, header]) => result.preview.headers.includes(header))) });
|
||||
} catch (value) { reportError(value); }
|
||||
finally { setBusy(false); }
|
||||
};
|
||||
const importAndUpdate = async () => {
|
||||
if (!workbook || !canImport) return; setBusy(true); setError('');
|
||||
try {
|
||||
let sourceId = configuredSourceId;
|
||||
if (!sourceId) {
|
||||
const configured = await api.configureSourceWorkbook({ uploadId: workbook.uploadId, stage, year, month, sheetName, headerRow, fieldMap, mode, expectedCurrentReleaseId: workflowStatus.currentReleaseId ?? options.currentReleaseId, ...(target ? { targetDocumentId: target.documentId, targetRevisionId: target.revisionId } : {}), reason: mode === 'REPLACE' ? '测试阶段更新来源数据' : '测试阶段导入来源数据', scopeCode });
|
||||
sourceId = configured.source.id; configuredUploadId.current = workbook.uploadId; setConfiguredSourceId(sourceId);
|
||||
}
|
||||
await uploadOperation.start(() => api.importDataWorkflow({ sourceIds: [sourceId] }));
|
||||
} catch (value) { reportError(value); }
|
||||
finally { setBusy(false); }
|
||||
};
|
||||
const recalculate = async () => {
|
||||
setError('');
|
||||
try { await recalcOperation.start(() => api.recalculateDataWorkflow()); }
|
||||
catch (value) { reportError(value); }
|
||||
};
|
||||
return <div className="nc-simplified-intake">
|
||||
<section className="panel nc-simple-upload-panel">
|
||||
<div className="nc-simple-upload-heading"><div><span className="nc-eyebrow">测试数据维护</span><h2>导入来源并更新报表</h2><p>Excel 标准表头自动识别;如有列未识别,可展开“列识别与预览”修正。</p></div><div className="nc-simple-upload-actions">{workflowStatus.capabilities?.canRecalculate !== false && <Button icon={<ReloadOutlined />} disabled={importBusy} loading={recalcOperation.busy} onClick={() => void recalculate()}>按当前来源重新计算</Button>}</div></div>
|
||||
{!hasImportCapability && <Alert showIcon type="info" message="当前账号没有导入权限" description="可查看来源;导入和更新报表需要发布权限。" />}
|
||||
{error && <Alert showIcon type="error" message="操作未完成,输入内容已保留" description={error} />}
|
||||
{needsNewFile && <Alert showIcon type="info" message="导入设置已修改" description="这份文件已提交过导入,请点击“更换文件”重新选择文件后再导入。" />}
|
||||
{!workbook ? <div className="nc-file-drop nc-simple-file-drop"><FileExcelOutlined /><h3>选择 Excel 来源文件</h3><p>系统自动识别标准表头,文件年月可在下方设置。</p><input className="visually-hidden-file" ref={input} type="file" accept=".xlsx" onChange={event => void readFile(event.target.files?.[0])} aria-label="选择质量数据Excel文件" />{hasImportCapability && <Button type="primary" icon={<UploadOutlined />} loading={busy} onClick={() => input.current?.click()}>选择 Excel 文件</Button>}</div> : <>
|
||||
<div className="nc-simple-file-line"><FileExcelOutlined /><strong>{workbook.sourceFile}</strong>{hasImportCapability && <Button type="link" disabled={importBusy} onClick={() => { setWorkbook(null); setConfiguredSourceId(''); }}>更换文件</Button>}</div>
|
||||
<div className="nc-simple-upload-fields">
|
||||
<label>导入方式<Select disabled={importBusy} value={mode} options={[{ value: 'ADD', label: '新增数据' }, { value: 'REPLACE', label: '替换已有数据' }]} onChange={value => { setMode(value); invalidateConfiguredSource(); }} /></label>
|
||||
<label>数据阶段<Select disabled={importBusy} value={stage} options={[{ value: 'black', label: '黑片' }, { value: 'bright', label: '亮片' }]} onChange={value => { setStage(value); invalidateConfiguredSource(); setFieldMap(matchFields(options.fields[value] || [], headers)); }} /></label>
|
||||
<label>统计年份<InputNumber disabled={importBusy} min={2000} max={2100} value={year} onChange={value => { if (value) setYear(value); invalidateConfiguredSource(); }} /></label>
|
||||
<label>统计月份<Select disabled={importBusy} value={month} options={Array.from({ length: 12 }, (_, index) => ({ value: index + 1, label: `${index + 1}月` }))} onChange={value => { setMonth(value); invalidateConfiguredSource(); }} /></label>
|
||||
{options.scopes.length > 1 && <label>数据范围<Select disabled={importBusy} value={scopeCode} options={options.scopes.map(value => ({ value, label: value === 'ALL' ? '全部范围' : value }))} onChange={value => { setScopeCode(value); invalidateConfiguredSource(); }} /></label>}
|
||||
{mode === 'REPLACE' && <label className="nc-simple-replace-target">替换对象<Select {...readableSelectPopup} disabled={importBusy} showSearch optionFilterProp="label" value={targetId || undefined} placeholder="选择已发布期间和阶段" options={options.targets.map(item => ({ value: item.documentId, label: `${item.year}年${item.month}月 · ${stageName(item.stage)} · ${item.sourceFile}` }))} onChange={value => { setTargetId(value); invalidateConfiguredSource(); }} /></label>}
|
||||
</div>
|
||||
<details className="nc-advanced-import-settings"><summary>列识别与预览</summary>
|
||||
<div className="nc-form-grid"><label>工作表<Select disabled={importBusy} value={sheetName} options={workbook.sheets.map(item => ({ value: item.sheetName, label: item.sheetName }))} onChange={value => void changePreview(value)} /></label><label>表头所在行<InputNumber disabled={importBusy} min={1} max={100} value={headerRow} onChange={value => { if (value) setHeaderRow(value); invalidateConfiguredSource(); }} onBlur={() => { if (workbook.preview.headerRow !== headerRow) void changePreview(sheetName, headerRow); }} /></label></div>
|
||||
<div className="nc-section-title"><h3>业务字段对应 Excel 列</h3><span>{missing.length ? `还有 ${missing.length} 个必填字段待匹配` : duplicate ? '同一 Excel 列不能重复对应' : '已匹配'}</span></div><ColumnMatching disabled={importBusy} fields={fields} headers={headers} value={fieldMap} onChange={value => { setFieldMap(value); invalidateConfiguredSource(); }} />
|
||||
<h3>原表预览</h3><SampleTable headers={headers} rows={workbook.preview.sampleRows.map(row => row.values)} />
|
||||
</details>
|
||||
{missing.length > 0 && <Alert showIcon type="warning" message="有必填列尚未识别" description={`请展开“列识别与预览”完成:${missing.map(item => item.name).join('、')}`} />}
|
||||
<div className="nc-simple-submit-row"><span>{mode === 'REPLACE' ? '替换后会按当前规则重算并更新对应报表。' : `${year}年${String(month).padStart(2, '0')}月 · ${stageName(stage)} · 完成后自动刷新报表`}</span>{hasImportCapability && <Button type="primary" size="large" loading={busy || uploadOperation.busy} disabled={!canImport || busy || uploadOperation.busy} onClick={() => void importAndUpdate()}>导入并更新报表</Button>}</div>
|
||||
</>}
|
||||
<WorkflowOperationFeedback operation={uploadOperation.operation} error={uploadOperation.error} busy={uploadOperation.busy} onResume={uploadOperation.resume} />
|
||||
<WorkflowOperationFeedback operation={recalcOperation.operation} error={recalcOperation.error} busy={recalcOperation.busy} onResume={recalcOperation.resume} />
|
||||
</section>
|
||||
</div>;
|
||||
}
|
||||
|
||||
function ValidationNotice({ value }: { value: unknown }) {
|
||||
const result = asRow(value); const missing = asRows(result.missingStages);
|
||||
const errors = [...(Array.isArray(result.errors) ? result.errors : []), ...missing.map(item => { const monthValue = String(item.month || ''); const match = monthValue.match(/^(\d{4})[-/](\d{1,2})$/); return `${txt(item.year || match?.[1])}年${txt(match?.[2] || item.month)}月${stageName(item.stage)}尚未到齐`; }), ...(Number(result.missingExpectedSlots) > 0 ? [`尚缺 ${Number(result.missingExpectedSlots)} 个应到来源`] : []), ...(Number(result.coverageOverlapCount) > 0 ? ['同一期间的数据范围重叠'] : []), ...(Array.isArray(result.blockingMappingIssues) ? result.blockingMappingIssues : Number(result.blockingMappingIssues) > 0 ? [`有 ${Number(result.blockingMappingIssues)} 项对应关系需要处理`] : [])];
|
||||
return errors.length ? <Alert showIcon type="warning" message="校验仍有需要处理的事项" description={<ul className="nc-issue-list">{errors.map((item, index) => <li key={index}>{txt(item)}</li>)}</ul>} /> : result.complete === true ? <Alert showIcon type="success" message="来源及对应关系校验通过" /> : result.complete === false ? <Alert showIcon type="warning" message="候选校验尚未通过" description="请核对来源是否齐备,以及基础数据和对应关系是否完整。" /> : null;
|
||||
}
|
||||
|
||||
export function DataWorkflowHub({ user, sources, currentReleaseId, onUnauthorized, onRefresh }: { user: AuthUser; sources: SourceItem[]; currentReleaseId: string | null; onUnauthorized: (error: unknown) => boolean; onRefresh: () => void }) {
|
||||
const { message } = App.useApp();
|
||||
const [mode, setMode] = useState<'ADD' | 'REPLACE' | 'REBUILD' | null>(null);
|
||||
const [options, setOptions] = useState<SourceUploadOptions | null>(null);
|
||||
const [workflowStatus, setWorkflowStatus] = useState<DataWorkflowStatus | null>(null);
|
||||
const [workflowStatusLoaded, setWorkflowStatusLoaded] = useState(false);
|
||||
const [optionError, setOptionError] = useState('');
|
||||
const [candidates, setCandidates] = useState<Row[]>([]);
|
||||
const [resumeId, setResumeId] = useState('');
|
||||
const canMaintain = rolesAllow(user, ['SYSTEM_ADMIN', 'DATA_MAINTAINER']);
|
||||
const canPublish = rolesAllow(user, ['SYSTEM_ADMIN', 'DATA_PUBLISHER']);
|
||||
const loadOptions = async () => {
|
||||
try { setOptions(await api.sourceUploadOptions()); setOptionError(''); }
|
||||
catch (error) { if (!onUnauthorized(error)) setOptionError(failure(error)); }
|
||||
};
|
||||
const loadWorkflowStatus = async () => {
|
||||
try { setWorkflowStatus(await api.dataWorkflowStatus()); }
|
||||
catch (error) { if (!onUnauthorized(error)) setWorkflowStatus(null); }
|
||||
finally { setWorkflowStatusLoaded(true); }
|
||||
};
|
||||
const loadCandidates = async () => {
|
||||
try { const result = await api.releases(); setCandidates(collectionItems(result).filter(row => String(row.status).toUpperCase() === 'CANDIDATE')); }
|
||||
catch (error) { if (!onUnauthorized(error)) setOptionError(failure(error)); }
|
||||
};
|
||||
useEffect(() => { void loadOptions(); void loadCandidates(); void loadWorkflowStatus(); }, [currentReleaseId, sources]);
|
||||
useEffect(() => { const candidate = new URLSearchParams(window.location.search).get('candidateReleaseId'); if (candidate) setResumeId(candidate); }, []);
|
||||
const opened = mode !== null || Boolean(resumeId);
|
||||
const open = (next: 'ADD' | 'REPLACE' | 'REBUILD') => { setMode(next); setResumeId(''); void loadOptions(); };
|
||||
if (!workflowStatusLoaded) return <section className="panel nc-operation-status"><div><strong>读取当前维护模式</strong><span>正在加载可执行操作</span></div><Spin /></section>;
|
||||
if (workflowStatus?.simplified === true && workflowStatus.mode === 'TEST' && options) return <SimplifiedDataWorkflow options={options} workflowStatus={workflowStatus} onUnauthorized={onUnauthorized} onRefresh={onRefresh} />;
|
||||
return <>
|
||||
<section className="nc-intake-start panel">
|
||||
<div className="nc-intake-intro"><span className="nc-eyebrow">日常数据维护</span><h2>选择文件,核对后发布</h2><p>文件名可以保持原样。黑片或亮片、统计年月和表头均在下一步选择。</p></div>
|
||||
<div className="nc-primary-actions"><Button type="primary" size="large" icon={<UploadOutlined />} disabled={!canMaintain || !options} onClick={() => open('ADD')}>上传新数据</Button><Button size="large" icon={<SwapOutlined />} disabled={!canMaintain || !options || !options.targets.length} onClick={() => open('REPLACE')}>替换已有数据</Button></div>
|
||||
<div className="nc-intake-links"><Button type="link" disabled={!canMaintain || !options?.targets.length} onClick={() => open('REBUILD')}>按当前来源重新计算</Button><span>上传 → 选择年月 → 匹配列 → 校验 → 发布</span></div>
|
||||
</section>
|
||||
{optionError && <Alert type="error" showIcon message="数据操作信息读取失败" description={optionError} action={<Button size="small" onClick={() => { void loadOptions(); void loadCandidates(); }}>重试</Button>} />}
|
||||
{!canMaintain && <Alert showIcon type="info" message={canPublish ? '当前账号可以核对和发布已有候选数据' : '上传和替换需要数据维护权限'} description="已授权的操作会按账号权限显示。" />}
|
||||
{candidates.length > 0 && <section className="nc-pending-strip panel"><div><strong>待完成的数据</strong><span>已保存的候选可继续校验、对账和发布。</span></div><Select {...readableSelectPopup} aria-label="选择待完成候选数据" placeholder="选择候选数据" value={resumeId || undefined} options={candidates.map(row => ({ value: String(row.id), label: `${txt(row.name || row.id)}${row.complete === false ? ' · 校验未通过' : ''}` }))} onChange={value => { setMode(null); setResumeId(value); }} /></section>}
|
||||
{opened && options && <DataUploadWizard key={`${mode}:${resumeId}`} user={user} mode={mode || 'ADD'} options={options} sources={sources} resumeId={resumeId} onUnauthorized={onUnauthorized} onClose={() => { setMode(null); setResumeId(''); }} onComplete={() => { onRefresh(); void loadOptions(); void loadCandidates(); message.success('操作结果已刷新'); }} />}
|
||||
</>;
|
||||
}
|
||||
|
||||
export function SourceFilesPanel({ user, sources, loading, onUnauthorized, onRefresh }: { user: AuthUser; sources: SourceItem[]; loading: boolean; onUnauthorized: (error: unknown) => boolean; onRefresh: () => void }) {
|
||||
const { message } = App.useApp();
|
||||
const [showDeleted, setShowDeleted] = useState(false);
|
||||
const [deleted, setDeleted] = useState<SourceDeletionPreview[]>([]);
|
||||
const [workflowStatus, setWorkflowStatus] = useState<DataWorkflowStatus | null>(null);
|
||||
const [currentSourceIds, setCurrentSourceIds] = useState<string[] | null>(null);
|
||||
const [deletedLoading, setDeletedLoading] = useState(false);
|
||||
const [deletedError, setDeletedError] = useState('');
|
||||
const [workflowStatusLoaded, setWorkflowStatusLoaded] = useState(false);
|
||||
const [selected, setSelected] = useState<{ id: string; restore: boolean } | null>(() => { const id = new URLSearchParams(window.location.search).get('sourceDeleteId'); return id ? { id, restore: false } : null; });
|
||||
const canOperate = rolesAllow(user, ['SYSTEM_ADMIN', 'DATA_MAINTAINER', 'DATA_PUBLISHER']);
|
||||
const loadDeleted = async () => {
|
||||
setDeletedLoading(true);
|
||||
try { const result = await api.deletedSources(); setDeleted(result.items); setDeletedError(''); }
|
||||
catch (value) { if (!onUnauthorized(value)) setDeletedError(failure(value)); }
|
||||
finally { setDeletedLoading(false); }
|
||||
};
|
||||
const sourceOperation = useDataWorkflowOperation('source-maintenance', value => {
|
||||
onRefresh(); if (showDeleted) void loadDeleted();
|
||||
message.success(String(value.operationType || '').toUpperCase().includes('RESTORE') ? '来源已恢复,报表已更新' : '来源已删除,报表已更新');
|
||||
});
|
||||
useEffect(() => {
|
||||
void api.dataWorkflowStatus().then(setWorkflowStatus).catch(() => setWorkflowStatus(null)).finally(() => setWorkflowStatusLoaded(true));
|
||||
void api.sourceUploadOptions().then(options => setCurrentSourceIds(options.currentSourceIds || [])).catch(() => setCurrentSourceIds(null));
|
||||
}, [sources]);
|
||||
useEffect(() => { if (showDeleted && canOperate) void loadDeleted(); }, [showDeleted, sources]);
|
||||
const period = (source: DeletionSource) => source.year && source.month ? `${source.year}年${String(source.month).padStart(2, '0')}月` : '尚未确认';
|
||||
const close = () => { setSelected(null); const url = new URL(window.location.href); if (url.searchParams.has('sourceDeleteId')) { url.searchParams.delete('sourceDeleteId'); window.history.replaceState({}, '', `${url.pathname}${url.search}${url.hash}`); } };
|
||||
const simplified = workflowStatus?.simplified === true && workflowStatus.mode === 'TEST';
|
||||
const runSourceOperation = async (id: string, restore: boolean) => {
|
||||
try { await sourceOperation.start(() => restore ? api.restoreDataWorkflowSource(id) : api.deleteDataWorkflowSource(id)); }
|
||||
catch (value) { if (!onUnauthorized(value)) setDeletedError(failure(value)); }
|
||||
};
|
||||
return <>
|
||||
<section className="panel section-panel nc-source-files">
|
||||
<div className="resource-toolbar"><strong>{showDeleted ? '已删除的来源文件' : '已接收的来源文件'}</strong><span>{showDeleted ? `${deleted.length} 个文件 · 原件和处理记录保留` : simplified ? `${sources.length} 个文件 · 来源变化会自动重算并更新报表` : `${sources.length} 个文件 · 上传或接收不等于已经发布`}</span>{canOperate && <Checkbox checked={showDeleted} onChange={event => setShowDeleted(event.target.checked)}>查看已删除来源</Checkbox>}</div>
|
||||
{simplified && <p className="nc-source-maintenance-note">删除会从当前数据中移除来源并更新报表;恢复会自动重新计算。原文件和处理记录保留。</p>}
|
||||
{deletedError && showDeleted && <Alert showIcon type="error" message="已删除来源读取失败" description={deletedError} action={<Button size="small" onClick={() => void loadDeleted()}>重试</Button>} />}
|
||||
{sourceOperation.operation && <WorkflowOperationFeedback operation={sourceOperation.operation} error={sourceOperation.error} busy={sourceOperation.busy} onResume={sourceOperation.resume} />}
|
||||
<Table<DeletionSource> size="small" bordered loading={showDeleted ? deletedLoading : loading} dataSource={showDeleted ? deleted.map(item => item.source) : sources} rowKey="id" pagination={{ pageSize: 12, showSizeChanger: false }} scroll={{ x: 980 }} columns={[
|
||||
{ title: '来源文件', dataIndex: 'sourceFile', key: 'sourceFile', width: 340, ellipsis: true },
|
||||
{ title: '阶段', dataIndex: 'stage', key: 'stage', align: 'center', width: 90, render: value => <Tag>{stageName(value)}</Tag> },
|
||||
{ title: '统计期间', key: 'period', align: 'center', width: 140, render: (_, row) => period(row) },
|
||||
{ title: showDeleted ? '删除理由' : '文件大小', dataIndex: showDeleted ? 'deletionReason' : 'sizeBytes', key: 'sizeBytes', align: showDeleted ? 'left' : 'right', width: showDeleted ? 220 : 120, ellipsis: true, render: value => showDeleted ? txt(value) : typeof value === 'number' ? `${(value / 1024).toFixed(1)} KB` : '—' },
|
||||
{ title: '接入状态', dataIndex: 'status', key: 'status', align: 'center', width: 130, render: value => showDeleted ? <Tag>已删除</Tag> : ({ DISCOVERED: '已接收', QUEUED: '等待校验', RUNNING: '正在校验', IMPORTED: '已校验', UNIDENTIFIED: '待确认', RETURNED: '已退回', COVERAGE_CONFLICT: '范围待确认', WRITING: '文件写入中' } as Record<string, string>)[String(value)] || value },
|
||||
{ title: '操作', key: 'actions', align: 'center', fixed: 'right', width: 170, render: (_, row) => {
|
||||
const onCurrentRelease = currentSourceIds?.includes(row.id) ?? false;
|
||||
const permitted = !simplified || (showDeleted ? workflowStatus?.capabilities?.canRestoreSource !== false : currentSourceIds !== null && workflowStatus?.capabilities?.canDeleteSource !== false && (!onCurrentRelease || workflowStatus?.capabilities?.canDeleteCurrentSource !== false));
|
||||
if (!workflowStatusLoaded || !canOperate || !permitted) return null;
|
||||
return <Button type="link" danger={!showDeleted} icon={showDeleted ? <UndoOutlined /> : <DeleteOutlined />} disabled={sourceOperation.busy} onClick={() => simplified ? void runSourceOperation(row.id, showDeleted) : setSelected({ id: row.id, restore: showDeleted })}>{simplified ? showDeleted ? '恢复并更新报表' : '删除并更新报表' : showDeleted ? '恢复' : '删除'}</Button>;
|
||||
} },
|
||||
]} locale={{ emptyText: showDeleted ? '没有已删除的来源。' : '尚无来源文件,点击“上传新数据”开始。' }} />
|
||||
</section>
|
||||
{selected && !simplified && <SourceDeletionDialog key={`${selected.id}:${selected.restore}`} user={user} sourceId={selected.id} restoring={selected.restore} sources={sources} onUnauthorized={onUnauthorized} onClose={close} onRefresh={() => { onRefresh(); if (showDeleted) void loadDeleted(); }} />}
|
||||
</>;
|
||||
}
|
||||
|
||||
function SourceDeletionDialog({ user, sourceId, restoring, sources, onUnauthorized, onClose, onRefresh }: { user: AuthUser; sourceId: string; restoring: boolean; sources: SourceItem[]; onUnauthorized: (error: unknown) => boolean; onClose: () => void; onRefresh: () => void }) {
|
||||
const { message } = App.useApp();
|
||||
const [preview, setPreview] = useState<SourceDeletionPreview | null>(null);
|
||||
const [busy, setBusy] = useState(true); const [error, setError] = useState(''); const [notice, setNotice] = useState('');
|
||||
const [reason, setReason] = useState(''); const [confirmed, setConfirmed] = useState(false); const [finished, setFinished] = useState(false);
|
||||
const [candidateId, setCandidateId] = useState(''); const [options, setOptions] = useState<SourceUploadOptions | null>(null);
|
||||
const requestKey = useRef(crypto.randomUUID()); const buildKey = useRef(crypto.randomUUID());
|
||||
const reportError = (value: unknown) => { if (!onUnauthorized(value)) setError(failure(value)); };
|
||||
const load = async () => { setBusy(true); try { const result = await api.sourceDeletionPreview(sourceId); setPreview(result); setError(''); if (restoring && !result.hidden) { setFinished(true); setNotice('此来源已在日常清单中,无需重复恢复。'); } } catch (value) { reportError(value); } finally { setBusy(false); } };
|
||||
useEffect(() => { void load(); }, [sourceId]);
|
||||
const request = preview?.changeRequest; const requestStatus = String(request?.status || '');
|
||||
const isRequested = preview?.nextAction === 'REVIEW_WITHDRAWAL'; const isApproved = preview?.nextAction === 'BUILD_WITHDRAWAL_CANDIDATE'; const isBuilt = preview?.nextAction === 'RECONCILE_CANDIDATE';
|
||||
const withdrawing = preview?.mode === 'WITHDRAW_CURRENT' || isRequested || isApproved || isBuilt;
|
||||
const canPublish = rolesAllow(user, ['SYSTEM_ADMIN', 'DATA_PUBLISHER']);
|
||||
const canReview = preview?.canReview ?? canPublish; const canBuild = preview?.canBuild ?? canPublish;
|
||||
const awaitingTask = preview?.nextAction === 'WAIT_FOR_TASK';
|
||||
const canStart = Boolean(preview?.canDelete && !awaitingTask && !preview.hidden && !isRequested && !isApproved && !isBuilt);
|
||||
const canRestore = Boolean(preview?.canRestore && preview.hidden);
|
||||
const actualRestore = Boolean((restoring || preview?.hidden) && !finished);
|
||||
const reasonLabel = actualRestore ? '恢复理由' : isRequested ? '审批说明' : '删除理由';
|
||||
const act = async (kind: 'delete' | 'restore' | 'approve' | 'reject' | 'build') => {
|
||||
if (!preview) return; setBusy(true); setError('');
|
||||
try {
|
||||
if (kind === 'delete') {
|
||||
const result = await api.deleteSource(sourceId, { expectedCurrentReleaseId: preview.currentReleaseId, expectedDeleteVersion: preview.deleteVersion, ...(preview.currentUsage ? { expectedRevisionId: preview.currentUsage.revisionId } : {}), reason: reason.trim(), idempotencyKey: requestKey.current });
|
||||
setPreview(result); requestKey.current = crypto.randomUUID(); setNotice(result.hidden ? '来源已从日常清单删除,可在“查看已删除来源”中恢复。' : '删除申请已提交,当前正式数据保持不变;下一步由发布者审批。'); setFinished(result.hidden);
|
||||
} else if (kind === 'restore') {
|
||||
const result = await api.restoreSource(sourceId, { expectedCurrentReleaseId: preview.currentReleaseId, expectedDeleteVersion: preview.deleteVersion, reason: reason.trim() });
|
||||
setPreview(result); setNotice('来源已恢复到日常清单。恢复文件清单不会修改已发布的数据结果。'); setFinished(true);
|
||||
} else if (kind === 'approve' || kind === 'reject') {
|
||||
if (!request?.id) throw new Error('删除申请已变化,请刷新后重试');
|
||||
await api.reviewSourceChange(request.id, { approve: kind === 'approve', expectedRowVersion: request.rowVersion, reason: reason.trim() });
|
||||
setPreview(await api.sourceDeletionPreview(sourceId)); setNotice(kind === 'approve' ? '删除申请已批准,下一步生成候选数据。' : '删除申请已驳回,当前正式数据未改变。');
|
||||
} else {
|
||||
if (!request?.id) throw new Error('删除申请已变化,请刷新后重试');
|
||||
const result = await api.buildSourceChange(request.id, { expectedCurrentReleaseId: preview.currentReleaseId, idempotencyKey: buildKey.current });
|
||||
const updated = await api.sourceDeletionPreview(sourceId); setPreview(updated);
|
||||
const releaseId = String(result.releaseId || asRow(result.request).resultReleaseId || updated.changeRequest?.resultReleaseId || '');
|
||||
if (releaseId) { setNotice('删除候选已生成,请核对差异后发布。'); await openCandidate(releaseId); }
|
||||
else { const run = asRow(result.run); throw new Error(String(run.errorMessage || '候选尚未生成,请刷新查看任务结果')); }
|
||||
}
|
||||
setReason(''); setConfirmed(false); onRefresh();
|
||||
} catch (value) { reportError(value); }
|
||||
finally { setBusy(false); }
|
||||
};
|
||||
const openCandidate = async (releaseId: string) => {
|
||||
setBusy(true); setError('');
|
||||
try { const support = await api.sourceUploadOptions(); setOptions(support); setCandidateId(releaseId); }
|
||||
catch (value) { reportError(value); } finally { setBusy(false); }
|
||||
};
|
||||
const handoff = async () => {
|
||||
const url = new URL(window.location.href); url.searchParams.set('page', 'sources'); url.searchParams.set('sourceDeleteId', sourceId); url.searchParams.delete('candidateReleaseId');
|
||||
try { await navigator.clipboard.writeText(url.toString()); message.success('处理链接已复制,可交由有权限的同事继续'); } catch (value) { reportError(value); }
|
||||
};
|
||||
const waitingForColleague = !finished && Boolean(preview && (actualRestore ? !canRestore : isRequested ? !canReview : isApproved ? !canBuild : isBuilt ? false : !canStart));
|
||||
const deletionStep = preview?.hidden ? 4 : isBuilt ? 3 : isApproved ? 2 : isRequested ? 1 : 0;
|
||||
return <>
|
||||
<Modal className="management-modal nc-workflow-modal nc-source-delete-modal" open={!candidateId} width={960} title={finished ? preview?.hidden ? '来源已删除' : '操作已完成' : actualRestore ? '恢复来源' : withdrawing ? '删除当前使用的来源' : '删除来源'} maskClosable={!busy} onCancel={onClose} footer={<div className="nc-modal-footer"><span>原文件及处理记录持续保留,删除操作可追溯。</span><div><Button onClick={onClose}>{finished ? '完成' : '关闭'}</Button>{!finished && preview && <>
|
||||
<Button icon={<ReloadOutlined />} disabled={busy} onClick={() => void load()}>刷新状态</Button>
|
||||
{actualRestore ? <Button type="primary" loading={busy} disabled={!canRestore || !confirmed || !reason.trim()} onClick={() => void act('restore')}>确认恢复来源</Button> : isRequested ? <>{canReview && <><Button danger disabled={busy || !reason.trim()} onClick={() => void act('reject')}>驳回申请</Button><Button type="primary" loading={busy} disabled={!confirmed || !reason.trim()} onClick={() => void act('approve')}>批准删除申请</Button></>}</> : isApproved ? <Button type="primary" loading={busy} disabled={!canBuild || !confirmed} onClick={() => void act('build')}>生成删除候选</Button> : isBuilt ? <Button type="primary" loading={busy} disabled={!request?.resultReleaseId} onClick={() => { if (request?.resultReleaseId) void openCandidate(request.resultReleaseId); }}>核对并发布删除候选</Button> : <Button type="primary" danger loading={busy} disabled={!canStart || !confirmed || !reason.trim()} onClick={() => void act('delete')}>{withdrawing ? '提交删除申请' : '确认删除来源'}</Button>}
|
||||
</>}</div></div>}>
|
||||
{error && <Alert type="error" showIcon message="操作未完成" description={error} />}
|
||||
{notice && <Alert type={finished ? 'success' : 'info'} showIcon message={notice} />}
|
||||
<Spin spinning={busy}>{preview ? <>
|
||||
<div className="nc-file-summary"><FileExcelOutlined /><strong>{preview.source.sourceFile}</strong><span>{preview.source.year && preview.source.month ? `${preview.source.year}年${preview.source.month}月` : '期间待确认'} · {stageName(preview.source.stage)}</span></div>
|
||||
{withdrawing && !actualRestore && <Steps className="nc-delete-steps" current={deletionStep} size="small" items={[{ title: '确认影响' }, { title: '审批申请' }, { title: '生成候选' }, { title: '对账与发布' }, { title: '移入已删除' }]} />}
|
||||
<div className="nc-review-facts nc-deletion-impact"><div><small>当前正式数据</small><strong>{preview.currentUsage ? '正在使用此来源' : '未使用此来源'}</strong></div><div><small>归档来源记录</small><strong>{preview.history.revisionCount} 个</strong></div><div><small>正式处理记录</small><strong>{preview.history.publishedReleaseCount} 个</strong></div><div><small>候选处理记录</small><strong>{preview.history.candidateReleaseCount} 个</strong></div></div>
|
||||
{!finished && <Alert showIcon type={preview.currentUsage ? 'warning' : 'info'} message={actualRestore ? '恢复到来源清单' : preview.currentUsage ? '此文件参与了当前正式结果,须完成审批、候选和发布' : '仅从日常来源清单删除'} description={actualRestore ? '恢复后可重新选择此来源;已有查询结果和处理记录保持原样。' : preview.currentUsage ? '提交申请和批准均不会改变当前查询结果。生成候选后须核对差异并明确发布,发布成功才从当前结果移除此来源,并转入已删除清单。' : '不会删除磁盘原文件,不会影响已有结果或处理记录;可从“查看已删除来源”恢复。'} />}
|
||||
{preview.source.deletionReason && !request && <section className="nc-delete-request"><p><span>删除理由</span>{preview.source.deletionReason}</p></section>}{request && <section className="nc-delete-request"><div><strong>删除申请</strong><Tag>{({ REQUESTED: '等待审批', APPROVED: '已批准,等待候选', REJECTED: '已驳回', BUILT: '候选已生成' } as Record<string, string>)[requestStatus] || requestStatus}</Tag></div><p><span>申请理由</span>{txt(request.reason)}</p>{request.reviewReason && <p><span>审批说明</span>{request.reviewReason}</p>}</section>}
|
||||
{!finished && awaitingTask && <Alert type="info" showIcon message="来源仍在校验或计算中" description="任务完成后再删除,点击“刷新状态”重新检查。" />}
|
||||
{!finished && !isBuilt && !awaitingTask && <>
|
||||
{actualRestore || canStart || (isRequested && canReview) ? <Form layout="vertical"><Form.Item label={reasonLabel} required><Input.TextArea aria-label={reasonLabel} rows={3} value={reason} maxLength={1000} placeholder={actualRestore ? '说明恢复此来源的原因' : isRequested ? '填写批准或驳回的依据' : '说明删除此来源的原因'} onChange={event => setReason(event.target.value)} /></Form.Item></Form> : null}
|
||||
{(actualRestore && canRestore || canStart || isRequested && canReview || isApproved && canBuild) && <Checkbox checked={confirmed} onChange={event => setConfirmed(event.target.checked)}>{actualRestore ? '我已核对文件和期间,确认恢复来源清单。' : isApproved ? '我已核对批准的删除范围,确认生成候选;正式数据在发布前保持不变。' : isRequested ? '我已核对该来源及删除影响,确认批准此申请。' : preview.currentUsage ? '我已核对删除影响,确认提交申请并保留原件及历史记录。' : '我确认将此文件从日常清单删除,并保留原件及历史记录。'}</Checkbox>}
|
||||
</>}
|
||||
{waitingForColleague && !awaitingTask && <Alert type="info" showIcon message={isRequested ? '等待有审批权限的发布者继续' : isApproved ? '等待有权限的发布者生成候选' : actualRestore ? '此账号没有恢复权限' : '此账号没有本次删除操作权限'} description={<>{preview.blockedReason && <p>{preview.blockedReason}</p>}<span>可复制当前处理链接交接;对方打开后会看到相同来源、申请和下一步。</span><Button type="link" onClick={() => void handoff()}>复制处理链接</Button></>} />}
|
||||
{!finished && isBuilt && <Alert type="info" showIcon message="删除候选已保存,等待核对与发布" description="点击“核对并发布删除候选”继续查看差异;没有发布权限的账号可在候选窗口复制交接链接。" />}
|
||||
</> : !busy ? <Empty description="未读取到来源信息" /> : <div className="loading-panel">正在核对来源及影响…</div>}</Spin>
|
||||
</Modal>
|
||||
{candidateId && options && <DataUploadWizard key={`deletion:${candidateId}`} user={user} mode="ADD" purpose="WITHDRAW" handoffSourceId={sourceId} initialReason={request?.reason} options={options} sources={sources} resumeId={candidateId} onUnauthorized={onUnauthorized} onClose={() => { setCandidateId(''); void load(); }} onComplete={() => { setFinished(true); setNotice('删除候选已发布,该来源已从当前结果移除;原件和处理记录保留。'); onRefresh(); void load(); }} />}
|
||||
</>;
|
||||
}
|
||||
|
||||
function DataUploadWizard({ user, mode, purpose, handoffSourceId, initialReason, options, sources, resumeId, onUnauthorized, onClose, onComplete }: { user: AuthUser; mode: 'ADD' | 'REPLACE' | 'REBUILD'; purpose?: 'WITHDRAW'; handoffSourceId?: string; initialReason?: string; options: SourceUploadOptions; sources: SourceItem[]; resumeId: string; onUnauthorized: (error: unknown) => boolean; onClose: () => void; onComplete: () => void }) {
|
||||
const { message } = App.useApp(); const input = useRef<HTMLInputElement>(null); const generation = useRef(0); const importKey = useRef(crypto.randomUUID()); const publishKey = useRef(crypto.randomUUID());
|
||||
const [pollAttempt, setPollAttempt] = useState(0);
|
||||
const [step, setStep] = useState(resumeId ? 4 : 0); const [busy, setBusy] = useState(false); const [error, setError] = useState('');
|
||||
const [workbook, setWorkbook] = useState<WorkbookPreview | null>(null); const [stage, setStage] = useState<DataStage>('black');
|
||||
const [year, setYear] = useState(new Date().getFullYear()); const [month, setMonth] = useState(new Date().getMonth() + 1);
|
||||
const [scopeCode, setScopeCode] = useState(options.scopes[0] || 'ALL'); const [targetId, setTargetId] = useState('');
|
||||
const [sheetName, setSheetName] = useState(''); const [headerRow, setHeaderRow] = useState(1); const [fieldMap, setFieldMap] = useState<Record<string, string>>({});
|
||||
const [configuredSourceId, setConfiguredSourceId] = useState('');
|
||||
const [reason, setReason] = useState(initialReason || ''); const [run, setRun] = useState<Row | null>(null); const [release, setRelease] = useState<Row | null>(null);
|
||||
const [reconciliation, setReconciliation] = useState<Row | null>(null); const [issues, setIssues] = useState<Row[]>([]);
|
||||
const [differenceReason, setDifferenceReason] = useState(''); const [confirmDifferences, setConfirmDifferences] = useState(false); const [publishConfirmed, setPublishConfirmed] = useState(false); const [published, setPublished] = useState(false);
|
||||
const target = options.targets.find(item => item.documentId === targetId); const fields = options.fields[stage] || [];
|
||||
const headers = workbook?.preview.headers || []; const missingFields = fields.filter(field => field.required && !fieldMap[field.name]); const duplicateColumns = Object.values(fieldMap).length !== new Set(Object.values(fieldMap)).size;
|
||||
const canPublish = rolesAllow(user, ['SYSTEM_ADMIN', 'DATA_PUBLISHER']);
|
||||
const reportError = (value: unknown) => { if (!onUnauthorized(value)) setError(failure(value)); };
|
||||
const loadCandidate = async (id: string) => {
|
||||
const inspected = await api.governanceReleaseInspect(id); setRelease(asRow(inspected.release));
|
||||
const result = await api.governanceReleaseReconciliations(id); const list = collectionItems(result); const selected = list.find(item => String(item.id) === String(result.acceptanceId)) || list[0];
|
||||
setReconciliation(selected?.id ? await api.governanceReconciliation(String(selected.id)) : null);
|
||||
};
|
||||
useEffect(() => { if (resumeId) { setBusy(true); loadCandidate(resumeId).catch(reportError).finally(() => setBusy(false)); } return () => { generation.current++; }; }, []);
|
||||
const runId = String(run?.id || '');
|
||||
useEffect(() => {
|
||||
if (!runId) return;
|
||||
let alive = true; let timer: ReturnType<typeof setTimeout>;
|
||||
const poll = async () => {
|
||||
try {
|
||||
const result = await api.importRun(runId); if (!alive) return; setRun(result.run);
|
||||
if (String(result.run.status) === 'COMPLETED') {
|
||||
const id = String(result.run.resultReleaseId || ''); if (!id) throw new Error('校验已完成,但没有返回候选数据');
|
||||
await loadCandidate(id); if (!alive) return; setStep(4); setBusy(false); onComplete();
|
||||
if (asRow(result.run.validation).complete === false) { const issueList = await api.importIssues(runId); if (alive) setIssues(collectionItems(issueList)); }
|
||||
} else if (['FAILED', 'CANCELLED'].includes(String(result.run.status))) {
|
||||
setBusy(false); const issueList = await api.importIssues(runId); if (alive) setIssues(collectionItems(issueList));
|
||||
} else timer = setTimeout(poll, 1400);
|
||||
} catch (value) { if (alive) { reportError(value); setBusy(false); } }
|
||||
};
|
||||
timer = setTimeout(poll, 700); return () => { alive = false; clearTimeout(timer); };
|
||||
}, [runId, pollAttempt]);
|
||||
const readFile = async (file?: File) => {
|
||||
if (!file) return; setBusy(true); setError(''); const ownGeneration = generation.current;
|
||||
try { const result = await api.previewSourceWorkbook(file); if (ownGeneration !== generation.current) return; setWorkbook(result); setSheetName(result.preview.sheetName); setHeaderRow(result.preview.headerRow); setFieldMap(matchFields(options.fields[stage] || [], result.preview.headers)); setStep(1); }
|
||||
catch (value) { reportError(value); } finally { setBusy(false); if (input.current) input.current.value = ''; }
|
||||
};
|
||||
const changePreview = async (nextSheet: string, nextHeader: number, nextStage = stage, preferredMap?: Record<string, string>) => {
|
||||
if (!workbook) return; setBusy(true); setError('');
|
||||
try { const result = await api.sourceWorkbookPreview(workbook.uploadId, { sheetName: nextSheet, headerRow: nextHeader, stage: nextStage }); setWorkbook(result); setSheetName(result.preview.sheetName); setHeaderRow(result.preview.headerRow); const chosen = preferredMap || fieldMap; setFieldMap({ ...matchFields(options.fields[nextStage] || [], result.preview.headers), ...Object.fromEntries(Object.entries(chosen).filter(([, header]) => result.preview.headers.includes(header))) }); }
|
||||
catch (value) { reportError(value); } finally { setBusy(false); }
|
||||
};
|
||||
const chooseTarget = (id: string) => { const selected = options.targets.find(item => item.documentId === id); setTargetId(id); if (selected) { setStage(selected.stage); setYear(selected.year); setMonth(selected.month); setScopeCode(selected.scopeCode); setFieldMap(matchFields(options.fields[selected.stage] || [], headers)); } };
|
||||
const beginImport = async () => {
|
||||
if (!workbook || missingFields.length || (mode === 'REPLACE' && !target)) return;
|
||||
setBusy(true); setError('');
|
||||
try {
|
||||
const configured = configuredSourceId ? { source: { id: configuredSourceId } } : await api.configureSourceWorkbook({ uploadId: workbook.uploadId, stage, year, month, sheetName, headerRow, fieldMap, mode: mode === 'REPLACE' ? 'REPLACE' : 'ADD', expectedCurrentReleaseId: options.currentReleaseId, ...(target ? { targetDocumentId: target.documentId, targetRevisionId: target.revisionId } : {}), reason: reason.trim() || `新增${year}年${month}月${stageName(stage)}数据`, scopeCode });
|
||||
setConfiguredSourceId(configured.source.id);
|
||||
const created = asRow(await api.startImport({ sourceIds: [configured.source.id], expectedCurrentReleaseId: options.currentReleaseId, idempotencyKey: importKey.current })); const nextRun = asRow(created.run || created); setRun(nextRun);
|
||||
if (!nextRun.id) throw new Error('服务端未返回计算任务,已接收的来源可稍后重新校验');
|
||||
} catch (value) { reportError(value); setBusy(false); }
|
||||
};
|
||||
const rebuild = async () => {
|
||||
setBusy(true); setError(''); setStep(3);
|
||||
try {
|
||||
if (!options.currentReleaseId) throw new Error('当前没有可用于重新计算的来源');
|
||||
const inspected = await api.governanceReleaseInspect(options.currentReleaseId); const members = asRows(inspected.members);
|
||||
const ids = options.currentSourcesComplete && options.currentSourceIds?.length ? options.currentSourceIds : members.map(member => sources.find(source => source.sha256 === member.sha256 && source.stage === member.stage && source.year === Number(member.sourceYear) && source.month === Number(member.sourceMonth))?.id);
|
||||
if (!ids.length || ids.some(id => !id)) throw new Error('部分原始文件当前不可用于重算,请重新上传缺少的原始文件。');
|
||||
const created = asRow(await api.startImport({ sourceIds: ids as string[], expectedCurrentReleaseId: options.currentReleaseId, idempotencyKey: importKey.current })); setRun(asRow(created.run || created));
|
||||
} catch (value) { reportError(value); setBusy(false); }
|
||||
};
|
||||
const reconcile = async () => {
|
||||
if (!release?.id) return; setBusy(true); setError('');
|
||||
try { const created = await api.createGovernanceReconciliation(String(release.id), { ...(options.currentReleaseId ? { baselineReleaseId: options.currentReleaseId } : {}), dimensions: ['overall', 'department', 'group', 'product', 'projectGroup'] }); const detail = asRow(created.reconciliation || created); setReconciliation(detail.id ? await api.governanceReconciliation(String(detail.id)) : detail); setConfirmDifferences(false); }
|
||||
catch (value) { reportError(value); } finally { setBusy(false); }
|
||||
};
|
||||
const confirm = async () => {
|
||||
if (!reconciliation?.id) return; setBusy(true); setError('');
|
||||
try { const evidence = asRow(reconciliation.result); const result = await api.confirmGovernanceReconciliation(String(reconciliation.id), { expectedRowVersion: Number(reconciliation.rowVersion || 0), expectedDifferenceHash: String(reconciliation.differenceHash), ...(evidence.transitionDifferenceHash ? { expectedTransitionDifferenceHash: String(evidence.transitionDifferenceHash) } : {}), reason: differenceReason.trim() }); setReconciliation(result); }
|
||||
catch (value) { reportError(value); } finally { setBusy(false); }
|
||||
};
|
||||
const publish = async () => {
|
||||
if (!release?.id) return; setBusy(true); setError('');
|
||||
try { await api.publishRelease(String(release.id), { expectedCurrentReleaseId: release.expectedCurrentReleaseId === undefined ? options.currentReleaseId : release.expectedCurrentReleaseId as string | null, idempotencyKey: publishKey.current, reason: reason.trim() || differenceReason.trim() || '经来源校验与候选基线对账后发布' }); setPublished(true); onComplete(); }
|
||||
catch (value) { reportError(value); } finally { setBusy(false); }
|
||||
};
|
||||
const evidence = asRow(reconciliation?.result); const comparisons = asRows(evidence.periodComparisons); const reconciliationErrors = Array.isArray(evidence.errors) ? evidence.errors : [];
|
||||
const publishReady = release?.complete === true && reconciliation?.publishReady === true;
|
||||
const steps = purpose === 'WITHDRAW' ? ['确认来源', '提交申请', '审批与候选', '来源校验', '对账与发布'] : mode === 'REBUILD' ? ['确认重算', '选择期间', '表头匹配', '计算校验', '对账与发布'] : ['选择文件', '确认期间', '工作表与表头', '预览与校验', '对账与发布'];
|
||||
const close = () => { generation.current++; onClose(); };
|
||||
return <Modal className="management-modal nc-workflow-modal" open width={1120} title={published ? purpose === 'WITHDRAW' ? '来源删除已发布' : '数据已发布' : purpose === 'WITHDRAW' ? '核对并发布删除候选' : resumeId ? '继续处理候选数据' : mode === 'REPLACE' ? '替换已有数据' : mode === 'REBUILD' ? '按当前来源重新计算' : '上传新数据'} onCancel={close} maskClosable={!busy} footer={<div className="nc-modal-footer"><span>{runId ? '关闭后任务继续,可在“导入与校验”查看;完成后从候选继续。' : '确认发布前,当前查询结果保持不变。'}</span><div>{step > 0 && step < 4 && !runId && !configuredSourceId && !busy && <Button onClick={() => { setStep(step - 1); setError(''); }}>上一步</Button>}<Button onClick={close}>{published ? '完成' : busy ? '关闭并稍后查看' : '关闭'}</Button>{!published && step === 1 && <Button type="primary" disabled={mode === 'REPLACE' && !target} loading={busy} onClick={() => { setStep(2); void changePreview(sheetName, headerRow); }}>下一步:匹配表头</Button>}{!published && step === 2 && <Button type="primary" loading={busy} disabled={Boolean(missingFields.length) || duplicateColumns || !sheetName} onClick={() => { if (workbook && (workbook.preview.headerRow !== headerRow || workbook.preview.sheetName !== sheetName)) { void changePreview(sheetName, headerRow); return; } setStep(3); }}>下一步:预览验证</Button>}{!published && step === 3 && !runId && mode !== 'REBUILD' && <Button type="primary" loading={busy} disabled={mode === 'REPLACE' && !reason.trim()} onClick={() => void beginImport()}>确认导入并校验</Button>}</div></div>}>
|
||||
<Steps className="nc-steps" current={published ? 5 : step} size="small" items={steps.map(title => ({ title }))} />
|
||||
{error && <Alert showIcon type="error" message="本次操作未完成" description={error} />}
|
||||
{published ? <div className="nc-success"><FileExcelOutlined /><h2>{purpose === 'WITHDRAW' ? '该来源已从当前查询结果移除' : '当前查询数据已更新'}</h2><p>来源原件和本次对账记录均已保留。</p></div> : <>
|
||||
{step === 0 && (mode === 'REBUILD' ? <div className="nc-rebuild-confirm"><h3>使用当前数据所用的全部来源重新计算</h3><p>计算使用当前启用的基础数据、对应关系和规则。完成后先生成候选,核对差异后再发布。</p><div className="nc-target-list">{options.targets.map(item => <div key={item.documentId}><Tag>{stageName(item.stage)}</Tag><strong>{item.year}年{item.month}月</strong><span>{item.sourceFile}</span></div>)}</div><Button type="primary" loading={busy} disabled={!options.targets.length} onClick={() => void rebuild()}>开始重新计算</Button></div> : <div className="nc-file-drop"><FileExcelOutlined /><h3>选择要{mode === 'REPLACE' ? '替换' : '上传'}的 Excel 文件</h3><p>支持 .xlsx;保留你的文件名,接下来选择数据期间和表头。</p><input className="visually-hidden-file" ref={input} type="file" accept=".xlsx" onChange={event => void readFile(event.target.files?.[0])} aria-label="选择质量数据Excel文件" /><Button type="primary" icon={<UploadOutlined />} loading={busy} onClick={() => input.current?.click()}>选择 Excel 文件</Button></div>)}
|
||||
{workbook && step > 0 && step < 4 && <div className="nc-file-summary"><FileExcelOutlined /><strong>{workbook.sourceFile}</strong><span>{stageName(stage)} · {year}年{month}月</span></div>}
|
||||
{step === 1 && <Form layout="vertical"><div className="nc-form-grid">{mode === 'REPLACE' ? <Form.Item className="nc-full-width" label="选择当前数据中的替换目标" required><Select {...readableSelectPopup} aria-label="选择当前数据中的替换目标" showSearch optionFilterProp="label" value={targetId || undefined} placeholder="选择年月、阶段和原文件" options={options.targets.map(item => ({ value: item.documentId, label: `${item.year}年${item.month}月 · ${stageName(item.stage)} · ${item.sourceFile}` }))} onChange={chooseTarget} /></Form.Item> : <><Form.Item label="数据阶段" required><Select aria-label="数据阶段" value={stage} options={[{ value: 'black', label: '黑片' }, { value: 'bright', label: '亮片' }]} onChange={value => { setStage(value); setFieldMap(matchFields(options.fields[value] || [], headers)); }} /></Form.Item><Form.Item label="统计年份" required><InputNumber aria-label="统计年份" min={2000} max={2100} value={year} onChange={value => { if (value) setYear(value); }} /></Form.Item><Form.Item label="统计月份" required><Select aria-label="统计月份" value={month} options={Array.from({ length: 12 }, (_, index) => ({ value: index + 1, label: `${index + 1}月` }))} onChange={setMonth} /></Form.Item>{options.scopes.length > 1 && <Form.Item label="数据范围" required><Select aria-label="数据范围" value={scopeCode} options={options.scopes.map(value => ({ value, label: value === 'ALL' ? '全部范围' : value }))} onChange={setScopeCode} /></Form.Item>}</>}</div>{target && <div className="nc-replacement"><span>原文件</span><strong>{target.sourceFile}</strong><ArrowRightOutlined /><span>新文件</span><strong>{workbook?.sourceFile}</strong></div>}<Form.Item label={mode === 'REPLACE' ? '替换理由' : '本次说明'} required={mode === 'REPLACE'}><Input.TextArea aria-label={mode === 'REPLACE' ? '替换理由' : '本次说明'} value={reason} rows={2} maxLength={1000} placeholder={mode === 'REPLACE' ? '例如:补齐遗漏记录,使用更新后的完整月表' : '可填写本次数据说明'} onChange={event => setReason(event.target.value)} /></Form.Item></Form>}
|
||||
{step === 2 && workbook && <><div className="nc-form-grid"><Form.Item label="工作表" required><Select aria-label="数据工作表" value={sheetName} options={workbook.sheets.map(sheet => ({ value: sheet.sheetName, label: sheet.sheetName }))} onChange={value => void changePreview(value, headerRow)} /></Form.Item><Form.Item label="表头在第几行" required><InputNumber aria-label="表头所在行" min={1} max={100} value={headerRow} onChange={value => { if (value) setHeaderRow(value); }} onBlur={() => { if (headerRow !== workbook.preview.headerRow) void changePreview(sheetName, headerRow); }} onPressEnter={() => void changePreview(sheetName, headerRow)} /></Form.Item></div><div className="nc-section-title"><h3>业务字段对应 Excel 中哪一列</h3><span>{duplicateColumns ? '同一 Excel 列不能对应多个业务字段' : missingFields.length ? `还需选择 ${missingFields.length} 个必填字段` : '必填字段已全部匹配'}</span></div><Spin spinning={busy}><ColumnMatching fields={fields} headers={headers} value={fieldMap} onChange={setFieldMap} /></Spin><h3>原表前几行</h3><SampleTable headers={headers} rows={workbook.preview.sampleRows.map(row => row.values)} /></>}
|
||||
{step === 3 && <>{!runId && workbook && <><div className="nc-review-facts"><div><small>统计期间</small><strong>{year}年{month}月 · {stageName(stage)}</strong></div><div><small>工作表与表头</small><strong>{sheetName} · 第{headerRow}行</strong></div><div><small>已匹配字段</small><strong>{Object.keys(fieldMap).length} 项</strong></div></div>{target && <Alert type="warning" showIcon message="即将使用新文件替换该期间的完整数据" description={`原文件:${target.sourceFile};新文件:${workbook.sourceFile}。本次先生成候选,最后发布后才更新查询结果。`} />}<SampleTable headers={Object.keys(fieldMap)} rows={workbook.preview.sampleRows.map(row => Object.fromEntries(Object.entries(fieldMap).map(([field, header]) => [field, row.values[header]])))} /><p className="nc-note">确认后由系统校验文件内容、数据范围及对应关系,并计算候选结果。</p></>}{(runId || (busy && mode === 'REBUILD')) && <div className="nc-processing"><Spin spinning={busy} /><h3>{statusLabel[String(run?.status)] || '正在创建计算任务'}</h3><Progress percent={Number(run?.total) > 0 ? Math.min(100, Math.round(Number(run?.processed || 0) / Number(run?.total) * 100)) : 0} status={run?.status === 'FAILED' ? 'exception' : 'active'} /><p>已处理 {txt(run?.processed || 0)} / {txt(run?.total)} 行</p>{run?.errorMessage ? <Alert type="error" showIcon message={txt(run.errorMessage)} /> : null}{!busy && runId && !['FAILED', 'CANCELLED'].includes(String(run?.status)) && <Button onClick={() => { setBusy(true); setPollAttempt(previous => previous + 1); }}>重新获取处理结果</Button>}</div>}<ValidationNotice value={run?.validation} /></>}
|
||||
{step === 4 && <Spin spinning={busy}><div className="nc-review-facts"><div><small>候选数据</small><strong>待核对</strong></div><div><small>来源校验</small><strong>{release?.complete === true ? '通过' : '尚未通过'}</strong></div><div><small>基线对账</small><strong>{statusLabel[String(reconciliation?.status)] || '待执行'}</strong></div></div><ValidationNotice value={release?.validation || run?.validation} />{reconciliationErrors.length > 0 && <Alert showIcon type="error" message="对账存在阻断事项" description={reconciliationErrors.map(txt).join(';')} />}<div className="nc-section-title"><h3>与当前数据的差异</h3><Button icon={<ReloadOutlined />} loading={busy} disabled={!release?.id} onClick={() => void reconcile()}>{reconciliation ? '重新对账' : '执行基线对账'}</Button></div>{comparisons.length > 0 ? <Table size="small" bordered dataSource={comparisons} rowKey={(row, index) => `${row.dimension}:${row.key}:${index}`} pagination={{ pageSize: 8, showSizeChanger: false }} scroll={{ x: 900 }} columns={[{ title: '期间', width: 130, render: (_, row) => { const period = asRow(row.period); return `${txt(period.year)}年${period.month ? `${txt(period.month)}月` : period.quarter ? `第${txt(period.quarter)}季度` : '全年'}`; } }, { title: '维度 / 对象', width: 200, render: (_, row) => `${({ overall: '总体', department: '产业部', group: '业务分组', product: '产品', projectGroup: '项目组' } as Record<string, string>)[String(row.dimension)] || txt(row.dimension)} / ${txt(row.key)}` }, { title: '原综合率', width: 120, render: (_, row) => ratio(asRow(row.before).compositeRate) }, { title: '新综合率', width: 120, render: (_, row) => ratio(asRow(row.after).compositeRate) }, { title: '差异', render: (_, row) => asRows(row.differences).map(item => `${metricLabel(item.path)}:${txt(item.before)} → ${txt(item.after)}`).join(';') || '一致' }]} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={reconciliation ? '本次没有可展示的期间比较;以对账结论为准' : '执行对账后在这里查看期间和指标差异'} />}{reconciliation?.status === 'REVIEW_REQUIRED' && <div className="nc-difference-confirm"><Alert type="warning" showIcon message={`发现 ${txt(evidence.differenceCount)} 项差异,需要发布者确认`} />{canPublish ? <><Input.TextArea aria-label="业务差异确认理由" rows={2} value={differenceReason} maxLength={1000} placeholder="填写差异原因及确认依据" onChange={event => setDifferenceReason(event.target.value)} /><Checkbox checked={confirmDifferences} onChange={event => setConfirmDifferences(event.target.checked)}>我已核对上方差异,并确认新数据正确</Checkbox><Button type="primary" disabled={!confirmDifferences || !differenceReason.trim() || busy} onClick={() => void confirm()}>确认差异并验收</Button></> : <p>候选已保存,请交由有数据发布权限的同事完成差异确认。</p>}</div>}{canPublish ? <div className="nc-publish-confirm"><Checkbox disabled={!publishReady} checked={publishConfirmed} onChange={event => setPublishConfirmed(event.target.checked)}>{purpose === 'WITHDRAW' ? '我确认发布此删除候选,从当前查询结果移除已批准的来源' : '我确认将此候选发布为当前查询数据'}{target ? `,替换${target.year}年${target.month}月${stageName(target.stage)}` : ''}</Checkbox><Button size="large" type="primary" disabled={!publishReady || !publishConfirmed || busy} onClick={() => void publish()}>确认发布</Button>{!publishReady && <span>来源校验和基线对账通过后可发布。</span>}</div> : <Alert showIcon type="info" message="候选数据已保存,等待有权限的同事发布" description={<><span>当前账号没有数据发布权限。可复制处理链接交接,正式查询数据尚未更新。</span><Button type="link" onClick={() => { const link = new URL(window.location.href); link.searchParams.set('page', 'sources'); if (handoffSourceId) { link.searchParams.set('sourceDeleteId', handoffSourceId); link.searchParams.delete('candidateReleaseId'); } else { link.searchParams.set('candidateReleaseId', String(release?.id || '')); link.searchParams.delete('sourceDeleteId'); } void navigator.clipboard.writeText(link.toString()).then(() => message.success('处理链接已复制')).catch(reportError); }}>复制处理链接</Button></>} />}</Spin>}
|
||||
{issues.length > 0 && <><h3>需要处理的来源行</h3><Table size="small" bordered dataSource={issues} rowKey={(row, index) => String(row.id || index)} pagination={{ pageSize: 8 }} columns={[{ title: '工作表', dataIndex: 'sheet', width: 120 }, { title: '行号', dataIndex: 'rowNumber', width: 80 }, { title: '字段', dataIndex: 'field', width: 130 }, { title: '问题说明', dataIndex: 'message' }]} /></>}
|
||||
</>}
|
||||
</Modal>;
|
||||
}
|
||||
|
||||
const MASTER_KINDS: { value: MasterWorkbookKind; label: string; columns: { key: string; label: string; required?: boolean }[] }[] = [
|
||||
...[{ value: 'departments', label: '产业部' }, { value: 'groups', label: '业务分组' }, { value: 'products', label: '产品' }, { value: 'projectGroups', label: '项目组' }].map(item => ({ ...item, value: item.value as MasterWorkbookKind, columns: [{ key: 'code', label: '编码(可选)' }, { key: 'name', label: '名称', required: true }, { key: 'enabled', label: '启用状态(可选)' }] })),
|
||||
{ value: 'categoryLookup', label: '业务分组对应', columns: [{ key: 'source', label: 'PDT代码', required: true }, { key: 'secondary', label: '销售片区', required: true }, { key: 'target', label: '业务分组', required: true }, { key: 'enabled', label: '启用状态(可选)' }] },
|
||||
{ value: 'projectGroupLookup', label: '项目组对应', columns: [{ key: 'source', label: '客户代码', required: true }, { key: 'secondary', label: '业务分组', required: true }, { key: 'target', label: '项目组', required: true }, { key: 'enabled', label: '启用状态(可选)' }] },
|
||||
{ value: 'departmentLookup', label: '产业部对应', columns: [{ key: 'source', label: '源事业部', required: true }, { key: 'target', label: '统一产业部', required: true }, { key: 'enabled', label: '启用状态(可选)' }] },
|
||||
{ value: 'productLookup', label: '产品对应', columns: [{ key: 'source', label: '源规格', required: true }, { key: 'target', label: '统一产品', required: true }, { key: 'enabled', label: '启用状态(可选)' }] },
|
||||
];
|
||||
|
||||
export function MasterWorkbookUpload({ kind, base, onUnauthorized, onComplete, simplified = false, expectedCurrentReleaseId = null }: { kind: 'masterData' | 'mappings'; base?: Row; onUnauthorized: (error: unknown) => boolean; onComplete: () => void; simplified?: boolean; expectedCurrentReleaseId?: string | null }) {
|
||||
const { message } = App.useApp();
|
||||
const fileInput = useRef<HTMLInputElement>(null);
|
||||
const [open, setOpen] = useState(false); const [preview, setPreview] = useState<MasterWorkbookPreview | null>(null);
|
||||
const [sheetName, setSheetName] = useState('');
|
||||
const [selectedKind, setSelectedKind] = useState<MasterWorkbookKind>(kind === 'masterData' ? 'departments' : 'categoryLookup');
|
||||
const [keyFormat, setKeyFormat] = useState<MasterWorkbookKeyFormat>('SEPARATE_COLUMNS');
|
||||
const [mode, setMode] = useState<'MERGE' | 'REPLACE'>('MERGE'); const [columns, setColumns] = useState<Record<string, string>>({});
|
||||
const [name, setName] = useState(''); const [reason, setReason] = useState(''); const [confirmed, setConfirmed] = useState(false);
|
||||
const [busy, setBusy] = useState(false); const [error, setError] = useState(''); const [result, setResult] = useState<Row | null>(null);
|
||||
const [preparedDefinition, setPreparedDefinition] = useState<Row | null>(null);
|
||||
const [preparedReleaseId, setPreparedReleaseId] = useState<string | null>(null);
|
||||
const workflowOperation = useDataWorkflowOperation('mapping-workbook-import', () => { onComplete(); message.success('基础数据已保存,报表已更新'); });
|
||||
useEffect(() => { if (workflowOperation.operation?.operationId) setOpen(true); }, [workflowOperation.operation?.operationId]);
|
||||
const bundle = selectedKind === 'standardBundle';
|
||||
const availableKinds = MASTER_KINDS.filter(item => kind === 'masterData' ? !item.value.endsWith('Lookup') : item.value.endsWith('Lookup'));
|
||||
const definition = MASTER_KINDS.find(item => item.value === selectedKind) || MASTER_KINDS[0];
|
||||
const activeColumns = selectedKind === 'categoryLookup' && keyFormat === 'PDT_REGION_COMBINED' ? definition.columns.filter(column => column.key !== 'secondary').map(column => column.key === 'source' ? { ...column, label: '匹配列(如P001中国区)' } : column) : definition.columns;
|
||||
const sheet = preview?.sheets.find(item => item.name === sheetName);
|
||||
const suggestedTables = preview?.suggestedTables || [];
|
||||
const summary = asRow(result?.summary); const validation = asRow(result?.validation); const draft = asRow(result?.mapping || result?.draft || result?.version || result);
|
||||
const tableSummaries = asRows(result?.tableSummaries || summary.tableSummaries);
|
||||
const kindLabel = (value: unknown) => MASTER_KINDS.find(item => item.value === value)?.label || txt(value);
|
||||
const inferFormat = (headers: string[], nextKind: MasterWorkbookKind): MasterWorkbookKeyFormat => nextKind === 'categoryLookup' && headers.includes('匹配') && headers.includes('产业部') ? 'PDT_REGION_COMBINED' : 'SEPARATE_COLUMNS';
|
||||
const autoMatch = (headers: string[], nextKind: MasterWorkbookKind, format: MasterWorkbookKeyFormat, suggestions = suggestedTables, selectedSheet = sheetName) => {
|
||||
const suggestion = suggestions.find(item => item.kind === nextKind && item.sheetName === selectedSheet && (!item.keyFormat || item.keyFormat === format));
|
||||
if (suggestion) return { ...suggestion.columns };
|
||||
const spec = MASTER_KINDS.find(item => item.value === nextKind); if (!spec) return {};
|
||||
const candidates: Record<string, string[]> = {
|
||||
code: ['编码', '代码'], name: ['名称', nextKind === 'departments' ? '事业部' : nextKind === 'groups' ? '产业部' : nextKind === 'projectGroups' ? '项目组' : '产品'], enabled: ['启用状态', '启用', '状态'],
|
||||
source: nextKind === 'categoryLookup' ? format === 'PDT_REGION_COMBINED' ? ['匹配'] : ['PDT代码', 'PDT号', 'PDT'] : nextKind === 'projectGroupLookup' ? ['客户代码'] : nextKind === 'departmentLookup' ? ['源事业部', '事业部'] : ['源规格', '成品规格', '规格'],
|
||||
secondary: nextKind === 'projectGroupLookup' ? ['业务分组', '产业部'] : ['销售片区', '销售区域'],
|
||||
target: nextKind === 'categoryLookup' ? ['业务分组', '产业部'] : nextKind === 'projectGroupLookup' ? ['项目组'] : nextKind === 'departmentLookup' ? ['统一产业部', '产业部'] : ['统一产品', '产品'],
|
||||
};
|
||||
return Object.fromEntries(spec.columns.filter(column => !(nextKind === 'categoryLookup' && format === 'PDT_REGION_COMBINED' && column.key === 'secondary')).map(column => [column.key, candidates[column.key]?.find(header => headers.includes(header)) || '']).filter(([, header]) => header));
|
||||
};
|
||||
const selectKind = (nextKind: MasterWorkbookKind) => {
|
||||
setSelectedKind(nextKind); setConfirmed(false);
|
||||
if (nextKind === 'standardBundle') { setColumns({}); return; }
|
||||
const suggested = suggestedTables.find(item => item.kind === nextKind);
|
||||
const nextSheet = suggested ? preview?.sheets.find(item => item.name === suggested.sheetName) : sheet;
|
||||
if (nextSheet) setSheetName(nextSheet.name);
|
||||
const format = suggested?.keyFormat || inferFormat(nextSheet?.headers || [], nextKind); setKeyFormat(format);
|
||||
setColumns(autoMatch(nextSheet?.headers || [], nextKind, format, suggestedTables, nextSheet?.name || sheetName));
|
||||
};
|
||||
const readFile = async (file?: File) => {
|
||||
if (!file) return; setBusy(true); setError('');
|
||||
try {
|
||||
const response = await api.previewMasterWorkbook(file); setPreview(response);
|
||||
const nextKind = response.standardBundleAvailable ? 'standardBundle' : (selectedKind === 'standardBundle' ? kind === 'masterData' ? 'departments' : 'categoryLookup' : selectedKind);
|
||||
const suggestion = response.suggestedTables?.find(item => item.kind === nextKind);
|
||||
const first = response.sheets.find(item => item.name === suggestion?.sheetName) || response.sheets[0];
|
||||
const format = suggestion?.keyFormat || inferFormat(first?.headers || [], nextKind);
|
||||
setSelectedKind(nextKind); setSheetName(first?.name || ''); setKeyFormat(format);
|
||||
setColumns(nextKind === 'standardBundle' ? {} : autoMatch(first?.headers || [], nextKind, format, response.suggestedTables || [], first?.name || ''));
|
||||
setName(`${nextKind === 'standardBundle' ? '整本基础数据' : kindLabel(nextKind)}·${file.name.replace(/\.xlsx$/i, '')}`.slice(0, 120));
|
||||
setResult(null); setConfirmed(false);
|
||||
} catch (value) { if (!onUnauthorized(value)) setError(failure(value)); }
|
||||
finally { setBusy(false); if (fileInput.current) fileInput.current.value = ''; }
|
||||
};
|
||||
const submit = async () => {
|
||||
if (!preview || !base || !sheet) return; setBusy(true); setError('');
|
||||
try {
|
||||
if (simplified && preparedDefinition) {
|
||||
await workflowOperation.start(() => api.applyDataWorkflow({ kind: 'mapping', name: name.trim(), definition: preparedDefinition, description: '测试阶段基础数据导入', expectedCurrentReleaseId: preparedReleaseId }));
|
||||
return;
|
||||
}
|
||||
const response = await (simplified ? api.prepareMasterWorkbook : api.importMasterWorkbook)({ previewId: preview.previewId, sheetName: bundle ? suggestedTables[0]?.sheetName || sheetName : sheetName, kind: selectedKind, mode, columns: bundle ? {} : columns, ...(selectedKind === 'categoryLookup' ? { keyFormat } : {}), baseMappingVersionId: String(base.id), expectedBaseRowVersion: Number(base.rowVersion || 0), name: name.trim(), reason: simplified ? '测试阶段基础数据导入' : reason.trim() });
|
||||
if (simplified) {
|
||||
const importedDraft = asRow(response.mapping || response.draft || response.version || response);
|
||||
let definition = asRow(importedDraft.definition);
|
||||
if (!Object.keys(definition).length) {
|
||||
const list = collectionItems(await api.mappings()).filter(item => item && typeof item === 'object') as Row[];
|
||||
const matching = list.find(item => String(item.id || '') === String(importedDraft.id || '') && item.definition && typeof item.definition === 'object')
|
||||
|| [...list].reverse().find(item => String(item.name || '') === name.trim() && item.definition && typeof item.definition === 'object');
|
||||
definition = asRow(matching?.definition);
|
||||
}
|
||||
if (!Object.keys(definition).length) throw new Error('导入内容已接收,但没有读取到生成的配置定义;请刷新后重试。');
|
||||
setPreparedDefinition(definition);
|
||||
setPreparedReleaseId(expectedCurrentReleaseId);
|
||||
setResult(response);
|
||||
await workflowOperation.start(() => api.applyDataWorkflow({ kind: 'mapping', name: name.trim(), definition, description: '测试阶段基础数据导入', expectedCurrentReleaseId }));
|
||||
return;
|
||||
}
|
||||
setResult(response); onComplete();
|
||||
} catch (value) { if (!onUnauthorized(value)) setError(failure(value)); }
|
||||
finally { setBusy(false); }
|
||||
};
|
||||
const canSubmit = Boolean(base && name.trim() && (simplified || (reason.trim() && confirmed)) && (bundle ? preview?.standardBundleAvailable && suggestedTables.length : sheet && activeColumns.every(column => !column.required || columns[column.key])));
|
||||
return <>
|
||||
<Button type="primary" icon={<UploadOutlined />} disabled={!base || workflowOperation.busy} title={!base ? '先加载当前配置' : undefined} onClick={() => { setOpen(true); setPreview(null); setResult(null); setPreparedDefinition(null); setError(''); setReason(''); setConfirmed(false); }}>上传{kind === 'masterData' ? '基础数据表' : '对应关系表'}</Button>
|
||||
<Modal className="management-modal nc-workflow-modal" open={open} title={`上传${kind === 'masterData' ? '基础数据表' : '对应关系表'}`} width={1040} onCancel={() => setOpen(false)} footer={<div className="nc-modal-footer"><span>{simplified ? '导入后自动保存配置、重算并更新报表。' : result ? '草稿经过校验并启用后,再重新计算和发布数据。' : '导入只创建新草稿,先预览、再确认。'}</span><div><Button onClick={() => setOpen(false)}>{result ? '完成' : '取消'}</Button>{(!result || simplified && Boolean(error || workflowOperation.error)) && <Button type="primary" disabled={!canSubmit || workflowOperation.busy} loading={busy || workflowOperation.busy} onClick={() => void submit()}>{simplified && result ? '重试保存并更新报表' : simplified ? '导入并更新报表' : '确认导入为草稿'}</Button>}</div></div>}>
|
||||
{error && <Alert type="error" showIcon message="表格导入未完成" description={error} />}
|
||||
{workflowOperation.error && <Alert type="error" showIcon message="导入或报表更新失败" description={workflowOperation.error} action={workflowOperation.operation?.operationId ? <Button size="small" onClick={workflowOperation.resume}>重试读取进度</Button> : undefined} />}
|
||||
{workflowOperation.operation && <WorkflowOperationFeedback operation={workflowOperation.operation} error={workflowOperation.error} busy={workflowOperation.busy} onResume={workflowOperation.resume} />}
|
||||
{result ? <>
|
||||
<Alert type={simplified ? workflowOperation.error ? 'error' : workflowOperation.busy ? 'info' : 'success' : 'success'} showIcon message={simplified ? workflowOperation.error ? '本次更新未完成' : workflowOperation.busy ? `正在更新:${txt(draft.name || name)}` : '基础数据和报表已更新' : `已生成草稿:${txt(draft.name || name)}`} description={simplified ? workflowOperation.error || (workflowOperation.busy ? '系统正在保存更新并重新计算报表。' : '配置已更新,报表已刷新。') : '当前数据未改变。可关闭此窗口,查看、校验并启用已保存的配置。'} />
|
||||
<div className="nc-review-facts"><div><small>新增</small><strong>{txt(summary.added)}</strong></div><div><small>更新</small><strong>{txt(summary.updated)}</strong></div><div><small>停用</small><strong>{txt(summary.disabled)}</strong></div><div><small>合计</small><strong>{txt(summary.total)}</strong></div></div>
|
||||
{tableSummaries.length > 0 && <Table size="small" bordered dataSource={tableSummaries} rowKey={(row, index) => `${row.kind}:${index}`} pagination={false} columns={[{ title: '数据类别', dataIndex: 'kind', render: (value, row) => txt(row.label || kindLabel(value)) }, { title: '工作表', dataIndex: 'sheetName' }, { title: '导入行数', dataIndex: 'rowCount', align: 'right', render: (value, row) => txt(row.imported ?? asRow(row.summary).imported ?? value) }, { title: '新增', align: 'right', render: (_, row) => txt(row.added ?? asRow(row.summary).added) }, { title: '更新', align: 'right', render: (_, row) => txt(row.updated ?? asRow(row.summary).updated) }, { title: '停用', align: 'right', render: (_, row) => txt(row.disabled ?? asRow(row.summary).disabled) }]} />}
|
||||
{Array.isArray(validation.errors) && validation.errors.length > 0 && <Alert type="warning" showIcon message="草稿需要处理以下事项" description={validation.errors.map(txt).join(';')} />}
|
||||
{!simplified && <Alert type="info" showIcon message="启用后还需要重新计算" description="启用名录或对应关系后,到“数据接入”选择“按当前来源重新计算”,完成对账并发布,查询结果才会采用新配置。" />}
|
||||
</> : <>
|
||||
<div className="nc-workbook-upload-intro"><div><strong>从 Excel 导入基础数据</strong><p>{simplified ? '可自动识别整本基础数据,或选择单个工作表匹配各列;合并更新和整表替换后直接重算并更新报表。' : '可自动识别整本基础数据,或选择单个工作表匹配各列。合并更新和整表替换均先生成草稿。'}</p></div><input ref={fileInput} type="file" accept=".xlsx" className="visually-hidden-file" aria-label="选择基础数据或对应关系Excel表" onChange={event => void readFile(event.target.files?.[0])} /><Button icon={<UploadOutlined />} loading={busy} onClick={() => fileInput.current?.click()}>{preview ? '重新选择文件' : '选择 Excel 文件'}</Button></div>
|
||||
{preview && <Form layout="vertical">
|
||||
<div className="nc-form-grid">
|
||||
<Form.Item label="导入哪一类数据" required><Select aria-label="导入数据类型" value={selectedKind} options={[...(preview.standardBundleAvailable ? [{ value: 'standardBundle' as MasterWorkbookKind, label: '整本基础数据(自动识别)' }] : []), ...availableKinds.map(item => ({ value: item.value, label: item.label }))]} onChange={selectKind} /></Form.Item>
|
||||
{!bundle && <Form.Item label="工作表" required><Select {...readableSelectPopup} aria-label="基础表工作表" value={sheetName} options={preview.sheets.map(item => ({ value: item.name, label: `${item.name} · ${item.rowCount}行` }))} onChange={value => { const next = preview.sheets.find(item => item.name === value); const format = inferFormat(next?.headers || [], selectedKind); setSheetName(value); setKeyFormat(format); setColumns(autoMatch(next?.headers || [], selectedKind, format, suggestedTables, value)); setConfirmed(false); }} /></Form.Item>}
|
||||
<Form.Item label="更新方式" required><Select aria-label="基础表更新方式" value={mode} options={[{ value: 'MERGE', label: '合并更新:新增或更新表内记录' }, { value: 'REPLACE', label: '整表替换:表外旧记录停用' }]} onChange={value => { setMode(value); setConfirmed(false); }} /></Form.Item>
|
||||
{selectedKind === 'categoryLookup' && <Form.Item label="业务分组匹配方式" required><Select aria-label="业务分组匹配方式" value={keyFormat} options={[{ value: 'SEPARATE_COLUMNS', label: '两列:PDT代码 + 销售片区' }, { value: 'PDT_REGION_COMBINED', label: '一列:匹配(如P001中国区)' }]} onChange={value => { setKeyFormat(value); setColumns(autoMatch(sheet?.headers || [], selectedKind, value)); setConfirmed(false); }} /></Form.Item>}
|
||||
</div>
|
||||
{bundle ? <section className="nc-bundle-preview"><h3>将一起导入的工作表</h3><Table size="small" bordered dataSource={suggestedTables} rowKey={(row, index) => `${row.kind}:${index}`} pagination={false} columns={[{ title: '工作表', dataIndex: 'sheetName', width: 200 }, { title: '数据类别', dataIndex: 'kind', width: 180, render: (value, row) => txt(row.label || kindLabel(value)) }, { title: '来源行数', dataIndex: 'rowCount', align: 'right', width: 100 }, { title: '已识别的字段对应', render: (_, row) => Object.entries(row.columns).map(([field, header]) => `${({ code: '编码', name: '名称', source: row.keyFormat === 'PDT_REGION_COMBINED' ? '匹配条件' : '来源条件', secondary: '业务分组/销售片区', target: '对应结果', enabled: '启用状态' } as Record<string, string>)[field] || field} ← ${header}`).join(';') }]} /><p className="nc-note">{simplified ? '以上名录和对应关系将一起保存并更新报表' : '以上名录和对应关系合并生成同一个草稿'},项目组名录按名称去重。月份等辅助工作表不导入。</p></section> : <>
|
||||
<div className="nc-column-matching">{activeColumns.map(column => <label key={column.key} className="nc-field-match"><span>{column.label}{column.required && <b>必填</b>}</span><Select {...readableSelectPopup} aria-label={`${column.label}对应的基础表列`} value={columns[column.key] || undefined} allowClear placeholder="选择 Excel 列" options={(sheet?.headers || []).map(header => ({ value: header, label: header }))} onChange={value => { setColumns(previous => { const next = { ...previous }; if (value) next[column.key] = value; else delete next[column.key]; return next; }); setConfirmed(false); }} /></label>)}</div>
|
||||
{selectedKind === 'projectGroupLookup' && <p className="nc-note">此处“业务分组”可以选择原表中的“产业部”列;“事业部”用于产业部名录。</p>}
|
||||
</>}
|
||||
{!simplified && <div className="nc-form-grid"><Form.Item label="草稿名称" required><Input aria-label="基础表草稿名称" value={name} maxLength={120} onChange={event => setName(event.target.value)} /></Form.Item><Form.Item label="变更理由" required><Input aria-label="基础表变更理由" value={reason} maxLength={1000} placeholder="说明新增或替换的原因" onChange={event => setReason(event.target.value)} /></Form.Item></div>}
|
||||
{simplified && <p className="nc-note">名称:{name || '新配置'} · 修改内容会在导入后直接应用。</p>}
|
||||
{mode === 'REPLACE' && <Alert type="warning" showIcon message={simplified ? '整表替换会停用导入表中未出现的旧记录' : '整表替换会在新草稿中停用导入表未出现的旧记录'} description={bundle ? '仅处理上方已识别的数据类别,其他名录和对应关系沿用当前配置。' : '仅影响当前选择的数据类型,其余名录和对应关系沿用当前配置。'} />}
|
||||
{!bundle && <><h3>导入预览 · {sheet?.rowCount || 0} 行</h3><SampleTable headers={activeColumns.filter(column => columns[column.key]).map(column => column.label)} rows={(sheet?.sampleRows || []).map(row => Object.fromEntries(activeColumns.filter(column => columns[column.key]).map(column => [column.label, row[columns[column.key]]])))} /></>}
|
||||
{!simplified && <Checkbox checked={confirmed} onChange={event => setConfirmed(event.target.checked)}>{bundle ? '我已核对上方全部工作表、数据类别和更新方式,确认合并生成一个新草稿。' : '我已核对所选类型、字段对应和更新方式,确认生成新草稿。'}</Checkbox>}
|
||||
</Form>}
|
||||
</>}
|
||||
</Modal>
|
||||
</>;
|
||||
}
|
||||
|
||||
export function ReadableConfigDefinition({ kind, value }: { kind: 'masterData' | 'mappings'; value: unknown }) {
|
||||
const definition = asRow(value); const master = asRow(definition.masterData); const disabled = asRow(definition.disabledMappings);
|
||||
const kinds = MASTER_KINDS.filter(item => kind === 'masterData' ? !item.value.endsWith('Lookup') : item.value.endsWith('Lookup'));
|
||||
return <div className="nc-config-contents">{kinds.map(item => {
|
||||
const isLookup = item.value.endsWith('Lookup');
|
||||
const stopped = new Set(Array.isArray(disabled[item.value]) ? disabled[item.value] as string[] : []);
|
||||
const rows = isLookup ? Object.entries(asRow(definition[item.value])).map(([key, target]) => { const split = key.indexOf('|'); return { code: key, source: split >= 0 ? key.slice(0, split) : key, secondary: split >= 0 ? key.slice(split + 1) : '', target, enabled: !stopped.has(key) }; }) : asRows(master[item.value]);
|
||||
return <section key={item.value}><h3>{item.label} · {rows.length} 条</h3><Table size="small" bordered dataSource={rows} rowKey={(row, index) => String(row.code || index)} pagination={{ pageSize: 8, showSizeChanger: false }} scroll={{ x: 600 }} columns={item.columns.map(column => ({ title: column.label.replace('(可选)', ''), dataIndex: column.key, key: column.key, render: column.key === 'enabled' ? (enabled: unknown) => <Tag>{enabled === false ? '停用' : '启用'}</Tag> : txt }))} locale={{ emptyText: '当前配置未单独维护此类记录' }} /></section>;
|
||||
})}</div>;
|
||||
}
|
||||
@@ -0,0 +1,382 @@
|
||||
import { lazy, Suspense, useCallback, useEffect, useState, type ReactNode } from 'react';
|
||||
import {
|
||||
Alert,
|
||||
App,
|
||||
Button,
|
||||
Dropdown,
|
||||
Form,
|
||||
Input,
|
||||
Modal,
|
||||
Select,
|
||||
Spin,
|
||||
Tooltip,
|
||||
} from 'antd';
|
||||
import {
|
||||
AppstoreOutlined,
|
||||
ApartmentOutlined,
|
||||
BgColorsOutlined,
|
||||
CheckSquareOutlined,
|
||||
CheckOutlined,
|
||||
DatabaseOutlined,
|
||||
DownOutlined,
|
||||
DeploymentUnitOutlined,
|
||||
FileSearchOutlined,
|
||||
KeyOutlined,
|
||||
LineChartOutlined,
|
||||
LoadingOutlined,
|
||||
LogoutOutlined,
|
||||
RobotOutlined,
|
||||
SearchOutlined,
|
||||
QuestionCircleOutlined,
|
||||
SettingOutlined,
|
||||
TeamOutlined,
|
||||
ToolOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import { ApiError, api } from './api';
|
||||
import type { AuthUser, QueryParams } from './types';
|
||||
import { workspaceThemes, type WorkspaceThemeId } from './ui-themes';
|
||||
import { readableSelectPopup } from './readableSelectPopup';
|
||||
|
||||
const QueryPage = lazy(() => import('./QueryPage'));
|
||||
const ManagementPages = lazy(() => import('./ManagementPages'));
|
||||
|
||||
export type PageKey = 'overall' | 'department' | 'group' | 'product' | 'basis' | 'analysis' | 'sources' | 'imports' | 'rules' | 'mappings' | 'masterData' | 'tasks' | 'access';
|
||||
|
||||
const pageNames: Record<PageKey, string> = {
|
||||
overall: '总体汇总', department: '产业部汇总', group: '产业部-业务分组', product: '产品汇总',
|
||||
basis: '数据与计算依据', analysis: '智能分析', sources: '数据接入', imports: '导入与校验',
|
||||
rules: '计算规则', mappings: '对应关系', masterData: '基础数据', tasks: '任务与监控', access: '权限与审计',
|
||||
};
|
||||
|
||||
const pageFromLocation = (): PageKey => {
|
||||
const key = new URLSearchParams(window.location.search).get('page');
|
||||
if (key === 'headers' || key === 'releases') return 'sources';
|
||||
if (key === 'scrap') return 'product';
|
||||
return key && key in pageNames ? key as PageKey : 'overall';
|
||||
};
|
||||
|
||||
type TopResultRef = { kind: 'TOP'; resultId: string; releaseId: string };
|
||||
function encodeContext(value: { query: QueryParams; resultRef?: TopResultRef }): string {
|
||||
const bytes = new TextEncoder().encode(JSON.stringify(value));
|
||||
let binary = '';
|
||||
for (const byte of bytes) binary += String.fromCharCode(byte);
|
||||
return btoa(binary).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
|
||||
}
|
||||
|
||||
const navGroups = [
|
||||
{
|
||||
label: '质量查询',
|
||||
items: [
|
||||
['overall', '总体汇总', AppstoreOutlined],
|
||||
['department', '产业部汇总', ApartmentOutlined],
|
||||
['group', '产业部-业务分组', DeploymentUnitOutlined],
|
||||
['product', '产品汇总', DatabaseOutlined],
|
||||
] as const,
|
||||
},
|
||||
{
|
||||
label: '分析工作台',
|
||||
items: [
|
||||
['analysis', '智能分析', RobotOutlined],
|
||||
] as const,
|
||||
},
|
||||
{
|
||||
label: '数据中心',
|
||||
items: [
|
||||
['sources', '数据接入', DatabaseOutlined],
|
||||
['imports', '导入与校验', CheckSquareOutlined],
|
||||
] as const,
|
||||
},
|
||||
{
|
||||
label: '规则与管理',
|
||||
items: [
|
||||
['rules', '计算规则', SettingOutlined],
|
||||
['mappings', '对应关系', ToolOutlined],
|
||||
['masterData', '基础数据', DatabaseOutlined],
|
||||
['tasks', '任务与监控', LineChartOutlined],
|
||||
['access', '权限与审计', KeyOutlined],
|
||||
] as const,
|
||||
},
|
||||
];
|
||||
|
||||
const searchablePages: { key: PageKey; label: string }[] = [
|
||||
...navGroups.flatMap(group => group.items.map(([key, label]) => ({ key, label }))),
|
||||
{ key: 'basis', label: pageNames.basis },
|
||||
];
|
||||
|
||||
function shownDepartment(value: string): string {
|
||||
return value === '质量管理部' ? '质量中心' : value;
|
||||
}
|
||||
|
||||
function PageReveal({ page, children }: { page: PageKey; children: ReactNode }) {
|
||||
return <div className="page-view" data-page={page}>{children}</div>;
|
||||
}
|
||||
|
||||
type QualityWorkspaceProps = {
|
||||
appearance: (typeof workspaceThemes)[number];
|
||||
onAppearanceChange: (themeId: WorkspaceThemeId) => void;
|
||||
};
|
||||
|
||||
export default function QualityWorkspace({ appearance, onAppearanceChange }: QualityWorkspaceProps) {
|
||||
const { message } = App.useApp();
|
||||
const [page, setPage] = useState<PageKey>(pageFromLocation);
|
||||
const [user, setUser] = useState<AuthUser | null>(null);
|
||||
const [sessionLoading, setSessionLoading] = useState(true);
|
||||
const [sessionError, setSessionError] = useState('');
|
||||
const [searchOpen, setSearchOpen] = useState(false);
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
if (!user) return;
|
||||
const onShortcut = (event: KeyboardEvent) => {
|
||||
if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'k') {
|
||||
event.preventDefault();
|
||||
setSearchTerm('');
|
||||
setSearchOpen(true);
|
||||
}
|
||||
};
|
||||
window.addEventListener('keydown', onShortcut);
|
||||
return () => window.removeEventListener('keydown', onShortcut);
|
||||
}, [user]);
|
||||
|
||||
useEffect(() => {
|
||||
const syncFromLocation = () => {
|
||||
const url = new URL(window.location.href);
|
||||
const currentPage = url.searchParams.get('page') || '';
|
||||
if (['headers', 'releases', 'scrap'].includes(currentPage)) {
|
||||
url.searchParams.set('page', currentPage === 'scrap' ? 'product' : 'sources');
|
||||
window.history.replaceState({}, '', `${url.pathname}${url.search}${url.hash}`);
|
||||
}
|
||||
setPage(pageFromLocation());
|
||||
};
|
||||
syncFromLocation();
|
||||
window.addEventListener('popstate', syncFromLocation);
|
||||
return () => window.removeEventListener('popstate', syncFromLocation);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
(async () => {
|
||||
try {
|
||||
await api.refreshCsrf();
|
||||
const current = await api.me();
|
||||
if (alive) setUser(current);
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError && error.status === 401) {
|
||||
if (alive) setUser(null);
|
||||
} else if (alive) {
|
||||
setSessionError(error instanceof Error ? error.message : '无法连接服务');
|
||||
}
|
||||
} finally {
|
||||
if (alive) setSessionLoading(false);
|
||||
}
|
||||
})();
|
||||
return () => { alive = false; };
|
||||
}, []);
|
||||
|
||||
const navigate = (next: PageKey, query?: QueryParams, resultRef?: TopResultRef) => {
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.set('page', next);
|
||||
if (next !== 'analysis' || query || resultRef) {
|
||||
url.searchParams.delete('sessionId');
|
||||
url.searchParams.delete('turnId');
|
||||
}
|
||||
if (query) url.searchParams.set('context', encodeContext({ query, ...(resultRef ? { resultRef } : {}) }));
|
||||
else url.searchParams.delete('context');
|
||||
window.history.pushState({}, '', `${url.pathname}${url.search}${url.hash}`);
|
||||
setPage(next);
|
||||
setSearchOpen(false);
|
||||
};
|
||||
|
||||
const matchingPages = searchablePages.filter(({ key, label }) => {
|
||||
const normalized = searchTerm.trim().toLocaleLowerCase();
|
||||
return !normalized || `${label} ${key}`.toLocaleLowerCase().includes(normalized);
|
||||
});
|
||||
|
||||
const handleUnauthorized = useCallback((error: unknown) => {
|
||||
if (error instanceof ApiError && error.status === 401) {
|
||||
setUser(null);
|
||||
void api.refreshCsrf().catch(() => undefined);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}, []);
|
||||
|
||||
if (sessionLoading) return <div className="screen-state"><Spin indicator={<LoadingOutlined spin />} /> <span>正在连接质量中心…</span></div>;
|
||||
if (sessionError) return <div className="screen-state"><div className="state-card"><strong>服务暂不可用</strong><p>{sessionError}</p><Button onClick={() => window.location.reload()}>重新连接</Button></div></div>;
|
||||
if (!user) return <LoginPage onSuccess={setUser} />;
|
||||
|
||||
return (
|
||||
<div className="app-shell">
|
||||
<aside className="sidebar">
|
||||
<button className="brand" onClick={() => navigate('overall')} aria-label="回到总体汇总">
|
||||
<span className="brand-mark" aria-hidden="true"><i /><i /><i /></span>
|
||||
<span>质量中心</span>
|
||||
</button>
|
||||
<div className="workspace-caption">质量中心 · 分析工作台</div>
|
||||
<nav className="side-navigation" aria-label="主导航">
|
||||
{navGroups.map(group => (
|
||||
<div className="nav-group" key={group.label}>
|
||||
<div className="nav-group-label">{group.label}</div>
|
||||
{group.items.map(([key, label, Icon]) => (
|
||||
<button
|
||||
key={key}
|
||||
className={`nav-item ${page === key ? 'active' : ''}`}
|
||||
aria-current={page === key ? 'page' : undefined}
|
||||
onClick={() => navigate(key)}
|
||||
>
|
||||
<Icon aria-hidden="true" />
|
||||
<span>{label}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
<div className="nav-group nav-group-tail">
|
||||
<div className="nav-group-label">数据口径</div>
|
||||
<button className={`nav-item ${page === 'basis' ? 'active' : ''}`} aria-current={page === 'basis' ? 'page' : undefined} onClick={() => navigate('basis')}>
|
||||
<FileSearchOutlined aria-hidden="true" /><span>数据与计算依据</span>
|
||||
</button>
|
||||
</div>
|
||||
</nav>
|
||||
<div className="user-block">
|
||||
<span className="avatar">{(user.displayName || user.username).slice(0, 1)}</span>
|
||||
<span className="user-copy"><strong>{user.displayName || user.username}</strong><small>{user.departments.length ? user.departments.map(shownDepartment).join('、') : '质量中心'}</small></span>
|
||||
<Tooltip title="退出登录"><Button type="text" icon={<LogoutOutlined />} aria-label="退出登录" onClick={async () => {
|
||||
try { await api.logout(); setUser(null); }
|
||||
catch (error) { if (!handleUnauthorized(error)) message.error(error instanceof Error ? error.message : '退出失败'); }
|
||||
}} /></Tooltip>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<main className="main-column">
|
||||
<header className="topbar">
|
||||
<div className="breadcrumb"><span>质量分析</span><span className="breadcrumb-slash">/</span><strong>{pageNames[page]}</strong></div>
|
||||
<div className="topbar-actions">
|
||||
<Button className="topbar-search" type="text" aria-label="搜索功能页面" onClick={() => { setSearchTerm(''); setSearchOpen(true); }}>
|
||||
<SearchOutlined /><span>搜索功能页面…</span><kbd>⌘ K</kbd>
|
||||
</Button>
|
||||
<Dropdown
|
||||
trigger={['click']}
|
||||
classNames={{ root: 'workspace-theme-dropdown' }}
|
||||
menu={{
|
||||
selectedKeys: [appearance.id],
|
||||
items: workspaceThemes.map(theme => ({
|
||||
key: theme.id,
|
||||
label: <span className="theme-choice"><i style={{ backgroundColor: theme.primary }} /><span>{theme.name}</span>{theme.id === appearance.id && <CheckOutlined />}</span>,
|
||||
})),
|
||||
onClick: ({ key }) => onAppearanceChange(key as WorkspaceThemeId),
|
||||
}}
|
||||
>
|
||||
<Button className="topbar-theme" type="text" aria-label={`切换主题,当前${appearance.name}`}>
|
||||
<BgColorsOutlined /><span>{appearance.name}</span><DownOutlined />
|
||||
</Button>
|
||||
</Dropdown>
|
||||
<Tooltip title="查看数据与计算依据">
|
||||
<Button className="topbar-help" type="text" icon={<QuestionCircleOutlined />} aria-label="查看数据与计算依据" onClick={() => navigate('basis')} />
|
||||
</Tooltip>
|
||||
<span className="top-organization"><TeamOutlined />质量中心</span>
|
||||
</div>
|
||||
</header>
|
||||
<div className="mobile-brand">
|
||||
<span className="brand-mark" aria-hidden="true"><i /><i /><i /></span><strong>质量中心</strong>
|
||||
<Select<PageKey> {...readableSelectPopup} aria-label="页面导航" value={page} onChange={value => navigate(value)} options={[
|
||||
...navGroups.map(group => ({ label: group.label, options: group.items.map(([value, label]) => ({ value, label })) })),
|
||||
{ label: '数据口径', options: [{ value: 'basis' as PageKey, label: '数据与计算依据' }] },
|
||||
]} />
|
||||
<Button type="text" icon={<LogoutOutlined />} aria-label="退出登录" onClick={async () => {
|
||||
try { await api.logout(); setUser(null); }
|
||||
catch (error) { if (!handleUnauthorized(error)) message.error(error instanceof Error ? error.message : '退出失败'); }
|
||||
}} />
|
||||
</div>
|
||||
<div className="page-content">
|
||||
<Suspense fallback={<div className="loading-panel"><Spin />正在打开页面…</div>}>
|
||||
<PageReveal page={page}>
|
||||
{['overall', 'department', 'group', 'product'].includes(page)
|
||||
? <QueryPage page={page} onUnauthorized={handleUnauthorized} onNavigate={navigate} />
|
||||
: <ManagementPages page={page} user={user} onUnauthorized={handleUnauthorized} onNavigate={navigate} />}
|
||||
</PageReveal>
|
||||
</Suspense>
|
||||
</div>
|
||||
</main>
|
||||
<Modal
|
||||
className="navigation-search-modal"
|
||||
title="搜索功能页面"
|
||||
open={searchOpen}
|
||||
footer={null}
|
||||
centered
|
||||
width={520}
|
||||
onCancel={() => setSearchOpen(false)}
|
||||
>
|
||||
<Input
|
||||
autoFocus
|
||||
allowClear
|
||||
prefix={<SearchOutlined />}
|
||||
placeholder="输入页面名称"
|
||||
value={searchTerm}
|
||||
onChange={event => setSearchTerm(event.target.value)}
|
||||
onPressEnter={() => matchingPages[0] && navigate(matchingPages[0].key)}
|
||||
/>
|
||||
<div className="navigation-search-results" role="listbox" aria-label="功能页面">
|
||||
{matchingPages.length ? matchingPages.map(item => (
|
||||
<button className="navigation-result" type="button" key={item.key} role="option" aria-selected={page === item.key} onClick={() => navigate(item.key)}>
|
||||
<span>{item.label}</span><kbd>Enter</kbd>
|
||||
</button>
|
||||
)) : <div className="navigation-search-empty">没有匹配的功能页面</div>}
|
||||
</div>
|
||||
<div className="navigation-search-footnote">按 Enter 打开首项,Esc 关闭</div>
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function LoginPage({ onSuccess }: { onSuccess: (user: AuthUser) => void }) {
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [loginError, setLoginError] = useState('');
|
||||
const [form] = Form.useForm<{ username: string; password: string }>();
|
||||
const submit = async (values: { username: string; password: string }) => {
|
||||
setBusy(true);
|
||||
setLoginError('');
|
||||
try {
|
||||
const result = await api.login(values.username, values.password);
|
||||
onSuccess(result.user);
|
||||
} catch (error) {
|
||||
setLoginError(error instanceof Error ? error.message : '登录失败,请检查账号后重试');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="login-screen">
|
||||
<section className="login-art" aria-label="质量中心品牌介绍">
|
||||
<div className="login-orbit login-orbit-one" aria-hidden="true" />
|
||||
<div className="login-orbit login-orbit-two" aria-hidden="true" />
|
||||
<div className="login-brand-lockup">
|
||||
<img src="/yunsheng-logo.png" alt="宁波韵升" />
|
||||
<span className="login-brand-divider" />
|
||||
<strong>质量中心</strong>
|
||||
</div>
|
||||
<div className="login-art-copy">
|
||||
<span className="login-eyebrow">QUALITY DATA PLATFORM</span>
|
||||
<h1>质量数据<br />分析平台</h1>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="login-panel" aria-label="账号登录">
|
||||
<div className="login-card">
|
||||
<h2>登录工作台</h2>
|
||||
<Form form={form} layout="vertical" onFinish={submit} onValuesChange={() => setLoginError('')} requiredMark={false} name="quality-center-login">
|
||||
<Form.Item name="username" label="账号" rules={[{ required: true, whitespace: true, message: '请输入账号' }]}>
|
||||
<Input autoComplete="username" autoFocus placeholder="请输入登录账号" disabled={busy} />
|
||||
</Form.Item>
|
||||
<Form.Item name="password" label="密码" rules={[{ required: true, message: '请输入密码' }]}>
|
||||
<Input.Password autoComplete="current-password" placeholder="请输入密码" disabled={busy} />
|
||||
</Form.Item>
|
||||
{loginError && <Alert className="login-error" type="error" showIcon message={loginError} role="alert" />}
|
||||
<Button className="login-submit" type="primary" htmlType="submit" loading={busy} block>{busy ? '正在登录…' : '登录质量中心'}</Button>
|
||||
</Form>
|
||||
</div>
|
||||
<footer className="login-footer">宁波韵升股份有限公司 <span>·</span> © 2026</footer>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,411 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { Alert, App, AutoComplete, Button, Checkbox, Form, Input, InputNumber, Modal, Select, Switch, Table, Tabs, Tag } from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import { DownloadOutlined, PlusOutlined, UploadOutlined } from '@ant-design/icons';
|
||||
import { readableSelectPopup } from './readableSelectPopup';
|
||||
import './structured-config-editors.css';
|
||||
|
||||
export type ConfigDefinition = Record<string, unknown>;
|
||||
type MappingKind = 'categoryLookup' | 'projectGroupLookup' | 'departmentLookup' | 'productLookup';
|
||||
type MasterKind = 'departments' | 'groups' | 'products' | 'projectGroups';
|
||||
type MappingRow = { key: string; source: string; secondary: string; target: string | null; enabled: boolean };
|
||||
type MasterRow = { code: string; name: string; enabled: boolean; department?: string; [key: string]: unknown };
|
||||
type DefinitionProps = { value: ConfigDefinition; onChange: (value: ConfigDefinition) => void };
|
||||
const mappingKinds: MappingKind[] = ['categoryLookup', 'projectGroupLookup', 'departmentLookup', 'productLookup'];
|
||||
const masterKinds: MasterKind[] = ['departments', 'groups', 'products', 'projectGroups'];
|
||||
const mappingInfo: Record<MappingKind, { label: string; source: string; secondary?: string; target: string; master: MasterKind }> = {
|
||||
categoryLookup: { label: '业务分组对应', source: 'PDT代码', secondary: '销售片区', target: '业务分组', master: 'groups' },
|
||||
projectGroupLookup: { label: '项目组对应', source: '客户代码', secondary: '业务分组', target: '项目组', master: 'projectGroups' },
|
||||
departmentLookup: { label: '产业部对应', source: '源事业部', target: '统一产业部', master: 'departments' },
|
||||
productLookup: { label: '产品对应', source: '源规格(大写)', target: '统一产品', master: 'products' },
|
||||
};
|
||||
const masterLabels: Record<MasterKind, string> = { departments: '产业部', groups: '业务分组', products: '产品', projectGroups: '项目组' };
|
||||
function objectValue(value: unknown): Record<string, unknown> { return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {}; }
|
||||
const SYSTEM_DEFINITION_METADATA_KEYS = new Set([
|
||||
'schemaversion', 'ruleversion', 'ruleversionid', 'engineversion', 'formulaversion', 'parserversion',
|
||||
'mappingversion', 'mappingversionid', 'basemappingversionid', 'versionid', 'versionno',
|
||||
'releaseid', 'currentreleaseid', 'revisionid', 'sourcerevisionid', 'rowversion',
|
||||
]);
|
||||
function isSystemDefinitionMetadataField(key: string): boolean {
|
||||
return SYSTEM_DEFINITION_METADATA_KEYS.has(key.replace(/[^a-z0-9]/gi, '').toLowerCase());
|
||||
}
|
||||
function withoutSystemVersionFields(value: unknown): unknown {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) return value;
|
||||
return Object.fromEntries(Object.entries(value as Record<string, unknown>)
|
||||
.filter(([key]) => !isSystemDefinitionMetadataField(key)));
|
||||
}
|
||||
function preserveSystemVersionFields(next: unknown, current: unknown): unknown {
|
||||
if (!next || typeof next !== 'object' || Array.isArray(next)) return next;
|
||||
const currentObject = objectValue(current);
|
||||
const result: Record<string, unknown> = {};
|
||||
for (const [key, value] of Object.entries(next as Record<string, unknown>)) {
|
||||
if (!isSystemDefinitionMetadataField(key)) result[key] = value;
|
||||
}
|
||||
for (const [key, value] of Object.entries(currentObject)) if (isSystemDefinitionMetadataField(key)) result[key] = value;
|
||||
return result;
|
||||
}
|
||||
function disabledKeys(value: ConfigDefinition, kind: MappingKind): string[] { const keys = objectValue(value.disabledMappings)[kind]; return Array.isArray(keys) ? keys.map(String) : []; }
|
||||
function mappingRows(value: ConfigDefinition, kind: MappingKind): MappingRow[] {
|
||||
const disabled = new Set(disabledKeys(value, kind));
|
||||
return Object.entries(objectValue(value[kind])).map(([key, target]) => {
|
||||
const split = mappingInfo[kind].secondary ? key.indexOf('|') : -1;
|
||||
return { key, source: split < 0 ? key : key.slice(0, split), secondary: split < 0 ? '' : key.slice(split + 1), target: target === null ? null : String(target), enabled: !disabled.has(key) };
|
||||
});
|
||||
}
|
||||
function masterRows(value: ConfigDefinition, kind: MasterKind): MasterRow[] {
|
||||
const rows = objectValue(value.masterData)[kind];
|
||||
return Array.isArray(rows) ? rows.map(item => { const row = objectValue(item); return { ...row, code: String(row.code ?? ''), name: String(row.name ?? ''), enabled: row.enabled !== false, ...(Object.hasOwn(row, 'department') ? { department: String(row.department ?? '') } : {}) }; }) : [];
|
||||
}
|
||||
function setMasterRows(value: ConfigDefinition, kind: MasterKind, rows: MasterRow[]): ConfigDefinition {
|
||||
return { ...value, masterData: { ...objectValue(value.masterData), [kind]: rows } };
|
||||
}
|
||||
function setMappingRows(value: ConfigDefinition, kind: MappingKind, rows: MappingRow[]): ConfigDefinition {
|
||||
return { ...value, [kind]: Object.fromEntries(rows.map(row => [row.key, row.target])), disabledMappings: { ...objectValue(value.disabledMappings), [kind]: rows.filter(row => !row.enabled).map(row => row.key) } };
|
||||
}
|
||||
function csvText(rows: (string | boolean | null)[][]): string { return rows.map(row => row.map(cell => `"${String(cell ?? '').replaceAll('"', '""')}"`).join(',')).join('\r\n'); }
|
||||
function downloadCsv(filename: string, rows: (string | boolean | null)[][]) {
|
||||
const url = URL.createObjectURL(new Blob(['\uFEFF', csvText(rows)], { type: 'text/csv;charset=utf-8' }));
|
||||
const link = document.createElement('a'); link.href = url; link.download = filename; link.click(); URL.revokeObjectURL(url);
|
||||
}
|
||||
export function parseConfigDelimited(text: string): string[][] {
|
||||
const source = text.replace(/^\uFEFF/, '').replace(/^[\r\n]+|[\r\n]+$/g, '');
|
||||
if (!source.trim()) throw new Error('请粘贴需要导入的内容');
|
||||
const firstLine = source.split(/\r?\n/, 1)[0];
|
||||
let headerQuoted = false; let hasTab = false;
|
||||
for (let index = 0; index < firstLine.length; index++) { if (firstLine[index] === '"') { if (headerQuoted && firstLine[index + 1] === '"') index++; else headerQuoted = !headerQuoted; } else if (!headerQuoted && firstLine[index] === '\t') hasTab = true; }
|
||||
const delimiter = hasTab ? '\t' : ',';
|
||||
const result: string[][] = []; let row: string[] = []; let cell = ''; let quoted = false; let closedQuote = false;
|
||||
for (let index = 0; index < source.length; index++) {
|
||||
const char = source[index];
|
||||
if (char === '"') { if (quoted && source[index + 1] === '"') { cell += '"'; index++; } else if (!quoted && (cell.trim() || closedQuote)) throw new Error('引号位置有误,请检查 CSV 格式'); else { quoted = !quoted; if (!quoted) closedQuote = true; } }
|
||||
else if (!quoted && char === delimiter) { row.push(cell.trim()); cell = ''; closedQuote = false; }
|
||||
else if (!quoted && (char === '\n' || char === '\r')) { row.push(cell.trim()); if (row.some(Boolean)) result.push(row); row = []; cell = ''; closedQuote = false; if (char === '\r' && source[index + 1] === '\n') index++; }
|
||||
else { if (!quoted && closedQuote && char.trim()) throw new Error('闭合引号后存在多余内容,请检查 CSV 格式'); cell += char; }
|
||||
}
|
||||
if (quoted) throw new Error('CSV 引号未闭合');
|
||||
row.push(cell.trim()); if (row.some(Boolean)) result.push(row);
|
||||
return result;
|
||||
}
|
||||
function parseEnabled(value: string | undefined, line: number): boolean | undefined {
|
||||
if (value === undefined || value === '') return undefined;
|
||||
if (['true', '1', '是', '启用'].includes(value.toLowerCase())) return true;
|
||||
if (['false', '0', '否', '停用'].includes(value.toLowerCase())) return false;
|
||||
throw new Error(`第 ${line} 行启用状态无效,请填写 true/false 或 启用/停用`);
|
||||
}
|
||||
export function validateStructuredMappingDefinition(value: ConfigDefinition, _groupDepartments?: Record<string, string | null>): string[] {
|
||||
const errors: string[] = [];
|
||||
for (const kind of masterKinds) {
|
||||
const codes = new Set<string>(); const names = new Set<string>();
|
||||
masterRows(value, kind).forEach((row, index) => {
|
||||
const prefix = `${masterLabels[kind]}名录第 ${index + 1} 行`;
|
||||
if (!row.code.trim() || !row.name.trim()) errors.push(`${prefix}:编码和名称必填`);
|
||||
if (row.code.length > 100 || row.name.length > 190) errors.push(`${prefix}:编码最多100字、名称最多190字`);
|
||||
if (codes.has(row.code)) errors.push(`${prefix}:编码“${row.code}”重复`);
|
||||
if (names.has(row.name)) errors.push(`${prefix}:名称“${row.name}”重复`);
|
||||
codes.add(row.code); names.add(row.name);
|
||||
});
|
||||
}
|
||||
const enabledDepartments = masterRows(value, 'departments');
|
||||
for (const group of masterRows(value, 'groups')) {
|
||||
const department = Object.hasOwn(group, 'department') ? String(group.department ?? '') : '';
|
||||
if (!department) continue;
|
||||
const parent = enabledDepartments.find(row => row.name === department);
|
||||
if (!parent) errors.push(`业务分组名录 ${group.name}:所属产业部“${department}”不在产业部名录中`);
|
||||
else if (!parent.enabled) errors.push(`业务分组名录 ${group.name}:所属产业部“${department}”已停用,请调整或清空所属产业部`);
|
||||
}
|
||||
for (const kind of mappingKinds) {
|
||||
const catalog = masterRows(value, mappingInfo[kind].master);
|
||||
if (!Object.hasOwn(objectValue(value.masterData), mappingInfo[kind].master)) continue;
|
||||
for (const row of mappingRows(value, kind)) {
|
||||
if (!row.enabled || row.target === null) continue;
|
||||
const target = catalog.find(item => item.name === row.target);
|
||||
if (!target) errors.push(`${mappingInfo[kind].label} ${row.key}:目标“${row.target}”不在${masterLabels[mappingInfo[kind].master]}名录中`);
|
||||
else if (!target.enabled) errors.push(`${mappingInfo[kind].label} ${row.key}:目标“${row.target}”已停用,请调整或停用此对应关系`);
|
||||
}
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
|
||||
function BatchImport({ open, title, columns, existing, writeTarget = '草稿', onCancel, onImport }: { open: boolean; title: string; columns: string[]; existing: boolean; writeTarget?: string; onCancel: () => void; onImport: (rows: string[][], replace: boolean) => void }) {
|
||||
const [text, setText] = useState(''); const [replace, setReplace] = useState(false); const [error, setError] = useState('');
|
||||
useEffect(() => { if (open) { setText(''); setReplace(false); setError(''); } }, [open]);
|
||||
return <Modal className="management-modal structured-config-modal" open={open} title={`批量导入${title}`} width={760} okText={`检查并写入${writeTarget}`} onCancel={onCancel} onOk={() => {
|
||||
try {
|
||||
const rows = parseConfigDelimited(text);
|
||||
const first = rows[0]?.map(item => item.replace(/\s/g, '').toLowerCase());
|
||||
if (first?.[0] === columns[0].replace(/\s/g, '').toLowerCase() || ['source', 'code', 'pdt代码'].includes(first?.[0] || '')) rows.shift();
|
||||
if (!rows.length) throw new Error('表头下没有可导入的记录');
|
||||
onImport(rows, replace); setError('');
|
||||
} catch (value) { setError(value instanceof Error ? value.message : '导入内容有误'); }
|
||||
}}>
|
||||
<p>粘贴 CSV 或从表格复制的内容,列顺序为:{columns.join('、')}。首行可含表头;启用列可填写 true/false。</p>
|
||||
<Input.TextArea value={text} onChange={event => setText(event.target.value)} rows={10} spellCheck={false} aria-label={`${title}批量导入内容`} placeholder={columns.join(',')} />
|
||||
{existing && <Checkbox checked={replace} onChange={event => setReplace(event.target.checked)}>按相同编码或源条件更新已有记录(不勾选时重复即停止导入)</Checkbox>}
|
||||
{error && <Alert showIcon type="error" message="导入未写入" description={error} />}
|
||||
</Modal>;
|
||||
}
|
||||
|
||||
export function MappingDefinitionEditor({ value, onChange, simplified = false, readOnly = false }: DefinitionProps & { simplified?: boolean; readOnly?: boolean }) {
|
||||
const { message } = App.useApp();
|
||||
const [kind, setKind] = useState<MappingKind>('categoryLookup'); const [search, setSearch] = useState(''); const [status, setStatus] = useState('all');
|
||||
const [editing, setEditing] = useState<MappingRow | null>(null); const [newRow, setNewRow] = useState(false); const [importing, setImporting] = useState(false); const [editError, setEditError] = useState('');
|
||||
const [form] = Form.useForm<{ source: string; secondary: string; target: string; unassigned: boolean; enabled: boolean }>();
|
||||
const info = mappingInfo[kind]; const rows = useMemo(() => mappingRows(value, kind), [value, kind]);
|
||||
const visibleRows = rows.filter(row => `${row.source} ${row.secondary} ${row.target ?? ''}`.toLowerCase().includes(search.toLowerCase()) && (status === 'all' || row.enabled === (status === 'enabled')));
|
||||
const targetNames = Array.from(new Set([...masterRows(value, info.master).map(row => row.name), ...rows.map(row => row.target).filter((target): target is string => target !== null)]));
|
||||
const openRow = (row?: MappingRow) => { setEditing(row ?? { key: '', source: '', secondary: '', target: '', enabled: true }); setNewRow(!row); setEditError(''); form.setFieldsValue({ source: row?.source ?? '', secondary: row?.secondary ?? '', target: row?.target ?? '', unassigned: row?.target === null, enabled: row?.enabled ?? true }); };
|
||||
const columns: ColumnsType<MappingRow> = [
|
||||
{ title: info.source, dataIndex: 'source', key: 'source', width: 190 },
|
||||
...(info.secondary ? [{ title: info.secondary, dataIndex: 'secondary', key: 'secondary', width: 180 }] : []),
|
||||
{ title: info.target, dataIndex: 'target', key: 'target', width: 220, render: target => target === null ? <span className="structured-config-muted">未配置</span> : target },
|
||||
{ title: '状态', dataIndex: 'enabled', key: 'enabled', width: 100, render: enabled => <Tag color={enabled ? 'green' : 'default'}>{enabled ? '启用' : '停用'}</Tag> },
|
||||
...(!readOnly ? [{ title: '操作', key: 'actions', width: 205, render: (_: unknown, row: MappingRow) => <span className="task-actions"><Button type="link" onClick={() => openRow(row)}>编辑</Button><Button type="link" onClick={() => onChange(setMappingRows(value, kind, rows.map(item => item.key === row.key ? { ...item, enabled: !item.enabled } : item)))}>{row.enabled ? '停用' : '恢复'}</Button><Button type="link" danger onClick={() => onChange(setMappingRows(value, kind, rows.filter(item => item.key !== row.key)))}>删除</Button></span> }] : []),
|
||||
];
|
||||
const headers = [info.source, ...(info.secondary ? [info.secondary] : []), info.target, '启用'];
|
||||
return <div className="structured-config-editor">
|
||||
<Tabs activeKey={kind} onChange={key => { setKind(key as MappingKind); setSearch(''); }} items={mappingKinds.map(key => ({ key, label: mappingInfo[key].label }))} />
|
||||
<div className="structured-config-toolbar"><Input.Search value={search} onChange={event => setSearch(event.target.value)} placeholder="查找来源或目标" allowClear aria-label="查找对应关系" /><Select value={status} onChange={setStatus} aria-label="对应关系状态" options={[{ value: 'all', label: '全部状态' }, { value: 'enabled', label: '启用中' }, { value: 'disabled', label: '已停用' }]} /><span>{rows.length} 条 · 启用 {rows.filter(row => row.enabled).length}</span><div className="structured-config-actions"><Button icon={<DownloadOutlined />} onClick={() => downloadCsv(`${info.label}.csv`, [headers, ...rows.map(row => [row.source, ...(info.secondary ? [row.secondary] : []), row.target, row.enabled])])}>导出 CSV</Button>{!readOnly && <><Button icon={<UploadOutlined />} onClick={() => setImporting(true)}>批量导入</Button><Button type="primary" icon={<PlusOutlined />} onClick={() => openRow()}>新增对应</Button></>}</div></div>
|
||||
<Table size="small" bordered rowKey="key" columns={columns} dataSource={visibleRows} pagination={{ pageSize: 10, showSizeChanger: false }} scroll={{ x: info.secondary ? 860 : 680 }} locale={{ emptyText: '没有符合条件的对应关系' }} />
|
||||
<p className="structured-config-note">{simplified ? '新增的对应目标会自动补入对应名录;全部变更由页面主按钮一次保存并更新报表。' : '停用保留原对应值;变更经保存、校验并启用后用于新的数据构建。'}</p>
|
||||
<Modal className="management-modal structured-config-modal" open={Boolean(editing)} title={`${newRow ? '新增' : '编辑'}${info.label}`} width={560} okText={simplified ? '保存此行' : '写入草稿'} onCancel={() => setEditing(null)} onOk={() => { void form.validateFields().then(fields => {
|
||||
const source = kind === 'productLookup' ? fields.source.trim().toUpperCase() : fields.source.trim(); const secondary = fields.secondary?.trim() ?? '';
|
||||
const key = info.secondary ? `${source}|${secondary}` : source;
|
||||
if (rows.some(row => row.key === key && (newRow || row.key !== editing?.key))) { setEditError('相同源条件已有对应关系,请编辑已有行'); return; }
|
||||
const target = fields.unassigned ? null : String(fields.target ?? '').trim();
|
||||
if (target === '') { setEditError('请填写目标名称,或勾选“明确不设归属”'); return; }
|
||||
const updated = { key, source, secondary, target, enabled: fields.enabled };
|
||||
onChange(setMappingRows(value, kind, newRow ? [...rows, updated] : rows.map(row => row.key === editing?.key ? updated : row))); setEditing(null);
|
||||
}).catch(() => undefined); }}>
|
||||
<Form form={form} layout="vertical"><div className="structured-config-form-grid"><Form.Item name="source" label={info.source} rules={[{ required: true, whitespace: true, message: `请填写${info.source}` }, { validator: (_, text) => !info.secondary || !String(text ?? '').includes('|') ? Promise.resolve() : Promise.reject(new Error('请分别填写两个源条件')) }]}><Input /></Form.Item>{info.secondary && <Form.Item name="secondary" label={info.secondary} rules={[{ required: true, whitespace: true, message: `请填写${info.secondary}` }, { validator: (_, text) => !String(text ?? '').includes('|') ? Promise.resolve() : Promise.reject(new Error('源条件不能包含 |')) }]}><Input /></Form.Item>}</div>
|
||||
<Form.Item noStyle shouldUpdate={(before, after) => before.unassigned !== after.unassigned}>{({ getFieldValue }) => <Form.Item name="target" label={info.target}><AutoComplete disabled={getFieldValue('unassigned')} options={targetNames.map(name => { const item = masterRows(value, info.master).find(row => row.name === name); return { value: name, label: `${name}${item?.enabled === false ? '(已停用)' : ''}` }; })} filterOption={(input, option) => String(option?.label || option?.value || '').toLowerCase().includes(input.toLowerCase())} placeholder="选择或输入目标名称" /></Form.Item>}</Form.Item>
|
||||
<Form.Item name="unassigned" valuePropName="checked"><Checkbox>明确不设归属(保留空值)</Checkbox></Form.Item><Form.Item name="enabled" label="状态" valuePropName="checked"><Switch checkedChildren="启用" unCheckedChildren="停用" /></Form.Item></Form>
|
||||
{editError && <Alert showIcon type="error" message={editError} />}
|
||||
</Modal>
|
||||
<BatchImport open={importing} title={info.label} columns={headers} existing={rows.length > 0} writeTarget={simplified ? '当前配置' : '草稿'} onCancel={() => setImporting(false)} onImport={(input, replace) => {
|
||||
const incoming: MappingRow[] = []; const keys = new Set<string>();
|
||||
input.forEach((cells, index) => {
|
||||
const expected = info.secondary ? 4 : 3;
|
||||
if (cells.length < expected - 1 || cells.length > expected) throw new Error(`第 ${index + 1} 行应为 ${expected - 1} 或 ${expected} 列`);
|
||||
const source = kind === 'productLookup' ? cells[0].toUpperCase() : cells[0]; const secondary = info.secondary ? cells[1] : '';
|
||||
if (!source || (info.secondary && !secondary)) throw new Error(`第 ${index + 1} 行来源条件不完整`);
|
||||
if (info.secondary && (source.includes('|') || secondary.includes('|'))) throw new Error(`第 ${index + 1} 行请分别填写两个源条件`);
|
||||
const key = info.secondary ? `${source}|${secondary}` : source;
|
||||
if (keys.has(key)) throw new Error(`第 ${index + 1} 行与导入内容重复:${key}`); keys.add(key);
|
||||
const previous = rows.find(row => row.key === key);
|
||||
if (previous && !replace) throw new Error(`第 ${index + 1} 行已存在:${key}`);
|
||||
incoming.push({ key, source, secondary, target: cells[info.secondary ? 2 : 1] || null, enabled: parseEnabled(cells[expected - 1], index + 1) ?? previous?.enabled ?? true });
|
||||
});
|
||||
const changed = new Set(incoming.map(row => row.key)); onChange(setMappingRows(value, kind, [...rows.filter(row => !changed.has(row.key)), ...incoming])); setImporting(false); message.success(simplified ? `已将 ${incoming.length} 条对应关系加入当前编辑` : `已将 ${incoming.length} 条对应关系写入草稿,请保存后校验`);
|
||||
}} />
|
||||
</div>;
|
||||
}
|
||||
|
||||
type MatchCondition = { field: string; operator: string; value?: string };
|
||||
type MatchRule = { id?: string; name: string; enabled: boolean; priority: number; stage: string; conditions: MatchCondition[]; target: string; value: string };
|
||||
type MatchMetadata = { fields?: unknown[]; operators?: unknown[]; targets?: unknown[]; stages?: unknown[]; defaultRules?: unknown[]; limits?: Record<string, unknown> };
|
||||
const defaultMatchRules: MatchRule[] = [{ id: 'vcm-category', name: '成品规格含VCM归工业电机-VCM', enabled: true, priority: 100, stage: 'all', conditions: [{ field: '成品规格', operator: 'CONTAINS', value: 'VCM' }], target: 'group', value: '工业电机-VCM' }];
|
||||
const plainObject = (value: unknown) => value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
||||
type MatchOption = { value: string; label: string };
|
||||
const metadataOptions = (value: unknown, fallback: MatchOption[]): MatchOption[] => Array.isArray(value) && value.length
|
||||
? value.map(item => { const row = plainObject(item); return { value: String(row.id || row.value || ''), label: String(row.label || row.name || row.id || row.value || '') }; }).filter(item => item.value)
|
||||
: fallback;
|
||||
|
||||
export function MatchRulesDefinitionEditor({ value, onChange, metadata, readOnly = false }: DefinitionProps & { metadata?: MatchMetadata | null; readOnly?: boolean }) {
|
||||
const [editing, setEditing] = useState<MatchRule | null>(null);
|
||||
const [error, setError] = useState('');
|
||||
const fields = metadataOptions(metadata?.fields, [
|
||||
{ value: 'PDT代码', label: 'PDT代码' }, { value: '销售片区', label: '销售片区' }, { value: '客户代码', label: '客户代码' },
|
||||
{ value: '成品规格', label: '成品规格' }, { value: '@department', label: '已算产业部 @department' }, { value: '@group', label: '已算业务分组 @group' },
|
||||
{ value: '@product', label: '已算产品 @product' }, { value: '@projectGroup', label: '已算项目组 @projectGroup' },
|
||||
]);
|
||||
const operators = metadataOptions(metadata?.operators, [
|
||||
{ value: 'EQUALS', label: '等于' }, { value: 'NOT_EQUALS', label: '不等于' }, { value: 'CONTAINS', label: '包含' },
|
||||
{ value: 'STARTS_WITH', label: '开头是' }, { value: 'IS_BLANK', label: '为空' }, { value: 'IS_NOT_BLANK', label: '不为空' },
|
||||
]);
|
||||
const targets = metadataOptions(metadata?.targets, [
|
||||
{ value: 'department', label: '产业部' }, { value: 'group', label: '业务分组' }, { value: 'product', label: '产品' }, { value: 'projectGroup', label: '项目组' },
|
||||
]);
|
||||
const stages = metadataOptions(metadata?.stages, [
|
||||
{ value: 'all', label: '黑片和亮片' }, { value: 'black', label: '黑片' }, { value: 'bright', label: '亮片' },
|
||||
]);
|
||||
const sourceRules = Array.isArray(value.matchRules) ? value.matchRules : (metadata?.defaultRules ?? defaultMatchRules);
|
||||
const rules = sourceRules.map((item, index) => {
|
||||
const row = plainObject(item);
|
||||
return { id: String(row.id || `match-${index + 1}`), name: String(row.name || `条件规则 ${index + 1}`), enabled: row.enabled !== false, priority: Number(row.priority ?? (index + 1) * 100), stage: String(row.stage || 'all'), conditions: Array.isArray(row.conditions) ? row.conditions.map(condition => { const conditionRow = plainObject(condition); return { field: String(conditionRow.field || ''), operator: String(conditionRow.operator || 'EQUALS'), ...(conditionRow.value === undefined ? {} : { value: String(conditionRow.value) }) }; }) : [], target: String(row.target || 'group'), value: String(row.value || '') } as MatchRule;
|
||||
});
|
||||
const labelFor = (options: MatchOption[], id: string) => options.find(option => option.value === id)?.label || id;
|
||||
const conditionText = (condition: MatchCondition) => `${labelFor(fields, condition.field)} ${labelFor(operators, condition.operator)}${['IS_BLANK', 'IS_NOT_BLANK'].includes(condition.operator) ? '' : ` ${condition.value || '…'}`}`;
|
||||
const readableRule = (rule: MatchRule) => `当 ${rule.conditions.map(conditionText).join(' 且 ') || '(未设置条件)'} → ${labelFor(targets, rule.target)}:${rule.value || '(未填写)'}`;
|
||||
const commit = (next: MatchRule[]) => onChange({ ...value, matchRules: next.map((rule, index) => ({ ...rule, id: rule.id || `match-${index + 1}` })) });
|
||||
const open = (rule?: MatchRule) => {
|
||||
setError('');
|
||||
setEditing(rule ? { ...rule, conditions: rule.conditions.map(condition => ({ ...condition })) } : { name: '', enabled: true, priority: Math.min(10000, (rules.length + 1) * 100), stage: 'all', conditions: [{ field: '', operator: 'EQUALS', value: '' }], target: 'group', value: '' });
|
||||
};
|
||||
const operatorDescription = (operator: string) => ['IS_BLANK', 'IS_NOT_BLANK'].includes(operator) ? '' : operator;
|
||||
return <div className="structured-config-editor structured-match-editor">
|
||||
<div className="structured-config-toolbar"><span>按优先级从小到大执行;同一目标类型只采用首条命中规则。条件之间按“且”组合。</span><div className="structured-config-actions">{!readOnly && <Button type="primary" icon={<PlusOutlined />} onClick={() => open()}>新增匹配规则</Button>}</div></div>
|
||||
<Table size="small" bordered rowKey="id" dataSource={rules} pagination={false} scroll={{ x: 1080 }} columns={[
|
||||
{ title: '顺序', dataIndex: 'priority', width: 84, align: 'right', sorter: (a, b) => a.priority - b.priority },
|
||||
{ title: '规则名称', dataIndex: 'name', width: 220 },
|
||||
{ title: '匹配条件', width: 410, render: (_, row) => <span className="structured-match-readable">{readableRule(row)}</span> },
|
||||
{ title: '阶段', dataIndex: 'stage', width: 104, render: stage => labelFor(stages, String(stage)) },
|
||||
{ title: '状态', dataIndex: 'enabled', width: 84, render: enabled => <Tag color={enabled ? 'green' : 'default'}>{enabled ? '启用' : '停用'}</Tag> },
|
||||
...(!readOnly ? [{ title: '操作', width: 150, render: (_: unknown, row: MatchRule) => <span className="task-actions"><Button type="link" onClick={() => open(row)}>编辑</Button><Button type="link" onClick={() => commit(rules.map(item => item.id === row.id ? { ...item, enabled: !item.enabled } : item))}>{row.enabled ? '停用' : '启用'}</Button><Button type="link" danger onClick={() => commit(rules.filter(item => item.id !== row.id))}>删除</Button></span> }] : []),
|
||||
]} locale={{ emptyText: '还没有条件匹配规则' }} />
|
||||
<Modal className="management-modal structured-config-modal" open={Boolean(editing)} title={editing?.id ? '编辑条件匹配规则' : '新增条件匹配规则'} width={860} okText="保存规则" onCancel={() => setEditing(null)} onOk={() => {
|
||||
if (!editing) return;
|
||||
const next = { ...editing, name: editing.name.trim(), value: editing.value.trim(), conditions: editing.conditions.map(condition => ({ field: condition.field.trim(), operator: condition.operator, value: ['IS_BLANK', 'IS_NOT_BLANK'].includes(condition.operator) ? '' : String(condition.value || '').trim() })) };
|
||||
if (!next.name) { setError('请填写规则名称'); return; }
|
||||
if (!next.conditions.length || next.conditions.some(condition => !condition.field || (!['IS_BLANK', 'IS_NOT_BLANK'].includes(condition.operator) && !condition.value))) { setError('请补全每条条件的字段和判断值'); return; }
|
||||
if (!next.value) { setError('请填写匹配结果'); return; }
|
||||
commit(editing.id ? rules.map(rule => rule.id === editing.id ? next : rule) : [...rules, { ...next, id: `match-${crypto.randomUUID()}` }]); setEditing(null);
|
||||
}}>
|
||||
{editing && <Form layout="vertical"><div className="structured-config-form-grid"><Form.Item label="规则名称" required><Input value={editing.name} maxLength={160} onChange={event => setEditing({ ...editing, name: event.target.value })} /></Form.Item><Form.Item label="优先级" required><InputNumber min={-10000} max={10000} style={{ width: '100%' }} value={editing.priority} onChange={priority => setEditing({ ...editing, priority: Number(priority ?? 0) })} /></Form.Item><Form.Item label="阶段"><Select value={editing.stage} options={stages} onChange={stage => setEditing({ ...editing, stage })} /></Form.Item><Form.Item label="状态"><Switch checked={editing.enabled} checkedChildren="启用" unCheckedChildren="停用" onChange={enabled => setEditing({ ...editing, enabled })} /></Form.Item></div>
|
||||
<div className="structured-config-toolbar"><strong>命中条件(条件之间按“且”组合)</strong><Button icon={<PlusOutlined />} onClick={() => setEditing({ ...editing, conditions: [...editing.conditions, { field: '', operator: 'EQUALS', value: '' }] })}>新增条件</Button></div>
|
||||
<Table size="small" bordered rowKey={(_, index) => String(index)} pagination={false} dataSource={editing.conditions} columns={[
|
||||
{ title: '字段', width: 250, render: (_, condition, index) => <AutoComplete value={condition.field} options={fields} style={{ width: '100%' }} filterOption={(input, option) => String(option?.label || '').toLowerCase().includes(input.toLowerCase())} placeholder="选择或输入字段" onChange={field => setEditing({ ...editing, conditions: editing.conditions.map((row, rowIndex) => rowIndex === index ? { ...row, field } : row) })} /> },
|
||||
{ title: '判断方式', width: 180, render: (_, condition, index) => <Select {...readableSelectPopup} value={condition.operator} options={operators} style={{ width: '100%' }} onChange={operator => setEditing({ ...editing, conditions: editing.conditions.map((row, rowIndex) => rowIndex === index ? { ...row, operator, ...(operatorDescription(operator) ? {} : { value: undefined }) } : row) })} /> },
|
||||
{ title: '判断值', render: (_, condition, index) => ['IS_BLANK', 'IS_NOT_BLANK'].includes(condition.operator) ? <span className="structured-config-muted">无需填写</span> : <Input value={condition.value} onChange={event => setEditing({ ...editing, conditions: editing.conditions.map((row, rowIndex) => rowIndex === index ? { ...row, value: event.target.value } : row) })} /> },
|
||||
{ title: '', width: 82, render: (_, __, index) => <Button type="link" danger disabled={editing.conditions.length <= 1} onClick={() => setEditing({ ...editing, conditions: editing.conditions.filter((__, rowIndex) => rowIndex !== index) })}>移除</Button> },
|
||||
]} />
|
||||
<div className="structured-config-form-grid" style={{ marginTop: 16 }}><Form.Item label="目标类型"><Select value={editing.target} options={targets} onChange={target => setEditing({ ...editing, target })} /></Form.Item><Form.Item label="匹配结果" required><Input value={editing.value} maxLength={190} onChange={event => setEditing({ ...editing, value: event.target.value })} placeholder="例如:工业电机-VCM" /></Form.Item></div>
|
||||
{error && <Alert showIcon type="error" message={error} />}
|
||||
</Form>}
|
||||
</Modal>
|
||||
</div>;
|
||||
}
|
||||
|
||||
export function MasterDataDefinitionEditor({ value, onChange, publishedNames, simplified = false, readOnly = false }: DefinitionProps & { publishedNames?: Partial<Record<MasterKind, string[]>> & { groupDepartments?: Record<string, string | null> }; simplified?: boolean; readOnly?: boolean }) {
|
||||
const { message } = App.useApp(); const [kind, setKind] = useState<MasterKind>('departments'); const [search, setSearch] = useState('');
|
||||
const [editing, setEditing] = useState<MasterRow | null>(null); const [originalCode, setOriginalCode] = useState<string | null>(null); const [error, setError] = useState(''); const [importing, setImporting] = useState(false);
|
||||
const [departmentAtOpen, setDepartmentAtOpen] = useState<{ value: string } | null>(null);
|
||||
const [form] = Form.useForm<MasterRow>(); const rows = masterRows(value, kind); const label = masterLabels[kind];
|
||||
const departmentFor = (row: MasterRow) => Object.hasOwn(row, 'department') ? String(row.department ?? '') : String(publishedNames?.groupDepartments?.[row.name] ?? '');
|
||||
const openRow = (row?: MasterRow) => { const initial = row ?? { code: '', name: '', enabled: true }; const department = kind === 'groups' ? row ? departmentFor(row) : '' : null; setEditing(initial); setOriginalCode(row?.code ?? null); setDepartmentAtOpen(department === null ? null : { value: department }); setError(''); form.setFieldsValue({ ...initial, ...(kind === 'groups' ? { department: department ?? '' } : {}) }); };
|
||||
const loadExisting = () => {
|
||||
let next = { ...value }; let count = 0;
|
||||
for (const masterKind of masterKinds) {
|
||||
const existing = masterRows(next, masterKind); const names = new Set(existing.map(row => row.name)); const codes = new Set(existing.map(row => row.code)); const added: MasterRow[] = [];
|
||||
const candidates = [...(publishedNames?.[masterKind] ?? []), ...mappingKinds.filter(item => mappingInfo[item].master === masterKind).flatMap(mappingKind => mappingRows(value, mappingKind).map(row => row.target))];
|
||||
for (const name of candidates) {
|
||||
if (name === null || !name || names.has(name)) continue;
|
||||
let code = name.slice(0, 100); let suffix = 2; while (codes.has(code)) { const tail = `-${suffix++}`; code = `${name.slice(0, 100 - tail.length)}${tail}`; }
|
||||
added.push({ code, name, enabled: true }); names.add(name); codes.add(code); count++;
|
||||
}
|
||||
next = setMasterRows(next, masterKind, [...existing, ...added]);
|
||||
}
|
||||
onChange(next); message.success(count ? `已从当前配置及对应值载入 ${count} 个名称,请核对编码后保存` : '现有名称均已在名录中');
|
||||
};
|
||||
const departments = masterRows(value, 'departments');
|
||||
const columns: ColumnsType<MasterRow> = [{ title: '编码', dataIndex: 'code', key: 'code', width: 220 }, { title: '名称', dataIndex: 'name', key: 'name', width: 300 }, ...(kind === 'groups' ? [{ title: '所属产业部', key: 'department', width: 220, render: (_: unknown, row: MasterRow) => { const department = departmentFor(row); const parent = departments.find(item => item.name === department); return department ? `${department}${parent && !parent.enabled ? '(已停用)' : ''}` : <span className="structured-config-muted">未设置</span>; } }] : []), { title: '状态', dataIndex: 'enabled', key: 'enabled', width: 100, render: enabled => <Tag color={enabled ? 'green' : 'default'}>{enabled ? '启用' : '停用'}</Tag> }, ...(!readOnly ? [{ title: '操作', key: 'actions', width: 205, render: (_: unknown, row: MasterRow) => <span className="task-actions"><Button type="link" onClick={() => openRow(row)}>编辑</Button><Button type="link" onClick={() => onChange(setMasterRows(value, kind, rows.map(item => item.code === row.code ? { ...item, enabled: !item.enabled } : item)))}>{row.enabled ? '停用' : '恢复'}</Button><Button type="link" danger onClick={() => onChange(setMasterRows(value, kind, rows.filter(item => item.code !== row.code)))}>删除</Button></span> }] : [])];
|
||||
const csvHeaders = kind === 'groups' ? ['编码', '名称', '启用', '所属产业部'] : ['编码', '名称', '启用'];
|
||||
const departmentValue = Form.useWatch('department', form);
|
||||
const selectedDepartment = typeof departmentValue === 'string' ? departmentValue : '';
|
||||
const departmentOptions = departments.filter(row => row.enabled || row.name === selectedDepartment).map(row => ({ value: row.name, label: `${row.name}${row.enabled ? '' : '(已停用)'}`, disabled: !row.enabled }));
|
||||
if (selectedDepartment && !departmentOptions.some(option => option.value === selectedDepartment)) departmentOptions.push({ value: selectedDepartment, label: `${selectedDepartment}(未在产业部名录中)`, disabled: true });
|
||||
const visibleRows = rows.filter(row => `${row.code} ${row.name} ${kind === 'groups' ? departmentFor(row) : ''}`.toLowerCase().includes(search.toLowerCase()));
|
||||
return <div className="structured-config-editor">
|
||||
<div className="structured-config-intro"><p>维护产业部、业务分组、产品及项目组的统一名录。编码与名称必须唯一。</p>{!simplified && <Button onClick={loadExisting}>从当前配置及对应关系载入名录</Button>}</div>
|
||||
<Tabs activeKey={kind} onChange={key => { setKind(key as MasterKind); setSearch(''); }} items={masterKinds.map(key => ({ key, label: `${masterLabels[key]}(${masterRows(value, key).length})` }))} />
|
||||
<div className="structured-config-toolbar"><Input.Search value={search} onChange={event => setSearch(event.target.value)} placeholder="查找编码、名称或所属产业部" allowClear aria-label={`查找${label}`} /><span>{rows.length} 条 · 启用 {rows.filter(row => row.enabled).length}</span><div className="structured-config-actions"><Button icon={<DownloadOutlined />} onClick={() => downloadCsv(`${label}名录.csv`, [csvHeaders, ...rows.map(row => [row.code, row.name, row.enabled, ...(kind === 'groups' ? [departmentFor(row)] : [])])])}>导出 CSV</Button>{!readOnly && <><Button icon={<UploadOutlined />} onClick={() => setImporting(true)}>批量导入</Button><Button type="primary" icon={<PlusOutlined />} onClick={() => openRow()}>新增{label}</Button></>}</div></div>
|
||||
<Table size="small" bordered rowKey="code" columns={columns} dataSource={visibleRows} pagination={{ pageSize: 10, showSizeChanger: false }} scroll={{ x: kind === 'groups' ? 940 : 720 }} locale={{ emptyText: `尚未维护${label}名录` }} />
|
||||
<p className="structured-config-note">停用项保留在名录中;启用中的对应关系如引用停用名称,校验将指出具体位置。已有分析记录保留生成时使用的名称。</p>
|
||||
<Modal className="management-modal structured-config-modal" open={Boolean(editing)} title={`${originalCode === null ? '新增' : '编辑'}${label}`} width={520} okText={simplified ? '保存此行' : '写入草稿'} onCancel={() => setEditing(null)} onOk={() => { void form.validateFields().then(fields => {
|
||||
const existing = originalCode === null ? undefined : rows.find(item => item.code === originalCode);
|
||||
const department = String(fields.department ?? '').trim();
|
||||
const persistDepartment = kind === 'groups' && (!existing || Object.hasOwn(existing, 'department')
|
||||
|| department !== (departmentAtOpen?.value ?? '') || (!!department && fields.name.trim() !== existing.name));
|
||||
const row: MasterRow = { ...existing, code: fields.code.trim(), name: fields.name.trim(), enabled: fields.enabled, ...(persistDepartment ? { department } : {}) };
|
||||
if (rows.some(item => item.code !== originalCode && (item.code === row.code || item.name === row.name))) { setError('编码或名称已存在,请编辑已有行'); return; }
|
||||
onChange(setMasterRows(value, kind, originalCode === null ? [...rows, row] : rows.map(item => item.code === originalCode ? row : item))); setEditing(null);
|
||||
}).catch(() => undefined); }}><Form form={form} layout="vertical"><Form.Item name="code" label="编码" rules={[{ required: true, whitespace: true, message: '请填写编码' }]}><Input maxLength={100} /></Form.Item><Form.Item name="name" label="名称" rules={[{ required: true, whitespace: true, message: '请填写名称' }]}><Input maxLength={190} /></Form.Item>{kind === 'groups' && <Form.Item name="department" label="所属产业部"><Select {...readableSelectPopup} allowClear placeholder="可不设置;选择启用中的产业部" options={departmentOptions} /></Form.Item>}<Form.Item name="enabled" label="状态" valuePropName="checked"><Switch checkedChildren="启用" unCheckedChildren="停用" /></Form.Item></Form>{error && <Alert showIcon type="error" message={error} />}</Modal>
|
||||
<BatchImport open={importing} title={`${label}名录`} columns={csvHeaders} existing={rows.length > 0} writeTarget={simplified ? '当前配置' : '草稿'} onCancel={() => setImporting(false)} onImport={(input, replace) => {
|
||||
const incoming: MasterRow[] = []; const codes = new Set<string>(); const names = new Set<string>();
|
||||
input.forEach((cells, index) => {
|
||||
const maxColumns = kind === 'groups' ? 4 : 3;
|
||||
if (cells.length < 2 || cells.length > maxColumns || !cells[0] || !cells[1]) throw new Error(`第 ${index + 1} 行应包含编码、名称${kind === 'groups' ? '、可选启用状态及可选所属产业部' : '及可选启用状态'}`);
|
||||
if (codes.has(cells[0]) || names.has(cells[1])) throw new Error(`第 ${index + 1} 行编码或名称在导入内容中重复`); codes.add(cells[0]); names.add(cells[1]);
|
||||
const previous = rows.find(row => row.code === cells[0]);
|
||||
if (previous && !replace) throw new Error(`第 ${index + 1} 行编码已存在:${cells[0]}`);
|
||||
if (rows.some(row => row.name === cells[1] && row.code !== cells[0] && !input.some(candidate => candidate[0] === row.code))) throw new Error(`第 ${index + 1} 行名称已被其他编码使用:${cells[1]}`);
|
||||
const renamedParent = kind === 'groups' && previous && previous.name !== cells[1] && !Object.hasOwn(previous, 'department')
|
||||
? departmentFor(previous) : '';
|
||||
incoming.push({ ...previous, code: cells[0], name: cells[1], enabled: parseEnabled(cells[2], index + 1) ?? previous?.enabled ?? true,
|
||||
...(kind === 'groups' && cells.length >= 4 ? { department: cells[3] } : renamedParent ? { department: renamedParent } : {}) });
|
||||
});
|
||||
const changed = new Set(incoming.map(row => row.code)); const result = [...rows.filter(row => !changed.has(row.code)), ...incoming];
|
||||
if (new Set(result.map(row => row.name)).size !== result.length) throw new Error('导入后名称重复,请检查编码与名称');
|
||||
onChange(setMasterRows(value, kind, result)); setImporting(false); message.success(simplified ? `已将 ${incoming.length} 个名称加入当前编辑` : `已将 ${incoming.length} 个名称写入草稿,请保存后校验`);
|
||||
}} />
|
||||
</div>;
|
||||
}
|
||||
|
||||
export function TechnicalDefinitionEditor({ value, onChange }: DefinitionProps) {
|
||||
const [text, setText] = useState(JSON.stringify(withoutSystemVersionFields(value), null, 2)); const [error, setError] = useState(''); const { message } = App.useApp();
|
||||
useEffect(() => { setText(JSON.stringify(withoutSystemVersionFields(value), null, 2)); setError(''); }, [value]);
|
||||
return <details className="structured-config-technical"><summary>可编辑规则定义</summary><p className="structured-config-note">系统维护字段已隐藏,保存时会自动保留。</p><Input.TextArea rows={12} value={text} onChange={event => setText(event.target.value)} spellCheck={false} className="json-editor" aria-label="可编辑规则定义" /><Button onClick={() => {
|
||||
try { const parsed: unknown = JSON.parse(text); if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('定义必须是对象'); onChange(preserveSystemVersionFields(parsed, value) as ConfigDefinition); setError(''); message.success('定义已应用到当前草稿,请保存'); } catch (value) { setError(value instanceof Error ? value.message : 'JSON 无效'); }
|
||||
}}>应用到草稿</Button>{error && <Alert type="error" showIcon message={error} />}</details>;
|
||||
}
|
||||
|
||||
type RuleRow = Record<string, unknown>;
|
||||
const policyLabels: Record<string, string> = { PROPAGATE: '任一输入为空则结果为空', ZERO: '空值按 0 参与计算', IGNORE: '全部为空则为空,其余按 0', ONE: '分母为 0 时返回 1', NULL: '分母为 0 时返回空值', ERROR: '分母为 0 时停止计算' };
|
||||
const nullResultLabels: Record<string, string> = { NULL: '保留空值', ONE: '返回 1', ZERO: '返回 0', ERROR: '停止并报错' };
|
||||
const zeroPolicyLabels: Record<string, string> = { ONE: '返回 1', ZERO: '返回 0', NULL: '返回空值', ERROR: '停止并报错' };
|
||||
const operatorLabels: Record<string, string> = { EQ: '等于', NE: '不等于', CONTAINS: '包含', NOT_CONTAINS: '不包含', IS_BLANK: '为空', IS_NOT_BLANK: '不为空', GT: '大于', GTE: '大于等于', LT: '小于', LTE: '小于等于' };
|
||||
function stringList(value: unknown): string[] { return Array.isArray(value) ? value.map(String) : []; }
|
||||
|
||||
export function RuleDefinitionEditor({ value, onChange, schema, schemaError }: DefinitionProps & { schema: Record<string, unknown> | null; schemaError: string }) {
|
||||
const [tab, setTab] = useState('source'); const [editing, setEditing] = useState<number | null>(null); const [ruleError, setRuleError] = useState('');
|
||||
const [form] = Form.useForm<{ stage: string; target: string; formula: string; nullPolicy: string; zeroDenominatorPolicy: string; nullResultPolicy: string; conditional: boolean; conditionField: string; conditionOperator: string; conditionValue: string; otherwiseFormula: string }>();
|
||||
const selectedStage = Form.useWatch('stage', form) || 'black'; const conditional = Form.useWatch('conditional', form); const conditionOperator = Form.useWatch('conditionOperator', form);
|
||||
if (!schema) return <Alert showIcon type={schemaError ? 'error' : 'info'} message={schemaError ? '规则编辑结构读取失败' : '正在读取规则编辑结构'} description={schemaError || '编辑项与可用公式变量由服务端提供。'} />;
|
||||
const configured = value.schemaVersion === schema.schemaVersion;
|
||||
const fields = objectValue(schema.sourceFields); const targets = objectValue(schema.rowTargets); const componentLabels = objectValue(schema.componentLabels); const metricLabels = objectValue(schema.metricLabels); const baselineDescriptions = objectValue(schema.baselineMetricDescriptions);
|
||||
const nullOptions = stringList(schema.nullPolicies).map(key => ({ value: key, label: policyLabels[key] || key })); const zeroOptions = stringList(schema.zeroDenominatorPolicies).map(key => ({ value: key, label: zeroPolicyLabels[key] || key }));
|
||||
const nullResultOptions = stringList(schema.nullResultPolicies).map(key => ({ value: key, label: nullResultLabels[key] || key }));
|
||||
const sourceFields = objectValue(value.sourceFields); const rowRules = Array.isArray(value.rowRules) ? value.rowRules.map(objectValue) : []; const metricRules = objectValue(value.metricRules); const metricCodes = stringList(schema.metricCodes);
|
||||
const limits = objectValue(schema.limits); const maxFormulaLength = Number(limits.maxFormulaLength || 500); const maxRowRules = Number(limits.maxRowRules || 100);
|
||||
const targetLabel = (target: unknown) => String(componentLabels[String(target)] || target || ''); const metricLabel = (metric: string) => String(metricLabels[metric] || metric);
|
||||
const replaceRules = (rules: RuleRow[]) => onChange({ ...value, rowRules: rules });
|
||||
const editRow = (index: number | null) => {
|
||||
const rule = index === null ? {} : rowRules[index]; const when = objectValue(rule.when); const stage = String(rule.stage || 'black');
|
||||
setEditing(index === null ? rowRules.length : index); setRuleError('');
|
||||
form.setFieldsValue({ stage, target: String(rule.target || stringList(targets[stage])[0] || ''), formula: String(rule.formula || ''), nullPolicy: String(rule.nullPolicy || 'PROPAGATE'), zeroDenominatorPolicy: String(rule.zeroDenominatorPolicy || 'ONE'), nullResultPolicy: String(rule.nullResultPolicy || 'NULL'), conditional: Boolean(rule.when), conditionField: String(when.field || Object.keys(objectValue(fields[stage]))[0] || ''), conditionOperator: String(when.operator || 'CONTAINS'), conditionValue: String(when.value ?? ''), otherwiseFormula: String(rule.otherwiseFormula || '') });
|
||||
};
|
||||
const metricVariables = ['blackGood', 'blackScrap', 'blackTotal', 'brightGood', 'brightScrap', 'brightTotal', 'headquartersScrap'];
|
||||
const ruleColumns: ColumnsType<RuleRow & { index: number }> = [
|
||||
{ title: '顺序', dataIndex: 'index', width: 70, render: index => index + 1 },
|
||||
{ title: '阶段 / 结果', key: 'target', width: 205, render: (_, row) => <span>{row.stage === 'black' ? '黑片' : '亮片'} · {targetLabel(row.target)}</span> },
|
||||
{ title: '公式', dataIndex: 'formula', width: 290, render: formula => <code>{String(formula)}</code> },
|
||||
{ title: '触发条件', key: 'when', width: 200, render: (_, row) => { const when = objectValue(row.when); return row.when ? `${String(objectValue(fields[String(row.stage)])[String(when.field)] || when.field)} ${operatorLabels[String(when.operator)] || when.operator} ${String(when.value ?? '')}` : '所有行'; } },
|
||||
{ title: '操作', key: 'actions', width: 205, render: (_, row) => <span className="task-actions"><Button type="link" onClick={() => editRow(row.index)}>编辑</Button><Button type="link" disabled={row.index === 0} onClick={() => { const next = [...rowRules]; [next[row.index - 1], next[row.index]] = [next[row.index], next[row.index - 1]]; replaceRules(next); }}>上移</Button><Button type="link" disabled={row.index === rowRules.length - 1} onClick={() => { const next = [...rowRules]; [next[row.index], next[row.index + 1]] = [next[row.index + 1], next[row.index]]; replaceRules(next); }}>下移</Button><Button type="link" onClick={() => replaceRules(rowRules.filter((_, index) => index !== row.index))}>移除</Button></span> },
|
||||
];
|
||||
if (!configured) return <div className="structured-config-editor"><Alert showIcon type="info" message="当前草稿沿用原始公式" description="当前公式继续生效。需要调整字段或公式时,先转换为可维护规则;未覆盖的计算继续沿用原逻辑。" /><Button style={{ marginTop: 12 }} onClick={() => onChange(JSON.parse(JSON.stringify(objectValue(schema.defaultDefinition))) as ConfigDefinition)}>开始维护字段与公式</Button></div>;
|
||||
return <div className="structured-config-editor">
|
||||
<Tabs activeKey={tab} onChange={setTab} items={[
|
||||
{ key: 'source', label: '来源字段', children: <div><p className="structured-config-note" style={{ marginBottom: 12 }}>将计算字段对应到来源表列名。未修改项沿用原列名,字段别名用于公式引用。</p><Tabs items={['black', 'bright'].map(stage => ({ key: stage, label: stage === 'black' ? '黑片字段' : '亮片字段', children: <Table size="small" bordered rowKey="alias" pagination={false} scroll={{ x: 670 }} dataSource={Object.entries(objectValue(fields[stage])).map(([alias, header]) => ({ alias, header: String(header) }))} columns={[
|
||||
{ title: '计算字段', dataIndex: 'header', width: 240 }, { title: '公式别名', dataIndex: 'alias', width: 200, render: alias => <code>{alias}</code> },
|
||||
{ title: '来源表列名', key: 'source', render: (_, row) => <Input aria-label={`${stage === 'black' ? '黑片' : '亮片'} ${row.header}来源列名`} value={String(objectValue(sourceFields[stage])[row.alias] ?? row.header)} maxLength={200} onChange={event => onChange({ ...value, sourceFields: { ...sourceFields, [stage]: { ...objectValue(sourceFields[stage]), [row.alias]: event.target.value } } })} /> },
|
||||
{ title: '操作', key: 'reset', width: 100, render: (_, row) => <Button type="link" onClick={() => { const next = { ...objectValue(sourceFields[stage]) }; delete next[row.alias]; onChange({ ...value, sourceFields: { ...sourceFields, [stage]: next } }); }}>恢复原列名</Button> },
|
||||
]} /> }))} /></div> },
|
||||
{ key: 'rows', label: `行计算(${rowRules.length})`, children: <div><div className="structured-config-toolbar"><span>按顺序执行;未覆盖的结果沿用原计算。</span><div className="structured-config-actions"><Button type="primary" icon={<PlusOutlined />} disabled={rowRules.length >= maxRowRules} onClick={() => editRow(null)}>新增行公式</Button></div></div><Table size="small" bordered rowKey="index" columns={ruleColumns} dataSource={rowRules.map((row, index) => ({ ...row, index }))} pagination={false} scroll={{ x: 980 }} locale={{ emptyText: '当前全部沿用原始行计算' }} /><p className="structured-config-note">修改报废等分量后,如需改变合计结果,请同时维护依赖它的合计公式。</p></div> },
|
||||
{ key: 'metrics', label: '指标公式', children: <div className="structured-config-rule-list"><p className="structured-config-note">未开启覆盖的指标沿用原始公式。公式可引用重量变量及排在前面的指标结果。</p>{metricCodes.map((metric, index) => {
|
||||
const rule = objectValue(metricRules[metric]); const enabled = Object.hasOwn(metricRules, metric);
|
||||
const updateMetric = (patch: Record<string, unknown>) => onChange({ ...value, metricRules: { ...metricRules, [metric]: { ...rule, ...patch } } });
|
||||
return <div className="structured-config-rule-card" key={metric}><div className="structured-config-toolbar"><strong>{metricLabel(metric)}</strong><code>{metric}</code><Checkbox checked={enabled} onChange={event => { const next = { ...metricRules }; if (event.target.checked) next[metric] = { formula: '', nullPolicy: 'PROPAGATE', zeroDenominatorPolicy: 'ONE', ...(nullResultOptions.length ? { nullResultPolicy: 'NULL' } : {}) }; else delete next[metric]; onChange({ ...value, metricRules: next }); }}>使用此公式</Checkbox></div>{Boolean(baselineDescriptions[metric]) && <p className="structured-config-note" style={{ marginBottom: 12 }}>原计算:{String(baselineDescriptions[metric])}</p>}{enabled && <><div className="structured-config-rule-grid"><div><label>公式</label><Input.TextArea rows={2} aria-label={`${metricLabel(metric)}公式`} value={String(rule.formula || '')} maxLength={maxFormulaLength} onChange={event => updateMetric({ formula: event.target.value })} placeholder="填写四则运算公式" /></div><div><label>空值策略</label><Select style={{ width: '100%' }} aria-label={`${metricLabel(metric)}空值策略`} options={nullOptions} value={String(rule.nullPolicy || 'PROPAGATE')} onChange={nullPolicy => updateMetric({ nullPolicy })} /></div><div><label>零分母策略</label><Select style={{ width: '100%' }} aria-label={`${metricLabel(metric)}零分母策略`} options={zeroOptions} value={String(rule.zeroDenominatorPolicy || 'ONE')} onChange={zeroDenominatorPolicy => updateMetric({ zeroDenominatorPolicy })} /></div>{nullResultOptions.length > 0 && <div><label>计算结果为空时</label><Select style={{ width: '100%' }} aria-label={`${metricLabel(metric)}空结果策略`} options={nullResultOptions} value={String(rule.nullResultPolicy || 'NULL')} onChange={nullResultPolicy => updateMetric({ nullResultPolicy })} /></div>}</div><p className="structured-config-note">可用变量:{[...metricVariables, ...metricCodes.slice(0, index)].join('、')}</p></>}</div>;
|
||||
})}</div> },
|
||||
]} />
|
||||
<Modal className="management-modal structured-config-modal" open={editing !== null} title={editing !== null && editing < rowRules.length ? '编辑行公式' : '新增行公式'} width={780} okText="写入草稿" onCancel={() => setEditing(null)} onOk={() => { void form.validateFields().then(formValue => {
|
||||
const rule: RuleRow = { stage: formValue.stage, target: formValue.target, formula: formValue.formula.trim(), nullPolicy: formValue.nullPolicy, zeroDenominatorPolicy: formValue.zeroDenominatorPolicy, ...(nullResultOptions.length ? { nullResultPolicy: formValue.nullResultPolicy } : {}) };
|
||||
if (formValue.conditional) {
|
||||
const when: RuleRow = { field: formValue.conditionField, operator: formValue.conditionOperator };
|
||||
if (!['IS_BLANK', 'IS_NOT_BLANK'].includes(formValue.conditionOperator)) { if (!formValue.conditionValue?.trim()) { setRuleError('请填写触发条件值'); return; } when.value = formValue.conditionValue; }
|
||||
rule.when = when; if (formValue.otherwiseFormula?.trim()) rule.otherwiseFormula = formValue.otherwiseFormula.trim();
|
||||
}
|
||||
const next = [...rowRules]; if (editing === null) return; next[editing] = rule; replaceRules(next); setEditing(null);
|
||||
}).catch(() => undefined); }}>
|
||||
<Form form={form} layout="vertical"><div className="structured-config-form-grid"><Form.Item name="stage" label="阶段" rules={[{ required: true }]}><Select options={[{ value: 'black', label: '黑片' }, { value: 'bright', label: '亮片' }]} onChange={stage => form.setFieldsValue({ target: stringList(targets[stage])[0], conditionField: Object.keys(objectValue(fields[stage]))[0] })} /></Form.Item><Form.Item name="target" label="计算结果" rules={[{ required: true, message: '请选择计算结果' }]}><Select {...readableSelectPopup} options={stringList(targets[selectedStage]).map(target => ({ value: target, label: `${targetLabel(target)} · ${target}` }))} /></Form.Item></div><Form.Item name="formula" label="公式" rules={[{ required: true, whitespace: true, message: '请填写公式' }]}><Input.TextArea rows={2} maxLength={maxFormulaLength} spellCheck={false} /></Form.Item><p className="structured-config-note" style={{ marginBottom: 14 }}>允许四则运算、括号及 SUM 求和(忽略空项,全部为空则为空)。可用别名与结果:{[...Object.keys(objectValue(fields[selectedStage])).filter(alias => !['issueLocation', 'inspectionNote', 'applicability'].includes(alias)), ...stringList(targets[selectedStage])].join('、')}</p><div className="structured-config-form-grid"><Form.Item name="nullPolicy" label="空值策略"><Select options={nullOptions} /></Form.Item><Form.Item name="zeroDenominatorPolicy" label="零分母策略"><Select options={zeroOptions} /></Form.Item>{nullResultOptions.length > 0 && <Form.Item name="nullResultPolicy" label="计算结果为空时"><Select options={nullResultOptions} /></Form.Item>}</div><Form.Item name="conditional" valuePropName="checked"><Checkbox>仅在符合条件时执行</Checkbox></Form.Item>{conditional && <><div className="structured-config-form-grid"><Form.Item name="conditionField" label="条件字段" rules={[{ required: true }]}><Select {...readableSelectPopup} options={Object.entries(objectValue(fields[selectedStage])).map(([alias, header]) => ({ value: alias, label: String(header) }))} /></Form.Item><Form.Item name="conditionOperator" label="判断方式" rules={[{ required: true }]}><Select options={stringList(schema.conditionOperators).map(operator => ({ value: operator, label: operatorLabels[operator] || operator }))} /></Form.Item></div>{!['IS_BLANK', 'IS_NOT_BLANK'].includes(conditionOperator) && <Form.Item name="conditionValue" label="条件值"><Input /></Form.Item>}<Form.Item name="otherwiseFormula" label="不符合条件时的公式(留空保留原结果)"><Input.TextArea rows={2} maxLength={maxFormulaLength} /></Form.Item></>}</Form>{ruleError && <Alert showIcon type="error" message={ruleError} />}
|
||||
</Modal>
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
.management-page.analysis-simple-page{gap:12px}
|
||||
.analysis-simple-page .analysis-workspace{height:calc(100dvh - 105px);min-height:540px;grid-template-columns:205px minmax(0,1fr)}
|
||||
.page-heading.page-actions-only{min-height:0;margin:0;justify-content:flex-end}
|
||||
.analysis-composer-buttons{display:flex;align-items:center;gap:8px}
|
||||
.analysis-simple-page .analysis-chat-panel{min-height:0;overflow:hidden;background:#fff}
|
||||
.analysis-simple-page .analysis-session-panel{min-height:0;overflow:hidden}
|
||||
.analysis-simple-page .analysis-session-list{flex:1;overflow:auto}
|
||||
.analysis-simple-page .analysis-session-item{padding:14px 12px;gap:5px}
|
||||
.analysis-simple-page .analysis-session-item small{font-size:11px}
|
||||
.analysis-simple-page .analysis-conversation{min-height:0;gap:26px;padding:30px max(24px,calc((100% - 850px)/2));scroll-behavior:smooth;overscroll-behavior:contain}
|
||||
.analysis-simple-page .analysis-turn{gap:16px}
|
||||
.analysis-simple-page .analysis-question{width:auto;max-width:85%;padding:10px 16px;border:0;border-radius:12px;background:#eef2fa}
|
||||
.analysis-simple-page .analysis-question p{margin:0;font-size:14px}
|
||||
.analysis-simple-page .analysis-answer{padding:0;border:0;background:transparent}
|
||||
.analysis-simple-page .ai-answer{font-size:14px;line-height:1.95;padding:0;white-space:normal;overflow-wrap:anywhere;word-break:break-word}
|
||||
.analysis-simple-page .ai-answer p{margin:0 0 10px;white-space:normal}
|
||||
.analysis-simple-page .ai-answer h1,.analysis-simple-page .ai-answer h2,.analysis-simple-page .ai-answer h3,.analysis-simple-page .ai-answer h4,.analysis-simple-page .ai-answer h5,.analysis-simple-page .ai-answer h6{margin:18px 0 8px;color:#263c5a;line-height:1.5}
|
||||
.analysis-simple-page .ai-answer h1{font-size:20px}.analysis-simple-page .ai-answer h2{font-size:18px}.analysis-simple-page .ai-answer h3{font-size:16px}.analysis-simple-page .ai-answer h4,.analysis-simple-page .ai-answer h5,.analysis-simple-page .ai-answer h6{font-size:14px}
|
||||
.analysis-simple-page .ai-answer ul,.analysis-simple-page .ai-answer ol{padding-left:24px;margin:4px 0 12px}
|
||||
.analysis-simple-page .ai-answer li{padding-left:2px;margin:3px 0;overflow-wrap:anywhere}
|
||||
.ai-markdown code{padding:1px 4px;border-radius:3px;background:#f0f3f7;font:0.92em ui-monospace,SFMono-Regular,Menlo,monospace;overflow-wrap:anywhere}
|
||||
.ai-markdown pre{max-width:100%;overflow:auto;padding:12px;background:#f4f6f9;border:1px solid #e5eaf0;white-space:pre-wrap;overflow-wrap:anywhere}
|
||||
.ai-markdown pre code{padding:0;background:transparent;white-space:pre-wrap}
|
||||
.ai-markdown-table-wrap{max-width:100%;margin:10px 0 14px;overflow:auto}
|
||||
.ai-markdown table{width:100%;border-collapse:collapse;table-layout:fixed;font-size:13px;line-height:1.65}
|
||||
.ai-markdown th,.ai-markdown td{padding:7px 9px;border:1px solid #dfe5ed;text-align:left;vertical-align:top;overflow-wrap:anywhere;word-break:break-word}
|
||||
.ai-markdown th{background:#f4f6f9;font-weight:650}
|
||||
.analysis-simple-page .analysis-message-actions{display:flex;gap:6px;margin-top:10px}
|
||||
.analysis-simple-page .analysis-message-actions .ant-btn{color:#627189}
|
||||
.analysis-simple-page .analysis-chat-notice{font-size:12px;color:#93671e}
|
||||
.analysis-simple-page .analysis-progress{background:transparent;padding:0;gap:10px;color:#63718a}
|
||||
.analysis-simple-page .analysis-composer{padding:16px max(24px,calc((100% - 850px)/2));border-top:0;gap:7px}
|
||||
.analysis-simple-page .analysis-composer textarea{font-size:14px;padding:13px 15px;border-radius:10px!important;resize:none}
|
||||
.analysis-simple-page .ai-actions{font-size:11px;color:#7a8598}
|
||||
.analysis-simple-page .analysis-empty{gap:10px}
|
||||
.analysis-simple-page .analysis-empty strong{font-size:20px;color:#3c4d67;font-weight:550}
|
||||
.analysis-simple-page .analysis-empty span{font-size:13px;color:#7b8799}
|
||||
.analysis-report-preview{max-height:65dvh;overflow:auto;background:#edf1f5;border:1px solid #e6ebf2}
|
||||
.analysis-report-preview .q-report{margin:auto}
|
||||
.analysis-report-preview .native-analysis-report-frame{display:block;width:900px;max-width:none;margin:0 auto;border:0;background:#fff}
|
||||
.analysis-report-preview .native-analysis-report{box-sizing:border-box;width:900px;margin:0 auto;padding:48px;background:#fff;color:#263346;font:15px/1.85 -apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;overflow-wrap:anywhere;word-break:break-word}
|
||||
.native-analysis-report .ai-markdown h1,.native-analysis-report .ai-markdown h2,.native-analysis-report .ai-markdown h3,.native-analysis-report .ai-markdown h4,.native-analysis-report .ai-markdown h5,.native-analysis-report .ai-markdown h6{color:#253a58;line-height:1.5}
|
||||
.native-analysis-report .ai-markdown h1{font-size:28px;margin:0 0 22px;padding-bottom:14px;border-bottom:2px solid #355f9b}
|
||||
.native-analysis-report .ai-markdown h2{font-size:21px;margin:28px 0 12px}
|
||||
.native-analysis-report .ai-markdown h3{font-size:17px;margin:22px 0 9px}
|
||||
.native-analysis-report .ai-markdown p{margin:10px 0}
|
||||
.native-analysis-report .ai-markdown li{margin:4px 0}
|
||||
.native-analysis-report .ai-markdown table{font-size:13px}
|
||||
.native-analysis-report .ai-markdown th,.native-analysis-report .ai-markdown td{padding:9px 10px}
|
||||
.native-analysis-report .ai-markdown th{background:#edf3fa}
|
||||
.native-analysis-report .ai-markdown pre{white-space:pre-wrap}
|
||||
@media(max-width:1000px){.analysis-simple-page .analysis-workspace{grid-template-columns:170px minmax(0,1fr)}.analysis-simple-page .analysis-conversation,.analysis-simple-page .analysis-composer{padding-left:20px;padding-right:20px}}
|
||||
@media(max-width:700px){.analysis-simple-page .analysis-workspace{grid-template-columns:1fr;height:calc(100dvh - 105px);min-height:480px}.analysis-simple-page .analysis-session-panel{max-height:100px}.analysis-simple-page .analysis-session-heading{min-height:36px}.analysis-simple-page .analysis-session-list{display:flex;overflow-x:auto}.analysis-simple-page .analysis-session-row{min-width:160px}.analysis-simple-page .analysis-session-item{padding:8px}.analysis-simple-page .analysis-session-item small{display:none}.analysis-simple-page .analysis-conversation{padding:18px 14px}.analysis-simple-page .analysis-composer{padding:12px 14px}.analysis-simple-page .analysis-question{max-width:92%}}
|
||||
@media(prefers-reduced-motion:reduce){.analysis-simple-page .analysis-conversation{scroll-behavior:auto}}
|
||||
@@ -0,0 +1,91 @@
|
||||
const RELEASE_UUID = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}';
|
||||
const RELEASE_ID = 'release[_ -]?id';
|
||||
const CANDIDATE = '候选[ \\t]+\\d{8}-\\d{6}(?:[ \\t]*[,,][ \\t]*ACTIVE)?';
|
||||
const STORY_SLUG = 'auto-quality-\\d{4}-\\d{2}-[a-z0-9-]+';
|
||||
|
||||
type TextRange = { start: number; end: number };
|
||||
|
||||
/** Only match data-release locking language; product/process versions are business facts. */
|
||||
const INTERNAL_DATA_LOCK_PATTERNS = [
|
||||
new RegExp(
|
||||
`(?:本轮|本次)(?:质量数据|查询数据|数据)(?:口径)?\\s*(?:将\\s*)?(?:固定使用|锁定使用|固定|锁定)(?:\\s*同一)?\\s*(?:发布|数据)?版本\\s*(?:[::=]\\s*)?(?:\\x60?${RELEASE_ID}\\s*[:=:]?\\s*)?(?:\\x60?${RELEASE_UUID}\\x60?)?(?:\\s*[,,;;]\\s*该版本(?:下)?[^。!?\\n]*)?`,
|
||||
'gi',
|
||||
),
|
||||
/(?:本轮|本次|当前)?(?:质量数据|数据|发布)版本\s*(?:已\s*)?(?:固定|锁定)(?:\s*[,,;;]\s*[^。!?\n]{0,30}?(?:不能|不可|不得)\s*(?:切换|更换)(?:发布|数据)?版本)?/gi,
|
||||
/(?:数据|发布|质量数据)(?:版本|口径)[^。!?\n]{0,30}(?:不能|不可|不得)\s*(?:切换|更换)(?:数据|发布)?版本/gi,
|
||||
];
|
||||
|
||||
/** Metadata-only deletions. UUIDs and version numbers are never removed without these labels. */
|
||||
const DISPLAY_METADATA_PATTERNS = [
|
||||
// A release label and its UUID can be split across <strong> and text nodes in old HTML.
|
||||
new RegExp(
|
||||
`(?:^|[ \\t |,,;;])(?:\\*{0,2})(?:发布版本|数据版本|固定版本)(?:\\*{0,2})[ \\t]*[::=][ \\t]*(?:${RELEASE_ID}[ \\t]*[:=:]?[ \\t]*)?${RELEASE_UUID}(?:[ \\t]*[((][ \\t]*${CANDIDATE}[ \\t]*[))])?`,
|
||||
'gim',
|
||||
),
|
||||
new RegExp(
|
||||
`(?:^|[ \\t ,,;;])同一[ \\t]*(?:发布版本|数据版本)[ \\t]*[((][ \\t]*${RELEASE_ID}[ \\t]*[:=:]?[ \\t]*${RELEASE_UUID}(?:[ \\t]*[,,][ \\t]*${CANDIDATE})?[ \\t]*[))]`,
|
||||
'gi',
|
||||
),
|
||||
new RegExp(`(?:^|[ \\t ,,;;])${RELEASE_ID}[ \\t]*[:=:]?[ \\t]*${RELEASE_UUID}`, 'gi'),
|
||||
new RegExp(`[((][ \\t]*${CANDIDATE}[ \\t]*[))]|(?:^|[ \\t ,,;;])${CANDIDATE}`, 'gi'),
|
||||
new RegExp(`[((][ \\t]*\\x60?${STORY_SLUG}\\x60?(?:[ \\t]*[,,;;/][ \\t]*version[ \\t]*(?:id|no\\.?|number)?[ \\t]*[:=:]?[ \\t]*\\d+(?:\\.\\d+)*)?[ \\t]*[))]`, 'gi'),
|
||||
new RegExp(`(?:^|[ \\t ,,;;])Story[ \\t]*(?:ID|slug|version)(?:[ \\t]*[/,][ \\t]*(?:ID|slug|version))*[ \\t]*[:=:]?[ \\t]*[A-Za-z0-9][A-Za-z0-9._:/-]*`, 'gi'),
|
||||
new RegExp(`(?:^|[ \\t ,,;;])${STORY_SLUG}`, 'gi'),
|
||||
/数据目录与发布版本/gi,
|
||||
/[((]\s*(?:\*{2}\s*)?v\d+(?:\.\d+)*\s*复核版(?:\s*\*{2})?\s*[))]|(?:\*{2}\s*)?v\d+(?:\.\d+)*\s*复核版(?:\s*\*{2})?/gi,
|
||||
/^[ \t]*>[ \t]*v\d+(?:\.\d+)*\s*复核说明\s*[::]?[^\n]*$/gim,
|
||||
];
|
||||
|
||||
function rangesForPattern(value: string, pattern: RegExp): TextRange[] {
|
||||
const ranges: TextRange[] = [];
|
||||
pattern.lastIndex = 0;
|
||||
let match: RegExpExecArray | null;
|
||||
while ((match = pattern.exec(value))) {
|
||||
if (match[0].length) ranges.push({ start: match.index, end: match.index + match[0].length });
|
||||
else pattern.lastIndex += 1;
|
||||
}
|
||||
return ranges;
|
||||
}
|
||||
|
||||
/** Ranges shared by the text and HTML renderers, so split inline tags cannot leak a label's value. */
|
||||
export function analysisDisplayTextRemovalRanges(value: string): TextRange[] {
|
||||
const ranges = [
|
||||
...INTERNAL_DATA_LOCK_PATTERNS.flatMap(pattern => rangesForPattern(value, pattern)),
|
||||
...DISPLAY_METADATA_PATTERNS.flatMap(pattern => rangesForPattern(value, pattern)),
|
||||
].sort((left, right) => left.start - right.start || right.end - left.end);
|
||||
|
||||
const merged: TextRange[] = [];
|
||||
for (const range of ranges) {
|
||||
const previous = merged.at(-1);
|
||||
if (previous && range.start <= previous.end) previous.end = Math.max(previous.end, range.end);
|
||||
else merged.push({ ...range });
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
function deleteRanges(value: string, ranges: TextRange[]): string {
|
||||
let cleaned = value;
|
||||
for (const range of [...ranges].reverse()) cleaned = cleaned.slice(0, range.start) + cleaned.slice(range.end);
|
||||
return cleaned;
|
||||
}
|
||||
|
||||
/** Remove internal release/story metadata while preserving business versions, values, and evidence IDs. */
|
||||
export function sanitizeAnalysisDisplayText(value: string): string {
|
||||
// Keep the useful status phrase while hiding the report's internal revision tag.
|
||||
const withoutRevisionPhrase = value.replace(
|
||||
/报告已更新为\s*(?:\*{1,2})?v\d+(?:\.\d+)*\s*复核版(?:\*{1,2})?/gi,
|
||||
'报告已更新',
|
||||
);
|
||||
let cleaned = deleteRanges(withoutRevisionPhrase, analysisDisplayTextRemovalRanges(withoutRevisionPhrase));
|
||||
|
||||
// Clean only punctuation made redundant by a removed metadata field. Do not trim leading colons:
|
||||
// HTML commonly stores a bold label and its business value in separate text nodes.
|
||||
return cleaned
|
||||
.replace(/[((]\s*[`*_~,,;;::/|\-–—\s]*[))]/g, '')
|
||||
.replace(/[,,;;::]{2,}/g, marks => marks.includes(':') || marks.includes(':') ? ':' : ';')
|
||||
.replace(/([。!?!?])\1+/g, '$1')
|
||||
.replace(/[ \t]{2,}/g, ' ')
|
||||
.replace(/[,,;;::][ \t]*[。!?!?]/g, match => match.trim().at(-1) || '')
|
||||
.replace(/\n{3,}/g, '\n\n')
|
||||
.replace(/^\n+|\n+$/g, '');
|
||||
}
|
||||
+707
@@ -0,0 +1,707 @@
|
||||
import { publicErrorMessage } from './publicDataDisplay';
|
||||
import type {
|
||||
AuthUser,
|
||||
Collection,
|
||||
FineDefectTopResponse,
|
||||
MetricsResponse,
|
||||
OptionsResponse,
|
||||
QueryParams,
|
||||
RecordExportParams,
|
||||
RecordsParams,
|
||||
RecordsResponse,
|
||||
} from './types';
|
||||
import type { ConfigureSourceBody, DataStage, DataWorkflowOperation, DataWorkflowStatus, MasterWorkbookImportBody, MasterWorkbookPreview, SourceDeletionPreview, SourceUploadOptions, WorkbookPreview } from './NoCodeDataTypes';
|
||||
|
||||
export class ApiError extends Error {
|
||||
status: number;
|
||||
details: unknown;
|
||||
|
||||
constructor(status: number, message: string, details?: unknown) {
|
||||
super(publicErrorMessage(message));
|
||||
this.name = 'ApiError';
|
||||
this.status = status;
|
||||
this.details = details;
|
||||
}
|
||||
}
|
||||
|
||||
let csrfToken: string | undefined;
|
||||
|
||||
async function readResponse<T>(response: Response): Promise<T> {
|
||||
const raw = await response.text();
|
||||
let payload: unknown;
|
||||
if (raw) {
|
||||
try {
|
||||
payload = JSON.parse(raw) as unknown;
|
||||
} catch {
|
||||
payload = raw;
|
||||
}
|
||||
}
|
||||
if (!response.ok) {
|
||||
const body = payload && typeof payload === 'object' ? payload as Record<string, unknown> : undefined;
|
||||
// Spring ProblemDetail uses `detail`; older endpoints may use `message` or `error`.
|
||||
const message = typeof body?.detail === 'string'
|
||||
? body.detail
|
||||
: typeof body?.message === 'string'
|
||||
? body.message
|
||||
: typeof body?.error === 'string'
|
||||
? body.error
|
||||
: typeof payload === 'string' && payload.trim()
|
||||
? payload
|
||||
: `请求失败(${response.status})`;
|
||||
throw new ApiError(response.status, message, payload);
|
||||
}
|
||||
return payload as T;
|
||||
}
|
||||
|
||||
async function request<T>(path: string, init: RequestInit = {}): Promise<T> {
|
||||
const headers = new Headers(init.headers);
|
||||
if (init.body && !(init.body instanceof FormData) && !headers.has('Content-Type')) headers.set('Content-Type', 'application/json');
|
||||
const response = await fetch(path, {
|
||||
...init,
|
||||
headers,
|
||||
credentials: 'same-origin',
|
||||
cache: 'no-store',
|
||||
});
|
||||
return readResponse<T>(response);
|
||||
}
|
||||
|
||||
async function requestBlob(path: string, signal?: AbortSignal): Promise<{ blob: Blob; filename: string }> {
|
||||
const response = await fetch(path, { credentials: 'same-origin', cache: 'no-store', signal });
|
||||
if (!response.ok) {
|
||||
const raw = await response.text();
|
||||
let payload: unknown = raw;
|
||||
try { payload = raw ? JSON.parse(raw) as unknown : undefined; } catch { /* keep plain text */ }
|
||||
const body = payload && typeof payload === 'object' ? payload as Record<string, unknown> : undefined;
|
||||
const message = typeof body?.detail === 'string' ? body.detail : typeof body?.message === 'string' ? body.message : `下载失败(${response.status})`;
|
||||
throw new ApiError(response.status, message, payload);
|
||||
}
|
||||
const disposition = response.headers.get('Content-Disposition') || '';
|
||||
const encoded = disposition.match(/filename\*=UTF-8''([^;]+)/i)?.[1];
|
||||
const plain = disposition.match(/filename="?([^";]+)"?/i)?.[1];
|
||||
let filename = 'source-evidence.xlsx';
|
||||
try { filename = encoded ? decodeURIComponent(encoded) : plain || filename; } catch { filename = plain || filename; }
|
||||
return { blob: await response.blob(), filename };
|
||||
}
|
||||
|
||||
export interface StreamEvent {
|
||||
id?: string;
|
||||
event: string;
|
||||
data: unknown;
|
||||
}
|
||||
|
||||
async function readEventStream(path: string, options: { signal?: AbortSignal; lastEventId?: string; onEvent: (event: StreamEvent) => void }): Promise<void> {
|
||||
const headers = new Headers({ Accept: 'text/event-stream' });
|
||||
if (options.lastEventId) headers.set('Last-Event-ID', options.lastEventId);
|
||||
const response = await fetch(path, { headers, credentials: 'same-origin', cache: 'no-store', signal: options.signal });
|
||||
if (!response.ok) {
|
||||
const raw = await response.text();
|
||||
let payload: unknown = raw;
|
||||
try { payload = raw ? JSON.parse(raw) as unknown : undefined; } catch { /* keep plain text */ }
|
||||
const body = payload && typeof payload === 'object' ? payload as Record<string, unknown> : undefined;
|
||||
throw new ApiError(response.status, typeof body?.detail === 'string' ? body.detail : typeof body?.message === 'string' ? body.message : `事件流读取失败(${response.status})`, payload);
|
||||
}
|
||||
if (!response.body) throw new ApiError(response.status, '浏览器没有收到可读的分析事件流');
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = '';
|
||||
const dispatch = (frame: string) => {
|
||||
if (!frame || frame.startsWith(':')) return;
|
||||
let id: string | undefined;
|
||||
let event = 'message';
|
||||
const data: string[] = [];
|
||||
for (const line of frame.split(/\r?\n/)) {
|
||||
if (line.startsWith('id:')) id = line.slice(3).trim();
|
||||
else if (line.startsWith('event:')) event = line.slice(6).trim() || 'message';
|
||||
else if (line.startsWith('data:')) data.push(line.slice(5).replace(/^ /, ''));
|
||||
}
|
||||
if (data.length) {
|
||||
const raw = data.join('\n');
|
||||
let value: unknown = raw;
|
||||
try { value = JSON.parse(raw) as unknown; } catch { /* allow plain text event data */ }
|
||||
options.onEvent({ ...(id ? { id } : {}), event, data: value });
|
||||
}
|
||||
};
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
buffer += decoder.decode(value, { stream: !done });
|
||||
const frames = buffer.split(/\r?\n\r?\n/);
|
||||
buffer = frames.pop() || '';
|
||||
for (const frame of frames) dispatch(frame);
|
||||
if (done) break;
|
||||
}
|
||||
if (buffer.trim()) dispatch(buffer);
|
||||
}
|
||||
|
||||
export async function refreshCsrf(): Promise<string> {
|
||||
const result = await request<{ token: string }>('/api/auth/csrf');
|
||||
csrfToken = result.token;
|
||||
return csrfToken;
|
||||
}
|
||||
|
||||
async function mutate<T>(path: string, body?: unknown, method = 'POST'): Promise<T> {
|
||||
const token = csrfToken ?? await refreshCsrf();
|
||||
const headers = new Headers({ 'X-XSRF-TOKEN': token });
|
||||
return request<T>(path, {
|
||||
method,
|
||||
headers,
|
||||
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
||||
});
|
||||
}
|
||||
|
||||
async function queryPost<T>(path: string, body: unknown, signal?: AbortSignal): Promise<T> {
|
||||
const token = csrfToken ?? await refreshCsrf();
|
||||
return request<T>(path, { method: 'POST', headers: { 'X-XSRF-TOKEN': token }, body: JSON.stringify(body), signal });
|
||||
}
|
||||
|
||||
async function mutateForm<T>(path: string, body: FormData): Promise<T> {
|
||||
const token = csrfToken ?? await refreshCsrf();
|
||||
return request<T>(path, { method: 'POST', headers: { 'X-XSRF-TOKEN': token }, body });
|
||||
}
|
||||
|
||||
export const api = {
|
||||
refreshCsrf,
|
||||
async me(): Promise<AuthUser> {
|
||||
const result = await request<{ user: AuthUser }>('/api/auth/me');
|
||||
return result.user;
|
||||
},
|
||||
login(username: string, password: string) {
|
||||
return mutate<{ user: AuthUser }>('/api/auth/login', { username, password });
|
||||
},
|
||||
logout() {
|
||||
return mutate<void>('/api/auth/logout');
|
||||
},
|
||||
options() {
|
||||
return request<OptionsResponse>('/api/options');
|
||||
},
|
||||
referenceNames() {
|
||||
return request<Pick<OptionsResponse, 'departments' | 'groups' | 'products' | 'projectGroups' | 'groupDepartments'>>('/api/options/reference-names');
|
||||
},
|
||||
metrics(params: QueryParams, signal?: AbortSignal) {
|
||||
return request<MetricsResponse>(`/api/metrics?${toQuery(params)}`, { signal });
|
||||
},
|
||||
fineDefectTop(params: Record<string, unknown>, signal?: AbortSignal) {
|
||||
return queryPost<FineDefectTopResponse>('/api/analysis/defects', params, signal);
|
||||
},
|
||||
records(params: RecordsParams, signal?: AbortSignal) {
|
||||
return request<RecordsResponse>(`/api/records?${toQuery(params)}`, { signal });
|
||||
},
|
||||
exportRecords(params: RecordExportParams, signal?: AbortSignal) {
|
||||
return requestBlob(`/api/records/export?${toQuery(params)}`, signal);
|
||||
},
|
||||
sources() {
|
||||
return request<Collection<import('./types').SourceItem>>('/api/sources');
|
||||
},
|
||||
sourceDeletionPreview(id: string) {
|
||||
return request<SourceDeletionPreview>(`/api/sources/${encodeURIComponent(id)}/deletion-preview`);
|
||||
},
|
||||
deletedSources() {
|
||||
return request<{ items: SourceDeletionPreview[] }>('/api/sources/deleted');
|
||||
},
|
||||
deleteSource(id: string, body: { expectedCurrentReleaseId: string | null; expectedDeleteVersion: number; expectedRevisionId?: string; reason: string; idempotencyKey: string }) {
|
||||
return mutate<SourceDeletionPreview>(`/api/sources/${encodeURIComponent(id)}/delete`, body);
|
||||
},
|
||||
restoreSource(id: string, body: { expectedCurrentReleaseId: string | null; expectedDeleteVersion: number; reason: string }) {
|
||||
return mutate<SourceDeletionPreview>(`/api/sources/${encodeURIComponent(id)}/restore`, body);
|
||||
},
|
||||
scanSources() {
|
||||
return mutate<{ items: import('./types').SourceItem[]; scannedAt: string }>('/api/sources/scan');
|
||||
},
|
||||
uploadSource(file: File) {
|
||||
const body = new FormData();
|
||||
body.append('file', file);
|
||||
return mutateForm<{ source: import('./types').SourceItem }>('/api/sources/upload', body);
|
||||
},
|
||||
sourceUploadOptions() {
|
||||
return request<SourceUploadOptions>('/api/sources/upload-options');
|
||||
},
|
||||
previewSourceWorkbook(file: File) {
|
||||
const body = new FormData(); body.append('file', file);
|
||||
return mutateForm<WorkbookPreview>('/api/sources/workbook-preview', body);
|
||||
},
|
||||
sourceWorkbookPreview(uploadId: string, params: { sheetName: string; headerRow: number; stage: DataStage }) {
|
||||
return request<WorkbookPreview>(`/api/sources/workbook-preview/${encodeURIComponent(uploadId)}?${toQuery(params)}`);
|
||||
},
|
||||
configureSourceWorkbook(body: ConfigureSourceBody) {
|
||||
return mutate<{ source: import('./types').SourceItem; configuration: Record<string, unknown>; currentReleaseId: string | null }>('/api/sources/configure', body);
|
||||
},
|
||||
previewMasterWorkbook(file: File) {
|
||||
const body = new FormData(); body.append('file', file);
|
||||
return mutateForm<MasterWorkbookPreview>('/api/master-data/workbooks/preview', body);
|
||||
},
|
||||
importMasterWorkbook(body: MasterWorkbookImportBody) {
|
||||
return mutate<Record<string, unknown>>('/api/master-data/workbooks/import', body);
|
||||
},
|
||||
prepareMasterWorkbook(body: MasterWorkbookImportBody) {
|
||||
return mutate<Record<string, unknown>>('/api/master-data/workbooks/prepare', body);
|
||||
},
|
||||
startImport(body: { sourceIds: string[]; idempotencyKey: string; expectedCurrentReleaseId: string | null }) {
|
||||
return mutate<unknown>('/api/import-runs', body);
|
||||
},
|
||||
importRun(id: string) {
|
||||
return request<{ run: Record<string, unknown> }>(`/api/import-runs/${encodeURIComponent(id)}`);
|
||||
},
|
||||
importIssues(id: string, page = 1, pageSize = 50) {
|
||||
return request<Collection>(`/api/import-runs/${encodeURIComponent(id)}/issues?page=${page}&pageSize=${pageSize}`);
|
||||
},
|
||||
mappingIssues(params: { importRunId?: string; status?: string; page?: number; pageSize?: number } = {}) {
|
||||
return request<Collection>(`/api/governance/mapping-issues?${toQuery({ page: 1, pageSize: 50, ...params })}`);
|
||||
},
|
||||
mappingIssue(id: string) {
|
||||
return request<Record<string, unknown>>(`/api/governance/mapping-issues/${encodeURIComponent(id)}`);
|
||||
},
|
||||
resolveMappingIssue(id: string, body: Record<string, unknown>) {
|
||||
return mutate<Record<string, unknown>>(`/api/governance/mapping-issues/${encodeURIComponent(id)}/resolve`, body);
|
||||
},
|
||||
revalidateMappingIssue(id: string, body: { decisionId: string; expectedCurrentReleaseId: string | null; idempotencyKey: string }) {
|
||||
return mutate<Record<string, unknown>>(`/api/governance/mapping-issues/${encodeURIComponent(id)}/revalidate`, body);
|
||||
},
|
||||
tasks() {
|
||||
return request<Collection>('/api/tasks');
|
||||
},
|
||||
retryTask(id: string, body: { idempotencyKey: string; expectedCurrentReleaseId: string | null }) {
|
||||
return mutate<unknown>(`/api/tasks/${encodeURIComponent(id)}/retry`, body);
|
||||
},
|
||||
cancelTask(id: string, body: { expectedStatus: string }) {
|
||||
return mutate<unknown>(`/api/tasks/${encodeURIComponent(id)}/cancel`, body);
|
||||
},
|
||||
releases() {
|
||||
return request<Collection>('/api/releases');
|
||||
},
|
||||
publishRelease(id: string, body: ReleaseActionBody) {
|
||||
return mutate<unknown>(`/api/releases/${encodeURIComponent(id)}/publish`, body);
|
||||
},
|
||||
rules() {
|
||||
return request<Collection>('/api/rules');
|
||||
},
|
||||
ruleSchema() {
|
||||
return request<Record<string, unknown>>('/api/rules/schema');
|
||||
},
|
||||
createRule(body: Record<string, unknown>) {
|
||||
return mutate<unknown>('/api/rules', body);
|
||||
},
|
||||
updateRule(id: string, body: Record<string, unknown>) {
|
||||
return mutate<unknown>(`/api/rules/${encodeURIComponent(id)}`, body, 'PUT');
|
||||
},
|
||||
validateRule(id: string, body: { expectedRowVersion: number }) {
|
||||
return mutate<unknown>(`/api/rules/${encodeURIComponent(id)}/validate`, body);
|
||||
},
|
||||
ruleRegressions(id: string) {
|
||||
return request<{ items: Record<string, unknown>[] }>(`/api/governance/rules/${encodeURIComponent(id)}/regressions`);
|
||||
},
|
||||
ruleRegression(id: string) {
|
||||
return request<Record<string, unknown>>(`/api/governance/rule-regressions/${encodeURIComponent(id)}`);
|
||||
},
|
||||
activateRule(id: string, body: { expectedRowVersion: number; confirmDifferences?: boolean; regressionRunId?: string }) {
|
||||
return mutate<unknown>(`/api/rules/${encodeURIComponent(id)}/activate`, body);
|
||||
},
|
||||
metricDictionary() {
|
||||
return request<{ items: Record<string, unknown>[] }>('/api/metric-dictionary');
|
||||
},
|
||||
metricDictionaryMigration() {
|
||||
return request<{ items: Record<string, unknown>[]; verification?: Record<string, unknown> }>('/api/metric-dictionary/migration');
|
||||
},
|
||||
updateMetricDictionary(code: string, body: Record<string, unknown>) {
|
||||
return mutate<Record<string, unknown>>(`/api/metric-dictionary/${encodeURIComponent(code)}`, body, 'PUT');
|
||||
},
|
||||
mappings() {
|
||||
return request<Collection>('/api/mappings');
|
||||
},
|
||||
createMapping(body: Record<string, unknown>) {
|
||||
return mutate<unknown>('/api/mappings', body);
|
||||
},
|
||||
updateMapping(id: string, body: Record<string, unknown>) {
|
||||
return mutate<unknown>(`/api/mappings/${encodeURIComponent(id)}`, body, 'PUT');
|
||||
},
|
||||
validateMapping(id: string, body: { expectedRowVersion: number }) {
|
||||
return mutate<unknown>(`/api/mappings/${encodeURIComponent(id)}/validate`, body);
|
||||
},
|
||||
activateMapping(id: string, body: { expectedRowVersion: number }) {
|
||||
return mutate<unknown>(`/api/mappings/${encodeURIComponent(id)}/activate`, body);
|
||||
},
|
||||
dataWorkflowStatus() {
|
||||
return request<DataWorkflowStatus>('/api/data-workflow/status');
|
||||
},
|
||||
applyDataWorkflow(body: { kind: 'mapping' | 'rule'; name: string; definition: Record<string, unknown>; description?: string; expectedCurrentReleaseId: string | null }) {
|
||||
const matchRules = body.definition.matchRules;
|
||||
const definition = Array.isArray(matchRules) ? {
|
||||
...body.definition,
|
||||
matchRules: matchRules.map(rule => {
|
||||
if (!rule || typeof rule !== 'object' || Array.isArray(rule)) return rule;
|
||||
const row = rule as Record<string, unknown>;
|
||||
if (!Array.isArray(row.conditions)) return row;
|
||||
return {
|
||||
...row,
|
||||
conditions: row.conditions.map(condition => {
|
||||
if (!condition || typeof condition !== 'object' || Array.isArray(condition)) return condition;
|
||||
const item = condition as Record<string, unknown>;
|
||||
return ['IS_BLANK', 'IS_NOT_BLANK'].includes(String(item.operator)) ? { ...item, value: '' } : item;
|
||||
}),
|
||||
};
|
||||
}),
|
||||
} : body.definition;
|
||||
return mutate<DataWorkflowOperation>('/api/data-workflow/apply', { ...body, definition });
|
||||
},
|
||||
recalculateDataWorkflow() {
|
||||
return mutate<DataWorkflowOperation>('/api/data-workflow/recalculate', {});
|
||||
},
|
||||
importDataWorkflow(body: { sourceIds: string[] }) {
|
||||
return mutate<DataWorkflowOperation>('/api/data-workflow/import', body);
|
||||
},
|
||||
deleteDataWorkflowSource(id: string) {
|
||||
return mutate<DataWorkflowOperation>(`/api/data-workflow/sources/${encodeURIComponent(id)}/delete`, {});
|
||||
},
|
||||
restoreDataWorkflowSource(id: string) {
|
||||
return mutate<DataWorkflowOperation>(`/api/data-workflow/sources/${encodeURIComponent(id)}/restore`, {});
|
||||
},
|
||||
dataWorkflowOperation(id: string) {
|
||||
return request<DataWorkflowOperation>(`/api/data-workflow/operations/${encodeURIComponent(id)}`);
|
||||
},
|
||||
audit(page = 1, pageSize = 50) {
|
||||
return request<Collection>(`/api/audit?page=${page}&pageSize=${pageSize}`);
|
||||
},
|
||||
users() {
|
||||
return request<Collection>('/api/users');
|
||||
},
|
||||
createUser(body: Record<string, unknown>) {
|
||||
return mutate<unknown>('/api/users', body);
|
||||
},
|
||||
updateUser(id: string, body: Record<string, unknown>) {
|
||||
return mutate<unknown>(`/api/users/${encodeURIComponent(id)}`, body, 'PUT');
|
||||
},
|
||||
analysis(body: { query: string; sessionId?: string; context?: Record<string, unknown> }) {
|
||||
return mutate<unknown>('/api/analysis', body);
|
||||
},
|
||||
analysisStatus() {
|
||||
return request<Record<string, unknown>>('/api/analysis/status');
|
||||
},
|
||||
analysisReports() { return request<{ items: Record<string, unknown>[] }>('/api/analysis/reports'); },
|
||||
createAnalysisReport(body: { periodType: string; periodKey: string }) {
|
||||
return mutate<{ report: Record<string, unknown>; turn: Record<string, unknown> }>('/api/analysis/reports', body);
|
||||
},
|
||||
analysisReportPlans() { return request<{ items: Record<string, unknown>[] }>('/api/analysis/report-plans'); },
|
||||
createAnalysisReportPlan(body: Record<string, unknown>) {
|
||||
return mutate<{ plan: Record<string, unknown> }>('/api/analysis/report-plans', body);
|
||||
},
|
||||
updateAnalysisReportPlan(id: string, body: Record<string, unknown>) {
|
||||
return mutate<{ plan: Record<string, unknown> }>(`/api/analysis/report-plans/${encodeURIComponent(id)}`, body, 'PUT');
|
||||
},
|
||||
analysisSessions() {
|
||||
return request<Collection<Record<string, unknown>>>('/api/analysis/sessions');
|
||||
},
|
||||
analysisSession(id: string) {
|
||||
return request<Record<string, unknown>>(`/api/analysis/sessions/${encodeURIComponent(id)}`);
|
||||
},
|
||||
deleteAnalysisSession(id: string) {
|
||||
return mutate<{ deleted: boolean; sessionId: string }>(`/api/analysis/sessions/${encodeURIComponent(id)}`, undefined, 'DELETE');
|
||||
},
|
||||
analysisSessionTurns(id: string) {
|
||||
return request<{ items: Record<string, unknown>[] }>(`/api/analysis/sessions/${encodeURIComponent(id)}/turns`);
|
||||
},
|
||||
createAnalysisSession(body: { title?: string; releaseId?: string; context?: Record<string, unknown> }) {
|
||||
return mutate<{ session: Record<string, unknown> }>('/api/analysis/sessions', body);
|
||||
},
|
||||
startAnalysisTurn(id: string, body: { question: string; context?: Record<string, unknown>; idempotencyKey?: string }) {
|
||||
return mutate<{ turn: Record<string, unknown> }>(`/api/analysis/sessions/${encodeURIComponent(id)}/turns`, body);
|
||||
},
|
||||
analysisTurn(id: string) {
|
||||
return request<Record<string, unknown>>(`/api/analysis/turns/${encodeURIComponent(id)}`);
|
||||
},
|
||||
analysisSettings() {
|
||||
return request<import('./AnalysisApiSettings').AnalysisModelSettings>('/api/analysis/settings');
|
||||
},
|
||||
saveAnalysisSettings(body: import('./AnalysisApiSettings').AnalysisModelSettingsInput) {
|
||||
return mutate<import('./AnalysisApiSettings').AnalysisModelSettings>('/api/analysis/settings', body, 'PUT');
|
||||
},
|
||||
testAnalysisSettings(body: import('./AnalysisApiSettings').AnalysisModelSettingsInput) {
|
||||
return mutate<{ success: boolean; message: string; elapsedMs?: number }>('/api/analysis/settings/test', body);
|
||||
},
|
||||
retryAnalysisTurn(id: string) {
|
||||
return mutate<{ turn: Record<string, unknown> }>(`/api/analysis/turns/${encodeURIComponent(id)}/retry`);
|
||||
},
|
||||
analysisTurnEvents(id: string, options: { signal?: AbortSignal; lastEventId?: string; onEvent: (event: StreamEvent) => void }) {
|
||||
return readEventStream(`/api/analysis/turns/${encodeURIComponent(id)}/events`, options);
|
||||
},
|
||||
cancelAnalysisTurn(id: string, reason?: string) {
|
||||
return mutate<Record<string, unknown>>(`/api/analysis/turns/${encodeURIComponent(id)}/cancel`, reason ? { reason } : {});
|
||||
},
|
||||
feedbackAnalysisTurn(id: string, body: { rating: string; comment?: string }) {
|
||||
return mutate<Record<string, unknown>>(`/api/analysis/turns/${encodeURIComponent(id)}/feedback`, body);
|
||||
},
|
||||
analyticsTop(params: Record<string, unknown>) {
|
||||
return request<Record<string, unknown>>(`/api/analytics/top?${toQuery(params)}`);
|
||||
},
|
||||
checklists() {
|
||||
return request<{ items: Record<string, unknown>[] }>('/api/analytics/checklists');
|
||||
},
|
||||
createChecklist(body: { title: string }) {
|
||||
return mutate<Record<string, unknown>>('/api/analytics/checklists', body);
|
||||
},
|
||||
checklist(id: string) {
|
||||
return request<Record<string, unknown>>(`/api/analytics/checklists/${encodeURIComponent(id)}`);
|
||||
},
|
||||
addChecklistItem(id: string, body: Record<string, unknown>) {
|
||||
return mutate<Record<string, unknown>>(`/api/analytics/checklists/${encodeURIComponent(id)}/items`, body);
|
||||
},
|
||||
deleteChecklistItem(id: string, itemId: string) {
|
||||
return mutate<void>(`/api/analytics/checklists/${encodeURIComponent(id)}/items/${encodeURIComponent(itemId)}`, undefined, 'DELETE');
|
||||
},
|
||||
analyticsCompare(body: Record<string, unknown>) {
|
||||
return mutate<Record<string, unknown>>('/api/analytics/compare', body);
|
||||
},
|
||||
analyticsImpact(body: Record<string, unknown>) {
|
||||
return mutate<Record<string, unknown>>('/api/analytics/impact', body);
|
||||
},
|
||||
structureDecomposition(body: Record<string, unknown>) {
|
||||
return mutate<Record<string, unknown>>('/api/analytics/structure-decomposition', body);
|
||||
},
|
||||
comparisonViews() {
|
||||
return request<{ items: Record<string, unknown>[] }>('/api/analytics/comparison-views');
|
||||
},
|
||||
sharedComparisonViews() {
|
||||
return request<{ items: Record<string, unknown>[] }>('/api/analytics/comparison-views/shared');
|
||||
},
|
||||
comparisonViewShareCandidates() {
|
||||
return request<{ items: Record<string, unknown>[] }>('/api/analytics/comparison-views/share-candidates');
|
||||
},
|
||||
comparisonViewShares(id: string) {
|
||||
return request<{ items: Record<string, unknown>[]; viewRowVersion: number }>(`/api/analytics/comparison-views/${encodeURIComponent(id)}/shares`);
|
||||
},
|
||||
shareComparisonView(id: string, body: { recipientUserId: string; expectedRowVersion: number }) {
|
||||
return mutate<Record<string, unknown>>(`/api/analytics/comparison-views/${encodeURIComponent(id)}/shares`, body);
|
||||
},
|
||||
revokeComparisonViewShare(id: string, recipientUserId: string, expectedRowVersion: number) {
|
||||
return mutate<Record<string, unknown>>(`/api/analytics/comparison-views/${encodeURIComponent(id)}/shares/${encodeURIComponent(recipientUserId)}?expectedRowVersion=${expectedRowVersion}`, undefined, 'DELETE');
|
||||
},
|
||||
createComparisonView(body: Record<string, unknown>) {
|
||||
return mutate<Record<string, unknown>>('/api/analytics/comparison-views', body);
|
||||
},
|
||||
updateComparisonView(id: string, body: Record<string, unknown>) {
|
||||
return mutate<Record<string, unknown>>(`/api/analytics/comparison-views/${encodeURIComponent(id)}`, body, 'PUT');
|
||||
},
|
||||
deleteComparisonView(id: string) {
|
||||
return mutate<void>(`/api/analytics/comparison-views/${encodeURIComponent(id)}`, undefined, 'DELETE');
|
||||
},
|
||||
openComparisonView(id: string) {
|
||||
return mutate<Record<string, unknown>>(`/api/analytics/comparison-views/${encodeURIComponent(id)}/open`, {});
|
||||
},
|
||||
analyticsTarget(params: Record<string, unknown>) {
|
||||
return request<Record<string, unknown>>(`/api/analytics/targets?${toQuery(params)}`);
|
||||
},
|
||||
targetVersions() {
|
||||
return request<{ items: Record<string, unknown>[]; currentVersionId?: string }>('/api/analytics/targets/versions');
|
||||
},
|
||||
targetVersion(id: string) {
|
||||
return request<Record<string, unknown>>(`/api/analytics/targets/versions/${encodeURIComponent(id)}`);
|
||||
},
|
||||
createTargetVersion(body: { name: string }) {
|
||||
return mutate<Record<string, unknown>>('/api/analytics/targets/versions', body);
|
||||
},
|
||||
updateTargetVersion(id: string, body: Record<string, unknown>) {
|
||||
return mutate<Record<string, unknown>>(`/api/analytics/targets/versions/${encodeURIComponent(id)}`, body, 'PUT');
|
||||
},
|
||||
updateCurrentTargets(body: Record<string, unknown>) {
|
||||
return mutate<Record<string, unknown>>('/api/analytics/targets/current', body, 'PUT');
|
||||
},
|
||||
validateTargetVersion(id: string, body: { expectedRowVersion: number }) {
|
||||
return mutate<Record<string, unknown>>(`/api/analytics/targets/versions/${encodeURIComponent(id)}/validate`, body);
|
||||
},
|
||||
activateTargetVersion(id: string, body: { expectedRowVersion: number }) {
|
||||
return mutate<Record<string, unknown>>(`/api/analytics/targets/versions/${encodeURIComponent(id)}/activate`, body);
|
||||
},
|
||||
governanceProtocols() {
|
||||
return request<{ items: Record<string, unknown>[] }>('/api/governance/protocols');
|
||||
},
|
||||
governanceSourceDocuments() {
|
||||
return request<{ items: Record<string, unknown>[]; revisions: Record<string, unknown>[] }>('/api/governance/source-documents');
|
||||
},
|
||||
createGovernanceProtocol(body: Record<string, unknown>) {
|
||||
return mutate<Record<string, unknown>>('/api/governance/protocols', body);
|
||||
},
|
||||
governanceCoverage(releaseId?: string) {
|
||||
const suffix = releaseId ? `?releaseId=${encodeURIComponent(releaseId)}` : '';
|
||||
return request<Record<string, unknown>>(`/api/governance/coverage${suffix}`);
|
||||
},
|
||||
governanceReleaseInspect(id: string) {
|
||||
return request<Record<string, unknown>>(`/api/governance/releases/${encodeURIComponent(id)}/inspect`);
|
||||
},
|
||||
governanceReleaseDiff(id: string, againstReleaseId: string) {
|
||||
return request<Record<string, unknown>>(`/api/governance/releases/${encodeURIComponent(id)}/diff?againstReleaseId=${encodeURIComponent(againstReleaseId)}`);
|
||||
},
|
||||
governanceReleaseReconciliations(id: string) {
|
||||
return request<{ items: Record<string, unknown>[]; acceptanceId?: string }>(`/api/governance/releases/${encodeURIComponent(id)}/reconciliations`);
|
||||
},
|
||||
createGovernanceReconciliation(id: string, body: Record<string, unknown>) {
|
||||
return mutate<Record<string, unknown>>(`/api/governance/releases/${encodeURIComponent(id)}/reconciliations`, body);
|
||||
},
|
||||
governanceReconciliation(id: string) {
|
||||
return request<Record<string, unknown>>(`/api/governance/reconciliations/${encodeURIComponent(id)}`);
|
||||
},
|
||||
confirmGovernanceReconciliation(id: string, body: { expectedRowVersion: number; expectedDifferenceHash: string; expectedTransitionDifferenceHash?: string; reason: string }) {
|
||||
return mutate<Record<string, unknown>>(`/api/governance/reconciliations/${encodeURIComponent(id)}/confirm`, body);
|
||||
},
|
||||
governanceDependencyImpact(kind: 'rule' | 'mapping', id: string) {
|
||||
return request<Record<string, unknown>>(`/api/governance/dependencies/${kind}/${encodeURIComponent(id)}/impact`);
|
||||
},
|
||||
costConfigurations() {
|
||||
return request<{ items: Record<string, unknown>[] }>('/api/governance/cost-configurations');
|
||||
},
|
||||
createCostConfiguration(body: Record<string, unknown>) {
|
||||
return mutate<Record<string, unknown>>('/api/governance/cost-configurations', body);
|
||||
},
|
||||
updateCostConfiguration(id: string, body: Record<string, unknown>) {
|
||||
return mutate<Record<string, unknown>>(`/api/governance/cost-configurations/${encodeURIComponent(id)}`, body, 'PUT');
|
||||
},
|
||||
validateCostConfiguration(id: string, body: { expectedRowVersion: number }) {
|
||||
return mutate<Record<string, unknown>>(`/api/governance/cost-configurations/${encodeURIComponent(id)}/validate`, body);
|
||||
},
|
||||
governanceBackups() {
|
||||
return request<Record<string, unknown>>('/api/governance/backups');
|
||||
},
|
||||
createBackupJob(body: Record<string, unknown>) {
|
||||
return mutate<Record<string, unknown>>('/api/governance/backups/jobs', body);
|
||||
},
|
||||
updateBackupPlan(body: Record<string, unknown>) {
|
||||
return mutate<Record<string, unknown>>('/api/governance/backups/plan', body, 'PUT');
|
||||
},
|
||||
resolveSourceCandidate(id: string, body: Record<string, unknown>) {
|
||||
return mutate<Record<string, unknown>>(`/api/governance/sources/${encodeURIComponent(id)}/resolve`, body);
|
||||
},
|
||||
sourceChanges() {
|
||||
return request<{ items: Record<string, unknown>[] }>('/api/governance/source-changes');
|
||||
},
|
||||
createSourceChange(body: Record<string, unknown>) {
|
||||
return mutate<Record<string, unknown>>('/api/governance/source-changes', body);
|
||||
},
|
||||
reviewSourceChange(id: string, body: Record<string, unknown>) {
|
||||
return mutate<Record<string, unknown>>(`/api/governance/source-changes/${encodeURIComponent(id)}/review`, body);
|
||||
},
|
||||
buildSourceChange(id: string, body: Record<string, unknown>) {
|
||||
return mutate<Record<string, unknown>>(`/api/governance/source-changes/${encodeURIComponent(id)}/build`, body);
|
||||
},
|
||||
governanceMonitor() {
|
||||
return request<Record<string, unknown>>('/api/governance/monitor');
|
||||
},
|
||||
inspectionStrategies() {
|
||||
return request<{ items: Record<string, unknown>[] }>('/api/analytics/inspection-strategies');
|
||||
},
|
||||
inspectionStrategy(id: string) {
|
||||
return request<Record<string, unknown>>(`/api/analytics/inspection-strategies/${encodeURIComponent(id)}`);
|
||||
},
|
||||
createInspectionStrategy(body: Record<string, unknown>) {
|
||||
return mutate<Record<string, unknown>>('/api/analytics/inspection-strategies', body);
|
||||
},
|
||||
updateInspectionStrategy(id: string, body: Record<string, unknown>) {
|
||||
return mutate<Record<string, unknown>>(`/api/analytics/inspection-strategies/${encodeURIComponent(id)}`, body, 'PUT');
|
||||
},
|
||||
inspectionRuns(releaseId?: string) {
|
||||
const query = releaseId ? `?releaseId=${encodeURIComponent(releaseId)}` : '';
|
||||
return request<{ items: Record<string, unknown>[]; resultAvailable?: boolean }>(`/api/analytics/inspection-runs${query}`);
|
||||
},
|
||||
runInspection(releaseId: string) {
|
||||
return mutate<{ items: Record<string, unknown>[]; resultAvailable?: boolean }>('/api/analytics/inspection-runs/run', { releaseId });
|
||||
},
|
||||
refreshGovernanceMonitor() {
|
||||
return mutate<Record<string, unknown>>('/api/governance/monitor/refresh', {});
|
||||
},
|
||||
governanceAlertPolicy() {
|
||||
return request<Record<string, unknown>>('/api/governance/monitor/alert-policy');
|
||||
},
|
||||
updateGovernanceAlertPolicy(body: Record<string, unknown>) {
|
||||
return mutate<Record<string, unknown>>('/api/governance/monitor/alert-policy', body, 'PUT');
|
||||
},
|
||||
serviceIdentities() {
|
||||
return request<{ items: Record<string, unknown>[]; allowedActions?: string[]; serviceTypes?: string[] }>('/api/governance/service-identities');
|
||||
},
|
||||
createServiceIdentity(body: Record<string, unknown>) {
|
||||
return mutate<Record<string, unknown>>('/api/governance/service-identities', body);
|
||||
},
|
||||
updateServiceIdentity(id: string, body: Record<string, unknown>) {
|
||||
return mutate<Record<string, unknown>>(`/api/governance/service-identities/${encodeURIComponent(id)}`, body, 'PUT');
|
||||
},
|
||||
rotateServiceIdentity(id: string, body: Record<string, unknown>) {
|
||||
return mutate<Record<string, unknown>>(`/api/governance/service-identities/${encodeURIComponent(id)}/rotate`, body);
|
||||
},
|
||||
userAccessPolicy(id: string) {
|
||||
return request<Record<string, unknown>>(`/api/governance/users/${encodeURIComponent(id)}/access-policy`);
|
||||
},
|
||||
updateUserAccessPolicy(id: string, body: Record<string, unknown>) {
|
||||
return mutate<Record<string, unknown>>(`/api/governance/users/${encodeURIComponent(id)}/access-policy`, body, 'PUT');
|
||||
},
|
||||
effectiveUserAccess(id: string) {
|
||||
return request<Record<string, unknown>>(`/api/governance/users/${encodeURIComponent(id)}/effective-access`);
|
||||
},
|
||||
userScopePreview(id: string) {
|
||||
return request<Record<string, unknown>>(`/api/governance/users/${encodeURIComponent(id)}/scope-preview`);
|
||||
},
|
||||
downloadSourceRevision(id: string, signal?: AbortSignal) {
|
||||
return requestBlob(`/api/governance/source-revisions/${encodeURIComponent(id)}/download`, signal);
|
||||
},
|
||||
sourceRevisionEvidence(id: string) {
|
||||
return request<Record<string, unknown>>(`/api/governance/source-revisions/${encodeURIComponent(id)}/evidence`);
|
||||
},
|
||||
serviceRotations(id: string) {
|
||||
return request<{ items: Record<string, unknown>[] }>(`/api/governance/service-identities/${encodeURIComponent(id)}/rotations`);
|
||||
},
|
||||
authorizeServiceAction(id: string, action: string) {
|
||||
return mutate<Record<string, unknown>>(`/api/governance/service-identities/${encodeURIComponent(id)}/authorize`, { action });
|
||||
},
|
||||
serviceBindings() {
|
||||
return request<{ items: Record<string, unknown>[] }>('/api/governance/service-bindings');
|
||||
},
|
||||
updateServiceBinding(type: string, body: { identityId: string; reason: string }) {
|
||||
return mutate<Record<string, unknown>>(`/api/governance/service-bindings/${encodeURIComponent(type)}`, body, 'PUT');
|
||||
},
|
||||
};
|
||||
|
||||
export interface ReleaseActionBody {
|
||||
expectedCurrentReleaseId: string | null;
|
||||
idempotencyKey: string;
|
||||
reason: string;
|
||||
}
|
||||
|
||||
function toQuery(values: object): string {
|
||||
const query = new URLSearchParams();
|
||||
for (const [key, value] of Object.entries(values)) {
|
||||
if (value === undefined || value === null || value === '') continue;
|
||||
if (Array.isArray(value)) value.forEach(item => {
|
||||
if (item !== undefined && item !== null && item !== '') query.append(key, String(item));
|
||||
});
|
||||
else query.set(key, String(value));
|
||||
}
|
||||
return query.toString();
|
||||
}
|
||||
|
||||
const MULTI_VALUE_MARKER = '~qv1~';
|
||||
|
||||
/** Encodes multiple selected values into the scalar query wire format understood by the API. */
|
||||
export function encodeQueryValueList(values: string[] | undefined): string | undefined {
|
||||
if (!values?.length) return undefined;
|
||||
const normalized = [...new Set(values.map(value => value.trim()).filter(Boolean))];
|
||||
if (normalized.length === 0) return undefined;
|
||||
if (normalized.length === 1) return normalized[0];
|
||||
const bytes = new TextEncoder().encode(JSON.stringify(normalized));
|
||||
let binary = '';
|
||||
bytes.forEach(byte => { binary += String.fromCharCode(byte); });
|
||||
return `${MULTI_VALUE_MARKER}${btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/g, '')}`;
|
||||
}
|
||||
|
||||
/** Reads a plain scalar or the versioned multi-value query wire format. */
|
||||
export function decodeQueryValueList(value: string | undefined): string[] {
|
||||
if (!value) return [];
|
||||
if (!value.startsWith(MULTI_VALUE_MARKER)) return [value];
|
||||
try {
|
||||
const encoded = value.slice(MULTI_VALUE_MARKER.length).replaceAll('-', '+').replaceAll('_', '/');
|
||||
const binary = atob(encoded.padEnd(Math.ceil(encoded.length / 4) * 4, '='));
|
||||
const bytes = Uint8Array.from(binary, character => character.charCodeAt(0));
|
||||
const parsed: unknown = JSON.parse(new TextDecoder().decode(bytes));
|
||||
return Array.isArray(parsed) ? [...new Set(parsed.filter(item => typeof item === 'string').map(item => item.trim()).filter(Boolean))] : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export function collectionItems<T>(value: Collection<T> | T[] | null | undefined): T[] {
|
||||
if (Array.isArray(value)) return value;
|
||||
if (value && Array.isArray(value.items)) return value.items;
|
||||
return [];
|
||||
}
|
||||
@@ -0,0 +1,798 @@
|
||||
.completion-insights,
|
||||
.completion-tools {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.completion-definition-list {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(105px, 150px) minmax(0, 1fr);
|
||||
margin: 0;
|
||||
border-top: 1px solid var(--line, #dce3ee);
|
||||
}
|
||||
|
||||
.completion-definition-list dt,
|
||||
.completion-definition-list dd {
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
padding: 10px 12px;
|
||||
border-bottom: 1px solid var(--line, #dce3ee);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.completion-definition-list dt {
|
||||
color: #5f6b7c;
|
||||
background: #f7f9fc;
|
||||
}
|
||||
|
||||
.completion-panel-heading {
|
||||
display: flex;
|
||||
min-height: 48px;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
padding: 9px 14px;
|
||||
border-bottom: 1px solid var(--line, #dce3ee);
|
||||
}
|
||||
|
||||
.completion-panel-heading > div:first-child {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
flex-direction: column;
|
||||
gap: 3px;
|
||||
}
|
||||
|
||||
.completion-panel-heading strong {
|
||||
color: var(--ink);
|
||||
font-size: 13px;
|
||||
font-weight: 650;
|
||||
}
|
||||
|
||||
.completion-panel-heading span,
|
||||
.completion-note,
|
||||
.completion-placeholder {
|
||||
color: var(--ink);
|
||||
font-size: 11px;
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
.completion-panel-heading .ant-btn,
|
||||
.completion-actions .ant-btn,
|
||||
.completion-filter-row .ant-btn,
|
||||
.completion-compare-controls .ant-btn,
|
||||
.completion-insights .ant-btn,
|
||||
.completion-tools .ant-btn,
|
||||
.completion-scrap-stack .ant-btn {
|
||||
border-radius: 0 !important;
|
||||
}
|
||||
|
||||
.completion-insight-grid {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(220px, 0.72fr) minmax(0, 1.55fr);
|
||||
gap: 10px;
|
||||
padding: 12px;
|
||||
}
|
||||
|
||||
.completion-focus-panel {
|
||||
min-width: 0;
|
||||
padding: 10px 12px 13px;
|
||||
border-top: 1px solid #dce3ee;
|
||||
}
|
||||
|
||||
.completion-focus-panel .completion-section-heading {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: 9px;
|
||||
margin: 0 0 8px;
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
.completion-focus-panel .completion-section-heading > div {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: baseline;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.completion-focus-panel .completion-section-heading span {
|
||||
color: #4d5b6e;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.completion-insight-card {
|
||||
min-width: 0;
|
||||
padding: 12px;
|
||||
border: 1px solid #dce3ee;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.completion-card-heading {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
color: var(--ink);
|
||||
font-size: 12px;
|
||||
font-weight: 650;
|
||||
}
|
||||
|
||||
.completion-target-value {
|
||||
margin: 16px 0 8px;
|
||||
color: var(--ink);
|
||||
font-size: 28px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
font-weight: 680;
|
||||
}
|
||||
|
||||
.completion-target-value small {
|
||||
color: var(--ink);
|
||||
font-size: 11px;
|
||||
font-weight: 450;
|
||||
}
|
||||
|
||||
.completion-empty-value,
|
||||
.completion-placeholder {
|
||||
margin-top: 12px;
|
||||
padding: 14px 10px;
|
||||
border: 1px dashed #cbd5e1;
|
||||
background: #f8fafc;
|
||||
}
|
||||
|
||||
.completion-compare-controls,
|
||||
.completion-actions,
|
||||
.completion-filter-row {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.completion-compare-controls .ant-select {
|
||||
min-width: 190px;
|
||||
}
|
||||
|
||||
.completion-compare-card > .completion-note {
|
||||
margin: 9px 0;
|
||||
}
|
||||
|
||||
.completion-compare-snapshots {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 8px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.completion-snapshot {
|
||||
min-width: 0;
|
||||
padding: 9px 10px;
|
||||
border: 1px solid #dce3ee;
|
||||
background: #f8fafc;
|
||||
}
|
||||
|
||||
.completion-snapshot > strong {
|
||||
color: var(--ink);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.completion-snapshot dl {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(90px, 0.8fr) minmax(80px, 1fr);
|
||||
gap: 4px 8px;
|
||||
margin: 8px 0 0;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.completion-snapshot dt {
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
.completion-snapshot dd {
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
color: var(--ink);
|
||||
font-variant-numeric: tabular-nums;
|
||||
text-align: right;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.completion-delta-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
|
||||
gap: 7px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.completion-delta-grid > span {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
padding: 9px;
|
||||
border-top: 2px solid #3974b8;
|
||||
background: #f5f8fc;
|
||||
}
|
||||
|
||||
.completion-delta-grid small {
|
||||
color: var(--ink);
|
||||
font-size: 10px;
|
||||
}
|
||||
|
||||
.completion-delta-grid strong {
|
||||
color: var(--ink);
|
||||
font-size: 13px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.completion-evidence-line,
|
||||
.completion-contribution {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 7px 12px;
|
||||
margin-top: 10px;
|
||||
color: var(--ink);
|
||||
font-size: 11px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.completion-evidence-line > span,
|
||||
.completion-contribution > span {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.completion-contribution {
|
||||
padding: 9px 10px;
|
||||
border-left: 3px solid #008f7d;
|
||||
background: #f3faf9;
|
||||
}
|
||||
|
||||
.completion-insights .ant-table-wrapper,
|
||||
.completion-tools .ant-table-wrapper {
|
||||
max-width: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.completion-insights .ant-table-cell,
|
||||
.completion-tools .ant-table-cell {
|
||||
padding: 8px 10px !important;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.completion-actions {
|
||||
gap: 1px;
|
||||
flex-wrap: nowrap;
|
||||
}
|
||||
|
||||
.completion-filter-row {
|
||||
padding: 10px 13px;
|
||||
border-bottom: 1px solid #e5eaf1;
|
||||
}
|
||||
|
||||
.completion-filter-row > .ant-select {
|
||||
min-width: 140px;
|
||||
}
|
||||
|
||||
.completion-loading {
|
||||
display: flex;
|
||||
min-height: 72px;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 10px;
|
||||
color: var(--ink);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.completion-scrap-stack {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.completion-scrap-stack .completion-tools > .ant-alert,
|
||||
.completion-scrap-stack .completion-tools > .completion-placeholder,
|
||||
.completion-scrap-stack .completion-tools > .completion-note {
|
||||
margin: 10px 13px;
|
||||
}
|
||||
|
||||
.completion-scrap-stack .completion-table-wrap {
|
||||
min-width: 0;
|
||||
margin: 8px 0 0;
|
||||
}
|
||||
|
||||
.completion-scrap-stack .ant-table {
|
||||
border-radius: 0 !important;
|
||||
}
|
||||
|
||||
.completion-insights .ant-tag,
|
||||
.completion-tools .ant-tag {
|
||||
border-radius: 0;
|
||||
}
|
||||
|
||||
.completion-compare-period {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
color: var(--ink);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.target-current-summary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
min-height: 64px;
|
||||
padding: 12px 16px;
|
||||
border-top: 1px solid var(--line);
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
.target-current-summary > span { color: var(--muted-ink, #68778b); }
|
||||
.target-current-summary .ant-btn { margin-left: auto; }
|
||||
.target-current-summary .ant-btn-primary,
|
||||
.target-editor-modal .ant-modal-footer .ant-btn-primary {
|
||||
color: #fff;
|
||||
background: #425fd0;
|
||||
border-color: #425fd0;
|
||||
}
|
||||
|
||||
.target-current-summary .ant-btn-primary:hover,
|
||||
.target-current-summary .ant-btn-primary:focus-visible,
|
||||
.target-editor-modal .ant-modal-footer .ant-btn-primary:hover,
|
||||
.target-editor-modal .ant-modal-footer .ant-btn-primary:focus-visible {
|
||||
color: #fff;
|
||||
background: #3452bd;
|
||||
border-color: #3452bd;
|
||||
}
|
||||
|
||||
.target-admin .completion-validation {
|
||||
margin: 11px 13px;
|
||||
}
|
||||
|
||||
.target-admin details {
|
||||
margin-top: 8px;
|
||||
color: var(--ink);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.target-admin details pre {
|
||||
max-height: 260px;
|
||||
overflow: auto;
|
||||
padding: 9px;
|
||||
border: 1px solid #dce3ee;
|
||||
background: #f7f9fc;
|
||||
color: var(--ink);
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.target-rule-list {
|
||||
max-height: 50vh;
|
||||
overflow: auto;
|
||||
border: 1px solid #dce3ee;
|
||||
}
|
||||
|
||||
.target-rule-list > .resource-toolbar {
|
||||
position: sticky;
|
||||
z-index: 2;
|
||||
top: 0;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.target-rule-row {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, minmax(105px, 1fr));
|
||||
align-items: end;
|
||||
gap: 0 10px;
|
||||
padding: 9px 11px;
|
||||
border-bottom: 1px solid #e5eaf1;
|
||||
}
|
||||
|
||||
.target-rule-row .ant-form-item {
|
||||
min-width: 0;
|
||||
margin-bottom: 9px;
|
||||
}
|
||||
|
||||
.target-rule-row .ant-form-item-label {
|
||||
padding-bottom: 3px;
|
||||
}
|
||||
|
||||
.target-rule-row .ant-form-item-label > label {
|
||||
color: var(--ink);
|
||||
font-size: 10px;
|
||||
}
|
||||
|
||||
.target-rule-row > .ant-btn {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.target-editor-modal .ant-modal-body {
|
||||
max-height: calc(100vh - 180px);
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.target-editor-section {
|
||||
margin: 10px 0 14px;
|
||||
}
|
||||
|
||||
.target-editor-heading {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
padding: 6px 8px;
|
||||
border: 1px solid var(--line, #dce3ee);
|
||||
border-bottom: 0;
|
||||
background: var(--surface-subtle, #f7f9fc);
|
||||
}
|
||||
|
||||
.target-editor-heading > div {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
flex-direction: column;
|
||||
gap: 3px;
|
||||
}
|
||||
|
||||
.target-editor-heading strong {
|
||||
color: var(--ink);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.target-editor-heading span {
|
||||
color: var(--muted-ink, #68778b);
|
||||
font-size: 11px;
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
.target-editor-rate {
|
||||
display: inline-flex;
|
||||
width: 100%;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.target-editor-table .target-editor-rate .ant-input-number {
|
||||
flex: 0 0 76px;
|
||||
width: 76px;
|
||||
}
|
||||
|
||||
.target-editor-rate > span:last-child,
|
||||
.target-editor-period-all {
|
||||
color: var(--muted-ink, #68778b);
|
||||
}
|
||||
|
||||
.target-editor-table .ant-select,
|
||||
.target-editor-table .ant-input-number,
|
||||
.target-editor-table .ant-input {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.target-editor-table .ant-table-cell {
|
||||
vertical-align: middle;
|
||||
padding: 5px 6px !important;
|
||||
}
|
||||
|
||||
.target-editor-table .ant-table-thead > tr > th,
|
||||
.target-editor-table .ant-table-tbody > tr > td {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.target-editor-table .ant-input,
|
||||
.target-editor-table .ant-input-number-input,
|
||||
.target-editor-table .ant-select-selection-item,
|
||||
.target-editor-table .ant-select-selection-search-input {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.target-editor-select-popup {
|
||||
z-index: 1200;
|
||||
background: var(--surface, #fff);
|
||||
}
|
||||
|
||||
.target-editor-select-popup .ant-select-item {
|
||||
min-height: 34px;
|
||||
}
|
||||
|
||||
.target-editor-select-popup .ant-select-item-option-content {
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.target-editor-table .ant-input,
|
||||
.target-editor-table .ant-input-number,
|
||||
.target-editor-table .ant-select-selector {
|
||||
min-height: 28px;
|
||||
}
|
||||
|
||||
.target-editor-table .ant-input-number-input {
|
||||
height: 26px;
|
||||
}
|
||||
|
||||
.governance-source-panel,
|
||||
.governance-monitor,
|
||||
.governance-service-identities {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.governance-source-panel > .completion-panel-heading,
|
||||
.governance-monitor > .completion-panel-heading,
|
||||
.governance-service-identities .completion-panel-heading {
|
||||
min-height: 54px;
|
||||
}
|
||||
|
||||
.governance-source-panel > .ant-alert {
|
||||
margin: 10px 13px;
|
||||
}
|
||||
|
||||
.governance-source-panel .ant-tabs-nav {
|
||||
margin: 0 13px 9px;
|
||||
}
|
||||
|
||||
.governance-source-panel .governance-panel-body {
|
||||
min-width: 0;
|
||||
padding: 0 13px 12px;
|
||||
}
|
||||
|
||||
.governance-status-strip {
|
||||
display: flex;
|
||||
min-height: 39px;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
padding: 0 2px 7px;
|
||||
color: var(--ink);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.governance-status-strip strong {
|
||||
font-weight: 650;
|
||||
}
|
||||
|
||||
.governance-source-panel .ant-table-wrapper,
|
||||
.governance-source-panel .ant-table-container {
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.governance-source-panel .ant-table-cell,
|
||||
.governance-monitor .ant-table-cell,
|
||||
.governance-service-identities .ant-table-cell {
|
||||
padding: 8px 10px !important;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.governance-form-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 0 13px;
|
||||
}
|
||||
|
||||
.governance-form-grid .ant-form-item {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.governance-form-grid .ant-input-number,
|
||||
.governance-form-grid .ant-select {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.governance-form-grid .ant-input,
|
||||
.governance-form-grid .ant-input-number,
|
||||
.governance-form-grid .ant-select-selector,
|
||||
.governance-source-panel .ant-btn,
|
||||
.governance-source-panel .ant-tag,
|
||||
.governance-monitor .ant-btn,
|
||||
.governance-service-identities .ant-btn,
|
||||
.governance-service-identities .ant-select-selector,
|
||||
.governance-service-identities .ant-input {
|
||||
border-radius: 0 !important;
|
||||
}
|
||||
|
||||
.governance-evidence-summary {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 9px;
|
||||
margin-bottom: 14px;
|
||||
padding: 12px;
|
||||
border: 1px solid #dce3ee;
|
||||
background: #f8fafc;
|
||||
color: var(--ink);
|
||||
font-size: 11px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.governance-evidence-summary strong {
|
||||
grid-column: 1 / -1;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.governance-evidence-summary span {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.governance-monitor .ant-alert {
|
||||
margin: 10px 13px;
|
||||
}
|
||||
|
||||
.governance-monitor-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(145px, 1fr));
|
||||
gap: 8px;
|
||||
padding: 12px 13px;
|
||||
}
|
||||
|
||||
.governance-monitor-grid > div {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
min-height: 58px;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
gap: 6px;
|
||||
padding: 8px 10px;
|
||||
border: 1px solid #dce3ee;
|
||||
background: #f8fafc;
|
||||
}
|
||||
|
||||
.governance-monitor-grid small {
|
||||
color: var(--ink);
|
||||
font-size: 10px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.governance-monitor-grid strong {
|
||||
color: var(--ink);
|
||||
font-size: 14px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.governance-monitor > .ant-table-wrapper {
|
||||
margin: 0 13px 12px;
|
||||
}
|
||||
|
||||
.governance-binding-list {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 8px;
|
||||
padding: 12px 13px;
|
||||
}
|
||||
|
||||
.governance-binding-list > div {
|
||||
display: grid;
|
||||
min-width: 0;
|
||||
grid-template-columns: minmax(85px, 0.7fr) minmax(90px, 1fr) minmax(140px, 1.3fr);
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 9px;
|
||||
border: 1px solid #dce3ee;
|
||||
color: var(--ink);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.governance-binding-list > div > * {
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.governance-policy-select {
|
||||
max-width: 480px;
|
||||
padding: 12px 13px 0;
|
||||
}
|
||||
|
||||
.governance-policy-select .ant-select {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.governance-policy-form {
|
||||
max-width: 880px;
|
||||
padding: 12px 13px;
|
||||
}
|
||||
|
||||
.governance-service-identities .completion-note,
|
||||
.governance-policy-form .completion-note {
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.governance-service-identities .ant-alert {
|
||||
margin: 10px 13px;
|
||||
}
|
||||
|
||||
.governance-service-identities > .panel:nth-child(2) .completion-panel-heading {
|
||||
border-bottom: 0;
|
||||
}
|
||||
|
||||
.completion-tools .ant-input,
|
||||
.completion-tools .ant-input-number,
|
||||
.completion-tools .ant-select-selector,
|
||||
.completion-tools .ant-btn,
|
||||
.completion-insights .ant-select-selector {
|
||||
border-radius: 0 !important;
|
||||
}
|
||||
|
||||
.analysis-feedback {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-top: 12px;
|
||||
padding-top: 10px;
|
||||
border-top: 1px solid #dce3ee;
|
||||
}
|
||||
|
||||
.analysis-feedback .ant-select { width: 190px; }
|
||||
.analysis-feedback .ant-input { flex: 1 1 200px; max-width: 380px; }
|
||||
.analysis-evidence-list { margin: 8px 0; padding-left: 22px; }
|
||||
.analysis-evidence-list li { margin: 5px 0; overflow-wrap: anywhere; }
|
||||
.analysis-result-ref-notice { margin: 10px 12px 0; }
|
||||
.completion-technical-detail { margin: 14px 0 4px; border-top: 1px solid #dce3ee; padding-top: 10px; }
|
||||
.completion-technical-detail > summary { cursor: pointer; color: #4b5563; font-size: 12px; }
|
||||
.completion-technical-detail > .json-result { max-height: 360px; overflow: auto; margin-top: 10px; }
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.completion-insight-grid {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 620px) {
|
||||
.completion-panel-heading {
|
||||
align-items: flex-start;
|
||||
flex-wrap: wrap;
|
||||
padding: 9px 10px;
|
||||
}
|
||||
|
||||
.completion-panel-heading > .ant-btn,
|
||||
.completion-panel-heading > .completion-actions {
|
||||
width: 100%;
|
||||
justify-content: flex-start;
|
||||
}
|
||||
|
||||
.completion-insight-grid {
|
||||
padding: 9px;
|
||||
}
|
||||
|
||||
.completion-card-heading {
|
||||
align-items: flex-start;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.completion-compare-controls,
|
||||
.completion-compare-controls .ant-select,
|
||||
.completion-compare-controls .ant-btn {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.completion-compare-snapshots {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.completion-filter-row > .ant-select,
|
||||
.completion-filter-row > .ant-btn {
|
||||
min-width: 0;
|
||||
flex: 1 1 132px;
|
||||
}
|
||||
|
||||
.target-rule-row {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
.governance-form-grid,
|
||||
.governance-evidence-summary,
|
||||
.governance-binding-list {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.governance-binding-list > div {
|
||||
grid-template-columns: minmax(75px, 0.7fr) minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.governance-binding-list > div > .ant-select {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
:root[data-workspace-theme='dark'] {
|
||||
color-scheme: dark;
|
||||
background: #0e1420;
|
||||
--ink: #eaf0fa;
|
||||
--muted-ink: #adbdd1;
|
||||
--surface: #172234;
|
||||
--surface-subtle: #1d2a3d;
|
||||
--sidebar-surface: #111b2a;
|
||||
--line: #35445a;
|
||||
--blue-dark: #a9bdff;
|
||||
}
|
||||
|
||||
:root[data-workspace-theme='dark'] body,
|
||||
:root[data-workspace-theme='dark'] .app-shell,
|
||||
:root[data-workspace-theme='dark'] .main-column { color: var(--ink); background: var(--background); }
|
||||
:root[data-workspace-theme='dark'] .sidebar,
|
||||
:root[data-workspace-theme='dark'] .mobile-brand { background: var(--sidebar-surface); }
|
||||
:root[data-workspace-theme='dark'] .topbar { background: var(--surface); }
|
||||
:root[data-workspace-theme='dark'] .nav-group-label,
|
||||
:root[data-workspace-theme='dark'] .nav-item .anticon,
|
||||
:root[data-workspace-theme='dark'] .topbar-search.ant-btn,
|
||||
:root[data-workspace-theme='dark'] .topbar-theme.ant-btn,
|
||||
:root[data-workspace-theme='dark'] .navigation-search-empty,
|
||||
:root[data-workspace-theme='dark'] .navigation-search-footnote,
|
||||
:root[data-workspace-theme='dark'] .navigation-result,
|
||||
:root[data-workspace-theme='dark'] .navigation-search-modal .ant-modal-title { color: var(--ink); }
|
||||
:root[data-workspace-theme='dark'] .breadcrumb-slash,
|
||||
:root[data-workspace-theme='dark'] .topbar-search .anticon,
|
||||
:root[data-workspace-theme='dark'] .topbar-help .anticon,
|
||||
:root[data-workspace-theme='dark'] .topbar-theme .anticon,
|
||||
:root[data-workspace-theme='dark'] .organization-breadcrumb > span:first-child,
|
||||
:root[data-workspace-theme='dark'] .organization-crumb > i { color: var(--muted-ink); }
|
||||
:root[data-workspace-theme='dark'] .nav-item:hover,
|
||||
:root[data-workspace-theme='dark'] .navigation-result:hover { background: var(--hover); }
|
||||
:root[data-workspace-theme='dark'] .nav-item.active { background: var(--blue-soft); color: var(--blue-dark); }
|
||||
:root[data-workspace-theme='dark'] .avatar,
|
||||
:root[data-workspace-theme='dark'] .topbar-search kbd,
|
||||
:root[data-workspace-theme='dark'] .navigation-result kbd,
|
||||
:root[data-workspace-theme='dark'] .organization-breadcrumb { background: var(--surface-subtle); color: var(--muted-ink); }
|
||||
|
||||
:root[data-workspace-theme='dark'] .panel,
|
||||
:root[data-workspace-theme='dark'] .metric-strip,
|
||||
:root[data-workspace-theme='dark'] .management-page .panel,
|
||||
:root[data-workspace-theme='dark'] .management-page .access-summary { background: var(--surface); border-color: var(--line); }
|
||||
:root[data-workspace-theme='dark'] .metric-card.primary,
|
||||
:root[data-workspace-theme='dark'] .basis-card { background: var(--blue-soft); }
|
||||
:root[data-workspace-theme='dark'] .metric-card:hover { background: var(--hover); }
|
||||
:root[data-workspace-theme='dark'] .metric-table-scroll .ant-table-tbody > tr > td.ant-table-cell-fix-left { background: var(--surface); }
|
||||
:root[data-workspace-theme='dark'] .metric-table-scroll .combined-column,
|
||||
:root[data-workspace-theme='dark'] .metric-table-scroll .combined-column.ant-table-cell-fix-left,
|
||||
:root[data-workspace-theme='dark'] .metric-table-scroll th.combined-column,
|
||||
:root[data-workspace-theme='dark'] .metric-table-scroll .ant-table-thead > tr:first-child > th:has(.stage-heading.black) { background: #253457 !important; }
|
||||
:root[data-workspace-theme='dark'] .metric-table-scroll .ant-table-thead > tr:first-child > th:has(.stage-heading.bright) { background: #183f3d !important; }
|
||||
:root[data-workspace-theme='dark'] .metric-table-scroll .ant-table-thead > tr > th { color: var(--ink); }
|
||||
:root[data-workspace-theme='dark'] .stage-heading.black,
|
||||
:root[data-workspace-theme='dark'] .rate-cell.black .table-value { color: var(--blue-dark); }
|
||||
:root[data-workspace-theme='dark'] .month-state { border-color: var(--line); }
|
||||
:root[data-workspace-theme='dark'] .defect-track { background: var(--surface-subtle); }
|
||||
|
||||
:root[data-workspace-theme='dark'] .management-page {
|
||||
--management-ink: var(--ink);
|
||||
--management-muted: var(--muted-ink);
|
||||
--management-line: var(--line);
|
||||
--management-blue-wash: var(--surface-subtle);
|
||||
}
|
||||
:root[data-workspace-theme='dark'] .management-page .ant-table-tbody > tr:hover > td,
|
||||
:root[data-workspace-theme='dark'] .management-page .ant-table-tbody > tr.ant-table-row:hover > td { background: var(--hover) !important; }
|
||||
:root[data-workspace-theme='dark'] .snapshot-card,
|
||||
:root[data-workspace-theme='dark'] .snapshot-kpis > span,
|
||||
:root[data-workspace-theme='dark'] .snapshot-defects > div,
|
||||
:root[data-workspace-theme='dark'] .json-result { background: var(--surface-subtle); color: var(--ink); }
|
||||
:root[data-workspace-theme='dark'] .management-page .analysis-answer,
|
||||
:root[data-workspace-theme='dark'] .management-page .snapshot-card,
|
||||
:root[data-workspace-theme='dark'] .management-page .json-result,
|
||||
:root[data-workspace-theme='dark'] .management-page .json-cell,
|
||||
:root[data-workspace-theme='dark'] .management-modal .json-result,
|
||||
:root[data-workspace-theme='dark'] .management-drawer .json-result,
|
||||
:root[data-workspace-theme='dark'] .inspection-ai-summary,
|
||||
:root[data-workspace-theme='dark'] .governance-evidence-summary,
|
||||
:root[data-workspace-theme='dark'] .governance-monitor-grid > div { background: var(--surface-subtle); color: var(--ink); border-color: var(--line); }
|
||||
:root[data-workspace-theme='dark'] .management-page .analysis-session-row { background: var(--surface); border-color: var(--line); }
|
||||
:root[data-workspace-theme='dark'] .management-page .analysis-session-row:hover,
|
||||
:root[data-workspace-theme='dark'] .management-page .analysis-session-row.active { background: var(--hover); }
|
||||
:root[data-workspace-theme='dark'] .management-page .analysis-session-item { color: var(--ink); background: transparent; }
|
||||
:root[data-workspace-theme='dark'] .management-page .analysis-session-item small { color: var(--muted-ink); }
|
||||
:root[data-workspace-theme='dark'] .management-modal,
|
||||
:root[data-workspace-theme='dark'] .management-drawer { --management-ink: var(--ink); --management-muted: var(--muted-ink); --management-line: var(--line); }
|
||||
:root[data-workspace-theme='dark'] .management-modal .ant-modal-container,
|
||||
:root[data-workspace-theme='dark'] .management-modal .ant-modal-content,
|
||||
:root[data-workspace-theme='dark'] .management-drawer .ant-drawer-content,
|
||||
:root[data-workspace-theme='dark'] .navigation-search-modal .ant-modal-container,
|
||||
:root[data-workspace-theme='dark'] .navigation-search-modal .ant-modal-content,
|
||||
:root[data-workspace-theme='dark'] .navigation-search-modal .ant-modal-header { background: var(--surface); }
|
||||
:root[data-workspace-theme='dark'] .analysis-question { background: var(--blue-soft); }
|
||||
|
||||
:root[data-workspace-theme='dark'] .completion-definition-list dt,
|
||||
:root[data-workspace-theme='dark'] .completion-insight-card,
|
||||
:root[data-workspace-theme='dark'] .completion-empty-value,
|
||||
:root[data-workspace-theme='dark'] .completion-placeholder,
|
||||
:root[data-workspace-theme='dark'] .completion-snapshot,
|
||||
:root[data-workspace-theme='dark'] .completion-delta-grid > span,
|
||||
:root[data-workspace-theme='dark'] .completion-contribution { background: var(--surface-subtle); border-color: var(--line); }
|
||||
:root[data-workspace-theme='dark'] .completion-focus-panel,
|
||||
:root[data-workspace-theme='dark'] .completion-filter-row { border-color: var(--line); }
|
||||
:root[data-workspace-theme='dark'] .completion-definition-list dt,
|
||||
:root[data-workspace-theme='dark'] .completion-panel-heading strong,
|
||||
:root[data-workspace-theme='dark'] .completion-panel-heading span,
|
||||
:root[data-workspace-theme='dark'] .completion-focus-panel .completion-section-heading,
|
||||
:root[data-workspace-theme='dark'] .completion-card-heading,
|
||||
:root[data-workspace-theme='dark'] .completion-target-value,
|
||||
:root[data-workspace-theme='dark'] .completion-target-value small,
|
||||
:root[data-workspace-theme='dark'] .completion-snapshot > strong,
|
||||
:root[data-workspace-theme='dark'] .completion-snapshot dt,
|
||||
:root[data-workspace-theme='dark'] .completion-snapshot dd,
|
||||
:root[data-workspace-theme='dark'] .completion-delta-grid small,
|
||||
:root[data-workspace-theme='dark'] .completion-delta-grid strong,
|
||||
:root[data-workspace-theme='dark'] .completion-evidence-line,
|
||||
:root[data-workspace-theme='dark'] .completion-contribution,
|
||||
:root[data-workspace-theme='dark'] .completion-note,
|
||||
:root[data-workspace-theme='dark'] .completion-placeholder { color: var(--ink); }
|
||||
:root[data-workspace-theme='dark'] .completion-focus-panel .completion-section-heading span { color: var(--muted-ink); }
|
||||
:root[data-workspace-theme='dark'] .target-rule-list > .resource-toolbar { background: var(--surface); border-color: var(--line); }
|
||||
:root[data-workspace-theme='dark'] .target-admin details pre { background: var(--surface-subtle); color: var(--ink); border-color: var(--line); }
|
||||
|
||||
:root[data-workspace-theme='dark'] .structured-config-editor,
|
||||
:root[data-workspace-theme='dark'] .structured-config-intro p,
|
||||
:root[data-workspace-theme='dark'] .structured-config-note,
|
||||
:root[data-workspace-theme='dark'] .structured-config-rule-card h4,
|
||||
:root[data-workspace-theme='dark'] .nc-simplified-intake,
|
||||
:root[data-workspace-theme='dark'] .nc-simplified-config-page,
|
||||
:root[data-workspace-theme='dark'] .nc-simplified-releases,
|
||||
:root[data-workspace-theme='dark'] .nc-workflow-modal .ant-modal-body,
|
||||
:root[data-workspace-theme='dark'] .nc-workflow-modal .ant-modal-title,
|
||||
:root[data-workspace-theme='dark'] .nc-workflow-modal h3,
|
||||
:root[data-workspace-theme='dark'] .nc-workflow-modal .ant-form-item-label > label,
|
||||
:root[data-workspace-theme='dark'] .nc-intake-intro h2,
|
||||
:root[data-workspace-theme='dark'] .nc-intake-intro p,
|
||||
:root[data-workspace-theme='dark'] .nc-intake-links .ant-btn,
|
||||
:root[data-workspace-theme='dark'] .nc-intake-links > span,
|
||||
:root[data-workspace-theme='dark'] .nc-advanced-records > summary,
|
||||
:root[data-workspace-theme='dark'] .nc-simple-upload-heading h2,
|
||||
:root[data-workspace-theme='dark'] .nc-simple-upload-heading p,
|
||||
:root[data-workspace-theme='dark'] .nc-simple-upload-fields > label,
|
||||
:root[data-workspace-theme='dark'] .nc-advanced-import-settings > summary,
|
||||
:root[data-workspace-theme='dark'] .nc-simple-submit-row > span,
|
||||
:root[data-workspace-theme='dark'] .nc-operation-status > div:not(.ant-alert) > strong,
|
||||
:root[data-workspace-theme='dark'] .nc-operation-status > div:not(.ant-alert) > span,
|
||||
:root[data-workspace-theme='dark'] .nc-source-maintenance-note { color: var(--ink); }
|
||||
:root[data-workspace-theme='dark'] .structured-config-intro,
|
||||
:root[data-workspace-theme='dark'] .structured-config-rule-card,
|
||||
:root[data-workspace-theme='dark'] .nc-file-drop,
|
||||
:root[data-workspace-theme='dark'] .nc-file-summary,
|
||||
:root[data-workspace-theme='dark'] .nc-workbook-upload-intro,
|
||||
:root[data-workspace-theme='dark'] .nc-processing,
|
||||
:root[data-workspace-theme='dark'] .nc-delete-request,
|
||||
:root[data-workspace-theme='dark'] .nc-simple-file-line { background: var(--surface-subtle); border-color: var(--line); }
|
||||
:root[data-workspace-theme='dark'] .nc-replacement { background: #3a3021; border-color: #786043; }
|
||||
:root[data-workspace-theme='dark'] .nc-replacement > span { color: var(--ink); }
|
||||
:root[data-workspace-theme='dark'] .nc-field-match b,
|
||||
:root[data-workspace-theme='dark'] .nc-simple-config-page .json-result,
|
||||
:root[data-workspace-theme='dark'] .nc-simple-config-tabs .ant-table-thead > tr > th,
|
||||
:root[data-workspace-theme='dark'] .nc-simple-history .ant-table-thead > tr > th,
|
||||
:root[data-workspace-theme='dark'] .nc-simplified-releases .ant-table-thead > tr > th { background: var(--surface-subtle); color: var(--ink); border-color: var(--line); }
|
||||
:root[data-workspace-theme='dark'] .structured-config-editor .ant-table-thead > tr > th,
|
||||
:root[data-workspace-theme='dark'] .structured-match-editor .ant-table-thead > tr > th { background: var(--surface-subtle); color: var(--ink); }
|
||||
|
||||
:root[data-workspace-theme='dark'] .screen-state { background: var(--background); }
|
||||
:root[data-workspace-theme='dark'] .state-card { background: var(--surface); }
|
||||
:root[data-workspace-theme='dark'] .login-screen,
|
||||
:root[data-workspace-theme='dark'] .login-panel { background: var(--background); }
|
||||
:root[data-workspace-theme='dark'] .login-card h2,
|
||||
:root[data-workspace-theme='dark'] .login-card .ant-form-item-label > label { color: var(--ink); }
|
||||
:root[data-workspace-theme='dark'] .login-panel-top,
|
||||
:root[data-workspace-theme='dark'] .login-card-subtitle,
|
||||
:root[data-workspace-theme='dark'] .login-footer { color: var(--muted-ink); }
|
||||
@@ -0,0 +1,79 @@
|
||||
import React, { useLayoutEffect, useState } from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import { App, ConfigProvider, theme as antdTheme } from 'antd';
|
||||
import zhCN from 'antd/locale/zh_CN';
|
||||
import QualityWorkspace from './QualityWorkspace';
|
||||
import { getStoredWorkspaceThemeId, getWorkspaceTheme, workspaceThemeStorageKey, type WorkspaceThemeId } from './ui-themes';
|
||||
import './styles.css';
|
||||
import './dark-theme.css';
|
||||
|
||||
function QualityCenterApp() {
|
||||
const [themeId, setThemeId] = useState<WorkspaceThemeId>(getStoredWorkspaceThemeId);
|
||||
const appearance = getWorkspaceTheme(themeId);
|
||||
const dark = appearance.id === 'dark';
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const root = document.documentElement;
|
||||
root.dataset.workspaceTheme = appearance.id;
|
||||
root.style.setProperty('--ink', dark ? '#EAF0FA' : '#111111');
|
||||
root.style.setProperty('--blue', appearance.primary);
|
||||
root.style.setProperty('--blue-dark', dark ? '#A9BDFF' : appearance.primary);
|
||||
root.style.setProperty('--blue-soft', appearance.soft);
|
||||
root.style.setProperty('--blue-muted', appearance.muted);
|
||||
root.style.setProperty('--background', appearance.background);
|
||||
root.style.setProperty('--hover', appearance.hover);
|
||||
root.style.setProperty('--metric-grid', appearance.metricGrid);
|
||||
root.style.setProperty('--metric-grid-head', appearance.metricGridHead);
|
||||
root.style.setProperty('--sidebar-surface', dark ? '#111B2A' : 'color-mix(in srgb, var(--background) 48%, white)');
|
||||
root.style.setProperty('--surface', dark ? '#172234' : '#ffffff');
|
||||
root.style.setProperty('--line', dark ? '#35445A' : '#dfe5ef');
|
||||
root.style.setProperty('--teal', dark ? '#54D5BF' : '#008f7d');
|
||||
try { window.localStorage.setItem(workspaceThemeStorageKey, appearance.id); } catch { /* local preference is optional */ }
|
||||
}, [appearance]);
|
||||
|
||||
return (
|
||||
<ConfigProvider
|
||||
locale={zhCN}
|
||||
theme={{
|
||||
algorithm: dark ? antdTheme.darkAlgorithm : antdTheme.defaultAlgorithm,
|
||||
token: {
|
||||
colorPrimary: appearance.primary,
|
||||
colorInfo: appearance.primary,
|
||||
colorBgBase: dark ? '#101928' : '#ffffff',
|
||||
colorBgContainer: dark ? '#172234' : '#ffffff',
|
||||
// Ant Design 6 renders modal panels on `.ant-modal-container` and
|
||||
// derives their background from this token. Keep it explicit in
|
||||
// light themes so overlays never inherit a transparent default.
|
||||
colorBgElevated: dark ? '#1A2638' : '#ffffff',
|
||||
colorText: dark ? '#EAF0FA' : '#111111',
|
||||
colorTextSecondary: dark ? '#ADBDD1' : '#111111',
|
||||
colorTextPlaceholder: dark ? '#98ABC5' : undefined,
|
||||
colorBorder: dark ? '#35445A' : '#dfe5ef',
|
||||
colorBorderSecondary: dark ? '#35445A' : undefined,
|
||||
borderRadius: 0,
|
||||
fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif',
|
||||
controlHeight: 32,
|
||||
fontSize: 14,
|
||||
},
|
||||
components: {
|
||||
Button: { borderRadius: 0 },
|
||||
Input: { borderRadius: 0 },
|
||||
Select: { borderRadius: 0 },
|
||||
Table: { headerBg: dark ? '#202D40' : '#f6f8fd', rowHoverBg: appearance.hover },
|
||||
Modal: { borderRadiusLG: 0 },
|
||||
Drawer: { borderRadiusLG: 0 },
|
||||
},
|
||||
}}
|
||||
>
|
||||
<App>
|
||||
<QualityWorkspace appearance={appearance} onAppearanceChange={setThemeId} />
|
||||
</App>
|
||||
</ConfigProvider>
|
||||
);
|
||||
}
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(
|
||||
<React.StrictMode>
|
||||
<QualityCenterApp />
|
||||
</React.StrictMode>,
|
||||
);
|
||||
@@ -0,0 +1,646 @@
|
||||
.management-page {
|
||||
--management-ink: #111111;
|
||||
--management-muted: #111111;
|
||||
--management-line: #dce3ee;
|
||||
--management-blue-wash: #f6f8fd;
|
||||
display: flex;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
color: var(--management-ink);
|
||||
}
|
||||
|
||||
.management-page > * {
|
||||
max-width: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.management-page .panel {
|
||||
min-width: 0;
|
||||
border: 1px solid var(--management-line);
|
||||
border-radius: 0 !important;
|
||||
background: #fff;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.management-page .section-panel {
|
||||
overflow: hidden;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.management-page > .page-heading {
|
||||
display: flex;
|
||||
min-height: 54px;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
margin: 0 0 2px;
|
||||
}
|
||||
|
||||
.management-page > .page-heading > div:first-child {
|
||||
min-width: 0;
|
||||
flex: 1 1 420px;
|
||||
}
|
||||
|
||||
.management-page .page-heading h1 {
|
||||
color: var(--management-ink);
|
||||
font-size: 20px;
|
||||
font-weight: 650;
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
.management-page .page-heading p {
|
||||
max-width: 980px;
|
||||
margin-top: 5px;
|
||||
color: var(--management-muted);
|
||||
font-size: 12px;
|
||||
line-height: 1.6;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.management-page .page-heading-actions {
|
||||
min-width: 0;
|
||||
flex: 0 1 auto;
|
||||
gap: 7px;
|
||||
}
|
||||
|
||||
.management-page .page-heading-actions .analysis-engine-status {
|
||||
max-width: 100%;
|
||||
flex-wrap: wrap;
|
||||
color: var(--management-muted);
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.management-page .resource-toolbar {
|
||||
min-height: 48px;
|
||||
flex-wrap: wrap;
|
||||
gap: 7px 14px;
|
||||
padding: 9px 15px;
|
||||
border-bottom: 1px solid var(--management-line);
|
||||
}
|
||||
|
||||
.management-page .resource-toolbar strong {
|
||||
color: var(--management-ink);
|
||||
font-size: 13px;
|
||||
font-weight: 650;
|
||||
}
|
||||
|
||||
.management-page .resource-toolbar span {
|
||||
min-width: 0;
|
||||
color: var(--management-muted);
|
||||
font-size: 11px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.management-page .resource-table,
|
||||
.management-page .resource-table .ant-table-wrapper,
|
||||
.management-page .ant-table-wrapper,
|
||||
.management-page .ant-table-container {
|
||||
width: 100%;
|
||||
max-width: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.management-page .resource-table .ant-table-cell {
|
||||
padding: 9px 11px !important;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.management-page .ant-table-thead > tr > th {
|
||||
background: var(--management-blue-wash) !important;
|
||||
color: var(--management-ink);
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.management-page .ant-table-tbody > tr > td {
|
||||
color: var(--management-ink);
|
||||
}
|
||||
|
||||
.management-page .ant-table-tbody > tr:hover > td,
|
||||
.management-page .ant-table-tbody > tr.ant-table-row:hover > td {
|
||||
background: #f8faff !important;
|
||||
}
|
||||
|
||||
.management-page .ant-table-bordered > .ant-table-container,
|
||||
.management-page .ant-table-container table > thead > tr:first-child > * {
|
||||
border-top: 0;
|
||||
}
|
||||
|
||||
.management-page .ant-table-bordered > .ant-table-container {
|
||||
border-inline-start: 0;
|
||||
}
|
||||
|
||||
.management-page .ant-table-bordered .ant-table-cell {
|
||||
border-inline-end: 0 !important;
|
||||
border-bottom-color: var(--management-line) !important;
|
||||
}
|
||||
|
||||
.management-page .ant-table-tbody > tr:last-child > td {
|
||||
border-bottom: 0 !important;
|
||||
}
|
||||
|
||||
.management-page .table-caption {
|
||||
margin: 8px 15px 11px;
|
||||
color: var(--management-muted);
|
||||
font-size: 11px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.management-page .access-summary {
|
||||
overflow: hidden;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.management-page .access-summary > div {
|
||||
min-width: 0;
|
||||
padding: 13px 15px;
|
||||
border-color: var(--management-line);
|
||||
}
|
||||
|
||||
.management-page .access-summary span,
|
||||
.management-page .access-summary small {
|
||||
color: var(--management-muted);
|
||||
font-size: 11px;
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
.management-page .access-summary strong {
|
||||
color: var(--management-ink);
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
line-height: 1.55;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.management-page .role-list {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 3px 9px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.management-page .role-list > span {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.management-page .role-summary-list {
|
||||
align-content: flex-start;
|
||||
}
|
||||
|
||||
.management-page .resource-tab,
|
||||
.management-page .basis-grid,
|
||||
.management-page .analysis-workspace,
|
||||
.management-page .analysis-chat-panel,
|
||||
.management-page .analysis-session-panel,
|
||||
.management-page .analysis-conversation,
|
||||
.management-page .analysis-context-bar,
|
||||
.management-page .analysis-composer,
|
||||
.management-page .analysis-snapshots,
|
||||
.management-page .snapshot-card {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.management-page .basis-grid {
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.management-page .analysis-workspace {
|
||||
min-height: min(680px, calc(100svh - 170px));
|
||||
grid-template-columns: minmax(210px, 240px) minmax(0, 1fr);
|
||||
align-items: stretch;
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.management-page .analysis-session-panel,
|
||||
.management-page .analysis-chat-panel {
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.management-page .analysis-session-heading {
|
||||
min-height: 50px;
|
||||
gap: 8px;
|
||||
padding: 9px 13px;
|
||||
border-bottom-color: var(--management-line);
|
||||
}
|
||||
|
||||
.management-page .analysis-session-heading strong {
|
||||
color: var(--management-ink);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.management-page .analysis-session-item {
|
||||
min-width: 0;
|
||||
padding: 11px 13px;
|
||||
border-bottom-color: var(--management-line);
|
||||
transition: background-color 170ms ease;
|
||||
}
|
||||
|
||||
.management-page .analysis-session-row:hover,
|
||||
.management-page .analysis-session-row.active {
|
||||
background: #eef2fc;
|
||||
}
|
||||
|
||||
.management-page .analysis-session-item strong,
|
||||
.management-page .analysis-session-item small {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.management-page .analysis-context-bar {
|
||||
gap: 8px;
|
||||
padding: 11px 13px;
|
||||
border-bottom-color: var(--management-line);
|
||||
}
|
||||
|
||||
.management-page .analysis-context-bar > .ant-select {
|
||||
min-width: 118px;
|
||||
max-width: 190px;
|
||||
}
|
||||
|
||||
.management-page .analysis-conversation {
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.management-page .analysis-answer,
|
||||
.management-page .analysis-question {
|
||||
border-color: var(--management-line);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.management-page .analysis-answer {
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.management-page .analysis-composer {
|
||||
gap: 9px;
|
||||
padding: 13px;
|
||||
border-top-color: var(--management-line);
|
||||
}
|
||||
|
||||
.management-page .analysis-composer > label {
|
||||
color: var(--management-ink);
|
||||
}
|
||||
|
||||
.management-page .analysis-composer textarea,
|
||||
.management-page .analysis-answer,
|
||||
.management-page .analysis-question p,
|
||||
.management-page .analysis-privacy-note,
|
||||
.management-page .snapshot-details {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.management-page .analysis-snapshots {
|
||||
grid-template-columns: repeat(auto-fit, minmax(min(100%, 320px), 1fr));
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.management-page .snapshot-card {
|
||||
border-color: var(--management-line);
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.management-page .analysis-steps span {
|
||||
max-width: 100%;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.inspection-ai-summary {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px 12px;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid var(--management-line);
|
||||
background: #f8faff;
|
||||
color: var(--management-ink);
|
||||
}
|
||||
|
||||
.inspection-ai-summary > span {
|
||||
min-width: min(100%, 260px);
|
||||
flex: 1 1 300px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.inspection-ai-summary .ant-btn {
|
||||
flex: 0 0 auto;
|
||||
padding-inline: 4px;
|
||||
}
|
||||
|
||||
.management-page .import-result {
|
||||
padding: 0 0 12px;
|
||||
}
|
||||
|
||||
.management-page .import-result .import-validation {
|
||||
padding: 10px 15px 0;
|
||||
}
|
||||
|
||||
.management-page .import-validation-grid > span {
|
||||
min-width: 0;
|
||||
border-color: var(--management-line);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.management-page .json-result,
|
||||
.management-page .json-cell {
|
||||
width: 100%;
|
||||
max-width: 100%;
|
||||
overflow: auto;
|
||||
border: 1px solid var(--management-line);
|
||||
border-radius: 0;
|
||||
background: #f7f9fc;
|
||||
color: #253044;
|
||||
font-size: 11px;
|
||||
line-height: 1.6;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.management-page .json-result {
|
||||
max-height: 560px;
|
||||
padding: 13px 15px;
|
||||
}
|
||||
|
||||
.management-page .json-cell {
|
||||
max-height: 140px;
|
||||
padding: 7px 8px;
|
||||
}
|
||||
|
||||
.management-page .json-editor,
|
||||
.management-modal .json-editor {
|
||||
font-family: var(--mono, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace);
|
||||
line-height: 1.6;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.management-modal .json-result,
|
||||
.management-drawer .json-result {
|
||||
max-width: 100%;
|
||||
max-height: 560px;
|
||||
overflow: auto;
|
||||
padding: 12px 14px;
|
||||
border: 1px solid var(--management-line);
|
||||
border-radius: 0;
|
||||
background: #f7f9fc;
|
||||
color: #253044;
|
||||
font: 11px/1.6 var(--mono, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace);
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.management-page .ant-btn,
|
||||
.management-page .ant-select-selector,
|
||||
.management-page .ant-input,
|
||||
.management-page .ant-input-affix-wrapper,
|
||||
.management-page .ant-picker,
|
||||
.management-page .ant-segmented,
|
||||
.management-modal .ant-btn,
|
||||
.management-modal .ant-input,
|
||||
.management-modal .ant-select-selector,
|
||||
.management-drawer .ant-btn {
|
||||
border-radius: 0 !important;
|
||||
}
|
||||
|
||||
.management-page .ant-btn,
|
||||
.management-drawer .ant-btn,
|
||||
.management-modal .ant-btn {
|
||||
transition-duration: 140ms;
|
||||
}
|
||||
|
||||
.management-page .ant-tabs-tab,
|
||||
.management-page .ant-tabs-ink-bar {
|
||||
transition-duration: 170ms;
|
||||
}
|
||||
|
||||
.management-page .ant-tabs-nav {
|
||||
margin: 0 15px 10px;
|
||||
}
|
||||
|
||||
.management-page .section-panel > .ant-tabs > .ant-tabs-nav {
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.management-page .ant-tabs-tab-btn {
|
||||
color: #475467;
|
||||
}
|
||||
|
||||
.management-page .ant-tabs-tab-active .ant-tabs-tab-btn {
|
||||
color: var(--management-ink) !important;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.management-page .ant-tabs-ink-bar {
|
||||
background: #3559dc;
|
||||
}
|
||||
|
||||
.management-page .task-detail-summary > span,
|
||||
.management-page .object-cell small {
|
||||
color: var(--management-muted);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.management-drawer,
|
||||
.management-modal {
|
||||
--management-ink: #111111;
|
||||
--management-muted: #667085;
|
||||
--management-line: #dce3ee;
|
||||
}
|
||||
|
||||
.management-drawer .ant-drawer-content,
|
||||
.management-modal .ant-modal-container,
|
||||
.management-modal .ant-modal-content {
|
||||
border-radius: 0 !important;
|
||||
background: var(--surface, #fff);
|
||||
}
|
||||
|
||||
.management-drawer .ant-drawer-content-wrapper {
|
||||
max-width: 100vw;
|
||||
transition-duration: 200ms !important;
|
||||
}
|
||||
|
||||
.management-drawer .ant-drawer-header {
|
||||
padding: 15px 19px;
|
||||
border-bottom-color: var(--management-line);
|
||||
}
|
||||
|
||||
.management-drawer .ant-drawer-body {
|
||||
min-width: 0;
|
||||
padding: 16px 19px;
|
||||
overflow-x: hidden;
|
||||
}
|
||||
|
||||
.management-drawer .ant-drawer-title,
|
||||
.management-modal .ant-modal-title {
|
||||
color: var(--management-ink);
|
||||
font-size: 15px;
|
||||
font-weight: 650;
|
||||
}
|
||||
|
||||
.ant-modal.management-modal {
|
||||
max-width: calc(100vw - 24px);
|
||||
}
|
||||
|
||||
.management-modal .ant-modal-header,
|
||||
.management-modal .ant-modal-footer {
|
||||
border-color: var(--management-line);
|
||||
}
|
||||
|
||||
.management-modal .ant-modal-header {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.management-modal .ant-modal-footer {
|
||||
margin-top: 16px;
|
||||
padding-top: 12px;
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.management-page .analysis-workspace {
|
||||
grid-template-columns: minmax(190px, 220px) minmax(0, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 760px) {
|
||||
.management-page {
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.management-page > .page-heading {
|
||||
align-items: flex-start;
|
||||
flex-direction: row;
|
||||
flex-wrap: wrap;
|
||||
gap: 9px 12px;
|
||||
}
|
||||
|
||||
.management-page > .page-heading > div:first-child {
|
||||
flex: 1 1 100%;
|
||||
}
|
||||
|
||||
.management-page .page-heading h1 {
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.management-page .page-heading-actions {
|
||||
width: auto;
|
||||
max-width: 100%;
|
||||
justify-content: flex-start;
|
||||
}
|
||||
|
||||
.management-page .page-heading-actions .ant-btn {
|
||||
min-width: 0;
|
||||
flex: 0 1 auto;
|
||||
height: auto;
|
||||
min-height: 30px;
|
||||
white-space: normal;
|
||||
}
|
||||
|
||||
.management-page .analysis-workspace {
|
||||
min-height: 0;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.management-page .analysis-session-panel {
|
||||
max-height: 190px;
|
||||
}
|
||||
|
||||
.management-page .analysis-chat-panel {
|
||||
min-height: 620px;
|
||||
}
|
||||
|
||||
.management-page .analysis-context-bar > .ant-select {
|
||||
min-width: 0;
|
||||
max-width: none;
|
||||
flex: 1 1 135px;
|
||||
}
|
||||
|
||||
.management-page .analysis-context-bar > .ant-checkbox-wrapper {
|
||||
flex-basis: 100%;
|
||||
}
|
||||
|
||||
.management-page .analysis-conversation {
|
||||
min-height: 250px;
|
||||
padding: 11px;
|
||||
}
|
||||
|
||||
.management-page .resource-toolbar {
|
||||
padding: 8px 11px;
|
||||
}
|
||||
|
||||
.management-page .resource-toolbar span {
|
||||
flex-basis: 100%;
|
||||
order: 2;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.management-page .resource-toolbar .ant-btn {
|
||||
order: 1;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.management-page .access-summary {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
.management-page .access-summary > div {
|
||||
min-height: 74px;
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
.management-page .access-summary > div:nth-child(2) {
|
||||
border-right: 0;
|
||||
}
|
||||
|
||||
.management-page .access-summary > div:nth-child(-n+2) {
|
||||
border-bottom: 1px solid var(--management-line);
|
||||
}
|
||||
|
||||
.management-page .json-result {
|
||||
padding: 10px;
|
||||
font-size: 10px;
|
||||
}
|
||||
|
||||
.management-drawer .ant-drawer-header {
|
||||
padding: 13px 14px;
|
||||
}
|
||||
|
||||
.management-drawer .ant-drawer-body {
|
||||
padding: 12px 14px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 420px) {
|
||||
.management-page .resource-toolbar {
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
.management-page .resource-toolbar .ant-btn {
|
||||
margin-left: 0;
|
||||
}
|
||||
|
||||
.management-page .access-summary {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.management-page .access-summary > div {
|
||||
min-height: 0;
|
||||
border-right: 0;
|
||||
border-bottom: 1px solid var(--management-line);
|
||||
}
|
||||
|
||||
.management-page .access-summary > div:last-child {
|
||||
border-bottom: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.management-page .ant-btn,
|
||||
.management-page .analysis-session-item,
|
||||
.management-page .ant-tabs-tab,
|
||||
.management-page .ant-tabs-ink-bar,
|
||||
.management-drawer .ant-drawer-content-wrapper {
|
||||
transition-duration: 0.01ms !important;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
.nc-intake-start { padding: 26px 28px 0; display: grid; grid-template-columns: minmax(320px, 1fr) auto; column-gap: 28px; }
|
||||
.nc-eyebrow { display: block; font-size: 11px; font-weight: 650; letter-spacing: .08em; margin-bottom: 7px; }
|
||||
.nc-intake-intro h2 { margin: 0 0 8px; font-size: 25px; line-height: 1.3; letter-spacing: -.025em; color: var(--ink); }
|
||||
.nc-intake-intro p { margin: 0; line-height: 1.7; font-size: 13px; color: var(--ink); }
|
||||
.nc-primary-actions { display: flex; gap: 10px; align-items: center; }
|
||||
.nc-primary-actions .ant-btn { height: 44px; padding: 0 21px; border-radius: 0; font-size: 14px; }
|
||||
.nc-intake-links { grid-column: 1 / -1; display: flex; align-items: center; gap: 14px; border-top: 1px solid #e0e4e9; margin-top: 24px; min-height: 51px; }
|
||||
.nc-intake-links .ant-btn { padding-left: 0; padding-right: 0; font-size: 12px; color: var(--ink); }
|
||||
.nc-intake-links > span { margin-left: auto; font-size: 11px; color: var(--ink); }
|
||||
.nc-pending-strip { padding: 15px 19px; display: flex; gap: 20px; align-items: center; justify-content: space-between; }
|
||||
.nc-pending-strip > div:first-child { display: flex; gap: 15px; align-items: center; font-size: 12px; }
|
||||
.nc-pending-strip .ant-select { min-width: 350px; }
|
||||
.nc-advanced-records { border-top: 1px solid #dce3ee; padding-top: 13px; }
|
||||
.nc-advanced-records > summary { cursor: pointer; font-size: 12px; padding: 6px 0; color: var(--ink); }
|
||||
.nc-advanced-records[open] > summary { margin-bottom: 12px; }
|
||||
.nc-workflow-modal { top: 24px; padding-bottom: 24px; }
|
||||
.nc-workflow-modal .ant-modal-container, .nc-workflow-modal .ant-modal-content, .nc-workflow-modal .ant-input, .nc-workflow-modal .ant-input-number, .nc-workflow-modal .ant-select-selector, .nc-workflow-modal .ant-btn, .nc-workflow-modal .ant-alert { border-radius: 0 !important; }
|
||||
.nc-workflow-modal .ant-modal-body { display: flex; flex-direction: column; gap: 18px; max-height: calc(100vh - 240px); overflow-y: auto; overflow-x: hidden; padding-right: 4px; color: var(--ink); }
|
||||
.nc-workflow-modal .ant-modal-title { font-size: 20px; color: var(--ink); }
|
||||
.nc-workflow-modal h3 { font-size: 14px; margin: 4px 0 12px; color: var(--ink); }
|
||||
.nc-workflow-modal .ant-form-item { margin-bottom: 16px; }
|
||||
.nc-workflow-modal .ant-form-item-label > label { color: var(--ink); font-size: 12px; }
|
||||
.nc-steps { margin: 8px 0 10px; padding-bottom: 18px; border-bottom: 1px solid #e0e4e9; }
|
||||
.nc-modal-footer { display: flex; justify-content: space-between; align-items: center; gap: 16px; padding-top: 8px; text-align: left; }
|
||||
.nc-modal-footer > span { font-size: 11px; color: var(--ink); }
|
||||
.nc-modal-footer > div { display: flex; flex-shrink: 0; gap: 8px; }
|
||||
.nc-file-drop { border: 1px dashed #bfc9d6; background: #f8faff; min-height: 260px; display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 30px; }
|
||||
.nc-file-drop > .anticon { font-size: 40px; margin-bottom: 16px; color: var(--ink); }
|
||||
.nc-file-drop h3 { font-size: 18px; margin: 0 0 10px; }
|
||||
.nc-file-drop p { font-size: 12px; margin-bottom: 22px; }
|
||||
.nc-file-summary { display: flex; align-items: center; gap: 12px; background: #f6f8fd; padding: 12px 16px; border: 1px solid #dce3ee; font-size: 12px; }
|
||||
.nc-file-summary > .anticon { font-size: 22px; }
|
||||
.nc-file-summary strong { overflow-wrap: anywhere; }
|
||||
.nc-file-summary > span:last-child { margin-left: auto; white-space: nowrap; }
|
||||
.nc-form-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0 16px; }
|
||||
.nc-form-grid .ant-select, .nc-form-grid .ant-input-number { width: 100%; }
|
||||
.nc-full-width { grid-column: 1 / -1; }
|
||||
.nc-replacement { display: flex; align-items: center; gap: 9px 14px; flex-wrap: wrap; background: #fffaf0; border: 1px solid #e9d8af; padding: 14px 16px; margin-bottom: 18px; font-size: 12px; }
|
||||
.nc-replacement > span { color: var(--ink); }
|
||||
.nc-replacement > strong { max-width: 380px; overflow-wrap: anywhere; }
|
||||
.nc-section-title { display: flex; justify-content: space-between; align-items: center; gap: 16px; margin-top: 2px; }
|
||||
.nc-section-title h3 { margin: 0 0 10px; }
|
||||
.nc-section-title > span { font-size: 11px; color: var(--ink); }
|
||||
.nc-column-matching { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 0 24px; border-top: 1px solid #dce3ee; margin-bottom: 16px; }
|
||||
.nc-field-match { display: grid; grid-template-columns: minmax(125px, 1fr) minmax(145px, 1.3fr); align-items: center; gap: 12px; padding: 9px 0; border-bottom: 1px solid #e4e8ef; font-size: 12px; }
|
||||
.nc-field-match > span { display: flex; gap: 7px; align-items: center; flex-wrap: wrap; }
|
||||
.nc-field-match b { font-size: 10px; font-weight: 500; padding: 1px 4px; background: #edf2fb; }
|
||||
.nc-field-match small { font-size: 10px; }
|
||||
.nc-field-match .ant-select { min-width: 0; width: 100%; }
|
||||
.nc-workbook-upload-intro { display: flex; justify-content: space-between; gap: 20px; align-items: center; padding: 16px; background: #f6f8fd; border: 1px solid #dce3ee; margin-bottom: 16px; }
|
||||
.nc-workbook-upload-intro strong { font-size: 13px; }
|
||||
.nc-workbook-upload-intro p { font-size: 12px; margin: 6px 0 0; line-height: 1.6; }
|
||||
.nc-workbook-upload-intro .ant-btn { flex-shrink: 0; }
|
||||
.nc-review-facts { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); border: 1px solid #dce3ee; margin-bottom: 16px; }
|
||||
.nc-review-facts > div { padding: 14px 16px; border-right: 1px solid #dce3ee; display: flex; flex-direction: column; gap: 8px; }
|
||||
.nc-review-facts > div:last-child { border-right: 0; }
|
||||
.nc-review-facts small { color: var(--ink); font-size: 11px; }
|
||||
.nc-review-facts strong { color: var(--ink); font-size: 14px; overflow-wrap: anywhere; }
|
||||
.nc-note { font-size: 12px; line-height: 1.65; margin: 12px 0 0; color: var(--ink); }
|
||||
.nc-processing { padding: 22px; text-align: center; background: #f6f8fd; border: 1px solid #dce3ee; }
|
||||
.nc-processing .ant-progress { max-width: 600px; }
|
||||
.nc-processing h3 { margin-top: 16px; }
|
||||
.nc-issue-list { margin: 0; padding-left: 18px; font-size: 12px; line-height: 1.7; }
|
||||
.nc-difference-confirm { display: flex; flex-direction: column; gap: 14px; margin-top: 18px; padding-top: 18px; border-top: 1px solid #dce3ee; }
|
||||
.nc-difference-confirm .ant-btn { align-self: flex-end; }
|
||||
.nc-publish-confirm { display: flex; gap: 16px; align-items: center; flex-wrap: wrap; padding: 20px 0 0; margin-top: 20px; border-top: 1px solid #dce3ee; }
|
||||
.nc-publish-confirm > .ant-btn { margin-left: auto; }
|
||||
.nc-publish-confirm > span { width: 100%; font-size: 11px; }
|
||||
.nc-success { text-align: center; padding: 55px 20px; color: var(--ink); }
|
||||
.nc-success > .anticon { font-size: 40px; margin-bottom: 14px; }
|
||||
.nc-success h2 { font-size: 22px; }
|
||||
.nc-success p { font-size: 13px; }
|
||||
.nc-target-list { max-height: 240px; overflow: auto; border: 1px solid #dce3ee; margin: 18px 0; }
|
||||
.nc-target-list > div { display: flex; gap: 14px; align-items: center; border-bottom: 1px solid #e4e8ef; padding: 10px 12px; font-size: 12px; }
|
||||
.nc-target-list > div:last-child { border-bottom: 0; }
|
||||
.nc-target-list > div > span:last-child { overflow-wrap: anywhere; }
|
||||
.nc-rebuild-confirm p { font-size: 13px; line-height: 1.7; }
|
||||
.nc-source-files .resource-toolbar > .ant-checkbox-wrapper { margin-left: auto; font-size: 12px; flex: 0 0 auto; white-space: nowrap; }
|
||||
.management-page .nc-source-files .resource-toolbar > .ant-checkbox-wrapper > span { flex: 0 0 auto; order: initial; text-align: left; overflow-wrap: normal; white-space: nowrap; }
|
||||
.nc-source-files .ant-table-cell .ant-btn { font-size: 12px; }
|
||||
.nc-source-delete-modal .nc-file-summary { margin-bottom: 20px; }
|
||||
.nc-source-delete-modal .ant-spin-container { display: flex; flex-direction: column; gap: 17px; }
|
||||
.nc-source-delete-modal .nc-review-facts, .nc-source-delete-modal .nc-file-summary { margin-bottom: 0; }
|
||||
.nc-delete-steps { padding: 3px 0 16px; border-bottom: 1px solid #dce3ee; }
|
||||
.nc-delete-request { border: 1px solid #dce3ee; padding: 14px 16px; background: #f6f8fd; }
|
||||
.nc-delete-request > div { display: flex; gap: 14px; align-items: center; font-size: 13px; }
|
||||
.nc-delete-request p { display: grid; grid-template-columns: 70px minmax(0, 1fr); gap: 14px; margin: 10px 0 0; font-size: 12px; line-height: 1.7; overflow-wrap: anywhere; }
|
||||
.nc-delete-request p > span { font-weight: 600; }
|
||||
.nc-source-delete-modal .nc-deletion-impact { grid-template-columns: repeat(4, minmax(0, 1fr)); }
|
||||
.nc-source-delete-modal .ant-alert p { margin: 0 0 7px; }
|
||||
/* TEST-mode maintenance: keep the existing 5276 square, compact visual language. */
|
||||
.nc-simplified-intake, .nc-simplified-config-page, .nc-simplified-releases { color: var(--ink); }
|
||||
.nc-simple-upload-panel { padding: 20px 22px; display: flex; flex-direction: column; gap: 16px; }
|
||||
.nc-simple-upload-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 24px; padding-bottom: 14px; border-bottom: 1px solid #dce3ee; }
|
||||
.nc-simple-upload-heading h2 { margin: 0 0 5px; color: var(--ink); font-size: 21px; line-height: 1.35; }
|
||||
.nc-simple-upload-heading p { margin: 0; color: var(--ink); font-size: 12px; line-height: 1.6; }
|
||||
.nc-simple-upload-actions { display: flex; gap: 8px; align-items: center; flex: 0 0 auto; }
|
||||
.nc-simple-upload-actions .ant-btn, .nc-simplified-intake .ant-btn, .nc-simplified-config-page .ant-btn, .nc-simplified-releases .ant-btn { border-radius: 0; }
|
||||
.nc-simple-file-drop { min-height: 190px; padding: 22px; }
|
||||
.nc-simple-file-drop > .anticon { font-size: 30px; margin-bottom: 8px; }
|
||||
.nc-simple-file-drop h3 { font-size: 15px; margin: 0 0 5px; }
|
||||
.nc-simple-file-drop p { margin: 0 0 13px; font-size: 12px; }
|
||||
.nc-simple-file-line { display: flex; gap: 10px; align-items: center; min-width: 0; padding: 10px 12px; border: 1px solid #dce3ee; background: #f6f8fd; font-size: 12px; }
|
||||
.nc-simple-file-line > .anticon { flex: 0 0 auto; font-size: 19px; }
|
||||
.nc-simple-file-line strong { min-width: 0; overflow-wrap: anywhere; }
|
||||
.nc-simple-file-line .ant-btn { margin-left: auto; flex: 0 0 auto; }
|
||||
.nc-simple-upload-fields { display: grid; grid-template-columns: repeat(4, minmax(130px, 1fr)); gap: 12px; }
|
||||
.nc-simple-upload-fields > label { display: flex; flex-direction: column; gap: 6px; color: var(--ink); font-size: 12px; }
|
||||
.nc-simple-upload-fields .ant-select, .nc-simple-upload-fields .ant-input-number { width: 100%; }
|
||||
.nc-simple-replace-target { grid-column: span 2; }
|
||||
.nc-simple-upload-panel .ant-input-number, .nc-simple-upload-panel .ant-select-selector, .nc-simple-upload-panel .ant-input, .nc-simple-upload-panel .ant-alert { border-radius: 0 !important; }
|
||||
.nc-advanced-import-settings { border-top: 1px solid #dce3ee; padding-top: 10px; }
|
||||
.nc-advanced-import-settings > summary { color: var(--ink); cursor: pointer; font-size: 12px; padding: 2px 0 7px; }
|
||||
.nc-advanced-import-settings[open] > summary { margin-bottom: 10px; }
|
||||
.nc-simple-submit-row { display: flex; gap: 18px; align-items: center; justify-content: space-between; border-top: 1px solid #dce3ee; padding-top: 14px; }
|
||||
.nc-simple-submit-row > span { color: var(--ink); font-size: 12px; line-height: 1.55; }
|
||||
.nc-simple-submit-row .ant-btn { min-width: 176px; height: 40px; }
|
||||
.nc-operation-status { display: grid; grid-template-columns: minmax(180px, 1fr) minmax(180px, 2fr); gap: 4px 18px; align-items: center; padding: 12px 16px; }
|
||||
.nc-operation-status > div:not(.ant-alert) { display: flex; flex-direction: column; gap: 3px; min-width: 0; }
|
||||
.nc-operation-status > div:not(.ant-alert) > strong { color: var(--ink); font-size: 13px; }
|
||||
.nc-operation-status > div:not(.ant-alert) > span { overflow-wrap: anywhere; color: var(--ink); font-size: 11px; }
|
||||
.nc-operation-status .ant-alert { grid-column: 1 / -1; border-radius: 0; }
|
||||
.nc-source-maintenance-note { margin: 0; padding: 0 18px 12px; color: var(--ink); font-size: 12px; line-height: 1.6; }
|
||||
.nc-simple-current-config { padding: 18px 20px; }
|
||||
.nc-simple-current-config > .ant-form { max-width: 850px; }
|
||||
.nc-simple-config-tabs { margin-top: 12px; }
|
||||
.nc-simple-config-tabs > .ant-tabs-nav { margin-bottom: 12px; }
|
||||
.nc-simple-config-intro { display: flex; gap: 14px; align-items: center; justify-content: space-between; margin-bottom: 12px; }
|
||||
.nc-simple-config-intro > .ant-alert { flex: 1; border-radius: 0; }
|
||||
.nc-simple-config-intro .ant-alert-message, .nc-simple-config-intro .ant-alert-description { color: var(--ink); }
|
||||
.nc-simple-save-row { display: flex; gap: 18px; align-items: center; justify-content: space-between; border-top: 1px solid #dce3ee; margin-top: 18px; padding-top: 16px; }
|
||||
.nc-simple-save-row > span { color: var(--ink); font-size: 12px; line-height: 1.6; }
|
||||
.nc-simple-save-row .ant-btn { min-width: 200px; height: 42px; }
|
||||
.nc-simple-history { padding-bottom: 4px; }
|
||||
.nc-simple-config-intro + .structured-config-editor, .nc-simple-config-tabs .structured-config-editor { margin-top: 10px; }
|
||||
.nc-simple-config-tabs .ant-table-thead > tr > th, .nc-simple-history .ant-table-thead > tr > th, .nc-simplified-releases .ant-table-thead > tr > th { background: #edf2fb; color: var(--ink); }
|
||||
.nc-simple-config-page .ant-form-item-label > label { color: var(--ink); font-size: 12px; }
|
||||
.nc-simple-config-page .ant-input, .nc-simple-config-page .ant-select-selector, .nc-simple-config-page .ant-input-number, .nc-simple-config-page .ant-alert { border-radius: 0 !important; }
|
||||
.nc-simple-config-page .ant-table-cell, .nc-simplified-releases .ant-table-cell { font-size: 12px; color: var(--ink); }
|
||||
.nc-simple-config-page .json-result { max-height: 320px; overflow: auto; background: #f6f8fd; border: 1px solid #dce3ee; padding: 12px; font-size: 11px; }
|
||||
.nc-simplified-releases .resource-table { padding: 0 16px 16px; }
|
||||
.nc-simplified-releases .resource-toolbar { margin-bottom: 8px; }
|
||||
@media (max-width: 850px) {
|
||||
.nc-simple-upload-heading { flex-direction: column; gap: 12px; }
|
||||
.nc-simple-upload-fields { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.nc-simple-config-intro { align-items: stretch; flex-direction: column; }
|
||||
.nc-operation-status { grid-template-columns: 1fr; }
|
||||
}
|
||||
@media (max-width: 600px) {
|
||||
.nc-simple-upload-panel, .nc-simple-current-config { padding: 14px; }
|
||||
.nc-simple-upload-fields { grid-template-columns: 1fr; }
|
||||
.nc-simple-replace-target { grid-column: auto; }
|
||||
.nc-simple-submit-row, .nc-simple-save-row { align-items: stretch; flex-direction: column; }
|
||||
.nc-simple-submit-row .ant-btn, .nc-simple-save-row .ant-btn { width: 100%; }
|
||||
}
|
||||
@media (max-width: 1050px) { .nc-intake-start { grid-template-columns: 1fr; } .nc-primary-actions { margin-top: 20px; } .nc-intake-links { flex-wrap: wrap; gap: 0 16px; padding: 8px 0; } .nc-intake-links > span { margin-left: 0; width: 100%; padding: 5px 0; } .nc-column-matching { grid-template-columns: 1fr; } .nc-pending-strip { align-items: flex-start; flex-direction: column; } .nc-pending-strip .ant-select { min-width: 0; width: 100%; } }
|
||||
@media (max-width: 680px) { .nc-intake-start { padding: 20px 18px 0; } .nc-intake-intro h2 { font-size: 22px; } .nc-primary-actions { flex-wrap: wrap; } .nc-form-grid { grid-template-columns: 1fr; } .nc-modal-footer { flex-direction: column; align-items: stretch; } .nc-modal-footer > div { justify-content: flex-end; flex-wrap: wrap; } .nc-file-summary { flex-wrap: wrap; } .nc-file-summary > span:last-child { margin-left: 0; } .nc-workbook-upload-intro { flex-direction: column; align-items: flex-start; } .nc-pending-strip > div:first-child { align-items: flex-start; flex-direction: column; gap: 6px; } .nc-review-facts { grid-template-columns: 1fr 1fr; } }
|
||||
@media (max-width: 680px) { .nc-source-delete-modal .nc-deletion-impact { grid-template-columns: 1fr 1fr; } }
|
||||
@@ -0,0 +1,10 @@
|
||||
export function previousCompleteMonth(reference = new Date()): { year: number; month: number } {
|
||||
const previous = new Date(reference.getFullYear(), reference.getMonth() - 1, 1);
|
||||
return { year: previous.getFullYear(), month: previous.getMonth() + 1 };
|
||||
}
|
||||
|
||||
export function previousCompleteQuarter(reference = new Date()): { year: number; quarter: number } {
|
||||
const firstMonthOfCurrentQuarter = Math.floor(reference.getMonth() / 3) * 3;
|
||||
const previousQuarterEnd = new Date(reference.getFullYear(), firstMonthOfCurrentQuarter, 0);
|
||||
return { year: previousQuarterEnd.getFullYear(), quarter: Math.floor(previousQuarterEnd.getMonth() / 3) + 1 };
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// Presentation only: request payloads and concurrency fields retain their original values.
|
||||
export function isInternalDataField(key: string): boolean {
|
||||
return /^(?:(?:current|expected|expectedCurrent|baseline|new|base|result|source|target|pinned)?(?:releaseId|mappingVersionId|ruleVersionId|targetVersionId|masterDataVersionId)|schemaVersion|rowVersion|revisionId|engineVersion|engineRuleVersion|ruleVersion|rulesVersion|mappingVersion|targetVersion|masterDataVersion|configVersion|baselineSha256)$/i.test(key);
|
||||
}
|
||||
|
||||
export function publicJson(value: unknown): string | undefined {
|
||||
return JSON.stringify(value, (key, child) => isInternalDataField(key) ? undefined : child, 2);
|
||||
}
|
||||
|
||||
export function publicErrorMessage(message: string): string {
|
||||
return message
|
||||
.replace(/(?:数据|发布|规则|映射|目标|配置)版本(?:\s*[((]?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}[))]?)?/gi, '当前数据或配置')
|
||||
.replace(/(?:releaseId|mappingVersionId|ruleVersionId|targetVersionId)\s*[:=:]?\s*[0-9a-f-]{36}/gi, '当前数据或配置');
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
.chart-container.chart-empty { display: none; }
|
||||
.chart-container svg { display: block; }
|
||||
.source-records-drawer .ant-drawer-content,
|
||||
.source-records-drawer .ant-drawer-header,
|
||||
.source-records-drawer .ant-drawer-body { background: var(--surface, #fff); }
|
||||
.source-records-drawer .ant-drawer-header { border-bottom-color: var(--line); }
|
||||
.readable-select-popup.ant-select-dropdown {
|
||||
background: var(--surface, #fff) !important;
|
||||
border: 1px solid var(--line);
|
||||
box-shadow: 0 6px 18px rgba(18, 30, 52, .18);
|
||||
opacity: 1;
|
||||
}
|
||||
.source-records-drawer .ant-table-tbody > tr > td { padding: 8px 9px; vertical-align: top; }
|
||||
.source-fields summary { width: fit-content; color: var(--blue-dark); cursor: pointer; font-size: 12px; }
|
||||
.source-fields .json-cell { margin-top: 7px; }
|
||||
.source-raw-fields { min-width: 220px; }
|
||||
.source-raw-fields > p { margin: 7px 0 0; color: var(--ink-muted); font-size: 11px; line-height: 1.5; }
|
||||
.source-raw-fields .json-cell { max-width: 420px; max-height: 220px; padding: 8px; border: 1px solid var(--line); background: var(--surface-subtle, #f7f9fc); }
|
||||
.organization-breadcrumb {
|
||||
flex: 1 0 100%; display: flex; align-items: center; flex-wrap: wrap; gap: 4px 10px;
|
||||
padding: 7px 10px; border-radius: 9px; background: #f6f8fb; color: #657087; font-size: 12px;
|
||||
}
|
||||
.organization-breadcrumb > span:first-child { color: #657087; font-weight: 600; }
|
||||
.organization-crumb { display: inline-flex; align-items: center; gap: 5px; color: var(--ink); }
|
||||
.organization-crumb > i { color: #657087; font-style: normal; }
|
||||
.organization-crumb .ant-btn { height: auto; padding-inline: 3px; font-size: 11px; }
|
||||
.rate-basis-control { grid-column: 1 / -1; display: flex; align-items: center; justify-content: flex-end; gap: 9px; color: #657087; font-size: 12px; }
|
||||
.object-drilldown { padding: 0; height: auto; font-weight: 650; }
|
||||
.object-drilldown > span { margin-left: 5px; color: var(--ink-muted); font-size: 16px; }
|
||||
.trend-granularity { min-width: 132px; }
|
||||
.record-query-tools {
|
||||
display: grid; grid-template-columns: minmax(170px, .85fr) minmax(180px, 1fr) minmax(220px, 1.3fr) minmax(160px, .8fr) auto;
|
||||
gap: 10px; align-items: end; margin: 10px 0 14px;
|
||||
}
|
||||
.record-query-tools > label { display: grid; gap: 5px; color: var(--ink-muted); font-size: 11px; }
|
||||
.record-query-tools .ant-select { width: 100%; }
|
||||
.record-query-tools .ant-segmented { align-self: end; }
|
||||
.record-query-tools + .ant-alert { margin-bottom: 12px; }
|
||||
.source-records-drawer .ant-table-cell { max-width: 260px; }
|
||||
.source-records-drawer .source-fields ul { padding-left: 18px; margin: 6px 0; color: var(--ink-muted); font-size: 12px; }
|
||||
@media (max-width: 900px) {
|
||||
.record-query-tools { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.record-query-tools > .ant-segmented { grid-column: 2; }
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
// Keep the control compact while giving long option labels room in its popup.
|
||||
export const readableSelectPopup = {
|
||||
popupMatchSelectWidth: 280,
|
||||
classNames: { popup: { root: 'readable-select-popup' } },
|
||||
} as const;
|
||||
@@ -0,0 +1,38 @@
|
||||
.structured-config-editor { color: var(--ink); min-width: 0; }
|
||||
.structured-config-editor .ant-tabs-nav { margin: 0 0 14px; }
|
||||
.structured-config-toolbar, .structured-config-intro { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; margin-bottom: 14px; }
|
||||
.structured-config-toolbar > .ant-input-search { width: 230px; }
|
||||
.structured-config-toolbar > .ant-select { min-width: 115px; }
|
||||
.structured-config-toolbar > span { font-size: 12px; }
|
||||
.structured-config-actions { display: flex; flex-wrap: wrap; gap: 7px; margin-left: auto; }
|
||||
.structured-config-intro { justify-content: space-between; background: #f6f8fd; border: 1px solid #dce3ee; padding: 12px 14px; }
|
||||
.structured-config-intro p, .structured-config-note { color: var(--ink); font-size: 12px; line-height: 1.65; margin: 0; }
|
||||
.structured-config-note { margin-top: 10px; }
|
||||
.structured-config-muted { color: #657185; }
|
||||
.structured-config-editor .ant-table-thead > tr > th { background: #f6f8fd; color: var(--ink); }
|
||||
.structured-config-editor .ant-table-cell { font-size: 12px; overflow-wrap: anywhere; }
|
||||
.structured-config-editor .ant-table-container, .structured-config-editor .ant-btn, .structured-config-editor .ant-input, .structured-config-editor .ant-select-selector, .structured-config-modal .ant-btn, .structured-config-modal .ant-input, .structured-config-modal .ant-select-selector { border-radius: 0 !important; }
|
||||
.structured-config-modal .ant-modal-body { max-height: 72vh; overflow-y: auto; padding-top: 16px; }
|
||||
.structured-config-modal p { color: var(--ink); font-size: 12px; line-height: 1.65; }
|
||||
.structured-config-modal .ant-checkbox-wrapper { margin: 12px 0; }
|
||||
.structured-config-form-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; }
|
||||
.structured-config-select-hint { padding: 8px 12px; color: #667085; font-size: 12px; border-top: 1px solid #dce3ee; }
|
||||
.structured-config-technical { margin-top: 18px; padding-top: 14px; border-top: 1px solid #dce3ee; }
|
||||
.structured-config-technical summary { cursor: pointer; font-size: 12px; margin-bottom: 12px; }
|
||||
.structured-config-technical > .ant-btn { margin-top: 8px; }
|
||||
.structured-config-rule-list { display: flex; flex-direction: column; gap: 14px; }
|
||||
.structured-config-rule-card { border: 1px solid #dce3ee; padding: 14px; background: #fff; }
|
||||
.structured-config-rule-card h4 { margin: 0 0 12px; color: var(--ink); }
|
||||
.structured-config-rule-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; }
|
||||
.structured-config-rule-grid > div:first-child { grid-column: 1 / -1; }
|
||||
.structured-config-rule-grid label { display: block; margin-bottom: 6px; font-size: 12px; }
|
||||
.structured-config-rule-grid .ant-form-item { margin-bottom: 10px; }
|
||||
.structured-config-error-list { margin: 8px 0 0; padding-left: 20px; max-height: 180px; overflow: auto; }
|
||||
.structured-match-editor .structured-config-toolbar { align-items: flex-start; }
|
||||
.structured-match-editor .structured-config-toolbar > span { max-width: 780px; line-height: 1.6; }
|
||||
.structured-match-editor .structured-match-readable { display: block; color: var(--ink); font-size: 12px; line-height: 1.6; white-space: normal; }
|
||||
.structured-match-editor .ant-table-cell { vertical-align: top; }
|
||||
.structured-match-editor .ant-table-cell .ant-select-selector, .structured-match-editor .ant-table-cell .ant-input { border-radius: 0 !important; }
|
||||
.structured-match-editor .ant-table-thead > tr > th { background: #edf2fb; color: var(--ink); }
|
||||
.nc-simple-config-page .structured-config-toolbar > span { color: var(--ink); }
|
||||
@media (max-width: 720px) { .structured-config-toolbar > .ant-input-search { width: 100%; } .structured-config-actions { margin-left: 0; width: 100%; } .structured-config-form-grid, .structured-config-rule-grid { grid-template-columns: 1fr; } }
|
||||
@@ -0,0 +1,574 @@
|
||||
:root {
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
|
||||
color: #111111;
|
||||
background: #f4f6fb;
|
||||
font-synthesis: none;
|
||||
text-rendering: optimizeLegibility;
|
||||
--ink: #111111;
|
||||
--blue: #607ae1;
|
||||
--blue-dark: #3f4fb3;
|
||||
--teal: #008f7d;
|
||||
--line: #dfe5ef;
|
||||
--surface: #ffffff;
|
||||
--sidebar-surface: #f8fafd;
|
||||
--sidebar: 202px;
|
||||
--mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
html, body, #root { min-width: 320px; min-height: 100%; margin: 0; }
|
||||
body { color: var(--ink); background: #f4f6fb; font-size: 14px; }
|
||||
button, input, textarea, select { font: inherit; }
|
||||
button { color: inherit; }
|
||||
.app-shell { min-height: 100vh; }
|
||||
.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); }
|
||||
.brand { display: flex; align-items: center; gap: 11px; min-height: 34px; padding: 0 7px; border: 0; background: transparent; text-align: left; font-size: 19px; font-weight: 700; cursor: pointer; }
|
||||
.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); }
|
||||
.brand-mark i:nth-child(2) { height: 21px; opacity: .76; }
|
||||
.brand-mark i:nth-child(3) { height: 13px; opacity: .52; }
|
||||
.workspace-caption { padding: 5px 7px 17px; font-size: 12px; font-weight: 600; }
|
||||
.side-navigation { flex: 1; overflow: auto; scrollbar-width: thin; }
|
||||
.nav-group { margin-top: 12px; }
|
||||
.nav-group-label { padding: 7px 9px 6px; color: var(--ink); font-size: 12px; 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: 13px; }
|
||||
.nav-item .anticon { width: 16px; color: var(--ink); font-size: 15px; }
|
||||
.nav-item:hover { background: #eef2fb; }
|
||||
.nav-item.active { color: var(--blue-dark); background: #e3ebff; font-weight: 650; }
|
||||
.nav-item.active .anticon { color: var(--blue); }
|
||||
.nav-group-tail { padding-top: 2px; }
|
||||
.user-block { display: flex; min-height: 52px; align-items: center; gap: 9px; padding: 9px 3px 0; border-top: 1px solid var(--line); }
|
||||
.avatar { display: inline-flex; width: 31px; height: 31px; flex: 0 0 31px; align-items: center; justify-content: center; background: #e7edf5; font-size: 13px; }
|
||||
.user-copy { display: flex; min-width: 0; flex: 1; flex-direction: column; gap: 3px; }
|
||||
.user-copy strong { overflow: hidden; font-size: 12px; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.user-copy small { overflow: hidden; font-size: 11px; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.user-block .ant-btn { width: 28px; padding: 0; }
|
||||
.main-column { min-height: 100vh; margin-left: var(--sidebar); }
|
||||
.topbar { position: sticky; top: 0; z-index: 40; display: flex; height: 44px; align-items: center; justify-content: space-between; padding: 0 22px; background: #ffffff; border-bottom: 1px solid var(--line); }
|
||||
.breadcrumb { display: flex; align-items: center; gap: 10px; font-size: 12px; }
|
||||
.breadcrumb strong { font-weight: 650; }
|
||||
.breadcrumb-slash { color: #63738a; }
|
||||
.top-organization { display: inline-flex; align-items: center; gap: 7px; font-size: 12px; }
|
||||
.mobile-brand { display: none; }
|
||||
.page-content { width: 100%; max-width: 1920px; min-width: 0; margin: 0 auto; padding: 15px 20px 20px; }
|
||||
.panel { background: var(--surface); border: 1px solid var(--line); border-radius: 0 !important; }
|
||||
.query-page { display: flex; min-width: 0; flex-direction: column; gap: 11px; }
|
||||
.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::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: 12px; }
|
||||
.query-field .ant-select { min-width: 108px; }
|
||||
.query-field .ant-select-selector { border-radius: 0 !important; }
|
||||
.query-field.release-field .ant-select { min-width: 180px; }
|
||||
.readable-select-popup { max-width: calc(100vw - 24px); }
|
||||
.readable-select-popup .ant-select-item-option-content { overflow: visible; text-overflow: clip; white-space: normal; overflow-wrap: anywhere; }
|
||||
.query-toolbar-tail { display: flex; min-width: max-content; flex: 1; align-items: center; justify-content: flex-end; gap: 8px; margin-left: auto; }
|
||||
.query-status { display: inline-flex; align-items: center; gap: 6px; font-size: 12px; white-space: nowrap; }
|
||||
.query-status i { width: 7px; height: 7px; background: var(--teal); }
|
||||
.query-status.busy i { background: #d18a2e; }
|
||||
.query-status.failed i { background: #bd342e; }
|
||||
.metric-strip { display: grid; grid-template-columns: 1.3fr 1fr 1fr 1.18fr; min-width: 0; background: #fff; border: 1px solid var(--line); }
|
||||
.metric-card { display: flex; min-width: 0; min-height: 92px; flex-direction: column; align-items: flex-start; justify-content: center; gap: 4px; padding: 11px 15px; border: 0; border-right: 1px solid var(--line); background: transparent; text-align: left; cursor: pointer; }
|
||||
.metric-card:last-child { border-right: 0; }
|
||||
.metric-card:hover { background: #f8faff; }
|
||||
.metric-card.primary { background: #e8efff; }
|
||||
.metric-label { display: inline-flex; align-items: center; gap: 7px; font-size: 13px; font-weight: 650; }
|
||||
.metric-value { overflow: hidden; max-width: 100%; font: 600 clamp(22px, 2.15vw, 31px)/1.15 var(--mono); letter-spacing: -1.2px; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.metric-card.primary .metric-value { font-size: clamp(26px, 2.5vw, 36px); }
|
||||
.metric-card.black .metric-value { color: var(--blue-dark); }
|
||||
.metric-card.bright .metric-value { color: var(--teal); }
|
||||
.metric-card small { font-size: 11px; line-height: 1.4; }
|
||||
.stage-dot { width: 7px; height: 7px; background: var(--blue); }
|
||||
.stage-dot.bright { background: var(--teal); }
|
||||
.section-panel { min-width: 0; overflow: hidden; }
|
||||
.section-heading-row { display: flex; min-height: 45px; align-items: center; justify-content: space-between; gap: 12px; padding: 8px 13px; }
|
||||
.section-heading { display: flex; min-width: 0; align-items: baseline; gap: 12px; }
|
||||
.section-heading h2 { margin: 0; font-size: 14px; font-weight: 650; }
|
||||
.section-heading > span { font-size: 12px; }
|
||||
.table-tools { display: flex; min-width: 0; align-items: center; justify-content: flex-end; gap: 7px; }
|
||||
.table-tools .ant-input-affix-wrapper { width: 205px; border-radius: 0; }
|
||||
.table-tools .ant-segmented { flex: 0 0 auto; border-radius: 0; }
|
||||
.metric-table-scroll { min-width: 0; }
|
||||
.metric-table-scroll .ant-table-wrapper { min-width: 0; }
|
||||
.metric-table-scroll .ant-table { font-size: 13px; }
|
||||
.metric-table-scroll .ant-table-container { border-color: var(--metric-grid-head) !important; }
|
||||
.metric-table-scroll .ant-table-cell { padding: 5px 9px !important; border-inline-end: 1px solid var(--metric-grid) !important; border-bottom: 1px solid var(--metric-grid) !important; text-align: center !important; white-space: normal; }
|
||||
.metric-table-scroll .ant-table-thead > tr > th { min-height: 36px; border-inline-end: 1px solid var(--metric-grid-head) !important; border-bottom: 1px solid var(--metric-grid-head) !important; text-align: center; font-size: 12px; font-weight: 650; line-height: 1.4; }
|
||||
.metric-table-scroll .ant-table-tbody > tr > td { height: 32px; }
|
||||
.metric-table-scroll .ant-table-tbody > tr > td.ant-table-cell-fix-left { background: #fff; }
|
||||
.metric-table-scroll .combined-column, .metric-table-scroll .combined-column.ant-table-cell-fix-left { background: #ebf0ff !important; }
|
||||
.metric-table-scroll th.combined-column { background: #ebf0ff !important; }
|
||||
.object-drilldown.ant-btn { height: auto; min-height: 22px; padding: 0; color: var(--ink); font-weight: 600; white-space: normal; }
|
||||
.object-drilldown.ant-btn:hover { color: var(--blue-dark); }
|
||||
.metric-table-pagination { display: flex; justify-content: flex-end; padding: 10px 13px; border-top: 1px solid var(--metric-grid); }
|
||||
.object-cell { display: flex; min-width: 0; flex-direction: column; align-items: center; gap: 3px; overflow-wrap: anywhere; text-align: center; white-space: normal; }
|
||||
.object-cell strong { color: var(--ink); font-weight: 600; }
|
||||
.object-cell small { font-size: 11px; }
|
||||
.month-state { width: fit-content; padding: 1px 3px; border: 1px solid #dce3ee; font-size: 10px !important; }
|
||||
.combined-value, .header-link { padding: 0; border: 0; background: transparent; color: var(--ink); font: 650 13px var(--mono); cursor: pointer; }
|
||||
.combined-value:hover, .header-link:hover { color: var(--blue-dark); text-decoration: underline; text-underline-offset: 3px; }
|
||||
.combined-value.static { cursor: default; }
|
||||
.table-value.ant-btn { height: auto; min-height: 20px; padding: 0; color: var(--ink); font: 13px var(--mono); }
|
||||
.rate-cell.black .table-value { color: var(--blue-dark); font-weight: 650; }
|
||||
.rate-cell.bright .table-value { color: var(--teal); font-weight: 650; }
|
||||
.stage-heading { display: inline-flex; align-items: center; gap: 6px; font-weight: 650; }
|
||||
.stage-heading i { display: inline-block; width: 7px; height: 7px; background: var(--blue); }
|
||||
.stage-heading.bright i { background: var(--teal); }
|
||||
.stage-heading.black { color: var(--blue-dark); }
|
||||
.stage-heading.bright { color: var(--teal); }
|
||||
.metric-table-scroll .ant-table-thead > tr:first-child > th:has(.stage-heading.black) { background: #e8edff; }
|
||||
.metric-table-scroll .ant-table-thead > tr:first-child > th:has(.stage-heading.bright) { background: #def4ee; }
|
||||
.table-footer { display: flex; min-height: 34px; align-items: center; justify-content: space-between; gap: 12px; padding: 6px 13px; border-top: 1px solid var(--line); font-size: 11px; }
|
||||
.mobile-scroll-hint { display: none; padding: 0 12px 8px; font-size: 11px; }
|
||||
.analysis-stack { display: grid; min-width: 0; grid-template-columns: minmax(0, 1fr); gap: 12px; }
|
||||
.trend-heading-row { flex-wrap: wrap; }
|
||||
.trend-controls { display: flex; min-height: 38px; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 9px; padding: 0 13px 9px; }
|
||||
.trend-chart-shell { position: relative; min-height: 380px; }
|
||||
.trend-refresh-indicator { position: absolute; top: 8px; right: 13px; z-index: 1; display: inline-flex; align-items: center; gap: 7px; padding: 5px 8px; border: 1px solid var(--line); background: var(--surface); font-size: 11px; pointer-events: none; }
|
||||
.trend-object { flex: 1 1 250px; }
|
||||
.trend-object .ant-select { width: min(420px, 100%); }
|
||||
.chart-viewport { width: 100%; overflow-x: auto; }
|
||||
.chart-surface { position: relative; width: 100%; min-width: 0; }
|
||||
.chart-container { width: 100%; height: 380px; min-width: 0; }
|
||||
.chart-bar-wash, .chart-bar-focus { position: absolute; pointer-events: none; }
|
||||
.chart-bar-wash { z-index: 1; background: var(--surface); opacity: .72; clip-path: inset(0 0 100% 0); }
|
||||
.chart-bar-focus { z-index: 2; border: 1px solid rgba(137, 165, 255, .7); box-shadow: 0 0 11px rgba(117, 151, 255, .26); opacity: 0; transition: opacity 240ms ease-out; }
|
||||
.chart-bar-focus.active { opacity: 1; }
|
||||
.chart-footnote { display: flex; justify-content: space-between; gap: 12px; padding: 0 13px 10px; font-size: 11px; }
|
||||
.defects-panel { min-height: 120px; }
|
||||
.defect-stage-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); border-top: 1px solid var(--line); }
|
||||
.defect-pareto-section { padding: 0 12px 10px; border-top: 1px solid var(--line); }
|
||||
.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: 13px; font-weight: 650; }
|
||||
.defect-pareto-heading span { color: var(--ink); font-size: 11px; }
|
||||
.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: 12px; }
|
||||
.defect-stage-column { min-width: 0; padding: 0 12px 10px; }
|
||||
.defect-stage-column + .defect-stage-column { border-left: 1px solid var(--line); }
|
||||
.defect-stage-title { display: flex; align-items: center; gap: 7px; margin: 0; padding: 11px 1px 4px; font-size: 13px; font-weight: 650; }
|
||||
.defect-stage-title i { width: 7px; height: 7px; background: var(--blue); }
|
||||
.defect-stage-title.bright i { background: var(--teal); }
|
||||
.defect-stage-title.black { color: var(--blue-dark); }
|
||||
.defect-stage-title.bright { color: var(--teal); }
|
||||
.defect-stage-column .ant-empty { margin: 13px 0 10px; }
|
||||
.defect-list { padding: 2px 0 0; }
|
||||
.defect-header, .defect-row { display: grid; grid-template-columns: minmax(72px, 95px) minmax(32px, 1fr) minmax(78px, 100px) 57px 57px; align-items: center; gap: 7px; }
|
||||
.defect-header { min-height: 27px; font-size: 11px; text-align: right; }
|
||||
.defect-header span:first-child { text-align: left; }
|
||||
.defect-row { width: 100%; min-height: 31px; padding: 4px 0; border: 0; background: transparent; text-align: left; cursor: pointer; }
|
||||
.defect-row:hover .defect-name { color: var(--blue-dark); text-decoration: underline; }
|
||||
.defect-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.defect-track { height: 8px; background: #eef1f6; }
|
||||
.defect-track i { display: block; height: 100%; background: var(--blue); transition: width 460ms cubic-bezier(.2,.7,.2,1); }
|
||||
.defect-track i.bright { background: var(--teal); }
|
||||
.defect-weight, .defect-rate { text-align: right; font: 12px var(--mono); }
|
||||
.query-footer { display: flex; align-items: center; justify-content: space-between; gap: 10px; font-size: 11px; }
|
||||
.query-footer .ant-btn { padding: 0; }
|
||||
.basis-card { display: flex; flex-direction: column; align-items: center; gap: 8px; margin: 5px 0 14px; padding: 17px; background: #eef2fc; border: 1px solid var(--line); text-align: center; }
|
||||
.basis-card strong { font: 650 35px var(--mono); }
|
||||
.basis-copy { line-height: 1.7; }
|
||||
.basis-details { display: grid; grid-template-columns: 110px minmax(0, 1fr); gap: 9px 12px; margin: 16px 0 0; font-size: 12px; }
|
||||
.basis-details dt { font-weight: 650; }
|
||||
.basis-details dd { margin: 0; overflow-wrap: anywhere; }
|
||||
.drawer-title { display: flex; flex-direction: column; gap: 3px; }
|
||||
.drawer-title small { font-weight: 400; font-size: 12px; }
|
||||
.drawer-controls { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 12px; font-size: 12px; }
|
||||
.json-cell { max-width: 360px; max-height: 140px; overflow: auto; margin: 0; font: 11px/1.45 var(--mono); white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.records-pagination { display: flex; justify-content: flex-end; margin-top: 14px; }
|
||||
.loading-panel { display: flex; min-height: 170px; align-items: center; justify-content: center; gap: 11px; }
|
||||
.loading-panel.compact { min-height: 240px; }
|
||||
.chart-footnote span:first-child { overflow-wrap: anywhere; }
|
||||
.management-page { display: flex; flex-direction: column; gap: 12px; }
|
||||
.page-heading { display: flex; min-height: 52px; align-items: center; justify-content: space-between; gap: 12px; }
|
||||
.page-heading h1 { margin: 0; font-size: 19px; font-weight: 650; }
|
||||
.page-heading p { margin: 5px 0 0; font-size: 12px; line-height: 1.55; }
|
||||
.page-heading-actions { display: flex; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: 8px; }
|
||||
.resource-toolbar { display: flex; min-height: 42px; align-items: center; gap: 12px; padding: 6px 12px; }
|
||||
.resource-toolbar strong { font-size: 13px; }
|
||||
.resource-toolbar span { flex: 1; font-size: 11px; text-align: right; }
|
||||
.resource-table { min-width: 0; }
|
||||
.resource-table .ant-table-cell { padding: 7px 9px !important; font-size: 12px; }
|
||||
.resource-table .ant-table-thead > tr > th { text-align: center; }
|
||||
.table-caption { margin: 6px 12px 9px; font-size: 11px; }
|
||||
.task-error { color: #a12a24; }
|
||||
.task-detail-summary { display: flex; flex-direction: column; gap: 8px; margin-bottom: 14px; }
|
||||
.task-actions { display: inline-flex; flex-wrap: wrap; align-items: center; justify-content: center; }
|
||||
.user-access-toggles { display: flex; flex-wrap: wrap; gap: 24px; }
|
||||
.import-result { padding: 8px 12px 12px; }
|
||||
.import-validation { display: flex; flex-direction: column; gap: 10px; padding: 0 8px; }
|
||||
.import-validation-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(135px, 1fr)); gap: 8px; }
|
||||
.import-validation-grid > span { display: flex; min-height: 52px; flex-direction: column; justify-content: center; gap: 4px; padding: 7px 9px; border: 1px solid var(--line); }
|
||||
.import-validation-grid small { font-size: 11px; }
|
||||
.import-validation-grid strong { font: 600 14px var(--mono); overflow-wrap: anywhere; }
|
||||
.import-validation-grid .positive { color: #08745e; }
|
||||
.import-validation-grid .negative { color: #a12a24; }
|
||||
.muted-dash { font-size: 12px; }
|
||||
.visually-hidden-file { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); }
|
||||
.ai-panel { display: flex; flex-direction: column; gap: 9px; padding: 14px; }
|
||||
.ai-panel > label { font-weight: 650; }
|
||||
.ai-actions { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
||||
.ai-actions span { font-size: 11px; }
|
||||
.ai-result { padding: 12px 14px; }
|
||||
.ai-answer { padding: 12px 0; line-height: 1.75; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.ai-result details { margin-top: 10px; border-top: 1px solid var(--line); padding-top: 10px; }
|
||||
.ai-result summary { cursor: pointer; font-size: 12px; }
|
||||
.analysis-engine-status { display: inline-flex; align-items: center; gap: 7px; font-size: 12px; }
|
||||
.analysis-engine-status i, .analysis-steps i { width: 7px; height: 7px; background: #c18a33; }
|
||||
.analysis-engine-status i.ready { background: var(--teal); }
|
||||
.analysis-workspace { display: grid; min-height: 650px; grid-template-columns: 225px minmax(0, 1fr); gap: 12px; }
|
||||
.analysis-session-panel { display: flex; min-height: 0; flex-direction: column; }
|
||||
.analysis-session-heading { display: flex; min-height: 46px; align-items: center; justify-content: space-between; padding: 8px 11px; border-bottom: 1px solid var(--line); }
|
||||
.analysis-session-list { overflow: auto; }
|
||||
.analysis-session-row { display: flex; align-items: center; min-width: 0; border-bottom: 1px solid var(--line); background: var(--surface); }
|
||||
.analysis-session-item { display: flex; flex: 1; min-width: 0; flex-direction: column; gap: 6px; padding: 11px; border: 0; background: transparent; color: var(--ink); text-align: left; cursor: pointer; }
|
||||
.analysis-session-row:hover, .analysis-session-row.active { background: var(--blue-soft); }
|
||||
.analysis-session-delete { flex: none; margin-right: 7px; }
|
||||
.analysis-session-item strong { overflow: hidden; font-size: 12px; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.analysis-session-item small { overflow: hidden; color: var(--muted-ink); font-size: 10px; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.analysis-chat-panel { display: flex; min-width: 0; min-height: 650px; flex-direction: column; }
|
||||
.analysis-context-bar { display: flex; align-items: center; flex-wrap: wrap; gap: 7px; padding: 9px; border-bottom: 1px solid var(--line); }
|
||||
.analysis-context-bar .ant-select { min-width: 112px; max-width: 190px; }
|
||||
.analysis-conversation { display: flex; min-height: 280px; flex: 1; flex-direction: column; gap: 15px; overflow: auto; padding: 15px; }
|
||||
.analysis-empty { display: flex; flex: 1; flex-direction: column; align-items: center; justify-content: center; gap: 11px; color: #4e5d72; text-align: center; }
|
||||
.analysis-empty .anticon { color: var(--blue); font-size: 24px; }
|
||||
.analysis-empty span { max-width: 440px; font-size: 12px; line-height: 1.6; }
|
||||
.analysis-turn { display: flex; flex-direction: column; gap: 9px; }
|
||||
.analysis-question { align-self: flex-end; width: min(720px, 92%); padding: 10px 12px; background: #edf1fb; border: 1px solid var(--line); }
|
||||
.analysis-question small { font-size: 10px; }
|
||||
.analysis-question p { margin: 5px 0 0; line-height: 1.6; white-space: pre-wrap; }
|
||||
.analysis-answer { width: 100%; padding: 11px 13px; background: #fff; border: 1px solid var(--line); }
|
||||
.analysis-answer-meta { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; font-size: 11px; }
|
||||
.analysis-answer .ai-answer { padding-bottom: 4px; }
|
||||
.analysis-steps { display: flex; flex-wrap: wrap; align-items: center; gap: 7px 13px; margin-top: 8px; font-size: 11px; }
|
||||
.analysis-steps strong { flex-basis: 100%; }
|
||||
.analysis-steps span { display: inline-flex; align-items: center; gap: 5px; padding: 4px 6px; background: #f4f6fa; }
|
||||
.analysis-steps i { background: var(--teal); }
|
||||
.analysis-privacy-note { display: block; margin-top: 9px; font-size: 10px; }
|
||||
.analysis-progress { display: flex; align-items: center; gap: 8px; padding: 12px; background: #f6f8fc; font-size: 12px; }
|
||||
.analysis-composer { display: flex; flex-direction: column; gap: 8px; padding: 12px; border-top: 1px solid var(--line); }
|
||||
.analysis-composer > label { font-size: 12px; font-weight: 650; }
|
||||
.analysis-snapshots { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 9px; margin-top: 11px; }
|
||||
.snapshot-card { min-width: 0; padding: 10px; background: #f8f9fc; border: 1px solid var(--line); }
|
||||
.snapshot-heading { display: flex; justify-content: space-between; gap: 9px; font-size: 11px; }
|
||||
.snapshot-heading span { text-align: right; }
|
||||
.snapshot-kpis { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 7px; margin: 9px 0; }
|
||||
.snapshot-kpis > span { display: flex; min-width: 0; flex-direction: column; gap: 4px; padding: 7px; background: #fff; border: 1px solid var(--line); }
|
||||
.snapshot-kpis small { font-size: 10px; }
|
||||
.snapshot-kpis strong { overflow: hidden; font: 600 14px var(--mono); text-overflow: ellipsis; white-space: nowrap; }
|
||||
.snapshot-details { display: flex; flex-direction: column; gap: 4px; padding-top: 7px; font-size: 11px; }
|
||||
.snapshot-defects { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 9px; margin-top: 7px; }
|
||||
.snapshot-defects > div { display: flex; flex-direction: column; gap: 4px; padding: 7px; background: #fff; border: 1px solid var(--line); }
|
||||
.snapshot-defects strong { font-size: 10px; }
|
||||
.snapshot-defects span { font-size: 10px; overflow-wrap: anywhere; }
|
||||
.snapshot-card details { margin-top: 8px; font-size: 11px; }
|
||||
.snapshot-card summary { cursor: pointer; }
|
||||
.json-result { max-height: 560px; overflow: auto; margin: 10px 0 0; padding: 12px; background: #f5f7fb; font: 12px/1.5 var(--mono); white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.empty-note { padding: 25px 16px; text-align: center; }
|
||||
.access-summary { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); }
|
||||
.access-summary > div { display: flex; min-height: 86px; flex-direction: column; justify-content: center; gap: 5px; padding: 12px 14px; border-right: 1px solid var(--line); }
|
||||
.access-summary > div:last-child { border-right: 0; }
|
||||
.access-summary span, .access-summary small { font-size: 11px; }
|
||||
.access-summary strong { overflow-wrap: anywhere; font-size: 13px; }
|
||||
.resource-tab { padding: 8px 0 0; }
|
||||
.basis-grid { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 12px; }
|
||||
.screen-state { display: flex; min-height: 100vh; align-items: center; justify-content: center; gap: 12px; background: #f3f5f9; }
|
||||
.state-card { width: min(390px, calc(100vw - 28px)); padding: 24px; background: #fff; border: 1px solid var(--line); }
|
||||
.state-card strong { font-size: 18px; }
|
||||
.state-card p { margin: 10px 0 16px; overflow-wrap: anywhere; }
|
||||
.login-screen { display: grid; min-height: 100vh; min-height: 100svh; grid-template-columns: minmax(0, 1.13fr) minmax(410px, .87fr); overflow: hidden; background: #fff; }
|
||||
.login-art { position: relative; isolation: isolate; min-width: 0; min-height: 640px; overflow: hidden; padding: 36px clamp(30px, 5vw, 76px) 25px; color: #fff; background: linear-gradient(148deg, #4d65ca, #253454 60%, #30456c); }
|
||||
/* Shared with the complaint platform's login artwork. */
|
||||
.login-art::before { content: ''; position: absolute; z-index: 0; width: 580px; height: 580px; border-radius: 50%; border: 1px solid rgba(189,204,255,.12); right: -206px; top: 147px; box-shadow: 0 0 0 70px rgba(189,204,255,.03), 0 0 0 145px rgba(189,204,255,.024); pointer-events: none; }
|
||||
.login-orbit { z-index: 1; position: absolute; border: 1px solid rgba(177,195,255,.16); border-radius: 50%; transform: rotate(33deg); pointer-events: none; }
|
||||
.login-orbit-one { width: 330px; height: 150px; right: 42px; top: 343px; }
|
||||
.login-orbit-two { width: 260px; height: 113px; right: -12px; top: 361px; transform: rotate(-29deg); }
|
||||
.login-brand-lockup { position: relative; z-index: 2; display: flex; align-items: center; gap: 17px; }
|
||||
.login-brand-lockup img { display: block; width: 168px; max-width: 48%; height: auto; }
|
||||
.login-brand-divider { width: 1px; height: 29px; background: rgba(255,255,255,.38); }
|
||||
.login-brand-lockup strong { color: #f7fbff; font-size: 15px; font-weight: 550; letter-spacing: .04em; white-space: nowrap; }
|
||||
.login-art-copy { position: relative; z-index: 2; max-width: 520px; margin-top: clamp(104px, 14vh, 150px); }
|
||||
.login-eyebrow { color: #91d6d0; font: 500 11px/1.4 var(--mono); letter-spacing: .16em; }
|
||||
.login-art-copy h1 { margin: 18px 0 17px; color: #fff; font-size: clamp(38px, 4.1vw, 56px); font-weight: 570; letter-spacing: -.045em; line-height: 1.22; }
|
||||
.login-art-copy p { max-width: 400px; margin: 0; color: #d1dfeb; font-size: 15px; line-height: 1.75; letter-spacing: .015em; }
|
||||
.login-panel { position: relative; display: flex; min-width: 0; min-height: 640px; flex-direction: column; align-items: center; justify-content: center; padding: 76px clamp(30px, 5vw, 78px) 98px; background: #fff; }
|
||||
.login-panel-top { position: absolute; top: 31px; right: clamp(28px, 4vw, 58px); display: inline-flex; align-items: center; gap: 9px; color: #42546a; font-size: 13px; font-weight: 600; }
|
||||
.login-panel-mark { display: inline-flex; height: 19px; align-items: center; gap: 2px; transform: skew(-17deg); }
|
||||
.login-panel-mark i { width: 3px; height: 13px; background: var(--blue); }
|
||||
.login-panel-mark i:nth-child(2) { height: 18px; opacity: .8; }
|
||||
.login-panel-mark i:nth-child(3) { height: 10px; background: var(--teal); }
|
||||
.login-card { width: min(100%, 390px); padding: 0; border: 0; background: transparent; }
|
||||
.login-card-kicker { color: var(--blue-dark); font-size: 13px; font-weight: 650; letter-spacing: .03em; }
|
||||
.login-card h2 { margin: 0 0 30px; color: #111111; font-size: 30px; font-weight: 650; letter-spacing: -.04em; line-height: 1.3; }
|
||||
.login-card-subtitle { margin: 0 0 30px; color: #526174; font-size: 14px; line-height: 1.6; }
|
||||
.login-card .ant-form-item { margin-bottom: 20px; }
|
||||
.login-card .ant-form-item-label { padding-bottom: 7px; }
|
||||
.login-card .ant-form-item-label > label { color: #111111; font-size: 14px; font-weight: 550; }
|
||||
.login-card .ant-form-item-control-input-content > .ant-input { height: 44px; padding: 0 11px; border-radius: 0; border-color: #bcc9d8; box-shadow: none; font-size: 14px; }
|
||||
.login-card .ant-form-item-control-input-content > .ant-input:hover { border-color: #3559dc; }
|
||||
.login-card .ant-form-item-control-input-content > .ant-input:focus { border-color: #3559dc; box-shadow: 0 0 0 2px rgba(53,89,220,.12); }
|
||||
.login-card .ant-input-affix-wrapper { min-height: 44px; padding: 0 11px; border-radius: 0; border-color: #bcc9d8; box-shadow: none; }
|
||||
.login-card .ant-input-affix-wrapper:hover { border-color: #3559dc; }
|
||||
.login-card .ant-input-affix-wrapper-focused { border-color: #3559dc; box-shadow: 0 0 0 2px rgba(53,89,220,.12); }
|
||||
.login-card .ant-input-affix-wrapper .ant-input { height: 40px; font-size: 14px; }
|
||||
.login-card .ant-input::placeholder { color: #8794a3; }
|
||||
.login-card .login-submit { min-height: 44px; margin-top: 4px; font-size: 14px; font-weight: 650; }
|
||||
.login-error { margin: -1px 0 17px; border-radius: 0; font-size: 13px; }
|
||||
.login-error .ant-alert-message { overflow-wrap: anywhere; }
|
||||
.login-footer { position: absolute; right: 24px; bottom: 25px; left: 24px; color: #677789; font-size: 12px; text-align: center; }
|
||||
.login-footer span { margin: 0 5px; color: #91a0ae; }
|
||||
|
||||
@media (max-width: 1140px) {
|
||||
:root { --sidebar: 182px; }
|
||||
.page-content { padding: 14px 15px 18px; }
|
||||
.query-toolbar { gap: 8px; }
|
||||
.query-field .ant-select { min-width: 100px; }
|
||||
.metric-strip { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.metric-card:nth-child(2) { border-right: 0; }
|
||||
.metric-card:nth-child(-n+2) { border-bottom: 1px solid var(--line); }
|
||||
.basis-grid { grid-template-columns: 1fr; }
|
||||
}
|
||||
|
||||
@media (max-width: 760px) {
|
||||
.login-screen { min-height: 100svh; grid-template-columns: minmax(0, 1fr); grid-template-rows: minmax(270px, 32svh) minmax(430px, 1fr); overflow: visible; }
|
||||
.login-art { min-height: 270px; padding: 23px 22px 20px; }
|
||||
.login-brand-lockup { gap: 12px; }
|
||||
.login-brand-lockup img { width: 146px; }
|
||||
.login-brand-lockup strong { font-size: 13px; }
|
||||
.login-art-copy { margin-top: 41px; }
|
||||
.login-eyebrow { font-size: 9px; }
|
||||
.login-art-copy h1 { margin: 10px 0 8px; font-size: 30px; line-height: 1.16; }
|
||||
.login-art-copy p { max-width: 330px; font-size: 12px; line-height: 1.55; }
|
||||
.login-art::before { width: 340px; height: 340px; right: -170px; top: 30px; box-shadow: 0 0 0 40px rgba(189,204,255,.03), 0 0 0 85px rgba(189,204,255,.024); }
|
||||
.login-orbit-one { width: 220px; height: 100px; right: 4px; top: 142px; }
|
||||
.login-orbit-two { width: 175px; height: 76px; right: -24px; top: 155px; }
|
||||
.login-panel { min-height: 430px; align-items: stretch; justify-content: flex-start; padding: 36px 24px 71px; }
|
||||
.login-panel-top { top: 18px; right: 23px; font-size: 11px; }
|
||||
.login-card { width: min(100%, 390px); margin: 0 auto; }
|
||||
.login-card h2 { margin-top: 8px; font-size: 26px; }
|
||||
.login-card-subtitle { margin-bottom: 22px; }
|
||||
.login-card .ant-form-item { margin-bottom: 16px; }
|
||||
.login-footer { bottom: 20px; font-size: 11px; }
|
||||
:root { --sidebar: 0px; }
|
||||
.sidebar { display: none; }
|
||||
.main-column { margin-left: 0; }
|
||||
.topbar { height: 40px; 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: 14px; }
|
||||
.mobile-brand > strong { white-space: nowrap; }
|
||||
.mobile-brand > .ant-select { flex: 1; min-width: 0; margin-left: 3px; }
|
||||
.mobile-brand .brand-mark { transform: scale(.83) skew(-17deg); transform-origin: left center; width: 18px; }
|
||||
.page-content { padding: 11px 10px 18px; }
|
||||
.analysis-workspace { grid-template-columns: 1fr; }
|
||||
.analysis-session-panel { max-height: 175px; }
|
||||
.analysis-session-list { display: flex; overflow-x: auto; }
|
||||
.analysis-session-row { min-width: 190px; border-right: 1px solid var(--line); border-bottom: 0; }
|
||||
.analysis-chat-panel { min-height: 680px; }
|
||||
.analysis-context-bar > .ant-select { max-width: none; flex: 1 1 135px; }
|
||||
.analysis-context-bar > .ant-segmented { width: 100%; }
|
||||
.analysis-context-bar > .ant-segmented .ant-segmented-item { flex: 1; }
|
||||
.analysis-context-bar > .ant-checkbox-wrapper { flex-basis: 100%; }
|
||||
.analysis-conversation { min-height: 250px; padding: 10px; }
|
||||
.analysis-question { width: 100%; }
|
||||
.analysis-snapshots { grid-template-columns: 1fr; }
|
||||
.query-page, .management-page { gap: 9px; }
|
||||
.query-toolbar { align-items: flex-start; gap: 8px; padding: 9px; }
|
||||
.query-toolbar > .ant-segmented { width: 100%; }
|
||||
.query-toolbar > .ant-segmented .ant-segmented-item { flex: 1; }
|
||||
.query-field { flex: 1 1 145px; flex-direction: column; align-items: stretch; gap: 4px; }
|
||||
.query-field .ant-select { width: 100%; min-width: 0; flex: initial; }
|
||||
.query-field.release-field { flex-basis: 100%; }
|
||||
.query-toolbar-tail { width: 100%; min-width: 0; }
|
||||
.metric-card { min-height: 80px; padding: 9px 10px; }
|
||||
.metric-label { gap: 5px; font-size: 11px; }
|
||||
.metric-value, .metric-card.primary .metric-value { font-size: clamp(19px, 6vw, 27px); letter-spacing: -.7px; }
|
||||
.metric-card small { font-size: 10px; }
|
||||
.section-heading-row { align-items: flex-start; flex-direction: column; gap: 8px; padding: 10px; }
|
||||
.section-heading { flex-wrap: wrap; gap: 5px 9px; }
|
||||
.section-heading h2 { font-size: 13px; }
|
||||
.table-tools { width: 100%; flex-wrap: wrap; justify-content: space-between; }
|
||||
.table-tools .ant-input-affix-wrapper { width: min(100%, 220px); flex: 1 1 145px; }
|
||||
.table-tools .ant-segmented { max-width: 100%; }
|
||||
.mobile-scroll-hint { display: block; }
|
||||
.metric-table-scroll .ant-table-cell { padding: 5px 8px !important; }
|
||||
.table-footer { align-items: flex-start; flex-direction: column; gap: 4px; padding: 7px 10px; }
|
||||
.chart-container { height: 310px; }
|
||||
.chart-surface { width: 760px; min-width: 760px; }
|
||||
.trend-chart-shell { min-height: 310px; }
|
||||
.trend-controls { align-items: flex-start; flex-direction: column; padding: 0 10px 8px; }
|
||||
.trend-object { width: 100%; flex-basis: auto; }
|
||||
.trend-object .ant-select { flex: 1; }
|
||||
.chart-footnote { flex-direction: column; gap: 5px; padding: 0 10px 9px; }
|
||||
.defect-stage-grid { grid-template-columns: 1fr; }
|
||||
.defect-pareto-section { padding: 0 10px 9px; }
|
||||
.defect-pareto-chart { height: 410px; }
|
||||
.defect-stage-column { padding: 0 10px 10px; }
|
||||
.defect-stage-column + .defect-stage-column { border-left: 0; border-top: 1px solid var(--line); }
|
||||
.defect-header, .defect-row { grid-template-columns: minmax(68px, 90px) minmax(28px, 1fr) 80px 52px 52px; gap: 6px; }
|
||||
.defect-name { font-size: 12px; }
|
||||
.defect-weight, .defect-rate { font-size: 10px; }
|
||||
.query-footer { align-items: flex-start; flex-direction: column; gap: 2px; }
|
||||
.page-heading { align-items: flex-start; flex-direction: column; }
|
||||
.page-heading h1 { font-size: 17px; }
|
||||
.page-heading-actions { width: 100%; justify-content: flex-start; }
|
||||
.page-heading-actions .ant-btn { flex: 1; }
|
||||
.resource-toolbar { flex-wrap: wrap; gap: 5px 10px; padding: 8px 10px; }
|
||||
.resource-toolbar span { flex-basis: 100%; order: 2; text-align: left; }
|
||||
.resource-toolbar .ant-btn { order: 1; margin-left: auto; }
|
||||
.access-summary { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.access-summary > div { min-height: 74px; padding: 9px; }
|
||||
.access-summary > div:nth-child(2) { border-right: 0; }
|
||||
.access-summary > div:nth-child(-n+2) { border-bottom: 1px solid var(--line); }
|
||||
.drawer-controls { align-items: flex-start; flex-direction: column; }
|
||||
.json-cell { max-width: 260px; }
|
||||
.basis-details { grid-template-columns: 90px minmax(0, 1fr); }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*, *::before, *::after { scroll-behavior: auto !important; animation-duration: .01ms !important; animation-iteration-count: 1 !important; transition-duration: .01ms !important; }
|
||||
}
|
||||
|
||||
/* 首阶段浅色工作台外壳:中性文字仍使用 #111,蓝紫用于导航与操作强调。 */
|
||||
:root {
|
||||
background: var(--background);
|
||||
color-scheme: light;
|
||||
--blue: #607ae1;
|
||||
--blue-dark: #607ae1;
|
||||
--blue-soft: #eef1ff;
|
||||
--blue-muted: #b0bcee;
|
||||
--background: #f4f6fa;
|
||||
--hover: #f5f6ff;
|
||||
--sidebar-surface: #f8fafd;
|
||||
--line: #dfe5ef;
|
||||
}
|
||||
|
||||
body { background: var(--background); }
|
||||
.sidebar { background: var(--sidebar-surface); }
|
||||
.workspace-caption { padding-bottom: 15px; }
|
||||
.nav-group { margin-top: 11px; }
|
||||
.nav-group-label { padding: 7px 9px 6px; color: #111; }
|
||||
.nav-item {
|
||||
min-height: 37px;
|
||||
transition: background-color 140ms cubic-bezier(.2,.7,.2,1), color 140ms cubic-bezier(.2,.7,.2,1);
|
||||
}
|
||||
.nav-item .anticon { color: #617087; }
|
||||
.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-actions { display: flex; align-items: center; gap: 8px; }
|
||||
.topbar-search.ant-btn {
|
||||
display: inline-flex;
|
||||
height: 30px;
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
padding: 0 8px;
|
||||
color: #111;
|
||||
font-size: 12px;
|
||||
}
|
||||
.topbar-search .anticon, .topbar-help .anticon { color: #667386; }
|
||||
.topbar-search kbd, .navigation-result kbd {
|
||||
display: inline-flex;
|
||||
min-height: 20px;
|
||||
align-items: center;
|
||||
padding: 1px 5px;
|
||||
border: 1px solid var(--line);
|
||||
background: #fafbfe;
|
||||
color: #58667b;
|
||||
font: 11px/1.2 var(--mono);
|
||||
}
|
||||
.topbar-help.ant-btn { width: 30px; height: 30px; padding: 0; }
|
||||
.topbar-theme.ant-btn { height: 30px; gap: 6px; padding: 0 7px; color: #111; font-size: 12px; }
|
||||
.topbar-theme .anticon { color: #667386; }
|
||||
.theme-choice { display: flex; min-width: 104px; align-items: center; gap: 9px; font-size: 13px; }
|
||||
.theme-choice > i { display: inline-block; width: 10px; height: 10px; flex: 0 0 10px; border: 1px solid #11111114; }
|
||||
.theme-choice > .anticon { margin-left: auto; font-size: 11px; }
|
||||
.workspace-theme-dropdown.ant-dropdown { z-index: 1250 !important; isolation: isolate; }
|
||||
.workspace-theme-dropdown .ant-dropdown-menu { border: 1px solid var(--line); background-color: var(--surface, #fff) !important; color: var(--ink); opacity: 1 !important; box-shadow: 0 8px 24px rgba(18, 30, 52, .2); }
|
||||
.workspace-theme-dropdown .ant-dropdown-menu-item { color: var(--ink) !important; }
|
||||
.workspace-theme-dropdown .ant-dropdown-menu-item-selected { background-color: var(--blue-soft) !important; color: var(--blue-dark) !important; }
|
||||
.workspace-theme-dropdown .ant-dropdown-menu-item:hover { background-color: var(--hover) !important; }
|
||||
.top-organization { padding-left: 5px; }
|
||||
.page-content { padding: 17px 20px 22px; }
|
||||
.page-view { min-width: 0; }
|
||||
.metric-value .metric-unit { font-size: .58em; font-weight: 450; letter-spacing: 0; }
|
||||
.metric-card.primary .metric-value .metric-unit { font-size: .62em; }
|
||||
.panel { border-color: var(--line); }
|
||||
.metric-table-scroll .ant-table-tbody > tr > td { height: 35px; }
|
||||
.metric-table-scroll .ant-table-cell { padding-top: 6px !important; padding-bottom: 6px !important; }
|
||||
.metric-table-scroll .ant-btn-link:not(.table-value) { min-height: 0; height: 22px; padding: 0; font-size: 12px; }
|
||||
.query-page > .ant-alert { padding: 10px 14px; }
|
||||
.coverage-details { margin-top: 3px; font-size: 12px; line-height: 1.6; }
|
||||
.coverage-details summary { width: fit-content; cursor: pointer; }
|
||||
.coverage-details p { margin: 7px 0 0; }
|
||||
.ant-btn, .ant-input, .ant-select-selector, .ant-segmented, .ant-tag, .ant-alert,
|
||||
.ant-modal-container, .ant-modal-content, .ant-drawer-content, .ant-input-affix-wrapper { border-radius: 0 !important; }
|
||||
.ant-modal { max-width: calc(100vw - 24px); }
|
||||
.ant-btn { transition: background-color 140ms cubic-bezier(.2,.7,.2,1), color 140ms cubic-bezier(.2,.7,.2,1), border-color 140ms cubic-bezier(.2,.7,.2,1), box-shadow 140ms cubic-bezier(.2,.7,.2,1); }
|
||||
.ant-segmented, .ant-segmented .ant-segmented-item, .ant-segmented .ant-segmented-thumb {
|
||||
transition: background-color 170ms cubic-bezier(.2,.7,.2,1), color 140ms cubic-bezier(.2,.7,.2,1), transform 170ms cubic-bezier(.2,.7,.2,1);
|
||||
}
|
||||
.ant-drawer .ant-drawer-content-wrapper { transition-duration: 200ms !important; transition-timing-function: cubic-bezier(.2,.7,.2,1) !important; }
|
||||
.navigation-search-modal .ant-modal-header { margin-bottom: 12px; }
|
||||
.navigation-search-modal .ant-modal-title { color: #111; font-size: 15px; font-weight: 650; }
|
||||
.navigation-search-modal .ant-modal-body > .ant-input-affix-wrapper { min-height: 40px; }
|
||||
.navigation-search-results { display: flex; max-height: min(48vh, 360px); flex-direction: column; gap: 2px; overflow-y: auto; margin: 9px -5px 0; padding: 0 5px; }
|
||||
.navigation-result {
|
||||
display: flex;
|
||||
min-height: 38px;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
padding: 6px 9px;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: #111;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
transition: background-color 140ms cubic-bezier(.2,.7,.2,1), color 140ms cubic-bezier(.2,.7,.2,1);
|
||||
}
|
||||
.navigation-result:hover, .navigation-result:focus-visible, .navigation-result[aria-selected="true"] { outline: 0; background: var(--blue-soft); color: var(--blue-dark); }
|
||||
.navigation-search-empty { padding: 18px 9px; color: #111; font-size: 13px; }
|
||||
.navigation-search-footnote { margin-top: 10px; padding-top: 9px; border-top: 1px solid var(--line); color: #111; font-size: 11px; }
|
||||
|
||||
@media (max-width: 1140px) {
|
||||
.page-content { padding: 15px 15px 20px; }
|
||||
.query-toolbar::before { right: -15px; left: -15px; height: 16px; }
|
||||
}
|
||||
@media (max-width: 760px) {
|
||||
.topbar { height: 40px; 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; }
|
||||
.topbar-help.ant-btn { width: 28px; }
|
||||
.topbar-theme.ant-btn { gap: 4px; padding: 0 5px; font-size: 11px; }
|
||||
.top-organization { display: none; }
|
||||
.mobile-brand { background: var(--sidebar-surface); }
|
||||
.page-content { padding: 11px 10px 18px; }
|
||||
.query-toolbar { top: 40px; }
|
||||
.query-toolbar::before { right: -10px; left: -10px; height: 12px; }
|
||||
.navigation-search-modal { max-width: calc(100vw - 24px); }
|
||||
}
|
||||
|
||||
.metric-card.primary { background: var(--blue-soft); }
|
||||
.metric-card:hover { background: var(--hover); }
|
||||
.metric-table-scroll .combined-column,
|
||||
.metric-table-scroll .combined-column.ant-table-cell-fix-left,
|
||||
.metric-table-scroll th.combined-column { background: var(--blue-soft) !important; }
|
||||
.metric-table-scroll .ant-table-thead > tr:first-child > th:has(.stage-heading.black) { background: var(--blue-soft); }
|
||||
.basis-card { background: var(--blue-soft); }
|
||||
.workspace-caption { padding-bottom: 6px; }
|
||||
.nav-group { margin-top: 4px; }
|
||||
.nav-group-label { padding: 4px 9px; }
|
||||
.nav-item { min-height: 33px; padding: 5px 9px; }
|
||||
.nav-group-tail { padding-top: 0; }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*, *::before, *::after { scroll-behavior: auto !important; animation-duration: .01ms !important; animation-iteration-count: 1 !important; transition-duration: .01ms !important; }
|
||||
.ant-drawer .ant-drawer-content-wrapper { transition-duration: .01ms !important; }
|
||||
}
|
||||
|
||||
.analysis-reports { padding: 12px 15px; border-top: 1px solid var(--border-color, #dce3ec); font-size: 13px; }
|
||||
.analysis-reports summary { cursor: pointer; font-weight: 600; }
|
||||
.analysis-reports p { color: var(--text-secondary, #667085); line-height: 1.6; }
|
||||
.analysis-report-plans { display: flex; flex-wrap: wrap; align-items: center; gap: 12px; padding-top: 12px; }
|
||||
.analysis-report-plans label { display: inline-flex; align-items: center; gap: 6px; }
|
||||
.analysis-reports ul { padding-left: 20px; }
|
||||
@@ -0,0 +1,183 @@
|
||||
export type Stage = 'black' | 'bright';
|
||||
export type ViewKind = 'overall' | 'department' | 'group' | 'product' | 'projectGroup';
|
||||
export type PeriodKind = 'year' | 'quarter' | 'month';
|
||||
|
||||
export interface QueryParams {
|
||||
year: number;
|
||||
month?: number;
|
||||
quarter?: number;
|
||||
department?: string;
|
||||
group?: string;
|
||||
product?: string;
|
||||
projectGroup?: string;
|
||||
view: ViewKind;
|
||||
releaseId?: string;
|
||||
includeUnassigned?: boolean;
|
||||
trendGranularity?: 'month' | 'quarter' | 'year';
|
||||
}
|
||||
|
||||
export interface RecordsParams extends QueryParams {
|
||||
stage: Stage;
|
||||
page: number;
|
||||
pageSize: number;
|
||||
field?: string;
|
||||
search?: string;
|
||||
sort?: string;
|
||||
direction?: 'asc' | 'desc';
|
||||
columns?: string[];
|
||||
}
|
||||
|
||||
export type RecordExportParams = Pick<
|
||||
QueryParams,
|
||||
'year' | 'month' | 'quarter' | 'department' | 'group' | 'product' | 'projectGroup' | 'includeUnassigned' | 'releaseId'
|
||||
>;
|
||||
|
||||
export interface DefectMetric {
|
||||
name: string;
|
||||
weight: number | null;
|
||||
rate: number | null;
|
||||
}
|
||||
|
||||
export interface FineDefectTopResponse {
|
||||
kind: 'fine_defect_top';
|
||||
releaseId: string;
|
||||
sourceRows: number;
|
||||
rows: Array<{ key: string; label: string; category: string; weight: number | null }>;
|
||||
sourceFields?: Array<{ key: string; label: string; category: string; sourceField: string }>;
|
||||
coverage?: {
|
||||
available?: boolean;
|
||||
sourceRows?: number;
|
||||
categories?: Array<{ category: string; reconciliationStatus: string; reconciliationReasons?: string[] }>;
|
||||
};
|
||||
notice?: string;
|
||||
}
|
||||
|
||||
export interface StageMetric {
|
||||
qualifiedWeight: number | null;
|
||||
scrapWeight: number | null;
|
||||
totalWeight: number | null;
|
||||
rate: number | null;
|
||||
headquartersScrapWeight?: number | null;
|
||||
rateWithoutHeadquartersScrap?: number | null;
|
||||
defects: DefectMetric[];
|
||||
}
|
||||
|
||||
export interface MetricRow {
|
||||
key: string;
|
||||
label: string;
|
||||
department: string | null;
|
||||
group: string | null;
|
||||
product: string | null;
|
||||
projectGroup?: string | null;
|
||||
compositeRate: number | null;
|
||||
compositeRateWithoutHeadquartersScrap?: number | null;
|
||||
black: StageMetric;
|
||||
bright: StageMetric;
|
||||
coverage: { blackRows: number; brightRows: number };
|
||||
}
|
||||
|
||||
export interface TrendMetricRow extends MetricRow {
|
||||
month: number | string;
|
||||
period?: string;
|
||||
periodLabel?: string;
|
||||
granularity?: 'month' | 'quarter' | 'year' | string;
|
||||
year?: number;
|
||||
quarter?: number;
|
||||
monthStatus?: 'in_progress' | 'future' | 'unavailable';
|
||||
noData?: boolean;
|
||||
}
|
||||
|
||||
export interface MetricsResponse {
|
||||
release: { id: string; name: string; status: string } | null;
|
||||
context: Record<string, unknown>;
|
||||
summary: MetricRow;
|
||||
rows: MetricRow[];
|
||||
trend: TrendMetricRow[];
|
||||
defects: { black: DefectMetric[]; bright: DefectMetric[] };
|
||||
coverage: CoverageSummary;
|
||||
}
|
||||
|
||||
export interface CoverageSummary {
|
||||
rawRows: number;
|
||||
includedRows: number;
|
||||
excludedBlankRows: number;
|
||||
unmappedRows: number;
|
||||
projectGroupUnconfiguredRows: number;
|
||||
missingStages: { year: number; month: number | string; stage: Stage }[];
|
||||
sourceMonths: { year: number; month: number | string; blackRows: number; brightRows: number }[];
|
||||
}
|
||||
|
||||
export interface ReleaseOption {
|
||||
id: string;
|
||||
name: string;
|
||||
status: string;
|
||||
}
|
||||
|
||||
export interface OptionsResponse {
|
||||
years: (number | string)[];
|
||||
departments: string[];
|
||||
groups: string[];
|
||||
groupDepartments?: Record<string, string | null>;
|
||||
products: string[];
|
||||
projectGroups?: string[];
|
||||
projectGroupStatus?: 'READY' | 'UNCONFIGURED' | string;
|
||||
organizationPaths?: { department: string | null; group: string | null; product: string | null }[];
|
||||
releases: ReleaseOption[];
|
||||
}
|
||||
|
||||
export interface RecordRow {
|
||||
id: string;
|
||||
sourceFile: string;
|
||||
sheet: string;
|
||||
rowNumber: number;
|
||||
stage: Stage;
|
||||
month: number | string;
|
||||
department: string | null;
|
||||
group: string | null;
|
||||
product: string | null;
|
||||
raw: Record<string, unknown>;
|
||||
components: Record<string, unknown>;
|
||||
sourceRevisionId?: string;
|
||||
normalized?: Record<string, unknown>;
|
||||
transformNotes?: string[] | Record<string, unknown>[];
|
||||
}
|
||||
|
||||
export interface RecordsResponse {
|
||||
rows: RecordRow[];
|
||||
total: number;
|
||||
page: number;
|
||||
pageSize: number;
|
||||
}
|
||||
|
||||
export interface AuthUser {
|
||||
id: string;
|
||||
username: string;
|
||||
displayName: string;
|
||||
roles: string[];
|
||||
departments: string[];
|
||||
groups: string[];
|
||||
}
|
||||
|
||||
export interface Collection<T = Record<string, unknown>> {
|
||||
items: T[];
|
||||
total?: number;
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
currentReleaseId?: string | null;
|
||||
}
|
||||
|
||||
export interface SourceItem {
|
||||
id: string;
|
||||
sourceFile: string;
|
||||
stage: Stage;
|
||||
year: number;
|
||||
month: number;
|
||||
sizeBytes: number;
|
||||
sha256: string;
|
||||
status: string;
|
||||
}
|
||||
|
||||
export interface ApiEnvelope<T> {
|
||||
data?: T;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
export const workspaceThemes = [
|
||||
{ id: 'light', name: '浅蓝', primary: '#607AE1', soft: '#EEF1FF', background: '#F3F5FA', hover: '#F5F6FF', muted: '#B0BCEE', metricGrid: '#9BAAC0', metricGridHead: '#7F91AA' },
|
||||
{ id: 'soft', name: '柔蓝', primary: '#5078AE', soft: '#E7EFF9', background: '#EDF2F8', hover: '#F0F5FB', muted: '#A7BDD9', metricGrid: '#98AAC0', metricGridHead: '#7C91AA' },
|
||||
{ id: 'deep', name: '深蓝', primary: '#34578F', soft: '#DFE8F5', background: '#E5EBF3', hover: '#E9EFF8', muted: '#99AFCD', metricGrid: '#94A7C0', metricGridHead: '#7188A7' },
|
||||
{ id: 'bright', name: '亮蓝', primary: '#008CF6', soft: '#E3F2FF', background: '#EFF7FC', hover: '#EDF8FF', muted: '#8DC7F4', metricGrid: '#96ADC3', metricGridHead: '#7697B3' },
|
||||
{ id: 'classic', name: '经典蓝', primary: '#4472C4', soft: '#E7EFFB', background: '#F0F4FA', hover: '#EEF3FC', muted: '#A1B9E2', metricGrid: '#95A8BF', metricGridHead: '#788EAA' },
|
||||
{ id: 'dark', name: '夜间黑', primary: '#8AA7FF', soft: '#202C49', background: '#0E1420', hover: '#202B3E', muted: '#516A9A', metricGrid: '#45566D', metricGridHead: '#5B6D85' },
|
||||
] as const;
|
||||
|
||||
export type WorkspaceTheme = (typeof workspaceThemes)[number];
|
||||
export type WorkspaceThemeId = WorkspaceTheme['id'];
|
||||
|
||||
export const workspaceThemeStorageKey = 'quality-workbench-theme';
|
||||
|
||||
export function getWorkspaceTheme(themeId: string | null | undefined): WorkspaceTheme {
|
||||
return workspaceThemes.find(theme => theme.id === themeId) ?? workspaceThemes[0];
|
||||
}
|
||||
|
||||
export function getStoredWorkspaceThemeId(): WorkspaceThemeId {
|
||||
try {
|
||||
return getWorkspaceTheme(window.localStorage.getItem(workspaceThemeStorageKey)).id;
|
||||
} catch {
|
||||
return workspaceThemes[0].id;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { api } from './api';
|
||||
import type { DataWorkflowOperation } from './NoCodeDataTypes';
|
||||
|
||||
type StoredOperation = { operationId: string; startedAt: string };
|
||||
const storageKey = (slot: string) => `quality-data-workflow:${slot}`;
|
||||
const isPending = (value: DataWorkflowOperation | null) => value && ['QUEUED', 'RUNNING'].includes(String(value.status).toUpperCase());
|
||||
const delay = (ms: number) => new Promise(resolve => window.setTimeout(resolve, ms));
|
||||
|
||||
export function operationError(value: DataWorkflowOperation | null): string {
|
||||
const errors = Array.isArray(value?.errors) ? value.errors : [];
|
||||
return errors.map(item => item?.message).filter(Boolean).join(';') || '操作未完成,请重试';
|
||||
}
|
||||
|
||||
export function useDataWorkflowOperation(slot: string, onComplete?: (value: DataWorkflowOperation) => void) {
|
||||
const [operation, setOperation] = useState<DataWorkflowOperation | null>(null);
|
||||
const [error, setError] = useState('');
|
||||
const [pollRevision, setPollRevision] = useState(0);
|
||||
const [starting, setStarting] = useState(false);
|
||||
const callbackRef = useRef(onComplete);
|
||||
const activeRef = useRef(0);
|
||||
const startPromiseRef = useRef<Promise<DataWorkflowOperation> | null>(null);
|
||||
useEffect(() => { callbackRef.current = onComplete; }, [onComplete]);
|
||||
|
||||
const savePendingId = useCallback((value: StoredOperation | null) => {
|
||||
try {
|
||||
if (value) localStorage.setItem(storageKey(slot), JSON.stringify(value));
|
||||
else localStorage.removeItem(storageKey(slot));
|
||||
} catch { /* storage may be unavailable in a restricted browser context */ }
|
||||
}, [slot]);
|
||||
|
||||
const poll = useCallback(async (operationId: string) => {
|
||||
const runId = ++activeRef.current;
|
||||
setError('');
|
||||
while (activeRef.current === runId) {
|
||||
try {
|
||||
const current = await api.dataWorkflowOperation(operationId);
|
||||
if (activeRef.current !== runId) return;
|
||||
setOperation(current);
|
||||
const status = String(current.status || '').toUpperCase();
|
||||
if (status === 'COMPLETED' || status === 'FAILED') {
|
||||
if (status === 'COMPLETED') { savePendingId(null); callbackRef.current?.(current); }
|
||||
else setError(operationError(current));
|
||||
return;
|
||||
}
|
||||
} catch (value) {
|
||||
if (activeRef.current !== runId) return;
|
||||
setError(value instanceof Error ? value.message : '处理进度读取失败');
|
||||
return;
|
||||
}
|
||||
await delay(900);
|
||||
}
|
||||
}, [savePendingId]);
|
||||
|
||||
useEffect(() => {
|
||||
let pending: StoredOperation | null = null;
|
||||
try { pending = JSON.parse(localStorage.getItem(storageKey(slot)) || 'null') as StoredOperation | null; } catch { pending = null; }
|
||||
if (pending?.operationId) void poll(pending.operationId);
|
||||
return () => { activeRef.current++; };
|
||||
}, [poll, slot, pollRevision]);
|
||||
|
||||
const start = useCallback(async (create: () => Promise<DataWorkflowOperation>) => {
|
||||
if (startPromiseRef.current) return startPromiseRef.current;
|
||||
if (isPending(operation)) return operation;
|
||||
const attempt = (async () => {
|
||||
setStarting(true);
|
||||
setError('');
|
||||
try {
|
||||
const started = await create();
|
||||
if (!started?.operationId) throw new Error('服务端未返回操作编号');
|
||||
setOperation(started);
|
||||
savePendingId({ operationId: started.operationId, startedAt: new Date().toISOString() });
|
||||
void poll(started.operationId);
|
||||
return started;
|
||||
} catch (value) {
|
||||
setError(value instanceof Error ? value.message : '操作未能开始');
|
||||
throw value;
|
||||
} finally {
|
||||
startPromiseRef.current = null;
|
||||
setStarting(false);
|
||||
}
|
||||
})();
|
||||
startPromiseRef.current = attempt;
|
||||
return attempt;
|
||||
}, [operation, poll, savePendingId]);
|
||||
|
||||
const resume = useCallback(() => {
|
||||
if (operation?.operationId) void poll(operation.operationId);
|
||||
else {
|
||||
let pending: StoredOperation | null = null;
|
||||
try { pending = JSON.parse(localStorage.getItem(storageKey(slot)) || 'null') as StoredOperation | null; } catch { pending = null; }
|
||||
if (pending?.operationId) void poll(pending.operationId);
|
||||
else setPollRevision(value => value + 1);
|
||||
}
|
||||
}, [operation?.operationId, poll, slot]);
|
||||
|
||||
const clear = useCallback(() => { activeRef.current++; setOperation(null); setError(''); savePendingId(null); }, [savePendingId]);
|
||||
return { operation, error, busy: starting || Boolean(isPending(operation)), start, resume, clear };
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
"moduleResolution": "Bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { defineConfig } from 'vite';
|
||||
|
||||
export default defineConfig({
|
||||
server: {
|
||||
host: '127.0.0.1',
|
||||
port: 5280,
|
||||
strictPort: true,
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'http://127.0.0.1:5281',
|
||||
changeOrigin: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user