feat: collect BPM field evidence and equip ZCode mapping assistant
This commit is contained in:
1 parent
24dbbb74c3
commit
d4070e08f9
30 files changed
+453
-61
No files matched your search
@@ -0,0 +1,45 @@
|
||||
'use strict';
|
||||
const {loadPlaywright}=require('../../platform/browser.cjs'),{normalizeArrival}=require('./list-client.cjs');
|
||||
const {safeEntry}=require('./order-form.cjs');
|
||||
const fail=(message,status=502)=>Object.assign(new Error(message),{status});
|
||||
const HISTORY_ROUTES=Object.freeze(['skyworth/todo/v2/workflow/get_process_of_myprocessed_v4','skyworth/todo/v2/workflow/get_process_of_mytasks_v4']);
|
||||
function normalizeHistory(raw){
|
||||
const id=String(raw.processInstanceId||'');if(!/^\d+$/.test(id)||!raw.processVersion)throw fail('历史样本缺少实例标识或明确版本。');
|
||||
const base=normalizeArrival({...raw,taskId:id,processInstanceSubject:raw.subject},'portal-v4-history'),entry=safeEntry(raw.businessKey,{history:true});
|
||||
if(!entry||entry.target.searchParams.get('tid')!==id)throw fail('历史表单实例标识不一致。',403);
|
||||
return {source:'history',configurationOnly:true,portalSource:'portal-v4-history',taskId:id,instanceId:id,revision:0,processName:base.processName,processVersion:String(raw.processVersion),nodeName:'历史查看(未提供办理节点)',receivedAt:base.arrivedAt,timestampType:'process-start',serialNum:base.serialNum,title:base.subject,detailUrl:raw.businessKey};
|
||||
}
|
||||
class BpmHistoryClient{
|
||||
constructor({requestFactory=options=>loadPlaywright().request.newContext(options)}={}){this.requestFactory=requestFactory;}
|
||||
async scan(storageState,names){
|
||||
if(!Array.isArray(names)||names.length>100||names.some(n=>typeof n!=='string'||!n||n.length>250))throw fail('历史采样流程范围无效。',400);
|
||||
const request=await this.requestFactory({storageState,baseURL:'https://bpmn.skyworthdigital.com/',timeout:20000});
|
||||
const get=async(route,params,token)=>{
|
||||
const response=await request.get(route,{params,headers:token?{Authorization:'Bearer '+token}:{},maxRedirects:0});
|
||||
if([301,302,303,307,308,401,403].includes(response.status()))throw fail('历史查询会话已失效,请重新核验连接。',401);
|
||||
if(response.status()!==200)throw fail('历史字段样本列表读取失败。');
|
||||
const bytes=await response.body();if(bytes.length>10*1024*1024)throw fail('历史列表超过读取上限。');return bytes.toString('utf8');
|
||||
};
|
||||
try{
|
||||
const html=await get('/'),token=/Yiez\.clientId\s*=\s*['"]([^'"\s<>]{1,16000})['"]/.exec(html)?.[1];if(!token)throw fail('BPM 会话需要续登。',401);
|
||||
const rows=[],seen=new Set();
|
||||
for(const processName of [...new Set(names)]){
|
||||
for(const route of HISTORY_ROUTES){
|
||||
let data;try{data=JSON.parse(await get(route,{page:1,start:0,limit:100,processName,year:-1},token));}catch(e){if(e.status)throw e;throw fail('历史列表格式无效。');}
|
||||
if(!Array.isArray(data.children)||data.children.length>100||!Number.isSafeInteger(data.total)||data.total<0||data.success===false)throw fail('历史列表不完整。');
|
||||
const matching=data.children.filter(r=>r.processName===processName).sort((a,b)=>String(b.startTime).localeCompare(String(a.startTime)));
|
||||
if(!matching.length)continue;
|
||||
// Configuration needs the latest actual form version, not an historical
|
||||
// order backlog. Keep up to 3 alternatives for explicit read failures.
|
||||
const version=String(matching[0].processVersion||'');
|
||||
for(const raw of matching.filter(r=>String(r.processVersion||'')===version).slice(0,3)){
|
||||
const row=normalizeHistory(raw),key=row.instanceId;if(seen.has(key))continue;seen.add(key);rows.push(row);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
return rows;
|
||||
}finally{await request.dispose();}
|
||||
}
|
||||
}
|
||||
module.exports={BpmHistoryClient,normalizeHistory,HISTORY_ROUTES};
|
||||
@@ -4,15 +4,20 @@ function processURL(value){
|
||||
const u=new URL(value,'https://bpm.skyworthdigital.com');
|
||||
if(u.origin!=='https://bpm.skyworthdigital.com'||u.pathname!=='/YZSoft/Forms/Process.aspx'||u.username||u.password||u.hash||[...u.searchParams.keys()].length!==2||!['tid','pid'].every(k=>/^\d+$/.test(u.searchParams.get(k)||'')))throw fail('待办流程目标地址未通过核验。',403);return u;
|
||||
}
|
||||
function safeEntry(value){
|
||||
function historyURL(value){
|
||||
let u;try{u=new URL(value,'https://bpm.skyworthdigital.com');}catch{throw fail('历史只读表单地址无效。',403);}
|
||||
if(u.origin!=='https://bpm.skyworthdigital.com'||u.username||u.password||u.hash||!u.pathname.startsWith('/YZSoft/Forms/XForm/')||!u.pathname.endsWith('.aspx')||[...u.searchParams.keys()].length!==1||!/^\d+$/.test(u.searchParams.get('tid')||''))throw fail('历史只读表单地址未通过核验。',403);return u;
|
||||
}
|
||||
function readURL(value){const u=new URL(value,'https://bpm.skyworthdigital.com');if(u.origin!=='https://bpm.skyworthdigital.com'||u.pathname!=='/YZSoft/Forms/Read.aspx'||u.username||u.password||u.hash||[...u.searchParams.keys()].length!==1||!/^\d+$/.test(u.searchParams.get('tid')||''))throw fail('历史只读流程地址未通过核验。',403);return u;}
|
||||
function safeEntry(value,{history=false}={}){
|
||||
let u;try{u=new URL(value);}catch{throw fail('待办表单地址格式无效。',403);}if(u.origin==='https://bpm.skyworthdigital.com'&&u.pathname==='/sso/ssologin.aspx'){
|
||||
if(u.username||u.password||u.hash||[...u.searchParams.keys()].length!==3||[...u.searchParams.keys()].some(k=>!['ReturnUrl','todo_token','todo_account'].includes(k))||!u.searchParams.get('todo_token')||!u.searchParams.get('todo_account'))throw fail('待办临时登录地址格式无效。',403);
|
||||
return {entry:u,target:processURL(u.searchParams.get('ReturnUrl'))};
|
||||
return {entry:u,target:(history?readURL:processURL)(u.searchParams.get('ReturnUrl'))};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
async function loadForm(request,entry,validateFinal){
|
||||
const known=safeEntry(entry);let url=known?.entry||validateFinal(entry),target=known?.target;const visited=new Set();
|
||||
async function loadForm(request,entry,validateFinal,{history=false}={}){
|
||||
const known=safeEntry(entry,{history});let url=known?.entry||validateFinal(entry),target=known?.target;const visited=new Set();
|
||||
for(let hop=0;hop<4;hop++){
|
||||
if(visited.has(url.href))throw fail('表单跳转发生循环。');visited.add(url.href);
|
||||
let response;try{response=await request.get(url.href,{maxRedirects:0,timeout:20000});}catch{throw fail('BPM 表单连接失败,请检查网络后重试。',502);}
|
||||
@@ -22,7 +27,7 @@ async function loadForm(request,entry,validateFinal){
|
||||
// Only the observed SSO -> Process -> XForm chain is allowed; never login,
|
||||
// Redirect.aspx, arbitrary domains, scripts or business mutation requests.
|
||||
url=validateFinal(next.href);
|
||||
if(target&&['tid','pid'].some(k=>url.searchParams.get(k)!==target.searchParams.get(k)))throw fail('表单跳转的实例或任务标识发生变化。',403);
|
||||
if(target&&(history?['tid']:['tid','pid']).some(k=>url.searchParams.get(k)!==target.searchParams.get(k)))throw fail('表单跳转的实例或任务标识发生变化。',403);
|
||||
continue;
|
||||
}
|
||||
if(status!==200)throw fail([401,403].includes(status)?'BPM 表单会话已失效,请重新核验连接。':'BPM 表单查询失败。',[401,403].includes(status)?401:502);
|
||||
@@ -31,9 +36,10 @@ async function loadForm(request,entry,validateFinal){
|
||||
}
|
||||
throw fail('表单跳转次数超过上限。');
|
||||
}
|
||||
async function loadData(request,url){
|
||||
const pid=url.searchParams.get('pid');if(!/^\d+$/.test(pid||''))throw fail('表单任务标识无效。');
|
||||
let response;try{response=await request.post(new URL('/YZSoft/BPM/XMLService/DataProvider.ashx',url).href,{data:'<?xml version="1.0"?><Requests><Params><Method>GetFormProcessData</Method><PID>'+pid+'</PID></Params></Requests>',headers:{'Content-Type':'text/xml'},maxRedirects:0,timeout:20000});}catch{throw fail('表单数据读取超时或连接失败。',502);}
|
||||
async function loadData(request,url,{history=false}={}){
|
||||
const id=url.searchParams.get(history?'tid':'pid');if(!/^\d+$/.test(id||''))throw fail('表单任务标识无效。');
|
||||
const method=history?'GetFormReadData':'GetFormProcessData',key=history?'TID':'PID';
|
||||
let response;try{response=await request.post(new URL('/YZSoft/BPM/XMLService/DataProvider.ashx',url).href,{data:'<?xml version="1.0"?><Requests><Params><Method>'+method+'</Method><'+key+'>'+id+'</'+key+'></Params></Requests>',headers:{'Content-Type':'text/xml'},maxRedirects:0,timeout:20000});}catch{throw fail('表单数据读取超时或连接失败。',502);}
|
||||
const status=response.status();if([301,302,303,307,308,401,403].includes(status))throw fail('表单数据会话失效,请重新核验 BPM 连接。',401);
|
||||
if(status!==200)throw fail('表单数据读取失败。',502);
|
||||
const bytes=await response.body();if(bytes.length>12000000)throw fail('表单数据超出采集上限。');
|
||||
@@ -41,4 +47,4 @@ async function loadData(request,url){
|
||||
if(data.success!==true||!Array.isArray(data.Tables)||data.Tables.length>200||data.Tables.some(t=>!t||typeof t.TableName!=='string'||!Array.isArray(t.Rows)||t.Rows.length>4000||t.Rows.some(r=>!r||Array.isArray(r)||typeof r!=='object')))throw fail('表单数据不完整或未通过权限检查。',502);
|
||||
return data.Tables.filter(t=>t.FormTable===true);
|
||||
}
|
||||
module.exports={safeEntry,processURL,loadForm,loadData};
|
||||
module.exports={safeEntry,processURL,historyURL,loadForm,loadData};
|
||||
@@ -1,7 +1,7 @@
|
||||
'use strict';
|
||||
const {BpmTodoClient}=require('./todo-client.cjs');
|
||||
const {loadPlaywright,browserOptions}=require('../../platform/browser.cjs');
|
||||
const {safeEntry,loadForm,loadData}=require('./order-form.cjs');
|
||||
const {safeEntry,historyURL,loadForm,loadData}=require('./order-form.cjs');
|
||||
const fail=(message,status=409)=>Object.assign(new Error(message),{status});
|
||||
function detailURL(value,allowLocal=false){
|
||||
let url;try{url=new URL(value);}catch{throw fail('待办没有可读取的表单地址;请核验对应门户表单接入。');}
|
||||
@@ -12,6 +12,11 @@ function detailURL(value,allowLocal=false){
|
||||
class BpmOrderProvider{
|
||||
constructor({manager,client=new BpmTodoClient(),browserFactory,allowLocal=false}={}){this.manager=manager;this.client=client;this.browserFactory=browserFactory||(()=>loadPlaywright().chromium.launch(browserOptions()));this.allowLocal=allowLocal;this.entries=new Map();this.checks={liveTodo:false,pdfExport:false,message:'尚未完成真实待办与表单采集检查。'};}
|
||||
capabilities(){return {...this.checks};}
|
||||
async scanHistory(connection,principal,names){
|
||||
const rows=await this.saved(connection,principal,state=>new (require('./history-client.cjs').BpmHistoryClient)().scan(state,names));
|
||||
this.historyEntries||=new Map();this.historyEntries.set(connection.id,new Map(rows.map(row=>[row.taskId,{url:row.detailUrl,row,at:Date.now()}])));
|
||||
return rows.map(row=>({...row,detailUrl:safeEntry(row.detailUrl,{history:true}).target.href}));
|
||||
}
|
||||
async saved(connection,principal,work){return this.manager.run(connection?.id,async()=>{
|
||||
this.manager.authorize(connection,principal);if(this.manager.sessions.has(connection.id))throw fail('此连接正在登录窗口中使用。');
|
||||
const saved=await this.manager.vault().read(connection.id);if(!saved?.storageState)throw fail('BPM 会话未保存,请前往 BPM 连接完成登录核验。',401);
|
||||
@@ -24,9 +29,11 @@ class BpmOrderProvider{
|
||||
this.checks={...this.checks,liveTodo:true,checkedAt:new Date().toISOString(),message:'真实待办接口已读取;各类别表单仍需字段与归档现场核验。'};return safe;}
|
||||
catch(error){this.checks={...this.checks,liveTodo:false,message:error.message};throw error;}
|
||||
}
|
||||
async capture(connection,principal,row){
|
||||
captureFields(connection,principal,row){return this.capture(connection,principal,row,{fieldsOnly:true});}
|
||||
async capture(connection,principal,row,{fieldsOnly=false}={}){
|
||||
const history=row.source==='history';if(history&&!fieldsOnly)throw fail('历史样本仅用于字段配置,不能导出或执行。',403);
|
||||
return this.saved(connection,principal,async storageState=>{
|
||||
let entry=this.entries.get(connection.id)?.get(row.taskId);
|
||||
let entry=(history?this.historyEntries:this.entries)?.get(connection.id)?.get(row.taskId);
|
||||
const sameTask=candidate=>['taskId','instanceId','processName','nodeName','processVersion','revision'].every(key=>String(candidate[key]??'')===String(row[key]??''));
|
||||
if(entry&&!sameTask(entry.row))throw fail('任务元数据已变化,请重新扫描核验原节点与版本。');
|
||||
if((!entry||Date.now()-entry.at>5*60*1000)&&row.detailUrl?.includes('/YZSoft/Forms/Process.aspx')){
|
||||
@@ -34,7 +41,7 @@ class BpmOrderProvider{
|
||||
if(!fresh)throw fail('此任务已不在原节点或版本,请重新扫描核验。');entry={url:fresh.detailUrl,row:fresh,at:Date.now()};
|
||||
}
|
||||
const request=await loadPlaywright().request.newContext({storageState,timeout:20000});let loaded,tables;
|
||||
try{loaded=await loadForm(request,entry?.url||row.detailUrl,value=>detailURL(value,this.allowLocal));tables=await loadData(request,loaded.url);}finally{await request.dispose();}
|
||||
try{loaded=await loadForm(request,entry?.url||row.detailUrl,history?historyURL:value=>detailURL(value,this.allowLocal),{history});tables=await loadData(request,loaded.url,{history});}finally{await request.dispose();}
|
||||
const url=loaded.url;
|
||||
const browser=await this.browserFactory();try{
|
||||
// Server-rendered V4 form only. No page scripts, approval requests or redirects.
|
||||
@@ -46,7 +53,7 @@ class BpmOrderProvider{
|
||||
const page=await context.newPage();let response;
|
||||
try{response=await page.goto(url.href,{waitUntil:'domcontentloaded',timeout:20000});}catch{throw fail('BPM 只读表单解析失败。',502);}
|
||||
if(!response||response.status()!==200||page.url()!==url.href)throw fail('BPM 表单读取失败或登录已失效,请续登后重试。',401);
|
||||
const snapshot=await page.evaluate(tables=>{
|
||||
const snapshot=await page.evaluate(({tables,fieldsOnly})=>{
|
||||
const copy=document.documentElement.cloneNode(true),fields=[],seen=new Map();
|
||||
const hydrated=new Map(),resolved=new Map(),bindings=[...document.querySelectorAll('[xdatabind]')],detailTables=new Set();
|
||||
const blocked=()=>({blocker:'明细多行表单的行数、字段或表格关系不明确,暂不支持此快照;请核验表单接入后重试。'});
|
||||
@@ -59,6 +66,7 @@ class BpmOrderProvider{
|
||||
const list=hydrated.get(key)||[];list.push(item);hydrated.set(key,list);
|
||||
}
|
||||
if(!bound.length)continue;
|
||||
if(fieldsOnly)continue;
|
||||
if(table.Rows.length>1){
|
||||
// Only a complete repeated row schema in one table section proves the
|
||||
// source Rows order maps to DOM rows. Never expand a single template or
|
||||
@@ -79,6 +87,17 @@ class BpmOrderProvider{
|
||||
for(const el of bound){const values=hydrated.get(el.getAttribute('xdatabind').toLowerCase());if(values?.length===1)resolved.set(el,values[0]);}
|
||||
}
|
||||
}
|
||||
if(fieldsOnly){
|
||||
// Field evidence comes from actual server Rows; DOM layout is not a PDF
|
||||
// proof. Index every detail row without assigning it to a template row.
|
||||
for(const el of bindings){
|
||||
const key=el.getAttribute('xdatabind'),items=hydrated.get(key?.toLowerCase());
|
||||
if(!items)continue;
|
||||
const label=el.getAttribute('aria-label')||el.closest('td')?.previousElementSibling?.textContent?.trim()||key;
|
||||
for(const item of items)if(!seen.has(item.path)){seen.set(item.path,item.value);fields.push({...item,label:label.slice(0,200)});}
|
||||
}
|
||||
return {purpose:'field-mapping',fields};
|
||||
}
|
||||
for(const el of bindings){
|
||||
const key=el.getAttribute('xdatabind');if(!key||key.length>250)continue;
|
||||
const item=resolved.get(el),label=el.getAttribute('aria-label')||el.closest('td')?.previousElementSibling?.textContent?.trim()||key;
|
||||
@@ -100,16 +119,16 @@ class BpmOrderProvider{
|
||||
}
|
||||
copy.querySelectorAll('script,iframe,object,embed,button,[printout="false"],#taskCommentForm').forEach(el=>el.remove());
|
||||
return {html:copy.outerHTML,styles:Array.from(document.querySelectorAll('style')).map(e=>e.textContent),images:[],fields:fields.filter(f=>seen.get(f.path)!==null).filter((f,i,a)=>a.findIndex(x=>x.path===f.path)===i)};
|
||||
},tables);
|
||||
},{tables,fieldsOnly});
|
||||
if(snapshot.blocker)throw fail(snapshot.blocker);
|
||||
if(snapshot.html.length>12000000||snapshot.fields.length>4000)throw fail('表单超出采集上限。');
|
||||
if((snapshot.html?.length||0)>12000000||snapshot.fields.length>4000)throw fail('表单超出采集上限。');
|
||||
if(!snapshot.fields.some(f=>f.value!==''))throw fail('只读表单未取得实际字段值,需核验表单加载接口;禁止使用空表单继续执行。');
|
||||
snapshot.sourceUrl=url.href;snapshot.processVersion=String(row.processVersion||'');
|
||||
if(!snapshot.processVersion)throw fail('待办未提供流程版本,需要核验版本来源。');
|
||||
const sample={...row,connectionId:connection.id,fields:Object.fromEntries(snapshot.fields.map(f=>[f.path,f.value])),brief:row.title};
|
||||
this.checks={...this.checks,pdfExport:true,capturedAt:new Date().toISOString()};return {sample,snapshot};
|
||||
if(!fieldsOnly)this.checks={...this.checks,pdfExport:true,capturedAt:new Date().toISOString()};return {sample,snapshot};
|
||||
}finally{await browser.close();}
|
||||
}).catch(error=>{this.checks={...this.checks,pdfExport:false,message:error.message};throw error;});
|
||||
}).catch(error=>{if(!fieldsOnly)this.checks={...this.checks,pdfExport:false,message:error.message};throw error;});
|
||||
}
|
||||
}
|
||||
module.exports={BpmOrderProvider,detailURL};
|
||||
Reference in new issue
Block a user