'use strict'; const {BpmTodoClient}=require('./todo-client.cjs'); const {loadPlaywright,browserOptions}=require('../../platform/browser.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('待办没有可读取的表单地址;请核验对应门户表单接入。');} 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,readonlyReader}={}){this.manager=manager;this.client=client;this.browserFactory=browserFactory||(()=>loadPlaywright().chromium.launch(browserOptions()));this.allowLocal=allowLocal;this.readonlyReader=readonlyReader;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){const query=()=>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); try{const result=await work(saved.storageState);this.manager.authorize(connection,principal);this.manager.observe?.(connection.id,'todo');return result;} catch(error){this.manager.observe?.(connection.id,'todo',error);throw error;} }); try{return await query();}catch(error){if(error.status!==401)throw error;} const renewed=await this.manager.ensure(connection,principal); if(renewed?.status!=='connected')throw fail(renewed?.checks?.portal?.message||'BPM 会话需要续登。',401); return query(); } 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.manager.observe?.(connection.id,'todo');this.checks={...this.checks,liveTodo:true,checkedAt:new Date().toISOString(),message:'真实待办接口已读取;各类别表单仍需字段与归档现场核验。'};return safe;} catch(error){this.manager.observe?.(connection.id,'todo',error);this.checks={...this.checks,liveTodo:false,message:error.message};throw error;} } 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); if(!history&&!this.allowLocal)return this.captureReadonly(connection,principal,row,{fieldsOnly}); return this.saved(connection,principal,async storageState=>{ 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')){ const rows=await this.client.scan(storageState),fresh=rows.find(sameTask); 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,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. 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,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:'明细多行表单的行数、字段或表格关系不明确,暂不支持此快照;请核验表单接入后重试。'}); for(const table of tables){ const prefix=(table.DataSource?table.DataSource+':':'')+table.TableName; const prefixKey=prefix.toLowerCase(),bound=bindings.filter(el=>{const key=el.getAttribute('xdatabind')?.toLowerCase();return key?.startsWith(prefixKey+'.')||key?.startsWith(prefixKey+'[');}); 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); } 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 // flatten a column into every occurrence. Other layouts need an adapter. const rows=new Map(),keys=new Set(bound.map(el=>el.getAttribute('xdatabind').toLowerCase()));let container,section; for(const el of bound){ const row=el.closest('tr'),host=el.closest('table'),cell=el.closest('td,th'),key=el.getAttribute('xdatabind').toLowerCase(),values=hydrated.get(key); if(!row||!host||row.closest('table')!==host||!cell||cell.rowSpan!==1||el.parentElement?.closest('[xdatabind]')||!values||values.length!==table.Rows.length)return blocked(); if(container&&(container!==host||section!==row.parentElement))return blocked();container=host;section=row.parentElement; const columns=rows.get(row)||new Map();if(columns.has(key))return blocked();columns.set(key,el);rows.set(row,columns); } if(rows.size!==table.Rows.length||detailTables.has(container))return blocked();detailTables.add(container); for(const [index,columns]of [...rows.values()].entries()){ if(columns.size!==keys.size||[...keys].some(key=>!columns.has(key)))return blocked(); for(const [key,el]of columns)resolved.set(el,hydrated.get(key)[index]); } }else{ 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; if(item){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 [index,el]of [...copy.querySelectorAll('[xdatabind]')].entries()){ if(el.matches('input,textarea,select'))continue; const item=resolved.get(bindings[index]);if(item)el.textContent=item.value; } for(const [index,el]of [...copy.querySelectorAll('input,textarea,select')].entries()){ const original=originals[index],span=document.createElement('span'); const item=resolved.get(original); span.textContent=item?['radio','checkbox'].includes(original.type)?item.value===original.value?'☑':'☐':item.value: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,fieldsOnly}); if(snapshot.blocker)throw fail(snapshot.blocker); 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}; if(!fieldsOnly)this.checks={...this.checks,pdfExport:true,capturedAt:new Date().toISOString()};return {sample,snapshot}; }finally{await browser.close();} }).catch(error=>{if(!fieldsOnly)this.checks={...this.checks,pdfExport:false,message:error.message};throw error;}); } async captureReadonly(connection,principal,row,{fieldsOnly=false}={}){ return this.saved(connection,principal,async storageState=>{ if(row.source!=='todo'||row.configurationOnly||row.demo)throw fail('只读执行只接受真实当前通知任务。'); const rows=await this.client.scan(storageState),same=rows.filter(fresh=>fresh.source===row.source&&String(fresh.taskId)===String(row.taskId)&&(!row.portalSource||fresh.portalSource===row.portalSource)); if(same.length!==1)throw Object.assign(fail('此任务已不在当前列表或来源存在歧义,请核验原通知任务后再恢复。'),{code:'BPM_TASK_NOT_CURRENT'}); const current=same[0]; if(['instanceId','processName','nodeName','processVersion','revision','receivedAt','serialNum','title'].some(key=>String(current[key]??'')!==String(row[key]??'')))throw fail('当前通知任务的节点、版本、摘要或时间已变化,请重新核对。'); const original=row.detailUrl?safeEntry(row.detailUrl):null,fresh=current.detailUrl?safeEntry(current.detailUrl):null; if(!fresh||original&&(original.target.searchParams.get('tid')!==fresh.target.searchParams.get('tid')||original.target.searchParams.get('pid')!==fresh.target.searchParams.get('pid')))throw fail('通知任务与详情标识不一致。'); const reader=this.readonlyReader||require('../../bpm-readonly-form.cjs').captureReadonlyForm; let captured; try{captured=await reader({storageState,detailUrl:current.detailUrl,processName:current.processName,nodeName:current.nodeName,listProcessVersion:current.processVersion,fieldsOnly,browserFactory:this.browserFactory});} catch(error){ if(error.partialDetail){ const partial=error.partialDetail; const fields=Object.entries(partial.detail.fields).map(([path,value])=>({path,label:path,value})); error.partialCapture={sample:{...row,detailUrl:fresh.target.href,connectionId:connection.id,fields:structuredClone(partial.detail.fields),brief:row.title,formVersion:partial.detail.formVersion,formPath:partial.detail.formPath,detailEvidence:{tid:partial.detail.tid,pid:partial.detail.pid,formVersion:partial.detail.formVersion,listProcessVersion:current.processVersion,readOnly:true}},snapshot:{purpose:'field-mapping',fields,sourceUrl:partial.detailUrl,processVersion:current.processVersion,formVersion:partial.detail.formVersion,formPath:partial.detail.formPath,fieldSources:partial.detail.fieldSources,capturedAt:partial.capturedAt,evidenceHash:partial.evidenceHash}}; delete error.partialDetail; } this.checks={...this.checks,pdfExport:false,message:error.message};throw error; } const fields=Object.entries(captured.detail.fields).map(([path,value])=>({path,label:path,value})); if(!fields.length||fields.length>4000||fields.every(field=>field.value===null||field.value===''))throw fail('只读表单缺少有效字段或超过采集上限。'); const snapshot={...(captured.snapshot||{purpose:'field-mapping'}),fields,sourceUrl:captured.detailUrl,processVersion:current.processVersion,formVersion:captured.detail.formVersion,formPath:captured.detail.formPath,fieldSources:captured.detail.fieldSources,capturedAt:captured.capturedAt,evidenceHash:captured.evidenceHash}; const sample={...row,detailUrl:fresh.target.href,connectionId:connection.id,fields:structuredClone(captured.detail.fields),brief:row.title,formVersion:captured.detail.formVersion,formPath:captured.detail.formPath,detailEvidence:{tid:captured.detail.tid,pid:captured.detail.pid,formVersion:captured.detail.formVersion,listProcessVersion:current.processVersion,readOnly:true}}; if(!fieldsOnly){if(!snapshot.html)throw fail('PDF 快照未完成。');this.checks={...this.checks,liveTodo:true,pdfExport:true,capturedAt:new Date().toISOString()};} return {sample,snapshot}; }); } } module.exports={BpmOrderProvider,detailURL};