Files
order-notification-automation/src/modules/bpm/order-provider.cjs
T

91 lines
8.1 KiB
JavaScript

'use strict';
const {BpmTodoClient}=require('./todo-client.cjs');
const {loadPlaywright,browserOptions}=require('../../platform/browser.cjs');
const {safeEntry,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('待办没有可读取的表单地址;请核验对应门户表单接入。');}
const local=allowLocal&&['127.0.0.1','localhost','[::1]'].includes(url.hostname);
if(url.username||url.password||url.hash||!['http:','https:'].includes(url.protocol)||(!local&&(url.origin!=='https://bpm.skyworthdigital.com'||!url.pathname.startsWith('/YZSoft/Forms/XForm/')))||!/^\/[\s\S]+\.aspx$/i.test(url.pathname)||[...url.searchParams.keys()].length!==2||[...url.searchParams.keys()].some(k=>!['tid','pid'].includes(k))||!/^\d+$/.test(url.searchParams.get('tid')||'')||!/^\d+$/.test(url.searchParams.get('pid')||''))throw fail('表单地址不在已核验的只读范围内。',403);
return url;
}
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 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);
const result=await work(saved.storageState);this.manager.authorize(connection,principal);return result;
});}
async scan(connection,principal){
try{const rows=await this.saved(connection,principal,state=>this.client.scan(state));
const safe=rows.map(row=>{const entry=row.detailUrl?safeEntry(row.detailUrl):null;return {...row,detailUrl:entry?entry.target.href:row.detailUrl?detailURL(row.detailUrl,this.allowLocal).href:undefined};});
this.entries.set(connection.id,new Map(rows.filter(r=>r.detailUrl).map(r=>[r.taskId,{url:r.detailUrl,row:r,at:Date.now()}])));
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){
return this.saved(connection,principal,async storageState=>{
let entry=this.entries.get(connection.id)?.get(row.taskId);
if((!entry||Date.now()-entry.at>5*60*1000)&&row.detailUrl?.includes('/YZSoft/Forms/Process.aspx')){
const rows=await this.client.scan(storageState),fresh=rows.find(r=>r.taskId===row.taskId&&r.instanceId===row.instanceId&&r.nodeName===row.nodeName&&r.processVersion===row.processVersion);
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();}
const url=loaded.url;
const browser=await this.browserFactory();try{
// Server-rendered V4 form only. No page scripts, approval requests or redirects.
const context=await browser.newContext({storageState,javaScriptEnabled:false,serviceWorkers:'block',acceptDownloads:false});
await context.route('**/*',async route=>{
if(route.request().method()!=='GET'||route.request().url()!==url.href)return route.abort();
return route.fulfill({status:200,contentType:'text/html; charset=utf-8',body:loaded.bytes});
});
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 copy=document.documentElement.cloneNode(true),fields=[],seen=new Map();
const hydrated=new Map();
for(const table of tables){
const prefix=(table.DataSource?table.DataSource+':':'')+table.TableName;
for(const [index,row]of table.Rows.entries())for(const [column,value]of Object.entries(row)){
if(value!==null&&!['string','number','boolean'].includes(typeof value))continue;
const path=prefix+'.'+column,key=path.toLowerCase(),item={path:table.Rows.length===1?path:prefix+'['+index+'].'+column,value:value===null?'':String(value)};
const list=hydrated.get(key)||[];list.push(item);hydrated.set(key,list);
}
}
for(const el of document.querySelectorAll('[xdatabind]')){
const key=el.getAttribute('xdatabind');if(!key||key.length>250)continue;
const values=hydrated.get(key.toLowerCase()),label=el.getAttribute('aria-label')||el.closest('td')?.previousElementSibling?.textContent?.trim()||key;
if(values){for(const item of values){if(!seen.has(item.path)){seen.set(item.path,item.value);fields.push({...item,label:label.slice(0,200)});}}continue;}
if(['radio','checkbox'].includes(el.type)&&!el.checked)continue;
const value='value'in el?el.value:el.textContent.trim();
if(seen.has(key)&&seen.get(key)!==value){seen.set(key,null);continue;}seen.set(key,value);fields.push({path:key,label:label.slice(0,200),value});
}
const originals=[...document.querySelectorAll('input,textarea,select')];
for(const el of copy.querySelectorAll('[xdatabind]')){
if(el.matches('input,textarea,select'))continue;
const values=hydrated.get(el.getAttribute('xdatabind')?.toLowerCase());if(values)el.textContent=values.map(v=>v.value).join('\n');
}
for(const [index,el]of [...copy.querySelectorAll('input,textarea,select')].entries()){
const original=originals[index],span=document.createElement('span');
const values=hydrated.get(original?.getAttribute('xdatabind')?.toLowerCase());
span.textContent=values?['radio','checkbox'].includes(original.type)?values.some(v=>v.value===original.value)?'☑':'☐':values.map(v=>v.value).join('\n'):original?['radio','checkbox'].includes(original.type)?original.checked?'☑':'☐':original.tagName==='SELECT'?original.selectedOptions?.[0]?.textContent||original.value:original.value||'':'';
if(original?.type==='hidden')span.hidden=true;el.replaceWith(span);
}
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);
if(snapshot.html.length>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};
}finally{await browser.close();}
}).catch(error=>{this.checks={...this.checks,pdfExport:false,message:error.message};throw error;});
}
}
module.exports={BpmOrderProvider,detailURL};