修复:目标保存后取消读取时自动重试并切换年度

This commit is contained in:
2026-11-04 12:32:26 +08:00
parent 866ba21bb8
commit 9f282baa95
2 changed files with 82 additions and 8 deletions
+28 -8
View File
@@ -6,6 +6,7 @@ import { CompactManagementTables, QualityTable as Table } from './QualityTable';
import { ApiError, api } from './api';
import { METRIC_NAMES, matchingTarget, ruleObject as obj, ruleList, type RuleDefinition as Row } from './rulePresentation';
import { readableSelectPopup } from './readableSelectPopup';
import { useMaintenanceRefresh } from './pageCache';
const DIMENSIONS=['department','group','product','projectGroup'] as const;
const dimensionName={department:'产业部',group:'业务分组',product:'产品',projectGroup:'项目组'};
@@ -22,17 +23,36 @@ export function QualityTargetsPanel({onUnauthorized}:{onUnauthorized:(error:unkn
const [year,setYear]=useState(new Date().getFullYear()),[metric,setMetric]=useState('COMPOSITE_RATE');
const [form]=Form.useForm<TargetForm>();const scope=Form.useWatch('scope',form),inherit=Form.useWatch('inherit',form),department=Form.useWatch('department',form);
const saveLock=useRef(false);
const readGeneration=useRef(0),mounted=useRef(false);
const selectedYear=Form.useWatch('year',form),selectedMetric=Form.useWatch('metric',form);
const load=useCallback(async()=>{
if(!mounted.current)return;
const generation=++readGeneration.current;
const current=()=>mounted.current&&generation===readGeneration.current;
setLoading(true);setError('');
try{
const list=await api.targetVersions();const active=list.items.find(row=>String(row.status).toUpperCase()==='ACTIVE');
if(!active){setVersion(null);setTargets([]);return;}
const [detail,names]=await Promise.all([api.targetVersion(String(active.id)),api.referenceNames()]);
setVersion(obj(detail.version||active));setTargets(ruleList(detail.targets));setReferences(names);
}catch(e){if(!onUnauthorized(e))setError(e instanceof Error?e.message:'目标读取失败');}finally{setLoading(false);}
for(let attempt=0;attempt<3;attempt++){
try{
const list=await api.targetVersions();if(!current())return;
const active=list.items.find(row=>String(row.status).toUpperCase()==='ACTIVE');
if(!active){setVersion(null);setTargets([]);return;}
const [detail,names]=await Promise.all([api.targetVersion(String(active.id)),api.referenceNames()]);
if(!current())return;
setVersion(obj(detail.version||active));setTargets(ruleList(detail.targets));setReferences(names);return;
}catch(e){
if(!current())return;
// 保存或跨页版本刷新会取消旧读取,只重读数据,绝不重复提交目标。
if(e instanceof Error&&e.name==='AbortError'){
if(attempt<2)continue;
throw new Error('目标数据正在刷新,请稍后点击重试');
}
throw e;
}
}
}catch(e){if(current()&&!onUnauthorized(e))setError(e instanceof Error?e.message:'目标读取失败');}finally{if(current())setLoading(false);}
},[onUnauthorized]);
useEffect(()=>{void load();},[load]);
useEffect(()=>{mounted.current=true;void load();return()=>{mounted.current=false;readGeneration.current++;};},[load]);
useMaintenanceRefresh(()=>void load());
const annual=targets.filter(row=>String(row.periodType).toUpperCase()==='YEAR');
const years=[...new Set([new Date().getFullYear(),...annual.map(row=>Number(row.year))])].sort((a,b)=>a-b);
const overall=annual.find(row=>row.metric===metric&&row.year===year&&!Object.keys(dimensions(row.dimensions)).length);
@@ -56,7 +76,7 @@ export function QualityTargetsPanel({onUnauthorized}:{onUnauthorized:(error:unkn
};
const persist=async(next:Row[])=>{
if(!version||saveLock.current)return false;saveLock.current=true;setSaving(true);
try{await api.updateCurrentTargets({targets:next.map(targetInput),expectedRowVersion:Number(version.rowVersion||0)});message.success('目标已更新');setEditing(null);await load();return true;}
try{const saved=await api.updateCurrentTargets({targets:next.map(targetInput),expectedRowVersion:Number(version.rowVersion||0)});if(saved.version)setVersion(obj(saved.version));if(Array.isArray(saved.targets))setTargets(ruleList(saved.targets));message.success('目标已更新');setEditing(null);await load();return true;}
catch(e){if(!onUnauthorized(e))message.error(e instanceof ApiError&&e.status===409?'目标已被其他人修改,请刷新后核对':e instanceof Error?e.message:'目标保存失败');return false;}
finally{saveLock.current=false;setSaving(false);}
};
@@ -72,7 +92,7 @@ export function QualityTargetsPanel({onUnauthorized}:{onUnauthorized:(error:unkn
next=[...next,{...prior,metric:f.metric,periodType:'YEAR',year:f.year,dimensions:d,value:Number(f.value)/100,unit:'RATE'}];
}
if(!next.some(row=>String(row.periodType).toUpperCase()==='YEAR'&&!Object.keys(dimensions(row.dimensions)).length)){message.error('至少保留一项总体年度目标');return;}
await persist(next);
if(await persist(next)){setYear(f.year);setMetric(f.metric);}
}catch{ /* 表单保留在原位置显示字段错误。 */ }
};
const defaultTarget=matchingTarget(annual.filter(row=>row.metric===selectedMetric&&row.year===selectedYear&&(!editing||identity(row)!==identity(editing))),dimensions(form.getFieldsValue(true)));
@@ -0,0 +1,54 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import ts from 'typescript';
import React from 'react';
const compile=s=>ts.transpileModule(s,{compilerOptions:{target:ts.ScriptTarget.ES2022,module:ts.ModuleKind.ESNext,jsx:ts.JsxEmit.React}}).outputText;
const component=compile(fs.readFileSync(new URL('../src/QualityTargetsPanel.tsx',import.meta.url),'utf8')).replace(/^import .*;\n/gm,'').replace(/export /g,'');
const coordinatorCode=compile(fs.readFileSync(new URL('../src/requestCoordinator.ts',import.meta.url),'utf8'));
const tick=()=>new Promise(r=>setTimeout(r,0));
const deferred=()=>{let resolve;return {promise:new Promise(r=>resolve=r),resolve:v=>resolve(v)};};
async function fixture({cancelInitial=false,cancelAfterSave=false,denied=false}={}){
const coordinator=await import(`data:text/javascript;base64,${Buffer.from(coordinatorCode).toString('base64')}#${Math.random()}`);
let revision=1;coordinator.configureRequestScope({userId:'actor',authRevision:'auth',dataRevision:String(revision),currentReleaseId:'release'});
const states=[],effects=new Map(),messages=[],formValues={};let cursor=0,dirty=true,tree,pending=[],writes=0,reads=0;
const data={version:{id:'targets',status:'ACTIVE',rowVersion:1},targets:[{metric:'COMPOSITE_RATE',periodType:'YEAR',year:2026,dimensions:{},value:.955,unit:'RATE'}]};
const stale=deferred();let cancelNext=cancelInitial;
const coordinated=(url,dataFn)=>coordinator.coordinateRequest({url,execute:async()=>({data:await dataFn(),status:200,bytes:100})});
const api={
targetVersions:()=>coordinated('/api/analytics/targets/versions',async()=>{reads++;if(denied)throw Object.assign(new Error('无权限'),{status:403});if(cancelNext){cancelNext=false;queueMicrotask(()=>coordinator.configureRequestScope({userId:'actor',authRevision:'auth',dataRevision:String(++revision),currentReleaseId:'release'}));await stale.promise;}return {items:[data.version]};}),
targetVersion:()=>coordinated('/api/analytics/targets/versions/targets',async()=>structuredClone(data)),
referenceNames:()=>coordinated('/api/options/reference-names',async()=>({})),
updateCurrentTargets:async body=>{writes++;data.targets=structuredClone(body.targets);data.version={...data.version,rowVersion:data.version.rowVersion+1};cancelNext=cancelAfterSave;return structuredClone(data);},
};
const hooks={
useState(initial){const i=cursor++;if(!(i in states))states[i]=initial;return [states[i],v=>{states[i]=typeof v==='function'?v(states[i]):v;dirty=true;}];},
useRef(initial){const i=cursor++;if(!(i in states))states[i]={current:initial};return states[i];},
useCallback(fn,deps){const i=cursor++,old=states[i];if(!old||deps.some((v,j)=>!Object.is(v,old.deps[j])))states[i]={fn,deps};return states[i].fn;},
useEffect(fn,deps){const i=cursor++,old=effects.get(i);if(!old||!deps||deps.some((v,j)=>!Object.is(v,old.deps[j])))pending.push(()=>{old?.cleanup?.();effects.set(i,{deps,cleanup:fn()});});},
};
const Form=Object.assign('Form',{useForm:()=>[{setFieldsValue(v){Object.assign(formValues,v);},getFieldsValue:()=>({...formValues}),validateFields:async()=>({...formValues})}],useWatch:key=>formValues[key],Item:'FormItem'});
const names=['React','useCallback','useEffect','useRef','useState','Alert','App','Button','Checkbox','Empty','Form','Input','InputNumber','Modal','Select','Spin','PlusOutlined','ReloadOutlined','CompactManagementTables','Table','ApiError','api','METRIC_NAMES','matchingTarget','obj','ruleList','readableSelectPopup','useDeleteConfirmation','useMaintenanceRefresh'];
class ApiError extends Error{}
const values=[React,hooks.useCallback,hooks.useEffect,hooks.useRef,hooks.useState,'Alert',{useApp:()=>({message:{success:x=>messages.push(['success',x]),error:x=>messages.push(['error',x])}})},'Button','Checkbox','Empty',Form,'Input','InputNumber','Modal','Select','Spin','Plus','Reload',{Provider:'Provider'},'Table',ApiError,api,{COMPOSITE_RATE:'综合合格率'},()=>null,v=>v&&typeof v==='object'?v:{},v=>Array.isArray(v)?v:[],{},()=>()=>{},()=>{}];
const Component=new Function(...names,component+';return QualityTargetsPanel;')(...values);
const props={onUnauthorized:e=>e?.status===401};
function render(){cursor=0;dirty=false;pending=[];tree=Component(props);pending.forEach(f=>f());}
async function settle(){for(let n=0;n<20;n++){if(dirty)render();await tick();}if(dirty)render();}
function nodes(e){return React.isValidElement(e)?[e,...React.Children.toArray(e.props.children).flatMap(nodes)]:[];}
function find(type,predicate=()=>true){return nodes(tree).find(n=>n.type===type&&predicate(n.props));}
await settle();
return {settle,find,messages,stale,formValues,get writes(){return writes;},get reads(){return reads;},get data(){return data;},dispose(){effects.forEach(e=>e.cleanup?.());coordinator.resetRequestScope();}};
}
test('target reads cancelled by a workspace revision automatically reload instead of leaving 请求已取消 on screen',async()=>{
const f=await fixture({cancelInitial:true});try{assert.ok(f.find('Table'),'a fresh target snapshot must render after the coordinator cancels the first GET');assert.equal(f.find('Alert'),undefined);assert.ok(f.reads>=2);f.stale.resolve();await f.settle();assert.equal(f.find('Alert'),undefined);}finally{f.dispose();}
});
test('a committed new year survives refresh cancellation, is not saved twice, and becomes the selected year',async()=>{
const f=await fixture({cancelAfterSave:true});try{
f.find('Button',p=>React.Children.toArray(p.children).includes('新增目标')).props.onClick();await f.settle();Object.assign(f.formValues,{year:2025,metric:'COMPOSITE_RATE',scope:'overall',value:95,inherit:false});f.find('Modal').props.onOk();await f.settle();
assert.equal(f.writes,1);assert.equal(f.find('Alert'),undefined,'a cancelled post-save refresh is not a save failure');assert.equal(f.find('Select',p=>p['aria-label']==='目标年度').props.value,2025);assert.equal(f.find('Table').props.dataSource[0].displayValue,.95);assert.equal(f.data.targets.length,2);assert.equal(f.data.targets.find(t=>t.year===2026).value,.955);
}finally{f.dispose();}
});
test('real authorization errors remain visible and are not retried as cancelled reads',async()=>{
const f=await fixture({denied:true});try{assert.equal(f.reads,1);assert.ok(f.find('Alert').props.description.includes('无权限'));}finally{f.dispose();}
});