Files
order-notification-automation/src/bpm-order-detail.cjs
T
abaishu0730 94fc985553 feat: add guarded BPM category and template workflow
Implement server-owned read-only sample checks, category publication, explicit
order-version identity and durable PDF/archive/notification steps. Freeze
category-bound templates and recipients for isolated scheduled delivery, and
require human verification for unknown SMTP outcomes. Add order/batch views
and local HTTP/browser/PDF/archive regression coverage.

Fix Unicode Windows startup links found by full regression using IShellLinkW.
Automatic processing and sending stay disabled; no service deployment.

Validation: npm ci; npm test -- --test-concurrency=1 (242 pass, 1 optional
ZCode skip, 0 fail); 31 syntax checks; scoped independent code review.
Live BPM V13/SMB/163 acceptance remains pending.
2026-10-22 16:52:59 +08:00

60 lines
8.2 KiB
JavaScript

'use strict';
const crypto=require('node:crypto');
const {loadPlaywright,browserOptions}=require('./runtime.cjs');
const fail=(message,status=409)=>{throw Object.assign(new Error(message),{status});};
function parseDetailUrl(value){
let url;try{url=new URL(value);}catch{fail('BPM 详情地址无效。');}
if(url.origin!=='https://bpm.skyworthdigital.com'||url.username||url.password||url.hash||!url.pathname.startsWith('/YZSoft/Forms/XForm/'))fail('BPM 详情地址不受支持。',403);
if([...url.searchParams.keys()].some(key=>!['tid','pid'].includes(key))||['tid','pid'].some(key=>url.searchParams.getAll(key).length!==1))fail('BPM 详情 tid/pid 参数必须唯一,不能包含办理动作。');
const tid=url.searchParams.get('tid'),pid=url.searchParams.get('pid');if(!/^\d{1,30}$/.test(tid||'')||!/^\d{1,30}$/.test(pid||''))fail('BPM 详情缺少有效 tid/pid。');
const pathname=decodeURIComponent(url.pathname),match=pathname.match(/\/([^/]+?)(V\d+)\.aspx$/i);if(!match)fail('BPM 详情缺少可识别的表单版本。');
return {tid,pid,processVersion:match[2].toUpperCase(),processName:match[1]};
}
function allowDetailRequest(value,method,target,navigation=false){
try{const url=new URL(value),detail=new URL(target);if(method!=='GET'||url.origin!==detail.origin||url.username||url.password)return false;
if(navigation)return url.href===detail.href;
return !url.search&&/\.(?:js|css|png|jpg|jpeg|gif|svg|woff2?|ttf|ico)$/i.test(url.pathname)&&!/(?:approve|fulfill|markread|upload|delete)/i.test(url.pathname);
}catch{return false;}
}
function readDetailDocument(){
const source=document.querySelector('form');if(!source)throw Error('BPM 详情表单未就绪。');
const visible=element=>{for(let node=element;node;node=node.parentElement){const style=getComputedStyle(node);if(node.hidden||['hidden','password','file'].includes(node.type)||style.display==='none'||['hidden','collapse'].includes(style.visibility))return false;}return true;};
const value=element=>element instanceof HTMLSelectElement?[...element.selectedOptions].map(option=>option.textContent).join('、'):['checkbox','radio'].includes(element.type)?(element.checked?element.value:''):'value'in element?element.value:element.innerText;
const elements=[...source.querySelectorAll('[xdatabind],[data-xdatabind],[data-bind]')].filter(visible).map(element=>({binding:element.getAttribute('xdatabind')||element.getAttribute('data-xdatabind')||element.getAttribute('data-bind'),value:value(element)}));
const processSteps=[];
for(const table of document.querySelectorAll('table')){
const rows=[...table.rows],header=rows.find(row=>[...row.cells].some(cell=>/^(节点|环节|步骤|活动名称|节点名称)$/.test(cell.textContent.trim()))&&[...row.cells].some(cell=>/^(状态|处理状态)$/.test(cell.textContent.trim())));if(!header)continue;
const labels=[...header.cells].map(cell=>cell.textContent.trim()),ni=labels.findIndex(label=>/^(节点|环节|步骤|活动名称|节点名称)$/.test(label)),si=labels.findIndex(label=>/^(状态|处理状态)$/.test(label));
for(const row of rows.slice(rows.indexOf(header)+1)){const name=row.cells[ni]?.textContent.trim(),status=row.cells[si]?.textContent.trim();if(name&&status)processSteps.push({name,status});}
}
const copy=source.cloneNode(true),originals=[source,...source.querySelectorAll('*')],copies=[copy,...copy.querySelectorAll('*')];
for(let i=originals.length-1;i>=0;i--){const original=originals[i],target=copies[i];if(!visible(original)||['SCRIPT','IFRAME','OBJECT','EMBED','BUTTON','LINK','META'].includes(original.tagName)||['hidden','password','file','submit','button','reset'].includes(original.type)||original.getAttribute('printout')==='false'){target.remove();continue;}if(['INPUT','TEXTAREA','SELECT'].includes(original.tagName)){const span=document.createElement('span');span.textContent=value(original);span.style.whiteSpace='pre-wrap';target.replaceWith(span);}else for(const attr of [...target.attributes])if(/^on/i.test(attr.name)||['action','srcdoc','srcset','formaction','value'].includes(attr.name))target.removeAttribute(attr.name);}
copy.querySelectorAll('#taskCommentForm,#TaskCommentCount').forEach(node=>node.remove());
const styles=[];for(const sheet of document.styleSheets)try{styles.push([...sheet.cssRules].map(rule=>rule.cssText).join('\n'));}catch{}
return {elements,processSteps,snapshot:{html:copy.outerHTML,styles,width:1264,images:[]}};
}
function extractFieldSnapshot(input){
if(!input||!Array.isArray(input.elements)||!Array.isArray(input.processSteps)||!input.processName||!input.nodeName||!input.processInstanceId)fail('BPM 详情缺少流程实例或字段证据。');
const fields={};for(const element of input.elements){if(!element||typeof element.binding!=='string'||!element.binding.trim())continue;if(fields[element.binding]!==undefined&&String(fields[element.binding])!==String(element.value??''))fail('BPM 详情字段存在多个不同值。');fields[element.binding]=element.value??'';}
if(!Object.keys(fields).length)fail('BPM 详情没有可用字段证据。');return {readOnly:true,processName:input.processName,nodeName:input.nodeName,processVersion:input.processVersion||'',processInstanceId:input.processInstanceId,fields,processSteps:structuredClone(input.processSteps)};
}
async function captureDetail({storageState,sessionStorage={},detailUrl,processName,nodeName,browserFactory=()=>loadPlaywright().chromium.launch(browserOptions()),timeout=20000}){
const identity=parseDetailUrl(detailUrl);if(!storageState)fail('BPM 会话需要续登。',401);if(processName&&identity.processName!==processName)fail('列表流程名称与详情表单不一致。');
const browser=await browserFactory();let context;
try{
context=await browser.newContext({storageState,serviceWorkers:'block',acceptDownloads:false,permissions:[]});const blocked=[];
await context.route('**/*',async route=>{try{const request=route.request();if(!allowDetailRequest(request.url(),request.method(),detailUrl,request.isNavigationRequest())){blocked.push({method:request.method(),path:new URL(request.url()).pathname});return await route.abort();}const response=await route.fetch({maxRedirects:0,timeout});if(response.status()>=300&&response.status()<400)return await route.abort();return await route.fulfill({response});}catch{await route.abort().catch(()=>{});}});
if(context.routeWebSocket)await context.routeWebSocket(/.*/,socket=>socket.close());
await context.addInitScript(({sessions})=>{for(const [key,value] of Object.entries(sessions[location.origin]||{}))sessionStorage.setItem(key,value);document.addEventListener('submit',event=>event.preventDefault(),true);},{sessions:sessionStorage});
const page=await context.newPage();page.on('dialog',dialog=>dialog.dismiss().catch(()=>{}));page.on('download',download=>download.cancel().catch(()=>{}));
const response=await page.goto(detailUrl,{waitUntil:'domcontentloaded',timeout});if(!response||response.status()!==200||page.url()!==new URL(detailUrl).href)fail('BPM 详情需要授权会话或页面未就绪。',401);
await page.locator('form [xdatabind]:visible,form [data-xdatabind]:visible').first().waitFor({state:'visible',timeout});
const raw=await page.evaluate(readDetailDocument),steps=raw.processSteps,current=[...new Set(steps.filter(step=>['处理中','running','active'].includes(step.status)).map(step=>step.name))];
if(current.length!==1||!nodeName||current[0]!==nodeName)fail('流程步骤未能唯一确认当前节点,详情采集已阻断。');
const detail=extractFieldSnapshot({...raw,processName:identity.processName,nodeName:current[0],processVersion:identity.processVersion,processInstanceId:identity.pid});
const capturedAt=new Date().toISOString(),evidenceHash=crypto.createHash('sha256').update(JSON.stringify(detail)).digest('hex');
return {...identity,detail:{...detail,tid:identity.tid,pid:identity.pid,capturedAt,evidenceHash},snapshot:raw.snapshot,capturedAt,evidenceHash,blockedRequests:blocked};
}catch(error){if(error.status)throw error;fail('BPM 详情读取未完成,可能需要登录或尚未批准页面所需的只读数据接口。',502);}finally{await context?.close().catch(()=>{});await browser.close().catch(()=>{});}
}
module.exports={parseDetailUrl,extractFieldSnapshot,captureDetail,allowDetailRequest,readDetailDocument};