优化:未分类连续维护与柏拉图预汇总,同步已发布修复

This commit is contained in:
2026-11-01 12:40:50 +08:00
parent 572873c6b8
commit 38290f5fec
135 changed files with 17613 additions and 663 deletions
+1 -1
View File
@@ -128,7 +128,7 @@ export function AiMarkdown({ content, className, evidenceLabels, evidencePrefix,
if (isTableStart(lines, index)) {
leadPending = false;
const headers = tableCells(lines[index]);
const hasIndex = headers[0]?.replace(/[*`]/g, '').trim() === '序号';
const hasIndex = ['序号', '排名', '名次'].includes(headers[0]?.replace(/[*`]/g, '').trim() || '');
index += 2;
const body: string[][] = [];
while (index < lines.length && lines[index].trim() && lines[index].includes('|')) body.push(tableCells(lines[index++]));
+19 -15
View File
@@ -10,20 +10,24 @@ export function AnalysisConclusion({ reading, visuals, renderVisuals }: {
}) {
const { comparison, sections } = buildConclusionDocument(reading, visuals);
return <div className="analysis-conclusion-document">
{sections.map((section, index) => <section key={section.id} className="analysis-conclusion-section" data-conclusion-section={section.id}>
<h3 className="analysis-conclusion-title">{section.title}</h3>
{index === 0 && comparison && <div className="analysis-comparison" aria-label={comparison.original}>
<div className="analysis-comparison-name">{comparison.metric}</div>
<div className="analysis-comparison-values">
<div className="analysis-comparison-previous"><span>{comparison.previousLabel}</span><strong>{comparison.previous}</strong></div>
<span className="analysis-comparison-arrow" aria-hidden="true">→</span>
<div className="analysis-comparison-current"><span>{comparison.currentLabel}</span><strong>{comparison.current}</strong></div>
<div className={`analysis-comparison-change ${/下降|降低/.test(comparison.direction) ? 'is-worse' : 'is-better'}`}><strong>{comparison.direction} {comparison.change}</strong><span>{comparison.unit}</span></div>
</div>
</div>}
{section.markdown && <AiMarkdown className="ai-answer" content={section.markdown} layout="sections" />}
{section.note && <p className="analysis-conclusion-context">{section.note}</p>}
{!!section.visuals.length && renderVisuals(section.visuals)}
</section>)}
{sections.map((section, index) => {
const repeatedFigureTitle = section.markdown.trim() === '' && section.visuals.length === 1
&& section.title === section.visuals[0].title && !(index === 0 && comparison);
return <section key={section.id} className="analysis-conclusion-section" data-conclusion-section={section.id}>
{!repeatedFigureTitle && <h3 className="analysis-conclusion-title">{section.title}</h3>}
{index === 0 && comparison && <div className="analysis-comparison" aria-label={comparison.original}>
<div className="analysis-comparison-name">{comparison.metric}</div>
<div className="analysis-comparison-values">
<div className="analysis-comparison-previous"><span>{comparison.previousLabel}</span><strong>{comparison.previous}</strong></div>
<span className="analysis-comparison-arrow" aria-hidden="true">→</span>
<div className="analysis-comparison-current"><span>{comparison.currentLabel}</span><strong>{comparison.current}</strong></div>
<div className={`analysis-comparison-change ${/下降|降低/.test(comparison.direction) ? 'is-worse' : 'is-better'}`}><strong>{comparison.direction} {comparison.change}</strong><span>{comparison.unit}</span></div>
</div>
</div>}
{section.markdown && <AiMarkdown className="ai-answer" content={section.markdown} layout="sections" />}
{section.note && <p className="analysis-conclusion-context">{section.note}</p>}
{!!section.visuals.length && renderVisuals(section.visuals)}
</section>;
})}
</div>;
}
+12 -4
View File
@@ -1,5 +1,5 @@
import { Spin } from 'antd';
import { useEffect, useState, type ReactNode } from 'react';
import { useEffect, useRef, useState, type ReactNode } from 'react';
import { CheckCircleOutlined, CloseCircleOutlined, ClockCircleOutlined, RightOutlined } from '@ant-design/icons';
import { analysisIsRunning, compactAnalysisTimeline, duplicatesFinalAnalysisAnswer } from './analysisConversationState';
import { AiMarkdown } from './AiMarkdown';
@@ -50,8 +50,16 @@ export function AnalysisProcess({ turn, metadata }: { turn: Record<string, unkno
const steps = Array.isArray(rawSteps) ? rawSteps.map(record) : [];
const fallback = steps.map((step, index) => ({ ...step, kind: 'tool', sequence: index, at: step.startedAt, hasResult: ['completed', 'failed'].includes(String(step.status)) }));
const events = groupAdjacentThinking(orderedAnalysisProcess(turn, timeline.length ? timeline : fallback));
const [open, setOpen] = useState(running);
useEffect(() => { setOpen(running); }, [running, turn.id]);
const turnId = String(turn.id || turn.turnId || '');
const [open, setOpen] = useState(false);
const previous = useRef({ turnId, running });
const visibleOpen = previous.current.turnId === turnId && open;
useEffect(() => {
const changedTurn = previous.current.turnId !== turnId;
const completed = previous.current.running && !running;
if (changedTurn || completed) setOpen(false);
previous.current = { turnId, running };
}, [running, turnId]);
const content = events.map(entry => {
if (entry.kind === 'thinking') return <AnalysisThinkingBlock key={String(entry.key)} entry={entry as unknown as ModelThinking} running={running} />;
const text = sanitizeAnalysisDisplayText(String(entry.text || ''));
@@ -63,7 +71,7 @@ export function AnalysisProcess({ turn, metadata }: { turn: Record<string, unkno
return <ToolCall key={String(entry.key)} entry={{ ...entry, ...(step?.recovered ? { recovered: true, text: step.outputSummary || '调整调用后已重试成功' } : {}) }} running={running} />;
});
if (!events.length) return <>{metadata}{running && <p className="analysis-chat-notice" role="status">{sanitizeAnalysisDisplayText(String(turn.progressMessage || plan.progressMessage || '正在准备分析…'))}</p>}</>;
return <details className="analysis-process-history analysis-agent-process" open={open} onToggle={event => setOpen(event.currentTarget.open)}>
return <details className="analysis-process-history analysis-agent-process" open={visibleOpen} onToggle={event => setOpen(event.currentTarget.open)}>
<summary aria-label={running ? '分析运行信息,展开分析过程' : '分析运行信息,展开已保存过程'}>{metadata || <span>{running ? '分析中' : '已完成'}</span>}<RightOutlined aria-hidden="true" /></summary>
<div className="analysis-agent-stream" aria-label={running ? '实时分析对话' : '已保存的分析过程'}>{content}</div>
</details>;
+2 -1
View File
@@ -29,10 +29,11 @@ ${narrativeCss}
${exportCss}
.q-report .ai-markdown-table-wrap{height:auto!important;max-height:none!important;overflow:visible!important;border:0;border-radius:0;background:#fff;margin:10px 0 14px}.q-report .ai-markdown{color:inherit;font:inherit}.q-report .ai-markdown pre{white-space:pre-wrap;overflow-wrap:anywhere}
.q-report{--surface:#fff;--blue-soft:#eef1ff;--line:#dfe5ef;--ink:#202b3c;--muted-ink:#738197;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{--surface:#fff;--blue-soft:#eef1ff;--line:#dfe5ef;--ink:#202b3c;--muted-ink:#738197;box-sizing:border-box;width:900px;max-width:100%;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:1px solid #dfe5ef;border-collapse:collapse;font-size:13px;table-layout:fixed}.q-report th{background:#f2f6fb;color:#53657c;text-align:center;font-weight:650}.q-report th,.q-report td{padding:10px 12px;border:1px solid #dfe5ef;text-align:center;vertical-align:middle}.q-report tbody tr:nth-child(even){background:#f8fafd}.q-report th:first-child,.q-report td:first-child{width:62px;color:#738197;font-variant-numeric:tabular-nums}.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}}
.q-report .q-member-list td{white-space:pre-wrap;overflow-wrap:anywhere;word-break:break-word}.q-report .q-member-list th:last-child,.q-report .q-member-list td:last-child{width:90px}
.q-report .q-source-record-list{margin-top:30px}.q-report .q-source-record-set{margin:22px 0}.q-report .q-source-record-set h3{font-size:15px;margin:18px 0 6px}.q-report .q-source-record-list .q-note{font-size:12px;color:#69778b}.q-report .q-source-record-list table{table-layout:auto}.q-report .q-source-record-list th:first-child,.q-report .q-source-record-list td:first-child{width:48px;min-width:48px;white-space:nowrap;overflow-wrap:normal;word-break:normal;color:inherit;font-variant-numeric:tabular-nums}.q-report .q-source-record-list th:nth-child(2),.q-report .q-source-record-list td:nth-child(2){width:140px}.q-report .q-source-record-list td{white-space:pre-wrap;overflow-wrap:anywhere;word-break:break-word}
@media screen and (max-width:600px){.q-report{padding:24px 18px}.q-report h1{font-size:22px}.q-report .ai-markdown-table-wrap,.q-report .analysis-focus-table-wrap{max-width:100%;overflow-x:auto!important;overflow-y:visible!important}.q-report .ai-markdown-table-wrap table,.q-report .analysis-focus-table-wrap table{min-width:796px}.q-report .q-kpis{flex-wrap:wrap}.q-report .q-kpi{min-width:140px}}
`;
export function ReportDocument({ turn, stamp, visualImages }: { turn: Row; stamp: string; visualImages: ReportVisualImage[] }) {
+18 -7
View File
@@ -3,6 +3,7 @@ import { Alert, App, AutoComplete, Button, Input, Modal, Select, Space, Tag } fr
import { DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import { QualityTable as Table } from './QualityTable';
import { api } from './api';
import { ClassificationSources } from './ClassificationSources';
import { MappingEditorContext } from './MappingEditorContext';
import { classificationConditions, editClassification, type ClassificationCondition, type ClassificationSelection } from './classificationMaintenance';
@@ -18,10 +19,12 @@ export function ClassificationRuleEditor({ children, onUnauthorized }: {
const [stage,setStage]=useState('all');const [target,setTarget]=useState('');const [name,setName]=useState('');
const [preview,setPreview]=useState<Record<string,unknown>|null>(null);
const project=selection?.kind==='projectGroup';
const [sourceRow,setSourceRow]=useState<Record<string,unknown>|null>(null);
const [busy,setBusy]=useState(false);const [error,setError]=useState('');const revision=useRef(0);
const [saving,setSaving]=useState(false);const savingRef=useRef(false);
const resetPreview=()=>{revision.current++;setPreview(null);setError('');};
const open=(next:ClassificationSelection)=>{
setSelection(next);setConditions(classificationConditions(next.row));setStage('all');setTarget('');setName('');resetPreview();
setSourceRow(null);setSelection(next);setConditions(classificationConditions(next.row));setStage('all');setTarget('');setName('');resetPreview();
};
const validate=()=>{
if(!context?.ready||!selection)throw new Error('请等待当前配置读取完成');
@@ -36,18 +39,26 @@ export function ClassificationRuleEditor({ children, onUnauthorized }: {
}catch(value){if(generation===revision.current&&!onUnauthorized(value))setError(value instanceof Error?value.message:'影响预览失败');}
finally{if(generation===revision.current)setBusy(false);}
};
const save=()=>{
try{if(!preview)throw new Error('请先预览当前条件的影响范围');const definition=validate();context!.update(definition);setSelection(null);message.success('规则已加入条件匹配,保存并更新报表后统一生效');}
const save=async()=>{
if(savingRef.current)return;
try{
const definition=validate();
savingRef.current=true;setSaving(true);
if(context!.saveAndApply){context!.saveAndApply({selection:selection!,target:target.trim(),options:{conditions,stage,name}});message.success('已加入后台更新,可继续分类');}
else{context!.update(definition);message.success('规则已加入条件匹配,保存并更新报表后统一生效');}
setSelection(null);
}
catch(value){setError(value instanceof Error?value.message:'规则保存失败');}
finally{savingRef.current=false;setSaving(false);}
};
return <>{children(open)}<Modal className="management-modal classification-rule-modal" width={880} open={!!selection}
title={project?'编辑项目组分类':'编辑业务分组分类'} okText={preview?'保存到条件匹配':'请先预览影响'} okButtonProps={{disabled:busy||!preview||!context?.ready}}
onOk={save} onCancel={()=>{revision.current++;setBusy(false);setSelection(null);}}>
title={project?'编辑项目组分类':'编辑业务分组分类'} okText={context?.saveAndApply?'保存并更新报表':'保存到条件匹配'} okButtonProps={{disabled:!target.trim()||!context?.ready}} confirmLoading={saving}
onOk={()=>void save()} onCancel={()=>{if(saving)return;revision.current++;setBusy(false);setSelection(null);}}>
{project?<p>客户代码 {String(selection?.row.customerCode)} · 业务分组 {String(selection?.row.businessGroup)}</p>:<><div className="classification-rule-fields">
<label>规则名称<Input aria-label="分类规则名称" value={name} maxLength={160} placeholder="默认使用业务分组名称" onChange={e=>{setName(e.target.value);}}/></label>
<label>适用范围<Select aria-label="分类适用范围" value={stage} options={[{value:'all',label:'黑片和亮片'},{value:'black',label:'黑片'},{value:'bright',label:'亮片'}]} onChange={value=>{setStage(value);resetPreview();setBusy(false);}}/></label>
</div>
<div className="classification-condition-heading"><strong>匹配条件</strong><Select aria-label="添加分类条件" placeholder="添加条件" value={undefined} style={{width:150}}
<div className="classification-condition-heading"><strong>匹配条件 <Button type="link" onClick={()=>setSourceRow(selection!.row)}>查看原始数据</Button></strong><Select aria-label="添加分类条件" placeholder="添加条件" value={undefined} style={{width:150}}
options={Object.entries(labels).filter(([key])=>!conditions.some(c=>c.field===key)).map(([value,label])=>({value,label}))}
disabled={conditions.length===4} suffixIcon={<PlusOutlined/>} onChange={field=>{setConditions([...conditions,classificationConditions(selection!.row).find(c=>c.field===field)!]);resetPreview();setBusy(false);}}/></div>
<div className="classification-conditions">{conditions.map(condition=><div className="classification-condition-row" key={condition.field}>
@@ -65,5 +76,5 @@ export function ClassificationRuleEditor({ children, onUnauthorized }: {
<Table size="small" bordered scroll={{x:720}} pagination={{pageSize:15,showSizeChanger:false}} rowKey={row=>JSON.stringify([row.stage,row.department,row.month,row.currentGroup])} dataSource={(preview.items??[]) as Record<string,unknown>[]}
columns={[{title:'阶段',dataIndex:'stage',render:value=>value==='black'?'黑片':'亮片'},{title:'产业部',dataIndex:'department'},{title:'月份',dataIndex:'month'},{title:project?'当前项目组':'当前业务分组',dataIndex:'currentGroup',render:value=>value||'未分类'},{title:'行数',dataIndex:'rowCount',align:'right'},{title:project?'目标项目组':'目标业务分组',render:()=>target}]}/>
</div>}
</Modal></>;
</Modal><ClassificationSources row={sourceRow} onClose={()=>setSourceRow(null)} onUnauthorized={onUnauthorized}/></>;
}
+54
View File
@@ -0,0 +1,54 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { Alert, Button, Drawer, Empty, Pagination, Select, Spin, Modal, Input } from 'antd';
import { api } from './api';
import { QualityTable } from './QualityTable';
import { BusinessValue } from './BusinessValue';
import { classificationConditions } from './classificationMaintenance';
import { publicJson } from './publicDataDisplay';
const withoutSystemVersionFields=(value:unknown)=>JSON.parse(publicJson(value)??'{}') as Record<string,unknown>;
export function ClassificationSources({row,onClose,onUnauthorized}:{row:Record<string,unknown>|null;onClose:()=>void;onUnauthorized:(error:unknown)=>boolean}) {
const [page,setPage]=useState(1),[revision,setRevision]=useState(0);
const [result,setResult]=useState<Awaited<ReturnType<typeof api.classificationSources>>|null>(null);
const [loading,setLoading]=useState(false),[error,setError]=useState('');
const [selected,setSelected]=useState<string[]>();
const [inspecting,setInspecting]=useState<Record<string,unknown>|null>(null),[rawSearch,setRawSearch]=useState('');
const release=useRef<string|undefined>(undefined);
const cache=useRef(new Map<number,Awaited<ReturnType<typeof api.classificationSources>>>());
const key=JSON.stringify(row);
useEffect(()=>{setPage(1);setResult(null);setSelected(undefined);setInspecting(null);release.current=undefined;cache.current.clear();},[key]);
useEffect(()=>{
if(!row)return;
const controller=new AbortController();
const cached=cache.current.get(page);if(cached){setResult(cached);setLoading(false);return;}
setLoading(true);setError('');
api.classificationSources({stage:String(row.stage),conditions:classificationConditions(row),page,pageSize:15,releaseId:release.current},controller.signal).then(value=>{
if(controller.signal.aborted)return;
release.current=value.releaseId;cache.current.set(page,value);setResult(value);
}).catch(value=>{if(!controller.signal.aborted&&!onUnauthorized(value))setError(value instanceof Error?value.message:'原始数据读取失败');})
.finally(()=>{if(!controller.signal.aborted)setLoading(false);});
return()=>controller.abort();
},[key,page,revision]);
const fields=useMemo(()=>[...new Set((result?.rows??[]).flatMap(item=>Object.keys(withoutSystemVersionFields(item.raw??{}) as Record<string,unknown>)))],[result]);
const defaultFields=['客户代码','客户名称','业务员','事业部','成品规格'].filter(field=>fields.includes(field));
const visibleFields=selected??(defaultFields.length?defaultFields:fields.filter(field=>field!=='序号').slice(0,5));
const columns=[
{title:'来源文件',dataIndex:'sourceFile',width:230},
{title:'工作表',dataIndex:'sheet',width:110},
{title:'行号',dataIndex:'rowNumber',width:80},
{title:'期间',dataIndex:'month',width:100},
{title:'原始行数据',width:190,render:(_:unknown,item:Record<string,unknown>)=><Button type="link" onClick={()=>{setInspecting(item);setRawSearch('');}}>查看全部原始字段</Button>},
...visibleFields.map(field=>({title:field,width:160,render:(_:unknown,item:Record<string,unknown>)=>String((item.raw as Record<string,unknown>)?.[field]??'—')})),
];
return <><Drawer className="source-records-drawer" title="分类参考 · 原始数据" open={!!row} onClose={onClose} width={Math.min(1180,window.innerWidth)} destroyOnHidden>
<div className="resource-toolbar"><span>{row?.stage==='black'?'黑片':'亮片'} · {String(row?.department??'—')} · {String(row?.product??'—')}{result?` · 共 ${result.total} 行`:''}</span>
<Select mode="multiple" allowClear style={{minWidth:260,maxWidth:'100%'}} aria-label="原始数据展示字段" placeholder="选择展示字段" value={selected} options={fields.map(value=>({value}))} onChange={setSelected}/></div>
{error&&<Alert type="error" showIcon message={error} action={<Button onClick={()=>setRevision(value=>value+1)}>重试</Button>}/>}
{loading?<div className="loading-panel"><Spin/>正在读取原始数据…</div>:result?.rows.length?<QualityTable dataSource={result.rows} columns={columns} rowKey="id" pagination={false} indexOffset={(page-1)*15} scroll={{x:850+visibleFields.length*160}}/>:<Empty description="当前条件没有原始数据"/>}
{!!result&&result.total>15&&<Pagination current={page} pageSize={15} total={result.total} onChange={setPage} showSizeChanger={false} className="records-pagination"/>}
</Drawer><Modal className="management-modal classification-raw-record-modal" open={!!inspecting} title="原始行数据" width={860} zIndex={1200} footer={<Button onClick={()=>setInspecting(null)}>关闭</Button>} onCancel={()=>setInspecting(null)}>
<p>{String(inspecting?.sourceFile??'')} · {String(inspecting?.sheet??'')} · 第 {String(inspecting?.rowNumber??'')} 行</p>
<Input allowClear placeholder="查找字段或内容" value={rawSearch} onChange={event=>setRawSearch(event.target.value)}/>
<div style={{maxHeight:'60vh',overflow:'auto',marginTop:12}}><BusinessValue value={Object.fromEntries(Object.entries(withoutSystemVersionFields(inspecting?.raw??{})).filter(([key,value])=>!rawSearch||`${key} ${String(value??'')}`.toLowerCase().includes(rawSearch.toLowerCase())))}/></div>
</Modal></>;
}
+43 -73
View File
@@ -15,6 +15,9 @@ import { usePageCache, useMaintenanceRefresh } from './pageCache';
import { FilterFieldSettings } from './FilterFieldSettings';
import { isInternalDataField, publicJson, readableRuleDescription } from './publicDataDisplay';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useClassificationQueue } from './useClassificationQueue';
import { useUnclassifiedInventory } from './useUnclassifiedInventory';
import type { ClassificationCommand } from './classificationQueue';
import {
Alert,
App,
@@ -386,6 +389,8 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
const [form] = Form.useForm<{ name: string; description: string }>();
const [draftDefinition, setDraftDefinition] = useState<ConfigDefinition>({});
const loadedDefinitionKey=useRef('');
const loadedDefinition=useRef('');
const classificationUpdates=useClassificationQueue(kind==='mappings'?String(user.id):'inactive-'+kind);
const [ruleSchema, setRuleSchema] = useState<Record<string, unknown> | null>(null);
const [ruleSchemaError, setRuleSchemaError] = useState('');
const [publishedNames, setPublishedNames] = useState<PublishedConfigNames | null>(null);
@@ -405,8 +410,8 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
? { ...items.find(item => String(item.id || '') === String(workflowStatus.activeMapping?.id || '')), ...workflowStatus.activeMapping }
: items.find(item => String(item.status).toUpperCase() === 'ACTIVE');
const load = async () => {
setLoading(true);
const load = async (silent = false) => {
if(!silent)setLoading(true);
try {
const result = isRules ? await api.rules() : await api.mappings();
setItems(collectionItems(result)); setError('');
@@ -438,7 +443,7 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
const definition = isRules && testMode && String(active?.id ?? fallback?.id) === 'pq-dax-v1' && ruleSchema?.defaultDefinition
? ruleSchema.defaultDefinition : storedDefinition;
const definitionKey=JSON.stringify([kind,active?.id??fallback?.id,definition]);
if (definition && typeof definition === 'object' && loadedDefinitionKey.current!==definitionKey) {loadedDefinitionKey.current=definitionKey;setDraftDefinition(JSON.parse(JSON.stringify(definition)) as ConfigDefinition);}
if (definition && typeof definition === 'object' && loadedDefinitionKey.current!==definitionKey) {loadedDefinitionKey.current=definitionKey;const serialized=JSON.stringify(definition),prior=loadedDefinition.current;setDraftDefinition(previous=>!prior||JSON.stringify(previous)===prior?JSON.parse(serialized) as ConfigDefinition:previous);loadedDefinition.current=serialized;}
const metadata = items.find(row => String(row.id) === String(active?.id)) ?? fallback;
form.setFieldsValue({ name: testMode ? currentConfigurationName(active?.name ?? metadata?.name, metadata?.createdAt) : isRules ? ruleDisplayName(active?.name || fallback?.name || '测试计算规则') : String(active?.name || fallback?.name || '测试基础数据与对应关系'), description: isRules ? readableRuleDescription(active?.description || fallback?.description) : String(active?.description || fallback?.description || '') });
}, [workflowStatus, items, kind, isRules, testMode, ruleSchema]);
@@ -556,6 +561,10 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
];
const simpleStageLabel: Record<string, string> = { QUEUED: '等待处理', VALIDATING: '检查配置与来源', VERSION_CREATED: '保存配置', CLASSIFYING_UNASSIGNED:'处理未分类记录', REBUILDING: '重新计算报表', PUBLISHING: '更新当前报表', COMPLETED: '已完成', FAILED: '处理失败' };
const saveClassification = (command: ClassificationCommand) => {
classificationUpdates.queue.enqueue(command,draftDefinition,Array.isArray(matchMetadata?.defaultRules)?matchMetadata.defaultRules:[]);
};
const classificationBusy=classificationUpdates.jobs.some(job=>!['failed','completed'].includes(job.status));
const applyCurrent = async () => {
try {
await form.validateFields();
@@ -567,15 +576,19 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
}
};
useMaintenanceRefresh(() => { void load(); void refreshWorkflowStatus(); void loadEditorSupport(); });
useMaintenanceRefresh(() => { void load(true); void refreshWorkflowStatus(); void loadEditorSupport(); });
if (!workflowStatusLoaded) return <div className="management-page"><div className="loading-panel"><Spin />正在读取当前维护模式…</div></div>;
if (testMode) {
const notices = <>
{kind==='mappings'&&classificationUpdates.jobs.some(job=>job.status!=='completed')&&<div className="classification-queue-status" role="status">
{classificationBusy&&<span><Spin size="small"/> 后台更新中 · {classificationUpdates.jobs.filter(job=>!['failed','completed'].includes(job.status)).length} 条</span>}
{classificationUpdates.jobs.filter(job=>['failed','paused'].includes(job.status)).map(job=><Alert key={job.id} type="error" showIcon message={`${job.target}:${job.error}`} action={<><Button size="small" onClick={()=>classificationUpdates.queue.retry(job.id)}>重试</Button>{job.status==='failed'&&<Button size="small" onClick={()=>classificationUpdates.queue.dismiss(job.id)}>关闭</Button>}</>}/>)}
</div>}
{error && <Alert showIcon type="error" message="配置清单读取失败" description={error} />}
{isRules && ruleSchemaError && <Alert showIcon type="error" message="规则编辑结构读取失败" description={ruleSchemaError} />}
{!canApplyWorkflow && <Alert showIcon type="info" message="当前账号可查看配置;保存和更新报表需要发布权限。" />}
{workflowOperation.error && <Alert showIcon type="error" message="保存或报表更新失败" description={workflowOperation.error} action={workflowOperation.operation?.operationId ? <Button size="small" onClick={workflowOperation.resume}>重试读取进度</Button> : undefined} />}
{workflowOperation.operation && <section className="nc-operation-status panel"><div><strong>{simpleStageLabel[String(workflowOperation.operation.stage || workflowOperation.operation.status)] || '正在处理'}</strong></div><Progress percent={workflowOperation.busy ? undefined : String(workflowOperation.operation.status).toUpperCase() === 'COMPLETED' ? 100 : 0} status={String(workflowOperation.operation.status).toUpperCase() === 'FAILED' ? 'exception' : workflowOperation.busy ? 'active' : 'success'} /></section>}
{workflowOperation.operation && <section className="nc-operation-status panel"><div><strong>{simpleStageLabel[String(workflowOperation.operation.stage || workflowOperation.operation.status)] || '正在处理'}</strong></div>{workflowOperation.busy ? <Spin size="small" /> : <Progress percent={String(workflowOperation.operation.status).toUpperCase() === 'COMPLETED' ? 100 : 0} status={String(workflowOperation.operation.status).toUpperCase() === 'FAILED' ? 'exception' : 'success'} />}</section>}
</>;
const editor = (mode: 'catalog' | 'lookups' | 'matchRules' | 'rules') => <div className="management-page nc-simplified-config-page flat-config-page">
{notices}
@@ -590,14 +603,14 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
: mode === 'lookups' ? <MappingDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} simplified readOnly={!canApplyWorkflow} />
: <MatchRulesDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} metadata={matchMetadata??workflowStatus} readOnly={!canApplyWorkflow} />}
{!isRules && validateStructuredMappingDefinition(draftDefinition, publishedNames?.groupDepartments).length > 0 && <Alert showIcon type="warning" message="有名录引用需要留意" description={<ul className="structured-config-error-list">{validateStructuredMappingDefinition(draftDefinition, publishedNames?.groupDepartments).slice(0,12).map((issue,index)=><li key={index}>{issue}</li>)}</ul>} />}
{canApplyWorkflow && <div className="nc-simple-save-row"><span>保存后检查配置并更新报表。</span><Button type="primary" size="large" disabled={workflowOperation.busy || (isRules && !ruleSchema)} loading={workflowOperation.busy} onClick={() => void applyCurrent()}>保存并更新报表</Button></div>}
{canApplyWorkflow && <div className="nc-simple-save-row"><span>保存后检查配置并更新报表。</span><Button type="primary" size="large" disabled={workflowOperation.busy || classificationBusy || (isRules && !ruleSchema)} loading={workflowOperation.busy} onClick={() => void applyCurrent()}>保存并更新报表</Button></div>}
</section>
</div>;
if (kind === 'masterData') return <><Form form={form} component={false} />{editor('catalog')}</>;
if (kind === 'mappings') return <MappingEditorContext.Provider value={{definition:draftDefinition,update:setDraftDefinition,ready:!loading && !!workflowMappingBase?.id && !!matchMetadata,defaultRules:Array.isArray(matchMetadata?.defaultRules)?matchMetadata.defaultRules:[],projectGroups:publishedNames?.projectGroups??[],groups:Array.isArray((draftDefinition.masterData as Record<string,unknown>|undefined)?.groups)?((draftDefinition.masterData as Record<string,unknown>).groups as Record<string,unknown>[]).filter(row=>row.enabled!==false).map(row=>String(row.name)):publishedNames?.groups??[]}}><Form form={form} component={false} /><ManagementSections items={[
if (kind === 'mappings') return <MappingEditorContext.Provider value={{definition:draftDefinition,update:setDraftDefinition,saveAndApply:saveClassification,classificationJobs:classificationUpdates.jobs,acknowledgeClassifications:ids=>classificationUpdates.queue.acknowledge(ids),ready:canApplyWorkflow && !loading && !workflowOperation.busy && !!workflowMappingBase?.id && !!matchMetadata,defaultRules:Array.isArray(matchMetadata?.defaultRules)?matchMetadata.defaultRules:[],projectGroups:publishedNames?.projectGroups??[],groups:Array.isArray((draftDefinition.masterData as Record<string,unknown>|undefined)?.groups)?((draftDefinition.masterData as Record<string,unknown>).groups as Record<string,unknown>[]).filter(row=>row.enabled!==false).map(row=>String(row.name)):publishedNames?.groups??[]}}><Form form={form} component={false} /><ManagementSections items={[
{ key: 'lookups', label: '基础对应', children: editor('lookups') },
{ key: 'matchRules', label: '条件匹配', children: editor('matchRules') },
...(extraSections ?? []),
...(extraSections ?? []).map(section => ({ ...section, children: <>{notices}{section.children}</> })),
]} /></MappingEditorContext.Provider>;
return editor('rules');
}
@@ -690,31 +703,12 @@ function MappingMaintenancePage({ user, onUnauthorized, onNavigate }: Omit<Manag
}
function UnclassifiedSourcesPanel({ onUnauthorized, onEdit }: { onUnauthorized: (error: unknown) => boolean; onEdit?: (selection: ClassificationSelection) => void }) {
const [items, setItems] = useState<Record<string, unknown>[]>([]);
const [total, setTotal] = useState(0);
const [page, setPage] = useState(1);
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const { refreshKey } = usePageCache();
const pages = useRef(new Map<string, Promise<ReturnType<typeof unwrapItems>>>());
const loadRevision = useRef(0);
const load = async (force = false) => {
const revision = ++loadRevision.current;
const key = `${refreshKey}:${page}`;
if (force) pages.current.clear();
setLoading(true);
let request: Promise<ReturnType<typeof unwrapItems>> | undefined;
try {
request = pages.current.get(key) ?? api.unclassifiedSources(page, TABLE_PAGE_SIZE).then(unwrapItems);
pages.current.set(key, request);
if (pages.current.size > 12) pages.current.delete(pages.current.keys().next().value!);
const result = await request;
if (revision !== loadRevision.current) return;
setItems(result.items); setTotal(Number(result.total ?? result.items.length)); setError('');
} catch (value) { if (pages.current.get(key) === request) pages.current.delete(key); if (revision === loadRevision.current && !onUnauthorized(value)) setError(apiMessage(value)); }
finally { if (revision === loadRevision.current) setLoading(false); }
};
useEffect(() => { void load(); }, [page]);
const inventory=useUnclassifiedInventory('group',onUnauthorized);
const [page,setPage]=useState(1);
const total=inventory.items.length;
const currentPage=Math.min(page,Math.max(1,Math.ceil(total/TABLE_PAGE_SIZE)));
const items=inventory.items.slice((currentPage-1)*TABLE_PAGE_SIZE,currentPage*TABLE_PAGE_SIZE);
const {loading,error}=inventory;
const columns: ColumnsType<Record<string, unknown>> = [
{ title: '阶段', dataIndex: 'stage', width: 85, render: value => value === 'black' ? '黑片' : '亮片' },
{ title: '产业部', dataIndex: 'department', width: 140, render: toText },
@@ -727,50 +721,27 @@ function UnclassifiedSourcesPanel({ onUnauthorized, onEdit }: { onUnauthorized:
{ title: '总重量 / kg', dataIndex: 'totalWeight', width: 140, align: 'right' },
{ title: '操作', key: 'action', width: 125, fixed: 'right', render: (_, row) => <Button type="link" disabled={!onEdit} onClick={() => onEdit?.({ kind: 'group', row })}>编辑分类</Button> },
];
useMaintenanceRefresh(() => { void load(true); });
return <div className="management-page">
{error && <Alert type="error" showIcon message={error} />}
<section className="panel section-panel">
<div className="resource-toolbar"><strong>业务分组未分类汇总</strong><div className="completion-actions"><span>共 {total} 条</span><Button icon={<ReloadOutlined />} onClick={() => void load(true)}>刷新</Button></div></div>
<div className="resource-table"><Table size="small" bordered loading={loading} columns={columns} dataSource={items} rowKey={row => JSON.stringify([row.stage, row.department, row.product, row.sourceKey])} pagination={false} indexOffset={(page - 1) * TABLE_PAGE_SIZE} scroll={{ x: 1280 }} /></div>
{total > TABLE_PAGE_SIZE && <Pagination className="records-pagination" current={page} pageSize={TABLE_PAGE_SIZE} total={total} onChange={setPage} />}
<div className="resource-toolbar"><strong>业务分组未分类汇总</strong><div className="completion-actions"><span>共 {total} 条</span><Button icon={<ReloadOutlined />} onClick={() => void inventory.refresh()}>刷新</Button></div></div>
<div className="resource-table"><Table size="small" bordered loading={loading} columns={columns} dataSource={items} rowKey={row => JSON.stringify([row.stage, row.department, row.product, row.sourceKey])} pagination={false} indexOffset={(currentPage - 1) * TABLE_PAGE_SIZE} scroll={{ x: 1280 }} /></div>
{total > TABLE_PAGE_SIZE && <Pagination className="records-pagination" current={currentPage} pageSize={TABLE_PAGE_SIZE} total={total} onChange={setPage} />}
</section>
</div>;
}
function MappingIssueResolutionPanel({ onUnauthorized, onEdit }: { onUnauthorized: (error: unknown) => boolean; onEdit?: (selection: ClassificationSelection) => void }) {
const [items, setItems] = useState<Record<string, unknown>[]>([]);
const [total, setTotal] = useState(0);
const [page, setPage] = useState(1);
const [customerCode, setCustomerCode] = useState<string>();
const [businessGroup, setBusinessGroup] = useState<string>();
const [department, setDepartment] = useState<string>();
const [filterOptions, setFilterOptions] = useState<{ customerCodes: string[]; businessGroups: string[]; departments: string[] }>({ customerCodes: [], businessGroups: [], departments: [] });
const [loading, setLoading] = useState(true);
const loadRevision = useRef(0);
const [error, setError] = useState('');
const { refreshKey } = usePageCache();
const pages = useRef(new Map<string, ReturnType<typeof api.unclassifiedProjects>>());
const load = async (force = false) => {
const revision = ++loadRevision.current;
const key = JSON.stringify([refreshKey, page, customerCode, businessGroup, department]);
if (force) pages.current.clear();
setLoading(true);
let request: ReturnType<typeof api.unclassifiedProjects> | undefined;
try {
request = pages.current.get(key) ?? api.unclassifiedProjects({ page, pageSize: TABLE_PAGE_SIZE, customerCode, businessGroup, department });
pages.current.set(key, request);
if (pages.current.size > 12) pages.current.delete(pages.current.keys().next().value!);
const result = await request;
if (revision !== loadRevision.current) return;
setFilterOptions(result.filterOptions ?? { customerCodes: [], businessGroups: [], departments: [] });
const normalized = unwrapItems(result);
setItems(normalized.items); setTotal(Number(normalized.total || normalized.items.length)); setError('');
} catch (value) { if (pages.current.get(key) === request) pages.current.delete(key); if (revision === loadRevision.current && !onUnauthorized(value)) setError(apiMessage(value)); }
finally { if (revision === loadRevision.current) setLoading(false); }
};
useEffect(() => { void load(); }, [page, customerCode, businessGroup, department]);
const inventory=useUnclassifiedInventory('projectGroup',onUnauthorized);
const [page,setPage]=useState(1);
const [customerCode,setCustomerCode]=useState<string>();
const [businessGroup,setBusinessGroup]=useState<string>();
const [department,setDepartment]=useState<string>();
const {loading,error}=inventory;
const filtered=inventory.items.filter(row=>(!customerCode||row.customerCode===customerCode)&&(!businessGroup||row.businessGroup===businessGroup)&&(!department||(Array.isArray(row.departments)&&row.departments.includes(department))));
const total=filtered.length,currentPage=Math.min(page,Math.max(1,Math.ceil(total/TABLE_PAGE_SIZE)));
const items=filtered.slice((currentPage-1)*TABLE_PAGE_SIZE,currentPage*TABLE_PAGE_SIZE);
const filterOptions={customerCodes:[...new Set(inventory.all.map(row=>String(row.customerCode)))].sort(),businessGroups:[...new Set(inventory.all.map(row=>String(row.businessGroup)))].sort(),departments:[...new Set(inventory.all.flatMap(row=>Array.isArray(row.departments)?row.departments.map(String):[]))].sort()};
const columns: ColumnsType<Record<string, unknown>> = [
{ title: '客户代码', dataIndex: 'customerCode', key: 'customerCode', fixed: 'left', width: 120, render: toText },
{ title: '业务分组', dataIndex: 'businessGroup', key: 'businessGroup', width: 190, render: toText },
@@ -782,16 +753,15 @@ function MappingIssueResolutionPanel({ onUnauthorized, onEdit }: { onUnauthorize
{ title: '状态', dataIndex: 'status', key: 'status', width: 120, render: value => <Tag color={value === 'OPEN' ? 'orange' : value === 'REVALIDATED' ? 'green' : 'blue'}>{value==='OPEN'?'待处理':toText(value)}</Tag> },
{ title: '操作', key: 'action', width: 120, fixed: 'right', render: (_, row) => <Button type="link" disabled={!onEdit} onClick={() => onEdit?.({ kind: 'projectGroup', row })}>编辑分类</Button> },
];
useMaintenanceRefresh(() => { void load(true); });
return <div className="management-page">
{error && <Alert showIcon type="error" message="映射问题操作失败" description={error} />}
<section className="panel section-panel"><div className="resource-toolbar"><strong>项目组未分类汇总</strong><div className="completion-actions"><span>共 {total} 条</span><div className="completion-actions"><Button icon={<ReloadOutlined />} onClick={() => void load(true)}>刷新</Button></div></div></div>
<section className="panel section-panel"><div className="resource-toolbar"><strong>项目组未分类汇总</strong><div className="completion-actions"><span>共 {total} 条</span><div className="completion-actions"><Button icon={<ReloadOutlined />} onClick={() => void inventory.refresh()}>刷新</Button></div></div></div>
<div className="resource-toolbar mapping-issue-filters">
<Select {...readableSelectPopup} showSearch allowClear aria-label="筛选客户代码" placeholder="客户代码" value={customerCode} options={filterOptions.customerCodes.map(value => ({ label: value, value }))} onChange={value => { setCustomerCode(value); setPage(1); }} />
<Select {...readableSelectPopup} showSearch allowClear aria-label="筛选业务分组" placeholder="业务分组" value={businessGroup} options={filterOptions.businessGroups.map(value => ({ label: value, value }))} onChange={value => { setBusinessGroup(value); setPage(1); }} />
<Select {...readableSelectPopup} showSearch allowClear aria-label="筛选产业部" placeholder="产业部" value={department} options={filterOptions.departments.map(value => ({ label: value, value }))} onChange={value => { setDepartment(value); setPage(1); }} />
<Button onClick={() => { setCustomerCode(undefined); setBusinessGroup(undefined); setDepartment(undefined); setPage(1); }}>重置</Button>
</div>{loading ? <div className="loading-panel"><Spin />正在读取未命中问题…</div> : items.length ? <div className="resource-table"><Table size="small" bordered columns={columns} dataSource={items} rowKey={row => String(row.id)} pagination={false} indexOffset={(page - 1) * TABLE_PAGE_SIZE} scroll={{ x: 1320 }} /></div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="没有项目组未分类记录" />}{total > TABLE_PAGE_SIZE && <Pagination className="records-pagination" current={page} pageSize={TABLE_PAGE_SIZE} total={total} showTotal={count => `共 ${count} 条问题`} onChange={setPage} />}</section>
</div>{loading ? <div className="loading-panel"><Spin />正在读取未命中问题…</div> : items.length ? <div className="resource-table"><Table size="small" bordered columns={columns} dataSource={items} rowKey={row => String(row.id)} pagination={false} indexOffset={(currentPage - 1) * TABLE_PAGE_SIZE} scroll={{ x: 1320 }} /></div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="没有项目组未分类记录" />}{total > TABLE_PAGE_SIZE && <Pagination className="records-pagination" current={currentPage} pageSize={TABLE_PAGE_SIZE} total={total} showTotal={count => `共 ${count} 条问题`} onChange={setPage} />}</section>
</div>;
}
@@ -1726,7 +1696,7 @@ function AnalysisTurn({ turn: sourceTurn, onResume, onRetry, onClarify, onUnauth
{resumable ? <AiMarkdown content={answer} className="ai-answer" />
: <AnalysisNarrative answer={answer} visuals={visuals} visualState={result.visualState} question={question} turnId={String(turn.id || '')} beforeExport={() => authorizeAnalysisSnapshot(turn)} turn={turn} />}
</> : <p className={resumable ? 'analysis-chat-notice' : undefined}>{resumable ? '分析任务仍在运行,尚未返回完整回答。' : emptyStatus}</p>}
{status === 'PARTIAL' && answer && <p className="analysis-chat-notice">{partialAnalysisNotice(result.stopReason || turn.stopReason || (isObjectRecord(turn.plan) ? turn.plan.stopReason : ''))}</p>}
{status === 'PARTIAL' && answer && <p className="analysis-chat-notice">{partialAnalysisNotice(result.stopReason || turn.stopReason || (isObjectRecord(turn.plan) ? turn.plan.stopReason : ''), result)}</p>}
<div className="analysis-message-actions">
{(reportMarkdown.trim() || reportHtml?.trim()) && <NativeAnalysisReport turn={turn} reportMarkdown={reportMarkdown} reportHtml={reportHtml} />}
{!reportMarkdown.trim() && !reportHtml?.trim() && answer && ['COMPLETED', 'PARTIAL'].includes(status) && <AnalysisReportExport turn={turn} />}
+4
View File
@@ -1,7 +1,11 @@
import { createContext } from 'react';
import type { ClassificationCommand, ClassificationJob } from './classificationQueue';
export type MappingEditorState = {
definition: Record<string, unknown>;
update: (definition: Record<string, unknown>) => void;
saveAndApply?: (command: ClassificationCommand) => void;
classificationJobs?: ClassificationJob[];
acknowledgeClassifications?: (ids: string[]) => void;
ready: boolean;
defaultRules: unknown[];
groups: string[];
+1 -1
View File
@@ -729,7 +729,7 @@ export default function QueryPage({ page, onUnauthorized }: {
<ExtraQueryFilters key={queryRevision} projectGroup={projectGroup} projectGroups={options?.projectGroupStatus === 'READY' ? options.projectGroups : undefined} onProjectGroup={setProjectGroup} value={extraFilters} onChange={setExtraFilters} onUnauthorized={onUnauthorized} />
<div className="query-toolbar-tail">
<span className={`query-status ${queryBusy || summaryBusy ? 'busy' : currentMetricsError || summaryMetricsError ? 'failed' : ''}`}><i />{queryBusy || summaryBusy ? '正在查询' : currentMetricsError || summaryMetricsError ? '查询失败' : '查询完成'}</span>
<Button type="text" onClick={() => { const previous = previousCompleteMonth(); const previousQuarter = previousCompleteQuarter(); setDepartment([]); setGroup([]); setProduct([]); setProjectGroup([]); setExtraFilters({}); setSearch(''); setAppliedSearch(''); setTrendObject(''); setYear(page === 'overall' ? new Date().getFullYear() : previous.year); setMonth(previous.month); setQuarter(previousQuarter.quarter); setPeriod(page === 'overall' ? 'year' : 'month'); setTrendGranularity('month'); }}>重置</Button>
<Button type="default" onClick={() => { const previous = previousCompleteMonth(); const previousQuarter = previousCompleteQuarter(); setDepartment([]); setGroup([]); setProduct([]); setProjectGroup([]); setExtraFilters({}); setSearch(''); setAppliedSearch(''); setTrendObject(''); setYear(page === 'overall' ? new Date().getFullYear() : previous.year); setMonth(previous.month); setQuarter(previousQuarter.quarter); setPeriod(page === 'overall' ? 'year' : 'month'); setTrendGranularity('month'); }}>重置</Button>
</div>
{organizationSummary.length > 0 && <div className="organization-breadcrumb" aria-label="当前组织路径">
<span>组织路径</span><Button type="link" onClick={() => { setDepartment([]); setGroup([]); setProduct([]); }}>全部组织</Button>
+8 -1
View File
@@ -86,8 +86,15 @@ export function analysisScrollFollows(distanceFromBottom: number, following: boo
return following;
}
export function partialAnalysisNotice(reason: unknown): string {
export function partialAnalysisNotice(reason: unknown, result: Record<string, unknown> = {}): string {
const value = String(reason || '');
const quality = result.answerQuality && typeof result.answerQuality === 'object' && !Array.isArray(result.answerQuality)
? result.answerQuality as Record<string, unknown> : {};
if (quality.version === 1) {
if (quality.dataComplete === true && quality.narrativeComplete === false) return '数据已查齐,答案尚未完整整理。已保留核验结果,可重新分析。';
if (quality.dataComplete === true && quality.chartsComplete === false) return '数据与文字已完成,部分图表尚未生成。可重试图表。';
if (quality.dataComplete === false) return '部分所需数据尚未通过完整性核验,当前仅展示可确认的结果。具体缺口见本轮说明。';
}
if (value === 'mcp_error') return '部分数据查询未成功,已保留其余分析结果。可以重试或继续追问。';
if (value === 'length') return '回答达到输出长度上限,已保存现有内容。可以重试或继续追问。';
if (/timeout|超时/.test(value)) return '本轮分析达到处理时限,已保存现有结果。可以重试或继续追问。';
+156 -20
View File
@@ -1,6 +1,6 @@
import { buildAnalysisNarrative, type AnalysisNarrativeModel } from './analysisReportModel.ts';
import { sanitizeAnalysisDisplayText } from './analysisDisplayText.ts';
import { parseAnalysisVisuals, type AnalysisVisual } from './analysisVisualsModel.ts';
import { parseAnalysisVisuals, combineStageDefectVisuals, type AnalysisVisual } from './analysisVisualsModel.ts';
import { parseAnalysisPeriod } from './analysisPeriodModel.ts';
import { isAnalysisEvidenceRef, isQueryEvidenceRef, analysisTextEvidenceRefs, analysisEvidenceParts } from './analysisEvidenceRefs.ts';
@@ -67,31 +67,75 @@ export function conclusionMarkdown(reading: AnalysisReadingSummary, keepEvidence
// Preserve the checked business answer's original sections and tables. The old
// summary split can separate a table from its heading, so it is not a renderer.
let hiddenLevel = 0;
let fenced = false;
const businessAnswer = reading.fullAnswer.split('\n').filter(line => {
const heading = line.match(/^(#{1,6})\s+(.+?)\s*$/);
if (/^\s*```/.test(line)) { fenced = !fenced; return !hiddenLevel; }
const heading = !fenced ? line.match(/^(#{1,6})\s+(.+?)\s*$/) : null;
if (heading) {
if (hiddenLevel && heading[1].length <= hiddenLevel) hiddenLevel = 0;
if (/^(完整统计依据|统计数据附录|数据明细|完整证据|历史事实依据)$/.test(heading[2])) hiddenLevel = heading[1].length;
const title = heading[2].replace(/[((].*?[))]$/, '').trim();
if (/^(?:附录(?:[::].*)?|完整统计依据|统计数据附录|数据明细|完整证据|历史事实依据|关键依据|证据审计|证据审查|查询依据|证据编号|来源明细|证据明细|依据审计|证据核查记录)$/.test(title)) hiddenLevel = heading[1].length;
}
return !hiddenLevel;
}).join('\n').trim();
const clean = (value: string) => conclusionDisplayText(value, reading.evidenceRefs, keepEvidence);
const checkedBody = clean(businessAnswer);
const selected = [reading.lead, ...reading.evidence].map(clean).filter(Boolean);
const paragraphs = reading.hasAppendix ? selected.map(item => {
// The model may put a selected comparison heading and its checked table in
// separate blocks. Keep that table with the heading, without exposing other
// detail paragraphs or replacing the model's semantic selection by position.
if (item.includes('\n|')) return item;
const start = checkedBody.indexOf(item);
if (start < 0 || start !== checkedBody.lastIndexOf(item)) return item;
const following = checkedBody.slice(start + item.length).trimStart();
const table = following.match(/^(\|[^\n]*\|\s*\n\|[\s:|\-]+\|\s*\n(?:\|[^\n]*\|(?:\n|$))+)/)?.[1].trim();
return table && !selected.some(other => other.includes(table)) ? item + '\n\n' + table : item;
}) : [checkedBody];
const body = [...new Set(paragraphs.map(clean).filter(Boolean))].join('\n\n');
const notices = [...new Set(reading.notices.map(clean).filter(Boolean))].filter(notice => !body.includes(notice));
return body + (notices.length ? '\n\n' + notices.join('\n\n') : '');
const selected = [...new Set([reading.lead, ...reading.evidence].map(clean).filter(Boolean))];
const noticeKey = (value: string) => value.trim().replace(/^[-*+]\s+/, '').replace(/^尚未解决[::]\s*/, '')
.replace(/[,,;;]?\s*报告保持部分完成[。.]?$/, '').replace(/[。.]$/, '').trim();
const notices = [...new Map(reading.notices.map(clean).filter(item => !!item && !selected.includes(item))
.map(item => [noticeKey(item), item] as const)).values()];
const noticeKeys = new Set(notices.map(noticeKey));
const markdownBlocks = (value: string): string[] => {
const blocks: string[] = [];
let current: string[] = [], fenced = false;
const flush = () => {
const block = current.join('\n').trim();
if (block) blocks.push(block);
current = [];
};
for (const line of value.split('\n')) {
const fence = /^\s*```/.test(line);
if (fence && !fenced) flush();
if (!fenced && !line.trim()) { flush(); continue; }
if (!fenced && /^\s*#{1,6}\s+/.test(line)) { flush(); blocks.push(line.trim()); continue; }
current.push(line);
if (fence) {
fenced = !fenced;
if (!fenced) flush();
}
}
flush();
return blocks;
};
const seenBodyNotices = new Set<string>();
const dedupedBody = checkedBody.split('\n').filter(line => {
const key = noticeKey(line);
if (!noticeKeys.has(key)) return true;
if (seenBodyNotices.has(key)) return false;
seenBodyNotices.add(key);
return true;
}).join('\n');
const allBodyBlocks = markdownBlocks(dedupedBody);
const isNoticeBlock = (block: string) => block.split('\n').map(line => line.trim()).filter(Boolean)
.every(line => noticeKeys.has(noticeKey(line)));
const bodyBlocks = allBodyBlocks.filter((block, index) => {
if (!/^#{1,6}\s+尚未覆盖的范围\s*$/.test(block)) return true;
return !allBodyBlocks[index + 1] || !isNoticeBlock(allBodyBlocks[index + 1]);
});
const contentKey = (block: string) => block.replace(/^#{1,6}\s+/, '').trim();
const existing = new Set(bodyBlocks.map(contentKey));
const missingBlocks = (values: string[]) => values.flatMap(markdownBlocks)
.filter(block => !existing.has(contentKey(block)) && !noticeKeys.has(noticeKey(block)))
.filter((block, index, all) => all.findIndex(candidate => contentKey(candidate) === contentKey(block)) === index);
const leadBlocks = missingBlocks(selected.slice(0, 1));
const evidenceBlocks = missingBlocks(selected.slice(1));
const bodyNoticeKeys = new Set(dedupedBody.split('\n').map(noticeKey));
const missingNotices = notices.filter(notice => !bodyNoticeKeys.has(noticeKey(notice)));
// Keep the verified answer as the structural source of truth. Summary-selected
// fragments stay at their original headings and list/table parents; only
// content absent from the answer is added around the intact body.
return [...leadBlocks, ...bodyBlocks, ...evidenceBlocks, ...missingNotices].filter(Boolean).join('\n\n');
}
/** Historical or invalid summaries keep all original prose visible, without positional extraction. */
@@ -111,6 +155,14 @@ const stable = (value: unknown): string => {
if (value && typeof value === 'object') return JSON.stringify(Object.fromEntries(Object.entries(object(value)).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, stable(item)])));
return JSON.stringify(value ?? null);
};
const HISTORY_VISUAL_PROVENANCE_KEYS = new Set(['id', 'originTurnId', 'evidenceRefs']);
function stableOrdered(value: unknown): string {
if (Array.isArray(value)) return `[${value.map(stableOrdered).join(',')}]`;
if (value && typeof value === 'object') return `{${Object.entries(object(value)).sort(([a], [b]) => a.localeCompare(b))
.map(([key, item]) => `${JSON.stringify(key)}:${stableOrdered(item)}`).join(',')}}`;
if (typeof value === 'number' && Object.is(value, -0)) return '-0';
return JSON.stringify(value ?? null);
}
const selection = (value: unknown) => Array.isArray(value) ? value : value === undefined || value === null || value === '' ? [] : [value];
const scopeFilters = ['department', 'group', 'product', 'projectGroup', 'productSearch', 'extraFilters', 'exclusions', 'columnFilters', 'columnLabels', 'includeUnassigned', 'category', 'defect'];
const dimensionFilters = new Set(['department', 'group', 'product', 'projectGroup']);
@@ -216,6 +268,86 @@ export function selectPrimaryAnalysisVisuals(model: AnalysisNarrativeModel, turn
&& (!release || visual.scope.releaseId === release) && matches(visual));
}
function resolvePreparedConclusionVisuals(model: AnalysisNarrativeModel, selected: AnalysisVisual[]): AnalysisVisual[] {
const modelVisuals = model.sections.flatMap(section => section.visuals).filter((visual, index, all) => all.findIndex(item => item.id === visual.id) === index);
return combineStageDefectVisuals(selected).flatMap(visual => {
const modelVisual = modelVisuals.find(candidate => candidate.id === visual.id);
return modelVisual && stable(modelVisual) === stable(visual) ? [modelVisual] : [];
});
}
/** Drop only byte-for-byte equivalent history charts; IDs and source citations retain their own lineage. */
function deduplicateHistoryBusinessVisuals(visuals: AnalysisVisual[]): AnalysisVisual[] {
const seen = new Set<string>();
return visuals.filter(visual => {
const businessChart = Object.fromEntries(Object.entries(visual).filter(([key]) => !HISTORY_VISUAL_PROVENANCE_KEYS.has(key)));
const key = stableOrdered(businessChart);
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}
/** History charts are eligible only when the server marks a confirmed import and binds each chart to its source. */
function selectConfirmedHistoryVisuals(model: AnalysisNarrativeModel, source: Row, result: Row, summary: ServerAnalysisReadingSummary): AnalysisVisual[] {
const turnId = String(source.id || source.turnId || ''), proof = object(result.historyEvidence);
const queryRefs = result.queryEvidenceRefs;
const lineages = result.historyVisualSources;
if (!turnId || result.completionMethod !== 'confirmed_history_report' || result.visualSchemaVersion !== 1
|| typeof proof.importId !== 'string' || !proof.importId.trim() || proof.importId.length > 256
|| typeof proof.snapshotHash !== 'string' || !proof.snapshotHash.trim() || proof.snapshotHash.length > 256
|| !Array.isArray(queryRefs) || !queryRefs.every(isAnalysisEvidenceRef)
|| !Array.isArray(lineages) || lineages.length > 100) return [];
const allowedRefs = new Set(summary.evidenceRefs), currentRefs = new Set(queryRefs as string[]);
const byVisualId = new Map<string, Row[]>();
for (const raw of lineages) {
const lineage = object(raw), id = lineage.visualId;
if (typeof id !== 'string' || !id || id.length > 160) continue;
const group = byVisualId.get(id) || [];
group.push(lineage);
byVisualId.set(id, group);
}
const candidates = parseAnalysisVisuals(result.visuals, 1).visuals.filter(visual => {
const matches = byVisualId.get(visual.id);
if (!matches || matches.length !== 1) return false;
const lineage = matches[0];
const required = ['sourceTurnId', 'scope', 'period', 'evidenceRefs'];
if (required.some(key => !Object.hasOwn(lineage, key))
|| Object.keys(lineage).some(key => !['visualId', 'sourceTurnId', 'scope', 'period', 'comparisonPeriod', 'dimension', 'stage', 'metric', 'evidenceRefs'].includes(key))) return false;
if (typeof lineage.sourceTurnId !== 'string' || !lineage.sourceTurnId.trim() || lineage.sourceTurnId.length > 160
|| !lineage.scope || typeof lineage.scope !== 'object' || Array.isArray(lineage.scope)
|| !canonicalReadingPeriod(lineage.period)
|| !Array.isArray(lineage.evidenceRefs) || !lineage.evidenceRefs.every(isAnalysisEvidenceRef)
|| new Set(lineage.evidenceRefs as string[]).size !== lineage.evidenceRefs.length) return false;
if (!visual.chartable || visual.originTurnId !== turnId || !visual.evidenceRefs.length
|| visual.evidenceRefs.some(ref => !allowedRefs.has(ref) || !currentRefs.has(ref))
|| stable(lineage.scope) !== stable(visual.scope)
|| stable(lineage.period) !== stable(visual.period)
|| stable(lineage.comparisonPeriod) !== stable(visual.comparisonPeriod)
|| stable(lineage.dimension) !== stable(visual.dimension)
|| stable(lineage.stage) !== stable(visual.stage)
|| stable(lineage.metric) !== stable(visual.metric)
|| stable(lineage.evidenceRefs) !== stable(visual.evidenceRefs)) return false;
return true;
});
if (!candidates.length) return [];
if (summary.visualIds?.length) {
const selected = summary.visualIds.map(id => candidates.find(visual => visual.id === id)).filter((visual): visual is AnalysisVisual => !!visual);
return deduplicateHistoryBusinessVisuals(resolvePreparedConclusionVisuals(model, selected));
}
const score = (visual: AnalysisVisual) => visual.metric === 'source_defect_delta_weight' ? 50
: visual.metric === 'scrap_delta' && visual.dimension === 'product' ? 40
: visual.type === 'waterfall' ? 60 : visual.dimension === 'department' ? 30 : visual.dimension === 'group' ? 20 : 10;
const selected: AnalysisVisual[] = [];
for (const visual of [...candidates].sort((a, b) => score(b) - score(a))) {
if (selected.some(item => item.dimension === visual.dimension && item.metric === visual.metric && item.stage === visual.stage)) continue;
selected.push(visual);
if (selected.length === 3) break;
}
return deduplicateHistoryBusinessVisuals(resolvePreparedConclusionVisuals(model, selected));
}
/** Show a few already-authorized business charts without requiring users to explicitly ask for a plot. */
export function selectConclusionAnalysisVisuals(model: AnalysisNarrativeModel, turn: unknown): AnalysisVisual[] {
const source = object(turn), result = Object.hasOwn(source, 'result') ? object(source.result) : source;
@@ -223,6 +355,7 @@ export function selectConclusionAnalysisVisuals(model: AnalysisNarrativeModel, t
if (!summary) return [];
const task = readingTask(source, result);
if (task.visualPreference === 'none') return [];
if (result.completionMethod === 'confirmed_history_report') return selectConfirmedHistoryVisuals(model, source, result, summary);
const required = selectPrimaryAnalysisVisuals(model, turn);
if (required.length || task.visualPreference === 'required' || (Array.isArray(task.queryPlan) && task.queryPlan.some(node => object(node).visualPreference === 'required'))) return required;
const refs = new Set(summary.evidenceRefs), filters = object(task.filters);
@@ -239,7 +372,10 @@ export function selectConclusionAnalysisVisuals(model: AnalysisNarrativeModel, t
&& (visual.comparisonPeriod ? samePeriod(visual.comparisonPeriod, task.comparisonPeriod) : task.comparisonRequired !== true)
&& Object.entries(filters).every(([key, value]) => key === 'includeUnassigned' ? (visual.scope[key] === true) === (value === true)
: dimensionFilters.has(key) ? stable(selection(visual.scope[key])) === stable(selection(value)) : stable(visual.scope[key]) === stable(value)));
if (summary.visualIds?.length) return summary.visualIds.map(id => candidates.find(visual => visual.id === id)).filter((visual): visual is AnalysisVisual => !!visual);
if (summary.visualIds?.length) {
const selected = summary.visualIds.map(id => candidates.find(visual => visual.id === id)).filter((visual): visual is AnalysisVisual => !!visual);
return resolvePreparedConclusionVisuals(model, selected);
}
const score = (visual: AnalysisVisual) => visual.metric === 'source_defect_delta_weight' ? 50
: visual.metric === 'scrap_delta' && visual.dimension === 'product' ? 40
: visual.type === 'waterfall' ? 60 : visual.dimension === 'department' ? 30 : visual.dimension === 'group' ? 20 : 10;
@@ -249,7 +385,7 @@ export function selectConclusionAnalysisVisuals(model: AnalysisNarrativeModel, t
selected.push(visual);
if (selected.length === 3) break;
}
return selected;
return resolvePreparedConclusionVisuals(model, selected);
}
/** Chat, HTML and PNG report views share this exact summary and evidence model. */
+20 -3
View File
@@ -54,9 +54,26 @@ function visualBinding(turn: Data, result: Data): Data | undefined {
* or reuse the mutable current session context for an older turn. */
export function analysisScopeText(turn: Data): string {
const result = record(turn.result), plan = record(turn.plan || result.plan);
const contexts = [record(plan.context), record(plan.frozenContext), record(result.context), record(turn.context)];
const durable = Object.keys(result).length ? result : turn;
const historyReport = durable.completionMethod === 'confirmed_history_report';
let historyContext: Data | undefined;
if (historyReport) {
const sources = new Set((Array.isArray(durable.historySources) ? durable.historySources : [])
.map(record).filter(source => source.available === true).map(source => source.turnId));
const frames = (Array.isArray(durable.historySections) ? durable.historySections : []).map(record)
.filter(section => sources.has(section.sourceTurnId) && analysisPeriodText(section.period))
.map(section => ({ ...record(section.filters), period: section.period,
...(section.comparisonPeriod ? { comparisonPeriod: section.comparisonPeriod } : {}),
...(section.stage ? { stage: section.stage } : {}), view: 'overall' }));
// A multi-scope report describes each source beside its own table. The
// chat's current query context must not label the whole report as one month
// or one organization.
if (!frames.length || new Set(frames.map(canonical)).size !== 1) return '';
historyContext = frames[0];
}
const contexts = historyReport ? [historyContext!] : [record(plan.context), record(plan.frozenContext), record(result.context), record(turn.context)];
const context = contexts.find(value => BINDING_KEYS.some(key => meaningful(value[key])));
const visual = visualBinding(turn, result);
const visual = historyReport ? undefined : visualBinding(turn, result);
const visualContext = visual ? { ...visual, ...record(visual.period) } : undefined;
const compatible = context && visualContext && BINDING_KEYS.filter(key => meaningful(context[key]))
.every(key => key === 'stage' && ['all', 'combined'].includes(String(context.stage)) && !meaningful(visualContext.stage)
@@ -64,7 +81,7 @@ export function analysisScopeText(turn: Data): string {
const binding = compatible ? { ...context, ...visual } : context || visual;
if (!binding) return '';
if (meaningful(binding.exclusions) && !isValidAnalysisExclusions(binding.exclusions)) return '';
const semantic = record(plan.semantic);
const semantic = historyReport ? {} : record(plan.semantic);
const period = analysisPeriodText(binding.period || binding);
// Legacy semantic plans store a comparison query in priorContext only when
// compare is explicitly true; an unmarked previous context is not evidence.
+15 -5
View File
@@ -83,23 +83,31 @@ const SCRAP_RATE_REQUIRED_FIELDS: Record<string, { stage: AnalysisVisualStage; f
black_scrap_rate: { stage: 'black', fields: ['black_scrap_weight', 'black_total_weight'] },
bright_scrap_rate: { stage: 'bright', fields: ['bright_scrap_weight', 'bright_total_weight'] },
};
const OFFICIAL_RATES_ALLOWING_OVER_ONE = new Set([
'black_rate', 'composite_rate', 'composite_rate_without_headquarters_scrap',
]);
const DEFAULT_COLORS = ['#607ae1', '#008f7d', '#d58c35', '#8b68c5'];
function isScrapRateMetric(metric: string): boolean {
return Object.hasOwn(SCRAP_RATE_REQUIRED_FIELDS, metric);
}
function allowsAboveOneRatio(metric: string): boolean {
return isScrapRateMetric(metric) || OFFICIAL_RATES_ALLOWING_OVER_ONE.has(metric);
}
function ratioAxisMax(visual: AnalysisVisual): number | undefined {
if (visual.unit !== 'ratio') return undefined;
if (!isScrapRateMetric(visual.metric)) return 100;
if (!allowsAboveOneRatio(visual.metric)) return 100;
const highest = Math.max(0, ...visual.series.flatMap(series => series.values.filter((value): value is number => value !== null && Number.isFinite(value))));
if (highest <= 1) {
if (isScrapRateMetric(visual.metric) && highest <= 1) {
if (highest === 0) return 1;
const targetPercent = highest * 100 * 1.15;
const magnitude = 10 ** Math.floor(Math.log10(targetPercent));
const factor = [1, 2, 5, 10].find(value => value * magnitude >= targetPercent) || 10;
return Math.min(100, factor * magnitude);
}
if (highest <= 1) return 100;
const highestPercent = highest * 100;
if (!Number.isFinite(highestPercent)) return undefined;
return Math.ceil((highestPercent + Math.max(10, highestPercent * 0.08)) / 10) * 10;
@@ -316,7 +324,7 @@ function parseVisual(value: unknown, index: number, issues: string[]): AnalysisV
invalidValueCells.push(`${seriesIndex}:${valueIndex}`);
return null;
}
if (unit === 'ratio' && (item < 0 || (!isScrapRateMetric(metric || '') && item > 1))) invalidValueCells.push(`${seriesIndex}:${valueIndex}`);
if (unit === 'ratio' && (item < 0 || (!allowsAboveOneRatio(metric || '') && item > 1))) invalidValueCells.push(`${seriesIndex}:${valueIndex}`);
return item;
});
series.push({ key, label, values });
@@ -403,8 +411,10 @@ function visualSemanticIssue(visual: AnalysisVisual): string | undefined {
if (visual.type === 'pareto' && visual.coverage.shareBasis === 'all_scope_weight') {
const values = visual.series[0]?.values || [];
const total = visual.coverage.denominator;
if (visual.unit !== 'kg' || !/^(?:black|bright)_(?:total|scrap)_weight$/.test(visual.metric)
|| !visual.stage || !visual.metric.startsWith(`${visual.stage}_`) || visual.comparisonPeriod
const combined = visual.metric === 'current_scrap_weight' && !visual.stage
&& ['black_scrap_weight', 'bright_scrap_weight'].every(field => visual.requiredFields.includes(field));
if (visual.unit !== 'kg' || !combined && !/^(?:black|bright)_(?:total|scrap)_weight$/.test(visual.metric)
|| !combined && (!visual.stage || !visual.metric.startsWith(`${visual.stage}_`)) || visual.comparisonPeriod
|| !['product','department','group'].includes(visual.dimension || '')
|| visual.categories.length < 1 || visual.categories.length > 10 || visual.series.length !== 1
|| visual.coverage.returnedRows !== visual.categories.length || typeof total !== 'number' || !(total > 0)
+10 -7
View File
@@ -123,7 +123,7 @@ export async function refreshCsrf(): Promise<string> {
return csrfToken;
}
async function mutate<T>(path: string, body?: unknown, method = 'POST', timeoutMs?: number): Promise<T> {
async function mutate<T>(path: string, body?: unknown, method = 'POST', timeoutMs?: number, silent = false): Promise<T> {
const token = csrfToken ?? await refreshCsrf();
const headers = new Headers({ 'X-XSRF-TOKEN': token });
const result = await request<T>(path, {
@@ -131,7 +131,7 @@ async function mutate<T>(path: string, body?: unknown, method = 'POST', timeoutM
headers,
...(body === undefined ? {} : { body: JSON.stringify(body) }),
}, timeoutMs);
if (!/^\/api\/(?:analysis|auth)(?:\/|$)/.test(path)) window.dispatchEvent(new Event(WORKSPACE_INVALIDATED));
if (!silent && !/^\/api\/(?:analysis|auth)(?:\/|$)/.test(path)) window.dispatchEvent(new Event(WORKSPACE_INVALIDATED));
return result;
}
@@ -243,17 +243,20 @@ export const api = {
return request<Collection>(`/api/import-runs/${encodeURIComponent(id)}/issues?page=${page}&pageSize=${pageSize}`);
},
classificationMetadata() { return request<{ defaultRules: unknown[] }>('/api/governance/mapping-issues/classification-metadata'); },
classificationSources(body: {stage:string;conditions:{field:string;operator:string;value:string}[];page:number;pageSize:number;releaseId?:string}, signal?:AbortSignal) {
return queryPost<{rows:Record<string,unknown>[];total:number;page:number;pageSize:number;releaseId?:string}>('/api/governance/mapping-issues/classification-sources',body,signal);
},
previewClassification(body: {kind?:'group'|'projectGroup';stage:string;target:string;conditions:{field:string;operator:string;value:string}[]}) {
return queryPost<Record<string,unknown>>('/api/governance/mapping-issues/classification-preview',body);
},
unclassifiedProjects(params: {page:number;pageSize:number;customerCode?:string;businessGroup?:string;department?:string}) {
return request<Collection & { filterOptions?: {customerCodes:string[];businessGroups:string[];departments:string[]} }>(`/api/governance/mapping-issues/unclassified-projects?${toQuery(params)}`);
return request<Collection & { releaseId?:string; filterOptions?: {customerCodes:string[];businessGroups:string[];departments:string[]} }>(`/api/governance/mapping-issues/unclassified-projects?${toQuery(params)}`);
},
unclassifiedSources(page = 1, pageSize = 50) {
return request<Collection>(`/api/governance/mapping-issues/unclassified?${toQuery({ page, pageSize })}`);
return request<Collection & {releaseId?:string}>(`/api/governance/mapping-issues/unclassified?${toQuery({ page, pageSize })}`);
},
mappingIssues(params: { mappingType?: string; importRunId?: string; status?: string; page?: number; pageSize?: number; customerCode?: string; businessGroup?: string; department?: string } = {}) {
return request<Collection & { filterOptions?: { customerCodes: string[]; businessGroups: string[]; departments: string[] } }>(`/api/governance/mapping-issues?${toQuery({ page: 1, pageSize: 50, ...params })}`);
return request<Collection & { releaseId?:string; filterOptions?: { customerCodes: string[]; businessGroups: string[]; departments: string[] } }>(`/api/governance/mapping-issues?${toQuery({ page: 1, pageSize: 50, ...params })}`);
},
mappingIssue(id: string) {
return request<Record<string, unknown>>(`/api/governance/mapping-issues/${encodeURIComponent(id)}`);
@@ -336,7 +339,7 @@ export const api = {
dataWorkflowStatus() {
return request<DataWorkflowStatus>('/api/data-workflow/status');
},
applyDataWorkflow(body: { kind: 'mapping' | 'rule'; name: string; definition: Record<string, unknown>; description?: string; expectedCurrentReleaseId: string | null }) {
applyDataWorkflow(body: { kind: 'mapping' | 'rule'; name: string; definition: Record<string, unknown>; description?: string; expectedCurrentReleaseId: string | null }, silent = false) {
const matchRules = body.definition.matchRules;
const definition = Array.isArray(matchRules) ? {
...body.definition,
@@ -354,7 +357,7 @@ export const api = {
};
}),
} : body.definition;
return mutate<DataWorkflowOperation>('/api/data-workflow/apply', { ...body, definition });
return mutate<DataWorkflowOperation>('/api/data-workflow/apply', { ...body, definition }, 'POST', undefined, silent);
},
recalculateDataWorkflow() {
return mutate<DataWorkflowOperation>('/api/data-workflow/recalculate', {});
+94
View File
@@ -0,0 +1,94 @@
import { editClassification, type ClassificationSelection, type ClassificationRuleOptions } from './classificationMaintenance.ts';
import type { DataWorkflowOperation, DataWorkflowStatus } from './NoCodeDataTypes.ts';
export type ClassificationCommand = { selection: ClassificationSelection; target: string; options: ClassificationRuleOptions };
export type ClassificationJob = ClassificationCommand & { id: string; status: 'queued'|'submitting'|'running'|'paused'|'failed'|'completed'; operationId?: string; error?: string; releaseId?: string };
type Dependencies = {
status: () => Promise<DataWorkflowStatus>;
apply: (definition: Record<string,unknown>, releaseId: string|null) => Promise<DataWorkflowOperation>;
operation: (id: string) => Promise<DataWorkflowOperation>;
persist: (jobs: ClassificationJob[]) => void;
completed: () => void;
wait: () => Promise<void>;
};
/** One operation at a time; rebase each command on the newly published mapping. */
export class ClassificationQueue {
private jobs: ClassificationJob[];
private listeners = new Set<()=>void>();
private processing = false;
private stopped = false;
private deps: Dependencies;
constructor(deps: Dependencies, saved: ClassificationJob[] = []) {
this.deps=deps;
this.jobs = saved.map(job => job.status === 'submitting' ? {...job,status:'failed',error:'提交结果尚未确认,请刷新列表后重试'} : job);
}
snapshot = () => this.jobs;
subscribe = (listener: ()=>void) => { this.listeners.add(listener); return () => {this.listeners.delete(listener);}; };
private emit() { this.deps.persist(this.jobs); this.listeners.forEach(listener=>listener()); }
private patch(id: string, value: Partial<ClassificationJob>) { this.jobs=this.jobs.map(job=>job.id===id?{...job,...value}:job);this.emit(); }
enqueue(command: ClassificationCommand, base: Record<string,unknown>, defaults: unknown[]) {
if(this.stopped)throw new Error('请重新打开对应关系页面');
// Validate against the current editor plus queued commands before hiding anything.
let definition=base;
for(const job of this.jobs.filter(job=>!['failed','completed'].includes(job.status))) definition=editClassification(definition,job.selection,job.target,defaults,job.options);
editClassification(definition,command.selection,command.target,defaults,command.options);
const job:ClassificationJob={...structuredClone(command),id:crypto.randomUUID(),status:'queued'};
this.jobs=[...this.jobs,job];this.emit();void this.run();return job.id;
}
retry(id: string) {
const job=this.jobs.find(job=>job.id===id);if(!job||!['failed','paused'].includes(job.status))return;
const resume=job.status==='paused'&&!!job.operationId;
this.patch(id,{status:resume?'running':'queued',operationId:resume?job.operationId:undefined,error:undefined});void this.run();
}
acknowledge(ids: string[]) { this.jobs=this.jobs.filter(job=>job.status!=='completed'||!ids.includes(job.id));this.emit(); }
dismiss(id: string) { this.jobs=this.jobs.filter(job=>job.id!==id||job.status!=='failed');this.emit(); }
stop() { this.stopped=true; }
resume() { this.stopped=false;void this.run(); }
async run() {
if(this.processing||this.stopped)return;this.processing=true;
try {
while(!this.stopped) {
// A failed progress read pauses the queue to avoid duplicate publication.
if(this.jobs.some(job=>job.status==='paused'))return;
const job=this.jobs.find(job=>['queued','running'].includes(job.status));if(!job)return;
try {
let operationId=job.operationId;
if(!operationId) {
const status=await this.deps.status();if(this.stopped)return;
const base=status.activeMapping?.definition;if(!base)throw new Error('当前配置读取失败,请刷新后重试');
const definition=editClassification(base,job.selection,job.target,status.defaultRules??[],job.options);
this.patch(job.id,{status:'submitting'});
const operation=await this.deps.apply(definition,status.currentReleaseId);
if(!operation.operationId)throw new Error('未收到更新任务编号,请刷新确认后重试');
operationId=operation.operationId;this.patch(job.id,{status:'running',operationId});
}
while(!this.stopped) {
const operation=await this.deps.operation(operationId);
if(operation.status==='FAILED') { this.patch(job.id,{status:'failed',error:(operation.errors??[]).map(item=>item.message).filter(Boolean).join(';')||'分类更新失败'});this.deps.completed();break; }
if(operation.status==='COMPLETED') { this.patch(job.id,{status:'completed',releaseId:String(operation.currentReleaseId??operation.releaseId??'')});this.deps.completed();break; }
await this.deps.wait();
}
} catch(error) {
const current=this.jobs.find(item=>item.id===job.id);
this.patch(job.id,{status:current?.operationId?'paused':'failed',error:error instanceof Error?error.message:'分类更新失败'});
if(current?.operationId)return;
}
}
} finally {this.processing=false;}
}
}
const values: Record<string,string> = {'@department':'department','@product':'product','PDT代码':'pdtCode','销售片区':'salesRegion','客户代码':'customerCode','@group':'businessGroup'};
export function classificationHides(row: Record<string,unknown>, kind: ClassificationSelection['kind'], jobs: ClassificationJob[]) {
return jobs.some(job=>{
if(job.status==='failed'||job.selection.kind!==kind)return false;
if(kind==='projectGroup')return row.customerCode===job.selection.row.customerCode&&row.businessGroup===job.selection.row.businessGroup;
const stage=job.options.stage??String(job.selection.row.stage);
if(stage!=='all'&&stage!==row.stage)return false;
return (job.options.conditions??[]).every(condition=>{
const value=String(row[values[condition.field]]??'');
return condition.operator==='IS_BLANK'?value.trim()==='':value===condition.value;
});
});
}
+1 -1
View File
@@ -606,7 +606,7 @@ body { background: var(--background); }
.query-period-field .ant-select { width: 90px; min-width: 90px; }
.query-period-month .ant-select { width: 80px; min-width: 80px; }
.query-unassigned { margin-left: auto; white-space: nowrap; }
.query-toolbar-tail { flex: 0 0 auto; margin-left: 0; }
.query-toolbar-tail { flex: 0 0 auto; margin-left: auto; }
.query-more-toggle { display: flex; flex: 0 0 auto; align-items: center; gap: 3px; min-height: 28px; }
.query-more-toggle > .ant-btn { flex-shrink: 0; }
.query-filter-summary { color: var(--muted-ink, #657087); font-size: var(--font-control); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+24
View File
@@ -0,0 +1,24 @@
import { useEffect, useMemo, useSyncExternalStore } from 'react';
import { api } from './api';
import { ClassificationQueue, type ClassificationJob } from './classificationQueue';
import { configurationDateTime } from './configurationName';
import { WORKSPACE_INVALIDATED } from './pageCache';
export function useClassificationQueue(userId: string) {
const queue=useMemo(()=>{
const key=`quality-classification-queue:${userId}`;
let saved:ClassificationJob[]=[];
try {const value=JSON.parse(localStorage.getItem(key)??'[]');if(Array.isArray(value))saved=value;} catch { /* empty queue */ }
return new ClassificationQueue({
status:async()=>{const status=await api.dataWorkflowStatus();return {...status,defaultRules:status.defaultRules??(await api.classificationMetadata()).defaultRules as unknown[]};},
apply:(definition,releaseId)=>api.applyDataWorkflow({kind:'mapping',name:configurationDateTime(new Date()),definition,expectedCurrentReleaseId:releaseId},true),
operation:id=>api.dataWorkflowOperation(id),
persist:jobs=>{try{localStorage.setItem(key,JSON.stringify(jobs));}catch{/* current session still works */}},
completed:()=>window.dispatchEvent(new Event(WORKSPACE_INVALIDATED)),
wait:()=>new Promise(resolve=>window.setTimeout(resolve,1000)),
},saved);
},[userId]);
const jobs=useSyncExternalStore(queue.subscribe,queue.snapshot);
useEffect(()=>{queue.resume();return()=>queue.stop();},[queue]);
return {queue,jobs};
}
+35
View File
@@ -0,0 +1,35 @@
import { useContext, useEffect, useRef, useState } from 'react';
import { MappingEditorContext } from './MappingEditorContext';
import { classificationHides } from './classificationQueue';
import { api, collectionItems } from './api';
import { useMaintenanceRefresh } from './pageCache';
import type { ClassificationSelection } from './classificationMaintenance';
/** Small grouped inventory is cached locally; pagination never repeats a server scan. */
export function useUnclassifiedInventory(kind: ClassificationSelection['kind'], onUnauthorized:(error:unknown)=>boolean) {
const context=useContext(MappingEditorContext);
const contextRef=useRef(context);contextRef.current=context;
const [all,setAll]=useState<Record<string,unknown>[]>([]);
const [loaded,setLoaded]=useState(false);
const [loading,setLoading]=useState(true);
const [error,setError]=useState('');const revision=useRef(0);
const load=async()=>{
const run=++revision.current;
const completed=(contextRef.current?.classificationJobs??[]).filter(job=>job.status==='completed').map(job=>job.id);
try {
const fetchPage=(page:number)=>kind==='group'?api.unclassifiedSources(page,100):api.unclassifiedProjects({page,pageSize:100});
const first=await fetchPage(1);const result=[...collectionItems(first)];const total=Number(first.total??result.length);
// A source release can change during paging. Never replace the list with mixed versions.
for(let page=2;result.length<total;page++) {
const next=await fetchPage(page);if(next.releaseId!==first.releaseId) { if(run===revision.current)void load();return; }
const rows=collectionItems(next);if(!rows.length)break;result.push(...rows);
}
if(run!==revision.current)return;
setAll(result);setLoaded(true);setError('');contextRef.current?.acknowledgeClassifications?.(completed);
}catch(value){if(run===revision.current&&!onUnauthorized(value))setError(value instanceof Error?value.message:'待处理数据读取失败');}
finally{if(run===revision.current)setLoading(false);}
};
useEffect(()=>{void load();return()=>{revision.current++;};},[kind]);
useMaintenanceRefresh(()=>{void load();});
return {all,items:all.filter(row=>!classificationHides(row,kind,context?.classificationJobs??[])),loading:loading&&!loaded,error,refresh:load};
}
+2
View File
@@ -147,3 +147,5 @@ body, .app-shell, .main-column { color: var(--ink); background: var(--background
.classification-rule-modal .ant-modal-body, .configuration-import-modal .ant-modal-body { max-height:calc(100dvh - 210px); overflow:auto; padding-right:3px; }
@media(max-width:680px) { .classification-rule-fields { grid-template-columns:1fr; } .classification-condition-row { grid-template-columns:80px 1fr; } .classification-condition-row > .ant-input { grid-column:1/-1; } }
@media (max-width: 960px) { .config-type-filter { flex-wrap: wrap; } .structured-config-actions { margin-left: auto; } }
.classification-queue-status { display:grid; gap:8px; margin:0 0 12px; }
.classification-queue-status > span { display:flex; align-items:center; gap:8px; color:var(--text-secondary); font-size:13px; }