修复:项目组分类仅补齐未分类并在完成后刷新列表
This commit is contained in:
@@ -21,7 +21,7 @@ export function ClassificationRuleEditor({ children, onUnauthorized }: {
|
||||
const [busy,setBusy]=useState(false);const [error,setError]=useState('');const revision=useRef(0);
|
||||
const resetPreview=()=>{revision.current++;setPreview(null);setError('');};
|
||||
const open=(next:ClassificationSelection)=>{
|
||||
setSelection(next);setConditions(classificationConditions(next.row));setStage('all');setTarget(next.kind==='projectGroup'?String((context?.definition.projectGroupLookup as Record<string,unknown>|undefined)?.[String(next.row.sourceKey)]??''):'');setName('');resetPreview();
|
||||
setSelection(next);setConditions(classificationConditions(next.row));setStage('all');setTarget('');setName('');resetPreview();
|
||||
};
|
||||
const validate=()=>{
|
||||
if(!context?.ready||!selection)throw new Error('请等待当前配置读取完成');
|
||||
@@ -31,17 +31,17 @@ export function ClassificationRuleEditor({ children, onUnauthorized }: {
|
||||
const generation=++revision.current;setError('');setPreview(null);
|
||||
try{
|
||||
validate();setBusy(true);
|
||||
const result=await api.previewClassification({stage,target:target.trim(),conditions});
|
||||
const result=await api.previewClassification({kind:project?'projectGroup':'group',stage,target:target.trim(),conditions:project?[{field:'客户代码',operator:'EQUALS',value:String(selection?.row.customerCode)},{field:'@group',operator:'EQUALS',value:String(selection?.row.businessGroup)}]:conditions});
|
||||
if(generation===revision.current)setPreview(result);
|
||||
}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(!project&&!preview)throw new Error('请先预览当前条件的影响范围');const definition=validate();context!.update(definition);setSelection(null);message.success(project?'对应关系已加入当前编辑,保存并更新报表后生效':'规则已加入条件匹配,保存并更新报表后统一生效');}
|
||||
try{if(!preview)throw new Error('请先预览当前条件的影响范围');const definition=validate();context!.update(definition);setSelection(null);message.success('规则已加入条件匹配,保存并更新报表后统一生效');}
|
||||
catch(value){setError(value instanceof Error?value.message:'规则保存失败');}
|
||||
};
|
||||
return <>{children(open)}<Modal className="management-modal classification-rule-modal" width={880} open={!!selection}
|
||||
title={project?'编辑项目组分类':'编辑业务分组分类'} okText={project?'保存到基础对应':preview?'保存到条件匹配':'请先预览影响'} okButtonProps={{disabled:busy||(!project&&!preview)||!context?.ready}}
|
||||
title={project?'编辑项目组分类':'编辑业务分组分类'} okText={preview?'保存到条件匹配':'请先预览影响'} okButtonProps={{disabled:busy||!preview||!context?.ready}}
|
||||
onOk={save} onCancel={()=>{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>
|
||||
@@ -59,11 +59,11 @@ export function ClassificationRuleEditor({ children, onUnauthorized }: {
|
||||
</div>)}</div></>}
|
||||
<label className="classification-target">{project?'项目组':'业务分组'}<AutoComplete aria-label={project?'目标项目组':'目标业务分组'} value={target} maxLength={160} options={(project?context?.projectGroups??[]:context?.groups??[]).map(value=>({value}))}
|
||||
filterOption={(input,option)=>String(option?.value).includes(input)} placeholder={project?'选择项目组':'选择业务分组'} onChange={value=>{setTarget(value);resetPreview();setBusy(false);}}/></label>
|
||||
{!project&&<div className="classification-preview-action"><span>只处理未分类记录,覆盖全部月份和来源文件;已有分类保持不动。</span><Button loading={busy} onClick={()=>void inspect()}>预览影响</Button></div>}
|
||||
<div className="classification-preview-action"><span>只处理未分类记录,覆盖全部月份和来源文件;已有分类保持不动。</span><Button loading={busy} onClick={()=>void inspect()}>预览影响</Button></div>
|
||||
{error&&<Alert type="error" showIcon message={error}/>}
|
||||
{preview&&<div className="classification-impact"><Space wrap><Tag color="blue">命中 {Number(preview.matchedRows).toLocaleString()} 行</Tag><Tag>总重量 {Number(preview.totalWeight).toLocaleString()} kg</Tag><Tag color={Number(preview.changedRows)>0?'orange':'default'}>当前归属不同 {Number(preview.changedRows).toLocaleString()} 行</Tag></Space>
|
||||
<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:'当前业务分组',dataIndex:'currentGroup',render:value=>value||'未分类'},{title:'行数',dataIndex:'rowCount',align:'right'},{title:'目标业务分组',render:()=>target}]}/>
|
||||
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></>;
|
||||
}
|
||||
|
||||
@@ -742,7 +742,6 @@ function MappingIssueResolutionPanel({ onUnauthorized, onEdit }: { onUnauthorize
|
||||
const [items, setItems] = useState<Record<string, unknown>[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [page, setPage] = useState(1);
|
||||
const [status, setStatus] = useState('OPEN');
|
||||
const [customerCode, setCustomerCode] = useState<string>();
|
||||
const [businessGroup, setBusinessGroup] = useState<string>();
|
||||
const [department, setDepartment] = useState<string>();
|
||||
@@ -752,15 +751,15 @@ function MappingIssueResolutionPanel({ onUnauthorized, onEdit }: { onUnauthorize
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const { refreshKey } = usePageCache();
|
||||
const pages = useRef(new Map<string, ReturnType<typeof api.mappingIssues>>());
|
||||
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, status, customerCode, businessGroup, department]);
|
||||
const key = JSON.stringify([refreshKey, page, customerCode, businessGroup, department]);
|
||||
if (force) pages.current.clear();
|
||||
setLoading(true);
|
||||
let request: ReturnType<typeof api.mappingIssues> | undefined;
|
||||
let request: ReturnType<typeof api.unclassifiedProjects> | undefined;
|
||||
try {
|
||||
request = pages.current.get(key) ?? api.mappingIssues({ status: status || undefined, page, pageSize: TABLE_PAGE_SIZE, customerCode, businessGroup, department, mappingType: 'PROJECT_GROUP' });
|
||||
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;
|
||||
@@ -771,7 +770,7 @@ function MappingIssueResolutionPanel({ onUnauthorized, onEdit }: { onUnauthorize
|
||||
} 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, status, customerCode, businessGroup, department]);
|
||||
useEffect(() => { void load(); }, [page, customerCode, businessGroup, department]);
|
||||
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 },
|
||||
@@ -780,19 +779,19 @@ function MappingIssueResolutionPanel({ onUnauthorized, onEdit }: { onUnauthorize
|
||||
{ title: '涉及行数', dataIndex: 'rowCount', key: 'rowCount', align: 'right', width: 110 },
|
||||
{ title: '涉及总重量', dataIndex: 'totalWeight', key: 'totalWeight', align: 'right', width: 130 },
|
||||
{ title: '问题期间', key: 'periods', width: 170, render: (_, row) => { const details = row.details && typeof row.details === 'object' ? row.details as Record<string, unknown> : {}; return Array.isArray(details.periods) ? (details.periods as unknown[]).map(toText).join('、') : '—'; } },
|
||||
{ title: '状态', dataIndex: 'status', key: 'status', width: 120, render: value => <Tag color={value === 'OPEN' ? 'orange' : value === 'REVALIDATED' ? 'green' : 'blue'}>{toText(value)}</Tag> },
|
||||
{ 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"><Select aria-label="映射问题状态" value={status} options={[{ label: '待处理', value: 'OPEN' }, { label: '已裁决', value: 'DECIDED' }, { label: '已退回', value: 'RETURNED' }, { label: '已重验', value: 'REVALIDATED' }, { label: '全部状态', value: '' }]} onChange={value => { setStatus(value); setPage(1); }} /><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 load(true)}>刷新</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={(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>;
|
||||
}
|
||||
|
||||
@@ -919,7 +918,7 @@ function TaskTable({ items, importOnly, user, onUnauthorized, onRefresh }: { ite
|
||||
{ title: '处理阶段', dataIndex: 'stage', key: 'stage', width: 150 },
|
||||
{ title: importOnly ? '进度' : '进度', dataIndex: 'progress', key: 'progress', width: 145, align: 'right', render: value => importOnly ? `${toText(value)}%` : toText(value) },
|
||||
{ title: '已处理 / 总数', key: 'processed', width: 140, align: 'right', render: (_, row) => `${toText(row.processed)} / ${toText(row.total)}` },
|
||||
{ title: '错误码', dataIndex: 'errorCode', key: 'errorCode', width: 150, render: value => value ? <Tag color="red">{toText(value)}</Tag> : '—' },
|
||||
{ title: '错误码', dataIndex: 'errorCode', key: 'errorCode', width: 150, render: value => value ? <Tag color="red">{value==='OPEN'?'待处理':toText(value)}</Tag> : '—' },
|
||||
{ title: '错误信息', dataIndex: 'errorMessage', key: 'errorMessage', width: 300, ellipsis: true, render: value => value ? <span className="task-error">{toText(value)}</span> : '—' },
|
||||
{ title: '创建时间', dataIndex: 'createdAt', key: 'createdAt', width: 205 },
|
||||
{ title: '操作', key: 'detail', fixed: 'right', width: importOnly ? 240 : 150, align: 'center', render: (_, row) => <span className="task-actions">
|
||||
|
||||
@@ -268,7 +268,7 @@ export function MatchRulesDefinitionEditor({ value, onChange, metadata, readOnly
|
||||
{ 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> },
|
||||
]} />
|
||||
<Form.Item label="处理范围"><Switch checked={editing.onlyUnclassified===true} disabled={editing.target!=='group' || rules.some(rule=>rule.id===editing.id && rule.onlyUnclassified===true)} checkedChildren="仅未分类" unCheckedChildren="全部匹配行" onChange={onlyUnclassified=>setEditing({...editing,onlyUnclassified})}/></Form.Item><div className="structured-config-form-grid" style={{ marginTop: 16 }}><Form.Item label="目标类型"><Select value={editing.target} options={targets} disabled={editing.onlyUnclassified===true} 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>
|
||||
<Form.Item label="处理范围"><Switch checked={editing.onlyUnclassified===true} disabled={!['group','projectGroup'].includes(editing.target) || rules.some(rule=>rule.id===editing.id && rule.onlyUnclassified===true)} checkedChildren="仅未分类" unCheckedChildren="全部匹配行" onChange={onlyUnclassified=>setEditing({...editing,onlyUnclassified})}/></Form.Item><div className="structured-config-form-grid" style={{ marginTop: 16 }}><Form.Item label="目标类型"><Select value={editing.target} options={targets} disabled={editing.onlyUnclassified===true} 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>
|
||||
|
||||
+4
-1
@@ -243,9 +243,12 @@ 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'); },
|
||||
previewClassification(body: {stage:string;target:string;conditions:{field:string;operator:string;value:string}[]}) {
|
||||
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)}`);
|
||||
},
|
||||
unclassifiedSources(page = 1, pageSize = 50) {
|
||||
return request<Collection>(`/api/governance/mapping-issues/unclassified?${toQuery({ page, pageSize })}`);
|
||||
},
|
||||
|
||||
@@ -32,11 +32,15 @@ export function editClassification(base: Definition, selection: ClassificationSe
|
||||
if (Array.isArray(catalog) && !catalog.some(item => item.name === target && item.enabled === true)) throw new Error('目标分类未登记或已停用,请先在基础数据中维护');
|
||||
if (kind === 'projectGroup') {
|
||||
if (row.mappingType !== 'PROJECT_GROUP' || !text(row.customerCode) || !text(row.businessGroup) || row.sourceKey !== `${row.customerCode}|${row.businessGroup}`) throw new Error('客户代码或业务分组缺失');
|
||||
result.projectGroupLookup = { ...(result.projectGroupLookup as Definition ?? {}), [text(row.sourceKey)]: target };
|
||||
const disabled = result.disabledMappings as Definition | undefined;
|
||||
if (disabled && Array.isArray(disabled.projectGroupLookup)) disabled.projectGroupLookup = disabled.projectGroupLookup.filter(key => key !== row.sourceKey);
|
||||
// Remove an interval override only when it would mask this explicit edit: require dedicated maintenance instead.
|
||||
if (Array.isArray(result.effectiveRanges) && result.effectiveRanges.some((raw: unknown) => { const range = raw as Definition; return range.mappingType === 'PROJECT_GROUP' && range.sourceKey === row.sourceKey; })) throw new Error('此分类有期间规则,请在对应关系草稿中修改有效期后再保存');
|
||||
const conditions:ClassificationCondition[]=[{field:'客户代码',operator:'EQUALS',value:text(row.customerCode)},{field:'@group',operator:'EQUALS',value:text(row.businessGroup)}];
|
||||
const rules=Array.isArray(result.matchRules)?result.matchRules as Definition[]:structuredClone(defaultRules) as Definition[];
|
||||
const signature=classificationSignature('all',conditions);
|
||||
const same=rules.find(rule=>rule.target==='projectGroup'&&classificationSignature(String(rule.stage),rule.conditions as ClassificationCondition[])===signature);
|
||||
if(same&&same.value!==target&&same.enabled!==false)throw new Error(`相同条件已指向“${String(same.value)}”,请在条件匹配中编辑已有规则`);
|
||||
const id=same?.id?String(same.id):'project-'+classificationRuleId(row,{stage:'all',conditions});
|
||||
if(rules.some(rule=>rule.id===id&&(rule.target!=='projectGroup'||classificationSignature(String(rule.stage),rule.conditions as ClassificationCondition[])!==signature)))throw new Error('规则标识冲突,请在条件匹配中维护');
|
||||
result.matchRules=[{id,name:`${target}项目组分类规则`,enabled:true,onlyUnclassified:true,priority:-9890,stage:'all',conditions,target:'projectGroup',value:target},...rules.filter(rule=>rule.id!==id)];
|
||||
if((result.matchRules as unknown[]).length>100)throw new Error('条件规则已满100条,请先整理规则');
|
||||
} else {
|
||||
if (!['black','bright'].includes(text(row.stage))) throw new Error('来源阶段无效');
|
||||
const conditions = options.conditions ?? classificationConditions(row);
|
||||
|
||||
@@ -105,7 +105,7 @@ export function importConfigurationTables(base:Definition,tables:ConfigurationTa
|
||||
if(!/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(id)||!name||!value||name.length>200||value.length>200)throw new Error(`条件匹配第${n+2}行规则编号、名称或目标分类无效`);
|
||||
if(!STAGES[stage]||!TARGETS[target]||!OPERATORS[operator]||!field||(field.startsWith('@')&&!Object.hasOwn(FIELDS,field))||field.length>200||(!['IS_BLANK','IS_NOT_BLANK'].includes(operator)&&!conditionValue)||conditionValue.length>200)throw new Error(`条件匹配第${n+2}行条件无效`);
|
||||
if(['IS_BLANK','IS_NOT_BLANK'].includes(operator)&&conditionValue)throw new Error(`条件匹配第${n+2}行空值判断不应填写判断值`);
|
||||
const prior=previous.find(rule=>rule.id===id);const scope=enabled(unclassifiedOnly,false);const metadata={id,name,priority:number(priority,'优先级',-10000,10000),stage,target,value,enabled:enabled(status),...(scope||Object.hasOwn(prior??{},'onlyUnclassified')?{onlyUnclassified:scope}:{})};if(scope&&target!=='group')throw new Error('仅未分类只适用于业务分组规则');
|
||||
const prior=previous.find(rule=>rule.id===id);const scope=enabled(unclassifiedOnly,false);const metadata={id,name,priority:number(priority,'优先级',-10000,10000),stage,target,value,enabled:enabled(status),...(scope||Object.hasOwn(prior??{},'onlyUnclassified')?{onlyUnclassified:scope}:{})};if(scope&&!['group','projectGroup'].includes(target))throw new Error('仅未分类只适用于业务分组和项目组规则');
|
||||
const row=byId.get(id);if(row&&!equal({...row,conditions:undefined},{...metadata,conditions:undefined}))throw new Error(`规则${id}各行的名称、目标、优先级或状态不一致`);
|
||||
const rule=row??{...metadata,conditions:[]};const conditions=rule.conditions as Definition[];const order=number(position,'条件序号',1,20);
|
||||
if(conditions.some(c=>c.order===order))throw new Error(`规则${id}条件序号重复`);conditions.push({order,field,operator,value:conditionValue});byId.set(id,rule);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { api } from './api';
|
||||
import { WORKSPACE_INVALIDATED } from './pageCache';
|
||||
import type { DataWorkflowOperation } from './NoCodeDataTypes';
|
||||
|
||||
type StoredOperation = { operationId: string; startedAt: string };
|
||||
@@ -39,7 +40,7 @@ export function useDataWorkflowOperation(slot: string, onComplete?: (value: Data
|
||||
setOperation(current);
|
||||
const status = String(current.status || '').toUpperCase();
|
||||
if (status === 'COMPLETED' || status === 'FAILED') {
|
||||
if (status === 'COMPLETED') { savePendingId(null); callbackRef.current?.(current); }
|
||||
if (status === 'COMPLETED') { savePendingId(null); window.dispatchEvent(new Event(WORKSPACE_INVALIDATED)); callbackRef.current?.(current); }
|
||||
else setError(operationError(current));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -23,22 +23,22 @@ test('blank-key source creates a narrowly scoped rule and preserves inherited de
|
||||
test('successive group and project edits accumulate without replacing other mappings or explicit empty rules',()=>{
|
||||
let result=editClassification({matchRules:[],categoryLookup:{keep:'category'}},selection,'G',defaults);
|
||||
result=editClassification(result,{kind:'projectGroup',row:{mappingType:'PROJECT_GROUP',customerCode:'001',businessGroup:'G',sourceKey:'001|G'}},'P',defaults);
|
||||
assert.equal(result.projectGroupLookup['001|G'],'P');assert.equal(result.matchRules.length,1);assert.deepEqual(result.categoryLookup,{keep:'category'});
|
||||
assert.equal(result.projectGroupLookup,undefined);assert.equal(result.matchRules.length,2);assert.equal(result.matchRules[0].target,'projectGroup');assert.equal(result.matchRules[0].onlyUnclassified,true);assert.deepEqual(result.categoryLookup,{keep:'category'});
|
||||
assert.throws(()=>editClassification(result,selection,' ',defaults));
|
||||
assert.throws(()=>editClassification(result,{kind:'projectGroup',row:{customerCode:'001',businessGroup:'G',sourceKey:'002|G'}},'P',defaults));
|
||||
});
|
||||
test('interval overrides and conflicting rule identities cannot silently mask a classification edit',()=>{
|
||||
const project={kind:'projectGroup',row:{mappingType:'PROJECT_GROUP',customerCode:'001',businessGroup:'G',sourceKey:'001|G'}};
|
||||
assert.throws(()=>editClassification({effectiveRanges:[{mappingType:'PROJECT_GROUP',sourceKey:'001|G'}]},project,'P',[]),/期间规则/);
|
||||
const ranges=[{mappingType:'PROJECT_GROUP',sourceKey:'001|G'}];assert.deepEqual(editClassification({effectiveRanges:ranges},project,'P',[]).effectiveRanges,ranges);
|
||||
const id=classificationRuleId(source);
|
||||
assert.throws(()=>editClassification({matchRules:[{id,stage:'bright',conditions:[]}]},selection,'G',[]),/冲突/);
|
||||
});
|
||||
|
||||
test('editing a disabled project relationship enables only that relationship and rejects unavailable targets',()=>{
|
||||
test('project maintenance creates only-unclassified rules without changing disabled lookups or existing classifications',()=>{
|
||||
const selection={kind:'projectGroup',row:{mappingType:'PROJECT_GROUP',customerCode:'001',businessGroup:'G',sourceKey:'001|G'}};
|
||||
const base={masterData:{projectGroups:[{code:'P',name:'项目组A',enabled:true}]},disabledMappings:{projectGroupLookup:['001|G','002|G']}};
|
||||
const result=editClassification(base,selection,'项目组A',[]);
|
||||
assert.deepEqual(result.disabledMappings.projectGroupLookup,['002|G']);
|
||||
assert.deepEqual(result.disabledMappings.projectGroupLookup,['001|G','002|G']);assert.equal(result.matchRules[0].onlyUnclassified,true);assert.equal(result.matchRules[0].target,'projectGroup');assert.deepEqual(result.matchRules[0].conditions,[{field:'客户代码',operator:'EQUALS',value:'001'},{field:'@group',operator:'EQUALS',value:'G'}]);assert.equal(editClassification(result,selection,'项目组A',[]).matchRules.length,1);
|
||||
assert.deepEqual(base.disabledMappings.projectGroupLookup,['001|G','002|G']);
|
||||
assert.throws(()=>editClassification(base,selection,'不存在的项目组',[]),/未登记/);
|
||||
});
|
||||
|
||||
@@ -51,3 +51,9 @@ test('legacy twelve-column workbooks preserve the existing unclassified-only res
|
||||
const tables=configurationTables(base,'matchRules');tables[0].headers.pop();tables[0].rows.forEach(row=>row.pop());
|
||||
for(const mode of ['MERGE','REPLACE'])assert.equal(importConfigurationTables(base,tables,'matchRules',mode).definition.matchRules[0].onlyUnclassified,true);
|
||||
});
|
||||
|
||||
test('project unclassified-only rules retain their scope and customer codes through Excel',async()=>{
|
||||
const projectRule={...rule,target:'projectGroup',conditions:[{field:'客户代码',operator:'EQUALS',value:'00001'},{field:'@group',operator:'EQUALS',value:'G'}]};const source={matchRules:[projectRule]};
|
||||
const workbook=await createConfigurationWorkbook(source,'matchRules');const tables=await readConfigurationWorkbook(await workbook.xlsx.writeBuffer());
|
||||
assert.deepEqual(importConfigurationTables(source,tables,'matchRules','REPLACE').definition,source);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {readFileSync} from 'node:fs';
|
||||
import ts from 'typescript';
|
||||
|
||||
const source=ts.transpileModule(readFileSync(new URL('../src/useDataWorkflowOperation.ts',import.meta.url),'utf8'),{compilerOptions:{target:ts.ScriptTarget.ES2022,module:ts.ModuleKind.ESNext}}).outputText.replace(/^import .*;\n/gm,'').replace(/export /g,'');
|
||||
const tick=()=>new Promise(resolve=>setImmediate(resolve));
|
||||
const deferred=()=>{let resolve;const promise=new Promise(done=>{resolve=done;});return{promise,resolve};};
|
||||
|
||||
test('the actual workflow hook refreshes retained data after completion, rather than while work is pending',async()=>{
|
||||
const final=deferred(),events=[],callbacks=[],storage=new Map();let calls=0;
|
||||
const window={localStorage:storage,setTimeout:fn=>setImmediate(fn),dispatchEvent:event=>events.push(event.type)};
|
||||
const localStorage={getItem:key=>storage.get(key)??null,setItem:(key,value)=>storage.set(key,value),removeItem:key=>storage.delete(key)};
|
||||
const api={dataWorkflowOperation:async()=>++calls===1?{operationId:'job',status:'RUNNING'}:final.promise};
|
||||
const hooks={useState:value=>[value,()=>{}],useRef:current=>({current}),useCallback:fn=>fn,useEffect:fn=>{fn();}};
|
||||
const load=new Function('api','window','localStorage','WORKSPACE_INVALIDATED','hooks',`const {useState,useRef,useCallback,useEffect}=hooks;${source};return useDataWorkflowOperation;`);
|
||||
const hook=load(api,window,localStorage,'quality-workspace-invalidated',hooks)('project',value=>callbacks.push(value));
|
||||
await hook.start(async()=>({operationId:'job',status:'QUEUED'}));await tick();await tick();
|
||||
assert.equal(calls,2);assert.deepEqual(events,[]);assert.equal(storage.size,1);
|
||||
final.resolve({operationId:'job',status:'COMPLETED',currentReleaseId:'new-release'});await tick();
|
||||
assert.deepEqual(events,['quality-workspace-invalidated']);assert.equal(callbacks[0].currentReleaseId,'new-release');assert.equal(storage.size,0);
|
||||
});
|
||||
|
||||
test('failed work never refreshes retained data as though a new version had been published',async()=>{
|
||||
const events=[],callbacks=[];const api={dataWorkflowOperation:async()=>({operationId:'job',status:'FAILED',errors:[{message:'rejected'}]})};
|
||||
const hooks={useState:value=>[value,()=>{}],useRef:current=>({current}),useCallback:fn=>fn,useEffect:fn=>{fn();}};
|
||||
const localStorage={getItem:()=>null,setItem:()=>{},removeItem:()=>{}};
|
||||
const window={setTimeout:fn=>setImmediate(fn),dispatchEvent:event=>events.push(event.type)};
|
||||
const load=new Function('api','window','localStorage','WORKSPACE_INVALIDATED','hooks',`const {useState,useRef,useCallback,useEffect}=hooks;${source};return useDataWorkflowOperation;`);
|
||||
const hook=load(api,window,localStorage,'quality-workspace-invalidated',hooks)('project',value=>callbacks.push(value));
|
||||
await hook.start(async()=>({operationId:'job',status:'QUEUED'}));await tick();assert.deepEqual(events,[]);assert.deepEqual(callbacks,[]);
|
||||
});
|
||||
Reference in New Issue
Block a user