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.
This commit is contained in:
abaishu0730 committed 2026-10-22 16:52:59 +08:00
1 parent 6e795a99b7
commit 94fc985553
38 files changed
+1204 -131

No files matched your search

+7 -4
View File
@@ -3,11 +3,12 @@ const sanitize=require('sanitize-html');
const {loadPlaywright}=require('./runtime.cjs');
const fail=(message,status=502)=>Object.assign(new Error(message),{status});
const SOURCES=[['portal-v8','bpm/worklist/informlist'],['portal-v4','skyworth/todo/v2/workflow/get_process_of_inform_v4']];
function plain(value,max=8000){
const text=sanitize(String(value??''),{allowedTags:[],allowedAttributes:{}}).replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|apos|nbsp);/gi,(m,key)=>{
function plain(value,max=8000,preserveLines=false){
const input=preserveLines?String(value??'').replace(/<br\s*\/?>/gi,'\n'):String(value??'');
const text=sanitize(input,{allowedTags:[],allowedAttributes:{}}).replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|apos|nbsp);/gi,(m,key)=>{
if(key[0]==='#'){const n=key[1].toLowerCase()==='x'?parseInt(key.slice(2),16):+key.slice(1);return n>0&&n<=0x10ffff?String.fromCodePoint(n):'';}
return {amp:'&',lt:'<',gt:'>',quot:'"',apos:"'",nbsp:' '}[key.toLowerCase()];
});return text.replace(/\s+/g,' ').trim().slice(0,max);
});return (preserveLines?text:text.replace(/\s+/g,' ').trim()).slice(0,max);
}
function normalizeArrival(row,source){
if(!row||typeof row!=='object'||!['string','number'].includes(typeof row.taskId)||!String(row.taskId)||String(row.taskId).length>200)throw fail('BPM 列表缺少有效的任务标识。');
@@ -18,7 +19,9 @@ function normalizeArrival(row,source){
const date=new Date(/(?:Z|[+-]\d{2}:\d{2})$/.test(raw)?raw:raw+'+08:00');
if(Number.isNaN(+date))throw fail('BPM 流程到达时间无效。');
const arrivedAt=date.toISOString(),arrivalDay=new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(date);
return {source,taskId:String(row.taskId),serialNum:plain(row.serialNum,250),processName:plain(row.processName,250),activityName:plain(row.activityName,250),subject:plain(row.processInstanceSubject),initiator:plain(row.processInstanceInitiatorShortName||row.processInstanceInitiator,250),arrivedAt,arrivalDay};
let detailUrl;if(typeof row.detailUrl==='string'){try{require('./bpm-order-detail.cjs').parseDetailUrl(row.detailUrl);detailUrl=row.detailUrl;}catch{}}
const identity={};for(const key of ['tid','pid'])if(['string','number'].includes(typeof row[key])&&/^\d{1,30}$/.test(String(row[key])))identity[key]=String(row[key]);
return {source,taskId:String(row.taskId),serialNum:plain(row.serialNum,250),processName:plain(row.processName,250),activityName:plain(row.activityName,250),subject:plain(row.processInstanceSubject,20000,true),initiator:plain(row.processInstanceInitiatorShortName||row.processInstanceInitiator,250),arrivedAt,arrivalDay,...identity,...(detailUrl?{detailUrl}:{})};
}
class BpmListClient{
constructor({baseURL='https://bpmn.skyworthdigital.com/',pageSize=100,allowLocal=false}={}){
+59
View File
@@ -0,0 +1,59 @@
'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};
+2
View File
@@ -22,6 +22,8 @@ class BpmScanStore{
fail(id,message){this.db.prepare('UPDATE runs SET status=?,finished_at=?,message=? WHERE id=?').run('error',new Date().toISOString(),message,id);this.prune();}
prune(){this.db.exec("DELETE FROM runs WHERE status!='running' AND id NOT IN(SELECT id FROM runs ORDER BY started_at DESC,rowid DESC LIMIT 200)");}
status(){return {config:this.config(),total:this.db.prepare('SELECT COUNT(*) n FROM arrivals').get().n,runs:this.db.prepare('SELECT id,connection_id AS connectionId,actor,started_at AS startedAt,finished_at AS finishedAt,status,seen,added,message FROM runs ORDER BY started_at DESC,rowid DESC LIMIT 30').all()};}
getArrival(connectionId,source,taskId){const row=this.db.prepare('SELECT connection_id AS connectionId,value,first_seen AS firstSeenAt FROM arrivals WHERE connection_id=? AND source=? AND task_id=?').get(connectionId,source,taskId);if(!row)return null;const {value,...metadata}=row;return {...JSON.parse(value),...metadata};}
recent({since='',limit=500}={}){return this.db.prepare('SELECT connection_id AS connectionId,value,first_seen AS firstSeenAt,last_seen AS lastSeenAt FROM arrivals WHERE first_seen>=? ORDER BY first_seen DESC,task_id LIMIT ?').all(since,limit).map(({value,...metadata})=>({...JSON.parse(value),...metadata}));}
list({connectionId='',q='',before='',days=7}={}){
if(typeof q!=='string'||q.length>200||typeof connectionId!=='string'||connectionId.length>200||typeof before!=='string'||(before&&!/^\d{4}-\d{2}-\d{2}$/.test(before))||!Number.isInteger(days)||days<1||days>31)throw invalid('查询条件无效。');
const conditions=[],args=[];if(connectionId){conditions.push('connection_id=?');args.push(connectionId);}if(q){conditions.push("value LIKE ? ESCAPE '\\'");args.push('%'+q.replace(/[\\%_]/g,'\\$&')+'%');}
+10
View File
@@ -175,6 +175,16 @@ class BpmSessionManager {
if(renewed.status!=='connected')throw error(renewed.checks?.portal?.message||'请在 BPM 连接中完成登录。',401);
return query();
}
async captureOrderDetail(connection,principal,arrival){
return this.run(connection?.id,async()=>{
this.authorize(connection,principal);
if(this.sessions.has(connection.id))throw error('此连接正在登录窗口中使用,请关闭后采集详情。',409);
const saved=await this.vault().read(connection.id);
const {captureDetail}=require('./bpm-order-detail.cjs');
const result=await captureDetail({storageState:saved?.storageState,sessionStorage:saved?.sessionStorage,detailUrl:arrival.detailUrl,processName:arrival.processName,nodeName:arrival.activityName});
this.authorize(connection,principal);return result;
});
}
authorize(connection, principal) {
if (!connection || typeof connection.id !== 'string' || !connection.id || connection.id.length > 200) throw error('连接标识无效。');
if (!principal?.sessionId || !principal.user || !['admin','operator'].includes(principal.user.role) || (principal.user.role !== 'admin' && connection.owner !== principal.user.username)) throw error('只有连接负责人或管理员可以操作。',403);
+3 -2
View File
@@ -14,7 +14,7 @@ const {SessionStore,SESSION_MS}=require('./dashboard-sessions.cjs');
const isLoopback=address=>['127.0.0.1','::1','::ffff:127.0.0.1'].includes(address);
const publicJob=({path:ignored,...job})=>({...job,downloadable:job.status==='success'});
function createDashboard({store,outputDir,workspace,previewUserId,bpmSessions,mail,scanner,storage,notifications,workflow,assistant,health,watchdog,trustedProxy=false}) {
function createDashboard({store,outputDir,workspace,previewUserId,bpmSessions,mail,scanner,storage,notifications,workflow,pipeline,assistant,health,watchdog,trustedProxy=false}) {
const sessions=new SessionStore(path.dirname(store.file));const failures=new Map();
const sessionCookieName=previewUserId?'order_preview_session':'order_session';
const sessionCookiePattern=new RegExp('(?:^|;\\s*)'+sessionCookieName+'=([a-f0-9]{64})(?:;|$)');
@@ -26,6 +26,7 @@ function createDashboard({store,outputDir,workspace,previewUserId,bpmSessions,ma
'/bpm.js':{path:path.join(webRoot,'bpm.js'),type:'text/javascript'},
'/mail.js':{path:path.join(webRoot,'mail.js'),type:'text/javascript'},
'/orders.js':{path:path.join(webRoot,'orders.js'),type:'text/javascript'},
'/order-workflow.js':{path:path.join(webRoot,'order-workflow.js'),type:'text/javascript'},
'/storage.js':{path:path.join(webRoot,'storage.js'),type:'text/javascript'},
'/storage-preview.html':{path:path.join(webRoot,'storage-preview.html'),type:'text/html',preview:true},
'/storage-preview.js':{path:path.join(webRoot,'storage-preview.js'),type:'text/javascript',preview:true},
@@ -104,7 +105,7 @@ function createDashboard({store,outputDir,workspace,previewUserId,bpmSessions,ma
if(await bpmScanApi({scanner,workspace,user,sessionId:token,url,route,method:request.method,body,reply}))return;
if(await storageApi({storage,workspace,user,url,route,method:request.method,body,request,response,reply,trustedProxy}))return;
if(await notificationApi({notifications,workspace,user,route,method:request.method,body,reply}))return;
if(await orderWorkflowApi({workflow,user,route,method:request.method,body,reply}))return;
if(await orderWorkflowApi({workflow,pipeline,workspace,user,sessionId:token,route,method:request.method,body,reply}))return;
if(await assistantApi({assistant,workspace,user,sessionId:token,route,method:request.method,body,request,reply,trustedProxy}))return;
if(workspaceApi({workspace,store,user,route,method:request.method,body,reply,bpmSessions}))return;
if(route==='/api/overview' && request.method==='GET') {
+7 -3
View File
@@ -18,6 +18,7 @@ class NotificationStore{
this.db.prepare('INSERT OR IGNORE INTO settings VALUES(1,?)').run(JSON.stringify({version:1,enabled:false,sourceKey:crypto.randomUUID(),sourceName:'业务来源',channelId:'',fieldMap:DEFAULT_MAP,maxAttempts:3}));
if(!this.db.prepare('PRAGMA table_info(items)').all().some(c=>c.name==='industry')){this.db.exec("ALTER TABLE items ADD COLUMN industry TEXT NOT NULL DEFAULT ''");for(const row of this.db.prepare('SELECT id,payload FROM items').all())this.db.prepare('UPDATE items SET industry=? WHERE id=?').run(this.decode(row.id,row.payload).industry,row.id);}
this.db.exec('CREATE INDEX IF NOT EXISTS notification_pending ON items(status,industry,attempts)');
if(!this.db.prepare('PRAGMA table_info(items)').all().some(c=>c.name==='owner'))this.db.exec("ALTER TABLE items ADD COLUMN owner TEXT NOT NULL DEFAULT 'generic'");
}
transaction(work){this.db.exec('BEGIN IMMEDIATE');try{const result=work();this.db.exec('COMMIT');return result;}catch(e){this.db.exec('ROLLBACK');throw e;}}
encode(id,data){try{return this.vault.encode(id,data);}catch{fail('通知内容加密不可用,请联系管理员。',503);}}
@@ -26,11 +27,12 @@ class NotificationStore{
saveSettings(input){const old=this.settings();if(!input||Object.keys(input).some(k=>!['version','enabled','sourceKey','sourceName','channelId','fieldMap','maxAttempts'].includes(k)))fail('通知配置无效。');if(input.version!==old.version)fail('通知配置已被修改,请刷新。',409);if(typeof input.enabled!=='boolean'||typeof input.sourceName!=='string'||!input.sourceName.trim()||input.sourceName.length>80||typeof input.channelId!=='string'||input.channelId.length>100||!Number.isInteger(input.maxAttempts)||input.maxAttempts<1||input.maxAttempts>10)fail('请检查来源、邮箱和尝试次数(1–10)。');if(input.sourceKey&&input.sourceKey!==old.sourceKey)fail('来源标识不能更改。');const saved={...input,sourceKey:old.sourceKey,sourceName:input.sourceName.trim(),fieldMap:validateMap(input.fieldMap),version:old.version+1};this.db.prepare('UPDATE settings SET value=? WHERE id=1').run(JSON.stringify(saved));return saved;}
scheduleState(){const row=this.db.prepare("SELECT value FROM metadata WHERE key='schedule'").get();return row?JSON.parse(row.value):null;}
setSchedule(value){this.db.prepare("INSERT INTO metadata VALUES('schedule',?) ON CONFLICT(key) DO UPDATE SET value=excluded.value").run(JSON.stringify(value));}
ingest(event){const id=hash([event.sourceKey,event.sourceId,event.sourceVersion,event.industry].join('\0')),old=this.db.prepare('SELECT * FROM items WHERE id=?').get(id);if(old){const value=this.decode(id,old.payload);if(value.brief!==event.brief||value.subject!==event.subject)fail('同一通知版本的内容已变化,请核实来源版本。',409);return this.item(old);}this.db.prepare('INSERT INTO items(id,payload,status,created_at,industry) VALUES(?,?,?,?,?)').run(id,this.encode(id,event),'pending',new Date().toISOString(),event.industry);return this.item(this.db.prepare('SELECT * FROM items WHERE id=?').get(id));}
ingest(event){const id=hash([event.sourceKey,event.sourceId,event.sourceVersion,event.industry].join('\0')),old=this.db.prepare('SELECT * FROM items WHERE id=?').get(id);if(old){const value=this.decode(id,old.payload);if(value.brief!==event.brief||value.subject!==event.subject)fail('同一通知版本的内容已变化,请核实来源版本。',409);return this.item(old);}this.db.prepare('INSERT INTO items(id,payload,status,created_at,industry,owner) VALUES(?,?,?,?,?,?)').run(id,this.encode(id,event),'pending',new Date().toISOString(),event.industry,event.owner==='order-workflow'?'order-workflow':'generic');return this.item(this.db.prepare('SELECT * FROM items WHERE id=?').get(id));}
item({payload,...row}){return {...this.decode(row.id,payload),...row};}
items(){return this.db.prepare('SELECT * FROM items ORDER BY rowid DESC LIMIT 100').all().map(r=>this.item(r));}
pending(attempts,industries){if(!industries.length)return [];return this.db.prepare("SELECT * FROM items WHERE status IN('pending','blocked') AND attempts<? AND industry IN("+industries.map(()=>'?').join(',')+") ORDER BY rowid LIMIT 200").all(attempts,...industries).map(r=>this.item(r));}
blockUnmapped(industries){this.db.prepare("UPDATE items SET status='blocked',error='此产业尚未配置接口人收件组。' WHERE status IN('pending','blocked')"+(industries.length?' AND industry NOT IN('+industries.map(()=>'?').join(',')+')':'')).run(...industries);}
pending(attempts,industries){if(!industries.length)return [];return this.db.prepare("SELECT * FROM items WHERE owner='generic' AND status IN('pending','blocked') AND attempts<? AND industry IN("+industries.map(()=>'?').join(',')+") ORDER BY rowid LIMIT 200").all(attempts,...industries).map(r=>this.item(r));}
blockUnmapped(industries){this.db.prepare("UPDATE items SET status='blocked',error='此产业尚未配置接口人收件组。' WHERE owner='generic' AND status IN('pending','blocked')"+(industries.length?' AND industry NOT IN('+industries.map(()=>'?').join(',')+')':'')).run(...industries);}
syncOrder(order){const id=hash(['order-workflow',order.versionKey,order.businessVersion,order.productLine].join('\0'));this.db.prepare("UPDATE items SET status=?,error=?,batch_id=? WHERE id=? AND owner='order-workflow'").run(order.notification?.status||order.status,order.notification?.error||null,order.notification?.batchId||null,id);}
block(id,message){this.db.prepare("UPDATE items SET status='blocked',error=? WHERE id=? AND status IN('pending','blocked')").run(message,id);}
prepare(items,snapshot){return this.transaction(()=>{const id=crypto.randomUUID();this.db.prepare('INSERT INTO batches VALUES(?,?,?,?,?)').run(id,'prepared',this.encode(id,snapshot),null,new Date().toISOString());for(const item of items){const result=this.db.prepare("UPDATE items SET status='reserved',attempts=attempts+1,error=NULL,batch_id=? WHERE id=? AND status IN('pending','blocked')").run(id,item.id);if(!result.changes)fail('通知队列已变化,请重试。',409);}return id;});}
mark(id,status,message=null){this.transaction(()=>{this.db.prepare('UPDATE batches SET status=?,error=? WHERE id=?').run(status,message,id);if(status!=='sending')this.db.prepare('UPDATE items SET status=?,error=? WHERE batch_id=?').run(status==='failed'?'pending':status,message,id);});}
@@ -43,6 +45,8 @@ class NotificationService{
map(data){if(!data||typeof data!=='object'||Array.isArray(data))fail('通知来源必须是 JSON 对象。');const config=this.store.settings(),raw=Object.fromEntries(Object.entries(config.fieldMap).map(([key,p])=>[key,valueAt(data,p)]));if(!['string','number'].includes(typeof raw.id)||!String(raw.id).trim()||String(raw.id).length>200||/[\x00-\x1f]/.test(String(raw.id))||typeof raw.industry!=='string'||!raw.industry.trim()||raw.industry.length>100||/[\x00-\x1f]/.test(raw.industry)||typeof raw.brief!=='string'||!raw.brief.trim()||raw.brief.length>20000)fail('通知 ID、产业和简要说明不能为空,正文最多 20000 字。');if(raw.subject!==undefined&&(typeof raw.subject!=='string'||raw.subject.length>300||/[\r\n\x00]/.test(raw.subject)))fail('通知标题最多 300 字,不能包含换行。');if(raw.version!==undefined&&(!['string','number'].includes(typeof raw.version)||String(raw.version).length>200||/[\x00-\x1f]/.test(String(raw.version))))fail('来源版本无效。');if(raw.occurredAt!==undefined&&(typeof raw.occurredAt!=='string'||!Number.isFinite(Date.parse(raw.occurredAt))))fail('业务时间无效。');return {source:config.sourceName,sourceKey:config.sourceKey,sourceId:String(raw.id).trim(),sourceVersion:raw.version===undefined||raw.version===''?hash(raw.brief):String(raw.version),industry:raw.industry.trim(),brief:raw.brief,subject:raw.subject||raw.industry.trim()+'业务通知',occurredAt:raw.occurredAt||this.clock().toISOString()};}
preview(data){try{const event=this.map(data),group=this.settings().groups.find(g=>g.productLine===event.industry);return {valid:!!group,event,to:group?.to||[],cc:group?.cc||[],issues:group?[]:['此产业尚未配置接口人收件组。']};}catch(e){if(!e.status)throw e;return {valid:false,issues:[e.message]};}}
ingest(data){return this.store.ingest(this.map(data));}
ingestOrder(order){if(order?.steps?.archive?.status!=='success'||!order.archive?.archiveId||!order.versionKey||!order.businessVersion||!order.templateId||!order.ruleId||!order.productLine||!order.brief)fail('订单通知必须有成功归档及已确认的订单版本证据。',409);return this.store.ingest({owner:'order-workflow',source:order.source,sourceKey:'order-workflow',sourceId:order.versionKey,sourceVersion:order.businessVersion,industry:order.productLine,brief:order.brief,subject:order.subject,occurredAt:order.businessTime,orderVersionKey:order.versionKey,ruleId:order.ruleId,templateId:order.templateId});}
syncOrder(order){this.store.syncOrder(order);}
saveSettings(input){if(this.running)fail('通知正在发送,请稍后修改配置。',409);if(input?.enabled){const c=this.mail.store.publicChannel(input.channelId);if(!c.state.smtp)fail('请先验证发件邮箱的 SMTP 连接。',409);if(!this.settings().groups.length)fail('请先配置产业接口人收件组。',409);}const old=this.store.settings(),saved=this.store.saveSettings(input);if(saved.enabled&&!old.enabled)this.resetSchedule(this.clock());return saved;}
resetSchedule(now){const schedule=this.settings().schedule,calendar=this.calendar();const state={signature:JSON.stringify([schedule,calendar]),next:nextSlots(schedule,now,1,calendar)[0]};this.store.setSchedule(state);return state;}
tick(now=this.clock()){
+201
View File
@@ -0,0 +1,201 @@
'use strict';
const crypto=require('node:crypto');
const {renderSnapshot}=require('./exporter.cjs');
const {nextSlots,dayPolicy}=require('./schedule.cjs');
const {parseDetailUrl}=require('./bpm-order-detail.cjs');
const {OrderWorkflow}=require('./order-workflow.cjs');
const TEST_RECIPIENT='2639266652@qq.com';
const fail=(message,status=409)=>Object.assign(new Error(message),{status});
const idFor=arrival=>crypto.createHash('sha256').update(JSON.stringify([arrival.connectionId,arrival.source,arrival.taskId])).digest('hex');
const DEFAULTS={version:1,enabled:false,sendEnabled:false,channelId:'',serverId:'',since:null,maxAttempts:3};
function latestElapsedSlot(now,schedule,calendar){
const shifted=new Date(+now+8*3600000),midnight=Date.UTC(shifted.getUTCFullYear(),shifted.getUTCMonth(),shifted.getUTCDate());
for(let offset=0;offset<370;offset++){
const day=midnight-offset*86400000;if(!dayPolicy(new Date(day).toISOString().slice(0,10),schedule,calendar).send)continue;
for(const time of [...schedule.times].sort().reverse()){const [hour,minute]=time.split(':').map(Number),slot=day+(hour*60+minute)*60000-8*3600000;if(slot<=+now)return slot;}
}
return null;
}
class OrderPipeline{
constructor({workflow,store,scanStore,workspace,manager,jobs,storage,mail,notifications,settings,calendar=()=>[],outputDir,render=renderSnapshot,clock=()=>new Date()}){
Object.assign(this,{workflow,store,scanStore,workspace,manager,jobs,storage,mail,notifications,settings,calendar,outputDir,render,clock});this.pending=new Map();this.stopped=false;this.sending=null;this.principal={sessionId:'order-pipeline:'+crypto.randomUUID(),user:{username:'订单任务',role:'admin'}};
}
config(){return {...DEFAULTS,...this.store.meta('config',{})};}
saveConfig(input){
const old=this.config();if(!input||Object.keys(input).some(key=>!Object.hasOwn(DEFAULTS,key))||input.version!==old.version)throw fail('订单运行配置已变化或包含无效参数。');
if(typeof input.enabled!=='boolean'||typeof input.sendEnabled!=='boolean'||!Number.isInteger(input.maxAttempts)||input.maxAttempts<1||input.maxAttempts>10||typeof input.channelId!=='string'||typeof input.serverId!=='string')throw fail('订单运行配置无效。');
if(this.pending.size||this.sending)throw fail('订单任务正在运行,请稍后修改配置。');
if(input.enabled){if(!this.workflow.rules().some(rule=>rule.enabled&&rule.status==='published'))throw fail('请先通过真实只读样本检查并发布分类规则。');if(!input.serverId)throw fail('请选择归档服务器。');const server=this.storage.store.publicServer(input.serverId);if(!server.enabled||!server.state.writable)throw fail('归档服务器未启用或未通过读写检查。');}
if(input.sendEnabled){if(!input.enabled||!input.channelId)throw fail('请先启用订单处理并指定发件邮箱。');const channel=this.mail.store.publicChannel(input.channelId);if(!channel.state.smtp)throw fail('请先验证 SMTP。');for(const group of this.settings().groups)this.assertRecipients(group);}
const saved={...input,version:old.version+1,since:input.enabled?(old.enabled?old.since:this.clock().toISOString()):old.since};this.store.setMeta('config',saved);this.store.setMeta('schedule',null);return saved;
}
assertRecipients(group){if(!Array.isArray(group?.to)||!group.to.length||!Array.isArray(group.cc)||[...group.to,...group.cc].some(address=>typeof address!=='string'||address.toLowerCase()!==TEST_RECIPIENT))throw fail('受限测试期间 To/Cc 只允许隔离测试邮箱。');}
authorize(arrival,principal){const connection=this.workspace.getConnection(arrival.connectionId);if(connection.status==='disabled'||!principal?.sessionId||!['admin','operator'].includes(principal.user?.role)||(principal.user.role!=='admin'&&connection.owner!==principal.user.username))throw fail('只有连接负责人或管理员可以读取和处理此订单。',403);return connection;}
arrivals(){return this.store.candidates();}
options(){return {templates:this.mail.store.templates(),groups:this.settings().groups,connections:this.workspace.snapshot?.().connections?.map(({id,name})=>({id,name}))||[],adapters:{}};}
async checkRule(ruleId,input,principal){
const arrival=this.scanStore.getArrival(input.connectionId,input.source,input.taskId);if(!arrival)throw fail('所选 BPM 到达记录不存在。',404);this.authorize(arrival,principal);
this.workflow.invalidateCheck(ruleId);
if(input.detailUrl){
const provided=parseDetailUrl(input.detailUrl),stored=arrival.detailUrl?parseDetailUrl(arrival.detailUrl):null;
if(stored?(provided.tid!==stored.tid||provided.pid!==stored.pid||provided.processVersion!==stored.processVersion||provided.processName!==stored.processName):(String(arrival.tid||'')!==provided.tid||String(arrival.pid||'')!==provided.pid||provided.processName!==arrival.processName))throw fail('详情链接与到达记录缺少同一订单的关联证据,请重新扫描带有明确 tid/pid 的记录。');
arrival.detailUrl=input.detailUrl;
}
if(!arrival.detailUrl)throw fail('到达记录没有真实详情链接,请提供该订单的 BPM 详情链接;不能猜测 tid/pid。');
const captured=await this.manager.captureOrderDetail(this.workspace.getConnection(arrival.connectionId),principal,arrival);
const result=this.workflow.checkRule(ruleId,{arrival,detail:captured.detail,provenance:'bpm-readonly'});
if(result.valid)this.store.setMeta('check:'+result.checkId,{ruleId,version:result.version,arrivalKey:idFor(arrival),evidenceHash:result.evidenceHash});
return result;
}
publishRule(id,input){
const check=this.store.meta('check:'+input.checkId);if(!check||check.ruleId!==id||check.version!==input.version)throw fail('缺少当前规则的服务器样本检查证据。');
const rule=this.workflow.getRule(id),template=this.mail.store.template(rule.templateId);if(template.status!=='active')throw fail('分类绑定模板尚未确认生效。');if(rule.pdfTemplateId!=='bpm-snapshot-v1')throw fail('不支持此 PDF 模板。');
const group=this.settings().groups.find(group=>group.productLine===(rule.recipientGroupId||rule.productLine));this.assertRecipients(group);
return this.workflow.publishRule(id,input);
}
async process(arrival,principal=this.principal){
const id=idFor(arrival);if(this.pending.has(id))return this.pending.get(id);if(this.stopped)throw fail('订单服务正在停止。');
const task=this.processOne(arrival,principal).finally(()=>this.pending.delete(id));this.pending.set(id,task);return task;
}
async processOne(arrival,principal){
const candidate={id:idFor(arrival),...structuredClone(arrival),status:'capturing',ruleRevision:this.workflow.rules().map(rule=>[rule.id,rule.version,rule.status]),updatedAt:this.clock().toISOString()};let order;
try{
const connection=this.authorize(arrival,principal);this.store.putCandidate(candidate);
if(!arrival.detailUrl)throw fail('缺少已核实的 BPM 详情链接。');
const capture=await this.manager.captureOrderDetail(connection,principal,arrival);
const identified=this.workflow.identify({arrival,detail:capture.detail});order=identified.order;
if(identified.status==='duplicate'){
if(['archive_error','pdf_error','notification_error','interrupted'].includes(order.status)){
order=order.steps.archive?.status==='success'?this.workflow.update(order.versionKey,draft=>{draft.status='archived';}):this.workflow.start(order.versionKey);
if(order.status==='detail_capturing')order=this.workflow.markDetailReady(order.versionKey,{capturedAt:capture.capturedAt,evidenceHash:capture.evidenceHash});
candidate.orderVersionKey=order.versionKey;candidate.snapshot=capture.snapshot;this.store.putCandidate(candidate);return await this.execute(order,capture.snapshot,principal,candidate);
}
if(['identified','detail_ready','pdf_success','archived'].includes(order.status)){
if(order.status==='identified'){this.workflow.start(order.versionKey);order=this.workflow.markDetailReady(order.versionKey,{capturedAt:capture.capturedAt,evidenceHash:capture.evidenceHash});}
candidate.orderVersionKey=order.versionKey;candidate.snapshot=capture.snapshot;this.store.putCandidate(candidate);return await this.execute(order,capture.snapshot,principal,candidate);
}
candidate.status='duplicate';candidate.orderVersionKey=order.versionKey;this.store.putCandidate(candidate);return order;
}
candidate.orderVersionKey=order.versionKey;candidate.snapshot=capture.snapshot;this.store.putCandidate(candidate);
order=this.workflow.start(order.versionKey);order=this.workflow.markDetailReady(order.versionKey,{capturedAt:capture.capturedAt,evidenceHash:capture.evidenceHash||capture.detail.evidenceHash});
return await this.execute(order,capture.snapshot,principal,candidate);
}catch(error){candidate.status='blocked';candidate.error=error.status?error.message:'详情或规则读取失败,请检查连接和采集记录。';candidate.code=error.code||'DETAIL_FAILED';this.store.putCandidate(candidate);return {status:'blocked',candidate};}
}
async execute(input,snapshot,principal,candidate){
let order=input;
try{
if(order.steps.pdf?.status!=='success'){
const jobId='order-'+order.versionKey,existing=this.jobs.jobs().find(job=>job.jobId===jobId);
if(existing?.status==='success'){order=this.workflow.markPdfSuccess(order.versionKey,{jobId,...existing});}
else{
if(existing&&['running','interrupted'].includes(existing.status))throw fail('上次 PDF 结果未确认,请核查输出记录,禁止重复生成。');
if(!snapshot)throw fail('缺少已采集的 PDF 快照。');
order=this.workflow.beginPdf(order.versionKey);
const field=order.sources.orderNo.path.replace(/^detail\./,'');
const pdfSnapshot={...snapshot,metadata:{order:order.orderNo,project:order.productCode,model:order.modelShort,serial:order.serialNo},...(/^OFR_(?:LSCP|BS|KD|WY)_Applicant\.OrderNum$/.test(field)?{bpmOrder:{field,value:order.orderNo}}:{})};
this.jobs.recordJob({jobId,status:'running',metadata:pdfSnapshot.metadata,orderVersionKey:order.versionKey});
let result;try{result=await this.render(pdfSnapshot,{outputDir:this.outputDir});}catch(error){this.jobs.recordJob({jobId,status:'error',error:'订单 PDF 生成失败。'});throw error;}
this.jobs.recordJob({jobId,status:'success',...result,metadata:pdfSnapshot.metadata,orderVersionKey:order.versionKey,...(pdfSnapshot.bpmOrder?{bpmOrder:pdfSnapshot.bpmOrder}:{})});order=this.workflow.markPdfSuccess(order.versionKey,{jobId,...result});
}
}
if(order.steps.archive?.status!=='success'){
const serverId=this.config().serverId||this.storage.store.settings().serverId;if(!serverId)throw fail('尚未指定归档服务器。');
order=this.workflow.beginArchive(order.versionKey);
const receipt=await this.storage.archive(serverId,order.pdf.jobId,'',principal.user.username);
if(!receipt?.id||!receipt.sha256||!receipt.bytes||!receipt.relativePath)throw fail('归档服务没有返回完整文件校验回执。');
order=this.workflow.markArchiveSuccess(order.versionKey,{archiveId:receipt.id,serverId,path:receipt.relativePath,bytes:receipt.bytes,sha256:receipt.sha256});
}
if(!order.notification){const event=this.notifications?.ingestOrder(order);order=this.workflow.createNotification(order.versionKey);if(event)order=this.workflow.update(order.versionKey,draft=>{draft.notification.eventId=event.id;});}
candidate.status='processed';candidate.orderVersionKey=order.versionKey;delete candidate.snapshot;delete candidate.error;this.store.putCandidate(candidate);return order;
}catch(error){
const current=this.workflow.get(order.versionKey),message=error.status?error.message:current.steps.archive?.status==='success'?'归档已成功,通知入队失败。':current.steps.pdf?.status==='success'?'SMB 归档失败,通知已阻断。':'PDF 未完成,通知已阻断。';
if(current.steps.pdf?.status==='success'&&current.steps.archive?.status!=='success')this.workflow.markArchiveError(order.versionKey,message);else if(current.steps.pdf?.status!=='success')this.workflow.markPdfError(order.versionKey,message);
if(current.steps.archive?.status==='success')this.workflow.update(order.versionKey,draft=>{draft.status='notification_error';draft.error=message;draft.steps.notification={status:'error',error:message};});
candidate.status='error';candidate.error=message;candidate.orderVersionKey=order.versionKey;this.store.putCandidate(candidate);return this.workflow.get(order.versionKey);
}
}
async retry(key,principal){
const order=this.workflow.get(key);if(!order)throw fail('订单版本不存在。',404);this.authorize(order.arrival,principal);
const candidate=this.arrivals().find(row=>row.orderVersionKey===key)||{id:idFor(order.arrival),...structuredClone(order.arrival),orderVersionKey:key,status:'recovering'};
if(this.pending.has(candidate.id))throw fail('订单任务正在运行。');if(!['archive_error','pdf_error','detail_error','notification_error','interrupted'].includes(order.status))throw fail('只能重试明确失败或中断的步骤。');
const task=(async()=>{
if(!candidate.snapshot&&order.steps.pdf?.status!=='success'){
const capture=await this.manager.captureOrderDetail(this.workspace.getConnection(order.arrival.connectionId),principal,order.arrival);
const preview=new OrderWorkflow({clock:this.clock}).identify({arrival:order.arrival,detail:capture.detail,rule:order.ruleSnapshot,mapping:order.ruleSnapshot.adapters[capture.detail.processVersion]});
if(preview.order.versionKey!==key||JSON.stringify(preview.order.sources)!==JSON.stringify(order.sources)||JSON.stringify(preview.order.detailSnapshot.fields)!==JSON.stringify(order.detailSnapshot.fields))throw fail('恢复采集的业务版本或字段已变化,原任务不能使用新内容的 PDF。');
candidate.snapshot=capture.snapshot;this.store.putCandidate(candidate);
}
let current=order.status==='notification_error'||order.steps.archive?.status==='success'?this.workflow.update(key,draft=>{draft.status='archived';}):this.workflow.start(key);if(current.status==='detail_capturing')current=this.workflow.markDetailReady(key,order.detailEvidence||{});return this.execute(current,candidate.snapshot,principal,candidate);
})().finally(()=>this.pending.delete(candidate.id));this.pending.set(candidate.id,task);return task;
}
async retryArrival(id,principal){
const candidate=this.arrivals().find(row=>row.id===id);if(!candidate)throw fail('候选记录不存在。',404);this.authorize(candidate,principal);
if(candidate.orderVersionKey)return this.retry(candidate.orderVersionKey,principal);
if(!['blocked','error'].includes(candidate.status))throw fail('只能重试失败或阻断的候选记录。');
const arrival=this.scanStore.getArrival(candidate.connectionId,candidate.source,candidate.taskId);if(!arrival)throw fail('原始 BPM 到达记录不存在。');return this.process(arrival,principal);
}
async tick(){
if(this.stopped||this.ticking)return;this.ticking=this.perform().finally(()=>{this.ticking=null;});return this.ticking;
}
async perform(){
const config=this.config();if(!config.enabled)return;const seen=new Map(this.arrivals().map(row=>[row.id,row]));
if(dayPolicy(this.clock(),this.settings().schedule,this.calendar()).scan)for(const arrival of this.scanStore.recent({since:config.since||this.clock().toISOString(),limit:10000})){
if(this.stopped)break;if(!Number.isFinite(Date.parse(arrival.arrivedAt))||Date.parse(arrival.arrivedAt)<Date.parse(config.since))continue;const old=seen.get(idFor(arrival)),revision=JSON.stringify(this.workflow.rules().map(rule=>[rule.id,rule.version,rule.status]));
const changed=!old||JSON.stringify(old.ruleRevision)!==revision||old.lastSeenAt!==arrival.lastSeenAt||old.arrivedAt!==arrival.arrivedAt||old.subject!==arrival.subject;
if(changed&&this.workflow.rules().some(rule=>rule.enabled&&rule.status==='published'&&rule.processName===arrival.processName&&rule.nodeName===arrival.activityName))await this.process(arrival);
}
for(const order of this.workflow.listOrders().filter(order=>order.status==='interrupted')){if(this.stopped)break;try{await this.retry(order.versionKey,this.principal);}catch{}}
if(config.sendEnabled)await this.sendDue();
for(const order of this.workflow.listOrders())if(order.notification)this.notifications?.syncOrder(order);
}
start(){if(!this.timer){this.timer=setInterval(()=>this.tick().catch(()=>{}),15000);this.timer.unref?.();}}
async stop(){this.stopped=true;clearInterval(this.timer);await this.ticking;await Promise.allSettled([...this.pending.values()]);if(this.sending)await this.sending;}
resetSchedule(now=this.clock()){
const schedule=this.settings().schedule,calendar=this.calendar(),state={signature:JSON.stringify([schedule,calendar]),next:nextSlots(schedule,now,1,calendar)[0]};this.store.setMeta('schedule',state);return state;
}
async sendDue(){
if(this.stopped||this.sending||!this.config().sendEnabled)return;
this.sending=this.performSend().finally(()=>{this.sending=null;});return this.sending;
}
async performSend(){
const now=this.clock(),config=this.config(),settings=this.settings(),calendar=this.calendar(),signature=JSON.stringify([settings.schedule,calendar]),state=this.store.meta('schedule');
if(!config.enabled||!config.sendEnabled)return;
if(!state||state.signature!==signature){this.resetSchedule(now);return;}
if(!state.next||Date.parse(state.next)>+now)return;
const due=Date.parse(state.next);
// A late service does not retroactively execute a send window. Pending events
// remain for next_window; skip explicitly retains an operator-visible record.
if(+now-due>60000){
const lastDue=latestElapsedSlot(now,settings.schedule,calendar)||due;
if(settings.schedule.missed==='skip')for(const order of this.workflow.listOrders().filter(order=>['notification_pending','blocked'].includes(order.status)&&order.notification&&Date.parse(order.businessTime)<=lastDue))this.workflow.update(order.versionKey,draft=>{draft.status='skipped';draft.notification.status='skipped';draft.notification.error='服务错过发送窗口,等待人工处理。';draft.steps.notification={status:'skipped',error:draft.notification.error};});
this.resetSchedule(now);
return;
}
if(!dayPolicy(now,settings.schedule,calendar).send){this.resetSchedule(now);return;}
const groups={};for(const group of settings.groups){try{this.assertRecipients(group);groups[group.productLine]=group;}catch{}}
const templates={};for(const template of this.mail.store.templates().filter(template=>template.status==='active'))templates[template.id]=this.mail.store.template(template.id);
try{this.workflow.freezeBatches(new Date(due).toISOString(),{groups,templates});}catch(error){if(error.code!=='EMPTY_BATCH')throw error;}
const pending=this.workflow.listBatches().filter(batch=>['prepared','failed'].includes(batch.status)&&(batch.attempts||0)<config.maxAttempts);
if(!pending.length){this.resetSchedule(now);return;}
await this.mail.exclusive(config.channelId,async()=>{
this.resetSchedule(now);
for(const batch of pending){
if(this.stopped||!this.config().sendEnabled)break;let transport,sending=false;
try{
this.assertRecipients(batch);if(batch.attachments?.length)throw fail('订单邮件附件必须为空。');
const channel=this.mail.store.channelSecret(config.channelId);transport=this.mail.smtpFactory(channel.smtp);await transport.verify();this.mail.store.guard(channel.id,channel.version);
this.assertRecipients(batch);this.workflow.markBatchSending(batch.id);sending=true;
const receipt=await transport.sendMail({from:{address:channel.email,name:channel.name},to:batch.to,cc:batch.cc,subject:batch.subject,text:batch.text,html:batch.html,attachments:[],messageId:`<${batch.id}@${channel.email.split('@')[1]}>`,disableFileAccess:true,disableUrlAccess:true});
const accepted=new Set((receipt.accepted||[]).map(address=>String(address.address||address).toLowerCase()));
if(receipt.rejected?.length||[...batch.to,...batch.cc].some(address=>!accepted.has(address.toLowerCase())))this.workflow.markBatchUnknown(batch.id,'部分收件人未被 SMTP 接受,必须人工核验,禁止自动重发。');
else this.workflow.markBatchSent(batch.id);
}catch{
if(sending)this.workflow.markBatchUnknown(batch.id,'SMTP 发送结果不明,必须人工核验,禁止自动重发。');
else this.workflow.markBatchFailed(batch.id,'SMTP 检查失败或隔离收件人校验失败;达到上限后需人工处理。');
}finally{transport?.close?.();}
}
}).catch(error=>{if(error.status!==409)throw error;});
}
}
module.exports={OrderPipeline,TEST_RECIPIENT};
+18
View File
@@ -0,0 +1,18 @@
'use strict';
const {renderTemplate}=require('./mail-parser.cjs');
const fail=(message)=>{throw Object.assign(new Error(message),{status:409});};
function buildTemplateValues({productLine,orders,date}){
if(typeof productLine!=='string'||!productLine.trim())fail('分类规则没有产品线。');
if(!Array.isArray(orders)||!orders.length)fail('模板批次没有订单。');
if(typeof date!=='string'||!date.trim())fail('模板批次没有业务日期。');
const orderNumbers=orders.map(order=>String(order.orderNo||'').trim());if(orderNumbers.some(value=>!value))fail('模板批次存在缺少订单号的订单。');
const orderList=orders.map(order=>String(order.brief||'')).join('\n\n');if(!orderList.trim())fail('模板批次没有简要说明原文。');
return {'产品线':productLine.trim(),'订单号':orderNumbers.join('、'),'日期':date.trim(),'订单列表':orderList};
}
function renderOrderTemplate(template,input){
if(!template||typeof template.id!=='string'||!Number.isInteger(template.version))fail('分类模板快照无效。');
if(Array.isArray(template.attachments)&&template.attachments.length)fail('业务通知模板不能包含 PDF 或其他附件。');
const values=buildTemplateValues(input),rendered=renderTemplate({...template,attachments:[]},values);
return {...rendered,templateId:template.id,templateVersion:template.version,attachments:[]};
}
module.exports={buildTemplateValues,renderOrderTemplate};
+31 -20
View File
@@ -1,29 +1,40 @@
'use strict';
const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
const keys=(body,allowed)=>{if(!body||typeof body!=='object'||Object.keys(body).some(key=>!allowed.includes(key)))fail('订单流程参数无效。');};
async function orderWorkflowApi({workflow,user,route,method,body,reply}){
if(!route.startsWith('/api/order-workflow'))return false;
const keys=(body,allowed)=>{if(!body||typeof body!=='object'||Array.isArray(body)||Object.keys(body).some(key=>!allowed.includes(key)))fail('订单流程参数无效。');};
async function orderWorkflowApi({workflow,pipeline,workspace,user,sessionId,route,method,body,reply}){
if(!/^\/api\/order-workflow(?:\/|$)/.test(route))return false;
if(!workflow)fail('订单流程服务未启动。',503);
if(route==='/api/order-workflow'&&method==='GET'){reply(200,{orders:workflow.listOrders(),batches:workflow.listBatches()});return true;}
if(user?.role==='viewer')fail('只读成员不能操作订单流程。',403);
const admin=()=>{if(user?.role!=='admin')fail('仅管理员可以维护分类规则或核验发信结果。',403);};
const service=()=>{if(!pipeline)fail('订单任务执行服务未启动。',503);return pipeline;};
const audit=(action,detail)=>workspace?.record(user,action,detail);
if(route==='/api/order-workflow'&&method==='GET'){const candidates=pipeline?.arrivals().map(({snapshot,...value})=>value)||[],arrivals=pipeline?.scanStore?.recent?.()||[];reply(200,{orders:workflow.listOrders(),batches:workflow.listBatches(),arrivals,blockedArrivals:candidates,settings:pipeline?.config()||{enabled:false,sendEnabled:false}});return true;}
if(route==='/api/order-workflow/rules'&&method==='GET'){reply(200,{rules:workflow.rules()});return true;}
if(route==='/api/order-workflow/options'&&method==='GET'){reply(200,service().options());return true;}
const orderRoute=/^\/api\/order-workflow\/order\/([^/]+)$/.exec(route);
if(orderRoute&&method==='GET'){const order=workflow.get(decodeURIComponent(orderRoute[1]));if(!order)fail('订单版本不存在。',404);reply(200,order);return true;}
if(user?.role==='viewer'||!['admin','operator'].includes(user?.role))fail('只读成员不能操作订单流程。',403);
if(method!=='POST')fail('没有找到此订单流程操作。',404);
if(route==='/api/order-workflow/identify'){
keys(body,['provenance','arrival','detail','mapping','rule']);if(body.provenance!=='bpm-readonly')fail('订单详情必须来自授权 BPM 只读采集。',409);
const result=workflow.identify(body);reply(200,result);return true;
if(route==='/api/order-workflow/rules'){
admin();keys(body,['id','version','enabled','processName','nodeName','productLine','templateId','pdfTemplateId','notificationType','batchMode','recipientGroup','recipientGroupId','adapters']);
if(Object.hasOwn(body,'recipientGroup'))fail('请绑定已保存的收件组,不能在分类中注入邮箱地址。');
const result=workflow.saveRule(body);audit('保存分类规则草稿',result.id);reply(200,result);return true;
}
const step=/^\/api\/order-workflow\/orders\/([^/]+)\/(start|detail-ready|pdf-success|pdf-error|archive-success|archive-error|notification)$/.exec(route);
if(step){const id=decodeURIComponent(step[1]);const action=step[2];let result;
if(action==='start'){keys(body,[]);result=workflow.start(id);}
else if(action==='detail-ready'){keys(body,['evidence']);result=workflow.markDetailReady(id,body.evidence||{});}
else if(action==='pdf-success'){keys(body,['jobId']);result=workflow.markPdfSuccess(id,{jobId:body.jobId});}
else if(action==='pdf-error'){keys(body,['message']);result=workflow.markPdfError(id,body.message);}
else if(action==='archive-success'){keys(body,['archiveId','path']);result=workflow.markArchiveSuccess(id,{archiveId:body.archiveId,path:body.path});}
else if(action==='archive-error'){keys(body,['message']);result=workflow.markArchiveError(id,body.message);}
else {keys(body,['productLine','brief','subject','occurredAt']);result=workflow.createNotification(id,body);}
const ruleAction=/^\/api\/order-workflow\/rules\/([^/]+)\/(check|publish)$/.exec(route);
if(ruleAction){
admin();const id=decodeURIComponent(ruleAction[1]);let result;
if(ruleAction[2]==='check'){keys(body,['connectionId','source','taskId','detailUrl']);result=await service().checkRule(id,body,{user,sessionId});audit('只读检查分类规则样本',id);}
else{keys(body,['version','checkId']);result=service().publishRule(id,body);audit('发布分类规则',id);}
reply(200,result);return true;
}
const batch=/^\/api\/order-workflow\/batches\/([^/]+)\/(freeze|unknown|retry)$/.exec(route);
if(batch){const id=decodeURIComponent(batch[1]);if(batch[2]==='freeze'){keys(body,['cutoff','mode','groups']);reply(200,workflow.freezeBatch(body.cutoff,{mode:body.mode,groups:body.groups}));return true;}if(batch[2]==='unknown'){keys(body,['message']);reply(200,workflow.markBatchUnknown(id,body.message));return true;}if(!workflow.canAutoRetry(id))fail('结果不明批次必须先人工核验,不能自动重发。',409);reply(200,{ok:true});return true;}
fail('没有找到此订单流程操作。',404);
if(route==='/api/order-workflow/settings'){admin();const result=service().saveConfig(body);audit('保存订单任务运行设置',result.enabled?'启用':'暂停');reply(200,result);return true;}
const retry=/^\/api\/order-workflow\/orders\/([^/]+)\/retry$/.exec(route);
if(retry){keys(body,[]);const id=decodeURIComponent(retry[1]);reply(200,await service().retry(id,{user,sessionId}));audit('重试失败订单步骤',id);return true;}
const retryArrival=/^\/api\/order-workflow\/arrivals\/([^/]+)\/retry$/.exec(route);
if(retryArrival){keys(body,[]);const id=decodeURIComponent(retryArrival[1]);reply(200,await service().retryArrival(id,{user,sessionId}));audit('重试候选订单采集',id);return true;}
const resolve=/^\/api\/order-workflow\/batches\/([^/]+)\/resolve$/.exec(route);
if(resolve){admin();keys(body,['resolution','note']);if(pipeline?.sending)fail('邮件发送中,请稍后核验。',409);const id=decodeURIComponent(resolve[1]);reply(200,workflow.resolveBatch(id,body,user.username));audit('核验订单邮件发送结果',id);return true;}
// Execution evidence is generated by server services. An HTTP provenance label
// or a caller-supplied job/archive ID never establishes a successful step.
fail('该订单流程操作不接受客户端执行证据。',409);
}
module.exports={orderWorkflowApi};
+21 -2
View File
@@ -2,16 +2,35 @@
const fs=require('node:fs');const path=require('node:path');const {DatabaseSync}=require('node:sqlite');const {BpmVault}=require('./bpm-vault.cjs');
const fail=(message,status=409)=>Object.assign(new Error(message),{status});
class OrderWorkflowStore{
constructor(dir){this.dir=path.resolve(dir);fs.mkdirSync(this.dir,{recursive:true});this.vault=new BpmVault({stateDir:path.join(this.dir,'secrets')});this.db=new DatabaseSync(path.join(this.dir,'workflow.sqlite'));this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA secure_delete=ON;
constructor(dir,{vault=null}={}){this.dir=path.resolve(dir);fs.mkdirSync(this.dir,{recursive:true});this.vault=vault||new BpmVault({stateDir:path.join(this.dir,'secrets')});this.db=new DatabaseSync(path.join(this.dir,'workflow.sqlite'));this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA secure_delete=ON;
CREATE TABLE IF NOT EXISTS orders(version_key TEXT PRIMARY KEY,order_no TEXT NOT NULL,status TEXT NOT NULL,payload BLOB NOT NULL,updated_at TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS batches(id TEXT PRIMARY KEY,status TEXT NOT NULL,payload BLOB NOT NULL,updated_at TEXT NOT NULL);`);for(const row of this.db.prepare("SELECT id,payload FROM batches WHERE status='sending'").all()){const batch=this.vault.decode('batch:'+row.id,row.payload);batch.status='unknown';batch.error='服务重启,发送结果需要核实。';this.putBatch(batch);}}
CREATE TABLE IF NOT EXISTS batches(id TEXT PRIMARY KEY,status TEXT NOT NULL,payload BLOB NOT NULL,updated_at TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS rules(id TEXT PRIMARY KEY,payload BLOB NOT NULL,updated_at TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS candidates(id TEXT PRIMARY KEY,payload BLOB NOT NULL,updated_at TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS metadata(key TEXT PRIMARY KEY,value TEXT NOT NULL);`);
for(const row of this.db.prepare("SELECT id,payload FROM batches WHERE status IN('sending','unknown')").all()){
const batch=this.vault.decode('batch:'+row.id,row.payload);batch.status='unknown';batch.error||='服务重启,发送结果需要核实。';
const orders=(batch.orderVersionKeys||[]).map(key=>this.getOrder(key)).filter(Boolean);
for(const order of orders){order.status='unknown';order.notification={...order.notification,status:'unknown',batchId:batch.id};order.steps={...order.steps,notification:{status:'unknown',batchId:batch.id,error:batch.error}};}
this.putGraph(orders,[batch]);
}
for(const order of this.orders())if(['identified','detail_capturing','detail_ready','pdf_pending','pdf_success','archive_pending','archived'].includes(order.status)){order.status='interrupted';order.error='服务重启,恢复时检查已完成步骤。';this.putOrder(order);}
}
now(){return new Date().toISOString();}
putGraph(orders,batches){this.db.exec('BEGIN IMMEDIATE');try{orders.forEach(order=>this.putOrder(order));batches.forEach(batch=>this.putBatch(batch));this.db.exec('COMMIT');}catch(error){this.db.exec('ROLLBACK');throw error;}}
putOrder(order){if(!order||typeof order.versionKey!=='string'||!order.versionKey)throw fail('订单版本键无效。',400);const value=structuredClone({...order,updatedAt:order.updatedAt||this.now()});this.db.prepare('INSERT INTO orders(version_key,order_no,status,payload,updated_at) VALUES(?,?,?,?,?) ON CONFLICT(version_key) DO UPDATE SET order_no=excluded.order_no,status=excluded.status,payload=excluded.payload,updated_at=excluded.updated_at').run(value.versionKey,String(value.orderNo||''),String(value.status||'unknown'),this.vault.encode('order:'+value.versionKey,value),value.updatedAt);return value;}
getOrder(versionKey){const row=this.db.prepare('SELECT version_key,payload FROM orders WHERE version_key=?').get(versionKey);return row?this.vault.decode('order:'+row.version_key,row.payload):null;}
orders(){return this.db.prepare('SELECT version_key,payload FROM orders ORDER BY updated_at DESC').all().map(row=>this.vault.decode('order:'+row.version_key,row.payload));}
putBatch(batch){if(!batch||typeof batch.id!=='string'||!batch.id)throw fail('批次标识无效。',400);const value=structuredClone({...batch,updatedAt:batch.updatedAt||this.now()});this.db.prepare('INSERT INTO batches(id,status,payload,updated_at) VALUES(?,?,?,?) ON CONFLICT(id) DO UPDATE SET status=excluded.status,payload=excluded.payload,updated_at=excluded.updated_at').run(value.id,String(value.status||'unknown'),this.vault.encode('batch:'+value.id,value),value.updatedAt);return value;}
getBatch(id){const row=this.db.prepare('SELECT id,payload FROM batches WHERE id=?').get(id);return row?this.vault.decode('batch:'+row.id,row.payload):null;}
batches(){return this.db.prepare('SELECT id,payload FROM batches ORDER BY updated_at DESC').all().map(row=>this.vault.decode('batch:'+row.id,row.payload));}
putRule(rule){if(!rule||typeof rule.id!=='string'||!rule.id)throw fail('分类规则标识无效。',400);const value=structuredClone(rule);this.db.prepare('INSERT INTO rules(id,payload,updated_at) VALUES(?,?,?) ON CONFLICT(id) DO UPDATE SET payload=excluded.payload,updated_at=excluded.updated_at').run(value.id,this.vault.encode('rule:'+value.id,value),this.now());return value;}
getRule(id){const row=this.db.prepare('SELECT id,payload FROM rules WHERE id=?').get(id);return row?this.vault.decode('rule:'+row.id,row.payload):null;}
rules(){return this.db.prepare('SELECT id,payload FROM rules ORDER BY updated_at DESC').all().map(row=>this.vault.decode('rule:'+row.id,row.payload));}
meta(key,fallback=null){const row=this.db.prepare('SELECT value FROM metadata WHERE key=?').get(key);return row?JSON.parse(row.value):fallback;}
setMeta(key,value){this.db.prepare('INSERT INTO metadata VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value').run(key,JSON.stringify(value));return value;}
putCandidate(value){this.db.prepare('INSERT INTO candidates VALUES(?,?,?) ON CONFLICT(id) DO UPDATE SET payload=excluded.payload,updated_at=excluded.updated_at').run(value.id,this.vault.encode('candidate:'+value.id,value),this.now());return value;}
candidates(){return this.db.prepare('SELECT id,payload FROM candidates ORDER BY updated_at DESC').all().map(row=>this.vault.decode('candidate:'+row.id,row.payload));}
close(){this.db.close();this.vault.destroy();}
}
module.exports={OrderWorkflowStore};
+115 -57
View File
@@ -1,6 +1,7 @@
'use strict';
const crypto=require('node:crypto');
const {renderOrderTemplate}=require('./order-template-bridge.cjs');
class OrderWorkflowError extends Error{
constructor(code,message){super(message);this.name='OrderWorkflowError';this.code=code;this.status=409;}
@@ -9,75 +10,132 @@ class OrderWorkflowError extends Error{
const clone=value=>structuredClone(value);
const hash=value=>crypto.createHash('sha256').update(String(value)).digest('hex');
const present=value=>value!==undefined&&value!==null&&(typeof value!=='string'||value.trim()!=='');
const text=value=>String(value??'').trim();
function readCandidate(fields,path){
const paths=Array.isArray(path)?path:[path];
if(!paths.length||paths.some(p=>typeof p!=='string'||!p.trim()))throw new OrderWorkflowError('MISSING_FIELD','字段映射路径不能为空。');
const values=paths.map(item=>({path:item,value:fields?.[item]})).filter(item=>present(item.value));
if(!values.length)throw new OrderWorkflowError('MISSING_FIELD','缺少字段:'+paths.join('、'));
function candidateValues(source,spec){
const paths=Array.isArray(spec)?spec:[spec];
if(!paths.length||paths.some(path=>typeof path!=='string'&&!(path&&typeof path==='object'&&typeof path.path==='string'))){throw new OrderWorkflowError('MISSING_FIELD','字段映射路径不能为空。');}
return paths.map(item=>{
const descriptor=typeof item==='string'?{source:'detail',path:item}:item;
const origin=descriptor.source||descriptor.from||'detail';
if(!['detail','arrival','list'].includes(origin)||!descriptor.path.trim())throw new OrderWorkflowError('MISSING_FIELD','字段来源或路径无效。');
const value=origin==='arrival'||origin==='list'?source.arrival?.[descriptor.path]:source.detail?.fields?.[descriptor.path];
if(present(value)&&!['string','number'].includes(typeof value))throw new OrderWorkflowError('AMBIGUOUS_FIELD','业务字段必须为单一文本或数值:'+descriptor.path);
return {path:`${origin}.${descriptor.path}`,value};
}).filter(item=>present(item.value));
}
function readCandidate(source,spec,label='字段'){
const values=candidateValues(source,spec);
if(!values.length){
const paths=(Array.isArray(spec)?spec:[spec]).map(item=>typeof item==='string'?item:item?.path||'').filter(Boolean);
throw new OrderWorkflowError('MISSING_FIELD','缺少字段'+(label?`(${label})`:'')+':'+paths.join('、'));
}
const distinct=new Map(values.map(item=>[JSON.stringify(item.value),item]));
if(distinct.size>1)throw new OrderWorkflowError('AMBIGUOUS_FIELD','字段存在多个不同候选值:'+paths.join('、'));
if(distinct.size>1)throw new OrderWorkflowError('AMBIGUOUS_FIELD','字段存在多个不同候选值:'+values.map(item=>item.path).join('、'));
return values[0];
}
function nodeNames(steps){return (Array.isArray(steps)?steps:[]).map(step=>text(step?.name||step?.nodeName||step?.activityName||step?.text)).filter(Boolean);}
function exactRule(arrival,detail,rule){
if(!rule||rule.enabled!==true)throw new OrderWorkflowError('RULE_BLOCKED','订单规则未启用。');
if(rule.processName!==arrival.processName||rule.processName!==detail.processName&&detail.processName!==undefined)throw new OrderWorkflowError('PROCESS_CONFLICT','流程名称与已确认规则不一致。');
if(rule.processVersion&&String(rule.processVersion)!==String(detail.processVersion))throw new OrderWorkflowError('FORM_VERSION_CONFLICT','表单版本与已确认规则不一致。');
if(rule.nodeName&&rule.nodeName!==detail.nodeName)throw new OrderWorkflowError('NODE_CONFLICT','当前节点与已确认规则不一致。');
if(rule.processName!==arrival.processName||(detail.processName!==undefined&&rule.processName!==detail.processName))throw new OrderWorkflowError('PROCESS_CONFLICT','流程名称与已确认规则不一致。');
const arrivalNode=text(arrival.activityName),detailNode=text(detail.nodeName);
if((arrivalNode&&arrivalNode!==rule.nodeName)||(detailNode&&detailNode!==rule.nodeName)||(arrivalNode&&detailNode&&arrivalNode!==detailNode))throw new OrderWorkflowError('NODE_CONFLICT','当前节点与已确认规则不一致。');
const observed=nodeNames(detail.processSteps);if(observed.length&&!observed.includes(rule.nodeName))throw new OrderWorkflowError('NODE_CONFLICT','流程步骤证据中没有当前节点。');
const current=nodeNames((detail.processSteps||[]).filter(step=>['处理中','running','active'].includes(step.status)));if(current.length&&(new Set(current).size!==1||current[0]!==rule.nodeName))throw new OrderWorkflowError('NODE_CONFLICT','流程步骤当前办理节点与列表不一致。');
}
function dateOnly(value){const date=new Date(value);if(Number.isNaN(+date))return text(value);return new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(date);}
class OrderWorkflow{
constructor({clock=()=>new Date(),schedule={times:['11:00','17:00'],timezone:'Asia/Shanghai'},store=null}={}){this.clock=clock;this.schedule=schedule;this.store=store;this.orders=new Map((store?.orders?.()||[]).map(order=>[order.versionKey,order]));this.batches=new Map((store?.batches?.()||[]).map(batch=>[batch.id,batch]));}
persistOrder(order){this.store?.putOrder?.(order);}
persistBatch(batch){this.store?.putBatch?.(batch);}
identify({arrival,detail,mapping,rule}){
if(!arrival?.source||!arrival.taskId)throw new OrderWorkflowError('SOURCE_ID_MISSING','缺少 BPM 来源和任务号。');
if(!detail||typeof detail.fields!=='object')throw new OrderWorkflowError('DETAIL_MISSING','缺少订单详情字段。');
exactRule(arrival,detail,rule);
const orderNo=readCandidate(detail.fields,mapping.orderNo),serialNo=readCandidate(detail.fields,mapping.serialNo);
const productCode=readCandidate(detail.fields,mapping.productCode),modelFull=readCandidate(detail.fields,mapping.modelFull);
const modelShort=readCandidate(detail.fields,mapping.modelShort),customer=readCandidate(detail.fields,mapping.customer);
const brief=readCandidate(detail.fields,mapping.brief);
const productLine=Object.hasOwn(mapping,'productLine')?readCandidate(detail.fields,mapping.productLine):rule.productLinePath?readCandidate(detail.fields,rule.productLinePath):null;
if(!detail.processInstanceId)throw new OrderWorkflowError('VERSION_MISSING','缺少流程实例或业务版本标识。');
const version=String(detail.businessVersion||detail.processInstanceId);
const versionKey=hash([arrival.source,arrival.taskId,detail.processInstanceId,version].join('\0'));
const order={
id:hash([arrival.source,orderNo.value].join('\0')),versionKey,orderNo: String(orderNo.value).trim(),version,
source:arrival.source,taskId:String(arrival.taskId),processName:arrival.processName,processVersion:String(detail.processVersion||''),
nodeName:detail.nodeName||arrival.activityName||'',serialNo:String(serialNo.value),productCode:String(productCode.value),
modelFull:String(modelFull.value),modelShort:String(modelShort.value),customer:String(customer.value),
productLine:productLine?String(productLine.value):null,brief:String(brief.value),subject:String(detail.subject||arrival.subject||''),
businessTime:detail.businessTime||null,sourceRevision:detail.sourceRevision||detail.processInstanceId,
sources:{orderNo,serialNo,productCode,modelFull,modelShort,customer,brief,...(productLine?{productLine}:{})},
ruleId:rule.id,status:'identified',createdAt:this.clock().toISOString(),updatedAt:this.clock().toISOString(),
};
const existing=this.orders.get(versionKey);if(existing)return {status:'duplicate',order:clone(existing)};
this.orders.set(versionKey,order);this.persistOrder(order);return {status:'matched',order:clone(order)};
constructor({clock=()=>new Date(),schedule={times:['11:00','17:00'],timezone:'Asia/Shanghai'},store=null}={}){
this.clock=clock;this.schedule=schedule;this.store=store;this.orders=new Map((store?.orders?.()||[]).map(order=>[order.versionKey,order]));this.batches=new Map((store?.batches?.()||[]).map(batch=>[batch.id,batch]));this.ruleMap=new Map((store?.rules?.()||[]).map(rule=>[rule.id,rule]));
}
get(versionKey){const order=this.orders.get(versionKey);return order?clone(order):null;}
listOrders(){return [...this.orders.values()].map(clone);}
update(versionKey,work){const order=this.orders.get(versionKey);if(!order)throw new OrderWorkflowError('ORDER_NOT_FOUND','订单版本不存在。');const result=work(order);order.updatedAt=this.clock().toISOString();this.persistOrder(order);return result||clone(order);}
transition(versionKey,from,to){return this.update(versionKey,order=>{if(order.status!==from)throw new OrderWorkflowError('INVALID_STATE',`订单状态 ${order.status} 不能转为 ${to}。`);order.status=to;});}
start(versionKey){return this.update(versionKey,order=>{if(!['identified','detail_error','pdf_error','archive_error'].includes(order.status))throw new OrderWorkflowError('INVALID_STATE','当前订单不能开始处理。');order.status='detail_capturing';});}
markDetailReady(versionKey,detailEvidence={}){return this.update(versionKey,order=>{if(order.status!=='detail_capturing')throw new OrderWorkflowError('INVALID_STATE','详情尚未处于采集状态。');order.detailEvidence=clone(detailEvidence);order.status='detail_ready';});}
markPdfSuccess(versionKey,pdf){return this.update(versionKey,order=>{if(order.status!=='detail_ready')throw new OrderWorkflowError('INVALID_STATE','详情未准备好,不能记录 PDF。');if(!pdf?.jobId)throw new OrderWorkflowError('PDF_EVIDENCE_MISSING','缺少 PDF 任务证据。');order.pdf=clone(pdf);order.status='pdf_success';});}
markPdfError(versionKey,message){return this.update(versionKey,order=>{if(!['detail_ready','pdf_pending','detail_capturing'].includes(order.status))throw new OrderWorkflowError('INVALID_STATE','当前状态不能记录 PDF 失败。');order.error=String(message);order.status='pdf_error';});}
markArchiveSuccess(versionKey,archive){return this.update(versionKey,order=>{if(order.status!=='pdf_success')throw new OrderWorkflowError('INVALID_STATE','PDF 未成功,不能记录归档。');if(!archive?.archiveId)throw new OrderWorkflowError('ARCHIVE_EVIDENCE_MISSING','缺少 SMB 归档回执。');order.archive=clone(archive);order.status='archived';});}
markArchiveError(versionKey,message){return this.update(versionKey,order=>{if(order.status!=='pdf_success')throw new OrderWorkflowError('INVALID_STATE','当前状态不能记录归档失败。');order.error=String(message);order.status='archive_error';});}
createNotification(versionKey,input){return this.update(versionKey,order=>{if(order.status!=='archived')throw new OrderWorkflowError('ARCHIVE_REQUIRED','归档未成功,不能创建通知事件。');for(const key of ['productLine','brief','subject','occurredAt'])if(!present(input?.[key]))throw new OrderWorkflowError('NOTIFICATION_FIELD_MISSING','通知字段未确认:'+key);order.notification={...clone(input),orderVersionKey:versionKey,createdAt:this.clock().toISOString(),status:'pending'};order.status='notification_pending';});}
freezeBatch(cutoff,{mode='product_line',groups={}}={}){
const candidates=[...this.orders.values()].filter(order=>order.status==='notification_pending'&&order.notification?.status==='pending');
const grouped=new Map();for(const order of candidates){const key=mode==='order'?order.versionKey:order.notification.productLine;const group=groups[order.notification.productLine];if(!group?.to?.length){order.notification.status='blocked';order.notification.error='产业/产品线没有已确认的收件组。';order.status='blocked';continue;}if(!grouped.has(key))grouped.set(key,{group,orders:[]});grouped.get(key).orders.push(order);}
const [key,selected]=grouped.entries().next().value||[];if(!selected)throw new OrderWorkflowError('EMPTY_BATCH','当前发送窗口没有待发通知。');
const batch={id:crypto.randomUUID(),status:'prepared',cutoff,mode,productLine:key,to:[...selected.group.to],cc:[...(selected.group.cc||[])],orderVersionKeys:selected.orders.map(order=>order.versionKey),subject:selected.orders.map(order=>order.notification.subject).join('、'),text:selected.orders.map(order=>order.notification.brief).join('\n\n'),attachments:[]};
this.batches.set(batch.id,batch);this.persistBatch(batch);for(const order of selected.orders){order.notification.status='reserved';order.notification.batchId=batch.id;order.status='batched';this.persistOrder(order);}return clone(batch);
persistOrder(order){this.store?.putOrder?.(order);}persistBatch(batch){this.store?.putBatch?.(batch);}
saveRule(rule){
if(!rule||typeof rule.id!=='string'||!rule.id||typeof rule.processName!=='string'||!rule.processName.trim()||typeof rule.nodeName!=='string'||!rule.nodeName.trim()||typeof rule.productLine!=='string'||!rule.productLine.trim()||typeof rule.templateId!=='string'||!rule.templateId.trim()||!rule.adapters||typeof rule.adapters!=='object'||Array.isArray(rule.adapters))throw new OrderWorkflowError('RULE_INVALID','分类规则缺少流程、节点、产品线、模板或版本适配器。');
for(const [version,mapping] of Object.entries(rule.adapters))if(!version.trim()||!mapping||typeof mapping!=='object'||Array.isArray(mapping))throw new OrderWorkflowError('RULE_INVALID','字段适配器版本无效。');
const old=this.ruleMap.get(rule.id);if(old&&rule.version!==old.version)throw new OrderWorkflowError('RULE_VERSION_CONFLICT','分类规则已被修改,请刷新后保存。');
const value={batchMode:'category_template',notificationType:'order',pdfTemplateId:'bpm-snapshot-v1',...clone(rule),version:(old?.version||0)+1,status:'draft',check:null,enabled:rule.enabled!==false,processName:rule.processName.trim(),nodeName:rule.nodeName.trim(),productLine:rule.productLine.trim(),templateId:rule.templateId.trim()};
if(!['category_template','product_line','order'].includes(value.batchMode))throw new OrderWorkflowError('RULE_INVALID','批次模式无效。');
this.store?.putRule?.(value);this.ruleMap.set(value.id,value);return clone(value);
}
getBatch(id){const batch=this.batches.get(id);return batch?clone(batch):null;}
listBatches(){return [...this.batches.values()].map(clone);}
markBatchUnknown(id,message){const batch=this.batches.get(id);if(!batch)throw new OrderWorkflowError('BATCH_NOT_FOUND','批次不存在。');batch.status='unknown';batch.error=String(message);this.persistBatch(batch);return clone(batch);}
checkRule(id,{arrival,detail,provenance}){
const rule=this.getRule(id);if(!rule)throw new OrderWorkflowError('RULE_NOT_FOUND','分类规则不存在。');if(provenance!=='bpm-readonly'||detail?.readOnly===false)throw new OrderWorkflowError('DETAIL_PROVENANCE','只能使用服务器只读采集的 BPM 样本。');
rule.check=null;this.store?.putRule?.(rule);this.ruleMap.set(id,rule);
try{const preview=new OrderWorkflow({clock:this.clock});preview.identify({arrival,detail,rule:{...rule,enabled:true},mapping:rule.adapters[String(detail.processVersion)]});}
catch(error){return {valid:false,issues:[{code:error.code||'SAMPLE_INVALID',message:error.message}],sample:{processName:arrival.processName,nodeName:detail.nodeName,processVersion:detail.processVersion,fields:clone(detail.fields),tid:detail.tid,pid:detail.pid}};}
const check={checkId:crypto.randomUUID(),version:rule.version,checkedAt:this.clock().toISOString(),evidenceHash:hash(JSON.stringify({arrival,detail}))};rule.check=check;this.store?.putRule?.(rule);this.ruleMap.set(id,rule);return {valid:true,issues:[],...check,sample:{processName:arrival.processName,nodeName:detail.nodeName,processVersion:detail.processVersion,fields:clone(detail.fields),tid:detail.tid,pid:detail.pid}};
}
publishRule(id,{version,checkId}){
const rule=this.getRule(id);if(!rule||rule.version!==version||rule.check?.version!==version||!checkId||rule.check?.checkId!==checkId)throw new OrderWorkflowError('RULE_CHECK_REQUIRED','必须对当前版本执行真实只读样本检查后发布。');
if(rule.enabled&&[...this.ruleMap.values()].some(old=>old.id!==id&&old.status==='published'&&old.enabled&&old.processName===rule.processName&&old.nodeName===rule.nodeName))throw new OrderWorkflowError('RULE_CONFLICT','同一流程和节点已有发布规则。');
rule.status='published';rule.publishedAt=this.clock().toISOString();this.store?.putRule?.(rule);this.ruleMap.set(id,rule);return clone(rule);
}
invalidateCheck(id){const rule=this.getRule(id);if(!rule)throw new OrderWorkflowError('RULE_NOT_FOUND','分类规则不存在。');rule.check=null;this.store?.putRule?.(rule);this.ruleMap.set(id,rule);}
getRule(id){const rule=this.ruleMap.get(id);return rule?clone(rule):null;}rules(){return [...this.ruleMap.values()].map(clone);}
resolveRule(arrival,detail){
const node=text(arrival?.activityName||detail?.nodeName);if(arrival?.activityName&&detail?.nodeName&&arrival.activityName!==detail.nodeName)throw new OrderWorkflowError('NODE_CONFLICT','列表当前节点与详情节点不一致。');
const candidates=[...this.ruleMap.values()].filter(rule=>rule.enabled===true&&rule.status==='published'&&rule.processName===arrival?.processName&&rule.nodeName===node);if(candidates.length!==1)throw new OrderWorkflowError(candidates.length?'RULE_CONFLICT':'RULE_UNMATCHED',candidates.length?'流程和节点命中多个分类规则。':'流程和节点没有命中已发布分类规则。');
const rule=candidates[0],mapping=rule.adapters?.[String(detail?.processVersion||'')];if(!mapping)throw new OrderWorkflowError('ADAPTER_MISSING','当前表单版本没有字段适配器:'+String(detail?.processVersion||''));return {rule,mapping};
}
identify(input){
let {arrival,detail,mapping,rule}=input||{};if(!arrival?.source||!present(arrival.taskId))throw new OrderWorkflowError('SOURCE_ID_MISSING','缺少 BPM 来源和任务号。');if(!detail||typeof detail.fields!=='object'||Array.isArray(detail.fields))throw new OrderWorkflowError('DETAIL_MISSING','缺少订单详情字段。');
if(!rule){const resolved=this.resolveRule(arrival,detail);rule=resolved.rule;mapping=resolved.mapping;}else if(!mapping&&rule.adapters?.[String(detail.processVersion||'')])mapping=rule.adapters[String(detail.processVersion)];if(!mapping)throw new OrderWorkflowError('ADAPTER_MISSING','当前表单版本没有字段适配器。');exactRule(arrival,detail,rule);
const mappedVersion=mapping.businessVersion?readCandidate({arrival,detail},mapping.businessVersion,'业务版本'):null;
const businessVersion=mappedVersion?.value??detail.businessVersion;
if(!present(detail.tid)||!present(detail.pid)||!present(businessVersion)||![detail.tid,detail.pid,businessVersion].every(value=>['string','number'].includes(typeof value)))throw new OrderWorkflowError('VERSION_MISSING','缺少 tid、pid 或明确的业务版本标识。');if(!present(detail.processVersion))throw new OrderWorkflowError('FORM_VERSION_MISSING','缺少表单版本。');
const source={arrival,detail},orderNo=readCandidate(source,mapping.orderNo,'订单号'),serialNo=readCandidate(source,mapping.serialNo,'流水号'),productCode=readCandidate(source,mapping.productCode,'产品编号'),modelFull=readCandidate(source,mapping.modelFull,'完整型号'),modelShort=readCandidate(source,mapping.modelShort,'短型号'),customer=readCandidate(source,mapping.customer,'客户'),brief=readCandidate(source,mapping.brief,'简要说明');
if(!present(rule.productLine))throw new OrderWorkflowError('RULE_INVALID','分类规则必须指定产品线。');
const productLine={path:'rule.productLine',value:rule.productLine},version=String(businessVersion),currentOrderNo=text(orderNo.value),tid=String(detail.tid),pid=String(detail.pid),versionKey=hash(JSON.stringify([tid,pid,currentOrderNo,version]));
const businessTime=detail.businessTime||arrival.arrivedAt||arrival.receivedAt||null,businessTimeSource=detail.businessTime?'detail.businessTime':businessTime?'list.receivedAt':null;if(!businessTime)throw new OrderWorkflowError('BUSINESS_TIME_MISSING','缺少业务时间和列表收到时间。');const now=this.clock().toISOString();
const order={id:hash([arrival.source,currentOrderNo].join('\0')),versionKey,version,businessVersion:version,tid,pid,orderNo:currentOrderNo,source:arrival.source,taskId:String(arrival.taskId),processName:arrival.processName,processVersion:String(detail.processVersion),nodeName:detail.nodeName||arrival.activityName||'',serialNo:text(serialNo.value),productCode:text(productCode.value),modelFull:text(modelFull.value),modelShort:text(modelShort.value),customer:text(customer.value),productLine:productLine.value,brief:String(brief.value),subject:String(detail.subject||arrival.subject||''),businessTime,businessTimeSource,sourceRevision:detail.sourceRevision||version,sources:{orderNo,serialNo,productCode,modelFull,modelShort,customer,brief,productLine},ruleId:rule.id,templateId:rule.templateId||null,status:'identified',steps:{discovery:{status:'success',source:'bpm-readonly'},detail:{status:'pending'},pdf:{status:'pending'},archive:{status:'pending'},notification:{status:'pending'}},createdAt:now,updatedAt:now};
order.ruleSnapshot=clone(rule);order.detailSnapshot=clone(detail);order.arrival=clone(arrival);order.sources.businessVersion=mappedVersion||{path:'detail.businessVersion',value:version};
const existing=this.orders.get(versionKey);if(existing){if(existing.ruleId!==order.ruleId||existing.brief!==order.brief||JSON.stringify(existing.sources)!==JSON.stringify(order.sources)||JSON.stringify(existing.detailSnapshot?.fields)!==JSON.stringify(detail.fields))throw new OrderWorkflowError('VERSION_CONTENT_CONFLICT','同一订单版本的分类或字段证据已变化,请人工确认业务版本。');return {status:'duplicate',order:clone(existing)};}this.persistOrder(order);this.orders.set(versionKey,order);return {status:'matched',order:clone(order)};
}
get(versionKey){const order=this.orders.get(versionKey);return order?clone(order):null;}listOrders(){return [...this.orders.values()].map(clone);}
update(versionKey,work){const saved=this.orders.get(versionKey);if(!saved)throw new OrderWorkflowError('ORDER_NOT_FOUND','订单版本不存在。');const order=clone(saved);order.steps||={};work(order);order.updatedAt=this.clock().toISOString();this.persistOrder(order);this.orders.set(versionKey,order);return clone(order);}
start(versionKey){return this.update(versionKey,order=>{if(!['identified','detail_error','pdf_error','archive_error','interrupted'].includes(order.status))throw new OrderWorkflowError('INVALID_STATE','当前订单不能开始处理。');if(order.steps.pdf?.status==='success'){order.status='pdf_success';return;}if(order.steps.detail?.status==='success'){order.status='detail_ready';return;}order.status='detail_capturing';order.steps.detail={status:'running',startedAt:this.clock().toISOString()};});}
markDetailReady(versionKey,detailEvidence={}){return this.update(versionKey,order=>{if(!['detail_capturing','detail_error'].includes(order.status))throw new OrderWorkflowError('INVALID_STATE','详情尚未处于采集状态。');order.detailEvidence=clone(detailEvidence);order.steps.detail={status:'success',...clone(detailEvidence)};order.status='detail_ready';});}
beginPdf(versionKey){return this.update(versionKey,order=>{if(!['detail_ready','pdf_error'].includes(order.status))throw new OrderWorkflowError('INVALID_STATE','当前状态不能生成 PDF。');order.status='pdf_pending';order.steps.pdf={status:'running',startedAt:this.clock().toISOString()};});}
beginArchive(versionKey){return this.update(versionKey,order=>{if(order.steps.pdf?.status!=='success'||!['pdf_success','archive_error'].includes(order.status))throw new OrderWorkflowError('INVALID_STATE','当前状态不能归档。');order.status='archive_pending';order.steps.archive={status:'running',startedAt:this.clock().toISOString()};});}
markPdfSuccess(versionKey,pdf){return this.update(versionKey,order=>{if(!['detail_ready','pdf_error','pdf_pending'].includes(order.status))throw new OrderWorkflowError('INVALID_STATE','详情未准备好,不能记录 PDF。');if(!pdf?.jobId)throw new OrderWorkflowError('PDF_EVIDENCE_MISSING','缺少 PDF 任务证据。');order.pdf=clone(pdf);order.steps.pdf={status:'success',...clone(pdf)};order.status='pdf_success';});}
markPdfError(versionKey,message){return this.update(versionKey,order=>{if(!['detail_ready','pdf_pending','detail_capturing'].includes(order.status))throw new OrderWorkflowError('INVALID_STATE','当前状态不能记录 PDF 失败。');order.error=String(message);order.steps.pdf={status:'error',error:String(message)};order.status='pdf_error';});}
markArchiveSuccess(versionKey,archive){return this.update(versionKey,order=>{if(!['pdf_success','archive_error','archive_pending'].includes(order.status))throw new OrderWorkflowError('INVALID_STATE','PDF 未成功,不能记录归档。');if(!archive?.archiveId)throw new OrderWorkflowError('ARCHIVE_EVIDENCE_MISSING','缺少 SMB 归档回执。');order.archive=clone(archive);order.steps.archive={status:'success',...clone(archive)};order.status='archived';});}
markArchiveError(versionKey,message){return this.update(versionKey,order=>{if(!['pdf_success','archive_pending'].includes(order.status))throw new OrderWorkflowError('INVALID_STATE','当前状态不能记录归档失败。');order.error=String(message);order.steps.archive={status:'error',error:String(message)};order.status='archive_error';});}
createNotification(versionKey,input){return this.update(versionKey,order=>{if(order.status!=='archived')throw new OrderWorkflowError('ARCHIVE_REQUIRED','归档未成功,不能创建通知事件。');const data=input||{productLine:order.productLine,templateId:order.templateId,brief:order.brief,subject:order.subject,occurredAt:order.businessTime};data.templateId||=order.templateId;for(const key of ['productLine','templateId','brief','subject','occurredAt'])if(!present(data[key]))throw new OrderWorkflowError('NOTIFICATION_FIELD_MISSING','通知字段未确认:'+key);order.notification={...clone(data),orderVersionKey:versionKey,createdAt:this.clock().toISOString(),status:'pending'};order.steps.notification={status:'pending'};order.status='notification_pending';});}
freezeBatches(cutoff,{mode='product_line',groups={},templates={}}={}){
if(!Number.isFinite(Date.parse(cutoff)))throw new OrderWorkflowError('WINDOW_INVALID','发送窗口无效。');
const candidates=[...this.orders.values()].filter(order=>['notification_pending','blocked'].includes(order.status)&&['pending','blocked'].includes(order.notification?.status)&&Date.parse(order.notification.occurredAt)<=Date.parse(cutoff)).map(clone),grouped=new Map();
const block=(order,message)=>{order.notification.status='blocked';order.notification.error=message;order.steps.notification={status:'blocked',error:message};order.status='blocked';};
for(const order of candidates){
const notification=order.notification,productLine=order.productLine,templateId=order.templateId,rule=order.ruleSnapshot||{};
const group=groups[rule.recipientGroupId||productLine];
if(!Array.isArray(group?.to)||!group.to.length){block(order,'分类规则没有已确认的收件组。');continue;}
const template=templates[templateId];if(!template){block(order,'分类规则绑定的邮件模板未加载。');continue;}
const key=JSON.stringify([order.ruleId,rule.version,productLine,templateId,rule.batchMode==='order'||mode==='order'?order.versionKey:'',group.to,group.cc||[]]);
if(!grouped.has(key))grouped.set(key,{ruleId:order.ruleId,productLine,templateId,group,template,orders:[]});grouped.get(key).orders.push(order);
}
const batches=[];
for(const selected of grouped.values()){
const orders=selected.orders,date=[...new Set(orders.map(order=>dateOnly(order.businessTime)))].join('、');let rendered;
try{rendered=renderOrderTemplate(selected.template,{productLine:selected.productLine,orders,date});}catch(error){orders.forEach(order=>block(order,error.message));continue;}
const batch={id:crypto.randomUUID(),status:'prepared',cutoff,mode,ruleId:selected.ruleId,productLine:selected.productLine,templateId:selected.templateId,templateVersion:rendered.templateVersion,templateSnapshot:{id:selected.template.id,version:selected.template.version,subject:selected.template.subject,text:selected.template.text,html:selected.template.html},to:[...selected.group.to],cc:[...(selected.group.cc||[])],orderVersionKeys:orders.map(order=>order.versionKey),subject:rendered.subject,text:rendered.text,html:rendered.html,attachments:[],attempts:0,createdAt:this.clock().toISOString()};
for(const order of orders){order.notification.status='reserved';order.notification.batchId=batch.id;delete order.notification.error;order.steps.notification={status:'batched',batchId:batch.id};order.status='batched';}batches.push(batch);
}
this.saveGraph(candidates,batches);
if(!batches.length)throw new OrderWorkflowError('EMPTY_BATCH','当前发送窗口没有待发通知。');return batches.map(clone);
}
saveGraph(orders,batches){if(this.store?.putGraph)this.store.putGraph(orders,batches);else {orders.forEach(order=>this.persistOrder(order));batches.forEach(batch=>this.persistBatch(batch));}orders.forEach(order=>this.orders.set(order.versionKey,order));batches.forEach(batch=>this.batches.set(batch.id,batch));}
freezeBatch(cutoff,options={}){return this.freezeBatches(cutoff,options)[0];}
getBatch(id){const batch=this.batches.get(id);return batch?clone(batch):null;}listBatches(){return [...this.batches.values()].map(clone);}
markBatchSending(id){return this.updateBatch(id,'sending');}markBatchSent(id){return this.updateBatch(id,'sent');}markBatchFailed(id,message){return this.updateBatch(id,'failed',message);}
updateBatch(id,status,error=null){const saved=this.batches.get(id);if(!saved)throw new OrderWorkflowError('BATCH_NOT_FOUND','批次不存在。');const allowed={prepared:['sending','failed'],sending:['sent','unknown'],failed:['sending','failed'],unknown:[]};if(!allowed[saved.status]?.includes(status))throw new OrderWorkflowError('INVALID_BATCH_STATE','当前批次不能执行此操作。');const batch={...clone(saved),status,error,updatedAt:this.clock().toISOString()};if(status==='sending'||status==='failed')batch.attempts=(batch.attempts||0)+1;const orders=batch.orderVersionKeys.map(key=>this.get(key)).filter(Boolean);for(const order of orders){order.status=status==='failed'?'batched':status;order.notification.status=status;order.steps.notification={status,batchId:id,...(error?{error}:{})};}this.saveGraph(orders,[batch]);return clone(batch);}
markBatchUnknown(id,message){return this.updateBatch(id,'unknown',String(message));}
resolveBatch(id,{resolution,note},actor){const saved=this.getBatch(id);if(!saved||!['unknown','failed'].includes(saved.status))throw new OrderWorkflowError('RESOLUTION_INVALID','只能核验结果不明或明确失败的批次。');if(!['sent','retry'].includes(resolution)||typeof note!=='string'||note.trim().length<5)throw new OrderWorkflowError('RESOLUTION_INVALID','请填写至少 5 字的核验依据。');const batch={...saved,status:resolution==='sent'?'sent':'prepared',resolution,verification:{actor,note:note.trim(),at:this.clock().toISOString()}};if(resolution==='retry')batch.attempts=0;const orders=batch.orderVersionKeys.map(key=>this.get(key)).filter(Boolean);for(const order of orders){order.status=resolution==='sent'?'sent':'batched';order.notification.status=resolution==='sent'?'sent':'reserved';order.steps.notification={status:order.status,batchId:id};}this.saveGraph(orders,[batch]);return clone(batch);}
canAutoRetry(id){const batch=this.batches.get(id);return !!batch&&batch.status==='failed';}
}
module.exports={OrderWorkflow,OrderWorkflowError};
module.exports={OrderWorkflow,OrderWorkflowError,readCandidate};
+8 -4
View File
@@ -23,6 +23,7 @@ const { StorageService } = require('./storage-service.cjs');
const { NotificationStore, NotificationService } = require('./notifications.cjs');
const { OrderWorkflowStore } = require('./order-workflow-store.cjs');
const { OrderWorkflow } = require('./order-workflow.cjs');
const { OrderPipeline } = require('./order-pipeline.cjs');
function createServer(options) {
let busy = false;
@@ -118,7 +119,7 @@ async function main(options = {}) {
const custodian=new BpmCustodian({workspace,manager:bpmSessions});
let server;
let dashboard;
let mailStore,mail,scanStore,scanner,storageStore,storage,notificationStore,notifications,workflowStore,workflow,assistantStore,assistant,health;
let mailStore,mail,scanStore,scanner,storageStore,storage,notificationStore,notifications,workflowStore,workflow,pipeline,assistantStore,assistant,health;
try {
mailStore=new MailStore(path.join(stateDir,'mail'));mail=new MailService({store:mailStore});
mailStore.migrateLegacy(store.settings().templates);
@@ -126,16 +127,18 @@ async function main(options = {}) {
storageStore=new StorageStore(path.join(stateDir,'storage'));storage=new StorageService({store:storageStore,jobs:store,outputDir});
notificationStore=new NotificationStore(path.join(stateDir,'notifications'));notifications=new NotificationService({store:notificationStore,mail,settings:()=>store.settings(),calendar:()=>workspace.meta('calendar').overrides});
workflowStore=new OrderWorkflowStore(path.join(stateDir,'order-workflow'));workflow=new OrderWorkflow({store:workflowStore,schedule:store.settings().schedule});
pipeline=new OrderPipeline({workflow,store:workflowStore,scanStore,workspace,manager:bpmSessions,jobs:store,storage,mail,notifications,settings:()=>store.settings(),calendar:()=>workspace.meta('calendar').overrides,outputDir});
assistantStore=new AssistantStore(path.join(stateDir,'assistant'));assistantStore.recover();assistant=new AssistantService({store:assistantStore,runtime:new ZcodeRuntime({stateDir:path.join(stateDir,'assistant','runtime')}),dashboard:store,workspace,scanner,storage});
health=new RuntimeHealth({stateDir,startedAt,instanceId:watchdog.instanceId,workspace,scanner,storage,mail});
await bpmSessions.migrateAccounts(workspace.snapshot().connections);
workspace.markSessionChecksPending();
server=await startService({token,port,outputDir,scale:config.scale,installedExtension,extensionSourceDir:path.join(root,'extension'),store,storage,watchdog});
dashboard=createDashboard({store,workspace,outputDir,bpmSessions,mail,scanner,storage,notifications,workflow,assistant,health,watchdog,trustedProxy:dashboardConfig.trustedProxy===true});
dashboard=createDashboard({store,workspace,outputDir,bpmSessions,mail,scanner,storage,notifications,workflow,pipeline,assistant,health,watchdog,trustedProxy:dashboardConfig.trustedProxy===true});
await new Promise((resolve,reject)=>{dashboard.once('error',reject);dashboard.listen(dashboardPort,dashboardHost,resolve);});store.recoverJobs();mailStore.recoverSends();custodian.start();mail.start();scanner.start();notifications.start();
health.start();
pipeline.start();
}
catch(error){health?.close();if(server?.listening)await new Promise(resolve=>server.close(resolve));if(dashboard?.listening)await new Promise(resolve=>dashboard.close(resolve));await assistant?.stop();assistantStore?.close();await notifications?.stop();notificationStore?.close();workflowStore?.close();await storage?.stop();storageStore?.close();await scanner?.stop();scanStore?.close();await mail?.stop();mailStore?.close();await bpmSessions.shutdown();workspace.close();throw error;}
catch(error){health?.close();if(server?.listening)await new Promise(resolve=>server.close(resolve));if(dashboard?.listening)await new Promise(resolve=>dashboard.close(resolve));await pipeline?.stop();await assistant?.stop();assistantStore?.close();await notifications?.stop();notificationStore?.close();workflowStore?.close();await storage?.stop();storageStore?.close();await scanner?.stop();scanStore?.close();await mail?.stop();mailStore?.close();await bpmSessions.shutdown();workspace.close();throw error;}
if(!options.quiet){
console.log('订单通知中心已启动。\nWeb 工作台支持业务日历、异常待办与转交、BPM 连接管理。\n在 Chrome 订单页仍可点击扩展中的“导出当前订单”。');
console.log(`首次使用:Chrome 扩展管理 → 开发者模式 → 加载已解压的扩展程序\n选择目录:${installedExtension}\n输出目录:${outputDir}\n本地服务:http://127.0.0.1:${port}`);
@@ -145,6 +148,7 @@ async function main(options = {}) {
let stopping;
const stop=()=>stopping ||= (async()=>{
health.close();
await pipeline.stop();
await assistant.stop();await notifications.stop();await storage.stop();await scanner.stop();await mail.stop();await custodian.stop();await bpmSessions.shutdown();
await Promise.all([dashboard,server].map(socket=>new Promise((resolve,reject)=>socket.close(error=>error?reject(error):resolve()))));
workspace.close();
@@ -155,7 +159,7 @@ async function main(options = {}) {
workflowStore.close();
assistantStore.close();
})();
return {server,dashboard,workspace,bpmSessions,custodian,mail,scanner,storage,notifications,workflow,assistant,health,stop};
return {server,dashboard,workspace,bpmSessions,custodian,mail,scanner,storage,notifications,workflow,pipeline,assistant,health,stop};
}
if (require.main === module) main().then(app=>{
const stop=()=>app.stop().then(()=>process.exit(0),()=>process.exit(1));
+57
View File
@@ -0,0 +1,57 @@
using System;
using System.Text;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
// WScript.Shell's shortcut wrapper truncates non-ANSI paths on some Windows
// installations. IShellLinkW and IPersistFile retain UTF-16 paths end to end.
[ComImport, Guid("00021401-0000-0000-C000-000000000046")]
internal class OrderShellLink { }
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("000214F9-0000-0000-C000-000000000046")]
internal interface IOrderShellLinkW {
void GetPath([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder path, int length, IntPtr findData, uint flags);
void GetIDList(out IntPtr list);
void SetIDList(IntPtr list);
void GetDescription([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder description, int length);
void SetDescription([MarshalAs(UnmanagedType.LPWStr)] string description);
void GetWorkingDirectory([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder directory, int length);
void SetWorkingDirectory([MarshalAs(UnmanagedType.LPWStr)] string directory);
void GetArguments([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder arguments, int length);
void SetArguments([MarshalAs(UnmanagedType.LPWStr)] string arguments);
void GetHotkey(out short hotkey);
void SetHotkey(short hotkey);
void GetShowCmd(out int command);
void SetShowCmd(int command);
void GetIconLocation([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder path, int length, out int index);
void SetIconLocation([MarshalAs(UnmanagedType.LPWStr)] string path, int index);
void SetRelativePath([MarshalAs(UnmanagedType.LPWStr)] string path, uint reserved);
void Resolve(IntPtr window, uint flags);
void SetPath([MarshalAs(UnmanagedType.LPWStr)] string path);
}
public static class OrderShortcut {
public static void Save(string file, string target, string arguments, string directory) {
object instance = new OrderShellLink();
try {
var link = (IOrderShellLinkW)instance;
link.SetPath(target);
link.SetArguments(arguments);
link.SetWorkingDirectory(directory);
link.SetDescription("Order workspace service supervisor");
((IPersistFile)instance).Save(file, true);
} finally { Marshal.FinalReleaseComObject(instance); }
}
public static string[] Read(string file) {
object instance = new OrderShellLink();
try {
((IPersistFile)instance).Load(file, 0);
var link = (IOrderShellLinkW)instance;
var target = new StringBuilder(32768);
var arguments = new StringBuilder(32768);
link.GetPath(target, target.Capacity, IntPtr.Zero, 4);
link.GetArguments(arguments, arguments.Capacity);
return new string[] { target.ToString(), arguments.ToString() };
} finally { Marshal.FinalReleaseComObject(instance); }
}
}
+7 -3
View File
@@ -1,15 +1,19 @@
'use strict';
const fs=require('node:fs'),path=require('node:path'),{execFileSync}=require('node:child_process'),{SupervisorStore}=require('./supervisor-store.cjs');
function powershell(script,data){return execFileSync('powershell.exe',['-NoLogo','-NoProfile','-NonInteractive','-Command','$ErrorActionPreference="Stop"; [Console]::InputEncoding=New-Object System.Text.UTF8Encoding; [Console]::OutputEncoding=New-Object System.Text.UTF8Encoding; '+script],{input:JSON.stringify(data),encoding:'utf8',windowsHide:true,timeout:15000,stdio:['pipe','pipe','pipe']}).trim();}
function powershell(script,data){
const source=fs.readFileSync(path.join(__dirname,'windows-shortcut.cs'),'utf8');
const prefix="$ErrorActionPreference=\"Stop\"; [Console]::InputEncoding=New-Object System.Text.UTF8Encoding; [Console]::OutputEncoding=New-Object System.Text.UTF8Encoding; Add-Type -TypeDefinition @'\n"+source+"\n'@\n";
return execFileSync('powershell.exe',['-NoLogo','-NoProfile','-NonInteractive','-Command',prefix+script],{input:JSON.stringify(data),encoding:'utf8',windowsHide:true,timeout:15000,stdio:['pipe','pipe','pipe']}).trim();
}
function locations({stateDir,startupDir}){
if(process.platform!=='win32')throw Error('登录自启动仅支持 Windows。');
const root=path.resolve(startupDir||path.join(process.env.APPDATA,'Microsoft','Windows','Start Menu','Programs','Startup'));
return {linkPath:path.join(root,'OrderNotificationAutomation.lnk'),launcherPath:path.join(path.resolve(stateDir),'supervisor','logon-launch.vbs'),wscript:path.join(process.env.SystemRoot,'System32','wscript.exe')};
}
function readShortcut(file){const raw=powershell('$d=[Console]::In.ReadToEnd()|ConvertFrom-Json; $s=(New-Object -ComObject WScript.Shell).CreateShortcut($d.file); @{target=$s.TargetPath;args=$s.Arguments}|ConvertTo-Json -Compress',{file});return JSON.parse(raw);}
function readShortcut(file){const raw=powershell('$d=[Console]::In.ReadToEnd()|ConvertFrom-Json; $s=[OrderShortcut]::Read($d.file); @{target=$s[0];args=$s[1]}|ConvertTo-Json -Compress',{file});return JSON.parse(raw);}
function ownedShortcut(paths){if(!fs.existsSync(paths.linkPath))return true;const old=readShortcut(paths.linkPath);return path.resolve(old.target).toLowerCase()===path.resolve(paths.wscript).toLowerCase()&&old.args==='//B "'+paths.launcherPath+'"';}
function removeFile(file){try{fs.unlinkSync(file);}catch(e){if(e.code!=='ENOENT')throw e;}if(fs.existsSync(file))throw Error('无法确认自启动文件已移除。');}
function writeShortcut({paths,projectRoot}){powershell('$d=[Console]::In.ReadToEnd()|ConvertFrom-Json; $s=(New-Object -ComObject WScript.Shell).CreateShortcut($d.link); $s.TargetPath=$d.target; $s.Arguments=$d.args; $s.WorkingDirectory=$d.cwd; $s.Description="Order workspace service supervisor"; $s.Save()',{link:paths.linkPath,target:paths.wscript,args:'//B "'+paths.launcherPath+'"',cwd:path.resolve(projectRoot)});}
function writeShortcut({paths,projectRoot}){powershell('$d=[Console]::In.ReadToEnd()|ConvertFrom-Json; [OrderShortcut]::Save($d.link,$d.target,$d.args,$d.cwd)',{link:paths.linkPath,target:paths.wscript,args:'//B "'+paths.launcherPath+'"',cwd:path.resolve(projectRoot)});}
function installAutostart({stateDir,projectRoot=path.resolve(__dirname,'..'),nodePath=process.execPath,startupDir,shortcutWriter=writeShortcut}={}){
const paths=locations({stateDir,startupDir}),store=new SupervisorStore(stateDir);
try{