'use strict'; const {BpmTodoClient}=require('./todo-client.cjs'); const {loadPlaywright,browserOptions}=require('../../platform/browser.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||(!local&&(url.origin!=='https://bpm.skyworthdigital.com'||!url.pathname.startsWith('/YZSoft/Forms/XForm/')))||!/^\/[\s\S]+\.aspx$/i.test(url.pathname)||[...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.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));this.checks={...this.checks,liveTodo:true,checkedAt:new Date().toISOString(),message:'真实待办接口已读取;各类别表单仍需字段与归档现场核验。'};return rows;} catch(error){this.checks={...this.checks,liveTodo:false,message:error.message};throw error;} } async capture(connection,principal,row){ const url=detailURL(row.detailUrl,this.allowLocal); return this.saved(connection,principal,async storageState=>{ 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('**/*',route=>route.request().method()==='GET'&&route.request().url()===url.href?route.continue():route.abort()); const page=await context.newPage(),response=await page.goto(url.href,{waitUntil:'domcontentloaded',timeout:20000}); if(!response||response.status()!==200||page.url()!==url.href)throw fail('BPM 表单读取失败或登录已失效,请续登后重试。',401); const snapshot=await page.evaluate(()=>{ const copy=document.documentElement.cloneNode(true),fields=[],seen=new Map(); for(const el of document.querySelectorAll('[xdatabind]')){ const key=el.getAttribute('xdatabind');if(!key||key.length>250)continue; if(['radio','checkbox'].includes(el.type)&&!el.checked)continue; const value='value'in el?el.value:el.textContent.trim(),label=el.getAttribute('aria-label')||el.closest('td')?.previousElementSibling?.textContent?.trim()||key; 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}); } for(const el of copy.querySelectorAll('input,textarea,select')){const original=document.getElementById(el.id),span=document.createElement('span');span.textContent=original?original.tagName==='SELECT'?original.selectedOptions?.[0]?.textContent||original.value:original.value||'':'';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)}; }); 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();} }); } } module.exports={BpmOrderProvider,detailURL};